| 1 | /** |
| 2 | * AgentTeams for DeepSeek Harness. |
| 3 | * |
| 4 | * A host-plane plugin that registers the `agent_teams_*` tools and one usage |
| 5 | * agent-scoped usage section. Each session keeps a stable tool set and core |
| 6 | * instructions. Existing business tools cover the complete team lifecycle. |
| 7 | * After installation any session can |
| 8 | * run multi-agent teamwork through natural language (e.g. "use AgentTeams to research X"): |
| 9 | * the model creates a team (it becomes the captain), spawns members as |
| 10 | * durable continuable subagents, breaks the goal into tasks with |
| 11 | * dependencies, wakes members with messages, relays reports, and collects |
| 12 | * results. |
| 13 | * |
| 14 | * Installation (bundle): `dsh plugin --profile <name> add @nanmicoder/dsh-agent-teams` |
| 15 | * (or a local path). The bundle patch mounts this plugin row into the host |
| 16 | * composition; the tools register into the shared `tools` registry and the |
| 17 | * usage section into the global system prompt, so the plugin needs no realm. |
| 18 | * |
| 19 | * @module dsh-agent-teams |
| 20 | */ |
| 21 | import z from '@deepseek-ai/schemastery'; |
| 22 | import { createUserMessage } from '@deepseek-ai/dsh-llm'; |
| 23 | import { haltTeamWork, stagedPlanApprovedContext, registerAgentTeamsTools, } from "./tools.js"; |
| 24 | import { installAgentTeamsGestureBoundary, registerAgentTeamsCommand } from "./command.js"; |
| 25 | import { readFile } from 'node:fs/promises'; |
| 26 | import { join } from 'node:path'; |
| 27 | import { fileURLToPath } from 'node:url'; |
| 28 | import { collectArchivedTeamsActivity, collectTeamsActivity } from "./snapshot.js"; |
| 29 | import { findTeamByCaptain } from "./state.js"; |
| 30 | import { leadIdentityOfAsync } from "./lineage.js"; |
| 31 | import { formatProfilesForPrompt } from "./profiles.js"; |
| 32 | import { parseToolPolicies } from "./tool-policies.js"; |
| 33 | import { installTeamCapabilities } from "./capabilities.js"; |
| 34 | import { agentTeamsSource, observedSessionFormatVersion } from "./harness-compat.js"; |
| 35 | import { TEAM_TOOL_NAMES } from "./tool-names.js"; |
| 36 | import { authenticatedWebRoutes, readJsonRequest, RequestBodyError, writeJsonWithEtag } from "./web-routes.js"; |
| 37 | /** Web-server service key candidates, newest first. */ |
| 38 | const WEB_SERVER_KEYS = ['webServer', 'httpServer']; |
| 39 | /** Workspace registry service key candidates, newest first. */ |
| 40 | const WORKSPACE_KEYS = ['workspaceRegistry', 'workspace']; |
| 41 | export const name = 'agent-teams'; |
| 42 | export const inject = ['tools', 'llm', 'subagents', 'systemPrompt', 'agents']; |
| 43 | // `z.object()` has an implicit `{}` default in Schemastery. Fallback routes |
| 44 | // are optional, so model absence explicitly; otherwise a missing route is |
| 45 | // validated as an empty object and fails on the required provider/model keys. |
| 46 | const fallbackRouteConfig = z.union([ |
| 47 | z.object({ provider: z.string().required(), model: z.string().required() }), |
| 48 | z.const(undefined), |
| 49 | ]); |
| 50 | // Same Schemastery defaulting trap for a tool policy: an `allow`-only policy |
| 51 | // would materialize `deny: []` and fail a `.min(1)` on an absent list. Model |
| 52 | // each accepted combination explicitly, so a policy that declares only one |
| 53 | // side stays valid while an empty side is still rejected. |
| 54 | const toolPolicyConfig = z.union([ |
| 55 | z.object({ allow: z.array(z.string()).min(1).required(), deny: z.const(undefined) }), |
| 56 | z.object({ allow: z.const(undefined), deny: z.array(z.string()).min(1).required() }), |
| 57 | z.object({ allow: z.array(z.string()).min(1).required(), deny: z.array(z.string()).min(1).required() }), |
| 58 | ]); |
| 59 | export const Config = z.object({ |
| 60 | stateDir: z.string().default('.agent-teams'), |
| 61 | memberProvider: z.string().default('spawn'), |
| 62 | memberModel: z.string(), |
| 63 | memberLlmProvider: z.string(), |
| 64 | executionPrompt: z.string(), |
| 65 | fallback: fallbackRouteConfig, |
| 66 | profiles: z.dict(z.object({ |
| 67 | description: z.string(), |
| 68 | protocol: z.string(), |
| 69 | executionPrompt: z.string(), |
| 70 | fallback: fallbackRouteConfig, |
| 71 | members: z.array(z.object({ |
| 72 | name: z.string().required(), |
| 73 | role: z.string(), |
| 74 | provider: z.string(), |
| 75 | model: z.string(), |
| 76 | reasoning_effort: z.string(), |
| 77 | executionPrompt: z.string(), |
| 78 | fallback: fallbackRouteConfig, |
| 79 | // Owner-declared tool-policy id this profile member selects (#59). |
| 80 | tool_policy: z.string(), |
| 81 | })).min(1).required(), |
| 82 | taskPlanning: z.union([z.const('captain'), z.const('seed')]), |
| 83 | reviewPolicy: z.object({ |
| 84 | requirementsMinRounds: z.natural().min(1), |
| 85 | requirementsMaxRounds: z.natural().min(1), |
| 86 | codeMaxRounds: z.natural().min(1), |
| 87 | maxRepairAttempts: z.natural().min(1), |
| 88 | requiredReviewers: z.array(z.string()), |
| 89 | }), |
| 90 | tasks: z.array(z.object({ |
| 91 | id: z.string().required(), |
| 92 | subject: z.string().required(), |
| 93 | description: z.string(), |
| 94 | assignee: z.string(), |
| 95 | dependencies: z.array(z.string()), |
| 96 | })), |
| 97 | })).default({}), |
| 98 | toolPolicies: z.dict(toolPolicyConfig).default({}), |
| 99 | memberMaxDepth: z.natural().default(0), |
| 100 | maxMembers: z.natural().min(1).default(8), |
| 101 | promptSectionOrder: z.natural().default(117), |
| 102 | slashCommand: z.boolean().default(true), |
| 103 | }); |
| 104 | /** The model-facing usage policy: when and how to drive AgentTeams. */ |
| 105 | export function usageSectionText(toolNames, profilesText = '') { |
| 106 | return `AgentTeams captain protocol: |
| 107 | 1. Inspect current team state when needed, using agent_teams_status. Continue existing work without duplicating its roster/tasks. Create only when no current team exists, with the user's goal as description and approval="required"; automatic approval requires an explicit request to run immediately. Staged plans never spawn or schedule work. |
| 108 | 2. Add each needed role once; members inherit your model route unless another is requested/needed. A requested profile goes to create({profile}); it supplies its roster. Seed profiles also supply tasks; captain-planning profiles require your DAG. Do not duplicate either. A member may also select one owner-declared tool policy by id (tool_policy on add_member, a plan member, or a profile member): it is the only way to change which global tools that member sees and may invoke, and you can never pass raw allow/deny lists. |
| 109 | 3. Build the complete smallest useful DAG while staged. For an ordinary research/audit plan, pass the roster and dependency graph together in create({plan:{members,tasks}}) to avoid repeated setup rounds. Every task needs a subject; pass kind and assignee explicitly when the plan specifies them. Titles, descriptions and member roles do not set these fields. Dependencies represent prerequisites. Give every required contributor a task or explicit message. Present the plan and end your turn for review; never approve in that planning turn. Approve only after a later explicit user approval or the Web action. |
| 110 | 4. Respect Web approve/return/discard control messages. On return, ask what to change before editing; after the answer, use one atomic agent_teams_edit_plan batch (edit downstream references before removals), summarize and await review again. Never inspect or edit .agent-teams state files or plugin source code to revise plans. Discard does not authorize a replacement. |
| 111 | 5. The scheduler dispatches ready tasks after approval. Delegate; do not duplicate slow work or send messages merely to start a stage. Handle reports/user work, then yield when waiting is all that remains: reports wake you automatically. Use status after a delivery or user request, never busy-poll or wait for unassigned members. |
| 112 | 6. Tasks carry attempt_id capabilities. Use the current attempt_id; stale means ownership changed. Pause members only on explicit request; later guidance via send_message continues that same attempt. Retry, transfer or take over through reassign_task first; it revokes the old attempt and waits for quiescence. Prefer a member. Captain implementation/review takeover requires a user request. Every takeover is one ready task at a time, finished in this turn; never yield with captain-owned work open. |
| 113 | 7. In a running team, correct never-started pending tasks with edit_plan update_task; preserve dependency and ownership contracts instead of cancelling and recreating the graph. A captain can cancel a never-started pending task directly. Active attempts still require reassign_task. Quality kinds (requirements, implementation, verification, review, repair, integration) require objective + acceptance; implementation/repair also require inScope + verify. Derive paths/commands from the workspace/profile, never assume src/ or pnpm test. Review/requirements complete only with verdict=pass; needs_revision/reject fail with findings. Never approve your own implementation or ask for a deliberate failure. When a quality contract itself is wrong (a verify command that cannot pass, an inScope that forbids the file the objective requires), fix it with agent_teams_amend_task — captain-only, non-terminal tasks only, frozen after a passing review, and every amendment is recorded in the task's revisions ledger — instead of letting the worker dead-lock or game the gate. |
| 114 | 8. When full quality mode is requested: requirements → implementation → verification → review → integration. Plan the entire DAG while staged, including implementation before requirements finishes and integration depending on review round 1. Failed review automatically adds repair + next review and rewires pending downstream gates. Do not recreate this loop, omit integration or depend on a failed task. Review acceptance judges the latest implementation. Do not put smoke-test scripts into task instructions. |
| 115 | 9. Halted means the user stopped work (including the captain turn). Resume only on a later explicit user request with a reason, via agent_teams_resume or create_task({resume:true,resumeReason}); creating tasks alone never resumes. Escalated means the review loop hit its limit, not a halt. Deployment requires explicit user confirmation. |
| 116 | 10. Wait for all required tasks to be terminal and members idle/ready, present results, then delete/archive unless the user wants to continue. Never discard unfinished work without authorization. |
| 117 | Tools: ${toolNames}${profilesText === '' ? '' : `\n\n${profilesText}`}`; |
| 118 | } |
| 119 | export function apply(ctx, config) { |
| 120 | const resolved = { |
| 121 | stateDir: config.stateDir ?? '.agent-teams', |
| 122 | memberProvider: config.memberProvider ?? 'spawn', |
| 123 | memberModel: config.memberModel, |
| 124 | memberLlmProvider: config.memberLlmProvider, |
| 125 | executionPrompt: config.executionPrompt, |
| 126 | fallback: config.fallback, |
| 127 | memberMaxDepth: config.memberMaxDepth ?? 0, |
| 128 | maxMembers: config.maxMembers ?? 8, |
| 129 | profiles: config.profiles ?? {}, |
| 130 | // Owner configuration is validated once, at mount: an empty or malformed |
| 131 | // policy must never reach a member creation path. |
| 132 | toolPolicies: parseToolPolicies(config.toolPolicies), |
| 133 | }; |
| 134 | // Provider registration is a sibling plugin's effect (`subagent-spawn` / |
| 135 | // `subagent-fork` rows), which can land after this mount under the Loader's |
| 136 | // concurrent activation — so capability validation happens at the first |
| 137 | // member spawn (`spawnMember`), the earliest point the provider list is |
| 138 | // settled, rather than here. |
| 139 | const agentTeamsRuntime = registerAgentTeamsTools(ctx, resolved); |
| 140 | installTeamCapabilities(ctx, { |
| 141 | stateDir: resolved.stateDir, |
| 142 | isPendingMember: agentTeamsRuntime.isPendingMember, |
| 143 | order: config.promptSectionOrder, |
| 144 | // Keep the bounded profile directory available without extra tool calls. |
| 145 | // installTeamCapabilities snapshots this once; no business state rewrites it. |
| 146 | captainPrompt: () => usageSectionText(TEAM_TOOL_NAMES.join(', '), formatProfilesForPrompt(config.profiles)), |
| 147 | }); |
| 148 | // Deterministic activation surfaces: the closed-namespace `/agent-teams` |
| 149 | // host command (surfaces in the Web GUI slash menu via the Harness |
| 150 | // ui-commands client) and the plain-text gesture boundary for surfaces |
| 151 | // without command adjudication (headless CLI). Both default on; a profile |
| 152 | // can disable them to keep the natural-language trigger exclusive. |
| 153 | // |
| 154 | // `commands` is registered lazily (not a required inject): it ships in the |
| 155 | // base bundle of every standard profile, but a minimal composition that |
| 156 | // omits the command registry keeps the plugin fully functional — the fiber |
| 157 | // never pends on it and simply never gains the slash command. |
| 158 | if (config.slashCommand ?? true) { |
| 159 | ctx.inject(['commands'], (commandCtx) => { |
| 160 | registerAgentTeamsCommand(commandCtx, () => config.profiles ?? {}); |
| 161 | }); |
| 162 | installAgentTeamsGestureBoundary(ctx, () => config.profiles ?? {}); |
| 163 | } |
| 164 | // The activity panel data/artwork routes need the Web server and the |
| 165 | // workspace registry, which headless profiles do not mount; under |
| 166 | // concurrent activation they may also bind after this plugin. Register the |
| 167 | // routes lazily: try now, then on each service binding event. In a webless |
| 168 | // profile the plugin stays tool-only and never blocks boot. |
| 169 | let webRegistered = false; |
| 170 | const registerWebSurface = () => { |
| 171 | if (webRegistered) |
| 172 | return; |
| 173 | const rawWebServer = (ctx.get(WEB_SERVER_KEYS[0]) ?? ctx.get(WEB_SERVER_KEYS[1])); |
| 174 | const workspaceRegistry = (ctx.get(WORKSPACE_KEYS[0]) ?? ctx.get(WORKSPACE_KEYS[1])); |
| 175 | if (rawWebServer === undefined || workspaceRegistry === undefined) |
| 176 | return; |
| 177 | const webServer = authenticatedWebRoutes(rawWebServer, () => ctx.get('connection')); |
| 178 | webRegistered = true; |
| 179 | // Activity panel data route: the browser floater polls this for team |
| 180 | // snapshots (disk truth + live subagent activity). Mirrors the Claude |
| 181 | // Code desktop watcher's server-side snapshot pattern. |
| 182 | ctx.effect(() => webServer.register({ |
| 183 | kind: 'exact', |
| 184 | path: '/plugins/dsh-agent-teams/state', |
| 185 | handler: async (req, res) => { |
| 186 | const url = new URL(req.url ?? '/', 'http://x'); |
| 187 | const captainSessionId = url.searchParams.get('session')?.trim() || undefined; |
| 188 | const roots = workspaceRegistry.list().map((workspace) => ({ |
| 189 | workspace: workspace.title, |
| 190 | // The panel audits the same current bytes as agent_teams_status, so it |
| 191 | // cannot advertise a passing gate over a changed revision (#161). |
| 192 | workspacePath: workspace.path, |
| 193 | stateRoot: join(workspace.path, resolved.stateDir), |
| 194 | })); |
| 195 | // ?archived=1 serves teams moved to archive/ (post-delete review). |
| 196 | const snapshots = url.searchParams.get('archived') === '1' |
| 197 | ? await collectArchivedTeamsActivity(ctx, roots, captainSessionId) |
| 198 | : await collectTeamsActivity(ctx, roots, captainSessionId, url.searchParams.get('summary') === '1'); |
| 199 | writeJsonWithEtag(req, res, JSON.stringify({ teams: snapshots })); |
| 200 | }, |
| 201 | }), 'agent-teams: activity route'); |
| 202 | ctx.effect(() => webServer.register({ |
| 203 | kind: 'exact', |
| 204 | path: '/plugins/dsh-agent-teams/halt', |
| 205 | handler: async (req, res) => { |
| 206 | if (req.method !== 'POST') { |
| 207 | res.writeHead(405, { allow: 'POST', 'cache-control': 'no-store' }); |
| 208 | res.end(); |
| 209 | return; |
| 210 | } |
| 211 | let payload; |
| 212 | try { |
| 213 | payload = await readJsonRequest(req); |
| 214 | } |
| 215 | catch (error) { |
| 216 | res.writeHead(error instanceof RequestBodyError ? error.status : 400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 217 | res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'invalid request body' })); |
| 218 | return; |
| 219 | } |
| 220 | const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId.trim() : ''; |
| 221 | const teamId = typeof payload.teamId === 'string' ? payload.teamId.trim() : ''; |
| 222 | if (sessionId === '' || teamId === '') { |
| 223 | res.writeHead(400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 224 | res.end(JSON.stringify({ error: 'sessionId and teamId are required' })); |
| 225 | return; |
| 226 | } |
| 227 | const captain = ctx.agents.get(sessionId); |
| 228 | if (captain === undefined) { |
| 229 | res.writeHead(409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 230 | res.end(JSON.stringify({ error: 'captain session is not attached' })); |
| 231 | return; |
| 232 | } |
| 233 | const workspace = captain.session.header.cwd ?? process.cwd(); |
| 234 | const stateRoot = join(workspace, resolved.stateDir); |
| 235 | const team = await findTeamByCaptain(stateRoot, captain.id, await leadIdentityOfAsync(ctx, captain.session)); |
| 236 | if (team === undefined || team.id !== teamId) { |
| 237 | res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 238 | res.end(JSON.stringify({ error: 'team not found for this captain' })); |
| 239 | return; |
| 240 | } |
| 241 | try { |
| 242 | const result = await haltTeamWork({ |
| 243 | ctx, |
| 244 | stateRoot, |
| 245 | teamId, |
| 246 | captain, |
| 247 | }); |
| 248 | res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 249 | res.end(JSON.stringify(result)); |
| 250 | } |
| 251 | catch (error) { |
| 252 | ctx.logger.warn(`agent-teams: halt failed for ${teamId}: ${String(error)}`); |
| 253 | res.writeHead(500, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 254 | res.end(JSON.stringify({ error: 'failed to stop the team' })); |
| 255 | } |
| 256 | }, |
| 257 | }), 'agent-teams: halt route'); |
| 258 | ctx.effect(() => webServer.register({ |
| 259 | kind: 'exact', |
| 260 | path: '/plugins/dsh-agent-teams/plan', |
| 261 | handler: async (req, res) => { |
| 262 | if (req.method !== 'POST') { |
| 263 | res.writeHead(405, { allow: 'POST', 'cache-control': 'no-store' }); |
| 264 | res.end(); |
| 265 | return; |
| 266 | } |
| 267 | let payload; |
| 268 | try { |
| 269 | payload = await readJsonRequest(req); |
| 270 | } |
| 271 | catch (error) { |
| 272 | res.writeHead(error instanceof RequestBodyError ? error.status : 400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 273 | res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'invalid request body' })); |
| 274 | return; |
| 275 | } |
| 276 | const sessionId = typeof payload['sessionId'] === 'string' ? payload['sessionId'].trim() : ''; |
| 277 | const teamId = typeof payload['teamId'] === 'string' ? payload['teamId'].trim() : ''; |
| 278 | const action = typeof payload['action'] === 'string' ? payload['action'] : ''; |
| 279 | if (sessionId === '' || teamId === '' || action === '') { |
| 280 | res.writeHead(400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 281 | res.end(JSON.stringify({ error: 'sessionId, teamId, and action are required' })); |
| 282 | return; |
| 283 | } |
| 284 | const captain = ctx.agents.get(sessionId); |
| 285 | if (captain === undefined) { |
| 286 | res.writeHead(409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 287 | res.end(JSON.stringify({ error: 'captain session is not attached' })); |
| 288 | return; |
| 289 | } |
| 290 | const workspace = captain.session.header.cwd ?? process.cwd(); |
| 291 | const stateRoot = join(workspace, resolved.stateDir); |
| 292 | const team = await findTeamByCaptain(stateRoot, captain.id, await leadIdentityOfAsync(ctx, captain.session)); |
| 293 | if (team === undefined || team.id !== teamId) { |
| 294 | res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 295 | res.end(JSON.stringify({ error: 'team not found for this captain' })); |
| 296 | return; |
| 297 | } |
| 298 | try { |
| 299 | if (action === 'approve') { |
| 300 | const approved = await agentTeamsRuntime.approveStagedTeam(captain, teamId); |
| 301 | // The browser receives the HTTP result, so the model needs its own |
| 302 | // control message. steer wakes an idle captain or joins its next |
| 303 | // step; the tool approve path already returns to the model itself. |
| 304 | try { |
| 305 | captain.steer(createUserMessage({ |
| 306 | content: [{ type: 'text', text: stagedPlanApprovedContext(team.name) }], |
| 307 | source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(captain)), |
| 308 | })); |
| 309 | } |
| 310 | catch (error) { |
| 311 | // Approval is already committed. Do not report a failed approval |
| 312 | // and invite a retry that could duplicate the user's action. |
| 313 | ctx.logger.warn(`agent-teams: approval notification failed for ${teamId}: ${String(error)}`); |
| 314 | } |
| 315 | res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 316 | res.end(JSON.stringify({ ok: true, phase: 'running', ...approved })); |
| 317 | return; |
| 318 | } |
| 319 | if (action === 'continue') { |
| 320 | const continued = await agentTeamsRuntime.continueStagedPlanning(captain, teamId); |
| 321 | res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 322 | res.end(JSON.stringify({ ok: true, phase: 'staged', review: 'awaiting_feedback', ...continued })); |
| 323 | return; |
| 324 | } |
| 325 | if (action === 'discard') { |
| 326 | const discarded = await agentTeamsRuntime.discardStagedTeam(captain, teamId); |
| 327 | res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 328 | res.end(JSON.stringify({ ok: true, phase: 'archived', ...discarded })); |
| 329 | return; |
| 330 | } |
| 331 | const dependencies = Array.isArray(payload['dependencies']) |
| 332 | ? payload['dependencies'].filter((item) => typeof item === 'string') |
| 333 | : []; |
| 334 | let mutation; |
| 335 | if (action === 'update_member') { |
| 336 | if (typeof payload['memberName'] !== 'string' |
| 337 | || typeof payload['provider'] !== 'string' |
| 338 | || typeof payload['model'] !== 'string') |
| 339 | throw new Error('memberName, provider, and model are required'); |
| 340 | mutation = { |
| 341 | action, |
| 342 | memberName: payload['memberName'], |
| 343 | provider: payload['provider'], |
| 344 | model: payload['model'], |
| 345 | ...typeof payload['role'] === 'string' || payload['role'] === null ? { role: payload['role'] } : {}, |
| 346 | ...typeof payload['reasoningEffort'] === 'string' || payload['reasoningEffort'] === null |
| 347 | ? { reasoningEffort: payload['reasoningEffort'] } |
| 348 | : {}, |
| 349 | ...typeof payload['executionPrompt'] === 'string' || payload['executionPrompt'] === null |
| 350 | ? { executionPrompt: payload['executionPrompt'] } |
| 351 | : {}, |
| 352 | ...typeof payload['tool_policy'] === 'string' ? { toolPolicy: payload['tool_policy'] } : {}, |
| 353 | }; |
| 354 | } |
| 355 | else if (action === 'update_task') { |
| 356 | if (typeof payload['taskId'] !== 'string' || typeof payload['subject'] !== 'string') { |
| 357 | throw new Error('taskId and subject are required'); |
| 358 | } |
| 359 | mutation = { |
| 360 | action, |
| 361 | taskId: payload['taskId'], |
| 362 | subject: payload['subject'], |
| 363 | dependencies, |
| 364 | ...typeof payload['description'] === 'string' || payload['description'] === null |
| 365 | ? { description: payload['description'] } |
| 366 | : {}, |
| 367 | ...typeof payload['assignee'] === 'string' || payload['assignee'] === null |
| 368 | ? { assignee: payload['assignee'] } |
| 369 | : {}, |
| 370 | }; |
| 371 | } |
| 372 | else if (action === 'add_task') { |
| 373 | if (typeof payload['subject'] !== 'string') |
| 374 | throw new Error('subject is required'); |
| 375 | mutation = { |
| 376 | action, |
| 377 | subject: payload['subject'], |
| 378 | dependencies, |
| 379 | ...typeof payload['description'] === 'string' || payload['description'] === null |
| 380 | ? { description: payload['description'] } |
| 381 | : {}, |
| 382 | ...typeof payload['assignee'] === 'string' || payload['assignee'] === null |
| 383 | ? { assignee: payload['assignee'] } |
| 384 | : {}, |
| 385 | }; |
| 386 | } |
| 387 | else if (action === 'remove_task') { |
| 388 | if (typeof payload['taskId'] !== 'string') |
| 389 | throw new Error('taskId is required'); |
| 390 | mutation = { action, taskId: payload['taskId'] }; |
| 391 | } |
| 392 | else { |
| 393 | throw new Error(`unknown plan action "${action}"`); |
| 394 | } |
| 395 | const updated = await agentTeamsRuntime.updateStagedPlan(captain, teamId, mutation); |
| 396 | res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 397 | res.end(JSON.stringify({ ok: true, phase: updated.phase, members: updated.members.length, tasks: updated.tasks.length })); |
| 398 | } |
| 399 | catch (error) { |
| 400 | res.writeHead(409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); |
| 401 | res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'plan operation failed' })); |
| 402 | } |
| 403 | }, |
| 404 | }), 'agent-teams: plan route'); |
| 405 | // Whale mascot artwork: serve the packaged V2 role/action images to the |
| 406 | // activity panel. An explicit allowlist guards the route (no path |
| 407 | // traversal); the images ship with the bundle (files: assets/). |
| 408 | const artDir = fileURLToPath(new URL('../assets/agent-teams/', import.meta.url)); |
| 409 | const ART_ALLOWLIST = new Set([ |
| 410 | 'team-lead-v2.png', |
| 411 | 'member-researcher-v2.png', 'member-engineer-v2.png', |
| 412 | 'member-qa-v2.png', 'member-designer-v2.png', |
| 413 | 'member-security-v2.png', 'member-docs-v2.png', |
| 414 | 'member-data-v2.png', 'member-operator-v2.png', |
| 415 | 'action-working-v2.png', 'action-thinking-v2.png', |
| 416 | 'action-reporting-v2.png', 'action-celebrating-v2.png', |
| 417 | 'action-sleeping-v2.png', 'action-sending-v2.png', |
| 418 | ]); |
| 419 | ctx.effect(() => webServer.register({ |
| 420 | kind: 'prefix', |
| 421 | path: '/plugins/dsh-agent-teams/assets', |
| 422 | handler: async (req, res) => { |
| 423 | let name; |
| 424 | try { |
| 425 | name = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname.split('/').pop() ?? ''); |
| 426 | } |
| 427 | catch { |
| 428 | // Malformed percent-encoding: treat as an unknown asset, not a 400. |
| 429 | res.writeHead(404); |
| 430 | res.end(); |
| 431 | return; |
| 432 | } |
| 433 | if (!ART_ALLOWLIST.has(name)) { |
| 434 | res.writeHead(404); |
| 435 | res.end(); |
| 436 | return; |
| 437 | } |
| 438 | try { |
| 439 | const data = await readFile(join(artDir, name)); |
| 440 | res.writeHead(200, { |
| 441 | 'content-type': 'image/png', |
| 442 | 'cache-control': 'public, max-age=86400', |
| 443 | }); |
| 444 | res.end(data); |
| 445 | } |
| 446 | catch (error) { |
| 447 | ctx.logger.warn(`agent-teams: artwork read failed for ${name}: ${String(error)}`); |
| 448 | res.writeHead(404); |
| 449 | res.end(); |
| 450 | } |
| 451 | }, |
| 452 | }), 'agent-teams: artwork route'); |
| 453 | }; |
| 454 | registerWebSurface(); |
| 455 | ctx.on('internal/service', (name) => { |
| 456 | if (WEB_SERVER_KEYS.includes(name) |
| 457 | || WORKSPACE_KEYS.includes(name)) { |
| 458 | registerWebSurface(); |
| 459 | } |
| 460 | }); |
| 461 | } |
| 462 |