Skip to content

Self-improving AI Employees for everyone

feat: add observable agent capabilities

trohitgfa31ec8b1838
diff --git a/CLAUDE.md b/CLAUDE.md
index 98406476..5961038e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -690,6 +690,8 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → Redis-parallel → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC 7233 + Web UI 8080, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the 7 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, resumption toggle (`TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`), the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
+**Temporal tracing ownership is strict.** Register the SDK `TracingInterceptor` exactly once on the shared `Client.connect(...)`; the Python SDK automatically prepends compatible client interceptors to every worker. Never repeat `TracingInterceptor` in `Worker(..., interceptors=...)`. Worker lists contain the distinct `ObservabilityWorkerInterceptor` and plugin-specific worker interceptors only. Exact paired `StartActivity` / `RunActivity` / `CompleteWorkflow` console spans with identical Temporal identities indicate duplicate instrumentation, not duplicate execution; use Temporal Event History and the `node.<type>.execute` application span to verify actual attempts. See the tracing and debugging sections in [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) and [errors.md](./docs-internal/errors.md).
+
## Development Commands
### CLI Commands (after the global install)
@@ -1030,7 +1032,7 @@ The workflow record carries three identity fields with strict separation:
| Field | Carrier | Stable? | Surfaces |
|---|---|---|---|
-| `Workflow.id` | opaque 32-hex UUID (`uuid.uuid4().hex`) | yes — never changes on rename | FK target (`Execution.workflow_id`), `EventWorkflowId` Search Attribute in Temporal Visibility, `WorkflowEvent.workflow_id` CloudEvents extension, `log_context(workflow_id=...)`, Redis cache keys, `DeploymentManager._deployments` dict key, frontend `useAppStore.currentWorkflow.id` |
+| `Workflow.id` | opaque 32-hex UUID (`uuid.uuid4().hex`) | yes — never changes on rename | FK target (`Execution.workflow_id`), `EventWorkflowId` Search Attribute in Temporal Visibility, legacy `WorkflowEvent.workflow_id` compatibility field, `log_context(workflow_id=...)`, Redis cache keys, `DeploymentManager._deployments` dict key, frontend `useAppStore.currentWorkflow.id` |
| `Workflow.name` | free-form display ("AI Assistant") | mutable | sidebar, parameter panel, exported JSON |
| `Workflow.slug` | `<Sanitized_Name>_<N>` (`AI_Assistant_1`) | mutable, recomputed on rename | `~/.opencompany/workspaces/<slug>/`, Temporal workflow IDs (visible in Temporal Web UI), cron Schedule IDs, export filenames |
@@ -2497,7 +2499,8 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins
| `android_status` | Android device connection update |
| `node_status` | Node execution status change |
| `node_output` | Node execution output data |
-| `agent_progress` | CloudEvents v1.0 envelope (type=`agent.progress`) — per-step agent-loop iteration count, drives the live "N / max" badge on AI Agent canvas nodes |
+| `agent_progress` | CloudEvents v1.0 envelope (type=`com.opencompany.agent.progress`) — per-step agent-loop iteration count, drives the live "N / max" badge on AI Agent canvas nodes |
+| `agent_capability` | CloudEvents v1.0 envelope (`com.opencompany.agent.(skill|tool).*`) — exact-agent capability lifecycle with deterministic Temporal IDs, `(source,id)` deduplication, sanitized data, and an optional exact target node |
| `deployment_snapshot` | CloudEvents v1.0 envelope (type=`workflow.deployment.snapshot`) — pushed once per WS connect from `broadcaster._send_deployment_snapshot`; lets the FE reconcile stale `deploymentStatus.isRunning=true` after a backend restart wiped `DeploymentManager._deployments`. Empty list is meaningful (forces reset). |
| `variable_update` | Single variable value change |
| `workflow_status` | Workflow execution progress |
@@ -2733,7 +2736,7 @@ This function:
- Source: https://github.com/trohitg/whatsapp-rpc
- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.
- **Workflow Export/Import with Parameters**: Exported workflow JSON includes a `nodeParameters` field containing all node configuration (provider, model, prompt, skillsConfig, etc.) fetched from the database at export time. On import, embedded `nodeParameters` are saved back to the database. `sanitizeNodes()` in `workflowExport.ts` still strips `node.data` to UI-only fields (`label`, `disabled`, `condition`). The `parameterSanitizer.ts` utility strips credential-bearing keys (SENSITIVE key sets + substring matching + runtime-key stripping) and is ACTIVE in the export path (`buildExportParameters` in `workflowExport.ts` calls `sanitizeParameters`). Old exports without `nodeParameters` import cleanly (backward compatible). Key files: `client/src/utils/workflowExport.ts`, `client/src/utils/parameterSanitizer.ts`, `client/src/Dashboard.tsx` (export/import handlers), `server/services/example_loader.py`.
-- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
+- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB/Master Skill customization is authoritative. Standard skills use progressive disclosure without modifying the agent system prompt: the dynamically connected `Skill` tool carries the bounded name/description catalogue, loads instructions, then separately reads/searches declared resources. Personality skills remain eager. Duplicate connected names block with `DUPLICATE_CONNECTED_SKILL_NAME`. Runtime state and sanitized `agent.skill.*` observability live in [`skill_runtime.py`](./server/services/skill_runtime.py); tool results persist in the current conversation while canvas badges clear at turn end. Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
- **Example Workflows**: Auto-load example workflow seeds from `<repo>/.opencompany/workflows/` on first use (git-tracked; the only non-ignored content under `<repo>/.opencompany/`). Path resolved by `core.paths.example_workflows_dir()` — fixed, NOT under `DATA_DIR`, preserved by `company clean` via `_OPENCOMPANY_KEEP`. Uses `UserSettings.examples_loaded` flag; supports anonymous users (`user_id="default"`); embedded `nodeParameters` saved to DB on import.
- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using shadcn primitives + lucide icons. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 3020 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. The code executor plugins under `server/nodes/code/` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).
@@ -2762,8 +2765,8 @@ This function:
- **Local-LLM provider routing + per-model context**: Ollama and LM Studio are first-class providers (9 in total for agents now: cloud 7 + 2 local). Provider detection is driven by `detect_ai_provider` in `server/constants.py` plus the `provider` Literal in `nodes/agent/{ai_agent,chat_agent,_specialized}.py` — both MUST list `ollama` / `lmstudio` or chat-model nodes / agent dropdowns silently fall through to `'openai'` and `execute_chat` calls api.openai.com with the placeholder key. The validator at `nodes/model/_local_validator.py` probes via the official SDKs (`ollama.AsyncClient.ps()` for typed `ProcessResponse.Model`, `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo`) — reads only typed fields (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`, plus Ollama's `details.{family,parameter_size,quantization_level}`). No regex, no Modelfile-parameters parsing, no `/api/show` modelinfo dict-key hunting. Per-model params persist in `EncryptedAPIKey.models["model_params"]` (via `save_api_key(model_params=...)`) AND in `model_registry.json` via `register_local_model()` — sync `get_context_length()` / `get_max_output_tokens()` find real values without async DB lookups, and entries survive process restart. `is_model_valid_for_provider` returns `True` for open-world providers (`openrouter` / `ollama` / `lmstudio`) so local model names like `qwen/qwen3.6-27b` aren't rejected by the cloud-style pattern check. Runtime path uses `OpenAIProvider(base_url={user_proxy_url}, api_key="ollama")` — traffic stays on `localhost`.
- **Typed openai exception → NodeUserError**: `execute_chat` / `execute_agent` / `execute_chat_agent` in `services/ai.py` each have **one** `except openai.OpenAIError as e` block that re-raises `NodeUserError(str(e)) from e`. The openai SDK's typed exception hierarchy — `BadRequestError` (400, e.g. `n_keep > n_ctx` overflow), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RateLimitError` (429), `APIConnectionError` (server unreachable), `APITimeoutError` — IS the user-correctable contract. `BaseNode.execute()` catches `NodeUserError` and logs at WARN with one line, no stacktrace. The plain `except Exception` block keeps the full-traceback path for real bugs. Zero string matching, zero flag plumbing, zero classification helpers. The `frontend toast` reads `response.message ?? response.error` so both clean envelopes (validator-style) and uncaught-error envelopes (handler-wrapper-style) surface a useful message.
- **Plugin extraction (Wave 11.I)**: every plugin's WS handlers, OAuth client, FastAPI router, and lifecycle service live entirely under `nodes/<plugin>/`. Eight plugin domains migrated this round (whatsapp / twitter / google-workspace / android / browser / email / code / credential-validation-scaffold for maps+apify+ollama+lmstudio) follow the telegram pattern. `routers/websocket.py` shrunk from ~3,785 to ~2,977 LOC (-808). Three plugin routers (`routers/twitter.py`, `routers/google.py`, `routers/android.py`) moved into `nodes/<plugin>/_router.py` and mount via the plugin-router loop in `main.py`; the explicit `app.include_router(<plugin>.router)` calls and `from routers import <plugin>` imports in `main.py` are gone. **`register_router(router, name=...)` is the new sibling helper to `register_ws_handlers` (same file: `services/ws_handler_registry.py`)** — six generic registries total now (ws_handlers, router, filter_builder, trigger_precheck, service_refresh, output_schema). **`Credential.validate(data) -> dict` + `Credential._probe(api_key) -> ProbeResult` is the new shared validator scaffold** in `services/plugin/credential.py` — replaces the per-router `_SPECIAL_PROVIDER_VALIDATORS` dict; one `_LLMApiKey._probe` method serves all 9 cloud LLM providers, dedicated `_probe` overrides handle Maps + Apify, `_LocalLLM.validate` overrides for Ollama / LM Studio's 2-storage edge case. **`tests/test_plugin_self_containment.py` locks the contract** with 7 invariant classes (forbidden-imports / no-router-outside-nodes / per-plugin self-registration / registry-API sanity / stale-paths-absent / main.py-does-not-mount / WS_HANDLERS-non-empty); same `inspect.getsource` introspection style as `test_credential_broadcasts.py`. Wire format unchanged — frontend WS message-type strings (`whatsapp_status`, `twitter_oauth_login`, `google_oauth_status`, `android_relay_connect`, etc.) and HTTP route paths (`/api/twitter/callback`, `/api/google/callback`, `/api/android/*`) are byte-identical post-migration.
-- **Typed CloudEvents factory pattern for new broadcasts** (b6aecd3): every new server→FE broadcast follows the recipe locked by `broadcast_credential_event` and `broadcast_agent_progress`. (1) Add a typed classmethod on `WorkflowEvent` (`services/events/envelope.py`) — convention: `source = "opencompany://services/<area>"`, `type = "<area>.<event>"`, `subject = <primary entity id>`, `workflow_id` extension if scoped. (2) Add a `broadcaster.broadcast_<area>_<event>(...)` method on `StatusBroadcaster` that builds the envelope and emits via `broadcast({type: "<wire_key>", data: event.model_dump(mode="json")})`. Wire key is typically the event topic with dots → underscores (`agent.progress` → `agent_progress`). (3) FE handler in `WebSocketContext.tsx` switch routes the wire key, parses `data` as `WorkflowEvent<TInner>`, writes the inner payload to whichever store consumes it (`nodeStatusStore` for per-node state, etc.). (4) Add a parity test in `tests/test_status_broadcasts.py` via `inspect.getsource` introspection. **Forbidden**: emitting raw-dict payloads through `update_node_status` for any new event type — that channel is allowlisted via `_LEGACY_RAW_DICT_CALLSITES` and the allowlist is closed.
-- **Plugin-folder location for plugin-specific CloudEvents factories** (RFC §6.4): when a typed event is owned by one plugin (telegram, whatsapp, android, email, google, master_skill, agent_builder, webhook_trigger, chat_trigger, agent), the factory + `broadcast_<event>` wrapper live in [`server/nodes/<plugin>/_events.py`](./server/nodes), NOT on `WorkflowEvent` / `StatusBroadcaster` directly. Telegram's [`_events.py`](./server/nodes/telegram/_events.py) is the canonical template — `broadcast_telegram_status` constructs the envelope via a plain factory function and calls `get_status_broadcaster().broadcast(...)` itself. Latest example: [`server/nodes/skill/master_skill/_events.py`](./server/nodes/skill/master_skill/_events.py) (`broadcast_skill_lifecycle("created" \| "updated" \| "deleted" \| "content_saved", name=..., **data_extra)`) — replaces four raw-dict broadcasts in `handle_create_user_skill` / `handle_update_user_skill` / `handle_delete_user_skill` / `handle_save_skill_content` (the last one was previously silent). FE routes wire key `skill_lifecycle` to invalidate `userSkills` + `folderSkills` queries and drop the `skillContent` cache on delete + content_saved so the Master Skill panel refreshes live across every connected client. Cross-cutting events (credential, workflow_lifecycle, agent_progress, node_parameters_updated) keep their `WorkflowEvent` classmethods + `StatusBroadcaster` wrappers — only plugin-scoped events move to the plugin folder.
+- **Typed CloudEvents factory pattern for new broadcasts** (b6aecd3): every new server→FE lifecycle broadcast follows the recipe locked by `broadcast_credential_event`, `broadcast_agent_progress`, and `broadcast_agent_capability`. (1) Add a typed factory — convention: `source = "opencompany://services/<area>"`, reverse-DNS `type = "com.opencompany.<area>.<event>"`, and `subject = <exact primary entity id>`. Put snake_case workflow/execution scope inside `data`; CloudEvents extension attribute names MUST be lowercase-alphanumeric, so the historical top-level `workflow_id`/`trigger_node_id`/`correlation_id` fields are compatibility debt and are forbidden on new contracts. (2) Add a broadcaster wrapper that emits `broadcast({type: "<wire_key>", data: event.model_dump(mode="json", exclude_none=True)})`. (3) FE validates `specversion`, ID/source/type, subject ownership, and event-specific payload invariants, deduplicates by `(source,id)`, then writes only the exact scoped entity. (4) Add contract tests in `test_events.py` and keep `tests/test_status_broadcasts.py`'s raw-callsite allowlist empty. Raw `node_status` remains allowed only as the established high-frequency latest-state/reconnect projection paired with a typed lifecycle occurrence; it is not the event of record.
+- **Plugin-folder location for plugin-specific CloudEvents factories** (RFC §6.4): when a typed event is owned by one plugin (telegram, whatsapp, android, email, google, master_skill, agent_builder, webhook_trigger, chat_trigger, agent), the factory + `broadcast_<event>` wrapper live in [`server/nodes/<plugin>/_events.py`](./server/nodes), NOT on `WorkflowEvent` / `StatusBroadcaster` directly. Telegram's [`_events.py`](./server/nodes/telegram/_events.py) is the canonical template — `broadcast_telegram_status` constructs the envelope via a plain factory function and calls `get_status_broadcaster().broadcast(...)` itself. Latest example: [`server/nodes/skill/master_skill/_events.py`](./server/nodes/skill/master_skill/_events.py) (`broadcast_skill_lifecycle("created" \| "updated" \| "deleted" \| "content_saved", name=..., **data_extra)`) — replaces four raw-dict broadcasts in `handle_create_user_skill` / `handle_update_user_skill` / `handle_delete_user_skill` / `handle_save_skill_content` (the last one was previously silent). FE routes wire key `skill_lifecycle` to invalidate `userSkills` + `folderSkills` queries and drop the `skillContent` cache on delete + content_saved so the Master Skill panel refreshes live across every connected client. Cross-cutting events (credential, workflow_lifecycle, agent_progress, agent_capability, node_parameters_updated) keep their `WorkflowEvent` classmethods + `StatusBroadcaster` wrappers — only plugin-scoped events move to the plugin folder.
- **Operator-metadata fields in credential panels** (f746ddf): when a credential panel needs a non-credential follow-up field (e.g. Telegram bot token + owner chat id), declare it as a second entry in the provider's `fields` array in `server/config/credential_providers.json`. The first field stays the validate/connect target; subsequent fields render below as plain text inputs via `SecondaryFieldRow` in `ApiKeyPanel.tsx` (shadcn `Input` + `Label` + `<ActionButton intent="save">`). Each field carries an optional `help` slot (`FieldDef.help` / `ServerFieldDef.help`) for always-visible explanatory text under the input. Save writes via `panel.actions.save(field.key, value)` → `auth_service.store_api_key` (which is permissive about provider string). The credential class must declare the new key in `extra_fields` (`Credential` subclass attribute) so the storage layer accepts it. Reference: `telegram_owner_chat_id` field.
- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.
- **Supervisor Job Object loud-failure (cli/tree.py + cli/supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in the root `pyproject.toml` (where `opencompany-cli` lives — `cli/pyproject.toml` was removed as a stale duplicate) carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / pnpm / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index b60f6cd0..f74d111c 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -221,7 +221,7 @@ const DashboardContent: React.FC = () => {
} = useWorkflowManagement();
const { collapsedSections, searchQuery, setSearchQuery, toggleSection } = useComponentPalette();
- const { saveNodeParameters, getAllNodeParameters, executeWorkflow, deployWorkflow, getWorkflowStatus, nodeStatuses, deploymentStatus, workflowControlStatuses, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, getWorkflowControlStatus, workflowLock, isConnected, isReady, sendRequest } = useWebSocket();
+ const { saveNodeParameters, getAllNodeParameters, executeWorkflow, deployWorkflow, getWorkflowStatus, nodeStatuses, deploymentStatus, workflowControlStatuses, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, getWorkflowControlStatus, workflowLock, isConnected, isReady, sendRequest, clearNodeStatus } = useWebSocket();
const applyUIDefaults = useAppStore((state) => state.applyUIDefaults);
// Workflows list: server-owned data, cached by TanStack Query.
@@ -248,7 +248,7 @@ const DashboardContent: React.FC = () => {
workflowLock.workflow_id === currentWorkflow?.id;
const [globalModelDefaults, setGlobalModelDefaults] = React.useState<{ provider: string; model: string } | null>(null);
const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new' });
- const { onConnect: baseOnConnect, onNodesDelete, onEdgesDelete: baseOnEdgesDelete } = useReactFlowNodes({ setNodes, setEdges });
+ const { onConnect: baseOnConnect, onNodesDelete, onEdgesDelete: baseOnEdgesDelete } = useReactFlowNodes({ setNodes, setEdges, clearNodeStatus });
const { onConnect, onEdgesDelete } = useAutoSkillEdges({
baseOnConnect,
baseOnEdgesDelete,
diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsx
index 5c6bc833..c1ea6a7b 100644
--- a/client/src/components/AIAgentNode.tsx
+++ b/client/src/components/AIAgentNode.tsx
@@ -24,6 +24,8 @@ const PHASE_CONFIG: Record<string, { icon: string; label: string; color: string
invoking_llm: { icon: '🧠', label: 'Thinking...', color: 'var(--node-trigger)' },
executing_tool: { icon: '⚡', label: 'Using Tool', color: 'var(--node-trigger)' },
tool_completed: { icon: '✓', label: 'Tool Done', color: 'var(--success)' },
+ loading_skill: { icon: '📚', label: 'Loading Skill', color: 'var(--node-agent)' },
+ skill_loaded: { icon: '✓', label: 'Skill Loaded', color: 'var(--success)' },
saving_memory: { icon: '💾', label: 'Saving Memory', color: 'var(--node-agent)' },
};
@@ -76,6 +78,37 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
const isExecuting = nodeStatus?.status === 'executing';
const currentPhase = nodeStatus?.data?.phase as string | undefined;
const phaseConfig = currentPhase ? PHASE_CONFIG[currentPhase] : null;
+ const activeSkills = (nodeStatus?.data?.active_skills as Array<{ name: string; state: string }> | undefined) ?? [];
+ const lastSkills = (nodeStatus?.data?.last_skills as Array<{ name: string; state: string }> | undefined) ?? [];
+ const currentSkill = activeSkills.find((skill) => skill.state === 'loading') ?? activeSkills[activeSkills.length - 1];
+ const previousSkill = lastSkills[lastSkills.length - 1];
+ const activeToolName = nodeStatus?.data?.tool_name as string | undefined;
+ const lastToolName = nodeStatus?.data?.last_tool_name as string | undefined;
+ const lastCapability = nodeStatus?.data?.last_capability as
+ | { kind?: 'skill' | 'tool'; name?: string; state?: string }
+ | undefined;
+ const currentOrdinaryTool =
+ (currentPhase === 'executing_tool' || currentPhase === 'tool_completed') && activeToolName && activeToolName !== 'Skill'
+ ? activeToolName
+ : undefined;
+ // Capability text is live turn state, not node history. Sticky summaries
+ // survive fast intermediate broadcasts so normal agents have time to paint
+ // them, but a terminal/idle agent must return to its configured subtitle.
+ // This also prevents several previously-used agents from looking as though
+ // they are all using the same capability at once.
+ const capabilityLabel = !isExecuting
+ ? undefined
+ : currentOrdinaryTool
+ ? `tool ${currentOrdinaryTool}`
+ : currentSkill
+ ? `skill ${currentSkill.name}`
+ : lastCapability?.kind && lastCapability?.name
+ ? `${lastCapability.kind} ${lastCapability.name}`
+ : previousSkill
+ ? `skill ${previousSkill.name}`
+ : lastToolName
+ ? `tool ${lastToolName}`
+ : undefined;
// Live agent-loop counter. Backed by the `agent_progress` CloudEvents
// broadcast (services/ai.py:_run_agent_loop emits one per iteration via
// the progress_callback). `iteration` advances per turn; `max_iterations`
@@ -247,7 +280,9 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
lineHeight: '1.2', marginBottom: theme.spacing.lg, transition: 'color 0.3s ease',
overflowWrap: 'break-word', wordBreak: 'break-word', whiteSpace: 'normal',
textAlign: 'center',
- }}>{isExecuting && phaseConfig ? phaseConfig.label : subtitle}</div>
+ }} aria-label={capabilityLabel ? 'Current agent capability' : undefined} title={capabilityLabel}>
+ {capabilityLabel || (isExecuting && phaseConfig ? phaseConfig.label : subtitle)}
+ </div>
{/* Left inputs below the main one (Memory / Task / etc.) */}
{leftInputs.map(h => (
diff --git a/client/src/components/ToolkitNode.tsx b/client/src/components/ToolkitNode.tsx
index 06780e03..c139d030 100644
--- a/client/src/components/ToolkitNode.tsx
+++ b/client/src/components/ToolkitNode.tsx
@@ -16,8 +16,9 @@ import { resolveNodeDescription } from '../lib/nodeSpec';
import { NodeIcon } from '../assets/icons';
import { useNodeSpec } from '../lib/nodeSpec';
import { useAppTheme } from '../hooks/useAppTheme';
-import { useWebSocket } from '../contexts/WebSocketContext';
+import { useNodeStatus } from '../contexts/WebSocketContext';
import EditableNodeLabel from './ui/EditableNodeLabel';
+import { Badge } from '@/components/ui/badge';
const ToolkitNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
const theme = useAppTheme();
@@ -25,10 +26,13 @@ const ToolkitNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
const setRenamingNodeId = useAppStore((s) => s.setRenamingNodeId);
const updateNodeData = useAppStore((s) => s.updateNodeData);
- // Get node status from WebSocket context
- const { getNodeStatus } = useWebSocket();
- const nodeStatus = getNodeStatus(id);
+ // Subscribe to this exact workflow/node status slot. The imperative
+ // getNodeStatus snapshot does not trigger a render when Zustand receives a
+ // skill lifecycle event, so Master Skill glow/badges would update only after
+ // some unrelated canvas render.
+ const nodeStatus = useNodeStatus(id);
const executionStatus = nodeStatus?.status || 'idle';
+ const activeSkills = (nodeStatus?.data?.active_skills as Array<{ name: string; state: string }> | undefined) ?? [];
// Wave 6 Phase 3e: backend NodeSpec -> legacy fallback
const definition = resolveNodeDescription(type || '');
@@ -204,6 +208,15 @@ const ToolkitNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
onLabelChange={handleLabelChange}
onActivate={handleLabelActivate}
/>
+ {activeSkills.length > 0 && (
+ <div className="mt-1 flex max-w-40 flex-wrap justify-center gap-1" aria-label="Master Skill activity">
+ {activeSkills.map((skill) => (
+ <Badge key={`${skill.name}-${skill.state}`} variant="outline" className="max-w-40 truncate text-[9px]">
+ skill {skill.name}
+ </Badge>
+ ))}
+ </div>
+ )}
</div>
);
};
diff --git a/client/src/components/parameterPanel/MasterSkillEditor.tsx b/client/src/components/parameterPanel/MasterSkillEditor.tsx
index 3a40e95d..8887bc99 100644
--- a/client/src/components/parameterPanel/MasterSkillEditor.tsx
+++ b/client/src/components/parameterPanel/MasterSkillEditor.tsx
@@ -46,7 +46,7 @@ import {
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { useWebSocket } from '../../contexts/WebSocketContext';
+import { useNodeStatus, useWebSocket } from '../../contexts/WebSocketContext';
import { NodeIcon } from '../../assets/icons';
import { cn } from '@/lib/utils';
import { useFolderSkills } from '../../hooks/useFolderSkills';
@@ -58,6 +58,7 @@ interface SkillConfig {
enabled: boolean;
instructions: string;
isCustomized: boolean;
+ required?: boolean;
}
interface MasterSkillConfig {
@@ -105,6 +106,7 @@ interface PendingSkillData {
// tears down the React Flow canvas.
const EMPTY_USER_SKILLS: UserSkill[] = [];
const EMPTY_FOLDER_SKILLS: AvailableSkill[] = [];
+const REQUIRED_ASSISTANT_SKILL = 'skill';
interface MasterSkillEditorProps {
skillsConfig: MasterSkillConfig;
@@ -128,6 +130,18 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
nodeId
}) => {
const { sendRequest } = useWebSocket();
+ const masterSkillStatus = useNodeStatus(nodeId || '');
+ const displayedSkillActivity = useMemo(() => {
+ const active = (masterSkillStatus?.data?.active_skills as Array<{ name: string; state: string }> | undefined) ?? [];
+ if (active.length > 0) return active;
+ return (masterSkillStatus?.data?.last_skills as Array<{ name: string; state: string }> | undefined) ?? [];
+ }, [masterSkillStatus?.data?.active_skills, masterSkillStatus?.data?.last_skills]);
+ const activeSkillStates = useMemo(
+ () => new Map(
+ displayedSkillActivity.map((item) => [item.name, item.state]),
+ ),
+ [displayedSkillActivity],
+ );
const [selectedSkillName, setSelectedSkillName] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
@@ -274,6 +288,32 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
}
}, [queryClient, sendRequest]);
+ // Existing Master Skill nodes may predate the required Skill-tool entry.
+ // Once the assistant catalogue is available, persist the authoritative
+ // prompt into skills_config so the checkbox and editor behave exactly like
+ // every other skill row rather than relying on a frontend-only illusion.
+ useEffect(() => {
+ if (skillFolder !== 'assistant') return;
+ if (!folderSkills.some((skill) => skill.skillName === REQUIRED_ASSISTANT_SKILL)) return;
+ const existing = skillsConfig[REQUIRED_ASSISTANT_SKILL];
+ if (existing?.enabled && existing?.instructions) return;
+ let cancelled = false;
+ void fetchSkillContent(REQUIRED_ASSISTANT_SKILL).then((instructions) => {
+ if (cancelled || !instructions) return;
+ onConfigChange({
+ ...skillsConfig,
+ [REQUIRED_ASSISTANT_SKILL]: {
+ ...existing,
+ enabled: true,
+ required: true,
+ instructions: existing?.instructions || instructions,
+ isCustomized: existing?.isCustomized || false,
+ },
+ });
+ });
+ return () => { cancelled = true; };
+ }, [skillFolder, folderSkills, skillsConfig, fetchSkillContent, onConfigChange]);
+
const getCachedSkillContent = useCallback(
(skillName: string): string | undefined => queryClient.getQueryData<string>(['skillContent', skillName]),
[queryClient],
@@ -648,8 +688,10 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
{filteredSkills.map((skill) => {
const config = skillsConfig[skill.skillName];
const isSelected = selectedSkillName === skill.skillName && !isCreatingNew;
- const isEnabled = config?.enabled || false;
+ const isRequired = skillFolder === 'assistant' && skill.skillName === REQUIRED_ASSISTANT_SKILL;
+ const isEnabled = isRequired || config?.enabled || false;
const isCustomized = config?.isCustomized || false;
+ const runtimeState = activeSkillStates.get(skill.skillName);
return (
<div
@@ -676,6 +718,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
<div className="flex w-full items-center gap-2">
<Checkbox
checked={isEnabled}
+ disabled={isRequired}
onCheckedChange={(checked) => {
handleToggleSkill(skill.skillName, checked === true);
}}
@@ -701,6 +744,25 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
</Tooltip>
</TooltipProvider>
)}
+ {runtimeState && (
+ <DSBadge
+ className={cn(
+ 'h-4 px-1 text-[10px]',
+ runtimeState === 'failed'
+ ? 'bg-destructive/20 text-destructive'
+ : runtimeState === 'loading'
+ ? 'bg-info/20 text-info'
+ : 'bg-success/20 text-success',
+ )}
+ >
+ {runtimeState === 'loading' ? 'Loading' : runtimeState === 'failed' ? 'Failed' : runtimeState === 'used' ? 'Used' : 'Loaded'}
+ </DSBadge>
+ )}
+ {isRequired && (
+ <DSBadge className="h-4 bg-agent/20 px-1 text-[10px] text-agent">
+ Required
+ </DSBadge>
+ )}
{skill.isUserSkill && (
<DSBadge className="h-4 bg-info/20 px-1 text-[10px] text-info">
Custom
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index fad3eb3b..0de4caca 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -33,7 +33,7 @@ import TaskManagerPanel from './TaskManagerPanel';
import TeamMonitorPanel from './TeamMonitorPanel';
import ProcessManagerPanel from './ProcessManagerPanel';
import { useAppStore } from '../../store/useAppStore';
-import { useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';
+import { useNodeStatus, useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';
import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';
import { nodeParamsQueryKey, type NodeParametersResponse } from '../../hooks/useNodeParamsQuery';
import { folderSkillsQueryKey, type AvailableSkill } from '../../hooks/useFolderSkills';
@@ -66,11 +66,13 @@ const Stat: React.FC<{ title: React.ReactNode; value: React.ReactNode }> = ({ ti
interface ConnectedSkill {
id: string;
+ skillName: string;
name: string;
type: string;
icon: string;
description: string;
color: string;
+ instructions?: string;
}
interface MiddleSectionProps {
@@ -93,6 +95,14 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
isLoadingParameters = false,
executionResults = []
}) => {
+ const agentNodeStatus = useNodeStatus(nodeId);
+ const skillRuntimeStates = useMemo(() => {
+ const active = (agentNodeStatus?.data?.active_skills as Array<{ name: string; state: string }> | undefined) ?? [];
+ const recent = active.length > 0
+ ? active
+ : ((agentNodeStatus?.data?.last_skills as Array<{ name: string; state: string }> | undefined) ?? []);
+ return new Map(recent.map((item) => [item.name, item.state]));
+ }, [agentNodeStatus?.data?.active_skills, agentNodeStatus?.data?.last_skills]);
const currentWorkflow = useAppStore((s) => s.currentWorkflow);
const { clearMemory, resetSkill, sendRequest, getNodeParameters, compactionStats: contextCompactionStats, updateCompactionStats } = useWebSocket();
@@ -437,11 +447,13 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const def = resolveNodeDescription(nodeType);
skills.push({
id: edge.source,
+ skillName: String(sourceNode?.data?.skillName || sourceNode?.data?.skill_name || nodeType),
name: sourceNode?.data?.label || def?.displayName || nodeType,
type: nodeType,
icon: def?.icon || '',
description: def?.description || '',
color: (def?.defaults?.color as string) || 'var(--node-agent)',
+ instructions: String(sourceNode?.data?.instructions || sourceNode?.data?.parameters?.instructions || ''),
});
}
return skills;
@@ -479,11 +491,13 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const meta = skillMetadataByName[skillName];
skills.push({
id: `${edge.source}_${skillName}`,
+ skillName,
name: meta?.displayName || skillName,
type: 'masterSkill',
icon: meta?.icon || '',
description: meta?.description || '',
color: meta?.color || 'var(--node-agent)',
+ instructions: String(config?.instructions || ''),
});
}
}
@@ -851,7 +865,9 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
</div>
) : (
<div className="flex flex-col gap-2">
- {expandedConnectedSkills.map((skill) => (
+ {expandedConnectedSkills.map((skill) => {
+ const runtimeState = skillRuntimeStates.get(skill.skillName);
+ return (
<div
key={skill.id}
className="flex items-start gap-3 rounded-md border border-border bg-muted/40 p-3"
@@ -877,10 +893,23 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
<div className="line-clamp-2 break-words text-xs text-muted-foreground">
{skill.description}
</div>
+ {skill.instructions && (
+ <details className="mt-2 text-xs">
+ <summary className="cursor-pointer font-medium text-fg-muted hover:text-fg-default">
+ Skill prompt
+ </summary>
+ <pre className="mt-2 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-bg-panel p-2 font-mono text-[11px] leading-relaxed text-fg-muted">
+ {skill.instructions}
+ </pre>
+ </details>
+ )}
</div>
- <Badge variant="success" className="shrink-0">Active</Badge>
+ <Badge variant="success" className="shrink-0">
+ {runtimeState === 'loading' ? 'Loading' : runtimeState === 'failed' ? 'Failed' : runtimeState === 'used' ? 'Used' : runtimeState === 'loaded' ? 'Loaded' : 'Active'}
+ </Badge>
</div>
- ))}
+ );
+ })}
</div>
)}
</AccordionContent>
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 9c9b3f19..7f5a0fe3 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -21,7 +21,14 @@ import { queryKeys } from '../lib/queryConfig';
import { invalidateCatalogue } from '../hooks/useCatalogueQuery';
import { nodeParamsQueryKey } from '../hooks/useNodeParamsQuery';
import { WORKFLOWS_QUERY_KEY } from '../hooks/useWorkflowsQuery';
-import type { WorkflowEvent } from '../types/cloudEvents';
+import type {
+ AgentCapabilityLifecycleData,
+ WorkflowEvent,
+} from '../types/cloudEvents';
+import {
+ cloudEventIdentity,
+ isAgentCapabilityEvent,
+} from '../types/cloudEvents';
import { WS_CLOSE, WS_RECONNECT } from '../lib/connectionConfig';
import { todoQueryKeyFromEvent } from '../lib/todoQuery';
import {
@@ -595,6 +602,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [workflowStatus, setWorkflowStatus] = useState<WorkflowStatus>(defaultWorkflowStatus);
const [deploymentStatus, setDeploymentStatus] = useState<DeploymentStatus>(defaultDeploymentStatus);
const [workflowControlStatuses, setWorkflowControlStatuses] = useState<Record<string, WorkflowControlStatus>>({});
+ const workflowControlStatusesRef = useRef<Record<string, WorkflowControlStatus>>({});
const [workflowLock, setWorkflowLock] = useState<WorkflowLock>(defaultWorkflowLock);
// Per-workflow compaction stats: workflow_id -> session_id -> CompactionStats (n8n pattern)
const [allCompactionStats, setAllCompactionStats] = useState<Record<string, Record<string, CompactionStats>>>({});
@@ -613,6 +621,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// listen for ad-hoc broadcasts without growing the switch statement
// or the context state shape.
const eventListenersRef = useRef<Map<string, Set<(data: any) => void>>>(new Map());
+ // CloudEvents duplicates are identified by (source, id), per CE 1.0.
+ // Bound the insertion-ordered set so a long-running editor cannot grow it
+ // without limit; retries normally arrive close together.
+ const processedCloudEventsRef = useRef<Set<string>>(new Set());
// Pending-send queue for backpressure + replay across reconnects.
// Drained inside `ws.onopen` after the init burst. Source of truth
// for currentWorkflowId is `useAppStore.getState().currentWorkflow?.id`
@@ -623,6 +635,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// do not read from elsewhere.
const previousWorkflowIdForSwitchRef = useRef<string | undefined>(currentWorkflowId);
+ useEffect(() => {
+ workflowControlStatusesRef.current = workflowControlStatuses;
+ }, [workflowControlStatuses]);
+
// Detect workflow switches and refresh deployment status from the backend.
// The single source of truth for currentWorkflowId is `useAppStore`; the
// node-status store is synced from Dashboard.tsx, not from here.
@@ -1004,6 +1020,159 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
+ case 'agent_capability': {
+ // Canonical CloudEvents v1.0 lifecycle occurrence. The outer
+ // `agent_capability` key is only the WebSocket transport route;
+ // identity, type and payload ownership come from the envelope.
+ const envelope = data;
+
+ // Do not infer ownership from the legacy outer message or a target
+ // id. CloudEvents `subject` is the exact invoking agent, and must
+ // agree with the safe application payload before anything is
+ // projected into node state.
+ if (!isAgentCapabilityEvent(envelope)) {
+ console.warn('[WebSocket] Ignoring invalid agent capability CloudEvent');
+ break;
+ }
+ const payload: AgentCapabilityLifecycleData = envelope.data;
+
+ // CloudEvents defines (source, id) as the duplicate-detection key.
+ // Keep a small insertion-ordered window: Temporal activity retries
+ // can redeliver the same occurrence, while distinct lifecycle
+ // stages deliberately have distinct ids.
+ const duplicateKey = cloudEventIdentity(envelope);
+ if (processedCloudEventsRef.current.has(duplicateKey)) break;
+ processedCloudEventsRef.current.add(duplicateKey);
+ if (processedCloudEventsRef.current.size > 1000) {
+ const oldest = processedCloudEventsRef.current.values().next().value;
+ if (oldest) processedCloudEventsRef.current.delete(oldest);
+ }
+
+ // Ignore late delivery from an archived/reset generation. Prefer
+ // the root execution identity because descendants have their own
+ // child execution ids.
+ const activeControl = workflowControlStatusesRef.current[payload.workflow_id];
+ if (
+ activeControl?.root_execution_id &&
+ payload.root_execution_id &&
+ activeControl.root_execution_id !== payload.root_execution_id
+ ) {
+ break;
+ }
+
+ const store = useNodeStatusStore.getState();
+ const previous =
+ store.allStatuses[payload.workflow_id]?.[payload.agent_node_id] ||
+ ({} as NodeStatus);
+ const previousData = previous.data || {};
+ const previousSkills = (
+ previousData.active_skills as Array<{ name: string; state: string }> | undefined
+ ) ?? [];
+ let nextSkills = previousSkills;
+ let nextData: Record<string, any> = { ...previousData };
+
+ if (payload.capability_kind === 'skill') {
+ if (payload.state === 'cleared') {
+ nextSkills = previousSkills.filter((skill) => skill.name !== payload.capability_name);
+ const previousLastSkills = (
+ previousData.last_skills as Array<{ name: string; state: string }> | undefined
+ ) ?? [];
+ const completedSkill = previousSkills.find(
+ (skill) => skill.name === payload.capability_name,
+ ) ?? previousLastSkills.find(
+ (skill) => skill.name === payload.capability_name,
+ );
+ const completedState = completedSkill?.state === 'failed' ? 'failed' : 'used';
+ nextData = {
+ ...nextData,
+ active_skills: nextSkills,
+ last_skills: [
+ ...previousLastSkills.filter((skill) => skill.name !== payload.capability_name),
+ { name: payload.capability_name, state: completedState },
+ ],
+ last_capability: {
+ kind: 'skill',
+ name: payload.capability_name,
+ state: completedState,
+ },
+ };
+ } else {
+ nextSkills = [
+ ...previousSkills.filter((skill) => skill.name !== payload.capability_name),
+ { name: payload.capability_name, state: payload.state },
+ ];
+ nextData = {
+ ...nextData,
+ phase: payload.state === 'loading' ? 'loading_skill' : 'skill_loaded',
+ active_skills: nextSkills,
+ last_capability: {
+ kind: 'skill',
+ name: payload.capability_name,
+ state: payload.state,
+ },
+ };
+ }
+ } else {
+ nextData = {
+ ...nextData,
+ phase: payload.state === 'started' ? 'executing_tool' : 'tool_completed',
+ tool_name: payload.capability_name,
+ last_tool_name: payload.capability_name,
+ last_capability: {
+ kind: 'tool',
+ name: payload.capability_name,
+ state: payload.state === 'failed' ? 'failed' : 'used',
+ },
+ tool_failed: payload.state === 'failed',
+ };
+ }
+
+ const terminalStatus = previous.status === 'success' || previous.status === 'error';
+ store.setStatus(payload.workflow_id, payload.agent_node_id, {
+ ...previous,
+ status: terminalStatus
+ ? previous.status
+ : payload.capability_kind === 'skill' && payload.state === 'cleared'
+ ? (previous.status || 'idle')
+ : 'executing',
+ workflow_id: payload.workflow_id,
+ data: nextData,
+ });
+
+ // Master Skill is a tool-like target: only the exact connected node
+ // glows while fetching. Loaded/failed/cleared transitions end that
+ // glow; no sibling or similarly-named node is touched.
+ if (payload.capability_kind === 'skill' && payload.target_node_id) {
+ const targetPrevious =
+ store.allStatuses[payload.workflow_id]?.[payload.target_node_id] ||
+ ({} as NodeStatus);
+ const targetData = targetPrevious.data || {};
+ const targetSkills = (
+ targetData.active_skills as Array<{ name: string; state: string }> | undefined
+ ) ?? [];
+ const targetNextSkills = payload.state === 'cleared'
+ ? targetSkills.filter((skill) => skill.name !== payload.capability_name)
+ : [
+ ...targetSkills.filter((skill) => skill.name !== payload.capability_name),
+ { name: payload.capability_name, state: payload.state },
+ ];
+ store.setStatus(payload.workflow_id, payload.target_node_id, {
+ ...targetPrevious,
+ status:
+ payload.state === 'loading'
+ ? 'executing'
+ : payload.state === 'failed'
+ ? 'error'
+ : payload.state === 'cleared'
+ ? 'idle'
+ : 'success',
+ workflow_id: payload.workflow_id,
+ data: { ...targetData, active_skills: targetNextSkills },
+ });
+ }
+ break;
+ }
+
case 'agent_progress': {
// CloudEvents v1.0 envelope from broadcaster.broadcast_agent_progress.
// Inner payload: { node_id, iteration, max_iterations, phase? }.
diff --git a/client/src/hooks/useReactFlowNodes.ts b/client/src/hooks/useReactFlowNodes.ts
index 58306e2b..795169e5 100644
--- a/client/src/hooks/useReactFlowNodes.ts
+++ b/client/src/hooks/useReactFlowNodes.ts
@@ -7,9 +7,10 @@ import { resolveNodeDescription } from '../lib/nodeSpec';
interface UseReactFlowNodesProps {
setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;
setEdges: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;
+ clearNodeStatus?: (nodeId: string) => void | Promise<void>;
}
-export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps) => {
+export const useReactFlowNodes = ({ setNodes, setEdges, clearNodeStatus }: UseReactFlowNodesProps) => {
const selectedNode = useAppStore((s) => s.selectedNode);
const setSelectedNode = useAppStore((s) => s.setSelectedNode);
@@ -168,13 +169,19 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps
(deleted: Node[]) => {
const removable = deleted.filter((node) => node.type !== 'taskManager');
setNodes((nds) => nds.filter((node) => !removable.find((d) => d.id === node.id)));
+ // Node ids can be reused after deletion. Clear the exact backend and
+ // workflow-scoped frontend status slot so a replacement node never
+ // inherits the deleted node's skill/tool capability label.
+ removable.forEach((node) => {
+ void clearNodeStatus?.(node.id);
+ });
// Clear selected node if it was deleted
if (selectedNode && removable.find((d) => d.id === selectedNode.id)) {
setSelectedNode(null);
}
},
- [setNodes, selectedNode, setSelectedNode]
+ [setNodes, selectedNode, setSelectedNode, clearNodeStatus]
);
const onEdgesDelete = useCallback(
diff --git a/client/src/types/__tests__/cloudEvents.test.ts b/client/src/types/__tests__/cloudEvents.test.ts
index 2a384709..06635ffe 100644
--- a/client/src/types/__tests__/cloudEvents.test.ts
+++ b/client/src/types/__tests__/cloudEvents.test.ts
@@ -8,7 +8,12 @@
*/
import { describe, it, expect } from 'vitest';
-import { matchesType, type WorkflowEvent } from '../cloudEvents';
+import {
+ cloudEventIdentity,
+ isAgentCapabilityEvent,
+ matchesType,
+ type WorkflowEvent,
+} from '../cloudEvents';
const sample: WorkflowEvent = {
specversion: '1.0',
@@ -99,7 +104,7 @@ describe('WorkflowEvent shape', () => {
expect(matchesType(legacyEnvelope, 'credential.*')).toBe(true);
});
- it('preserves CloudEvents extension attributes when present', () => {
+ it('preserves legacy extension-shaped compatibility fields when present', () => {
const event: WorkflowEvent = {
...sample,
workflow_id: 'wf_42',
@@ -111,3 +116,45 @@ describe('WorkflowEvent shape', () => {
expect(event.correlation_id).toBe('corr_xyz');
});
});
+
+describe('agent capability CloudEvents', () => {
+ const capability = {
+ specversion: '1.0',
+ id: 'cap-1',
+ source: 'opencompany://services/agent',
+ type: 'com.opencompany.agent.skill.loading',
+ time: '2026-07-20T12:00:00Z',
+ subject: 'agent-1',
+ data: {
+ workflow_id: '7',
+ execution_id: '3',
+ agent_node_id: 'agent-1',
+ author_node_id: 'agent-1',
+ target_node_id: 'master-1',
+ capability_kind: 'skill',
+ capability_name: 'todo-skill',
+ state: 'loading',
+ },
+ };
+
+ it('accepts the exact subject/type/state contract', () => {
+ expect(isAgentCapabilityEvent(capability)).toBe(true);
+ expect(cloudEventIdentity(capability)).toBe('opencompany://services/agent\u0000cap-1');
+ });
+
+ it('rejects spoofed subjects and invalid kind/state pairs', () => {
+ expect(isAgentCapabilityEvent({ ...capability, subject: 'agent-2' })).toBe(false);
+ expect(isAgentCapabilityEvent({
+ ...capability,
+ type: 'com.opencompany.agent.skill.started',
+ data: { ...capability.data, state: 'started' },
+ })).toBe(false);
+ });
+
+ it('rejects a mismatched or non-canonical source', () => {
+ expect(isAgentCapabilityEvent({
+ ...capability,
+ source: 'opencompany://services/other',
+ })).toBe(false);
+ });
+});
diff --git a/client/src/types/cloudEvents.ts b/client/src/types/cloudEvents.ts
index 8c137adc..70c9d3b8 100644
--- a/client/src/types/cloudEvents.ts
+++ b/client/src/types/cloudEvents.ts
@@ -33,14 +33,14 @@
*/
export interface WorkflowEvent<TData = unknown> {
- // CloudEvents v1.0 required fields (ordered to match envelope.py).
+ // CloudEvents v1.0 required context attributes.
specversion: '1.0';
id: string;
source: string;
type: string;
/**
- * ISO 8601 string. The backend serialises `datetime` via Pydantic's
- * `model_dump(mode="json")` which produces RFC 3339 UTC timestamps.
+ * CloudEvents makes `time` optional; OpenCompany's producer model always
+ * supplies it. Pydantic JSON mode serialises it as an RFC 3339 timestamp.
*/
time: string;
subject?: string;
@@ -48,7 +48,9 @@ export interface WorkflowEvent<TData = unknown> {
dataschema?: string;
data: TData;
- // CloudEvents extension attributes used by OpenCompany.
+ // Legacy OpenCompany extension attributes. Their underscores are not
+ // CloudEvents-conformant; new event contracts keep workflow/execution
+ // scope in `data` instead. These remain optional compatibility reads.
// `model_config = ConfigDict(extra="allow")` on the Pydantic side means
// additional fields may appear and should be tolerated; cast through
// `WorkflowEvent<T> & {extra?: unknown}` if you need to read them.
@@ -57,6 +59,76 @@ export interface WorkflowEvent<TData = unknown> {
correlation_id?: string | null;
}
+export type AgentCapabilityKind = 'skill' | 'tool';
+export type AgentCapabilityState =
+ | 'loading'
+ | 'loaded'
+ | 'resource_read'
+ | 'cleared'
+ | 'started'
+ | 'completed'
+ | 'failed';
+
+/** Safe payload for `com.opencompany.agent.(skill|tool).*` events. */
+export interface AgentCapabilityLifecycleData {
+ workflow_id: string;
+ execution_id?: string;
+ root_execution_id?: string;
+ agent_node_id: string;
+ author_node_id: string;
+ target_node_id?: string;
+ capability_kind: AgentCapabilityKind;
+ capability_name: string;
+ state: AgentCapabilityState;
+ action?: string;
+ provider?: string;
+ invocation_source?: string;
+ tool_call_id?: string;
+ duration_ms?: number;
+ returned_characters?: number;
+ token_estimate?: number;
+ content_hash?: string;
+ error_code?: string;
+}
+
+const AGENT_CAPABILITY_STATES: Record<AgentCapabilityKind, ReadonlySet<AgentCapabilityState>> = {
+ skill: new Set(['loading', 'loaded', 'resource_read', 'failed', 'cleared']),
+ tool: new Set(['started', 'completed', 'failed']),
+};
+
+/** Strict consumer guard for the agent-capability CloudEvents contract. */
+export function isAgentCapabilityEvent(
+ value: unknown,
+): value is WorkflowEvent<AgentCapabilityLifecycleData> {
+ if (!value || typeof value !== 'object') return false;
+ const event = value as Partial<WorkflowEvent<Partial<AgentCapabilityLifecycleData>>>;
+ const payload = event.data;
+ if (!payload || typeof payload !== 'object') return false;
+ const kind = payload.capability_kind;
+ const state = payload.state;
+ if (kind !== 'skill' && kind !== 'tool') return false;
+ if (typeof state !== 'string' || !AGENT_CAPABILITY_STATES[kind].has(state as AgentCapabilityState)) {
+ return false;
+ }
+ return (
+ event.specversion === '1.0' &&
+ typeof event.id === 'string' && event.id.length > 0 &&
+ event.source === 'opencompany://services/agent' &&
+ event.type === `com.opencompany.agent.${kind}.${state}` &&
+ typeof payload.workflow_id === 'string' && payload.workflow_id.length > 0 &&
+ typeof payload.agent_node_id === 'string' && payload.agent_node_id.length > 0 &&
+ typeof payload.author_node_id === 'string' &&
+ payload.author_node_id === payload.agent_node_id &&
+ event.subject === payload.agent_node_id &&
+ typeof payload.capability_name === 'string' && payload.capability_name.length > 0
+ );
+}
+
+/** CloudEvents duplicate identity is the tuple `(source, id)`. */
+export function cloudEventIdentity(event: Pick<WorkflowEvent, 'source' | 'id'>): string {
+ return `${event.source}\u0000${event.id}`;
+}
+
const TYPE_PREFIXES = [
'com.opencompany.',
// Accept events persisted or replayed from before the product rename.
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index 310f6949..3d8399b8 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -318,7 +318,8 @@ Env overrides: `TEMPORAL_<QUEUE>_CONCURRENCY` (int) and `TEMPORAL_<QUEUE>_RATE_L
- **Sticky workflow cache** (Wave 18.2, manager worker only): `max_cached_workflows` = local 50 / cloud 500 / self_hosted 100. Cached workflows skip Event-History replay; evictions are a latency cost, not an error.
- **Poller autoscaling** (Wave 18.3): `PollerBehaviorAutoscaling` — manager activity pollers 1-10 (initial 2), workflow pollers 1-20 (initial 2); pool workers 1-5 (initial 1). Invariant per the [worker-performance docs](https://docs.temporal.io/develop/worker-performance): pollers stay below executor slots.
- **Resource-based slot supplier** (Wave 18.4): `ai-heavy` + `browser` (unpredictable workloads) use `ResourceBasedSlotSupplier` targeting 80% host CPU + memory, `minimum_slots=1`, `maximum_slots` = the per-queue concurrency. Requires `temporalio>=1.25.0` (pinned).
-- **Observability interceptors** (Wave 17.3, `services/temporal/_interceptors.py`): `activity_retry` WARN when `activity.info().attempt > 1` — the "worker died and Temporal re-dispatched" signal; `workflow_start` guarded by `workflow.unsafe.is_replaying()`.
+- **SDK tracing interceptor ownership**: `TracingInterceptor` is registered exactly once on the shared `Client.connect(...)`. The Temporal Python SDK automatically prepends compatible client interceptors to every `Worker` built from that client. Worker constructors must not repeat `TracingInterceptor`; doing so creates paired OpenTelemetry spans for one execution.
+- **Application observability interceptor** (Wave 17.3, `services/temporal/_interceptors.py`): workers explicitly register `ObservabilityWorkerInterceptor` for `activity_retry` WARN logs when `activity.info().attempt > 1` — the "worker died and Temporal re-dispatched" signal — and replay-guarded `workflow_start` logs. This is separate from SDK tracing and remains worker-owned.
- **Periodic activity heartbeat** (Wave 17.6, `plugin/base.py::as_activity`): 30s background beat during long bodies so a laptop-sleep crash is detected within one `heartbeat_timeout` (2 min) instead of `start_to_close` (10 min).
- **Cron catch-up bound** (Wave 17.1, `services/temporal/schedules.py`): `SchedulePolicy(catchup_window=24h)` + `SKIP` overlap — a laptop offline a week does not replay 168 hourly ticks on wake.
- **One-shot LLM-step retry** (Wave 17.2): `LLM_STEP_RETRY(maximum_attempts=1)` on `agent.execute_llm_step.v1` — LLM calls are not idempotent; the workflow surfaces the failure instead of silently re-billing the prompt. `agent.refresh_tools.v1` deliberately keeps 3 attempts (idempotent canvas rebuild).
@@ -581,6 +582,51 @@ One supervisor-build-time env var (read inside `_temporal_specs.py`, not in `Set
The Web UI is at http://localhost:8080; the UI's HTTP API is served at http://localhost:8233.
+### Reading Temporal tracing output
+
+The compact OpenTelemetry formatter intentionally places one completed span on
+one line. Several lines for a single node are normal because they describe
+different layers of the same execution:
+
+| Span or log | Layer and interpretation |
+|---|---|
+| `StartActivity:<activity>` | Workflow-side scheduling span; propagates trace context but does not execute the node body |
+| `RunActivity:<activity>` | Worker-side invocation span covering the activity attempt |
+| `node.<type>.execute` | OpenCompany application span around the plugin's `execute()` body |
+| `CompleteWorkflow:AgentWorkflow` | Agent child workflow reached a terminal state |
+| `CompleteWorkflow:MachinaWorkflow` | Parent graph workflow reached a terminal state |
+
+`CompleteWorkflow ... 0ms` is expected. Temporal creates the completion span at
+one replay-safe workflow timestamp, so its duration is not the workflow's
+wall-clock runtime. An `AgentWorkflow` completion and a `MachinaWorkflow`
+completion are also separate parent/child lifecycle events.
+
+Exact adjacent pairs are not expected. If `StartActivity`, `RunActivity`, or
+`CompleteWorkflow` appears twice with the same operation name,
+`temporalWorkflowID`, `temporalRunID`, and (when present)
+`temporalActivityID`, inspect interceptor ownership before investigating task
+retries. The shared client already carries `TracingInterceptor`, and the SDK
+prepends it to workers; adding a second instance to `Worker(...,
+interceptors=...)` creates two nested spans with the same Temporal attributes.
+The compact formatter does not print OpenTelemetry span IDs, which makes those
+distinct spans look byte-for-byte identical.
+
+Verification checklist:
+
+1. `Client.connect(...)` contains one `TracingInterceptor`.
+2. Manager, pool, standalone, and test worker constructors do not add another;
+ their explicit list contains `ObservabilityWorkerInterceptor` and any
+ distinct plugin interceptors only.
+3. Temporal Event History contains one activity attempt unless a real retry
+ occurred.
+4. The application log contains one `node.<type>.execute` span for one node-body
+ invocation.
+
+After correcting duplicate instrumentation, one `StartActivity`, one
+`RunActivity`, and one application node span may still appear for the same
+activity. Those are expected scheduling, worker, and application layers—not
+duplicate execution.
+
```bash
# Temporal Web UI
open http://localhost:8080
diff --git a/docs-internal/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md b/docs-internal/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md
index 5101295c..c2bedcd8 100644
--- a/docs-internal/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md
+++ b/docs-internal/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md
@@ -127,6 +127,12 @@ Default `True`; invariant `test_temporal_worker_pool_enabled_defaults_true`; doc
### 17.3 `ObservabilityInterceptor`
NEW `temporal/_interceptors.py` (~50 LOC): `ActivityObservabilityInterceptor` (log `activity_start` / `activity_retry` when `activity.info().attempt > 1` / `activity_end` + outcome), `WorkflowObservabilityInterceptor` (log `workflow_start` guarded by `not workflow.unsafe.is_read_only()` — replay-safe per SDK docs), `ObservabilityWorkerInterceptor` wiring class. Pass `interceptors=[...]` to manager Worker (L159-181) + pool Worker (L334-341).
+
+**Implemented ownership invariant**: the worker list above refers to
+`ObservabilityWorkerInterceptor` only. SDK `TracingInterceptor` is owned by the
+shared Temporal client and inherited automatically by workers; repeating it in
+the worker list produces duplicate OpenTelemetry spans for one execution.
+
**Verify**: kill worker mid-activity, restart → one `activity_retry` log at attempt=2.
### 17.4 `DEPLOYMENT_MODE` + worker identity
diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.md
index 59c692b6..561dbe2c 100644
--- a/docs-internal/agent_architecture.md
+++ b/docs-internal/agent_architecture.md
@@ -208,26 +208,53 @@ if skill_type == 'masterSkill':
if not skill_cfg.get('enabled', False):
continue # Skip disabled skills
- # DB-first: use stored instructions
- instructions = skill_cfg.get('instructions', '')
-
- if not instructions:
- # Fallback: load from SKILL.md on disk
- skill = skill_loader.load_skill(skill_key)
- if skill:
- instructions = skill.instructions
-
skill_data.append({
'node_id': f"{source_node_id}_{skill_key}", # Unique composite ID
+ 'master_skill_node_id': source_node_id,
'node_type': 'masterSkill',
'skill_name': skill_key,
- 'parameters': {'instructions': instructions, 'skillName': skill_key},
+ 'description': metadata.description,
+ # Customized instructions remain authoritative but are not put in
+ # the initial prompt for standard skills.
+ 'parameters': {'instructions': skill_cfg.get('instructions', '')},
'label': skill_key
})
```
One Master Skill node with 5 enabled skills produces 5 separate `skill_data` entries.
+Standard entries use progressive disclosure. They do not alter the agent system
+prompt. Their bounded name/description catalogue is carried by the dynamically
+bound provider-neutral `Skill` tool, using the same contract as other connected
+tool nodes.
+
+The Assistant folder contains a required `skill` entry whose editable SKILL.md
+body teaches use of that tool. Master Skill defaults and legacy expansion keep
+it enabled, so the row appears checked as **Skill** beside the other Assistant
+skills. This makes the usage prompt visible/configurable on the node instead of
+hardcoding it into every agent prompt.
+`Skill.load` returns authoritative instructions and a resource manifest;
+`read_resource` and `search_resource` provide bounded access to declared text
+files after loading. Personality skills are the sole eager-body exception.
+Duplicate enabled names across connected Master Skill nodes fail with
+`DUPLICATE_CONNECTED_SKILL_NAME` before the first model call.
+
+The runtime revalidates the connected descriptor on each call, keys loaded-body
+deduplication by workflow execution and agent, and emits sanitized CloudEvents
+`com.opencompany.agent.skill.loading|loaded|resource_read|failed|cleared`.
+Ordinary tools emit the parallel
+`com.opencompany.agent.tool.started|completed|failed` contract. `subject` and
+`data.author_node_id` both identify the exact invoking agent;
+`data.target_node_id` identifies only its connected capability node. Temporal
+event IDs are deterministic per model tool call and lifecycle stage, and
+consumers deduplicate by `(source, id)`. Bodies and resource contents appear
+only in tool results, never status broadcasts.
+The generic loop, chat/specialized-agent loop, RLM bridge, Claude/Codex native
+MCP bridge, and Temporal AgentWorkflow all emit the same parent-agent
+capability phases. Consequently
+every agent component renders `skill <name>` and `tool <name>` consistently;
+this behavior is not owned by the team-lead implementation.
+
### 4. SkillLoader Architecture
Defined in `server/services/skill_loader.py:38+`:
@@ -255,7 +282,8 @@ SkillLoader
1. Check `_cache` -- return immediately if cached
2. Look up `_registry[name]` -- fail if not registered
3. Read `SKILL.md`, strip frontmatter, extract markdown body as `instructions`
-4. Load optional `scripts/` and `references/` directories
+4. Discover optional `scripts/` and `references/`; the Skill tool returns a
+ manifest and reads their text separately rather than injecting them eagerly
5. Cache and return `Skill` dataclass
**`get_skill_loader()` is database-wired** (`skill_loader.py`):
diff --git a/docs-internal/errors.md b/docs-internal/errors.md
index 6d9a2d2e..c47d22c3 100644
--- a/docs-internal/errors.md
+++ b/docs-internal/errors.md
@@ -89,6 +89,54 @@ company start
---
+### 2a. Temporal OpenTelemetry Lines Appear Twice
+
+**Symptom**: SDK spans appear in exact adjacent pairs with the same operation
+and Temporal identity fields:
+
+```text
+CompleteWorkflow:AgentWorkflow ... temporalWorkflowID=<same> temporalRunID=<same>
+CompleteWorkflow:AgentWorkflow ... temporalWorkflowID=<same> temporalRunID=<same>
+StartActivity:node.console.v1 ... temporalWorkflowID=<same> temporalRunID=<same>
+StartActivity:node.console.v1 ... temporalWorkflowID=<same> temporalRunID=<same>
+```
+
+The OpenCompany `node.console.execute` span may appear only once between those
+pairs.
+
+**Root cause**: `TracingInterceptor` was attached to the shared Temporal client
+and repeated in `Worker(..., interceptors=...)`. The Python SDK automatically
+prepends worker-compatible client interceptors, so the activity and workflow
+pass through two tracing interceptors. The two generated OpenTelemetry spans
+have distinct span IDs, but the compact console formatter displays only the
+operation and Temporal attributes; they therefore look identical.
+
+This does **not** mean that the node executed twice. `StartActivity` is the
+workflow-side scheduling span, `RunActivity` is the worker-side invocation
+span, and `node.<type>.execute` surrounds the application body. Separate
+`CompleteWorkflow:AgentWorkflow` and `CompleteWorkflow:MachinaWorkflow` lines
+represent the child and parent workflow. A `CompleteWorkflow` duration of
+`0ms` is normal for Temporal's replay-safe terminal marker.
+
+**Fix**: keep exactly one `TracingInterceptor` on `Client.connect(...)`. Do not
+repeat it in worker interceptor lists; workers explicitly register only
+`ObservabilityWorkerInterceptor` and distinct plugin-owned interceptors. Apply
+the invariant to manager, specialized-pool, standalone, helper, and test worker
+construction paths.
+
+**Verification**:
+
+1. Compare operation name, `temporalWorkflowID`, `temporalRunID`, and
+ `temporalActivityID`; each identity tuple should occur once per phase.
+2. Confirm Temporal Event History contains one activity attempt. A genuine
+ retry has another attempt and is reported by the application observability
+ interceptor.
+3. Confirm one `node.<type>.execute` span for one plugin-body invocation.
+4. Keep the expected single `StartActivity`, `RunActivity`, and workflow
+ completion entries; they are different lifecycle layers.
+
+---
+
## 3. Temporal Activity `CancelledError` on Long-Running Nodes
**Symptom**: Nodes that run for more than ~2 minutes (Deep Agent, browser automation, AI multi-tool loops) fail with:
diff --git a/docs-internal/event_framework.md b/docs-internal/event_framework.md
index d3f5afea..24e239db 100644
--- a/docs-internal/event_framework.md
+++ b/docs-internal/event_framework.md
@@ -19,7 +19,7 @@ phase plan lives in `~/.claude/plans/properly-fix-the-tech-dreamy-tarjan.md`.
| Phase | State |
|---|---|
-| A1-A9 — Temporal primitives + CloudEvents spec compliance | ✅ commit `c3dc85a` (16 tests) |
+| A1-A9 — Temporal primitives + core CloudEvents envelope compliance | ✅ commit `c3dc85a` (16 tests; legacy extension-name debt documented below) |
| A7 completion — `_pop_matching_event` helper | ✅ commit `0e835e2` (4 tests) |
| B1-B10 — plugin-owned `_events.py` modules (9 plugin folders) | ✅ commits `7e4ff7b` / `c4d9428` / `da63d73` / `de8be88` |
| C1 canary (webhookTrigger) — `TriggerListenerWorkflow` | ✅ commit `c24bc62` (25 tests) |
@@ -158,21 +158,53 @@ or hand back to the server for retry instead of being killed mid-call.
## CloudEvents envelope
-Every server→FE broadcast wraps `WorkflowEvent` (CloudEvents v1.0;
-`services/events/envelope.py`). Spec-compliant ID, source, type, time,
-plus OpenCompany extension attributes (`workflow_id`, `trigger_node_id`,
-`correlation_id` — kept in snake_case per the documented internal-naming
-rationale at `envelope.py:4-12`).
+Domain/lifecycle broadcasts wrap `WorkflowEvent` (CloudEvents v1.0;
+`services/events/envelope.py`). High-frequency state projections such as
+`node_status`, output, variables, and log streams remain the explicitly tested
+telemetry carve-out; they are reconnect snapshots, not lifecycle occurrences.
+
+New envelopes use the required `specversion`, `id`, `source`, and `type`
+attributes, a reverse-DNS `type`, and an exact entity `subject`. Application
+scope such as `workflow_id`, `execution_id`, and `root_execution_id` belongs
+inside `data`. CloudEvents requires extension-attribute names to contain only
+lowercase ASCII letters and digits, so the historical top-level
+`workflow_id`, `trigger_node_id`, and `correlation_id` fields are compatibility
+debt and must not be copied into new contracts.
Wire shape: `{"type": "<legacy_wire_key>", "data": <WorkflowEvent JSON>}`.
-The outer `type` is what FE switches on; the inner envelope is what
-parses for spec-compliant routing + dataschema lookup.
+The outer `type` is what FE switches on; the inner envelope carries the
+CloudEvents routing identity and dataschema lookup.
+
+### Agent capability occurrences
+
+Skill and tool activity uses the `agent_capability` WebSocket route with a
+complete CloudEvent inside `data`:
+
+- `source = opencompany://services/agent`;
+- `type = com.opencompany.agent.(skill|tool).<state>`;
+- `subject = data.agent_node_id`, the exact invoking agent;
+- `data.target_node_id`, when present, is the exact connected Master Skill or
+ tool node;
+- Temporal occurrences use a deterministic `id`; consumers deduplicate on the
+ CloudEvents `(source, id)` identity pair.
+
+The browser rejects envelopes whose type/state/subject disagree, ignores late
+events from an archived root execution, and updates only the stated agent and
+target nodes. Prompts, tool arguments, instruction/resource bodies, raw
+results, secrets, and raw exceptions are forbidden from the payload.
+
+Capability telemetry broadcasts directly to WebSocket clients through
+`StatusBroadcaster.broadcast_agent_capability`. It does not use
+`services.events.dispatch.emit`: that path performs Temporal Visibility lookup
+and signals trigger consumers, while capability activity is an observation of
+an execution already in progress. The paired raw `node_status` frame is only a
+latest-state/reconnect projection; the CloudEvent is the canonical occurrence.
### Plugin-owned event factories
Plugin-specific events (e.g. `com.opencompany.telegram.message.received`)
live in `nodes/<plugin>/_events.py`. Cross-cutting factories
-(`credential`, `oauth_completed`, `agent_progress`, `task_completed`,
+(`credential`, `oauth_completed`, `agent_progress`, `agent_capability`, `task_completed`,
`workflow_lifecycle`, `deployment_snapshot`, `team_event`,
`node_parameters_updated`) stay in `services/events/envelope.py`.
@@ -282,4 +314,4 @@ Locked by `TestCancelSweepsStuckNodeStatuses` in [`test_deployment_canary_listen
- Plan: `~/.claude/plans/properly-fix-the-tech-dreamy-tarjan.md`
- RFC: [`plugin_authoring_rfc.md`](./ARCHIVE/plugin_authoring_rfc.md)
- Temporal: [Search Attributes](https://docs.temporal.io/search-attribute) · [Signals](https://docs.temporal.io/develop/python/message-passing) · [Schedules](https://docs.temporal.io/develop/python/schedules) · [Retry Policies](https://docs.temporal.io/encyclopedia/retry-policies)
-- CloudEvents: [v1.0 spec](https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md)
+- CloudEvents: [v1.0.2 spec](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md)
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index e0bc593d..209f3c90 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -455,6 +455,43 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
Adding new panel behaviour: add a flag to `INodeUIHints`, annotate the relevant node definitions (or extend the auto-derivation rule on the backend), read the flag in the panel. Don't add another `nodeDefinition.name === '…'` branch — six such checks for `'masterSkill'` were retired in this round in favour of `uiHints.isMasterSkillEditor`. Pytest invariant `test_ui_hints_only_carry_known_flags` in `server/tests/test_node_spec.py` locks the flag set; new flags must be added there too.
+### Observable skill loading
+
+The `agent_capability` wire route carries the canonical CloudEvents occurrence;
+`node_status.data.active_skills` is its reconnect/latest-state projection. The
+consumer validates `specversion`, reverse-DNS type, allowed kind/state, and
+exact `subject === data.agent_node_id === data.author_node_id`, then
+deduplicates on `(source, id)`. Root-execution checks reject late events from a
+reset generation. It never falls back to an outer message node id or a label.
+Agent cards show Loading/Loaded/Failed badges for the current turn;
+the exact Master Skill card glows only during retrieval, then returns to a
+non-executing success/error state while retaining the same safe names.
+Agent live text replaces the card's center subtitle with `skill <name>` for
+instruction retrieval or `tool <name>` for ordinary tool execution; it is never
+rendered as an extra line near the bottom handles. Capability ownership is the
+exact invoking agent node: descendant tool metadata is never mirrored to its
+parent, completed agents restore their configured subtitle, and deleting a node
+clears its status slot before that ID can be reused. The Master Skill editor projects runtime state onto
+the matching enabled skill row so operators can see which listed skill is active.
+Every agent's Connected Skills section also exposes an expandable, read-only
+`Skill prompt` sourced from the connected Master Skill's authoritative
+`skills_config.instructions`; this is configuration inspection, not runtime
+status broadcasting or system-prompt injection.
+Capability summaries are producer-owned. The status broadcaster preserves the
+allowlisted `last_capability`, `last_tool_name`, and `last_skills` fields across
+generic phase and outer terminal snapshots, but only within the same workflow;
+the next agent initialization explicitly clears them. Temporal and legacy tool
+paths emit the same typed capability lifecycle and also publish a raw executing
+node status containing only safe tool-name fields for reconnect snapshots. The
+parallel `agent_progress` CloudEvent intentionally carries only phase and
+iteration counters. Do not deep-merge arbitrary status data in the browser:
+omitted fields are not universally equivalent to unchanged fields. Capability
+payloads never carry prompts, arguments, results, contents, secrets, or raw
+exception text.
+Ref-counted backend state prevents concurrent calls from clearing one another.
+`agent.skill.cleared`, reconnect reconciliation, cancellation, pause, and reset
+remove transient badges. This is independent from ordinary tool-node glow.
+
### Node output shape — backend as single source of truth
Frontend does **not** declare output shapes anymore. The backend owns them exclusively via Pydantic models in [server/services/node_output_schemas.py](../server/services/node_output_schemas.py) — live size via `len(NODE_OUTPUT_SCHEMAS)`. JSON Schema is emitted via Pydantic's `model_json_schema()` and exposed two ways:
diff --git a/docs-internal/temporal-execution-engine-rfc.md b/docs-internal/temporal-execution-engine-rfc.md
index 3c3dc3fe..15cec5cd 100644
--- a/docs-internal/temporal-execution-engine-rfc.md
+++ b/docs-internal/temporal-execution-engine-rfc.md
@@ -666,9 +666,50 @@ five surrounding events. Raw payload mode does not exist. Prompts, tool
arguments, credentials, tokens, raw results, and arbitrary failure payloads are
excluded by allowlist normalization and secret redaction.
-Temporal clients and workers use the SDK OpenTelemetry tracing interceptor.
-Only opaque correlation identities are added. Application task records remain
-available when Temporal retention has removed detailed history.
+### 12.1 OpenTelemetry interceptor ownership
+
+`core.tracing.init_tracing()` owns the process-wide `TracerProvider` and span
+exporter. The shared Temporal client owns exactly one SDK
+`TracingInterceptor`. A Python SDK `Worker` automatically prepends compatible
+interceptors from its client, so worker interceptor lists **must not** repeat
+`TracingInterceptor`; they contain only OpenCompany's
+`ObservabilityWorkerInterceptor` and any distinct plugin-owned worker
+interceptors.
+
+```text
+Temporal client
+└── TracingInterceptor (registered once)
+ └── inherited by every Worker built from that client
+ └── ObservabilityWorkerInterceptor (explicit, worker-only)
+```
+
+Registering `TracingInterceptor` on both `Client.connect(...)` and
+`Worker(...)` wraps every workflow and activity twice. The resulting spans are
+different OpenTelemetry spans, but the compact console formatter omits their
+span IDs, so adjacent copies have the same operation name and Temporal
+workflow/run/activity attributes and appear identical. This is duplicate
+instrumentation, not evidence that Temporal executed the workflow twice.
+
+| Span or log | Meaning |
+|---|---|
+| `StartActivity:<activity>` | Workflow-side scheduling and trace-context propagation; not the activity body |
+| `RunActivity:<activity>` | Worker-side activity invocation; a real retry is a separate attempt |
+| `node.<type>.execute` | OpenCompany plugin-body span emitted by `BaseNode.execute()` |
+| `CompleteWorkflow:AgentWorkflow` | Terminal marker for an agent child workflow |
+| `CompleteWorkflow:MachinaWorkflow` | Terminal marker for the graph workflow |
+
+`CompleteWorkflow` commonly reports `0ms`: the SDK emits a replay-safe
+instantaneous completion marker rather than a wall-clock workflow-duration
+span. Separate agent-child and graph-workflow completions are expected, as are
+one `StartActivity` and one `RunActivity` for the same activity. Exact adjacent
+repeats of the *same* phase and Temporal identity tuple indicate interceptor
+duplication. Temporal Event History remains the execution authority; a single
+`node.<type>.execute` span and one activity attempt in history corroborate that
+the node body ran once.
+
+Only opaque correlation identities are added to tracing attributes. Prompts,
+credentials, tool arguments, and raw results are excluded. Application task
+records remain available when Temporal retention has removed detailed history.
## 13. Worker and task-queue topology
@@ -834,6 +875,7 @@ triggered graph invocation does.
| Temporal start identity | `server/services/temporal/executor.py` |
| Agent and delegation workflows | `server/services/temporal/agent_workflow.py` |
| Agent lifecycle activities | `server/services/temporal/agent_activities.py` |
+| Progressive skill runtime | `server/services/skill_runtime.py`, `server/services/skill_prompt.py` |
| Team/task authorization | `server/services/agent_team.py` |
| Trace service | `server/services/team_task_trace.py` |
| Worker topology | `server/services/temporal/worker.py`, `server/services/temporal/plugin_activities.py` |
@@ -866,3 +908,24 @@ Any change to this engine must demonstrate:
7. Sanitized trace output with bounded pagination/search.
8. UI reconciliation from backend authority after reconnect.
9. Focused unit tests plus an integration or replay test proportional to risk.
+
+## 23. Progressive skill activities
+
+Temporal agents expose metadata on the connected `Skill` tool (not through a
+hardcoded agent prompt) and schedule `agent.skill.invoke.v1` only
+after the model calls `Skill`. Its deterministic tool activity ID includes the
+agent, iteration, and model call index, so the returned instructions are written
+to workflow history and activity retries do not refetch into replay. Customized
+Master Skill content is authoritative. Supporting resources are bounded and
+separate. `agent.skill.clear.v1` clears canvas-only state at turn completion;
+loaded tool results remain in the conversation until that execution ends.
+
+Every Temporal skill/tool lifecycle is also emitted as a sanitized
+`com.opencompany.agent.(skill|tool).<state>` CloudEvent. Its ID is derived from
+workflow execution, agent, model tool-call identity, capability, and stage, so
+an activity retry redelivers the same occurrence instead of inventing a second
+one. `subject` remains the invoking child agent; parent progress mirroring never
+copies child capability metadata. Workflow/execution scope stays inside event
+`data` rather than non-conformant snake_case extension attributes. These events
+are direct observability fan-out, not trigger Signals; Temporal Event History
+continues to be the durable execution authority.
diff --git a/server/nodes/agent/claude_code_agent/__init__.py b/server/nodes/agent/claude_code_agent/__init__.py
index d17eec14..0e8efd78 100644
--- a/server/nodes/agent/claude_code_agent/__init__.py
+++ b/server/nodes/agent/claude_code_agent/__init__.py
@@ -387,6 +387,7 @@ class ClaudeCodeAgentNode(ActionNode):
broadcaster=broadcaster,
repo_root=repo_root,
connected_skill_names=connected_skills,
+ connected_skill_descriptors=skill_data,
connected_tools=tool_data,
connected_memory=memory_data,
execution_id=ctx.execution_id,
diff --git a/server/nodes/agent/claude_code_agent/_provider.py b/server/nodes/agent/claude_code_agent/_provider.py
index 1197b8be..200a0809 100644
--- a/server/nodes/agent/claude_code_agent/_provider.py
+++ b/server/nodes/agent/claude_code_agent/_provider.py
@@ -276,6 +276,8 @@ class AnthropicClaudeProvider:
"mcp__opencompany__getWorkspaceFiles",
"mcp__opencompany__listSkills",
"mcp__opencompany__getSkill",
+ "mcp__opencompany__readSkillResource",
+ "mcp__opencompany__searchSkillResource",
"mcp__opencompany__getCredential",
"mcp__opencompany__broadcastLog",
]
diff --git a/server/nodes/agent/codex_agent/__init__.py b/server/nodes/agent/codex_agent/__init__.py
index 3ed18de7..0806c351 100644
--- a/server/nodes/agent/codex_agent/__init__.py
+++ b/server/nodes/agent/codex_agent/__init__.py
@@ -141,7 +141,7 @@ class CodexAgentNode(ActionNode):
tasks[i] = t.model_copy(update=changed)
database = get_database()
- _, skill_data, _, _, _ = await collect_agent_connections(
+ _, skill_data, tool_data, _, _ = await collect_agent_connections(
node_id,
ctx.raw,
database,
@@ -167,6 +167,9 @@ class CodexAgentNode(ActionNode):
broadcaster=broadcaster,
repo_root=repo_root,
connected_skill_names=connected_skills,
+ connected_skill_descriptors=skill_data,
+ connected_tools=tool_data,
+ execution_id=ctx.execution_id,
allowed_credentials=params.allowed_credentials,
max_parallel=params.max_parallel,
)
diff --git a/server/nodes/skill/_expander.py b/server/nodes/skill/_expander.py
index af2001af..80a88f3b 100644
--- a/server/nodes/skill/_expander.py
+++ b/server/nodes/skill/_expander.py
@@ -7,9 +7,9 @@ expansion logic and registers this callback from its ``__init__.py``;
edge_walker calls the registered callback through the
:func:`services.plugin.edge_walker.get_master_skill_expander` lookup.
-Per-enabled-skill instructions come from the DB config first (the
-user-customised version in the Master-Skill node parameters), with a
-fallback to the disk SKILL.md via :mod:`services.skill_loader`.
+Expansion is metadata-only for standard skills. The authoritative body is
+kept on the descriptor and is returned only by the scoped ``Skill`` tool.
+Personality skills remain eager because they define agent identity.
"""
from __future__ import annotations
@@ -43,7 +43,7 @@ async def expand_master_skill(
"""
from services.skill_loader import get_skill_loader
- skill_loader = get_skill_loader()
+ registry = get_skill_loader().scan_skills()
entries: List[Dict[str, Any]] = []
for skill_key, skill_cfg in skills_config.items():
@@ -51,20 +51,31 @@ async def expand_master_skill(
continue
instructions = skill_cfg.get("instructions", "")
- if not instructions:
+ metadata = registry.get(skill_key)
+ if skill_key.endswith("-personality") and not instructions:
try:
- skill = skill_loader.load_skill(skill_key)
- if skill:
- instructions = skill.instructions
- except Exception as exc: # noqa: BLE001 -- log + skip
- logger.warning(f"[MasterSkill] Failed to load skill {skill_key}: {exc}")
+ personality = get_skill_loader().load_skill(skill_key)
+ instructions = personality.instructions if personality else ""
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[MasterSkill] Failed to load personality skill %s: %s", skill_key, exc)
+ description = (
+ skill_cfg.get("description")
+ or (metadata.description if metadata else "")
+ or f"Instructions for {skill_key}"
+ )
entries.append(
{
"node_id": f"{source_node_id}_{skill_key}",
+ "master_skill_node_id": source_node_id,
"node_type": "masterSkill",
"skill_name": skill_key,
- "parameters": {"instructions": instructions, "skillName": skill_key},
+ "description": description,
+ "parameters": {
+ "instructions": instructions,
+ "skillName": skill_key,
+ "description": description,
+ },
"label": skill_key,
}
)
diff --git a/server/nodes/skill/master_skill/__init__.py b/server/nodes/skill/master_skill/__init__.py
index c460dbb9..0ab032cf 100644
--- a/server/nodes/skill/master_skill/__init__.py
+++ b/server/nodes/skill/master_skill/__init__.py
@@ -18,7 +18,14 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
class MasterSkillParams(BaseModel):
skill_folder: str = Field(default="assistant")
skills_config: Dict[str, Any] = Field(
- default_factory=dict,
+ default_factory=lambda: {
+ "skill": {
+ "enabled": True,
+ "instructions": "",
+ "isCustomized": False,
+ "required": True,
+ }
+ },
)
model_config = ConfigDict(extra="ignore")
diff --git a/server/services/ai.py b/server/services/ai.py
index b13a5ae3..7af5c624 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -917,49 +917,11 @@ def _build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str
append to system_message. has_personality indicates whether any
personality skills were found (used to drop the default system message).
"""
- if not skill_data:
- return "", False
+ # Kept as a compatibility entry point for callers and tests; the shared
+ # builder is the sole progressive-disclosure implementation.
+ from services.skill_prompt import build_skill_system_prompt
- from services.skill_loader import get_skill_loader
-
- skill_loader = get_skill_loader()
- skill_loader.scan_skills()
-
- personality_blocks = []
- non_personality_names = []
-
- for skill_info in skill_data:
- skill_name = skill_info.get("skill_name") or skill_info.get("node_type", "").replace("Skill", "-skill").lower()
- if skill_name.endswith("skill") and "-" not in skill_name:
- skill_name = skill_name[:-5] + "-skill"
-
- if skill_name.endswith("-personality"):
- instructions = skill_info.get("parameters", {}).get("instructions", "")
- if instructions:
- personality_blocks.append(instructions)
- logger.debug(f"{log_prefix} Personality skill injected (full): {skill_name}")
- else:
- logger.warning(f"{log_prefix} Personality skill {skill_name} has no instructions")
- else:
- non_personality_names.append(skill_name)
- logger.debug(f"{log_prefix} Skill detected: {skill_name}")
-
- parts = []
-
- for block in personality_blocks:
- parts.append(block)
-
- if non_personality_names:
- registry_prompt = skill_loader.get_registry_prompt(non_personality_names)
- if registry_prompt:
- parts.append(registry_prompt)
-
- if parts:
- logger.debug(
- f"{log_prefix} Enhanced system message: {len(personality_blocks)} personality, {len(non_personality_names)} standard skills"
- )
-
- return "\n\n".join(parts), len(personality_blocks) > 0
+ return build_skill_system_prompt(skill_data, log_prefix)
class AIService:
@@ -1677,7 +1639,7 @@ class AIService:
temperature = _resolve_temperature(flattened, model, provider, bool(thinking_config and thinking_config.enabled))
# Broadcast: Initializing model
- await broadcast_status("initializing", {"message": f"Initializing {provider} model...", "provider": provider, "model": model})
+ await broadcast_status("initializing", {"message": f"Initializing {provider} model...", "provider": provider, "model": model, "active_skills": [], "last_skills": [], "last_tool_name": None, "last_capability": None})
# Check for proxy URL (stored as {provider}_proxy credential)
proxy_url = await self.auth.get_api_key(f"{provider}_proxy")
@@ -1748,10 +1710,19 @@ class AIService:
tool_identities: List[Dict[str, str]] = []
tool_bindings: List[tuple[Any, Dict[str, Any]]] = []
- if tool_data:
- await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)...", "tool_count": len(tool_data)})
+ # Standard skills are progressively disclosed through one scoped
+ # provider-neutral tool. Personality skills were injected above.
+ from services.skill_runtime import skill_tool_info
- for tool_info in tool_data:
+ skill_info = skill_tool_info(skill_data or [], node_id)
+ effective_tool_data = list(tool_data or [])
+ if skill_info:
+ effective_tool_data.append(skill_info)
+
+ if effective_tool_data:
+ await broadcast_status("building_tools", {"message": f"Building {len(effective_tool_data)} tool(s)...", "tool_count": len(effective_tool_data)})
+
+ for tool_info in effective_tool_data:
tool, config = await self._build_tool_from_node(tool_info)
if tool:
tools.append(tool)
@@ -1826,15 +1797,30 @@ class AIService:
# Parent-agent phase broadcast (does not touch tool node).
await broadcast_status(
- "executing_tool", {"message": f"Executing tool: {tool_name}", "tool_name": tool_name, "tool_args": tool_args}
+ "executing_tool", {"message": f"Executing tool: {tool_name}", "tool_name": tool_name}
)
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="started",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ )
+
# Inject services + graph context so execute_tool can scope its
# broadcasts and nested agents can execute with their own tools.
config["workflow_id"] = workflow_id
config["ai_service"] = self
config["database"] = self.database
config["parent_node_id"] = node_id
+ config["provider"] = provider
# Surface the auto-rebind toggle so agentBuilder's summary
# text reflects the user's current preference.
config["auto_rebind_tools"] = auto_rebind_enabled
@@ -1856,15 +1842,57 @@ class AIService:
await broadcast_status(
"tool_completed",
- {"message": f"Tool completed: {tool_name}", "tool_name": tool_name, "result_preview": str(result)[:100]},
+ {"message": f"Tool completed: {tool_name}", "tool_name": tool_name},
)
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="completed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ )
+
return result
except Exception as e:
error_msg = str(e)
logger.error(f"[Agent] Tool execution failed: {tool_name}", error=error_msg)
+ # Keep normal AI agents on the same observable contract as
+ # specialized/team-lead agents. Without this terminal
+ # phase a failed fast tool call leaves only the preceding
+ # generic executing phase, so the canvas cannot retain
+ # ``tool <name>`` or mark the capability as failed.
+ await broadcast_status(
+ "tool_completed",
+ {
+ "message": f"Tool failed: {tool_name}",
+ "tool_name": tool_name,
+ "tool_failed": True,
+ },
+ )
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="failed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ error_code=type(e).__name__,
+ )
+
# Re-raise to let _run_agent_loop surface the error to the LLM
raise
@@ -2168,6 +2196,11 @@ class AIService:
"timestamp": datetime.now().isoformat(),
}
+ finally:
+ from services.skill_runtime import clear_skill_turn
+
+ await clear_skill_turn(workflow_id or "", str((context or {}).get("execution_id") or ""), node_id)
+
async def execute_chat_agent(
self,
node_id: str,
@@ -2237,11 +2270,17 @@ class AIService:
tool_node_configs = {} # Map tool name to node config (same as AI Agent's tool_configs)
tool_identities: List[Dict[str, str]] = []
tool_bindings: List[tuple[Any, Dict[str, Any]]] = []
- if tool_data:
- await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)...", "tool_count": len(tool_data)})
+ from services.skill_runtime import skill_tool_info
- task_manager_bound = any(info.get("node_type") == "taskManager" for info in tool_data)
- durable_delegates = [info for info in tool_data if info.get("delegate_tool_name")]
+ effective_tool_data = list(tool_data or [])
+ progressive_skill_tool = skill_tool_info(skill_data or [], node_id)
+ if progressive_skill_tool:
+ effective_tool_data.append(progressive_skill_tool)
+ if effective_tool_data:
+ await broadcast_status("building_tools", {"message": f"Building {len(effective_tool_data)} tool(s)...", "tool_count": len(effective_tool_data)})
+
+ task_manager_bound = any(info.get("node_type") == "taskManager" for info in effective_tool_data)
+ durable_delegates = [info for info in effective_tool_data if info.get("delegate_tool_name")]
if task_manager_bound and durable_delegates:
teammate_lines = "\n".join(
f"- {info.get('node_id')}: {info.get('label') or info.get('node_type')} ({info.get('node_type')})"
@@ -2259,7 +2298,7 @@ class AIService:
f"Connected teammates:\n{teammate_lines}"
)
- for tool_info in tool_data:
+ for tool_info in effective_tool_data:
if task_manager_bound and tool_info.get("delegate_tool_name"):
continue
# Use AI Agent's _build_tool_from_node for all tool types
@@ -2361,7 +2400,7 @@ class AIService:
temperature = _resolve_temperature(flattened, model, provider, bool(thinking_config and thinking_config.enabled))
# Broadcast: Initializing
- await broadcast_status("initializing", {"message": f"Initializing {provider} model...", "provider": provider, "model": model})
+ await broadcast_status("initializing", {"message": f"Initializing {provider} model...", "provider": provider, "model": model, "active_skills": [], "last_skills": [], "last_tool_name": None, "last_capability": None})
# Check for proxy URL (stored as {provider}_proxy credential)
proxy_url = await self.auth.get_api_key(f"{provider}_proxy")
@@ -2451,12 +2490,31 @@ class AIService:
f"[ChatAgent] Tool config: node_id={tool_node_id}, node_type={config.get('node_type')}, workflow_id={workflow_id}"
)
+ await broadcast_status(
+ "executing_tool",
+ {"message": f"Executing tool: {tool_name}", "tool_name": tool_name},
+ )
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="started",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ )
+
# Inject services + graph context so execute_tool can scope its
# broadcasts and nested agents can execute with their own tools.
config["workflow_id"] = workflow_id
config["ai_service"] = self
config["database"] = self.database
config["parent_node_id"] = node_id
+ config["provider"] = provider
config["auto_rebind_tools"] = auto_rebind_enabled
if context:
config["nodes"] = context.get("nodes", [])
@@ -2473,10 +2531,45 @@ class AIService:
try:
result = await execute_tool(tool_name, tool_args, config)
+ await broadcast_status(
+ "tool_completed",
+ {"message": f"Tool completed: {tool_name}", "tool_name": tool_name},
+ )
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="completed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ )
logger.debug(f"[ChatAgent] Tool executed successfully: {tool_name}")
return result
except Exception as e:
logger.error(f"[ChatAgent] Tool execution failed: {tool_name}", error=str(e))
+ await broadcast_status(
+ "tool_completed",
+ {"message": f"Tool failed: {tool_name}", "tool_name": tool_name, "tool_failed": True},
+ )
+ if broadcaster and tool_name and tool_name != "Skill":
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state="failed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(tool_node_id or "") or None,
+ provider=provider,
+ invocation_source="legacy",
+ error_code=type(e).__name__,
+ )
return {"error": str(e)}
# Auto-rebind toggle + recursion_limit override: same
@@ -2750,6 +2843,11 @@ class AIService:
"timestamp": datetime.now().isoformat(),
}
+ finally:
+ from services.skill_runtime import clear_skill_turn
+
+ await clear_skill_turn(workflow_id or "", str((context or {}).get("execution_id") or ""), node_id)
+
async def _build_tool_from_node(self, tool_info: Dict[str, Any]) -> tuple:
"""Convert a node configuration into a LangChain StructuredTool.
@@ -2783,6 +2881,10 @@ class AIService:
"check_delegated_tasks",
"Check status and retrieve results of previously delegated tasks.",
),
+ "_builtin_skill": (
+ "Skill",
+ "Load a connected skill or read/search one of its declared text resources on demand.",
+ ),
}
def _resolve_default_tool_name_description(node_type: str) -> tuple:
@@ -2974,6 +3076,21 @@ class AIService:
return DelegateToAgentSchema
+ if node_type == "_builtin_skill":
+ from typing import Literal
+
+ class SkillInvocationSchema(BaseModel):
+ action: Literal["load", "read_resource", "search_resource"] = Field(
+ default="load", description="Load instructions, read a bounded resource page, or search a resource."
+ )
+ skill_name: str = Field(description="Exact connected skill name from Available Skills.")
+ path: Optional[str] = Field(default=None, description="Declared references/<file> or scripts/<file> path.")
+ query: Optional[str] = Field(default=None, description="Case-insensitive search query for search_resource.")
+ cursor: int = Field(default=0, ge=0, description="Pagination cursor.")
+ limit: int = Field(default=4000, ge=1, le=16000, description="Bounded character or match limit.")
+
+ return SkillInvocationSchema
+
# Built-in check tool for delegation result retrieval (no plugin).
if node_type == "_builtin_check_delegated_tasks":
diff --git a/server/services/cli_agent/mcp_server.py b/server/services/cli_agent/mcp_server.py
index b83e423f..02c96982 100644
--- a/server/services/cli_agent/mcp_server.py
+++ b/server/services/cli_agent/mcp_server.py
@@ -60,6 +60,7 @@ class BatchContext:
workspace_dir: Path
execution_id: Optional[str] = None
connected_skill_names: Set[str] = field(default_factory=set)
+ connected_skill_descriptors: List[Dict[str, Any]] = field(default_factory=list)
allowed_credentials: Set[str] = field(default_factory=set)
# Connected ``input-tools`` nodes (entries from
# ``services.plugin.edge_walker.collect_agent_connections``). Each
@@ -152,6 +153,7 @@ def rebind_batch(
broadcaster: Any = _UNSET,
connected_tools: Optional[List[Dict[str, Any]]] = None,
connected_skill_names: Optional[Set[str]] = None,
+ connected_skill_descriptors: Optional[List[Dict[str, Any]]] = None,
allowed_credentials: Optional[Set[str]] = None,
workspace_dir: Optional[Path] = None,
) -> Optional[BatchContext]:
@@ -219,6 +221,8 @@ def rebind_batch(
)
if connected_skill_names is not None:
ctx.connected_skill_names = set(connected_skill_names)
+ if connected_skill_descriptors is not None:
+ ctx.connected_skill_descriptors = list(connected_skill_descriptors)
if allowed_credentials is not None:
ctx.allowed_credentials = set(allowed_credentials)
if workspace_dir is not None:
@@ -439,7 +443,7 @@ def _build_tools(mcp: Any) -> None: # FastMCP type
"docs). The skill must be connected to the parent agent node."
),
)
- def get_skill(name: str) -> Dict[str, Any]:
+ async def get_skill(name: str) -> Dict[str, Any]:
ctx = _require_batch()
if name not in ctx.connected_skill_names:
return {
@@ -447,26 +451,50 @@ def _build_tools(mcp: Any) -> None: # FastMCP type
"name": name,
}
try:
- from services.skill_loader import get_skill_loader
-
- loader = get_skill_loader()
- skill = loader.load_skill(name)
- if skill is None:
- return {"error": f"skill {name!r} not found", "name": name}
- return {
- "name": skill.metadata.name,
- "description": skill.metadata.description,
- "instructions": skill.instructions,
- "allowed_tools": list(skill.metadata.allowed_tools),
- "metadata": dict(skill.metadata.metadata) if skill.metadata.metadata else {},
- "scripts": dict(skill.scripts),
- "references": dict(skill.references),
- # `assets` (binary) excluded by default — too big for MCP responses.
- }
+ from services.skill_runtime import execute_skill_tool
+
+ descriptors = ctx.connected_skill_descriptors or [
+ {"skill_name": item, "node_id": item, "parameters": {}}
+ for item in ctx.connected_skill_names
+ ]
+ return await execute_skill_tool(
+ {"action": "load", "skill_name": name},
+ {"parameters": {"skill_descriptors": descriptors, "agent_node_id": ctx.node_id},
+ "workflow_id": ctx.workflow_id, "execution_id": ctx.execution_id, "parent_node_id": ctx.node_id,
+ "skill_invocation_source": "native_mcp"},
+ )
except Exception as exc: # pragma: no cover
logger.exception("[CC-Agent MCP] getSkill failed for %r", name)
return {"error": str(exc), "name": name}
+ @mcp.tool(name="readSkillResource", description="Read a bounded page of a declared resource from a loaded connected skill.")
+ async def read_skill_resource(name: str, path: str, cursor: int = 0, limit: int = 4000) -> Dict[str, Any]:
+ ctx = _require_batch()
+ try:
+ from services.skill_runtime import execute_skill_tool
+ descriptors = ctx.connected_skill_descriptors or [{"skill_name": item, "node_id": item, "parameters": {}} for item in ctx.connected_skill_names]
+ return await execute_skill_tool(
+ {"action": "read_resource", "skill_name": name, "path": path, "cursor": cursor, "limit": limit},
+ {"parameters": {"skill_descriptors": descriptors, "agent_node_id": ctx.node_id}, "workflow_id": ctx.workflow_id,
+ "execution_id": ctx.execution_id, "parent_node_id": ctx.node_id, "skill_invocation_source": "native_mcp"},
+ )
+ except Exception as exc:
+ return {"error": str(exc), "name": name, "path": path}
+
+ @mcp.tool(name="searchSkillResource", description="Search a declared text resource in a loaded connected skill and return line-numbered matches.")
+ async def search_skill_resource(name: str, path: str, query: str, cursor: int = 0, limit: int = 20) -> Dict[str, Any]:
+ ctx = _require_batch()
+ try:
+ from services.skill_runtime import execute_skill_tool
+ descriptors = ctx.connected_skill_descriptors or [{"skill_name": item, "node_id": item, "parameters": {}} for item in ctx.connected_skill_names]
+ return await execute_skill_tool(
+ {"action": "search_resource", "skill_name": name, "path": path, "query": query, "cursor": cursor, "limit": limit},
+ {"parameters": {"skill_descriptors": descriptors, "agent_node_id": ctx.node_id}, "workflow_id": ctx.workflow_id,
+ "execution_id": ctx.execution_id, "parent_node_id": ctx.node_id, "skill_invocation_source": "native_mcp"},
+ )
+ except Exception as exc:
+ return {"error": str(exc), "name": name, "path": path}
+
@mcp.tool(
name="getCredential",
description=(
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index 7c311a7e..3a0d63c5 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -76,6 +76,7 @@ class AICliService:
broadcaster: Any,
repo_root: Optional[Path] = None,
connected_skill_names: Optional[List[str]] = None,
+ connected_skill_descriptors: Optional[List[Dict[str, Any]]] = None,
connected_tools: Optional[List[Dict[str, Any]]] = None,
connected_memory: Optional[Dict[str, Any]] = None,
execution_id: Optional[str] = None,
@@ -173,8 +174,12 @@ class AICliService:
workflow_id=workflow_id,
node_id=node_id,
workspace_dir=Path(workspace_dir).resolve(),
- execution_id=execution_id,
+ # A batch token is a safe ephemeral conversation scope when the
+ # caller has no durable execution id; never share loaded-skill
+ # state across later CLI runs of the same workflow/node.
+ execution_id=execution_id or token,
connected_skill_names=set(connected_skill_names or []),
+ connected_skill_descriptors=list(connected_skill_descriptors or []),
allowed_credentials=set(allowed_credentials or []),
connected_tools=list(connected_tools or []),
broadcaster=broadcaster,
@@ -291,6 +296,9 @@ class AICliService:
finally:
async with self._lock:
self._active_sessions.pop(key, None)
+ from services.skill_runtime import clear_skill_turn
+
+ await clear_skill_turn(workflow_id, str(ctx.execution_id or ""), node_id)
# When ``use_pool`` is True, the bearer token for THIS batch
# is consumed by ``ClaudeSessionPool.acquire`` directly:
# - Cold spawn: pool stores ``token`` on
diff --git a/server/services/cli_agent/workflow_tools.py b/server/services/cli_agent/workflow_tools.py
index 49977ee9..bb8ed729 100644
--- a/server/services/cli_agent/workflow_tools.py
+++ b/server/services/cli_agent/workflow_tools.py
@@ -216,10 +216,83 @@ def _build_handler(node_type: str, params_cls: type):
"label": entry.get("label") or node_type,
"parameters": dict(entry.get("parameters") or {}),
}
- result = await execute_tool(node_type, args, config)
+ broadcaster = ctx.broadcaster
+ if broadcaster is None:
+ from services.status_broadcaster import get_status_broadcaster
+
+ broadcaster = get_status_broadcaster()
+ await broadcaster.update_node_status(
+ ctx.node_id,
+ "executing",
+ {
+ "phase": "executing_tool",
+ "agent_type": "native_cli",
+ "tool_name": node_type,
+ },
+ workflow_id=ctx.workflow_id,
+ )
+ await broadcaster.broadcast_agent_capability(
+ ctx.node_id,
+ capability_kind="tool",
+ capability_name=node_type,
+ state="started",
+ workflow_id=ctx.workflow_id,
+ execution_id=ctx.execution_id,
+ target_node_id=str(entry.get("node_id") or "") or None,
+ invocation_source="native_mcp",
+ )
+ try:
+ result = await execute_tool(node_type, args, config)
+ except Exception as exc:
+ await broadcaster.update_node_status(
+ ctx.node_id,
+ "executing",
+ {
+ "phase": "tool_completed",
+ "agent_type": "native_cli",
+ "tool_name": node_type,
+ "tool_failed": True,
+ },
+ workflow_id=ctx.workflow_id,
+ )
+ await broadcaster.broadcast_agent_capability(
+ ctx.node_id,
+ capability_kind="tool",
+ capability_name=node_type,
+ state="failed",
+ workflow_id=ctx.workflow_id,
+ execution_id=ctx.execution_id,
+ target_node_id=str(entry.get("node_id") or "") or None,
+ invocation_source="native_mcp",
+ error_code=type(exc).__name__,
+ )
+ raise
if not isinstance(result, dict):
result = {"result": result}
- if "error" in result:
+ failed = "error" in result
+ await broadcaster.update_node_status(
+ ctx.node_id,
+ "executing",
+ {
+ "phase": "tool_completed",
+ "agent_type": "native_cli",
+ "tool_name": node_type,
+ "tool_failed": failed,
+ },
+ workflow_id=ctx.workflow_id,
+ )
+ await broadcaster.broadcast_agent_capability(
+ ctx.node_id,
+ capability_kind="tool",
+ capability_name=node_type,
+ state="failed" if failed else "completed",
+ workflow_id=ctx.workflow_id,
+ execution_id=ctx.execution_id,
+ target_node_id=str(entry.get("node_id") or "") or None,
+ invocation_source="native_mcp",
+ error_code="TOOL_RETURNED_ERROR" if failed else None,
+ )
+ if failed:
logger.warning(
"[CC-Agent MCP %s] node=%s ERROR: %s",
node_type,
diff --git a/server/services/events/envelope.py b/server/services/events/envelope.py
index 4da0dc53..dff818e3 100644
--- a/server/services/events/envelope.py
+++ b/server/services/events/envelope.py
@@ -1,15 +1,17 @@
"""WorkflowEvent — CloudEvents v1.0 envelope (in-house, no external dep).
-Field set mirrors https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md
-verbatim so future interop with EventBridge / Knative is a JSON-schema swap.
-The OpenCompany extensions (``workflow_id``, ``trigger_node_id``,
-``correlation_id``) ride as CloudEvents extension attributes. Spec §3.1
-SHOULDs lowercase-alphanumeric extension names; we deliberately keep
-Python snake_case for codebase consistency — the rest of the project
-uses snake_case as a strict naming convention and the readability win
-outweighs the spec recommendation. Internal interop only; if we ever
-publish events to an external CloudEvents broker, an alias layer can
-translate at the producer boundary.
+The core field set mirrors
+https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md. New
+factories must keep application scope in ``data`` unless they use a valid
+lowercase-alphanumeric extension name. CloudEvents 1.0 makes that spelling a
+MUST, not a recommendation.
+
+The historical ``workflow_id``, ``trigger_node_id`` and ``correlation_id``
+model fields remain readable for wire compatibility, but their underscores
+make them non-conformant extension attributes. They are legacy debt, not the
+template for new event types. ``agent_capability`` demonstrates the current
+contract: standards-shaped context attributes plus snake_case application
+fields nested under ``data``.
Type strings carry the reverse-DNS prefix ``com.opencompany.`` per
Primer guidance. ``dataschema`` is auto-populated from ``type`` so
@@ -82,9 +84,10 @@ class WorkflowEvent(BaseModel):
dataschema: Optional[str] = None
data: Any = None
- # CloudEvents extension attributes. Snake-case (Python convention)
- # rather than lowercase-alphanumeric (CloudEvents §3.1 SHOULD) —
- # see module docstring.
+ # Legacy non-conformant extension attributes. CloudEvents §3.1 requires
+ # lowercase-alphanumeric names; do not add more snake_case fields here.
+ # New application scope belongs in ``data`` until these compatibility
+ # fields receive a coordinated wire migration.
workflow_id: Optional[str] = None
trigger_node_id: Optional[str] = None
correlation_id: Optional[str] = None
@@ -272,6 +275,92 @@ class WorkflowEvent(BaseModel):
},
)
+ @classmethod
+ def agent_capability(
+ cls,
+ agent_node_id: str,
+ *,
+ capability_kind: Literal["skill", "tool"],
+ capability_name: str,
+ state: Literal[
+ "loading",
+ "loaded",
+ "resource_read",
+ "cleared",
+ "started",
+ "completed",
+ "failed",
+ ],
+ workflow_id: Optional[str] = None,
+ execution_id: Optional[str] = None,
+ root_execution_id: Optional[str] = None,
+ target_node_id: Optional[str] = None,
+ action: Optional[str] = None,
+ provider: Optional[str] = None,
+ invocation_source: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
+ duration_ms: Optional[int] = None,
+ returned_characters: Optional[int] = None,
+ token_estimate: Optional[int] = None,
+ content_hash: Optional[str] = None,
+ error_code: Optional[str] = None,
+ event_id: Optional[str] = None,
+ ) -> "WorkflowEvent":
+ """One safe, node-owned skill/tool lifecycle occurrence.
+
+ This is observability telemetry, not a trigger input. Operational
+ scope stays inside ``data`` rather than becoming custom top-level
+ attributes: CloudEvents 1.0 requires extension attribute names to be
+ lowercase ASCII letters/digits, while OpenCompany's application
+ payload convention intentionally uses snake_case.
+
+ Prompts, tool arguments, instruction/resource contents, results,
+ secrets, and raw errors are deliberately absent from this contract.
+ ``subject`` is always the exact invoking agent; ``target_node_id`` is
+ the exact connected Master Skill or tool node.
+ """
+ valid_states = {
+ "skill": {"loading", "loaded", "resource_read", "failed", "cleared"},
+ "tool": {"started", "completed", "failed"},
+ }
+ if capability_kind not in valid_states:
+ raise ValueError(f"Invalid capability kind: {capability_kind}")
+ if not agent_node_id or not capability_name:
+ raise ValueError("agent_node_id and capability_name are required")
+ if state not in valid_states[capability_kind]:
+ raise ValueError(
+ f"Invalid {capability_kind} capability state: {state}"
+ )
+ payload = {
+ "workflow_id": workflow_id,
+ "execution_id": execution_id,
+ "root_execution_id": root_execution_id,
+ "agent_node_id": agent_node_id,
+ "author_node_id": agent_node_id,
+ "target_node_id": target_node_id,
+ "capability_kind": capability_kind,
+ "capability_name": capability_name,
+ "state": state,
+ "action": action,
+ "provider": provider,
+ "invocation_source": invocation_source,
+ "tool_call_id": tool_call_id,
+ "duration_ms": duration_ms,
+ "returned_characters": returned_characters,
+ "token_estimate": token_estimate,
+ "content_hash": content_hash,
+ "error_code": error_code,
+ }
+ event_kwargs: dict[str, Any] = {
+ "source": "opencompany://services/agent",
+ "type": f"{_TYPE_PREFIX}agent.{capability_kind}.{state}",
+ "subject": agent_node_id,
+ "data": {key: value for key, value in payload.items() if value is not None},
+ }
+ if event_id:
+ event_kwargs["id"] = event_id
+ return cls(**event_kwargs)
+
@classmethod
def node_parameters_updated(
cls,
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index cf447c76..056a1d9a 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -172,6 +172,11 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any], config: Dict
logger.info("[Tool] Executing '%s' (node_type=%s, workspace=%s)", tool_name, node_type, context["workspace_dir"])
+ if node_type == "_builtin_skill":
+ from services.skill_runtime import execute_skill_tool
+
+ return await execute_skill_tool(tool_args, config)
+
# ----------------------------------------------------------------
# Plugin fast-path (Wave 11.B.1): if this node_type is a
# BaseNode subclass, invoke BaseNode.execute_as_tool() — the
diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.py
index 0eb444fc..48eb6c82 100644
--- a/server/services/plugin/edge_walker.py
+++ b/server/services/plugin/edge_walker.py
@@ -342,7 +342,14 @@ async def _append_skill_entries(
)
return
- skills_config = skill_params.get("skills_config", {})
+ skills_config = dict(skill_params.get("skills_config", {}))
+ # The Assistant Master Skill owns the provider-neutral Skill tool's
+ # usage contract. Keep this real, editable skill enabled for legacy
+ # nodes whose saved params predate the default.
+ if (skill_params.get("skill_folder") or "assistant") == "assistant":
+ configured = dict(skills_config.get("skill") or {})
+ configured.update({"enabled": True, "required": True})
+ skills_config["skill"] = configured
logger.debug(f"{log_prefix} Master Skill found with {len(skills_config)} configured skills")
entries = await expander(source_node_id, skills_config)
skill_data.extend(entries)
diff --git a/server/services/rlm/adapters.py b/server/services/rlm/adapters.py
index 51daefc2..3ef27e8b 100644
--- a/server/services/rlm/adapters.py
+++ b/server/services/rlm/adapters.py
@@ -100,7 +100,9 @@ class ToolBridgeAdapter:
@staticmethod
def bridge(
- tool_data: Optional[List[Dict[str, Any]]], context: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None
+ tool_data: Optional[List[Dict[str, Any]]], context: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None,
+ broadcaster=None, parent_node_id: Optional[str] = None, workflow_id: Optional[str] = None,
+ provider: Optional[str] = None,
) -> Dict[str, Dict]:
from constants import AI_AGENT_TYPES, AI_CHAT_MODEL_TYPES
from services.handlers.tools import execute_tool
@@ -121,32 +123,109 @@ class ToolBridgeAdapter:
node_id = tool_info.get("node_id", "")
label = tool_info.get("label", node_type)
params = tool_info.get("parameters", {})
+ # Provider-visible name is the capability identity shown to the
+ # model and UI. Human labels remain descriptions only.
+ tool_name = re.sub(r"[^a-zA-Z0-9_]", "_", label.lower().replace(" ", "_"))
- def _make_sync_wrapper(t_type, t_id, t_params, t_label):
+ def _make_sync_wrapper(t_type, t_id, t_params, t_label, t_name):
def wrapper(**kwargs):
config = {
"node_type": t_type,
"node_id": t_id,
"parameters": t_params,
"label": t_label,
+ "workflow_id": workflow_id,
+ "parent_node_id": parent_node_id,
+ "provider": provider,
}
if context:
config["nodes"] = context.get("nodes", [])
config["edges"] = context.get("edges", [])
- future = asyncio.run_coroutine_threadsafe(
- execute_tool(t_label, kwargs, config),
- main_loop,
- )
+ config["execution_id"] = context.get("execution_id")
+ config["root_execution_id"] = context.get("root_execution_id")
+
+ async def execute_with_parent_status():
+ if broadcaster and parent_node_id:
+ await broadcaster.update_node_status(
+ parent_node_id,
+ "executing",
+ {"phase": "executing_tool", "agent_type": "rlm", "tool_name": t_name},
+ workflow_id=workflow_id,
+ )
+ if t_type != "_builtin_skill":
+ await broadcaster.broadcast_agent_capability(
+ parent_node_id,
+ capability_kind="tool",
+ capability_name=t_name,
+ state="started",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(t_id or "") or None,
+ provider=provider,
+ invocation_source="rlm",
+ )
+ try:
+ result = await execute_tool(t_label, kwargs, config)
+ if broadcaster and parent_node_id:
+ await broadcaster.update_node_status(
+ parent_node_id,
+ "executing",
+ {"phase": "tool_completed", "agent_type": "rlm", "tool_name": t_name},
+ workflow_id=workflow_id,
+ )
+ if t_type != "_builtin_skill":
+ await broadcaster.broadcast_agent_capability(
+ parent_node_id,
+ capability_kind="tool",
+ capability_name=t_name,
+ state="completed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(t_id or "") or None,
+ provider=provider,
+ invocation_source="rlm",
+ )
+ return result
+ except Exception as exc:
+ if broadcaster and parent_node_id:
+ await broadcaster.update_node_status(
+ parent_node_id,
+ "executing",
+ {
+ "phase": "tool_completed",
+ "agent_type": "rlm",
+ "tool_name": t_name,
+ "tool_failed": True,
+ },
+ workflow_id=workflow_id,
+ )
+ if t_type != "_builtin_skill":
+ await broadcaster.broadcast_agent_capability(
+ parent_node_id,
+ capability_kind="tool",
+ capability_name=t_name,
+ state="failed",
+ workflow_id=workflow_id,
+ execution_id=str((context or {}).get("execution_id") or "") or None,
+ root_execution_id=str((context or {}).get("root_execution_id") or "") or None,
+ target_node_id=str(t_id or "") or None,
+ provider=provider,
+ invocation_source="rlm",
+ error_code=type(exc).__name__,
+ )
+ raise
+
+ future = asyncio.run_coroutine_threadsafe(execute_with_parent_status(), main_loop)
return future.result(timeout=60)
return wrapper
- # Clean tool name (same pattern as _build_tool_from_node ai.py:2567)
- tool_name = re.sub(r"[^a-zA-Z0-9_]", "_", label.lower().replace(" ", "_"))
- description = ToolBridgeAdapter.TOOL_DESCRIPTIONS.get(node_type, f"Execute {label} ({node_type})")
+ description = params.get("tool_description") or ToolBridgeAdapter.TOOL_DESCRIPTIONS.get(node_type, f"Execute {label} ({node_type})")
tools[tool_name] = {
- "tool": _make_sync_wrapper(node_type, node_id, params, label),
+ "tool": _make_sync_wrapper(node_type, node_id, params, label, tool_name),
"description": description,
}
logger.info(f"[RLM] Bridged tool: {tool_name} ({node_type})")
diff --git a/server/services/rlm/service.py b/server/services/rlm/service.py
index 1ab72845..bde4e435 100644
--- a/server/services/rlm/service.py
+++ b/server/services/rlm/service.py
@@ -55,8 +55,8 @@ class RLMService:
prompt = parameters.get("prompt", "")
system_message = parameters.get("system_message", "")
- # Skill injection (reuse ai.py:833 _build_skill_system_prompt)
- # Collected as supplementary context -- appended to RLM prompt, never replaces it
+ # Personality skills remain eager. Standard skills are added to
+ # the same callable tool surface as every other connected tool.
from services.ai import _build_skill_system_prompt
supplementary_context = ""
@@ -89,6 +89,10 @@ class RLMService:
"message": f"Initializing RLM with {provider}/{model}",
"provider": provider,
"model": model,
+ "active_skills": [],
+ "last_skills": [],
+ "last_tool_name": None,
+ "last_capability": None,
},
)
@@ -106,7 +110,21 @@ class RLMService:
# === Adapter: Bridge tool nodes as RLM custom_tools ===
await broadcast_status("building_tools", {"message": "Bridging connected tools..."})
running_loop = asyncio.get_running_loop()
- custom_tools = ToolBridgeAdapter.bridge(tool_data, context, loop=running_loop)
+ from services.skill_runtime import skill_tool_info
+
+ effective_tool_data = list(tool_data or [])
+ progressive_skill_tool = skill_tool_info(skill_data or [], node_id)
+ if progressive_skill_tool:
+ effective_tool_data.append(progressive_skill_tool)
+ custom_tools = ToolBridgeAdapter.bridge(
+ effective_tool_data,
+ context,
+ loop=running_loop,
+ broadcaster=broadcaster,
+ parent_node_id=node_id,
+ workflow_id=workflow_id,
+ provider=provider,
+ )
# === RLM-specific parameters ===
max_iterations = int(flattened.get("max_iterations", DEFAULT_MAX_ITERATIONS))
@@ -211,3 +229,11 @@ class RLMService:
"error": str(e),
"execution_time": execution_time,
}
+ finally:
+ from services.skill_runtime import clear_skill_turn
+
+ await clear_skill_turn(
+ workflow_id or "",
+ str((context or {}).get("execution_id") or ""),
+ node_id,
+ )
diff --git a/server/services/skill_prompt.py b/server/services/skill_prompt.py
index 986ebf93..22033e37 100644
--- a/server/services/skill_prompt.py
+++ b/server/services/skill_prompt.py
@@ -2,7 +2,7 @@
Constructs system message text from connected skill nodes.
Personality skills get full SKILL.md instructions injected.
-Standard skills get brief registry descriptions.
+Standard skills are represented only by the connected ``Skill`` tool.
"""
from typing import Dict, Any, List
@@ -16,7 +16,9 @@ def build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str
"""Build skill injection text for the system message.
Personality skills (names ending in '-personality') get their FULL SKILL.md
- instructions injected. All other skills get brief registry descriptions only.
+ instructions injected. Standard skills do not alter the system prompt; their
+ names and descriptions live on the dynamically bound ``Skill`` tool, exactly
+ like other connected tool nodes.
Args:
skill_data: List of skill entries from _collect_agent_connections.
@@ -30,13 +32,8 @@ def build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str
if not skill_data:
return "", False
- from services.skill_loader import get_skill_loader
-
- skill_loader = get_skill_loader()
- skill_loader.scan_skills()
-
personality_blocks = []
- non_personality_names = []
+ standard_count = 0
for skill_info in skill_data:
skill_name = skill_info.get("skill_name") or skill_info.get("node_type", "").replace("Skill", "-skill").lower()
@@ -51,7 +48,7 @@ def build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str
else:
logger.warning(f"{log_prefix} Personality skill {skill_name} has no instructions")
else:
- non_personality_names.append(skill_name)
+ standard_count += 1
logger.debug(f"{log_prefix} Skill detected: {skill_name}")
parts = []
@@ -59,14 +56,10 @@ def build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str
for block in personality_blocks:
parts.append(block)
- if non_personality_names:
- registry_prompt = skill_loader.get_registry_prompt(non_personality_names)
- if registry_prompt:
- parts.append(registry_prompt)
-
if parts:
logger.debug(
- f"{log_prefix} Enhanced system message: {len(personality_blocks)} personality, {len(non_personality_names)} standard skills"
+ f"{log_prefix} Enhanced system message: {len(personality_blocks)} personality; "
+ f"{standard_count} standard skills exposed through the Skill tool"
)
return "\n\n".join(parts), len(personality_blocks) > 0
diff --git a/server/services/skill_runtime.py b/server/services/skill_runtime.py
new file mode 100644
index 00000000..367a43af
--- /dev/null
+++ b/server/services/skill_runtime.py
@@ -0,0 +1,311 @@
+"""Scoped progressive-disclosure runtime for connected agent skills."""
+
+from __future__ import annotations
+
+import hashlib
+import re
+import time
+from typing import Any, Dict, Iterable, List, Tuple
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+MAX_RESOURCE_CHARS = 16_000
+MAX_SEARCH_MATCHES = 50
+_loaded: Dict[Tuple[str, str, str, str], str] = {}
+_turn_activity: Dict[Tuple[str, str, str], Dict[str, Dict[str, Any]]] = {}
+
+
+class SkillRuntimeError(ValueError):
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.code = code
+
+
+def validate_connected_skills(skills: Iterable[Dict[str, Any]]) -> None:
+ by_name: Dict[str, List[Dict[str, str]]] = {}
+ for item in skills:
+ name = str(item.get("skill_name") or "").strip()
+ if not name:
+ continue
+ by_name.setdefault(name, []).append(
+ {
+ "node_id": str(item.get("master_skill_node_id") or item.get("node_id") or ""),
+ "label": str(item.get("label") or name),
+ }
+ )
+ duplicate = next(((name, refs) for name, refs in by_name.items() if len(refs) > 1), None)
+ if duplicate:
+ name, refs = duplicate
+ raise SkillRuntimeError(
+ "DUPLICATE_CONNECTED_SKILL_NAME",
+ f"Connected skill {name!r} is ambiguous across Master Skill nodes: {refs}",
+ )
+
+
+def standard_skill_descriptors(skills: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ validate_connected_skills(skills)
+ return [item for item in skills if not str(item.get("skill_name") or "").endswith("-personality")]
+
+
+def skill_tool_info(skills: Iterable[Dict[str, Any]], agent_node_id: str) -> Dict[str, Any] | None:
+ descriptors = standard_skill_descriptors(skills)
+ if not descriptors:
+ return None
+ rows = []
+ for item in descriptors:
+ name = str(item.get("skill_name") or "")
+ description = str(item.get("description") or (item.get("parameters") or {}).get("description") or "Connected skill")
+ rows.append(f"- {name}: {description}")
+ # Tool descriptions are part of the normal provider tool contract. Keep
+ # the surface bounded for providers with small function-description limits.
+ catalogue = "\n".join(rows)
+ if len(catalogue) > 7000:
+ catalogue = catalogue[:6950] + "\n[additional connected skills omitted from this description]"
+ tool_description = (
+ "Load the instructions for a connected skill when its description matches the task. "
+ "After loading, declared text resources can be read or searched with this same tool. "
+ "Do not guess skill instructions from their descriptions.\nConnected skills:\n"
+ f"{catalogue}"
+ )
+ return {
+ "node_type": "_builtin_skill",
+ "node_id": f"{agent_node_id}_skill_runtime",
+ "label": "Skill",
+ "parameters": {
+ "skill_descriptors": descriptors,
+ "agent_node_id": agent_node_id,
+ "tool_description": tool_description,
+ },
+ }
+
+
+def _resolve(config: Dict[str, Any], name: str) -> Dict[str, Any]:
+ descriptors = config.get("parameters", {}).get("skill_descriptors") or []
+ validate_connected_skills(descriptors)
+ matches = [item for item in descriptors if item.get("skill_name") == name]
+ if len(matches) != 1:
+ raise SkillRuntimeError("SKILL_NOT_CONNECTED", f"Skill {name!r} is not enabled and connected to this agent")
+ return matches[0]
+
+
+def _load_authoritative(descriptor: Dict[str, Any]):
+ from services.skill_loader import get_skill_loader
+
+ name = descriptor["skill_name"]
+ configured = str((descriptor.get("parameters") or {}).get("instructions") or "")
+ skill = get_skill_loader().load_skill(name)
+ if configured:
+ instructions = configured
+ elif skill:
+ instructions = skill.instructions
+ else:
+ raise SkillRuntimeError("SKILL_NOT_FOUND", f"Skill {name!r} could not be loaded")
+ return instructions, skill
+
+
+def _manifest(skill: Any) -> List[Dict[str, Any]]:
+ if not skill:
+ return []
+ result = []
+ for folder, values in (("references", skill.references), ("scripts", skill.scripts)):
+ for name, content in sorted(values.items()):
+ result.append({"path": f"{folder}/{name}", "characters": len(content)})
+ return result
+
+
+def _resource(skill: Any, path: str) -> str:
+ if not skill or not re.fullmatch(r"(?:references|scripts)/[^/\\]+", path or "") or ".." in path:
+ raise SkillRuntimeError("INVALID_SKILL_RESOURCE", "Resource must be a declared text reference or script")
+ folder, name = path.split("/", 1)
+ content = (skill.references if folder == "references" else skill.scripts).get(name)
+ if content is None:
+ raise SkillRuntimeError("SKILL_RESOURCE_NOT_FOUND", f"Undeclared skill resource: {path}")
+ return content
+
+
+async def _event(config: Dict[str, Any], descriptor: Dict[str, Any], action: str, state: str, **extra: Any) -> None:
+ from services.status_broadcaster import get_status_broadcaster
+
+ workflow_id = str(config.get("workflow_id") or "")
+ execution_id = str(config.get("execution_id") or "")
+ agent_id = str(config.get("parent_node_id") or (config.get("parameters") or {}).get("agent_node_id") or "")
+ master_id = str(descriptor.get("master_skill_node_id") or "")
+ name = str(descriptor.get("skill_name") or "")
+ key = (workflow_id, execution_id, agent_id)
+ activities = _turn_activity.setdefault(key, {})
+ if state == "loading":
+ activities[name] = {"name": name, "state": state, "master_skill_node_id": master_id}
+ else:
+ activities[name] = {"name": name, "state": state, "master_skill_node_id": master_id,
+ **{k: v for k, v in extra.items() if k in {"duration_ms", "error_code"}}}
+ public = [{k: v for k, v in item.items() if k != "master_skill_node_id"} for item in activities.values()]
+ broadcaster = get_status_broadcaster()
+ payload = {
+ "phase": "loading_skill" if state == "loading" else "skill_loaded",
+ "active_skills": public,
+ "last_capability": {"kind": "skill", "name": name, "state": state},
+ }
+ if agent_id:
+ await broadcaster.update_node_status(agent_id, "executing", payload, workflow_id=workflow_id)
+ if master_id:
+ master_public = [
+ {k: v for k, v in item.items() if k != "master_skill_node_id"}
+ for item in activities.values()
+ if item.get("master_skill_node_id") == master_id
+ ]
+ # Master Skill follows the same lifecycle as an ordinary tool node:
+ # glow only while content is being fetched. Loaded/resource-read
+ # results remain inspectable as badges but must not keep the node
+ # visually executing for the rest of the agent turn.
+ master_status = "executing" if state == "loading" else ("error" if state == "failed" else "success")
+ await broadcaster.update_node_status(
+ master_id,
+ master_status,
+ {"active_skills": master_public},
+ workflow_id=workflow_id,
+ )
+ tool_call_id = str(config.get("tool_call_id") or "")
+ event_id = None
+ if tool_call_id:
+ identity = "|".join(
+ (
+ workflow_id,
+ execution_id,
+ agent_id,
+ tool_call_id,
+ name,
+ action,
+ state,
+ )
+ )
+ event_id = f"agent-capability-{hashlib.sha256(identity.encode()).hexdigest()}"
+ await broadcaster.broadcast_agent_capability(
+ agent_id,
+ capability_kind="skill",
+ capability_name=name,
+ state=state,
+ workflow_id=workflow_id,
+ execution_id=execution_id,
+ root_execution_id=str(config.get("root_execution_id") or "") or None,
+ target_node_id=master_id or None,
+ action=action,
+ provider=str(config.get("provider") or "") or None,
+ invocation_source=str(config.get("skill_invocation_source") or "internal"),
+ tool_call_id=tool_call_id or None,
+ duration_ms=extra.get("duration_ms"),
+ returned_characters=extra.get("returned_characters"),
+ token_estimate=extra.get("token_estimate"),
+ content_hash=extra.get("content_hash"),
+ error_code=extra.get("error_code"),
+ event_id=event_id,
+ )
+
+
+async def execute_skill_tool(args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:
+ action = str(args.get("action") or "load")
+ name = str(args.get("skill_name") or "")
+ descriptor = _resolve(config, name)
+ started = time.monotonic()
+ await _event(config, descriptor, action, "loading")
+ try:
+ instructions, skill = _load_authoritative(descriptor)
+ content_hash = hashlib.sha256(instructions.encode()).hexdigest()
+ scope = (str(config.get("workflow_id") or ""), str(config.get("execution_id") or ""),
+ str(config.get("parent_node_id") or ""), name)
+ if action == "load":
+ if _loaded.get(scope) == content_hash:
+ result = {"status": "already_loaded", "skill_name": name, "content_hash": content_hash}
+ else:
+ _loaded[scope] = content_hash
+ result = {"status": "loaded", "skill_name": name, "content_hash": content_hash,
+ "instructions": instructions, "resources": _manifest(skill)}
+ state = "loaded"
+ else:
+ if _loaded.get(scope) != content_hash:
+ raise SkillRuntimeError("SKILL_NOT_LOADED", "Load the skill before reading its resources")
+ content = _resource(skill, str(args.get("path") or ""))
+ if action == "read_resource":
+ cursor = max(0, int(args.get("cursor") or 0)); limit = min(MAX_RESOURCE_CHARS, max(1, int(args.get("limit") or 4000)))
+ result = {"skill_name": name, "path": args.get("path"), "content": content[cursor:cursor + limit],
+ "cursor": cursor, "next_cursor": cursor + limit if cursor + limit < len(content) else None}
+ elif action == "search_resource":
+ query = str(args.get("query") or "")
+ if not query: raise SkillRuntimeError("INVALID_SKILL_QUERY", "query is required")
+ matches = [{"line": i, "text": line[:500]} for i, line in enumerate(content.splitlines(), 1) if query.lower() in line.lower()]
+ cursor = max(0, int(args.get("cursor") or 0)); limit = min(MAX_SEARCH_MATCHES, max(1, int(args.get("limit") or 20)))
+ result = {"skill_name": name, "path": args.get("path"), "matches": matches[cursor:cursor + limit],
+ "next_cursor": cursor + limit if cursor + limit < len(matches) else None}
+ else:
+ raise SkillRuntimeError("INVALID_SKILL_ACTION", f"Unsupported Skill action: {action}")
+ state = "resource_read"
+ duration = int((time.monotonic() - started) * 1000)
+ await _event(config, descriptor, action, state, content_hash=content_hash, duration_ms=duration,
+ returned_characters=len(str(result)), token_estimate=max(1, len(str(result)) // 4))
+ return result
+ except Exception as exc:
+ await _event(config, descriptor, action, "failed", duration_ms=int((time.monotonic() - started) * 1000),
+ error_code=getattr(exc, "code", "SKILL_RUNTIME_ERROR"))
+ raise
+
+
+async def clear_skill_turn(workflow_id: str, execution_id: str, agent_node_id: str) -> None:
+ key = (str(workflow_id or ""), str(execution_id or ""), str(agent_node_id or ""))
+ activities = _turn_activity.pop(key, {})
+ if not activities:
+ return
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+ if agent_node_id:
+ current = broadcaster.get_node_status(agent_node_id) or {}
+ current_data = dict(current.get("data") or {})
+ current_data["last_skills"] = [
+ {"name": name, "state": "used" if item.get("state") != "failed" else "failed"}
+ for name, item in activities.items()
+ ]
+ current_data["active_skills"] = []
+ await broadcaster.update_node_status(
+ agent_node_id,
+ str(current.get("status") or "executing"),
+ current_data,
+ workflow_id=workflow_id,
+ )
+ for item in activities.values():
+ master_id = item.get("master_skill_node_id")
+ if master_id:
+ same_master = [
+ {"name": name, "state": "used" if value.get("state") != "failed" else "failed"}
+ for name, value in activities.items()
+ if value.get("master_skill_node_id") == master_id
+ ]
+ await broadcaster.update_node_status(
+ master_id,
+ "idle",
+ {"active_skills": [], "last_skills": same_master},
+ workflow_id=workflow_id,
+ )
+ for name, item in activities.items():
+ event_id = None
+ if execution_id:
+ identity = "|".join(
+ (
+ str(workflow_id or ""),
+ str(execution_id or ""),
+ str(agent_node_id or ""),
+ name,
+ "cleared",
+ )
+ )
+ event_id = f"agent-capability-{hashlib.sha256(identity.encode()).hexdigest()}"
+ await broadcaster.broadcast_agent_capability(
+ agent_node_id,
+ capability_kind="skill",
+ capability_name=name,
+ state="cleared",
+ workflow_id=workflow_id,
+ execution_id=execution_id,
+ target_node_id=str(item.get("master_skill_node_id") or "") or None,
+ invocation_source="internal",
+ event_id=event_id,
+ )
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index 99f2a8b4..64218ad8 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -260,8 +260,9 @@ class StatusBroadcaster:
``".disconnected"`` / ``".runtime_failed"``.
provider: Provider id (e.g. ``"openai"``, ``"twitter"``).
customer_id: For multi-tenant OAuth flows. Default omitted.
- workflow_id: Optional CloudEvents extension attribute scoping
- runtime events to the workflow that triggered them.
+ workflow_id: Optional legacy extension-shaped workflow scope.
+ New event contracts put this field inside ``data`` because
+ underscores are not valid CloudEvents attribute names.
**data_extra: Additional fields merged into the envelope's
``data`` block (e.g. ``reason``, ``node_id``, ``error``
for runtime failure events).
@@ -396,6 +397,65 @@ class StatusBroadcaster:
}
)
+ async def broadcast_agent_capability(
+ self,
+ agent_node_id: str,
+ *,
+ capability_kind: str,
+ capability_name: str,
+ state: str,
+ workflow_id: Optional[str] = None,
+ execution_id: Optional[str] = None,
+ root_execution_id: Optional[str] = None,
+ target_node_id: Optional[str] = None,
+ action: Optional[str] = None,
+ provider: Optional[str] = None,
+ invocation_source: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
+ duration_ms: Optional[int] = None,
+ returned_characters: Optional[int] = None,
+ token_estimate: Optional[int] = None,
+ content_hash: Optional[str] = None,
+ error_code: Optional[str] = None,
+ event_id: Optional[str] = None,
+ ):
+ """Emit the canonical CloudEvents capability lifecycle envelope.
+
+ Capability ticks are high-frequency UI/observability telemetry, so
+ they are broadcast directly like ``agent_progress``. They must not go
+ through ``events.dispatch.emit``: that path performs Temporal
+ Visibility queries and Signals workflow controllers for trigger input.
+ """
+ from services.events import WorkflowEvent
+
+ event = WorkflowEvent.agent_capability(
+ agent_node_id,
+ capability_kind=capability_kind,
+ capability_name=capability_name,
+ state=state,
+ workflow_id=workflow_id,
+ execution_id=execution_id,
+ root_execution_id=root_execution_id,
+ target_node_id=target_node_id,
+ action=action,
+ provider=provider,
+ invocation_source=invocation_source,
+ tool_call_id=tool_call_id,
+ duration_ms=duration_ms,
+ returned_characters=returned_characters,
+ token_estimate=token_estimate,
+ content_hash=content_hash,
+ error_code=error_code,
+ event_id=event_id,
+ )
+ await self.broadcast(
+ {
+ "type": "agent_capability",
+ "data": event.model_dump(mode="json", exclude_none=True),
+ }
+ )
+ return event
+
async def broadcast_claude_session_spawned(
self,
memory_node_id: str,
@@ -574,9 +634,47 @@ class StatusBroadcaster:
logger.debug(
f"[BROADCAST] update_node_status: node={node_id}, status={status}, workflow={workflow_id}, connections={len(self._connections)}"
)
+ incoming_data = dict(data or {})
+ previous = self._status["nodes"].get(node_id) or {}
+ # The cache is historically keyed by node id. Never inherit sticky
+ # capability fields from a different workflow that happens to reuse
+ # that id; the browser store is workflow-scoped and the server must
+ # uphold the same boundary. A future cache-key migration can make
+ # this structural, but this guard keeps compatibility snapshots safe.
+ same_workflow = previous.get("workflow_id") == workflow_id
+ previous_data = (previous.get("data") or {}) if same_workflow else {}
+ # Skill activity belongs to the whole agent turn, while ordinary
+ # phase broadcasts belong to one loop step. Preserve the former when
+ # a later invoking_llm/tool_completed update does not mention it.
+ # Callers clear it explicitly with active_skills=[] at turn end.
+ if "active_skills" not in incoming_data and previous_data.get("active_skills"):
+ incoming_data["active_skills"] = previous_data["active_skills"]
+ # Turn cleanup converts active skill calls into a safe last_skills
+ # summary before the outer plugin/Temporal wrapper emits its terminal
+ # success payload. Preserve that summary across the wrapper broadcast;
+ # otherwise short normal-agent runs lose their usage text while slower
+ # team-lead runs appear to work. A new turn explicitly sends [] and
+ # therefore clears it.
+ if "last_skills" not in incoming_data and previous_data.get("last_skills"):
+ incoming_data["last_skills"] = previous_data["last_skills"]
+ # Tool calls are often faster than a paint frame. Retain only the safe
+ # LLM-visible tool name so every agent card can show the most recent
+ # capability after the phase advances back to invoking_llm/completed.
+ tool_name = incoming_data.get("tool_name")
+ if tool_name and tool_name != "Skill":
+ incoming_data["last_tool_name"] = tool_name
+ incoming_data["last_capability"] = {
+ "kind": "tool",
+ "name": tool_name,
+ "state": "failed" if incoming_data.get("error") or incoming_data.get("tool_failed") else "used",
+ }
+ elif "last_tool_name" not in incoming_data and previous_data.get("last_tool_name"):
+ incoming_data["last_tool_name"] = previous_data["last_tool_name"]
+ if "last_capability" not in incoming_data and previous_data.get("last_capability"):
+ incoming_data["last_capability"] = previous_data["last_capability"]
self._status["nodes"][node_id] = {
"status": status,
- "data": data or {},
+ "data": incoming_data,
"timestamp": asyncio.get_event_loop().time(),
"workflow_id": workflow_id,
}
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 617cb6c9..9dbf97fc 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -35,6 +35,7 @@ References:
from __future__ import annotations
import asyncio
+import hashlib
import logging
from typing import Any, Dict, List, Optional
@@ -389,12 +390,71 @@ async def broadcast_agent_progress(payload: Dict[str, Any]) -> Dict[str, Any]:
# _node_activity wrapper uses). Lets the FE swap node colors on
# executing/success/error without a separate CloudEvents handler.
status = payload.get("status")
- if status:
+ # Tool phases normally keep the AgentWorkflow itself in its existing
+ # ``executing`` state, so their callers do not need to repeat a status on
+ # every progress event. They *do* carry the LLM-visible tool name though.
+ # Previously this activity only copied payload details into ``node_status``
+ # when ``status`` was explicitly present. The parallel ``agent_progress``
+ # CloudEvent contains phase/counter fields only, which meant normal
+ # Temporal agents rendered a generic "Using Tool" phase and immediately
+ # lost the actual capability name. Team leads appeared healthier because
+ # their Task Manager/skill paths also emitted dedicated status events.
+ capability_data = {
+ key: payload[key]
+ for key in ("tool_name", "tool_node_id", "tool_failed")
+ if payload.get(key) is not None
+ }
+ status_for_node = status or ("executing" if capability_data else None)
+ if status_for_node:
+ lifecycle_data = {
+ "agent_type": "temporal",
+ **({"phase": phase} if phase else {}),
+ **capability_data,
+ }
+ if phase == "starting":
+ lifecycle_data.update({"active_skills": [], "last_skills": [], "last_tool_name": None, "last_capability": None})
await broadcaster.update_node_status(
node_id,
- status,
- {"agent_type": "temporal", **({"phase": phase} if phase else {})},
+ status_for_node,
+ lifecycle_data,
+ workflow_id=workflow_id,
+ )
+
+ # Tool use is a first-class CloudEvents occurrence. Keep it separate
+ # from the raw node-status projection: the latter is a reconnect snapshot,
+ # while this envelope supplies durable identity, ownership and retry
+ # deduplication semantics to live consumers.
+ tool_name = str(payload.get("tool_name") or "")
+ if tool_name and tool_name != "Skill" and phase in {"executing_tool", "tool_completed"}:
+ state = (
+ "started"
+ if phase == "executing_tool"
+ else ("failed" if payload.get("tool_failed") else "completed")
+ )
+ identity = "|".join(
+ (
+ str(workflow_id or ""),
+ str(payload.get("execution_id") or ""),
+ node_id,
+ str(payload.get("tool_call_id") or payload.get("iteration") or ""),
+ tool_name,
+ state,
+ )
+ )
+ await broadcaster.broadcast_agent_capability(
+ node_id,
+ capability_kind="tool",
+ capability_name=tool_name,
+ state=state,
workflow_id=workflow_id,
+ execution_id=str(payload.get("execution_id") or "") or None,
+ root_execution_id=str(payload.get("root_execution_id") or "") or None,
+ target_node_id=str(payload.get("tool_node_id") or "") or None,
+ provider=str(payload.get("provider") or "") or None,
+ invocation_source="temporal",
+ tool_call_id=str(payload.get("tool_call_id") or "") or None,
+ error_code=("TOOL_EXECUTION_FAILED" if state == "failed" else None),
+ event_id=f"agent-capability-{hashlib.sha256(identity.encode()).hexdigest()}",
)
# CloudEvents v1.0 envelope (com.opencompany.agent.progress). Drives
@@ -741,7 +801,13 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
# blew up Gemini's ``convert_to_genai_function_declarations``
# (``properties.<field> Input should be a valid dictionary or object``).
tools_payload: List[Dict[str, Any]] = []
- for tool_info in tool_data or []:
+ from services.skill_runtime import skill_tool_info
+
+ effective_tool_data = list(tool_data or [])
+ progressive_skill_tool = skill_tool_info(skill_data or [], node_id)
+ if progressive_skill_tool:
+ effective_tool_data.append(progressive_skill_tool)
+ for tool_info in effective_tool_data:
try:
tool, _config = await ai_service._build_tool_from_node(tool_info)
except Exception as e: # noqa: BLE001 — defensive: skip a broken tool
@@ -1012,6 +1078,48 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:
return {"tools": new_tools_payload}
[email protected](name="agent.skill.invoke.v1")
+async def invoke_agent_skill(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Retry-safe, history-recorded progressive skill invocation."""
+ from services.skill_runtime import execute_skill_tool
+
+ node_data = dict(payload.get("node_data") or {})
+ descriptors = node_data.pop("skill_descriptors", [])
+ action_args = {
+ key: node_data.get(key)
+ for key in ("action", "skill_name", "path", "query", "cursor", "limit")
+ if key in node_data
+ }
+ return await execute_skill_tool(
+ action_args,
+ {
+ "parameters": {"skill_descriptors": descriptors, "agent_node_id": payload.get("parent_node_id")},
+ "workflow_id": payload.get("workflow_id"),
+ "execution_id": payload.get("execution_id"),
+ "root_execution_id": payload.get("root_execution_id"),
+ "parent_node_id": payload.get("parent_node_id"),
+ # New histories carry the provider call id. The Temporal activity
+ # id is a stable fallback for pre-marker histories and remains
+ # identical across activity retries.
+ "tool_call_id": payload.get("tool_call_id") or activity.info().activity_id,
+ "provider": payload.get("provider"),
+ "skill_invocation_source": "temporal",
+ },
+ )
+
+
[email protected](name="agent.skill.clear.v1")
+async def clear_agent_skills(payload: Dict[str, Any]) -> Dict[str, Any]:
+ from services.skill_runtime import clear_skill_turn
+
+ await clear_skill_turn(
+ str(payload.get("workflow_id") or ""),
+ str(payload.get("execution_id") or ""),
+ str(payload.get("agent_node_id") or ""),
+ )
+ return {"cleared": True}
+
+
@activity.defn(name="agent.begin_delegation.v1")
async def begin_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:
"""Idempotently persist and claim a delegation before child startup."""
@@ -1297,6 +1405,8 @@ def collect_agent_activities() -> List[Any]:
broadcast_agent_progress,
store_agent_output,
refresh_agent_tools,
+ invoke_agent_skill,
+ clear_agent_skills,
begin_agent_delegation,
queue_agent_delegation,
acquire_subagent_permit,
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index b0bc7b81..f9835c9a 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -142,7 +142,9 @@ def _tool_call_metadata(
"invoking_agent_node_id": agent_node_id,
"agent_iteration": iteration + 1,
"tool_call_index": call_index + 1,
- "tool_call_id": str(call.get("id", "") or ""),
+ "tool_call_id": str(
+ call.get("id") or f"{iteration + 1}:{call_index + 1}"
+ ),
}
@@ -426,6 +428,9 @@ class AgentWorkflow:
agent_node_id = payload["node_id"]
agent_workflow_id = payload.get("workflow_id")
self._parent_node_id: Optional[str] = context.get("parent_node_id")
+ self._execution_id = task_scope_execution_id
+ self._root_execution_id = root_execution_id
+ self._provider = str(payload.get("provider") or "")
# The provider-visible name is the dispatch key. The legacy dict
# comprehension silently selected the last connected node when two
@@ -574,6 +579,30 @@ class AgentWorkflow:
cause = getattr(e, "cause", None)
detail = str(cause) if cause is not None else str(e)
workflow.logger.error(f"AgentWorkflow LLM step failed (iteration {iteration + 1}, " f"no auto-retry): {detail}")
+ # A failed model step is terminal for this run. Clear any
+ # turn-scoped skill badges and publish an error status before
+ # returning; otherwise the normal agent can remain visually
+ # stuck on its last capability while the workflow has already
+ # ended. Keep the public event free of provider error text.
+ await workflow.execute_activity(
+ "agent.skill.clear.v1",
+ args=[{
+ "workflow_id": payload.get("workflow_id"),
+ "execution_id": task_scope_execution_id,
+ "agent_node_id": agent_node_id,
+ }],
+ activity_id="clear-active-skills-failed",
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ await self._emit_phase(
+ agent_node_id,
+ agent_workflow_id,
+ iteration,
+ max_iterations,
+ phase="failed",
+ status="error",
+ )
return {
"success": False,
"error": f"LLM step failed: {detail}",
@@ -706,6 +735,7 @@ class AgentWorkflow:
"session_id": payload.get("session_id", "default"),
"execution_id": task_scope_execution_id,
"root_execution_id": root_execution_id,
+ "provider": payload.get("provider"),
"parent_node_id": agent_node_id,
"delegation_depth": delegation_depth + 1,
"team_id": payload.get("team_id") or context.get("team_id"),
@@ -1194,10 +1224,20 @@ class AgentWorkflow:
# so canvas-mutating tools (agentBuilder) render their
# summary text to match the user's current preference.
"auto_rebind_tools": bool(payload.get("auto_rebind_tools", True)),
+ # Provider call ids are normally present. The stable
+ # workflow position keeps CloudEvents occurrence IDs
+ # unique when an adapter omits one.
+ "tool_call_id": str(
+ call.get("id") or f"{iteration + 1}:{call_index + 1}"
+ ),
**call_metadata,
}
- tool_activity_name = f"node.{tool_info['node_type']}.v{tool_info['version']}"
+ tool_activity_name = (
+ "agent.skill.invoke.v1"
+ if tool_info["node_type"] == "_builtin_skill"
+ else f"node.{tool_info['node_type']}.v{tool_info['version']}"
+ )
await self._emit_phase(
agent_node_id,
@@ -1205,7 +1245,13 @@ class AgentWorkflow:
iteration,
max_iterations,
phase="executing_tool",
- extra={"tool_name": call.get("name", ""), "tool_node_id": tool_info["tool_node_id"]},
+ extra={
+ "tool_name": call.get("name", ""),
+ "tool_node_id": tool_info["tool_node_id"],
+ "tool_call_id": str(
+ call.get("id") or f"{iteration + 1}:{call_index + 1}"
+ ),
+ },
)
try:
@@ -1334,7 +1380,13 @@ class AgentWorkflow:
iteration,
max_iterations,
phase="tool_completed",
- extra={"tool_name": call.get("name", "")},
+ extra={
+ "tool_name": call.get("name", ""),
+ "tool_node_id": tool_info["tool_node_id"],
+ "tool_call_id": str(
+ call.get("id") or f"{iteration + 1}:{call_index + 1}"
+ ),
+ },
)
# Hot-rebind: if the tool returned ``operations`` (canvas
@@ -1458,6 +1510,25 @@ class AgentWorkflow:
retry_policy=AGENT_ACTIVITY_RETRY,
)
tool_content = f'{{"error": "{type(e).__name__}: {e}"}}'
+ await self._emit_phase(
+ agent_node_id,
+ agent_workflow_id,
+ iteration,
+ max_iterations,
+ phase="tool_completed",
+ extra={
+ "tool_name": call.get("name", ""),
+ "tool_node_id": tool_info["tool_node_id"],
+ "tool_call_id": str(
+ call.get("id") or f"{iteration + 1}:{call_index + 1}"
+ ),
+ # Do not put raw failures into public status
+ # events. This safe flag is enough for the
+ # broadcaster to retain ``tool <name>`` with a
+ # failed capability state.
+ "tool_failed": True,
+ },
+ )
messages.append(
{
@@ -1574,6 +1645,15 @@ class AgentWorkflow:
retry_policy=AGENT_ACTIVITY_RETRY,
)
+ await workflow.execute_activity(
+ "agent.skill.clear.v1",
+ args=[{"workflow_id": payload.get("workflow_id"), "execution_id": task_scope_execution_id,
+ "agent_node_id": agent_node_id}],
+ activity_id="clear-active-skills",
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+
# Final lifecycle broadcast — canvas glow goes green + FE
# consumers of com.opencompany.agent.progress see phase="completed".
await self._emit_phase(
@@ -1617,6 +1697,9 @@ class AgentWorkflow:
"iteration": iteration,
"max_iterations": max_iterations,
"phase": phase,
+ "execution_id": getattr(self, "_execution_id", None),
+ "root_execution_id": getattr(self, "_root_execution_id", None),
+ "provider": getattr(self, "_provider", None),
**({"status": status} if status else {}),
**(extra or {}),
}
@@ -1626,6 +1709,14 @@ class AgentWorkflow:
)
if self._parent_node_id:
+ # Parent progress is a relationship signal, not capability
+ # ownership. Never mirror the child's ``tool_name`` /
+ # ``tool_node_id`` extras onto the parent: the status activity
+ # turns those fields into durable ``last_capability`` metadata,
+ # which made a child's tool usage appear on other agent cards.
+ # The parent keeps its own delegate/task-manager tool status while
+ # this phase-only event merely indicates that descendant work is
+ # advancing.
await workflow.execute_activity(
"agent.broadcast_progress.v1",
args=[
@@ -1635,7 +1726,6 @@ class AgentWorkflow:
"iteration": iteration,
"max_iterations": max_iterations,
"phase": "delegating",
- **(extra or {}),
}
],
start_to_close_timeout=PERSIST_TURN_TIMEOUT,
diff --git a/server/skills/assistant/skill/SKILL.md b/server/skills/assistant/skill/SKILL.md
new file mode 100644
index 00000000..9bd6a4b8
--- /dev/null
+++ b/server/skills/assistant/skill/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: skill
+description: Select and load connected skills through the Skill tool using progressive disclosure. Use before applying a connected skill's procedures or consulting its declared references and scripts.
+metadata:
+ author: opencompany
+ version: "1.0"
+ category: automation
+ icon: "✨"
+ color: "#8b5cf6"
+---
+
+# Skill
+
+Use the `Skill` tool to retrieve instructions from skills connected through the
+Master Skill node.
+
+1. Inspect the connected skill names and descriptions exposed by the tool.
+2. When the task materially matches a skill, call `Skill` with
+ `action="load"` and its exact `skill_name` before applying that skill.
+3. Treat returned instructions as authoritative for the current conversation.
+ Do not infer missing instructions from metadata alone.
+4. Inspect the returned resource manifest. Use `read_resource` for a bounded
+ page or `search_resource` for line-numbered matches only when more detail is
+ required.
+5. Do not load unrelated skills. If a repeated load returns `already_loaded`,
+ continue using the instructions already present in the conversation.
+6. Loading a skill retrieves guidance; it does not execute ordinary action
+ tools. Call connected tools separately when the loaded instructions require
+ them.
diff --git a/server/tests/nodes/test_ai_agents.py b/server/tests/nodes/test_ai_agents.py
index 07e31d98..115bbf00 100644
--- a/server/tests/nodes/test_ai_agents.py
+++ b/server/tests/nodes/test_ai_agents.py
@@ -196,8 +196,13 @@ class TestAIAgent:
_, kwargs = harness.ai_service.execute_agent.call_args
skill_data = kwargs["skill_data"]
assert skill_data is not None
- assert len(skill_data) == 1 # shell-skill disabled -> skipped
- assert skill_data[0]["skill_name"] == "python-skill"
+ # The Master Skill's required Assistant ``skill`` entry is always
+ # present so every connected agent can learn the progressive-loading
+ # contract through the same skill surface. User-disabled entries are
+ # still excluded.
+ names = {item["skill_name"] for item in skill_data}
+ assert names == {"python-skill", "skill"}
+ assert "shell-skill" not in names
assert skill_data[0]["parameters"]["instructions"] == "Use python."
async def test_task_completion_strips_all_tools(self, harness):
diff --git a/server/tests/services/cli_agent/test_workflow_tool_context.py b/server/tests/services/cli_agent/test_workflow_tool_context.py
index 2c831d25..8215acd8 100644
--- a/server/tests/services/cli_agent/test_workflow_tool_context.py
+++ b/server/tests/services/cli_agent/test_workflow_tool_context.py
@@ -1,6 +1,7 @@
"""Execution identity passed from CLI BatchContext to connected tools."""
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from pydantic import BaseModel
@@ -14,11 +15,16 @@ class _Params(BaseModel):
async def test_handler_forwards_execution_workspace_and_parent_identity():
+ broadcaster = SimpleNamespace(
+ update_node_status=AsyncMock(),
+ broadcast_agent_capability=AsyncMock(),
+ )
context = BatchContext(
workflow_id="workflow-1",
node_id="cli-parent-1",
execution_id="execution-1",
workspace_dir=Path("workspace-1").resolve(),
+ broadcaster=broadcaster,
connected_tools=[
{
"node_id": "tool-1",
@@ -42,3 +48,13 @@ async def test_handler_forwards_execution_workspace_and_parent_identity():
assert config["execution_id"] == "execution-1"
assert config["workspace_dir"] == str(Path("workspace-1").resolve())
assert config["parent_node_id"] == "cli-parent-1"
+ assert [call.kwargs["state"] for call in broadcaster.broadcast_agent_capability.await_args_list] == [
+ "started",
+ "completed",
+ ]
+ started = broadcaster.broadcast_agent_capability.await_args_list[0]
+ assert started.args == ("cli-parent-1",)
+ assert started.kwargs["capability_name"] == "contextTestTool"
+ assert started.kwargs["target_node_id"] == "tool-1"
+ assert started.kwargs["workflow_id"] == "workflow-1"
+ assert started.kwargs["execution_id"] == "execution-1"
diff --git a/server/tests/services/test_events.py b/server/tests/services/test_events.py
index c2f6bc42..4b8d10b1 100644
--- a/server/tests/services/test_events.py
+++ b/server/tests/services/test_events.py
@@ -9,7 +9,7 @@ import hmac
import json
import time
from typing import Iterable
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
import pytest
@@ -66,6 +66,76 @@ class TestWorkflowEvent:
assert ev.data == {"text": "hi"}
assert ev.source.startswith("legacy://")
+ def test_agent_capability_is_a_safe_cloudevent(self):
+ from services.events import WorkflowEvent
+
+ ev = WorkflowEvent.agent_capability(
+ "agent-7",
+ capability_kind="skill",
+ capability_name="write-todos",
+ state="loaded",
+ workflow_id="7",
+ execution_id="12",
+ root_execution_id="10",
+ target_node_id="master-skill-7",
+ tool_call_id="call-1",
+ content_hash="sha256-safe",
+ event_id="occurrence-1",
+ )
+ dumped = ev.model_dump(mode="json", exclude_none=True)
+
+ assert dumped["specversion"] == "1.0"
+ assert dumped["id"] == "occurrence-1"
+ assert dumped["source"] == "opencompany://services/agent"
+ assert dumped["type"] == "com.opencompany.agent.skill.loaded"
+ assert dumped["subject"] == "agent-7"
+ assert dumped["dataschema"].endswith("agent.skill.loaded.json")
+ assert dumped["data"]["author_node_id"] == "agent-7"
+ # Operational scope belongs to data, not invalid snake_case
+ # CloudEvents extension attributes.
+ assert "execution_id" not in {key for key in dumped if dumped[key] is not None}
+ for secret_field in ("prompt", "tool_args", "result", "instructions", "resource", "error"):
+ assert secret_field not in dumped["data"]
+
+ @pytest.mark.parametrize(
+ ("kind", "state"),
+ [("skill", "started"), ("tool", "loaded"), ("other", "started")],
+ )
+ def test_agent_capability_rejects_invalid_kind_state_pairs(self, kind, state):
+ from services.events import WorkflowEvent
+
+ with pytest.raises(ValueError):
+ WorkflowEvent.agent_capability(
+ "agent-1",
+ capability_kind=kind,
+ capability_name="capability",
+ state=state,
+ )
+
+ def test_capability_broadcaster_keeps_cloudevent_envelope_intact(self):
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ broadcaster.broadcast = AsyncMock()
+ event = _run(
+ broadcaster.broadcast_agent_capability(
+ "agent-1",
+ capability_kind="tool",
+ capability_name="write_todos",
+ state="started",
+ workflow_id="1",
+ event_id="tool-start-1",
+ )
+ )
+
+ assert event.subject == "agent-1"
+ wire = broadcaster.broadcast.await_args.args[0]
+ assert wire["type"] == "agent_capability"
+ assert wire["data"]["specversion"] == "1.0"
+ assert wire["data"]["id"] == "tool-start-1"
+ assert wire["data"]["type"] == "com.opencompany.agent.tool.started"
+ assert wire["data"]["data"]["workflow_id"] == "1"
+
# ============================================================================
# Verifiers
diff --git a/server/tests/services/test_skill_runtime.py b/server/tests/services/test_skill_runtime.py
new file mode 100644
index 00000000..81559371
--- /dev/null
+++ b/server/tests/services/test_skill_runtime.py
@@ -0,0 +1,275 @@
+from types import SimpleNamespace
+
+import pytest
+
+from services.skill_runtime import (
+ SkillRuntimeError,
+ execute_skill_tool,
+ skill_tool_info,
+ validate_connected_skills,
+)
+
+
+class _Broadcaster:
+ def __init__(self):
+ self.events = []
+
+ async def update_node_status(self, *args, **kwargs):
+ self.events.append(("status", args, kwargs))
+
+ async def broadcast_agent_capability(self, agent_node_id, **data):
+ self.events.append(("capability", agent_node_id, data))
+
+
+def _descriptor(instructions="custom authoritative body"):
+ return {
+ "node_id": "master-1_todo-skill",
+ "master_skill_node_id": "master-1",
+ "node_type": "masterSkill",
+ "skill_name": "todo-skill",
+ "description": "Manage todos",
+ "label": "Todo",
+ "parameters": {"instructions": instructions},
+ }
+
+
+def test_duplicate_connected_names_are_blocking():
+ with pytest.raises(SkillRuntimeError) as exc:
+ validate_connected_skills([_descriptor(), {**_descriptor(), "master_skill_node_id": "master-2"}])
+ assert exc.value.code == "DUPLICATE_CONNECTED_SKILL_NAME"
+
+
+def test_standard_skills_create_one_provider_neutral_tool():
+ info = skill_tool_info([_descriptor()], "agent-1")
+ assert info["node_type"] == "_builtin_skill"
+ assert info["parameters"]["skill_descriptors"][0]["skill_name"] == "todo-skill"
+
+
+def test_standard_skill_does_not_modify_agent_system_prompt(monkeypatch):
+ from services.skill_prompt import build_skill_system_prompt
+ import services.skill_loader as loader_module
+
+ monkeypatch.setattr(loader_module, "get_skill_loader", lambda: SimpleNamespace(scan_skills=lambda: {}))
+ prompt, personality = build_skill_system_prompt([_descriptor()])
+ assert not personality
+ assert prompt == ""
+
+
+def test_connected_skill_metadata_is_on_tool_description():
+ info = skill_tool_info([_descriptor()], "agent-1")
+ description = info["parameters"]["tool_description"]
+ assert "todo-skill" in description
+ assert "Manage todos" in description
+ assert "Load the instructions" in description
+
+
+async def test_node_phase_updates_preserve_active_skills_until_explicit_clear():
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ await broadcaster.update_node_status("agent-1", "executing", {"active_skills": [{"name": "todo-skill", "state": "loaded"}]}, "1")
+ await broadcaster.update_node_status("agent-1", "executing", {"phase": "invoking_llm"}, "1")
+ assert broadcaster.get_node_status("agent-1")["data"]["active_skills"][0]["name"] == "todo-skill"
+ await broadcaster.update_node_status("agent-1", "success", {"active_skills": []}, "1")
+ assert broadcaster.get_node_status("agent-1")["data"]["active_skills"] == []
+
+
+async def test_fast_tool_name_remains_visible_until_next_agent_turn():
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ await broadcaster.update_node_status("agent-1", "executing", {"phase": "executing_tool", "tool_name": "write_todos"}, "1")
+ await broadcaster.update_node_status("agent-1", "executing", {"phase": "invoking_llm"}, "1")
+ assert broadcaster.get_node_status("agent-1")["data"]["last_tool_name"] == "write_todos"
+ await broadcaster.update_node_status("agent-1", "executing", {"phase": "initializing", "last_tool_name": None}, "1")
+ assert broadcaster.get_node_status("agent-1")["data"]["last_tool_name"] is None
+
+
+async def test_failed_tool_retains_safe_failed_capability_without_public_error_text():
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ await broadcaster.update_node_status(
+ "agent-1",
+ "executing",
+ {
+ "phase": "tool_completed",
+ "tool_name": "write_todos",
+ "tool_failed": True,
+ },
+ "1",
+ )
+ capability = broadcaster.get_node_status("agent-1")["data"]["last_capability"]
+ assert capability == {"kind": "tool", "name": "write_todos", "state": "failed"}
+
+
+async def test_normal_agent_terminal_wrapper_preserves_last_skill_usage():
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ await broadcaster.update_node_status(
+ "normal-agent",
+ "executing",
+ {"active_skills": [], "last_skills": [{"name": "memory-skill", "state": "used"}]},
+ "1",
+ )
+ # BaseNode / per-type activity terminal payload does not know about the
+ # inner agent loop's skill lifecycle.
+ await broadcaster.update_node_status(
+ "normal-agent",
+ "success",
+ {"response": "done", "execution_id": "1"},
+ "1",
+ )
+ assert broadcaster.get_node_status("normal-agent")["data"]["last_skills"] == [
+ {"name": "memory-skill", "state": "used"}
+ ]
+ # The next turn owns an explicit reset.
+ await broadcaster.update_node_status(
+ "normal-agent",
+ "executing",
+ {"phase": "initializing", "active_skills": [], "last_skills": [], "last_tool_name": None},
+ "1",
+ )
+ assert broadcaster.get_node_status("normal-agent")["data"]["last_skills"] == []
+
+
+async def test_capability_summary_never_leaks_between_workflows_with_same_node_id():
+ from services.status_broadcaster import StatusBroadcaster
+
+ broadcaster = StatusBroadcaster()
+ await broadcaster.update_node_status(
+ "shared-agent",
+ "success",
+ {
+ "last_skills": [{"name": "workflow-a-skill", "state": "used"}],
+ "last_capability": {"kind": "skill", "name": "workflow-a-skill", "state": "used"},
+ },
+ "workflow-a",
+ )
+ await broadcaster.update_node_status(
+ "shared-agent",
+ "success",
+ {"response": "workflow b result"},
+ "workflow-b",
+ )
+
+ current = broadcaster.get_node_status("shared-agent")
+ assert current["workflow_id"] == "workflow-b"
+ assert "last_skills" not in current["data"]
+ assert "last_capability" not in current["data"]
+
+
+async def test_customized_content_wins_and_repeat_load_is_compact(monkeypatch):
+ import services.skill_loader as loader_module
+ import services.status_broadcaster as broadcaster_module
+
+ skill = SimpleNamespace(
+ instructions="global body",
+ references={"guide.md": "one\nneedle\nthree"},
+ scripts={},
+ )
+ monkeypatch.setattr(loader_module, "get_skill_loader", lambda: SimpleNamespace(load_skill=lambda name: skill))
+ broadcaster = _Broadcaster()
+ monkeypatch.setattr(broadcaster_module, "get_status_broadcaster", lambda: broadcaster)
+ config = {
+ "parameters": {"skill_descriptors": [_descriptor()]},
+ "workflow_id": "1", "execution_id": "9", "parent_node_id": "agent-1",
+ "tool_call_id": "call-9",
+ }
+
+ first = await execute_skill_tool({"action": "load", "skill_name": "todo-skill"}, config)
+ second = await execute_skill_tool({"action": "load", "skill_name": "todo-skill"}, config)
+ assert first["instructions"] == "custom authoritative body"
+ assert first["status"] == "loaded"
+ assert second == {"status": "already_loaded", "skill_name": "todo-skill", "content_hash": first["content_hash"]}
+ master_statuses = [item[1][1] for item in broadcaster.events if item[0] == "status" and item[1][0] == "master-1"]
+ assert "executing" in master_statuses
+ assert master_statuses[-1] == "success"
+
+ capability_events = [item[2] for item in broadcaster.events if item[0] == "capability"]
+ loading_ids = [item["event_id"] for item in capability_events if item["state"] == "loading"]
+ loaded_ids = [item["event_id"] for item in capability_events if item["state"] == "loaded"]
+ assert len(loading_ids) == 2 and len(set(loading_ids)) == 1
+ assert len(loaded_ids) == 2 and len(set(loaded_ids)) == 1
+ assert loading_ids[0] != loaded_ids[0]
+
+ found = await execute_skill_tool(
+ {"action": "search_resource", "skill_name": "todo-skill", "path": "references/guide.md", "query": "needle"},
+ config,
+ )
+ assert found["matches"] == [{"line": 2, "text": "needle"}]
+
+
+async def test_each_master_skill_receives_only_its_own_skill_activity(monkeypatch):
+ import services.skill_loader as loader_module
+ import services.status_broadcaster as broadcaster_module
+
+ first = {
+ **_descriptor("first instructions"),
+ "skill_name": "first-skill",
+ "master_skill_node_id": "master-first",
+ }
+ second = {
+ **_descriptor("second instructions"),
+ "skill_name": "second-skill",
+ "master_skill_node_id": "master-second",
+ }
+ monkeypatch.setattr(
+ loader_module,
+ "get_skill_loader",
+ lambda: SimpleNamespace(load_skill=lambda _name: None),
+ )
+ broadcaster = _Broadcaster()
+ monkeypatch.setattr(
+ broadcaster_module,
+ "get_status_broadcaster",
+ lambda: broadcaster,
+ )
+ config = {
+ "parameters": {"skill_descriptors": [first, second]},
+ "workflow_id": "1",
+ "execution_id": "master-scope-test",
+ "parent_node_id": "agent-1",
+ }
+
+ await execute_skill_tool(
+ {"action": "load", "skill_name": "first-skill"},
+ config,
+ )
+ await execute_skill_tool(
+ {"action": "load", "skill_name": "second-skill"},
+ config,
+ )
+
+ second_master_events = [
+ item[1][2]["active_skills"]
+ for item in broadcaster.events
+ if item[0] == "status" and item[1][0] == "master-second"
+ ]
+ assert second_master_events
+ assert {
+ item["name"] for item in second_master_events[-1]
+ } == {"second-skill"}
+
+
+async def test_resource_requires_successful_load(monkeypatch):
+ import services.skill_loader as loader_module
+ import services.status_broadcaster as broadcaster_module
+
+ skill = SimpleNamespace(instructions="body", references={"guide.md": "text"}, scripts={})
+ monkeypatch.setattr(loader_module, "get_skill_loader", lambda: SimpleNamespace(load_skill=lambda name: skill))
+ monkeypatch.setattr(broadcaster_module, "get_status_broadcaster", lambda: _Broadcaster())
+ config = {"parameters": {"skill_descriptors": [_descriptor("body")]}, "workflow_id": "1",
+ "execution_id": "fresh", "parent_node_id": "agent-1"}
+ with pytest.raises(SkillRuntimeError) as exc:
+ await execute_skill_tool({"action": "read_resource", "skill_name": "todo-skill", "path": "references/guide.md"}, config)
+ assert exc.value.code == "SKILL_NOT_LOADED"
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 5473bbb0..8cf77ae0 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -16,7 +16,7 @@ canary agent migration lands. This file locks the static contracts:
from __future__ import annotations
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
class TestAgentWorkflowDefinition:
@@ -281,6 +281,8 @@ class TestAgentActivities:
"agent.refresh_tools.v1",
"agent.register_task_execution.v1",
"agent.release_subagent_permit.v1",
+ "agent.skill.clear.v1",
+ "agent.skill.invoke.v1",
"agent.store_output.v1",
]
@@ -296,6 +298,103 @@ class TestAgentActivities:
defn = getattr(broadcast_agent_progress, "__temporal_activity_definition")
assert defn.name == "agent.broadcast_progress.v1"
+ async def test_temporal_tool_progress_preserves_visible_tool_name(self, monkeypatch):
+ """A phase-only Temporal event must still update the agent card.
+
+ AgentWorkflow intentionally omits ``status`` for intermediate tool
+ phases. The activity therefore owns translating a tool-bearing
+ progress payload into an executing node status; otherwise the
+ frontend receives only the generic phase and cannot render
+ ``tool <name>`` for normal AI agents.
+ """
+ import services.status_broadcaster as broadcaster_module
+ from services.temporal.agent_activities import broadcast_agent_progress
+
+ broadcaster = MagicMock()
+ broadcaster.update_node_status = AsyncMock()
+ broadcaster.broadcast_agent_progress = AsyncMock()
+ broadcaster.broadcast_agent_capability = AsyncMock()
+ monkeypatch.setattr(
+ broadcaster_module,
+ "get_status_broadcaster",
+ lambda: broadcaster,
+ )
+
+ await broadcast_agent_progress(
+ {
+ "node_id": "normal-agent",
+ "workflow_id": "7",
+ "iteration": 1,
+ "max_iterations": 20,
+ "phase": "executing_tool",
+ "tool_name": "write_todos",
+ "tool_node_id": "7:writeTodos:1",
+ }
+ )
+
+ broadcaster.update_node_status.assert_awaited_once_with(
+ "normal-agent",
+ "executing",
+ {
+ "agent_type": "temporal",
+ "phase": "executing_tool",
+ "tool_name": "write_todos",
+ "tool_node_id": "7:writeTodos:1",
+ },
+ workflow_id="7",
+ )
+ broadcaster.broadcast_agent_capability.assert_awaited_once()
+ capability = broadcaster.broadcast_agent_capability.await_args
+ assert capability.args == ("normal-agent",)
+ assert capability.kwargs["capability_kind"] == "tool"
+ assert capability.kwargs["capability_name"] == "write_todos"
+ assert capability.kwargs["state"] == "started"
+ assert capability.kwargs["target_node_id"] == "7:writeTodos:1"
+ assert capability.kwargs["event_id"].startswith("agent-capability-")
+
+ def test_llm_failure_clears_skills_and_emits_terminal_error(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ failure = source.index("except Exception as e:", source.index('"agent.execute_llm_step.v1"'))
+ terminal_return = source.index('"error_type": "LLMStepError"', failure)
+ cleanup = source.index('activity_id="clear-active-skills-failed"', failure)
+ error_phase = source.index('phase="failed"', cleanup)
+ assert failure < cleanup < error_phase < terminal_return
+
+ async def test_child_capability_metadata_is_not_mirrored_to_parent(self, monkeypatch):
+ """Only the agent that invoked a capability may display its name."""
+ import services.temporal.agent_workflow as workflow_module
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ execute_activity = AsyncMock(return_value=None)
+ monkeypatch.setattr(workflow_module.workflow, "execute_activity", execute_activity)
+
+ agent = AgentWorkflow()
+ agent._parent_node_id = "lead-agent"
+ await agent._emit_phase(
+ "child-agent",
+ "7",
+ 2,
+ 20,
+ phase="executing_tool",
+ extra={"tool_name": "child_search", "tool_node_id": "7:search:1"},
+ )
+
+ child_payload = execute_activity.await_args_list[0].kwargs["args"][0]
+ parent_payload = execute_activity.await_args_list[1].kwargs["args"][0]
+ assert child_payload["node_id"] == "child-agent"
+ assert child_payload["tool_name"] == "child_search"
+ assert parent_payload == {
+ "node_id": "lead-agent",
+ "workflow_id": "7",
+ "iteration": 2,
+ "max_iterations": 20,
+ "phase": "delegating",
+ }
+
class TestWorkerWiring:
"""Worker registration must include AgentWorkflow + activities so the