@celljs/ta-rooms 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/index.mjs CHANGED
@@ -298,6 +298,7 @@ var DoubleKeys;
298
298
  var GRANT_HOURS = [1, 24, 24 * 7];
299
299
 
300
300
  // ../ta-protocol/esm/common/ta-extension-host.js
301
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
301
302
  var TA_HOST_EVENT = "ta:host";
302
303
  var TaHostUtil;
303
304
  (function(TaHostUtil2) {
@@ -592,7 +593,7 @@ var DoubleUtil;
592
593
  DoubleUtil.id = id;
593
594
  })(DoubleUtil ||= {});
594
595
 
595
- // web-src/double-tasks.ts
596
+ // web-src/double-tasks-base.ts
596
597
  function language() {
597
598
  return TaLanguageUtil.of(process.env.TA_LANGUAGE || process.env.LANG || "");
598
599
  }
@@ -600,7 +601,7 @@ var ATTACH_MS = 1e4;
600
601
  var SWEEP_MS = 60000;
601
602
  var ANSWER_GRACE_MS = 5000;
602
603
 
603
- class RoomTasks {
604
+ class RoomTasksBase {
604
605
  doubles;
605
606
  queues = new Map;
606
607
  running = new Map;
@@ -612,298 +613,6 @@ class RoomTasks {
612
613
  constructor(doubles) {
613
614
  this.doubles = doubles;
614
615
  }
615
- async start() {
616
- const now = this.now();
617
- const lang = language();
618
- const records = await this.update(DoubleKeys.TASKS, (list) => list.map((task) => task.status === "running" ? {
619
- ...task,
620
- status: "failed",
621
- detail: TaLanguageUtil.pick(lang, {
622
- "zh-CN": "Ta 重启了,任务中断",
623
- "zh-TW": "Ta 重啟了,任務中斷",
624
- "en-US": "Ta restarted",
625
- "ja-JP": "Ta が再起動しました"
626
- }),
627
- endedAt: now
628
- } : task));
629
- for (const room of new Set(records.map((task) => task.room))) {
630
- await this.publish(room).catch(() => {
631
- return;
632
- });
633
- }
634
- for (const task of records.filter((each) => each.status === "queued")) {
635
- this.enqueue(task);
636
- }
637
- this.timer = setInterval(() => void this.sweep().catch(() => {
638
- return;
639
- }), SWEEP_MS);
640
- this.timer.unref?.();
641
- }
642
- dispose() {
643
- clearInterval(this.timer);
644
- for (const wake of [...this.attaching.values()].flat()) {
645
- wake();
646
- }
647
- }
648
- async take(room, self, line, quiet) {
649
- const member = room.members.find((each) => each.member === line.from);
650
- if (!member || member.guest) {
651
- return;
652
- }
653
- const known = (await this.list(DoubleKeys.TASKS)).find((task) => task.id === line.id && task.room === room.id);
654
- if (known) {
655
- return;
656
- }
657
- const now = this.now();
658
- let record = {
659
- id: line.id,
660
- room: room.id,
661
- title: room.title,
662
- friend: member.id,
663
- member: member.member,
664
- name: member.name,
665
- text: DoubleUtil.cut(DoubleUtil.unmention(line.text, self.name), 600),
666
- status: "queued",
667
- at: now
668
- };
669
- await this.update(DoubleKeys.TASKS, (list) => {
670
- const open = list.filter((task) => task.friend === member.id && !RoomTasksUtil.ended(task.status)).length;
671
- const lang = language();
672
- const why = quiet ? TaLanguageUtil.pick(lang, {
673
- "zh-CN": "这个房间里分身不回答",
674
- "zh-TW": "這個房間裡分身不回答",
675
- "en-US": "the double keeps quiet here",
676
- "ja-JP": "このルームではダブルは応答しません"
677
- }) : open >= TASKS_OPEN ? TaLanguageUtil.pick(lang, {
678
- "zh-CN": "手上的任务太多了",
679
- "zh-TW": "手上的任務太多了",
680
- "en-US": "too many tasks at once",
681
- "ja-JP": "一度に処理できるタスクが多すぎます"
682
- }) : "";
683
- record = why ? { ...record, status: "declined", detail: why, endedAt: now } : record;
684
- return DoubleUtil.keep([...list, record]);
685
- });
686
- await this.publish(room.id);
687
- if (record.status === "declined") {
688
- const lang = language();
689
- await this.say(room.id, self, TaLanguageUtil.pick(lang, {
690
- "zh-CN": `这个任务我这次不接:${record.detail}。`,
691
- "zh-TW": `這個任務我這次不接:${record.detail}。`,
692
- "en-US": `I cannot take this task now: ${record.detail}.`,
693
- "ja-JP": `今回このタスクは受け取れません:${record.detail}。`
694
- }), line.id);
695
- await this.log(record, { outcome: "limited", error: record.detail });
696
- return;
697
- }
698
- this.enqueue(record);
699
- }
700
- async waiting(friend) {
701
- return (await this.list(DoubleKeys.TASKS)).some((task) => task.friend === friend && task.status === "permission");
702
- }
703
- async granted(friend) {
704
- const waiting = await this.mark((task) => task.friend === friend && task.status === "permission", { status: "queued" });
705
- for (const task of waiting) {
706
- this.enqueue(task, true);
707
- }
708
- }
709
- async refused(friend) {
710
- const lang = language();
711
- await this.mark((task) => task.friend === friend && task.status === "permission", {
712
- status: "declined",
713
- detail: TaLanguageUtil.pick(lang, { "zh-CN": "没有得到授权", "zh-TW": "沒有得到授權", "en-US": "not let", "ja-JP": "許可が得られません" }),
714
- endedAt: this.now()
715
- });
716
- }
717
- async stop(id, detail) {
718
- const [task] = await this.mark((each) => each.id === id && !RoomTasksUtil.ended(each.status), {
719
- status: "stopped",
720
- ...detail ? { detail } : {},
721
- endedAt: this.now()
722
- });
723
- if (!task) {
724
- return;
725
- }
726
- const run = this.running.get(id);
727
- if (run) {
728
- run.turn.active = false;
729
- await this.doubles.host.abort(run.sessionId).catch(() => {
730
- return;
731
- });
732
- }
733
- const self = await this.self(task.room);
734
- if (self) {
735
- const lang = language();
736
- await this.say(task.room, self, TaLanguageUtil.pick(lang, {
737
- "zh-CN": "这个任务停下了。",
738
- "zh-TW": "這個任務停下了。",
739
- "en-US": "This task is stopped.",
740
- "ja-JP": "このタスクは停止しました。"
741
- }), task.id);
742
- }
743
- }
744
- async stopAll(friend) {
745
- for (const task of (await this.list(DoubleKeys.TASKS)).filter((each) => each.friend === friend && !RoomTasksUtil.ended(each.status))) {
746
- await this.stop(task.id);
747
- }
748
- }
749
- async heard(room, key, value, by) {
750
- if (key.startsWith("cancel:")) {
751
- const member = key.slice("cancel:".length);
752
- const ids = RoomTasksUtil.cancelled(member, value, by);
753
- const mine = (await this.list(DoubleKeys.TASKS)).filter((task) => task.room === room && task.member === member && ids.includes(task.id) && !RoomTasksUtil.ended(task.status));
754
- for (const task of mine) {
755
- const lang = language();
756
- await this.stop(task.id, TaLanguageUtil.pick(lang, {
757
- "zh-CN": `${task.name}取消了`,
758
- "zh-TW": `${task.name}取消了`,
759
- "en-US": `called off by ${task.name}`,
760
- "ja-JP": `${task.name}によってキャンセルされました`
761
- }));
762
- }
763
- } else if (key.startsWith(ROOM_TASKS_KEY)) {
764
- await this.sync(room);
765
- }
766
- }
767
- enqueue(task, again = false) {
768
- const before = this.queues.get(task.friend) ?? Promise.resolve();
769
- const next = before.then(() => this.run(task.id, again)).catch((error) => console.error("ta-rooms: a task of a double failed:", error)).finally(() => {
770
- if (this.queues.get(task.friend) === next) {
771
- this.queues.delete(task.friend);
772
- }
773
- });
774
- this.queues.set(task.friend, next);
775
- }
776
- async run(id, again) {
777
- const task = (await this.list(DoubleKeys.TASKS)).find((each) => each.id === id);
778
- if (task?.status !== "queued") {
779
- return;
780
- }
781
- const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === task.room && each.status === "member");
782
- const self = room?.members.find((member) => member.self);
783
- if (!room || !self) {
784
- const lang = language();
785
- await this.mark((each) => each.id === id, {
786
- status: "failed",
787
- detail: TaLanguageUtil.pick(lang, {
788
- "zh-CN": "已经不在这个房间里",
789
- "zh-TW": "已經不在這個房間裡",
790
- "en-US": "not in the room any more",
791
- "ja-JP": "もうこのルームにいません"
792
- }),
793
- endedAt: this.now()
794
- });
795
- return;
796
- }
797
- const now = this.now();
798
- if (!this.doubles.count(room.id, now)) {
799
- const lang = language();
800
- await this.end(task, self, "declined", TaLanguageUtil.pick(lang, {
801
- "zh-CN": "这个小时回答得太多了",
802
- "zh-TW": "這個小時回答得太多了",
803
- "en-US": "too many answers this hour",
804
- "ja-JP": "今時間内に回答が多すぎます"
805
- }));
806
- return;
807
- }
808
- const grants = DoubleUtil.grantsOf(await this.doubles.get(DoubleKeys.GRANTS) ?? [], task.friend, now);
809
- const work = DoubleUtil.work(grants);
810
- const asker = { id: task.friend, member: task.member, name: task.name };
811
- const turn = {
812
- room: room.id,
813
- title: room.title,
814
- asker,
815
- capabilities: work?.capabilities ?? [],
816
- cwd: work?.cwd,
817
- active: true,
818
- tools: [],
819
- task: id
820
- };
821
- await this.mark((each) => each.id === id, { status: "running", detail: undefined });
822
- try {
823
- const me = (await this.doubles.host.rooms.getIdentity()).name;
824
- const cwd = work?.cwd ?? await this.doubles.chatDirectory();
825
- const lang = language();
826
- const name = TaLanguageUtil.pick(lang, {
827
- "zh-CN": `替${task.name}做:${DoubleUtil.cut(task.text, 30)}`,
828
- "zh-TW": `替${task.name}做:${DoubleUtil.cut(task.text, 30)}`,
829
- "en-US": `For ${task.name}: ${DoubleUtil.cut(task.text, 30)}`,
830
- "ja-JP": `${task.name}の代わりに:${DoubleUtil.cut(task.text, 30)}`
831
- });
832
- const { sessionId, sessionFile } = await this.doubles.session(`task:${room.id}:${id}:${cwd}`, cwd, DoubleUtil.role(me, room.title), name);
833
- this.doubles.track(sessionFile, turn);
834
- this.running.set(id, { sessionId, turn });
835
- const before = await this.doubles.host.getState(sessionId);
836
- const chat = await this.doubles.chatOf(room.id);
837
- const line = chat.lines.find((each) => each.id === id) ?? { id, from: task.member, name: task.name, text: task.text, at: task.at };
838
- const nameOf = (each) => each.agent?.name ?? room.members.find((other) => other.member === each.from)?.name ?? each.name;
839
- const permits = [DoubleUtil.permits(me, task.name, work), ...again ? [DoubleUtil.taskAgain(me)] : [], DoubleUtil.taskNote(me, task.name)].join(`
840
- `);
841
- const message = DoubleUtil.prompt({ title: room.title, asker, line, lines: chat.lines, nameOf, permits });
842
- await this.doubles.host.prompt(sessionId, { clientMessageId: `task:${room.id}:${id}:${again ? now : 0}`, message });
843
- await this.doubles.settled(sessionId, before.messageCount, TASK_MS);
844
- if (!turn.active) {
845
- return;
846
- }
847
- const text = (await this.doubles.host.getLastAssistantText(sessionId)).text?.trim();
848
- if (!text) {
849
- const lang2 = language();
850
- throw new Error(TaLanguageUtil.pick(lang2, { "zh-CN": "没有回答", "zh-TW": "沒有回答", "en-US": "No answer.", "ja-JP": "回答がありません。" }));
851
- }
852
- this.doubles.counted(room.id, now);
853
- await this.say(room.id, self, text, id);
854
- const asked = turn.tools.includes("ask_permission");
855
- await this.mark((each) => each.id === id && !RoomTasksUtil.ended(each.status), {
856
- status: asked ? "permission" : "done",
857
- answer: DoubleUtil.clip(text, 1500),
858
- ...asked ? {} : { endedAt: this.now() }
859
- });
860
- await this.log({ ...task, answer: text }, { outcome: "answered", tools: turn.tools, capabilities: turn.capabilities });
861
- } catch (error) {
862
- if (!turn.active) {
863
- return;
864
- }
865
- const reason = error instanceof Error ? error.message : String(error);
866
- await this.end(task, self, "failed", reason);
867
- await this.log(task, { outcome: "failed", error: reason, tools: turn.tools, capabilities: turn.capabilities });
868
- } finally {
869
- turn.active = false;
870
- this.running.delete(id);
871
- }
872
- }
873
- async end(task, self, status, detail) {
874
- await this.mark((each) => each.id === task.id, { status, detail: DoubleUtil.cut(detail, 200), endedAt: this.now() });
875
- const lang = language();
876
- await this.say(task.room, self, TaLanguageUtil.pick(lang, {
877
- "zh-CN": `这个任务没能完成:${detail}`,
878
- "zh-TW": `這個任務沒能完成:${detail}`,
879
- "en-US": `I could not do this task: ${detail}`,
880
- "ja-JP": `このタスクを完了できませんでした:${detail}`
881
- }), task.id);
882
- }
883
- async log(task, outcome) {
884
- await this.doubles.log({
885
- id: DoubleUtil.id("log"),
886
- at: this.now(),
887
- room: task.room,
888
- title: task.title,
889
- friend: task.friend,
890
- name: task.name,
891
- asked: DoubleUtil.cut(task.text, 300),
892
- answer: task.answer ? DoubleUtil.cut(task.answer, 300) : "",
893
- tools: [],
894
- capabilities: [],
895
- task: true,
896
- ...outcome
897
- });
898
- }
899
- async publish(roomId) {
900
- const self = await this.self(roomId);
901
- if (!self) {
902
- return;
903
- }
904
- const tasks = (await this.list(DoubleKeys.TASKS)).filter((task) => task.room === roomId);
905
- await this.doubles.host.rooms.setState(roomId, RoomTasksUtil.key(self.member), tasks.length ? DoubleUtil.published(tasks, roomId) : null);
906
- }
907
616
  async hand(sessionFile, ref, to, text) {
908
617
  const room = await this.doubles.roomOf(ref);
909
618
  const self = room.members.find((member2) => member2.self);
@@ -1155,10 +864,10 @@ class RoomAgents {
1155
864
  const self = room?.members.find((member) => member.self);
1156
865
  if (!room || !self) {
1157
866
  throw new Error(TaLanguageUtil.pick(language(), {
1158
- "zh-CN": "你不在这个房间里。",
1159
- "zh-TW": "你不在這個房間裡。",
867
+ "zh-CN": "你不在这个群里。",
868
+ "zh-TW": "你不在這個群裡。",
1160
869
  "en-US": "You are not in this room.",
1161
- "ja-JP": "このルームにいません。"
870
+ "ja-JP": "このグループチャットにいません。"
1162
871
  }));
1163
872
  }
1164
873
  return { room, self };
@@ -1184,10 +893,10 @@ class RoomAgents {
1184
893
  }
1185
894
  if (mine.length >= AGENTS_MAX) {
1186
895
  throw new Error(TaLanguageUtil.pick(language(), {
1187
- "zh-CN": `一个房间最多邀请 ${AGENTS_MAX} 个智能体。`,
1188
- "zh-TW": `一個房間最多邀請 ${AGENTS_MAX} 個智慧體。`,
896
+ "zh-CN": `一个群聊最多邀请 ${AGENTS_MAX} 个智能体。`,
897
+ "zh-TW": `一個群聊最多邀請 ${AGENTS_MAX} 個智慧體。`,
1189
898
  "en-US": `At most ${AGENTS_MAX} agents in a room.`,
1190
- "ja-JP": `1 つのルームでは最大 ${AGENTS_MAX} 個のエージェントを招待できます。`
899
+ "ja-JP": `1 つのグループチャットでは最大 ${AGENTS_MAX} 個のエージェントを招待できます。`
1191
900
  }));
1192
901
  }
1193
902
  const joined = {
@@ -1219,10 +928,10 @@ class RoomAgents {
1219
928
  const next = mine.filter((each) => each !== gone);
1220
929
  await this.doubles.host.rooms.setState(room.id, RoomAgentsUtil.key(self.member), next.length ? next : null);
1221
930
  await (await this.doubles.chatOf(room.id)).say(TaLanguageUtil.pick(language(), {
1222
- "zh-CN": "我先离开房间了。",
1223
- "zh-TW": "我先離開房間了。",
931
+ "zh-CN": "我先离开群聊了。",
932
+ "zh-TW": "我先離開群聊了。",
1224
933
  "en-US": "I am leaving the room now.",
1225
- "ja-JP": "ルームを離れます。"
934
+ "ja-JP": "グループチャットを離れます。"
1226
935
  }), self, { agent: { id: gone.id, name: gone.name } }).catch(() => {
1227
936
  return;
1228
937
  });
@@ -1288,104 +997,400 @@ class RoomGrants {
1288
997
  if (typeof friend !== "string" || !friend || chosen.length === 0) {
1289
998
  throw new Error("Whom and what to let the double do are needed.");
1290
999
  }
1291
- if (!GRANT_HOURS.includes(Number(hours))) {
1292
- throw new Error(`hours is one of ${GRANT_HOURS.join(", ")}.`);
1000
+ if (!GRANT_HOURS.includes(Number(hours))) {
1001
+ throw new Error(`hours is one of ${GRANT_HOURS.join(", ")}.`);
1002
+ }
1003
+ const directory = String(cwd ?? "").trim();
1004
+ if (!isAbsolute(directory) || !await stat(directory).then((info) => info.isDirectory(), () => false)) {
1005
+ throw new Error(TaLanguageUtil.pick(language(), {
1006
+ "zh-CN": `没有这个目录:${directory}`,
1007
+ "zh-TW": `沒有這個目錄:${directory}`,
1008
+ "en-US": `No such directory: ${directory}`,
1009
+ "ja-JP": `そのようなディレクトリはありません:${directory}`
1010
+ }));
1011
+ }
1012
+ const now = this.doubles.options.now();
1013
+ const given = chosen.map((capability) => ({
1014
+ id: DoubleUtil.id("grant"),
1015
+ friend,
1016
+ name: String(name ?? ""),
1017
+ capability,
1018
+ cwd: directory,
1019
+ grantedAt: now,
1020
+ expiresAt: now + Number(hours) * 60 * 60 * 1000
1021
+ }));
1022
+ const grants = (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.expiresAt > now && !(grant.friend === friend && chosen.includes(grant.capability)));
1023
+ await this.doubles.set(DoubleKeys.GRANTS, [...grants, ...given]);
1024
+ await this.doubles.tasks.granted(friend);
1025
+ return given;
1026
+ }
1027
+ async answer(request) {
1028
+ const asks = await this.doubles.get(DoubleKeys.ASKS) ?? [];
1029
+ const ask = asks.find((each) => each.id === request.ask);
1030
+ if (!ask) {
1031
+ return;
1032
+ }
1033
+ const goesOn = request.accept && await this.doubles.tasks.waiting(ask.friend);
1034
+ if (request.accept) {
1035
+ await this.grant(ask.friend, ask.name, [ask.capability], request.cwd, request.hours);
1036
+ } else {
1037
+ await this.doubles.tasks.refused(ask.friend);
1038
+ }
1039
+ await this.doubles.set(DoubleKeys.ASKS, asks.filter((each) => each.id !== ask.id));
1040
+ const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === ask.room && each.status === "member");
1041
+ const self = room?.members.find((member) => member.self);
1042
+ if (room && self) {
1043
+ const what = ask.capability === "files" ? TaLanguageUtil.pick(language(), {
1044
+ "zh-CN": "读写文件",
1045
+ "zh-TW": "讀寫檔案",
1046
+ "en-US": "work with files",
1047
+ "ja-JP": "ファイルを操作する"
1048
+ }) : TaLanguageUtil.pick(language(), {
1049
+ "zh-CN": "运行命令",
1050
+ "zh-TW": "執行指令",
1051
+ "en-US": "run commands",
1052
+ "ja-JP": "コマンドを実行する"
1053
+ });
1054
+ const text = goesOn ? TaLanguageUtil.pick(language(), {
1055
+ "zh-CN": `${self.name}同意了:我现在可以替${ask.name}${what},接着做任务。`,
1056
+ "zh-TW": `${self.name}同意了:我現在可以替${ask.name}${what},接著做任務。`,
1057
+ "en-US": `${self.name} said yes: I may ${what} for ${ask.name} now, and go on with the task.`,
1058
+ "ja-JP": `${self.name}は同意しました:私は今${ask.name}のため${what}ことができ、タスクを続けます。`
1059
+ }) : request.accept ? TaLanguageUtil.pick(language(), {
1060
+ "zh-CN": `${self.name}同意了:我现在可以替${ask.name}${what},再问我一次吧。`,
1061
+ "zh-TW": `${self.name}同意了:我現在可以替${ask.name}${what},再問我一次吧。`,
1062
+ "en-US": `${self.name} said yes: I may ${what} for ${ask.name} now. Ask me again.`,
1063
+ "ja-JP": `${self.name}は同意しました:私は今${ask.name}のため${what}ことができます。もう一度聞いてください。`
1064
+ }) : TaLanguageUtil.pick(language(), {
1065
+ "zh-CN": `${self.name}这次没有同意替${ask.name}${what}。`,
1066
+ "zh-TW": `${self.name}這次沒有同意替${ask.name}${what}。`,
1067
+ "en-US": `${self.name} did not let me ${what} for ${ask.name} this time.`,
1068
+ "ja-JP": `${self.name}は今回${ask.name}のため${what}ことを許可しませんでした。`
1069
+ });
1070
+ await (await this.doubles.chatOf(room.id)).say(text, self, { double: true }).catch(() => {
1071
+ return;
1072
+ });
1073
+ }
1074
+ }
1075
+ async revokeAll(friend) {
1076
+ await this.doubles.tasks.stopAll(friend);
1077
+ await this.doubles.set(DoubleKeys.GRANTS, (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.friend !== friend));
1078
+ await this.doubles.set(DoubleKeys.ASKS, (await this.doubles.get(DoubleKeys.ASKS) ?? []).filter((ask) => ask.friend !== friend));
1079
+ const sessions = await this.doubles.get(DoubleKeys.SESSIONS) ?? {};
1080
+ const open = await this.doubles.host.listSessions();
1081
+ for (const [file, turn] of this.doubles.turns) {
1082
+ if (turn.active && turn.asker.id === friend) {
1083
+ turn.active = false;
1084
+ const session = open.find((each) => each.sessionFile === file && Object.values(sessions).includes(file));
1085
+ if (session) {
1086
+ await this.doubles.host.abort(session.sessionId).catch(() => {
1087
+ return;
1088
+ });
1089
+ }
1090
+ }
1091
+ }
1092
+ }
1093
+ tell(id, title, text) {
1094
+ this.doubles.host.callPackageHost(NOTIFY, "notify", [{ from: NAME, id, level: "ask", title, text, view: ROOMS_VIEW }]).catch(() => {
1095
+ return;
1096
+ });
1097
+ }
1098
+ }
1099
+
1100
+ // web-src/double-tasks.ts
1101
+ class RoomTasks extends RoomTasksBase {
1102
+ async start() {
1103
+ const now = this.now();
1104
+ const lang = language();
1105
+ const records = await this.update(DoubleKeys.TASKS, (list) => list.map((task) => task.status === "running" ? {
1106
+ ...task,
1107
+ status: "failed",
1108
+ detail: TaLanguageUtil.pick(lang, {
1109
+ "zh-CN": "Ta 重启了,任务中断",
1110
+ "zh-TW": "Ta 重啟了,任務中斷",
1111
+ "en-US": "Ta restarted",
1112
+ "ja-JP": "Ta が再起動しました"
1113
+ }),
1114
+ endedAt: now
1115
+ } : task));
1116
+ for (const room of new Set(records.map((task) => task.room))) {
1117
+ await this.publish(room).catch(() => {
1118
+ return;
1119
+ });
1120
+ }
1121
+ for (const task of records.filter((each) => each.status === "queued")) {
1122
+ this.enqueue(task);
1123
+ }
1124
+ this.timer = setInterval(() => void this.sweep().catch(() => {
1125
+ return;
1126
+ }), SWEEP_MS);
1127
+ this.timer.unref?.();
1128
+ }
1129
+ dispose() {
1130
+ clearInterval(this.timer);
1131
+ for (const wake of [...this.attaching.values()].flat()) {
1132
+ wake();
1133
+ }
1134
+ }
1135
+ async take(room, self, line, quiet) {
1136
+ const member = room.members.find((each) => each.member === line.from);
1137
+ if (!member || member.guest) {
1138
+ return;
1139
+ }
1140
+ const known = (await this.list(DoubleKeys.TASKS)).find((task) => task.id === line.id && task.room === room.id);
1141
+ if (known) {
1142
+ return;
1143
+ }
1144
+ const now = this.now();
1145
+ let record = {
1146
+ id: line.id,
1147
+ room: room.id,
1148
+ title: room.title,
1149
+ friend: member.id,
1150
+ member: member.member,
1151
+ name: member.name,
1152
+ text: DoubleUtil.cut(DoubleUtil.unmention(line.text, self.name), 600),
1153
+ status: "queued",
1154
+ at: now
1155
+ };
1156
+ await this.update(DoubleKeys.TASKS, (list) => {
1157
+ const open = list.filter((task) => task.friend === member.id && !RoomTasksUtil.ended(task.status)).length;
1158
+ const lang = language();
1159
+ const why = quiet ? TaLanguageUtil.pick(lang, {
1160
+ "zh-CN": "这个群里分身不回答",
1161
+ "zh-TW": "這個群裡分身不回答",
1162
+ "en-US": "the double keeps quiet here",
1163
+ "ja-JP": "このグループチャットではダブルは応答しません"
1164
+ }) : open >= TASKS_OPEN ? TaLanguageUtil.pick(lang, {
1165
+ "zh-CN": "手上的任务太多了",
1166
+ "zh-TW": "手上的任務太多了",
1167
+ "en-US": "too many tasks at once",
1168
+ "ja-JP": "一度に処理できるタスクが多すぎます"
1169
+ }) : "";
1170
+ record = why ? { ...record, status: "declined", detail: why, endedAt: now } : record;
1171
+ return DoubleUtil.keep([...list, record]);
1172
+ });
1173
+ await this.publish(room.id);
1174
+ if (record.status === "declined") {
1175
+ const lang = language();
1176
+ await this.say(room.id, self, TaLanguageUtil.pick(lang, {
1177
+ "zh-CN": `这个任务我这次不接:${record.detail}。`,
1178
+ "zh-TW": `這個任務我這次不接:${record.detail}。`,
1179
+ "en-US": `I cannot take this task now: ${record.detail}.`,
1180
+ "ja-JP": `今回このタスクは受け取れません:${record.detail}。`
1181
+ }), line.id);
1182
+ await this.log(record, { outcome: "limited", error: record.detail });
1183
+ return;
1184
+ }
1185
+ this.enqueue(record);
1186
+ }
1187
+ async waiting(friend) {
1188
+ return (await this.list(DoubleKeys.TASKS)).some((task) => task.friend === friend && task.status === "permission");
1189
+ }
1190
+ async granted(friend) {
1191
+ const waiting = await this.mark((task) => task.friend === friend && task.status === "permission", { status: "queued" });
1192
+ for (const task of waiting) {
1193
+ this.enqueue(task, true);
1194
+ }
1195
+ }
1196
+ async refused(friend) {
1197
+ const lang = language();
1198
+ await this.mark((task) => task.friend === friend && task.status === "permission", {
1199
+ status: "declined",
1200
+ detail: TaLanguageUtil.pick(lang, { "zh-CN": "没有得到授权", "zh-TW": "沒有得到授權", "en-US": "not let", "ja-JP": "許可が得られません" }),
1201
+ endedAt: this.now()
1202
+ });
1203
+ }
1204
+ async stop(id, detail) {
1205
+ const [task] = await this.mark((each) => each.id === id && !RoomTasksUtil.ended(each.status), {
1206
+ status: "stopped",
1207
+ ...detail ? { detail } : {},
1208
+ endedAt: this.now()
1209
+ });
1210
+ if (!task) {
1211
+ return;
1212
+ }
1213
+ const run = this.running.get(id);
1214
+ if (run) {
1215
+ run.turn.active = false;
1216
+ await this.doubles.host.abort(run.sessionId).catch(() => {
1217
+ return;
1218
+ });
1219
+ }
1220
+ const self = await this.self(task.room);
1221
+ if (self) {
1222
+ const lang = language();
1223
+ await this.say(task.room, self, TaLanguageUtil.pick(lang, {
1224
+ "zh-CN": "这个任务停下了。",
1225
+ "zh-TW": "這個任務停下了。",
1226
+ "en-US": "This task is stopped.",
1227
+ "ja-JP": "このタスクは停止しました。"
1228
+ }), task.id);
1229
+ }
1230
+ }
1231
+ async stopAll(friend) {
1232
+ for (const task of (await this.list(DoubleKeys.TASKS)).filter((each) => each.friend === friend && !RoomTasksUtil.ended(each.status))) {
1233
+ await this.stop(task.id);
1293
1234
  }
1294
- const directory = String(cwd ?? "").trim();
1295
- if (!isAbsolute(directory) || !await stat(directory).then((info) => info.isDirectory(), () => false)) {
1296
- throw new Error(TaLanguageUtil.pick(language(), {
1297
- "zh-CN": `没有这个目录:${directory}`,
1298
- "zh-TW": `沒有這個目錄:${directory}`,
1299
- "en-US": `No such directory: ${directory}`,
1300
- "ja-JP": `そのようなディレクトリはありません:${directory}`
1301
- }));
1235
+ }
1236
+ async heard(room, key, value, by) {
1237
+ if (key.startsWith("cancel:")) {
1238
+ const member = key.slice("cancel:".length);
1239
+ const ids = RoomTasksUtil.cancelled(member, value, by);
1240
+ const mine = (await this.list(DoubleKeys.TASKS)).filter((task) => task.room === room && task.member === member && ids.includes(task.id) && !RoomTasksUtil.ended(task.status));
1241
+ for (const task of mine) {
1242
+ const lang = language();
1243
+ await this.stop(task.id, TaLanguageUtil.pick(lang, {
1244
+ "zh-CN": `${task.name}取消了`,
1245
+ "zh-TW": `${task.name}取消了`,
1246
+ "en-US": `called off by ${task.name}`,
1247
+ "ja-JP": `${task.name}によってキャンセルされました`
1248
+ }));
1249
+ }
1250
+ } else if (key.startsWith(ROOM_TASKS_KEY)) {
1251
+ await this.sync(room);
1302
1252
  }
1303
- const now = this.doubles.options.now();
1304
- const given = chosen.map((capability) => ({
1305
- id: DoubleUtil.id("grant"),
1306
- friend,
1307
- name: String(name ?? ""),
1308
- capability,
1309
- cwd: directory,
1310
- grantedAt: now,
1311
- expiresAt: now + Number(hours) * 60 * 60 * 1000
1312
- }));
1313
- const grants = (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.expiresAt > now && !(grant.friend === friend && chosen.includes(grant.capability)));
1314
- await this.doubles.set(DoubleKeys.GRANTS, [...grants, ...given]);
1315
- await this.doubles.tasks.granted(friend);
1316
- return given;
1317
1253
  }
1318
- async answer(request) {
1319
- const asks = await this.doubles.get(DoubleKeys.ASKS) ?? [];
1320
- const ask = asks.find((each) => each.id === request.ask);
1321
- if (!ask) {
1254
+ enqueue(task, again = false) {
1255
+ const before = this.queues.get(task.friend) ?? Promise.resolve();
1256
+ const next = before.then(() => this.run(task.id, again)).catch((error) => console.error("ta-rooms: a task of a double failed:", error)).finally(() => {
1257
+ if (this.queues.get(task.friend) === next) {
1258
+ this.queues.delete(task.friend);
1259
+ }
1260
+ });
1261
+ this.queues.set(task.friend, next);
1262
+ }
1263
+ async run(id, again) {
1264
+ const task = (await this.list(DoubleKeys.TASKS)).find((each) => each.id === id);
1265
+ if (task?.status !== "queued") {
1322
1266
  return;
1323
1267
  }
1324
- const goesOn = request.accept && await this.doubles.tasks.waiting(ask.friend);
1325
- if (request.accept) {
1326
- await this.grant(ask.friend, ask.name, [ask.capability], request.cwd, request.hours);
1327
- } else {
1328
- await this.doubles.tasks.refused(ask.friend);
1329
- }
1330
- await this.doubles.set(DoubleKeys.ASKS, asks.filter((each) => each.id !== ask.id));
1331
- const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === ask.room && each.status === "member");
1268
+ const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === task.room && each.status === "member");
1332
1269
  const self = room?.members.find((member) => member.self);
1333
- if (room && self) {
1334
- const what = ask.capability === "files" ? TaLanguageUtil.pick(language(), {
1335
- "zh-CN": "读写文件",
1336
- "zh-TW": "讀寫檔案",
1337
- "en-US": "work with files",
1338
- "ja-JP": "ファイルを操作する"
1339
- }) : TaLanguageUtil.pick(language(), {
1340
- "zh-CN": "运行命令",
1341
- "zh-TW": "執行指令",
1342
- "en-US": "run commands",
1343
- "ja-JP": "コマンドを実行する"
1270
+ if (!room || !self) {
1271
+ const lang = language();
1272
+ await this.mark((each) => each.id === id, {
1273
+ status: "failed",
1274
+ detail: TaLanguageUtil.pick(lang, {
1275
+ "zh-CN": "已经不在这个群里",
1276
+ "zh-TW": "已經不在這個群裡",
1277
+ "en-US": "not in the room any more",
1278
+ "ja-JP": "もうこのグループチャットにいません"
1279
+ }),
1280
+ endedAt: this.now()
1344
1281
  });
1345
- const text = goesOn ? TaLanguageUtil.pick(language(), {
1346
- "zh-CN": `${self.name}同意了:我现在可以替${ask.name}${what},接着做任务。`,
1347
- "zh-TW": `${self.name}同意了:我現在可以替${ask.name}${what},接著做任務。`,
1348
- "en-US": `${self.name} said yes: I may ${what} for ${ask.name} now, and go on with the task.`,
1349
- "ja-JP": `${self.name}は同意しました:私は今${ask.name}のため${what}ことができ、タスクを続けます。`
1350
- }) : request.accept ? TaLanguageUtil.pick(language(), {
1351
- "zh-CN": `${self.name}同意了:我现在可以替${ask.name}${what},再问我一次吧。`,
1352
- "zh-TW": `${self.name}同意了:我現在可以替${ask.name}${what},再問我一次吧。`,
1353
- "en-US": `${self.name} said yes: I may ${what} for ${ask.name} now. Ask me again.`,
1354
- "ja-JP": `${self.name}は同意しました:私は今${ask.name}のため${what}ことができます。もう一度聞いてください。`
1355
- }) : TaLanguageUtil.pick(language(), {
1356
- "zh-CN": `${self.name}这次没有同意替${ask.name}${what}。`,
1357
- "zh-TW": `${self.name}這次沒有同意替${ask.name}${what}。`,
1358
- "en-US": `${self.name} did not let me ${what} for ${ask.name} this time.`,
1359
- "ja-JP": `${self.name}は今回${ask.name}のため${what}ことを許可しませんでした。`
1282
+ return;
1283
+ }
1284
+ const now = this.now();
1285
+ if (!this.doubles.count(room.id, now)) {
1286
+ const lang = language();
1287
+ await this.end(task, self, "declined", TaLanguageUtil.pick(lang, {
1288
+ "zh-CN": "这个小时回答得太多了",
1289
+ "zh-TW": "這個小時回答得太多了",
1290
+ "en-US": "too many answers this hour",
1291
+ "ja-JP": "今時間内に回答が多すぎます"
1292
+ }));
1293
+ return;
1294
+ }
1295
+ const grants = DoubleUtil.grantsOf(await this.doubles.get(DoubleKeys.GRANTS) ?? [], task.friend, now);
1296
+ const work = DoubleUtil.work(grants);
1297
+ const asker = { id: task.friend, member: task.member, name: task.name };
1298
+ const turn = {
1299
+ room: room.id,
1300
+ title: room.title,
1301
+ asker,
1302
+ capabilities: work?.capabilities ?? [],
1303
+ cwd: work?.cwd,
1304
+ active: true,
1305
+ tools: [],
1306
+ task: id
1307
+ };
1308
+ await this.mark((each) => each.id === id, { status: "running", detail: undefined });
1309
+ try {
1310
+ const me = (await this.doubles.host.rooms.getIdentity()).name;
1311
+ const cwd = work?.cwd ?? await this.doubles.chatDirectory();
1312
+ const lang = language();
1313
+ const name = TaLanguageUtil.pick(lang, {
1314
+ "zh-CN": `替${task.name}做:${DoubleUtil.cut(task.text, 30)}`,
1315
+ "zh-TW": `替${task.name}做:${DoubleUtil.cut(task.text, 30)}`,
1316
+ "en-US": `For ${task.name}: ${DoubleUtil.cut(task.text, 30)}`,
1317
+ "ja-JP": `${task.name}の代わりに:${DoubleUtil.cut(task.text, 30)}`
1360
1318
  });
1361
- await (await this.doubles.chatOf(room.id)).say(text, self, { double: true }).catch(() => {
1319
+ const { sessionId, sessionFile } = await this.doubles.session(`task:${room.id}:${id}:${cwd}`, cwd, DoubleUtil.role(me, room.title), name);
1320
+ this.doubles.track(sessionFile, turn);
1321
+ this.running.set(id, { sessionId, turn });
1322
+ const before = await this.doubles.host.getState(sessionId);
1323
+ const chat = await this.doubles.chatOf(room.id);
1324
+ const line = chat.lines.find((each) => each.id === id) ?? { id, from: task.member, name: task.name, text: task.text, at: task.at };
1325
+ const nameOf = (each) => each.agent?.name ?? room.members.find((other) => other.member === each.from)?.name ?? each.name;
1326
+ const permits = [DoubleUtil.permits(me, task.name, work), ...again ? [DoubleUtil.taskAgain(me)] : [], DoubleUtil.taskNote(me, task.name)].join(`
1327
+ `);
1328
+ const message = DoubleUtil.prompt({ title: room.title, asker, line, lines: chat.lines, nameOf, permits });
1329
+ await this.doubles.host.prompt(sessionId, { clientMessageId: `task:${room.id}:${id}:${again ? now : 0}`, message });
1330
+ await this.doubles.settled(sessionId, before.messageCount, TASK_MS);
1331
+ if (!turn.active) {
1362
1332
  return;
1333
+ }
1334
+ const text = (await this.doubles.host.getLastAssistantText(sessionId)).text?.trim();
1335
+ if (!text) {
1336
+ const lang2 = language();
1337
+ throw new Error(TaLanguageUtil.pick(lang2, { "zh-CN": "没有回答", "zh-TW": "沒有回答", "en-US": "No answer.", "ja-JP": "回答がありません。" }));
1338
+ }
1339
+ this.doubles.counted(room.id, now);
1340
+ await this.say(room.id, self, text, id);
1341
+ const asked = turn.tools.includes("ask_permission");
1342
+ await this.mark((each) => each.id === id && !RoomTasksUtil.ended(each.status), {
1343
+ status: asked ? "permission" : "done",
1344
+ answer: DoubleUtil.clip(text, 1500),
1345
+ ...asked ? {} : { endedAt: this.now() }
1363
1346
  });
1364
- }
1365
- }
1366
- async revokeAll(friend) {
1367
- await this.doubles.tasks.stopAll(friend);
1368
- await this.doubles.set(DoubleKeys.GRANTS, (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.friend !== friend));
1369
- await this.doubles.set(DoubleKeys.ASKS, (await this.doubles.get(DoubleKeys.ASKS) ?? []).filter((ask) => ask.friend !== friend));
1370
- const sessions = await this.doubles.get(DoubleKeys.SESSIONS) ?? {};
1371
- const open = await this.doubles.host.listSessions();
1372
- for (const [file, turn] of this.doubles.turns) {
1373
- if (turn.active && turn.asker.id === friend) {
1374
- turn.active = false;
1375
- const session = open.find((each) => each.sessionFile === file && Object.values(sessions).includes(file));
1376
- if (session) {
1377
- await this.doubles.host.abort(session.sessionId).catch(() => {
1378
- return;
1379
- });
1380
- }
1347
+ await this.log({ ...task, answer: text }, { outcome: "answered", tools: turn.tools, capabilities: turn.capabilities });
1348
+ } catch (error) {
1349
+ if (!turn.active) {
1350
+ return;
1381
1351
  }
1352
+ const reason = error instanceof Error ? error.message : String(error);
1353
+ await this.end(task, self, "failed", reason);
1354
+ await this.log(task, { outcome: "failed", error: reason, tools: turn.tools, capabilities: turn.capabilities });
1355
+ } finally {
1356
+ turn.active = false;
1357
+ this.running.delete(id);
1382
1358
  }
1383
1359
  }
1384
- tell(id, title, text) {
1385
- this.doubles.host.callPackageHost(NOTIFY, "notify", [{ from: NAME, id, level: "ask", title, text, view: ROOMS_VIEW }]).catch(() => {
1386
- return;
1360
+ async end(task, self, status, detail) {
1361
+ await this.mark((each) => each.id === task.id, { status, detail: DoubleUtil.cut(detail, 200), endedAt: this.now() });
1362
+ const lang = language();
1363
+ await this.say(task.room, self, TaLanguageUtil.pick(lang, {
1364
+ "zh-CN": `这个任务没能完成:${detail}`,
1365
+ "zh-TW": `這個任務沒能完成:${detail}`,
1366
+ "en-US": `I could not do this task: ${detail}`,
1367
+ "ja-JP": `このタスクを完了できませんでした:${detail}`
1368
+ }), task.id);
1369
+ }
1370
+ async log(task, outcome) {
1371
+ await this.doubles.log({
1372
+ id: DoubleUtil.id("log"),
1373
+ at: this.now(),
1374
+ room: task.room,
1375
+ title: task.title,
1376
+ friend: task.friend,
1377
+ name: task.name,
1378
+ asked: DoubleUtil.cut(task.text, 300),
1379
+ answer: task.answer ? DoubleUtil.cut(task.answer, 300) : "",
1380
+ tools: [],
1381
+ capabilities: [],
1382
+ task: true,
1383
+ ...outcome
1387
1384
  });
1388
1385
  }
1386
+ async publish(roomId) {
1387
+ const self = await this.self(roomId);
1388
+ if (!self) {
1389
+ return;
1390
+ }
1391
+ const tasks = (await this.list(DoubleKeys.TASKS)).filter((task) => task.room === roomId);
1392
+ await this.doubles.host.rooms.setState(roomId, RoomTasksUtil.key(self.member), tasks.length ? DoubleUtil.published(tasks, roomId) : null);
1393
+ }
1389
1394
  }
1390
1395
 
1391
1396
  // web-src/double-user.ts
@@ -1622,10 +1627,10 @@ class RoomDoubles {
1622
1627
  this.host.rooms.listRooms().then((rooms) => {
1623
1628
  if (!rooms.find((room) => room.id === request.room)?.unlisted) {
1624
1629
  this.grants.tell(`join:${request.room}:${request.id}:${request.at}`, request.title, TaLanguageUtil.pick(language(), {
1625
- "zh-CN": `${request.name}想加入房间`,
1626
- "zh-TW": `${request.name}想加入房間`,
1630
+ "zh-CN": `${request.name}想加入群聊`,
1631
+ "zh-TW": `${request.name}想加入群聊`,
1627
1632
  "en-US": `${request.name} asks to join`,
1628
- "ja-JP": `${request.name}はルームへの参加をリクエストしています`
1633
+ "ja-JP": `${request.name}はグループチャットへの参加をリクエストしています`
1629
1634
  }));
1630
1635
  }
1631
1636
  }).catch(() => {
@@ -1926,6 +1931,7 @@ class RoomDoubles {
1926
1931
  var NOTIFY2 = "@celljs/ta-notify";
1927
1932
  var NAME2 = "@celljs/ta-rooms";
1928
1933
  var VIEW = `${NAME2}/friends`;
1934
+ var ROOMS_VIEW2 = `${NAME2}/rooms`;
1929
1935
 
1930
1936
  class FriendNotices {
1931
1937
  host;
@@ -1938,12 +1944,75 @@ class FriendNotices {
1938
1944
  this.stop = this.host.rooms.onEvent((event) => {
1939
1945
  if (event.type === "friend") {
1940
1946
  this.tell(event.request);
1947
+ } else if (event.type === "rooms") {
1948
+ this.tellInvites();
1949
+ this.tellShares();
1941
1950
  }
1942
1951
  });
1952
+ this.tellInvites();
1953
+ this.tellShares();
1943
1954
  }
1944
1955
  dispose() {
1945
1956
  this.stop?.();
1946
1957
  }
1958
+ async tellInvites() {
1959
+ const invites = await Promise.resolve(this.host.rooms.listGroupInvites?.()).catch(() => {
1960
+ return;
1961
+ });
1962
+ for (const invite of invites ?? []) {
1963
+ const key = `invite:${invite.room}:${invite.at}`;
1964
+ if (this.told.has(key)) {
1965
+ continue;
1966
+ }
1967
+ this.told.add(key);
1968
+ const lang = language();
1969
+ await this.host.callPackageHost(NOTIFY2, "notify", [
1970
+ {
1971
+ from: NAME2,
1972
+ id: `invite:${invite.room}`,
1973
+ level: "ask",
1974
+ title: invite.title,
1975
+ text: TaLanguageUtil.pick(lang, {
1976
+ "zh-CN": `${invite.by.name} 邀请你加入群聊`,
1977
+ "zh-TW": `${invite.by.name} 邀請你加入群聊`,
1978
+ "en-US": `${invite.by.name} invites you to a group chat`,
1979
+ "ja-JP": `${invite.by.name} からグループチャットへの招待`
1980
+ }),
1981
+ view: ROOMS_VIEW2
1982
+ }
1983
+ ]).catch(() => {
1984
+ return;
1985
+ });
1986
+ }
1987
+ }
1988
+ async tellShares() {
1989
+ const shares = await Promise.resolve(this.host.rooms.listFriendShares?.()).catch(() => {
1990
+ return;
1991
+ });
1992
+ for (const share of shares ?? []) {
1993
+ if (share.seen || this.told.has(`share:${share.id}`)) {
1994
+ continue;
1995
+ }
1996
+ this.told.add(`share:${share.id}`);
1997
+ await this.host.callPackageHost(NOTIFY2, "notify", [
1998
+ {
1999
+ from: NAME2,
2000
+ id: `share:${share.id}`,
2001
+ level: "ask",
2002
+ title: share.title || share.by.name,
2003
+ text: TaLanguageUtil.pick(language(), {
2004
+ "zh-CN": `${share.by.name} 发给你`,
2005
+ "zh-TW": `${share.by.name} 傳給你`,
2006
+ "en-US": `${share.by.name} sent you this`,
2007
+ "ja-JP": `${share.by.name} から届きました`
2008
+ }),
2009
+ view: ROOMS_VIEW2
2010
+ }
2011
+ ]).catch(() => {
2012
+ return;
2013
+ });
2014
+ }
2015
+ }
1947
2016
  async tell(request) {
1948
2017
  const key = `${request.id}:${request.at}`;
1949
2018
  if (this.told.has(key)) {