@celljs/ta-channels 4.19.0 → 4.21.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/host/index.mjs CHANGED
@@ -785,6 +785,12 @@ var FaceUtil;
785
785
  })(FaceUtil || (FaceUtil = {}));
786
786
 
787
787
  // web-src/channels-model.ts
788
+ var DEFAULT_LIMITS = { answer: 300000, channelDay: 5000000, allDay: 20000000 };
789
+ var LIMIT_CHOICES = {
790
+ answer: [1e5, 300000, 1e6],
791
+ channelDay: [2000000, 5000000, 20000000, 0],
792
+ allDay: [5000000, 20000000, 0]
793
+ };
788
794
  var NAME = "@celljs/ta-channels";
789
795
  var AGENT_MARK = "one of the agents of Ta";
790
796
  var MEMBER_CHANGES = ["lead", "remove", "mute", "unmute"];
@@ -796,16 +802,25 @@ var Keys;
796
802
  Keys.FOCUS = "focus";
797
803
  Keys.ANSWERED = "answered";
798
804
  Keys.CARDS = "cards";
805
+ Keys.LIMITS = "limits";
806
+ Keys.SPENT = "spent";
799
807
  Keys.MESSAGES = "messages/";
800
808
  Keys.messages = (channelId) => `${Keys.MESSAGES}${channelId}`;
801
809
  })(Keys ||= {});
802
810
  var USER = "user";
803
811
  var TA = "ta";
804
812
  var SYSTEM = "system";
805
- var MAX_HOPS = 3;
806
- var MAX_REPLIES = 8;
807
- var MAX_AGENT_REPLIES = 2;
808
- var STOP_NOTE = "The agents stopped handing on here, at the limit of a round; it is your turn.";
813
+ var BUDGETS = {
814
+ short: { tokens: 200000, replies: 10 },
815
+ normal: { tokens: 800000, replies: 30 },
816
+ long: { tokens: 3000000, replies: 100 }
817
+ };
818
+ var DEFAULT_BUDGET = "normal";
819
+ var WRAP_UP_AT = 0.7;
820
+ var EXTEND_BY = 0.5;
821
+ var WATCH_MS = 30000;
822
+ var STOP_NOTE = "The agents paused here, at the budget of the round: the user decides whether they go on. Do not post to make them go on unless the user asked for it.";
823
+ var WRAP_UP_NOTE = "The discussion paused at its budget, and the user asked you to sum it up: what the members concluded, where they still disagree, and what the user is to decide. Do not hand on to anyone; name nobody with @.";
809
824
  var MAX_MESSAGES = 200;
810
825
  var FACES = FACE_COUNT;
811
826
  var MAX_MEMBERS = 12;
@@ -819,25 +834,58 @@ var CARD_DAYS = 30;
819
834
  var ChannelsUtil;
820
835
  ((ChannelsUtil) => {
821
836
  function newRound() {
822
- return { total: 0, byAgent: {}, stopped: false };
837
+ return { total: 0, tokens: 0, stopped: false };
823
838
  }
824
839
  ChannelsUtil.newRound = newRound;
825
- function limit(round, targets, hops) {
826
- const allowed = [];
827
- const byAgent = { ...round.byAgent };
828
- let total = round.total;
829
- for (const id of targets) {
830
- if (hops < MAX_HOPS && total < MAX_REPLIES && (byAgent[id] ?? 0) < MAX_AGENT_REPLIES) {
831
- allowed.push(id);
832
- byAgent[id] = (byAgent[id] ?? 0) + 1;
833
- total++;
840
+ function budgetOf(channel) {
841
+ return channel?.budget && channel.budget in BUDGETS ? channel.budget : DEFAULT_BUDGET;
842
+ }
843
+ ChannelsUtil.budgetOf = budgetOf;
844
+ function limit(round, targets, budget, from, scale = 1) {
845
+ const fit = (extended2) => {
846
+ const { tokens, replies } = caps(budget, scale, extended2);
847
+ const open = (round.tokens ?? 0) < tokens;
848
+ const allowed2 = [];
849
+ let total2 = round.total;
850
+ for (const id of targets) {
851
+ if (open && total2 < replies) {
852
+ allowed2.push(id);
853
+ total2++;
854
+ }
834
855
  }
856
+ return { allowed: allowed2, total: total2 };
857
+ };
858
+ let extended = !!round.extended;
859
+ let { allowed, total } = fit(extended);
860
+ if (allowed.length < targets.length && round.progress && !extended) {
861
+ extended = true;
862
+ ({ allowed, total } = fit(true));
835
863
  }
836
- const cut = allowed.length < targets.length;
837
- const note = cut && !round.stopped;
838
- return { allowed, round: { total, byAgent, stopped: round.stopped || cut }, cut, note };
864
+ round = extended ? { ...round, extended } : round;
865
+ const cut = targets.filter((id) => !allowed.includes(id));
866
+ const pending = cut.length > 0 && from ? [...round.pending ?? [], { ...from, agentIds: cut }] : round.pending;
867
+ return { allowed, cut, round: { ...round, total, stopped: round.stopped || cut.length > 0, ...pending ? { pending } : {} } };
839
868
  }
840
869
  ChannelsUtil.limit = limit;
870
+ function used(round, budget, scale = 1) {
871
+ const limits = caps(budget, scale, !!round.extended);
872
+ return Math.max((round.tokens ?? 0) / limits.tokens, round.total / limits.replies);
873
+ }
874
+ ChannelsUtil.used = used;
875
+ function caps(budget, scale, extended) {
876
+ const { tokens, replies } = BUDGETS[budget];
877
+ const factor = scale * (extended ? 1 + EXTEND_BY : 1);
878
+ return { tokens: tokens * factor, replies: Math.max(1, Math.round(replies * factor)) };
879
+ }
880
+ ChannelsUtil.caps = caps;
881
+ function spent(before, after) {
882
+ if (!before || !after) {
883
+ return 0;
884
+ }
885
+ const delta = (key) => Math.max(0, (after[key] ?? 0) - (before[key] ?? 0));
886
+ return Math.round(delta("input") + delta("output") + delta("cacheWrite") + delta("cacheRead") / 10);
887
+ }
888
+ ChannelsUtil.spent = spent;
841
889
  function emptyTeam() {
842
890
  return { agents: [], channels: [] };
843
891
  }
@@ -1054,6 +1102,24 @@ var ChannelsUtil;
1054
1102
  delete channel.pinned;
1055
1103
  }
1056
1104
  }
1105
+ if (input.budget !== undefined) {
1106
+ if (typeof input.budget !== "string" || !(input.budget in BUDGETS)) {
1107
+ throw new Error(`The budget of a channel is one of ${Object.keys(BUDGETS).join(", ")}.`);
1108
+ }
1109
+ if (input.budget === DEFAULT_BUDGET) {
1110
+ delete channel.budget;
1111
+ } else {
1112
+ channel.budget = input.budget;
1113
+ }
1114
+ }
1115
+ if (input.dailyLimit === null) {
1116
+ delete channel.dailyLimit;
1117
+ } else if (input.dailyLimit !== undefined) {
1118
+ if (!LIMIT_CHOICES.channelDay.includes(input.dailyLimit)) {
1119
+ throw new Error(`The limit of a day of a channel is one of ${LIMIT_CHOICES.channelDay.join(", ")} tokens (0 for none), or null.`);
1120
+ }
1121
+ channel.dailyLimit = input.dailyLimit;
1122
+ }
1057
1123
  return { team: { ...team, channels: team.channels.map((other) => other.id === channel.id ? channel : other) }, channel, before };
1058
1124
  }
1059
1125
  ChannelsUtil.updateChannel = updateChannel;
@@ -1134,9 +1200,40 @@ var ChannelsUtil;
1134
1200
  delete agent.cwd;
1135
1201
  }
1136
1202
  }
1203
+ if (input.model !== undefined) {
1204
+ const model = checkModel(input.model);
1205
+ if (model) {
1206
+ agent.model = model;
1207
+ } else {
1208
+ delete agent.model;
1209
+ }
1210
+ }
1137
1211
  return { team: { ...team, agents: team.agents.map((other) => other.id === agent.id ? agent : other) }, agent, before };
1138
1212
  }
1139
1213
  ChannelsUtil.updateAgent = updateAgent;
1214
+ function checkModel(value) {
1215
+ if (value === "" || value === null) {
1216
+ return;
1217
+ }
1218
+ if (typeof value !== "string" || value.length > 200 || !/^[^/\s]+\/\S+$/.test(value)) {
1219
+ throw new Error("A model is named `<provider>/<model id>`.");
1220
+ }
1221
+ return value;
1222
+ }
1223
+ ChannelsUtil.checkModel = checkModel;
1224
+ function setChannelModel(team, input) {
1225
+ const channel = findChannel(team, typeof input.channel === "string" ? input.channel : "");
1226
+ if (!channel) {
1227
+ throw new Error(`No channel is ${String(input.channel)}.`);
1228
+ }
1229
+ let next = team;
1230
+ for (const id of channel.members) {
1231
+ next = updateAgent(next, { agent: id, model: input.model }).team;
1232
+ }
1233
+ const agents = next.agents.filter((agent) => channel.members.includes(agent.id));
1234
+ return { team: next, channel, agents };
1235
+ }
1236
+ ChannelsUtil.setChannelModel = setChannelModel;
1140
1237
  function removeAgent(team, ref) {
1141
1238
  const agent = findAgent(team, typeof ref === "string" ? ref : "");
1142
1239
  if (!agent) {
@@ -1535,12 +1632,13 @@ var ChannelsText;
1535
1632
  "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.",
1536
1633
  "Do the part of the work your role covers with your tools, then answer: your answer is posted to the channel as it is.",
1537
1634
  "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.",
1635
+ "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.",
1538
1636
  NOTICE_RULE
1539
1637
  ].join(`
1540
1638
  `);
1541
1639
  }
1542
1640
  ChannelsText.systemPrompt = systemPrompt;
1543
- function prompt(team, channel, history, message, agent) {
1641
+ function prompt(team, channel, history, message, agent, options = {}) {
1544
1642
  const labels = { user: "user", ta: "Ta" };
1545
1643
  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)}`);
1546
1644
  const before = history.filter((item) => item.id !== message.id && !item.failed && !item.notice).slice(-CONTEXT_MESSAGES);
@@ -1551,6 +1649,9 @@ var ChannelsText;
1551
1649
  if (before.length > 0) {
1552
1650
  lines.push("", "Recent messages:", ...before.map((item) => `${authorName(team, item.author, labels)}: ${item.text}`));
1553
1651
  }
1652
+ if (options.closing) {
1653
+ lines.push("", CLOSING_NOTE);
1654
+ }
1554
1655
  lines.push("", `${authorName(team, message.author, labels)} to you:`);
1555
1656
  const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels)}`;
1556
1657
  lines.push(TaMessageSource.line(NAME, `#${channel.name}${speaker}`));
@@ -1615,6 +1716,7 @@ var ChannelsText;
1615
1716
  `)[0];
1616
1717
  }
1617
1718
  })(ChannelsText ||= {});
1719
+ 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.";
1618
1720
  var NOTICE_RULE = [
1619
1721
  "A channel may have a notice, in the <context> block: what its members decided, agreed and are to do. Follow it.",
1620
1722
  `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.`
@@ -1731,6 +1833,135 @@ ${brief.trim()}`;
1731
1833
  HandOff.result = result;
1732
1834
  })(HandOff ||= {});
1733
1835
 
1836
+ // web-src/round-rules.ts
1837
+ var ChannelRounds;
1838
+ ((ChannelRounds) => {
1839
+ const SHORT = 20;
1840
+ const MIN_PAIRS = 8;
1841
+ const ALIKE = 0.8;
1842
+ const PING_PONG = 4;
1843
+ const NEW = 0.35;
1844
+ const CHANGES = new Set(["edit", "write", "delete", "move"]);
1845
+ function scale(watchedAt, pages, now) {
1846
+ if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
1847
+ return 2;
1848
+ }
1849
+ return pages === undefined || pages > 0 ? 1 : 0.5;
1850
+ }
1851
+ ChannelRounds.scale = scale;
1852
+ function idle(said, progress) {
1853
+ const last = said.at(-1);
1854
+ if (!last) {
1855
+ return;
1856
+ }
1857
+ const pairs = said.map((item) => pairsOf(item.text));
1858
+ const mine = pairs[pairs.length - 1];
1859
+ if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
1860
+ return "repeat";
1861
+ }
1862
+ const recent = said.slice(-3);
1863
+ if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
1864
+ return "agree";
1865
+ }
1866
+ const run = said.slice(-PING_PONG);
1867
+ const authors = new Set(run.map((item) => item.author));
1868
+ const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
1869
+ const start = said.length - PING_PONG;
1870
+ if (progress || start <= 0 || authors.size !== 2 || !alternate) {
1871
+ return;
1872
+ }
1873
+ const seen = new Set(pairs.slice(0, start).flat());
1874
+ for (const own of pairs.slice(start)) {
1875
+ const fresh = own.filter((pair) => !seen.has(pair)).length;
1876
+ if (own.length === 0 || fresh / own.length >= NEW) {
1877
+ return;
1878
+ }
1879
+ for (const pair of own) {
1880
+ seen.add(pair);
1881
+ }
1882
+ }
1883
+ return "pingPong";
1884
+ }
1885
+ ChannelRounds.idle = idle;
1886
+ function day(now) {
1887
+ const date = new Date(now);
1888
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
1889
+ }
1890
+ ChannelRounds.day = day;
1891
+ function limits(stored) {
1892
+ const given = stored ?? {};
1893
+ const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
1894
+ return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
1895
+ }
1896
+ ChannelRounds.limits = limits;
1897
+ function today(stored, now) {
1898
+ const current = day(now);
1899
+ return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
1900
+ }
1901
+ ChannelRounds.today = today;
1902
+ function spend(stored, channelId, tokens, now) {
1903
+ const current = today(stored, now);
1904
+ return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
1905
+ }
1906
+ ChannelRounds.spend = spend;
1907
+ function held(spent, limits2, channelId, hops, granted = false) {
1908
+ if (granted) {
1909
+ return;
1910
+ }
1911
+ if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
1912
+ return "all";
1913
+ }
1914
+ if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
1915
+ return "channel";
1916
+ }
1917
+ return;
1918
+ }
1919
+ ChannelRounds.held = held;
1920
+ function changedFiles(entries) {
1921
+ for (const entry of entries) {
1922
+ const message = entry?.message;
1923
+ if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
1924
+ continue;
1925
+ }
1926
+ for (const part of message.content) {
1927
+ if (part?.type !== "toolCall") {
1928
+ continue;
1929
+ }
1930
+ if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
1931
+ return true;
1932
+ }
1933
+ }
1934
+ }
1935
+ return false;
1936
+ }
1937
+ ChannelRounds.changedFiles = changedFiles;
1938
+ function units(text) {
1939
+ return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
1940
+ }
1941
+ function pairsOf(text) {
1942
+ const words = units(text);
1943
+ return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
1944
+ }
1945
+ function alike(a, b) {
1946
+ if (a.length === 0 || b.length === 0) {
1947
+ return 0;
1948
+ }
1949
+ const left = new Map;
1950
+ for (const pair of a) {
1951
+ left.set(pair, (left.get(pair) ?? 0) + 1);
1952
+ }
1953
+ let common = 0;
1954
+ for (const pair of b) {
1955
+ const n = left.get(pair) ?? 0;
1956
+ if (n > 0) {
1957
+ left.set(pair, n - 1);
1958
+ common++;
1959
+ }
1960
+ }
1961
+ return 2 * common / (a.length + b.length);
1962
+ }
1963
+ })(ChannelRounds ||= {});
1964
+
1734
1965
  // ../ta-protocol/esm/common/access-protocol.js
1735
1966
  var TaAccessServer = Symbol("TaAccessServer");
1736
1967
  var TA_SIGN_IN_PATH = "/sign-in";
@@ -1789,6 +2020,22 @@ var TaHostUtil;
1789
2020
  }
1790
2021
  TaHostUtil2.role = role;
1791
2022
  })(TaHostUtil || (TaHostUtil = {}));
2023
+ var TA_DOUBLE_LOOK = {
2024
+ name: "@celljs/ta-web",
2025
+ key: "assistant.species",
2026
+ given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
2027
+ };
2028
+ var TaDoubleLookUtil;
2029
+ (function(TaDoubleLookUtil2) {
2030
+ function given(id) {
2031
+ let hash = 2166136261;
2032
+ for (let i = 0;i < id.length; i++) {
2033
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
2034
+ }
2035
+ return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
2036
+ }
2037
+ TaDoubleLookUtil2.given = given;
2038
+ })(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
1792
2039
  var TA_ASK_ENTRY = "ta-ask";
1793
2040
  var TaAskUtil;
1794
2041
  (function(TaAskUtil2) {
@@ -2626,6 +2873,7 @@ var TaRelayServer = Symbol("TaRelayServer");
2626
2873
  var TaRemoteServer = Symbol("TaRemoteServer");
2627
2874
  // ../ta-protocol/esm/common/room-protocol.js
2628
2875
  var TaRoomServer = Symbol("TaRoomServer");
2876
+ var TA_PICTURE = { key: "picture:", maxChars: 16 * 1024 };
2629
2877
  var TaRoomWatchUtil;
2630
2878
  (function(TaRoomWatchUtil2) {
2631
2879
  function of(messages, state) {
@@ -2833,6 +3081,7 @@ class TeamStore {
2833
3081
  waiting = new Map;
2834
3082
  opening = new Map;
2835
3083
  settling = new Set;
3084
+ watched = new Map;
2836
3085
  options;
2837
3086
  disposed = false;
2838
3087
  constructor(host, options = {}) {
@@ -2934,7 +3183,7 @@ class TeamStore {
2934
3183
  }
2935
3184
  }
2936
3185
  const cwd = agent.cwd ?? (await this.host.getServerInfo()).cwd;
2937
- const options = { cwd, appendSystemPrompt: ChannelsText.systemPrompt(agent), group: NAME };
3186
+ const options = { cwd, appendSystemPrompt: ChannelsText.systemPrompt(agent), group: NAME, ...agent.model ? { model: agent.model } : {} };
2938
3187
  if (agent.sessionFile) {
2939
3188
  try {
2940
3189
  return (await this.host.openSession({ ...options, sessionFile: agent.sessionFile })).sessionId;
@@ -2952,13 +3201,21 @@ class TeamStore {
2952
3201
  }
2953
3202
  return sessionId;
2954
3203
  }
2955
- async settled(sessionId, before) {
3204
+ async switchModel(agent) {
3205
+ const open = agent.model && agent.sessionFile && (await this.host.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
3206
+ if (open && agent.model && open.model !== agent.model) {
3207
+ const slash = agent.model.indexOf("/");
3208
+ await this.host.setModel(open.sessionId, agent.model.slice(0, slash), agent.model.slice(slash + 1));
3209
+ }
3210
+ }
3211
+ async settled(sessionId, before, poll) {
2956
3212
  const start = Date.now();
2957
3213
  for (;; ) {
2958
3214
  const state = await this.host.getState(sessionId);
2959
3215
  if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
2960
3216
  return;
2961
3217
  }
3218
+ await poll?.();
2962
3219
  if (Date.now() - start > this.options.timeoutMs) {
2963
3220
  throw new Error("No answer in time; the agent may still be working in its session.");
2964
3221
  }
@@ -2991,6 +3248,11 @@ class TeamStore {
2991
3248
  await this.set(Keys.messages(channelId), messages);
2992
3249
  return message;
2993
3250
  }
3251
+ async replace(channelId, message) {
3252
+ const messages = (await this.messagesOf(channelId)).map((item) => item.id === message.id ? message : item);
3253
+ this.messages.set(channelId, messages);
3254
+ await this.set(Keys.messages(channelId), messages);
3255
+ }
2994
3256
  async saveTeam(team) {
2995
3257
  this.team = team;
2996
3258
  this.linkSessions();
@@ -3027,6 +3289,48 @@ class TeamStore {
3027
3289
  }
3028
3290
  }
3029
3291
  }
3292
+ watch(channelRef) {
3293
+ this.watched.set(ChannelsUtil.channelOf(this.team, channelRef).id, Date.now());
3294
+ }
3295
+ scale(channelId) {
3296
+ return ChannelRounds.scale(this.watched.get(channelId), this.host.presence?.().pages, Date.now());
3297
+ }
3298
+ progressed(channelId, round) {
3299
+ const rounds = Object.entries(this.queue.rounds).map(([id, entry]) => entry.channelId === channelId && (!round || id === round) ? [id, { ...entry, round: { ...entry.round, progress: true } }] : [id, entry]);
3300
+ this.queue = { ...this.queue, rounds: Object.fromEntries(rounds) };
3301
+ }
3302
+ async leaf(sessionId) {
3303
+ try {
3304
+ return (await this.host.getEntries?.(sessionId))?.leafId ?? null;
3305
+ } catch {
3306
+ return;
3307
+ }
3308
+ }
3309
+ async changedSince(sessionId, leaf) {
3310
+ if (leaf === undefined) {
3311
+ return false;
3312
+ }
3313
+ try {
3314
+ const result = await this.host.getEntries?.(sessionId, leaf ?? undefined);
3315
+ return ChannelRounds.changedFiles(result?.entries ?? []);
3316
+ } catch {
3317
+ return false;
3318
+ }
3319
+ }
3320
+ spend(round, tokens) {
3321
+ const entry = this.queue.rounds[round];
3322
+ if (entry && tokens > 0) {
3323
+ const spent = { ...entry.round, tokens: (entry.round.tokens ?? 0) + tokens };
3324
+ this.queue = { ...this.queue, rounds: { ...this.queue.rounds, [round]: { ...entry, round: spent } } };
3325
+ }
3326
+ }
3327
+ async tokens(sessionId) {
3328
+ try {
3329
+ return (await this.host.getSessionStats?.(sessionId))?.tokens;
3330
+ } catch {
3331
+ return;
3332
+ }
3333
+ }
3030
3334
  async setWorking(channelId, agentId, on) {
3031
3335
  const others = (this.working[channelId] ?? []).filter((id) => id !== agentId);
3032
3336
  this.working = { ...this.working, [channelId]: on ? [...others, agentId] : others };
@@ -3040,8 +3344,150 @@ class TeamStore {
3040
3344
  }
3041
3345
  }
3042
3346
 
3347
+ // web-src/team-answers.ts
3348
+ var CAP_EVERY = 5;
3349
+
3350
+ class TeamAnswers extends TeamStore {
3351
+ daily;
3352
+ async answer(channel, message, agentId, by, closing = false) {
3353
+ await this.setWorking(channel.id, agentId, true);
3354
+ let text;
3355
+ let tokens = 0;
3356
+ let changed = false;
3357
+ let over = false;
3358
+ let failed = false;
3359
+ try {
3360
+ const team = this.host.team;
3361
+ const ask = () => this.ask(channel, message, agentId, closing);
3362
+ const asked = await (by && team ? team.actAs(by, ask) : ask());
3363
+ text = asked.text;
3364
+ tokens = asked.tokens;
3365
+ changed = asked.changed;
3366
+ over = asked.over;
3367
+ } catch (error) {
3368
+ text = error instanceof Error ? error.message : String(error);
3369
+ failed = true;
3370
+ } finally {
3371
+ await this.setAnswered(agentId, Date.now());
3372
+ await this.setWorking(channel.id, agentId, false);
3373
+ }
3374
+ const posted = await this.append(channel.id, {
3375
+ id: ChannelsUtil.newId("message"),
3376
+ author: agentId,
3377
+ text,
3378
+ at: Date.now(),
3379
+ replyTo: message.id,
3380
+ failed,
3381
+ ...over ? { overBudget: true } : {}
3382
+ });
3383
+ return { message: posted, tokens, changed };
3384
+ }
3385
+ async ask(channel, message, agentId, closing = false) {
3386
+ const agent = this.team.agents.find((candidate) => candidate.id === agentId);
3387
+ if (!agent) {
3388
+ throw new Error(`The agent ${agentId} is gone.`);
3389
+ }
3390
+ const sessionId = await this.session(agent);
3391
+ const before = await this.host.getState(sessionId);
3392
+ const counted = await this.tokens(sessionId);
3393
+ const leaf = await this.leaf(sessionId);
3394
+ const history = await this.messagesOf(channel.id);
3395
+ const input = {
3396
+ clientMessageId: `${message.id}:${agent.id}`,
3397
+ message: ChannelsText.prompt(this.team, channel, history, message, agent, { closing })
3398
+ };
3399
+ await this.host.prompt(sessionId, input);
3400
+ const cap = (await this.limits()).answer;
3401
+ let over = false;
3402
+ let polls = 0;
3403
+ await this.settled(sessionId, before.messageCount, async () => {
3404
+ polls++;
3405
+ if (over || cap <= 0 || !this.host.abort || polls !== 1 && polls % CAP_EVERY !== 0) {
3406
+ return;
3407
+ }
3408
+ if (ChannelsUtil.spent(counted, await this.tokens(sessionId)) > cap) {
3409
+ over = true;
3410
+ await this.host.abort(sessionId);
3411
+ }
3412
+ });
3413
+ const tokens = ChannelsUtil.spent(counted, await this.tokens(sessionId));
3414
+ const changed = await this.changedSince(sessionId, leaf);
3415
+ const { text } = await this.host.getLastAssistantText(sessionId);
3416
+ if (!text?.trim() && !over) {
3417
+ throw new Error(`${agent.name} gave no answer.`);
3418
+ }
3419
+ return { text: text?.trim() || "…", tokens, changed, over };
3420
+ }
3421
+ async limits() {
3422
+ return ChannelRounds.limits(await this.get(Keys.LIMITS));
3423
+ }
3424
+ async setLimits(input) {
3425
+ const limits = ChannelRounds.limits({ ...await this.limits(), ...input ?? {} });
3426
+ await this.set(Keys.LIMITS, limits);
3427
+ return limits;
3428
+ }
3429
+ async today() {
3430
+ this.daily = ChannelRounds.today(this.daily ?? await this.get(Keys.SPENT), Date.now());
3431
+ return this.daily;
3432
+ }
3433
+ async spendToday(channelId, tokens) {
3434
+ if (tokens > 0) {
3435
+ this.daily = ChannelRounds.spend(await this.today(), channelId, tokens, Date.now());
3436
+ await this.set(Keys.SPENT, this.daily);
3437
+ }
3438
+ }
3439
+ async held(channel, hops, granted) {
3440
+ const limits = await this.limits();
3441
+ const own = channel.dailyLimit === undefined ? limits : { ...limits, channelDay: channel.dailyLimit };
3442
+ const held = ChannelRounds.held(await this.today(), own, channel.id, hops, granted);
3443
+ if (held === "all") {
3444
+ await this.tellStopped();
3445
+ }
3446
+ return held;
3447
+ }
3448
+ async tellStopped() {
3449
+ const spent = await this.today();
3450
+ if (spent.told || !this.host.callPackageHost) {
3451
+ return;
3452
+ }
3453
+ this.daily = { ...spent, told: true };
3454
+ await this.set(Keys.SPENT, this.daily);
3455
+ const tokens = new Intl.NumberFormat(HandOff.serverLanguage(), { notation: "compact", maximumFractionDigits: 1 }).format(spent.total);
3456
+ const words2 = TaLanguageUtil.pick(HandOff.serverLanguage(), {
3457
+ "zh-CN": {
3458
+ title: "群聊今天的用量到了上限",
3459
+ text: `所有群聊的智能体已暂停(今天约 ${tokens} tokens)。在群里点“继续讨论”可以让这一轮接着做,或在设置里调整上限。`
3460
+ },
3461
+ "zh-TW": {
3462
+ title: "群聊今天的用量到了上限",
3463
+ text: `所有群聊的智能體已暫停(今天約 ${tokens} tokens)。在群裡點「繼續討論」可以讓這一輪接著做,或在設定裡調整上限。`
3464
+ },
3465
+ "en-US": {
3466
+ title: "Group chats reached the limit of the day",
3467
+ text: `The agents of all group chats paused (about ${tokens} tokens today). Go on in a group chat to let its round continue, or change the limit in the settings.`
3468
+ },
3469
+ "ja-JP": {
3470
+ title: "グループチャットが今日の上限に達しました",
3471
+ text: `すべてのグループのエージェントを一時停止しました(今日 約 ${tokens} トークン)。グループで「続ける」を押すとこのラウンドを続けられます。上限は設定で変更できます。`
3472
+ }
3473
+ });
3474
+ await this.host.callPackageHost("@celljs/ta-notify", "notify", [
3475
+ {
3476
+ from: NAME,
3477
+ id: `daily-${spent.day}`,
3478
+ level: "ask",
3479
+ title: words2.title,
3480
+ text: words2.text,
3481
+ view: `${NAME}/channel`
3482
+ }
3483
+ ]).catch(() => {
3484
+ return;
3485
+ });
3486
+ }
3487
+ }
3488
+
3043
3489
  // web-src/team.ts
3044
- class TeamService extends TeamStore {
3490
+ class TeamService extends TeamAnswers {
3045
3491
  async start() {
3046
3492
  this.team = await this.get(Keys.TEAM) ?? ChannelsUtil.emptyTeam();
3047
3493
  this.shareWithMembers();
@@ -3095,6 +3541,9 @@ class TeamService extends TeamStore {
3095
3541
  async updateAgent(input) {
3096
3542
  const cwd = input.cwd === undefined ? undefined : ChannelsUtil.directory(input.cwd) ?? (await this.host.getServerInfo()).cwd;
3097
3543
  const { team, agent, before } = ChannelsUtil.updateAgent(this.team, cwd === undefined ? input : { ...input, cwd });
3544
+ if (agent.model !== before.model) {
3545
+ await this.switchModel(agent);
3546
+ }
3098
3547
  await this.saveTeam(team);
3099
3548
  if (agent.name !== before.name && agent.sessionFile) {
3100
3549
  const open = (await this.host.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
@@ -3106,12 +3555,23 @@ class TeamService extends TeamStore {
3106
3555
  }
3107
3556
  return agent;
3108
3557
  }
3558
+ async setChannelModel(input) {
3559
+ const { team, channel, agents } = ChannelsUtil.setChannelModel(this.team, input);
3560
+ for (const agent of agents) {
3561
+ await this.switchModel(agent);
3562
+ }
3563
+ await this.saveTeam(team);
3564
+ return channel;
3565
+ }
3109
3566
  async setNotice(input) {
3110
3567
  const { team, channel, changed } = ChannelsUtil.setNotice(this.team, input);
3111
3568
  if (input.by !== USER && input.by !== TA && !channel.members.includes(input.by)) {
3112
3569
  throw new Error(`You are not in #${channel.name}: only its members keep its notice.`);
3113
3570
  }
3114
3571
  if (changed) {
3572
+ if (input.by !== USER && input.by !== TA) {
3573
+ this.progressed(channel.id);
3574
+ }
3115
3575
  await this.saveTeam(team);
3116
3576
  await this.append(channel.id, {
3117
3577
  id: ChannelsUtil.newId("message"),
@@ -3229,6 +3689,7 @@ class TeamService extends TeamStore {
3229
3689
  mark: agent.mark,
3230
3690
  face: faces.get(agent.id) ?? 0,
3231
3691
  ...agent.cwd ? { cwd: agent.cwd } : {},
3692
+ ...agent.model ? { model: agent.model } : {},
3232
3693
  ...agent.temporary ? { temporary: true } : {}
3233
3694
  }));
3234
3695
  }
@@ -3253,10 +3714,18 @@ class TeamService extends TeamStore {
3253
3714
  return this.resetAgent(request.agent);
3254
3715
  case "updateAgent":
3255
3716
  return this.updateAgent(request);
3717
+ case "setChannelModel":
3718
+ return this.setChannelModel(request);
3256
3719
  case "deleteAgent":
3257
3720
  return this.deleteAgent(request.agent);
3258
3721
  case "post":
3259
3722
  return (await this.post(String(request.channel ?? ""), USER, String(request.text ?? ""), this.poster())).message;
3723
+ case "resumeRound":
3724
+ return this.resumeRound(request.channel, request.message, request.how, this.poster());
3725
+ case "watch":
3726
+ return this.watch(request.channel);
3727
+ case "setLimits":
3728
+ return this.setLimits(request.limits);
3260
3729
  case "setNotice":
3261
3730
  return this.setNotice({ channel: request.channel, text: request.text, by: USER });
3262
3731
  case "shareAgent":
@@ -3279,18 +3748,19 @@ class TeamService extends TeamStore {
3279
3748
  }
3280
3749
  }
3281
3750
  async handOn(channel, message, hops, round) {
3751
+ await this.enqueue(channel, message.id, ChannelsText.targets(this.team, channel, message), hops, round);
3752
+ }
3753
+ async enqueue(channel, messageId, targets, hops, round) {
3282
3754
  const current = this.queue.rounds[round]?.round ?? ChannelsUtil.newRound();
3283
3755
  const messages = await this.messagesOf(channel.id);
3284
- const targets = ChannelsText.targets(this.team, channel, message).filter((agentId) => !this.queue.jobs.some((job) => job.messageId === message.id && job.agentId === agentId) && !messages.some((item) => item.replyTo === message.id && item.author === agentId));
3285
- const limited = ChannelsUtil.limit(current, targets, hops);
3286
- const jobs = limited.allowed.map((agentId) => ({
3287
- id: ChannelsUtil.newId("job"),
3288
- channelId: channel.id,
3289
- messageId: message.id,
3290
- agentId,
3291
- hops,
3292
- round
3293
- }));
3756
+ const left = targets.filter((agentId) => !this.queue.jobs.some((job) => job.messageId === messageId && job.agentId === agentId) && !messages.some((item) => item.replyTo === messageId && item.author === agentId));
3757
+ const from = { messageId, hops };
3758
+ const daily = left.length > 0 && !current.idle ? await this.held(channel, hops, current.granted) : undefined;
3759
+ const limited = (current.idle || daily) && left.length > 0 ? {
3760
+ allowed: [],
3761
+ round: { ...current, stopped: true, ...daily ? { daily } : {}, pending: [...current.pending ?? [], { ...from, agentIds: left }] }
3762
+ } : ChannelsUtil.limit(current, left, ChannelsUtil.budgetOf(channel), from, this.scale(channel.id));
3763
+ const jobs = limited.allowed.map((agentId) => ({ id: ChannelsUtil.newId("job"), channelId: channel.id, messageId, agentId, hops, round }));
3294
3764
  this.queue = {
3295
3765
  jobs: [...this.queue.jobs, ...jobs],
3296
3766
  rounds: { ...this.queue.rounds, [round]: { channelId: channel.id, round: limited.round } }
@@ -3300,6 +3770,46 @@ class TeamService extends TeamStore {
3300
3770
  this.run(job);
3301
3771
  }
3302
3772
  }
3773
+ async resumeRound(channelRef, messageRef, how, poster = {}) {
3774
+ if (how !== "continue" && how !== "wrapUp") {
3775
+ throw new Error("A round goes on with continue or wrapUp.");
3776
+ }
3777
+ const channel = ChannelsUtil.channelOf(this.team, channelRef);
3778
+ const line = (await this.messagesOf(channel.id)).find((item) => item.id === messageRef && item.author === SYSTEM);
3779
+ if (!line?.stop) {
3780
+ throw new Error("No round stopped there.");
3781
+ }
3782
+ if (line.stop.resumed) {
3783
+ throw new Error("That round went on already.");
3784
+ }
3785
+ const muted = channel.muted ?? [];
3786
+ const lead = channel.members.find((id) => !muted.includes(id));
3787
+ if (how === "wrapUp" && !lead) {
3788
+ throw new Error(`Nobody in #${channel.name} answers now.`);
3789
+ }
3790
+ const message = { ...line, ...poster, stop: { ...line.stop, resumed: how } };
3791
+ await this.replace(channel.id, message);
3792
+ const round = line.id;
3793
+ const done = new Promise((resolve) => this.waitingFor(round).waiters.push(resolve));
3794
+ if (how === "wrapUp" && lead) {
3795
+ const job = { id: ChannelsUtil.newId("job"), channelId: channel.id, messageId: line.id, agentId: lead, hops: 0, round, wrapUp: true };
3796
+ const entry = ChannelsUtil.limit(ChannelsUtil.newRound(), [lead], ChannelsUtil.budgetOf(channel)).round;
3797
+ this.queue = { jobs: [...this.queue.jobs, job], rounds: { ...this.queue.rounds, [round]: { channelId: channel.id, round: entry } } };
3798
+ await this.set(Keys.QUEUE, this.queue);
3799
+ this.run(job);
3800
+ } else {
3801
+ this.queue = {
3802
+ ...this.queue,
3803
+ rounds: { ...this.queue.rounds, [round]: { channelId: channel.id, round: { ...ChannelsUtil.newRound(), granted: true } } }
3804
+ };
3805
+ for (const pending of line.stop.pending) {
3806
+ const members = pending.agentIds.filter((id) => channel.members.includes(id) && !muted.includes(id));
3807
+ await this.enqueue(channel, pending.messageId, members, pending.hops, round);
3808
+ }
3809
+ }
3810
+ await this.settle(round);
3811
+ return { message, done };
3812
+ }
3303
3813
  run(job) {
3304
3814
  if (this.started.has(job.id)) {
3305
3815
  return;
@@ -3320,14 +3830,24 @@ class TeamService extends TeamStore {
3320
3830
  let reply = messages.find((candidate) => candidate.replyTo === job.messageId && candidate.author === job.agentId);
3321
3831
  if (!reply && channel && message) {
3322
3832
  const by = messages.find((candidate) => candidate.id === job.round)?.by;
3323
- reply = await this.answer(channel, message, job.agentId, by);
3833
+ const round = this.queue.rounds[job.round]?.round;
3834
+ const closing = !job.wrapUp && !!round && ChannelsUtil.used(round, ChannelsUtil.budgetOf(channel), this.scale(channel.id)) >= WRAP_UP_AT;
3835
+ const asked = job.wrapUp ? { ...message, text: WRAP_UP_NOTE } : message;
3836
+ const answered = await this.answer(channel, asked, job.agentId, by, closing);
3837
+ reply = answered.message;
3838
+ this.spend(job.round, answered.tokens);
3839
+ await this.spendToday(channel.id, answered.tokens);
3840
+ if (answered.changed) {
3841
+ this.progressed(channel.id, job.round);
3842
+ }
3843
+ this.checkIdle(job.round, reply);
3324
3844
  }
3325
3845
  if (this.disposed) {
3326
3846
  return;
3327
3847
  }
3328
3848
  if (reply) {
3329
3849
  this.waitingFor(job.round).replies.push(reply);
3330
- if (!reply.failed && channel) {
3850
+ if (!reply.failed && !reply.overBudget && channel && !job.wrapUp) {
3331
3851
  await this.handOn(channel, reply, job.hops + 1, job.round);
3332
3852
  }
3333
3853
  }
@@ -3335,6 +3855,17 @@ class TeamService extends TeamStore {
3335
3855
  await this.set(Keys.QUEUE, this.queue);
3336
3856
  await this.settle(job.round);
3337
3857
  }
3858
+ checkIdle(round, reply) {
3859
+ const entry = this.queue.rounds[round];
3860
+ if (!entry || entry.round.idle || reply.failed) {
3861
+ return;
3862
+ }
3863
+ const said = [...this.waitingFor(round).replies, reply].filter((item) => item.author !== SYSTEM && !item.failed);
3864
+ const idle = ChannelRounds.idle(said, !!entry.round.progress);
3865
+ if (idle) {
3866
+ this.queue = { ...this.queue, rounds: { ...this.queue.rounds, [round]: { ...entry, round: { ...entry.round, idle } } } };
3867
+ }
3868
+ }
3338
3869
  async settle(round) {
3339
3870
  const entry = this.queue.rounds[round];
3340
3871
  if (!entry || this.settling.has(round) || this.queue.jobs.some((job) => job.round === round)) {
@@ -3356,7 +3887,15 @@ class TeamService extends TeamStore {
3356
3887
  author: SYSTEM,
3357
3888
  text: STOP_NOTE,
3358
3889
  at: Date.now(),
3359
- replyTo: round
3890
+ replyTo: round,
3891
+ stop: {
3892
+ replies: entry.round.total,
3893
+ tokens: entry.round.tokens ?? 0,
3894
+ pending: entry.round.pending ?? [],
3895
+ ...entry.round.idle ? { idle: entry.round.idle } : {},
3896
+ ...entry.round.extended ? { extended: true } : {},
3897
+ ...entry.round.daily ? { daily: entry.round.daily } : {}
3898
+ }
3360
3899
  }));
3361
3900
  }
3362
3901
  const { [round]: _ended, ...rounds } = this.queue.rounds;
@@ -3367,39 +3906,6 @@ class TeamService extends TeamStore {
3367
3906
  resolve(waiting.replies);
3368
3907
  }
3369
3908
  }
3370
- async answer(channel, message, agentId, by) {
3371
- await this.setWorking(channel.id, agentId, true);
3372
- let text;
3373
- let failed = false;
3374
- try {
3375
- const team = this.host.team;
3376
- text = await (by && team ? team.actAs(by, () => this.ask(channel, message, agentId)) : this.ask(channel, message, agentId));
3377
- } catch (error) {
3378
- text = error instanceof Error ? error.message : String(error);
3379
- failed = true;
3380
- } finally {
3381
- await this.setAnswered(agentId, Date.now());
3382
- await this.setWorking(channel.id, agentId, false);
3383
- }
3384
- return this.append(channel.id, { id: ChannelsUtil.newId("message"), author: agentId, text, at: Date.now(), replyTo: message.id, failed });
3385
- }
3386
- async ask(channel, message, agentId) {
3387
- const agent = this.team.agents.find((candidate) => candidate.id === agentId);
3388
- if (!agent) {
3389
- throw new Error(`The agent ${agentId} is gone.`);
3390
- }
3391
- const sessionId = await this.session(agent);
3392
- const before = await this.host.getState(sessionId);
3393
- const history = await this.messagesOf(channel.id);
3394
- const input = { clientMessageId: `${message.id}:${agent.id}`, message: ChannelsText.prompt(this.team, channel, history, message, agent) };
3395
- await this.host.prompt(sessionId, input);
3396
- await this.settled(sessionId, before.messageCount);
3397
- const { text } = await this.host.getLastAssistantText(sessionId);
3398
- if (!text?.trim()) {
3399
- throw new Error(`${agent.name} gave no answer.`);
3400
- }
3401
- return text.trim();
3402
- }
3403
3909
  listChannels() {
3404
3910
  return this.team.channels.map((channel) => ({
3405
3911
  id: channel.id,