@celljs/ta-channels 4.22.0 → 4.23.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/web/index.js CHANGED
@@ -144,6 +144,11 @@ var TaImageNote;
144
144
  var TaImageSize;
145
145
  (function(TaImageSize2) {
146
146
  const JPEG_BYTES = 256 * 1024;
147
+ function type(bytes) {
148
+ const at = (offset, ...values) => values.every((value, index) => bytes[offset + index] === value);
149
+ return at(0, 255, 216, 255) ? "image/jpeg" : at(0, 137, 80, 78, 71) ? "image/png" : at(0, 71, 73, 70, 56) ? "image/gif" : at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80) ? "image/webp" : undefined;
150
+ }
151
+ TaImageSize2.type = type;
147
152
  function of(base64) {
148
153
  var _a, _b, _c;
149
154
  let bytes;
@@ -731,6 +736,9 @@ var BUDGETS = {
731
736
  long: { tokens: 3000000, replies: 100 }
732
737
  };
733
738
  var DEFAULT_BUDGET = "normal";
739
+ var REPLIES = ["mentioned", "lead", "all"];
740
+ var DEFAULT_REPLY = "lead";
741
+ var PASS = "PASS";
734
742
  var EXTEND_BY = 0.5;
735
743
  var WATCH_MS = 30000;
736
744
  var MAX_MESSAGES = 200;
@@ -745,6 +753,16 @@ var NOTICE_HEADINGS = { zh: ["决定", "约定", "待办"], en: ["Decisions", "C
745
753
  // web-src/channels-util.ts
746
754
  var ChannelsUtil;
747
755
  ((ChannelsUtil) => {
756
+ function may(team) {
757
+ const given = team.may;
758
+ return {
759
+ create: !given || given.create,
760
+ agent: (id) => !given || given.agents.includes(id),
761
+ manage: (id) => !given || given.manage.includes(id),
762
+ edit: (id) => !given || given.edit.includes(id)
763
+ };
764
+ }
765
+ ChannelsUtil.may = may;
748
766
  function newRound() {
749
767
  return { total: 0, tokens: 0, stopped: false };
750
768
  }
@@ -1014,16 +1032,22 @@ var ChannelsUtil;
1014
1032
  delete channel.pinned;
1015
1033
  }
1016
1034
  }
1017
- if (input.budget !== undefined) {
1018
- if (typeof input.budget !== "string" || !(input.budget in BUDGETS)) {
1019
- throw new Error(`The budget of a channel is one of ${Object.keys(BUDGETS).join(", ")}.`);
1035
+ const choose = (key, choices, fallback, what) => {
1036
+ const value = input[key];
1037
+ if (value === undefined) {
1038
+ return;
1039
+ }
1040
+ if (typeof value !== "string" || !choices.includes(value)) {
1041
+ throw new Error(`${what} is one of ${choices.join(", ")}.`);
1020
1042
  }
1021
- if (input.budget === DEFAULT_BUDGET) {
1022
- delete channel.budget;
1043
+ if (value === fallback) {
1044
+ delete channel[key];
1023
1045
  } else {
1024
- channel.budget = input.budget;
1046
+ channel[key] = value;
1025
1047
  }
1026
- }
1048
+ };
1049
+ choose("budget", Object.keys(BUDGETS), DEFAULT_BUDGET, "The budget of a channel");
1050
+ choose("reply", REPLIES, DEFAULT_REPLY, "Who answers what names nobody in a channel");
1027
1051
  if (input.dailyLimit === null) {
1028
1052
  delete channel.dailyLimit;
1029
1053
  } else if (input.dailyLimit !== undefined) {
@@ -1355,8 +1379,9 @@ var JA = {
1355
1379
  topic: "トピック",
1356
1380
  members: "メンバー",
1357
1381
  addMembers: "メンバーを追加",
1358
- makeExtension: "拡張機能にする",
1359
- makeExtensionDetail: "ここで作成されたものを工具にする",
1382
+ mentionMember: "メンバー",
1383
+ makeExtension: "保存",
1384
+ makeExtensionDetail: "ここで決めたやり方をワンタップで再利用できるように保存",
1360
1385
  makeExtensionAsk: "このグループチャットで作成された事項を拡張機能にする(ta-package スキルで)、将来は 1 クリックで再利用可能",
1361
1386
  add: "追加",
1362
1387
  allMembers: "すべてのエージェントがこのグループチャットに既に含まれています",
@@ -1366,6 +1391,7 @@ var JA = {
1366
1391
  back: "戻る",
1367
1392
  send: "送信",
1368
1393
  you: "あなた",
1394
+ picture: "[画像]",
1369
1395
  owner: "オーナー",
1370
1396
  ta: "Ta",
1371
1397
  lead: "リーダー",
@@ -1376,6 +1402,8 @@ var JA = {
1376
1402
  pick: "グループチャットを選択",
1377
1403
  quiet: "まだメッセージがありません。@ で指定したエージェントが答えます。",
1378
1404
  placeholder: "{channel} に送信;@ でメンバーを指定",
1405
+ placeholderLead: "{channel} に送信;@ なしは{lead}が回答",
1406
+ placeholderAll: "{channel} に送信;誰でも回答できます",
1379
1407
  answering: "{name} が回答中",
1380
1408
  failed: "回答がありません",
1381
1409
  mention: "@{name}",
@@ -1402,6 +1430,10 @@ var JA = {
1402
1430
  budgetShortWord: "短い",
1403
1431
  budgetNormalWord: "標準",
1404
1432
  budgetLongWord: "長い",
1433
+ replyHead: "@ なしのとき",
1434
+ replyMentionedWord: "@ のみ",
1435
+ replyLeadWord: "リーダー",
1436
+ replyAllWord: "全員",
1405
1437
  dailyLimit: "1日の上限",
1406
1438
  dailySpent: "今日 {spent}",
1407
1439
  dailySpentOf: "今日 {spent} / {limit}",
@@ -1568,6 +1600,11 @@ var JA = {
1568
1600
  shareCard: "カードを共有…",
1569
1601
  cardTitle: "{name} のカード",
1570
1602
  cardKind: "エージェントカード",
1603
+ profileTitle: "エージェントのプロフィール",
1604
+ noAgentOpen: "エージェントとの会話を開くと、ここにプロフィールが表示されます",
1605
+ sendMessage: "メッセージ",
1606
+ workDir: "作業ディレクトリ",
1607
+ deleteAgentLong: "エージェントを削除",
1571
1608
  cardGets: "相手は自分のエージェントとして追加し、自分のプロジェクトに合わせて役割を調整します",
1572
1609
  cardHint: "役割のみ(秘密のように見えるものは除去)、ディレクトリと会話は含まれません。リンクは 30 日間有効で、このコンピューターがオフでも開けます。",
1573
1610
  cardRedacted: "役割に {n} 箇所の秘密のように見えるものが除去されました。",
@@ -1597,8 +1634,9 @@ var ZH = {
1597
1634
  topic: "主题",
1598
1635
  members: "成员",
1599
1636
  addMembers: "添加成员",
1600
- makeExtension: "做成扩展",
1601
- makeExtensionDetail: "把这里商量出的事做成工具",
1637
+ mentionMember: "成员",
1638
+ makeExtension: "存下来",
1639
+ makeExtensionDetail: "把这里商量出的做法存成以后一键再用的",
1602
1640
  makeExtensionAsk: "把这个群聊里商量和做成的事做成扩展(用 ta-package 技能),以后一键就能再用",
1603
1641
  add: "添加",
1604
1642
  allMembers: "所有智能体都已在这个群聊里",
@@ -1608,6 +1646,7 @@ var ZH = {
1608
1646
  back: "返回",
1609
1647
  send: "发送",
1610
1648
  you: "你",
1649
+ picture: "[图片]",
1611
1650
  owner: "所有者",
1612
1651
  ta: "Ta",
1613
1652
  lead: "负责人",
@@ -1618,6 +1657,8 @@ var ZH = {
1618
1657
  pick: "选一个群聊",
1619
1658
  quiet: "还没有消息。@ 哪个智能体,它就会回答。",
1620
1659
  placeholder: "发到 {channel};@ 点名成员",
1660
+ placeholderLead: "发到 {channel};不 @ 时{lead}来答",
1661
+ placeholderAll: "发到 {channel};大家都可以接话",
1621
1662
  answering: "{name} 正在回答",
1622
1663
  failed: "没有回答",
1623
1664
  mention: "@{name}",
@@ -1644,6 +1685,10 @@ var ZH = {
1644
1685
  budgetShortWord: "简短",
1645
1686
  budgetNormalWord: "标准",
1646
1687
  budgetLongWord: "深入",
1688
+ replyHead: "没 @ 时谁接话",
1689
+ replyMentionedWord: "只回 @",
1690
+ replyLeadWord: "负责人接",
1691
+ replyAllWord: "大家都接",
1647
1692
  dailyLimit: "每天上限",
1648
1693
  dailySpent: "今天 {spent}",
1649
1694
  dailySpentOf: "今天 {spent} / {limit}",
@@ -1810,6 +1855,11 @@ var ZH = {
1810
1855
  shareCard: "分享名片…",
1811
1856
  cardTitle: "{name} 的名片",
1812
1857
  cardKind: "智能体名片",
1858
+ profileTitle: "智能体资料",
1859
+ noAgentOpen: "打开和智能体的对话后,这里显示它的资料",
1860
+ sendMessage: "发消息",
1861
+ workDir: "工作目录",
1862
+ deleteAgentLong: "删除智能体",
1813
1863
  cardGets: "对方把它加为自己的智能体,并按自己的项目调整职责",
1814
1864
  cardHint: "只带上职责(隐去疑似密钥),不带工作目录和对话。链接 30 天内有效,你的电脑关机也能打开。",
1815
1865
  cardRedacted: "职责里有 {n} 处疑似密钥已隐去。",
@@ -1839,8 +1889,9 @@ var ZH_TW = {
1839
1889
  topic: "主題",
1840
1890
  members: "成員",
1841
1891
  addMembers: "新增成員",
1842
- makeExtension: "做成擴充功能",
1843
- makeExtensionDetail: "把這裡商量出的事做成工具",
1892
+ mentionMember: "成員",
1893
+ makeExtension: "存下來",
1894
+ makeExtensionDetail: "把這裡商量出的做法存成以後一鍵再用的",
1844
1895
  makeExtensionAsk: "把這個群聊里商量和做成的事做成擴充功能(用 ta-package 技能),以後一鍵就能再用",
1845
1896
  add: "新增",
1846
1897
  allMembers: "所有智慧體都已在這個群聊里",
@@ -1850,6 +1901,7 @@ var ZH_TW = {
1850
1901
  back: "返回",
1851
1902
  send: "傳送",
1852
1903
  you: "你",
1904
+ picture: "[圖片]",
1853
1905
  owner: "所有者",
1854
1906
  ta: "Ta",
1855
1907
  lead: "負責人",
@@ -1860,6 +1912,8 @@ var ZH_TW = {
1860
1912
  pick: "選一個群聊",
1861
1913
  quiet: "還沒有訊息。@ 哪個智慧體,它就會回答。",
1862
1914
  placeholder: "發到 {channel};@ 點名成員",
1915
+ placeholderLead: "發到 {channel};不 @ 時{lead}來答",
1916
+ placeholderAll: "發到 {channel};大家都可以接話",
1863
1917
  answering: "{name} 正在回答",
1864
1918
  failed: "沒有回答",
1865
1919
  mention: "@{name}",
@@ -1886,6 +1940,10 @@ var ZH_TW = {
1886
1940
  budgetShortWord: "簡短",
1887
1941
  budgetNormalWord: "標準",
1888
1942
  budgetLongWord: "深入",
1943
+ replyHead: "沒 @ 時誰接話",
1944
+ replyMentionedWord: "只回 @",
1945
+ replyLeadWord: "負責人接",
1946
+ replyAllWord: "大家都接",
1889
1947
  dailyLimit: "每天上限",
1890
1948
  dailySpent: "今天 {spent}",
1891
1949
  dailySpentOf: "今天 {spent} / {limit}",
@@ -2052,6 +2110,11 @@ var ZH_TW = {
2052
2110
  shareCard: "分享名片…",
2053
2111
  cardTitle: "{name} 的名片",
2054
2112
  cardKind: "智慧體名片",
2113
+ profileTitle: "智慧體資料",
2114
+ noAgentOpen: "開啟與智慧體的對話後,這裡顯示它的資料",
2115
+ sendMessage: "發訊息",
2116
+ workDir: "工作目錄",
2117
+ deleteAgentLong: "刪除智慧體",
2055
2118
  cardGets: "對方把它加為自己的智慧體,並按自己的專案調整職責",
2056
2119
  cardHint: "只帶上職責(隱去疑似金鑰),不帶工作目錄和對話。連結 30 天內有效,你的電腦關機也能開啟。",
2057
2120
  cardRedacted: "職責裡有 {n} 處疑似金鑰已隱去。",
@@ -2081,8 +2144,9 @@ var EN = {
2081
2144
  topic: "Topic",
2082
2145
  members: "Members",
2083
2146
  addMembers: "Add members",
2084
- makeExtension: "Make an extension",
2085
- makeExtensionDetail: "Of what was worked out here",
2147
+ mentionMember: "Member",
2148
+ makeExtension: "Keep",
2149
+ makeExtensionDetail: "Make what was worked out here a one-tap thing to use again",
2086
2150
  makeExtensionAsk: "Make what this group chat worked out an extension, with the ta-package skill, to do it again in a click",
2087
2151
  add: "Add",
2088
2152
  allMembers: "Every agent is in this group chat already",
@@ -2092,6 +2156,7 @@ var EN = {
2092
2156
  back: "Back",
2093
2157
  send: "Send",
2094
2158
  you: "You",
2159
+ picture: "[Picture]",
2095
2160
  owner: "Owner",
2096
2161
  ta: "Ta",
2097
2162
  lead: "Lead",
@@ -2102,6 +2167,8 @@ var EN = {
2102
2167
  pick: "Pick a group chat",
2103
2168
  quiet: "Nothing said yet. Mention an agent with @ to have it answer.",
2104
2169
  placeholder: "Message {channel}; @ names a member",
2170
+ placeholderLead: "Message {channel}; {lead} answers without @",
2171
+ placeholderAll: "Message {channel}; anyone may answer",
2105
2172
  answering: "{name} is answering",
2106
2173
  failed: "did not answer",
2107
2174
  mention: "Mention {name}",
@@ -2128,6 +2195,10 @@ var EN = {
2128
2195
  budgetShortWord: "Short",
2129
2196
  budgetNormalWord: "Normal",
2130
2197
  budgetLongWord: "Long",
2198
+ replyHead: "Without @",
2199
+ replyMentionedWord: "Only @",
2200
+ replyLeadWord: "The lead",
2201
+ replyAllWord: "Everyone",
2131
2202
  dailyLimit: "A day",
2132
2203
  dailySpent: "today {spent}",
2133
2204
  dailySpentOf: "today {spent} / {limit}",
@@ -2294,6 +2365,11 @@ var EN = {
2294
2365
  shareCard: "Share card…",
2295
2366
  cardTitle: "{name}'s card",
2296
2367
  cardKind: "An agent's card",
2368
+ profileTitle: "Agent profile",
2369
+ noAgentOpen: "Open a conversation with an agent to see its profile here",
2370
+ sendMessage: "Message",
2371
+ workDir: "Directory",
2372
+ deleteAgentLong: "Delete agent",
2297
2373
  cardGets: "They add it as an agent of their own, fitted to their project",
2298
2374
  cardHint: "Only its role goes, secrets taken out; not its directory nor its conversation. The link works for 30 days, while this computer is off too.",
2299
2375
  cardRedacted: "{n} places that looked like secrets were taken out.",
@@ -2324,6 +2400,7 @@ var ChannelWords;
2324
2400
  var DOUBLE_PAGE = "assistant/assistant";
2325
2401
  var CHANNEL_PAGE = `${NAME}/channel`;
2326
2402
  var MEMBERS_VIEW = `${NAME}/members`;
2403
+ var AGENT_INFO_VIEW = `${NAME}/agent-info`;
2327
2404
  var ROOM_INFO_VIEW = "@celljs/ta-rooms/members";
2328
2405
  var CHANNEL_KEY = "ta-channels.channel";
2329
2406
 
@@ -2831,1749 +2908,1985 @@ function registerCardOpener(context) {
2831
2908
  }, { specific: true });
2832
2909
  }
2833
2910
 
2834
- // web-src/channels.ts
2835
- class ChannelsClient {
2836
- storage;
2837
- send;
2838
- current = { team: ChannelsUtil.emptyTeam(), messages: {}, working: {}, answered: {}, loaded: false, deleting: [] };
2839
- listeners = new Set;
2840
- focusListeners = new Set;
2841
- loading;
2842
- unlisten;
2843
- constructor(storage, send) {
2844
- this.storage = storage;
2845
- this.send = send;
2846
- this.unlisten = storage.onChange((keys) => void this.changed(keys));
2911
+ // ../ta-protocol/esm/common/said-protocol.js
2912
+ var TaSaid;
2913
+ (function(TaSaid2) {
2914
+ const CARD = /^ta-/i;
2915
+ const READ = 4000;
2916
+ const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)/;
2917
+ const TAG_LINE = /^<\/?[A-Za-z][\w:.-]*(?:\s[^<>]*)?\/?>$/;
2918
+ const MARKS_ONLY = /^[-*_=|:+\s]+$/;
2919
+ const MARKS = [
2920
+ ["context", /<\/?context>/],
2921
+ ["source", /\[ta:(?:from|notice|by) /],
2922
+ ["image note", /\[Image: original \d+x\d+|\[Image converted from /],
2923
+ ["skill", /<skill name="|<\/skill>/],
2924
+ ["task note", /<\/?task_(?:update|adopted|renamed)\b/],
2925
+ ["summary", /<\/?(?:conversation_history_summary|summary)>/]
2926
+ ];
2927
+ function text(content, joiner = `
2928
+ `) {
2929
+ if (typeof content === "string") {
2930
+ return content;
2931
+ }
2932
+ return Array.isArray(content) ? content.filter((part) => (part === null || part === undefined ? undefined : part.type) === "text" && typeof part.text === "string").map((part) => part.text).join(joiner) : "";
2847
2933
  }
2848
- get state() {
2849
- return this.current;
2934
+ TaSaid2.text = text;
2935
+ function words(role, text2, options = {}) {
2936
+ const said = role === "user" ? userWords(text2) : TaAgentSummary.strip(text2);
2937
+ return withoutFences(said, (language) => options.cards === false && CARD.test(language), true).trim();
2850
2938
  }
2851
- subscribe(listener) {
2852
- this.listeners.add(listener);
2853
- return () => this.listeners.delete(listener);
2939
+ TaSaid2.words = words;
2940
+ function of(message, options) {
2941
+ return message ? words(message.role, text(message.content), options) : "";
2854
2942
  }
2855
- onFocus(listener) {
2856
- this.focusListeners.add(listener);
2857
- return () => this.focusListeners.delete(listener);
2943
+ TaSaid2.of = of;
2944
+ function notice(message) {
2945
+ return (message === null || message === undefined ? undefined : message.role) === "user" && TaMessageSource.isNotice(text(message.content));
2858
2946
  }
2859
- dispose() {
2860
- this.unlisten();
2947
+ TaSaid2.notice = notice;
2948
+ function marksOnly(role, text2) {
2949
+ return !!text2.trim() && !line(words(role, text2), { chars: Number.POSITIVE_INFINITY });
2861
2950
  }
2862
- load(again = false) {
2863
- if (!this.loading || again) {
2864
- this.loading = Promise.all([
2865
- this.storage.get(Keys.TEAM),
2866
- this.storage.get(Keys.WORKING),
2867
- this.storage.get(Keys.ANSWERED)
2868
- ]).then(([team, working, answered]) => this.update({ team: team ?? ChannelsUtil.emptyTeam(), working: working ?? {}, answered: answered ?? {}, loaded: true }));
2869
- }
2870
- return this.loading;
2951
+ TaSaid2.marksOnly = marksOnly;
2952
+ function line(markdown, options) {
2953
+ var _a;
2954
+ const read = markdown.slice(0, READ);
2955
+ const prose = withoutFences(read, () => true, true).trim();
2956
+ const lines = plain(prose || codeOf(read)).split(`
2957
+ `).map((part) => part.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)/, "").replace(/\*{1,3}|`+|~~|(?<![\p{L}\p{N}])_{1,3}|_{1,3}(?![\p{L}\p{N}])/gu, "").replace(/\s+/g, " ").trim()).filter((part) => part && !MARKS_ONLY.test(part) && !TAG_LINE.test(part));
2958
+ const count = (_a = options.lines) !== null && _a !== undefined ? _a : 1;
2959
+ const joined = count <= 1 ? lines.join(" ") : lines.slice(0, count).join(`
2960
+ `);
2961
+ return joined.length > options.chars ? `${joined.slice(0, Math.max(0, options.chars - 1)).trimEnd()}…` : joined;
2871
2962
  }
2872
- async messages(channelId, again = false) {
2873
- const known = this.current.messages[channelId];
2874
- if (known && !again) {
2875
- return known;
2963
+ TaSaid2.line = line;
2964
+ function leaks(shown, options = {}) {
2965
+ const found = MARKS.filter(([, mark]) => mark.test(shown)).map(([name]) => name);
2966
+ const lines = shown.split(`
2967
+ `);
2968
+ if (options.cards !== true && lines.some((part) => {
2969
+ var _a;
2970
+ var _b;
2971
+ return CARD.test((_b = (_a = FENCE.exec(part)) === null || _a === undefined ? undefined : _a[2]) !== null && _b !== undefined ? _b : "");
2972
+ })) {
2973
+ found.push("card");
2876
2974
  }
2877
- const messages = await this.storage.get(Keys.messages(channelId)) ?? [];
2878
- this.update({ messages: { ...this.current.messages, [channelId]: messages } });
2879
- return messages;
2975
+ if (lines.some((part) => TAG_LINE.test(part.trim()))) {
2976
+ found.push("tag");
2977
+ }
2978
+ return found;
2880
2979
  }
2881
- async createAgent(input) {
2882
- const agent = await this.send({ kind: "createAgent", ...input });
2883
- await this.load(true);
2884
- return agent;
2980
+ TaSaid2.leaks = leaks;
2981
+ const SUMMARY = `<conversation_history_summary>
2982
+ <summary>
2983
+ 1. Primary Request and Intent:
2984
+ The user works on the relay.
2985
+ </summary>
2986
+ </conversation_history_summary>`;
2987
+ TaSaid2.SAMPLES = [
2988
+ {
2989
+ mark: "context and where it came from",
2990
+ role: "user",
2991
+ text: `<context>
2992
+ The channel #ops, its members.
2993
+ [ta:from @celljs/ta-channels #ops]
2994
+ </context>
2995
+ Check the build`,
2996
+ said: "Check the build"
2997
+ },
2998
+ {
2999
+ mark: "a notice, not the user",
3000
+ role: "user",
3001
+ text: `<context>
3002
+ [ta:notice @celljs/ta-call]
3003
+ </context>
3004
+ The work finished. Its last words: tests pass.`,
3005
+ said: "The work finished. Its last words: tests pass."
3006
+ },
3007
+ { mark: "one let in", role: "user", text: `<context>
3008
+ [ta:by p-7 Alice]
3009
+ </context>
3010
+ Hello there`, said: "Hello there" },
3011
+ {
3012
+ mark: "notes of images",
3013
+ role: "user",
3014
+ text: `Look at this
3015
+ [Image: original 3024x4032, displayed at 1512x2016. Multiply coordinates by 2.00 to map to original image.]
3016
+ [Image converted from image/heic to image/png.]`,
3017
+ said: "Look at this"
3018
+ },
3019
+ {
3020
+ mark: "a skill run",
3021
+ role: "user",
3022
+ text: `<skill name="ta-package" location="/skills/ta-package/SKILL.md">
3023
+ # Ta package
3024
+ Steps.
3025
+ </skill>
3026
+
3027
+ Make a card`,
3028
+ said: "Make a card"
3029
+ },
3030
+ {
3031
+ mark: "a note of a task",
3032
+ role: "user",
3033
+ text: `<task_update id="t1" title="Fix login" status="done">
3034
+ All tests pass.
3035
+ </task_update>`,
3036
+ said: "Fix login"
3037
+ },
3038
+ { mark: "a note of a new id", role: "user", text: `<task_renamed id="t2" was="t1" title="Fix login">
3039
+ Now t2.
3040
+ </task_renamed>` },
3041
+ { mark: "a summary, then the answer", role: "assistant", text: `${SUMMARY}
3042
+ Switched to voice.`, said: "Switched to voice." },
3043
+ { mark: "a summary alone", role: "assistant", text: SUMMARY },
3044
+ { mark: "a summary as it streams", role: "assistant", text: `<conversation_history_summary>
3045
+ <summary>` },
3046
+ {
3047
+ mark: "a card after the answer",
3048
+ role: "assistant",
3049
+ text: '**Done**: tests pass.\n\n```ta-glance\n{"status":"done","blocks":[]}\n```',
3050
+ said: "tests pass"
3051
+ },
3052
+ { mark: "a card alone", role: "assistant", text: '```ta-glance\n{"status":"done","blocks":[]}\n```' },
3053
+ { mark: "a proposal", role: "assistant", text: 'Committed.\n\n```ta-propose\n{"kind":"git.push","title":"Push"}\n```', said: "Committed." },
3054
+ { mark: "what a call says aloud", role: "assistant", text: "All fixed.\n\n```ta-say\nIt is fixed.\n```", said: "All fixed." },
3055
+ { mark: "a tag not known yet", role: "assistant", text: `<system-reminder>
3056
+ </system-reminder>
3057
+ Ready.`, said: "Ready." }
3058
+ ];
3059
+ function userWords(text2) {
3060
+ const said = TaImageNote.strip(TaMessageContext.strip(text2));
3061
+ const skill = TaSkillUse.parse(said);
3062
+ if (skill) {
3063
+ return TaSkillUse.command(skill);
3064
+ }
3065
+ const note = TaTaskNote.parse(said);
3066
+ if (!note) {
3067
+ return said;
3068
+ }
3069
+ if (note.kind === "renamed") {
3070
+ return "";
3071
+ }
3072
+ return note.kind === "update" && note.body.trim() ? `${note.title} · ${note.body}` : note.title;
2885
3073
  }
2886
- async createChannel(input) {
2887
- const channel = await this.send({ kind: "createChannel", ...input });
2888
- await this.load(true);
2889
- return channel;
3074
+ function withoutFences(text2, drop, tags = false) {
3075
+ const kept = [];
3076
+ let fence;
3077
+ let left = false;
3078
+ for (const part of text2.split(`
3079
+ `)) {
3080
+ const open = FENCE.exec(part);
3081
+ if (!fence && open) {
3082
+ fence = { mark: open[1], dropped: drop(open[2]) };
3083
+ } else if (fence && closes(part, fence.mark)) {
3084
+ const dropped = fence.dropped;
3085
+ fence = undefined;
3086
+ if (dropped) {
3087
+ continue;
3088
+ }
3089
+ }
3090
+ if ((fence === null || fence === undefined ? undefined : fence.dropped) || !fence && tags && TAG_LINE.test(part.trim())) {
3091
+ left = true;
3092
+ } else {
3093
+ kept.push(part);
3094
+ }
3095
+ }
3096
+ return left ? kept.join(`
3097
+ `).replace(/\n{3,}/g, `
3098
+
3099
+ `) : kept.join(`
3100
+ `);
2890
3101
  }
2891
- async addMembers(channelId, members) {
2892
- const channel = await this.send({ kind: "addMembers", channel: channelId, members });
2893
- await this.load(true);
2894
- return channel;
3102
+ function codeOf(text2) {
3103
+ const code = [];
3104
+ let fence;
3105
+ for (const part of text2.split(`
3106
+ `)) {
3107
+ const open = FENCE.exec(part);
3108
+ if (!fence && open) {
3109
+ fence = { mark: open[1], card: CARD.test(open[2]) };
3110
+ } else if (fence && closes(part, fence.mark)) {
3111
+ fence = undefined;
3112
+ } else if (fence && !fence.card) {
3113
+ code.push(part);
3114
+ }
3115
+ }
3116
+ return code.join(`
3117
+ `);
2895
3118
  }
2896
- async changeMember(channelId, agentId, change) {
2897
- const channel = await this.send({ kind: "changeMember", channel: channelId, agent: agentId, change });
2898
- await this.load(true);
2899
- return channel;
2900
- }
2901
- async updateChannel(channelId, change) {
2902
- const channel = await this.send({ kind: "updateChannel", channel: channelId, ...change });
2903
- await this.load(true);
2904
- return channel;
2905
- }
2906
- async deleteChannel(channelId) {
2907
- await this.deleting(channelId, async () => {
2908
- await this.send({ kind: "deleteChannel", channel: channelId });
2909
- const { [channelId]: _gone, ...messages } = this.current.messages;
2910
- this.update({ messages });
2911
- await this.load(true);
2912
- });
2913
- }
2914
- async resetAgent(agentId) {
2915
- const agent = await this.send({ kind: "resetAgent", agent: agentId });
2916
- await this.load(true);
2917
- return agent;
3119
+ function closes(part, mark) {
3120
+ var _a;
3121
+ const close = (_a = /^\s*(`{3,}|~{3,})\s*$/.exec(part)) === null || _a === undefined ? undefined : _a[1];
3122
+ return !!close && close[0] === mark[0] && close.length >= mark.length;
2918
3123
  }
2919
- async updateAgent(agentId, change) {
2920
- const agent = await this.send({ kind: "updateAgent", agent: agentId, ...change });
2921
- await this.load(true);
2922
- return agent;
3124
+ function plain(text2) {
3125
+ const linked = text2.replace(/(?<!!)\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
3126
+ const words2 = linked.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").trim();
3127
+ return words2 || linked.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
2923
3128
  }
2924
- async setChannelModel(channelId, model) {
2925
- const channel = await this.send({ kind: "setChannelModel", channel: channelId, model });
2926
- await this.load(true);
2927
- return channel;
3129
+ })(TaSaid || (TaSaid = {}));
3130
+
3131
+ // web-src/channels-text.ts
3132
+ var ChannelsText;
3133
+ ((ChannelsText) => {
3134
+ function markMentions(text, agents) {
3135
+ if (agents.length === 0) {
3136
+ return text;
3137
+ }
3138
+ const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3139
+ const pattern = new RegExp(`(?<![*A-Za-z0-9_])@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
3140
+ return text.split(/(```[\s\S]*?(?:```|$)|`[^`\n]*`)/).map((part, index) => index % 2 === 1 ? part : part.replace(pattern, "**$&**")).join("");
2928
3141
  }
2929
- async deleteAgent(agentId) {
2930
- await this.deleting(agentId, async () => {
2931
- await this.send({ kind: "deleteAgent", agent: agentId });
2932
- await this.load(true);
2933
- });
3142
+ ChannelsText.markMentions = markMentions;
3143
+ function mentions(text, agents) {
3144
+ if (agents.length === 0) {
3145
+ return [];
3146
+ }
3147
+ const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3148
+ const pattern = new RegExp(`@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
3149
+ const found = [];
3150
+ for (const match of text.matchAll(pattern)) {
3151
+ const agent = agents.find((candidate) => candidate.name.toLowerCase() === match[1].toLowerCase());
3152
+ if (agent && !found.includes(agent.id)) {
3153
+ found.push(agent.id);
3154
+ }
3155
+ }
3156
+ return found;
2934
3157
  }
2935
- async deleting(id, action) {
2936
- this.update({ deleting: [...this.current.deleting, id] });
2937
- try {
2938
- await action();
2939
- } finally {
2940
- this.update({ deleting: this.current.deleting.filter((other) => other !== id) });
3158
+ ChannelsText.mentions = mentions;
3159
+ function targets(team, channel, message) {
3160
+ const members = answering(team, channel);
3161
+ const named = mentions(message.text, members).filter((id) => id !== message.author);
3162
+ if (message.author === SYSTEM) {
3163
+ return [];
3164
+ }
3165
+ if (named.length > 0 || message.author !== TA && message.author !== USER || mentions(message.text, team.agents).length > 0) {
3166
+ return named;
3167
+ }
3168
+ const reply = message.author === TA ? "lead" : replyOf(channel);
3169
+ if (reply === "all") {
3170
+ return members.map((agent) => agent.id);
2941
3171
  }
3172
+ return reply === "lead" && members.length > 0 ? [members[0].id] : [];
2942
3173
  }
2943
- async openAgent(agentId) {
2944
- const { sessionId } = await this.send({ kind: "openAgent", agent: agentId });
2945
- return sessionId;
3174
+ ChannelsText.targets = targets;
3175
+ function replyOf(channel) {
3176
+ return channel?.reply && REPLIES.includes(channel.reply) ? channel.reply : DEFAULT_REPLY;
2946
3177
  }
2947
- async setNotice(channelId, text) {
2948
- const channel = await this.send({ kind: "setNotice", channel: channelId, text });
2949
- await this.load(true);
2950
- return channel;
3178
+ ChannelsText.replyOf = replyOf;
3179
+ function passes(text) {
3180
+ return text.replace(/[\s.。!!*_`"'“”]/g, "").toUpperCase() === PASS;
2951
3181
  }
2952
- shareAgent(agentId, color) {
2953
- return this.send({ kind: "shareAgent", agent: agentId, ...color ? { color } : {} });
3182
+ ChannelsText.passes = passes;
3183
+ function answering(team, channel) {
3184
+ const muted = channel.muted ?? [];
3185
+ return channel.members.filter((id) => !muted.includes(id)).map((id) => team.agents.find((agent) => agent.id === id)).filter((agent) => !!agent);
2954
3186
  }
2955
- async stopCard(agentId) {
2956
- return await this.send({ kind: "stopCard", agent: agentId });
3187
+ function mayPass(team, channel, message, agent) {
3188
+ const members = answering(team, channel);
3189
+ return message.author === USER && replyOf(channel) === "all" && members[0]?.id !== agent.id && mentions(message.text, team.agents).length === 0;
2957
3190
  }
2958
- openCard(link, password) {
2959
- return this.send({ kind: "openCard", link, ...password ? { password } : {} });
3191
+ ChannelsText.mayPass = mayPass;
3192
+ function authorName(team, author, labels) {
3193
+ if (author === SYSTEM) {
3194
+ return "channel";
3195
+ }
3196
+ if (author === USER) {
3197
+ return labels.user;
3198
+ }
3199
+ if (author === TA) {
3200
+ return labels.ta;
3201
+ }
3202
+ return team.agents.find((agent) => agent.id === author)?.name ?? author;
2960
3203
  }
2961
- async addFromCard(link, cwd, password) {
2962
- const added = await this.send({ kind: "addFromCard", link, cwd, ...password ? { password } : {} });
2963
- await this.load(true);
2964
- return added;
3204
+ ChannelsText.authorName = authorName;
3205
+ function systemPrompt(agent) {
3206
+ return [
3207
+ `You are ${agent.name}, ${AGENT_MARK}. Your role: ${agent.role}`,
3208
+ "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.",
3209
+ "Do the part of the work your role covers with your tools, then answer: your answer is posted to the channel as it is.",
3210
+ "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.",
3211
+ "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.",
3212
+ NOTICE_RULE
3213
+ ].join(`
3214
+ `);
2965
3215
  }
2966
- async post(channelId, text) {
2967
- await this.send({ kind: "post", channel: channelId, text });
3216
+ ChannelsText.systemPrompt = systemPrompt;
3217
+ function prompt(team, channel, history, message, agent, options = {}) {
3218
+ const labels = { user: "user", ta: "Ta" };
3219
+ 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)}`);
3220
+ const before = history.filter((item) => item.id !== message.id && !item.failed && !item.notice).slice(-CONTEXT_MESSAGES);
3221
+ const lines = [`[#${channel.name}]${channel.topic ? ` ${channel.topic}` : ""}`, "Members:", ...members.map((line) => `- ${line}`)];
3222
+ if (channel.notice) {
3223
+ lines.push("", "Notice of the channel (follow it; keep it with update_channel_notice):", channel.notice.text);
3224
+ }
3225
+ if (before.length > 0) {
3226
+ lines.push("", "Recent messages:", ...before.map((item) => `${authorName(team, item.author, labels)}: ${said(item)}`));
3227
+ }
3228
+ if (options.closing) {
3229
+ lines.push("", CLOSING_NOTE);
3230
+ }
3231
+ if (mayPass(team, channel, message, agent)) {
3232
+ lines.push("", PASS_NOTE);
3233
+ }
3234
+ lines.push("", `${authorName(team, message.author, labels)} to you:`);
3235
+ const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels)}`;
3236
+ lines.push(TaMessageSource.line(NAME, `#${channel.name}${speaker}`));
3237
+ if (message.images?.length) {
3238
+ lines.push(`(${message.images.length > 1 ? `${message.images.length} pictures` : "A picture"} sent with it, attached.)`);
3239
+ }
3240
+ return TaMessageContext.wrap(lines.join(`
3241
+ `), message.text);
2968
3242
  }
2969
- async resumeRound(channelId, messageId, how) {
2970
- await this.send({ kind: "resumeRound", channel: channelId, message: messageId, how });
3243
+ ChannelsText.prompt = prompt;
3244
+ function said(message) {
3245
+ const pictures = message.images?.length ? `[${message.images.length > 1 ? `${message.images.length} pictures` : "picture"}]` : "";
3246
+ return [pictures, message.text].filter(Boolean).join(" ");
2971
3247
  }
2972
- async setLimits(limits) {
2973
- await this.send({ kind: "setLimits", limits });
3248
+ ChannelsText.said = said;
3249
+ function summary(team) {
3250
+ if (team.agents.length === 0) {
3251
+ return "No agents and no channels yet.";
3252
+ }
3253
+ const name = (id) => team.agents.find((agent) => agent.id === id)?.name ?? id;
3254
+ const agents = team.agents.map((agent) => `- @${agent.name}: ${firstLine(agent.role)}`);
3255
+ const channels = team.channels.map((channel) => `- #${channel.name}${channel.topic ? ` (${channel.topic})` : ""}: ${channel.members.map((id) => `@${name(id)}`).join(", ")}${channel.muted?.length ? `; muted by the user, answering nothing: ${channel.muted.map((id) => `@${name(id)}`).join(", ")}` : ""}${channel.notice ? `
3256
+ notice: ${channel.notice.text.replace(/\s+/g, " ").slice(0, 300)}` : ""}`);
3257
+ return ["Agents:", ...agents, "", "Channels:", ...channels.length > 0 ? channels : ["none yet"]].join(`
3258
+ `);
2974
3259
  }
2975
- async watch(channelId) {
2976
- await this.send({ kind: "watch", channel: channelId });
3260
+ ChannelsText.summary = summary;
3261
+ function transcript(team, messages) {
3262
+ const labels = { user: "user", ta: "Ta" };
3263
+ return messages.map((item) => `${authorName(team, item.author, labels)}${item.failed ? " (failed)" : ""}: ${said(item)}`).join(`
3264
+
3265
+ `);
2977
3266
  }
2978
- async changed(keys) {
2979
- const reads = [];
2980
- for (const key of keys) {
2981
- if (key === Keys.TEAM || key === Keys.WORKING || key === Keys.ANSWERED) {
2982
- reads.push(this.load(true));
2983
- } else if (key.startsWith(Keys.MESSAGES)) {
2984
- const channelId = key.slice(Keys.MESSAGES.length);
2985
- if (this.current.messages[channelId]) {
2986
- reads.push(this.messages(channelId, true));
2987
- }
2988
- } else if (key === Keys.FOCUS) {
2989
- reads.push(this.storage.get(Keys.FOCUS).then(async (focus) => {
2990
- if (focus) {
2991
- await this.load(true);
2992
- for (const listener of this.focusListeners) {
2993
- listener(focus.channelId);
2994
- }
2995
- }
2996
- }));
3267
+ ChannelsText.transcript = transcript;
3268
+ function markdown(agent, messages, labels) {
3269
+ const parts = [`# ${agent.name}`, "", `> ${firstLine(agent.role)}`];
3270
+ for (const message of messages) {
3271
+ const { role, content } = message ?? {};
3272
+ if (role !== "user" && role !== "assistant") {
3273
+ continue;
3274
+ }
3275
+ const text = TaSaid.words(role, TaSaid.text(content, ""));
3276
+ if (text) {
3277
+ parts.push("", `## ${role === "user" ? labels.user : agent.name}`, "", text);
2997
3278
  }
2998
3279
  }
2999
- await Promise.all(reads).catch((error) => console.error(error));
3280
+ return `${parts.join(`
3281
+ `)}
3282
+ `;
3000
3283
  }
3001
- update(change) {
3002
- this.current = { ...this.current, ...change };
3003
- for (const listener of this.listeners) {
3004
- listener(this.current);
3284
+ ChannelsText.markdown = markdown;
3285
+ function channelMarkdown(team, channel, messages, labels) {
3286
+ const parts = [`# #${channel.name}`];
3287
+ if (channel.topic) {
3288
+ parts.push("", `> ${firstLine(channel.topic)}`);
3005
3289
  }
3290
+ for (const message of messages) {
3291
+ const text = message.text.trim();
3292
+ if (text && message.author !== SYSTEM) {
3293
+ parts.push("", `## ${authorName(team, message.author, labels)}${message.failed ? " (failed)" : ""}`, "", text);
3294
+ }
3295
+ }
3296
+ return `${parts.join(`
3297
+ `)}
3298
+ `;
3006
3299
  }
3007
- }
3008
-
3009
- // web-src/shared-group.tsx
3010
- function useFriends(pi) {
3011
- const [friends, setFriends] = React.useState([]);
3012
- React.useEffect(() => {
3013
- let live = true;
3014
- pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
3015
- return;
3016
- });
3017
- return () => {
3018
- live = false;
3019
- };
3020
- }, [pi]);
3021
- return friends;
3022
- }
3023
- async function createShared(context, title, friends, agents) {
3024
- const { pi } = context;
3025
- const rooms = pi.rooms;
3026
- if (!rooms) {
3027
- throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
3028
- }
3029
- const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
3030
- await rooms.inviteFriends(room.id, friends);
3031
- for (const agent of agents) {
3032
- await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
3033
- pi.ui.notify(ChannelViews.message(error), "error");
3034
- });
3300
+ ChannelsText.channelMarkdown = channelMarkdown;
3301
+ function firstLine(text) {
3302
+ return text.split(`
3303
+ `)[0];
3035
3304
  }
3036
- const { link } = await rooms.invite(room.id);
3037
- await pi.openLink?.(link);
3038
- return room.id;
3039
- }
3040
- var ROOMS_PACKAGE = "@celljs/ta-rooms";
3041
- var ROOMS_KIND = "ta-rooms";
3042
- async function becomeGroup(context, channel, friends, agents) {
3043
- const { pi } = context;
3044
- const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
3045
- const room = await createShared(context, channel.name, friends, members);
3046
- await context.service.updateChannel(channel.id, { shared: room });
3047
- pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
3048
- }
3305
+ })(ChannelsText ||= {});
3306
+ 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.";
3307
+ var PASS_NOTE = `The user named nobody, and every member got this message: answer only if your role has something of its own to add; the lead answers for the channel. Else answer exactly ${PASS}, which is not posted.`;
3308
+ var NOTICE_RULE = [
3309
+ "A channel may have a notice, in the <context> block: what its members decided, agreed and are to do. Follow it.",
3310
+ `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.`
3311
+ ].join(`
3312
+ `);
3049
3313
 
3050
- // web-src/create.tsx
3051
- var noBack = (_open, _close) => false;
3052
- var AGENT_PAGE = `${NAME}/agent`;
3053
- function newAgent(context) {
3054
- const { pi, service, ui } = context;
3055
- if (!ui.state.draft) {
3056
- const team = service.state.team;
3057
- const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
3058
- ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
3059
- }
3060
- pi.ui.showView(AGENT_PAGE);
3061
- }
3062
- function Identity({ context, onClose }) {
3063
- const { pi, ui } = context;
3064
- const { draft } = useUi(ui);
3314
+ // web-src/more-menu.tsx
3315
+ var MARGIN = 8;
3316
+ function MoreMenu({ pi, label, items }) {
3065
3317
  const w = ChannelViews.words(pi);
3066
- const ref = React.useRef(null);
3067
- const name = React.useRef(null);
3068
- React.useEffect(() => name.current?.select(), []);
3069
- (pi.ui.useBackLayer ?? noBack)(true, onClose);
3318
+ const [open, setOpen] = React.useState(false);
3319
+ const anchor = React.useRef({
3320
+ right: 0,
3321
+ below: 0,
3322
+ above: 0,
3323
+ finger: undefined
3324
+ });
3325
+ const root = React.useRef(null);
3326
+ const menu = React.useRef(null);
3327
+ const Ellipsis = ChannelViews.icon(pi, "Ellipsis");
3328
+ const show = React.useCallback((button, at) => {
3329
+ const box = button.getBoundingClientRect();
3330
+ const touch = document.documentElement.hasAttribute("data-touch");
3331
+ const row = root.current?.parentElement?.getBoundingClientRect() ?? box;
3332
+ anchor.current = {
3333
+ right: box.right,
3334
+ below: at?.y ?? box.bottom,
3335
+ above: at?.y ?? box.top,
3336
+ finger: touch && at ? { ...at, around: { top: row.top, bottom: row.bottom } } : undefined
3337
+ };
3338
+ setOpen(true);
3339
+ }, []);
3340
+ React.useLayoutEffect(() => {
3341
+ const element = menu.current;
3342
+ if (!open || !element) {
3343
+ return;
3344
+ }
3345
+ const { right, below, above, finger } = anchor.current;
3346
+ if (finger) {
3347
+ return pi.ui.attachMenu(element, finger, () => setOpen(false));
3348
+ }
3349
+ const width = element.offsetWidth;
3350
+ const height = element.offsetHeight;
3351
+ const top = below + 4 + height <= window.innerHeight - MARGIN ? below + 4 : Math.max(MARGIN, above - 4 - height);
3352
+ element.style.top = `${top}px`;
3353
+ element.style.left = `${Math.max(MARGIN, right - width)}px`;
3354
+ }, [open, pi]);
3355
+ React.useEffect(() => {
3356
+ const row = root.current?.parentElement;
3357
+ const button = root.current?.querySelector(".tac-action");
3358
+ if (!row || !button) {
3359
+ return;
3360
+ }
3361
+ const onContextMenu = (event) => {
3362
+ event.preventDefault();
3363
+ show(button, event.clientX || event.clientY ? { x: event.clientX, y: event.clientY } : undefined);
3364
+ };
3365
+ row.addEventListener("contextmenu", onContextMenu);
3366
+ return () => row.removeEventListener("contextmenu", onContextMenu);
3367
+ }, [show]);
3070
3368
  React.useEffect(() => {
3369
+ if (!open) {
3370
+ return;
3371
+ }
3071
3372
  const close = (event) => {
3072
- const target = event.target;
3073
- if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
3074
- onClose();
3373
+ if (!root.current?.contains(event.target)) {
3374
+ setOpen(false);
3375
+ }
3376
+ };
3377
+ const onKey = (event) => {
3378
+ if (event.key === "Escape") {
3379
+ setOpen(false);
3075
3380
  }
3076
3381
  };
3077
- const onKey = (event) => event.key === "Escape" && onClose();
3078
3382
  document.addEventListener("pointerdown", close);
3079
3383
  document.addEventListener("keydown", onKey);
3080
3384
  return () => {
3081
3385
  document.removeEventListener("pointerdown", close);
3082
3386
  document.removeEventListener("keydown", onKey);
3083
3387
  };
3084
- }, [onClose]);
3085
- if (!draft) {
3086
- return null;
3087
- }
3088
- return /* @__PURE__ */ React.createElement("div", {
3089
- className: "tac-identity",
3090
- ref,
3091
- role: "dialog",
3092
- "aria-label": w.editAgent
3093
- }, /* @__PURE__ */ React.createElement("label", {
3094
- className: "tac-identity-label"
3095
- }, w.name, /* @__PURE__ */ React.createElement("input", {
3096
- className: "tac-input",
3097
- value: draft.name,
3098
- maxLength: 40,
3099
- ref: name,
3100
- onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
3101
- onKeyDown: (event) => event.key === "Enter" && onClose()
3102
- })), /* @__PURE__ */ React.createElement("div", {
3103
- className: "tac-identity-label"
3104
- }, w.avatar), /* @__PURE__ */ React.createElement("div", {
3105
- className: "tac-faces"
3106
- }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
3107
- key: face,
3108
- type: "button",
3109
- "aria-pressed": draft.face === face,
3110
- className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
3111
- onClick: () => ui.set({ draft: { ...draft, face } })
3112
- }, /* @__PURE__ */ React.createElement(Face, {
3113
- face,
3114
- size: 30
3115
- })))));
3116
- }
3117
- function NewAgentHead({ context }) {
3118
- const { pi, ui } = context;
3119
- const { draft, editing } = useUi(ui);
3120
- const w = ChannelViews.words(pi);
3121
- const Down = ChannelViews.icon(pi, "ChevronDown");
3122
- if (!draft) {
3123
- return null;
3124
- }
3388
+ }, [open]);
3125
3389
  return /* @__PURE__ */ React.createElement("div", {
3126
- className: "tac-new-head"
3127
- }, /* @__PURE__ */ React.createElement("div", {
3128
- className: "tac-new-title"
3390
+ className: "tac-item-more",
3391
+ ref: root
3129
3392
  }, /* @__PURE__ */ React.createElement("button", {
3130
3393
  type: "button",
3131
- className: "tac-new-trigger tac-identity-open",
3132
- "aria-expanded": editing,
3133
- title: w.editAgent,
3134
- onClick: () => ui.set({ editing: !editing })
3135
- }, /* @__PURE__ */ React.createElement(Face, {
3136
- face: draft.face,
3137
- size: 20
3138
- }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
3139
- size: 14
3140
- })), editing && /* @__PURE__ */ React.createElement(Identity, {
3141
- context,
3142
- onClose: () => ui.set({ editing: false })
3143
- })), /* @__PURE__ */ React.createElement("button", {
3394
+ className: `tac-action${open ? " tac-on" : ""}`,
3395
+ title: w.more,
3396
+ "aria-label": w.more,
3397
+ "aria-haspopup": "menu",
3398
+ "aria-expanded": open,
3399
+ onClick: (event) => {
3400
+ event.stopPropagation();
3401
+ if (open) {
3402
+ setOpen(false);
3403
+ } else {
3404
+ show(event.currentTarget);
3405
+ }
3406
+ }
3407
+ }, /* @__PURE__ */ React.createElement(Ellipsis, {
3408
+ size: 15
3409
+ })), open && /* @__PURE__ */ React.createElement("div", {
3410
+ ref: menu,
3411
+ className: "tac-menu tac-agent-menu",
3412
+ role: "menu",
3413
+ "aria-label": label
3414
+ }, items().filter((section) => section.length > 0).map((section, index) => /* @__PURE__ */ React.createElement(React.Fragment, {
3415
+ key: section[0]?.key ?? index
3416
+ }, index > 0 && /* @__PURE__ */ React.createElement("hr", {
3417
+ className: "tac-menu-line"
3418
+ }), section.map((item) => /* @__PURE__ */ React.createElement("button", {
3419
+ key: item.key,
3144
3420
  type: "button",
3145
- className: "tac-button tac-quiet",
3421
+ role: "menuitem",
3422
+ className: item.danger ? "tac-danger" : undefined,
3423
+ disabled: item.disabled,
3146
3424
  onClick: () => {
3147
- ui.set({ draft: undefined, editing: false });
3148
- pi.ui.showView("");
3425
+ setOpen(false);
3426
+ item.run();
3149
3427
  }
3150
- }, w.cancel));
3428
+ }, item.icon, /* @__PURE__ */ React.createElement("span", {
3429
+ className: "tac-menu-label"
3430
+ }, item.label)))))));
3151
3431
  }
3152
- function NewAgentPage({ context }) {
3153
- const { pi, service, ui } = context;
3154
- const { draft } = useUi(ui);
3155
- const { loaded } = useChannels(service);
3156
- const w = ChannelViews.words(pi);
3157
- const Pencil = ChannelViews.icon(pi, "Pencil");
3158
- const Composer = pi.ui.Composer;
3159
- const first = React.useRef(true);
3160
- React.useEffect(() => {
3161
- if (!loaded || !first.current) {
3432
+
3433
+ // web-src/agent-menu.tsx
3434
+ async function copy(text) {
3435
+ try {
3436
+ await navigator.clipboard.writeText(text);
3437
+ return true;
3438
+ } catch {
3439
+ return false;
3440
+ }
3441
+ }
3442
+ function download(name, text) {
3443
+ const url = URL.createObjectURL(new Blob([text], { type: "text/markdown;charset=utf-8" }));
3444
+ const link = document.createElement("a");
3445
+ link.href = url;
3446
+ link.download = name;
3447
+ link.click();
3448
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
3449
+ }
3450
+ async function deleteAgent(context, agent) {
3451
+ const w = ChannelViews.words(context.pi);
3452
+ const sure = await context.pi.ui.confirm(ChannelWords.format(w.confirmDeleteAgent, { name: agent.name }), undefined, {
3453
+ confirmLabel: w.delete,
3454
+ danger: true
3455
+ });
3456
+ if (sure) {
3457
+ await context.service.deleteAgent(agent.id);
3458
+ context.sessions.delete(agent.id);
3459
+ }
3460
+ }
3461
+ var AgentActions;
3462
+ ((AgentActions) => {
3463
+ function fail(context, error) {
3464
+ context.pi.ui.notify(ChannelViews.message(error), "error");
3465
+ }
3466
+ function run(context, action) {
3467
+ return () => {
3468
+ Promise.resolve().then(action).catch((error) => fail(context, error));
3469
+ };
3470
+ }
3471
+ AgentActions.run = run;
3472
+ async function openSession(context, agent) {
3473
+ if (!agent.sessionFile) {
3162
3474
  return;
3163
3475
  }
3164
- first.current = false;
3165
- if (!ui.state.draft) {
3166
- newAgent(context);
3476
+ return (await context.pi.server.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
3477
+ }
3478
+ async function stop(context, agent) {
3479
+ const session = await openSession(context, agent);
3480
+ if (session) {
3481
+ await context.pi.server.abort(session.sessionId);
3167
3482
  }
3168
- }, [loaded, ui, context]);
3169
- if (!draft) {
3170
- return null;
3483
+ context.pi.ui.notify(ChannelWords.format(ChannelViews.words(context.pi).stoppedAgent, { name: agent.name }), "info");
3171
3484
  }
3172
- const send = async (text) => {
3173
- const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
3174
- ui.set({ draft: undefined, editing: false });
3175
- try {
3176
- const sessionId = await service.openAgent(agent.id);
3177
- context.sessions.set(agent.id, sessionId);
3178
- await pi.switchSession(sessionId);
3179
- await pi.sendUserMessage(text);
3180
- } catch (error) {
3181
- pi.ui.notify(ChannelViews.message(error), "error");
3485
+ AgentActions.stop = stop;
3486
+ async function restart(context, agent) {
3487
+ await context.service.resetAgent(agent.id);
3488
+ context.sessions.delete(agent.id);
3489
+ context.pi.ui.notify(ChannelWords.format(ChannelViews.words(context.pi).resetDone, { name: agent.name }), "info");
3490
+ }
3491
+ AgentActions.restart = restart;
3492
+ async function copyCwd(context, cwd) {
3493
+ if (await copy(cwd)) {
3494
+ context.pi.ui.notify(ChannelWords.format(ChannelViews.words(context.pi).copied, { path: cwd }), "info");
3182
3495
  }
3183
- };
3184
- return /* @__PURE__ */ React.createElement("div", {
3185
- className: "tac-new-page"
3186
- }, /* @__PURE__ */ React.createElement("div", {
3187
- className: "tac-new-col"
3188
- }, /* @__PURE__ */ React.createElement(Face, {
3189
- face: draft.face,
3190
- size: 88
3191
- }), /* @__PURE__ */ React.createElement("h2", {
3192
- className: "tac-new-name"
3193
- }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
3194
- type: "button",
3195
- className: "tac-action tac-identity-open",
3196
- title: w.editAgent,
3197
- "aria-label": w.editAgent,
3198
- onClick: () => ui.set({ editing: !ui.state.editing })
3199
- }, /* @__PURE__ */ React.createElement(Pencil, {
3200
- size: 14
3201
- }))), /* @__PURE__ */ React.createElement("p", {
3202
- className: "tac-new-hint"
3203
- }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
3204
- className: "tac-new-box"
3205
- }, /* @__PURE__ */ React.createElement(Composer, {
3206
- placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
3207
- onSend: send,
3208
- cwd: draft.cwd,
3209
- onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
3210
- draft: "new-agent"
3211
- }))));
3212
- }
3213
- function NewChannelDialog({ context, onClose }) {
3496
+ }
3497
+ AgentActions.copyCwd = copyCwd;
3498
+ async function exportChat(context, agent) {
3499
+ const { pi, service } = context;
3500
+ const w = ChannelViews.words(pi);
3501
+ const session = await openSession(context, agent);
3502
+ const sessionId = session?.sessionId ?? (agent.sessionFile ? await service.openAgent(agent.id) : undefined);
3503
+ const { messages } = sessionId ? await pi.server.getMessages(sessionId) : { messages: [] };
3504
+ if (!messages.some((message) => message.role === "assistant")) {
3505
+ pi.ui.notify(ChannelWords.format(w.nothingToExport, { name: agent.name }), "info");
3506
+ return;
3507
+ }
3508
+ download(`${agent.name}.md`, ChannelsText.markdown(agent, messages, { user: w.you }));
3509
+ }
3510
+ AgentActions.exportChat = exportChat;
3511
+ function show(context, Dialog, agent) {
3512
+ context.pi.ui.custom(({ close }) => /* @__PURE__ */ React.createElement(Dialog, {
3513
+ context,
3514
+ agent,
3515
+ onClose: close
3516
+ }));
3517
+ }
3518
+ function shareCard(context, agent) {
3519
+ show(context, CardDialog, agent);
3520
+ }
3521
+ AgentActions.shareCard = shareCard;
3522
+ function joinChannel(context, agent) {
3523
+ show(context, JoinDialog, agent);
3524
+ }
3525
+ AgentActions.joinChannel = joinChannel;
3526
+ async function profile(context, agent) {
3527
+ await ChannelViews.openAgent(context, agent.id);
3528
+ await context.pi.ui.showView(AGENT_INFO_VIEW);
3529
+ }
3530
+ AgentActions.profile = profile;
3531
+ function menu(context, agent, working) {
3532
+ const w = ChannelViews.words(context.pi);
3533
+ const edits = ChannelsUtil.may(context.service.state.team).agent(agent.id);
3534
+ const icon = (name) => ChannelViews.icon(context.pi, name);
3535
+ return [
3536
+ [
3537
+ { key: "stop", label: w.stop, icon: icon("Square"), disabled: !working && !agent.sessionFile, run: run(context, () => stop(context, agent)) },
3538
+ ...edits ? [{ key: "restart", label: w.restart, icon: icon("RotateCcw"), run: run(context, () => restart(context, agent)) }] : []
3539
+ ],
3540
+ [
3541
+ ...edits ? [{ key: "card", label: w.shareCard, icon: icon("Contact"), run: () => shareCard(context, agent) }] : [],
3542
+ ...edits ? [{ key: "join", label: w.joinChannel, icon: icon("UserPlus"), run: () => joinChannel(context, agent) }] : [],
3543
+ { key: "export", label: w.exportChat, icon: icon("Download"), run: run(context, () => exportChat(context, agent)) }
3544
+ ]
3545
+ ];
3546
+ }
3547
+ AgentActions.menu = menu;
3548
+ })(AgentActions ||= {});
3549
+ function AgentMenu({ context, agent, cwd, working }) {
3214
3550
  const { pi, service } = context;
3215
- const { team } = useChannels(service);
3216
- const faces = useFaces(team);
3217
3551
  const w = ChannelViews.words(pi);
3218
- const Search = ChannelViews.icon(pi, "Search");
3219
- const Check = ChannelViews.icon(pi, "Check");
3220
- const [name, setName] = React.useState("");
3221
- const [query, setQuery] = React.useState("");
3222
- const [picked, setPicked] = React.useState([]);
3223
- const friends = useFriends(pi);
3224
- const [pickedFriends, setPickedFriends] = React.useState([]);
3225
- const shared = pickedFriends.length > 0;
3226
- const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
3552
+ const [dialog, setDialog] = React.useState();
3553
+ const icon = (name) => ChannelViews.maybeIcon(pi, name, null, 15);
3554
+ const fail = (error) => pi.ui.notify(ChannelViews.message(error), "error");
3555
+ const act = (action) => AgentActions.run(context, action);
3556
+ const stop = act(() => AgentActions.stop(context, agent));
3557
+ const restart = act(() => AgentActions.restart(context, agent));
3558
+ const copyCwd = act(() => AgentActions.copyCwd(context, cwd));
3559
+ const exportMarkdown = act(() => AgentActions.exportChat(context, agent));
3560
+ const remove = act(() => deleteAgent(context, agent));
3561
+ const pin = act(() => service.updateAgent(agent.id, { pinned: !agent.pinned }));
3562
+ const keep = act(async () => {
3563
+ await service.updateAgent(agent.id, { keep: true });
3564
+ pi.ui.notify(ChannelWords.format(w.kept, { name: agent.name }), "info");
3565
+ });
3566
+ const show = (next) => () => setDialog(next);
3567
+ const edits = ChannelsUtil.may(service.state.team).agent(agent.id);
3568
+ const item = (key, label, glyph, run, options = {}) => ({
3569
+ key,
3570
+ label,
3571
+ icon: icon(glyph),
3572
+ run,
3573
+ ...options
3574
+ });
3575
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(MoreMenu, {
3576
+ pi,
3577
+ label: agent.name,
3578
+ items: () => [
3579
+ edits ? [
3580
+ ...agent.temporary ? [item("keep", w.keep, "UserPlus", keep)] : [],
3581
+ item("pin", agent.pinned ? w.unpin : w.pin, agent.pinned ? "PinOff" : "Pin", pin)
3582
+ ] : [],
3583
+ [
3584
+ item("stop", w.stop, "Square", stop, { disabled: !working && !agent.sessionFile }),
3585
+ ...edits ? [item("restart", w.restart, "RotateCcw", restart)] : []
3586
+ ],
3587
+ edits ? [
3588
+ item("settings", w.agentSettings, "SlidersHorizontal", show("settings")),
3589
+ item("rename", w.rename, "Pencil", show("rename")),
3590
+ item("role", w.editRole, "ScrollText", show("role")),
3591
+ item("move", w.moveTo, "FolderInput", show("move")),
3592
+ item("copy", w.copyCwd, "Copy", copyCwd)
3593
+ ] : [],
3594
+ [
3595
+ ...edits ? [item("card", w.shareCard, "Contact", show("card"))] : [],
3596
+ item("export", w.exportChat, "Download", exportMarkdown),
3597
+ ...edits ? [item("join", w.joinChannel, "UserPlus", show("join"))] : []
3598
+ ],
3599
+ edits ? [item("delete", w.deleteAgent, "Trash2", remove, { danger: true })] : []
3600
+ ]
3601
+ }), dialog === "settings" && /* @__PURE__ */ React.createElement(AgentSettingsDialog, {
3602
+ context,
3603
+ agent,
3604
+ onClose: () => setDialog(undefined)
3605
+ }), dialog === "rename" && /* @__PURE__ */ React.createElement(RenameDialog, {
3606
+ context,
3607
+ agent,
3608
+ onClose: () => setDialog(undefined)
3609
+ }), dialog === "role" && /* @__PURE__ */ React.createElement(RoleDialog, {
3610
+ context,
3611
+ agent,
3612
+ onClose: () => setDialog(undefined)
3613
+ }), dialog === "join" && /* @__PURE__ */ React.createElement(JoinDialog, {
3614
+ context,
3615
+ agent,
3616
+ onClose: () => setDialog(undefined)
3617
+ }), dialog === "card" && /* @__PURE__ */ React.createElement(CardDialog, {
3618
+ context,
3619
+ agent,
3620
+ onClose: () => setDialog(undefined)
3621
+ }), dialog === "move" && /* @__PURE__ */ React.createElement(pi.ui.FolderPicker, {
3622
+ initial: cwd,
3623
+ onClose: () => setDialog(undefined),
3624
+ onPick: async (path) => {
3625
+ setDialog(undefined);
3626
+ if (path !== cwd) {
3627
+ await service.updateAgent(agent.id, { cwd: path }).catch(fail);
3628
+ context.sessions.delete(agent.id);
3629
+ }
3630
+ }
3631
+ }));
3632
+ }
3633
+ function useSave(action, onClose) {
3227
3634
  const [busy, setBusy] = React.useState(false);
3228
3635
  const [error, setError] = React.useState();
3229
- const Dialog = pi.ui.Dialog;
3230
- const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
3231
- const full = picked.length >= MAX_MEMBERS;
3232
- const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
3233
- const create = (event) => {
3636
+ const submit = (event) => {
3234
3637
  event.preventDefault();
3235
3638
  setBusy(true);
3236
3639
  setError(undefined);
3237
- if (shared) {
3238
- createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
3239
- setBusy(false);
3240
- setError(ChannelViews.message(failure));
3241
- });
3242
- return;
3243
- }
3244
- service.createChannel({ name, members: picked }).then((channel) => {
3245
- onClose();
3246
- context.showChannel(channel.id);
3247
- }, (failure) => {
3640
+ action().then(onClose, (failure) => {
3248
3641
  setBusy(false);
3249
3642
  setError(ChannelViews.message(failure));
3250
3643
  });
3251
3644
  };
3252
- return /* @__PURE__ */ React.createElement(Dialog, {
3253
- title: w.newChannel,
3645
+ return { busy, error, submit };
3646
+ }
3647
+ function AgentSettingsDialog({ context, agent, onClose }) {
3648
+ const { pi, service } = context;
3649
+ const w = ChannelViews.words(pi);
3650
+ const [name, setName] = React.useState(agent.name);
3651
+ const [model, setModel] = React.useState(agent.model ?? "");
3652
+ const [role, setRole] = React.useState(agent.role);
3653
+ const change = {
3654
+ ...name.trim() !== agent.name ? { name } : {},
3655
+ ...model !== (agent.model ?? "") ? { model } : {},
3656
+ ...role.trim() !== agent.role ? { role } : {}
3657
+ };
3658
+ const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, change), onClose);
3659
+ return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
3660
+ title: `${w.agentSettings} · ${agent.name}`,
3254
3661
  onClose
3255
3662
  }, /* @__PURE__ */ React.createElement("form", {
3256
3663
  className: "tac-dialog",
3257
- onSubmit: create
3664
+ onSubmit: submit
3258
3665
  }, /* @__PURE__ */ React.createElement("label", {
3259
3666
  className: "tac-dialog-label"
3260
3667
  }, w.name, /* @__PURE__ */ React.createElement("input", {
3261
3668
  className: "tac-input tac-dialog-input",
3262
3669
  value: name,
3263
- placeholder: w.channelNamePlaceholder,
3264
- maxLength: 40,
3265
- autoFocus: true,
3670
+ maxLength: 32,
3266
3671
  onChange: (event) => setName(event.target.value)
3267
3672
  })), /* @__PURE__ */ React.createElement("div", {
3673
+ className: "tac-dialog-field"
3674
+ }, /* @__PURE__ */ React.createElement("span", null, w.model), /* @__PURE__ */ React.createElement(pi.ui.ModelPicker, {
3675
+ cwd: agent.cwd,
3676
+ value: model,
3677
+ label: w.model,
3678
+ onChange: setModel
3679
+ })), /* @__PURE__ */ React.createElement("label", {
3268
3680
  className: "tac-dialog-label"
3269
- }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
3270
- className: "tac-dialog-count"
3271
- }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
3272
- className: "tac-dialog-search"
3273
- }, /* @__PURE__ */ React.createElement(Search, {
3274
- size: 15
3275
- }), /* @__PURE__ */ React.createElement("input", {
3276
- value: query,
3277
- placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
3278
- "aria-label": w.search,
3279
- onChange: (event) => setQuery(event.target.value)
3280
- })), /* @__PURE__ */ React.createElement("div", {
3281
- className: "tac-pick-list"
3282
- }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
3283
- compact: true,
3284
- title: w.noAgents,
3285
- hint: w.noAgentsHint
3286
- }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
3287
- compact: true,
3288
- title: w.noMatch
3289
- }), shown.map((agent) => {
3290
- const on = picked.includes(agent.id);
3291
- return /* @__PURE__ */ React.createElement("button", {
3292
- key: agent.id,
3293
- type: "button",
3294
- "aria-pressed": on,
3295
- disabled: !on && full,
3296
- className: `tac-pick${on ? " tac-on" : ""}`,
3297
- onClick: () => toggle(agent)
3298
- }, /* @__PURE__ */ React.createElement("span", {
3299
- className: "tac-check"
3300
- }, on && /* @__PURE__ */ React.createElement(Check, {
3301
- size: 13,
3302
- strokeWidth: 3
3303
- })), /* @__PURE__ */ React.createElement(AgentAvatar, {
3304
- agent,
3305
- faces,
3306
- size: 30
3307
- }), /* @__PURE__ */ React.createElement("span", {
3308
- className: "tac-pick-text"
3309
- }, /* @__PURE__ */ React.createElement("span", {
3310
- className: "tac-pick-name"
3311
- }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
3312
- className: "tac-msg-lead"
3313
- }, w.lead)), /* @__PURE__ */ React.createElement("span", {
3314
- className: "tac-pick-role"
3315
- }, agent.role.split(`
3316
- `)[0])));
3317
- })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
3318
- className: "tac-dialog-label"
3319
- }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
3320
- className: "tac-dialog-count"
3321
- }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
3322
- className: "tac-pick-list"
3323
- }, friends.map((friend) => {
3324
- const on = pickedFriends.includes(friend.id);
3325
- return /* @__PURE__ */ React.createElement("button", {
3326
- key: friend.id,
3327
- type: "button",
3328
- "aria-pressed": on,
3329
- className: `tac-pick${on ? " tac-on" : ""}`,
3330
- onClick: () => toggleFriend(friend)
3331
- }, /* @__PURE__ */ React.createElement("span", {
3332
- className: "tac-check"
3333
- }, on && /* @__PURE__ */ React.createElement(Check, {
3334
- size: 13,
3335
- strokeWidth: 3
3336
- })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
3337
- seed: friend.id,
3338
- size: 30,
3339
- look: friend.look
3340
- }) : /* @__PURE__ */ React.createElement("span", {
3341
- className: "tac-pick-face"
3342
- }), /* @__PURE__ */ React.createElement("span", {
3343
- className: "tac-pick-text"
3344
- }, /* @__PURE__ */ React.createElement("span", {
3345
- className: "tac-pick-name"
3346
- }, friend.name), /* @__PURE__ */ React.createElement("span", {
3347
- className: "tac-pick-role"
3348
- }, w.friend)));
3349
- }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
3681
+ }, w.editRole, /* @__PURE__ */ React.createElement("textarea", {
3682
+ className: "tac-input tac-settings-role",
3683
+ value: role,
3684
+ placeholder: w.rolePlaceholder,
3685
+ onChange: (event) => setRole(event.target.value)
3686
+ })), /* @__PURE__ */ React.createElement("p", {
3350
3687
  className: "tac-dialog-note"
3351
- }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
3352
- className: "tac-empty tac-error"
3688
+ }, w.agentSettingsHint), error && /* @__PURE__ */ React.createElement("div", {
3689
+ className: "tac-error"
3353
3690
  }, error), /* @__PURE__ */ React.createElement("div", {
3354
3691
  className: "tac-dialog-actions"
3355
3692
  }, /* @__PURE__ */ React.createElement("button", {
3356
3693
  type: "submit",
3357
3694
  className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
3358
- disabled: busy || !name.trim() || picked.length === 0 && !shared
3359
- }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
3695
+ disabled: busy || !name.trim() || !role.trim() || Object.keys(change).length === 0
3696
+ }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
3360
3697
  className: "ta-spinner ta-busy-mark ta-on-brand"
3361
3698
  })))));
3362
3699
  }
3363
-
3364
- // web-src/handoff.ts
3365
- var HandOff;
3366
- ((HandOff) => {
3367
- HandOff.TOOL = "hand_off";
3368
- HandOff.CARD = "ta-channels-handoff";
3369
- HandOff.BLOCK = "ta-handoff";
3370
- const MARK = /\[ta-handoff:([^\]\s]+)\]/;
3371
- HandOff.DEFINITION = {
3372
- name: HandOff.TOOL,
3373
- label: "Hand off",
3374
- description: "Hands the work of this conversation over to one of the user's agents (@name) or channels (#name), when the user says so (hand it to, give it to, 交给, 转给). The other side does not see this conversation: write the brief it needs to go on, in the user's language: the goal, what is done and decided, what is left or blocks, the files, branches, commands and links that matter. It works on it in its own conversation, which the user follows; you stop working on it here. list_channels lists the team. After the call, say in one line to whom it went.",
3375
- promptSnippet: "Hand the work over to one of the user's agents or channels",
3376
- parameters: {
3377
- type: "object",
3378
- properties: {
3379
- to: { type: "string", description: "@name of an agent or #name of a channel." },
3380
- brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
3381
- },
3382
- required: ["to", "brief"]
3383
- }
3700
+ function RenameDialog({ context, agent, onClose }) {
3701
+ const { pi, service } = context;
3702
+ const w = ChannelViews.words(pi);
3703
+ const [name, setName] = React.useState(agent.name);
3704
+ const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { name }), onClose);
3705
+ return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
3706
+ title: w.rename,
3707
+ onClose
3708
+ }, /* @__PURE__ */ React.createElement("form", {
3709
+ className: "tac-dialog",
3710
+ onSubmit: submit
3711
+ }, /* @__PURE__ */ React.createElement("label", {
3712
+ className: "tac-dialog-label"
3713
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
3714
+ className: "tac-input tac-dialog-input",
3715
+ value: name,
3716
+ maxLength: 32,
3717
+ autoFocus: true,
3718
+ onChange: (event) => setName(event.target.value)
3719
+ })), error && /* @__PURE__ */ React.createElement("div", {
3720
+ className: "tac-error"
3721
+ }, error), /* @__PURE__ */ React.createElement("div", {
3722
+ className: "tac-dialog-actions"
3723
+ }, /* @__PURE__ */ React.createElement("button", {
3724
+ type: "submit",
3725
+ className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
3726
+ disabled: busy || !name.trim() || name.trim() === agent.name
3727
+ }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
3728
+ className: "ta-spinner ta-busy-mark ta-on-brand"
3729
+ })))));
3730
+ }
3731
+ function RoleDialog({ context, agent, onClose }) {
3732
+ const { pi, service } = context;
3733
+ const w = ChannelViews.words(pi);
3734
+ const [role, setRole] = React.useState(agent.role);
3735
+ const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { role }), onClose);
3736
+ return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
3737
+ title: `${w.editRole} · ${agent.name}`,
3738
+ onClose
3739
+ }, /* @__PURE__ */ React.createElement("form", {
3740
+ className: "tac-dialog",
3741
+ onSubmit: submit
3742
+ }, /* @__PURE__ */ React.createElement("p", {
3743
+ className: "tac-dialog-note"
3744
+ }, w.roleHint), /* @__PURE__ */ React.createElement("textarea", {
3745
+ className: "tac-input tac-role-input",
3746
+ value: role,
3747
+ placeholder: w.rolePlaceholder,
3748
+ "aria-label": w.editRole,
3749
+ autoFocus: true,
3750
+ onChange: (event) => setRole(event.target.value)
3751
+ }), error && /* @__PURE__ */ React.createElement("div", {
3752
+ className: "tac-error"
3753
+ }, error), /* @__PURE__ */ React.createElement("div", {
3754
+ className: "tac-dialog-actions"
3755
+ }, /* @__PURE__ */ React.createElement("button", {
3756
+ type: "submit",
3757
+ className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
3758
+ disabled: busy || !role.trim() || role.trim() === agent.role
3759
+ }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
3760
+ className: "ta-spinner ta-busy-mark ta-on-brand"
3761
+ })))));
3762
+ }
3763
+ function JoinDialog({ context, agent, onClose }) {
3764
+ const { pi, service } = context;
3765
+ const { team } = useChannels(service);
3766
+ const w = ChannelViews.words(pi);
3767
+ const Hash = ChannelViews.icon(pi, "Hash");
3768
+ const [error, setError] = React.useState();
3769
+ const open = team.channels.filter((channel) => !channel.members.includes(agent.id));
3770
+ const join = (channelId, name) => {
3771
+ service.addMembers(channelId, [agent.id]).then(() => {
3772
+ onClose();
3773
+ pi.ui.notify(ChannelWords.format(w.joined, { name: agent.name, channel: name }), "info");
3774
+ }, (failure) => setError(ChannelViews.message(failure)));
3384
3775
  };
3385
- function ref(target) {
3386
- return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
3387
- }
3388
- HandOff.ref = ref;
3389
- function ask(language, to) {
3390
- const fence = "```";
3391
- const context = [
3392
- `[ta-handoff:${to}]`,
3393
- `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
3394
- `- Write the brief it needs to go on: the goal, what is done and decided, what is left or blocks, the files, branches, commands and links that matter, in the user's language. Leave out what was only tried and dropped.`,
3395
- `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
3396
- `- Without it, say in one line what you hand over, then end your answer with the brief in a fenced block of the language ${HandOff.BLOCK}, which Ta reads to hand it over (a longer fence when the brief has one of its own):`,
3397
- `${fence}${HandOff.BLOCK}`,
3398
- "<the brief>",
3399
- fence,
3400
- `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
3401
- ].join(`
3402
- `);
3403
- const line = TaLanguageUtil.pick(language, {
3404
- "zh-CN": `把这件事交给 ${to}`,
3405
- "zh-TW": `把這件事交給 ${to}`,
3406
- "en-US": `Hand this over to ${to}`,
3407
- "ja-JP": `これを ${to} に引き継ぐ`
3408
- });
3409
- return TaMessageContext.wrap(context, line);
3776
+ return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
3777
+ title: `${w.joinChannel} · ${agent.name}`,
3778
+ onClose
3779
+ }, /* @__PURE__ */ React.createElement("div", {
3780
+ className: "tac-dialog"
3781
+ }, /* @__PURE__ */ React.createElement("div", {
3782
+ className: "tac-pick-list"
3783
+ }, open.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
3784
+ compact: true,
3785
+ title: w.noChannelToJoin
3786
+ }), open.map((channel) => /* @__PURE__ */ React.createElement("button", {
3787
+ key: channel.id,
3788
+ type: "button",
3789
+ className: "tac-pick",
3790
+ disabled: channel.members.length >= MAX_MEMBERS,
3791
+ onClick: () => join(channel.id, channel.name)
3792
+ }, /* @__PURE__ */ React.createElement(Hash, {
3793
+ size: 16
3794
+ }), /* @__PURE__ */ React.createElement("span", {
3795
+ className: "tac-pick-text"
3796
+ }, /* @__PURE__ */ React.createElement("span", {
3797
+ className: "tac-pick-name"
3798
+ }, channel.name), /* @__PURE__ */ React.createElement("span", {
3799
+ className: "tac-pick-role"
3800
+ }, channel.topic ?? ChannelWords.format(w.memberCount, { count: String(channel.members.length) })))))), error && /* @__PURE__ */ React.createElement("div", {
3801
+ className: "tac-error"
3802
+ }, error)));
3803
+ }
3804
+ function useShownAgent(context) {
3805
+ const { pi, service } = context;
3806
+ const { team } = useChannels(service);
3807
+ const sessionId = pi.ui.useSessionId();
3808
+ const sessions = pi.ui.useSessions();
3809
+ const channelPage = !!pi.ui.useView(CHANNEL_PAGE)?.shown;
3810
+ if (channelPage || !sessionId) {
3811
+ return;
3410
3812
  }
3411
- HandOff.ask = ask;
3412
- function asked(text) {
3413
- return MARK.exec(text)?.[1];
3813
+ const file = sessions.find((session) => session.sessionId === sessionId)?.sessionFile;
3814
+ return team.agents.find((agent) => !!file && agent.sessionFile === file || context.sessions.get(agent.id) === sessionId);
3815
+ }
3816
+ function AgentInfoView({ context }) {
3817
+ const { pi, service } = context;
3818
+ const { team, working, loaded } = useChannels(service);
3819
+ const w = ChannelViews.words(pi);
3820
+ const [dialog, setDialog] = React.useState();
3821
+ const serverCwd = useServerCwd(pi);
3822
+ const faces = useFaces(team);
3823
+ const agent = useShownAgent(context);
3824
+ if (!agent) {
3825
+ return /* @__PURE__ */ React.createElement("div", {
3826
+ className: "tac-view tac-members"
3827
+ }, loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
3828
+ title: w.noAgentOpen
3829
+ }));
3414
3830
  }
3415
- HandOff.asked = asked;
3416
- function find(text) {
3417
- const lines = text.split(/\r?\n/);
3418
- let found;
3419
- for (let index = 0;index < lines.length; index++) {
3420
- const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
3421
- if (open?.[2] !== HandOff.BLOCK) {
3422
- continue;
3423
- }
3424
- const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
3425
- const end = lines.findIndex((line, at) => at > index && close.test(line));
3426
- found = lines.slice(index + 1, end < 0 ? lines.length : end);
3427
- index = end < 0 ? lines.length : end;
3831
+ const edits = ChannelsUtil.may(team).agent(agent.id);
3832
+ const busy = Object.values(working).some((ids) => ids.includes(agent.id));
3833
+ const cwd = agent.cwd ?? serverCwd ?? "";
3834
+ const Chevron = ChannelViews.icon(pi, "ChevronRight");
3835
+ const Trash = ChannelViews.icon(pi, "Trash2");
3836
+ const HostTag = pi.ui.HostTag;
3837
+ const fail = (error) => pi.ui.notify(ChannelViews.message(error), "error");
3838
+ const act = (action2) => AgentActions.run(context, action2);
3839
+ const rename = act(async () => {
3840
+ const name = await pi.ui.input(w.rename, w.name, { value: agent.name });
3841
+ if (name !== undefined && name.trim() && name.trim() !== agent.name) {
3842
+ await service.updateAgent(agent.id, { name });
3428
3843
  }
3429
- const brief = found?.join(`
3430
- `).trim();
3431
- return brief || undefined;
3432
- }
3433
- HandOff.find = find;
3434
- function message(origin, brief, language) {
3435
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
3436
- const head = TaLanguageUtil.pick(language, {
3437
- "zh-CN": `(交接自“${title}”)`,
3438
- "zh-TW": `(交接自「${title}」)`,
3439
- "en-US": `(Handed over from “${title}”)`,
3440
- "ja-JP": `(“${title}” から引き継ぎました)`
3441
- });
3442
- const context = [
3443
- "The user handed you this work from another conversation of theirs, which you do not see; the brief below is all it says. Go on from there in this conversation, which the user follows; ask them when the brief leaves out something you need.",
3444
- origin.sessionFile ? `That conversation is pi's session file ${origin.sessionFile}${origin.cwd ? `, working in ${origin.cwd}` : ""}: read it only when the brief is not enough.` : ""
3445
- ].filter(Boolean).join(`
3446
- `);
3447
- return TaMessageContext.wrap(context, `${head}
3448
-
3449
- ${brief.trim()}`);
3450
- }
3451
- HandOff.message = message;
3452
- function channelText(origin, brief, language) {
3453
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
3454
- return `${TaLanguageUtil.pick(language, {
3455
- "zh-CN": `(交接自“${title}”)`,
3456
- "zh-TW": `(交接自「${title}」)`,
3457
- "en-US": `(Handed over from “${title}”)`,
3458
- "ja-JP": `(“${title}” から引き継ぎました)`
3459
- })}
3460
-
3461
- ${brief.trim()}`;
3462
- }
3463
- HandOff.channelText = channelText;
3464
- function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
3465
- return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
3466
- }
3467
- HandOff.serverLanguage = serverLanguage;
3468
- function result(target) {
3469
- return `Handed over to ${ref(target)}; it works on it in its own conversation, which the user follows. Do not go on with it here.`;
3470
- }
3471
- HandOff.result = result;
3472
- })(HandOff ||= {});
3473
-
3474
- // web-src/handoff-view.tsx
3475
- var HandOffViewUtil;
3476
- ((HandOffViewUtil) => {
3477
- function members(team, target) {
3478
- if (target.kind === "agent") {
3479
- const agent = team.agents.find((candidate) => candidate.id === target.id);
3480
- return agent ? [agent] : [];
3481
- }
3482
- const channel = team.channels.find((candidate) => candidate.id === target.id);
3483
- return channel ? membersOf(team, channel) : [];
3484
- }
3485
- HandOffViewUtil.members = members;
3486
- })(HandOffViewUtil ||= {});
3487
- function useTeam(context) {
3488
- return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
3489
- }
3490
- function HandOffCard({ context, message }) {
3491
- const card = message.details;
3492
- const team = useTeam(context);
3493
- const faces = useFaces(team);
3494
- if (!card?.target) {
3495
- return null;
3496
- }
3497
- const w = ChannelViews.words(context.pi);
3498
- const members = HandOffViewUtil.members(team, card.target);
3499
- const open = () => card.target.kind === "agent" ? void ChannelViews.openAgent(context, card.target.id).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error")) : context.showChannel(card.target.id);
3844
+ });
3845
+ const row = (label, value, edit) => edit && edits ? /* @__PURE__ */ React.createElement("button", {
3846
+ type: "button",
3847
+ className: "tac-setting",
3848
+ onClick: edit
3849
+ }, /* @__PURE__ */ React.createElement("span", {
3850
+ className: "tac-setting-label"
3851
+ }, label), /* @__PURE__ */ React.createElement("span", {
3852
+ className: "tac-setting-value"
3853
+ }, value), /* @__PURE__ */ React.createElement(Chevron, {
3854
+ size: 15
3855
+ })) : /* @__PURE__ */ React.createElement("div", {
3856
+ className: "tac-setting"
3857
+ }, /* @__PURE__ */ React.createElement("span", {
3858
+ className: "tac-setting-label"
3859
+ }, label), /* @__PURE__ */ React.createElement("span", {
3860
+ className: "tac-setting-value"
3861
+ }, value));
3862
+ const action = (label, run) => /* @__PURE__ */ React.createElement("button", {
3863
+ type: "button",
3864
+ className: "tac-setting",
3865
+ onClick: run
3866
+ }, /* @__PURE__ */ React.createElement("span", {
3867
+ className: "tac-setting-label"
3868
+ }, label), /* @__PURE__ */ React.createElement(Chevron, {
3869
+ size: 15
3870
+ }));
3500
3871
  return /* @__PURE__ */ React.createElement("div", {
3501
- className: "tac-handoff"
3872
+ className: "tac-view tac-members"
3502
3873
  }, /* @__PURE__ */ React.createElement("div", {
3503
- className: "tac-handoff-head"
3504
- }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
3505
- members,
3506
- faces,
3507
- size: 20,
3508
- working: []
3874
+ className: "tac-members-scroll"
3875
+ }, /* @__PURE__ */ React.createElement("div", {
3876
+ className: "tac-members-top"
3877
+ }, /* @__PURE__ */ React.createElement(Face, {
3878
+ face: faces.get(agent.id) ?? agent.face ?? 0,
3879
+ size: 44,
3880
+ working: busy
3509
3881
  }), /* @__PURE__ */ React.createElement("span", {
3510
- className: "tac-handoff-title"
3511
- }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
3882
+ className: "tac-members-title"
3883
+ }, /* @__PURE__ */ React.createElement("strong", null, agent.name), /* @__PURE__ */ React.createElement("span", null, agent.role.split(`
3884
+ `)[0] || w.agentTag))), /* @__PURE__ */ React.createElement("div", {
3885
+ className: "tac-members-sep"
3886
+ }), row(w.name, agent.name, rename), /* @__PURE__ */ React.createElement("div", {
3887
+ className: "tac-setting tac-setting-model"
3888
+ }, /* @__PURE__ */ React.createElement("span", {
3889
+ className: "tac-setting-label"
3890
+ }, w.model), edits ? /* @__PURE__ */ React.createElement(pi.ui.ModelPicker, {
3891
+ cwd: agent.cwd,
3892
+ value: agent.model ?? "",
3893
+ label: w.model,
3894
+ onChange: (model) => void service.updateAgent(agent.id, { model }).catch(fail)
3895
+ }) : /* @__PURE__ */ React.createElement("span", {
3896
+ className: "tac-setting-value"
3897
+ }, agent.model || "—")), row(w.editRole, agent.role.split(`
3898
+ `)[0], () => setDialog("role")), row(w.workDir, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(HostTag, {
3899
+ location: cwd
3900
+ }), cwd && SidebarUtil.folder(cwd)), () => setDialog("move")), /* @__PURE__ */ React.createElement("div", {
3901
+ className: "tac-members-sep"
3902
+ }), edits && action(w.shareCard, () => AgentActions.shareCard(context, agent)), edits && action(w.joinChannel, () => AgentActions.joinChannel(context, agent)), action(w.exportChat, act(() => AgentActions.exportChat(context, agent))), cwd && action(w.copyCwd, act(() => AgentActions.copyCwd(context, cwd)))), edits && /* @__PURE__ */ React.createElement("div", {
3903
+ className: "tac-members-foot"
3904
+ }, /* @__PURE__ */ React.createElement("button", {
3512
3905
  type: "button",
3513
- className: "tac-link",
3514
- onClick: open
3515
- }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
3516
- className: "tac-handoff-brief"
3517
- }, card.brief));
3906
+ className: "tac-link tac-danger",
3907
+ onClick: act(() => deleteAgent(context, agent))
3908
+ }, /* @__PURE__ */ React.createElement(Trash, {
3909
+ size: 14
3910
+ }), w.deleteAgentLong)), dialog === "role" && /* @__PURE__ */ React.createElement(RoleDialog, {
3911
+ context,
3912
+ agent,
3913
+ onClose: () => setDialog(undefined)
3914
+ }), dialog === "move" && /* @__PURE__ */ React.createElement(pi.ui.FolderPicker, {
3915
+ initial: cwd,
3916
+ onClose: () => setDialog(undefined),
3917
+ onPick: async (path) => {
3918
+ setDialog(undefined);
3919
+ if (path !== cwd) {
3920
+ await service.updateAgent(agent.id, { cwd: path }).catch(fail);
3921
+ context.sessions.delete(agent.id);
3922
+ }
3923
+ }
3924
+ }));
3518
3925
  }
3519
- var HandOffView;
3520
- ((HandOffView) => {
3521
- function card(context) {
3522
- return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
3523
- context,
3524
- message
3525
- });
3926
+
3927
+ // web-src/channels.ts
3928
+ class ChannelsClient {
3929
+ storage;
3930
+ send;
3931
+ current = { team: ChannelsUtil.emptyTeam(), messages: {}, working: {}, answered: {}, loaded: false, deleting: [] };
3932
+ listeners = new Set;
3933
+ focusListeners = new Set;
3934
+ loading;
3935
+ pictures = new Map;
3936
+ unlisten;
3937
+ constructor(storage, send) {
3938
+ this.storage = storage;
3939
+ this.send = send;
3940
+ this.unlisten = storage.onChange((keys) => void this.changed(keys));
3526
3941
  }
3527
- HandOffView.card = card;
3528
- function icon(context, target, icons) {
3529
- const key = `${target.kind}:${target.id}`;
3530
- let node2 = icons.get(key);
3531
- if (!node2) {
3532
- const Face2 = () => {
3533
- const team = useTeam(context);
3534
- const faces = useFaces(team);
3535
- const members = HandOffViewUtil.members(team, target);
3536
- return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
3537
- members,
3538
- faces,
3539
- size: 16,
3540
- working: []
3541
- }) : null;
3542
- };
3543
- node2 = /* @__PURE__ */ React.createElement(Face2, null);
3544
- icons.set(key, node2);
3545
- }
3546
- return node2;
3942
+ get state() {
3943
+ return this.current;
3547
3944
  }
3548
- function composerAddon(context) {
3549
- const icons = new Map;
3550
- const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
3551
- clientMessageId: ChannelsUtil.newId("handoff-ask"),
3552
- message: HandOff.ask(context.pi.ui.language, to),
3553
- streamingBehavior: "followUp"
3554
- }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
3555
- return {
3556
- actions: (conversation) => {
3557
- const { team } = context.service.state;
3558
- if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
3559
- return [];
3560
- }
3561
- const w = ChannelViews.words(context.pi);
3562
- const Forward = ChannelViews.icon(context.pi, "Forward");
3563
- const agents = team.agents.filter((agent) => !agent.temporary).map((agent) => ({
3564
- key: `handoff:agent:${agent.id}`,
3565
- label: agent.name,
3566
- detail: agent.role.split(`
3567
- `)[0],
3568
- group: w.agents,
3569
- icon: icon(context, { kind: "agent", id: agent.id }, icons),
3570
- run: () => send(conversation, `@${agent.name}`)
3571
- }));
3572
- const channels = team.channels.map((channel) => ({
3573
- key: `handoff:channel:${channel.id}`,
3574
- label: `#${channel.name}`,
3575
- detail: channel.topic,
3576
- group: w.channels,
3577
- icon: icon(context, { kind: "channel", id: channel.id }, icons),
3578
- run: () => send(conversation, `#${channel.name}`)
3579
- }));
3580
- return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
3581
- size: 16
3582
- }), items: [...agents, ...channels] }];
3583
- },
3584
- subscribe: (listener) => context.service.subscribe(listener)
3585
- };
3945
+ subscribe(listener) {
3946
+ this.listeners.add(listener);
3947
+ return () => this.listeners.delete(listener);
3586
3948
  }
3587
- HandOffView.composerAddon = composerAddon;
3588
- })(HandOffView ||= {});
3589
-
3590
- // web-src/round-rules.ts
3591
- var ChannelRounds;
3592
- ((ChannelRounds) => {
3593
- const SHORT = 20;
3594
- const MIN_PAIRS = 8;
3595
- const ALIKE = 0.8;
3596
- const PING_PONG = 4;
3597
- const NEW = 0.35;
3598
- const CHANGES = new Set(["edit", "write", "delete", "move"]);
3599
- function scale(watchedAt, pages, now) {
3600
- if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
3601
- return 2;
3602
- }
3603
- return pages === undefined || pages > 0 ? 1 : 0.5;
3949
+ onFocus(listener) {
3950
+ this.focusListeners.add(listener);
3951
+ return () => this.focusListeners.delete(listener);
3604
3952
  }
3605
- ChannelRounds.scale = scale;
3606
- function idle(said, progress) {
3607
- const last = said.at(-1);
3608
- if (!last) {
3609
- return;
3610
- }
3611
- const pairs = said.map((item) => pairsOf(item.text));
3612
- const mine = pairs[pairs.length - 1];
3613
- if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
3614
- return "repeat";
3615
- }
3616
- const recent = said.slice(-3);
3617
- if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
3618
- return "agree";
3619
- }
3620
- const run = said.slice(-PING_PONG);
3621
- const authors = new Set(run.map((item) => item.author));
3622
- const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
3623
- const start = said.length - PING_PONG;
3624
- if (progress || start <= 0 || authors.size !== 2 || !alternate) {
3625
- return;
3626
- }
3627
- const seen = new Set(pairs.slice(0, start).flat());
3628
- for (const own of pairs.slice(start)) {
3629
- const fresh = own.filter((pair) => !seen.has(pair)).length;
3630
- if (own.length === 0 || fresh / own.length >= NEW) {
3631
- return;
3632
- }
3633
- for (const pair of own) {
3634
- seen.add(pair);
3635
- }
3953
+ dispose() {
3954
+ this.unlisten();
3955
+ }
3956
+ load(again = false) {
3957
+ if (!this.loading || again) {
3958
+ this.loading = Promise.all([
3959
+ this.storage.get(Keys.TEAM),
3960
+ this.storage.get(Keys.WORKING),
3961
+ this.storage.get(Keys.ANSWERED)
3962
+ ]).then(([team, working, answered]) => this.update({ team: team ?? ChannelsUtil.emptyTeam(), working: working ?? {}, answered: answered ?? {}, loaded: true }));
3636
3963
  }
3637
- return "pingPong";
3964
+ return this.loading;
3638
3965
  }
3639
- ChannelRounds.idle = idle;
3640
- function day(now) {
3641
- const date = new Date(now);
3642
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
3966
+ async messages(channelId, again = false) {
3967
+ const known = this.current.messages[channelId];
3968
+ if (known && !again) {
3969
+ return known;
3970
+ }
3971
+ const messages = await this.storage.get(Keys.messages(channelId)) ?? [];
3972
+ this.update({ messages: { ...this.current.messages, [channelId]: messages } });
3973
+ return messages;
3643
3974
  }
3644
- ChannelRounds.day = day;
3645
- function limits(stored) {
3646
- const given = stored ?? {};
3647
- const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
3648
- return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
3975
+ async createAgent(input) {
3976
+ const agent = await this.send({ kind: "createAgent", ...input });
3977
+ await this.load(true);
3978
+ return agent;
3649
3979
  }
3650
- ChannelRounds.limits = limits;
3651
- function today(stored, now) {
3652
- const current = day(now);
3653
- return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
3980
+ async createChannel(input) {
3981
+ const channel = await this.send({ kind: "createChannel", ...input });
3982
+ await this.load(true);
3983
+ return channel;
3654
3984
  }
3655
- ChannelRounds.today = today;
3656
- function spend(stored, channelId, tokens, now) {
3657
- const current = today(stored, now);
3658
- return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
3985
+ async addMembers(channelId, members) {
3986
+ const channel = await this.send({ kind: "addMembers", channel: channelId, members });
3987
+ await this.load(true);
3988
+ return channel;
3659
3989
  }
3660
- ChannelRounds.spend = spend;
3661
- function held(spent, limits2, channelId, hops, granted = false) {
3662
- if (granted) {
3663
- return;
3664
- }
3665
- if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
3666
- return "all";
3667
- }
3668
- if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
3669
- return "channel";
3990
+ async changeMember(channelId, agentId, change) {
3991
+ const channel = await this.send({ kind: "changeMember", channel: channelId, agent: agentId, change });
3992
+ await this.load(true);
3993
+ return channel;
3994
+ }
3995
+ async updateChannel(channelId, change) {
3996
+ const channel = await this.send({ kind: "updateChannel", channel: channelId, ...change });
3997
+ await this.load(true);
3998
+ return channel;
3999
+ }
4000
+ async deleteChannel(channelId) {
4001
+ await this.deleting(channelId, async () => {
4002
+ await this.send({ kind: "deleteChannel", channel: channelId });
4003
+ const { [channelId]: _gone, ...messages } = this.current.messages;
4004
+ this.update({ messages });
4005
+ await this.load(true);
4006
+ });
4007
+ }
4008
+ async resetAgent(agentId) {
4009
+ const agent = await this.send({ kind: "resetAgent", agent: agentId });
4010
+ await this.load(true);
4011
+ return agent;
4012
+ }
4013
+ async updateAgent(agentId, change) {
4014
+ const agent = await this.send({ kind: "updateAgent", agent: agentId, ...change });
4015
+ await this.load(true);
4016
+ return agent;
4017
+ }
4018
+ async setChannelModel(channelId, model) {
4019
+ const channel = await this.send({ kind: "setChannelModel", channel: channelId, model });
4020
+ await this.load(true);
4021
+ return channel;
4022
+ }
4023
+ async deleteAgent(agentId) {
4024
+ await this.deleting(agentId, async () => {
4025
+ await this.send({ kind: "deleteAgent", agent: agentId });
4026
+ await this.load(true);
4027
+ });
4028
+ }
4029
+ async deleting(id, action) {
4030
+ this.update({ deleting: [...this.current.deleting, id] });
4031
+ try {
4032
+ await action();
4033
+ } finally {
4034
+ this.update({ deleting: this.current.deleting.filter((other) => other !== id) });
3670
4035
  }
3671
- return;
3672
4036
  }
3673
- ChannelRounds.held = held;
3674
- function changedFiles(entries) {
3675
- for (const entry of entries) {
3676
- const message = entry?.message;
3677
- if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
3678
- continue;
3679
- }
3680
- for (const part of message.content) {
3681
- if (part?.type !== "toolCall") {
3682
- continue;
3683
- }
3684
- if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
3685
- return true;
4037
+ async openAgent(agentId) {
4038
+ const { sessionId } = await this.send({ kind: "openAgent", agent: agentId });
4039
+ return sessionId;
4040
+ }
4041
+ async setNotice(channelId, text) {
4042
+ const channel = await this.send({ kind: "setNotice", channel: channelId, text });
4043
+ await this.load(true);
4044
+ return channel;
4045
+ }
4046
+ shareAgent(agentId, color) {
4047
+ return this.send({ kind: "shareAgent", agent: agentId, ...color ? { color } : {} });
4048
+ }
4049
+ async stopCard(agentId) {
4050
+ return await this.send({ kind: "stopCard", agent: agentId });
4051
+ }
4052
+ openCard(link, password) {
4053
+ return this.send({ kind: "openCard", link, ...password ? { password } : {} });
4054
+ }
4055
+ async addFromCard(link, cwd, password) {
4056
+ const added = await this.send({ kind: "addFromCard", link, cwd, ...password ? { password } : {} });
4057
+ await this.load(true);
4058
+ return added;
4059
+ }
4060
+ async post(channelId, text, images = []) {
4061
+ await this.send({
4062
+ kind: "post",
4063
+ channel: channelId,
4064
+ text,
4065
+ ...images.length ? { images: images.map(({ data, mimeType, width, height }) => ({ data, mimeType, width, height })) } : {}
4066
+ });
4067
+ }
4068
+ picture(channelId, id) {
4069
+ const key = `${channelId}:${id}`;
4070
+ let read = this.pictures.get(key);
4071
+ if (!read) {
4072
+ read = this.send({ kind: "picture", channel: channelId, id }).then((data) => typeof data === "string" ? data : "", () => "");
4073
+ this.pictures.set(key, read);
4074
+ for (const old of this.pictures.keys()) {
4075
+ if (this.pictures.size <= 60) {
4076
+ break;
3686
4077
  }
4078
+ this.pictures.delete(old);
3687
4079
  }
3688
4080
  }
3689
- return false;
4081
+ return read;
3690
4082
  }
3691
- ChannelRounds.changedFiles = changedFiles;
3692
- function units(text) {
3693
- return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
4083
+ async resumeRound(channelId, messageId, how) {
4084
+ await this.send({ kind: "resumeRound", channel: channelId, message: messageId, how });
3694
4085
  }
3695
- function pairsOf(text) {
3696
- const words = units(text);
3697
- return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
4086
+ async setLimits(limits) {
4087
+ await this.send({ kind: "setLimits", limits });
3698
4088
  }
3699
- function alike(a, b) {
3700
- if (a.length === 0 || b.length === 0) {
3701
- return 0;
3702
- }
3703
- const left = new Map;
3704
- for (const pair of a) {
3705
- left.set(pair, (left.get(pair) ?? 0) + 1);
3706
- }
3707
- let common = 0;
3708
- for (const pair of b) {
3709
- const n = left.get(pair) ?? 0;
3710
- if (n > 0) {
3711
- left.set(pair, n - 1);
3712
- common++;
4089
+ async watch(channelId) {
4090
+ await this.send({ kind: "watch", channel: channelId });
4091
+ }
4092
+ async changed(keys) {
4093
+ const reads = [];
4094
+ for (const key of keys) {
4095
+ if (key === Keys.TEAM || key === Keys.WORKING || key === Keys.ANSWERED) {
4096
+ reads.push(this.load(true));
4097
+ } else if (key.startsWith(Keys.MESSAGES)) {
4098
+ const channelId = key.slice(Keys.MESSAGES.length);
4099
+ if (this.current.messages[channelId]) {
4100
+ reads.push(this.messages(channelId, true));
4101
+ }
4102
+ } else if (key === Keys.FOCUS) {
4103
+ reads.push(this.storage.get(Keys.FOCUS).then(async (focus) => {
4104
+ if (focus) {
4105
+ await this.load(true);
4106
+ for (const listener of this.focusListeners) {
4107
+ listener(focus.channelId);
4108
+ }
4109
+ }
4110
+ }));
3713
4111
  }
3714
4112
  }
3715
- return 2 * common / (a.length + b.length);
4113
+ await Promise.all(reads).catch((error) => console.error(error));
4114
+ }
4115
+ update(change) {
4116
+ this.current = { ...this.current, ...change };
4117
+ for (const listener of this.listeners) {
4118
+ listener(this.current);
4119
+ }
3716
4120
  }
3717
- })(ChannelRounds ||= {});
3718
-
3719
- // web-src/limit-settings.tsx
3720
- function amount(pi, tokens) {
3721
- return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
3722
4121
  }
3723
- function useLimits(pi) {
3724
- const read = React.useCallback(async () => ({
3725
- limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
3726
- ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
3727
- }), [pi]);
3728
- const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
4122
+
4123
+ // web-src/shared-group.tsx
4124
+ function useFriends(pi) {
4125
+ const [friends, setFriends] = React.useState([]);
3729
4126
  React.useEffect(() => {
3730
4127
  let live = true;
3731
- const load = () => void read().then((next) => live && setValue(next), () => {
4128
+ pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
3732
4129
  return;
3733
4130
  });
3734
- load();
3735
- const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
3736
4131
  return () => {
3737
4132
  live = false;
3738
- stop();
3739
4133
  };
3740
- }, [pi, read]);
3741
- return value;
4134
+ }, [pi]);
4135
+ return friends;
3742
4136
  }
3743
- function limitSettings(pi, service) {
3744
- const words = () => ChannelWords.of(pi.ui.language);
3745
- const row = (key) => function Choices() {
3746
- const { limits } = useLimits(pi);
3747
- const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
3748
- return /* @__PURE__ */ React.createElement("fieldset", {
3749
- className: "ta-segmented",
3750
- "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
3751
- }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
3752
- key: value,
3753
- type: "button",
3754
- "aria-pressed": limits[key] === value,
3755
- className: limits[key] === value ? "ta-on" : "",
3756
- onClick: () => pick(value)
3757
- }, amount(pi, value))));
3758
- };
3759
- function Spent() {
3760
- const { spent } = useLimits(pi);
3761
- return /* @__PURE__ */ React.createElement("span", {
3762
- className: "tac-limit-spent"
3763
- }, spent > 0 ? amount(pi, spent) : "0");
4137
+ async function createShared(context, title, friends, agents) {
4138
+ const { pi } = context;
4139
+ const rooms = pi.rooms;
4140
+ if (!rooms) {
4141
+ throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
3764
4142
  }
3765
- return {
3766
- title: () => words().limitsTitle,
3767
- icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
3768
- group: "ta",
3769
- rows: [
3770
- { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
3771
- { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
3772
- { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
3773
- { key: "spent", label: () => words().limitSpent, render: Spent }
3774
- ]
3775
- };
4143
+ const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
4144
+ await rooms.inviteFriends(room.id, friends);
4145
+ for (const agent of agents) {
4146
+ await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
4147
+ pi.ui.notify(ChannelViews.message(error), "error");
4148
+ });
4149
+ }
4150
+ const { link } = await rooms.invite(room.id);
4151
+ await pi.openLink?.(link);
4152
+ return room.id;
4153
+ }
4154
+ var ROOMS_PACKAGE = "@celljs/ta-rooms";
4155
+ var ROOMS_KIND = "ta-rooms";
4156
+ async function becomeGroup(context, channel, friends, agents) {
4157
+ const { pi } = context;
4158
+ const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
4159
+ const room = await createShared(context, channel.name, friends, members);
4160
+ await context.service.updateChannel(channel.id, { shared: room });
4161
+ pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
3776
4162
  }
3777
4163
 
3778
- // ../ta-protocol/esm/common/said-protocol.js
3779
- var TaSaid;
3780
- (function(TaSaid2) {
3781
- const CARD = /^ta-/i;
3782
- const READ = 4000;
3783
- const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)/;
3784
- const TAG_LINE = /^<\/?[A-Za-z][\w:.-]*(?:\s[^<>]*)?\/?>$/;
3785
- const MARKS_ONLY = /^[-*_=|:+\s]+$/;
3786
- const MARKS = [
3787
- ["context", /<\/?context>/],
3788
- ["source", /\[ta:(?:from|notice|by) /],
3789
- ["image note", /\[Image: original \d+x\d+|\[Image converted from /],
3790
- ["skill", /<skill name="|<\/skill>/],
3791
- ["task note", /<\/?task_(?:update|adopted|renamed)\b/],
3792
- ["summary", /<\/?(?:conversation_history_summary|summary)>/]
3793
- ];
3794
- function text(content, joiner = `
3795
- `) {
3796
- if (typeof content === "string") {
3797
- return content;
3798
- }
3799
- return Array.isArray(content) ? content.filter((part) => (part === null || part === undefined ? undefined : part.type) === "text" && typeof part.text === "string").map((part) => part.text).join(joiner) : "";
3800
- }
3801
- TaSaid2.text = text;
3802
- function words(role, text2, options = {}) {
3803
- const said = role === "user" ? userWords(text2) : TaAgentSummary.strip(text2);
3804
- return withoutFences(said, (language) => options.cards === false && CARD.test(language), true).trim();
3805
- }
3806
- TaSaid2.words = words;
3807
- function of(message, options) {
3808
- return message ? words(message.role, text(message.content), options) : "";
3809
- }
3810
- TaSaid2.of = of;
3811
- function notice(message) {
3812
- return (message === null || message === undefined ? undefined : message.role) === "user" && TaMessageSource.isNotice(text(message.content));
3813
- }
3814
- TaSaid2.notice = notice;
3815
- function marksOnly(role, text2) {
3816
- return !!text2.trim() && !line(words(role, text2), { chars: Number.POSITIVE_INFINITY });
4164
+ // web-src/create.tsx
4165
+ var noBack = (_open, _close) => false;
4166
+ var AGENT_PAGE = `${NAME}/agent`;
4167
+ function newAgent(context) {
4168
+ const { pi, service, ui } = context;
4169
+ if (!ui.state.draft) {
4170
+ const team = service.state.team;
4171
+ const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
4172
+ ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
3817
4173
  }
3818
- TaSaid2.marksOnly = marksOnly;
3819
- function line(markdown, options) {
3820
- var _a;
3821
- const read = markdown.slice(0, READ);
3822
- const prose = withoutFences(read, () => true, true).trim();
3823
- const lines = plain(prose || codeOf(read)).split(`
3824
- `).map((part) => part.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)/, "").replace(/\*{1,3}|`+|~~|(?<![\p{L}\p{N}])_{1,3}|_{1,3}(?![\p{L}\p{N}])/gu, "").replace(/\s+/g, " ").trim()).filter((part) => part && !MARKS_ONLY.test(part) && !TAG_LINE.test(part));
3825
- const count = (_a = options.lines) !== null && _a !== undefined ? _a : 1;
3826
- const joined = count <= 1 ? lines.join(" ") : lines.slice(0, count).join(`
3827
- `);
3828
- return joined.length > options.chars ? `${joined.slice(0, Math.max(0, options.chars - 1)).trimEnd()}…` : joined;
4174
+ pi.ui.showView(AGENT_PAGE);
4175
+ }
4176
+ function Identity({ context, onClose }) {
4177
+ const { pi, ui } = context;
4178
+ const { draft } = useUi(ui);
4179
+ const w = ChannelViews.words(pi);
4180
+ const ref = React.useRef(null);
4181
+ const name = React.useRef(null);
4182
+ React.useEffect(() => name.current?.select(), []);
4183
+ (pi.ui.useBackLayer ?? noBack)(true, onClose);
4184
+ React.useEffect(() => {
4185
+ const close = (event) => {
4186
+ const target = event.target;
4187
+ if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
4188
+ onClose();
4189
+ }
4190
+ };
4191
+ const onKey = (event) => event.key === "Escape" && onClose();
4192
+ document.addEventListener("pointerdown", close);
4193
+ document.addEventListener("keydown", onKey);
4194
+ return () => {
4195
+ document.removeEventListener("pointerdown", close);
4196
+ document.removeEventListener("keydown", onKey);
4197
+ };
4198
+ }, [onClose]);
4199
+ if (!draft) {
4200
+ return null;
3829
4201
  }
3830
- TaSaid2.line = line;
3831
- function leaks(shown, options = {}) {
3832
- const found = MARKS.filter(([, mark]) => mark.test(shown)).map(([name]) => name);
3833
- const lines = shown.split(`
3834
- `);
3835
- if (options.cards !== true && lines.some((part) => {
3836
- var _a;
3837
- var _b;
3838
- return CARD.test((_b = (_a = FENCE.exec(part)) === null || _a === undefined ? undefined : _a[2]) !== null && _b !== undefined ? _b : "");
3839
- })) {
3840
- found.push("card");
3841
- }
3842
- if (lines.some((part) => TAG_LINE.test(part.trim()))) {
3843
- found.push("tag");
3844
- }
3845
- return found;
4202
+ return /* @__PURE__ */ React.createElement("div", {
4203
+ className: "tac-identity",
4204
+ ref,
4205
+ role: "dialog",
4206
+ "aria-label": w.editAgent
4207
+ }, /* @__PURE__ */ React.createElement("label", {
4208
+ className: "tac-identity-label"
4209
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
4210
+ className: "tac-input",
4211
+ value: draft.name,
4212
+ maxLength: 40,
4213
+ ref: name,
4214
+ onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
4215
+ onKeyDown: (event) => event.key === "Enter" && onClose()
4216
+ })), /* @__PURE__ */ React.createElement("div", {
4217
+ className: "tac-identity-label"
4218
+ }, w.avatar), /* @__PURE__ */ React.createElement("div", {
4219
+ className: "tac-faces"
4220
+ }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
4221
+ key: face,
4222
+ type: "button",
4223
+ "aria-pressed": draft.face === face,
4224
+ className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
4225
+ onClick: () => ui.set({ draft: { ...draft, face } })
4226
+ }, /* @__PURE__ */ React.createElement(Face, {
4227
+ face,
4228
+ size: 30
4229
+ })))));
4230
+ }
4231
+ function NewAgentHead({ context }) {
4232
+ const { pi, ui } = context;
4233
+ const { draft, editing } = useUi(ui);
4234
+ const w = ChannelViews.words(pi);
4235
+ const Down = ChannelViews.icon(pi, "ChevronDown");
4236
+ if (!draft) {
4237
+ return null;
3846
4238
  }
3847
- TaSaid2.leaks = leaks;
3848
- const SUMMARY = `<conversation_history_summary>
3849
- <summary>
3850
- 1. Primary Request and Intent:
3851
- The user works on the relay.
3852
- </summary>
3853
- </conversation_history_summary>`;
3854
- TaSaid2.SAMPLES = [
3855
- {
3856
- mark: "context and where it came from",
3857
- role: "user",
3858
- text: `<context>
3859
- The channel #ops, its members.
3860
- [ta:from @celljs/ta-channels #ops]
3861
- </context>
3862
- Check the build`,
3863
- said: "Check the build"
3864
- },
3865
- {
3866
- mark: "a notice, not the user",
3867
- role: "user",
3868
- text: `<context>
3869
- [ta:notice @celljs/ta-call]
3870
- </context>
3871
- The work finished. Its last words: tests pass.`,
3872
- said: "The work finished. Its last words: tests pass."
3873
- },
3874
- { mark: "one let in", role: "user", text: `<context>
3875
- [ta:by p-7 Alice]
3876
- </context>
3877
- Hello there`, said: "Hello there" },
3878
- {
3879
- mark: "notes of images",
3880
- role: "user",
3881
- text: `Look at this
3882
- [Image: original 3024x4032, displayed at 1512x2016. Multiply coordinates by 2.00 to map to original image.]
3883
- [Image converted from image/heic to image/png.]`,
3884
- said: "Look at this"
3885
- },
3886
- {
3887
- mark: "a skill run",
3888
- role: "user",
3889
- text: `<skill name="ta-package" location="/skills/ta-package/SKILL.md">
3890
- # Ta package
3891
- Steps.
3892
- </skill>
3893
-
3894
- Make a card`,
3895
- said: "Make a card"
3896
- },
3897
- {
3898
- mark: "a note of a task",
3899
- role: "user",
3900
- text: `<task_update id="t1" title="Fix login" status="done">
3901
- All tests pass.
3902
- </task_update>`,
3903
- said: "Fix login"
3904
- },
3905
- { mark: "a note of a new id", role: "user", text: `<task_renamed id="t2" was="t1" title="Fix login">
3906
- Now t2.
3907
- </task_renamed>` },
3908
- { mark: "a summary, then the answer", role: "assistant", text: `${SUMMARY}
3909
- Switched to voice.`, said: "Switched to voice." },
3910
- { mark: "a summary alone", role: "assistant", text: SUMMARY },
3911
- { mark: "a summary as it streams", role: "assistant", text: `<conversation_history_summary>
3912
- <summary>` },
3913
- {
3914
- mark: "a card after the answer",
3915
- role: "assistant",
3916
- text: '**Done**: tests pass.\n\n```ta-glance\n{"status":"done","blocks":[]}\n```',
3917
- said: "tests pass"
3918
- },
3919
- { mark: "a card alone", role: "assistant", text: '```ta-glance\n{"status":"done","blocks":[]}\n```' },
3920
- { mark: "a proposal", role: "assistant", text: 'Committed.\n\n```ta-propose\n{"kind":"git.push","title":"Push"}\n```', said: "Committed." },
3921
- { mark: "what a call says aloud", role: "assistant", text: "All fixed.\n\n```ta-say\nIt is fixed.\n```", said: "All fixed." },
3922
- { mark: "a tag not known yet", role: "assistant", text: `<system-reminder>
3923
- </system-reminder>
3924
- Ready.`, said: "Ready." }
3925
- ];
3926
- function userWords(text2) {
3927
- const said = TaImageNote.strip(TaMessageContext.strip(text2));
3928
- const skill = TaSkillUse.parse(said);
3929
- if (skill) {
3930
- return TaSkillUse.command(skill);
4239
+ return /* @__PURE__ */ React.createElement("div", {
4240
+ className: "tac-new-head"
4241
+ }, /* @__PURE__ */ React.createElement("div", {
4242
+ className: "tac-new-title"
4243
+ }, /* @__PURE__ */ React.createElement("button", {
4244
+ type: "button",
4245
+ className: "tac-new-trigger tac-identity-open",
4246
+ "aria-expanded": editing,
4247
+ title: w.editAgent,
4248
+ onClick: () => ui.set({ editing: !editing })
4249
+ }, /* @__PURE__ */ React.createElement(Face, {
4250
+ face: draft.face,
4251
+ size: 20
4252
+ }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
4253
+ size: 14
4254
+ })), editing && /* @__PURE__ */ React.createElement(Identity, {
4255
+ context,
4256
+ onClose: () => ui.set({ editing: false })
4257
+ })), /* @__PURE__ */ React.createElement("button", {
4258
+ type: "button",
4259
+ className: "tac-button tac-quiet",
4260
+ onClick: () => {
4261
+ ui.set({ draft: undefined, editing: false });
4262
+ pi.ui.showView("");
3931
4263
  }
3932
- const note = TaTaskNote.parse(said);
3933
- if (!note) {
3934
- return said;
4264
+ }, w.cancel));
4265
+ }
4266
+ function NewAgentPage({ context }) {
4267
+ const { pi, service, ui } = context;
4268
+ const { draft } = useUi(ui);
4269
+ const { loaded } = useChannels(service);
4270
+ const w = ChannelViews.words(pi);
4271
+ const Pencil = ChannelViews.icon(pi, "Pencil");
4272
+ const Composer = pi.ui.Composer;
4273
+ const first = React.useRef(true);
4274
+ React.useEffect(() => {
4275
+ if (!loaded || !first.current) {
4276
+ return;
3935
4277
  }
3936
- if (note.kind === "renamed") {
3937
- return "";
4278
+ first.current = false;
4279
+ if (!ui.state.draft) {
4280
+ newAgent(context);
3938
4281
  }
3939
- return note.kind === "update" && note.body.trim() ? `${note.title} · ${note.body}` : note.title;
4282
+ }, [loaded, ui, context]);
4283
+ if (!draft) {
4284
+ return null;
3940
4285
  }
3941
- function withoutFences(text2, drop, tags = false) {
3942
- const kept = [];
3943
- let fence;
3944
- let left = false;
3945
- for (const part of text2.split(`
3946
- `)) {
3947
- const open = FENCE.exec(part);
3948
- if (!fence && open) {
3949
- fence = { mark: open[1], dropped: drop(open[2]) };
3950
- } else if (fence && closes(part, fence.mark)) {
3951
- const dropped = fence.dropped;
3952
- fence = undefined;
3953
- if (dropped) {
3954
- continue;
3955
- }
3956
- }
3957
- if ((fence === null || fence === undefined ? undefined : fence.dropped) || !fence && tags && TAG_LINE.test(part.trim())) {
3958
- left = true;
3959
- } else {
3960
- kept.push(part);
3961
- }
4286
+ const send = async (text) => {
4287
+ const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
4288
+ ui.set({ draft: undefined, editing: false });
4289
+ try {
4290
+ const sessionId = await service.openAgent(agent.id);
4291
+ context.sessions.set(agent.id, sessionId);
4292
+ await pi.switchSession(sessionId);
4293
+ await pi.sendUserMessage(text);
4294
+ } catch (error) {
4295
+ pi.ui.notify(ChannelViews.message(error), "error");
3962
4296
  }
3963
- return left ? kept.join(`
3964
- `).replace(/\n{3,}/g, `
3965
-
3966
- `) : kept.join(`
3967
- `);
3968
- }
3969
- function codeOf(text2) {
3970
- const code = [];
3971
- let fence;
3972
- for (const part of text2.split(`
3973
- `)) {
3974
- const open = FENCE.exec(part);
3975
- if (!fence && open) {
3976
- fence = { mark: open[1], card: CARD.test(open[2]) };
3977
- } else if (fence && closes(part, fence.mark)) {
3978
- fence = undefined;
3979
- } else if (fence && !fence.card) {
3980
- code.push(part);
3981
- }
4297
+ };
4298
+ return /* @__PURE__ */ React.createElement("div", {
4299
+ className: "tac-new-page"
4300
+ }, /* @__PURE__ */ React.createElement("div", {
4301
+ className: "tac-new-col"
4302
+ }, /* @__PURE__ */ React.createElement(Face, {
4303
+ face: draft.face,
4304
+ size: 88
4305
+ }), /* @__PURE__ */ React.createElement("h2", {
4306
+ className: "tac-new-name"
4307
+ }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
4308
+ type: "button",
4309
+ className: "tac-action tac-identity-open",
4310
+ title: w.editAgent,
4311
+ "aria-label": w.editAgent,
4312
+ onClick: () => ui.set({ editing: !ui.state.editing })
4313
+ }, /* @__PURE__ */ React.createElement(Pencil, {
4314
+ size: 14
4315
+ }))), /* @__PURE__ */ React.createElement("p", {
4316
+ className: "tac-new-hint"
4317
+ }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
4318
+ className: "tac-new-box"
4319
+ }, /* @__PURE__ */ React.createElement(Composer, {
4320
+ placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
4321
+ onSend: send,
4322
+ cwd: draft.cwd,
4323
+ onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
4324
+ draft: "new-agent"
4325
+ }))));
4326
+ }
4327
+ function NewChannelDialog({ context, onClose }) {
4328
+ const { pi, service } = context;
4329
+ const { team } = useChannels(service);
4330
+ const faces = useFaces(team);
4331
+ const w = ChannelViews.words(pi);
4332
+ const Search = ChannelViews.icon(pi, "Search");
4333
+ const Check = ChannelViews.icon(pi, "Check");
4334
+ const [name, setName] = React.useState("");
4335
+ const [query, setQuery] = React.useState("");
4336
+ const [picked, setPicked] = React.useState([]);
4337
+ const friends = useFriends(pi);
4338
+ const [pickedFriends, setPickedFriends] = React.useState([]);
4339
+ const shared = pickedFriends.length > 0;
4340
+ const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
4341
+ const [busy, setBusy] = React.useState(false);
4342
+ const [error, setError] = React.useState();
4343
+ const Dialog = pi.ui.Dialog;
4344
+ const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
4345
+ const full = picked.length >= MAX_MEMBERS;
4346
+ const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
4347
+ const create = (event) => {
4348
+ event.preventDefault();
4349
+ setBusy(true);
4350
+ setError(undefined);
4351
+ if (shared) {
4352
+ createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
4353
+ setBusy(false);
4354
+ setError(ChannelViews.message(failure));
4355
+ });
4356
+ return;
3982
4357
  }
3983
- return code.join(`
3984
- `);
3985
- }
3986
- function closes(part, mark) {
3987
- var _a;
3988
- const close = (_a = /^\s*(`{3,}|~{3,})\s*$/.exec(part)) === null || _a === undefined ? undefined : _a[1];
3989
- return !!close && close[0] === mark[0] && close.length >= mark.length;
3990
- }
3991
- function plain(text2) {
3992
- const linked = text2.replace(/(?<!!)\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
3993
- const words2 = linked.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").trim();
3994
- return words2 || linked.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
3995
- }
3996
- })(TaSaid || (TaSaid = {}));
4358
+ service.createChannel({ name, members: picked }).then((channel) => {
4359
+ onClose();
4360
+ context.showChannel(channel.id);
4361
+ }, (failure) => {
4362
+ setBusy(false);
4363
+ setError(ChannelViews.message(failure));
4364
+ });
4365
+ };
4366
+ return /* @__PURE__ */ React.createElement(Dialog, {
4367
+ title: w.newChannel,
4368
+ onClose
4369
+ }, /* @__PURE__ */ React.createElement("form", {
4370
+ className: "tac-dialog",
4371
+ onSubmit: create
4372
+ }, /* @__PURE__ */ React.createElement("label", {
4373
+ className: "tac-dialog-label"
4374
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
4375
+ className: "tac-input tac-dialog-input",
4376
+ value: name,
4377
+ placeholder: w.channelNamePlaceholder,
4378
+ maxLength: 40,
4379
+ autoFocus: true,
4380
+ onChange: (event) => setName(event.target.value)
4381
+ })), /* @__PURE__ */ React.createElement("div", {
4382
+ className: "tac-dialog-label"
4383
+ }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
4384
+ className: "tac-dialog-count"
4385
+ }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
4386
+ className: "tac-dialog-search"
4387
+ }, /* @__PURE__ */ React.createElement(Search, {
4388
+ size: 15
4389
+ }), /* @__PURE__ */ React.createElement("input", {
4390
+ value: query,
4391
+ placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
4392
+ "aria-label": w.search,
4393
+ onChange: (event) => setQuery(event.target.value)
4394
+ })), /* @__PURE__ */ React.createElement("div", {
4395
+ className: "tac-pick-list"
4396
+ }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4397
+ compact: true,
4398
+ title: w.noAgents,
4399
+ hint: w.noAgentsHint
4400
+ }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4401
+ compact: true,
4402
+ title: w.noMatch
4403
+ }), shown.map((agent) => {
4404
+ const on = picked.includes(agent.id);
4405
+ return /* @__PURE__ */ React.createElement("button", {
4406
+ key: agent.id,
4407
+ type: "button",
4408
+ "aria-pressed": on,
4409
+ disabled: !on && full,
4410
+ className: `tac-pick${on ? " tac-on" : ""}`,
4411
+ onClick: () => toggle(agent)
4412
+ }, /* @__PURE__ */ React.createElement("span", {
4413
+ className: "tac-check"
4414
+ }, on && /* @__PURE__ */ React.createElement(Check, {
4415
+ size: 13,
4416
+ strokeWidth: 3
4417
+ })), /* @__PURE__ */ React.createElement(AgentAvatar, {
4418
+ agent,
4419
+ faces,
4420
+ size: 30
4421
+ }), /* @__PURE__ */ React.createElement("span", {
4422
+ className: "tac-pick-text"
4423
+ }, /* @__PURE__ */ React.createElement("span", {
4424
+ className: "tac-pick-name"
4425
+ }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
4426
+ className: "tac-msg-lead"
4427
+ }, w.lead)), /* @__PURE__ */ React.createElement("span", {
4428
+ className: "tac-pick-role"
4429
+ }, agent.role.split(`
4430
+ `)[0])));
4431
+ })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
4432
+ className: "tac-dialog-label"
4433
+ }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
4434
+ className: "tac-dialog-count"
4435
+ }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
4436
+ className: "tac-pick-list"
4437
+ }, friends.map((friend) => {
4438
+ const on = pickedFriends.includes(friend.id);
4439
+ return /* @__PURE__ */ React.createElement("button", {
4440
+ key: friend.id,
4441
+ type: "button",
4442
+ "aria-pressed": on,
4443
+ className: `tac-pick${on ? " tac-on" : ""}`,
4444
+ onClick: () => toggleFriend(friend)
4445
+ }, /* @__PURE__ */ React.createElement("span", {
4446
+ className: "tac-check"
4447
+ }, on && /* @__PURE__ */ React.createElement(Check, {
4448
+ size: 13,
4449
+ strokeWidth: 3
4450
+ })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
4451
+ seed: friend.id,
4452
+ size: 30,
4453
+ look: friend.look
4454
+ }) : /* @__PURE__ */ React.createElement("span", {
4455
+ className: "tac-pick-face"
4456
+ }), /* @__PURE__ */ React.createElement("span", {
4457
+ className: "tac-pick-text"
4458
+ }, /* @__PURE__ */ React.createElement("span", {
4459
+ className: "tac-pick-name"
4460
+ }, friend.name), /* @__PURE__ */ React.createElement("span", {
4461
+ className: "tac-pick-role"
4462
+ }, w.friend)));
4463
+ }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
4464
+ className: "tac-dialog-note"
4465
+ }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
4466
+ className: "tac-empty tac-error"
4467
+ }, error), /* @__PURE__ */ React.createElement("div", {
4468
+ className: "tac-dialog-actions"
4469
+ }, /* @__PURE__ */ React.createElement("button", {
4470
+ type: "submit",
4471
+ className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4472
+ disabled: busy || !name.trim() || picked.length === 0 && !shared
4473
+ }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
4474
+ className: "ta-spinner ta-busy-mark ta-on-brand"
4475
+ })))));
4476
+ }
3997
4477
 
3998
- // web-src/channels-text.ts
3999
- var ChannelsText;
4000
- ((ChannelsText) => {
4001
- function markMentions(text, agents) {
4002
- if (agents.length === 0) {
4003
- return text;
4004
- }
4005
- const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
4006
- const pattern = new RegExp(`(?<![*A-Za-z0-9_])@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
4007
- return text.split(/(```[\s\S]*?(?:```|$)|`[^`\n]*`)/).map((part, index) => index % 2 === 1 ? part : part.replace(pattern, "**$&**")).join("");
4008
- }
4009
- ChannelsText.markMentions = markMentions;
4010
- function mentions(text, agents) {
4011
- if (agents.length === 0) {
4012
- return [];
4013
- }
4014
- const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
4015
- const pattern = new RegExp(`@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
4016
- const found = [];
4017
- for (const match of text.matchAll(pattern)) {
4018
- const agent = agents.find((candidate) => candidate.name.toLowerCase() === match[1].toLowerCase());
4019
- if (agent && !found.includes(agent.id)) {
4020
- found.push(agent.id);
4021
- }
4022
- }
4023
- return found;
4024
- }
4025
- ChannelsText.mentions = mentions;
4026
- function targets(team, channel, message) {
4027
- const muted = channel.muted ?? [];
4028
- const members = channel.members.filter((id) => !muted.includes(id)).map((id) => team.agents.find((agent) => agent.id === id)).filter((agent) => !!agent);
4029
- const named = mentions(message.text, members).filter((id) => id !== message.author);
4030
- if (message.author === SYSTEM) {
4031
- return [];
4032
- }
4033
- if (named.length > 0 || message.author !== TA) {
4034
- return named;
4035
- }
4036
- return members.length > 0 ? [members[0].id] : [];
4037
- }
4038
- ChannelsText.targets = targets;
4039
- function authorName(team, author, labels) {
4040
- if (author === SYSTEM) {
4041
- return "channel";
4042
- }
4043
- if (author === USER) {
4044
- return labels.user;
4045
- }
4046
- if (author === TA) {
4047
- return labels.ta;
4478
+ // web-src/handoff.ts
4479
+ var HandOff;
4480
+ ((HandOff) => {
4481
+ HandOff.TOOL = "hand_off";
4482
+ HandOff.CARD = "ta-channels-handoff";
4483
+ HandOff.BLOCK = "ta-handoff";
4484
+ const MARK = /\[ta-handoff:([^\]\s]+)\]/;
4485
+ HandOff.DEFINITION = {
4486
+ name: HandOff.TOOL,
4487
+ label: "Hand off",
4488
+ description: "Hands the work of this conversation over to one of the user's agents (@name) or channels (#name), when the user says so (hand it to, give it to, 交给, 转给). The other side does not see this conversation: write the brief it needs to go on, in the user's language: the goal, what is done and decided, what is left or blocks, the files, branches, commands and links that matter. It works on it in its own conversation, which the user follows; you stop working on it here. list_channels lists the team. After the call, say in one line to whom it went.",
4489
+ promptSnippet: "Hand the work over to one of the user's agents or channels",
4490
+ parameters: {
4491
+ type: "object",
4492
+ properties: {
4493
+ to: { type: "string", description: "@name of an agent or #name of a channel." },
4494
+ brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
4495
+ },
4496
+ required: ["to", "brief"]
4048
4497
  }
4049
- return team.agents.find((agent) => agent.id === author)?.name ?? author;
4498
+ };
4499
+ function ref(target) {
4500
+ return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
4050
4501
  }
4051
- ChannelsText.authorName = authorName;
4052
- function systemPrompt(agent) {
4053
- return [
4054
- `You are ${agent.name}, ${AGENT_MARK}. Your role: ${agent.role}`,
4055
- "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.",
4056
- "Do the part of the work your role covers with your tools, then answer: your answer is posted to the channel as it is.",
4057
- "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.",
4058
- "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.",
4059
- NOTICE_RULE
4502
+ HandOff.ref = ref;
4503
+ function ask(language, to) {
4504
+ const fence = "```";
4505
+ const context = [
4506
+ `[ta-handoff:${to}]`,
4507
+ `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
4508
+ `- Write the brief it needs to go on: the goal, what is done and decided, what is left or blocks, the files, branches, commands and links that matter, in the user's language. Leave out what was only tried and dropped.`,
4509
+ `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
4510
+ `- Without it, say in one line what you hand over, then end your answer with the brief in a fenced block of the language ${HandOff.BLOCK}, which Ta reads to hand it over (a longer fence when the brief has one of its own):`,
4511
+ `${fence}${HandOff.BLOCK}`,
4512
+ "<the brief>",
4513
+ fence,
4514
+ `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
4060
4515
  ].join(`
4061
4516
  `);
4517
+ const line = TaLanguageUtil.pick(language, {
4518
+ "zh-CN": `把这件事交给 ${to}`,
4519
+ "zh-TW": `把這件事交給 ${to}`,
4520
+ "en-US": `Hand this over to ${to}`,
4521
+ "ja-JP": `これを ${to} に引き継ぐ`
4522
+ });
4523
+ return TaMessageContext.wrap(context, line);
4062
4524
  }
4063
- ChannelsText.systemPrompt = systemPrompt;
4064
- function prompt(team, channel, history, message, agent, options = {}) {
4065
- const labels = { user: "user", ta: "Ta" };
4066
- 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)}`);
4067
- const before = history.filter((item) => item.id !== message.id && !item.failed && !item.notice).slice(-CONTEXT_MESSAGES);
4068
- const lines = [`[#${channel.name}]${channel.topic ? ` ${channel.topic}` : ""}`, "Members:", ...members.map((line) => `- ${line}`)];
4069
- if (channel.notice) {
4070
- lines.push("", "Notice of the channel (follow it; keep it with update_channel_notice):", channel.notice.text);
4071
- }
4072
- if (before.length > 0) {
4073
- lines.push("", "Recent messages:", ...before.map((item) => `${authorName(team, item.author, labels)}: ${item.text}`));
4074
- }
4075
- if (options.closing) {
4076
- lines.push("", CLOSING_NOTE);
4077
- }
4078
- lines.push("", `${authorName(team, message.author, labels)} to you:`);
4079
- const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels)}`;
4080
- lines.push(TaMessageSource.line(NAME, `#${channel.name}${speaker}`));
4081
- return TaMessageContext.wrap(lines.join(`
4082
- `), message.text);
4525
+ HandOff.ask = ask;
4526
+ function asked(text) {
4527
+ return MARK.exec(text)?.[1];
4083
4528
  }
4084
- ChannelsText.prompt = prompt;
4085
- function summary(team) {
4086
- if (team.agents.length === 0) {
4087
- return "No agents and no channels yet.";
4529
+ HandOff.asked = asked;
4530
+ function find(text) {
4531
+ const lines = text.split(/\r?\n/);
4532
+ let found;
4533
+ for (let index = 0;index < lines.length; index++) {
4534
+ const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
4535
+ if (open?.[2] !== HandOff.BLOCK) {
4536
+ continue;
4537
+ }
4538
+ const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
4539
+ const end = lines.findIndex((line, at) => at > index && close.test(line));
4540
+ found = lines.slice(index + 1, end < 0 ? lines.length : end);
4541
+ index = end < 0 ? lines.length : end;
4088
4542
  }
4089
- const name = (id) => team.agents.find((agent) => agent.id === id)?.name ?? id;
4090
- const agents = team.agents.map((agent) => `- @${agent.name}: ${firstLine(agent.role)}`);
4091
- const channels = team.channels.map((channel) => `- #${channel.name}${channel.topic ? ` (${channel.topic})` : ""}: ${channel.members.map((id) => `@${name(id)}`).join(", ")}${channel.muted?.length ? `; muted by the user, answering nothing: ${channel.muted.map((id) => `@${name(id)}`).join(", ")}` : ""}${channel.notice ? `
4092
- notice: ${channel.notice.text.replace(/\s+/g, " ").slice(0, 300)}` : ""}`);
4093
- return ["Agents:", ...agents, "", "Channels:", ...channels.length > 0 ? channels : ["none yet"]].join(`
4094
- `);
4543
+ const brief = found?.join(`
4544
+ `).trim();
4545
+ return brief || undefined;
4095
4546
  }
4096
- ChannelsText.summary = summary;
4097
- function transcript(team, messages) {
4098
- const labels = { user: "user", ta: "Ta" };
4099
- return messages.map((item) => `${authorName(team, item.author, labels)}${item.failed ? " (failed)" : ""}: ${item.text}`).join(`
4100
-
4547
+ HandOff.find = find;
4548
+ function message(origin, brief, language) {
4549
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4550
+ const head = TaLanguageUtil.pick(language, {
4551
+ "zh-CN": `(交接自“${title}”)`,
4552
+ "zh-TW": `(交接自「${title}」)`,
4553
+ "en-US": `(Handed over from “${title}”)`,
4554
+ "ja-JP": `(“${title}” から引き継ぎました)`
4555
+ });
4556
+ const context = [
4557
+ "The user handed you this work from another conversation of theirs, which you do not see; the brief below is all it says. Go on from there in this conversation, which the user follows; ask them when the brief leaves out something you need.",
4558
+ origin.sessionFile ? `That conversation is pi's session file ${origin.sessionFile}${origin.cwd ? `, working in ${origin.cwd}` : ""}: read it only when the brief is not enough.` : ""
4559
+ ].filter(Boolean).join(`
4101
4560
  `);
4561
+ return TaMessageContext.wrap(context, `${head}
4562
+
4563
+ ${brief.trim()}`);
4102
4564
  }
4103
- ChannelsText.transcript = transcript;
4104
- function markdown(agent, messages, labels) {
4105
- const parts = [`# ${agent.name}`, "", `> ${firstLine(agent.role)}`];
4106
- for (const message of messages) {
4107
- const { role, content } = message ?? {};
4108
- if (role !== "user" && role !== "assistant") {
4109
- continue;
4110
- }
4111
- const text = TaSaid.words(role, TaSaid.text(content, ""));
4112
- if (text) {
4113
- parts.push("", `## ${role === "user" ? labels.user : agent.name}`, "", text);
4114
- }
4115
- }
4116
- return `${parts.join(`
4117
- `)}
4118
- `;
4565
+ HandOff.message = message;
4566
+ function channelText(origin, brief, language) {
4567
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4568
+ return `${TaLanguageUtil.pick(language, {
4569
+ "zh-CN": `(交接自“${title}”)`,
4570
+ "zh-TW": `(交接自「${title}」)`,
4571
+ "en-US": `(Handed over from “${title}”)`,
4572
+ "ja-JP": `(“${title}” から引き継ぎました)`
4573
+ })}
4574
+
4575
+ ${brief.trim()}`;
4119
4576
  }
4120
- ChannelsText.markdown = markdown;
4121
- function channelMarkdown(team, channel, messages, labels) {
4122
- const parts = [`# #${channel.name}`];
4123
- if (channel.topic) {
4124
- parts.push("", `> ${firstLine(channel.topic)}`);
4125
- }
4126
- for (const message of messages) {
4127
- const text = message.text.trim();
4128
- if (text && message.author !== SYSTEM) {
4129
- parts.push("", `## ${authorName(team, message.author, labels)}${message.failed ? " (failed)" : ""}`, "", text);
4130
- }
4131
- }
4132
- return `${parts.join(`
4133
- `)}
4134
- `;
4577
+ HandOff.channelText = channelText;
4578
+ function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
4579
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
4135
4580
  }
4136
- ChannelsText.channelMarkdown = channelMarkdown;
4137
- function firstLine(text) {
4138
- return text.split(`
4139
- `)[0];
4581
+ HandOff.serverLanguage = serverLanguage;
4582
+ function result(target) {
4583
+ return `Handed over to ${ref(target)}; it works on it in its own conversation, which the user follows. Do not go on with it here.`;
4140
4584
  }
4141
- })(ChannelsText ||= {});
4142
- 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.";
4143
- var NOTICE_RULE = [
4144
- "A channel may have a notice, in the <context> block: what its members decided, agreed and are to do. Follow it.",
4145
- `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.`
4146
- ].join(`
4147
- `);
4585
+ HandOff.result = result;
4586
+ })(HandOff ||= {});
4148
4587
 
4149
- // web-src/more-menu.tsx
4150
- var MARGIN = 8;
4151
- function MoreMenu({ pi, label, items }) {
4152
- const w = ChannelViews.words(pi);
4153
- const [open, setOpen] = React.useState(false);
4154
- const anchor = React.useRef({
4155
- right: 0,
4156
- below: 0,
4157
- above: 0,
4158
- finger: undefined
4159
- });
4160
- const root = React.useRef(null);
4161
- const menu = React.useRef(null);
4162
- const Ellipsis = ChannelViews.icon(pi, "Ellipsis");
4163
- const show = React.useCallback((button, at) => {
4164
- const box = button.getBoundingClientRect();
4165
- const touch = document.documentElement.hasAttribute("data-touch");
4166
- const row = root.current?.parentElement?.getBoundingClientRect() ?? box;
4167
- anchor.current = {
4168
- right: box.right,
4169
- below: at?.y ?? box.bottom,
4170
- above: at?.y ?? box.top,
4171
- finger: touch && at ? { ...at, around: { top: row.top, bottom: row.bottom } } : undefined
4172
- };
4173
- setOpen(true);
4174
- }, []);
4175
- React.useLayoutEffect(() => {
4176
- const element = menu.current;
4177
- if (!open || !element) {
4178
- return;
4179
- }
4180
- const { right, below, above, finger } = anchor.current;
4181
- if (finger) {
4182
- return pi.ui.attachMenu(element, finger, () => setOpen(false));
4183
- }
4184
- const width = element.offsetWidth;
4185
- const height = element.offsetHeight;
4186
- const top = below + 4 + height <= window.innerHeight - MARGIN ? below + 4 : Math.max(MARGIN, above - 4 - height);
4187
- element.style.top = `${top}px`;
4188
- element.style.left = `${Math.max(MARGIN, right - width)}px`;
4189
- }, [open, pi]);
4190
- React.useEffect(() => {
4191
- const row = root.current?.parentElement;
4192
- const button = root.current?.querySelector(".tac-action");
4193
- if (!row || !button) {
4194
- return;
4195
- }
4196
- const onContextMenu = (event) => {
4197
- event.preventDefault();
4198
- show(button, event.clientX || event.clientY ? { x: event.clientX, y: event.clientY } : undefined);
4199
- };
4200
- row.addEventListener("contextmenu", onContextMenu);
4201
- return () => row.removeEventListener("contextmenu", onContextMenu);
4202
- }, [show]);
4203
- React.useEffect(() => {
4204
- if (!open) {
4205
- return;
4588
+ // web-src/handoff-view.tsx
4589
+ var HandOffViewUtil;
4590
+ ((HandOffViewUtil) => {
4591
+ function members(team, target) {
4592
+ if (target.kind === "agent") {
4593
+ const agent = team.agents.find((candidate) => candidate.id === target.id);
4594
+ return agent ? [agent] : [];
4206
4595
  }
4207
- const close = (event) => {
4208
- if (!root.current?.contains(event.target)) {
4209
- setOpen(false);
4210
- }
4211
- };
4212
- const onKey = (event) => {
4213
- if (event.key === "Escape") {
4214
- setOpen(false);
4215
- }
4216
- };
4217
- document.addEventListener("pointerdown", close);
4218
- document.addEventListener("keydown", onKey);
4219
- return () => {
4220
- document.removeEventListener("pointerdown", close);
4221
- document.removeEventListener("keydown", onKey);
4222
- };
4223
- }, [open]);
4596
+ const channel = team.channels.find((candidate) => candidate.id === target.id);
4597
+ return channel ? membersOf(team, channel) : [];
4598
+ }
4599
+ HandOffViewUtil.members = members;
4600
+ })(HandOffViewUtil ||= {});
4601
+ function useTeam(context) {
4602
+ return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
4603
+ }
4604
+ function HandOffCard({ context, message }) {
4605
+ const card = message.details;
4606
+ const team = useTeam(context);
4607
+ const faces = useFaces(team);
4608
+ if (!card?.target) {
4609
+ return null;
4610
+ }
4611
+ const w = ChannelViews.words(context.pi);
4612
+ const members = HandOffViewUtil.members(team, card.target);
4613
+ const open = () => card.target.kind === "agent" ? void ChannelViews.openAgent(context, card.target.id).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error")) : context.showChannel(card.target.id);
4224
4614
  return /* @__PURE__ */ React.createElement("div", {
4225
- className: "tac-item-more",
4226
- ref: root
4227
- }, /* @__PURE__ */ React.createElement("button", {
4228
- type: "button",
4229
- className: `tac-action${open ? " tac-on" : ""}`,
4230
- title: w.more,
4231
- "aria-label": w.more,
4232
- "aria-haspopup": "menu",
4233
- "aria-expanded": open,
4234
- onClick: (event) => {
4235
- event.stopPropagation();
4236
- if (open) {
4237
- setOpen(false);
4238
- } else {
4239
- show(event.currentTarget);
4240
- }
4241
- }
4242
- }, /* @__PURE__ */ React.createElement(Ellipsis, {
4243
- size: 15
4244
- })), open && /* @__PURE__ */ React.createElement("div", {
4245
- ref: menu,
4246
- className: "tac-menu tac-agent-menu",
4247
- role: "menu",
4248
- "aria-label": label
4249
- }, items().filter((section) => section.length > 0).map((section, index) => /* @__PURE__ */ React.createElement(React.Fragment, {
4250
- key: section[0]?.key ?? index
4251
- }, index > 0 && /* @__PURE__ */ React.createElement("hr", {
4252
- className: "tac-menu-line"
4253
- }), section.map((item) => /* @__PURE__ */ React.createElement("button", {
4254
- key: item.key,
4615
+ className: "tac-handoff"
4616
+ }, /* @__PURE__ */ React.createElement("div", {
4617
+ className: "tac-handoff-head"
4618
+ }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
4619
+ members,
4620
+ faces,
4621
+ size: 20,
4622
+ working: []
4623
+ }), /* @__PURE__ */ React.createElement("span", {
4624
+ className: "tac-handoff-title"
4625
+ }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
4255
4626
  type: "button",
4256
- role: "menuitem",
4257
- className: item.danger ? "tac-danger" : undefined,
4258
- disabled: item.disabled,
4259
- onClick: () => {
4260
- setOpen(false);
4261
- item.run();
4262
- }
4263
- }, item.icon, /* @__PURE__ */ React.createElement("span", {
4264
- className: "tac-menu-label"
4265
- }, item.label)))))));
4627
+ className: "tac-link",
4628
+ onClick: open
4629
+ }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
4630
+ className: "tac-handoff-brief"
4631
+ }, card.brief));
4266
4632
  }
4267
-
4268
- // web-src/agent-menu.tsx
4269
- async function copy(text) {
4270
- try {
4271
- await navigator.clipboard.writeText(text);
4272
- return true;
4273
- } catch {
4274
- return false;
4633
+ var HandOffView;
4634
+ ((HandOffView) => {
4635
+ function card(context) {
4636
+ return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
4637
+ context,
4638
+ message
4639
+ });
4275
4640
  }
4276
- }
4277
- function download(name, text) {
4278
- const url = URL.createObjectURL(new Blob([text], { type: "text/markdown;charset=utf-8" }));
4279
- const link = document.createElement("a");
4280
- link.href = url;
4281
- link.download = name;
4282
- link.click();
4283
- setTimeout(() => URL.revokeObjectURL(url), 1000);
4284
- }
4285
- async function deleteAgent(context, agent) {
4286
- const w = ChannelViews.words(context.pi);
4287
- const sure = await context.pi.ui.confirm(ChannelWords.format(w.confirmDeleteAgent, { name: agent.name }), undefined, {
4288
- confirmLabel: w.delete,
4289
- danger: true
4290
- });
4291
- if (sure) {
4292
- await context.service.deleteAgent(agent.id);
4293
- context.sessions.delete(agent.id);
4641
+ HandOffView.card = card;
4642
+ function icon(context, target, icons) {
4643
+ const key = `${target.kind}:${target.id}`;
4644
+ let node2 = icons.get(key);
4645
+ if (!node2) {
4646
+ const Face2 = () => {
4647
+ const team = useTeam(context);
4648
+ const faces = useFaces(team);
4649
+ const members = HandOffViewUtil.members(team, target);
4650
+ return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
4651
+ members,
4652
+ faces,
4653
+ size: 16,
4654
+ working: []
4655
+ }) : null;
4656
+ };
4657
+ node2 = /* @__PURE__ */ React.createElement(Face2, null);
4658
+ icons.set(key, node2);
4659
+ }
4660
+ return node2;
4661
+ }
4662
+ function composerAddon(context) {
4663
+ const icons = new Map;
4664
+ const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
4665
+ clientMessageId: ChannelsUtil.newId("handoff-ask"),
4666
+ message: HandOff.ask(context.pi.ui.language, to),
4667
+ streamingBehavior: "followUp"
4668
+ }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
4669
+ return {
4670
+ actions: (conversation) => {
4671
+ const { team } = context.service.state;
4672
+ if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
4673
+ return [];
4674
+ }
4675
+ const w = ChannelViews.words(context.pi);
4676
+ const Forward = ChannelViews.icon(context.pi, "Forward");
4677
+ const agents = team.agents.filter((agent) => !agent.temporary).map((agent) => ({
4678
+ key: `handoff:agent:${agent.id}`,
4679
+ label: agent.name,
4680
+ detail: agent.role.split(`
4681
+ `)[0],
4682
+ group: w.agents,
4683
+ icon: icon(context, { kind: "agent", id: agent.id }, icons),
4684
+ run: () => send(conversation, `@${agent.name}`)
4685
+ }));
4686
+ const channels = team.channels.map((channel) => ({
4687
+ key: `handoff:channel:${channel.id}`,
4688
+ label: `#${channel.name}`,
4689
+ detail: channel.topic,
4690
+ group: w.channels,
4691
+ icon: icon(context, { kind: "channel", id: channel.id }, icons),
4692
+ run: () => send(conversation, `#${channel.name}`)
4693
+ }));
4694
+ return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
4695
+ size: 16
4696
+ }), items: [...agents, ...channels] }];
4697
+ },
4698
+ subscribe: (listener) => context.service.subscribe(listener)
4699
+ };
4294
4700
  }
4295
- }
4296
- function AgentMenu({ context, agent, cwd, working }) {
4297
- const { pi, service } = context;
4298
- const w = ChannelViews.words(pi);
4299
- const [dialog, setDialog] = React.useState();
4300
- const icon = (name) => ChannelViews.maybeIcon(pi, name, null, 15);
4301
- const fail = (error) => pi.ui.notify(ChannelViews.message(error), "error");
4302
- const act = (action) => () => {
4303
- Promise.resolve().then(action).catch(fail);
4304
- };
4305
- const openSession = async () => {
4306
- if (!agent.sessionFile) {
4701
+ HandOffView.composerAddon = composerAddon;
4702
+ })(HandOffView ||= {});
4703
+
4704
+ // web-src/round-rules.ts
4705
+ var ChannelRounds;
4706
+ ((ChannelRounds) => {
4707
+ const SHORT = 20;
4708
+ const MIN_PAIRS = 8;
4709
+ const ALIKE = 0.8;
4710
+ const PING_PONG = 4;
4711
+ const NEW = 0.35;
4712
+ const CHANGES = new Set(["edit", "write", "delete", "move"]);
4713
+ function scale(watchedAt, pages, now) {
4714
+ if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
4715
+ return 2;
4716
+ }
4717
+ return pages === undefined || pages > 0 ? 1 : 0.5;
4718
+ }
4719
+ ChannelRounds.scale = scale;
4720
+ function idle(said, progress) {
4721
+ const last = said.at(-1);
4722
+ if (!last) {
4307
4723
  return;
4308
4724
  }
4309
- return (await pi.server.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
4310
- };
4311
- const stop = act(async () => {
4312
- const session = await openSession();
4313
- if (session) {
4314
- await pi.server.abort(session.sessionId);
4725
+ const pairs = said.map((item) => pairsOf(item.text));
4726
+ const mine = pairs[pairs.length - 1];
4727
+ if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
4728
+ return "repeat";
4315
4729
  }
4316
- pi.ui.notify(ChannelWords.format(w.stoppedAgent, { name: agent.name }), "info");
4317
- });
4318
- const restart = act(async () => {
4319
- await service.resetAgent(agent.id);
4320
- context.sessions.delete(agent.id);
4321
- pi.ui.notify(ChannelWords.format(w.resetDone, { name: agent.name }), "info");
4322
- });
4323
- const copyCwd = act(async () => {
4324
- if (await copy(cwd)) {
4325
- pi.ui.notify(ChannelWords.format(w.copied, { path: cwd }), "info");
4730
+ const recent = said.slice(-3);
4731
+ if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
4732
+ return "agree";
4326
4733
  }
4327
- });
4328
- const exportMarkdown = act(async () => {
4329
- const session = await openSession();
4330
- const sessionId = session?.sessionId ?? (agent.sessionFile ? await service.openAgent(agent.id) : undefined);
4331
- const { messages } = sessionId ? await pi.server.getMessages(sessionId) : { messages: [] };
4332
- if (!messages.some((message) => message.role === "assistant")) {
4333
- pi.ui.notify(ChannelWords.format(w.nothingToExport, { name: agent.name }), "info");
4734
+ const run = said.slice(-PING_PONG);
4735
+ const authors = new Set(run.map((item) => item.author));
4736
+ const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
4737
+ const start = said.length - PING_PONG;
4738
+ if (progress || start <= 0 || authors.size !== 2 || !alternate) {
4334
4739
  return;
4335
4740
  }
4336
- download(`${agent.name}.md`, ChannelsText.markdown(agent, messages, { user: w.you }));
4337
- });
4338
- const remove = act(() => deleteAgent(context, agent));
4339
- const pin = act(() => service.updateAgent(agent.id, { pinned: !agent.pinned }));
4340
- const keep = act(async () => {
4341
- await service.updateAgent(agent.id, { keep: true });
4342
- pi.ui.notify(ChannelWords.format(w.kept, { name: agent.name }), "info");
4343
- });
4344
- const show = (next) => () => setDialog(next);
4345
- const item = (key, label, glyph, run, options = {}) => ({
4346
- key,
4347
- label,
4348
- icon: icon(glyph),
4349
- run,
4350
- ...options
4351
- });
4352
- return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(MoreMenu, {
4353
- pi,
4354
- label: agent.name,
4355
- items: () => [
4356
- [
4357
- ...agent.temporary ? [item("keep", w.keep, "UserPlus", keep)] : [],
4358
- item("pin", agent.pinned ? w.unpin : w.pin, agent.pinned ? "PinOff" : "Pin", pin)
4359
- ],
4360
- [item("stop", w.stop, "Square", stop, { disabled: !working && !agent.sessionFile }), item("restart", w.restart, "RotateCcw", restart)],
4361
- [
4362
- item("settings", w.agentSettings, "SlidersHorizontal", show("settings")),
4363
- item("rename", w.rename, "Pencil", show("rename")),
4364
- item("role", w.editRole, "ScrollText", show("role")),
4365
- item("move", w.moveTo, "FolderInput", show("move")),
4366
- item("copy", w.copyCwd, "Copy", copyCwd)
4367
- ],
4368
- [
4369
- item("card", w.shareCard, "Contact", show("card")),
4370
- item("export", w.exportChat, "Download", exportMarkdown),
4371
- item("join", w.joinChannel, "UserPlus", show("join"))
4372
- ],
4373
- [item("delete", w.deleteAgent, "Trash2", remove, { danger: true })]
4374
- ]
4375
- }), dialog === "settings" && /* @__PURE__ */ React.createElement(AgentSettingsDialog, {
4376
- context,
4377
- agent,
4378
- onClose: () => setDialog(undefined)
4379
- }), dialog === "rename" && /* @__PURE__ */ React.createElement(RenameDialog, {
4380
- context,
4381
- agent,
4382
- onClose: () => setDialog(undefined)
4383
- }), dialog === "role" && /* @__PURE__ */ React.createElement(RoleDialog, {
4384
- context,
4385
- agent,
4386
- onClose: () => setDialog(undefined)
4387
- }), dialog === "join" && /* @__PURE__ */ React.createElement(JoinDialog, {
4388
- context,
4389
- agent,
4390
- onClose: () => setDialog(undefined)
4391
- }), dialog === "card" && /* @__PURE__ */ React.createElement(CardDialog, {
4392
- context,
4393
- agent,
4394
- onClose: () => setDialog(undefined)
4395
- }), dialog === "move" && /* @__PURE__ */ React.createElement(pi.ui.FolderPicker, {
4396
- initial: cwd,
4397
- onClose: () => setDialog(undefined),
4398
- onPick: async (path) => {
4399
- setDialog(undefined);
4400
- if (path !== cwd) {
4401
- await service.updateAgent(agent.id, { cwd: path }).catch(fail);
4402
- context.sessions.delete(agent.id);
4741
+ const seen = new Set(pairs.slice(0, start).flat());
4742
+ for (const own of pairs.slice(start)) {
4743
+ const fresh = own.filter((pair) => !seen.has(pair)).length;
4744
+ if (own.length === 0 || fresh / own.length >= NEW) {
4745
+ return;
4746
+ }
4747
+ for (const pair of own) {
4748
+ seen.add(pair);
4403
4749
  }
4404
4750
  }
4405
- }));
4406
- }
4407
- function useSave(action, onClose) {
4408
- const [busy, setBusy] = React.useState(false);
4409
- const [error, setError] = React.useState();
4410
- const submit = (event) => {
4411
- event.preventDefault();
4412
- setBusy(true);
4413
- setError(undefined);
4414
- action().then(onClose, (failure) => {
4415
- setBusy(false);
4416
- setError(ChannelViews.message(failure));
4417
- });
4418
- };
4419
- return { busy, error, submit };
4420
- }
4421
- function AgentSettingsDialog({ context, agent, onClose }) {
4422
- const { pi, service } = context;
4423
- const w = ChannelViews.words(pi);
4424
- const [name, setName] = React.useState(agent.name);
4425
- const [model, setModel] = React.useState(agent.model ?? "");
4426
- const [role, setRole] = React.useState(agent.role);
4427
- const change = {
4428
- ...name.trim() !== agent.name ? { name } : {},
4429
- ...model !== (agent.model ?? "") ? { model } : {},
4430
- ...role.trim() !== agent.role ? { role } : {}
4431
- };
4432
- const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, change), onClose);
4433
- return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
4434
- title: `${w.agentSettings} · ${agent.name}`,
4435
- onClose
4436
- }, /* @__PURE__ */ React.createElement("form", {
4437
- className: "tac-dialog",
4438
- onSubmit: submit
4439
- }, /* @__PURE__ */ React.createElement("label", {
4440
- className: "tac-dialog-label"
4441
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4442
- className: "tac-input tac-dialog-input",
4443
- value: name,
4444
- maxLength: 32,
4445
- onChange: (event) => setName(event.target.value)
4446
- })), /* @__PURE__ */ React.createElement("div", {
4447
- className: "tac-dialog-field"
4448
- }, /* @__PURE__ */ React.createElement("span", null, w.model), /* @__PURE__ */ React.createElement(pi.ui.ModelPicker, {
4449
- cwd: agent.cwd,
4450
- value: model,
4451
- label: w.model,
4452
- onChange: setModel
4453
- })), /* @__PURE__ */ React.createElement("label", {
4454
- className: "tac-dialog-label"
4455
- }, w.editRole, /* @__PURE__ */ React.createElement("textarea", {
4456
- className: "tac-input tac-settings-role",
4457
- value: role,
4458
- placeholder: w.rolePlaceholder,
4459
- onChange: (event) => setRole(event.target.value)
4460
- })), /* @__PURE__ */ React.createElement("p", {
4461
- className: "tac-dialog-note"
4462
- }, w.agentSettingsHint), error && /* @__PURE__ */ React.createElement("div", {
4463
- className: "tac-error"
4464
- }, error), /* @__PURE__ */ React.createElement("div", {
4465
- className: "tac-dialog-actions"
4466
- }, /* @__PURE__ */ React.createElement("button", {
4467
- type: "submit",
4468
- className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4469
- disabled: busy || !name.trim() || !role.trim() || Object.keys(change).length === 0
4470
- }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
4471
- className: "ta-spinner ta-busy-mark ta-on-brand"
4472
- })))));
4473
- }
4474
- function RenameDialog({ context, agent, onClose }) {
4475
- const { pi, service } = context;
4476
- const w = ChannelViews.words(pi);
4477
- const [name, setName] = React.useState(agent.name);
4478
- const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { name }), onClose);
4479
- return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
4480
- title: w.rename,
4481
- onClose
4482
- }, /* @__PURE__ */ React.createElement("form", {
4483
- className: "tac-dialog",
4484
- onSubmit: submit
4485
- }, /* @__PURE__ */ React.createElement("label", {
4486
- className: "tac-dialog-label"
4487
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4488
- className: "tac-input tac-dialog-input",
4489
- value: name,
4490
- maxLength: 32,
4491
- autoFocus: true,
4492
- onChange: (event) => setName(event.target.value)
4493
- })), error && /* @__PURE__ */ React.createElement("div", {
4494
- className: "tac-error"
4495
- }, error), /* @__PURE__ */ React.createElement("div", {
4496
- className: "tac-dialog-actions"
4497
- }, /* @__PURE__ */ React.createElement("button", {
4498
- type: "submit",
4499
- className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4500
- disabled: busy || !name.trim() || name.trim() === agent.name
4501
- }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
4502
- className: "ta-spinner ta-busy-mark ta-on-brand"
4503
- })))));
4751
+ return "pingPong";
4752
+ }
4753
+ ChannelRounds.idle = idle;
4754
+ function day(now) {
4755
+ const date = new Date(now);
4756
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
4757
+ }
4758
+ ChannelRounds.day = day;
4759
+ function limits(stored) {
4760
+ const given = stored ?? {};
4761
+ const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
4762
+ return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
4763
+ }
4764
+ ChannelRounds.limits = limits;
4765
+ function today(stored, now) {
4766
+ const current = day(now);
4767
+ return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
4768
+ }
4769
+ ChannelRounds.today = today;
4770
+ function spend(stored, channelId, tokens, now) {
4771
+ const current = today(stored, now);
4772
+ return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
4773
+ }
4774
+ ChannelRounds.spend = spend;
4775
+ function held(spent, limits2, channelId, hops, granted = false) {
4776
+ if (granted) {
4777
+ return;
4778
+ }
4779
+ if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
4780
+ return "all";
4781
+ }
4782
+ if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
4783
+ return "channel";
4784
+ }
4785
+ return;
4786
+ }
4787
+ ChannelRounds.held = held;
4788
+ function changedFiles(entries) {
4789
+ for (const entry of entries) {
4790
+ const message = entry?.message;
4791
+ if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
4792
+ continue;
4793
+ }
4794
+ for (const part of message.content) {
4795
+ if (part?.type !== "toolCall") {
4796
+ continue;
4797
+ }
4798
+ if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
4799
+ return true;
4800
+ }
4801
+ }
4802
+ }
4803
+ return false;
4804
+ }
4805
+ ChannelRounds.changedFiles = changedFiles;
4806
+ function units(text) {
4807
+ return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
4808
+ }
4809
+ function pairsOf(text) {
4810
+ const words = units(text);
4811
+ return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
4812
+ }
4813
+ function alike(a, b) {
4814
+ if (a.length === 0 || b.length === 0) {
4815
+ return 0;
4816
+ }
4817
+ const left = new Map;
4818
+ for (const pair of a) {
4819
+ left.set(pair, (left.get(pair) ?? 0) + 1);
4820
+ }
4821
+ let common = 0;
4822
+ for (const pair of b) {
4823
+ const n = left.get(pair) ?? 0;
4824
+ if (n > 0) {
4825
+ left.set(pair, n - 1);
4826
+ common++;
4827
+ }
4828
+ }
4829
+ return 2 * common / (a.length + b.length);
4830
+ }
4831
+ })(ChannelRounds ||= {});
4832
+
4833
+ // web-src/limit-settings.tsx
4834
+ function amount(pi, tokens) {
4835
+ return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
4504
4836
  }
4505
- function RoleDialog({ context, agent, onClose }) {
4506
- const { pi, service } = context;
4507
- const w = ChannelViews.words(pi);
4508
- const [role, setRole] = React.useState(agent.role);
4509
- const { busy, error, submit } = useSave(() => service.updateAgent(agent.id, { role }), onClose);
4510
- return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
4511
- title: `${w.editRole} · ${agent.name}`,
4512
- onClose
4513
- }, /* @__PURE__ */ React.createElement("form", {
4514
- className: "tac-dialog",
4515
- onSubmit: submit
4516
- }, /* @__PURE__ */ React.createElement("p", {
4517
- className: "tac-dialog-note"
4518
- }, w.roleHint), /* @__PURE__ */ React.createElement("textarea", {
4519
- className: "tac-input tac-role-input",
4520
- value: role,
4521
- placeholder: w.rolePlaceholder,
4522
- "aria-label": w.editRole,
4523
- autoFocus: true,
4524
- onChange: (event) => setRole(event.target.value)
4525
- }), error && /* @__PURE__ */ React.createElement("div", {
4526
- className: "tac-error"
4527
- }, error), /* @__PURE__ */ React.createElement("div", {
4528
- className: "tac-dialog-actions"
4529
- }, /* @__PURE__ */ React.createElement("button", {
4530
- type: "submit",
4531
- className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4532
- disabled: busy || !role.trim() || role.trim() === agent.role
4533
- }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
4534
- className: "ta-spinner ta-busy-mark ta-on-brand"
4535
- })))));
4837
+ function useLimits(pi) {
4838
+ const read = React.useCallback(async () => ({
4839
+ limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
4840
+ ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
4841
+ }), [pi]);
4842
+ const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
4843
+ React.useEffect(() => {
4844
+ let live = true;
4845
+ const load = () => void read().then((next) => live && setValue(next), () => {
4846
+ return;
4847
+ });
4848
+ load();
4849
+ const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
4850
+ return () => {
4851
+ live = false;
4852
+ stop();
4853
+ };
4854
+ }, [pi, read]);
4855
+ return value;
4536
4856
  }
4537
- function JoinDialog({ context, agent, onClose }) {
4538
- const { pi, service } = context;
4539
- const { team } = useChannels(service);
4540
- const w = ChannelViews.words(pi);
4541
- const Hash = ChannelViews.icon(pi, "Hash");
4542
- const [error, setError] = React.useState();
4543
- const open = team.channels.filter((channel) => !channel.members.includes(agent.id));
4544
- const join = (channelId, name) => {
4545
- service.addMembers(channelId, [agent.id]).then(() => {
4546
- onClose();
4547
- pi.ui.notify(ChannelWords.format(w.joined, { name: agent.name, channel: name }), "info");
4548
- }, (failure) => setError(ChannelViews.message(failure)));
4857
+ function limitSettings(pi, service) {
4858
+ const words = () => ChannelWords.of(pi.ui.language);
4859
+ const row = (key) => function Choices() {
4860
+ const { limits } = useLimits(pi);
4861
+ const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
4862
+ return /* @__PURE__ */ React.createElement("fieldset", {
4863
+ className: "ta-segmented",
4864
+ "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
4865
+ }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
4866
+ key: value,
4867
+ type: "button",
4868
+ "aria-pressed": limits[key] === value,
4869
+ className: limits[key] === value ? "ta-on" : "",
4870
+ onClick: () => pick(value)
4871
+ }, amount(pi, value))));
4872
+ };
4873
+ function Spent() {
4874
+ const { spent } = useLimits(pi);
4875
+ return /* @__PURE__ */ React.createElement("span", {
4876
+ className: "tac-limit-spent"
4877
+ }, spent > 0 ? amount(pi, spent) : "0");
4878
+ }
4879
+ return {
4880
+ title: () => words().limitsTitle,
4881
+ icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
4882
+ group: "ta",
4883
+ rows: [
4884
+ { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
4885
+ { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
4886
+ { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
4887
+ { key: "spent", label: () => words().limitSpent, render: Spent }
4888
+ ]
4549
4889
  };
4550
- return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
4551
- title: `${w.joinChannel} · ${agent.name}`,
4552
- onClose
4553
- }, /* @__PURE__ */ React.createElement("div", {
4554
- className: "tac-dialog"
4555
- }, /* @__PURE__ */ React.createElement("div", {
4556
- className: "tac-pick-list"
4557
- }, open.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4558
- compact: true,
4559
- title: w.noChannelToJoin
4560
- }), open.map((channel) => /* @__PURE__ */ React.createElement("button", {
4561
- key: channel.id,
4562
- type: "button",
4563
- className: "tac-pick",
4564
- disabled: channel.members.length >= MAX_MEMBERS,
4565
- onClick: () => join(channel.id, channel.name)
4566
- }, /* @__PURE__ */ React.createElement(Hash, {
4567
- size: 16
4568
- }), /* @__PURE__ */ React.createElement("span", {
4569
- className: "tac-pick-text"
4570
- }, /* @__PURE__ */ React.createElement("span", {
4571
- className: "tac-pick-name"
4572
- }, channel.name), /* @__PURE__ */ React.createElement("span", {
4573
- className: "tac-pick-role"
4574
- }, channel.topic ?? ChannelWords.format(w.memberCount, { count: String(channel.members.length) })))))), error && /* @__PURE__ */ React.createElement("div", {
4575
- className: "tac-error"
4576
- }, error)));
4577
4890
  }
4578
4891
 
4579
4892
  // ../ta-protocol/esm/common/team-protocol.js
@@ -4864,6 +5177,31 @@ var RoomUtil;
4864
5177
  }
4865
5178
  RoomUtil.rows = rows;
4866
5179
  })(RoomUtil ||= {});
5180
+ function MessagePictures({ context, channelId, message, alt }) {
5181
+ const { pi, service } = context;
5182
+ const images = message.images ?? [];
5183
+ const [sources, setSources] = React.useState({});
5184
+ const ids = images.map((image) => image.id).join(",");
5185
+ React.useEffect(() => {
5186
+ let live = true;
5187
+ for (const id of ids ? ids.split(",") : []) {
5188
+ service.picture(channelId, id).then((data) => live && data && setSources((current) => ({ ...current, [id]: data })));
5189
+ }
5190
+ return () => {
5191
+ live = false;
5192
+ };
5193
+ }, [service, channelId, ids]);
5194
+ const ChatImages = pi.ui.ChatImages;
5195
+ if (!images.length || !ChatImages) {
5196
+ return null;
5197
+ }
5198
+ return /* @__PURE__ */ React.createElement("div", {
5199
+ className: "tac-pics"
5200
+ }, /* @__PURE__ */ React.createElement(ChatImages, {
5201
+ alt,
5202
+ images: images.map((image) => ({ key: image.id, src: sources[image.id], width: image.w, height: image.h }))
5203
+ }));
5204
+ }
4867
5205
  function Mentions({ text, agents }) {
4868
5206
  const names = new Set(agents.map((agent) => agent.name.toLowerCase()));
4869
5207
  const parts = text.split(/(@[^\s@#,,。::]+)/);
@@ -5054,19 +5392,11 @@ function ChannelRoom({ context, channelId: fixed }) {
5054
5392
  }
5055
5393
  const members = membersOf(state.team, channel);
5056
5394
  const agentOf = (id) => state.team.agents.find((agent) => agent.id === id);
5395
+ const reply = ChannelsText.replyOf(channel);
5396
+ const lead = members.find((agent) => !(channel.muted ?? []).includes(agent.id));
5397
+ const placeholder = reply === "all" ? w.placeholderAll : reply === "lead" && lead ? w.placeholderLead : w.placeholder;
5057
5398
  const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5058
5399
  const time = (at) => SidebarUtil.time(at, pi.ui.language);
5059
- const mention = (agent) => ({
5060
- key: agent.id,
5061
- label: agent.name,
5062
- icon: /* @__PURE__ */ React.createElement(AgentAvatar, {
5063
- agent,
5064
- faces,
5065
- size: 20
5066
- }),
5067
- detail: agent.id === channel.members[0] ? w.lead : undefined,
5068
- insert: `@${agent.name} `
5069
- });
5070
5400
  return /* @__PURE__ */ React.createElement("div", {
5071
5401
  className: "tac-room-page"
5072
5402
  }, /* @__PURE__ */ React.createElement(NoticeBar, {
@@ -5115,7 +5445,12 @@ function ChannelRoom({ context, channelId: fixed }) {
5115
5445
  className: "tac-msg-col"
5116
5446
  }, first && /* @__PURE__ */ React.createElement("div", {
5117
5447
  className: "tac-msg-name"
5118
- }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement("div", {
5448
+ }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement(MessagePictures, {
5449
+ context,
5450
+ channelId: channel.id,
5451
+ message,
5452
+ alt: message.byName ?? w.owner
5453
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
5119
5454
  className: "tac-msg-bubble",
5120
5455
  title: time(message.at)
5121
5456
  }, /* @__PURE__ */ React.createElement(Mentions, {
@@ -5123,7 +5458,12 @@ function ChannelRoom({ context, channelId: fixed }) {
5123
5458
  agents: state.team.agents
5124
5459
  })))) : message.author === USER ? /* @__PURE__ */ React.createElement("div", {
5125
5460
  className: "ta-message ta-user tac-mine"
5126
- }, /* @__PURE__ */ React.createElement("div", {
5461
+ }, /* @__PURE__ */ React.createElement(MessagePictures, {
5462
+ context,
5463
+ channelId: channel.id,
5464
+ message,
5465
+ alt: w.you
5466
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
5127
5467
  className: "ta-bubble"
5128
5468
  }, /* @__PURE__ */ React.createElement(Mentions, {
5129
5469
  text: message.text,
@@ -5167,12 +5507,12 @@ function ChannelRoom({ context, channelId: fixed }) {
5167
5507
  }))), ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") })))), /* @__PURE__ */ React.createElement("div", {
5168
5508
  className: "tac-chat-bottom"
5169
5509
  }, /* @__PURE__ */ React.createElement(Composer, {
5170
- placeholder: ChannelWords.format(w.placeholder, { channel: channel.name }),
5510
+ placeholder: ChannelWords.format(placeholder, { channel: channel.name, lead: lead?.name ?? "" }),
5171
5511
  draft: channel.id,
5172
5512
  mentions: members.map((agent) => ({ name: agent.name, detail: agent.role.split(`
5173
5513
  `)[0] })),
5514
+ mentionLabel: w.mentionMember,
5174
5515
  actions: [
5175
- members.map(mention),
5176
5516
  [
5177
5517
  {
5178
5518
  key: "notice",
@@ -5202,7 +5542,8 @@ function ChannelRoom({ context, channelId: fixed }) {
5202
5542
  }
5203
5543
  ]
5204
5544
  ],
5205
- onSend: (text) => service.post(channel.id, text)
5545
+ images: { side: 1600, bytes: 1024 * 1024 },
5546
+ onSend: (text, images) => service.post(channel.id, text, images ?? [])
5206
5547
  })));
5207
5548
  }
5208
5549
 
@@ -5448,6 +5789,16 @@ async function editChannelTopic(context, channel) {
5448
5789
  await context.service.updateChannel(channel.id, { topic });
5449
5790
  }
5450
5791
  }
5792
+ async function exportChannel(context, channel) {
5793
+ const { pi, service } = context;
5794
+ const w = ChannelViews.words(pi);
5795
+ const messages = await service.messages(channel.id);
5796
+ if (!messages.some((message) => message.text.trim())) {
5797
+ pi.ui.notify(ChannelWords.format(w.noMessagesToExport, { channel: channel.name }), "info");
5798
+ return;
5799
+ }
5800
+ download2(`${channel.name}.md`, ChannelsText.channelMarkdown(service.state.team, channel, messages, { user: w.you, ta: w.ta }));
5801
+ }
5451
5802
  function ChannelMenu({ context, channel, working }) {
5452
5803
  const { pi, service, ui } = context;
5453
5804
  const { fresh } = useUi(ui);
@@ -5457,6 +5808,7 @@ function ChannelMenu({ context, channel, working }) {
5457
5808
  Promise.resolve().then(action2).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"));
5458
5809
  };
5459
5810
  const unread = fresh.includes(channel.id);
5811
+ const manage = ChannelsUtil.may(service.state.team).manage(channel.id);
5460
5812
  const pin = act(() => service.updateChannel(channel.id, { pinned: !channel.pinned }));
5461
5813
  const markRead = act(() => ui.set({ fresh: unread ? fresh.filter((id) => id !== channel.id) : [...fresh, channel.id] }));
5462
5814
  const rename = act(() => renameChannel(context, channel));
@@ -5469,14 +5821,7 @@ function ChannelMenu({ context, channel, working }) {
5469
5821
  await TeamActions.stop(context, working);
5470
5822
  pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info");
5471
5823
  });
5472
- const exportMarkdown = act(async () => {
5473
- const messages = await service.messages(channel.id);
5474
- if (!messages.some((message) => message.text.trim())) {
5475
- pi.ui.notify(ChannelWords.format(w.noMessagesToExport, { channel: channel.name }), "info");
5476
- return;
5477
- }
5478
- download2(`${channel.name}.md`, ChannelsText.channelMarkdown(service.state.team, channel, messages, { user: w.you, ta: w.ta }));
5479
- });
5824
+ const exportMarkdown = act(() => exportChannel(context, channel));
5480
5825
  const remove = act(() => deleteChannel(context, channel));
5481
5826
  const budget = ChannelsUtil.budgetOf(channel);
5482
5827
  const budgets = [
@@ -5504,13 +5849,16 @@ function ChannelMenu({ context, channel, working }) {
5504
5849
  label: channel.name,
5505
5850
  items: () => [
5506
5851
  [
5507
- item("pin", channel.pinned ? w.unpin : w.pin, channel.pinned ? "PinOff" : "Pin", pin),
5852
+ ...manage ? [item("pin", channel.pinned ? w.unpin : w.pin, channel.pinned ? "PinOff" : "Pin", pin)] : [],
5508
5853
  item("read", unread ? w.markRead : w.markUnread, unread ? "MessageSquareText" : "MessageSquareDot", markRead)
5509
5854
  ],
5510
- [item("rename", w.rename, "Pencil", rename), item("topic", w.editTopic, "Text", editTopic), item("members", w.showMembers, "Users", members)],
5511
- budgets.map(budgetItem),
5855
+ [
5856
+ ...manage ? [item("rename", w.rename, "Pencil", rename), item("topic", w.editTopic, "Text", editTopic)] : [],
5857
+ item("members", w.showMembers, "Users", members)
5858
+ ],
5859
+ manage ? budgets.map(budgetItem) : [],
5512
5860
  [item("stop", w.stopAnswering, "Square", stop, { disabled: working.length === 0 }), item("export", w.exportChat, "Download", exportMarkdown)],
5513
- [item("delete", w.deleteChannel, "Trash2", remove, { danger: true })]
5861
+ manage ? [item("delete", w.deleteChannel, "Trash2", remove, { danger: true })] : []
5514
5862
  ]
5515
5863
  });
5516
5864
  }
@@ -5559,6 +5907,9 @@ function MemberList({ context, team, channel, faces, working }) {
5559
5907
  const Trash = ChannelViews.icon(pi, "Trash2");
5560
5908
  const Sliders = pi.ui.icons.SlidersHorizontal ?? ChannelViews.icon(pi, "Pencil");
5561
5909
  const members = membersOf(team, channel);
5910
+ const may = ChannelsUtil.may(team);
5911
+ const manage = may.manage(channel.id);
5912
+ const edit = may.edit(channel.id);
5562
5913
  const models = new Set(members.map((agent) => agent.model ?? ""));
5563
5914
  const shared = models.size === 1 ? [...models][0] : undefined;
5564
5915
  const muted = channel.muted ?? [];
@@ -5592,7 +5943,7 @@ function MemberList({ context, team, channel, faces, working }) {
5592
5943
  className: "tac-members-title"
5593
5944
  }, /* @__PURE__ */ React.createElement("strong", null, channel.name), /* @__PURE__ */ React.createElement("span", null, channel.topic ?? ChannelWords.format(w.memberCount, { count: String(members.length) })))), /* @__PURE__ */ React.createElement("div", {
5594
5945
  className: "tac-members-label"
5595
- }, /* @__PURE__ */ React.createElement("span", null, w.members, " · ", members.length), /* @__PURE__ */ React.createElement("span", {
5946
+ }, /* @__PURE__ */ React.createElement("span", null, w.members, " · ", members.length), edit && /* @__PURE__ */ React.createElement("span", {
5596
5947
  className: "tac-members-model",
5597
5948
  title: w.sameModelHint
5598
5949
  }, /* @__PURE__ */ React.createElement("span", null, w.sameModel), /* @__PURE__ */ React.createElement(pi.ui.ModelPicker, {
@@ -5601,7 +5952,7 @@ function MemberList({ context, team, channel, faces, working }) {
5601
5952
  label: w.sameModelHint,
5602
5953
  disabled: !!busy,
5603
5954
  onChange: setModel
5604
- }))), /* @__PURE__ */ React.createElement("button", {
5955
+ }))), edit && /* @__PURE__ */ React.createElement("button", {
5605
5956
  type: "button",
5606
5957
  className: "tac-member-main",
5607
5958
  onClick: () => ui.set({ adding: true })
@@ -5619,6 +5970,7 @@ function MemberList({ context, team, channel, faces, working }) {
5619
5970
  const answering = working.includes(agent.id);
5620
5971
  const detail = answering ? w.replying : off ? w.muted : agent.role.split(`
5621
5972
  `)[0] ?? "";
5973
+ const edits = may.agent(agent.id);
5622
5974
  return /* @__PURE__ */ React.createElement("div", {
5623
5975
  key: agent.id,
5624
5976
  className: `tac-member${off ? " tac-muted" : ""}`
@@ -5649,9 +6001,9 @@ ${agent.role}`,
5649
6001
  title: w.temporary
5650
6002
  }, w.temporaryTag)), /* @__PURE__ */ React.createElement("span", {
5651
6003
  className: `tac-member-detail${answering ? " tac-live" : ""}`
5652
- }, detail))), /* @__PURE__ */ React.createElement("span", {
6004
+ }, detail))), (edits || manage) && /* @__PURE__ */ React.createElement("span", {
5653
6005
  className: "tac-member-actions"
5654
- }, /* @__PURE__ */ React.createElement("button", {
6006
+ }, edits && /* @__PURE__ */ React.createElement("button", {
5655
6007
  type: "button",
5656
6008
  className: "tac-action",
5657
6009
  title: w.agentSettings,
@@ -5660,7 +6012,7 @@ ${agent.role}`,
5660
6012
  onClick: () => setEditing(agent)
5661
6013
  }, /* @__PURE__ */ React.createElement(Sliders, {
5662
6014
  size: 15
5663
- })), agent.temporary && /* @__PURE__ */ React.createElement("button", {
6015
+ })), edits && agent.temporary && /* @__PURE__ */ React.createElement("button", {
5664
6016
  type: "button",
5665
6017
  className: "tac-action",
5666
6018
  title: w.keep,
@@ -5669,7 +6021,7 @@ ${agent.role}`,
5669
6021
  onClick: () => service.updateAgent(agent.id, { keep: true }).then(() => pi.ui.notify(ChannelWords.format(w.kept, { name: agent.name }), "info")).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"))
5670
6022
  }, /* @__PURE__ */ React.createElement(UserPlus, {
5671
6023
  size: 15
5672
- })), !lead && /* @__PURE__ */ React.createElement("button", {
6024
+ })), manage && !lead && /* @__PURE__ */ React.createElement("button", {
5673
6025
  type: "button",
5674
6026
  className: "tac-action",
5675
6027
  title: w.makeLead,
@@ -5678,7 +6030,7 @@ ${agent.role}`,
5678
6030
  onClick: () => change(agent, "lead")
5679
6031
  }, /* @__PURE__ */ React.createElement(Crown, {
5680
6032
  size: 15
5681
- })), /* @__PURE__ */ React.createElement("button", {
6033
+ })), manage && /* @__PURE__ */ React.createElement("button", {
5682
6034
  type: "button",
5683
6035
  className: `tac-action${off ? " tac-on" : ""}`,
5684
6036
  title: off ? w.unmute : w.mute,
@@ -5688,7 +6040,7 @@ ${agent.role}`,
5688
6040
  onClick: () => change(agent, off ? "unmute" : "mute")
5689
6041
  }, /* @__PURE__ */ React.createElement(BellOff, {
5690
6042
  size: 15
5691
- })), /* @__PURE__ */ React.createElement("button", {
6043
+ })), edits && /* @__PURE__ */ React.createElement("button", {
5692
6044
  type: "button",
5693
6045
  className: "tac-action",
5694
6046
  title: w.reset,
@@ -5697,7 +6049,7 @@ ${agent.role}`,
5697
6049
  onClick: () => reset(agent)
5698
6050
  }, /* @__PURE__ */ React.createElement(RotateCcw, {
5699
6051
  size: 15
5700
- })), /* @__PURE__ */ React.createElement("button", {
6052
+ })), manage && /* @__PURE__ */ React.createElement("button", {
5701
6053
  type: "button",
5702
6054
  className: "tac-action",
5703
6055
  title: members.length === 1 ? w.onlyMember : w.remove,
@@ -5709,12 +6061,13 @@ ${agent.role}`,
5709
6061
  }))));
5710
6062
  }), /* @__PURE__ */ React.createElement(ChannelSettings, {
5711
6063
  context,
5712
- channel
6064
+ channel,
6065
+ manage
5713
6066
  })), editing && /* @__PURE__ */ React.createElement(AgentSettingsDialog, {
5714
6067
  context,
5715
6068
  agent: editing,
5716
6069
  onClose: () => setEditing(undefined)
5717
- }), /* @__PURE__ */ React.createElement("div", {
6070
+ }), manage && /* @__PURE__ */ React.createElement("div", {
5718
6071
  className: "tac-members-foot"
5719
6072
  }, confirming ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("span", {
5720
6073
  className: "tac-members-ask"
@@ -5737,12 +6090,12 @@ ${agent.role}`,
5737
6090
  size: 14
5738
6091
  }), w.deleteChannel)));
5739
6092
  }
5740
- function ChannelSettings({ context, channel }) {
6093
+ function ChannelSettings({ context, channel, manage }) {
5741
6094
  const { pi, service } = context;
5742
6095
  const w = ChannelViews.words(pi);
5743
6096
  const Chevron = ChannelViews.icon(pi, "ChevronRight");
5744
6097
  const fail = (error) => pi.ui.notify(ChannelViews.message(error), "error");
5745
- const row = (label, value, edit) => /* @__PURE__ */ React.createElement("button", {
6098
+ const row = (label, value, edit) => manage ? /* @__PURE__ */ React.createElement("button", {
5746
6099
  type: "button",
5747
6100
  className: "tac-setting",
5748
6101
  onClick: () => edit().catch(fail)
@@ -5752,10 +6105,16 @@ function ChannelSettings({ context, channel }) {
5752
6105
  className: "tac-setting-value"
5753
6106
  }, value), /* @__PURE__ */ React.createElement(Chevron, {
5754
6107
  size: 15
5755
- }));
6108
+ })) : /* @__PURE__ */ React.createElement("div", {
6109
+ className: "tac-setting"
6110
+ }, /* @__PURE__ */ React.createElement("span", {
6111
+ className: "tac-setting-label"
6112
+ }, label), /* @__PURE__ */ React.createElement("span", {
6113
+ className: "tac-setting-value"
6114
+ }, value));
5756
6115
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
5757
6116
  className: "tac-members-sep"
5758
- }), row(w.channelName, channel.name, () => renameChannel(context, channel)), row(w.topic, channel.topic ?? w.notSet, () => editChannelTopic(context, channel)), /* @__PURE__ */ React.createElement("div", {
6117
+ }), row(w.channelName, channel.name, () => renameChannel(context, channel)), row(w.topic, channel.topic ?? w.notSet, () => editChannelTopic(context, channel)), manage && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
5759
6118
  className: "tac-setting"
5760
6119
  }, /* @__PURE__ */ React.createElement("span", {
5761
6120
  className: "tac-setting-label"
@@ -5766,7 +6125,7 @@ function ChannelSettings({ context, channel }) {
5766
6125
  })), /* @__PURE__ */ React.createElement(ChannelLimits, {
5767
6126
  context,
5768
6127
  channel
5769
- }));
6128
+ })));
5770
6129
  }
5771
6130
  function ChannelLimits({ context, channel }) {
5772
6131
  const { pi, service } = context;
@@ -5779,6 +6138,12 @@ function ChannelLimits({ context, channel }) {
5779
6138
  ["normal", w.budgetNormalWord],
5780
6139
  ["long", w.budgetLongWord]
5781
6140
  ];
6141
+ const reply = ChannelsText.replyOf(channel);
6142
+ const replies = [
6143
+ ["mentioned", w.replyMentionedWord],
6144
+ ["lead", w.replyLeadWord],
6145
+ ["all", w.replyAllWord]
6146
+ ];
5782
6147
  const daily = [null, ...LIMIT_CHOICES.channelDay];
5783
6148
  const own = channel.dailyLimit ?? null;
5784
6149
  const limit = channel.dailyLimit ?? limits.channelDay;
@@ -5797,6 +6162,8 @@ function ChannelLimits({ context, channel }) {
5797
6162
  className: "tac-limits"
5798
6163
  }, /* @__PURE__ */ React.createElement("div", {
5799
6164
  className: "tac-limit-head"
6165
+ }, /* @__PURE__ */ React.createElement("span", null, w.replyHead)), segment(w.replyHead, replies.map(([key]) => key), reply, (key) => replies.find(([other]) => other === key)?.[1] ?? key, (key) => service.updateChannel(channel.id, { reply: key }).catch(fail)), /* @__PURE__ */ React.createElement("div", {
6166
+ className: "tac-limit-head"
5800
6167
  }, /* @__PURE__ */ React.createElement("span", null, w.talkLength)), segment(w.talkLength, budgets.map(([key]) => key), budget, (key) => budgets.find(([other]) => other === key)?.[1] ?? key, (key) => service.updateChannel(channel.id, { budget: key }).catch(fail)), /* @__PURE__ */ React.createElement("div", {
5801
6168
  className: "tac-limit-head"
5802
6169
  }, /* @__PURE__ */ React.createElement("span", null, w.dailyLimit), /* @__PURE__ */ React.createElement("span", {
@@ -5816,7 +6183,8 @@ function MemberPicker({ context, team, channel, faces }) {
5816
6183
  const Check = ChannelViews.icon(pi, "Check");
5817
6184
  const UserPlus = ChannelViews.icon(pi, "UserPlus");
5818
6185
  const back = () => ui.set({ adding: false });
5819
- const friends = useFriends(pi).filter(() => !!pi.rooms && channel.by !== "ta" && !channel.shared);
6186
+ const friends = useFriends(pi).filter(() => !!pi.rooms && !team.may && channel.by !== "ta" && !channel.shared);
6187
+ const creates = ChannelsUtil.may(team).create;
5820
6188
  const [pickedFriends, setPickedFriends] = React.useState([]);
5821
6189
  const toggleFriend = (id) => setPickedFriends(pickedFriends.includes(id) ? pickedFriends.filter((other) => other !== id) : [...pickedFriends, id]);
5822
6190
  const { busy, error, submit } = useSubmit(() => pickedFriends.length > 0 ? becomeGroup(context, channel, pickedFriends, picked) : service.addMembers(channel.id, picked), back);
@@ -5915,7 +6283,7 @@ function MemberPicker({ context, team, channel, faces }) {
5915
6283
  })));
5916
6284
  }), pickedFriends.length > 0 && /* @__PURE__ */ React.createElement("div", {
5917
6285
  className: "tac-members-note"
5918
- }, w.shareGroupHint)), /* @__PURE__ */ React.createElement("div", {
6286
+ }, w.shareGroupHint)), creates && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
5919
6287
  className: "tac-members-sep"
5920
6288
  }), /* @__PURE__ */ React.createElement("button", {
5921
6289
  type: "button",
@@ -5929,7 +6297,7 @@ function MemberPicker({ context, team, channel, faces }) {
5929
6297
  className: "tac-member-text"
5930
6298
  }, /* @__PURE__ */ React.createElement("span", {
5931
6299
  className: "tac-member-name"
5932
- }, w.newAgent)))), error && /* @__PURE__ */ React.createElement("div", {
6300
+ }, w.newAgent))))), error && /* @__PURE__ */ React.createElement("div", {
5933
6301
  className: "tac-empty tac-error"
5934
6302
  }, error), /* @__PURE__ */ React.createElement("div", {
5935
6303
  className: "tac-members-foot"
@@ -5969,7 +6337,10 @@ class ChannelPartners {
5969
6337
  };
5970
6338
  }
5971
6339
  add() {
5972
- const { pi } = this.context;
6340
+ const { pi, service } = this.context;
6341
+ if (!ChannelsUtil.may(service.state.team).create) {
6342
+ return [];
6343
+ }
5973
6344
  return [{ key: "agent", label: ChannelViews.words(pi).newAgent, icon: ChannelViews.icon(pi, "Bot"), run: () => newAgent(this.context) }];
5974
6345
  }
5975
6346
  async group(members) {
@@ -6051,7 +6422,9 @@ class ChannelPartners {
6051
6422
  chat: agent.sessionFile ? { sessionFile: agent.sessionFile } : undefined,
6052
6423
  location: agent.cwd,
6053
6424
  open: () => ChannelViews.openAgent(this.context, agent.id),
6054
- menu: () => [[{ key: "delete", label: w.deleteAgent, danger: true, run: () => void deleteAgent(this.context, agent) }]]
6425
+ info: () => AgentActions.profile(this.context, agent),
6426
+ menu: () => AgentActions.menu(this.context, agent, this.answering(agent.id)),
6427
+ ...ChannelsUtil.may(this.context.service.state.team).agent(agent.id) ? { remove: { key: "delete", label: w.deleteAgent, danger: true, run: () => void deleteAgent(this.context, agent) } } : {}
6055
6428
  };
6056
6429
  }
6057
6430
  channel(channel, w) {
@@ -6068,15 +6441,52 @@ class ChannelPartners {
6068
6441
  icon: ChannelViews.icon(pi, "Hash"),
6069
6442
  about: channel.topic ?? membersOf(team, channel).map((agent) => agent.name).join("、"),
6070
6443
  chat: {
6071
- last: busy.length > 0 ? ChannelWords.format(w.answeringNow, { name: busy.map(name).join("、") }) : last ? `${name(last.author)}:${last.text.replace(/\s+/g, " ")}` : undefined,
6444
+ last: busy.length > 0 ? ChannelWords.format(w.answeringNow, { name: busy.map(name).join("、") }) : last ? `${name(last.author)}:${(last.images?.length && !last.text ? w.picture : last.text).replace(/\s+/g, " ")}` : undefined,
6072
6445
  at: SidebarUtil.channelAt(channel, messages[channel.id]),
6073
6446
  unseen: ui.state.fresh.includes(channel.id),
6074
6447
  busy: busy.length > 0
6075
6448
  },
6076
6449
  open: () => this.context.showChannel(channel.id),
6077
- menu: () => [[{ key: "delete", label: w.deleteChannel, danger: true, run: () => void deleteChannel(this.context, channel) }]]
6450
+ info: () => {
6451
+ this.context.showChannel(channel.id);
6452
+ this.context.showMembers();
6453
+ },
6454
+ menu: () => this.channelMenu(channel),
6455
+ ...ChannelsUtil.may(service.state.team).manage(channel.id) ? { remove: { key: "delete", label: w.deleteChannel, danger: true, run: () => void deleteChannel(this.context, channel) } } : {}
6078
6456
  };
6079
6457
  }
6458
+ answering(id) {
6459
+ return Object.values(this.context.service.state.working).some((ids) => ids.includes(id));
6460
+ }
6461
+ channelMenu(channel) {
6462
+ const { pi, service, ui } = this.context;
6463
+ const w = ChannelViews.words(pi);
6464
+ const icon = (name) => ChannelViews.icon(pi, name);
6465
+ const fail = (error) => pi.ui.notify(ChannelViews.message(error), "error");
6466
+ const { fresh } = ui.state;
6467
+ const unread = fresh.includes(channel.id);
6468
+ const working = service.state.working[channel.id] ?? [];
6469
+ return [
6470
+ [
6471
+ {
6472
+ key: "read",
6473
+ label: unread ? w.markRead : w.markUnread,
6474
+ icon: icon(unread ? "MessageSquareText" : "MessageSquareDot"),
6475
+ run: () => ui.set({ fresh: unread ? fresh.filter((id) => id !== channel.id) : [...fresh, channel.id] })
6476
+ }
6477
+ ],
6478
+ [
6479
+ {
6480
+ key: "stop",
6481
+ label: w.stopAnswering,
6482
+ icon: icon("Square"),
6483
+ disabled: working.length === 0,
6484
+ run: () => void TeamActions.stop(this.context, working).then(() => pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info")).catch(fail)
6485
+ },
6486
+ { key: "export", label: w.exportChat, icon: icon("Download"), run: () => void exportChannel(this.context, channel).catch(fail) }
6487
+ ]
6488
+ ];
6489
+ }
6080
6490
  agentFace(id) {
6081
6491
  return this.face(`agent:${id}`, function AgentFace({ size, state: { team, working } }) {
6082
6492
  const faces = useFaces(team);
@@ -6518,6 +6928,7 @@ function AgentsSidebar({ context, partners = false }) {
6518
6928
  const { query, draft, channelId, fresh: unread } = useUi(ui);
6519
6929
  const w = ChannelViews.words(pi);
6520
6930
  const faces = useFaces(state.team);
6931
+ const may = ChannelsUtil.may(state.team);
6521
6932
  const serverCwd = useServerCwd(pi) ?? "";
6522
6933
  const shownSession = pi.ui.useSessionId();
6523
6934
  const double = pi.ui.useView(DOUBLE_PAGE);
@@ -6659,7 +7070,7 @@ function AgentsSidebar({ context, partners = false }) {
6659
7070
  cwd,
6660
7071
  working: !!where
6661
7072
  }),
6662
- swipe: swipePinDelete(pi, !!agent.pinned, (pinned) => context.service.updateAgent(agent.id, { pinned }), () => deleteAgent(context, agent))
7073
+ swipe: may.agent(agent.id) ? swipePinDelete(pi, !!agent.pinned, (pinned) => context.service.updateAgent(agent.id, { pinned }), () => deleteAgent(context, agent)) : undefined
6663
7074
  });
6664
7075
  };
6665
7076
  const chatAgents = partners && lastLines ? agents.filter((agent) => lastLines.has(agent.id)) : [];
@@ -6818,7 +7229,7 @@ function AgentsSidebar({ context, partners = false }) {
6818
7229
  channel,
6819
7230
  working: busy
6820
7231
  }),
6821
- swipe: swipePinDelete(pi, !!channel.pinned, (pinned) => context.service.updateChannel(channel.id, { pinned }), () => deleteChannel(context, channel))
7232
+ swipe: may.manage(channel.id) ? swipePinDelete(pi, !!channel.pinned, (pinned) => context.service.updateChannel(channel.id, { pinned }), () => deleteChannel(context, channel)) : undefined
6822
7233
  });
6823
7234
  })), agents.length > 0 && /* @__PURE__ */ React.createElement(Section, {
6824
7235
  id: "members",
@@ -7030,6 +7441,9 @@ var STYLE = `
7030
7441
  .tac-chat-empty strong { margin-top: 6px; color: var(--ta-text); font-size: calc(16px * var(--ta-font-scale)); }
7031
7442
  .tac-chat-hint { margin-top: 4px; font-size: calc(12px * var(--ta-font-scale)); }
7032
7443
  .tac-mine { margin: 6px 0 2px; }
7444
+ /* Pictures of a message (ui.ChatImages), no bubble around them, on the side of who sent them. */
7445
+ .tac-pics { margin: 1px 0 3px; }
7446
+ .tac-mine .tac-pics { align-self: flex-end; }
7033
7447
  .tac-msg { display: flex; align-items: flex-start; gap: 10px; }
7034
7448
  .tac-msg.tac-first { margin-top: 10px; }
7035
7449
  .tac-msg-face { display: flex; justify-content: center; width: 28px; flex: none; }
@@ -7243,6 +7657,10 @@ textarea.tac-input { resize: vertical; min-height: 56px; line-height: 1.5; }
7243
7657
  .tac-members-scroll > .tac-pick { margin: 1px 0; }
7244
7658
  .tac-check { display: grid; place-items: center; width: 18px; height: 18px; flex: none; box-sizing: border-box; border: 1.5px solid var(--ta-border-field); border-radius: 50%; color: var(--ta-main); }
7245
7659
  .tac-pick.tac-on .tac-check { border-color: var(--ta-green); background: var(--ta-green); }
7660
+ .tac-setting-model > :last-child { flex: none; width: auto; max-width: 60%; margin-left: auto; }
7661
+ .tac-setting-model .ta-model-field { width: auto; justify-content: flex-end; gap: 4px; height: 28px; padding: 0 2px 0 8px; border: 0; border-radius: 6px; background: none; color: var(--ta-muted); font-size: inherit; }
7662
+ .tac-setting-model .ta-model-field:not(:disabled):hover { background: var(--ta-hover); color: var(--ta-text); }
7663
+ .tac-setting-model .ta-model-field > svg { width: 15px; height: 15px; }
7246
7664
  .tac-members-foot { display: flex; align-items: center; justify-content: flex-end; gap: 6px; flex: none; padding: 10px 16px calc(12px + env(safe-area-inset-bottom)); border-top: 1px solid var(--ta-border-muted); }
7247
7665
  .tac-members-ask { flex: 1; min-width: 0; color: var(--ta-body); font-size: calc(12.5px * var(--ta-font-scale)); }
7248
7666
  .tac-members-label { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
@@ -7579,7 +7997,8 @@ function activate(pi) {
7579
7997
  }),
7580
7998
  render: () => /* @__PURE__ */ React.createElement(ChannelRoom, {
7581
7999
  context
7582
- })
8000
+ }),
8001
+ navigation: false
7583
8002
  });
7584
8003
  pi.registerView("agent", {
7585
8004
  title: () => ui.state.draft?.name || ChannelWords.of(pi.ui.language).newAgentName,
@@ -7589,7 +8008,17 @@ function activate(pi) {
7589
8008
  }),
7590
8009
  render: () => /* @__PURE__ */ React.createElement(NewAgentPage, {
7591
8010
  context
7592
- })
8011
+ }),
8012
+ navigation: false
8013
+ });
8014
+ pi.registerView("agent-info", {
8015
+ title: () => ChannelWords.of(pi.ui.language).profileTitle,
8016
+ icon: ChannelViews.icon(pi, "Bot"),
8017
+ render: () => /* @__PURE__ */ React.createElement(AgentInfoView, {
8018
+ context
8019
+ }),
8020
+ location: "panel",
8021
+ order: 61
7593
8022
  });
7594
8023
  pi.registerView("members", {
7595
8024
  title: () => ChannelWords.of(pi.ui.language).showMembers,