diff --git a/.github/workflows/plugins-package.yml b/.github/workflows/plugins-package.yml index 5afae0a0a..b1454ec4d 100644 --- a/.github/workflows/plugins-package.yml +++ b/.github/workflows/plugins-package.yml @@ -26,7 +26,7 @@ jobs: - name: Install the plugin build CLI independently of Core run: | uv venv "$RUNNER_TEMP/plugin-build" - uv pip install --python "$RUNNER_TEMP/plugin-build/bin/python" 'langbot-plugin==0.7.19' pyyaml + uv pip install --python "$RUNNER_TEMP/plugin-build/bin/python" 'langbot-plugin==0.7.20' pyyaml echo "$RUNNER_TEMP/plugin-build/bin" >> "$GITHUB_PATH" - name: Build selected plugin without publishing env: diff --git a/.github/workflows/plugins-runner-tests.yml b/.github/workflows/plugins-runner-tests.yml index fb1042934..3554603f9 100644 --- a/.github/workflows/plugins-runner-tests.yml +++ b/.github/workflows/plugins-runner-tests.yml @@ -40,17 +40,17 @@ jobs: - name: Install dependencies run: uv sync --locked --dev - - name: Verify published SDK pin - run: uv run --no-sync python -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.4"; print("langbot-plugin", version("langbot-plugin"))' + - name: Verify SDK snapshot + run: uv run --no-sync python -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.20"; print("langbot-plugin", version("langbot-plugin"))' - name: Prepare isolated certified coding Runner SDK environment run: | - uv venv "$RUNNER_TEMP/coding-074" - # PyPI's aggregate index can lag the exact 0.7.4 release endpoint. - uv pip install --python "$RUNNER_TEMP/coding-074/bin/python" \ - 'https://files.pythonhosted.org/packages/f2/c7/c870377771cbe27e047b19778b5f249b15efef52409358901af94d13e6c0/langbot_plugin-0.7.4-py3-none-any.whl#sha256=596ecd776c13efa6f6cfe178463dc4a967653238548c9569195cdbb5aa47506e' \ + uv venv "$RUNNER_TEMP/coding-sdk" + # Coding Runners call ctx.request_interaction, first released in SDK 0.7.20. + uv pip install --python "$RUNNER_TEMP/coding-sdk/bin/python" \ + 'langbot-plugin==0.7.20' \ -r acp-agent-runner/requirements.txt -r claude-code-agent/requirements.txt -r codex-agent/requirements.txt pytest pyyaml packaging - "$RUNNER_TEMP/coding-074/bin/python" -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.4"' - printf 'CODING_RUNNER_TEST_PYTHON=%s/coding-074/bin/python\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + "$RUNNER_TEMP/coding-sdk/bin/python" -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.20"' + printf 'CODING_RUNNER_TEST_PYTHON=%s/coding-sdk/bin/python\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" - name: Prepare isolated LocalAgent environment with the latest stable SDK run: | UV_PROJECT_ENVIRONMENT="$RUNNER_TEMP/localagent-latest" uv sync --project LocalAgent --extra dev --upgrade-package langbot-plugin @@ -73,9 +73,9 @@ jobs: run: uv run --no-sync python -m pytest http-certification-tests -q --junitxml="${RUNNER_EVIDENCE_DIR}/http-certification.xml" - name: Certified RunnerDemo SDK admission and package tests run: | - "$RUNNER_TEMP/coding-074/bin/python" certification-tests/test_runner_demo_dependency_admission.py -v + "$RUNNER_TEMP/coding-sdk/bin/python" certification-tests/test_runner_demo_dependency_admission.py -v cd RunnerDemo - "$RUNNER_TEMP/coding-074/bin/python" -m unittest discover -s tests -v + "$RUNNER_TEMP/coding-sdk/bin/python" -m unittest discover -s tests -v - name: Upload test evidence if: always() uses: actions/upload-artifact@v4 diff --git a/dev-docs/agent-runner-pluginization/INTERACTION_CALLBACK_LIFECYCLE.md b/dev-docs/agent-runner-pluginization/INTERACTION_CALLBACK_LIFECYCLE.md new file mode 100644 index 000000000..72089e64c --- /dev/null +++ b/dev-docs/agent-runner-pluginization/INTERACTION_CALLBACK_LIFECYCLE.md @@ -0,0 +1,44 @@ +# Interaction Callback Lifecycle: Follow-up Design + +## Current Issue + +The DingTalk A2UI adapter stores `outTrackId` callback context only in process +memory. The callback is ignored after an adapter restart even though the +interaction request and hashed callback token are persisted. The in-memory +context uses a fixed 30-minute expiry, while a Host interaction may remain +valid for up to 24 hours. Expired contexts are pruned only when another card is +sent, and there is no capacity limit. + +The legacy DingTalk Dify form path has separate in-memory `card_state` and +requires its own migration assessment. + +## Intended Contract + +1. `InteractionStore` remains authoritative for callback token, request, + delivery target, status, and expiry. An in-memory cache miss must never + invalidate a pending card. +2. Parse the callback token and `outTrackId` from DingTalk's card callback. + Resolve the stored request and delivery result, then validate the bot, + conversation, actor, and card identity before consuming the submission. + Reconstruct field types and option values from the stored request. +3. If profiling justifies a cache, bound it globally and per bot, cache only + small derived metadata, and use a short TTL with LRU eviction. Starting + limits to evaluate: 4,096 entries per process, 512 per bot, and five + minutes. Cache eviction affects performance only. +4. Waiting cards are database records, not queued in-memory tasks. Bound + concurrent callback execution separately. Persist callback admission and + the resume intent atomically before acknowledging delivery; a durable + worker queue with leases can then resume after process restart. A bounded + in-memory queue alone cannot close the crash gap after submission commit. +5. Track pending-card count, callback backlog, processing latency, cache + occupancy, and expired/rejected callbacks. Apply workspace-level admission + limits and database retention separately from the cache bounds. + +## Verification Needed + +- A pending card still submits after adapter restart and after cache eviction. +- A card remains usable until its actual persisted expiry, including when + other cards are sent. +- Replayed callbacks resume the processor once; crashes between admission and + execution recover the queued work once. +- Forged card, conversation, actor, or option identifiers are rejected. diff --git a/dev-docs/event-based-agents/adapters/wecombot.md b/dev-docs/event-based-agents/adapters/wecombot.md index 23751aec7..5525853d2 100644 --- a/dev-docs/event-based-agents/adapters/wecombot.md +++ b/dev-docs/event-based-agents/adapters/wecombot.md @@ -19,6 +19,16 @@ The adapter is registered as `wecombot-omni`. This is separate from regular WeCom internal applications (`wecom-omni`). WeComBot supports WebSocket long connection mode, which does not require a webhook URL. Webhook mode remains available when `enable-webhook=true`. +## AI Interactions + +In WebSocket mode, `interaction.request` renders actions as a +`button_interaction` template card. A single `select` field renders as a native +`multiple_interaction` dropdown with a Submit button (up to 10 options). The +callback's `selected_items.selected_item[].option_ids.option_id` carries the +selected option ID, as documented in the WeCom AI Bot event protocol. The Host +resolves the original option value from its persisted interaction request. +Webhook mode does not offer this proactive card API. + ## Configuration | Field | Required | Default | Description | diff --git a/plugins/Runner/LocalAgent/components/runner/default.py b/plugins/Runner/LocalAgent/components/runner/default.py index 58ecbd39a..8edb2a54e 100644 --- a/plugins/Runner/LocalAgent/components/runner/default.py +++ b/plugins/Runner/LocalAgent/components/runner/default.py @@ -49,12 +49,18 @@ class RunCancelledError(Exception): class RunDeadline: """Wall-clock deadline shared by assembly, model calls, and tool calls.""" - def __init__(self, timeout_seconds: float): + def __init__(self, timeout_seconds: float, runtime: Any = None): self.timeout_seconds = max(0.001, float(timeout_seconds)) self._deadline = time.monotonic() + self.timeout_seconds + self._runtime = runtime + self._initial_host_deadline = getattr(runtime, "deadline_at", None) def remaining(self) -> float: - return max(0.0, self._deadline - time.monotonic()) + extension = 0.0 + current_host_deadline = getattr(self._runtime, "deadline_at", None) + if self._initial_host_deadline is not None and current_host_deadline is not None: + extension = float(current_host_deadline) - float(self._initial_host_deadline) + return max(0.0, self._deadline + extension - time.monotonic()) class RunInterruptChecker: @@ -148,16 +154,19 @@ class RunInterruptChecker: cancellation = asyncio.create_task(self._cancelled.wait()) temporary_watcher = asyncio.create_task(self._watch()) if self.available and self._watcher is None else None try: - await asyncio.wait( - {task, cancellation}, - timeout=deadline.remaining() if deadline else None, - return_when=asyncio.FIRST_COMPLETED, - ) - if self._cancelled.is_set(): - raise RunCancelledError(CANCELLED_ERROR) - if not task.done(): - raise asyncio.TimeoutError(TIMEOUT_ERROR) - return task.result() + while True: + if self._cancelled.is_set(): + raise RunCancelledError(CANCELLED_ERROR) + if task.done(): + return task.result() + remaining = deadline.remaining() if deadline else None + if remaining is not None and remaining <= 0: + raise asyncio.TimeoutError(TIMEOUT_ERROR) + await asyncio.wait( + {task, cancellation}, + timeout=min(remaining, self.interval_seconds) if remaining is not None else None, + return_when=asyncio.FIRST_COMPLETED, + ) finally: pending = [task, cancellation] + ([temporary_watcher] if temporary_watcher else []) for future in pending: @@ -222,7 +231,7 @@ class DefaultRunner(Runner): api = self.get_run_api(ctx) config = ctx.config if isinstance(ctx.config, dict) else {} timeout_seconds = get_run_timeout_seconds(config) - deadline = RunDeadline(timeout_seconds) if timeout_seconds is not None else None + deadline = RunDeadline(timeout_seconds, ctx.runtime) if timeout_seconds is not None else None usage_tracker = RunUsageTracker() if await interrupt_checker.is_cancelled(force=True): diff --git a/plugins/Runner/LocalAgent/components/runner/default.yaml b/plugins/Runner/LocalAgent/components/runner/default.yaml index cdf045c50..46a44619d 100644 --- a/plugins/Runner/LocalAgent/components/runner/default.yaml +++ b/plugins/Runner/LocalAgent/components/runner/default.yaml @@ -310,6 +310,7 @@ spec: skill_authoring: true interrupt: true steering: true + interactions: true permissions: models: - count_tokens @@ -324,6 +325,8 @@ spec: - retrieve history: - page + interactions: + - request execution: python: path: default.py diff --git a/plugins/Runner/LocalAgent/manifest.yaml b/plugins/Runner/LocalAgent/manifest.yaml index 39b90e3d1..6c07f2482 100644 --- a/plugins/Runner/LocalAgent/manifest.yaml +++ b/plugins/Runner/LocalAgent/manifest.yaml @@ -3,7 +3,7 @@ kind: Plugin metadata: author: langbot-team name: LocalAgent - version: 0.2.4 + version: 0.2.5 repository: https://github.com/langbot-app/LangBot/tree/master/plugins/Runner/LocalAgent label: en_US: Local Agent diff --git a/plugins/Runner/LocalAgent/pyproject.toml b/plugins/Runner/LocalAgent/pyproject.toml index a824c660a..2cbab7e75 100644 --- a/plugins/Runner/LocalAgent/pyproject.toml +++ b/plugins/Runner/LocalAgent/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "langbot-local-agent" -version = "0.2.4" +version = "0.2.5" description = "Built-in agent with model fallback, tools, and knowledge retrieval" requires-python = ">=3.11,<4.0" dependencies = [ diff --git a/plugins/Runner/LocalAgent/tests/test_run_controls.py b/plugins/Runner/LocalAgent/tests/test_run_controls.py index 7b4f28893..ed2b8a6cf 100644 --- a/plugins/Runner/LocalAgent/tests/test_run_controls.py +++ b/plugins/Runner/LocalAgent/tests/test_run_controls.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import time import pytest @@ -31,6 +32,25 @@ async def test_slow_ledger_does_not_delay_chunks_or_deadline(): assert checker._watcher is None +@pytest.mark.asyncio +async def test_interaction_extension_keeps_local_runner_wait_alive(): + context = make_context() + context.runtime.deadline_at = time.time() + 0.03 + deadline = RunDeadline(0.03, context.runtime) + checker = RunInterruptChecker(None, context, interval_seconds=0.01) + + async def interaction(): + await asyncio.sleep(0.01) + context.runtime.deadline_at += 0.1 + await asyncio.sleep(0.06) + return "submitted" + + assert await checker.wait_for(interaction(), deadline=deadline) == "submitted" + assert deadline.remaining() > 0 + assert await checker.wait_for(interaction(), deadline=deadline) == "submitted" + assert deadline.remaining() > 0 + + @pytest.mark.asyncio async def test_operation_timeout_is_not_mistaken_for_poll_timeout(): checker = RunInterruptChecker(None, make_context()) diff --git a/plugins/Runner/claude-code-agent/README.md b/plugins/Runner/claude-code-agent/README.md index 1311c515e..b9e7ae143 100644 --- a/plugins/Runner/claude-code-agent/README.md +++ b/plugins/Runner/claude-code-agent/README.md @@ -70,13 +70,9 @@ Run Claude Code CLI as a LangBot Runner. The runner exposes a real MCP tool named `ask_user_question` through the run-scoped LangBot MCP bridge. Its standard Claude `tool_use` event is converted -to LangBot's provider-neutral `interaction.requested` contract. The CLI process -is stopped while the user is answering. A card submission starts a new -AgentRun, resumes the same Claude Code session, and sends the answer as the next -authoritative user turn. Claude CLI must complete an MCP call before persisting -a resumable session, so it cannot accept a second result for the old -`tool_use_id` after the process exits. No Python coroutine or Claude process is -kept waiting for the user. +to a single LangBot `request_interaction` call. The call waits for the user's +card submission and returns all form values to the MCP tool in the same AgentRun. +The CLI process remains active while the interaction is pending. ## Shared-worker candidate / daemon upgrade diff --git a/plugins/Runner/claude-code-agent/pkg/native_cli.py b/plugins/Runner/claude-code-agent/pkg/native_cli.py index 112454a1d..d3d479692 100644 --- a/plugins/Runner/claude-code-agent/pkg/native_cli.py +++ b/plugins/Runner/claude-code-agent/pkg/native_cli.py @@ -21,7 +21,6 @@ from langbot_plugin.api.agent_tools.mcp_access import AgentRunMCPAccess from langbot_plugin.api.agent_tools.mcp_config import AgentMCPServerConfig from langbot_plugin.api.definition.components.runner.runner import Runner from langbot_plugin.api.entities.builtin.runner import ( - InteractionAction, InteractionField, InteractionOption, InteractionRequest, @@ -40,7 +39,6 @@ from pkg.runtime_support import local_workspace, terminate_process_group from pkg.steering import run_with_steering SESSION_STATE_KEY = "external.claude_code_session_id" -PENDING_INTERACTION_STATE_KEY = "external.claude_code_pending_interaction" SUPPORTED_LOCATIONS = {"local", "remote-ssh", "daemon"} @@ -238,7 +236,9 @@ _LANGBOT_MCP_SYSTEM_PROMPT = ( "any mcp__langbot_agent__* tool, then call that tool directly. In coordinator mode, " "the main session may expose only delegation tools; delegate the MCP request to one " "worker and require that worker to perform the same ToolSearch-then-call flow. Never " - "claim a LangBot tool result unless the direct or delegated tool call completed." + "claim a LangBot tool result unless the direct or delegated tool call completed. " + "For user questions, call mcp__langbot_agent__ask_user_question so the answer returns " + "inside the current CLI process; do not call the built-in AskUserQuestion tool." ) @@ -351,7 +351,7 @@ def _interaction_from_claude_tool( title=title, description=(str(tool_input.get("description") or "").strip()[:10000] or None), fields=fields, - actions=[InteractionAction(id="submit", label="Submit", style="primary")], + actions=[], fallback_text=f"{title}: " + "; ".join(field.label for field in fields), ) continuation = { @@ -363,11 +363,6 @@ def _interaction_from_claude_tool( return request, continuation -def _pending_interaction(ctx: RunnerContext) -> dict[str, typing.Any] | None: - value = ctx.state.conversation.get(PENDING_INTERACTION_STATE_KEY) - return dict(value) if isinstance(value, dict) else None - - def _submission_payload( submission: InteractionSubmission, continuation: dict[str, typing.Any], @@ -391,14 +386,6 @@ def _submission_payload( } -def _interaction_resume_prompt(payload: dict[str, typing.Any]) -> str: - return ( - "The user answered the previously paused ask_user_question call. " - "Treat these values as the authoritative response and continue the interrupted task.\n" - + json.dumps(payload, ensure_ascii=False) - ) - - class ClaudeQuestionOption(pydantic.BaseModel): label: str = pydantic.Field(min_length=1, max_length=512) description: str | None = pydantic.Field(default=None, max_length=2000) @@ -450,7 +437,14 @@ class ClaudeCodeExternalTools(AgentRunExternalTools): args_model=AskUserQuestionArgs, ) async def ask_user_question(self, args: AskUserQuestionArgs) -> dict[str, typing.Any]: - return {"status": "paused", "question_count": len(args.questions)} + request, continuation = _interaction_from_claude_tool( + uuid.uuid4().hex, args.model_dump(mode="json", by_alias=True) + ) + result = await self.ctx.request_interaction(request, timeout=3600, on_unsupported="degrade") + if result.status != "submitted" or result.submission is None: + raise NativeCliError(f"User interaction {result.status}", code="claude_code.interaction_expired") + answers = _submission_payload(result.submission, continuation)["answers"] + return {"status": "submitted", "answers": answers} class NativeClaudeCodeRunner(Runner): @@ -550,31 +544,9 @@ class NativeClaudeCodeRunner(Runner): async def run(self, ctx: RunnerContext) -> typing.AsyncGenerator[RunnerResult, None]: try: config = self._validate_config(ctx) - submission = ctx.input.interaction - if submission is not None: - continuation = _pending_interaction(ctx) - if continuation is None: - raise NativeCliError( - "pending Claude interaction state was not found", - code="claude_code.interaction_not_found", - ) - tool_use_id = str(continuation.get("tool_use_id") or "").strip() - if not tool_use_id: - raise NativeCliError( - "pending Claude interaction has no tool_use_id", - code="claude_code.interaction_invalid", - ) - prompt = _interaction_resume_prompt(_submission_payload(submission, continuation)) - yield RunnerResult.state_updated( - ctx.run_id, - PENDING_INTERACTION_STATE_KEY, - None, - scope="conversation", - ) - else: - prompt = _input_text(ctx) - if not prompt: - raise NativeCliError("input text is required", code="claude_code.empty_input") + prompt = _input_text(ctx) + if not prompt: + raise NativeCliError("input text is required", code="claude_code.empty_input") session_id, session_created = self._session_id(ctx, config) if session_created: yield RunnerResult.state_updated(ctx.run_id, SESSION_STATE_KEY, session_id, scope="conversation") @@ -850,7 +822,6 @@ async def _run_cli_process_events( deadline = time.monotonic() + timeout sequence = 0 final_parts: list[str] = [] - pending_interaction: tuple[InteractionRequest, dict[str, typing.Any]] | None = None terminal_result_text = "" stderr_task = asyncio.create_task(process.stderr.read()) try: @@ -884,15 +855,16 @@ async def _run_cli_process_events( "data": {"key": SESSION_STATE_KEY, "value": session_id, "scope": "conversation"}, } question_tool = _claude_question_tool_use(parsed) - if question_tool is not None and pending_interaction is None: - tool_use_id, tool_input = question_tool - pending_interaction = _interaction_from_claude_tool(tool_use_id, tool_input) - continue + if question_tool is not None: + raise NativeCliError( + "Use the LangBot ask_user_question MCP tool for user input", + code="claude_code.interaction_invalid", + ) chunk = _event_text(parsed) if parsed.get("type") == "result" and chunk: terminal_result_text = chunk continue - if chunk and pending_interaction is None: + if chunk: final_parts.append(chunk) if streaming: sequence += 1 @@ -914,24 +886,6 @@ async def _run_cli_process_events( raise NativeCliError( stderr or f"Claude Code exited with status {returncode}", code="claude_code.process_failed" ) - if pending_interaction is not None: - request, continuation = pending_interaction - yield { - "type": "state.updated", - "data": { - "key": PENDING_INTERACTION_STATE_KEY, - "value": continuation, - "scope": "conversation", - }, - } - yield { - "type": "action.requested", - "data": { - "action": "interaction.requested", - "payload": request.model_dump(mode="json"), - }, - } - return final_text = (terminal_result_text or "".join(final_parts)).strip() if not final_text: raise NativeCliError("Claude Code returned no assistant text", code="claude_code.empty_response") diff --git a/plugins/Runner/claude-code-agent/readme/README_en_US.md b/plugins/Runner/claude-code-agent/readme/README_en_US.md index 1311c515e..b9e7ae143 100644 --- a/plugins/Runner/claude-code-agent/readme/README_en_US.md +++ b/plugins/Runner/claude-code-agent/readme/README_en_US.md @@ -70,13 +70,9 @@ Run Claude Code CLI as a LangBot Runner. The runner exposes a real MCP tool named `ask_user_question` through the run-scoped LangBot MCP bridge. Its standard Claude `tool_use` event is converted -to LangBot's provider-neutral `interaction.requested` contract. The CLI process -is stopped while the user is answering. A card submission starts a new -AgentRun, resumes the same Claude Code session, and sends the answer as the next -authoritative user turn. Claude CLI must complete an MCP call before persisting -a resumable session, so it cannot accept a second result for the old -`tool_use_id` after the process exits. No Python coroutine or Claude process is -kept waiting for the user. +to a single LangBot `request_interaction` call. The call waits for the user's +card submission and returns all form values to the MCP tool in the same AgentRun. +The CLI process remains active while the interaction is pending. ## Shared-worker candidate / daemon upgrade diff --git a/plugins/Runner/claude-code-agent/requirements.txt b/plugins/Runner/claude-code-agent/requirements.txt index 6b0a0cb18..2e08a9945 100644 --- a/plugins/Runner/claude-code-agent/requirements.txt +++ b/plugins/Runner/claude-code-agent/requirements.txt @@ -1 +1 @@ -langbot-plugin>=0.7.4,<0.8 +langbot-plugin>=0.7.20,<0.8 diff --git a/plugins/Runner/codex-agent/README.md b/plugins/Runner/codex-agent/README.md index c8138fb08..c5cd3fe29 100644 --- a/plugins/Runner/codex-agent/README.md +++ b/plugins/Runner/codex-agent/README.md @@ -66,15 +66,12 @@ Run Codex CLI as a LangBot Runner. The runner registers a real Codex app-server dynamic tool named `ask_user_question` and also accepts Codex's native `item/tool/requestUserInput` request. Both are converted to LangBot's -provider-neutral `interaction.requested` contract, so Lark, DingTalk, and other +provider-neutral `request_interaction` call, so Lark, DingTalk, and other delivery adapters can render the same fields and actions. -The app-server process is stopped while the user is answering. The submission -starts a new AgentRun and resumes the same Codex thread. Codex app-server does -not support replying to an old JSON-RPC tool request from a new process, so the -answer is delivered as the next authoritative user turn rather than injected -as the old tool result. This is a provider transport limitation; the interaction -is still a real model tool call and no process is kept waiting. +The call waits for the user's submission and returns all form values to the +app-server tool in the same AgentRun. The app-server process remains active +while the interaction is pending. Codex app-server command-execution and file-change approval requests are also converted to action-only confirmation cards. The previous turn is cancelled diff --git a/plugins/Runner/codex-agent/pkg/native_cli.py b/plugins/Runner/codex-agent/pkg/native_cli.py index e8111b1b2..a8584355c 100644 --- a/plugins/Runner/codex-agent/pkg/native_cli.py +++ b/plugins/Runner/codex-agent/pkg/native_cli.py @@ -40,7 +40,6 @@ from pkg.runtime_support import local_workspace, serialize_codex_session, termin from pkg.steering import run_with_steering SESSION_STATE_KEY = "external.codex_session_id" -PENDING_INTERACTION_STATE_KEY = "external.codex_pending_interaction" SUPPORTED_LOCATIONS = {"local", "remote-ssh", "daemon"} DEFAULT_TIMEOUT_SECONDS = 1800.0 CODEX_STDIO_LIMIT_BYTES = 16 * 1024 * 1024 @@ -523,7 +522,7 @@ def _interaction_from_questions( title=request_title, description=description.strip()[:10000] or None, fields=fields, - actions=[InteractionAction(id="submit", label="Submit", style="primary")], + actions=[], fallback_text=f"{request_title}: " + "; ".join(field.label for field in fields), ) continuation = { @@ -568,11 +567,6 @@ def _interaction_from_codex_request( return request, continuation -def _pending_interaction(ctx: RunnerContext) -> dict[str, typing.Any] | None: - value = ctx.state.conversation.get(PENDING_INTERACTION_STATE_KEY) - return dict(value) if isinstance(value, dict) else None - - def _approval_item(params: dict[str, typing.Any], items: dict[str, dict[str, typing.Any]]) -> dict[str, typing.Any]: item_id = str(params.get("itemId") or params.get("callId") or "") item = items.get(item_id) @@ -695,61 +689,6 @@ def _interaction_from_codex_approval( return request, continuation -def _interaction_resume_prompt( - submission: InteractionSubmission, - continuation: dict[str, typing.Any], -) -> str: - if submission.interaction_id != continuation.get("interaction_id"): - raise NativeCliError( - "interaction submission does not match the pending Codex request", code="codex.interaction_mismatch" - ) - question_by_id = { - str(item.get("id")): str(item.get("question") or item.get("id")) - for item in continuation.get("questions", []) - if isinstance(item, dict) and item.get("id") - } - answers = [ - {"id": field_id, "question": question_by_id.get(field_id, field_id), "answer": value} - for field_id, value in submission.values.items() - ] - payload = {"action": submission.action_id, "answers": answers} - return ( - "The user answered the previously paused ask_user_question call. " - "Treat these values as the authoritative response and continue the interrupted task.\n" - + json.dumps(payload, ensure_ascii=False) - ) - - -def _approval_resume( - submission: InteractionSubmission, - continuation: dict[str, typing.Any], -) -> tuple[str, dict[str, str] | None]: - if submission.interaction_id != continuation.get("interaction_id"): - raise NativeCliError( - "interaction submission does not match the pending Codex approval", code="codex.interaction_mismatch" - ) - action_id = str(submission.action_id or "") - summary = str(continuation.get("approval_summary") or "") - if action_id == APPROVE_ONCE_ACTION: - category = str(continuation.get("approval_category") or "") - fingerprint = str(continuation.get("approval_fingerprint") or "") - if not category or not fingerprint: - raise NativeCliError("pending Codex approval has no operation fingerprint", code="codex.approval_invalid") - prompt = ( - "The user approved exactly one retry of the previously paused Codex operation. " - "Retry that same operation now. This approval does not authorize any different command or file change.\n" - + summary - ) - return prompt, {"category": category, "fingerprint": fingerprint} - if action_id == REJECT_ACTION: - prompt = ( - "The user rejected the previously paused Codex operation. Do not retry that exact operation. " - "Continue with a safe alternative or explain why the task cannot proceed.\n" + summary - ) - return prompt, None - raise NativeCliError(f"unsupported Codex approval action: {action_id}", code="codex.approval_invalid") - - class NativeCodexRunner(Runner): def _validate_config(self, ctx: RunnerContext) -> dict[str, typing.Any]: data = ctx.config or {} @@ -810,8 +749,6 @@ class NativeCodexRunner(Runner): stored = self._stored_session_id(ctx) if not stored or not config["reuse_session"]: return "" - if ctx.input.interaction is not None and _pending_interaction(ctx) is not None: - return stored if config["location"] == "local": env = {**os.environ, **config["env"]} pending_calls = _pending_session_tool_calls(_shared_codex_home(env), stored) @@ -847,53 +784,14 @@ class NativeCodexRunner(Runner): async def run(self, ctx: RunnerContext) -> typing.AsyncGenerator[RunnerResult, None]: try: config = self._validate_config(ctx) - submission = ctx.input.interaction - approval_grant: dict[str, str] | None = None - if submission is not None: - continuation = _pending_interaction(ctx) - if continuation is None: - raise NativeCliError( - "pending Codex interaction state was not found", code="codex.interaction_not_found" - ) - if continuation.get("kind") == "approval": - prompt, approval_grant = _approval_resume(submission, continuation) - else: - prompt = _interaction_resume_prompt(submission, continuation) - yield RunnerResult.state_updated( - ctx.run_id, - PENDING_INTERACTION_STATE_KEY, - None, - scope="conversation", - ) - else: - prompt = _input_text(ctx) - if not prompt: - raise NativeCliError("input text is required", code="codex.empty_input") - - approval_grant_holder = {"value": approval_grant} + prompt = _input_text(ctx) + if not prompt: + raise NativeCliError("input text is required", code="codex.empty_input") def run_turn(turn_prompt: str, resume_session_id: str) -> typing.AsyncGenerator[RunnerResult, None]: - turn_approval_grant = approval_grant_holder["value"] - approval_grant_holder["value"] = None if config["location"] == "daemon": - if turn_approval_grant is None: - return self._run_daemon(ctx, config, turn_prompt, resume_session_id) - return self._run_daemon( - ctx, - config, - turn_prompt, - resume_session_id, - approval_grant=turn_approval_grant, - ) - if turn_approval_grant is None: - return self._run_local_or_ssh(ctx, config, turn_prompt, resume_session_id) - return self._run_local_or_ssh( - ctx, - config, - turn_prompt, - resume_session_id, - approval_grant=turn_approval_grant, - ) + return self._run_daemon(ctx, config, turn_prompt, resume_session_id) + return self._run_local_or_ssh(ctx, config, turn_prompt, resume_session_id) async for result in run_with_steering( ctx, @@ -1112,6 +1010,7 @@ async def _run_cli_process( _run_cli_process_events( command, args, + ctx=ctx, cwd=cwd, env=env, timeout=timeout, @@ -1165,6 +1064,8 @@ class _CodexAppServerClient: streaming: bool, approval_grant: dict[str, str] | None, approval_policy: str | None, + ctx: RunnerContext | None = None, + operation_timeout: float = 120, ) -> None: self.process = process self.streaming = streaming @@ -1179,12 +1080,28 @@ class _CodexAppServerClient: self.final_error = "" self.seen_agent_message_item_ids: set[str] = set() self.final_chunk_emitted = False - self.interaction_request: InteractionRequest | None = None - self.interaction_continuation: dict[str, typing.Any] | None = None self.approval_grant = dict(approval_grant) if approval_grant else None self.approval_policy = approval_policy + self.ctx = ctx + self.operation_timeout = operation_timeout + self.timeout_scope: asyncio.Timeout | None = None self.items: dict[str, dict[str, typing.Any]] = {} + async def _wait_for_user(self, request: InteractionRequest) -> InteractionSubmission: + if self.ctx is None: + raise NativeCliError("No active run for interaction", code="codex.interaction_invalid") + loop = asyncio.get_running_loop() + if self.timeout_scope is not None: + self.timeout_scope.reschedule(loop.time() + 3600 + self.operation_timeout) + try: + result = await self.ctx.request_interaction(request, timeout=3600, on_unsupported="degrade") + if result.status != "submitted" or result.submission is None: + raise NativeCliError(f"User interaction {result.status}", code="codex.interaction_expired") + return result.submission + finally: + if self.timeout_scope is not None: + self.timeout_scope.reschedule(loop.time() + self.operation_timeout) + async def _write_json(self, payload: dict[str, typing.Any]) -> None: assert self.process.stdin is not None data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n" @@ -1363,12 +1280,11 @@ class _CodexAppServerClient: self.approval_grant = None await self.respond(request_id, {"decision": "accept"}) return - request, continuation = _interaction_from_codex_approval(method, params, item) - self.interaction_request = request - self.interaction_continuation = continuation - await self.respond(request_id, {"decision": "cancel"}) - await self._interrupt_turn(params) - self.finish_turn() + request, _ = _interaction_from_codex_approval(method, params, item) + submission = await self._wait_for_user(request) + await self.respond( + request_id, {"decision": "accept" if submission.action_id == APPROVE_ONCE_ACTION else "cancel"} + ) elif method in {"item/tool/call", "item/tool/requestUserInput"}: params = raw.get("params") if not isinstance(params, dict): @@ -1377,50 +1293,36 @@ class _CodexAppServerClient: await self.respond_error(request_id, f"unhandled dynamic tool: {params.get('tool')}") return try: - request, continuation = _interaction_from_codex_request(method, params) + request, _ = _interaction_from_codex_request(method, params) except NativeCliError as exc: await self.respond_error(request_id, exc.message) return - self.interaction_request = request - self.interaction_continuation = continuation + submission = await self._wait_for_user(request) if method == "item/tool/call": await self.respond( request_id, { "success": True, "contentItems": [ - { - "type": "inputText", - "text": "LangBot paused this run for user input; the answer will arrive in a later turn.", - } + {"type": "inputText", "text": json.dumps(submission.values, ensure_ascii=False)} ], }, ) else: - empty_answers = {field.id: {"answers": []} for field in request.fields} - await self.respond(request_id, {"answers": empty_answers}) - await self._interrupt_turn(params) - self.finish_turn() + await self.respond( + request_id, + { + "answers": { + field_id: {"answers": value if isinstance(value, list) else [str(value)]} + for field_id, value in submission.values.items() + } + }, + ) elif method == "mcpServer/elicitation/request": await self.respond(request_id, {"action": "accept", "content": None, "_meta": None}) else: await self.respond_error(request_id, f"unhandled server request: {method}") - async def _interrupt_turn(self, params: dict[str, typing.Any]) -> None: - thread_id = str(params.get("threadId") or self.thread_id) - turn_id = str(params.get("turnId") or "") - if not thread_id or not turn_id: - return - self.next_id += 1 - await self._write_json( - { - "jsonrpc": "2.0", - "id": self.next_id, - "method": "turn/interrupt", - "params": {"threadId": thread_id, "turnId": turn_id}, - } - ) - async def handle_notification(self, raw: dict[str, typing.Any]) -> None: method = str(raw.get("method") or "") params = raw.get("params") @@ -1560,6 +1462,7 @@ async def _run_cli_process_events( command: str, args: list[str], *, + ctx: RunnerContext | None = None, cwd: str | None, env: dict[str, str], timeout: float, @@ -1598,6 +1501,8 @@ async def _run_cli_process_events( streaming=streaming, approval_grant=approval_grant, approval_policy=approval_policy, + ctx=ctx, + operation_timeout=timeout, ) reader_task = asyncio.create_task(client.read_stdout()) stderr_task = asyncio.create_task(process.stderr.read()) @@ -1606,7 +1511,8 @@ async def _run_cli_process_events( if initial_stdin: process.stdin.write(initial_stdin) await process.stdin.drain() - async with asyncio.timeout(timeout): + async with asyncio.timeout(timeout) as timeout_scope: + client.timeout_scope = timeout_scope await client.initialize() thread_id = await client.start_or_resume_thread( resume_session_id, @@ -1632,27 +1538,6 @@ async def _run_cli_process_events( raise NativeCliError( stderr or f"Codex app-server exited with status {process.returncode}", code="codex.process_failed" ) - if client.interaction_request is not None and client.interaction_continuation is not None: - result_sequence += 1 - yield { - "type": "state.updated", - "sequence": result_sequence, - "data": { - "key": PENDING_INTERACTION_STATE_KEY, - "value": client.interaction_continuation, - "scope": "conversation", - }, - } - result_sequence += 1 - yield { - "type": "action.requested", - "sequence": result_sequence, - "data": { - "action": "interaction.requested", - "payload": client.interaction_request.model_dump(mode="json"), - }, - } - return if client.final_error: raise NativeCliError(client.final_error, code="codex.turn_failed") final_text = "".join(client.final_parts).strip() diff --git a/plugins/Runner/codex-agent/readme/README_en_US.md b/plugins/Runner/codex-agent/readme/README_en_US.md index c8138fb08..c5cd3fe29 100644 --- a/plugins/Runner/codex-agent/readme/README_en_US.md +++ b/plugins/Runner/codex-agent/readme/README_en_US.md @@ -66,15 +66,12 @@ Run Codex CLI as a LangBot Runner. The runner registers a real Codex app-server dynamic tool named `ask_user_question` and also accepts Codex's native `item/tool/requestUserInput` request. Both are converted to LangBot's -provider-neutral `interaction.requested` contract, so Lark, DingTalk, and other +provider-neutral `request_interaction` call, so Lark, DingTalk, and other delivery adapters can render the same fields and actions. -The app-server process is stopped while the user is answering. The submission -starts a new AgentRun and resumes the same Codex thread. Codex app-server does -not support replying to an old JSON-RPC tool request from a new process, so the -answer is delivered as the next authoritative user turn rather than injected -as the old tool result. This is a provider transport limitation; the interaction -is still a real model tool call and no process is kept waiting. +The call waits for the user's submission and returns all form values to the +app-server tool in the same AgentRun. The app-server process remains active +while the interaction is pending. Codex app-server command-execution and file-change approval requests are also converted to action-only confirmation cards. The previous turn is cancelled diff --git a/plugins/Runner/codex-agent/requirements.txt b/plugins/Runner/codex-agent/requirements.txt index 6b0a0cb18..2e08a9945 100644 --- a/plugins/Runner/codex-agent/requirements.txt +++ b/plugins/Runner/codex-agent/requirements.txt @@ -1 +1 @@ -langbot-plugin>=0.7.4,<0.8 +langbot-plugin>=0.7.20,<0.8 diff --git a/plugins/Runner/dify-agent/README.md b/plugins/Runner/dify-agent/README.md index fad5ed7b5..6988a7d48 100644 --- a/plugins/Runner/dify-agent/README.md +++ b/plugins/Runner/dify-agent/README.md @@ -54,20 +54,20 @@ events, which are used only when no explicit answer was produced. ## Workflow Human Input -When Dify emits `workflow_paused` with a `human_input_required` reason, the -runner asks LangBot to deliver a structured interaction. A validated -`interaction.submitted` event resumes Dify through -`/form/human_input/{form_token}` and `/workflow/{workflow_run_id}/events`. +When Dify emits `workflow_paused` with a `human_input_required` reason, or a +direct `human_input_required` event, the runner asks LangBot to deliver a +structured interaction and waits for the validated submission in the same run. +It then resumes Dify through `/form/human_input/{form_token}`. The response may itself +stream events; otherwise the runner reads `/workflow/{workflow_run_id}/events`. Workflows that pause again produce a new interaction and can be resumed again. Forms are emitted as atomic steps: the runner collects one field at a time and then emits the action buttons. This matches LangBot delivery adapters that support a single select or an action-only confirmation. Provider continuation data is not included in the interaction payload. The -runner stores `form_token`, `workflow_run_id`, the Dify user tag, and field/action -mappings in authorized plugin storage under a random LangBot `interaction_id`. -The continuation is deleted after a successful terminal event or after it is -replaced by a later pause. +runner keeps `form_token`, `workflow_run_id`, the Dify user tag, and field/action +mappings in the active run. Previously issued interactions can still resume +through their stored continuation records during migration. The selected Runner binding must allow interactions, and the delivery adapter must support the requested field/action shape. Adapters with a smaller diff --git a/plugins/Runner/dify-agent/components/runner/default.py b/plugins/Runner/dify-agent/components/runner/default.py index ddb946be1..30068c412 100644 --- a/plugins/Runner/dify-agent/components/runner/default.py +++ b/plugins/Runner/dify-agent/components/runner/default.py @@ -6,14 +6,11 @@ Real Dify Service API integration supporting chat, agent, and workflow app types from __future__ import annotations import base64 -import hashlib import json import logging import re -import time import typing import uuid -from contextlib import aclosing from langbot_plugin.api.definition.components.runner.runner import Runner from langbot_plugin.api.entities.builtin.provider.message import MessageChunk @@ -25,7 +22,6 @@ from langbot_plugin.api.entities.builtin.runner import ( RunnerContext, RunnerResult, ) -from langbot_plugin.entities.io.errors import ActionCallError from pkg.asset_gateway import register_assets from pkg.dify_client import ( AsyncDifyClient, @@ -39,7 +35,6 @@ from pkg.scoped_identity import scoped_identity logger = logging.getLogger(__name__) DEFAULT_LANGBOT_ASSET_TOKEN_INPUT = "langbot_asset_run_token" -INTERACTION_STORAGE_PREFIX = "dify.interactions." def _to_bool(value: typing.Any, default: bool = False) -> bool: @@ -247,17 +242,68 @@ def _usage_from_payload(payload: typing.Any) -> dict[str, typing.Any] | None: return normalized or None +def _mapping_value(mapping: typing.Any, *keys: str) -> typing.Any: + """Return a protocol value using explicit aliases with case-insensitive matching.""" + if not isinstance(mapping, dict): + return None + for key in keys: + if key in mapping: + return mapping[key] + lowered = {str(key).lower(): value for key, value in mapping.items()} + for key in keys: + if key.lower() in lowered: + return lowered[key.lower()] + return None + + +def _protocol_name(value: typing.Any) -> str: + if not isinstance(value, str): + return "" + return re.sub(r"[-\s]+", "_", value.strip().lower()) + + +def _workflow_run_id(event: dict[str, typing.Any], fallback: str = "") -> str: + data = event.get("data") if isinstance(event.get("data"), dict) else {} + value = _mapping_value(data, "workflow_run_id", "workflowRunId") + if value in (None, ""): + value = _mapping_value(event, "workflow_run_id", "workflowRunId") + return str(value or fallback).strip() + + +def _human_input_reason(event: dict[str, typing.Any]) -> dict[str, typing.Any] | None: + data = event.get("data") if isinstance(event.get("data"), dict) else {} + if _protocol_name(event.get("event")) == "human_input_required": + return data + + raw_reasons = _mapping_value(data, "reasons", "pause_reasons", "pauseReasons") + if isinstance(raw_reasons, dict): + reasons = [raw_reasons] + elif isinstance(raw_reasons, list): + reasons = raw_reasons + else: + raw_reason = _mapping_value(data, "reason", "pause_reason", "pauseReason") + reasons = [raw_reason] if isinstance(raw_reason, dict) else [] + + for reason in reasons: + if not isinstance(reason, dict): + continue + reason_type = _mapping_value(reason, "TYPE", "type", "reason_type", "reasonType") + if _protocol_name(reason_type) == "human_input_required": + return reason + return None + + def _form_field_name(field: dict[str, typing.Any]) -> str: return str( - field.get("output_variable_name") or field.get("variable") or field.get("name") or field.get("id") or "" + _mapping_value(field, "output_variable_name", "outputVariableName", "variable", "name", "id") or "" ).strip() def _form_field_options(field: dict[str, typing.Any]) -> list[str]: - source = field.get("option_source") - raw_options = source.get("value") if isinstance(source, dict) else None + source = _mapping_value(field, "option_source", "optionSource") + raw_options = _mapping_value(source, "value") if isinstance(source, dict) else None if raw_options is None: - raw_options = field.get("options") + raw_options = _mapping_value(field, "options") if isinstance(raw_options, str): raw_options = [line.strip() for line in raw_options.splitlines() if line.strip()] if not isinstance(raw_options, list): @@ -266,7 +312,7 @@ def _form_field_options(field: dict[str, typing.Any]) -> list[str]: options: list[str] = [] for option in raw_options: if isinstance(option, dict): - value = option.get("value") or option.get("label") or option.get("name") + value = _mapping_value(option, "value", "label", "name") else: value = option if value is not None and str(value).strip(): @@ -275,9 +321,9 @@ def _form_field_options(field: dict[str, typing.Any]) -> list[str]: def _form_field_default(field: dict[str, typing.Any]) -> typing.Any: - default = field.get("default") - if isinstance(default, dict) and default.get("type") == "constant": - return default.get("value") + default = _mapping_value(field, "default", "default_value", "defaultValue") + if isinstance(default, dict) and _protocol_name(_mapping_value(default, "type")) == "constant": + return _mapping_value(default, "value") return default @@ -313,10 +359,6 @@ def _form_step_descriptions( return descriptions, action_description -def _interaction_storage_key(interaction_id: str) -> str: - return f"{INTERACTION_STORAGE_PREFIX}{interaction_id}.json" - - class DefaultRunner(Runner): """Real Runner for Dify Service API. @@ -546,129 +588,17 @@ class DefaultRunner(Runner): return base_prompt return text - async def _store_interaction_continuation( - self, - ctx: RunnerContext, - continuation: dict[str, typing.Any], - ) -> None: - interaction_id = str(continuation["interaction_id"]) - continuation = dict(continuation, owner=self._continuation_owner(ctx)) - continuation.setdefault("expires_at", time.time() + 3600) - payload = json.dumps(continuation, ensure_ascii=False, separators=(",", ":")).encode("utf-8") - await self.get_run_api(ctx).set_plugin_storage(_interaction_storage_key(interaction_id), payload) - - async def _load_interaction_continuation( - self, - ctx: RunnerContext, - interaction_id: str, - ) -> dict[str, typing.Any]: - key = _interaction_storage_key(interaction_id) - try: - payload = await self.get_run_api(ctx).get_plugin_storage(key) - except (KeyError, ActionCallError) as exc: - if isinstance(exc, ActionCallError): - message = str(exc) - while message.startswith("ActionCallError: "): - message = message.removeprefix("ActionCallError: ") - if message != f"Storage with key {key} not found": - raise - raise DifyAPIError( - "The Dify human-input request is no longer pending", - code="dify.interaction_not_found", - ) from exc - continuation = json.loads(payload.decode("utf-8")) - if not isinstance(continuation, dict) or continuation.get("interaction_id") != interaction_id: - raise DifyAPIError( - "The Dify human-input continuation is invalid", - code="dify.interaction_invalid", - ) - if continuation.get("version") != 1: - raise DifyAPIError( - "The Dify human-input continuation version is unsupported", - code="dify.interaction_invalid", - ) - if continuation.get("consumed") or continuation.get("expires_at", 0) < time.time(): - raise DifyAPIError("Dify continuation expired or already consumed", code="dify.interaction_not_found") - owner = self._continuation_owner(ctx) - stored_owner = continuation.get("owner") - if stored_owner != owner: - if stored_owner != self._legacy_continuation_owner(ctx): - raise DifyAPIError("Dify continuation belongs to another context", code="dify.interaction_invalid") - # One-time migration: a continuation stored before identity resolution moved - # to task-local bindings is accepted and re-written with the current owner. - # No long-term dual-rule compatibility branch beyond this upgrade path. - continuation = dict(continuation, owner=owner) - return continuation - - def _continuation_subject(self, ctx): - conversation = ctx.conversation - return json.dumps( - [ - getattr(conversation, "conversation_id", None), - getattr(conversation, "launcher_type", None), - getattr(conversation, "launcher_id", None), - getattr(ctx.actor, "actor_id", None), - (ctx.config or {}).get("base-url"), - ], - separators=(",", ":"), - ) - - def _continuation_owner(self, ctx): - return scoped_identity(self, ctx, self._continuation_subject(ctx)) - - def _legacy_continuation_owner(self, ctx): - """Owner computed before identity resolution moved to task-local bindings. - - Used only to accept continuations persisted by the previous release so an - in-flight human-input request survives the upgrade; the record is re-written - with the current owner on the next store. - """ - binding = getattr(getattr(self, "_plugin_runtime_handler", None), "bound_action_context", None) - subject = self._continuation_subject(ctx) - if binding is not None: - scope = [binding.instance_uuid, binding.workspace_uuid, binding.installation_uuid] - else: - workspace = getattr(ctx.conversation, "workspace_id", None) - if not workspace: - return subject - scope = [workspace] - encoded = json.dumps([scope, subject], ensure_ascii=False, separators=(",", ":")).encode() - return "lb_" + hashlib.sha256(encoded).hexdigest() - - async def _delete_interaction_continuation(self, ctx: RunnerContext, interaction_id: str) -> None: - await self.get_run_api(ctx).delete_plugin_storage(_interaction_storage_key(interaction_id)) - @staticmethod def _request_from_continuation(continuation: dict[str, typing.Any]) -> InteractionRequest: fields = [InteractionField.model_validate(item) for item in continuation.get("current_fields") or []] actions = [InteractionAction.model_validate(item) for item in continuation.get("interaction_actions") or []] - if continuation.get("phase") == "field": + if fields: actions = [] kind = ( "confirmation" if actions and not fields else "choice" if fields and fields[0].type == "select" else "form" ) - if "field_descriptions" in continuation: - field_descriptions = ( - continuation.get("field_descriptions") - if isinstance(continuation.get("field_descriptions"), dict) - else {} - ) - description = ( - field_descriptions.get(fields[0].id) - if continuation.get("phase") == "field" and fields - else continuation.get("action_description") - ) - else: - description = continuation.get("description") + description = continuation.get("description") fallback_text = str(continuation.get("fallback_text") or "Human input is required.") - if fields: - field = fields[0] - field_lines = [str(continuation.get("title") or "Human input required"), field.label] - if description: - field_lines.insert(1, str(description)) - if field.options: - field_lines.append("Options: " + ", ".join(option.label for option in field.options)) - fallback_text = "\n".join(field_lines) return InteractionRequest( interaction_id=str(continuation["interaction_id"]), kind=kind, @@ -679,53 +609,13 @@ class DefaultRunner(Runner): fallback_text=fallback_text, ) - async def _advance_field_interaction( - self, - ctx: RunnerContext, - continuation: dict[str, typing.Any], - submission: typing.Any, - ) -> RunnerResult: - field_map = continuation.get("field_map") if isinstance(continuation.get("field_map"), dict) else {} - inputs = dict(continuation.get("default_inputs") or {}) - current_fields = [InteractionField.model_validate(item) for item in continuation.get("current_fields") or []] - for field_id, value in submission.values.items(): - provider_name = field_map.get(field_id) - if provider_name: - inputs[str(provider_name)] = value - for field in current_fields: - provider_name = field_map.get(field.id) - if field.required and provider_name and inputs.get(str(provider_name)) in (None, "", []): - raise DifyAPIError( - f"Dify human-input field is required: {field.label}", - code="dify.interaction_invalid", - ) - - old_interaction_id = str(continuation["interaction_id"]) - remaining_fields = list(continuation.get("remaining_fields") or []) - continuation = dict(continuation) - continuation["interaction_id"] = f"dify-{uuid.uuid4().hex}" - continuation["default_inputs"] = inputs - if remaining_fields: - continuation["phase"] = "field" - continuation["current_fields"] = [remaining_fields.pop(0)] - continuation["remaining_fields"] = remaining_fields - else: - continuation["phase"] = "action" - continuation["current_fields"] = [] - continuation["remaining_fields"] = [] - - request = self._request_from_continuation(continuation) - await self._store_interaction_continuation(ctx, continuation) - await self._delete_interaction_continuation(ctx, old_interaction_id) - return RunnerResult.interaction_requested(ctx.run_id, request) - def _build_interaction_request( self, reason: dict[str, typing.Any], workflow_run_id: str, user: str, ) -> tuple[InteractionRequest, dict[str, typing.Any]]: - form_token = str(reason.get("form_token") or "").strip() + form_token = str(_mapping_value(reason, "form_token", "formToken") or "").strip() if not form_token or not workflow_run_id: raise DifyAPIError( "Dify human-input event is missing continuation identifiers", @@ -735,9 +625,10 @@ class DefaultRunner(Runner): interaction_id = f"dify-{uuid.uuid4().hex}" fields: list[InteractionField] = [] field_map: dict[str, str] = {} - resolved_defaults = reason.get("resolved_default_values") + resolved_defaults = _mapping_value(reason, "resolved_default_values", "resolvedDefaultValues") default_inputs = dict(resolved_defaults) if isinstance(resolved_defaults, dict) else {} - raw_fields = reason.get("inputs") if isinstance(reason.get("inputs"), list) else [] + reason_inputs = _mapping_value(reason, "inputs", "fields") + raw_fields = reason_inputs if isinstance(reason_inputs, list) else [] for index, raw_field in enumerate(raw_fields): if not isinstance(raw_field, dict): continue @@ -746,7 +637,7 @@ class DefaultRunner(Runner): continue field_id = f"field_{index + 1}" field_map[field_id] = provider_name - provider_type = str(raw_field.get("type") or "text").lower() + provider_type = _protocol_name(_mapping_value(raw_field, "type") or "text") field_type = { "paragraph": "textarea", "textarea": "textarea", @@ -755,7 +646,7 @@ class DefaultRunner(Runner): "checkbox": "boolean", "boolean": "boolean", "file": "file", - "file-list": "file", + "file_list": "file", }.get(provider_type, "text") option_values = _form_field_options(raw_field) if field_type == "select" else [] if field_type == "select" and not option_values: @@ -766,22 +657,23 @@ class DefaultRunner(Runner): fields.append( InteractionField( id=field_id, - label=str(raw_field.get("label") or raw_field.get("title") or provider_name), + label=str(_mapping_value(raw_field, "label", "title") or provider_name), type=field_type, - required=bool(raw_field.get("required", True)), + required=_to_bool(_mapping_value(raw_field, "required", "is_required", "isRequired"), True), options=[InteractionOption(value=value, label=value) for value in option_values], - placeholder=raw_field.get("placeholder"), + placeholder=_mapping_value(raw_field, "placeholder"), default=default, ) ) actions: list[InteractionAction] = [] action_map: dict[str, str] = {} - raw_actions = reason.get("actions") if isinstance(reason.get("actions"), list) else [] + reason_actions = _mapping_value(reason, "actions", "user_actions", "userActions") + raw_actions = reason_actions if isinstance(reason_actions, list) else [] for index, raw_action in enumerate(raw_actions): if not isinstance(raw_action, dict): continue - provider_action_id = str(raw_action.get("id") or "").strip() + provider_action_id = str(_mapping_value(raw_action, "id", "action_id", "actionId") or "").strip() if not provider_action_id: continue action_id = f"action_{index + 1}" @@ -789,15 +681,15 @@ class DefaultRunner(Runner): actions.append( InteractionAction( id=action_id, - label=str(raw_action.get("title") or raw_action.get("label") or provider_action_id), + label=str(_mapping_value(raw_action, "title", "label", "text") or provider_action_id), ) ) if not actions: action_map["continue"] = "" actions.append(InteractionAction(id="continue", label="Continue", style="primary")) - node_title = str(reason.get("node_title") or "Human input required") - form_content = str(reason.get("form_content") or "") + node_title = str(_mapping_value(reason, "node_title", "nodeTitle", "title") or "Human input required") + form_content = str(_mapping_value(reason, "form_content", "formContent", "content") or "") provider_names = [field_map[field.id] for field in fields if field.id in field_map] provider_descriptions, action_description = _form_step_descriptions(form_content, provider_names) field_descriptions = { @@ -832,32 +724,47 @@ class DefaultRunner(Runner): "field_descriptions": field_descriptions, "action_description": action_description, "fallback_text": "\n".join(fallback_lines), - "phase": "field" if fields else "action", - "current_fields": [fields[0].model_dump(mode="json")] if fields else [], - "remaining_fields": [field.model_dump(mode="json") for field in fields[1:]], + "phase": "action", + "current_fields": [field.model_dump(mode="json") for field in fields], + "remaining_fields": [], "interaction_actions": [action.model_dump(mode="json") for action in actions], } + if fields and len(actions) > 1: + continuation["current_fields"].append( + InteractionField( + id="_dify_action", + label="Action", + type="select", + required=True, + options=[InteractionOption(value=action.id, label=action.label) for action in actions], + ).model_dump(mode="json") + ) request = self._request_from_continuation(continuation) return request, continuation - async def _interaction_result_for_pause( + async def _wait_and_resume_workflow( self, ctx: RunnerContext, + client: AsyncDifyClient, event: dict[str, typing.Any], user: str, - ) -> RunnerResult | None: - data = event.get("data") if isinstance(event.get("data"), dict) else {} - workflow_run_id = str(data.get("workflow_run_id") or "").strip() - reasons = data.get("reasons") if isinstance(data.get("reasons"), list) else [] - reason = next( - (item for item in reasons if isinstance(item, dict) and item.get("TYPE") == "human_input_required"), - None, - ) + remove_think: bool, + ) -> typing.AsyncGenerator[RunnerResult, None]: + reason = _human_input_reason(event) if reason is None: - return None - request, continuation = self._build_interaction_request(reason, workflow_run_id, user) - await self._store_interaction_continuation(ctx, continuation) - return RunnerResult.interaction_requested(ctx.run_id, request) + raise DifyAPIError("Dify paused without a supported human-input reason", code="dify.response_invalid") + request, continuation = self._build_interaction_request(reason, _workflow_run_id(event), user) + result = await ctx.request_interaction(request, timeout=3600, on_unsupported="degrade") + if result.status != "submitted" or result.submission is None: + raise DifyAPIError(f"Dify human input {result.status}", code="dify.interaction_expired") + async for item in self._resume_workflow_once( + ctx, + client, + result.submission, + remove_think, + continuation=continuation, + ): + yield item async def run(self, ctx: RunnerContext) -> typing.AsyncGenerator[RunnerResult, None]: """Run the Dify agent. @@ -886,21 +793,6 @@ class DefaultRunner(Runner): asset_registration = None try: - if ctx.event.event_type == "interaction.submitted": - if ctx.input.interaction is None: - raise DifyAPIError( - "interaction.submitted event is missing its validated submission", - code="dify.interaction_invalid", - ) - async for result in self._resume_workflow(ctx, client, ctx.input.interaction, remove_think): - yield result - return - if ctx.input.interaction is not None: - raise DifyAPIError( - "Interaction submission is only valid for interaction.submitted events", - code="dify.interaction_invalid", - ) - # Upload files if present. Multimodal inputs must not silently # degrade to text-only when the provider upload path fails. files = await self._upload_input_files(ctx, client, user) @@ -985,11 +877,11 @@ class DefaultRunner(Runner): "node_finished", "workflow_finished", "workflow_paused", + "human_input_required", }: mode = "workflow" if event_type == "workflow_started": - data = event.get("data") if isinstance(event.get("data"), dict) else {} - workflow_run_id = str(data.get("workflow_run_id") or workflow_run_id) + workflow_run_id = _workflow_run_id(event, workflow_run_id) if event_type == "error": raise DifyAPIError( @@ -1011,9 +903,10 @@ class DefaultRunner(Runner): has_response = True yield RunnerResult.message_delta(ctx.run_id, MessageChunk(role="assistant", content=content)) - elif mode == "workflow" and event_type == "workflow_paused": + elif mode == "workflow" and event_type in {"workflow_paused", "human_input_required"}: data = event.get("data") if isinstance(event.get("data"), dict) else {} - if workflow_run_id and not data.get("workflow_run_id"): + workflow_run_id = _workflow_run_id(event, workflow_run_id) + if workflow_run_id and not _workflow_run_id(event): event = dict(event) event["data"] = {**data, "workflow_run_id": workflow_run_id} if pending_content: @@ -1030,13 +923,8 @@ class DefaultRunner(Runner): final_conversation_id, scope="conversation", ) - interaction_result = await self._interaction_result_for_pause(ctx, event, user) - if interaction_result is None: - raise DifyAPIError( - "Dify paused the workflow without a supported reason", - code="dify.response_invalid", - ) - yield interaction_result + async for result in self._wait_and_resume_workflow(ctx, client, event, user, remove_think): + yield result return elif event_type == "message" or event_type == "agent_message": @@ -1224,8 +1112,7 @@ class DefaultRunner(Runner): usage = _usage_from_payload(event) or usage if event_type == "workflow_started": - data = event.get("data") if isinstance(event.get("data"), dict) else {} - workflow_run_id = str(data.get("workflow_run_id") or workflow_run_id) + workflow_run_id = _workflow_run_id(event, workflow_run_id) if event_type == "error": raise DifyAPIError( @@ -1267,9 +1154,10 @@ class DefaultRunner(Runner): MessageChunk(role="assistant", content=content, is_final=True), ) - elif event_type == "workflow_paused": + elif event_type in {"workflow_paused", "human_input_required"}: data = event.get("data") if isinstance(event.get("data"), dict) else {} - if workflow_run_id and not data.get("workflow_run_id"): + workflow_run_id = _workflow_run_id(event, workflow_run_id) + if workflow_run_id and not _workflow_run_id(event): event = dict(event) event["data"] = {**data, "workflow_run_id": workflow_run_id} if pending_content: @@ -1293,13 +1181,8 @@ class DefaultRunner(Runner): external_conv_id, scope="conversation", ) - interaction_result = await self._interaction_result_for_pause(ctx, event, user) - if interaction_result is None: - raise DifyAPIError( - "Dify paused the workflow without a supported reason", - code="dify.response_invalid", - ) - yield interaction_result + async for result in self._wait_and_resume_workflow(ctx, client, event, user, remove_think): + yield result return elif event_type == "workflow_finished": @@ -1348,41 +1231,14 @@ class DefaultRunner(Runner): yield RunnerResult.run_completed(ctx.run_id, usage=usage) - async def _resume_workflow(self, ctx, client, submission, remove_think): - active = getattr(self, "_active_resumes", None) - if active is None: - active = self._active_resumes = set() - from langbot_plugin.api.proxies.invocation import current_binding - - handler = getattr(self, "_plugin_runtime_handler", None) - # Same binding chain as scoped_identity, so the owner and the concurrency - # key can never disagree within one invocation. - binding = current_binding(handler) if handler is not None else None - if binding is None: - binding = getattr(handler, "bound_action_context", None) - key = (binding, self._continuation_owner(ctx), str(submission.interaction_id)) - if key in active: - raise DifyAPIError("Dify continuation is already being resumed", code="dify.interaction_invalid") - active.add(key) - try: - async with aclosing(self._resume_workflow_once(ctx, client, submission, remove_think)) as stream: - async for result in stream: - yield result - finally: - active.remove(key) - async def _resume_workflow_once( self, ctx: RunnerContext, client: AsyncDifyClient, submission: typing.Any, remove_think: bool, + continuation: dict[str, typing.Any], ) -> typing.AsyncGenerator[RunnerResult, None]: - interaction_id = str(submission.interaction_id) - continuation = await self._load_interaction_continuation(ctx, interaction_id) - if continuation.get("phase") == "field": - yield await self._advance_field_interaction(ctx, continuation, submission) - return field_map = continuation.get("field_map") if isinstance(continuation.get("field_map"), dict) else {} action_map = continuation.get("action_map") if isinstance(continuation.get("action_map"), dict) else {} inputs = dict(continuation.get("default_inputs") or {}) @@ -1390,20 +1246,20 @@ class DefaultRunner(Runner): provider_name = field_map.get(field_id) if provider_name: inputs[str(provider_name)] = value - action_id = submission.action_id or "" + action_id = submission.action_id or submission.values.get("_dify_action") or "" + if not action_id and len(action_map) == 1: + action_id = next(iter(action_map)) if action_id not in action_map: raise DifyAPIError( "Dify human-input action is missing or invalid", code="dify.interaction_invalid", ) action = action_map[action_id] - # Persist consumption BEFORE the external effect. An ambiguous failure - # remains consumed, never silently retries an approval at the vendor. - continuation["consumed"] = True - await self._store_interaction_continuation(ctx, continuation) - pending_content = "" + streamed_content = "" + text_event_count = 0 has_response = False + final_response = False terminal = False usage: dict[str, typing.Any] | None = None async for event in client.workflow_submit( @@ -1426,47 +1282,62 @@ class DefaultRunner(Runner): if event_type != "text_chunk" else str(event.get("data", {}).get("text") or "") ) - if len(pending_content) + len(chunk) > 1024 * 1024: + if event_type != "text_chunk" and pending_content and chunk.startswith(pending_content): + next_content = chunk + else: + next_content = pending_content + chunk + if len(next_content) > 1024 * 1024: raise DifyAPIError("Dify response exceeds the runtime limit", code="dify.response_limit") - pending_content += chunk + pending_content = next_content + text_event_count += 1 + if text_event_count % 8 == 0: + content, _ = process_thinking_content(pending_content, remove_think) + if content and content != streamed_content: + streamed_content = content + has_response = True + yield RunnerResult.message_delta( + ctx.run_id, + MessageChunk(role="assistant", content=content, is_final=False), + ) elif event_type == "node_finished": data = event.get("data", {}) if data.get("node_type") == "answer": answer = extract_text_from_output(data.get("outputs", {}).get("answer")) if answer: content, _ = process_thinking_content(answer, remove_think) - has_response = True - yield RunnerResult.message_delta( - ctx.run_id, - MessageChunk(role="assistant", content=content, is_final=True), - ) - elif event_type == "workflow_paused": + final_response = bool(content) + if content and content != streamed_content: + has_response = True + streamed_content = content + yield RunnerResult.message_delta( + ctx.run_id, + MessageChunk(role="assistant", content=content, is_final=True), + ) + elif event_type in {"workflow_paused", "human_input_required"}: if pending_content: content, _ = process_thinking_content(pending_content, remove_think) - if content: + if content and content != streamed_content: + has_response = True + streamed_content = content yield RunnerResult.message_delta( ctx.run_id, MessageChunk(role="assistant", content=content, is_final=True), ) data = event.get("data") if isinstance(event.get("data"), dict) else {} - if not data.get("workflow_run_id"): + if not _workflow_run_id(event): event = dict(event) event["data"] = { **data, "workflow_run_id": str(continuation["workflow_run_id"]), } - interaction_result = await self._interaction_result_for_pause( + async for result in self._wait_and_resume_workflow( ctx, + client, event, str(continuation["user"]), - ) - if interaction_result is None: - raise DifyAPIError( - "Dify paused the workflow without a supported reason", - code="dify.response_invalid", - ) - await self._delete_interaction_continuation(ctx, interaction_id) - yield interaction_result + remove_think, + ): + yield result return elif event_type == "workflow_finished": data = event.get("data", {}) @@ -1475,30 +1346,32 @@ class DefaultRunner(Runner): summary = extract_text_from_output(data.get("outputs", {}).get("summary", "")) if summary: content, _ = process_thinking_content(summary, remove_think) - has_response = True - yield RunnerResult.message_delta( - ctx.run_id, - MessageChunk(role="assistant", content=content, is_final=True), - ) + final_response = bool(content) + if content and content != streamed_content: + has_response = True + streamed_content = content + yield RunnerResult.message_delta( + ctx.run_id, + MessageChunk(role="assistant", content=content, is_final=True), + ) terminal = True - if pending_content and not has_response: - content, _ = process_thinking_content(pending_content, remove_think) - if content: - has_response = True - yield RunnerResult.message_delta( - ctx.run_id, - MessageChunk(role="assistant", content=content, is_final=True), - ) if not terminal: raise DifyAPIError( "Dify workflow resume ended before a terminal event", code="dify.response_invalid", ) + if pending_content and not final_response: + content, _ = process_thinking_content(pending_content, remove_think) + if content and content != streamed_content: + has_response = True + yield RunnerResult.message_delta( + ctx.run_id, + MessageChunk(role="assistant", content=content, is_final=True), + ) if not has_response: raise DifyAPIError( "Dify workflow returned no response after human input", code="dify.api_error", ) - await self._delete_interaction_continuation(ctx, interaction_id) yield RunnerResult.run_completed(ctx.run_id, usage=usage) diff --git a/plugins/Runner/dify-agent/pkg/dify_client.py b/plugins/Runner/dify-agent/pkg/dify_client.py index cff68b758..905db3f05 100644 --- a/plugins/Runner/dify-agent/pkg/dify_client.py +++ b/plugins/Runner/dify-agent/pkg/dify_client.py @@ -208,18 +208,25 @@ class AsyncDifyClient: timeout=self.timeout, trust_env=False, ) as client: - response = await limited_post( - client, + async with client.stream( + "POST", f"/form/human_input/{form_token}", - DifyAPIError, headers=headers, json={"inputs": inputs, "user": user, "action": action}, - ) - if not response.is_success: - raise DifyAPIError( - f"Dify API error: {response.status_code} - {response.text[:200]}", - code="dify.http_error", - ) + ) as response: + if not response.is_success: + body = await limited_body(response, DifyAPIError) + raise DifyAPIError( + f"Dify API error: {response.status_code} - {body.decode('utf-8', errors='replace')[:200]}", + code="dify.http_error", + ) + + content_type = response.headers.get("content-type", "").lower() + if content_type.split(";", 1)[0].strip() == "text/event-stream": + async for event in _iter_sse_json(response): + yield event + return + await limited_body(response, DifyAPIError) async with client.stream( "GET", diff --git a/plugins/Runner/dify-agent/pkg/http_limits.py b/plugins/Runner/dify-agent/pkg/http_limits.py index fb3984c37..670998262 100644 --- a/plugins/Runner/dify-agent/pkg/http_limits.py +++ b/plugins/Runner/dify-agent/pkg/http_limits.py @@ -13,7 +13,7 @@ MAX_STREAM_BYTES = 16 * 1024 * 1024 async def limited_bytes(response, error): total = 0 - async for chunk in response.aiter_bytes(chunk_size=8192): + async for chunk in response.aiter_bytes(): total += len(chunk) if total > MAX_STREAM_BYTES: raise error("Provider stream exceeds the runtime limit") diff --git a/plugins/Runner/dify-agent/readme/README_en_US.md b/plugins/Runner/dify-agent/readme/README_en_US.md index 4b62497fc..e471df244 100644 --- a/plugins/Runner/dify-agent/readme/README_en_US.md +++ b/plugins/Runner/dify-agent/readme/README_en_US.md @@ -38,8 +38,8 @@ Configuration is **static** and should not contain runtime state. Only the follo ## Workflow Human Input When Dify emits `workflow_paused` with a `human_input_required` reason, the -runner asks LangBot to deliver a structured interaction. A validated -`interaction.submitted` event resumes Dify through +runner asks LangBot to deliver a structured interaction and waits for the +validated submission in the same run. It resumes Dify through `/form/human_input/{form_token}` and `/workflow/{workflow_run_id}/events`. Workflows that pause again produce a new interaction and can be resumed again. Forms are emitted as atomic steps: the runner collects one field at a time and @@ -47,10 +47,9 @@ then emits the action buttons. This matches LangBot delivery adapters that support a single select or an action-only confirmation. Provider continuation data is not included in the interaction payload. The -runner stores `form_token`, `workflow_run_id`, the Dify user tag, and field/action -mappings in authorized plugin storage under a random LangBot `interaction_id`. -The continuation is deleted after a successful terminal event or after it is -replaced by a later pause. +runner keeps `form_token`, `workflow_run_id`, the Dify user tag, and field/action +mappings in the active run. Previously issued interactions can still resume +through their stored continuation records during migration. The selected Runner binding must allow interactions, and the delivery adapter must support the requested field/action shape. Adapters with a smaller diff --git a/plugins/Runner/dify-agent/requirements.txt b/plugins/Runner/dify-agent/requirements.txt index 0df2e86e1..8632daa79 100644 --- a/plugins/Runner/dify-agent/requirements.txt +++ b/plugins/Runner/dify-agent/requirements.txt @@ -1,3 +1,3 @@ -langbot-plugin>=0.7.4,<0.8 +langbot-plugin>=0.7.20,<0.8 pydantic>=2.0.0 httpx>=0.28.1 diff --git a/plugins/Runner/dify-agent/tests/test_missing_continuation.py b/plugins/Runner/dify-agent/tests/test_missing_continuation.py deleted file mode 100644 index 54e0dfdc2..000000000 --- a/plugins/Runner/dify-agent/tests/test_missing_continuation.py +++ /dev/null @@ -1,46 +0,0 @@ -import json -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest -from components.runner.default import DefaultRunner, _interaction_storage_key -from langbot_plugin.entities.io.errors import ActionCallError -from pkg.dify_client import DifyAPIError - - -@pytest.mark.asyncio -@pytest.mark.parametrize("prefix", ["", "ActionCallError: ", "ActionCallError: ActionCallError: "]) -async def test_missing_rpc_key(prefix): - key = _interaction_storage_key("missing") - api = SimpleNamespace( - get_plugin_storage=AsyncMock(side_effect=ActionCallError(prefix + f"Storage with key {key} not found")) - ) - runner = SimpleNamespace(get_run_api=lambda ctx: api) - with pytest.raises(DifyAPIError) as exc: - await DefaultRunner._load_interaction_continuation(runner, None, "missing") - assert exc.value.code == "dify.interaction_not_found" - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "error", - [ - ActionCallError("permission denied"), - ActionCallError("Storage with key other not found"), - TimeoutError("timeout"), - ], -) -async def test_other_errors_propagate(error): - runner = SimpleNamespace(get_run_api=lambda ctx: SimpleNamespace(get_plugin_storage=AsyncMock(side_effect=error))) - with pytest.raises(type(error)) as exc: - await DefaultRunner._load_interaction_continuation(runner, None, "missing") - assert exc.value is error - - -@pytest.mark.asyncio -async def test_corrupt_json_propagates(): - runner = SimpleNamespace( - get_run_api=lambda ctx: SimpleNamespace(get_plugin_storage=AsyncMock(return_value=b"broken")) - ) - with pytest.raises(json.JSONDecodeError): - await DefaultRunner._load_interaction_continuation(runner, None, "missing") diff --git a/plugins/Runner/dify-agent/tests/test_resume_streaming.py b/plugins/Runner/dify-agent/tests/test_resume_streaming.py new file mode 100644 index 000000000..dfcf9cc3a --- /dev/null +++ b/plugins/Runner/dify-agent/tests/test_resume_streaming.py @@ -0,0 +1,56 @@ +"""Streaming and deduplication after a blocking Dify form submission.""" + +from types import SimpleNamespace + +import pytest +from components.runner.default import DefaultRunner + + +async def _resume(events): + continuation = { + "phase": "submit", + "field_map": {}, + "action_map": {"approve": "approve"}, + "default_inputs": {}, + "form_token": "form", + "workflow_run_id": "workflow", + "user": "user", + } + runner = SimpleNamespace() + + class Client: + async def workflow_submit(self, **kwargs): + for event in events: + yield event + + submission = SimpleNamespace(interaction_id="interaction", action_id="approve", values={}) + result = [ + item + async for item in DefaultRunner._resume_workflow_once( + runner, SimpleNamespace(run_id="run"), Client(), submission, False, continuation + ) + ] + return [item.data["chunk"] for item in result if item.type == "message.delta"], result + + +@pytest.mark.asyncio +async def test_resume_emits_intermediate_snapshots_without_repeating_final_answer(): + events = [{"event": "text_chunk", "data": {"text": char}} for char in "abcdefghij"] + events += [ + {"event": "node_finished", "data": {"node_type": "answer", "outputs": {"answer": "abcdefghij"}}}, + {"event": "workflow_finished", "data": {"outputs": {"summary": "abcdefghij"}}}, + ] + chunks, results = await _resume(events) + assert [(chunk["content"], chunk["is_final"]) for chunk in chunks] == [ + ("abcdefgh", False), + ("abcdefghij", True), + ] + assert results[-1].type == "run.completed" + + +@pytest.mark.asyncio +async def test_resume_accepts_cumulative_message_snapshots(): + events = [{"event": "message", "answer": "abcdefgh"[:length]} for length in range(1, 9)] + events.append({"event": "workflow_finished", "data": {"outputs": {}}}) + chunks, _ = await _resume(events) + assert [chunk["content"] for chunk in chunks] == ["abcdefgh"] diff --git a/plugins/Runner/dify-agent/tests/test_scoped_identity.py b/plugins/Runner/dify-agent/tests/test_scoped_identity.py index ab31018ac..8424620d5 100644 --- a/plugins/Runner/dify-agent/tests/test_scoped_identity.py +++ b/plugins/Runner/dify-agent/tests/test_scoped_identity.py @@ -16,7 +16,6 @@ PLUGIN_ROOT = Path(__file__).resolve().parents[1] if str(PLUGIN_ROOT) not in sys.path: sys.path.insert(0, str(PLUGIN_ROOT)) -from components.runner.default import DefaultRunner, DifyAPIError # noqa: E402 from pkg.scoped_identity import scoped_identity # noqa: E402 @@ -62,7 +61,6 @@ def test_identity_is_stable_for_the_same_binding(): return scoped_identity(_runner(handler), _ctx(), "local-1") assert compute(1) == compute(1) - # Only the installation scope matters: a worker upgrade must not rename upstream state. assert compute(1) == compute(7) @@ -95,97 +93,3 @@ def test_dedicated_falls_back_to_workspace_then_legacy_local_id(monkeypatch): assert scoped.startswith("lb_") assert scoped != scoped_identity(_runner(handler), _ctx(workspace_id="workspace-2"), "local-1") assert scoped_identity(_runner(handler), _ctx(), "local-1") == "local-1" - - -# --- Dify continuation owner ------------------------------------------------- - - -def _dify_context(): - return SimpleNamespace( - conversation=SimpleNamespace( - conversation_id="conversation-1", - launcher_type="group", - launcher_id="launcher-1", - workspace_id=None, - ), - actor=SimpleNamespace(actor_id="actor-1"), - config={"base-url": "https://dify.invalid"}, - ) - - -def _dify_runner(handler): - runner = object.__new__(DefaultRunner) - runner._plugin_runtime_handler = handler - return runner - - -def _legacy_owner(binding: InstallationBinding, subject: str) -> str: - scope = [binding.instance_uuid, binding.workspace_uuid, binding.installation_uuid] - encoded = json.dumps([scope, subject], ensure_ascii=False, separators=(",", ":")).encode() - return "lb_" + hashlib.sha256(encoded).hexdigest() - - -class _StorageAPI: - def __init__(self, payload: bytes): - self._payload = payload - - async def get_plugin_storage(self, key: str) -> bytes: - return self._payload - - -def _continuation_payload(owner: str) -> bytes: - return json.dumps( - { - "interaction_id": "interaction-1", - "version": 1, - "owner": owner, - "expires_at": 4_000_000_000, - } - ).encode("utf-8") - - -@pytest.mark.asyncio -async def test_resume_concurrency_key_uses_the_same_owner_and_binding(): - ctx = _dify_context() - handler = SimpleNamespace() - runner = _dify_runner(handler) - binding = _binding("installation-a") - with bind_invocation(handler, binding=binding): - owner = runner._continuation_owner(ctx) - assert owner == _expected(binding, runner._continuation_subject(ctx)) - # Pre-seeding the exact key proves _resume_workflow derives it from the same - # invocation binding and owner rather than a different scope. - runner._active_resumes = {(binding, owner, "interaction-1")} - stream = runner._resume_workflow( - ctx, - client=None, - submission=SimpleNamespace(interaction_id="interaction-1"), - remove_think=False, - ) - with pytest.raises(DifyAPIError): - await stream.__anext__() - - -@pytest.mark.asyncio -async def test_legacy_owner_is_accepted_and_migrated(): - ctx = _dify_context() - legacy_binding = _binding("installation-legacy") - handler = SimpleNamespace(bound_action_context=legacy_binding) - runner = _dify_runner(handler) - subject = runner._continuation_subject(ctx) - runner.get_run_api = lambda _ctx: _StorageAPI(_continuation_payload(_legacy_owner(legacy_binding, subject))) - binding = _binding("installation-current") - with bind_invocation(handler, binding=binding): - current_owner = runner._continuation_owner(ctx) - assert current_owner != _legacy_owner(legacy_binding, subject) - continuation = await runner._load_interaction_continuation(ctx, "interaction-1") - assert continuation["owner"] == current_owner - - -@pytest.mark.asyncio -async def test_foreign_owner_is_rejected(): - ctx = _dify_context() - runner = _dify_runner(SimpleNamespace()) - runner.get_run_api = lambda _ctx: _StorageAPI(_continuation_payload("lb_" + "0" * 64)) - with pytest.raises(DifyAPIError): - await runner._load_interaction_continuation(ctx, "interaction-1") diff --git a/plugins/Runner/http-certification-tests/test_dify_continuation_parity.py b/plugins/Runner/http-certification-tests/test_dify_continuation_parity.py deleted file mode 100644 index a007c7f96..000000000 --- a/plugins/Runner/http-certification-tests/test_dify_continuation_parity.py +++ /dev/null @@ -1,182 +0,0 @@ -"""Continuation feature parity with owner-bound, expiring new-format records.""" - -import asyncio -import json -import os -import sys -from pathlib import Path -from typing import Any - -from langbot_plugin.api.entities.builtin.runner import InteractionSubmission - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from tests.test_traditional_runner_protocol_fixes import ( - _collect_async, - _ctx, - _FakePluginStorage, - _load_runner_module, - _type, -) - -if os.environ.get("HTTP_RUNNER_SOURCE_ROOT"): - _load_runner_module.__globals__["ROOT"] = Path(os.environ["HTTP_RUNNER_SOURCE_ROOT"]) - - -def test_dify_interaction_resume_submits_mapped_values_and_clears_continuation() -> None: - module = _load_runner_module("dify-agent") - runner = object.__new__(module.DefaultRunner) - storage = _FakePluginStorage() - runner.get_run_api = lambda ctx: storage - interaction_id = "dify-test" - storage_key = module._interaction_storage_key(interaction_id) - storage.values[storage_key] = json.dumps( - { - "version": 1, - "interaction_id": interaction_id, - "form_token": "form-private", - "workflow_run_id": "workflow-private", - "user": "user_1", - "field_map": {"field_1": "priority"}, - "action_map": {"action_1": "approve-private"}, - "default_inputs": {"comment": "default"}, - } - ).encode() - captured: dict[str, Any] = {} - - class FakeClient: - async def workflow_submit(self, **kwargs): - captured.update(kwargs) - yield { - "event": "workflow_finished", - "data": {"error": None, "outputs": {"summary": "Approved"}}, - } - - submission = InteractionSubmission( - interaction_id=interaction_id, - action_id="action_1", - values={"field_1": "high"}, - ) - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) - ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), FakeClient(), submission, False))) - - assert captured == { - "form_token": "form-private", - "workflow_run_id": "workflow-private", - "inputs": {"comment": "default", "priority": "high"}, - "user": "user_1", - "action": "approve-private", - } - assert [_type(result) for result in results] == ["message.delta", "run.completed"] - assert storage_key in storage.deleted - assert storage_key not in storage.values - - -def test_dify_field_submission_advances_to_action_without_calling_provider() -> None: - module = _load_runner_module("dify-agent") - runner = object.__new__(module.DefaultRunner) - storage = _FakePluginStorage() - runner.get_run_api = lambda ctx: storage - interaction_id = "dify-field" - storage.values[module._interaction_storage_key(interaction_id)] = json.dumps( - { - "version": 1, - "interaction_id": interaction_id, - "form_token": "form-private", - "workflow_run_id": "workflow-private", - "user": "user_1", - "field_map": {"field_1": "priority"}, - "action_map": {"action_1": "approve-private"}, - "default_inputs": {}, - "title": "Manual review", - "description": "Review it", - "fallback_text": "Review it", - "phase": "field", - "current_fields": [ - { - "id": "field_1", - "label": "Priority", - "type": "select", - "required": True, - "options": [{"value": "high", "label": "High"}], - } - ], - "remaining_fields": [], - "interaction_actions": [{"id": "action_1", "label": "Approve", "style": "primary"}], - } - ).encode() - - class ProviderMustNotRun: - def workflow_submit(self, **kwargs): - raise AssertionError("provider must not resume before the action step") - - submission = InteractionSubmission(interaction_id=interaction_id, values={"field_1": "high"}) - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) - ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), ProviderMustNotRun(), submission, False))) - - assert [_type(result) for result in results] == ["action.requested"] - request = results[0].data["payload"] - assert request["fields"] == [] - assert request["actions"][0]["label"] == "Approve" - continuation = json.loads(storage.values[module._interaction_storage_key(request["interaction_id"])]) - assert continuation["default_inputs"] == {"priority": "high"} - - -def test_dify_interaction_resume_can_pause_again() -> None: - module = _load_runner_module("dify-agent") - runner = object.__new__(module.DefaultRunner) - storage = _FakePluginStorage() - runner.get_run_api = lambda ctx: storage - interaction_id = "dify-first" - old_key = module._interaction_storage_key(interaction_id) - storage.values[old_key] = json.dumps( - { - "version": 1, - "interaction_id": interaction_id, - "form_token": "form-1", - "workflow_run_id": "workflow-1", - "user": "user_1", - "field_map": {}, - "action_map": {"continue": ""}, - "default_inputs": {}, - } - ).encode() - - class FakeClient: - async def workflow_submit(self, **kwargs): - yield { - "event": "workflow_paused", - "data": { - "workflow_run_id": "workflow-2", - "reasons": [ - { - "TYPE": "human_input_required", - "form_token": "form-2", - "node_title": "Second review", - "inputs": [], - "actions": [{"id": "done", "title": "Done"}], - } - ], - }, - } - - submission = InteractionSubmission(interaction_id=interaction_id, action_id="continue") - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) - ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), FakeClient(), submission, False))) - - assert [_type(result) for result in results] == ["action.requested"] - new_interaction_id = results[0].data["payload"]["interaction_id"] - assert new_interaction_id != interaction_id - assert old_key in storage.deleted - assert module._interaction_storage_key(new_interaction_id) in storage.values diff --git a/plugins/Runner/http-certification-tests/test_http_lifecycle.py b/plugins/Runner/http-certification-tests/test_http_lifecycle.py index f2908b0da..2a9d96922 100644 --- a/plugins/Runner/http-certification-tests/test_http_lifecycle.py +++ b/plugins/Runner/http-certification-tests/test_http_lifecycle.py @@ -116,73 +116,6 @@ def test_total_deadline_includes_trickle_stream(name, monkeypatch): asyncio.run(run()) -def test_dify_continuation_rejects_cross_conversation(): - with load("dify") as (m, runner): - - async def run(): - data = {} - - async def put(k, v): - data[k] = v - - async def get(k): - return data[k] - - runner.get_run_api = lambda ctx: SimpleNamespace(set_plugin_storage=put, get_plugin_storage=get) - a = context() - b = context() - b.conversation.conversation_id = "other" - await runner._store_interaction_continuation(a, {"interaction_id": "i", "version": 1}) - with pytest.raises(m.DifyAPIError): - await runner._load_interaction_continuation(b, "i") - - asyncio.run(run()) - - -def test_dify_failed_resume_is_not_replayed(): - with load("dify") as (m, runner): - - async def run(): - data = {} - calls = [] - - async def put(k, v): - data[k] = v - - async def get(k): - return data[k] - - runner.get_run_api = lambda ctx: SimpleNamespace(set_plugin_storage=put, get_plugin_storage=get) - - class Client: - async def workflow_submit(self, **kwargs): - calls.append(kwargs) - raise ConnectionError("ambiguous remote failure") - yield - - ctx = context() - await runner._store_interaction_continuation( - ctx, - { - "interaction_id": "i", - "version": 1, - "phase": "action", - "action_map": {"yes": "approve"}, - "form_token": "fixture", - "workflow_run_id": "w", - "user": "u", - }, - ) - submission = SimpleNamespace(interaction_id="i", values={}, action_id="yes") - for _ in range(2): - with pytest.raises((ConnectionError, m.DifyAPIError)): - async for _ in runner._resume_workflow(ctx, Client(), submission, False): - pass - assert len(calls) == 1 - - asyncio.run(run()) - - @pytest.mark.parametrize("name", GATEWAYS) def test_same_installation_gateway_overlap_keeps_other_token_alive(name): async def run(runner): diff --git a/plugins/Runner/http-certification-tests/test_isolation.py b/plugins/Runner/http-certification-tests/test_isolation.py index f3b0926ac..e4cd12fda 100644 --- a/plugins/Runner/http-certification-tests/test_isolation.py +++ b/plugins/Runner/http-certification-tests/test_isolation.py @@ -171,16 +171,3 @@ def test_gateway_overlap_has_independent_timeout_and_tokens(name): with load(name) as (_, runner): with gateway_invocation(runner): asyncio.run(run(runner)) - - -def test_dify_storage_transport_failure_not_misreported_absent(): - async def run(module, runner): - async def broken(key): - raise PermissionError("fixture denial") - - runner.get_run_api = lambda ctx: SimpleNamespace(get_plugin_storage=broken) - with pytest.raises(PermissionError): - await runner._load_interaction_continuation(context(), "id") - - with load("dify") as (m, runner): - asyncio.run(run(m, runner)) diff --git a/plugins/Runner/pyproject.toml b/plugins/Runner/pyproject.toml index 7a3eb22ca..d8feed774 100644 --- a/plugins/Runner/pyproject.toml +++ b/plugins/Runner/pyproject.toml @@ -9,7 +9,7 @@ authors = [{ name = "LangBot Team" }] keywords = ["langbot", "agent", "runner", "plugin"] dependencies = [ - "langbot-plugin==0.7.4", + "langbot-plugin==0.7.20", "pydantic>=2.0.0", ] diff --git a/plugins/Runner/tests/test_plugin_layout.py b/plugins/Runner/tests/test_plugin_layout.py index ea2bc0d95..2ee3945ef 100644 --- a/plugins/Runner/tests/test_plugin_layout.py +++ b/plugins/Runner/tests/test_plugin_layout.py @@ -852,12 +852,20 @@ def _write_fake_codex_app_server(path: Path) -> None: " method = request.get('method')", " request_id = request.get('id')", " params = request.get('params') or {}", + " if request_id == 700 and method is None:", + " answer = (request.get('result') or {}).get('contentItems') or []", + " send({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'threadId': thread_id, 'item': {'id': 'answer-result', 'type': 'agentMessage', 'text': 'USER_ANSWER:' + str(answer), 'phase': 'final_answer'}}})", + " send({'jsonrpc': '2.0', 'method': 'turn/completed', 'params': {'threadId': thread_id, 'turn': {'id': 'turn-1', 'status': 'completed'}}})", + " continue", " if request_id == 701 and method is None and pending_approval_prompt:", " decision = (request.get('result') or {}).get('decision')", " if decision == 'accept':", " send({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'threadId': thread_id, 'item': {'id': 'command-1', 'type': 'commandExecution', 'command': 'Write approval-probe.txt', 'cwd': '.', 'commandActions': [], 'status': 'completed', 'aggregatedOutput': 'created'}}})", " send({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'threadId': thread_id, 'item': {'id': 'approval-result', 'type': 'agentMessage', 'text': 'APPROVAL_EXECUTED', 'phase': 'final_answer'}}})", " send({'jsonrpc': '2.0', 'method': 'turn/completed', 'params': {'threadId': thread_id, 'turn': {'id': 'turn-approval', 'status': 'completed'}}})", + " else:", + " send({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'threadId': thread_id, 'item': {'id': 'rejection-result', 'type': 'agentMessage', 'text': 'APPROVAL_REJECTED', 'phase': 'final_answer'}}})", + " send({'jsonrpc': '2.0', 'method': 'turn/completed', 'params': {'threadId': thread_id, 'turn': {'id': 'turn-approval', 'status': 'completed'}}})", " pending_approval_prompt = ''", " continue", " if request_id is not None and method == 'initialize':", @@ -1105,11 +1113,10 @@ def test_claude_code_runner_non_streaming_emits_one_message(tmp_path: Path) -> N assert "message" not in results[2].data -def test_claude_code_runner_pauses_for_question_and_resumes_with_tool_result(tmp_path: Path) -> None: +def test_claude_code_runner_rejects_builtin_question_tool(tmp_path: Path) -> None: fake_cli = tmp_path / "fake_native_cli.py" _write_fake_native_cli(fake_cli) module = _load_runner_module("claude-code-agent") - native = sys.modules["pkg.native_cli"] runner = object.__new__(module.DefaultRunner) runner.get_plugin_config = lambda: {} runner.get_run_api = lambda ctx: None @@ -1121,45 +1128,9 @@ def test_claude_code_runner_pauses_for_question_and_resumes_with_tool_result(tmp "langbot-assets-enabled": False, } - paused = asyncio.run(_collect_async(runner.run(_native_ctx(config, text="ASK_INTERACTION")))) - - assert [item.type for item in paused] == ["state.updated", "state.updated", "action.requested"] - pending = paused[1].data["value"] - request = paused[2].data["payload"] - assert paused[2].data["action"] == "interaction.requested" - assert request["fields"][0]["type"] == "select" - assert request["fields"][0]["label"] == "Choose an environment" - - resumed = asyncio.run( - _collect_async( - runner.run( - _native_ctx( - config, - conversation_state={ - native.SESSION_STATE_KEY: "fake-session", - native.PENDING_INTERACTION_STATE_KEY: pending, - }, - interaction=InteractionSubmission( - interaction_id=request["interaction_id"], - action_id="submit", - values={"environment": "staging"}, - ), - ) - ) - ) - ) - - assert resumed[0].data == { - "key": native.PENDING_INTERACTION_STATE_KEY, - "value": None, - "scope": "conversation", - } - assert resumed[-1].type == "run.completed" - message_text = "".join( - str(item.data.get("chunk", {}).get("content") or "") for item in resumed if item.type == "message.delta" - ) - assert "authoritative response" in message_text - assert '"answer": "staging"' in message_text + results = asyncio.run(_collect_async(runner.run(_native_ctx(config, text="ASK_INTERACTION")))) + assert [item.type for item in results] == ["state.updated", "run.failed"] + assert results[-1].data["code"] == "claude_code.interaction_invalid" def test_codex_runner_executes_fake_native_cli(tmp_path: Path) -> None: @@ -1238,11 +1209,27 @@ def test_codex_runner_defaults_to_non_interactive_full_access(tmp_path: Path) -> assert config["sandbox_mode"] == "danger-full-access" -def test_codex_runner_pauses_for_dynamic_question_and_resumes_thread(tmp_path: Path) -> None: +def _interaction_context(config, text, *, action_id=None, values=None): + ctx = _native_ctx(config, text=text) + + async def request_interaction(request, **kwargs): + return types.SimpleNamespace( + status="submitted", + submission=InteractionSubmission( + interaction_id=request.interaction_id, + action_id=action_id, + values=values or {}, + ), + ) + + ctx._api = types.SimpleNamespace(request_interaction=request_interaction) + return ctx + + +def test_codex_runner_answers_dynamic_question_in_live_turn(tmp_path: Path) -> None: fake_cli = tmp_path / "fake_codex_app_server.py" _write_fake_codex_app_server(fake_cli) module = _load_runner_module("codex-agent") - native = sys.modules["pkg.native_cli"] runner = object.__new__(module.DefaultRunner) runner.get_plugin_config = lambda: {} runner.get_run_api = lambda ctx: None @@ -1255,37 +1242,20 @@ def test_codex_runner_pauses_for_dynamic_question_and_resumes_thread(tmp_path: P "sandbox-mode": "read-only", } - paused = asyncio.run(_collect_async(runner.run(_native_ctx(config, text="ASK_INTERACTION")))) - - assert [item.type for item in paused] == ["state.updated", "state.updated", "action.requested"] - pending = paused[1].data["value"] - request = paused[2].data["payload"] - assert paused[2].data["action"] == "interaction.requested" - assert request["fields"][0]["type"] == "select" - assert pending["provider_call_id"] == "call-question-1" - resumed = asyncio.run( _collect_async( runner.run( - _native_ctx( + _interaction_context( config, - conversation_state={ - native.SESSION_STATE_KEY: "thread-123", - native.PENDING_INTERACTION_STATE_KEY: pending, - }, - interaction=InteractionSubmission( - interaction_id=request["interaction_id"], - action_id="submit", - values={"environment": "production"}, - ), + "ASK_INTERACTION", + values={"environment": "production"}, ) ) ) ) - assert resumed[0].data["key"] == native.PENDING_INTERACTION_STATE_KEY - assert resumed[0].data["value"] is None assert resumed[-1].type == "run.completed" + assert not any(item.type == "action.requested" for item in resumed) assert any( "production" in str(item.data.get("chunk", {}).get("content") or "") for item in resumed @@ -1293,11 +1263,10 @@ def test_codex_runner_pauses_for_dynamic_question_and_resumes_thread(tmp_path: P ) -def test_codex_runner_pauses_for_native_approval_and_approves_exact_retry(tmp_path: Path) -> None: +def test_codex_runner_approves_native_request_in_live_turn(tmp_path: Path) -> None: fake_cli = tmp_path / "fake_codex_app_server.py" _write_fake_codex_app_server(fake_cli) module = _load_runner_module("codex-agent") - native = sys.modules["pkg.native_cli"] runner = object.__new__(module.DefaultRunner) runner.get_plugin_config = lambda: {} runner.get_run_api = lambda ctx: None @@ -1310,39 +1279,20 @@ def test_codex_runner_pauses_for_native_approval_and_approves_exact_retry(tmp_pa "sandbox-mode": "read-only", } - paused = asyncio.run(_collect_async(runner.run(_native_ctx(config, text="TRIGGER_COMMAND_APPROVAL")))) - - assert [item.type for item in paused] == ["state.updated", "state.updated", "action.requested"] - pending = paused[1].data["value"] - request = paused[2].data["payload"] - assert pending["kind"] == "approval" - assert pending["approval_category"] == "command" - assert request["kind"] == "confirmation" - assert request["fields"] == [] - assert [action["id"] for action in request["actions"]] == ["approve_once", "reject"] - assert "Write approval-probe.txt" in request["description"] - resumed = asyncio.run( _collect_async( runner.run( - _native_ctx( + _interaction_context( config, - conversation_state={ - native.SESSION_STATE_KEY: "thread-123", - native.PENDING_INTERACTION_STATE_KEY: pending, - }, - interaction=InteractionSubmission( - interaction_id=request["interaction_id"], - action_id="approve_once", - ), + "TRIGGER_COMMAND_APPROVAL", + action_id="approve_once", ) ) ) ) - assert resumed[0].data["key"] == native.PENDING_INTERACTION_STATE_KEY - assert resumed[0].data["value"] is None assert resumed[-1].type == "run.completed" + assert not any(item.type == "action.requested" for item in resumed) assert any( "APPROVAL_EXECUTED" in str(item.data.get("chunk", {}).get("content") or "") for item in resumed @@ -1350,11 +1300,10 @@ def test_codex_runner_pauses_for_native_approval_and_approves_exact_retry(tmp_pa ) -def test_codex_runner_resumes_after_native_approval_rejection(tmp_path: Path) -> None: +def test_codex_runner_rejects_native_request_in_live_turn(tmp_path: Path) -> None: fake_cli = tmp_path / "fake_codex_app_server.py" _write_fake_codex_app_server(fake_cli) module = _load_runner_module("codex-agent") - native = sys.modules["pkg.native_cli"] runner = object.__new__(module.DefaultRunner) runner.get_plugin_config = lambda: {} runner.get_run_api = lambda ctx: None @@ -1366,23 +1315,13 @@ def test_codex_runner_resumes_after_native_approval_rejection(tmp_path: Path) -> "approval-policy": "on-request", "sandbox-mode": "read-only", } - paused = asyncio.run(_collect_async(runner.run(_native_ctx(config, text="TRIGGER_COMMAND_APPROVAL")))) - pending = paused[1].data["value"] - request = paused[2].data["payload"] - resumed = asyncio.run( _collect_async( runner.run( - _native_ctx( + _interaction_context( config, - conversation_state={ - native.SESSION_STATE_KEY: "thread-123", - native.PENDING_INTERACTION_STATE_KEY: pending, - }, - interaction=InteractionSubmission( - interaction_id=request["interaction_id"], - action_id="reject", - ), + "TRIGGER_COMMAND_APPROVAL", + action_id="reject", ) ) ) @@ -1582,12 +1521,11 @@ def test_codex_app_server_auto_approves_legacy_request_when_policy_is_never() -> "params": {"command": "touch probe.txt", "cwd": "/workspace"}, } ) - return json.loads(stdin.data.decode("utf-8")), client.interaction_request + return json.loads(stdin.data.decode("utf-8")) - response, interaction_request = asyncio.run(approve()) + response = asyncio.run(approve()) assert response == {"jsonrpc": "2.0", "id": 42, "result": {"decision": "accept"}} - assert interaction_request is None def test_codex_local_home_is_unique_per_resumed_run(tmp_path: Path) -> None: diff --git a/plugins/Runner/tests/test_steering.py b/plugins/Runner/tests/test_steering.py index d1c73422f..bfff79fef 100644 --- a/plugins/Runner/tests/test_steering.py +++ b/plugins/Runner/tests/test_steering.py @@ -218,7 +218,7 @@ def test_steering_loop_stops_on_action_request_without_completing() -> None: ) yield RunnerResult.action_requested( "run_steering", - "interaction.requested", + "test.action", {"interaction_id": "question-1"}, ) diff --git a/plugins/Runner/tests/test_traditional_runner_protocol_fixes.py b/plugins/Runner/tests/test_traditional_runner_protocol_fixes.py index eb5f6d6e0..0d6730f01 100644 --- a/plugins/Runner/tests/test_traditional_runner_protocol_fixes.py +++ b/plugins/Runner/tests/test_traditional_runner_protocol_fixes.py @@ -21,6 +21,7 @@ from langbot_plugin.api.entities.builtin.runner import ( AgentTrigger, ConversationContext, DeliveryContext, + InteractionResult, InteractionSubmission, RunnerContext, ) @@ -92,6 +93,25 @@ def _ctx( ) +def _dify_interaction_ctx(): + ctx = _ctx() + requests = [] + + async def request_interaction(request, **kwargs): + requests.append(request) + return InteractionResult( + status="submitted", + submission=InteractionSubmission( + interaction_id=request.interaction_id, + action_id=request.actions[0].id if request.actions else None, + values={field.id: ("action_1" if field.id == "_dify_action" else "high") for field in request.fields}, + ), + ) + + ctx._api = types.SimpleNamespace(request_interaction=request_interaction) + return ctx, requests + + def _text_and_image_ctx(config: dict[str, Any]) -> RunnerContext: return _ctx( config=config, @@ -231,46 +251,122 @@ def test_dify_workflow_pause_requests_host_interaction_and_hides_provider_tokens }, } - results = asyncio.run(_collect_async(runner._run_workflow(_ctx(), FakeClient(), {}, "hello", "user_1", [], False))) + async def workflow_submit(self, **kwargs): + assert kwargs["form_token"] == "form-private" + assert kwargs["workflow_run_id"] == "workflow-private" + assert kwargs["inputs"]["priority"] == "high" + assert kwargs["action"] == "approve-private" + yield {"event": "node_finished", "data": {"node_type": "answer", "outputs": {"answer": "Approved"}}} + yield {"event": "workflow_finished", "data": {"outputs": {}}} + + ctx, requests = _dify_interaction_ctx() + results = asyncio.run(_collect_async(runner._run_workflow(ctx, FakeClient(), {}, "hello", "user_1", [], False))) - interaction_result = results[-1] assert _type(results[0]) == "tool.call.started" assert results[0].data["tool_name"] == "Manual review" - assert all(_type(result) != "message.delta" for result in results) - assert _type(interaction_result) == "action.requested" - assert interaction_result.data["action"] == "interaction.requested" - request = interaction_result.data["payload"] - assert request["fields"][0]["options"][0]["value"] == "high" - assert request["actions"] == [] - assert "form-private" not in str(request) - assert "workflow-private" not in str(request) - assert len(storage.values) == 1 - continuation = json.loads(next(iter(storage.values.values()))) - assert continuation["form_token"] == "form-private" - assert continuation["workflow_run_id"] == "workflow-private" - assert continuation["interaction_actions"][0]["label"] == "Approve" - assert all(_type(result) != "run.completed" for result in results) + assert requests[0].fields[0].options[0].value == "high" + assert len(requests) == 1 + assert requests[0].actions == [] + assert "form-private" not in str(requests) + assert "workflow-private" not in str(requests) + assert storage.values == {} + assert _type(results[-1]) == "run.completed" -def test_dify_interaction_resume_submits_mapped_values_and_clears_continuation() -> None: +def test_dify_current_human_input_event_requests_host_interaction() -> None: module = _load_runner_module("dify-agent") runner = object.__new__(module.DefaultRunner) storage = _FakePluginStorage() runner.get_run_api = lambda ctx: storage + + class FakeClient: + async def workflow_run(self, *, inputs, user, files): + yield { + "event": "human_input_required", + "workflow_run_id": "workflow-private", + "data": { + "form_token": "form-private", + "node_title": "Manual review", + "form_content": "Choose a priority\n{{#$output.priority#}}", + "inputs": [ + { + "output_variable_name": "priority", + "type": "select", + "option_source": {"type": "constant", "value": ["high", "low"]}, + } + ], + "actions": [{"id": "approve-private", "title": "Approve"}], + }, + } + + async def workflow_submit(self, **kwargs): + assert kwargs["inputs"]["priority"] == "high" + yield {"event": "node_finished", "data": {"node_type": "answer", "outputs": {"answer": "Approved"}}} + yield {"event": "workflow_finished", "data": {"outputs": {}}} + + ctx, requests = _dify_interaction_ctx() + results = asyncio.run(_collect_async(runner._run_workflow(ctx, FakeClient(), {}, "hello", "user_1", [], False))) + + assert _type(results[-1]) == "run.completed" + assert requests[0].title == "Manual review" + assert requests[0].fields[0].options[0].value == "high" + assert "form-private" not in str(requests) + assert "workflow-private" not in str(requests) + assert storage.values == {} + + +def test_dify_pause_accepts_single_reason_and_camel_case_fields() -> None: + module = _load_runner_module("dify-agent") + runner = object.__new__(module.DefaultRunner) + storage = _FakePluginStorage() + runner.get_run_api = lambda ctx: storage + event = { + "event": "workflow_paused", + "data": { + "workflowRunId": "workflow-private", + "reason": { + "type": "human-input-required", + "formToken": "form-private", + "nodeTitle": "Manual review", + "formContent": "Choose a priority\n{{#$output.priority#}}", + "resolvedDefaultValues": {"priority": "low"}, + "fields": [ + { + "outputVariableName": "priority", + "type": "select", + "optionSource": {"type": "constant", "value": [{"label": "High", "value": "high"}]}, + } + ], + "userActions": [{"actionId": "approve-private", "label": "Approve"}], + }, + }, + } + + request, continuation = runner._build_interaction_request(event["data"]["reason"], "workflow-private", "user_1") + + assert request.title == "Manual review" + assert request.fields[0].default == "low" + assert request.fields[0].options[0].value == "high" + assert request.fields[0].options[0].label == "high" + assert continuation["action_map"] == {"action_1": "approve-private"} + assert "form-private" not in str(request) + assert "workflow-private" not in str(request) + assert storage.values == {} + + +def test_dify_interaction_resume_submits_mapped_values_in_same_run() -> None: + module = _load_runner_module("dify-agent") + runner = object.__new__(module.DefaultRunner) interaction_id = "dify-test" - storage_key = module._interaction_storage_key(interaction_id) - storage.values[storage_key] = json.dumps( - { - "version": 1, - "interaction_id": interaction_id, - "form_token": "form-private", - "workflow_run_id": "workflow-private", - "user": "user_1", - "field_map": {"field_1": "priority"}, - "action_map": {"action_1": "approve-private"}, - "default_inputs": {"comment": "default"}, - } - ).encode() + continuation = { + "interaction_id": interaction_id, + "form_token": "form-private", + "workflow_run_id": "workflow-private", + "user": "user_1", + "field_map": {"field_1": "priority"}, + "action_map": {"action_1": "approve-private"}, + "default_inputs": {"comment": "default"}, + } captured: dict[str, Any] = {} class FakeClient: @@ -286,13 +382,9 @@ def test_dify_interaction_resume_submits_mapped_values_and_clears_continuation() action_id="action_1", values={"field_1": "high"}, ) - # Persist through the real contract: owner scope, expiry and pending status. - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) + results = asyncio.run( + _collect_async(runner._resume_workflow_once(_ctx(), FakeClient(), submission, False, continuation)) ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), FakeClient(), submission, False))) assert captured == { "form_token": "form-private", @@ -302,66 +394,32 @@ def test_dify_interaction_resume_submits_mapped_values_and_clears_continuation() "action": "approve-private", } assert [_type(result) for result in results] == ["message.delta", "run.completed"] - assert storage_key in storage.deleted - assert storage_key not in storage.values -def test_dify_field_submission_advances_to_action_without_calling_provider() -> None: +def test_dify_multi_field_form_is_requested_once() -> None: module = _load_runner_module("dify-agent") runner = object.__new__(module.DefaultRunner) - storage = _FakePluginStorage() - runner.get_run_api = lambda ctx: storage - interaction_id = "dify-field" - storage.values[module._interaction_storage_key(interaction_id)] = json.dumps( + request, continuation = runner._build_interaction_request( { - "version": 1, - "interaction_id": interaction_id, "form_token": "form-private", - "workflow_run_id": "workflow-private", - "user": "user_1", - "field_map": {"field_1": "priority"}, - "action_map": {"action_1": "approve-private"}, - "default_inputs": {}, - "title": "Manual review", - "description": "Review it", - "fallback_text": "Review it", - "phase": "field", - "current_fields": [ - { - "id": "field_1", - "label": "Priority", - "type": "select", - "required": True, - "options": [{"value": "high", "label": "High"}], - } + "node_title": "Manual review", + "inputs": [ + {"output_variable_name": "first", "type": "text"}, + {"output_variable_name": "second", "type": "text"}, ], - "remaining_fields": [], - "interaction_actions": [{"id": "action_1", "label": "Approve", "style": "primary"}], - } - ).encode() - - class ProviderMustNotRun: - def workflow_submit(self, **kwargs): - raise AssertionError("provider must not resume before the action step") - - submission = InteractionSubmission(interaction_id=interaction_id, values={"field_1": "high"}) - # Persist through the real contract: owner scope, expiry and pending status. - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) + "actions": [{"id": "approve", "title": "Approve"}, {"id": "reject", "title": "Reject"}], + }, + "workflow-private", + "user_1", ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), ProviderMustNotRun(), submission, False))) - assert [_type(result) for result in results] == ["action.requested"] - request = results[0].data["payload"] - assert request["fields"] == [] - assert request["actions"][0]["label"] == "Approve" - continuation = json.loads(storage.values[module._interaction_storage_key(request["interaction_id"])]) - assert continuation["default_inputs"] == {"priority": "high"} + assert [field.id for field in request.fields] == ["field_1", "field_2", "_dify_action"] + assert [option.value for option in request.fields[-1].options] == ["action_1", "action_2"] + assert request.actions == [] + assert continuation["field_map"] == {"field_1": "first", "field_2": "second"} -def test_dify_form_content_is_revealed_with_its_current_field() -> None: +def test_dify_form_content_is_sent_with_all_fields() -> None: module = _load_runner_module("dify-agent") runner = object.__new__(module.DefaultRunner) storage = _FakePluginStorage() @@ -386,92 +444,56 @@ def test_dify_form_content_is_revealed_with_its_current_field() -> None: "user-1", ) - assert request.description == "1\n请输入你的问题" - assert request.fields[0].label == "us_input" - assert "请选择你的答案" not in request.description - - asyncio.run(runner._store_interaction_continuation(_ctx(), continuation)) - second_result = asyncio.run( - runner._advance_field_interaction( - _ctx(), - continuation, - InteractionSubmission(interaction_id=request.interaction_id, values={"field_1": "问题内容"}), - ) - ) - second_request = second_result.data["payload"] - assert second_request["description"] == "请选择你的答案" - assert second_request["fields"][0]["label"] == "xiala" - assert "请输入你的问题" not in second_request["description"] - - second_continuation = json.loads(storage.values[module._interaction_storage_key(second_request["interaction_id"])]) - final_result = asyncio.run( - runner._advance_field_interaction( - _ctx(), - second_continuation, - InteractionSubmission( - interaction_id=second_request["interaction_id"], - values={"field_2": "1"}, - ), - ) - ) - final_request = final_result.data["payload"] - assert final_request["description"] is None - assert final_request["fields"] == [] - assert final_request["actions"][0]["label"] == "or" + assert request.description == "1\n请输入你的问题\n\n请选择你的答案" + assert [field.label for field in request.fields] == ["us_input", "xiala"] + assert request.actions == [] + assert continuation["action_map"] == {"action_1": "or-private"} def test_dify_interaction_resume_can_pause_again() -> None: module = _load_runner_module("dify-agent") runner = object.__new__(module.DefaultRunner) - storage = _FakePluginStorage() - runner.get_run_api = lambda ctx: storage - interaction_id = "dify-first" - old_key = module._interaction_storage_key(interaction_id) - storage.values[old_key] = json.dumps( - { - "version": 1, - "interaction_id": interaction_id, - "form_token": "form-1", - "workflow_run_id": "workflow-1", - "user": "user_1", - "field_map": {}, - "action_map": {"continue": ""}, - "default_inputs": {}, - } - ).encode() + continuation = { + "interaction_id": "dify-first", + "form_token": "form-1", + "workflow_run_id": "workflow-1", + "user": "user_1", + "field_map": {}, + "action_map": {"continue": ""}, + "default_inputs": {}, + } class FakeClient: async def workflow_submit(self, **kwargs): - yield { - "event": "workflow_paused", - "data": { - "workflow_run_id": "workflow-2", - "reasons": [ - { - "TYPE": "human_input_required", - "form_token": "form-2", - "node_title": "Second review", - "inputs": [], - "actions": [{"id": "done", "title": "Done"}], - } - ], - }, - } + if kwargs["form_token"] == "form-1": + yield { + "event": "workflow_paused", + "data": { + "workflow_run_id": "workflow-2", + "reasons": [ + { + "TYPE": "human_input_required", + "form_token": "form-2", + "node_title": "Second review", + "inputs": [], + "actions": [{"id": "done", "title": "Done"}], + } + ], + }, + } + else: + yield {"event": "node_finished", "data": {"node_type": "answer", "outputs": {"answer": "Done"}}} + yield {"event": "workflow_finished", "data": {"outputs": {}}} - submission = InteractionSubmission(interaction_id=interaction_id, action_id="continue") - # Persist through the real contract: owner scope, expiry and pending status. - asyncio.run( - runner._store_interaction_continuation( - _ctx(), json.loads(storage.values[module._interaction_storage_key(interaction_id)]) - ) + ctx, requests = _dify_interaction_ctx() + submission = InteractionSubmission(interaction_id="dify-first", action_id="continue") + results = asyncio.run( + _collect_async(runner._resume_workflow_once(ctx, FakeClient(), submission, False, continuation)) ) - results = asyncio.run(_collect_async(runner._resume_workflow(_ctx(), FakeClient(), submission, False))) - assert [_type(result) for result in results] == ["action.requested"] - new_interaction_id = results[0].data["payload"]["interaction_id"] - assert new_interaction_id != interaction_id - assert old_key in storage.deleted - assert module._interaction_storage_key(new_interaction_id) in storage.values + assert len(requests) == 1 + assert requests[0].title == "Second review" + assert _type(results[-1]) == "run.completed" def test_dify_client_submits_form_then_streams_resumed_events(monkeypatch) -> None: @@ -558,6 +580,77 @@ def test_dify_client_submits_form_then_streams_resumed_events(monkeypatch) -> No assert event_body.consumed and event_body.closed +def test_dify_client_consumes_sse_returned_by_form_submission(monkeypatch) -> None: + module = _load_runner_module("dify-agent") + client_module = sys.modules["pkg.dify_client"] + real_async_client = httpx.AsyncClient + calls: list[httpx.Request] = [] + expected_event = {"event": "workflow_finished", "data": {"outputs": {"summary": "done"}}} + + def handle_request(request): + calls.append(request) + return httpx.Response( + 200, + headers={"content-type": "text/event-stream; charset=utf-8"}, + content=b"data: " + json.dumps(expected_event).encode() + b"\n\n", + ) + + transport = httpx.MockTransport(handle_request) + monkeypatch.setattr( + client_module.httpx, + "AsyncClient", + lambda **kwargs: real_async_client(transport=transport, **kwargs), + ) + client = module.AsyncDifyClient(api_key="key", base_url="https://dify.example/v1") + + events = asyncio.run( + _collect_async( + client.workflow_submit( + form_token="form-token", + workflow_run_id="workflow-run", + inputs={"priority": "high"}, + user="user-1", + action="approve", + ) + ) + ) + + assert events == [expected_event] + assert [(request.method, request.url.path) for request in calls] == [("POST", "/v1/form/human_input/form-token")] + + +def test_dify_client_yields_submission_sse_before_stream_ends(monkeypatch) -> None: + module = _load_runner_module("dify-agent") + client_module = sys.modules["pkg.dify_client"] + real_async_client = httpx.AsyncClient + first_event = {"event": "text_chunk", "data": {"text": "ready"}} + + class FirstEventStream(httpx.AsyncByteStream): + async def __aiter__(self): + yield b"data: " + json.dumps(first_event).encode() + b"\n\n" + raise AssertionError("submission response was buffered before the first event") + + def handle_request(request): + assert request.method == "POST" + return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=FirstEventStream()) + + monkeypatch.setattr( + client_module.httpx, + "AsyncClient", + lambda **kwargs: real_async_client(transport=httpx.MockTransport(handle_request), **kwargs), + ) + client = module.AsyncDifyClient(api_key="key", base_url="https://dify.example/v1") + + async def read_first(): + stream = client.workflow_submit("form-token", "workflow-run", {}, "user-1", "approve") + try: + return await anext(stream) + finally: + await stream.aclose() + + assert asyncio.run(read_first()) == first_event + + def test_dify_text_image_upload_failure_is_input_error() -> None: module = _load_runner_module("dify-agent") diff --git a/plugins/Runner/uv.lock b/plugins/Runner/uv.lock index 772a18935..5e6f0e427 100644 --- a/plugins/Runner/uv.lock +++ b/plugins/Runner/uv.lock @@ -830,7 +830,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "langbot-plugin", specifier = "==0.7.4" }, + { name = "langbot-plugin", specifier = "==0.7.20" }, { name = "pydantic", specifier = ">=2.0.0" }, ] @@ -847,7 +847,7 @@ dev = [ [[package]] name = "langbot-plugin" -version = "0.7.4" +version = "0.7.20" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiofiles" }, @@ -868,9 +868,9 @@ dependencies = [ { name = "watchdog" }, { name = "websockets" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/92/71/b4bed3cfe28ba7a24e1108465429d833c1f702e33fdbc0d31d7bea3587d9/langbot_plugin-0.7.4.tar.gz", hash = "sha256:af3a0bcb9711fd734af811c0e178d259ae4a0d3e45d25e844661aba3dd574f96", size = 673043, upload-time = "2026-09-28T10:43:41.289Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5e/b9/e93ee14ccb584b2351652e6b37a80d255ca99efcdd7761edf54223505f6b/langbot_plugin-0.7.20.tar.gz", hash = "sha256:10a8ad7dd15d040680962148357d49294faad0ae677f5b8989fedb81b4d936c0", size = 758993, upload-time = "2026-11-03T04:59:16.695Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f2/c7/c870377771cbe27e047b19778b5f249b15efef52409358901af94d13e6c0/langbot_plugin-0.7.4-py3-none-any.whl", hash = "sha256:596ecd776c13efa6f6cfe178463dc4a967653238548c9569195cdbb5aa47506e", size = 433419, upload-time = "2026-09-28T10:43:40.073Z" }, + { url = "https://files.pythonhosted.org/packages/66/2f/7bfd9692fd142f919a7ee6d13957935155e6c9d8a6b4ec24a2ce3b6a99e0/langbot_plugin-0.7.20-py3-none-any.whl", hash = "sha256:de33471621e2bde6074ffae6174f14a9f34c6d5625a2aa1adbe92ec6d62ed2bc", size = 479090, upload-time = "2026-11-03T04:59:15.256Z" }, ] [[package]] diff --git a/plugins/catalog.json b/plugins/catalog.json index ef3b34c7e..42c18b4d1 100644 --- a/plugins/catalog.json +++ b/plugins/catalog.json @@ -36,7 +36,7 @@ }, { "id": "langbot-team/LocalAgent", - "version": "0.2.4", + "version": "0.2.5", "category": "Runner", "path": "Runner/LocalAgent", "repository": "https://github.com/langbot-app/LangBot/tree/master/plugins/Runner/LocalAgent" diff --git a/pyproject.toml b/pyproject.toml index 7e82defe7..bf1d765c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,7 +71,7 @@ dependencies = [ "langchain-text-splitters>=1.1.2", "chromadb>=1.0.0,<2.0.0", "qdrant-client (>=1.15.1,<2.0.0)", - "langbot-plugin==0.7.19", + "langbot-plugin==0.7.20", "asyncpg>=0.30.0", "line-bot-sdk>=3.19.0", "matrix-nio>=0.25.2", diff --git a/src/langbot/libs/dingtalk_api/a2ui.py b/src/langbot/libs/dingtalk_api/a2ui.py new file mode 100644 index 000000000..2b28882ef --- /dev/null +++ b/src/langbot/libs/dingtalk_api/a2ui.py @@ -0,0 +1,157 @@ +"""DingTalk A2UI message builders shared by both DingTalk adapters.""" + +from __future__ import annotations + +import json +import typing + + +A2UI_CATALOG_ID = 'https://dingtalk.com/card/a2ui/catalogs/public/catalog.json' +A2UI_MESSAGE_VERSION = 'v1.0' +A2UI_PROTOCOL_VERSION = '1.0' +LANGBOT_LOGO_URL = 'https://langbot.app/logo-blue.png' +LANGBOT_CARD_URL = 'https://langbot.app?utm_source=dingtalk&utm_medium=bot_card&utm_campaign=langbot' + + +def binding(path: str) -> dict[str, str]: + return {'path': path} + + +def brand_components() -> list[dict[str, typing.Any]]: + return [ + { + 'id': 'langbot-brand', + 'component': 'Row', + 'children': ['langbot-generated', 'langbot-brand-link'], + 'align': 'center', + 'justify': 'spaceBetween', + 'gap': 8, + }, + { + 'id': 'langbot-generated', + 'component': 'Text', + 'text': 'AI-generated', + 'variant': 'caption', + }, + { + 'id': 'langbot-brand-link', + 'component': 'Text', + 'text': 'LangBot', + 'variant': 'caption', + 'icon': {'url': LANGBOT_LOGO_URL}, + 'onLinkClick': {'functionCall': {'call': 'openUrl', 'args': {'url': LANGBOT_CARD_URL}}}, + }, + ] + + +def serialize_messages(messages: typing.Iterable[dict | str]) -> list[str]: + serialized = [ + message if isinstance(message, str) else json.dumps(message, ensure_ascii=False, separators=(',', ':')) + for message in messages + ] + if not serialized: + raise ValueError('DingTalk A2UI messages must not be empty') + return serialized + + +def create_surface_messages( + surface_id: str, + *, + data: dict[str, typing.Any], + components: list[dict[str, typing.Any]], +) -> list[dict[str, typing.Any]]: + return [ + { + 'version': A2UI_MESSAGE_VERSION, + 'createSurface': { + 'surfaceId': surface_id, + 'catalogId': A2UI_CATALOG_ID, + }, + }, + { + 'version': A2UI_MESSAGE_VERSION, + 'updateDataModel': { + 'surfaceId': surface_id, + 'path': '/', + 'value': data, + }, + }, + { + 'version': A2UI_MESSAGE_VERSION, + 'updateComponents': { + 'surfaceId': surface_id, + 'components': components, + }, + }, + ] + + +def update_surface_messages( + surface_id: str, + *, + data: dict[str, typing.Any] | None = None, + components: list[dict[str, typing.Any]] | None = None, +) -> list[dict[str, typing.Any]]: + messages: list[dict[str, typing.Any]] = [] + if data is not None: + messages.append( + { + 'version': A2UI_MESSAGE_VERSION, + 'updateDataModel': { + 'surfaceId': surface_id, + 'path': '/', + 'value': data, + }, + } + ) + if components is not None: + messages.append( + { + 'version': A2UI_MESSAGE_VERSION, + 'updateComponents': { + 'surfaceId': surface_id, + 'components': components, + }, + } + ) + if not messages: + raise ValueError('DingTalk A2UI update requires data or components') + return messages + + +def text_card_components() -> list[dict[str, typing.Any]]: + return [ + { + 'id': 'root', + 'component': 'Column', + 'children': ['content', 'langbot-brand'], + 'gap': 8, + }, + { + 'id': 'content', + 'component': 'Markdown', + 'content': binding('/content'), + }, + *brand_components(), + ] + + +def create_text_card_messages(surface_id: str, content: str = '') -> list[dict[str, typing.Any]]: + return create_surface_messages( + surface_id, + data={'content': content}, + components=text_card_components(), + ) + + +def update_text_card_messages(surface_id: str, content: str) -> list[dict[str, typing.Any]]: + return [ + { + 'version': A2UI_MESSAGE_VERSION, + 'updateDataModel': { + 'surfaceId': surface_id, + 'path': '/content', + 'value': content, + }, + } + ] diff --git a/src/langbot/libs/dingtalk_api/api.py b/src/langbot/libs/dingtalk_api/api.py index 700294579..9565e787a 100644 --- a/src/langbot/libs/dingtalk_api/api.py +++ b/src/langbot/libs/dingtalk_api/api.py @@ -14,15 +14,17 @@ import websockets from .EchoHandler import EchoTextHandler from .card_callback import DingTalkCardActionHandler from .dingtalkevent import DingTalkEvent -from .thinking import card_text_fields, visible_think_markers +from .a2ui import ( + A2UI_PROTOCOL_VERSION, + create_text_card_messages, + serialize_messages, + update_text_card_messages, +) +from .thinking import visible_think_markers import httpx import traceback from langbot.pkg.utils import httpclient -from langbot.pkg.utils.outbound_url import ( - UnsafeOutboundUrlError, - assert_safe_local_media_path, - assert_safe_outbound_url, -) +from langbot.pkg.utils.outbound_url import assert_safe_outbound_url _stdout_logger = logging.getLogger('langbot.dingtalk_api') @@ -66,34 +68,8 @@ async def _read_httpx_media_limited(response: httpx.Response) -> bytes: return bytes(body) -def _stringify_card_param_map(card_param_map: Optional[dict]) -> dict: - """DingTalk cardParamMap only accepts string values. - - Keep callers free to pass structured values for template variables such - as button groups or select options, then encode them once at the API - boundary. - """ - if not card_param_map: - return {} - result = {} - for key, value in card_param_map.items(): - if value is None: - result[key] = '' - elif isinstance(value, str): - result[key] = value - else: - result[key] = json.dumps(value, ensure_ascii=False) - return result - - def is_stream_card_configured(config: dict) -> bool: - if not config.get('markdown_card', True): - return False - template_id = config.get('card_template_id') - # Older manifests stored instructional placeholder text as the default. - return ( - isinstance(template_id, str) and bool(template_id.strip()) and template_id.strip() != '填写你的卡片template_id' - ) + return bool(config.get('markdown_card', True)) class DingTalkClient: @@ -134,10 +110,8 @@ class DingTalkClient: self.access_token_expiry_time = '' self.markdown_card = markdown_card self.logger = logger - # Legacy access_token used by the OLD oapi.dingtalk.com endpoints - # (e.g. /media/upload, which is the only documented way to get an - # `@xxx` media_id usable in card Avatar.imageUrl). The new v1.0 - # token doesn't work there — different auth domain. + # Attachment uploads still use the legacy oapi.dingtalk.com token. + # The v1.0 application token does not work for that auth domain. self.legacy_access_token = '' self.legacy_access_token_expiry_time: typing.Optional[float] = None self._stopped = False # Flag to control the event loop @@ -805,118 +779,114 @@ class DingTalkClient: async def create_and_card( self, - temp_card_id: str, incoming_message: dingtalk_stream.ChatbotMessage, quote_origin: bool = False, - card_auto_layout: bool = True, ): """Create + deliver the streaming chat card for a chatbot reply. - Replaces the old `dingtalk_stream.AICardReplier`-based path. Returns - `(layout_config, out_track_id)` keeps the adapter's tuple contract - while preserving the layout setting on subsequent data updates. + Returns ``(card state, out_track_id)`` for subsequent A2UI updates. """ - out_track_id = uuid.uuid4().hex is_group = str(incoming_message.conversation_type) == '2' - if is_group: - open_space_id = f'dtv1.card//IM_GROUP.{incoming_message.conversation_id}' - else: - open_space_id = f'dtv1.card//IM_ROBOT.{incoming_message.sender_staff_id}' + return await self.create_and_card_for_target( + 'group' if is_group else 'person', + incoming_message.conversation_id if is_group else incoming_message.sender_staff_id, + ) - card_param_map = { - 'content': '', - 'answer': '', - 'reasoning': '', - 'flowStatus': '1', - 'brand': '', - 'hasReasoning': '', - } - if incoming_message.message_type == 'text': - card_param_map['query'] = incoming_message.get_text_list()[0] - else: - card_param_map['query'] = '...' + async def create_and_card_for_target(self, target_type: str, target_id: str): + """Create a streaming card when the reply has no original chat message.""" + if target_type not in {'group', 'person'} or not target_id: + raise ValueError('DingTalk streaming card requires a group or person target') + out_track_id = uuid.uuid4().hex + surface_id = f'langbot-{out_track_id}' + is_group = target_type == 'group' + open_space_id = f'dtv1.card//im_group.{target_id}' if is_group else f'dtv1.card//im_robot.{target_id}' - await self.create_and_deliver_card( - card_template_id=temp_card_id, + await self.create_and_deliver_ai_card( out_track_id=out_track_id, open_space_id=open_space_id, is_group=is_group, - card_param_map=card_param_map, - card_data_config={'autoLayout': card_auto_layout}, + a2ui_messages=create_text_card_messages(surface_id), + flow_status='PROCESSING', + summary='LangBot is replying', ) - return {'autoLayout': card_auto_layout}, out_track_id + return {'surface_id': surface_id}, out_track_id async def send_card_message(self, card_instance, card_instance_id: str, content: str, is_final: bool): - """Update separate reasoning/answer fields and the legacy content field.""" - fields = card_text_fields(content) - # Old templates continue to render content with explicit think markers; - # the supplied split template binds only reasoning and answer. - fields['content'] = visible_think_markers(content) - fields['flowStatus'] = '3' if is_final else '2' - fields['brand'] = '' - if isinstance(card_instance, dict): - fields['config'] = card_instance - fields['autoLayout'] = str(card_instance.get('autoLayout', True)).lower() - if not await self.update_card_data(out_track_id=card_instance_id, card_param_map=fields): - raise RuntimeError('DingTalk card content update failed; see adapter logs for the API response') + """Replace the streamed Markdown content on an A2UI card.""" + surface_id = ( + str(card_instance.get('surface_id') or '') if isinstance(card_instance, dict) else '' + ) or f'langbot-{card_instance_id}' + await self.update_ai_card( + out_track_id=card_instance_id, + a2ui_messages=update_text_card_messages(surface_id, visible_think_markers(content)), + flow_status='FINISH' if is_final else 'PROCESSING', + ) - async def create_and_deliver_card( + @staticmethod + def _check_ai_card_result(response) -> dict: + try: + data = response.json() + except Exception as exc: + raise RuntimeError(f'Invalid DingTalk AI card response (HTTP {response.status_code})') from exc + if response.status_code != 200 or data.get('success') is not True: + raise RuntimeError( + f'DingTalk AI card request failed (HTTP {response.status_code}): ' + f'{data.get("message", data.get("errorMsg", data))}' + ) + result = data.get('result') if isinstance(data.get('result'), dict) else {} + failures = [ + item + for item in result.get('deliverResults') or [] + if isinstance(item, dict) and item.get('success') is not True + ] + if failures: + raise RuntimeError(f'DingTalk AI card delivery failed: {failures}') + return result + + async def create_and_deliver_ai_card( self, *, - card_template_id: str, out_track_id: str, open_space_id: str, is_group: bool, - card_param_map: Optional[dict] = None, + a2ui_messages: list[dict | str], + flow_status: str = 'PROCESSING', + summary: str = '', callback_type: str = 'STREAM', - callback_route_key: Optional[str] = None, - support_forward: bool = True, - dynamic_data_source_configs: Optional[list] = None, - card_data_config: Optional[dict] = None, at_user_ids: Optional[dict] = None, recipients: Optional[list] = None, - ) -> bool: - """POST /v1.0/card/instances/createAndDeliver. - - Mirrors the SDK's `async_create_and_deliver_card` shape but exposes - the dynamic-data-source config slot so we can register a pull URL - for variable-length button lists. - """ + biz_context: Optional[dict] = None, + ) -> dict: + """Create and deliver an A2UI card as the configured robot application.""" if not await self.check_access_token(): await self.get_access_token() - template_params = dict(card_param_map or {}) - if card_data_config is not None: - template_params['config'] = card_data_config - template_params['autoLayout'] = str(card_data_config.get('autoLayout', True)).lower() - cardData: dict = {'cardParamMap': _stringify_card_param_map(template_params)} - + robot_code = self.robot_code or self.key body: dict = { - 'cardTemplateId': card_template_id, 'outTrackId': out_track_id, - 'cardData': cardData, - 'callbackType': callback_type, 'openSpaceId': open_space_id, - 'imGroupOpenSpaceModel': {'supportForward': support_forward}, - 'imRobotOpenSpaceModel': {'supportForward': support_forward}, + 'protocolVersion': A2UI_PROTOCOL_VERSION, + 'flowStatus': flow_status, + 'a2uiMessages': serialize_messages(a2ui_messages), + 'summary': summary, + 'callbackType': callback_type, } - if callback_type == 'HTTP' and callback_route_key: - body['callbackRouteKey'] = callback_route_key - if is_group: - deliver: dict = {'robotCode': self.robot_code or self.key} - if at_user_ids: - deliver['atUserIds'] = at_user_ids - if recipients is not None: - deliver['recipients'] = recipients + body['imGroupOpenSpaceModel'] = {'supportForward': False} + deliver: dict = {'robotCode': robot_code} body['imGroupOpenDeliverModel'] = deliver else: - body['imRobotOpenDeliverModel'] = {'spaceType': 'IM_ROBOT'} + body['imRobotOpenSpaceModel'] = {'supportForward': False} + deliver = {'robotCode': robot_code} + body['imRobotOpenDeliverModel'] = deliver + if at_user_ids: + deliver['atUserIds'] = at_user_ids + if recipients is not None: + deliver['recipients'] = recipients + if biz_context: + body['bizContext'] = biz_context - if dynamic_data_source_configs: - body['openDynamicDataConfig'] = {'dynamicDataSourceConfigs': dynamic_data_source_configs} - - url = f'{DINGTALK_OPENAPI_BASE}/v1.0/card/instances/createAndDeliver' + url = f'{DINGTALK_OPENAPI_BASE}/v1.0/card/ai/instances/createAndDeliver' headers = { 'x-acs-dingtalk-access-token': self.access_token, 'Content-Type': 'application/json', @@ -924,45 +894,33 @@ class DingTalkClient: try: async with self._http_client_context() as client: response = await client.post(url, headers=headers, json=body, timeout=30.0) - # Propagate business failures as well as transport failures. Callers - # must not register or update a card that was never delivered. - self._check_send_result(response) + result = self._check_ai_card_result(response) except Exception as exc: - error = RuntimeError(f'DingTalk card creation failed: {exc}') + error = RuntimeError(f'DingTalk AI card creation failed: {exc}') _stdout_logger.error('%s', error) raise error from exc - _stdout_logger.info('DingTalk card created: outTrackId=%s', out_track_id) - return True + _stdout_logger.info('DingTalk AI card created: outTrackId=%s', out_track_id) + return result - async def streaming_update_card( + async def update_ai_card( self, *, out_track_id: str, - content_key: str, - content_value: str, - append: bool, - finished: bool, - failed: bool = False, - ) -> bool: - """PUT /v1.0/card/streaming. - - Replaces `dingtalk_stream.AICardReplier.async_streaming` — same body - shape (outTrackId / guid / key / content / isFull / isFinalize / - isError) per the SDK source. - """ + a2ui_messages: list[dict | str], + flow_status: str, + out_update_id: Optional[str] = None, + ) -> dict: + """Apply an idempotent A2UI delta to an existing AI card.""" if not await self.check_access_token(): await self.get_access_token() body = { 'outTrackId': out_track_id, - 'guid': uuid.uuid4().hex, - 'key': content_key, - 'content': content_value, - 'isFull': not append, - 'isFinalize': finished, - 'isError': failed, + 'outUpdateId': out_update_id or uuid.uuid4().hex, + 'flowStatus': flow_status, + 'a2uiMessages': serialize_messages(a2ui_messages), } - url = f'{DINGTALK_OPENAPI_BASE}/v1.0/card/streaming' + url = f'{DINGTALK_OPENAPI_BASE}/v1.0/card/ai/instances/update' headers = { 'x-acs-dingtalk-access-token': self.access_token, 'Content-Type': 'application/json', @@ -970,75 +928,17 @@ class DingTalkClient: try: async with self._http_client_context() as client: response = await client.put(url, headers=headers, json=body, timeout=30.0) - if response.status_code == 200: - return True - if self.logger: - response_body = await httpclient.response_text(response) - await self.logger.error( - f'DingTalk card streaming failed: status={response.status_code} body={response_body}' - ) - return False - except Exception: - if self.logger: - await self.logger.error(f'DingTalk card streaming error: {traceback.format_exc()}') - return False - - async def update_card_data( - self, - *, - out_track_id: str, - card_param_map: Optional[dict] = None, - private_data: Optional[dict] = None, - ) -> bool: - """PUT /v1.0/card/instances — non-streaming card content update.""" - if not await self.check_access_token(): - await self.get_access_token() - - body: dict = { - 'outTrackId': out_track_id, - 'cardData': {'cardParamMap': _stringify_card_param_map(card_param_map)}, - } - if private_data: - body['privateData'] = private_data - - url = f'{DINGTALK_OPENAPI_BASE}/v1.0/card/instances' - headers = { - 'x-acs-dingtalk-access-token': self.access_token, - 'Content-Type': 'application/json', - } - try: - _stdout_logger.info( - 'DingTalk update_card_data request: out_track_id=%s body=%s', - out_track_id, - json.dumps(body, ensure_ascii=False)[:1500], - ) - async with self._http_client_context() as client: - response = await client.put(url, headers=headers, json=body, timeout=30.0) - response_body = await httpclient.response_text(response, max_chars=300) - _stdout_logger.info( - 'DingTalk update_card_data response: status=%d body=%s', - response.status_code, - response_body, - ) - if response.status_code == 200: - return True - if self.logger: - await self.logger.error( - f'DingTalk update card failed: status={response.status_code} body={response_body}' - ) - return False - except Exception: - _stdout_logger.exception('DingTalk update_card_data error') - if self.logger: - await self.logger.error(f'DingTalk update card error: {traceback.format_exc()}') - return False + return self._check_ai_card_result(response) + except Exception as exc: + error = RuntimeError(f'DingTalk AI card update failed: {exc}') + _stdout_logger.error('%s', error) + raise error from exc async def get_legacy_access_token(self) -> Optional[str]: """Fetch the LEGACY (oapi.dingtalk.com) access_token. This is a different auth domain from the v1.0 token cached in ``self.access_token`` — only the legacy token authorises the - ``/media/upload`` endpoint that returns an ``@xxx`` media_id - consumable by card components like Avatar.imageUrl. + ``/media/upload`` endpoint used by attachment delivery. Returns the token string on success, None on failure. Caches with a 60s safety margin before the documented 7200s expiry. @@ -1072,67 +972,6 @@ class DingTalkClient: await self.logger.error(f'DingTalk legacy gettoken error: {traceback.format_exc()}') return None - async def upload_image_media(self, file_path: str) -> Optional[str]: - """Upload an image file to DingTalk media storage and return the - ``@xxx`` media_id, which can be passed straight into card variables - like Avatar.imageUrl. Endpoint: - - POST https://oapi.dingtalk.com/media/upload?access_token=…&type=image - - Returns the media_id on success, None on any failure (caller - should handle a None gracefully — DingTalk falls back to a - default avatar when imageUrl is empty/unknown). - """ - if not os.path.exists(file_path): - if self.logger: - await self.logger.error(f'DingTalk upload_image_media: file not found {file_path}') - return None - - try: - # Caller-supplied path: confine it to the media roots so a plugin or - # external input cannot make the adapter upload arbitrary files. - safe_file_path = assert_safe_local_media_path(file_path) - except UnsafeOutboundUrlError as exc: - if self.logger: - await self.logger.error(f'DingTalk upload_image_media: rejected path: {exc}') - return None - - token = await self.get_legacy_access_token() - if not token: - return None - - url = 'https://oapi.dingtalk.com/media/upload' - try: - file_bytes = await asyncio.to_thread(_read_local_media_limited, safe_file_path) - file_name = os.path.basename(safe_file_path) - # Best-effort content-type guess; DingTalk accepts the major image - # mime types and otherwise infers from the bytes. - ext = os.path.splitext(file_name)[1].lower().lstrip('.') - mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif'}.get( - ext, 'application/octet-stream' - ) - async with self._http_client_context() as client: - response = await client.post( - url, - params={'access_token': token, 'type': 'image'}, - files={'media': (file_name, file_bytes, mime)}, - timeout=30.0, - ) - data = await httpclient.parse_json_response(response) if response.status_code == 200 else {} - if data.get('errcode') == 0 and data.get('media_id'): - _stdout_logger.info('DingTalk upload_image_media OK: media_id=%s', data['media_id']) - return data['media_id'] - if self.logger: - response_body = await httpclient.response_text(response, max_chars=300) - await self.logger.error( - f'DingTalk upload_image_media failed: status={response.status_code} body={response_body}' - ) - except Exception: - _stdout_logger.exception('DingTalk upload_image_media error') - if self.logger: - await self.logger.error(f'DingTalk upload_image_media error: {traceback.format_exc()}') - return None - async def start(self): """启动 WebSocket 连接,监听消息""" self._stopped = False diff --git a/src/langbot/libs/dingtalk_api/card_callback.py b/src/langbot/libs/dingtalk_api/card_callback.py index 4634a696b..e18d03c59 100644 --- a/src/langbot/libs/dingtalk_api/card_callback.py +++ b/src/langbot/libs/dingtalk_api/card_callback.py @@ -26,6 +26,10 @@ from dingtalk_stream.card_callback import CardCallbackMessage _PARAM_PATHS = ( + ('actionData', 'a2uiAction', 'context'), + ('a2uiAction', 'context'), + ('action', 'context'), + ('context',), ('params',), ('cardPrivateData', 'params'), ('userPrivateData', 'params'), @@ -77,7 +81,7 @@ class DingTalkCardActionHandler(dingtalk_stream.CallbackHandler): # there). Pull it from the raw callback.data instead. raw = callback.data if isinstance(callback.data, dict) else {} params = _merge_params(_extract_params(content), _extract_params(raw)) - action_id = raw.get('actionId') or '' + action_id = raw.get('actionId') or params.get('actionId') or params.get('action_id') or '' if not action_id: # Some templates nest it under actionData / cardPrivateData. action_data = raw.get('actionData') or {} diff --git a/src/langbot/libs/qq_official_api/api.py b/src/langbot/libs/qq_official_api/api.py index 5dce0ce9a..a19cd1b6c 100644 --- a/src/langbot/libs/qq_official_api/api.py +++ b/src/langbot/libs/qq_official_api/api.py @@ -401,11 +401,15 @@ class QQOfficialClient: content_type = attachment.get('content_type', '') return content_type.startswith('image/') + def allocate_msg_seq(self) -> int: + """Reserve a sequence for a new outgoing message, including a stream.""" + self._msg_seq_counter += 1 + return self._msg_seq_counter + def _resolve_msg_seq(self, msg_seq: Optional[int] = None) -> int: """Allocate automatic sequences across message types, preserving explicit stream sequences.""" if msg_seq is None: - self._msg_seq_counter += 1 - return self._msg_seq_counter + return self.allocate_msg_seq() self._msg_seq_counter = max(self._msg_seq_counter, msg_seq) return msg_seq diff --git a/src/langbot/libs/wecom_ai_bot_api/ws_client.py b/src/langbot/libs/wecom_ai_bot_api/ws_client.py index 06f58552f..5fcec43be 100644 --- a/src/langbot/libs/wecom_ai_bot_api/ws_client.py +++ b/src/langbot/libs/wecom_ai_bot_api/ws_client.py @@ -60,6 +60,7 @@ _UPLOAD_CHUNK_SIZE = 512 * 1024 _DEDUP_CACHE_MAX = 4096 _STREAM_CACHE_MAX = 1024 +_INTERACTION_STREAM_MAX_AGE_SECONDS = 570 _FEEDBACK_CACHE_MAX = 4096 _PENDING_FORM_MAX = 1024 _PENDING_FORM_TTL_SECONDS = 1800 @@ -149,6 +150,7 @@ class WecomBotWsClient: self._completed_stream_content: dict[str, str] = {} # Stream session info for feedback tracking self._stream_sessions: dict[str, dict] = {} # msg_id -> session info + self._interaction_stream_origins: dict[str, dict] = {} # msg_id -> original callback context # Feedback tracking: feedback_id -> session info self._feedback_sessions: dict[str, dict] = {} # feedback_id -> {msg_id, user_id, chat_id, stream_id, req_id} # msg_id -> feedback_id (for associating feedback with message) @@ -188,6 +190,72 @@ class WecomBotWsClient: if task_id: self._pending_forms_by_task.pop(task_id, None) + async def finish_stream_for_interaction(self, msg_id: str) -> bool: + """Release an unused stream or finish text already shown before a card.""" + key = self._stream_ids.get(msg_id) + if not key: + return True + session = self._stream_sessions.get(msg_id, {}) + if not self._stream_sessions.get(msg_id, {}).get('stream_started'): + self._remember_interaction_stream_origin(msg_id, session) + self._stream_ids.pop(msg_id, None) + self._stream_last_content.pop(msg_id, None) + self._stream_sessions.pop(msg_id, None) + return True + req_id, stream_id = key.split('|', 1) + content = self._stream_last_content.get(msg_id, '') + try: + ack = await self.reply_stream(req_id, stream_id, content, finish=True) + except Exception: + await self.logger.warning(f'Failed to finish WeCom loading stream: {traceback.format_exc()}') + return False + if not isinstance(ack, dict) or ack.get('errcode', 0) != 0: + detail = ack.get('errmsg', ack.get('errcode')) if isinstance(ack, dict) else 'no acknowledgement' + await self.logger.warning(f'Failed to finish WeCom loading stream: {detail}') + return False + self._remember_interaction_stream_origin(msg_id, session) + self._stream_ids.pop(msg_id, None) + self._stream_last_content.pop(msg_id, None) + self._stream_sessions.pop(msg_id, None) + return True + + def _remember_interaction_stream_origin(self, msg_id: str, session: dict) -> None: + if session.get('req_id'): + self._interaction_stream_origins[msg_id] = { + key: session.get(key) for key in ('req_id', 'user_id', 'chat_id', 'created_at') + } + self._cap_mapping(self._interaction_stream_origins, _STREAM_CACHE_MAX) + + def begin_interaction_stream(self, msg_id: str, target_type: str, target_id: str) -> bool: + """Use a fresh stream ID so the resumed answer appears after the card.""" + origin = self._interaction_stream_origins.get(msg_id) + if not origin or msg_id in self._stream_ids: + return False + age = time.monotonic() - float(origin.get('created_at') or 0) + if age >= _INTERACTION_STREAM_MAX_AGE_SECONDS: + self._interaction_stream_origins.pop(msg_id, None) + return False + expected = origin.get('chat_id') if target_type == 'group' else origin.get('user_id') + if target_type not in {'group', 'person', 'private'} or str(expected or '') != target_id: + return False + stream_id = _generate_req_id('stream') + self._stream_ids[msg_id] = f'{origin["req_id"]}|{stream_id}' + self._stream_sessions[msg_id] = {**origin, 'stream_id': stream_id, 'stream_started': False} + self._prune_stream_state() + return True + + async def push_interaction_stream_chunk(self, msg_id: str, content: str, is_final: bool) -> bool: + first_frame = not self._stream_sessions.get(msg_id, {}).get('stream_started') + if await self.push_stream_chunk(msg_id, content, is_final=is_final): + if first_frame and (is_final or self._stream_sessions.get(msg_id, {}).get('stream_started')): + await self.logger.info(f'WeCom interaction reply stream accepted for message {msg_id}') + return True + await self.logger.warning(f'WeCom interaction reply stream unavailable for message {msg_id}') + self._stream_ids.pop(msg_id, None) + self._stream_last_content.pop(msg_id, None) + self._stream_sessions.pop(msg_id, None) + return False + def _prune_pending_forms(self) -> None: cutoff = time.monotonic() - _PENDING_FORM_TTL_SECONDS for task_id, pending in tuple(self._pending_forms_by_task.items()): @@ -267,6 +335,7 @@ class WecomBotWsClient: self._stream_latest_content.clear() self._stream_last_push_at.clear() self._stream_sessions.clear() + self._interaction_stream_origins.clear() self._feedback_sessions.clear() self._msg_feedback_ids.clear() self._pending_forms_by_task.clear() @@ -766,8 +835,13 @@ class WecomBotWsClient: # WeCom replaces the displayed stream content on each refresh, so # every frame must contain the complete snapshot, not only a delta. - await self.reply_stream(req_id, stream_id, next_content, finish=is_final, feedback_id=feedback_id) + ack = await self.reply_stream(req_id, stream_id, next_content, finish=is_final, feedback_id=feedback_id) + if not isinstance(ack, dict) or ack.get('errcode', 0) != 0: + detail = ack.get('errmsg', ack.get('errcode')) if isinstance(ack, dict) else 'no acknowledgement' + raise RuntimeError(f'WeCom stream frame rejected: {detail}') self._stream_last_content[msg_id] = next_content + if msg_id in self._stream_sessions: + self._stream_sessions[msg_id]['stream_started'] = True if is_final: self._completed_stream_content[msg_id] = hashlib.sha256(next_content.encode()).hexdigest() self._cap_mapping(self._completed_stream_content, _STREAM_CACHE_MAX) @@ -1009,15 +1083,11 @@ class WecomBotWsClient: 'user_id': message_data.get('userid', ''), 'chat_id': message_data.get('chatid', ''), 'chat_type': message_data.get('type', 'single'), + 'stream_started': False, + 'created_at': time.monotonic(), } + self._remember_interaction_stream_origin(msg_id, self._stream_sessions[msg_id]) self._prune_stream_state() - # Send an initial empty stream frame so the WeCom client - # shows its built-in loading spinner while the pipeline - # processes the message (e.g. RAG retrieval). - try: - await self.reply_stream(req_id, stream_id, '', finish=False) - except Exception: - await self.logger.warning(f'Failed to send initial stream frame: {traceback.format_exc()}') message_data['stream_id'] = stream_id message_data['req_id'] = req_id diff --git a/src/langbot/pkg/agent/runner/context_builder.py b/src/langbot/pkg/agent/runner/context_builder.py index 30544694d..4637ba221 100644 --- a/src/langbot/pkg/agent/runner/context_builder.py +++ b/src/langbot/pkg/agent/runner/context_builder.py @@ -249,19 +249,7 @@ class RunnerContextBuilder: 'timestamp': event.event_time or int(time.time()), } - # A legacy Tbox resume must use the persisted original bot, not a - # newly reconstructed callback envelope. Ordinary sender mode is unchanged. bot_id = event.bot_id - if event.event_type == 'interaction.submitted' and binding.runner_config.get('user-id-source') == 'legacy-bot': - identity = event.legacy_identity - bot_id = ( - identity.bot_id - if identity is not None - and identity.workspace_id == event.workspace_id - and identity.bot_id == event.bot_id - and identity.pipeline_id == (binding.processor_id or binding.agent_id) - else None - ) # Build conversation context from event conversation: ConversationContext | None = None diff --git a/src/langbot/pkg/agent/runner/events.py b/src/langbot/pkg/agent/runner/events.py index 4fa988244..4f422149c 100644 --- a/src/langbot/pkg/agent/runner/events.py +++ b/src/langbot/pkg/agent/runner/events.py @@ -15,16 +15,11 @@ GROUP_MEMBER_JOINED = 'group.member_joined' FRIEND_REQUEST_RECEIVED = 'friend.request_received' """A new friend/contact request was received.""" -INTERACTION_SUBMITTED = 'interaction.submitted' -"""A user submitted a Host-rendered structured interaction.""" - - RESERVED_EVENT_TYPES = frozenset( { MESSAGE_RECEIVED, MESSAGE_RECALLED, GROUP_MEMBER_JOINED, FRIEND_REQUEST_RECEIVED, - INTERACTION_SUBMITTED, } ) diff --git a/src/langbot/pkg/agent/runner/interaction_manager.py b/src/langbot/pkg/agent/runner/interaction_manager.py index efa09bb5d..0aeedac82 100644 --- a/src/langbot/pkg/agent/runner/interaction_manager.py +++ b/src/langbot/pkg/agent/runner/interaction_manager.py @@ -3,6 +3,7 @@ from __future__ import annotations import copy +import asyncio import json import time import typing @@ -10,16 +11,17 @@ import typing import pydantic from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionDeliveryCapabilities, + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) -from .descriptor import RunnerDescriptor from .errors import RunnerProtocolError -from .host_models import AgentBinding, AgentEventEnvelope, LegacyRunnerIdentity from .interaction_store import InteractionStore -INTERACTION_REQUESTED_ACTION = 'interaction.requested' -INTERACTION_DELIVERY_API = 'interaction.request' -INTERACTION_ACKNOWLEDGE_API = 'interaction.acknowledge' INTERACTION_PAYLOAD_MAX_BYTES = 256 * 1024 DEFAULT_INTERACTION_TTL_SECONDS = 30 * 60 MAX_INTERACTION_TTL_SECONDS = 24 * 60 * 60 @@ -69,7 +71,7 @@ class HostInteractionRequest(pydantic.BaseModel): fields: list[HostInteractionField] = pydantic.Field(default_factory=list, max_length=50) actions: list[HostInteractionAction] = pydantic.Field(default_factory=list, max_length=20) expires_at: int | None = None - fallback_text: str = pydantic.Field(min_length=1, max_length=20000) + fallback_text: str | None = pydantic.Field(default=None, min_length=1, max_length=20000) model_config = pydantic.ConfigDict(extra='forbid') @@ -81,6 +83,7 @@ class HostInteractionSubmission(pydantic.BaseModel): action_id: str | None = pydantic.Field(default=None, max_length=128) values: dict[str, typing.Any] = pydantic.Field(default_factory=dict) submitted_at: int | None = None + label: str | None = None model_config = pydantic.ConfigDict(extra='forbid') @@ -91,218 +94,376 @@ class InteractionManager: def __init__(self, ap: typing.Any, store: InteractionStore | None = None): self.ap = ap self.store = store or InteractionStore(ap.persistence_mgr.get_db_engine()) + self._waiters: dict[tuple[str, str], asyncio.Future[dict[str, typing.Any]]] = {} + self._waiter_scopes: dict[tuple[str, str], tuple[str, str]] = {} + self._responders: dict[tuple[str, str], str | list[str]] = {} + self._callback_contexts: dict[tuple[str, str], dict[str, typing.Any]] = {} + self._text_waiters: dict[tuple[str, str], tuple[str, str, str, str, InteractionRequest]] = {} - async def handle_result( + async def request_interaction( self, *, - result_dict: dict[str, typing.Any], - event: AgentEventEnvelope, - binding: AgentBinding, - descriptor: RunnerDescriptor, - run_id: str, - adapter_context: dict[str, typing.Any] | None, - ) -> bool: - """Execute an authorized interaction request; return whether it was consumed.""" - data = result_dict.get('data') - if not isinstance(data, dict) or data.get('action') != INTERACTION_REQUESTED_ACTION: - return False - - self._authorize(descriptor, binding) - payload = data.get('payload') - try: - request = HostInteractionRequest.model_validate(payload) - except pydantic.ValidationError as exc: - raise RunnerProtocolError(descriptor.id, f'invalid interaction request: {exc}') from exc - - processor_id = binding.processor_id or binding.agent_id - if not processor_id: - raise RunnerProtocolError(descriptor.id, 'interaction request has no stable processor identity') - adapter = self._resolve_adapter(adapter_context) - if adapter is None: - raise RunnerProtocolError(descriptor.id, 'interaction request has no delivery adapter') - - request_data = request.model_dump(mode='json') - now = int(time.time()) - expires_at = now + DEFAULT_INTERACTION_TTL_SECONDS if request.expires_at is None else request.expires_at - if expires_at <= now: - raise RunnerProtocolError(descriptor.id, 'interaction request is already expired') - if expires_at > now + MAX_INTERACTION_TTL_SECONDS: - raise RunnerProtocolError(descriptor.id, 'interaction request expiry exceeds 24 hours') - request_data['expires_at'] = expires_at - if len(json.dumps(request_data, ensure_ascii=False).encode('utf-8')) > INTERACTION_PAYLOAD_MAX_BYTES: - raise RunnerProtocolError(descriptor.id, 'interaction request exceeds 256 KiB') - self._validate_request_identity(request, descriptor.id) - reply_target = event.delivery.reply_target or {} - target_type = reply_target.get('target_type') - target_id = reply_target.get('target_id') - callback_conversation_id = f'{target_type}_{target_id}' if target_type and target_id else event.conversation_id - update_target = await self._find_update_target( - event=event, - binding=binding, - descriptor=descriptor, - processor_id=processor_id, - conversation_id=callback_conversation_id, + session: typing.Mapping[str, typing.Any], + adapter: typing.Any, + request_payload: dict[str, typing.Any], + timeout: float, + on_unsupported: str, + responders: str | list[str], + target_type: str | None = None, + target_id: str | None = None, + ) -> dict[str, typing.Any]: + """Deliver an interaction and wait for its validated callback in this run.""" + authorization = session['authorization'] + if not authorization.get('interactions_enabled') or not authorization.get('interactions_authorized'): + raise ValueError('Runner did not declare interaction capability and permission') + if not 0 < timeout <= MAX_INTERACTION_TTL_SECONDS: + raise ValueError('Interaction timeout must be within 24 hours') + if on_unsupported not in {'error', 'degrade'}: + raise ValueError('Invalid interaction fallback policy') + valid_responders = ( + responders in {'actor', 'any'} + if isinstance(responders, str) + else ( + isinstance(responders, list) + and bool(responders) + and all(isinstance(item, str) and item for item in responders) + ) ) + if not valid_responders: + raise ValueError('Invalid interaction responders') + + request = InteractionRequest.model_validate(request_payload) + if request.fields and request.actions: + raise ValueError('Interaction cannot combine fields and actions') + self._validate_request_identity( + HostInteractionRequest.model_validate(request.model_dump(mode='json')), session['runner_id'] + ) + run_id = session['run_id'] + key = (run_id, request.interaction_id) + bot_id = authorization.get('bot_id') + workspace_id = authorization.get('workspace_id') + workspace_waiters = sum(scope[0] == workspace_id for scope in self._waiter_scopes.values()) + bot_waiters = sum(scope == (workspace_id, bot_id) for scope in self._waiter_scopes.values()) + if workspace_waiters >= 256 or bot_waiters >= 32: + raise ValueError('Too many pending interactions') + if key in self._waiters: + raise ValueError('Interaction is already waiting') + platform_context = authorization.get('platform_context') or {} + delivery = platform_context.get('delivery') or {} + reply_target = delivery.get('reply_target') or {} + selected_type = target_type or reply_target.get('target_type') + selected_id = target_id or reply_target.get('target_id') + if not selected_type or not selected_id: + raise ValueError('Interaction has no delivery target') + if target_type is not None and (target_type, target_id) != ( + reply_target.get('target_type'), + reply_target.get('target_id'), + ): + from .platform_tools import resolve_platform_api_call + + resolve_platform_api_call( + session, + bot_id, + 'send_message', + { + 'target_type': target_type, + 'target_id': target_id, + 'message': platform_message.MessageChain( + [platform_message.Plain(text='Interaction request')] + ).model_dump(mode='json'), + }, + ) + actor = platform_context.get('actor') or {} + actor_id = actor.get('actor_id') + if responders == 'actor' and not actor_id: + raise ValueError('Interaction has no actor') + capabilities = adapter.get_interaction_capabilities() + if not isinstance(capabilities, InteractionDeliveryCapabilities): + capabilities = InteractionDeliveryCapabilities.model_validate(capabilities) + supported_apis = adapter.get_supported_apis() if callable(getattr(adapter, 'get_supported_apis', None)) else [] + if supported_apis and 'send_interaction' not in supported_apis: + capabilities = InteractionDeliveryCapabilities(text_fallback=capabilities.text_fallback) + if supported_apis and 'update_interaction' not in supported_apis: + capabilities.supports_updates = False + normalized, degraded, use_text, issues = self._normalize_request(request, capabilities, on_unsupported) + if issues: + return {'unsupported': issues} + request_data = normalized.model_dump(mode='json') + request_data['expires_at'] = int(time.time() + timeout + 1) + if len(json.dumps(request_data, ensure_ascii=False).encode('utf-8')) > INTERACTION_PAYLOAD_MAX_BYTES: + raise ValueError('Interaction request exceeds 256 KiB') + conversation_id = f'{selected_type}_{selected_id}' _, callback_token = await self.store.create_request( interaction_id=request.interaction_id, run_id=run_id, - binding_id=binding.binding_id, - runner_id=descriptor.id, - processor_type=binding.processor_type, - processor_id=processor_id, - request={ - **request_data, - '_host_legacy_identity': event.legacy_identity.model_dump(mode='json') - if event.legacy_identity is not None - else None, - }, - delivery_target=reply_target, - replaces_interaction_id=(update_target or {}).get('interaction_id'), - bot_id=event.bot_id, - workspace_id=event.workspace_id, - conversation_id=callback_conversation_id, - thread_id=event.thread_id, - actor_id=event.actor.actor_id if event.actor else None, - expires_at=expires_at, - **self._pipeline_admission(binding, descriptor, adapter_context), + binding_id=authorization['binding_id'], + runner_id=session['runner_id'], + processor_type=authorization['processor_type'], + processor_id=authorization['processor_id'], + request=request_data, + delivery_target={'target_type': selected_type, 'target_id': selected_id}, + bot_id=bot_id, + workspace_id=workspace_id, + conversation_id=conversation_id, + thread_id=authorization.get('thread_id'), + actor_id=actor_id if responders == 'actor' else None, + expires_at=request_data['expires_at'], + blocking=True, + **self._pipeline_tool_admission(session, authorization, session['runner_id']), ) - + future = asyncio.get_running_loop().create_future() + self._waiters[key] = future + self._responders[key] = responders + self._waiter_scopes[key] = (workspace_id, bot_id) + if use_text: + self._text_waiters[key] = (workspace_id, bot_id, conversation_id, callback_token, normalized) + runtime = session.get('runtime_context') + original_deadline = runtime.get('deadline_at') if isinstance(runtime, dict) else None + started_at = time.time() + if original_deadline is not None: + runtime['deadline_at'] = float(original_deadline) + timeout + 30 + handle = None + terminal = None try: - if self._supports_interaction_delivery(adapter): - delivery_params = { - 'request': request_data, - 'callback_token': callback_token, - 'reply_target': event.delivery.reply_target, - } - if update_target is not None: - delivery_params['update_target'] = update_target.get('delivery_result') + if use_text: + await adapter.send_message( + str(selected_type), + str(selected_id), + platform_message.MessageChain( + [platform_message.Plain(text=normalized.fallback_text or normalized.title)] + ), + ) + else: + handle = await adapter.send_interaction( + str(selected_type), + str(selected_id), + normalized, + callback_token, + reply_to=reply_target.get('message_id'), + ) + if isinstance(handle, dict): + handle = InteractionHandle.model_validate(handle) + await self.store.record_delivery_success(run_id, request.interaction_id, handle.model_dump(mode='json')) + try: + submission = await asyncio.wait_for(future, timeout=timeout) + terminal = 'submitted' + except asyncio.TimeoutError: + terminal = 'expired' + await self.store.mark_terminal(run_id, request.interaction_id, terminal) + submission = None + if handle is not None and capabilities.supports_updates: + handle.context['callback_context'] = self._callback_contexts.get(key, {}) try: - delivery_result = await adapter.call_platform_api( - INTERACTION_DELIVERY_API, - delivery_params, + await adapter.update_interaction( + handle, + terminal, + InteractionSubmission.model_validate(submission) if submission else None, ) except Exception as exc: - if update_target is None: - raise - self._warning(f'Interaction update failed; sending a new presentation: {exc}') - fallback_params = dict(delivery_params) - fallback_params.pop('update_target', None) - delivery_result = await adapter.call_platform_api( - INTERACTION_DELIVERY_API, - fallback_params, - ) - if isinstance(delivery_result, dict): - try: - await self.store.record_delivery_success( - run_id, - request.interaction_id, - delivery_result, - ) - except Exception as exc: - self._warning(f'Failed to persist interaction delivery result: {exc}') - else: - await self._deliver_fallback(adapter, event, request.fallback_text) - except Exception as exc: - await self.store.mark_delivery_failed(run_id, request.interaction_id, str(exc)) + self._warning(f'Failed to update interaction card: {exc}') + if original_deadline is not None: + runtime['deadline_at'] = float(original_deadline) + (time.time() - started_at) + return { + 'status': 'timeout' if terminal == 'expired' else 'submitted', + 'submission': submission, + 'degraded': degraded, + 'deadline_at': runtime.get('deadline_at') if isinstance(runtime, dict) else None, + } + except asyncio.CancelledError: + terminal = 'cancelled' + await self.store.mark_terminal(run_id, request.interaction_id, terminal) + if handle is not None and capabilities.supports_updates: + try: + await adapter.update_interaction(handle, terminal) + except Exception as exc: + self._warning(f'Failed to cancel interaction card: {exc}') raise - return True + except Exception as exc: + if terminal is None: + await self.store.mark_delivery_failed(run_id, request.interaction_id, str(exc)) + raise + finally: + if original_deadline is not None: + runtime['deadline_at'] = float(original_deadline) + (time.time() - started_at) + self._waiters.pop(key, None) + self._responders.pop(key, None) + self._callback_contexts.pop(key, None) + self._text_waiters.pop(key, None) + self._waiter_scopes.pop(key, None) @staticmethod - def _pipeline_admission(binding, descriptor, adapter_context): - if binding.processor_type != 'pipeline': + def _normalize_request(request, capabilities, policy): + normalized = request.model_copy(deep=True) + issues = [] + degraded = [] + native = bool(capabilities.field_types or capabilities.max_actions or capabilities.action_styles) + if not native: + issues.append({'path': 'platform', 'reason': 'native_interactions_unavailable'}) + for index, field in enumerate(request.fields): + if field.type not in capabilities.field_types: + issues.append({'path': f'fields[{index}].type', 'reason': 'unsupported_field_type'}) + if capabilities.max_options is not None and len(field.options) > capabilities.max_options: + issues.append({'path': f'fields[{index}].options', 'reason': 'too_many_options'}) + if field.placeholder: + degraded.append( + {'path': f'fields[{index}].placeholder', 'reason': 'unsupported_placeholder', 'applied': 'omit'} + ) + normalized.fields[index].placeholder = None + if field.default is not None: + degraded.append( + {'path': f'fields[{index}].default', 'reason': 'unsupported_default', 'applied': 'omit'} + ) + normalized.fields[index].default = None + if capabilities.max_fields is not None and len(request.fields) > capabilities.max_fields: + issues.append({'path': 'fields', 'reason': 'too_many_fields'}) + if capabilities.max_actions is not None and len(request.actions) > capabilities.max_actions: + issues.append({'path': 'actions', 'reason': 'too_many_actions'}) + for index, action in enumerate(request.actions): + if action.style not in capabilities.action_styles: + degraded.append( + {'path': f'actions[{index}].style', 'reason': 'unsupported_style', 'applied': 'default'} + ) + normalized.actions[index].style = 'default' + if request.description and not capabilities.supports_markdown: + degraded.append({'path': 'description', 'reason': 'unsupported_markdown', 'applied': 'literal_text'}) + if issues and policy == 'error': + return normalized, degraded, False, issues + if issues and ( + not capabilities.text_fallback + or len(request.fields) > 1 + or any(field.type in {'file', 'multiselect'} for field in request.fields) + ): + return normalized, degraded, False, issues + use_text = bool(issues) + fallback_text = request.fallback_text or request.title + if use_text and request.actions: + choices = ' / '.join(f'{index + 1} {action.label}' for index, action in enumerate(request.actions)) + fallback_text = f'{fallback_text}\n{choices}' + elif use_text and request.fields: + field = request.fields[0] + fallback_text = f'{fallback_text}\n{field.label}' + if field.type == 'select': + fallback_text += '\n' + ' / '.join( + f'{index + 1} {option.label}' for index, option in enumerate(field.options) + ) + normalized.fallback_text = fallback_text + return ( + normalized, + degraded + + ( + [{'path': 'platform', 'reason': 'unsupported_structure', 'applied': 'text_fallback'}] + if use_text + else [] + ), + use_text, + [], + ) + + def wake_waiter( + self, + record: dict[str, typing.Any], + actor_id: str | None, + callback_context: dict[str, typing.Any] | None = None, + ) -> bool: + key = (record['run_id'], record['interaction_id']) + future = self._waiters.get(key) + if future is None or future.done(): + return False + responders = self._responders[key] + if isinstance(responders, list) and actor_id not in responders: + raise ValueError('Interaction actor is not an allowed responder') + self._callback_contexts[key] = callback_context or {} + future.set_result(record['submission']) + return True + + def waiting_run_ids(self) -> set[str]: + return {run_id for (run_id, _), future in self._waiters.items() if not future.done()} + + async def consume_text_message( + self, + *, + workspace_id: str, + bot_id: str, + conversation_id: str, + actor_id: str, + text: str, + ) -> bool: + answer = text.strip() + if not answer or len(answer) > 20000: + return False + for key, (workspace, bot, conversation, token, request) in reversed(list(self._text_waiters.items())): + if (workspace, bot, conversation) != (workspace_id, bot_id, conversation_id): + continue + responders = self._responders.get(key) + if responders == 'actor': + pending = await self.store.get_by_callback_token(token) + if pending is None or pending.get('actor_id') != actor_id: + continue + elif isinstance(responders, list) and actor_id not in responders: + continue + submission: dict[str, typing.Any] = {'interaction_id': request.interaction_id, 'values': {}} + if request.actions: + if not answer.isdigit() or not 1 <= int(answer) <= len(request.actions): + return False + submission['action_id'] = request.actions[int(answer) - 1].id + submission['label'] = request.actions[int(answer) - 1].label + elif request.fields: + field = request.fields[0] + value: typing.Any = answer + if field.type == 'number': + try: + value = float(answer) + except ValueError: + return False + elif field.type == 'boolean': + if answer.lower() not in {'yes', 'no', 'true', 'false', '1', '0'}: + return False + value = answer.lower() in {'yes', 'true', '1'} + elif field.type == 'select': + options = field.options + if answer.isdigit() and 1 <= int(answer) <= len(options): + value = options[int(answer) - 1].value + elif answer not in {option.value for option in options}: + return False + submission['values'] = {field.id: value} + record = await self.consume_callback( + callback_token=token, + submission=submission, + bot_id=bot_id, + conversation_id=conversation_id, + actor_id=actor_id, + ) + return self.wake_waiter(record, actor_id) + return False + + @staticmethod + def _pipeline_tool_admission(session, authorization, runner_id): + if authorization.get('processor_type') != 'pipeline': return {} - query = (adapter_context or {}).get('_query') - expected = copy.deepcopy((adapter_context or {}).get('_pipeline_expected_config')) - session = getattr(query, 'session', None) - conversation = (adapter_context or {}).get('_pipeline_conversation') + + query = session.get('execution_query') + expected = copy.deepcopy(getattr(query, 'pipeline_config', None)) + query_session = getattr(query, 'session', None) + conversation = getattr(query_session, 'using_conversation', None) + processor_id = str(authorization.get('processor_id') or '').strip() def authority(): from .config_resolver import RunnerConfigResolver + current_config = getattr(query, 'pipeline_config', None) return ( query is not None - and session is not None + and query_session is not None and conversation is not None and isinstance(expected, dict) - and session.using_conversation is conversation - and getattr(query, 'pipeline_uuid', None) == binding.processor_id - and RunnerConfigResolver.resolve_runner_id(expected) == descriptor.id == binding.runner_id - and RunnerConfigResolver.resolve_runner_config(expected, descriptor.id) == binding.runner_config + and query_session.using_conversation is conversation + and getattr(query, 'pipeline_uuid', None) == processor_id + and current_config == expected + and RunnerConfigResolver.resolve_runner_id(expected) == runner_id ) return {'expected_config': expected, 'authority_check': authority} - async def restore_legacy_identity(self, event: AgentEventEnvelope, binding: AgentBinding) -> None: - """Resume only from the scoped, consumed Host record, never callback fields.""" - event.legacy_identity = None - submission = getattr(event.input, 'interaction', None) - if submission is None: - return - if hasattr(submission, 'model_dump'): - submission = submission.model_dump(mode='json') - record = await self.store.find_resume_request(event=event, binding=binding, submission=submission) - if record is None: - return - identity = record['request'].get('_host_legacy_identity') - if not isinstance(identity, dict): - return - try: - event.legacy_identity = LegacyRunnerIdentity.model_validate(identity) - except pydantic.ValidationError: - return - - async def acknowledge_submission(self, record: dict[str, typing.Any], adapter: typing.Any) -> None: - """Best-effort transition of submitted controls into a read-only state.""" - delivery_result = record.get('delivery_result') - if not isinstance(delivery_result, dict) or not self._supports_platform_api( - adapter, INTERACTION_ACKNOWLEDGE_API - ): - return - try: - delivery_result = await adapter.call_platform_api( - INTERACTION_ACKNOWLEDGE_API, - { - 'request': record.get('request') or {}, - 'submission': record.get('submission') or {}, - 'update_target': delivery_result, - }, - ) - if isinstance(delivery_result, dict): - await self.store.record_delivery_success( - record['run_id'], - record['interaction_id'], - delivery_result, - ) - except Exception as exc: - self._warning(f'Failed to acknowledge interaction submission: {exc}') - - async def _find_update_target( - self, - *, - event: AgentEventEnvelope, - binding: AgentBinding, - descriptor: RunnerDescriptor, - processor_id: str, - conversation_id: str | None, - ) -> dict[str, typing.Any] | None: - capabilities = getattr(event.delivery, 'interactions', None) - if not capabilities or not getattr(capabilities, 'supports_updates', False): - return None - prior = getattr(event.input, 'interaction', None) - prior_interaction_id = getattr(prior, 'interaction_id', None) - if not prior_interaction_id: - return None - return await self.store.find_update_target( - interaction_id=str(prior_interaction_id), - binding_id=binding.binding_id, - runner_id=descriptor.id, - processor_type=binding.processor_type, - processor_id=processor_id, - bot_id=event.bot_id, - conversation_id=conversation_id, - actor_id=event.actor.actor_id if event.actor else None, - ) - @staticmethod def _validate_request_identity(request: HostInteractionRequest, runner_id: str) -> None: field_ids = [field.id for field in request.fields] @@ -339,6 +500,9 @@ class InteractionManager: from .interaction_store import InteractionNotFoundError raise InteractionNotFoundError('Unknown interaction callback token') + responders = self._responders.get((pending['run_id'], pending['interaction_id'])) + if isinstance(responders, list) and actor_id not in responders: + raise ValueError('Interaction actor is not an allowed responder') normalized_submission = self._resolve_submission_refs(pending, submission) try: normalized = HostInteractionSubmission.model_validate(normalized_submission) @@ -440,53 +604,8 @@ class InteractionManager: if any(selected not in allowed_values for selected in selected_values): raise ValueError(f'interaction submission option is not present in the request: {field_id}') - @staticmethod - def _authorize(descriptor: RunnerDescriptor, binding: AgentBinding) -> None: - supports_interactions = bool(getattr(descriptor.capabilities, 'interactions', False)) - permissions = set(getattr(descriptor.permissions, 'interactions', []) or []) - if not supports_interactions or 'request' not in permissions: - raise RunnerProtocolError(descriptor.id, 'runner did not declare interaction capability and permission') - if not binding.delivery_policy.enable_interactions: - raise RunnerProtocolError(descriptor.id, 'binding delivery policy does not allow interactions') - - @staticmethod - def _resolve_adapter(adapter_context: dict[str, typing.Any] | None) -> typing.Any | None: - if not adapter_context: - return None - query = adapter_context.get('_query') - if query is not None and getattr(query, 'adapter', None) is not None: - return query.adapter - return adapter_context.get('_delivery_adapter') - - @staticmethod - def _supports_interaction_delivery(adapter: typing.Any) -> bool: - return InteractionManager._supports_platform_api(adapter, INTERACTION_DELIVERY_API) - - @staticmethod - def _supports_platform_api(adapter: typing.Any, api_name: str) -> bool: - get_supported_apis = getattr(adapter, 'get_supported_apis', None) - if not callable(get_supported_apis): - return False - try: - return api_name in (get_supported_apis() or []) - except Exception: - return False - def _warning(self, message: str) -> None: logger = getattr(self.ap, 'logger', None) warning = getattr(logger, 'warning', None) if callable(warning): warning(message) - - @staticmethod - async def _deliver_fallback(adapter: typing.Any, event: AgentEventEnvelope, text: str) -> None: - target = event.delivery.reply_target or {} - target_type = target.get('target_type') - target_id = target.get('target_id') - if not target_type or not target_id: - raise ValueError('interaction fallback has no reply target') - await adapter.send_message( - str(target_type), - str(target_id), - platform_message.MessageChain([platform_message.Plain(text=text)]), - ) diff --git a/src/langbot/pkg/agent/runner/interaction_store.py b/src/langbot/pkg/agent/runner/interaction_store.py index 22bc21eb6..f1df825ed 100644 --- a/src/langbot/pkg/agent/runner/interaction_store.py +++ b/src/langbot/pkg/agent/runner/interaction_store.py @@ -126,6 +126,7 @@ class InteractionStore: expires_at: int | float | None = None, expected_config: dict | None = None, authority_check: typing.Callable[[], bool] | None = None, + blocking: bool = False, ) -> tuple[dict[str, typing.Any], str]: """Persist a request and return its record plus one-time callback token.""" if not interaction_id or not run_id or not binding_id or not runner_id or not processor_id: @@ -154,6 +155,7 @@ class InteractionStore: thread_id=thread_id, actor_id=actor_id, status='pending', + status_reason='blocking' if blocking else None, request_json=request_json, delivery_target_json=delivery_target_json, replaces_interaction_id=replaces_interaction_id, @@ -221,79 +223,6 @@ class InteractionStore: await session.commit() return result.rowcount == 1 - async def find_update_target( - self, - *, - interaction_id: str, - binding_id: str, - runner_id: str, - processor_type: str, - processor_id: str, - bot_id: str | None, - conversation_id: str | None, - actor_id: str | None, - ) -> dict[str, typing.Any] | None: - """Find a submitted interaction whose platform presentation can be replaced.""" - if not interaction_id: - return None - conditions = [ - AgentInteraction.interaction_id == interaction_id, - AgentInteraction.binding_id == binding_id, - AgentInteraction.runner_id == runner_id, - AgentInteraction.processor_type == processor_type, - AgentInteraction.processor_id == processor_id, - AgentInteraction.status == 'submitted', - AgentInteraction.delivery_result_json.is_not(None), - ] - for column, value in ( - (AgentInteraction.bot_id, bot_id), - (AgentInteraction.conversation_id, conversation_id), - (AgentInteraction.actor_id, actor_id), - ): - conditions.append(column.is_(None) if value is None else column == value) - - async with self._session_factory() as session: - result = await session.execute( - sqlalchemy.select(AgentInteraction) - .where(*conditions) - .order_by(AgentInteraction.submitted_at.desc(), AgentInteraction.id.desc()) - .limit(1) - ) - row = result.scalar_one_or_none() - return self._to_dict(row) if row is not None else None - - async def find_resume_request(self, *, event, binding, submission) -> dict[str, typing.Any] | None: - """Resolve persisted provenance with exact tenant/processor/callback scope. - - Ambiguous identities fail closed instead of picking the newest run. - """ - if not isinstance(submission, dict) or not submission.get('interaction_id'): - return None - target = event.delivery.reply_target or {} - target_type, target_id = target.get('target_type'), target.get('target_id') - conversation_id = f'{target_type}_{target_id}' if target_type and target_id else event.conversation_id - conditions = [ - AgentInteraction.interaction_id == submission['interaction_id'], - AgentInteraction.status == 'submitted', - AgentInteraction.binding_id == binding.binding_id, - AgentInteraction.runner_id == binding.runner_id, - AgentInteraction.processor_type == binding.processor_type, - AgentInteraction.processor_id == (binding.processor_id or binding.agent_id), - ] - for column, value in ( - (AgentInteraction.workspace_id, event.workspace_id), - (AgentInteraction.bot_id, event.bot_id), - (AgentInteraction.conversation_id, conversation_id), - (AgentInteraction.thread_id, event.thread_id), - (AgentInteraction.actor_id, event.actor.actor_id if event.actor else None), - ): - conditions.append(column.is_(None) if value is None else column == value) - async with self._session_factory() as session: - result = await session.execute(sqlalchemy.select(AgentInteraction).where(*conditions)) - records = [self._to_dict(row) for row in result.scalars()] - matches = [record for record in records if record['submission'] == submission] - return matches[0] if len(matches) == 1 else None - async def get_request(self, run_id: str, interaction_id: str) -> dict[str, typing.Any] | None: """Return a request by the runner-visible identity.""" async with self._session_factory() as session: @@ -394,6 +323,36 @@ class InteractionStore: await session.commit() return result.rowcount == 1 + async def mark_terminal(self, run_id: str, interaction_id: str, status: str) -> bool: + if status not in {'expired', 'cancelled'}: + raise ValueError('Invalid terminal interaction status') + now = _utc_now() + async with self._session_factory() as session: + result = await session.execute( + sqlalchemy.update(AgentInteraction) + .where( + AgentInteraction.run_id == run_id, + AgentInteraction.interaction_id == interaction_id, + AgentInteraction.status == 'pending', + ) + .values(status=status, status_reason=f'interaction {status}', updated_at=_db_datetime(now)) + ) + await session.commit() + return result.rowcount == 1 + + async def cancel_orphaned_pending(self, active_run_ids: set[str]) -> int: + """Invalidate pending callbacks after Host restart or run cleanup.""" + now = _utc_now() + condition = ~AgentInteraction.run_id.in_(active_run_ids) if active_run_ids else sqlalchemy.true() + async with self._session_factory() as session: + result = await session.execute( + sqlalchemy.update(AgentInteraction) + .where(AgentInteraction.status == 'pending', AgentInteraction.status_reason == 'blocking', condition) + .values(status='cancelled', status_reason='run is no longer active', updated_at=_db_datetime(now)) + ) + await session.commit() + return int(result.rowcount or 0) + async def expire_pending(self, *, now: datetime.datetime | None = None) -> int: """Expire pending interactions whose deadline has elapsed.""" cutoff = _as_utc(now) or _utc_now() diff --git a/src/langbot/pkg/agent/runner/invoker.py b/src/langbot/pkg/agent/runner/invoker.py index c4e54307b..53e92582a 100644 --- a/src/langbot/pkg/agent/runner/invoker.py +++ b/src/langbot/pkg/agent/runner/invoker.py @@ -94,17 +94,33 @@ class RunnerInvoker: await self._close_generator(gen, descriptor) raise asyncio.TimeoutError + next_result = asyncio.create_task(anext(gen)) try: - if remaining is None: - return await anext(gen) - return await asyncio.wait_for(anext(gen), timeout=remaining) + while True: + if remaining is None: + return await next_result + try: + return await asyncio.wait_for(asyncio.shield(next_result), timeout=remaining) + except asyncio.TimeoutError: + # The Host can extend the deadline while a blocking interaction + # is active. Keep the same pending read when that happens. + renewed = self._remaining_deadline_seconds(context) + if renewed is None or renewed <= 0: + raise + remaining = renewed except StopAsyncIteration: if self._is_deadline_exhausted(context): raise asyncio.TimeoutError raise except asyncio.TimeoutError: + next_result.cancel() + await asyncio.gather(next_result, return_exceptions=True) await self._close_generator(gen, descriptor) raise + finally: + if not next_result.done(): + next_result.cancel() + await asyncio.gather(next_result, return_exceptions=True) def _remaining_deadline_seconds( self, diff --git a/src/langbot/pkg/agent/runner/orchestrator.py b/src/langbot/pkg/agent/runner/orchestrator.py index 23706f9e9..6889de784 100644 --- a/src/langbot/pkg/agent/runner/orchestrator.py +++ b/src/langbot/pkg/agent/runner/orchestrator.py @@ -5,15 +5,17 @@ from __future__ import annotations import time import asyncio import contextlib +import re import copy import typing +from uuid import uuid4 from langbot_plugin.api.entities.builtin.provider import message as provider_message from langbot_plugin.api.entities.builtin.provider import prompt as provider_prompt from langbot_plugin.api.entities.builtin.pipeline import query as pipeline_query from langbot_plugin.entities.io.actions.enums import PluginToRuntimeAction -from .reply_stream import ReplyStreamSession +from .reply_stream import ReplyStreamRequest, ReplyStreamSession from ...core import app from ...i18n import t from ...i18n.workspace import get_workspace_language @@ -36,7 +38,7 @@ from .interaction_manager import InteractionManager from .query_bridge import QueryRunBridge from .registry import RunnerRegistry from .resource_builder import AgentResourceBuilder -from .platform_tools import freeze_platform_context +from .platform_tools import PLATFORM_TOOLS_BY_NAME, freeze_platform_context from .result_normalizer import AgentResultNormalizer from .run_journal import AgentRunJournal from .session_registry import AgentRunSessionRegistry, get_session_registry @@ -49,6 +51,14 @@ from ...telemetry.execution import close_trace as close_execution_trace from ...telemetry.execution import record as record_execution +def _visible_auto_reply_text(content: str) -> str: + visible = re.sub(r'.*?(?:|$)', '', content, flags=re.IGNORECASE | re.DOTALL) + for size in range(min(7, len(visible)), 0, -1): + if any(tag.startswith(visible[-size:].lower()) for tag in ('', '')): + return visible[:-size] + return visible + + class AgentRunOrchestrator: """Coordinate one Runner execution. @@ -126,12 +136,6 @@ class AgentRunOrchestrator: project_mcp_resource_config(execution_query, binding.runner_config) object.__setattr__(execution_query, '_execution_context', execution_context) - if event.event_type == 'interaction.submitted' and binding.runner_config.get('user-id-source') in ( - 'legacy-session', - 'legacy-bot', - ): - await self.interaction_manager.restore_legacy_identity(event, binding) - from ...box.runner import prepare_input_files event = event.model_copy(deep=True) @@ -250,6 +254,21 @@ class AgentRunOrchestrator: terminal_usage: dict[str, typing.Any] | None = None execution_outcome = 'unknown' execution_error = '' + auto_reply_enabled = ( + binding.processor_type == 'agent' + and binding.delivery_policy.enable_reply + and event.event_type == 'message.received' + and reply_streams.adapter is not None + ) + auto_reply_stream_id = uuid4() + auto_reply_stream_text = '' + auto_reply_stream_open = False + auto_reply_cumulative_text = '' + auto_reply_prefix = '' + auto_reply_deferred = False + explicit_event_reply_sent = False + explicit_reply_text: str | None = None + pending_explicit_replies: dict[str, str] = {} # A run reached without a platform ingress (WebUI debug, service API) # owns its own chain; a run inside an ingress reuses that chain. trace_binding: trace_mod.TraceBinding | None = None @@ -292,6 +311,15 @@ class AgentRunOrchestrator: execution_query=execution_query, platform_context=freeze_platform_context(event), reply_streams=reply_streams, + binding_id=binding.binding_id, + processor_type=binding.processor_type, + processor_id=binding.processor_id or binding.agent_id, + interactions_enabled=binding.delivery_policy.enable_interactions, + interactions_authorized=( + bool(getattr(descriptor.capabilities, 'interactions', False)) + and 'request' in (getattr(descriptor.permissions, 'interactions', []) or []) + ), + runtime_context=context.get('runtime'), ) event_log_id = await self.journal.write_event_log( @@ -355,6 +383,41 @@ class AgentRunOrchestrator: ): continue + if result_type == 'tool.call.started': + result_data = result_dict.get('data') or {} + tool_definition = PLATFORM_TOOLS_BY_NAME.get(result_data.get('tool_name')) + parameters = result_data.get('parameters') or {} + if tool_definition is not None and tool_definition.api == 'send_message': + text = parameters.get('text') if isinstance(parameters, dict) else None + if isinstance(text, str): + pending_explicit_replies[str(result_data.get('tool_call_id') or '')] = text + + if result_type == 'tool.call.completed' and auto_reply_enabled: + if auto_reply_stream_open: + await reply_streams.apply( + ReplyStreamRequest( + stream_id=auto_reply_stream_id, + operation='finish', + text=auto_reply_stream_text, + ) + ) + auto_reply_prefix = auto_reply_cumulative_text + auto_reply_stream_id = uuid4() + auto_reply_stream_text = '' + auto_reply_stream_open = False + result_data = result_dict.get('data') or {} + tool_definition = PLATFORM_TOOLS_BY_NAME.get(result_data.get('tool_name')) + auto_reply_deferred = ( + tool_definition is not None + and tool_definition.api == 'send_message' + and not result_data.get('error') + ) + if auto_reply_deferred and result_data.get('tool_name') == 'event_reply': + explicit_event_reply_sent = True + explicit_reply_text = pending_explicit_replies.pop( + str(result_data.get('tool_call_id') or ''), None + ) + journal_started = time.monotonic() await self.journal.append_run_result( result_dict=result_dict, @@ -386,17 +449,6 @@ class AgentRunOrchestrator: await self.result_normalizer.normalize(result_dict, descriptor) continue - if result_type == 'action.requested': - if await self.interaction_manager.handle_result( - result_dict=result_dict, - event=event, - binding=binding, - descriptor=descriptor, - run_id=run_id, - adapter_context=adapter_context, - ): - continue - if result_type == 'run.completed': terminal_status = 'completed' terminal_reason = ( @@ -441,6 +493,65 @@ class AgentRunOrchestrator: async with binding_for(execution_query).lock: result.attachments = exported_message(execution_query, file_ids, consume=True) + if auto_reply_enabled and not explicit_event_reply_sent and result is not None: + if result_type == 'message.delta' and isinstance(result, provider_message.MessageChunk): + cumulative_text = result.all_content or result.content + if isinstance(cumulative_text, str): + reply_text = _visible_auto_reply_text(cumulative_text) + if auto_reply_prefix and cumulative_text.startswith(auto_reply_prefix): + visible_prefix = _visible_auto_reply_text(auto_reply_prefix) + if reply_text.startswith(visible_prefix): + reply_text = reply_text[len(visible_prefix) :] + else: + auto_reply_prefix = '' + auto_reply_cumulative_text = cumulative_text + auto_reply_stream_text = reply_text + if reply_text.strip() and not auto_reply_deferred: + await reply_streams.apply( + ReplyStreamRequest( + stream_id=auto_reply_stream_id, + operation='update', + text=reply_text, + ) + ) + auto_reply_stream_open = True + elif has_completed_message: + reply_text = result.content + if isinstance(reply_text, str): + reply_text = _visible_auto_reply_text(reply_text) + if auto_reply_prefix and result.content.startswith(auto_reply_prefix): + visible_prefix = _visible_auto_reply_text(auto_reply_prefix) + if reply_text.startswith(visible_prefix): + reply_text = reply_text[len(visible_prefix) :] + if reply_text.strip() and ( + not auto_reply_deferred + or explicit_reply_text is None + or reply_text.strip() != explicit_reply_text.strip() + ): + await reply_streams.apply( + ReplyStreamRequest( + stream_id=auto_reply_stream_id, + operation='finish', + text=reply_text, + ) + ) + auto_reply_stream_id = uuid4() + auto_reply_stream_text = '' + auto_reply_stream_open = False + auto_reply_prefix = auto_reply_cumulative_text + auto_reply_deferred = False + explicit_reply_text = None + + if auto_reply_enabled and result_type == 'run.completed' and auto_reply_stream_open: + await reply_streams.apply( + ReplyStreamRequest( + stream_id=auto_reply_stream_id, + operation='finish', + text=auto_reply_stream_text, + ) + ) + auto_reply_stream_open = False + if result is not None: yield result @@ -697,6 +808,59 @@ class AgentRunOrchestrator: self.ap.logger.info(f'Claimed event {event.event_id} as steering input for run {target_run_id}') return True + async def try_claim_steering_from_event( + self, + event: AgentEventEnvelope, + binding: AgentBinding, + execution_context: ExecutionContext, + ) -> bool: + """Route a new platform message to an Agent waiting for interaction.""" + if event.event_type != 'message.received' or not event.conversation_id: + return False + waiting_run_ids = self.interaction_manager.waiting_run_ids() + if not waiting_run_ids: + return False + descriptor = await self.registry.get(execution_context, binding.runner_id) + if not descriptor.supports_steering(): + return False + target_run_id = await self._session_registry.find_steering_target( + conversation_id=event.conversation_id, + runner_id=descriptor.id, + bot_id=event.bot_id, + workspace_id=event.workspace_id, + thread_id=event.thread_id, + binding_id=binding.binding_id, + eligible_run_ids=waiting_run_ids, + ) + if target_run_id is None: + return False + steering_item = self._build_steering_item(event, target_run_id, descriptor.id) + if not await self._session_registry.enqueue_steering(target_run_id, steering_item): + return False + try: + event_log_id = await self.journal.write_event_log( + event=event, + binding=binding, + run_id=target_run_id, + runner_id=descriptor.id, + metadata={ + 'steering': { + 'status': 'queued', + 'trigger_behavior': 'absorbed_into_active_run', + 'claimed_by_run_id': target_run_id, + 'claimed_runner_id': descriptor.id, + 'claimed_at': steering_item.get('claimed_at'), + } + }, + ) + await self.journal.write_user_transcript(event, event_log_id) + except Exception as exc: + self.ap.logger.warning( + f'Failed to persist steering event {event.event_id} for run {target_run_id}: {exc}', + exc_info=True, + ) + return True + def _build_steering_item( self, event: AgentEventEnvelope, diff --git a/src/langbot/pkg/agent/runner/platform_tools.py b/src/langbot/pkg/agent/runner/platform_tools.py index b744f865b..ef93ab84d 100644 --- a/src/langbot/pkg/agent/runner/platform_tools.py +++ b/src/langbot/pkg/agent/runner/platform_tools.py @@ -4,7 +4,9 @@ from __future__ import annotations import copy import fnmatch +import time import typing +import uuid from dataclasses import dataclass import langbot_plugin.api.entities.builtin.platform.message as platform_message @@ -44,8 +46,78 @@ _TARGET_TYPE = {'type': 'string', 'enum': ['person', 'group']} _CHAT_TYPE = {'type': 'string', 'enum': ['person', 'private', 'group']} _APPROVE = {'type': 'boolean', 'description': 'true to accept; false to reject'} +PRESENT_INTERACTIVE_CARD_TOOL = 'request_interaction' + +_INTERACTION_OPTION_SCHEMA = { + 'type': 'object', + 'properties': { + 'value': {'type': 'string', 'minLength': 1, 'maxLength': 512}, + 'label': {'type': 'string', 'minLength': 1, 'maxLength': 512}, + 'description': {'type': 'string', 'maxLength': 2000}, + }, + 'required': ['value', 'label'], + 'additionalProperties': False, +} +_INTERACTION_FIELD_SCHEMA = { + 'type': 'object', + 'properties': { + 'id': {'type': 'string', 'minLength': 1, 'maxLength': 128}, + 'label': {'type': 'string', 'minLength': 1, 'maxLength': 512}, + 'type': { + 'type': 'string', + 'enum': ['text', 'textarea', 'select', 'multiselect', 'number', 'boolean', 'file'], + }, + 'required': {'type': 'boolean'}, + 'options': {'type': 'array', 'items': _INTERACTION_OPTION_SCHEMA, 'maxItems': 100}, + 'placeholder': {'type': 'string', 'maxLength': 2000}, + 'default': {}, + }, + 'required': ['id', 'label', 'type'], + 'additionalProperties': False, +} +_INTERACTION_ACTION_SCHEMA = { + 'type': 'object', + 'properties': { + 'id': {'type': 'string', 'minLength': 1, 'maxLength': 128}, + 'label': {'type': 'string', 'minLength': 1, 'maxLength': 512}, + 'style': {'type': 'string', 'enum': ['default', 'primary', 'danger']}, + }, + 'required': ['id', 'label'], + 'additionalProperties': False, +} + PLATFORM_TOOL_DEFINITIONS: tuple[PlatformToolDefinition, ...] = ( + PlatformToolDefinition( + PRESENT_INTERACTIVE_CARD_TOOL, + 'send_interaction', + 'event', + 'interaction', + 'write', + {'en_US': 'Request user interaction'}, + { + 'en_US': ( + 'Present a native interactive card in the current conversation. Define semantic buttons, selects, ' + 'and input fields; LangBot owns the target, callback token, validation, and platform rendering. ' + 'Each card is one step: provide either actions or fields, never both. ' + 'The tool waits for the user and returns the structured submission in this run.' + ), + }, + _object_schema( + { + 'kind': {'type': 'string', 'enum': ['form', 'confirmation', 'choice']}, + 'title': {'type': 'string', 'minLength': 1, 'maxLength': 1000}, + 'description': {'type': 'string', 'maxLength': 10000}, + 'fields': {'type': 'array', 'items': _INTERACTION_FIELD_SCHEMA, 'maxItems': 50}, + 'actions': {'type': 'array', 'items': _INTERACTION_ACTION_SCHEMA, 'maxItems': 20}, + 'expires_in_seconds': {'type': 'integer', 'minimum': 60, 'maximum': 86400}, + 'responders': {'type': 'string', 'enum': ['actor', 'any']}, + }, + ['title'], + ), + ('message.*',), + 'reply_target', + ), PlatformToolDefinition( 'event_reply', 'send_message', @@ -55,12 +127,12 @@ PLATFORM_TOOL_DEFINITIONS: tuple[PlatformToolDefinition, ...] = ( {'zh_Hans': '回复当前会话', 'en_US': 'Reply to current conversation'}, { 'zh_Hans': '向触发当前事件的会话发送回复或任务进度。目标由 LangBot 固定,Agent 无法改写。' - '需要发送消息时请调用此工具,Agent 的输出文本不会自动发送。', + '需要显式发送消息时请调用此工具;独立 Agent 的文本输出也可能自动回复。', 'en_US': 'Send a reply or task progress to the conversation that triggered this run. LangBot fixes the target. ' - 'Call this tool to send a message; Agent output text is not sent automatically.', + 'Call this tool to send an explicit message. Direct Agent text output may also be delivered automatically.', }, _object_schema({'text': {**_TEXT, 'description': 'Reply text'}}, ['text']), - ('message.*', 'friend.*', 'group.*', 'feedback.*', 'interaction.submitted'), + ('message.*', 'friend.*', 'group.*', 'feedback.*'), 'reply_target', ), PlatformToolDefinition( @@ -211,9 +283,9 @@ PLATFORM_TOOL_DEFINITIONS: tuple[PlatformToolDefinition, ...] = ( 'write', {'zh_Hans': '发送消息', 'en_US': 'Send message'}, { - 'zh_Hans': '使用当前机器人向指定用户或群组发送回复或任务进度。Agent 的输出文本不会自动发送。', + 'zh_Hans': '使用当前机器人向指定用户或群组发送回复或任务进度。独立 Agent 的文本输出也可能自动回复。', 'en_US': 'Send a reply or task progress to a specified person or group using the current bot. ' - 'Agent output text is not sent automatically.', + 'Direct Agent text output may also be delivered automatically.', }, _object_schema( {'target_type': _TARGET_TYPE, 'target_id': _ID, 'text': _TEXT}, ['target_type', 'target_id', 'text'] @@ -465,10 +537,14 @@ def build_platform_tool_resources( reason = None if definition is None: reason = 'unknown_tool' - elif definition.api not in supported_apis and not ( - definition.name == 'event_reply' - and {'reply_message', 'get_message'} <= supported_apis - and (event.delivery.reply_target or {}).get('message_id') + elif ( + definition.api not in supported_apis + and not (definition.name == PRESENT_INTERACTIVE_CARD_TOOL and 'send_message' in supported_apis) + and not ( + definition.name == 'event_reply' + and {'reply_message', 'get_message'} <= supported_apis + and (event.delivery.reply_target or {}).get('message_id') + ) ): reason = 'adapter_api_unsupported' elif definition.scope == 'event' and not _event_matches(event.event_type, definition.event_patterns): @@ -479,13 +555,26 @@ def build_platform_tool_resources( unavailable.append({'name': name, 'reason': reason}) continue assert definition is not None + parameters = copy.deepcopy(definition.parameters) + if definition.name == PRESENT_INTERACTIVE_CARD_TOOL: + capabilities = getattr(event.delivery, 'interactions', None) + field_types = list(getattr(capabilities, 'field_types', []) or []) + action_styles = list(getattr(capabilities, 'action_styles', []) or []) + max_fields = getattr(capabilities, 'max_fields', None) + field_schema = parameters['properties']['fields'] + if field_types: + field_schema['items']['properties']['type']['enum'] = field_types + if isinstance(max_fields, int): + field_schema['maxItems'] = max_fields + if action_styles: + parameters['properties']['actions']['items']['properties']['style']['enum'] = action_styles resources.append( { 'tool_name': definition.name, 'tool_type': 'platform', 'description': definition.description.get('en_US') or definition.description.get('zh_Hans'), 'operations': list(operations), - 'parameters': copy.deepcopy(definition.parameters), + 'parameters': parameters, 'source': 'platform', 'source_id': definition.name, } @@ -537,6 +626,8 @@ def _event_params( subject.get('subject_id') if subject.get('subject_type') == 'group' else None ) actor_id = actor.get('actor_id') + if definition.name == PRESENT_INTERACTIVE_CARD_TOOL: + return dict(parameters) if definition.binding == 'reply_target': return { 'target_type': reply_target.get('target_type'), @@ -608,6 +699,49 @@ def _normalize_platform_params( return dict(parameters) +def _interactive_card_request(parameters: dict[str, typing.Any]) -> dict[str, typing.Any]: + fields = copy.deepcopy(parameters.get('fields') or []) + actions = copy.deepcopy(parameters.get('actions') or []) + if not isinstance(fields, list) or not isinstance(actions, list): + raise ValueError('fields and actions must be arrays') + if not fields and not actions: + raise ValueError('An interactive card requires at least one field or action') + if fields and actions: + raise ValueError('An interactive card step cannot combine fields and actions') + + title = _require_string(parameters, 'title') + description = parameters.get('description') + lines = [title] + if isinstance(description, str) and description.strip(): + lines.extend(['', description.strip()]) + for field in fields: + if not isinstance(field, dict): + raise ValueError('Every interaction field must be an object') + label = str(field.get('label') or field.get('id') or 'Input') + options = field.get('options') if isinstance(field.get('options'), list) else [] + option_labels = [str(item.get('label')) for item in options if isinstance(item, dict) and item.get('label')] + lines.append(f'{label}: {", ".join(option_labels) if option_labels else "input required"}') + if actions: + lines.append( + 'Actions: ' + + ', '.join(str(item.get('label')) for item in actions if isinstance(item, dict) and item.get('label')) + ) + + expires_in = parameters.get('expires_in_seconds', 30 * 60) + if isinstance(expires_in, bool) or not isinstance(expires_in, int) or not 60 <= expires_in <= 86400: + raise ValueError('expires_in_seconds must be an integer from 60 to 86400') + return { + 'interaction_id': f'card-{uuid.uuid4().hex}', + 'kind': parameters.get('kind', 'form'), + 'title': title, + 'description': description, + 'fields': fields, + 'actions': actions, + 'expires_at': int(time.time()) + expires_in, + 'fallback_text': '\n'.join(lines), + } + + def resolve_platform_api_call(session, bot_uuid, action, params, context_tool=None): """Resolve an adapter call against Host-frozen tool grants and event targets.""" authorization = session.get('authorization') or {} @@ -738,8 +872,24 @@ async def execute_platform_tool( and {'reply_message', 'get_message'} <= supported_apis and (delivery.get('reply_target') or {}).get('message_id') ) - if definition.api not in supported_apis and not reply_via_source: + if ( + definition.api not in supported_apis + and not reply_via_source + and not (definition.name == PRESENT_INTERACTIVE_CARD_TOOL and 'send_message' in supported_apis) + ): raise ValueError(f'Platform API {definition.api} is no longer supported by bot {bot_id}') + if definition.name == PRESENT_INTERACTIVE_CARD_TOOL: + manager = getattr(getattr(ap, 'agent_run_orchestrator', None), 'interaction_manager', None) + if manager is None: + raise ValueError('Interactive card delivery is unavailable') + return await manager.request_interaction( + request_payload=_interactive_card_request(normalized), + session=session, + adapter=bot.adapter, + timeout=normalized.get('expires_in_seconds', 600), + on_unsupported='degrade', + responders=normalized.get('responders', 'actor'), + ) api_func = getattr(bot.adapter, definition.api, None) if reply_via_source: @@ -761,6 +911,27 @@ async def execute_platform_tool( context=context, target_type=target_type, target_id=target_id, message=message ) + reply_streams = session.get('reply_streams') + if ( + definition.name == 'event_reply' + and message_chain is None + and reply_streams is not None + and getattr(reply_streams, 'adapter', None) is bot.adapter + ): + from uuid import uuid4 + + from .reply_stream import ReplyStreamRequest + + async def api_func(target_type, target_id, message): + text = ''.join(part.text for part in message if isinstance(part, platform_message.Plain)) + return await reply_streams.apply( + ReplyStreamRequest( + stream_id=uuid4(), + operation='finish', + text=text, + ) + ) + if not callable(api_func): raise ValueError(f'Platform API {definition.api} is declared but not implemented') if definition.api == 'send_message': @@ -879,6 +1050,7 @@ def _execute_mock_platform_tool( __all__ = [ 'PLATFORM_TOOL_DEFINITIONS', + 'PRESENT_INTERACTIVE_CARD_TOOL', 'build_platform_tool_resources', 'execute_platform_tool', 'freeze_platform_context', diff --git a/src/langbot/pkg/agent/runner/query_entry_adapter.py b/src/langbot/pkg/agent/runner/query_entry_adapter.py index a3ecbfe16..3ad830179 100644 --- a/src/langbot/pkg/agent/runner/query_entry_adapter.py +++ b/src/langbot/pkg/agent/runner/query_entry_adapter.py @@ -31,6 +31,7 @@ from .host_models import ( ) from .config_resolver import RunnerConfigResolver from .resource_policy import ResourcePolicyProjector +from .platform_tools import PRESENT_INTERACTIVE_CARD_TOOL, resolve_agent_platform_tool_names from . import events as runner_events from ...pipeline.pool import get_query_execution_context from ...provider.tools.toolmgr import TOOL_SOURCE_REFS_QUERY_KEY @@ -131,6 +132,11 @@ class QueryEntryAdapter: pipeline_config = query.pipeline_config or {} runner_config = RunnerConfigResolver.resolve_runner_config(pipeline_config, runner_id) agent_id = getattr(query, 'pipeline_uuid', None) + platform_tool_names = [ + name + for name in resolve_agent_platform_tool_names({}, runner_events.MESSAGE_RECEIVED) + if name == PRESENT_INTERACTIVE_CARD_TOOL + ] resource_policy = ResourcePolicyProjector.from_runner_config( runner_config, @@ -139,6 +145,7 @@ class QueryEntryAdapter: resolved_tool_sources=cls._extract_allowed_tool_sources(query), resolved_kb_uuids=cls._extract_allowed_kbs(query), resolved_skill_names=cls._extract_allowed_skills(query), + allowed_platform_tool_names=platform_tool_names, ) # Build state policy @@ -153,13 +160,6 @@ class QueryEntryAdapter: enable_reply=True, enable_interactions=True, ) - variables = getattr(query, 'variables', None) or {} - event_type = ( - runner_events.INTERACTION_SUBMITTED - if isinstance(variables.get('_interaction_submission'), dict) - else runner_events.MESSAGE_RECEIVED - ) - return AgentConfig( agent_id=agent_id, processor_type='pipeline', @@ -169,7 +169,7 @@ class QueryEntryAdapter: resource_policy=resource_policy, state_policy=state_policy, delivery_policy=delivery_policy, - event_types=[event_type], + event_types=[runner_events.MESSAGE_RECEIVED], metadata={'source': 'pipeline_adapter'}, ) @@ -249,17 +249,10 @@ class QueryEntryAdapter: event_time = cls._normalize_event_time(getattr(message_event, 'time', None) if message_event else None) - variables = getattr(query, 'variables', None) or {} - interaction = variables.get('_interaction_submission') - event_type = runner_events.MESSAGE_RECEIVED - if isinstance(interaction, dict): - event_type = runner_events.INTERACTION_SUBMITTED - event_data['interaction'] = interaction - source_event_id = str(message_id or query.query_id) return AgentEventContext( event_id=cls._build_scoped_event_id(query, source_event_id, event_time), - event_type=event_type, + event_type=runner_events.MESSAGE_RECEIVED, event_time=event_time, source='host_adapter', source_event_type=source_event_type, @@ -417,15 +410,6 @@ class QueryEntryAdapter: if launcher_type is not None: launcher_type_value = getattr(launcher_type, 'value', launcher_type) - variables = getattr(query, 'variables', None) or {} - interaction = variables.get('_interaction_submission') - if isinstance(interaction, dict): - return SubjectContext( - subject_type='interaction', - subject_id=str(interaction.get('interaction_id') or ''), - data={'action_id': interaction.get('action_id')}, - ) - return SubjectContext( subject_type='message', subject_id=str(message_id or query_id or ''), @@ -496,10 +480,6 @@ class QueryEntryAdapter: 'contents': contents, 'attachments': attachments, } - variables = getattr(query, 'variables', None) or {} - interaction = variables.get('_interaction_submission') - if isinstance(interaction, dict) and 'interaction' in AgentInput.model_fields: - input_data['interaction'] = interaction return AgentInput.model_validate(input_data) @classmethod @@ -660,7 +640,7 @@ class QueryEntryAdapter: 'supported_apis': supported_apis, }, } - if 'interactions' in DeliveryContext.model_fields and 'interaction.request' in supported_apis: + if 'interactions' in DeliveryContext.model_fields and 'send_interaction' in supported_apis: get_capabilities = getattr(adapter, 'get_interaction_capabilities', None) if callable(get_capabilities): capabilities = get_capabilities() diff --git a/src/langbot/pkg/agent/runner/reply_stream.py b/src/langbot/pkg/agent/runner/reply_stream.py index aa2f3500f..8e06963b6 100644 --- a/src/langbot/pkg/agent/runner/reply_stream.py +++ b/src/langbot/pkg/agent/runner/reply_stream.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import logging from dataclasses import dataclass, field from typing import Literal from uuid import UUID, uuid4 @@ -12,6 +13,9 @@ from langbot_plugin.api.entities.builtin.platform import events, message from langbot_plugin.api.entities.builtin.provider import message as provider_message +logger = logging.getLogger(__name__) + + class ReplyStreamRequest(pydantic.BaseModel): model_config = pydantic.ConfigDict(extra='forbid') @@ -86,12 +90,33 @@ class ReplyStreamSession: raise ValueError('This run has no platform delivery adapter') # Set before I/O: an uncertain create must never be retried as another send. reply.started = True - reply.native = self.source is not None and await self.adapter.is_stream_output_supported() + target_streaming = ( + self.source is None + and callable(getattr(self.adapter, 'create_message_card_for_target', None)) + and callable(getattr(self.adapter, 'reply_message_chunk_for_target', None)) + ) + reply.native = ( + self.source is not None or target_streaming + ) and await self.adapter.is_stream_output_supported() if reply.native: - await self.adapter.create_message_card(reply.delivery_id, self.source) + if self.source is not None: + await self.adapter.create_message_card(reply.delivery_id, self.source) + else: + target_type, target_id = self.target.get('target_type'), self.target.get('target_id') + if not target_type or not target_id: + raise ValueError('This event has no reply target') + await self.adapter.create_message_card_for_target( + reply.delivery_id, str(target_type), str(target_id) + ) if reply.started and reply.native: await self._update_native(key, reply, final=request.operation != 'update') - elif request.operation == 'finish' and reply.text and not self.mock: + if ( + reply.started + and not reply.native + and request.operation == 'finish' + and reply.text + and not self.mock + ): if self.source is not None: await self.adapter.reply_message( message_source=self.source, message=self._message(reply.text), quote_origin=False @@ -131,13 +156,18 @@ class ReplyStreamSession: msg_sequence=reply.sequence, is_final=final, ) - await self.adapter.reply_message_chunk( - message_source=self.source, - bot_message=chunk, - message=self._message(reply.text), - quote_origin=False, - is_final=final, - ) + if self.source is not None: + await self.adapter.reply_message_chunk( + message_source=self.source, + bot_message=chunk, + message=self._message(reply.text), + quote_origin=False, + is_final=final, + ) + else: + await self.adapter.reply_message_chunk_for_target( + message_id=reply.delivery_id, content=reply.text, is_final=final + ) async def close(self): """Close visible streams on cancellation; never send a buffered partial reply.""" diff --git a/src/langbot/pkg/agent/runner/resource_builder.py b/src/langbot/pkg/agent/runner/resource_builder.py index 6cec4ba6a..ec3a2b83c 100644 --- a/src/langbot/pkg/agent/runner/resource_builder.py +++ b/src/langbot/pkg/agent/runner/resource_builder.py @@ -20,7 +20,7 @@ from .host_models import AgentEventEnvelope, AgentBinding from .resource_policy import ResourcePolicyProjector from ...provider.tools.loaders.mcp import MCP_TOOL_LIST_RESOURCES, MCP_TOOL_READ_RESOURCE from ...provider.tools.toolmgr import ToolSourceRef -from .platform_tools import build_platform_tool_resources +from .platform_tools import PRESENT_INTERACTIVE_CARD_TOOL, build_platform_tool_resources class AgentResourceBuilder: @@ -90,9 +90,19 @@ class AgentResourceBuilder: tool_catalog, ) runner_uses_host_tools = config_schema.uses_host_tools(descriptor) + selected_platform_tools = list(resource_policy.allowed_platform_tool_names or []) + if ( + binding.processor_type not in {'agent', 'pipeline'} + or not binding.delivery_policy.enable_interactions + or not getattr(descriptor.capabilities, 'interactions', False) + or 'request' not in (getattr(manifest_perms, 'interactions', []) or []) + ): + selected_platform_tools = [ + name for name in selected_platform_tools if name != PRESENT_INTERACTIVE_CARD_TOOL + ] platform_tools, platform_capabilities = build_platform_tool_resources( event, - resource_policy.allowed_platform_tool_names, + selected_platform_tools, ( [operation for operation in ('detail', 'call') if operation in set(manifest_perms.tools)] if runner_uses_host_tools diff --git a/src/langbot/pkg/agent/runner/session_registry.py b/src/langbot/pkg/agent/runner/session_registry.py index 0e63df5b2..0081f50ce 100644 --- a/src/langbot/pkg/agent/runner/session_registry.py +++ b/src/langbot/pkg/agent/runner/session_registry.py @@ -51,6 +51,11 @@ class RunAuthorizationSnapshot(typing.TypedDict): platform_context: dict[str, typing.Any] authorized_ids: dict[str, set[str]] authorized_operations: dict[str, dict[str, set[str]]] + binding_id: str | None + processor_type: str | None + processor_id: str | None + interactions_enabled: bool + interactions_authorized: bool SteeringQueueItem = dict[str, typing.Any] @@ -80,6 +85,7 @@ class AgentRunSession(typing.TypedDict): status: AgentRunSessionStatus reply_streams: typing.Any steering_queue: list[SteeringQueueItem] + runtime_context: dict[str, typing.Any] | None task: asyncio.Task[typing.Any] | None @@ -120,6 +126,12 @@ class AgentRunSessionRegistry: execution_query: pipeline_query.Query | None = None, platform_context: dict[str, typing.Any] | None = None, reply_streams: typing.Any = None, + binding_id: str | None = None, + processor_type: str | None = None, + processor_id: str | None = None, + interactions_enabled: bool = False, + interactions_authorized: bool = False, + runtime_context: dict[str, typing.Any] | None = None, ) -> None: """Register a new agent run session. @@ -167,6 +179,11 @@ class AgentRunSessionRegistry: 'platform_context': copy.deepcopy(platform_context or {}), 'authorized_ids': self._build_authorized_ids(resources_snapshot), 'authorized_operations': self._build_authorized_operations(resources_snapshot), + 'binding_id': binding_id, + 'processor_type': processor_type, + 'processor_id': processor_id, + 'interactions_enabled': interactions_enabled, + 'interactions_authorized': interactions_authorized, } session: AgentRunSession = { @@ -182,6 +199,7 @@ class AgentRunSessionRegistry: 'last_activity_at': now, }, 'steering_queue': [], + 'runtime_context': runtime_context, 'task': asyncio.current_task(), } @@ -276,12 +294,18 @@ class AgentRunSessionRegistry: bot_id: str | None = None, workspace_id: str | None = None, thread_id: str | None = None, + binding_id: str | None = None, + eligible_run_ids: set[str] | None = None, ) -> str | None: """Find the oldest active run that can accept steering for a conversation.""" async with self._lock: candidates: list[tuple[int, str]] = [] for run_id, session in self._sessions.items(): authorization = session['authorization'] + if eligible_run_ids is not None and run_id not in eligible_run_ids: + continue + if binding_id is not None and authorization.get('binding_id') != binding_id: + continue if session.get('runner_id') != runner_id: continue if authorization.get('conversation_id') != conversation_id: diff --git a/src/langbot/pkg/api/http/controller/groups/platform/adapters.py b/src/langbot/pkg/api/http/controller/groups/platform/adapters.py index 6b7f41d16..a72c6dcd2 100644 --- a/src/langbot/pkg/api/http/controller/groups/platform/adapters.py +++ b/src/langbot/pkg/api/http/controller/groups/platform/adapters.py @@ -309,24 +309,6 @@ class AdaptersRouterGroup(group.RouterGroup): importutil.read_resource_file_bytes(icon_path), mimetype=mimetypes.guess_type(icon_path)[0] ) - @self.route('/dingtalk/stream-card-template', methods=['GET'], auth_type=group.AuthType.NONE) - async def _() -> quart.Response: - filename = 'dingtalk_stream_card.json' - response = quart.Response( - importutil.read_resource_file_bytes(f'templates/{filename}'), mimetype='application/json' - ) - response.headers['Content-Disposition'] = f'attachment; filename={filename}' - return response - - @self.route('/dingtalk/human-input-card-template', methods=['GET'], auth_type=group.AuthType.NONE) - async def _() -> quart.Response: - filename = 'dingtalk_human_input_card.json' - response = quart.Response( - importutil.read_resource_file_bytes(f'templates/{filename}'), mimetype='application/json' - ) - response.headers['Content-Disposition'] = f'attachment; filename={filename}' - return response - # In-memory session store for active registrations _create_app_sessions: dict = {} _SESSION_TTL = 900 # 15 minutes diff --git a/src/langbot/pkg/api/http/service/agent.py b/src/langbot/pkg/api/http/service/agent.py index 61a64d3dd..c3e6ed39a 100644 --- a/src/langbot/pkg/api/http/service/agent.py +++ b/src/langbot/pkg/api/http/service/agent.py @@ -436,6 +436,7 @@ class AgentService: 'description': agent_data.get('description') or '', 'emoji': agent_data.get('emoji') or '⚙️', }, + runner_id=agent_data.get('runner_id'), ) return {'uuid': pipeline_uuid, 'kind': AGENT_KIND_PIPELINE} diff --git a/src/langbot/pkg/api/http/service/pipeline.py b/src/langbot/pkg/api/http/service/pipeline.py index d362743aa..d36798a61 100644 --- a/src/langbot/pkg/api/http/service/pipeline.py +++ b/src/langbot/pkg/api/http/service/pipeline.py @@ -7,6 +7,7 @@ import typing from ....core import app from ....agent.runner.config_resolver import RunnerConfigResolver +from ....agent.runner.errors import RunnerNotFoundError from ....entity.persistence import pipeline as persistence_pipeline from ....pipeline.extension_preferences import ( normalize_extension_preferences, @@ -46,7 +47,11 @@ class PipelineService: ) -> dict[str, typing.Any]: return {item['name']: item['default'] for item in config_schema if item.get('name') and 'default' in item} - async def get_default_pipeline_config(self, context: TenantContext) -> dict[str, typing.Any]: + async def get_default_pipeline_config( + self, + context: TenantContext, + runner_id: str | None = None, + ) -> dict[str, typing.Any]: from ....utils import paths as path_utils template_path = path_utils.get_resource_path('templates/default-pipeline-config.json') @@ -56,15 +61,20 @@ class PipelineService: registry = getattr(self.ap, 'runner_registry', None) if registry is None: return config - try: - runners = await registry.list_runners(context, bound_plugins=None) - except Exception as exc: - self.ap.logger.warning(f'Failed to load Runner defaults for pipeline config: {exc}') - return config - if not runners: - return config - - selected = runners[0] + if runner_id: + try: + selected = await registry.get(context, runner_id) + except RunnerNotFoundError as exc: + raise ValueError(f'Runner {runner_id} not found') from exc + else: + try: + runners = await registry.list_runners(context, bound_plugins=None) + except Exception as exc: + self.ap.logger.warning(f'Failed to load Runner defaults for pipeline config: {exc}') + return config + if not runners: + return config + selected = runners[0] ai_config = config.setdefault('ai', {}) runner_config = ai_config.setdefault('runner', {}) runner_config['id'] = selected.id @@ -169,7 +179,14 @@ class PipelineService: serialized = self.ap.persistence_mgr.serialize_model(persistence_pipeline.LegacyPipeline, pipeline) return serialized if include_secret else redact_secrets(serialized) - async def create_pipeline(self, context: TenantContext, pipeline_data: dict, default: bool = False) -> str: + async def create_pipeline( + self, + context: TenantContext, + pipeline_data: dict, + default: bool = False, + *, + runner_id: str | None = None, + ) -> str: workspace_uuid = require_workspace_uuid(context) if 'extensions_preferences' in pipeline_data: self._validate_extension_preferences(pipeline_data['extensions_preferences']) @@ -196,7 +213,7 @@ class PipelineService: pipeline_data['is_default'] = default if 'config' not in pipeline_data or pipeline_data['config'] == {}: - pipeline_data['config'] = await self.get_default_pipeline_config(context) + pipeline_data['config'] = await self.get_default_pipeline_config(context, runner_id) RunnerConfigResolver.validate_pipeline_config(pipeline_data['config']) # Ensure extensions_preferences is set with enable_all_plugins and enable_all_mcp_servers=True by default diff --git a/src/langbot/pkg/core/stages/build_app.py b/src/langbot/pkg/core/stages/build_app.py index 94f073a6b..1bce9778f 100644 --- a/src/langbot/pkg/core/stages/build_app.py +++ b/src/langbot/pkg/core/stages/build_app.py @@ -353,6 +353,7 @@ class BuildAppStage(stage.BootingStage): agent_run_orchestrator_inst = AgentRunOrchestrator(ap, runner_registry_inst) ap.agent_run_orchestrator = agent_run_orchestrator_inst + await agent_run_orchestrator_inst.interaction_manager.store.cancel_orphaned_pending(set()) ctrl = controller.Controller(ap) ap.ctrl = ctrl diff --git a/src/langbot/pkg/pipeline/resprule/resprule.py b/src/langbot/pkg/pipeline/resprule/resprule.py index c541880e4..aba6e628d 100644 --- a/src/langbot/pkg/pipeline/resprule/resprule.py +++ b/src/langbot/pkg/pipeline/resprule/resprule.py @@ -52,13 +52,7 @@ class GroupRespondRuleCheckStage(stage.PipelineStage): if is_stop_command: return entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query) - # Interaction submissions and routed platform form callbacks resume the - # original run without another mention or prefix. Ordinary routing only - # selects a pipeline and must still obey its group response rules. - if query.variables and ( - query.variables.get('_interaction_submission') - or (query.variables.get('_routed_by_rule') and query.variables.get('_dify_form_action')) - ): + if query.variables and query.variables.get('_routed_by_rule') and query.variables.get('_dify_form_action'): return entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query) rules = query.pipeline_config['trigger']['group-respond-rules'] diff --git a/src/langbot/pkg/platform/adapters/dingtalk/adapter.py b/src/langbot/pkg/platform/adapters/dingtalk/adapter.py index 6dd0f55df..1ae94ec45 100644 --- a/src/langbot/pkg/platform/adapters/dingtalk/adapter.py +++ b/src/langbot/pkg/platform/adapters/dingtalk/adapter.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json import time import traceback import typing @@ -18,6 +19,7 @@ from langbot.pkg.platform.adapters.dingtalk.event_converter import DingTalkEvent from langbot.pkg.platform.adapters.dingtalk.message_converter import DingTalkMessageConverter from langbot.pkg.platform.adapters.dingtalk.platform_api import PLATFORM_API_MAP from langbot.pkg.platform.adapters.dingtalk.interaction import ( + acknowledge_interaction, interaction_delivery_capabilities, interaction_event_from_native, send_interaction, @@ -26,6 +28,11 @@ from langbot_plugin.api.entities.builtin.platform import entities as platform_en from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class DingTalkCardCallbackHandler(dingtalk_stream.CallbackHandler): @@ -34,27 +41,59 @@ class DingTalkCardCallbackHandler(dingtalk_stream.CallbackHandler): self.adapter = adapter async def process(self, message: dingtalk_stream.CallbackMessage): - callback = dingtalk_stream.CardCallbackMessage.from_dict(message.data or {}) - content = dict(callback.content) if isinstance(callback.content, dict) else {} - if isinstance(message.data, dict): - content['_raw_callback'] = message.data + raw = message.data if isinstance(message.data, dict) else {} + content = raw.get('content') + if isinstance(content, str): + try: + content = json.loads(content) + except json.JSONDecodeError: + content = {} + content = dict(content) if isinstance(content, dict) else {} + content['_raw_callback'] = raw + extension = raw.get('extension') + if isinstance(extension, str): + try: + extension = json.loads(extension) + except json.JSONDecodeError: + extension = {} + track_id = str(raw.get('outTrackId') or '') + matched = track_id in self.adapter.interaction_callback_contexts + self.logger.info( + 'DingTalk card callback: topic=%s track=%s keys=%s content_keys=%s context_matched=%s', + getattr(message.headers, 'topic', None), + track_id, + sorted(raw), + sorted(content), + matched, + ) event = DingTalkEvent.from_payload( { 'conversation_type': 'CardCallback', 'Type': 'card_callback', 'timestamp': float(message.headers.time or 0) / 1000, 'CardCallback': { - 'extension': callback.extension, - 'corp_id': callback.corp_id, - 'user_id': callback.user_id, + 'extension': extension if isinstance(extension, dict) else {}, + 'corp_id': raw.get('corpId'), + 'user_id': raw.get('userId'), 'content': content, - 'space_id': callback.space_id, - 'card_instance_id': callback.card_instance_id, + 'space_id': raw.get('openSpaceId') or raw.get('spaceId'), + 'card_instance_id': track_id, }, } ) if event is not None: - await self.adapter._handle_native_event(event) + interaction = interaction_event_from_native(event, self.adapter.interaction_callback_contexts) + if interaction is not None: + try: + await self.adapter._dispatch_eba_event(interaction) + except Exception: + self.logger.exception('DingTalk card callback dispatch failed: track=%s', track_id) + return 500, 'Card callback dispatch failed' + elif matched: + self.logger.warning('DingTalk card callback could not be parsed: track=%s', track_id) + return 500, 'Card callback could not be parsed' + else: + self.logger.info('DingTalk card callback has no active interaction: track=%s', track_id) return dingtalk_stream.AckMessage.STATUS_OK, 'OK' @@ -115,6 +154,7 @@ class DingTalkAdapter(DingTalkAPIMixin, abstract_platform_adapter.AbstractPlatfo 'group.info_updated', 'dingtalk.card_action', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -130,13 +170,54 @@ class DingTalkAdapter(DingTalkAPIMixin, abstract_platform_adapter.AbstractPlatfo 'get_file_url', 'call_platform_api', ] - if self.config.get('human_input_card_template_id') and hasattr(self.bot, 'create_and_deliver_card'): - apis.append('interaction.request') + if hasattr(self.bot, 'create_and_deliver_ai_card'): + apis.extend(['send_interaction', 'get_interaction_capabilities']) + if hasattr(self.bot, 'update_ai_card'): + apis.append('update_interaction') return apis def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + return handle + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + result = await acknowledge_interaction( + self, + { + 'update_target': handle.model_dump(mode='json'), + 'request': handle.context['request'], + 'submission': submission.model_dump(mode='json') if submission else {}, + 'state': state, + }, + ) + updated = InteractionHandle.model_validate(result) + updated.context.update(handle.context) + return updated + @staticmethod def _plain_message(text: str) -> platform_message.MessageChain: return platform_message.MessageChain([platform_message.Plain(text=text)]) @@ -233,23 +314,34 @@ class DingTalkAdapter(DingTalkAPIMixin, abstract_platform_adapter.AbstractPlatfo oldest_id = next(iter(self.card_instance_id_dict)) self.card_instance_id_dict.pop(oldest_id, None) getattr(self, '_card_last_updates', {}).pop(oldest_id, None) - card_template_id = self.config['card_template_id'].strip() incoming_message = event.source_platform_object.incoming_message - card_auto_layout = self.config.get('card_auto_layout', True) - card_instance, card_instance_id = await self.bot.create_and_card( - card_template_id, - incoming_message, - card_auto_layout=card_auto_layout, - ) + card_instance, card_instance_id = await self.bot.create_and_card(incoming_message) self.card_instance_id_dict[message_id] = (card_instance, card_instance_id) return True + async def create_message_card_for_target(self, message_id: str, target_type: str, target_id: str) -> bool: + card_instance, card_instance_id = await self.bot.create_and_card_for_target(target_type, target_id) + self.card_instance_id_dict[message_id] = (card_instance, card_instance_id) + return True + + async def reply_message_chunk_for_target(self, *, message_id: str, content: str, is_final: bool) -> None: + now = time.monotonic() + last_updates = getattr(self, '_card_last_updates', None) + if last_updates is None: + self._card_last_updates = last_updates = {} + if not is_final and now - last_updates.get(message_id, 0) < 0.35: + return + card_instance, card_instance_id = self.card_instance_id_dict[message_id] + await self.bot.send_card_message(card_instance, card_instance_id, content, is_final) + last_updates[message_id] = now + if is_final: + self.card_instance_id_dict.pop(message_id, None) + last_updates.pop(message_id, None) + async def is_stream_output_supported(self) -> bool: return is_stream_card_configured(self.config) async def call_platform_api(self, action: str, params: dict = {}) -> dict: - if action == 'interaction.request' and action in self.get_supported_apis(): - return await send_interaction(self, params) handler = PLATFORM_API_MAP.get(action) if handler is None: raise NotSupportedError(f'call_platform_api:{action}') diff --git a/src/langbot/pkg/platform/adapters/dingtalk/interaction.py b/src/langbot/pkg/platform/adapters/dingtalk/interaction.py index db9185292..f1845bee6 100644 --- a/src/langbot/pkg/platform/adapters/dingtalk/interaction.py +++ b/src/langbot/pkg/platform/adapters/dingtalk/interaction.py @@ -7,6 +7,7 @@ import time import typing import uuid +from langbot.libs.dingtalk_api.a2ui import brand_components, binding, create_surface_messages, update_surface_messages from langbot.libs.dingtalk_api.dingtalkevent import DingTalkEvent from langbot_plugin.api.entities.builtin.platform import events as platform_events @@ -16,69 +17,223 @@ def interaction_delivery_capabilities() -> dict[str, typing.Any]: 'field_types': ['text', 'textarea', 'number', 'select'], 'action_styles': ['default', 'primary', 'danger'], 'supports_updates': True, - 'max_fields': 1, + 'max_fields': 8, } -def _select_options(options: list[dict[str, typing.Any]]) -> list[dict[str, typing.Any]]: - locales = ['zh_CN', 'zh_TW', 'en_US', 'ja_JP', 'vi_VN', 'th_TH', 'id_ID', 'ms_MY', 'ko_KR'] - result = [] - for option in options: - value = str(option.get('value') or '') - label = str(option.get('label') or value) - if value: - result.append({'value': value, 'text': {locale: label for locale in locales}}) - return result +def _json_pointer_segment(value: str) -> str: + return value.replace('~', '~0').replace('/', '~1') -def _field_card_params(field: dict[str, typing.Any]) -> dict[str, typing.Any] | None: - field_type = str(field.get('type') or '') - field_id = str(field.get('id') or '') - if field_type not in {'text', 'textarea', 'number', 'select'} or not field_id: - return None - label = str(field.get('label') or field_id) - placeholder = str(field.get('placeholder') or label) - default = field.get('default') - params: dict[str, typing.Any] = { - 'input_visible': '', - 'input_title': '', - 'input_placeholder': '', - 'input_value': '', - 'select_visible': '', - 'select_placeholder': '', - 'select_options': [], - 'index_o': [], - 'select_index': -1, - } - if field_type == 'select': - raw_options = field.get('options') if isinstance(field.get('options'), list) else [] - options = [option for option in raw_options if isinstance(option, dict)] - encoded_options = _select_options(options) - if not encoded_options: - return None - selected_index = next( - (index for index, option in enumerate(options) if str(option.get('value')) == str(default)), - -1, +def _stored_submitted_values(value: typing.Any) -> list[dict[str, str]]: + if not isinstance(value, list): + return [] + return [ + { + 'label': str(item['label'])[:200], + 'value': str(item['value'])[:2000], + **({'description': str(item['description'])[:4000]} if item.get('description') is not None else {}), + } + for item in value[:50] + if isinstance(item, dict) and item.get('label') is not None and item.get('value') is not None + ] + + +def _submission_display_values( + request: dict[str, typing.Any], submission: dict[str, typing.Any] +) -> list[dict[str, str]]: + values = submission.get('values') if isinstance(submission.get('values'), dict) else {} + displayed: list[dict[str, str]] = [] + for field in request.get('fields') or []: + if not isinstance(field, dict): + continue + field_id = str(field.get('id') or '') + if not field_id or field_id not in values: + continue + value = values[field_id] + if field.get('type') == 'select': + value = next( + ( + option.get('label') or option.get('value') + for option in field.get('options') or [] + if isinstance(option, dict) and option.get('value') == value + ), + value, + ) + rendered = json.dumps(value, ensure_ascii=False) if isinstance(value, (dict, list)) else str(value) + display_value = {'label': str(field.get('label') or field_id), 'value': rendered[:2000]} + description = str(request.get('description') or '').strip() + if description: + display_value['description'] = description[:4000] + displayed.append(display_value) + + action_id = submission.get('action_id') + if action_id: + action_label = next( + ( + str(action.get('label') or action_id) + for action in request.get('actions') or [] + if isinstance(action, dict) and str(action.get('id') or '') == str(action_id) + ), + str(action_id), ) - params.update( - { - 'select_visible': 'true', - 'select_placeholder': placeholder, - 'select_options': [str(option.get('value') or '') for option in options], - 'index_o': encoded_options, - 'select_index': selected_index, + action_value = {'label': '', 'value': action_label} + description = str(request.get('description') or '').strip() + if description and not displayed: + action_value['description'] = description[:4000] + displayed.append(action_value) + return displayed + + +def _submitted_components(values: list[dict[str, str]]) -> tuple[list[dict[str, typing.Any]], list[str]]: + components = [] + children = [] + for index, item in enumerate(values): + description = item.get('description') + if description: + description_id = f'submitted-description-{index}' + components.append({'id': description_id, 'component': 'Text', 'text': description}) + children.append(description_id) + component_id = f'submitted-{index}' + label = f'{item["label"]}: ' if item['label'] else '' + components.append({'id': component_id, 'component': 'Text', 'text': f'\u2705 {label}{item["value"]}'}) + children.append(component_id) + return components, children + + +def _build_interaction_messages( + surface_id: str, + request: dict[str, typing.Any], + callback_token: str, + submitted_values: list[dict[str, str]] | None = None, +) -> tuple[dict[str, typing.Any], list[dict[str, typing.Any]], dict[str, str]]: + raw_fields = request.get('fields') if isinstance(request.get('fields'), list) else [] + raw_actions = request.get('actions') if isinstance(request.get('actions'), list) else [] + fields = [field for field in raw_fields if isinstance(field, dict)][:8] + actions = [action for action in raw_actions if isinstance(action, dict)] + + form: dict[str, typing.Any] = {} + field_types: dict[str, str] = {} + required_fields: list[tuple[str, str]] = [] + components: list[dict[str, typing.Any]] = [] + children: list[str] = [] + + title = str(request.get('title') or '').strip() + description = str(request.get('description') or '').strip() + if title: + components.append({'id': 'title', 'component': 'Text', 'text': title}) + children.append('title') + history_components, history_children = _submitted_components(submitted_values or []) + components.extend(history_components) + children.extend(history_children) + if description: + components.append({'id': 'description', 'component': 'Markdown', 'content': description}) + children.append('description') + + for index, field in enumerate(fields): + field_id = str(field.get('id') or f'field_{index}') + field_type = str(field.get('type') or 'text') + if field_type not in {'text', 'textarea', 'number', 'select'}: + continue + field_types[field_id] = field_type + path = f'/form/{_json_pointer_segment(field_id)}' + component_id = f'field-{index}' + label = str(field.get('label') or field_id) + placeholder = str(field.get('placeholder') or '') + default = field.get('default') + + if field_type == 'select': + options = [ + { + 'label': str(option.get('label') or option.get('value') or ''), + 'value': str(option.get('value') or ''), + } + for option in field.get('options') or [] + if isinstance(option, dict) and str(option.get('value') or '') + ] + if not options: + continue + selected = default if isinstance(default, list) else ([] if default in (None, '') else [str(default)]) + form[field_id] = [str(value) for value in selected] + component = { + 'id': component_id, + 'component': 'ChoicePicker', + 'label': placeholder or label, + 'variant': 'mutuallyExclusive', + 'displayStyle': 'dropdown', + 'options': options, + 'value': binding(path), } - ) - else: - params.update( - { - 'input_visible': 'true', - 'input_title': label, - 'input_placeholder': placeholder, - 'input_value': '' if default is None else str(default), + elif field_type == 'number': + numeric_default = default if isinstance(default, (int, float)) and not isinstance(default, bool) else 0 + form[field_id] = numeric_default + component = { + 'id': component_id, + 'component': 'NumberInput', + 'label': label, + 'placeholder': placeholder, + 'value': binding(path), } + else: + form[field_id] = '' if default is None else str(default) + component = { + 'id': component_id, + 'component': 'TextField', + 'label': label, + 'placeholder': placeholder, + 'variant': 'longText' if field_type == 'textarea' else 'shortText', + 'value': binding(path), + } + components.append(component) + children.append(component_id) + if field.get('required'): + required_fields.append((path, label)) + + rendered_actions = actions or ([{'label': 'Submit', 'style': 'primary'}] if field_types else []) + for index, action in enumerate(rendered_actions): + label_id = f'action-label-{index}' + button_id = f'action-{index}' + callback_data = f'lbi:{callback_token}:a:{index}' if actions else f'lbi:{callback_token}:f:0' + style = str(action.get('style') or 'default') + button: dict[str, typing.Any] = { + 'id': button_id, + 'component': 'Button', + 'child': label_id, + 'variant': 'primary' if style == 'primary' else 'default', + 'action': { + 'event': { + 'name': 'langbot_interaction_submit', + 'context': { + 'actionId': callback_data, + 'values': binding('/form'), + }, + } + }, + } + if required_fields: + button['checks'] = [ + { + 'condition': {'call': 'required', 'args': {'value': binding(path)}}, + 'message': f'{label} is required', + } + for path, label in required_fields + ] + components.extend( + [ + button, + { + 'id': label_id, + 'component': 'Text', + 'text': str(action.get('label') or action.get('id') or 'Submit'), + }, + ] ) - return params + children.append(button_id) + + children.append('langbot-brand') + components.extend(brand_components()) + components.insert(0, {'id': 'root', 'component': 'Column', 'children': children, 'gap': 12}) + return {'form': form}, components, field_types def _prune_callback_contexts(adapter: typing.Any, now: float | None = None) -> None: @@ -88,63 +243,17 @@ def _prune_callback_contexts(adapter: typing.Any, now: float | None = None) -> N contexts.pop(key, None) -def _buttons(request: dict[str, typing.Any], callback_token: str) -> list[dict[str, typing.Any]]: - fields = request.get('fields') if isinstance(request.get('fields'), list) else [] - actions = request.get('actions') if isinstance(request.get('actions'), list) else [] - items: list[tuple[str, str, str]] = [] - if actions and not fields: - items = [ - ( - str(action.get('label') or action.get('id') or index + 1), - f'lbi:{callback_token}:a:{index}', - str(action.get('style') or 'default'), - ) - for index, action in enumerate(actions) - if isinstance(action, dict) - ] - elif len(fields) == 1 and not actions and isinstance(fields[0], dict): - field = fields[0] - if field.get('type') != 'select': - return [] - options = field.get('options') if isinstance(field.get('options'), list) else [] - items = [ - ( - str(option.get('label') or option.get('value') or index + 1), - f'lbi:{callback_token}:f:0:{index}', - 'default', - ) - for index, option in enumerate(options) - if isinstance(option, dict) - ] - return [ - { - 'text': label, - 'color': 'blue' if style == 'primary' else 'red' if style == 'danger' else 'gray', - 'status': 'normal', - 'event': { - 'type': 'sendCardRequest', - 'params': {'actionId': callback_data, 'params': {'action_id': callback_data}}, - }, - } - for label, callback_data, style in items - ] - - async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) -> dict[str, typing.Any]: request = params.get('request') reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') target_type = str(reply_target.get('target_type') or '') target_id = str(reply_target.get('target_id') or '') fields = request.get('fields') if isinstance(request.get('fields'), list) else [] actions = request.get('actions') if isinstance(request.get('actions'), list) else [] - buttons = _buttons(request, callback_token) - field_params = ( - _field_card_params(fields[0]) if len(fields) == 1 and not actions and isinstance(fields[0], dict) else None - ) - if not buttons and field_params is None: + if not fields and not actions: fallback = '\n\n'.join( part for part in ( @@ -157,49 +266,97 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - result = await adapter.send_message(target_type, target_id, adapter._plain_message(fallback)) return {'ok': True, 'message_id': result.message_id, 'rich': False} if target_type not in {'group', 'person'} or not target_id: - raise ValueError('interaction.request has an invalid DingTalk target') - field_label = str(fields[0].get('label') or '').strip() if fields and isinstance(fields[0], dict) else '' - content = '\n\n'.join( - part - for part in ( - f'## {str(request.get("title") or "").strip()}', - str(request.get('description') or '').strip(), - field_label, + raise ValueError('send_interaction has an invalid DingTalk target') + update_target = params.get('update_target') + submitted_values = _stored_submitted_values( + update_target.get('submitted_values') if isinstance(update_target, dict) else None + ) + if isinstance(update_target, dict): + if update_target.get('rich') is not True or not update_target.get('message_id'): + raise ValueError('DingTalk interaction update target is not an A2UI card') + out_track_id = str(update_target['message_id']) + else: + out_track_id = uuid.uuid4().hex + surface_id = f'langbot-interaction-{out_track_id}' + data, components, field_types = _build_interaction_messages(surface_id, request, callback_token, submitted_values) + if isinstance(update_target, dict): + await adapter.bot.update_ai_card( + out_track_id=out_track_id, + a2ui_messages=update_surface_messages(surface_id, data=data, components=components), + flow_status='CONFIRMING', ) - if part - ) - out_track_id = uuid.uuid4().hex - card_param_map = {'content': content, 'btns': buttons} - if field_params is not None: - card_param_map.update(field_params) - await adapter.bot.create_and_deliver_card( - card_template_id=adapter.config['human_input_card_template_id'], + else: + await adapter.bot.create_and_deliver_ai_card( + out_track_id=out_track_id, + open_space_id=( + f'dtv1.card//im_group.{target_id}' if target_type == 'group' else f'dtv1.card//im_robot.{target_id}' + ), + is_group=target_type == 'group', + a2ui_messages=create_surface_messages(surface_id, data=data, components=components), + flow_status='CONFIRMING', + summary=str(request.get('title') or request.get('fallback_text') or 'Interaction required'), + biz_context={'callbackToken': callback_token}, + ) + _prune_callback_contexts(adapter) + adapter.interaction_callback_contexts[out_track_id] = { + 'callback_token': callback_token, + 'field_types': field_types, + 'target_type': target_type, + 'target_id': target_id, + 'expires_at': time.monotonic() + max(1, int(request.get('expires_at') or time.time() + 30 * 60) - time.time()), + } + result = { + 'ok': True, + 'message_id': out_track_id, + 'rich': True, + 'updated': isinstance(update_target, dict), + } + if submitted_values: + result['submitted_values'] = submitted_values + return result + + +async def acknowledge_interaction(adapter: typing.Any, params: dict[str, typing.Any]) -> dict[str, typing.Any]: + request = params.get('request') + submission = params.get('submission') + target = params.get('update_target') + if not all(isinstance(value, dict) for value in (request, submission, target)): + raise ValueError('update_interaction requires request, submission, and update_target') + if target.get('rich') is not True or not target.get('message_id'): + raise ValueError('DingTalk interaction acknowledgement requires an A2UI card') + + out_track_id = str(target['message_id']) + state = params.get('state', 'submitted') + submitted_values = _stored_submitted_values(target.get('submitted_values')) + if state == 'submitted': + submitted_values.extend(_submission_display_values(request, submission)) + else: + submitted_values.append({'label': '', 'value': 'Expired' if state == 'expired' else 'Cancelled'}) + submitted_values = submitted_values[-50:] + components, children = _submitted_components(submitted_values) + title = str(request.get('title') or '').strip() + if title: + components.insert(0, {'id': 'title', 'component': 'Text', 'text': title}) + children.insert(0, 'title') + children.append('langbot-brand') + components.extend(brand_components()) + components.insert(0, {'id': 'root', 'component': 'Column', 'children': children, 'gap': 12}) + await adapter.bot.update_ai_card( out_track_id=out_track_id, - open_space_id=( - f'dtv1.card//IM_GROUP.{target_id}' if target_type == 'group' else f'dtv1.card//IM_ROBOT.{target_id}' + a2ui_messages=update_surface_messages( + f'langbot-interaction-{out_track_id}', data={'form': {}}, components=components ), - is_group=target_type == 'group', - card_param_map=card_param_map, + flow_status='CONFIRMED', ) - if field_params is not None: - _prune_callback_contexts(adapter) - field = fields[0] - adapter.interaction_callback_contexts[out_track_id] = { - 'callback_token': callback_token, - 'field_id': str(field.get('id') or ''), - 'field_type': str(field.get('type') or ''), - 'options': [ - str(option.get('value') or '') for option in field.get('options') or [] if isinstance(option, dict) - ], - 'expires_at': time.monotonic() + 30 * 60, - } - return {'ok': True, 'message_id': out_track_id, 'rich': True} + return {**target, 'updated': True, 'submitted_values': submitted_values} def parse_callback_data(value: str) -> dict[str, typing.Any]: parts = value.split(':') if len(parts) == 4 and parts[0] == 'lbi' and parts[1] and parts[2] == 'a' and parts[3].isdigit(): return {'callback_token': parts[1], 'action_ref': int(parts[3])} + if len(parts) == 4 and parts[0] == 'lbi' and parts[1] and parts[2] == 'f' and parts[3].isdigit(): + return {'callback_token': parts[1], 'field_ref': int(parts[3])} if ( len(parts) == 5 and parts[0] == 'lbi' @@ -254,7 +411,7 @@ def _find_named_value(value: typing.Any, names: set[str]) -> typing.Any: def _callback_track_id(callback: dict[str, typing.Any]) -> str: - value = _find_named_value(callback, {'outTrackId', 'out_track_id', 'outtrackid'}) + value = _find_named_value(callback, {'outTrackId', 'out_track_id', 'outtrackid', 'card_instance_id'}) return str(value or '') @@ -307,6 +464,29 @@ def interaction_event_from_native( callback_data = _find_callback_data(callback) if callback_data: parsed = parse_callback_data(callback_data) + raw_values = _mapping(_find_named_value(callback, {'values'})) + if 'field_ref' in parsed and 'option_ref' not in parsed: + # The A2UI form submit button uses f:0, but its values already + # contain the selected option; option refs belong to native pickers. + if not raw_values: + return None + parsed.pop('field_ref') + context: dict[str, typing.Any] = {} + if callback_contexts is not None: + track_id = _callback_track_id(callback) + context = callback_contexts.get(track_id) + if context is None: + return None + if parsed.get('callback_token') != context.get('callback_token'): + return None + if raw_values: + field_types = context.get('field_types') if isinstance(context.get('field_types'), dict) else {} + values = {} + for field_id, value in raw_values.items(): + if field_types.get(field_id) == 'select' and isinstance(value, list): + value = value[0] if value else '' + values[str(field_id)] = value + parsed['values'] = values else: contexts = callback_contexts if callback_contexts is not None else {} track_id = _callback_track_id(callback) @@ -320,27 +500,28 @@ def interaction_event_from_native( 'callback_token': str(context.get('callback_token') or ''), 'values': {str(context.get('field_id') or ''): value}, } - contexts.pop(track_id, None) space_id = str(callback.get('space_id') or '') - if 'IM_GROUP.' in space_id: + normalized_space_id = space_id.lower() + if context.get('target_type') in {'group', 'person'} and context.get('target_id'): + target_type = str(context['target_type']) + target_id = str(context['target_id']) + elif 'im_group.' in normalized_space_id: target_type = 'group' - target_id = space_id.split('IM_GROUP.', 1)[1] - elif 'IM_ROBOT.' in space_id: + target_id = space_id[normalized_space_id.index('im_group.') + len('im_group.') :] + elif 'im_robot.' in normalized_space_id: target_type = 'person' - target_id = space_id.split('IM_ROBOT.', 1)[1] + target_id = space_id[normalized_space_id.index('im_robot.') + len('im_robot.') :] else: raise ValueError('DingTalk interaction callback has no delivery space') - return platform_events.PlatformSpecificEvent( - type='platform.specific', + return platform_events.InteractionCallbackEvent( adapter_name='dingtalk-omni', - action='interaction.submitted', - data={ - **parsed, - 'actor_id': str(callback.get('user_id') or ''), - 'target_type': target_type, - 'target_id': target_id, - 'display_text': 'submitted', - }, + callback_token=str(parsed.get('callback_token') or ''), + values=parsed.get('values') if isinstance(parsed.get('values'), dict) else {}, + actor_id=str(callback.get('user_id') or ''), + target_type=target_type, + target_id=target_id, + callback_context={'outTrackId': _callback_track_id(callback)}, + raw_submission=parsed, timestamp=time.time(), source_platform_object=event, ) diff --git a/src/langbot/pkg/platform/adapters/dingtalk/manifest.yaml b/src/langbot/pkg/platform/adapters/dingtalk/manifest.yaml index 11a0b0e1f..8eb47a65e 100644 --- a/src/langbot/pkg/platform/adapters/dingtalk/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/dingtalk/manifest.yaml @@ -56,97 +56,12 @@ spec: zh_Hans: 使用卡片回复 zh_Hant: 使用卡片回覆 description: - en_US: Controls Markdown and streaming card replies. Disable to use plain text while keeping your template settings. When enabled, a configured template automatically enables streaming. - zh_Hans: 控制 Markdown 和流式卡片回复。关闭后使用纯文本,保留模板配置;开启且已配置模板时自动使用流式回复。 - zh_Hant: 控制 Markdown 和串流卡片回覆。關閉後使用純文字,保留範本設定;開啟且已設定範本時自動使用串流回覆。 + en_US: Uses built-in A2UI cards for Markdown, streaming replies, and interactions. No card template is required. The app must have AICard.Instance.Write permission. + zh_Hans: 使用内置 A2UI 卡片提供 Markdown、流式回复和交互能力,无需配置卡片模板。应用必须开通 AICard.Instance.Write 权限。 + zh_Hant: 使用內建 A2UI 卡片提供 Markdown、串流回覆和互動能力,無需設定卡片範本。應用必須開通 AICard.Instance.Write 權限。 type: boolean required: false default: true - - name: card_template_id - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: Card Template ID - zh_Hans: 卡片模板ID - zh_Hant: 卡片範本ID - description: - en_US: Template for streaming text replies. Save and publish it in DingTalk Card Platform, then paste its ID here to automatically enable streaming while card replies are enabled. Leave empty for ordinary replies. Separate from the human input template. - zh_Hans: 用于流式文字回复。在钉钉卡片平台保存并发布模板后,开启卡片回复后,填写 ID 即自动启用流式回复,留空使用普通回复;与人工输入卡片模板分开配置。 - zh_Hant: 用於串流文字回覆。在釘釘卡片平台儲存並發布範本後,開啟卡片回覆後,填寫 ID 即自動啟用串流回覆,留空使用一般回覆;與人工輸入卡片範本分開設定。 - type: string - required: false - default: "" - - name: stream_card_template_download - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: Download Streaming Reply Card Template - zh_Hans: 下载流式回复卡片模板 - zh_Hant: 下載串流回覆卡片範本 - description: - en_US: Displays reasoning and the answer separately. Import through More > Import Card Template in the DingTalk AI card editor, save and publish, then paste its ID into Card Template ID above. Respects the pipeline thinking removal setting. - zh_Hans: 分开展示思考与正文。在钉钉 AI 卡片编辑器中选择「更多 → 导入卡片模板」,保存并发布后,将 ID 填入上方「卡片模板 ID」。是否保留思考仍由流水线设置控制。 - zh_Hant: 分開展示思考與正文。在釘釘 AI 卡片編輯器中選擇「更多 → 匯入卡片範本」,儲存並發布後,將 ID 填入上方「卡片範本 ID」。是否保留思考仍由流水線設定控制。 - type: download-link - required: false - default: '' - url: /api/v1/platform/adapters/dingtalk/stream-card-template - download_filename: dingtalk_stream_card.json - - name: card_auto_layout - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: Card Auto Layout - zh_Hans: 卡片宽屏自动布局 - zh_Hant: 卡片寬螢幕自動佈局 - description: - en_US: Enabled by default. Allows supported cards to adapt to wider windows. The LangBot streaming reply template includes the required variables; you can disable this for a narrower layout. - zh_Hans: 默认开启,让支持的卡片适应较宽的聊天窗口。LangBot 流式回复模板已包含所需变量;如需较窄布局,可关闭此项。 - zh_Hant: 預設開啟,讓支援的卡片適應較寬的聊天視窗。LangBot 串流回覆範本已包含所需變數;如需較窄版面,可關閉此項。 - type: boolean - required: false - default: true - - name: human_input_card_template_id - label: - en_US: Human Input Card Template ID - zh_Hans: 人工输入卡片模板 ID - zh_Hant: 人工輸入卡片範本 ID - description: - en_US: Optional. Used when a workflow or plugin requests user input, a choice, or confirmation before continuing (for example, a Dify Human Input node). Ordinary chat does not require it. Import the template below and enter its published ID here; streaming text replies use the separate Card Template ID. - zh_Hans: 可选。当工作流或插件需要用户填写信息、选择选项或确认后再继续执行时使用,例如 Dify 的人工输入节点。普通聊天无需配置。请导入下方模板,将发布后的 ID 填在这里;流式文字回复使用单独的「卡片模板 ID」。 - zh_Hant: 可選。當工作流或外掛需要使用者填寫資訊、選擇選項或確認後再繼續執行時使用,例如 Dify 的人工輸入節點。一般聊天無需設定。請匯入下方範本,將發布後的 ID 填在這裡;串流文字回覆使用獨立的「卡片範本 ID」。 - type: string - required: false - default: "" - - name: human_input_card_template_download - label: - en_US: Download Human Input Card Template - zh_Hans: 下载人工输入卡片模板 - zh_Hant: 下載人工輸入卡片範本 - description: - en_US: Download the human input template. Create an AI card in DingTalk Card Platform, choose More > Import Card Template in the editor, then save and publish. Paste its ID into the field above. - zh_Hans: 下载人工输入模板后,在钉钉卡片平台新建 AI 卡片,在编辑器中选择「更多 → 导入卡片模板」,保存并发布,将 ID 填入上方字段。 - zh_Hant: 下載人工輸入範本後,在釘釘卡片平台新建 AI 卡片,在編輯器中選擇「更多 → 匯入卡片範本」,儲存並發布,將 ID 填入上方欄位。 - type: download-link - required: false - default: '' - url: /api/v1/platform/adapters/dingtalk/human-input-card-template - download_filename: dingtalk_human_input_card.json - help_links: - zh: https://langbot.app/docs/zh/usage/platforms/dingtalk#导入人工输入卡片模板 - en: https://open-dev.dingtalk.com/fe/card - ja: https://open-dev.dingtalk.com/fe/card - help_label: - en_US: Import Guide - zh_Hans: 导入指引 - zh_Hant: 匯入指引 - ja_JP: インポート手順 supported_events: - message.received @@ -156,6 +71,7 @@ spec: - group.info_updated - dingtalk.card_action - platform.specific + - interaction.callback supported_apis: required: @@ -170,7 +86,9 @@ spec: - get_friend_list - get_file_url - call_platform_api - - interaction.request + - send_interaction + - get_interaction_capabilities + - update_interaction platform_specific_apis: - action: check_access_token diff --git a/src/langbot/pkg/platform/adapters/discord/adapter.py b/src/langbot/pkg/platform/adapters/discord/adapter.py index 374c008cf..6bd1cefa1 100644 --- a/src/langbot/pkg/platform/adapters/discord/adapter.py +++ b/src/langbot/pkg/platform/adapters/discord/adapter.py @@ -1,5 +1,6 @@ from __future__ import annotations +import collections import os import time import traceback @@ -22,6 +23,11 @@ from langbot.pkg.platform.adapters.discord.interaction import ( ) from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter): @@ -32,6 +38,13 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform _stream_buffer: dict = pydantic.PrivateAttr(default_factory=dict) _STREAM_EDIT_INTERVAL: typing.ClassVar[int] = 8 + # Guild conversations are keyed by guild id, so interaction replies resolve + # their channel from the message they answer. + _message_channels: collections.OrderedDict = pydantic.PrivateAttr(default_factory=collections.OrderedDict) + # Callbacks must report the conversation the card was sent for, which may be + # a guild rather than the channel the button lives in. + _interaction_targets: collections.OrderedDict = pydantic.PrivateAttr(default_factory=collections.OrderedDict) + _MESSAGE_CHANNEL_LIMIT: typing.ClassVar[int] = 1024 config: dict listeners: dict[ typing.Type[platform_events.Event], @@ -54,6 +67,7 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform return if message.author.bot: return + adapter_self._remember_message_channel(message) try: if ( platform_events.FriendMessage in adapter_self.listeners @@ -85,7 +99,12 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform if not interaction.response.is_done(): await interaction.response.defer() try: - await adapter_self._dispatch_eba_event(interaction_event_from_component(interaction, parsed)) + conversation = adapter_self._interaction_targets.get( + str(interaction.message.id) if interaction.message is not None else '' + ) + await adapter_self._dispatch_eba_event( + interaction_event_from_component(interaction, parsed, conversation) + ) if interaction.message is not None: await interaction.message.edit(view=None) except Exception: @@ -185,6 +204,7 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform 'bot.invited_to_group', 'bot.removed_from_group', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -204,12 +224,72 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform 'kick_member', 'leave_group', 'call_platform_api', - 'interaction.request', + 'send_interaction', + 'update_interaction', + 'get_interaction_capabilities', ] def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + handle.context['target_id'] = target_id + self._remember(self._interaction_targets, str(handle.message_id), (target_type, str(target_id))) + return handle + + def _remember_message_channel(self, message: discord.Message) -> None: + self._remember(self._message_channels, str(message.id), message.channel.id) + + def _remember(self, cache: collections.OrderedDict, key: str, value: typing.Any) -> None: + cache[key] = value + cache.move_to_end(key) + while len(cache) > self._MESSAGE_CHANNEL_LIMIT: + cache.popitem(last=False) + + async def _resolve_interaction_channel( + self, target_type: str, target_id: str, reply_to: str | None + ) -> discord.abc.Messageable: + channel_id = self._message_channels.get(str(reply_to)) if reply_to is not None else None + if channel_id is not None: + return await self._get_channel(channel_id) + guild = self.bot.get_guild(int(target_id)) if target_type == 'group' else None + if guild is not None: + # Match send_message: without an originating message, use the system channel. + if guild.system_channel is None: + raise ValueError('Discord guild has no system channel configured for interactions') + return guild.system_channel + return await self._get_channel(target_id) + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + del submission + channel = await self._get_channel(str(handle.context.get('channel_id') or handle.context['target_id'])) + message = await channel.fetch_message(int(handle.message_id)) + label = {'submitted': 'Submitted', 'expired': 'Expired', 'cancelled': 'Cancelled'}[state] + await message.edit(content=f'{handle.context["request"]["title"]}\n\n{label}', view=None) + return handle + async def send_message(self, target_type: str, target_id: str, message: platform_message.MessageChain): content, files = await self.message_converter.yiri2target(message) guild = self.bot.get_guild(int(target_id)) if target_type == 'group' else None @@ -278,8 +358,6 @@ class DiscordAdapter(DiscordAPIMixin, abstract_platform_adapter.AbstractPlatform self.listeners.pop(event_type, None) async def call_platform_api(self, action: str, params: dict = {}) -> dict: - if action == 'interaction.request': - return await send_interaction(self, params) handler = PLATFORM_API_MAP.get(action) if handler is None: from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError diff --git a/src/langbot/pkg/platform/adapters/discord/interaction.py b/src/langbot/pkg/platform/adapters/discord/interaction.py index a66e29808..a09efd2fa 100644 --- a/src/langbot/pkg/platform/adapters/discord/interaction.py +++ b/src/langbot/pkg/platform/adapters/discord/interaction.py @@ -100,33 +100,38 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') target_id = str(reply_target.get('target_id') or '') if not target_id: - raise ValueError('interaction.request has no target_id') - channel = await adapter._get_channel(target_id) + raise ValueError('send_interaction has no target_id') + channel = await adapter._resolve_interaction_channel( + str(reply_target.get('target_type') or ''), target_id, reply_target.get('message_id') + ) view = build_interaction_view(request, callback_token) sent = await channel.send(content=_content(request, rich=view is not None), view=view) - return {'ok': True, 'message_id': sent.id, 'rich': view is not None} + return {'ok': True, 'message_id': sent.id, 'rich': view is not None, 'context': {'channel_id': str(channel.id)}} def interaction_event_from_component( interaction: discord.Interaction, parsed: dict[str, typing.Any], -) -> platform_events.PlatformSpecificEvent: + conversation: tuple[str, str] | None = None, +) -> platform_events.InteractionCallbackEvent: + """Build a callback event; ``conversation`` is the target the card was sent for.""" if interaction.user is None or interaction.channel is None: raise ValueError('Discord interaction has no actor or channel') - return platform_events.PlatformSpecificEvent( - type='platform.specific', + target_type, target_id = conversation or ( + 'group' if interaction.guild is not None else 'person', + str(interaction.channel.id), + ) + return platform_events.InteractionCallbackEvent( adapter_name='discord-omni', - action='interaction.submitted', - data={ - **parsed, - 'actor_id': str(interaction.user.id), - 'target_type': 'group' if interaction.guild is not None else 'person', - 'target_id': str(interaction.channel.id), - 'display_text': 'submitted', - }, + callback_token=str(parsed.get('callback_token') or ''), + actor_id=str(interaction.user.id), + target_type=target_type, + target_id=target_id, + callback_context={'channel_id': str(interaction.channel.id)}, + raw_submission=parsed, timestamp=time.time(), source_platform_object=interaction, ) diff --git a/src/langbot/pkg/platform/adapters/discord/manifest.yaml b/src/langbot/pkg/platform/adapters/discord/manifest.yaml index 0ddd1c02a..d696512a0 100644 --- a/src/langbot/pkg/platform/adapters/discord/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/discord/manifest.yaml @@ -45,6 +45,7 @@ spec: - bot.invited_to_group - bot.removed_from_group - platform.specific + - interaction.callback supported_apis: required: @@ -64,7 +65,9 @@ spec: - kick_member - leave_group - call_platform_api - - interaction.request + - send_interaction + - update_interaction + - get_interaction_capabilities platform_specific_apis: - action: get_channel diff --git a/src/langbot/pkg/platform/adapters/lark/adapter.py b/src/langbot/pkg/platform/adapters/lark/adapter.py index ec0635968..3b274cf84 100644 --- a/src/langbot/pkg/platform/adapters/lark/adapter.py +++ b/src/langbot/pkg/platform/adapters/lark/adapter.py @@ -80,6 +80,11 @@ from langbot_plugin.api.entities.builtin.platform import entities as platform_en from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class AESCipher: @@ -231,6 +236,7 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte 'message.deleted', 'message.reaction', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -243,13 +249,53 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte 'get_user_info', 'get_file_url', 'call_platform_api', - 'interaction.request', - 'interaction.acknowledge', + 'send_interaction', + 'update_interaction', + 'get_interaction_capabilities', ] def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + return handle + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + result = await acknowledge_interaction( + self, + { + 'update_target': handle.model_dump(mode='json'), + 'request': handle.context['request'], + 'submission': submission.model_dump(mode='json') if submission else {}, + 'state': state, + }, + ) + updated = InteractionHandle.model_validate(result) + updated.context.update(handle.context) + return updated + @staticmethod def _plain_message(text: str) -> platform_message.MessageChain: return platform_message.MessageChain([platform_message.Plain(text=text)]) @@ -490,6 +536,31 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte self.reply_to_monitoring_msg.pop(next(iter(self.reply_to_monitoring_msg)), None) return True + async def create_message_card_for_target(self, message_id: str, target_type: str, target_id: str) -> bool: + if target_type not in {'group', 'person'} or not target_id: + raise ValueError('Lark streaming card requires a group or person target') + card_id = await self.create_card_id(message_id) + content = {'type': 'card', 'data': {'card_id': card_id, 'template_variable': {'content': 'Thinking...'}}} + request = ( + CreateMessageRequest.builder() + .receive_id_type('chat_id' if target_type == 'group' else 'open_id') + .request_body( + CreateMessageRequestBody.builder() + .receive_id(target_id) + .content(json.dumps(content)) + .msg_type('interactive') + .uuid(str(uuid.uuid4())) + .build() + ) + .build() + ) + response: CreateMessageResponse = await self.api_client.im.v1.message.acreate(request) + if not response.success(): + self.card_id_dict.pop(message_id, None) + self.card_sequence_dict.pop(card_id, None) + raise RuntimeError(f'Lark create_message_card_for_target failed: {response.code} {response.msg}') + return True + async def create_card_id(self, message_id) -> str: while len(self.card_id_dict) >= 1000: old_key = next(iter(self.card_id_dict)) @@ -552,13 +623,6 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte quote_origin: bool = False, is_final: bool = False, ): - card_id = self.card_id_dict[bot_message.resp_message_id] - has_sent_update = self.card_sequence_dict.get(card_id, 0) > 0 - now = time.monotonic() - last_update = self.card_last_update_dict.get(card_id, 0.0) - is_high_frequency_chunk = now - last_update < 1.0 - if has_sent_update and is_high_frequency_chunk and bot_message.msg_sequence % 8 != 0 and not is_final: - return cumulative_content = getattr(bot_message, 'all_content', None) if isinstance(cumulative_content, str) and cumulative_content: content = cumulative_content @@ -568,8 +632,37 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte ''.join(ele.get('text', '') for ele in paragraph if ele.get('tag') in {'text', 'md'}) for paragraph in text_elements ) - if (is_final and not bot_message.tool_calls) or card_id in self.closed_streaming_cards: - await self._replace_streaming_card(card_id, content, finished=is_final and not bot_message.tool_calls) + await self._update_streaming_card( + bot_message.resp_message_id, + content, + is_final=is_final, + tool_calls=bot_message.tool_calls, + msg_sequence=bot_message.msg_sequence, + tenant_key=self._tenant_key_from_source(message_source), + ) + + async def reply_message_chunk_for_target(self, *, message_id: str, content: str, is_final: bool) -> None: + await self._update_streaming_card(message_id, content, is_final=is_final, msg_sequence=1) + + async def _update_streaming_card( + self, + message_id: str, + content: str, + *, + is_final: bool, + msg_sequence: int, + tool_calls: typing.Any = None, + tenant_key: str | None = None, + ) -> None: + card_id = self.card_id_dict[message_id] + has_sent_update = self.card_sequence_dict.get(card_id, 0) > 0 + now = time.monotonic() + last_update = self.card_last_update_dict.get(card_id, 0.0) + is_high_frequency_chunk = now - last_update < 1.0 + if has_sent_update and is_high_frequency_chunk and msg_sequence % 8 != 0 and not is_final: + return + if (is_final and not tool_calls) or card_id in self.closed_streaming_cards: + await self._replace_streaming_card(card_id, content, finished=is_final and not tool_calls) else: sequence = self._next_card_sequence(card_id) request = ( @@ -582,28 +675,22 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte .build() ) response: ContentCardElementResponse = await self.api_client.cardkit.v1.card_element.acontent( - request, self.request_option(self._tenant_key_from_source(message_source)) + request, self.request_option(tenant_key) ) if not response.success(): if self._streaming_mode_closed(response): - await self._replace_streaming_card( - card_id, content, finished=is_final and not bot_message.tool_calls - ) + await self._replace_streaming_card(card_id, content, finished=is_final and not tool_calls) else: raise RuntimeError(f'Lark card_element update failed: {response.code} {response.msg}') self.card_last_update_dict[card_id] = now - if is_final and bot_message.tool_calls is None: - self.card_id_dict.pop(bot_message.resp_message_id, None) + if is_final and tool_calls is None: + self.card_id_dict.pop(message_id, None) self.card_sequence_dict.pop(card_id, None) self.card_last_update_dict.pop(card_id, None) self.closed_streaming_cards.discard(card_id) @localized_adapter async def call_platform_api(self, action: str, params: dict = {}) -> dict: - if action == 'interaction.request': - return await send_interaction(self, params) - if action == 'interaction.acknowledge': - return await acknowledge_interaction(self, params) handler = PLATFORM_API_MAP.get(action) if handler is None: raise NotSupportedError(f'call_platform_api:{action}') @@ -951,11 +1038,11 @@ class LarkAdapter(LarkAPIMixin, abstract_platform_adapter.AbstractPlatformAdapte {'toast': {'type': 'success', 'content': adapter_t(self, 'Thank you for your feedback')}} ) - def _interaction_action_response(self, event: platform_events.PlatformSpecificEvent) -> dict[str, typing.Any]: + def _interaction_action_response(self, event: platform_events.InteractionCallbackEvent) -> dict[str, typing.Any]: response: dict[str, typing.Any] = { 'toast': {'type': 'success', 'content': adapter_t(self, 'Submitted')}, } - if not event.data.get('cardkit'): + if not event.raw_submission.get('cardkit'): response['card'] = { 'type': 'raw', 'data': { diff --git a/src/langbot/pkg/platform/adapters/lark/interaction.py b/src/langbot/pkg/platform/adapters/lark/interaction.py index 8896f6316..c202e9942 100644 --- a/src/langbot/pkg/platform/adapters/lark/interaction.py +++ b/src/langbot/pkg/platform/adapters/lark/interaction.py @@ -361,7 +361,7 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') update_target = params.get('update_target') submitted_values = _stored_submitted_values( @@ -383,7 +383,7 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - target_type = str(reply_target.get('target_type') or '') target_id = str(reply_target.get('target_id') or '') if target_type not in {'group', 'person'} or not target_id: - raise ValueError('interaction.request has an invalid reply target') + raise ValueError('send_interaction has an invalid reply target') card_request = ( CreateCardRequest.builder() .request_body( @@ -429,15 +429,22 @@ async def acknowledge_interaction(adapter: typing.Any, params: dict[str, typing. submission = params.get('submission') update_target = params.get('update_target') if not isinstance(request, dict) or not isinstance(submission, dict) or not isinstance(update_target, dict): - raise ValueError('interaction.acknowledge requires request, submission, and update_target') - submitted_values = [ - *_stored_submitted_values(update_target.get('submitted_values')), - *_submission_display_values(request, submission), - ] + raise ValueError('update_interaction requires request, submission, and update_target') + state = params.get('state', 'submitted') + submitted_values = _stored_submitted_values(update_target.get('submitted_values')) + if state == 'submitted': + submitted_values.extend(_submission_display_values(request, submission)) + else: + submitted_values.append({'label': '', 'value': 'Expired' if state == 'expired' else 'Cancelled'}) + card = ( + build_submitted_card(request, submission, _stored_submitted_values(update_target.get('submitted_values'))) + if state == 'submitted' + else build_submitted_card(request, {}, submitted_values) + ) return await _update_interaction_card( adapter, update_target, - build_submitted_card(request, submission, _stored_submitted_values(update_target.get('submitted_values'))), + card, submitted_values, ) @@ -507,7 +514,7 @@ def _event_from_parts( actor_id: typing.Any, chat_id: typing.Any, message_id: typing.Any, -) -> platform_events.PlatformSpecificEvent | None: +) -> platform_events.InteractionCallbackEvent | None: payload = _mapping(_action_attr(action, 'value')) callback_token = str(payload.get('lbi') or '') if not callback_token: @@ -532,17 +539,21 @@ def _event_from_parts( data['option_ref'] = payload.get('o') if payload.get('fm'): data['values'] = _form_submission_values(action, payload) - return platform_events.PlatformSpecificEvent( - type='platform.specific', + return platform_events.InteractionCallbackEvent( adapter_name='lark-omni', - action='interaction.submitted', - data=data, + callback_token=callback_token, + values=data.get('values', {}), + actor_id=data['actor_id'], + target_type=target_type, + target_id=target_id, + callback_context={'message_id': str(message_id)} if message_id else {}, + raw_submission=data, timestamp=time.time(), source_platform_object=raw, ) -def interaction_event_from_callback(event: typing.Any) -> platform_events.PlatformSpecificEvent | None: +def interaction_event_from_callback(event: typing.Any) -> platform_events.InteractionCallbackEvent | None: action = getattr(getattr(event, 'event', None), 'action', None) operator = getattr(getattr(event, 'event', None), 'operator', None) context = getattr(getattr(event, 'event', None), 'context', None) @@ -555,7 +566,7 @@ def interaction_event_from_callback(event: typing.Any) -> platform_events.Platfo ) -def interaction_event_from_webhook(data: dict[str, typing.Any]) -> platform_events.PlatformSpecificEvent | None: +def interaction_event_from_webhook(data: dict[str, typing.Any]) -> platform_events.InteractionCallbackEvent | None: event = data.get('event') if isinstance(data.get('event'), dict) else {} action = event.get('action') if isinstance(event.get('action'), dict) else {} operator = event.get('operator') if isinstance(event.get('operator'), dict) else {} diff --git a/src/langbot/pkg/platform/adapters/lark/manifest.yaml b/src/langbot/pkg/platform/adapters/lark/manifest.yaml index f13f84369..575d4776c 100644 --- a/src/langbot/pkg/platform/adapters/lark/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/lark/manifest.yaml @@ -252,6 +252,7 @@ spec: - message.deleted - message.reaction - platform.specific + - interaction.callback supported_apis: required: @@ -264,8 +265,9 @@ spec: - get_user_info - get_file_url - call_platform_api - - interaction.request - - interaction.acknowledge + - send_interaction + - update_interaction + - get_interaction_capabilities platform_specific_apis: - action: check_tenant_access_token diff --git a/src/langbot/pkg/platform/adapters/qqofficial/adapter.py b/src/langbot/pkg/platform/adapters/qqofficial/adapter.py index c0dfa8d25..e84876151 100644 --- a/src/langbot/pkg/platform/adapters/qqofficial/adapter.py +++ b/src/langbot/pkg/platform/adapters/qqofficial/adapter.py @@ -33,6 +33,11 @@ import langbot_plugin.api.definition.abstract.platform.event_logger as abstract_ from langbot_plugin.api.entities.builtin.platform import entities as platform_entities from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter): @@ -56,9 +61,12 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl _stream_ctx_ts: dict[str, float] = {} _fallback_text: dict[str, str] = {} _fallback_text_ts: dict[str, float] = {} + _anchor_msg_seq: dict[str, int] = {} _ws_task: asyncio.Task | None = None + _gateway_tasks: set[asyncio.Task] = set() _STREAM_CTX_TTL = 300 + _MAX_REPLIES_PER_ANCHOR = 5 class Config: arbitrary_types_allowed = True @@ -93,7 +101,9 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl _stream_ctx_ts={}, _fallback_text={}, _fallback_text_ts={}, + _anchor_msg_seq={}, _ws_task=None, + _gateway_tasks=set(), ) self._register_native_handlers() @@ -109,6 +119,7 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl 'bot.invited_to_group', 'bot.removed_from_group', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -122,12 +133,63 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl 'get_group_member_list', 'get_group_member_info', 'call_platform_api', - 'interaction.request', + 'send_interaction', + 'update_interaction', + 'get_interaction_capabilities', ] def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + handle.context['target_type'] = target_type + handle.context['target_id'] = target_id + return handle + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + del submission + label = {'submitted': 'Submitted', 'expired': 'Expired', 'cancelled': 'Cancelled'}[state] + await self.send_message( + str(handle.context['target_type']), + str(handle.context['target_id']), + self._plain_message(f'{handle.context["request"]["title"]}: {label}'), + ) + return handle + + def next_interaction_msg_seq(self, anchor: str) -> int | None: + """Allocate QQ's per-anchor passive reply sequence for interaction cards.""" + if not anchor: + return 1 + used = self._anchor_msg_seq.get(anchor, 0) + if used >= self._MAX_REPLIES_PER_ANCHOR: + return None + self._anchor_msg_seq[anchor] = used + 1 + while len(self._anchor_msg_seq) > 4096: + self._anchor_msg_seq.pop(next(iter(self._anchor_msg_seq)), None) + return used + 1 + @staticmethod def _plain_message(text: str) -> platform_message.MessageChain: return platform_message.MessageChain([platform_message.Plain(text=text)]) @@ -172,8 +234,6 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl return platform_events.MessageResult(message_id=source.d_id or source.id, raw={'results': raw}) async def call_platform_api(self, action: str, params: dict = {}) -> dict: - if action == 'interaction.request': - return await send_interaction(self, params) handler = PLATFORM_API_MAP.get(action) if handler is None: raise NotSupportedError(f'call_platform_api:{action}') @@ -251,7 +311,13 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl except asyncio.CancelledError: pass self._ws_task = None + for task in tuple(self._gateway_tasks): + task.cancel() + if self._gateway_tasks: + await asyncio.gather(*self._gateway_tasks, return_exceptions=True) + self._gateway_tasks.clear() await self.bot.close() + self._anchor_msg_seq.clear() self._stream_ctx.clear() self._stream_ctx_ts.clear() self._fallback_text.clear() @@ -277,7 +343,7 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl 'user_openid': source.user_openid, 'msg_id': source.d_id, 'stream_msg_id': None, - 'msg_seq': 1, + 'msg_seq': None, 'index': 0, 'last_update_ts': 0, 'accumulated_text': '', @@ -335,6 +401,9 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl return ctx['last_update_ts'] = now + if ctx['msg_seq'] is None: + ctx['msg_seq'] = self.bot.allocate_msg_seq() + resp = await self.bot.send_stream_msg( user_openid=ctx['user_openid'], content=content_to_send, @@ -372,7 +441,20 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl await self.bot.ack_interaction(interaction_id) event = interaction_event_from_payload(event_data) if event is not None: - await self._dispatch_eba_event(event) + self._queue_gateway_event(self._dispatch_eba_event(event)) + + def _queue_gateway_event(self, awaitable: typing.Awaitable[None]) -> None: + async def run() -> None: + try: + await awaitable + except asyncio.CancelledError: + raise + except Exception: + await self.logger.error(f'Error in qqofficial gateway event: {traceback.format_exc()}') + + task = asyncio.create_task(run()) + self._gateway_tasks.add(task) + task.add_done_callback(self._gateway_tasks.discard) async def _handle_native_event(self, event: QQOfficialEvent): self.bot_account_id = self.config.get('appid', self.bot_account_id) @@ -429,12 +511,12 @@ class QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPl await self.logger.warning(f'Event data is not dict, skipping: {event_type} -> {type(event_data)}') return if event_type not in MESSAGE_EVENT_TYPES: - await self._handle_native_event(QQOfficialEvent({'t': event_type, **event_data})) + self._queue_gateway_event(self._handle_native_event(QQOfficialEvent({'t': event_type, **event_data}))) return payload = {'t': event_type, 'd': event_data} message_data = await self.bot.get_message(payload) if message_data: - await self.bot._handle_message(QQOfficialEvent.from_payload(message_data)) + self._queue_gateway_event(self.bot._handle_message(QQOfficialEvent.from_payload(message_data))) async def on_error(error: Exception): await self.logger.error(f'QQ Official WebSocket error: {error}') diff --git a/src/langbot/pkg/platform/adapters/qqofficial/interaction.py b/src/langbot/pkg/platform/adapters/qqofficial/interaction.py index be28492fa..90f36b3f8 100644 --- a/src/langbot/pkg/platform/adapters/qqofficial/interaction.py +++ b/src/langbot/pkg/platform/adapters/qqofficial/interaction.py @@ -12,7 +12,7 @@ def interaction_delivery_capabilities() -> dict[str, typing.Any]: return { 'field_types': ['select'], 'action_styles': ['default', 'primary', 'danger'], - 'supports_updates': True, + 'supports_updates': False, 'max_fields': 1, } @@ -94,7 +94,7 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') target_type = str(reply_target.get('target_type') or '') target_id = str(reply_target.get('target_id') or '') keyboard = build_interaction_keyboard(request, callback_token) @@ -105,12 +105,23 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - adapter._plain_message(_text(request, False)), ) return {'ok': True, 'message_id': result.message_id, 'rich': False} + msg_id = reply_target.get('message_id') + if msg_id in (None, '', -1, '-1'): + msg_id = None + event_id = reply_target.get('event_id') + if event_id in (None, '', -1, '-1'): + event_id = None + anchor = str(msg_id or event_id or '') + if adapter.next_interaction_msg_seq(anchor) is None: + raise ValueError('QQ interaction reply limit reached for this message') raw = await adapter.bot.send_markdown_keyboard( target_type='c2c' if target_type == 'person' else 'group', target_id=target_id, markdown_content=_text(request, True), keyboard=keyboard, - msg_id=reply_target.get('message_id'), + msg_id=msg_id, + event_id=event_id, + msg_seq=None, ) return {'ok': True, 'message_id': raw.get('id') if isinstance(raw, dict) else None, 'rich': True} @@ -137,7 +148,7 @@ def parse_callback_data(value: str) -> dict[str, typing.Any]: def interaction_event_from_payload( event_data: dict[str, typing.Any], -) -> platform_events.PlatformSpecificEvent | None: +) -> platform_events.InteractionCallbackEvent | None: resolved = (event_data.get('data') or {}).get('resolved') or {} callback_data = str(resolved.get('button_data') or '') if not callback_data.startswith('lbi:'): @@ -161,17 +172,13 @@ def interaction_event_from_payload( or ((event_data.get('member') or {}).get('user') or {}).get('id') or '' ) - return platform_events.PlatformSpecificEvent( - type='platform.specific', + return platform_events.InteractionCallbackEvent( adapter_name='qqofficial-omni', - action='interaction.submitted', - data={ - **parsed, - 'actor_id': actor_id, - 'target_type': target_type, - 'target_id': target_id, - 'display_text': 'submitted', - }, + callback_token=str(parsed.get('callback_token') or ''), + actor_id=actor_id, + target_type=target_type, + target_id=target_id, + raw_submission=parsed, timestamp=time.time(), source_platform_object=event_data, ) diff --git a/src/langbot/pkg/platform/adapters/qqofficial/manifest.yaml b/src/langbot/pkg/platform/adapters/qqofficial/manifest.yaml index 0b6caa430..d4a7b20e2 100644 --- a/src/langbot/pkg/platform/adapters/qqofficial/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/qqofficial/manifest.yaml @@ -132,6 +132,7 @@ spec: - bot.invited_to_group - bot.removed_from_group - platform.specific + - interaction.callback supported_apis: required: @@ -145,7 +146,9 @@ spec: - get_group_member_list - get_group_member_info - call_platform_api - - interaction.request + - send_interaction + - update_interaction + - get_interaction_capabilities platform_specific_apis: - action: check_access_token diff --git a/src/langbot/pkg/platform/adapters/telegram/adapter.py b/src/langbot/pkg/platform/adapters/telegram/adapter.py index 4f1664726..76e91fc10 100644 --- a/src/langbot/pkg/platform/adapters/telegram/adapter.py +++ b/src/langbot/pkg/platform/adapters/telegram/adapter.py @@ -39,6 +39,11 @@ from langbot.pkg.platform.adapters.telegram.interaction import ( parse_interaction_callback, send_interaction, ) +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class TelegramAdapter(TelegramAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter): @@ -179,6 +184,7 @@ class TelegramAdapter(TelegramAPIMixin, abstract_platform_adapter.AbstractPlatfo 'bot.muted', 'bot.unmuted', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -198,12 +204,53 @@ class TelegramAdapter(TelegramAPIMixin, abstract_platform_adapter.AbstractPlatfo 'kick_member', 'leave_group', 'call_platform_api', - 'interaction.request', + 'send_interaction', + 'update_interaction', + 'get_interaction_capabilities', ] def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self.bot, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + handle.context['target_id'] = target_id + return handle + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + del submission + target_id = str(handle.context['target_id']).split('#', 1)[0] + request = handle.context['request'] + label = {'submitted': 'Submitted', 'expired': 'Expired', 'cancelled': 'Cancelled'}[state] + await self.bot.edit_message_text( + chat_id=int(target_id) if target_id.lstrip('-').isdigit() else target_id, + message_id=handle.message_id, + text=f'{request["title"]}\n\n{label}', + reply_markup=None, + ) + return handle + # ---- Message Send / Reply (preserving original logic) ---- async def send_message(self, target_type: str, target_id: str, message: platform_message.MessageChain): @@ -559,8 +606,6 @@ class TelegramAdapter(TelegramAPIMixin, abstract_platform_adapter.AbstractPlatfo params: dict = {}, ) -> dict: """Call a Telegram-specific platform API.""" - if action == 'interaction.request': - return await send_interaction(self.bot, params) handler = PLATFORM_API_MAP.get(action) if handler is None: from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError diff --git a/src/langbot/pkg/platform/adapters/telegram/interaction.py b/src/langbot/pkg/platform/adapters/telegram/interaction.py index 38f5a5584..11eb7e706 100644 --- a/src/langbot/pkg/platform/adapters/telegram/interaction.py +++ b/src/langbot/pkg/platform/adapters/telegram/interaction.py @@ -110,11 +110,11 @@ async def send_interaction(bot: telegram.Bot, params: dict[str, typing.Any]) -> reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') target_id = str(reply_target.get('target_id') or '') if not target_id: - raise ValueError('interaction.request has no target_id') + raise ValueError('send_interaction has no target_id') chat_id_text, _, thread_id_text = target_id.partition('#') chat_id: int | str = int(chat_id_text) if chat_id_text.lstrip('-').isdigit() else chat_id_text message_thread_id = int(thread_id_text) if thread_id_text.isdigit() else None @@ -135,7 +135,7 @@ async def send_interaction(bot: telegram.Bot, params: dict[str, typing.Any]) -> def interaction_event_from_update( update: telegram.Update, parsed: dict[str, typing.Any], -) -> platform_events.PlatformSpecificEvent: +) -> platform_events.InteractionCallbackEvent: """Convert a trusted callback shape into the Host interaction event.""" query = update.callback_query if query is None or query.message is None or query.from_user is None: @@ -153,11 +153,13 @@ def interaction_event_from_update( 'target_id': target_id, 'display_text': 'submitted', } - return platform_events.PlatformSpecificEvent( - type='platform.specific', + return platform_events.InteractionCallbackEvent( timestamp=time.time(), adapter_name='telegram-omni', - action='interaction.submitted', - data=data, + callback_token=str(parsed.get('callback_token') or ''), + actor_id=data['actor_id'], + target_type=target_type, + target_id=target_id, + raw_submission=parsed, source_platform_object=update, ) diff --git a/src/langbot/pkg/platform/adapters/telegram/manifest.yaml b/src/langbot/pkg/platform/adapters/telegram/manifest.yaml index c54902a97..2d0facf19 100644 --- a/src/langbot/pkg/platform/adapters/telegram/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/telegram/manifest.yaml @@ -57,6 +57,7 @@ spec: - bot.muted - bot.unmuted - platform.specific + - interaction.callback supported_apis: required: @@ -76,7 +77,9 @@ spec: - kick_member - leave_group - call_platform_api - - interaction.request + - send_interaction + - update_interaction + - get_interaction_capabilities platform_specific_apis: - action: pin_message diff --git a/src/langbot/pkg/platform/adapters/wecombot/adapter.py b/src/langbot/pkg/platform/adapters/wecombot/adapter.py index 09f7c8e16..622c86225 100644 --- a/src/langbot/pkg/platform/adapters/wecombot/adapter.py +++ b/src/langbot/pkg/platform/adapters/wecombot/adapter.py @@ -18,6 +18,7 @@ from langbot.pkg.platform.adapters.wecombot.event_converter import WecomBotEvent from langbot.pkg.platform.adapters.wecombot.message_converter import WecomBotMessageConverter from langbot.pkg.platform.adapters.wecombot.platform_api import PLATFORM_API_MAP from langbot.pkg.platform.adapters.wecombot.interaction import ( + acknowledge_interaction, interaction_delivery_capabilities, interaction_event_from_native, send_interaction, @@ -28,6 +29,11 @@ from langbot_plugin.api.entities.builtin.platform import entities as platform_en from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter): @@ -108,6 +114,7 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo 'wecombot.enter_chat', 'wecombot.template_card_event', 'platform.specific', + 'interaction.callback', ] def get_supported_apis(self) -> list[str]: @@ -123,12 +130,58 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo 'call_platform_api', ] if not self.config.get('enable-webhook', False) and hasattr(self.bot, 'send_template_card'): - apis.append('interaction.request') + apis.extend( + [ + 'send_interaction', + 'update_interaction', + 'get_interaction_capabilities', + ] + ) return apis def get_interaction_capabilities(self) -> dict[str, typing.Any]: return interaction_delivery_capabilities() + async def send_interaction( + self, + target_type: str, + target_id: str, + request: InteractionRequest, + callback_token: str, + reply_to: str | None = None, + ) -> InteractionHandle: + result = await send_interaction( + self, + { + 'request': request.model_dump(mode='json'), + 'callback_token': callback_token, + 'reply_target': {'target_type': target_type, 'target_id': target_id, 'message_id': reply_to}, + }, + ) + handle = InteractionHandle.model_validate(result) + handle.context['request'] = request.model_dump(mode='json') + return handle + + async def update_interaction( + self, + handle: InteractionHandle, + state: str, + submission: InteractionSubmission | None = None, + ) -> InteractionHandle: + result = await acknowledge_interaction( + self, + { + 'update_target': handle.model_dump(mode='json'), + 'request': handle.context['request'], + 'submission': submission.model_dump(mode='json') if submission else {}, + 'callback_context': handle.context.get('callback_context') or {}, + 'state': state, + }, + ) + updated = InteractionHandle.model_validate(result) + updated.context.update(handle.context) + return updated + @staticmethod def _plain_message(text: str) -> platform_message.MessageChain: return platform_message.MessageChain([platform_message.Plain(text=text)]) @@ -236,6 +289,9 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo if list(self._iter_media_components(items)): raise NotSupportedError('send_message:media requires an originating message callback') raw = await self.bot.send_message(str(target_id), content) + if not isinstance(raw, dict) or raw.get('errcode', 0) != 0: + detail = raw.get('errmsg', raw.get('errcode')) if isinstance(raw, dict) else 'no acknowledgement' + raise RuntimeError(f'WeCom message delivery failed: {detail}') return platform_events.MessageResult(raw={'result': raw}) async def reply_to_event( @@ -284,8 +340,8 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo if not self.config.get('enable-webhook', False) and event.get('req_id'): if content: finished = await self.bot.push_stream_chunk(event.message_id, content, is_final=True) - if not finished: - raw = await self.bot.reply_text(event.get('req_id'), content) + if not finished and content.strip(' \t\r\n\u200b\u200c\u200d\ufeff'): + raw = await self.bot.send_message(str(event.get('chatid') or event.get('userid') or ''), content) for item in self._iter_media_components(items): await self._send_media(self.bot, event.get('req_id'), item, self.config) else: @@ -310,8 +366,14 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo content = format_stream_text(self._join_text_components(items)) success = await self.bot.push_stream_chunk(event.message_id, content, is_final=is_final) - if not success and is_final and not self.config.get('enable-webhook', False) and event.get('req_id'): - await self.bot.reply_text(event.get('req_id'), content) + if ( + not success + and is_final + and content.strip(' \t\r\n\u200b\u200c\u200d\ufeff') + and not self.config.get('enable-webhook', False) + and event.get('req_id') + ): + await self.bot.send_message(str(event.get('chatid') or event.get('userid') or ''), content) if is_final: if not self.config.get('enable-webhook', False) and event.get('req_id'): for item in self._iter_media_components(items): @@ -323,9 +385,25 @@ class WecomBotAdapter(WecomBotAPIMixin, abstract_platform_adapter.AbstractPlatfo async def is_stream_output_supported(self) -> bool: return self.config.get('enable-stream-reply', True) + async def begin_interaction_stream(self, source_message_id: str, target: dict) -> bool: + if self.config.get('enable-webhook', False): + return False + started = self.bot.begin_interaction_stream( + source_message_id, + str(target.get('target_type') or ''), + str(target.get('target_id') or ''), + ) + if not started: + await self.logger.warning('WeCom interaction stream context unavailable; buffering final reply') + return started + + async def reply_interaction_stream_chunk(self, *, source_message_id: str, content: str, is_final: bool) -> None: + from .stream_text import format_stream_text + + if not await self.bot.push_interaction_stream_chunk(source_message_id, format_stream_text(content), is_final): + raise RuntimeError('WeCom rejected the new interaction reply stream') + async def call_platform_api(self, action: str, params: dict = {}) -> dict: - if action == 'interaction.request' and 'interaction.request' in self.get_supported_apis(): - return await send_interaction(self, params) handler = PLATFORM_API_MAP.get(action) if handler is None: raise NotSupportedError(f'call_platform_api:{action}') diff --git a/src/langbot/pkg/platform/adapters/wecombot/interaction.py b/src/langbot/pkg/platform/adapters/wecombot/interaction.py index 46e46dd00..ec7f7ea6c 100644 --- a/src/langbot/pkg/platform/adapters/wecombot/interaction.py +++ b/src/langbot/pkg/platform/adapters/wecombot/interaction.py @@ -2,10 +2,12 @@ from __future__ import annotations +import json import time import typing import uuid +from langbot.libs.wecom_ai_bot_api.api import extract_template_card_action, extract_template_card_event_payload from langbot.libs.wecom_ai_bot_api.wecombotevent import WecomBotEvent from langbot_plugin.api.entities.builtin.platform import events as platform_events @@ -31,6 +33,7 @@ def build_interaction_card(request: dict[str, typing.Any], callback_token: str) fields = request.get('fields') if isinstance(request.get('fields'), list) else [] actions = request.get('actions') if isinstance(request.get('actions'), list) else [] buttons: list[dict[str, typing.Any]] = [] + select_field: dict[str, typing.Any] | None = None if actions and not fields: buttons = [ { @@ -46,18 +49,43 @@ def build_interaction_card(request: dict[str, typing.Any], callback_token: str) if field.get('type') != 'select': return None options = field.get('options') if isinstance(field.get('options'), list) else [] - buttons = [ - { - 'text': str(option.get('label') or option.get('value') or index + 1), - 'style': 0, - 'key': f'lbi:{callback_token}:f:0:{index}', - } - for index, option in enumerate(options[:6]) - if isinstance(option, dict) - ] - if not buttons: + if len(options) > 10: + raise ValueError('WeCom select cards support at most 10 options') + if options and all(isinstance(option, dict) for option in options): + select_field = field + if not buttons and select_field is None: return None description = str(request.get('description') or '').strip() + if select_field is not None: + options = select_field['options'] + selected_id = 'opt_1' + for index, option in enumerate(options): + if option.get('value') == select_field.get('default'): + selected_id = f'opt_{index + 1}' + break + return { + 'msgtype': 'template_card', + 'template_card': { + 'card_type': 'multiple_interaction', + 'main_title': {'title': str(request.get('title') or ''), 'desc': description}, + 'select_list': [ + { + 'question_key': 'f0', + 'title': str(select_field.get('label') or ''), + 'selected_id': selected_id, + 'option_list': [ + { + 'id': f'opt_{index + 1}', + 'text': str(option.get('label') or option.get('value') or '')[:10], + } + for index, option in enumerate(options) + ], + } + ], + 'submit_button': {'text': 'Submit', 'key': f'lbi:{callback_token}:s'}, + 'task_id': f'lbi-{uuid.uuid4().hex}', + }, + } if len(fields) == 1 and isinstance(fields[0], dict): label = str(fields[0].get('label') or '').strip() description = '\n\n'.join(part for part in (description, label) if part) @@ -78,7 +106,7 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - reply_target = params.get('reply_target') callback_token = str(params.get('callback_token') or '') if not isinstance(request, dict) or not isinstance(reply_target, dict) or not callback_token: - raise ValueError('interaction.request requires request, reply_target, and callback_token') + raise ValueError('send_interaction requires request, reply_target, and callback_token') target_type = str(reply_target.get('target_type') or '') target_id = str(reply_target.get('target_id') or '') card = build_interaction_card(request, callback_token) @@ -95,18 +123,69 @@ async def send_interaction(adapter: typing.Any, params: dict[str, typing.Any]) - result = await adapter.send_message(target_type, target_id, adapter._plain_message(fallback)) return {'ok': True, 'message_id': result.message_id, 'rich': False} raw = await adapter.bot.send_template_card(target_id, card) - return {'ok': True, 'message_id': None, 'rich': True, 'raw': raw} + if not isinstance(raw, dict) or raw.get('errcode', 0) != 0: + detail = raw.get('errmsg', raw.get('errcode')) if isinstance(raw, dict) else 'no acknowledgement' + raise RuntimeError(f'WeCom template card delivery failed: {detail}') + source_message_id = str(reply_target.get('message_id') or '') + if source_message_id and hasattr(adapter.bot, 'finish_stream_for_interaction'): + await adapter.bot.finish_stream_for_interaction(source_message_id) + return { + 'ok': True, + 'message_id': None, + 'rich': True, + 'task_id': card['template_card']['task_id'], + 'raw': raw, + } + + +async def acknowledge_interaction(adapter: typing.Any, params: dict[str, typing.Any]) -> dict[str, typing.Any]: + request = params.get('request') + submission = params.get('submission') + target = params.get('update_target') + callback = params.get('callback_context') + if not all(isinstance(value, dict) for value in (request, submission, target, callback)): + raise ValueError('update_interaction requires request, submission, update_target, and callback_context') + state = params.get('state', 'submitted') + task_id = str(callback.get('task_id') or target.get('task_id') or '') + req_id = str(callback.get('req_id') or '') + if not req_id or not task_id or task_id != target.get('task_id') or target.get('rich') is not True: + raise ValueError('WeCom interaction callback does not match the delivered card') + + card = build_interaction_card(request, state) + if card is None: + raise ValueError('WeCom interaction has no card to update') + updated = card['template_card'] + updated['task_id'] = task_id + action_id = submission.get('action_id') if state == 'submitted' else None + if updated['card_type'] == 'button_interaction': + for index, action in enumerate((request.get('actions') or [])[:6]): + updated['button_list'][index]['key'] = state + if isinstance(action, dict) and action.get('id') == action_id: + button = updated['button_list'][index] + button['text'] = f'✓ {button["text"]}' + button['replace_text'] = button['text'] + break + else: + field = request['fields'][0] + selected = (submission.get('values') or {}).get(field['id']) + for index, option in enumerate(field.get('options') or []): + if option.get('value') == selected: + updated['select_list'][0]['selected_id'] = f'opt_{index + 1}' + break + updated['select_list'][0]['disable'] = True + updated['submit_button']['text'] = {'submitted': 'Submitted', 'expired': 'Expired', 'cancelled': 'Cancelled'}[ + state + ] + updated['submit_button']['key'] = state + raw = await adapter.bot.update_template_card(req_id, updated) + if not isinstance(raw, dict) or raw.get('errcode', 0) != 0: + detail = raw.get('errmsg', raw.get('errcode')) if isinstance(raw, dict) else 'no acknowledgement' + raise RuntimeError(f'WeCom template card update failed: {detail}') + return {**target, 'updated': True, 'raw': raw} def _template_card_event(event: WecomBotEvent) -> dict[str, typing.Any]: - wrapper = event.get('event') or {} - if not isinstance(wrapper, dict): - return {} - for key in ('template_card_event', 'templateCardEvent', 'TemplateCardEvent'): - value = wrapper.get(key) - if isinstance(value, dict): - return value - return wrapper + return extract_template_card_event_payload(event) def _callback_key(payload: dict[str, typing.Any]) -> str: @@ -125,6 +204,8 @@ def _callback_key(payload: dict[str, typing.Any]) -> str: def parse_callback_key(value: str) -> dict[str, typing.Any]: parts = value.split(':') + if len(parts) == 3 and parts[0] == 'lbi' and parts[1] and parts[2] == 's': + return {'callback_token': parts[1], 'select_submit': True} if len(parts) == 4 and parts[0] == 'lbi' and parts[1] and parts[2] == 'a' and parts[3].isdigit(): return {'callback_token': parts[1], 'action_ref': int(parts[3])} if ( @@ -143,26 +224,78 @@ def parse_callback_key(value: str) -> dict[str, typing.Any]: raise ValueError('invalid WeCom interaction callback key') +def _selected_option_ref(payload: dict[str, typing.Any]) -> int: + selected_id: typing.Any = None + selected_items = payload.get('selected_items', payload.get('SelectedItems')) + if isinstance(selected_items, dict): + items = selected_items.get('selected_item', selected_items.get('SelectedItem')) + if isinstance(items, list): + for item in items: + if not isinstance(item, dict) or item.get('question_key', item.get('QuestionKey')) != 'f0': + continue + option_ids = item.get('option_ids', item.get('OptionIds')) + if isinstance(option_ids, dict): + option_ids = option_ids.get('option_id', option_ids.get('OptionId')) + if isinstance(option_ids, list) and len(option_ids) == 1: + selected_id = option_ids[0] + break + if selected_id is None and selected_items is None: + response: typing.Any = next( + (payload[key] for key in ('ResponseData', 'response_data', 'responseData') if key in payload), None + ) + if isinstance(response, str): + try: + response = json.loads(response) + except json.JSONDecodeError as exc: + raise ValueError('invalid WeCom select response data') from exc + if isinstance(response, dict): + selections = next( + (response[key] for key in ('select_list', 'SelectList', 'selectList') if key in response), None + ) + if isinstance(selections, list): + for item in selections: + if not isinstance(item, dict) or item.get('question_key', item.get('QuestionKey')) != 'f0': + continue + selected_id = next( + ( + item[key] + for key in ('option_id', 'OptionId', 'optionId', 'selected_id', 'SelectedId', 'selectedId') + if item.get(key) + ), + None, + ) + break + else: + selected_id = response.get('f0') + if not isinstance(selected_id, str) or not selected_id.startswith('opt_') or not selected_id[4:].isdigit(): + raise ValueError('WeCom select response has an invalid option') + option_number = int(selected_id[4:]) + if option_number < 1: + raise ValueError('WeCom select response has an invalid option') + return option_number - 1 + + def interaction_event_from_native( event: WecomBotEvent, -) -> platform_events.PlatformSpecificEvent | None: +) -> platform_events.InteractionCallbackEvent | None: callback_key = _callback_key(_template_card_event(event)) if not callback_key.startswith('lbi:'): return None parsed = parse_callback_key(callback_key) + task_id, _, _ = extract_template_card_action(_template_card_event(event)) + if parsed.pop('select_submit', False): + parsed['field_ref'] = 0 + parsed['option_ref'] = _selected_option_ref(_template_card_event(event)) target_type = 'group' if event.type == 'group' or event.chatid else 'person' target_id = str(event.chatid or event.userid or '') - return platform_events.PlatformSpecificEvent( - type='platform.specific', + return platform_events.InteractionCallbackEvent( adapter_name='wecombot-omni', - action='interaction.submitted', - data={ - **parsed, - 'actor_id': str(event.userid or ''), - 'target_type': target_type, - 'target_id': target_id, - 'display_text': 'submitted', - }, + callback_token=str(parsed.get('callback_token') or ''), + actor_id=str(event.userid or ''), + target_type=target_type, + target_id=target_id, + callback_context={'req_id': str(event.get('req_id') or ''), 'task_id': task_id}, + raw_submission=parsed, timestamp=time.time(), source_platform_object=event, ) diff --git a/src/langbot/pkg/platform/adapters/wecombot/manifest.yaml b/src/langbot/pkg/platform/adapters/wecombot/manifest.yaml index 5b3f18c5f..54101bcbd 100644 --- a/src/langbot/pkg/platform/adapters/wecombot/manifest.yaml +++ b/src/langbot/pkg/platform/adapters/wecombot/manifest.yaml @@ -200,6 +200,7 @@ spec: - wecombot.enter_chat - wecombot.template_card_event - platform.specific + - interaction.callback supported_apis: required: @@ -213,7 +214,9 @@ spec: - get_group_member_info - get_group_member_list - call_platform_api - - interaction.request + - send_interaction + - update_interaction + - get_interaction_capabilities platform_specific_apis: - action: is_websocket_mode diff --git a/src/langbot/pkg/platform/botmgr.py b/src/langbot/pkg/platform/botmgr.py index cd3e150fe..8800905f8 100644 --- a/src/langbot/pkg/platform/botmgr.py +++ b/src/langbot/pkg/platform/botmgr.py @@ -35,6 +35,8 @@ from ..agent.runner.host_models import ( from ..agent.runner.resource_policy import ResourcePolicyProjector from ..agent.runner.platform_tools import resolve_agent_platform_tool_names from ..agent.runner.query_entry_adapter import QueryEntryAdapter +from ..agent.runner.interaction_store import InteractionAlreadySubmittedError, InteractionExpiredError +from langbot_plugin.api.entities.builtin.runner.interaction import InteractionHandle from ..entity.persistence import workspace as persistence_workspace from ..api.http.context import ExecutionContext, PrincipalContext, PrincipalType, RequestContext @@ -853,7 +855,7 @@ class RuntimeBot: adapter: abstract_platform_adapter.AbstractMessagePlatformAdapter, supported_apis: list[str], ) -> dict[str, typing.Any] | None: - if 'interactions' not in DeliveryContext.model_fields or 'interaction.request' not in supported_apis: + if 'interactions' not in DeliveryContext.model_fields or 'send_interaction' not in supported_apis: return None get_capabilities = getattr(adapter, 'get_interaction_capabilities', None) if not callable(get_capabilities): @@ -897,8 +899,8 @@ class RuntimeBot: ), state_policy=StatePolicy(state_scopes=['conversation', 'actor', 'subject', 'runner']), delivery_policy=DeliveryPolicy( - enable_streaming=False, - enable_reply=False, + enable_streaming=agent.get('kind') == 'agent' and event_type == 'message.received', + enable_reply=agent.get('kind') == 'agent' and event_type == 'message.received', enable_interactions=agent.get('kind') != 'event_processor', ), agent_id=agent.get('uuid'), @@ -1034,7 +1036,7 @@ class RuntimeBot: primary_handler = ( self._handle_interaction_submission - if isinstance(event, platform_events.PlatformSpecificEvent) and event.action == 'interaction.submitted' + if isinstance(event, platform_events.InteractionCallbackEvent) else self._dispatch_eba_event_to_processor ) subscriptions = self._get_event_bindings_from_value(getattr(self.bot_entity, 'plugin_processors', [])) @@ -1139,6 +1141,28 @@ class RuntimeBot: ) -> dict[str, typing.Any]: event_type = getattr(event, 'type', None) or event.__class__.__name__ + if isinstance(event, platform_events.MessageReceivedEvent): + interaction_manager = getattr(getattr(self.ap, 'agent_run_orchestrator', None), 'interaction_manager', None) + else: + interaction_manager = None + if callable(getattr(interaction_manager, 'consume_text_message', None)): + target_type_for_text, target_id_for_text, _ = self._infer_reply_target(event) + sender_for_text = getattr(event, 'sender', None) or getattr(event, 'user', None) + actor_id_for_text = self._get_entity_id(sender_for_text) + text_for_interaction = ''.join( + part.text for part in event.message_chain if isinstance(part, platform_message.Plain) + ) + if target_type_for_text and target_id_for_text and actor_id_for_text and text_for_interaction: + consumed = await interaction_manager.consume_text_message( + workspace_id=self.execution_context.workspace_uuid, + bot_id=self.bot_entity.uuid, + conversation_id=f'{target_type_for_text}_{target_id_for_text}', + actor_id=str(actor_id_for_text), + text=text_for_interaction, + ) + if consumed: + return {'status': 'delivered', 'interaction': 'text_reply'} + if event_binding is None: event_binding = self._resolve_eba_event_binding(event, event_type) if event_binding is None: @@ -1290,6 +1314,8 @@ class RuntimeBot: ) envelope = self._eba_event_to_agent_envelope(event, adapter, execution_id) + if target_type == 'agent' and isinstance(event, platform_events.MessageReceivedEvent): + envelope.delivery.supports_streaming = True if target_type == 'event_processor': envelope.data = event.model_dump(mode='json', exclude={'source_platform_object', 'legacy_event'}) if isinstance(event, platform_events.MessageReceivedEvent): @@ -1300,6 +1326,17 @@ class RuntimeBot: try: with trace_mod.scope(route_ref=self._route_ref(event_binding, target_type, target_uuid)): + if target_type == 'agent' and await self.ap.agent_run_orchestrator.try_claim_steering_from_event( + envelope, binding, self.execution_context + ): + return await self._record_event_route_trace( + event_type=event_type, + status='delivered', + binding=event_binding, + target_type=target_type, + target_uuid=target_uuid, + text=f'Event {event_type} queued as steering', + ) from .processing_indicator import processing_indicator reply_type, reply_id = (None, None) @@ -1491,209 +1528,58 @@ class RuntimeBot: async def _handle_interaction_submission( self, - event: platform_events.PlatformSpecificEvent, + event: platform_events.InteractionCallbackEvent, adapter: abstract_platform_adapter.AbstractMessagePlatformAdapter, execution_id: str | None = None, ) -> None: - """Consume a platform interaction callback and resume its original processor.""" - data = event.data if isinstance(event.data, dict) else {} - callback_token = str(data.get('callback_token') or '') - actor_id = str(data.get('actor_id') or data.get('user_id') or '') or None - target_type = str(data.get('target_type') or '') or None - target_id = str(data.get('target_id') or data.get('chat_id') or '') or None + """Validate a callback and wake the Runner waiting in the original run.""" + del execution_id + manager = self.ap.agent_run_orchestrator.interaction_manager + target_type = event.target_type + target_id = event.target_id conversation_id = f'{target_type}_{target_id}' if target_type and target_id else None - submission = { - 'interaction_id': data.get('interaction_id'), - 'action_id': data.get('action_id'), - 'values': data.get('values') if isinstance(data.get('values'), dict) else {}, - 'submitted_at': int(event.timestamp) if event.timestamp else None, + submission: dict[str, typing.Any] = { + 'action_id': event.action_id, + 'values': event.values, } for ref_name in ('action_ref', 'field_ref', 'option_ref'): - if data.get(ref_name) is not None: - submission[ref_name] = data[ref_name] + value = event.raw_submission.get(ref_name) + if value is not None: + submission[ref_name] = value - record = await self.ap.agent_run_orchestrator.interaction_manager.consume_callback( - callback_token=callback_token, - submission=submission, - bot_id=self.bot_entity.uuid, - conversation_id=conversation_id, - actor_id=actor_id, - ) - if record['processor_type'] not in {'agent', 'pipeline'}: - raise ValueError(f'Unsupported interaction processor type: {record["processor_type"]}') - from ..telemetry import trace as trace_mod - - # Only a validated callback resolving an original processor is eligible. - # Admit before acknowledgement and target lookup to preserve failures. - trace_mod.admit() - await self.ap.agent_run_orchestrator.interaction_manager.acknowledge_submission(record, adapter) - - if record['processor_type'] == 'agent': - await self._resume_agent_interaction(record, event, adapter, actor_id, execution_id) + try: + record = await manager.consume_callback( + callback_token=event.callback_token, + submission=submission, + bot_id=self.bot_entity.uuid, + conversation_id=conversation_id, + actor_id=event.actor_id, + ) + except InteractionAlreadySubmittedError: + return + except InteractionExpiredError: + stale = await manager.store.get_by_callback_token(event.callback_token) + delivery_result = stale.get('delivery_result') if stale else None + if isinstance(delivery_result, dict) and callable(getattr(adapter, 'update_interaction', None)): + try: + handle = InteractionHandle.model_validate(delivery_result) + handle.context.setdefault('request', stale.get('request') or {}) + handle.context['callback_context'] = event.callback_context + await adapter.update_interaction(handle, 'expired') + except Exception as exc: + await self.logger.warning(f'Failed to invalidate stale interaction card: {exc}') return - pipeline = await self.ap.pipeline_service.get_pipeline( - self.execution_context, - record['processor_id'], - include_secret=True, - ) - if not pipeline: - raise ValueError(f'Interaction target Pipeline is unavailable: {record["processor_id"]}') - current_runner_id = RunnerConfigResolver.resolve_runner_id(pipeline.get('config') or {}) - if current_runner_id != record['runner_id']: - raise ValueError('Interaction target Pipeline runner changed after the request was created') - - message_components: list[platform_message.MessageComponent] = [] - callback_message_id = data.get('message_id') - if callback_message_id: - message_components.append( - platform_message.Source( - id=str(callback_message_id), - time=int(event.timestamp) if event.timestamp else int(time.time()), - ) - ) - message_components.append( - platform_message.Plain(text=str(data.get('display_text') or data.get('action_id') or 'submitted')) - ) - message_chain = platform_message.MessageChain(message_components) - delivery_target = record.get('delivery_target') or {} - original_target_type = delivery_target.get('target_type') - original_target_id = delivery_target.get('target_id') - if original_target_type == 'group': - group = platform_entities.Group( - id=original_target_id, - name='', - permission=platform_entities.Permission.Member, - ) - message_event: platform_events.MessageEvent = platform_events.GroupMessage( - sender=platform_entities.GroupMember( - id=actor_id or '', - member_name='', - permission=platform_entities.Permission.Member, - group=group, - ), - message_chain=message_chain, - time=event.timestamp, - source_platform_object=event.source_platform_object, - ) - else: - message_event = platform_events.FriendMessage( - sender=platform_entities.Friend(id=actor_id or '', nickname='', remark=''), - message_chain=message_chain, - time=event.timestamp, - source_platform_object=event.source_platform_object, - ) - - launcher_type = ( - provider_session.LauncherTypes.GROUP - if original_target_type == 'group' - else provider_session.LauncherTypes.PERSON - ) - await self.ap.msg_aggregator.add_message( - bot_uuid=self.bot_entity.uuid, - launcher_type=launcher_type, - launcher_id=original_target_id or target_id or actor_id or '', - sender_id=actor_id or '', - message_event=message_event, - message_chain=message_chain, - adapter=adapter, - pipeline_uuid=record['processor_id'], - routed_by_rule=True, - variables={'_interaction_submission': record['submission']}, - execution_context=self.execution_context, - ) - - async def _resume_agent_interaction( - self, - record: dict[str, typing.Any], - event: platform_events.PlatformSpecificEvent, - adapter: abstract_platform_adapter.AbstractMessagePlatformAdapter, - actor_id: str | None, - execution_id: str | None = None, - ) -> None: - """Resume the exact independent Agent that produced an interaction.""" - agent = await self.ap.agent_service.get_agent( - self.execution_context, - record['processor_id'], - ) - if not agent or agent.get('kind') != 'agent': - raise ValueError(f'Interaction target Agent is unavailable: {record["processor_id"]}') - - binding = self._agent_product_to_binding( - agent, - {'id': record['binding_id']}, - 'interaction.submitted', - self.bot_entity.uuid, - ) - if binding is None or binding.runner_id != record['runner_id']: - raise ValueError('Interaction target Agent runner changed after the request was created') - binding.binding_id = record['binding_id'] - - submission = record['submission'] - display_text = str( - (submission or {}).get('action_id') - or (event.data if isinstance(event.data, dict) else {}).get('display_text') - or 'submitted' - ) - input_data: dict[str, typing.Any] = { - 'text': display_text, - 'contents': [{'type': 'text', 'text': display_text}], - 'attachments': [], - } - if 'interaction' in AgentInput.model_fields: - input_data['interaction'] = submission - - delivery_target = record.get('delivery_target') or {} - supported_apis = self._get_adapter_supported_apis(adapter) - delivery_data: dict[str, typing.Any] = { - 'surface': 'platform', - 'reply_target': delivery_target, - 'supports_streaming': False, - 'supports_edit': 'edit_message' in supported_apis, - 'supports_reaction': bool({'add_reaction', 'remove_reaction'} & set(supported_apis)), - 'platform_capabilities': { - 'adapter': adapter.__class__.__name__, - 'event_type': 'interaction.submitted', - 'supported_apis': supported_apis, - }, - } - interaction_capabilities = self._get_adapter_interaction_capabilities(adapter, supported_apis) - if interaction_capabilities is not None: - delivery_data['interactions'] = interaction_capabilities - - envelope = AgentEventEnvelope( - event_id=execution_id or f'interaction:{record["id"]}:{uuid.uuid4()}', - event_type='interaction.submitted', - event_time=int(event.timestamp) if event.timestamp else int(time.time()), - source='platform', - source_event_type='interaction.submitted', - bot_id=self.bot_entity.uuid, - workspace_id=record.get('workspace_id'), - conversation_id=record.get('conversation_id'), - thread_id=record.get('thread_id'), - actor=ActorContext(actor_type='user', actor_id=actor_id), - subject=SubjectContext( - subject_type='interaction', - subject_id=record['interaction_id'], - data={'action_id': (submission or {}).get('action_id')}, - ), - input=AgentInput.model_validate(input_data), - delivery=DeliveryContext.model_validate(delivery_data), - raw_ref=RawEventRef(ref_id=f'interaction:{record["id"]}', storage_key=None), - data={'interaction': submission}, - ) - - async for _ in self.ap.agent_run_orchestrator.run( - envelope, - binding, - adapter_context={ - '_delivery_adapter': adapter, - '_platform_event': event, - '_execution_context': self.execution_context, - }, - ): - # Resuming an interaction follows the same explicit-action delivery policy. - pass + if not manager.wake_waiter(record, event.actor_id, event.callback_context): + delivery_result = record.get('delivery_result') + if isinstance(delivery_result, dict) and callable(getattr(adapter, 'update_interaction', None)): + try: + handle = InteractionHandle.model_validate(delivery_result) + handle.context.setdefault('request', record.get('request') or {}) + handle.context['callback_context'] = event.callback_context + await adapter.update_interaction(handle, 'cancelled') + except Exception as exc: + await self.logger.warning(f'Failed to invalidate orphaned interaction card: {exc}') async def _dispatch_eba_message_to_pipeline( self, diff --git a/src/langbot/pkg/platform/sources/dingtalk.py b/src/langbot/pkg/platform/sources/dingtalk.py index 7e3efcbcd..dcbb7608a 100644 --- a/src/langbot/pkg/platform/sources/dingtalk.py +++ b/src/langbot/pkg/platform/sources/dingtalk.py @@ -1,7 +1,11 @@ -from langbot.libs.dingtalk_api.thinking import visible_think_markers +from langbot.libs.dingtalk_api.a2ui import ( + brand_components, + binding, + create_surface_messages, + create_text_card_messages, + update_surface_messages, +) import asyncio -import json -import pathlib import re import traceback import typing @@ -317,17 +321,6 @@ def _dingtalk_missing_completed_input_lines(form_data: dict, form_content: str) return [line for line in _dingtalk_completed_input_lines(form_data) if line.strip() not in rendered_lines] -def _dingtalk_supports_native_field(form_data: dict) -> bool: - current_name = str(form_data.get('_current_input_field') or '').strip() - if not current_name or form_data.get('_action_select_only'): - return False - for field in _dingtalk_form_input_defs(form_data): - if str(field.get('output_variable_name') or '').strip() != current_name: - continue - return str(field.get('type') or 'text').strip().lower() not in {'file', 'file-list'} - return False - - def _dingtalk_field_name(field: dict) -> str: return str(field.get('output_variable_name') or field.get('name') or field.get('id') or '').strip() @@ -355,28 +348,6 @@ def _dingtalk_select_options(field: dict) -> list[str]: return [] -def _dingtalk_select_block_options(options: list[str]) -> list[dict]: - """Build the option shape consumed by DingTalk SelectBlock templates.""" - locales = ( - 'zh_CN', - 'zh_TW', - 'en_US', - 'ja_JP', - 'vi_VN', - 'th_TH', - 'id_ID', - 'ne_NP', - 'ms_MY', - 'ko_KR', - 'ru_RU', - 'es_EA', - 'tr_TR', - 'fr_FR', - 'pt_BR', - ) - return [{'value': option, 'text': {locale: option for locale in locales}} for option in options] - - def _dingtalk_current_input_field(form_data: dict) -> dict | None: current_name = str(form_data.get('_current_input_field') or '').strip() if not current_name or form_data.get('_action_select_only'): @@ -387,62 +358,8 @@ def _dingtalk_current_input_field(form_data: dict) -> dict | None: return None -def _dingtalk_form_component_params(form_data: dict) -> dict: - field = _dingtalk_current_input_field(form_data) - params = { - 'input_visible': '', - 'input_title': '', - 'input_placeholder': '', - 'input_value': '', - 'select_visible': '', - 'select_placeholder': '', - 'select_options': [], - 'index_o': [], - 'test_index': [], - 'select_index': -1, - } - if not field: - return params - - field_name = _dingtalk_field_name(field) - field_type = _dingtalk_field_type(field) - value = form_data.get('inputs', {}).get(field_name, '') - if field_type == 'select': - options = _dingtalk_select_options(field) - selected_index = -1 - if value not in (None, ''): - try: - selected_index = options.index(str(value)) - except ValueError: - selected_index = -1 - params.update( - { - 'select_visible': 'true', - 'select_placeholder': field_name or 'Select', - 'select_options': options, - 'index_o': _dingtalk_select_block_options(options), - 'test_index': _dingtalk_select_block_options(options), - 'select_index': selected_index, - } - ) - elif field_type not in {'file', 'file-list'}: - params.update( - { - 'input_visible': 'true', - 'input_title': field_name or 'Input', - 'input_placeholder': field_name or 'Input', - 'input_value': '' if value is None else str(value), - } - ) - return params - - -def _dingtalk_empty_form_component_params() -> dict: - return _dingtalk_form_component_params({}) - - def _dingtalk_extract_component_inputs(params: dict) -> dict: - """Normalize DingTalk native Input/SelectBlock callback payloads.""" + """Normalize legacy template and A2UI input callback payloads.""" if not isinstance(params, dict): return {} @@ -468,6 +385,8 @@ def _dingtalk_extract_component_inputs(params: dict) -> dict: break if isinstance(select_value, dict): select_value = select_value.get('value') or select_value.get('label') or select_value.get('index') + if isinstance(select_value, list): + select_value = select_value[0] if select_value else '' if select_value not in (None, ''): if isinstance(select_value, str): select_value = select_value.strip() @@ -476,6 +395,136 @@ def _dingtalk_extract_component_inputs(params: dict) -> dict: return result +def _dingtalk_a2ui_form( + form_data: dict, + out_track_id: str, + *, + prior_content: str = '', +) -> tuple[dict, list[dict]]: + node_title = str(form_data.get('node_title') or 'Human Input Required') + form_content = _dingtalk_clean_form_content(form_data) + content_parts = [part for part in (prior_content.strip(), f'## {node_title}', form_content) if part] + data: dict[str, typing.Any] = {'content': '\n\n'.join(content_parts), 'form': {}} + components: list[dict] = [ + {'id': 'root', 'component': 'Column', 'children': ['content'], 'gap': 12}, + {'id': 'content', 'component': 'Markdown', 'content': binding('/content')}, + ] + children = components[0]['children'] + + field = _dingtalk_current_input_field(form_data) + if field is not None: + field_name = _dingtalk_field_name(field) or 'value' + field_type = _dingtalk_field_type(field) + default = (form_data.get('inputs') or {}).get(field_name, field.get('default')) + label = str(field.get('label') or field_name) + placeholder = str(field.get('placeholder') or '') + if field_type == 'select': + options = [{'label': option, 'value': option} for option in _dingtalk_select_options(field)] + data['form']['value'] = [] if default in (None, '') else [str(default)] + components.append( + { + 'id': 'field', + 'component': 'ChoicePicker', + 'label': placeholder or label, + 'variant': 'mutuallyExclusive', + 'displayStyle': 'dropdown', + 'options': options, + 'value': binding('/form/value'), + } + ) + value_key = 'select' + elif field_type == 'number': + data['form']['value'] = default if isinstance(default, (int, float)) else 0 + components.append( + { + 'id': 'field', + 'component': 'NumberInput', + 'label': label, + 'placeholder': placeholder, + 'value': binding('/form/value'), + } + ) + value_key = 'input' + else: + data['form']['value'] = '' if default is None else str(default) + components.append( + { + 'id': 'field', + 'component': 'TextField', + 'label': label, + 'placeholder': placeholder, + 'variant': 'longText' if field_type == 'textarea' else 'shortText', + 'value': binding('/form/value'), + } + ) + value_key = 'input' + components.extend( + [ + { + 'id': 'submit-input', + 'component': 'Button', + 'child': 'submit-input-label', + 'variant': 'primary', + 'action': { + 'event': { + 'name': 'langbot_form_input', + 'context': { + 'actionId': '__langbot_input__', + 'out_track_id': out_track_id, + value_key: binding('/form/value'), + }, + } + }, + 'checks': [ + { + 'condition': { + 'call': 'required', + 'args': {'value': binding('/form/value')}, + }, + 'message': f'{label} is required', + } + ], + }, + {'id': 'submit-input-label', 'component': 'Text', 'text': 'Submit'}, + ] + ) + children.extend(['field', 'submit-input']) + else: + for index, action in enumerate(form_data.get('actions') or []): + action_id = str(action.get('id') or '') + label_id = f'action-label-{index}' + button_id = f'action-{index}' + style = str(action.get('button_style') or '') + components.extend( + [ + { + 'id': button_id, + 'component': 'Button', + 'child': label_id, + 'variant': 'primary' if style == 'primary' or (not style and index == 0) else 'default', + 'action': { + 'event': { + 'name': 'langbot_form_action', + 'context': { + 'actionId': action_id, + 'out_track_id': out_track_id, + }, + } + }, + }, + { + 'id': label_id, + 'component': 'Text', + 'text': str(action.get('title') or action_id or f'Option {index + 1}'), + }, + ] + ) + children.append(button_id) + children.append('langbot-brand') + components.extend(brand_components()) + return data, components + + class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): bot: DingTalkClient bot_account_id: str @@ -508,17 +557,6 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): ] ap: typing.Any = None bot_uuid: str = '' - # DingTalk media_id (`@xxx` format) for the bot avatar image, fetched - # on adapter startup by uploading the bundled LangBot logo via the - # legacy /media/upload endpoint. Empty string when the upload hasn't - # run yet or failed — the template's Avatar then falls back to its - # default (initials of `name`). - bot_avatar_media_id: str = '' - - # Path to the LangBot logo bundled in the repo (`res/logo-blue.png`), - # resolved relative to this file. Updated to find the file even when - # LangBot is installed as a package or run from a different cwd. - _LOGO_PATH: typing.ClassVar[pathlib.Path] = pathlib.Path(__file__).resolve().parents[5] / 'res' / 'logo-blue.png' def __init__(self, config: dict, logger: EventLogger): required_keys = [ @@ -637,12 +675,10 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): message_id = bot_message.resp_message_id msg_seq = bot_message.msg_sequence - form_template_id = (self.config.get('human_input_card_template_id') or '').strip() form_data = getattr(bot_message, '_form_data', None) if is_final and self.ap is not None: self.ap.logger.info( - f'DingTalk reply_message_chunk final: form_data_present={form_data is not None}, ' - f'form_template_configured={bool(form_template_id)}' + f'DingTalk reply_message_chunk final: form_data_present={form_data is not None}, a2ui_enabled=True' ) if form_data and is_final: @@ -680,51 +716,16 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): return card_instance, card_instance_id = chat_card_entry - # btns is reserved exclusively for Dify form-action buttons. - # The template renders an Avatar header above the markdown - # content; no feedback buttons get injected here. if content: - if form_template_id: - # The card content has already been written via - # update_card_data (in _paint_form_on_card and the - # initial card creation). The streaming endpoint - # (PUT /v1.0/card/streaming) does not propagate - # updates on cards whose content was last set via - # update_card_data — they take different code paths - # on the DingTalk client. Stick with update_card_data - # for the whole turn for consistency. - try: - await self.bot.update_card_data( - out_track_id=card_instance_id, - card_param_map=self._card_params( - content=content, - btns='[]', - flowStatus='3' if is_final else '1', - **_dingtalk_empty_form_component_params(), - ), - ) - session_key = self._session_key_from_event(message_source) - if session_key: - self.active_turn_text[session_key] = content - except Exception: - if self.ap is not None: - self.ap.logger.exception('DingTalk: update card content failed') - else: - await self.bot.send_card_message(card_instance, card_instance_id, content, is_final) + await self.bot.send_card_message(card_instance, card_instance_id, content, is_final) + session_key = self._session_key_from_event(message_source) + if session_key: + self.active_turn_text[session_key] = content if is_final: - if form_template_id and not content: - # Empty final chunk still needs to leave the card with - # flowStatus=3 so the spinner stops. - try: - await self.bot.update_card_data( - out_track_id=card_instance_id, - card_param_map=self._card_params( - flowStatus='3', - **_dingtalk_empty_form_component_params(), - ), - ) - except Exception: - pass + if not content: + session_key = self._session_key_from_event(message_source) + final_content = self.active_turn_text.get(session_key, '') if session_key else '' + await self.bot.send_card_message(card_instance, card_instance_id, final_content, True) if bot_message.tool_calls is None: self.card_instance_id_dict.pop(message_id, None) event = await DingTalkEventConverter.yiri2target(message_source) @@ -745,63 +746,24 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): async def create_message_card(self, message_id, event): self._prune_card_state() - form_template_id = (self.config.get('human_input_card_template_id') or '').strip() - legacy_template_id = (self.config.get('card_template_id') or '').strip() # Synthetic events (button clicks): look up the card already in # active_turn_card so reply_message_chunk can stream to it. if event is None or event.source_platform_object is None: - if form_template_id: - session_key = self._session_key_from_event(event) if event is not None else '' - carry = self.active_turn_card.get(session_key, '') if session_key else '' - if carry: - self.card_instance_id_dict[message_id] = (None, carry) - return True + session_key = self._session_key_from_event(event) if event is not None else '' + carry = self.active_turn_card.get(session_key, '') if session_key else '' + if carry: + self.card_instance_id_dict[message_id] = ({'surface_id': f'langbot-{carry}'}, carry) + return True return False - if form_template_id: - # Create one card with the form template, empty buttons, - # pending state. Streaming writes content to it; form pause - # paints buttons onto it. One card per turn, no duplication. - incoming_message = event.source_platform_object.incoming_message - out_track_id = uuid.uuid4().hex - is_group = str(incoming_message.conversation_type) == '2' - if is_group: - open_space_id = f'dtv1.card//IM_GROUP.{incoming_message.conversation_id}' - else: - open_space_id = f'dtv1.card//IM_ROBOT.{incoming_message.sender_staff_id}' - try: - await self.bot.create_and_deliver_card( - card_template_id=form_template_id, - out_track_id=out_track_id, - open_space_id=open_space_id, - is_group=is_group, - card_param_map=self._card_params( - content='', - btns='[]', - flowStatus='1', - **_dingtalk_empty_form_component_params(), - ), - callback_type='STREAM', - ) - except Exception: - if self.ap is not None: - self.ap.logger.exception('DingTalk: create form-template card failed') - return False - self.card_instance_id_dict[message_id] = (None, out_track_id) - session_key = self._session_key_from_event(event) - if session_key: - self.active_turn_card[session_key] = out_track_id - self.active_turn_text[session_key] = '' - return True - - # Legacy chat-card path (no form template). incoming_message = event.source_platform_object.incoming_message - card_auto_layout = self.config.get('card_auto_layout', True) - card_instance, card_instance_id = await self.bot.create_and_card( - legacy_template_id, incoming_message, card_auto_layout=card_auto_layout - ) + card_instance, card_instance_id = await self.bot.create_and_card(incoming_message) self.card_instance_id_dict[message_id] = (card_instance, card_instance_id) + session_key = self._session_key_from_event(event) + if session_key: + self.active_turn_card[session_key] = card_instance_id + self.active_turn_text[session_key] = '' return True def _session_key_from_event(self, event) -> str: @@ -847,38 +809,8 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): self.bot.on_message('GroupMessage')(on_message) async def run_async(self): - # Upload the bundled LangBot logo so the card Avatar can render - # via DingTalk's media CDN — external URLs (e.g. raw.githubusercontent) - # are blocked by DingTalk's Avatar.imageUrl resolver. Non-fatal if - # the upload fails: cards still render without an avatar image. - if self._LOGO_PATH.exists(): - media_id = await self.bot.upload_image_media(str(self._LOGO_PATH)) - if media_id: - self.bot_avatar_media_id = media_id - if self.ap is not None: - self.ap.logger.info(f'DingTalk bot avatar uploaded: media_id={media_id}') - else: - if self.ap is not None: - self.ap.logger.warning('DingTalk bot avatar upload failed; card will use default') - else: - if self.ap is not None: - self.ap.logger.warning(f'DingTalk bot avatar source not found: {self._LOGO_PATH}') await self.bot.start() - def _card_params(self, **extra) -> dict: - """Build a cardParamMap dict that always carries `bot_avatar` - (when uploaded) alongside whatever caller-specific params. The - bot_avatar key gets dropped on every update_card_data call — - DingTalk wipes unspecified template variables, so re-sending it - on each update is mandatory.""" - params = {} - if self.bot_avatar_media_id: - params['bot_avatar'] = self.bot_avatar_media_id - params.update(extra) - if isinstance(params.get('content'), str): - params['content'] = visible_think_markers(params['content']) - return params - async def kill(self) -> bool: task_set = getattr(self, '_background_tasks', set()) background_tasks = list(task_set) @@ -924,8 +856,8 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): def _derive_open_space(self, message_source: platform_events.MessageEvent) -> tuple[str, bool]: """Return (openSpaceId, is_group) for the given inbound event.""" if isinstance(message_source, platform_events.GroupMessage): - return f'dtv1.card//IM_GROUP.{message_source.group.id}', True - return f'dtv1.card//IM_ROBOT.{message_source.sender.id}', False + return f'dtv1.card//im_group.{message_source.group.id}', True + return f'dtv1.card//im_robot.{message_source.sender.id}', False def _derive_session_descriptor( self, message_source: platform_events.MessageEvent @@ -950,53 +882,23 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): message: platform_message.MessageChain, form_data: dict, ) -> None: - """Surface human-input prompt + buttons on the active card. - - In single-card mode (form_template_id configured): update the - EXISTING card with form buttons so it transitions from streaming - output to prompt+buttons on the same card. In legacy mode: - finalize the chat card and deliver a separate form card. - """ + """Surface a human-input prompt on the active A2UI card.""" if self.ap is not None: self.ap.logger.info( f'DingTalk _handle_form_chunk: actions={len(form_data.get("actions") or [])}, ' f'node_title={form_data.get("node_title", "")!r}' ) message_id = bot_message.resp_message_id - template_id = (self.config.get('human_input_card_template_id') or '').strip() - - if template_id: - # Single-card mode: paint prompt + buttons onto the existing card. - session_key = self._session_key_from_event(message_source) - entry = self.card_instance_id_dict.get(message_id) - out_track_id = entry[1] if entry else None - if not out_track_id and session_key: - out_track_id = self.active_turn_card.get(session_key, '') - if out_track_id: - await self._paint_form_on_card(message_source, out_track_id, form_data, session_key) - self.card_instance_id_dict.pop(message_id, None) - return - - # No existing card (e.g. Dify paused immediately with no LLM - # output before the pause). Create a form card directly. - await self._send_form_card(message_source, form_data, template_id) - self.card_instance_id_dict.pop(message_id, None) - return - - # Legacy mode: finalize the streaming card with text fallback. - chat_card_entry = self.card_instance_id_dict.pop(message_id, None) - if chat_card_entry is not None: - _, chat_out_track_id = chat_card_entry - markdown_enabled = self.config.get('markdown_card', False) - text_content, _ = await DingTalkMessageConverter.yiri2target(message, markdown_enabled) - if not text_content and bot_message.content: - text_content = bot_message.content - try: - await self.bot.send_card_message(None, chat_out_track_id, text_content or '​', True) - except Exception: - await self.logger.error(f'DingTalk: finalize chat card before form failed: {traceback.format_exc()}') - - await self.send_message_text_form(message_source, form_data) + session_key = self._session_key_from_event(message_source) + entry = self.card_instance_id_dict.get(message_id) + out_track_id = entry[1] if entry else None + if not out_track_id and session_key: + out_track_id = self.active_turn_card.get(session_key, '') + if out_track_id: + await self._paint_form_on_card(message_source, out_track_id, form_data, session_key) + else: + await self._send_form_card(message_source, form_data) + self.card_instance_id_dict.pop(message_id, None) async def _paint_form_on_card( self, @@ -1010,13 +912,6 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): node_title = form_data.get('node_title', '') or 'Human Input Required' form_content = _dingtalk_clean_form_content(form_data) should_show_actions = not _dingtalk_pending_input_defs(form_data) - component_params = _dingtalk_form_component_params(form_data) - native_field = _dingtalk_supports_native_field(form_data) - if self.ap is not None and component_params.get('select_visible'): - self.ap.logger.info( - f'DingTalk form select params: field={form_data.get("_current_input_field", "")!r} ' - f'options={len(component_params.get("select_options") or [])}' - ) # Record form state for the click-handler. self._prune_card_state() @@ -1039,37 +934,18 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): 'created_at': time.monotonic(), } - btns = self._build_btns(actions if should_show_actions else [], out_track_id) - parts: list[str] = [] prior = self.active_turn_text.get(session_key, '') if session_key else '' - if prior.strip(): - parts.append(prior.rstrip()) - parts.append('
') - # DingTalk's card markdown widget strips `\n\n` paragraph breaks in - # template content slots, fusing inline siblings into a single line. - # Force visual line breaks with explicit HTML `
` tags so the - # title sits on its own line above form_content. - if node_title: - parts.append(f'**{node_title}**') - if form_content: - parts.append(_dingtalk_card_markdown(form_content)) - missing_completed_lines = _dingtalk_missing_completed_input_lines(form_data, form_content) - if missing_completed_lines: - parts.append('
' + '
'.join(missing_completed_lines)) - input_hint_lines = [] if native_field else _dingtalk_input_hint_lines(form_data) - if input_hint_lines: - parts.append('Fill these fields in chat before choosing an action:
' + '
'.join(input_hint_lines)) - display_content = '

'.join(parts) + data, components = _dingtalk_a2ui_form(form_data, out_track_id, prior_content=prior) try: - await self.bot.update_card_data( + await self.bot.update_ai_card( out_track_id=out_track_id, - card_param_map=self._card_params( - content=display_content, - btns=json.dumps(btns, ensure_ascii=False), - flowStatus='3', - **component_params, + a2ui_messages=update_surface_messages( + f'langbot-{out_track_id}', + data=data, + components=components, ), + flow_status='CONFIRMING', ) except Exception: if self.ap is not None: @@ -1077,40 +953,10 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): await self.send_message_text_form(message_source, form_data) return - @staticmethod - def _build_btns(actions: list, out_track_id: str) -> list: - btns = [] - for idx, action in enumerate(actions): - action_id = str(action.get('id') or '') - title = str(action.get('title') or action_id or f'选项 {idx + 1}') - style = (action.get('button_style') or '').lower() - if style == 'primary' or (style == '' and idx == 0): - color = 'blue' - elif style == 'danger': - color = 'red' - else: - color = 'gray' - btns.append( - { - 'text': title, - 'color': color, - 'status': 'normal', - 'event': { - 'type': 'sendCardRequest', - 'params': { - 'actionId': action_id, - 'params': {'action_id': action_id, 'out_track_id': out_track_id}, - }, - }, - } - ) - return btns - async def _send_form_card( self, message_source: platform_events.MessageEvent, form_data: dict, - template_id: str, ) -> None: """Deliver a new card pre-loaded with the human-input prompt + buttons.""" out_track_id = uuid.uuid4().hex @@ -1122,13 +968,6 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): node_title = form_data.get('node_title', '') or 'Human Input Required' form_content = _dingtalk_clean_form_content(form_data) should_show_actions = not _dingtalk_pending_input_defs(form_data) - component_params = _dingtalk_form_component_params(form_data) - native_field = _dingtalk_supports_native_field(form_data) - if self.ap is not None and component_params.get('select_visible'): - self.ap.logger.info( - f'DingTalk form select params: field={form_data.get("_current_input_field", "")!r} ' - f'options={len(component_params.get("select_options") or [])}' - ) self._prune_card_state() self.card_state[out_track_id] = { @@ -1151,38 +990,25 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): 'created_at': time.monotonic(), } - parts = [] - if node_title: - parts.append(f'**{node_title}**') - if form_content: - parts.append(_dingtalk_card_markdown(form_content)) - missing_completed_lines = _dingtalk_missing_completed_input_lines(form_data, form_content) - if missing_completed_lines: - parts.append('
' + '
'.join(missing_completed_lines)) - input_hint_lines = [] if native_field else _dingtalk_input_hint_lines(form_data) - if input_hint_lines: - parts.append('Fill these fields in chat before choosing an action:
' + '
'.join(input_hint_lines)) - display_content = '

'.join(parts) - - btns = self._build_btns(actions if should_show_actions else [], out_track_id) + data, components = _dingtalk_a2ui_form(form_data, out_track_id) try: if self.ap is not None: self.ap.logger.info( - f'DingTalk _send_form_card: out_track_id={out_track_id} template_id={template_id} ' - f'open_space_id={open_space_id} is_group={is_group} btns={len(btns)}' + f'DingTalk _send_form_card: out_track_id={out_track_id} ' + f'open_space_id={open_space_id} is_group={is_group} actions={len(actions)}' ) - await self.bot.create_and_deliver_card( - card_template_id=template_id, + await self.bot.create_and_deliver_ai_card( out_track_id=out_track_id, open_space_id=open_space_id, is_group=is_group, - card_param_map=self._card_params( - content=display_content, - btns=json.dumps(btns, ensure_ascii=False), - flowStatus='3', - **component_params, + a2ui_messages=create_surface_messages( + f'langbot-{out_track_id}', + data=data, + components=components, ), + flow_status='CONFIRMING', + summary=node_title, callback_type='STREAM', ) except Exception: @@ -1201,43 +1027,24 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): card stays put with the selection notice, and a fresh card is spawned here for the LLM reply to stream into. """ - form_template_id = (self.config.get('human_input_card_template_id') or '').strip() - legacy_template_id = (self.config.get('card_template_id') or '').strip() - template_id = form_template_id or legacy_template_id - if not template_id: - return None out_track_id = uuid.uuid4().hex open_space_id, is_group = self._derive_open_space(message_source) - if form_template_id: - card_param_map = self._card_params( - content='', - btns='[]', - flowStatus='1', - **_dingtalk_empty_form_component_params(), - ) - card_data_config = None - else: - # Legacy chat-card template doesn't carry a `bot_avatar` - # variable, so don't decorate the param map here. - card_param_map = {'content': '', 'query': '...'} - card_data_config = {'autoLayout': self.config.get('card_auto_layout', True)} + surface_id = f'langbot-{out_track_id}' try: - success = await self.bot.create_and_deliver_card( - card_template_id=template_id, + await self.bot.create_and_deliver_ai_card( out_track_id=out_track_id, open_space_id=open_space_id, is_group=is_group, - card_param_map=card_param_map, - card_data_config=card_data_config, + a2ui_messages=create_text_card_messages(surface_id), + flow_status='PROCESSING', + summary='LangBot is replying', callback_type='STREAM', ) except Exception: if self.ap is not None: self.ap.logger.exception('DingTalk: lazy create resume chat card failed') return None - if not success: - return None - entry = (None, out_track_id) + entry = ({'surface_id': surface_id}, out_track_id) self.card_instance_id_dict[message_id] = entry # Register as the active card so any further chunks on this turn # (and a subsequent re-pause) land on the same new card. @@ -1609,14 +1416,17 @@ class DingTalkAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter): if self.ap is not None: self.ap.logger.info(f'DingTalk _mark_card_resolved: out_track_id={out_track_id} action={action_title!r}') try: - await self.bot.update_card_data( + await self.bot.update_ai_card( out_track_id=out_track_id, - card_param_map=self._card_params( - content=content, - btns='[]', - flowStatus='3', - **_dingtalk_empty_form_component_params(), + a2ui_messages=update_surface_messages( + f'langbot-{out_track_id}', + data={'content': content}, + components=[ + {'id': 'root', 'component': 'Column', 'children': ['content'], 'gap': 8}, + {'id': 'content', 'component': 'Markdown', 'content': binding('/content')}, + ], ), + flow_status='CONFIRMED', ) except Exception: if self.ap is not None: diff --git a/src/langbot/pkg/platform/sources/dingtalk.yaml b/src/langbot/pkg/platform/sources/dingtalk.yaml index 43392cf0b..a9ef513b8 100644 --- a/src/langbot/pkg/platform/sources/dingtalk.yaml +++ b/src/langbot/pkg/platform/sources/dingtalk.yaml @@ -55,97 +55,12 @@ spec: zh_Hans: 使用卡片回复 zh_Hant: 使用卡片回覆 description: - en_US: Controls Markdown and streaming card replies. Disable to use plain text while keeping your template settings. When enabled, a configured template automatically enables streaming. - zh_Hans: 控制 Markdown 和流式卡片回复。关闭后使用纯文本,保留模板配置;开启且已配置模板时自动使用流式回复。 - zh_Hant: 控制 Markdown 和串流卡片回覆。關閉後使用純文字,保留範本設定;開啟且已設定範本時自動使用串流回覆。 + en_US: Uses built-in A2UI cards for Markdown, streaming replies, and interactions. No card template is required. The app must have AICard.Instance.Write permission. + zh_Hans: 使用内置 A2UI 卡片提供 Markdown、流式回复和交互能力,无需配置卡片模板。应用必须开通 AICard.Instance.Write 权限。 + zh_Hant: 使用內建 A2UI 卡片提供 Markdown、串流回覆和互動能力,無需設定卡片範本。應用必須開通 AICard.Instance.Write 權限。 type: boolean required: false default: true - - name: card_template_id - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: card template id - zh_Hans: 卡片模板ID - zh_Hant: 卡片範本ID - description: - en_US: Template for streaming text replies. Save and publish it in DingTalk Card Platform, then paste its ID here to automatically enable streaming while card replies are enabled. Leave empty for ordinary replies. Separate from the human input template. - zh_Hans: 用于流式文字回复。在钉钉卡片平台保存并发布模板后,开启卡片回复后,填写 ID 即自动启用流式回复,留空使用普通回复;与人工输入卡片模板分开配置。 - zh_Hant: 用於串流文字回覆。在釘釘卡片平台儲存並發布範本後,開啟卡片回覆後,填寫 ID 即自動啟用串流回覆,留空使用一般回覆;與人工輸入卡片範本分開設定。 - type: string - required: false - default: "" - - name: stream_card_template_download - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: Download Streaming Reply Card Template - zh_Hans: 下载流式回复卡片模板 - zh_Hant: 下載串流回覆卡片範本 - description: - en_US: Displays reasoning and the answer separately. Import through More > Import Card Template in the DingTalk AI card editor, save and publish, then paste its ID into Card Template ID above. Respects the pipeline thinking removal setting. - zh_Hans: 分开展示思考与正文。在钉钉 AI 卡片编辑器中选择「更多 → 导入卡片模板」,保存并发布后,将 ID 填入上方「卡片模板 ID」。是否保留思考仍由流水线设置控制。 - zh_Hant: 分開展示思考與正文。在釘釘 AI 卡片編輯器中選擇「更多 → 匯入卡片範本」,儲存並發布後,將 ID 填入上方「卡片範本 ID」。是否保留思考仍由流水線設定控制。 - type: download-link - required: false - default: '' - url: /api/v1/platform/adapters/dingtalk/stream-card-template - download_filename: dingtalk_stream_card.json - - name: card_auto_layout - show_if: - field: markdown_card - operator: eq - value: true - label: - en_US: Card Auto Layout - zh_Hans: 卡片宽屏自动布局 - zh_Hant: 卡片寬螢幕自動佈局 - description: - en_US: Enabled by default. Allows supported cards to adapt to wider windows. The LangBot streaming reply template includes the required variables; you can disable this for a narrower layout. - zh_Hans: 默认开启,让支持的卡片适应较宽的聊天窗口。LangBot 流式回复模板已包含所需变量;如需较窄布局,可关闭此项。 - zh_Hant: 預設開啟,讓支援的卡片適應較寬的聊天視窗。LangBot 串流回覆範本已包含所需變數;如需較窄版面,可關閉此項。 - type: boolean - required: false - default: true - - name: human_input_card_template_id - label: - en_US: Human Input Card Template ID - zh_Hans: 人工输入卡片模板ID - zh_Hant: 人工輸入卡片範本ID - description: - en_US: Optional. Used when a workflow or plugin requests user input, a choice, or confirmation before continuing (for example, a Dify Human Input node). Ordinary chat does not require it. Import the template below and enter its published ID here; streaming text replies use the separate Card Template ID. - zh_Hans: 可选。当工作流或插件需要用户填写信息、选择选项或确认后再继续执行时使用,例如 Dify 的人工输入节点。普通聊天无需配置。请导入下方模板,将发布后的 ID 填在这里;流式文字回复使用单独的「卡片模板 ID」。 - zh_Hant: 可選。當工作流或外掛需要使用者填寫資訊、選擇選項或確認後再繼續執行時使用,例如 Dify 的人工輸入節點。一般聊天無需設定。請匯入下方範本,將發布後的 ID 填在這裡;串流文字回覆使用獨立的「卡片範本 ID」。 - type: string - required: false - default: "" - - name: human_input_card_template_download - label: - en_US: Download Human Input Card Template - zh_Hans: 下载人工输入卡片模板 - zh_Hant: 下載人工輸入卡片範本 - description: - en_US: Download the human input template. Create an AI card in DingTalk Card Platform, choose More > Import Card Template in the editor, then save and publish. Paste its ID into the field above. - zh_Hans: 下载人工输入模板后,在钉钉卡片平台新建 AI 卡片,在编辑器中选择「更多 → 导入卡片模板」,保存并发布,将 ID 填入上方字段。 - zh_Hant: 下載人工輸入範本後,在釘釘卡片平台新建 AI 卡片,在編輯器中選擇「更多 → 匯入卡片範本」,儲存並發布,將 ID 填入上方欄位。 - type: download-link - required: false - default: "" - url: /api/v1/platform/adapters/dingtalk/human-input-card-template - download_filename: dingtalk_human_input_card.json - help_links: - zh: https://langbot.app/docs/zh/usage/platforms/dingtalk#导入人工输入卡片模板 - en: https://open-dev.dingtalk.com/fe/card - ja: https://open-dev.dingtalk.com/fe/card - help_label: - en_US: Import Guide - zh_Hans: 导入指引 - zh_Hant: 匯入指引 - ja_JP: インポート手順 execution: python: path: ./dingtalk.py diff --git a/src/langbot/pkg/plugin/handler.py b/src/langbot/pkg/plugin/handler.py index 05a17cbab..bc19381f7 100644 --- a/src/langbot/pkg/plugin/handler.py +++ b/src/langbot/pkg/plugin/handler.py @@ -1364,6 +1364,41 @@ class RuntimeConnectionHandler(handler.Handler): }, ) + @self.action(PluginToRuntimeAction.REQUEST_INTERACTION) + async def request_interaction(data: dict[str, Any]) -> handler.ActionResponse: + action_context, _ = await self._require_plugin_action_context() + session, error = await _validate_agent_run_session( + data.get('run_id'), data.get('caller_plugin_identity'), self.ap, 'request_interaction' + ) + if error: + return error + authorization = session['authorization'] + if authorization.get('workspace_id') != action_context.workspace_uuid: + return handler.ActionResponse.error('Run belongs to another Workspace') + if not authorization.get('interactions_enabled') or not authorization.get('interactions_authorized'): + return handler.ActionResponse.error('Runner did not declare interaction capability and permission') + bot_id = authorization.get('bot_id') + if not bot_id: + return handler.ActionResponse.error('Interaction requires a platform bot') + bot = await self.ap.platform_mgr.get_bot_by_uuid(self._execution_context(action_context), bot_id) + if bot is None: + return handler.ActionResponse.error('Interaction bot is not running') + manager = self.ap.agent_run_orchestrator.interaction_manager + try: + result = await manager.request_interaction( + session=session, + adapter=bot.adapter, + request_payload=data['request'], + timeout=float(data['timeout']), + on_unsupported=data.get('on_unsupported', 'error'), + responders=data.get('responders', 'actor'), + target_type=data.get('target_type'), + target_id=data.get('target_id'), + ) + return handler.ActionResponse.success(data=result) + except (ValueError, KeyError, TypeError, pydantic.ValidationError) as exc: + return handler.ActionResponse.error(str(exc)) + @self.action(PluginToRuntimeAction.GET_LLM_MODELS) async def get_llm_models(data: dict[str, Any]) -> handler.ActionResponse: """Get llm models, returns list of UUID strings""" @@ -3032,7 +3067,6 @@ class RuntimeConnectionHandler(handler.Handler): Yields RunnerResult dicts. """ - timeout = self._get_runner_action_timeout(context) gen = self.call_action_generator( LangBotToRuntimeAction.RUN_RUNNER, { @@ -3041,28 +3075,13 @@ class RuntimeConnectionHandler(handler.Handler): 'runner_name': runner_name, 'context': context, }, - timeout=timeout, + timeout=None, ) async with contextlib.aclosing(gen): async for ret in gen: yield ret - def _get_runner_action_timeout(self, context: dict[str, Any]) -> float: - """Use the run deadline as the transport idle timeout when available.""" - try: - import time - - deadline_at = (context.get('runtime') or {}).get('deadline_at') - if deadline_at is None: - return 300 - remaining = float(deadline_at) - time.time() - if remaining <= 0: - return 0.001 - return max(remaining + 1.0, 0.001) - except (TypeError, ValueError): - return 300 - async def get_plugin_icon(self, plugin_author: str, plugin_name: str) -> dict[str, Any]: """Get plugin icon""" result = await self.call_action( diff --git a/src/langbot/templates/dingtalk_human_input_card.json b/src/langbot/templates/dingtalk_human_input_card.json deleted file mode 100644 index 81e891ac6..000000000 --- a/src/langbot/templates/dingtalk_human_input_card.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "editorData": "{\"schemaVersion\":\"3.0.0\",\"schema\":{\"config\":null,\"componentsMap\":[{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AIPending\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AIPending\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardStatusContainer\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardStatusContainer\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"BaseText\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"BaseText\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardContent\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardContent\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardContainer\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardContainer\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"ButtonGroup\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"ButtonGroup\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"MarkdownBlock\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"MarkdownBlock\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"Avatar\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"Avatar\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"Input\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"Input\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"SelectBlock\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"SelectBlock\"}],\"componentsTree\":[{\"componentName\":\"AICardContainer\",\"id\":\"node_root\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enablePending\":true,\"enableWriting\":true,\"enableDoing\":true,\"enableFailed\":true,\"summaryContent\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"\"},\"enableTitle\":false,\"flowStatusVar\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"flowStatus\"},\"operationPenalType\":\"custom\",\"enableFlowAbort\":true,\"innerOffset\":0,\"enableGradientBorder\":true,\"cardSizeMode\":\"adaptive\",\"cardSizeHeightMode\":\"adaptive\",\"cardSizeWidthMode\":\"adaptive\",\"cardSizeHeight\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":226,\"variable\":\"\",\"variableType\":\"global\"},\"hasBackground\":false,\"backgroundType\":\"Standard\",\"standardBackgroundColor\":\"gray\",\"backgroundColor\":\"#F6F6F6\",\"darkModeBackgroundColor\":\"#3C3C3C\",\"enableEngineUpgrade\":false,\"enableExposeStatPoint\":false,\"enableDebugTool\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_pending\",\"props\":{\"status\":1,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"处理中状态\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AIPending\",\"id\":\"node_pending_inner\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"pendingTip\":{\"type\":\"dynamicString\",\"content\":\"处理中...\",\"i18n\":false},\"style\":\"embed\",\"hideIcon\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_writing\",\"props\":{\"status\":2,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"状态2占位\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_status_writing_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[]}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_doing\",\"props\":{\"status\":4,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"状态4占位\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_status_doing_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[]}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_done\",\"props\":{\"status\":3,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"完成状态\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_done_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"Avatar\",\"id\":\"node_avatar\",\"props\":{\"imageUrl\":{\"value\":\"\",\"valueType\":\"variable\",\"type\":\"dynamicImage\",\"variable\":\"bot_avatar\",\"variableType\":\"global\"},\"name\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"LangBot\"},\"sizeType\":\"Standard\",\"size\":\"extraSmall\",\"customSize\":48,\"marginLeft\":12,\"marginRight\":12,\"marginTop\":6,\"marginBottom\":6,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"mode\":\"userInfo\",\"margin\":-2,\"innerOffset\":0},\"title\":\"头像\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"},{\"componentName\":\"MarkdownBlock\",\"id\":\"node_text_content\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"content\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":6,\"marginBottom\":6,\"marginLeft\":12,\"marginRight\":12},\"title\":\"AI 流式富文本\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"},{\"componentName\":\"Input\",\"id\":\"node_input\",\"props\":{\"placeholder\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false,\"variable\":\"input_placeholder\",\"variableType\":\"global\"},\"currentValue\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false,\"variable\":\"input_value\",\"variableType\":\"global\"},\"message\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false,\"variable\":\"input_placeholder\",\"variableType\":\"global\"},\"title\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false,\"variable\":\"input_title\",\"variableType\":\"global\"},\"id\":{\"type\":\"dynamicString\",\"content\":\"input\",\"i18n\":false},\"params\":[{\"type\":\"builtIn\",\"variable\":\"\",\"value\":\"\",\"name\":\"input\",\"variableType\":\"global\",\"id\":\"__built_in_inputResult__\"}],\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"variable\",\"variable\":\"input_visible\",\"variableType\":\"global\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"status\":{\"type\":\"dynamicSelect\",\"valueType\":\"fixed\",\"value\":\"normal\",\"variable\":\"\",\"variableType\":\"global\"},\"actionType\":\"request\",\"localVarAction\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"\"},\"keyOfDynamicObject\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"inlineMode\":false,\"textArea\":true,\"minRows\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":2,\"variable\":\"\",\"variableType\":\"global\"},\"maxRows\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":6,\"variable\":\"\",\"variableType\":\"global\"},\"marginLeft\":12,\"marginRight\":12,\"marginTop\":6,\"marginBottom\":6,\"margin\":12,\"innerOffset\":0},\"title\":\"Text input\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"},{\"componentName\":\"SelectBlock\",\"id\":\"node_select\",\"props\":{\"id\":{\"type\":\"dynamicString\",\"content\":\"select\",\"i18n\":false},\"placeholder\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false,\"variable\":\"select_placeholder\",\"variableType\":\"global\"},\"currentIndex\":{\"type\":\"dynamicNumber\",\"valueType\":\"variable\",\"value\":-1,\"variable\":\"select_index\",\"variableType\":\"global\"},\"options\":{\"type\":\"dynamicSelectOptions\",\"valueType\":\"variable\",\"value\":[],\"variable\":\"index_o\",\"variableType\":\"global\"},\"optionLabelMaxLines\":3,\"params\":[{\"type\":\"builtIn\",\"variable\":\"\",\"value\":\"{\\\"index\\\": ${index}, \\\"value\\\": \\\"${value}\\\"}\",\"name\":\"select\",\"variableType\":\"global\",\"id\":\"__built_in_selectResult__\"}],\"actionType\":\"request\",\"localVarAction\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"\"},\"keyOfDynamicObject\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"status\":{\"type\":\"dynamicSelect\",\"valueType\":\"fixed\",\"value\":\"normal\",\"variable\":\"\",\"variableType\":\"global\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"variable\",\"variable\":\"select_visible\",\"variableType\":\"global\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"marginLeft\":12,\"marginRight\":12,\"marginTop\":6,\"marginBottom\":6,\"pullOptionsWhileOpen\":false,\"pullOptionsRequestParams\":[],\"margin\":12,\"innerOffset\":0},\"title\":\"Select\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"},{\"componentName\":\"ButtonGroup\",\"id\":\"node_btn_group\",\"props\":{\"dynamicButtons\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"btns\"},\"marginLeft\":12,\"marginRight\":12,\"marginTop\":6,\"marginBottom\":12,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"responsiveLayoutWidth\":350,\"buttonsSource\":\"variable\",\"fixedButtonIds\":[],\"fixedButtons\":[],\"enableResponsiveLayout\":false,\"matchContent\":false,\"buttonSpacing\":8,\"margin\":-2,\"innerOffset\":0},\"title\":\"按钮组\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_failed\",\"props\":{\"status\":5,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"失败状态\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_failed_content\",\"props\":{\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"BaseText\",\"id\":\"node_failed_text\",\"props\":{\"text\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"操作失败,请稍后重试。\"},\"hoverText\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"iconType\":\"iconCode\",\"iconFont\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"ddIcon\"},\"icon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"darkIcon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"autoWidth\":false,\"maxWidth\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":0,\"variable\":\"\",\"variableType\":\"global\"},\"fixedWidth\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":0,\"variable\":\"\",\"variableType\":\"global\"},\"marginLeft\":10,\"marginRight\":10,\"marginTop\":10,\"marginBottom\":10,\"fontColorType\":\"Standard\",\"enableHighlight\":false,\"maxLine\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":2,\"variable\":\"\",\"variableType\":\"global\"},\"color\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"common_level1_base_color\",\"variable\":\"\",\"variableType\":\"global\"},\"customLightColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#35404b\",\"variable\":\"\",\"variableType\":\"global\"},\"customDarkColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#f6f6f6\",\"variable\":\"\",\"variableType\":\"global\"},\"gravity\":\"center\",\"fontSizeType\":\"Standard\",\"styleType\":\"custom\",\"styleToken\":\"common_body_text_style\",\"size\":\"middle\",\"customFontSize\":15,\"customFontLineHeight\":22,\"bold\":false,\"italic\":false,\"strikeThrough\":false,\"lineHeight\":\"normal\",\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"autoMaxWidth\":false,\"innerOffset\":0,\"enableIcon\":false,\"widthMode\":\"match_parent\",\"margin\":-2},\"title\":\"基础文本\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]}]}]}],\"i18n\":{},\"version\":\"1.0.0\"},\"mockData\":{\"cardData\":{\"flowStatus\":3,\"content\":\"请审核以下报销申请:\\n\\n- 申请人:张三\\n- 金额:¥1,200\\n- 类别:差旅\",\"input_visible\":\"\",\"input_title\":\"\",\"input_placeholder\":\"\",\"input_value\":\"\",\"select_visible\":\"\",\"select_placeholder\":\"\",\"index_o\":[{\"value\":\"\",\"text\":{\"zh_CN\":\"\",\"zh_TW\":\"\",\"en_US\":\"\",\"ja_JP\":\"\",\"vi_VN\":\"\",\"th_TH\":\"\",\"id_ID\":\"\",\"ne_NP\":\"\",\"ms_MY\":\"\",\"ko_KR\":\"\",\"ru_RU\":\"\",\"es_EA\":\"\",\"tr_TR\":\"\",\"fr_FR\":\"\",\"pt_BR\":\"\"}}],\"select_options\":[],\"select_index\":-1,\"btns\":[{\"text\":\"通过\",\"color\":\"blue\",\"status\":\"normal\",\"event\":{\"type\":\"sendCardRequest\",\"params\":{\"actionId\":\"approve\",\"params\":{\"action_id\":\"approve\"}}}},{\"text\":\"驳回\",\"color\":\"gray\",\"status\":\"normal\",\"event\":{\"type\":\"sendCardRequest\",\"params\":{\"actionId\":\"reject\",\"params\":{\"action_id\":\"reject\"}}}},{\"text\":\"补充资料\",\"color\":\"gray\",\"status\":\"normal\",\"event\":{\"type\":\"sendCardRequest\",\"params\":{\"actionId\":\"more_info\",\"params\":{\"action_id\":\"more_info\"}}}}]},\"cardPrivateData\":{},\"localData\":{\"flowStatus\":\"\",\"_cardFoldStatusLocalDataKey\":\"\"},\"richTextData\":{}},\"renderContext\":{\"regenerateEnabled\":\"1\",\"regenerateIndex\":\"2\",\"regenerateTotal\":\"5\"},\"editVersion\":0,\"customWidgetInfo\":\"\",\"useCustomWidgetInfo\":false,\"variableList\":[{\"id\":\"content\",\"type\":\"markdown\",\"name\":\"content\",\"description\":\"人工输入提示词(Dify form_content 含可选 node_title 前缀)\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"flowStatus\",\"type\":\"string\",\"name\":\"flowStatus\",\"description\":\"AI卡片状态:pending(1)、writing(2)、done(3)、failed(5)\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"visible\":false},{\"id\":\"bot_avatar\",\"type\":\"string\",\"name\":\"bot_avatar\",\"description\":\"机器人头像 DingTalk 媒体 ID(@xxx 格式,启动时由 /media/upload 拿到)\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"input_visible\",\"type\":\"string\",\"name\":\"input_visible\",\"description\":\"Whether to show the text input component\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"input_title\",\"type\":\"string\",\"name\":\"input_title\",\"description\":\"Text input title\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"input_placeholder\",\"type\":\"string\",\"name\":\"input_placeholder\",\"description\":\"Text input placeholder\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"input_value\",\"type\":\"string\",\"name\":\"input_value\",\"description\":\"Text input current value\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"select_visible\",\"type\":\"string\",\"name\":\"select_visible\",\"description\":\"Whether to show the select component\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"select_placeholder\",\"type\":\"string\",\"name\":\"select_placeholder\",\"description\":\"Select placeholder\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"name\":\"index_o\",\"private\":false,\"type\":\"selectOptions\",\"id\":\"index_o\",\"description\":\"Select options\",\"editorVarType\":\"variables\",\"disabled\":false,\"schema\":[{\"id\":\"index_o.value\",\"type\":\"string\",\"name\":\"value\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.text\",\"type\":\"object\",\"name\":\"text\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\",\"schema\":[{\"id\":\"index_o.zh_CN\",\"type\":\"string\",\"name\":\"zh_CN\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.zh_TW\",\"type\":\"string\",\"name\":\"zh_TW\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.en_US\",\"type\":\"string\",\"name\":\"en_US\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.ja_JP\",\"type\":\"string\",\"name\":\"ja_JP\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.vi_VN\",\"type\":\"string\",\"name\":\"vi_VN\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.th_TH\",\"type\":\"string\",\"name\":\"th_TH\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.id_ID\",\"type\":\"string\",\"name\":\"id_ID\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.ne_NP\",\"type\":\"string\",\"name\":\"ne_NP\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.ms_MY\",\"type\":\"string\",\"name\":\"ms_MY\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.ko_KR\",\"type\":\"string\",\"name\":\"ko_KR\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.ru_RU\",\"type\":\"string\",\"name\":\"ru_RU\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.es_EA\",\"type\":\"string\",\"name\":\"es_EA\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.tr_TR\",\"type\":\"string\",\"name\":\"tr_TR\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.fr_FR\",\"type\":\"string\",\"name\":\"fr_FR\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"},{\"id\":\"index_o.pt_BR\",\"type\":\"string\",\"name\":\"pt_BR\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"\"}]}]},{\"id\":\"select_options\",\"type\":\"array\",\"name\":\"select_options\",\"description\":\"Legacy select options\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"select_index\",\"type\":\"number\",\"name\":\"select_index\",\"description\":\"Current select index\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"name\":\"btns\",\"private\":false,\"type\":\"buttonGroup\",\"id\":\"btns\",\"description\":\"动态按钮列表(Dify actions)\",\"editorVarType\":\"variables\",\"disabled\":false,\"schema\":[{\"id\":\"btns.text\",\"type\":\"string\",\"name\":\"text\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"按钮文案\"},{\"id\":\"btns.color\",\"type\":\"string\",\"name\":\"color\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"按钮颜色\"},{\"id\":\"btns.status\",\"type\":\"string\",\"name\":\"status\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"按钮状态\"},{\"id\":\"btns.event\",\"type\":\"dynamicEvent\",\"name\":\"event\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"按钮点击事件\",\"schema\":[{\"id\":\"btns.type\",\"type\":\"string\",\"name\":\"type\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"事件类型:openLink / sendCardRequest\"},{\"id\":\"btns.params\",\"type\":\"object\",\"name\":\"params\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"事件参数\",\"schema\":[{\"id\":\"btns.url\",\"type\":\"string\",\"name\":\"url\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"点击跳转链接(type=openLink)\"},{\"id\":\"btns.actionId\",\"type\":\"string\",\"name\":\"actionId\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"回传请求 id(type=sendCardRequest)\"},{\"id\":\"btns.params\",\"type\":\"object\",\"name\":\"params\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":true,\"description\":\"回传请求参数(type=sendCardRequest)\"}]}]}]}],\"formList\":[],\"customContextList\":[],\"expList\":[],\"localList\":[],\"hsfList\":[],\"lwpList\":[],\"pageData\":{},\"extension\":{\"extendType\":\"AI\",\"aiStatusList\":[3,1,5,2,4],\"fileTypeList\":[]}}", - "widgetInfo": "", - "type": "im", - "mode": "card" -} \ No newline at end of file diff --git a/src/langbot/templates/dingtalk_stream_card.json b/src/langbot/templates/dingtalk_stream_card.json deleted file mode 100644 index e11cb3154..000000000 --- a/src/langbot/templates/dingtalk_stream_card.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "editorData": "{\"schemaVersion\":\"3.0.0\",\"schema\":{\"config\":null,\"componentsMap\":[{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AIPending\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AIPending\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardStatusContainer\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardStatusContainer\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"BaseText\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"BaseText\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardContent\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardContent\",\"children\":[]},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AICardContainer\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AICardContainer\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"MarkdownBlock\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"MarkdownBlock\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"CollapsePanel\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"CollapsePanel\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"AIGenerationProcessing\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"AIGenerationProcessing\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"Feedback\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"Feedback\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"Grid\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"Grid\"},{\"package\":\"@ali/dxComponent\",\"version\":\"1.0.0\",\"exportName\":\"Image\",\"main\":\"./src/index.tsx\",\"destructuring\":false,\"subName\":\"\",\"componentName\":\"Image\"}],\"componentsTree\":[{\"componentName\":\"AICardContainer\",\"id\":\"node_root\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enablePending\":true,\"enableWriting\":true,\"enableDoing\":true,\"enableFailed\":true,\"summaryContent\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"\"},\"enableTitle\":false,\"flowStatusVar\":{\"type\":\"variableValue\",\"variableType\":\"global\",\"variable\":\"flowStatus\"},\"operationPenalType\":\"prompt\",\"enableFlowAbort\":false,\"innerOffset\":0,\"enableGradientBorder\":true,\"cardSizeMode\":\"adaptive\",\"cardSizeHeightMode\":\"adaptive\",\"cardSizeWidthMode\":\"adaptive\",\"cardSizeHeight\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":226,\"variable\":\"\",\"variableType\":\"global\"},\"hasBackground\":false,\"backgroundType\":\"Standard\",\"standardBackgroundColor\":\"gray\",\"backgroundColor\":\"#F6F6F6\",\"darkModeBackgroundColor\":\"#3C3C3C\",\"enableEngineUpgrade\":false,\"enableExposeStatPoint\":false,\"enableDebugTool\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_pending\",\"props\":{\"status\":1,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"处理中\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AIPending\",\"id\":\"node_pending_inner\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"pendingTip\":{\"type\":\"dynamicString\",\"content\":\"正在处理…\",\"i18n\":false},\"style\":\"embed\",\"hideIcon\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_writing\",\"props\":{\"status\":2,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":false,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"回复中\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_status_writing_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"CollapsePanel\",\"id\":\"langbot_reasoning_2\",\"props\":{\"id\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"reasoning_2\"},\"title\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"思考过程 · 输出中\"},\"contentVisible\":true,\"marginLeft\":12,\"marginRight\":12,\"marginBottom\":8,\"marginTop\":4,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"variable\",\"variable\":\"hasReasoning\",\"variableType\":\"global\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"margin\":-2,\"innerOffset\":0},\"title\":\"思考过程\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"MarkdownBlock\",\"id\":\"node_2_reasoning\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"reasoning\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"reasoning\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"MarkdownBlock\",\"id\":\"node_2_answer\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"answer\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"answer\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_doing\",\"props\":{\"status\":4,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":false,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"执行中\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_status_doing_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"CollapsePanel\",\"id\":\"langbot_reasoning_4\",\"props\":{\"id\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"reasoning_4\"},\"title\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"思考过程 · 输出中\"},\"contentVisible\":true,\"marginLeft\":12,\"marginRight\":12,\"marginBottom\":8,\"marginTop\":4,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"variable\",\"variable\":\"hasReasoning\",\"variableType\":\"global\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"margin\":-2,\"innerOffset\":0},\"title\":\"思考过程\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"MarkdownBlock\",\"id\":\"node_4_reasoning\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"reasoning\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"reasoning\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"MarkdownBlock\",\"id\":\"node_4_answer\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"answer\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"answer\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_done\",\"props\":{\"status\":3,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":false,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"已完成\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_done_content\",\"props\":{\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"CollapsePanel\",\"id\":\"langbot_reasoning_3\",\"props\":{\"id\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"reasoning_3\"},\"title\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"思考过程\"},\"contentVisible\":false,\"marginLeft\":12,\"marginRight\":12,\"marginBottom\":8,\"marginTop\":4,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"variable\",\"variable\":\"hasReasoning\",\"variableType\":\"global\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"margin\":-2,\"innerOffset\":0},\"title\":\"思考过程\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"MarkdownBlock\",\"id\":\"node_3_reasoning\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"reasoning\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"reasoning\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"MarkdownBlock\",\"id\":\"node_3_answer\",\"props\":{\"mdVer\":0,\"icon\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"emoji\"},\"content\":{\"variable\":\"answer\",\"variableType\":\"global\",\"type\":\"variableValue\",\"varType\":\"markdown\"},\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"isStreaming\":false,\"enableLinkStatPoint\":false,\"linkStatPoint\":{\"type\":\"dynamicString\",\"content\":\"Page_InteractiveCard__Click_markdownOpenlink\",\"i18n\":false},\"linkStatPointParams\":[],\"marginTop\":8,\"marginBottom\":8,\"marginLeft\":12,\"marginRight\":12},\"title\":\"answer\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"Grid\",\"id\":\"langbot_operation_row\",\"props\":{\"direction\":\"horizontal\",\"isAutoHeight\":true,\"isAutoWidth\":false,\"autoWidth\":false,\"isFixedWidth\":false,\"fixWidth\":false,\"width\":100,\"childGravity\":\"leftTop\",\"hasBackground\":false,\"hasGradientBackground\":false,\"hasBorder\":false,\"marginLeft\":12,\"marginRight\":12,\"marginTop\":0,\"marginBottom\":0,\"actionType\":\"none\"},\"children\":[{\"componentName\":\"Grid\",\"id\":\"langbot_link\",\"props\":{\"direction\":\"horizontal\",\"isAutoHeight\":false,\"isAutoWidth\":true,\"autoWidth\":true,\"isFixedWidth\":false,\"fixWidth\":false,\"childGravity\":\"leftCenter\",\"hasBackground\":false,\"hasGradientBackground\":false,\"hasBorder\":false,\"marginLeft\":0,\"marginRight\":8,\"marginTop\":0,\"marginBottom\":0,\"actionType\":\"url\",\"urlType\":\"all\",\"url\":{\"type\":\"dynamicLink\",\"valueType\":\"fixed\",\"value\":\"https://langbot.app?utm_source=dingtalk&utm_medium=bot_card&utm_campaign=langbot\",\"variable\":\"\",\"variableType\":\"global\"},\"height\":28},\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"Image\",\"id\":\"langbot_logo\",\"props\":{\"images\":{\"defaultLang\":\"zh_Hans\",\"content\":{\"zh_Hans\":{\"value\":\"https://langbot.app/logo-blue.png\",\"valueType\":\"fixed\",\"type\":\"dynamicImage\"}},\"i18n\":false},\"darkModeImages\":{\"defaultLang\":\"zh_Hans\",\"content\":{\"zh_Hans\":{\"value\":\"\",\"valueType\":\"fixed\",\"type\":\"dynamicImage\"}},\"i18n\":false},\"single\":true,\"height\":{\"type\":\"dynamicWidth\",\"valueType\":\"fixed\",\"value\":12,\"variableType\":\"global\",\"variable\":\"\",\"full\":false,\"adaptive\":false},\"width\":{\"type\":\"dynamicWidth\",\"valueType\":\"fixed\",\"value\":12,\"variableType\":\"global\",\"variable\":\"\",\"full\":false,\"adaptive\":false},\"cornerRadius\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":0,\"variable\":\"\",\"variableType\":\"global\"},\"scaleType\":\"fitCenter\",\"enablePreview\":false,\"marginRight\":4,\"marginTop\":0,\"marginBottom\":0,\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"adaptiveSize\":false,\"fixedRatio\":false,\"hoverText\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"enableBorder\":false,\"borderColor\":\"#297f8790\",\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"aspectRatio\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":2,\"variable\":\"\",\"variableType\":\"global\"},\"offsetLeft\":0,\"offsetRight\":0,\"marginLeft\":0,\"innerOffset\":0,\"enableStatPoint\":false,\"margin\":-2},\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"},{\"componentName\":\"BaseText\",\"id\":\"langbot_name\",\"props\":{\"text\":{\"type\":\"dynamicString\",\"content\":\"LangBot\",\"i18n\":false},\"hoverText\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"iconType\":\"iconCode\",\"iconFont\":{\"type\":\"icon\",\"iconType\":\"ddIcon\",\"icon\":\"icon_question_fill\"},\"icon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"darkIcon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"autoWidth\":true,\"maxWidth\":0,\"fixedWidth\":0,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"fontColorType\":\"Standard\",\"enableHighlight\":false,\"maxLine\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":1},\"color\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"common_level3_base_color\"},\"customLightColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#35404b\",\"variable\":\"\",\"variableType\":\"global\"},\"customDarkColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#f6f6f6\",\"variable\":\"\",\"variableType\":\"global\"},\"gravity\":\"left\",\"fontSizeType\":\"Standard\",\"styleType\":\"custom\",\"styleToken\":\"common_body_text_style\",\"size\":\"small\",\"customFontSize\":12,\"customFontLineHeight\":16,\"bold\":false,\"italic\":false,\"strikeThrough\":false,\"lineHeight\":\"normal\",\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"autoMaxWidth\":false,\"innerOffset\":0,\"enableIcon\":false,\"widthMode\":\"wrap_content\"},\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"Grid\",\"id\":\"langbot_native_operations\",\"props\":{\"direction\":\"horizontal\",\"isAutoHeight\":true,\"isAutoWidth\":false,\"autoWidth\":false,\"isFixedWidth\":false,\"fixWidth\":false,\"width\":100,\"childGravity\":\"leftTop\",\"hasBackground\":false,\"hasGradientBackground\":false,\"hasBorder\":false,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"actionType\":\"none\"},\"children\":[{\"componentName\":\"Feedback\",\"id\":\"node_ocmv2bczc8a\",\"props\":{\"params\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"marginConfigurable\":false,\"enableLikeDislike\":true,\"enableCopy\":true,\"copyType\":\"common\",\"copyVariable\":{\"type\":\"variableValue\",\"variable\":\"answer\",\"variableType\":\"global\",\"varType\":\"markdown\"},\"enableDivider\":false,\"margin\":-2,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"innerOffset\":0,\"enableRefresh\":false,\"actionType\":\"none\",\"actionId\":{\"type\":\"dynamicString\",\"content\":\"sys_action_like_component\",\"i18n\":false},\"refreshParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"refreshSuccessCondition\":{\"op\":\"and\",\"conditions\":[]},\"refreshSuccessToast\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"refreshFailureToast\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"refreshVisible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}}},\"title\":\"操作区\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[]}],\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}],\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]},{\"componentName\":\"AICardStatusContainer\",\"id\":\"node_status_failed\",\"props\":{\"status\":5,\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"enableExtend\":false,\"autoFoldConfig\":{\"needFold\":true,\"heightLimit\":480,\"foldStatusLocalDataKey\":\"_cardFoldStatusLocalDataKey\"},\"innerOffset\":0,\"enableCollapse\":false,\"margin\":-2},\"title\":\"失败\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"AICardContent\",\"id\":\"node_failed_content\",\"props\":{\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"marginLeft\":0,\"marginRight\":0,\"marginTop\":0,\"marginBottom\":0,\"innerOffset\":0,\"disabledWhileForward\":false,\"statPoint\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"statPointParams\":[{\"type\":\"fixed\",\"variable\":\"\",\"value\":\"\",\"name\":\"\",\"variableType\":\"global\",\"id\":\"1\"}],\"margin\":-2,\"transformToEventChain\":false,\"enableStatPoint\":false},\"hidden\":false,\"title\":\"\",\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\",\"children\":[{\"componentName\":\"BaseText\",\"id\":\"node_failed_text\",\"props\":{\"text\":{\"i18n\":false,\"type\":\"dynamicString\",\"content\":\"操作失败,请稍后重试。\"},\"hoverText\":{\"type\":\"dynamicString\",\"content\":\"\",\"i18n\":false},\"iconType\":\"iconCode\",\"iconFont\":{\"type\":\"icon\",\"icon\":\"\",\"iconType\":\"ddIcon\"},\"icon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"darkIcon\":{\"type\":\"dynamicLink\",\"value\":\"\",\"valueType\":\"fixed\",\"variable\":\"\",\"variableType\":\"global\"},\"autoWidth\":false,\"maxWidth\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":0,\"variable\":\"\",\"variableType\":\"global\"},\"fixedWidth\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":0,\"variable\":\"\",\"variableType\":\"global\"},\"marginLeft\":10,\"marginRight\":10,\"marginTop\":10,\"marginBottom\":10,\"fontColorType\":\"Standard\",\"enableHighlight\":false,\"maxLine\":{\"type\":\"dynamicNumber\",\"valueType\":\"fixed\",\"value\":2,\"variable\":\"\",\"variableType\":\"global\"},\"color\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"common_level1_base_color\",\"variable\":\"\",\"variableType\":\"global\"},\"customLightColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#35404b\",\"variable\":\"\",\"variableType\":\"global\"},\"customDarkColor\":{\"type\":\"dynamicColor\",\"valueType\":\"fixed\",\"value\":\"#f6f6f6\",\"variable\":\"\",\"variableType\":\"global\"},\"gravity\":\"center\",\"fontSizeType\":\"Standard\",\"styleType\":\"custom\",\"styleToken\":\"common_body_text_style\",\"size\":\"middle\",\"customFontSize\":15,\"customFontLineHeight\":22,\"bold\":false,\"italic\":false,\"strikeThrough\":false,\"lineHeight\":\"normal\",\"visible\":{\"type\":\"dynamicVisible\",\"value\":true,\"valueType\":\"fixed\",\"condition\":{\"op\":\"and\",\"conditions\":[]}},\"autoMaxWidth\":false,\"innerOffset\":0,\"enableIcon\":false,\"widthMode\":\"match_parent\",\"margin\":-2},\"title\":\"基础文本\",\"hidden\":false,\"isLocked\":false,\"condition\":true,\"conditionGroup\":\"\"}]}]}]}],\"i18n\":{},\"version\":\"1.0.0\"},\"mockData\":{\"cardData\":{\"flowStatus\":\"3\",\"content\":\"\",\"reasoning\":\"> 这里展示模型返回的思考内容。\",\"answer\":\"这里展示正式回答。\",\"query\":\"\",\"config\":{\"autoLayout\":true},\"brand\":\"\",\"hasReasoning\":\"true\",\"autoLayout\":\"true\"},\"cardPrivateData\":{},\"localData\":{\"flowStatus\":\"\",\"_cardFoldStatusLocalDataKey\":\"\"},\"richTextData\":{}},\"renderContext\":{\"regenerateEnabled\":\"1\",\"regenerateIndex\":\"2\",\"regenerateTotal\":\"5\"},\"editVersion\":0,\"customWidgetInfo\":\"\",\"useCustomWidgetInfo\":false,\"variableList\":[{\"id\":\"content\",\"name\":\"content\",\"type\":\"markdown\",\"description\":\"content\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"reasoning\",\"name\":\"reasoning\",\"type\":\"markdown\",\"description\":\"reasoning\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"answer\",\"name\":\"answer\",\"type\":\"markdown\",\"description\":\"answer\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"flowStatus\",\"name\":\"flowStatus\",\"type\":\"string\",\"description\":\"flowStatus\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"query\",\"name\":\"query\",\"type\":\"string\",\"description\":\"query\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"config\",\"name\":\"config\",\"type\":\"object\",\"description\":\"config\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false,\"schema\":[{\"id\":\"config.autoLayout\",\"name\":\"autoLayout\",\"type\":\"boolean\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false,\"description\":\"Wide card layout\"}]},{\"id\":\"brand\",\"name\":\"brand\",\"type\":\"markdown\",\"description\":\"brand\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"hasReasoning\",\"name\":\"hasReasoning\",\"type\":\"string\",\"description\":\"hasReasoning\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false},{\"id\":\"autoLayout\",\"name\":\"autoLayout\",\"type\":\"string\",\"description\":\"Card auto layout\",\"private\":false,\"editorVarType\":\"variables\",\"disabled\":false}],\"formList\":[],\"customContextList\":[],\"expList\":[],\"localList\":[],\"hsfList\":[],\"lwpList\":[],\"pageData\":{},\"extension\":{\"extendType\":\"AI\",\"aiStatusList\":[3,1,5,2,4],\"fileTypeList\":[]}}", - "widgetInfo": "", - "type": "im", - "mode": "card" -} diff --git a/tests/fixtures/legacy_plugin_identity_sources.json b/tests/fixtures/legacy_plugin_identity_sources.json index e820e59e0..c73102001 100644 --- a/tests/fixtures/legacy_plugin_identity_sources.json +++ b/tests/fixtures/legacy_plugin_identity_sources.json @@ -21,7 +21,7 @@ "Runner/LocalAgent/components/runner/default.py": "49f80640d5b26442516b210cd9e65c452c9ce3a9909d6dbd1aa05e5bf3b232ac", "Runner/LocalAgent/components/runner/default.yaml": "c1364cf0f211162bb701e27ed92b351fd9ff4cfa0b4469cfeb83ad58136cdf47", "Runner/LocalAgent/main.py": "0cde45d7f6f411563fbded09be70d0a497c7c7999b5eaa27f83052383348277f", - "Runner/LocalAgent/manifest.yaml": "d4ccb50d83e83e452ab0b14822f245d5dc4bb85c7bc963ee467f299d4723063f", + "Runner/LocalAgent/manifest.yaml": "4482d1ba2ece2acee8763d2d18af6b105a71fde8c8871be46105fcf35aabd521", "Runner/LocalAgent/pkg/__init__.py": "ce5142b4971e8d7945fb3c202bacbc28011b033de0ddcb612d5d29106d6985ec", "Runner/LocalAgent/pkg/agent_core/__init__.py": "56e95f2391f796e17aee6a168603853ea78b59df97a136bfa33532aede2fa413", "Runner/LocalAgent/pkg/agent_core/langbot.py": "6bc0e6ee89e8ba3705d14545169f25f54a0c56dc5da89bd8384b3e22e3f21fea", @@ -34,8 +34,8 @@ "Runner/LocalAgent/pkg/model_calling.py": "3ebdb8900bb0de5b14e84bf027cc4ff01e59a4669d28dcede7ca3dcea3a3de4c", "Runner/LocalAgent/pkg/rag.py": "ea407af8d4f6fe5b00cde72c7d85ccc541d6fc46254188c372351d93da4a1f0f", "Runner/LocalAgent/pkg/run_assembly.py": "e1e2dd0029c976b6c0eb3763e5f94a369fd1909e8bf796a2cb84658c59727630", - "Runner/LocalAgent/pyproject.toml": "99f1c80dd3d5085c2e7836363e8aa4ad07308e7ae02622051946b7da27c3bcef", - "Runner/LocalAgent/requirements.txt": "ed1c13a389087b49644422f2e06f75ff9809412083c9d0d11fa6c750ea75c5b6", + "Runner/LocalAgent/pyproject.toml": "0fbcf5fff8c110a254797d8fae4a90a7dba9701e97355edc2e54b4e7246f88cb", + "Runner/LocalAgent/requirements.txt": "191f36c434aee4dcb5678ce06ac89c25e9d6a2952cf43a6cdc35914039584f41", "Runner/LocalAgent/uv.lock": "96ce3a806d40e282393d46fdc263ec2b1d03aff9f876786dadca12f02d08a6d0" }, "root": "plugins" diff --git a/tests/unit_tests/agent/test_context_validation.py b/tests/unit_tests/agent/test_context_validation.py index bb47a6e12..438a85eed 100644 --- a/tests/unit_tests/agent/test_context_validation.py +++ b/tests/unit_tests/agent/test_context_validation.py @@ -178,22 +178,15 @@ class TestContextValidation: assert validated.input.text == 'Hello world' @pytest.mark.asyncio - async def test_build_context_preserves_interaction_protocol_fields(self): - """Validated submissions and delivery capabilities survive the final context projection.""" + async def test_build_context_preserves_interaction_delivery_capabilities(self): + """Delivery capabilities survive the final context projection.""" from langbot_plugin.api.entities.builtin.runner.interaction import ( InteractionDeliveryCapabilities, - InteractionSubmission, ) mock_app = self._make_mock_app() builder = RunnerContextBuilder(mock_app) event = self._make_event_envelope() - event.event_type = 'interaction.submitted' - event.input.interaction = InteractionSubmission( - interaction_id='form-1', - action_id='approve', - values={'comment': 'looks good'}, - ) event.delivery.interactions = InteractionDeliveryCapabilities( field_types=['text', 'select'], action_styles=['primary'], @@ -213,9 +206,6 @@ class TestContextValidation: ) validated = RunnerContext.model_validate(context_dict) - assert validated.input.interaction is not None - assert validated.input.interaction.interaction_id == 'form-1' - assert validated.input.interaction.values == {'comment': 'looks good'} assert validated.delivery.interactions is not None assert validated.delivery.interactions.field_types == ['text', 'select'] diff --git a/tests/unit_tests/agent/test_event_first_protocol.py b/tests/unit_tests/agent/test_event_first_protocol.py index 2721ff630..a7c7a333e 100644 --- a/tests/unit_tests/agent/test_event_first_protocol.py +++ b/tests/unit_tests/agent/test_event_first_protocol.py @@ -245,8 +245,8 @@ class TestQueryConfigToAgentConfig: assert binding.processor_type == 'pipeline' assert binding.processor_id == mock_query.pipeline_uuid - def test_interaction_submission_projects_control_event(self, mock_query): - """Pipeline callbacks keep structured submission data and match the runner binding.""" + def test_legacy_submission_variable_does_not_create_control_event(self, mock_query): + """Legacy query variables cannot forge an interaction callback.""" mock_query.variables = { '_interaction_submission': { 'interaction_id': 'form-1', @@ -259,10 +259,10 @@ class TestQueryConfigToAgentConfig: agent_config = QueryEntryAdapter.config_to_agent_config(mock_query, 'plugin:langbot-team/DifyAgent/default') binding = AgentBindingResolver().resolve_one(event, [agent_config]) - assert event.event_type == 'interaction.submitted' - assert event.data['interaction']['values'] == {'name': 'Alice'} - assert event.subject.subject_type == 'interaction' - assert agent_config.event_types == ['interaction.submitted'] + assert event.event_type == 'message.received' + assert 'interaction' not in event.data + assert event.subject.subject_type == 'message' + assert agent_config.event_types == ['message.received'] assert binding.processor_type == 'pipeline' def test_resolver_rejects_multiple_matching_agents(self, mock_query): diff --git a/tests/unit_tests/agent/test_interaction_manager.py b/tests/unit_tests/agent/test_interaction_manager.py index 821c24fc7..7d4133a40 100644 --- a/tests/unit_tests/agent/test_interaction_manager.py +++ b/tests/unit_tests/agent/test_interaction_manager.py @@ -1,595 +1,292 @@ -"""Tests for structured interaction authorization and delivery.""" +"""Blocking interaction and callback authorization tests.""" -from __future__ import annotations - -from types import SimpleNamespace +import asyncio import time +from types import SimpleNamespace import pytest -import sqlalchemy as sa from sqlalchemy.ext.asyncio import create_async_engine -from langbot_plugin.api.entities.builtin.runner.delivery import DeliveryContext -from langbot_plugin.api.entities.builtin.runner.event import ActorContext -from langbot_plugin.api.entities.builtin.runner.input import AgentInput from langbot_plugin.api.entities.builtin.runner.interaction import ( InteractionDeliveryCapabilities, - InteractionSubmission, -) - -from langbot.pkg.agent.runner.errors import RunnerProtocolError -from langbot.pkg.agent.runner.host_models import ( - AgentBinding, - AgentEventEnvelope, - BindingScope, - DeliveryPolicy, + InteractionHandle, + InteractionRequest, ) from langbot.pkg.agent.runner.interaction_manager import InteractionManager -from langbot.pkg.agent.runner.interaction_store import InteractionStore +from langbot.pkg.agent.runner.interaction_store import ( + InteractionAlreadySubmittedError, + InteractionExpiredError, + InteractionNotFoundError, + InteractionScopeError, + InteractionStore, +) from langbot.pkg.entity.persistence.base import Base -from langbot.pkg.entity.persistence.pipeline import LegacyPipeline - -CONFIG = { - 'ai': { - 'runner': {'id': 'plugin:test/ApprovalRunner/default'}, - 'runner_config': {'plugin:test/ApprovalRunner/default': {}}, - } -} -def _context(adapter): - conversation = SimpleNamespace(pipeline_uuid='pipeline-1') - query = SimpleNamespace( - pipeline_uuid='pipeline-1', pipeline_config=CONFIG, session=SimpleNamespace(using_conversation=conversation) - ) +def _session(): return { - '_delivery_adapter': adapter, - '_query': query, - '_pipeline_expected_config': CONFIG, - '_pipeline_conversation': conversation, - } - - -class FakeAdapter: - def __init__(self, *, supports_interactions: bool, fail_updates: bool = False): - self.supports_interactions = supports_interactions - self.fail_updates = fail_updates - self.actions: list[tuple[str, dict]] = [] - self.messages: list[tuple[str, str, object]] = [] - - def get_supported_apis(self): - return ['interaction.request', 'interaction.acknowledge'] if self.supports_interactions else ['send_message'] - - async def call_platform_api(self, action: str, params: dict): - self.actions.append((action, params)) - if action == 'interaction.request' and params.get('update_target') and self.fail_updates: - raise RuntimeError('update unavailable') - update_target = params.get('update_target') or {} - message_id = update_target.get('message_id') or f'message-{len(self.actions)}' - card_id = update_target.get('card_id') or f'card-{len(self.actions)}' - sequence = int(update_target.get('sequence') or 0) + (1 if update_target else 0) - return { - 'ok': True, - 'message_id': message_id, - 'card_id': card_id, - 'sequence': sequence, - 'rich': True, - } - - async def send_message(self, target_type: str, target_id: str, message_chain): - self.messages.append((target_type, target_id, message_chain)) - - -@pytest.fixture -async def store(tmp_path): - engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "manager.db"}', echo=False) - async with engine.begin() as conn: - await conn.run_sync(Base.metadata.create_all) - await conn.execute( - sa.insert(LegacyPipeline).values( - uuid='pipeline-1', - workspace_uuid='workspace-1', - name='test', - description='', - for_version='4.11', - stages=[], - config=CONFIG, - extensions_preferences={}, - ) - ) - yield InteractionStore(engine) - await engine.dispose() - - -@pytest.fixture -def event(): - return AgentEventEnvelope( - event_id='evt-1', - event_type='message.received', - source='platform', - bot_id='bot-1', - workspace_id='workspace-1', - conversation_id='group_chat-1', - actor=ActorContext(actor_type='user', actor_id='user-1'), - input=AgentInput(text='start'), - delivery=DeliveryContext( - surface='platform', - reply_target={'target_type': 'group', 'target_id': 'chat-1'}, - ), - ) - - -@pytest.fixture -def binding(): - return AgentBinding( - binding_id='binding-1', - scope=BindingScope(scope_type='agent', scope_id='pipeline-1'), - runner_id='plugin:test/ApprovalRunner/default', - delivery_policy=DeliveryPolicy(enable_interactions=True), - processor_type='pipeline', - processor_id='pipeline-1', - ) - - -def _descriptor(*, permitted: bool = True): - return SimpleNamespace( - id='plugin:test/ApprovalRunner/default', - capabilities=SimpleNamespace(interactions=permitted), - permissions=SimpleNamespace(interactions=['request'] if permitted else []), - ) - - -def _result(): - return { - 'type': 'action.requested', - 'data': { - 'action': 'interaction.requested', - 'target': {'target_type': 'person', 'target_id': 'attacker-selected'}, - 'payload': { - 'interaction_id': 'form-1', - 'kind': 'choice', - 'title': 'Approve request?', - 'actions': [ - {'id': 'approve', 'label': 'Approve', 'style': 'primary'}, - {'id': 'reject', 'label': 'Reject', 'style': 'danger'}, - ], - 'fallback_text': 'Reply approve or reject.', + 'run_id': 'run-1', + 'runner_id': 'plugin:test/Runner/default', + 'runtime_context': {'deadline_at': time.time() + 300}, + 'authorization': { + 'binding_id': 'binding-1', + 'processor_type': 'agent', + 'processor_id': 'agent-1', + 'bot_id': 'bot-1', + 'workspace_id': 'workspace-1', + 'thread_id': None, + 'interactions_enabled': True, + 'interactions_authorized': True, + 'platform_context': { + 'actor': {'actor_id': 'user-1'}, + 'delivery': {'reply_target': {'target_type': 'group', 'target_id': 'chat-1'}}, }, }, } -@pytest.mark.asyncio -async def test_structured_delivery_uses_frozen_target_and_persists_request(store, event, binding): - adapter = FakeAdapter(supports_interactions=True) - manager = InteractionManager(SimpleNamespace(), store=store) - - consumed = await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - - assert consumed is True - assert adapter.actions[0][0] == 'interaction.request' - params = adapter.actions[0][1] - assert params['reply_target'] == {'target_type': 'group', 'target_id': 'chat-1'} - assert params['callback_token'] - assert 'attacker-selected' not in str(params) - - record = await store.get_request('run-1', 'form-1') - assert record is not None - assert record['processor_type'] == 'pipeline' - assert record['processor_id'] == 'pipeline-1' - assert record['actor_id'] == 'user-1' - assert record['expires_at'] is not None - assert 0 < record['expires_at'] - time.time() <= 30 * 60 - assert record['delivery_result']['message_id'] == 'message-1' +def _request(**changes): + return { + 'interaction_id': 'approval', + 'title': 'Approve?', + 'actions': [{'id': 'yes', 'label': 'Yes'}, {'id': 'no', 'label': 'No'}], + **changes, + } -@pytest.mark.asyncio -async def test_continuous_interaction_reuses_submitted_platform_presentation(store, event, binding): - adapter = FakeAdapter(supports_interactions=True) - manager = InteractionManager(SimpleNamespace(), store=store) - event.delivery.interactions = InteractionDeliveryCapabilities(supports_updates=True) +class Adapter: + def __init__(self, native=True): + self.native = native + self.sent = asyncio.Event() + self.token = None + self.updates = [] + self.messages = [] - await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - first_token = adapter.actions[0][1]['callback_token'] - submitted = await manager.consume_callback( - callback_token=first_token, - submission={'interaction_id': 'form-1', 'action_id': 'approve', 'values': {}}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - await manager.acknowledge_submission(submitted, adapter) + def get_supported_apis(self): + return ['send_interaction', 'update_interaction', 'send_message'] if self.native else ['send_message'] - event.event_type = 'interaction.submitted' - event.input.interaction = InteractionSubmission( - interaction_id='form-1', - action_id='approve', - ) - second_result = _result() - second_result['data']['payload']['interaction_id'] = 'form-2' - await manager.handle_result( - result_dict=second_result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-2', - adapter_context=_context(adapter), - ) - - assert [action for action, _ in adapter.actions] == [ - 'interaction.request', - 'interaction.acknowledge', - 'interaction.request', - ] - update_params = adapter.actions[-1][1] - assert update_params['update_target']['message_id'] == 'message-1' - assert update_params['update_target']['sequence'] == 1 - second_record = await store.get_request('run-2', 'form-2') - assert second_record['replaces_interaction_id'] == 'form-1' - assert second_record['delivery_result']['message_id'] == 'message-1' - assert second_record['delivery_result']['sequence'] == 2 - - -@pytest.mark.asyncio -async def test_interaction_update_failure_falls_back_to_new_presentation(store, event, binding): - adapter = FakeAdapter(supports_interactions=True, fail_updates=True) - manager = InteractionManager(SimpleNamespace(), store=store) - event.delivery.interactions = InteractionDeliveryCapabilities(supports_updates=True) - - await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - first_token = adapter.actions[0][1]['callback_token'] - await manager.consume_callback( - callback_token=first_token, - submission={'interaction_id': 'form-1', 'action_id': 'approve', 'values': {}}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - - event.input.interaction = InteractionSubmission(interaction_id='form-1', action_id='approve') - second_result = _result() - second_result['data']['payload']['interaction_id'] = 'form-2' - await manager.handle_result( - result_dict=second_result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-2', - adapter_context=_context(adapter), - ) - - update_attempt = adapter.actions[-2][1] - fallback_attempt = adapter.actions[-1][1] - assert update_attempt['update_target']['message_id'] == 'message-1' - assert 'update_target' not in fallback_attempt - assert fallback_attempt['callback_token'] == update_attempt['callback_token'] - - -@pytest.mark.asyncio -async def test_callback_scope_uses_frozen_delivery_conversation(store, event, binding): - event.conversation_id = 'runner-owned-external-conversation' - adapter = FakeAdapter(supports_interactions=True) - manager = InteractionManager(SimpleNamespace(), store=store) - - await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - - record = await store.get_request('run-1', 'form-1') - assert record['conversation_id'] == 'group_chat-1' - - -@pytest.mark.asyncio -async def test_adapter_without_interactions_receives_fallback_text(store, event, binding): - adapter = FakeAdapter(supports_interactions=False) - manager = InteractionManager(SimpleNamespace(), store=store) - - assert await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - - assert adapter.actions == [] - target_type, target_id, message_chain = adapter.messages[0] - assert (target_type, target_id) == ('group', 'chat-1') - assert str(message_chain) == 'Reply approve or reject.' - - -@pytest.mark.asyncio -async def test_runner_without_interaction_permission_is_rejected(store, event, binding): - manager = InteractionManager(SimpleNamespace(), store=store) - - with pytest.raises(RunnerProtocolError, match='did not declare'): - await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(permitted=False), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), + def get_interaction_capabilities(self): + return InteractionDeliveryCapabilities( + field_types=['text', 'select'] if self.native else [], + action_styles=['default', 'primary'] if self.native else [], + max_fields=8 if self.native else None, + max_actions=6 if self.native else None, + supports_updates=self.native, ) - assert await store.get_request('run-1', 'form-1') is None + async def send_interaction(self, target_type, target_id, request, callback_token, reply_to=None): + self.token = callback_token + self.sent.set() + return InteractionHandle(message_id='card-1') + + async def update_interaction(self, handle, state, submission=None): + self.updates.append(state) + return handle + + async def send_message(self, target_type, target_id, message): + self.messages.append(str(message)) + self.sent.set() -@pytest.mark.asyncio -async def test_binding_policy_can_disable_interactions(store, event, binding): - manager = InteractionManager(SimpleNamespace(), store=store) - binding.delivery_policy.enable_interactions = False +@pytest.fixture +async def store(tmp_path): + engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "interactions.db"}') + async with engine.begin() as connection: + await connection.run_sync(Base.metadata.create_all) + yield InteractionStore(engine) + await engine.dispose() - with pytest.raises(RunnerProtocolError, match='delivery policy'): - await manager.handle_result( - result_dict=_result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), + +async def _start(manager, adapter, *, request=None): + task = asyncio.create_task( + manager.request_interaction( + session=_session(), + adapter=adapter, + request_payload=request or _request(), + timeout=2, + on_unsupported='error', + responders='actor', ) + ) + await asyncio.wait_for(adapter.sent.wait(), 1) + return task + + +def _callback(token, **overrides): + return { + **dict( + callback_token=token, + submission={'action_ref': 0}, + bot_id='bot-1', + conversation_id='group_chat-1', + actor_id='user-1', + ), + **overrides, + } @pytest.mark.asyncio -@pytest.mark.parametrize( - ('expires_at', 'error'), - [ - (lambda now: 0, 'already expired'), - (lambda now: now - 1, 'already expired'), - (lambda now: now + 24 * 60 * 60 + 1, 'exceeds 24 hours'), - ], -) -async def test_interaction_expiry_is_bounded(store, event, binding, expires_at, error): - result = _result() - result['data']['payload']['expires_at'] = expires_at(int(time.time())) +async def test_callback_is_single_use_and_stays_in_same_run(store): + adapter = Adapter() manager = InteractionManager(SimpleNamespace(), store=store) - - with pytest.raises(RunnerProtocolError, match=error): - await manager.handle_result( - result_dict=result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), - ) + task = await _start(manager, adapter) + record = await manager.consume_callback(**_callback(adapter.token, submission={'action_ref': 0, 'action_id': 'no'})) + assert record['run_id'] == 'run-1' + assert manager.wake_waiter(record, 'user-1') + assert (await task)['submission']['action_id'] == 'yes' + assert adapter.updates == ['submitted'] + with pytest.raises(InteractionAlreadySubmittedError): + await manager.consume_callback(**_callback(adapter.token)) @pytest.mark.asyncio -async def test_interaction_rejects_duplicate_protocol_ids(store, event, binding): - result = _result() - result['data']['payload']['actions'].append({'id': 'approve', 'label': 'Approve again'}) +async def test_forged_token_actor_and_conversation_do_not_consume(store): + adapter = Adapter() manager = InteractionManager(SimpleNamespace(), store=store) - - with pytest.raises(RunnerProtocolError, match='duplicate action IDs'): - await manager.handle_result( - result_dict=result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), - ) + task = await _start(manager, adapter) + with pytest.raises(InteractionNotFoundError): + await manager.consume_callback(**_callback('forged')) + for override in ({'actor_id': 'attacker'}, {'conversation_id': 'group-other'}, {'bot_id': 'bot-other'}): + with pytest.raises(InteractionScopeError): + await manager.consume_callback(**_callback(adapter.token, **override)) + assert (await store.get_request('run-1', 'approval'))['status'] == 'pending' + record = await manager.consume_callback(**_callback(adapter.token)) + assert manager.wake_waiter(record, 'user-1') + await task @pytest.mark.asyncio -async def test_interaction_request_payload_is_bounded(store, event, binding): - result = _result() - result['data']['payload']['fields'] = [ - { - 'id': f'field-{field_index}', - 'label': 'Field', - 'type': 'select', - 'options': [ - { - 'value': f'{field_index}-{option_index}', - 'label': 'x' * 512, - } - for option_index in range(100) +async def test_responder_list_rejects_other_actor_before_consuming(store): + adapter = Adapter() + manager = InteractionManager(SimpleNamespace(), store=store) + task = asyncio.create_task( + manager.request_interaction( + session=_session(), + adapter=adapter, + request_payload=_request(), + timeout=2, + on_unsupported='error', + responders=['user-1'], + ) + ) + await asyncio.wait_for(adapter.sent.wait(), 1) + with pytest.raises(ValueError, match='allowed responder'): + await manager.consume_callback(**_callback(adapter.token, actor_id='attacker')) + assert (await store.get_request('run-1', 'approval'))['status'] == 'pending' + record = await manager.consume_callback(**_callback(adapter.token)) + assert manager.wake_waiter(record, 'user-1') + await task + + +@pytest.mark.asyncio +async def test_restart_cancels_pending_and_old_callback_expires(store): + adapter = Adapter() + manager = InteractionManager(SimpleNamespace(), store=store) + task = await _start(manager, adapter) + assert await store.cancel_orphaned_pending(set()) == 1 + assert (await store.get_request('run-1', 'approval'))['status'] == 'cancelled' + with pytest.raises(InteractionExpiredError): + await manager.consume_callback(**_callback(adapter.token)) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +@pytest.mark.asyncio +async def test_timeout_updates_card(store): + adapter = Adapter() + manager = InteractionManager(SimpleNamespace(), store=store) + result = await manager.request_interaction( + session=_session(), + adapter=adapter, + request_payload=_request(), + timeout=0.01, + on_unsupported='error', + responders='actor', + ) + assert result['status'] == 'timeout' + assert adapter.updates == ['expired'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('policy', ['degrade', 'error']) +async def test_multi_field_form_never_splits_into_text_questions(store, policy): + adapter = Adapter(native=False) + manager = InteractionManager(SimpleNamespace(), store=store) + result = await manager.request_interaction( + session=_session(), + adapter=adapter, + request_payload=_request( + actions=[], + fields=[ + {'id': 'first', 'label': 'First', 'type': 'text'}, + {'id': 'second', 'label': 'Second', 'type': 'text'}, ], - } - for field_index in range(10) - ] + ), + timeout=1, + on_unsupported=policy, + responders='actor', + ) + assert result['unsupported'] + assert adapter.messages == [] + + +@pytest.mark.asyncio +async def test_visual_degradation_keeps_native_form(store): + adapter = Adapter() manager = InteractionManager(SimpleNamespace(), store=store) - - with pytest.raises(RunnerProtocolError, match='exceeds 256 KiB'): - await manager.handle_result( - result_dict=result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), - ) - - -@pytest.mark.asyncio -async def test_non_interaction_action_is_not_consumed(store, event, binding): - manager = InteractionManager(SimpleNamespace(), store=store) - result = _result() - result['data']['action'] = 'platform.message.delete' - - assert not await manager.handle_result( - result_dict=result, - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(FakeAdapter(supports_interactions=True)), - ) - - -async def _deliver_interaction(store, event, binding, result=None): - adapter = FakeAdapter(supports_interactions=True) - manager = InteractionManager(SimpleNamespace(), store=store) - await manager.handle_result( - result_dict=result or _result(), - event=event, - binding=binding, - descriptor=_descriptor(), - run_id='run-1', - adapter_context=_context(adapter), - ) - return manager, adapter.actions[0][1]['callback_token'] - - -@pytest.mark.asyncio -async def test_callback_action_ref_resolves_persisted_action_and_ignores_forged_id(store, event, binding): - manager, callback_token = await _deliver_interaction(store, event, binding) - - resumed = await manager.consume_callback( - callback_token=callback_token, - submission={ - 'interaction_id': 'attacker-selected', - 'action_ref': 1, - 'values': {}, - }, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - - assert resumed['submission']['interaction_id'] == 'form-1' - assert resumed['submission']['action_id'] == 'reject' - - -@pytest.mark.asyncio -async def test_callback_submission_time_is_host_owned(store, event, binding): - manager, callback_token = await _deliver_interaction(store, event, binding) - before = int(time.time()) - - resumed = await manager.consume_callback( - callback_token=callback_token, - submission={'action_ref': 0, 'submitted_at': 1}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - - assert before <= resumed['submission']['submitted_at'] <= int(time.time()) - assert resumed['submitted_at'] == resumed['submission']['submitted_at'] - - -@pytest.mark.asyncio -async def test_callback_option_refs_resolve_persisted_field_and_value(store, event, binding): - result = _result() - result['data']['payload']['fields'] = [ - { - 'id': 'priority', - 'label': 'Priority', - 'type': 'select', - 'options': [ - {'value': 'normal', 'label': 'Normal'}, - {'value': 'urgent', 'label': 'Urgent'}, + task = await _start( + manager, + adapter, + request=_request( + actions=[], + fields=[ + {'id': 'name', 'label': 'Name', 'type': 'text', 'placeholder': 'Your name', 'default': 'Alex'}, ], - } - ] - manager, callback_token = await _deliver_interaction(store, event, binding, result) - - resumed = await manager.consume_callback( - callback_token=callback_token, - submission={'field_ref': 0, 'option_ref': 1}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', + ), ) - - assert resumed['submission']['interaction_id'] == 'form-1' - assert resumed['submission']['values'] == {'priority': 'urgent'} + record = await store.get_request('run-1', 'approval') + assert record['request']['fields'][0]['placeholder'] is None + assert record['request']['fields'][0]['default'] is None + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task -@pytest.mark.asyncio -async def test_callback_rejects_out_of_range_reference(store, event, binding): - manager, callback_token = await _deliver_interaction(store, event, binding) - - with pytest.raises(ValueError, match='action reference is invalid'): - await manager.consume_callback( - callback_token=callback_token, - submission={'action_ref': 99}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', +@pytest.mark.parametrize('policy', ['error', 'degrade']) +def test_structural_policy_and_visual_degradation_are_independent(policy): + capabilities = InteractionDeliveryCapabilities( + field_types=['text'], + action_styles=['default'], + max_fields=8, + max_actions=2, + text_fallback=True, + supports_markdown=False, + ) + structural = InteractionRequest.model_validate( + _request( + actions=[], + fields=[{'id': 'count', 'label': 'Count', 'type': 'number'}], ) + ) + _, _, use_text, issues = InteractionManager._normalize_request(structural, capabilities, policy) + if policy == 'error': + assert use_text is False + assert issues == [{'path': 'fields[0].type', 'reason': 'unsupported_field_type'}] + else: + assert use_text is True + assert issues == [] - pending = await store.get_request('run-1', 'form-1') - assert pending is not None - assert pending['status'] == 'pending' - - -@pytest.mark.asyncio -async def test_callback_rejects_negative_reference(store, event, binding): - manager, callback_token = await _deliver_interaction(store, event, binding) - - with pytest.raises(ValueError, match='action reference is invalid'): - await manager.consume_callback( - callback_token=callback_token, - submission={'action_ref': -1}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - - -@pytest.mark.asyncio -async def test_callback_rejects_action_not_present_in_request(store, event, binding): - manager, callback_token = await _deliver_interaction(store, event, binding) - - with pytest.raises(ValueError, match='action is not present'): - await manager.consume_callback( - callback_token=callback_token, - submission={'action_id': 'attacker-selected'}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) - - -@pytest.mark.asyncio -async def test_callback_rejects_option_not_present_in_request(store, event, binding): - result = _result() - result['data']['payload']['fields'] = [ - { - 'id': 'priority', - 'label': 'Priority', - 'type': 'select', - 'options': [{'value': 'normal', 'label': 'Normal'}], - } - ] - manager, callback_token = await _deliver_interaction(store, event, binding, result) - - with pytest.raises(ValueError, match='option is not present'): - await manager.consume_callback( - callback_token=callback_token, - submission={'values': {'priority': 'attacker-selected'}}, - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', + visual = InteractionRequest.model_validate( + _request( + description='**Approve**', + actions=[{'id': 'yes', 'label': 'Yes', 'style': 'primary'}], ) + ) + normalized, degraded, use_text, issues = InteractionManager._normalize_request(visual, capabilities, policy) + assert not use_text and not issues + assert normalized.actions[0].style == 'default' + assert {(item['path'], item['reason']) for item in degraded} == { + ('actions[0].style', 'unsupported_style'), + ('description', 'unsupported_markdown'), + } diff --git a/tests/unit_tests/agent/test_interaction_store.py b/tests/unit_tests/agent/test_interaction_store.py index 4502bd1cb..51357e71d 100644 --- a/tests/unit_tests/agent/test_interaction_store.py +++ b/tests/unit_tests/agent/test_interaction_store.py @@ -139,7 +139,7 @@ async def test_submission_is_scope_checked_and_consumed_once(store): @pytest.mark.asyncio -async def test_delivery_result_can_be_resolved_for_scoped_update(store): +async def test_delivery_result_remains_available_for_callback_update(store): _, token = await _create(store) assert await store.record_delivery_success( 'run-1', @@ -159,16 +159,7 @@ async def test_delivery_result_can_be_resolved_for_scoped_update(store): {'message_id': 'message-1', 'card_id': 'card-1', 'sequence': 1, 'rich': True}, ) - target = await store.find_update_target( - interaction_id='form-1', - binding_id='binding-1', - runner_id='plugin:test/ApprovalRunner/default', - processor_type='pipeline', - processor_id='pipeline-1', - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='user-1', - ) + target = await store.get_by_callback_token(token) assert target['delivery_result'] == { 'message_id': 'message-1', 'card_id': 'card-1', @@ -176,20 +167,6 @@ async def test_delivery_result_can_be_resolved_for_scoped_update(store): 'rich': True, } - assert ( - await store.find_update_target( - interaction_id='form-1', - binding_id='binding-1', - runner_id='plugin:test/ApprovalRunner/default', - processor_type='pipeline', - processor_id='pipeline-1', - bot_id='bot-1', - conversation_id='group_chat-1', - actor_id='other-user', - ) - is None - ) - @pytest.mark.asyncio async def test_scope_mismatch_does_not_consume_request(store): diff --git a/tests/unit_tests/agent/test_invoker_interaction_deadline.py b/tests/unit_tests/agent/test_invoker_interaction_deadline.py new file mode 100644 index 000000000..ec79b3919 --- /dev/null +++ b/tests/unit_tests/agent/test_invoker_interaction_deadline.py @@ -0,0 +1,34 @@ +"""Deadline behavior while a Runner blocks on a Host interaction.""" + +import asyncio +import time +from types import SimpleNamespace + +import pytest + +from langbot.pkg.agent.runner.invoker import RunnerInvoker + + +@pytest.mark.asyncio +async def test_next_result_survives_interaction_deadline_extension(): + gate = asyncio.Event() + context = {'runtime': {'deadline_at': time.time() + 0.02}} + + async def results(): + await gate.wait() + yield {'type': 'run.completed'} + + reader = RunnerInvoker(SimpleNamespace()) + task = asyncio.create_task( + reader._next_with_deadline( + results(), + SimpleNamespace(id='test'), + context, + ) + ) + await asyncio.sleep(0.01) + context['runtime']['deadline_at'] = time.time() + 0.1 + await asyncio.sleep(0.03) + gate.set() + + assert (await task)['type'] == 'run.completed' diff --git a/tests/unit_tests/agent/test_legacy_identity_boundary.py b/tests/unit_tests/agent/test_legacy_identity_boundary.py index 6c963c4ee..ea8997acb 100644 --- a/tests/unit_tests/agent/test_legacy_identity_boundary.py +++ b/tests/unit_tests/agent/test_legacy_identity_boundary.py @@ -13,10 +13,6 @@ from langbot_plugin.entities.io.context import InstallationBinding from langbot.pkg.agent.runner.query_entry_adapter import QueryEntryAdapter from langbot.pkg.agent.runner.context_builder import RunnerContextBuilder from langbot.pkg.agent.runner.host_models import AgentEventEnvelope -from langbot.pkg.agent.runner.interaction_manager import InteractionManager -from langbot.pkg.agent.runner.interaction_store import InteractionStore -from langbot.pkg.entity.persistence.base import Base -from sqlalchemy.ext.asyncio import create_async_engine from tests.unit_tests.agent import test_event_first_protocol as event_fixtures from tests.unit_tests.agent.test_context_validation import TestContextValidation as Helpers from tests.utils.legacy_plugin_contract import load_identity_helper, verified_plugin_root @@ -132,101 +128,6 @@ async def test_provenance_cannot_cross_pipeline(mock_query): assert context['conversation']['session_id'] is None -@pytest.mark.asyncio -@pytest.mark.parametrize('changed', [None, 'workspace_id', 'bot_id', 'processor_id', 'actor_id']) -async def test_resume_uses_persisted_identity_not_new_session(tmp_path, mock_query, changed): - engine = create_async_engine('sqlite+aiosqlite:///:memory:') - async with engine.begin() as conn: - await conn.run_sync(Base.metadata.create_all) - try: - store = InteractionStore(engine) - event = QueryEntryAdapter.query_to_event(mock_query) - context, binding = await build(event, 'DifyAgent') - manager = InteractionManager(SimpleNamespace(), store) - descriptor = Helpers()._make_descriptor() - descriptor.id = binding.runner_id - descriptor.capabilities.interactions = True - descriptor.permissions.interactions = ['request'] - binding.delivery_policy.enable_interactions = True - import sqlalchemy as sa - from langbot.pkg.entity.persistence.pipeline import LegacyPipeline - - config = { - 'ai': {'runner': {'id': binding.runner_id}, 'runner_config': {binding.runner_id: binding.runner_config}} - } - mock_query.pipeline_config = config - conversation = mock_query.session.using_conversation - async with engine.begin() as conn: - await conn.execute( - sa.insert(LegacyPipeline).values( - uuid=binding.processor_id, - workspace_uuid=event.workspace_id, - name='test', - description='', - for_version='4.11', - stages=[], - config=config, - extensions_preferences={}, - ) - ) - adapter = SimpleNamespace( - get_supported_apis=lambda: ['interaction.request'], call_platform_api=AsyncMock(return_value={}) - ) - mock_query.adapter = adapter - await manager.handle_result( - result_dict={ - 'data': { - 'action': 'interaction.requested', - 'payload': {'interaction_id': 'form', 'title': 'Approve', 'fallback_text': 'Approve'}, - } - }, - event=event, - binding=binding, - descriptor=descriptor, - run_id='original', - adapter_context={ - '_delivery_adapter': adapter, - '_query': mock_query, - '_pipeline_expected_config': config, - '_pipeline_conversation': conversation, - }, - ) - token = adapter.call_platform_api.call_args.args[1]['callback_token'] - record = await manager.consume_callback( - callback_token=token, - submission={'interaction_id': 'form', 'values': {}}, - bot_id=event.bot_id, - conversation_id='person_launcher-123', - actor_id='sender-123', - ) - mock_query.variables['_interaction_submission'] = record['submission'] - mock_query.session.launcher_id = 'wrong-new-session' - resumed = QueryEntryAdapter.query_to_event(mock_query) - if changed in ('workspace_id', 'bot_id'): - setattr(resumed, changed, 'other') - elif changed == 'processor_id': - binding.processor_id = 'other' - elif changed == 'actor_id': - resumed.actor.actor_id = 'other' - # A fresh manager/store represents a process restart, not an in-memory cache. - manager = InteractionManager(SimpleNamespace(), InteractionStore(engine)) - await manager.restore_legacy_identity(resumed, binding) - result, _ = await build(resumed, 'DifyAgent') - assert result['conversation']['launcher_id'] == (None if changed else 'launcher-123') - finally: - await engine.dispose() - - -@pytest.mark.asyncio -async def test_tbox_resume_without_persisted_identity_fails_closed(mock_query): - event = QueryEntryAdapter.query_to_event(mock_query) - event.event_type = 'interaction.submitted' - event.legacy_identity = None - context, _ = await build(event, 'TboxAgent', 'legacy-bot') - assert context['conversation']['bot_id'] is None - assert context['runtime']['metadata']['bot_id'] is None - - @pytest.fixture(scope='session') def official_plugin_root(): return verified_plugin_root() diff --git a/tests/unit_tests/agent/test_orchestrator_integration.py b/tests/unit_tests/agent/test_orchestrator_integration.py index e50fc9984..89e0bf379 100644 --- a/tests/unit_tests/agent/test_orchestrator_integration.py +++ b/tests/unit_tests/agent/test_orchestrator_integration.py @@ -17,7 +17,6 @@ from langbot.pkg.agent.runner.query_entry_adapter import QueryEntryAdapter from langbot.pkg.agent.runner.binding_resolver import AgentBindingResolver from langbot.pkg.agent.runner.session_registry import get_session_registry from langbot.pkg.agent.runner.run_ledger_store import RunLedgerStore -from langbot.pkg.agent.runner.interaction_store import InteractionStore from langbot.pkg.agent.runner.persistent_state_store import reset_persistent_state_store from langbot.pkg.api.http.context import ExecutionContext from langbot_plugin.api.entities.builtin.platform import entities as platform_entities @@ -592,84 +591,6 @@ async def test_cancel_active_from_query_marks_other_actor_run_as_denied(clean_ag orchestrator._session_registry.cancel_task.assert_not_awaited() -@pytest.mark.asyncio -async def test_orchestrator_consumes_interaction_request_before_message_output(clean_agent_state): - """Whitelisted interaction actions are delivered and never emitted as messages.""" - db_engine = clean_agent_state - descriptor = make_descriptor() - # The local SDK pin predates this contract; these become typed fields with SDK 0.5.0a3. - descriptor.capabilities.__dict__['interactions'] = True - descriptor.permissions.__dict__['interactions'] = ['request'] - plugin_connector = FakePluginConnector( - results=[ - { - 'type': 'action.requested', - 'data': { - 'action': 'interaction.requested', - 'payload': { - 'interaction_id': 'approval-1', - 'kind': 'choice', - 'title': 'Approve request?', - 'actions': [ - {'id': 'approve', 'label': 'Approve', 'style': 'primary'}, - {'id': 'reject', 'label': 'Reject', 'style': 'danger'}, - ], - 'fallback_text': 'Reply approve or reject.', - }, - }, - }, - { - 'type': 'message.completed', - 'data': {'message': {'role': 'assistant', 'content': 'Waiting for approval'}}, - }, - ] - ) - ap = FakeApplication(plugin_connector, db_engine) - orchestrator = AgentRunOrchestrator(ap, FakeRegistry(descriptor)) - query = make_query() - query.adapter = types.SimpleNamespace( - get_supported_apis=lambda: ['interaction.request'], - call_platform_api=AsyncMock(return_value={'ok': True}), - ) - - import sqlalchemy as sa - from langbot.pkg.entity.persistence.pipeline import LegacyPipeline - - async with db_engine.begin() as conn: - await conn.execute( - sa.insert(LegacyPipeline).values( - uuid=query.pipeline_uuid, - workspace_uuid=TEST_CONTEXT.workspace_uuid, - name='test', - description='', - for_version='4.11', - stages=[], - config=query.pipeline_config, - extensions_preferences={}, - ) - ) - - messages = [message async for message in orchestrator.run_from_query(query)] - - assert [message.content for message in messages] == ['Waiting for approval'] - query.adapter.call_platform_api.assert_awaited_once() - action, params = query.adapter.call_platform_api.await_args.args - assert action == 'interaction.request' - assert params['reply_target'] == { - 'target_type': 'person', - 'target_id': 'user_001', - 'message_id': 'msg_001', - } - assert params['callback_token'] - - run_id = plugin_connector.contexts[0]['run_id'] - request = await InteractionStore(db_engine).get_request(run_id, 'approval-1') - assert request is not None - assert request['status'] == 'pending' - assert request['processor_type'] == 'pipeline' - assert request['processor_id'] == 'pipeline_001' - - @pytest.mark.asyncio async def test_orchestrator_persists_run_ledger(clean_agent_state): """AgentRunOrchestrator records Host-owned run and result events.""" @@ -1180,6 +1101,70 @@ async def test_unconsumed_steering_audit_does_not_persist_pinned_context(clean_a assert pinned_context not in str(event_logs) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('waiting', 'supports_steering', 'target_run_id', 'expected'), + [ + ({'run-1'}, True, 'run-1', True), + (set(), True, 'run-1', False), + ({'run-1'}, False, 'run-1', False), + ({'run-1'}, True, None, False), + ], +) +async def test_platform_event_steering_requires_waiting_run_and_matching_binding( + waiting, + supports_steering, + target_run_id, + expected, +): + event = types.SimpleNamespace( + event_type='message.received', + event_id='event-1', + conversation_id='person-user-1', + bot_id='bot-1', + workspace_id='workspace-test', + thread_id=None, + ) + binding = types.SimpleNamespace(runner_id=RUNNER_ID, binding_id='binding-1') + descriptor = types.SimpleNamespace(id=RUNNER_ID, supports_steering=lambda: supports_steering) + sessions = types.SimpleNamespace( + find_steering_target=AsyncMock(return_value=target_run_id), + enqueue_steering=AsyncMock(return_value=True), + ) + journal = types.SimpleNamespace(write_event_log=AsyncMock(return_value='log-1'), write_user_transcript=AsyncMock()) + orchestrator = types.SimpleNamespace( + interaction_manager=types.SimpleNamespace(waiting_run_ids=lambda: waiting), + registry=types.SimpleNamespace(get=AsyncMock(return_value=descriptor)), + _session_registry=sessions, + _build_steering_item=Mock(return_value={'claimed_at': 1}), + journal=journal, + ap=types.SimpleNamespace(logger=FakeLogger()), + ) + + claimed = await AgentRunOrchestrator.try_claim_steering_from_event( + orchestrator, + event, + binding, + TEST_CONTEXT, + ) + + assert claimed is expected + if waiting and supports_steering: + sessions.find_steering_target.assert_awaited_once_with( + conversation_id='person-user-1', + runner_id=RUNNER_ID, + bot_id='bot-1', + workspace_id='workspace-test', + thread_id=None, + binding_id='binding-1', + eligible_run_ids=waiting, + ) + else: + sessions.find_steering_target.assert_not_awaited() + assert sessions.enqueue_steering.await_count == int(expected) + assert journal.write_event_log.await_count == int(expected) + + @pytest.mark.asyncio async def test_orchestrator_enforces_total_runner_deadline(clean_agent_state): """Test that orchestrator enforces total runner timeout.""" @@ -1429,6 +1414,260 @@ class TestQueryEntrySessionQueryId: mcp_loader.build_resource_context_for_query.assert_awaited_once_with(execution_query) +@pytest.mark.asyncio +@pytest.mark.parametrize('event_type', ['message.received']) +@pytest.mark.parametrize('completed_message', [False, True]) +@pytest.mark.parametrize('reasoning', [False, True]) +async def test_direct_agent_streams_output_to_the_originating_platform( + clean_agent_state, event_type, completed_message, reasoning +): + from langbot.pkg.agent.runner.host_models import ( + AgentBinding, + AgentEventEnvelope, + BindingScope, + DeliveryPolicy, + ResourcePolicy, + StatePolicy, + ) + from langbot_plugin.api.entities.builtin.runner.delivery import DeliveryContext + from langbot_plugin.api.entities.builtin.runner.input import AgentInput + + first_content = 'Checking the requesthello' if reasoning else 'hello' + final_content = 'Checking the requesthello world' if reasoning else 'hello world' + runner_results = [ + { + 'type': 'message.delta', + 'data': { + 'chunk': { + 'role': 'assistant', + 'content': first_content, + 'all_content': first_content, + } + }, + }, + ] + if completed_message: + runner_results.append( + { + 'type': 'message.completed', + 'data': {'message': {'role': 'assistant', 'content': final_content}}, + } + ) + runner_results.append({'type': 'run.completed', 'data': {'finish_reason': 'stop'}}) + connector = FakePluginConnector(results=runner_results) + ap = FakeApplication(connector, clean_agent_state) + orchestrator = AgentRunOrchestrator(ap, FakeRegistry(make_descriptor())) + adapter = types.SimpleNamespace( + is_stream_output_supported=AsyncMock(return_value=True), + create_message_card=AsyncMock(return_value=True), + reply_message_chunk=AsyncMock(), + reply_message=AsyncMock(), + send_message=AsyncMock(), + ) + incoming = platform_events.MessageReceivedEvent( + message_id='message-1', + sender=platform_entities.User(id='user-1'), + chat_type=platform_entities.ChatType.PRIVATE, + chat_id='user-1', + message_chain=platform_message.MessageChain([platform_message.Plain(text='hi')]), + source_platform_object=object(), + ) + event = AgentEventEnvelope( + event_id='event-1', + event_type=event_type, + source='platform', + bot_id='bot_001', + workspace_id=TEST_CONTEXT.workspace_uuid, + conversation_id='person_user-1', + input=AgentInput(text='hi'), + delivery=DeliveryContext( + surface='platform', + reply_target={'target_type': 'person', 'target_id': 'user-1', 'message_id': 'message-1'}, + supports_streaming=event_type == 'message.received', + ), + ) + binding = AgentBinding( + binding_id='binding-1', + scope=BindingScope(scope_type='bot', scope_id='bot_001'), + event_types=[event_type], + runner_id=RUNNER_ID, + resource_policy=ResourcePolicy(), + state_policy=StatePolicy(), + delivery_policy=DeliveryPolicy(enable_streaming=event_type == 'message.received', enable_reply=True), + processor_type='agent', + processor_id='agent-1', + ) + + results = [ + item + async for item in orchestrator.run( + event, + binding, + adapter_context={ + '_delivery_adapter': adapter, + '_platform_event': incoming if event_type == 'message.received' else None, + '_execution_context': TEST_CONTEXT, + }, + ) + ] + + assert [item.content for item in results] == ( + [first_content, final_content] if completed_message else [first_content] + ) + if event_type == 'message.received': + adapter.create_message_card.assert_awaited_once() + chunks = adapter.reply_message_chunk.await_args_list + assert [call.kwargs['bot_message'].all_content for call in chunks] == ( + ['hello', 'hello world'] if completed_message else ['hello', 'hello'] + ) + assert [call.kwargs['is_final'] for call in chunks] == [False, True] + adapter.reply_message.assert_not_awaited() + adapter.send_message.assert_not_awaited() + else: + adapter.create_message_card.assert_not_awaited() + adapter.reply_message_chunk.assert_not_awaited() + adapter.reply_message.assert_not_awaited() + adapter.send_message.assert_awaited_once() + assert adapter.send_message.await_args.args[2][0].text == ('hello world' if completed_message else 'hello') + + +@pytest.mark.asyncio +@pytest.mark.parametrize('tool_name', ['present_interactive_card', 'event_reply']) +async def test_direct_agent_delivers_text_after_card_without_repeating_explicit_reply(clean_agent_state, tool_name): + from langbot.pkg.agent.runner.host_models import ( + AgentBinding, + AgentEventEnvelope, + BindingScope, + DeliveryPolicy, + ResourcePolicy, + StatePolicy, + ) + from langbot_plugin.api.entities.builtin.runner.delivery import DeliveryContext + from langbot_plugin.api.entities.builtin.runner.input import AgentInput + + results = [] + if tool_name == 'present_interactive_card': + results.append({'type': 'message.delta', 'data': {'chunk': {'role': 'assistant', 'content': 'Before'}}}) + else: + results.extend( + [ + { + 'type': 'message.delta', + 'data': {'chunk': {'role': 'assistant', 'content': 'Checking available tools'}}, + }, + { + 'type': 'tool.call.completed', + 'data': {'tool_call_id': 'skill-1', 'tool_name': 'list_skills', 'result': {'skills': []}}, + }, + { + 'type': 'message.delta', + 'data': {'chunk': {'role': 'assistant', 'content': 'Checking available tools'}}, + }, + ] + ) + results.extend( + [ + { + 'type': 'tool.call.started', + 'data': {'tool_call_id': 'call-1', 'tool_name': tool_name, 'parameters': {'text': 'After'}}, + }, + { + 'type': 'tool.call.completed', + 'data': {'tool_call_id': 'call-1', 'tool_name': tool_name, 'result': {'ok': True}, 'error': None}, + }, + ] + ) + if tool_name == 'present_interactive_card': + results.append({'type': 'message.delta', 'data': {'chunk': {'role': 'assistant', 'content': 'BeforeAfter'}}}) + else: + results.append( + { + 'type': 'message.delta', + 'data': {'chunk': {'role': 'assistant', 'content': 'Checking available toolsAfter'}}, + } + ) + results.extend( + [ + {'type': 'message.completed', 'data': {'message': {'role': 'assistant', 'content': 'After'}}}, + {'type': 'run.completed', 'data': {'finish_reason': 'stop'}}, + ] + ) + connector = FakePluginConnector(results=results) + orchestrator = AgentRunOrchestrator(FakeApplication(connector, clean_agent_state), FakeRegistry(make_descriptor())) + adapter = types.SimpleNamespace( + is_stream_output_supported=AsyncMock(return_value=True), + create_message_card=AsyncMock(return_value=True), + reply_message_chunk=AsyncMock(), + reply_message=AsyncMock(), + send_message=AsyncMock(), + ) + incoming = platform_events.MessageReceivedEvent( + message_id='message-1', + sender=platform_entities.User(id='user-1'), + chat_type=platform_entities.ChatType.PRIVATE, + chat_id='user-1', + message_chain=platform_message.MessageChain([platform_message.Plain(text='hi')]), + source_platform_object=object(), + ) + event = AgentEventEnvelope( + event_id='event-1', + event_type='message.received', + source='platform', + bot_id='bot_001', + workspace_id=TEST_CONTEXT.workspace_uuid, + conversation_id='person_user-1', + input=AgentInput(text='hi'), + delivery=DeliveryContext( + surface='platform', + reply_target={'target_type': 'person', 'target_id': 'user-1', 'message_id': 'message-1'}, + supports_streaming=True, + ), + ) + binding = AgentBinding( + binding_id='binding-1', + scope=BindingScope(scope_type='bot', scope_id='bot_001'), + event_types=['message.received'], + runner_id=RUNNER_ID, + resource_policy=ResourcePolicy(), + state_policy=StatePolicy(), + delivery_policy=DeliveryPolicy(enable_streaming=True, enable_reply=True), + processor_type='agent', + processor_id='agent-1', + ) + + _ = [ + item + async for item in orchestrator.run( + event, + binding, + adapter_context={ + '_delivery_adapter': adapter, + '_platform_event': incoming, + '_execution_context': TEST_CONTEXT, + }, + ) + ] + + if tool_name == 'present_interactive_card': + assert adapter.create_message_card.await_count == 2 + chunks = adapter.reply_message_chunk.await_args_list + assert [call.kwargs['bot_message'].all_content for call in chunks] == [ + 'Before', + 'Before', + 'After', + 'After', + ] + assert [call.kwargs['is_final'] for call in chunks] == [False, True, False, True] + assert chunks[0].kwargs['bot_message'].resp_message_id != chunks[2].kwargs['bot_message'].resp_message_id + else: + adapter.create_message_card.assert_not_awaited() + adapter.reply_message_chunk.assert_not_awaited() + + class TestQueryEntryAdapterParams: """Tests for params handling in Query entry adapter.""" diff --git a/tests/unit_tests/agent/test_platform_tools.py b/tests/unit_tests/agent/test_platform_tools.py index 160c9f625..0882414ac 100644 --- a/tests/unit_tests/agent/test_platform_tools.py +++ b/tests/unit_tests/agent/test_platform_tools.py @@ -6,6 +6,7 @@ from langbot_plugin.api.entities.builtin.runner import ( ActorContext, AgentInput, DeliveryContext, + InteractionDeliveryCapabilities, RawEventRef, SubjectContext, ) @@ -16,6 +17,7 @@ from langbot_plugin.api.entities.builtin.platform import events as platform_even from langbot.pkg.agent.runner.host_models import AgentEventEnvelope from langbot.pkg.agent.runner.platform_tools import ( PLATFORM_TOOL_DEFINITIONS, + PRESENT_INTERACTIVE_CARD_TOOL, build_platform_tool_resources, execute_platform_tool, freeze_platform_context, @@ -207,8 +209,8 @@ def test_platform_resources_require_runner_call_permission() -> None: assert capabilities['unavailable_tools'] == [{'name': 'event_reply', 'reason': 'runner_call_permission_missing'}] -def test_interaction_resume_can_reply_only_to_a_frozen_delivery_target() -> None: - event = _event().model_copy(update={'event_type': 'interaction.submitted'}) +def test_message_can_reply_only_to_a_frozen_delivery_target() -> None: + event = _event() names = resolve_agent_platform_tool_names({}, event.event_type) assert 'event_reply' in names resources, _ = build_platform_tool_resources(event, names, ['detail', 'call']) @@ -362,6 +364,135 @@ async def test_event_reply_builds_message_chain_for_the_frozen_target() -> None: assert call.kwargs['message'][0].text == 'hello' +@pytest.mark.asyncio +async def test_event_reply_uses_run_reply_stream_when_available() -> None: + adapter = SimpleNamespace( + get_supported_apis=lambda: ['send_message'], + send_message=AsyncMock(return_value=None), + ) + reply_streams = SimpleNamespace( + adapter=adapter, + apply=AsyncMock(return_value={'status': 'completed', 'delivery': 'streaming'}), + ) + ap = SimpleNamespace( + platform_mgr=SimpleNamespace(get_bot_by_uuid=AsyncMock(return_value=SimpleNamespace(adapter=adapter))) + ) + session = { + 'reply_streams': reply_streams, + 'authorization': { + 'bot_id': 'bot-1', + 'platform_context': freeze_platform_context(_event()), + }, + } + + result = await execute_platform_tool(ap, object(), session, 'event_reply', {'text': 'hello'}) + + request = reply_streams.apply.await_args.args[0] + assert request.operation == 'finish' + assert request.text == 'hello' + assert result == {'status': 'completed', 'delivery': 'streaming'} + adapter.send_message.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_request_interaction_uses_host_interaction_manager() -> None: + adapter = SimpleNamespace(get_supported_apis=lambda: ['send_interaction']) + manager = SimpleNamespace( + request_interaction=AsyncMock( + return_value={'status': 'submitted', 'submission': {'interaction_id': 'card-host-generated'}} + ) + ) + ap = SimpleNamespace( + agent_run_orchestrator=SimpleNamespace(interaction_manager=manager), + platform_mgr=SimpleNamespace(get_bot_by_uuid=AsyncMock(return_value=SimpleNamespace(adapter=adapter))), + ) + event = _event('message.received') + event.delivery.platform_capabilities['supported_apis'].append('send_interaction') + session = { + 'run_id': 'run-1', + 'runner_id': 'plugin:test/Agent/default', + 'authorization': { + 'bot_id': 'bot-1', + 'platform_context': freeze_platform_context(event), + }, + } + + result = await execute_platform_tool( + ap, + object(), + session, + PRESENT_INTERACTIVE_CARD_TOOL, + { + 'kind': 'choice', + 'title': 'Choose deployment environment', + 'fields': [ + { + 'id': 'environment', + 'label': 'Environment', + 'type': 'select', + 'options': [ + {'value': 'staging', 'label': 'Staging'}, + {'value': 'production', 'label': 'Production'}, + ], + } + ], + }, + ) + + assert result == {'status': 'submitted', 'submission': {'interaction_id': 'card-host-generated'}} + payload = manager.request_interaction.await_args.kwargs['request_payload'] + assert payload['interaction_id'].startswith('card-') + assert payload['fallback_text'].startswith('Choose deployment environment') + assert 'callback_token' not in payload + assert manager.request_interaction.await_args.kwargs['session'] is session + assert manager.request_interaction.await_args.kwargs['adapter'] is adapter + assert manager.request_interaction.await_args.kwargs['on_unsupported'] == 'degrade' + + with pytest.raises(ValueError, match='cannot combine fields and actions'): + await execute_platform_tool( + ap, + object(), + session, + PRESENT_INTERACTIVE_CARD_TOOL, + { + 'title': 'Invalid mixed step', + 'fields': [ + { + 'id': 'environment', + 'label': 'Environment', + 'type': 'select', + 'options': [{'value': 'staging', 'label': 'Staging'}], + } + ], + 'actions': [{'id': 'continue', 'label': 'Continue'}], + }, + ) + + +def test_interactive_card_tool_is_automatic_only_for_interactive_message_surfaces() -> None: + selected = resolve_agent_platform_tool_names({}, 'message.received') + assert PRESENT_INTERACTIVE_CARD_TOOL in selected + assert PRESENT_INTERACTIVE_CARD_TOOL not in resolve_agent_platform_tool_names({}, 'group.member_joined') + + +def test_interactive_card_tool_schema_is_narrowed_to_adapter_capabilities() -> None: + event = _event('message.received') + event.delivery.platform_capabilities['supported_apis'].append('send_interaction') + event.delivery.interactions = InteractionDeliveryCapabilities( + field_types=['select'], + action_styles=['default', 'primary'], + supports_updates=True, + max_fields=1, + ) + + resources, _ = build_platform_tool_resources(event, [PRESENT_INTERACTIVE_CARD_TOOL], ['call']) + + parameters = resources[0]['parameters']['properties'] + assert parameters['fields']['maxItems'] == 1 + assert parameters['fields']['items']['properties']['type']['enum'] == ['select'] + assert parameters['actions']['items']['properties']['style']['enum'] == ['default', 'primary'] + + @pytest.mark.asyncio async def test_platform_action_rejects_parameters_outside_the_declared_schema() -> None: adapter = SimpleNamespace( diff --git a/tests/unit_tests/agent/test_reply_stream.py b/tests/unit_tests/agent/test_reply_stream.py index 45490d425..922a361a7 100644 --- a/tests/unit_tests/agent/test_reply_stream.py +++ b/tests/unit_tests/agent/test_reply_stream.py @@ -123,6 +123,82 @@ async def test_sdk_stream_reuses_adapter_or_sends_one_final_message(native, sour await session.close() +async def test_target_streaming_adapter_updates_card_without_source_message(): + session, adapter, _ = make_session(source=False) + adapter.create_message_card_for_target = AsyncMock(return_value=True) + adapter.reply_message_chunk_for_target = AsyncMock() + key = uuid4() + + await session.apply(request(key, text='hello')) + result = await session.apply(request(key, 'finish', 'hello world')) + + assert result['delivery'] == 'streaming' + adapter.create_message_card_for_target.assert_awaited_once_with( + adapter.reply_message_chunk_for_target.await_args.kwargs['message_id'], 'person', 'user-1' + ) + assert [call.kwargs['content'] for call in adapter.reply_message_chunk_for_target.await_args_list] == [ + 'hello', + 'hello world', + ] + assert [call.kwargs['is_final'] for call in adapter.reply_message_chunk_for_target.await_args_list] == [False, True] + adapter.send_message.assert_not_awaited() + await session.close() + + +async def test_non_message_event_buffers_one_final_reply(): + event = SimpleNamespace( + event_type='platform.specific', + delivery=SimpleNamespace( + surface='platform', + platform_capabilities={}, + reply_target={'target_type': 'person', 'target_id': 'user-1'}, + ), + ) + source = events.PlatformSpecificEvent( + type='platform.specific', + adapter_name='wecombot-omni', + action='test.event', + data={'callback_req_id': 'callback-1'}, + ) + adapter = SimpleNamespace( + is_stream_output_supported=AsyncMock(return_value=True), + send_message=AsyncMock(), + ) + session = ReplyStreamSession(event, adapter, source) + key = uuid4() + await session.apply(request(key, text='partial')) + result = await session.apply(request(key, 'finish', 'complete')) + + assert result['delivery'] == 'buffered' + adapter.send_message.assert_awaited_once() + assert adapter.send_message.await_args.args[2][0].text == 'complete' + await session.close() + + +async def test_target_reply_is_sent_as_new_message(): + event = SimpleNamespace( + event_type='message.received', + delivery=SimpleNamespace( + surface='platform', + platform_capabilities={}, + reply_target={'target_type': 'person', 'target_id': 'user-1', 'message_id': 'original-1'}, + ), + ) + adapter = SimpleNamespace( + is_stream_output_supported=AsyncMock(return_value=True), + send_message=AsyncMock(), + ) + session = ReplyStreamSession(event, adapter, source=None) + key = uuid4() + await session.apply(request(key, text='partial')) + result = await session.apply(request(key, 'finish', 'complete')) + + assert result['delivery'] == 'buffered' + adapter.send_message.assert_awaited_once() + assert adapter.send_message.await_args.args[2][0].text == 'complete' + await session.close() + + @pytest.mark.parametrize('native', [True, False]) @pytest.mark.parametrize('error', [RuntimeError, asyncio.CancelledError]) async def test_exception_finalizes_visible_card_without_sending_buffered_partial(native, error): diff --git a/tests/unit_tests/agent/test_resource_builder.py b/tests/unit_tests/agent/test_resource_builder.py index 3273a6293..47de83d6e 100644 --- a/tests/unit_tests/agent/test_resource_builder.py +++ b/tests/unit_tests/agent/test_resource_builder.py @@ -12,7 +12,13 @@ from langbot.pkg.agent.runner.descriptor import RunnerDescriptor from langbot.pkg.agent.runner.binding_resolver import AgentBindingResolver from langbot.pkg.agent.runner.query_entry_adapter import QueryEntryAdapter from langbot.pkg.agent.runner.resource_builder import AgentResourceBuilder -from langbot.pkg.agent.runner.host_models import AgentBinding, AgentEventEnvelope, BindingScope, ResourcePolicy +from langbot.pkg.agent.runner.host_models import ( + AgentBinding, + AgentEventEnvelope, + BindingScope, + DeliveryPolicy, + ResourcePolicy, +) from langbot.pkg.api.http.context import ExecutionContext from langbot.pkg.provider.tools.toolmgr import ToolManager @@ -240,6 +246,65 @@ async def test_platform_tools_are_not_claimed_when_runner_disables_tool_calling( ] +@pytest.mark.asyncio +async def test_pipeline_receives_interactive_card_tool_for_supported_adapter(app): + query = make_query({}) + query.adapter = SimpleNamespace( + get_supported_apis=lambda: ['send_interaction'], + get_interaction_capabilities=lambda: { + 'field_types': ['select'], + 'action_styles': ['default', 'primary', 'danger'], + 'supports_updates': True, + 'max_fields': 10, + }, + ) + + resources = await build_resources( + app, + query, + make_descriptor( + capabilities={'tool_calling': True, 'interactions': True}, + permissions={**FULL_PERMISSIONS, 'interactions': ['request']}, + ), + ) + + assert [tool['tool_name'] for tool in resources['tools']] == ['request_interaction'] + assert resources['platform_capabilities']['authorized_tools'] == ['request_interaction'] + + +@pytest.mark.asyncio +async def test_event_processor_cannot_receive_interactive_card_tool(app): + event = AgentEventEnvelope( + event_id='event-processor-card', + event_type='message.received', + source='platform', + bot_id='bot-1', + input=AgentInput(text='hello'), + delivery=DeliveryContext( + surface='platform', + reply_target={'target_type': 'person', 'target_id': 'user-1'}, + platform_capabilities={'supported_apis': ['send_interaction']}, + ), + ) + binding = AgentBinding( + binding_id='event-processor-binding', + scope=BindingScope(scope_type='global'), + runner_id=RUNNER_ID, + processor_type='event_processor', + resource_policy=ResourcePolicy(allowed_platform_tool_names=['request_interaction']), + delivery_policy=DeliveryPolicy(enable_interactions=True), + ) + + resources = await AgentResourceBuilder(app).build_resources_from_binding( + execution_context=TEST_CONTEXT, + event=event, + binding=binding, + descriptor=make_descriptor(capabilities={'tool_calling': True}), + ) + + assert resources['tools'] == [] + + @pytest.mark.asyncio async def test_build_models_authorizes_rerank_and_llm_refs_from_config(app): """Config-selected model references are projected regardless of method granularity.""" diff --git a/tests/unit_tests/api/service/test_agent_service.py b/tests/unit_tests/api/service/test_agent_service.py index bca8b3a9c..c4375885c 100644 --- a/tests/unit_tests/api/service/test_agent_service.py +++ b/tests/unit_tests/api/service/test_agent_service.py @@ -762,6 +762,7 @@ class TestAgentServiceCreateUpdateDelete: 'name': 'Pipeline Agent', 'description': 'Legacy pipeline', 'emoji': 'P', + 'runner_id': 'plugin:test/runner/default', }, ) await service.update_agent( @@ -779,6 +780,7 @@ class TestAgentServiceCreateUpdateDelete: 'description': 'Legacy pipeline', 'emoji': 'P', }, + runner_id='plugin:test/runner/default', ) app.pipeline_service.update_pipeline.assert_awaited_once_with( WORKSPACE_UUID, diff --git a/tests/unit_tests/api/service/test_pipeline_create_description.py b/tests/unit_tests/api/service/test_pipeline_create_description.py index 7fec6bca1..230e6d801 100644 --- a/tests/unit_tests/api/service/test_pipeline_create_description.py +++ b/tests/unit_tests/api/service/test_pipeline_create_description.py @@ -22,7 +22,7 @@ async def test_create_pipeline_defaults_missing_description(monkeypatch): service = PipelineService.__new__(PipelineService) service.ap = app - async def fake_get_default_config(context): + async def fake_get_default_config(context, runner_id=None): runner_id = 'plugin:langbot-team/LocalAgent/default' return { 'ai': { diff --git a/tests/unit_tests/api/service/test_pipeline_migration_cloud.py b/tests/unit_tests/api/service/test_pipeline_migration_cloud.py index 09fc71ae7..f4c225831 100644 --- a/tests/unit_tests/api/service/test_pipeline_migration_cloud.py +++ b/tests/unit_tests/api/service/test_pipeline_migration_cloud.py @@ -105,17 +105,12 @@ def test_conversation_authority_is_captured_before_runner_returns(): old, new = NS(), NS() config = planner(SOURCE)['config'] - query = NS(pipeline_config=config, pipeline_uuid='one', session=NS(using_conversation=new)) - binding = NS( - processor_type='pipeline', processor_id='one', runner_id=RID, runner_config=config['ai']['runner_config'][RID] - ) - authority = InteractionManager._pipeline_admission( - binding, - NS(id=RID), - { - '_query': query, - '_pipeline_expected_config': copy.deepcopy(config), - '_pipeline_conversation': old, - }, + query = NS(pipeline_config=config, pipeline_uuid='one', session=NS(using_conversation=old)) + authority = InteractionManager._pipeline_tool_admission( + {'execution_query': query}, + {'processor_type': 'pipeline', 'processor_id': 'one'}, + RID, ) + assert authority['authority_check']() is True + query.session.using_conversation = new assert authority['authority_check']() is False diff --git a/tests/unit_tests/api/test_pipeline_service_defaults.py b/tests/unit_tests/api/test_pipeline_service_defaults.py index 20fa685ac..348edfa51 100644 --- a/tests/unit_tests/api/test_pipeline_service_defaults.py +++ b/tests/unit_tests/api/test_pipeline_service_defaults.py @@ -23,6 +23,9 @@ class FakeRegistry: async def list_runners(self, context, bound_plugins=None): return self.runners + async def get(self, context, runner_id): + return next(runner for runner in self.runners if runner.id == runner_id) + def make_runner(runner_id: str, config_schema: list[dict]): parts = runner_id.removeprefix('plugin:').split('/') @@ -67,6 +70,28 @@ async def test_default_pipeline_config_uses_first_installed_runner_schema(): } +@pytest.mark.asyncio +async def test_default_pipeline_config_uses_requested_runner_schema(): + first = make_runner( + 'plugin:alice/custom-agent/default', + [{'name': 'api-key', 'type': 'string', 'default': ''}], + ) + selected = make_runner( + 'plugin:langbot-team/LocalAgent/default', + [{'name': 'temperature', 'type': 'number', 'default': 0.2}], + ) + ap = SimpleNamespace( + logger=FakeLogger(), + runner_registry=FakeRegistry([first, selected]), + ) + ap.llm_model_service = LLMModelsService(ap) + + config = await PipelineService(ap).get_default_pipeline_config('workspace-test', selected.id) + + assert config['ai']['runner']['id'] == selected.id + assert config['ai']['runner_config'] == {selected.id: {'temperature': 0.2}} + + @pytest.mark.asyncio async def test_default_pipeline_config_stays_neutral_without_installed_runners(): ap = SimpleNamespace( diff --git a/tests/unit_tests/pipeline/test_aggregator.py b/tests/unit_tests/pipeline/test_aggregator.py index 274c6b523..f9bc74631 100644 --- a/tests/unit_tests/pipeline/test_aggregator.py +++ b/tests/unit_tests/pipeline/test_aggregator.py @@ -560,14 +560,12 @@ class TestMessageAggregatorAddMessage: message_chain=chain, adapter=mock_adapter(), pipeline_uuid='test-pipeline', - variables={'_interaction_submission': {'interaction_id': 'form-1'}}, + variables={'test_marker': {'interaction_id': 'form-1'}}, ) assert agg.buffers == {} app.query_pool.add_query.assert_awaited_once() - assert app.query_pool.add_query.call_args.kwargs['variables'] == { - '_interaction_submission': {'interaction_id': 'form-1'} - } + assert app.query_pool.add_query.call_args.kwargs['variables'] == {'test_marker': {'interaction_id': 'form-1'}} @pytest.mark.asyncio async def test_max_buffer_flushes_immediately(self): diff --git a/tests/unit_tests/pipeline/test_pool.py b/tests/unit_tests/pipeline/test_pool.py index ffd237606..364664156 100644 --- a/tests/unit_tests/pipeline/test_pool.py +++ b/tests/unit_tests/pipeline/test_pool.py @@ -258,12 +258,12 @@ class TestQueryPoolAddQuery: message_chain=Mock(), adapter=Mock(), routed_by_rule=True, - variables={'_interaction_submission': {'interaction_id': 'form-1'}}, + variables={'test_marker': {'interaction_id': 'form-1'}}, ) variables = MockQuery.call_args.kwargs['variables'] assert variables['_routed_by_rule'] is True - assert variables['_interaction_submission'] == {'interaction_id': 'form-1'} + assert variables['test_marker'] == {'interaction_id': 'form-1'} async def test_add_query_notifier_condition(self): """add_query notifies waiting consumers.""" diff --git a/tests/unit_tests/pipeline/test_resprule.py b/tests/unit_tests/pipeline/test_resprule.py index 7edea001e..4dbb73e5f 100644 --- a/tests/unit_tests/pipeline/test_resprule.py +++ b/tests/unit_tests/pipeline/test_resprule.py @@ -320,13 +320,12 @@ async def test_group_response_rule_configuration( @pytest.mark.asyncio -@pytest.mark.parametrize('callback_key', ['_interaction_submission', '_dify_form_action']) -async def test_interaction_callbacks_do_not_require_another_mention(mock_app, sample_query, callback_key): +async def test_dify_form_action_does_not_require_another_mention(mock_app, sample_query): resprule, entities, _, _ = get_modules() sample_query.launcher_type = provider_session.LauncherTypes.GROUP sample_query.adapter.bot_account_id = '999' submission = {'action_id': 'approve'} - sample_query.variables = {'_routed_by_rule': True, callback_key: submission} + sample_query.variables = {'_routed_by_rule': True, '_dify_form_action': submission} sample_query.message_chain = platform_message.MessageChain([platform_message.Plain(text='[Form Action: Approve]')]) sample_query.pipeline_config = { 'trigger': {'group-respond-rules': {'at': True, 'prefix': ['!bot '], 'regexp': [], 'random': 0}} @@ -338,7 +337,7 @@ async def test_interaction_callbacks_do_not_require_another_mention(mock_app, sa assert result.result_type == entities.ResultType.CONTINUE assert str(result.new_query.message_chain) == '[Form Action: Approve]' - assert result.new_query.variables[callback_key] == submission + assert result.new_query.variables['_dify_form_action'] == submission @pytest.mark.asyncio diff --git a/tests/unit_tests/platform/test_botmgr_execution_trace.py b/tests/unit_tests/platform/test_botmgr_execution_trace.py index f3a523b0d..8c1693361 100644 --- a/tests/unit_tests/platform/test_botmgr_execution_trace.py +++ b/tests/unit_tests/platform/test_botmgr_execution_trace.py @@ -376,29 +376,16 @@ async def test_matched_subscription_keeps_failed_timeout_and_cancelled_execution await counters.shutdown() -@pytest.mark.parametrize('processor', ['agent', 'pipeline', 'invalid', 'expired', 'duplicate']) -async def test_interaction_admission_requires_valid_callback(processor): - from langbot_plugin.api.entities.builtin.platform import events +async def test_interaction_callback_failure_does_not_start_a_traced_run(): + from langbot_plugin.api.entities.builtin.platform.events import InteractionCallbackEvent bot, manager, counters = make_bot([]) - callbacks = SimpleNamespace( - consume_callback=AsyncMock(return_value={'processor_type': processor, 'processor_id': 'target'}), - acknowledge_submission=AsyncMock(), - ) - if processor in {'expired', 'duplicate'}: - callbacks.consume_callback.side_effect = ValueError(processor) + callbacks = SimpleNamespace(consume_callback=AsyncMock(side_effect=RuntimeError('store unavailable'))) bot.ap.agent_run_orchestrator = SimpleNamespace(interaction_manager=callbacks) - bot._resume_agent_interaction = AsyncMock(side_effect=ValueError('target unavailable')) - event = events.PlatformSpecificEvent(platform='test', action='interaction.submitted', data={}) + event = InteractionCallbackEvent(callback_token='token-1', actor_id='user-1') await bot._handle_platform_event(event, FakeAdapter()) - if processor in {'agent', 'pipeline'}: - (chain,) = execution_chains(await flushed_records(counters, manager)) - assert chain['outcome'] == 'failed' - callbacks.acknowledge_submission.assert_awaited_once() - await counters.shutdown() - else: - callbacks.acknowledge_submission.assert_not_awaited() - await assert_no_upload(counters, manager) + callbacks.consume_callback.assert_awaited_once() + await assert_no_upload(counters, manager) async def test_rejected_event_does_not_contaminate_next_matched_event_or_monitoring(): @@ -537,32 +524,17 @@ async def test_retry_of_matched_batch_cannot_include_intervening_unrouted_event( assert counters.dropped == 0 -async def test_valid_interaction_success_keeps_acknowledgement_and_execution(): - from langbot.pkg.telemetry.execution import record - from langbot_plugin.api.entities.builtin.platform import events +async def test_valid_interaction_callback_wakes_waiter_without_new_execution(): + from langbot_plugin.api.entities.builtin.platform.events import InteractionCallbackEvent bot, manager, counters = make_bot([]) - - async def acknowledge(*args): - record(bot.ap, TEST_CONTEXT, family='platform_api', operation='ack', outcome='success') - - async def resume(*args): - record(bot.ap, TEST_CONTEXT, family='runner', operation='execute', outcome='success') - - bot.ap.agent_run_orchestrator = SimpleNamespace( - interaction_manager=SimpleNamespace( - consume_callback=AsyncMock(return_value={'processor_type': 'agent'}), - acknowledge_submission=acknowledge, - ) - ) - bot._resume_agent_interaction = resume - event = events.PlatformSpecificEvent(platform='test', action='interaction.submitted', data={}) + record = {'run_id': 'run-1', 'submission': {'action_id': 'approve'}} + callbacks = SimpleNamespace(consume_callback=AsyncMock(return_value=record), wake_waiter=Mock(return_value=True)) + bot.ap.agent_run_orchestrator = SimpleNamespace(interaction_manager=callbacks) + event = InteractionCallbackEvent(callback_token='token-1', actor_id='user-1') await bot._handle_platform_event(event, FakeAdapter()) - records = await flushed_records(counters, manager) - (chain,) = execution_chains(records) - assert chain['outcome'] == 'success' - assert {node['family'] for node in execution_nodes(records)} == {'platform_event', 'platform_api', 'runner'} - await counters.shutdown() + callbacks.wake_waiter.assert_called_once_with(record, 'user-1', {}) + await assert_no_upload(counters, manager) @pytest.mark.parametrize('channel_id', ['channel-1', 'channel-2']) diff --git a/tests/unit_tests/platform/test_dingtalk_adapter.py b/tests/unit_tests/platform/test_dingtalk_adapter.py index b2974837a..a5fb28382 100644 --- a/tests/unit_tests/platform/test_dingtalk_adapter.py +++ b/tests/unit_tests/platform/test_dingtalk_adapter.py @@ -8,11 +8,11 @@ import pytest from langbot.pkg.platform import botmgr as _botmgr # noqa: F401 from langbot.pkg.platform.sources.dingtalk import ( DingTalkAdapter, + _dingtalk_a2ui_form, _dingtalk_card_markdown, _dingtalk_clean_form_content, _dingtalk_completed_input_lines, _dingtalk_extract_component_inputs, - _dingtalk_form_component_params, _dingtalk_missing_completed_input_lines, _dingtalk_pending_input_defs, ) @@ -29,29 +29,32 @@ def test_dingtalk_auxiliary_tasks_are_bounded(): assert len(adapter._background_tasks) == 100 -def test_dingtalk_select_component_params_expose_options(): - params = _dingtalk_form_component_params( +def test_dingtalk_dify_input_card_uses_a2ui_binding_and_required_check(): + data, components = _dingtalk_a2ui_form( { - '_current_input_field': 'choice', + 'node_title': 'Review', + 'form_content': 'Add a comment', + '_current_input_field': 'comment', 'input_defs': [ { - 'output_variable_name': 'choice', - 'type': 'select', - 'option_source': {'type': 'constant', 'value': ['A', 'B']}, + 'output_variable_name': 'comment', + 'type': 'textarea', + 'label': 'Comment', } ], 'inputs': {}, - } + }, + 'track-id', ) - assert params['select_visible'] == 'true' - assert params['select_placeholder'] == 'choice' - assert params['select_options'] == ['A', 'B'] - assert [option['value'] for option in params['index_o']] == ['A', 'B'] - assert [option['value'] for option in params['test_index']] == ['A', 'B'] - assert params['index_o'][0]['text']['zh_CN'] == 'A' - assert params['index_o'][0]['text']['en_US'] == 'A' - assert params['select_index'] == -1 + field = next(component for component in components if component['component'] == 'TextField') + button = next(component for component in components if component['component'] == 'Button') + assert data['form']['value'] == '' + assert field['value'] == {'path': '/form/value'} + assert button['action']['event']['context']['input'] == {'path': '/form/value'} + assert button['checks'][0]['condition']['call'] == 'required' + assert components[0]['children'][-1] == 'langbot-brand' + assert any(component['id'] == 'langbot-brand-link' for component in components) def test_dingtalk_extract_select_from_builtin_result_dict(): diff --git a/tests/unit_tests/platform/test_dingtalk_api.py b/tests/unit_tests/platform/test_dingtalk_api.py index 12cecff0d..d94d7ef75 100644 --- a/tests/unit_tests/platform/test_dingtalk_api.py +++ b/tests/unit_tests/platform/test_dingtalk_api.py @@ -1,4 +1,4 @@ -"""Tests for DingTalk API payload helpers.""" +"""Tests for DingTalk A2UI API payloads.""" import base64 import json @@ -7,54 +7,14 @@ from unittest.mock import AsyncMock import pytest -from langbot.libs.dingtalk_api.api import DingTalkClient, _stringify_card_param_map -from langbot.pkg.utils import httpclient +from langbot.libs.dingtalk_api.a2ui import create_text_card_messages, update_text_card_messages +from langbot.libs.dingtalk_api.api import DingTalkClient -def test_dingtalk_card_param_map_stringifies_select_component_arrays(): - params = _stringify_card_param_map( - { - 'content': 'Pick one', - 'btns': json.dumps([{'text': 'OK'}], ensure_ascii=False), - 'select_options': ['A', 'B'], - 'index_o': [ - { - 'value': 'A', - 'text': {'zh_CN': 'A', 'en_US': 'A'}, - } - ], - 'test_index': [ - { - 'value': 'A', - 'text': {'zh_CN': 'A', 'en_US': 'A'}, - } - ], - 'select_index': -1, - } - ) - - assert params['content'] == 'Pick one' - assert params['btns'] == '[{"text": "OK"}]' - assert params['select_options'] == '["A", "B"]' - assert json.loads(params['index_o'])[0]['value'] == 'A' - assert json.loads(params['test_index'])[0]['value'] == 'A' - assert params['select_index'] == '-1' - - -def test_dingtalk_card_param_map_stringifies_unregistered_structures(): - params = _stringify_card_param_map({'other': ['A'], 'empty': None}) - - assert params['other'] == '["A"]' - assert params['empty'] == '' - - -async def test_create_card_embeds_layout_config_as_template_parameter(monkeypatch): - response = type('Response', (), {'status_code': 200, 'json': lambda self: {}})() - post = AsyncMock(return_value=response) - +def _client(http_client): @asynccontextmanager async def client_context(): - yield type('HttpClient', (), {'post': post})() + yield http_client client = object.__new__(DingTalkClient) client.access_token = 'access-token' @@ -62,29 +22,136 @@ async def test_create_card_embeds_layout_config_as_template_parameter(monkeypatc client.key = 'client-id' client.logger = None client.check_access_token = AsyncMock(return_value=True) + client.get_access_token = AsyncMock() client._http_client_context = client_context - monkeypatch.setattr(httpclient, 'response_text', AsyncMock(return_value='{}')) + return client - original_params = {'content': 'hello'} - delivered = await client.create_and_deliver_card( - card_template_id='template-id', + +def _response(result=None): + payload = {'success': True, 'result': result or {}} + return type('Response', (), {'status_code': 200, 'json': lambda self: payload})() + + +def test_text_card_keeps_brand_when_content_updates(): + components = create_text_card_messages('surface-id', 'hello')[2]['updateComponents']['components'] + by_id = {component['id']: component for component in components} + + assert by_id['root']['children'] == ['content', 'langbot-brand'] + assert by_id['langbot-brand']['children'] == ['langbot-generated', 'langbot-brand-link'] + assert by_id['langbot-brand']['justify'] == 'spaceBetween' + assert by_id['langbot-generated']['text'] == 'AI-generated' + assert by_id['langbot-generated']['variant'] == 'caption' + assert by_id['langbot-brand-link']['text'] == 'LangBot' + assert by_id['langbot-brand-link']['variant'] == 'caption' + assert by_id['langbot-brand-link']['icon']['url'] == 'https://langbot.app/logo-blue.png' + assert by_id['langbot-brand-link']['onLinkClick']['functionCall'] == { + 'call': 'openUrl', + 'args': {'url': 'https://langbot.app?utm_source=dingtalk&utm_medium=bot_card&utm_campaign=langbot'}, + } + assert update_text_card_messages('surface-id', 'done')[0]['updateDataModel']['path'] == '/content' + + +@pytest.mark.asyncio +async def test_create_card_for_target_uses_robot_a2ui_delivery(): + client = _client(None) + client.create_and_deliver_ai_card = AsyncMock(return_value={}) + + card, track_id = await client.create_and_card_for_target('person', 'user-1') + + assert card == {'surface_id': f'langbot-{track_id}'} + request = client.create_and_deliver_ai_card.await_args.kwargs + assert request['open_space_id'] == 'dtv1.card//im_robot.user-1' + assert request['is_group'] is False + assert request['a2ui_messages'][2]['updateComponents']['components'][0]['children'][-1] == 'langbot-brand' + + +@pytest.mark.asyncio +async def test_create_ai_card_uses_group_robot_delivery_model(): + post = AsyncMock( + return_value=_response( + { + 'outTrackId': 'track-id', + 'deliverResults': [{'spaceType': 'IM_GROUP', 'success': True}], + } + ) + ) + client = _client(type('HttpClient', (), {'post': post})()) + + result = await client.create_and_deliver_ai_card( out_track_id='track-id', - open_space_id='dtv1.card//IM_ROBOT.user-id', - is_group=False, - card_param_map=original_params, - card_data_config={'autoLayout': True}, + open_space_id='dtv1.card//im_group.group-id', + is_group=True, + a2ui_messages=create_text_card_messages('surface-id', 'hello'), + summary='hello', ) - request_body = post.await_args.kwargs['json'] - assert delivered is True - assert request_body['cardData'] == { - 'cardParamMap': { - 'content': 'hello', - 'config': '{"autoLayout": true}', - 'autoLayout': 'true', - } - } - assert original_params == {'content': 'hello'} + request = post.await_args + body = request.kwargs['json'] + assert request.args[0].endswith('/v1.0/card/ai/instances/createAndDeliver') + assert result['outTrackId'] == 'track-id' + assert body['imGroupOpenDeliverModel'] == {'robotCode': 'robot-code'} + assert body['imGroupOpenSpaceModel'] == {'supportForward': False} + assert 'imRobotOpenDeliverModel' not in body + assert 'cardTemplateId' not in body + assert body['protocolVersion'] == '1.0' + assert body['flowStatus'] == 'PROCESSING' + assert all(isinstance(message, str) for message in body['a2uiMessages']) + assert json.loads(body['a2uiMessages'][0])['createSurface']['surfaceId'] == 'surface-id' + + +@pytest.mark.asyncio +async def test_create_ai_card_uses_single_chat_robot_delivery_model(): + post = AsyncMock(return_value=_response({'deliverResults': [{'spaceType': 'IM_ROBOT', 'success': True}]})) + client = _client(type('HttpClient', (), {'post': post})()) + + await client.create_and_deliver_ai_card( + out_track_id='track-id', + open_space_id='dtv1.card//im_robot.user-id', + is_group=False, + a2ui_messages=create_text_card_messages('surface-id'), + ) + + body = post.await_args.kwargs['json'] + assert body['imRobotOpenDeliverModel'] == {'robotCode': 'robot-code'} + assert body['imRobotOpenSpaceModel'] == {'supportForward': False} + assert 'imGroupOpenDeliverModel' not in body + + +@pytest.mark.asyncio +async def test_update_ai_card_uses_a2ui_delta_and_idempotency_key(): + put = AsyncMock(return_value=_response({'outTrackId': 'track-id', 'flowStatus': 'FINISH'})) + client = _client(type('HttpClient', (), {'put': put})()) + + await client.update_ai_card( + out_track_id='track-id', + out_update_id='update-id', + flow_status='FINISH', + a2ui_messages=update_text_card_messages('surface-id', 'done'), + ) + + request = put.await_args + body = request.kwargs['json'] + assert request.args[0].endswith('/v1.0/card/ai/instances/update') + assert body['outTrackId'] == 'track-id' + assert body['outUpdateId'] == 'update-id' + assert body['flowStatus'] == 'FINISH' + assert json.loads(body['a2uiMessages'][0])['updateDataModel']['path'] == '/content' + + +@pytest.mark.asyncio +async def test_create_ai_card_rejects_failed_delivery_result(): + post = AsyncMock( + return_value=_response({'deliverResults': [{'spaceType': 'IM_GROUP', 'success': False, 'errorMsg': 'denied'}]}) + ) + client = _client(type('HttpClient', (), {'post': post})()) + + with pytest.raises(RuntimeError, match='delivery failed'): + await client.create_and_deliver_ai_card( + out_track_id='track-id', + open_space_id='dtv1.card//im_group.group-id', + is_group=True, + a2ui_messages=create_text_card_messages('surface-id'), + ) def _voice_client(): diff --git a/tests/unit_tests/platform/test_dingtalk_eba_adapter.py b/tests/unit_tests/platform/test_dingtalk_eba_adapter.py index 015aa2fe7..d187f04d2 100644 --- a/tests/unit_tests/platform/test_dingtalk_eba_adapter.py +++ b/tests/unit_tests/platform/test_dingtalk_eba_adapter.py @@ -10,7 +10,8 @@ import yaml from langbot.libs.dingtalk_api.api import DingTalkClient from langbot.libs.dingtalk_api.dingtalkevent import DingTalkEvent -from langbot.pkg.platform.adapters.dingtalk.adapter import DingTalkAdapter +from langbot.pkg.agent.runner.interaction_manager import InteractionManager +from langbot.pkg.platform.adapters.dingtalk.adapter import DingTalkAdapter, DingTalkCardCallbackHandler from langbot.pkg.platform.adapters.dingtalk.event_converter import DingTalkEventConverter from langbot.pkg.platform.adapters.dingtalk.message_converter import DingTalkMessageConverter from langbot.pkg.platform.adapters.dingtalk.platform_api import PLATFORM_API_MAP @@ -19,6 +20,48 @@ from langbot_plugin.api.definition.abstract.platform.event_logger import Abstrac from langbot_plugin.api.entities.builtin.platform import entities as platform_entities from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) + + +async def _send_interaction(adapter, params): + target = params['reply_target'] + request = InteractionRequest.model_validate( + { + 'interaction_id': 'test-interaction', + 'title': 'Interaction', + **params['request'], + } + ) + handle = await adapter.send_interaction( + target['target_type'], + target['target_id'], + request, + params['callback_token'], + reply_to=target.get('message_id'), + ) + return handle.model_dump() + + +async def _update_interaction(adapter, params): + target = params['update_target'] + handle = InteractionHandle.model_validate( + { + **target, + 'context': {'request': params['request'], 'callback_context': params.get('callback_context') or {}}, + } + ) + submission = InteractionSubmission.model_validate( + { + 'interaction_id': 'test-interaction', + **params['submission'], + } + ) + updated = await adapter.update_interaction(handle, params.get('state', 'submitted'), submission) + return updated.model_dump() class DummyLogger(AbstractEventLogger): @@ -50,8 +93,10 @@ class DummyDingTalkClient(DingTalkClient): self.get_audio_url = AsyncMock(return_value='data:audio/ogg;base64,AAAA') self.download_image = AsyncMock(return_value='data:image/png;base64,BBBB') self.create_and_card = AsyncMock(return_value=('card', 'card-id')) + self.create_and_card_for_target = AsyncMock(return_value=({'surface_id': 'surface-id'}, 'card-id')) self.send_card_message = AsyncMock() - self.create_and_deliver_card = AsyncMock(return_value=True) + self.create_and_deliver_ai_card = AsyncMock(return_value={}) + self.update_ai_card = AsyncMock(return_value={}) self.start = AsyncMock() self.stop = AsyncMock() @@ -85,9 +130,6 @@ def make_adapter() -> DingTalkAdapter: 'robot_code': 'robot-code', 'markdown_card': True, 'enable-stream-reply': False, - 'card_auto_layout': False, - 'card_template_id': 'template-id', - 'human_input_card_template_id': 'human-input-template-id', } with patch('langbot.pkg.platform.adapters.dingtalk.adapter.DingTalkClient', DummyDingTalkClient): return DingTalkAdapter(config, DummyLogger()) @@ -161,36 +203,6 @@ def test_dingtalk_platform_api_map_matches_manifest(): assert set(PLATFORM_API_MAP) == manifest_actions -def test_dingtalk_human_input_card_template_matches_interaction_contract(): - template_path = ( - pathlib.Path(__file__).parents[3] / 'src' / 'langbot' / 'templates' / 'dingtalk_human_input_card.json' - ) - exported_template = json.loads(template_path.read_text(encoding='utf-8')) - editor_data = json.loads(exported_template['editorData']) - variable_ids = {item['id'] for item in editor_data['variableList']} - serialized_editor = json.dumps(editor_data, ensure_ascii=False) - - assert exported_template['type'] == 'im' - assert exported_template['mode'] == 'card' - assert { - 'content', - 'btns', - 'input_visible', - 'input_title', - 'input_placeholder', - 'input_value', - 'select_visible', - 'select_placeholder', - 'select_options', - 'select_index', - 'index_o', - } <= variable_ids - assert '"componentName": "Input"' in serialized_editor - assert '"componentName": "SelectBlock"' in serialized_editor - assert '__built_in_inputResult__' in serialized_editor - assert '__built_in_selectResult__' in serialized_editor - - @pytest.mark.asyncio async def test_dingtalk_message_converter_maps_outbound_components(): content, at = await DingTalkMessageConverter.yiri2target( @@ -349,11 +361,25 @@ async def test_dingtalk_send_reply_and_platform_api_use_underlying_client(): assert file_url == {'url': 'https://example.test/file'} +@pytest.mark.asyncio +async def test_dingtalk_target_reply_stream_updates_one_card(): + adapter = make_adapter() + + assert await adapter.create_message_card_for_target('reply-id', 'person', 'user-1') is True + await adapter.reply_message_chunk_for_target(message_id='reply-id', content='hello', is_final=False) + await adapter.reply_message_chunk_for_target(message_id='reply-id', content='hello world', is_final=True) + + adapter.bot.create_and_card_for_target.assert_awaited_once_with('person', 'user-1') + assert [call.args[2] for call in adapter.bot.send_card_message.await_args_list] == ['hello', 'hello world'] + assert [call.args[3] for call in adapter.bot.send_card_message.await_args_list] == [False, True] + assert 'reply-id' not in adapter.card_instance_id_dict + + @pytest.mark.asyncio async def test_dingtalk_interaction_delivery_and_callback_event(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'group', 'target_id': 'group-1'}, @@ -367,27 +393,31 @@ async def test_dingtalk_interaction_delivery_and_callback_event(): ) assert result['rich'] is True - kwargs = adapter.bot.create_and_deliver_card.await_args.kwargs - assert kwargs['card_template_id'] == 'human-input-template-id' - assert kwargs['open_space_id'] == 'dtv1.card//IM_GROUP.group-1' - assert kwargs['card_param_map']['btns'][0]['event']['params']['actionId'] == 'lbi:callback-token:a:0' + kwargs = adapter.bot.create_and_deliver_ai_card.await_args.kwargs + assert kwargs['open_space_id'] == 'dtv1.card//im_group.group-1' + assert kwargs['flow_status'] == 'CONFIRMING' + components = kwargs['a2ui_messages'][2]['updateComponents']['components'] + button = next(component for component in components if component['component'] == 'Button') + assert button['action']['event']['context']['actionId'] == 'lbi:callback-token:a:0' + assert components[0]['children'][-1] == 'langbot-brand' + assert any(component['id'] == 'langbot-brand-link' for component in components) native = dingtalk_card_callback_event( content={'actionId': 'lbi:callback-token:a:0'}, space_id='dtv1.card//IM_GROUP.group-1', ) event = interaction_event_from_native(native) - assert event.action == 'interaction.submitted' - assert event.data['action_ref'] == 0 - assert event.data['actor_id'] == 'user-1' - assert event.data['target_id'] == 'group-1' + assert isinstance(event, platform_events.InteractionCallbackEvent) + assert event.raw_submission['action_ref'] == 0 + assert event.actor_id == 'user-1' + assert event.target_id == 'group-1' @pytest.mark.asyncio async def test_dingtalk_native_input_uses_template_variables_and_submits_value(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'group', 'target_id': 'group-1'}, @@ -409,33 +439,47 @@ async def test_dingtalk_native_input_uses_template_variables_and_submits_value() }, ) - params = adapter.bot.create_and_deliver_card.await_args.kwargs['card_param_map'] - assert params['input_visible'] == 'true' - assert params['input_title'] == 'Comment' - assert params['input_placeholder'] == 'Explain the decision' - assert params['select_visible'] == '' - assert params['btns'] == [] + kwargs = adapter.bot.create_and_deliver_ai_card.await_args.kwargs + components = kwargs['a2ui_messages'][2]['updateComponents']['components'] + field = next(component for component in components if component['component'] == 'TextField') + button = next(component for component in components if component['component'] == 'Button') + assert field['label'] == 'Comment' + assert field['placeholder'] == 'Explain the decision' + assert field['variant'] == 'longText' + assert button['checks'] == [ + { + 'condition': {'call': 'required', 'args': {'value': {'path': '/form/comment'}}}, + 'message': 'Comment is required', + } + ] assert result['message_id'] in adapter.interaction_callback_contexts native = dingtalk_card_callback_event( content={ - 'outTrackId': result['message_id'], - 'params': {'input': 'Looks good'}, + 'actionData': { + 'a2uiAction': { + 'context': { + 'actionId': 'lbi:callback-token:f:0', + 'values': {'comment': 'Looks good'}, + } + } + } }, - space_id='dtv1.card//IM_GROUP.group-1', + card_instance_id=result['message_id'], + space_id='dtv1.card//im_group.group-1', ) event = interaction_event_from_native(native, adapter.interaction_callback_contexts) - assert event.data['callback_token'] == 'callback-token' - assert event.data['values'] == {'comment': 'Looks good'} - assert result['message_id'] not in adapter.interaction_callback_contexts + assert event.callback_token == 'callback-token' + assert event.values == {'comment': 'Looks good'} + assert result['message_id'] in adapter.interaction_callback_contexts @pytest.mark.asyncio async def test_dingtalk_native_select_uses_select_block_and_normalizes_callback(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, @@ -459,23 +503,279 @@ async def test_dingtalk_native_select_uses_select_block_and_normalizes_callback( }, ) - params = adapter.bot.create_and_deliver_card.await_args.kwargs['card_param_map'] - assert params['select_visible'] == 'true' - assert [option['value'] for option in params['index_o']] == ['normal', 'urgent'] - assert params['input_visible'] == '' + kwargs = adapter.bot.create_and_deliver_ai_card.await_args.kwargs + components = kwargs['a2ui_messages'][2]['updateComponents']['components'] + field = next(component for component in components if component['component'] == 'ChoicePicker') + assert field['displayStyle'] == 'dropdown' + assert [option['value'] for option in field['options']] == ['normal', 'urgent'] native = dingtalk_card_callback_event( content={ - 'out_track_id': result['message_id'], - 'params': {'select': '{"index": 1, "value": "urgent"}'}, + 'actionData': { + 'a2uiAction': { + 'context': { + 'actionId': 'lbi:callback-token:f:0', + 'values': {'priority': ['urgent']}, + } + } + } }, - space_id='dtv1.card//IM_ROBOT.user-1', + card_instance_id=result['message_id'], + space_id='dtv1.card//im_robot.user-1', ) event = interaction_event_from_native(native, adapter.interaction_callback_contexts) - assert event.data['target_type'] == 'person' - assert event.data['target_id'] == 'user-1' - assert event.data['values'] == {'priority': 'urgent'} + assert event.target_type == 'person' + assert event.target_id == 'user-1' + assert event.values == {'priority': 'urgent'} + assert 'field_ref' not in event.raw_submission + resolved = InteractionManager._resolve_submission_refs( + { + 'interaction_id': 'form-1', + 'request': { + 'fields': [ + {'id': 'priority', 'type': 'select', 'options': [{'value': 'urgent'}]}, + ] + }, + }, + {'values': event.values}, + ) + assert resolved['values'] == {'priority': 'urgent'} + + +@pytest.mark.asyncio +async def test_dingtalk_stream_callback_submits_dropdown_without_space_id(): + adapter = make_adapter() + received = [] + + async def listener(event, _adapter): + received.append(event) + + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) + result = await _send_interaction( + adapter, + { + 'callback_token': 'callback-token', + 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, + 'request': { + 'title': 'Priority', + 'fields': [ + { + 'id': 'priority', + 'label': 'Priority', + 'type': 'select', + 'options': [{'value': 'urgent', 'label': 'Urgent'}], + } + ], + }, + }, + ) + raw_callback = { + 'outTrackId': result['message_id'], + 'userId': 'user-1', + 'corpId': 'corp-1', + 'extension': '{}', + 'content': json.dumps( + { + 'actionData': { + 'a2uiAction': { + 'context': { + 'actionId': 'lbi:callback-token:f:0', + 'values': {'priority': ['urgent']}, + } + } + } + } + ), + } + + await DingTalkCardCallbackHandler(adapter).process( + SimpleNamespace(data=raw_callback, headers=SimpleNamespace(time=1_714_000_000_000)) + ) + + assert len(received) == 1 + assert isinstance(received[0], platform_events.InteractionCallbackEvent) + assert received[0].target_type == 'person' + assert received[0].target_id == 'user-1' + assert received[0].values == {'priority': 'urgent'} + assert result['message_id'] in adapter.interaction_callback_contexts + + +@pytest.mark.asyncio +async def test_dingtalk_stream_callback_accepts_object_content_and_retries_unparsed_action(): + adapter = make_adapter() + received = [] + + async def listener(event, _adapter): + received.append(event) + + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) + result = await _send_interaction( + adapter, + { + 'callback_token': 'callback-token', + 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, + 'request': { + 'fields': [ + { + 'id': 'priority', + 'label': 'Priority', + 'type': 'select', + 'options': [{'value': 'urgent', 'label': 'Urgent'}], + } + ] + }, + }, + ) + raw = { + 'outTrackId': result['message_id'], + 'userId': 'user-1', + 'content': { + 'actionData': { + 'a2uiAction': { + 'context': { + 'actionId': 'lbi:callback-token:f:0', + 'values': {'priority': ['urgent']}, + } + } + } + }, + } + handler = DingTalkCardCallbackHandler(adapter) + message = SimpleNamespace(data=raw, headers=SimpleNamespace(time=1_714_000_000_000)) + + assert (await handler.process(message))[0] == 200 + assert received[0].values == {'priority': 'urgent'} + raw['content'] = {'actionData': {'unexpected': True}} + assert (await handler.process(message))[0] == 500 + + +@pytest.mark.asyncio +async def test_dingtalk_expired_interaction_updates_read_only_card(): + adapter = make_adapter() + result = await _update_interaction( + adapter, + { + 'state': 'expired', + 'request': {'title': 'Approve?', 'actions': [{'id': 'approve', 'label': 'Approve'}]}, + 'submission': {}, + 'update_target': {'message_id': 'existing-track-id', 'rich': True}, + }, + ) + components = adapter.bot.update_ai_card.await_args.kwargs['a2ui_messages'][1]['updateComponents']['components'] + assert result['message_id'] == 'existing-track-id' + assert any(component.get('text') == '\u2705 Expired' for component in components) + assert not any(component['component'] == 'Button' for component in components) + + +@pytest.mark.asyncio +async def test_dingtalk_acknowledgement_shows_text_selection_and_clicked_button(): + adapter = make_adapter() + assert 'update_interaction' in adapter.get_supported_apis() + result = await _update_interaction( + adapter, + { + 'request': { + 'title': 'Review', + 'fields': [ + {'id': 'reason', 'label': 'Reason', 'type': 'text'}, + { + 'id': 'priority', + 'label': 'Priority', + 'type': 'select', + 'options': [{'value': 'urgent', 'label': 'Urgent'}], + }, + ], + 'actions': [{'id': 'approve', 'label': 'Approve'}], + }, + 'submission': {'values': {'reason': 'Looks good', 'priority': 'urgent'}, 'action_id': 'approve'}, + 'update_target': {'message_id': 'card-1', 'rich': True}, + }, + ) + + kwargs = adapter.bot.update_ai_card.await_args.kwargs + assert kwargs['out_track_id'] == 'card-1' + assert kwargs['flow_status'] == 'CONFIRMED' + components = kwargs['a2ui_messages'][1]['updateComponents']['components'] + assert [ + component['text'] + for component in components + if component['component'] == 'Text' and component['id'].startswith('submitted-') + ] == [ + '\u2705 Reason: Looks good', + '\u2705 Priority: Urgent', + '\u2705 Approve', + ] + assert not any(component['component'] in {'Button', 'TextField', 'ChoicePicker'} for component in components) + assert result['submitted_values'] == [ + {'label': 'Reason', 'value': 'Looks good'}, + {'label': 'Priority', 'value': 'Urgent'}, + {'label': '', 'value': 'Approve'}, + ] + + +@pytest.mark.asyncio +async def test_dingtalk_field_submit_shows_entered_value_without_submit_action(): + adapter = make_adapter() + await _update_interaction( + adapter, + { + 'request': { + 'description': 'Please enter your question', + 'fields': [{'id': 'question', 'label': 'Question', 'type': 'textarea'}], + }, + 'submission': {'values': {'question': 'What happened?'}}, + 'update_target': {'message_id': 'card-2', 'rich': True}, + }, + ) + components = adapter.bot.update_ai_card.await_args.kwargs['a2ui_messages'][1]['updateComponents']['components'] + assert [component['text'] for component in components if component['id'].startswith('submitted-')] == [ + 'Please enter your question', + '\u2705 Question: What happened?', + ] + + +@pytest.mark.asyncio +async def test_dingtalk_button_submit_preserves_its_prompt(): + adapter = make_adapter() + result = await _update_interaction( + adapter, + { + 'request': { + 'title': 'Human input', + 'description': 'Choose how to proceed', + 'actions': [{'id': 'continue', 'label': 'Continue'}], + }, + 'submission': {'action_id': 'continue', 'values': {}}, + 'update_target': {'message_id': 'card-3', 'rich': True}, + }, + ) + components = adapter.bot.update_ai_card.await_args.kwargs['a2ui_messages'][1]['updateComponents']['components'] + assert [component['text'] for component in components if component['id'].startswith('submitted-')] == [ + 'Choose how to proceed', + '\u2705 Continue', + ] + assert result['submitted_values'] == [ + {'label': '', 'value': 'Continue', 'description': 'Choose how to proceed'}, + ] + + +def test_dingtalk_stale_callback_does_not_consume_replacement_context(): + contexts = { + 'card-1': { + 'callback_token': 'new-token', + 'field_types': {}, + 'expires_at': float('inf'), + } + } + native = dingtalk_card_callback_event( + content={'actionId': 'lbi:old-token:a:0'}, + card_instance_id='card-1', + space_id='dtv1.card//im_group.group-1', + ) + + assert interaction_event_from_native(native, contexts) is None + assert contexts['card-1']['callback_token'] == 'new-token' @pytest.mark.asyncio @@ -486,9 +786,9 @@ async def test_dingtalk_adapter_dispatches_native_input_submission(): async def listener(event, adapter): calls.append(event) - adapter.register_listener(platform_events.PlatformSpecificEvent, listener) - result = await adapter.call_platform_api( - 'interaction.request', + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'group', 'target_id': 'group-1'}, @@ -509,19 +809,26 @@ async def test_dingtalk_adapter_dispatches_native_input_submission(): ) native = dingtalk_card_callback_event( content={ - 'outTrackId': result['message_id'], - 'params': {'inputResult': '42.5'}, + 'actionData': { + 'a2uiAction': { + 'context': { + 'actionId': 'lbi:callback-token:f:0', + 'values': {'score': 42.5}, + } + } + } }, - space_id='dtv1.card//IM_GROUP.group-1', + card_instance_id=result['message_id'], + space_id='dtv1.card//im_group.group-1', ) await adapter._handle_native_event(native) assert len(calls) == 1 - assert calls[0].action == 'interaction.submitted' - assert calls[0].data['callback_token'] == 'callback-token' - assert calls[0].data['values'] == {'score': 42.5} - assert result['message_id'] not in adapter.interaction_callback_contexts + assert isinstance(calls[0], platform_events.InteractionCallbackEvent) + assert calls[0].callback_token == 'callback-token' + assert calls[0].values == {'score': 42.5} + assert result['message_id'] in adapter.interaction_callback_contexts def test_dingtalk_subscription_member_and_group_mapping(): diff --git a/tests/unit_tests/platform/test_discord_eba_adapter.py b/tests/unit_tests/platform/test_discord_eba_adapter.py index db86c1d21..a84fc92cb 100644 --- a/tests/unit_tests/platform/test_discord_eba_adapter.py +++ b/tests/unit_tests/platform/test_discord_eba_adapter.py @@ -22,6 +22,7 @@ from langbot_plugin.api.definition.abstract.platform.event_logger import Abstrac from langbot_plugin.api.entities.builtin.platform import entities as platform_entities from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import InteractionRequest, InteractionHandle class DummyLogger(AbstractEventLogger): @@ -88,7 +89,7 @@ def test_discord_interaction_custom_id_parser_uses_host_indexes(): @pytest.mark.asyncio async def test_discord_interaction_view_and_delivery(): adapter = make_adapter() - channel = SimpleNamespace(send=AsyncMock(return_value=SimpleNamespace(id=321))) + channel = SimpleNamespace(id=789, send=AsyncMock(return_value=SimpleNamespace(id=321))) adapter._get_channel = AsyncMock(return_value=channel) request = { 'interaction_id': 'form-1', @@ -100,19 +101,54 @@ async def test_discord_interaction_view_and_delivery(): view = build_interaction_view(request, 'callback-token') assert view.children[0].custom_id == 'lbi:callback-token:a:0' - result = await adapter.call_platform_api( - 'interaction.request', - { - 'request': request, - 'callback_token': 'callback-token', - 'reply_target': {'target_type': 'group', 'target_id': '789'}, - }, + result = await adapter.send_interaction( + 'group', '789', InteractionRequest.model_validate(request), 'callback-token' ) - assert result == {'ok': True, 'message_id': 321, 'rich': True} + assert isinstance(result, InteractionHandle) + assert result.message_id == 321 and result.rich is True + assert result.context['channel_id'] == '789' assert channel.send.await_args.kwargs['view'].children[0].label == 'Approve' +@pytest.mark.asyncio +async def test_discord_guild_interaction_targets_the_originating_channel(): + adapter = make_adapter() + channel = SimpleNamespace(id=555, send=AsyncMock(return_value=SimpleNamespace(id=321))) + adapter._get_channel = AsyncMock(return_value=channel) + adapter._remember_message_channel(SimpleNamespace(id=42, channel=SimpleNamespace(id=555))) + request = InteractionRequest.model_validate( + {'interaction_id': 'form-1', 'title': 'Approve?', 'actions': [{'id': 'approve', 'label': 'Approve'}]} + ) + + # Pipeline group conversations are keyed by guild id; the card must go to the message's channel. + result = await adapter.send_interaction('group', '1558675416288333856', request, 'callback-token', reply_to='42') + + adapter._get_channel.assert_awaited_once_with(555) + assert result.context['channel_id'] == '555' + assert result.context['target_id'] == '1558675416288333856' + + message = SimpleNamespace(edit=AsyncMock()) + channel.fetch_message = AsyncMock(return_value=message) + adapter._get_channel.reset_mock() + await adapter.update_interaction(result, 'submitted') + adapter._get_channel.assert_awaited_once_with('555') + message.edit.assert_awaited_once_with(content='Approve?\n\nSubmitted', view=None) + + # The click happens in the channel, but the Host recorded the guild conversation. + interaction = SimpleNamespace( + user=SimpleNamespace(id=7), + channel=SimpleNamespace(id=555), + guild=SimpleNamespace(id=1558675416288333856), + message=SimpleNamespace(id=321), + ) + event = interaction_event_from_component( + interaction, {'callback_token': 'callback-token', 'action_ref': 0}, adapter._interaction_targets.get('321') + ) + assert (event.target_type, event.target_id) == ('group', '1558675416288333856') + assert event.callback_context == {'channel_id': '555'} + + def test_discord_interaction_component_builds_scoped_host_event(): interaction = SimpleNamespace( user=SimpleNamespace(id=123), @@ -125,10 +161,31 @@ def test_discord_interaction_component_builds_scoped_host_event(): {'callback_token': 'callback-token', 'action_ref': 0}, ) - assert event.action == 'interaction.submitted' - assert event.data['actor_id'] == '123' - assert event.data['target_type'] == 'group' - assert event.data['target_id'] == '789' + assert isinstance(event, platform_events.InteractionCallbackEvent) + assert event.actor_id == '123' + assert event.target_type == 'group' + assert event.target_id == '789' + + +@pytest.mark.asyncio +async def test_discord_update_interaction_removes_components(): + adapter = make_adapter() + message = SimpleNamespace(edit=AsyncMock()) + channel = SimpleNamespace(fetch_message=AsyncMock(return_value=message)) + adapter._get_channel = AsyncMock(return_value=channel) + handle = InteractionHandle( + message_id=321, + context={ + 'target_id': '789', + 'request': {'title': 'Approve?'}, + }, + ) + + assert 'update_interaction' in adapter.get_supported_apis() + await adapter.update_interaction(handle, 'cancelled') + + channel.fetch_message.assert_awaited_once_with(321) + message.edit.assert_awaited_once_with(content='Approve?\n\nCancelled', view=None) @pytest.mark.asyncio diff --git a/tests/unit_tests/platform/test_lark_eba_adapter.py b/tests/unit_tests/platform/test_lark_eba_adapter.py index fc07b24f8..2aa44f36b 100644 --- a/tests/unit_tests/platform/test_lark_eba_adapter.py +++ b/tests/unit_tests/platform/test_lark_eba_adapter.py @@ -7,6 +7,7 @@ import asyncio import time from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch +from uuid import uuid4 import pytest import yaml @@ -20,10 +21,51 @@ from langbot.pkg.platform.adapters.lark.interaction import ( interaction_delivery_capabilities, interaction_event_from_callback, ) +from langbot.pkg.agent.runner.reply_stream import ReplyStreamRequest, ReplyStreamSession from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger from langbot_plugin.api.entities.builtin.platform import entities as platform_entities from langbot_plugin.api.entities.builtin.platform import events as platform_events from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.runner.interaction import ( + InteractionHandle, + InteractionRequest, + InteractionSubmission, +) + + +async def _send_interaction(adapter, params): + target = params['reply_target'] + request = InteractionRequest.model_validate( + { + 'interaction_id': 'test-interaction', + 'title': 'Interaction', + **params['request'], + } + ) + handle = await adapter.send_interaction( + target['target_type'], + target['target_id'], + request, + params['callback_token'], + reply_to=target.get('message_id'), + ) + return handle.model_dump() + + +async def _update_interaction(adapter, params): + handle = InteractionHandle.model_validate( + { + **params['update_target'], + 'context': {'request': params['request']}, + } + ) + submission = InteractionSubmission.model_validate( + { + 'interaction_id': 'test-interaction', + **params['submission'], + } + ) + return (await adapter.update_interaction(handle, params.get('state', 'submitted'), submission)).model_dump() class DummyLogger(AbstractEventLogger): @@ -469,8 +511,8 @@ def test_lark_interaction_card_uses_native_select_and_declares_fields(): async def test_lark_interaction_request_sends_interactive_message(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, @@ -493,53 +535,36 @@ async def test_lark_interaction_request_sends_interactive_message(): @pytest.mark.asyncio -async def test_lark_interaction_request_updates_existing_message(): +async def test_lark_expired_interaction_updates_existing_card(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _update_interaction( + adapter, { - 'callback_token': 'next-token', - 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, - 'update_target': { - 'message_id': 'card-message-1', - 'card_id': 'card-id', - 'sequence': 0, - 'rich': True, - }, - 'request': { - 'interaction_id': 'form-2', - 'title': 'Choose action', - 'actions': [{'id': 'approve', 'label': 'Approve'}], - 'fallback_text': 'Reply approve.', - }, + 'state': 'expired', + 'update_target': {'message_id': 'card-message-1', 'card_id': 'card-id', 'sequence': 0, 'rich': True}, + 'request': {'title': 'Choose action', 'actions': [{'id': 'approve', 'label': 'Approve'}]}, + 'submission': {}, }, ) - assert result == { - 'ok': True, - 'message_id': 'card-message-1', - 'card_id': 'card-id', - 'sequence': 1, - 'rich': True, - 'updated': True, - } + assert result['message_id'] == 'card-message-1' + assert result['sequence'] == 1 adapter.api_client.im.v1.message.acreate.assert_not_awaited() update_request = adapter.api_client.cardkit.v1.card.aupdate.await_args.args[0] assert update_request.card_id == 'card-id' assert update_request.request_body.sequence == 1 card = json.loads(update_request.request_body.card.data) assert card['header']['title']['content'] == 'Choose action' - button = card['body']['elements'][-1]['columns'][0]['elements'][0] - assert button['behaviors'][0]['value']['lbi'] == 'next-token' + assert 'Expired' in card['body']['elements'][-1]['content'] @pytest.mark.asyncio async def test_lark_interaction_acknowledge_replaces_controls_with_summary(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.acknowledge', + result = await _update_interaction( + adapter, { 'update_target': { 'message_id': 'card-message-1', @@ -563,7 +588,7 @@ async def test_lark_interaction_acknowledge_replaces_controls_with_summary(): @pytest.mark.asyncio -async def test_lark_interaction_keeps_prior_values_through_next_action_and_final_acknowledgement(): +async def test_lark_interaction_update_keeps_prior_values(): adapter = make_adapter() update_target = { 'message_id': 'card-message-1', @@ -573,30 +598,10 @@ async def test_lark_interaction_keeps_prior_values_through_next_action_and_final 'submitted_values': [{'label': 'Question', 'value': '123'}], } - action_result = await adapter.call_platform_api( - 'interaction.request', + final_result = await _update_interaction( + adapter, { - 'callback_token': 'next-token', - 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, 'update_target': update_target, - 'request': { - 'interaction_id': 'action-1', - 'title': 'Manual review', - 'actions': [{'id': 'or', 'label': 'or'}], - 'fallback_text': 'Reply or.', - }, - }, - ) - - action_update = adapter.api_client.cardkit.v1.card.aupdate.await_args.args[0] - action_card = json.loads(action_update.request_body.card.data) - assert '✅ Question:123' in action_card['body']['elements'][0]['content'] - assert action_result['submitted_values'] == [{'label': 'Question', 'value': '123'}] - - final_result = await adapter.call_platform_api( - 'interaction.acknowledge', - { - 'update_target': action_result, 'request': { 'title': 'Manual review', 'actions': [{'id': 'or', 'label': 'or'}], @@ -729,7 +734,10 @@ async def test_lark_streaming_card_uses_strictly_increasing_sequences(): final_card = json.loads(final_request.request_body.card.data) assert final_card['body']['elements'][0] == {'tag': 'markdown', 'content': 'answer'} assert 'header' not in final_card - assert final_card['body']['elements'][-1]['columns'][1]['elements'][0]['content'] == '[LangBot](https://langbot.app?utm_source=feishu&utm_medium=bot_card&utm_campaign=langbot)' + assert ( + final_card['body']['elements'][-1]['columns'][1]['elements'][0]['content'] + == '[LangBot](https://langbot.app?utm_source=feishu&utm_medium=bot_card&utm_campaign=langbot)' + ) assert not final_card['config'].get('streaming_mode', False) assert 'response-1' not in adapter.card_id_dict assert 'stream-card-1' not in adapter.card_sequence_dict @@ -828,6 +836,43 @@ async def test_lark_streaming_card_falls_back_to_full_card_update_when_stream_cl assert 'stream-card-1' not in adapter.closed_streaming_cards +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('target_type', 'target_id', 'receive_id_type'), + [ + ('person', 'user-1', 'open_id'), + ('group', 'chat-1', 'chat_id'), + ], +) +async def test_lark_hitl_reply_stream_creates_and_updates_new_card(target_type, target_id, receive_id_type): + adapter = make_adapter({'enable-stream-reply': True}) + event = SimpleNamespace( + event_type='message.received', + delivery=SimpleNamespace( + surface='platform', + platform_capabilities={}, + reply_target={'target_type': target_type, 'target_id': target_id, 'message_id': 'interaction-card'}, + ), + ) + session = ReplyStreamSession(event, adapter) + stream_id = uuid4() + + first = await session.apply(ReplyStreamRequest(stream_id=stream_id, operation='update', text='partial')) + final = await session.apply(ReplyStreamRequest(stream_id=stream_id, operation='finish', text='complete')) + + assert first['delivery'] == final['delivery'] == 'streaming' + request = adapter.api_client.im.v1.message.acreate.await_args.args[0] + assert request.receive_id_type == receive_id_type + assert request.request_body.receive_id == target_id + assert request.request_body.msg_type == 'interactive' + assert adapter.api_client.im.v1.message.areply.await_count == 0 + assert adapter.api_client.cardkit.v1.card_element.acontent.await_count == 1 + final_card = json.loads(adapter.api_client.cardkit.v1.card.aupdate.await_args.args[0].request_body.card.data) + assert final_card['body']['elements'][0]['content'] == 'complete' + assert not adapter.card_id_dict + await session.close() + + def test_lark_interaction_callback_builds_scoped_host_event(): callback = SimpleNamespace( event=SimpleNamespace( @@ -839,12 +884,12 @@ def test_lark_interaction_callback_builds_scoped_host_event(): event = interaction_event_from_callback(callback) - assert event.action == 'interaction.submitted' - assert event.data['callback_token'] == 'callback-token' - assert event.data['action_ref'] == 1 - assert event.data['actor_id'] == 'user-1' - assert event.data['target_id'] == 'chat-1' - assert event.data['message_id'] == 'card-message-1' + assert isinstance(event, platform_events.InteractionCallbackEvent) + assert event.callback_token == 'callback-token' + assert event.raw_submission['action_ref'] == 1 + assert event.actor_id == 'user-1' + assert event.target_id == 'chat-1' + assert event.callback_context['message_id'] == 'card-message-1' def test_lark_native_form_callback_submits_typed_field_value(): @@ -866,10 +911,10 @@ def test_lark_native_form_callback_submits_typed_field_value(): event = interaction_event_from_callback(callback) - assert event.data['callback_token'] == 'callback-token' - assert event.data['target_type'] == 'person' - assert event.data['target_id'] == 'user-1' - assert event.data['values'] == {'score': 42.5} + assert event.callback_token == 'callback-token' + assert event.target_type == 'person' + assert event.target_id == 'user-1' + assert event.values == {'score': 42.5} @pytest.mark.asyncio @@ -880,7 +925,7 @@ async def test_lark_webhook_dispatches_native_form_submission(): async def listener(event, adapter): calls.append(event) - adapter.register_listener(platform_events.PlatformSpecificEvent, listener) + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) payload = { 'schema': '2.0', 'header': {'event_type': 'card.action.trigger'}, @@ -906,10 +951,10 @@ async def test_lark_webhook_dispatches_native_form_submission(): assert response['card']['type'] == 'raw' assert response['card']['data']['elements'][0]['text']['content'] == '**Submitted**' assert len(calls) == 1 - assert calls[0].action == 'interaction.submitted' - assert calls[0].data['callback_token'] == 'callback-token' - assert calls[0].data['values'] == {'comment': 'Looks good'} - assert calls[0].data['message_id'] == 'card-message-1' + assert isinstance(calls[0], platform_events.InteractionCallbackEvent) + assert calls[0].callback_token == 'callback-token' + assert calls[0].values == {'comment': 'Looks good'} + assert calls[0].callback_context['message_id'] == 'card-message-1' @pytest.mark.asyncio @@ -919,7 +964,7 @@ async def test_lark_webhook_cardkit_submission_uses_async_card_update_only(): async def listener(event, adapter): pass - adapter.register_listener(platform_events.PlatformSpecificEvent, listener) + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) payload = { 'schema': '2.0', 'header': {'event_type': 'card.action.trigger'}, @@ -991,6 +1036,7 @@ async def test_lark_webhook_rejects_wrong_signature(): def test_lark_stream_card_separates_multiple_reasoning_rounds(): from langbot.pkg.platform.adapters.lark.stream_card import build_card, streaming_text + content = 'first thoughtfirst answersecond thoughtfinal answer' preview = streaming_text(content) assert '' not in preview and '' not in preview @@ -1006,6 +1052,7 @@ def test_lark_stream_card_separates_multiple_reasoning_rounds(): def test_lark_live_preview_is_bounded_but_final_reasoning_is_complete(): from langbot.pkg.platform.adapters.lark.stream_card import build_card, streaming_text + thought = 'reasoning ' * 200 content = '' + thought + ' WecomBotAdapter: return WecomBotAdapter(config, DummyLogger()) +@pytest.mark.asyncio +async def test_interaction_card_finishes_original_loading_stream(): + adapter = make_adapter() + await _send_interaction( + adapter, + { + 'request': {'title': 'Continue', 'actions': [{'id': 'ok', 'label': 'OK'}]}, + 'reply_target': {'target_type': 'person', 'target_id': 'user-1', 'message_id': 'original-1'}, + 'callback_token': 'token-1', + }, + ) + adapter.bot.finish_stream_for_interaction.assert_awaited_once_with('original-1') + + +@pytest.mark.asyncio +async def test_interaction_reply_uses_new_wecom_stream(): + adapter = make_adapter() + target = {'target_type': 'person', 'target_id': 'user-1', 'message_id': 'original-1'} + assert await adapter.begin_interaction_stream('original-1', target) + adapter.bot.begin_interaction_stream.assert_called_once_with('original-1', 'person', 'user-1') + await adapter.reply_interaction_stream_chunk(source_message_id='original-1', content='part', is_final=False) + adapter.bot.push_interaction_stream_chunk.assert_awaited_once_with('original-1', 'part', False) + + def wecombot_event(**overrides) -> WecomBotEvent: event_type = overrides.get('type', 'single') payload = { @@ -164,11 +233,229 @@ def test_wecombot_interaction_card_uses_host_callback_token_and_index(): assert button['key'] == 'lbi:callback-token:a:0' +@pytest.mark.asyncio +async def test_wecombot_select_card_submits_native_dropdown_value(): + adapter = make_adapter() + request = { + 'interaction_id': 'form-1', + 'title': 'Choose priority', + 'description': 'Select one option.', + 'fields': [ + { + 'id': 'priority', + 'label': 'Priority', + 'type': 'select', + 'default': 'normal', + 'options': [ + {'value': 'normal', 'label': 'Normal'}, + {'value': 'urgent', 'label': 'Urgent'}, + ], + } + ], + 'fallback_text': 'Choose priority.', + } + result = await _send_interaction( + adapter, + { + 'callback_token': 'callback-token', + 'reply_target': {'target_type': 'group', 'target_id': 'group-1'}, + 'request': request, + }, + ) + + assert result['rich'] is True + card = adapter.bot.send_template_card.await_args.args[1]['template_card'] + assert card['card_type'] == 'multiple_interaction' + assert card['select_list'] == [ + { + 'question_key': 'f0', + 'title': 'Priority', + 'selected_id': 'opt_1', + 'option_list': [ + {'id': 'opt_1', 'text': 'Normal'}, + {'id': 'opt_2', 'text': 'Urgent'}, + ], + } + ] + assert card['submit_button'] == {'text': 'Submit', 'key': 'lbi:callback-token:s'} + + native = wecombot_event(type='group', msgtype='event') + native['event'] = { + 'eventtype': 'template_card_event', + 'template_card_event': { + 'card_type': 'multiple_interaction', + 'task_id': result['task_id'], + 'event_key': card['submit_button']['key'], + 'selected_items': { + 'selected_item': [ + {'question_key': 'f0', 'option_ids': {'option_id': ['opt_2']}}, + ] + }, + }, + } + event = interaction_event_from_native(native) + assert event.callback_token == 'callback-token' + assert event.callback_context['req_id'] == 'req-1' + assert event.callback_context['task_id'] == result['task_id'] + resolved = InteractionManager._resolve_submission_refs( + {'interaction_id': request['interaction_id'], 'request': request}, event.raw_submission + ) + assert resolved['values'] == {'priority': 'urgent'} + + listener = AsyncMock() + adapter.register_listener(platform_events.InteractionCallbackEvent, listener) + await adapter._handle_interaction_event(native) + listener.assert_awaited_once() + assert listener.await_args.args[0].raw_submission['option_ref'] == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('kind', ['button', 'select']) +async def test_wecombot_acknowledges_submitted_card(kind): + adapter = make_adapter() + request = {'title': 'Choose', 'actions': [{'id': 'yes', 'label': 'Yes'}, {'id': 'no', 'label': 'No'}]} + submission = {'action_id': 'no', 'values': {}} + if kind == 'select': + request = { + 'title': 'Choose', + 'actions': [], + 'fields': [ + { + 'id': 'choice', + 'type': 'select', + 'label': 'Choice', + 'options': [{'value': 'a', 'label': 'A'}, {'value': 'b', 'label': 'B'}], + } + ], + } + submission = {'action_id': None, 'values': {'choice': 'b'}} + delivered = await _send_interaction( + adapter, + { + 'callback_token': 'token-1', + 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, + 'request': request, + }, + ) + + result = await _update_interaction( + adapter, + { + 'request': request, + 'submission': submission, + 'update_target': delivered, + 'callback_context': {'req_id': 'callback-req', 'task_id': delivered['task_id']}, + }, + ) + + assert result['updated'] is True + req_id, card = adapter.bot.update_template_card.await_args.args + assert req_id == 'callback-req' + assert card['task_id'] == delivered['task_id'] + if kind == 'select': + assert card['select_list'][0]['selected_id'] == 'opt_2' + assert card['select_list'][0]['disable'] is True + assert card['submit_button']['key'] == 'submitted' + else: + assert card['button_list'][1]['replace_text'].endswith('No') + assert all(button['key'] == 'submitted' for button in card['button_list']) + + with pytest.raises(ValueError, match='does not match'): + await _update_interaction( + adapter, + { + 'request': request, + 'submission': submission, + 'update_target': delivered, + 'callback_context': {'req_id': 'callback-req', 'task_id': 'another-card'}, + }, + ) + assert adapter.bot.update_template_card.await_count == 1 + + +def test_wecombot_select_rejects_more_than_ten_options(): + with pytest.raises(ValueError, match='at most 10 options'): + build_interaction_card( + { + 'title': 'Choose priority', + 'fields': [ + { + 'id': 'priority', + 'type': 'select', + 'options': [{'value': f'option-{index}'} for index in range(11)], + } + ], + }, + 'callback-token', + ) + + +@pytest.mark.parametrize( + 'selected_items', + [ + {'selected_item': []}, + {'selected_item': [{'question_key': 'f0', 'option_ids': {'option_id': []}}]}, + {'selected_item': [{'question_key': 'f0', 'option_ids': {'option_id': ['opt_0']}}]}, + ], +) +def test_wecombot_select_rejects_invalid_native_selection(selected_items): + native = wecombot_event(type='single', msgtype='event') + native['event'] = { + 'eventtype': 'template_card_event', + 'template_card_event': { + 'event_key': 'lbi:callback-token:s', + 'selected_items': selected_items, + }, + } + with pytest.raises(ValueError, match='invalid option'): + interaction_event_from_native(native) + + +def test_wecombot_select_accepts_legacy_response_data(): + native = wecombot_event(type='single', msgtype='event') + native['event'] = { + 'eventtype': 'template_card_event', + 'template_card_event': { + 'EventKey': 'lbi:callback-token:s', + 'ResponseData': '{"select_list":[{"question_key":"f0","option_id":"opt_2"}]}', + }, + } + assert interaction_event_from_native(native).raw_submission['option_ref'] == 1 + + +@pytest.mark.asyncio +async def test_wecombot_interaction_delivery_rejects_failed_ack(): + adapter = make_adapter() + adapter.bot.send_template_card.return_value = {'errcode': 40001, 'errmsg': 'invalid card'} + + with pytest.raises(RuntimeError, match='invalid card'): + await _send_interaction( + adapter, + { + 'callback_token': 'callback-token', + 'reply_target': {'target_type': 'person', 'target_id': 'user-1'}, + 'request': { + 'interaction_id': 'form-1', + 'title': 'Choose priority', + 'fields': [ + { + 'id': 'priority', + 'label': 'Priority', + 'type': 'select', + 'options': [{'value': 'normal', 'label': 'Normal'}], + } + ], + 'fallback_text': 'Choose priority.', + }, + }, + ) + + @pytest.mark.asyncio async def test_wecombot_interaction_delivery_and_callback_event(): adapter = make_adapter() - result = await adapter.call_platform_api( - 'interaction.request', + result = await _send_interaction( + adapter, { 'callback_token': 'callback-token', 'reply_target': {'target_type': 'group', 'target_id': 'group-1'}, @@ -190,14 +477,14 @@ async def test_wecombot_interaction_delivery_and_callback_event(): 'template_card_event': {'EventKey': 'lbi:callback-token:a:0'}, } event = interaction_event_from_native(native) - assert event.action == 'interaction.submitted' - assert event.data['action_ref'] == 0 - assert event.data['target_id'] == 'group-1' + assert isinstance(event, platform_events.InteractionCallbackEvent) + assert event.raw_submission['action_ref'] == 0 + assert event.target_id == 'group-1' native['event']['template_card_event'] = {'button': {'key': 'lbi:callback-token:f:0:2'}} nested_event = interaction_event_from_native(native) - assert nested_event.data['field_ref'] == 0 - assert nested_event.data['option_ref'] == 2 + assert nested_event.raw_submission['field_ref'] == 0 + assert nested_event.raw_submission['option_ref'] == 2 @pytest.mark.asyncio @@ -323,6 +610,29 @@ async def test_wecombot_send_reply_feedback_and_platform_api_use_underlying_clie assert feedback_calls[0].inaccurate_reasons == ['1', '2'] +@pytest.mark.asyncio +async def test_wecombot_expired_stream_falls_back_to_proactive_reply(): + adapter = make_adapter() + adapter.bot.push_stream_chunk.return_value = False + source_event = await WecomBotEventConverter().target2yiri(wecombot_event()) + message = platform_message.MessageChain([platform_message.Plain(text='late answer')]) + + await adapter.reply_message_chunk(source_event, None, message, is_final=True) + + adapter.bot.send_message.assert_awaited_once_with('user-1', 'late answer') + adapter.bot.reply_text.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_wecombot_send_message_rejects_failed_ack(): + adapter = make_adapter() + adapter.bot.send_message.return_value = {'errcode': 400, 'errmsg': 'invalid message'} + with pytest.raises(RuntimeError, match='invalid message'): + await adapter.send_message( + 'person', 'user-1', platform_message.MessageChain([platform_message.Plain(text='hello')]) + ) + + @pytest.mark.asyncio async def test_wecombot_webhook_mode_rejects_proactive_send(): adapter = make_adapter(enable_webhook=True) @@ -399,8 +709,7 @@ async def test_managed_card_callback_does_not_start_business_event(): ) listener.assert_awaited_once() event = listener.await_args.args[0] - assert event.type == 'platform.specific' - assert event.action == 'interaction.submitted' + assert isinstance(event, platform_events.InteractionCallbackEvent) @pytest.mark.asyncio diff --git a/tests/unit_tests/platform/test_wecombot_template_card.py b/tests/unit_tests/platform/test_wecombot_template_card.py index 410ad621a..3afc8587b 100644 --- a/tests/unit_tests/platform/test_wecombot_template_card.py +++ b/tests/unit_tests/platform/test_wecombot_template_card.py @@ -1,14 +1,10 @@ -import sys +import time import types -from unittest.mock import Mock +from unittest.mock import AsyncMock, Mock import pytest -logger_module = types.ModuleType('langbot.pkg.platform.logger') -logger_module.EventLogger = object -sys.modules.setdefault('langbot.pkg.platform.logger', logger_module) - from langbot.libs.wecom_ai_bot_api.api import ( # noqa: E402 WecomBotClient, build_button_interaction_payload, @@ -46,7 +42,7 @@ def test_webhook_dispatch_tasks_are_bounded(): @pytest.mark.asyncio -async def test_ws_initial_stream_frame_precedes_pipeline_dispatch(monkeypatch): +async def test_ws_message_waits_for_real_content_before_creating_stream(monkeypatch): from langbot.libs.wecom_ai_bot_api import ws_client as ws_client_module order = [] @@ -62,9 +58,7 @@ async def test_ws_initial_stream_frame_precedes_pipeline_dispatch(monkeypatch): return {'msgid': 'msg-1', 'type': 'single', 'userid': 'user-1'} async def reply_stream(*args, **kwargs): - del args, kwargs - order.append('initial-frame') - return {} + raise AssertionError('An empty stream must not be created') async def dispatch_event(event): del event @@ -77,11 +71,126 @@ async def test_ws_initial_stream_frame_precedes_pipeline_dispatch(monkeypatch): await client._handle_message_callback({'headers': {'req_id': 'req-1'}, 'body': {}}) - assert order == ['initial-frame', 'pipeline-dispatch'] + assert order == ['pipeline-dispatch'] + assert client._stream_sessions['msg-1']['stream_started'] is False @pytest.mark.asyncio -async def test_ws_initial_stream_failure_still_dispatches_message(monkeypatch): +async def test_ws_interaction_releases_unused_stream_without_visible_message(): + client = WecomBotWsClient('bot-id', 'secret', object()) + client._stream_ids['msg-1'] = 'req-1|stream-1' + client._stream_sessions['msg-1'] = {'user_id': 'user-1'} + sent = [] + + async def reply_stream(req_id, stream_id, content, finish=False): + sent.append((req_id, stream_id, content, finish)) + return {'errcode': 0} + + client.reply_stream = reply_stream + assert await client.finish_stream_for_interaction('msg-1') + assert sent == [] + assert 'msg-1' not in client._stream_ids + assert 'msg-1' not in client._stream_sessions + + +@pytest.mark.asyncio +async def test_ws_interaction_starts_a_new_stream_after_card(): + client = WecomBotWsClient('bot-id', 'secret', types.SimpleNamespace(info=AsyncMock())) + client._stream_ids['msg-1'] = 'req-1|old-stream' + client._stream_sessions['msg-1'] = { + 'req_id': 'req-1', + 'user_id': 'user-1', + 'chat_id': '', + 'created_at': time.monotonic(), + 'stream_started': False, + } + sent = [] + + async def reply_stream(req_id, stream_id, content, finish=False, feedback_id=''): + sent.append((req_id, stream_id, content, finish)) + return {'errcode': 0} + + client.reply_stream = reply_stream + assert await client.finish_stream_for_interaction('msg-1') + assert sent == [] + assert client.begin_interaction_stream('msg-1', 'person', 'user-1') + assert not client.begin_interaction_stream('msg-1', 'person', 'user-1') + assert await client.push_interaction_stream_chunk('msg-1', 'part', False) + assert await client.push_interaction_stream_chunk('msg-1', 'part done', True) + assert [item[2:] for item in sent] == [('part', False), ('part done', True)] + assert sent[0][0] == sent[1][0] == 'req-1' + assert sent[0][1] == sent[1][1] + assert sent[0][1] != 'old-stream' + + +def test_ws_interaction_stream_checks_target_and_expiry(): + client = WecomBotWsClient('bot-id', 'secret', object()) + client._interaction_stream_origins['msg-1'] = { + 'req_id': 'req-1', + 'user_id': 'user-1', + 'chat_id': 'group-1', + 'created_at': time.monotonic(), + } + assert not client.begin_interaction_stream('msg-1', 'person', 'other-user') + assert not client.begin_interaction_stream('msg-1', 'group', 'other-group') + client._interaction_stream_origins['msg-1']['created_at'] -= 571 + assert not client.begin_interaction_stream('msg-1', 'person', 'user-1') + assert 'msg-1' not in client._interaction_stream_origins + + +@pytest.mark.asyncio +async def test_ws_interaction_preserves_existing_stream_text_when_finishing(): + client = WecomBotWsClient('bot-id', 'secret', object()) + client._stream_ids['msg-1'] = 'req-1|stream-1' + client._stream_sessions['msg-1'] = {'stream_started': True} + client._stream_last_content['msg-1'] = 'Earlier answer' + sent = [] + + async def reply_stream(req_id, stream_id, content, finish=False): + sent.append((content, finish)) + return {'errcode': 0} + + client.reply_stream = reply_stream + assert await client.finish_stream_for_interaction('msg-1') + assert sent == [('Earlier answer', True)] + + +@pytest.mark.asyncio +async def test_ws_interaction_finish_failure_keeps_stream_state(): + logger = types.SimpleNamespace(warning=AsyncMock()) + client = WecomBotWsClient('bot-id', 'secret', logger) + client._stream_ids['msg-1'] = 'req-1|stream-1' + client._stream_sessions['msg-1'] = {'stream_started': True} + + async def reject(*args, **kwargs): + raise ConnectionError('disconnected') + + client.reply_stream = reject + assert not await client.finish_stream_for_interaction('msg-1') + assert client._stream_ids['msg-1'] == 'req-1|stream-1' + + +@pytest.mark.asyncio +async def test_ws_rejected_stream_refresh_does_not_complete_session(): + logger = types.SimpleNamespace(error=Mock()) + client = WecomBotWsClient('bot-id', 'secret', logger) + client._stream_ids['msg-1'] = 'req-1|stream-1' + client._stream_sessions['msg-1'] = {'user_id': 'user-1'} + + async def reject(*args, **kwargs): + return {'errcode': 400, 'errmsg': 'invalid req_id'} + + async def record_error(message): + assert 'invalid req_id' in message + + client.reply_stream = reject + logger.error = record_error + assert not await client.push_stream_chunk('msg-1', 'answer', is_final=True) + assert 'msg-1' in client._stream_ids + + +@pytest.mark.asyncio +async def test_ws_stream_starts_with_first_real_content(monkeypatch): from langbot.libs.wecom_ai_bot_api import ws_client as ws_client_module dispatched = [] @@ -106,9 +215,11 @@ async def test_ws_initial_stream_failure_still_dispatches_message(monkeypatch): del args, kwargs return {'msgid': 'msg-1', 'type': 'single', 'userid': 'user-1'} - async def reply_stream(*args, **kwargs): - del args, kwargs - raise ConnectionError('simulated reply failure') + sent = [] + + async def reply_stream(req_id, stream_id, content, finish=False, feedback_id=''): + sent.append((req_id, content, finish)) + return {'errcode': 0} async def dispatch_event(event): dispatched.append(event) @@ -119,10 +230,17 @@ async def test_ws_initial_stream_failure_still_dispatches_message(monkeypatch): client._dispatch_event = dispatch_event await client._handle_message_callback({'headers': {'req_id': 'req-1'}, 'body': {}}) + assert sent == [] + assert await client.push_stream_chunk('msg-1', 'hello') assert len(dispatched) == 1 - assert len(logger.warnings) == 1 - assert 'simulated reply failure' in logger.warnings[0] + assert sent == [('req-1', 'hello', False)] + assert client._stream_sessions['msg-1']['stream_started'] is True + assert logger.warnings == [] + + assert await client.push_stream_chunk('msg-1', 'hello', is_final=True) + assert 'msg-1' not in client._stream_ids + assert client.begin_interaction_stream('msg-1', 'person', 'user-1') def test_extract_template_card_action_supports_nested_button_key(): diff --git a/tests/unit_tests/plugin/test_runner_stream_context.py b/tests/unit_tests/plugin/test_runner_stream_context.py index 76df1bad8..dc25d3d55 100644 --- a/tests/unit_tests/plugin/test_runner_stream_context.py +++ b/tests/unit_tests/plugin/test_runner_stream_context.py @@ -68,6 +68,22 @@ async def test_scope_is_reset_before_yield_and_stream_finishes(deadline): assert closed == [TEST_INSTALLATION_BINDING] +@pytest.mark.asyncio +async def test_runner_transport_wait_has_no_stale_idle_deadline(): + stream, handler, _, _, _, _ = make_stream() + original = handler.call_action_generator + timeouts = [] + + async def capture_timeout(*args, **kwargs): + timeouts.append(kwargs['timeout']) + async for frame in original(*args, **kwargs): + yield frame + + handler.call_action_generator = capture_timeout + assert [frame['sequence'] async for frame in stream] == [0, 1, 2] + assert timeouts == [None] + + @pytest.mark.asyncio @pytest.mark.parametrize('deadline', [True, False]) async def test_early_close_releases_wire_stream_in_scope(deadline): diff --git a/uv.lock b/uv.lock index 6ba1a6d82..f8c24804d 100644 --- a/uv.lock +++ b/uv.lock @@ -12,10 +12,10 @@ resolution-markers = [ "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] @@ -317,7 +317,7 @@ wheels = [ [package.optional-dependencies] trio = [ - { name = "trio", marker = "sys_platform != 'win32'" }, + { name = "trio" }, ] [[package]] @@ -1119,7 +1119,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "cuda-pathfinder" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/51/6b/457ca12dad3ee9bfcc9a545cfd6b64b359ba49de40f776f6e028e678f262/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5879712accf6e14bb01aa5e67440eb84998b8d104b509cc7a6dc0b8f656a474", size = 6053539, upload-time = "2026-05-29T23:11:43.19Z" }, @@ -1152,43 +1152,43 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-cuda-nvrtc", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cuda-runtime", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cufft = [ - { name = "nvidia-cufft", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-nvjitlink", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cufft", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cufile = [ - { name = "nvidia-cufile", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cufile", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cuda-cupti", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] curand = [ - { name = "nvidia-curand", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cusolver = [ - { name = "nvidia-cublas", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-cusolver", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-cusparse", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-nvjitlink", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusolver", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, - { name = "nvidia-nvjitlink", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "(python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] [[package]] @@ -2244,7 +2244,7 @@ requires-dist = [ { name = "gewechat-client", specifier = ">=0.1.5" }, { name = "html2text", specifier = ">=2024.2.26" }, { name = "httpx", extras = ["socks"], specifier = ">=0.28.1" }, - { name = "langbot-plugin", specifier = "==0.7.19" }, + { name = "langbot-plugin", specifier = "==0.7.20" }, { name = "langchain", specifier = ">=1.3.9" }, { name = "langchain-core", specifier = ">=1.3.3" }, { name = "langchain-text-splitters", specifier = ">=1.1.2" }, @@ -2315,7 +2315,7 @@ dev = [ [[package]] name = "langbot-plugin" -version = "0.7.19" +version = "0.7.20" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiofiles" }, @@ -2336,9 +2336,9 @@ dependencies = [ { name = "watchdog" }, { name = "websockets" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f5/23/ffce65a9c333a6545b47d8364bbd5083f6517292b95bdfffc7ac87b702c3/langbot_plugin-0.7.19.tar.gz", hash = "sha256:62a972592e2160dee963ecbfc4276719e43178e137273ea29af1a43152b8353e", size = 749638, upload-time = "2026-10-28T10:52:04.63Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5e/b9/e93ee14ccb584b2351652e6b37a80d255ca99efcdd7761edf54223505f6b/langbot_plugin-0.7.20.tar.gz", hash = "sha256:10a8ad7dd15d040680962148357d49294faad0ae677f5b8989fedb81b4d936c0", size = 758993, upload-time = "2026-11-03T04:59:16.695Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4c/99/e32e004c6869a40e63276440de3b31a8d22bf89a22a1ae1133f0233e55e3/langbot_plugin-0.7.19-py3-none-any.whl", hash = "sha256:a94037c766e0f4bc2f108edfa0e1c075fc28d480217b6794a652d2532be5ca1f", size = 474676, upload-time = "2026-10-28T10:52:02.788Z" }, + { url = "https://files.pythonhosted.org/packages/66/2f/7bfd9692fd142f919a7ee6d13957935155e6c9d8a6b4ec24a2ce3b6a99e0/langbot_plugin-0.7.20-py3-none-any.whl", hash = "sha256:de33471621e2bde6074ffae6174f14a9f34c6d5625a2aa1adbe92ec6d62ed2bc", size = 479090, upload-time = "2026-11-03T04:59:15.256Z" }, ] [[package]] @@ -3421,7 +3421,7 @@ name = "nvidia-cublas" version = "13.1.1.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cuda-nvrtc", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "nvidia-cuda-nvrtc" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, @@ -3460,7 +3460,7 @@ name = "nvidia-cudnn-cu13" version = "9.24.0.43" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "nvidia-cublas" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/ca/30/7c257e3d5cb4fecb147b93895c66e29c93f8e76d74b45bb418ff0587c4ec/nvidia_cudnn_cu13-9.24.0.43-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:a6812a554a1ff0413e9c52b84c26c050380649ab9615f9c16bded368ce9f421f", size = 650976863, upload-time = "2026-07-02T16:23:39.248Z" }, @@ -3472,7 +3472,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -3502,9 +3502,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "nvidia-cusparse", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "nvidia-nvjitlink", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -3516,7 +3516,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -3856,7 +3856,7 @@ name = "outcome" version = "1.3.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "attrs", marker = "sys_platform != 'win32'" }, + { name = "attrs" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/df/77698abfac98571e65ffeb0c1fba8ffd692ab8458d617a0eed7d9a8d38f2/outcome-1.3.0.post0.tar.gz", hash = "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8", size = 21060, upload-time = "2023-10-26T04:26:04.361Z" } wheels = [ @@ -4632,7 +4632,7 @@ name = "pylibseekdb" version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pymysql", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "pymysql" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/ae/a8/7413d33218aff55a14ec9d20532b49243ffd0579e7a92244922c1885444e/pylibseekdb-1.4.0-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:5cb2efab9f1321cdb4b034d3a2bd92e41a402fc95e7dc9579c7473a426f96e24", size = 52173499, upload-time = "2026-08-27T13:05:09.347Z" }, @@ -5414,10 +5414,10 @@ name = "scikit-learn" version = "1.8.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "joblib", marker = "python_full_version >= '3.14'" }, - { name = "numpy", marker = "python_full_version >= '3.14'" }, - { name = "scipy", marker = "python_full_version >= '3.14'" }, - { name = "threadpoolctl", marker = "python_full_version >= '3.14'" }, + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/0e/d4/40988bf3b8e34feec1d0e6a051446b1f66225f8529b9309becaeef62b6c4/scikit_learn-1.8.0.tar.gz", hash = "sha256:9bccbb3b40e3de10351f8f5068e105d0f4083b1a65fa07b6634fbc401a6287fd", size = 7335585, upload-time = "2025-12-10T07:08:53.618Z" } wheels = [ @@ -5464,7 +5464,7 @@ name = "scipy" version = "1.17.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version >= '3.14'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } wheels = [ @@ -5535,15 +5535,15 @@ name = "sentence-transformers" version = "6.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub", marker = "python_full_version >= '3.14'" }, - { name = "numpy", marker = "python_full_version >= '3.14'" }, - { name = "scikit-learn", marker = "python_full_version >= '3.14'" }, - { name = "scipy", marker = "python_full_version >= '3.14'" }, - { name = "tokenizers", version = "0.23.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "torch", marker = "python_full_version >= '3.14'" }, - { name = "tqdm", marker = "python_full_version >= '3.14'" }, - { name = "transformers", marker = "python_full_version >= '3.14'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.14'" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "scikit-learn" }, + { name = "scipy" }, + { name = "tokenizers", version = "0.23.3", source = { registry = "https://pypi.org/simple" } }, + { name = "torch" }, + { name = "tqdm" }, + { name = "transformers" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7f/66/635443b9b1d7ea618c4699c8ad4c43b022ceac0c0a1dc4404b7597b38754/sentence_transformers-6.2.0.tar.gz", hash = "sha256:1e3cd8796ab7bcad4cfa2f51e2083d8b37b15d6b68e6fa6b91a147c67380574d", size = 600810, upload-time = "2026-10-21T12:26:50.404Z" } wheels = [ @@ -5889,14 +5889,14 @@ resolution-markers = [ "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "huggingface-hub", marker = "python_full_version < '3.14'" }, + { name = "huggingface-hub" }, ] sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } wheels = [ @@ -5927,7 +5927,7 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "huggingface-hub", marker = "python_full_version >= '3.14'" }, + { name = "huggingface-hub" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" } wheels = [ @@ -6015,20 +6015,20 @@ name = "torch" version = "2.14.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-bindings", marker = "python_full_version == '3.14.*' and sys_platform == 'linux'" }, - { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "python_full_version >= '3.14' and sys_platform == 'linux'" }, - { name = "filelock", marker = "python_full_version >= '3.14'" }, - { name = "fsspec", marker = "python_full_version >= '3.14'" }, - { name = "jinja2", marker = "python_full_version >= '3.14'" }, - { name = "networkx", marker = "python_full_version >= '3.14'" }, - { name = "nvidia-cudnn-cu13", marker = "python_full_version >= '3.14' and sys_platform == 'linux'" }, - { name = "nvidia-cusparselt-cu13", marker = "python_full_version >= '3.14' and sys_platform == 'linux'" }, - { name = "nvidia-nccl-cu13", marker = "python_full_version >= '3.14' and sys_platform == 'linux'" }, - { name = "nvidia-nvshmem-cu13", marker = "python_full_version >= '3.14' and sys_platform == 'linux'" }, - { name = "setuptools", marker = "python_full_version >= '3.14'" }, - { name = "sympy", marker = "python_full_version >= '3.14'" }, - { name = "triton", marker = "python_full_version == '3.14.*' and sys_platform == 'linux'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.14'" }, + { name = "cuda-bindings", marker = "python_full_version < '3.15' and sys_platform == 'linux'" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux'" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "python_full_version < '3.15' and sys_platform == 'linux'" }, + { name = "typing-extensions" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/5d/9b/fd1cd143a7bda5abc1fc352ed7b431f6f52aa3c454293211a33656db2cb5/torch-2.14.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:b6074b130fd26bc50f5d171f07dfed70db22dd0c354ab34767729249f9e0f042", size = 127281154, upload-time = "2026-09-30T17:43:58.328Z" }, @@ -6070,15 +6070,15 @@ name = "transformers" version = "5.20.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub", marker = "python_full_version >= '3.14'" }, - { name = "numpy", marker = "python_full_version >= '3.14'" }, - { name = "packaging", marker = "python_full_version >= '3.14'" }, - { name = "pyyaml", marker = "python_full_version >= '3.14'" }, - { name = "regex", marker = "python_full_version >= '3.14'" }, - { name = "safetensors", marker = "python_full_version >= '3.14'" }, - { name = "tokenizers", version = "0.23.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "tqdm", marker = "python_full_version >= '3.14'" }, - { name = "typer", marker = "python_full_version >= '3.14'" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "safetensors" }, + { name = "tokenizers", version = "0.23.3", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, + { name = "typer" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8c/4e/3cd6f08cc84ee612d40f3cdb1649475e7c997f2d5cbd95ade8780708af62/transformers-5.20.2.tar.gz", hash = "sha256:080871e061546d720be57f5846fce426f46b44d61574907cc7404c2cba49d180", size = 10225379, upload-time = "2026-10-19T17:46:03.092Z" } wheels = [ @@ -6090,12 +6090,12 @@ name = "trio" version = "0.34.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "attrs", marker = "sys_platform != 'win32'" }, - { name = "cffi", marker = "implementation_name != 'pypy' and os_name == 'nt' and sys_platform != 'win32'" }, - { name = "idna", marker = "sys_platform != 'win32'" }, - { name = "outcome", marker = "sys_platform != 'win32'" }, - { name = "sniffio", marker = "sys_platform != 'win32'" }, - { name = "sortedcontainers", marker = "sys_platform != 'win32'" }, + { name = "attrs" }, + { name = "cffi", marker = "implementation_name != 'pypy' and os_name == 'nt'" }, + { name = "idna" }, + { name = "outcome" }, + { name = "sniffio" }, + { name = "sortedcontainers" }, ] sdist = { url = "https://files.pythonhosted.org/packages/92/dc/a2d25ed73ad49cfd79bf18d262577c3731c98e382284e28d522f49a0df35/trio-0.34.0.tar.gz", hash = "sha256:63b9485408bdfdde544fced107045a8c0086cdc4bd0ef2f797b9e0dd111b964b", size = 607457, upload-time = "2026-08-11T00:33:42.198Z" } wheels = [ @@ -6343,10 +6343,10 @@ name = "valkey-glide" version = "2.5.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", extra = ["trio"], marker = "sys_platform != 'win32'" }, - { name = "cffi", marker = "sys_platform != 'win32'" }, - { name = "protobuf", marker = "sys_platform != 'win32'" }, - { name = "sniffio", marker = "sys_platform != 'win32'" }, + { name = "anyio", extra = ["trio"] }, + { name = "cffi" }, + { name = "protobuf" }, + { name = "sniffio" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b0/d8/ed10fa0fe319daf0651c69221372b8523cfa865df5b9b1040c9a9a41b518/valkey_glide-2.5.3.tar.gz", hash = "sha256:ce3da1a0a927631385d6bc0a1ac8ab4e8e2efa9f41404bf54bbcf82904f3ea98", size = 1012668, upload-time = "2026-09-25T02:10:19.611Z" } wheels = [ diff --git a/web/src/app/home/agents/components/AgentCreateContent.tsx b/web/src/app/home/agents/components/AgentCreateContent.tsx index c7d96248f..5daee54eb 100644 --- a/web/src/app/home/agents/components/AgentCreateContent.tsx +++ b/web/src/app/home/agents/components/AgentCreateContent.tsx @@ -1,10 +1,10 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; -import { Bot, Workflow, Puzzle } from 'lucide-react'; +import { Bot, Workflow, Puzzle, Loader2 } from 'lucide-react'; import { httpClient } from '@/app/infra/http/HttpClient'; import { AgentKind } from '@/app/infra/entities/api'; import { Button } from '@/components/ui/button'; @@ -46,7 +46,6 @@ export default function AgentCreateContent({ const [metadata, setMetadata] = useState(); const [runner, setRunner] = useState(''); const [loading, setLoading] = useState(true); - const createdPipeline = useRef(null); const loadMetadata = useCallback(async () => { setLoading(true); try { @@ -135,58 +134,13 @@ export default function AgentCreateContent({ runner_config: { [runner]: parameters }, }; try { - if ( - kind === 'pipeline' && - runnerStage?.config.some((field) => - [ - 'llm-model-selector', - 'select-llm-model', - 'model-fallback-selector', - ].includes(field.type), - ) - ) { - const { uuid } = await httpClient.getDefaultModel(); - if (uuid) { - for (const field of runnerStage.config) { - if ( - ['llm-model-selector', 'select-llm-model'].includes(field.type) && - !parameters[field.name] - ) - parameters[field.name] = uuid; - if ( - field.type === 'model-fallback-selector' && - !parameters[field.name]?.primary - ) { - parameters[field.name] = { - ...parameters[field.name], - primary: uuid, - fallbacks: parameters[field.name]?.fallbacks ?? [], - }; - } - } - } - } if (kind === 'pipeline') { - // Keep the created ID if configuration fails, so retry does not create duplicates. - const uuid = - createdPipeline.current ?? - ( - await httpClient.createAgent({ - kind, - name: values.name, - description: '', - emoji: values.emoji, - }) - ).uuid; - createdPipeline.current = uuid; - const { pipeline } = await httpClient.getPipeline(uuid); - await httpClient.updatePipeline(uuid, { + const { uuid } = await httpClient.createAgent({ + kind, name: values.name, + description: '', emoji: values.emoji, - config: { - ...pipeline.config, - ai: { ...pipeline.config.ai, ...config }, - }, + runner_id: runner, }); toast.success(t('agents.createSuccess')); onCreated(uuid); @@ -248,7 +202,12 @@ export default function AgentCreateContent({ form="agent-create-form" disabled={form.formState.isSubmitting || loading || !runner} > - {t('common.submit')} + {form.formState.isSubmitting && ( +