Repository navigation
feat(tools): Replace tool declarations @tool_function decorators on IInstanceBase - #599
Conversation
…n decorators on IInstanceBase
Every tool-providing node previously required two parallel classes: an
IInstance (pipeline integration) and a ToolsBase driver (tool definitions).
The driver implemented three abstract methods (_tool_query, _tool_validate,
_tool_invoke) and the IInstance wired them together with boilerplate
delegation in invoke(). This created a parallel system that was hard to
understand and tedious to write — the driver often just called back into
the instance for the actual work, and every node repeated the same
delegation pattern.
The root cause was that tool declaration was separate from the class that
actually owned the state and connections needed to execute the tool. A
MySQL node's IInstance had the database connection, the LLM access, and
the lane handlers — but its tool definitions lived in a MySQLDriver class
that had to reach back into the instance for everything.
This commit collapses both layers into one by adding @invoke_function and
@tool_function decorators directly to IInstanceBase in rocketlib/filters.py.
Any IInstanceBase subclass can now declare tool entry points with a
decorator — the method name becomes the tool ID, the decorator carries the
schema and description, and the base class invoke() dispatches
automatically. No separate driver class, no factory method, no delegation.
Usage example — static tool:
from rocketlib import IInstanceBase, tool_function
class IInstance(IInstanceBase):
IGlobal: IGlobal
@tool_function(
input_schema={
'type': 'object',
'required': ['url', 'method'],
'properties': {
'url': {'type': 'string'},
'method': {'type': 'string', 'enum': ['GET', 'POST']},
},
},
description='Make an HTTP request.',
)
def http_request(self, args):
if args['method'] not in self.IGlobal.enabled_methods:
raise ValueError('Method not allowed')
return execute_request(url=args['url'], method=args['method'])
Usage example — dynamic description from config:
class DatabaseInstanceBase(IInstanceBase):
@tool_function(
input_schema={...},
description=lambda self: (
f'Query the {self._db_display_name()} database. '
f'Just describe what data you need.'
),
)
def get_data(self, args):
...
Usage example — dynamic tools (MCP, tools discovered at runtime):
class IInstance(IInstanceBase):
def _tool_query_dynamic(self):
return self.IGlobal.list_namespaced_tools()
def _tool_invoke_dynamic(self, *, tool_name, input_obj):
server, bare = tool_name.split('.', 1)
return self.IGlobal.call_tool(server, bare, input_obj)
The decorator system follows the existing control/invoke layering:
control() <- engine entry point, rarely overridden
└─ invoke() <- dispatches on param.op
├─ tool.* -> @tool_function methods (tool.query builds
| descriptors, tool.invoke calls the method)
└─ other ops -> @invoke_function methods (op name = method name)
Key design decisions:
- Decorators live in rocketlib/filters.py with zero upstream dependencies.
The declaration plumbing (ToolDescriptor, @tool_function, @invoke_function,
dispatch logic) is entirely self-contained in the engine base layer.
- No tool name prefix. Tool IDs are bare method names (e.g. 'get_data',
not 'mysql.get_data'). The agent host already namespaces by nodeId to
prevent collisions between multiple nodes of the same type.
- No separate validation step. tool.validate is removed from the dispatch.
Validation is guard clauses at the top of the function body — simpler,
more obvious, impossible to forget.
- Decorator parameters accept static values or callables. Roughly half of
all tools need runtime config in their descriptions (e.g. the user-entered
database description, allowed import lists, display names). These use
lambda self: ... which is resolved at tool.query time when self.IGlobal
is available. This is a first-class pattern, not an escape hatch.
- User-entered tool descriptions are auto-prepended. The "tool" field from
the node config (e.g. "This is a database of world cities") is read via
_tool_config_description() and prepended to every @tool_function's
description automatically. Individual decorators only provide the fixed
part.
- Dynamic tools (MCP) use _tool_query_dynamic / _tool_invoke_dynamic
overrides on IInstanceBase for tools discovered at runtime from external
servers. Only MCP needs this.
- Backward compatible with the agent-as-tool pattern. The four agent nodes
still use _AgentAsToolProvider via ToolsBase — they are not tool nodes in
the decorator sense, they use a different mechanism for exposing
themselves as tools to other agents.
Migrated nodes:
- chart_chartjs: generate_chart (also eliminated the set_llm_invoker
callback — IInstance calls self.instance.invoke('llm', ...) directly)
- tool_python: execute
- tool_http_request: http_request
- tool_firecrawl: scrape_url, map_url
- memory_internal: put, get, list, clear
- db_mysql, db_postgres: get_data, get_schema, get_sql (via
DatabaseInstanceBase with callable descriptors for display names)
- db_neo4j: get_data, get_schema, get_cypher
- mcp_client: dynamic tools via _tool_query_dynamic/_tool_invoke_dynamic
Deleted (11 files, ~1600 lines):
- All *_driver.py files (http, python, firecrawl, chartjs, memory, mcp,
mysql, postgres, neo4j)
- packages/ai/src/ai/common/database/db_driver_base.py
- DatabaseDriverBase removed from database __init__.py exports
Updated imports:
- Agent framework drivers (langchain, crewai, deepagent) and AgentBase
now use ToolDescriptor from rocketlib instead of ToolsBase.ToolDescriptor
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
📝 WalkthroughWalkthroughThis PR replaces many ToolsBase driver implementations with decorator-driven tool handlers: it adds Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant IInstanceBase
participant DecoratorMeta
participant DynamicHandler
participant ToolMethod
Client->>IInstanceBase: invoke(op, param)
alt op starts with "tool."
IInstanceBase->>IInstanceBase: _dispatch_tool(param, op)
alt op == "tool.query"
IInstanceBase->>DecoratorMeta: _collect_tool_methods()
DecoratorMeta-->>IInstanceBase: static tool descriptors
IInstanceBase->>DynamicHandler: _tool_query_dynamic()
DynamicHandler-->>IInstanceBase: dynamic descriptors
IInstanceBase-->>Client: return aggregated tool list
else op == "tool.invoke"
IInstanceBase->>DecoratorMeta: find matching static tool method
alt static method found
IInstanceBase->>ToolMethod: call with input_obj
ToolMethod-->>IInstanceBase: result
else
IInstanceBase->>DynamicHandler: _tool_invoke_dynamic(tool_name, input_obj)
DynamicHandler-->>IInstanceBase: result
end
IInstanceBase-->>Client: return result
end
else
IInstanceBase->>DecoratorMeta: lookup `@invoke_function` handler
IInstanceBase->>ToolMethod: dispatch call
ToolMethod-->>Client: return value
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 11
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nodes/src/nodes/chart_chartjs/IInstance.py`:
- Around line 140-142: The ternary passed to q.addQuestion is inverted and hard
to read; change the expression used in the q.addQuestion call (in IInstance.py)
to a more idiomatic form — e.g., use description if description else "Generate
the Chart.js configuration JSON for the data above." or simply description or
"Generate the Chart.js configuration JSON for the data above." so the default
string is used only when description is falsy.
In `@nodes/src/nodes/db_neo4j/IInstance.py`:
- Around line 158-163: The branching in the block that checks is_valid, cypher,
and _is_cypher_safe(cypher) should be flattened to remove the unnecessary
"elif": after the first "return {'cypher': cypher, 'valid': True}" replace "elif
is_valid and cypher:" with "if is_valid and cypher:" (or restructure to
sequential if/return/else) so control flow is the same but without the redundant
elif; update the code that references is_valid, cypher, and _is_cypher_safe to
use the simplified if / else structure.
In `@nodes/src/nodes/memory_internal/IInstance.py`:
- Around line 49-53: The methods in class IInstance (put, get, delete — the
blocks at the shown diffs) currently coerce non-dict args to {} silently; change
them to validate that args is a dict and raise ValueError with a clear message
(e.g., "args must be a dict") if not, then continue to extract key/value via
args.get('key', '') / args.get('value') as before; update the put, get, and
delete method bodies to perform this check instead of replacing args with {} to
match other tool nodes' behavior.
- Line 28: The class attribute _store in IInstance.py is annotated as
MemoryStore but initialized to None; change its type to allow None (e.g.,
Optional[MemoryStore] or MemoryStore | None) and add the corresponding import of
Optional from typing if using Optional, so the declaration for _store (in class
IInstance) correctly reflects that it may be None without a type mismatch.
In `@nodes/src/nodes/tool_firecrawl/IInstance.py`:
- Around line 79-82: The current try/except around metadata.model_dump()
swallows all exceptions silently; change it to catch Exception but log the error
(with stack/exception info) before falling back to metadata = {} so debugging
context is preserved — for example, use a module logger
(logging.getLogger(__name__) or the existing logger in this module) and call
logger.debug or logger.exception (or logger.debug(..., exc_info=True)) inside
the except block, then set metadata = {}; keep the same conditional model_dump
check and behavior otherwise.
- Around line 136-141: The JSON parsing block inside IInstance (where
json.loads(input_obj) is used) silently swallows all errors; change the broad
try-except-pass to catch narrowly (json.JSONDecodeError and TypeError) and emit
a diagnostic log entry (use the module/class logger or self.logger used
elsewhere in IInstance) that includes the offending input and the exception
message so malformed JSON is visible during debugging; do not reintroduce broad
except-pass—either log and continue only for expected types or let unexpected
errors propagate.
In `@nodes/src/nodes/tool_http_request/IGlobal.py`:
- Around line 53-54: The class-level mutable defaults enabled_methods and
url_patterns can cause shared-state bugs; change their declarations to use None
(or remove the default and only annotate the types) and then initialize them to
fresh instances inside beginGlobal (e.g., set enabled_methods = set() and
url_patterns = [] within beginGlobal) so each IGlobal instance gets its own
containers; update references to enabled_methods and url_patterns accordingly.
In `@nodes/src/nodes/tool_http_request/IInstance.py`:
- Around line 183-186: The current logic in IInstance.py sets args['body'] from
body_json using str(body_json) for non-dict/list values which can produce
invalid JSON; change it to: if body_json is a dict or list use
json.dumps(body_json); if it's already a str treat it as the raw JSON string
unchanged; otherwise attempt json.dumps(body_json) and if json.dumps raises
TypeError/ValueError raise or log a clear error (or return a validation error)
instead of falling back to str(). Update the block that assigns args['body']
(referencing the body_json variable and args['body'] assignment) to implement
this behavior.
In `@nodes/src/nodes/tool_python/IGlobal.py`:
- Line 33: Replace typing.Set with the built-in generic set: remove Set from the
typing import and change all annotations that use Set[...] to use set[...]
instead (i.e., update the IGlobal-related type hints in this file where Set is
used). Ensure you keep Optional and other typing wrappers intact (e.g.,
Optional[set[str]]), update imports accordingly (no typing.Set), and run a quick
type check to confirm no remaining references to typing.Set remain.
In `@packages/ai/src/ai/common/database/db_instance_base.py`:
- Around line 115-116: The code converts raw_limit to int without validation
(raw_limit → int(raw_limit)) which can raise ValueError/TypeError; update the
logic in db_instance_base.py to safely parse and clamp the limit: either wrap
the int(raw_limit) conversion in a try/except and fall back to the default (250)
on parse errors, then apply max/min bounds (1..25000) to set limit, or refactor
to call a shared helper like the existing _clamp_limit used in db_neo4j; adjust
the variables raw_limit and limit accordingly so non-numeric inputs no longer
raise.
- Around line 214-219: Simplify the branching logic in the SQL validation return
block by replacing the `elif` statement with `if`, since the first `if`
condition returns early, making the `elif` check unnecessary. After the first
`if is_valid and sql_query and is_sql_safe(sql_query):` block that returns,
change the subsequent `elif is_valid and sql_query:` to just `if is_valid and
sql_query:`. Optionally, you can also replace the final `else:` with a direct
`return` statement since all paths now explicitly return, simplifying the
branching structure.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 35ec41f6-7854-4cb6-9aa7-73d19cd4de72
📒 Files selected for processing (34)
nodes/src/nodes/agent_crewai/crewai.pynodes/src/nodes/agent_deepagent/deepagent.pynodes/src/nodes/agent_langchain/langchain.pynodes/src/nodes/chart_chartjs/IGlobal.pynodes/src/nodes/chart_chartjs/IInstance.pynodes/src/nodes/chart_chartjs/chartjs_driver.pynodes/src/nodes/db_mysql/IInstance.pynodes/src/nodes/db_mysql/mysql_driver.pynodes/src/nodes/db_neo4j/IInstance.pynodes/src/nodes/db_neo4j/neo4j_driver.pynodes/src/nodes/db_postgres/IInstance.pynodes/src/nodes/db_postgres/postgres_driver.pynodes/src/nodes/mcp_client/IGlobal.pynodes/src/nodes/mcp_client/IInstance.pynodes/src/nodes/mcp_client/mcp_driver.pynodes/src/nodes/memory_internal/IInstance.pynodes/src/nodes/memory_internal/__init__.pynodes/src/nodes/memory_internal/memory_driver.pynodes/src/nodes/tool_firecrawl/IGlobal.pynodes/src/nodes/tool_firecrawl/IInstance.pynodes/src/nodes/tool_firecrawl/firecrawl_driver.pynodes/src/nodes/tool_http_request/IGlobal.pynodes/src/nodes/tool_http_request/IInstance.pynodes/src/nodes/tool_http_request/http_driver.pynodes/src/nodes/tool_python/IGlobal.pynodes/src/nodes/tool_python/IInstance.pynodes/src/nodes/tool_python/python_driver.pypackages/ai/src/ai/common/agent/_internal/agent_tool.pypackages/ai/src/ai/common/agent/agent.pypackages/ai/src/ai/common/database/__init__.pypackages/ai/src/ai/common/database/db_driver_base.pypackages/ai/src/ai/common/database/db_instance_base.pypackages/server/engine-lib/rocketlib-python/lib/rocketlib/__init__.pypackages/server/engine-lib/rocketlib-python/lib/rocketlib/filters.py
💤 Files with no reviewable changes (10)
- nodes/src/nodes/db_mysql/mysql_driver.py
- nodes/src/nodes/db_postgres/postgres_driver.py
- nodes/src/nodes/db_neo4j/neo4j_driver.py
- nodes/src/nodes/chart_chartjs/chartjs_driver.py
- nodes/src/nodes/memory_internal/memory_driver.py
- nodes/src/nodes/tool_firecrawl/firecrawl_driver.py
- nodes/src/nodes/mcp_client/mcp_driver.py
- nodes/src/nodes/tool_python/python_driver.py
- packages/ai/src/ai/common/database/db_driver_base.py
- nodes/src/nodes/tool_http_request/http_driver.py
The @tool_function decorator builds ToolDescriptors with camelCase keys
(inputSchema, outputSchema) but three of the four agent drivers were
reading snake_case (input_schema), silently getting None for every
tool's parameter schema. The LLM never saw real parameter definitions —
it always fell back to a generic "accept anything" schema.
Tool schema fix (3 agent drivers)
---
- agent_langchain: td.get('input_schema') → td.get('inputSchema')
- agent_deepagent: td.get('input_schema') → td.get('inputSchema')
- agent_crewai: already handled both with fallback; simplified to
td.get('inputSchema') for consistency
llm_base: replace manual dispatch with @invoke_function
---
The manual match/case block in llm_base/IInstance.py duplicated what the
base class invoke() auto-dispatcher already provides. Replaced with four
@invoke_function decorated methods (ask, getContextLength,
getOutputLength, getTokenCounter). Removed the now-unused IInvokeLLM
import.
Node hardening (from code review)
---
- chart_chartjs: inverted ternary → idiomatic `description or "default"`
- memory_internal: _store type MemoryStore → MemoryStore | None; put/get/
clear raise ValueError on non-dict args instead of silently coercing
- tool_firecrawl: metadata.model_dump() exception now logged via warning;
JSON parse catch narrowed to JSONDecodeError/TypeError with log
- tool_http_request/IGlobal: mutable class-level set()/[] defaults →
None; typing.Set/List → built-in set/list
- tool_http_request/IInstance: str(body_json) fallback → json.dumps() so
non-dict/list/str values produce valid JSON
- tool_python/IGlobal: typing.Set → built-in set; removed unused imports
- db_instance_base: int(raw_limit) wrapped in try/except, falls back to
250 on parse error instead of raising
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
nodes/src/nodes/tool_python/IGlobal.py (1)
79-88:⚠️ Potential issue | 🟠 MajorGuard
_parse_allowed_modulesagainst non-list JSON resultsIf
json.loads()returns a primitive (e.g.,123/true), Line 88 attempts to iterate a non-iterable and raisesTypeError. This can break global initialization on malformed config.💡 Proposed fix
if not isinstance(raw, list): import json try: raw = json.loads(str(raw)) except (json.JSONDecodeError, TypeError, ValueError): return set() + if not isinstance(raw, list): + return set() modules: set[str] = set() for row in raw: if not hasattr(row, 'get'): continue🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/tool_python/IGlobal.py` around lines 79 - 88, The _parse_allowed_modules function currently json.loads(str(raw)) without ensuring the result is a list, so a primitive (e.g., 123/true) will make the subsequent for row in raw raise TypeError; fix by validating the decoded value is a list before iterating (if not a list, return an empty set or coerce to an empty list), i.e., after json.loads assign to raw and check isinstance(raw, list) and only then proceed to build modules (referencing raw, modules and _parse_allowed_modules).packages/ai/src/ai/common/database/db_instance_base.py (1)
24-35: 🧹 Nitpick | 🔵 TrivialModule docstring references removed method
_create_driver.The docstring states derived classes must implement
_create_driver, but this method no longer exists after the refactor. The actual required method is_db_display_name()as correctly documented in the class docstring at line 59-60.📝 Proposed docstring update
""" Shared instance-level base class for relational database nodes. -Derived classes must implement one method: - -- ``_create_driver``: instantiate and return the concrete tool-provider driver - for this database engine (e.g. ``MySQLDriver``, ``PostgreSQLDriver``). +Derived classes must implement: + +- ``_db_display_name``: return the human-readable database name used in tool + descriptions (e.g. ``'MySQL'``, ``'PostgreSQL'``). All pipeline lane handlers (``writeQuestions``, ``writeTable``, ``writeAnswers``), query execution, and data insertion are implemented here using SQLAlchemy abstractions that work across dialects. """🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/ai/src/ai/common/database/db_instance_base.py` around lines 24 - 35, The module docstring still instructs derived classes to implement `_create_driver`, which no longer exists after the refactor; update the docstring to reference the actual required abstract method `_db_display_name()` (as already documented in the class docstring) and remove or replace all mentions of `_create_driver` in the top-level module/class docstring so it accurately reflects the current implementation and required overrides.nodes/src/nodes/tool_http_request/IGlobal.py (1)
69-87:⚠️ Potential issue | 🟠 MajorFail closed when the whitelist config is malformed.
If
urlWhitelistcannot be parsed, or everywhitelistPatternfails to compile,_build_guardrails()returnspatterns = [].IInstance._validate_guardrails()then treats that exactly like an intentionally empty whitelist, so a typo disables the URL guardrail instead of blocking startup. Empty/unset allowlists can stay permissive; malformed non-empty allowlists should not.🔒 Proposed fix
raw_whitelist = cfg.get('urlWhitelist') or [] if not isinstance(raw_whitelist, list): import json try: raw_whitelist = json.loads(str(raw_whitelist)) - except (json.JSONDecodeError, TypeError, ValueError): - raw_whitelist = [] + except (json.JSONDecodeError, TypeError, ValueError) as e: + raise ValueError('urlWhitelist must be a JSON array of whitelist entries') from e + if not isinstance(raw_whitelist, list): + raise ValueError('urlWhitelist must be a JSON array of whitelist entries') + whitelist_configured = bool(raw_whitelist) patterns: list[re.Pattern] = [] for row in raw_whitelist: if not hasattr(row, 'get'): continue pat_str = str(row.get('whitelistPattern') or '').strip() if pat_str: try: patterns.append(re.compile(pat_str)) except re.error as e: - warning(f'Invalid URL whitelist regex {pat_str!r}: {e}') + raise ValueError(f'Invalid URL whitelist regex {pat_str!r}: {e}') from e + + if whitelist_configured and not patterns: + raise ValueError('urlWhitelist is configured but produced no valid regex patterns')Also applies to: 97-99
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/tool_http_request/IGlobal.py` around lines 69 - 87, _build_guardrails() currently treats a malformed or entirely-invalid urlWhitelist as an empty list of patterns, which disables the guardrail; change it to fail-closed: detect when cfg contains a non-empty raw_whitelist that cannot be parsed (JSON decode error or wrong type) or when every whitelistPattern either is missing or fails regex compilation, and in those cases raise a clear exception or return an explicit error state (rather than patterns = []). Update callers (IInstance._validate_guardrails()) to treat that error state as a startup-blocking failure. Reference raw_whitelist, whitelistPattern, patterns, _build_guardrails(), and IInstance._validate_guardrails() when locating and implementing this change.
♻️ Duplicate comments (1)
nodes/src/nodes/memory_internal/IInstance.py (1)
37-53:⚠️ Potential issue | 🟠 MajorThese tool methods still accept schema-invalid payloads.
With standalone validation removed, these handlers need to enforce their own
input_schema. Right nowput()/get()turn a missingkeyinto'',put()accepts a missingvalue,list()ignores non-object payloads entirely, andclear()forwards non-string keys. Those cases will silently read/write the wrong memory entry instead of failing fast.Suggested validation
def put(self, args): """Store a value under a key.""" if not isinstance(args, dict): raise ValueError('args must be a dict') - return self._store.put(args.get('key', ''), args.get('value')) + key = args.get('key') + if not isinstance(key, str): + raise ValueError('key must be a string') + if 'value' not in args: + raise ValueError('value is required') + return self._store.put(key, args['value']) def get(self, args): """Retrieve a value by key.""" if not isinstance(args, dict): raise ValueError('args must be a dict') - return self._store.get(args.get('key', '')) + key = args.get('key') + if not isinstance(key, str): + raise ValueError('key must be a string') + return self._store.get(key) def list(self, args): """List all keys.""" + if not isinstance(args, dict): + raise ValueError('args must be a dict') return self._store.list() def clear(self, args): """Clear one or all keys.""" if not isinstance(args, dict): raise ValueError('args must be a dict') - return self._store.clear(args.get('key')) + key = args.get('key') + if key is not None and not isinstance(key, str): + raise ValueError('key must be a string') + return self._store.clear(key)Also applies to: 55-77, 79-92, 94-115
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/memory_internal/IInstance.py` around lines 37 - 53, The tool handlers (methods put, get, list, clear on IInstance) must enforce their declared input_schema at runtime: validate args is a dict, that required fields exist, and that types/constraints are correct (e.g., 'key' must be a non-empty string matching the expected pattern; 'value' must be present for put; list should only accept an object payload and validate any optional fields; clear/get must accept only string keys). If validation fails, raise ValueError (or similar) instead of coercing to ''/None or forwarding bad types; implement these checks at the start of put(), get(), list(), and clear() (or delegate to a shared validator) and return/continue only after inputs are confirmed valid.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nodes/src/nodes/agent_langchain/langchain.py`:
- Line 70: Update the bind_tools method signature on
RocketRideToolCallingChatModel: change the parameter type from tools: Any to
tools: object, rename **kwargs to **_kwargs to mark it unused, and unquote the
return annotation so it reads -> RocketRideToolCallingChatModel (remove the
string quotes) since the module uses from __future__ import annotations; this
fixes ANN401, ARG002, and UP037 lint violations.
In `@nodes/src/nodes/chart_chartjs/IInstance.py`:
- Around line 98-102: The code only truncates top-level lists but still creates
an unbounded data_str which can be huge; after serializing the input (the data
-> data_str flow used before calling q.addContext) introduce a
MAX_SERIALIZED_BYTES constant (e.g., ~20k) and enforce it: serialize with
json.dumps(default=str) for dicts/other types and for strings, then if
len(data_str) > MAX_SERIALIZED_BYTES either (a) produce a concise
summary/summary-placeholder (for example keep the first N and last M characters
with an explicit "...[truncated]" marker) or (b) raise a clear error/ValueError
indicating the payload is too large to add to context; update the code paths
around data, data_str and the call site q.addContext(...) to use the bounded
data_str (or reject) so oversized dicts/strings are handled the same as lists.
- Around line 87-105: The method currently allows scalars/strings for data and
doesn't validate title/description; update the input checks in IInstance (the
block handling data, chart_type, title, description) to enforce schema: require
data to be either list or dict (raise ValueError if data is None or not an
instance of (list, dict)), keep the empty-check for list/dict, and only allow
truncation for lists; validate chart_type against valid_types as before; also
validate that title and description, if provided, are strings (raise ValueError
if not). If raw string data is intended, instead expand the input_schema
accordingly and do not accept strings here.
- Around line 151-157: Validate and normalize the LLM output before wrapping it
in a chartjs fence: in the code that reads result.getText() into response_text
(the block handling result/result.getText in IInstance), strip any existing
fenced code markers (leading/trailing triple backticks and info strings), trim
whitespace, raise a RuntimeError if the resulting response_text is empty, then
attempt to json.loads(response_text) and raise a RuntimeError on
JSONDecodeError; if parsing succeeds re-serialize with json.dumps(parsed,
ensure_ascii=False) and return that inside the ```chartjs\n...\n``` fence. Also
add an import json at the module top if not present.
In `@nodes/src/nodes/llm_base/IInstance.py`:
- Around line 36-45: The handlers getContextLength, getOutputLength, and
getTokenCounter declare an unused parameter named param which triggers Ruff
ARG002; update each signature to mark the unused dispatch payload as intentional
by renaming the argument to _param (e.g., def getContextLength(self, _param)) or
alternatively add a targeted comment (# noqa: ARG002) to each handler, ensuring
you change the signatures in the methods getContextLength, getOutputLength, and
getTokenCounter so the linter no longer flags the unused parameter.
In `@nodes/src/nodes/tool_firecrawl/IInstance.py`:
- Around line 51-60: The schema declares 'formats' as an array but the
implementation only returns a single 'content' string and never uses
args['formats'] when calling Firecrawl; either implement multi-format support or
make the schema honest. Fix by updating the code that calls Firecrawl (the place
that reads args and invokes Firecrawl around the current call block) to iterate
over args['formats'] (or default ['markdown']), request/generate content for
each format (call Firecrawl per format or convert the single result), and
populate the output as a mapping from format to content (e.g., content: {
"markdown": "...", "html": "..." }); also update output_schema: change 'content'
from {'type':'string'} to
{'type':'object','additionalProperties':{'type':'string'}} so clients can
receive multiple formats. Alternatively, if you prefer single-format support,
change the 'formats' schema to accept a single string and ensure args['formats']
is used to select that format and return one content string.
- Around line 144-146: The warning currently logs the raw unexpected payload
(input_obj!r) which can leak sensitive fields; update the warning in
IInstance.py to omit the raw object and only include the type name or a minimal
redacted summary (e.g., use type(input_obj).__name__ or a fixed "<redacted>"
token) where the current warning call occurs, keeping the existing message
prefix 'firecrawl: unexpected input type' and returning {} as before.
- Line 102: The decorator in nodes/src/nodes/tool_firecrawl/IInstance.py uses a
double-quoted string for the description parameter; change that double-quoted
literal to use single quotes instead (i.e., update the description="Map a
website's structure and return all discovered URLs." to use single quotes) so
the decorator's description argument follows the repository's Python style for
nodes/**/*.py; update the literal where the decorator with the description
argument appears in IInstance.py.
In `@nodes/src/nodes/tool_http_request/IInstance.py`:
- Around line 163-178: The code currently skips validation for non-dict
auth/body and may call .strip() on non-strings or silently ignore non-dict
basic_auth; update the validation in the auth and body handling blocks so they
fail fast: if auth is present and not a dict, raise a ValueError; when reading
auth_type ensure the value is a string (or raise) before .strip() and likewise
require basic_auth to be a dict (raise if not) when auth_type == 'basic'; mirror
these checks for body—raise if body is not a dict, require body.type to be a
string before .strip(), require body.raw to be a dict when body_type == 'raw'
and require raw.content_type to be a string before .strip(), and validate
against valid_auth_types, valid_body_types, and valid_raw_content_types
accordingly (also apply same fixes around the body checks noted at the other
location).
In `@packages/ai/src/ai/common/database/db_instance_base.py`:
- Around line 121-131: The returned dicts from the SQL flow are inconsistent:
ensure every return includes a 'valid' boolean so consumers can always check
result.get('valid'); update the success path in the method that calls
get_sql/_executeSQLQuery/_sanitize_row to return {'valid': True, 'rows': rows,
'sql': sql_query, 'row_limit': limit} and update the execution-failure path that
currently returns {'error': 'Query execution failed', 'sql': sql_query, 'rows':
[]} to include 'valid': False; keep the existing failed-get_sql path as-is (it
already provides valid: False).
---
Outside diff comments:
In `@nodes/src/nodes/tool_http_request/IGlobal.py`:
- Around line 69-87: _build_guardrails() currently treats a malformed or
entirely-invalid urlWhitelist as an empty list of patterns, which disables the
guardrail; change it to fail-closed: detect when cfg contains a non-empty
raw_whitelist that cannot be parsed (JSON decode error or wrong type) or when
every whitelistPattern either is missing or fails regex compilation, and in
those cases raise a clear exception or return an explicit error state (rather
than patterns = []). Update callers (IInstance._validate_guardrails()) to treat
that error state as a startup-blocking failure. Reference raw_whitelist,
whitelistPattern, patterns, _build_guardrails(), and
IInstance._validate_guardrails() when locating and implementing this change.
In `@nodes/src/nodes/tool_python/IGlobal.py`:
- Around line 79-88: The _parse_allowed_modules function currently
json.loads(str(raw)) without ensuring the result is a list, so a primitive
(e.g., 123/true) will make the subsequent for row in raw raise TypeError; fix by
validating the decoded value is a list before iterating (if not a list, return
an empty set or coerce to an empty list), i.e., after json.loads assign to raw
and check isinstance(raw, list) and only then proceed to build modules
(referencing raw, modules and _parse_allowed_modules).
In `@packages/ai/src/ai/common/database/db_instance_base.py`:
- Around line 24-35: The module docstring still instructs derived classes to
implement `_create_driver`, which no longer exists after the refactor; update
the docstring to reference the actual required abstract method
`_db_display_name()` (as already documented in the class docstring) and remove
or replace all mentions of `_create_driver` in the top-level module/class
docstring so it accurately reflects the current implementation and required
overrides.
---
Duplicate comments:
In `@nodes/src/nodes/memory_internal/IInstance.py`:
- Around line 37-53: The tool handlers (methods put, get, list, clear on
IInstance) must enforce their declared input_schema at runtime: validate args is
a dict, that required fields exist, and that types/constraints are correct
(e.g., 'key' must be a non-empty string matching the expected pattern; 'value'
must be present for put; list should only accept an object payload and validate
any optional fields; clear/get must accept only string keys). If validation
fails, raise ValueError (or similar) instead of coercing to ''/None or
forwarding bad types; implement these checks at the start of put(), get(),
list(), and clear() (or delegate to a shared validator) and return/continue only
after inputs are confirmed valid.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 5fb8ac22-da13-478b-99e4-6a7c1048d0de
📒 Files selected for processing (11)
nodes/src/nodes/agent_crewai/crewai.pynodes/src/nodes/agent_deepagent/deepagent.pynodes/src/nodes/agent_langchain/langchain.pynodes/src/nodes/chart_chartjs/IInstance.pynodes/src/nodes/llm_base/IInstance.pynodes/src/nodes/memory_internal/IInstance.pynodes/src/nodes/tool_firecrawl/IInstance.pynodes/src/nodes/tool_http_request/IGlobal.pynodes/src/nodes/tool_http_request/IInstance.pynodes/src/nodes/tool_python/IGlobal.pypackages/ai/src/ai/common/database/db_instance_base.py
…hardening - langchain: fix ANN401/ARG002/UP037 on bind_tools signature - chart_chartjs: reject non-list/dict data, cap serialized payload at 20KB, validate and normalize LLM JSON output before wrapping in chartjs fence - llm_base: rename unused param → _param on invoke handlers (ARG002) - tool_firecrawl: simplify formats array → single format string, redact raw payload from warning log - tool_http_request: fail-fast validation on auth/body types and nested fields; fail-closed on malformed urlWhitelist in guardrails - tool_python: validate json.loads result is a list before iterating - memory_internal: enforce key type/presence in put/get/clear, add dict check to list handler - db_instance_base: add missing valid boolean to success/failure return dicts; fix stale _create_driver docstring → _db_display_name() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (3)
nodes/src/nodes/tool_http_request/IInstance.py (1)
200-213:⚠️ Potential issue | 🟡 MinorInconsistent handling of
basic_authvs other shortcuts.Line 212 silently ignores non-dict
basic_authvalues (if isinstance(basic_auth, dict)), while_validate_guardrailswould later fail ifauth.basicis not a dict. This differs frombearer_tokenwhich usesstr(bearer_token)to coerce.The past review suggested raising
ValueErrorfor non-dictbasic_auth. Consider aligning behavior:🛡️ Proposed fix for consistency
basic_auth = args.pop('basic_auth', None) - if isinstance(basic_auth, dict) and not args.get('auth'): + if basic_auth is not None and not args.get('auth'): + if not isinstance(basic_auth, dict): + raise ValueError('basic_auth must be a JSON object with username and password') args['auth'] = {'type': 'basic', 'basic': basic_auth}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/tool_http_request/IInstance.py` around lines 200 - 213, _normalize_shortcuts currently ignores non-dict basic_auth values, causing later _validate_guardrails to fail; change the basic_auth handling to pop basic_auth and, if basic_auth is not None and args.get('auth') is falsy, validate its type: if isinstance(basic_auth, dict) set args['auth'] = {'type': 'basic', 'basic': basic_auth} else raise a ValueError("basic_auth must be a dict") so invalid inputs are surfaced consistently (similar to how bearer_token is coerced/validated) and to match _validate_guardrails expectations.nodes/src/nodes/tool_firecrawl/IInstance.py (2)
103-103:⚠️ Potential issue | 🟡 MinorUse single quotes for this decorator description.
Line 103 is the remaining changed regular string literal using double quotes in a
nodes/**/*.pyfile.As per coding guidelines, "
nodes/**/*.py: Python pipeline nodes: use single quotes, ruff for linting/formatting, PEP 257 docstrings, target Python 3.10+."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/tool_firecrawl/IInstance.py` at line 103, The decorator description in nodes/src/nodes/tool_firecrawl/IInstance.py uses double quotes; update the string literal for the decorator's description parameter to use single quotes (e.g., change "Map a website's structure and return all discovered URLs." to 'Map a website's structure and return all discovered URLs.') so it follows the project's Python style for nodes/**/*.py; ensure only the decorator's description argument is modified and run ruff/formatting checks afterward.
45-52:⚠️ Potential issue | 🟠 Major
formatis declared, but not actually requested from Firecrawl.Line 51 advertises a selectable
format, but Line 71 always callsscrape(url)without it, and Line 74 silently falls back tomarkdownif the requested attribute is missing. Sohtmlonly works if the SDK happens to return it by default, and invalid values can still reportsuccess=Truewith markdown content. Either forwardformatinto the Firecrawl request, or narrow this tool to markdown-only and reject anything else locally.In the Firecrawl Python SDK version used by rocketride-server, how do you request `html` versus `markdown` from `FirecrawlApp.scrape`, and does calling `scrape(url)` without explicit format options return both representations or only the default one?Also applies to: 71-75
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nodes/src/nodes/tool_firecrawl/IInstance.py` around lines 45 - 52, The tool accepts a 'format' in the input schema but never forwards it to Firecrawl, so html requests are ignored and invalid values can silently fall back to markdown; update the code that currently calls FirecrawlApp.scrape(url) to extract and validate the incoming format from the tool input (the same 'format' declared under the tool_function input_schema) and pass it into FirecrawlApp.scrape (or the SDK's equivalent parameter) so the request explicitly asks for 'html' or 'markdown'; if the SDK uses a different option name, map the 'format' value to that parameter, and return a clear error (success=false) for unsupported values instead of silently defaulting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nodes/src/nodes/llm_base/IInstance.py`:
- Around line 36-50: Add concise PEP 257 one-line docstrings (triple-quoted
single-line summaries) to each `@invoke_function` method in IInstance:
getContextLength, getOutputLength, getTokenCounter, and ask so the new LLM
invoke surface is self-describing; ensure docstrings use single quotes and
describe what each operation returns/accepts (e.g., 'Return total token
capacity', 'Return output token count', 'Return token counter callable', 'Ask
the LLM with param.question and return response'), keep them brief, placed
immediately under each def, and run ruff/formatting to satisfy Python 3.10+
style rules.
In `@nodes/src/nodes/memory_internal/IInstance.py`:
- Around line 33-35: The open method currently calls self._store.clear() which
can raise AttributeError if self._store is None (e.g., open called before
beginInstance or if beginInstance failed); update open in IInstance to
defensively check if self._store is truthy (not None) before calling clear —
either no-op when _store is None or initialize _store to an empty dict/list as
appropriate for the class invariant; reference the open method and the
beginInstance initialization of self._store when making the change.
In `@nodes/src/nodes/tool_firecrawl/IInstance.py`:
- Around line 67-69: Validate that `url` is a non-empty trimmed string before
calling the SDK: replace the loose truthiness check (url = args.get('url'); if
not url: ...) with an explicit type and content check such as if not
isinstance(url, str) or not url.strip(): raise ValueError('scrape_url requires a
non-empty string `url` parameter'); apply the same pattern where `url` is later
retrieved (the other occurrence that proxies to firecrawl_wrapper) so invalid
types like ints, lists, or whitespace-only strings are rejected early with a
clear tool-validation error.
In `@nodes/src/nodes/tool_http_request/IGlobal.py`:
- Around line 105-107: The endGlobal method in IGlobal currently resets
enabled_methods to an empty set and url_patterns to an empty list which
conflicts with the class defaults of None; update IGlobal.endGlobal to assign
None to self.enabled_methods and self.url_patterns (or otherwise match the class
initializer behavior) so the uninitialized state remains consistent with checks
in IInstance (and adjust any call sites or tests that expect containers
accordingly).
In `@nodes/src/nodes/tool_http_request/IInstance.py`:
- Around line 154-155: The code in IInstance where you check if method.upper()
not in self.IGlobal.enabled_methods can raise a TypeError when
self.IGlobal.enabled_methods is None; update the check to first handle a
None/empty case (e.g., treat None as no enabled methods or raise a clear
ValueError) before using "in" or join. Specifically, in the method that
validates request methods (referencing self.IGlobal.enabled_methods in
IInstance), guard against None by replacing the direct membership and join usage
with a safe check (if enabled_methods is falsy) and provide an explicit error
message that includes a safe representation of enabled methods. Ensure the logic
still raises ValueError for disallowed methods but never attempts iteration over
None.
---
Duplicate comments:
In `@nodes/src/nodes/tool_firecrawl/IInstance.py`:
- Line 103: The decorator description in
nodes/src/nodes/tool_firecrawl/IInstance.py uses double quotes; update the
string literal for the decorator's description parameter to use single quotes
(e.g., change "Map a website's structure and return all discovered URLs." to
'Map a website's structure and return all discovered URLs.') so it follows the
project's Python style for nodes/**/*.py; ensure only the decorator's
description argument is modified and run ruff/formatting checks afterward.
- Around line 45-52: The tool accepts a 'format' in the input schema but never
forwards it to Firecrawl, so html requests are ignored and invalid values can
silently fall back to markdown; update the code that currently calls
FirecrawlApp.scrape(url) to extract and validate the incoming format from the
tool input (the same 'format' declared under the tool_function input_schema) and
pass it into FirecrawlApp.scrape (or the SDK's equivalent parameter) so the
request explicitly asks for 'html' or 'markdown'; if the SDK uses a different
option name, map the 'format' value to that parameter, and return a clear error
(success=false) for unsupported values instead of silently defaulting.
In `@nodes/src/nodes/tool_http_request/IInstance.py`:
- Around line 200-213: _normalize_shortcuts currently ignores non-dict
basic_auth values, causing later _validate_guardrails to fail; change the
basic_auth handling to pop basic_auth and, if basic_auth is not None and
args.get('auth') is falsy, validate its type: if isinstance(basic_auth, dict)
set args['auth'] = {'type': 'basic', 'basic': basic_auth} else raise a
ValueError("basic_auth must be a dict") so invalid inputs are surfaced
consistently (similar to how bearer_token is coerced/validated) and to match
_validate_guardrails expectations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: ef450905-18d7-4851-ac27-b8611879f0ad
📒 Files selected for processing (9)
nodes/src/nodes/agent_langchain/langchain.pynodes/src/nodes/chart_chartjs/IInstance.pynodes/src/nodes/llm_base/IInstance.pynodes/src/nodes/memory_internal/IInstance.pynodes/src/nodes/tool_firecrawl/IInstance.pynodes/src/nodes/tool_http_request/IGlobal.pynodes/src/nodes/tool_http_request/IInstance.pynodes/src/nodes/tool_python/IGlobal.pypackages/ai/src/ai/common/database/db_instance_base.py
rocketride-org#599 Remove VectorDBDriver(ToolsBase) and move search/upsert/delete tool logic to @tool_function decorated methods on IInstance. Store config and backend connection directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ketride-org#599 Remove V0Driver(ToolsBase) and move generate_ui/refine_ui tool logic to @tool_function decorated methods on IInstance. Store apikey directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…InstanceBase (#599) * refactor(engine): replace ToolsBase driver classes with @tool_function decorators on IInstanceBase Every tool-providing node previously required two parallel classes: an IInstance (pipeline integration) and a ToolsBase driver (tool definitions). The driver implemented three abstract methods (_tool_query, _tool_validate, _tool_invoke) and the IInstance wired them together with boilerplate delegation in invoke(). This created a parallel system that was hard to understand and tedious to write — the driver often just called back into the instance for the actual work, and every node repeated the same delegation pattern. The root cause was that tool declaration was separate from the class that actually owned the state and connections needed to execute the tool. A MySQL node's IInstance had the database connection, the LLM access, and the lane handlers — but its tool definitions lived in a MySQLDriver class that had to reach back into the instance for everything. This commit collapses both layers into one by adding @invoke_function and @tool_function decorators directly to IInstanceBase in rocketlib/filters.py. Any IInstanceBase subclass can now declare tool entry points with a decorator — the method name becomes the tool ID, the decorator carries the schema and description, and the base class invoke() dispatches automatically. No separate driver class, no factory method, no delegation. Usage example — static tool: from rocketlib import IInstanceBase, tool_function class IInstance(IInstanceBase): IGlobal: IGlobal @tool_function( input_schema={ 'type': 'object', 'required': ['url', 'method'], 'properties': { 'url': {'type': 'string'}, 'method': {'type': 'string', 'enum': ['GET', 'POST']}, }, }, description='Make an HTTP request.', ) def http_request(self, args): if args['method'] not in self.IGlobal.enabled_methods: raise ValueError('Method not allowed') return execute_request(url=args['url'], method=args['method']) Usage example — dynamic description from config: class DatabaseInstanceBase(IInstanceBase): @tool_function( input_schema={...}, description=lambda self: ( f'Query the {self._db_display_name()} database. ' f'Just describe what data you need.' ), ) def get_data(self, args): ... Usage example — dynamic tools (MCP, tools discovered at runtime): class IInstance(IInstanceBase): def _tool_query_dynamic(self): return self.IGlobal.list_namespaced_tools() def _tool_invoke_dynamic(self, *, tool_name, input_obj): server, bare = tool_name.split('.', 1) return self.IGlobal.call_tool(server, bare, input_obj) The decorator system follows the existing control/invoke layering: control() <- engine entry point, rarely overridden └─ invoke() <- dispatches on param.op ├─ tool.* -> @tool_function methods (tool.query builds | descriptors, tool.invoke calls the method) └─ other ops -> @invoke_function methods (op name = method name) Key design decisions: - Decorators live in rocketlib/filters.py with zero upstream dependencies. The declaration plumbing (ToolDescriptor, @tool_function, @invoke_function, dispatch logic) is entirely self-contained in the engine base layer. - No tool name prefix. Tool IDs are bare method names (e.g. 'get_data', not 'mysql.get_data'). The agent host already namespaces by nodeId to prevent collisions between multiple nodes of the same type. - No separate validation step. tool.validate is removed from the dispatch. Validation is guard clauses at the top of the function body — simpler, more obvious, impossible to forget. - Decorator parameters accept static values or callables. Roughly half of all tools need runtime config in their descriptions (e.g. the user-entered database description, allowed import lists, display names). These use lambda self: ... which is resolved at tool.query time when self.IGlobal is available. This is a first-class pattern, not an escape hatch. - User-entered tool descriptions are auto-prepended. The "tool" field from the node config (e.g. "This is a database of world cities") is read via _tool_config_description() and prepended to every @tool_function's description automatically. Individual decorators only provide the fixed part. - Dynamic tools (MCP) use _tool_query_dynamic / _tool_invoke_dynamic overrides on IInstanceBase for tools discovered at runtime from external servers. Only MCP needs this. - Backward compatible with the agent-as-tool pattern. The four agent nodes still use _AgentAsToolProvider via ToolsBase — they are not tool nodes in the decorator sense, they use a different mechanism for exposing themselves as tools to other agents. Migrated nodes: - chart_chartjs: generate_chart (also eliminated the set_llm_invoker callback — IInstance calls self.instance.invoke('llm', ...) directly) - tool_python: execute - tool_http_request: http_request - tool_firecrawl: scrape_url, map_url - memory_internal: put, get, list, clear - db_mysql, db_postgres: get_data, get_schema, get_sql (via DatabaseInstanceBase with callable descriptors for display names) - db_neo4j: get_data, get_schema, get_cypher - mcp_client: dynamic tools via _tool_query_dynamic/_tool_invoke_dynamic Deleted (11 files, ~1600 lines): - All *_driver.py files (http, python, firecrawl, chartjs, memory, mcp, mysql, postgres, neo4j) - packages/ai/src/ai/common/database/db_driver_base.py - DatabaseDriverBase removed from database __init__.py exports Updated imports: - Agent framework drivers (langchain, crewai, deepagent) and AgentBase now use ToolDescriptor from rocketlib instead of ToolsBase.ToolDescriptor Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): fix tool schema key mismatch, harden node implementations The @tool_function decorator builds ToolDescriptors with camelCase keys (inputSchema, outputSchema) but three of the four agent drivers were reading snake_case (input_schema), silently getting None for every tool's parameter schema. The LLM never saw real parameter definitions — it always fell back to a generic "accept anything" schema. Tool schema fix (3 agent drivers) --- - agent_langchain: td.get('input_schema') → td.get('inputSchema') - agent_deepagent: td.get('input_schema') → td.get('inputSchema') - agent_crewai: already handled both with fallback; simplified to td.get('inputSchema') for consistency llm_base: replace manual dispatch with @invoke_function --- The manual match/case block in llm_base/IInstance.py duplicated what the base class invoke() auto-dispatcher already provides. Replaced with four @invoke_function decorated methods (ask, getContextLength, getOutputLength, getTokenCounter). Removed the now-unused IInvokeLLM import. Node hardening (from code review) --- - chart_chartjs: inverted ternary → idiomatic `description or "default"` - memory_internal: _store type MemoryStore → MemoryStore | None; put/get/ clear raise ValueError on non-dict args instead of silently coercing - tool_firecrawl: metadata.model_dump() exception now logged via warning; JSON parse catch narrowed to JSONDecodeError/TypeError with log - tool_http_request/IGlobal: mutable class-level set()/[] defaults → None; typing.Set/List → built-in set/list - tool_http_request/IInstance: str(body_json) fallback → json.dumps() so non-dict/list/str values produce valid JSON - tool_python/IGlobal: typing.Set → built-in set; removed unused imports - db_instance_base: int(raw_limit) wrapped in try/except, falls back to 250 on parse error instead of raising Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR review findings — input validation, lint, and hardening - langchain: fix ANN401/ARG002/UP037 on bind_tools signature - chart_chartjs: reject non-list/dict data, cap serialized payload at 20KB, validate and normalize LLM JSON output before wrapping in chartjs fence - llm_base: rename unused param → _param on invoke handlers (ARG002) - tool_firecrawl: simplify formats array → single format string, redact raw payload from warning log - tool_http_request: fail-fast validation on auth/body types and nested fields; fail-closed on malformed urlWhitelist in guardrails - tool_python: validate json.loads result is a list before iterating - memory_internal: enforce key type/presence in put/get/clear, add dict check to list handler - db_instance_base: add missing valid boolean to success/failure return dicts; fix stale _create_driver docstring → _db_display_name() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
rocketride-org#599 Remove VectorDBDriver(ToolsBase) and move search/upsert/delete tool logic to @tool_function decorated methods on IInstance. Store config and backend connection directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ix DAP cross-client seq collision AGENT BASE REFACTOR — AgentContext + call_llm/call_tool adapters ---------------------------------------------------------------- Replace the old host: AgentHost + _bind_framework_* callback API with a clean AgentContext dataclass and three host adapters on AgentBase: call_llm, call_llm_json, call_tool. The driver _run signature changes from (agent_input, host, ctx) to (*, context, question). AgentInput is deleted; its run metadata moves onto AgentContext and the Question travels alongside as a separate parameter. The two abstract _bind_framework_llm / _bind_framework_tools methods are removed — each driver now defines plain module-level builder functions (e.g. _build_langchain_llm(agent_base, context), _build_deepagent_tools(agent_base, context, descriptors)) that close over agent_base and context directly. _internal/agent_tool.py is removed entirely; agent-as-tool is now declared per IInstance as a @tool_function def run_agent(self, input_obj) using the shared AGENT_TOOL_INPUT_SCHEMA / AGENT_TOOL_OUTPUT_SCHEMA exported from ai.common.agent.types. AgentBase.run_agent now lazy-builds AgentHostServices once per IInstance and caches it on iInstance._agent_host. Tool discovery (one engine invoke per connected tool node) happens once at first question instead of on every question. A new REQUIRES_MEMORY class flag lets drivers declare a memory dependency that run_agent enforces at first question. sendSSE now takes context as an explicit parameter and reads the invoker from there instead of from self._invoker. The _invoker and _host instance attributes on AgentBase are gone. All engine envelope construction (IInvokeLLM.Ask(...)) lives inside call_llm / call_llm_json. Drivers never touch IInvokeLLM directly. call_llm accepts a polymorphic prompt that is either a pre-built Question (used by drivers like rocketride that build structured prompts) or framework-native messages that get flattened to a transcript. AgentHostServices.Tools exposes a prepared flat list: List[ToolDescriptor] built once at construction. Drivers read context.tools.list directly and the old discover_tools helper is gone. The class also drops the leaky class-level _tool_nodes / _tool_list attributes that would have been shared across instances and silently leaked descriptors between concurrent agent runs. Tools.invoke(tool_name, args) is renamed from (tool_name, input) to make it explicit that it takes a clean dict — framework-shape conversion is the driver wrapper's job, not the host's. Why: the old _bind_framework_* methods existed only to receive callbacks (call_llm, invoke_tool, log_tool_call) that the driver would then capture in its inner LangChain / CrewAI subclasses. Every driver wrote the same closure boilerplate around the same shims. Passing agent_base and context directly to module-level builder functions lets the inner classes close over them naturally — the entire indirection layer disappears, and the resulting drivers are dramatically smaller (deepagent loses ~280 lines). AgentInput was a half-honest wrapper: it carried a Question plus run metadata, but the question and the metadata have completely different lifecycles. Run metadata is per-call scaffolding (immutable, threadsafe, shared across reentrant call_llm chains); a question is the actual unit of work and changes meaning every time a framework loop synthesizes a new one from messages. Splitting them into AgentContext (frozen dataclass) + a separate question parameter is structurally honest and makes reentrancy safe. self._invoker was a latent concurrency bug. Two concurrent run_agent calls on the same IInstance would race to set self._invoker, and SSE events from one call could be routed to the other call's pipe. Reading the invoker from context instead means each call has its own immutable binding. Same reasoning for self._host. Lazy host construction per IInstance fixes a real performance pothole. Tool discovery does N engine invokes per connected tool node. Rebuilding the host on every question multiplied that cost by question rate — and worse, the discovered descriptors were thrown away after each question. Caching on iInstance._agent_host discovers once and reuses forever. Centralizing IInvokeLLM construction in call_llm means engine type changes (like the IInvokeLLM(op=ask,...) to IInvokeLLM.Ask(...) factory pattern) only need to land in one place. Drivers don't need co-ordinated updates. Replacing the bespoke agent-as-tool path with @tool_function def run_agent unifies the surface with the @tool_function decorator pattern from #599. The old handle_agent_tool_invoke / _AgentAsToolProvider branch was a parallel system that did the same thing the decorator does — it existed because @tool_function post-dated the original agent base. Now that the decorator exists, the parallel system is dead code. CREWAI SPLIT — three node types out of one package --------------------------------------------------- The single agent_crewai node becomes three logical nodes, each registered via its own services.*.json and living in its own sub-package: - crewai_agent — standalone single-agent node, also exposed as a run_agent tool. classType: [agent, tool]. - crewai_subagent — managed sub-agent. No questions lane. Can only be wired into a Manager via the crewai lane. classType: [crewai]. - crewai_manager — hierarchical multi-agent delegator. Fans out describe on the crewai lane to connected subagents, assembles a Crew, runs CrewAI hierarchical process. classType: [agent, tool]. Shared framework code lives at the package root: crewai_base.py (the CrewBase(AgentBase) shared base with _build_crew_llm / _build_crew_tools), crewai_runner.py, crewai_listener.py, plus the shared requirements.txt. The package no longer exports IInstance / IGlobal; the engine loads each sub-package via the path field in its services manifest. The crew control-plane op renames from crewai.describe to bare describe on lane crewai, and IInvokeCrew.Describe now extends IInvokeOp (with lane = crewai) instead of plain BaseModel. IInvokeCrew.DescribeResponse is no longer an IInvokeOp — it is a value object that travels inside a Describe response, not an op that gets dispatched. The trace renderer (render_invoke.tsx) is updated to display the new op name. Why: the original single agent_crewai node tried to be both a standalone agent and the orchestrator depending on which lanes were connected. There was no way to validate the combinations: nothing stopped someone from running a subagent standalone, or wiring a manager without subagents. The behavior was implicit in connection topology, which means errors only surfaced at runtime and only with confusing symptoms. Splitting the role into three explicit node types makes the constraints declarative in the services manifest. Subagents have no questions lane and literally cannot be invoked directly. Managers require at least one crewai lane connection. The engine normal lane validation now catches misuse before pipeline start. Cross-Manager nesting (one Crew calling into another Crew as a black box) still works — but now it is via the tool.run_agent path (the agent-as-tool surface), not by overloading the crewai lane. That keeps the crewai lane semantics clean: it is the manager/subagent fan-out channel, nothing else. The op rename matches the @invoke_function decorator dispatch convention landed in #599: bare op names route to def describe(self, ...) methods on the receiving IInstance. Keeping the old crewai.describe form would have forced a special case in the dispatcher. DAP CROSS-CLIENT SEQ COLLISION — two clients, one task ------------------------------------------------------- Task._send_data now constructs a fresh outbound DAP packet via _data_client.dap_request(command=..., arguments=..., token=...) instead of forwarding the inbound dict verbatim. DataCommands.handle_data wraps the subprocess response in a fresh build_response(request, body=...) keyed off the inbound request. New tests in both RocketRideClient_test.py and RocketRideClient.test.ts exercise the path: two independent clients sharing one task via useExisting, sending concurrently. Why: two independent client connections that share a task (via useExisting) each have their own DAP seq counter. They can independently issue overlapping seqs — both clients can reach seq=4 within milliseconds of each other. Eaas multiplexes both into one outbound _data_client to the subprocess. If we forwarded the inbound dict verbatim, the colliding seqs would clobber each other in _data_client._pending_requests: the second future overwrites the first, the first response gets dropped, and the originating client hangs forever waiting for a reply that already came back to the wrong slot. Building a fresh outbound packet via dap_request allocates a unique seq from _data_client._next_seq() so each outbound message has its own correlation slot. Rebuilding the response envelope via build_response ensures the inbound DAPConn sees its original request_seq so it can correlate the response back to the originating client. This bug is invisible with one client because a single client has one monotonic seq counter — it never collides with itself. The single-client concurrent test in the same suite does NOT exercise the path. Two independent clients fanning into one task are the necessary precondition, which is exactly what the new tests reproduce. MISTRAL SDK 1.x / 2.x COMPATIBILITY ------------------------------------ llm_mistral/IGlobal.py, llm_mistral/mistral.py, and llm_vision_mistral/mistral_vision.py try from mistralai.client import Mistral (2.x layout) and fall back to from mistralai import Mistral (1.x). The >=2.0.0 constraint is dropped from both requirements.txt. The mistralai SDK reorganized its package layout between 1.x and 2.x. Pinning to 2.x broke installs in environments still on 1.x. The shim accepts whichever is installed without forcing an upgrade. INCIDENTAL FIT-AND-FINISH -------------------------- - PageProjectProvider.ts adds a clipboard bridge: webview iframes can post {type:requestPaste} / {type:copyText,text} and the extension host proxies to vscode.env.clipboard.read/writeText. VSCode intercepts native paste at the Electron layer, so embedded iframes cannot read the OS clipboard themselves. - task_engine.py adds debug(output_message) on subprocess output events so traces capture the same payload that gets appended to _status_trace. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ix DAP cross-client seq collision AGENT BASE REFACTOR — AgentContext + call_llm/call_tool adapters ---------------------------------------------------------------- Replace the old host: AgentHost + _bind_framework_* callback API with a clean AgentContext dataclass and three host adapters on AgentBase: call_llm, call_llm_json, call_tool. The driver _run signature changes from (agent_input, host, ctx) to (*, context, question). AgentInput is deleted; its run metadata moves onto AgentContext and the Question travels alongside as a separate parameter. The two abstract _bind_framework_llm / _bind_framework_tools methods are removed — each driver now defines plain module-level builder functions (e.g. _build_langchain_llm(agent_base, context), _build_deepagent_tools(agent_base, context, descriptors)) that close over agent_base and context directly. _internal/agent_tool.py is removed entirely; agent-as-tool is now declared per IInstance as a @tool_function def run_agent(self, input_obj) using the shared AGENT_TOOL_INPUT_SCHEMA / AGENT_TOOL_OUTPUT_SCHEMA exported from ai.common.agent.types. AgentBase.run_agent now lazy-builds AgentHostServices once per IInstance and caches it on iInstance._agent_host. Tool discovery (one engine invoke per connected tool node) happens once at first question instead of on every question. A new REQUIRES_MEMORY class flag lets drivers declare a memory dependency that run_agent enforces at first question. sendSSE now takes context as an explicit parameter and reads the invoker from there instead of from self._invoker. The _invoker and _host instance attributes on AgentBase are gone. All engine envelope construction (IInvokeLLM.Ask(...)) lives inside call_llm / call_llm_json. Drivers never touch IInvokeLLM directly. call_llm accepts a polymorphic prompt that is either a pre-built Question (used by drivers like rocketride that build structured prompts) or framework-native messages that get flattened to a transcript. AgentHostServices.Tools exposes a prepared flat list: List[ToolDescriptor] built once at construction. Drivers read context.tools.list directly and the old discover_tools helper is gone. The class also drops the leaky class-level _tool_nodes / _tool_list attributes that would have been shared across instances and silently leaked descriptors between concurrent agent runs. Tools.invoke(tool_name, args) is renamed from (tool_name, input) to make it explicit that it takes a clean dict — framework-shape conversion is the driver wrapper's job, not the host's. Why: the old _bind_framework_* methods existed only to receive callbacks (call_llm, invoke_tool, log_tool_call) that the driver would then capture in its inner LangChain / CrewAI subclasses. Every driver wrote the same closure boilerplate around the same shims. Passing agent_base and context directly to module-level builder functions lets the inner classes close over them naturally — the entire indirection layer disappears, and the resulting drivers are dramatically smaller (deepagent loses ~280 lines). AgentInput was a half-honest wrapper: it carried a Question plus run metadata, but the question and the metadata have completely different lifecycles. Run metadata is per-call scaffolding (immutable, threadsafe, shared across reentrant call_llm chains); a question is the actual unit of work and changes meaning every time a framework loop synthesizes a new one from messages. Splitting them into AgentContext (frozen dataclass) + a separate question parameter is structurally honest and makes reentrancy safe. self._invoker was a latent concurrency bug. Two concurrent run_agent calls on the same IInstance would race to set self._invoker, and SSE events from one call could be routed to the other call's pipe. Reading the invoker from context instead means each call has its own immutable binding. Same reasoning for self._host. Lazy host construction per IInstance fixes a real performance pothole. Tool discovery does N engine invokes per connected tool node. Rebuilding the host on every question multiplied that cost by question rate — and worse, the discovered descriptors were thrown away after each question. Caching on iInstance._agent_host discovers once and reuses forever. Centralizing IInvokeLLM construction in call_llm means engine type changes (like the IInvokeLLM(op=ask,...) to IInvokeLLM.Ask(...) factory pattern) only need to land in one place. Drivers don't need co-ordinated updates. Replacing the bespoke agent-as-tool path with @tool_function def run_agent unifies the surface with the @tool_function decorator pattern from #599. The old handle_agent_tool_invoke / _AgentAsToolProvider branch was a parallel system that did the same thing the decorator does — it existed because @tool_function post-dated the original agent base. Now that the decorator exists, the parallel system is dead code. CREWAI SPLIT — three node types out of one package --------------------------------------------------- The single agent_crewai node becomes three logical nodes, each registered via its own services.*.json and living in its own sub-package: - crewai_agent — standalone single-agent node, also exposed as a run_agent tool. classType: [agent, tool]. - crewai_subagent — managed sub-agent. No questions lane. Can only be wired into a Manager via the crewai lane. classType: [crewai]. - crewai_manager — hierarchical multi-agent delegator. Fans out describe on the crewai lane to connected subagents, assembles a Crew, runs CrewAI hierarchical process. classType: [agent, tool]. Shared framework code lives at the package root: crewai_base.py (the CrewBase(AgentBase) shared base with _build_crew_llm / _build_crew_tools), crewai_runner.py, crewai_listener.py, plus the shared requirements.txt. The package no longer exports IInstance / IGlobal; the engine loads each sub-package via the path field in its services manifest. The crew control-plane op renames from crewai.describe to bare describe on lane crewai, and IInvokeCrew.Describe now extends IInvokeOp (with lane = crewai) instead of plain BaseModel. IInvokeCrew.DescribeResponse is no longer an IInvokeOp — it is a value object that travels inside a Describe response, not an op that gets dispatched. The trace renderer (render_invoke.tsx) is updated to display the new op name. Why: the original single agent_crewai node tried to be both a standalone agent and the orchestrator depending on which lanes were connected. There was no way to validate the combinations: nothing stopped someone from running a subagent standalone, or wiring a manager without subagents. The behavior was implicit in connection topology, which means errors only surfaced at runtime and only with confusing symptoms. Splitting the role into three explicit node types makes the constraints declarative in the services manifest. Subagents have no questions lane and literally cannot be invoked directly. Managers require at least one crewai lane connection. The engine normal lane validation now catches misuse before pipeline start. Cross-Manager nesting (one Crew calling into another Crew as a black box) still works — but now it is via the tool.run_agent path (the agent-as-tool surface), not by overloading the crewai lane. That keeps the crewai lane semantics clean: it is the manager/subagent fan-out channel, nothing else. The op rename matches the @invoke_function decorator dispatch convention landed in #599: bare op names route to def describe(self, ...) methods on the receiving IInstance. Keeping the old crewai.describe form would have forced a special case in the dispatcher. DAP CROSS-CLIENT SEQ COLLISION — two clients, one task ------------------------------------------------------- Task._send_data now constructs a fresh outbound DAP packet via _data_client.dap_request(command=..., arguments=..., token=...) instead of forwarding the inbound dict verbatim. DataCommands.handle_data wraps the subprocess response in a fresh build_response(request, body=...) keyed off the inbound request. New tests in both RocketRideClient_test.py and RocketRideClient.test.ts exercise the path: two independent clients sharing one task via useExisting, sending concurrently. Why: two independent client connections that share a task (via useExisting) each have their own DAP seq counter. They can independently issue overlapping seqs — both clients can reach seq=4 within milliseconds of each other. Eaas multiplexes both into one outbound _data_client to the subprocess. If we forwarded the inbound dict verbatim, the colliding seqs would clobber each other in _data_client._pending_requests: the second future overwrites the first, the first response gets dropped, and the originating client hangs forever waiting for a reply that already came back to the wrong slot. Building a fresh outbound packet via dap_request allocates a unique seq from _data_client._next_seq() so each outbound message has its own correlation slot. Rebuilding the response envelope via build_response ensures the inbound DAPConn sees its original request_seq so it can correlate the response back to the originating client. This bug is invisible with one client because a single client has one monotonic seq counter — it never collides with itself. The single-client concurrent test in the same suite does NOT exercise the path. Two independent clients fanning into one task are the necessary precondition, which is exactly what the new tests reproduce. MISTRAL SDK 1.x / 2.x COMPATIBILITY ------------------------------------ llm_mistral/IGlobal.py, llm_mistral/mistral.py, and llm_vision_mistral/mistral_vision.py try from mistralai.client import Mistral (2.x layout) and fall back to from mistralai import Mistral (1.x). The >=2.0.0 constraint is dropped from both requirements.txt. The mistralai SDK reorganized its package layout between 1.x and 2.x. Pinning to 2.x broke installs in environments still on 1.x. The shim accepts whichever is installed without forcing an upgrade. INCIDENTAL FIT-AND-FINISH -------------------------- - PageProjectProvider.ts adds a clipboard bridge: webview iframes can post {type:requestPaste} / {type:copyText,text} and the extension host proxies to vscode.env.clipboard.read/writeText. VSCode intercepts native paste at the Electron layer, so embedded iframes cannot read the OS clipboard themselves. - task_engine.py adds debug(output_message) on subprocess output events so traces capture the same payload that gets appended to _status_trace. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…overhaul (#670) * feat(shared-ui): persist canvas state, add isFlowReady, and centralize node loading Previously, viewport (zoom/pan), lock state, snap-to-grid, and editor mode were either not persisted at all or stored only in local preferences. On reload the canvas always reset to fitView at default zoom, losing the user's position. Additionally, ReactFlow timing was managed through scattered setTimeout/requestAnimationFrame workarounds with no unified signal for when nodes were measured and the canvas was ready for viewport operations. PipelineConfig schema (TypeScript + Python SDKs): - Added docRevision, isLocked, snapToGrid, snapGridSize, and editorMode to PipelineConfig so these fields travel with the .pipe file across all consumers. IProject now inherits them instead of declaring docRevision separately. isFlowReady state (FlowGraphContext): - Added an isFlowReady boolean state that tracks whether all nodes have been rendered and measured by ReactFlow. Transitions false→true when every node has measured.width, and true→false when unmeasured nodes appear (new node added, template instantiated, project loaded). - All effects that need measured nodes (viewport restoration, fitView, template post-processing) now depend on isFlowReady instead of using setTimeout(0) or requestAnimationFrame. loadCanvas centralization (FlowGraphContext): - Extracted a loadCanvas(nodes, edges) function that sets isLoadingRef, resets isFlowReady, and calls setNodes/setEdges. This is the single entry point for structural canvas changes. - loadData (project load) now delegates to loadCanvas for the node/edge work, then handles layout preference sync and viewport queueing. - addNode now uses loadCanvas instead of calling setNodes directly, so single-node additions get the same isFlowReady cycle and isLoadingRef guard as bulk loads. Viewport save/restore: - onToolchainUpdated now includes isLocked, snapToGrid, and snapGridSize from projectLayoutRef in the saved project, so layout prefs persist with the document. - onMoveEnd handler added to ReactFlow so viewport-only changes (zoom/pan without node edits) trigger a save via onToolchainUpdated. - On load, viewport is restored from project.viewport via a useEffect that fires when isFlowReady transitions to true. Falls back to fitView if no saved viewport exists. - Removed the fitView prop from ReactFlow — viewport is now always managed programmatically through the isFlowReady cycle. FlowPreferencesContext: - isLocked is now derived from projectLayout state instead of a separate useState, eliminating dual-state sync issues when loadData pushes layout prefs from the project document. useTemplateInstantiator simplification: - Replaced the two-phase measurement polling (pendingIds + needsFit + doneRef) with a single useEffect gated on isFlowReady. When isFlowReady becomes true and pendingIds exist, it updates internals, notifies the host, and calls fitView. - Template instantiation now uses loadCanvas instead of calling setNodes/setEdges directly, getting the same isLoadingRef guard and isFlowReady cycle. addNode positioning: - When no position is specified (accordion/create panel), addNode now finds a non-overlapping spot by starting at viewport center and shifting down until clear of existing nodes, matching the quick-add popup behavior. EmptyCanvasPrompt: - Only shown when nodes.length === 0 AND isFlowReady is true, preventing the brief flash of the "Select your starting point" dialog while a project's components are still loading into nodes. - Fixed React style warnings by replacing border shorthand with longhand properties (borderWidth/borderStyle/borderColor) in item and templateItem styles to avoid conflicts with conditional borderColor overrides. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): use spiral search for non-overlapping node placement Replace the downward-only linear search with a spiral pattern that searches outward from the viewport center, finding the nearest available slot in all directions. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): decompose monolithic flow module into modular ProjectView architecture Restructure the shared-ui package from a single monolithic `modules/flow/` canvas module into a composable, multi-view project architecture. The canvas editor is relocated, five new standalone view components are introduced, and a new ProjectView orchestration module ties them together behind a redesigned TabPanel. === CANVAS RELOCATION === Move the entire ReactFlow-based pipeline canvas editor from `modules/flow/` to `components/canvas/`. The internal directory structure is preserved verbatim (components/, context/, hooks/, templates/, util/, types.ts, theme.ts). The barrel export in `src/index.tsx` is updated to re-export `Canvas` and `IFlowProps` from the new path. No functional changes to the canvas itself. Files moved (92 files): modules/flow/** → components/canvas/** === NEW MODULE: ProjectView (modules/project/) === Add a top-level orchestration component that composes the canvas editor and all runtime views (Status, Tokens, Flow, Trace, Errors) into a unified project frame with a shared TabPanel. - ProjectView.tsx (229 lines): Wires up lazy-loaded tab content via React.lazy + Suspense, manages active tab state, and delegates host↔view communication through typed callback props. - types.ts (131 lines): Defines the complete message protocol for host↔view communication, split into per-component message pairs: • CanvasIncoming / CanvasOutgoing • StatusIncoming / StatusOutgoing • TraceIncoming / TraceOutgoing Composed into aggregate types: • ProjectViewIncoming — all messages the host can send • ProjectViewOutgoing — all messages the view can emit Also defines ProjectViewMode, IProjectViewProps, and IViewProps. - hooks/useTraceState.ts (274 lines): Incrementally processes an array of TraceEvent objects (begin/enter/leave/end ops) into a flat list of TraceRow objects for the trace viewer. Maintains document map, slot bindings, and pending call stacks via refs. Supports reset detection when the event array shrinks. Caps retained documents at 64. - hooks/useElapsedTimer.ts (85 lines): Returns a live-updating elapsed-seconds counter while a pipeline task is in the RUNNING state. Starts a 1-second interval on RUNNING, clears on completion/cancel/ unmount. === NEW VIEW COMPONENTS === All five new view components follow the established shared-ui conventions: plain React, inline CSSProperties style objects, --rr-* CSS custom property tokens, section divider comments, no MUI dependencies. 1. components/status/ (5 files, ~1,210 lines total) - Status.tsx: Completions chart and stats for a running pipeline. 1-second sampling interval, 600 data points (10 min history), automatic reset detection on pipeline restart. - StatusHeader.tsx: Header bar with pipeline state display and run/stop/restart action buttons. - StatusFooter.tsx: Footer with summary statistics row. - CompletionsChart.tsx: Canvas-based time-series chart rendering completions data with configurable time ranges. - types.ts: ChartStats, StatusDataPoint, TimeRange interfaces. 2. components/tokens/ (2 files, ~160 lines) - Tokens.tsx: Token consumption metrics display with breakdown by resource type (CPU Usage, CPU Memory, GPU Memory), progress bars, and total count. 3. components/flow/ (2 files, ~217 lines) - Flow.tsx: Pipeline flow visualization with list/graph view toggle. Renders pipeline stage progression. 4. components/trace/ (3 files, ~1,514 lines) - Trace.tsx (1,255 lines): Pipeline call-tree viewer. Builds a tree from TraceRow data, groups by document/object, renders expandable tree nodes with elapsed time, status indicators (in-flight, error, completed), and a detail panel showing entry/exit data. - JsonTree.tsx (259 lines): Recursive JSON viewer for the trace detail panel. Supports configurable default expansion depth, collapsible object/array nodes, and syntax-colored primitives. 5. components/errors/ (2 files, ~234 lines) - Errors.tsx: Structured error/warning message parser and display. Parses "ErrorType*`message`*filepath:linenumber" format with graceful fallback for unstructured messages. === TABPANEL REDESIGN === Rewrite the TabPanel component with a new visual design and mounting strategy. Visual changes: - Tab bar: sliding underline indicator → centered pill-style segmented control with rounded container and brand-colored active segment. - Removed resize/scroll event listeners (indicator tracking no longer needed). API changes: - Removed: `children` prop, `contentClassName` prop. - Added: `panels: Record<string, React.ReactNode>` prop — maps tab IDs to their content elements. Mount strategy change: - Old: Single `children` slot rendered unconditionally. - New: Panels render on first activation and stay mounted, with visibility toggled via `display: none`. This avoids re-mounting components like ReactFlow that require measured containers for correct initialization, while preventing premature mounting of panels that have never been visited. - Internal `activated` Set tracks which tabs have been shown at least once. Style migration: - Deleted tab-panel.css (85 lines of class-based styles). - All styles moved to inline CSSProperties objects in TabPanel.tsx, consistent with the shared-ui convention. === BARREL EXPORT UPDATES (src/index.tsx) === - Canvas/IFlowProps: re-export path updated from `./modules/flow` to `./components/canvas`. - Added exports: ProjectView, IProjectViewProps, IViewProps, ProjectViewMode, ProjectViewIncoming, ProjectViewOutgoing, TaskStatus, TraceEvent. === DEPENDENCY ADDITIONS === - lucide-react ^0.540.0: Icon library added to shared-ui (pnpm-lock.yaml updated). === DELETIONS === - modules/flow/ (92 files, ~14,058 lines): Entire legacy module removed. All canvas functionality is preserved in components/canvas/. The MUI-dependent top-level Flow.tsx wrapper in modules/flow/ is superseded by the new components/canvas/Canvas.tsx (which retains MUI for the ReactFlow integration) and by ProjectView (which is MUI-free). - components/tab-panel/tab-panel.css (85 lines): Superseded by inline styles in the rewritten TabPanel.tsx. Net change: 98 files changed, ~101 insertions, ~14,159 deletions (large deletion count reflects the modules/flow/ removal; equivalent code exists in the new components/canvas/ untracked directory). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): unify tab bars, add StatusHeader with Run/Stop, remove vscode.css from components Rework shared-ui tab bars, status header, and theme CSS loading: - TabPanel: simplify to mount-only-active-panel (unmounts on tab switch), remove activated-set tracking and display:none toggling, add pill-style badge support with active/inactive styling via color-mix tokens - StatusHeader: consolidate into a full two-column header bar with state indicator (dot + Running/Offline/etc), status subtitle, Run/Stop button with state-aware variants (run/stop/disabled), and elapsed timer — all self-contained with no layout responsibility on the parent - Status: integrate StatusHeader directly, accept onPipelineAction prop, remove need for parent to compose header layout - ServerMonitor: replace custom CSS tab bar and header with shared TabPanel component, remove sm-header/sm-tab-bar/sm-tab CSS classes - ProjectView: remove lazy loading and Suspense wrappers (panels now mount/unmount with tab switches), remove redundant layout styles and control button logic (now in StatusHeader), add empty state for Tokens panel - Theme: remove rocketride-vscode.css imports from ProjectView, ServerMonitor, and FlowCanvas (web app uses rocketride-default.css + JSON themes via applyTheme, VS Code extension loads vscode.css separately). Add fallback values to rocketride-vscode.css for --rr-bg-button, --rr-fg-button, --rr-font-family, --rr-font-family-widget - Barrel exports: add DashboardResponse, ActivityEvent and related dashboard types to shared-ui index.tsx Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: unify VSCode + shared-ui architecture with ref-based ProjectView - Merge PageEditorProvider + PageStatusProvider into PageProjectProvider - ProjectView owns all state via useImperativeHandle ref API - Stateless message bridges in both VSCode and rocket-ui - Multi-source status panes (one per source, sorted A-Z) - Canvas toolbar via context (CanvasToolbarContext) - Rename PageDashboard -> PageMonitor across VSCode extension - Inline styles with --rr-* tokens, delete all per-view CSS files - Add tabContent common style, readTheme utility - Add chart.js as shared-ui peer dependency - Remove applyDefaults from shared-ui components (theme owned by host) - Fix ActivityBar theme message type mismatch for iframes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): cache theme tokens, notify host on canvas content change Cache applied theme tokens in applyTheme.ts for reliable readTheme(), update ProjectView to sync project state on content changes, and notify host immediately when nodes are added via FlowGraphContext. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): overlay tab bar, floating canvas toolbar, workspace state persistence - TabPanel: absolute-positioned transparent overlay with centered pills, pointer-events passthrough so canvas is interactive underneath - FloatingToolbar: restored as draggable bar on canvas, switches between horizontal/vertical based on cursor proximity to parent edges - ProjectView: wire getPreference/setPreference to workspace state for toolbar position persistence, restore state on initialState arrival - Remove CanvasToolbarContext (dead code — toolbar no longer in tab bar) - Default node name from service catalog title on addNode - tabContent padding clears the overlay tab bar Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: migrate DAP to SDK, strongly type APIs, document/view/prefs state model SDK changes (TypeScript + Python): - Add ServiceDefinition, ServicesResponse, ValidationResult, ValidationError types - Strongly type getDashboard() → DashboardResponse, getServices() → ServicesResponse, getService() → ServiceDefinition, validate() → ValidationResult - Add name parameter to use(), add restart() and getTaskToken() methods - Add setEnv()/set_env() for runtime env variable updates - Add addMonitor/removeMonitor with reference counting and auto-resubscribe VS Code extension: - Replace all raw DAP commands with SDK methods (use, terminate, getTaskToken, getDashboard, getServices, restart, connect+ping for test connections) - Remove ConnectionManager.request() and monitor-manager.ts - Remove substituteEnvVariables — SDK handles env substitution via setEnv() - Pass env to client at creation, sync on onEnvVarsChanged - Split project:stateChange into project:viewStateChange + project:prefsChange - Send project:initialState + project:initialPrefs before canvas:update on ready shared-ui: - Split ProjectView state into viewState (mode, flowViewMode) and prefs (toolbar etc.) - Gate rendering on viewState and prefs being received (eliminates flash) - Export ViewState type from project module - FloatingToolbar: use visibility:hidden when parent has 0 dimensions - FloatingToolbar: skip ResizeObserver callbacks for hidden parents Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: project:load atomic message, viewport/layout state, dark mode fixes, dirty tracking State architecture: - Add project:load message — sends project, viewState, prefs, services, isConnected, and statuses in one atomic message (eliminates flash) - Add ViewState.viewport — viewport persisted per-view, not in pipeline - Add layouts (per-document defaults) — new views inherit from last layout - VS Code: use webview getState()/setState() for per-document state, rocketride.layouts in workspaceState for defaults - Add onViewportChange callback threaded through Canvas → FlowProvider → FlowProjectContext → FlowCanvas (replaces prefs-based viewport storage) Dirty tracking fixes: - Strip ui.measured from getComponentFromNode — computed field no longer dirties document on initial render - Remove viewport from onContentUpdated/addNode project output — viewport is view state, not document content - Remove onMoveEnd → onContentUpdated — panning/zooming no longer dirties - Fix template instantiation: call onContentChanged directly instead of onContentUpdated (was blocked by isLoadingRef race condition) Canvas improvements: - Rename onToolchainUpdated → onContentUpdated across all canvas files - Dark mode: detect via data-vscode-theme-kind body attribute in getMuiTheme - Dark mode: sync --icon-filter on body when theme changes - Dark mode: CSS-only --icon-filter rules for vscode-dark/high-contrast - Dark mode: theme-aware edge stroke colors via --xy-edge-stroke - Dark mode: icon filter on create-node panel sidebar icons - Fix gear icon fill override in NodeHeader (conditional spread) - Fix MoreMenu icon color (explicit --rr-text-secondary) - Edge delete button: use --rr-bg-paper background with --rr-text-secondary Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): remove debug component log from ProjectView Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): stop icon Square, PipelineActions on Status tab, remove metrics bg - RunButton: swap StopCircle for Square icon with transparent fill - StatusHeader: add extraActions slot, render PipelineActions (Chat now / Endpoint Info) - Status: remove background from Performance Metrics header - ProjectView: pass taskStatuses to Canvas, import PipelineActions for SourceStatusPane Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: wire onOpenLink end-to-end, serverHost, fix EndpointInfoModal tabs - ProjectView: add handleOpenLink callback, pass onOpenLink + serverHost to Canvas and SourceStatusPane PipelineActions - types: add project:openLink to ProjectViewOutgoing, serverHost to load msg - PageProjectProvider: handle project:openLink with full WebviewPanel bridge (theme, clipboard, drag-drop), send serverHost in project:load - EndpointInfoModal: replace overlay TabPanel with inline toggleButtons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): per-source Flow panes, parsed error messages in NodeStatus - Flow: extract SourceFlowContent for single-source rendering - ProjectView: render per-source SourceFlowPane (matches Tokens pattern), remove pickActiveStatus, clean up unused imports - NodeStatus: parse structured error format (Type*message*path), wrap instead of truncate, bold error type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: simplify project API — plain name string, strongly typed PipelineConfig Client SDK project methods now take a plain file name string instead of an options object, and use PipelineConfig types instead of Record<string, any>. TypeScript: - saveProject(name, pipeline: PipelineConfig) - getProject(name): PipelineConfig - deleteProject(name) Python: - save_project(name, pipeline: PipelineConfig) - get_project(name) -> PipelineConfig - delete_project(name) The name parameter is the file name on disk (e.g. "my-chat"), not the pipeline's UUID. The UUID (project_id) lives inside the pipeline JSON and is used for identity tracking, not file storage. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(shared-ui): remove duplicate theme JSON files Theme JSON files are served from rocket-ui's public/themes/ at runtime. The shared-ui copies were unused — fetchAndApplyTheme() fetches from the host's /themes/ endpoint, not from the shared-ui package. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): stop viewport/source leaking into pipeline, simplify RunButton Root cause: ProjectView injected viewState.viewport into the project object before passing to Canvas. This caused viewport and source to leak through onContentChanged, marking documents dirty on every pan/zoom or Play click. Fixes: - Pass viewport as separate initialViewport prop through Canvas → FlowContainer → FlowProvider → FlowProjectContext → FlowGraphContext - Remove viewport injection hack from ProjectView - RunButton: remove source injection from project (source passed separately via status:pipelineAction message) - handleRunPipeline: stop sending canvas:contentChanged on Play (pressing Play doesn't edit content) - RunButton: remove isPending state entirely (host may cancel via save dialog; pending spinner would get stuck) - RunButton: remove label spans, icon-only (Run/Stop/Stopping) - Run and Stop buttons now same hover width (3.5rem) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: per-source trace panes, flow event types, UI style consolidation Wire source field through flow events end-to-end (task engine → vscode provider → shared-ui) so trace and flow tabs can show per-source panes. Add TaskEventFlow / TASK_EVENT_FLOW types to TS and Python SDKs, remove unused EVENT_STATUS_UPDATE export. Move useTraceState processing into useEffect for React 18 Strict Mode compatibility. Consolidate card/header styles via commonStyles, simplify node header CSS to use surface-alt tokens, and add rocketride theme. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): collapsible trace call tree with lane-typed renderers Major refactor of the Trace component for the pipeline trace viewer. Call tree structure: - Each enter/leave pair renders as a single collapsible row (▸/▾) - Expanded: Input data box → children → Output data box (no ENTER/LEAVE rows) - Structural nesting via CSS margin-left + border-left - Batching of identical consecutive siblings with "N more..." progressive reveal - Inline detail panel under expanded nodes (not side panel) Lane-typed renderers (new renderers/ directory): - render_question: displays question text, history, instructions, examples, goals - render_answer: displays answer text with word count, token usage cards - render_document: displays content, metadata (source, objectId, chunk) - render_text: displays text with char/word count - render_video: displays action (Begin/Write/End), buffer size, mimeType - render_audio: displays format, duration, sample rate, channels (or stream action) - render_image: displays format, dimensions, file size (or stream action) - render_table: parses markdown tables and renders as HTML table - Each renderer has: TypeScript type guard (isX), summary function, render function - Dispatch by lane name, validated by type guard Data view modes: [Tree] [JSON] [Raw] toggle buttons - Tree: lane-typed renderer (falls back to JSON if no renderer matches) - JSON: JsonTree with defaultExpanded=2 - Raw: JSON.stringify compact string Other changes: - Removed side detail panel and resize handle - Removed "Trace" header and Clear button (handled by parent) - Lane colors for all lanes including image, table - Lane display names: tags→data, closing→flush - Explicit rgba backgrounds for lane badges (no color-mix) - useTraceState moved to useEffect (fixes React 18 Strict Mode) - Flow events forwarded with source field for per-source filtering - Removed unused helpers (findNodeById, collectVisibleNodes, etc.) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): restore titleBar colors for node headers, cardHeader consistency - Node headers: restore --rr-bg-titleBar-inactive/active with hover/selected transitions (was incorrectly changed to surface-alt which had insufficient contrast in dark themes) - cardHeader: use --rr-bg-titleBar-inactive instead of --rr-bg-surface-alt for consistency with canvas node headers across all panel headers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): trace viewer theme cleanup, UX polish, component name resolution - Replace all made-up CSS variables (--rr-font-mono, --rr-border-subtle, --rr-bg-surface, etc.) with declared --rr-* tokens from theme files - Add --rr-chart-* lane colours and --rr-annotation-bg-default to rocketride-vscode.css - Remove ~30 unused styles, dead selection state, and stale props - Resolve component IDs to display names via pipeline lookup map - Show recursive call counts on every level including object groups - Muted styling for empty pass-through nodes - Smart Data/JSON/Raw toggle: default to Data when a typed renderer exists, hide Data option otherwise - Move result status to output box with collapsed/expanded display - Square left corners on inline data boxes - Fix documents renderer to handle arrays, not just single objects - Remove redundant Node/Called by/Lane fields from input box - Add left/right padding to rendered data content Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui, rocketlib): invoke lane renderer + IInvoke computed type field Add @computed_field `type` to IInvoke so trace events carry the Python class name (IInvokeLLM, IInvokeTool, etc.) for dispatch. New invoke lane renderer handles LLM asks, tool discovery/invoke/validate with type-specific detail views. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(rocketlib, shared-ui): invoke type hierarchy refactor, IInvokeOp, IInvokeMemory Python (rocketlib): - Add IInvokeOp base class with computed type via __qualname__ (e.g. "IInvokeLLM.Ask") and lane field for routing - IInvokeLLM: pure namespace with nested Ask, GetContextLength, GetOutputLength, GetTokenCounter operation classes - IInvokeTool: migrate nested classes to IInvokeOp, add lane - IInvokeMemory: new type deriving from IInvokeTool with Put, Get, List, Clear operations backed by tool dispatch - IInvoke: remove computed_field type (envelope only) - instance.invoke(): takes single param, reads param.lane for routing, component_id replaces classType+nodeId - Driver control(): unpacks control.param instead of *control.args Callers (host.py, 12 node files): - IInvokeLLM(op='ask', question=q) → IInvokeLLM.Ask(question=q) - instance.invoke('llm', param, nodeId=x) → instance.invoke(param, component_id=x) - Memory class uses IInvokeMemory.Put/Get/List/Clear Frontend (shared-ui): - Invoke renderer dispatches on param.type split ("IInvokeLLM.Ask" → category + operation) via lookup tables - Add IInvokeMemory renderer - Remove redundant input/output/result from tool/memory Data views - Add RS.sectionContent for consistent label→content indentation - Apply sectionContent to question and invoke renderers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): split trace renderers into input/output, diff view, collapsible sections - Split InlineDataBox into InputDataBox and OutputDataBox - InputDataBox: call info, typed Data renderer per lane - OutputDataBox: DiffView by default, invoke-specific overrides - When entryData === exitData: single "Data" box, no Output - New utils.ts: traceDataEqual, diffObjects (10-entry cap, shallow per change), DiffView component, CollapsibleSection component - Split index.tsx: renderTraceInput/Output, summaryTraceInput/Output - Default output renderer: DiffView showing adds/changes/deletes - Invoke output: table-driven dispatch (LLM Ask shows Answer) - Invoke renderer improvements: - LLM Ask input: Goal, Question always visible; Instructions, Context, History collapsed by default via CollapsibleSection - LLM Ask output: renders Answer (string or JSON) from result - Memory input: shows Operation, Key, Value - Memory output: shows Status, Key, returned Value - Remove OP_LABELS map, show raw op values - Remove renderExtras, unknown types get JSON/Raw only - Instruction text blocks get yellow left border - Goal before Question in field order - Consistent RS.sectionContent indentation across all renderers (answer, text, document, invoke) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): shared question/answer formatters, result footer, robust trace stack - Extract format_question/format_answer so render_question, render_answer and render_invoke (LLM Ask) share one renderer - Add ResultFooter showing OK/Error/Skip/PreventDefault at the bottom of each expanded call - Shift/Ctrl-click a call header to expand or collapse the whole subtree - IInvokeCrew renderer + summarizer; Tool Query output lists discovered tools - useElapsedTimer now ticks during INITIALIZING as well as RUNNING - useTraceState recovers from missing enter/leave events by aligning the pending stack and marking orphaned frames as errors Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(agent): refactor AgentBase to AgentContext seam, split CrewAI, fix DAP cross-client seq collision AGENT BASE REFACTOR — AgentContext + call_llm/call_tool adapters ---------------------------------------------------------------- Replace the old host: AgentHost + _bind_framework_* callback API with a clean AgentContext dataclass and three host adapters on AgentBase: call_llm, call_llm_json, call_tool. The driver _run signature changes from (agent_input, host, ctx) to (*, context, question). AgentInput is deleted; its run metadata moves onto AgentContext and the Question travels alongside as a separate parameter. The two abstract _bind_framework_llm / _bind_framework_tools methods are removed — each driver now defines plain module-level builder functions (e.g. _build_langchain_llm(agent_base, context), _build_deepagent_tools(agent_base, context, descriptors)) that close over agent_base and context directly. _internal/agent_tool.py is removed entirely; agent-as-tool is now declared per IInstance as a @tool_function def run_agent(self, input_obj) using the shared AGENT_TOOL_INPUT_SCHEMA / AGENT_TOOL_OUTPUT_SCHEMA exported from ai.common.agent.types. AgentBase.run_agent now lazy-builds AgentHostServices once per IInstance and caches it on iInstance._agent_host. Tool discovery (one engine invoke per connected tool node) happens once at first question instead of on every question. A new REQUIRES_MEMORY class flag lets drivers declare a memory dependency that run_agent enforces at first question. sendSSE now takes context as an explicit parameter and reads the invoker from there instead of from self._invoker. The _invoker and _host instance attributes on AgentBase are gone. All engine envelope construction (IInvokeLLM.Ask(...)) lives inside call_llm / call_llm_json. Drivers never touch IInvokeLLM directly. call_llm accepts a polymorphic prompt that is either a pre-built Question (used by drivers like rocketride that build structured prompts) or framework-native messages that get flattened to a transcript. AgentHostServices.Tools exposes a prepared flat list: List[ToolDescriptor] built once at construction. Drivers read context.tools.list directly and the old discover_tools helper is gone. The class also drops the leaky class-level _tool_nodes / _tool_list attributes that would have been shared across instances and silently leaked descriptors between concurrent agent runs. Tools.invoke(tool_name, args) is renamed from (tool_name, input) to make it explicit that it takes a clean dict — framework-shape conversion is the driver wrapper's job, not the host's. Why: the old _bind_framework_* methods existed only to receive callbacks (call_llm, invoke_tool, log_tool_call) that the driver would then capture in its inner LangChain / CrewAI subclasses. Every driver wrote the same closure boilerplate around the same shims. Passing agent_base and context directly to module-level builder functions lets the inner classes close over them naturally — the entire indirection layer disappears, and the resulting drivers are dramatically smaller (deepagent loses ~280 lines). AgentInput was a half-honest wrapper: it carried a Question plus run metadata, but the question and the metadata have completely different lifecycles. Run metadata is per-call scaffolding (immutable, threadsafe, shared across reentrant call_llm chains); a question is the actual unit of work and changes meaning every time a framework loop synthesizes a new one from messages. Splitting them into AgentContext (frozen dataclass) + a separate question parameter is structurally honest and makes reentrancy safe. self._invoker was a latent concurrency bug. Two concurrent run_agent calls on the same IInstance would race to set self._invoker, and SSE events from one call could be routed to the other call's pipe. Reading the invoker from context instead means each call has its own immutable binding. Same reasoning for self._host. Lazy host construction per IInstance fixes a real performance pothole. Tool discovery does N engine invokes per connected tool node. Rebuilding the host on every question multiplied that cost by question rate — and worse, the discovered descriptors were thrown away after each question. Caching on iInstance._agent_host discovers once and reuses forever. Centralizing IInvokeLLM construction in call_llm means engine type changes (like the IInvokeLLM(op=ask,...) to IInvokeLLM.Ask(...) factory pattern) only need to land in one place. Drivers don't need co-ordinated updates. Replacing the bespoke agent-as-tool path with @tool_function def run_agent unifies the surface with the @tool_function decorator pattern from #599. The old handle_agent_tool_invoke / _AgentAsToolProvider branch was a parallel system that did the same thing the decorator does — it existed because @tool_function post-dated the original agent base. Now that the decorator exists, the parallel system is dead code. CREWAI SPLIT — three node types out of one package --------------------------------------------------- The single agent_crewai node becomes three logical nodes, each registered via its own services.*.json and living in its own sub-package: - crewai_agent — standalone single-agent node, also exposed as a run_agent tool. classType: [agent, tool]. - crewai_subagent — managed sub-agent. No questions lane. Can only be wired into a Manager via the crewai lane. classType: [crewai]. - crewai_manager — hierarchical multi-agent delegator. Fans out describe on the crewai lane to connected subagents, assembles a Crew, runs CrewAI hierarchical process. classType: [agent, tool]. Shared framework code lives at the package root: crewai_base.py (the CrewBase(AgentBase) shared base with _build_crew_llm / _build_crew_tools), crewai_runner.py, crewai_listener.py, plus the shared requirements.txt. The package no longer exports IInstance / IGlobal; the engine loads each sub-package via the path field in its services manifest. The crew control-plane op renames from crewai.describe to bare describe on lane crewai, and IInvokeCrew.Describe now extends IInvokeOp (with lane = crewai) instead of plain BaseModel. IInvokeCrew.DescribeResponse is no longer an IInvokeOp — it is a value object that travels inside a Describe response, not an op that gets dispatched. The trace renderer (render_invoke.tsx) is updated to display the new op name. Why: the original single agent_crewai node tried to be both a standalone agent and the orchestrator depending on which lanes were connected. There was no way to validate the combinations: nothing stopped someone from running a subagent standalone, or wiring a manager without subagents. The behavior was implicit in connection topology, which means errors only surfaced at runtime and only with confusing symptoms. Splitting the role into three explicit node types makes the constraints declarative in the services manifest. Subagents have no questions lane and literally cannot be invoked directly. Managers require at least one crewai lane connection. The engine normal lane validation now catches misuse before pipeline start. Cross-Manager nesting (one Crew calling into another Crew as a black box) still works — but now it is via the tool.run_agent path (the agent-as-tool surface), not by overloading the crewai lane. That keeps the crewai lane semantics clean: it is the manager/subagent fan-out channel, nothing else. The op rename matches the @invoke_function decorator dispatch convention landed in #599: bare op names route to def describe(self, ...) methods on the receiving IInstance. Keeping the old crewai.describe form would have forced a special case in the dispatcher. DAP CROSS-CLIENT SEQ COLLISION — two clients, one task ------------------------------------------------------- Task._send_data now constructs a fresh outbound DAP packet via _data_client.dap_request(command=..., arguments=..., token=...) instead of forwarding the inbound dict verbatim. DataCommands.handle_data wraps the subprocess response in a fresh build_response(request, body=...) keyed off the inbound request. New tests in both RocketRideClient_test.py and RocketRideClient.test.ts exercise the path: two independent clients sharing one task via useExisting, sending concurrently. Why: two independent client connections that share a task (via useExisting) each have their own DAP seq counter. They can independently issue overlapping seqs — both clients can reach seq=4 within milliseconds of each other. Eaas multiplexes both into one outbound _data_client to the subprocess. If we forwarded the inbound dict verbatim, the colliding seqs would clobber each other in _data_client._pending_requests: the second future overwrites the first, the first response gets dropped, and the originating client hangs forever waiting for a reply that already came back to the wrong slot. Building a fresh outbound packet via dap_request allocates a unique seq from _data_client._next_seq() so each outbound message has its own correlation slot. Rebuilding the response envelope via build_response ensures the inbound DAPConn sees its original request_seq so it can correlate the response back to the originating client. This bug is invisible with one client because a single client has one monotonic seq counter — it never collides with itself. The single-client concurrent test in the same suite does NOT exercise the path. Two independent clients fanning into one task are the necessary precondition, which is exactly what the new tests reproduce. MISTRAL SDK 1.x / 2.x COMPATIBILITY ------------------------------------ llm_mistral/IGlobal.py, llm_mistral/mistral.py, and llm_vision_mistral/mistral_vision.py try from mistralai.client import Mistral (2.x layout) and fall back to from mistralai import Mistral (1.x). The >=2.0.0 constraint is dropped from both requirements.txt. The mistralai SDK reorganized its package layout between 1.x and 2.x. Pinning to 2.x broke installs in environments still on 1.x. The shim accepts whichever is installed without forcing an upgrade. INCIDENTAL FIT-AND-FINISH -------------------------- - PageProjectProvider.ts adds a clipboard bridge: webview iframes can post {type:requestPaste} / {type:copyText,text} and the extension host proxies to vscode.env.clipboard.read/writeText. VSCode intercepts native paste at the Electron layer, so embedded iframes cannot read the OS clipboard themselves. - task_engine.py adds debug(output_message) on subprocess output events so traces capture the same payload that gets appended to _status_trace. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(vscode, shared-ui): persistent client, virtualized managers, disconnect overlay Refactor ConnectionManager to use a single persistent RocketRideClient (persist: true) that survives across connect/disconnect cycles. The SDK's _resubscribeAllMonitors() now correctly replays monitor subscriptions on every reconnect — fixing the bug where Server Monitor showed 0 MONITORS after a disconnect/reconnect. Backend lifecycle virtualized behind BaseManager with two concrete implementations: - LocalManager: composes EngineManager, connect with retries for engine startup race - RemoteManager: credential validation + direct connect Removed CloudManager (no-op stub), all retry/backoff logic from ConnectionManager (SDK handles it), isMonitoring flag from PageProjectProvider (SDK tracks via _monitorKeys). Disconnect overlay added to ProjectView and ServerMonitor — semi-opaque with blur, showing [ Disconnected ] over the existing content. On reconnect, statusMap/traceEvents/cachedStatuses are cleared for a fresh start. Status chart pauses while disconnected and resets on reconnect. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui, vscode, server, clients): pipeline result display, toolbar orientation context, icon standardization, connect dedup, engine EventEmitter Pipeline result end-to-end: - pipe.instance.cpp: gate BEGIN/END debug events on PIPELINE_TRACE_LEVEL::METADATA and serialize the pipe response into the END event at SUMMARY level — previously always emitted "{}" unconditionally, so the final result never reached the UI - client-ts/python: add result/pipelineResult field to TaskEventFlow for op === 'end' - useTraceState: on op === 'end' inject a synthetic __result__ sentinel TraceRow so Trace.tsx can render it separately from the call tree - Trace.tsx: extract __result__ rows in buildObjectGroups, add collapsible ResultRow component (green header) rendered after the call tree via renderFinalSections - render_final.tsx (new): dispatches each result field through the existing per-type renderers (renderAnswer, renderDocument, etc.) via result_types map; falls back to JsonTree for unknown types - format_answer.tsx: render structured JSON answers via JsonTree instead of a plain text block Toolbar orientation context: - FloatingToolbar.tsx: expose ToolbarOrientationContext so toolbar button children can read horizontal/vertical orientation via useToolbarOrientation() without prop drilling; fix null guard on getRenderedPosition() before writing dragStart - toolbar/index.tsx: re-export useToolbarOrientation from barrel Icon standardization: - FitIcon, LockIcon, NoteIcon, TidyIcon, UnlockIcon, ZoomInIcon, ZoomOutIcon: replace verbose per-element SVG markup with compact single-path 24x24 BoxIcons-style paths; standardizes icon visual style and halves markup weight - FlowCanvas.tsx: replace lucide Undo2/Redo2/Move/BoxSelect/PlusSquare imports with inline BxIcon helpers using BoxIcons paths, consistent with the icon overhaul VSCode reliability fixes: - connection.ts: add connectPromise dedup guard — concurrent connect() calls (e.g. racing event handlers at startup) now share one in-flight promise instead of each spawning an independent _connect(), preventing double-initialization - engine-manager.ts: switch from BaseManager to Node.js EventEmitter — was already calling this.emit('terminated') but BaseManager didn't extend EventEmitter so events were silently dropped; capture child in a local var so exit/error handlers guard this.child === child before mutating state, preventing a race where a new start() replaces this.child before the old process's exit handler fires - PageProjectProvider.ts: re-key editorStates from document.uri to WebviewPanel — URI was wrong because the same document can open in multiple panels; fan status updates out to all panels for a project; filter apaevt_flow trace events by project_id so unrelated projects don't receive each other's traces; extract pipelineResult from op === 'end' trace body into its own field Client transport fix (ts + python): - Clear _transport on disconnect so the next connect() with a new URI always creates a fresh transport — reconnecting to a different URI was reusing the stale transport with the old URI baked in Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * UI/UX fixes for canvas nodes * fix rotate on stopping button, fix coloring on stop button (#667) * fix(vscode): pipeline submenu now opens canvas editor instead of JSON (#669) The openFile and createNewPipelineFile commands were passing 'rocketride.PageEditor' as the viewType to vscode.openWith, which is not registered. VSCode fell back to the default JSON text editor. Fixed both call sites to use the registered 'rocketride.PageProject' viewType. Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat(agent_deepagent): port hierarchical subagents to AgentBase/AgentContext (#668) Splits agent_deepagent into two node types under one parent folder, mirroring the agent_crewai layout: - agent_deepagent (deepagent_agent/) flexible: standalone or orchestrator - agent_deepagent_subagent (deepagent_subagent/) invoke-only, classType ["deepagent"] Driver changes: - DeepAgentDriver._collect_subagents fans out `describe` via getControllerNodeIds('deepagent') + per-node invoke(component_id=...), builds one AgentContext + LLM + tools per subagent, passes SubAgent records to create_deep_agent(subagents=...) - DeepAgentSubagentDriver adds describe() and a _run that raises as defense-in-depth (subagent has no questions lane) - _read_connconfig_values reads connConfig directly so form values the UI writes nested under the default-profile key (e.g. {"default": {...}}) are resolved correctly; Config.getNodeConfig left untouched - Helpers: _tool_args_schema (real JSON Schema for tool args_schema), _extract_first_json_object (tolerant balanced-brace parser), _compose_system_prompt (shared manager/subagent prompt composition) Rocketlib: - IInvokeDeepagent (Describe + DescribeResponse) alongside IInvokeCrew - Re-exported from rocketlib/__init__.py UX: - Advanced Mode boolean checkbox on both nodes — Normal shows Instructions only; Advanced swaps in Agent Description + System Prompt (main) or System Prompt (subagent, with Description always visible) - Subagent has no lanes/input sections, cannot be wired as a top-level pipeline agent or as a general tool Docs: - Per-subfolder README following agent_crewai convention - Deepagents library link corrected to github.com/langchain-ai/deepagents Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(agent): strip ReAct trace from CrewAI Manager result, chain task context (#666) * fix(agent): strip ReAct trace from CrewAI Manager result, chain task context Three fixes for hierarchical CrewAI result quality: 1. Add _strip_react_preamble() — in hierarchical mode result.raw and tasks_output[-1].raw often contain the full manager delegation trace (Thought/Action/Observation chain) rather than just the final answer. Strips to the last "Final Answer:" marker, or the last JSON block if the text looks like a ReAct trace, or returns '' for inline traces so garbage doesn't leak to the user. 2. Add context=list(sub_tasks) to each Task — without this, downstream sub-agents (word analyst, chart renderer) had no access to prior task outputs (e.g. the fetched Wikipedia text). CrewAI requires explicit context wiring for inter-task data flow. 3. Update result extraction to iterate tasks_output in reverse and take the first clean result, falling back to result.raw with the same stripping. Avoids returning the manager's full delegation trace. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * harden ReAct stripping, remove fragile context chaining * address CR comment * update doc string --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: ryan-t-christensen <ryan.christensen@rocketride.ai> Co-authored-by: dylan-savage <130109357+dylan-savage@users.noreply.github.com>
rocketride-org#599 Remove VectorDBDriver(ToolsBase) and move search/upsert/delete tool logic to @tool_function decorated methods on IInstance. Store config and backend connection directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…933) Closes the 9 mechanically-fixable Scorecard `PinnedDependenciesID` alerts on this repo. Mutable tag references (`@v4`, `:tag`) become immutable hash references; Dependabot will continue to bump the SHAs as new versions ship. GitHub Actions (7 alerts): sync-models.yml actions/checkout v4 → 34e1148... #599 actions/setup-python v5 → a26af69... #600 actions/cache v4 → 0057852... #601 peter-evans/create-pull-req. v7 → 22a9089... #602 discord-discussions.yml actions/checkout v4 → 34e1148... #644 discord-issues.yml actions/checkout v4 → 34e1148... #645 discord-pr.yml actions/checkout v4 → 34e1148... #646 Docker base images (2 alerts): docker/Dockerfile.engine ubuntu:jammy-20240808 → @sha256:adbb90115a21969d2fe6fa7f9af4253e16d45f8d4c1e930182610c4731962658 #561 docker/Dockerfile.mcp python:3.12-slim → @sha256:9d3abd9fc11d06998ccdbdd93b4dd49b5ad7d67fcbbc11c016eb0eb2c2194891 #471 Both digests are the OCI image index (multi-platform manifest list), so platform resolution still happens at build time. `jammy-20240808` is already a date-pinned snapshot tag; `3.12-slim` is a floating upstream tag and was pinned at the digest current as of 2026-05-20. The remaining 6 `PinnedDependenciesID` alerts (#465, #466, #467, #468, #472, #603) flag pip/npm install commands with already-exact version pins (`twine==6.1.0`, `@vscode/vsce@3.7.1`, `ovsx@0.10.9`, etc.). Scorecard wants `pip install --require-hashes` or lockfile-driven installs for these; the ergonomics of doing that for one-shot workflow installs (and for the `./client-python` local-path install in Dockerfile.mcp, which can't be hash-pinned at all) outweigh the incremental supply-chain hardening over an already-exact version constraint. Those alerts are being dismissed separately with "won't fix" + per-alert justification.
* fix(security): prevent arbitrary module injection via /use endpoint (RCE) (#342)
* docs: add project rules for claude code
* fix(security): add module whitelist to prevent arbitrary code injection via /use endpoint
The /use endpoint accepts a module name from the HTTP query string and
passes it directly to importlib.import_module() with only lowercase/strip
normalization. This allows an attacker to load arbitrary Python modules
by sending crafted requests, potentially achieving remote code execution.
Add an ALLOWED_MODULES frozenset whitelist that restricts dynamic imports
to the 10 known service modules (chat, clients, data, dropper, pipe,
profiler, remote, services, task, task_http). Requests for any other
module name now raise ValueError, returning a 400 response.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add language identifier to markdown code fence
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(security): require authentication for profiler endpoints
All 5 profiler endpoints (/profile, /profile/start, /profile/stop,
/profile/status, /profile/report) were registered with public=True,
bypassing the AuthMiddleware entirely. This allows unauthenticated
users to start/stop profiling and read performance reports that expose
internal function names, call counts, and timing data.
Remove public=True from all profiler route registrations so they
require authentication like other protected endpoints.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: correct HTTP method in profiler docs (PUT → POST)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove claude.md from version control
This file is project-specific AI tooling configuration and should not
be tracked in git. Added to .gitignore instead.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(security): add tests for ALLOWED_MODULES allowlist validation
Verify that:
- ALLOWED_MODULES is an immutable frozenset with the expected 10 entries
- use() rejects non-allowlisted modules and path traversal attempts
- use() accepts valid modules and calls initModule correctly
- use() normalizes module names (lower + strip)
- use() skips already-loaded modules without re-importing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(security): address CodeRabbit review feedback on test_server.py
- Fix S104: change stub host from 0.0.0.0 to 127.0.0.1
- Add return type annotation to _make_server() -> WebServer
- Track injected sys.modules mocks and clean up in teardown_module()
- Assert cached module's initModule is not re-called in reload test
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: minor changes
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: stepmik <stepmikhaylov@yandex.ru>
* fix(security): prevent filter expression injection in Milvus vector store (#355)
* fix(security): prevent filter expression injection in Milvus vector store
Add _escape_milvus_str() helper to sanitize user-controlled values
before interpolation into Milvus filter expressions. Escapes single
quotes and backslashes to prevent filter injection attacks across all
query construction points in the Milvus store implementation.
* fix: address review feedback on Milvus filter injection PR
- Remove unnecessary tuple wrappers on append calls
- Fix isTable filter using wrong field (docFilter.nodeId -> docFilter.isTable)
- Use unquoted boolean for isTable filter (matches isDeleted pattern)
- Add type annotation and docstring to _escape_milvus_str
* fix: move test to nodes/test/ per project conventions
* fix(security): use secure temporary file creation in task engine (#356)
* fix(security): use secure temporary file creation in task engine
Replace insecure predictable temp file path with tempfile.mkstemp()
to prevent information disclosure and symlink attacks.
_write_task_file previously wrote pipeline config (which may contain
API keys and resolved env vars) to /tmp/<task-id>.json with default
0644 permissions. This was vulnerable to:
- World-readable files exposing sensitive pipeline configuration
- Symlink attacks due to predictable path based on task ID
- TOCTOU races from lack of O_EXCL exclusive creation
mkstemp() creates the file atomically with O_EXCL, uses a random
suffix making the path unpredictable, and defaults to 0600 permissions
(owner read/write only).
Uses await asyncio.to_thread(os.write, ...) for async compatibility.
Tests use asyncio.run() instead of deprecated get_event_loop().
* fix: address CodeRabbit findings on temp file PR
- Use os.fdopen + f.write instead of os.write to prevent partial writes
- Remove unused tempfile import in tests
- Add @skipIf(os.name == 'nt') on POSIX-specific tests
* chore: minor changes
---------
Co-authored-by: stepmik <stepmikhaylov@yandex.ru>
* fix(security): require authentication for profiler endpoints and escape HTML output (#362)
* fix(security): require authentication for profiler endpoints and escape HTML output
Remove public=True from all 5 profiler routes so they require authentication
via AuthMiddleware, and HTML-escape the profile report output to prevent XSS.
* fix: improve profiler XSS tests to verify actual endpoint output
* fix: revert conftest.py changes, scope mocks to test file
Remove depends and rocketride mocks from conftest.py (they break
other tests per asclearuc). Move stubs into the profiler test file
where they're needed, scoped locally.
* fix(ci): pin all actions to immutable commit hash (#483)
* chore(ci): remove PR title validation check (#502)
Co-authored-by: Dmitrii Karataev <dmitriikarataev@Dmitriis-MacBook-Pro.local>
* Fix: SDK connect error callback type (#576)
* fix(client-ts): correct ConnectErrorCallback type signature
The callback type expected (message: string) => Promise<void> but
the implementation passes Error objects and callers may return void
instead of Promise<void>. Updated to accept Error | string and
return void | Promise<void>.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(client-ts): use ConnectionException in ConnectErrorCallback type
Address maintainer feedback:
- Replace Error | string with ConnectionException from exceptions module
- Pass ConnectionException object directly to callback instead of extracting message string
- Keep void | Promise<void> return type as approved
- Fix invocation site in client.ts to construct ConnectionException when needed
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(apps): migrate onConnectError handlers to accept ConnectionException
Update three call sites to match the new ConnectErrorCallback type
signature that accepts ConnectionException instead of a plain string.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(client-ts): revert formatting changes
---------
Co-authored-by: NIHAL NIHALANI <nihal.nihalani@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: stepmik <stepmikhaylov@yandex.ru>
* fix(llm): clear correct _chat reference in endGlobal across all LLM nodes (#531)
All LLM node IGlobal classes assigned the Chat instance to `self._chat`
in `beginGlobal`, but `endGlobal` cleared `self.chat` (no underscore) —
a different attribute that was never set. This meant `endGlobal` was a
no-op: the Chat object was never explicitly released when a pipeline
stopped.
Fixed in 12 nodes: llm_anthropic, llm_bedrock, llm_deepseek, llm_gemini,
llm_ibm_watson, llm_mistral, llm_ollama, llm_openai, llm_perplexity,
llm_qwen, llm_vertex, llm_xai.
llm_vision_ollama and llm_vision_mistral were already correct.
* feat(llm): add GMI Cloud LLM connector (#540)
Adds a new LLM node for GMI Cloud (api.gmi-serving.com), an OpenAI-compatible
inference platform hosting 100+ models including DeepSeek, GPT, Claude, Gemini,
Llama 4, and Qwen3 on owned H100/H200 GPU infrastructure.
## Profiles
Two model tiers are supported:
Shared (always-on) — API key only required:
DeepSeek V3.2, V3, R1, R1 Distill 32B & 1.5B, Prover V2
GPT-5.2, 5.1, 5, 4o
Claude Opus 4.5, Sonnet 4.5
Gemini 3 Pro, Gemini 3 Flash
Deploy-on-demand — endpoint URL + API key required (deploy first at
console.gmicloud.ai, then paste the provided endpoint URL):
Llama 4 Scout, Llama 4 Maverick
Qwen3 235B, 32B, 30B, Coder 480B
A custom profile allows specifying any model name and endpoint URL manually.
* fix(security): use pathlib.is_relative_to for path traversal checks (#580)
Replace fragile str().startswith() path traversal checks with
Path.is_relative_to() in chat and dropper modules. The string prefix
comparison could be bypassed with crafted paths like /app/static/chat-evil/.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(security): switch SQL safety check from blacklist to whitelist approach (#577)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(security): expand sensitive field redaction patterns in VS Code logger (#578)
The redactSensitiveFields function only checked for auth-key, token-key,
and apikey patterns. This missed commonly used sensitive fields like
password, secret, authorization, bearer, credential, access_token,
refresh_token, and private_key, which could be logged unredacted.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add Product Hunt badge to all READMEs (#590)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* chore(community): add initial Code of Conduct (#591)
Establish baseline community guidelines for inclusive collaboration.
Intentionally kept lightweight to be expanded over time.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* docs: fix broken image links in README — use absolute URLs (#506)
* fix(vscode): remove Product Hunt SVG badge from VS Code README — marketplace rejects SVGs
* fix(vscode): add Product Hunt badge as PNG — marketplace rejects SVGs
* fix(security): restrict environment variable expansion in pipeline configs (#359)
* fix(security): restrict environment variable expansion in pipeline configs
Add an allowlist of permitted env var prefixes (ROCKETRIDE_, PIPELINE_,
NODE_, ROCKET_) to _resolve_pipeline(). All other ${VAR} references are
replaced with <REDACTED> to prevent exfiltration of sensitive environment
variables (AWS keys, DB URLs, tokens) via pipeline configuration.
* chore(ai): allow ROCKETRIDE_ prefixed variables
* chore(ai): check json injection
---------
Co-authored-by: stepmik <stepmikhaylov@yandex.ru>
* fix(client-ts): preserve user-specified port in normalizeUri (#377)
The URL API silently strips ports that are default-for-scheme (e.g. :443
on https), so url.port is empty for both "no port given" and
"scheme-default port given". This caused normalizeUri to always overwrite
with the default 5565 port, breaking connections through ngrok/Cloudflare
tunnels and custom reverse proxies.
Check the raw input string for an explicit port pattern before deciding
whether to apply the default port.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(connection): handle missing hostname in URI parsing (#530)
* Update connection.py
* cr
* Update dap_base.py (#532)
* Update execution.py (#537)
* feat(nodes): config - add deprecation pathway for deprecated profiles (#504)
* deprecation pathway
* coderabbit suggestions
* add tests
* cr
* fix build
* fix build
* Update conftest.py
* Update conftest.py
* Update conftest.py
* Update conftest.py
* simplify
* simplify
* fix(mixins): error handling for missing pipeline configuration files (#544)
* fix(nodes): openai - add latest openai models (#503)
* add latest openai model profiles
* coderabbit fixes
* fix typo (we didn't introduce)
* don't change default
* Update services.json
* Update services.json
* fix(nodes): remove deprecated gemini models (#500)
* remove gemini 3 pro (deprecated), gemini 2
* code rabbit response
* coderabbit
* Update services.json
* Update services.json
* feat: #429 Add Exa search node and working sample pipeline [FRONTIER TOWER HACKATHON] (#386)
* Add Exa search node and stable pipeline
* Harden Exa search node runtime handling
* Fix Exa fallback question parsing
* Fix Exa mock credential test wiring
* Assert Exa mock request contract
* Tighten Exa API exception types
* Document Exa node lifecycle hooks
* Handle unsafe Exa result URLs per item
* Clean up Exa backend from endpoint bag
* Unpin Exa node requests dependency
* Add comments to Exa service definition
* Add Exa search docstrings
* Parse Exa boolean config defensively
* Guard Exa error payload parsing
* revert: remove Exa node test changes
* revert: restore base test framework behavior
* chore: drop test framework whitespace diff
---------
Co-authored-by: Kaushik Sivakumar <kaushik.siva88@gmail.com>
* fix(vscode): register canvas-played pipelines in sidebar menu (#571)
* feat(vscode): improve stop button feedback in Pipeline Observability screen
Handle TASK_STATE.STOPPING in the control button to show "Stopping..."
with a disabled state and distinct orange styling, preventing duplicate
clicks and giving immediate visual feedback during pipeline shutdown.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(vscode): register canvas-played pipelines in sidebar menu
The PIPELINES sidebar failed to track pipelines started from the canvas
because source-component detection relied solely on config.mode being
set to "Source". The canvas editor never writes that field — only the
C++ engine adds it at execution time — so freshly saved .pipe files
from the canvas had zero recognised source components.
Three changes fix the issue:
1. PipelineFileParser.getSourceComponents now accepts an optional
service catalog and also checks each component's provider classType
array for "source", matching the same logic the canvas uses to
decide which nodes get a Run button.
2. SidebarFilesProvider passes the cached service catalog to the parser
when loading/re-parsing files, and re-parses all files when the
catalog first arrives (servicesUpdated) so that files parsed before
connect are retroactively enriched.
3. handleEvent now handles the "restart" apaevt_task action, which the
server sends instead of "begin" when a pipeline is restarted. Without
this, restarted pipelines silently dropped out of the active set.
Closes #396
#Hack-with-bay-2
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(test): resolve flaky timeouts and hanging in concurrent pipeline tests (#561)
The stress test (4 pipelines x 32 cycles) used a 30s hard-coded timeout
that was too tight for CI runners, causing both Jest timeout errors and
"Connection closed" failures under load. Several other concurrent tests
had the same issue. Test teardown could also hang indefinitely if a
WebSocket connection failed to close cleanly.
Root causes addressed:
- Hard-coded 30s timeouts on concurrent tests replaced with
TEST_CONFIG.timeout (120s) matching the rest of the suite
- Added single-retry with backoff in the stress test to handle transient
"Connection closed" errors from server-side frame drops under load
- Added bounded timeouts to all afterEach teardown blocks so cleanup
never hangs the runner
- Added forceExit to jest.config.js so Jest exits even with leaked handles
- Added pytest-timeout (120s default) in pyproject.toml to prevent
individual Python tests from hanging indefinitely
- Removed deprecated event_loop fixture from conftest.py (replaced by
pytest-asyncio auto mode)
- Added asyncio_mode = "auto" to pyproject.toml for consistent async
test handling
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(vscode): change play button to show actionable text instead of current state (#575)
- Rename idle label from "Play" to "Run Pipeline" for clearer intent
- Add STOPPING state with "Stopping..." disabled button to prevent
double-clicks and provide immediate visual feedback during shutdown
- Widen hover expansion to accommodate longer label text
- Smooth CSS transitions with easing functions for polished UX
Closes #398
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(ci): add build passthrough for docs-only PRs (#607)
When a PR only changes docs/README files, the Build job is correctly
skipped. But branch protection requires "Build / Ubuntu 22.04",
"Build / macOS (ARM64)", and "Build / Windows Server 2022" checks
to pass. The skipped jobs never report status, so PRs hang forever.
Add a build-skip job that runs on docs-only PRs and reports success
under the same check names, satisfying branch protection without
running actual builds.
Co-authored-by: Dmitrii <dmitrii@Dmitriis-MacBook-Pro-2.local>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(docs): reorder README header (#594)
* chore(docs): reorder README header — move language icons above description
Swaps the position of the language icon badges and the project
description so the icons appear more prominently. Also removes
fixed height attributes to let icons render at their native size.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): move closing div to include screenshots in header block
Extends the centered header div to wrap the screenshot images and
captions so they inherit the same alignment as the rest of the hero
section.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): remove Product Hunt badges from all READMEs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): reformat features section as table and update install screenshot
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): simplify features table — remove icons column
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): theme-aware language icons and replace emojis with unicode
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): revert language icons to original native-color PNGs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): reorder README header — move language icons above description
Swaps the position of the language icon badges and the project
description so the icons appear more prominently. Also removes
fixed height attributes to let icons render at their native size.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): move closing div to include screenshots in header block
Extends the centered header div to wrap the screenshot images and
captions so they inherit the same alignment as the rest of the hero
section.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): remove Product Hunt badges from all READMEs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): reformat features section as table and update install screenshot
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): simplify features table — remove icons column
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): theme-aware language icons and replace emojis with unicode
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): revert language icons to original native-color PNGs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): rename engine badge to Runtime and capitalize License
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(docs): capitalize all badge labels for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat(engine): support for experimental capability (#606)
* feat(engine): support for experimental capability
* feat(engine): support for experimental capability
* feat(engine): add DEPRECATED capability bit, move EXPERIMENTAL to BIT(16), and surface experimental badge in UI
- Insert DEPRECATED = BIT(15) into PROTOCOL_CAPS so services.json can
flag drivers as deprecated; shift EXPERIMENTAL from BIT(15) to BIT(16).
- Wire "deprecated" string in services.cpp parser and expose the new
constant via pybind11 bindings.
- Add PROTOCOL_CAPS enum to both client SDKs (TypeScript and Python)
with all 17 capability flags.
- Add Experimental flag (1 << 16) to the shared-ui IServiceCapabilities
enum.
- Render a yellow "EXPERIMENTAL" / "Experimental" badge on canvas nodes,
the Add Node slider, and the Quick Add popup when a service carries
the experimental capability.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(store): handle-based streaming I/O for file store (#600)
* feat(store): add handle-based streaming I/O to file store (open/read/write/close)
The store system previously had two problems: it buffered entire files
in memory for every read/write, and domain operations (save_project,
get_template, save_log, etc.) were implemented as monolithic methods
on the Store class with bespoke path construction and JSON
serialization baked in.
This change replaces that with a generic filesystem-style interface
(open, read, write, close, delete, stat, mkdir, list_dir) on
FileStore, with domain methods (save_project, get_template, save_log,
etc.) becoming thin convenience wrappers on the client SDKs that
call the generic file operations with well-known paths. The server
no longer needs to know about project/template/log semantics — it
just serves files.
The handle-based open/read/write/close pattern also enables streaming
large files without holding everything in memory, and lets each
backend use its native chunked upload API.
The open/write/close pattern is the lowest common denominator across
all three backends:
- S3: create_multipart_upload → upload_part (5 MB buffer) → complete
- Azure: stage_block (4 MB buffer) → commit_block_list
- Filesystem: open('wb') → write() → close()
Each handle is tagged with the owning connection_id so that when a
connection terminates, all its handles are force-closed (committing
whatever data has been written, not discarding it).
Changes by layer:
IStore (store.py):
- Added open_write, write_chunk, close_write, abort_write,
open_read, read_chunk, close_read with default in-memory
implementations so custom backends continue to work.
Backends (filesystem.py, s3.py, azure.py):
- FilesystemStore: holds aiofiles file descriptors across calls.
- S3Store: multipart upload with 5 MB buffer threshold; falls back
to single put_object for files under 5 MB.
- AzureBlobStore: staged blocks with 4 MB threshold; falls back to
upload_blob for small files.
- abort_write on all backends commits rather than discards.
FileStore (file_store.py — new file):
- FileHandle dataclass and FileHandleMode enum (inline, no separate
module — nothing outside FileStore imports them).
- Handle registry with per-path write locks (one writer at a time).
- close_all_handles(connection_id) for disconnect cleanup.
- read()/write() convenience methods now use handles internally.
- Fixed stat() to check directory before file (prevents filesystem
directories from being reported as files).
DAP command handler (cmd_task.py):
- fs_open, fs_read (handle-based), fs_write (handle-based), fs_close
replace the old path-based fs_read/fs_write subcommands.
- Removed domain-specific subcommands (save_project, get_template,
etc.) — these are now client-side convenience wrappers.
Disconnect cleanup (task_server.py):
- _dapbase_on_disconnected now calls close_all_handles for the
disconnecting connection.
Client SDKs (store.py, client.ts):
- fs_open/fs_read/fs_write/fs_close (Python) and
fsOpen/fsRead/fsWrite/fsClose (TypeScript) — identical shapes.
- Convenience wrappers (fs_read_string, fs_write_json, etc.) now
perform open/read|write/close internally.
- Domain methods (save_project, get_project, save_template, etc.)
are thin wrappers that serialize to JSON and write to well-known
paths using the generic file operations.
- Both SDKs use plain string handle IDs, no wrapper classes.
Tests:
- Fixed stale tests in test_store.py and test_file_store.py that
called methods removed from Store and FileStore.
- Added TestHandleIO to test_file_store.py (server-side).
- Added TestFileStoreOperations to Python client integration tests.
- Added File Store Operations to TypeScript client integration tests.
* fix(store): harden store API — validation, offset-on-read, file info, CLI fixes
The handle-based I/O added in f079c994 shipped with several gaps that
this commit addresses across the full stack (server, Python SDK, TS SDK,
both CLIs, and tests).
Security — path and ID validation
---
Paths and domain IDs (projectId, templateId, source) were interpolated
into storage keys without checking individual segments. A malicious
client_id like "../../other" or a projectId containing "*" could escape
account isolation or cause backend errors. Validation now happens at
three layers:
- Server (FileStore._validate_path): rejects *, ?, <, >, |, ", null,
and control characters per segment. __init__ rejects client_ids with
path separators or ".." values.
- Python SDK (StoreMixin._validate_store_path / _validate_id): same
rules applied before every DAP request that takes a path or domain ID.
- TS SDK (RocketRideClient.validateStorePath / validateId): same rules.
API change — move offset from open to read
---
Passing the byte offset at open time forced the server to track cursor
state internally, and gave the client no way to seek after opening.
Offset is now a parameter of read_chunk / fs_read / fsRead, letting the
client control position on every call. Convenience wrappers
(fs_read_string, fsReadString) track offset client-side in a loop.
File metadata — get_file_info, size in list_dir/stat
---
list_dir and stat previously returned only modification time for files,
and list_dir fetched it via a separate get_modified_time call. Added
IStore.get_file_info() returning {size, modified} in a single backend
call:
- Filesystem: one stat() call
- S3: one head_object call
- Azure: one get_blob_properties call
list_dir and stat now return both size (bytes) and modified (epoch
timestamp) for file entries. CLI dir output reformatted to match Windows
DIR style (date, time, <DIR> or size, name, summary counts).
Concurrency fixes in FileStore
---
- open_write: write lock was acquired after awaiting the backend, leaving
a race window at the suspension point. Lock now acquired before await,
released on failure.
- delete: rejects deletion while the path has an active write handle.
- read_chunk: negative offset rejected, length capped at MAX_CHUNK_SIZE.
- cmd_task handler: clamps client-supplied offset and length.
Broken CLI write commands
---
Both Python and TS CLIs called fs_write(path, data) — but after the
handle-based refactor, fs_write takes (handle, data). Fixed to use
fs_open/fs_write/fs_close with chunked streaming (64 KB in Python,
createReadStream in TS).
Cloud provider fixes
---
- Azure write_chunk: buffer bytes were deleted before _stage_block
completed, losing data on transient failures. Deletion now happens
after staging succeeds. close_write clears buffer after commit.
- S3 open_write: unconditionally called create_multipart_upload even for
small files, then aborted it in close_write. Multipart creation is now
deferred until the buffer first reaches 5 MB; small files use simple
put_object.
Minor fixes
---
- store.py: fallback temp path used 'dtc' instead of 'store', diverging
from the primary branch.
- task_server.py: disconnect path created a FileStore instance even when
the connection never used the store. Now checks the cache first.
- main.py: error message listed old command names (save_project, etc.)
instead of current ones (dir, type, write, rm, mkdir, stat).
- Integration tests: Python and TS test path schemes aligned to
.test-store/{lang}-{name}-{random} to prevent collision when run
concurrently.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(store): offload sync cloud SDK calls to thread pool via asyncio.to_thread
Both the Azure and S3 storage providers use synchronous SDKs (azure-storage-blob
and boto3) but are called from async methods on the event loop. With multiple
clients connected over WebSocket via the rrext_store DAP path, a blocking
upload_blob() or put_object() call freezes the entire event loop for all
connected clients.
Wrapped every synchronous SDK call in asyncio.to_thread() so network I/O runs
in the default thread pool executor:
Azure (azure.py):
- upload_blob, download_blob/readall, get_blob_properties, exists, delete_blob,
list_blobs, stage_block, commit_block_list — all offloaded
- _stage_block made async to await the to_thread call
S3 (s3.py):
- put_object, get_object/Body.read, head_object, delete_object, paginate
(list_objects_v2), create_multipart_upload, upload_part,
complete_multipart_upload, abort_multipart_upload — all offloaded
- _upload_part made async to await the to_thread call
- Multi-step operations (read + parse, paginate + collect) wrapped in
inner functions to keep the entire blocking sequence in one thread call
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(store): enforce handle ownership, fix empty-dir display, remove abort_write
Applied fixes from code review. Each finding was verified against the
current code; findings that were already addressed, architecturally
unsound, or purely stylistic were rejected with reasoning below.
Handle ownership enforcement
---
_get_handle now accepts an optional connection_id and rejects operations
from connections that don't own the handle. The cmd_task DAP handlers
pass self._connection_id on every read_chunk, write_chunk, close_write,
and close_read call. The parameter defaults to 0 (no check) so internal
callers (convenience methods, tests, close_all_handles) are unaffected.
This matters because handle IDs are UUIDs sent over the wire — without
ownership checks, a client that guesses or intercepts a handle ID from
another connection could read or write another user's open file.
Empty directory vs missing path
---
Both CLIs printed "File Not Found" when fs_list_dir returned zero
entries, which is wrong for an existing empty directory. They now call
fs_stat/fsStat to distinguish: empty dirs show a zero-count summary,
missing paths show "File Not Found".
Remove abort_write from API
---
abort_write existed on IStore and all three providers but had zero
callers — it was dead code. Rather than build out discard semantics for
an unused API surface, the method was removed entirely. If abort
semantics are needed in the future, they can be added with a clear
use case driving the design.
Silent exception swallowing in listing
---
_get_all_items (Python) and getAllProjects/getAllTemplates (TS) caught
all exceptions and silently continued when reading project/template JSON
files. This hid file corruption, permission errors, and malformed JSON
with no diagnostic output. Both now log the error at debug level before
continuing, so issues are visible in logs without breaking the listing.
Findings rejected (with reasoning)
---
- task_server.py client_id empty default: The empty string is a
dataclass initialization pattern, not a security gap. client_id is set
from _account_info.clientid after authentication succeeds, and
unauthenticated connections cannot reach the store. Adding validation
at the dataclass level would require finding and updating every
construction site for a field that is always set by the auth flow.
- cmd_task.py chunk length clamping: Already implemented in the prior
commit (ec225ed3). The review was looking at stale code.
- filesystem.py lock/temp-file staging for open_write: The review
proposed acquiring the existing file lock for the entire lifetime of a
write handle and writing to a temp file with atomic rename on close.
This would be a significant architectural change that conflicts with
the current design: FileStore._write_locks already provides
single-writer exclusion at the application layer, and the handle-based
API is designed for streaming large files where holding a filesystem
lock for minutes would block all other operations (reads, stat,
list_dir) on that file. The current approach — application-level write
locks + direct file I/O — is appropriate for the access patterns.
- fs_write_string simplification: The review suggested replacing the
nested try/except with finally + contextlib.suppress. The current
pattern correctly calls fs_close exactly once on the success path and
exactly once (best-effort) on the error path before re-raising. A
finally block would call close twice on the success path (once
explicitly, once in finally). Equivalent behavior would require a
flag variable, making it no simpler than the current code.
- Integration tests for mkdir/list_dir: Test additions are valuable but
are a separate concern from the code fixes in this commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(tools): Replace tool declarations @tool_function decorators on IInstanceBase (#599)
* refactor(engine): replace ToolsBase driver classes with @tool_function decorators on IInstanceBase
Every tool-providing node previously required two parallel classes: an
IInstance (pipeline integration) and a ToolsBase driver (tool definitions).
The driver implemented three abstract methods (_tool_query, _tool_validate,
_tool_invoke) and the IInstance wired them together with boilerplate
delegation in invoke(). This created a parallel system that was hard to
understand and tedious to write — the driver often just called back into
the instance for the actual work, and every node repeated the same
delegation pattern.
The root cause was that tool declaration was separate from the class that
actually owned the state and connections needed to execute the tool. A
MySQL node's IInstance had the database connection, the LLM access, and
the lane handlers — but its tool definitions lived in a MySQLDriver class
that had to reach back into the instance for everything.
This commit collapses both layers into one by adding @invoke_function and
@tool_function decorators directly to IInstanceBase in rocketlib/filters.py.
Any IInstanceBase subclass can now declare tool entry points with a
decorator — the method name becomes the tool ID, the decorator carries the
schema and description, and the base class invoke() dispatches
automatically. No separate driver class, no factory method, no delegation.
Usage example — static tool:
from rocketlib import IInstanceBase, tool_function
class IInstance(IInstanceBase):
IGlobal: IGlobal
@tool_function(
input_schema={
'type': 'object',
'required': ['url', 'method'],
'properties': {
'url': {'type': 'string'},
'method': {'type': 'string', 'enum': ['GET', 'POST']},
},
},
description='Make an HTTP request.',
)
def http_request(self, args):
if args['method'] not in self.IGlobal.enabled_methods:
raise ValueError('Method not allowed')
return execute_request(url=args['url'], method=args['method'])
Usage example — dynamic description from config:
class DatabaseInstanceBase(IInstanceBase):
@tool_function(
input_schema={...},
description=lambda self: (
f'Query the {self._db_display_name()} database. '
f'Just describe what data you need.'
),
)
def get_data(self, args):
...
Usage example — dynamic tools (MCP, tools discovered at runtime):
class IInstance(IInstanceBase):
def _tool_query_dynamic(self):
return self.IGlobal.list_namespaced_tools()
def _tool_invoke_dynamic(self, *, tool_name, input_obj):
server, bare = tool_name.split('.', 1)
return self.IGlobal.call_tool(server, bare, input_obj)
The decorator system follows the existing control/invoke layering:
control() <- engine entry point, rarely overridden
└─ invoke() <- dispatches on param.op
├─ tool.* -> @tool_function methods (tool.query builds
| descriptors, tool.invoke calls the method)
└─ other ops -> @invoke_function methods (op name = method name)
Key design decisions:
- Decorators live in rocketlib/filters.py with zero upstream dependencies.
The declaration plumbing (ToolDescriptor, @tool_function, @invoke_function,
dispatch logic) is entirely self-contained in the engine base layer.
- No tool name prefix. Tool IDs are bare method names (e.g. 'get_data',
not 'mysql.get_data'). The agent host already namespaces by nodeId to
prevent collisions between multiple nodes of the same type.
- No separate validation step. tool.validate is removed from the dispatch.
Validation is guard clauses at the top of the function body — simpler,
more obvious, impossible to forget.
- Decorator parameters accept static values or callables. Roughly half of
all tools need runtime config in their descriptions (e.g. the user-entered
database description, allowed import lists, display names). These use
lambda self: ... which is resolved at tool.query time when self.IGlobal
is available. This is a first-class pattern, not an escape hatch.
- User-entered tool descriptions are auto-prepended. The "tool" field from
the node config (e.g. "This is a database of world cities") is read via
_tool_config_description() and prepended to every @tool_function's
description automatically. Individual decorators only provide the fixed
part.
- Dynamic tools (MCP) use _tool_query_dynamic / _tool_invoke_dynamic
overrides on IInstanceBase for tools discovered at runtime from external
servers. Only MCP needs this.
- Backward compatible with the agent-as-tool pattern. The four agent nodes
still use _AgentAsToolProvider via ToolsBase — they are not tool nodes in
the decorator sense, they use a different mechanism for exposing
themselves as tools to other agents.
Migrated nodes:
- chart_chartjs: generate_chart (also eliminated the set_llm_invoker
callback — IInstance calls self.instance.invoke('llm', ...) directly)
- tool_python: execute
- tool_http_request: http_request
- tool_firecrawl: scrape_url, map_url
- memory_internal: put, get, list, clear
- db_mysql, db_postgres: get_data, get_schema, get_sql (via
DatabaseInstanceBase with callable descriptors for display names)
- db_neo4j: get_data, get_schema, get_cypher
- mcp_client: dynamic tools via _tool_query_dynamic/_tool_invoke_dynamic
Deleted (11 files, ~1600 lines):
- All *_driver.py files (http, python, firecrawl, chartjs, memory, mcp,
mysql, postgres, neo4j)
- packages/ai/src/ai/common/database/db_driver_base.py
- DatabaseDriverBase removed from database __init__.py exports
Updated imports:
- Agent framework drivers (langchain, crewai, deepagent) and AgentBase
now use ToolDescriptor from rocketlib instead of ToolsBase.ToolDescriptor
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(nodes): fix tool schema key mismatch, harden node implementations
The @tool_function decorator builds ToolDescriptors with camelCase keys
(inputSchema, outputSchema) but three of the four agent drivers were
reading snake_case (input_schema), silently getting None for every
tool's parameter schema. The LLM never saw real parameter definitions —
it always fell back to a generic "accept anything" schema.
Tool schema fix (3 agent drivers)
---
- agent_langchain: td.get('input_schema') → td.get('inputSchema')
- agent_deepagent: td.get('input_schema') → td.get('inputSchema')
- agent_crewai: already handled both with fallback; simplified to
td.get('inputSchema') for consistency
llm_base: replace manual dispatch with @invoke_function
---
The manual match/case block in llm_base/IInstance.py duplicated what the
base class invoke() auto-dispatcher already provides. Replaced with four
@invoke_function decorated methods (ask, getContextLength,
getOutputLength, getTokenCounter). Removed the now-unused IInvokeLLM
import.
Node hardening (from code review)
---
- chart_chartjs: inverted ternary → idiomatic `description or "default"`
- memory_internal: _store type MemoryStore → MemoryStore | None; put/get/
clear raise ValueError on non-dict args instead of silently coercing
- tool_firecrawl: metadata.model_dump() exception now logged via warning;
JSON parse catch narrowed to JSONDecodeError/TypeError with log
- tool_http_request/IGlobal: mutable class-level set()/[] defaults →
None; typing.Set/List → built-in set/list
- tool_http_request/IInstance: str(body_json) fallback → json.dumps() so
non-dict/list/str values produce valid JSON
- tool_python/IGlobal: typing.Set → built-in set; removed unused imports
- db_instance_base: int(raw_limit) wrapped in try/except, falls back to
250 on parse error instead of raising
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(nodes): address PR review findings — input validation, lint, and hardening
- langchain: fix ANN401/ARG002/UP037 on bind_tools signature
- chart_chartjs: reject non-list/dict data, cap serialized payload at 20KB,
validate and normalize LLM JSON output before wrapping in chartjs fence
- llm_base: rename unused param → _param on invoke handlers (ARG002)
- tool_firecrawl: simplify formats array → single format string, redact raw
payload from warning log
- tool_http_request: fail-fast validation on auth/body types and nested
fields; fail-closed on malformed urlWhitelist in guardrails
- tool_python: validate json.loads result is a list before iterating
- memory_internal: enforce key type/presence in put/get/clear, add dict
check to list handler
- db_instance_base: add missing valid boolean to success/failure return
dicts; fix stale _create_driver docstring → _db_display_name()
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add Discord notifications for PRs, issues, and discussions (#612)
- Posts to separate Discord channels via webhooks on PR open, issue
open, and discussion create events
- Uses jq for safe JSON construction (avoids shell escaping issues)
- Truncates body to 1500 chars with unclosed code block detection
- Webhook URLs stored as GitHub Secrets
- Uses GitHub Actions (not native /github endpoint which is unreliable
for discussions per Reddit r/discordapp consensus)
Closes #610
Co-authored-by: Dmitrii <dmitrii@Dmitriis-MacBook-Pro-2.local>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(vscode,engine): Add server monitor (#595)
* refactor(engine): remove ServicePython log level in favor of DebugOut
ServicePython was a dedicated trace level only used by the Python
service layer, but it duplicated what DebugOut already provides.
Consolidating into DebugOut simplifies the Lvl enum surface, removes
a Python-specific flag that callers had to know about separately,
and makes trace configuration more intuitive — `--trace=debugOut`
now covers Python service output alongside other debug tracing.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(sdk): add dashboard API and client identification to auth handshake
The server's new rrext_dashboard command provides real-time visibility into
connections, tasks, and aggregate metrics — but neither SDK could call it.
This adds getDashboard() (TS) and get_dashboard() (Python) with full type
definitions so consumers like the VS Code extension can surface server
health without raw DAP calls.
Both SDKs now also accept clientName/clientVersion config options and
forward them during the auth handshake. This lets the server distinguish
which client is connected (e.g. "VS Code 0.9.4" vs "CLI 1.2.0"), which
the dashboard surfaces in each connection's clientInfo field.
The Python DAPClient also now skips the auth message when the transport
lacks get_auth() (e.g. stdio to a subprocess), fixing a crash for
non-WebSocket transports that don't implement DAP authentication.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(vscode): add server monitoring dashboard and fix subscription stomping
Multiple VS Code providers (editor, status, sidebar) share a single
WebSocket connection but independently called rrext_monitor with REPLACE
semantics — each provider's subscription silently overwrote the previous
one, causing missed events depending on activation order.
Introduce MonitorManager, a reference-counted subscription layer that
merges per-key bitmasks across providers and replays them on reconnect.
All providers now subscribe/unsubscribe through MonitorManager instead
of issuing raw rrext_monitor requests.
Add a Server Monitor dashboard (PageDashboardProvider + ServerMonitor
shared-ui component) that surfaces connected clients, running tasks,
and server activity without leaving the IDE. To support this, the
auth handshake now sends clientName/clientVersion so the server can
identify who is connected.
Also threads pipeline names through the execute command and defaults
component display names from the service catalog, so tasks appear with
human-readable labels in the dashboard and status views.
* feat(engine): add dashboard endpoint, connection tracking, and transport fixes
Implement rrext_dashboard command handler with server overview, active
connections, and task metrics. Track per-connection message counts, activity
timestamps, and client identity from auth handshake. Fix status_object event
name typo and exit message parsing in stdio transport. Add task name priority
from execute args over config.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(monitor): improve dashboard readability, component naming, and UX polish
The server monitoring dashboard was functional but hard to read — monitor
subscription keys showed raw UUIDs (p.3fda047b-fcc8-...), attached tasks
showed internal IDs (aa37e50b.chat_1), the outgoing message counter was
never incremented, and several UI details felt rough.
Dashboard data improvements (cmd_misc.py, task_conn.py):
- Resolve monitor keys to human-friendly labels: '*' becomes 'All tasks',
'p.{uuid}.*' becomes 'analyze.*', 'p.{uuid}.chat_1' becomes 'analyze.Chat'
- Show event type flags (summary, flow, task, etc.) alongside each monitor
subscription so operators can see what each connection is listening for
- Return task display names in attachedTasks instead of internal token IDs
- Increment _messages_out counter via send() override in TaskConn — the
counter was initialized but never updated, so the dashboard always showed 0
Task naming (task_engine.py):
- Change status name format to '{task_name|task_id}.{component_name|source}'
so tasks are identifiable by both their execution context and component,
which feeds into the dashboard's friendly label resolution
Component name enrichment (PageEditorProvider.ts):
- Enrich pipeline components with default names from the service catalog
before sending to the canvas webview, so components that lack an explicit
name get the service title (e.g. 'Chat', 'OpenAI') at the provider level
rather than displaying blank or falling back to the raw component ID
Connection page UX (PageConnection.tsx):
- Show Monitor button always, disabled when not connected — previously it
disappeared entirely, giving no indication the feature exists
Sidebar UX (SidebarFilesProvider.ts):
- Switch pipeline restart prompt from modal to toast notification to
eliminate the redundant Cancel button that VS Code forces on modal dialogs
Dashboard UI (ConnectionsTab.tsx, server-monitor.css, dashboard.ts):
- Render each monitor subscription on its own row with flag badges instead
of cramming all keys into a single tag list
- Remove left border accent from selected table row in favor of full
background highlight for cleaner selection feedback
- Update DashboardConnection.monitors type from string[] to {key, flags}[]
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(engine): add task token auth, harden multi-tenant isolation, and clean up teardown
The task server lacked tenant isolation — any authenticated API key could
interact with any task, the dashboard exposed all connections and tasks
across accounts, monitor subscriptions weren't ownership-checked, and
there was no way for external tools to authenticate scoped to a single
task. The debug disconnect also didn't actually detach, and subprocess
teardown had race conditions.
Task token authentication (task_server.py):
- Introduce 'tk_' prefixed task tokens that grant scoped control over a
single task, alongside the existing 'pk_' public tokens for data-only
access. This gives external integrations (MCP, webhooks) a way to
authenticate directly to a task without a full API key.
- Generate task tokens with the 'tk_' prefix during task setup so they
are distinguishable from public and API key credentials.
- Rework control.id to strip the auth prefix before hashing, so display
IDs remain clean regardless of token type.
- Remove get_server_status() and the _tasks_peak/_tasks_total counters —
these were server-global metrics that leaked cross-tenant data and are
now replaced by the per-account dashboard endpoint.
Multi-tenant dashboard isolation (cmd_misc.py):
- Add permission check (task.monitor) to the dashboard endpoint.
- Filter task_controls and connections to only the caller's API key so
each account sees only its own tasks and connections.
- Remove peakTasks and totalTasksLifetime from overview — these were
server-global counters that exposed cross-tenant activity.
Dashboard type updates (dashboard.ts, dashboard.py, OverviewTab.tsx):
- Remove peakTasks and totalTasksLifetime from DashboardOverview in both
TypeScript and Python SDK types.
- Update OverviewTab to remove the Total Tasks card and peak subtitle.
- Update comments to clarify metrics are scoped to the caller's account.
Task ownership enforcement (task_conn.py, cmd_task.py, cmd_monitor.py):
- Add apikey ownership checks in get_task() so API key callers can only
access tasks they launched — previously any valid key could reach any
task. pk_ and tk_ auth are already inherently scoped by get_task_token.
- Add permission check and ownership verification to rrext_get_token so
the token for a running task can't be retrieved by a different account.
- Add ownership checks to monitor set_monitor() for both token-based and
project-based subscriptions, with PermissionError re-raised past the
generic exception handler.
- Fix verify_permission return type annotation (was bool, actually None).
- Resolve token from request.arguments.token as a fallback, not just the
top-level request.token, so callers that pass token in args work correctly.
- Recognize tk_ tokens in get_task_token as locked to their task, same as pk_.
Debugger fixes (cmd_debug.py):
- Rewrite attach to use get_task()/get_task_token() for ownership validation
instead of manually extracting the token and calling verify_permission,
aligning it with how all other commands validate access.
- The disconnect handler was calling self.get_task() (which just validates)
but never called self._server.detach_task(), so disconnecting a debug
session left the debugger attached on the task side. Now properly detaches.
- Rewrite terminate to also use get_task()/get_task_token() consistently.
- Save task control ID on attach so debug events reference the right task.
Subprocess teardown hardening (task_engine.py):
- Set _is_terminating flag at the start of on_teardown and on_terminate to
block new data operations from racing against shutdown.
- Guard engine.terminate() against None engine reference — the subprocess
may not have started if the task fails during init.
- Use local 'engine' variable consistently instead of self._engine_process
to avoid TOCTOU issues during termination.
- Use Task.TaskData wrapper for data client connections.
- Reset exitCode to None instead of 0 in reset_status so completed-with-
success (exit 0) is distinguishable from never-ran.
Source resolution extraction (pipeline.py):
- Extract the duplicated "find the single source component" logic from
task_server.py and cmd_misc.py into a shared resolve_implied_source()
utility. Both call sites had identical logic for scanning components,
detecting ambiguity, and returning the source ID.
Minor cleanup:
- Replace magic number 3 with TASK_STATE.RUNNING.value in MCP tool listing.
- Remove unused HTTPException import and dead config variable in task_server.
- Remove stray blank line in data_conn.py.
- Fix error log in detach to reference token instead of unresolved control.id.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(monitor): add strongly-typed event definitions, dashboard activity stream, and SDK self-identification
The server monitor Activity tab was always empty because no events were
emitted or forwarded. Monitor subscriptions leaked when tasks were removed
or editors closed. The SDKs didn't identify themselves, making connections
opaque. And the event type definitions between Python and TypeScript were
inconsistent, incomplete, and weakly typed — the old EVENT_TASK used a
loose TypedDict with total=False in Python and a DAP wrapper with fields
that never existed on the wire in TypeScript.
Strongly-typed event definitions (events.ts, events.py, dashboard.ts, dashboard.py):
- Replace weak, inconsistent event types with strongly-typed discriminated
unions in both SDKs, using 'action' as the discriminant field. TypeScript
enforces exact field sets per variant at compile time; Python uses Literal
types on action fields for the same guarantee at type-check time.
- TaskEvent (TS) / TASK_EVENT (Python): four variants — TaskEventRunning,
TaskEventBegin, TaskEventEnd, TaskEventRestart. Each lifecycle variant
includes the new 'name' field. These are body-only types describing the
apaevt_task payload — not DAP message wrappers. The old EVENT_TASK had
an 'id' field at the root that never existed on the wire (the server
puts id into body.__id via build_event). The new types correctly describe
what clients actually receive.
- DashboardEvent (TS) / DASHBOARD_EVENT (Python): eight variants —
ConnectionAdded, ConnectionRemoved, TaskStarted, TaskStopped,
TaskRemoved, TaskError, AuthFailed, MonitorChanged. Each variant has
only the fields that apply — connection events carry connectionId and
optional client identity, task events carry taskId, error events carry
exitCode, etc. No optional fields leaking across variants.
- Both SDKs are in full parity: identical variant names (PascalCase TS,
SCREAMING_CASE Python), identical fields per variant, identical action
string literals.
- Add DASHBOARD (1 << 7) and SSE (1 << 6) to EVENT_TYPE enum in both
SDKs — SSE was already on the server but missing from the client types.
- Update DASHBOARD_MONITOR, DASHBOARD_TASK (add name, Optional nullables,
rate/count fields) and DASHBOARD_CONNECTION (monitors as {key, flags}[])
in both SDKs.
Server event emission (task_server.py, task_conn.py, cmd_monitor.py, task_engine.py):
- Add broadcast_server_event(type, event) on TaskServer and
send_server_event(type, event) on MonitorCommands for server-level
events that aren't task-scoped. Mirrors the existing
broadcast_task_event/send_task_event pattern — both paths go through
the connection's monitor layer, server events just check the '*'
wildcard only.
- Rename forward_event to send_task_event for clarity alongside the new
send_server_event.
- Emit apaevt_dashboard events: connection_added (from on_auth, after
client info is captured), connection_removed (from on_disconnect),
task_removed (from remove_task cleanup), task_error (non-zero exit
in task teardown), auth_failed (from on_auth rejection),
monitor_changed (from set_monitor subscribe/unsubscribe).
- Include 'name' in all apaevt_task lifecycle event bodies (begin, end,
restart) so consumers can display human-readable task names.
- Clean up monitor subscriptions when tasks are removed from the registry.
Dashboard provider and webview (PageDashboardProvider.ts, PageDashboard.tsx):
- Subscribe to ['task', 'summary', 'dashboard'] so the provider receives
both apaevt_task and apaevt_dashboard events.
- Forward them as separate typed message types to the webview: 'taskEvent'
with TaskEvent body, 'dashboardEvent' with DashboardEvent body. No
conversion between them — each channel keeps its native shape.
- Webview wraps both in ActivityEvent tagged union ({ source: 'task' |
'dashboard', body }) and accumulates up to 100 events newest-first.
Activity tab display (ActivityTab.tsx, OverviewTab.tsx):
- Separate display functions per event source: getTaskEventDisplay handles
running/begin/end/restart, getDashboardEventDisplay handles all eight
dashboard event types. Both leverage discriminant narrowing for type-safe
field access.
- Show client identity in connection events: "Cursor 1.0.6:#3 connected".
- Fix completed tasks showing internal ID instead of display name.
Monitor lifecycle cleanup (task_server.py, PageEditorProvider.ts):
- Remove monitor subscriptions for a task across all connections when the
task is removed from the registry.
- Fix PageEditorProvider.stopMonitoring to always call removeMonitor on
editor dispose regardless of isMonitoring flag — a disconnect/reconnect
cycle could desync the flag from the MonitorManager refcount, leaking
subscriptions.
SDK self-identification (DAPClient.ts, client.py, constants.ts, tasks.js):
- Default clientName to 'TypeScript SDK' / 'Python SDK' when not provided
by the caller, so connections are identifiable in the dashboard.
- Default clientVersion to the SDK's own version: TypeScript reads
SDK_VERSION from constants.ts (auto-synced from package.json by the new
sync-version build task), Python reads from importlib.metadata so it
always matches pyproject.toml. Source files default to '' — the real
value is set at build time (TS) or import time (Python).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(vscode): fix broken CSS comment headers and move padding/background to views
Every view-specific CSS file (PageConnection, PageDeploy, PageEditor,
PageSettings, PageStatus) plus the shared app.css and vscode.css were
missing the opening '/*' on their license comment blocks. The CSS parser
treated the unclosed comment as content, silently dropping all rules that
followed — body resets, container padding, layout classes, everything.
This is why view-specific styles appeared to have no effect.
CSS comment fixes:
- Add missing '/*' opener to PageConnection, PageEditor, PageStatus,
PageSettings, app.css, and vscode.css
- Remove stray closing comment fragment from PageDeploy
View-owned padding and background:
- Remove view-specific body padding rules (body.settings, body.sidebar-status,
body:not(...)) from vscode.css — these were unreliable because VS Code's
own webview styles can override body padding
- Set body to padding: 0; margin: 0 as a clean baseline
- Each view's root container now owns its own padding and background:
PageSettings gets padding: 24px, PageStatus/PageDeploy get background-color
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(monitor): harden monitor branch — security, correctness, and cleanup
Addresses code review findings across the monitor feature branch. Each
fix was verified against the current code before applying.
Security
---
- ConnectionsTab: raw API key no longer displayed in the detail panel;
masked to first/last 4 chars with bullets in between.
- cmd_misc: _resolve_monitor_label no longer echoes raw task tokens for
non-'p.' monitor keys; returns 'Task monitor' instead.
Correctness
---
- extension.ts: _pageDashboard.dispose() added to deactivate() — was
leaking event listeners registered in setupEventListeners().
- PageDashboardProvider: generateNonce() now uses crypto.randomBytes()
instead of Math.random(); require('fs') replaced with ES import.
- SidebarFilesProvider: pipeName strips both .pipe and .pipe.json
suffixes so legacy filenames produce the correct name.
- cmd_debug: disconnect flow tolerant of tasks removed by on_terminate
(best-effort detach); debug state cleared in finally block.
- cmd_monitor: 'type' parameter renamed to 'event_type' to avoid
shadowing the Python builtin; bitmask parsing now accepts integer
values and legacy listenType in addition to string arrays.
- pipeline.py: separate seen_source boolean from source_id to correctly
detect multiple Source components even when the first has no id.
- task_conn: mutable default dict on on_receive replaced with None
guard to prevent shared-state leakage across calls.
- dap_client: auth request wrapped in try/except — transport is now
disconnected if the auth request itself throws (timeout, network
error) instead of leaving a half-open connection.
- transport_stdio: None guard at top of _process_message prevents
AttributeError when message is None (end-of-stream).
- FlowGraphContext: shallow clone data.config before mutating .name so
the caller's object is not modified.
Cleanup
---
- client.ts: getDashboard docstring corrected from 'server.monitor' to
'task.monitor'.
- engine.py: debug() docstring no longer references removed
ServicePython trace level.
- hooks/index.ts: added export {} so the file is a valid ES module.
- server-monitor.css: currentColor → currentcolor for stylelint
value-keyword-case rule.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(monitor): address PR review findings — error propagation, naming, types
- monitor-manager: syncKey now rethrows on failure; addMonitor rolls back
refCounts so local state stays in sync with server on error
- PageDashboardProvider: add hasWildcardMonitor guard to prevent duplicate
wildcard subscriptions on reconnect
- cmd_debug: move get_task_token() before get_task() in attach/terminate
so token is always defined in error handlers
- cmd_monitor: rename shadowed `type` parameter to `event_type` in
send_task_event (A002); update callers in task_server and task_engine
- task_conn: fix mutable default argument on on_receive (Dict={} → Optional=None)
- task_server: include token-scoped keys in stop_task monitor cleanup;
only strip known auth prefixes (tk_, pk_) when building display id
- tasks.js: use robust regex for SDK_VERSION matching; throw on no match
instead of silently succeeding
- dashboard.ts: allow string | null on nullable wire fields (clientName,
clientVersion, clientId, exitMessage)
- events.ts: fix docstring example to match TaskEvent type fields
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Update packages/shared-ui/src/modules/flow/context/FlowGraphContext.tsx
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* fix(monitor): address remaining PR review findings — security, dedup, a11y, types
- Restrict tk_ token dashboard scope to own task/connection (cmd_misc.py)
- Deduplicate overlapping monitor event sends by merging preferences (cmd_monitor.py)
- Import shared ActivityEvent type instead of local duplicate (PageDashboard.tsx)
- Stamp receivedAt on activity events at receive time, not render (ActivityTab/types)
- Add ARIA tab semantics: role=tablist/tab/tabpanel, aria-selected (ServerMonitor)
- Add keyboard accessibility: tabIndex/onKeyDown on tr, semantic close button (ConnectionsTab)
- Extract TRANSITIONAL_STATES constant to eliminate 4× duplicated OR-chains (PageConnection)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(monitor): tenant-scope broadcasts, coalesce fetches, balance monitors, harden dashboard
- Add apikey parameter to broadcast_server_event + send_server_event for tenant scoping
- Pass apikey from all 6 scoped call sites (connection add/remove, task error/remove, monitor change)
- Coalesce overlapping fetchAndPost() calls via in-flight/pending flags (PageDashboardProvider)
- Balance wi…
* feat(nodes): add tool interface for vector DB operations Introduces a generic tool_vectordb node that exposes vector database operations (search, upsert, delete) as ToolsBase-compatible tools that LLM agents can invoke. The node works with multiple vector DB backends (Pinecone, ChromaDB, Qdrant) through the shared DocumentStoreBase interface, providing a unified tool abstraction for semantic search. Closes #442 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): use glb.connConfig instead of missing getConnConfig() IGlobalBase does not have getConnConfig() — that method is on IGlobalTransform. Use self.glb.connConfig which is the standard pattern for tool nodes (matches tool_http_request, tool_firecrawl). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): correct description to match supported backends Remove Weaviate and pgvector from services.json description since _BACKEND_MODULES only supports pinecone, chroma, and qdrant. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): add vectordb.svg node icon Database cylinder icon matching the 24px viewBox, fill="currentColor" pattern used by other node icons (e.g. http.svg). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): log warning on malformed JSON input _normalize_input previously swallowed JSON parse errors silently, making it hard to diagnose bad tool inputs. Now logs a warning with the parse error before returning an empty dict. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style(tool_vectordb): remove redundant parentheses in str() calls Clean up double-wrapped parens like str((cfg.get('x') or 'y')) to the simpler str(cfg.get('x') or 'y'). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR #524 review feedback for tool_vectordb - Remove invalid topK param from QuestionText constructor; use doc_filter.limit to control result count instead - Add embedding warning in upsert and document the limitation in the tool description - Read backend connection config from bag first, fall back to own connConfig - Distinguish disabled-tool vs unknown-tool error messages Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): migrate tool_vectordb to @tool_function pattern per PR #599 Remove VectorDBDriver(ToolsBase) and move search/upsert/delete tool logic to @tool_function decorated methods on IInstance. Store config and backend connection directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address remaining review feedback on tool_vectordb - Add return type annotation to IGlobal._create_store() - Downgrade semantic-to-keyword fallback log from warning to debug - Fix total count to match actual returned results after top_k slice - Return skipped document count from upsert operation - Narrow metadata schema to document only recognized fields (nodeId, parent, chunkId) instead of additionalProperties: true Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): move vector DB tool interface into store.py per review feedback Rod-Christensen suggested co-locating the tool definitions with the underlying store so every vectordb node can "morph into a tool" without a separate generic wrapper node. The engine dispatches ``invoke`` against the node's ``IInstance`` (not the ``DocumentStoreBase`` subclass, which is composed via ``self.IGlobal.store``), so a mixin that lives next to ``DocumentStoreBase`` in ``store.py`` and is inherited by the vectordb ``IInstance`` classes achieves the spirit of the suggestion while being technically correct. Changes: - Add ``VectorStoreToolMixin`` to ``packages/ai/src/ai/common/store.py`` with ``@tool_function`` decorated ``search``, ``upsert`` and ``delete`` methods that delegate to ``self.IGlobal.store``. The mixin is picked up automatically by ``IInstanceBase._collect_tool_methods`` via MRO walk. - Have ``pinecone``, ``chroma`` and ``qdrant`` ``IInstance`` classes inherit from ``VectorStoreToolMixin`` so each vectordb node exposes the search/upsert/delete tools natively. - Add ``"tool"`` to ``classType`` and ``"invoke"`` to ``capabilities`` in each node's ``services.json`` so ``getControllerNodeIds('tool')`` discovers them as tool nodes. - Delete the ``tool_vectordb`` node entirely — obsolete now that every vectordb node has native tool capability. - Delete the unused ``vectordb.svg`` icon that existed only for the now-deleted ``tool_vectordb`` node. - Fix the wrapped-payload normalization bug flagged in CodeRabbit comment 3049766102: ``{'input': '{"query": "x"}'}`` and ``{'input': SomeModel(...)}`` now recurse through ``_normalize_vectordb_tool_input`` on the inner value, so string-, model- and dict-wrapped payloads all receive the same JSON-parse/``model_dump`` treatment before merging outer extras. Other vectordb connectors (astra_db, milvus, weaviate, atlas, vectordb_postgres, index_search) can opt in to the same tool interface with a one-line change to their ``IInstance.py`` plus the services.json update — out of scope for this PR. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address blockers on vectordb tool interface Address 3 blocking issues on PR #524: 1. Tool name collisions: adopt the established <serverName>.<toolName> convention used by mcp_client. VectorStoreToolMixin now overrides _collect_tool_methods to prefix each tool with a per-node serverName sourced from IGlobal.serverName (user-configurable via services.json). Two pinecone/chroma/qdrant instances in the same pipeline no longer collide on bare names like "search"/"upsert"/"delete". 2. Broken pinecone semantic search: the mixin was calling searchSemantic with an unset embedding, which raises in every backend (pinecone/ chroma/qdrant) and silently fell through to keyword search. Add an IGlobal.embed_query hook so nodes can plug in an embedder for the control-plane tool path; when no embedder is bound, go straight to keyword search with a one-shot warning and update the tool description so agents know the mode. Unexpected semantic errors still fall back to keyword search with a clearer warning message. 3. No tests for VectorStoreToolMixin: add nodes/test/test_vectordb_tool_mixin.py (28 tests) covering input normalization (dict/JSON/pydantic v1+v2/ nested input wrapper/security_context stripping/malformed payloads), namespaced tool method collection including the collision-avoidance scenario, and search/upsert/delete dispatch through a fake store plus keyword-fallback, semantic-fallback, and missing-store error paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(nodes): cover embedder envelope contract + auto-embed + caller-supplied (#524) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(nodes): add envelope test for addChunks exception path (#524) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(nodes): repair embedding_* package-level Embedding aliases (#524) `embedding_openai/__init__.py` imported `Embedding` from `OpenAIEmbeddingWrapper` but the class there is named `OpenAIEmbeddingWrapper`. The `getEmbedding` dispatcher (`ai.common.embedding`) resolves embedding providers by calling `module.getEmbedding()` which previously returned the wrong name, crashing any caller that instantiated the result. Add an alias so `getEmbedding()` returns a name-stable `Embedding` class. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(nodes): wire per-node embedder + return tool-invoke error envelopes (#524) Wire a control-plane embedder (embed_query / embed_model_name) into the beginGlobal of each vectordb node (pinecone, chroma, qdrant) using the same autopipe/vectorizer pattern: read the 'embedding' sub-config from the merged node config and only instantiate when present. endGlobal tears down the embedder before the store. The _embed_query closure wraps the text in a Question object so encodeQuestion iterates question.questions correctly. In VectorStoreToolMixin: - search: remove silent keyword-fallback for the no-embedder case; return an error envelope instead (keeps keyword fallback only after a failed semantic call when an embedder IS bound) - upsert: accept optional per-doc 'embedding'/'embedding_model' fields; compute via IGlobal.embed_query when not supplied; return envelope when no embedder is available; wrap addChunks in try/except -> envelope - delete: convert ValueError raises to error envelopes - search: expand output_schema with optional success/error fields Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style: ruff format store.py after rebase onto develop (#524) Develop's ruff format pass (landed after branch point) reformatted some regions of store.py. Re-apply ruff format to stay consistent. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style(nodes): ruff format test_vectordb_tool_mixin.py for CI line wrap CI's ruff config wrapped 3 multi-arg FakeStore/FakeIInstance calls onto multiple lines; local ruff didn't. Apply ruff format to align. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ketride-org#599 Remove V0Driver(ToolsBase) and move generate_ui/refine_ui tool logic to @tool_function decorated methods on IInstance. Store apikey directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ketride-org#599 Remove V0Driver(ToolsBase) and move generate_ui/refine_ui tool logic to @tool_function decorated methods on IInstance. Store apikey directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(nodes): add v0 by Vercel tool node for AI-powered UI generation Adds a new tool_v0 pipeline node that integrates with Vercel's v0 API to generate React + Tailwind CSS components from natural-language prompts. Exposes generate_ui and refine_ui as agent-invocable tools. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR #557 feedback on v0 Vercel node - Format services.json with inline comments matching repo conventions - Return success:false when _extract_code yields empty code instead of success:true with empty string - Include prior_messages in refine_ui for stateless API fallback while keeping parent_message_id for stateful servers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): format services.json and add header comment for v0 node Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): migrate tool_v0 to @tool_function pattern per PR #599 Remove V0Driver(ToolsBase) and move generate_ui/refine_ui tool logic to @tool_function decorated methods on IInstance. Store apikey directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address CodeRabbit review feedback on tool_v0 node - Remove extraneous parentheses around cfg.get() in IGlobal.py - Add defensive JSON error handling for non-JSON API responses - Update tile label to generic "Tool: v0 UI Generation" - Add 'error' field to both tool output schemas - Remove raw response body from HTTP error logging Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: format JSON file * fix(nodes): return schema-shaped errors and redact log payloads in tool_v0 Address CodeRabbit review feedback on the v0 by Vercel tool node: - generate_ui and refine_ui now wrap _call_v0_api/_extract_code in try/except and return {success: False, error: ...} on transport or parse failures, so downstream nodes can branch on failure instead of seeing raised exceptions. Argument validation also returns the same shape rather than raising ValueError. - _normalize_tool_input no longer logs the raw input repr when given an unexpected type; prompts, prior messages, and generated code are now redacted from server logs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(nodes): narrow tool_v0 exception types per reviewer feedback Replace broad `except Exception` in generate_ui and refine_ui with `except (httpx.HTTPError, ValueError, json.JSONDecodeError)` so unexpected errors propagate rather than being silently swallowed. The internal _call_v0_api handler is intentionally left broad as it logs and re-raises. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(nodes): add unit tests for tool_v0 IInstance pure-logic helpers Covers _normalize_tool_input, _extract_code, generate_ui, and refine_ui with rocketlib stubbed via sys.modules to avoid runtime dependencies. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(nodes): patch tool_v0 module warning attr directly for CI environment The tests stubbed rocketlib via sys.modules.setdefault, but on CI the real rocketlib is already loaded into sys.modules so the stub is a no-op. The production code does `from rocketlib import warning` which binds the name at import time, so the IInstance module ends up with a reference to the engine's real logger and never appends to _WARNING_CALLS. Override _mod.warning directly after loading IInstance — patches the actual reference _normalize_tool_input uses, independent of rocketlib's state in sys.modules. Fixes test_non_dict_type_logs_type_name_only and test_non_dict_list_logs_type_name_only failing inside the engine pytest runner on Build / Ubuntu / macOS / Windows. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(tool_v0): address review feedback - raise ValueError/RuntimeError instead of returning {success:False,error} dicts; drop the try/except wrappers so framework sees real failures (asclearuc: match tool_firecrawl/memory_internal pattern) - require prior_messages in refine_ui so a stateless v0 endpoint can't silently produce an unrelated component - surface the v0 API error payload in the no-code RuntimeError - shallow-copy tool input so security_context strip never mutates the caller-owned args dict - drop now-unused 'error' output_schema field * feat(tool_v0): add co-located vercel.svg icon (#926 convention) * fix(tool_v0): target v0 Platform API, use shared tool utils Address asclearuc's PR #557 review: - API contract: the node POSTed to /v1/chat (OpenAI Model API shape) but parsed an OpenAI choices[] response. Switch to the v0 Platform API: generate_ui -> POST /v1/chats {message}; refine_ui -> POST /v1/chats/{chat_id}/messages {message}. Parse the stateful chat object ({id, latestVersion: {demoUrl, files: [{name, content}]}}) into chat_id, code (primary file), files, and demo_url. Drop parent_message_id, message_id, prior_messages, and the model parameter (chats are stateful server-side, so no history replay). - Retries: replace the hand-rolled httpx client with ai.common.utils.post_with_retry (requests + tenacity), keeping the 120s timeout via kwarg. - Input handling: replace the local _normalize_tool_input with ai.common.utils.normalize_tool_input(tool_name='v0'). - requirements.txt: httpx -> requests; drop the depends() bootstrap from __init__.py to match the sibling tool nodes (tool_tavily, tool_exa_search). - vercel.svg: fill="#000" -> fill="currentColor" so the SVGO auto-currentcolor pipeline keeps the icon theme-adaptive. - tests: rewrite against the Platform API shape with a mocked post_with_retry covering success, the {"error": {...}} shape, empty files, transport errors (status-only logging), and non-JSON bodies. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(tool_v0): fix stub leak into shared pytest session, add coverage The test injected import stubs via sys.modules.setdefault('rocketlib', ...) and never removed them. When test_tool_v0 was collected before test_tool_tavily, v0's incomplete rocketlib stub leaked and tavily's collection failed with ImportError. Adopt tavily's install-then-pop pattern: inject only modules not already present, import, then remove exactly what was added (plus the private tool_v0 scaffolding). Also close coverage gaps: api-error prefers error.message over userMessage/code; refine_ui builds the URL from the input chat_id even when the response carries a different id; non-dict JSON payload raises "unexpected payload type"; Content-Type: application/json header. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Alexandru Sclearuc <asclearuc@gmail.com>
…InstanceBase (rocketride-org#599) * refactor(engine): replace ToolsBase driver classes with @tool_function decorators on IInstanceBase Every tool-providing node previously required two parallel classes: an IInstance (pipeline integration) and a ToolsBase driver (tool definitions). The driver implemented three abstract methods (_tool_query, _tool_validate, _tool_invoke) and the IInstance wired them together with boilerplate delegation in invoke(). This created a parallel system that was hard to understand and tedious to write — the driver often just called back into the instance for the actual work, and every node repeated the same delegation pattern. The root cause was that tool declaration was separate from the class that actually owned the state and connections needed to execute the tool. A MySQL node's IInstance had the database connection, the LLM access, and the lane handlers — but its tool definitions lived in a MySQLDriver class that had to reach back into the instance for everything. This commit collapses both layers into one by adding @invoke_function and @tool_function decorators directly to IInstanceBase in rocketlib/filters.py. Any IInstanceBase subclass can now declare tool entry points with a decorator — the method name becomes the tool ID, the decorator carries the schema and description, and the base class invoke() dispatches automatically. No separate driver class, no factory method, no delegation. Usage example — static tool: from rocketlib import IInstanceBase, tool_function class IInstance(IInstanceBase): IGlobal: IGlobal @tool_function( input_schema={ 'type': 'object', 'required': ['url', 'method'], 'properties': { 'url': {'type': 'string'}, 'method': {'type': 'string', 'enum': ['GET', 'POST']}, }, }, description='Make an HTTP request.', ) def http_request(self, args): if args['method'] not in self.IGlobal.enabled_methods: raise ValueError('Method not allowed') return execute_request(url=args['url'], method=args['method']) Usage example — dynamic description from config: class DatabaseInstanceBase(IInstanceBase): @tool_function( input_schema={...}, description=lambda self: ( f'Query the {self._db_display_name()} database. ' f'Just describe what data you need.' ), ) def get_data(self, args): ... Usage example — dynamic tools (MCP, tools discovered at runtime): class IInstance(IInstanceBase): def _tool_query_dynamic(self): return self.IGlobal.list_namespaced_tools() def _tool_invoke_dynamic(self, *, tool_name, input_obj): server, bare = tool_name.split('.', 1) return self.IGlobal.call_tool(server, bare, input_obj) The decorator system follows the existing control/invoke layering: control() <- engine entry point, rarely overridden └─ invoke() <- dispatches on param.op ├─ tool.* -> @tool_function methods (tool.query builds | descriptors, tool.invoke calls the method) └─ other ops -> @invoke_function methods (op name = method name) Key design decisions: - Decorators live in rocketlib/filters.py with zero upstream dependencies. The declaration plumbing (ToolDescriptor, @tool_function, @invoke_function, dispatch logic) is entirely self-contained in the engine base layer. - No tool name prefix. Tool IDs are bare method names (e.g. 'get_data', not 'mysql.get_data'). The agent host already namespaces by nodeId to prevent collisions between multiple nodes of the same type. - No separate validation step. tool.validate is removed from the dispatch. Validation is guard clauses at the top of the function body — simpler, more obvious, impossible to forget. - Decorator parameters accept static values or callables. Roughly half of all tools need runtime config in their descriptions (e.g. the user-entered database description, allowed import lists, display names). These use lambda self: ... which is resolved at tool.query time when self.IGlobal is available. This is a first-class pattern, not an escape hatch. - User-entered tool descriptions are auto-prepended. The "tool" field from the node config (e.g. "This is a database of world cities") is read via _tool_config_description() and prepended to every @tool_function's description automatically. Individual decorators only provide the fixed part. - Dynamic tools (MCP) use _tool_query_dynamic / _tool_invoke_dynamic overrides on IInstanceBase for tools discovered at runtime from external servers. Only MCP needs this. - Backward compatible with the agent-as-tool pattern. The four agent nodes still use _AgentAsToolProvider via ToolsBase — they are not tool nodes in the decorator sense, they use a different mechanism for exposing themselves as tools to other agents. Migrated nodes: - chart_chartjs: generate_chart (also eliminated the set_llm_invoker callback — IInstance calls self.instance.invoke('llm', ...) directly) - tool_python: execute - tool_http_request: http_request - tool_firecrawl: scrape_url, map_url - memory_internal: put, get, list, clear - db_mysql, db_postgres: get_data, get_schema, get_sql (via DatabaseInstanceBase with callable descriptors for display names) - db_neo4j: get_data, get_schema, get_cypher - mcp_client: dynamic tools via _tool_query_dynamic/_tool_invoke_dynamic Deleted (11 files, ~1600 lines): - All *_driver.py files (http, python, firecrawl, chartjs, memory, mcp, mysql, postgres, neo4j) - packages/ai/src/ai/common/database/db_driver_base.py - DatabaseDriverBase removed from database __init__.py exports Updated imports: - Agent framework drivers (langchain, crewai, deepagent) and AgentBase now use ToolDescriptor from rocketlib instead of ToolsBase.ToolDescriptor Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): fix tool schema key mismatch, harden node implementations The @tool_function decorator builds ToolDescriptors with camelCase keys (inputSchema, outputSchema) but three of the four agent drivers were reading snake_case (input_schema), silently getting None for every tool's parameter schema. The LLM never saw real parameter definitions — it always fell back to a generic "accept anything" schema. Tool schema fix (3 agent drivers) --- - agent_langchain: td.get('input_schema') → td.get('inputSchema') - agent_deepagent: td.get('input_schema') → td.get('inputSchema') - agent_crewai: already handled both with fallback; simplified to td.get('inputSchema') for consistency llm_base: replace manual dispatch with @invoke_function --- The manual match/case block in llm_base/IInstance.py duplicated what the base class invoke() auto-dispatcher already provides. Replaced with four @invoke_function decorated methods (ask, getContextLength, getOutputLength, getTokenCounter). Removed the now-unused IInvokeLLM import. Node hardening (from code review) --- - chart_chartjs: inverted ternary → idiomatic `description or "default"` - memory_internal: _store type MemoryStore → MemoryStore | None; put/get/ clear raise ValueError on non-dict args instead of silently coercing - tool_firecrawl: metadata.model_dump() exception now logged via warning; JSON parse catch narrowed to JSONDecodeError/TypeError with log - tool_http_request/IGlobal: mutable class-level set()/[] defaults → None; typing.Set/List → built-in set/list - tool_http_request/IInstance: str(body_json) fallback → json.dumps() so non-dict/list/str values produce valid JSON - tool_python/IGlobal: typing.Set → built-in set; removed unused imports - db_instance_base: int(raw_limit) wrapped in try/except, falls back to 250 on parse error instead of raising Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR review findings — input validation, lint, and hardening - langchain: fix ANN401/ARG002/UP037 on bind_tools signature - chart_chartjs: reject non-list/dict data, cap serialized payload at 20KB, validate and normalize LLM JSON output before wrapping in chartjs fence - llm_base: rename unused param → _param on invoke handlers (ARG002) - tool_firecrawl: simplify formats array → single format string, redact raw payload from warning log - tool_http_request: fail-fast validation on auth/body types and nested fields; fail-closed on malformed urlWhitelist in guardrails - tool_python: validate json.loads result is a list before iterating - memory_internal: enforce key type/presence in put/get/clear, add dict check to list handler - db_instance_base: add missing valid boolean to success/failure return dicts; fix stale _create_driver docstring → _db_display_name() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…overhaul (rocketride-org#670) * feat(shared-ui): persist canvas state, add isFlowReady, and centralize node loading Previously, viewport (zoom/pan), lock state, snap-to-grid, and editor mode were either not persisted at all or stored only in local preferences. On reload the canvas always reset to fitView at default zoom, losing the user's position. Additionally, ReactFlow timing was managed through scattered setTimeout/requestAnimationFrame workarounds with no unified signal for when nodes were measured and the canvas was ready for viewport operations. PipelineConfig schema (TypeScript + Python SDKs): - Added docRevision, isLocked, snapToGrid, snapGridSize, and editorMode to PipelineConfig so these fields travel with the .pipe file across all consumers. IProject now inherits them instead of declaring docRevision separately. isFlowReady state (FlowGraphContext): - Added an isFlowReady boolean state that tracks whether all nodes have been rendered and measured by ReactFlow. Transitions false→true when every node has measured.width, and true→false when unmeasured nodes appear (new node added, template instantiated, project loaded). - All effects that need measured nodes (viewport restoration, fitView, template post-processing) now depend on isFlowReady instead of using setTimeout(0) or requestAnimationFrame. loadCanvas centralization (FlowGraphContext): - Extracted a loadCanvas(nodes, edges) function that sets isLoadingRef, resets isFlowReady, and calls setNodes/setEdges. This is the single entry point for structural canvas changes. - loadData (project load) now delegates to loadCanvas for the node/edge work, then handles layout preference sync and viewport queueing. - addNode now uses loadCanvas instead of calling setNodes directly, so single-node additions get the same isFlowReady cycle and isLoadingRef guard as bulk loads. Viewport save/restore: - onToolchainUpdated now includes isLocked, snapToGrid, and snapGridSize from projectLayoutRef in the saved project, so layout prefs persist with the document. - onMoveEnd handler added to ReactFlow so viewport-only changes (zoom/pan without node edits) trigger a save via onToolchainUpdated. - On load, viewport is restored from project.viewport via a useEffect that fires when isFlowReady transitions to true. Falls back to fitView if no saved viewport exists. - Removed the fitView prop from ReactFlow — viewport is now always managed programmatically through the isFlowReady cycle. FlowPreferencesContext: - isLocked is now derived from projectLayout state instead of a separate useState, eliminating dual-state sync issues when loadData pushes layout prefs from the project document. useTemplateInstantiator simplification: - Replaced the two-phase measurement polling (pendingIds + needsFit + doneRef) with a single useEffect gated on isFlowReady. When isFlowReady becomes true and pendingIds exist, it updates internals, notifies the host, and calls fitView. - Template instantiation now uses loadCanvas instead of calling setNodes/setEdges directly, getting the same isLoadingRef guard and isFlowReady cycle. addNode positioning: - When no position is specified (accordion/create panel), addNode now finds a non-overlapping spot by starting at viewport center and shifting down until clear of existing nodes, matching the quick-add popup behavior. EmptyCanvasPrompt: - Only shown when nodes.length === 0 AND isFlowReady is true, preventing the brief flash of the "Select your starting point" dialog while a project's components are still loading into nodes. - Fixed React style warnings by replacing border shorthand with longhand properties (borderWidth/borderStyle/borderColor) in item and templateItem styles to avoid conflicts with conditional borderColor overrides. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): use spiral search for non-overlapping node placement Replace the downward-only linear search with a spiral pattern that searches outward from the viewport center, finding the nearest available slot in all directions. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): decompose monolithic flow module into modular ProjectView architecture Restructure the shared-ui package from a single monolithic `modules/flow/` canvas module into a composable, multi-view project architecture. The canvas editor is relocated, five new standalone view components are introduced, and a new ProjectView orchestration module ties them together behind a redesigned TabPanel. === CANVAS RELOCATION === Move the entire ReactFlow-based pipeline canvas editor from `modules/flow/` to `components/canvas/`. The internal directory structure is preserved verbatim (components/, context/, hooks/, templates/, util/, types.ts, theme.ts). The barrel export in `src/index.tsx` is updated to re-export `Canvas` and `IFlowProps` from the new path. No functional changes to the canvas itself. Files moved (92 files): modules/flow/** → components/canvas/** === NEW MODULE: ProjectView (modules/project/) === Add a top-level orchestration component that composes the canvas editor and all runtime views (Status, Tokens, Flow, Trace, Errors) into a unified project frame with a shared TabPanel. - ProjectView.tsx (229 lines): Wires up lazy-loaded tab content via React.lazy + Suspense, manages active tab state, and delegates host↔view communication through typed callback props. - types.ts (131 lines): Defines the complete message protocol for host↔view communication, split into per-component message pairs: • CanvasIncoming / CanvasOutgoing • StatusIncoming / StatusOutgoing • TraceIncoming / TraceOutgoing Composed into aggregate types: • ProjectViewIncoming — all messages the host can send • ProjectViewOutgoing — all messages the view can emit Also defines ProjectViewMode, IProjectViewProps, and IViewProps. - hooks/useTraceState.ts (274 lines): Incrementally processes an array of TraceEvent objects (begin/enter/leave/end ops) into a flat list of TraceRow objects for the trace viewer. Maintains document map, slot bindings, and pending call stacks via refs. Supports reset detection when the event array shrinks. Caps retained documents at 64. - hooks/useElapsedTimer.ts (85 lines): Returns a live-updating elapsed-seconds counter while a pipeline task is in the RUNNING state. Starts a 1-second interval on RUNNING, clears on completion/cancel/ unmount. === NEW VIEW COMPONENTS === All five new view components follow the established shared-ui conventions: plain React, inline CSSProperties style objects, --rr-* CSS custom property tokens, section divider comments, no MUI dependencies. 1. components/status/ (5 files, ~1,210 lines total) - Status.tsx: Completions chart and stats for a running pipeline. 1-second sampling interval, 600 data points (10 min history), automatic reset detection on pipeline restart. - StatusHeader.tsx: Header bar with pipeline state display and run/stop/restart action buttons. - StatusFooter.tsx: Footer with summary statistics row. - CompletionsChart.tsx: Canvas-based time-series chart rendering completions data with configurable time ranges. - types.ts: ChartStats, StatusDataPoint, TimeRange interfaces. 2. components/tokens/ (2 files, ~160 lines) - Tokens.tsx: Token consumption metrics display with breakdown by resource type (CPU Usage, CPU Memory, GPU Memory), progress bars, and total count. 3. components/flow/ (2 files, ~217 lines) - Flow.tsx: Pipeline flow visualization with list/graph view toggle. Renders pipeline stage progression. 4. components/trace/ (3 files, ~1,514 lines) - Trace.tsx (1,255 lines): Pipeline call-tree viewer. Builds a tree from TraceRow data, groups by document/object, renders expandable tree nodes with elapsed time, status indicators (in-flight, error, completed), and a detail panel showing entry/exit data. - JsonTree.tsx (259 lines): Recursive JSON viewer for the trace detail panel. Supports configurable default expansion depth, collapsible object/array nodes, and syntax-colored primitives. 5. components/errors/ (2 files, ~234 lines) - Errors.tsx: Structured error/warning message parser and display. Parses "ErrorType*`message`*filepath:linenumber" format with graceful fallback for unstructured messages. === TABPANEL REDESIGN === Rewrite the TabPanel component with a new visual design and mounting strategy. Visual changes: - Tab bar: sliding underline indicator → centered pill-style segmented control with rounded container and brand-colored active segment. - Removed resize/scroll event listeners (indicator tracking no longer needed). API changes: - Removed: `children` prop, `contentClassName` prop. - Added: `panels: Record<string, React.ReactNode>` prop — maps tab IDs to their content elements. Mount strategy change: - Old: Single `children` slot rendered unconditionally. - New: Panels render on first activation and stay mounted, with visibility toggled via `display: none`. This avoids re-mounting components like ReactFlow that require measured containers for correct initialization, while preventing premature mounting of panels that have never been visited. - Internal `activated` Set tracks which tabs have been shown at least once. Style migration: - Deleted tab-panel.css (85 lines of class-based styles). - All styles moved to inline CSSProperties objects in TabPanel.tsx, consistent with the shared-ui convention. === BARREL EXPORT UPDATES (src/index.tsx) === - Canvas/IFlowProps: re-export path updated from `./modules/flow` to `./components/canvas`. - Added exports: ProjectView, IProjectViewProps, IViewProps, ProjectViewMode, ProjectViewIncoming, ProjectViewOutgoing, TaskStatus, TraceEvent. === DEPENDENCY ADDITIONS === - lucide-react ^0.540.0: Icon library added to shared-ui (pnpm-lock.yaml updated). === DELETIONS === - modules/flow/ (92 files, ~14,058 lines): Entire legacy module removed. All canvas functionality is preserved in components/canvas/. The MUI-dependent top-level Flow.tsx wrapper in modules/flow/ is superseded by the new components/canvas/Canvas.tsx (which retains MUI for the ReactFlow integration) and by ProjectView (which is MUI-free). - components/tab-panel/tab-panel.css (85 lines): Superseded by inline styles in the rewritten TabPanel.tsx. Net change: 98 files changed, ~101 insertions, ~14,159 deletions (large deletion count reflects the modules/flow/ removal; equivalent code exists in the new components/canvas/ untracked directory). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): unify tab bars, add StatusHeader with Run/Stop, remove vscode.css from components Rework shared-ui tab bars, status header, and theme CSS loading: - TabPanel: simplify to mount-only-active-panel (unmounts on tab switch), remove activated-set tracking and display:none toggling, add pill-style badge support with active/inactive styling via color-mix tokens - StatusHeader: consolidate into a full two-column header bar with state indicator (dot + Running/Offline/etc), status subtitle, Run/Stop button with state-aware variants (run/stop/disabled), and elapsed timer — all self-contained with no layout responsibility on the parent - Status: integrate StatusHeader directly, accept onPipelineAction prop, remove need for parent to compose header layout - ServerMonitor: replace custom CSS tab bar and header with shared TabPanel component, remove sm-header/sm-tab-bar/sm-tab CSS classes - ProjectView: remove lazy loading and Suspense wrappers (panels now mount/unmount with tab switches), remove redundant layout styles and control button logic (now in StatusHeader), add empty state for Tokens panel - Theme: remove rocketride-vscode.css imports from ProjectView, ServerMonitor, and FlowCanvas (web app uses rocketride-default.css + JSON themes via applyTheme, VS Code extension loads vscode.css separately). Add fallback values to rocketride-vscode.css for --rr-bg-button, --rr-fg-button, --rr-font-family, --rr-font-family-widget - Barrel exports: add DashboardResponse, ActivityEvent and related dashboard types to shared-ui index.tsx Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: unify VSCode + shared-ui architecture with ref-based ProjectView - Merge PageEditorProvider + PageStatusProvider into PageProjectProvider - ProjectView owns all state via useImperativeHandle ref API - Stateless message bridges in both VSCode and rocket-ui - Multi-source status panes (one per source, sorted A-Z) - Canvas toolbar via context (CanvasToolbarContext) - Rename PageDashboard -> PageMonitor across VSCode extension - Inline styles with --rr-* tokens, delete all per-view CSS files - Add tabContent common style, readTheme utility - Add chart.js as shared-ui peer dependency - Remove applyDefaults from shared-ui components (theme owned by host) - Fix ActivityBar theme message type mismatch for iframes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): cache theme tokens, notify host on canvas content change Cache applied theme tokens in applyTheme.ts for reliable readTheme(), update ProjectView to sync project state on content changes, and notify host immediately when nodes are added via FlowGraphContext. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): overlay tab bar, floating canvas toolbar, workspace state persistence - TabPanel: absolute-positioned transparent overlay with centered pills, pointer-events passthrough so canvas is interactive underneath - FloatingToolbar: restored as draggable bar on canvas, switches between horizontal/vertical based on cursor proximity to parent edges - ProjectView: wire getPreference/setPreference to workspace state for toolbar position persistence, restore state on initialState arrival - Remove CanvasToolbarContext (dead code — toolbar no longer in tab bar) - Default node name from service catalog title on addNode - tabContent padding clears the overlay tab bar Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: migrate DAP to SDK, strongly type APIs, document/view/prefs state model SDK changes (TypeScript + Python): - Add ServiceDefinition, ServicesResponse, ValidationResult, ValidationError types - Strongly type getDashboard() → DashboardResponse, getServices() → ServicesResponse, getService() → ServiceDefinition, validate() → ValidationResult - Add name parameter to use(), add restart() and getTaskToken() methods - Add setEnv()/set_env() for runtime env variable updates - Add addMonitor/removeMonitor with reference counting and auto-resubscribe VS Code extension: - Replace all raw DAP commands with SDK methods (use, terminate, getTaskToken, getDashboard, getServices, restart, connect+ping for test connections) - Remove ConnectionManager.request() and monitor-manager.ts - Remove substituteEnvVariables — SDK handles env substitution via setEnv() - Pass env to client at creation, sync on onEnvVarsChanged - Split project:stateChange into project:viewStateChange + project:prefsChange - Send project:initialState + project:initialPrefs before canvas:update on ready shared-ui: - Split ProjectView state into viewState (mode, flowViewMode) and prefs (toolbar etc.) - Gate rendering on viewState and prefs being received (eliminates flash) - Export ViewState type from project module - FloatingToolbar: use visibility:hidden when parent has 0 dimensions - FloatingToolbar: skip ResizeObserver callbacks for hidden parents Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: project:load atomic message, viewport/layout state, dark mode fixes, dirty tracking State architecture: - Add project:load message — sends project, viewState, prefs, services, isConnected, and statuses in one atomic message (eliminates flash) - Add ViewState.viewport — viewport persisted per-view, not in pipeline - Add layouts (per-document defaults) — new views inherit from last layout - VS Code: use webview getState()/setState() for per-document state, rocketride.layouts in workspaceState for defaults - Add onViewportChange callback threaded through Canvas → FlowProvider → FlowProjectContext → FlowCanvas (replaces prefs-based viewport storage) Dirty tracking fixes: - Strip ui.measured from getComponentFromNode — computed field no longer dirties document on initial render - Remove viewport from onContentUpdated/addNode project output — viewport is view state, not document content - Remove onMoveEnd → onContentUpdated — panning/zooming no longer dirties - Fix template instantiation: call onContentChanged directly instead of onContentUpdated (was blocked by isLoadingRef race condition) Canvas improvements: - Rename onToolchainUpdated → onContentUpdated across all canvas files - Dark mode: detect via data-vscode-theme-kind body attribute in getMuiTheme - Dark mode: sync --icon-filter on body when theme changes - Dark mode: CSS-only --icon-filter rules for vscode-dark/high-contrast - Dark mode: theme-aware edge stroke colors via --xy-edge-stroke - Dark mode: icon filter on create-node panel sidebar icons - Fix gear icon fill override in NodeHeader (conditional spread) - Fix MoreMenu icon color (explicit --rr-text-secondary) - Edge delete button: use --rr-bg-paper background with --rr-text-secondary Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): remove debug component log from ProjectView Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): stop icon Square, PipelineActions on Status tab, remove metrics bg - RunButton: swap StopCircle for Square icon with transparent fill - StatusHeader: add extraActions slot, render PipelineActions (Chat now / Endpoint Info) - Status: remove background from Performance Metrics header - ProjectView: pass taskStatuses to Canvas, import PipelineActions for SourceStatusPane Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: wire onOpenLink end-to-end, serverHost, fix EndpointInfoModal tabs - ProjectView: add handleOpenLink callback, pass onOpenLink + serverHost to Canvas and SourceStatusPane PipelineActions - types: add project:openLink to ProjectViewOutgoing, serverHost to load msg - PageProjectProvider: handle project:openLink with full WebviewPanel bridge (theme, clipboard, drag-drop), send serverHost in project:load - EndpointInfoModal: replace overlay TabPanel with inline toggleButtons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): per-source Flow panes, parsed error messages in NodeStatus - Flow: extract SourceFlowContent for single-source rendering - ProjectView: render per-source SourceFlowPane (matches Tokens pattern), remove pickActiveStatus, clean up unused imports - NodeStatus: parse structured error format (Type*message*path), wrap instead of truncate, bold error type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: simplify project API — plain name string, strongly typed PipelineConfig Client SDK project methods now take a plain file name string instead of an options object, and use PipelineConfig types instead of Record<string, any>. TypeScript: - saveProject(name, pipeline: PipelineConfig) - getProject(name): PipelineConfig - deleteProject(name) Python: - save_project(name, pipeline: PipelineConfig) - get_project(name) -> PipelineConfig - delete_project(name) The name parameter is the file name on disk (e.g. "my-chat"), not the pipeline's UUID. The UUID (project_id) lives inside the pipeline JSON and is used for identity tracking, not file storage. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(shared-ui): remove duplicate theme JSON files Theme JSON files are served from rocket-ui's public/themes/ at runtime. The shared-ui copies were unused — fetchAndApplyTheme() fetches from the host's /themes/ endpoint, not from the shared-ui package. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): stop viewport/source leaking into pipeline, simplify RunButton Root cause: ProjectView injected viewState.viewport into the project object before passing to Canvas. This caused viewport and source to leak through onContentChanged, marking documents dirty on every pan/zoom or Play click. Fixes: - Pass viewport as separate initialViewport prop through Canvas → FlowContainer → FlowProvider → FlowProjectContext → FlowGraphContext - Remove viewport injection hack from ProjectView - RunButton: remove source injection from project (source passed separately via status:pipelineAction message) - handleRunPipeline: stop sending canvas:contentChanged on Play (pressing Play doesn't edit content) - RunButton: remove isPending state entirely (host may cancel via save dialog; pending spinner would get stuck) - RunButton: remove label spans, icon-only (Run/Stop/Stopping) - Run and Stop buttons now same hover width (3.5rem) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: per-source trace panes, flow event types, UI style consolidation Wire source field through flow events end-to-end (task engine → vscode provider → shared-ui) so trace and flow tabs can show per-source panes. Add TaskEventFlow / TASK_EVENT_FLOW types to TS and Python SDKs, remove unused EVENT_STATUS_UPDATE export. Move useTraceState processing into useEffect for React 18 Strict Mode compatibility. Consolidate card/header styles via commonStyles, simplify node header CSS to use surface-alt tokens, and add rocketride theme. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): collapsible trace call tree with lane-typed renderers Major refactor of the Trace component for the pipeline trace viewer. Call tree structure: - Each enter/leave pair renders as a single collapsible row (▸/▾) - Expanded: Input data box → children → Output data box (no ENTER/LEAVE rows) - Structural nesting via CSS margin-left + border-left - Batching of identical consecutive siblings with "N more..." progressive reveal - Inline detail panel under expanded nodes (not side panel) Lane-typed renderers (new renderers/ directory): - render_question: displays question text, history, instructions, examples, goals - render_answer: displays answer text with word count, token usage cards - render_document: displays content, metadata (source, objectId, chunk) - render_text: displays text with char/word count - render_video: displays action (Begin/Write/End), buffer size, mimeType - render_audio: displays format, duration, sample rate, channels (or stream action) - render_image: displays format, dimensions, file size (or stream action) - render_table: parses markdown tables and renders as HTML table - Each renderer has: TypeScript type guard (isX), summary function, render function - Dispatch by lane name, validated by type guard Data view modes: [Tree] [JSON] [Raw] toggle buttons - Tree: lane-typed renderer (falls back to JSON if no renderer matches) - JSON: JsonTree with defaultExpanded=2 - Raw: JSON.stringify compact string Other changes: - Removed side detail panel and resize handle - Removed "Trace" header and Clear button (handled by parent) - Lane colors for all lanes including image, table - Lane display names: tags→data, closing→flush - Explicit rgba backgrounds for lane badges (no color-mix) - useTraceState moved to useEffect (fixes React 18 Strict Mode) - Flow events forwarded with source field for per-source filtering - Removed unused helpers (findNodeById, collectVisibleNodes, etc.) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(shared-ui): restore titleBar colors for node headers, cardHeader consistency - Node headers: restore --rr-bg-titleBar-inactive/active with hover/selected transitions (was incorrectly changed to surface-alt which had insufficient contrast in dark themes) - cardHeader: use --rr-bg-titleBar-inactive instead of --rr-bg-surface-alt for consistency with canvas node headers across all panel headers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): trace viewer theme cleanup, UX polish, component name resolution - Replace all made-up CSS variables (--rr-font-mono, --rr-border-subtle, --rr-bg-surface, etc.) with declared --rr-* tokens from theme files - Add --rr-chart-* lane colours and --rr-annotation-bg-default to rocketride-vscode.css - Remove ~30 unused styles, dead selection state, and stale props - Resolve component IDs to display names via pipeline lookup map - Show recursive call counts on every level including object groups - Muted styling for empty pass-through nodes - Smart Data/JSON/Raw toggle: default to Data when a typed renderer exists, hide Data option otherwise - Move result status to output box with collapsed/expanded display - Square left corners on inline data boxes - Fix documents renderer to handle arrays, not just single objects - Remove redundant Node/Called by/Lane fields from input box - Add left/right padding to rendered data content Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui, rocketlib): invoke lane renderer + IInvoke computed type field Add @computed_field `type` to IInvoke so trace events carry the Python class name (IInvokeLLM, IInvokeTool, etc.) for dispatch. New invoke lane renderer handles LLM asks, tool discovery/invoke/validate with type-specific detail views. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(rocketlib, shared-ui): invoke type hierarchy refactor, IInvokeOp, IInvokeMemory Python (rocketlib): - Add IInvokeOp base class with computed type via __qualname__ (e.g. "IInvokeLLM.Ask") and lane field for routing - IInvokeLLM: pure namespace with nested Ask, GetContextLength, GetOutputLength, GetTokenCounter operation classes - IInvokeTool: migrate nested classes to IInvokeOp, add lane - IInvokeMemory: new type deriving from IInvokeTool with Put, Get, List, Clear operations backed by tool dispatch - IInvoke: remove computed_field type (envelope only) - instance.invoke(): takes single param, reads param.lane for routing, component_id replaces classType+nodeId - Driver control(): unpacks control.param instead of *control.args Callers (host.py, 12 node files): - IInvokeLLM(op='ask', question=q) → IInvokeLLM.Ask(question=q) - instance.invoke('llm', param, nodeId=x) → instance.invoke(param, component_id=x) - Memory class uses IInvokeMemory.Put/Get/List/Clear Frontend (shared-ui): - Invoke renderer dispatches on param.type split ("IInvokeLLM.Ask" → category + operation) via lookup tables - Add IInvokeMemory renderer - Remove redundant input/output/result from tool/memory Data views - Add RS.sectionContent for consistent label→content indentation - Apply sectionContent to question and invoke renderers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): split trace renderers into input/output, diff view, collapsible sections - Split InlineDataBox into InputDataBox and OutputDataBox - InputDataBox: call info, typed Data renderer per lane - OutputDataBox: DiffView by default, invoke-specific overrides - When entryData === exitData: single "Data" box, no Output - New utils.ts: traceDataEqual, diffObjects (10-entry cap, shallow per change), DiffView component, CollapsibleSection component - Split index.tsx: renderTraceInput/Output, summaryTraceInput/Output - Default output renderer: DiffView showing adds/changes/deletes - Invoke output: table-driven dispatch (LLM Ask shows Answer) - Invoke renderer improvements: - LLM Ask input: Goal, Question always visible; Instructions, Context, History collapsed by default via CollapsibleSection - LLM Ask output: renders Answer (string or JSON) from result - Memory input: shows Operation, Key, Value - Memory output: shows Status, Key, returned Value - Remove OP_LABELS map, show raw op values - Remove renderExtras, unknown types get JSON/Raw only - Instruction text blocks get yellow left border - Goal before Question in field order - Consistent RS.sectionContent indentation across all renderers (answer, text, document, invoke) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): shared question/answer formatters, result footer, robust trace stack - Extract format_question/format_answer so render_question, render_answer and render_invoke (LLM Ask) share one renderer - Add ResultFooter showing OK/Error/Skip/PreventDefault at the bottom of each expanded call - Shift/Ctrl-click a call header to expand or collapse the whole subtree - IInvokeCrew renderer + summarizer; Tool Query output lists discovered tools - useElapsedTimer now ticks during INITIALIZING as well as RUNNING - useTraceState recovers from missing enter/leave events by aligning the pending stack and marking orphaned frames as errors Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(agent): refactor AgentBase to AgentContext seam, split CrewAI, fix DAP cross-client seq collision AGENT BASE REFACTOR — AgentContext + call_llm/call_tool adapters ---------------------------------------------------------------- Replace the old host: AgentHost + _bind_framework_* callback API with a clean AgentContext dataclass and three host adapters on AgentBase: call_llm, call_llm_json, call_tool. The driver _run signature changes from (agent_input, host, ctx) to (*, context, question). AgentInput is deleted; its run metadata moves onto AgentContext and the Question travels alongside as a separate parameter. The two abstract _bind_framework_llm / _bind_framework_tools methods are removed — each driver now defines plain module-level builder functions (e.g. _build_langchain_llm(agent_base, context), _build_deepagent_tools(agent_base, context, descriptors)) that close over agent_base and context directly. _internal/agent_tool.py is removed entirely; agent-as-tool is now declared per IInstance as a @tool_function def run_agent(self, input_obj) using the shared AGENT_TOOL_INPUT_SCHEMA / AGENT_TOOL_OUTPUT_SCHEMA exported from ai.common.agent.types. AgentBase.run_agent now lazy-builds AgentHostServices once per IInstance and caches it on iInstance._agent_host. Tool discovery (one engine invoke per connected tool node) happens once at first question instead of on every question. A new REQUIRES_MEMORY class flag lets drivers declare a memory dependency that run_agent enforces at first question. sendSSE now takes context as an explicit parameter and reads the invoker from there instead of from self._invoker. The _invoker and _host instance attributes on AgentBase are gone. All engine envelope construction (IInvokeLLM.Ask(...)) lives inside call_llm / call_llm_json. Drivers never touch IInvokeLLM directly. call_llm accepts a polymorphic prompt that is either a pre-built Question (used by drivers like rocketride that build structured prompts) or framework-native messages that get flattened to a transcript. AgentHostServices.Tools exposes a prepared flat list: List[ToolDescriptor] built once at construction. Drivers read context.tools.list directly and the old discover_tools helper is gone. The class also drops the leaky class-level _tool_nodes / _tool_list attributes that would have been shared across instances and silently leaked descriptors between concurrent agent runs. Tools.invoke(tool_name, args) is renamed from (tool_name, input) to make it explicit that it takes a clean dict — framework-shape conversion is the driver wrapper's job, not the host's. Why: the old _bind_framework_* methods existed only to receive callbacks (call_llm, invoke_tool, log_tool_call) that the driver would then capture in its inner LangChain / CrewAI subclasses. Every driver wrote the same closure boilerplate around the same shims. Passing agent_base and context directly to module-level builder functions lets the inner classes close over them naturally — the entire indirection layer disappears, and the resulting drivers are dramatically smaller (deepagent loses ~280 lines). AgentInput was a half-honest wrapper: it carried a Question plus run metadata, but the question and the metadata have completely different lifecycles. Run metadata is per-call scaffolding (immutable, threadsafe, shared across reentrant call_llm chains); a question is the actual unit of work and changes meaning every time a framework loop synthesizes a new one from messages. Splitting them into AgentContext (frozen dataclass) + a separate question parameter is structurally honest and makes reentrancy safe. self._invoker was a latent concurrency bug. Two concurrent run_agent calls on the same IInstance would race to set self._invoker, and SSE events from one call could be routed to the other call's pipe. Reading the invoker from context instead means each call has its own immutable binding. Same reasoning for self._host. Lazy host construction per IInstance fixes a real performance pothole. Tool discovery does N engine invokes per connected tool node. Rebuilding the host on every question multiplied that cost by question rate — and worse, the discovered descriptors were thrown away after each question. Caching on iInstance._agent_host discovers once and reuses forever. Centralizing IInvokeLLM construction in call_llm means engine type changes (like the IInvokeLLM(op=ask,...) to IInvokeLLM.Ask(...) factory pattern) only need to land in one place. Drivers don't need co-ordinated updates. Replacing the bespoke agent-as-tool path with @tool_function def run_agent unifies the surface with the @tool_function decorator pattern from rocketride-org#599. The old handle_agent_tool_invoke / _AgentAsToolProvider branch was a parallel system that did the same thing the decorator does — it existed because @tool_function post-dated the original agent base. Now that the decorator exists, the parallel system is dead code. CREWAI SPLIT — three node types out of one package --------------------------------------------------- The single agent_crewai node becomes three logical nodes, each registered via its own services.*.json and living in its own sub-package: - crewai_agent — standalone single-agent node, also exposed as a run_agent tool. classType: [agent, tool]. - crewai_subagent — managed sub-agent. No questions lane. Can only be wired into a Manager via the crewai lane. classType: [crewai]. - crewai_manager — hierarchical multi-agent delegator. Fans out describe on the crewai lane to connected subagents, assembles a Crew, runs CrewAI hierarchical process. classType: [agent, tool]. Shared framework code lives at the package root: crewai_base.py (the CrewBase(AgentBase) shared base with _build_crew_llm / _build_crew_tools), crewai_runner.py, crewai_listener.py, plus the shared requirements.txt. The package no longer exports IInstance / IGlobal; the engine loads each sub-package via the path field in its services manifest. The crew control-plane op renames from crewai.describe to bare describe on lane crewai, and IInvokeCrew.Describe now extends IInvokeOp (with lane = crewai) instead of plain BaseModel. IInvokeCrew.DescribeResponse is no longer an IInvokeOp — it is a value object that travels inside a Describe response, not an op that gets dispatched. The trace renderer (render_invoke.tsx) is updated to display the new op name. Why: the original single agent_crewai node tried to be both a standalone agent and the orchestrator depending on which lanes were connected. There was no way to validate the combinations: nothing stopped someone from running a subagent standalone, or wiring a manager without subagents. The behavior was implicit in connection topology, which means errors only surfaced at runtime and only with confusing symptoms. Splitting the role into three explicit node types makes the constraints declarative in the services manifest. Subagents have no questions lane and literally cannot be invoked directly. Managers require at least one crewai lane connection. The engine normal lane validation now catches misuse before pipeline start. Cross-Manager nesting (one Crew calling into another Crew as a black box) still works — but now it is via the tool.run_agent path (the agent-as-tool surface), not by overloading the crewai lane. That keeps the crewai lane semantics clean: it is the manager/subagent fan-out channel, nothing else. The op rename matches the @invoke_function decorator dispatch convention landed in rocketride-org#599: bare op names route to def describe(self, ...) methods on the receiving IInstance. Keeping the old crewai.describe form would have forced a special case in the dispatcher. DAP CROSS-CLIENT SEQ COLLISION — two clients, one task ------------------------------------------------------- Task._send_data now constructs a fresh outbound DAP packet via _data_client.dap_request(command=..., arguments=..., token=...) instead of forwarding the inbound dict verbatim. DataCommands.handle_data wraps the subprocess response in a fresh build_response(request, body=...) keyed off the inbound request. New tests in both RocketRideClient_test.py and RocketRideClient.test.ts exercise the path: two independent clients sharing one task via useExisting, sending concurrently. Why: two independent client connections that share a task (via useExisting) each have their own DAP seq counter. They can independently issue overlapping seqs — both clients can reach seq=4 within milliseconds of each other. Eaas multiplexes both into one outbound _data_client to the subprocess. If we forwarded the inbound dict verbatim, the colliding seqs would clobber each other in _data_client._pending_requests: the second future overwrites the first, the first response gets dropped, and the originating client hangs forever waiting for a reply that already came back to the wrong slot. Building a fresh outbound packet via dap_request allocates a unique seq from _data_client._next_seq() so each outbound message has its own correlation slot. Rebuilding the response envelope via build_response ensures the inbound DAPConn sees its original request_seq so it can correlate the response back to the originating client. This bug is invisible with one client because a single client has one monotonic seq counter — it never collides with itself. The single-client concurrent test in the same suite does NOT exercise the path. Two independent clients fanning into one task are the necessary precondition, which is exactly what the new tests reproduce. MISTRAL SDK 1.x / 2.x COMPATIBILITY ------------------------------------ llm_mistral/IGlobal.py, llm_mistral/mistral.py, and llm_vision_mistral/mistral_vision.py try from mistralai.client import Mistral (2.x layout) and fall back to from mistralai import Mistral (1.x). The >=2.0.0 constraint is dropped from both requirements.txt. The mistralai SDK reorganized its package layout between 1.x and 2.x. Pinning to 2.x broke installs in environments still on 1.x. The shim accepts whichever is installed without forcing an upgrade. INCIDENTAL FIT-AND-FINISH -------------------------- - PageProjectProvider.ts adds a clipboard bridge: webview iframes can post {type:requestPaste} / {type:copyText,text} and the extension host proxies to vscode.env.clipboard.read/writeText. VSCode intercepts native paste at the Electron layer, so embedded iframes cannot read the OS clipboard themselves. - task_engine.py adds debug(output_message) on subprocess output events so traces capture the same payload that gets appended to _status_trace. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(vscode, shared-ui): persistent client, virtualized managers, disconnect overlay Refactor ConnectionManager to use a single persistent RocketRideClient (persist: true) that survives across connect/disconnect cycles. The SDK's _resubscribeAllMonitors() now correctly replays monitor subscriptions on every reconnect — fixing the bug where Server Monitor showed 0 MONITORS after a disconnect/reconnect. Backend lifecycle virtualized behind BaseManager with two concrete implementations: - LocalManager: composes EngineManager, connect with retries for engine startup race - RemoteManager: credential validation + direct connect Removed CloudManager (no-op stub), all retry/backoff logic from ConnectionManager (SDK handles it), isMonitoring flag from PageProjectProvider (SDK tracks via _monitorKeys). Disconnect overlay added to ProjectView and ServerMonitor — semi-opaque with blur, showing [ Disconnected ] over the existing content. On reconnect, statusMap/traceEvents/cachedStatuses are cleared for a fresh start. Status chart pauses while disconnected and resets on reconnect. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui, vscode, server, clients): pipeline result display, toolbar orientation context, icon standardization, connect dedup, engine EventEmitter Pipeline result end-to-end: - pipe.instance.cpp: gate BEGIN/END debug events on PIPELINE_TRACE_LEVEL::METADATA and serialize the pipe response into the END event at SUMMARY level — previously always emitted "{}" unconditionally, so the final result never reached the UI - client-ts/python: add result/pipelineResult field to TaskEventFlow for op === 'end' - useTraceState: on op === 'end' inject a synthetic __result__ sentinel TraceRow so Trace.tsx can render it separately from the call tree - Trace.tsx: extract __result__ rows in buildObjectGroups, add collapsible ResultRow component (green header) rendered after the call tree via renderFinalSections - render_final.tsx (new): dispatches each result field through the existing per-type renderers (renderAnswer, renderDocument, etc.) via result_types map; falls back to JsonTree for unknown types - format_answer.tsx: render structured JSON answers via JsonTree instead of a plain text block Toolbar orientation context: - FloatingToolbar.tsx: expose ToolbarOrientationContext so toolbar button children can read horizontal/vertical orientation via useToolbarOrientation() without prop drilling; fix null guard on getRenderedPosition() before writing dragStart - toolbar/index.tsx: re-export useToolbarOrientation from barrel Icon standardization: - FitIcon, LockIcon, NoteIcon, TidyIcon, UnlockIcon, ZoomInIcon, ZoomOutIcon: replace verbose per-element SVG markup with compact single-path 24x24 BoxIcons-style paths; standardizes icon visual style and halves markup weight - FlowCanvas.tsx: replace lucide Undo2/Redo2/Move/BoxSelect/PlusSquare imports with inline BxIcon helpers using BoxIcons paths, consistent with the icon overhaul VSCode reliability fixes: - connection.ts: add connectPromise dedup guard — concurrent connect() calls (e.g. racing event handlers at startup) now share one in-flight promise instead of each spawning an independent _connect(), preventing double-initialization - engine-manager.ts: switch from BaseManager to Node.js EventEmitter — was already calling this.emit('terminated') but BaseManager didn't extend EventEmitter so events were silently dropped; capture child in a local var so exit/error handlers guard this.child === child before mutating state, preventing a race where a new start() replaces this.child before the old process's exit handler fires - PageProjectProvider.ts: re-key editorStates from document.uri to WebviewPanel — URI was wrong because the same document can open in multiple panels; fan status updates out to all panels for a project; filter apaevt_flow trace events by project_id so unrelated projects don't receive each other's traces; extract pipelineResult from op === 'end' trace body into its own field Client transport fix (ts + python): - Clear _transport on disconnect so the next connect() with a new URI always creates a fresh transport — reconnecting to a different URI was reusing the stale transport with the old URI baked in Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * UI/UX fixes for canvas nodes * fix rotate on stopping button, fix coloring on stop button (rocketride-org#667) * fix(vscode): pipeline submenu now opens canvas editor instead of JSON (rocketride-org#669) The openFile and createNewPipelineFile commands were passing 'rocketride.PageEditor' as the viewType to vscode.openWith, which is not registered. VSCode fell back to the default JSON text editor. Fixed both call sites to use the registered 'rocketride.PageProject' viewType. Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat(agent_deepagent): port hierarchical subagents to AgentBase/AgentContext (rocketride-org#668) Splits agent_deepagent into two node types under one parent folder, mirroring the agent_crewai layout: - agent_deepagent (deepagent_agent/) flexible: standalone or orchestrator - agent_deepagent_subagent (deepagent_subagent/) invoke-only, classType ["deepagent"] Driver changes: - DeepAgentDriver._collect_subagents fans out `describe` via getControllerNodeIds('deepagent') + per-node invoke(component_id=...), builds one AgentContext + LLM + tools per subagent, passes SubAgent records to create_deep_agent(subagents=...) - DeepAgentSubagentDriver adds describe() and a _run that raises as defense-in-depth (subagent has no questions lane) - _read_connconfig_values reads connConfig directly so form values the UI writes nested under the default-profile key (e.g. {"default": {...}}) are resolved correctly; Config.getNodeConfig left untouched - Helpers: _tool_args_schema (real JSON Schema for tool args_schema), _extract_first_json_object (tolerant balanced-brace parser), _compose_system_prompt (shared manager/subagent prompt composition) Rocketlib: - IInvokeDeepagent (Describe + DescribeResponse) alongside IInvokeCrew - Re-exported from rocketlib/__init__.py UX: - Advanced Mode boolean checkbox on both nodes — Normal shows Instructions only; Advanced swaps in Agent Description + System Prompt (main) or System Prompt (subagent, with Description always visible) - Subagent has no lanes/input sections, cannot be wired as a top-level pipeline agent or as a general tool Docs: - Per-subfolder README following agent_crewai convention - Deepagents library link corrected to github.com/langchain-ai/deepagents Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(agent): strip ReAct trace from CrewAI Manager result, chain task context (rocketride-org#666) * fix(agent): strip ReAct trace from CrewAI Manager result, chain task context Three fixes for hierarchical CrewAI result quality: 1. Add _strip_react_preamble() — in hierarchical mode result.raw and tasks_output[-1].raw often contain the full manager delegation trace (Thought/Action/Observation chain) rather than just the final answer. Strips to the last "Final Answer:" marker, or the last JSON block if the text looks like a ReAct trace, or returns '' for inline traces so garbage doesn't leak to the user. 2. Add context=list(sub_tasks) to each Task — without this, downstream sub-agents (word analyst, chart renderer) had no access to prior task outputs (e.g. the fetched Wikipedia text). CrewAI requires explicit context wiring for inter-task data flow. 3. Update result extraction to iterate tasks_output in reverse and take the first clean result, falling back to result.raw with the same stripping. Avoids returning the manager's full delegation trace. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * harden ReAct stripping, remove fragile context chaining * address CR comment * update doc string --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Rod.Christensen <rod.christensen@aparavi.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: ryan-t-christensen <ryan.christensen@rocketride.ai> Co-authored-by: dylan-savage <130109357+dylan-savage@users.noreply.github.com>
…ocketride-org#933) Closes the 9 mechanically-fixable Scorecard `PinnedDependenciesID` alerts on this repo. Mutable tag references (`@v4`, `:tag`) become immutable hash references; Dependabot will continue to bump the SHAs as new versions ship. GitHub Actions (7 alerts): sync-models.yml actions/checkout v4 → 34e1148... rocketride-org#599 actions/setup-python v5 → a26af69... rocketride-org#600 actions/cache v4 → 0057852... rocketride-org#601 peter-evans/create-pull-req. v7 → 22a9089... rocketride-org#602 discord-discussions.yml actions/checkout v4 → 34e1148... rocketride-org#644 discord-issues.yml actions/checkout v4 → 34e1148... rocketride-org#645 discord-pr.yml actions/checkout v4 → 34e1148... rocketride-org#646 Docker base images (2 alerts): docker/Dockerfile.engine ubuntu:jammy-20240808 → @sha256:adbb90115a21969d2fe6fa7f9af4253e16d45f8d4c1e930182610c4731962658 rocketride-org#561 docker/Dockerfile.mcp python:3.12-slim → @sha256:9d3abd9fc11d06998ccdbdd93b4dd49b5ad7d67fcbbc11c016eb0eb2c2194891 rocketride-org#471 Both digests are the OCI image index (multi-platform manifest list), so platform resolution still happens at build time. `jammy-20240808` is already a date-pinned snapshot tag; `3.12-slim` is a floating upstream tag and was pinned at the digest current as of 2026-05-20. The remaining 6 `PinnedDependenciesID` alerts (rocketride-org#465, rocketride-org#466, rocketride-org#467, rocketride-org#468, rocketride-org#472, rocketride-org#603) flag pip/npm install commands with already-exact version pins (`twine==6.1.0`, `@vscode/vsce@3.7.1`, `ovsx@0.10.9`, etc.). Scorecard wants `pip install --require-hashes` or lockfile-driven installs for these; the ergonomics of doing that for one-shot workflow installs (and for the `./client-python` local-path install in Dockerfile.mcp, which can't be hash-pinned at all) outweigh the incremental supply-chain hardening over an already-exact version constraint. Those alerts are being dismissed separately with "won't fix" + per-alert justification.
…org#524) * feat(nodes): add tool interface for vector DB operations Introduces a generic tool_vectordb node that exposes vector database operations (search, upsert, delete) as ToolsBase-compatible tools that LLM agents can invoke. The node works with multiple vector DB backends (Pinecone, ChromaDB, Qdrant) through the shared DocumentStoreBase interface, providing a unified tool abstraction for semantic search. Closes rocketride-org#442 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): use glb.connConfig instead of missing getConnConfig() IGlobalBase does not have getConnConfig() — that method is on IGlobalTransform. Use self.glb.connConfig which is the standard pattern for tool nodes (matches tool_http_request, tool_firecrawl). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): correct description to match supported backends Remove Weaviate and pgvector from services.json description since _BACKEND_MODULES only supports pinecone, chroma, and qdrant. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(shared-ui): add vectordb.svg node icon Database cylinder icon matching the 24px viewBox, fill="currentColor" pattern used by other node icons (e.g. http.svg). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tool_vectordb): log warning on malformed JSON input _normalize_input previously swallowed JSON parse errors silently, making it hard to diagnose bad tool inputs. Now logs a warning with the parse error before returning an empty dict. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style(tool_vectordb): remove redundant parentheses in str() calls Clean up double-wrapped parens like str((cfg.get('x') or 'y')) to the simpler str(cfg.get('x') or 'y'). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR rocketride-org#524 review feedback for tool_vectordb - Remove invalid topK param from QuestionText constructor; use doc_filter.limit to control result count instead - Add embedding warning in upsert and document the limitation in the tool description - Read backend connection config from bag first, fall back to own connConfig - Distinguish disabled-tool vs unknown-tool error messages Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): migrate tool_vectordb to @tool_function pattern per PR rocketride-org#599 Remove VectorDBDriver(ToolsBase) and move search/upsert/delete tool logic to @tool_function decorated methods on IInstance. Store config and backend connection directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address remaining review feedback on tool_vectordb - Add return type annotation to IGlobal._create_store() - Downgrade semantic-to-keyword fallback log from warning to debug - Fix total count to match actual returned results after top_k slice - Return skipped document count from upsert operation - Narrow metadata schema to document only recognized fields (nodeId, parent, chunkId) instead of additionalProperties: true Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): move vector DB tool interface into store.py per review feedback Rod-Christensen suggested co-locating the tool definitions with the underlying store so every vectordb node can "morph into a tool" without a separate generic wrapper node. The engine dispatches ``invoke`` against the node's ``IInstance`` (not the ``DocumentStoreBase`` subclass, which is composed via ``self.IGlobal.store``), so a mixin that lives next to ``DocumentStoreBase`` in ``store.py`` and is inherited by the vectordb ``IInstance`` classes achieves the spirit of the suggestion while being technically correct. Changes: - Add ``VectorStoreToolMixin`` to ``packages/ai/src/ai/common/store.py`` with ``@tool_function`` decorated ``search``, ``upsert`` and ``delete`` methods that delegate to ``self.IGlobal.store``. The mixin is picked up automatically by ``IInstanceBase._collect_tool_methods`` via MRO walk. - Have ``pinecone``, ``chroma`` and ``qdrant`` ``IInstance`` classes inherit from ``VectorStoreToolMixin`` so each vectordb node exposes the search/upsert/delete tools natively. - Add ``"tool"`` to ``classType`` and ``"invoke"`` to ``capabilities`` in each node's ``services.json`` so ``getControllerNodeIds('tool')`` discovers them as tool nodes. - Delete the ``tool_vectordb`` node entirely — obsolete now that every vectordb node has native tool capability. - Delete the unused ``vectordb.svg`` icon that existed only for the now-deleted ``tool_vectordb`` node. - Fix the wrapped-payload normalization bug flagged in CodeRabbit comment 3049766102: ``{'input': '{"query": "x"}'}`` and ``{'input': SomeModel(...)}`` now recurse through ``_normalize_vectordb_tool_input`` on the inner value, so string-, model- and dict-wrapped payloads all receive the same JSON-parse/``model_dump`` treatment before merging outer extras. Other vectordb connectors (astra_db, milvus, weaviate, atlas, vectordb_postgres, index_search) can opt in to the same tool interface with a one-line change to their ``IInstance.py`` plus the services.json update — out of scope for this PR. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address blockers on vectordb tool interface Address 3 blocking issues on PR rocketride-org#524: 1. Tool name collisions: adopt the established <serverName>.<toolName> convention used by mcp_client. VectorStoreToolMixin now overrides _collect_tool_methods to prefix each tool with a per-node serverName sourced from IGlobal.serverName (user-configurable via services.json). Two pinecone/chroma/qdrant instances in the same pipeline no longer collide on bare names like "search"/"upsert"/"delete". 2. Broken pinecone semantic search: the mixin was calling searchSemantic with an unset embedding, which raises in every backend (pinecone/ chroma/qdrant) and silently fell through to keyword search. Add an IGlobal.embed_query hook so nodes can plug in an embedder for the control-plane tool path; when no embedder is bound, go straight to keyword search with a one-shot warning and update the tool description so agents know the mode. Unexpected semantic errors still fall back to keyword search with a clearer warning message. 3. No tests for VectorStoreToolMixin: add nodes/test/test_vectordb_tool_mixin.py (28 tests) covering input normalization (dict/JSON/pydantic v1+v2/ nested input wrapper/security_context stripping/malformed payloads), namespaced tool method collection including the collision-avoidance scenario, and search/upsert/delete dispatch through a fake store plus keyword-fallback, semantic-fallback, and missing-store error paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(nodes): cover embedder envelope contract + auto-embed + caller-supplied (rocketride-org#524) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(nodes): add envelope test for addChunks exception path (rocketride-org#524) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(nodes): repair embedding_* package-level Embedding aliases (rocketride-org#524) `embedding_openai/__init__.py` imported `Embedding` from `OpenAIEmbeddingWrapper` but the class there is named `OpenAIEmbeddingWrapper`. The `getEmbedding` dispatcher (`ai.common.embedding`) resolves embedding providers by calling `module.getEmbedding()` which previously returned the wrong name, crashing any caller that instantiated the result. Add an alias so `getEmbedding()` returns a name-stable `Embedding` class. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(nodes): wire per-node embedder + return tool-invoke error envelopes (rocketride-org#524) Wire a control-plane embedder (embed_query / embed_model_name) into the beginGlobal of each vectordb node (pinecone, chroma, qdrant) using the same autopipe/vectorizer pattern: read the 'embedding' sub-config from the merged node config and only instantiate when present. endGlobal tears down the embedder before the store. The _embed_query closure wraps the text in a Question object so encodeQuestion iterates question.questions correctly. In VectorStoreToolMixin: - search: remove silent keyword-fallback for the no-embedder case; return an error envelope instead (keeps keyword fallback only after a failed semantic call when an embedder IS bound) - upsert: accept optional per-doc 'embedding'/'embedding_model' fields; compute via IGlobal.embed_query when not supplied; return envelope when no embedder is available; wrap addChunks in try/except -> envelope - delete: convert ValueError raises to error envelopes - search: expand output_schema with optional success/error fields Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style: ruff format store.py after rebase onto develop (rocketride-org#524) Develop's ruff format pass (landed after branch point) reformatted some regions of store.py. Re-apply ruff format to stay consistent. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style(nodes): ruff format test_vectordb_tool_mixin.py for CI line wrap CI's ruff config wrapped 3 multi-arg FakeStore/FakeIInstance calls onto multiple lines; local ruff didn't. Apply ruff format to align. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…-org#557) * feat(nodes): add v0 by Vercel tool node for AI-powered UI generation Adds a new tool_v0 pipeline node that integrates with Vercel's v0 API to generate React + Tailwind CSS components from natural-language prompts. Exposes generate_ui and refine_ui as agent-invocable tools. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address PR rocketride-org#557 feedback on v0 Vercel node - Format services.json with inline comments matching repo conventions - Return success:false when _extract_code yields empty code instead of success:true with empty string - Include prior_messages in refine_ui for stateless API fallback while keeping parent_message_id for stateful servers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): format services.json and add header comment for v0 node Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(nodes): migrate tool_v0 to @tool_function pattern per PR rocketride-org#599 Remove V0Driver(ToolsBase) and move generate_ui/refine_ui tool logic to @tool_function decorated methods on IInstance. Store apikey directly on IGlobal instead of through a driver object. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(nodes): address CodeRabbit review feedback on tool_v0 node - Remove extraneous parentheses around cfg.get() in IGlobal.py - Add defensive JSON error handling for non-JSON API responses - Update tile label to generic "Tool: v0 UI Generation" - Add 'error' field to both tool output schemas - Remove raw response body from HTTP error logging Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: format JSON file * fix(nodes): return schema-shaped errors and redact log payloads in tool_v0 Address CodeRabbit review feedback on the v0 by Vercel tool node: - generate_ui and refine_ui now wrap _call_v0_api/_extract_code in try/except and return {success: False, error: ...} on transport or parse failures, so downstream nodes can branch on failure instead of seeing raised exceptions. Argument validation also returns the same shape rather than raising ValueError. - _normalize_tool_input no longer logs the raw input repr when given an unexpected type; prompts, prior messages, and generated code are now redacted from server logs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(nodes): narrow tool_v0 exception types per reviewer feedback Replace broad `except Exception` in generate_ui and refine_ui with `except (httpx.HTTPError, ValueError, json.JSONDecodeError)` so unexpected errors propagate rather than being silently swallowed. The internal _call_v0_api handler is intentionally left broad as it logs and re-raises. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(nodes): add unit tests for tool_v0 IInstance pure-logic helpers Covers _normalize_tool_input, _extract_code, generate_ui, and refine_ui with rocketlib stubbed via sys.modules to avoid runtime dependencies. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(nodes): patch tool_v0 module warning attr directly for CI environment The tests stubbed rocketlib via sys.modules.setdefault, but on CI the real rocketlib is already loaded into sys.modules so the stub is a no-op. The production code does `from rocketlib import warning` which binds the name at import time, so the IInstance module ends up with a reference to the engine's real logger and never appends to _WARNING_CALLS. Override _mod.warning directly after loading IInstance — patches the actual reference _normalize_tool_input uses, independent of rocketlib's state in sys.modules. Fixes test_non_dict_type_logs_type_name_only and test_non_dict_list_logs_type_name_only failing inside the engine pytest runner on Build / Ubuntu / macOS / Windows. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(tool_v0): address review feedback - raise ValueError/RuntimeError instead of returning {success:False,error} dicts; drop the try/except wrappers so framework sees real failures (asclearuc: match tool_firecrawl/memory_internal pattern) - require prior_messages in refine_ui so a stateless v0 endpoint can't silently produce an unrelated component - surface the v0 API error payload in the no-code RuntimeError - shallow-copy tool input so security_context strip never mutates the caller-owned args dict - drop now-unused 'error' output_schema field * feat(tool_v0): add co-located vercel.svg icon (rocketride-org#926 convention) * fix(tool_v0): target v0 Platform API, use shared tool utils Address asclearuc's PR rocketride-org#557 review: - API contract: the node POSTed to /v1/chat (OpenAI Model API shape) but parsed an OpenAI choices[] response. Switch to the v0 Platform API: generate_ui -> POST /v1/chats {message}; refine_ui -> POST /v1/chats/{chat_id}/messages {message}. Parse the stateful chat object ({id, latestVersion: {demoUrl, files: [{name, content}]}}) into chat_id, code (primary file), files, and demo_url. Drop parent_message_id, message_id, prior_messages, and the model parameter (chats are stateful server-side, so no history replay). - Retries: replace the hand-rolled httpx client with ai.common.utils.post_with_retry (requests + tenacity), keeping the 120s timeout via kwarg. - Input handling: replace the local _normalize_tool_input with ai.common.utils.normalize_tool_input(tool_name='v0'). - requirements.txt: httpx -> requests; drop the depends() bootstrap from __init__.py to match the sibling tool nodes (tool_tavily, tool_exa_search). - vercel.svg: fill="#000" -> fill="currentColor" so the SVGO auto-currentcolor pipeline keeps the icon theme-adaptive. - tests: rewrite against the Platform API shape with a mocked post_with_retry covering success, the {"error": {...}} shape, empty files, transport errors (status-only logging), and non-JSON bodies. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(tool_v0): fix stub leak into shared pytest session, add coverage The test injected import stubs via sys.modules.setdefault('rocketlib', ...) and never removed them. When test_tool_v0 was collected before test_tool_tavily, v0's incomplete rocketlib stub leaked and tavily's collection failed with ImportError. Adopt tavily's install-then-pop pattern: inject only modules not already present, import, then remove exactly what was added (plus the private tool_v0 scaffolding). Also close coverage gaps: api-error prefers error.message over userMessage/code; refine_ui builds the URL from the input chat_id even when the response carries a different id; non-dict JSON payload raises "unexpected payload type"; Content-Type: application/json header. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Alexandru Sclearuc <asclearuc@gmail.com>
Summary
ToolDescriptoruses camelCase keys (inputSchema) but agent_langchain, agent_deepagent, and agent_crewai were readinginput_schema(snake_case) — the LLM never saw real parameter schemas, always falling back to a generic "accept anything" input. Fixed all three drivers to useinputSchema.@invoke_functiondecorated methods, matching the pattern established in the@tool_functionrefactor.Changes
input_schema→inputSchemainput_schema→inputSchemainput_schemafallback, useinputSchemaonlymatch/case→@invoke_functiondecoratorsdescription or "default"_storetype fix; raiseValueErroron bad argsNone; modernize typesstr(body_json)→json.dumps()for valid JSONtyping.Set→ built-insetint()parse for limit with fallbackTest plan
llm_baseinvoke operations (ask, getContextLength, getOutputLength, getTokenCounter) still workpytest packages/ai/tests/🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Refactor