@celljs/ta-rooms 4.20.0 → 4.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/index.mjs CHANGED
@@ -78,6 +78,7 @@ var RelayRoomChatUtil;
78
78
  ...line.double === true ? { double: true } : {},
79
79
  ...agent && typeof agent.id === "string" && agent.id && typeof agent.name === "string" && line.double !== true ? { agent: { id: agent.id.slice(0, 64), name: agent.name.slice(0, 64) } } : {},
80
80
  ...to.length ? { to } : {},
81
+ ...line.person === true && to.length && line.double !== true && !line.agent ? { person: true } : {},
81
82
  ...typeof line.re === "string" ? { re: line.re } : {},
82
83
  ...line.task === true && to.length ? { task: true } : {}
83
84
  };
@@ -206,6 +207,7 @@ class RelayRoomChat {
206
207
  // web-src/double-protocol.ts
207
208
  var NAME = "@celljs/ta-rooms";
208
209
  var ROOM_DOUBLE_MARK = "[ta-rooms:double]";
210
+ var DIRECT_KIND = "ta-direct";
209
211
  var CHANNELS = "@celljs/ta-channels";
210
212
  var ROOM_AGENTS_KEY = "agents:";
211
213
  var RoomAgentsUtil;
@@ -286,6 +288,9 @@ var ROOM_CAPABILITIES = ["files", "commands"];
286
288
  var DoubleKeys;
287
289
  ((DoubleKeys) => {
288
290
  DoubleKeys.QUIET = "doubles.quiet";
291
+ DoubleKeys.REPLY = "doubles.reply";
292
+ DoubleKeys.DRAFTS = "doubles.drafts";
293
+ DoubleKeys.DONE = "doubles.done";
289
294
  DoubleKeys.GRANTS = "doubles.grants";
290
295
  DoubleKeys.ASKS = "doubles.asks";
291
296
  DoubleKeys.LOG = "doubles.log";
@@ -295,6 +300,8 @@ var DoubleKeys;
295
300
  DoubleKeys.HANDED = "doubles.handed";
296
301
  DoubleKeys.DEVICE = "doubles.device";
297
302
  })(DoubleKeys ||= {});
303
+ var DRAFTS_MAX = 50;
304
+ var DRAFT_MS = 24 * 60 * 60 * 1000;
298
305
  var GRANT_HOURS = [1, 24, 24 * 7];
299
306
 
300
307
  // ../ta-protocol/esm/common/ta-extension-host.js
@@ -436,8 +443,8 @@ var DoubleUtil;
436
443
  return all.filter((name) => !off.has(name));
437
444
  }
438
445
  DoubleUtil.ownTools = ownTools;
439
- function grantsOf(grants, friend, now) {
440
- return grants.filter((grant) => grant.friend === friend && grant.expiresAt > now);
446
+ function grantsOf(grants, friend, now, room) {
447
+ return grants.filter((grant) => grant.friend === friend && grant.expiresAt > now && (grant.room === undefined || grant.room === room));
441
448
  }
442
449
  DoubleUtil.grantsOf = grantsOf;
443
450
  function work(grants) {
@@ -459,9 +466,28 @@ var DoubleUtil;
459
466
  }
460
467
  DoubleUtil.tools = tools;
461
468
  function asking(lines, self, since, now) {
462
- return lines.filter((line) => line.from !== self && line.at > since && now - line.at < STALE_MS && !!line.to?.includes(self));
469
+ return lines.filter((line) => line.from !== self && line.at > since && now - line.at < STALE_MS && !line.person && !!line.to?.includes(self));
463
470
  }
464
471
  DoubleUtil.asking = asking;
472
+ function calling(lines, self, direct, since, now, awayMs) {
473
+ return lines.filter((line) => line.from !== self && !line.double && !line.agent && !line.task && line.at > since && now - line.at < awayMs + STALE_MS && (line.person ? !!line.to?.includes(self) : direct && !line.to));
474
+ }
475
+ DoubleUtil.calling = calling;
476
+ function answered(lines, self, at) {
477
+ return lines.some((line) => line.from === self && !line.double && !line.agent && line.at > at);
478
+ }
479
+ DoubleUtil.answered = answered;
480
+ function callNote(me, name, how, direct) {
481
+ const where = direct ? `wrote to ${me} in their chat of two` : `named ${me} with @`;
482
+ const why = how === "away" ? `${me} has not seen it for a while: answer for them.` : how === "draft" ? `Write the answer ${me} would send: ${me} reads it first, and sends it, changes it or drops it.` : `${me} lets you answer such lines for them at once.`;
483
+ return `[Ta] ${name} ${where}. ${why} You are ${me}'s double, not ${me}: decide nothing only ${me} can (promises, plans, money), say you will tell ${me}, and keep it short.`;
484
+ }
485
+ DoubleUtil.callNote = callNote;
486
+ function drafts(all, draft, now) {
487
+ const kept = all.filter((each) => now - each.at < DRAFT_MS && !(draft && each.room === draft.room && each.re === draft.re));
488
+ return [...kept, ...draft ? [draft] : []].slice(-DRAFTS_MAX);
489
+ }
490
+ DoubleUtil.drafts = drafts;
465
491
  function askingAgents(lines, self, agents, since, now) {
466
492
  return lines.flatMap((line) => line.at > since && now - line.at < STALE_MS ? agents.filter((agent) => line.to?.includes(RoomAgentsUtil.address(self, agent)) && !(line.from === self && line.agent?.id === agent)).map((agent) => ({ line, agent })) : []);
467
493
  }
@@ -609,6 +635,42 @@ var DoubleUtil;
609
635
  DoubleUtil.id = id;
610
636
  })(DoubleUtil ||= {});
611
637
 
638
+ // web-src/room-rules.ts
639
+ var RoomRulesUtil;
640
+ ((RoomRulesUtil) => {
641
+ function allows(room, rule) {
642
+ return room?.rules?.[rule] !== false;
643
+ }
644
+ RoomRulesUtil.allows = allows;
645
+ function approves(room) {
646
+ return room?.rules?.approve === true;
647
+ }
648
+ RoomRulesUtil.approves = approves;
649
+ function refused(rule, language) {
650
+ return TaLanguageUtil.pick(language, {
651
+ agents: {
652
+ "zh-CN": "群主没有允许在这个群里用智能体",
653
+ "zh-TW": "群主沒有允許在這個群裡用智慧體",
654
+ "en-US": "the owner allows no agents in this group chat",
655
+ "ja-JP": "このグループチャットではグループ主がエージェントを許可していません"
656
+ },
657
+ doubles: {
658
+ "zh-CN": "群主没有允许分身在这个群里代答",
659
+ "zh-TW": "群主沒有允許分身在這個群裡代答",
660
+ "en-US": "the owner allows no double to answer in this group chat",
661
+ "ja-JP": "このグループチャットではグループ主が分身の代理応答を許可していません"
662
+ },
663
+ tasks: {
664
+ "zh-CN": "群主没有允许在这个群里给分身派任务",
665
+ "zh-TW": "群主沒有允許在這個群裡給分身派任務",
666
+ "en-US": "the owner allows no tasks for doubles in this group chat",
667
+ "ja-JP": "このグループチャットではグループ主が分身へのタスクを許可していません"
668
+ }
669
+ }[rule]);
670
+ }
671
+ RoomRulesUtil.refused = refused;
672
+ })(RoomRulesUtil ||= {});
673
+
612
674
  // web-src/double-tasks-base.ts
613
675
  function language() {
614
676
  return TaLanguageUtil.of(process.env.TA_LANGUAGE || process.env.LANG || "");
@@ -644,6 +706,9 @@ class RoomTasksBase {
644
706
  if (member.guest) {
645
707
  throw new Error(`${member.name} is a web guest, without a double.`);
646
708
  }
709
+ if (!RoomRulesUtil.allows(room, "tasks")) {
710
+ throw new Error(`Not handed: ${RoomRulesUtil.refused("tasks", "en-US")}.`);
711
+ }
647
712
  const said = String(text ?? "").trim();
648
713
  if (!said) {
649
714
  throw new Error("What is the task?");
@@ -894,6 +959,9 @@ class RoomAgents {
894
959
  return;
895
960
  });
896
961
  const [{ room, self }, agents, inRoom] = await Promise.all([this.ownRoom(roomId), this.teamAgents(), this.agentsIn(roomId)]);
962
+ if (!RoomRulesUtil.allows(room, "agents")) {
963
+ throw new Error(`${RoomRulesUtil.refused("agents", language())}.`);
964
+ }
897
965
  const agent = agents.find((each) => each.id === agentId);
898
966
  if (!agent) {
899
967
  throw new Error(TaLanguageUtil.pick(language(), {
@@ -1008,7 +1076,8 @@ class RoomGrants {
1008
1076
  const me = (await this.doubles.host.rooms.getIdentity()).name;
1009
1077
  return `Asked ${me}. They decide in Ta, when they see it; you cannot. Tell ${turn.asker.name} it is asked.`;
1010
1078
  }
1011
- async grant(friend, name, capabilities, cwd, hours) {
1079
+ async grant(friend, name, capabilities, cwd, hours, room, title) {
1080
+ const only = typeof room === "string" && room ? room : undefined;
1012
1081
  const chosen = Array.isArray(capabilities) ? capabilities.filter((each) => ROOM_CAPABILITIES.includes(each)) : [];
1013
1082
  if (typeof friend !== "string" || !friend || chosen.length === 0) {
1014
1083
  throw new Error("Whom and what to let the double do are needed.");
@@ -1032,12 +1101,13 @@ class RoomGrants {
1032
1101
  name: String(name ?? ""),
1033
1102
  capability,
1034
1103
  cwd: directory,
1104
+ ...only ? { room: only, ...typeof title === "string" && title ? { title: DoubleUtil.cut(title, 80) } : {} } : {},
1035
1105
  grantedAt: now,
1036
1106
  expiresAt: now + Number(hours) * 60 * 60 * 1000
1037
1107
  }));
1038
- const grants = (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.expiresAt > now && !(grant.friend === friend && chosen.includes(grant.capability)));
1108
+ const grants = (await this.doubles.get(DoubleKeys.GRANTS) ?? []).filter((grant) => grant.expiresAt > now && !(grant.friend === friend && chosen.includes(grant.capability) && grant.room === only));
1039
1109
  await this.doubles.set(DoubleKeys.GRANTS, [...grants, ...given]);
1040
- await this.doubles.tasks.granted(friend);
1110
+ await this.doubles.tasks.granted(friend, only);
1041
1111
  return given;
1042
1112
  }
1043
1113
  async answer(request) {
@@ -1048,7 +1118,7 @@ class RoomGrants {
1048
1118
  }
1049
1119
  const goesOn = request.accept && await this.doubles.tasks.waiting(ask.friend);
1050
1120
  if (request.accept) {
1051
- await this.grant(ask.friend, ask.name, [ask.capability], request.cwd, request.hours);
1121
+ await this.grant(ask.friend, ask.name, [ask.capability], request.cwd, request.hours, request.everywhere ? undefined : ask.room, typeof request.place === "string" && request.place ? request.place : ask.title);
1052
1122
  } else {
1053
1123
  await this.doubles.tasks.refused(ask.friend);
1054
1124
  }
@@ -1113,6 +1183,356 @@ class RoomGrants {
1113
1183
  }
1114
1184
  }
1115
1185
 
1186
+ // web-src/direct.ts
1187
+ var DIRECT_KEY = "direct";
1188
+ var DirectUtil;
1189
+ ((DirectUtil) => {
1190
+ function is(room) {
1191
+ return room?.kind === DIRECT_KIND;
1192
+ }
1193
+ DirectUtil.is = is;
1194
+ function peer(room) {
1195
+ return room.members.find((member) => !member.self);
1196
+ }
1197
+ DirectUtil.peer = peer;
1198
+ function parse(value) {
1199
+ return value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : {};
1200
+ }
1201
+ DirectUtil.parse = parse;
1202
+ function friendOf(room, kept) {
1203
+ return peer(room)?.id ?? Object.entries(kept).find(([, id]) => id === room.id)?.[0];
1204
+ }
1205
+ DirectUtil.friendOf = friendOf;
1206
+ function find(rooms, kept, friend) {
1207
+ const mine = rooms.filter((room) => is(room) && room.status === "member");
1208
+ return mine.find((room) => room.id === kept[friend]) ?? mine.find((room) => peer(room)?.id === friend);
1209
+ }
1210
+ DirectUtil.find = find;
1211
+ })(DirectUtil ||= {});
1212
+
1213
+ // web-src/reply-policy.ts
1214
+ var REPLY_MODES = ["away", "draft", "always", "notify"];
1215
+ var TASK_MODES = ["allow", "ask", "deny"];
1216
+ var INVITE_MODES = ["join", "ask", "deny"];
1217
+ var ReplyPolicyUtil;
1218
+ ((ReplyPolicyUtil) => {
1219
+ ReplyPolicyUtil.DEFAULT = {
1220
+ mode: "away",
1221
+ awayMinutes: 10,
1222
+ strangers: "notify",
1223
+ tasks: { friends: "allow", strangers: "ask" },
1224
+ invites: "ask",
1225
+ chats: {},
1226
+ people: {}
1227
+ };
1228
+ function isTaskMode(value) {
1229
+ return typeof value === "string" && TASK_MODES.includes(value);
1230
+ }
1231
+ ReplyPolicyUtil.isTaskMode = isTaskMode;
1232
+ function isInviteMode(value) {
1233
+ return typeof value === "string" && INVITE_MODES.includes(value);
1234
+ }
1235
+ ReplyPolicyUtil.isInviteMode = isInviteMode;
1236
+ function person(value) {
1237
+ if (isMode(value)) {
1238
+ return { reply: value };
1239
+ }
1240
+ const kept = value && typeof value === "object" ? value : undefined;
1241
+ const policy = {
1242
+ ...isMode(kept?.reply) ? { reply: kept.reply } : {},
1243
+ ...isTaskMode(kept?.tasks) ? { tasks: kept.tasks } : {},
1244
+ ...isInviteMode(kept?.invites) ? { invites: kept.invites } : {},
1245
+ ...kept?.moments === false ? { moments: false } : {}
1246
+ };
1247
+ return Object.keys(policy).length ? policy : undefined;
1248
+ }
1249
+ ReplyPolicyUtil.person = person;
1250
+ function isMode(value) {
1251
+ return typeof value === "string" && REPLY_MODES.includes(value);
1252
+ }
1253
+ ReplyPolicyUtil.isMode = isMode;
1254
+ function parse(value, quiet) {
1255
+ const kept = value && typeof value === "object" ? value : {};
1256
+ const modes = (map, max) => map && typeof map === "object" ? Object.fromEntries(Object.entries(map).filter((entry) => isMode(entry[1])).slice(0, max)) : {};
1257
+ const off = quiet && typeof quiet === "object" ? Object.fromEntries(Object.entries(quiet).filter(([, on]) => on === true).map(([room]) => [room, "notify"])) : {};
1258
+ const minutes2 = Number(kept.awayMinutes);
1259
+ const q = kept.quiet;
1260
+ const tasks = kept.tasks;
1261
+ const minute = (each) => Number.isInteger(each) && each >= 0 && each < 24 * 60;
1262
+ return {
1263
+ mode: isMode(kept.mode) ? kept.mode : ReplyPolicyUtil.DEFAULT.mode,
1264
+ awayMinutes: Number.isFinite(minutes2) && minutes2 >= 1 && minutes2 <= 24 * 60 ? Math.round(minutes2) : ReplyPolicyUtil.DEFAULT.awayMinutes,
1265
+ strangers: isMode(kept.strangers) ? kept.strangers : ReplyPolicyUtil.DEFAULT.strangers,
1266
+ ...q && minute(q.from) && minute(q.to) && q.from !== q.to && isMode(q.mode) ? { quiet: { from: q.from, to: q.to, mode: q.mode } } : {},
1267
+ tasks: {
1268
+ friends: isTaskMode(tasks?.friends) ? tasks.friends : ReplyPolicyUtil.DEFAULT.tasks.friends,
1269
+ strangers: isTaskMode(tasks?.strangers) ? tasks.strangers : ReplyPolicyUtil.DEFAULT.tasks.strangers
1270
+ },
1271
+ invites: isInviteMode(kept.invites) ? kept.invites : ReplyPolicyUtil.DEFAULT.invites,
1272
+ chats: { ...off, ...modes(kept.chats, 500) },
1273
+ people: Object.fromEntries(Object.entries(kept.people && typeof kept.people === "object" ? kept.people : {}).slice(0, 500).flatMap(([id, value2]) => {
1274
+ const one = person(value2);
1275
+ return one ? [[id, one]] : [];
1276
+ }))
1277
+ };
1278
+ }
1279
+ ReplyPolicyUtil.parse = parse;
1280
+ function within(quiet, date) {
1281
+ const now = date.getHours() * 60 + date.getMinutes();
1282
+ return quiet.from < quiet.to ? now >= quiet.from && now < quiet.to : now >= quiet.from || now < quiet.to;
1283
+ }
1284
+ ReplyPolicyUtil.within = within;
1285
+ function modeOf(policy, input) {
1286
+ const person2 = policy.people[input.person]?.reply;
1287
+ if (person2) {
1288
+ return { mode: person2, source: "person" };
1289
+ }
1290
+ const chat = policy.chats[input.room];
1291
+ if (chat) {
1292
+ return { mode: chat, source: "chat" };
1293
+ }
1294
+ if (!input.friend) {
1295
+ return { mode: policy.strangers, source: "strangers" };
1296
+ }
1297
+ if (policy.quiet && within(policy.quiet, input.date)) {
1298
+ return { mode: policy.quiet.mode, source: "quiet" };
1299
+ }
1300
+ return { mode: policy.mode, source: "default" };
1301
+ }
1302
+ ReplyPolicyUtil.modeOf = modeOf;
1303
+ function taskOf(policy, person2, friend) {
1304
+ return policy.people[person2]?.tasks ?? (friend ? policy.tasks.friends : policy.tasks.strangers);
1305
+ }
1306
+ ReplyPolicyUtil.taskOf = taskOf;
1307
+ function inviteOf(policy, person2) {
1308
+ return policy.people[person2]?.invites ?? policy.invites;
1309
+ }
1310
+ ReplyPolicyUtil.inviteOf = inviteOf;
1311
+ function set(policy, where, id, mode) {
1312
+ const { [id]: _was, ...rest } = policy[where];
1313
+ return { ...policy, [where]: mode ? { ...rest, [id]: mode } : rest };
1314
+ }
1315
+ ReplyPolicyUtil.set = set;
1316
+ function setPerson(policy, id, key, value) {
1317
+ const { [key]: _was, ...others } = policy.people[id] ?? {};
1318
+ const next = value === undefined ? others : { ...others, [key]: value };
1319
+ const { [id]: _person, ...rest } = policy.people;
1320
+ return { ...policy, people: Object.keys(next).length ? { ...rest, [id]: next } : rest };
1321
+ }
1322
+ ReplyPolicyUtil.setPerson = setPerson;
1323
+ function clock(minutes2) {
1324
+ return `${String(Math.floor(minutes2 / 60)).padStart(2, "0")}:${String(minutes2 % 60).padStart(2, "0")}`;
1325
+ }
1326
+ ReplyPolicyUtil.clock = clock;
1327
+ function minutes(clock2) {
1328
+ const match = /^(\d{1,2}):(\d{2})$/.exec(clock2.trim());
1329
+ const value = match ? Number(match[1]) * 60 + Number(match[2]) : Number.NaN;
1330
+ return Number.isInteger(value) && value >= 0 && value < 24 * 60 ? value : undefined;
1331
+ }
1332
+ ReplyPolicyUtil.minutes = minutes;
1333
+ })(ReplyPolicyUtil ||= {});
1334
+
1335
+ // web-src/room-seen.ts
1336
+ var RoomSeenUtil;
1337
+ ((RoomSeenUtil) => {
1338
+ function parse(value) {
1339
+ return value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "number")) : {};
1340
+ }
1341
+ RoomSeenUtil.parse = parse;
1342
+ function merge(a, b) {
1343
+ const later = Object.entries(b).filter(([room, at]) => at > (a[room] ?? 0));
1344
+ return later.length ? { ...a, ...Object.fromEntries(later) } : a;
1345
+ }
1346
+ RoomSeenUtil.merge = merge;
1347
+ })(RoomSeenUtil ||= {});
1348
+
1349
+ // web-src/double-reach.ts
1350
+ var DONE_KEPT = 200;
1351
+ var SEEN_KEY = "seen";
1352
+
1353
+ class RoomReach {
1354
+ doubles;
1355
+ timers = new Map;
1356
+ told = new Set;
1357
+ constructor(doubles) {
1358
+ this.doubles = doubles;
1359
+ }
1360
+ dispose() {
1361
+ for (const timer of this.timers.values()) {
1362
+ clearTimeout(timer);
1363
+ }
1364
+ this.timers.clear();
1365
+ }
1366
+ async look(roomId) {
1367
+ if (this.doubles.disposed) {
1368
+ return;
1369
+ }
1370
+ const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === roomId);
1371
+ const self = room?.members.find((member) => member.self);
1372
+ if (room?.status !== "member" || !self) {
1373
+ return;
1374
+ }
1375
+ const chat = await this.doubles.chatOf(roomId);
1376
+ const read = await this.doubles.get(DoubleKeys.READ) ?? {};
1377
+ const since = read[roomId] ?? 0;
1378
+ const done = new Set(Object.keys((await this.doubles.get(DoubleKeys.DONE) ?? {})[roomId] ?? {}));
1379
+ const policy = ReplyPolicyUtil.parse(await this.doubles.get(DoubleKeys.REPLY), await this.doubles.get(DoubleKeys.QUIET));
1380
+ const awayMs = policy.awayMinutes * 60 * 1000;
1381
+ const now = this.doubles.options.now();
1382
+ const direct = DirectUtil.is(room);
1383
+ const agents = (await this.doubles.agents.agentsIn(roomId)).filter((agent) => agent.member === self.member);
1384
+ const asking = [
1385
+ ...DoubleUtil.asking(chat.lines, self.member, since, now).map((line) => ({ line, key: line.id })),
1386
+ ...DoubleUtil.calling(chat.lines, self.member, direct, since, now, awayMs).map((line) => ({ line, call: true, key: line.id })),
1387
+ ...DoubleUtil.askingAgents(chat.lines, self.member, agents.map((agent) => agent.id), since, now).map(({ line, agent }) => ({ line, agent: agents.find((each) => each.id === agent), key: `${line.id}:${agent}` }))
1388
+ ].filter((each) => !done.has(each.key)).sort((a, b) => a.line.at - b.line.at);
1389
+ await this.pruneDrafts(roomId, chat, self.member);
1390
+ if (!asking.length) {
1391
+ return;
1392
+ }
1393
+ const friends = new Set((await this.doubles.host.rooms.listFriends().catch(() => [])).filter((friend) => friend.status === "friend").map((friend) => friend.id));
1394
+ const seen = RoomSeenUtil.parse(await this.doubles.get(SEEN_KEY));
1395
+ let waiting;
1396
+ const handled = [];
1397
+ for (const { line, agent, call, key } of asking) {
1398
+ const member = room.members.find((each) => each.member === line.from);
1399
+ const person = member?.id ?? line.from;
1400
+ const chosen = ReplyPolicyUtil.modeOf(policy, {
1401
+ room: roomId,
1402
+ person,
1403
+ friend: !member?.guest && friends.has(person),
1404
+ date: new Date(line.at)
1405
+ }).mode;
1406
+ const mode = RoomRulesUtil.allows(room, "doubles") || chosen === "draft" ? chosen : "notify";
1407
+ if (call) {
1408
+ const due = await this.call(room, self, chat, line, mode, { seen: seen[roomId] ?? 0, awayMs, now });
1409
+ if (due !== undefined) {
1410
+ waiting = Math.min(waiting ?? due, due);
1411
+ continue;
1412
+ }
1413
+ } else if (!await this.doubles.claim(roomId, self.member, agent ? `${line.id}:${agent.id}` : line.id)) {} else if (line.task && !agent && !member?.guest) {
1414
+ await this.doubles.tasks.take(room, self, line, policy.chats[roomId] === "notify", ReplyPolicyUtil.taskOf(policy, person, !member?.guest && friends.has(person)));
1415
+ } else if (agent ? RoomRulesUtil.allows(room, "agents") : mode !== "notify") {
1416
+ await this.doubles.reply(room, self, chat, line, agent);
1417
+ }
1418
+ handled.push({ key, at: line.at });
1419
+ }
1420
+ await this.handled(roomId, handled, waiting === undefined ? undefined : Math.min(...asking.filter((each) => !handled.some((h) => h.key === each.key)).map((each) => each.line.at)));
1421
+ if (waiting !== undefined) {
1422
+ this.wait(roomId, waiting);
1423
+ }
1424
+ }
1425
+ async call(room, self, chat, line, mode, when) {
1426
+ const name = room.members.find((each) => each.member === line.from)?.name ?? line.name;
1427
+ const direct = DirectUtil.is(room);
1428
+ if (mode !== "draft") {
1429
+ this.tellCall(room, line, name, direct);
1430
+ }
1431
+ if (mode === "notify") {
1432
+ return;
1433
+ }
1434
+ if (mode === "away") {
1435
+ if (DoubleUtil.answered(chat.lines, self.member, line.at) || when.seen >= line.at) {
1436
+ return;
1437
+ }
1438
+ const due = line.at + when.awayMs;
1439
+ if (when.now < due) {
1440
+ return due;
1441
+ }
1442
+ }
1443
+ if (await this.doubles.claim(room.id, self.member, line.id)) {
1444
+ await this.doubles.reply(room, self, chat, line, undefined, { how: mode, direct });
1445
+ }
1446
+ return;
1447
+ }
1448
+ async keepDraft(room, line, asker, text) {
1449
+ const now = this.doubles.options.now();
1450
+ const draft = {
1451
+ id: DoubleUtil.id("draft"),
1452
+ room: room.id,
1453
+ re: line.id,
1454
+ friend: asker.id,
1455
+ name: asker.name,
1456
+ asked: DoubleUtil.cut(line.text, 300),
1457
+ text,
1458
+ at: now
1459
+ };
1460
+ await this.doubles.set(DoubleKeys.DRAFTS, DoubleUtil.drafts(await this.doubles.get(DoubleKeys.DRAFTS) ?? [], draft, now));
1461
+ this.doubles.grants.tell(`draft:${draft.id}`, DirectUtil.is(room) ? asker.name : room.title, TaLanguageUtil.pick(language(), {
1462
+ "zh-CN": `分身拟好了给${asker.name}的回复,等你发送`,
1463
+ "zh-TW": `分身擬好了給${asker.name}的回覆,等你傳送`,
1464
+ "en-US": `Your double wrote an answer to ${asker.name}, for you to send`,
1465
+ "ja-JP": `分身が${asker.name}への返信を下書きしました。送信を待っています`
1466
+ }));
1467
+ }
1468
+ tellCall(room, line, name, direct) {
1469
+ if (this.told.has(line.id)) {
1470
+ return;
1471
+ }
1472
+ this.told.add(line.id);
1473
+ const text = DoubleUtil.cut(line.text, 80);
1474
+ this.doubles.grants.tell(`call:${room.id}:${line.id}`, direct ? name : room.title, direct ? text : TaLanguageUtil.pick(language(), {
1475
+ "zh-CN": `${name} @ 了你:${text}`,
1476
+ "zh-TW": `${name} @ 了你:${text}`,
1477
+ "en-US": `${name} mentioned you: ${text}`,
1478
+ "ja-JP": `${name} があなたをメンションしました:${text}`
1479
+ }));
1480
+ }
1481
+ async handled(roomId, lines, waitingAt) {
1482
+ const done = await this.doubles.get(DoubleKeys.DONE) ?? {};
1483
+ const merged = { ...done[roomId] ?? {}, ...Object.fromEntries(lines.map((line) => [line.key, line.at])) };
1484
+ if (!lines.length && waitingAt !== undefined) {
1485
+ return;
1486
+ }
1487
+ const read = await this.doubles.get(DoubleKeys.READ) ?? {};
1488
+ const upTo = Math.max(read[roomId] ?? 0, ...Object.values(merged).filter((at) => waitingAt === undefined || at < waitingAt));
1489
+ if (upTo !== (read[roomId] ?? 0)) {
1490
+ await this.doubles.set(DoubleKeys.READ, { ...read, [roomId]: upTo });
1491
+ }
1492
+ const after = Object.entries(merged).filter(([, at]) => at > upTo).slice(-DONE_KEPT);
1493
+ const { [roomId]: _was, ...rest } = done;
1494
+ if (after.length || done[roomId]) {
1495
+ await this.doubles.set(DoubleKeys.DONE, after.length ? { ...rest, [roomId]: Object.fromEntries(after) } : rest);
1496
+ }
1497
+ }
1498
+ wait(roomId, at) {
1499
+ clearTimeout(this.timers.get(roomId));
1500
+ const delay = Math.max(1000, at - this.doubles.options.now() + 500);
1501
+ const timer = setTimeout(() => {
1502
+ this.timers.delete(roomId);
1503
+ this.doubles.check(roomId);
1504
+ }, delay);
1505
+ timer.unref?.();
1506
+ this.timers.set(roomId, timer);
1507
+ }
1508
+ async pruneDrafts(roomId, chat, self) {
1509
+ const drafts = await this.doubles.get(DoubleKeys.DRAFTS) ?? [];
1510
+ const kept = DoubleUtil.drafts(drafts.filter((draft) => draft.room !== roomId || !DoubleUtil.answered(chat.lines, self, draft.at)), undefined, this.doubles.options.now());
1511
+ if (kept.length !== drafts.length) {
1512
+ await this.doubles.set(DoubleKeys.DRAFTS, kept);
1513
+ }
1514
+ }
1515
+ async sendDraft(id, text, send) {
1516
+ const drafts = await this.doubles.get(DoubleKeys.DRAFTS) ?? [];
1517
+ const draft = drafts.find((each) => each.id === id);
1518
+ if (!draft) {
1519
+ throw new Error("That draft is gone.");
1520
+ }
1521
+ if (send) {
1522
+ const room = (await this.doubles.host.rooms.listRooms()).find((each) => each.id === draft.room && each.status === "member");
1523
+ const self = room?.members.find((member) => member.self);
1524
+ if (!room || !self) {
1525
+ throw new Error("You are no longer in that chat.");
1526
+ }
1527
+ const said = (text ?? draft.text).trim();
1528
+ const chat = await this.doubles.chatOf(room.id);
1529
+ const asDouble = said === draft.text.trim() && RoomRulesUtil.allows(room, "doubles");
1530
+ await chat.say(said, self, asDouble ? { double: true, re: draft.re } : { re: draft.re });
1531
+ }
1532
+ await this.doubles.set(DoubleKeys.DRAFTS, (await this.doubles.get(DoubleKeys.DRAFTS) ?? []).filter((each) => each.id !== id));
1533
+ }
1534
+ }
1535
+
1116
1536
  // web-src/double-tasks.ts
1117
1537
  class RoomTasks extends RoomTasksBase {
1118
1538
  async start() {
@@ -1148,7 +1568,7 @@ class RoomTasks extends RoomTasksBase {
1148
1568
  wake();
1149
1569
  }
1150
1570
  }
1151
- async take(room, self, line, quiet) {
1571
+ async take(room, self, line, quiet, may = "allow") {
1152
1572
  const member = room.members.find((each) => each.member === line.from);
1153
1573
  if (!member || member.guest) {
1154
1574
  return;
@@ -1172,7 +1592,12 @@ class RoomTasks extends RoomTasksBase {
1172
1592
  await this.update(DoubleKeys.TASKS, (list) => {
1173
1593
  const open = list.filter((task) => task.friend === member.id && !RoomTasksUtil.ended(task.status)).length;
1174
1594
  const lang = language();
1175
- const why = quiet ? TaLanguageUtil.pick(lang, {
1595
+ const why = !RoomRulesUtil.allows(room, "tasks") ? RoomRulesUtil.refused("tasks", lang) : may === "deny" ? TaLanguageUtil.pick(lang, {
1596
+ "zh-CN": "我没有开放给你派任务",
1597
+ "zh-TW": "我沒有開放給你派任務",
1598
+ "en-US": "I do not take tasks from you",
1599
+ "ja-JP": "あなたからのタスクは受け付けていません"
1600
+ }) : quiet ? TaLanguageUtil.pick(lang, {
1176
1601
  "zh-CN": "这个群里分身不回答",
1177
1602
  "zh-TW": "這個群裡分身不回答",
1178
1603
  "en-US": "the double keeps quiet here",
@@ -1183,7 +1608,7 @@ class RoomTasks extends RoomTasksBase {
1183
1608
  "en-US": "too many tasks at once",
1184
1609
  "ja-JP": "一度に処理できるタスクが多すぎます"
1185
1610
  }) : "";
1186
- record = why ? { ...record, status: "declined", detail: why, endedAt: now } : record;
1611
+ record = why ? { ...record, status: "declined", detail: why, endedAt: now } : may === "ask" ? { ...record, status: "permission", approval: true } : record;
1187
1612
  return DoubleUtil.keep([...list, record]);
1188
1613
  });
1189
1614
  await this.publish(room.id);
@@ -1198,20 +1623,54 @@ class RoomTasks extends RoomTasksBase {
1198
1623
  await this.log(record, { outcome: "limited", error: record.detail });
1199
1624
  return;
1200
1625
  }
1626
+ if (record.approval) {
1627
+ this.doubles.grants.tell(`approve:${record.id}`, record.name, TaLanguageUtil.pick(language(), {
1628
+ "zh-CN": `${record.name}想让你的分身做:${DoubleUtil.cut(record.text, 60)}`,
1629
+ "zh-TW": `${record.name}想讓你的分身做:${DoubleUtil.cut(record.text, 60)}`,
1630
+ "en-US": `${record.name} hands your double: ${DoubleUtil.cut(record.text, 60)}`,
1631
+ "ja-JP": `${record.name}があなたの分身に依頼:${DoubleUtil.cut(record.text, 60)}`
1632
+ }));
1633
+ return;
1634
+ }
1201
1635
  this.enqueue(record);
1202
1636
  }
1637
+ async approve(id, accept) {
1638
+ const [task] = accept ? await this.mark((each) => each.id === id && !!each.approval && each.status === "permission", { status: "queued", approval: undefined }) : await this.mark((each) => each.id === id && !!each.approval && each.status === "permission", {
1639
+ status: "declined",
1640
+ approval: undefined,
1641
+ detail: TaLanguageUtil.pick(language(), { "zh-CN": "这次不接", "zh-TW": "這次不接", "en-US": "not this time", "ja-JP": "今回は受けません" }),
1642
+ endedAt: this.now()
1643
+ });
1644
+ if (!task) {
1645
+ throw new Error("That task no longer waits for you.");
1646
+ }
1647
+ await this.publish(task.room);
1648
+ if (accept) {
1649
+ this.enqueue(task);
1650
+ return;
1651
+ }
1652
+ const self = await this.self(task.room);
1653
+ if (self) {
1654
+ await this.say(task.room, self, TaLanguageUtil.pick(language(), {
1655
+ "zh-CN": "这个任务我这次不接。",
1656
+ "zh-TW": "這個任務我這次不接。",
1657
+ "en-US": "I will not take this task this time.",
1658
+ "ja-JP": "今回このタスクは受けません。"
1659
+ }), task.id);
1660
+ }
1661
+ }
1203
1662
  async waiting(friend) {
1204
1663
  return (await this.list(DoubleKeys.TASKS)).some((task) => task.friend === friend && task.status === "permission");
1205
1664
  }
1206
- async granted(friend) {
1207
- const waiting = await this.mark((task) => task.friend === friend && task.status === "permission", { status: "queued" });
1665
+ async granted(friend, room) {
1666
+ const waiting = await this.mark((task) => task.friend === friend && task.status === "permission" && !task.approval && (room === undefined || task.room === room), { status: "queued" });
1208
1667
  for (const task of waiting) {
1209
1668
  this.enqueue(task, true);
1210
1669
  }
1211
1670
  }
1212
1671
  async refused(friend) {
1213
1672
  const lang = language();
1214
- await this.mark((task) => task.friend === friend && task.status === "permission", {
1673
+ await this.mark((task) => task.friend === friend && task.status === "permission" && !task.approval, {
1215
1674
  status: "declined",
1216
1675
  detail: TaLanguageUtil.pick(lang, { "zh-CN": "没有得到授权", "zh-TW": "沒有得到授權", "en-US": "not let", "ja-JP": "許可が得られません" }),
1217
1676
  endedAt: this.now()
@@ -1308,7 +1767,7 @@ class RoomTasks extends RoomTasksBase {
1308
1767
  }));
1309
1768
  return;
1310
1769
  }
1311
- const grants = DoubleUtil.grantsOf(await this.doubles.get(DoubleKeys.GRANTS) ?? [], task.friend, now);
1770
+ const grants = DoubleUtil.grantsOf(await this.doubles.get(DoubleKeys.GRANTS) ?? [], task.friend, now, task.room);
1312
1771
  const work = DoubleUtil.work(grants);
1313
1772
  const asker = { id: task.friend, member: task.member, name: task.name };
1314
1773
  const turn = {
@@ -1532,6 +1991,7 @@ class RoomDoubles {
1532
1991
  user = new RoomUserTools(this);
1533
1992
  agents = new RoomAgents(this);
1534
1993
  grants = new RoomGrants(this);
1994
+ reach = new RoomReach(this);
1535
1995
  chats = new Map;
1536
1996
  queues = new Map;
1537
1997
  answered = new Map;
@@ -1557,6 +2017,7 @@ class RoomDoubles {
1557
2017
  dispose() {
1558
2018
  this.disposed = true;
1559
2019
  this.stopEvents?.();
2020
+ this.reach.dispose();
1560
2021
  this.tasks.dispose();
1561
2022
  this.user.wake();
1562
2023
  }
@@ -1599,18 +2060,12 @@ class RoomDoubles {
1599
2060
  }
1600
2061
  async request(request) {
1601
2062
  switch (request?.kind) {
1602
- case "quiet": {
1603
- const quiet = { ...await this.get(DoubleKeys.QUIET) ?? {} };
1604
- if (request.quiet) {
1605
- quiet[String(request.room)] = true;
1606
- } else {
1607
- delete quiet[String(request.room)];
1608
- }
1609
- await this.set(DoubleKeys.QUIET, quiet);
1610
- return;
1611
- }
2063
+ case "sendDraft":
2064
+ return this.reach.sendDraft(String(request.draft), typeof request.text === "string" ? request.text : undefined, true);
2065
+ case "dropDraft":
2066
+ return this.reach.sendDraft(String(request.draft), undefined, false);
1612
2067
  case "grant":
1613
- return this.grants.grant(request.friend, request.name, request.capabilities, request.cwd, request.hours);
2068
+ return this.grants.grant(request.friend, request.name, request.capabilities, request.cwd, request.hours, request.room, request.title);
1614
2069
  case "answer":
1615
2070
  return this.grants.answer(request);
1616
2071
  case "revoke": {
@@ -1631,6 +2086,8 @@ class RoomDoubles {
1631
2086
  return this.agents.dismiss(String(request.room), String(request.agent));
1632
2087
  case "stopTask":
1633
2088
  return request.handed ? this.tasks.cancel(String(request.task)) : this.tasks.stop(String(request.task));
2089
+ case "approveTask":
2090
+ return this.tasks.approve(String(request.task), !!request.accept);
1634
2091
  case "forgetTask":
1635
2092
  return this.tasks.forget(String(request.task), !!request.handed);
1636
2093
  default:
@@ -1688,44 +2145,14 @@ class RoomDoubles {
1688
2145
  }
1689
2146
  check(room) {
1690
2147
  const before = this.queues.get(room) ?? Promise.resolve();
1691
- const next = before.then(() => this.look(room)).catch((error) => console.error("ta-rooms: the double could not answer:", error)).finally(() => {
2148
+ const next = before.then(() => this.reach.look(room)).catch((error) => console.error("ta-rooms: the double could not answer:", error)).finally(() => {
1692
2149
  if (this.queues.get(room) === next) {
1693
2150
  this.queues.delete(room);
1694
2151
  }
1695
2152
  });
1696
2153
  this.queues.set(room, next);
1697
2154
  }
1698
- async look(roomId) {
1699
- if (this.disposed) {
1700
- return;
1701
- }
1702
- const room = (await this.host.rooms.listRooms()).find((each) => each.id === roomId);
1703
- const self = room?.members.find((member) => member.self);
1704
- if (room?.status !== "member" || !self) {
1705
- return;
1706
- }
1707
- const chat = await this.chatOf(roomId);
1708
- const read = await this.get(DoubleKeys.READ) ?? {};
1709
- const since = read[roomId] ?? 0;
1710
- const now = this.options.now();
1711
- const agents = (await this.agents.agentsIn(roomId)).filter((agent) => agent.member === self.member);
1712
- const asking = [
1713
- ...DoubleUtil.asking(chat.lines, self.member, since, now).map((line) => ({ line })),
1714
- ...DoubleUtil.askingAgents(chat.lines, self.member, agents.map((agent) => agent.id), since, now).map(({ line, agent }) => ({ line, agent: agents.find((each) => each.id === agent) }))
1715
- ].sort((a, b) => a.line.at - b.line.at);
1716
- for (const { line, agent } of asking) {
1717
- const quiet = await this.get(DoubleKeys.QUIET) ?? {};
1718
- const guest = room.members.find((member) => member.member === line.from)?.guest;
1719
- if (!await this.claim(roomId, self.member, agent ? `${line.id}:${agent.id}` : line.id)) {} else if (line.task && !agent && !guest) {
1720
- await this.tasks.take(room, self, line, !!quiet[roomId]);
1721
- } else if (agent || !quiet[roomId]) {
1722
- await this.reply(room, self, chat, line, agent);
1723
- }
1724
- const read2 = await this.get(DoubleKeys.READ) ?? {};
1725
- await this.set(DoubleKeys.READ, { ...read2, [roomId]: Math.max(read2[roomId] ?? 0, line.at) });
1726
- }
1727
- }
1728
- async reply(room, self, chat, line, agent) {
2155
+ async reply(room, self, chat, line, agent, call) {
1729
2156
  const member = room.members.find((each) => each.member === line.from);
1730
2157
  if (!member) {
1731
2158
  return;
@@ -1753,7 +2180,7 @@ class RoomDoubles {
1753
2180
  await this.log({ ...entry, outcome: "limited" });
1754
2181
  return;
1755
2182
  }
1756
- const grants = own || asker.guest ? [] : DoubleUtil.grantsOf(await this.get(DoubleKeys.GRANTS) ?? [], asker.id, now);
2183
+ const grants = own || asker.guest ? [] : DoubleUtil.grantsOf(await this.get(DoubleKeys.GRANTS) ?? [], asker.id, now, room.id);
1757
2184
  const work = DoubleUtil.work(grants);
1758
2185
  const me = (await this.host.rooms.getIdentity()).name;
1759
2186
  const turn = {
@@ -1786,7 +2213,11 @@ class RoomDoubles {
1786
2213
  this.track(sessionFile, turn);
1787
2214
  const before = await this.host.getState(sessionId);
1788
2215
  const nameOf = (each) => each.agent?.name ?? room.members.find((other) => other.member === each.from)?.name ?? each.name;
1789
- const permits = own ? DoubleUtil.ownPermits(me, cwd) : DoubleUtil.permits(me, asker.name, work);
2216
+ const permits = [
2217
+ own ? DoubleUtil.ownPermits(me, cwd) : DoubleUtil.permits(me, asker.name, work),
2218
+ ...call ? [DoubleUtil.callNote(me, asker.name, call.how, call.direct)] : []
2219
+ ].join(`
2220
+ `);
1790
2221
  const message = DoubleUtil.prompt({ title: room.title, asker, line, lines: chat.lines, nameOf, permits });
1791
2222
  await this.host.prompt(sessionId, { clientMessageId: `${room.id}:${line.id}:${agent?.id ?? "double"}`, message });
1792
2223
  await this.settled(sessionId, before.messageCount);
@@ -1794,11 +2225,21 @@ class RoomDoubles {
1794
2225
  if (!text) {
1795
2226
  throw new Error("No answer.");
1796
2227
  }
1797
- await chat.say(text, self, agent ? { agent: { id: agent.id, name: agent.name }, re: line.id } : { double: true, re: line.id });
2228
+ if (call?.how === "draft") {
2229
+ await this.reach.keepDraft(room, line, asker, text);
2230
+ } else {
2231
+ await chat.say(text, self, agent ? { agent: { id: agent.id, name: agent.name }, re: line.id } : { double: true, re: line.id });
2232
+ }
1798
2233
  if (!own) {
1799
2234
  this.counted(room.id, now);
1800
2235
  }
1801
- await this.log({ ...entry, answer: DoubleUtil.cut(text, 300), tools: turn.tools, capabilities: turn.capabilities });
2236
+ await this.log({
2237
+ ...entry,
2238
+ answer: DoubleUtil.cut(text, 300),
2239
+ tools: turn.tools,
2240
+ capabilities: turn.capabilities,
2241
+ ...call?.how === "draft" ? { outcome: "drafted" } : {}
2242
+ });
1802
2243
  } catch (error) {
1803
2244
  const reason = error instanceof Error ? error.message : String(error);
1804
2245
  await this.log({ ...entry, outcome: "failed", error: reason, tools: turn.tools, capabilities: turn.capabilities });
@@ -1959,6 +2400,8 @@ class FriendNotices {
1959
2400
  host;
1960
2401
  stop;
1961
2402
  told = new Set;
2403
+ joining = new Set;
2404
+ answered = new Set;
1962
2405
  constructor(host) {
1963
2406
  this.host = host;
1964
2407
  }
@@ -1982,6 +2425,20 @@ class FriendNotices {
1982
2425
  return;
1983
2426
  });
1984
2427
  for (const invite of invites ?? []) {
2428
+ if (invite.kind === DIRECT_KIND) {
2429
+ await this.joinDirect(invite.room, invite.by.id);
2430
+ continue;
2431
+ }
2432
+ const how = ReplyPolicyUtil.inviteOf(ReplyPolicyUtil.parse(await this.host.getExtensionData(NAME2, DoubleKeys.REPLY).catch(() => {
2433
+ return;
2434
+ })), invite.by.id);
2435
+ if (how !== "ask") {
2436
+ if (!this.answered.has(invite.room)) {
2437
+ this.answered.add(invite.room);
2438
+ await this.host.rooms.answerGroupInvite(invite.room, how === "join").catch(() => this.answered.delete(invite.room));
2439
+ }
2440
+ continue;
2441
+ }
1985
2442
  const key = `invite:${invite.room}:${invite.at}`;
1986
2443
  if (this.told.has(key)) {
1987
2444
  continue;
@@ -2007,6 +2464,25 @@ class FriendNotices {
2007
2464
  });
2008
2465
  }
2009
2466
  }
2467
+ async joinDirect(room, friend) {
2468
+ if (this.joining.has(room)) {
2469
+ return;
2470
+ }
2471
+ this.joining.add(room);
2472
+ try {
2473
+ await this.host.rooms.answerGroupInvite(room, true);
2474
+ const kept = DirectUtil.parse(await this.host.getExtensionData(NAME2, DIRECT_KEY));
2475
+ const current = kept[friend];
2476
+ const inside = !!current && (await this.host.rooms.listRooms()).some((each) => each.id === current && each.status === "member");
2477
+ if (!inside) {
2478
+ await this.host.setExtensionData(NAME2, DIRECT_KEY, { ...kept, [friend]: room });
2479
+ }
2480
+ } catch (error) {
2481
+ console.error("ta-rooms could not join a chat of two:", error);
2482
+ } finally {
2483
+ this.joining.delete(room);
2484
+ }
2485
+ }
2010
2486
  async tellShares() {
2011
2487
  const shares = await Promise.resolve(this.host.rooms.listFriendShares?.()).catch(() => {
2012
2488
  return;