@celljs/ta-channels 0.0.0-stage → 4.6.1

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