返回 CodeWhale
command.js
根目录 / crates / plugins / assets / agent-teams / lib / command.js
1 import { createUserMessage } from '@deepseek-ai/dsh-llm';
2 import { agentTeamsSource, observedSessionFormatVersion } from "./harness-compat.js";
3 import { parseProfileInvocation, resolveProfileTaskPlanning } from "./profiles.js";
4 export const AGENT_TEAMS_COMMAND = 'agent-teams';
5 const PROFILE_COMMAND_PREFIX = `${AGENT_TEAMS_COMMAND}-`;
6 const GESTURE = /^\/agent-teams(?=$|[\t\n\r ])/u;
7 /**
8 * Convert a configured profile key into a stable, closed-namespace command
9 * suffix. Only lowercase ASCII letters, digits and dashes are representable;
10 * this deliberately prevents accidental command aliases for ambiguous profile
11 * names such as `foo bar`, `foo_bar`, or non-ASCII keys.
12 */
13 export function profileCommandName(profileName) {
14 const normalized = profileName.trim().toLowerCase();
15 if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(normalized))
16 return undefined;
17 return `${PROFILE_COMMAND_PREFIX}${normalized}`;
18 }
19 /** Resolve a profile command only when it maps uniquely to a live profile. */
20 function profileForCommand(commandName, profiles) {
21 const matches = Object.keys(profiles).filter((profileName) => profileCommandName(profileName) === commandName);
22 return matches.length === 1 ? matches[0] : undefined;
23 }
24 /** Parse either the generic command or one generated profile alias. */
25 function parseCommandText(text, profiles) {
26 const trimmed = text.trimStart();
27 if (GESTURE.test(trimmed))
28 return parseProfileInvocation(trimmed.slice(AGENT_TEAMS_COMMAND.length + 1).trim());
29 if (!trimmed.startsWith(`/${PROFILE_COMMAND_PREFIX}`))
30 return undefined;
31 const tokenEnd = trimmed.search(/[\t\n\r ]/u);
32 const commandName = trimmed.slice(1, tokenEnd === -1 ? undefined : tokenEnd);
33 const profile = profileForCommand(commandName, profiles);
34 if (profile === undefined)
35 return undefined;
36 return { profile, goal: (tokenEnd === -1 ? '' : trimmed.slice(tokenEnd)).trim() };
37 }
38 export function invokedAgentTeamsInvocation(messages, getProfiles = () => ({})) {
39 for (let index = messages.length - 1; index >= 0; index -= 1) {
40 const message = messages[index];
41 if (message === undefined || message.source.kind !== 'user')
42 continue;
43 for (const block of message.content) {
44 if (block.type !== 'text')
45 continue;
46 const invocation = parseCommandText(block.text, getProfiles());
47 if (invocation !== undefined)
48 return invocation;
49 }
50 }
51 return undefined;
52 }
53 export function invokedAgentTeamsGoal(messages) {
54 return invokedAgentTeamsInvocation(messages)?.goal;
55 }
56 export function buildActivationDirective(goal, profile, taskPlanning = 'seed') {
57 const lines = [
58 'The user invoked an AgentTeams slash command. Follow the AgentTeams protocol already in your system instructions. Inspect existing team state with agent_teams_status when needed.',
59 'Respect the current team state. Continue an existing plan or team without recreating it. Only when no current team exists, call agent_teams_create with approval="required". Build the complete staged roster and DAG, then stop and ask the user to review the Web plan. Do not approve or start it in this same turn.',
60 ];
61 if (profile !== undefined) {
62 lines.push(`Use profile="${profile}" when creating a new team.`);
63 if (taskPlanning === 'captain') {
64 lines.push('This profile supplies the roster and guardrails. After create, do not recreate members.', 'Derive the smallest useful task graph from the goal while the team is staged; do not ask the user whether to split, merge, serialize, or parallelize.', 'Independent supplemental work must become separate ready tasks so idle members can run in parallel. Add dependencies only for genuine prerequisites and later synthesis.');
65 }
66 else {
67 lines.push('Do not recreate the same members or seed tasks manually.');
68 }
69 }
70 lines.push(goal === '' ? 'The goal was not given — ask the user what the team should accomplish.' : `Goal: ${goal}`);
71 return lines.join('\n');
72 }
73 export function registerAgentTeamsCommand(ctx, getProfiles = () => ({})) {
74 ctx.effect(() => {
75 const dispose = [];
76 dispose.push(ctx.commands.register({
77 name: AGENT_TEAMS_COMMAND,
78 description: 'run a goal with a multi-agent team (you become the captain)',
79 input: { hint: '[--profile <name>] <goal>' },
80 handler(invocation) {
81 let parsed;
82 try {
83 parsed = parseProfileInvocation(invocation.rawInput.trim());
84 }
85 catch (error) {
86 return { kind: 'error', text: String(error) };
87 }
88 if (parsed.profile !== undefined && !Object.keys(getProfiles()).some(key => key.trim() === parsed.profile))
89 return { kind: 'error', text: `unknown AgentTeams profile "${parsed.profile}"` };
90 if (parsed.profile === undefined && parsed.goal === '')
91 return { kind: 'error', text: `Usage: /${AGENT_TEAMS_COMMAND} [--profile <name>] <goal>` };
92 invocation.agent.followup(createUserMessage({ content: [{ type: 'text', text: `/${AGENT_TEAMS_COMMAND}${invocation.rawInput}` }], source: { kind: 'user' } }));
93 return { kind: 'success', text: `AgentTeams activated${parsed.profile === undefined ? '' : ` with profile ${parsed.profile}`} — the captain will assemble the team.` };
94 },
95 }));
96 for (const profileName of Object.keys(getProfiles())) {
97 const commandName = profileCommandName(profileName);
98 if (commandName === undefined)
99 continue;
100 dispose.push(ctx.commands.register({
101 name: commandName,
102 description: `run a goal with the AgentTeams ${profileName} profile`,
103 input: { hint: '<goal>' },
104 handler(invocation) {
105 const profile = profileForCommand(commandName, getProfiles());
106 if (profile === undefined)
107 return { kind: 'error', text: `AgentTeams profile command "/${commandName}" is unavailable` };
108 invocation.agent.followup(createUserMessage({ content: [{ type: 'text', text: `/${commandName}${invocation.rawInput}` }], source: { kind: 'user' } }));
109 return { kind: 'success', text: `AgentTeams activated with profile ${profile} — the captain will assemble the team.` };
110 },
111 }));
112 }
113 return () => {
114 for (const unregister of dispose.reverse())
115 unregister();
116 };
117 }, 'agent-teams: slash commands');
118 }
119 export function installAgentTeamsGestureBoundary(ctx, getProfiles = () => ({})) {
120 ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => {
121 const decision = await next();
122 if (decision.kind === 'reject')
123 return decision;
124 // The live session header carries the format this host actually stores; the
125 // resolved module constant can name another DSH line in the same profile (#236).
126 const observed = observedSessionFormatVersion(agent);
127 let invocation;
128 try {
129 invocation = invokedAgentTeamsInvocation(messages, getProfiles);
130 }
131 catch (error) {
132 return { kind: 'enter', messages: [...decision.messages, createUserMessage({ content: [{ type: 'text', text: `AgentTeams profile parsing failed: ${String(error)}` }], source: agentTeamsSource({ kind: 'agent-teams-command' }, observed) })] };
133 }
134 if (invocation === undefined)
135 return decision;
136 signal.throwIfAborted();
137 const profiles = getProfiles();
138 const matched = invocation.profile === undefined
139 ? undefined
140 : Object.entries(profiles).find(([key]) => key.trim() === invocation.profile);
141 const known = invocation.profile === undefined || matched !== undefined;
142 const text = !known
143 ? `AgentTeams profile "${invocation.profile}" does not exist. Available profiles: ${Object.keys(profiles).join(', ') || '(none)'}. Do not create a team.`
144 : buildActivationDirective(invocation.goal, invocation.profile, resolveProfileTaskPlanning(matched?.[1]));
145 return { kind: 'enter', messages: [...decision.messages, createUserMessage({ content: [{ type: 'text', text }], source: agentTeamsSource({ kind: 'agent-teams-command', ...invocation.goal === '' ? {} : { goal: invocation.goal }, ...invocation.profile === undefined ? {} : { profile: invocation.profile } }, observed) })] };
146 });
147 }
148
148 lines JAVASCRIPT