forked from spacedriveapp/spacebot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspawn_worker.rs
More file actions
193 lines (173 loc) · 7.04 KB
/
spawn_worker.rs
File metadata and controls
193 lines (173 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Spawn worker tool for creating new workers.
use crate::WorkerId;
use crate::agent::channel::{
ChannelState, spawn_opencode_worker_from_state, spawn_worker_from_state,
};
use rig::completion::ToolDefinition;
use rig::tool::Tool;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
/// Tool for spawning workers.
#[derive(Debug, Clone)]
pub struct SpawnWorkerTool {
state: ChannelState,
}
impl SpawnWorkerTool {
/// Create a new spawn worker tool with access to channel state.
pub fn new(state: ChannelState) -> Self {
Self { state }
}
}
/// Error type for spawn worker tool.
#[derive(Debug, thiserror::Error)]
#[error("Worker spawn failed: {0}")]
pub struct SpawnWorkerError(String);
/// Arguments for spawn worker tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SpawnWorkerArgs {
/// The task description for the worker.
pub task: String,
/// Whether this is an interactive worker (accepts follow-up messages).
#[serde(default)]
pub interactive: bool,
/// Optional list of skill names to suggest to the worker. The worker sees
/// all available skills and can read any of them via read_skill, but
/// suggested skills are flagged as recommended for this task.
#[serde(default)]
pub suggested_skills: Vec<String>,
/// Worker type: "builtin" (default) runs a Rig agent loop with shell/file/exec
/// tools. "opencode" spawns an OpenCode subprocess with full coding agent
/// capabilities. Use "opencode" for complex coding tasks that benefit from
/// codebase exploration and context management.
#[serde(default)]
pub worker_type: Option<String>,
/// Working directory for the worker. Required for "opencode" workers.
/// The OpenCode agent will operate in this directory.
#[serde(default)]
pub directory: Option<String>,
}
/// Output from spawn worker tool.
#[derive(Debug, Serialize)]
pub struct SpawnWorkerOutput {
/// The ID of the spawned worker.
pub worker_id: WorkerId,
/// Whether the worker was spawned successfully.
pub spawned: bool,
/// Whether this is an interactive worker.
pub interactive: bool,
/// Status message.
pub message: String,
}
impl Tool for SpawnWorkerTool {
const NAME: &'static str = "spawn_worker";
type Error = SpawnWorkerError;
type Args = SpawnWorkerArgs;
type Output = SpawnWorkerOutput;
async fn definition(&self, _prompt: String) -> ToolDefinition {
let rc = &self.state.deps.runtime_config;
let browser_enabled = rc.browser_config.load().enabled;
let web_search_enabled = rc.brave_search_key.load().is_some();
let opencode_enabled = rc.opencode.load().enabled;
let mut tools_list = vec!["shell", "file", "exec"];
if browser_enabled {
tools_list.push("browser");
}
if web_search_enabled {
tools_list.push("web_search");
}
let opencode_note = if opencode_enabled {
" Set worker_type to \"opencode\" with a directory path for complex coding tasks — this spawns a full OpenCode coding agent with codebase exploration, context management, and its own tool suite."
} else {
""
};
let base_description = crate::prompts::text::get("tools/spawn_worker");
let description = base_description
.replace("{tools}", &tools_list.join(", "))
.replace("{opencode_note}", opencode_note);
let mut properties = serde_json::json!({
"task": {
"type": "string",
"description": "Clear, specific description of what the worker should do. Include all context needed since the worker can't see your conversation."
},
"interactive": {
"type": "boolean",
"default": false,
"description": "If true, the worker stays alive and accepts follow-up messages via route_to_worker. If false (default), the worker runs once and returns."
},
"suggested_skills": {
"type": "array",
"items": { "type": "string" },
"description": "Skill names from <available_skills> that are likely relevant to this task. The worker sees all skills and decides what to read, but suggested skills are flagged as recommended."
}
});
if opencode_enabled && let Some(obj) = properties.as_object_mut() {
obj.insert(
"worker_type".to_string(),
serde_json::json!({
"type": "string",
"enum": ["builtin", "opencode"],
"default": "builtin",
"description": "\"builtin\" (default) runs a Rig agent loop. \"opencode\" spawns a full OpenCode coding agent — use for complex multi-file coding tasks."
}),
);
obj.insert(
"directory".to_string(),
serde_json::json!({
"type": "string",
"description": "Working directory for the worker. Required when worker_type is \"opencode\". The OpenCode agent operates in this directory."
}),
);
}
ToolDefinition {
name: Self::NAME.to_string(),
description,
parameters: serde_json::json!({
"type": "object",
"properties": properties,
"required": ["task"]
}),
}
}
async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error> {
let is_opencode = args.worker_type.as_deref() == Some("opencode");
let worker_id = if is_opencode {
let directory = args.directory.as_deref().ok_or_else(|| {
SpawnWorkerError("directory is required for opencode workers".into())
})?;
spawn_opencode_worker_from_state(&self.state, &args.task, directory, args.interactive)
.await
.map_err(|e| SpawnWorkerError(format!("{e}")))?
} else {
spawn_worker_from_state(
&self.state,
&args.task,
args.interactive,
&args
.suggested_skills
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
)
.await
.map_err(|e| SpawnWorkerError(format!("{e}")))?
};
let worker_type_label = if is_opencode { "OpenCode" } else { "builtin" };
let message = if args.interactive {
format!(
"Interactive {worker_type_label} worker {worker_id} spawned for: {}. Route follow-ups with route_to_worker.",
args.task
)
} else {
format!(
"{worker_type_label} worker {worker_id} spawned for: {}. It will report back when done.",
args.task
)
};
Ok(SpawnWorkerOutput {
worker_id,
spawned: true,
interactive: args.interactive,
message,
})
}
}