@celljs/ta-channels 4.34.0 → 4.36.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) {
@@ -4165,7 +4166,404 @@ class ChannelSeenBook {
4165
4166
  }
4166
4167
  }
4167
4168
 
4169
+ // ../../packages/core/esm/common/utils/error-util.js
4170
+ class ErrorUtil {
4171
+ static fixProto(target, prototype) {
4172
+ const setPrototypeOf = Object.setPrototypeOf;
4173
+ if (setPrototypeOf) {
4174
+ setPrototypeOf(target, prototype);
4175
+ } else {
4176
+ target.__proto__ = prototype;
4177
+ }
4178
+ }
4179
+ static fixStack(target, fn = target.constructor) {
4180
+ const captureStackTrace = Error.captureStackTrace;
4181
+ if (captureStackTrace) {
4182
+ captureStackTrace(target, fn);
4183
+ }
4184
+ }
4185
+ static describe(error) {
4186
+ let text = ErrorUtil.describeOne(error);
4187
+ let cause = ErrorUtil.causeOf(error);
4188
+ for (let depth = 0;cause !== undefined && depth < 5; depth++) {
4189
+ text += `
4190
+ Caused by: ${ErrorUtil.describeOne(cause)}`;
4191
+ cause = ErrorUtil.causeOf(cause);
4192
+ }
4193
+ return text;
4194
+ }
4195
+ static causeOf(error) {
4196
+ return error instanceof Error ? error.cause : undefined;
4197
+ }
4198
+ static describeOne(error) {
4199
+ var _a;
4200
+ if (error instanceof Error) {
4201
+ return (_a = error.stack) !== null && _a !== undefined ? _a : `${error.name}: ${error.message}`;
4202
+ }
4203
+ return String(error);
4204
+ }
4205
+ }
4206
+
4207
+ // ../../packages/core/esm/common/utils/event.js
4208
+ var Event;
4209
+ (function(Event2) {
4210
+ const _disposable = { dispose() {} };
4211
+ Event2.None = Object.assign(function() {
4212
+ return _disposable;
4213
+ }, {
4214
+ get maxListeners() {
4215
+ return 0;
4216
+ },
4217
+ set maxListeners(maxListeners) {}
4218
+ });
4219
+ function map(event, mapFunc) {
4220
+ return Object.assign((listener, thisArgs, disposables) => event((i) => listener.call(thisArgs, mapFunc(i)), undefined, disposables), {
4221
+ maxListeners: 0
4222
+ });
4223
+ }
4224
+ Event2.map = map;
4225
+ })(Event || (Event = {}));
4226
+
4227
+ class CallbackList {
4228
+ get length() {
4229
+ return this._callbacks && this._callbacks.length || 0;
4230
+ }
4231
+ add(callback, context = undefined, bucket) {
4232
+ if (!this._callbacks) {
4233
+ this._callbacks = [];
4234
+ this._contexts = [];
4235
+ }
4236
+ this._callbacks.push(callback);
4237
+ this._contexts.push(context);
4238
+ if (Array.isArray(bucket)) {
4239
+ bucket.push({ dispose: () => this.remove(callback, context) });
4240
+ }
4241
+ }
4242
+ remove(callback, context = undefined) {
4243
+ if (!this._callbacks) {
4244
+ return;
4245
+ }
4246
+ let foundCallbackWithDifferentContext = false;
4247
+ for (let i = 0;i < this._callbacks.length; i++) {
4248
+ if (this._callbacks[i] === callback) {
4249
+ if (this._contexts[i] === context) {
4250
+ this._callbacks.splice(i, 1);
4251
+ this._contexts.splice(i, 1);
4252
+ return;
4253
+ } else {
4254
+ foundCallbackWithDifferentContext = true;
4255
+ }
4256
+ }
4257
+ }
4258
+ if (foundCallbackWithDifferentContext) {
4259
+ throw new Error("When adding a listener with a context, you should remove it with the same context");
4260
+ }
4261
+ }
4262
+ *[Symbol.iterator]() {
4263
+ if (!this._callbacks) {
4264
+ return;
4265
+ }
4266
+ const callbacks = this._callbacks.slice(0);
4267
+ const contexts = this._contexts.slice(0);
4268
+ for (let i = 0;i < callbacks.length; i++) {
4269
+ const callback = callbacks[i];
4270
+ const context = contexts[i];
4271
+ yield (...args) => callback.apply(context, args);
4272
+ }
4273
+ }
4274
+ invoke(...args) {
4275
+ if (!this._callbacks) {
4276
+ return [];
4277
+ }
4278
+ const callbacks = this._callbacks.slice(0);
4279
+ const contexts = this._contexts.slice(0);
4280
+ const ret = [];
4281
+ for (let i = 0;i < callbacks.length; i++) {
4282
+ try {
4283
+ ret.push(callbacks[i].apply(contexts[i], args));
4284
+ } catch (e) {
4285
+ console.error(e);
4286
+ }
4287
+ }
4288
+ return ret;
4289
+ }
4290
+ isEmpty() {
4291
+ return !this._callbacks || this._callbacks.length === 0;
4292
+ }
4293
+ dispose() {
4294
+ this._callbacks = undefined;
4295
+ this._contexts = undefined;
4296
+ }
4297
+ }
4298
+
4299
+ // ../../packages/core/esm/common/utils/emitter.js
4300
+ class Emitter {
4301
+ constructor(_options) {
4302
+ this._options = _options;
4303
+ this._disposed = false;
4304
+ this._leakWarnCountdown = 0;
4305
+ }
4306
+ get event() {
4307
+ if (!this._event) {
4308
+ this._event = Object.assign((listener, thisArgs, disposables) => {
4309
+ if (!this._callbacks) {
4310
+ this._callbacks = new CallbackList;
4311
+ }
4312
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
4313
+ this._options.onFirstListenerAdd(this);
4314
+ }
4315
+ this._callbacks.add(listener, thisArgs);
4316
+ const removeMaxListenersCheck = this.checkMaxListeners(this._event.maxListeners);
4317
+ const result = {
4318
+ dispose: () => {
4319
+ if (removeMaxListenersCheck) {
4320
+ removeMaxListenersCheck();
4321
+ }
4322
+ result.dispose = Emitter._noop;
4323
+ if (!this._disposed) {
4324
+ this._callbacks.remove(listener, thisArgs);
4325
+ result.dispose = Emitter._noop;
4326
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
4327
+ this._options.onLastListenerRemove(this);
4328
+ }
4329
+ }
4330
+ }
4331
+ };
4332
+ if (Array.isArray(disposables)) {
4333
+ disposables.push(result);
4334
+ }
4335
+ return result;
4336
+ }, {
4337
+ maxListeners: Emitter.LEAK_WARNING_THRESHHOLD
4338
+ });
4339
+ }
4340
+ return this._event;
4341
+ }
4342
+ checkMaxListeners(maxListeners) {
4343
+ if (maxListeners === 0 || !this._callbacks) {
4344
+ return;
4345
+ }
4346
+ const listenerCount = this._callbacks.length;
4347
+ if (listenerCount <= maxListeners) {
4348
+ return;
4349
+ }
4350
+ const popStack = this.pushLeakingStack();
4351
+ this._leakWarnCountdown -= 1;
4352
+ if (this._leakWarnCountdown <= 0) {
4353
+ this._leakWarnCountdown = maxListeners * 0.5;
4354
+ let topStack;
4355
+ let topCount = 0;
4356
+ this._leakingStacks.forEach((stackCount, stack) => {
4357
+ if (!topStack || topCount < stackCount) {
4358
+ topStack = stack;
4359
+ topCount = stackCount;
4360
+ }
4361
+ });
4362
+ console.warn(`Possible Emitter memory leak detected. ${listenerCount} listeners added. Use event.maxListeners to increase the limit (${maxListeners}). MOST frequent listener (${topCount}):`);
4363
+ console.warn(topStack);
4364
+ }
4365
+ return popStack;
4366
+ }
4367
+ pushLeakingStack() {
4368
+ if (!this._leakingStacks) {
4369
+ this._leakingStacks = new Map;
4370
+ }
4371
+ const stack = new Error().stack.split(`
4372
+ `).slice(3).join(`
4373
+ `);
4374
+ const count = this._leakingStacks.get(stack) || 0;
4375
+ this._leakingStacks.set(stack, count + 1);
4376
+ return () => this.popLeakingStack(stack);
4377
+ }
4378
+ popLeakingStack(stack) {
4379
+ if (!this._leakingStacks) {
4380
+ return;
4381
+ }
4382
+ const count = this._leakingStacks.get(stack) || 0;
4383
+ this._leakingStacks.set(stack, count - 1);
4384
+ }
4385
+ get hasListeners() {
4386
+ return !!this._callbacks && !this._callbacks.isEmpty();
4387
+ }
4388
+ fire(event) {
4389
+ if (this._callbacks) {
4390
+ this._callbacks.invoke(event);
4391
+ }
4392
+ }
4393
+ async sequence(processor) {
4394
+ if (this._callbacks) {
4395
+ for (const listener of this._callbacks) {
4396
+ if (!await processor(listener)) {
4397
+ break;
4398
+ }
4399
+ }
4400
+ }
4401
+ }
4402
+ dispose() {
4403
+ if (this._leakingStacks) {
4404
+ this._leakingStacks.clear();
4405
+ this._leakingStacks = undefined;
4406
+ }
4407
+ if (this._callbacks) {
4408
+ this._callbacks.dispose();
4409
+ this._callbacks = undefined;
4410
+ }
4411
+ this._disposed = true;
4412
+ }
4413
+ }
4414
+ Emitter.LEAK_WARNING_THRESHHOLD = 175;
4415
+ Emitter._noop = function() {};
4416
+ var WaitUntilEvent;
4417
+ (function(WaitUntilEvent2) {
4418
+ async function fire(emitter, event, timeout = undefined) {
4419
+ const waitables = [];
4420
+ const asyncEvent = Object.assign(event, {
4421
+ waitUntil: (thenable) => {
4422
+ if (Object.isFrozen(waitables)) {
4423
+ throw new Error("waitUntil cannot be called asynchronously.");
4424
+ }
4425
+ waitables.push(thenable);
4426
+ }
4427
+ });
4428
+ try {
4429
+ emitter.fire(asyncEvent);
4430
+ Object.freeze(waitables);
4431
+ } finally {
4432
+ delete asyncEvent.waitUntil;
4433
+ }
4434
+ if (!waitables.length) {
4435
+ return;
4436
+ }
4437
+ if (timeout !== undefined) {
4438
+ await Promise.race([Promise.all(waitables), new Promise((resolve) => setTimeout(resolve, timeout))]);
4439
+ } else {
4440
+ await Promise.all(waitables);
4441
+ }
4442
+ }
4443
+ WaitUntilEvent2.fire = fire;
4444
+ })(WaitUntilEvent || (WaitUntilEvent = {}));
4445
+
4446
+ // ../../packages/core/esm/common/logger/logger-protocol.js
4447
+ var LOGGER_CONFIG = "logger";
4448
+ var LOGGER_LEVEL = `${LOGGER_CONFIG}.level`;
4449
+ var Logger = Symbol("Logger");
4450
+ var TraceIdProvider = Symbol("TraceIdProvider");
4451
+ var LoggerService = Symbol("LoggerService");
4452
+ var LOG_LEVELS = ["verbose", "debug", "info", "warn", "error"];
4453
+ var onLogEmitter = new Emitter;
4454
+
4455
+ // ../../packages/core/esm/common/logger/console-logger.js
4456
+ var RANK = Object.fromEntries(LOG_LEVELS.map((level, index) => [level, index]));
4457
+ var write = {
4458
+ error: (text) => console.error(text),
4459
+ warn: (text) => console.warn(text),
4460
+ info: (text) => console.info(text),
4461
+ debug: (text) => console.debug(text)
4462
+ };
4463
+ var LEVEL = Symbol.for("@celljs/core/logger/level");
4464
+ var Loggers;
4465
+ (function(Loggers2) {
4466
+ function get(context) {
4467
+ return new ConsoleLogger(context);
4468
+ }
4469
+ Loggers2.get = get;
4470
+ function level() {
4471
+ var _a;
4472
+ const set = globalThis[LEVEL];
4473
+ if (set) {
4474
+ return set;
4475
+ }
4476
+ const env = typeof process === "undefined" ? undefined : (_a = process.env) === null || _a === undefined ? undefined : _a.CELL_LOGGER__LEVEL;
4477
+ return env && env in RANK ? env : "info";
4478
+ }
4479
+ Loggers2.level = level;
4480
+ function setLevel(level2) {
4481
+ globalThis[LEVEL] = level2 && level2 in RANK ? level2 : undefined;
4482
+ }
4483
+ Loggers2.setLevel = setLevel;
4484
+ })(Loggers || (Loggers = {}));
4485
+
4486
+ class ConsoleLogger {
4487
+ constructor(context) {
4488
+ this.context = context;
4489
+ }
4490
+ setContext(context) {
4491
+ this.context = context;
4492
+ }
4493
+ isEnabled(level) {
4494
+ var _a, _b;
4495
+ return RANK[level] >= ((_b = RANK[(_a = this.level) !== null && _a !== undefined ? _a : Loggers.level()]) !== null && _b !== undefined ? _b : RANK.info);
4496
+ }
4497
+ error(message, context) {
4498
+ this.log(message, context, write.error, "error");
4499
+ }
4500
+ warn(message, context) {
4501
+ if (this.isEnabled("warn")) {
4502
+ this.log(message, context, write.warn, "warn");
4503
+ }
4504
+ }
4505
+ info(message, context) {
4506
+ if (this.isEnabled("info")) {
4507
+ this.log(message, context, write.info, "info");
4508
+ }
4509
+ }
4510
+ debug(message, context) {
4511
+ if (this.isEnabled("debug")) {
4512
+ this.log(message, context, write.debug, "debug");
4513
+ }
4514
+ }
4515
+ time(label) {
4516
+ var _a;
4517
+ ((_a = this.timeRecords) !== null && _a !== undefined ? _a : this.timeRecords = new Map).set(label, Date.now());
4518
+ }
4519
+ timeEnd(label, context) {
4520
+ var _a;
4521
+ const start = (_a = this.timeRecords) === null || _a === undefined ? undefined : _a.get(label);
4522
+ if (start !== undefined) {
4523
+ const duration = Date.now() - start;
4524
+ this.timeRecords.delete(label);
4525
+ this.log(`${label} [${duration}ms]`, context);
4526
+ return duration;
4527
+ } else {
4528
+ this.log(`No such label: ${label} for timeEnd`, context);
4529
+ return;
4530
+ }
4531
+ }
4532
+ resolveContextString(context) {
4533
+ if (this.context) {
4534
+ return context ? `[${this.context}] [${context}] ` : `[${this.context}] `;
4535
+ }
4536
+ return context ? `[${context}] ` : "";
4537
+ }
4538
+ resolvePrefix(level) {
4539
+ const time = new Date().toISOString();
4540
+ return `${time} [${level}]`;
4541
+ }
4542
+ log(message, context, logFn = write.info, level = "info") {
4543
+ var _a;
4544
+ const traceId = (_a = this.traceIdProvider) === null || _a === undefined ? undefined : _a.provide();
4545
+ const contextStr = this.resolveContextString(context);
4546
+ const text = message instanceof Error ? ErrorUtil.describe(message) : message;
4547
+ let head = this.resolvePrefix(level);
4548
+ if (traceId) {
4549
+ head = head ? `${head} [trace: ${traceId}]` : `[trace: ${traceId}]`;
4550
+ }
4551
+ logFn(`${head ? `${head} ` : ""}${contextStr}${text}`);
4552
+ if (onLogEmitter.hasListeners) {
4553
+ onLogEmitter.fire({
4554
+ level,
4555
+ traceId,
4556
+ rootContext: this.context,
4557
+ context,
4558
+ message
4559
+ });
4560
+ }
4561
+ }
4562
+ }
4563
+
4168
4564
  // web-src/channels.ts
4565
+ var logger = Loggers.get("ta-channels");
4566
+
4169
4567
  class ChannelsClient {
4170
4568
  storage;
4171
4569
  send;
@@ -4356,7 +4754,7 @@ class ChannelsClient {
4356
4754
  }));
4357
4755
  }
4358
4756
  }
4359
- await Promise.all(reads).catch((error) => console.error(error));
4757
+ await Promise.all(reads).catch((error) => logger.error(error));
4360
4758
  }
4361
4759
  update(change) {
4362
4760
  this.current = { ...this.current, ...change };
@@ -4366,1685 +4764,1690 @@ class ChannelsClient {
4366
4764
  }
4367
4765
  }
4368
4766
 
4369
- // web-src/shared-group.tsx
4370
- function useFriends(pi) {
4371
- const [friends, setFriends] = React.useState([]);
4372
- React.useEffect(() => {
4373
- let live = true;
4374
- pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
4375
- return;
4376
- });
4377
- return () => {
4378
- live = false;
4767
+ // ../ta-protocol/esm/common/team-protocol.js
4768
+ var TA_OWNER = "owner";
4769
+ var TA_UNDECLARED = "extensions.install";
4770
+ var TaPermissionUtil;
4771
+ (function(TaPermissionUtil2) {
4772
+ function read(pi) {
4773
+ const given = pi === null || pi === undefined ? undefined : pi.permissions;
4774
+ const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
4775
+ const host2 = map(given === null || given === undefined ? undefined : given.host);
4776
+ const tools = map(given === null || given === undefined ? undefined : given.tools);
4777
+ return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
4778
+ }
4779
+ TaPermissionUtil2.read = read;
4780
+ function host(manifest, method, kind) {
4781
+ var _a, _b, _c, _d;
4782
+ const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
4783
+ const own = (key) => {
4784
+ var _a2;
4785
+ return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
4379
4786
  };
4380
- }, [pi]);
4381
- return friends;
4382
- }
4383
- async function createShared(context, title, friends, agents) {
4384
- const { pi } = context;
4385
- const rooms = pi.rooms;
4386
- if (!rooms) {
4387
- throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
4787
+ 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;
4388
4788
  }
4389
- const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
4390
- await rooms.inviteFriends(room.id, friends);
4391
- for (const agent of agents) {
4392
- await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
4393
- pi.ui.notify(ChannelViews.message(error), "error");
4789
+ TaPermissionUtil2.host = host;
4790
+ })(TaPermissionUtil || (TaPermissionUtil = {}));
4791
+ var action = (id, en, zh, tw, ja, more = {}) => ({
4792
+ id,
4793
+ area: id.split(".")[0],
4794
+ title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
4795
+ ...more
4796
+ });
4797
+ var TA_ACTIONS = [
4798
+ action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
4799
+ action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
4800
+ action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
4801
+ action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
4802
+ action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
4803
+ action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
4804
+ action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
4805
+ action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
4806
+ action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
4807
+ action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
4808
+ action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
4809
+ action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
4810
+ action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
4811
+ action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
4812
+ action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
4813
+ action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
4814
+ action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
4815
+ action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
4816
+ action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
4817
+ action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
4818
+ action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
4819
+ action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
4820
+ action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
4821
+ action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
4822
+ action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
4823
+ action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
4824
+ action("extensions.trust", "Decide how far others' extensions reach", "决定别人的扩展能用到哪一步", "決定別人的擴充功能能用到哪一步", "他の人の拡張機能に許す範囲を決める", { risky: true }),
4825
+ action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
4826
+ action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
4827
+ action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
4828
+ action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
4829
+ action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
4830
+ action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
4831
+ action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
4832
+ ];
4833
+ var TA_OWNER_ACTIONS = [
4834
+ action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
4835
+ action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true }),
4836
+ action("models.owner", "Ask models on the owner's keys", "用你的密钥和本机模型做判断", "用你的金鑰和本機模型做判斷", "あなたのキーとローカルモデルで判断", {
4837
+ risky: true
4838
+ })
4839
+ ];
4840
+ var OWNER_AREAS = ["desktop"];
4841
+ var TaActionUtil;
4842
+ (function(TaActionUtil2) {
4843
+ const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
4844
+ const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
4845
+ function info(id) {
4846
+ return byId.get(id);
4847
+ }
4848
+ TaActionUtil2.info = info;
4849
+ function title(id, language) {
4850
+ var _a;
4851
+ var _b, _c;
4852
+ const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
4853
+ if (!title2) {
4854
+ return id;
4855
+ }
4856
+ return TaLanguageUtil.pick(language, {
4857
+ "zh-CN": title2["zh-CN"],
4858
+ "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
4859
+ "en-US": title2.en,
4860
+ "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
4394
4861
  });
4395
4862
  }
4396
- const { link } = await rooms.invite(room.id);
4397
- await pi.openLink?.(link);
4398
- return room.id;
4399
- }
4400
- var ROOMS_PACKAGE = "@celljs/ta-rooms";
4401
- var ROOMS_KIND = "ta-rooms";
4402
- async function becomeGroup(context, channel, friends, agents) {
4403
- const { pi } = context;
4404
- const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
4405
- const room = await createShared(context, channel.name, friends, members);
4406
- await context.service.updateChannel(channel.id, { shared: room });
4407
- pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
4408
- }
4409
-
4410
- // web-src/create.tsx
4411
- var noBack = (_open, _close) => false;
4412
- var AGENT_PAGE = `${NAME}/agent`;
4413
- function newAgent(context) {
4414
- const { pi, service, ui } = context;
4415
- if (!ui.state.draft) {
4416
- const team = service.state.team;
4417
- const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
4418
- ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
4863
+ TaActionUtil2.title = title;
4864
+ function grantable(id) {
4865
+ const info2 = byId.get(id);
4866
+ return !!info2 && !OWNER_AREAS.includes(info2.area);
4419
4867
  }
4420
- pi.ui.showView(AGENT_PAGE);
4421
- }
4422
- function Identity({ context, onClose }) {
4423
- const { pi, ui } = context;
4424
- const { draft } = useUi(ui);
4425
- const w = ChannelViews.words(pi);
4426
- const ref = React.useRef(null);
4427
- const name = React.useRef(null);
4428
- React.useEffect(() => name.current?.select(), []);
4429
- (pi.ui.useBackLayer ?? noBack)(true, onClose);
4430
- React.useEffect(() => {
4431
- const close = (event) => {
4432
- const target = event.target;
4433
- if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
4434
- onClose();
4868
+ TaActionUtil2.grantable = grantable;
4869
+ function inRoles(id) {
4870
+ var _a;
4871
+ return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
4872
+ }
4873
+ TaActionUtil2.inRoles = inRoles;
4874
+ function inside(dir, path) {
4875
+ const base = dir.replace(/\/+$/, "");
4876
+ return path === base || path.startsWith(`${base}/`) || base === "";
4877
+ }
4878
+ TaActionUtil2.inside = inside;
4879
+ })(TaActionUtil || (TaActionUtil = {}));
4880
+
4881
+ // web-src/notice-util.ts
4882
+ var NoticeUtil;
4883
+ ((NoticeUtil) => {
4884
+ const PARTS = {
4885
+ 决定: "decisions",
4886
+ decisions: "decisions",
4887
+ 约定: "conventions",
4888
+ conventions: "conventions",
4889
+ 待办: "todo",
4890
+ "to do": "todo",
4891
+ todo: "todo",
4892
+ "to-do": "todo"
4893
+ };
4894
+ function counts(text) {
4895
+ const counts2 = { decisions: 0, conventions: 0, todo: 0, done: 0 };
4896
+ let part;
4897
+ for (const line of text.split(/\r?\n/)) {
4898
+ const heading = /^\s*#{1,6}\s+(.+?)\s*#*\s*$/.exec(line) ?? /^\s*\*\*(.+?)\*\*\s*[::]?\s*$/.exec(line);
4899
+ if (heading) {
4900
+ part = PARTS[heading[1].replace(/[::]$/, "").trim().toLowerCase()];
4901
+ continue;
4435
4902
  }
4436
- };
4437
- const onKey = (event) => event.key === "Escape" && onClose();
4438
- document.addEventListener("pointerdown", close);
4439
- document.addEventListener("keydown", onKey);
4440
- return () => {
4441
- document.removeEventListener("pointerdown", close);
4442
- document.removeEventListener("keydown", onKey);
4443
- };
4444
- }, [onClose]);
4445
- if (!draft) {
4446
- return null;
4903
+ const item = /^\s*(?:[-*+]|\d+[.)])\s+(\[( |x|X)\]\s+)?\S/.exec(line);
4904
+ if (!part || !item) {
4905
+ continue;
4906
+ }
4907
+ if (part === "todo" && item[2] && item[2] !== " ") {
4908
+ counts2.done++;
4909
+ } else {
4910
+ counts2[part]++;
4911
+ }
4912
+ }
4913
+ return counts2;
4447
4914
  }
4448
- return /* @__PURE__ */ React.createElement("div", {
4449
- className: "tac-identity",
4450
- ref,
4451
- role: "dialog",
4452
- "aria-label": w.editAgent
4453
- }, /* @__PURE__ */ React.createElement("label", {
4454
- className: "tac-identity-label"
4455
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4456
- className: "tac-input",
4457
- value: draft.name,
4458
- maxLength: 40,
4459
- ref: name,
4460
- onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
4461
- onKeyDown: (event) => event.key === "Enter" && onClose()
4462
- })), /* @__PURE__ */ React.createElement("div", {
4463
- className: "tac-identity-label"
4464
- }, w.avatar), /* @__PURE__ */ React.createElement("div", {
4465
- className: "tac-faces"
4466
- }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
4467
- key: face,
4468
- type: "button",
4469
- "aria-pressed": draft.face === face,
4470
- className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
4471
- onClick: () => ui.set({ draft: { ...draft, face } })
4472
- }, /* @__PURE__ */ React.createElement(Face, {
4473
- face,
4474
- size: 30
4475
- })))));
4476
- }
4477
- function NewAgentHead({ context }) {
4478
- const { pi, ui } = context;
4479
- const { draft, editing } = useUi(ui);
4480
- const w = ChannelViews.words(pi);
4481
- const Down = ChannelViews.icon(pi, "ChevronDown");
4482
- if (!draft) {
4483
- return null;
4915
+ NoticeUtil.counts = counts;
4916
+ function firstLine(text) {
4917
+ for (const line of text.split(/\r?\n/)) {
4918
+ const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(line);
4919
+ if (item) {
4920
+ return item[1].replace(/[*_`~]+/g, "").trim();
4921
+ }
4922
+ }
4923
+ return text.split(/\r?\n/).find((line) => line.trim() && !/^\s*#/.test(line))?.trim() ?? "";
4484
4924
  }
4485
- return /* @__PURE__ */ React.createElement("div", {
4486
- className: "tac-new-head"
4487
- }, /* @__PURE__ */ React.createElement("div", {
4488
- className: "tac-new-title"
4489
- }, /* @__PURE__ */ React.createElement("button", {
4490
- type: "button",
4491
- className: "tac-new-trigger tac-identity-open",
4492
- "aria-expanded": editing,
4493
- title: w.editAgent,
4494
- onClick: () => ui.set({ editing: !editing })
4495
- }, /* @__PURE__ */ React.createElement(Face, {
4496
- face: draft.face,
4497
- size: 20
4498
- }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
4499
- size: 14
4500
- })), editing && /* @__PURE__ */ React.createElement(Identity, {
4501
- context,
4502
- onClose: () => ui.set({ editing: false })
4503
- })), /* @__PURE__ */ React.createElement("button", {
4504
- type: "button",
4505
- className: "tac-button tac-quiet",
4506
- onClick: () => {
4507
- ui.set({ draft: undefined, editing: false });
4508
- pi.ui.showView("");
4925
+ NoticeUtil.firstLine = firstLine;
4926
+ })(NoticeUtil ||= {});
4927
+
4928
+ // web-src/notice.tsx
4929
+ var NoticeView;
4930
+ ((NoticeView) => {
4931
+ function display(text) {
4932
+ return text.replace(/^(\s*[-*+]\s+)\[ \]\s+/gm, "$1☐ ").replace(/^(\s*[-*+]\s+)\[[xX]\]\s+/gm, "$1☑ ");
4933
+ }
4934
+ NoticeView.display = display;
4935
+ function counts(text, language) {
4936
+ const w = ChannelWords.of(language);
4937
+ const counts2 = NoticeUtil.counts(text);
4938
+ if (counts2.decisions + counts2.conventions + counts2.todo === 0) {
4939
+ return NoticeUtil.firstLine(text);
4509
4940
  }
4510
- }, w.cancel));
4511
- }
4512
- function NewAgentPage({ context }) {
4513
- const { pi, service, ui } = context;
4514
- const { draft } = useUi(ui);
4515
- const { loaded } = useChannels(service);
4941
+ const values = { decisions: String(counts2.decisions), conventions: String(counts2.conventions), todo: String(counts2.todo) };
4942
+ return ChannelWords.format(w.noticeCounts, values).split(" · ").filter((_, at) => [counts2.decisions, counts2.conventions, counts2.todo][at] > 0).join(" · ");
4943
+ }
4944
+ NoticeView.counts = counts;
4945
+ })(NoticeView ||= {});
4946
+ function NoticeBar({
4947
+ context,
4948
+ channel,
4949
+ state,
4950
+ onState
4951
+ }) {
4952
+ const { pi, service } = context;
4953
+ const { team } = useChannels(service);
4516
4954
  const w = ChannelViews.words(pi);
4517
- const Pencil = ChannelViews.icon(pi, "Pencil");
4518
- const Composer = pi.ui.Composer;
4519
- const first = React.useRef(true);
4955
+ const notice = channel.notice;
4956
+ const [draft, setDraft] = React.useState("");
4957
+ const [busy, setBusy] = React.useState(false);
4958
+ const [error, setError] = React.useState();
4520
4959
  React.useEffect(() => {
4521
- if (!loaded || !first.current) {
4522
- return;
4523
- }
4524
- first.current = false;
4525
- if (!ui.state.draft) {
4526
- newAgent(context);
4960
+ if (state.editing) {
4961
+ setDraft(notice?.text ?? w.noticeTemplate);
4962
+ setError(undefined);
4527
4963
  }
4528
- }, [loaded, ui, context]);
4529
- if (!draft) {
4964
+ }, [state.editing]);
4965
+ if (!notice && !state.editing) {
4530
4966
  return null;
4531
4967
  }
4532
- const send = async (text) => {
4533
- const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
4534
- ui.set({ draft: undefined, editing: false });
4535
- try {
4536
- const sessionId = await service.openAgent(agent.id);
4537
- context.sessions.set(agent.id, sessionId);
4538
- await pi.switchSession(sessionId);
4539
- await pi.sendUserMessage(text);
4540
- } catch (error) {
4541
- pi.ui.notify(ChannelViews.message(error), "error");
4542
- }
4968
+ const Megaphone = ChannelViews.icon(pi, "Megaphone");
4969
+ const Chevron = ChannelViews.icon(pi, "ChevronDown");
4970
+ const Markdown = pi.ui.Markdown;
4971
+ const save = (event) => {
4972
+ event.preventDefault();
4973
+ setBusy(true);
4974
+ setError(undefined);
4975
+ service.setNotice(channel.id, draft).then(() => {
4976
+ setBusy(false);
4977
+ onState({ open: true, editing: false });
4978
+ }, (failure) => {
4979
+ setBusy(false);
4980
+ setError(ChannelViews.message(failure));
4981
+ });
4543
4982
  };
4983
+ const open = state.open || state.editing;
4544
4984
  return /* @__PURE__ */ React.createElement("div", {
4545
- className: "tac-new-page"
4546
- }, /* @__PURE__ */ React.createElement("div", {
4547
- className: "tac-new-col"
4548
- }, /* @__PURE__ */ React.createElement(Face, {
4549
- face: draft.face,
4550
- size: 88
4551
- }), /* @__PURE__ */ React.createElement("h2", {
4552
- className: "tac-new-name"
4553
- }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
4985
+ className: "tac-notice-bar",
4986
+ "data-open": open ? "" : undefined
4987
+ }, /* @__PURE__ */ React.createElement("button", {
4554
4988
  type: "button",
4555
- className: "tac-action tac-identity-open",
4556
- title: w.editAgent,
4557
- "aria-label": w.editAgent,
4558
- onClick: () => ui.set({ editing: !ui.state.editing })
4559
- }, /* @__PURE__ */ React.createElement(Pencil, {
4560
- size: 14
4561
- }))), /* @__PURE__ */ React.createElement("p", {
4562
- className: "tac-new-hint"
4563
- }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
4564
- className: "tac-new-box"
4565
- }, /* @__PURE__ */ React.createElement(Composer, {
4566
- placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
4567
- onSend: send,
4568
- cwd: draft.cwd,
4569
- onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
4570
- draft: "new-agent"
4571
- }))));
4572
- }
4573
- function NewChannelDialog({ context, onClose }) {
4574
- const { pi, service } = context;
4575
- const { team } = useChannels(service);
4576
- const faces = useFaces(team);
4577
- const w = ChannelViews.words(pi);
4578
- const Search = ChannelViews.icon(pi, "Search");
4579
- const Check = ChannelViews.icon(pi, "Check");
4580
- const [name, setName] = React.useState("");
4581
- const [query, setQuery] = React.useState("");
4582
- const [picked, setPicked] = React.useState([]);
4583
- const friends = useFriends(pi);
4584
- const [pickedFriends, setPickedFriends] = React.useState([]);
4585
- const shared = pickedFriends.length > 0;
4586
- const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
4587
- const [busy, setBusy] = React.useState(false);
4588
- const [error, setError] = React.useState();
4589
- const Dialog = pi.ui.Dialog;
4590
- const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
4591
- const full = picked.length >= MAX_MEMBERS;
4592
- const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
4593
- const create = (event) => {
4594
- event.preventDefault();
4595
- setBusy(true);
4596
- setError(undefined);
4597
- if (shared) {
4598
- createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
4599
- setBusy(false);
4600
- setError(ChannelViews.message(failure));
4601
- });
4602
- return;
4603
- }
4604
- service.createChannel({ name, members: picked }).then((channel) => {
4605
- onClose();
4606
- context.showChannel(channel.id);
4607
- }, (failure) => {
4608
- setBusy(false);
4609
- setError(ChannelViews.message(failure));
4610
- });
4611
- };
4612
- return /* @__PURE__ */ React.createElement(Dialog, {
4613
- title: w.newChannel,
4614
- onClose
4615
- }, /* @__PURE__ */ React.createElement("form", {
4616
- className: "tac-dialog",
4617
- onSubmit: create
4618
- }, /* @__PURE__ */ React.createElement("label", {
4619
- className: "tac-dialog-label"
4620
- }, w.name, /* @__PURE__ */ React.createElement("input", {
4621
- className: "tac-input tac-dialog-input",
4622
- value: name,
4623
- placeholder: w.channelNamePlaceholder,
4624
- maxLength: 40,
4625
- autoFocus: true,
4626
- onChange: (event) => setName(event.target.value)
4627
- })), /* @__PURE__ */ React.createElement("div", {
4628
- className: "tac-dialog-label"
4629
- }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
4630
- className: "tac-dialog-count"
4631
- }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
4632
- className: "tac-dialog-search"
4633
- }, /* @__PURE__ */ React.createElement(Search, {
4989
+ className: "tac-notice-head",
4990
+ "aria-expanded": open,
4991
+ title: open ? w.noticeHide : w.noticeShow,
4992
+ onClick: () => onState({ open: !open, editing: false })
4993
+ }, /* @__PURE__ */ React.createElement("span", {
4994
+ className: "tac-notice-icon"
4995
+ }, /* @__PURE__ */ React.createElement(Megaphone, {
4996
+ size: 13,
4997
+ strokeWidth: 2
4998
+ })), /* @__PURE__ */ React.createElement("strong", null, w.notice), /* @__PURE__ */ React.createElement("span", {
4999
+ className: "tac-notice-sum"
5000
+ }, notice ? NoticeView.counts(notice.text, pi.ui.language) : w.noticeEmpty), /* @__PURE__ */ React.createElement("span", {
5001
+ className: "tac-notice-chevron"
5002
+ }, /* @__PURE__ */ React.createElement(Chevron, {
4634
5003
  size: 15
4635
- }), /* @__PURE__ */ React.createElement("input", {
4636
- value: query,
4637
- placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
4638
- "aria-label": w.search,
4639
- onChange: (event) => setQuery(event.target.value)
5004
+ }))), open && !state.editing && notice && /* @__PURE__ */ React.createElement("div", {
5005
+ className: "tac-notice-body"
5006
+ }, /* @__PURE__ */ React.createElement("div", {
5007
+ className: "tac-notice-text"
5008
+ }, /* @__PURE__ */ React.createElement(Markdown, {
5009
+ text: NoticeView.display(notice.text)
4640
5010
  })), /* @__PURE__ */ React.createElement("div", {
4641
- className: "tac-pick-list"
4642
- }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4643
- compact: true,
4644
- title: w.noAgents,
4645
- hint: w.noAgentsHint
4646
- }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
4647
- compact: true,
4648
- title: w.noMatch
4649
- }), shown.map((agent) => {
4650
- const on = picked.includes(agent.id);
4651
- return /* @__PURE__ */ React.createElement("button", {
4652
- key: agent.id,
4653
- type: "button",
4654
- "aria-pressed": on,
4655
- disabled: !on && full,
4656
- className: `tac-pick${on ? " tac-on" : ""}`,
4657
- onClick: () => toggle(agent)
4658
- }, /* @__PURE__ */ React.createElement("span", {
4659
- className: "tac-check"
4660
- }, on && /* @__PURE__ */ React.createElement(Check, {
4661
- size: 13,
4662
- strokeWidth: 3
4663
- })), /* @__PURE__ */ React.createElement(AgentAvatar, {
4664
- agent,
4665
- faces,
4666
- size: 30
4667
- }), /* @__PURE__ */ React.createElement("span", {
4668
- className: "tac-pick-text"
4669
- }, /* @__PURE__ */ React.createElement("span", {
4670
- className: "tac-pick-name"
4671
- }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
4672
- className: "tac-msg-lead"
4673
- }, w.lead)), /* @__PURE__ */ React.createElement("span", {
4674
- className: "tac-pick-role"
4675
- }, agent.role.split(`
4676
- `)[0])));
4677
- })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
4678
- className: "tac-dialog-label"
4679
- }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
4680
- className: "tac-dialog-count"
4681
- }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
4682
- className: "tac-pick-list"
4683
- }, friends.map((friend) => {
4684
- const on = pickedFriends.includes(friend.id);
4685
- return /* @__PURE__ */ React.createElement("button", {
4686
- key: friend.id,
4687
- type: "button",
4688
- "aria-pressed": on,
4689
- className: `tac-pick${on ? " tac-on" : ""}`,
4690
- onClick: () => toggleFriend(friend)
4691
- }, /* @__PURE__ */ React.createElement("span", {
4692
- className: "tac-check"
4693
- }, on && /* @__PURE__ */ React.createElement(Check, {
4694
- size: 13,
4695
- strokeWidth: 3
4696
- })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
4697
- seed: friend.id,
4698
- size: 30,
4699
- look: friend.look
4700
- }) : /* @__PURE__ */ React.createElement("span", {
4701
- className: "tac-pick-face"
4702
- }), /* @__PURE__ */ React.createElement("span", {
4703
- className: "tac-pick-text"
4704
- }, /* @__PURE__ */ React.createElement("span", {
4705
- className: "tac-pick-name"
4706
- }, friend.name), /* @__PURE__ */ React.createElement("span", {
4707
- className: "tac-pick-role"
4708
- }, w.friend)));
4709
- }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
5011
+ className: "tac-notice-foot"
5012
+ }, /* @__PURE__ */ React.createElement("span", null, ChannelWords.format(w.noticeBy, {
5013
+ name: ChannelsText.authorName(team, notice.by, { user: w.you, ta: w.ta }),
5014
+ time: SidebarUtil.time(notice.at, pi.ui.language)
5015
+ })), /* @__PURE__ */ React.createElement("button", {
5016
+ type: "button",
5017
+ className: "tac-button tac-quiet",
5018
+ onClick: () => onState({ open: true, editing: true })
5019
+ }, w.noticeEdit))), state.editing && /* @__PURE__ */ React.createElement("form", {
5020
+ className: "tac-notice-body tac-notice-form",
5021
+ onSubmit: save
5022
+ }, /* @__PURE__ */ React.createElement("p", {
4710
5023
  className: "tac-dialog-note"
4711
- }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
4712
- className: "tac-empty tac-error"
5024
+ }, w.noticeHint), /* @__PURE__ */ React.createElement("textarea", {
5025
+ className: "tac-input tac-notice-input",
5026
+ value: draft,
5027
+ "aria-label": w.noticeEdit,
5028
+ autoFocus: true,
5029
+ onChange: (event) => setDraft(event.target.value)
5030
+ }), error && /* @__PURE__ */ React.createElement("div", {
5031
+ className: "tac-error"
4713
5032
  }, error), /* @__PURE__ */ React.createElement("div", {
4714
- className: "tac-dialog-actions"
5033
+ className: "tac-notice-actions"
4715
5034
  }, /* @__PURE__ */ React.createElement("button", {
5035
+ type: "button",
5036
+ className: "tac-button tac-quiet",
5037
+ onClick: () => onState({ open: !!notice, editing: false })
5038
+ }, w.cancel), /* @__PURE__ */ React.createElement("button", {
4716
5039
  type: "submit",
4717
5040
  className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
4718
- disabled: busy || !name.trim() || picked.length === 0 && !shared
4719
- }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
5041
+ disabled: busy || draft.trim() === (notice?.text ?? "")
5042
+ }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
4720
5043
  className: "ta-spinner ta-busy-mark ta-on-brand"
4721
5044
  })))));
4722
5045
  }
4723
5046
 
4724
- // web-src/handoff.ts
4725
- var HandOff;
4726
- ((HandOff) => {
4727
- HandOff.TOOL = "hand_off";
4728
- HandOff.CARD = "ta-channels-handoff";
4729
- HandOff.BLOCK = "ta-handoff";
4730
- const MARK = /\[ta-handoff:([^\]\s]+)\]/;
4731
- HandOff.DEFINITION = {
4732
- name: HandOff.TOOL,
4733
- label: "Hand off",
4734
- 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.",
4735
- promptSnippet: "Hand the work over to one of the user's agents or channels",
4736
- parameters: {
4737
- type: "object",
4738
- properties: {
4739
- to: { type: "string", description: "@name of an agent or #name of a channel." },
4740
- brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
4741
- },
4742
- required: ["to", "brief"]
4743
- }
4744
- };
4745
- function ref(target) {
4746
- return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
4747
- }
4748
- HandOff.ref = ref;
4749
- function ask(language, to) {
4750
- const fence = "```";
4751
- const context = [
4752
- `[ta-handoff:${to}]`,
4753
- `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
4754
- `- 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.`,
4755
- `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
4756
- `- 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):`,
4757
- `${fence}${HandOff.BLOCK}`,
4758
- "<the brief>",
4759
- fence,
4760
- `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
4761
- ].join(`
4762
- `);
4763
- const line = TaLanguageUtil.pick(language, {
4764
- "zh-CN": `把这件事交给 ${to}`,
4765
- "zh-TW": `把這件事交給 ${to}`,
4766
- "en-US": `Hand this over to ${to}`,
4767
- "ja-JP": `これを ${to} に引き継ぐ`
5047
+ // web-src/room.tsx
5048
+ var RUN_MS = 5 * 60 * 1000;
5049
+ var PAUSE_MS = 15 * 60 * 1000;
5050
+ var RoomUtil;
5051
+ ((RoomUtil) => {
5052
+ function rows(messages) {
5053
+ return messages.map((message, index) => {
5054
+ const before = messages[index - 1];
5055
+ const separator = !before || message.at - before.at > PAUSE_MS;
5056
+ const first = separator || before.author !== message.author || before.by !== message.by || before.author === SYSTEM || !!before.notice || message.at - before.at > RUN_MS;
5057
+ return { message, first, separator };
4768
5058
  });
4769
- return TaMessageContext.wrap(context, line);
4770
5059
  }
4771
- HandOff.ask = ask;
4772
- function asked(text) {
4773
- return MARK.exec(text)?.[1];
5060
+ RoomUtil.rows = rows;
5061
+ function choice(agent, text) {
5062
+ return `@${agent.name} ${TaMessageContext.strip(text)}`;
4774
5063
  }
4775
- HandOff.asked = asked;
4776
- function find(text) {
4777
- const lines = text.split(/\r?\n/);
4778
- let found;
4779
- for (let index = 0;index < lines.length; index++) {
4780
- const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
4781
- if (open?.[2] !== HandOff.BLOCK) {
4782
- continue;
4783
- }
4784
- const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
4785
- const end = lines.findIndex((line, at) => at > index && close.test(line));
4786
- found = lines.slice(index + 1, end < 0 ? lines.length : end);
4787
- index = end < 0 ? lines.length : end;
5064
+ RoomUtil.choice = choice;
5065
+ function answer(messages, message, agent) {
5066
+ const said = messages.slice(messages.indexOf(message) + 1).find((later) => later.author === USER && !later.notice);
5067
+ if (!said) {
5068
+ return;
4788
5069
  }
4789
- const brief = found?.join(`
4790
- `).trim();
4791
- return brief || undefined;
4792
- }
4793
- HandOff.find = find;
4794
- function message(origin, brief, language) {
4795
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4796
- const head = TaLanguageUtil.pick(language, {
4797
- "zh-CN": `(交接自“${title}”)`,
4798
- "zh-TW": `(交接自「${title}」)`,
4799
- "en-US": `(Handed over from “${title}”)`,
4800
- "ja-JP": `(“${title}” から引き継ぎました)`
4801
- });
4802
- const context = [
4803
- "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.",
4804
- 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.` : ""
4805
- ].filter(Boolean).join(`
4806
- `);
4807
- return TaMessageContext.wrap(context, `${head}
4808
-
4809
- ${brief.trim()}`);
4810
- }
4811
- HandOff.message = message;
4812
- function channelText(origin, brief, language) {
4813
- const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
4814
- return `${TaLanguageUtil.pick(language, {
4815
- "zh-CN": `(交接自“${title}”)`,
4816
- "zh-TW": `(交接自「${title}」)`,
4817
- "en-US": `(Handed over from “${title}”)`,
4818
- "ja-JP": `(“${title}” から引き継ぎました)`
4819
- })}
4820
-
4821
- ${brief.trim()}`;
4822
- }
4823
- HandOff.channelText = channelText;
4824
- function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
4825
- return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
4826
- }
4827
- HandOff.serverLanguage = serverLanguage;
4828
- function result(target) {
4829
- 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.`;
5070
+ const named = `@${agent.name} `;
5071
+ return said.text.startsWith(named) ? said.text.slice(named.length) : said.text;
4830
5072
  }
4831
- HandOff.result = result;
4832
- })(HandOff ||= {});
4833
-
4834
- // web-src/handoff-view.tsx
4835
- var HandOffViewUtil;
4836
- ((HandOffViewUtil) => {
4837
- function members(team, target) {
4838
- if (target.kind === "agent") {
4839
- const agent = team.agents.find((candidate) => candidate.id === target.id);
4840
- return agent ? [agent] : [];
5073
+ RoomUtil.answer = answer;
5074
+ })(RoomUtil ||= {});
5075
+ function AgentText({ context, channelId, agent, text, answer }) {
5076
+ const { pi, service } = context;
5077
+ const send = React.useCallback((said) => service.post(channelId, RoomUtil.choice(agent, said)), [service, channelId, agent.name]);
5078
+ return /* @__PURE__ */ React.createElement(pi.ui.Markdown, {
5079
+ text,
5080
+ send,
5081
+ answer
5082
+ });
5083
+ }
5084
+ function MessagePictures({ context, channelId, message, alt }) {
5085
+ const { pi, service } = context;
5086
+ const images = message.images ?? [];
5087
+ const [sources, setSources] = React.useState({});
5088
+ const ids = images.map((image) => image.id).join(",");
5089
+ React.useEffect(() => {
5090
+ let live = true;
5091
+ for (const id of ids ? ids.split(",") : []) {
5092
+ service.picture(channelId, id).then((data) => live && data && setSources((current) => ({ ...current, [id]: data })));
4841
5093
  }
4842
- const channel = team.channels.find((candidate) => candidate.id === target.id);
4843
- return channel ? membersOf(team, channel) : [];
5094
+ return () => {
5095
+ live = false;
5096
+ };
5097
+ }, [service, channelId, ids]);
5098
+ const ChatImages = pi.ui.ChatImages;
5099
+ if (!images.length || !ChatImages) {
5100
+ return null;
4844
5101
  }
4845
- HandOffViewUtil.members = members;
4846
- })(HandOffViewUtil ||= {});
4847
- function useTeam(context) {
4848
- return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
5102
+ return /* @__PURE__ */ React.createElement("div", {
5103
+ className: "tac-pics"
5104
+ }, /* @__PURE__ */ React.createElement(ChatImages, {
5105
+ alt,
5106
+ images: images.map((image) => ({ key: image.id, src: sources[image.id], width: image.w, height: image.h }))
5107
+ }));
4849
5108
  }
4850
- function HandOffCard({ context, message }) {
4851
- const card = message.details;
4852
- const team = useTeam(context);
4853
- const faces = useFaces(team);
4854
- if (!card?.target) {
5109
+ function Mentions({ text, agents }) {
5110
+ const names = new Set(agents.map((agent) => agent.name.toLowerCase()));
5111
+ const parts = text.split(/(@[^\s@#,,。::]+)/);
5112
+ return /* @__PURE__ */ React.createElement("span", null, parts.map((part, index) => part.startsWith("@") && names.has(part.slice(1).toLowerCase()) ? /* @__PURE__ */ React.createElement("span", {
5113
+ key: index,
5114
+ className: "tac-mention"
5115
+ }, part) : part));
5116
+ }
5117
+ function StopLine({
5118
+ context,
5119
+ channel,
5120
+ message,
5121
+ later,
5122
+ agents
5123
+ }) {
5124
+ const { pi, service } = context;
5125
+ const w = ChannelViews.words(pi);
5126
+ const [busy, setBusy] = React.useState(false);
5127
+ const stop = message.stop;
5128
+ const lead = agents.find((agent) => agent.id === channel.members.find((id) => !(channel.muted ?? []).includes(id)));
5129
+ const replies = String(stop?.replies ?? 0);
5130
+ const tokens = stop?.tokens ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(stop.tokens) : "";
5131
+ const stats = stop ? ChannelWords.format(tokens ? w.stoppedStats : w.stoppedReplies, { replies, tokens }) : "";
5132
+ const resumed = stop?.resumed === "continue" ? w.wentOn : stop?.resumed === "wrapUp" ? w.summedUp : "";
5133
+ 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;
5134
+ const extended = stop?.extended ? w.extendedOnce : "";
5135
+ const go = (how) => {
5136
+ setBusy(true);
5137
+ service.resumeRound(channel.id, message.id, how).catch((error) => pi.ui.notify(ChannelViews.message(error), "error")).finally(() => setBusy(false));
5138
+ };
5139
+ const open = !!stop?.pending.length && !stop.resumed && !later;
5140
+ return /* @__PURE__ */ React.createElement("div", {
5141
+ className: "tac-stop",
5142
+ role: "note"
5143
+ }, /* @__PURE__ */ React.createElement("div", {
5144
+ className: "tac-notice"
5145
+ }, why), /* @__PURE__ */ React.createElement("div", {
5146
+ className: "tac-stop-meta"
5147
+ }, [stats, extended, resumed].filter(Boolean).join(" · ")), open && /* @__PURE__ */ React.createElement("div", {
5148
+ className: "tac-stop-actions"
5149
+ }, /* @__PURE__ */ React.createElement("button", {
5150
+ type: "button",
5151
+ className: "tac-stop-button",
5152
+ disabled: busy,
5153
+ onClick: () => go("continue")
5154
+ }, w.keepGoing), lead && /* @__PURE__ */ React.createElement("button", {
5155
+ type: "button",
5156
+ className: "tac-stop-button",
5157
+ disabled: busy,
5158
+ onClick: () => go("wrapUp")
5159
+ }, ChannelWords.format(w.wrapUp, { name: `@${lead.name}` }))));
5160
+ }
5161
+ function ChannelHead({ context }) {
5162
+ const { pi, service, ui } = context;
5163
+ const state = useChannels(service);
5164
+ const { channelId } = useUi(ui);
5165
+ const faces = useFaces(state.team);
5166
+ const w = ChannelViews.words(pi);
5167
+ const shown = !!pi.ui.useView(MEMBERS_VIEW)?.shown;
5168
+ const roomInfo = !!pi.ui.useView(ROOM_INFO_VIEW)?.shown;
5169
+ const follow = React.useRef(roomInfo);
5170
+ follow.current = roomInfo;
5171
+ React.useEffect(() => {
5172
+ if (channelId && follow.current) {
5173
+ context.showMembers();
5174
+ }
5175
+ }, [channelId, context]);
5176
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5177
+ if (!channel) {
4855
5178
  return null;
4856
5179
  }
4857
- const w = ChannelViews.words(context.pi);
4858
- const members = HandOffViewUtil.members(team, card.target);
4859
- 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);
5180
+ const members = membersOf(state.team, channel);
5181
+ const working = state.working[channel.id] ?? [];
4860
5182
  return /* @__PURE__ */ React.createElement("div", {
4861
- className: "tac-handoff"
5183
+ className: "tac-head"
4862
5184
  }, /* @__PURE__ */ React.createElement("div", {
4863
- className: "tac-handoff-head"
4864
- }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
5185
+ className: "tac-head-title"
5186
+ }, /* @__PURE__ */ React.createElement("strong", null, channel.name), /* @__PURE__ */ React.createElement("span", {
5187
+ className: "tac-head-count"
5188
+ }, ChannelWords.format(w.memberCount, { count: String(members.length) })), channel.topic && /* @__PURE__ */ React.createElement("span", {
5189
+ className: "tac-head-topic"
5190
+ }, channel.topic)), /* @__PURE__ */ React.createElement("button", {
5191
+ type: "button",
5192
+ className: `tac-head-members${shown ? " tac-on" : ""}`,
5193
+ title: w.showMembers,
5194
+ "aria-label": w.showMembers,
5195
+ "aria-pressed": shown,
5196
+ onClick: () => context.showMembers()
5197
+ }, members.slice(0, 5).map((agent) => /* @__PURE__ */ React.createElement("span", {
5198
+ key: agent.id,
5199
+ className: "tac-head-face"
5200
+ }, /* @__PURE__ */ React.createElement(AgentAvatar, {
5201
+ agent,
5202
+ faces,
5203
+ size: 24,
5204
+ working: working.includes(agent.id)
5205
+ }))), members.length > 5 && /* @__PURE__ */ React.createElement("span", {
5206
+ className: "tac-head-more"
5207
+ }, "+", members.length - 5)));
5208
+ }
5209
+ function ChannelSceneHead({ context, channelId }) {
5210
+ const { pi, service } = context;
5211
+ const state = useChannels(service);
5212
+ const faces = useFaces(state.team);
5213
+ const w = ChannelViews.words(pi);
5214
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5215
+ if (!channel) {
5216
+ return null;
5217
+ }
5218
+ const members = membersOf(state.team, channel);
5219
+ const working = state.working[channel.id] ?? [];
5220
+ const External = ChannelViews.icon(pi, "ExternalLink");
5221
+ return /* @__PURE__ */ React.createElement("div", {
5222
+ className: "tac-scene-head"
5223
+ }, /* @__PURE__ */ React.createElement(RoomFace, {
4865
5224
  members,
4866
5225
  faces,
4867
- size: 20,
4868
- working: []
4869
- }), /* @__PURE__ */ React.createElement("span", {
4870
- className: "tac-handoff-title"
4871
- }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
5226
+ size: 26,
5227
+ working
5228
+ }), /* @__PURE__ */ React.createElement("div", {
5229
+ className: "tac-scene-title"
5230
+ }, /* @__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", {
4872
5231
  type: "button",
4873
- className: "tac-link",
4874
- onClick: open
4875
- }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
4876
- className: "tac-handoff-brief"
4877
- }, card.brief));
5232
+ className: "tac-button tac-scene-main",
5233
+ title: w.openInMainHint,
5234
+ onClick: () => context.showChannel(channel.id)
5235
+ }, /* @__PURE__ */ React.createElement(External, {
5236
+ size: 13
5237
+ }), w.openInMain));
4878
5238
  }
4879
- var HandOffView;
4880
- ((HandOffView) => {
4881
- function card(context) {
4882
- return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
4883
- context,
4884
- message
4885
- });
4886
- }
4887
- HandOffView.card = card;
4888
- function icon(context, target, icons) {
4889
- const key = `${target.kind}:${target.id}`;
4890
- let node2 = icons.get(key);
4891
- if (!node2) {
4892
- const Face2 = () => {
4893
- const team = useTeam(context);
4894
- const faces = useFaces(team);
4895
- const members = HandOffViewUtil.members(team, target);
4896
- return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
4897
- members,
4898
- faces,
4899
- size: 16,
4900
- working: []
4901
- }) : null;
4902
- };
4903
- node2 = /* @__PURE__ */ React.createElement(Face2, null);
4904
- icons.set(key, node2);
4905
- }
4906
- return node2;
4907
- }
4908
- function composerAddon(context) {
4909
- const icons = new Map;
4910
- const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
4911
- clientMessageId: ChannelsUtil.newId("handoff-ask"),
4912
- message: HandOff.ask(context.pi.ui.language, to),
4913
- streamingBehavior: "followUp"
4914
- }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
4915
- return {
4916
- actions: (conversation) => {
4917
- const { team } = context.service.state;
4918
- if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
4919
- return [];
4920
- }
4921
- const w = ChannelViews.words(context.pi);
4922
- const Forward = ChannelViews.icon(context.pi, "Forward");
4923
- const agents = team.agents.filter((agent) => !agent.temporary).map((agent) => ({
4924
- key: `handoff:agent:${agent.id}`,
4925
- label: agent.name,
4926
- detail: agent.role.split(`
4927
- `)[0],
4928
- group: w.agents,
4929
- icon: icon(context, { kind: "agent", id: agent.id }, icons),
4930
- run: () => send(conversation, `@${agent.name}`)
4931
- }));
4932
- const channels = team.channels.map((channel) => ({
4933
- key: `handoff:channel:${channel.id}`,
4934
- label: `#${channel.name}`,
4935
- detail: channel.topic,
4936
- group: w.channels,
4937
- icon: icon(context, { kind: "channel", id: channel.id }, icons),
4938
- run: () => send(conversation, `#${channel.name}`)
4939
- }));
4940
- return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
4941
- size: 16
4942
- }), items: [...agents, ...channels] }];
4943
- },
4944
- subscribe: (listener) => context.service.subscribe(listener)
5239
+ var mePromise;
5240
+ function useMe(pi) {
5241
+ const [me, setMe] = React.useState(TA_OWNER);
5242
+ React.useEffect(() => {
5243
+ mePromise ??= pi.server.getServerInfo().then((info) => info.member?.id ?? TA_OWNER, () => TA_OWNER);
5244
+ let live = true;
5245
+ mePromise.then((id) => live && setMe(id));
5246
+ return () => {
5247
+ live = false;
4945
5248
  };
4946
- }
4947
- HandOffView.composerAddon = composerAddon;
4948
- })(HandOffView ||= {});
4949
-
4950
- // web-src/round-rules.ts
4951
- var ChannelRounds;
4952
- ((ChannelRounds) => {
4953
- const SHORT = 20;
4954
- const MIN_PAIRS = 8;
4955
- const ALIKE = 0.8;
4956
- const PING_PONG = 4;
4957
- const NEW = 0.35;
4958
- const CHANGES = new Set(["edit", "write", "delete", "move"]);
4959
- function scale(watchedAt, pages, now) {
4960
- if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
4961
- return 2;
4962
- }
4963
- return pages === undefined || pages > 0 ? 1 : 0.5;
4964
- }
4965
- ChannelRounds.scale = scale;
4966
- function idle(said, progress) {
4967
- const last = said.at(-1);
4968
- if (!last) {
4969
- return;
4970
- }
4971
- const pairs = said.map((item) => pairsOf(item.text));
4972
- const mine = pairs[pairs.length - 1];
4973
- if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
4974
- return "repeat";
4975
- }
4976
- const recent = said.slice(-3);
4977
- if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
4978
- return "agree";
5249
+ }, [pi]);
5250
+ return me;
5251
+ }
5252
+ function ChannelRoom({ context, channelId: fixed }) {
5253
+ const { pi, service, ui } = context;
5254
+ const me = useMe(pi);
5255
+ const state = useChannels(service);
5256
+ const shown = useUi(ui).channelId;
5257
+ const channelId = fixed ?? shown;
5258
+ const faces = useFaces(state.team);
5259
+ const w = ChannelViews.words(pi);
5260
+ const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5261
+ const messages = channel ? state.messages[channel.id] : undefined;
5262
+ const working = channel ? state.working[channel.id] ?? [] : [];
5263
+ React.useEffect(() => {
5264
+ if (channelId) {
5265
+ service.messages(channelId);
4979
5266
  }
4980
- const run = said.slice(-PING_PONG);
4981
- const authors = new Set(run.map((item) => item.author));
4982
- const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
4983
- const start = said.length - PING_PONG;
4984
- if (progress || start <= 0 || authors.size !== 2 || !alternate) {
5267
+ }, [service, channelId]);
5268
+ const page = pi.ui.useView(CHANNEL_PAGE);
5269
+ const inFront = !!channelId && (!!fixed || !!page?.shown);
5270
+ const lastAt = ChannelSeenUtil.lastAt(messages);
5271
+ const resting = working.length === 0;
5272
+ React.useEffect(() => {
5273
+ if (!channelId || !inFront || !resting) {
4985
5274
  return;
4986
5275
  }
4987
- const seen = new Set(pairs.slice(0, start).flat());
4988
- for (const own of pairs.slice(start)) {
4989
- const fresh = own.filter((pair) => !seen.has(pair)).length;
4990
- if (own.length === 0 || fresh / own.length >= NEW) {
4991
- return;
4992
- }
4993
- for (const pair of own) {
4994
- seen.add(pair);
4995
- }
4996
- }
4997
- return "pingPong";
4998
- }
4999
- ChannelRounds.idle = idle;
5000
- function day(now) {
5001
- const date = new Date(now);
5002
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
5003
- }
5004
- ChannelRounds.day = day;
5005
- function limits(stored) {
5006
- const given = stored ?? {};
5007
- const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
5008
- return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
5009
- }
5010
- ChannelRounds.limits = limits;
5011
- function today(stored, now) {
5012
- const current = day(now);
5013
- return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
5014
- }
5015
- ChannelRounds.today = today;
5016
- function spend(stored, channelId, tokens, now) {
5017
- const current = today(stored, now);
5018
- return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
5019
- }
5020
- ChannelRounds.spend = spend;
5021
- function held(spent, limits2, channelId, hops, granted = false) {
5022
- if (granted) {
5276
+ const look = () => document.visibilityState === "visible" && context.seen.look(channelId, Math.max(Date.now(), lastAt ?? 0));
5277
+ look();
5278
+ document.addEventListener("visibilitychange", look);
5279
+ return () => document.removeEventListener("visibilitychange", look);
5280
+ }, [context, channelId, inFront, resting, lastAt]);
5281
+ React.useEffect(() => {
5282
+ if (!channelId) {
5023
5283
  return;
5024
5284
  }
5025
- if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
5026
- return "all";
5027
- }
5028
- if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
5029
- return "channel";
5030
- }
5031
- return;
5032
- }
5033
- ChannelRounds.held = held;
5034
- function changedFiles(entries) {
5035
- for (const entry of entries) {
5036
- const message = entry?.message;
5037
- if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
5038
- continue;
5039
- }
5040
- for (const part of message.content) {
5041
- if (part?.type !== "toolCall") {
5042
- continue;
5043
- }
5044
- if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
5045
- return true;
5046
- }
5047
- }
5048
- }
5049
- return false;
5050
- }
5051
- ChannelRounds.changedFiles = changedFiles;
5052
- function units(text) {
5053
- return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
5054
- }
5055
- function pairsOf(text) {
5056
- const words = units(text);
5057
- return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
5058
- }
5059
- function alike(a, b) {
5060
- if (a.length === 0 || b.length === 0) {
5061
- return 0;
5062
- }
5063
- const left = new Map;
5064
- for (const pair of a) {
5065
- left.set(pair, (left.get(pair) ?? 0) + 1);
5066
- }
5067
- let common = 0;
5068
- for (const pair of b) {
5069
- const n = left.get(pair) ?? 0;
5070
- if (n > 0) {
5071
- left.set(pair, n - 1);
5072
- common++;
5073
- }
5074
- }
5075
- return 2 * common / (a.length + b.length);
5076
- }
5077
- })(ChannelRounds ||= {});
5078
-
5079
- // web-src/limit-settings.tsx
5080
- function amount(pi, tokens) {
5081
- return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
5082
- }
5083
- function useLimits(pi) {
5084
- const read = React.useCallback(async () => ({
5085
- limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
5086
- ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
5087
- }), [pi]);
5088
- const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
5089
- React.useEffect(() => {
5090
- let live = true;
5091
- const load = () => void read().then((next) => live && setValue(next), () => {
5285
+ const watch = () => document.visibilityState === "visible" && void service.watch(channelId).catch(() => {
5092
5286
  return;
5093
5287
  });
5094
- load();
5095
- const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
5288
+ watch();
5289
+ const timer = setInterval(watch, WATCH_MS);
5290
+ document.addEventListener("visibilitychange", watch);
5096
5291
  return () => {
5097
- live = false;
5098
- stop();
5292
+ clearInterval(timer);
5293
+ document.removeEventListener("visibilitychange", watch);
5099
5294
  };
5100
- }, [pi, read]);
5101
- return value;
5102
- }
5103
- function limitSettings(pi, service) {
5104
- const words = () => ChannelWords.of(pi.ui.language);
5105
- const row = (key) => function Choices() {
5106
- const { limits } = useLimits(pi);
5107
- const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
5108
- return /* @__PURE__ */ React.createElement("fieldset", {
5109
- className: "ta-segmented",
5110
- "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
5111
- }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
5112
- key: value,
5113
- type: "button",
5114
- "aria-pressed": limits[key] === value,
5115
- className: limits[key] === value ? "ta-on" : "",
5116
- onClick: () => pick(value)
5117
- }, amount(pi, value))));
5118
- };
5119
- function Spent() {
5120
- const { spent } = useLimits(pi);
5121
- return /* @__PURE__ */ React.createElement("span", {
5122
- className: "tac-limit-spent"
5123
- }, spent > 0 ? amount(pi, spent) : "0");
5295
+ }, [service, channelId]);
5296
+ const sent = React.useMemo(() => messages?.filter((message) => message.author === USER).length ?? 0, [messages]);
5297
+ const list = pi.ui.useChatScroll(sent, channelId);
5298
+ const [notice, setNotice] = React.useState({ open: false, editing: false });
5299
+ React.useEffect(() => setNotice({ open: false, editing: false }), [channelId]);
5300
+ const Markdown = pi.ui.Markdown;
5301
+ const Composer = pi.ui.Composer;
5302
+ const Avatar = pi.ui.Avatar;
5303
+ if (!channel) {
5304
+ return /* @__PURE__ */ React.createElement("div", {
5305
+ className: "tac-room-page"
5306
+ }, state.loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5307
+ title: w.pick
5308
+ }));
5124
5309
  }
5125
- return {
5126
- title: () => words().limitsTitle,
5127
- icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
5128
- group: "ta",
5129
- rows: [
5130
- { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
5131
- { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
5132
- { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
5133
- { key: "spent", label: () => words().limitSpent, render: Spent }
5134
- ]
5135
- };
5310
+ const members = membersOf(state.team, channel);
5311
+ const agentOf = (id) => state.team.agents.find((agent) => agent.id === id);
5312
+ const reply = ChannelsText.replyOf(channel);
5313
+ const lead = members.find((agent) => !(channel.muted ?? []).includes(agent.id));
5314
+ const placeholder = reply === "all" ? w.placeholderAll : reply === "lead" && lead ? w.placeholderLead : w.placeholder;
5315
+ const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5316
+ const time = (at) => SidebarUtil.time(at, pi.ui.language);
5317
+ return /* @__PURE__ */ React.createElement("div", {
5318
+ className: "tac-room-page"
5319
+ }, /* @__PURE__ */ React.createElement(NoticeBar, {
5320
+ context,
5321
+ channel,
5322
+ state: notice,
5323
+ onState: setNotice
5324
+ }), /* @__PURE__ */ React.createElement("div", {
5325
+ className: "tac-chat ta-conversation",
5326
+ ref: list
5327
+ }, /* @__PURE__ */ React.createElement("div", {
5328
+ className: "tac-chat-col"
5329
+ }, messages && messages.length === 0 && /* @__PURE__ */ React.createElement("div", {
5330
+ className: "tac-chat-empty"
5331
+ }, /* @__PURE__ */ React.createElement(RoomFace, {
5332
+ members,
5333
+ faces,
5334
+ size: 56,
5335
+ working
5336
+ }), /* @__PURE__ */ React.createElement("strong", null, channel.name), channel.topic && /* @__PURE__ */ React.createElement("span", null, channel.topic), /* @__PURE__ */ React.createElement("span", {
5337
+ className: "tac-chat-hint"
5338
+ }, w.quiet)), messages && RoomUtil.rows(messages).map(({ message, first, separator }) => /* @__PURE__ */ React.createElement(React.Fragment, {
5339
+ key: message.id
5340
+ }, separator && /* @__PURE__ */ React.createElement("div", {
5341
+ className: "tac-chat-time"
5342
+ }, time(message.at)), message.author === SYSTEM ? /* @__PURE__ */ React.createElement(StopLine, {
5343
+ context,
5344
+ channel,
5345
+ message,
5346
+ agents: state.team.agents,
5347
+ later: messages.some((other) => other.at > message.at && (other.author === USER || other.author === TA))
5348
+ }) : message.notice ? /* @__PURE__ */ React.createElement("button", {
5349
+ type: "button",
5350
+ className: "tac-notice tac-notice-line",
5351
+ disabled: !channel.notice,
5352
+ onClick: () => setNotice({ open: true, editing: false })
5353
+ }, 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", {
5354
+ className: `tac-msg${first ? " tac-first" : ""}`
5355
+ }, /* @__PURE__ */ React.createElement("div", {
5356
+ className: "tac-msg-face"
5357
+ }, first && pi.ui.Face && /* @__PURE__ */ React.createElement(pi.ui.Face, {
5358
+ seed: message.by ?? TA_OWNER,
5359
+ double: (message.by ?? TA_OWNER) === TA_OWNER,
5360
+ size: 28
5361
+ })), /* @__PURE__ */ React.createElement("div", {
5362
+ className: "tac-msg-col"
5363
+ }, first && /* @__PURE__ */ React.createElement("div", {
5364
+ className: "tac-msg-name"
5365
+ }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement(MessagePictures, {
5366
+ context,
5367
+ channelId: channel.id,
5368
+ message,
5369
+ alt: message.byName ?? w.owner
5370
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
5371
+ className: "tac-msg-bubble",
5372
+ title: time(message.at)
5373
+ }, /* @__PURE__ */ React.createElement(Mentions, {
5374
+ text: message.text,
5375
+ agents: state.team.agents
5376
+ })))) : message.author === USER ? /* @__PURE__ */ React.createElement("div", {
5377
+ className: "ta-message ta-user tac-mine"
5378
+ }, /* @__PURE__ */ React.createElement(MessagePictures, {
5379
+ context,
5380
+ channelId: channel.id,
5381
+ message,
5382
+ alt: w.you
5383
+ }), message.text && /* @__PURE__ */ React.createElement("div", {
5384
+ className: "ta-bubble"
5385
+ }, /* @__PURE__ */ React.createElement(Mentions, {
5386
+ text: message.text,
5387
+ agents: state.team.agents
5388
+ }))) : /* @__PURE__ */ React.createElement("div", {
5389
+ className: `tac-msg${first ? " tac-first" : ""}`
5390
+ }, /* @__PURE__ */ React.createElement("div", {
5391
+ className: "tac-msg-face"
5392
+ }, first && (message.author === TA ? /* @__PURE__ */ React.createElement(Avatar, {
5393
+ size: 28
5394
+ }) : /* @__PURE__ */ React.createElement(AgentAvatar, {
5395
+ agent: agentOf(message.author),
5396
+ faces,
5397
+ size: 28,
5398
+ working: working.includes(message.author)
5399
+ }))), /* @__PURE__ */ React.createElement("div", {
5400
+ className: "tac-msg-col"
5401
+ }, first && /* @__PURE__ */ React.createElement("div", {
5402
+ className: "tac-msg-name"
5403
+ }, name(message.author), message.author === channel.members[0] && /* @__PURE__ */ React.createElement("span", {
5404
+ className: "tac-msg-lead"
5405
+ }, w.lead)), /* @__PURE__ */ React.createElement("div", {
5406
+ className: `tac-msg-bubble${message.failed ? " tac-failed" : ""}`,
5407
+ title: time(message.at)
5408
+ }, message.failed && /* @__PURE__ */ React.createElement("div", {
5409
+ className: "tac-msg-failed"
5410
+ }, w.failed), message.overBudget && /* @__PURE__ */ React.createElement("div", {
5411
+ className: "tac-msg-over"
5412
+ }, w.overBudget), agentOf(message.author) ? /* @__PURE__ */ React.createElement(AgentText, {
5413
+ context,
5414
+ channelId: channel.id,
5415
+ agent: agentOf(message.author),
5416
+ text: ChannelsText.markMentions(message.text, state.team.agents),
5417
+ answer: RoomUtil.answer(messages, message, agentOf(message.author))
5418
+ }) : /* @__PURE__ */ React.createElement(Markdown, {
5419
+ text: ChannelsText.markMentions(message.text, state.team.agents)
5420
+ })))))), working.length > 0 && /* @__PURE__ */ React.createElement("div", {
5421
+ className: "tac-live",
5422
+ role: "status"
5423
+ }, /* @__PURE__ */ React.createElement("span", {
5424
+ className: "tac-live-faces"
5425
+ }, working.map((id) => /* @__PURE__ */ React.createElement(Face, {
5426
+ key: id,
5427
+ face: faces.get(id) ?? 0,
5428
+ size: 18,
5429
+ working: true
5430
+ }))), ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") })))), /* @__PURE__ */ React.createElement("div", {
5431
+ className: "tac-chat-bottom"
5432
+ }, /* @__PURE__ */ React.createElement(Composer, {
5433
+ placeholder: ChannelWords.format(placeholder, { channel: channel.name, lead: lead?.name ?? "" }),
5434
+ draft: channel.id,
5435
+ mentions: members.map((agent) => ({ name: agent.name, detail: agent.role.split(`
5436
+ `)[0] })),
5437
+ mentionLabel: w.mentionMember,
5438
+ actions: [
5439
+ [
5440
+ {
5441
+ key: "notice",
5442
+ label: w.noticeEdit,
5443
+ icon: ChannelViews.maybeIcon(pi, "Megaphone", null, 16),
5444
+ run: () => setNotice({ open: true, editing: true })
5445
+ },
5446
+ {
5447
+ key: "add",
5448
+ label: w.addMembers,
5449
+ icon: ChannelViews.maybeIcon(pi, "UserPlus", null, 16),
5450
+ run: () => {
5451
+ if (fixed) {
5452
+ ui.set({ channelId: fixed });
5453
+ }
5454
+ context.showMembers(true);
5455
+ }
5456
+ }
5457
+ ],
5458
+ [
5459
+ {
5460
+ key: "make-extension",
5461
+ label: w.makeExtension,
5462
+ detail: w.makeExtensionDetail,
5463
+ icon: ChannelViews.maybeIcon(pi, "Sparkles", null, 16),
5464
+ run: () => void service.post(channel.id, w.makeExtensionAsk).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"))
5465
+ }
5466
+ ]
5467
+ ],
5468
+ images: { side: 1600, bytes: 1024 * 1024 },
5469
+ onSend: (text, images) => service.post(channel.id, text, images ?? [])
5470
+ })));
5136
5471
  }
5137
5472
 
5138
- // ../ta-protocol/esm/common/team-protocol.js
5139
- var TA_OWNER = "owner";
5140
- var TA_UNDECLARED = "extensions.install";
5141
- var TaPermissionUtil;
5142
- (function(TaPermissionUtil2) {
5143
- function read(pi) {
5144
- const given = pi === null || pi === undefined ? undefined : pi.permissions;
5145
- const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
5146
- const host2 = map(given === null || given === undefined ? undefined : given.host);
5147
- const tools = map(given === null || given === undefined ? undefined : given.tools);
5148
- return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
5473
+ // web-src/tasks.tsx
5474
+ var BUILDING_MS = 60 * 1000;
5475
+
5476
+ class ChannelTaskSource {
5477
+ context;
5478
+ shown = new Map;
5479
+ list = [];
5480
+ listeners = new Set;
5481
+ reading = new Set;
5482
+ stop;
5483
+ constructor(context) {
5484
+ this.context = context;
5149
5485
  }
5150
- TaPermissionUtil2.read = read;
5151
- function host(manifest, method, kind) {
5152
- var _a, _b, _c, _d;
5153
- const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
5154
- const own = (key) => {
5155
- var _a2;
5156
- return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
5486
+ tasks() {
5487
+ return this.list;
5488
+ }
5489
+ subscribe(listener) {
5490
+ if (this.listeners.size === 0) {
5491
+ this.stop = this.context.service.subscribe((state) => this.build(state));
5492
+ this.build(this.context.service.state);
5493
+ }
5494
+ this.listeners.add(listener);
5495
+ return () => {
5496
+ this.listeners.delete(listener);
5497
+ if (this.listeners.size === 0) {
5498
+ this.stop?.();
5499
+ this.stop = undefined;
5500
+ }
5157
5501
  };
5158
- 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;
5159
5502
  }
5160
- TaPermissionUtil2.host = host;
5161
- })(TaPermissionUtil || (TaPermissionUtil = {}));
5162
- var action = (id, en, zh, tw, ja, more = {}) => ({
5163
- id,
5164
- area: id.split(".")[0],
5165
- title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
5166
- ...more
5167
- });
5168
- var TA_ACTIONS = [
5169
- action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
5170
- action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
5171
- action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
5172
- action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
5173
- action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
5174
- action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
5175
- action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
5176
- action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
5177
- action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
5178
- action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
5179
- action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
5180
- action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
5181
- action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
5182
- action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
5183
- action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
5184
- action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
5185
- action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
5186
- action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
5187
- action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
5188
- action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
5189
- action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
5190
- action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
5191
- action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
5192
- action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
5193
- action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
5194
- action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
5195
- action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
5196
- action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
5197
- action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
5198
- action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
5199
- action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
5200
- action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
5201
- action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
5202
- ];
5203
- var TA_OWNER_ACTIONS = [
5204
- action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
5205
- action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true })
5206
- ];
5207
- var OWNER_AREAS = ["desktop"];
5208
- var TaActionUtil;
5209
- (function(TaActionUtil2) {
5210
- const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
5211
- const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
5212
- function info(id) {
5213
- return byId.get(id);
5214
- }
5215
- TaActionUtil2.info = info;
5216
- function title(id, language) {
5217
- var _a;
5218
- var _b, _c;
5219
- const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
5220
- if (!title2) {
5221
- return id;
5222
- }
5223
- return TaLanguageUtil.pick(language, {
5224
- "zh-CN": title2["zh-CN"],
5225
- "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
5226
- "en-US": title2.en,
5227
- "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
5228
- });
5229
- }
5230
- TaActionUtil2.title = title;
5231
- function grantable(id) {
5232
- const info2 = byId.get(id);
5233
- return !!info2 && !OWNER_AREAS.includes(info2.area);
5234
- }
5235
- TaActionUtil2.grantable = grantable;
5236
- function inRoles(id) {
5237
- var _a;
5238
- return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
5239
- }
5240
- TaActionUtil2.inRoles = inRoles;
5241
- function inside(dir, path) {
5242
- const base = dir.replace(/\/+$/, "");
5243
- return path === base || path.startsWith(`${base}/`) || base === "";
5503
+ refresh() {
5504
+ this.shown.clear();
5505
+ this.build(this.context.service.state);
5244
5506
  }
5245
- TaActionUtil2.inside = inside;
5246
- })(TaActionUtil || (TaActionUtil = {}));
5247
-
5248
- // web-src/notice-util.ts
5249
- var NoticeUtil;
5250
- ((NoticeUtil) => {
5251
- const PARTS = {
5252
- 决定: "decisions",
5253
- decisions: "decisions",
5254
- 约定: "conventions",
5255
- conventions: "conventions",
5256
- 待办: "todo",
5257
- "to do": "todo",
5258
- todo: "todo",
5259
- "to-do": "todo"
5260
- };
5261
- function counts(text) {
5262
- const counts2 = { decisions: 0, conventions: 0, todo: 0, done: 0 };
5263
- let part;
5264
- for (const line of text.split(/\r?\n/)) {
5265
- const heading = /^\s*#{1,6}\s+(.+?)\s*#*\s*$/.exec(line) ?? /^\s*\*\*(.+?)\*\*\s*[::]?\s*$/.exec(line);
5266
- if (heading) {
5267
- part = PARTS[heading[1].replace(/[::]$/, "").trim().toLowerCase()];
5268
- continue;
5269
- }
5270
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(\[( |x|X)\]\s+)?\S/.exec(line);
5271
- if (!part || !item) {
5272
- continue;
5273
- }
5274
- if (part === "todo" && item[2] && item[2] !== " ") {
5275
- counts2.done++;
5276
- } else {
5277
- counts2[part]++;
5507
+ build(state) {
5508
+ const { team } = state;
5509
+ const faces = ChannelsUtil.faces(team.agents);
5510
+ const next = new Map;
5511
+ const channels = ChannelsUtil.taskChannels(team);
5512
+ let changed = channels.length !== this.list.length;
5513
+ const list = channels.map((channel, index) => {
5514
+ const messages = state.messages[channel.id];
5515
+ if (!messages) {
5516
+ this.read(channel.id);
5278
5517
  }
5518
+ const members = membersOf(team, channel);
5519
+ const working = state.working[channel.id] ?? [];
5520
+ const { status, detail, endedAt } = this.status(state, channel, messages, working);
5521
+ const signature = members.map((agent) => `${agent.id}:${faces.get(agent.id)}:${working.includes(agent.id) ? 1 : 0}`).join(",");
5522
+ const before = this.shown.get(channel.id);
5523
+ const shown = before && before.channel === channel && before.faces === signature && before.status === status && before.detail === detail && before.endedAt === endedAt ? before : {
5524
+ channel,
5525
+ members,
5526
+ faces: signature,
5527
+ status,
5528
+ detail,
5529
+ endedAt,
5530
+ entry: this.entry(channel, members, faces, working, status, detail, endedAt)
5531
+ };
5532
+ next.set(channel.id, shown);
5533
+ changed ||= shown.entry !== this.list[index];
5534
+ return shown.entry;
5535
+ });
5536
+ this.shown = next;
5537
+ if (!changed) {
5538
+ return;
5279
5539
  }
5280
- return counts2;
5281
- }
5282
- NoticeUtil.counts = counts;
5283
- function firstLine(text) {
5284
- for (const line of text.split(/\r?\n/)) {
5285
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(line);
5286
- if (item) {
5287
- return item[1].replace(/[*_`~]+/g, "").trim();
5288
- }
5540
+ this.list = list;
5541
+ for (const listener of this.listeners) {
5542
+ listener();
5289
5543
  }
5290
- return text.split(/\r?\n/).find((line) => line.trim() && !/^\s*#/.test(line))?.trim() ?? "";
5291
5544
  }
5292
- NoticeUtil.firstLine = firstLine;
5293
- })(NoticeUtil ||= {});
5294
-
5295
- // web-src/notice.tsx
5296
- var NoticeView;
5297
- ((NoticeView) => {
5298
- function display(text) {
5299
- return text.replace(/^(\s*[-*+]\s+)\[ \]\s+/gm, "$1☐ ").replace(/^(\s*[-*+]\s+)\[[xX]\]\s+/gm, "$1☑ ");
5545
+ read(channelId) {
5546
+ if (!this.reading.has(channelId)) {
5547
+ this.reading.add(channelId);
5548
+ this.context.service.messages(channelId).catch(() => this.reading.delete(channelId));
5549
+ }
5300
5550
  }
5301
- NoticeView.display = display;
5302
- function counts(text, language) {
5303
- const w = ChannelWords.of(language);
5304
- const counts2 = NoticeUtil.counts(text);
5305
- if (counts2.decisions + counts2.conventions + counts2.todo === 0) {
5306
- return NoticeUtil.firstLine(text);
5551
+ status(state, channel, messages, working) {
5552
+ const w = ChannelViews.words(this.context.pi);
5553
+ const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5554
+ if (working.length > 0) {
5555
+ return { status: "running", detail: ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") }) };
5307
5556
  }
5308
- const values = { decisions: String(counts2.decisions), conventions: String(counts2.conventions), todo: String(counts2.todo) };
5309
- return ChannelWords.format(w.noticeCounts, values).split(" · ").filter((_, at) => [counts2.decisions, counts2.conventions, counts2.todo][at] > 0).join(" · ");
5557
+ const last = messages?.at(-1);
5558
+ if (!last) {
5559
+ const building = Date.now() - channel.createdAt < BUILDING_MS;
5560
+ return building ? { status: "running", detail: w.building } : { status: "done", detail: channel.topic || w.noMessages, endedAt: channel.createdAt };
5561
+ }
5562
+ if (last.author === SYSTEM) {
5563
+ return { status: "waiting", detail: w.yourTurn };
5564
+ }
5565
+ const said = `${name(last.author)}:${last.text.replace(/\s+/g, " ").slice(0, 120)}`;
5566
+ return { status: last.failed ? "failed" : "done", detail: said, endedAt: last.at };
5310
5567
  }
5311
- NoticeView.counts = counts;
5312
- })(NoticeView ||= {});
5313
- function NoticeBar({
5314
- context,
5315
- channel,
5316
- state,
5317
- onState
5318
- }) {
5568
+ entry(channel, members, faces, working, status, detail, endedAt) {
5569
+ return {
5570
+ id: channel.id,
5571
+ title: taskTitle(channel),
5572
+ status,
5573
+ detail,
5574
+ startedAt: channel.createdAt,
5575
+ endedAt: status === "running" || status === "waiting" ? undefined : endedAt,
5576
+ origin: channel.origin,
5577
+ icon: ({ size }) => /* @__PURE__ */ React.createElement(RoomFace, {
5578
+ members,
5579
+ faces,
5580
+ size,
5581
+ working
5582
+ }),
5583
+ open: () => openScene(this.context, channel),
5584
+ show: () => this.context.showChannel(channel.id),
5585
+ menu: () => taskMenu(this.context, channel, working),
5586
+ remove: () => deleteTeam(this.context, channel),
5587
+ removeHint: ChannelWords.format(ChannelViews.words(this.context.pi).deleteTaskHint, { channel: channel.name })
5588
+ };
5589
+ }
5590
+ }
5591
+ function taskTitle(channel) {
5592
+ return channel.name;
5593
+ }
5594
+ async function deleteTeam(context, channel) {
5595
+ await context.service.deleteChannel(channel.id);
5596
+ context.pi.ui.closeEditor(`channel:${channel.id}`);
5597
+ }
5598
+ function openScene(context, channel) {
5599
+ context.pi.ui.openEditor({
5600
+ id: `channel:${channel.id}`,
5601
+ title: channel.name,
5602
+ icon: ChannelViews.icon(context.pi, "Hash"),
5603
+ render: () => /* @__PURE__ */ React.createElement("div", {
5604
+ className: "tac-scene"
5605
+ }, /* @__PURE__ */ React.createElement(ChannelSceneHead, {
5606
+ context,
5607
+ channelId: channel.id
5608
+ }), /* @__PURE__ */ React.createElement(ChannelRoom, {
5609
+ context,
5610
+ channelId: channel.id
5611
+ }))
5612
+ });
5613
+ }
5614
+ function taskMenu(context, channel, working) {
5319
5615
  const { pi, service } = context;
5320
- const { team } = useChannels(service);
5321
5616
  const w = ChannelViews.words(pi);
5322
- const notice = channel.notice;
5323
- const [draft, setDraft] = React.useState("");
5324
- const [busy, setBusy] = React.useState(false);
5325
- const [error, setError] = React.useState();
5326
- React.useEffect(() => {
5327
- if (state.editing) {
5328
- setDraft(notice?.text ?? w.noticeTemplate);
5329
- setError(undefined);
5330
- }
5331
- }, [state.editing]);
5332
- if (!notice && !state.editing) {
5333
- return null;
5334
- }
5335
- const Megaphone = ChannelViews.icon(pi, "Megaphone");
5336
- const Chevron = ChannelViews.icon(pi, "ChevronDown");
5337
- const Markdown = pi.ui.Markdown;
5338
- const save = (event) => {
5339
- event.preventDefault();
5340
- setBusy(true);
5341
- setError(undefined);
5342
- service.setNotice(channel.id, draft).then(() => {
5343
- setBusy(false);
5344
- onState({ open: true, editing: false });
5345
- }, (failure) => {
5346
- setBusy(false);
5347
- setError(ChannelViews.message(failure));
5348
- });
5617
+ const icon = (name) => ChannelViews.icon(pi, name);
5618
+ const act = (action2) => () => {
5619
+ Promise.resolve().then(action2).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"));
5349
5620
  };
5350
- const open = state.open || state.editing;
5351
- return /* @__PURE__ */ React.createElement("div", {
5352
- className: "tac-notice-bar",
5353
- "data-open": open ? "" : undefined
5354
- }, /* @__PURE__ */ React.createElement("button", {
5355
- type: "button",
5356
- className: "tac-notice-head",
5357
- "aria-expanded": open,
5358
- title: open ? w.noticeHide : w.noticeShow,
5359
- onClick: () => onState({ open: !open, editing: false })
5360
- }, /* @__PURE__ */ React.createElement("span", {
5361
- className: "tac-notice-icon"
5362
- }, /* @__PURE__ */ React.createElement(Megaphone, {
5363
- size: 13,
5364
- strokeWidth: 2
5365
- })), /* @__PURE__ */ React.createElement("strong", null, w.notice), /* @__PURE__ */ React.createElement("span", {
5366
- className: "tac-notice-sum"
5367
- }, notice ? NoticeView.counts(notice.text, pi.ui.language) : w.noticeEmpty), /* @__PURE__ */ React.createElement("span", {
5368
- className: "tac-notice-chevron"
5369
- }, /* @__PURE__ */ React.createElement(Chevron, {
5370
- size: 15
5371
- }))), open && !state.editing && notice && /* @__PURE__ */ React.createElement("div", {
5372
- className: "tac-notice-body"
5373
- }, /* @__PURE__ */ React.createElement("div", {
5374
- className: "tac-notice-text"
5375
- }, /* @__PURE__ */ React.createElement(Markdown, {
5376
- text: NoticeView.display(notice.text)
5377
- })), /* @__PURE__ */ React.createElement("div", {
5378
- className: "tac-notice-foot"
5379
- }, /* @__PURE__ */ React.createElement("span", null, ChannelWords.format(w.noticeBy, {
5380
- name: ChannelsText.authorName(team, notice.by, { user: w.you, ta: w.ta }),
5381
- time: SidebarUtil.time(notice.at, pi.ui.language)
5382
- })), /* @__PURE__ */ React.createElement("button", {
5383
- type: "button",
5384
- className: "tac-button tac-quiet",
5385
- onClick: () => onState({ open: true, editing: true })
5386
- }, w.noticeEdit))), state.editing && /* @__PURE__ */ React.createElement("form", {
5387
- className: "tac-notice-body tac-notice-form",
5388
- onSubmit: save
5389
- }, /* @__PURE__ */ React.createElement("p", {
5390
- className: "tac-dialog-note"
5391
- }, w.noticeHint), /* @__PURE__ */ React.createElement("textarea", {
5392
- className: "tac-input tac-notice-input",
5393
- value: draft,
5394
- "aria-label": w.noticeEdit,
5395
- autoFocus: true,
5396
- onChange: (event) => setDraft(event.target.value)
5397
- }), error && /* @__PURE__ */ React.createElement("div", {
5398
- className: "tac-error"
5399
- }, error), /* @__PURE__ */ React.createElement("div", {
5400
- className: "tac-notice-actions"
5401
- }, /* @__PURE__ */ React.createElement("button", {
5402
- type: "button",
5403
- className: "tac-button tac-quiet",
5404
- onClick: () => onState({ open: !!notice, editing: false })
5405
- }, w.cancel), /* @__PURE__ */ React.createElement("button", {
5406
- type: "submit",
5407
- className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
5408
- disabled: busy || draft.trim() === (notice?.text ?? "")
5409
- }, w.save, busy && /* @__PURE__ */ React.createElement("span", {
5410
- className: "ta-spinner ta-busy-mark ta-on-brand"
5411
- })))));
5621
+ const temporary = membersOf(service.state.team, channel).filter((agent) => agent.temporary);
5622
+ return [
5623
+ working.length > 0 ? [
5624
+ {
5625
+ key: "stop",
5626
+ label: w.stopAnswering,
5627
+ icon: icon("Square"),
5628
+ run: act(async () => {
5629
+ await TeamActions.stop(context, working);
5630
+ pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info");
5631
+ })
5632
+ }
5633
+ ] : [],
5634
+ [
5635
+ { key: "main", label: w.openInMain, icon: icon("ExternalLink"), run: () => context.showChannel(channel.id) },
5636
+ ...temporary.length > 0 ? [
5637
+ {
5638
+ key: "keep",
5639
+ label: w.keepMembers,
5640
+ icon: icon("UserPlus"),
5641
+ run: act(async () => {
5642
+ await TeamActions.keep(context, temporary);
5643
+ pi.ui.notify(ChannelWords.format(w.keptMembers, { names: temporary.map((agent) => `@${agent.name}`).join("、") }), "info");
5644
+ })
5645
+ }
5646
+ ] : []
5647
+ ],
5648
+ [
5649
+ {
5650
+ key: "delete",
5651
+ label: w.deleteTask,
5652
+ icon: icon("Trash2"),
5653
+ danger: true,
5654
+ run: act(() => pi.ui.removeTasks([
5655
+ {
5656
+ title: taskTitle(channel),
5657
+ removeHint: ChannelWords.format(w.deleteTaskHint, { channel: channel.name }),
5658
+ remove: () => deleteTeam(context, channel)
5659
+ }
5660
+ ]))
5661
+ }
5662
+ ]
5663
+ ];
5412
5664
  }
5413
-
5414
- // web-src/room.tsx
5415
- var RUN_MS = 5 * 60 * 1000;
5416
- var PAUSE_MS = 15 * 60 * 1000;
5417
- var RoomUtil;
5418
- ((RoomUtil) => {
5419
- function rows(messages) {
5420
- return messages.map((message, index) => {
5421
- const before = messages[index - 1];
5422
- const separator = !before || message.at - before.at > PAUSE_MS;
5423
- const first = separator || before.author !== message.author || before.by !== message.by || before.author === SYSTEM || !!before.notice || message.at - before.at > RUN_MS;
5424
- return { message, first, separator };
5425
- });
5426
- }
5427
- RoomUtil.rows = rows;
5428
- function choice(agent, text) {
5429
- return `@${agent.name} ${text}`;
5665
+ var TeamActions;
5666
+ ((TeamActions) => {
5667
+ async function stop(context, agentIds) {
5668
+ const { pi, service } = context;
5669
+ const files = new Set(service.state.team.agents.filter((agent) => agentIds.includes(agent.id) && agent.sessionFile).map((agent) => agent.sessionFile));
5670
+ const sessions = (await pi.server.listSessions()).filter((session) => session.sessionFile && files.has(session.sessionFile));
5671
+ await Promise.all(sessions.map((session) => pi.server.abort(session.sessionId)));
5430
5672
  }
5431
- RoomUtil.choice = choice;
5432
- function answer(messages, message, agent) {
5433
- const said = messages.slice(messages.indexOf(message) + 1).find((later) => later.author === USER && !later.notice);
5434
- if (!said) {
5435
- return;
5673
+ TeamActions.stop = stop;
5674
+ async function keep(context, agents) {
5675
+ for (const agent of agents) {
5676
+ await context.service.updateAgent(agent.id, { keep: true });
5436
5677
  }
5437
- const named = `@${agent.name} `;
5438
- return said.text.startsWith(named) ? said.text.slice(named.length) : said.text;
5439
5678
  }
5440
- RoomUtil.answer = answer;
5441
- })(RoomUtil ||= {});
5442
- function AgentText({ context, channelId, agent, text, answer }) {
5443
- const { pi, service } = context;
5444
- const send = React.useCallback((said) => service.post(channelId, RoomUtil.choice(agent, said)), [service, channelId, agent.name]);
5445
- return /* @__PURE__ */ React.createElement(pi.ui.Markdown, {
5446
- text,
5447
- send,
5448
- answer
5449
- });
5450
- }
5451
- function MessagePictures({ context, channelId, message, alt }) {
5452
- const { pi, service } = context;
5453
- const images = message.images ?? [];
5454
- const [sources, setSources] = React.useState({});
5455
- const ids = images.map((image) => image.id).join(",");
5679
+ TeamActions.keep = keep;
5680
+ })(TeamActions ||= {});
5681
+
5682
+ // web-src/shared-group.tsx
5683
+ function useFriends(pi) {
5684
+ const [friends, setFriends] = React.useState([]);
5456
5685
  React.useEffect(() => {
5457
5686
  let live = true;
5458
- for (const id of ids ? ids.split(",") : []) {
5459
- service.picture(channelId, id).then((data) => live && data && setSources((current) => ({ ...current, [id]: data })));
5460
- }
5687
+ pi.rooms?.listFriends().then((list) => live && setFriends(list.filter((friend) => friend.status === "friend")), () => {
5688
+ return;
5689
+ });
5461
5690
  return () => {
5462
5691
  live = false;
5463
5692
  };
5464
- }, [service, channelId, ids]);
5465
- const ChatImages = pi.ui.ChatImages;
5466
- if (!images.length || !ChatImages) {
5467
- return null;
5693
+ }, [pi]);
5694
+ return friends;
5695
+ }
5696
+ async function createShared(context, title, friends, agents) {
5697
+ const { pi } = context;
5698
+ const rooms = pi.rooms;
5699
+ if (!rooms) {
5700
+ throw new Error(ChannelViews.words(pi).sharedNeedsRooms);
5468
5701
  }
5469
- return /* @__PURE__ */ React.createElement("div", {
5470
- className: "tac-pics"
5471
- }, /* @__PURE__ */ React.createElement(ChatImages, {
5472
- alt,
5473
- images: images.map((image) => ({ key: image.id, src: sources[image.id], width: image.w, height: image.h }))
5474
- }));
5702
+ const room = await rooms.createRoom({ kind: ROOMS_KIND, title });
5703
+ await rooms.inviteFriends(room.id, friends);
5704
+ await TeamActions.keep(context, context.service.state.team.agents.filter((agent) => agent.temporary && agents.includes(agent.id)));
5705
+ for (const agent of agents) {
5706
+ await pi.packages.callPackageHost(ROOMS_PACKAGE, "doubles", [{ kind: "invite", room: room.id, agent }]).catch((error) => {
5707
+ pi.ui.notify(ChannelViews.message(error), "error");
5708
+ });
5709
+ }
5710
+ const { link } = await rooms.invite(room.id);
5711
+ await pi.openLink?.(link);
5712
+ return room.id;
5475
5713
  }
5476
- function Mentions({ text, agents }) {
5477
- const names = new Set(agents.map((agent) => agent.name.toLowerCase()));
5478
- const parts = text.split(/(@[^\s@#,,。::]+)/);
5479
- return /* @__PURE__ */ React.createElement("span", null, parts.map((part, index) => part.startsWith("@") && names.has(part.slice(1).toLowerCase()) ? /* @__PURE__ */ React.createElement("span", {
5480
- key: index,
5481
- className: "tac-mention"
5482
- }, part) : part));
5714
+ var ROOMS_PACKAGE = "@celljs/ta-rooms";
5715
+ var ROOMS_KIND = "ta-rooms";
5716
+ async function becomeGroup(context, channel, friends, agents) {
5717
+ const { pi } = context;
5718
+ const members = [...channel.members, ...agents.filter((id) => !channel.members.includes(id))];
5719
+ const room = await createShared(context, channel.name, friends, members);
5720
+ await context.service.updateChannel(channel.id, { shared: room });
5721
+ pi.ui.notify(ChannelWords.format(ChannelViews.words(pi).sharedMade, { name: channel.name }), "info");
5483
5722
  }
5484
- function StopLine({
5485
- context,
5486
- channel,
5487
- message,
5488
- later,
5489
- agents
5490
- }) {
5491
- const { pi, service } = context;
5492
- const w = ChannelViews.words(pi);
5493
- const [busy, setBusy] = React.useState(false);
5494
- const stop = message.stop;
5495
- const lead = agents.find((agent) => agent.id === channel.members.find((id) => !(channel.muted ?? []).includes(id)));
5496
- const replies = String(stop?.replies ?? 0);
5497
- const tokens = stop?.tokens ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(stop.tokens) : "";
5498
- const stats = stop ? ChannelWords.format(tokens ? w.stoppedStats : w.stoppedReplies, { replies, tokens }) : "";
5499
- const resumed = stop?.resumed === "continue" ? w.wentOn : stop?.resumed === "wrapUp" ? w.summedUp : "";
5500
- 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;
5501
- const extended = stop?.extended ? w.extendedOnce : "";
5502
- const go = (how) => {
5503
- setBusy(true);
5504
- service.resumeRound(channel.id, message.id, how).catch((error) => pi.ui.notify(ChannelViews.message(error), "error")).finally(() => setBusy(false));
5505
- };
5506
- const open = !!stop?.pending.length && !stop.resumed && !later;
5507
- return /* @__PURE__ */ React.createElement("div", {
5508
- className: "tac-stop",
5509
- role: "note"
5510
- }, /* @__PURE__ */ React.createElement("div", {
5511
- className: "tac-notice"
5512
- }, why), /* @__PURE__ */ React.createElement("div", {
5513
- className: "tac-stop-meta"
5514
- }, [stats, extended, resumed].filter(Boolean).join(" · ")), open && /* @__PURE__ */ React.createElement("div", {
5515
- className: "tac-stop-actions"
5516
- }, /* @__PURE__ */ React.createElement("button", {
5517
- type: "button",
5518
- className: "tac-stop-button",
5519
- disabled: busy,
5520
- onClick: () => go("continue")
5521
- }, w.keepGoing), lead && /* @__PURE__ */ React.createElement("button", {
5522
- type: "button",
5523
- className: "tac-stop-button",
5524
- disabled: busy,
5525
- onClick: () => go("wrapUp")
5526
- }, ChannelWords.format(w.wrapUp, { name: `@${lead.name}` }))));
5527
- }
5528
- function ChannelHead({ context }) {
5723
+
5724
+ // web-src/create.tsx
5725
+ var noBack = (_open, _close) => false;
5726
+ var AGENT_PAGE = `${NAME}/agent`;
5727
+ function newAgent(context) {
5529
5728
  const { pi, service, ui } = context;
5530
- const state = useChannels(service);
5531
- const { channelId } = useUi(ui);
5532
- const faces = useFaces(state.team);
5729
+ if (!ui.state.draft) {
5730
+ const team = service.state.team;
5731
+ const name = ChannelsUtil.freeName(team, ChannelViews.words(pi).newAgentName);
5732
+ ui.set({ draft: { name, face: ChannelsUtil.freeFaceFor(team.agents, ChannelsUtil.newId("draft")) } });
5733
+ }
5734
+ pi.ui.showView(AGENT_PAGE);
5735
+ }
5736
+ function Identity({ context, onClose }) {
5737
+ const { pi, ui } = context;
5738
+ const { draft } = useUi(ui);
5533
5739
  const w = ChannelViews.words(pi);
5534
- const shown = !!pi.ui.useView(MEMBERS_VIEW)?.shown;
5535
- const roomInfo = !!pi.ui.useView(ROOM_INFO_VIEW)?.shown;
5536
- const follow = React.useRef(roomInfo);
5537
- follow.current = roomInfo;
5740
+ const ref = React.useRef(null);
5741
+ const name = React.useRef(null);
5742
+ React.useEffect(() => name.current?.select(), []);
5743
+ (pi.ui.useBackLayer ?? noBack)(true, onClose);
5538
5744
  React.useEffect(() => {
5539
- if (channelId && follow.current) {
5540
- context.showMembers();
5541
- }
5542
- }, [channelId, context]);
5543
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5544
- if (!channel) {
5745
+ const close = (event) => {
5746
+ const target = event.target;
5747
+ if (!ref.current?.contains(target) && !target.closest?.(".tac-identity-open")) {
5748
+ onClose();
5749
+ }
5750
+ };
5751
+ const onKey = (event) => event.key === "Escape" && onClose();
5752
+ document.addEventListener("pointerdown", close);
5753
+ document.addEventListener("keydown", onKey);
5754
+ return () => {
5755
+ document.removeEventListener("pointerdown", close);
5756
+ document.removeEventListener("keydown", onKey);
5757
+ };
5758
+ }, [onClose]);
5759
+ if (!draft) {
5545
5760
  return null;
5546
5761
  }
5547
- const members = membersOf(state.team, channel);
5548
- const working = state.working[channel.id] ?? [];
5549
5762
  return /* @__PURE__ */ React.createElement("div", {
5550
- className: "tac-head"
5551
- }, /* @__PURE__ */ React.createElement("div", {
5552
- className: "tac-head-title"
5553
- }, /* @__PURE__ */ React.createElement("strong", null, channel.name), /* @__PURE__ */ React.createElement("span", {
5554
- className: "tac-head-count"
5555
- }, ChannelWords.format(w.memberCount, { count: String(members.length) })), channel.topic && /* @__PURE__ */ React.createElement("span", {
5556
- className: "tac-head-topic"
5557
- }, channel.topic)), /* @__PURE__ */ React.createElement("button", {
5763
+ className: "tac-identity",
5764
+ ref,
5765
+ role: "dialog",
5766
+ "aria-label": w.editAgent
5767
+ }, /* @__PURE__ */ React.createElement("label", {
5768
+ className: "tac-identity-label"
5769
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
5770
+ className: "tac-input",
5771
+ value: draft.name,
5772
+ maxLength: 40,
5773
+ ref: name,
5774
+ onChange: (event) => ui.set({ draft: { ...draft, name: event.target.value } }),
5775
+ onKeyDown: (event) => event.key === "Enter" && onClose()
5776
+ })), /* @__PURE__ */ React.createElement("div", {
5777
+ className: "tac-identity-label"
5778
+ }, w.avatar), /* @__PURE__ */ React.createElement("div", {
5779
+ className: "tac-faces"
5780
+ }, Array.from({ length: FACES }, (_, face) => /* @__PURE__ */ React.createElement("button", {
5781
+ key: face,
5558
5782
  type: "button",
5559
- className: `tac-head-members${shown ? " tac-on" : ""}`,
5560
- title: w.showMembers,
5561
- "aria-label": w.showMembers,
5562
- "aria-pressed": shown,
5563
- onClick: () => context.showMembers()
5564
- }, members.slice(0, 5).map((agent) => /* @__PURE__ */ React.createElement("span", {
5565
- key: agent.id,
5566
- className: "tac-head-face"
5567
- }, /* @__PURE__ */ React.createElement(AgentAvatar, {
5568
- agent,
5569
- faces,
5570
- size: 24,
5571
- working: working.includes(agent.id)
5572
- }))), members.length > 5 && /* @__PURE__ */ React.createElement("span", {
5573
- className: "tac-head-more"
5574
- }, "+", members.length - 5)));
5783
+ "aria-pressed": draft.face === face,
5784
+ className: `tac-face-pick${draft.face === face ? " tac-on" : ""}`,
5785
+ onClick: () => ui.set({ draft: { ...draft, face } })
5786
+ }, /* @__PURE__ */ React.createElement(Face, {
5787
+ face,
5788
+ size: 30
5789
+ })))));
5575
5790
  }
5576
- function ChannelSceneHead({ context, channelId }) {
5577
- const { pi, service } = context;
5578
- const state = useChannels(service);
5579
- const faces = useFaces(state.team);
5791
+ function NewAgentHead({ context }) {
5792
+ const { pi, ui } = context;
5793
+ const { draft, editing } = useUi(ui);
5580
5794
  const w = ChannelViews.words(pi);
5581
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5582
- if (!channel) {
5795
+ const Down = ChannelViews.icon(pi, "ChevronDown");
5796
+ if (!draft) {
5583
5797
  return null;
5584
5798
  }
5585
- const members = membersOf(state.team, channel);
5586
- const working = state.working[channel.id] ?? [];
5587
- const External = ChannelViews.icon(pi, "ExternalLink");
5588
5799
  return /* @__PURE__ */ React.createElement("div", {
5589
- className: "tac-scene-head"
5590
- }, /* @__PURE__ */ React.createElement(RoomFace, {
5591
- members,
5592
- faces,
5593
- size: 26,
5594
- working
5595
- }), /* @__PURE__ */ React.createElement("div", {
5596
- className: "tac-scene-title"
5597
- }, /* @__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", {
5800
+ className: "tac-new-head"
5801
+ }, /* @__PURE__ */ React.createElement("div", {
5802
+ className: "tac-new-title"
5803
+ }, /* @__PURE__ */ React.createElement("button", {
5598
5804
  type: "button",
5599
- className: "tac-button tac-scene-main",
5600
- title: w.openInMainHint,
5601
- onClick: () => context.showChannel(channel.id)
5602
- }, /* @__PURE__ */ React.createElement(External, {
5603
- size: 13
5604
- }), w.openInMain));
5605
- }
5606
- var mePromise;
5607
- function useMe(pi) {
5608
- const [me, setMe] = React.useState(TA_OWNER);
5609
- React.useEffect(() => {
5610
- mePromise ??= pi.server.getServerInfo().then((info) => info.member?.id ?? TA_OWNER, () => TA_OWNER);
5611
- let live = true;
5612
- mePromise.then((id) => live && setMe(id));
5613
- return () => {
5614
- live = false;
5615
- };
5616
- }, [pi]);
5617
- return me;
5805
+ className: "tac-new-trigger tac-identity-open",
5806
+ "aria-expanded": editing,
5807
+ title: w.editAgent,
5808
+ onClick: () => ui.set({ editing: !editing })
5809
+ }, /* @__PURE__ */ React.createElement(Face, {
5810
+ face: draft.face,
5811
+ size: 20
5812
+ }), /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement(Down, {
5813
+ size: 14
5814
+ })), editing && /* @__PURE__ */ React.createElement(Identity, {
5815
+ context,
5816
+ onClose: () => ui.set({ editing: false })
5817
+ })), /* @__PURE__ */ React.createElement("button", {
5818
+ type: "button",
5819
+ className: "tac-button tac-quiet",
5820
+ onClick: () => {
5821
+ ui.set({ draft: undefined, editing: false });
5822
+ pi.ui.showView("");
5823
+ }
5824
+ }, w.cancel));
5618
5825
  }
5619
- function ChannelRoom({ context, channelId: fixed }) {
5826
+ function NewAgentPage({ context }) {
5620
5827
  const { pi, service, ui } = context;
5621
- const me = useMe(pi);
5622
- const state = useChannels(service);
5623
- const shown = useUi(ui).channelId;
5624
- const channelId = fixed ?? shown;
5625
- const faces = useFaces(state.team);
5828
+ const { draft } = useUi(ui);
5829
+ const { loaded } = useChannels(service);
5626
5830
  const w = ChannelViews.words(pi);
5627
- const channel = state.team.channels.find((candidate) => candidate.id === channelId);
5628
- const messages = channel ? state.messages[channel.id] : undefined;
5629
- const working = channel ? state.working[channel.id] ?? [] : [];
5630
- React.useEffect(() => {
5631
- if (channelId) {
5632
- service.messages(channelId);
5633
- }
5634
- }, [service, channelId]);
5635
- const page = pi.ui.useView(CHANNEL_PAGE);
5636
- const inFront = !!channelId && (!!fixed || !!page?.shown);
5637
- const lastAt = ChannelSeenUtil.lastAt(messages);
5638
- const resting = working.length === 0;
5831
+ const Pencil = ChannelViews.icon(pi, "Pencil");
5832
+ const Composer = pi.ui.Composer;
5833
+ const first = React.useRef(true);
5639
5834
  React.useEffect(() => {
5640
- if (!channelId || !inFront || !resting) {
5835
+ if (!loaded || !first.current) {
5641
5836
  return;
5642
5837
  }
5643
- const look = () => document.visibilityState === "visible" && context.seen.look(channelId, Math.max(Date.now(), lastAt ?? 0));
5644
- look();
5645
- document.addEventListener("visibilitychange", look);
5646
- return () => document.removeEventListener("visibilitychange", look);
5647
- }, [context, channelId, inFront, resting, lastAt]);
5648
- React.useEffect(() => {
5649
- if (!channelId) {
5650
- return;
5838
+ first.current = false;
5839
+ if (!ui.state.draft) {
5840
+ newAgent(context);
5651
5841
  }
5652
- const watch = () => document.visibilityState === "visible" && void service.watch(channelId).catch(() => {
5653
- return;
5654
- });
5655
- watch();
5656
- const timer = setInterval(watch, WATCH_MS);
5657
- document.addEventListener("visibilitychange", watch);
5658
- return () => {
5659
- clearInterval(timer);
5660
- document.removeEventListener("visibilitychange", watch);
5661
- };
5662
- }, [service, channelId]);
5663
- const sent = React.useMemo(() => messages?.filter((message) => message.author === USER).length ?? 0, [messages]);
5664
- const list = pi.ui.useChatScroll(sent, channelId);
5665
- const [notice, setNotice] = React.useState({ open: false, editing: false });
5666
- React.useEffect(() => setNotice({ open: false, editing: false }), [channelId]);
5667
- const Markdown = pi.ui.Markdown;
5668
- const Composer = pi.ui.Composer;
5669
- const Avatar = pi.ui.Avatar;
5670
- if (!channel) {
5671
- return /* @__PURE__ */ React.createElement("div", {
5672
- className: "tac-room-page"
5673
- }, state.loaded && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5674
- title: w.pick
5675
- }));
5842
+ }, [loaded, ui, context]);
5843
+ if (!draft) {
5844
+ return null;
5676
5845
  }
5677
- const members = membersOf(state.team, channel);
5678
- const agentOf = (id) => state.team.agents.find((agent) => agent.id === id);
5679
- const reply = ChannelsText.replyOf(channel);
5680
- const lead = members.find((agent) => !(channel.muted ?? []).includes(agent.id));
5681
- const placeholder = reply === "all" ? w.placeholderAll : reply === "lead" && lead ? w.placeholderLead : w.placeholder;
5682
- const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5683
- const time = (at) => SidebarUtil.time(at, pi.ui.language);
5846
+ const send = async (text) => {
5847
+ const agent = await service.createAgent({ name: draft.name, role: DEFAULT_ROLE, face: draft.face, cwd: draft.cwd });
5848
+ ui.set({ draft: undefined, editing: false });
5849
+ try {
5850
+ const sessionId = await service.openAgent(agent.id);
5851
+ context.sessions.set(agent.id, sessionId);
5852
+ await pi.switchSession(sessionId);
5853
+ await pi.sendUserMessage(text);
5854
+ } catch (error) {
5855
+ pi.ui.notify(ChannelViews.message(error), "error");
5856
+ }
5857
+ };
5684
5858
  return /* @__PURE__ */ React.createElement("div", {
5685
- className: "tac-room-page"
5686
- }, /* @__PURE__ */ React.createElement(NoticeBar, {
5687
- context,
5688
- channel,
5689
- state: notice,
5690
- onState: setNotice
5691
- }), /* @__PURE__ */ React.createElement("div", {
5692
- className: "tac-chat ta-conversation",
5693
- ref: list
5859
+ className: "tac-new-page"
5694
5860
  }, /* @__PURE__ */ React.createElement("div", {
5695
- className: "tac-chat-col"
5696
- }, messages && messages.length === 0 && /* @__PURE__ */ React.createElement("div", {
5697
- className: "tac-chat-empty"
5698
- }, /* @__PURE__ */ React.createElement(RoomFace, {
5699
- members,
5700
- faces,
5701
- size: 56,
5702
- working
5703
- }), /* @__PURE__ */ React.createElement("strong", null, channel.name), channel.topic && /* @__PURE__ */ React.createElement("span", null, channel.topic), /* @__PURE__ */ React.createElement("span", {
5704
- className: "tac-chat-hint"
5705
- }, w.quiet)), messages && RoomUtil.rows(messages).map(({ message, first, separator }) => /* @__PURE__ */ React.createElement(React.Fragment, {
5706
- key: message.id
5707
- }, separator && /* @__PURE__ */ React.createElement("div", {
5708
- className: "tac-chat-time"
5709
- }, time(message.at)), message.author === SYSTEM ? /* @__PURE__ */ React.createElement(StopLine, {
5710
- context,
5711
- channel,
5712
- message,
5713
- agents: state.team.agents,
5714
- later: messages.some((other) => other.at > message.at && (other.author === USER || other.author === TA))
5715
- }) : message.notice ? /* @__PURE__ */ React.createElement("button", {
5861
+ className: "tac-new-col"
5862
+ }, /* @__PURE__ */ React.createElement(Face, {
5863
+ face: draft.face,
5864
+ size: 88
5865
+ }), /* @__PURE__ */ React.createElement("h2", {
5866
+ className: "tac-new-name"
5867
+ }, /* @__PURE__ */ React.createElement("span", null, draft.name || w.newAgentName), /* @__PURE__ */ React.createElement("button", {
5716
5868
  type: "button",
5717
- className: "tac-notice tac-notice-line",
5718
- disabled: !channel.notice,
5719
- onClick: () => setNotice({ open: true, editing: false })
5720
- }, 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", {
5721
- className: `tac-msg${first ? " tac-first" : ""}`
5722
- }, /* @__PURE__ */ React.createElement("div", {
5723
- className: "tac-msg-face"
5724
- }, first && pi.ui.Face && /* @__PURE__ */ React.createElement(pi.ui.Face, {
5725
- seed: message.by ?? TA_OWNER,
5726
- double: (message.by ?? TA_OWNER) === TA_OWNER,
5727
- size: 28
5728
- })), /* @__PURE__ */ React.createElement("div", {
5729
- className: "tac-msg-col"
5730
- }, first && /* @__PURE__ */ React.createElement("div", {
5731
- className: "tac-msg-name"
5732
- }, message.byName ?? w.owner), /* @__PURE__ */ React.createElement(MessagePictures, {
5733
- context,
5734
- channelId: channel.id,
5735
- message,
5736
- alt: message.byName ?? w.owner
5737
- }), message.text && /* @__PURE__ */ React.createElement("div", {
5738
- className: "tac-msg-bubble",
5739
- title: time(message.at)
5740
- }, /* @__PURE__ */ React.createElement(Mentions, {
5741
- text: message.text,
5742
- agents: state.team.agents
5743
- })))) : message.author === USER ? /* @__PURE__ */ React.createElement("div", {
5744
- className: "ta-message ta-user tac-mine"
5745
- }, /* @__PURE__ */ React.createElement(MessagePictures, {
5746
- context,
5747
- channelId: channel.id,
5748
- message,
5749
- alt: w.you
5750
- }), message.text && /* @__PURE__ */ React.createElement("div", {
5751
- className: "ta-bubble"
5752
- }, /* @__PURE__ */ React.createElement(Mentions, {
5753
- text: message.text,
5754
- agents: state.team.agents
5755
- }))) : /* @__PURE__ */ React.createElement("div", {
5756
- className: `tac-msg${first ? " tac-first" : ""}`
5757
- }, /* @__PURE__ */ React.createElement("div", {
5758
- className: "tac-msg-face"
5759
- }, first && (message.author === TA ? /* @__PURE__ */ React.createElement(Avatar, {
5760
- size: 28
5761
- }) : /* @__PURE__ */ React.createElement(AgentAvatar, {
5762
- agent: agentOf(message.author),
5763
- faces,
5764
- size: 28,
5765
- working: working.includes(message.author)
5766
- }))), /* @__PURE__ */ React.createElement("div", {
5767
- className: "tac-msg-col"
5768
- }, first && /* @__PURE__ */ React.createElement("div", {
5769
- className: "tac-msg-name"
5770
- }, name(message.author), message.author === channel.members[0] && /* @__PURE__ */ React.createElement("span", {
5771
- className: "tac-msg-lead"
5772
- }, w.lead)), /* @__PURE__ */ React.createElement("div", {
5773
- className: `tac-msg-bubble${message.failed ? " tac-failed" : ""}`,
5774
- title: time(message.at)
5775
- }, message.failed && /* @__PURE__ */ React.createElement("div", {
5776
- className: "tac-msg-failed"
5777
- }, w.failed), message.overBudget && /* @__PURE__ */ React.createElement("div", {
5778
- className: "tac-msg-over"
5779
- }, w.overBudget), agentOf(message.author) ? /* @__PURE__ */ React.createElement(AgentText, {
5780
- context,
5781
- channelId: channel.id,
5782
- agent: agentOf(message.author),
5783
- text: ChannelsText.markMentions(message.text, state.team.agents),
5784
- answer: RoomUtil.answer(messages, message, agentOf(message.author))
5785
- }) : /* @__PURE__ */ React.createElement(Markdown, {
5786
- text: ChannelsText.markMentions(message.text, state.team.agents)
5787
- })))))), working.length > 0 && /* @__PURE__ */ React.createElement("div", {
5788
- className: "tac-live",
5789
- role: "status"
5790
- }, /* @__PURE__ */ React.createElement("span", {
5791
- className: "tac-live-faces"
5792
- }, working.map((id) => /* @__PURE__ */ React.createElement(Face, {
5793
- key: id,
5794
- face: faces.get(id) ?? 0,
5795
- size: 18,
5796
- working: true
5797
- }))), ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") })))), /* @__PURE__ */ React.createElement("div", {
5798
- className: "tac-chat-bottom"
5869
+ className: "tac-action tac-identity-open",
5870
+ title: w.editAgent,
5871
+ "aria-label": w.editAgent,
5872
+ onClick: () => ui.set({ editing: !ui.state.editing })
5873
+ }, /* @__PURE__ */ React.createElement(Pencil, {
5874
+ size: 14
5875
+ }))), /* @__PURE__ */ React.createElement("p", {
5876
+ className: "tac-new-hint"
5877
+ }, w.newAgentHint), /* @__PURE__ */ React.createElement("div", {
5878
+ className: "tac-new-box"
5799
5879
  }, /* @__PURE__ */ React.createElement(Composer, {
5800
- placeholder: ChannelWords.format(placeholder, { channel: channel.name, lead: lead?.name ?? "" }),
5801
- draft: channel.id,
5802
- mentions: members.map((agent) => ({ name: agent.name, detail: agent.role.split(`
5803
- `)[0] })),
5804
- mentionLabel: w.mentionMember,
5805
- actions: [
5806
- [
5807
- {
5808
- key: "notice",
5809
- label: w.noticeEdit,
5810
- icon: ChannelViews.maybeIcon(pi, "Megaphone", null, 16),
5811
- run: () => setNotice({ open: true, editing: true })
5812
- },
5813
- {
5814
- key: "add",
5815
- label: w.addMembers,
5816
- icon: ChannelViews.maybeIcon(pi, "UserPlus", null, 16),
5817
- run: () => {
5818
- if (fixed) {
5819
- ui.set({ channelId: fixed });
5820
- }
5821
- context.showMembers(true);
5822
- }
5823
- }
5824
- ],
5825
- [
5826
- {
5827
- key: "make-extension",
5828
- label: w.makeExtension,
5829
- detail: w.makeExtensionDetail,
5830
- icon: ChannelViews.maybeIcon(pi, "Sparkles", null, 16),
5831
- run: () => void service.post(channel.id, w.makeExtensionAsk).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"))
5832
- }
5833
- ]
5834
- ],
5835
- images: { side: 1600, bytes: 1024 * 1024 },
5836
- onSend: (text, images) => service.post(channel.id, text, images ?? [])
5837
- })));
5880
+ placeholder: ChannelWords.format(w.agentPlaceholder, { name: draft.name || w.newAgentName }),
5881
+ onSend: send,
5882
+ cwd: draft.cwd,
5883
+ onPickCwd: (cwd) => ui.set({ draft: { ...draft, cwd } }),
5884
+ draft: "new-agent"
5885
+ }))));
5886
+ }
5887
+ function NewChannelDialog({ context, onClose }) {
5888
+ const { pi, service } = context;
5889
+ const { team } = useChannels(service);
5890
+ const faces = useFaces(team);
5891
+ const w = ChannelViews.words(pi);
5892
+ const Search = ChannelViews.icon(pi, "Search");
5893
+ const Check = ChannelViews.icon(pi, "Check");
5894
+ const [name, setName] = React.useState("");
5895
+ const [query, setQuery] = React.useState("");
5896
+ const [picked, setPicked] = React.useState([]);
5897
+ const friends = useFriends(pi);
5898
+ const [pickedFriends, setPickedFriends] = React.useState([]);
5899
+ const shared = pickedFriends.length > 0;
5900
+ const toggleFriend = (friend) => setPickedFriends(pickedFriends.includes(friend.id) ? pickedFriends.filter((id) => id !== friend.id) : [...pickedFriends, friend.id]);
5901
+ const [busy, setBusy] = React.useState(false);
5902
+ const [error, setError] = React.useState();
5903
+ const Dialog = pi.ui.Dialog;
5904
+ const shown = team.agents.filter((agent) => SidebarUtil.matches(query, agent.name, agent.role));
5905
+ const full = picked.length >= MAX_MEMBERS;
5906
+ const toggle = (agent) => setPicked(picked.includes(agent.id) ? picked.filter((id) => id !== agent.id) : full ? picked : [...picked, agent.id]);
5907
+ const create = (event) => {
5908
+ event.preventDefault();
5909
+ setBusy(true);
5910
+ setError(undefined);
5911
+ if (shared) {
5912
+ createShared(context, name.trim(), pickedFriends, picked).then(onClose, (failure) => {
5913
+ setBusy(false);
5914
+ setError(ChannelViews.message(failure));
5915
+ });
5916
+ return;
5917
+ }
5918
+ service.createChannel({ name, members: picked }).then((channel) => {
5919
+ onClose();
5920
+ context.showChannel(channel.id);
5921
+ }, (failure) => {
5922
+ setBusy(false);
5923
+ setError(ChannelViews.message(failure));
5924
+ });
5925
+ };
5926
+ return /* @__PURE__ */ React.createElement(Dialog, {
5927
+ title: w.newChannel,
5928
+ onClose
5929
+ }, /* @__PURE__ */ React.createElement("form", {
5930
+ className: "tac-dialog",
5931
+ onSubmit: create
5932
+ }, /* @__PURE__ */ React.createElement("label", {
5933
+ className: "tac-dialog-label"
5934
+ }, w.name, /* @__PURE__ */ React.createElement("input", {
5935
+ className: "tac-input tac-dialog-input",
5936
+ value: name,
5937
+ placeholder: w.channelNamePlaceholder,
5938
+ maxLength: 40,
5939
+ autoFocus: true,
5940
+ onChange: (event) => setName(event.target.value)
5941
+ })), /* @__PURE__ */ React.createElement("div", {
5942
+ className: "tac-dialog-label"
5943
+ }, /* @__PURE__ */ React.createElement("span", null, w.addAgents), /* @__PURE__ */ React.createElement("span", {
5944
+ className: "tac-dialog-count"
5945
+ }, picked.length, "/", MAX_MEMBERS)), /* @__PURE__ */ React.createElement("label", {
5946
+ className: "tac-dialog-search"
5947
+ }, /* @__PURE__ */ React.createElement(Search, {
5948
+ size: 15
5949
+ }), /* @__PURE__ */ React.createElement("input", {
5950
+ value: query,
5951
+ placeholder: ChannelWords.format(w.searchAgents, { max: String(MAX_MEMBERS) }),
5952
+ "aria-label": w.search,
5953
+ onChange: (event) => setQuery(event.target.value)
5954
+ })), /* @__PURE__ */ React.createElement("div", {
5955
+ className: "tac-pick-list"
5956
+ }, team.agents.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5957
+ compact: true,
5958
+ title: w.noAgents,
5959
+ hint: w.noAgentsHint
5960
+ }), team.agents.length > 0 && shown.length === 0 && /* @__PURE__ */ React.createElement(pi.ui.Empty, {
5961
+ compact: true,
5962
+ title: w.noMatch
5963
+ }), shown.map((agent) => {
5964
+ const on = picked.includes(agent.id);
5965
+ return /* @__PURE__ */ React.createElement("button", {
5966
+ key: agent.id,
5967
+ type: "button",
5968
+ "aria-pressed": on,
5969
+ disabled: !on && full,
5970
+ className: `tac-pick${on ? " tac-on" : ""}`,
5971
+ onClick: () => toggle(agent)
5972
+ }, /* @__PURE__ */ React.createElement("span", {
5973
+ className: "tac-check"
5974
+ }, on && /* @__PURE__ */ React.createElement(Check, {
5975
+ size: 13,
5976
+ strokeWidth: 3
5977
+ })), /* @__PURE__ */ React.createElement(AgentAvatar, {
5978
+ agent,
5979
+ faces,
5980
+ size: 30
5981
+ }), /* @__PURE__ */ React.createElement("span", {
5982
+ className: "tac-pick-text"
5983
+ }, /* @__PURE__ */ React.createElement("span", {
5984
+ className: "tac-pick-name"
5985
+ }, agent.name, picked[0] === agent.id && /* @__PURE__ */ React.createElement("span", {
5986
+ className: "tac-msg-lead"
5987
+ }, w.lead)), /* @__PURE__ */ React.createElement("span", {
5988
+ className: "tac-pick-role"
5989
+ }, agent.role.split(`
5990
+ `)[0])));
5991
+ })), friends.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
5992
+ className: "tac-dialog-label"
5993
+ }, /* @__PURE__ */ React.createElement("span", null, w.addFriends), shared && /* @__PURE__ */ React.createElement("span", {
5994
+ className: "tac-dialog-count"
5995
+ }, pickedFriends.length)), /* @__PURE__ */ React.createElement("div", {
5996
+ className: "tac-pick-list"
5997
+ }, friends.map((friend) => {
5998
+ const on = pickedFriends.includes(friend.id);
5999
+ return /* @__PURE__ */ React.createElement("button", {
6000
+ key: friend.id,
6001
+ type: "button",
6002
+ "aria-pressed": on,
6003
+ className: `tac-pick${on ? " tac-on" : ""}`,
6004
+ onClick: () => toggleFriend(friend)
6005
+ }, /* @__PURE__ */ React.createElement("span", {
6006
+ className: "tac-check"
6007
+ }, on && /* @__PURE__ */ React.createElement(Check, {
6008
+ size: 13,
6009
+ strokeWidth: 3
6010
+ })), pi.ui.Face ? /* @__PURE__ */ React.createElement(pi.ui.Face, {
6011
+ seed: friend.id,
6012
+ size: 30,
6013
+ look: friend.look
6014
+ }) : /* @__PURE__ */ React.createElement("span", {
6015
+ className: "tac-pick-face"
6016
+ }), /* @__PURE__ */ React.createElement("span", {
6017
+ className: "tac-pick-text"
6018
+ }, /* @__PURE__ */ React.createElement("span", {
6019
+ className: "tac-pick-name"
6020
+ }, friend.name), /* @__PURE__ */ React.createElement("span", {
6021
+ className: "tac-pick-role"
6022
+ }, w.friend)));
6023
+ }))), (picked.length > 0 || shared) && /* @__PURE__ */ React.createElement("div", {
6024
+ className: "tac-dialog-note"
6025
+ }, shared ? w.sharedHint : w.membersHint), error && /* @__PURE__ */ React.createElement("div", {
6026
+ className: "tac-empty tac-error"
6027
+ }, error), /* @__PURE__ */ React.createElement("div", {
6028
+ className: "tac-dialog-actions"
6029
+ }, /* @__PURE__ */ React.createElement("button", {
6030
+ type: "submit",
6031
+ className: busy ? "tac-button tac-primary ta-busy" : "tac-button tac-primary",
6032
+ disabled: busy || !name.trim() || picked.length === 0 && !shared
6033
+ }, w.create, busy && /* @__PURE__ */ React.createElement("span", {
6034
+ className: "ta-spinner ta-busy-mark ta-on-brand"
6035
+ })))));
5838
6036
  }
5839
6037
 
5840
- // web-src/tasks.tsx
5841
- var BUILDING_MS = 60 * 1000;
6038
+ // web-src/handoff.ts
6039
+ var HandOff;
6040
+ ((HandOff) => {
6041
+ HandOff.TOOL = "hand_off";
6042
+ HandOff.CARD = "ta-channels-handoff";
6043
+ HandOff.BLOCK = "ta-handoff";
6044
+ const MARK = /\[ta-handoff:([^\]\s]+)\]/;
6045
+ HandOff.DEFINITION = {
6046
+ name: HandOff.TOOL,
6047
+ label: "Hand off",
6048
+ 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.",
6049
+ promptSnippet: "Hand the work over to one of the user's agents or channels",
6050
+ parameters: {
6051
+ type: "object",
6052
+ properties: {
6053
+ to: { type: "string", description: "@name of an agent or #name of a channel." },
6054
+ brief: { type: "string", description: "Complete in itself: the receiver sees only this." }
6055
+ },
6056
+ required: ["to", "brief"]
6057
+ }
6058
+ };
6059
+ function ref(target) {
6060
+ return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
6061
+ }
6062
+ HandOff.ref = ref;
6063
+ function ask(language, to) {
6064
+ const fence = "```";
6065
+ const context = [
6066
+ `[ta-handoff:${to}]`,
6067
+ `The user hands the work of this conversation over to ${to}, which does not see this conversation.`,
6068
+ `- 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.`,
6069
+ `- With the tool ${HandOff.TOOL}, call it with to "${to}" and the brief, then say in one line that it went.`,
6070
+ `- 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):`,
6071
+ `${fence}${HandOff.BLOCK}`,
6072
+ "<the brief>",
6073
+ fence,
6074
+ `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
6075
+ ].join(`
6076
+ `);
6077
+ const line = TaLanguageUtil.pick(language, {
6078
+ "zh-CN": `把这件事交给 ${to}`,
6079
+ "zh-TW": `把這件事交給 ${to}`,
6080
+ "en-US": `Hand this over to ${to}`,
6081
+ "ja-JP": `これを ${to} に引き継ぐ`
6082
+ });
6083
+ return TaMessageContext.wrap(context, line);
6084
+ }
6085
+ HandOff.ask = ask;
6086
+ function asked(text) {
6087
+ return MARK.exec(text)?.[1];
6088
+ }
6089
+ HandOff.asked = asked;
6090
+ function find(text) {
6091
+ const lines = text.split(/\r?\n/);
6092
+ let found;
6093
+ for (let index = 0;index < lines.length; index++) {
6094
+ const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
6095
+ if (open?.[2] !== HandOff.BLOCK) {
6096
+ continue;
6097
+ }
6098
+ const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
6099
+ const end = lines.findIndex((line, at) => at > index && close.test(line));
6100
+ found = lines.slice(index + 1, end < 0 ? lines.length : end);
6101
+ index = end < 0 ? lines.length : end;
6102
+ }
6103
+ const brief = found?.join(`
6104
+ `).trim();
6105
+ return brief || undefined;
6106
+ }
6107
+ HandOff.find = find;
6108
+ function message(origin, brief, language) {
6109
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
6110
+ const head = TaLanguageUtil.pick(language, {
6111
+ "zh-CN": `(交接自“${title}”)`,
6112
+ "zh-TW": `(交接自「${title}」)`,
6113
+ "en-US": `(Handed over from “${title}”)`,
6114
+ "ja-JP": `(“${title}” から引き継ぎました)`
6115
+ });
6116
+ const context = [
6117
+ "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.",
6118
+ 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.` : ""
6119
+ ].filter(Boolean).join(`
6120
+ `);
6121
+ return TaMessageContext.wrap(context, `${head}
6122
+
6123
+ ${brief.trim()}`);
6124
+ }
6125
+ HandOff.message = message;
6126
+ function channelText(origin, brief, language) {
6127
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
6128
+ return `${TaLanguageUtil.pick(language, {
6129
+ "zh-CN": `(交接自“${title}”)`,
6130
+ "zh-TW": `(交接自「${title}」)`,
6131
+ "en-US": `(Handed over from “${title}”)`,
6132
+ "ja-JP": `(“${title}” から引き継ぎました)`
6133
+ })}
5842
6134
 
5843
- class ChannelTaskSource {
5844
- context;
5845
- shown = new Map;
5846
- list = [];
5847
- listeners = new Set;
5848
- reading = new Set;
5849
- stop;
5850
- constructor(context) {
5851
- this.context = context;
6135
+ ${brief.trim()}`;
5852
6136
  }
5853
- tasks() {
5854
- return this.list;
6137
+ HandOff.channelText = channelText;
6138
+ function serverLanguage(env = typeof process === "undefined" ? {} : process.env) {
6139
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
5855
6140
  }
5856
- subscribe(listener) {
5857
- if (this.listeners.size === 0) {
5858
- this.stop = this.context.service.subscribe((state) => this.build(state));
5859
- this.build(this.context.service.state);
6141
+ HandOff.serverLanguage = serverLanguage;
6142
+ function result(target) {
6143
+ 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.`;
6144
+ }
6145
+ HandOff.result = result;
6146
+ })(HandOff ||= {});
6147
+
6148
+ // web-src/handoff-view.tsx
6149
+ var HandOffViewUtil;
6150
+ ((HandOffViewUtil) => {
6151
+ function members(team, target) {
6152
+ if (target.kind === "agent") {
6153
+ const agent = team.agents.find((candidate) => candidate.id === target.id);
6154
+ return agent ? [agent] : [];
5860
6155
  }
5861
- this.listeners.add(listener);
5862
- return () => {
5863
- this.listeners.delete(listener);
5864
- if (this.listeners.size === 0) {
5865
- this.stop?.();
5866
- this.stop = undefined;
5867
- }
6156
+ const channel = team.channels.find((candidate) => candidate.id === target.id);
6157
+ return channel ? membersOf(team, channel) : [];
6158
+ }
6159
+ HandOffViewUtil.members = members;
6160
+ })(HandOffViewUtil ||= {});
6161
+ function useTeam(context) {
6162
+ return React.useSyncExternalStore((listener) => context.service.subscribe(listener), () => context.service.state).team;
6163
+ }
6164
+ function HandOffCard({ context, message }) {
6165
+ const card = message.details;
6166
+ const team = useTeam(context);
6167
+ const faces = useFaces(team);
6168
+ if (!card?.target) {
6169
+ return null;
6170
+ }
6171
+ const w = ChannelViews.words(context.pi);
6172
+ const members = HandOffViewUtil.members(team, card.target);
6173
+ 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);
6174
+ return /* @__PURE__ */ React.createElement("div", {
6175
+ className: "tac-handoff"
6176
+ }, /* @__PURE__ */ React.createElement("div", {
6177
+ className: "tac-handoff-head"
6178
+ }, members.length > 0 && /* @__PURE__ */ React.createElement(RoomFace, {
6179
+ members,
6180
+ faces,
6181
+ size: 20,
6182
+ working: []
6183
+ }), /* @__PURE__ */ React.createElement("span", {
6184
+ className: "tac-handoff-title"
6185
+ }, w.handedTo.replace("{to}", HandOff.ref(card.target))), members.length > 0 && /* @__PURE__ */ React.createElement("button", {
6186
+ type: "button",
6187
+ className: "tac-link",
6188
+ onClick: open
6189
+ }, w.handOffOpen)), /* @__PURE__ */ React.createElement("div", {
6190
+ className: "tac-handoff-brief"
6191
+ }, card.brief));
6192
+ }
6193
+ var HandOffView;
6194
+ ((HandOffView) => {
6195
+ function card(context) {
6196
+ return ({ message }) => /* @__PURE__ */ React.createElement(HandOffCard, {
6197
+ context,
6198
+ message
6199
+ });
6200
+ }
6201
+ HandOffView.card = card;
6202
+ function icon(context, target, icons) {
6203
+ const key = `${target.kind}:${target.id}`;
6204
+ let node2 = icons.get(key);
6205
+ if (!node2) {
6206
+ const Face2 = () => {
6207
+ const team = useTeam(context);
6208
+ const faces = useFaces(team);
6209
+ const members = HandOffViewUtil.members(team, target);
6210
+ return members.length ? /* @__PURE__ */ React.createElement(RoomFace, {
6211
+ members,
6212
+ faces,
6213
+ size: 16,
6214
+ working: []
6215
+ }) : null;
6216
+ };
6217
+ node2 = /* @__PURE__ */ React.createElement(Face2, null);
6218
+ icons.set(key, node2);
6219
+ }
6220
+ return node2;
6221
+ }
6222
+ function composerAddon(context) {
6223
+ const icons = new Map;
6224
+ const send = (conversation, to) => void context.pi.server.prompt(conversation.sessionId, {
6225
+ clientMessageId: ChannelsUtil.newId("handoff-ask"),
6226
+ message: HandOff.ask(context.pi.ui.language, to),
6227
+ streamingBehavior: "followUp"
6228
+ }).catch((error) => context.pi.ui.notify(ChannelViews.message(error), "error"));
6229
+ return {
6230
+ actions: (conversation) => {
6231
+ const { team } = context.service.state;
6232
+ if (conversation.group === NAME || team.agents.length === 0 && team.channels.length === 0) {
6233
+ return [];
6234
+ }
6235
+ const w = ChannelViews.words(context.pi);
6236
+ const Forward = ChannelViews.icon(context.pi, "Forward");
6237
+ const agents = ChannelsUtil.standing(team).map((agent) => ({
6238
+ key: `handoff:agent:${agent.id}`,
6239
+ label: agent.name,
6240
+ detail: agent.role.split(`
6241
+ `)[0],
6242
+ group: w.agents,
6243
+ icon: icon(context, { kind: "agent", id: agent.id }, icons),
6244
+ run: () => send(conversation, `@${agent.name}`)
6245
+ }));
6246
+ const channels = team.channels.map((channel) => ({
6247
+ key: `handoff:channel:${channel.id}`,
6248
+ label: `#${channel.name}`,
6249
+ detail: channel.topic,
6250
+ group: w.channels,
6251
+ icon: icon(context, { kind: "channel", id: channel.id }, icons),
6252
+ run: () => send(conversation, `#${channel.name}`)
6253
+ }));
6254
+ return [{ key: "handoff", label: w.handOff, detail: w.handOffDetail, icon: /* @__PURE__ */ React.createElement(Forward, {
6255
+ size: 16
6256
+ }), items: [...agents, ...channels] }];
6257
+ },
6258
+ subscribe: (listener) => context.service.subscribe(listener)
5868
6259
  };
5869
6260
  }
5870
- refresh() {
5871
- this.shown.clear();
5872
- this.build(this.context.service.state);
6261
+ HandOffView.composerAddon = composerAddon;
6262
+ })(HandOffView ||= {});
6263
+
6264
+ // web-src/round-rules.ts
6265
+ var ChannelRounds;
6266
+ ((ChannelRounds) => {
6267
+ const SHORT = 20;
6268
+ const MIN_PAIRS = 8;
6269
+ const ALIKE = 0.8;
6270
+ const PING_PONG = 4;
6271
+ const NEW = 0.35;
6272
+ const CHANGES = new Set(["edit", "write", "delete", "move"]);
6273
+ function scale(watchedAt, pages, now) {
6274
+ if (watchedAt !== undefined && now - watchedAt < 2 * WATCH_MS) {
6275
+ return 2;
6276
+ }
6277
+ return pages === undefined || pages > 0 ? 1 : 0.5;
5873
6278
  }
5874
- build(state) {
5875
- const { team } = state;
5876
- const faces = ChannelsUtil.faces(team.agents);
5877
- const next = new Map;
5878
- const channels = ChannelsUtil.taskChannels(team);
5879
- let changed = channels.length !== this.list.length;
5880
- const list = channels.map((channel, index) => {
5881
- const messages = state.messages[channel.id];
5882
- if (!messages) {
5883
- this.read(channel.id);
6279
+ ChannelRounds.scale = scale;
6280
+ function idle(said, progress) {
6281
+ const last = said.at(-1);
6282
+ if (!last) {
6283
+ return;
6284
+ }
6285
+ const pairs = said.map((item) => pairsOf(item.text));
6286
+ const mine = pairs[pairs.length - 1];
6287
+ if (mine.length >= MIN_PAIRS && pairs.slice(0, -1).some((other) => alike(other, mine) >= ALIKE)) {
6288
+ return "repeat";
6289
+ }
6290
+ const recent = said.slice(-3);
6291
+ if (recent.length === 3 && recent.every((item) => units(item.text).join("").length < SHORT)) {
6292
+ return "agree";
6293
+ }
6294
+ const run = said.slice(-PING_PONG);
6295
+ const authors = new Set(run.map((item) => item.author));
6296
+ const alternate = run.every((item, i) => i === 0 || item.author !== run[i - 1].author);
6297
+ const start = said.length - PING_PONG;
6298
+ if (progress || start <= 0 || authors.size !== 2 || !alternate) {
6299
+ return;
6300
+ }
6301
+ const seen = new Set(pairs.slice(0, start).flat());
6302
+ for (const own of pairs.slice(start)) {
6303
+ const fresh = own.filter((pair) => !seen.has(pair)).length;
6304
+ if (own.length === 0 || fresh / own.length >= NEW) {
6305
+ return;
5884
6306
  }
5885
- const members = membersOf(team, channel);
5886
- const working = state.working[channel.id] ?? [];
5887
- const { status, detail, endedAt } = this.status(state, channel, messages, working);
5888
- const signature = members.map((agent) => `${agent.id}:${faces.get(agent.id)}:${working.includes(agent.id) ? 1 : 0}`).join(",");
5889
- const before = this.shown.get(channel.id);
5890
- const shown = before && before.channel === channel && before.faces === signature && before.status === status && before.detail === detail && before.endedAt === endedAt ? before : {
5891
- channel,
5892
- members,
5893
- faces: signature,
5894
- status,
5895
- detail,
5896
- endedAt,
5897
- entry: this.entry(channel, members, faces, working, status, detail, endedAt)
5898
- };
5899
- next.set(channel.id, shown);
5900
- changed ||= shown.entry !== this.list[index];
5901
- return shown.entry;
5902
- });
5903
- this.shown = next;
5904
- if (!changed) {
6307
+ for (const pair of own) {
6308
+ seen.add(pair);
6309
+ }
6310
+ }
6311
+ return "pingPong";
6312
+ }
6313
+ ChannelRounds.idle = idle;
6314
+ function day(now) {
6315
+ const date = new Date(now);
6316
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
6317
+ }
6318
+ ChannelRounds.day = day;
6319
+ function limits(stored) {
6320
+ const given = stored ?? {};
6321
+ const pick = (key) => LIMIT_CHOICES[key].includes(given[key]) ? given[key] : DEFAULT_LIMITS[key];
6322
+ return { answer: pick("answer"), channelDay: pick("channelDay"), allDay: pick("allDay") };
6323
+ }
6324
+ ChannelRounds.limits = limits;
6325
+ function today(stored, now) {
6326
+ const current = day(now);
6327
+ return stored?.day === current ? stored : { day: current, total: 0, channels: {} };
6328
+ }
6329
+ ChannelRounds.today = today;
6330
+ function spend(stored, channelId, tokens, now) {
6331
+ const current = today(stored, now);
6332
+ return { ...current, total: current.total + tokens, channels: { ...current.channels, [channelId]: (current.channels[channelId] ?? 0) + tokens } };
6333
+ }
6334
+ ChannelRounds.spend = spend;
6335
+ function held(spent, limits2, channelId, hops, granted = false) {
6336
+ if (granted) {
5905
6337
  return;
5906
6338
  }
5907
- this.list = list;
5908
- for (const listener of this.listeners) {
5909
- listener();
6339
+ if (limits2.allDay > 0 && spent.total >= limits2.allDay) {
6340
+ return "all";
6341
+ }
6342
+ if (hops > 0 && limits2.channelDay > 0 && (spent.channels[channelId] ?? 0) >= limits2.channelDay) {
6343
+ return "channel";
5910
6344
  }
6345
+ return;
5911
6346
  }
5912
- read(channelId) {
5913
- if (!this.reading.has(channelId)) {
5914
- this.reading.add(channelId);
5915
- this.context.service.messages(channelId).catch(() => this.reading.delete(channelId));
6347
+ ChannelRounds.held = held;
6348
+ function changedFiles(entries) {
6349
+ for (const entry of entries) {
6350
+ const message = entry?.message;
6351
+ if (entry?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) {
6352
+ continue;
6353
+ }
6354
+ for (const part of message.content) {
6355
+ if (part?.type !== "toolCall") {
6356
+ continue;
6357
+ }
6358
+ if (CHANGES.has(String(part.name)) || part.name === "agent_tool" && CHANGES.has(String(part.arguments?.kind))) {
6359
+ return true;
6360
+ }
6361
+ }
5916
6362
  }
6363
+ return false;
5917
6364
  }
5918
- status(state, channel, messages, working) {
5919
- const w = ChannelViews.words(this.context.pi);
5920
- const name = (id) => ChannelsText.authorName(state.team, id, { user: w.you, ta: w.ta });
5921
- if (working.length > 0) {
5922
- return { status: "running", detail: ChannelWords.format(w.answeringNow, { name: working.map(name).join("、") }) };
6365
+ ChannelRounds.changedFiles = changedFiles;
6366
+ function units(text) {
6367
+ return text.replace(/@[^\s@#,,。::]+/g, " ").toLowerCase().match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}]+/gu) ?? [];
6368
+ }
6369
+ function pairsOf(text) {
6370
+ const words = units(text);
6371
+ return words.length === 1 ? words : words.slice(1).map((word, i) => `${words[i]} ${word}`);
6372
+ }
6373
+ function alike(a, b) {
6374
+ if (a.length === 0 || b.length === 0) {
6375
+ return 0;
5923
6376
  }
5924
- const last = messages?.at(-1);
5925
- if (!last) {
5926
- const building = Date.now() - channel.createdAt < BUILDING_MS;
5927
- return building ? { status: "running", detail: w.building } : { status: "done", detail: channel.topic || w.noMessages, endedAt: channel.createdAt };
6377
+ const left = new Map;
6378
+ for (const pair of a) {
6379
+ left.set(pair, (left.get(pair) ?? 0) + 1);
5928
6380
  }
5929
- if (last.author === SYSTEM) {
5930
- return { status: "waiting", detail: w.yourTurn };
6381
+ let common = 0;
6382
+ for (const pair of b) {
6383
+ const n = left.get(pair) ?? 0;
6384
+ if (n > 0) {
6385
+ left.set(pair, n - 1);
6386
+ common++;
6387
+ }
5931
6388
  }
5932
- const said = `${name(last.author)}:${last.text.replace(/\s+/g, " ").slice(0, 120)}`;
5933
- return { status: last.failed ? "failed" : "done", detail: said, endedAt: last.at };
5934
- }
5935
- entry(channel, members, faces, working, status, detail, endedAt) {
5936
- return {
5937
- id: channel.id,
5938
- title: taskTitle(channel),
5939
- status,
5940
- detail,
5941
- startedAt: channel.createdAt,
5942
- endedAt: status === "running" || status === "waiting" ? undefined : endedAt,
5943
- origin: channel.origin,
5944
- icon: ({ size }) => /* @__PURE__ */ React.createElement(RoomFace, {
5945
- members,
5946
- faces,
5947
- size,
5948
- working
5949
- }),
5950
- open: () => openScene(this.context, channel),
5951
- show: () => this.context.showChannel(channel.id),
5952
- menu: () => taskMenu(this.context, channel, working),
5953
- remove: () => deleteTeam(this.context, channel),
5954
- removeHint: ChannelWords.format(ChannelViews.words(this.context.pi).deleteTaskHint, { channel: channel.name })
5955
- };
6389
+ return 2 * common / (a.length + b.length);
5956
6390
  }
6391
+ })(ChannelRounds ||= {});
6392
+
6393
+ // web-src/limit-settings.tsx
6394
+ function amount(pi, tokens) {
6395
+ return tokens > 0 ? new Intl.NumberFormat(pi.ui.language, { notation: "compact", maximumFractionDigits: 1 }).format(tokens) : ChannelWords.of(pi.ui.language).noLimit;
5957
6396
  }
5958
- function taskTitle(channel) {
5959
- return channel.name;
5960
- }
5961
- async function deleteTeam(context, channel) {
5962
- await context.service.deleteChannel(channel.id);
5963
- context.pi.ui.closeEditor(`channel:${channel.id}`);
5964
- }
5965
- function openScene(context, channel) {
5966
- context.pi.ui.openEditor({
5967
- id: `channel:${channel.id}`,
5968
- title: channel.name,
5969
- icon: ChannelViews.icon(context.pi, "Hash"),
5970
- render: () => /* @__PURE__ */ React.createElement("div", {
5971
- className: "tac-scene"
5972
- }, /* @__PURE__ */ React.createElement(ChannelSceneHead, {
5973
- context,
5974
- channelId: channel.id
5975
- }), /* @__PURE__ */ React.createElement(ChannelRoom, {
5976
- context,
5977
- channelId: channel.id
5978
- }))
5979
- });
6397
+ function useLimits(pi) {
6398
+ const read = React.useCallback(async () => ({
6399
+ limits: ChannelRounds.limits(await pi.storage.get(Keys.LIMITS)),
6400
+ ...((today) => ({ spent: today.total, channels: today.channels }))(ChannelRounds.today(await pi.storage.get(Keys.SPENT), Date.now()))
6401
+ }), [pi]);
6402
+ const [value, setValue] = React.useState({ limits: ChannelRounds.limits(undefined), spent: 0, channels: {} });
6403
+ React.useEffect(() => {
6404
+ let live = true;
6405
+ const load = () => void read().then((next) => live && setValue(next), () => {
6406
+ return;
6407
+ });
6408
+ load();
6409
+ const stop = pi.storage.onChange((keys) => (keys.includes(Keys.LIMITS) || keys.includes(Keys.SPENT)) && load());
6410
+ return () => {
6411
+ live = false;
6412
+ stop();
6413
+ };
6414
+ }, [pi, read]);
6415
+ return value;
5980
6416
  }
5981
- function taskMenu(context, channel, working) {
5982
- const { pi, service } = context;
5983
- const w = ChannelViews.words(pi);
5984
- const icon = (name) => ChannelViews.icon(pi, name);
5985
- const act = (action2) => () => {
5986
- Promise.resolve().then(action2).catch((error) => pi.ui.notify(ChannelViews.message(error), "error"));
6417
+ function limitSettings(pi, service) {
6418
+ const words = () => ChannelWords.of(pi.ui.language);
6419
+ const row = (key) => function Choices() {
6420
+ const { limits } = useLimits(pi);
6421
+ const pick = (value) => void service.setLimits({ [key]: value }).catch((error) => pi.ui.notify(String(error?.message ?? error), "error"));
6422
+ return /* @__PURE__ */ React.createElement("fieldset", {
6423
+ className: "ta-segmented",
6424
+ "aria-label": words()[key === "answer" ? "limitAnswer" : key === "channelDay" ? "limitChannelDay" : "limitAllDay"]
6425
+ }, LIMIT_CHOICES[key].map((value) => /* @__PURE__ */ React.createElement("button", {
6426
+ key: value,
6427
+ type: "button",
6428
+ "aria-pressed": limits[key] === value,
6429
+ className: limits[key] === value ? "ta-on" : "",
6430
+ onClick: () => pick(value)
6431
+ }, amount(pi, value))));
5987
6432
  };
5988
- const temporary = membersOf(service.state.team, channel).filter((agent) => agent.temporary);
5989
- return [
5990
- working.length > 0 ? [
5991
- {
5992
- key: "stop",
5993
- label: w.stopAnswering,
5994
- icon: icon("Square"),
5995
- run: act(async () => {
5996
- await TeamActions.stop(context, working);
5997
- pi.ui.notify(ChannelWords.format(w.stoppedChannel, { channel: channel.name }), "info");
5998
- })
5999
- }
6000
- ] : [],
6001
- [
6002
- { key: "main", label: w.openInMain, icon: icon("ExternalLink"), run: () => context.showChannel(channel.id) },
6003
- ...temporary.length > 0 ? [
6004
- {
6005
- key: "keep",
6006
- label: w.keepMembers,
6007
- icon: icon("UserPlus"),
6008
- run: act(async () => {
6009
- await TeamActions.keep(context, temporary);
6010
- pi.ui.notify(ChannelWords.format(w.keptMembers, { names: temporary.map((agent) => `@${agent.name}`).join("、") }), "info");
6011
- })
6012
- }
6013
- ] : []
6014
- ],
6015
- [
6016
- {
6017
- key: "delete",
6018
- label: w.deleteTask,
6019
- icon: icon("Trash2"),
6020
- danger: true,
6021
- run: act(() => pi.ui.removeTasks([
6022
- {
6023
- title: taskTitle(channel),
6024
- removeHint: ChannelWords.format(w.deleteTaskHint, { channel: channel.name }),
6025
- remove: () => deleteTeam(context, channel)
6026
- }
6027
- ]))
6028
- }
6433
+ function Spent() {
6434
+ const { spent } = useLimits(pi);
6435
+ return /* @__PURE__ */ React.createElement("span", {
6436
+ className: "tac-limit-spent"
6437
+ }, spent > 0 ? amount(pi, spent) : "0");
6438
+ }
6439
+ return {
6440
+ title: () => words().limitsTitle,
6441
+ icon: pi.ui.icons.Coins ?? pi.ui.icons.Gauge,
6442
+ group: "ta",
6443
+ rows: [
6444
+ { key: "answer", label: () => words().limitAnswer, description: () => words().limitAnswerHint, render: row("answer") },
6445
+ { key: "channelDay", label: () => words().limitChannelDay, description: () => words().limitChannelDayHint, render: row("channelDay") },
6446
+ { key: "allDay", label: () => words().limitAllDay, description: () => words().limitAllDayHint, render: row("allDay") },
6447
+ { key: "spent", label: () => words().limitSpent, render: Spent }
6029
6448
  ]
6030
- ];
6449
+ };
6031
6450
  }
6032
- var TeamActions;
6033
- ((TeamActions) => {
6034
- async function stop(context, agentIds) {
6035
- const { pi, service } = context;
6036
- const files = new Set(service.state.team.agents.filter((agent) => agentIds.includes(agent.id) && agent.sessionFile).map((agent) => agent.sessionFile));
6037
- const sessions = (await pi.server.listSessions()).filter((session) => session.sessionFile && files.has(session.sessionFile));
6038
- await Promise.all(sessions.map((session) => pi.server.abort(session.sessionId)));
6039
- }
6040
- TeamActions.stop = stop;
6041
- async function keep(context, agents) {
6042
- for (const agent of agents) {
6043
- await context.service.updateAgent(agent.id, { keep: true });
6044
- }
6045
- }
6046
- TeamActions.keep = keep;
6047
- })(TeamActions ||= {});
6048
6451
 
6049
6452
  // web-src/channel-menu.tsx
6050
6453
  function download2(name, text) {