From c749f78a7bcad274c0d398241c871cb80974409d Mon Sep 17 00:00:00 2001 From: Fabricio Medrano <48396639+fabricio3g@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:32:46 -0300 Subject: [PATCH 1/2] feat(search): let the model choose result counts; drop the results setting Settings -> Search had a "Target results" field (default 6) left over from the old Electron search. It fed plain chat search and was copied into the core's web.json, while the Home web_search tool ignored it and used a fixed 8/12/18 by depth. - Remove the field, its copy in every locale, `search.max_results` from the config types and defaults (an old saved value is deleted on load), and stop syncing it to the core. - Home `web_search` exposes `max_results` (1-50) to the model and uses what it asks for; the depth's 8/12/18 applies only when it gives none. The search engine takes the caller's count up to 50. - Home research no longer refuses a search once it judges the evidence sufficient: the model searches as much as it needs, bounded only by the turn's tool budget and the identical-call loop guard. - Core `web_search` describes `max_results` as the model's choice. --- apps/desktop/main/agente/core-web.ts | 4 --- apps/desktop/main/config.defaults.ts | 1 - apps/desktop/main/config.migrate.ts | 6 +++-- apps/desktop/main/config.types.ts | 1 - apps/desktop/main/search-engine.ts | 9 +++++-- .../settings/SearchSettings.spec.ts | 1 - .../components/settings/SearchSettings.svelte | 17 ------------ .../settings/UnifiedSettingsPanel.svelte | 13 +-------- apps/desktop/renderer/src/lib/locales/de.json | 2 -- apps/desktop/renderer/src/lib/locales/en.json | 2 -- apps/desktop/renderer/src/lib/locales/es.json | 2 -- apps/desktop/renderer/src/lib/locales/fr.json | 2 -- apps/desktop/renderer/src/lib/locales/ja.json | 2 -- .../renderer/src/lib/locales/pt-BR.json | 2 -- apps/desktop/renderer/src/lib/locales/zh.json | 2 -- .../src/lib/services/agent-home-policy.ts | 21 +++++---------- .../src/lib/services/agent-tool-core.spec.ts | 27 ++++++++++++++++++- .../src/lib/services/agent-tool-core.ts | 16 ++++++++++- .../src/lib/services/agent-tooling.ts | 11 ++++++-- .../renderer/src/lib/services/chat-api.ts | 3 +-- .../renderer/src/lib/services/search.ts | 1 - .../src/lib/stores/app-store-config.ts | 1 - .../renderer/src/lib/stores/app.svelte.ts | 1 - apps/desktop/renderer/src/lib/types/chat.ts | 1 - .../tests/unit/config.defaults.test.js | 2 +- .../desktop/tests/unit/config.migrate.test.js | 22 +++++++++------ apps/desktop/tests/unit/config.redact.test.js | 1 - apps/desktop/tests/unit/core-web.test.js | 2 -- crates/agente-core/src/tools/web/search.rs | 4 ++- 29 files changed, 87 insertions(+), 92 deletions(-) diff --git a/apps/desktop/main/agente/core-web.ts b/apps/desktop/main/agente/core-web.ts index 782be413..f4d75a85 100644 --- a/apps/desktop/main/agente/core-web.ts +++ b/apps/desktop/main/agente/core-web.ts @@ -9,13 +9,11 @@ type Rpc = Pick; type SearchSettings = { provider?: string; - max_results?: number; providers?: Record; }; export type WebSyncPayload = { provider: string; - max_results?: number; searxng_url?: string; keys: Record; }; @@ -36,8 +34,6 @@ export function webSyncPayload(search: SearchSettings | undefined): WebSyncPaylo const payload: WebSyncPayload = { provider: text(search?.provider) || 'auto', keys }; const searxng = text(providers.searxng?.base_url); if (searxng) payload.searxng_url = searxng; - const max = Number(search?.max_results); - if (Number.isFinite(max) && max > 0) payload.max_results = Math.round(max); return payload; } diff --git a/apps/desktop/main/config.defaults.ts b/apps/desktop/main/config.defaults.ts index 42cf586c..dbaf462c 100644 --- a/apps/desktop/main/config.defaults.ts +++ b/apps/desktop/main/config.defaults.ts @@ -157,7 +157,6 @@ export function getDefaultSearchConfig(): SearchConfig { return { // Auto: a keyed search API when one is set up, else the free API sources. provider: 'auto', - max_results: 6, aggregator_engines: [...DEFAULT_AGGREGATOR_ENGINES], safe_search: 2, providers: {}, diff --git a/apps/desktop/main/config.migrate.ts b/apps/desktop/main/config.migrate.ts index 751d8496..05a34786 100644 --- a/apps/desktop/main/config.migrate.ts +++ b/apps/desktop/main/config.migrate.ts @@ -215,8 +215,10 @@ export function ensureSearchConfig(cfg: AppConfig): boolean { } } - if (!search.max_results) { - search.max_results = 6; + // The result-count setting is gone: each search mode and agent tool + // asks for its own count. Drop a value saved by an older version. + if ('max_results' in search) { + delete search.max_results; dirty = true; } diff --git a/apps/desktop/main/config.types.ts b/apps/desktop/main/config.types.ts index c37972d6..c63a37e3 100644 --- a/apps/desktop/main/config.types.ts +++ b/apps/desktop/main/config.types.ts @@ -194,7 +194,6 @@ export interface RAGConfig { export interface SearchConfig { provider: string; - max_results: number; context_budget_chars?: number; aggregator_engines?: string[]; safe_search?: number; diff --git a/apps/desktop/main/search-engine.ts b/apps/desktop/main/search-engine.ts index b7f8e966..0995cb7b 100644 --- a/apps/desktop/main/search-engine.ts +++ b/apps/desktop/main/search-engine.ts @@ -291,7 +291,12 @@ export async function webSearch({ query, context, deep, mode, options }: { query const requestedProvider = normalizeProviderName(options?.provider || 'auto'); // A saved choice of a removed provider (a scraper or reseller) searches with auto. const explicitProvider = REMOVED_SEARCH_PROVIDERS.includes(requestedProvider) ? 'auto' : requestedProvider; - const maxResults = Math.max(1, Math.min(Number(options?.max_results) || 6, 20)); + // The caller (the model, through its tool) says how many results it wants; + // with no count the depth decides. There is no user setting for this. + const requestedResults = Math.round(Number(options?.max_results)); + const maxResults = Number.isFinite(requestedResults) && requestedResults >= 1 + ? Math.min(requestedResults, 50) + : searchMode === 'max' ? 18 : searchMode === 'deep' ? 12 : 8; const searchOptions = { ...(options || {}), conversation_context: conversationContext, search_query: effectiveQuery || normalizedQuery }; const emit = (step: string, detail: string) => { @@ -403,7 +408,7 @@ export async function webSearch({ query, context, deep, mode, options }: { query } const responseLimit = searchMode === 'max' - ? Math.min(40, Math.max(maxResults * 2, 18)) + ? Math.max(maxResults, Math.min(40, Math.max(maxResults * 2, 18))) : searchMode === 'deep' ? Math.max(maxResults, 12) : maxResults; diff --git a/apps/desktop/renderer/src/lib/components/settings/SearchSettings.spec.ts b/apps/desktop/renderer/src/lib/components/settings/SearchSettings.spec.ts index cc84531f..c00e3ae0 100644 --- a/apps/desktop/renderer/src/lib/components/settings/SearchSettings.spec.ts +++ b/apps/desktop/renderer/src/lib/components/settings/SearchSettings.spec.ts @@ -43,7 +43,6 @@ function renderSearch(provider = 'aggregator') { return render(SearchSettings, { props: { searchProvider: provider, - searchMaxResults: '6', searchApiKey: '', searchBaseUrl: '', searchModel: 'sonar', diff --git a/apps/desktop/renderer/src/lib/components/settings/SearchSettings.svelte b/apps/desktop/renderer/src/lib/components/settings/SearchSettings.svelte index 9c7f8911..d8cefaa3 100644 --- a/apps/desktop/renderer/src/lib/components/settings/SearchSettings.svelte +++ b/apps/desktop/renderer/src/lib/components/settings/SearchSettings.svelte @@ -66,7 +66,6 @@ let { searchProvider = $bindable(), - searchMaxResults = $bindable(), searchApiKey = $bindable(), searchBaseUrl = $bindable(), searchModel = $bindable(), @@ -78,7 +77,6 @@ savingConfiguration = false, }: { searchProvider: string; - searchMaxResults: string; searchApiKey: string; searchBaseUrl: string; searchModel: string; @@ -218,21 +216,6 @@ /> - - - - ({ searchProvider, - searchMaxResults, aggregatorEngines, searchSafeSearch, }))); @@ -131,16 +128,10 @@ return searchApiKey.trim().length > 0; } - function normalizedMaxResults(): number { - const parsed = Number(searchMaxResults); - return Number.isFinite(parsed) ? Math.max(1, Math.min(Math.round(parsed), 20)) : 6; - } - function currentSearchPreferences(): SearchPreferences { const canActivateProvider = providerHasConfiguration(searchProvider); return { provider: canActivateProvider ? searchProvider : persistedSearchProvider, - max_results: normalizedMaxResults(), aggregator_engines: [...aggregatorEngines], safe_search: Number(searchSafeSearch), }; @@ -174,7 +165,7 @@ }); $effect(() => { - const signature = JSON.stringify({ searchProvider, searchMaxResults, aggregatorEngines, searchSafeSearch }); + const signature = JSON.stringify({ searchProvider, aggregatorEngines, searchSafeSearch }); if (!mounted || signature === previousSearchSignature) return; previousSearchSignature = signature; @@ -212,7 +203,6 @@ await searchAutosave.cancel(); await appStore.updateSearchSettings({ provider: searchProvider, - max_results: normalizedMaxResults(), aggregator_engines: aggregatorEngines, safe_search: Number(searchSafeSearch), providers: { @@ -265,7 +255,6 @@ {:else} call.name === 'web_search')) { - return { stop: true }; - } - }, - - async beforeToolCall(_id: string, toolName: string) { - if (plan.isResearchChat && state.researchForceWrite && toolName === 'web_search') { - return { block: 'Enough sources have been gathered. Write the report from the evidence pack instead of searching again.' }; - } + // Research never refuses a search: the model decides how much to + // gather. Only the turn's tool budget and the loop guard (identical + // repeats) bound it. }, async prepareNextTurn(turn: number) { diff --git a/apps/desktop/renderer/src/lib/services/agent-tool-core.spec.ts b/apps/desktop/renderer/src/lib/services/agent-tool-core.spec.ts index d8816e87..0075ff12 100644 --- a/apps/desktop/renderer/src/lib/services/agent-tool-core.spec.ts +++ b/apps/desktop/renderer/src/lib/services/agent-tool-core.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; -import { handleWebSearch } from '$lib/services/agent-tool-core'; +import { MAX_SEARCH_RESULTS, handleWebSearch, searchResultCount } from '$lib/services/agent-tool-core'; import type { ToolContext } from '$lib/services/agent-types'; const baseCtx = { @@ -50,3 +50,28 @@ describe('handleWebSearch', () => { expect(output.next_step).toMatch(/full_content/i); }); }); + +describe('web_search result count', () => { + it('uses the count the model asked for', async () => { + expect(searchResultCount(3, 'search')).toBe(3); + expect(searchResultCount('30', 'deep')).toBe(30); + expect(searchResultCount(500, 'max')).toBe(MAX_SEARCH_RESULTS); + + const webSearch = vi.fn(async () => ({ results: [] })); + await handleWebSearch({ + args: { query: 'q', mode: 'search', max_results: 25 }, + ctx: baseCtx, + webSearch, + ok: (output) => ({ success: true, output }), + fail: (error) => ({ success: false, error }), + failFromError: (err) => ({ success: false, error: String(err) }) + }); + expect(webSearch).toHaveBeenCalledWith(expect.objectContaining({ options: { max_results: 25 } })); + }); + + it('falls back to the mode only when the model gave none', () => { + expect(searchResultCount(undefined, 'search')).toBe(8); + expect(searchResultCount(0, 'deep')).toBe(12); + expect(searchResultCount('lots', 'max')).toBe(18); + }); +}); diff --git a/apps/desktop/renderer/src/lib/services/agent-tool-core.ts b/apps/desktop/renderer/src/lib/services/agent-tool-core.ts index b70c085a..279536ed 100644 --- a/apps/desktop/renderer/src/lib/services/agent-tool-core.ts +++ b/apps/desktop/renderer/src/lib/services/agent-tool-core.ts @@ -1,6 +1,18 @@ import type { ToolContext, ToolResult } from '$lib/services/agent-types'; import type { SearchResult } from '$lib/types/bridge'; +/** The most results one `web_search` call may ask for. */ +export const MAX_SEARCH_RESULTS = 50; + +/** How many results a call gets when the model does not say. */ +const MODE_RESULTS = { search: 8, deep: 12, max: 18 } as const; + +/** The model's own count when it gave a usable one, else the mode's. */ +export function searchResultCount(requested: unknown, mode: 'search' | 'deep' | 'max'): number { + const count = Math.round(Number(requested)); + return Number.isFinite(count) && count >= 1 ? Math.min(count, MAX_SEARCH_RESULTS) : MODE_RESULTS[mode]; +} + export async function handleWebSearch(params: { args: Record; ctx: ToolContext; @@ -14,7 +26,9 @@ export async function handleWebSearch(params: { ? (params.args.mode as 'search' | 'deep' | 'max') : params.ctx.searchMode || 'search'; try { - const resultBudget = mode === 'max' ? 18 : mode === 'deep' ? 12 : 8; + // The model decides how many results it needs (a few for one fact, many + // for a survey); the mode only fills in when it does not say. + const resultBudget = searchResultCount(params.args.max_results, mode); const result = await params.webSearch({ query, context: params.ctx.conversationContext, diff --git a/apps/desktop/renderer/src/lib/services/agent-tooling.ts b/apps/desktop/renderer/src/lib/services/agent-tooling.ts index 27c60dcd..c659a5ba 100644 --- a/apps/desktop/renderer/src/lib/services/agent-tooling.ts +++ b/apps/desktop/renderer/src/lib/services/agent-tooling.ts @@ -3,6 +3,7 @@ import type { ToolDefinition } from '$lib/services/chat/types'; import { HOME_EXTRA_TOOL_DEFS } from '$lib/services/agent-tool-home-schemas'; import { DOMAIN_TOOL_DEFS } from '$shared/domains'; import { filterEnabledTools } from '$lib/services/agent-tool-registry'; +import { MAX_SEARCH_RESULTS } from '$lib/services/agent-tool-core'; import { getAllArtifacts, getEnabledArtifactIds } from '$lib/services/artifact-registry'; /** Simple Chat Agent: research + calc + sandbox files (no host bash). */ @@ -88,12 +89,18 @@ function buildToolDefinitions( { type: 'function', function: { name: 'web_search', - description: 'Search the web for up-to-date information. The tool automatically receives recent conversation context, so write a focused query and include key entities when helpful.', + description: 'Search the web for up-to-date information. The tool automatically receives recent conversation context, so write a focused query and include key entities when helpful. Search as many times as the question needs: refine, follow leads, and cover each sub-question with its own query.', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query' }, - mode: { type: 'string', description: 'Depth mode: "search" (fast), "deep" (thorough), or "max" (exhaustive)' } + mode: { type: 'string', description: 'Depth mode: "search" (fast), "deep" (thorough), or "max" (exhaustive)' }, + max_results: { + type: 'integer', + minimum: 1, + maximum: MAX_SEARCH_RESULTS, + description: `How many results you want (1–${MAX_SEARCH_RESULTS}). Choose it for the question: a few for one fact, many for a survey or comparison. Without it the mode decides (8, 12 or 18).` + } }, required: ['query'] } diff --git a/apps/desktop/renderer/src/lib/services/chat-api.ts b/apps/desktop/renderer/src/lib/services/chat-api.ts index af20461d..57e2b99c 100644 --- a/apps/desktop/renderer/src/lib/services/chat-api.ts +++ b/apps/desktop/renderer/src/lib/services/chat-api.ts @@ -305,8 +305,7 @@ export async function loadChatConfig(): Promise { }, search: { ...(config.search || {}), - provider: config.search?.provider || 'aggregator', - max_results: config.search?.max_results || 6 + provider: config.search?.provider || 'aggregator' }, tts: { ...(config.tts || {}), diff --git a/apps/desktop/renderer/src/lib/services/search.ts b/apps/desktop/renderer/src/lib/services/search.ts index 86279bfc..6c50afa5 100644 --- a/apps/desktop/renderer/src/lib/services/search.ts +++ b/apps/desktop/renderer/src/lib/services/search.ts @@ -71,7 +71,6 @@ export async function webSearch(args: { deep: args.deep ?? false, mode: args.mode, options: { - max_results: stored.search?.max_results, provider: stored.search?.provider || 'aggregator', aggregator_engines: stored.search?.aggregator_engines, safe_search: stored.search?.safe_search, diff --git a/apps/desktop/renderer/src/lib/stores/app-store-config.ts b/apps/desktop/renderer/src/lib/stores/app-store-config.ts index ee5022d7..2eefd382 100644 --- a/apps/desktop/renderer/src/lib/stores/app-store-config.ts +++ b/apps/desktop/renderer/src/lib/stores/app-store-config.ts @@ -173,7 +173,6 @@ export function mergeSearchSettingsConfig( config: AppConfig, partial: { provider?: string; - max_results?: number; context_budget_chars?: number; aggregator_engines?: string[]; safe_search?: number; diff --git a/apps/desktop/renderer/src/lib/stores/app.svelte.ts b/apps/desktop/renderer/src/lib/stores/app.svelte.ts index ae464942..c7b8f98d 100644 --- a/apps/desktop/renderer/src/lib/stores/app.svelte.ts +++ b/apps/desktop/renderer/src/lib/stores/app.svelte.ts @@ -2917,7 +2917,6 @@ class AppStore { async updateSearchSettings(partial: { provider?: string; - max_results?: number; context_budget_chars?: number; aggregator_engines?: string[]; safe_search?: number; diff --git a/apps/desktop/renderer/src/lib/types/chat.ts b/apps/desktop/renderer/src/lib/types/chat.ts index 99c5c82f..6cf89abe 100644 --- a/apps/desktop/renderer/src/lib/types/chat.ts +++ b/apps/desktop/renderer/src/lib/types/chat.ts @@ -1078,7 +1078,6 @@ export interface AppConfig { }; search?: { provider?: string; - max_results?: number; context_budget_chars?: number; aggregator_engines?: string[]; safe_search?: number; diff --git a/apps/desktop/tests/unit/config.defaults.test.js b/apps/desktop/tests/unit/config.defaults.test.js index bd606b77..c5db1c58 100644 --- a/apps/desktop/tests/unit/config.defaults.test.js +++ b/apps/desktop/tests/unit/config.defaults.test.js @@ -75,7 +75,7 @@ describe('getDefaultSearchConfig', () => { it('searches with auto and the free API sources by default', () => { const search = getDefaultSearchConfig(); assert.strictEqual(search.provider, 'auto'); - assert.strictEqual(search.max_results, 6); + assert.strictEqual('max_results' in search, false); assert.deepStrictEqual(search.aggregator_engines, ['wikipedia', 'arxiv', 'crossref', 'pubmed']); }); }); diff --git a/apps/desktop/tests/unit/config.migrate.test.js b/apps/desktop/tests/unit/config.migrate.test.js index 0353ce15..538fce3c 100644 --- a/apps/desktop/tests/unit/config.migrate.test.js +++ b/apps/desktop/tests/unit/config.migrate.test.js @@ -346,7 +346,7 @@ describe('migrateConfig', () => { tts: { model_variant: 'kokoro_v11', model_dir: '/path/to/models/kokoro-multi-lang-v1_1', model: 'model.int8.onnx' }, stt: { provider: 'local' }, onboarding: { completed: true }, - search: { provider: 'aggregator', max_results: 6, aggregator_engines: ['wikipedia', 'arxiv'] }, + search: { provider: 'aggregator', aggregator_engines: ['wikipedia', 'arxiv'] }, }; const result = migrateConfig(cfg, modelsRoot); assert.strictEqual(result.dirty, false); @@ -378,7 +378,7 @@ describe('migrateConfig', () => { const cfg = { llm: { providers: {} }, onboarding: { completed: false }, - search: { provider: 'aggregator', max_results: 6, aggregator_engines: ['wikipedia', 'arxiv'] }, + search: { provider: 'aggregator', aggregator_engines: ['wikipedia', 'arxiv'] }, }; const result = migrateConfig(cfg, modelsRoot); assert.strictEqual(result.dirty, false); @@ -389,7 +389,7 @@ describe('migrateConfig', () => { custom_field: 'should_remain', llm: { providers: {} }, onboarding: { completed: true }, - search: { provider: 'aggregator', max_results: 6, aggregator_engines: ['wikipedia', 'arxiv'] }, + search: { provider: 'aggregator', aggregator_engines: ['wikipedia', 'arxiv'] }, }; const result = migrateConfig(cfg, modelsRoot); assert.strictEqual(result.dirty, false); @@ -409,20 +409,26 @@ describe('ensureSearchConfig', () => { const dirty = ensureSearchConfig(cfg); assert.strictEqual(dirty, true); assert.strictEqual(cfg.search.provider, 'auto'); - assert.strictEqual(cfg.search.max_results, 6); + assert.strictEqual('max_results' in cfg.search, false); assert.deepStrictEqual(cfg.search.aggregator_engines, ['wikipedia', 'arxiv', 'crossref', 'pubmed']); }); it('does not overwrite an explicit provider', () => { - const cfg = { search: { provider: 'brave', max_results: 8, aggregator_engines: ['wikipedia'] } }; + const cfg = { search: { provider: 'brave', aggregator_engines: ['wikipedia'] } }; const dirty = ensureSearchConfig(cfg); assert.strictEqual(dirty, false); assert.strictEqual(cfg.search.provider, 'brave'); - assert.strictEqual(cfg.search.max_results, 8); + }); + + it('drops the removed result-count setting', () => { + const cfg = { search: { provider: 'brave', max_results: 8, aggregator_engines: ['wikipedia'] } }; + assert.strictEqual(ensureSearchConfig(cfg), true); + assert.strictEqual('max_results' in cfg.search, false); + assert.strictEqual(cfg.search.provider, 'brave'); }); it('moves users off removed scrapers and resellers', () => { - const cfg = { search: { provider: 'serpapi', max_results: 6, aggregator_engines: ['duckduckgo', 'google', 'wikipedia'], providers: { serpapi: { api_key: 'k' }, tavily: { api_key: 't' } } } }; + const cfg = { search: { provider: 'serpapi', aggregator_engines: ['duckduckgo', 'google', 'wikipedia'], providers: { serpapi: { api_key: 'k' }, tavily: { api_key: 't' } } } }; assert.strictEqual(ensureSearchConfig(cfg), true); assert.strictEqual(cfg.search.provider, 'auto'); assert.deepStrictEqual(cfg.search.aggregator_engines, ['wikipedia']); @@ -430,7 +436,7 @@ describe('ensureSearchConfig', () => { }); it('falls back to the default engines when none are left', () => { - const cfg = { search: { provider: 'aggregator', max_results: 6, aggregator_engines: ['duckduckgo', 'mojeek'] } }; + const cfg = { search: { provider: 'aggregator', aggregator_engines: ['duckduckgo', 'mojeek'] } }; ensureSearchConfig(cfg); assert.deepStrictEqual(cfg.search.aggregator_engines, ['wikipedia', 'arxiv', 'crossref', 'pubmed']); }); diff --git a/apps/desktop/tests/unit/config.redact.test.js b/apps/desktop/tests/unit/config.redact.test.js index d4e8ee35..52741a9b 100644 --- a/apps/desktop/tests/unit/config.redact.test.js +++ b/apps/desktop/tests/unit/config.redact.test.js @@ -260,7 +260,6 @@ describe('redactConfig', () => { onboarding: {}, search: { provider: 'brave', - max_results: 6, providers: { brave: { api_key: 'BSA-secret-token' }, tavily: { api_key: '' }, diff --git a/apps/desktop/tests/unit/core-web.test.js b/apps/desktop/tests/unit/core-web.test.js index f7bc4d37..790b51b3 100644 --- a/apps/desktop/tests/unit/core-web.test.js +++ b/apps/desktop/tests/unit/core-web.test.js @@ -6,7 +6,6 @@ describe('core web search sync', () => { it('sends the choice, the keyed providers and the SearXNG URL', () => { assert.deepEqual(webSyncPayload({ provider: 'brave', - max_results: 8, providers: { brave: { api_key: ' b-key ' }, tavily: { api_key: '' }, @@ -16,7 +15,6 @@ describe('core web search sync', () => { }, }), { provider: 'brave', - max_results: 8, searxng_url: 'https://search.example/', keys: { brave: 'b-key', exa: 'e-key' }, }); diff --git a/crates/agente-core/src/tools/web/search.rs b/crates/agente-core/src/tools/web/search.rs index 72878db5..188cc851 100644 --- a/crates/agente-core/src/tools/web/search.rs +++ b/crates/agente-core/src/tools/web/search.rs @@ -19,7 +19,9 @@ pub struct WebSearchArgs { /// Search query #[serde(default)] pub query: Option, - /// How many results to return (1-20; default from settings, usually 8) + /// How many results you want (1-20). Choose it for the question: a few + /// for one fact, many for a survey. Without it you get 8. Search as many + /// times as the task needs. #[serde(default)] pub max_results: Option, } From e369d72bbbb1e2b6316130f88dc2d0e9b2fb8100 Mon Sep 17 00:00:00 2001 From: Fabricio Medrano <48396639+fabricio3g@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:37:29 -0300 Subject: [PATCH 2/2] feat(swarm): shared findings between members and one swarm view Swarm members can now talk to each other while they work. The board keeps a findings log; each card's subagent gets a `swarm` tool to post a finding (to everyone or to named cards) and read the cards and log, plus an inbox so posts reach working members at their next step. Cards that start later get the findings in their prompt, the lead sees the newest in every board result, and `board` `post` lets the lead broadcast a decision. Display: on Desktop a turn's swarm members draw as one SwarmBlock (a lane per card with status, role, model, activity, waits-for/feeds, then the newest findings) instead of the subagent tally, and the Board pane lists the whole log. Board cards drop their coloured rails and borders. In the TUI, member cards read as their card with what they feed and their newest finding, and /board shows findings under the columns. --- AGENTS.md | 2 +- .../src/lib/features/code/BoardPanel.svelte | 23 +- .../lib/features/code/CodeTranscript.svelte | 17 +- .../src/lib/features/code/SwarmBlock.svelte | 177 ++++++++ .../lib/features/code/SwarmFindingList.svelte | 39 ++ .../src/lib/features/code/swarm-lanes.spec.ts | 47 +++ .../src/lib/features/code/swarm-lanes.ts | 35 ++ apps/desktop/renderer/src/lib/locales/de.json | 10 +- apps/desktop/renderer/src/lib/locales/en.json | 10 +- apps/desktop/renderer/src/lib/locales/es.json | 10 +- apps/desktop/renderer/src/lib/locales/fr.json | 10 +- apps/desktop/renderer/src/lib/locales/ja.json | 10 +- .../renderer/src/lib/locales/pt-BR.json | 10 +- apps/desktop/renderer/src/lib/locales/zh.json | 10 +- apps/desktop/shared/agente-protocol.ts | 17 + crates/agente-core/src/subagent/definition.rs | 4 +- crates/agente-core/src/subagent/host/board.rs | 66 ++- crates/agente-core/src/subagent/host/mod.rs | 8 + crates/agente-core/src/subagent/host/spawn.rs | 10 +- crates/agente-core/src/swarm.rs | 395 +++++++++++++++++- .../src/app/agent_events/subagents.rs | 16 + crates/agente-tui/src/board_view.rs | 81 +++- crates/agente-tui/src/state/agent.rs | 44 ++ crates/agente-tui/src/state/mod.rs | 2 +- crates/agente-tui/src/ui_harness.rs | 1 + crates/agente-tui/src/widgets/chat/blocks.rs | 40 +- .../agente-tui/src/widgets/chat/snapshot.rs | 16 + crates/agente-tui/src/widgets/chat/tests.rs | 49 +++ docs/SUBAGENTS_PLAN.md | 14 +- 29 files changed, 1137 insertions(+), 36 deletions(-) create mode 100644 apps/desktop/renderer/src/lib/features/code/SwarmBlock.svelte create mode 100644 apps/desktop/renderer/src/lib/features/code/SwarmFindingList.svelte create mode 100644 apps/desktop/renderer/src/lib/features/code/swarm-lanes.spec.ts create mode 100644 apps/desktop/renderer/src/lib/features/code/swarm-lanes.ts diff --git a/AGENTS.md b/AGENTS.md index 9ef0d906..c7ce9b23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ Build a development-engineer tool: a keyboard-first terminal coding agent (Rust) - **Provider cache notes**: DeepSeek/GLM cache automatically on an exact prefix (hits in `prompt_cache_hit_tokens` / `prompt_tokens_details.cached_tokens`); MiniMax's Anthropic API caches only `cache_control` breakpoints (≤4); Go's TOML enables a session `prompt_cache_key` on every route, with protocol defaults enabling markers only for Messages. OpenRouter's Claude/Gemini marker rules also live in TOML. These defaults are configurable; transport builders contain no provider/model cache branches. Gateways may report several dialects at once, so the largest cache count wins - **Categorized errors**: API errors show actionable messages with `/compact`, `/model`, `/provider` hints - **Subagents**: `task` / `task_output` / `kill_task` hosted tools routed to `SubagentHost`. There are no predetermined subagents: the parent model creates each one for its task — `role` (shown on the card; defaults to the description), optional `instructions`, `capability_mode` (read-only by default) and a `model` — on the base prompt `crates/agente-core/agents/_role.md`; the user's own `.agente/agents/*.md` still launch by name (`subagent_type`, listed only when they exist). Models come from the user's list (`config::SubagentSettings`: entries with a name, provider/model, thinking and a `use_for` note the parent reads; one `default_model`; `orchestrator_picks`), routed by `subagent::routing::resolve_model` — the parent's pick (list name or `main`; anything else fails the call) → an agent file's `model:` → the default → the parent's model; old per-type `subagent_models` pins fold into the list on read. The list's menu (price, window, note) is appended to the `task` description byte-stably; cards show `name · model` (`ChildStarted.seat`). Edited in the TUI `/subagent-models` and Desktop's Subagents dialog (`SubagentModelsEditor.svelte`), both laid out by the Laws of UX: one radio per row for the default with the conversation's model as the last option, names folded into shape instead of refused, a row without a model kept as a draft. A read-only child waits inline, one that may change things runs in the background; children run unbounded (the wall-clock watchdog is the backstop); writing children get an isolated git worktree (two kept warm), read-only children read the parent root directly — no checkout; up to `max_parallel_subagents` (default 8, `/settings`) run at once, the rest queue FIFO; parent + child approvals route by `request_id` via `ApprovalBroker`. Roadmap (limits/recovery, durable children, swarm): `docs/SUBAGENTS_PLAN.md` -- **Swarm mode** (`crates/agente-core/src/swarm.rs`, `subagent/host/board.rs`): a per-session switch (`BoardStore`, `~/.agente/sessions/boards/.json`, daemon `board.get|enable|clear`) that gives the main model the hosted `board` tool. It adds cards — title, role, `capability_mode` (read-only default), model, prompt, `depends_on`, `owns` — and the host starts every card whose dependencies are done as a created background subagent (the card's prompt plus its files and the results it builds on); readers land in Done, writers in Review, failures in Failed; `move` accepts, sends back with a note (a fresh subagent retries) or gives up. One writer per path: a writer's `owns` may not overlap another open writer's. `AgentEvent::BoardChanged` → `RuntimeEvent::BoardChanged` carries the whole board. TUI: `/swarm` toggles, `/board` shows the columns, the status row says `+ swarm`. Desktop: the switch sits in the composer's mode menu (the trigger reads `Auto + Swarm`), and a Board pane (`BoardPanel.svelte`, `swarm.svelte.ts`) shows Backlog / Working / Review / Done — side by side when wide, stacked in a side pane — with review cards on an amber rail; its chip appears only while swarm is on or cards remain +- **Swarm mode** (`crates/agente-core/src/swarm.rs`, `subagent/host/board.rs`): a per-session switch (`BoardStore`, `~/.agente/sessions/boards/.json`, daemon `board.get|enable|clear`) that gives the main model the hosted `board` tool. It adds cards — title, role, `capability_mode` (read-only default), model, prompt, `depends_on`, `owns` — and the host starts every card whose dependencies are done as a created background subagent (the card's prompt plus its files and the results it builds on); readers land in Done, writers in Review, failures in Failed; `move` accepts, sends back with a note (a fresh subagent retries) or gives up. One writer per path: a writer's `owns` may not overlap another open writer's. Members talk through the board's findings log (`Board.findings`): each card's child gets the `swarm` tool (`post` a finding, optionally `to` some cards; `read` the cards and log) and an inbox, so a post reaches the members still working at their next step (no reply expected) and every card that starts later in its prompt; the lead sees the newest ten in every `board` result and broadcasts with `board` `post`. One view: a turn's swarm members draw as one block — Desktop `SwarmBlock.svelte` (a lane per card: status, id, title, role · model, activity hard right, waits for / feeds, then the newest findings via the shared `SwarmFindingList`) instead of the subagent tally line, the Board pane lists the whole log under its columns; TUI member cards read `c2 Title Role` with `· feeds c3` and `✎ c1 → c2 finding`, and `/board` shows the newest findings under the columns. `AgentEvent::BoardChanged` → `RuntimeEvent::BoardChanged` carries the whole board. TUI: `/swarm` toggles, `/board` shows the columns, the status row says `+ swarm`. Desktop: the switch sits in the composer's mode menu (the trigger reads `Auto + Swarm`), and a Board pane (`BoardPanel.svelte`, `swarm.svelte.ts`) shows Backlog / Working / Review / Done — side by side when wide, stacked in a side pane — cards are borderless rows lit on hover (no rails), review marked only by its amber `◆`; its chip appears only while swarm is on or cards remain - **Loop guard**: identical tool-call signatures nudge after 3 repeats, hard-stop after 6 with a visible notice - **Skills** (Agent Skills spec, `extensions/skills.rs`): folders with a `SKILL.md` discovered in `~/.claude|.agents|.config/agente|.agente/skills` then `/.claude|.agents|.agente/skills` (later wins, so project beats user); lenient frontmatter (block scalars, nested `metadata`, colons in values), only a missing description skips a skill. Progressive disclosure: the catalog (name + description) lives in the `skill` tool's description with a `name` enum — the model picks the skill itself, and the tool is not registered when there are none; activation returns `` with the body, skill dir and a resource listing (files are read on demand — `read_file`/`list_dir`/`grep`/`find` may open files inside skill dirs outside the project via `resolve_read_path`). `/skill-name request` injects the same block from the composer (the bubble shows what was typed); `/skills` lists them; `disable-model-invocation` keeps one manual-only. Compaction never truncates a skill block and re-attaches any it dropped (`carry_skills`) - **Desktop typography** (`apps/desktop/renderer/src/app.css`, `lib/stores/accessibility.svelte.ts`): one type ladder (`--text-prose|base|sm|xs|code`) multiplied by `--reading-scale`, so Settings → Text size moves captions, chrome, prose, code, diffs and the terminal together; interface size is a window zoom on top of it and reaches 200% (WCAG 1.4.4 wants no less). Nothing hardcodes below `--text-xs` (12px at 100%, the smallest legible regular size); the one exception is the scaled-down page preview in `ArtifactThumb`, which is artwork. Monaco and xterm resolve the tokens through `utils/type-tokens.ts` because canvas cannot read `var()`. Fonts are OFL only and bundled: Inter Variable, IBM Plex Mono, and the Atkinson Hyperlegible pair, where the reading font also swaps `--font-mono` so code follows it. The OS preference reaches the app too: `prefers-contrast: more` raises the same tokens as the manual switch, `forced-colors: active` drops decoration. Zoom belongs to the setting, not to Chromium (`setZoomMode('manual')` plus `zoom-changed` feeding the same presets) diff --git a/apps/desktop/renderer/src/lib/features/code/BoardPanel.svelte b/apps/desktop/renderer/src/lib/features/code/BoardPanel.svelte index 430eb9d6..fc16abad 100644 --- a/apps/desktop/renderer/src/lib/features/code/BoardPanel.svelte +++ b/apps/desktop/renderer/src/lib/features/code/BoardPanel.svelte @@ -6,9 +6,12 @@ - Jakob: a kanban — Backlog, Working, Review, Done — columns side by side when the pane is wide, stacked sections when it is a side pane. - Von Restorff: Review is the one thing that needs the user, so review - cards carry the amber rail and the tally names them; done cards dim. + cards carry the amber `◆` and the tally names them; done cards dim. No + rails or card borders: a card is a row on the canvas, lit on hover. - Chunking + proximity: a card is its title, then `role · model`, then what it waits for / owns, then its result — one block per card. + - Findings: under the columns, what the members told each other — the + same list the transcript's swarm block shows the newest of. - Hick + Occam: the board is read-only; the agent moves cards. The only controls are the swarm switch and "Clear board". - Fitts: the whole card opens its subagent. @@ -23,6 +26,7 @@ import type { SwarmCard } from '$shared/agente-protocol'; import { subagentFocus } from './subagent-focus.svelte'; import { columnsOf, swarmStore, tallyOf } from './swarm.svelte'; + import SwarmFindingList from './SwarmFindingList.svelte'; let { chatId }: { chatId: string } = $props(); @@ -30,6 +34,7 @@ const enabled = $derived(!!board?.enabled); const columns = $derived(columnsOf(board)); const tally = $derived(tallyOf(board)); + const findings = $derived(board?.findings ?? []); let switching = $state(false); /** The switch follows the store; a failed change puts it back. */ let checked = $state(false); @@ -122,6 +127,13 @@ {/each} + {#if findings.length} +
+

{$t('code.swarm.lane.findings')}{findings.length}

+ +
+ {/if} + {#if !tally.working}
{/if} @@ -142,16 +154,15 @@ /* Side pane: sections stacked. Wide pane: the kanban side by side. */ .columns { display: grid; gap: 1rem; } @container (min-width: 44rem) { .columns { grid-template-columns: repeat(4, minmax(0, 1fr)); align-items: start; } } - .column { display: grid; gap: 0.5rem; min-width: 0; } - .column h3 { display: flex; align-items: baseline; gap: 0.375rem; font-size: var(--text-xs); font-weight: 500; color: var(--muted-foreground); } + .column { display: grid; gap: 0.125rem; min-width: 0; } + .findings { display: grid; gap: 0.5rem; min-width: 0; } + .column h3, .findings h3 { display: flex; align-items: baseline; gap: 0.375rem; font-size: var(--text-xs); font-weight: 500; color: var(--muted-foreground); } .count { color: var(--text-muted, var(--muted-foreground)); font-variant-numeric: tabular-nums; } .column-empty { font-size: var(--text-xs); color: var(--muted-foreground); padding-left: 0.25rem; } - :global(.card.ui-local-0875e6c3){ display: grid; gap: 0.25rem; width: 100%; min-width: 0; border: 1px solid var(--border-subtle); border-radius: 0.625rem; background: var(--card, transparent); padding: 0.625rem 0.75rem; text-align: left; transition: background var(--motion-instant) var(--motion-ease); } + :global(.card.ui-local-0875e6c3){ display: grid; gap: 0.25rem; min-width: 0; border: 0; border-radius: 0.5rem; background: transparent; margin-inline: -0.5rem; width: calc(100% + 1rem); padding: 0.5rem; text-align: left; transition: background var(--motion-instant) var(--motion-ease); } :global(.card.ui-local-0875e6c3:not(:disabled)){ cursor: pointer; } :global(.card.ui-local-0875e6c3:not(:disabled):hover), :global(.card.ui-local-0875e6c3:focus-visible){ background: var(--surface-hover); } - :global(.card.ui-local-0875e6c3.status-review){ box-shadow: inset 3px 0 0 var(--warning); } - :global(.card.ui-local-0875e6c3.status-failed){ box-shadow: inset 3px 0 0 var(--error); } :global(.card.ui-local-0875e6c3.status-done){ opacity: 0.72; } .card-head { display: flex; min-width: 0; align-items: baseline; gap: 0.5rem; } .mark { width: 1rem; flex-shrink: 0; text-align: center; font-size: var(--text-xs); color: var(--muted-foreground); } diff --git a/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte b/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte index 7fd2bc4e..d2c2804c 100644 --- a/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte +++ b/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte @@ -30,6 +30,8 @@ import MediaAttachmentCard from './MediaAttachmentCard.svelte'; import CodeWorkBlock from './CodeWorkBlock.svelte'; import SubagentTally from './SubagentTally.svelte'; + import SwarmBlock from './SwarmBlock.svelte'; + import { swarmStore } from './swarm.svelte'; import { composerChildren } from './subagent-row'; import { subagentFocus } from './subagent-focus.svelte'; import CodeLiveStatus from './CodeLiveStatus.svelte'; @@ -67,6 +69,11 @@ /** Live run state for retry + todo visibility while streaming. */ const run = $derived(codeStore.runFor(chatId)); + // The board joins a turn's swarm members into one block; keep it current + // even while the Board pane is closed. + $effect(() => { void swarmStore.load(chatId).catch(() => {}); }); + /** Subagents working a board card: the swarm block draws them, not the tally line. */ + const swarmChildIds = $derived(new Set((swarmStore.boardFor(chatId)?.cards ?? []).map((card) => card.child_id).filter((id): id is string => !!id))); const dockedChildren = $derived(new Set(liveSubagentDock ? composerChildren(run).map((child) => child.id) : [])); const plan = $derived(pendingPlan(messages)); @@ -319,7 +326,8 @@ {@const live = run?.assistantMessageId === message.id} {@const entries = entriesFor(message)} {@const children = live ? run?.children ?? [] : message.metadata?.codeChildren ?? []} - {@const transcriptChildren = children.filter((child) => !dockedChildren.has(child.id))} + {@const swarmChildren = children.filter((child) => swarmChildIds.has(child.id))} + {@const transcriptChildren = children.filter((child) => !dockedChildren.has(child.id) && !swarmChildIds.has(child.id))} {@const diagnostics = live ? run?.diagnostics ?? [] : message.metadata?.codeDiagnostics ?? []} {@const blocks = replyBlocks(entries)}
@@ -348,7 +356,12 @@ {/if} {/if} - + + {#if swarmChildren.length} + + {/if} + + {#if transcriptChildren.length} + + +
    + {#each lanes as card (card.id)} + {@const child = childOf(card)} + {@const elapsed = child ? childElapsedMs(child, now) : undefined} + {@const linkText = links(card)} +
  1. + +
  2. + {/each} +
+ + {#if findings.length} +
+

{$t('code.swarm.lane.findings')}

+ + {#if hidden > 0} + + {/if} +
+ {/if} + +{/if} + + diff --git a/apps/desktop/renderer/src/lib/features/code/SwarmFindingList.svelte b/apps/desktop/renderer/src/lib/features/code/SwarmFindingList.svelte new file mode 100644 index 00000000..1de31645 --- /dev/null +++ b/apps/desktop/renderer/src/lib/features/code/SwarmFindingList.svelte @@ -0,0 +1,39 @@ + + + + + + +
    + {#each findings as finding (finding.id)} +
  1. + {route(finding)} + {finding.text} +
  2. + {/each} +
+ + diff --git a/apps/desktop/renderer/src/lib/features/code/swarm-lanes.spec.ts b/apps/desktop/renderer/src/lib/features/code/swarm-lanes.spec.ts new file mode 100644 index 00000000..304857b0 --- /dev/null +++ b/apps/desktop/renderer/src/lib/features/code/swarm-lanes.spec.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import type { SwarmBoard, SwarmCard } from '$shared/agente-protocol'; +import { feedsOf, findingRoute, lanesFor, recentFindings } from './swarm-lanes'; + +const card = (id: string, extra: Partial = {}): SwarmCard => ({ + id, title: id.toUpperCase(), role: 'Reader', capability: 'read-only', prompt: '', status: 'working', ...extra +}); + +const board: SwarmBoard = { + enabled: true, + cards: [ + card('c1', { child_id: 'a' }), + card('c2', { child_id: 'b', status: 'done' }), + card('c3', { status: 'backlog', depends_on: ['c1'] }), + card('c4', { child_id: 'z' }), + card('c5', { status: 'backlog', depends_on: ['c4'] }) + ], + findings: [ + { id: 1, from: 'c1', text: 'one' }, + { id: 2, from: 'c4', text: 'other swarm turn' }, + { id: 3, from: 'c2', text: 'to c1', to: ['c1'] }, + { id: 4, from: 'lead', text: 'keep the api' } + ] +}; + +describe('swarm lanes', () => { + it('takes the cards the turn\'s children work, plus the backlog waiting on them', () => { + expect(lanesFor(board, new Set(['a', 'b'])).map((c) => c.id)).toEqual(['c1', 'c2', 'c3']); + expect(lanesFor(board, new Set(['nobody']))).toEqual([]); + expect(lanesFor(null, new Set(['a']))).toEqual([]); + }); + + it('names the cards a card feeds', () => { + expect(feedsOf(board, board.cards[0])).toEqual(['c3']); + expect(feedsOf(board, board.cards[1])).toEqual([]); + }); + + it('keeps the newest findings, narrowed to the lanes shown', () => { + expect(recentFindings(board, 2).map((f) => f.id)).toEqual([3, 4]); + expect(recentFindings(board, 10, new Set(['c1', 'c2', 'c3'])).map((f) => f.id)).toEqual([1, 3, 4]); + }); + + it('routes a finding from its author to its addressees', () => { + expect(findingRoute({ id: 1, from: 'c2', text: '', to: ['c1', 'c3'] })).toBe('c2 → c1, c3'); + expect(findingRoute({ id: 2, from: 'lead', text: '' })).toBe('lead'); + }); +}); diff --git a/apps/desktop/renderer/src/lib/features/code/swarm-lanes.ts b/apps/desktop/renderer/src/lib/features/code/swarm-lanes.ts new file mode 100644 index 00000000..99a260e8 --- /dev/null +++ b/apps/desktop/renderer/src/lib/features/code/swarm-lanes.ts @@ -0,0 +1,35 @@ +// Reading the swarm board as lanes: which cards a turn's subagents work, who +// waits on whom, and the findings members posted to each other. Pure, so the +// transcript's swarm block and the Board pane read the board the same way. + +import type { SwarmBoard, SwarmCard, SwarmFinding } from '$shared/agente-protocol'; + +/** + * The cards a turn's subagents work, in board order: the swarm block draws one + * lane per card whose subagent is among `childIds`. Cards waiting on those + * (still in the backlog) join too, so the block shows what comes next. + */ +export function lanesFor(board: SwarmBoard | null, childIds: ReadonlySet): SwarmCard[] { + const cards = board?.cards ?? []; + const mine = new Set(cards.filter((card) => card.child_id && childIds.has(card.child_id)).map((card) => card.id)); + if (!mine.size) return []; + return cards.filter((card) => mine.has(card.id) || (card.status === 'backlog' && (card.depends_on ?? []).some((dep) => mine.has(dep)))); +} + +/** The cards that wait on `card` — who its result goes to. */ +export function feedsOf(board: SwarmBoard | null, card: SwarmCard): string[] { + return (board?.cards ?? []).filter((other) => (other.depends_on ?? []).includes(card.id)).map((other) => other.id); +} + +/** The newest `limit` findings, oldest first, optionally only those touching `cards`. */ +export function recentFindings(board: SwarmBoard | null, limit: number, cards?: ReadonlySet): SwarmFinding[] { + const all = board?.findings ?? []; + const touching = cards ? all.filter((finding) => finding.from === 'lead' || cards.has(finding.from) || (finding.to ?? []).some((to) => cards.has(to))) : all; + return touching.slice(Math.max(0, touching.length - limit)); +} + +/** Who a finding came from and went to, the way the block heads it: `c1 → c2`, `lead`. */ +export function findingRoute(finding: SwarmFinding): string { + const to = finding.to?.length ? ` → ${finding.to.join(', ')}` : ''; + return `${finding.from}${to}`; +} diff --git a/apps/desktop/renderer/src/lib/locales/de.json b/apps/desktop/renderer/src/lib/locales/de.json index 93bcb8a1..30b42a03 100644 --- a/apps/desktop/renderer/src/lib/locales/de.json +++ b/apps/desktop/renderer/src/lib/locales/de.json @@ -430,7 +430,15 @@ }, "waitsFor": "Wartet auf {cards}", "openCard": "Subagent öffnen", - "clear": "Board leeren" + "clear": "Board leeren", + "lane": { + "title": "Schwarm", + "feeds": "Liefert an {cards}", + "failed": "Fehlgeschlagen", + "findings": "Erkenntnisse", + "lead": "Leitung", + "more": "{n, plural, one {# frühere Erkenntnis} other {# frühere Erkenntnisse}} auf dem Board" + } }, "traceCopyInput": "Eingabe kopieren", "traceCopyOutput": "Ausgabe kopieren", diff --git a/apps/desktop/renderer/src/lib/locales/en.json b/apps/desktop/renderer/src/lib/locales/en.json index 833ca609..9dbbe6b5 100644 --- a/apps/desktop/renderer/src/lib/locales/en.json +++ b/apps/desktop/renderer/src/lib/locales/en.json @@ -430,7 +430,15 @@ }, "waitsFor": "Waits for {cards}", "openCard": "Open its subagent", - "clear": "Clear board" + "clear": "Clear board", + "lane": { + "title": "Swarm", + "feeds": "Feeds {cards}", + "failed": "Failed", + "findings": "Findings", + "lead": "Lead", + "more": "{n, plural, one {# earlier finding} other {# earlier findings}} on the board" + } }, "traceCopyInput": "Copy input", "traceCopyOutput": "Copy output", diff --git a/apps/desktop/renderer/src/lib/locales/es.json b/apps/desktop/renderer/src/lib/locales/es.json index c952e391..53cd0b0a 100644 --- a/apps/desktop/renderer/src/lib/locales/es.json +++ b/apps/desktop/renderer/src/lib/locales/es.json @@ -430,7 +430,15 @@ }, "waitsFor": "Espera a {cards}", "openCard": "Abrir su subagente", - "clear": "Vaciar tablero" + "clear": "Vaciar tablero", + "lane": { + "title": "Enjambre", + "feeds": "Alimenta a {cards}", + "failed": "Falló", + "findings": "Hallazgos", + "lead": "Líder", + "more": "{n, plural, one {# hallazgo anterior} other {# hallazgos anteriores}} en el tablero" + } }, "traceCopyInput": "Copiar entrada", "traceCopyOutput": "Copiar resultado", diff --git a/apps/desktop/renderer/src/lib/locales/fr.json b/apps/desktop/renderer/src/lib/locales/fr.json index 058aeab8..88c1b227 100644 --- a/apps/desktop/renderer/src/lib/locales/fr.json +++ b/apps/desktop/renderer/src/lib/locales/fr.json @@ -430,7 +430,15 @@ }, "waitsFor": "Attend {cards}", "openCard": "Ouvrir son sous-agent", - "clear": "Vider le tableau" + "clear": "Vider le tableau", + "lane": { + "title": "Essaim", + "feeds": "Alimente {cards}", + "failed": "Échec", + "findings": "Constats", + "lead": "Pilote", + "more": "{n, plural, one {# constat précédent} other {# constats précédents}} sur le tableau" + } }, "traceCopyInput": "Copier l’entrée", "traceCopyOutput": "Copier le résultat", diff --git a/apps/desktop/renderer/src/lib/locales/ja.json b/apps/desktop/renderer/src/lib/locales/ja.json index 2dbf1291..4691ed2b 100644 --- a/apps/desktop/renderer/src/lib/locales/ja.json +++ b/apps/desktop/renderer/src/lib/locales/ja.json @@ -430,7 +430,15 @@ }, "waitsFor": "{cards} を待機中", "openCard": "サブエージェントを開く", - "clear": "ボードを空にする" + "clear": "ボードを空にする", + "lane": { + "title": "スウォーム", + "feeds": "{cards} に渡す", + "failed": "失敗", + "findings": "共有メモ", + "lead": "リード", + "more": "ボードに以前のメモ {n} 件" + } }, "traceCopyInput": "入力をコピー", "traceCopyOutput": "出力をコピー", diff --git a/apps/desktop/renderer/src/lib/locales/pt-BR.json b/apps/desktop/renderer/src/lib/locales/pt-BR.json index a54bf3b2..7cfef791 100644 --- a/apps/desktop/renderer/src/lib/locales/pt-BR.json +++ b/apps/desktop/renderer/src/lib/locales/pt-BR.json @@ -430,7 +430,15 @@ }, "waitsFor": "Espera {cards}", "openCard": "Abrir o subagente", - "clear": "Limpar quadro" + "clear": "Limpar quadro", + "lane": { + "title": "Enxame", + "feeds": "Alimenta {cards}", + "failed": "Falhou", + "findings": "Descobertas", + "lead": "Líder", + "more": "{n, plural, one {# descoberta anterior} other {# descobertas anteriores}} no quadro" + } }, "traceCopyInput": "Copiar entrada", "traceCopyOutput": "Copiar resultado", diff --git a/apps/desktop/renderer/src/lib/locales/zh.json b/apps/desktop/renderer/src/lib/locales/zh.json index 549e0be3..c1f0d9b3 100644 --- a/apps/desktop/renderer/src/lib/locales/zh.json +++ b/apps/desktop/renderer/src/lib/locales/zh.json @@ -430,7 +430,15 @@ }, "waitsFor": "等待 {cards}", "openCard": "打开其子智能体", - "clear": "清空看板" + "clear": "清空看板", + "lane": { + "title": "蜂群", + "feeds": "供给 {cards}", + "failed": "失败", + "findings": "发现", + "lead": "主控", + "more": "看板上还有 {n} 条更早的发现" + } }, "traceCopyInput": "复制输入", "traceCopyOutput": "复制输出", diff --git a/apps/desktop/shared/agente-protocol.ts b/apps/desktop/shared/agente-protocol.ts index 83320432..5cf0bbf6 100644 --- a/apps/desktop/shared/agente-protocol.ts +++ b/apps/desktop/shared/agente-protocol.ts @@ -141,10 +141,27 @@ export interface SwarmCard { notes?: string[]; } +/** + * One entry in the swarm's findings log (`agente_core::swarm::Finding`): what a + * member — or the lead (`from: 'lead'`) — told the others while working. + */ +export interface SwarmFinding { + id: number; + /** The card whose subagent posted it, or `lead`. */ + from: string; + text: string; + /** Cards it was addressed to; absent means every member. */ + to?: string[]; + /** Unix milliseconds. */ + at?: number; +} + /** A session's swarm board (`agente_core::swarm::Board`); `enabled` is the swarm switch. */ export interface SwarmBoard { enabled: boolean; cards: SwarmCard[]; + /** Oldest first; absent while nobody has posted. */ + findings?: SwarmFinding[]; } /** One model the user offers to subagents, under the name the orchestrator picks it by. */ diff --git a/crates/agente-core/src/subagent/definition.rs b/crates/agente-core/src/subagent/definition.rs index 013d7f7a..a6318fc2 100644 --- a/crates/agente-core/src/subagent/definition.rs +++ b/crates/agente-core/src/subagent/definition.rs @@ -126,7 +126,7 @@ pub fn custom_capability( Some(list) => { let has_shell = list.iter().any(|t| t == "shell"); let all_read_only = list.iter().all(|t| { - is_read_only_tool(t) || matches!(t.as_str(), "todo_write" | "present_plan") + is_read_only_tool(t) || matches!(t.as_str(), "todo_write" | "present_plan" | "swarm") }); if has_shell { SubagentCapabilityMode::Execute @@ -339,7 +339,7 @@ pub fn is_hosted_tool(name: &str) -> bool { /// True when a tool name is allowed for the given capability mode. pub fn tool_allowed_by_capability(name: &str, capability: SubagentCapabilityMode) -> bool { use crate::tools::ToolKind; - if is_read_only_tool(name) || matches!(name, "todo_write" | "present_plan") { + if is_read_only_tool(name) || matches!(name, "todo_write" | "present_plan" | "swarm") { return true; } if is_hosted_tool(name) { diff --git a/crates/agente-core/src/subagent/host/board.rs b/crates/agente-core/src/subagent/host/board.rs index 4b265bcd..fe9daafa 100644 --- a/crates/agente-core/src/subagent/host/board.rs +++ b/crates/agente-core/src/subagent/host/board.rs @@ -8,7 +8,7 @@ use super::*; use crate::subagent::definition::capability_for_parent_mode; -use crate::swarm::{BoardAction, BoardArgs, BoardStore}; +use crate::swarm::{BoardAction, BoardArgs, BoardStore, DeliverFinding, SwarmTool, LEAD}; /// What a card start needs from the lead's turn: its cancel signal (a card /// started after the turn ends still stops with it) and its depth. @@ -66,6 +66,14 @@ impl SubagentHost { BoardAction::Add => store .update(session, |board| board.add(args.cards)) .map(|(ids, board)| (format!("Added {}.", ids.join(", ")), board)), + BoardAction::Post => { + let text = args.text.as_deref().or(args.note.as_deref()).unwrap_or_default(); + let deliver = self.finding_deliverer(); + match crate::swarm::post_and_deliver(session, LEAD, text, &args.recipients, &deliver) { + Ok(said) => store.get(session).map(|board| (said, board)).map_err(|e| e.to_string()), + Err(error) => Err(error), + } + } BoardAction::Move => { let (Some(id), Some(to)) = (args.id.as_deref(), args.to) else { return outcome("Error: move needs `id` and `to`".into(), true); @@ -133,6 +141,10 @@ impl SubagentHost { }; let mut started = Vec::new(); for (card, child_id, prompt) in starts { + self.inner + .swarm_members + .lock() + .insert(child_id.clone(), card.id.clone()); let owns = if card.capability == SubagentCapabilityMode::ReadOnly { Vec::new() } else { @@ -157,6 +169,7 @@ impl SubagentHost { }; let result = Box::pin(self.spawn(request, lead.cancel.clone(), lead.depth)).await; if result.is_error { + self.forget_swarm_member(&child_id); let summary = result.summary.unwrap_or_else(|| "could not start".into()); let clear_child = !self.inner.registry.contains(&child_id); let _ = store.update(session, |board| { @@ -177,6 +190,7 @@ impl SubagentHost { /// and start the cards that were waiting on it. Runs on the child's /// forwarder thread. pub(super) fn board_child_finished(&self, child_id: &str) { + self.forget_swarm_member(child_id); let Some(session) = self.board_session() else { return; }; @@ -206,4 +220,54 @@ impl SubagentHost { } }); } + + /// For a swarm card's child (registered by `start_ready_cards`): its + /// inbox, now open for findings, and its `swarm` tool. + pub(super) fn swarm_member_tools( + &self, + child_id: &str, + ) -> Option<(crate::agent::channel::UserInbox, Box)> { + let card_id = self.inner.swarm_members.lock().get(child_id).cloned()?; + let session = self.board_session()?; + let inbox = crate::agent::channel::UserInbox::default(); + self.inner + .swarm_inboxes + .lock() + .insert(child_id.to_string(), inbox.clone()); + let tool = SwarmTool::new(session, card_id, self.finding_deliverer()); + Some((inbox, Box::new(tool))) + } + + fn forget_swarm_member(&self, child_id: &str) { + self.inner.swarm_members.lock().remove(child_id); + self.inner.swarm_inboxes.lock().remove(child_id); + } + + /// Delivers a finding: one message into each recipient's inbox, taken at + /// its next step, then the board to the UI. Holds the host weakly — the + /// tool lives in a child's registry, and must not keep the host alive. + pub(super) fn finding_deliverer(&self) -> DeliverFinding { + let host = std::sync::Arc::downgrade(&self.inner); + std::sync::Arc::new(move |board, finding| { + let Some(inner) = host.upgrade() else { + return; + }; + let host = SubagentHost { inner }; + let message = format!( + "Swarm finding {} +(From another member of your swarm. Use it if it bears on your card; there is no need to reply.)", + board.finding_line(finding) + ); + let inboxes = host.inner.swarm_inboxes.lock(); + for child_id in board.recipients(finding) { + if let Some(inbox) = inboxes.get(&child_id) { + if !inbox.is_closed() { + inbox.lock().push(crate::types::Message::user(message.clone())); + } + } + } + drop(inboxes); + host.send_board(board); + }) + } } diff --git a/crates/agente-core/src/subagent/host/mod.rs b/crates/agente-core/src/subagent/host/mod.rs index 92f5f0e2..3f3d383c 100644 --- a/crates/agente-core/src/subagent/host/mod.rs +++ b/crates/agente-core/src/subagent/host/mod.rs @@ -210,6 +210,12 @@ pub(super) struct SubagentHostInner { pub(super) mcp_session_id: OnceLock, /// Set by the first `board` call of the turn: what card starts run under. board_lead: OnceLock, + /// Swarm members of this host: child id → card id, set before a card's + /// spawn so its launch gives the child the `swarm` tool and an inbox. + swarm_members: parking_lot::Mutex>, + /// Running members' inboxes, where findings from the others land. + swarm_inboxes: + parking_lot::Mutex>, } fn outcome_from_result( @@ -238,6 +244,8 @@ impl SubagentHost { scheduler: OnceLock::new(), mcp_session_id: OnceLock::new(), board_lead: OnceLock::new(), + swarm_members: Default::default(), + swarm_inboxes: Default::default(), }), } } diff --git a/crates/agente-core/src/subagent/host/spawn.rs b/crates/agente-core/src/subagent/host/spawn.rs index d81935c9..8d08f3f1 100644 --- a/crates/agente-core/src/subagent/host/spawn.rs +++ b/crates/agente-core/src/subagent/host/spawn.rs @@ -522,6 +522,12 @@ impl SubagentHost { } } + // A swarm card's child talks to the other members: the `swarm` tool + // to post and read findings, an inbox where theirs arrive. + let (swarm_inbox, swarm_tools) = match self.swarm_member_tools(&id) { + Some((inbox, tool)) => (Some(inbox), vec![tool]), + None => (None, Vec::new()), + }; let run_config = AgentRunConfig { session_id: uuid::Uuid::new_v4(), sender: child_tx.clone(), @@ -561,8 +567,8 @@ impl SubagentHost { smart_compaction: false, compaction_model: None, initial_gap: 0, - user_inbox: None, - extra_tools: Vec::new(), + user_inbox: swarm_inbox, + extra_tools: swarm_tools, only_tools: host.inner.config.only_tools.clone(), shell_env: host.inner.config.shell_env.clone(), }; diff --git a/crates/agente-core/src/swarm.rs b/crates/agente-core/src/swarm.rs index 5bd47bca..7b2c31ca 100644 --- a/crates/agente-core/src/swarm.rs +++ b/crates/agente-core/src/swarm.rs @@ -9,6 +9,12 @@ //! main model accepts a review, or sends a card back with feedback. One //! writer per file: a writer's `owns` may not overlap another open writer's. //! +//! Members talk through the board's findings log: each card's subagent gets +//! the `swarm` tool to post a finding (a fact, a decision, a changed +//! signature) and to read what the others posted. A post reaches the members +//! still working at their next step and every card that starts later; the +//! main model sees the log in each board result and may post to it too. +//! //! The board is session state, not transcript: one file per session beside //! the session goals, written atomically, so a restart keeps it. @@ -99,10 +105,55 @@ pub struct Board { pub enabled: bool, #[serde(default)] pub cards: Vec, + /// What members (and the lead) told each other, oldest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub findings: Vec, #[serde(default)] next_id: u32, } +/// Who posted a finding when no card did: the main model. +pub const LEAD: &str = "lead"; + +/// The log keeps the newest findings; older ones fall off. +const MAX_FINDINGS: usize = 200; +/// Findings a starting member's prompt carries. +const PROMPT_FINDINGS: usize = 20; +/// Findings the main model's board result carries. +const SUMMARY_FINDINGS: usize = 10; + +impl Finding { + /// Who it came from and went to: `c1 → c2, c3`, `lead`, `c4`. + pub fn route(&self) -> String { + if self.to.is_empty() { + self.from.clone() + } else { + format!("{} \u{2192} {}", self.from, self.to.join(", ")) + } + } + + /// True when `card` wrote it or it was addressed to `card`. + pub fn touches(&self, card: &str) -> bool { + self.from == card || self.to.iter().any(|to| to == card) + } +} + +/// One entry in the swarm's findings log. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Finding { + /// 1, 2, … in the order posted. + pub id: u32, + /// The card whose subagent posted it, or [`LEAD`]. + pub from: String, + pub text: String, + /// Cards it is addressed to; empty means everyone. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub to: Vec, + /// Unix milliseconds. + #[serde(default)] + pub at: i64, +} + /// A card as the main model writes it (`board` `add`). #[derive(Debug, Clone, Deserialize)] pub struct CardSpec { @@ -467,6 +518,121 @@ impl Board { Ok(()) } + /// Post a finding. `from` is a card id or [`LEAD`]; `to` names cards by + /// id or title (empty = everyone). Returns the finding. + pub fn post(&mut self, from: &str, text: &str, to: &[String]) -> Result { + let text = text.trim(); + if text.is_empty() { + return Err("a finding needs text".into()); + } + if from != LEAD && self.card(from).is_none() { + return Err(format!("no card {from}")); + } + let mut targets: Vec = Vec::new(); + for name in to { + let name = name.trim(); + let Some(card) = self + .cards + .iter() + .find(|card| card.id == name || card.title.eq_ignore_ascii_case(name)) + else { + return Err(format!("no card {name}")); + }; + if !targets.contains(&card.id) { + targets.push(card.id.clone()); + } + } + let finding = Finding { + id: self.findings.last().map_or(1, |last| last.id + 1), + from: from.to_string(), + text: trim_limit(text, 1_200), + to: targets, + at: chrono::Utc::now().timestamp_millis(), + }; + self.findings.push(finding.clone()); + if self.findings.len() > MAX_FINDINGS { + let excess = self.findings.len() - MAX_FINDINGS; + self.findings.drain(..excess); + } + Ok(finding) + } + + /// The subagents a finding goes to now: every working card's but the + /// author's, narrowed to the addressees when it names any. + pub fn recipients(&self, finding: &Finding) -> Vec { + self.cards + .iter() + .filter(|card| card.status == CardStatus::Working && card.id != finding.from) + .filter(|card| finding.to.is_empty() || finding.to.contains(&card.id)) + .filter_map(|card| card.child_id.clone()) + .collect() + } + + /// How a finding reads to a member or the lead: + /// `#3 c1 "Parse" (Parser refactorer) → c2: text`. + pub fn finding_line(&self, finding: &Finding) -> String { + let author = match self.card(&finding.from) { + Some(card) => format!("{} \"{}\" ({})", card.id, card.title, card.role), + None => "the lead".to_string(), + }; + let to = if finding.to.is_empty() { + String::new() + } else { + format!(" \u{2192} {}", finding.to.join(", ")) + }; + format!("#{} {author}{to}: {}", finding.id, finding.text) + } + + /// The findings a card may read — everyone's, its own and those + /// addressed to it; every finding for the lead (`None`) — newest `limit`. + fn findings_for(&self, card: Option<&str>, limit: usize) -> Vec<&Finding> { + let visible: Vec<&Finding> = self + .findings + .iter() + .filter(|finding| match card { + None => true, + Some(id) => { + finding.to.is_empty() + || finding.from == id + || finding.to.iter().any(|to| to == id) + } + }) + .collect(); + let skip = visible.len().saturating_sub(limit); + visible.into_iter().skip(skip).collect() + } + + /// What `swarm` `read` returns to a member: every card's state, then the + /// findings it may read. + pub fn member_view(&self, card_id: &str) -> String { + let mut out = String::from("Cards:\n"); + for card in &self.cards { + let me = if card.id == card_id { " (you)" } else { "" }; + out.push_str(&format!( + "- {} {} [{} · {}]{me}", + card.id, + card.title, + card.role, + card.status.as_str() + )); + if !card.owns.is_empty() { + out.push_str(&format!(" owns {}", card.owns.join(", "))); + } + out.push('\n'); + } + let findings = self.findings_for(Some(card_id), MAX_FINDINGS); + if findings.is_empty() { + out.push_str("No findings yet."); + } else { + out.push_str("Findings:\n"); + for finding in findings { + out.push_str(&self.finding_line(finding)); + out.push('\n'); + } + } + out.trim_end().to_string() + } + /// The prompt a card's subagent gets: the card's own, then what the /// swarm needs it to know — its files and the results it builds on. pub fn child_prompt(&self, id: &str) -> Option { @@ -505,6 +671,14 @@ impl Board { )); } } + let findings = self.findings_for(Some(&card.id), PROMPT_FINDINGS); + if !findings.is_empty() { + out.push_str("\n\nFindings the swarm has posted so far:"); + for finding in findings { + out.push_str(&format!("\n- {}", self.finding_line(finding))); + } + } + out.push_str(&format!("\n\n{MEMBER_GUIDE} Your card id is {}.", card.id)); Some(out) } @@ -546,10 +720,25 @@ impl Board { out.push('\n'); } } + let findings = self.findings_for(None, SUMMARY_FINDINGS); + if !findings.is_empty() { + out.push_str("findings:\n"); + for finding in findings { + out.push_str(&format!("- {}\n", self.finding_line(finding))); + } + } out.trim_end().to_string() } } +/// How a member works with the others; ends every card's prompt. +const MEMBER_GUIDE: &str = "\ +The other members work at the same time. Use the `swarm` tool to post what they need to know the \ +moment you learn it — a fact about the code, a decision you made, a signature or file you changed — \ +in one or two sentences, addressed with `to` when it concerns only some cards. Findings from the \ +others arrive in your conversation as you work; `swarm` `read` shows the cards and every finding. \ +Do not post your final report: your last message goes to the lead."; + /// One board file per session, written atomically. Session ids are UUIDs and /// cannot escape the directory. Read-modify-write goes through one process /// lock, since the forwarder threads of several children update one board. @@ -651,6 +840,12 @@ pub struct BoardArgs { pub to: Option, #[serde(default)] pub note: Option, + /// For post: what to tell the members. + #[serde(default)] + pub text: Option, + /// For post: the cards it is for (ids or titles); empty = every member. + #[serde(default)] + pub recipients: Vec, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] @@ -659,6 +854,135 @@ pub enum BoardAction { Add, Move, Show, + Post, +} + +/// Hands a new finding to the members working now (their inboxes) and +/// tells the UI the board changed. The host builds it; the `board` and +/// `swarm` tools call it after every post. +pub type DeliverFinding = std::sync::Arc; + +/// Post to a session's board and deliver the finding. Returns the line the +/// poster gets back. +pub fn post_and_deliver( + session: Uuid, + from: &str, + text: &str, + to: &[String], + deliver: &DeliverFinding, +) -> Result { + let (finding, board) = BoardStore::user().update(session, |board| board.post(from, text, to))?; + let reached = board.recipients(&finding).len(); + deliver(&board, &finding); + Ok(match reached { + 0 => format!("Posted #{}. No other member is working right now; cards that start later will see it.", finding.id), + 1 => format!("Posted #{} to 1 working member.", finding.id), + n => format!("Posted #{} to {n} working members.", finding.id), + }) +} + +/// The `swarm` tool a card's subagent gets: post a finding to the other +/// members, or read the cards and the findings log. +pub struct SwarmTool { + session: Uuid, + card_id: String, + deliver: DeliverFinding, +} + +impl SwarmTool { + pub fn new(session: Uuid, card_id: impl Into, deliver: DeliverFinding) -> Self { + Self { + session, + card_id: card_id.into(), + deliver, + } + } +} + +#[derive(Debug, Deserialize)] +struct SwarmArgs { + action: SwarmAction, + #[serde(default)] + text: Option, + #[serde(default)] + to: Vec, +} + +#[derive(Debug, Clone, Copy, Deserialize)] +#[serde(rename_all = "snake_case")] +enum SwarmAction { + Post, + Read, +} + +const SWARM_DESCRIPTION: &str = "\ +Talk to the other members of your swarm. action \"post\": share a finding the moment you have it — \ +a fact about the code, a decision, a signature or file you changed — in one or two sentences \ +(`text`); `to` addresses some cards (ids like c2, or titles), otherwise every member sees it. \ +Members working now get it at their next step; cards that start later get it in their prompt. \ +action \"read\": every card's state and the findings you may read. Your final report is not a \ +finding: end with it as your last message."; + +#[async_trait::async_trait] +impl crate::tools::Tool for SwarmTool { + fn name(&self) -> &str { + "swarm" + } + + fn kind(&self) -> crate::tools::ToolKind { + crate::tools::ToolKind::Todo + } + + fn description(&self) -> &str { + SWARM_DESCRIPTION + } + + fn parameters(&self) -> serde_json::Value { + serde_json::json!({ + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["post", "read"] }, + "text": { "type": "string", "description": "For post: the finding, one or two sentences." }, + "to": { "type": "array", "items": { "type": "string" }, "description": "For post: the cards it is for; omit for every member." } + }, + "required": ["action"] + }) + } + + fn execution_mode(&self) -> crate::tools::ToolExecutionMode { + crate::tools::ToolExecutionMode::Sequential + } + + fn uses_host_filesystem(&self) -> bool { + false + } + + fn default_permission( + &self, + _mode: crate::types::AgentMode, + ) -> Option { + Some(crate::permissions::Permission::Allow) + } + + async fn execute( + &self, + args: serde_json::Value, + _project_dir: &str, + ) -> Result { + let args: SwarmArgs = serde_json::from_value(args) + .map_err(|e| crate::tools::ToolError::InvalidArguments(e.to_string()))?; + match args.action { + SwarmAction::Read => BoardStore::user() + .get(self.session) + .map(|board| board.member_view(&self.card_id)) + .map_err(|e| crate::tools::ToolError::ExecutionError(e.to_string())), + SwarmAction::Post => { + let text = args.text.unwrap_or_default(); + post_and_deliver(self.session, &self.card_id, &text, &args.to, &self.deliver) + .map_err(crate::tools::ToolError::InvalidArguments) + } + } + } } /// The `board` tool. Hosted like `task`: its schema is exposed through the @@ -707,7 +1031,11 @@ subagent; the rest start as their dependencies finish. Readers go to done when t to review.\n\ - action \"move\": accept a reviewed card (`to`: \"done\"), send one back with a `note` of what to fix \ (`to`: \"backlog\" — a new subagent retries with your note), or give up on one (`to`: \"failed\").\n\ -- action \"show\": the board.\n\ +- action \"show\": the board and the newest findings.\n\ +- action \"post\": tell the working members something (`text`; `recipients` to address some cards) — \ +a decision, a correction, a change of plan. It reaches them at their next step.\n\ +Members post findings to each other as they work (they have a `swarm` tool), so related cards can run \ +at once instead of waiting; the newest findings come back with every board result. \ Plan for parallel work: independent cards run at once, so split by area and give each writer its \ own files. Results of finished cards reach the cards that wait for them. You are told as cards \ finish; review writers' work (read the files, run the tests) before accepting it, and finish by \ @@ -731,7 +1059,7 @@ impl crate::tools::Tool for BoardTool { let mut schema = serde_json::json!({ "type": "object", "properties": { - "action": { "type": "string", "enum": ["add", "move", "show"] }, + "action": { "type": "string", "enum": ["add", "move", "show", "post"] }, "cards": { "type": "array", "description": "For add: the cards to put on the board.", @@ -751,7 +1079,9 @@ impl crate::tools::Tool for BoardTool { }, "id": { "type": "string", "description": "For move: the card (c1, c2, …)." }, "to": { "type": "string", "enum": ["done", "backlog", "failed"] }, - "note": { "type": "string", "description": "For move to backlog: what to fix." } + "note": { "type": "string", "description": "For move to backlog: what to fix." }, + "text": { "type": "string", "description": "For post: what to tell the working members." }, + "recipients": { "type": "array", "items": { "type": "string" }, "description": "For post: the cards it is for; omit for every member." } }, "required": ["action"] }); @@ -931,6 +1261,65 @@ mod tests { assert_eq!(Board::default().summary(), "The board is empty."); } + #[test] + fn findings_reach_working_members_and_later_cards() { + let mut board = Board::default(); + board + .add(vec![ + spec("Map", false, &[], &[]), + spec("Parse", true, &[], &["src/parse.rs"]), + spec("Docs", false, &[], &[]), + spec("Wire", true, &["c1"], &["src/main.rs"]), + ]) + .unwrap(); + board.start("c1", "child-1"); + board.start("c2", "child-2"); + board.start("c3", "child-3"); + + // Everyone working but the author hears a broadcast. + let all = board.post("c1", " Tokens live in lexer.rs ", &[]).unwrap(); + assert_eq!((all.id, all.text.as_str()), (1, "Tokens live in lexer.rs")); + assert_eq!(board.recipients(&all), vec!["child-2", "child-3"]); + + // Addressed by id or title, only the addressee. + let one = board.post("c2", "parse() now returns Result", &["docs".into()]).unwrap(); + assert_eq!(one.to, vec!["c3"]); + assert_eq!(board.recipients(&one), vec!["child-3"]); + assert!(board.post("c2", "x", &["nope".into()]).is_err()); + assert!(board.post("c9", "x", &[]).is_err()); + assert!(board.post("c1", " ", &[]).is_err()); + + // The lead posts too, and sees everything in its summary. + board.post(LEAD, "Keep the public API", &[]).unwrap(); + let summary = board.summary(); + assert!(summary.contains("findings:\n- #1 c1 \"Map\" (Map role): Tokens live in lexer.rs"), "{summary}"); + assert!(summary.contains("#2 c2 \"Parse\" (Parse role) \u{2192} c3: parse() now returns Result"), "{summary}"); + assert!(summary.contains("#3 the lead: Keep the public API"), "{summary}"); + + // A card starting later gets the broadcasts, not others' private notes. + let prompt = board.child_prompt("c4").unwrap(); + assert!(prompt.contains("Tokens live in lexer.rs"), "{prompt}"); + assert!(prompt.contains("Keep the public API"), "{prompt}"); + assert!(!prompt.contains("returns Result"), "{prompt}"); + assert!(prompt.contains("`swarm` tool") && prompt.contains("Your card id is c4."), "{prompt}"); + + // The addressee's view has it. + assert!(board.member_view("c3").contains("returns Result")); + assert!(board.member_view("c3").contains("c3 Docs [Docs role · working] (you)")); + } + + #[test] + fn the_findings_log_keeps_the_newest() { + let mut board = Board::default(); + board.add(vec![spec("Map", false, &[], &[])]).unwrap(); + for n in 0..(MAX_FINDINGS + 5) { + board.post("c1", &format!("note {n}"), &[]).unwrap(); + } + assert_eq!(board.findings.len(), MAX_FINDINGS); + assert_eq!(board.findings[0].id, 6); + assert_eq!(board.findings.last().unwrap().id as usize, MAX_FINDINGS + 5); + } + #[test] fn the_store_keeps_the_switch_and_the_cards() { let dir = std::env::temp_dir().join(format!("agente-boards-{}", Uuid::new_v4())); diff --git a/crates/agente-tui/src/app/agent_events/subagents.rs b/crates/agente-tui/src/app/agent_events/subagents.rs index 9d09e2d5..12c25686 100644 --- a/crates/agente-tui/src/app/agent_events/subagents.rs +++ b/crates/agente-tui/src/app/agent_events/subagents.rs @@ -10,6 +10,7 @@ impl App { match event { AgentEvent::BoardChanged { board } => { self.state.agent.board = Some(board); + self.sync_swarm_lanes(); } AgentEvent::SubagentStarted { id, @@ -66,6 +67,7 @@ impl App { description.clone(), ); } + self.sync_swarm_lanes(); tracing::info!( subagent_id = %id, subagent_type = %subagent_type, @@ -269,4 +271,18 @@ impl App { .get_mut(id) .expect("subagent card just inserted") } + + /// Give every subagent working a board card its lane (card, feeds, the + /// newest finding touching it), so its transcript card reads as part of + /// the swarm. Runs when the board changes and when a child appears. + fn sync_swarm_lanes(&mut self) { + let Some(board) = self.state.agent.board.as_ref() else { + return; + }; + for (id, card) in self.state.agent.subagents.iter_mut() { + if let Some(lane) = crate::state::SwarmLane::of(board, id) { + card.swarm = Some(lane); + } + } + } } diff --git a/crates/agente-tui/src/board_view.rs b/crates/agente-tui/src/board_view.rs index 8692afb2..e0415cb1 100644 --- a/crates/agente-tui/src/board_view.rs +++ b/crates/agente-tui/src/board_view.rs @@ -4,7 +4,9 @@ //! Four columns hard-left to hard-right: Backlog, Working, Review, Done //! (failed cards sit in Done with a red `✗`). A card is two lines: its title, //! then `role · model` dim; the working ones carry the accent `●`, cards -//! waiting on others say what for. Esc closes, `s` turns swarm mode off/on. +//! waiting on others say what for. Under the columns, the newest findings +//! the members posted to each other (`c1 → c2 text`), route in a column. +//! Esc closes, `s` turns swarm mode off/on. use agente_core::swarm::{Board, Card, CardStatus}; use ratatui::layout::Rect; @@ -24,6 +26,40 @@ const COLUMNS: [(&str, &[CardStatus]); 4] = [ ("Done", &[CardStatus::Done, CardStatus::Failed]), ]; +/// Findings the board shows under its columns. +const MAX_FINDING_ROWS: usize = 4; + +/// `Findings N` then the newest `shown`, oldest first: the route in a +/// column hard left, the text beside it. +fn finding_lines(board: &Board, shown: usize, width: usize) -> Vec> { + let newest = &board.findings[board.findings.len() - shown..]; + let route_width = newest + .iter() + .map(|finding| finding.route().chars().count()) + .max() + .unwrap_or(0) + .min(width / 3); + let mut lines = vec![Line::from(vec![ + s("Findings", style::muted()), + s(format!(" {}", board.findings.len()), style::dim()), + ])]; + for finding in newest { + let route = truncate_cells(&finding.route(), route_width); + let pad = route_width.saturating_sub(route.chars().count()); + let text_width = width.saturating_sub(route_width + 2); + let route_style = if finding.from == agente_core::swarm::LEAD { + style::muted() + } else { + style::dim() + }; + lines.push(Line::from(vec![ + s(format!("{route}{} ", " ".repeat(pad)), route_style), + s(truncate_cells(&finding.text, text_width), style::muted()), + ])); + } + lines +} + fn card_lines(card: &Card, width: usize) -> [Line<'static>; 2] { let (mark, mark_style) = match card.status { CardStatus::Working => ("● ", style::accent()), @@ -125,7 +161,15 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut AppState) { frame.render_widget(Paragraph::new(s(tally(&board), style::dim())), top); let gap = 2u16; let column_width = (inner_width.saturating_sub(gap * 3)) / 4; - let rows = modal.body.height.saturating_sub(3); + // The findings band: a header and the newest few, when there is + // room for them and the columns both. + let shown_findings = board.findings.len().min(MAX_FINDING_ROWS); + let findings_rows = if shown_findings > 0 && modal.body.height >= 14 { + shown_findings as u16 + 2 + } else { + 0 + }; + let rows = modal.body.height.saturating_sub(3 + findings_rows); let rows_usize = rows as usize; // Each card occupies 2 lines + 1 gap row (the final card needs no gap). let full_cap = ((rows_usize + 1) / 3).max(1); @@ -194,6 +238,13 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut AppState) { let list = Rect::new(x, top.y + 3, column_width, rows); frame.render_widget(Paragraph::new(lines), list); } + if findings_rows > 0 { + let band = Rect::new(top.x, top.y + 3 + rows + 1, inner_width, findings_rows - 1); + frame.render_widget( + Paragraph::new(finding_lines(&board, shown_findings, inner_width as usize)), + band, + ); + } } } let mut hints = vec![( @@ -259,6 +310,32 @@ mod tests { assert!(text.contains("2 cards · 1 working"), "{text}"); } + #[test] + fn findings_sit_under_the_columns() { + let mut board = Board::default(); + board.enabled = true; + let spec = |title: &str| -> CardSpec { + serde_json::from_value(serde_json::json!({ + "title": title, "role": "Mapper", "prompt": "p" + })) + .unwrap() + }; + board.add(vec![spec("Map code"), spec("Write docs")]).unwrap(); + board.start("c1", "child-1"); + board.start("c2", "child-2"); + board.post("c1", "Tokens live in lexer.rs", &[]).unwrap(); + board.post("c2", "Docs cite parse()", &["c1".into()]).unwrap(); + board.post(agente_core::swarm::LEAD, "Keep the public API", &[]).unwrap(); + let mut state = AppState::new(AppConfig::default(), "/tmp/board-findings".into()); + state.agent.board = Some(board); + state.input.show_board = true; + let text = draw(&mut state); + assert!(text.contains("Findings 3"), "{text}"); + assert!(text.contains("c1 Tokens live in lexer.rs"), "{text}"); + assert!(text.contains("c2 → c1 Docs cite parse()"), "{text}"); + assert!(text.contains("lead Keep the public API"), "{text}"); + } + #[test] fn an_empty_board_says_how_to_start() { let mut state = AppState::new(AppConfig::default(), "/tmp/board".into()); diff --git a/crates/agente-tui/src/state/agent.rs b/crates/agente-tui/src/state/agent.rs index d65c6442..f263e6f5 100644 --- a/crates/agente-tui/src/state/agent.rs +++ b/crates/agente-tui/src/state/agent.rs @@ -356,6 +356,50 @@ pub struct SubagentUiState { pub worktree: Option, /// What this child's model calls cost (its own nested children included). pub spend: Spend, + /// The swarm card this child works, when a board started it. + pub swarm: Option, +} + +/// A subagent's place in a swarm, read from the board: its card, whom its +/// result feeds, and the newest finding it posted or was sent. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SwarmLane { + pub card_id: String, + pub title: String, + pub role: String, + /// Cards that wait on this one. + pub feeds: Vec, + /// `c1 → c2 text` — the newest finding touching this card. + pub latest: Option, +} + +impl SwarmLane { + /// The lane for `child_id` on `board`, if a card of it is that child's. + pub fn of(board: &agente_core::swarm::Board, child_id: &str) -> Option { + let card = board + .cards + .iter() + .find(|card| card.child_id.as_deref() == Some(child_id))?; + let feeds = board + .cards + .iter() + .filter(|other| other.depends_on.iter().any(|dep| dep == &card.id)) + .map(|other| other.id.clone()) + .collect(); + let latest = board + .findings + .iter() + .rev() + .find(|finding| finding.touches(&card.id)) + .map(|finding| format!("{} {}", finding.route(), finding.text)); + Some(Self { + card_id: card.id.clone(), + title: card.title.clone(), + role: card.role.clone(), + feeds, + latest, + }) + } } impl SubagentUiState { diff --git a/crates/agente-tui/src/state/mod.rs b/crates/agente-tui/src/state/mod.rs index b60268d6..0feb8027 100644 --- a/crates/agente-tui/src/state/mod.rs +++ b/crates/agente-tui/src/state/mod.rs @@ -26,7 +26,7 @@ pub use session::diff_line_counts; pub use agent::{ AgentRuntimeState, LiveToolCall, QueuedMessage, RetryStatus, Spend, SubagentToolRow, - SubagentUiState, WorkMode, + SubagentUiState, SwarmLane, WorkMode, }; pub use config::{ConfigState, ConnectScreen, DiscoveryStatus, ModelEntry}; pub use hits::{HitMap, HitTarget, ListId}; diff --git a/crates/agente-tui/src/ui_harness.rs b/crates/agente-tui/src/ui_harness.rs index 02718da7..15998c64 100644 --- a/crates/agente-tui/src/ui_harness.rs +++ b/crates/agente-tui/src/ui_harness.rs @@ -703,6 +703,7 @@ fn seed_subagent(state: &mut AppState) { finished_at: None, worktree: Some(worktree), spend: Default::default(), + swarm: None, }, ); } diff --git a/crates/agente-tui/src/widgets/chat/blocks.rs b/crates/agente-tui/src/widgets/chat/blocks.rs index a3945347..6d367abd 100644 --- a/crates/agente-tui/src/widgets/chat/blocks.rs +++ b/crates/agente-tui/src/widgets/chat/blocks.rs @@ -1001,8 +1001,19 @@ pub(super) fn render_subagent( "completed" }); let kind = SubagentStatusKind::from_status(status); - let type_label = capitalize_label(entry.subagent_type.as_deref().unwrap_or("subagent")); - let description = ui.map(|u| u.description.as_str()).unwrap_or(&entry.content); + // A swarm member is its card: `c2 Parse lexer` then the role, so the + // members of one swarm read as one team instead of unrelated spawns. + let lane = ui.and_then(|u| u.swarm.as_ref()); + let (type_label, description) = match lane { + Some(lane) => ( + format!("{} {}", lane.card_id, lane.title), + lane.role.as_str(), + ), + None => ( + capitalize_label(entry.subagent_type.as_deref().unwrap_or("subagent")), + ui.map(|u| u.description.as_str()).unwrap_or(&entry.content), + ), + }; // One-column inset, aligned with the `◆` of ordinary tool rows. let mut lead = vec![ @@ -1062,13 +1073,28 @@ pub(super) fn render_subagent( on(Style::default().fg(FG_DIM())), )); } + if let Some(lane) = lane.filter(|lane| !lane.feeds.is_empty()) { + detail.push(Span::styled( + format!(" · feeds {}", lane.feeds.join(", ")), + on(Style::default().fg(FG_DIM())), + )); + } } - vec![ - Line::from(header), - Line::from(fill_row(detail, width, bg)), - themed_blank_row(width), - ] + let mut lines = vec![Line::from(header), Line::from(fill_row(detail, width, bg))]; + // The newest finding this member posted or was sent: `✎ c1 → c2 text`. + if let Some(latest) = lane.and_then(|lane| lane.latest.as_deref()) { + let finding = vec![ + Span::styled(" \u{270e} ", on(Style::default().fg(FG_DIM()))), + Span::styled( + truncate_cells(latest, width.saturating_sub(6)), + on(Style::default().fg(FG_MUTED())), + ), + ]; + lines.push(Line::from(fill_row(finding, width, bg))); + } + lines.push(themed_blank_row(width)); + lines } /// `explore` to `Explore`; other labels keep their shape after the first char. diff --git a/crates/agente-tui/src/widgets/chat/snapshot.rs b/crates/agente-tui/src/widgets/chat/snapshot.rs index 7999d99e..7d9d4127 100644 --- a/crates/agente-tui/src/widgets/chat/snapshot.rs +++ b/crates/agente-tui/src/widgets/chat/snapshot.rs @@ -337,6 +337,21 @@ pub(super) fn subagent_fingerprint( .as_ref() .map(|wt| format!("{}:{}", wt.branch, wt.dirty)) .unwrap_or_default(); + // A board change (a finding, a card it feeds) reshapes a member's card. + let swarm = state + .swarm + .as_ref() + .map(|lane| { + format!( + "{}|{}|{}|{}|{}", + lane.card_id, + lane.title, + lane.role, + lane.feeds.join(","), + lane.latest.as_deref().unwrap_or_default() + ) + }) + .unwrap_or_default(); for byte in state .description .bytes() @@ -347,6 +362,7 @@ pub(super) fn subagent_fingerprint( // Cost shows on the card: a new tenth of a cent re-renders it. .chain(((state.spend.cost_usd * 1000.0).round() as u64).to_le_bytes()) .chain((state.tool_rows.len() as u64).to_le_bytes()) + .chain(swarm.bytes()) { h = (h ^ u64::from(byte)).wrapping_mul(0x100_0000_01B3); } diff --git a/crates/agente-tui/src/widgets/chat/tests.rs b/crates/agente-tui/src/widgets/chat/tests.rs index 2a92d3be..dfae8bbb 100644 --- a/crates/agente-tui/src/widgets/chat/tests.rs +++ b/crates/agente-tui/src/widgets/chat/tests.rs @@ -93,6 +93,55 @@ fn subagent_card_stays_compact_with_long_history() { assert_eq!(before, subagent_fingerprint(&map, 100)); } +#[test] +fn a_swarm_member_card_reads_as_its_lane() { + let mut board = agente_core::swarm::Board::default(); + let spec = |title: &str, deps: &[&str]| -> agente_core::swarm::CardSpec { + serde_json::from_value(serde_json::json!({ + "title": title, "role": "Lexer mapper", "prompt": "p", "depends_on": deps + })) + .unwrap() + }; + board + .add(vec![spec("Map lexer", &[]), spec("Wire parser", &["c1"])]) + .unwrap(); + board.start("c1", "child"); + board.post("c1", "Tokens live in lexer.rs", &[]).unwrap(); + + let mut entry = tool_entry("task", "Map lexer", None); + entry.subagent_id = Some("child".into()); + let mut ui = SubagentUiState { + status: "running".into(), + description: "Map lexer".into(), + swarm: crate::state::SwarmLane::of(&board, "child"), + ..Default::default() + }; + let text = |line: &Line<'static>| -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect() + }; + let lines = render_subagent(&entry, 100, Some(&ui), false); + assert_eq!(lines.len(), 4, "header + activity + finding + gap"); + let row1 = text(&lines[0]); + assert!(row1.contains("c1 Map lexer Lexer mapper"), "row1: {row1:?}"); + assert!(text(&lines[1]).contains("· feeds c2"), "{:?}", text(&lines[1])); + assert!( + text(&lines[2]).contains("\u{270e} c1 Tokens live in lexer.rs"), + "{:?}", + text(&lines[2]) + ); + + // A new finding re-renders the card. + let mut map = std::collections::HashMap::from([("child".into(), ui.clone())]); + let before = subagent_fingerprint(&map, 100); + board.post(agente_core::swarm::LEAD, "Keep the API", &["c1".into()]).unwrap(); + ui.swarm = crate::state::SwarmLane::of(&board, "child"); + map.insert("child".into(), ui); + assert_ne!(before, subagent_fingerprint(&map, 100)); +} + #[test] fn expanded_group_survives_opening_a_child_and_keeps_line_alignment() { let entries: Vec<_> = (0..3).map(|_| tool_entry("grep", "output", None)).collect(); diff --git a/docs/SUBAGENTS_PLAN.md b/docs/SUBAGENTS_PLAN.md index fd65f525..47d37de6 100644 --- a/docs/SUBAGENTS_PLAN.md +++ b/docs/SUBAGENTS_PLAN.md @@ -177,7 +177,16 @@ model gets the `board` tool, adds cards (role, model, prompt, depends_on, owns), and the host starts ready cards as created subagents, moving them Backlog → Working → Review/Done/Failed and starting dependents as cards finish. One writer per path. Board views: TUI `/board`, Desktop Board pane. -Still to build below: `race` and `best_of`. +Members talk to each other through a findings log on the board (built +2026-11-24): each card's subagent gets the `swarm` tool — `post` a finding +(optionally `to` some cards) or `read` the cards and log — and an inbox, so a +post lands in the working members' conversations at their next step and in +the prompt of every card that starts later. The lead reads the newest findings +in every `board` result and broadcasts with `board` `post`. Display: a turn's +members draw as one swarm block (lanes + findings) on Desktop and as lane-named +cards with their newest finding in the TUI. +Still to build below: `race` and `best_of`; a member asking the lead and +waiting (`ask_lead`); steering one running card. - Hosted `swarm` tool: the parent creates every member in one call — `{ strategy: "fan_out" | "race" | "best_of", members: [{ role, @@ -197,6 +206,7 @@ Still to build below: `race` and `best_of`. ## Out of scope (for now) - Subagents in Home / Design (the TypeScript runtime has none). -- Agents messaging each other (agent teams). +- Free-form chat between agents (members share findings through the board, + not conversations). - Learned / automatic routing; the parent picks by your notes. - Project-level model lists.