@celljs/ta-channels 4.8.0 → 4.9.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.
@@ -1,236 +0,0 @@
1
- import { type Agent, ChannelsUtil, MAX_MEMBERS } from './channels-util';
2
- import { ChannelWords } from './i18n';
3
- import { MoreMenu } from './more-menu';
4
- import { React } from './react';
5
- import { type ChannelsContext, ChannelViews, useChannels } from './views';
6
-
7
- type Dialog = 'rename' | 'role' | 'move' | 'join' | undefined;
8
-
9
- /** Copies text; false where the page may not. */
10
- async function copy(text: string): Promise<boolean> {
11
- try {
12
- await navigator.clipboard.writeText(text);
13
- return true;
14
- } catch {
15
- return false;
16
- }
17
- }
18
-
19
- function download(name: string, text: string): void {
20
- const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown;charset=utf-8' }));
21
- const link = document.createElement('a');
22
- link.href = url;
23
- link.download = name;
24
- link.click();
25
- setTimeout(() => URL.revokeObjectURL(url), 1000);
26
- }
27
-
28
- /**
29
- * The … of an agent in the side bar: stop it, start it over, its name, role and directory, its
30
- * conversation as a file, a channel to join, and delete.
31
- */
32
- export function AgentMenu({ context, agent, cwd, working }: { context: ChannelsContext; agent: Agent; cwd: string; working: boolean }) {
33
- const { pi, service } = context;
34
- const w = ChannelViews.words(pi);
35
- const [dialog, setDialog] = React.useState<Dialog>();
36
- const icon = (name: string) => ChannelViews.maybeIcon(pi, name, null, 15);
37
- const fail = (error: unknown) => pi.ui.notify(ChannelViews.message(error), 'error');
38
- const act = (action: () => Promise<unknown>) => () => {
39
- Promise.resolve().then(action).catch(fail);
40
- };
41
-
42
- /** The session of the agent when ta serve has it open; none opens for this. */
43
- const openSession = async () => {
44
- if (!agent.sessionFile) {
45
- return undefined;
46
- }
47
- return (await pi.server.listSessions()).find(session => session.sessionFile === agent.sessionFile);
48
- };
49
- const stop = act(async () => {
50
- const session = await openSession();
51
- if (session) {
52
- await pi.server.abort(session.sessionId);
53
- }
54
- pi.ui.notify(ChannelWords.format(w.stoppedAgent, { name: agent.name }), 'info');
55
- });
56
- const restart = act(async () => {
57
- await service.resetAgent(agent.id);
58
- context.sessions.delete(agent.id);
59
- pi.ui.notify(ChannelWords.format(w.resetDone, { name: agent.name }), 'info');
60
- });
61
- const copyCwd = act(async () => {
62
- if (await copy(cwd)) {
63
- pi.ui.notify(ChannelWords.format(w.copied, { path: cwd }), 'info');
64
- }
65
- });
66
- const exportMarkdown = act(async () => {
67
- const session = await openSession();
68
- const sessionId = session?.sessionId ?? (agent.sessionFile ? await service.openAgent(agent.id) : undefined);
69
- const { messages } = sessionId ? await pi.server.getMessages(sessionId) : { messages: [] };
70
- if (!messages.some(message => (message as { role?: string }).role === 'assistant')) {
71
- pi.ui.notify(ChannelWords.format(w.nothingToExport, { name: agent.name }), 'info');
72
- return;
73
- }
74
- download(`${agent.name}.md`, ChannelsUtil.markdown(agent, messages, { user: w.you }));
75
- });
76
- const remove = act(async () => {
77
- if (window.confirm(ChannelWords.format(w.confirmDeleteAgent, { name: agent.name }))) {
78
- await service.deleteAgent(agent.id);
79
- context.sessions.delete(agent.id);
80
- }
81
- });
82
- const show = (next: Dialog) => () => setDialog(next);
83
- const item = (key: string, label: string, glyph: string, run: () => void, options: { disabled?: boolean; danger?: boolean } = {}) => ({
84
- key,
85
- label,
86
- icon: icon(glyph),
87
- run,
88
- ...options,
89
- });
90
- return (
91
- <React.Fragment>
92
- <MoreMenu
93
- pi={pi}
94
- label={agent.name}
95
- items={() => [
96
- [item('stop', w.stop, 'Square', stop, { disabled: !working && !agent.sessionFile }), item('restart', w.restart, 'RotateCcw', restart)],
97
- [
98
- item('rename', w.rename, 'Pencil', show('rename')),
99
- item('role', w.editRole, 'ScrollText', show('role')),
100
- item('move', w.moveTo, 'FolderInput', show('move')),
101
- item('copy', w.copyCwd, 'Copy', copyCwd),
102
- ],
103
- [item('export', w.exportChat, 'Download', exportMarkdown), item('join', w.joinChannel, 'UserPlus', show('join'))],
104
- [item('delete', w.deleteAgent, 'Trash2', remove, { danger: true })],
105
- ]}
106
- />
107
- {dialog === 'rename' && <RenameDialog context={context} agent={agent} onClose={() => setDialog(undefined)} />}
108
- {dialog === 'role' && <RoleDialog context={context} agent={agent} onClose={() => setDialog(undefined)} />}
109
- {dialog === 'join' && <JoinDialog context={context} agent={agent} onClose={() => setDialog(undefined)} />}
110
- {dialog === 'move' && (
111
- <pi.ui.FolderPicker
112
- initial={cwd}
113
- onClose={() => setDialog(undefined)}
114
- onPick={async path => {
115
- setDialog(undefined);
116
- if (path !== cwd) {
117
- await service.updateAgent(agent.id, { cwd: path }).catch(fail);
118
- context.sessions.delete(agent.id);
119
- }
120
- }}
121
- />
122
- )}
123
- </React.Fragment>
124
- );
125
- }
126
-
127
- function useSave(action: () => Promise<unknown>, onClose: () => void) {
128
- const [busy, setBusy] = React.useState(false);
129
- const [error, setError] = React.useState<string>();
130
- const submit = (event: React.FormEvent) => {
131
- event.preventDefault();
132
- setBusy(true);
133
- setError(undefined);
134
- action().then(onClose, failure => {
135
- setBusy(false);
136
- setError(ChannelViews.message(failure));
137
- });
138
- };
139
- return { busy, error, submit };
140
- }
141
-
142
- function RenameDialog({ context, agent, onClose }: { context: ChannelsContext; agent: Agent; onClose(): void }) {
143
- const { pi, service } = context;
144
- const w = ChannelViews.words(pi);
145
- const [name, setName] = React.useState(agent.name);
146
- const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { name }), onClose);
147
- return (
148
- <pi.ui.Dialog title={w.rename} onClose={onClose}>
149
- <form className="tac-dialog" onSubmit={submit}>
150
- <label className="tac-dialog-label">
151
- {w.name}
152
- <input className="tac-input tac-dialog-input" value={name} maxLength={32} autoFocus onChange={event => setName(event.target.value)} />
153
- </label>
154
- {error && <div className="tac-error">{error}</div>}
155
- <div className="tac-dialog-actions">
156
- <button type="submit" className="tac-button tac-primary" disabled={busy || !name.trim() || name.trim() === agent.name}>
157
- {w.save}
158
- </button>
159
- </div>
160
- </form>
161
- </pi.ui.Dialog>
162
- );
163
- }
164
-
165
- function RoleDialog({ context, agent, onClose }: { context: ChannelsContext; agent: Agent; onClose(): void }) {
166
- const { pi, service } = context;
167
- const w = ChannelViews.words(pi);
168
- const [role, setRole] = React.useState(agent.role);
169
- const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { role }), onClose);
170
- return (
171
- <pi.ui.Dialog title={`${w.editRole} · ${agent.name}`} onClose={onClose}>
172
- <form className="tac-dialog" onSubmit={submit}>
173
- <p className="tac-dialog-note">{w.roleHint}</p>
174
- <textarea
175
- className="tac-input tac-role-input"
176
- value={role}
177
- placeholder={w.rolePlaceholder}
178
- aria-label={w.editRole}
179
- autoFocus
180
- onChange={event => setRole(event.target.value)}
181
- />
182
- {error && <div className="tac-error">{error}</div>}
183
- <div className="tac-dialog-actions">
184
- <button type="submit" className="tac-button tac-primary" disabled={busy || !role.trim() || role.trim() === agent.role}>
185
- {w.save}
186
- </button>
187
- </div>
188
- </form>
189
- </pi.ui.Dialog>
190
- );
191
- }
192
-
193
- function JoinDialog({ context, agent, onClose }: { context: ChannelsContext; agent: Agent; onClose(): void }) {
194
- const { pi, service } = context;
195
- const { team } = useChannels(service);
196
- const w = ChannelViews.words(pi);
197
- const Hash = ChannelViews.icon(pi, 'Hash');
198
- const [error, setError] = React.useState<string>();
199
- const open = team.channels.filter(channel => !channel.members.includes(agent.id));
200
- const join = (channelId: string, name: string) => {
201
- service.addMembers(channelId, [agent.id]).then(
202
- () => {
203
- onClose();
204
- pi.ui.notify(ChannelWords.format(w.joined, { name: agent.name, channel: name }), 'info');
205
- },
206
- failure => setError(ChannelViews.message(failure)),
207
- );
208
- };
209
- return (
210
- <pi.ui.Dialog title={`${w.joinChannel} · ${agent.name}`} onClose={onClose}>
211
- <div className="tac-dialog">
212
- <div className="tac-pick-list">
213
- {open.length === 0 && <div className="tac-empty">{w.noChannelToJoin}</div>}
214
- {open.map(channel => (
215
- <button
216
- key={channel.id}
217
- type="button"
218
- className="tac-pick"
219
- disabled={channel.members.length >= MAX_MEMBERS}
220
- onClick={() => join(channel.id, channel.name)}
221
- >
222
- <Hash size={16} />
223
- <span className="tac-pick-text">
224
- <span className="tac-pick-name">{channel.name}</span>
225
- <span className="tac-pick-role">
226
- {channel.topic ?? ChannelWords.format(w.memberCount, { count: String(channel.members.length) })}
227
- </span>
228
- </span>
229
- </button>
230
- ))}
231
- </div>
232
- {error && <div className="tac-error">{error}</div>}
233
- </div>
234
- </pi.ui.Dialog>
235
- );
236
- }
@@ -1,98 +0,0 @@
1
- import { type Channel, ChannelsUtil } from './channels-util';
2
- import { ChannelWords } from './i18n';
3
- import { type MoreItem, MoreMenu } from './more-menu';
4
- // biome-ignore lint/correctness/noUnusedImports: the JSX below compiles to React.createElement (jsxFactory)
5
- import { React } from './react';
6
- import { type ChannelsContext, ChannelViews, useUi } from './views';
7
-
8
- function download(name: string, text: string): void {
9
- const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown;charset=utf-8' }));
10
- const link = document.createElement('a');
11
- link.href = url;
12
- link.download = name;
13
- link.click();
14
- setTimeout(() => URL.revokeObjectURL(url), 1000);
15
- }
16
-
17
- /**
18
- * The … of a channel in the side bar, also on a right click of its row: pin it, mark it read or not, its
19
- * name, topic and members, stop who is answering, its messages as a file, and delete.
20
- */
21
- export function ChannelMenu({ context, channel, working }: { context: ChannelsContext; channel: Channel; working: string[] }) {
22
- const { pi, service, ui } = context;
23
- const { fresh } = useUi(ui);
24
- const w = ChannelViews.words(pi);
25
- const icon = (name: string) => ChannelViews.maybeIcon(pi, name, null, 15);
26
- const act = (action: () => unknown) => () => {
27
- Promise.resolve()
28
- .then(action)
29
- .catch(error => pi.ui.notify(ChannelViews.message(error), 'error'));
30
- };
31
- const unread = fresh.includes(channel.id);
32
- const pin = act(() => service.updateChannel(channel.id, { pinned: !channel.pinned }));
33
- const markRead = act(() => ui.set({ fresh: unread ? fresh.filter(id => id !== channel.id) : [...fresh, channel.id] }));
34
- const rename = act(async () => {
35
- const name = await pi.ui.input(ChannelWords.format(w.renameChannel, { channel: channel.name }), w.channelNamePlaceholder, { value: channel.name });
36
- if (name !== undefined && name.trim() !== channel.name) {
37
- await service.updateChannel(channel.id, { name });
38
- }
39
- });
40
- const editTopic = act(async () => {
41
- const topic = await pi.ui.input(w.editTopic, w.topicPlaceholder, { value: channel.topic ?? '' });
42
- if (topic !== undefined && topic.trim() !== (channel.topic ?? '')) {
43
- await service.updateChannel(channel.id, { topic });
44
- }
45
- });
46
- const members = act(() => {
47
- context.showChannel(channel.id);
48
- context.showMembers();
49
- });
50
- /** The sessions of the members answering here: what they do now stops, and their answers say so. */
51
- const stop = act(async () => {
52
- const files = new Set(
53
- service.state.team.agents.filter(agent => working.includes(agent.id) && agent.sessionFile).map(agent => agent.sessionFile as string),
54
- );
55
- const sessions = (await pi.server.listSessions()).filter(session => session.sessionFile && files.has(session.sessionFile));
56
- await Promise.all(sessions.map(session => pi.server.abort(session.sessionId)));
57
- pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), 'info');
58
- });
59
- const exportMarkdown = act(async () => {
60
- const messages = await service.messages(channel.id);
61
- if (!messages.some(message => message.text.trim())) {
62
- pi.ui.notify(ChannelWords.format(w.noMessagesToExport, { channel: channel.name }), 'info');
63
- return;
64
- }
65
- download(`${channel.name}.md`, ChannelsUtil.channelMarkdown(service.state.team, channel, messages, { user: w.you, ta: w.ta }));
66
- });
67
- const remove = act(async () => {
68
- const sure = await pi.ui.confirm(ChannelWords.format(w.confirmDelete, { channel: channel.name }), undefined, {
69
- confirmLabel: w.delete,
70
- danger: true,
71
- });
72
- if (sure) {
73
- await service.deleteChannel(channel.id);
74
- }
75
- });
76
- const item = (key: string, label: string, glyph: string, run: () => void, options: Partial<MoreItem> = {}): MoreItem => ({
77
- key,
78
- label,
79
- icon: icon(glyph),
80
- run,
81
- ...options,
82
- });
83
- return (
84
- <MoreMenu
85
- pi={pi}
86
- label={channel.name}
87
- items={() => [
88
- [
89
- item('pin', channel.pinned ? w.unpin : w.pin, channel.pinned ? 'PinOff' : 'Pin', pin),
90
- item('read', unread ? w.markRead : w.markUnread, unread ? 'MessageSquareText' : 'MessageSquareDot', markRead),
91
- ],
92
- [item('rename', w.rename, 'Pencil', rename), item('topic', w.editTopic, 'Text', editTopic), item('members', w.showMembers, 'Users', members)],
93
- [item('stop', w.stopAnswering, 'Square', stop, { disabled: working.length === 0 }), item('export', w.exportChat, 'Download', exportMarkdown)],
94
- [item('delete', w.deleteChannel, 'Trash2', remove, { danger: true })],
95
- ]}
96
- />
97
- );
98
- }
@@ -1,156 +0,0 @@
1
- // The team of a channel: its agents, channels, messages and the limits of a round.
2
- /** An agent: a ta session with a role of its own, kept by its session file. */
3
- export interface Agent {
4
- id: string;
5
- /** Unique among the agents, without spaces: it is what `@` names. */
6
- name: string;
7
- role: string;
8
- /** One or two characters on its avatar. */
9
- mark: string;
10
- /** Which of the {@link FACES} faces it has; agents made before faces get one by their id (ChannelsUtil.faces). */
11
- face?: number;
12
- /**
13
- * Where its session works: a path, or an `ssh://` location. Kept from when it is made (the server's
14
- * directory then, when none is given), so that changing the server's does not move it.
15
- */
16
- cwd?: string;
17
- sessionFile?: string;
18
- createdAt: number;
19
- }
20
-
21
- /** A conversation of the user, ta and some agents. */
22
- export interface Channel {
23
- id: string;
24
- name: string;
25
- topic?: string;
26
- /** Ids of agents; the first is the lead, who takes what nobody is named for. */
27
- members: string[];
28
- /** Members that answer nothing here, named or not, until the user lets them again. */
29
- muted?: string[];
30
- /** Listed first in the side bar. */
31
- pinned?: boolean;
32
- createdAt: number;
33
- }
34
-
35
- export interface ChannelMessage {
36
- id: string;
37
- /** {@link USER}, {@link TA}, {@link SYSTEM} or the id of an agent. */
38
- author: string;
39
- text: string;
40
- at: number;
41
- /** The message this answers. */
42
- replyTo?: string;
43
- /** The agent did not answer: `text` says why. */
44
- failed?: boolean;
45
- }
46
-
47
- export interface Team {
48
- agents: Agent[];
49
- channels: Channel[];
50
- }
51
-
52
- /** The name of this package: the key of its data on the server and the group of the sessions of its agents. */
53
- export const NAME = '@celljs/ta-channels';
54
- /** In the system prompt of every agent: how the tools tell an agent's session from ta's. */
55
- export const AGENT_MARK = 'one of the agents of Ta';
56
-
57
- /** An answer an agent owes: kept on the server until it is posted, so that a restart neither loses nor repeats it. */
58
- export interface Job {
59
- id: string;
60
- channelId: string;
61
- /** The message to answer. */
62
- messageId: string;
63
- agentId: string;
64
- /** How many hand-ons away from the message of the user or ta. */
65
- hops: number;
66
- /** The id of that message: the round the limits count. */
67
- round: string;
68
- }
69
-
70
- /** What is being answered, kept in the data as `queue`. */
71
- export interface Queue {
72
- jobs: Job[];
73
- /** By the id of the message that started the round. */
74
- rounds: Record<string, { channelId: string; round: Round }>;
75
- }
76
-
77
- /** What a page asks the server to do, as `requests/<id>`; the server answers as `results/<id>`. */
78
- export type TeamRequest =
79
- | { kind: 'createAgent'; name: unknown; role: unknown; cwd?: unknown; face?: unknown }
80
- | { kind: 'createChannel'; name: unknown; members: unknown; topic?: unknown }
81
- | { kind: 'addMembers'; channel: unknown; members: unknown }
82
- | { kind: 'changeMember'; channel: unknown; agent: unknown; change: unknown }
83
- | { kind: 'deleteChannel'; channel: unknown }
84
- /** Its name, topic, or whether it is pinned; what is not given stays, an empty topic goes. */
85
- | { kind: 'updateChannel'; channel: unknown; name?: unknown; topic?: unknown; pinned?: unknown }
86
- /** The agent starts over in a new session the next time it answers. */
87
- | { kind: 'resetAgent'; agent: unknown }
88
- /** Its name, face, role or directory; what is not given stays. */
89
- | { kind: 'updateAgent'; agent: unknown; name?: unknown; role?: unknown; face?: unknown; cwd?: unknown }
90
- /** The agent goes, and with it the channels it was the only member of. */
91
- | { kind: 'deleteAgent'; agent: unknown }
92
- | { kind: 'post'; channel: string; text: string }
93
- /** The session of an agent, opened if it is not: answered with its id, for the page to show. */
94
- | { kind: 'openAgent'; agent: unknown };
95
-
96
- export type TeamResult = { ok: true; value?: unknown } | { ok: false; error: string };
97
-
98
- /** What the user changes of a member of a channel: makes it lead, takes it out, mutes it or lets it answer again. */
99
- export type MemberChange = 'lead' | 'remove' | 'mute' | 'unmute';
100
- export const MEMBER_CHANGES: readonly string[] = ['lead', 'remove', 'mute', 'unmute'];
101
-
102
- /** The channel ta made or wrote to with its tools: pages show it. */
103
- export interface Focus {
104
- channelId: string;
105
- at: number;
106
- }
107
-
108
- /** The keys of the data of the package. The server writes all but `requests/*`, which pages write. */
109
- export namespace Keys {
110
- export const TEAM = 'team';
111
- export const QUEUE = 'queue';
112
- /** By channel id: the agents answering there now. */
113
- export const WORKING = 'working';
114
- export const FOCUS = 'focus';
115
- export const REQUESTS = 'requests/';
116
- export const RESULTS = 'results/';
117
- export const MESSAGES = 'messages/';
118
- export const messages = (channelId: string) => `${MESSAGES}${channelId}`;
119
- export const request = (id: string) => `${REQUESTS}${id}`;
120
- export const result = (id: string) => `${RESULTS}${id}`;
121
- }
122
-
123
- /** The person at the page. */
124
- export const USER = 'user';
125
- /** ta itself, in the conversation shown: what it posts with its tools. */
126
- export const TA = 'ta';
127
- /** The channel itself: the line that says why the agents stopped. */
128
- export const SYSTEM = 'system';
129
- /** How many times agents hand a message on to each other before the channel waits for someone. */
130
- export const MAX_HOPS = 3;
131
- /** How many answers one message of the user or ta leads to, at most, however the agents hand on. */
132
- export const MAX_REPLIES = 8;
133
- /** How many of those one agent gives. */
134
- export const MAX_AGENT_REPLIES = 2;
135
- /** What the channel says when it stops the agents; the page shows it in its own words. */
136
- export const STOP_NOTE = 'The agents stopped handing on here, at the limit of a round; it is your turn.';
137
-
138
- /** The answers one message of the user or ta has led to so far: what the limits count. */
139
- export interface Round {
140
- total: number;
141
- /** By agent id. */
142
- byAgent: Record<string, number>;
143
- /** The channel said it stopped. */
144
- stopped: boolean;
145
- }
146
- /** What a channel keeps. */
147
- export const MAX_MESSAGES = 200;
148
- /** How many faces there are for agents (faces.tsx draws them). */
149
- export const FACES = 16;
150
- /** The most agents a channel holds. */
151
- export const MAX_MEMBERS = 12;
152
- /** The role of an agent the user made on the page without saying one; what it is for comes with the first message. */
153
- export const DEFAULT_ROLE = 'You help the user with what they ask, as a colleague who takes on the work and does it.';
154
- /** What an agent reads of a channel besides the message for it. */
155
- export const CONTEXT_MESSAGES = 12;
156
- export const MAX_NAME = 32;