Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): replace sessions_spawn with synchronous delegate tool
Jiayuan Zhangd3ef8ecc3126
diff --git a/packages/core/src/agent/index.ts b/packages/core/src/agent/index.tsindex 6dccd6f7f1..01488856ef 100644--- a/packages/core/src/agent/index.ts+++ b/packages/core/src/agent/index.ts@@ -13,6 +13,8 @@ export * from "./tools.js";export * from "./tools/policy.js";export * from "./tools/groups.js";export * from "./extract-text.js";+// @deprecated — Old subagent registry. Use `delegate` tool instead.+// Kept temporarily for desktop app compatibility.export {listSubagentRuns,getSubagentRun,@@ -23,6 +25,7 @@ export type {SubagentRunOutcome,SubagentGroup,} from "./subagent/types.js";+export {readClaudeCliCredentials,readCodexCliCredentials,diff --git a/packages/core/src/agent/run-log.ts b/packages/core/src/agent/run-log.tsindex 18bf5c80bd..29b525850e 100644--- a/packages/core/src/agent/run-log.ts+++ b/packages/core/src/agent/run-log.ts@@ -45,6 +45,16 @@* - `compaction_detail` — Detailed compaction breakdown.* Fields: pre_pruning_tokens, post_compaction_tokens, messages_removed, reason, pruning_applied*+ * ### Delegation (Sub-Agents)+ * - `delegate_start` — Delegate tool invoked.+ * Fields: task_count, timeout_seconds, labels[]+ * - `delegate_task_start` — Individual sub-agent task begins.+ * Fields: index, label, task (first 200 chars)+ * - `delegate_task_end` — Individual sub-agent task completes.+ * Fields: index, label, status (ok|error|timeout), duration_ms, findings_chars, error?+ * - `delegate_end` — All delegated tasks complete.+ * Fields: task_count, ok, errors, timeouts, total_duration_ms+ ** ### Error Recovery* - `context_overflow` — Context window overflow detected.* Fields: attempt, messages_beforediff --git a/packages/core/src/agent/runner.ts b/packages/core/src/agent/runner.tsindex e5f6b2b8f4..c812b4a15a 100644--- a/packages/core/src/agent/runner.ts+++ b/packages/core/src/agent/runner.ts@@ -393,11 +393,10 @@ export class Agent {const mergedToolsConfig = mergeToolsConfig(profileToolsConfig, options.tools);const profileDir = this.profile?.getProfileDir();// Use this.sessionId (which may be auto-generated) instead of options.sessionId- // (which may be undefined). Without this, sessions_list and sessions_spawn- // can't find sub-agent runs because they have no session context.+ // (which may be undefined). Without this, delegate tool has no session context.this.toolsOptions = mergedToolsConfig- ? { ...options, sessionId: this.sessionId, cwd: effectiveCwd, tools: mergedToolsConfig, profileDir, provider: this.resolvedProvider }- : { ...options, sessionId: this.sessionId, cwd: effectiveCwd, profileDir, provider: this.resolvedProvider };+ ? { ...options, sessionId: this.sessionId, cwd: effectiveCwd, tools: mergedToolsConfig, profileDir, provider: this.resolvedProvider, runLog: this.runLog }+ : { ...options, sessionId: this.sessionId, cwd: effectiveCwd, profileDir, provider: this.resolvedProvider, runLog: this.runLog };const tools = resolveTools(this.toolsOptions);if (this.debug) {@@ -1242,10 +1241,10 @@ export class Agent {// Update internal statethis.resolvedProvider = providerId;- // Keep toolsOptions.provider in sync so sessions_spawn inherits the current provider+ // Keep toolsOptions.provider in sync so delegate tool inherits the current providerthis.toolsOptions = { ...this.toolsOptions, provider: providerId };- // Reload tools so sessions_spawn picks up the new provider in its closure.+ // Reload tools so delegate picks up the new provider in its closure.// Without this, the existing tool instance still captures the old provider.const tools = resolveTools(this.toolsOptions);this.agent.setTools(tools);diff --git a/packages/core/src/agent/system-prompt/sections.ts b/packages/core/src/agent/system-prompt/sections.tsindex fae475353b..bf935fcee9 100644--- a/packages/core/src/agent/system-prompt/sections.ts+++ b/packages/core/src/agent/system-prompt/sections.ts@@ -28,7 +28,7 @@ const CORE_TOOL_SUMMARIES: Record<string, string> = {web_search: "Search the web via Devv Search",web_fetch: "Fetch and extract readable content from a URL",memory_search: "Search memory files by keyword",- sessions_spawn: "Spawn a sub-agent session",+ delegate: "Run tasks in parallel via sub-agents",data: "Query structured financial and market data",};@@ -43,7 +43,7 @@ const TOOL_ORDER = ["web_search","web_fetch","memory_search",- "sessions_spawn",+ "delegate","data",];@@ -313,52 +313,34 @@ export function buildConditionalToolSections();}- // Subagent tools (full mode only — minimal agents cannot spawn)- if (mode === "full" && toolSet.has("sessions_spawn")) {+ // Delegate tool (full mode only — sub-agents cannot delegate)+ if (mode === "full" && toolSet.has("delegate")) {lines.push(- "## Sub-Agents",- "If a task is complex or long-running, spawn a sub-agent. It will do the work and report back when done.",+ "## Delegation (Sub-Agents)",+ "Use `delegate` to run tasks in parallel via isolated sub-agents. " ++ "Each task gets its own agent with full tool access. Results are returned directly when all tasks complete.","",- "### Critical Rules",- "- **NEVER fabricate, guess, or make up data that a sub-agent has not yet returned.** " +- "This includes completion status — do NOT claim tasks are done until you receive actual results.",- "- After spawning, do NOT proceed with work that depends on the sub-agent results. " +- "You can still chat with the user, do unrelated tasks, or explain what the sub-agents are working on.",- "- Sub-agents cannot spawn nested sub-agents.",- "- You can use `sessions_list` to check sub-agent status if needed.",- "",- "### Groups and Continuation (`next`) — ALWAYS use for multi-agent tasks",- "When spawning multiple sub-agents, **always** use `next` to define the follow-up work. " +- "This is the standard pattern — do NOT use bare `announce: \"silent\"` for multi-agent collect-then-act workflows.",+ "### When to Use",+ "- Collecting data from multiple independent sources (e.g. research 3 stocks simultaneously)",+ "- Comparative analysis that can be parallelized (e.g. analyze 5 error logs in parallel)",+ "- Any task where independent sub-tasks would benefit from parallel execution","",+ "### Example","```",- "// First spawn — creates a group automatically, returns groupId",- 'sessions_spawn({ task: "Get AAPL financials", next: "Summarize all data and write a PDF report", label: "AAPL" })',- "// → { groupId: \"grp-abc\", runId: \"...\" }",- "",- "// Subsequent spawns — join the same group",- 'sessions_spawn({ task: "Get MSFT financials", groupId: "grp-abc", label: "MSFT" })',- 'sessions_spawn({ task: "Get GOOG financials", groupId: "grp-abc", label: "GOOG" })',+ "delegate({",+ ' tasks: [',+ ' { task: "Research AAPL financials: revenue, net income, stock price", label: "AAPL" },',+ ' { task: "Research MSFT financials: revenue, net income, stock price", label: "MSFT" },',+ ' { task: "Research GOOG financials: revenue, net income, stock price", label: "GOOG" }',+ " ]",+ "})","```","",- "The system waits for ALL runs in the group to complete, then delivers the combined findings " +- "plus the `next` continuation prompt back to you. You can then use tools (write files, call APIs, etc.) " +- "to complete the follow-up work. The user is NOT blocked during this process — they can keep chatting.",- "",- "Use `next` whenever the user's request involves: collect data → then act on it (summarize, analyze, generate files).",- "Without `next`, findings are summarized but no further action is taken.",- "",- "### Announce Modes (when not using groups)",- "- `announce: \"immediate\"` (default): findings delivered per sub-agent as each completes.",- "- `announce: \"silent\"`: all findings held until every silent sub-agent finishes, then delivered together.",- "Groups always use silent collection internally — you don't need to set announce when using groupId.",- "",- "### Timeout Guidelines",- "Set timeoutSeconds generously — a sub-agent that times out loses all its work.",- "- Simple tasks (search, read, summarize): 1800 (30 min, the default)",- "- Moderate tasks (multi-step research, file downloads + analysis): 1800–2400 (30–40 min)",- "- Complex tasks (code generation, PDF creation, multi-file operations): 2400–3600 (40–60 min)",- "When in doubt, use a longer timeout.",+ "### Rules",+ "- Each sub-agent task should be self-contained — include all context needed in the task description.",+ "- Sub-agents cannot delegate further (no nesting).",+ "- The tool blocks until all tasks complete — plan your workflow accordingly.",+ "- Set `timeoutSeconds` generously for complex tasks (default: 1800 = 30 min).","",);}diff --git a/packages/core/src/agent/tools.ts b/packages/core/src/agent/tools.tsindex fd9bf10ae4..83a61876d6 100644--- a/packages/core/src/agent/tools.ts+++ b/packages/core/src/agent/tools.ts@@ -6,8 +6,7 @@ import { createExecTool } from "./tools/exec.js";import { createProcessTool } from "./tools/process.js";import { createGlobTool } from "./tools/glob.js";import { createWebFetchTool, createWebSearchTool } from "./tools/web/index.js";-import { createSessionsSpawnTool } from "./tools/sessions-spawn.js";-import { createSessionsListTool } from "./tools/sessions-list.js";+import { createDelegateTool } from "./tools/delegate.js";import { createMemorySearchTool } from "./tools/memory-search.js";import { createCronTool } from "./tools/cron/index.js";import { createDataTool } from "./tools/data/index.js";@@ -26,12 +25,20 @@ export interface CreateToolsOptions {cwd: string;/** Profile directory for memory_search tool (optional) */profileDir?: string | undefined;- /** Whether this agent is a subagent (passed to sessions_spawn tool) */+ /** Whether this agent is a subagent (passed to delegate tool) */isSubagent?: boolean | undefined;- /** Session ID of the agent (passed to sessions_spawn tool) */+ /** Session ID of the agent (passed to delegate tool) */sessionId?: string | undefined;- /** Resolved provider ID of the parent agent (passed to sessions_spawn for subagent inheritance) */+ /** Resolved provider ID of the parent agent (inherited by sub-agents) */provider?: string | undefined;+ /** Model name (inherited by sub-agents) */+ model?: string | undefined;+ /** API key (inherited by sub-agents) */+ apiKey?: string | undefined;+ /** Whether run-log is enabled (passed to child agents) */+ enableRunLog?: boolean | undefined;+ /** Run-log instance for delegate events */+ runLog?: import("./run-log.js").RunLog | undefined;/** Callback invoked when exec tool needs approval before running a command */onExecApprovalNeeded?: ExecApprovalCallback | undefined;/** Callback for sending files through messaging channels */@@ -143,17 +150,18 @@ export function createAllTools(options: CreateToolsOptions | string): AgentTool<tools.push(sendFileTool as AgentTool<any>);}- // Add sessions_spawn tool (will be filtered by policy for subagents)- const sessionsSpawnTool = createSessionsSpawnTool({+ // Add delegate tool (will be filtered by policy for subagents)+ const delegateTool = createDelegateTool({isSubagent: isSubagent ?? false,- ...(sessionId !== undefined ? { sessionId } : {}),- ...(opts.provider !== undefined ? { provider: opts.provider } : {}),+ sessionId,+ provider: opts.provider,+ model: opts.model,+ apiKey: opts.apiKey,+ cwd,+ runLog: opts.runLog,+ enableRunLog: opts.enableRunLog,});- tools.push(sessionsSpawnTool as AgentTool<any>);-- // Add sessions_list tool- const sessionsListTool = createSessionsListTool({ ...(sessionId !== undefined ? { sessionId } : {}) });- tools.push(sessionsListTool as AgentTool<any>);+ tools.push(delegateTool as AgentTool<any>);return tools;}@@ -162,6 +170,8 @@ export function createAllTools(options: CreateToolsOptions | string): AgentTool<export interface ResolveToolsOptions extends AgentOptions {/** Profile directory for memory_search tool (computed from profileId if not provided) */profileDir?: string | undefined;+ /** Run-log instance (forwarded to delegate tool) */+ runLog?: import("./run-log.js").RunLog | undefined;}/**@@ -183,6 +193,10 @@ export function resolveTools(options: ResolveToolsOptions): AgentTool<any>[] {isSubagent: options.isSubagent,sessionId: options.sessionId,provider: options.provider,+ model: options.model,+ apiKey: options.apiKey,+ enableRunLog: options.enableRunLog,+ runLog: options.runLog,onExecApprovalNeeded: options.onExecApprovalNeeded,onChannelSendFile: options.onChannelSendFile,});diff --git a/packages/core/src/agent/tools/delegate.ts b/packages/core/src/agent/tools/delegate.tsnew file mode 100644index 0000000000..9c414006dc--- /dev/null+++ b/packages/core/src/agent/tools/delegate.ts@@ -0,0 +1,318 @@+/**+ * delegate tool — run tasks in parallel via sub-agents.+ *+ * Synchronous from the LLM's perspective: the tool blocks until all+ * sub-agent tasks complete (or timeout), then returns combined results+ * directly in the tool response. No async infrastructure needed.+ */++import { join } from "node:path";+import { rmSync } from "node:fs";+import { Writable } from "node:stream";+import { Type } from "@sinclair/typebox";+import type { AgentTool } from "@mariozechner/pi-agent-core";+import { Agent } from "../runner.js";+import type { RunLog } from "../run-log.js";+import { DATA_DIR } from "@multica/utils";++const TaskItemSchema = Type.Object({+ task: Type.String({ description: "The task for the sub-agent to perform.", minLength: 1 }),+ label: Type.Optional(+ Type.String({ description: "Short human-readable label for this task (used in output headers)." }),+ ),+});++const DelegateSchema = Type.Object({+ tasks: Type.Array(TaskItemSchema, {+ description: "One or more tasks to run in parallel. Each spawns an isolated sub-agent.",+ minItems: 1,+ }),+ timeoutSeconds: Type.Optional(+ Type.Number({+ description:+ "Per-task timeout in seconds. Default: 1800 (30 min). " ++ "Set higher for complex tasks. The sub-agent is aborted if it exceeds this limit.",+ minimum: 0,+ }),+ ),+});++type DelegateArgs = {+ tasks: Array<{ task: string; label?: string }>;+ timeoutSeconds?: number;+};++type TaskResult = {+ index: number;+ label: string;+ status: "ok" | "error" | "timeout";+ durationMs: number;+ findings: string;+ error?: string;+};++export type DelegateResult = {+ taskCount: number;+ ok: number;+ errors: number;+ timeouts: number;+ totalDurationMs: number;+ tasks: TaskResult[];+};++export interface CreateDelegateToolOptions {+ /** Whether the current agent is itself a subagent */+ isSubagent?: boolean;+ /** Session ID of the parent agent */+ sessionId?: string;+ /** Resolved provider ID (inherited by sub-agents) */+ provider?: string;+ /** Model override (inherited by sub-agents) */+ model?: string;+ /** API key (inherited by sub-agents) */+ apiKey?: string;+ /** Working directory (inherited by sub-agents) */+ cwd?: string;+ /** Run-log instance for emitting delegate events */+ runLog?: RunLog;+ /** Whether run-log is enabled (passed to child agents) */+ enableRunLog?: boolean;+}++const DEFAULT_TIMEOUT_SECONDS = 1800; // 30 minutes++function formatElapsed(ms: number): string {+ const totalSeconds = Math.round(ms / 1000);+ if (totalSeconds < 60) return `${totalSeconds}s`;+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ if (minutes < 60) return seconds > 0 ? `${minutes}m${seconds}s` : `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ const remainingMinutes = minutes % 60;+ return remainingMinutes > 0 ? `${hours}h${remainingMinutes}m` : `${hours}h`;+}++/**+ * Run a single sub-agent task with timeout.+ */+async function runSubagentTask(+ taskDef: { task: string; label?: string },+ index: number,+ timeoutMs: number,+ parentOptions: CreateDelegateToolOptions,+ runLog?: RunLog,+): Promise<TaskResult> {+ const label = taskDef.label || `Task ${index + 1}`;+ const start = Date.now();++ runLog?.log("delegate_task_start", {+ index,+ label,+ task: taskDef.task.slice(0, 200),+ });++ const childAgent = new Agent({+ provider: parentOptions.provider,+ model: parentOptions.model,+ apiKey: parentOptions.apiKey,+ cwd: parentOptions.cwd,+ isSubagent: true,+ enableSkills: false,+ compactionMode: "tokens",+ enableRunLog: parentOptions.enableRunLog,+ // Suppress stdout/stderr output from child agents+ logger: {+ stdout: new NullStream(),+ stderr: new NullStream(),+ },+ });++ try {+ let result: { text: string; error?: string };+ let timedOut = false;++ if (timeoutMs > 0) {+ // Race agent.run against timeout+ result = await Promise.race([+ childAgent.run(taskDef.task),+ new Promise<never>((_, reject) => {+ setTimeout(() => {+ timedOut = true;+ childAgent.abort();+ reject(new Error("timeout"));+ }, timeoutMs);+ }),+ ]).catch((err) => {+ if (timedOut) {+ return { text: "", error: `Timed out after ${formatElapsed(timeoutMs)}` };+ }+ throw err;+ });+ } else {+ // No timeout+ result = await childAgent.run(taskDef.task);+ }++ const durationMs = Date.now() - start;+ const status = timedOut ? "timeout" : result.error ? "error" : "ok";++ const taskResult: TaskResult = {+ index,+ label,+ status,+ durationMs,+ findings: result.text || "(no output)",+ error: result.error || undefined,+ };++ runLog?.log("delegate_task_end", {+ index,+ label,+ status,+ duration_ms: durationMs,+ findings_chars: taskResult.findings.length,+ error: taskResult.error,+ });++ return taskResult;+ } catch (err) {+ const durationMs = Date.now() - start;+ const message = err instanceof Error ? err.message : String(err);++ const taskResult: TaskResult = {+ index,+ label,+ status: "error",+ durationMs,+ findings: "",+ error: message,+ };++ runLog?.log("delegate_task_end", {+ index,+ label,+ status: "error",+ duration_ms: durationMs,+ findings_chars: 0,+ error: message,+ });++ return taskResult;+ } finally {+ // Flush session writes before cleanup+ await childAgent.flushSession();++ // Clean up child session directory unless run-log is enabled+ if (!parentOptions.enableRunLog) {+ try {+ const sessionDir = join(DATA_DIR, "sessions", childAgent.sessionId);+ rmSync(sessionDir, { recursive: true, force: true });+ } catch {+ // Best-effort cleanup+ }+ }+ }+}++export function createDelegateTool(+ options: CreateDelegateToolOptions,+): AgentTool<typeof DelegateSchema, DelegateResult> {+ return {+ name: "delegate",+ label: "Delegate Tasks",+ description:+ "Run one or more tasks in parallel via isolated sub-agents. " ++ "Each task gets its own agent with full tool access. " ++ "Results are returned directly when all tasks complete. " ++ "Use this for parallelizable work: multi-stock research, comparative analysis, " ++ "data collection from multiple sources, or any task that benefits from parallel execution.",+ parameters: DelegateSchema,+ execute: async (_toolCallId, args) => {+ const { tasks, timeoutSeconds } = args as DelegateArgs;+ const timeoutMs = (timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000;++ // Guard: sub-agents cannot delegate+ if (options.isSubagent) {+ return {+ content: [{ type: "text", text: "Error: delegate is not allowed from sub-agent sessions." }],+ details: {+ taskCount: 0,+ ok: 0,+ errors: 1,+ timeouts: 0,+ totalDurationMs: 0,+ tasks: [],+ },+ };+ }++ const labels = tasks.map((t, i) => t.label || `Task ${i + 1}`);++ options.runLog?.log("delegate_start", {+ task_count: tasks.length,+ timeout_seconds: timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,+ labels,+ });++ const totalStart = Date.now();++ // Run all tasks in parallel+ const results = await Promise.all(+ tasks.map((taskDef, index) =>+ runSubagentTask(taskDef, index, timeoutMs, options, options.runLog),+ ),+ );++ const totalDurationMs = Date.now() - totalStart;+ const ok = results.filter((r) => r.status === "ok").length;+ const errors = results.filter((r) => r.status === "error").length;+ const timeouts = results.filter((r) => r.status === "timeout").length;++ options.runLog?.log("delegate_end", {+ task_count: tasks.length,+ ok,+ errors,+ timeouts,+ total_duration_ms: totalDurationMs,+ });++ // Format combined response+ const statusLine =+ `All ${tasks.length} task(s) completed: ${ok} succeeded, ${errors} failed, ${timeouts} timed out.\n` ++ `Total wall time: ${formatElapsed(totalDurationMs)}`;++ const taskSections = results.map((r) => {+ const statusTag = r.status === "ok" ? "OK" : r.status.toUpperCase();+ const header = `--- Task ${r.index + 1}: "${r.label}" [${statusTag}] (${formatElapsed(r.durationMs)}) ---`;+ const body = r.status === "error" && r.error+ ? `Error: ${r.error}\n${r.findings || ""}`+ : r.findings;+ return `${header}\n${body}`;+ });++ const responseText = `${statusLine}\n\n${taskSections.join("\n\n")}`;++ return {+ content: [{ type: "text", text: responseText }],+ details: {+ taskCount: tasks.length,+ ok,+ errors,+ timeouts,+ totalDurationMs,+ tasks: results,+ },+ };+ },+ };+}++/**+ * Writable stream that discards all output.+ * Used to suppress child agent stdout/stderr.+ */+class NullStream extends Writable {+ _write(_chunk: any, _encoding: string, callback: () => void): void {+ callback();+ }+}diff --git a/packages/core/src/agent/tools/groups.ts b/packages/core/src/agent/tools/groups.tsindex a2bbed126a..465d6875a6 100644--- a/packages/core/src/agent/tools/groups.ts+++ b/packages/core/src/agent/tools/groups.ts@@ -34,7 +34,7 @@ export const TOOL_GROUPS: Record<string, string[]> = {"group:memory": ["memory_search"],// Subagent tools- "group:subagent": ["sessions_spawn", "sessions_list"],+ "group:subagent": ["delegate"],// Cron/scheduling tools"group:cron": ["cron"],@@ -61,8 +61,8 @@ export const TOOL_GROUPS: Record<string, string[]> = {* Subagents should not have access to session management or system tools.*/export const DEFAULT_SUBAGENT_TOOL_DENY: string[] = [- // Subagents cannot spawn subagents (no nested spawning)- "sessions_spawn",+ // Subagents cannot delegate (no nested delegation)+ "delegate",];/**diff --git a/packages/core/src/agent/tools/index.ts b/packages/core/src/agent/tools/index.tsindex 3e148e1a91..bb90da2419 100644--- a/packages/core/src/agent/tools/index.ts+++ b/packages/core/src/agent/tools/index.ts@@ -9,7 +9,7 @@ export { createGlobTool } from "./glob.js";export { createWebFetchTool, createWebSearchTool } from "./web/index.js";export { createCronTool } from "./cron/index.js";export { createDataTool } from "./data/index.js";-export { createSessionsListTool } from "./sessions-list.js";+export { createDelegateTool } from "./delegate.js";// Tool groupsexport {