mirror of
https://github.com/tinyhumansai/openhuman.git
synced 2026-07-27 21:08:00 +00:00
1a676c6d4488fdc1e32b35bb9fb141d5bb8e7bf8
289
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6b044a9456 | docs: rewrite README + gitbooks around current product, add Developing section (#1384) | ||
|
|
8d9a1ca788 |
perf(agent): orchestrator harness efficiency improvements (#1314)
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
0f6cc583f3 |
feat(tools/whatsapp_data): expose local WhatsApp store to agent (#1341) (#1373)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
0636b0c1a5 | feat(meet_agent): live note-taking agent for Google Meet (listen + speak) (#1355) | ||
|
|
836a6d852c | feat(meet): join Google Meet calls with mascot virtual camera (#1350) | ||
|
|
3bbf4b5d9f | fix(stt): rewrite stale-sidecar voice error + e2e registration guard (#1298) | ||
|
|
ba88d8cfc3 |
fix(webview/meet): gate orchestrator handoff on user opt-in (#1299) (#1310)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
a35ba10bb2 |
feat(channels): expose WhatsApp Web data to agent via structured RPC API (#1308)
Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
b03412111d | Agent harness: USD cost tracking, stop hooks, per-tool result caps (#1268) | ||
|
|
1570f3220b | feat(local-ai): off by default, scoped usage flags, faster auto-updates (#1263) | ||
|
|
1ac3feed3a | fix(channels): managed-DM credentials surface as connected to chat (#1209) | ||
|
|
49a9b835b6 | Persist turn state + restore conversation history on cold-boot (#1202) | ||
|
|
62516ba418 |
feat(memory_tree): cloud-default LLM, queue priority, entity filter, Memory tab UI (#1198)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
995e5ccccb | feat(security): enforce prompt-injection guard before model and tool execution (#1175) | ||
|
|
d812bf9da7 | fix(agent): drop redundant [Memory context] recall injection (#1173) | ||
|
|
e6b491bcf1 | feat(threads): surface live subagent work in parent thread (#1122) (#1159) | ||
|
|
2484ea40f2 | feat(memory): ingestion pipeline + tree-architecture docs + ops/schemas split (#1142) | ||
|
|
52eb3a175f | feat(memory): singleton ingestion + status RPC + UI pill (#1126) | ||
|
|
393852b1d6 |
Feat: core rpc auth (#881)
Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
2304d9d58f | feat(memory): add Sync and Learn sections to Memory workspace (#1031) | ||
|
|
ac97a96d3a | fix(local-ai): cap local models to 1b preset (#1029) | ||
|
|
0768d18873 |
feat(orchestrator): wire memory-tree retrieval tools with periodic prefetch (#1027)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
40fddf5bfa |
chore(dev): add Windows dev runner and align lockfile versions (#1015)
Co-authored-by: oxoxDev <164490987+oxoxDev@users.noreply.github.com> |
||
|
|
b11b8f333f | [Feature] Thread labels / categories for list organization (#947) | ||
|
|
da94043c31 | test(memory): phase 1 email ingest harness (#1009) | ||
|
|
cf89552273 |
Fix: calendar events (#1004)
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> |
||
|
|
fd0398d5fa |
feat(memory): MD-on-disk content + participant bucketing + async pipeline foundation (#1008)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
4f9da9eb8d |
test(foundation): coverage matrix + strategy + gap-fill batch (#773) (#980)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
215a776eea | feat(ux): lock UI to welcome agent until chat onboarding completes (#883) (#892) | ||
|
|
d2f045769f | test(notifications): add Phase 4 RPC and dismiss reducer coverage (#878) | ||
|
|
95504d4b09 |
test: add 196 tests across MCP, services, utils, autocomplete (#855)
Co-authored-by: Jwalin Shah <jshah1331@gmail.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
7bd8f9d4c1 | ci: parallelize rust tests, dedupe typecheck/clippy/sentry across workflows (#895) | ||
|
|
a96d9da3a4 | chore: migrate from yarn to pnpm (#886) | ||
|
|
3862b1bb1c | fix(tests): run webview_apis mock bridge on a dedicated runtime (#893) | ||
|
|
11c67a70b9 | feat(notifications): add dismiss/stats RPC, DomainEvents, and triage bus integration (#875) | ||
|
|
208c276a3e | feat(notifications): bridge CEF providers into core ingest pipeline with dedup (#874) | ||
|
|
b329e45cdb |
feat(skills): uninstall for user-scope SKILL.md skills (#781) (#833)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> |
||
|
|
500ddc2a8a | feat(webview_apis): WebSocket bridge for live-webview APIs, Gmail first (#869) | ||
|
|
629b4ccb07 |
test(memory_tree): unit tests for retrieval RPC handlers (#710) (#839)
- Add JSON-RPC handlers for source, global, and topic-based memory retrieval. - Integrate Ollama embeddings for semantic reranking of chunks and summaries. - Implement 15 unit tests for RPC handlers covering parameter parsing and PII redaction. - Redact PII from logs by removing raw source, entity, and node identifiers. - Fix BFS traversal for drill-down and deduplicate results in topic queries. - Add configuration for embedding endpoints, models, and strictness modes. Co-authored-by: sanil-23 <sanil@vezures.xyz> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
5e660f2fe8 |
feat(core): memory namespaces, recall citations, provider_surfaces RPC (#803)
Co-authored-by: Jwalin Shah <jshah1331@gmail.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
3bb714bf96 |
feat(webview): native OS notifications from embedded webview apps (#714) (#727)
* feat(webview_accounts): native OS notifications from embedded webviews (#714) Forward CEF notification intercept payloads to tauri-plugin-notification, prefixing the title with the provider label so the source of each toast is obvious at a glance. Honour `silent` (skip toast, still record route), `icon` (passed through to the native builder), and `tag` (used as the dedup key, with a monotonic timestamp fallback for untagged payloads). Record a NotificationRoute keyed by `{provider}:{account_id}:{tag_or_uuid}` so a future click hook (UNUserNotificationCenter / notify-rust on_response) can route the OS click back to the source account. Entries are cleared on webview_account_close / _purge to bound map growth. Expose webview_notification_permission_state / _request commands mapping tauri::plugin::PermissionState onto the web API triple. Non-cef stubs return "default" so the frontend can call the same invoke names on both runtimes. Wire notification:allow-* capabilities so the plugin can be invoked from the webview. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(accounts): wire notification permission + click bridge (#714) Round-trip the OS notification permission once per session on first account open via the new invoke pair. Attach a dormant notification:click listener that dispatches setActiveAccount and brings the main window to front when a platform click hook starts emitting the event — contract matches the Rust NotificationRoute shape so the emit side is a one-liner. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync Cargo.lock to 0.52.26 after version bump Lockfile picked up the pending 0.52.26 version bump from Cargo.toml while building the notification feature. No dependency graph change. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(notifications): add notification bypass for embedded webview apps (#679) - Add NotificationBypassPrefs (global DND, per-account mute, bypass-when-focused) to WebviewAccountsState with thread-safe AtomicBool window focus tracking - Evaluate all three bypass conditions inside forward_native_notification before showing OS toast; each suppression path logs at debug with [notify-bypass] prefix - Add four new Tauri commands: webview_notification_set_dnd, webview_notification_mute_account, webview_notification_get_bypass_prefs, webview_set_focused_account - Wire window focus tracking in setup hook via on_window_event Focused handler - Frontend: add setAccountMuted, setGlobalDnd, getBypassPrefs, setFocusedAccount helpers in webviewAccountService; sync focused account on open + click - Add NotificationsPanel settings page with Global DND toggle - Register NotificationsPanel at /settings/notifications Closes #679 * feat(notifications): integrate notifications feature into app - Added Notifications page and routing to AppRoutes. - Introduced NotificationRoutingPanel in Settings for managing notification settings. - Updated SettingsHome to include navigation for notification routing. - Integrated notifications reducer into the store for state management. - Enhanced Rust backend to support notification handling from embedded webviews. This commit lays the groundwork for a comprehensive notification system within the application. * refactor(notifications): clean up code formatting and structure - Simplified JSX structure in NotificationCard for better readability. - Consolidated fetchNotifications call in NotificationCenter for cleaner syntax. - Improved formatting in NotificationRoutingPanel and notificationsSlice for consistency. - Enhanced Rust code readability by streamlining function signatures and logic. These changes enhance code maintainability and readability across the notifications feature. * refactor(webview_accounts): simplify webview_notification_set_dnd function signature - Removed unnecessary line breaks in the webview_notification_set_dnd function for improved readability. * feat(notifications): implement provider-level notification settings management - Added `getNotificationSettings` and `setNotificationSettings` functions to manage notification settings for providers. - Enhanced `NotificationRoutingPanel` to display and update settings for Gmail, Slack, Discord, and WhatsApp. - Introduced new RPC endpoints for retrieving and updating notification settings. - Updated database schema to store notification settings persistently. This commit establishes a robust system for managing notification preferences, improving user control over notifications. * refactor(notifications): improve code formatting and readability - Enhanced formatting in NotificationRoutingPanel for better clarity. - Streamlined function signatures in notificationService and Rust backend. - Improved readability of assertions in tests by adjusting line breaks. These changes contribute to a more maintainable and comprehensible codebase for the notifications feature. * chore(vendor): bump tauri-cef to fix Slack notification permission banner Updates the tauri-cef submodule to 55db2d6 which adds a navigator.permissions.query shim in the CEF render process. Slack checks this API (not just Notification.permission) to decide whether to show its "needs your permission" banner — the shim returns "granted" for notifications queries so the banner no longer appears. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(vendor): bump tauri-cef for cargo fmt fixes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(vendor): bump tauri-cef — native V8 permissions.query shim Switches from context.eval() to a proper PermissionsQueryV8Handler so the navigator.permissions.query fix actually runs in on_context_created. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(notifications): patch navigator.permissions.query in ua_spoof.js The V8 set_value_bykey approach in cef-helper's on_context_created does not stick on CEF platform objects (Chromium's V8 binding layer silently ignores property writes on native wrappers like Permissions). The init script path via frame.execute_java_script runs in the fully-initialised JS context where navigator.permissions IS writable, matching how ua_spoof.js already overrides navigator.userAgent successfully. Slack checks navigator.permissions.query({ name: 'notifications' }) before showing its "needs permission" banner — patching it here to return "granted" removes the banner. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(notifications): use Object.defineProperty to shim navigator.permissions Two-layer fix for the Slack "needs permission to enable notifications" banner: 1. cef-helper (submodule update to 99a2686): context.eval() in on_context_created installs Object.defineProperty(navigator, 'permissions', ...) before any page JS runs. 2. ua_spoof.js: same Object.defineProperty pattern as belt-and-suspenders for frames that reload or trigger permission checks after on_load_end. Simple property assignment on Blink platform objects is silently ignored; Object.defineProperty on the navigator wrapper itself (the same mechanism already used for navigator.userAgent) works correctly. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(notifications): address CodeRabbit review issues on PR #727 - Move raw_title out of log::info! (PII risk) — log title_chars at info, raw_title at debug only - Fix permissionChecked set before async invoke in ensureNotificationPermission so transient failures allow retry on next account open * fix(cef): enable webview-data-url feature for CEF placeholder URL The CEF backend uses a data: URL as the initial webview location so CDP can attach before the real provider URL loads. Tauri's add_child rejects data: URLs unless the webview-data-url feature is enabled. * fix(notifications): address remaining CodeRabbit issues on PR #727 - cdp/emulation: bump Chrome UA 124→136 to pass Slack browser check - cdp/session: inject Page.addScriptToEvaluateOnNewDocument to stub Notification.permission as "granted" and silence provider banners - notifications/mod.rs + core/all.rs: wire notifications domain into the controller registry (fixes unknown-method in json_rpc_e2e tests) - notifications/schemas: add skipped bool output to ingest schema - notifications/store: add tracing::warn on datetime parse failure - notificationService: union return type for ingestNotification - webviewAccountService: narrow union before accessing result.id - NotificationCenter: drive loading/error from fetch effect; track allProviders separately so filter pills don't collapse on selection - NotificationRoutingPanel: rollback optimistic update on save failure - useSettingsNavigation: add notifications/notification-routing routes - scripts/install.sh: remove silent dry-run exit 0 on asset failure - scripts/setup-dev-codesign.sh: remove unconditional -legacy flag - docs/SUMMARY.md: remove worktree path, fix macOS capitalisation, remove self-referential deletion note * chore: apply prettier + cargo fmt + fix useEffect dep warning Auto-apply formatting changes flagged by the pre-push hook: - prettier reformatted NotificationCenter.tsx and notificationService.ts - cargo fmt reformatted all.rs, openhuman/mod.rs, notifications/schemas.rs - NotificationRoutingPanel: move providers array to module scope so useEffect dependency array is satisfied without exhaustive-deps warning * feat(notifications): enhance notification management and permissions - Added new commands for managing notification preferences, including setting global Do Not Disturb (DND), muting specific accounts, and retrieving current bypass preferences. - Implemented a notification permission state handler to ensure consistent behavior across different environments. - Updated the JavaScript shim for notification permissions to handle both Notification and PushManager states, ensuring compatibility with various providers. - Refactored the WebviewAccountsState to include a new structure for managing notification bypass preferences, improving the overall notification handling logic. * update agents * fix(notifications): complete schema + navigation metadata for ingest/settings routes - app/src/components/settings/hooks/useSettingsNavigation.ts: resolve the new `/settings/notifications` and `/settings/notification-routing` URLs to their SettingsRoute values and feed them into breadcrumbs so the new panels don't silently fall through to `'home'`. Addresses CodeRabbit on useSettingsNavigation.ts:34. - src/openhuman/notifications/schemas.rs: add the optional `reason` output on `notification.ingest` (populated alongside `skipped=true` by the runtime) and the normalized `settings` output on `notification.settings_set` so schema-driven clients see the full response shape. Addresses CodeRabbit on schemas.rs:103 and schemas.rs:217. - src/core/all.rs: add a `notification` namespace_description so CLI help covers the new controllers, plus a test assertion. Addresses CodeRabbit on src/core/all.rs:149. * fix(notifications): trace DB entry, surface empty update matches, warn on bad scored_at - Add `tracing::trace!` checkpoints around the `with_connection` DB open and schema migration so notification-delivery issues are reconstructible from logs. - `update_triage` and `mark_read` now inspect `Connection::execute`'s affected-row count: log a `warn!` when the update matched zero rows (row deleted between ingest and scoring / client passed a stale id), `debug!` on the normal path. - `scored_at` parsing no longer silently drops malformed values — log a `warn!` with the raw value and parse error before treating the row as unscored, matching the existing behavior for `received_at`. Addresses CodeRabbit on store.rs (lines 72, 172, 294). * fix(webview): respect silent notifications, multi-host CDP fallback, shim idempotency - webview_accounts/mod.rs: honor the Web Notification `silent` flag. Previously we only logged it and still called `builder.show()`, so pages that marked a notification silent still produced an OS toast. Mirror event still fires so the in-app center updates; only the OS toast is suppressed. Also picks up a prior cargo-fmt rewrap. - cdp/target.rs: `browser_ws_url()` now continues the host loop when `resp.json()` fails instead of early-returning via `?`. A malformed response from the first host (CDP_HOST) no longer prevents the `localhost` fallback from being tried. - webview_accounts/ua_spoof.js: guard the Notification wrapper behind `window.__OH_NOTIF_SHIM` so repeated evaluations of the script (Page.addScriptToEvaluateOnNewDocument + frame-level re-injections) don't stack wrappers onto the same page globals or re-proxy `Function.prototype.toString`. Addresses CodeRabbit on webview_accounts/mod.rs:377, cdp/target.rs:33, and ua_spoof.js:176. * update agents * update --------- Co-authored-by: oxoxDev <nikhil@tinyhumans.ai> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
5fff5568d3 |
feat(memory): Phase 2 memory tree - preprocessing, scoring, admission gate (#708) (#733)
* feat(memory): phase 1 memory tree - multi-source ingestion & canonical chunks (#707) Adds an isolated memory tree layer under src/openhuman/memory/tree/ implementing Phase 1 of the new memory architecture (umbrella #711). Zero edits to existing memory/*.rs files - the new layer coexists with the legacy TinyHumans-backed client. - Source adapters: chat / email / document -> canonical Markdown - Token-bounded chunker with deterministic SHA-256 chunk IDs - SQLite persistence at <workspace>/memory_tree/chunks.db with full provenance metadata (source_kind, source_id, owner, timestamps, tags, time_range) and back-pointer to raw source - Unified JSON-RPC ingest (dispatches on source_kind + JSON payload): openhuman.memory_tree_ingest, _list_chunks, _get_chunk - DataSource enum covering the 8 providers from m.excalidraw step 1 (Discord/Telegram/Whatsapp/Gmail/OtherEmail/Notion/MeetingNotes/DriveDocs) - ~40 unit tests (chunk ID stability, UTF-8-safe splitting, canonicalisation idempotence, store round-trip, filter behavior) Additive only: new tables in a new DB file, new JSON-RPC namespace, no existing behavior changes. Feeds #708 (scoring), #709 (summary trees), #710 (query tools). Closes #707. Parent: #711. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(memory): phase 2 memory tree - preprocessing, scoring, admission gate (#708) Adds the scoring / admission layer between Phase 1's chunker and store. Stacked on feat/707-memory-ingestion (PR #732) - depends on Phase 1's chunk substrate. - Pluggable EntityExtractor trait + CompositeExtractor chain - RegexEntityExtractor: mechanical entities (emails, URLs, @handles, #hashtags) - Always on, deterministic, zero deps, UTF-8-safe char spans - Five weighted signals: token count, unique-word ratio, metadata weight, source weight (per-DataSource), interaction (reply/sent/mention/dm tags), entity density - Exact-match entity canonicalisation (email lowercased, @ and # stripped) - Admission gate drops chunks below configurable threshold (default 0.3) - Score rationale persists for EVERY chunk (kept or dropped) for debugging - Entities indexed for KEPT chunks only - Two new SQLite tables added to the memory_tree DB: - mem_tree_score: per-chunk score rationale with all signal values - mem_tree_entity_index: inverted index entity_id -> node_id - Idempotent ALTER TABLE migration adds embedding BLOB column to mem_tree_chunks (used in Phase 3 retrieval, wired but not populated here) - Ingest pipeline converted to async to accommodate the extractor trait; blocking SQLite work isolated on spawn_blocking; JSON-RPC surface unchanged (same memory_tree_ingest / list / get methods) - Phase 2 deliberately ships without GLiNER/semantic NER - per-chunk semantic entities land later behind a cargo feature flag; the composite extractor interface keeps that drop-in trivial Additive only: new tables, new columns, new module. Existing Phase 1 behavior unchanged except that low-signal chunks are now dropped before reaching mem_tree_chunks. Raise score_drop_threshold to 0 to disable the gate and restore Phase-1-identical behavior. Closes #708. Parent: #711. Depends on: #707 (#732). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Fix memory tree scoring persistence issues * Fix memory tree scoring robustness issues from PR review - ingest: fail fast if scorer returns fewer/more results than chunks (silent zip truncation would drop chunks or their score rationale) - score::persist_score{,_tx}: clear stale entity-index rows before re-indexing a re-scored chunk, since INSERT OR REPLACE never deletes rows whose entity_id is no longer in the new extraction - score::store::lookup_entity: clamp limit to i64::MAX before casting to prevent a large usize wrapping into a negative LIMIT Adds clear_entity_index_drops_stale_rows regression test. --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
0ce1253fe1 |
feat(memory): Phase 1 memory tree - multi-source ingestion & canonical chunks (#707) (#732)
* feat(memory): phase 1 memory tree - multi-source ingestion & canonical chunks (#707) Adds an isolated memory tree layer under src/openhuman/memory/tree/ implementing Phase 1 of the new memory architecture (umbrella #711). Zero edits to existing memory/*.rs files - the new layer coexists with the legacy TinyHumans-backed client. - Source adapters: chat / email / document -> canonical Markdown - Token-bounded chunker with deterministic SHA-256 chunk IDs - SQLite persistence at <workspace>/memory_tree/chunks.db with full provenance metadata (source_kind, source_id, owner, timestamps, tags, time_range) and back-pointer to raw source - Unified JSON-RPC ingest (dispatches on source_kind + JSON payload): openhuman.memory_tree_ingest, _list_chunks, _get_chunk - DataSource enum covering the 8 providers from m.excalidraw step 1 (Discord/Telegram/Whatsapp/Gmail/OtherEmail/Notion/MeetingNotes/DriveDocs) - ~40 unit tests (chunk ID stability, UTF-8-safe splitting, canonicalisation idempotence, store round-trip, filter behavior) Additive only: new tables in a new DB file, new JSON-RPC namespace, no existing behavior changes. Feeds #708 (scoring), #709 (summary trees), #710 (query tools). Closes #707. Parent: #711. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(memory): enhance memory tree functionality and tests - Added support for "memory_tree" namespace description in `namespace_description`. - Implemented clamping for zero token budget in `chunk_markdown` to prevent empty leading chunks. - Introduced detailed logging for document ingestion, including title length. - Updated output schemas in `schemas.rs` for improved clarity. - Enhanced chunk listing with clamping limits and ordering by sequence in `list_chunks`. - Normalized source references in canonicalization functions to drop blank values. - Added comprehensive tests for new features and edge cases in chunking and canonicalization. These changes improve the robustness and usability of the memory tree layer, aligning with ongoing development efforts for Phase 1 of the memory architecture. * fix(memory): address follow-up CodeRabbit comments --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai> |
||
|
|
e5f571cec7 |
feat(tokenjuice): Rust port of terminal-output compaction engine (#644)
* feat(tokenjuice): implement core functionality for terminal-output compaction engine - Introduced the `tokenjuice` module, which includes the classification and reduction of tool outputs based on JSON-configured rules. - Added new dependencies for Unicode handling: `unicode-segmentation` and `unicode-width`. - Implemented the `classify` module to match tool execution inputs against predefined rules, enhancing the ability to process and summarize terminal outputs. - Created a comprehensive set of types and utilities for managing tool execution inputs and classification results. - Established a built-in rule set for common tools, improving the initial setup and usability of the `tokenjuice` engine. - Enhanced testing framework with integration tests to ensure the accuracy of output compaction and classification. These changes lay the groundwork for a robust terminal-output management system, facilitating better interaction with various tools and improving overall user experience. * feat(tokenjuice): implement tokenjuice module for terminal output compaction - Introduced the `tokenjuice` module, which includes functionality for classifying and reducing terminal output based on JSON-configured rules. - Added new dependencies: `unicode-segmentation` and `unicode-width` to support text processing. - Created a new `classify.rs` file for rule classification logic, including matching helpers and scoring functions. - Implemented a `reduce.rs` file to handle the main reduction pipeline and text normalization. - Established a structured approach for loading and compiling rules from multiple sources, including built-in and user-defined rules. - Added integration tests to ensure the correctness of the output reduction process. These changes enhance the application's ability to manage and compact verbose tool outputs, improving overall efficiency and user experience. * test(tokenjuice): enhance test coverage for classification and reduction logic - Added a series of unit tests to `classify.rs` to validate the behavior of tool name filters and argument matching, ensuring correct classification of tool executions. - Introduced tests for edge cases in `reduce.rs`, including command tokenization and normalization of execution inputs, to improve robustness against various input formats. - Expanded tests in `builtin.rs` to cover duplicate ID reporting and compile issues, enhancing error handling and reporting mechanisms. - Implemented additional tests in `compiler.rs` to verify regex handling in rule definitions, ensuring invalid patterns are correctly ignored. These enhancements improve the overall test coverage and reliability of the tokenjuice module, facilitating better maintenance and future development. * test(tokenjuice): add edge-case tests for gh table and reduction pipeline * style(tokenjuice): apply cargo fmt * feat(tokenjuice): wire into agent tool loop output compaction Add `tokenjuice::compact_tool_output` helper and call it in the agent tool loop after credential scrubbing (and on error paths with exit=1), before any optional payload_summarizer. Derives argv/command heuristically from JSON tool arguments (command / args / argv / cmd shapes) so shell-wrapping tools still match upstream family rules (git/*, package/*, tests/*, etc.). Pass-through safe: outputs under 512 bytes or where compaction saves <5% are returned untouched. * fix(tokenjuice): address coderabbit review comments - classify: derive command from argv join when input.command is unset, so commandIncludes* rules still match argv-only callers - rules/loader: log read_dir / file_type / read_to_string failures at debug level so permission or filesystem issues are observable rather than silently skipped - text/ansi: add trace log at strip_ansi entry/exit with lengths (no text content) per the project debug-logging rules - tests: remove orphan src/openhuman/tokenjuice/tests/integration.rs which was never wired into any module declaration; the real fixture- parity runner lives at tests/tokenjuice_integration.rs and asserts hard when the fixtures directory is missing Vendored-rule issues (docker-ps / kubectl-describe / git/branch / grep casing / counter-pattern overbreadth / etc.) come from upstream and are left as-is; this module is a straight port of the upstream rule set and should not fork from it in v1. |
||
|
|
fff24a6c6f |
fix(prompts): v2 prompt pipeline, integrations_agent, and subagent session plumbing (#642)
* refactor(transcript): update session transcript paths and enhance directory structure
- Changed the source of truth path for session transcripts from `sessions/{DDMMYYYY}/{agent}_{index}.jsonl` to `session_raw/{DDMMYYYY}/{agent}_{index}.jsonl` to better reflect the organization of files.
- Updated the logic for creating and resolving transcript paths to accommodate the new directory structure, ensuring compatibility with legacy `.md` files.
- Improved documentation to clarify the changes in file organization and their implications for transcript management.
This refactor enhances the clarity and maintainability of session transcript handling by establishing a more logical file structure.
* refactor(prompts): update tool handling in prompt builders
- Replaced `Vec<String>` with `Vec<ToolSummary<'_>>` for available tools in multiple agent prompt builders, enhancing type safety and clarity.
- Introduced `render_tool_catalog` and `render_connected_integrations` functions to dynamically generate sections in prompts based on available tools and connected integrations.
- Updated the `build` function in various agent prompts to utilize the new rendering functions, ensuring that prompts accurately reflect the current context and available resources.
These changes improve the maintainability and functionality of the prompt generation process across different agents.
* refactor(prompts): streamline prompt builders for agent templates
- Updated the prompt builders for various agents to utilize the sibling `prompt.md` template directly, enhancing clarity and maintainability.
- Replaced `Vec<ToolSummary<'_>>` with `Vec<ToolSummary>` and `Vec<ConnectedIntegration>` for improved type safety in test cases.
- Adjusted the `build` function to ensure consistent formatting and handling of tool catalogs across different agents.
These changes simplify the prompt generation process and prepare the codebase for future enhancements.
* refactor(harness): unify tool filtering and prompt loading for debug consistency
- Exposed `filter_tool_indices` and `load_prompt_source` as `pub(crate)` to ensure that both the live runner and debug dump share the same filtering and loading logic, eliminating discrepancies.
- Enhanced documentation for both functions to clarify their purpose and usage, improving maintainability and understanding of the codebase.
These changes streamline the tool management process and enhance the reliability of debug outputs, ensuring consistency across different contexts.
* refactor(prompts): enhance prompt builders for agent templates
- Updated the prompt builders for various agents to return fully-assembled system prompts, incorporating section helpers from `crate::openhuman::context::prompt`.
- Replaced `Vec<ToolSummary<'_>>` with `Vec<ToolSummary>` and `Vec<ConnectedIntegration>` for improved type safety in test cases.
- Adjusted the `build` function to ensure consistent formatting and handling of user files, tools, and workspace sections across different agents.
These changes streamline the prompt generation process, improve maintainability, and prepare the codebase for future enhancements.
* refactor(prompts): enhance prompt context handling for dynamic sources
- Updated the prompt builders to support fully-assembled prompts from dynamic sources, allowing for more flexible prompt generation.
- Introduced `PromptTool` and `PromptContext` structures to replace `ToolSummary`, improving type safety and clarity in prompt construction.
- Refactored the handling of prompt sources in both the subagent runner and session builder to streamline the integration of dynamic prompts and legacy sources.
These changes improve the maintainability and functionality of the prompt generation process, ensuring accurate representation of available tools and context in agent interactions.
* refactor(prompts): improve prompt context and tool handling
- Enhanced the `PromptContext` structure to include additional fields for better context management, such as `skills`, `dispatcher_instructions`, and `tool_call_format`.
- Replaced `ToolSummary` with `PromptTool` for improved type safety and clarity in prompt generation.
- Updated the handling of dynamic prompt sources in both the subagent runner and debug dump, ensuring consistent integration and rendering of prompts.
- Introduced a mechanism to handle empty visible tool names, enhancing the robustness of prompt generation.
These changes streamline the prompt construction process and improve the overall maintainability of the codebase.
* refactor(prompts): reorganize prompt handling and introduce SystemPromptBuilder
- Moved prompt-related types and builders from `openhuman::context::prompt` to `openhuman::agent::prompts` for better modularity.
- Introduced `SystemPromptBuilder` to streamline the construction of system prompts, allowing for flexible section management.
- Updated module exports to maintain compatibility while enhancing the organization of prompt-related code.
These changes improve the clarity and maintainability of the prompt generation process, aligning it more closely with the agents that utilize these prompts.
* refactor(prompts): unify agent prompt handling and update CLI references
- Removed the "main" alias for the orchestrator in the prompt dumping process, treating it as just another registered agent.
- Updated the `debug-agent-prompts.sh` script to reflect this change, ensuring all agents are included uniformly.
- Revised documentation and error messages in `agent_cli.rs` to replace references to "main" with "orchestrator" for clarity.
- Enhanced the debug dump functionality to maintain consistency across agent prompts, improving overall maintainability and usability.
These changes streamline the prompt handling process and clarify the usage of agent identifiers in the CLI, aligning with the new architecture.
* refactor(prompts): remove CACHE_BOUNDARY references from agent prompts
- Eliminated the CACHE_BOUNDARY marker from various agent prompt files, streamlining the prompt generation process.
- Updated the build functions in multiple agents to ensure consistent handling of workspace rendering without the cache boundary.
- Refactored related prompt handling logic to enhance clarity and maintainability, aligning with the new architecture.
These changes simplify the prompt structure and improve the overall efficiency of prompt generation across agents.
* refactor(prompts): remove cache boundary references from tests and prompts
- Eliminated all instances of cache boundary references from the subagent runner and related tests, simplifying the prompt handling logic.
- Updated test assertions to reflect the removal of cache boundary checks, ensuring consistency across the testing framework.
- Refactored the session manager to streamline the system prompt assembly process without relying on cache boundaries.
These changes enhance the clarity and maintainability of the prompt generation process, aligning with the recent architectural updates.
* refactor(harness): clean up unused imports and streamline code
- Removed unnecessary imports from multiple files, including `RandomState`, `Hasher`, and `SerializeMap`, to enhance code clarity and maintainability.
- Simplified the structure of several modules by eliminating redundant use statements, ensuring a cleaner and more efficient codebase.
These changes contribute to a more organized and readable code structure, aligning with ongoing refactoring efforts.
* refactor(prompts): enhance agent prompt structures and integration handling
- Updated the `orchestrator`, `skills_agent`, and `welcome` prompts to streamline the rendering of connected integrations and delegation guides.
- Introduced dedicated functions for rendering integration information, ensuring clarity in the agent's voice and responsibilities.
- Removed redundant sections from the shared prompt builder, allowing each agent to manage its own prompt content more effectively.
- Improved test coverage for prompt generation, ensuring accurate representation of connected integrations and skills.
These changes enhance the maintainability and clarity of the prompt generation process, aligning with the recent architectural updates.
* refactor(session): update integration handling and clean up prompt parameters
- Revised documentation for `connected_integrations` in the `Agent` struct to clarify its role in the agent's prompt rendering.
- Updated the parameter name in `render_subagent_system_prompt_with_format` to `_connected_integrations` to indicate it is unused, enhancing code clarity.
- Cleaned up import statements in the context module for better organization and maintainability.
These changes improve the clarity of integration handling and streamline the code structure, aligning with ongoing refactoring efforts.
* refactor(agent_cli): simplify command options and improve documentation
- Removed the `--skill` option from the `dump-prompt` command, streamlining the command usage and focusing on essential parameters.
- Updated documentation to clarify the usage of the `dump-prompt` command and its parameters, enhancing user understanding.
- Cleaned up the `DumpFlags` structure by removing unused fields, contributing to a more maintainable codebase.
These changes improve the clarity and usability of the agent CLI, aligning with ongoing refactoring efforts.
* refactor(cli): streamline dotenv loading and clean up prompt rendering
- Introduced `load_dotenv_for_cli` to load environment variables for all CLI entrypoints, ensuring consistent configuration across commands.
- Updated documentation to clarify the purpose of the dotenv loading mechanism.
- Removed unnecessary blank lines in prompt rendering functions across multiple agents, enhancing code readability.
These changes improve the maintainability and clarity of the CLI and prompt handling, aligning with ongoing refactoring efforts.
* refactor(debug-agent-prompts): enhance environment loading and streamline workspace resolution
- Updated the script to load environment variables from a `.env` file, ensuring consistent configuration for prompt generation.
- Simplified workspace resolution by delegating to the binary's internal logic, improving reliability and reducing code duplication.
- Revised documentation to clarify the usage of command options and the impact of environment variables on prompt rendering.
These changes improve the maintainability and clarity of the debug agent prompts script, aligning with ongoing refactoring efforts.
* refactor(agent): remove category filter and simplify agent definitions
- Eliminated the `category_filter` from various agent definitions and related tests, streamlining the agent configuration.
- Updated the `run_list` function in `agent_cli.rs` to reflect the removal of category filtering, enhancing output clarity.
- Revised documentation and comments to remove references to the now-removed category filter, improving overall code maintainability.
These changes contribute to a cleaner and more efficient agent architecture, aligning with ongoing refactoring efforts.
* feat(agents): introduce integrations_agent and tools_agent for enhanced service handling
- Added the `integrations_agent` to manage service integrations via Composio, including a new TOML configuration and prompt structure.
- Introduced the `tools_agent` for general ad-hoc tasks using built-in OpenHuman tools, with its own configuration and prompt.
- Updated the loader to include both agents in the built-in agent list, increasing the total number of agents from 13 to 14.
- Revised orchestrator and welcome prompts to delegate integration tasks to the new `integrations_agent`, ensuring clarity in agent responsibilities.
- Enhanced tests to verify the registration and functionality of the new agents, improving overall test coverage.
These changes expand the capabilities of the agent architecture, allowing for more specialized handling of integrations and tool usage.
* refactor(agents): update references from skills_agent to integrations_agent
- Changed all instances of `skills_agent` to `integrations_agent` across various files, including prompts, CLI commands, and tool registrations.
- Updated documentation and comments to reflect the new agent name, ensuring clarity in agent responsibilities and usage.
- Revised debug scripts to align with the new prompt structure for the integrations agent.
These changes enhance consistency in the codebase and improve the clarity of agent interactions.
* refactor(agents): rename skills_agent to integrations_agent throughout the codebase
- Updated all instances of `skills_agent` to `integrations_agent` in various files, including tests, documentation, and comments.
- Ensured consistency in agent references to improve clarity in agent responsibilities and interactions.
- Revised related code structures to align with the new naming convention, enhancing overall maintainability.
These changes support the transition to the new agent architecture and improve code readability.
* refactor(prompts): implement dynamic prompt rendering for enhanced context handling
- Introduced `DynamicPromptSection` to allow prompts to be built dynamically using a function pointer, enabling real-time access to the `PromptContext`.
- Updated `SystemPromptBuilder` to support dynamic prompts, ensuring that late-arriving state like `connected_integrations` is accurately reflected in the rendered output.
- Revised the prompt handling logic in the agent builder to streamline the integration of dynamic prompts, improving overall flexibility and responsiveness.
These changes enhance the prompt generation process, aligning with the ongoing improvements in agent architecture and context management.
* refactor(prompts): refine delegation guide to display only connected integrations
- Updated the `render_delegation_guide` function to list only the toolkits that are actively connected, omitting unauthorized toolkits to prevent hallucinations during delegation.
- Revised related tests to ensure the prompt correctly reflects the current state of integrations, including scenarios where no integrations are connected.
- Introduced a new utility function to filter out welcome-only tools from non-welcome agents, enhancing the clarity and safety of tool visibility.
These changes improve the accuracy and focus of the delegation guide, aligning with the ongoing enhancements in agent prompt handling.
* refactor(planner): update tool usage and prompt guidelines for read-only operations
- Modified the `agent.toml` configuration to clarify that the planner operates in a read-only mode, specifying that it does not mutate the workspace or memory.
- Revised the prompt guidelines to reflect the read-only nature of the planner, emphasizing the need for explicit nodes for any required writes to be handled by downstream agents.
These changes enhance the clarity of the planner's operational constraints and improve the overall structure of the planning process.
* refactor(config): remove web search enable flag and update related configurations
- Eliminated the `OPENHUMAN_WEB_SEARCH_ENABLED` environment variable and associated logic, as web search is now always enabled by default.
- Updated the configuration schema to reflect the removal of the enable flag from `WebSearchConfig`.
- Adjusted tool registration to ensure web search is always available, simplifying the configuration process.
These changes streamline the web search functionality, ensuring it is consistently available across all sessions.
* refactor(config): update http_request flag to always enabled
- Changed the `http_request` configuration to always be enabled, removing the dependency on the `config.http_request.enabled` flag.
- This adjustment simplifies the configuration process and ensures consistent behavior across the application.
These changes contribute to a more streamlined configuration and enhance the overall reliability of the onboarding process.
* refactor(debug-agent-prompts): transition to dump-all command for agent prompts
- Replaced the previous method of listing agent IDs and dumping prompts with a new `dump-all` command that consolidates the functionality into a single call.
- Updated the script to handle output directory and workspace options more efficiently, leveraging Rust's `dump_all_agent_prompts` for processing.
- Enhanced the handling of the `integrations_agent` to generate separate dumps for each connected toolkit, improving the clarity and organization of output files.
- Revised related logging and summary generation to reflect the new structure, ensuring a more streamlined user experience.
These changes modernize the prompt dumping process, aligning it with the latest architectural improvements and enhancing usability.
* feat(composio): implement dynamic fetching of toolkit actions for integrations
- Added a new `fetch_toolkit_actions` function to retrieve the current action catalogue for a specified Composio toolkit, enhancing the responsiveness of the integrations agent.
- Updated the `subagent_runner` to utilize the fresh action list at spawn time, ensuring that the toolkit's actions reflect the latest backend state.
- Modified the `render_integrations_agent` function to refresh the action catalogue during prompt generation, improving the accuracy of the displayed tools.
These changes enhance the integration experience by providing up-to-date action information, aligning with the ongoing improvements in agent functionality.
* refactor(integrations-agent): update tool visibility and configuration handling
- Modified the `agent.toml` to replace `wildcard` with `named` tools, enhancing control over tool visibility for the integrations agent.
- Updated the `subagent_runner` to ensure that tool visibility aligns with the new TOML configuration, preventing unnecessary stripping of tools.
- Revised the `render_integrations_agent` function to respect the updated tool scope, improving the accuracy of the tool list generated for subagents.
These changes streamline the tool management process, ensuring that only explicitly defined tools are available during agent execution.
* feat(composio): add composio_list_connections tool for dynamic integration detection
- Introduced the `composio_list_connections` tool in the orchestrator's configuration, allowing the agent to detect newly-authorized Composio integrations mid-session.
- Enhanced the `ComposioListConnectionsTool` to filter and return only currently-connected integrations with ACTIVE or CONNECTED status, improving the accuracy of integration management.
- Updated the tool's description to clarify its functionality and usage context.
These changes enhance the agent's ability to manage integrations dynamically, aligning with ongoing improvements in the integration experience.
* fix(prompt): update delegation guide to reference Skills page
- Modified the `render_delegation_guide` function to change the reference from **Settings → Integrations** to the **Skills** page for connecting integrations. This update clarifies the user instructions for integration management.
* feat(session): introduce session key management for sub-agents
- Added `session_key` and `session_parent_prefix` fields to `ParentExecutionContext` to facilitate hierarchical transcript naming for sub-agents.
- Updated `persist_subagent_transcript` to generate transcript filenames based on the parent's session key, ensuring a flat file structure that reflects the parent-child relationship.
- Enhanced `AgentBuilder` and `Agent` to support the new session key management, allowing for better organization of session transcripts.
- Adjusted related functions to ensure proper handling of session keys during agent execution and transcript persistence.
These changes improve the clarity and organization of session transcripts, aligning with the ongoing enhancements in agent functionality.
* refactor(tests): update integrations agent tests for tool scope and transcript handling
- Renamed the `integrations_agent_is_wildcard` test to `integrations_agent_tool_scope_honours_toml` to better reflect its purpose of validating tool scope based on TOML configuration.
- Enhanced the test to assert that the `integrations_agent` correctly recognizes named tools instead of a wildcard.
- Removed the `integrations_agent_has_extra_tools_for_export` test as it is no longer relevant to the current tool management strategy.
- Improved the `latest_in_dir` function to clarify the handling of transcript naming schemes, ensuring proper differentiation between legacy and keyed formats.
These changes streamline the testing process and improve the accuracy of tool scope validation, aligning with recent updates in agent functionality.
* refactor(subagent_runner): improve transcript persistence and streamline inner loop
- Removed the `persist_subagent_transcript` function, transitioning transcript persistence to occur per-iteration within the `run_inner_loop`, enhancing reliability by ensuring transcripts are written immediately after each provider response.
- Updated the handling of session keys to maintain consistent naming for transcripts, reflecting the parent-child relationship in the file structure.
- Simplified the code by eliminating redundant post-loop transcript writes, aligning with recent changes in agent functionality and improving overall clarity in transcript management.
* refactor(agent_cli, subagent_runner, session): improve code readability and formatting
- Enhanced formatting in `agent_cli.rs` for better readability by adjusting the structure of string formatting.
- Streamlined conditional checks in `subagent_runner.rs` to improve clarity and maintainability.
- Simplified the handling of agent IDs in `builder.rs` to reduce line length and improve code flow.
- Updated test cases in `tests.rs` for better alignment and readability of expected values.
- Improved formatting in `debug_dump.rs` to enhance the clarity of toolkit action fetching and logging.
These changes collectively enhance the overall readability and maintainability of the codebase, aligning with ongoing refactoring efforts.
* fix(tests): add missing session_key fields to ParentExecutionContext stub
* fix: address PR review feedback
* fix(prompts-v2): round 2 PR review — dispatcher instructions, workspace-file preservation, cached-tool fallback, transcript persistence
- subagent_runner: populate PromptContext.dispatcher_instructions for Dynamic prompts (was empty string, dropping the ## Tool Use Protocol block in render_tools for PFormat/Json/Native sub-agents)
- subagent_runner: add post-tool persist_transcript after tool results are appended so a mid-round crash doesn't lose tool outputs
- prompts::sync_workspace_file: preserve user-edited workspace files — only overwrite when the file doesn't exist OR its current hash matches the stored builtin hash
- context::debug_dump: mirror runner's cached-tool fallback — keep cached action catalogue on empty/error from fetch_toolkit_actions instead of blanking it
- core::agent_cli: add entry/exit debug logs around dump_all / dump_prompt calls and a trace log around each prompt file write; update module banner to note --toolkit is required when --agent is integrations_agent
|
||
|
|
d545c193b9 |
feat(agent): fuzzy-filter skills_agent toolkit actions by task prompt (#579)
* feat(agent): fuzzy-filter skills_agent toolkit actions by task prompt Narrow large Composio toolkits (e.g. github ~500 actions) down to the handful relevant to a given delegation prompt before registering them as native tools on a spawned skills_agent. Falls back to the full catalogue when the filter yields fewer than MIN_CONFIDENT_HITS hits to avoid starving the sub-agent on under-specified prompts. Filter is only invoked when both `definition.id == "skills_agent"` and a `toolkit=` argument is present, so orchestrator and other sub-agents are unaffected. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(composio): mock toolkits route in ops integration test --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
ea088d9f15 |
feat(prompt): unified delegation guide + dynamic per-toolkit tool registration (#447) (#570)
* feat(prompt): unified delegation guide + dynamic per-toolkit tool registration (#447) Cuts main agent prompt token cost ~98% on accounts with connected integrations and replaces the generic Composio dispatcher with native per-action tool calling inside skills_agent. ## Why Issue #447: prompt payloads were ballooning because main/orchestrator re-shipped a full prose enumeration of every connected toolkit's actions on every turn (~13.7k tokens for one gmail integration alone), and skills_agent had no way to scope tools to a single toolkit so it inherited a flat dispatcher (composio_execute) that the LLM couldn't reliably call without first round-tripping composio_list_tools. ## What ### main / orchestrator prompt - Replace `ConnectedIntegrationsSection`'s per-action prose dump with a unified Delegation Guide: one bullet per integration (toolkit + one-line description + spawn snippet). Tokens added per integration: ~30. Savings vs old per-action listing: ~5k+ tokens per connected toolkit. - Drop every "Composio" reference from delegating-agent prose so the surface stays provider-neutral. ### skills_agent - Add a `toolkit` argument to `spawn_subagent` with three pre-flight validation modes resolved against the parent's connected integrations list before any LLM call: * missing toolkit -> ToolResult::error (model retries) * unknown toolkit -> ToolResult::error (model retries) * in allowlist, not connected -> ToolResult::success (model surfaces "authorize in Settings -> Integrations" to user; not flagged as a tool failure in the agent loop or web channel) - New `ComposioActionTool` (`src/openhuman/composio/action_tool.rs`) implements the `Tool` trait per Composio action. The sub-agent runner constructs ~N of these at spawn time from the cached integration overview and injects them via a new `extra_tools` parameter through `run_typed_mode` -> `run_inner_loop`. - `filter_tool_indices` drops every skill-category parent tool when `is_skills_agent_with_toolkit` is true so the only skill-category entries the sub-agent sees are the freshly-built per-action tools. This eliminates apify_*, composio_list_*, composio_authorize, and composio_execute from the toolkit-scoped surface. - Sub-agent renderer takes the parent's actual `tool_call_format` instead of hardcoding PFormat. Native dispatchers no longer carry a prose `## Tools` section at all (schemas already travel through the request body's `tools` field) — eliminates a ~30k-token duplication that was blowing past the model's context window. ### integration overview fetch - `fetch_connected_integrations_uncached` now merges Composio's toolkit allowlist with the user's active connections and returns one `ConnectedIntegration` per allowlisted toolkit with a `connected: bool` flag. Unconnected entries carry no schemas, just the toolkit name + description, so the orchestrator can mention them without trying to invoke them. - `ConnectedIntegrationTool` preserves the action's full JSON parameter schema so `ComposioActionTool` can advertise it through native function-calling. ### plumbing - `ParentExecutionContext` carries a `ComposioClient` and the parent's resolved `tool_call_format`, populated alongside `connected_integrations` in `Session::fetch_connected_integrations`. Triage and test paths pass `None` / `PFormat` defaults. - `dispatch_subagent` (the `SkillDelegationTool` path) plumbs its pre-bound skill_id through `toolkit_override` instead of the broken `skill_filter_override` (which used `{skill}__` prefix matching that never matched Composio's `TOOLKIT_*` naming). - `web::run_chat_task` failures now log the underlying error at WARN so debugging an in-flight failure no longer requires turning on TRACE for socket events. - `scripts/stage-core-sidecar.mjs` queries `cargo metadata` for the real target directory instead of assuming `<repo>/target` so the staging step works under workspace-level `target-dir` overrides (the vezures-workspace shared `.cargo-target` setup). ## Verified end-to-end Two RPC tests against a freshly-rebuilt sidecar (gmail connected, notion / slack / etc. allowlisted but not connected): | Test | Behavior | Tokens | Iterations | |---|---|---|---| | Connected (gmail, "fetch 5 unread emails") | spawn_subagent -> 62 dynamic gmail tools registered -> 1 GMAIL_FETCH_EMAILS call with smart args -> markdown table response | 42,911 input | 1 | | Not-connected (notion, "create a page") | main answers directly without spawning, tells user to authorize in Settings -> Integrations | 3,319 input | 1 | Both flows complete cleanly. The connected path proves dynamic per-action tool registration is working with full schema validation; the unconnected path proves the unified delegation guide + ToolResult::success return for not-connected toolkits keeps the model on a graceful path without polluting the chat with error styling. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(prompt): update test callers + assertions for new renderer signature Follow-up to #447. The main patch changed three signatures that test callers hadn't been updated for, and flipped one assertion that was validating the now-removed prose schema duplication. - `SubagentRunOptions` test constructors in subagent_runner.rs (2 sites) now pass `toolkit_override: None`. - `ConnectedIntegration` test constructor in orchestrator_tools.rs now passes `connected: true` (the default for test integrations — they're treated as authorized so delegation logic still runs). - 12 `render_subagent_system_prompt` test callers in prompt.rs now pass `&[]` for the new `extra_tools` slice and `ToolCallFormat::PFormat` for the new `tool_call_format` argument. - `render_subagent_system_prompt_honors_identity_safety_and_skills_flags` used to assert `rendered.contains("Parameters:")` on the Json dispatcher branch — that was valid in the old world where the prose `## Tools` section dumped full JSON schemas for Json/Native formats. The main patch deliberately removes that dump (it was the ~30k-token duplication of the native `tools` field), so the test now asserts the opposite: no `## Tools` header and no `Parameters:` line are emitted for Native/Json dispatchers. The schemas still travel through the provider request's `tools` field. Also picks up `rustfmt` rewraps in action_tool.rs and ops.rs from a background linter run — pure whitespace, no semantic change. Verified green against the full `cargo test --lib` suite for every test touched by this PR: - openhuman::context::prompt::tests (26 passed) - openhuman::agent::harness::subagent_runner::tests (19 passed) - openhuman::composio::ops::tests (2 passed) - openhuman::tools::impl::agent::tests (0 scoped) The 7 remaining failures in `cargo test --lib` are pre-existing Windows-path/filesystem flakes in subsystems this PR doesn't touch (self_healing polyfill path separator, cron scheduler shell spawning, local_ai::paths absolute-path detection, security::policy sandbox path handling, composio::trigger_history jsonl archive, and a real pre-existing `Option::unwrap()` panic in browser::screenshot). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(harness): add composio_client + tool_call_format to integration test stub Follow-up to #447. The `tests/agent_harness_public.rs` integration test constructs a `ParentExecutionContext` in `stub_parent_context` that was missing the two fields added in the main patch (`composio_client` and `tool_call_format`). `cargo test --lib` doesn't compile integration tests, which is why this slipped past local verification — it only surfaced on Linux CI. - `composio_client: None` — the stub parent has no composio client because these tests don't exercise the integration-overview path. - `tool_call_format: ToolCallFormat::PFormat` — default legacy format; none of the tests in this file exercise the sub-agent renderer's format branching, so PFormat is the safe pick. Verified locally that `cargo test --no-run` compiles all integration test targets including `agent_harness_public`. (The `agent_memory_loader_public` link error in the local run is a pre-existing Windows `libucrt`/`fgets` C-runtime issue unrelated to this PR — won't reproduce on Linux CI.) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(prompt,composio): address CodeRabbit review on #570 (#447) Four fixes from the CodeRabbit review of PR #570, ranked by impact: ## `context/prompt.rs` — Json dispatcher needs prose tool catalog The initial patch gated the prose `## Tools` section behind `matches!(tool_call_format, ToolCallFormat::PFormat)`, which conflated Json with Native. Only `ToolCallFormat::Native` uses the provider's native function-calling channel where schemas travel via the request body's `tools` field. `ToolCallFormat::Json` is a prompt-driven format (the model wraps JSON tool calls in `<tool_call>` tags) and relies on the prose catalog the same way PFormat does — without it the model sees protocol instructions but no visible tool names or schemas. Inverted the guard to `!matches!(tool_call_format, Native)` so PFormat and Json both render the `## Tools` section with their respective per-entry shapes (compact `Call as:` signature for PFormat, inline `Parameters:` JSON schema for Json). Updated the `render_subagent_system_prompt_honors_identity_safety_and_skills_flags` test: the Json assertion now expects `Parameters:` to be present again (reverting commit 2's flip), and a new Native-branch assertion guards against the ~54k-token schema duplication the original PR fixed. ## `composio/ops.rs` — don't cache degraded snapshots All three backend calls in `fetch_connected_integrations_uncached` (`list_toolkits`, `list_connections`, `list_tools`) previously returned `Some(Vec::new())` or fell through to an empty inner vec on transient errors. The outer `fetch_connected_integrations` caches whatever the uncached path returns, so a single transient 5xx would silently hide every integration, mark connected toolkits as disconnected, or register dynamic Composio tools with zero callable actions — until the cache is invalidated or the process restarts. Changed all three branches to return `None`, which signals the caller to NOT cache the result and retry on the next call. ## `composio/ops.rs` — prefix match needs a delimiter `starts_with(&slug.to_uppercase())` false-matches when two toolkit slugs share a text prefix (e.g. `git` vs `github`). The current allowlist doesn't trigger this, but adding a new toolkit could silently leak actions between integrations. Anchored the prefix with an underscore so `GMAIL_SEND_EMAIL` matches `gmail_`, not just `gmail`. ## `scripts/stage-core-sidecar.mjs` — resolve CARGO_TARGET_DIR vs repo root `resolve(process.env.CARGO_TARGET_DIR)` uses the process's current working directory, but the `cargo build` spawn below runs with `cwd: root`. For an absolute env var this is identical, but a relative `CARGO_TARGET_DIR` and a cwd outside the repo would make the two paths disagree and the binary lookup would miss. Defensive fix: `resolve(root, process.env.CARGO_TARGET_DIR)` so both paths anchor to the same base. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
1836c7691f |
Feat: smart routing (#569)
* chore: update OpenHuman version to 0.52.9 and add intelligent routing functionality - Bumped OpenHuman version from 0.52.7 to 0.52.9 in Cargo.lock files. - Introduced a new routing module that implements intelligent model routing based on task complexity and local model health. - Added a health checker for the local Ollama model server to improve routing decisions. - Enhanced the provider to classify tasks and determine the appropriate backend (local or remote) for processing requests. - Updated related files to support the new routing logic and ensure seamless integration with existing functionalities. * refactor(routing): streamline provider and enhance routing logic - Removed the `build_tool_instructions` function from the public API, simplifying the routing module. - Updated the `IntelligentRoutingProvider` to utilize a more efficient model resolution process, improving routing decisions based on task complexity and local model health. - Introduced a new `quality` module to assess response quality, enabling better fallback decisions when local responses are deemed low quality. - Enhanced the `RoutingHints` struct to provide more granular control over routing behavior, including privacy requirements and cost sensitivity. - Added tests to validate the new routing logic and quality assessment, ensuring robust functionality across various scenarios. * feat(tests): add live end-to-end routing tests for real backend integration - Introduced a new test file `live_routing_e2e.rs` containing end-to-end tests for routing against a live backend. - Tests require a valid backend URL, user session JWT, and real network interactions, hence marked as `#[ignore]`. - Implemented functionality to set up environment variables, write configuration files, and perform JSON-RPC calls to validate routing behavior. - Added assertions to ensure correct handling of various routing cases, enhancing test coverage for the routing module. * refactor(format): ran format command * feat(routing): add IntelligentRoutingProvider and enhance LocalHealthChecker - Introduced a new `factory.rs` file containing the `new_provider` function to construct an `IntelligentRoutingProvider` that integrates local AI capabilities with remote backend providers. - Enhanced the `LocalHealthChecker` in `health.rs` by adding a `reqwest::Client` for improved health probing, including better logging for cache hits and misses, and streamlined cache updates. - Updated health check logic to utilize the new client, ensuring more reliable health status checks for local AI services. * refactor(routing): move new_provider function to factory module - Moved the `new_provider` function from `mod.rs` to a new `factory.rs` module to improve code organization and maintainability. - Updated public exports to include the new location of `new_provider`, ensuring continued accessibility for constructing `IntelligentRoutingProvider` instances. - Removed the old implementation from `mod.rs`, streamlining the routing module's structure. * refactor(routing): simplify local task routing logic - Removed redundant conditions for routing medium tasks locally, streamlining the decision-making process in the `decide` function. - Updated comments to reflect the simplified logic, enhancing code clarity and maintainability. * docs(tests): clarify comments in json_rpc_e2e.rs regarding hint overrides logic. * refactor(tests): enhance live routing end-to-end tests with timeout handling - Introduced a timeout mechanism for reading SSE events to prevent indefinite blocking. - Updated environment variable management in tests to ensure safe access and cleanup. - Improved comments for clarity regarding the safety of environment variable mutations during tests. * refactor(tests): update SSE event reading in live routing tests. * refactor(routing): enhance medium task routing logic and update comments - Updated the routing logic for medium tasks to utilize hints for local bias, ensuring more accurate routing decisions. - Revised comments throughout the code to clarify the behavior of task categories and routing preferences. - Adjusted test cases to reflect the new routing logic, ensuring they accurately validate the expected behavior for medium tasks. * refactor(tests): implement timeout handling for dictation event reception - Added a timeout mechanism to the dictation event test to prevent indefinite blocking while waiting for the "pressed" event. - Enhanced the test logic to consume events until the expected event type is received, improving reliability and clarity in the test flow. --------- Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com> |
||
|
|
7685e877ee |
feat(agent): welcome->orchestrator routing + per-agent tool scoping (#525, #526) (#544)
* feat(agent): add subagents + delegate_name fields to AgentDefinition (#525, #526) Introduces the schema change needed to make agent definitions the single source of truth for both direct tools and delegation targets: - `subagents: Vec<SubagentEntry>` — declarative list of agents this agent can spawn, expanding at build time into synthesised delegate_* tools on the LLM's function-calling surface. Supports two TOML shapes via `#[serde(untagged)]`: * Bare string (`"researcher"`) → `SubagentEntry::AgentId` * Inline table (`{ skills = "*" }`) → `SubagentEntry::Skills(SkillsWildcard)` The `Skills` variant expands dynamically to one delegate_{toolkit} tool per connected Composio toolkit at runtime. - `delegate_name: Option<String>` — optional override for the tool name this agent is exposed as when another agent lists it in `subagents`. Defaults to `delegate_{id}` when absent, lets the researcher agent be exposed as `research`, code_executor as `run_code`, etc. Schema only — no runtime behavior change yet. Follow-up commits wire the field into `collect_orchestrator_tools`, the dispatch path, and the debug dump. TOML placement note: `subagents = [...]` must appear before the `[tools]` table header in agent TOMLs. Once a table section opens, every subsequent top-level key is consumed by that table, so placing `subagents` after `[tools]` parses it as `tools.subagents` and fails deserializing ToolScope. The test doc-comment records this constraint. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(agent): drive orchestrator delegation tools from TOML subagents (#525, #526) Completes the half-built migration from a hardcoded ARCHETYPE_TOOLS table + orphan skill_delegation.rs to a TOML-driven delegation surface where each agent declares its subagents and the tool list is synthesised from the registry at agent-build time. Rewrites `collect_orchestrator_tools` to take the orchestrator's AgentDefinition, the global AgentDefinitionRegistry, and the slice of connected Composio integrations, then iterates the definition's `subagents` field: * `SubagentEntry::AgentId` → one ArchetypeDelegationTool. The tool's `name()` comes from the target agent's `delegate_name` override (or `delegate_{id}` fallback) and its `description()` is the target's `when_to_use`. Editing an agent's TOML when_to_use now immediately updates the tool schema the orchestrator LLM sees — zero drift, no hardcoded description strings to keep in sync. * `SubagentEntry::Skills { skills = "*" }` → one SkillDelegationTool per connected Composio toolkit. Each routes to the generic skills_agent with `skill_filter` pre-populated. Empty integrations list (CLI path, or user not yet connected) produces zero tools rather than phantom `delegate_*` entries for unconnected toolkits. Also in this commit: - Wire the orphan `skill_delegation.rs` into `impl/agent/mod.rs` via `mod skill_delegation;` + `pub use SkillDelegationTool;`. The file has existed since earlier work but was never declared in the module tree, so it compiled as dead code. - Delete the legacy `MAIN_AGENT_TOOL_ALLOWLIST` constant and the `main_agent_tools` filter in `tools/ops.rs`. They were documented as "no longer the primary source of truth" since the from_config builder switched to `collect_orchestrator_tools`, and grep confirms no external callers remain. Clean deletion. - Delete the hardcoded `ARCHETYPE_TOOLS` const in `tools/impl/agent/mod.rs`. The 4-entry table has been replaced by the orchestrator TOML's `subagents` list (which covers those 4 plus archivist plus the skills wildcard), and the re-export in `tools/mod.rs` is removed accordingly. - Update `agents/orchestrator/agent.toml`: add the `subagents` field listing researcher / planner / code_executor / critic / archivist / { skills = "*" }. Keep `spawn_subagent` in `[tools] named` as an advanced fallback so power users can still spawn custom workspace- override agent ids that aren't in the declarative subagents list. - Add `delegate_name = "..."` to the 5 archetype TOMLs so the orchestrator LLM sees natural tool names (`research`, `plan`, `run_code`, `review_code`, `archive_session`) rather than the `delegate_<agent_id>` fallback. - Update `agent/harness/session/builder.rs` (line ~461) to call the new `collect_orchestrator_tools` signature. Looks up the orchestrator definition from the global registry; passes an empty integrations slice because the builder is synchronous and cannot await Composio's async fetch. The channel-dispatch path will populate integrations in a later commit — the CLI/REPL path ships without per-toolkit delegation tools, which is acceptable regression since CLI users still reach Composio via `composio_execute` and the retained `spawn_subagent` fallback. Tests: * 5 new unit tests in `orchestrator_tools.rs` cover the baseline AgentId + Skills wildcard expansion, empty-integrations edge case, unknown-id graceful skip, non-delegating agent with empty subagents, and the slug sanitiser for tool-name-safe Composio toolkit names. * Runs clean alongside all existing agent-module tests (323 pass; one pre-existing Windows-path failure in `self_healing::tests:: tool_maker_prompt_includes_command` is unrelated to this PR and fails identically on the upstream baseline). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(agent): plumb per-agent tool scoping through bus + tool loop (#525, #526) Adds the parameter plumbing for agent-aware tool filtering without changing any runtime behaviour. Every existing call site continues to pass `None` / empty extras, so the LLM still sees the full unfiltered registry — the actual routing logic that populates these fields lands in commit 4b (dispatch.rs onboarding-flag → target_agent_id). Why two parameters and not one filter: Tools in this codebase are `Box<dyn Tool>` — owned trait objects with no Clone impl, stored in a shared `Arc<Vec<Box<dyn Tool>>>`. We can't cheaply build a per-turn filtered subset of the global registry, and we can't mutate the Arc to remove entries. Two new parameters work around this without touching the global registry's lifetime model: * `visible_tool_names: Option<&HashSet<String>>` — whitelist filter applied at the iteration site inside `run_tool_call_loop`. When `Some(set)`, only tools whose `name()` is in the set contribute to the function-calling schema and are eligible for execution; every other tool in the combined registry is hidden from the model and rejected if the model emits a call for it. `None` preserves the legacy "everything visible" behaviour. * `extra_tools: &[Box<dyn Tool>]` — per-turn synthesised tools spliced alongside `tools_registry`. The dispatch path will use this to surface delegation tools (`research`, `delegate_gmail`, …) that are built fresh each turn from the active agent's `subagents` field and the current Composio integration list — tools that don't exist in the global startup-time registry because they depend on per-user runtime state. Empty slice for agents that don't delegate. Inside the loop, `tool_specs` is built from `tools_registry.iter().chain(extra_tools.iter()).filter(is_visible)`, and the tool-execution lookup uses the same chain + filter so the function-calling schema and the execution surface stay in sync. Files touched in this commit: src/openhuman/agent/harness/tool_loop.rs - Add `visible_tool_names` and `extra_tools` parameters to `run_tool_call_loop`. Build `tool_specs` from chained iteration with the visibility filter applied. Replace the `find_tool` call at the execution site with an inline chain+filter lookup so hallucinated calls to filtered-out tools surface as "unknown tool" errors. Drop the now-unused `find_tool` import. - Update the legacy `agent_turn` wrapper to pass `None, &[]`, preserving its existing unfiltered behaviour. - Update all 9 in-file test sites to pass `None, &[]`. src/openhuman/agent/harness/tests.rs - Update all 3 `run_tool_call_loop` test sites to pass `None, &[]`. src/openhuman/agent/bus.rs - Add `target_agent_id: Option<String>`, `visible_tool_names: Option<HashSet<String>>`, and `extra_tools: Vec<Box<dyn Tool>>` fields to `AgentTurnRequest`, with rustdoc explaining each. - Destructure the new fields in the `agent.run_turn` handler; thread `visible_tool_names.as_ref()` and `&extra_tools` through to `run_tool_call_loop`. Augment the dispatch trace with target_agent / extra_tool_count / visible_tool_count / filter_active so production logs show whether scoping is active. - Update the in-test `test_request()` helper to populate the new fields with safe defaults. src/openhuman/agent/triage/evaluator.rs - Update the triage `AgentTurnRequest` initializer to set `target_agent_id = Some("trigger_triage")` (for tracing) with `visible_tool_names: None` + `extra_tools: Vec::new()` because the classifier intentionally runs against an empty registry and emits a structured JSON decision rather than calling tools. src/openhuman/channels/runtime/dispatch.rs - Update the channel-message `AgentTurnRequest` initializer to set the three new fields to safe defaults (`None` / `None` / empty vec). Commit 4b will replace these with the real onboarding-flag based routing. src/openhuman/tools/impl/agent/mod.rs - Bug fix: `dispatch_subagent` previously took `_skill_filter: Option<&str>` but discarded the value, hardcoding `SubagentRunOptions::skill_filter_override = None`. That meant `SkillDelegationTool::execute()` synthesising `dispatch_subagent("skills_agent", ..., Some("gmail"))` never actually narrowed `skills_agent`'s tool list — so even with the orchestrator's view scoped, the spawned `skills_agent` subagent would still see the full Composio catalog. Drop the underscore, propagate `skill_filter` into `skill_filter_override`, and add a tracing log line to make this path observable. This is the downstream half of the #526 leak that commit 3's orchestrator- side scoping alone wouldn't have caught. Tests: 8/8 `tool_loop` tests pass, 3/3 harness `tests.rs` cases pass, 323/324 agent module tests pass overall (the one failure is the same pre-existing Windows-path bug in `self_healing::tool_maker_prompt_ includes_command` that fails identically on the upstream baseline). No existing test expectations were changed. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(dispatch): route channel messages to welcome/orchestrator by onboarding flag (#525) Wires the per-agent tool scoping plumbing from commit 4a into the channel-message dispatch path. Each incoming channel message now picks the active agent — `welcome` pre-onboarding, `orchestrator` post — based on `Config::onboarding_completed`, loads the matching definition from the global `AgentDefinitionRegistry`, synthesises any `delegate_*` tools the agent declares in its `subagents` field, and passes everything through to `agent.run_turn` on the bus. This is the half of #525 that makes the welcome agent actually run for new users — the welcome definition has existed since upstream PR #522 but had no caller; nothing in dispatch consulted the onboarding flag, so every channel message ran through the same generic tool loop with the full registry exposed. Changes: src/openhuman/channels/runtime/dispatch.rs - New `AgentScoping` struct carrying the three new `AgentTurnRequest` fields (`target_agent_id`, `visible_tool_names`, `extra_tools`) plus an `unscoped()` constructor for safe-fallback paths. - New async `resolve_target_agent(channel)` helper: * fresh `Config::load_or_init().await` per turn (no cache — the loader reads from disk every call, verified at `config/schema/load.rs:409`, so the welcome→orchestrator handoff is observed on the next message after `complete_onboarding(complete)` flips the flag, with no need for an explicit handoff event); * picks `"welcome"` or `"orchestrator"` based on the flag and emits a structured `[dispatch::routing] selected target agent` info trace recording the choice + the flag value, satisfying the #525 acceptance criterion `"agent-selection logs clearly record why each agent was selected at onboarding boundaries"`; * looks up the definition in `AgentDefinitionRegistry::global()`, gracefully falling back to `AgentScoping::unscoped()` (= legacy behaviour, no filter, no extras) if the registry isn't initialised or the definition isn't found, so a routing miss never fails the user message; * for agents with a non-empty `subagents` field, awaits `composio::fetch_connected_integrations(&config)` and runs `orchestrator_tools::collect_orchestrator_tools` to materialise per-turn delegation tools (`research`, `plan`, `delegate_gmail`, …). Agents with empty `subagents` get an empty extras vec. - New `build_visible_tool_set(definition, &extra_tools)` helper that returns `Some(union)` for `ToolScope::Named` agents (their named list ∪ the names of the synthesised delegation tools) and `None` for `ToolScope::Wildcard` agents to preserve the unfiltered semantics — so agents like `skills_agent` and `morning_briefing` that already work via `wildcard + category_filter` keep their existing behaviour without this layer interfering. - `process_channel_message` calls `resolve_target_agent` once per turn, drops the placeholder defaults from commit 4a, and feeds the real `target_agent_id`/`visible_tool_names`/`extra_tools` into `AgentTurnRequest`. - New imports: `AgentDefinition`, `AgentDefinitionRegistry`, `ToolScope`, `Config`, `fetch_connected_integrations`, `orchestrator_tools`, `Tool`, `HashSet`. End-to-end behaviour after this commit: 1. New user, `onboarding_completed=false`: dispatch picks `welcome`, loads its 2-tool TOML scope, builds `visible_tool_names = {complete_onboarding, memory_recall}`, no extras, hands off to the bus. Bus handler applies the filter → welcome's LLM sees exactly 2 tools. 2. Welcome agent guides the user through setup, eventually calls `complete_onboarding(action="complete")` → flag persists to disk via `config.save()`. 3. Next user message: dispatch reads the flag fresh, picks `orchestrator`, fetches connected Composio integrations, expands `subagents = ["researcher", "planner", "code_executor", "critic", "archivist", { skills = "*" }]` into delegate_research / delegate_plan / delegate_run_code / delegate_review_code / delegate_archive_session + one delegate_<toolkit> per connected integration. visible_tool_names is the union with the 4 direct tools from orchestrator's `[tools] named` list. LLM sees the scoped delegation surface, not the full 1000+ Composio catalog. #526's runtime leak is now fixed end-to-end: the orchestrator's LLM prompt only contains the tools its TOML allows, and the SkillDelegationTool path narrows skills_agent to a single toolkit via the `skill_filter` propagation fix from commit 4a. No agent at any layer sees more than its definition declares. Tests: 599/599 channel module tests pass — including `runtime_dispatch::dispatch_routes_through_agent_run_turn_bus_handler` and the telegram integration variant, which exercise the full bus roundtrip with the new fields populated. No existing assertions were modified. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(debug_dump): apply orchestrator definition filter to main dump (#526) Replaces the explicit `empty_filter: HashSet::new()` in `render_main_agent_dump` with a real visibility whitelist derived from the orchestrator's `AgentDefinition`. The "main" dump path now mirrors the runtime dispatch path from commits 4a/4b — same definition, same delegation tool synthesis, same filter — so `openhuman agent dump-prompt main` shows what the LLM actually sees in production instead of the unfiltered global registry. Before this commit, `dump-prompt main` always rendered every tool in the registry regardless of which agent was supposed to run, which is exactly the symptom #526 reports: "agent prompt tool scopes leak full GitHub tool catalog". The runtime fix in commit 4b stops the leak in production but the dump path was the user's primary observability tool for inspecting prompts, so leaving it unscoped would mask future regressions and confuse debug sessions. Changes in `src/openhuman/context/debug_dump.rs`: * `dump_agent_prompt` now loads `AgentDefinitionRegistry` once at the top (previously only loaded inside the sub-agent branch). When the request is for "main" or "orchestrator_main", it looks up the "orchestrator" definition from the registry and passes it into `render_main_agent_dump` along with the registry itself. Missing orchestrator entry → structured error listing known agents instead of silently rendering an unfiltered prompt. * `render_main_agent_dump` signature gains `registry: &AgentDefinitionRegistry` and `orchestrator_def: &AgentDefinition`. Inside, it: - calls `collect_orchestrator_tools(orchestrator_def, registry, connected_integrations)` to synthesise the same per-turn delegation tools (`research`, `plan`, `delegate_<toolkit>`, …) that dispatch generates; - extends `prompt_tools` with the synthesised extras so they contribute to the rendered tool catalogue; - builds `visible_filter: HashSet<String>` from `orchestrator_def.tools` (the `[tools] named` list) ∪ the names of the synthesised extras, falling back to an empty HashSet when the orchestrator definition uses `ToolScope::Wildcard` (which the prompt builder treats as "no filter, every tool visible") so dump consumers that supply a wildcard orchestrator (custom workspace overrides, tests) retain the legacy unscoped behaviour; - replaces `visible_tool_names: &empty_filter` in the `PromptContext` with `&visible_filter`; - filters the returned `tool_names` and `skill_tool_count` by the same predicate so the `DumpedPrompt` summary fields match what the prompt text actually contains. Tests: * Replaces the previous `render_main_agent_dump_includes_tool_ instructions_and_skill_count` test with two more focused cases: 1. `render_main_agent_dump_wildcard_scope_shows_full_tool_set` — regression guard for the legacy wildcard path. Builds a wildcard-scoped orchestrator definition, asserts every tool from `tools_vec` survives, and checks the standard system- prompt skeleton (Tools section, Tool Use Protocol, cache boundary) still renders. 2. `render_main_agent_dump_named_scope_filters_to_whitelist` — the #526 regression guard. Builds an orchestrator with `ToolScope::Named(["query_memory", "ask_user_clarification"])` and a `tools_vec` containing `shell`, `query_memory`, and `GMAIL_SEND_EMAIL`. Asserts the dump's `tool_names` is exactly `["query_memory"]` — `shell` and `GMAIL_SEND_EMAIL` are in the global registry but NOT in the whitelist, so they MUST be excluded. If a future change reintroduces the unfiltered behaviour this test fails immediately. * Adds two test helpers: `wildcard_orchestrator_def()` builds a minimal orchestrator definition with all `omit_*` flags set and `ToolScope::Wildcard`, and `registry_with_orchestrator(orch)` wraps it in an `AgentDefinitionRegistry` so the tests can call `render_main_agent_dump` without going through the full TOML loader. 11/11 debug_dump tests pass. The two new guards plus the 9 existing sub-agent / filter / composio-stub tests all run clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(dispatch): unit tests for build_visible_tool_set + cargo fmt cleanup (#525, #526) Adds focused unit tests for the per-agent scoping helper landed in commit 4b and runs `cargo fmt` across the files touched by this PR. Why scoping unit tests, not full integration tests: `resolve_target_agent` is async and reads `Config::load_or_init().await` which does a real disk read every call (no cache, verified at `config/schema/load.rs:409`). Mocking that requires either spinning up a full workspace under a temp dir with a config.toml containing the right `onboarding_completed` value, or adding a test-only injection point on the public Config API. Both are tractable but invasive enough to belong in their own follow-up PR. The end-to-end dispatch path is already covered by the existing channel integration tests (`dispatch_routes_through_agent_run_turn_bus_handler` etc.) which exercise the full bus roundtrip with the new fields populated, and which still pass after the new resolver landed (it gracefully falls back to `AgentScoping::unscoped()` when no orchestrator definition is registered in the test environment). Pure-function unit tests for `build_visible_tool_set` cover the branching logic that does the actual scoping work: how the named whitelist + extras union is built, how Wildcard scope is preserved, how duplicates are de-duplicated, etc. That's the part most likely to drift in future changes, so it's the part most worth fencing with focused tests. Tests added (all in `src/openhuman/channels/runtime/dispatch.rs` under the new `scoping_tests` module): * `wildcard_scope_yields_none_filter` — `ToolScope::Wildcard` must produce `None` regardless of whether extras are present, so skills_agent / morning_briefing keep their full skill-category catalogue. * `named_scope_without_extras_returns_named_only` — the welcome agent's path: 2 named tools, no delegation, exactly 2 entries in the visibility whitelist. * `named_scope_with_extras_returns_union` — the orchestrator's path: 3 direct named tools + 3 synthesised extras (research, delegate_gmail, delegate_github) → 6 entries. * `empty_named_with_extras_returns_extras_only` — guards a future "delegation-only" agent layout where the agent has no direct tools of its own, just spawns subagents. * `empty_named_with_no_extras_returns_empty_set` — guards the distinction between `None` (no filter, all visible) and `Some(empty)` (filter active, nothing matches). Important because the prompt loop's `is_visible` check treats them differently. * `duplicate_names_across_named_and_extras_are_deduplicated` — the HashSet handles collisions automatically, but the test pins that behaviour so a future migration to `Vec<String>` (which would silently double-count) gets caught. * `agent_scoping_unscoped_has_no_filter_or_extras` — pins the safe-fallback constructor's contract. Used when the registry is uninitialised or the target agent is missing — every field must default to "no scoping" so the channel turn falls back to legacy unfiltered behaviour rather than crashing. Plus `cargo fmt` run across the 6 files modified by this PR. No behavioural changes. Final test status across all commits 2-6 in this PR: * agent::harness::definition: 10/10 ✅ (4 new for Subagents schema) * agent::harness::tool_loop: 8/8 ✅ * agent::harness::tests: 3/3 ✅ * tools::orchestrator_tools: 5/5 ✅ (5 new) * channels::*: 599/599 ✅ (incl. dispatch integration) * channels::runtime::dispatch::scoping_tests: 7/7 ✅ (7 new) * context::debug_dump: 11/11 ✅ (1 replaced + 1 new) * Total agent module: 323/324 (one pre-existing Windows path failure in `self_healing::tool_maker_prompt_includes_command` confirmed identical against upstream/main baseline) Pre-existing Windows-environment test failures NOT caused by this PR and out of scope (all confirmed identical on upstream baseline; CI on Linux is unaffected): * self_healing::tool_maker_prompt_includes_command (PathBuf separator) * cron::scheduler::run_job_command_success / _failure (Unix shell) * composio::trigger_history::archives_triggers_in_daily_jsonl... (path) * local_ai::paths::target_paths_preserve_absolute_overrides (path) * security::policy::checklist_root_path_blocked (POSIX absolute) * security::policy::checklist_workspace_only_blocks_all_absolute (POSIX) * tools::implementations::browser::screenshot::screenshot_command_ contains_output_path (browser binary lookup) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(welcome): upgrade bare-install nudge with concrete integration pitches (#525) Follow-up to #522 that addresses a rough UX edge in the welcome agent prompt: users who arrive with only an API key configured (no channels, no Composio integrations, no web search / browser / local AI) were getting a "gentle suggestion" to connect something without any concrete picture of what they'd actually unlock. The welcome agent would finish onboarding, hand off to orchestrator, and leave the user staring at a functional-but-empty assistant with no roadmap for how to make it useful. This commit rewrites the prompt to handle sparse setups explicitly. No Rust changes — this is prompt.md only, picked up at build time via the existing `include_str!` loader in `agents/mod.rs`. Changes to `src/openhuman/agent/agents/welcome/prompt.md`: * Step 2's "point out what's missing" sub-point is rewritten from a single "gently suggest" line into a four-case decision tree keyed off `check_status` state: - No API key → critical, block completion. - Integrations yes, channels no → note the Tauri-only reach limitation, suggest a messaging platform. - Channels yes, integrations no → degraded assistant, nudge toward Composio. - Nothing beyond the API key → the "bare install" case, gets the new Step 2.5 treatment. * New **Step 2.5: Handling a bare install** section added after Step 2. Spells out what the user DOES have (sandboxed reasoning + coding assistant with memory), what they're MISSING (any external action), and how to structure the message: state the current capability honestly, pitch 2-3 specific integrations with concrete example prompts, point to Settings → Integrations / Channels, and leave room for the user to opt into the coding-only experience if that's what they actually want. For bare-install users the word budget stretches to 250-400 words (up from 200-350) so the concrete pitches and example prompts actually fit without cramming. * New **Integration capability reference** section giving the LLM a menu it can draw from when pitching integrations. Each entry is a one-line "connect X → I can Y" with a concrete example prompt the user could send next: - Gmail: "Summarise the most important emails that came in overnight and flag anything that needs a reply today." - Google Calendar: "What's on my calendar tomorrow, and do I have a 30-minute gap before 2pm?" - GitHub: "List open issues on my main project tagged 'bug' and summarise which ones look newest or most urgent." - Notion: "Pull up my 'Ideas' Notion database and show me the three newest entries." - Slack / Discord / Linear / Jira / etc. with similar shapes. Plus a sub-section for messaging platforms (Telegram / Discord / Slack / iMessage / WhatsApp / Signal / web-fallback) that clarifies which each is best for, and a sub-section for the other capabilities (web search, browser automation, HTTP requests, local AI) that explains what breaks without them. The LLM is told NOT to list everything — just pick 2-3 most likely to matter, defaulting to Gmail + GitHub + one of {Calendar, Notion} as the top-3 pitch when no profile context is available. * Tone guidelines updated to document the stretched word budget for bare installs (200-350 for configured users, 250-400 for bare installs). * "What NOT to do" list updated: - Explicitly allows product-tour-style listing ONLY in the bare-install case (Step 2.5), forbids it elsewhere. - Clarifies that describing what WOULD unlock with integration X is fine and encouraged; claiming a capability the user doesn't have is still forbidden. - Adds a new "Don't gloss over a bare install" entry that pins the rule: API-key-only users get concrete pitches and example prompts, not vague suggestions. Scope note: this commit does NOT change the completion logic. `complete_onboarding(complete)` still accepts API-key-only as the minimum bar — that's a separate design question for the maintainer about whether zero-integration users should be gatekept. This change improves what the welcome agent SAYS to those users, not whether they're allowed to proceed. Tests: all 14 `agent::agents::tests` pass (including `welcome_has_onboarding_and_memory_tools` which validates the welcome agent's declarative shape is unchanged). The prompt.md edit is pure content — no schema changes, no tool additions. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(web-channel): route Tauri in-app chat to welcome/orchestrator + Windows fsync fix (#525) Closes the web-channel-side half of the #525 welcome agent routing. Also bundles a small pre-existing Windows compatibility fix for `app_state::ops::sync_parent_dir` that was blocking end-to-end testing of this branch on Windows. ## Web channel routing (primary change) Commit 4b ( |
||
|
|
3a20599f45 |
feat: dynamic connected integrations in agent system prompts (#520)
* feat(agent): add support for connected integrations in system prompts - Introduced a new `fetch_connected_integrations` method to retrieve and populate active Composio integrations for the agent. - Updated the `Agent` struct to include a `connected_integrations` field, allowing the system prompt to display available external services. - Enhanced the `build_system_prompt` method to incorporate connected integrations, improving the context provided to users during interactions. - Added a `ConnectedIntegrationsSection` to the prompt rendering, ensuring visibility of active integrations in the system prompt output. - Overall, these changes enhance the agent's ability to leverage connected services, improving user experience and interaction capabilities. * feat(debug_dump): integrate connected integrations into agent prompt dumps - Added a new `fetch_connected_integrations_for_dump` function to retrieve active integrations for the agent during prompt dumps. - Updated the `render_main_agent_dump` function to include connected integrations, enhancing the context provided in the debug output. - Improved the overall structure and clarity of the debug dump process, ensuring that connected integrations are accurately represented in the agent's prompt context. * refactor(agent): streamline integration fetching for system prompts - Refactored the `fetch_connected_integrations` method in the `Agent` struct to delegate integration fetching to a new centralized function in the `composio` module, enhancing code clarity and maintainability. - Updated the `fetch_connected_integrations_for_dump` function to utilize the new centralized fetching logic, ensuring consistent integration retrieval across different contexts. - Improved the overall structure of integration handling, allowing for better error management and logging during the fetching process. * feat(agent): add connected integrations support to parent execution context - Introduced a new field `connected_integrations` in the `ParentExecutionContext` struct to store active Composio integrations. - Updated relevant functions to utilize the new `connected_integrations` field, ensuring that system prompts and agent dumps reflect the current integrations. - Enhanced the integration cache management by implementing cache invalidation logic when connections are created or deleted, improving the accuracy of integration data across sessions. - Overall, these changes enhance the agent's ability to leverage connected services, providing users with better context during interactions. * feat(agent): initialize connected integrations in subagent context - Added a `connected_integrations` field to the `ParentExecutionContext` and `Agent` struct, allowing for the storage and retrieval of active Composio integrations. - Updated the `dispatch_target_agent` function to populate the `connected_integrations` field when creating a new sub-agent context. - Enhanced the `fetch_connected_integrations` method to return an `Option<Vec<ConnectedIntegration>>`, improving error handling and caching logic. - These changes improve the agent's ability to manage and utilize connected integrations, enhancing user interactions and context awareness. * refactor(agent): improve caching logic in fetch_connected_integrations - Updated the `fetch_connected_integrations` function to handle caching more effectively by using a match statement. - The function now caches results only when the backend is reachable, preventing unnecessary caching when the client is unavailable. - This change enhances error handling and ensures that subsequent calls with different configurations can retry without stale data. * style: apply cargo fmt formatting * feat(agent): enhance connected integrations handling and caching - Updated the `dispatch_target_agent` function to initialize connected integrations for sub-agents, ensuring they have access to the latest integrations. - Improved the caching mechanism for connected integrations by using a `HashMap` keyed by configuration identity, allowing for user-specific caching and better isolation of integration data. - Refactored the `invalidate_connected_integrations_cache` function to clear the entire cache instead of setting it to `None`, enhancing cache management. - Added a new method `load_from_default_paths` in the `Config` struct to reliably load user configurations without being affected by environment variable overrides, improving the debug dump process. - Enhanced the rendering of connected integrations in system prompts to provide clearer instructions based on available tools, improving user interaction clarity. * feat(agent): add method to set connected integrations - Introduced a new `set_connected_integrations` method in the `Agent` struct to allow for replacing the agent's connected integrations from external sources, enhancing flexibility in integration management. - Updated the caching mechanism for connected integrations to utilize `LazyLock`, improving initialization efficiency and thread safety. * style: apply cargo fmt |