@celljs/ta-channels 4.33.0 → 4.35.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
@@ -1100,8 +1100,9 @@ var ChannelsUtil;
1100
1100
  }
1101
1101
  ChannelsUtil.updateChannel = updateChannel;
1102
1102
  function standing(team) {
1103
- const inChannel = new Set(team.channels.flatMap((channel) => channel.members));
1104
- return team.agents.filter((agent) => !agent.temporary || !inChannel.has(agent.id));
1103
+ const inTeams = new Set(taskChannels(team).flatMap((channel) => channel.members));
1104
+ const inOwn = new Set(team.channels.filter((channel) => channel.by !== "ta").flatMap((channel) => channel.members));
1105
+ return team.agents.filter((agent) => !agent.temporary || !inTeams.has(agent.id) || inOwn.has(agent.id));
1105
1106
  }
1106
1107
  ChannelsUtil.standing = standing;
1107
1108
  function taskChannels(team) {
@@ -1535,7 +1536,7 @@ var JA = {
1535
1536
  noChannelToJoin: "すべてのグループチャットに既に含まれています",
1536
1537
  joined: "{name} が #{channel} に参加しました。",
1537
1538
  deleteAgent: "削除",
1538
- confirmDeleteAgent: "{name} を削除しますか?それはそのグループチャットから削除され、それだけのグループチャットも削除されます;セッションファイルは保持されます。",
1539
+ confirmDeleteAgent: "{name} を削除しますか?グループチャットから外れ、ほかに誰もいないグループチャットも削除されます。30 日以内なら「削除したエージェント」から復元できます。",
1539
1540
  pin: "ピン留め",
1540
1541
  unpin: "ピン留めを解除",
1541
1542
  pinned: "ピン留めされています",
@@ -1623,7 +1624,20 @@ var JA = {
1623
1624
  cardAddHint: "追加後、このディレクトリ下のプロジェクトを確認し、役割をここに合わせます;変更内容はセッションで通知します。",
1624
1625
  cardAdded: "@{name} として追加されました",
1625
1626
  cardOpen: "会話を開く",
1626
- cardFailed: "このカードを開けません:{message}"
1627
+ cardFailed: "このカードを開けません:{message}",
1628
+ optimize: "最適化",
1629
+ optimizeAll: "すべて最適化",
1630
+ optimizing: "Ta が使い方に合わせた最適化を検討中です。提案はこの会話に届きます",
1631
+ noInitiative: "エージェントを最適化するには「提案」をオンにしてください",
1632
+ removedAgents: "削除したエージェント({n})",
1633
+ removedTitle: "削除したエージェント",
1634
+ removedHint: "30 日間保持され、復元すると元のグループチャットに戻ります",
1635
+ removedAt: "{days} 日前に削除",
1636
+ removedToday: "今日削除",
1637
+ removedIn: "元は {channels}",
1638
+ restore: "復元",
1639
+ restored: "{name} を復元しました",
1640
+ noRemoved: "この 30 日間に削除したエージェントはありません"
1627
1641
  };
1628
1642
 
1629
1643
  // web-src/i18n-zh.ts
@@ -1790,7 +1804,7 @@ var ZH = {
1790
1804
  noChannelToJoin: "它已经在所有群聊里了",
1791
1805
  joined: "{name} 已加入 #{channel}。",
1792
1806
  deleteAgent: "删除",
1793
- confirmDeleteAgent: "删除 {name}?它会退出所在的群聊,只剩它一个成员的群聊也会一起删除;会话文件会保留。",
1807
+ confirmDeleteAgent: "删除 {name}?它会退出所在的群聊,只剩它一个成员的群聊也会一起删除。30 天内可以在「已移除的智能体」里恢复。",
1794
1808
  pin: "置顶",
1795
1809
  unpin: "取消置顶",
1796
1810
  pinned: "已置顶",
@@ -1878,7 +1892,20 @@ var ZH = {
1878
1892
  cardAddHint: "加进来后它会先看看这个目录下的项目,把职责调整得贴合这里;改了什么会在它的对话里告诉你。",
1879
1893
  cardAdded: "已添加为 @{name}",
1880
1894
  cardOpen: "打开对话",
1881
- cardFailed: "打不开这张名片:{message}"
1895
+ cardFailed: "打不开这张名片:{message}",
1896
+ optimize: "优化",
1897
+ optimizeAll: "全部优化",
1898
+ optimizing: "Ta 正在看怎么按你的用法优化,建议会出现在这个对话里",
1899
+ noInitiative: "打开「主动」后才能优化智能体",
1900
+ removedAgents: "已移除的智能体({n})",
1901
+ removedTitle: "已移除的智能体",
1902
+ removedHint: "保留 30 天,恢复后回到原来的群聊",
1903
+ removedAt: "{days} 天前移除",
1904
+ removedToday: "今天移除",
1905
+ removedIn: "原在 {channels}",
1906
+ restore: "恢复",
1907
+ restored: "{name} 已恢复",
1908
+ noRemoved: "最近 30 天没有移除的智能体"
1882
1909
  };
1883
1910
 
1884
1911
  // web-src/i18n-zh-tw.ts
@@ -2045,7 +2072,7 @@ var ZH_TW = {
2045
2072
  noChannelToJoin: "它已經在所有群聊里了",
2046
2073
  joined: "{name} 已加入 #{channel}。",
2047
2074
  deleteAgent: "刪除",
2048
- confirmDeleteAgent: "刪除 {name}?它會退出所在的群聊,只剩它一個成員的群聊也會一起刪除;會話檔案會保留。",
2075
+ confirmDeleteAgent: "刪除 {name}?它會退出所在的群聊,只剩它一個成員的群聊也會一起刪除。30 天內可以在「已移除的智慧體」裡恢復。",
2049
2076
  pin: "置頂",
2050
2077
  unpin: "取消置頂",
2051
2078
  pinned: "已置頂",
@@ -2133,7 +2160,20 @@ var ZH_TW = {
2133
2160
  cardAddHint: "加進來後它會先看看這個目錄下的專案,把職責調整得貼合這裡;改了什麼會在它的對話裡告訴你。",
2134
2161
  cardAdded: "已新增為 @{name}",
2135
2162
  cardOpen: "開啟對話",
2136
- cardFailed: "打不開這張名片:{message}"
2163
+ cardFailed: "打不開這張名片:{message}",
2164
+ optimize: "優化",
2165
+ optimizeAll: "全部優化",
2166
+ optimizing: "Ta 正在看怎麼按你的用法優化,建議會出現在這個對話裡",
2167
+ noInitiative: "開啟「主動」後才能優化智慧體",
2168
+ removedAgents: "已移除的智慧體({n})",
2169
+ removedTitle: "已移除的智慧體",
2170
+ removedHint: "保留 30 天,恢復後回到原來的群聊",
2171
+ removedAt: "{days} 天前移除",
2172
+ removedToday: "今天移除",
2173
+ removedIn: "原在 {channels}",
2174
+ restore: "恢復",
2175
+ restored: "{name} 已恢復",
2176
+ noRemoved: "最近 30 天沒有移除的智慧體"
2137
2177
  };
2138
2178
 
2139
2179
  // web-src/i18n.ts
@@ -2300,7 +2340,7 @@ var EN = {
2300
2340
  noChannelToJoin: "It is in every group chat already",
2301
2341
  joined: "{name} joined #{channel}.",
2302
2342
  deleteAgent: "Delete",
2303
- confirmDeleteAgent: "Delete {name}? It leaves its group chats, and group chats with no one else go too; its session file stays.",
2343
+ confirmDeleteAgent: "Delete {name}? It leaves its group chats, and group chats with no one else go too. It waits 30 days among the removed agents to restore.",
2304
2344
  pin: "Pin",
2305
2345
  unpin: "Unpin",
2306
2346
  pinned: "Pinned",
@@ -2388,7 +2428,20 @@ var EN = {
2388
2428
  cardAddHint: "It looks at the project there first and fits its role to it; you see what it changed in its conversation.",
2389
2429
  cardAdded: "Added as @{name}",
2390
2430
  cardOpen: "Open the conversation",
2391
- cardFailed: "Could not open the card: {message}"
2431
+ cardFailed: "Could not open the card: {message}",
2432
+ optimize: "Optimize",
2433
+ optimizeAll: "Optimize all agents",
2434
+ optimizing: "Ta is looking at how to fit them to your work; what it suggests waits in this conversation",
2435
+ noInitiative: "Turn on Initiative to optimize agents",
2436
+ removedAgents: "Removed agents ({n})",
2437
+ removedTitle: "Removed agents",
2438
+ removedHint: "Kept 30 days; restored, an agent goes back to its group chats",
2439
+ removedAt: "Removed {days} days ago",
2440
+ removedToday: "Removed today",
2441
+ removedIn: "was in {channels}",
2442
+ restore: "Restore",
2443
+ restored: "{name} is back",
2444
+ noRemoved: "No agent removed in the last 30 days"
2392
2445
  };
2393
2446
  var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
2394
2447
  var ChannelWords;
@@ -2408,6 +2461,7 @@ var DOUBLE_PAGE = "assistant/assistant";
2408
2461
  var CHANNEL_PAGE = `${NAME}/channel`;
2409
2462
  var MEMBERS_VIEW = `${NAME}/members`;
2410
2463
  var AGENT_INFO_VIEW = `${NAME}/agent-info`;
2464
+ var REMOVED_VIEW = `${NAME}/removed-agents`;
2411
2465
  var ROOM_INFO_VIEW = "@celljs/ta-rooms/members";
2412
2466
  var CHANNEL_KEY = "ta-channels.channel";
2413
2467
 
@@ -3462,6 +3516,7 @@ function MoreMenu({ pi, label, items }) {
3462
3516
  }
3463
3517
 
3464
3518
  // web-src/agent-menu.tsx
3519
+ var INITIATIVE = "@celljs/ta-initiative";
3465
3520
  async function copy(text) {
3466
3521
  try {
3467
3522
  await navigator.clipboard.writeText(text);
@@ -3559,6 +3614,18 @@ var AgentActions;
3559
3614
  await context.pi.ui.showView(AGENT_INFO_VIEW);
3560
3615
  }
3561
3616
  AgentActions.profile = profile;
3617
+ async function optimize(context, ids) {
3618
+ const { pi } = context;
3619
+ const w = ChannelViews.words(pi);
3620
+ const file = await pi.packages.callPackageHost(INITIATIVE, "optimizeAgents", [ids]).catch(() => {
3621
+ throw new Error(w.noInitiative);
3622
+ });
3623
+ pi.ui.notify(w.optimizing, "info");
3624
+ if (typeof file === "string" && file) {
3625
+ await pi.openChat?.(file);
3626
+ }
3627
+ }
3628
+ AgentActions.optimize = optimize;
3562
3629
  function menu(context, agent, working) {
3563
3630
  const w = ChannelViews.words(context.pi);
3564
3631
  const edits = ChannelsUtil.may(context.service.state.team).agent(agent.id);
@@ -3569,6 +3636,7 @@ var AgentActions;
3569
3636
  ...edits ? [{ key: "restart", label: w.restart, icon: icon("RotateCcw"), run: run(context, () => restart(context, agent)) }] : []
3570
3637
  ],
3571
3638
  [
3639
+ ...edits ? [{ key: "optimize", label: w.optimize, icon: icon("Sparkles"), run: run(context, () => optimize(context, [agent.id])) }] : [],
3572
3640
  ...edits ? [{ key: "card", label: w.shareCard, icon: icon("Contact"), run: () => shareCard(context, agent) }] : [],
3573
3641
  ...edits ? [{ key: "join", label: w.joinChannel, icon: icon("UserPlus"), run: () => joinChannel(context, agent) }] : [],
3574
3642
  { key: "export", label: w.exportChat, icon: icon("Download"), run: run(context, () => exportChat(context, agent)) }
@@ -3930,7 +3998,7 @@ function AgentInfoView({ context }) {
3930
3998
  location: cwd
3931
3999
  }), cwd && SidebarUtil.folder(cwd)), () => setDialog("move")), /* @__PURE__ */ React.createElement("div", {
3932
4000
  className: "tac-members-sep"
3933
- }), 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", {
4001
+ }), edits && action(w.optimize, act(() => AgentActions.optimize(context, [agent.id]))), 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", {
3934
4002
  className: "tac-members-foot"
3935
4003
  }, /* @__PURE__ */ React.createElement("button", {
3936
4004
  type: "button",
@@ -4299,1685 +4367,1687 @@ class ChannelsClient {
4299
4367
  }
4300
4368
  }
4301
4369
 
4302
- // web-src/shared-group.tsx
4303
- function useFriends(pi) {
4304
- const [friends, setFriends] = React.useState([]);
4305
- React.useEffect(() => {
4306
- let live = true;
4307
- pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
4308
- return;
4309
- });
4310
- return () => {
4311
- live = false;
4370
+ // ../ta-protocol/esm/common/team-protocol.js
4371
+ var TA_OWNER = "owner";
4372
+ var TA_UNDECLARED = "extensions.install";
4373
+ var TaPermissionUtil;
4374
+ (function(TaPermissionUtil2) {
4375
+ function read(pi) {
4376
+ const given = pi === null || pi === undefined ? undefined : pi.permissions;
4377
+ const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
4378
+ const host2 = map(given === null || given === undefined ? undefined : given.host);
4379
+ const tools = map(given === null || given === undefined ? undefined : given.tools);
4380
+ return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
4381
+ }
4382
+ TaPermissionUtil2.read = read;
4383
+ function host(manifest, method, kind) {
4384
+ var _a, _b, _c, _d;
4385
+ const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
4386
+ const own = (key) => {
4387
+ var _a2;
4388
+ return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
4312
4389
  };
4313
- }, [pi]);
4314
- return friends;
4315
- }
4316
- async function createShared(context, title, friends, agents) {
4317
- const { pi } = context;
4318
- const rooms = pi.rooms;
4319
- if (!rooms) {
4320
- throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
4390
+ return (_d = (_c = (_b = kind ? own(`${method}:${kind}`) : undefined) !== null && _b !== undefined ? _b : own(method)) !== null && _c !== undefined ? _c : own("*")) !== null && _d !== undefined ? _d : TA_UNDECLARED;
4321
4391
  }
4322
- const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
4323
- await rooms.inviteFriends(room.id, friends);
4324
- for (const agent of agents) {
4325
- await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
4326
- pi.ui.notify(ChannelViews.message(error), "error");
4392
+ TaPermissionUtil2.host = host;
4393
+ })(TaPermissionUtil || (TaPermissionUtil = {}));
4394
+ var action = (id, en, zh, tw, ja, more = {}) => ({
4395
+ id,
4396
+ area: id.split(".")[0],
4397
+ title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
4398
+ ...more
4399
+ });
4400
+ var TA_ACTIONS = [
4401
+ action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
4402
+ action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
4403
+ action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
4404
+ action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
4405
+ action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
4406
+ action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
4407
+ action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
4408
+ action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
4409
+ action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
4410
+ action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
4411
+ action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
4412
+ action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
4413
+ action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
4414
+ action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
4415
+ action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
4416
+ action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
4417
+ action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
4418
+ action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
4419
+ action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
4420
+ action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
4421
+ action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
4422
+ action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
4423
+ action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
4424
+ action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
4425
+ action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
4426
+ action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
4427
+ action("extensions.trust", "Decide how far others' extensions reach", "决定别人的扩展能用到哪一步", "決定別人的擴充功能能用到哪一步", "他の人の拡張機能に許す範囲を決める", { risky: true }),
4428
+ action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
4429
+ action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
4430
+ action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
4431
+ action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
4432
+ action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
4433
+ action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
4434
+ action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
4435
+ ];
4436
+ var TA_OWNER_ACTIONS = [
4437
+ action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
4438
+ action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true })
4439
+ ];
4440
+ var OWNER_AREAS = ["desktop"];
4441
+ var TaActionUtil;
4442
+ (function(TaActionUtil2) {
4443
+ const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
4444
+ const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
4445
+ function info(id) {
4446
+ return byId.get(id);
4447
+ }
4448
+ TaActionUtil2.info = info;
4449
+ function title(id, language) {
4450
+ var _a;
4451
+ var _b, _c;
4452
+ const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
4453
+ if (!title2) {
4454
+ return id;
4455
+ }
4456
+ return TaLanguageUtil.pick(language, {
4457
+ "zh-CN": title2["zh-CN"],
4458
+ "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
4459
+ "en-US": title2.en,
4460
+ "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
4327
4461
  });
4328
4462
  }
4329
- const { link } = await rooms.invite(room.id);
4330
- await pi.openLink?.(link);
4331
- return room.id;
4332
- }
4333
- var ROOMS_PACKAGE = "@celljs/ta-rooms";
4334
- var ROOMS_KIND = "ta-rooms";
4335
- async function becomeGroup(context, channel, friends, agents) {
4336
- const { pi } = context;
4337
- const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
4338
- const room = await createShared(context, channel.name, friends, members);
4339
- await context.service.updateChannel(channel.id, { shared: room });
4340
- pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
4341
- }
4463
+ TaActionUtil2.title = title;
4464
+ function grantable(id) {
4465
+ const info2 = byId.get(id);
4466
+ return !!info2 && !OWNER_AREAS.includes(info2.area);
4467
+ }
4468
+ TaActionUtil2.grantable = grantable;
4469
+ function inRoles(id) {
4470
+ var _a;
4471
+ return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
4472
+ }
4473
+ TaActionUtil2.inRoles = inRoles;
4474
+ function inside(dir, path) {
4475
+ const base = dir.replace(/\/+$/, "");
4476
+ return path === base || path.startsWith(`${base}/`) || base === "";
4477
+ }
4478
+ TaActionUtil2.inside = inside;
4479
+ })(TaActionUtil || (TaActionUtil = {}));
4342
4480
 
4343
- // web-src/create.tsx
4344
- var noBack = (_open, _close) => false;
4345
- var AGENT_PAGE = `${NAME}/agent`;
4346
- function newAgent(context) {
4347
- const { pi, service, ui } = context;
4348
- if (!ui.state.draft) {
4349
- const team = service.state.team;
4350
- const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
4351
- ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
4481
+ // web-src/notice-util.ts
4482
+ var NoticeUtil;
4483
+ ((NoticeUtil) => {
4484
+ const PARTS = {
4485
+ 决定: "decisions",
4486
+ decisions: "decisions",
4487
+ 约定: "conventions",
4488
+ conventions: "conventions",
4489
+ 待办: "todo",
4490
+ "to do": "todo",
4491
+ todo: "todo",
4492
+ "to-do": "todo"
4493
+ };
4494
+ function counts(text) {
4495
+ const counts2 = { decisions: 0, conventions: 0, todo: 0, done: 0 };
4496
+ let part;
4497
+ for (const line of text.split(/\r?\n/)) {
4498
+ const heading = /^\s*#{1,6}\s+(.+?)\s*#*\s*$/.exec(line) ?? /^\s*\*\*(.+?)\*\*\s*[::]?\s*$/.exec(line);
4499
+ if (heading) {
4500
+ part = PARTS[heading[1].replace(/[::]$/, "").trim().toLowerCase()];
4501
+ continue;
4502
+ }
4503
+ const item = /^\s*(?:[-*+]|\d+[.)])\s+(\[( |x|X)\]\s+)?\S/.exec(line);
4504
+ if (!part || !item) {
4505
+ continue;
4506
+ }
4507
+ if (part === "todo" && item[2] && item[2] !== " ") {
4508
+ counts2.done++;
4509
+ } else {
4510
+ counts2[part]++;
4511
+ }
4512
+ }
4513
+ return counts2;
4352
4514
  }
4353
- pi.ui.showView(AGENT_PAGE);
4354
- }
4355
- function Identity({ context, onClose }) {
4356
- const { pi, ui } = context;
4357
- const { draft } = useUi(ui);
4358
- const w = ChannelViews.words(pi);
4359
- const ref = React.useRef(null);
4360
- const name = React.useRef(null);
4361
- React.useEffect(() => name.current?.select(), []);
4362
- (pi.ui.useBackLayer ?? noBack)(true, onClose);
4363
- React.useEffect(() => {
4364
- const close = (event) => {
4365
- const target = event.target;
4366
- if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
4367
- onClose();
4515
+ NoticeUtil.counts = counts;
4516
+ function firstLine(text) {
4517
+ for (const line of text.split(/\r?\n/)) {
4518
+ const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(line);
4519
+ if (item) {
4520
+ return item[1].replace(/[*_`~]+/g, "").trim();
4368
4521
  }
4369
- };
4370
- const onKey = (event) => event.key === "Escape" && onClose();
4371
- document.addEventListener("pointerdown", close);
4372
- document.addEventListener("keydown", onKey);
4373
- return () => {
4374
- document.removeEventListener("pointerdown", close);
4375
- document.removeEventListener("keydown", onKey);
4376
- };
4377
- }, [onClose]);
4378
- if (!draft) {
4379
- return null;
4522
+ }
4523
+ return text.split(/\r?\n/).find((line) => line.trim() && !/^\s*#/.test(line))?.trim() ?? "";
4380
4524
  }
4381
- return /* @__PURE__ */ React.createElement("div", {
4382
- className: "tac-identity",
4383
- ref,
4384
- role: "dialog",
4385
- "aria-label": w.editAgent
4386
- }, /* @__PURE__ */ React.createElement("label", {
4387
- className: "tac-identity-label"
4388
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4389
- className: "tac-input",
4390
- value: draft.name,
4391
- maxLength: 40,
4392
- ref: name,
4393
- onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
4394
- onKeyDown: (event) => event.key === "Enter" && onClose()
4395
- })), /* @__PURE__ */ React.createElement("div", {
4396
- className: "tac-identity-label"
4397
- }, w.avatar), /* @__PURE__ */ React.createElement("div", {
4398
- className: "tac-faces"
4399
- }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
4400
- key: face,
4401
- type: "button",
4402
- "aria-pressed": draft.face === face,
4403
- className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
4404
- onClick: () => ui.set({ draft: { ...draft, face } })
4405
- }, /* @__PURE__ */ React.createElement(Face, {
4406
- face,
4407
- size: 30
4408
- })))));
4409
- }
4410
- function NewAgentHead({ context }) {
4411
- const { pi, ui } = context;
4412
- const { draft, editing } = useUi(ui);
4413
- const w = ChannelViews.words(pi);
4414
- const Down = ChannelViews.icon(pi, "ChevronDown");
4415
- if (!draft) {
4416
- return null;
4525
+ NoticeUtil.firstLine = firstLine;
4526
+ })(NoticeUtil ||= {});
4527
+
4528
+ // web-src/notice.tsx
4529
+ var NoticeView;
4530
+ ((NoticeView) => {
4531
+ function display(text) {
4532
+ return text.replace(/^(\s*[-*+]\s+)\[ \]\s+/gm, "$1☐ ").replace(/^(\s*[-*+]\s+)\[[xX]\]\s+/gm, "$1☑ ");
4417
4533
  }
4418
- return /* @__PURE__ */ React.createElement("div", {
4419
- className: "tac-new-head"
4420
- }, /* @__PURE__ */ React.createElement("div", {
4421
- className: "tac-new-title"
4422
- }, /* @__PURE__ */ React.createElement("button", {
4423
- type: "button",
4424
- className: "tac-new-trigger tac-identity-open",
4425
- "aria-expanded": editing,
4426
- title: w.editAgent,
4427
- onClick: () => ui.set({ editing: !editing })
4428
- }, /* @__PURE__ */ React.createElement(Face, {
4429
- face: draft.face,
4430
- size: 20
4431
- }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
4432
- size: 14
4433
- })), editing && /* @__PURE__ */ React.createElement(Identity, {
4434
- context,
4435
- onClose: () => ui.set({ editing: false })
4436
- })), /* @__PURE__ */ React.createElement("button", {
4437
- type: "button",
4438
- className: "tac-button tac-quiet",
4439
- onClick: () => {
4440
- ui.set({ draft: undefined, editing: false });
4441
- pi.ui.showView("");
4442
- }
4443
- }, w.cancel));
4444
- }
4445
- function NewAgentPage({ context }) {
4446
- const { pi, service, ui } = context;
4447
- const { draft } = useUi(ui);
4448
- const { loaded } = useChannels(service);
4449
- const w = ChannelViews.words(pi);
4450
- const Pencil = ChannelViews.icon(pi, "Pencil");
4451
- const Composer = pi.ui.Composer;
4452
- const first = React.useRef(true);
4453
- React.useEffect(() => {
4454
- if (!loaded || !first.current) {
4455
- return;
4456
- }
4457
- first.current = false;
4458
- if (!ui.state.draft) {
4459
- newAgent(context);
4534
+ NoticeView.display = display;
4535
+ function counts(text, language) {
4536
+ const w = ChannelWords.of(language);
4537
+ const counts2 = NoticeUtil.counts(text);
4538
+ if (counts2.decisions + counts2.conventions + counts2.todo === 0) {
4539
+ return NoticeUtil.firstLine(text);
4460
4540
  }
4461
- }, [loaded, ui, context]);
4462
- if (!draft) {
4463
- return null;
4541
+ const values = { decisions: String(counts2.decisions), conventions: String(counts2.conventions), todo: String(counts2.todo) };
4542
+ return ChannelWords.format(w.noticeCounts, values).split(" · ").filter((_, at) => [counts2.decisions, counts2.conventions, counts2.todo][at] > 0).join(" · ");
4464
4543
  }
4465
- const send = async (text) => {
4466
- const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
4467
- ui.set({ draft: undefined, editing: false });
4468
- try {
4469
- const sessionId = await service.openAgent(agent.id);
4470
- context.sessions.set(agent.id, sessionId);
4471
- await pi.switchSession(sessionId);
4472
- await pi.sendUserMessage(text);
4473
- } catch (error) {
4474
- pi.ui.notify(ChannelViews.message(error), "error");
4475
- }
4476
- };
4477
- return /* @__PURE__ */ React.createElement("div", {
4478
- className: "tac-new-page"
4479
- }, /* @__PURE__ */ React.createElement("div", {
4480
- className: "tac-new-col"
4481
- }, /* @__PURE__ */ React.createElement(Face, {
4482
- face: draft.face,
4483
- size: 88
4484
- }), /* @__PURE__ */ React.createElement("h2", {
4485
- className: "tac-new-name"
4486
- }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
4487
- type: "button",
4488
- className: "tac-action tac-identity-open",
4489
- title: w.editAgent,
4490
- "aria-label": w.editAgent,
4491
- onClick: () => ui.set({ editing: !ui.state.editing })
4492
- }, /* @__PURE__ */ React.createElement(Pencil, {
4493
- size: 14
4494
- }))), /* @__PURE__ */ React.createElement("p", {
4495
- className: "tac-new-hint"
4496
- }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
4497
- className: "tac-new-box"
4498
- }, /* @__PURE__ */ React.createElement(Composer, {
4499
- placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
4500
- onSend: send,
4501
- cwd: draft.cwd,
4502
- onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
4503
- draft: "new-agent"
4504
- }))));
4505
- }
4506
- function NewChannelDialog({ context, onClose }) {
4544
+ NoticeView.counts = counts;
4545
+ })(NoticeView ||= {});
4546
+ function NoticeBar({
4547
+ context,
4548
+ channel,
4549
+ state,
4550
+ onState
4551
+ }) {
4507
4552
  const { pi, service } = context;
4508
4553
  const { team } = useChannels(service);
4509
- const faces = useFaces(team);
4510
4554
  const w = ChannelViews.words(pi);
4511
- const Search = ChannelViews.icon(pi, "Search");
4512
- const Check = ChannelViews.icon(pi, "Check");
4513
- const [name, setName] = React.useState("");
4514
- const [query, setQuery] = React.useState("");
4515
- const [picked, setPicked] = React.useState([]);
4516
- const friends = useFriends(pi);
4517
- const [pickedFriends, setPickedFriends] = React.useState([]);
4518
- const shared = pickedFriends.length > 0;
4519
- const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
4555
+ const notice = channel.notice;
4556
+ const [draft, setDraft] = React.useState("");
4520
4557
  const [busy, setBusy] = React.useState(false);
4521
4558
  const [error, setError] = React.useState();
4522
- const Dialog = pi.ui.Dialog;
4523
- const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
4524
- const full = picked.length >= MAX_MEMBERS;
4525
- const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
4526
- const create = (event) => {
4559
+ React.useEffect(() => {
4560
+ if (state.editing) {
4561
+ setDraft(notice?.text ?? w.noticeTemplate);
4562
+ setError(undefined);
4563
+ }
4564
+ }, [state.editing]);
4565
+ if (!notice && !state.editing) {
4566
+ return null;
4567
+ }
4568
+ const Megaphone = ChannelViews.icon(pi, "Megaphone");
4569
+ const Chevron = ChannelViews.icon(pi, "ChevronDown");
4570
+ const Markdown = pi.ui.Markdown;
4571
+ const save = (event) => {
4527
4572
  event.preventDefault();
4528
4573
  setBusy(true);
4529
4574
  setError(undefined);
4530
- if (shared) {
4531
- createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
4532
- setBusy(false);
4533
- setError(ChannelViews.message(failure));
4534
- });
4535
- return;
4536
- }
4537
- service.createChannel({ name, members: picked }).then((channel) => {
4538
- onClose();
4539
- context.showChannel(channel.id);
4575
+ service.setNotice(channel.id, draft).then(() => {
4576
+ setBusy(false);
4577
+ onState({ open: true, editing: false });
4540
4578
  }, (failure) => {
4541
4579
  setBusy(false);
4542
4580
  setError(ChannelViews.message(failure));
4543
4581
  });
4544
4582
  };
4545
- return /* @__PURE__ */ React.createElement(Dialog, {
4546
- title: w.newChannel,
4547
- onClose
4548
- }, /* @__PURE__ */ React.createElement("form", {
4549
- className: "tac-dialog",
4550
- onSubmit: create
4551
- }, /* @__PURE__ */ React.createElement("label", {
4552
- className: "tac-dialog-label"
4553
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4554
- className: "tac-input tac-dialog-input",
4555
- value: name,
4556
- placeholder: w.channelNamePlaceholder,
4557
- maxLength: 40,
4558
- autoFocus: true,
4559
- onChange: (event) => setName(event.target.value)
4560
- })), /* @__PURE__ */ React.createElement("div", {
4561
- className: "tac-dialog-label"
4562
- }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
4563
- className: "tac-dialog-count"
4564
- }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
4565
- className: "tac-dialog-search"
4566
- }, /* @__PURE__ */ React.createElement(Search, {
4583
+ const open = state.open || state.editing;
4584
+ return /* @__PURE__ */ React.createElement("div", {
4585
+ className: "tac-notice-bar",
4586
+ "data-open": open ? "" : undefined
4587
+ }, /* @__PURE__ */ React.createElement("button", {
4588
+ type: "button",
4589
+ className: "tac-notice-head",
4590
+ "aria-expanded": open,
4591
+ title: open ? w.noticeHide : w.noticeShow,
4592
+ onClick: () => onState({ open: !open, editing: false })
4593
+ }, /* @__PURE__ */ React.createElement("span", {
4594
+ className: "tac-notice-icon"
4595
+ }, /* @__PURE__ */ React.createElement(Megaphone, {
4596
+ size: 13,
4597
+ strokeWidth: 2
4598
+ })), /* @__PURE__ */ React.createElement("strong", null, w.notice), /* @__PURE__ */ React.createElement("span", {
4599
+ className: "tac-notice-sum"
4600
+ }, notice ? NoticeView.counts(notice.text, pi.ui.language) : w.noticeEmpty), /* @__PURE__ */ React.createElement("span", {
4601
+ className: "tac-notice-chevron"
4602
+ }, /* @__PURE__ */ React.createElement(Chevron, {
4567
4603
  size: 15
4568
- }), /* @__PURE__ */ React.createElement("input", {
4569
- value: query,
4570
- placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
4571
- "aria-label": w.search,
4572
- onChange: (event) => setQuery(event.target.value)
4604
+ }))), open && !state.editing && notice && /* @__PURE__ */ React.createElement("div", {
4605
+ className: "tac-notice-body"
4606
+ }, /* @__PURE__ */ React.createElement("div", {
4607
+ className: "tac-notice-text"
4608
+ }, /* @__PURE__ */ React.createElement(Markdown, {
4609
+ text: NoticeView.display(notice.text)
4573
4610
  })), /* @__PURE__ */ React.createElement("div", {
4574
- className: "tac-pick-list"
4575
- }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4576
- compact: true,
4577
- title: w.noAgents,
4578
- hint: w.noAgentsHint
4579
- }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4580
- compact: true,
4581
- title: w.noMatch
4582
- }), shown.map((agent) => {
4583
- const on = picked.includes(agent.id);
4584
- return /* @__PURE__ */ React.createElement("button", {
4585
- key: agent.id,
4586
- type: "button",
4587
- "aria-pressed": on,
4588
- disabled: !on && full,
4589
- className: `tac-pick${on ? " tac-on" : ""}`,
4590
- onClick: () => toggle(agent)
4591
- }, /* @__PURE__ */ React.createElement("span", {
4592
- className: "tac-check"
4593
- }, on && /* @__PURE__ */ React.createElement(Check, {
4594
- size: 13,
4595
- strokeWidth: 3
4596
- })), /* @__PURE__ */ React.createElement(AgentAvatar, {
4597
- agent,
4598
- faces,
4599
- size: 30
4600
- }), /* @__PURE__ */ React.createElement("span", {
4601
- className: "tac-pick-text"
4602
- }, /* @__PURE__ */ React.createElement("span", {
4603
- className: "tac-pick-name"
4604
- }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
4605
- className: "tac-msg-lead"
4606
- }, w.lead)), /* @__PURE__ */ React.createElement("span", {
4607
- className: "tac-pick-role"
4608
- }, agent.role.split(`
4609
- `)[0])));
4610
- })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
4611
- className: "tac-dialog-label"
4612
- }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
4613
- className: "tac-dialog-count"
4614
- }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
4615
- className: "tac-pick-list"
4616
- }, friends.map((friend) => {
4617
- const on = pickedFriends.includes(friend.id);
4618
- return /* @__PURE__ */ React.createElement("button", {
4619
- key: friend.id,
4620
- type: "button",
4621
- "aria-pressed": on,
4622
- className: `tac-pick${on ? " tac-on" : ""}`,
4623
- onClick: () => toggleFriend(friend)
4624
- }, /* @__PURE__ */ React.createElement("span", {
4625
- className: "tac-check"
4626
- }, on && /* @__PURE__ */ React.createElement(Check, {
4627
- size: 13,
4628
- strokeWidth: 3
4629
- })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
4630
- seed: friend.id,
4631
- size: 30,
4632
- look: friend.look
4633
- }) : /* @__PURE__ */ React.createElement("span", {
4634
- className: "tac-pick-face"
4635
- }), /* @__PURE__ */ React.createElement("span", {
4636
- className: "tac-pick-text"
4637
- }, /* @__PURE__ */ React.createElement("span", {
4638
- className: "tac-pick-name"
4639
- }, friend.name), /* @__PURE__ */ React.createElement("span", {
4640
- className: "tac-pick-role"
4641
- }, w.friend)));
4642
- }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
4611
+ className: "tac-notice-foot"
4612
+ }, /* @__PURE__ */ React.createElement("span", null, ChannelWords.format(w.noticeBy, {
4613
+ name: ChannelsText.authorName(team, notice.by, { user: w.you, ta: w.ta }),
4614
+ time: SidebarUtil.time(notice.at, pi.ui.language)
4615
+ })), /* @__PURE__ */ React.createElement("button", {
4616
+ type: "button",
4617
+ className: "tac-button tac-quiet",
4618
+ onClick: () => onState({ open: true, editing: true })
4619
+ }, w.noticeEdit))), state.editing && /* @__PURE__ */ React.createElement("form", {
4620
+ className: "tac-notice-body tac-notice-form",
4621
+ onSubmit: save
4622
+ }, /* @__PURE__ */ React.createElement("p", {
4643
4623
  className: "tac-dialog-note"
4644
- }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
4645
- className: "tac-empty tac-error"
4624
+ }, w.noticeHint), /* @__PURE__ */ React.createElement("textarea", {
4625
+ className: "tac-input tac-notice-input",
4626
+ value: draft,
4627
+ "aria-label": w.noticeEdit,
4628
+ autoFocus: true,
4629
+ onChange: (event) => setDraft(event.target.value)
4630
+ }), error && /* @__PURE__ */ React.createElement("div", {
4631
+ className: "tac-error"
4646
4632
  }, error), /* @__PURE__ */ React.createElement("div", {
4647
- className: "tac-dialog-actions"
4633
+ className: "tac-notice-actions"
4648
4634
  }, /* @__PURE__ */ React.createElement("button", {
4635
+ type: "button",
4636
+ className: "tac-button tac-quiet",
4637
+ onClick: () => onState({ open: !!notice, editing: false })
4638
+ }, w.cancel), /* @__PURE__ */ React.createElement("button", {
4649
4639
  type: "submit",
4650
4640
  className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4651
- disabled: busy || !name.trim() || picked.length === 0 && !shared
4652
- }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
4641
+ disabled: busy || draft.trim() === (notice?.text ?? "")
4642
+ }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
4653
4643
  className: "ta-spinner ta-busy-mark ta-on-brand"
4654
4644
  })))));
4655
4645
  }
4656
4646
 
4657
- // web-src/handoff.ts
4658
- var HandOff;
4659
- ((HandOff) => {
4660
- HandOff.TOOL = "hand_off";
4661
- HandOff.CARD = "ta-channels-handoff";
4662
- HandOff.BLOCK = "ta-handoff";
4663
- const MARK = /\[ta-handoff:([^\]\s]+)\]/;
4664
- HandOff.DEFINITION = {
4665
- name: HandOff.TOOL,
4666
- label: "Hand off",
4667
- 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.",
4668
- promptSnippet: "Hand the work over to one of the user's agents or channels",
4669
- parameters: {
4670
- type: "object",
4671
- properties: {
4672
- to: { type: "string", description: "@name of an agent or #name of a channel." },
4673
- brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
4674
- },
4675
- required: ["to", "brief"]
4676
- }
4677
- };
4678
- function ref(target) {
4679
- return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
4680
- }
4681
- HandOff.ref = ref;
4682
- function ask(language, to) {
4683
- const fence = "```";
4684
- const context = [
4685
- `[ta-handoff:${to}]`,
4686
- `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
4687
- `- 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.`,
4688
- `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
4689
- `- 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):`,
4690
- `${fence}${HandOff.BLOCK}`,
4691
- "<the brief>",
4692
- fence,
4693
- `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
4694
- ].join(`
4695
- `);
4696
- const line = TaLanguageUtil.pick(language, {
4697
- "zh-CN": `把这件事交给 ${to}`,
4698
- "zh-TW": `把這件事交給 ${to}`,
4699
- "en-US": `Hand this over to ${to}`,
4700
- "ja-JP": `これを ${to} に引き継ぐ`
4701
- });
4702
- return TaMessageContext.wrap(context, line);
4703
- }
4704
- HandOff.ask = ask;
4705
- function asked(text) {
4706
- return MARK.exec(text)?.[1];
4707
- }
4708
- HandOff.asked = asked;
4709
- function find(text) {
4710
- const lines = text.split(/\r?\n/);
4711
- let found;
4712
- for (let index = 0;index < lines.length; index++) {
4713
- const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
4714
- if (open?.[2] !== HandOff.BLOCK) {
4715
- continue;
4716
- }
4717
- const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
4718
- const end = lines.findIndex((line, at) => at > index && close.test(line));
4719
- found = lines.slice(index + 1, end < 0 ? lines.length : end);
4720
- index = end < 0 ? lines.length : end;
4721
- }
4722
- const brief = found?.join(`
4723
- `).trim();
4724
- return brief || undefined;
4725
- }
4726
- HandOff.find = find;
4727
- function message(origin, brief, language) {
4728
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4729
- const head = TaLanguageUtil.pick(language, {
4730
- "zh-CN": `(交接自“${title}”)`,
4731
- "zh-TW": `(交接自「${title}」)`,
4732
- "en-US": `(Handed over from “${title}”)`,
4733
- "ja-JP": `(“${title}” から引き継ぎました)`
4647
+ // web-src/room.tsx
4648
+ var RUN_MS = 5 * 60 * 1000;
4649
+ var PAUSE_MS = 15 * 60 * 1000;
4650
+ var RoomUtil;
4651
+ ((RoomUtil) => {
4652
+ function rows(messages) {
4653
+ return messages.map((message, index) => {
4654
+ const before = messages[index - 1];
4655
+ const separator = !before || message.at - before.at > PAUSE_MS;
4656
+ const first = separator || before.author !== message.author || before.by !== message.by || before.author === SYSTEM || !!before.notice || message.at - before.at > RUN_MS;
4657
+ return { message, first, separator };
4734
4658
  });
4735
- const context = [
4736
- "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.",
4737
- 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.` : ""
4738
- ].filter(Boolean).join(`
4739
- `);
4740
- return TaMessageContext.wrap(context, `${head}
4741
-
4742
- ${brief.trim()}`);
4743
- }
4744
- HandOff.message = message;
4745
- function channelText(origin, brief, language) {
4746
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4747
- return `${TaLanguageUtil.pick(language, {
4748
- "zh-CN": `(交接自“${title}”)`,
4749
- "zh-TW": `(交接自「${title}」)`,
4750
- "en-US": `(Handed over from “${title}”)`,
4751
- "ja-JP": `(“${title}” から引き継ぎました)`
4752
- })}
4753
-
4754
- ${brief.trim()}`;
4755
- }
4756
- HandOff.channelText = channelText;
4757
- function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
4758
- return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
4759
4659
  }
4760
- HandOff.serverLanguage = serverLanguage;
4761
- function result(target) {
4762
- 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.`;
4660
+ RoomUtil.rows = rows;
4661
+ function choice(agent, text) {
4662
+ return `@${agent.name} ${TaMessageContext.strip(text)}`;
4763
4663
  }
4764
- HandOff.result = result;
4765
- })(HandOff ||= {});
4766
-
4767
- // web-src/handoff-view.tsx
4768
- var HandOffViewUtil;
4769
- ((HandOffViewUtil) => {
4770
- function members(team, target) {
4771
- if (target.kind === "agent") {
4772
- const agent = team.agents.find((candidate) => candidate.id === target.id);
4773
- return agent ? [agent] : [];
4664
+ RoomUtil.choice = choice;
4665
+ function answer(messages, message, agent) {
4666
+ const said = messages.slice(messages.indexOf(message) + 1).find((later) => later.author === USER && !later.notice);
4667
+ if (!said) {
4668
+ return;
4774
4669
  }
4775
- const channel = team.channels.find((candidate) => candidate.id === target.id);
4776
- return channel ? membersOf(team, channel) : [];
4670
+ const named = `@${agent.name} `;
4671
+ return said.text.startsWith(named) ? said.text.slice(named.length) : said.text;
4777
4672
  }
4778
- HandOffViewUtil.members = members;
4779
- })(HandOffViewUtil ||= {});
4780
- function useTeam(context) {
4781
- return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
4673
+ RoomUtil.answer = answer;
4674
+ })(RoomUtil ||= {});
4675
+ function AgentText({ context, channelId, agent, text, answer }) {
4676
+ const { pi, service } = context;
4677
+ const send = React.useCallback((said) => service.post(channelId, RoomUtil.choice(agent, said)), [service, channelId, agent.name]);
4678
+ return /* @__PURE__ */ React.createElement(pi.ui.Markdown, {
4679
+ text,
4680
+ send,
4681
+ answer
4682
+ });
4782
4683
  }
4783
- function HandOffCard({ context, message }) {
4784
- const card = message.details;
4785
- const team = useTeam(context);
4786
- const faces = useFaces(team);
4787
- if (!card?.target) {
4684
+ function MessagePictures({ context, channelId, message, alt }) {
4685
+ const { pi, service } = context;
4686
+ const images = message.images ?? [];
4687
+ const [sources, setSources] = React.useState({});
4688
+ const ids = images.map((image) => image.id).join(",");
4689
+ React.useEffect(() => {
4690
+ let live = true;
4691
+ for (const id of ids ? ids.split(",") : []) {
4692
+ service.picture(channelId, id).then((data) => live && data && setSources((current) => ({ ...current, [id]: data })));
4693
+ }
4694
+ return () => {
4695
+ live = false;
4696
+ };
4697
+ }, [service, channelId, ids]);
4698
+ const ChatImages = pi.ui.ChatImages;
4699
+ if (!images.length || !ChatImages) {
4788
4700
  return null;
4789
4701
  }
4790
- const w = ChannelViews.words(context.pi);
4791
- const members = HandOffViewUtil.members(team, card.target);
4792
- 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);
4793
4702
  return /* @__PURE__ */ React.createElement("div", {
4794
- className: "tac-handoff"
4795
- }, /* @__PURE__ */ React.createElement("div", {
4796
- className: "tac-handoff-head"
4797
- }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
4798
- members,
4799
- faces,
4800
- size: 20,
4801
- working: []
4802
- }), /* @__PURE__ */ React.createElement("span", {
4803
- className: "tac-handoff-title"
4804
- }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
4805
- type: "button",
4806
- className: "tac-link",
4807
- onClick: open
4808
- }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
4809
- className: "tac-handoff-brief"
4810
- }, card.brief));
4703
+ className: "tac-pics"
4704
+ }, /* @__PURE__ */ React.createElement(ChatImages, {
4705
+ alt,
4706
+ images: images.map((image) => ({ key: image.id, src: sources[image.id], width: image.w, height: image.h }))
4707
+ }));
4811
4708
  }
4812
- var HandOffView;
4813
- ((HandOffView) => {
4814
- function card(context) {
4815
- return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
4816
- context,
4817
- message
4818
- });
4819
- }
4820
- HandOffView.card = card;
4821
- function icon(context, target, icons) {
4822
- const key = `${target.kind}:${target.id}`;
4823
- let node2 = icons.get(key);
4824
- if (!node2) {
4825
- const Face2 = () => {
4826
- const team = useTeam(context);
4827
- const faces = useFaces(team);
4828
- const members = HandOffViewUtil.members(team, target);
4829
- return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
4830
- members,
4831
- faces,
4832
- size: 16,
4833
- working: []
4834
- }) : null;
4835
- };
4836
- node2 = /* @__PURE__ */ React.createElement(Face2, null);
4837
- icons.set(key, node2);
4709
+ function Mentions({ text, agents }) {
4710
+ const names = new Set(agents.map((agent) => agent.name.toLowerCase()));
4711
+ const parts = text.split(/(@[^\s@#,,。::]+)/);
4712
+ return /* @__PURE__ */ React.createElement("span", null, parts.map((part, index) => part.startsWith("@") && names.has(part.slice(1).toLowerCase()) ? /* @__PURE__ */ React.createElement("span", {
4713
+ key: index,
4714
+ className: "tac-mention"
4715
+ }, part) : part));
4716
+ }
4717
+ function StopLine({
4718
+ context,
4719
+ channel,
4720
+ message,
4721
+ later,
4722
+ agents
4723
+ }) {
4724
+ const { pi, service } = context;
4725
+ const w = ChannelViews.words(pi);
4726
+ const [busy, setBusy] = React.useState(false);
4727
+ const stop = message.stop;
4728
+ const lead = agents.find((agent) => agent.id === channel.members.find((id) => !(channel.muted ?? []).includes(id)));
4729
+ const replies = String(stop?.replies ?? 0);
4730
+ const tokens = stop?.tokens ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(stop.tokens) : "";
4731
+ const stats = stop ? ChannelWords.format(tokens ? w.stoppedStats : w.stoppedReplies, { replies, tokens }) : "";
4732
+ const resumed = stop?.resumed === "continue" ? w.wentOn : stop?.resumed === "wrapUp" ? w.summedUp : "";
4733
+ const why = stop?.daily === "all" ? w.dailyAll : stop?.daily === "channel" ? w.dailyChannel : stop?.idle === "repeat" ? w.idleRepeat : stop?.idle === "agree" ? w.idleAgree : stop?.idle === "pingPong" ? w.idlePingPong : w.stopped;
4734
+ const extended = stop?.extended ? w.extendedOnce : "";
4735
+ const go = (how) => {
4736
+ setBusy(true);
4737
+ service.resumeRound(channel.id, message.id, how).catch((error) => pi.ui.notify(ChannelViews.message(error), "error")).finally(() => setBusy(false));
4738
+ };
4739
+ const open = !!stop?.pending.length && !stop.resumed && !later;
4740
+ return /* @__PURE__ */ React.createElement("div", {
4741
+ className: "tac-stop",
4742
+ role: "note"
4743
+ }, /* @__PURE__ */ React.createElement("div", {
4744
+ className: "tac-notice"
4745
+ }, why), /* @__PURE__ */ React.createElement("div", {
4746
+ className: "tac-stop-meta"
4747
+ }, [stats, extended, resumed].filter(Boolean).join(" · ")), open && /* @__PURE__ */ React.createElement("div", {
4748
+ className: "tac-stop-actions"
4749
+ }, /* @__PURE__ */ React.createElement("button", {
4750
+ type: "button",
4751
+ className: "tac-stop-button",
4752
+ disabled: busy,
4753
+ onClick: () => go("continue")
4754
+ }, w.keepGoing), lead && /* @__PURE__ */ React.createElement("button", {
4755
+ type: "button",
4756
+ className: "tac-stop-button",
4757
+ disabled: busy,
4758
+ onClick: () => go("wrapUp")
4759
+ }, ChannelWords.format(w.wrapUp, { name: `@${lead.name}` }))));
4760
+ }
4761
+ function ChannelHead({ context }) {
4762
+ const { pi, service, ui } = context;
4763
+ const state = useChannels(service);
4764
+ const { channelId } = useUi(ui);
4765
+ const faces = useFaces(state.team);
4766
+ const w = ChannelViews.words(pi);
4767
+ const shown = !!pi.ui.useView(MEMBERS_VIEW)?.shown;
4768
+ const roomInfo = !!pi.ui.useView(ROOM_INFO_VIEW)?.shown;
4769
+ const follow = React.useRef(roomInfo);
4770
+ follow.current = roomInfo;
4771
+ React.useEffect(() => {
4772
+ if (channelId && follow.current) {
4773
+ context.showMembers();
4838
4774
  }
4839
- return node2;
4775
+ }, [channelId, context]);
4776
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
4777
+ if (!channel) {
4778
+ return null;
4840
4779
  }
4841
- function composerAddon(context) {
4842
- const icons = new Map;
4843
- const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
4844
- clientMessageId: ChannelsUtil.newId("handoff-ask"),
4845
- message: HandOff.ask(context.pi.ui.language, to),
4846
- streamingBehavior: "followUp"
4847
- }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
4848
- return {
4849
- actions: (conversation) => {
4850
- const { team } = context.service.state;
4851
- if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
4852
- return [];
4853
- }
4854
- const w = ChannelViews.words(context.pi);
4855
- const Forward = ChannelViews.icon(context.pi, "Forward");
4856
- const agents = team.agents.filter((agent) => !agent.temporary).map((agent) => ({
4857
- key: `handoff:agent:${agent.id}`,
4858
- label: agent.name,
4859
- detail: agent.role.split(`
4860
- `)[0],
4861
- group: w.agents,
4862
- icon: icon(context, { kind: "agent", id: agent.id }, icons),
4863
- run: () => send(conversation, `@${agent.name}`)
4864
- }));
4865
- const channels = team.channels.map((channel) => ({
4866
- key: `handoff:channel:${channel.id}`,
4867
- label: `#${channel.name}`,
4868
- detail: channel.topic,
4869
- group: w.channels,
4870
- icon: icon(context, { kind: "channel", id: channel.id }, icons),
4871
- run: () => send(conversation, `#${channel.name}`)
4872
- }));
4873
- return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
4874
- size: 16
4875
- }), items: [...agents, ...channels] }];
4876
- },
4877
- subscribe: (listener) => context.service.subscribe(listener)
4878
- };
4780
+ const members = membersOf(state.team, channel);
4781
+ const working = state.working[channel.id] ?? [];
4782
+ return /* @__PURE__ */ React.createElement("div", {
4783
+ className: "tac-head"
4784
+ }, /* @__PURE__ */ React.createElement("div", {
4785
+ className: "tac-head-title"
4786
+ }, /* @__PURE__ */ React.createElement("strong", null, channel.name), /* @__PURE__ */ React.createElement("span", {
4787
+ className: "tac-head-count"
4788
+ }, ChannelWords.format(w.memberCount, { count: String(members.length) })), channel.topic && /* @__PURE__ */ React.createElement("span", {
4789
+ className: "tac-head-topic"
4790
+ }, channel.topic)), /* @__PURE__ */ React.createElement("button", {
4791
+ type: "button",
4792
+ className: `tac-head-members${shown ? " tac-on" : ""}`,
4793
+ title: w.showMembers,
4794
+ "aria-label": w.showMembers,
4795
+ "aria-pressed": shown,
4796
+ onClick: () => context.showMembers()
4797
+ }, members.slice(0, 5).map((agent) => /* @__PURE__ */ React.createElement("span", {
4798
+ key: agent.id,
4799
+ className: "tac-head-face"
4800
+ }, /* @__PURE__ */ React.createElement(AgentAvatar, {
4801
+ agent,
4802
+ faces,
4803
+ size: 24,
4804
+ working: working.includes(agent.id)
4805
+ }))), members.length > 5 && /* @__PURE__ */ React.createElement("span", {
4806
+ className: "tac-head-more"
4807
+ }, "+", members.length - 5)));
4808
+ }
4809
+ function ChannelSceneHead({ context, channelId }) {
4810
+ const { pi, service } = context;
4811
+ const state = useChannels(service);
4812
+ const faces = useFaces(state.team);
4813
+ const w = ChannelViews.words(pi);
4814
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
4815
+ if (!channel) {
4816
+ return null;
4879
4817
  }
4880
- HandOffView.composerAddon = composerAddon;
4881
- })(HandOffView ||= {});
4882
-
4883
- // web-src/round-rules.ts
4884
- var ChannelRounds;
4885
- ((ChannelRounds) => {
4886
- const SHORT = 20;
4887
- const MIN_PAIRS = 8;
4888
- const ALIKE = 0.8;
4889
- const PING_PONG = 4;
4890
- const NEW = 0.35;
4891
- const CHANGES = new Set(["edit", "write", "delete", "move"]);
4892
- function scale(watchedAt, pages, now) {
4893
- if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
4894
- return 2;
4818
+ const members = membersOf(state.team, channel);
4819
+ const working = state.working[channel.id] ?? [];
4820
+ const External = ChannelViews.icon(pi, "ExternalLink");
4821
+ return /* @__PURE__ */ React.createElement("div", {
4822
+ className: "tac-scene-head"
4823
+ }, /* @__PURE__ */ React.createElement(RoomFace, {
4824
+ members,
4825
+ faces,
4826
+ size: 26,
4827
+ working
4828
+ }), /* @__PURE__ */ React.createElement("div", {
4829
+ className: "tac-scene-title"
4830
+ }, /* @__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("button", {
4831
+ type: "button",
4832
+ className: "tac-button tac-scene-main",
4833
+ title: w.openInMainHint,
4834
+ onClick: () => context.showChannel(channel.id)
4835
+ }, /* @__PURE__ */ React.createElement(External, {
4836
+ size: 13
4837
+ }), w.openInMain));
4838
+ }
4839
+ var mePromise;
4840
+ function useMe(pi) {
4841
+ const [me, setMe] = React.useState(TA_OWNER);
4842
+ React.useEffect(() => {
4843
+ mePromise ??= pi.server.getServerInfo().then((info) => info.member?.id ?? TA_OWNER, () => TA_OWNER);
4844
+ let live = true;
4845
+ mePromise.then((id) => live && setMe(id));
4846
+ return () => {
4847
+ live = false;
4848
+ };
4849
+ }, [pi]);
4850
+ return me;
4851
+ }
4852
+ function ChannelRoom({ context, channelId: fixed }) {
4853
+ const { pi, service, ui } = context;
4854
+ const me = useMe(pi);
4855
+ const state = useChannels(service);
4856
+ const shown = useUi(ui).channelId;
4857
+ const channelId = fixed ?? shown;
4858
+ const faces = useFaces(state.team);
4859
+ const w = ChannelViews.words(pi);
4860
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
4861
+ const messages = channel ? state.messages[channel.id] : undefined;
4862
+ const working = channel ? state.working[channel.id] ?? [] : [];
4863
+ React.useEffect(() => {
4864
+ if (channelId) {
4865
+ service.messages(channelId);
4895
4866
  }
4896
- return pages === undefined || pages > 0 ? 1 : 0.5;
4897
- }
4898
- ChannelRounds.scale = scale;
4899
- function idle(said, progress) {
4900
- const last = said.at(-1);
4901
- if (!last) {
4867
+ }, [service, channelId]);
4868
+ const page = pi.ui.useView(CHANNEL_PAGE);
4869
+ const inFront = !!channelId && (!!fixed || !!page?.shown);
4870
+ const lastAt = ChannelSeenUtil.lastAt(messages);
4871
+ const resting = working.length === 0;
4872
+ React.useEffect(() => {
4873
+ if (!channelId || !inFront || !resting) {
4902
4874
  return;
4903
4875
  }
4904
- const pairs = said.map((item) => pairsOf(item.text));
4905
- const mine = pairs[pairs.length - 1];
4906
- if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
4907
- return "repeat";
4908
- }
4909
- const recent = said.slice(-3);
4910
- if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
4911
- return "agree";
4876
+ const look = () => document.visibilityState === "visible" && context.seen.look(channelId, Math.max(Date.now(), lastAt ?? 0));
4877
+ look();
4878
+ document.addEventListener("visibilitychange", look);
4879
+ return () => document.removeEventListener("visibilitychange", look);
4880
+ }, [context, channelId, inFront, resting, lastAt]);
4881
+ React.useEffect(() => {
4882
+ if (!channelId) {
4883
+ return;
4912
4884
  }
4913
- const run = said.slice(-PING_PONG);
4914
- const authors = new Set(run.map((item) => item.author));
4915
- const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
4916
- const start = said.length - PING_PONG;
4917
- if (progress || start <= 0 || authors.size !== 2 || !alternate) {
4885
+ const watch = () => document.visibilityState === "visible" && void service.watch(channelId).catch(() => {
4918
4886
  return;
4919
- }
4920
- const seen = new Set(pairs.slice(0, start).flat());
4921
- for (const own of pairs.slice(start)) {
4922
- const fresh = own.filter((pair) => !seen.has(pair)).length;
4923
- if (own.length === 0 || fresh / own.length >= NEW) {
4924
- return;
4925
- }
4926
- for (const pair of own) {
4927
- seen.add(pair);
4928
- }
4929
- }
4930
- return "pingPong";
4887
+ });
4888
+ watch();
4889
+ const timer = setInterval(watch, WATCH_MS);
4890
+ document.addEventListener("visibilitychange", watch);
4891
+ return () => {
4892
+ clearInterval(timer);
4893
+ document.removeEventListener("visibilitychange", watch);
4894
+ };
4895
+ }, [service, channelId]);
4896
+ const sent = React.useMemo(() => messages?.filter((message) => message.author === USER).length ?? 0, [messages]);
4897
+ const list = pi.ui.useChatScroll(sent, channelId);
4898
+ const [notice, setNotice] = React.useState({ open: false, editing: false });
4899
+ React.useEffect(() => setNotice({ open: false, editing: false }), [channelId]);
4900
+ const Markdown = pi.ui.Markdown;
4901
+ const Composer = pi.ui.Composer;
4902
+ const Avatar = pi.ui.Avatar;
4903
+ if (!channel) {
4904
+ return /* @__PURE__ */ React.createElement("div", {
4905
+ className: "tac-room-page"
4906
+ }, state.loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4907
+ title: w.pick
4908
+ }));
4931
4909
  }
4932
- ChannelRounds.idle = idle;
4933
- function day(now) {
4934
- const date = new Date(now);
4935
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
4910
+ const members = membersOf(state.team, channel);
4911
+ const agentOf = (id) => state.team.agents.find((agent) => agent.id === id);
4912
+ const reply = ChannelsText.replyOf(channel);
4913
+ const lead = members.find((agent) => !(channel.muted ?? []).includes(agent.id));
4914
+ const placeholder = reply === "all" ? w.placeholderAll : reply === "lead" && lead ? w.placeholderLead : w.placeholder;
4915
+ const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
4916
+ const time = (at) => SidebarUtil.time(at, pi.ui.language);
4917
+ return /* @__PURE__ */ React.createElement("div", {
4918
+ className: "tac-room-page"
4919
+ }, /* @__PURE__ */ React.createElement(NoticeBar, {
4920
+ context,
4921
+ channel,
4922
+ state: notice,
4923
+ onState: setNotice
4924
+ }), /* @__PURE__ */ React.createElement("div", {
4925
+ className: "tac-chat ta-conversation",
4926
+ ref: list
4927
+ }, /* @__PURE__ */ React.createElement("div", {
4928
+ className: "tac-chat-col"
4929
+ }, messages && messages.length === 0 && /* @__PURE__ */ React.createElement("div", {
4930
+ className: "tac-chat-empty"
4931
+ }, /* @__PURE__ */ React.createElement(RoomFace, {
4932
+ members,
4933
+ faces,
4934
+ size: 56,
4935
+ working
4936
+ }), /* @__PURE__ */ React.createElement("strong", null, channel.name), channel.topic && /* @__PURE__ */ React.createElement("span", null, channel.topic), /* @__PURE__ */ React.createElement("span", {
4937
+ className: "tac-chat-hint"
4938
+ }, w.quiet)), messages && RoomUtil.rows(messages).map(({ message, first, separator }) => /* @__PURE__ */ React.createElement(React.Fragment, {
4939
+ key: message.id
4940
+ }, separator && /* @__PURE__ */ React.createElement("div", {
4941
+ className: "tac-chat-time"
4942
+ }, time(message.at)), message.author === SYSTEM ? /* @__PURE__ */ React.createElement(StopLine, {
4943
+ context,
4944
+ channel,
4945
+ message,
4946
+ agents: state.team.agents,
4947
+ later: messages.some((other) => other.at > message.at && (other.author === USER || other.author === TA))
4948
+ }) : message.notice ? /* @__PURE__ */ React.createElement("button", {
4949
+ type: "button",
4950
+ className: "tac-notice tac-notice-line",
4951
+ disabled: !channel.notice,
4952
+ onClick: () => setNotice({ open: true, editing: false })
4953
+ }, ChannelWords.format(message.notice === "cleared" ? w.noticeCleared : w.noticeUpdated, { name: name(message.author) })) : message.author === USER && (message.by ?? TA_OWNER) !== me ? /* @__PURE__ */ React.createElement("div", {
4954
+ className: `tac-msg${first ? " tac-first" : ""}`
4955
+ }, /* @__PURE__ */ React.createElement("div", {
4956
+ className: "tac-msg-face"
4957
+ }, first && pi.ui.Face && /* @__PURE__ */ React.createElement(pi.ui.Face, {
4958
+ seed: message.by ?? TA_OWNER,
4959
+ double: (message.by ?? TA_OWNER) === TA_OWNER,
4960
+ size: 28
4961
+ })), /* @__PURE__ */ React.createElement("div", {
4962
+ className: "tac-msg-col"
4963
+ }, first && /* @__PURE__ */ React.createElement("div", {
4964
+ className: "tac-msg-name"
4965
+ }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement(MessagePictures, {
4966
+ context,
4967
+ channelId: channel.id,
4968
+ message,
4969
+ alt: message.byName ?? w.owner
4970
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
4971
+ className: "tac-msg-bubble",
4972
+ title: time(message.at)
4973
+ }, /* @__PURE__ */ React.createElement(Mentions, {
4974
+ text: message.text,
4975
+ agents: state.team.agents
4976
+ })))) : message.author === USER ? /* @__PURE__ */ React.createElement("div", {
4977
+ className: "ta-message ta-user tac-mine"
4978
+ }, /* @__PURE__ */ React.createElement(MessagePictures, {
4979
+ context,
4980
+ channelId: channel.id,
4981
+ message,
4982
+ alt: w.you
4983
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
4984
+ className: "ta-bubble"
4985
+ }, /* @__PURE__ */ React.createElement(Mentions, {
4986
+ text: message.text,
4987
+ agents: state.team.agents
4988
+ }))) : /* @__PURE__ */ React.createElement("div", {
4989
+ className: `tac-msg${first ? " tac-first" : ""}`
4990
+ }, /* @__PURE__ */ React.createElement("div", {
4991
+ className: "tac-msg-face"
4992
+ }, first && (message.author === TA ? /* @__PURE__ */ React.createElement(Avatar, {
4993
+ size: 28
4994
+ }) : /* @__PURE__ */ React.createElement(AgentAvatar, {
4995
+ agent: agentOf(message.author),
4996
+ faces,
4997
+ size: 28,
4998
+ working: working.includes(message.author)
4999
+ }))), /* @__PURE__ */ React.createElement("div", {
5000
+ className: "tac-msg-col"
5001
+ }, first && /* @__PURE__ */ React.createElement("div", {
5002
+ className: "tac-msg-name"
5003
+ }, name(message.author), message.author === channel.members[0] && /* @__PURE__ */ React.createElement("span", {
5004
+ className: "tac-msg-lead"
5005
+ }, w.lead)), /* @__PURE__ */ React.createElement("div", {
5006
+ className: `tac-msg-bubble${message.failed ? " tac-failed" : ""}`,
5007
+ title: time(message.at)
5008
+ }, message.failed && /* @__PURE__ */ React.createElement("div", {
5009
+ className: "tac-msg-failed"
5010
+ }, w.failed), message.overBudget && /* @__PURE__ */ React.createElement("div", {
5011
+ className: "tac-msg-over"
5012
+ }, w.overBudget), agentOf(message.author) ? /* @__PURE__ */ React.createElement(AgentText, {
5013
+ context,
5014
+ channelId: channel.id,
5015
+ agent: agentOf(message.author),
5016
+ text: ChannelsText.markMentions(message.text, state.team.agents),
5017
+ answer: RoomUtil.answer(messages, message, agentOf(message.author))
5018
+ }) : /* @__PURE__ */ React.createElement(Markdown, {
5019
+ text: ChannelsText.markMentions(message.text, state.team.agents)
5020
+ })))))), working.length > 0 && /* @__PURE__ */ React.createElement("div", {
5021
+ className: "tac-live",
5022
+ role: "status"
5023
+ }, /* @__PURE__ */ React.createElement("span", {
5024
+ className: "tac-live-faces"
5025
+ }, working.map((id) => /* @__PURE__ */ React.createElement(Face, {
5026
+ key: id,
5027
+ face: faces.get(id) ?? 0,
5028
+ size: 18,
5029
+ working: true
5030
+ }))), ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") })))), /* @__PURE__ */ React.createElement("div", {
5031
+ className: "tac-chat-bottom"
5032
+ }, /* @__PURE__ */ React.createElement(Composer, {
5033
+ placeholder: ChannelWords.format(placeholder, { channel: channel.name, lead: lead?.name ?? "" }),
5034
+ draft: channel.id,
5035
+ mentions: members.map((agent) => ({ name: agent.name, detail: agent.role.split(`
5036
+ `)[0] })),
5037
+ mentionLabel: w.mentionMember,
5038
+ actions: [
5039
+ [
5040
+ {
5041
+ key: "notice",
5042
+ label: w.noticeEdit,
5043
+ icon: ChannelViews.maybeIcon(pi, "Megaphone", null, 16),
5044
+ run: () => setNotice({ open: true, editing: true })
5045
+ },
5046
+ {
5047
+ key: "add",
5048
+ label: w.addMembers,
5049
+ icon: ChannelViews.maybeIcon(pi, "UserPlus", null, 16),
5050
+ run: () => {
5051
+ if (fixed) {
5052
+ ui.set({ channelId: fixed });
5053
+ }
5054
+ context.showMembers(true);
5055
+ }
5056
+ }
5057
+ ],
5058
+ [
5059
+ {
5060
+ key: "make-extension",
5061
+ label: w.makeExtension,
5062
+ detail: w.makeExtensionDetail,
5063
+ icon: ChannelViews.maybeIcon(pi, "Sparkles", null, 16),
5064
+ run: () => void service.post(channel.id, w.makeExtensionAsk).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"))
5065
+ }
5066
+ ]
5067
+ ],
5068
+ images: { side: 1600, bytes: 1024 * 1024 },
5069
+ onSend: (text, images) => service.post(channel.id, text, images ?? [])
5070
+ })));
5071
+ }
5072
+
5073
+ // web-src/tasks.tsx
5074
+ var BUILDING_MS = 60 * 1000;
5075
+
5076
+ class ChannelTaskSource {
5077
+ context;
5078
+ shown = new Map;
5079
+ list = [];
5080
+ listeners = new Set;
5081
+ reading = new Set;
5082
+ stop;
5083
+ constructor(context) {
5084
+ this.context = context;
4936
5085
  }
4937
- ChannelRounds.day = day;
4938
- function limits(stored) {
4939
- const given = stored ?? {};
4940
- const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
4941
- return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
5086
+ tasks() {
5087
+ return this.list;
4942
5088
  }
4943
- ChannelRounds.limits = limits;
4944
- function today(stored, now) {
4945
- const current = day(now);
4946
- return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
5089
+ subscribe(listener) {
5090
+ if (this.listeners.size === 0) {
5091
+ this.stop = this.context.service.subscribe((state) => this.build(state));
5092
+ this.build(this.context.service.state);
5093
+ }
5094
+ this.listeners.add(listener);
5095
+ return () => {
5096
+ this.listeners.delete(listener);
5097
+ if (this.listeners.size === 0) {
5098
+ this.stop?.();
5099
+ this.stop = undefined;
5100
+ }
5101
+ };
4947
5102
  }
4948
- ChannelRounds.today = today;
4949
- function spend(stored, channelId, tokens, now) {
4950
- const current = today(stored, now);
4951
- return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
5103
+ refresh() {
5104
+ this.shown.clear();
5105
+ this.build(this.context.service.state);
4952
5106
  }
4953
- ChannelRounds.spend = spend;
4954
- function held(spent, limits2, channelId, hops, granted = false) {
4955
- if (granted) {
4956
- return;
4957
- }
4958
- if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
4959
- return "all";
5107
+ build(state) {
5108
+ const { team } = state;
5109
+ const faces = ChannelsUtil.faces(team.agents);
5110
+ const next = new Map;
5111
+ const channels = ChannelsUtil.taskChannels(team);
5112
+ let changed = channels.length !== this.list.length;
5113
+ const list = channels.map((channel, index) => {
5114
+ const messages = state.messages[channel.id];
5115
+ if (!messages) {
5116
+ this.read(channel.id);
5117
+ }
5118
+ const members = membersOf(team, channel);
5119
+ const working = state.working[channel.id] ?? [];
5120
+ const { status, detail, endedAt } = this.status(state, channel, messages, working);
5121
+ const signature = members.map((agent) => `${agent.id}:${faces.get(agent.id)}:${working.includes(agent.id) ? 1 : 0}`).join(",");
5122
+ const before = this.shown.get(channel.id);
5123
+ const shown = before && before.channel === channel && before.faces === signature && before.status === status && before.detail === detail && before.endedAt === endedAt ? before : {
5124
+ channel,
5125
+ members,
5126
+ faces: signature,
5127
+ status,
5128
+ detail,
5129
+ endedAt,
5130
+ entry: this.entry(channel, members, faces, working, status, detail, endedAt)
5131
+ };
5132
+ next.set(channel.id, shown);
5133
+ changed ||= shown.entry !== this.list[index];
5134
+ return shown.entry;
5135
+ });
5136
+ this.shown = next;
5137
+ if (!changed) {
5138
+ return;
4960
5139
  }
4961
- if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
4962
- return "channel";
5140
+ this.list = list;
5141
+ for (const listener of this.listeners) {
5142
+ listener();
4963
5143
  }
4964
- return;
4965
5144
  }
4966
- ChannelRounds.held = held;
4967
- function changedFiles(entries) {
4968
- for (const entry of entries) {
4969
- const message = entry?.message;
4970
- if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
4971
- continue;
4972
- }
4973
- for (const part of message.content) {
4974
- if (part?.type !== "toolCall") {
4975
- continue;
4976
- }
4977
- if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
4978
- return true;
4979
- }
4980
- }
5145
+ read(channelId) {
5146
+ if (!this.reading.has(channelId)) {
5147
+ this.reading.add(channelId);
5148
+ this.context.service.messages(channelId).catch(() => this.reading.delete(channelId));
4981
5149
  }
4982
- return false;
4983
- }
4984
- ChannelRounds.changedFiles = changedFiles;
4985
- function units(text) {
4986
- return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
4987
- }
4988
- function pairsOf(text) {
4989
- const words = units(text);
4990
- return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
4991
5150
  }
4992
- function alike(a, b) {
4993
- if (a.length === 0 || b.length === 0) {
4994
- return 0;
5151
+ status(state, channel, messages, working) {
5152
+ const w = ChannelViews.words(this.context.pi);
5153
+ const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5154
+ if (working.length > 0) {
5155
+ return { status: "running", detail: ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") }) };
4995
5156
  }
4996
- const left = new Map;
4997
- for (const pair of a) {
4998
- left.set(pair, (left.get(pair) ?? 0) + 1);
5157
+ const last = messages?.at(-1);
5158
+ if (!last) {
5159
+ const building = Date.now() - channel.createdAt < BUILDING_MS;
5160
+ return building ? { status: "running", detail: w.building } : { status: "done", detail: channel.topic || w.noMessages, endedAt: channel.createdAt };
4999
5161
  }
5000
- let common = 0;
5001
- for (const pair of b) {
5002
- const n = left.get(pair) ?? 0;
5003
- if (n > 0) {
5004
- left.set(pair, n - 1);
5005
- common++;
5162
+ if (last.author === SYSTEM) {
5163
+ return { status: "waiting", detail: w.yourTurn };
5164
+ }
5165
+ const said = `${name(last.author)}:${last.text.replace(/\s+/g, " ").slice(0, 120)}`;
5166
+ return { status: last.failed ? "failed" : "done", detail: said, endedAt: last.at };
5167
+ }
5168
+ entry(channel, members, faces, working, status, detail, endedAt) {
5169
+ return {
5170
+ id: channel.id,
5171
+ title: taskTitle(channel),
5172
+ status,
5173
+ detail,
5174
+ startedAt: channel.createdAt,
5175
+ endedAt: status === "running" || status === "waiting" ? undefined : endedAt,
5176
+ origin: channel.origin,
5177
+ icon: ({ size }) => /* @__PURE__ */ React.createElement(RoomFace, {
5178
+ members,
5179
+ faces,
5180
+ size,
5181
+ working
5182
+ }),
5183
+ open: () => openScene(this.context, channel),
5184
+ show: () => this.context.showChannel(channel.id),
5185
+ menu: () => taskMenu(this.context, channel, working),
5186
+ remove: () => deleteTeam(this.context, channel),
5187
+ removeHint: ChannelWords.format(ChannelViews.words(this.context.pi).deleteTaskHint, { channel: channel.name })
5188
+ };
5189
+ }
5190
+ }
5191
+ function taskTitle(channel) {
5192
+ return channel.name;
5193
+ }
5194
+ async function deleteTeam(context, channel) {
5195
+ await context.service.deleteChannel(channel.id);
5196
+ context.pi.ui.closeEditor(`channel:${channel.id}`);
5197
+ }
5198
+ function openScene(context, channel) {
5199
+ context.pi.ui.openEditor({
5200
+ id: `channel:${channel.id}`,
5201
+ title: channel.name,
5202
+ icon: ChannelViews.icon(context.pi, "Hash"),
5203
+ render: () => /* @__PURE__ */ React.createElement("div", {
5204
+ className: "tac-scene"
5205
+ }, /* @__PURE__ */ React.createElement(ChannelSceneHead, {
5206
+ context,
5207
+ channelId: channel.id
5208
+ }), /* @__PURE__ */ React.createElement(ChannelRoom, {
5209
+ context,
5210
+ channelId: channel.id
5211
+ }))
5212
+ });
5213
+ }
5214
+ function taskMenu(context, channel, working) {
5215
+ const { pi, service } = context;
5216
+ const w = ChannelViews.words(pi);
5217
+ const icon = (name) => ChannelViews.icon(pi, name);
5218
+ const act = (action2) => () => {
5219
+ Promise.resolve().then(action2).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"));
5220
+ };
5221
+ const temporary = membersOf(service.state.team, channel).filter((agent) => agent.temporary);
5222
+ return [
5223
+ working.length > 0 ? [
5224
+ {
5225
+ key: "stop",
5226
+ label: w.stopAnswering,
5227
+ icon: icon("Square"),
5228
+ run: act(async () => {
5229
+ await TeamActions.stop(context, working);
5230
+ pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info");
5231
+ })
5232
+ }
5233
+ ] : [],
5234
+ [
5235
+ { key: "main", label: w.openInMain, icon: icon("ExternalLink"), run: () => context.showChannel(channel.id) },
5236
+ ...temporary.length > 0 ? [
5237
+ {
5238
+ key: "keep",
5239
+ label: w.keepMembers,
5240
+ icon: icon("UserPlus"),
5241
+ run: act(async () => {
5242
+ await TeamActions.keep(context, temporary);
5243
+ pi.ui.notify(ChannelWords.format(w.keptMembers, { names: temporary.map((agent) => `@${agent.name}`).join("、") }), "info");
5244
+ })
5245
+ }
5246
+ ] : []
5247
+ ],
5248
+ [
5249
+ {
5250
+ key: "delete",
5251
+ label: w.deleteTask,
5252
+ icon: icon("Trash2"),
5253
+ danger: true,
5254
+ run: act(() => pi.ui.removeTasks([
5255
+ {
5256
+ title: taskTitle(channel),
5257
+ removeHint: ChannelWords.format(w.deleteTaskHint, { channel: channel.name }),
5258
+ remove: () => deleteTeam(context, channel)
5259
+ }
5260
+ ]))
5006
5261
  }
5262
+ ]
5263
+ ];
5264
+ }
5265
+ var TeamActions;
5266
+ ((TeamActions) => {
5267
+ async function stop(context, agentIds) {
5268
+ const { pi, service } = context;
5269
+ const files = new Set(service.state.team.agents.filter((agent) => agentIds.includes(agent.id) && agent.sessionFile).map((agent) => agent.sessionFile));
5270
+ const sessions = (await pi.server.listSessions()).filter((session) => session.sessionFile && files.has(session.sessionFile));
5271
+ await Promise.all(sessions.map((session) => pi.server.abort(session.sessionId)));
5272
+ }
5273
+ TeamActions.stop = stop;
5274
+ async function keep(context, agents) {
5275
+ for (const agent of agents) {
5276
+ await context.service.updateAgent(agent.id, { keep: true });
5007
5277
  }
5008
- return 2 * common / (a.length + b.length);
5009
5278
  }
5010
- })(ChannelRounds ||= {});
5279
+ TeamActions.keep = keep;
5280
+ })(TeamActions ||= {});
5011
5281
 
5012
- // web-src/limit-settings.tsx
5013
- function amount(pi, tokens) {
5014
- return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
5015
- }
5016
- function useLimits(pi) {
5017
- const read = React.useCallback(async () => ({
5018
- limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
5019
- ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
5020
- }), [pi]);
5021
- const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
5282
+ // web-src/shared-group.tsx
5283
+ function useFriends(pi) {
5284
+ const [friends, setFriends] = React.useState([]);
5022
5285
  React.useEffect(() => {
5023
5286
  let live = true;
5024
- const load = () => void read().then((next) => live && setValue(next), () => {
5287
+ pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
5025
5288
  return;
5026
5289
  });
5027
- load();
5028
- const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
5029
5290
  return () => {
5030
5291
  live = false;
5031
- stop();
5032
5292
  };
5033
- }, [pi, read]);
5034
- return value;
5293
+ }, [pi]);
5294
+ return friends;
5035
5295
  }
5036
- function limitSettings(pi, service) {
5037
- const words = () => ChannelWords.of(pi.ui.language);
5038
- const row = (key) => function Choices() {
5039
- const { limits } = useLimits(pi);
5040
- const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
5041
- return /* @__PURE__ */ React.createElement("fieldset", {
5042
- className: "ta-segmented",
5043
- "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
5044
- }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
5045
- key: value,
5046
- type: "button",
5047
- "aria-pressed": limits[key] === value,
5048
- className: limits[key] === value ? "ta-on" : "",
5049
- onClick: () => pick(value)
5050
- }, amount(pi, value))));
5051
- };
5052
- function Spent() {
5053
- const { spent } = useLimits(pi);
5054
- return /* @__PURE__ */ React.createElement("span", {
5055
- className: "tac-limit-spent"
5056
- }, spent > 0 ? amount(pi, spent) : "0");
5296
+ async function createShared(context, title, friends, agents) {
5297
+ const { pi } = context;
5298
+ const rooms = pi.rooms;
5299
+ if (!rooms) {
5300
+ throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
5057
5301
  }
5058
- return {
5059
- title: () => words().limitsTitle,
5060
- icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
5061
- group: "ta",
5062
- rows: [
5063
- { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
5064
- { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
5065
- { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
5066
- { key: "spent", label: () => words().limitSpent, render: Spent }
5067
- ]
5068
- };
5069
- }
5070
-
5071
- // ../ta-protocol/esm/common/team-protocol.js
5072
- var TA_OWNER = "owner";
5073
- var TA_UNDECLARED = "extensions.install";
5074
- var TaPermissionUtil;
5075
- (function(TaPermissionUtil2) {
5076
- function read(pi) {
5077
- const given = pi === null || pi === undefined ? undefined : pi.permissions;
5078
- const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
5079
- const host2 = map(given === null || given === undefined ? undefined : given.host);
5080
- const tools = map(given === null || given === undefined ? undefined : given.tools);
5081
- return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
5082
- }
5083
- TaPermissionUtil2.read = read;
5084
- function host(manifest, method, kind) {
5085
- var _a, _b, _c, _d;
5086
- const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
5087
- const own = (key) => {
5088
- var _a2;
5089
- return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
5090
- };
5091
- return (_d = (_c = (_b = kind ? own(`${method}:${kind}`) : undefined) !== null && _b !== undefined ? _b : own(method)) !== null && _c !== undefined ? _c : own("*")) !== null && _d !== undefined ? _d : TA_UNDECLARED;
5092
- }
5093
- TaPermissionUtil2.host = host;
5094
- })(TaPermissionUtil || (TaPermissionUtil = {}));
5095
- var action = (id, en, zh, tw, ja, more = {}) => ({
5096
- id,
5097
- area: id.split(".")[0],
5098
- title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
5099
- ...more
5100
- });
5101
- var TA_ACTIONS = [
5102
- action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
5103
- action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
5104
- action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
5105
- action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
5106
- action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
5107
- action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
5108
- action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
5109
- action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
5110
- action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
5111
- action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
5112
- action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
5113
- action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
5114
- action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
5115
- action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
5116
- action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
5117
- action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
5118
- action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
5119
- action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
5120
- action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
5121
- action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
5122
- action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
5123
- action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
5124
- action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
5125
- action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
5126
- action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
5127
- action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
5128
- action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
5129
- action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
5130
- action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
5131
- action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
5132
- action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
5133
- action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
5134
- action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
5135
- ];
5136
- var TA_OWNER_ACTIONS = [
5137
- action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
5138
- action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true })
5139
- ];
5140
- var OWNER_AREAS = ["desktop"];
5141
- var TaActionUtil;
5142
- (function(TaActionUtil2) {
5143
- const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
5144
- const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
5145
- function info(id) {
5146
- return byId.get(id);
5147
- }
5148
- TaActionUtil2.info = info;
5149
- function title(id, language) {
5150
- var _a;
5151
- var _b, _c;
5152
- const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
5153
- if (!title2) {
5154
- return id;
5155
- }
5156
- return TaLanguageUtil.pick(language, {
5157
- "zh-CN": title2["zh-CN"],
5158
- "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
5159
- "en-US": title2.en,
5160
- "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
5302
+ const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
5303
+ await rooms.inviteFriends(room.id, friends);
5304
+ await TeamActions.keep(context, context.service.state.team.agents.filter((agent) => agent.temporary && agents.includes(agent.id)));
5305
+ for (const agent of agents) {
5306
+ await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
5307
+ pi.ui.notify(ChannelViews.message(error), "error");
5161
5308
  });
5162
5309
  }
5163
- TaActionUtil2.title = title;
5164
- function grantable(id) {
5165
- const info2 = byId.get(id);
5166
- return !!info2 && !OWNER_AREAS.includes(info2.area);
5167
- }
5168
- TaActionUtil2.grantable = grantable;
5169
- function inRoles(id) {
5170
- var _a;
5171
- return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
5172
- }
5173
- TaActionUtil2.inRoles = inRoles;
5174
- function inside(dir, path) {
5175
- const base = dir.replace(/\/+$/, "");
5176
- return path === base || path.startsWith(`${base}/`) || base === "";
5177
- }
5178
- TaActionUtil2.inside = inside;
5179
- })(TaActionUtil || (TaActionUtil = {}));
5180
-
5181
- // web-src/notice-util.ts
5182
- var NoticeUtil;
5183
- ((NoticeUtil) => {
5184
- const PARTS = {
5185
- 决定: "decisions",
5186
- decisions: "decisions",
5187
- 约定: "conventions",
5188
- conventions: "conventions",
5189
- 待办: "todo",
5190
- "to do": "todo",
5191
- todo: "todo",
5192
- "to-do": "todo"
5193
- };
5194
- function counts(text) {
5195
- const counts2 = { decisions: 0, conventions: 0, todo: 0, done: 0 };
5196
- let part;
5197
- for (const line of text.split(/\r?\n/)) {
5198
- const heading = /^\s*#{1,6}\s+(.+?)\s*#*\s*$/.exec(line) ?? /^\s*\*\*(.+?)\*\*\s*[::]?\s*$/.exec(line);
5199
- if (heading) {
5200
- part = PARTS[heading[1].replace(/[::]$/, "").trim().toLowerCase()];
5201
- continue;
5202
- }
5203
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(\[( |x|X)\]\s+)?\S/.exec(line);
5204
- if (!part || !item) {
5205
- continue;
5206
- }
5207
- if (part === "todo" && item[2] && item[2] !== " ") {
5208
- counts2.done++;
5209
- } else {
5210
- counts2[part]++;
5211
- }
5212
- }
5213
- return counts2;
5214
- }
5215
- NoticeUtil.counts = counts;
5216
- function firstLine(text) {
5217
- for (const line of text.split(/\r?\n/)) {
5218
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(line);
5219
- if (item) {
5220
- return item[1].replace(/[*_`~]+/g, "").trim();
5221
- }
5222
- }
5223
- return text.split(/\r?\n/).find((line) => line.trim() && !/^\s*#/.test(line))?.trim() ?? "";
5224
- }
5225
- NoticeUtil.firstLine = firstLine;
5226
- })(NoticeUtil ||= {});
5310
+ const { link } = await rooms.invite(room.id);
5311
+ await pi.openLink?.(link);
5312
+ return room.id;
5313
+ }
5314
+ var ROOMS_PACKAGE = "@celljs/ta-rooms";
5315
+ var ROOMS_KIND = "ta-rooms";
5316
+ async function becomeGroup(context, channel, friends, agents) {
5317
+ const { pi } = context;
5318
+ const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
5319
+ const room = await createShared(context, channel.name, friends, members);
5320
+ await context.service.updateChannel(channel.id, { shared: room });
5321
+ pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
5322
+ }
5227
5323
 
5228
- // web-src/notice.tsx
5229
- var NoticeView;
5230
- ((NoticeView) => {
5231
- function display(text) {
5232
- return text.replace(/^(\s*[-*+]\s+)\[ \]\s+/gm, "$1☐ ").replace(/^(\s*[-*+]\s+)\[[xX]\]\s+/gm, "$1☑ ");
5233
- }
5234
- NoticeView.display = display;
5235
- function counts(text, language) {
5236
- const w = ChannelWords.of(language);
5237
- const counts2 = NoticeUtil.counts(text);
5238
- if (counts2.decisions + counts2.conventions + counts2.todo === 0) {
5239
- return NoticeUtil.firstLine(text);
5240
- }
5241
- const values = { decisions: String(counts2.decisions), conventions: String(counts2.conventions), todo: String(counts2.todo) };
5242
- return ChannelWords.format(w.noticeCounts, values).split(" · ").filter((_, at) => [counts2.decisions, counts2.conventions, counts2.todo][at] > 0).join(" · ");
5324
+ // web-src/create.tsx
5325
+ var noBack = (_open, _close) => false;
5326
+ var AGENT_PAGE = `${NAME}/agent`;
5327
+ function newAgent(context) {
5328
+ const { pi, service, ui } = context;
5329
+ if (!ui.state.draft) {
5330
+ const team = service.state.team;
5331
+ const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
5332
+ ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
5243
5333
  }
5244
- NoticeView.counts = counts;
5245
- })(NoticeView ||= {});
5246
- function NoticeBar({
5247
- context,
5248
- channel,
5249
- state,
5250
- onState
5251
- }) {
5252
- const { pi, service } = context;
5253
- const { team } = useChannels(service);
5334
+ pi.ui.showView(AGENT_PAGE);
5335
+ }
5336
+ function Identity({ context, onClose }) {
5337
+ const { pi, ui } = context;
5338
+ const { draft } = useUi(ui);
5254
5339
  const w = ChannelViews.words(pi);
5255
- const notice = channel.notice;
5256
- const [draft, setDraft] = React.useState("");
5257
- const [busy, setBusy] = React.useState(false);
5258
- const [error, setError] = React.useState();
5340
+ const ref = React.useRef(null);
5341
+ const name = React.useRef(null);
5342
+ React.useEffect(() => name.current?.select(), []);
5343
+ (pi.ui.useBackLayer ?? noBack)(true, onClose);
5259
5344
  React.useEffect(() => {
5260
- if (state.editing) {
5261
- setDraft(notice?.text ?? w.noticeTemplate);
5262
- setError(undefined);
5263
- }
5264
- }, [state.editing]);
5265
- if (!notice && !state.editing) {
5345
+ const close = (event) => {
5346
+ const target = event.target;
5347
+ if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
5348
+ onClose();
5349
+ }
5350
+ };
5351
+ const onKey = (event) => event.key === "Escape" && onClose();
5352
+ document.addEventListener("pointerdown", close);
5353
+ document.addEventListener("keydown", onKey);
5354
+ return () => {
5355
+ document.removeEventListener("pointerdown", close);
5356
+ document.removeEventListener("keydown", onKey);
5357
+ };
5358
+ }, [onClose]);
5359
+ if (!draft) {
5266
5360
  return null;
5267
5361
  }
5268
- const Megaphone = ChannelViews.icon(pi, "Megaphone");
5269
- const Chevron = ChannelViews.icon(pi, "ChevronDown");
5270
- const Markdown = pi.ui.Markdown;
5271
- const save = (event) => {
5272
- event.preventDefault();
5273
- setBusy(true);
5274
- setError(undefined);
5275
- service.setNotice(channel.id, draft).then(() => {
5276
- setBusy(false);
5277
- onState({ open: true, editing: false });
5278
- }, (failure) => {
5279
- setBusy(false);
5280
- setError(ChannelViews.message(failure));
5281
- });
5282
- };
5283
- const open = state.open || state.editing;
5284
5362
  return /* @__PURE__ */ React.createElement("div", {
5285
- className: "tac-notice-bar",
5286
- "data-open": open ? "" : undefined
5287
- }, /* @__PURE__ */ React.createElement("button", {
5288
- type: "button",
5289
- className: "tac-notice-head",
5290
- "aria-expanded": open,
5291
- title: open ? w.noticeHide : w.noticeShow,
5292
- onClick: () => onState({ open: !open, editing: false })
5293
- }, /* @__PURE__ */ React.createElement("span", {
5294
- className: "tac-notice-icon"
5295
- }, /* @__PURE__ */ React.createElement(Megaphone, {
5296
- size: 13,
5297
- strokeWidth: 2
5298
- })), /* @__PURE__ */ React.createElement("strong", null, w.notice), /* @__PURE__ */ React.createElement("span", {
5299
- className: "tac-notice-sum"
5300
- }, notice ? NoticeView.counts(notice.text, pi.ui.language) : w.noticeEmpty), /* @__PURE__ */ React.createElement("span", {
5301
- className: "tac-notice-chevron"
5302
- }, /* @__PURE__ */ React.createElement(Chevron, {
5303
- size: 15
5304
- }))), open && !state.editing && notice && /* @__PURE__ */ React.createElement("div", {
5305
- className: "tac-notice-body"
5306
- }, /* @__PURE__ */ React.createElement("div", {
5307
- className: "tac-notice-text"
5308
- }, /* @__PURE__ */ React.createElement(Markdown, {
5309
- text: NoticeView.display(notice.text)
5363
+ className: "tac-identity",
5364
+ ref,
5365
+ role: "dialog",
5366
+ "aria-label": w.editAgent
5367
+ }, /* @__PURE__ */ React.createElement("label", {
5368
+ className: "tac-identity-label"
5369
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
5370
+ className: "tac-input",
5371
+ value: draft.name,
5372
+ maxLength: 40,
5373
+ ref: name,
5374
+ onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
5375
+ onKeyDown: (event) => event.key === "Enter" && onClose()
5310
5376
  })), /* @__PURE__ */ React.createElement("div", {
5311
- className: "tac-notice-foot"
5312
- }, /* @__PURE__ */ React.createElement("span", null, ChannelWords.format(w.noticeBy, {
5313
- name: ChannelsText.authorName(team, notice.by, { user: w.you, ta: w.ta }),
5314
- time: SidebarUtil.time(notice.at, pi.ui.language)
5315
- })), /* @__PURE__ */ React.createElement("button", {
5316
- type: "button",
5317
- className: "tac-button tac-quiet",
5318
- onClick: () => onState({ open: true, editing: true })
5319
- }, w.noticeEdit))), state.editing && /* @__PURE__ */ React.createElement("form", {
5320
- className: "tac-notice-body tac-notice-form",
5321
- onSubmit: save
5322
- }, /* @__PURE__ */ React.createElement("p", {
5323
- className: "tac-dialog-note"
5324
- }, w.noticeHint), /* @__PURE__ */ React.createElement("textarea", {
5325
- className: "tac-input tac-notice-input",
5326
- value: draft,
5327
- "aria-label": w.noticeEdit,
5328
- autoFocus: true,
5329
- onChange: (event) => setDraft(event.target.value)
5330
- }), error && /* @__PURE__ */ React.createElement("div", {
5331
- className: "tac-error"
5332
- }, error), /* @__PURE__ */ React.createElement("div", {
5333
- className: "tac-notice-actions"
5334
- }, /* @__PURE__ */ React.createElement("button", {
5377
+ className: "tac-identity-label"
5378
+ }, w.avatar), /* @__PURE__ */ React.createElement("div", {
5379
+ className: "tac-faces"
5380
+ }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
5381
+ key: face,
5335
5382
  type: "button",
5336
- className: "tac-button tac-quiet",
5337
- onClick: () => onState({ open: !!notice, editing: false })
5338
- }, w.cancel), /* @__PURE__ */ React.createElement("button", {
5339
- type: "submit",
5340
- className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
5341
- disabled: busy || draft.trim() === (notice?.text ?? "")
5342
- }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
5343
- className: "ta-spinner ta-busy-mark ta-on-brand"
5383
+ "aria-pressed": draft.face === face,
5384
+ className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
5385
+ onClick: () => ui.set({ draft: { ...draft, face } })
5386
+ }, /* @__PURE__ */ React.createElement(Face, {
5387
+ face,
5388
+ size: 30
5344
5389
  })))));
5345
5390
  }
5346
-
5347
- // web-src/room.tsx
5348
- var RUN_MS = 5 * 60 * 1000;
5349
- var PAUSE_MS = 15 * 60 * 1000;
5350
- var RoomUtil;
5351
- ((RoomUtil) => {
5352
- function rows(messages) {
5353
- return messages.map((message, index) => {
5354
- const before = messages[index - 1];
5355
- const separator = !before || message.at - before.at > PAUSE_MS;
5356
- const first = separator || before.author !== message.author || before.by !== message.by || before.author === SYSTEM || !!before.notice || message.at - before.at > RUN_MS;
5357
- return { message, first, separator };
5358
- });
5359
- }
5360
- RoomUtil.rows = rows;
5361
- function choice(agent, text) {
5362
- return `@${agent.name} ${text}`;
5363
- }
5364
- RoomUtil.choice = choice;
5365
- function answer(messages, message, agent) {
5366
- const said = messages.slice(messages.indexOf(message) + 1).find((later) => later.author === USER && !later.notice);
5367
- if (!said) {
5368
- return;
5369
- }
5370
- const named = `@${agent.name} `;
5371
- return said.text.startsWith(named) ? said.text.slice(named.length) : said.text;
5372
- }
5373
- RoomUtil.answer = answer;
5374
- })(RoomUtil ||= {});
5375
- function AgentText({ context, channelId, agent, text, answer }) {
5376
- const { pi, service } = context;
5377
- const send = React.useCallback((said) => service.post(channelId, RoomUtil.choice(agent, said)), [service, channelId, agent.name]);
5378
- return /* @__PURE__ */ React.createElement(pi.ui.Markdown, {
5379
- text,
5380
- send,
5381
- answer
5382
- });
5383
- }
5384
- function MessagePictures({ context, channelId, message, alt }) {
5385
- const { pi, service } = context;
5386
- const images = message.images ?? [];
5387
- const [sources, setSources] = React.useState({});
5388
- const ids = images.map((image) => image.id).join(",");
5389
- React.useEffect(() => {
5390
- let live = true;
5391
- for (const id of ids ? ids.split(",") : []) {
5392
- service.picture(channelId, id).then((data) => live && data && setSources((current) => ({ ...current, [id]: data })));
5393
- }
5394
- return () => {
5395
- live = false;
5396
- };
5397
- }, [service, channelId, ids]);
5398
- const ChatImages = pi.ui.ChatImages;
5399
- if (!images.length || !ChatImages) {
5391
+ function NewAgentHead({ context }) {
5392
+ const { pi, ui } = context;
5393
+ const { draft, editing } = useUi(ui);
5394
+ const w = ChannelViews.words(pi);
5395
+ const Down = ChannelViews.icon(pi, "ChevronDown");
5396
+ if (!draft) {
5400
5397
  return null;
5401
5398
  }
5402
5399
  return /* @__PURE__ */ React.createElement("div", {
5403
- className: "tac-pics"
5404
- }, /* @__PURE__ */ React.createElement(ChatImages, {
5405
- alt,
5406
- images: images.map((image) => ({ key: image.id, src: sources[image.id], width: image.w, height: image.h }))
5407
- }));
5408
- }
5409
- function Mentions({ text, agents }) {
5410
- const names = new Set(agents.map((agent) => agent.name.toLowerCase()));
5411
- const parts = text.split(/(@[^\s@#,,。::]+)/);
5412
- return /* @__PURE__ */ React.createElement("span", null, parts.map((part, index) => part.startsWith("@") && names.has(part.slice(1).toLowerCase()) ? /* @__PURE__ */ React.createElement("span", {
5413
- key: index,
5414
- className: "tac-mention"
5415
- }, part) : part));
5416
- }
5417
- function StopLine({
5418
- context,
5419
- channel,
5420
- message,
5421
- later,
5422
- agents
5423
- }) {
5424
- const { pi, service } = context;
5425
- const w = ChannelViews.words(pi);
5426
- const [busy, setBusy] = React.useState(false);
5427
- const stop = message.stop;
5428
- const lead = agents.find((agent) => agent.id === channel.members.find((id) => !(channel.muted ?? []).includes(id)));
5429
- const replies = String(stop?.replies ?? 0);
5430
- const tokens = stop?.tokens ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(stop.tokens) : "";
5431
- const stats = stop ? ChannelWords.format(tokens ? w.stoppedStats : w.stoppedReplies, { replies, tokens }) : "";
5432
- const resumed = stop?.resumed === "continue" ? w.wentOn : stop?.resumed === "wrapUp" ? w.summedUp : "";
5433
- const why = stop?.daily === "all" ? w.dailyAll : stop?.daily === "channel" ? w.dailyChannel : stop?.idle === "repeat" ? w.idleRepeat : stop?.idle === "agree" ? w.idleAgree : stop?.idle === "pingPong" ? w.idlePingPong : w.stopped;
5434
- const extended = stop?.extended ? w.extendedOnce : "";
5435
- const go = (how) => {
5436
- setBusy(true);
5437
- service.resumeRound(channel.id, message.id, how).catch((error) => pi.ui.notify(ChannelViews.message(error), "error")).finally(() => setBusy(false));
5438
- };
5439
- const open = !!stop?.pending.length && !stop.resumed && !later;
5440
- return /* @__PURE__ */ React.createElement("div", {
5441
- className: "tac-stop",
5442
- role: "note"
5400
+ className: "tac-new-head"
5443
5401
  }, /* @__PURE__ */ React.createElement("div", {
5444
- className: "tac-notice"
5445
- }, why), /* @__PURE__ */ React.createElement("div", {
5446
- className: "tac-stop-meta"
5447
- }, [stats, extended, resumed].filter(Boolean).join(" · ")), open && /* @__PURE__ */ React.createElement("div", {
5448
- className: "tac-stop-actions"
5402
+ className: "tac-new-title"
5449
5403
  }, /* @__PURE__ */ React.createElement("button", {
5450
5404
  type: "button",
5451
- className: "tac-stop-button",
5452
- disabled: busy,
5453
- onClick: () => go("continue")
5454
- }, w.keepGoing), lead && /* @__PURE__ */ React.createElement("button", {
5405
+ className: "tac-new-trigger tac-identity-open",
5406
+ "aria-expanded": editing,
5407
+ title: w.editAgent,
5408
+ onClick: () => ui.set({ editing: !editing })
5409
+ }, /* @__PURE__ */ React.createElement(Face, {
5410
+ face: draft.face,
5411
+ size: 20
5412
+ }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
5413
+ size: 14
5414
+ })), editing && /* @__PURE__ */ React.createElement(Identity, {
5415
+ context,
5416
+ onClose: () => ui.set({ editing: false })
5417
+ })), /* @__PURE__ */ React.createElement("button", {
5455
5418
  type: "button",
5456
- className: "tac-stop-button",
5457
- disabled: busy,
5458
- onClick: () => go("wrapUp")
5459
- }, ChannelWords.format(w.wrapUp, { name: `@${lead.name}` }))));
5419
+ className: "tac-button tac-quiet",
5420
+ onClick: () => {
5421
+ ui.set({ draft: undefined, editing: false });
5422
+ pi.ui.showView("");
5423
+ }
5424
+ }, w.cancel));
5460
5425
  }
5461
- function ChannelHead({ context }) {
5426
+ function NewAgentPage({ context }) {
5462
5427
  const { pi, service, ui } = context;
5463
- const state = useChannels(service);
5464
- const { channelId } = useUi(ui);
5465
- const faces = useFaces(state.team);
5428
+ const { draft } = useUi(ui);
5429
+ const { loaded } = useChannels(service);
5466
5430
  const w = ChannelViews.words(pi);
5467
- const shown = !!pi.ui.useView(MEMBERS_VIEW)?.shown;
5468
- const roomInfo = !!pi.ui.useView(ROOM_INFO_VIEW)?.shown;
5469
- const follow = React.useRef(roomInfo);
5470
- follow.current = roomInfo;
5431
+ const Pencil = ChannelViews.icon(pi, "Pencil");
5432
+ const Composer = pi.ui.Composer;
5433
+ const first = React.useRef(true);
5471
5434
  React.useEffect(() => {
5472
- if (channelId && follow.current) {
5473
- context.showMembers();
5435
+ if (!loaded || !first.current) {
5436
+ return;
5474
5437
  }
5475
- }, [channelId, context]);
5476
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5477
- if (!channel) {
5438
+ first.current = false;
5439
+ if (!ui.state.draft) {
5440
+ newAgent(context);
5441
+ }
5442
+ }, [loaded, ui, context]);
5443
+ if (!draft) {
5478
5444
  return null;
5479
5445
  }
5480
- const members = membersOf(state.team, channel);
5481
- const working = state.working[channel.id] ?? [];
5482
- return /* @__PURE__ */ React.createElement("div", {
5483
- className: "tac-head"
5484
- }, /* @__PURE__ */ React.createElement("div", {
5485
- className: "tac-head-title"
5486
- }, /* @__PURE__ */ React.createElement("strong", null, channel.name), /* @__PURE__ */ React.createElement("span", {
5487
- className: "tac-head-count"
5488
- }, ChannelWords.format(w.memberCount, { count: String(members.length) })), channel.topic && /* @__PURE__ */ React.createElement("span", {
5489
- className: "tac-head-topic"
5490
- }, channel.topic)), /* @__PURE__ */ React.createElement("button", {
5491
- type: "button",
5492
- className: `tac-head-members${shown ? " tac-on" : ""}`,
5493
- title: w.showMembers,
5494
- "aria-label": w.showMembers,
5495
- "aria-pressed": shown,
5496
- onClick: () => context.showMembers()
5497
- }, members.slice(0, 5).map((agent) => /* @__PURE__ */ React.createElement("span", {
5498
- key: agent.id,
5499
- className: "tac-head-face"
5500
- }, /* @__PURE__ */ React.createElement(AgentAvatar, {
5501
- agent,
5502
- faces,
5503
- size: 24,
5504
- working: working.includes(agent.id)
5505
- }))), members.length > 5 && /* @__PURE__ */ React.createElement("span", {
5506
- className: "tac-head-more"
5507
- }, "+", members.length - 5)));
5508
- }
5509
- function ChannelSceneHead({ context, channelId }) {
5510
- const { pi, service } = context;
5511
- const state = useChannels(service);
5512
- const faces = useFaces(state.team);
5513
- const w = ChannelViews.words(pi);
5514
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5515
- if (!channel) {
5516
- return null;
5517
- }
5518
- const members = membersOf(state.team, channel);
5519
- const working = state.working[channel.id] ?? [];
5520
- const External = ChannelViews.icon(pi, "ExternalLink");
5446
+ const send = async (text) => {
5447
+ const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
5448
+ ui.set({ draft: undefined, editing: false });
5449
+ try {
5450
+ const sessionId = await service.openAgent(agent.id);
5451
+ context.sessions.set(agent.id, sessionId);
5452
+ await pi.switchSession(sessionId);
5453
+ await pi.sendUserMessage(text);
5454
+ } catch (error) {
5455
+ pi.ui.notify(ChannelViews.message(error), "error");
5456
+ }
5457
+ };
5521
5458
  return /* @__PURE__ */ React.createElement("div", {
5522
- className: "tac-scene-head"
5523
- }, /* @__PURE__ */ React.createElement(RoomFace, {
5524
- members,
5525
- faces,
5526
- size: 26,
5527
- working
5528
- }), /* @__PURE__ */ React.createElement("div", {
5529
- className: "tac-scene-title"
5530
- }, /* @__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("button", {
5459
+ className: "tac-new-page"
5460
+ }, /* @__PURE__ */ React.createElement("div", {
5461
+ className: "tac-new-col"
5462
+ }, /* @__PURE__ */ React.createElement(Face, {
5463
+ face: draft.face,
5464
+ size: 88
5465
+ }), /* @__PURE__ */ React.createElement("h2", {
5466
+ className: "tac-new-name"
5467
+ }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
5531
5468
  type: "button",
5532
- className: "tac-button tac-scene-main",
5533
- title: w.openInMainHint,
5534
- onClick: () => context.showChannel(channel.id)
5535
- }, /* @__PURE__ */ React.createElement(External, {
5536
- size: 13
5537
- }), w.openInMain));
5538
- }
5539
- var mePromise;
5540
- function useMe(pi) {
5541
- const [me, setMe] = React.useState(TA_OWNER);
5542
- React.useEffect(() => {
5543
- mePromise ??= pi.server.getServerInfo().then((info) => info.member?.id ?? TA_OWNER, () => TA_OWNER);
5544
- let live = true;
5545
- mePromise.then((id) => live && setMe(id));
5546
- return () => {
5547
- live = false;
5548
- };
5549
- }, [pi]);
5550
- return me;
5469
+ className: "tac-action tac-identity-open",
5470
+ title: w.editAgent,
5471
+ "aria-label": w.editAgent,
5472
+ onClick: () => ui.set({ editing: !ui.state.editing })
5473
+ }, /* @__PURE__ */ React.createElement(Pencil, {
5474
+ size: 14
5475
+ }))), /* @__PURE__ */ React.createElement("p", {
5476
+ className: "tac-new-hint"
5477
+ }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
5478
+ className: "tac-new-box"
5479
+ }, /* @__PURE__ */ React.createElement(Composer, {
5480
+ placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
5481
+ onSend: send,
5482
+ cwd: draft.cwd,
5483
+ onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
5484
+ draft: "new-agent"
5485
+ }))));
5551
5486
  }
5552
- function ChannelRoom({ context, channelId: fixed }) {
5553
- const { pi, service, ui } = context;
5554
- const me = useMe(pi);
5555
- const state = useChannels(service);
5556
- const shown = useUi(ui).channelId;
5557
- const channelId = fixed ?? shown;
5558
- const faces = useFaces(state.team);
5487
+ function NewChannelDialog({ context, onClose }) {
5488
+ const { pi, service } = context;
5489
+ const { team } = useChannels(service);
5490
+ const faces = useFaces(team);
5559
5491
  const w = ChannelViews.words(pi);
5560
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5561
- const messages = channel ? state.messages[channel.id] : undefined;
5562
- const working = channel ? state.working[channel.id] ?? [] : [];
5563
- React.useEffect(() => {
5564
- if (channelId) {
5565
- service.messages(channelId);
5566
- }
5567
- }, [service, channelId]);
5568
- const page = pi.ui.useView(CHANNEL_PAGE);
5569
- const inFront = !!channelId && (!!fixed || !!page?.shown);
5570
- const lastAt = ChannelSeenUtil.lastAt(messages);
5571
- const resting = working.length === 0;
5572
- React.useEffect(() => {
5573
- if (!channelId || !inFront || !resting) {
5574
- return;
5575
- }
5576
- const look = () => document.visibilityState === "visible" && context.seen.look(channelId, Math.max(Date.now(), lastAt ?? 0));
5577
- look();
5578
- document.addEventListener("visibilitychange", look);
5579
- return () => document.removeEventListener("visibilitychange", look);
5580
- }, [context, channelId, inFront, resting, lastAt]);
5581
- React.useEffect(() => {
5582
- if (!channelId) {
5492
+ const Search = ChannelViews.icon(pi, "Search");
5493
+ const Check = ChannelViews.icon(pi, "Check");
5494
+ const [name, setName] = React.useState("");
5495
+ const [query, setQuery] = React.useState("");
5496
+ const [picked, setPicked] = React.useState([]);
5497
+ const friends = useFriends(pi);
5498
+ const [pickedFriends, setPickedFriends] = React.useState([]);
5499
+ const shared = pickedFriends.length > 0;
5500
+ const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
5501
+ const [busy, setBusy] = React.useState(false);
5502
+ const [error, setError] = React.useState();
5503
+ const Dialog = pi.ui.Dialog;
5504
+ const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
5505
+ const full = picked.length >= MAX_MEMBERS;
5506
+ const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
5507
+ const create = (event) => {
5508
+ event.preventDefault();
5509
+ setBusy(true);
5510
+ setError(undefined);
5511
+ if (shared) {
5512
+ createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
5513
+ setBusy(false);
5514
+ setError(ChannelViews.message(failure));
5515
+ });
5583
5516
  return;
5584
5517
  }
5585
- const watch = () => document.visibilityState === "visible" && void service.watch(channelId).catch(() => {
5586
- return;
5518
+ service.createChannel({ name, members: picked }).then((channel) => {
5519
+ onClose();
5520
+ context.showChannel(channel.id);
5521
+ }, (failure) => {
5522
+ setBusy(false);
5523
+ setError(ChannelViews.message(failure));
5587
5524
  });
5588
- watch();
5589
- const timer = setInterval(watch, WATCH_MS);
5590
- document.addEventListener("visibilitychange", watch);
5591
- return () => {
5592
- clearInterval(timer);
5593
- document.removeEventListener("visibilitychange", watch);
5594
- };
5595
- }, [service, channelId]);
5596
- const sent = React.useMemo(() => messages?.filter((message) => message.author === USER).length ?? 0, [messages]);
5597
- const list = pi.ui.useChatScroll(sent, channelId);
5598
- const [notice, setNotice] = React.useState({ open: false, editing: false });
5599
- React.useEffect(() => setNotice({ open: false, editing: false }), [channelId]);
5600
- const Markdown = pi.ui.Markdown;
5601
- const Composer = pi.ui.Composer;
5602
- const Avatar = pi.ui.Avatar;
5603
- if (!channel) {
5604
- return /* @__PURE__ */ React.createElement("div", {
5605
- className: "tac-room-page"
5606
- }, state.loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5607
- title: w.pick
5608
- }));
5609
- }
5610
- const members = membersOf(state.team, channel);
5611
- const agentOf = (id) => state.team.agents.find((agent) => agent.id === id);
5612
- const reply = ChannelsText.replyOf(channel);
5613
- const lead = members.find((agent) => !(channel.muted ?? []).includes(agent.id));
5614
- const placeholder = reply === "all" ? w.placeholderAll : reply === "lead" && lead ? w.placeholderLead : w.placeholder;
5615
- const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5616
- const time = (at) => SidebarUtil.time(at, pi.ui.language);
5617
- return /* @__PURE__ */ React.createElement("div", {
5618
- className: "tac-room-page"
5619
- }, /* @__PURE__ */ React.createElement(NoticeBar, {
5620
- context,
5621
- channel,
5622
- state: notice,
5623
- onState: setNotice
5624
- }), /* @__PURE__ */ React.createElement("div", {
5625
- className: "tac-chat ta-conversation",
5626
- ref: list
5627
- }, /* @__PURE__ */ React.createElement("div", {
5628
- className: "tac-chat-col"
5629
- }, messages && messages.length === 0 && /* @__PURE__ */ React.createElement("div", {
5630
- className: "tac-chat-empty"
5631
- }, /* @__PURE__ */ React.createElement(RoomFace, {
5632
- members,
5633
- faces,
5634
- size: 56,
5635
- working
5636
- }), /* @__PURE__ */ React.createElement("strong", null, channel.name), channel.topic && /* @__PURE__ */ React.createElement("span", null, channel.topic), /* @__PURE__ */ React.createElement("span", {
5637
- className: "tac-chat-hint"
5638
- }, w.quiet)), messages && RoomUtil.rows(messages).map(({ message, first, separator }) => /* @__PURE__ */ React.createElement(React.Fragment, {
5639
- key: message.id
5640
- }, separator && /* @__PURE__ */ React.createElement("div", {
5641
- className: "tac-chat-time"
5642
- }, time(message.at)), message.author === SYSTEM ? /* @__PURE__ */ React.createElement(StopLine, {
5643
- context,
5644
- channel,
5645
- message,
5646
- agents: state.team.agents,
5647
- later: messages.some((other) => other.at > message.at && (other.author === USER || other.author === TA))
5648
- }) : message.notice ? /* @__PURE__ */ React.createElement("button", {
5649
- type: "button",
5650
- className: "tac-notice tac-notice-line",
5651
- disabled: !channel.notice,
5652
- onClick: () => setNotice({ open: true, editing: false })
5653
- }, ChannelWords.format(message.notice === "cleared" ? w.noticeCleared : w.noticeUpdated, { name: name(message.author) })) : message.author === USER && (message.by ?? TA_OWNER) !== me ? /* @__PURE__ */ React.createElement("div", {
5654
- className: `tac-msg${first ? " tac-first" : ""}`
5655
- }, /* @__PURE__ */ React.createElement("div", {
5656
- className: "tac-msg-face"
5657
- }, first && pi.ui.Face && /* @__PURE__ */ React.createElement(pi.ui.Face, {
5658
- seed: message.by ?? TA_OWNER,
5659
- double: (message.by ?? TA_OWNER) === TA_OWNER,
5660
- size: 28
5661
- })), /* @__PURE__ */ React.createElement("div", {
5662
- className: "tac-msg-col"
5663
- }, first && /* @__PURE__ */ React.createElement("div", {
5664
- className: "tac-msg-name"
5665
- }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement(MessagePictures, {
5666
- context,
5667
- channelId: channel.id,
5668
- message,
5669
- alt: message.byName ?? w.owner
5670
- }), message.text && /* @__PURE__ */ React.createElement("div", {
5671
- className: "tac-msg-bubble",
5672
- title: time(message.at)
5673
- }, /* @__PURE__ */ React.createElement(Mentions, {
5674
- text: message.text,
5675
- agents: state.team.agents
5676
- })))) : message.author === USER ? /* @__PURE__ */ React.createElement("div", {
5677
- className: "ta-message ta-user tac-mine"
5678
- }, /* @__PURE__ */ React.createElement(MessagePictures, {
5679
- context,
5680
- channelId: channel.id,
5681
- message,
5682
- alt: w.you
5683
- }), message.text && /* @__PURE__ */ React.createElement("div", {
5684
- className: "ta-bubble"
5685
- }, /* @__PURE__ */ React.createElement(Mentions, {
5686
- text: message.text,
5687
- agents: state.team.agents
5688
- }))) : /* @__PURE__ */ React.createElement("div", {
5689
- className: `tac-msg${first ? " tac-first" : ""}`
5690
- }, /* @__PURE__ */ React.createElement("div", {
5691
- className: "tac-msg-face"
5692
- }, first && (message.author === TA ? /* @__PURE__ */ React.createElement(Avatar, {
5693
- size: 28
5694
- }) : /* @__PURE__ */ React.createElement(AgentAvatar, {
5695
- agent: agentOf(message.author),
5696
- faces,
5697
- size: 28,
5698
- working: working.includes(message.author)
5699
- }))), /* @__PURE__ */ React.createElement("div", {
5700
- className: "tac-msg-col"
5701
- }, first && /* @__PURE__ */ React.createElement("div", {
5702
- className: "tac-msg-name"
5703
- }, name(message.author), message.author === channel.members[0] && /* @__PURE__ */ React.createElement("span", {
5704
- className: "tac-msg-lead"
5705
- }, w.lead)), /* @__PURE__ */ React.createElement("div", {
5706
- className: `tac-msg-bubble${message.failed ? " tac-failed" : ""}`,
5707
- title: time(message.at)
5708
- }, message.failed && /* @__PURE__ */ React.createElement("div", {
5709
- className: "tac-msg-failed"
5710
- }, w.failed), message.overBudget && /* @__PURE__ */ React.createElement("div", {
5711
- className: "tac-msg-over"
5712
- }, w.overBudget), agentOf(message.author) ? /* @__PURE__ */ React.createElement(AgentText, {
5713
- context,
5714
- channelId: channel.id,
5715
- agent: agentOf(message.author),
5716
- text: ChannelsText.markMentions(message.text, state.team.agents),
5717
- answer: RoomUtil.answer(messages, message, agentOf(message.author))
5718
- }) : /* @__PURE__ */ React.createElement(Markdown, {
5719
- text: ChannelsText.markMentions(message.text, state.team.agents)
5720
- })))))), working.length > 0 && /* @__PURE__ */ React.createElement("div", {
5721
- className: "tac-live",
5722
- role: "status"
5723
- }, /* @__PURE__ */ React.createElement("span", {
5724
- className: "tac-live-faces"
5725
- }, working.map((id) => /* @__PURE__ */ React.createElement(Face, {
5726
- key: id,
5727
- face: faces.get(id) ?? 0,
5728
- size: 18,
5729
- working: true
5730
- }))), ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") })))), /* @__PURE__ */ React.createElement("div", {
5731
- className: "tac-chat-bottom"
5732
- }, /* @__PURE__ */ React.createElement(Composer, {
5733
- placeholder: ChannelWords.format(placeholder, { channel: channel.name, lead: lead?.name ?? "" }),
5734
- draft: channel.id,
5735
- mentions: members.map((agent) => ({ name: agent.name, detail: agent.role.split(`
5736
- `)[0] })),
5737
- mentionLabel: w.mentionMember,
5738
- actions: [
5739
- [
5740
- {
5741
- key: "notice",
5742
- label: w.noticeEdit,
5743
- icon: ChannelViews.maybeIcon(pi, "Megaphone", null, 16),
5744
- run: () => setNotice({ open: true, editing: true })
5745
- },
5746
- {
5747
- key: "add",
5748
- label: w.addMembers,
5749
- icon: ChannelViews.maybeIcon(pi, "UserPlus", null, 16),
5750
- run: () => {
5751
- if (fixed) {
5752
- ui.set({ channelId: fixed });
5753
- }
5754
- context.showMembers(true);
5755
- }
5756
- }
5757
- ],
5758
- [
5759
- {
5760
- key: "make-extension",
5761
- label: w.makeExtension,
5762
- detail: w.makeExtensionDetail,
5763
- icon: ChannelViews.maybeIcon(pi, "Sparkles", null, 16),
5764
- run: () => void service.post(channel.id, w.makeExtensionAsk).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"))
5765
- }
5766
- ]
5767
- ],
5768
- images: { side: 1600, bytes: 1024 * 1024 },
5769
- onSend: (text, images) => service.post(channel.id, text, images ?? [])
5770
- })));
5525
+ };
5526
+ return /* @__PURE__ */ React.createElement(Dialog, {
5527
+ title: w.newChannel,
5528
+ onClose
5529
+ }, /* @__PURE__ */ React.createElement("form", {
5530
+ className: "tac-dialog",
5531
+ onSubmit: create
5532
+ }, /* @__PURE__ */ React.createElement("label", {
5533
+ className: "tac-dialog-label"
5534
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
5535
+ className: "tac-input tac-dialog-input",
5536
+ value: name,
5537
+ placeholder: w.channelNamePlaceholder,
5538
+ maxLength: 40,
5539
+ autoFocus: true,
5540
+ onChange: (event) => setName(event.target.value)
5541
+ })), /* @__PURE__ */ React.createElement("div", {
5542
+ className: "tac-dialog-label"
5543
+ }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
5544
+ className: "tac-dialog-count"
5545
+ }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
5546
+ className: "tac-dialog-search"
5547
+ }, /* @__PURE__ */ React.createElement(Search, {
5548
+ size: 15
5549
+ }), /* @__PURE__ */ React.createElement("input", {
5550
+ value: query,
5551
+ placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
5552
+ "aria-label": w.search,
5553
+ onChange: (event) => setQuery(event.target.value)
5554
+ })), /* @__PURE__ */ React.createElement("div", {
5555
+ className: "tac-pick-list"
5556
+ }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5557
+ compact: true,
5558
+ title: w.noAgents,
5559
+ hint: w.noAgentsHint
5560
+ }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5561
+ compact: true,
5562
+ title: w.noMatch
5563
+ }), shown.map((agent) => {
5564
+ const on = picked.includes(agent.id);
5565
+ return /* @__PURE__ */ React.createElement("button", {
5566
+ key: agent.id,
5567
+ type: "button",
5568
+ "aria-pressed": on,
5569
+ disabled: !on && full,
5570
+ className: `tac-pick${on ? " tac-on" : ""}`,
5571
+ onClick: () => toggle(agent)
5572
+ }, /* @__PURE__ */ React.createElement("span", {
5573
+ className: "tac-check"
5574
+ }, on && /* @__PURE__ */ React.createElement(Check, {
5575
+ size: 13,
5576
+ strokeWidth: 3
5577
+ })), /* @__PURE__ */ React.createElement(AgentAvatar, {
5578
+ agent,
5579
+ faces,
5580
+ size: 30
5581
+ }), /* @__PURE__ */ React.createElement("span", {
5582
+ className: "tac-pick-text"
5583
+ }, /* @__PURE__ */ React.createElement("span", {
5584
+ className: "tac-pick-name"
5585
+ }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
5586
+ className: "tac-msg-lead"
5587
+ }, w.lead)), /* @__PURE__ */ React.createElement("span", {
5588
+ className: "tac-pick-role"
5589
+ }, agent.role.split(`
5590
+ `)[0])));
5591
+ })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
5592
+ className: "tac-dialog-label"
5593
+ }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
5594
+ className: "tac-dialog-count"
5595
+ }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
5596
+ className: "tac-pick-list"
5597
+ }, friends.map((friend) => {
5598
+ const on = pickedFriends.includes(friend.id);
5599
+ return /* @__PURE__ */ React.createElement("button", {
5600
+ key: friend.id,
5601
+ type: "button",
5602
+ "aria-pressed": on,
5603
+ className: `tac-pick${on ? " tac-on" : ""}`,
5604
+ onClick: () => toggleFriend(friend)
5605
+ }, /* @__PURE__ */ React.createElement("span", {
5606
+ className: "tac-check"
5607
+ }, on && /* @__PURE__ */ React.createElement(Check, {
5608
+ size: 13,
5609
+ strokeWidth: 3
5610
+ })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
5611
+ seed: friend.id,
5612
+ size: 30,
5613
+ look: friend.look
5614
+ }) : /* @__PURE__ */ React.createElement("span", {
5615
+ className: "tac-pick-face"
5616
+ }), /* @__PURE__ */ React.createElement("span", {
5617
+ className: "tac-pick-text"
5618
+ }, /* @__PURE__ */ React.createElement("span", {
5619
+ className: "tac-pick-name"
5620
+ }, friend.name), /* @__PURE__ */ React.createElement("span", {
5621
+ className: "tac-pick-role"
5622
+ }, w.friend)));
5623
+ }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
5624
+ className: "tac-dialog-note"
5625
+ }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
5626
+ className: "tac-empty tac-error"
5627
+ }, error), /* @__PURE__ */ React.createElement("div", {
5628
+ className: "tac-dialog-actions"
5629
+ }, /* @__PURE__ */ React.createElement("button", {
5630
+ type: "submit",
5631
+ className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
5632
+ disabled: busy || !name.trim() || picked.length === 0 && !shared
5633
+ }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
5634
+ className: "ta-spinner ta-busy-mark ta-on-brand"
5635
+ })))));
5771
5636
  }
5772
5637
 
5773
- // web-src/tasks.tsx
5774
- var BUILDING_MS = 60 * 1000;
5638
+ // web-src/handoff.ts
5639
+ var HandOff;
5640
+ ((HandOff) => {
5641
+ HandOff.TOOL = "hand_off";
5642
+ HandOff.CARD = "ta-channels-handoff";
5643
+ HandOff.BLOCK = "ta-handoff";
5644
+ const MARK = /\[ta-handoff:([^\]\s]+)\]/;
5645
+ HandOff.DEFINITION = {
5646
+ name: HandOff.TOOL,
5647
+ label: "Hand off",
5648
+ 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.",
5649
+ promptSnippet: "Hand the work over to one of the user's agents or channels",
5650
+ parameters: {
5651
+ type: "object",
5652
+ properties: {
5653
+ to: { type: "string", description: "@name of an agent or #name of a channel." },
5654
+ brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
5655
+ },
5656
+ required: ["to", "brief"]
5657
+ }
5658
+ };
5659
+ function ref(target) {
5660
+ return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
5661
+ }
5662
+ HandOff.ref = ref;
5663
+ function ask(language, to) {
5664
+ const fence = "```";
5665
+ const context = [
5666
+ `[ta-handoff:${to}]`,
5667
+ `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
5668
+ `- 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.`,
5669
+ `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
5670
+ `- 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):`,
5671
+ `${fence}${HandOff.BLOCK}`,
5672
+ "<the brief>",
5673
+ fence,
5674
+ `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
5675
+ ].join(`
5676
+ `);
5677
+ const line = TaLanguageUtil.pick(language, {
5678
+ "zh-CN": `把这件事交给 ${to}`,
5679
+ "zh-TW": `把這件事交給 ${to}`,
5680
+ "en-US": `Hand this over to ${to}`,
5681
+ "ja-JP": `これを ${to} に引き継ぐ`
5682
+ });
5683
+ return TaMessageContext.wrap(context, line);
5684
+ }
5685
+ HandOff.ask = ask;
5686
+ function asked(text) {
5687
+ return MARK.exec(text)?.[1];
5688
+ }
5689
+ HandOff.asked = asked;
5690
+ function find(text) {
5691
+ const lines = text.split(/\r?\n/);
5692
+ let found;
5693
+ for (let index = 0;index < lines.length; index++) {
5694
+ const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
5695
+ if (open?.[2] !== HandOff.BLOCK) {
5696
+ continue;
5697
+ }
5698
+ const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
5699
+ const end = lines.findIndex((line, at) => at > index && close.test(line));
5700
+ found = lines.slice(index + 1, end < 0 ? lines.length : end);
5701
+ index = end < 0 ? lines.length : end;
5702
+ }
5703
+ const brief = found?.join(`
5704
+ `).trim();
5705
+ return brief || undefined;
5706
+ }
5707
+ HandOff.find = find;
5708
+ function message(origin, brief, language) {
5709
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
5710
+ const head = TaLanguageUtil.pick(language, {
5711
+ "zh-CN": `(交接自“${title}”)`,
5712
+ "zh-TW": `(交接自「${title}」)`,
5713
+ "en-US": `(Handed over from “${title}”)`,
5714
+ "ja-JP": `(“${title}” から引き継ぎました)`
5715
+ });
5716
+ const context = [
5717
+ "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.",
5718
+ 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.` : ""
5719
+ ].filter(Boolean).join(`
5720
+ `);
5721
+ return TaMessageContext.wrap(context, `${head}
5722
+
5723
+ ${brief.trim()}`);
5724
+ }
5725
+ HandOff.message = message;
5726
+ function channelText(origin, brief, language) {
5727
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
5728
+ return `${TaLanguageUtil.pick(language, {
5729
+ "zh-CN": `(交接自“${title}”)`,
5730
+ "zh-TW": `(交接自「${title}」)`,
5731
+ "en-US": `(Handed over from “${title}”)`,
5732
+ "ja-JP": `(“${title}” から引き継ぎました)`
5733
+ })}
5734
+
5735
+ ${brief.trim()}`;
5736
+ }
5737
+ HandOff.channelText = channelText;
5738
+ function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
5739
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
5740
+ }
5741
+ HandOff.serverLanguage = serverLanguage;
5742
+ function result(target) {
5743
+ 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.`;
5744
+ }
5745
+ HandOff.result = result;
5746
+ })(HandOff ||= {});
5775
5747
 
5776
- class ChannelTaskSource {
5777
- context;
5778
- shown = new Map;
5779
- list = [];
5780
- listeners = new Set;
5781
- reading = new Set;
5782
- stop;
5783
- constructor(context) {
5784
- this.context = context;
5748
+ // web-src/handoff-view.tsx
5749
+ var HandOffViewUtil;
5750
+ ((HandOffViewUtil) => {
5751
+ function members(team, target) {
5752
+ if (target.kind === "agent") {
5753
+ const agent = team.agents.find((candidate) => candidate.id === target.id);
5754
+ return agent ? [agent] : [];
5755
+ }
5756
+ const channel = team.channels.find((candidate) => candidate.id === target.id);
5757
+ return channel ? membersOf(team, channel) : [];
5785
5758
  }
5786
- tasks() {
5787
- return this.list;
5759
+ HandOffViewUtil.members = members;
5760
+ })(HandOffViewUtil ||= {});
5761
+ function useTeam(context) {
5762
+ return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
5763
+ }
5764
+ function HandOffCard({ context, message }) {
5765
+ const card = message.details;
5766
+ const team = useTeam(context);
5767
+ const faces = useFaces(team);
5768
+ if (!card?.target) {
5769
+ return null;
5788
5770
  }
5789
- subscribe(listener) {
5790
- if (this.listeners.size === 0) {
5791
- this.stop = this.context.service.subscribe((state) => this.build(state));
5792
- this.build(this.context.service.state);
5771
+ const w = ChannelViews.words(context.pi);
5772
+ const members = HandOffViewUtil.members(team, card.target);
5773
+ 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);
5774
+ return /* @__PURE__ */ React.createElement("div", {
5775
+ className: "tac-handoff"
5776
+ }, /* @__PURE__ */ React.createElement("div", {
5777
+ className: "tac-handoff-head"
5778
+ }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
5779
+ members,
5780
+ faces,
5781
+ size: 20,
5782
+ working: []
5783
+ }), /* @__PURE__ */ React.createElement("span", {
5784
+ className: "tac-handoff-title"
5785
+ }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
5786
+ type: "button",
5787
+ className: "tac-link",
5788
+ onClick: open
5789
+ }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
5790
+ className: "tac-handoff-brief"
5791
+ }, card.brief));
5792
+ }
5793
+ var HandOffView;
5794
+ ((HandOffView) => {
5795
+ function card(context) {
5796
+ return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
5797
+ context,
5798
+ message
5799
+ });
5800
+ }
5801
+ HandOffView.card = card;
5802
+ function icon(context, target, icons) {
5803
+ const key = `${target.kind}:${target.id}`;
5804
+ let node2 = icons.get(key);
5805
+ if (!node2) {
5806
+ const Face2 = () => {
5807
+ const team = useTeam(context);
5808
+ const faces = useFaces(team);
5809
+ const members = HandOffViewUtil.members(team, target);
5810
+ return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
5811
+ members,
5812
+ faces,
5813
+ size: 16,
5814
+ working: []
5815
+ }) : null;
5816
+ };
5817
+ node2 = /* @__PURE__ */ React.createElement(Face2, null);
5818
+ icons.set(key, node2);
5793
5819
  }
5794
- this.listeners.add(listener);
5795
- return () => {
5796
- this.listeners.delete(listener);
5797
- if (this.listeners.size === 0) {
5798
- this.stop?.();
5799
- this.stop = undefined;
5800
- }
5820
+ return node2;
5821
+ }
5822
+ function composerAddon(context) {
5823
+ const icons = new Map;
5824
+ const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
5825
+ clientMessageId: ChannelsUtil.newId("handoff-ask"),
5826
+ message: HandOff.ask(context.pi.ui.language, to),
5827
+ streamingBehavior: "followUp"
5828
+ }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
5829
+ return {
5830
+ actions: (conversation) => {
5831
+ const { team } = context.service.state;
5832
+ if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
5833
+ return [];
5834
+ }
5835
+ const w = ChannelViews.words(context.pi);
5836
+ const Forward = ChannelViews.icon(context.pi, "Forward");
5837
+ const agents = ChannelsUtil.standing(team).map((agent) => ({
5838
+ key: `handoff:agent:${agent.id}`,
5839
+ label: agent.name,
5840
+ detail: agent.role.split(`
5841
+ `)[0],
5842
+ group: w.agents,
5843
+ icon: icon(context, { kind: "agent", id: agent.id }, icons),
5844
+ run: () => send(conversation, `@${agent.name}`)
5845
+ }));
5846
+ const channels = team.channels.map((channel) => ({
5847
+ key: `handoff:channel:${channel.id}`,
5848
+ label: `#${channel.name}`,
5849
+ detail: channel.topic,
5850
+ group: w.channels,
5851
+ icon: icon(context, { kind: "channel", id: channel.id }, icons),
5852
+ run: () => send(conversation, `#${channel.name}`)
5853
+ }));
5854
+ return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
5855
+ size: 16
5856
+ }), items: [...agents, ...channels] }];
5857
+ },
5858
+ subscribe: (listener) => context.service.subscribe(listener)
5801
5859
  };
5802
5860
  }
5803
- refresh() {
5804
- this.shown.clear();
5805
- this.build(this.context.service.state);
5861
+ HandOffView.composerAddon = composerAddon;
5862
+ })(HandOffView ||= {});
5863
+
5864
+ // web-src/round-rules.ts
5865
+ var ChannelRounds;
5866
+ ((ChannelRounds) => {
5867
+ const SHORT = 20;
5868
+ const MIN_PAIRS = 8;
5869
+ const ALIKE = 0.8;
5870
+ const PING_PONG = 4;
5871
+ const NEW = 0.35;
5872
+ const CHANGES = new Set(["edit", "write", "delete", "move"]);
5873
+ function scale(watchedAt, pages, now) {
5874
+ if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
5875
+ return 2;
5876
+ }
5877
+ return pages === undefined || pages > 0 ? 1 : 0.5;
5806
5878
  }
5807
- build(state) {
5808
- const { team } = state;
5809
- const faces = ChannelsUtil.faces(team.agents);
5810
- const next = new Map;
5811
- const channels = ChannelsUtil.taskChannels(team);
5812
- let changed = channels.length !== this.list.length;
5813
- const list = channels.map((channel, index) => {
5814
- const messages = state.messages[channel.id];
5815
- if (!messages) {
5816
- this.read(channel.id);
5879
+ ChannelRounds.scale = scale;
5880
+ function idle(said, progress) {
5881
+ const last = said.at(-1);
5882
+ if (!last) {
5883
+ return;
5884
+ }
5885
+ const pairs = said.map((item) => pairsOf(item.text));
5886
+ const mine = pairs[pairs.length - 1];
5887
+ if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
5888
+ return "repeat";
5889
+ }
5890
+ const recent = said.slice(-3);
5891
+ if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
5892
+ return "agree";
5893
+ }
5894
+ const run = said.slice(-PING_PONG);
5895
+ const authors = new Set(run.map((item) => item.author));
5896
+ const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
5897
+ const start = said.length - PING_PONG;
5898
+ if (progress || start <= 0 || authors.size !== 2 || !alternate) {
5899
+ return;
5900
+ }
5901
+ const seen = new Set(pairs.slice(0, start).flat());
5902
+ for (const own of pairs.slice(start)) {
5903
+ const fresh = own.filter((pair) => !seen.has(pair)).length;
5904
+ if (own.length === 0 || fresh / own.length >= NEW) {
5905
+ return;
5817
5906
  }
5818
- const members = membersOf(team, channel);
5819
- const working = state.working[channel.id] ?? [];
5820
- const { status, detail, endedAt } = this.status(state, channel, messages, working);
5821
- const signature = members.map((agent) => `${agent.id}:${faces.get(agent.id)}:${working.includes(agent.id) ? 1 : 0}`).join(",");
5822
- const before = this.shown.get(channel.id);
5823
- const shown = before && before.channel === channel && before.faces === signature && before.status === status && before.detail === detail && before.endedAt === endedAt ? before : {
5824
- channel,
5825
- members,
5826
- faces: signature,
5827
- status,
5828
- detail,
5829
- endedAt,
5830
- entry: this.entry(channel, members, faces, working, status, detail, endedAt)
5831
- };
5832
- next.set(channel.id, shown);
5833
- changed ||= shown.entry !== this.list[index];
5834
- return shown.entry;
5835
- });
5836
- this.shown = next;
5837
- if (!changed) {
5907
+ for (const pair of own) {
5908
+ seen.add(pair);
5909
+ }
5910
+ }
5911
+ return "pingPong";
5912
+ }
5913
+ ChannelRounds.idle = idle;
5914
+ function day(now) {
5915
+ const date = new Date(now);
5916
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
5917
+ }
5918
+ ChannelRounds.day = day;
5919
+ function limits(stored) {
5920
+ const given = stored ?? {};
5921
+ const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
5922
+ return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
5923
+ }
5924
+ ChannelRounds.limits = limits;
5925
+ function today(stored, now) {
5926
+ const current = day(now);
5927
+ return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
5928
+ }
5929
+ ChannelRounds.today = today;
5930
+ function spend(stored, channelId, tokens, now) {
5931
+ const current = today(stored, now);
5932
+ return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
5933
+ }
5934
+ ChannelRounds.spend = spend;
5935
+ function held(spent, limits2, channelId, hops, granted = false) {
5936
+ if (granted) {
5838
5937
  return;
5839
5938
  }
5840
- this.list = list;
5841
- for (const listener of this.listeners) {
5842
- listener();
5939
+ if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
5940
+ return "all";
5941
+ }
5942
+ if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
5943
+ return "channel";
5944
+ }
5945
+ return;
5946
+ }
5947
+ ChannelRounds.held = held;
5948
+ function changedFiles(entries) {
5949
+ for (const entry of entries) {
5950
+ const message = entry?.message;
5951
+ if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
5952
+ continue;
5953
+ }
5954
+ for (const part of message.content) {
5955
+ if (part?.type !== "toolCall") {
5956
+ continue;
5957
+ }
5958
+ if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
5959
+ return true;
5960
+ }
5961
+ }
5843
5962
  }
5963
+ return false;
5844
5964
  }
5845
- read(channelId) {
5846
- if (!this.reading.has(channelId)) {
5847
- this.reading.add(channelId);
5848
- this.context.service.messages(channelId).catch(() => this.reading.delete(channelId));
5849
- }
5965
+ ChannelRounds.changedFiles = changedFiles;
5966
+ function units(text) {
5967
+ return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
5850
5968
  }
5851
- status(state, channel, messages, working) {
5852
- const w = ChannelViews.words(this.context.pi);
5853
- const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5854
- if (working.length > 0) {
5855
- return { status: "running", detail: ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") }) };
5969
+ function pairsOf(text) {
5970
+ const words = units(text);
5971
+ return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
5972
+ }
5973
+ function alike(a, b) {
5974
+ if (a.length === 0 || b.length === 0) {
5975
+ return 0;
5856
5976
  }
5857
- const last = messages?.at(-1);
5858
- if (!last) {
5859
- const building = Date.now() - channel.createdAt < BUILDING_MS;
5860
- return building ? { status: "running", detail: w.building } : { status: "done", detail: channel.topic || w.noMessages, endedAt: channel.createdAt };
5977
+ const left = new Map;
5978
+ for (const pair of a) {
5979
+ left.set(pair, (left.get(pair) ?? 0) + 1);
5861
5980
  }
5862
- if (last.author === SYSTEM) {
5863
- return { status: "waiting", detail: w.yourTurn };
5981
+ let common = 0;
5982
+ for (const pair of b) {
5983
+ const n = left.get(pair) ?? 0;
5984
+ if (n > 0) {
5985
+ left.set(pair, n - 1);
5986
+ common++;
5987
+ }
5864
5988
  }
5865
- const said = `${name(last.author)}:${last.text.replace(/\s+/g, " ").slice(0, 120)}`;
5866
- return { status: last.failed ? "failed" : "done", detail: said, endedAt: last.at };
5867
- }
5868
- entry(channel, members, faces, working, status, detail, endedAt) {
5869
- return {
5870
- id: channel.id,
5871
- title: taskTitle(channel),
5872
- status,
5873
- detail,
5874
- startedAt: channel.createdAt,
5875
- endedAt: status === "running" || status === "waiting" ? undefined : endedAt,
5876
- origin: channel.origin,
5877
- icon: ({ size }) => /* @__PURE__ */ React.createElement(RoomFace, {
5878
- members,
5879
- faces,
5880
- size,
5881
- working
5882
- }),
5883
- open: () => openScene(this.context, channel),
5884
- show: () => this.context.showChannel(channel.id),
5885
- menu: () => taskMenu(this.context, channel, working),
5886
- remove: () => deleteTeam(this.context, channel),
5887
- removeHint: ChannelWords.format(ChannelViews.words(this.context.pi).deleteTaskHint, { channel: channel.name })
5888
- };
5989
+ return 2 * common / (a.length + b.length);
5889
5990
  }
5991
+ })(ChannelRounds ||= {});
5992
+
5993
+ // web-src/limit-settings.tsx
5994
+ function amount(pi, tokens) {
5995
+ return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
5890
5996
  }
5891
- function taskTitle(channel) {
5892
- return channel.name;
5893
- }
5894
- async function deleteTeam(context, channel) {
5895
- await context.service.deleteChannel(channel.id);
5896
- context.pi.ui.closeEditor(`channel:${channel.id}`);
5897
- }
5898
- function openScene(context, channel) {
5899
- context.pi.ui.openEditor({
5900
- id: `channel:${channel.id}`,
5901
- title: channel.name,
5902
- icon: ChannelViews.icon(context.pi, "Hash"),
5903
- render: () => /* @__PURE__ */ React.createElement("div", {
5904
- className: "tac-scene"
5905
- }, /* @__PURE__ */ React.createElement(ChannelSceneHead, {
5906
- context,
5907
- channelId: channel.id
5908
- }), /* @__PURE__ */ React.createElement(ChannelRoom, {
5909
- context,
5910
- channelId: channel.id
5911
- }))
5912
- });
5997
+ function useLimits(pi) {
5998
+ const read = React.useCallback(async () => ({
5999
+ limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
6000
+ ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
6001
+ }), [pi]);
6002
+ const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
6003
+ React.useEffect(() => {
6004
+ let live = true;
6005
+ const load = () => void read().then((next) => live && setValue(next), () => {
6006
+ return;
6007
+ });
6008
+ load();
6009
+ const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
6010
+ return () => {
6011
+ live = false;
6012
+ stop();
6013
+ };
6014
+ }, [pi, read]);
6015
+ return value;
5913
6016
  }
5914
- function taskMenu(context, channel, working) {
5915
- const { pi, service } = context;
5916
- const w = ChannelViews.words(pi);
5917
- const icon = (name) => ChannelViews.icon(pi, name);
5918
- const act = (action2) => () => {
5919
- Promise.resolve().then(action2).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"));
6017
+ function limitSettings(pi, service) {
6018
+ const words = () => ChannelWords.of(pi.ui.language);
6019
+ const row = (key) => function Choices() {
6020
+ const { limits } = useLimits(pi);
6021
+ const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
6022
+ return /* @__PURE__ */ React.createElement("fieldset", {
6023
+ className: "ta-segmented",
6024
+ "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
6025
+ }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
6026
+ key: value,
6027
+ type: "button",
6028
+ "aria-pressed": limits[key] === value,
6029
+ className: limits[key] === value ? "ta-on" : "",
6030
+ onClick: () => pick(value)
6031
+ }, amount(pi, value))));
5920
6032
  };
5921
- const temporary = membersOf(service.state.team, channel).filter((agent) => agent.temporary);
5922
- return [
5923
- working.length > 0 ? [
5924
- {
5925
- key: "stop",
5926
- label: w.stopAnswering,
5927
- icon: icon("Square"),
5928
- run: act(async () => {
5929
- await TeamActions.stop(context, working);
5930
- pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info");
5931
- })
5932
- }
5933
- ] : [],
5934
- [
5935
- { key: "main", label: w.openInMain, icon: icon("ExternalLink"), run: () => context.showChannel(channel.id) },
5936
- ...temporary.length > 0 ? [
5937
- {
5938
- key: "keep",
5939
- label: w.keepMembers,
5940
- icon: icon("UserPlus"),
5941
- run: act(async () => {
5942
- await TeamActions.keep(context, temporary);
5943
- pi.ui.notify(ChannelWords.format(w.keptMembers, { names: temporary.map((agent) => `@${agent.name}`).join("、") }), "info");
5944
- })
5945
- }
5946
- ] : []
5947
- ],
5948
- [
5949
- {
5950
- key: "delete",
5951
- label: w.deleteTask,
5952
- icon: icon("Trash2"),
5953
- danger: true,
5954
- run: act(() => pi.ui.removeTasks([
5955
- {
5956
- title: taskTitle(channel),
5957
- removeHint: ChannelWords.format(w.deleteTaskHint, { channel: channel.name }),
5958
- remove: () => deleteTeam(context, channel)
5959
- }
5960
- ]))
5961
- }
6033
+ function Spent() {
6034
+ const { spent } = useLimits(pi);
6035
+ return /* @__PURE__ */ React.createElement("span", {
6036
+ className: "tac-limit-spent"
6037
+ }, spent > 0 ? amount(pi, spent) : "0");
6038
+ }
6039
+ return {
6040
+ title: () => words().limitsTitle,
6041
+ icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
6042
+ group: "ta",
6043
+ rows: [
6044
+ { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
6045
+ { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
6046
+ { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
6047
+ { key: "spent", label: () => words().limitSpent, render: Spent }
5962
6048
  ]
5963
- ];
6049
+ };
5964
6050
  }
5965
- var TeamActions;
5966
- ((TeamActions) => {
5967
- async function stop(context, agentIds) {
5968
- const { pi, service } = context;
5969
- const files = new Set(service.state.team.agents.filter((agent) => agentIds.includes(agent.id) && agent.sessionFile).map((agent) => agent.sessionFile));
5970
- const sessions = (await pi.server.listSessions()).filter((session) => session.sessionFile && files.has(session.sessionFile));
5971
- await Promise.all(sessions.map((session) => pi.server.abort(session.sessionId)));
5972
- }
5973
- TeamActions.stop = stop;
5974
- async function keep(context, agents) {
5975
- for (const agent of agents) {
5976
- await context.service.updateAgent(agent.id, { keep: true });
5977
- }
5978
- }
5979
- TeamActions.keep = keep;
5980
- })(TeamActions ||= {});
5981
6051
 
5982
6052
  // web-src/channel-menu.tsx
5983
6053
  function download2(name, text) {
@@ -6565,7 +6635,27 @@ class ChannelPartners {
6565
6635
  if (!ChannelsUtil.may(service.state.team).create) {
6566
6636
  return [];
6567
6637
  }
6568
- return [{ key: "agent", label: ChannelViews.words(pi).newAgent, icon: ChannelViews.icon(pi, "Bot"), run: () => newAgent(this.context) }];
6638
+ const w = ChannelViews.words(pi);
6639
+ const { agents, removed } = service.state.team;
6640
+ return [
6641
+ { key: "agent", label: w.newAgent, icon: ChannelViews.icon(pi, "Bot"), run: () => newAgent(this.context) },
6642
+ ...agents.length ? [
6643
+ {
6644
+ key: "optimize",
6645
+ label: w.optimizeAll,
6646
+ icon: ChannelViews.icon(pi, "Sparkles"),
6647
+ run: AgentActions.run(this.context, () => AgentActions.optimize(this.context))
6648
+ }
6649
+ ] : [],
6650
+ ...removed?.length ? [
6651
+ {
6652
+ key: "removed",
6653
+ label: ChannelWords.format(w.removedAgents, { n: String(removed.length) }),
6654
+ icon: ChannelViews.icon(pi, "Archive"),
6655
+ run: () => void pi.ui.showView(REMOVED_VIEW)
6656
+ }
6657
+ ] : []
6658
+ ];
6569
6659
  }
6570
6660
  async group(members) {
6571
6661
  if (!members.every((member) => member.extension === NAME && member.kind === "agent")) {
@@ -6749,6 +6839,63 @@ class ChannelPartners {
6749
6839
  }
6750
6840
  }
6751
6841
 
6842
+ // web-src/removed-view.tsx
6843
+ var DAY_MS = 24 * 60 * 60000;
6844
+ function RemovedAgentsView({ context }) {
6845
+ const { pi, service } = context;
6846
+ const { team, loaded } = useChannels(service);
6847
+ const w = ChannelViews.words(pi);
6848
+ const [busy, setBusy] = React.useState();
6849
+ const removed = [...team.removed ?? []].reverse();
6850
+ const restore = (one) => {
6851
+ setBusy(one.agent.id);
6852
+ service.restoreAgent(one.agent.id).then((agent) => pi.ui.notify(ChannelWords.format(w.restored, { name: agent.name }), "info")).catch((error) => pi.ui.notify(ChannelViews.message(error), "error")).finally(() => setBusy(undefined));
6853
+ };
6854
+ if (!removed.length) {
6855
+ return /* @__PURE__ */ React.createElement("div", {
6856
+ className: "tac-view tac-members"
6857
+ }, loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
6858
+ title: w.noRemoved
6859
+ }));
6860
+ }
6861
+ return /* @__PURE__ */ React.createElement("div", {
6862
+ className: "tac-view tac-members"
6863
+ }, /* @__PURE__ */ React.createElement("div", {
6864
+ className: "tac-members-scroll"
6865
+ }, /* @__PURE__ */ React.createElement("div", {
6866
+ className: "tac-members-note"
6867
+ }, w.removedHint), removed.map((one) => {
6868
+ const days = Math.floor((Date.now() - one.at) / DAY_MS);
6869
+ const channels = [...one.channels.flatMap((id) => team.channels.filter((channel) => channel.id === id)), ...one.gone].map((channel) => `#${channel.name}`);
6870
+ const detail = [
6871
+ days < 1 ? w.removedToday : ChannelWords.format(w.removedAt, { days: String(days) }),
6872
+ ...channels.length ? [ChannelWords.format(w.removedIn, { channels: channels.join("、") })] : []
6873
+ ].join(" · ");
6874
+ return /* @__PURE__ */ React.createElement("div", {
6875
+ key: one.agent.id,
6876
+ className: "tac-member tac-removed"
6877
+ }, /* @__PURE__ */ React.createElement("div", {
6878
+ className: "tac-member-main"
6879
+ }, /* @__PURE__ */ React.createElement(Face, {
6880
+ face: one.agent.face ?? 0,
6881
+ size: 32
6882
+ }), /* @__PURE__ */ React.createElement("span", {
6883
+ className: "tac-member-text"
6884
+ }, /* @__PURE__ */ React.createElement("span", {
6885
+ className: "tac-member-name"
6886
+ }, /* @__PURE__ */ React.createElement("span", {
6887
+ className: "tac-member-label"
6888
+ }, one.agent.name)), /* @__PURE__ */ React.createElement("span", {
6889
+ className: "tac-member-detail"
6890
+ }, detail))), /* @__PURE__ */ React.createElement("button", {
6891
+ type: "button",
6892
+ className: "tac-link tac-restore",
6893
+ disabled: !!busy,
6894
+ onClick: () => restore(one)
6895
+ }, w.restore));
6896
+ })));
6897
+ }
6898
+
6752
6899
  // web-src/sidebar-hooks.ts
6753
6900
  var FOLDED_KEY = "ta-channels.folded";
6754
6901
  var BY_DIRECTORY_KEY = "ui.membersByDirectory";
@@ -7872,6 +8019,12 @@ textarea.tac-input { resize: vertical; min-height: 56px; line-height: 1.5; }
7872
8019
  .tac-member-detail { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ta-muted); font-size: calc(12px * var(--ta-font-scale)); line-height: calc(17px * var(--ta-font-scale)); }
7873
8020
  .tac-member-detail.tac-live { color: var(--ta-green); }
7874
8021
  .tac-member.tac-muted .tac-member-main > :first-child { opacity: 0.5; }
8022
+ .tac-removed:hover, .tac-removed:focus-within { background: none; }
8023
+ .tac-removed .tac-member-main { cursor: default; }
8024
+ .tac-removed .tac-member-main > :first-child { opacity: 0.55; }
8025
+ .tac-restore { flex: none; margin-right: 8px; padding: 4px 10px; border-radius: 8px; background: var(--ta-hover); color: var(--ta-text); font-weight: 500; }
8026
+ .tac-restore:hover { background: var(--ta-hover-strong); }
8027
+ .tac-restore:disabled { opacity: 0.5; cursor: default; }
7875
8028
  .tac-member-actions { display: flex; align-items: center; gap: 2px; flex: none; padding-right: 8px; opacity: 0; transition: opacity 120ms; }
7876
8029
  .tac-member:hover .tac-member-actions, .tac-member:focus-within .tac-member-actions, .tac-member.tac-muted .tac-member-actions { opacity: 1; }
7877
8030
  .tac-member.tac-muted:not(:hover):not(:focus-within) .tac-member-actions > :not(.tac-on) { visibility: hidden; }
@@ -8249,6 +8402,16 @@ function activate(pi) {
8249
8402
  navigation: false,
8250
8403
  order: 61
8251
8404
  });
8405
+ pi.registerView("removed-agents", {
8406
+ title: () => ChannelWords.of(pi.ui.language).removedTitle,
8407
+ icon: ChannelViews.icon(pi, "Archive"),
8408
+ render: () => /* @__PURE__ */ React.createElement(RemovedAgentsView, {
8409
+ context
8410
+ }),
8411
+ location: "panel",
8412
+ navigation: false,
8413
+ order: 62
8414
+ });
8252
8415
  pi.registerView("members", {
8253
8416
  title: () => ChannelWords.of(pi.ui.language).showMembers,
8254
8417
  icon: ChannelViews.icon(pi, "Users"),