@celljs/ta-channels 4.7.0 → 4.9.0

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.
@@ -1,103 +0,0 @@
1
- import { ChannelsUtil, TA } from './channels-util';
2
- import type { TeamService } from './team';
3
-
4
- /** A tool of ta to build a team for what the user wants and to talk to it, with the team of ta serve. */
5
- export interface TeamTool {
6
- name: string;
7
- label: string;
8
- description: string;
9
- /** JSON Schema of an object. */
10
- parameters: Record<string, unknown>;
11
- run(team: TeamService, params: Record<string, unknown>): Promise<string>;
12
- }
13
-
14
- export namespace TeamTools {
15
- export const ALL: TeamTool[] = [
16
- {
17
- name: 'create_agent',
18
- label: 'Create agent',
19
- description:
20
- 'Creates an agent: another Ta with a role of its own and its own session, which works in channels. Create agents when a goal needs several roles (for example a designer, an engineer and a reviewer), then a channel for them.',
21
- parameters: {
22
- type: 'object',
23
- properties: {
24
- name: { type: 'string', description: 'Short and unique, without spaces; channels mention it as @name.' },
25
- role: { type: 'string', description: 'What the agent does and how, in the second person: its instructions.' },
26
- cwd: { type: 'string', description: "The directory it works in, for good; default: the server's directory now." },
27
- },
28
- required: ['name', 'role'],
29
- },
30
- run: async (team, params) => `Created @${(await team.createAgent(params as { name: unknown; role: unknown; cwd?: unknown })).name}.`,
31
- },
32
- {
33
- name: 'create_channel',
34
- label: 'Create channel',
35
- description:
36
- 'Creates a channel of agents that exist. The first member leads: it gets the messages that mention nobody. The user sees the channel in the Team view of the web page.',
37
- parameters: {
38
- type: 'object',
39
- properties: {
40
- name: { type: 'string', description: 'Short, without spaces.' },
41
- members: { type: 'array', items: { type: 'string' }, description: 'Names of agents; the lead first.' },
42
- topic: { type: 'string', description: 'What the channel is for, in one sentence.' },
43
- },
44
- required: ['name', 'members'],
45
- },
46
- run: async (team, params) => {
47
- const channel = await team.createChannel(params as { name: unknown; members: unknown; topic?: unknown });
48
- await team.focus(channel.id);
49
- return `Created #${channel.name}.`;
50
- },
51
- },
52
- {
53
- name: 'add_to_channel',
54
- label: 'Add to channel',
55
- description:
56
- 'Adds agents that exist to a channel, after its members: the lead stays. Add an agent when the work in a channel needs a role it lacks; create the agent first if there is none.',
57
- parameters: {
58
- type: 'object',
59
- properties: {
60
- channel: { type: 'string', description: 'The name of the channel.' },
61
- members: { type: 'array', items: { type: 'string' }, description: 'Names of agents to add.' },
62
- },
63
- required: ['channel', 'members'],
64
- },
65
- run: async (team, params) => {
66
- const { channel, added } = await team.addMembers(params as { channel: unknown; members: unknown });
67
- await team.focus(channel.id);
68
- return added.length > 0
69
- ? `Added ${added.map(agent => `@${agent.name}`).join(', ')} to #${channel.name}.`
70
- : `They are in #${channel.name} already.`;
71
- },
72
- },
73
- {
74
- name: 'post_to_channel',
75
- label: 'Post to channel',
76
- description:
77
- 'Posts a message to a channel and waits for the answers. The agents it mentions as @name answer, or the lead when it mentions nobody; agents may hand on to each other a few times. Returns the answers.',
78
- parameters: {
79
- type: 'object',
80
- properties: {
81
- channel: { type: 'string', description: 'The name of the channel.' },
82
- message: { type: 'string', description: 'What to say; mention agents as @name.' },
83
- },
84
- required: ['channel', 'message'],
85
- },
86
- run: async (team, params) => {
87
- const { channel, done } = await team.post(String(params.channel ?? ''), TA, String(params.message ?? ''));
88
- await team.focus(channel.id);
89
- const replies = await done;
90
- return replies.length > 0 ? ChannelsUtil.transcript(team.state, replies) : 'Posted; nobody was asked to answer.';
91
- },
92
- },
93
- {
94
- name: 'list_channels',
95
- label: 'List channels',
96
- description: 'Lists the agents, their roles, and the channels with their members.',
97
- parameters: { type: 'object', properties: {} },
98
- run: async team => ChannelsUtil.summary(team.state),
99
- },
100
- ];
101
-
102
- export const NAMES = ALL.map(tool => tool.name);
103
- }
@@ -1,370 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
3
- import { ChannelsClient } from './channels';
4
- import { type ChannelMessage, Keys, MAX_HOPS, MAX_REPLIES, NAME, type Queue, STOP_NOTE, SYSTEM, TA, type Team, USER } from './channels-util';
5
- import activate, { NO_TEAM, NOT_FOR_AGENTS } from './extension';
6
- import { type TeamHost, TeamService } from './team';
7
- import { TeamTools } from './team-tools';
8
-
9
- /** ta serve: sessions that answer at once, by what `reply` says, and the data of packages with its notices. */
10
- class FakeHost {
11
- readonly opened: TaOpenSessionOptions[] = [];
12
- readonly prompts: { name?: string; message: string }[] = [];
13
- readonly sessions = new Map<string, { name?: string; file: string; count: number; last?: string }>();
14
- readonly data = new Map<string, unknown>();
15
- /** The directory of ta serve, which the user may change. */
16
- serverCwd = '/work';
17
- /** What the header of each session file says. */
18
- readonly headers = new Map<string, string>();
19
- readonly listeners = new Set<(name: string, key: string) => void>();
20
- reply: (name: string, prompt: string) => string = name => `${name} here.`;
21
-
22
- asHost(): TeamHost {
23
- return this as unknown as TeamHost;
24
- }
25
-
26
- async getServerInfo() {
27
- return { version: '0', cwd: this.serverCwd, user: 'me', host: 'box' };
28
- }
29
-
30
- async sessionCwd(file: string) {
31
- return this.headers.get(file);
32
- }
33
-
34
- async listSessions() {
35
- return [...this.sessions].map(([sessionId, session]) => ({ sessionId, sessionFile: session.file }));
36
- }
37
-
38
- async openSession(options: TaOpenSessionOptions) {
39
- this.opened.push(options);
40
- const sessionId = `s${this.opened.length}`;
41
- this.sessions.set(sessionId, { file: options.sessionFile ?? `/sessions/${sessionId}.jsonl`, count: 0 });
42
- return { sessionId };
43
- }
44
-
45
- async setSessionName(sessionId: string, name: string) {
46
- this.sessions.get(sessionId)!.name = name;
47
- }
48
-
49
- async prompt(sessionId: string, input: { message: string }) {
50
- const session = this.sessions.get(sessionId)!;
51
- this.prompts.push({ name: session.name, message: input.message });
52
- session.count += 2;
53
- session.last = this.reply(session.name ?? '', input.message);
54
- return { status: 'accepted' };
55
- }
56
-
57
- async getState(sessionId: string) {
58
- const session = this.sessions.get(sessionId)!;
59
- return { isStreaming: false, pendingMessageCount: 0, messageCount: session.count, sessionFile: session.file };
60
- }
61
-
62
- async getLastAssistantText(sessionId: string) {
63
- return { text: this.sessions.get(sessionId)!.last };
64
- }
65
-
66
- async getExtensionData(name: string, key: string) {
67
- return structuredClone(this.data.get(`${name}:${key}`)) ?? null;
68
- }
69
-
70
- async setExtensionData(name: string, key: string, value: unknown) {
71
- if (value === null || value === undefined) {
72
- this.data.delete(`${name}:${key}`);
73
- } else {
74
- this.data.set(`${name}:${key}`, structuredClone(value));
75
- }
76
- for (const listener of this.listeners) {
77
- listener(name, key);
78
- }
79
- }
80
-
81
- onExtensionData(listener: (name: string, key: string) => void) {
82
- this.listeners.add(listener);
83
- return () => this.listeners.delete(listener);
84
- }
85
-
86
- value<T>(key: string): T {
87
- return this.data.get(`${NAME}:${key}`) as T;
88
- }
89
-
90
- /** pi.storage of a page, with the notices of the host. */
91
- storage() {
92
- return {
93
- get: async <T>(key: string) => ((await this.getExtensionData(NAME, key)) ?? undefined) as T | undefined,
94
- set: (key: string, value: unknown) => this.setExtensionData(NAME, key, value),
95
- onChange: (listener: (keys: string[]) => void) => this.onExtensionData((name, key) => name === NAME && queueMicrotask(() => listener([key]))),
96
- };
97
- }
98
- }
99
-
100
- async function setUp(host = new FakeHost()) {
101
- const team = new TeamService(host.asHost(), { pollMs: 1 });
102
- await team.start();
103
- await team.createAgent({ name: 'pm', role: 'You plan.' });
104
- await team.createAgent({ name: 'dev', role: 'You build.' });
105
- const channel = await team.createChannel({ name: 'launch', members: ['pm', 'dev'] });
106
- return { host, team, channel };
107
- }
108
-
109
- const until = async (check: () => boolean) => {
110
- for (let i = 0; i < 200 && !check(); i++) {
111
- await new Promise(resolve => setTimeout(resolve, 5));
112
- }
113
- expect(check()).toBe(true);
114
- };
115
-
116
- describe('TeamService', () => {
117
- it('keeps the directory of an agent when the server moves to another', async () => {
118
- const host = new FakeHost();
119
- const team = new TeamService(host.asHost(), { pollMs: 1 });
120
- await team.start();
121
- expect((await team.createAgent({ name: 'pm', role: 'You plan.' })).cwd).toBe('/work');
122
- host.serverCwd = 'ssh://dev/srv';
123
- expect((await team.createAgent({ name: 'dev', role: 'You build.' })).cwd).toBe('ssh://dev/srv');
124
- await team.createChannel({ name: 'launch', members: ['pm'] });
125
- await (await team.post('launch', USER, 'Go')).done;
126
- expect(host.opened[0].cwd).toBe('/work');
127
- expect((await team.updateAgent({ agent: 'pm', cwd: '' })).cwd).toBe('ssh://dev/srv');
128
- });
129
-
130
- it('gives agents made before each kept a directory the one of their conversation', async () => {
131
- const host = new FakeHost();
132
- const agent = (name: string, sessionFile?: string) => ({ id: name, name, role: 'x', mark: 'X', createdAt: 0, sessionFile });
133
- host.data.set(`${NAME}:${Keys.TEAM}`, { agents: [agent('old', '/s/old.jsonl'), agent('gone', '/s/gone.jsonl'), agent('new')], channels: [] });
134
- host.headers.set('/s/old.jsonl', 'ssh://dev/app');
135
- host.serverCwd = '/home';
136
- const team = new TeamService(host.asHost(), { pollMs: 1 });
137
- await team.start();
138
- expect(host.value<Team>(Keys.TEAM).agents.map(item => item.cwd)).toEqual(['ssh://dev/app', '/home', '/home']);
139
- });
140
-
141
- it('opens a session per agent with its role, in the group of the package, and posts its answer', async () => {
142
- const { host, team, channel } = await setUp();
143
- const { done } = await team.post('launch', USER, 'What first?');
144
- expect((await done).map(reply => reply.text)).toEqual(['pm here.']);
145
- expect(host.opened).toEqual([{ cwd: '/work', appendSystemPrompt: expect.stringContaining('You are pm'), group: NAME }]);
146
- expect(host.prompts[0].message).toEndWith('user to you:\n</context>\nWhat first?');
147
- expect(host.value<ChannelMessage[]>(Keys.messages(channel.id))).toHaveLength(2);
148
- expect(host.value<Team>(Keys.TEAM).agents[0].sessionFile).toBe('/sessions/s1.jsonl');
149
- expect(host.value<Queue>(Keys.QUEUE)).toEqual({ jobs: [], rounds: {} });
150
- await (await team.post('launch', USER, 'And then?')).done;
151
- expect(host.opened).toHaveLength(1);
152
- });
153
-
154
- it('hands on to whom an answer names, and stops after a few hops with one line of the channel', async () => {
155
- const { host, team, channel } = await setUp();
156
- host.reply = name => (name === 'pm' ? '@dev your turn' : '@pm back to you');
157
- const replies = await (await team.post('launch', TA, 'Go.')).done;
158
- expect(replies.map(reply => reply.text)).toEqual([...['@dev your turn', '@pm back to you', '@dev your turn'].slice(0, MAX_HOPS), STOP_NOTE]);
159
- expect(replies.at(-1)).toMatchObject({ author: SYSTEM });
160
- expect(host.prompts).toHaveLength(MAX_HOPS);
161
- expect(host.value<ChannelMessage[]>(Keys.messages(channel.id)).filter(item => item.author === SYSTEM)).toHaveLength(1);
162
- host.reply = () => 'Done.';
163
- expect((await (await team.post('launch', USER, 'Again.')).done).map(reply => reply.author)).not.toContain(SYSTEM);
164
- });
165
-
166
- it('limits the answers of one message, however many agents are named', async () => {
167
- const host = new FakeHost();
168
- const team = new TeamService(host.asHost(), { pollMs: 1 });
169
- await team.start();
170
- const names = Array.from({ length: MAX_REPLIES + 3 }, (_, i) => `a${i}`);
171
- for (const name of names) {
172
- await team.createAgent({ name, role: 'You help.' });
173
- }
174
- await team.createChannel({ name: 'all', members: names });
175
- host.reply = () => names.map(name => `@${name}`).join(' ');
176
- const replies = await (await team.post('all', USER, names.map(name => `@${name}`).join(' '))).done;
177
- expect(replies.filter(reply => reply.author !== SYSTEM)).toHaveLength(MAX_REPLIES);
178
- expect(replies.filter(reply => reply.author === SYSTEM)).toHaveLength(1);
179
- });
180
-
181
- it('posts a failure as such and goes on', async () => {
182
- const { host, team } = await setUp();
183
- host.reply = () => '';
184
- const [reply] = await (await team.post('launch', USER, 'hi')).done;
185
- expect(reply).toMatchObject({ failed: true, text: 'pm gave no answer.' });
186
- await expect(team.post('nowhere', USER, 'hi')).rejects.toThrow('No channel is named nowhere. The channels: #launch.');
187
- });
188
-
189
- it('goes on after a restart with what was left, without asking again what was answered', async () => {
190
- const { host, team, channel } = await setUp();
191
- host.reply = name => (name === 'pm' ? '@dev build it' : 'Built.');
192
- await (await team.post('launch', USER, 'Go.')).done;
193
- team.dispose();
194
- const [, answered, built] = host.value<ChannelMessage[]>(Keys.messages(channel.id));
195
- const [pm, dev] = host.value<Team>(Keys.TEAM).agents;
196
- // As if the server stopped after posting the answer of dev, before taking its job off, and with
197
- // the user's next message not answered yet.
198
- const next: ChannelMessage = { id: 'm-next', author: USER, text: 'Ship it.', at: Date.now() };
199
- await host.setExtensionData(NAME, Keys.messages(channel.id), [...host.value<ChannelMessage[]>(Keys.messages(channel.id)), next]);
200
- const round = { total: 2, byAgent: { [pm.id]: 1, [dev.id]: 1 }, stopped: false };
201
- await host.setExtensionData(NAME, Keys.QUEUE, {
202
- jobs: [
203
- { id: 'j1', channelId: channel.id, messageId: answered.id, agentId: dev.id, hops: 1, round: 'r1' },
204
- { id: 'j2', channelId: channel.id, messageId: next.id, agentId: pm.id, hops: 0, round: next.id },
205
- ],
206
- rounds: {
207
- r1: { channelId: channel.id, round },
208
- [next.id]: { channelId: channel.id, round: { total: 1, byAgent: { [pm.id]: 1 }, stopped: false } },
209
- },
210
- } satisfies Queue);
211
- expect(built.author).toBe(dev.id);
212
- const asked = host.prompts.length;
213
- host.reply = () => 'Shipped.';
214
- const again = new TeamService(host.asHost(), { pollMs: 1 });
215
- await again.start();
216
- await until(() => host.value<Queue>(Keys.QUEUE).jobs.length === 0 && Object.keys(host.value<Queue>(Keys.QUEUE).rounds).length === 0);
217
- // dev was not asked again; pm answered the message left.
218
- expect(host.prompts.slice(asked).map(prompt => prompt.name)).toEqual(['pm']);
219
- const messages = host.value<ChannelMessage[]>(Keys.messages(channel.id));
220
- expect(messages.map(item => item.text)).toEqual(['Go.', '@dev build it', 'Built.', 'Ship it.', 'Shipped.']);
221
- });
222
- });
223
-
224
- describe('ChannelsClient', () => {
225
- it('asks the server for changes through the data and hears what changes', async () => {
226
- const { host, channel } = await setUp();
227
- const client = new ChannelsClient(host.storage(), { timeoutMs: 1000 });
228
- await client.load();
229
- expect(client.state.team.channels.map(item => item.name)).toEqual(['launch']);
230
- const agent = await client.createAgent({ name: 'qa', role: 'You test.' });
231
- expect(agent.name).toBe('qa');
232
- expect(client.state.team.agents.map(item => item.name)).toEqual(['pm', 'dev', 'qa']);
233
- await expect(client.createAgent({ name: 'qa', role: 'x' })).rejects.toThrow('There is an agent named qa already.');
234
- // The page makes an agent with the face the user picked.
235
- expect((await client.createAgent({ name: 'new-agent', role: 'x', face: 7 })).face).toBe(7);
236
- expect((await client.addMembers(channel.id, [agent.id])).members).toHaveLength(3);
237
- expect(client.state.team.channels[0].members.at(-1)).toBe(agent.id);
238
- await client.messages(channel.id);
239
- await client.post(channel.id, 'Hello');
240
- await until(() => (client.state.messages[channel.id] ?? []).length === 2);
241
- expect(client.state.messages[channel.id].map(item => item.author)).toEqual([USER, expect.stringMatching(/^agent-/)]);
242
- // What the server answered is taken off.
243
- expect([...host.data.keys()].filter(key => key.includes('requests/') || key.includes('results/'))).toEqual([]);
244
- // The page shows an agent's session: the open one, and the same one again however often it asks.
245
- const [first, again] = await Promise.all([client.openAgent(agent.id), client.openAgent(agent.id)]);
246
- expect(first).toBe(again);
247
- expect(await client.openAgent(agent.id)).toBe(first);
248
- await expect(client.openAgent('nobody')).rejects.toThrow('No agent is nobody.');
249
- const focused: string[] = [];
250
- client.onFocus(id => focused.push(id));
251
- await host.setExtensionData(NAME, Keys.FOCUS, { channelId: channel.id, at: 1 });
252
- await until(() => focused.length === 1);
253
- client.dispose();
254
- });
255
-
256
- it('changes the members, starts an agent over and deletes a channel with its messages', async () => {
257
- const { host, channel } = await setUp();
258
- const client = new ChannelsClient(host.storage(), { timeoutMs: 1000 });
259
- await client.load();
260
- const [pm, dev] = client.state.team.agents;
261
- expect((await client.changeMember(channel.id, dev.id, 'lead')).members).toEqual([dev.id, pm.id]);
262
- await client.changeMember(channel.id, dev.id, 'mute');
263
- expect(client.state.team.channels[0].muted).toEqual([dev.id]);
264
- await expect(client.changeMember(channel.id, 'nobody', 'remove')).rejects.toThrow('nobody is not a member of #launch.');
265
- // The muted lead does not answer: the next member does.
266
- await client.messages(channel.id);
267
- await client.post(channel.id, 'Hello');
268
- await until(() => (client.state.messages[channel.id] ?? []).length === 2);
269
- expect(client.state.messages[channel.id][1].author).toBe(pm.id);
270
- const sessions = host.opened.length;
271
- expect((await client.resetAgent(pm.id)).sessionFile).toBeUndefined();
272
- await client.post(channel.id, 'Again');
273
- await until(() => (client.state.messages[channel.id] ?? []).length === 4);
274
- expect(host.opened.length).toBe(sessions + 1);
275
- expect(await client.updateChannel(channel.id, { name: 'release', topic: 'Ship it', pinned: true })).toMatchObject({
276
- name: 'release',
277
- topic: 'Ship it',
278
- pinned: true,
279
- });
280
- expect(client.state.team.channels[0].name).toBe('release');
281
- await expect(client.updateChannel(channel.id, { name: '' })).rejects.toThrow('The name of the channel');
282
- await client.deleteChannel(channel.id);
283
- expect(client.state.team.channels).toEqual([]);
284
- expect(host.value(Keys.messages(channel.id))).toBeUndefined();
285
- await expect(client.deleteChannel(channel.id)).rejects.toThrow(`No channel is named ${channel.id}.`);
286
- client.dispose();
287
- });
288
-
289
- it('renames an agent in its open session, and deletes it with what it owed and the channels it was alone in', async () => {
290
- const { host, channel } = await setUp();
291
- const client = new ChannelsClient(host.storage(), { timeoutMs: 1000 });
292
- await client.load();
293
- const [pm, dev] = client.state.team.agents;
294
- await client.messages(channel.id);
295
- await client.post(channel.id, 'Hello');
296
- await until(() => (client.state.messages[channel.id] ?? []).length === 2);
297
- const renamed = await client.updateAgent(pm.id, { name: 'lead', role: 'You lead.' });
298
- expect(renamed).toMatchObject({ name: 'lead', role: 'You lead.' });
299
- expect([...host.sessions.values()].some(session => session.name === 'lead')).toBe(true);
300
- await expect(client.updateAgent(pm.id, { name: dev.name })).rejects.toThrow('already');
301
- const solo = await client.createChannel({ name: 'solo', members: [dev.id] });
302
- await client.deleteAgent(dev.id);
303
- expect(client.state.team.agents.map(agent => agent.id)).toEqual([pm.id]);
304
- expect(client.state.team.channels.map(other => other.id)).toEqual([channel.id]);
305
- expect(client.state.team.channels[0].members).toEqual([pm.id]);
306
- expect(host.value(Keys.messages(solo.id))).toBeUndefined();
307
- client.dispose();
308
- });
309
-
310
- it('says so when nobody answers', async () => {
311
- const host = new FakeHost();
312
- const client = new ChannelsClient(host.storage(), { timeoutMs: 20 });
313
- await expect(client.post('c', 'hi')).rejects.toThrow('The Ta service did not answer');
314
- });
315
- });
316
-
317
- describe('TeamTools and the pi extension', () => {
318
- it('build a team, post to it and say where the agents were stopped', async () => {
319
- const host = new FakeHost();
320
- const team = new TeamService(host.asHost(), { pollMs: 1 });
321
- await team.start();
322
- const tools = Object.fromEntries(TeamTools.ALL.map(tool => [tool.name, tool]));
323
- expect(TeamTools.NAMES).toEqual(['create_agent', 'create_channel', 'add_to_channel', 'post_to_channel', 'list_channels']);
324
- expect(await tools.create_agent.run(team, { name: 'writer', role: 'You write.' })).toBe('Created @writer.');
325
- expect(await tools.create_agent.run(team, { name: 'editor', role: 'You edit.' })).toBe('Created @editor.');
326
- expect(await tools.create_channel.run(team, { name: 'docs', members: ['writer', 'editor'], topic: 'The guide' })).toBe('Created #docs.');
327
- expect(host.value<{ channelId: string }>(Keys.FOCUS).channelId).toBe(team.state.channels[0].id);
328
- expect(await tools.list_channels.run(team, {})).toContain('- #docs (The guide): @writer, @editor');
329
- expect(await tools.create_agent.run(team, { name: 'reviewer', role: 'You review.' })).toBe('Created @reviewer.');
330
- expect(await tools.add_to_channel.run(team, { channel: 'docs', members: ['reviewer', 'writer'] })).toBe('Added @reviewer to #docs.');
331
- expect(await tools.add_to_channel.run(team, { channel: 'docs', members: ['@reviewer'] })).toBe('They are in #docs already.');
332
- expect(await tools.list_channels.run(team, {})).toContain('- #docs (The guide): @writer, @editor, @reviewer');
333
- // The new member is asked like the others.
334
- expect((await (await team.post('docs', USER, '@reviewer look')).done).map(reply => reply.text)).toEqual(['reviewer here.']);
335
- host.reply = name => (name === 'writer' ? '@editor yours' : '@writer yours');
336
- expect(await tools.post_to_channel.run(team, { channel: 'docs', message: 'Go.' })).toEndWith(`channel: ${STOP_NOTE}`);
337
- });
338
-
339
- it('registers the tools, which reach the team of the server, and refuse in the sessions of agents', async () => {
340
- const host = new FakeHost();
341
- const team = new TeamService(host.asHost(), { pollMs: 1 });
342
- await team.start();
343
- const load = (service: unknown) => {
344
- const tools = new Map<string, { execute(...args: unknown[]): Promise<{ content: { text: string }[] }> }>();
345
- const handlers = new Map<string, (event: unknown, ctx: unknown) => void>();
346
- const pi = {
347
- active: ['read', ...TeamTools.NAMES],
348
- events: { emit: (_event: string, data: unknown) => (data as { resolve(answer: unknown): void }).resolve({ host, service }) },
349
- on: (event: string, handler: (event: unknown, ctx: unknown) => void) => handlers.set(event, handler),
350
- registerTool: (tool: never) => tools.set((tool as { name: string }).name, tool),
351
- getActiveTools: () => pi.active,
352
- setActiveTools: (names: string[]) => {
353
- pi.active = names;
354
- },
355
- };
356
- activate(pi as unknown as Parameters<typeof activate>[0]);
357
- return { tools, handlers, pi };
358
- };
359
- const ta = { getSystemPrompt: () => 'You are Ta.' };
360
- const agent = { getSystemPrompt: () => 'You are pm, one of the agents of Ta. Your role: x' };
361
- const { tools, handlers, pi } = load(team);
362
- const result = await tools.get('create_agent')!.execute('1', { name: 'pm', role: 'You plan.' }, undefined, undefined, ta);
363
- expect(result.content[0].text).toBe('Created @pm.');
364
- await expect(tools.get('list_channels')!.execute('2', {}, undefined, undefined, agent)).rejects.toThrow(NOT_FOR_AGENTS);
365
- handlers.get('before_agent_start')!({}, agent);
366
- expect(pi.active).toEqual(['read']);
367
- // The host of the package failed to start.
368
- await expect(load(undefined).tools.get('list_channels')!.execute('3', {}, undefined, undefined, ta)).rejects.toThrow(NO_TEAM);
369
- });
370
- });