@celljs/ta-channels 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/index.mjs CHANGED
@@ -1,9 +1,3 @@
1
- // ../ta-protocol/esm/common/access-protocol.js
2
- var TaAccessServer = Symbol("TaAccessServer");
3
- // ../ta-protocol/esm/common/auth-protocol.js
4
- var TaAuthServer = Symbol("TaAuthServer");
5
- // ../ta-protocol/esm/common/gateway-protocol.js
6
- var TaGatewayServer = Symbol("TaGatewayServer");
7
1
  // ../ta-protocol/esm/common/language.js
8
2
  var TaLanguageUtil;
9
3
  (function(TaLanguageUtil2) {
@@ -42,303 +36,180 @@ var TaLanguageUtil;
42
36
  }
43
37
  TaLanguageUtil2.list = list;
44
38
  })(TaLanguageUtil || (TaLanguageUtil = {}));
45
- // ../ta-protocol/esm/common/location.js
46
- var TaLocation;
47
- (function(TaLocation2) {
48
- TaLocation2.SSH = "ssh://";
49
- TaLocation2.CLOUD = "ta://";
50
- const CLOUD_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
51
- const HOST = /^(?!-)[\w.@:%+[\]-]+$/;
52
- function isRemote(location) {
53
- return location.startsWith(TaLocation2.SSH) || location.startsWith(TaLocation2.CLOUD);
54
- }
55
- TaLocation2.isRemote = isRemote;
56
- function isCloud(host2) {
57
- return !!host2 && host2.startsWith(TaLocation2.CLOUD);
58
- }
59
- TaLocation2.isCloud = isCloud;
60
- function isCloudName(name) {
61
- return CLOUD_NAME.test(name);
39
+
40
+ // ../ta-protocol/esm/common/team-protocol.js
41
+ var TA_OWNER = "owner";
42
+ var TA_UNDECLARED = "extensions.install";
43
+ var TaPermissionUtil;
44
+ (function(TaPermissionUtil2) {
45
+ function read(pi) {
46
+ const given = pi === null || pi === undefined ? undefined : pi.permissions;
47
+ const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
48
+ const host2 = map(given === null || given === undefined ? undefined : given.host);
49
+ const tools = map(given === null || given === undefined ? undefined : given.tools);
50
+ return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
62
51
  }
63
- TaLocation2.isCloudName = isCloudName;
64
- function cloud(name, path2 = "") {
65
- return `${TaLocation2.CLOUD}${name}${path2 ? normalize(path2) : ""}`;
52
+ TaPermissionUtil2.read = read;
53
+ function host(manifest, method, kind) {
54
+ var _a, _b, _c, _d;
55
+ const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
56
+ const own = (key) => Object.prototype.hasOwnProperty.call(host2, key) ? host2[key] : undefined;
57
+ 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;
66
58
  }
67
- TaLocation2.cloud = cloud;
68
- function cloudName(hostOrLocation) {
69
- if (!hostOrLocation.startsWith(TaLocation2.CLOUD)) {
70
- return;
71
- }
72
- const rest = hostOrLocation.slice(TaLocation2.CLOUD.length);
73
- const slash = rest.indexOf("/");
74
- return slash < 0 ? rest : rest.slice(0, slash);
59
+ TaPermissionUtil2.host = host;
60
+ })(TaPermissionUtil || (TaPermissionUtil = {}));
61
+ var action = (id, en, zh, tw, ja, more = {}) => ({
62
+ id,
63
+ area: id.split(".")[0],
64
+ title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
65
+ ...more
66
+ });
67
+ var TA_ACTIONS = [
68
+ action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
69
+ action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
70
+ action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
71
+ action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
72
+ action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
73
+ action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
74
+ action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
75
+ action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
76
+ action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
77
+ action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
78
+ action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
79
+ action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
80
+ action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
81
+ action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
82
+ action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
83
+ action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
84
+ action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
85
+ action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
86
+ action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
87
+ action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
88
+ action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
89
+ action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
90
+ action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
91
+ action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
92
+ action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
93
+ action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
94
+ action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
95
+ action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
96
+ action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
97
+ action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
98
+ action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
99
+ action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
100
+ action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
101
+ ];
102
+ var TA_OWNER_ACTIONS = [
103
+ action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
104
+ action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true })
105
+ ];
106
+ var OWNER_AREAS = ["desktop"];
107
+ var TaActionUtil;
108
+ (function(TaActionUtil2) {
109
+ const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
110
+ const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
111
+ function info(id) {
112
+ return byId.get(id);
75
113
  }
76
- TaLocation2.cloudName = cloudName;
77
- function parse(location) {
114
+ TaActionUtil2.info = info;
115
+ function title(id, language) {
78
116
  var _a;
79
- if (!isRemote(location)) {
80
- return;
81
- }
82
- if (location.startsWith(TaLocation2.CLOUD)) {
83
- const name = (_a = cloudName(location)) !== null && _a !== undefined ? _a : "";
84
- if (!isCloudName(name)) {
85
- throw new Error(`${JSON.stringify(location)} names no cloud workspace: write ta://<name>/<path>.`);
86
- }
87
- const path3 = location.slice(TaLocation2.CLOUD.length + name.length);
88
- return { host: `${TaLocation2.CLOUD}${name}`, path: path3 ? normalize(path3) : "" };
89
- }
90
- const rest = location.slice(TaLocation2.SSH.length);
91
- const slash = rest.indexOf("/");
92
- const host2 = slash < 0 ? rest : rest.slice(0, slash);
93
- const path2 = slash < 0 ? "" : normalize(rest.slice(slash));
94
- if (!isHost(host2)) {
95
- throw new Error(`${JSON.stringify(location)} names no host: write ssh://<host>/<path>, the host as ssh takes it.`);
117
+ var _b, _c;
118
+ const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
119
+ if (!title2) {
120
+ return id;
96
121
  }
97
- return { host: host2, path: path2 };
122
+ return TaLanguageUtil.pick(language, {
123
+ "zh-CN": title2["zh-CN"],
124
+ "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
125
+ "en-US": title2.en,
126
+ "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
127
+ });
98
128
  }
99
- TaLocation2.parse = parse;
100
- function isHost(host2) {
101
- return isCloud(host2) ? isCloudName(host2.slice(TaLocation2.CLOUD.length)) : HOST.test(host2);
129
+ TaActionUtil2.title = title;
130
+ function grantable(id) {
131
+ const info2 = byId.get(id);
132
+ return !!info2 && !OWNER_AREAS.includes(info2.area);
102
133
  }
103
- TaLocation2.isHost = isHost;
104
- const FLAGS = /^-[46AaCfGgKkMNnqsTtVvXxYy]+$/;
105
- function readHost(input) {
106
- const words = input.trim().split(/\s+/).filter(Boolean);
107
- if (words[0] === "ssh") {
108
- words.shift();
109
- }
110
- let destination;
111
- let port;
112
- let user;
113
- const options = [];
114
- for (let i = 0;i < words.length; i++) {
115
- const word = words[i];
116
- const glued = /^-([pl])(.+)$/.exec(word);
117
- if (word === "-p" || word === "-l" || glued) {
118
- const value = glued ? glued[2] : words[++i];
119
- if (value === undefined) {
120
- return { error: "invalid" };
121
- }
122
- if ((glued ? glued[1] : word[1]) === "p") {
123
- port = value;
124
- } else {
125
- user = value;
126
- }
127
- } else if (word === "-o" || word.startsWith("-o")) {
128
- const value = word === "-o" ? words[++i] : word.slice(2);
129
- const option = /^(port|user)\s*=?\s*(.+)$/i.exec(value !== null && value !== undefined ? value : "");
130
- if (!option) {
131
- options.push(`-o ${value !== null && value !== undefined ? value : ""}`.trim());
132
- } else if (option[1].toLowerCase() === "port") {
133
- port = option[2];
134
- } else {
135
- user = option[2];
136
- }
137
- } else if (FLAGS.test(word)) {} else if (word.startsWith("-")) {
138
- options.push(/^-[bBcDeEFiIJLmOQRSwW]$/.test(word) && words[i + 1] !== undefined ? `${word} ${words[++i]}` : word);
139
- } else if (destination === undefined) {
140
- destination = word;
141
- } else {
142
- return { error: "invalid" };
143
- }
144
- }
145
- if (options.length > 0) {
146
- return { error: "options", options };
147
- }
148
- if (!destination) {
149
- return { error: "empty" };
150
- }
151
- let host2 = destination.replace(/^ssh:\/\//, "").replace(/\/.*$/, "");
152
- if (user && !host2.includes("@")) {
153
- host2 = `${user}@${host2}`;
154
- }
155
- if (port) {
156
- if (!/^\d{1,5}$/.test(port) || /:\d+$/.test(host2)) {
157
- return { error: "invalid" };
158
- }
159
- host2 = port === "22" ? host2 : `${host2}:${port}`;
160
- }
161
- return isHost(host2) ? { host: host2 } : { error: "invalid" };
134
+ TaActionUtil2.grantable = grantable;
135
+ function inRoles(id) {
136
+ var _a;
137
+ return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
162
138
  }
163
- TaLocation2.readHost = readHost;
164
- function ssh(host2, path2 = "") {
165
- return isCloud(host2) ? `${host2}${path2 ? normalize(path2) : ""}` : `${TaLocation2.SSH}${host2}${path2 ? normalize(path2) : ""}`;
139
+ TaActionUtil2.inRoles = inRoles;
140
+ function inside(dir, path) {
141
+ const base = dir.replace(/\/+$/, "");
142
+ return path === base || path.startsWith(`${base}/`) || base === "";
166
143
  }
167
- TaLocation2.ssh = ssh;
168
- function hostLabel(host2) {
169
- if (isCloud(host2)) {
170
- return host2.slice(TaLocation2.CLOUD.length);
171
- }
172
- const name = host2.replace(/^[^@]*@/, "").replace(/^\[(.*)\](?::\d+)?$/, "$1").replace(/^([^:]*):\d+$/, "$1");
173
- return /^[\d.]+$/.test(name) || name.includes(":") ? name : name.split(".")[0] || name;
144
+ TaActionUtil2.inside = inside;
145
+ })(TaActionUtil || (TaActionUtil = {}));
146
+
147
+ // ../ta-protocol/esm/common/message-protocol.js
148
+ var TaMessageContext;
149
+ (function(TaMessageContext2) {
150
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
151
+ function wrap(context, message) {
152
+ return `<context>
153
+ ${context}
154
+ </context>
155
+ ${message}`;
174
156
  }
175
- TaLocation2.hostLabel = hostLabel;
176
- function host(location) {
177
- var _a;
178
- return isRemote(location) ? (_a = parse(location)) === null || _a === undefined ? undefined : _a.host : undefined;
157
+ TaMessageContext2.wrap = wrap;
158
+ function strip(message) {
159
+ return message.replace(BLOCK, "");
179
160
  }
180
- TaLocation2.host = host;
181
- function path(location) {
161
+ TaMessageContext2.strip = strip;
162
+ function read(message) {
182
163
  var _a;
183
- var _b;
184
- return (_b = (_a = parse(location)) === null || _a === undefined ? undefined : _a.path) !== null && _b !== undefined ? _b : location;
164
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
165
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
185
166
  }
186
- TaLocation2.path = path;
187
- function parent(location) {
188
- const remote = parse(location);
189
- if (remote) {
190
- const above = remote.path ? parentPath(remote.path) : undefined;
191
- return above === undefined ? undefined : ssh(remote.host, above);
192
- }
193
- return parentPath(location);
167
+ TaMessageContext2.read = read;
168
+ })(TaMessageContext || (TaMessageContext = {}));
169
+ var TaMessageSource;
170
+ (function(TaMessageSource2) {
171
+ TaMessageSource2.DOUBLE = "ta:double";
172
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
173
+ function mark(message, from, detail) {
174
+ return marked(message, line(from, detail));
194
175
  }
195
- TaLocation2.parent = parent;
196
- function child(location, name) {
197
- const remote = parse(location);
198
- if (remote) {
199
- return ssh(remote.host, childPath(remote.path || "/", name));
200
- }
201
- return childPath(location, name);
176
+ TaMessageSource2.mark = mark;
177
+ function notice(message, from, detail) {
178
+ return marked(message, line(from, detail, true));
202
179
  }
203
- TaLocation2.child = child;
204
- function basename(location) {
205
- const remote = parse(location);
206
- const path2 = (remote ? remote.path : location).replace(/[\\/]+$/, "");
207
- const name = path2.slice(Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\")) + 1);
208
- return name || (remote === null || remote === undefined ? undefined : remote.host) || location;
180
+ TaMessageSource2.notice = notice;
181
+ function line(from, detail, notice2 = false) {
182
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
209
183
  }
210
- TaLocation2.basename = basename;
211
- function homeRelative(location) {
212
- var _a;
213
- const remote = parse(location);
214
- const path2 = remote ? remote.path ? remote.path.slice(1) : "~" : location;
215
- const match = /^~(?:[\\/]+(.*))?$/.exec(path2);
216
- return match ? ((_a = match[1]) !== null && _a !== undefined ? _a : "").replace(/[\\/]+$/, "") : undefined;
217
- }
218
- TaLocation2.homeRelative = homeRelative;
219
- function isAbsolute(location) {
220
- if (homeRelative(location) !== undefined) {
221
- return false;
222
- }
223
- return isRemote(location) || /^([\\/]|[A-Za-z]:)/.test(location);
224
- }
225
- TaLocation2.isAbsolute = isAbsolute;
226
- function parentPath(path2) {
227
- const trimmed = path2.replace(/[\\/]+$/, "");
228
- const at = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
229
- if (at < 0) {
230
- return;
231
- }
232
- const head = trimmed.slice(0, at);
233
- return head === "" || /^[A-Za-z]:$/.test(head) ? head + trimmed[at] : head;
234
- }
235
- function childPath(path2, name) {
236
- const separator = path2.includes("/") || !path2.includes("\\") ? "/" : "\\";
237
- return path2.endsWith(separator) ? path2 + name : path2 + separator + name;
238
- }
239
- function normalize(path2) {
240
- const squeezed = `/${path2}`.replace(/\/+/g, "/");
241
- return squeezed.length > 1 ? squeezed.replace(/\/$/, "") : squeezed;
242
- }
243
- })(TaLocation || (TaLocation = {}));
244
- // ../ta-protocol/esm/common/package-protocol.js
245
- var TaPackageServer = Symbol("TaPackageServer");
246
- var TaPackageTextUtil;
247
- (function(TaPackageTextUtil2) {
248
- function pick(text, language) {
249
- var _a, _b, _c, _d, _e;
250
- if (text === undefined || typeof text === "string") {
251
- return text;
252
- }
253
- const base = language.split("-")[0];
254
- const kin = Object.keys(text).find((key) => key.split("-")[0] === base);
255
- return (_e = (_d = (_c = (_b = (_a = text[language]) !== null && _a !== undefined ? _a : text[base]) !== null && _b !== undefined ? _b : kin === undefined ? undefined : text[kin]) !== null && _c !== undefined ? _c : text.en) !== null && _d !== undefined ? _d : text["en-US"]) !== null && _e !== undefined ? _e : Object.values(text)[0];
256
- }
257
- TaPackageTextUtil2.pick = pick;
258
- })(TaPackageTextUtil || (TaPackageTextUtil = {}));
259
- // ../ta-protocol/esm/common/ta-protocol.js
260
- var TaServer = Symbol("TaServer");
261
- var TaClient = Symbol("TaClient");
262
- var TaErrorCode = {
263
- SESSION_NOT_FOUND: "CELL_TA_SESSION_NOT_FOUND",
264
- SESSION_LOCKED: "CELL_TA_SESSION_LOCKED",
265
- TOO_MANY_SESSIONS: "CELL_TA_TOO_MANY_SESSIONS",
266
- MESSAGE_CONFLICT: "CELL_TA_MESSAGE_CONFLICT",
267
- MODEL_NOT_FOUND: "CELL_TA_MODEL_NOT_FOUND",
268
- INVALID_ARGUMENT: "CELL_TA_INVALID_ARGUMENT",
269
- COMMAND_FAILED: "CELL_TA_COMMAND_FAILED",
270
- NOTHING_TO_COMPACT: "CELL_TA_NOTHING_TO_COMPACT",
271
- ALREADY_COMPACTED: "CELL_TA_ALREADY_COMPACTED",
272
- SESSION_BUSY: "CELL_TA_SESSION_BUSY",
273
- CANCELLED: "CELL_TA_CANCELLED",
274
- NOT_SIGNED_IN: "CELL_TA_NOT_SIGNED_IN",
275
- ENVIRONMENT_FAILED: "CELL_TA_ENVIRONMENT_FAILED",
276
- RATE_LIMITED: "CELL_TA_RATE_LIMITED",
277
- FORBIDDEN: "CELL_TA_FORBIDDEN",
278
- LIMIT: "CELL_TA_LIMIT",
279
- CONNECTION_LOST: "CELL_TA_CONNECTION_LOST"
280
- };
281
- var TaErrorUtil;
282
- (function(TaErrorUtil2) {
283
- function code(error) {
284
- var _a;
285
- var _b;
286
- const failure = error;
287
- const code2 = (_b = failure === null || failure === undefined ? undefined : failure.code) !== null && _b !== undefined ? _b : (_a = failure === null || failure === undefined ? undefined : failure.data) === null || _a === undefined ? undefined : _a.code;
288
- return typeof code2 === "string" ? code2 : undefined;
289
- }
290
- TaErrorUtil2.code = code;
291
- })(TaErrorUtil || (TaErrorUtil = {}));
292
- var TaSlashCommandUtil;
293
- (function(TaSlashCommandUtil2) {
294
- function description(command, language) {
295
- var _a, _b;
296
- const { descriptions } = command;
297
- return (_b = (_a = descriptions === null || descriptions === undefined ? undefined : descriptions[language]) !== null && _a !== undefined ? _a : descriptions === null || descriptions === undefined ? undefined : descriptions[language.split("-")[0]]) !== null && _b !== undefined ? _b : command.description;
298
- }
299
- TaSlashCommandUtil2.description = description;
300
- })(TaSlashCommandUtil || (TaSlashCommandUtil = {}));
301
- var TaMessageContext;
302
- (function(TaMessageContext2) {
303
- const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
304
- function wrap(context, message) {
305
- return `<context>
306
- ${context}
307
- </context>
308
- ${message}`;
309
- }
310
- TaMessageContext2.wrap = wrap;
311
- function strip(message) {
312
- return message.replace(BLOCK, "");
184
+ TaMessageSource2.line = line;
185
+ function of(message) {
186
+ const context = TaMessageContext.read(message);
187
+ const match = context === undefined ? null : LINE.exec(context);
188
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
313
189
  }
314
- TaMessageContext2.strip = strip;
315
- function read(message) {
190
+ TaMessageSource2.of = of;
191
+ function isNotice(message) {
316
192
  var _a;
317
- const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
318
- return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
319
- }
320
- TaMessageContext2.read = read;
321
- })(TaMessageContext || (TaMessageContext = {}));
322
- var TaMessageSource;
323
- (function(TaMessageSource2) {
324
- TaMessageSource2.DOUBLE = "ta:double";
325
- const LINE = /^\[ta:from ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
326
- function mark(message, from, detail) {
193
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
194
+ }
195
+ TaMessageSource2.isNotice = isNotice;
196
+ TaMessageSource2.SECTION = "ta-sources";
197
+ TaMessageSource2.PROMPT = [
198
+ "Who wrote a message: what the user typed or said is theirs. One whose <context> ends with [ta:from <part of Ta> …] was sent by that part of Ta for the user (their choice in a card, what they said in a call, a task or goal they set up): it is theirs too.",
199
+ "One with [ta:notice <part of Ta> …] is not the user's: news or an event of that part of Ta (work that ended elsewhere, a time limit, a permission granted). Weigh it below what the user said:",
200
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
201
+ "- Act on it only as far as what they asked, your role or a limit they set calls for; otherwise take it in and go on, and tell them of it in a line only when they need it (a result they wait for, a failure, a question for them).",
202
+ "- Never quote it as the user's words nor answer it as if they had said it."
203
+ ].join(`
204
+ `);
205
+ function marked(message, source) {
327
206
  if (/^[/!]/.test(message) || of(message)) {
328
207
  return message;
329
208
  }
330
- const line = `[ta:from ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
331
- const context = TaMessageContext.read(message);
332
- return TaMessageContext.wrap(context === undefined ? line : `${context}
333
- ${line}`, TaMessageContext.strip(message));
334
- }
335
- TaMessageSource2.mark = mark;
336
- function of(message) {
337
209
  const context = TaMessageContext.read(message);
338
- const match = context === undefined ? null : LINE.exec(context);
339
- return match ? { from: match[1], ...match[2] ? { detail: match[2].trim() } : {} } : undefined;
210
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
211
+ ${source}`, TaMessageContext.strip(message));
340
212
  }
341
- TaMessageSource2.of = of;
342
213
  })(TaMessageSource || (TaMessageSource = {}));
343
214
  var TaImageNote;
344
215
  (function(TaImageNote2) {
@@ -460,328 +331,169 @@ var TaSkillUse;
460
331
  }
461
332
  TaSkillUse2.command = command;
462
333
  })(TaSkillUse || (TaSkillUse = {}));
463
-
464
- // ../ta-protocol/esm/common/presence-protocol.js
465
- var TaPresenceServer = Symbol("TaPresenceServer");
466
- var TaMessageAuthor;
467
- (function(TaMessageAuthor2) {
468
- const LINE = /^\[ta:by ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
469
- const LINES = /^\[ta:by [^\]\n]*\]$\n?/gm;
470
- function strip(message) {
471
- const context = TaMessageContext.read(message);
472
- if (context === undefined || !LINE.test(context)) {
473
- return message;
334
+ var TaTaskNote;
335
+ (function(TaTaskNote2) {
336
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
337
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
338
+ function write(note) {
339
+ const attributes = [`id="${quote(note.id)}"`];
340
+ if (note.was !== undefined) {
341
+ attributes.push(`was="${quote(note.was)}"`);
342
+ }
343
+ attributes.push(`title="${quote(note.title)}"`);
344
+ if (note.status !== undefined) {
345
+ attributes.push(`status="${quote(note.status)}"`);
346
+ }
347
+ return `<task_${note.kind} ${attributes.join(" ")}>
348
+ ${note.body}
349
+ </task_${note.kind}>`;
350
+ }
351
+ TaTaskNote2.write = write;
352
+ function parse(text) {
353
+ const match = NOTE.exec(text.trim());
354
+ if (!match) {
355
+ return;
474
356
  }
475
- const kept = context.replace(LINES, "").replace(/\n+$/, "");
476
- const body = TaMessageContext.strip(message);
477
- return kept.trim() ? TaMessageContext.wrap(kept, body) : body;
478
- }
479
- TaMessageAuthor2.strip = strip;
480
- function mark(message, id, name) {
481
- const plain = strip(message);
482
- if (/^[/!]/.test(plain)) {
483
- return plain;
357
+ const attributes = {};
358
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
359
+ attributes[name] = unquote(value);
484
360
  }
485
- const line = `[ta:by ${id.replace(/[\s\]]/g, "")} ${name.replace(/[\]\n]/g, " ").trim() || id}]`;
486
- const context = TaMessageContext.read(plain);
487
- return TaMessageContext.wrap(context === undefined ? line : `${context}
488
- ${line}`, TaMessageContext.strip(plain));
489
- }
490
- TaMessageAuthor2.mark = mark;
491
- function of(message) {
361
+ if (!attributes.id || attributes.title === undefined) {
362
+ return;
363
+ }
364
+ const { id, title, status, was } = attributes;
365
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
366
+ }
367
+ TaTaskNote2.parse = parse;
368
+ function quote(text) {
369
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
370
+ }
371
+ function unquote(text) {
372
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
373
+ }
374
+ })(TaTaskNote || (TaTaskNote = {}));
375
+ var TaSecretRef;
376
+ (function(TaSecretRef2) {
377
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
378
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
379
+ const KINDS = [
380
+ [/^PHONE(?:_\d+)?$/, "phone"],
381
+ [/^EMAIL(?:_\d+)?$/, "email"],
382
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
383
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
384
+ ];
385
+ function has(text) {
386
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
387
+ }
388
+ TaSecretRef2.has = has;
389
+ function kind(name) {
492
390
  var _a;
493
- const context = TaMessageContext.read(message);
494
- const match = context === undefined ? null : LINE.exec(context);
495
- return match ? { id: match[1], name: ((_a = match[2]) !== null && _a !== undefined ? _a : match[1]).trim() } : undefined;
391
+ var _b;
392
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
393
+ }
394
+ TaSecretRef2.kind = kind;
395
+ function split(text) {
396
+ if (!has(text)) {
397
+ return [{ text }];
398
+ }
399
+ const parts = [];
400
+ let at = 0;
401
+ for (const match of text.matchAll(REF)) {
402
+ if (match.index > at) {
403
+ parts.push({ text: text.slice(at, match.index) });
404
+ }
405
+ parts.push({ secret: match[1], kind: kind(match[1]) });
406
+ at = match.index + match[0].length;
407
+ }
408
+ if (at < text.length) {
409
+ parts.push({ text: text.slice(at) });
410
+ }
411
+ return parts;
496
412
  }
497
- TaMessageAuthor2.of = of;
498
- })(TaMessageAuthor || (TaMessageAuthor = {}));
499
- // ../ta-protocol/esm/common/relay-protocol.js
500
- var TaRelayServer = Symbol("TaRelayServer");
501
- // ../ta-protocol/esm/common/remote-protocol.js
502
- var TaRemoteServer = Symbol("TaRemoteServer");
503
- // ../ta-protocol/esm/common/room-protocol.js
504
- var TaRoomServer = Symbol("TaRoomServer");
505
- var TaRoomWatchUtil;
506
- (function(TaRoomWatchUtil2) {
507
- function of(messages, state) {
508
- const prefixes = Array.isArray(state) ? state.filter((prefix) => typeof prefix === "string" && prefix.length > 0) : [];
509
- return { messages: messages !== false, state: [...new Set(prefixes)].sort() };
413
+ TaSecretRef2.split = split;
414
+ function plain(text, label) {
415
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
510
416
  }
511
- TaRoomWatchUtil2.of = of;
512
- function union(watches) {
513
- let messages = false;
514
- const state = [];
515
- for (const watch of watches) {
516
- messages || (messages = watch.messages);
517
- state.push(...watch.state);
417
+ TaSecretRef2.plain = plain;
418
+ })(TaSecretRef || (TaSecretRef = {}));
419
+
420
+ // ../ta-protocol/esm/common/redactor.js
421
+ var REDACTED = "[redacted]";
422
+ var WHOLE = [
423
+ ["PRIVATE_KEY", /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g],
424
+ ["API_KEY", /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g],
425
+ ["GITHUB_TOKEN", /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g],
426
+ ["GITHUB_TOKEN", /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g],
427
+ ["GITLAB_TOKEN", /\bglpat-[A-Za-z0-9_-]{20,}\b/g],
428
+ ["SLACK_TOKEN", /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g],
429
+ ["AWS_ACCESS_KEY_ID", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g],
430
+ ["GOOGLE_API_KEY", /\bAIza[0-9A-Za-z_-]{35}\b/g],
431
+ ["JWT", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g]
432
+ ];
433
+ var NAMED = [
434
+ /(\bBearer\s+)[A-Za-z0-9._~+/-]{16,}=*/gi,
435
+ /(\b[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)([^\s"'`,;]{6,})/gi,
436
+ /(:\/\/[^\s:/@]+:)([^\s@/]{3,})(@)/g
437
+ ];
438
+
439
+ class Redactor {
440
+ constructor() {
441
+ this.count = 0;
442
+ }
443
+ text(text) {
444
+ let out = text;
445
+ for (const [, pattern] of WHOLE) {
446
+ out = out.replace(pattern, () => this.hide());
518
447
  }
519
- return of(messages, messages ? [] : state);
448
+ out = out.replace(NAMED[0], (_match, before) => before + this.hide());
449
+ out = out.replace(NAMED[1], (match, before, value) => Redactor.placeholder(value) ? match : before + this.hide());
450
+ out = out.replace(NAMED[2], (_match, before, _value, after) => before + this.hide() + after);
451
+ return out;
520
452
  }
521
- TaRoomWatchUtil2.union = union;
522
- function same(a, b) {
523
- return a === b || !!a && !!b && a.messages === b.messages && a.state.join(`
524
- `) === b.state.join(`
525
- `);
453
+ value(value, max) {
454
+ if (typeof value === "string") {
455
+ return Redactor.cut(this.text(value), max);
456
+ }
457
+ if (Array.isArray(value)) {
458
+ return value.map((item) => this.value(item, max));
459
+ }
460
+ if (value && typeof value === "object") {
461
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.value(item, max)]));
462
+ }
463
+ return value;
526
464
  }
527
- TaRoomWatchUtil2.same = same;
528
- function hears(watch, event) {
529
- if (event.type === "message") {
530
- return watch.messages;
465
+ static spans(text) {
466
+ var _a;
467
+ var _b;
468
+ const found = [];
469
+ for (const [kind, pattern] of WHOLE) {
470
+ for (const match of text.matchAll(pattern)) {
471
+ found.push({ start: match.index, end: match.index + match[0].length, kind });
472
+ }
531
473
  }
532
- if (event.type === "state") {
533
- return watch.messages || watch.state.some((prefix) => event.key.startsWith(prefix));
474
+ for (const match of text.matchAll(NAMED[0])) {
475
+ found.push({ start: match.index + match[1].length, end: match.index + match[0].length, kind: "BEARER_TOKEN" });
534
476
  }
535
- return true;
536
- }
537
- TaRoomWatchUtil2.hears = hears;
538
- })(TaRoomWatchUtil || (TaRoomWatchUtil = {}));
539
- // ../ta-protocol/esm/common/settings-protocol.js
540
- var TaSettingsServer = Symbol("TaSettingsServer");
541
- // ../ta-protocol/esm/common/ta-extension-host.js
542
- var TA_HOST_EVENT = "ta:host";
543
- var TaHostUtil;
544
- (function(TaHostUtil2) {
545
- TaHostUtil2.WAIT_MS = 1000;
546
- function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
547
- return new Promise((resolve) => {
548
- let heard = false;
549
- let answered = false;
550
- const timer = setTimeout(() => resolve(undefined), waitMs);
551
- const request = {
552
- name,
553
- heard: () => {
554
- heard = true;
555
- },
556
- resolve: (answer) => {
557
- answered = true;
558
- clearTimeout(timer);
559
- resolve(answer);
560
- }
561
- };
562
- events.emit(TA_HOST_EVENT, request);
563
- if (!heard && !answered) {
564
- clearTimeout(timer);
565
- resolve(undefined);
566
- }
567
- });
568
- }
569
- TaHostUtil2.reach = reach;
570
- function marked(systemPrompt, mark) {
571
- return role(systemPrompt).includes(mark);
572
- }
573
- TaHostUtil2.marked = marked;
574
- function role(systemPrompt) {
575
- if (!systemPrompt) {
576
- return "";
577
- }
578
- const open = `<addendum>
579
- `;
580
- const start = systemPrompt.indexOf(open);
581
- const context = systemPrompt.indexOf(`<project_context>
582
- `);
583
- if (start < 0 || context >= 0 && context < start) {
584
- return "";
585
- }
586
- const end = systemPrompt.indexOf(`
587
- </addendum>`, start);
588
- return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
589
- }
590
- TaHostUtil2.role = role;
591
- })(TaHostUtil || (TaHostUtil = {}));
592
- var TA_ASK_ENTRY = "ta-ask";
593
- var TaAskUtil;
594
- (function(TaAskUtil2) {
595
- const LENGTH = 120;
596
- function entry(question) {
597
- const line = question.replace(/\s+/g, " ").trim();
598
- return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
599
- }
600
- TaAskUtil2.entry = entry;
601
- function asking(entries) {
602
- var _a;
603
- for (let i = entries.length - 1;i >= 0; i--) {
604
- const entry2 = entries[i];
605
- if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
606
- return;
607
- }
608
- if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
609
- return read(entry2);
610
- }
611
- }
612
- return;
613
- }
614
- TaAskUtil2.asking = asking;
615
- function next(asked, entry2) {
616
- var _a;
617
- if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
618
- return;
619
- }
620
- return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
621
- }
622
- TaAskUtil2.next = next;
623
- function read(found) {
624
- var _a;
625
- const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
626
- if (typeof question !== "string" || !question.trim()) {
627
- return;
628
- }
629
- const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
630
- return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
631
- }
632
- })(TaAskUtil || (TaAskUtil = {}));
633
- // ../ta-protocol/esm/common/team-protocol.js
634
- var TA_OWNER = "owner";
635
- var TA_UNDECLARED = "extensions.install";
636
- var TaPermissionUtil;
637
- (function(TaPermissionUtil2) {
638
- function read(pi) {
639
- const given = pi === null || pi === undefined ? undefined : pi.permissions;
640
- const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
641
- const host2 = map(given === null || given === undefined ? undefined : given.host);
642
- const tools = map(given === null || given === undefined ? undefined : given.tools);
643
- return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
644
- }
645
- TaPermissionUtil2.read = read;
646
- function host(manifest, method, kind) {
647
- var _a, _b, _c, _d;
648
- const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
649
- const own = (key) => Object.prototype.hasOwnProperty.call(host2, key) ? host2[key] : undefined;
650
- 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;
651
- }
652
- TaPermissionUtil2.host = host;
653
- })(TaPermissionUtil || (TaPermissionUtil = {}));
654
- var action = (id, en, zh, tw, ja, more = {}) => ({
655
- id,
656
- area: id.split(".")[0],
657
- title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
658
- ...more
659
- });
660
- var TA_ACTIONS = [
661
- action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
662
- action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
663
- action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
664
- action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
665
- action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
666
- action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
667
- action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
668
- action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
669
- action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
670
- action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
671
- action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
672
- action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
673
- action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
674
- action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
675
- action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
676
- action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
677
- action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
678
- action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
679
- action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
680
- action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
681
- action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
682
- action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更"),
683
- action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
684
- action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
685
- action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
686
- action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
687
- action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
688
- action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
689
- action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
690
- action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
691
- action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
692
- action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
693
- action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
694
- ];
695
- var TaActionUtil;
696
- (function(TaActionUtil2) {
697
- const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
698
- function info(id) {
699
- return byId.get(id);
700
- }
701
- TaActionUtil2.info = info;
702
- function title(id, language) {
703
- var _a;
704
- var _b, _c;
705
- const title2 = (_a = byId.get(id)) === null || _a === undefined ? undefined : _a.title;
706
- if (!title2) {
707
- return id;
708
- }
709
- return TaLanguageUtil.pick(language, {
710
- "zh-CN": title2["zh-CN"],
711
- "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
712
- "en-US": title2.en,
713
- "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
714
- });
715
- }
716
- TaActionUtil2.title = title;
717
- function inside(dir, path) {
718
- const base = dir.replace(/\/+$/, "");
719
- return path === base || path.startsWith(`${base}/`) || base === "";
720
- }
721
- TaActionUtil2.inside = inside;
722
- })(TaActionUtil || (TaActionUtil = {}));
723
- // ../ta-protocol/esm/common/usage-protocol.js
724
- var TaUsageServer = Symbol("TaUsageServer");
725
- // ../ta-protocol/esm/common/workspace-protocol.js
726
- var TaWorkspaceServer = Symbol("TaWorkspaceServer");
727
- var TaTerminalServer = Symbol("TaTerminalServer");
728
- var TaExcludedFiles;
729
- (function(TaExcludedFiles2) {
730
- TaExcludedFiles2.NAMES = [".git", ".svn", ".hg", ".DS_Store", "Thumbs.db"];
731
- function has(name) {
732
- return TaExcludedFiles2.NAMES.includes(name);
733
- }
734
- TaExcludedFiles2.has = has;
735
- function filter(entries) {
736
- return entries.filter((entry) => !has(entry.name));
737
- }
738
- TaExcludedFiles2.filter = filter;
739
- })(TaExcludedFiles || (TaExcludedFiles = {}));
740
- var TA_UPLOAD_PART_BYTES = 4 * 1024 * 1024;
741
- // ../ta-protocol/esm/common/redactor.js
742
- var REDACTED = "[redacted]";
743
- var WHOLE = [
744
- /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
745
- /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g,
746
- /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,
747
- /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g,
748
- /\bglpat-[A-Za-z0-9_-]{20,}\b/g,
749
- /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g,
750
- /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
751
- /\bAIza[0-9A-Za-z_-]{35}\b/g,
752
- /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g
753
- ];
754
- var NAMED = [
755
- /(\bBearer\s+)[A-Za-z0-9._~+/-]{16,}=*/gi,
756
- /(\b[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)([^\s"'`,;]{6,})/gi,
757
- /(:\/\/[^\s:/@]+:)([^\s@/]{3,})(@)/g
758
- ];
759
-
760
- class Redactor {
761
- constructor() {
762
- this.count = 0;
763
- }
764
- text(text) {
765
- let out = text;
766
- for (const pattern of WHOLE) {
767
- out = out.replace(pattern, () => this.hide());
768
- }
769
- out = out.replace(NAMED[0], (_match, before) => before + this.hide());
770
- out = out.replace(NAMED[1], (match, before, value) => Redactor.placeholder(value) ? match : before + this.hide());
771
- out = out.replace(NAMED[2], (_match, before, _value, after) => before + this.hide() + after);
772
- return out;
773
- }
774
- value(value, max) {
775
- if (typeof value === "string") {
776
- return Redactor.cut(this.text(value), max);
777
- }
778
- if (Array.isArray(value)) {
779
- return value.map((item) => this.value(item, max));
780
- }
781
- if (value && typeof value === "object") {
782
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.value(item, max)]));
783
- }
784
- return value;
477
+ for (const match of text.matchAll(NAMED[1])) {
478
+ if (!Redactor.placeholder(match[2])) {
479
+ const start = match.index + match[1].length;
480
+ const name = (_b = (_a = /[A-Za-z0-9_.-]+/.exec(match[1])) === null || _a === undefined ? undefined : _a[0]) !== null && _b !== undefined ? _b : "SECRET";
481
+ found.push({ start, end: start + match[2].length, kind: name.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase() });
482
+ }
483
+ }
484
+ for (const match of text.matchAll(NAMED[2])) {
485
+ const start = match.index + match[1].length;
486
+ found.push({ start, end: start + match[2].length, kind: "URL_PASSWORD" });
487
+ }
488
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
489
+ const spans = [];
490
+ for (const span of found) {
491
+ const last = spans.at(-1);
492
+ if (!last || span.start >= last.end) {
493
+ spans.push(span);
494
+ }
495
+ }
496
+ return spans;
785
497
  }
786
498
  static cut(text, max) {
787
499
  return text.length > max ? `${text.slice(0, max)}…` : text;
@@ -823,6 +535,255 @@ var RelayAgentCards;
823
535
  RelayAgentCards2.parse = parse;
824
536
  })(RelayAgentCards || (RelayAgentCards = {}));
825
537
 
538
+ // ../ta-relay/esm/common/relay-faces.js
539
+ var FACE_COUNT = 25;
540
+ var BLUE = "#4285F4";
541
+ var RED = "#EA4335";
542
+ var YELLOW = "#FBBC05";
543
+ var GREEN = "#34A853";
544
+ var MINT = "#5CC27F";
545
+ var ORANGE = "#EE7B3B";
546
+ var VIOLET = "#8C5CF0";
547
+ var CREAM = "#F1DFC0";
548
+ var TEAL = "#26B0A9";
549
+ var PINK = "#F27BA6";
550
+ var LILAC = "#B49CF5";
551
+ var SKY = "#45B5E8";
552
+ var INDIGO = "#5C6BC0";
553
+ var MIST = "#DCE3F0";
554
+ var INK = "#202124";
555
+ var WHITE = "#FFFFFF";
556
+ var CHEEK = "rgba(255, 160, 185, 0.55)";
557
+ var EDGE = "rgba(0, 0, 0, 0.14)";
558
+ var CHEEK_DEEP = "rgba(120, 10, 30, 0.35)";
559
+ var CHEEK_WARM = "rgba(234, 67, 53, 0.4)";
560
+ var LOOKS = [
561
+ { color: MINT, eye: "#1D3B27", cheek: CHEEK, eyeY: 21, gap: 8 },
562
+ { color: BLUE, eye: WHITE, cheek: CHEEK, eyeY: 23, gap: 8 },
563
+ { color: RED, eye: WHITE, cheek: CHEEK_DEEP, eyeY: 22, gap: 8 },
564
+ { color: CREAM, eye: "#4A3420", cheek: "rgba(240, 120, 120, 0.5)", accent: "#DDBF8E", eyeY: 22, gap: 7.6 },
565
+ { color: GREEN, eye: WHITE, cheek: CHEEK, eyeY: 19, gap: 7.2 },
566
+ { color: INDIGO, eye: WHITE, cheek: CHEEK, eyeY: 20, gap: 7.4 },
567
+ { color: YELLOW, eye: INK, cheek: CHEEK_WARM, accent: "#F29900", eyeY: 24, gap: 8.4 },
568
+ { color: VIOLET, eye: "#22134A", cheek: CHEEK, eyeY: 20, gap: 8 },
569
+ { color: MIST, eye: "#2B3245", cheek: CHEEK, eyeY: 19, gap: 7.6 },
570
+ { color: SKY, eye: WHITE, cheek: CHEEK, eyeY: 21, gap: 6.4 },
571
+ { color: ORANGE, eye: "#3D1C08", cheek: CHEEK, accent: GREEN, eyeY: 22, gap: 8.6, brows: true },
572
+ { color: WHITE, eye: WHITE, cheek: CHEEK, accent: INK, mouth: INK, eyeY: 22, gap: 10 },
573
+ { color: TEAL, eye: WHITE, cheek: CHEEK, accent: "#1B8A84", eyeY: 22.5, gap: 8.4 },
574
+ { color: PINK, eye: "#4A1428", cheek: "rgba(160, 20, 70, 0.3)", eyeY: 24, gap: 7.4 },
575
+ { color: LILAC, eye: "#2A1A5E", cheek: CHEEK, eyeY: 25, gap: 8 },
576
+ { color: YELLOW, eye: INK, cheek: CHEEK_WARM, eyeY: 25, gap: 7.4 },
577
+ { color: BLUE, eye: WHITE, cheek: CHEEK, eyeY: 19.5, gap: 8 },
578
+ { color: CREAM, eye: "#4A3420", cheek: "rgba(240, 120, 120, 0.5)", eyeY: 23.5, gap: 8 },
579
+ { color: GREEN, eye: WHITE, cheek: CHEEK, eyeY: 21, gap: 8 },
580
+ { color: PINK, eye: "#4A1428", cheek: "rgba(160, 20, 70, 0.3)", eyeY: 19.5, gap: 8.4 },
581
+ { color: RED, eye: WHITE, cheek: CHEEK_DEEP, accent: "#B3261E", eyeY: 20, gap: 8.4 },
582
+ { color: SKY, eye: WHITE, cheek: CHEEK, eyeY: 23.5, gap: 8 },
583
+ { color: VIOLET, eye: WHITE, cheek: CHEEK, accent: "#6B3FD4", eyeY: 22, gap: 8 },
584
+ { color: TEAL, eye: WHITE, cheek: CHEEK, accent: "#1B8A84", eyeY: 25, gap: 7.6 },
585
+ { color: MINT, eye: "#1D3B27", cheek: CHEEK, accent: "#4AAE6C", eyeY: 22.5, gap: 9 }
586
+ ];
587
+ function corners(count, radius, cx, cy, inner) {
588
+ const points = [];
589
+ const steps = inner ? count * 2 : count;
590
+ for (let index = 0;index < steps; index++) {
591
+ const r = inner && index % 2 === 1 ? inner : radius;
592
+ const angle = -Math.PI / 2 + index * 2 * Math.PI / steps;
593
+ points.push(`${(cx + r * Math.cos(angle)).toFixed(2)},${(cy + r * Math.sin(angle)).toFixed(2)}`);
594
+ }
595
+ return points.join(" ");
596
+ }
597
+ var PENTAGON = corners(5, 13.5, 20, 21.5);
598
+ var HEXAGON = corners(6, 14, 20, 20);
599
+ var STAR = corners(5, 15.5, 20, 21.5, 8.6);
600
+ function node(tag, attrs, children) {
601
+ return children ? { tag, attrs, children } : { tag, attrs };
602
+ }
603
+ function rounded(points, color, width = 5) {
604
+ return node("polygon", { points, fill: color, stroke: color, "stroke-width": width, "stroke-linejoin": "round" });
605
+ }
606
+ function shape(face, look) {
607
+ const { color, accent = color } = look;
608
+ switch (face) {
609
+ case 1:
610
+ return node("g", {}, [
611
+ rounded("7.5,6.5 17,12 8.5,18", color, 4),
612
+ rounded("32.5,6.5 23,12 31.5,18", color, 4),
613
+ node("ellipse", { cx: 20, cy: 23, rx: 14.5, ry: 12.5, fill: color })
614
+ ]);
615
+ case 2:
616
+ return rounded(PENTAGON, color);
617
+ case 3:
618
+ return node("g", {}, [
619
+ node("circle", { cx: 9.5, cy: 10.5, r: 5.5, fill: color }),
620
+ node("circle", { cx: 30.5, cy: 10.5, r: 5.5, fill: color }),
621
+ node("circle", { cx: 9.5, cy: 10.5, r: 2.6, fill: accent }),
622
+ node("circle", { cx: 30.5, cy: 10.5, r: 2.6, fill: accent }),
623
+ node("ellipse", { cx: 20, cy: 22.5, rx: 14.5, ry: 13, fill: color })
624
+ ]);
625
+ case 4:
626
+ return node("rect", { x: 8.5, y: 4, width: 23, height: 32, rx: 11.5, fill: color });
627
+ case 5:
628
+ return rounded("20,5.5 34.5,20 20,34.5 5.5,20", color, 5.5);
629
+ case 6:
630
+ return node("g", {}, [
631
+ node("ellipse", { cx: 20, cy: 11, rx: 3.2, ry: 3.6, fill: accent }),
632
+ node("path", { d: "M20 12.5c9.2 0 15.5 5.6 15.5 12.4 0 6.4-6.9 10.1-15.5 10.1S4.5 31.3 4.5 24.9C4.5 18.1 10.8 12.5 20 12.5Z", fill: color })
633
+ ]);
634
+ case 7:
635
+ return rounded(HEXAGON, color);
636
+ case 8:
637
+ return node("path", {
638
+ d: "M8 19a12 12 0 0 1 24 0v14l-4-3-4 3-4-3-4 3-4-3-4 3Z",
639
+ fill: color,
640
+ stroke: EDGE,
641
+ "stroke-width": 0.8,
642
+ "stroke-linejoin": "round"
643
+ });
644
+ case 9:
645
+ return rounded(STAR, color, 4.5);
646
+ case 10:
647
+ return node("g", {}, [
648
+ node("rect", { x: 18.6, y: 4.5, width: 2.8, height: 7, rx: 1.4, fill: accent }),
649
+ node("ellipse", { cx: 12.5, cy: 23, rx: 8.5, ry: 11, fill: color }),
650
+ node("ellipse", { cx: 27.5, cy: 23, rx: 8.5, ry: 11, fill: color }),
651
+ node("ellipse", { cx: 20, cy: 22.5, rx: 9.5, ry: 12, fill: color })
652
+ ]);
653
+ case 11:
654
+ return node("g", {}, [
655
+ node("circle", { cx: 9.5, cy: 10, r: 5, fill: accent }),
656
+ node("circle", { cx: 30.5, cy: 10, r: 5, fill: accent }),
657
+ node("ellipse", { cx: 20, cy: 22.5, rx: 14.5, ry: 13, fill: color, stroke: EDGE, "stroke-width": 0.8 }),
658
+ node("ellipse", { cx: 14.6, cy: 22, rx: 3.6, ry: 4.4, transform: "rotate(20 14.6 22)", fill: accent }),
659
+ node("ellipse", { cx: 25.4, cy: 22, rx: 3.6, ry: 4.4, transform: "rotate(-20 25.4 22)", fill: accent })
660
+ ]);
661
+ case 12:
662
+ return node("g", {}, [
663
+ node("rect", { x: 19.1, y: 6, width: 1.8, height: 7, fill: accent }),
664
+ node("circle", { cx: 20, cy: 5, r: 2.2, fill: accent }),
665
+ node("rect", { x: 5.5, y: 12, width: 29, height: 22.5, rx: 6.5, fill: color })
666
+ ]);
667
+ case 13:
668
+ return node("path", { d: "M20 4.5c2 0 13 11.6 13 20.2 0 6.4-5.8 10.8-13 10.8S7 31.1 7 24.7C7 16.1 18 4.5 20 4.5Z", fill: color });
669
+ case 14:
670
+ return node("g", {}, [
671
+ node("ellipse", { cx: 14, cy: 10.5, rx: 3.6, ry: 8, transform: "rotate(-8 14 10.5)", fill: color }),
672
+ node("ellipse", { cx: 26, cy: 10.5, rx: 3.6, ry: 8, transform: "rotate(8 26 10.5)", fill: color }),
673
+ node("ellipse", { cx: 20, cy: 25, rx: 14, ry: 11, fill: color })
674
+ ]);
675
+ case 15:
676
+ return rounded("20,7 35,33 5,33", color, 6);
677
+ case 16:
678
+ return node("path", {
679
+ d: "M20 6.5l12 4.2v8.4c0 7.4-4.9 12.6-12 15.9-7.1-3.3-12-8.5-12-15.9v-8.4Z",
680
+ fill: color,
681
+ stroke: color,
682
+ "stroke-width": 3,
683
+ "stroke-linejoin": "round"
684
+ });
685
+ case 17:
686
+ return rounded("20,7 32.5,17.5 32.5,33 7.5,33 7.5,17.5", color, 4.5);
687
+ case 18:
688
+ return rounded("14,9 26,9 32.5,32 7.5,32", color, 6);
689
+ case 19:
690
+ return node("rect", { x: 4.5, y: 10.5, width: 31, height: 19.5, rx: 9.75, fill: color });
691
+ case 20:
692
+ return node("g", {}, [
693
+ node("rect", { x: 14, y: 5.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
694
+ node("rect", { x: 14, y: 30.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
695
+ node("ellipse", { cx: 20, cy: 20.25, rx: 15, ry: 12.25, fill: color })
696
+ ]);
697
+ case 21:
698
+ return node("g", {}, [
699
+ node("circle", { cx: 13.5, cy: 21.5, r: 7, fill: color }),
700
+ node("circle", { cx: 21.5, cy: 16.5, r: 9, fill: color }),
701
+ node("circle", { cx: 28.5, cy: 22.5, r: 6.5, fill: color }),
702
+ node("rect", { x: 5.5, y: 21, width: 29, height: 12, rx: 6, fill: color })
703
+ ]);
704
+ case 22:
705
+ return node("g", {}, [
706
+ node("rect", { x: 12.5, y: 5.5, width: 15, height: 5.5, rx: 2, fill: accent }),
707
+ node("rect", { x: 7.5, y: 9.5, width: 25, height: 25.5, rx: 6.5, fill: color })
708
+ ]);
709
+ case 23:
710
+ return node("g", {}, [
711
+ node("rect", { x: 18.8, y: 3.5, width: 2.4, height: 6, rx: 1.2, fill: accent }),
712
+ node("circle", { cx: 20, cy: 13, r: 6.5, fill: color }),
713
+ node("circle", { cx: 20, cy: 25, r: 11.5, fill: color })
714
+ ]);
715
+ case 24:
716
+ return node("g", {}, [
717
+ node("circle", { cx: 12, cy: 13, r: 5.5, fill: color }),
718
+ node("circle", { cx: 28, cy: 13, r: 5.5, fill: color }),
719
+ node("circle", { cx: 12, cy: 13, r: 2.2, fill: accent }),
720
+ node("circle", { cx: 28, cy: 13, r: 2.2, fill: accent }),
721
+ node("ellipse", { cx: 20, cy: 23.5, rx: 15.5, ry: 11.5, fill: color })
722
+ ]);
723
+ default:
724
+ return node("circle", { cx: 20, cy: 21, r: 14.5, fill: color });
725
+ }
726
+ }
727
+ var FaceUtil;
728
+ (function(FaceUtil2) {
729
+ function of(seed) {
730
+ let hash = 0;
731
+ for (const char of seed) {
732
+ hash = hash * 31 + char.charCodeAt(0) | 0;
733
+ }
734
+ return Math.abs(hash) % FACE_COUNT;
735
+ }
736
+ FaceUtil2.of = of;
737
+ function pick(face, seed = "") {
738
+ return face !== undefined && face >= 0 && face < FACE_COUNT ? Math.floor(face) : of(seed);
739
+ }
740
+ FaceUtil2.pick = pick;
741
+ function color(face) {
742
+ var _a;
743
+ return ((_a = LOOKS[face]) !== null && _a !== undefined ? _a : LOOKS[0]).color;
744
+ }
745
+ FaceUtil2.color = color;
746
+ function art(face) {
747
+ var _a, _b;
748
+ const look = (_a = LOOKS[face]) !== null && _a !== undefined ? _a : LOOKS[0];
749
+ const half = look.gap / 2;
750
+ const eyeW = 4.1;
751
+ const eyeH = 4.9;
752
+ const top = look.eyeY - eyeH / 2;
753
+ const cheekY = look.eyeY + 3.6;
754
+ const cheekX = half + 2.2;
755
+ const mouthY = look.eyeY + 3.4;
756
+ const features = [
757
+ node("g", { fill: look.cheek }, [
758
+ node("ellipse", { cx: 20 - cheekX, cy: cheekY, rx: 2.2, ry: 1.25 }),
759
+ node("ellipse", { cx: 20 + cheekX, cy: cheekY, rx: 2.2, ry: 1.25 })
760
+ ])
761
+ ];
762
+ if (look.brows) {
763
+ features.push(node("path", {
764
+ d: `M${20 - half - 3.4} ${top - 2.6}l3.6 1.6M${20 + half + 3.4} ${top - 2.6}l-3.6 1.6`,
765
+ stroke: look.eye,
766
+ "stroke-width": 1.4,
767
+ "stroke-linecap": "round",
768
+ fill: "none"
769
+ }));
770
+ }
771
+ features.push(node("g", { class: "ta-face-eyes", fill: look.eye }, [
772
+ node("rect", { x: 20 - half - eyeW / 2, y: top, width: eyeW, height: eyeH, rx: eyeW / 2 }),
773
+ node("rect", { x: 20 + half - eyeW / 2, y: top, width: eyeW, height: eyeH, rx: eyeW / 2 })
774
+ ]), node("path", {
775
+ d: `M18.1 ${mouthY}q.95 1.25 1.9 0q.95 1.25 1.9 0`,
776
+ fill: "none",
777
+ stroke: (_b = look.mouth) !== null && _b !== undefined ? _b : look.eye,
778
+ "stroke-width": 1.1,
779
+ "stroke-linecap": "round",
780
+ "stroke-linejoin": "round"
781
+ }));
782
+ return node("g", { class: "ta-face-body" }, [shape(face, look), node("g", { class: "ta-face-look" }, features)]);
783
+ }
784
+ FaceUtil2.art = art;
785
+ })(FaceUtil || (FaceUtil = {}));
786
+
826
787
  // web-src/channels-model.ts
827
788
  var NAME = "@celljs/ta-channels";
828
789
  var AGENT_MARK = "one of the agents of Ta";
@@ -846,7 +807,7 @@ var MAX_REPLIES = 8;
846
807
  var MAX_AGENT_REPLIES = 2;
847
808
  var STOP_NOTE = "The agents stopped handing on here, at the limit of a round; it is your turn.";
848
809
  var MAX_MESSAGES = 200;
849
- var FACES = 16;
810
+ var FACES = FACE_COUNT;
850
811
  var MAX_MEMBERS = 12;
851
812
  var CONTEXT_MESSAGES = 12;
852
813
  var MAX_NAME = 32;
@@ -861,18 +822,18 @@ var ChannelsUtil;
861
822
  return { total: 0, byAgent: {}, stopped: false };
862
823
  }
863
824
  ChannelsUtil.newRound = newRound;
864
- function limit(round, targets2, hops) {
825
+ function limit(round, targets, hops) {
865
826
  const allowed = [];
866
827
  const byAgent = { ...round.byAgent };
867
828
  let total = round.total;
868
- for (const id of targets2) {
829
+ for (const id of targets) {
869
830
  if (hops < MAX_HOPS && total < MAX_REPLIES && (byAgent[id] ?? 0) < MAX_AGENT_REPLIES) {
870
831
  allowed.push(id);
871
832
  byAgent[id] = (byAgent[id] ?? 0) + 1;
872
833
  total++;
873
834
  }
874
835
  }
875
- const cut = allowed.length < targets2.length;
836
+ const cut = allowed.length < targets.length;
876
837
  const note = cut && !round.stopped;
877
838
  return { allowed, round: { total, byAgent, stopped: round.stopped || cut }, cut, note };
878
839
  }
@@ -1217,20 +1178,320 @@ var ChannelsUtil;
1217
1178
  }
1218
1179
  return ids;
1219
1180
  }
1220
- function markMentions(text, agents) {
1221
- if (agents.length === 0) {
1222
- return text;
1181
+ function setNotice(team, input) {
1182
+ const before = channelOf(team, input.channel);
1183
+ const text = typeof input.text === "string" ? input.text.replace(/\r\n/g, `
1184
+ `).trim() : "";
1185
+ if (text.length > MAX_NOTICE) {
1186
+ throw new Error(`The notice is too long (${text.length} characters, ${MAX_NOTICE} at most): keep it short, and drop to-dos done long ago.`);
1223
1187
  }
1224
- const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1225
- const pattern = new RegExp(`(?<![*A-Za-z0-9_])@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
1226
- return text.split(/(```[\s\S]*?(?:```|$)|`[^`\n]*`)/).map((part, index) => index % 2 === 1 ? part : part.replace(pattern, "**$&**")).join("");
1227
- }
1228
- ChannelsUtil.markMentions = markMentions;
1229
- function mentions(text, agents) {
1230
- if (agents.length === 0) {
1231
- return [];
1188
+ if (text === (before.notice?.text ?? "")) {
1189
+ return { team, channel: before, before, changed: false };
1232
1190
  }
1233
- const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1191
+ const channel = { ...before };
1192
+ if (text) {
1193
+ channel.notice = { text, at: input.at ?? Date.now(), by: input.by };
1194
+ } else {
1195
+ delete channel.notice;
1196
+ }
1197
+ return { team: { ...team, channels: team.channels.map((other) => other.id === channel.id ? channel : other) }, channel, before, changed: true };
1198
+ }
1199
+ ChannelsUtil.setNotice = setNotice;
1200
+ function append(messages, message) {
1201
+ const next = [...messages, message];
1202
+ return next.length > MAX_MESSAGES ? next.slice(next.length - MAX_MESSAGES) : next;
1203
+ }
1204
+ ChannelsUtil.append = append;
1205
+ })(ChannelsUtil ||= {});
1206
+
1207
+ // web-src/agent-cards.ts
1208
+ var AgentCards;
1209
+ ((AgentCards) => {
1210
+ AgentCards.KIND = RELAY_AGENT_KIND;
1211
+ AgentCards.MARK = "[ta-channels:card]";
1212
+ function card(agent, color) {
1213
+ const redactor = new Redactor;
1214
+ const role = redactor.text(agent.role);
1215
+ return {
1216
+ v: 1,
1217
+ name: agent.name,
1218
+ role,
1219
+ mark: agent.mark,
1220
+ ...agent.face !== undefined ? { face: agent.face } : {},
1221
+ ...color && /^#[0-9a-fA-F]{6}$/.test(color) ? { color } : {},
1222
+ ...redactor.count ? { redacted: redactor.count } : {}
1223
+ };
1224
+ }
1225
+ AgentCards.card = card;
1226
+ function parse(data) {
1227
+ return RelayAgentCards.parse(data);
1228
+ }
1229
+ AgentCards.parse = parse;
1230
+ function freeName(team, name) {
1231
+ const base = (name.trim().replace(/\s+/g, "-") || "agent").slice(0, MAX_NAME - 3);
1232
+ if (!ChannelsUtil.findAgent(team, base)) {
1233
+ return base;
1234
+ }
1235
+ for (let n = 2;; n++) {
1236
+ if (!ChannelsUtil.findAgent(team, `${base}-${n}`)) {
1237
+ return `${base}-${n}`;
1238
+ }
1239
+ }
1240
+ }
1241
+ AgentCards.freeName = freeName;
1242
+ function adapt(cwd, language) {
1243
+ const context = [
1244
+ AgentCards.MARK,
1245
+ `You were just added to this Ta from a card someone shared: the role in your instructions is theirs, written for their own work. Fit it to the project of your directory (${cwd}): look at it first (its README, manifests such as package.json, its layout, how it builds and tests), then rewrite your role for it, keeping what you are for, and save it with update_my_role. Then tell the user, in ${TaLanguageUtil.pick(language, { "zh-CN": "Chinese", "zh-TW": "Traditional Chinese", "en-US": "English", "ja-JP": "Japanese" })}, what you changed and what you can do here. Change no files.`
1246
+ ].join(`
1247
+ `);
1248
+ return TaMessageContext.wrap(context, TaLanguageUtil.pick(language, {
1249
+ "zh-CN": "看看这个项目,把你的职责调整得贴合这里",
1250
+ "zh-TW": "看看這個專案,把你的職責調整得貼合這裡",
1251
+ "en-US": "Look at this project and fit your role to it",
1252
+ "ja-JP": "このプロジェクトを見て、ロールをそれに適応させてください"
1253
+ }));
1254
+ }
1255
+ AgentCards.adapt = adapt;
1256
+ })(AgentCards ||= {});
1257
+
1258
+ // ../ta-protocol/esm/common/said-protocol.js
1259
+ var TaSaid;
1260
+ (function(TaSaid2) {
1261
+ const CARD = /^ta-/i;
1262
+ const READ = 4000;
1263
+ const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)/;
1264
+ const TAG_LINE = /^<\/?[A-Za-z][\w:.-]*(?:\s[^<>]*)?\/?>$/;
1265
+ const MARKS_ONLY = /^[-*_=|:+\s]+$/;
1266
+ const MARKS = [
1267
+ ["context", /<\/?context>/],
1268
+ ["source", /\[ta:(?:from|notice|by) /],
1269
+ ["image note", /\[Image: original \d+x\d+|\[Image converted from /],
1270
+ ["skill", /<skill name="|<\/skill>/],
1271
+ ["task note", /<\/?task_(?:update|adopted|renamed)\b/],
1272
+ ["summary", /<\/?(?:conversation_history_summary|summary)>/]
1273
+ ];
1274
+ function text(content, joiner = `
1275
+ `) {
1276
+ if (typeof content === "string") {
1277
+ return content;
1278
+ }
1279
+ return Array.isArray(content) ? content.filter((part) => (part === null || part === undefined ? undefined : part.type) === "text" && typeof part.text === "string").map((part) => part.text).join(joiner) : "";
1280
+ }
1281
+ TaSaid2.text = text;
1282
+ function words(role, text2, options = {}) {
1283
+ const said = role === "user" ? userWords(text2) : TaAgentSummary.strip(text2);
1284
+ return withoutFences(said, (language) => options.cards === false && CARD.test(language), true).trim();
1285
+ }
1286
+ TaSaid2.words = words;
1287
+ function of(message, options) {
1288
+ return message ? words(message.role, text(message.content), options) : "";
1289
+ }
1290
+ TaSaid2.of = of;
1291
+ function notice(message) {
1292
+ return (message === null || message === undefined ? undefined : message.role) === "user" && TaMessageSource.isNotice(text(message.content));
1293
+ }
1294
+ TaSaid2.notice = notice;
1295
+ function marksOnly(role, text2) {
1296
+ return !!text2.trim() && !line(words(role, text2), { chars: Number.POSITIVE_INFINITY });
1297
+ }
1298
+ TaSaid2.marksOnly = marksOnly;
1299
+ function line(markdown, options) {
1300
+ var _a;
1301
+ const read = markdown.slice(0, READ);
1302
+ const prose = withoutFences(read, () => true, true).trim();
1303
+ const lines = plain(prose || codeOf(read)).split(`
1304
+ `).map((part) => part.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)/, "").replace(/\*{1,3}|`+|~~|(?<![\p{L}\p{N}])_{1,3}|_{1,3}(?![\p{L}\p{N}])/gu, "").replace(/\s+/g, " ").trim()).filter((part) => part && !MARKS_ONLY.test(part) && !TAG_LINE.test(part));
1305
+ const count = (_a = options.lines) !== null && _a !== undefined ? _a : 1;
1306
+ const joined = count <= 1 ? lines.join(" ") : lines.slice(0, count).join(`
1307
+ `);
1308
+ return joined.length > options.chars ? `${joined.slice(0, Math.max(0, options.chars - 1)).trimEnd()}…` : joined;
1309
+ }
1310
+ TaSaid2.line = line;
1311
+ function leaks(shown, options = {}) {
1312
+ const found = MARKS.filter(([, mark]) => mark.test(shown)).map(([name]) => name);
1313
+ const lines = shown.split(`
1314
+ `);
1315
+ if (options.cards !== true && lines.some((part) => {
1316
+ var _a;
1317
+ var _b;
1318
+ return CARD.test((_b = (_a = FENCE.exec(part)) === null || _a === undefined ? undefined : _a[2]) !== null && _b !== undefined ? _b : "");
1319
+ })) {
1320
+ found.push("card");
1321
+ }
1322
+ if (lines.some((part) => TAG_LINE.test(part.trim()))) {
1323
+ found.push("tag");
1324
+ }
1325
+ return found;
1326
+ }
1327
+ TaSaid2.leaks = leaks;
1328
+ const SUMMARY = `<conversation_history_summary>
1329
+ <summary>
1330
+ 1. Primary Request and Intent:
1331
+ The user works on the relay.
1332
+ </summary>
1333
+ </conversation_history_summary>`;
1334
+ TaSaid2.SAMPLES = [
1335
+ {
1336
+ mark: "context and where it came from",
1337
+ role: "user",
1338
+ text: `<context>
1339
+ The channel #ops, its members.
1340
+ [ta:from @celljs/ta-channels #ops]
1341
+ </context>
1342
+ Check the build`,
1343
+ said: "Check the build"
1344
+ },
1345
+ {
1346
+ mark: "a notice, not the user",
1347
+ role: "user",
1348
+ text: `<context>
1349
+ [ta:notice @celljs/ta-call]
1350
+ </context>
1351
+ The work finished. Its last words: tests pass.`,
1352
+ said: "The work finished. Its last words: tests pass."
1353
+ },
1354
+ { mark: "one let in", role: "user", text: `<context>
1355
+ [ta:by p-7 Alice]
1356
+ </context>
1357
+ Hello there`, said: "Hello there" },
1358
+ {
1359
+ mark: "notes of images",
1360
+ role: "user",
1361
+ text: `Look at this
1362
+ [Image: original 3024x4032, displayed at 1512x2016. Multiply coordinates by 2.00 to map to original image.]
1363
+ [Image converted from image/heic to image/png.]`,
1364
+ said: "Look at this"
1365
+ },
1366
+ {
1367
+ mark: "a skill run",
1368
+ role: "user",
1369
+ text: `<skill name="ta-package" location="/skills/ta-package/SKILL.md">
1370
+ # Ta package
1371
+ Steps.
1372
+ </skill>
1373
+
1374
+ Make a card`,
1375
+ said: "Make a card"
1376
+ },
1377
+ {
1378
+ mark: "a note of a task",
1379
+ role: "user",
1380
+ text: `<task_update id="t1" title="Fix login" status="done">
1381
+ All tests pass.
1382
+ </task_update>`,
1383
+ said: "Fix login"
1384
+ },
1385
+ { mark: "a note of a new id", role: "user", text: `<task_renamed id="t2" was="t1" title="Fix login">
1386
+ Now t2.
1387
+ </task_renamed>` },
1388
+ { mark: "a summary, then the answer", role: "assistant", text: `${SUMMARY}
1389
+ Switched to voice.`, said: "Switched to voice." },
1390
+ { mark: "a summary alone", role: "assistant", text: SUMMARY },
1391
+ { mark: "a summary as it streams", role: "assistant", text: `<conversation_history_summary>
1392
+ <summary>` },
1393
+ {
1394
+ mark: "a card after the answer",
1395
+ role: "assistant",
1396
+ text: '**Done**: tests pass.\n\n```ta-glance\n{"status":"done","blocks":[]}\n```',
1397
+ said: "tests pass"
1398
+ },
1399
+ { mark: "a card alone", role: "assistant", text: '```ta-glance\n{"status":"done","blocks":[]}\n```' },
1400
+ { mark: "a proposal", role: "assistant", text: 'Committed.\n\n```ta-propose\n{"kind":"git.push","title":"Push"}\n```', said: "Committed." },
1401
+ { mark: "what a call says aloud", role: "assistant", text: "All fixed.\n\n```ta-say\nIt is fixed.\n```", said: "All fixed." },
1402
+ { mark: "a tag not known yet", role: "assistant", text: `<system-reminder>
1403
+ </system-reminder>
1404
+ Ready.`, said: "Ready." }
1405
+ ];
1406
+ function userWords(text2) {
1407
+ const said = TaImageNote.strip(TaMessageContext.strip(text2));
1408
+ const skill = TaSkillUse.parse(said);
1409
+ if (skill) {
1410
+ return TaSkillUse.command(skill);
1411
+ }
1412
+ const note = TaTaskNote.parse(said);
1413
+ if (!note) {
1414
+ return said;
1415
+ }
1416
+ if (note.kind === "renamed") {
1417
+ return "";
1418
+ }
1419
+ return note.kind === "update" && note.body.trim() ? `${note.title} · ${note.body}` : note.title;
1420
+ }
1421
+ function withoutFences(text2, drop, tags = false) {
1422
+ const kept = [];
1423
+ let fence;
1424
+ let left = false;
1425
+ for (const part of text2.split(`
1426
+ `)) {
1427
+ const open = FENCE.exec(part);
1428
+ if (!fence && open) {
1429
+ fence = { mark: open[1], dropped: drop(open[2]) };
1430
+ } else if (fence && closes(part, fence.mark)) {
1431
+ const dropped = fence.dropped;
1432
+ fence = undefined;
1433
+ if (dropped) {
1434
+ continue;
1435
+ }
1436
+ }
1437
+ if ((fence === null || fence === undefined ? undefined : fence.dropped) || !fence && tags && TAG_LINE.test(part.trim())) {
1438
+ left = true;
1439
+ } else {
1440
+ kept.push(part);
1441
+ }
1442
+ }
1443
+ return left ? kept.join(`
1444
+ `).replace(/\n{3,}/g, `
1445
+
1446
+ `) : kept.join(`
1447
+ `);
1448
+ }
1449
+ function codeOf(text2) {
1450
+ const code = [];
1451
+ let fence;
1452
+ for (const part of text2.split(`
1453
+ `)) {
1454
+ const open = FENCE.exec(part);
1455
+ if (!fence && open) {
1456
+ fence = { mark: open[1], card: CARD.test(open[2]) };
1457
+ } else if (fence && closes(part, fence.mark)) {
1458
+ fence = undefined;
1459
+ } else if (fence && !fence.card) {
1460
+ code.push(part);
1461
+ }
1462
+ }
1463
+ return code.join(`
1464
+ `);
1465
+ }
1466
+ function closes(part, mark) {
1467
+ var _a;
1468
+ const close = (_a = /^\s*(`{3,}|~{3,})\s*$/.exec(part)) === null || _a === undefined ? undefined : _a[1];
1469
+ return !!close && close[0] === mark[0] && close.length >= mark.length;
1470
+ }
1471
+ function plain(text2) {
1472
+ const linked = text2.replace(/(?<!!)\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
1473
+ const words2 = linked.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").trim();
1474
+ return words2 || linked.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
1475
+ }
1476
+ })(TaSaid || (TaSaid = {}));
1477
+
1478
+ // web-src/channels-text.ts
1479
+ var ChannelsText;
1480
+ ((ChannelsText) => {
1481
+ function markMentions(text, agents) {
1482
+ if (agents.length === 0) {
1483
+ return text;
1484
+ }
1485
+ const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1486
+ const pattern = new RegExp(`(?<![*A-Za-z0-9_])@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
1487
+ return text.split(/(```[\s\S]*?(?:```|$)|`[^`\n]*`)/).map((part, index) => index % 2 === 1 ? part : part.replace(pattern, "**$&**")).join("");
1488
+ }
1489
+ ChannelsText.markMentions = markMentions;
1490
+ function mentions(text, agents) {
1491
+ if (agents.length === 0) {
1492
+ return [];
1493
+ }
1494
+ const names = [...agents].sort((a, b) => b.name.length - a.name.length).map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1234
1495
  const pattern = new RegExp(`@(${names.join("|")})(?![A-Za-z0-9_-])`, "gi");
1235
1496
  const found = [];
1236
1497
  for (const match of text.matchAll(pattern)) {
@@ -1241,7 +1502,7 @@ var ChannelsUtil;
1241
1502
  }
1242
1503
  return found;
1243
1504
  }
1244
- ChannelsUtil.mentions = mentions;
1505
+ ChannelsText.mentions = mentions;
1245
1506
  function targets(team, channel, message) {
1246
1507
  const muted = channel.muted ?? [];
1247
1508
  const members = channel.members.filter((id) => !muted.includes(id)).map((id) => team.agents.find((agent) => agent.id === id)).filter((agent) => !!agent);
@@ -1254,7 +1515,7 @@ var ChannelsUtil;
1254
1515
  }
1255
1516
  return members.length > 0 ? [members[0].id] : [];
1256
1517
  }
1257
- ChannelsUtil.targets = targets;
1518
+ ChannelsText.targets = targets;
1258
1519
  function authorName(team, author, labels) {
1259
1520
  if (author === SYSTEM) {
1260
1521
  return "channel";
@@ -1267,37 +1528,18 @@ var ChannelsUtil;
1267
1528
  }
1268
1529
  return team.agents.find((agent) => agent.id === author)?.name ?? author;
1269
1530
  }
1270
- ChannelsUtil.authorName = authorName;
1531
+ ChannelsText.authorName = authorName;
1271
1532
  function systemPrompt(agent) {
1272
1533
  return [
1273
1534
  `You are ${agent.name}, ${AGENT_MARK}. Your role: ${agent.role}`,
1274
1535
  "You work with the user, Ta and other agents in channels. A message for you starts with a <context> block: the channel, its members, the recent messages and who speaks to you; answer what follows the block.",
1275
- "Do the part of the work your role covers with your tools, then answer in a few sentences: your answer is posted to the channel as it is.",
1536
+ "Do the part of the work your role covers with your tools, then answer: your answer is posted to the channel as it is.",
1276
1537
  "To hand work to another member, write @ and their name in your answer; name nobody when the work is done or you need the user.",
1277
1538
  NOTICE_RULE
1278
1539
  ].join(`
1279
1540
  `);
1280
1541
  }
1281
- ChannelsUtil.systemPrompt = systemPrompt;
1282
- function setNotice(team, input) {
1283
- const before = channelOf(team, input.channel);
1284
- const text = typeof input.text === "string" ? input.text.replace(/\r\n/g, `
1285
- `).trim() : "";
1286
- if (text.length > MAX_NOTICE) {
1287
- throw new Error(`The notice is too long (${text.length} characters, ${MAX_NOTICE} at most): keep it short, and drop to-dos done long ago.`);
1288
- }
1289
- if (text === (before.notice?.text ?? "")) {
1290
- return { team, channel: before, before, changed: false };
1291
- }
1292
- const channel = { ...before };
1293
- if (text) {
1294
- channel.notice = { text, at: input.at ?? Date.now(), by: input.by };
1295
- } else {
1296
- delete channel.notice;
1297
- }
1298
- return { team: { ...team, channels: team.channels.map((other) => other.id === channel.id ? channel : other) }, channel, before, changed: true };
1299
- }
1300
- ChannelsUtil.setNotice = setNotice;
1542
+ ChannelsText.systemPrompt = systemPrompt;
1301
1543
  function prompt(team, channel, history, message, agent) {
1302
1544
  const labels = { user: "user", ta: "Ta" };
1303
1545
  const members = channel.members.map((id) => team.agents.find((other) => other.id === id)).filter((other) => !!other).map((other) => `@${other.name}${other.id === agent.id ? " (you)" : ""}: ${firstLine(other.role)}`);
@@ -1310,20 +1552,12 @@ var ChannelsUtil;
1310
1552
  lines.push("", "Recent messages:", ...before.map((item) => `${authorName(team, item.author, labels)}: ${item.text}`));
1311
1553
  }
1312
1554
  lines.push("", `${authorName(team, message.author, labels)} to you:`);
1313
- const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels).replace(/[\]\n]/g, " ")}`;
1314
- lines.push(`[ta:from ${NAME} #${channel.name}${speaker}]`);
1315
- return `<context>
1316
- ${lines.join(`
1317
- `)}
1318
- </context>
1319
- ${message.text}`;
1320
- }
1321
- ChannelsUtil.prompt = prompt;
1322
- function append(messages, message) {
1323
- const next = [...messages, message];
1324
- return next.length > MAX_MESSAGES ? next.slice(next.length - MAX_MESSAGES) : next;
1555
+ const speaker = message.author === USER ? "" : ` · ${authorName(team, message.author, labels)}`;
1556
+ lines.push(TaMessageSource.line(NAME, `#${channel.name}${speaker}`));
1557
+ return TaMessageContext.wrap(lines.join(`
1558
+ `), message.text);
1325
1559
  }
1326
- ChannelsUtil.append = append;
1560
+ ChannelsText.prompt = prompt;
1327
1561
  function summary(team) {
1328
1562
  if (team.agents.length === 0) {
1329
1563
  return "No agents and no channels yet.";
@@ -1335,14 +1569,14 @@ ${message.text}`;
1335
1569
  return ["Agents:", ...agents, "", "Channels:", ...channels.length > 0 ? channels : ["none yet"]].join(`
1336
1570
  `);
1337
1571
  }
1338
- ChannelsUtil.summary = summary;
1572
+ ChannelsText.summary = summary;
1339
1573
  function transcript(team, messages) {
1340
1574
  const labels = { user: "user", ta: "Ta" };
1341
1575
  return messages.map((item) => `${authorName(team, item.author, labels)}${item.failed ? " (failed)" : ""}: ${item.text}`).join(`
1342
1576
 
1343
1577
  `);
1344
1578
  }
1345
- ChannelsUtil.transcript = transcript;
1579
+ ChannelsText.transcript = transcript;
1346
1580
  function markdown(agent, messages, labels) {
1347
1581
  const parts = [`# ${agent.name}`, "", `> ${firstLine(agent.role)}`];
1348
1582
  for (const message of messages) {
@@ -1350,7 +1584,7 @@ ${message.text}`;
1350
1584
  if (role !== "user" && role !== "assistant") {
1351
1585
  continue;
1352
1586
  }
1353
- const text = (typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => block?.type === "text" ? String(block.text ?? "") : "").join("") : "").replace(/^<context>\n?[\s\S]*?\n?<\/context>\n?/, "").trim();
1587
+ const text = TaSaid.words(role, TaSaid.text(content, ""));
1354
1588
  if (text) {
1355
1589
  parts.push("", `## ${role === "user" ? labels.user : agent.name}`, "", text);
1356
1590
  }
@@ -1359,7 +1593,7 @@ ${message.text}`;
1359
1593
  `)}
1360
1594
  `;
1361
1595
  }
1362
- ChannelsUtil.markdown = markdown;
1596
+ ChannelsText.markdown = markdown;
1363
1597
  function channelMarkdown(team, channel, messages, labels) {
1364
1598
  const parts = [`# #${channel.name}`];
1365
1599
  if (channel.topic) {
@@ -1375,111 +1609,17 @@ ${message.text}`;
1375
1609
  `)}
1376
1610
  `;
1377
1611
  }
1378
- ChannelsUtil.channelMarkdown = channelMarkdown;
1612
+ ChannelsText.channelMarkdown = channelMarkdown;
1379
1613
  function firstLine(text) {
1380
1614
  return text.split(`
1381
1615
  `)[0];
1382
1616
  }
1383
- })(ChannelsUtil ||= {});
1617
+ })(ChannelsText ||= {});
1384
1618
  var NOTICE_RULE = [
1385
1619
  "A channel may have a notice, in the <context> block: what its members decided, agreed and are to do. Follow it.",
1386
1620
  `When the talk settles a decision or a convention, or adds, assigns or finishes a to-do, update it with update_channel_notice: the whole notice, short, under the headings ### ${NOTICE_HEADINGS.zh.join(" / ")} (### ${NOTICE_HEADINGS.en.join(" / ")} in English), in the language of the channel, to-dos as - [ ] or - [x] with who does them. The lead keeps it most; leave it for small talk.`
1387
1621
  ].join(`
1388
1622
  `);
1389
- var NoticeUtil;
1390
- ((NoticeUtil) => {
1391
- const PARTS = {
1392
- 决定: "decisions",
1393
- decisions: "decisions",
1394
- 约定: "conventions",
1395
- conventions: "conventions",
1396
- 待办: "todo",
1397
- "to do": "todo",
1398
- todo: "todo",
1399
- "to-do": "todo"
1400
- };
1401
- function counts(text) {
1402
- const counts2 = { decisions: 0, conventions: 0, todo: 0, done: 0 };
1403
- let part;
1404
- for (const line of text.split(/\r?\n/)) {
1405
- const heading = /^\s*#{1,6}\s+(.+?)\s*#*\s*$/.exec(line) ?? /^\s*\*\*(.+?)\*\*\s*[::]?\s*$/.exec(line);
1406
- if (heading) {
1407
- part = PARTS[heading[1].replace(/[::]$/, "").trim().toLowerCase()];
1408
- continue;
1409
- }
1410
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(\[( |x|X)\]\s+)?\S/.exec(line);
1411
- if (!part || !item) {
1412
- continue;
1413
- }
1414
- if (part === "todo" && item[2] && item[2] !== " ") {
1415
- counts2.done++;
1416
- } else {
1417
- counts2[part]++;
1418
- }
1419
- }
1420
- return counts2;
1421
- }
1422
- NoticeUtil.counts = counts;
1423
- function firstLine(text) {
1424
- for (const line of text.split(/\r?\n/)) {
1425
- const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(line);
1426
- if (item) {
1427
- return item[1].replace(/[*_`~]+/g, "").trim();
1428
- }
1429
- }
1430
- return text.split(/\r?\n/).find((line) => line.trim() && !/^\s*#/.test(line))?.trim() ?? "";
1431
- }
1432
- NoticeUtil.firstLine = firstLine;
1433
- })(NoticeUtil ||= {});
1434
-
1435
- // web-src/agent-cards.ts
1436
- var AgentCards;
1437
- ((AgentCards) => {
1438
- AgentCards.KIND = RELAY_AGENT_KIND;
1439
- AgentCards.MARK = "[ta-channels:card]";
1440
- function card(agent, color) {
1441
- const redactor = new Redactor;
1442
- const role = redactor.text(agent.role);
1443
- return {
1444
- v: 1,
1445
- name: agent.name,
1446
- role,
1447
- mark: agent.mark,
1448
- ...agent.face !== undefined ? { face: agent.face } : {},
1449
- ...color && /^#[0-9a-fA-F]{6}$/.test(color) ? { color } : {},
1450
- ...redactor.count ? { redacted: redactor.count } : {}
1451
- };
1452
- }
1453
- AgentCards.card = card;
1454
- function parse(data) {
1455
- return RelayAgentCards.parse(data);
1456
- }
1457
- AgentCards.parse = parse;
1458
- function freeName(team, name) {
1459
- const base = (name.trim().replace(/\s+/g, "-") || "agent").slice(0, MAX_NAME - 3);
1460
- if (!ChannelsUtil.findAgent(team, base)) {
1461
- return base;
1462
- }
1463
- for (let n = 2;; n++) {
1464
- if (!ChannelsUtil.findAgent(team, `${base}-${n}`)) {
1465
- return `${base}-${n}`;
1466
- }
1467
- }
1468
- }
1469
- AgentCards.freeName = freeName;
1470
- function adapt(cwd, language2) {
1471
- const context = [
1472
- AgentCards.MARK,
1473
- `You were just added to this Ta from a card someone shared: the role in your instructions is theirs, written for their own work. Fit it to the project of your directory (${cwd}): look at it first (its README, manifests such as package.json, its layout, how it builds and tests), then rewrite your role for it, keeping what you are for, and save it with update_my_role. Then tell the user in a few sentences, in ${TaLanguageUtil.pick(language2, { "zh-CN": "Chinese", "zh-TW": "Traditional Chinese", "en-US": "English", "ja-JP": "Japanese" })}, what you changed and what you can do here. Change no files.`
1474
- ].join(`
1475
- `);
1476
- return `<context>
1477
- ${context}
1478
- </context>
1479
- ${TaLanguageUtil.pick(language2, { "zh-CN": "看看这个项目,把你的职责调整得贴合这里", "zh-TW": "看看這個專案,把你的職責調整得貼合這裡", "en-US": "Look at this project and fit your role to it", "ja-JP": "このプロジェクトを見て、ロールをそれに適応させてください" })}`;
1480
- }
1481
- AgentCards.adapt = adapt;
1482
- })(AgentCards ||= {});
1483
1623
 
1484
1624
  // web-src/handoff.ts
1485
1625
  var HandOff;
@@ -1506,7 +1646,7 @@ var HandOff;
1506
1646
  return `${target.kind === "agent" ? "@" : "#"}${target.name}`;
1507
1647
  }
1508
1648
  HandOff.ref = ref;
1509
- function ask(language2, to) {
1649
+ function ask(language, to) {
1510
1650
  const fence = "```";
1511
1651
  const context = [
1512
1652
  `[ta-handoff:${to}]`,
@@ -1520,16 +1660,13 @@ var HandOff;
1520
1660
  `- When the conversation holds nothing to hand over yet, say so and ask what ${to} should do.`
1521
1661
  ].join(`
1522
1662
  `);
1523
- const line = TaLanguageUtil.pick(language2, {
1663
+ const line = TaLanguageUtil.pick(language, {
1524
1664
  "zh-CN": `把这件事交给 ${to}`,
1525
1665
  "zh-TW": `把這件事交給 ${to}`,
1526
1666
  "en-US": `Hand this over to ${to}`,
1527
1667
  "ja-JP": `これを ${to} に引き継ぐ`
1528
1668
  });
1529
- return `<context>
1530
- ${context}
1531
- </context>
1532
- ${line}`;
1669
+ return TaMessageContext.wrap(context, line);
1533
1670
  }
1534
1671
  HandOff.ask = ask;
1535
1672
  function asked(text) {
@@ -1554,9 +1691,9 @@ ${line}`;
1554
1691
  return brief || undefined;
1555
1692
  }
1556
1693
  HandOff.find = find;
1557
- function message(origin, brief, language2) {
1558
- const title = origin.title?.trim() || TaLanguageUtil.pick(language2, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
1559
- const head = TaLanguageUtil.pick(language2, {
1694
+ function message(origin, brief, language) {
1695
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
1696
+ const head = TaLanguageUtil.pick(language, {
1560
1697
  "zh-CN": `(交接自“${title}”)`,
1561
1698
  "zh-TW": `(交接自「${title}」)`,
1562
1699
  "en-US": `(Handed over from “${title}”)`,
@@ -1567,17 +1704,14 @@ ${line}`;
1567
1704
  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.` : ""
1568
1705
  ].filter(Boolean).join(`
1569
1706
  `);
1570
- return `<context>
1571
- ${context}
1572
- </context>
1573
- ${head}
1707
+ return TaMessageContext.wrap(context, `${head}
1574
1708
 
1575
- ${brief.trim()}`;
1709
+ ${brief.trim()}`);
1576
1710
  }
1577
1711
  HandOff.message = message;
1578
- function channelText(origin, brief, language2) {
1579
- const title = origin.title?.trim() || TaLanguageUtil.pick(language2, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
1580
- return `${TaLanguageUtil.pick(language2, {
1712
+ function channelText(origin, brief, language) {
1713
+ const title = origin.title?.trim() || TaLanguageUtil.pick(language, { "zh-CN": "一个对话", "zh-TW": "一個對話", "en-US": "a conversation", "ja-JP": "ある会話" });
1714
+ return `${TaLanguageUtil.pick(language, {
1581
1715
  "zh-CN": `(交接自“${title}”)`,
1582
1716
  "zh-TW": `(交接自「${title}」)`,
1583
1717
  "en-US": `(Handed over from “${title}”)`,
@@ -1597,65 +1731,1315 @@ ${brief.trim()}`;
1597
1731
  HandOff.result = result;
1598
1732
  })(HandOff ||= {});
1599
1733
 
1600
- // web-src/team-view.ts
1601
- var TeamViewUtil;
1602
- ((TeamViewUtil) => {
1603
- function visible(team2, can) {
1604
- const channels = new Set(team2.channels.filter((channel) => can("channel", channel.id)).map((channel) => channel.id));
1605
- const agents = new Set(team2.agents.filter((agent) => can("agent", agent.id)).map((agent) => agent.id));
1606
- for (const channel of team2.channels) {
1607
- if (channels.has(channel.id)) {
1608
- for (const member of channel.members) {
1609
- agents.add(member);
1734
+ // ../ta-protocol/esm/common/access-protocol.js
1735
+ var TaAccessServer = Symbol("TaAccessServer");
1736
+ var TA_SIGN_IN_PATH = "/sign-in";
1737
+ var TA_DEVICE_SIGN_IN_PATH = `${TA_SIGN_IN_PATH}/device`;
1738
+ // ../ta-protocol/esm/common/ta-extension-host.js
1739
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
1740
+ var TA_HOST_EVENT = "ta:host";
1741
+ var TaHostUtil;
1742
+ (function(TaHostUtil2) {
1743
+ TaHostUtil2.WAIT_MS = 1000;
1744
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
1745
+ return new Promise((resolve) => {
1746
+ let heard = false;
1747
+ let answered = false;
1748
+ const timer = setTimeout(() => resolve(undefined), waitMs);
1749
+ const request = {
1750
+ name,
1751
+ heard: () => {
1752
+ heard = true;
1753
+ },
1754
+ resolve: (answer) => {
1755
+ answered = true;
1756
+ clearTimeout(timer);
1757
+ resolve(answer);
1758
+ }
1759
+ };
1760
+ events.emit(TA_HOST_EVENT, request);
1761
+ if (!heard && !answered) {
1762
+ clearTimeout(timer);
1763
+ resolve(undefined);
1764
+ }
1765
+ });
1766
+ }
1767
+ TaHostUtil2.reach = reach;
1768
+ function marked(systemPrompt, mark) {
1769
+ return role(systemPrompt).includes(mark);
1770
+ }
1771
+ TaHostUtil2.marked = marked;
1772
+ function role(systemPrompt) {
1773
+ if (!systemPrompt) {
1774
+ return "";
1775
+ }
1776
+ const open = `<addendum>
1777
+ `;
1778
+ const start = systemPrompt.indexOf(open);
1779
+ const context = systemPrompt.indexOf(`<project_context>
1780
+ `);
1781
+ if (start < 0 || context >= 0 && context < start) {
1782
+ return "";
1783
+ }
1784
+ const end = systemPrompt.indexOf(`
1785
+ </addendum>`, start);
1786
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
1787
+ }
1788
+ TaHostUtil2.role = role;
1789
+ })(TaHostUtil || (TaHostUtil = {}));
1790
+ var TA_ASK_ENTRY = "ta-ask";
1791
+ var TaAskUtil;
1792
+ (function(TaAskUtil2) {
1793
+ const LENGTH = 120;
1794
+ function entry(question) {
1795
+ const line = question.replace(/\s+/g, " ").trim();
1796
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
1797
+ }
1798
+ TaAskUtil2.entry = entry;
1799
+ function asking(entries) {
1800
+ var _a;
1801
+ for (let i = entries.length - 1;i >= 0; i--) {
1802
+ const entry2 = entries[i];
1803
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
1804
+ return;
1805
+ }
1806
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
1807
+ return read(entry2);
1808
+ }
1809
+ }
1810
+ return;
1811
+ }
1812
+ TaAskUtil2.asking = asking;
1813
+ function next(asked, entry2) {
1814
+ var _a;
1815
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
1816
+ return;
1817
+ }
1818
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
1819
+ }
1820
+ TaAskUtil2.next = next;
1821
+ function read(found) {
1822
+ var _a;
1823
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
1824
+ if (typeof question !== "string" || !question.trim()) {
1825
+ return;
1826
+ }
1827
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
1828
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
1829
+ }
1830
+ })(TaAskUtil || (TaAskUtil = {}));
1831
+
1832
+ // ../ta-protocol/esm/common/delegate-protocol.js
1833
+ var TaDelegateUtil;
1834
+ (function(TaDelegateUtil2) {
1835
+ TaDelegateUtil2.LEVELS = ["less", "balanced", "more"];
1836
+ TaDelegateUtil2.DEFAULT = "balanced";
1837
+ TaDelegateUtil2.WORK_TOOLS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
1838
+ TaDelegateUtil2.CHANGE_TOOLS = ["edit", "write"];
1839
+ const LIMITS = {
1840
+ less: { noChanges: false },
1841
+ balanced: { noChanges: true, steps: 6 },
1842
+ more: { noChanges: true, steps: 2 }
1843
+ };
1844
+ function parse(value) {
1845
+ return TaDelegateUtil2.LEVELS.includes(value) ? value : TaDelegateUtil2.DEFAULT;
1846
+ }
1847
+ TaDelegateUtil2.parse = parse;
1848
+ function mark(level) {
1849
+ return `(delegate=${level})`;
1850
+ }
1851
+ TaDelegateUtil2.mark = mark;
1852
+ function levelOf(systemPrompt) {
1853
+ const role = TaHostUtil.role(systemPrompt);
1854
+ return TaDelegateUtil2.LEVELS.find((level) => role.includes(mark(level)));
1855
+ }
1856
+ TaDelegateUtil2.levelOf = levelOf;
1857
+ function limits(level) {
1858
+ return LIMITS[level];
1859
+ }
1860
+ TaDelegateUtil2.limits = limits;
1861
+ function refusal(level, tool, steps) {
1862
+ if (!TaDelegateUtil2.WORK_TOOLS.includes(tool)) {
1863
+ return;
1864
+ }
1865
+ const limit = LIMITS[level];
1866
+ if (limit.noChanges && TaDelegateUtil2.CHANGE_TOOLS.includes(tool)) {
1867
+ return "You do not change files yourself: hand this to a task with start_task, with instructions complete enough to do it. The user set how much you hand out in the settings of the double.";
1868
+ }
1869
+ if (limit.steps !== undefined && steps >= limit.steps) {
1870
+ return "You have looked enough for this: hand the work to a task with start_task now, with what you found in its instructions, and tell the user what you started.";
1871
+ }
1872
+ return;
1873
+ }
1874
+ TaDelegateUtil2.refusal = refusal;
1875
+ })(TaDelegateUtil || (TaDelegateUtil = {}));
1876
+
1877
+ // ../ta-protocol/esm/common/app-protocol.js
1878
+ var FONT_SIZES = ["small", "standard", "large", "xlarge"];
1879
+ var words = (en, zh, tw, ja) => ({ "en-US": en, "zh-CN": zh, "zh-TW": tw, "ja-JP": ja });
1880
+ var SYSTEM2 = words("as the system", "跟随系统", "跟隨系統", "システムに合わせる");
1881
+ var FONT_SHOWN = {
1882
+ small: words("small", "小", "小", "小"),
1883
+ standard: words("standard", "标准", "標準", "標準"),
1884
+ large: words("large", "大", "大", "大"),
1885
+ xlarge: words("extra large", "特大", "特大", "特大")
1886
+ };
1887
+ var TA_WEB_SETTINGS = [
1888
+ {
1889
+ key: "theme",
1890
+ type: "enum",
1891
+ values: ["system", "light", "dark"],
1892
+ default: "system",
1893
+ what: "Light or dark look; system follows the device.",
1894
+ title: words("Theme", "外观", "外觀", "外観"),
1895
+ shown: { system: SYSTEM2, light: words("light", "浅色", "淺色", "ライト"), dark: words("dark", "深色", "深色", "ダーク") }
1896
+ },
1897
+ {
1898
+ key: "language",
1899
+ type: "enum",
1900
+ values: ["system", ...TaLanguageUtil.ALL],
1901
+ default: "system",
1902
+ what: "The language of Ta's pages and of what Ta says; system follows the device.",
1903
+ title: words("Language", "语言", "語言", "言語"),
1904
+ shown: {
1905
+ system: SYSTEM2,
1906
+ ...Object.fromEntries(TaLanguageUtil.ALL.map((language) => [
1907
+ language,
1908
+ words(TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language])
1909
+ ]))
1910
+ }
1911
+ },
1912
+ {
1913
+ key: "fontSize",
1914
+ type: "enum",
1915
+ values: FONT_SIZES,
1916
+ default: "standard",
1917
+ what: "The size of the text of the whole page.",
1918
+ title: words("Text size", "字体大小", "字型大小", "文字サイズ"),
1919
+ shown: FONT_SHOWN
1920
+ },
1921
+ {
1922
+ key: "chatFontSize",
1923
+ type: "enum",
1924
+ values: FONT_SIZES,
1925
+ default: "standard",
1926
+ what: "The size of the text of conversations, on top of fontSize.",
1927
+ title: words("Text size of conversations", "对话字体大小", "對話字型大小", "会話の文字サイズ"),
1928
+ shown: FONT_SHOWN
1929
+ },
1930
+ {
1931
+ key: "speak",
1932
+ type: "boolean",
1933
+ default: false,
1934
+ what: "Read every reply aloud.",
1935
+ title: words("Read replies aloud", "朗读回复", "朗讀回覆", "返信を読み上げ")
1936
+ },
1937
+ {
1938
+ key: "speakTalk",
1939
+ type: "boolean",
1940
+ default: false,
1941
+ what: "Read the reply aloud when the user spoke to the double by voice.",
1942
+ title: words("Read aloud what was asked by voice", "语音提问时朗读回复", "語音提問時朗讀回覆", "音声で聞いたら読み上げ")
1943
+ },
1944
+ {
1945
+ key: "callCaptions",
1946
+ type: "boolean",
1947
+ default: false,
1948
+ what: "Show captions in a call: what the user says and what Ta reads.",
1949
+ title: words("Call captions", "通话字幕", "通話字幕", "通話の字幕")
1950
+ },
1951
+ {
1952
+ key: "voice",
1953
+ type: "string",
1954
+ default: "",
1955
+ what: "The voice replies are read with (a voiceURI of the device's voices); empty for the most natural one.",
1956
+ title: words("Voice", "朗读声音", "朗讀聲音", "読み上げの声")
1957
+ },
1958
+ {
1959
+ key: "confirmTasks",
1960
+ type: "boolean",
1961
+ default: false,
1962
+ what: "The double asks before it hands out work.",
1963
+ title: words("Ask before handing out work", "派任务前先问我", "派任務前先問我", "作業を割り当てる前に確認")
1964
+ },
1965
+ {
1966
+ key: "maxTasks",
1967
+ type: "number",
1968
+ values: [0, 2, 4, 8],
1969
+ default: 0,
1970
+ what: "How many of the double's tasks run at once; 0 for as many as it starts.",
1971
+ title: words("Tasks at once", "同时运行的任务", "同時執行的任務", "同時に実行するタスク")
1972
+ },
1973
+ {
1974
+ key: "delegate",
1975
+ type: "enum",
1976
+ values: TaDelegateUtil.LEVELS,
1977
+ default: TaDelegateUtil.DEFAULT,
1978
+ what: "How much of the work the double hands out to tasks rather than doing it itself.",
1979
+ title: words("Hand out work", "派活多少", "派活多少", "作業の割り当て"),
1980
+ shown: { less: words("less", "少", "少", "少なめ"), balanced: words("balanced", "适中", "適中", "ふつう"), more: words("more", "多", "多", "多め") }
1981
+ },
1982
+ {
1983
+ key: "assistantModel",
1984
+ type: "model",
1985
+ default: "",
1986
+ what: "The model of the double, <provider>/<model id>; empty for the default model.",
1987
+ title: words("Model of the double", "分身的模型", "分身的模型", "分身のモデル")
1988
+ },
1989
+ {
1990
+ key: "taskModel",
1991
+ type: "model",
1992
+ default: "",
1993
+ what: "The model of the tasks the double starts; empty for the default model.",
1994
+ title: words("Model of tasks", "任务的模型", "任務的模型", "タスクのモデル")
1995
+ },
1996
+ { key: "reduceMotion", type: "boolean", default: false, what: "Fewer animations.", title: words("Reduce motion", "减少动画", "減少動畫", "動きを減らす") },
1997
+ {
1998
+ key: "diagramStyle",
1999
+ type: "enum",
2000
+ values: ["clean", "sketch", "colour", "motion"],
2001
+ default: "clean",
2002
+ what: "How diagrams in replies draw: in the colours of the page, as by hand, a colour to a node, or coming in with flowing lines.",
2003
+ title: words("Diagram style", "图表风格", "圖表風格", "図のスタイル"),
2004
+ shown: {
2005
+ clean: words("clean", "简洁", "簡潔", "シンプル"),
2006
+ sketch: words("sketch", "草图", "草圖", "スケッチ"),
2007
+ colour: words("colour", "彩色", "彩色", "カラー"),
2008
+ motion: words("motion", "动效", "動效", "モーション")
2009
+ }
2010
+ },
2011
+ {
2012
+ key: "keepAliveMinutes",
2013
+ type: "number",
2014
+ values: [1, 5, 15, 30],
2015
+ default: 5,
2016
+ what: "How long an extension started on open keeps running once left, in minutes.",
2017
+ title: words("Keep extensions running", "扩展离开后保留", "擴充功能離開後保留", "拡張機能を保持")
2018
+ },
2019
+ {
2020
+ key: "chatFoldDays",
2021
+ type: "number",
2022
+ values: [3, 7, 30, 0],
2023
+ default: 7,
2024
+ what: "Conversations not updated for these days fold at the end of the list; 0 for none.",
2025
+ title: words("Fold old conversations", "折叠旧对话", "摺疊舊對話", "古い会話を折りたたむ")
2026
+ },
2027
+ {
2028
+ key: "chatArchiveDays",
2029
+ type: "number",
2030
+ values: [30, 90, 365, 0],
2031
+ default: 30,
2032
+ what: "Conversations not updated for these days are archived (out of the list, found by search); 0 for none.",
2033
+ title: words("Archive old conversations", "归档旧对话", "歸檔舊對話", "古い会話をアーカイブ")
2034
+ },
2035
+ {
2036
+ key: "recentShots",
2037
+ type: "boolean",
2038
+ default: true,
2039
+ what: "The screenshot just taken is offered above the message box, once.",
2040
+ title: words("Offer recent screenshots", "提示刚截的图", "提示剛截的圖", "撮ったばかりのスクリーンショットを提案")
2041
+ }
2042
+ ];
2043
+ var TaAppUtil;
2044
+ (function(TaAppUtil2) {
2045
+ function check(spec, value) {
2046
+ var _a, _b;
2047
+ switch (spec.type) {
2048
+ case "boolean":
2049
+ return typeof value === "boolean" ? undefined : "true or false";
2050
+ case "string":
2051
+ return typeof value === "string" ? undefined : "a string";
2052
+ case "model":
2053
+ return value === "" || typeof value === "string" && /^[^/\s]+\/\S+$/.test(value) ? undefined : "<provider>/<model id>, or empty";
2054
+ default:
2055
+ return ((_a = spec.values) === null || _a === undefined ? undefined : _a.includes(value)) ? undefined : `one of ${(_b = spec.values) === null || _b === undefined ? undefined : _b.map((one) => JSON.stringify(one)).join(", ")}`;
2056
+ }
2057
+ }
2058
+ TaAppUtil2.check = check;
2059
+ function shown(value, language, spec) {
2060
+ var _a;
2061
+ const named = (_a = spec === null || spec === undefined ? undefined : spec.shown) === null || _a === undefined ? undefined : _a[String(value)];
2062
+ if (named) {
2063
+ return TaLanguageUtil.pick(language, named);
2064
+ }
2065
+ if (typeof value === "boolean") {
2066
+ return TaLanguageUtil.pick(language, value ? words("on", "开", "開", "オン") : words("off", "关", "關", "オフ"));
2067
+ }
2068
+ if (value === "" || value === undefined || value === null) {
2069
+ return TaLanguageUtil.pick(language, words("default", "默认", "預設", "デフォルト"));
2070
+ }
2071
+ return String(value);
2072
+ }
2073
+ TaAppUtil2.shown = shown;
2074
+ })(TaAppUtil || (TaAppUtil = {}));
2075
+ // ../ta-protocol/esm/common/auth-protocol.js
2076
+ var TaAuthServer = Symbol("TaAuthServer");
2077
+ // ../ta-protocol/esm/common/deployment-protocol.js
2078
+ var TA_WELL_KNOWN_PATH = "/.well-known/ta";
2079
+
2080
+ class TaDeploymentError extends Error {
2081
+ }
2082
+ var TaDeploymentUtil;
2083
+ (function(TaDeploymentUtil2) {
2084
+ TaDeploymentUtil2.DISTRIBUTION_FILE = "distribution.json";
2085
+ function url(value) {
2086
+ if (typeof value !== "string" || !value.trim()) {
2087
+ return;
2088
+ }
2089
+ try {
2090
+ const parsed = new URL(value.trim());
2091
+ if (!/^https?:$/.test(parsed.protocol) || parsed.search || parsed.hash || parsed.username || parsed.password) {
2092
+ return;
2093
+ }
2094
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, "");
2095
+ } catch (_a) {
2096
+ return;
2097
+ }
2098
+ }
2099
+ TaDeploymentUtil2.url = url;
2100
+ function name(value) {
2101
+ return typeof value === "string" && value.trim() ? value.trim().slice(0, 80) : undefined;
2102
+ }
2103
+ function describe(env, own, version) {
2104
+ var _a, _b;
2105
+ const gateway = (_a = url(own.gateway)) !== null && _a !== undefined ? _a : url(env.TA_GATEWAY_URL);
2106
+ const relay = (_b = url(own.relay)) !== null && _b !== undefined ? _b : url(env.TA_RELAY_URL);
2107
+ const called = name(env.TA_DEPLOYMENT_NAME);
2108
+ return { v: 1, ...called ? { name: called } : {}, ...gateway ? { gateway } : {}, ...relay ? { relay } : {}, ...version ? { version } : {} };
2109
+ }
2110
+ TaDeploymentUtil2.describe = describe;
2111
+ TaDeploymentUtil2.HEADERS = {
2112
+ "content-type": "application/json",
2113
+ "access-control-allow-origin": "*",
2114
+ "cache-control": "no-store"
2115
+ };
2116
+ function parse(value) {
2117
+ const given = value;
2118
+ if (!given || typeof given !== "object" || given.v !== 1) {
2119
+ return;
2120
+ }
2121
+ const deployment = describe({ TA_DEPLOYMENT_NAME: given.name, TA_GATEWAY_URL: given.gateway, TA_RELAY_URL: given.relay }, {});
2122
+ const version = name(given.version);
2123
+ return version ? { ...deployment, version } : deployment;
2124
+ }
2125
+ TaDeploymentUtil2.parse = parse;
2126
+ async function discover(address, timeoutMs = 6000) {
2127
+ const base = url(address);
2128
+ if (!base) {
2129
+ throw new TaDeploymentError(`${address} is not an address of http or https.`);
2130
+ }
2131
+ const controller = new AbortController;
2132
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2133
+ try {
2134
+ const response = await fetch(`${base}${TA_WELL_KNOWN_PATH}`, { signal: controller.signal, redirect: "follow" });
2135
+ if (!response.ok) {
2136
+ throw new TaDeploymentError(`${base} is not a deployment of Ta (${response.status}).`);
2137
+ }
2138
+ const deployment = parse(await response.json().catch(() => {
2139
+ return;
2140
+ }));
2141
+ if (!deployment || !deployment.gateway && !deployment.relay) {
2142
+ throw new TaDeploymentError(`${base} is not a deployment of Ta.`);
2143
+ }
2144
+ return deployment;
2145
+ } catch (error) {
2146
+ if ((error === null || error === undefined ? undefined : error.name) === "AbortError") {
2147
+ throw new TaDeploymentError(`${base} did not answer in time.`);
2148
+ }
2149
+ throw error;
2150
+ } finally {
2151
+ clearTimeout(timer);
2152
+ }
2153
+ }
2154
+ TaDeploymentUtil2.discover = discover;
2155
+ function distribution(value) {
2156
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2157
+ throw new TaDeploymentError(`${TaDeploymentUtil2.DISTRIBUTION_FILE} holds a JSON object.`);
2158
+ }
2159
+ const given = value;
2160
+ const result = {};
2161
+ if (given.name !== undefined) {
2162
+ result.name = name(given.name);
2163
+ }
2164
+ for (const key of ["relay", "gateway"]) {
2165
+ if (given[key] !== undefined) {
2166
+ const address = url(given[key]);
2167
+ if (!address) {
2168
+ throw new TaDeploymentError(`"${key}" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is not an address of http or https.`);
2169
+ }
2170
+ result[key] = address;
2171
+ }
2172
+ }
2173
+ if (given.updates !== undefined) {
2174
+ const updates = given.updates;
2175
+ const base = url(updates === null || updates === undefined ? undefined : updates.base);
2176
+ if (!base && (updates === null || updates === undefined ? undefined : updates.base) !== undefined) {
2177
+ throw new TaDeploymentError(`"updates.base" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is not an address of http or https.`);
2178
+ }
2179
+ const key = typeof (updates === null || updates === undefined ? undefined : updates.key) === "string" && updates.key.includes("PUBLIC KEY") ? updates.key : undefined;
2180
+ if ((updates === null || updates === undefined ? undefined : updates.key) !== undefined && !key) {
2181
+ throw new TaDeploymentError(`"updates.key" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is a public key in PEM.`);
2182
+ }
2183
+ result.updates = { ...base ? { base } : {}, ...key ? { key } : {} };
2184
+ }
2185
+ if (given.reach !== undefined) {
2186
+ result.reach = reach(given.reach);
2187
+ }
2188
+ if (given.inside !== undefined) {
2189
+ const inside = url(given.inside);
2190
+ if (!inside) {
2191
+ throw new TaDeploymentError(`"inside" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is not an address of http or https.`);
2192
+ }
2193
+ result.inside = inside;
2194
+ }
2195
+ return result;
2196
+ }
2197
+ TaDeploymentUtil2.distribution = distribution;
2198
+ function reach(value) {
2199
+ const given = typeof value === "string" ? { "*": value } : value;
2200
+ const entries = given && typeof given === "object" && !Array.isArray(given) ? Object.entries(given) : [];
2201
+ const result = {};
2202
+ for (const [language, text] of entries) {
2203
+ if (typeof text !== "string" || !text.trim()) {
2204
+ throw new TaDeploymentError(`"reach.${language}" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is not a sentence.`);
2205
+ }
2206
+ result[language] = text.trim().slice(0, 200);
2207
+ }
2208
+ if (Object.keys(result).length === 0) {
2209
+ throw new TaDeploymentError(`"reach" of ${TaDeploymentUtil2.DISTRIBUTION_FILE} is a sentence, or one by language.`);
2210
+ }
2211
+ return result;
2212
+ }
2213
+ function reachIn(reach2, language) {
2214
+ var _a, _b, _c, _d, _e;
2215
+ if (!reach2) {
2216
+ return;
2217
+ }
2218
+ const base = language.split("-")[0];
2219
+ const near = Object.keys(reach2).find((key) => key.split("-")[0] === base);
2220
+ return (_e = (_d = (_c = (_b = (_a = reach2[language]) !== null && _a !== undefined ? _a : reach2[base]) !== null && _b !== undefined ? _b : near && reach2[near]) !== null && _c !== undefined ? _c : reach2["*"]) !== null && _d !== undefined ? _d : reach2.en) !== null && _e !== undefined ? _e : Object.values(reach2)[0];
2221
+ }
2222
+ TaDeploymentUtil2.reachIn = reachIn;
2223
+ function apply(distribution2, env) {
2224
+ const defaults = { TA_DEPLOYMENT_NAME: distribution2.name, TA_RELAY_URL: distribution2.relay, TA_GATEWAY_URL: distribution2.gateway };
2225
+ for (const [key, value] of Object.entries(defaults)) {
2226
+ if (value && !env[key]) {
2227
+ env[key] = value;
2228
+ }
2229
+ }
2230
+ }
2231
+ TaDeploymentUtil2.apply = apply;
2232
+ })(TaDeploymentUtil || (TaDeploymentUtil = {}));
2233
+ // ../ta-protocol/esm/common/error-protocol.js
2234
+ var TaErrorCode = {
2235
+ SESSION_NOT_FOUND: "CELL_TA_SESSION_NOT_FOUND",
2236
+ SESSION_LOCKED: "CELL_TA_SESSION_LOCKED",
2237
+ TOO_MANY_SESSIONS: "CELL_TA_TOO_MANY_SESSIONS",
2238
+ MESSAGE_CONFLICT: "CELL_TA_MESSAGE_CONFLICT",
2239
+ MODEL_NOT_FOUND: "CELL_TA_MODEL_NOT_FOUND",
2240
+ INVALID_ARGUMENT: "CELL_TA_INVALID_ARGUMENT",
2241
+ COMMAND_FAILED: "CELL_TA_COMMAND_FAILED",
2242
+ NOTHING_TO_COMPACT: "CELL_TA_NOTHING_TO_COMPACT",
2243
+ ALREADY_COMPACTED: "CELL_TA_ALREADY_COMPACTED",
2244
+ SESSION_BUSY: "CELL_TA_SESSION_BUSY",
2245
+ CANCELLED: "CELL_TA_CANCELLED",
2246
+ NOT_SIGNED_IN: "CELL_TA_NOT_SIGNED_IN",
2247
+ ENVIRONMENT_FAILED: "CELL_TA_ENVIRONMENT_FAILED",
2248
+ RATE_LIMITED: "CELL_TA_RATE_LIMITED",
2249
+ FORBIDDEN: "CELL_TA_FORBIDDEN",
2250
+ LIMIT: "CELL_TA_LIMIT",
2251
+ CONNECTION_LOST: "CELL_TA_CONNECTION_LOST"
2252
+ };
2253
+ var TaErrorUtil;
2254
+ (function(TaErrorUtil2) {
2255
+ function code(error) {
2256
+ var _a;
2257
+ var _b;
2258
+ const failure = error;
2259
+ const code2 = (_b = failure === null || failure === undefined ? undefined : failure.code) !== null && _b !== undefined ? _b : (_a = failure === null || failure === undefined ? undefined : failure.data) === null || _a === undefined ? undefined : _a.code;
2260
+ return typeof code2 === "string" ? code2 : undefined;
2261
+ }
2262
+ TaErrorUtil2.code = code;
2263
+ })(TaErrorUtil || (TaErrorUtil = {}));
2264
+ // ../ta-protocol/esm/common/gateway-protocol.js
2265
+ var TaGatewayServer = Symbol("TaGatewayServer");
2266
+ // ../ta-protocol/esm/common/location.js
2267
+ var TaLocation;
2268
+ (function(TaLocation2) {
2269
+ TaLocation2.SSH = "ssh://";
2270
+ TaLocation2.CLOUD = "ta://";
2271
+ const CLOUD_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
2272
+ const HOST = /^(?!-)[\w.@:%+[\]-]+$/;
2273
+ function isRemote(location) {
2274
+ return location.startsWith(TaLocation2.SSH) || location.startsWith(TaLocation2.CLOUD);
2275
+ }
2276
+ TaLocation2.isRemote = isRemote;
2277
+ function isCloud(host2) {
2278
+ return !!host2 && host2.startsWith(TaLocation2.CLOUD);
2279
+ }
2280
+ TaLocation2.isCloud = isCloud;
2281
+ function isCloudName(name) {
2282
+ return CLOUD_NAME.test(name);
2283
+ }
2284
+ TaLocation2.isCloudName = isCloudName;
2285
+ function cloud(name, path2 = "") {
2286
+ return `${TaLocation2.CLOUD}${name}${path2 ? normalize(path2) : ""}`;
2287
+ }
2288
+ TaLocation2.cloud = cloud;
2289
+ function cloudName(hostOrLocation) {
2290
+ if (!hostOrLocation.startsWith(TaLocation2.CLOUD)) {
2291
+ return;
2292
+ }
2293
+ const rest = hostOrLocation.slice(TaLocation2.CLOUD.length);
2294
+ const slash = rest.indexOf("/");
2295
+ return slash < 0 ? rest : rest.slice(0, slash);
2296
+ }
2297
+ TaLocation2.cloudName = cloudName;
2298
+ function parse(location) {
2299
+ var _a;
2300
+ if (!isRemote(location)) {
2301
+ return;
2302
+ }
2303
+ if (location.startsWith(TaLocation2.CLOUD)) {
2304
+ const name = (_a = cloudName(location)) !== null && _a !== undefined ? _a : "";
2305
+ if (!isCloudName(name)) {
2306
+ throw new Error(`${JSON.stringify(location)} names no cloud workspace: write ta://<name>/<path>.`);
2307
+ }
2308
+ const path3 = location.slice(TaLocation2.CLOUD.length + name.length);
2309
+ return { host: `${TaLocation2.CLOUD}${name}`, path: path3 ? normalize(path3) : "" };
2310
+ }
2311
+ const rest = location.slice(TaLocation2.SSH.length);
2312
+ const slash = rest.indexOf("/");
2313
+ const host2 = slash < 0 ? rest : rest.slice(0, slash);
2314
+ const path2 = slash < 0 ? "" : normalize(rest.slice(slash));
2315
+ if (!isHost(host2)) {
2316
+ throw new Error(`${JSON.stringify(location)} names no host: write ssh://<host>/<path>, the host as ssh takes it.`);
2317
+ }
2318
+ return { host: host2, path: path2 };
2319
+ }
2320
+ TaLocation2.parse = parse;
2321
+ function isHost(host2) {
2322
+ return isCloud(host2) ? isCloudName(host2.slice(TaLocation2.CLOUD.length)) : HOST.test(host2);
2323
+ }
2324
+ TaLocation2.isHost = isHost;
2325
+ const FLAGS = /^-[46AaCfGgKkMNnqsTtVvXxYy]+$/;
2326
+ function readHost(input) {
2327
+ const words2 = input.trim().split(/\s+/).filter(Boolean);
2328
+ if (words2[0] === "ssh") {
2329
+ words2.shift();
2330
+ }
2331
+ let destination;
2332
+ let port;
2333
+ let user;
2334
+ const options = [];
2335
+ for (let i = 0;i < words2.length; i++) {
2336
+ const word = words2[i];
2337
+ const glued = /^-([pl])(.+)$/.exec(word);
2338
+ if (word === "-p" || word === "-l" || glued) {
2339
+ const value = glued ? glued[2] : words2[++i];
2340
+ if (value === undefined) {
2341
+ return { error: "invalid" };
2342
+ }
2343
+ if ((glued ? glued[1] : word[1]) === "p") {
2344
+ port = value;
2345
+ } else {
2346
+ user = value;
2347
+ }
2348
+ } else if (word === "-o" || word.startsWith("-o")) {
2349
+ const value = word === "-o" ? words2[++i] : word.slice(2);
2350
+ const option = /^(port|user)\s*=?\s*(.+)$/i.exec(value !== null && value !== undefined ? value : "");
2351
+ if (!option) {
2352
+ options.push(`-o ${value !== null && value !== undefined ? value : ""}`.trim());
2353
+ } else if (option[1].toLowerCase() === "port") {
2354
+ port = option[2];
2355
+ } else {
2356
+ user = option[2];
2357
+ }
2358
+ } else if (FLAGS.test(word)) {} else if (word.startsWith("-")) {
2359
+ options.push(/^-[bBcDeEFiIJLmOQRSwW]$/.test(word) && words2[i + 1] !== undefined ? `${word} ${words2[++i]}` : word);
2360
+ } else if (destination === undefined) {
2361
+ destination = word;
2362
+ } else {
2363
+ return { error: "invalid" };
2364
+ }
2365
+ }
2366
+ if (options.length > 0) {
2367
+ return { error: "options", options };
2368
+ }
2369
+ if (!destination) {
2370
+ return { error: "empty" };
2371
+ }
2372
+ let host2 = destination.replace(/^ssh:\/\//, "").replace(/\/.*$/, "");
2373
+ if (user && !host2.includes("@")) {
2374
+ host2 = `${user}@${host2}`;
2375
+ }
2376
+ if (port) {
2377
+ if (!/^\d{1,5}$/.test(port) || /:\d+$/.test(host2)) {
2378
+ return { error: "invalid" };
2379
+ }
2380
+ host2 = port === "22" ? host2 : `${host2}:${port}`;
2381
+ }
2382
+ return isHost(host2) ? { host: host2 } : { error: "invalid" };
2383
+ }
2384
+ TaLocation2.readHost = readHost;
2385
+ function ssh(host2, path2 = "") {
2386
+ return isCloud(host2) ? `${host2}${path2 ? normalize(path2) : ""}` : `${TaLocation2.SSH}${host2}${path2 ? normalize(path2) : ""}`;
2387
+ }
2388
+ TaLocation2.ssh = ssh;
2389
+ function hostLabel(host2) {
2390
+ if (isCloud(host2)) {
2391
+ return host2.slice(TaLocation2.CLOUD.length);
2392
+ }
2393
+ const name = host2.replace(/^[^@]*@/, "").replace(/^\[(.*)\](?::\d+)?$/, "$1").replace(/^([^:]*):\d+$/, "$1");
2394
+ return /^[\d.]+$/.test(name) || name.includes(":") ? name : name.split(".")[0] || name;
2395
+ }
2396
+ TaLocation2.hostLabel = hostLabel;
2397
+ function host(location) {
2398
+ var _a;
2399
+ return isRemote(location) ? (_a = parse(location)) === null || _a === undefined ? undefined : _a.host : undefined;
2400
+ }
2401
+ TaLocation2.host = host;
2402
+ function path(location) {
2403
+ var _a;
2404
+ var _b;
2405
+ return (_b = (_a = parse(location)) === null || _a === undefined ? undefined : _a.path) !== null && _b !== undefined ? _b : location;
2406
+ }
2407
+ TaLocation2.path = path;
2408
+ function parent(location) {
2409
+ const remote = parse(location);
2410
+ if (remote) {
2411
+ const above = remote.path ? parentPath(remote.path) : undefined;
2412
+ return above === undefined ? undefined : ssh(remote.host, above);
2413
+ }
2414
+ return parentPath(location);
2415
+ }
2416
+ TaLocation2.parent = parent;
2417
+ function child(location, name) {
2418
+ const remote = parse(location);
2419
+ if (remote) {
2420
+ return ssh(remote.host, childPath(remote.path || "/", name));
2421
+ }
2422
+ return childPath(location, name);
2423
+ }
2424
+ TaLocation2.child = child;
2425
+ function basename(location) {
2426
+ const remote = parse(location);
2427
+ const path2 = (remote ? remote.path : location).replace(/[\\/]+$/, "");
2428
+ const name = path2.slice(Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\")) + 1);
2429
+ return name || (remote === null || remote === undefined ? undefined : remote.host) || location;
2430
+ }
2431
+ TaLocation2.basename = basename;
2432
+ function homeRelative(location) {
2433
+ var _a;
2434
+ const remote = parse(location);
2435
+ const path2 = remote ? remote.path ? remote.path.slice(1) : "~" : location;
2436
+ const match = /^~(?:[\\/]+(.*))?$/.exec(path2);
2437
+ return match ? ((_a = match[1]) !== null && _a !== undefined ? _a : "").replace(/[\\/]+$/, "") : undefined;
2438
+ }
2439
+ TaLocation2.homeRelative = homeRelative;
2440
+ function isAbsolute(location) {
2441
+ if (homeRelative(location) !== undefined) {
2442
+ return false;
2443
+ }
2444
+ return isRemote(location) || /^([\\/]|[A-Za-z]:)/.test(location);
2445
+ }
2446
+ TaLocation2.isAbsolute = isAbsolute;
2447
+ function parentPath(path2) {
2448
+ const trimmed = path2.replace(/[\\/]+$/, "");
2449
+ const at = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
2450
+ if (at < 0) {
2451
+ return;
2452
+ }
2453
+ const head = trimmed.slice(0, at);
2454
+ return head === "" || /^[A-Za-z]:$/.test(head) ? head + trimmed[at] : head;
2455
+ }
2456
+ function childPath(path2, name) {
2457
+ const separator = path2.includes("/") || !path2.includes("\\") ? "/" : "\\";
2458
+ return path2.endsWith(separator) ? path2 + name : path2 + separator + name;
2459
+ }
2460
+ function normalize(path2) {
2461
+ const squeezed = `/${path2}`.replace(/\/+/g, "/");
2462
+ return squeezed.length > 1 ? squeezed.replace(/\/$/, "") : squeezed;
2463
+ }
2464
+ })(TaLocation || (TaLocation = {}));
2465
+ // ../ta-protocol/esm/common/package-protocol.js
2466
+ var TaPackageServer = Symbol("TaPackageServer");
2467
+ var TaPackageTextUtil;
2468
+ (function(TaPackageTextUtil2) {
2469
+ function pick(text, language) {
2470
+ var _a, _b, _c, _d, _e;
2471
+ if (text === undefined || typeof text === "string") {
2472
+ return text;
2473
+ }
2474
+ const base = language.split("-")[0];
2475
+ const kin = Object.keys(text).find((key) => key.split("-")[0] === base);
2476
+ return (_e = (_d = (_c = (_b = (_a = text[language]) !== null && _a !== undefined ? _a : text[base]) !== null && _b !== undefined ? _b : kin === undefined ? undefined : text[kin]) !== null && _c !== undefined ? _c : text.en) !== null && _d !== undefined ? _d : text["en-US"]) !== null && _e !== undefined ? _e : Object.values(text)[0];
2477
+ }
2478
+ TaPackageTextUtil2.pick = pick;
2479
+ })(TaPackageTextUtil || (TaPackageTextUtil = {}));
2480
+ // ../ta-protocol/esm/common/page-protocol.js
2481
+ var TaPageServer = Symbol("TaPageServer");
2482
+ // ../ta-protocol/esm/common/path-map.js
2483
+ var TaPathMap;
2484
+ (function(TaPathMap2) {
2485
+ function isWindows(path2) {
2486
+ return /^[a-zA-Z]:([\\/]|$)/.test(path2) || /^\\\\[^\\]/.test(path2);
2487
+ }
2488
+ TaPathMap2.isWindows = isWindows;
2489
+ function rest(path2, base) {
2490
+ const windows = isWindows(base);
2491
+ if (windows ? !isWindows(path2) : !base.startsWith("/") || !path2.startsWith("/")) {
2492
+ return;
2493
+ }
2494
+ const within = parts(base, windows);
2495
+ const all = parts(path2, windows);
2496
+ if (!within.length || all.length < within.length) {
2497
+ return;
2498
+ }
2499
+ const same = (a, b) => windows ? a.toLowerCase() === b.toLowerCase() : a === b;
2500
+ return within.every((part, i) => same(part, all[i])) ? all.slice(within.length) : undefined;
2501
+ }
2502
+ TaPathMap2.rest = rest;
2503
+ function under(path2, base) {
2504
+ return rest(path2, base) !== undefined;
2505
+ }
2506
+ TaPathMap2.under = under;
2507
+ function join(base, parts2) {
2508
+ if (!parts2.length) {
2509
+ return base;
2510
+ }
2511
+ const sep = isWindows(base) ? "\\" : "/";
2512
+ return `${base.replace(/[\\/]+$/, "")}${sep}${parts2.join(sep)}`;
2513
+ }
2514
+ TaPathMap2.join = join;
2515
+ function basename(path2) {
2516
+ var _a;
2517
+ return (_a = path2.split(/[\\/]+/).filter(Boolean).pop()) !== null && _a !== undefined ? _a : "";
2518
+ }
2519
+ TaPathMap2.basename = basename;
2520
+ function path(value, pairs) {
2521
+ for (const [from, to] of deepest(pairs)) {
2522
+ const found = rest(value, from);
2523
+ if (found) {
2524
+ return join(to, found);
2525
+ }
2526
+ }
2527
+ return value;
2528
+ }
2529
+ TaPathMap2.path = path;
2530
+ function text(value, pairs) {
2531
+ const order = deepest(pairs);
2532
+ if (!order.length) {
2533
+ return value;
2534
+ }
2535
+ const end = String.raw`\s"'<>|*?:;,`;
2536
+ const pattern = new RegExp(String.raw`(^|[^\w.~-])(?:${order.map(([from]) => `(${source(from)})`).join("|")})((?:[\\/][^\\/${end}]*)*)(?=$|[\\/${end})\]}])`, "g");
2537
+ return value.replace(pattern, (...match) => {
2538
+ var _a;
2539
+ const before = match[1];
2540
+ const found = order.findIndex((_, i) => match[i + 2] !== undefined);
2541
+ const tail = (_a = match[order.length + 2]) !== null && _a !== undefined ? _a : "";
2542
+ return `${before}${join(order[found][1], tail.split(/[\\/]+/).filter(Boolean))}`;
2543
+ });
2544
+ }
2545
+ TaPathMap2.text = text;
2546
+ function json(value, pairs) {
2547
+ const order = deepest(pairs);
2548
+ if (!order.length) {
2549
+ return value;
2550
+ }
2551
+ const one = (each) => {
2552
+ const whole = path(each, order);
2553
+ return whole !== each ? whole : text(each, order);
2554
+ };
2555
+ const walk = (each) => {
2556
+ if (typeof each === "string") {
2557
+ return one(each);
2558
+ }
2559
+ if (Array.isArray(each)) {
2560
+ return each.map(walk);
2561
+ }
2562
+ if (each && typeof each === "object") {
2563
+ return Object.fromEntries(Object.entries(each).map(([key, inner]) => [one(key), walk(inner)]));
2564
+ }
2565
+ return each;
2566
+ };
2567
+ return walk(value);
2568
+ }
2569
+ TaPathMap2.json = json;
2570
+ function parts(path2, windows) {
2571
+ return path2.split(windows ? /[\\/]+/ : /\/+/).filter(Boolean);
2572
+ }
2573
+ function deepest(pairs) {
2574
+ return pairs.filter(([from, to]) => from && to && from !== to && parts(from, isWindows(from)).length > 0).sort(([a], [b]) => parts(b, isWindows(b)).length - parts(a, isWindows(a)).length);
2575
+ }
2576
+ function source(base) {
2577
+ const windows = isWindows(base);
2578
+ const quote = (part) => [...part].map((char) => windows && char.toLowerCase() !== char.toUpperCase() ? `[${char.toLowerCase()}${char.toUpperCase()}]` : char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
2579
+ const each = parts(base, windows).map(quote);
2580
+ if (!windows) {
2581
+ return `/${each.join("/+")}`;
2582
+ }
2583
+ return `${base.startsWith("\\\\") ? String.raw`\\\\` : ""}${each.join(String.raw`[\\/]+`)}`;
2584
+ }
2585
+ })(TaPathMap || (TaPathMap = {}));
2586
+ // ../ta-protocol/esm/common/presence-protocol.js
2587
+ var TaPresenceServer = Symbol("TaPresenceServer");
2588
+ var TaMessageAuthor;
2589
+ (function(TaMessageAuthor2) {
2590
+ const LINE = /^\[ta:by ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
2591
+ const LINES = /^\[ta:by [^\]\n]*\]$\n?/gm;
2592
+ function strip(message) {
2593
+ const context = TaMessageContext.read(message);
2594
+ if (context === undefined || !LINE.test(context)) {
2595
+ return message;
2596
+ }
2597
+ const kept = context.replace(LINES, "").replace(/\n+$/, "");
2598
+ const body = TaMessageContext.strip(message);
2599
+ return kept.trim() ? TaMessageContext.wrap(kept, body) : body;
2600
+ }
2601
+ TaMessageAuthor2.strip = strip;
2602
+ function mark(message, id, name) {
2603
+ const plain = strip(message);
2604
+ if (/^[/!]/.test(plain)) {
2605
+ return plain;
2606
+ }
2607
+ const line = `[ta:by ${id.replace(/[\s\]]/g, "")} ${name.replace(/[\]\n]/g, " ").trim() || id}]`;
2608
+ const context = TaMessageContext.read(plain);
2609
+ return TaMessageContext.wrap(context === undefined ? line : `${context}
2610
+ ${line}`, TaMessageContext.strip(plain));
2611
+ }
2612
+ TaMessageAuthor2.mark = mark;
2613
+ function of(message) {
2614
+ var _a;
2615
+ const context = TaMessageContext.read(message);
2616
+ const match = context === undefined ? null : LINE.exec(context);
2617
+ return match ? { id: match[1], name: ((_a = match[2]) !== null && _a !== undefined ? _a : match[1]).trim() } : undefined;
2618
+ }
2619
+ TaMessageAuthor2.of = of;
2620
+ })(TaMessageAuthor || (TaMessageAuthor = {}));
2621
+ // ../ta-protocol/esm/common/relay-protocol.js
2622
+ var TaRelayServer = Symbol("TaRelayServer");
2623
+ // ../ta-protocol/esm/common/remote-protocol.js
2624
+ var TaRemoteServer = Symbol("TaRemoteServer");
2625
+ // ../ta-protocol/esm/common/room-protocol.js
2626
+ var TaRoomServer = Symbol("TaRoomServer");
2627
+ var TaRoomWatchUtil;
2628
+ (function(TaRoomWatchUtil2) {
2629
+ function of(messages, state) {
2630
+ const prefixes = Array.isArray(state) ? state.filter((prefix) => typeof prefix === "string" && prefix.length > 0) : [];
2631
+ return { messages: messages !== false, state: [...new Set(prefixes)].sort() };
2632
+ }
2633
+ TaRoomWatchUtil2.of = of;
2634
+ function union(watches) {
2635
+ let messages = false;
2636
+ const state = [];
2637
+ for (const watch of watches) {
2638
+ messages || (messages = watch.messages);
2639
+ state.push(...watch.state);
2640
+ }
2641
+ return of(messages, messages ? [] : state);
2642
+ }
2643
+ TaRoomWatchUtil2.union = union;
2644
+ function same(a, b) {
2645
+ return a === b || !!a && !!b && a.messages === b.messages && a.state.join(`
2646
+ `) === b.state.join(`
2647
+ `);
2648
+ }
2649
+ TaRoomWatchUtil2.same = same;
2650
+ function hears(watch, event) {
2651
+ if (event.type === "message") {
2652
+ return watch.messages;
2653
+ }
2654
+ if (event.type === "state") {
2655
+ return watch.messages || watch.state.some((prefix) => event.key.startsWith(prefix));
2656
+ }
2657
+ return true;
2658
+ }
2659
+ TaRoomWatchUtil2.hears = hears;
2660
+ })(TaRoomWatchUtil || (TaRoomWatchUtil = {}));
2661
+ // ../ta-protocol/esm/common/screen-share-protocol.js
2662
+ var TaScreenShareServer = Symbol("TaScreenShareServer");
2663
+ var TaDesktopUtil;
2664
+ (function(TaDesktopUtil2) {
2665
+ TaDesktopUtil2.DEFAULT_PORT = 5900;
2666
+ function id(target) {
2667
+ var _a;
2668
+ return `${(_a = target.via) !== null && _a !== undefined ? _a : ""}|${host(target)}:${port(target)}`;
2669
+ }
2670
+ TaDesktopUtil2.id = id;
2671
+ function host(target) {
2672
+ var _a;
2673
+ return ((_a = target.host) !== null && _a !== undefined ? _a : "").trim() || "127.0.0.1";
2674
+ }
2675
+ TaDesktopUtil2.host = host;
2676
+ function port(target) {
2677
+ var _a;
2678
+ return (_a = target.port) !== null && _a !== undefined ? _a : TaDesktopUtil2.DEFAULT_PORT;
2679
+ }
2680
+ TaDesktopUtil2.port = port;
2681
+ function parse(id2) {
2682
+ const match = /^([^|]*)\|(.+):(\d+)$/.exec(String(id2 !== null && id2 !== undefined ? id2 : ""));
2683
+ if (!match) {
2684
+ return;
2685
+ }
2686
+ const port2 = Number(match[3]);
2687
+ return port2 > 0 && port2 < 65536 ? { via: match[1], host: match[2], port: port2 } : undefined;
2688
+ }
2689
+ TaDesktopUtil2.parse = parse;
2690
+ function validPort(port2) {
2691
+ return typeof port2 === "number" && Number.isInteger(port2) && port2 >= 1024 && port2 < 65536;
2692
+ }
2693
+ TaDesktopUtil2.validPort = validPort;
2694
+ function loopback(host2) {
2695
+ return /^(127\.\d+\.\d+\.\d+|localhost|::1|\[::1\])$/i.test(host2);
2696
+ }
2697
+ TaDesktopUtil2.loopback = loopback;
2698
+ function validHost(host2) {
2699
+ return typeof host2 === "string" && /^[A-Za-z0-9.:\-[\]]{1,253}$/.test(host2);
2700
+ }
2701
+ TaDesktopUtil2.validHost = validHost;
2702
+ })(TaDesktopUtil || (TaDesktopUtil = {}));
2703
+ // ../ta-protocol/esm/common/settings-protocol.js
2704
+ var TaSettingsServer = Symbol("TaSettingsServer");
2705
+ // ../ta-protocol/esm/common/ta-protocol.js
2706
+ var TaServer = Symbol("TaServer");
2707
+ var TaClient = Symbol("TaClient");
2708
+ var TaSlashCommandUtil;
2709
+ (function(TaSlashCommandUtil2) {
2710
+ function description(command, language) {
2711
+ var _a, _b;
2712
+ const { descriptions } = command;
2713
+ return (_b = (_a = descriptions === null || descriptions === undefined ? undefined : descriptions[language]) !== null && _a !== undefined ? _a : descriptions === null || descriptions === undefined ? undefined : descriptions[language.split("-")[0]]) !== null && _b !== undefined ? _b : command.description;
2714
+ }
2715
+ TaSlashCommandUtil2.description = description;
2716
+ })(TaSlashCommandUtil || (TaSlashCommandUtil = {}));
2717
+ // ../ta-protocol/esm/common/usage-protocol.js
2718
+ var TaUsageServer = Symbol("TaUsageServer");
2719
+ // ../ta-protocol/esm/common/voice-protocol.js
2720
+ var TaVoiceServer = Symbol("TaVoiceServer");
2721
+ var TaBargeIn;
2722
+ (function(TaBargeIn2) {
2723
+ TaBargeIn2.DEFAULTS = { duck: 0.2, speechMs: 500, level: 0.02, words: 2, waitMs: 1500, echo: 0.3, joinMs: 300, tap: false };
2724
+ TaBargeIn2.SENSITIVITY = [
2725
+ { speechMs: 1000, level: 0.05 },
2726
+ { speechMs: 750, level: 0.035 },
2727
+ { speechMs: TaBargeIn2.DEFAULTS.speechMs, level: TaBargeIn2.DEFAULTS.level },
2728
+ { speechMs: 300, level: 0.012 },
2729
+ { speechMs: 150, level: 0.006 }
2730
+ ];
2731
+ function sensitivity(bargeIn) {
2732
+ let nearest = 0;
2733
+ TaBargeIn2.SENSITIVITY.forEach((step, index) => {
2734
+ if (Math.abs(step.speechMs - bargeIn.speechMs) < Math.abs(TaBargeIn2.SENSITIVITY[nearest].speechMs - bargeIn.speechMs)) {
2735
+ nearest = index;
2736
+ }
2737
+ });
2738
+ return nearest;
2739
+ }
2740
+ TaBargeIn2.sensitivity = sensitivity;
2741
+ function pick(value) {
2742
+ const given = value && typeof value === "object" ? value : {};
2743
+ const out = typeof given.tap === "boolean" ? { tap: given.tap } : {};
2744
+ for (const key of Object.keys(RANGES)) {
2745
+ const number = given[key];
2746
+ if (typeof number === "number" && Number.isFinite(number)) {
2747
+ const [min, max] = RANGES[key];
2748
+ out[key] = Math.min(max, Math.max(min, number));
2749
+ }
2750
+ }
2751
+ return out;
2752
+ }
2753
+ TaBargeIn2.pick = pick;
2754
+ const RANGES = {
2755
+ duck: [0, 1],
2756
+ speechMs: [0, 5000],
2757
+ level: [0, 1],
2758
+ words: [1, 50],
2759
+ waitMs: [100, 1e4],
2760
+ echo: [0, 4],
2761
+ joinMs: [0, 3000]
2762
+ };
2763
+ function resolve(value) {
2764
+ return { ...TaBargeIn2.DEFAULTS, ...pick(value) };
2765
+ }
2766
+ TaBargeIn2.resolve = resolve;
2767
+ })(TaBargeIn || (TaBargeIn = {}));
2768
+ // ../ta-protocol/esm/common/workspace-protocol.js
2769
+ var TaWorkspaceServer = Symbol("TaWorkspaceServer");
2770
+ var TaTerminalServer = Symbol("TaTerminalServer");
2771
+ var TaExcludedFiles;
2772
+ (function(TaExcludedFiles2) {
2773
+ TaExcludedFiles2.NAMES = [".git", ".svn", ".hg", ".DS_Store", "Thumbs.db"];
2774
+ function has(name) {
2775
+ return TaExcludedFiles2.NAMES.includes(name);
2776
+ }
2777
+ TaExcludedFiles2.has = has;
2778
+ function filter(entries) {
2779
+ return entries.filter((entry) => !has(entry.name));
2780
+ }
2781
+ TaExcludedFiles2.filter = filter;
2782
+ })(TaExcludedFiles || (TaExcludedFiles = {}));
2783
+ var TA_UPLOAD_PART_BYTES = 4 * 1024 * 1024;
2784
+ // web-src/team-view.ts
2785
+ var TeamViewUtil;
2786
+ ((TeamViewUtil) => {
2787
+ function visible(team2, can) {
2788
+ const channels = new Set(team2.channels.filter((channel) => can("channel", channel.id)).map((channel) => channel.id));
2789
+ const agents = new Set(team2.agents.filter((agent) => can("agent", agent.id)).map((agent) => agent.id));
2790
+ for (const channel of team2.channels) {
2791
+ if (channels.has(channel.id)) {
2792
+ for (const member of channel.members) {
2793
+ agents.add(member);
2794
+ }
2795
+ }
2796
+ }
2797
+ return { agents, channels };
2798
+ }
2799
+ TeamViewUtil.visible = visible;
2800
+ function team(value, visible2) {
2801
+ if (!value) {
2802
+ return value;
2803
+ }
2804
+ return {
2805
+ ...value,
2806
+ agents: value.agents.filter((agent) => visible2.agents.has(agent.id)),
2807
+ channels: value.channels.filter((channel) => visible2.channels.has(channel.id))
2808
+ };
2809
+ }
2810
+ TeamViewUtil.team = team;
2811
+ function byId(value, seen) {
2812
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2813
+ return value;
2814
+ }
2815
+ return Object.fromEntries(Object.entries(value).filter(([id]) => seen.has(id)));
2816
+ }
2817
+ TeamViewUtil.byId = byId;
2818
+ })(TeamViewUtil ||= {});
2819
+
2820
+ // web-src/team-store.ts
2821
+ class TeamStore {
2822
+ host;
2823
+ team = ChannelsUtil.emptyTeam();
2824
+ queue = { jobs: [], rounds: {} };
2825
+ working = {};
2826
+ answered;
2827
+ messages = new Map;
2828
+ reading = new Map;
2829
+ agents = new Map;
2830
+ started = new Set;
2831
+ waiting = new Map;
2832
+ opening = new Map;
2833
+ settling = new Set;
2834
+ options;
2835
+ disposed = false;
2836
+ constructor(host, options = {}) {
2837
+ this.host = host;
2838
+ this.options = { pollMs: 300, timeoutMs: 15 * 60 * 1000, ...options };
2839
+ }
2840
+ get state() {
2841
+ return this.team;
2842
+ }
2843
+ async shareAgent(ref, color) {
2844
+ const agent = ChannelsUtil.findAgent(this.team, String(ref ?? ""));
2845
+ if (!agent) {
2846
+ throw new Error(`No agent is ${String(ref)}.`);
2847
+ }
2848
+ const card = JSON.stringify(AgentCards.card(agent, typeof color === "string" ? color : undefined));
2849
+ const cards = await this.get(Keys.CARDS) ?? {};
2850
+ const kept = cards[agent.id];
2851
+ const live = kept ? (await this.host.shares.list()).find((share2) => share2.id === kept.share) : undefined;
2852
+ if (live && kept?.card === card) {
2853
+ return live;
2854
+ }
2855
+ if (live) {
2856
+ await this.host.shares.remove(live.id);
2857
+ }
2858
+ const share = await this.host.shares.create({
2859
+ kind: AgentCards.KIND,
2860
+ title: `@${agent.name}`,
2861
+ type: "application/json",
2862
+ data: new TextEncoder().encode(card),
2863
+ access: "link",
2864
+ days: CARD_DAYS,
2865
+ offline: true
2866
+ });
2867
+ await this.set(Keys.CARDS, { ...this.liveCards(cards), [agent.id]: { share: share.id, card } });
2868
+ return share;
2869
+ }
2870
+ async stopCard(ref) {
2871
+ const agent = ChannelsUtil.findAgent(this.team, String(ref ?? ""));
2872
+ const cards = await this.get(Keys.CARDS) ?? {};
2873
+ const kept = agent && cards[agent.id];
2874
+ if (!agent || !kept) {
2875
+ return false;
2876
+ }
2877
+ const { [agent.id]: _gone, ...rest } = cards;
2878
+ await this.set(Keys.CARDS, this.liveCards(rest));
2879
+ return this.host.shares.remove(kept.share);
2880
+ }
2881
+ liveCards(cards) {
2882
+ return Object.fromEntries(Object.entries(cards).filter(([id]) => this.team.agents.some((agent) => agent.id === id)));
2883
+ }
2884
+ async openCard(link, password) {
2885
+ const content = await this.host.shares.open(String(link ?? ""), typeof password === "string" && password ? password : undefined);
2886
+ const card = content.kind === AgentCards.KIND ? AgentCards.parse(content.data) : undefined;
2887
+ if (!card) {
2888
+ throw new Error("This link shares no card of an agent.");
2889
+ }
2890
+ return card;
2891
+ }
2892
+ waitingFor(round) {
2893
+ let waiting = this.waiting.get(round);
2894
+ if (!waiting) {
2895
+ waiting = { replies: [], waiters: [] };
2896
+ this.waiting.set(round, waiting);
2897
+ }
2898
+ return waiting;
2899
+ }
2900
+ async setAnswered(agentId, at) {
2901
+ this.answered ??= await this.get(Keys.ANSWERED) ?? {};
2902
+ const known = new Set(this.team.agents.map((agent) => agent.id));
2903
+ const kept = Object.fromEntries(Object.entries(this.answered).filter(([id]) => known.has(id)));
2904
+ this.answered = { ...kept, [agentId]: at };
2905
+ await this.set(Keys.ANSWERED, this.answered);
2906
+ }
2907
+ async pinDirectories() {
2908
+ const loose = this.team.agents.filter((agent) => !agent.cwd);
2909
+ if (loose.length === 0) {
2910
+ return;
2911
+ }
2912
+ const serverCwd = (await this.host.getServerInfo()).cwd;
2913
+ const pinned = new Map;
2914
+ for (const agent of loose) {
2915
+ pinned.set(agent.id, agent.sessionFile && await this.host.sessionCwd(agent.sessionFile) || serverCwd);
2916
+ }
2917
+ await this.saveTeam({ ...this.team, agents: this.team.agents.map((agent) => pinned.has(agent.id) ? { ...agent, cwd: pinned.get(agent.id) } : agent) });
2918
+ }
2919
+ session(agent) {
2920
+ let opening = this.opening.get(agent.id);
2921
+ if (!opening) {
2922
+ opening = this.openSession(agent).finally(() => this.opening.delete(agent.id));
2923
+ this.opening.set(agent.id, opening);
2924
+ }
2925
+ return opening;
2926
+ }
2927
+ async openSession(agent) {
2928
+ if (agent.sessionFile) {
2929
+ const open = (await this.host.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
2930
+ if (open) {
2931
+ return open.sessionId;
2932
+ }
2933
+ }
2934
+ const cwd = agent.cwd ?? (await this.host.getServerInfo()).cwd;
2935
+ const options = { cwd, appendSystemPrompt: ChannelsText.systemPrompt(agent), group: NAME };
2936
+ if (agent.sessionFile) {
2937
+ try {
2938
+ return (await this.host.openSession({ ...options, sessionFile: agent.sessionFile })).sessionId;
2939
+ } catch (error) {
2940
+ if (TaErrorUtil.code(error) !== TaErrorCode.INVALID_ARGUMENT) {
2941
+ throw error;
2942
+ }
2943
+ }
2944
+ }
2945
+ const { sessionId } = await this.host.openSession(options);
2946
+ await this.host.setSessionName(sessionId, agent.name);
2947
+ const { sessionFile } = await this.host.getState(sessionId);
2948
+ if (sessionFile) {
2949
+ await this.saveTeam({ ...this.team, agents: this.team.agents.map((other) => other.id === agent.id ? { ...other, sessionFile } : other) });
2950
+ }
2951
+ return sessionId;
2952
+ }
2953
+ async settled(sessionId, before) {
2954
+ const start = Date.now();
2955
+ for (;; ) {
2956
+ const state = await this.host.getState(sessionId);
2957
+ if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
2958
+ return;
2959
+ }
2960
+ if (Date.now() - start > this.options.timeoutMs) {
2961
+ throw new Error("No answer in time; the agent may still be working in its session.");
2962
+ }
2963
+ await new Promise((resolve) => setTimeout(resolve, this.options.pollMs));
2964
+ }
2965
+ }
2966
+ messagesOf(channelId) {
2967
+ const known = this.messages.get(channelId);
2968
+ if (known) {
2969
+ return Promise.resolve(known);
2970
+ }
2971
+ let reading = this.reading.get(channelId);
2972
+ if (!reading) {
2973
+ reading = this.get(Keys.messages(channelId)).then((stored) => {
2974
+ const messages = this.messages.get(channelId) ?? stored ?? [];
2975
+ this.messages.set(channelId, messages);
2976
+ return messages;
2977
+ });
2978
+ this.reading.set(channelId, reading);
2979
+ }
2980
+ return reading;
2981
+ }
2982
+ async append(channelId, message) {
2983
+ if (!this.team.channels.some((channel) => channel.id === channelId)) {
2984
+ return message;
2985
+ }
2986
+ await this.messagesOf(channelId);
2987
+ const messages = ChannelsUtil.append(this.messages.get(channelId) ?? [], message);
2988
+ this.messages.set(channelId, messages);
2989
+ await this.set(Keys.messages(channelId), messages);
2990
+ return message;
2991
+ }
2992
+ async saveTeam(team) {
2993
+ this.team = team;
2994
+ this.linkSessions();
2995
+ await this.set(Keys.TEAM, team);
2996
+ }
2997
+ shareWithMembers() {
2998
+ const team = this.host.team;
2999
+ if (!team) {
3000
+ return;
3001
+ }
3002
+ const can = (principal, kind, id) => team.can(principal, kind === "agent" ? "agent.view" : "channel.view", { kind, id });
3003
+ team.shareData(NAME, {
3004
+ keys: [Keys.TEAM, Keys.WORKING, Keys.ANSWERED, Keys.FOCUS, Keys.MESSAGES],
3005
+ view: (principal, key, value) => {
3006
+ const visible = TeamViewUtil.visible(this.team, (kind, id) => can(principal, kind, id));
3007
+ if (key === Keys.TEAM) {
3008
+ return TeamViewUtil.team(value, visible);
3009
+ }
3010
+ if (key.startsWith(Keys.MESSAGES)) {
3011
+ return visible.channels.has(key.slice(Keys.MESSAGES.length)) ? value : undefined;
3012
+ }
3013
+ if (key === Keys.FOCUS) {
3014
+ return visible.channels.has(value?.channelId ?? "") ? value : undefined;
1610
3015
  }
3016
+ return TeamViewUtil.byId(value, key === Keys.WORKING ? visible.channels : visible.agents);
1611
3017
  }
1612
- }
1613
- return { agents, channels };
3018
+ });
3019
+ this.linkSessions();
1614
3020
  }
1615
- TeamViewUtil.visible = visible;
1616
- function team(value, visible2) {
1617
- if (!value) {
1618
- return value;
3021
+ linkSessions() {
3022
+ for (const agent of this.team.agents) {
3023
+ if (agent.sessionFile) {
3024
+ this.host.team?.link(agent.sessionFile, { kind: "agent", id: agent.id });
3025
+ }
1619
3026
  }
1620
- return {
1621
- ...value,
1622
- agents: value.agents.filter((agent) => visible2.agents.has(agent.id)),
1623
- channels: value.channels.filter((channel) => visible2.channels.has(channel.id))
1624
- };
1625
3027
  }
1626
- TeamViewUtil.team = team;
1627
- function byId(value, seen) {
1628
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1629
- return value;
1630
- }
1631
- return Object.fromEntries(Object.entries(value).filter(([id]) => seen.has(id)));
3028
+ async setWorking(channelId, agentId, on) {
3029
+ const others = (this.working[channelId] ?? []).filter((id) => id !== agentId);
3030
+ this.working = { ...this.working, [channelId]: on ? [...others, agentId] : others };
3031
+ await this.set(Keys.WORKING, this.working);
1632
3032
  }
1633
- TeamViewUtil.byId = byId;
1634
- })(TeamViewUtil ||= {});
1635
-
1636
- // web-src/team.ts
1637
- class TeamService {
1638
- host;
1639
- team = ChannelsUtil.emptyTeam();
1640
- queue = { jobs: [], rounds: {} };
1641
- working = {};
1642
- answered;
1643
- messages = new Map;
1644
- reading = new Map;
1645
- agents = new Map;
1646
- started = new Set;
1647
- waiting = new Map;
1648
- opening = new Map;
1649
- settling = new Set;
1650
- options;
1651
- disposed = false;
1652
- constructor(host, options = {}) {
1653
- this.host = host;
1654
- this.options = { pollMs: 300, timeoutMs: 15 * 60 * 1000, ...options };
3033
+ async get(key) {
3034
+ return await this.host.getExtensionData(NAME, key) ?? undefined;
1655
3035
  }
1656
- get state() {
1657
- return this.team;
3036
+ set(key, value) {
3037
+ return this.host.setExtensionData(NAME, key, value);
1658
3038
  }
3039
+ }
3040
+
3041
+ // web-src/team.ts
3042
+ class TeamService extends TeamStore {
1659
3043
  async start() {
1660
3044
  this.team = await this.get(Keys.TEAM) ?? ChannelsUtil.emptyTeam();
1661
3045
  this.shareWithMembers();
@@ -1740,55 +3124,6 @@ class TeamService {
1740
3124
  agentOf(sessionFile) {
1741
3125
  return sessionFile ? this.team.agents.find((agent) => agent.sessionFile === sessionFile) : undefined;
1742
3126
  }
1743
- async shareAgent(ref, color) {
1744
- const agent = ChannelsUtil.findAgent(this.team, String(ref ?? ""));
1745
- if (!agent) {
1746
- throw new Error(`No agent is ${String(ref)}.`);
1747
- }
1748
- const card = JSON.stringify(AgentCards.card(agent, typeof color === "string" ? color : undefined));
1749
- const cards = await this.get(Keys.CARDS) ?? {};
1750
- const kept = cards[agent.id];
1751
- const live = kept ? (await this.host.shares.list()).find((share2) => share2.id === kept.share) : undefined;
1752
- if (live && kept?.card === card) {
1753
- return live;
1754
- }
1755
- if (live) {
1756
- await this.host.shares.remove(live.id);
1757
- }
1758
- const share = await this.host.shares.create({
1759
- kind: AgentCards.KIND,
1760
- title: `@${agent.name}`,
1761
- type: "application/json",
1762
- data: new TextEncoder().encode(card),
1763
- access: "link",
1764
- days: CARD_DAYS,
1765
- offline: true
1766
- });
1767
- await this.set(Keys.CARDS, { ...this.liveCards(cards), [agent.id]: { share: share.id, card } });
1768
- return share;
1769
- }
1770
- async stopCard(ref) {
1771
- const agent = ChannelsUtil.findAgent(this.team, String(ref ?? ""));
1772
- const cards = await this.get(Keys.CARDS) ?? {};
1773
- const kept = agent && cards[agent.id];
1774
- if (!agent || !kept) {
1775
- return false;
1776
- }
1777
- const { [agent.id]: _gone, ...rest } = cards;
1778
- await this.set(Keys.CARDS, this.liveCards(rest));
1779
- return this.host.shares.remove(kept.share);
1780
- }
1781
- liveCards(cards) {
1782
- return Object.fromEntries(Object.entries(cards).filter(([id]) => this.team.agents.some((agent) => agent.id === id)));
1783
- }
1784
- async openCard(link, password) {
1785
- const content = await this.host.shares.open(String(link ?? ""), typeof password === "string" && password ? password : undefined);
1786
- const card = content.kind === AgentCards.KIND ? AgentCards.parse(content.data) : undefined;
1787
- if (!card) {
1788
- throw new Error("This link shares no card of an agent.");
1789
- }
1790
- return card;
1791
- }
1792
3127
  async addFromCard(input, language2 = HandOff.serverLanguage()) {
1793
3128
  const card = await this.openCard(input.link, input.password);
1794
3129
  const agent = await this.createAgent({ name: AgentCards.freeName(this.team, card.name), role: card.role, cwd: input.cwd, face: card.face });
@@ -1944,7 +3279,7 @@ class TeamService {
1944
3279
  async handOn(channel, message, hops, round) {
1945
3280
  const current = this.queue.rounds[round]?.round ?? ChannelsUtil.newRound();
1946
3281
  const messages = await this.messagesOf(channel.id);
1947
- const targets = ChannelsUtil.targets(this.team, channel, message).filter((agentId) => !this.queue.jobs.some((job) => job.messageId === message.id && job.agentId === agentId) && !messages.some((item) => item.replyTo === message.id && item.author === agentId));
3282
+ const targets = ChannelsText.targets(this.team, channel, message).filter((agentId) => !this.queue.jobs.some((job) => job.messageId === message.id && job.agentId === agentId) && !messages.some((item) => item.replyTo === message.id && item.author === agentId));
1948
3283
  const limited = ChannelsUtil.limit(current, targets, hops);
1949
3284
  const jobs = limited.allowed.map((agentId) => ({
1950
3285
  id: ChannelsUtil.newId("job"),
@@ -2030,14 +3365,6 @@ class TeamService {
2030
3365
  resolve(waiting.replies);
2031
3366
  }
2032
3367
  }
2033
- waitingFor(round) {
2034
- let waiting = this.waiting.get(round);
2035
- if (!waiting) {
2036
- waiting = { replies: [], waiters: [] };
2037
- this.waiting.set(round, waiting);
2038
- }
2039
- return waiting;
2040
- }
2041
3368
  async answer(channel, message, agentId, by) {
2042
3369
  await this.setWorking(channel.id, agentId, true);
2043
3370
  let text;
@@ -2054,13 +3381,6 @@ class TeamService {
2054
3381
  }
2055
3382
  return this.append(channel.id, { id: ChannelsUtil.newId("message"), author: agentId, text, at: Date.now(), replyTo: message.id, failed });
2056
3383
  }
2057
- async setAnswered(agentId, at) {
2058
- this.answered ??= await this.get(Keys.ANSWERED) ?? {};
2059
- const known = new Set(this.team.agents.map((agent) => agent.id));
2060
- const kept = Object.fromEntries(Object.entries(this.answered).filter(([id]) => known.has(id)));
2061
- this.answered = { ...kept, [agentId]: at };
2062
- await this.set(Keys.ANSWERED, this.answered);
2063
- }
2064
3384
  async ask(channel, message, agentId) {
2065
3385
  const agent = this.team.agents.find((candidate) => candidate.id === agentId);
2066
3386
  if (!agent) {
@@ -2069,7 +3389,7 @@ class TeamService {
2069
3389
  const sessionId = await this.session(agent);
2070
3390
  const before = await this.host.getState(sessionId);
2071
3391
  const history = await this.messagesOf(channel.id);
2072
- const input = { clientMessageId: `${message.id}:${agent.id}`, message: ChannelsUtil.prompt(this.team, channel, history, message, agent) };
3392
+ const input = { clientMessageId: `${message.id}:${agent.id}`, message: ChannelsText.prompt(this.team, channel, history, message, agent) };
2073
3393
  await this.host.prompt(sessionId, input);
2074
3394
  await this.settled(sessionId, before.messageCount);
2075
3395
  const { text } = await this.host.getLastAssistantText(sessionId);
@@ -2078,127 +3398,6 @@ class TeamService {
2078
3398
  }
2079
3399
  return text.trim();
2080
3400
  }
2081
- async pinDirectories() {
2082
- const loose = this.team.agents.filter((agent) => !agent.cwd);
2083
- if (loose.length === 0) {
2084
- return;
2085
- }
2086
- const serverCwd = (await this.host.getServerInfo()).cwd;
2087
- const pinned = new Map;
2088
- for (const agent of loose) {
2089
- pinned.set(agent.id, agent.sessionFile && await this.host.sessionCwd(agent.sessionFile) || serverCwd);
2090
- }
2091
- await this.saveTeam({ ...this.team, agents: this.team.agents.map((agent) => pinned.has(agent.id) ? { ...agent, cwd: pinned.get(agent.id) } : agent) });
2092
- }
2093
- session(agent) {
2094
- let opening = this.opening.get(agent.id);
2095
- if (!opening) {
2096
- opening = this.openSession(agent).finally(() => this.opening.delete(agent.id));
2097
- this.opening.set(agent.id, opening);
2098
- }
2099
- return opening;
2100
- }
2101
- async openSession(agent) {
2102
- if (agent.sessionFile) {
2103
- const open = (await this.host.listSessions()).find((session) => session.sessionFile === agent.sessionFile);
2104
- if (open) {
2105
- return open.sessionId;
2106
- }
2107
- }
2108
- const cwd = agent.cwd ?? (await this.host.getServerInfo()).cwd;
2109
- const options = { cwd, appendSystemPrompt: ChannelsUtil.systemPrompt(agent), group: NAME };
2110
- if (agent.sessionFile) {
2111
- try {
2112
- return (await this.host.openSession({ ...options, sessionFile: agent.sessionFile })).sessionId;
2113
- } catch (error) {
2114
- if (TaErrorUtil.code(error) !== TaErrorCode.INVALID_ARGUMENT) {
2115
- throw error;
2116
- }
2117
- }
2118
- }
2119
- const { sessionId } = await this.host.openSession(options);
2120
- await this.host.setSessionName(sessionId, agent.name);
2121
- const { sessionFile } = await this.host.getState(sessionId);
2122
- if (sessionFile) {
2123
- await this.saveTeam({ ...this.team, agents: this.team.agents.map((other) => other.id === agent.id ? { ...other, sessionFile } : other) });
2124
- }
2125
- return sessionId;
2126
- }
2127
- async settled(sessionId, before) {
2128
- const start = Date.now();
2129
- for (;; ) {
2130
- const state = await this.host.getState(sessionId);
2131
- if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
2132
- return;
2133
- }
2134
- if (Date.now() - start > this.options.timeoutMs) {
2135
- throw new Error("No answer in time; the agent may still be working in its session.");
2136
- }
2137
- await new Promise((resolve) => setTimeout(resolve, this.options.pollMs));
2138
- }
2139
- }
2140
- messagesOf(channelId) {
2141
- const known = this.messages.get(channelId);
2142
- if (known) {
2143
- return Promise.resolve(known);
2144
- }
2145
- let reading = this.reading.get(channelId);
2146
- if (!reading) {
2147
- reading = this.get(Keys.messages(channelId)).then((stored) => {
2148
- const messages = this.messages.get(channelId) ?? stored ?? [];
2149
- this.messages.set(channelId, messages);
2150
- return messages;
2151
- });
2152
- this.reading.set(channelId, reading);
2153
- }
2154
- return reading;
2155
- }
2156
- async append(channelId, message) {
2157
- if (!this.team.channels.some((channel) => channel.id === channelId)) {
2158
- return message;
2159
- }
2160
- await this.messagesOf(channelId);
2161
- const messages = ChannelsUtil.append(this.messages.get(channelId) ?? [], message);
2162
- this.messages.set(channelId, messages);
2163
- await this.set(Keys.messages(channelId), messages);
2164
- return message;
2165
- }
2166
- async saveTeam(team) {
2167
- this.team = team;
2168
- this.linkSessions();
2169
- await this.set(Keys.TEAM, team);
2170
- }
2171
- shareWithMembers() {
2172
- const team = this.host.team;
2173
- if (!team) {
2174
- return;
2175
- }
2176
- const can = (principal, kind, id) => team.can(principal, kind === "agent" ? "agent.view" : "channel.view", { kind, id });
2177
- team.shareData(NAME, {
2178
- keys: [Keys.TEAM, Keys.WORKING, Keys.ANSWERED, Keys.FOCUS, Keys.MESSAGES],
2179
- view: (principal, key, value) => {
2180
- const visible = TeamViewUtil.visible(this.team, (kind, id) => can(principal, kind, id));
2181
- if (key === Keys.TEAM) {
2182
- return TeamViewUtil.team(value, visible);
2183
- }
2184
- if (key.startsWith(Keys.MESSAGES)) {
2185
- return visible.channels.has(key.slice(Keys.MESSAGES.length)) ? value : undefined;
2186
- }
2187
- if (key === Keys.FOCUS) {
2188
- return visible.channels.has(value?.channelId ?? "") ? value : undefined;
2189
- }
2190
- return TeamViewUtil.byId(value, key === Keys.WORKING ? visible.channels : visible.agents);
2191
- }
2192
- });
2193
- this.linkSessions();
2194
- }
2195
- linkSessions() {
2196
- for (const agent of this.team.agents) {
2197
- if (agent.sessionFile) {
2198
- this.host.team?.link(agent.sessionFile, { kind: "agent", id: agent.id });
2199
- }
2200
- }
2201
- }
2202
3401
  listChannels() {
2203
3402
  return this.team.channels.map((channel) => ({
2204
3403
  id: channel.id,
@@ -2207,17 +3406,6 @@ class TeamService {
2207
3406
  members: channel.members
2208
3407
  }));
2209
3408
  }
2210
- async setWorking(channelId, agentId, on) {
2211
- const others = (this.working[channelId] ?? []).filter((id) => id !== agentId);
2212
- this.working = { ...this.working, [channelId]: on ? [...others, agentId] : others };
2213
- await this.set(Keys.WORKING, this.working);
2214
- }
2215
- async get(key) {
2216
- return await this.host.getExtensionData(NAME, key) ?? undefined;
2217
- }
2218
- set(key, value) {
2219
- return this.host.setExtensionData(NAME, key, value);
2220
- }
2221
3409
  }
2222
3410
 
2223
3411
  // web-src/host.ts