@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +30 -4
- package/src/address-display.ts +141 -0
- package/src/conversation-budget.ts +651 -0
- package/src/conversation-store.ts +351 -0
- package/src/distress.ts +161 -0
- package/src/env-info-scope.ts +153 -0
- package/src/error-text.ts +28 -0
- package/src/inbox-source.ts +73 -0
- package/src/inbox.ts +2335 -0
- package/src/index.ts +273 -0
- package/src/member-cwd.ts +128 -0
- package/src/member-ports.ts +162 -0
- package/src/refs.ts +51 -0
- package/src/registry.ts +741 -0
- package/src/runtime.ts +2501 -0
- package/src/self-card-delta.ts +428 -0
- package/src/service.ts +9212 -0
- package/src/snapshot.ts +614 -0
- package/src/team-address.ts +96 -0
- package/src/team-log.ts +487 -0
- package/src/team-service.ts +1966 -0
- package/src/team-slug.ts +167 -0
- package/src/team-store.ts +619 -0
- package/src/tool.ts +1306 -0
- package/src/types/budget.ts +168 -0
- package/src/types/constants.ts +17 -0
- package/src/types/dispatch.ts +133 -0
- package/src/types/events.ts +132 -0
- package/src/types/execution.ts +289 -0
- package/src/types/lifecycle.ts +372 -0
- package/src/types/member.ts +221 -0
- package/src/types/message.ts +113 -0
- package/src/types/results.ts +64 -0
- package/src/types/roster.ts +137 -0
- package/src/types/service.ts +702 -0
- package/src/types/session.ts +102 -0
- package/src/types/team.ts +558 -0
- package/src/types.ts +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1966 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Team 能力层默认实现(0.19 S3)。
|
|
3
|
+
*
|
|
4
|
+
* 职责:
|
|
5
|
+
* - roster 由 Agent 记录派生(`team_id` + `membership`),不单独持久化;
|
|
6
|
+
* - 只追加团队日志;无 `@` 的 post 绝不 dispatch(结构性保证零 run);
|
|
7
|
+
* - `@` 使用结构化 agent id,先写日志再并行 dispatch,逐条返回结果;
|
|
8
|
+
* - 订阅 `agent.spawned/rejoined/closed/forked` 写系统消息(只写日志);
|
|
9
|
+
* 0.51 起不再订阅 `agent.rotated`(该事件从未发出,`rotate` 系统行因此从未写过)。
|
|
10
|
+
* - 0.27:另从可注入的 `EventStream` 订阅 `run.*` 终态写 reply / 失败日志。
|
|
11
|
+
*
|
|
12
|
+
* 依赖边界:只依赖 `AgentService` 与 `TeamStore` 接口,不 import team-store.ts。
|
|
13
|
+
*
|
|
14
|
+
* @module @vessel-agent/agent
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
18
|
+
import type { EventStream, Logger, MessageRef, RunEvent, RunTrigger } from '@vessel-agent/core';
|
|
19
|
+
import { type AddressStyle, DEFAULT_ADDRESS_STYLE, formatAddress } from './address-display.js';
|
|
20
|
+
import { generateConversationId, isValidConversationId } from './conversation-budget.js';
|
|
21
|
+
import { errorText } from './error-text.js';
|
|
22
|
+
import { type AgentInboxDelivery, DEFAULT_INBOX_DELIVERY } from './inbox.js';
|
|
23
|
+
import { normalizeRefs } from './refs.js';
|
|
24
|
+
import { addressSegmentCount, HUMAN_PRINCIPAL } from './team-address.js';
|
|
25
|
+
import { MAX_LOG_READ_LIMIT } from './team-log.js';
|
|
26
|
+
import {
|
|
27
|
+
type AgentEvent,
|
|
28
|
+
type AgentService,
|
|
29
|
+
type AgentTeamService,
|
|
30
|
+
type BudgetOverrideInput,
|
|
31
|
+
type BudgetOverview,
|
|
32
|
+
type BudgetStatusInput,
|
|
33
|
+
DEFAULT_OWNER,
|
|
34
|
+
type FederationSendPort,
|
|
35
|
+
MAX_MESSAGE_BYTES,
|
|
36
|
+
type MemberStatus,
|
|
37
|
+
type SendResult,
|
|
38
|
+
type TeamAgentSendInput,
|
|
39
|
+
type TeamAgentSendResult,
|
|
40
|
+
type TeamArchiveInput,
|
|
41
|
+
type TeamCreateInput,
|
|
42
|
+
type TeamDelivery,
|
|
43
|
+
type TeamDetail,
|
|
44
|
+
TeamError,
|
|
45
|
+
type TeamGetOptions,
|
|
46
|
+
type TeamListOptions,
|
|
47
|
+
type TeamLogEntry,
|
|
48
|
+
type TeamMemberSummary,
|
|
49
|
+
type TeamMembersInput,
|
|
50
|
+
type TeamMembersResult,
|
|
51
|
+
type TeamPostInput,
|
|
52
|
+
type TeamPostResult,
|
|
53
|
+
type TeamRecallDeliveryInput,
|
|
54
|
+
type TeamRecallDeliveryResult,
|
|
55
|
+
type TeamRecord,
|
|
56
|
+
type TeamRetractInput,
|
|
57
|
+
type TeamRetractResult,
|
|
58
|
+
type TeamRosterOptions,
|
|
59
|
+
type TeamServiceEvent,
|
|
60
|
+
type TeamStore,
|
|
61
|
+
type TeamSummary,
|
|
62
|
+
type TeamSystemEvent,
|
|
63
|
+
type TeamUpdateInput,
|
|
64
|
+
} from './types.js';
|
|
65
|
+
|
|
66
|
+
/** DefaultTeamService 构造参数(app 装配按此名称接线) */
|
|
67
|
+
export interface TeamServiceOptions {
|
|
68
|
+
tenantId: string;
|
|
69
|
+
agent: AgentService;
|
|
70
|
+
store: TeamStore;
|
|
71
|
+
now?: () => number;
|
|
72
|
+
newId?: () => string;
|
|
73
|
+
logger?: Logger;
|
|
74
|
+
/** 0.21:跨节点发送端口;缺失时地址形式返回 federation_unavailable */
|
|
75
|
+
federation?: FederationSendPort;
|
|
76
|
+
/** 0.27:run.* 事件来源;缺省时 reply / 失败日志不写(fail-closed) */
|
|
77
|
+
events?: EventStream;
|
|
78
|
+
/**
|
|
79
|
+
* q-addr-display:地址显示风格(`ui.addressStyle`,装配层读 config 传入)。
|
|
80
|
+
* 只影响 federation 抬头的 `from` 显示行;`reply with` 的路由地址恒 canonical。
|
|
81
|
+
* 缺省 name 优先(远端 node 无名可查时兜底短 id)。
|
|
82
|
+
*/
|
|
83
|
+
addressStyle?: AddressStyle;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 系统消息固定英文文案(不含正文) */
|
|
87
|
+
const SYSTEM_CONTENT: Record<TeamSystemEvent, string> = {
|
|
88
|
+
join: 'agent joined team',
|
|
89
|
+
leave: 'agent left team',
|
|
90
|
+
archive: 'agent archived',
|
|
91
|
+
budget_override: 'budget limit overridden',
|
|
92
|
+
create: 'agent created',
|
|
93
|
+
// 旧日志只读;新代码不再写 `system_event:'fork'`。
|
|
94
|
+
fork: 'agent forked',
|
|
95
|
+
// retract 的 tombstone 由 retract() 自己写(content 为空,UI 按 system_event 渲染);
|
|
96
|
+
// 这里只满足 Record 完整性,不会被 systemEventFor 选中。
|
|
97
|
+
retract: 'message retracted',
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 已退役 Binding 记账上限(0.27)。每 agent 退役 Binding ≤`MAX_RETIRED_BODIES`(50),
|
|
102
|
+
* 超限按插入顺序丢最旧,保证长活进程不无界增长。
|
|
103
|
+
*/
|
|
104
|
+
const MAX_RETIRED_BODIES_TRACKED = 256;
|
|
105
|
+
|
|
106
|
+
/** 退役 Binding 键(`agentId\0sessionId`):同一 agent 的不同 Binding 互不共用 */
|
|
107
|
+
function retiredBindingKey(agentId: string, sessionId: string): string {
|
|
108
|
+
return `${agentId}\u0000${sessionId}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const NOOP_LOGGER: Logger = {
|
|
112
|
+
debug: () => undefined,
|
|
113
|
+
info: () => undefined,
|
|
114
|
+
warn: () => undefined,
|
|
115
|
+
error: () => undefined,
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** 解析后的 send 目标(`team_id` 用于判断是否写 mention 日志) */
|
|
119
|
+
interface SendTarget {
|
|
120
|
+
agent_id: string;
|
|
121
|
+
team_id?: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface NamedSendTarget extends SendTarget {
|
|
125
|
+
name?: string;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
type ResolvedSendTarget =
|
|
129
|
+
| { ok: true; target?: SendTarget }
|
|
130
|
+
| { ok: false; result: TeamAgentSendResult };
|
|
131
|
+
|
|
132
|
+
/** post 的投递槽:校验失败的直接带 delivery,校验通过的等日志写完后 dispatch */
|
|
133
|
+
interface DispatchSlot {
|
|
134
|
+
targetId?: string;
|
|
135
|
+
delivery?: TeamDelivery;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export class DefaultTeamService implements AgentTeamService {
|
|
139
|
+
readonly tenantId: string;
|
|
140
|
+
|
|
141
|
+
private readonly agent: AgentService;
|
|
142
|
+
private readonly store: TeamStore;
|
|
143
|
+
private readonly now: () => number;
|
|
144
|
+
private readonly newId: () => string;
|
|
145
|
+
private readonly logger: Logger;
|
|
146
|
+
private readonly federation: FederationSendPort | undefined;
|
|
147
|
+
private readonly addressStyle: AddressStyle;
|
|
148
|
+
private readonly unsubscribe: () => void;
|
|
149
|
+
/** 0.27:run.* 订阅的取消函数;没有 events 时为 undefined */
|
|
150
|
+
private readonly unsubscribeRuns: (() => void) | undefined;
|
|
151
|
+
/** 指针事件监听者;绝不含正文(Web hub 用) */
|
|
152
|
+
private readonly listeners = new Set<(event: TeamServiceEvent) => void>();
|
|
153
|
+
/** members remove 期间的标记:把该次 agent.closed 写成 archive 而不是 leave */
|
|
154
|
+
private readonly archiveInFlight = new Set<string>();
|
|
155
|
+
/**
|
|
156
|
+
* 已退役 / 已关闭的 Binding:`(agent_id, session_id)` → 退役时在途的那一轮 run id。
|
|
157
|
+
*
|
|
158
|
+
* B′(0.52):值区分两类终态。带 run id(rotate 交棒轮)⇒ 该 run 的终态照常记账;
|
|
159
|
+
* `undefined`(close / 其它路径)或 run id 对不上 ⇒ 真迟到旧轮,fence 掉。
|
|
160
|
+
*/
|
|
161
|
+
private readonly retiredBodies = new Map<string, string | undefined>();
|
|
162
|
+
private disposed = false;
|
|
163
|
+
|
|
164
|
+
constructor(options: TeamServiceOptions) {
|
|
165
|
+
this.tenantId = options.tenantId;
|
|
166
|
+
this.agent = options.agent;
|
|
167
|
+
this.store = options.store;
|
|
168
|
+
this.now = options.now ?? Date.now;
|
|
169
|
+
this.newId = options.newId ?? randomUUID;
|
|
170
|
+
this.logger = options.logger ?? NOOP_LOGGER;
|
|
171
|
+
this.federation = options.federation;
|
|
172
|
+
this.addressStyle = options.addressStyle ?? DEFAULT_ADDRESS_STYLE;
|
|
173
|
+
this.unsubscribe = this.agent.subscribe((event) => this.onAgentEvent(event));
|
|
174
|
+
this.unsubscribeRuns =
|
|
175
|
+
options.events !== undefined
|
|
176
|
+
? options.events.subscribe((event) => this.onRunEvent(event))
|
|
177
|
+
: undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async list(options: TeamListOptions = {}): Promise<TeamSummary[]> {
|
|
181
|
+
const records = this.store.list();
|
|
182
|
+
const counts = new Map<string, number>();
|
|
183
|
+
const online = new Map<string, number>();
|
|
184
|
+
for (const status of await this.listVisible(options.viewer)) {
|
|
185
|
+
if (status.team_id === undefined || status.membership !== 'present') continue;
|
|
186
|
+
counts.set(status.team_id, (counts.get(status.team_id) ?? 0) + 1);
|
|
187
|
+
if (status.presence === 'live') {
|
|
188
|
+
online.set(status.team_id, (online.get(status.team_id) ?? 0) + 1);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return records.map((record) =>
|
|
192
|
+
toTeamSummary(record, counts.get(record.team_id) ?? 0, online.get(record.team_id) ?? 0),
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async get(teamId: string, options: TeamGetOptions = {}): Promise<TeamDetail | undefined> {
|
|
197
|
+
const record = this.store.get(teamId);
|
|
198
|
+
if (record === undefined) return undefined;
|
|
199
|
+
const members = await this.rosterFor(teamId, options.viewer);
|
|
200
|
+
// 分页窗口由日志层计算:无 before = 尾读,有 before = 有界回扫。
|
|
201
|
+
const window = await this.store.readLogWindow(teamId, {
|
|
202
|
+
...(options.limit !== undefined ? { limit: options.limit } : {}),
|
|
203
|
+
...(options.before !== undefined ? { before: options.before } : {}),
|
|
204
|
+
});
|
|
205
|
+
return {
|
|
206
|
+
// 计数用完整 roster;窗口只裁剪返回的 members(DECISION-037 §7.1)。
|
|
207
|
+
team: toTeamSummary(
|
|
208
|
+
record,
|
|
209
|
+
members.length,
|
|
210
|
+
members.filter((member) => member.presence === 'live').length,
|
|
211
|
+
),
|
|
212
|
+
members: windowRoster(members, options.members_limit),
|
|
213
|
+
messages: window.entries,
|
|
214
|
+
messages_has_more: window.hasMore,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async roster(teamId: string, options: TeamRosterOptions = {}): Promise<TeamMemberSummary[]> {
|
|
219
|
+
return this.rosterFor(teamId, options.viewer);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async identify(sessionId: string): Promise<TeamMemberSummary | undefined> {
|
|
223
|
+
const status = await this.agent.identify(sessionId);
|
|
224
|
+
return status === undefined ? undefined : toMemberSummary(status);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async create(input: TeamCreateInput): Promise<TeamSummary> {
|
|
228
|
+
// Store 负责 workspace 幂等去重;canonical / CLI / Web 都只消费 TeamSummary。
|
|
229
|
+
const { record } = await this.store.create(input);
|
|
230
|
+
const team = await this.summarize(record);
|
|
231
|
+
this.emit({ team_id: record.team_id, kind: 'roster' });
|
|
232
|
+
return team;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async update(input: TeamUpdateInput): Promise<TeamSummary> {
|
|
236
|
+
const { team_id, ...patch } = input;
|
|
237
|
+
const record = await this.store.update(team_id, patch);
|
|
238
|
+
const team = await this.summarize(record);
|
|
239
|
+
this.emit({ team_id: record.team_id, kind: 'roster' });
|
|
240
|
+
return team;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async archive(input: TeamArchiveInput): Promise<TeamSummary> {
|
|
244
|
+
// Store 不知道 roster:present(含 live / gone)成员一律拒绝归档。
|
|
245
|
+
const members = await this.rosterFor(input.team_id);
|
|
246
|
+
if (members.length > 0) {
|
|
247
|
+
throw new TeamError('team_not_empty', `team_not_empty: ${input.team_id}`);
|
|
248
|
+
}
|
|
249
|
+
const record = await this.store.archive(input.team_id);
|
|
250
|
+
this.emit({ team_id: record.team_id, kind: 'roster' });
|
|
251
|
+
return toTeamSummary(record, 0, 0);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async setSpawnFrozen(teamId: string, frozen: boolean): Promise<TeamSummary> {
|
|
255
|
+
const record = await this.store.setSpawnFrozen(teamId, frozen);
|
|
256
|
+
const team = await this.summarize(record);
|
|
257
|
+
this.emit({ team_id: record.team_id, kind: 'spawn', frozen });
|
|
258
|
+
return team;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
isSpawnFrozen(teamId: string): boolean {
|
|
262
|
+
return this.store.get(teamId)?.spawn_frozen === true;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async budget(input: BudgetStatusInput | BudgetOverrideInput): Promise<BudgetOverview> {
|
|
266
|
+
const record = this.store.get(input.team_id);
|
|
267
|
+
if (record === undefined) {
|
|
268
|
+
throw new TeamError('team_not_found', `team_not_found: ${input.team_id}`);
|
|
269
|
+
}
|
|
270
|
+
// 归档 Team 只读:status 仍可读,人工 override 拒绝。
|
|
271
|
+
if ('dimension' in input) assertTeamNotArchived(record, input.team_id);
|
|
272
|
+
if (!this.agent.budget) {
|
|
273
|
+
throw new TeamError('team_not_found', 'budget unavailable');
|
|
274
|
+
}
|
|
275
|
+
const result = await this.agent.budget(input);
|
|
276
|
+
if (
|
|
277
|
+
result.action === 'status' &&
|
|
278
|
+
input.conversation_id !== undefined &&
|
|
279
|
+
result.conversations.length === 0
|
|
280
|
+
) {
|
|
281
|
+
throw new TeamError(
|
|
282
|
+
'team_conversation_not_found',
|
|
283
|
+
`conversation_not_found: ${input.conversation_id}`,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
if (result.action === 'override') {
|
|
287
|
+
// override 审计:只写 system 日志,绝不 dispatch。
|
|
288
|
+
const messageId = this.newId();
|
|
289
|
+
const entry: TeamLogEntry = {
|
|
290
|
+
message_id: messageId,
|
|
291
|
+
team_id: input.team_id,
|
|
292
|
+
from: HUMAN_PRINCIPAL,
|
|
293
|
+
to: [],
|
|
294
|
+
mentions: [],
|
|
295
|
+
content: `budget override ${result.conversation_id} ${result.dimension} ${result.previous_max} -> ${result.max}`,
|
|
296
|
+
ts: this.now(),
|
|
297
|
+
kind: 'system',
|
|
298
|
+
system_event: 'budget_override',
|
|
299
|
+
conversation_id: result.conversation_id,
|
|
300
|
+
};
|
|
301
|
+
try {
|
|
302
|
+
await this.store.appendLog(entry);
|
|
303
|
+
} catch (error) {
|
|
304
|
+
throw new TeamError('team_log_write_failed', errorText(error));
|
|
305
|
+
}
|
|
306
|
+
this.emit({ team_id: input.team_id, kind: 'system', message_id: messageId });
|
|
307
|
+
}
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async post(input: TeamPostInput): Promise<TeamPostResult> {
|
|
312
|
+
const record = this.store.get(input.team_id);
|
|
313
|
+
if (record === undefined) {
|
|
314
|
+
throw new TeamError('team_not_found', `team_not_found: ${input.team_id}`);
|
|
315
|
+
}
|
|
316
|
+
assertTeamNotArchived(record, input.team_id);
|
|
317
|
+
const content = readContent(input.content);
|
|
318
|
+
const from = input.from ?? DEFAULT_OWNER;
|
|
319
|
+
const mentions = dedupe(input.mentions ?? []);
|
|
320
|
+
// 附件引用(0.52):只有路径与种类。三个去处同源:成员侧的 core `Message.refs`、
|
|
321
|
+
// 本条 Team 日志的 `refs`(时间线据此显示 chip)、`TeamPostResult.refs`(乐观更新)。
|
|
322
|
+
// 形状归一与 dispatch 共用一份。
|
|
323
|
+
const refs = normalizeRefs(input.refs);
|
|
324
|
+
// 一次生成、所有 mention 共用;显式 id 先校验。
|
|
325
|
+
const conversationId = this.resolveConversationId(input.conversation_id);
|
|
326
|
+
|
|
327
|
+
// Team 日志对 team 可见:private roster 成员不能作为 post 的 actor。
|
|
328
|
+
if (from !== HUMAN_PRINCIPAL) {
|
|
329
|
+
const actor = await this.agent.identify(from);
|
|
330
|
+
if (actor !== undefined && isPrivateRosterMember(actor)) {
|
|
331
|
+
throw new TeamError('team_private_member', `team_private_member: ${from}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// 1. 只做校验与解析,不产生任何 dispatch。
|
|
336
|
+
const visible = await this.listVisible(from);
|
|
337
|
+
const byId = new Map(visible.map((status) => [status.id, status]));
|
|
338
|
+
const bySession = new Map(visible.map((status) => [status.session_id, status]));
|
|
339
|
+
const slots: DispatchSlot[] = [];
|
|
340
|
+
const resolved: string[] = [];
|
|
341
|
+
const seenTargets = new Set<string>();
|
|
342
|
+
|
|
343
|
+
for (const mention of mentions) {
|
|
344
|
+
const target = byId.get(mention) ?? bySession.get(mention);
|
|
345
|
+
if (target === undefined) {
|
|
346
|
+
// 不可见 / 不存在在 viewer 视角下不可区分,按 unknown_member 返回。
|
|
347
|
+
slots.push({
|
|
348
|
+
delivery: {
|
|
349
|
+
agent_id: mention,
|
|
350
|
+
status: 'error',
|
|
351
|
+
code: 'unknown_member',
|
|
352
|
+
reason: `unknown_member: ${mention}`,
|
|
353
|
+
},
|
|
354
|
+
});
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (isPrivateRosterMember(target)) {
|
|
358
|
+
// private 成员不能被 @,其 id 也不得进入日志的 to / mentions。
|
|
359
|
+
slots.push({
|
|
360
|
+
delivery: {
|
|
361
|
+
agent_id: target.id,
|
|
362
|
+
status: 'error',
|
|
363
|
+
code: 'team_private_member',
|
|
364
|
+
reason: `team_private_member: ${target.id}`,
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (target.id === from) {
|
|
370
|
+
slots.push({
|
|
371
|
+
delivery: {
|
|
372
|
+
agent_id: target.id,
|
|
373
|
+
status: 'error',
|
|
374
|
+
code: 'team_self_mention',
|
|
375
|
+
reason: 'team_self_mention',
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (target.team_id !== input.team_id) {
|
|
381
|
+
slots.push({
|
|
382
|
+
delivery: {
|
|
383
|
+
agent_id: target.id,
|
|
384
|
+
status: 'error',
|
|
385
|
+
code: 'team_not_member',
|
|
386
|
+
reason: `team_not_member: ${target.id}`,
|
|
387
|
+
},
|
|
388
|
+
});
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (target.membership !== 'present') {
|
|
392
|
+
slots.push({
|
|
393
|
+
delivery: {
|
|
394
|
+
agent_id: target.id,
|
|
395
|
+
status: 'error',
|
|
396
|
+
code: 'agent_left',
|
|
397
|
+
reason: `agent_left: ${target.id}`,
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
// 同一目标(id 与 session 两种写法)只投递一次。
|
|
403
|
+
if (seenTargets.has(target.id)) continue;
|
|
404
|
+
seenTargets.add(target.id);
|
|
405
|
+
resolved.push(target.id);
|
|
406
|
+
slots.push({ targetId: target.id });
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// 2. 先写日志;失败直接抛错,绝不 dispatch。
|
|
410
|
+
// 日志 `to` 优先用解析出的 agent id;owner 日志标记(input.to)只进日志、绝不 dispatch。
|
|
411
|
+
const messageId = this.newId();
|
|
412
|
+
const ts = this.now();
|
|
413
|
+
const kind: TeamPostResult['kind'] = mentions.length > 0 ? 'mention' : 'post';
|
|
414
|
+
const to = resolved.length > 0 ? [...resolved] : [...(input.to ?? [])];
|
|
415
|
+
const entry: TeamLogEntry = {
|
|
416
|
+
message_id: messageId,
|
|
417
|
+
team_id: input.team_id,
|
|
418
|
+
from,
|
|
419
|
+
to,
|
|
420
|
+
mentions: [...resolved],
|
|
421
|
+
content,
|
|
422
|
+
ts,
|
|
423
|
+
kind,
|
|
424
|
+
conversation_id: conversationId,
|
|
425
|
+
...(input.federation !== undefined ? { federation: input.federation } : {}),
|
|
426
|
+
// 只在非空时写:旧日志没有该键,无引用的新行形状与旧行一致。
|
|
427
|
+
...(refs.length > 0 ? { refs } : {}),
|
|
428
|
+
};
|
|
429
|
+
try {
|
|
430
|
+
await this.store.appendLog(entry);
|
|
431
|
+
} catch (error) {
|
|
432
|
+
throw new TeamError('team_log_write_failed', errorText(error));
|
|
433
|
+
}
|
|
434
|
+
this.emit({ team_id: input.team_id, kind, message_id: messageId });
|
|
435
|
+
|
|
436
|
+
// 3. 日志已落盘后再并行投递;单条失败不影响其它条目。
|
|
437
|
+
// 跨节点报文只给 dispatch 前置回信抬头;日志 content 保持原文(DECISION-037 §8)。
|
|
438
|
+
const dispatchContent =
|
|
439
|
+
input.federation === undefined
|
|
440
|
+
? content
|
|
441
|
+
: federationDispatchContent(input.federation.from_addr, content, this.addressStyle);
|
|
442
|
+
const dispatched = await Promise.all(
|
|
443
|
+
slots.map((slot) =>
|
|
444
|
+
slot.targetId === undefined
|
|
445
|
+
? Promise.resolve(undefined)
|
|
446
|
+
: this.dispatchMention(
|
|
447
|
+
slot.targetId,
|
|
448
|
+
dispatchContent,
|
|
449
|
+
from,
|
|
450
|
+
conversationId,
|
|
451
|
+
input.team_id,
|
|
452
|
+
refs,
|
|
453
|
+
messageId,
|
|
454
|
+
input.triggered_by,
|
|
455
|
+
),
|
|
456
|
+
),
|
|
457
|
+
);
|
|
458
|
+
const delivered: TeamDelivery[] = [];
|
|
459
|
+
slots.forEach((slot, index) => {
|
|
460
|
+
const delivery = slot.delivery ?? dispatched[index];
|
|
461
|
+
if (delivery !== undefined) delivered.push(delivery);
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
return {
|
|
465
|
+
message_id: messageId,
|
|
466
|
+
team_id: input.team_id,
|
|
467
|
+
kind,
|
|
468
|
+
mentions: resolved,
|
|
469
|
+
delivered,
|
|
470
|
+
ts,
|
|
471
|
+
conversation_id: conversationId,
|
|
472
|
+
// 回执与日志同一份(乐观更新直接用,不必等下一次 teams.get)。
|
|
473
|
+
...(refs.length > 0 ? { refs } : {}),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* 删除(wire 仍叫 retract,用户裁定改「删除」语义):日志保持 append-only,追加一条
|
|
479
|
+
* system tombstone;不删除 / 不改写原消息,也不级联删除后续回复。目标必须仍在可读
|
|
480
|
+
* 窗口(≤1000 条)内。
|
|
481
|
+
*
|
|
482
|
+
* tombstone 之外**级联真删各成员 inbox 里的那一份**(cascadeRecall):只隐藏视图
|
|
483
|
+
* 而收件箱照投照跑不是「删除」。级联 best-effort —— tombstone 已落盘,单条收口
|
|
484
|
+
* 失败只 warn,不推翻删除结果(已消费 / 正在跑的副本本就收不回,按 skipped 如实)。
|
|
485
|
+
*/
|
|
486
|
+
async retract(input: TeamRetractInput): Promise<TeamRetractResult> {
|
|
487
|
+
const record = this.store.get(input.team_id);
|
|
488
|
+
if (record === undefined) {
|
|
489
|
+
throw new TeamError('team_not_found', `team_not_found: ${input.team_id}`);
|
|
490
|
+
}
|
|
491
|
+
assertTeamNotArchived(record, input.team_id);
|
|
492
|
+
|
|
493
|
+
const entries = await this.store.readLog(input.team_id, { limit: MAX_LOG_READ_LIMIT });
|
|
494
|
+
const target = entries.find((entry) => entry.message_id === input.message_id);
|
|
495
|
+
if (target === undefined) {
|
|
496
|
+
// 窗口外的旧消息不支持撤回:与真正不存在一样按 message_not_found 返回。
|
|
497
|
+
throw new TeamError(
|
|
498
|
+
'message_not_found',
|
|
499
|
+
`message_not_found: ${input.message_id} (outside the ${MAX_LOG_READ_LIMIT}-entry read window)`,
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
// system 行(含已有 tombstone)本身不可撤回。
|
|
503
|
+
if (target.kind === 'system') {
|
|
504
|
+
throw new TeamError('invalid_input', `cannot retract system message: ${input.message_id}`);
|
|
505
|
+
}
|
|
506
|
+
const alreadyRetracted = entries.some(
|
|
507
|
+
(entry) =>
|
|
508
|
+
entry.system_event === 'retract' && entry.retracted_message_id === input.message_id,
|
|
509
|
+
);
|
|
510
|
+
if (alreadyRetracted) {
|
|
511
|
+
throw new TeamError('conflict', 'already_retracted');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const messageId = this.newId();
|
|
515
|
+
const entry: TeamLogEntry = {
|
|
516
|
+
message_id: messageId,
|
|
517
|
+
team_id: input.team_id,
|
|
518
|
+
from: input.from ?? HUMAN_PRINCIPAL,
|
|
519
|
+
to: [],
|
|
520
|
+
mentions: [],
|
|
521
|
+
content: '',
|
|
522
|
+
ts: this.now(),
|
|
523
|
+
kind: 'system',
|
|
524
|
+
system_event: 'retract',
|
|
525
|
+
retracted_message_id: input.message_id,
|
|
526
|
+
};
|
|
527
|
+
try {
|
|
528
|
+
await this.store.appendLog(entry);
|
|
529
|
+
} catch (error) {
|
|
530
|
+
throw new TeamError('team_log_write_failed', errorText(error));
|
|
531
|
+
}
|
|
532
|
+
// 指针事件:web 的定向 reload 据此拉到 tombstone;不含正文。
|
|
533
|
+
this.emit({ team_id: input.team_id, kind: 'system', message_id: messageId });
|
|
534
|
+
// 删除语义的另一半:收件箱副本级联真删(与编辑共用同一段收口)。
|
|
535
|
+
try {
|
|
536
|
+
await this.cascadeRecall(target);
|
|
537
|
+
} catch (error) {
|
|
538
|
+
this.logger.warn('team.retract.cascade_failed', {
|
|
539
|
+
team_id: input.team_id,
|
|
540
|
+
message_id: input.message_id,
|
|
541
|
+
error: errorText(error),
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
message_id: messageId,
|
|
546
|
+
team_id: input.team_id,
|
|
547
|
+
retracted_message_id: input.message_id,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* 消费一条 team 消息的 inbox 投递(编辑按钮):**不写 tombstone、不改日志**,
|
|
553
|
+
* 只把该消息投进各成员收件箱的那一份拿走 —— 否则人改完重发,成员还会把旧的那份
|
|
554
|
+
* 执行一遍(同一段话两份)。
|
|
555
|
+
*
|
|
556
|
+
* 目标必须仍在可读窗口内(与 retract 同口径);system 行没有投递,拒绝。
|
|
557
|
+
* 不检查归档:这不是日志写操作,归档 Team 的旧投递同样该能被收掉。
|
|
558
|
+
*/
|
|
559
|
+
async recallDelivery(input: TeamRecallDeliveryInput): Promise<TeamRecallDeliveryResult> {
|
|
560
|
+
const record = this.store.get(input.team_id);
|
|
561
|
+
if (record === undefined) {
|
|
562
|
+
throw new TeamError('team_not_found', `team_not_found: ${input.team_id}`);
|
|
563
|
+
}
|
|
564
|
+
const entries = await this.store.readLog(input.team_id, { limit: MAX_LOG_READ_LIMIT });
|
|
565
|
+
const target = entries.find((entry) => entry.message_id === input.message_id);
|
|
566
|
+
if (target === undefined) {
|
|
567
|
+
throw new TeamError(
|
|
568
|
+
'message_not_found',
|
|
569
|
+
`message_not_found: ${input.message_id} (outside the ${MAX_LOG_READ_LIMIT}-entry read window)`,
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
if (target.kind === 'system') {
|
|
573
|
+
throw new TeamError('invalid_input', `cannot recall system message: ${input.message_id}`);
|
|
574
|
+
}
|
|
575
|
+
return {
|
|
576
|
+
team_id: input.team_id,
|
|
577
|
+
message_id: input.message_id,
|
|
578
|
+
deliveries: await this.cascadeRecall(target),
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* 级联收口(retract / recallDelivery 共用):对目标消息的每个收件成员,按
|
|
584
|
+
* `team_message_id` 关联撤回 inbox 里的那一份(`AgentService.recallTeamDelivery`,
|
|
585
|
+
* 与 `agents.recall` 同一段逐条收口:human 源真删、consumed / active 跳过)。
|
|
586
|
+
*
|
|
587
|
+
* 只走 `mentions`(真正 dispatch 过的解析后 id);`to` 里的 owner 日志标记不投递,
|
|
588
|
+
* 也不该级联。逐成员 best-effort:单条失败不影响其它成员。
|
|
589
|
+
*/
|
|
590
|
+
private async cascadeRecall(
|
|
591
|
+
target: TeamLogEntry,
|
|
592
|
+
): Promise<TeamRecallDeliveryResult['deliveries']> {
|
|
593
|
+
const deliveries: TeamRecallDeliveryResult['deliveries'] = [];
|
|
594
|
+
for (const agentId of target.mentions) {
|
|
595
|
+
const result = await this.agent.recallTeamDelivery(agentId, target.message_id);
|
|
596
|
+
deliveries.push({ agent_id: agentId, deleted: result.deleted, skipped: result.skipped });
|
|
597
|
+
}
|
|
598
|
+
return deliveries;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async members(input: TeamMembersInput): Promise<TeamMembersResult | undefined> {
|
|
602
|
+
const record = this.store.get(input.team_id);
|
|
603
|
+
if (record === undefined) return undefined;
|
|
604
|
+
// 归档 Team 只读:add / remove 都拒绝。
|
|
605
|
+
assertTeamNotArchived(record, input.team_id);
|
|
606
|
+
const from = input.from ?? DEFAULT_OWNER;
|
|
607
|
+
const visible = await this.listVisible(from);
|
|
608
|
+
const target = resolveMember(input.member, visible);
|
|
609
|
+
|
|
610
|
+
if (input.action === 'add') {
|
|
611
|
+
if (target.team_id !== undefined && target.team_id !== input.team_id) {
|
|
612
|
+
throw new TeamError('team_already_in_team', `team_already_in_team: ${target.id}`);
|
|
613
|
+
}
|
|
614
|
+
if (
|
|
615
|
+
target.name !== undefined &&
|
|
616
|
+
visible.some(
|
|
617
|
+
(status) =>
|
|
618
|
+
status.id !== target.id &&
|
|
619
|
+
status.team_id === input.team_id &&
|
|
620
|
+
status.membership === 'present' &&
|
|
621
|
+
status.name === target.name,
|
|
622
|
+
)
|
|
623
|
+
) {
|
|
624
|
+
throw new TeamError('invalid_input', `duplicate member name: ${target.name}`);
|
|
625
|
+
}
|
|
626
|
+
await this.agent.reinstate({ to: target.id, team_id: input.team_id, from });
|
|
627
|
+
this.emit({ team_id: input.team_id, kind: 'roster' });
|
|
628
|
+
return {
|
|
629
|
+
team_id: input.team_id,
|
|
630
|
+
action: 'add',
|
|
631
|
+
agent_id: target.id,
|
|
632
|
+
membership: 'present',
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
if (target.team_id !== input.team_id) {
|
|
637
|
+
throw new TeamError('team_not_member', `team_not_member: ${target.id}`);
|
|
638
|
+
}
|
|
639
|
+
this.archiveInFlight.add(target.id);
|
|
640
|
+
try {
|
|
641
|
+
await this.agent.close({ member: target.id });
|
|
642
|
+
} finally {
|
|
643
|
+
this.archiveInFlight.delete(target.id);
|
|
644
|
+
}
|
|
645
|
+
this.emit({ team_id: input.team_id, kind: 'roster' });
|
|
646
|
+
return {
|
|
647
|
+
team_id: input.team_id,
|
|
648
|
+
action: 'remove',
|
|
649
|
+
agent_id: target.id,
|
|
650
|
+
membership: 'left',
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
async listForCaller(sessionId: string): Promise<TeamMemberSummary[]> {
|
|
655
|
+
const caller = await this.agent.identify(sessionId);
|
|
656
|
+
if (caller === undefined) return [];
|
|
657
|
+
if (caller.team_id !== undefined) {
|
|
658
|
+
return this.rosterFor(caller.team_id, caller.id);
|
|
659
|
+
}
|
|
660
|
+
const visible = await this.listVisible(caller.id);
|
|
661
|
+
// 无 Team 时至少能看到自己(private 成员的 canView 对自身也不放行)。
|
|
662
|
+
return (visible.some((status) => status.id === caller.id) ? visible : [caller, ...visible]).map(
|
|
663
|
+
toMemberSummary,
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async send(input: TeamAgentSendInput): Promise<TeamAgentSendResult | SendResult> {
|
|
668
|
+
const caller = await this.agent.identify(input.from_session_id);
|
|
669
|
+
if (caller === undefined) {
|
|
670
|
+
return {
|
|
671
|
+
status: 'error',
|
|
672
|
+
code: 'unknown_member',
|
|
673
|
+
reason: `unknown_member: ${input.from_session_id}`,
|
|
674
|
+
logged: false,
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const interrupt = input.interrupt === true;
|
|
679
|
+
// 投递模式取代原来的 notify 布尔:内部只认 input / wake / quiet,wire 的
|
|
680
|
+
// `notify: true` 在 tool 边界已经转成 `delivery: 'wake'`。
|
|
681
|
+
const delivery: AgentInboxDelivery = input.delivery ?? DEFAULT_INBOX_DELIVERY;
|
|
682
|
+
const wakes = delivery === 'wake';
|
|
683
|
+
const messageId = input.message_id;
|
|
684
|
+
// 块 P2 additive:附件引用与 dispatch / post 共用同一份形状归一(只形状,不权限判定)。
|
|
685
|
+
const refs = normalizeRefs(input.refs);
|
|
686
|
+
|
|
687
|
+
let content: string;
|
|
688
|
+
if (messageId !== undefined) {
|
|
689
|
+
// message_id urgent:正文取自既有 inbox 消息;content 可省 / 为空。
|
|
690
|
+
if (input.content !== undefined && input.content !== '') {
|
|
691
|
+
return {
|
|
692
|
+
status: 'error',
|
|
693
|
+
code: 'invalid_input',
|
|
694
|
+
reason: 'pass either content or message_id, not both',
|
|
695
|
+
logged: false,
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
content = '';
|
|
699
|
+
} else {
|
|
700
|
+
try {
|
|
701
|
+
content = readContent(input.content);
|
|
702
|
+
} catch (error) {
|
|
703
|
+
return {
|
|
704
|
+
status: 'error',
|
|
705
|
+
code: errorCode(error) ?? 'invalid_input',
|
|
706
|
+
reason: errorText(error),
|
|
707
|
+
logged: false,
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// 地址形式优先于 id / session / name 解析。按段数分派(0.27):
|
|
713
|
+
// - 3 段 → 地址路;由 port 判定本机 / 远端,本机的就地投递,绝不出网;
|
|
714
|
+
// - 2 段 → 本机,但仍是地址形态,需要拆成 principal + team 再投,不能当名字查;
|
|
715
|
+
// - 1 段 → 普通 id / name 解析;裸 `human` 单独短路(它不是成员名)。
|
|
716
|
+
const segments = typeof input.to === 'string' ? addressSegmentCount(input.to) : undefined;
|
|
717
|
+
// 0.41:地址 / 跨节点目标不支持 urgent / wake 投递(1 段是普通 id / name)。
|
|
718
|
+
if (
|
|
719
|
+
(interrupt || wakes) &&
|
|
720
|
+
(segments === 2 || segments === 3 || input.to === HUMAN_PRINCIPAL)
|
|
721
|
+
) {
|
|
722
|
+
return {
|
|
723
|
+
status: 'rejected',
|
|
724
|
+
code: 'invalid_input',
|
|
725
|
+
reason: 'unsupported_delivery',
|
|
726
|
+
logged: false,
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
// 块 P2:refs 是 node-local 路径 —— 地址 / human 路(含跨节点)携带不了,
|
|
730
|
+
// 显式拒绝而不是静默丢附件(federation wire 无 refs 字段,不扩 wire)。
|
|
731
|
+
if (refs.length > 0 && (segments === 2 || segments === 3 || input.to === HUMAN_PRINCIPAL)) {
|
|
732
|
+
return {
|
|
733
|
+
status: 'error',
|
|
734
|
+
code: 'invalid_input',
|
|
735
|
+
reason: 'refs are only supported for local member targets',
|
|
736
|
+
logged: false,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
let conversationId: string;
|
|
741
|
+
try {
|
|
742
|
+
// 缺省继承调用者 session 当前 turn;跨 team 不继承;没有则生成。
|
|
743
|
+
conversationId = this.resolveConversationId(
|
|
744
|
+
input.conversation_id,
|
|
745
|
+
input.from_session_id,
|
|
746
|
+
caller.team_id,
|
|
747
|
+
caller.team_id,
|
|
748
|
+
);
|
|
749
|
+
} catch (error) {
|
|
750
|
+
return {
|
|
751
|
+
status: 'error',
|
|
752
|
+
code: errorCode(error) ?? 'invalid_input',
|
|
753
|
+
reason: errorText(error),
|
|
754
|
+
logged: false,
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
if (segments === 3) {
|
|
759
|
+
return this.sendAddress(caller, input.to, content, conversationId);
|
|
760
|
+
}
|
|
761
|
+
if (segments === 2) {
|
|
762
|
+
return this.sendLocalAddress(caller, input.to, content, conversationId);
|
|
763
|
+
}
|
|
764
|
+
// 1 段 `human`:本机人类,写进调用者自己的 Team 日志。
|
|
765
|
+
if (input.to === HUMAN_PRINCIPAL) {
|
|
766
|
+
return this.deliverLocalAddress(
|
|
767
|
+
caller,
|
|
768
|
+
{ kind: 'local_human' },
|
|
769
|
+
input.to,
|
|
770
|
+
content,
|
|
771
|
+
conversationId,
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const visible = await this.listVisible(caller.id);
|
|
776
|
+
if (!visible.some((status) => status.id === caller.id)) visible.push(caller);
|
|
777
|
+
const resolved = await this.resolveSendTarget(caller, input.to, visible);
|
|
778
|
+
if (!resolved.ok) return resolved.result;
|
|
779
|
+
const target = resolved.target;
|
|
780
|
+
|
|
781
|
+
// 目标已知后按 target team 重新判断是否可继承调用者 session 的会话(跨 team 不继承)。
|
|
782
|
+
if (input.conversation_id === undefined) {
|
|
783
|
+
conversationId = this.resolveConversationId(
|
|
784
|
+
undefined,
|
|
785
|
+
input.from_session_id,
|
|
786
|
+
caller.team_id,
|
|
787
|
+
target?.team_id ?? caller.team_id,
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// Team 日志对 team 可见:private roster 成员不能作为 send 目标,直接拒绝。
|
|
792
|
+
const targetStatus =
|
|
793
|
+
target === undefined ? undefined : visible.find((status) => status.id === target.agent_id);
|
|
794
|
+
if (targetStatus !== undefined && isPrivateRosterMember(targetStatus)) {
|
|
795
|
+
return {
|
|
796
|
+
status: 'error',
|
|
797
|
+
code: 'team_private_member',
|
|
798
|
+
reason: `team_private_member: ${targetStatus.id}`,
|
|
799
|
+
logged: false,
|
|
800
|
+
conversation_id: conversationId,
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// 裸名未命中本队 roster 时只能跨 team / 跨节点升级解析;那条路径不携带
|
|
805
|
+
// 三档语义,urgent / wake 一旦放过去会在升级后静默降级成普通投递,直接拒绝。
|
|
806
|
+
if (caller.team_id !== undefined && target === undefined && (interrupt || wakes)) {
|
|
807
|
+
return {
|
|
808
|
+
status: 'rejected',
|
|
809
|
+
code: 'invalid_input',
|
|
810
|
+
reason: 'unsupported_delivery',
|
|
811
|
+
logged: false,
|
|
812
|
+
conversation_id: conversationId,
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// 有 Team 的调用者:name 只在同 Team roster 内解析;未命中不得把原始 name
|
|
817
|
+
// 交给 tenant 全局 dispatch(否则会绕过 roster 解析到别的 Team)。
|
|
818
|
+
if (caller.team_id !== undefined && target === undefined) {
|
|
819
|
+
// 块 P2:裸名升级路可能跨节点(federation 携带不了 node-local refs)——
|
|
820
|
+
// 带 refs 时要求显式本机成员 id,不静默丢附件。
|
|
821
|
+
if (refs.length > 0) {
|
|
822
|
+
return {
|
|
823
|
+
status: 'error',
|
|
824
|
+
code: 'invalid_input',
|
|
825
|
+
reason: 'refs require a resolved local member id (bare-name escalation may cross nodes)',
|
|
826
|
+
logged: false,
|
|
827
|
+
conversation_id: conversationId,
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
// 1 段裸名的查找阶梯:本 Team(上面已查)→ 本机其它 Team → 可访问节点。
|
|
831
|
+
const escalated = await this.resolveBareAgent(caller, input.to, content, conversationId);
|
|
832
|
+
if (escalated !== undefined) return escalated;
|
|
833
|
+
return {
|
|
834
|
+
status: 'error',
|
|
835
|
+
code: 'unknown_member',
|
|
836
|
+
reason: `unknown_member: ${input.to}`,
|
|
837
|
+
logged: false,
|
|
838
|
+
conversation_id: conversationId,
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
let logged = false;
|
|
843
|
+
// private 调用者同样不得写 Team 日志(消息本身仍可 dispatch,只是不留痕)。
|
|
844
|
+
// wake 投递只做 inbox 通知,不写 team mention 日志。
|
|
845
|
+
if (
|
|
846
|
+
!wakes &&
|
|
847
|
+
target !== undefined &&
|
|
848
|
+
caller.team_id !== undefined &&
|
|
849
|
+
target.team_id === caller.team_id &&
|
|
850
|
+
!isPrivateRosterMember(caller)
|
|
851
|
+
) {
|
|
852
|
+
const entry: TeamLogEntry = {
|
|
853
|
+
message_id: this.newId(),
|
|
854
|
+
team_id: caller.team_id,
|
|
855
|
+
from: caller.id,
|
|
856
|
+
to: [target.agent_id],
|
|
857
|
+
mentions: [target.agent_id],
|
|
858
|
+
content,
|
|
859
|
+
ts: this.now(),
|
|
860
|
+
kind: 'mention',
|
|
861
|
+
conversation_id: conversationId,
|
|
862
|
+
// 块 P2 additive:引用随日志(时间线 chip 与 post 同口径);无引用不写键。
|
|
863
|
+
...(refs.length > 0 ? { refs } : {}),
|
|
864
|
+
};
|
|
865
|
+
try {
|
|
866
|
+
await this.store.appendLog(entry);
|
|
867
|
+
} catch (error) {
|
|
868
|
+
return {
|
|
869
|
+
status: 'error',
|
|
870
|
+
code: 'team_log_write_failed',
|
|
871
|
+
reason: errorText(error),
|
|
872
|
+
logged: false,
|
|
873
|
+
conversation_id: conversationId,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
logged = true;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
try {
|
|
880
|
+
const result = await this.agent.dispatch({
|
|
881
|
+
to: target?.agent_id ?? input.to,
|
|
882
|
+
content,
|
|
883
|
+
from: caller.id,
|
|
884
|
+
conversation_id: conversationId,
|
|
885
|
+
...(interrupt ? { interrupt: true } : {}),
|
|
886
|
+
// wire 边界:dispatch 只认 `notify` 布尔,wake 模式在这里转回去。
|
|
887
|
+
...(wakes ? { notify: true } : {}),
|
|
888
|
+
...(messageId !== undefined ? { message_id: messageId } : {}),
|
|
889
|
+
// 块 P2 additive:引用随投递(wake 落 inbox / input 进 Message.refs,dispatch 既有两路)。
|
|
890
|
+
...(refs.length > 0 ? { refs } : {}),
|
|
891
|
+
// 内部(非 wire):调用者 session / run 供 conversation 继承与同 run 边去重;
|
|
892
|
+
// batch_key 让一次 messages 数组的 wake 投递共享边计数。
|
|
893
|
+
origin_session_id: input.origin_session_id ?? input.from_session_id,
|
|
894
|
+
...(input.origin_run_id !== undefined ? { origin_run_id: input.origin_run_id } : {}),
|
|
895
|
+
...(input.batch_key !== undefined ? { batch_key: input.batch_key } : {}),
|
|
896
|
+
});
|
|
897
|
+
if (result.status === 'queued') {
|
|
898
|
+
return {
|
|
899
|
+
status: 'queued',
|
|
900
|
+
resolved_to: result.resolved_to,
|
|
901
|
+
message_id: result.message_id,
|
|
902
|
+
resolution: result.resolution,
|
|
903
|
+
logged,
|
|
904
|
+
conversation_id: conversationId,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
if (result.status === 'notified') {
|
|
908
|
+
// wake 模式直接返回 SendResult(契约 §2.6:状态名仍是 notified);不混入
|
|
909
|
+
// TeamAgentSendResult 字段。
|
|
910
|
+
return {
|
|
911
|
+
queued: false,
|
|
912
|
+
notified: true,
|
|
913
|
+
message_id: result.message_id,
|
|
914
|
+
resolution: result.resolution,
|
|
915
|
+
wake: result.wake,
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
return {
|
|
919
|
+
status: 'rejected',
|
|
920
|
+
...(target !== undefined ? { resolved_to: target.agent_id } : {}),
|
|
921
|
+
code: result.code,
|
|
922
|
+
reason: result.reason,
|
|
923
|
+
logged,
|
|
924
|
+
conversation_id: conversationId,
|
|
925
|
+
};
|
|
926
|
+
} catch (error) {
|
|
927
|
+
return {
|
|
928
|
+
status: 'error',
|
|
929
|
+
...(target !== undefined ? { resolved_to: target.agent_id } : {}),
|
|
930
|
+
code: errorCode(error) ?? 'invalid_input',
|
|
931
|
+
reason: errorText(error),
|
|
932
|
+
logged,
|
|
933
|
+
conversation_id: conversationId,
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
subscribe(listener: (event: TeamServiceEvent) => void): () => void {
|
|
939
|
+
if (this.disposed) return () => undefined;
|
|
940
|
+
this.listeners.add(listener);
|
|
941
|
+
return () => {
|
|
942
|
+
this.listeners.delete(listener);
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
dispose(): void {
|
|
947
|
+
if (this.disposed) return;
|
|
948
|
+
this.disposed = true;
|
|
949
|
+
this.listeners.clear();
|
|
950
|
+
this.retiredBodies.clear();
|
|
951
|
+
this.unsubscribe();
|
|
952
|
+
this.unsubscribeRuns?.();
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* 指针事件:只带 team_id / kind / message_id,绝不含正文。
|
|
957
|
+
* 监听者异常被隔离,不影响日志与生命周期。
|
|
958
|
+
*/
|
|
959
|
+
private emit(event: TeamServiceEvent): void {
|
|
960
|
+
if (this.disposed) return;
|
|
961
|
+
for (const listener of [...this.listeners]) {
|
|
962
|
+
try {
|
|
963
|
+
listener(event);
|
|
964
|
+
} catch (error) {
|
|
965
|
+
this.logger.warn('team.event.listener_failed', {
|
|
966
|
+
team_id: event.team_id,
|
|
967
|
+
kind: event.kind,
|
|
968
|
+
error: errorText(error),
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
private async listVisible(viewer?: string): Promise<MemberStatus[]> {
|
|
975
|
+
return viewer === undefined ? this.agent.list() : this.agent.list({ viewer });
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/** S10.3:create / update 的摘要计数从 roster 派生(新 Team = 0 / 0)。 */
|
|
979
|
+
private async summarize(record: TeamRecord): Promise<TeamSummary> {
|
|
980
|
+
const members = await this.rosterFor(record.team_id);
|
|
981
|
+
return toTeamSummary(
|
|
982
|
+
record,
|
|
983
|
+
members.length,
|
|
984
|
+
members.filter((member) => member.presence === 'live').length,
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* 显式 id 先校验;缺省优先按调用者 session 继承当前 turn,否则生成。
|
|
990
|
+
*
|
|
991
|
+
* 0.41:继承必须按 session 精确定位(multi-live 时不回退 agent 级);跨 team
|
|
992
|
+
* 不继承(两边都 undefined 视为相同)。
|
|
993
|
+
*/
|
|
994
|
+
private resolveConversationId(
|
|
995
|
+
value: string | undefined,
|
|
996
|
+
inheritFromSession?: string,
|
|
997
|
+
callerTeamId?: string,
|
|
998
|
+
targetTeamId?: string,
|
|
999
|
+
): string {
|
|
1000
|
+
if (value !== undefined) {
|
|
1001
|
+
if (!isValidConversationId(value)) {
|
|
1002
|
+
throw new TeamError('invalid_input', 'invalid conversation_id');
|
|
1003
|
+
}
|
|
1004
|
+
return value;
|
|
1005
|
+
}
|
|
1006
|
+
if (inheritFromSession !== undefined && callerTeamId === targetTeamId) {
|
|
1007
|
+
const inherited = this.agent.currentConversation(inheritFromSession);
|
|
1008
|
+
if (inherited !== undefined) return inherited;
|
|
1009
|
+
}
|
|
1010
|
+
return generateConversationId(this.newId);
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* 唯一 roster 排序来源(DECISION-038 §2.3):返回**已排序**的完整 present roster。
|
|
1015
|
+
* `get` 的窗口、`roster`、`listForCaller` 与 federation team-info 都复用此顺序,
|
|
1016
|
+
* 不得在别处再排序。
|
|
1017
|
+
*/
|
|
1018
|
+
private async rosterFor(teamId: string, viewer?: string): Promise<TeamMemberSummary[]> {
|
|
1019
|
+
const statuses = await this.listVisible(viewer);
|
|
1020
|
+
return statuses
|
|
1021
|
+
.filter((status) => status.team_id === teamId && status.membership === 'present')
|
|
1022
|
+
.map(toMemberSummary)
|
|
1023
|
+
.sort(compareRoster);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/**
|
|
1027
|
+
* 裸 agent 名的查找阶梯(0.27):本 Team 已查过 → 本机其它 Team → 可访问节点。
|
|
1028
|
+
*
|
|
1029
|
+
* 返回 `undefined` 表示**继续按「查完了确实没有」处理**;返回结果表示已经给出
|
|
1030
|
+
* 明确答复(投递成功、歧义、超时)。
|
|
1031
|
+
*
|
|
1032
|
+
* 跨 team 重名不能静默择一:调用方要用完整地址 `<agent>@<team>` 精确指定,
|
|
1033
|
+
* 所以重名一律报错并列出候选。
|
|
1034
|
+
*/
|
|
1035
|
+
private async resolveBareAgent(
|
|
1036
|
+
caller: MemberStatus,
|
|
1037
|
+
to: string,
|
|
1038
|
+
content: string,
|
|
1039
|
+
conversationId: string,
|
|
1040
|
+
): Promise<TeamAgentSendResult | undefined> {
|
|
1041
|
+
const localTeams = this.store
|
|
1042
|
+
.list()
|
|
1043
|
+
.filter((record) => record.team_id !== caller.team_id && record.archived_at === undefined);
|
|
1044
|
+
|
|
1045
|
+
const localMatches: { teamId: string; agentId: string }[] = [];
|
|
1046
|
+
for (const record of localTeams) {
|
|
1047
|
+
const roster = await this.rosterFor(record.team_id, caller.id);
|
|
1048
|
+
const hit = roster.find(
|
|
1049
|
+
(member) => member.agent_id === to || member.session_id === to || member.name === to,
|
|
1050
|
+
);
|
|
1051
|
+
if (hit !== undefined) localMatches.push({ teamId: record.team_id, agentId: hit.agent_id });
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
if (localMatches.length > 1) {
|
|
1055
|
+
const candidates = localMatches
|
|
1056
|
+
.map((match) => `${to}@${match.teamId}`)
|
|
1057
|
+
.sort()
|
|
1058
|
+
.join(', ');
|
|
1059
|
+
return {
|
|
1060
|
+
status: 'error',
|
|
1061
|
+
code: 'ambiguous_member',
|
|
1062
|
+
reason: `ambiguous name: ${to}; use one of: ${candidates}`,
|
|
1063
|
+
logged: false,
|
|
1064
|
+
conversation_id: conversationId,
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
const [local] = localMatches;
|
|
1069
|
+
if (local !== undefined) {
|
|
1070
|
+
return this.deliverLocalAddress(
|
|
1071
|
+
caller,
|
|
1072
|
+
{ kind: 'local_member', principal: local.agentId, team_id: local.teamId },
|
|
1073
|
+
`${local.agentId}@${local.teamId}`,
|
|
1074
|
+
content,
|
|
1075
|
+
conversationId,
|
|
1076
|
+
);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
const federation = this.federation;
|
|
1080
|
+
if (federation === undefined) return undefined;
|
|
1081
|
+
|
|
1082
|
+
const found = await federation.lookup(to);
|
|
1083
|
+
if (found.candidates.length > 1) {
|
|
1084
|
+
const candidates = found.candidates
|
|
1085
|
+
.map((candidate) => candidate.address)
|
|
1086
|
+
.sort()
|
|
1087
|
+
.join(', ');
|
|
1088
|
+
return {
|
|
1089
|
+
status: 'error',
|
|
1090
|
+
code: 'ambiguous_member',
|
|
1091
|
+
reason: `ambiguous name: ${to}; use one of: ${candidates}`,
|
|
1092
|
+
logged: false,
|
|
1093
|
+
conversation_id: conversationId,
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
const [remote] = found.candidates;
|
|
1097
|
+
if (remote !== undefined) {
|
|
1098
|
+
return this.sendAddress(caller, remote.address, content, conversationId);
|
|
1099
|
+
}
|
|
1100
|
+
// 没查完就不能说「不存在」:离线 peer 会被误报成查无此人。
|
|
1101
|
+
if (found.timedOut) {
|
|
1102
|
+
return {
|
|
1103
|
+
status: 'error',
|
|
1104
|
+
code: 'lookup_timeout',
|
|
1105
|
+
reason: `could not finish looking up "${to}" within the lookup budget`,
|
|
1106
|
+
logged: false,
|
|
1107
|
+
conversation_id: conversationId,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
return undefined;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* 三段地址 `<principal>@<node>:<team>`(0.21 / 0.27)。
|
|
1115
|
+
*
|
|
1116
|
+
* **先问 port 指向哪里**:node 段命中本机时走本机投递(`deliverLocalAddress`),
|
|
1117
|
+
* 绝不出网;只有 `remote` 才发请求。这样模型照抄来源行里的
|
|
1118
|
+
* `<principal>@<本机 nodeId>:<team>` 也能送达,而不是绕一圈被自己拒绝。
|
|
1119
|
+
*
|
|
1120
|
+
* 前置失败一律不发请求;`from` 由运行时按调用者身份构造,模型不能伪造。
|
|
1121
|
+
* 跨节点发送不写本地 Team 日志(`logged:false`),对端负责落日志。
|
|
1122
|
+
*/
|
|
1123
|
+
private async sendAddress(
|
|
1124
|
+
caller: MemberStatus,
|
|
1125
|
+
to: string,
|
|
1126
|
+
content: string,
|
|
1127
|
+
conversationId: string,
|
|
1128
|
+
): Promise<TeamAgentSendResult> {
|
|
1129
|
+
const guard = this.addressCallerGuard(caller, conversationId);
|
|
1130
|
+
if (guard !== undefined) return guard;
|
|
1131
|
+
|
|
1132
|
+
const federation = this.federation;
|
|
1133
|
+
if (federation === undefined) {
|
|
1134
|
+
return {
|
|
1135
|
+
status: 'error',
|
|
1136
|
+
code: 'federation_unavailable',
|
|
1137
|
+
reason: 'federation_unavailable',
|
|
1138
|
+
logged: false,
|
|
1139
|
+
conversation_id: conversationId,
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
const placement = federation.resolve(to);
|
|
1144
|
+
if (placement.kind === 'invalid') {
|
|
1145
|
+
return {
|
|
1146
|
+
status: 'error',
|
|
1147
|
+
code: placement.code,
|
|
1148
|
+
reason: placement.reason,
|
|
1149
|
+
logged: false,
|
|
1150
|
+
conversation_id: conversationId,
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
if (placement.kind !== 'remote') {
|
|
1154
|
+
return this.deliverLocalAddress(caller, placement, to, content, conversationId);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
const result = await federation.send({
|
|
1158
|
+
from: `${caller.name}@${federation.nodeId}:${caller.team_id}`,
|
|
1159
|
+
to,
|
|
1160
|
+
content,
|
|
1161
|
+
conversation_id: conversationId,
|
|
1162
|
+
});
|
|
1163
|
+
if (result.status === 'queued') {
|
|
1164
|
+
return {
|
|
1165
|
+
status: 'queued',
|
|
1166
|
+
resolved_to: to,
|
|
1167
|
+
message_id: result.message_id,
|
|
1168
|
+
logged: false,
|
|
1169
|
+
conversation_id: conversationId,
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
return {
|
|
1173
|
+
status: result.status,
|
|
1174
|
+
code: result.code,
|
|
1175
|
+
reason: result.reason,
|
|
1176
|
+
logged: false,
|
|
1177
|
+
conversation_id: conversationId,
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/**
|
|
1182
|
+
* 两段地址 `<agent>@<team>`:node 恒为本机,直接本机投递。
|
|
1183
|
+
*
|
|
1184
|
+
* 拆成 principal + team,不走 port —— 两段形态不需要判定「是不是本机」。
|
|
1185
|
+
*/
|
|
1186
|
+
private async sendLocalAddress(
|
|
1187
|
+
caller: MemberStatus,
|
|
1188
|
+
to: string,
|
|
1189
|
+
content: string,
|
|
1190
|
+
conversationId: string,
|
|
1191
|
+
): Promise<TeamAgentSendResult> {
|
|
1192
|
+
const guard = this.addressCallerGuard(caller, conversationId);
|
|
1193
|
+
if (guard !== undefined) return guard;
|
|
1194
|
+
|
|
1195
|
+
const at = to.indexOf('@');
|
|
1196
|
+
const principal = to.slice(0, at);
|
|
1197
|
+
const teamId = to.slice(at + 1);
|
|
1198
|
+
// `human@<team>` 是同一条地址规则的 human 形态,不是名叫 human 的成员。
|
|
1199
|
+
if (principal === HUMAN_PRINCIPAL) {
|
|
1200
|
+
return this.deliverLocalAddress(
|
|
1201
|
+
caller,
|
|
1202
|
+
{ kind: 'local_human', team_id: teamId },
|
|
1203
|
+
to,
|
|
1204
|
+
content,
|
|
1205
|
+
conversationId,
|
|
1206
|
+
);
|
|
1207
|
+
}
|
|
1208
|
+
return this.deliverLocalAddress(
|
|
1209
|
+
caller,
|
|
1210
|
+
{ kind: 'local_member', principal, team_id: teamId },
|
|
1211
|
+
to,
|
|
1212
|
+
content,
|
|
1213
|
+
conversationId,
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/** 发送者前置条件:left 不能发;没有 Team / 名字则构造不出 `from`。 */
|
|
1218
|
+
private addressCallerGuard(
|
|
1219
|
+
caller: MemberStatus,
|
|
1220
|
+
conversationId: string,
|
|
1221
|
+
): TeamAgentSendResult | undefined {
|
|
1222
|
+
if (caller.membership === 'left') {
|
|
1223
|
+
return {
|
|
1224
|
+
status: 'error',
|
|
1225
|
+
code: 'member_left',
|
|
1226
|
+
reason: `member_left: ${caller.id}`,
|
|
1227
|
+
logged: false,
|
|
1228
|
+
conversation_id: conversationId,
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
if (caller.team_id === undefined) {
|
|
1232
|
+
return {
|
|
1233
|
+
status: 'error',
|
|
1234
|
+
code: 'no_team',
|
|
1235
|
+
reason: 'no_team',
|
|
1236
|
+
logged: false,
|
|
1237
|
+
conversation_id: conversationId,
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
if (caller.name === undefined) {
|
|
1241
|
+
return {
|
|
1242
|
+
status: 'error',
|
|
1243
|
+
code: 'no_name',
|
|
1244
|
+
reason: 'no_name',
|
|
1245
|
+
logged: false,
|
|
1246
|
+
conversation_id: conversationId,
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
return undefined;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* 本机地址投递:`human` 只写 Team 日志(零 run);成员在目标 Team 内按
|
|
1254
|
+
* id / session / name 唯一命中后写 mention 日志并 dispatch 一次。
|
|
1255
|
+
*
|
|
1256
|
+
* **复用 `post()`**:它已经是「校验 roster → 写日志 → dispatch」的唯一实现,
|
|
1257
|
+
* 这里只多做一件事 —— 把地址里的 principal 解析成 agent id。node 段在这条路径上
|
|
1258
|
+
* 没有意义(已经是本机了),所以 2 段与命中本机的 3 段共用这里。
|
|
1259
|
+
*/
|
|
1260
|
+
private async deliverLocalAddress(
|
|
1261
|
+
caller: MemberStatus,
|
|
1262
|
+
placement: {
|
|
1263
|
+
kind: 'local_human' | 'local_member';
|
|
1264
|
+
principal?: string;
|
|
1265
|
+
team_id?: string;
|
|
1266
|
+
},
|
|
1267
|
+
to: string,
|
|
1268
|
+
content: string,
|
|
1269
|
+
conversationId: string,
|
|
1270
|
+
): Promise<TeamAgentSendResult> {
|
|
1271
|
+
const teamId = placement.team_id ?? caller.team_id;
|
|
1272
|
+
if (teamId === undefined) {
|
|
1273
|
+
return {
|
|
1274
|
+
status: 'error',
|
|
1275
|
+
code: 'no_team',
|
|
1276
|
+
reason: 'local address needs a team segment or a team-bound sender',
|
|
1277
|
+
logged: false,
|
|
1278
|
+
conversation_id: conversationId,
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
// 地址里的 team 段写错必须报 team_not_found,不能退化成 unknown_member:
|
|
1282
|
+
// 前者是「Team 不存在」,后者会让人去查成员名,排查方向相反。
|
|
1283
|
+
if (this.store.get(teamId) === undefined) {
|
|
1284
|
+
return {
|
|
1285
|
+
status: 'error',
|
|
1286
|
+
code: 'team_not_found',
|
|
1287
|
+
reason: `team_not_found: ${teamId}`,
|
|
1288
|
+
logged: false,
|
|
1289
|
+
conversation_id: conversationId,
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// `human`:只写日志、不唤醒成员(与跨节点入站的 human 分支同形)。
|
|
1294
|
+
if (placement.kind === 'local_human') {
|
|
1295
|
+
try {
|
|
1296
|
+
await this.post({
|
|
1297
|
+
team_id: teamId,
|
|
1298
|
+
content,
|
|
1299
|
+
from: caller.id,
|
|
1300
|
+
to: [HUMAN_PRINCIPAL],
|
|
1301
|
+
conversation_id: conversationId,
|
|
1302
|
+
});
|
|
1303
|
+
} catch (error) {
|
|
1304
|
+
return {
|
|
1305
|
+
status: 'error',
|
|
1306
|
+
code: errorCode(error) ?? 'team_log_write_failed',
|
|
1307
|
+
reason: errorText(error),
|
|
1308
|
+
logged: false,
|
|
1309
|
+
conversation_id: conversationId,
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
return {
|
|
1313
|
+
status: 'queued',
|
|
1314
|
+
resolved_to: HUMAN_PRINCIPAL,
|
|
1315
|
+
logged: true,
|
|
1316
|
+
conversation_id: conversationId,
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
const principal = placement.principal ?? to;
|
|
1321
|
+
let targetId: string;
|
|
1322
|
+
try {
|
|
1323
|
+
targetId = await this.resolveAddressMember(teamId, caller.id, principal);
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
return {
|
|
1326
|
+
status: 'error',
|
|
1327
|
+
code: errorCode(error) ?? 'unknown_member',
|
|
1328
|
+
reason: errorText(error),
|
|
1329
|
+
logged: false,
|
|
1330
|
+
conversation_id: conversationId,
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
let posted: TeamPostResult;
|
|
1335
|
+
try {
|
|
1336
|
+
posted = await this.post({
|
|
1337
|
+
team_id: teamId,
|
|
1338
|
+
content,
|
|
1339
|
+
from: caller.id,
|
|
1340
|
+
mentions: [targetId],
|
|
1341
|
+
conversation_id: conversationId,
|
|
1342
|
+
});
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
return {
|
|
1345
|
+
status: 'error',
|
|
1346
|
+
code: errorCode(error) ?? 'team_log_write_failed',
|
|
1347
|
+
reason: errorText(error),
|
|
1348
|
+
logged: false,
|
|
1349
|
+
conversation_id: conversationId,
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
const [delivery] = posted.delivered;
|
|
1354
|
+
if (delivery === undefined) {
|
|
1355
|
+
return {
|
|
1356
|
+
status: 'queued',
|
|
1357
|
+
resolved_to: targetId,
|
|
1358
|
+
message_id: posted.message_id,
|
|
1359
|
+
logged: true,
|
|
1360
|
+
conversation_id: conversationId,
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
if (delivery.status === 'queued') {
|
|
1364
|
+
return {
|
|
1365
|
+
status: 'queued',
|
|
1366
|
+
resolved_to: targetId,
|
|
1367
|
+
...(delivery.message_id !== undefined ? { message_id: delivery.message_id } : {}),
|
|
1368
|
+
...(delivery.resolution !== undefined ? { resolution: delivery.resolution } : {}),
|
|
1369
|
+
logged: true,
|
|
1370
|
+
conversation_id: conversationId,
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
return {
|
|
1374
|
+
status: delivery.status === 'rejected' ? 'rejected' : 'error',
|
|
1375
|
+
resolved_to: targetId,
|
|
1376
|
+
...(delivery.code !== undefined ? { code: delivery.code } : {}),
|
|
1377
|
+
...(delivery.reason !== undefined ? { reason: delivery.reason } : {}),
|
|
1378
|
+
logged: true,
|
|
1379
|
+
conversation_id: conversationId,
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
/**
|
|
1384
|
+
* 目标 Team 内按 id / session 精确匹配,再按 name 唯一匹配。
|
|
1385
|
+
*
|
|
1386
|
+
* **只看目标 Team 的 present roster**:地址里的 team 段决定作用域,不能退回
|
|
1387
|
+
* tenant 全局查找,否则 `alice@team-b` 会打到 `team-a` 里的同名成员。
|
|
1388
|
+
*/
|
|
1389
|
+
private async resolveAddressMember(
|
|
1390
|
+
teamId: string,
|
|
1391
|
+
viewer: string,
|
|
1392
|
+
principal: string,
|
|
1393
|
+
): Promise<string> {
|
|
1394
|
+
const roster = await this.rosterFor(teamId, viewer);
|
|
1395
|
+
const exact = roster.find(
|
|
1396
|
+
(member) => member.agent_id === principal || member.session_id === principal,
|
|
1397
|
+
);
|
|
1398
|
+
if (exact !== undefined) return exact.agent_id;
|
|
1399
|
+
|
|
1400
|
+
const byName = roster.filter((member) => member.name === principal);
|
|
1401
|
+
if (byName.length === 1) {
|
|
1402
|
+
const [match] = byName;
|
|
1403
|
+
if (match !== undefined) return match.agent_id;
|
|
1404
|
+
}
|
|
1405
|
+
if (byName.length > 1) {
|
|
1406
|
+
throw new TeamError('invalid_input', `ambiguous name: ${principal}`);
|
|
1407
|
+
}
|
|
1408
|
+
throw new TeamError('unknown_member', `unknown_member: ${principal}`);
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/** send 的 to 解析:id / 当前 session 精确匹配优先,其次按调用者可见范围解析 name */
|
|
1412
|
+
private async resolveSendTarget(
|
|
1413
|
+
caller: MemberStatus,
|
|
1414
|
+
to: string,
|
|
1415
|
+
visible: MemberStatus[],
|
|
1416
|
+
): Promise<ResolvedSendTarget> {
|
|
1417
|
+
const exact = visible.find((status) => status.id === to || status.session_id === to);
|
|
1418
|
+
if (exact !== undefined) {
|
|
1419
|
+
return {
|
|
1420
|
+
ok: true,
|
|
1421
|
+
target: {
|
|
1422
|
+
agent_id: exact.id,
|
|
1423
|
+
...(exact.team_id !== undefined ? { team_id: exact.team_id } : {}),
|
|
1424
|
+
},
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// 有 Team 时 name 只在同 Team present roster 内解析;无 Team 用自己可见成员。
|
|
1429
|
+
let pool: NamedSendTarget[];
|
|
1430
|
+
if (caller.team_id !== undefined) {
|
|
1431
|
+
const roster = await this.rosterFor(caller.team_id, caller.id);
|
|
1432
|
+
pool = roster.map((member) => ({
|
|
1433
|
+
agent_id: member.agent_id,
|
|
1434
|
+
team_id: caller.team_id,
|
|
1435
|
+
...(member.name !== undefined ? { name: member.name } : {}),
|
|
1436
|
+
}));
|
|
1437
|
+
} else {
|
|
1438
|
+
pool = visible.map((status) => ({
|
|
1439
|
+
agent_id: status.id,
|
|
1440
|
+
...(status.team_id !== undefined ? { team_id: status.team_id } : {}),
|
|
1441
|
+
...(status.name !== undefined ? { name: status.name } : {}),
|
|
1442
|
+
}));
|
|
1443
|
+
}
|
|
1444
|
+
const matches = pool.filter((member) => member.name === to);
|
|
1445
|
+
if (matches.length > 1) {
|
|
1446
|
+
return {
|
|
1447
|
+
ok: false,
|
|
1448
|
+
result: {
|
|
1449
|
+
status: 'error',
|
|
1450
|
+
code: 'invalid_input',
|
|
1451
|
+
reason: 'ambiguous name',
|
|
1452
|
+
logged: false,
|
|
1453
|
+
},
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
const match = matches[0];
|
|
1457
|
+
return {
|
|
1458
|
+
ok: true,
|
|
1459
|
+
...(match !== undefined
|
|
1460
|
+
? {
|
|
1461
|
+
target: {
|
|
1462
|
+
agent_id: match.agent_id,
|
|
1463
|
+
...(match.team_id !== undefined ? { team_id: match.team_id } : {}),
|
|
1464
|
+
},
|
|
1465
|
+
}
|
|
1466
|
+
: {}),
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
private async dispatchMention(
|
|
1471
|
+
targetId: string,
|
|
1472
|
+
content: string,
|
|
1473
|
+
from: string,
|
|
1474
|
+
conversationId: string,
|
|
1475
|
+
originTeamId?: string,
|
|
1476
|
+
refs: readonly MessageRef[] = [],
|
|
1477
|
+
teamMessageId?: string,
|
|
1478
|
+
triggeredBy?: RunTrigger,
|
|
1479
|
+
): Promise<TeamDelivery> {
|
|
1480
|
+
try {
|
|
1481
|
+
const result = await this.agent.dispatch({
|
|
1482
|
+
to: targetId,
|
|
1483
|
+
content,
|
|
1484
|
+
from,
|
|
1485
|
+
conversation_id: conversationId,
|
|
1486
|
+
// 引用随投递进 admit → core `Message.refs`;没有引用时字段整个不出现
|
|
1487
|
+
//(等价 `refs = []`),旧路径的 payload 一字不变。
|
|
1488
|
+
...(refs.length > 0 ? { refs: [...refs] } : {}),
|
|
1489
|
+
...(originTeamId !== undefined ? { origin_team_id: originTeamId } : {}),
|
|
1490
|
+
// team 日志关联随投递落 inbox:编辑 / 删除这条 team 消息时按它级联消费副本。
|
|
1491
|
+
...(teamMessageId !== undefined ? { team_message_id: teamMessageId } : {}),
|
|
1492
|
+
// q-error-e3 §3.7:teams.post RPC correlation(缺省不写键,逐字节不变)。
|
|
1493
|
+
...(triggeredBy !== undefined ? { triggered_by: triggeredBy } : {}),
|
|
1494
|
+
});
|
|
1495
|
+
if (result.status === 'queued') {
|
|
1496
|
+
return {
|
|
1497
|
+
agent_id: targetId,
|
|
1498
|
+
status: 'queued',
|
|
1499
|
+
message_id: result.message_id,
|
|
1500
|
+
resolution: result.resolution,
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
if (result.status === 'rejected') {
|
|
1504
|
+
return {
|
|
1505
|
+
agent_id: targetId,
|
|
1506
|
+
status: 'rejected',
|
|
1507
|
+
code: result.code,
|
|
1508
|
+
reason: result.reason,
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
// 这条路径恒为 input 投递(不传 notify),dispatch 不可能返回 notified;
|
|
1512
|
+
// 显式标记不可达以完成收窄。
|
|
1513
|
+
throw new Error('unreachable: dispatchMention does not send notify');
|
|
1514
|
+
} catch (error) {
|
|
1515
|
+
return {
|
|
1516
|
+
agent_id: targetId,
|
|
1517
|
+
status: 'error',
|
|
1518
|
+
code: errorCode(error) ?? 'invalid_input',
|
|
1519
|
+
reason: errorText(error),
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/** system 消息:只写日志、不 dispatch;失败只 warning(不改变生命周期) */
|
|
1525
|
+
private onAgentEvent(event: AgentEvent): void {
|
|
1526
|
+
// 0.27:先记账(早于下面所有 early return)——private / unbound 成员的退役、
|
|
1527
|
+
// 关闭同样要抑制其旧 Binding 的 run.* 终态。
|
|
1528
|
+
this.noteBindingLifecycle(event);
|
|
1529
|
+
|
|
1530
|
+
// Team log is team-visible. Private members (internal workers) must not leak
|
|
1531
|
+
// id / name / reply into the team log. Fail closed for unknown visibility.
|
|
1532
|
+
if (event.visibility !== 'team' && event.visibility !== 'tenant') return;
|
|
1533
|
+
|
|
1534
|
+
const teamId = event.team_id;
|
|
1535
|
+
if (teamId === undefined || teamId.length === 0) return;
|
|
1536
|
+
|
|
1537
|
+
const systemEvent = this.systemEventFor(event);
|
|
1538
|
+
if (systemEvent === undefined) return;
|
|
1539
|
+
// join 的 from 记录“谁招的”:agent.spawned 带 spawned_by 时用它,否则保持 system。
|
|
1540
|
+
const from =
|
|
1541
|
+
event.type === 'agent.spawned' &&
|
|
1542
|
+
typeof event.spawned_by === 'string' &&
|
|
1543
|
+
event.spawned_by.length > 0
|
|
1544
|
+
? event.spawned_by
|
|
1545
|
+
: 'system';
|
|
1546
|
+
this.writeSystemLog({
|
|
1547
|
+
teamId,
|
|
1548
|
+
from,
|
|
1549
|
+
to: [event.agent_id],
|
|
1550
|
+
content: SYSTEM_CONTENT[systemEvent],
|
|
1551
|
+
systemEvent,
|
|
1552
|
+
eventType: event.type,
|
|
1553
|
+
agentId: event.agent_id,
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/**
|
|
1558
|
+
* 0.27:Binding 退役 / 成员关闭记账(`agent.*` 管道)。
|
|
1559
|
+
*
|
|
1560
|
+
* 只维护 `(agent_id, session_id)` 集合;不写日志、不改变生命周期。
|
|
1561
|
+
* 放在 `onAgentEvent` 所有 early return 之前:private / unbound 成员的
|
|
1562
|
+
* 旧 Binding 同样要抑制终态。
|
|
1563
|
+
*/
|
|
1564
|
+
private noteBindingLifecycle(event: AgentEvent): void {
|
|
1565
|
+
switch (event.type) {
|
|
1566
|
+
case 'agent.retired':
|
|
1567
|
+
if (event.session_id !== undefined && event.session_id.length > 0) {
|
|
1568
|
+
// B′(0.52):只认「退役时在途的那一轮」,交棒轮因此不被 fence。
|
|
1569
|
+
this.markRetiredBinding(event.agent_id, event.session_id, event.retired_during_run_id);
|
|
1570
|
+
}
|
|
1571
|
+
return;
|
|
1572
|
+
case 'agent.closed':
|
|
1573
|
+
// close 关掉该成员的全部 Binding,逐条记账(不用通配键:复活时无法逐条撤销)。
|
|
1574
|
+
if (event.session_id !== undefined && event.session_id.length > 0) {
|
|
1575
|
+
this.markRetiredBinding(event.agent_id, event.session_id);
|
|
1576
|
+
}
|
|
1577
|
+
return;
|
|
1578
|
+
case 'agent.rejoined':
|
|
1579
|
+
// reinstate 把 close 置 closing 的 live Binding 放回可跑:撤销该 Binding 的记账,
|
|
1580
|
+
// 否则复活后的正常轮会被误判成旧 Binding。
|
|
1581
|
+
if (event.session_id !== undefined && event.session_id.length > 0) {
|
|
1582
|
+
this.retiredBodies.delete(retiredBindingKey(event.agent_id, event.session_id));
|
|
1583
|
+
}
|
|
1584
|
+
return;
|
|
1585
|
+
default:
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
/**
|
|
1591
|
+
* 记账并维持上限(Map 保持插入顺序,超出丢最旧)。
|
|
1592
|
+
*
|
|
1593
|
+
* `retiredDuringRunId` 是退役时仍在 in-flight 的 run id(只有 rotate 交棒轮会给);
|
|
1594
|
+
* 传 `undefined` 表示「该 Binding 的终态一律 fence」。
|
|
1595
|
+
*/
|
|
1596
|
+
private markRetiredBinding(
|
|
1597
|
+
agentId: string,
|
|
1598
|
+
sessionId: string,
|
|
1599
|
+
retiredDuringRunId?: string,
|
|
1600
|
+
): void {
|
|
1601
|
+
const key = retiredBindingKey(agentId, sessionId);
|
|
1602
|
+
this.retiredBodies.delete(key);
|
|
1603
|
+
this.retiredBodies.set(key, retiredDuringRunId);
|
|
1604
|
+
while (this.retiredBodies.size > MAX_RETIRED_BODIES_TRACKED) {
|
|
1605
|
+
const oldest = this.retiredBodies.keys().next().value;
|
|
1606
|
+
if (oldest === undefined) return;
|
|
1607
|
+
this.retiredBodies.delete(oldest);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
/**
|
|
1612
|
+
* 该 Binding 是否已退役 / 已关闭。没记账就当活着:`agent.retired` 与 `run.*` 终态
|
|
1613
|
+
* 都出自同一进程内的 `AgentService`,退役一定先记账(`retireExecutionUnitEntry` 先 emit)。
|
|
1614
|
+
*
|
|
1615
|
+
* B′(0.52):判据不是「body 已退役」,而是「这一轮是不是自己交棒的那一轮」——
|
|
1616
|
+
* 交棒轮(`run_id === retiredDuringRunId`)是合法收尾,要照常记账;只有 run id
|
|
1617
|
+
* 对不上的真迟到旧轮才 fence。
|
|
1618
|
+
*/
|
|
1619
|
+
private isRetiredBinding(
|
|
1620
|
+
agentId: string,
|
|
1621
|
+
sessionId: string | undefined,
|
|
1622
|
+
runId: string | undefined,
|
|
1623
|
+
): boolean {
|
|
1624
|
+
if (sessionId === undefined) return false;
|
|
1625
|
+
const key = retiredBindingKey(agentId, sessionId);
|
|
1626
|
+
if (!this.retiredBodies.has(key)) return false;
|
|
1627
|
+
const retiredDuringRunId = this.retiredBodies.get(key);
|
|
1628
|
+
if (retiredDuringRunId !== undefined && runId !== undefined && runId === retiredDuringRunId) {
|
|
1629
|
+
return false;
|
|
1630
|
+
}
|
|
1631
|
+
return true;
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/**
|
|
1635
|
+
* 0.27:run.* 终态写 Team 日志(成员 run 走父事件流,与 agent.* 不同管道)。
|
|
1636
|
+
* 归属字段由 runtime 并入 `data`;缺任一字段即放弃(fail-closed),不猜。
|
|
1637
|
+
* 真迟到的旧 Binding 终态不写:与旧回合事件的 `stale` 抑制等价,
|
|
1638
|
+
* reply / 失败 / 取消三条分支共用这一次判断。只写日志、不 dispatch。
|
|
1639
|
+
*
|
|
1640
|
+
* B′(0.52):rotate 交棒轮是合法收尾,不算迟到 —— 它的 `run_id` 等于退役时
|
|
1641
|
+
* 记下的 `retired_during_run_id`,因此照常记账(见 `isRetiredBinding`)。
|
|
1642
|
+
*/
|
|
1643
|
+
private onRunEvent(event: RunEvent): void {
|
|
1644
|
+
if (typeof event.data !== 'object' || event.data === null) return;
|
|
1645
|
+
const data = event.data as Record<string, unknown>;
|
|
1646
|
+
const sessionId = typeof data.session_id === 'string' ? data.session_id : undefined;
|
|
1647
|
+
|
|
1648
|
+
// Team log is team-visible. Private members must not leak id / reply.
|
|
1649
|
+
const visibility = data.visibility;
|
|
1650
|
+
if (visibility !== 'team' && visibility !== 'tenant') return;
|
|
1651
|
+
|
|
1652
|
+
const teamId = data.team_id;
|
|
1653
|
+
if (typeof teamId !== 'string' || teamId.length === 0) return;
|
|
1654
|
+
const agentId = data.agent_id;
|
|
1655
|
+
if (typeof agentId !== 'string' || agentId.length === 0) return;
|
|
1656
|
+
// 真迟到的旧 Binding 终态不写 Team 日志;rotate 交棒轮(run id 对得上)照常记账。
|
|
1657
|
+
if (this.isRetiredBinding(agentId, sessionId, event.run_id)) return;
|
|
1658
|
+
|
|
1659
|
+
if (event.type === 'run.completed') {
|
|
1660
|
+
const output = data.output;
|
|
1661
|
+
if (typeof output !== 'string' || output.length === 0) return;
|
|
1662
|
+
const entry: TeamLogEntry = {
|
|
1663
|
+
message_id: this.newId(),
|
|
1664
|
+
team_id: teamId,
|
|
1665
|
+
from: agentId,
|
|
1666
|
+
to: [],
|
|
1667
|
+
mentions: [],
|
|
1668
|
+
content: truncateReplyContent(output),
|
|
1669
|
+
ts: event.ts,
|
|
1670
|
+
kind: 'reply',
|
|
1671
|
+
};
|
|
1672
|
+
this.store
|
|
1673
|
+
.appendLog(entry)
|
|
1674
|
+
.then(() => {
|
|
1675
|
+
this.emit({ team_id: teamId, kind: 'reply', message_id: entry.message_id });
|
|
1676
|
+
})
|
|
1677
|
+
.catch((error: unknown) => {
|
|
1678
|
+
this.logger.warn('team.reply_message.failed', {
|
|
1679
|
+
team_id: teamId,
|
|
1680
|
+
agent_id: agentId,
|
|
1681
|
+
error: errorText(error),
|
|
1682
|
+
});
|
|
1683
|
+
});
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
// 失败 / 取消同样要可见:否则人类只看到 Team 里的沉默。
|
|
1688
|
+
if (event.type === 'run.failed' || event.type === 'run.cancelled') {
|
|
1689
|
+
const verb = event.type === 'run.failed' ? 'turn failed' : 'turn cancelled';
|
|
1690
|
+
const error = typeof data.error === 'string' ? singleLine(data.error) : '';
|
|
1691
|
+
const reason = typeof data.reason === 'string' ? singleLine(data.reason) : '';
|
|
1692
|
+
const detail = error.length > 0 ? error : reason;
|
|
1693
|
+
this.writeSystemLog({
|
|
1694
|
+
teamId,
|
|
1695
|
+
to: [agentId],
|
|
1696
|
+
content: detail.length > 0 ? `${verb}: ${truncateReason(detail)}` : verb,
|
|
1697
|
+
eventType: event.type,
|
|
1698
|
+
agentId,
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/** 唯一 system 日志写入点;失败只 warning,不改变生命周期 / roster。 */
|
|
1704
|
+
private writeSystemLog(input: {
|
|
1705
|
+
teamId: string;
|
|
1706
|
+
from?: string;
|
|
1707
|
+
to: string[];
|
|
1708
|
+
content: string;
|
|
1709
|
+
conversationId?: string;
|
|
1710
|
+
systemEvent?: TeamSystemEvent;
|
|
1711
|
+
eventType: string;
|
|
1712
|
+
agentId?: string;
|
|
1713
|
+
}): void {
|
|
1714
|
+
const messageId = this.newId();
|
|
1715
|
+
const entry: TeamLogEntry = {
|
|
1716
|
+
message_id: messageId,
|
|
1717
|
+
team_id: input.teamId,
|
|
1718
|
+
from: input.from ?? 'system',
|
|
1719
|
+
to: input.to,
|
|
1720
|
+
mentions: [],
|
|
1721
|
+
content: input.content,
|
|
1722
|
+
ts: this.now(),
|
|
1723
|
+
kind: 'system',
|
|
1724
|
+
...(input.conversationId !== undefined ? { conversation_id: input.conversationId } : {}),
|
|
1725
|
+
...(input.systemEvent !== undefined ? { system_event: input.systemEvent } : {}),
|
|
1726
|
+
};
|
|
1727
|
+
this.store
|
|
1728
|
+
.appendLog(entry)
|
|
1729
|
+
.then(() => {
|
|
1730
|
+
this.emit({ team_id: input.teamId, kind: 'system', message_id: messageId });
|
|
1731
|
+
})
|
|
1732
|
+
.catch((error: unknown) => {
|
|
1733
|
+
this.logger.warn('team.system_message.failed', {
|
|
1734
|
+
team_id: input.teamId,
|
|
1735
|
+
...(input.agentId !== undefined ? { agent_id: input.agentId } : {}),
|
|
1736
|
+
...(input.systemEvent !== undefined ? { system_event: input.systemEvent } : {}),
|
|
1737
|
+
event_type: input.eventType,
|
|
1738
|
+
error: errorText(error),
|
|
1739
|
+
});
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
private systemEventFor(event: AgentEvent): TeamSystemEvent | undefined {
|
|
1744
|
+
switch (event.type) {
|
|
1745
|
+
case 'agent.spawned':
|
|
1746
|
+
// CREATE-0.39:有来源的创建(公共 seeded create / 内部 dispatch 自动创建)
|
|
1747
|
+
// 必须派生 `create`,不能退化成 `join`。
|
|
1748
|
+
return event.source_agent_id !== undefined || event.from_session_id !== undefined
|
|
1749
|
+
? 'create'
|
|
1750
|
+
: 'join';
|
|
1751
|
+
case 'agent.rejoined':
|
|
1752
|
+
return 'join';
|
|
1753
|
+
case 'agent.closed':
|
|
1754
|
+
return this.archiveInFlight.has(event.agent_id) ? 'archive' : 'leave';
|
|
1755
|
+
// 旧日志只读;新代码不再写 `agent.forked`。
|
|
1756
|
+
case 'agent.forked':
|
|
1757
|
+
return 'fork';
|
|
1758
|
+
default:
|
|
1759
|
+
return undefined;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
/** 工厂:app 装配按此名称接线 */
|
|
1765
|
+
export function createTeamService(options: TeamServiceOptions): DefaultTeamService {
|
|
1766
|
+
return new DefaultTeamService(options);
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
function toTeamSummary(record: TeamRecord, memberCount: number, onlineCount: number): TeamSummary {
|
|
1770
|
+
return {
|
|
1771
|
+
team_id: record.team_id,
|
|
1772
|
+
name: record.name,
|
|
1773
|
+
workspace: record.workspace,
|
|
1774
|
+
...(record.description !== undefined ? { description: record.description } : {}),
|
|
1775
|
+
policy: record.policy,
|
|
1776
|
+
member_count: memberCount,
|
|
1777
|
+
online_count: onlineCount,
|
|
1778
|
+
created_at: record.created_at,
|
|
1779
|
+
...(record.archived_at !== undefined ? { archived_at: record.archived_at } : {}),
|
|
1780
|
+
...(record.spawn_frozen !== undefined ? { spawn_frozen: record.spawn_frozen } : {}),
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
/** 归档 Team 只读;`post` / `members` / `budget override` 统一抛 team_archived。 */
|
|
1785
|
+
function assertTeamNotArchived(record: TeamRecord, teamId: string): void {
|
|
1786
|
+
if (record.archived_at !== undefined) {
|
|
1787
|
+
throw new TeamError('team_archived', `team_archived: ${teamId}`);
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
function toMemberSummary(status: MemberStatus): TeamMemberSummary {
|
|
1792
|
+
// 0.55:硬错误闸跟着 roster 一起出去 —— Team 侧只看得到 roster(`bodies` 不进
|
|
1793
|
+
// roster),少了这一格,团队视角只有 `state=failed`,看不出「为什么跑不动」,
|
|
1794
|
+
// 于是会继续往这具不会再动的 body 投消息。
|
|
1795
|
+
const blocked = status.bodies?.find((body) => body.blocked !== undefined)?.blocked;
|
|
1796
|
+
return {
|
|
1797
|
+
agent_id: status.id,
|
|
1798
|
+
...(status.name !== undefined ? { name: status.name } : {}),
|
|
1799
|
+
session_id: status.session_id,
|
|
1800
|
+
...(status.team_id !== undefined ? { team_id: status.team_id } : {}),
|
|
1801
|
+
// 树深度(depth-color D1):与 MemberStatus.depth 同值透传,roster 反查档的 depth 源。
|
|
1802
|
+
...(status.depth !== undefined ? { depth: status.depth } : {}),
|
|
1803
|
+
membership: status.membership ?? 'present',
|
|
1804
|
+
presence: status.presence ?? 'gone',
|
|
1805
|
+
role: status.role,
|
|
1806
|
+
...(status.owner !== undefined ? { owner: status.owner } : {}),
|
|
1807
|
+
visibility: status.visibility,
|
|
1808
|
+
state: status.state,
|
|
1809
|
+
epoch: status.epoch ?? 0,
|
|
1810
|
+
...(status.last_seen !== undefined ? { last_seen: status.last_seen } : {}),
|
|
1811
|
+
// 显式 pin 只读外露(model-registry A+B);缺省跟随默认,不写键。
|
|
1812
|
+
...(status.model !== undefined ? { model: status.model } : {}),
|
|
1813
|
+
...(blocked !== undefined ? { blocked } : {}),
|
|
1814
|
+
...(status.body_history !== undefined && status.body_history.length > 0
|
|
1815
|
+
? { body_history: status.body_history }
|
|
1816
|
+
: {}),
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/** `members_limit`:缺省 20;非整数 / <1 回退 20;上限 100(DECISION-037 §7.1)。 */
|
|
1821
|
+
const DEFAULT_MEMBERS_LIMIT = 20;
|
|
1822
|
+
const MAX_MEMBERS_LIMIT = 100;
|
|
1823
|
+
|
|
1824
|
+
function normalizeMembersLimit(value: number | undefined): number {
|
|
1825
|
+
if (value === undefined || !Number.isInteger(value) || value < 1) {
|
|
1826
|
+
return DEFAULT_MEMBERS_LIMIT;
|
|
1827
|
+
}
|
|
1828
|
+
return Math.min(value, MAX_MEMBERS_LIMIT);
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
/**
|
|
1832
|
+
* TeamService 唯一 roster 顺序(DECISION-038 §2.3):
|
|
1833
|
+
* live 优先 → last_seen 降序(缺失最后)→ name 字典序(缺失最后,同缺失保持稳定)。
|
|
1834
|
+
*/
|
|
1835
|
+
function compareRoster(left: TeamMemberSummary, right: TeamMemberSummary): number {
|
|
1836
|
+
const leftLive = left.presence === 'live';
|
|
1837
|
+
const rightLive = right.presence === 'live';
|
|
1838
|
+
if (leftLive !== rightLive) return leftLive ? -1 : 1;
|
|
1839
|
+
|
|
1840
|
+
if (left.last_seen !== undefined || right.last_seen !== undefined) {
|
|
1841
|
+
if (left.last_seen === undefined) return 1;
|
|
1842
|
+
if (right.last_seen === undefined) return -1;
|
|
1843
|
+
if (left.last_seen !== right.last_seen) return right.last_seen - left.last_seen;
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
if (left.name !== undefined || right.name !== undefined) {
|
|
1847
|
+
if (left.name === undefined) return 1;
|
|
1848
|
+
if (right.name === undefined) return -1;
|
|
1849
|
+
return left.name.localeCompare(right.name);
|
|
1850
|
+
}
|
|
1851
|
+
return 0;
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
/** 只截断,不再排序:顺序唯一来源是 `rosterFor`(DECISION-038 §2.3)。 */
|
|
1855
|
+
function windowRoster(
|
|
1856
|
+
members: readonly TeamMemberSummary[],
|
|
1857
|
+
limit: number | undefined,
|
|
1858
|
+
): TeamMemberSummary[] {
|
|
1859
|
+
return members.slice(0, normalizeMembersLimit(limit));
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
/**
|
|
1863
|
+
* dispatch 前置抬头(只进投递正文,不进 Team 日志)。
|
|
1864
|
+
*
|
|
1865
|
+
* q-addr-display:`from` 显示行按 addressStyle 渲染(远端 node 无名可查 →
|
|
1866
|
+
* name 档兜底短 id);**`reply with` 的 `to` 恒 canonical full-id** —— 那是路由
|
|
1867
|
+
* 地址,远端 node 短 id / 名字都不可解析(显示与路由分离裁定)。
|
|
1868
|
+
*/
|
|
1869
|
+
function federationDispatchContent(fromAddr: string, content: string, style: AddressStyle): string {
|
|
1870
|
+
return `[federation] from ${formatFederationDisplay(fromAddr, style)}\nreply with: agent(send, to="${fromAddr}", content="...")\n\n${content}`;
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
/** 三段拆段 → formatAddress;形状不符(非 canonical 三段)时原样显示,不猜。 */
|
|
1874
|
+
function formatFederationDisplay(fromAddr: string, style: AddressStyle): string {
|
|
1875
|
+
const at = fromAddr.lastIndexOf('@');
|
|
1876
|
+
if (at <= 0) return fromAddr;
|
|
1877
|
+
const colon = fromAddr.indexOf(':', at + 1);
|
|
1878
|
+
if (colon <= at + 1 || colon === fromAddr.length - 1) return fromAddr;
|
|
1879
|
+
return formatAddress(
|
|
1880
|
+
{
|
|
1881
|
+
principal: fromAddr.slice(0, at),
|
|
1882
|
+
node: fromAddr.slice(at + 1, colon),
|
|
1883
|
+
team: fromAddr.slice(colon + 1),
|
|
1884
|
+
},
|
|
1885
|
+
style,
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
/** Team 回复日志上限:与 AgentService 一致,超限截断并加标记 */
|
|
1890
|
+
function truncateReplyContent(content: string): string {
|
|
1891
|
+
if (Buffer.byteLength(content, 'utf8') <= MAX_MESSAGE_BYTES) return content;
|
|
1892
|
+
const marker = '\n[truncated]';
|
|
1893
|
+
const budget = MAX_MESSAGE_BYTES - Buffer.byteLength(marker, 'utf8');
|
|
1894
|
+
let used = 0;
|
|
1895
|
+
let out = '';
|
|
1896
|
+
for (const char of content) {
|
|
1897
|
+
const size = Buffer.byteLength(char, 'utf8');
|
|
1898
|
+
if (used + size > budget) break;
|
|
1899
|
+
out += char;
|
|
1900
|
+
used += size;
|
|
1901
|
+
}
|
|
1902
|
+
return out + marker;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
/**
|
|
1906
|
+
* private roster 成员判定:所有 private 成员都是 roster 成员(0.28 起不再有
|
|
1907
|
+
* `single` 旁路 —— 那是「无 Team 的独立 agent」才需要的例外)。
|
|
1908
|
+
* Team 日志对 team 可见,这类成员不得作为 actor / mention / send 目标,也不写日志。
|
|
1909
|
+
*/
|
|
1910
|
+
function isPrivateRosterMember(status: MemberStatus): boolean {
|
|
1911
|
+
return status.visibility === 'private';
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/** 按首次出现顺序去重 */
|
|
1915
|
+
function dedupe(values: readonly string[]): string[] {
|
|
1916
|
+
return [...new Set(values)];
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/** 消息体:非空且不超过上限;失败抛 TeamError('invalid_input') */
|
|
1920
|
+
function readContent(content: string): string {
|
|
1921
|
+
if (content.length === 0) {
|
|
1922
|
+
throw new TeamError('invalid_input', 'content must be a non-empty string');
|
|
1923
|
+
}
|
|
1924
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_MESSAGE_BYTES) {
|
|
1925
|
+
throw new TeamError('invalid_input', `content exceeds ${MAX_MESSAGE_BYTES} bytes`);
|
|
1926
|
+
}
|
|
1927
|
+
return content;
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/** 成员解析:id / 当前 session 优先,其次唯一 name;歧义与缺失抛 TeamError */
|
|
1931
|
+
function resolveMember(member: string, visible: readonly MemberStatus[]): MemberStatus {
|
|
1932
|
+
const direct = visible.find((status) => status.id === member || status.session_id === member);
|
|
1933
|
+
if (direct !== undefined) return direct;
|
|
1934
|
+
const matches = visible.filter((status) => status.name === member);
|
|
1935
|
+
if (matches.length === 0) {
|
|
1936
|
+
throw new TeamError('unknown_member', `unknown_member: ${member}`);
|
|
1937
|
+
}
|
|
1938
|
+
if (matches.length > 1) {
|
|
1939
|
+
throw new TeamError('invalid_input', `ambiguous name: ${member}`);
|
|
1940
|
+
}
|
|
1941
|
+
const [match] = matches;
|
|
1942
|
+
if (match === undefined) {
|
|
1943
|
+
throw new TeamError('unknown_member', `unknown_member: ${member}`);
|
|
1944
|
+
}
|
|
1945
|
+
return match;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
/** 失败原因折成单行,避免一条 system 日志被正文换行撑开 */
|
|
1949
|
+
function singleLine(value: string): string {
|
|
1950
|
+
return value.replace(/\s+/g, ' ').trim();
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
/** system 日志里的失败原因上限;超出截断并加标记 */
|
|
1954
|
+
const MAX_SYSTEM_REASON_CHARS = 500;
|
|
1955
|
+
|
|
1956
|
+
function truncateReason(reason: string): string {
|
|
1957
|
+
return reason.length > MAX_SYSTEM_REASON_CHARS
|
|
1958
|
+
? `${reason.slice(0, MAX_SYSTEM_REASON_CHARS)}...`
|
|
1959
|
+
: reason;
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
function errorCode(error: unknown): string | undefined {
|
|
1963
|
+
if (typeof error !== 'object' || error === null) return undefined;
|
|
1964
|
+
const code = (error as { code?: unknown }).code;
|
|
1965
|
+
return typeof code === 'string' ? code : undefined;
|
|
1966
|
+
}
|