返回 CodeWhale
mailbox.js
根目录 / crates / plugins / assets / agent-teams / lib / mailbox.js
1 import { join } from 'node:path';
2 import { acknowledgeMailbox, CAPTAIN_KEY, discardMailboxMessages, findTeamByCaptain, readMailbox, readUnreadMailbox, readTeam, sanitizeKey, withTeamLock } from "./state.js";
3 import { sessionOwnEvents } from "./harness-compat.js";
4 import { leadIdentityOfAsync, sessionLeadsTeamAsync } from "./lineage.js";
5 const PREFIX = 'AgentTeams inbox receipt: ';
6 export function isCurrentMail(team, message) {
7 if (message.discardedAt !== undefined)
8 return false;
9 if (message.sourceAttemptId !== undefined && !team.tasks.some(task => task.id === message.sourceTaskId
10 && task.attemptId === message.sourceAttemptId && task.assignee === message.from
11 && (message.sourceTaskStatus === undefined || !['completed', 'failed', 'cancelled'].includes(task.status) || message.sourceTaskStatus === task.status)))
12 return false;
13 if (message.attemptId === undefined)
14 return true;
15 return team.tasks.some(task => task.id === message.taskId && task.attemptId === message.attemptId
16 && task.assignee === message.to && (task.status === 'claimed' || task.status === 'in_progress'));
17 }
18 /** Include structured provenance even in the status-tool fallback presentation. */
19 export function mailboxContent(message) {
20 return (message.sourceTaskId === undefined ? ''
21 : `[Source task ${message.sourceTaskId}, attempt_id ${message.sourceAttemptId}${message.sourceTaskStatus === undefined ? '' : `, status=${message.sourceTaskStatus}`}]\n`) + message.content;
22 }
23 function mailboxBody(recipient, messages) {
24 return messages.map(message => recipient === CAPTAIN_KEY
25 ? `AgentTeams message from member ${message.from}:\n\n${mailboxContent(message)}`
26 : `AgentTeams message from ${message.from}${message.attemptId === undefined ? '' : ` for task ${message.taskId}, attempt_id ${message.attemptId}`}:\n\n${mailboxContent(message)}`).join('\n\n');
27 }
28 /** Read current mail while the caller holds the lock and has verified the team. */
29 export async function readCurrentMailboxLocked(root, team, recipient, onMalformed) {
30 const messages = await readUnreadMailbox(root, team.id, recipient, onMalformed);
31 const current = [];
32 const staleIds = [];
33 for (const message of messages) {
34 if (isCurrentMail(team, message))
35 current.push(message);
36 else
37 staleIds.push(message.id);
38 }
39 await discardMailboxMessages(root, team.id, recipient, staleIds);
40 return current;
41 }
42 /** Fallback reads must enforce the same current-generation rule as live admission. */
43 export async function readCurrentMailbox(root, teamId, recipient, onMalformed) {
44 return withTeamLock(`team:${root}:${teamId}`, async () => {
45 const team = await readTeam(root, teamId);
46 return team === undefined ? [] : readCurrentMailboxLocked(root, team, recipient, onMalformed);
47 });
48 }
49 export function mailboxPrompt(teamId, recipient, messages) {
50 return PREFIX + JSON.stringify({ teamId, recipient, ids: messages.map(message => message.id) }) + '\n\n' + mailboxBody(recipient, messages);
51 }
52 function parseReceipt(text) {
53 if (!text.startsWith(PREFIX))
54 return undefined;
55 try {
56 const value = JSON.parse(text.slice(PREFIX.length).split('\n')[0]);
57 if (typeof value !== 'object' || value === null)
58 return undefined;
59 const raw = value;
60 if (typeof raw['teamId'] !== 'string' || typeof raw['recipient'] !== 'string'
61 || !Array.isArray(raw['ids']) || !raw['ids'].every(id => typeof id === 'string'))
62 return undefined;
63 if (raw['teamId'] !== sanitizeKey(raw['teamId']))
64 return undefined;
65 return { teamId: raw['teamId'], recipient: raw['recipient'], ids: raw['ids'] };
66 }
67 catch {
68 return undefined;
69 }
70 }
71 /** Only messages actually admitted to this recipient's step become read. */
72 export function installMailboxAdmission(ctx, stateDir) {
73 ctx.on('agent/pre-step', async (payload, next) => {
74 const decision = await next();
75 if (decision.kind !== 'enter')
76 return decision;
77 const root = join(payload.agent.session.header.cwd ?? process.cwd(), stateDir);
78 // The native runtime also wakes a parent when a background activation
79 // settles. A successfully delivered Team report already carries that
80 // result. Keep abnormal endings and missing reports as fallback signals.
81 const successfulSettlements = new Set(decision.messages.flatMap(input => {
82 const source = input.source;
83 return source?.kind === 'subagent-settled'
84 && source.summary === `Background subagent ${source.senderSessionId} finished and will do no further work unless you send it more.`
85 ? [source.senderSessionId] : [];
86 }));
87 const redundantSettlements = new Set();
88 if (successfulSettlements.size > 0) {
89 // Narrow containment: only AgentTeams state reads degrade silently.
90 try {
91 const owned = await findTeamByCaptain(root, payload.agent.id, await leadIdentityOfAsync(ctx, payload.agent.session));
92 if (owned !== undefined)
93 await withTeamLock(`team:${root}:${owned.id}`, async () => {
94 const team = await readTeam(root, owned.id);
95 if (team === undefined || !(await sessionLeadsTeamAsync(ctx, team, payload.agent.id)) || team.halted)
96 return;
97 const reports = await readMailbox(root, team.id, CAPTAIN_KEY);
98 for (const member of team.members) {
99 if (!successfulSettlements.has(member.id) || member.status === 'removed' || member.stopping)
100 continue;
101 const tasks = team.tasks.filter(task => task.assignee === member.name);
102 if (tasks.some(task => task.status === 'claimed' || task.status === 'in_progress'))
103 continue;
104 const latest = tasks.filter(task => (task.attempt ?? 0) > 0 || task.status === 'completed').sort((a, b) => b.updatedAt - a.updatedAt)[0];
105 if (latest?.status === 'completed' && reports.some(report => report.from === member.name && report.ts >= latest.updatedAt
106 && report.discardedAt === undefined && (report.deliveredAt !== undefined || report.readAt !== undefined))) {
107 redundantSettlements.add(member.id);
108 }
109 }
110 });
111 }
112 catch (error) {
113 // A corrupt AgentTeams state file (e.g. an invalid team.json) must never
114 // hold the host's step admission hostage: degrade to plain admission.
115 ctx.logger?.warn(`agent-teams: mailbox admission degraded to plain pass-through for agent ${payload.agent.id}: could not read team state under ${root} (a team.json may be corrupt or unreadable): ${String(error)}`);
116 return decision;
117 }
118 }
119 const batches = new Map();
120 const inputs = decision.messages.map(input => {
121 // Alpha.5/0.1.2-rc.1 public steering prepends a native sender block.
122 // The host-authored receipt remains a separate text block after it.
123 const receipt = input.content.flatMap(block => block.type === 'text' ? [parseReceipt(block.text)] : []).find(value => value !== undefined);
124 if (receipt === undefined)
125 return { input };
126 const key = JSON.stringify([receipt.teamId, receipt.recipient]);
127 let batch = batches.get(key);
128 if (batch === undefined) {
129 batch = { receipt, ids: new Set(), current: new Map() };
130 batches.set(key, batch);
131 }
132 for (const id of receipt.ids)
133 batch.ids.add(id);
134 return { input, receipt, batch };
135 });
136 // One read/acknowledgement per recipient per step, even for a large burst.
137 for (const batch of batches.values()) {
138 const { receipt } = batch;
139 try {
140 await withTeamLock(`team:${root}:${receipt.teamId}`, async () => {
141 const team = await readTeam(root, receipt.teamId);
142 if (team === undefined)
143 return;
144 // Captain mail is admitted for any lead session of the team: after a
145 // fork the human reads it in the fork while members still address the
146 // recorded captain. Acknowledging marks it read for both.
147 const isCaptainRecipient = receipt.recipient === CAPTAIN_KEY
148 && await sessionLeadsTeamAsync(ctx, team, payload.agent.id);
149 const recipientId = receipt.recipient === CAPTAIN_KEY ? team.captainSessionId
150 : team.members.find(member => member.name === receipt.recipient && member.status !== 'removed' && member.stopping !== true)?.id;
151 if (!isCaptainRecipient && recipientId !== payload.agent.id)
152 return;
153 const selected = (await readMailbox(root, team.id, receipt.recipient)).filter(message => batch.ids.has(message.id));
154 const current = selected.filter(message => message.readAt === undefined && isCurrentMail(team, message));
155 await discardMailboxMessages(root, team.id, receipt.recipient, selected.filter(message => !isCurrentMail(team, message)).map(message => message.id));
156 await acknowledgeMailbox(root, team.id, receipt.recipient, current.map(message => message.id));
157 batch.current = new Map(current.map(message => [message.id, message]));
158 });
159 }
160 catch (error) {
161 // Narrow containment, per team: the messages of this batch are not
162 // acked (the teamId/recipient above identify the unread mail), but the
163 // receipt inputs still pass through untouched instead of holding the
164 // host's step admission hostage.
165 batch.failed = true;
166 ctx.logger?.warn(`agent-teams: mailbox admission degraded to plain pass-through for agent ${payload.agent.id}: could not read team "${receipt.teamId}" (state under ${root} may be corrupt or unreadable, recipient ${receipt.recipient} mail left unacked): ${String(error)}`);
167 }
168 }
169 const admitted = [];
170 for (const { input, receipt, batch } of inputs) {
171 if (input.source?.kind === 'subagent-settled' && redundantSettlements.has(input.source.senderSessionId)
172 && input.source.summary === `Background subagent ${input.source.senderSessionId} finished and will do no further work unless you send it more.`)
173 continue;
174 if (receipt === undefined || batch === undefined || batch.failed === true) {
175 admitted.push(input);
176 continue;
177 }
178 const messages = [];
179 for (const id of receipt.ids) {
180 const message = batch.current.get(id);
181 if (message === undefined)
182 continue;
183 batch.current.delete(id);
184 messages.push(message);
185 }
186 if (messages.length > 0)
187 admitted.push({ ...input, content: [{ type: 'text', text: mailboxBody(receipt.recipient, messages) }] });
188 }
189 // Reject only a new turn whose sole trigger was obsolete mail. During an
190 // existing turn, a status tool may have consumed this same mail already;
191 // dropping its duplicate must not block the pending tool-result response.
192 if (decision.messages.length > 0 && admitted.length === 0) {
193 const events = sessionOwnEvents(payload.agent.session);
194 let continuing = false;
195 for (let i = events.length - 1; i >= 0; i--) {
196 const event = events[i];
197 if (event.type === 'step/start' && event.data.turn === payload.turn) {
198 continuing = true;
199 break;
200 }
201 if (event.type === 'turn/start')
202 break;
203 }
204 if (!continuing)
205 return { kind: 'reject' };
206 }
207 return { ...decision, messages: admitted };
208 });
209 }
210
210 lines JAVASCRIPT