@celljs/ta-channels 4.19.0 → 4.20.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.
package/README.en.md CHANGED
@@ -10,12 +10,13 @@ A built-in Ta package (enabled by default but can be toggled in the Web client's
10
10
 
11
11
  - **Agent**: a normal Ta session plus a name and responsibility (as `appendSystemPrompt`); the session name is the agent's name, and the session belongs to the `@celljs/ta-channels` group (folded into one row in the conversation list). Each agent has its own cartoon avatar (those of `ui.Face`, drawn by `FaceUtil` of ta-relay, with 25 shapes and color schemes stored in `face`; on creation, it tries to avoid duplicates with existing avatars; old data without `face` is assigned by id), blinks, and looks left and right while answering; Ta itself remains the Cell logo. The session file is recorded when first opened and reopened from the file next time. A session with an agent has no team tools.
12
12
  - **Channel**: members (agents, with the first being the lead) and messages. Messages are sent to members `@`-mentioned; agents' answers are posted back to the channel, and if they `@` someone in their answer, it is passed on to them. Each agent processes one message at a time. Users can mute members in a channel (`muted`): they do not answer anything in this channel, even if `@`-mentioned; when the lead is muted, messages with no one `@`-mentioned go to the next unmuted member.
13
- - **Loop prevention** (`ChannelsUtil.limit`): relaying between agents is at most 3 hops; one message yields at most 8 answers, with at most 2 per agent. When cut off, after this round a light-colored note is appended to the channel ("reached relay limit, waiting for you to continue"), only once per round; the return from `post_to_channel` includes this note too.
13
+ - **Budget of a discussion** (`ChannelsUtil.limit`, design in docs/design/ta-channel-rounds.md): a message of the user or Ta starts a round; agents hand on without a limit of hops, within the tokens and answers the channel's length of talks allows (short / normal / long, in its … menu), and are told to conclude past 70% of it; the budget doubles while the user watches the channel and halves while nobody is there, a round stops early when the agents only agree, repeat themselves or hand back and forth bringing nothing new, and one that changed files or the notice goes on once past it (×1.5). Three more limits, in tokens, are set in Settings → Group chats: an answer past its own is stopped where it is, a channel past its own of the day (set in its info, or the default) answers only the user, and past that of all channels all pause and the user is told; Go on lets a round past those of the day. Where it stops, the channel adds a line "The agents paused to wait for you" with the replies and tokens of the round, and two buttons: Go on (the hand-ons it cut go on, the budget anew) and Have the lead sum up, chosen once; the return of `post_to_channel` says so too.
14
14
  - **Tools**: each session in Ta (web pages and other clients connected to ta serve) has `create_agent`, `create_channel`, `add_to_channel`, `post_to_channel`, and `list_channels`. When a user specifies a goal ("assemble a team to do the landing page"), Ta creates agents and channels, posts the goal, and waits for answers from each member before replying to the user. When a role is missing from a channel, Ta uses `add_to_channel` to add an existing agent (added after existing members; lead unchanged). The open page marks this channel with a green dot in the sidebar, which disappears when opened. Pausing Ta just stops waiting; agents continue to answer in the channel.
15
15
  - **Hand over to…** (WeChat's forward, of work rather than of words): say "give this to @life" in a conversation, or pick Hand over to… in the + of the message box and an agent or a channel; Ta first writes a brief in that conversation (the goal, what is done and decided, what is left or blocks, the files and commands that matter), then hands it over with the tool `hand_off`. An agent gets the brief as a message of its own conversation (starting with "Handed over from 'that conversation'", the session file of the conversation in the `<context>` for the model, to read when the brief is not enough) and goes on; a channel gets it as a message of Ta's, which its lead answers. Neither is waited for: the user follows it there. The conversation it came from keeps a card "Handed over to @life" (the model does not read it) with the brief, Open going to the agent's conversation or the channel. An external agent without Ta's tools writes the brief in a `ta-handoff` block in the turn the + asked for, and the pi extension hands it over. On the server it is `TeamService.handOff` (`web-src/handoff.ts`).
16
16
  - **Channel notices and agents' cards** (see `docs/design/ta-social.md`): a channel's notice (decisions, conventions, to-dos) is in the `<context>` of every member's message; the members keep it with the tool `update_channel_notice` as the talk settles things, the user reads and edits it in the bar above the chat, and each change is a line of the channel. Share card… in a member's menu makes the link and QR code of its card (`TeamService.shareAgent`, 30 days, also while the computer is off; its name, face and role, secrets taken out); a card's link opened in Ta adds the agent in the directory picked (`addFromCard`), which first looks at the project and fits its role with `update_my_role`.
17
17
  - **Tasks of the double** (see `docs/design/ta-double.md`): a channel Ta builds with its tools has `by: 'ta'` and the session that built it (`origin`), and is listed as a task of the double (`registerTasks`), not among the user's own channels; the agents it makes are `temporary`, shown with their team until the user keeps them in the members panel or the agent's menu, and one in no channel is listed among the members. This list of the navigation is called "Double": the double's card, the tasks in one list (what waits for you first, then what goes on, then what ended), the members (as contacts, by directory if the user wants), the channels, each section folding (kept in the browser). A team opened from its task shows in the workbench on the right, with "Open in the main area" in its bar. While the double asks first, the team tools ask with `ctx.ui.confirm` before they build a team and before work goes to a channel the user did not let them use. Below, the channels and agents once listed flat are now under "Channels" and "Members".
18
18
  - **UI**: "Agents" at the top of the navigation bar (above "Conversations"; the first bottom tab on a phone) puts the double, channels, and agents together (the double is a built-in page from ta-web, and once enabled is listed at the top, no longer appears separately in the navigation bar); the search box and + are at the top of the sidebar. + → create agent opens a draft page in the main area: first assigns an unused name and avatar, clicking the name in the top bar can rename or pick from 25 avatars, the sidebar has one more line "not started"; the agent is truly created when the first message is sent from the input box (responsibility is generic, what to do is written in this message), then switches to its session and sends the message. + → create channel is a dialog: name, search and check agents (1–12, first checked is lead), create; channel row has lead first, next member in overlapping avatars, lead is labeled beside the name, second line is the most recent message or who's answering; agents are grouped by working directory, second line is "idle" or which channel they're answering in, right side is time of most recent message. Click agent to open its session: it is in front at once, under the agent's name, showing that it opens (`pi.switchSession` takes the promise of the `openAgent` request), and shows as the current conversation once the server opens or finds the session. Hovering over agent row (long-press on touch) shows …, menu has: stop (abort its current answer), restart (open new session), rename, responsibility (edit the role in the system prompt, takes effect in next session), move to… (switch working directory, open new session in that directory), copy working directory, export conversation (Markdown, strip channel context blocks), add to channel, delete (leave all channels it's in, delete channels that only have it, keep the session file); when near the bottom the menu expands upward. Channel is a page in the main area (not in the right workbench), displayed as a group chat: others' messages on the left with avatar and name, user's on the right, consecutive messages are grouped, after a long pause insert a time line; top bar is channel name and member avatars, click avatar to open "Channel Members" (`members`, `location: 'panel'` view, follows the current channel) in the right workbench: lists members, lead has a marker, answering ones are marked green; each row opens that agent's session, hovering (long-press on touch) shows set as lead, mute, restart session (forget earlier conversation, open new session next time it answers, old session stays in conversation list), and remove from channel (at least one left); top has "Add Members" as a searchable agent list, check to add, bottom of list has "New Agent" to open the draft page for creating a new agent; bottom has delete channel (confirm once more, messages deleted too, ongoing answers no longer posted). Input box is the conversation input box (`pi.ui.Composer`), `@` lists members, + allows naming members or adding members (opens the member list for adding); messages use the conversation's Markdown rendering (`pi.ui.Markdown`), `@`-mentioned members are bold.
19
+ - **About the group chat, and models**: the faces of the members in the bar of a channel open “About the group chat” on the right (once “Members”): “Model for all” beside the members has every agent of the group answer with one model (`setChannelModel`; “Each its own” while they differ), and the quick settings of each member's row (also in the agent's menu) change its name, model and role in one place; under the members are the group's name, topic and Pin the chat. An agent's `model` (`<provider>/<model id>`, pi's default without one) is what its session opens on, an open one switched at once (`TaExtensionHost.setModel`), and a model pi does not have is not kept; it answers in rooms (ta-rooms) with it too.
19
20
 
20
21
  ## Data and Forwarding
21
22
 
@@ -31,7 +32,7 @@ Data is stored on the server in `<agentDir>/extension-data/@celljs/ta-channels.j
31
32
 
32
33
  The page learns of changes via `pi.storage.onChange` and rereads them. To change something (create agent, create channel, add channel member, set lead / mute / remove member, delete channel, restart agent session, modify or delete agent, post message as user, open agent session), a page calls `request` on the server side: this package's web extension with `pi.callHost('request', request)`, other extensions with `pi.packages.callPackageHost('@celljs/ta-channels', 'request', [request])` (the host of another package with `host.callPackageHost`). `request` is a `TeamRequest` (`web-src/channels-model.ts`); the call returns the result, or throws the reason. Each answer is first recorded as a job in `queue` and removed only after the answer is posted to the channel. After ta serve restarts, it continues processing remaining jobs: jobs that already have an answer (the channel has this agent's reply to that message) are not asked again, and messages already forwarded are not forwarded again, so processed messages do not duplicate. On restart, the one message that was being answered and not yet posted is asked again.
33
34
 
34
- Another package that needs the agents (ta-rooms, for those to invite to a room) calls `listAgents` of the server side (`callPackageHost('@celljs/ta-channels', 'listAgents')`) rather than reading `team`: it returns `TeamAgentInfo[]` (`web-src/channels-model.ts`), each agent's `id`, `name`, `role`, `mark`, `face` (the one given by its id to an agent made before faces) and `cwd`, `temporary` on those Ta made for a team of its own; it only reads, and holds no session files.
35
+ Another package that needs the agents (ta-rooms, for those to invite to a room) calls `listAgents` of the server side (`callPackageHost('@celljs/ta-channels', 'listAgents')`) rather than reading `team`: it returns `TeamAgentInfo[]` (`web-src/channels-model.ts`), each agent's `id`, `name`, `role`, `mark`, `face` (the one given by its id to an agent made before faces) and `cwd`, `model` when it has one, `temporary` on those Ta made for a team of its own; it only reads, and holds no session files.
35
36
 
36
37
  ## Limitations
37
38
 
package/README.md CHANGED
@@ -10,12 +10,13 @@ Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 包 关
10
10
 
11
11
  - **智能体**:一个普通的 Ta 会话,加上名字和职责(作为 `appendSystemPrompt`),会话名就是智能体的名字,会话属于 `@celljs/ta-channels` 分组(对话列表里折成一行)。每个智能体有自己的卡通头像(`ui.Face` 那一套,ta-relay 的 `FaceUtil` 画,25 种形状和配色,记在 `face` 里;新建时尽量不和已有的重样,没有 `face` 的旧数据按 id 分配),会眨眼,回答时左右张望;Ta 自己仍是 Cell logo。会话文件一打开就记下,下次从文件重新打开。智能体的会话里没有团队工具。
12
12
  - **频道**:成员(智能体,第一个是负责人)和消息。消息发给其中 `@` 到的成员;智能体的回答贴回频道,它在回答里 `@` 谁就再交给谁。每个智能体一次只处理一条消息。用户可以把成员设为免打扰(`muted`):它在这个频道里什么都不回答,被 `@` 也不回答;负责人免打扰时,没人被 `@` 的消息交给下一位没有免打扰的成员。
13
- - **防循环**(`ChannelsUtil.limit`):智能体之间接力最多 3 跳,一条消息引出的回答最多 8 条、每个智能体最多 2 条;被截断时,等这一轮结束后在频道里追加一行淡色说明("已到交接上限,等你继续"),每轮只追加一次,`post_to_channel` 的返回里也带上这句。
13
+ - **讨论预算**(`ChannelsUtil.limit`,设计见 docs/design/ta-channel-rounds.md):一条用户或 Ta 的消息开启一轮,智能体之间接力不限跳数,按群聊的"讨论长度"(简短 / 标准 / 深入,… 菜单里改)限制这一轮花的 token 和回答条数;花到 70% 时提示智能体收尾;你在看这个群时预算翻倍、没人在时减半,智能体只附和、重复或两人来回没进展时提前停下,这一轮改了文件或公告则到预算时自动续一次(×1.5)。另有三层按 token 的上限(设置 → 群聊用量):单条回复超了就地停下,每个群每天超了只回答你(每个群也可在群聊信息里单独设),所有群每天超了全部暂停并通知你;点"继续讨论"可越过当天的上限。停下时频道里追加一行"讨论暂停,等你决定",带这一轮的回复数和 token,下面是"继续讨论"(接上被截下的接力,预算重新计)和"请负责人总结"两个按钮,只能选一次;`post_to_channel` 的返回里也带上这句。
14
14
  - **工具**:ta serve 里 Ta 的每个会话(Web 页面里的对话,以及连到 ta serve 的其他客户端)都有 `create_agent`、`create_channel`、`add_to_channel`、`post_to_channel`、`list_channels`。用户说一个目标("组个团队做落地页")时,Ta 建好智能体和频道、把目标贴进去,等各成员回答完再回复用户;频道缺某个角色时,Ta 用 `add_to_channel` 把已有的智能体加进来(加在已有成员之后,负责人不变);开着的页面在侧栏给这个频道标一个绿点,打开后消失。中途停止 Ta 只是不再等待,智能体会在频道里接着回答。
15
15
  - **交给…**(参照微信的转发,但转的是工作):对话里说"这个交给 @life",或在输入框的 + 里选"交给…"再挑一个智能体或频道,Ta 先在这个对话里写一份交接摘要(目标、已完成和已决定的、剩下的或卡住的、相关的文件和命令),再用工具 `hand_off` 交出去。交给智能体时,摘要作为一条消息进入它自己的对话(开头是"交接自'某某对话'",原对话的会话文件写在给模型读的 `<context>` 里,摘要不够时它可以去读),它接着干;交给频道时,摘要作为 Ta 的一条消息贴进频道,由负责人回答。两者都不等回答,用户在那边跟进。原对话里留一张"已交给 @life"卡片(模型读不到),显示摘要,点"打开"进入对方的对话或频道。没有 Ta 工具的外部 Agent 在 + 发起的这一轮把摘要写进 `ta-handoff` 代码块,由 pi 扩展交出去。服务端方法是 `TeamService.handOff`(`web-src/handoff.ts`)。
16
16
  - **频道公告与智能体名片**(见 `docs/design/ta-social.md`):频道的公告(决定 / 约定 / 待办)放进每个成员每条消息的 `<context>`,成员用工具 `update_channel_notice` 随讨论更新,用户在聊天上方的公告栏查看和编辑,每次改动在频道里留一行提示。成员菜单"分享名片…"生成名片链接和二维码(`TeamService.shareAgent`,30 天,电脑关机也能打开;只带名字、头像和隐去密钥的职责);在 Ta 里打开名片链接,选目录后"加为我的智能体"(`addFromCard`),它先看这个项目,用 `update_my_role` 把职责改得贴合这里。
17
17
  - **分身的任务**(见 `docs/design/ta-double.md`):Ta 用工具建的频道带 `by: 'ta'` 和建它的会话 `origin`,作为分身的任务(`registerTasks`)列出,不进用户自己的"频道"分组;它建的智能体带 `temporary`,只在团队里出现,在成员面板或智能体菜单里"留下"后才成为常驻成员,不在任何频道里的临时智能体也列在成员里。导航栏里这个列表叫"分身":分身卡片、"任务"(一个列表,待你处理的在前,然后进行中、已结束)、"成员"(像通讯录,可选按目录分组)、"频道",各组可折叠(折叠状态存在浏览器本地)。从任务打开的团队显示在右侧工作台,顶栏可"在主区打开"。分身开启"开始任务前先问我"时,建团队前、以及第一次往用户放行过以外的频道派活前,用 `ctx.ui.confirm` 询问。下文的列表描述里,原先平铺的频道和智能体现在分别在"频道"和"成员"分组。
18
18
  - **界面**:导航栏最上面的"智能体"(在"对话"上面,手机上是第一个底部标签)把分身、频道和智能体放在一起(分身是 ta-web 内置的页面,开启后列在最上面,导航栏里不再单独出现):侧栏顶部是搜索框和 +。+ → 新建智能体在主区域打开一个草稿页:先给一个没人用的名字和头像,顶栏点名字可以改名、从 25 个头像里挑,侧栏顶部多一行"还没开工";输入框发出第一条消息时才真正建好智能体(职责是通用的,具体做什么写在这条消息里),随即切到它的会话并发出这条消息。+ → 新建频道是一个弹窗:名称、搜索并勾选智能体(1–12 个,先勾的是负责人)、创建;频道行是负责人在前、下一位成员在后的叠放头像,名称旁标出负责人,第二行是最近一条消息或谁正在回答;智能体按工作目录分组,第二行是"空闲"或正在哪个频道回答,右侧是最近一次发言的时间。点智能体打开它的会话:立即切过去,以智能体的名字显示"正在打开"(`pi.switchSession` 接收 `openAgent` 请求的 Promise),服务端打开或找到会话后显示为当前对话。智能体行悬停(触屏上常显)出现 …,菜单里是:停止(中止它正在进行的回答)、重新开始(开新会话)、重命名、职责(编辑系统提示词里的角色,下一个会话生效)、移至…(换工作目录,在新目录开新会话)、复制工作目录、导出对话(Markdown,去掉频道的上下文块)、加入频道、删除(退出所在频道,只剩它的频道一并删除,会话文件保留);靠近底部时菜单向上展开。频道是主区域的一个页面(不进右侧工作台),以群聊显示:别人的消息在左边带头像和名字,用户的在右边,连续发言合成一组,停顿久了插一行时间;顶栏是频道名和成员头像,点头像在右侧工作台打开"频道成员"(`members`,`location: 'panel'` 的视图,跟着当前频道):列出成员,负责人带标记,正在回答的标绿;每行点开是智能体的会话,悬停(触屏上常显)出现设为负责人、免打扰、重开会话(忘掉之前的对话,下次回答时开新会话,旧会话仍在对话列表里)和移出频道(至少留一位);顶部"添加成员"换成可搜索的智能体列表,勾选后添加,列表底部的"新建智能体"打开新建智能体的草稿页;底部是删除频道(再确认一次,消息一并删除,正在进行的回答不再贴出)。输入框就是对话的输入框(`pi.ui.Composer`),`@` 列出成员,+ 里可以点名成员、添加成员(打开频道成员的添加列表),或"做成扩展"(在频道里请负责人用 ta-package 技能把这里商量和做成的事做成扩展);消息用对话的 Markdown 渲染(`pi.ui.Markdown`),点名的成员加粗。
19
+ - **群聊信息与模型**:频道顶栏的成员头像打开右侧“群聊信息”(原“频道成员”):成员列表旁的“统一模型”一次让群里所有智能体改用同一个模型(`setChannelModel`;成员各用各的时显示“各用各的”),每个成员行的快捷设置(智能体菜单里也有)一处改名字、模型和职责;成员下面是群聊名称、主题和置顶聊天。智能体的 `model`(`<provider>/<model id>`,不设就用 pi 的默认)在它打开会话时用上,已开着的会话当即切换(`TaExtensionHost.setModel`),pi 没有的模型不会保存;它在房间里回答时(ta-rooms)也用这个模型。
19
20
 
20
21
  ## 数据与转发
21
22
 
@@ -31,7 +32,7 @@ Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 包 关
31
32
 
32
33
  页面通过 `pi.storage.onChange` 得知变化后重新读取。页面要改什么(新建智能体、新建频道、添加频道成员、设负责人 / 免打扰 / 移出成员、删除频道、重开智能体的会话、修改或删除智能体、以用户身份发消息、打开智能体的会话),调用服务端的 `request`:本包的 Web 扩展用 `pi.callHost('request', request)`,其他扩展用 `pi.packages.callPackageHost('@celljs/ta-channels', 'request', [request])`(别的包的服务端用 `host.callPackageHost`);`request` 的类型是 `TeamRequest`(`web-src/channels-model.ts`),返回结果,出错时抛出原因。每个回答先作为 job 记进 `queue`,回答贴进频道后才移除。ta serve 重启后接着处理剩下的 job:已经有回答(频道里有该智能体对这条消息的回复)的 job 不会再问,已经交出去的消息也不会再交一次,所以已处理的消息不会重复转发。重启时正在回答、还没有贴出的那一条,会再问一次。
33
34
 
34
- 别的包要知道有哪些智能体(如 ta-rooms 列出可以邀请进房间的),调用服务端的 `listAgents`(`callPackageHost('@celljs/ta-channels', 'listAgents')`),不要读 `team`:它返回 `TeamAgentInfo[]`(`web-src/channels-model.ts`),每个智能体的 `id`、`name`、`role`、`mark`、`face`(早于头像的智能体按 id 分到的那个)、`cwd`,Ta 为自己的团队临时建的带 `temporary`;只读,不含会话文件。
35
+ 别的包要知道有哪些智能体(如 ta-rooms 列出可以邀请进房间的),调用服务端的 `listAgents`(`callPackageHost('@celljs/ta-channels', 'listAgents')`),不要读 `team`:它返回 `TeamAgentInfo[]`(`web-src/channels-model.ts`),每个智能体的 `id`、`name`、`role`、`mark`、`face`(早于头像的智能体按 id 分到的那个)、`cwd`,设了模型的带 `model`,Ta 为自己的团队临时建的带 `temporary`;只读,不含会话文件。
35
36
 
36
37
  ## 限制
37
38
 
@@ -50,6 +50,22 @@ var TaHostUtil;
50
50
  }
51
51
  TaHostUtil2.role = role;
52
52
  })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_DOUBLE_LOOK = {
54
+ name: "@celljs/ta-web",
55
+ key: "assistant.species",
56
+ given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
57
+ };
58
+ var TaDoubleLookUtil;
59
+ (function(TaDoubleLookUtil2) {
60
+ function given(id) {
61
+ let hash = 2166136261;
62
+ for (let i = 0;i < id.length; i++) {
63
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
64
+ }
65
+ return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
66
+ }
67
+ TaDoubleLookUtil2.given = given;
68
+ })(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
53
69
  var TA_ASK_ENTRY = "ta-ask";
54
70
  var TaAskUtil;
55
71
  (function(TaAskUtil2) {
@@ -342,6 +358,11 @@ var FaceUtil;
342
358
  })(FaceUtil || (FaceUtil = {}));
343
359
 
344
360
  // web-src/channels-model.ts
361
+ var LIMIT_CHOICES = {
362
+ answer: [1e5, 300000, 1e6],
363
+ channelDay: [2000000, 5000000, 20000000, 0],
364
+ allDay: [5000000, 20000000, 0]
365
+ };
345
366
  var NAME = "@celljs/ta-channels";
346
367
  var AGENT_MARK = "one of the agents of Ta";
347
368
  var MEMBER_CHANGES = ["lead", "remove", "mute", "unmute"];
@@ -353,15 +374,21 @@ var Keys;
353
374
  Keys.FOCUS = "focus";
354
375
  Keys.ANSWERED = "answered";
355
376
  Keys.CARDS = "cards";
377
+ Keys.LIMITS = "limits";
378
+ Keys.SPENT = "spent";
356
379
  Keys.MESSAGES = "messages/";
357
380
  Keys.messages = (channelId) => `${Keys.MESSAGES}${channelId}`;
358
381
  })(Keys ||= {});
359
382
  var USER = "user";
360
383
  var TA = "ta";
361
384
  var SYSTEM = "system";
362
- var MAX_HOPS = 3;
363
- var MAX_REPLIES = 8;
364
- var MAX_AGENT_REPLIES = 2;
385
+ var BUDGETS = {
386
+ short: { tokens: 200000, replies: 10 },
387
+ normal: { tokens: 800000, replies: 30 },
388
+ long: { tokens: 3000000, replies: 100 }
389
+ };
390
+ var DEFAULT_BUDGET = "normal";
391
+ var EXTEND_BY = 0.5;
365
392
  var MAX_MESSAGES = 200;
366
393
  var FACES = FACE_COUNT;
367
394
  var MAX_MEMBERS = 12;
@@ -374,25 +401,58 @@ var NOTICE_HEADINGS = { zh: ["决定", "约定", "待办"], en: ["Decisions", "C
374
401
  var ChannelsUtil;
375
402
  ((ChannelsUtil) => {
376
403
  function newRound() {
377
- return { total: 0, byAgent: {}, stopped: false };
404
+ return { total: 0, tokens: 0, stopped: false };
378
405
  }
379
406
  ChannelsUtil.newRound = newRound;
380
- function limit(round, targets, hops) {
381
- const allowed = [];
382
- const byAgent = { ...round.byAgent };
383
- let total = round.total;
384
- for (const id of targets) {
385
- if (hops < MAX_HOPS && total < MAX_REPLIES && (byAgent[id] ?? 0) < MAX_AGENT_REPLIES) {
386
- allowed.push(id);
387
- byAgent[id] = (byAgent[id] ?? 0) + 1;
388
- total++;
407
+ function budgetOf(channel) {
408
+ return channel?.budget && channel.budget in BUDGETS ? channel.budget : DEFAULT_BUDGET;
409
+ }
410
+ ChannelsUtil.budgetOf = budgetOf;
411
+ function limit(round, targets, budget, from, scale = 1) {
412
+ const fit = (extended2) => {
413
+ const { tokens, replies } = caps(budget, scale, extended2);
414
+ const open = (round.tokens ?? 0) < tokens;
415
+ const allowed2 = [];
416
+ let total2 = round.total;
417
+ for (const id of targets) {
418
+ if (open && total2 < replies) {
419
+ allowed2.push(id);
420
+ total2++;
421
+ }
389
422
  }
423
+ return { allowed: allowed2, total: total2 };
424
+ };
425
+ let extended = !!round.extended;
426
+ let { allowed, total } = fit(extended);
427
+ if (allowed.length < targets.length && round.progress && !extended) {
428
+ extended = true;
429
+ ({ allowed, total } = fit(true));
390
430
  }
391
- const cut = allowed.length < targets.length;
392
- const note = cut && !round.stopped;
393
- return { allowed, round: { total, byAgent, stopped: round.stopped || cut }, cut, note };
431
+ round = extended ? { ...round, extended } : round;
432
+ const cut = targets.filter((id) => !allowed.includes(id));
433
+ const pending = cut.length > 0 && from ? [...round.pending ?? [], { ...from, agentIds: cut }] : round.pending;
434
+ return { allowed, cut, round: { ...round, total, stopped: round.stopped || cut.length > 0, ...pending ? { pending } : {} } };
394
435
  }
395
436
  ChannelsUtil.limit = limit;
437
+ function used(round, budget, scale = 1) {
438
+ const limits = caps(budget, scale, !!round.extended);
439
+ return Math.max((round.tokens ?? 0) / limits.tokens, round.total / limits.replies);
440
+ }
441
+ ChannelsUtil.used = used;
442
+ function caps(budget, scale, extended) {
443
+ const { tokens, replies } = BUDGETS[budget];
444
+ const factor = scale * (extended ? 1 + EXTEND_BY : 1);
445
+ return { tokens: tokens * factor, replies: Math.max(1, Math.round(replies * factor)) };
446
+ }
447
+ ChannelsUtil.caps = caps;
448
+ function spent(before, after) {
449
+ if (!before || !after) {
450
+ return 0;
451
+ }
452
+ const delta = (key) => Math.max(0, (after[key] ?? 0) - (before[key] ?? 0));
453
+ return Math.round(delta("input") + delta("output") + delta("cacheWrite") + delta("cacheRead") / 10);
454
+ }
455
+ ChannelsUtil.spent = spent;
396
456
  function emptyTeam() {
397
457
  return { agents: [], channels: [] };
398
458
  }
@@ -609,6 +669,24 @@ var ChannelsUtil;
609
669
  delete channel.pinned;
610
670
  }
611
671
  }
672
+ if (input.budget !== undefined) {
673
+ if (typeof input.budget !== "string" || !(input.budget in BUDGETS)) {
674
+ throw new Error(`The budget of a channel is one of ${Object.keys(BUDGETS).join(", ")}.`);
675
+ }
676
+ if (input.budget === DEFAULT_BUDGET) {
677
+ delete channel.budget;
678
+ } else {
679
+ channel.budget = input.budget;
680
+ }
681
+ }
682
+ if (input.dailyLimit === null) {
683
+ delete channel.dailyLimit;
684
+ } else if (input.dailyLimit !== undefined) {
685
+ if (!LIMIT_CHOICES.channelDay.includes(input.dailyLimit)) {
686
+ throw new Error(`The limit of a day of a channel is one of ${LIMIT_CHOICES.channelDay.join(", ")} tokens (0 for none), or null.`);
687
+ }
688
+ channel.dailyLimit = input.dailyLimit;
689
+ }
612
690
  return { team: { ...team, channels: team.channels.map((other) => other.id === channel.id ? channel : other) }, channel, before };
613
691
  }
614
692
  ChannelsUtil.updateChannel = updateChannel;
@@ -689,9 +767,40 @@ var ChannelsUtil;
689
767
  delete agent.cwd;
690
768
  }
691
769
  }
770
+ if (input.model !== undefined) {
771
+ const model = checkModel(input.model);
772
+ if (model) {
773
+ agent.model = model;
774
+ } else {
775
+ delete agent.model;
776
+ }
777
+ }
692
778
  return { team: { ...team, agents: team.agents.map((other) => other.id === agent.id ? agent : other) }, agent, before };
693
779
  }
694
780
  ChannelsUtil.updateAgent = updateAgent;
781
+ function checkModel(value) {
782
+ if (value === "" || value === null) {
783
+ return;
784
+ }
785
+ if (typeof value !== "string" || value.length > 200 || !/^[^/\s]+\/\S+$/.test(value)) {
786
+ throw new Error("A model is named `<provider>/<model id>`.");
787
+ }
788
+ return value;
789
+ }
790
+ ChannelsUtil.checkModel = checkModel;
791
+ function setChannelModel(team, input) {
792
+ const channel = findChannel(team, typeof input.channel === "string" ? input.channel : "");
793
+ if (!channel) {
794
+ throw new Error(`No channel is ${String(input.channel)}.`);
795
+ }
796
+ let next = team;
797
+ for (const id of channel.members) {
798
+ next = updateAgent(next, { agent: id, model: input.model }).team;
799
+ }
800
+ const agents = next.agents.filter((agent) => channel.members.includes(agent.id));
801
+ return { team: next, channel, agents };
802
+ }
803
+ ChannelsUtil.setChannelModel = setChannelModel;
695
804
  function removeAgent(team, ref) {
696
805
  const agent = findAgent(team, typeof ref === "string" ? ref : "");
697
806
  if (!agent) {
@@ -1584,12 +1693,13 @@ var ChannelsText;
1584
1693
  "You work with the user, Ta and other agents in channels. A message for you starts with a <context> block: the channel, its members, the recent messages and who speaks to you; answer what follows the block.",
1585
1694
  "Do the part of the work your role covers with your tools, then answer: your answer is posted to the channel as it is.",
1586
1695
  "To hand work to another member, write @ and their name in your answer; name nobody when the work is done or you need the user.",
1696
+ "Name a member only when you need their part, not to thank them or agree: each answer spends what the user allows the channel before they look in. Once the members agree or the work is done, name nobody; the lead sums up for the user.",
1587
1697
  NOTICE_RULE
1588
1698
  ].join(`
1589
1699
  `);
1590
1700
  }
1591
1701
  ChannelsText.systemPrompt = systemPrompt;
1592
- function prompt(team, channel, history, message, agent) {
1702
+ function prompt(team, channel, history, message, agent, options = {}) {
1593
1703
  const labels = { user: "user", ta: "Ta" };
1594
1704
  const members = channel.members.map((id) => team.agents.find((other) => other.id === id)).filter((other) => !!other).map((other) => `@${other.name}${other.id === agent.id ? " (you)" : ""}: ${firstLine(other.role)}`);
1595
1705
  const before = history.filter((item) => item.id !== message.id && !item.failed && !item.notice).slice(-CONTEXT_MESSAGES);
@@ -1600,6 +1710,9 @@ var ChannelsText;
1600
1710
  if (before.length > 0) {
1601
1711
  lines.push("", "Recent messages:", ...before.map((item) => `${authorName(team, item.author, labels)}: ${item.text}`));
1602
1712
  }
1713
+ if (options.closing) {
1714
+ lines.push("", CLOSING_NOTE);
1715
+ }
1603
1716
  lines.push("", `${authorName(team, message.author, labels)} to you:`);
1604
1717
  const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels)}`;
1605
1718
  lines.push(TaMessageSource.line(NAME, `#${channel.name}${speaker}`));
@@ -1664,6 +1777,7 @@ var ChannelsText;
1664
1777
  `)[0];
1665
1778
  }
1666
1779
  })(ChannelsText ||= {});
1780
+ var CLOSING_NOTE = "This discussion has spent most of what the user allows it before they look in: conclude now. Hand on only if the work cannot go on without that member; the lead sums up what was concluded and what the user is to decide.";
1667
1781
  var NOTICE_RULE = [
1668
1782
  "A channel may have a notice, in the <context> block: what its members decided, agreed and are to do. Follow it.",
1669
1783
  `When the talk settles a decision or a convention, or adds, assigns or finishes a to-do, update it with update_channel_notice: the whole notice, short, under the headings ### ${NOTICE_HEADINGS.zh.join(" / ")} (### ${NOTICE_HEADINGS.en.join(" / ")} in English), in the language of the channel, to-dos as - [ ] or - [x] with who does them. The lead keeps it most; leave it for small talk.`