返回 CodeWhale
capabilities.js
根目录 / crates / plugins / assets / agent-teams / lib / capabilities.js
1 /** Stable, agent-scoped presentation. Business authority stays in the tools. */
2 import { onAgentReady } from "./harness-compat.js";
3 import { readdirSync } from 'node:fs';
4 import { join } from 'node:path';
5 import { readTeamSync, readRetiredMemberIdsSync } from "./state.js";
6 import { leadIdentityOf, teamLeadMatch } from "./lineage.js";
7 import { MEMBER_TOOL_NAMES, TEAM_TOOL_NAMES } from "./tool-names.js";
8 export const TEAM_ACTIVATION_PROMPT = 'AgentTeams (Agent Teams) provides multi-agent team collaboration. Apply these rules when the user requests it (including /agent-teams) or when continuing an existing team. Mentioning, quoting, discussing, or declining AgentTeams alone is not a request to start work.';
9 export const TEAM_MEMBER_PROMPT = 'You are an AgentTeams member. Follow your assigned member persona and task contract. Use agent_teams_claim_task, agent_teams_update_task, agent_teams_send_message and agent_teams_status for your own work. Include the current attempt_id in updates; report completion or failure to the captain. Do not create, approve, edit or resume a team. If your durable membership is unavailable, report that to the parent instead of creating a replacement.';
10 function stateRoot(agent, config) {
11 return join(agent.session.header.cwd ?? process.cwd(), config.stateDir);
12 }
13 /** Synchronous startup/HMR hydration must finish before the first assembly. */
14 function currentTeam(ctx, agent, config) {
15 const lead = leadIdentityOf(ctx, agent.session);
16 const root = stateRoot(agent, config);
17 let entries;
18 try {
19 entries = readdirSync(root, { withFileTypes: true });
20 }
21 catch (error) {
22 if (error.code === 'ENOENT')
23 return undefined;
24 throw error;
25 }
26 let found;
27 for (const entry of entries) {
28 if (!entry.isDirectory() || entry.name === 'archive')
29 continue;
30 const team = readTeamSync(root, entry.name);
31 if (team === undefined || (!teamLeadMatch(team, lead)
32 && !team.members.some(member => member.id === agent.id)))
33 continue;
34 if (found !== undefined)
35 throw new Error('ambiguous AgentTeams membership');
36 found = team;
37 }
38 return found;
39 }
40 /** Call once, after all business definitions have registered. Never per member. */
41 export function installTeamCapabilities(ctx, config) {
42 const states = new WeakMap();
43 const active = new Set();
44 let mounted = true;
45 // Snapshot policy once: profiles, team state, and tool results must never
46 // rewrite this prefix or control whether core instructions are available.
47 const captainPrompt = `${TEAM_ACTIVATION_PROMPT}\n\n${config.captainPrompt()}`;
48 function attach(agent) {
49 const prior = states.get(agent);
50 if (prior !== undefined)
51 return prior;
52 if (!mounted)
53 throw new Error('AgentTeams capability provider is disposed');
54 // Determine a member's role before its first request and retain it for the
55 // lifetime of this scope. Team creation/archive must never rewrite the
56 // captain's system/tools prefix, even after a long ordinary conversation.
57 let member = config.isPendingMember(agent);
58 try {
59 member ||= readRetiredMemberIdsSync(stateRoot(agent, config)).has(agent.id);
60 const team = currentTeam(ctx, agent, config);
61 member ||= team !== undefined && !teamLeadMatch(team, leadIdentityOf(ctx, agent.session));
62 }
63 catch (error) {
64 // Unrelated damaged state must not disable ordinary conversation.
65 // Business tools still validate durable team state before acting.
66 ctx.logger.warn(`agent-teams: capability hydration failed: ${String(error)}`);
67 }
68 const state = { member, dispose: () => undefined };
69 let revoke;
70 let disposed = false;
71 let releaseLifetime;
72 state.dispose = () => {
73 if (disposed)
74 return;
75 disposed = true;
76 revoke?.();
77 releaseLifetime?.();
78 states.delete(agent);
79 active.delete(state);
80 };
81 states.set(agent, state);
82 active.add(state);
83 try {
84 if (member)
85 revoke = agent.ctx.tools.restrict({
86 deny: TEAM_TOOL_NAMES.filter(name => !MEMBER_TOOL_NAMES.includes(name)),
87 });
88 releaseLifetime = agent.ctx.effect(() => state.dispose, 'agent-teams: capability lifetime');
89 return state;
90 }
91 catch (error) {
92 state.dispose();
93 throw error;
94 }
95 }
96 ctx.systemPrompt.section({
97 name: 'agent-teams:usage', order: config.order ?? 117,
98 text: ({ agent }) => {
99 return agent !== undefined && states.get(agent)?.member ? TEAM_MEMBER_PROMPT : captainPrompt;
100 },
101 });
102 onAgentReady(ctx, agent => { attach(agent); });
103 ctx.effect(() => () => {
104 mounted = false;
105 for (const state of [...active])
106 state.dispose();
107 }, 'agent-teams: capability scopes');
108 for (const agent of ctx.agents.list())
109 attach(agent);
110 }
111
111 lines JAVASCRIPT