ai_co_discuss 0.4.90 → 0.4.91

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.
@@ -24,7 +24,7 @@ description: "AI CoDiscuss 的主持技能,仅主持人调用,且须同时
24
24
  1. **用户是需求方和最终决策者**:先处理尚未处理的用户留言,再安排他人或收束;遵守用户设定的上限,不自行放宽。(主持人负责理解意图,不替用户做决定。)
25
25
  2. **收束前自查**:收束、宣告完成(含 Goal 完成)或关闭定时检查前,对照任务里的 `room_goal` 和用户最近的要求;还有遗留方向就继续安排,或告诉用户还差什么。(一次派活或一个 Goal 做完,不等于房间任务完成。)
26
26
  3. **权限由用户授予**:不邀请成员,不开启讨论或 Goal,不扩大工作目录、软件权限或执行额度,派活不超出用户给的范围。唯一例外是任务有 `host_workflows: true`(房主打开了“主持人完整权限”),边界见 [房间控制与恢复](references/control.md)。(扩权与刹车留在用户手里。)
27
- 4. **有工作流先分流**:任务有 `workflow` 字段时,派活或改文件之前先读 `workflow.skill_path`,把请求对照主线和每个 `workflow.sub_workflows` 的 `description`;命中就读它的 SKILL.md 并照做,不问用户要不要用,回答开头写明走的哪条;写明只在用户要求时用的,用户没要求就不用。(靠临场想起来会漏掉,流程也就形同虚设。)
27
+ 4. **有工作流先分流**:任务有 `workflow` 字段时,派活或改文件之前先读 `workflow.skill_path`,把请求对照主线和每个 `workflow.sub_workflows` 的 `description`;命中就读它的 SKILL.md 并照做,不问用户要不要用,回答开头用一句话写明走的哪条;都不命中就按普通请求处理,回答里不必说明;写明只在用户要求时用的,用户没要求就不用。(靠临场想起来会漏掉,流程也就形同虚设。)
28
28
  5. **不用软件自带的定时、唤醒或后台等待**,也不手动通知已配置的本地成员;要隔一段时间再看进展用 `checkin`。(本轮结束即执行结束,之后回来的结果无法提交;自带唤醒还会和程序投递并发续接同一会话。)
29
29
 
30
30
  ## 主持判断
package/docs/en/runner.md CHANGED
@@ -71,7 +71,7 @@ If you deploy the site yourself, run this once on the machine running your agent
71
71
  codiscuss local connect https://your-site
72
72
  ```
73
73
 
74
- It binds this computer to the site with a one-time token: generated automatically on the machine that deployed the site (after `wrangler login`); otherwise run `codiscuss token` there first and add `--setup-key TOKEN`. Each token works once. Without the command line: in this computer's management panel, choose Bind under This computer → Online site and paste the access code generated on the deploying computer (Generate access code in the same place there, or `codiscuss admin entry code`). Inviting external experts also needs this binding. For a hosted account to invite external experts, turn on Allow inviting external experts for it on the Accounts page; the panel binds it for you, with no access code. The hosted site has no accounts or passwords and keeps no rooms: every device pairs with this computer first, then reads and writes its rooms through the relay, which must be deployed first (see "Relay" in the [deployment guide](deployment.md)). Revoke with `codiscuss local disconnect https://your-site`.
74
+ It binds this computer to the site with a one-time token: generated automatically on the machine that deployed the site (after `wrangler login`); otherwise run `codiscuss token` there first and add `--setup-key TOKEN`. Each token works once. Without the command line: in this computer's management panel, choose Bind under This computer → Online site and paste the access code generated on the deploying computer (Generate access code in the same place there, or `codiscuss admin entry code`). Inviting external experts also needs this binding. For a hosted account to invite external experts, turn on Allow inviting external experts for it on the Accounts page: with your own domain on, the other computer reaches the account directly through your domain, not the online site; otherwise the panel binds it to the online site for you. Neither needs an access code. The hosted site has no accounts or passwords and keeps no rooms: every device pairs with this computer first, then reads and writes its rooms through the relay, which must be deployed first (see "Relay" in the [deployment guide](deployment.md)). Revoke with `codiscuss local disconnect https://your-site`.
75
75
 
76
76
  ### From Other Devices
77
77
 
package/docs/runner.md CHANGED
@@ -85,7 +85,7 @@ Windows 上在终端运行 `codiscuss setup` 时,“安装配置”一步有
85
85
  codiscuss local connect https://你的站点
86
86
  ```
87
87
 
88
- 它用一次性绑定令牌把这台电脑绑定到网站:在部署网站的电脑上(已 `wrangler login`)自动生成,否则先在部署网站的电脑上运行 `codiscuss token`,再加 `--setup-key 令牌`。每个令牌只能用一次。也可以不用命令行:在这台电脑的管理面板“本机 → 线上网站”点“绑定”,粘贴部署网站的电脑生成的接入码(它的同一处“生成接入码”,或 `codiscuss admin entry code`),一步完成。邀请外部专家也需要先绑定。托管账号要邀请外部专家时,在“账号”页打开该账号的“允许邀请外部专家”,面板会自动替它绑定,不需要接入码。线上网站没有账号和密码,也不保存房间;任何设备都要先与这台电脑配对,再经中转读写电脑上的房间,需先部署中转(见[部署指南](deployment.md)“中转”)。撤销使用 `codiscuss local disconnect https://你的站点`。
88
+ 它用一次性绑定令牌把这台电脑绑定到网站:在部署网站的电脑上(已 `wrangler login`)自动生成,否则先在部署网站的电脑上运行 `codiscuss token`,再加 `--setup-key 令牌`。每个令牌只能用一次。也可以不用命令行:在这台电脑的管理面板“本机 → 线上网站”点“绑定”,粘贴部署网站的电脑生成的接入码(它的同一处“生成接入码”,或 `codiscuss admin entry code`),一步完成。邀请外部专家也需要先绑定。托管账号要邀请外部专家时,在“账号”页打开该账号的“允许邀请外部专家”:开着自有域名时,对方经你的域名直接连到这个账号,不经线上网站;否则面板自动替它绑定线上网站。两种都不需要接入码。线上网站没有账号和密码,也不保存房间;任何设备都要先与这台电脑配对,再经中转读写电脑上的房间,需先部署中转(见[部署指南](deployment.md)“中转”)。撤销使用 `codiscuss local disconnect https://你的站点`。
89
89
 
90
90
  ### 在其他设备上远程控制
91
91
 
@@ -376,7 +376,6 @@
376
376
  "已允许该账号邀请外部专家": "This account can now invite external experts",
377
377
  "已停止该账号邀请外部专家": "This account can no longer invite external experts",
378
378
  "允许邀请外部专家": "Allow inviting external experts",
379
- "这台电脑未绑定线上网站,请先在“概览 → 本机 → 线上网站”绑定": "This computer is not bound to an online site. Bind it first under Overview → This computer → Online site",
380
379
  "扫码配对过的设备可以在外面使用这台电脑": "Devices paired by QR code can use this computer from elsewhere",
381
380
  "需先在“本机 → 线上网站”绑定": "Bind under This computer → Online site first",
382
381
  "经线上网站中转": "Through the online site",
@@ -388,6 +387,7 @@
388
387
  "绑定共议线上网站(形如 https://xxx.pages.dev),不是你的自有域名": "Bind the CoDiscuss online site (like https://xxx.pages.dev), not your own domain",
389
388
  "在部署线上网站的电脑上生成(它的管理面板“本机 → 线上网站 → 生成接入码”,或运行 codiscuss admin entry code),只能用一次。就在那台电脑上绑定时,只填站点地址即可。": "Generate it on the computer that deployed the online site (its management panel: This computer → Online site → Generate access code, or run codiscuss admin entry code); each code works once. On that computer itself, the site address alone is enough.",
390
389
  "发给要绑定的电脑,在它的管理面板“本机 → 线上网站 → 绑定”里粘贴。只能用一次;再生成一个会让之前没用过的作废。": "Send it to the computer to bind and paste it in its management panel under This computer → Online site → Bind. It works once; generating another voids any unused earlier one.",
391
- "打开后自动替这个账号绑定线上网站,它就能在房间里邀请另一台电脑上的 AI": "Turning this on binds the account to the online site for it, so it can invite AI on other computers into its rooms",
392
- "不需要域名:经共议线上网站中转到这台电脑,手机和外地的电脑都能打开。": "No domain needed: relayed through the CoDiscuss online site to this computer, so phones and computers elsewhere can open it."
390
+ "不需要域名:经共议线上网站中转到这台电脑,手机和外地的电脑都能打开。": "No domain needed: relayed through the CoDiscuss online site to this computer, so phones and computers elsewhere can open it.",
391
+ "打开后,这个账号就能在房间里邀请另一台电脑上的 AI;关闭再打开后,之前加入的外部专家需要重新邀请": "Turned on, this account can invite AI on other computers into its rooms; after turning it off and on again, external experts who joined must be invited again",
392
+ "需要先开启托管账号入口的自有域名,或在“概览 → 本机 → 线上网站”绑定线上网站": "Turn on your own domain for the hosted account entry, or bind an online site under Overview → This computer → Online site, first"
393
393
  }
@@ -823,5 +823,7 @@
823
823
  "线上网站没有签发绑定令牌:{value1}": "The online site did not issue a binding token: {value1}",
824
824
  "绑定令牌已过期,请重试": "The binding token expired; try again",
825
825
  "线上网站没有释放这个账号:{value1}": "The online site did not release this account: {value1}",
826
- "请先关闭该账号的“允许邀请外部专家”,再更改隔离": "Turn off Allow inviting external experts for this account before changing its isolation"
826
+ "请先关闭该账号的“允许邀请外部专家”,再更改隔离": "Turn off Allow inviting external experts for this account before changing its isolation",
827
+ "没有建立直连身份": "The direct identity was not created",
828
+ "还有托管账号经自有域名邀请外部专家,请先在“账号”页关闭它们的“允许邀请外部专家”": "Some hosted accounts invite external experts through your own domain; turn off Allow inviting external experts for them on the Accounts page first"
827
829
  }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * The three addresses an external member's computer uses, answered by the sign-in entry on the owner's own domain for
3
+ * hosted accounts that invite external experts without the online relay (user 2026-11-19, #5588; security #5599):
4
+ *
5
+ * GET /api/machines the accounts reached directly: id and public keys under a neutral name
6
+ * POST /api/machines/<id>/pair a sealed invite redemption, handed to that account's receiver
7
+ * POST /api/machines/<id>/relay a member's sealed request, handed to that account's receiver
8
+ *
9
+ * They are answered only when the request comes in on the owner's domain (its Host), the tunnel is on, and the request
10
+ * carries no live session; everything else goes through the entry as before. What this never does:
11
+ * - pass anything from the account's receiver to the caller but a status and a sealed reply it re-serialises itself, with
12
+ * fixed headers, so an account cannot put a page of its own on the entry's address (#8);
13
+ * - add the entry's handshake, a cookie or the caller's path when calling the receiver: the path is fixed and the
14
+ * member's path travels in the body, so an account that points its `local/direct.json` elsewhere gains nothing (#9);
15
+ * - serve more at once than a few requests per account and in all, nor more redemptions than the limits below (#11, #12).
16
+ * Which computer id belongs to which account is the panel's (`direct-accounts.json` in the administrator's directory).
17
+ */
18
+ import http from 'node:http';
19
+ import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+
22
+ export const DIRECT_ACCOUNTS_FILE = 'direct-accounts.json';
23
+ const RECEIVER_FILE = join('local', 'direct.json');
24
+ const RECEIVER_PATH = '/direct';
25
+ const RECEIVER_TOKEN_HEADER = 'x-codiscuss-direct';
26
+ const BODY_MAX = 512 * 1024;
27
+ // A member's computer sends its request at once; a slow sender is cut off and only ever holds a cheap reading slot (#5617).
28
+ const READ_TIMEOUT_MS = 5_000;
29
+ const READING_MAX = 64;
30
+ // The receiver file is the account's to write: read only a small one (#5617).
31
+ const RECEIVER_FILE_MAX = 16 * 1024;
32
+ const KEY_PART = /^[A-Za-z0-9_-]{1,64}$/;
33
+ // The online relay holds a request at most this long (backend/updates.mjs RELAY_MAX_WAIT_MS).
34
+ const WAIT_MAX_MS = 80_000;
35
+ const REPLY_MAX = 4 * 1024 * 1024;
36
+ const GLOBAL_CONCURRENT = 16;
37
+ const ACCOUNT_CONCURRENT = 4;
38
+ // Redemptions: per sending address as the online site allows (worker.mjs limit_pairing), and per account in all.
39
+ const PAIR_WINDOW_MS = 10 * 60 * 1000;
40
+ const PAIR_PER_SOURCE = 10;
41
+ const PAIR_PER_ACCOUNT = 40;
42
+ const ID_PATTERN = /^[A-Za-z0-9_-]{16,80}$/;
43
+ const MACHINE_PATTERN = /^[0-9a-f]{32}$/;
44
+ const ROUTE = /^\/api\/machines\/([0-9a-f]{32})\/(pair|relay)$/;
45
+ const HEADERS = { 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store' };
46
+
47
+ function answer(response, status, value) {
48
+ response.writeHead(status, HEADERS);
49
+ response.end(JSON.stringify(value));
50
+ }
51
+
52
+ function read_json(path) {
53
+ try { return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {}; } catch { return {}; }
54
+ }
55
+
56
+ /** The owner's domain the tunnel serves, or '' while the tunnel is off. */
57
+ function direct_host(settings) {
58
+ return settings.tunnel_enabled && settings.tunnel?.host ? String(settings.tunnel.host).toLowerCase() : '';
59
+ }
60
+
61
+ /** One account's receiver as its discussion service published it, refusing a folder that is a link (#9). */
62
+ function read_receiver(home) {
63
+ for (const path of [home, join(home, 'local')]) {
64
+ try { if (lstatSync(path).isSymbolicLink()) return null; } catch { return null; }
65
+ }
66
+ const file = join(home, RECEIVER_FILE);
67
+ let receiver;
68
+ try {
69
+ if (lstatSync(file).isSymbolicLink()) return null;
70
+ // The limit is kept by the read itself, not by a size checked before it that could change in between (#5625).
71
+ const fd = openSync(file, 'r'), buffer = Buffer.alloc(RECEIVER_FILE_MAX + 1);
72
+ let size;
73
+ try { size = readSync(fd, buffer, 0, buffer.length, 0); } finally { closeSync(fd); }
74
+ if (size > RECEIVER_FILE_MAX) return null;
75
+ receiver = JSON.parse(buffer.subarray(0, size).toString('utf8'));
76
+ } catch { return null; }
77
+ const valid = Number.isInteger(receiver.port) && receiver.port > 0 && receiver.port < 65536 && typeof receiver.token === 'string'
78
+ && /^[0-9a-f]{64}$/.test(receiver.token) && typeof receiver.machine === 'string' && MACHINE_PATTERN.test(receiver.machine);
79
+ return valid ? { port: receiver.port, token: receiver.token, machine: receiver.machine, public_key: public_key(receiver.public_key), sign_key: public_key(receiver.sign_key) } : null;
80
+ }
81
+
82
+ /** A P-256 public key rebuilt from its four fields, or null: nothing else the account wrote is passed on (#5617). */
83
+ function public_key(value) {
84
+ if (!value || typeof value !== 'object' || value.kty !== 'EC' || value.crv !== 'P-256' || !KEY_PART.test(String(value.x)) || !KEY_PART.test(String(value.y))) return null;
85
+ return { kty: 'EC', crv: 'P-256', x: value.x, y: value.y };
86
+ }
87
+
88
+ /** Read a JSON body up to BODY_MAX within READ_TIMEOUT_MS. */
89
+ function read_body(request) {
90
+ return new Promise((done, fail) => {
91
+ const parts = [];
92
+ let size = 0;
93
+ const timer = setTimeout(() => { request.destroy(); fail(Object.assign(new Error('读取超时'), { status: 408 })); }, READ_TIMEOUT_MS);
94
+ request.on('data', part => {
95
+ size += part.length;
96
+ if (size > BODY_MAX) { clearTimeout(timer); request.destroy(); fail(Object.assign(new Error('请求过大'), { status: 413 })); return; }
97
+ parts.push(part);
98
+ });
99
+ request.on('end', () => { clearTimeout(timer); try { done(JSON.parse(Buffer.concat(parts).toString('utf8'))); } catch { fail(Object.assign(new Error('请求格式无效'), { status: 400 })); } });
100
+ request.on('error', error => { clearTimeout(timer); fail(error); });
101
+ });
102
+ }
103
+
104
+ /** Call one receiver; resolves `{ status, body }`, or null when it could not be reached or did not answer in time. */
105
+ function call_receiver(receiver, payload, timeout_ms) {
106
+ return new Promise(done => {
107
+ const text = JSON.stringify(payload);
108
+ const upstream = http.request({ host: '127.0.0.1', port: receiver.port, path: RECEIVER_PATH, method: 'POST', timeout: timeout_ms,
109
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(text), [RECEIVER_TOKEN_HEADER]: receiver.token } }, reply => {
110
+ const parts = [];
111
+ let size = 0;
112
+ reply.on('data', part => { size += part.length; if (size > REPLY_MAX) { reply.destroy(); done(null); } else parts.push(part); });
113
+ reply.on('end', () => { try { done({ status: reply.statusCode, body: JSON.parse(Buffer.concat(parts).toString('utf8')) }); } catch { done(null); } });
114
+ reply.on('error', () => done(null));
115
+ });
116
+ upstream.on('timeout', () => { upstream.destroy(); done(null); });
117
+ upstream.on('error', () => done(null));
118
+ upstream.end(text);
119
+ });
120
+ }
121
+
122
+ /** Only a sealed reply in the relay's shape, rebuilt field by field (#8). */
123
+ function sealed_reply(id, body) {
124
+ const response = body?.response;
125
+ if (body?.id !== id || body?.status !== 'done' || !response || typeof response.iv !== 'string' || typeof response.data !== 'string'
126
+ || response.iv.length > 64 || response.data.length > REPLY_MAX) return null;
127
+ return { id, status: 'done', response: { iv: response.iv, data: response.data, ...(response.encoding === 'gzip' ? { encoding: 'gzip' } : {}) } };
128
+ }
129
+
130
+ /**
131
+ * Build the direct handler for one entry. Returns `handle(request, response, signed_in)`, true when it answered the
132
+ * request; `data` is the administrator's directory, `instance_home(data, name)` an account's service directory.
133
+ */
134
+ export function create_direct({ data, read_accounts, entry_settings, instance_home, now = Date.now }) {
135
+ let active = 0, reading = 0;
136
+ const per_account = new Map(), pairs = new Map();
137
+
138
+ /** Count one redemption against its source and account; false once either is over its limit. */
139
+ function allow_pair(source, name) {
140
+ const at = now();
141
+ const fresh = list => (list || []).filter(time => at - time < PAIR_WINDOW_MS);
142
+ const by_source = fresh(pairs.get(`s:${source}`)), by_account = fresh(pairs.get(`a:${name}`));
143
+ if (by_source.length >= PAIR_PER_SOURCE || by_account.length >= PAIR_PER_ACCOUNT) {
144
+ pairs.set(`s:${source}`, by_source); pairs.set(`a:${name}`, by_account);
145
+ return false;
146
+ }
147
+ pairs.set(`s:${source}`, [...by_source, at]); pairs.set(`a:${name}`, [...by_account, at]);
148
+ if (pairs.size > 10_000) for (const [key, list] of pairs) if (!fresh(list).length) pairs.delete(key);
149
+ return true;
150
+ }
151
+
152
+ /** The accounts reached directly: id → name, for accounts that exist and are not disabled. */
153
+ function direct_accounts() {
154
+ const accounts = read_accounts(data), mapped = read_json(join(data, DIRECT_ACCOUNTS_FILE));
155
+ return Object.entries(mapped).filter(([id, name]) => MACHINE_PATTERN.test(id) && accounts[name] && !accounts[name].disabled);
156
+ }
157
+
158
+ return async function handle(request, response, signed_in) {
159
+ if (signed_in) return false;
160
+ const path = new URL(request.url, 'http://entry').pathname;
161
+ const route = ROUTE.exec(path);
162
+ if (!route && path !== '/api/machines') return false;
163
+ // Only these addresses read the entry's settings, so signed-in pages pay nothing for this (#5617).
164
+ const host = direct_host(entry_settings(data));
165
+ if (!host || String(request.headers.host || '').toLowerCase() !== host) return false;
166
+ if (path === '/api/machines') {
167
+ if (request.method !== 'GET') return false;
168
+ const machines = [];
169
+ for (const [id, name] of direct_accounts()) {
170
+ const receiver = read_receiver(instance_home(data, name));
171
+ if (receiver?.machine === id && receiver.public_key && receiver.sign_key) {
172
+ machines.push({ id, name: '托管账号', public_key: receiver.public_key, sign_key: receiver.sign_key, online: true, projects: [], clients: {} });
173
+ }
174
+ }
175
+ answer(response, 200, { machines });
176
+ return true;
177
+ }
178
+ if (request.method !== 'POST') { request.resume(); answer(response, 404, { error: '地址不存在' }); return true; }
179
+ const [, machine, kind] = route;
180
+ const name = direct_accounts().find(([id]) => id === machine)?.[1];
181
+ if (!name) { request.resume(); answer(response, 404, { error: '这台电脑尚未连接网站' }); return true; }
182
+ // Cloudflare writes the sending address on the way in through the tunnel.
183
+ const source = String(request.headers['cf-connecting-ip'] || request.socket.remoteAddress || 'unknown');
184
+ if (kind === 'pair' && !allow_pair(source, name)) { request.resume(); answer(response, 429, { error: '配对尝试过于频繁,请稍后再试' }); return true; }
185
+ // The body is announced and small; it is read in a slot of its own, apart from the slots the receiver is called in.
186
+ const length = Number(request.headers['content-length']);
187
+ if (!Number.isInteger(length) || length <= 0 || length > BODY_MAX) { request.resume(); answer(response, length > BODY_MAX ? 413 : 411, { error: '请求须注明长度且不超过上限' }); return true; }
188
+ if (reading >= READING_MAX) { request.resume(); answer(response, 503, { error: '请求过多,请稍后再试' }); return true; }
189
+ reading += 1;
190
+ let body;
191
+ try { body = await read_body(request); } catch (error) { answer(response, error.status || 400, { error: error.message }); return true; }
192
+ finally { reading -= 1; }
193
+ const { id, envelope, wait } = body || {};
194
+ if (typeof id !== 'string' || !ID_PATTERN.test(id) || !envelope || typeof envelope !== 'object') { answer(response, 400, { error: '命令编号无效' }); return true; }
195
+ if (active >= GLOBAL_CONCURRENT || (per_account.get(name) || 0) >= ACCOUNT_CONCURRENT) { answer(response, 503, { error: '请求过多,请稍后再试' }); return true; }
196
+ active += 1;
197
+ per_account.set(name, (per_account.get(name) || 0) + 1);
198
+ try {
199
+ const receiver = read_receiver(instance_home(data, name));
200
+ if (!receiver || receiver.machine !== machine) { answer(response, 200, { id, status: 'offline' }); return true; }
201
+ const timeout = Math.min(Math.max(Number.isInteger(wait) ? wait : 8000, 1000), WAIT_MAX_MS);
202
+ const result = await call_receiver(receiver, { kind, path, credential: String(request.headers['x-codiscuss-device'] || ''), id, envelope }, timeout);
203
+ if (!result) { answer(response, 200, { id, status: 'unknown' }); return true; }
204
+ if (result.status === 200) {
205
+ const reply = sealed_reply(id, result.body);
206
+ reply ? answer(response, 200, reply) : answer(response, 200, { id, status: 'unknown' });
207
+ return true;
208
+ }
209
+ // A refusal keeps only its kind; the receiver's own words are not passed on.
210
+ const refusal = { 400: '请求格式无效', 401: '这台设备没有与电脑配对,或配对已失效', 403: '这个入口只接受外部成员的请求', 404: '地址不存在', 413: '请求过大', 503: '请求过多,请稍后再试' };
211
+ const status = refusal[result.status] ? result.status : 502;
212
+ answer(response, status, { error: refusal[status] || '暂时无法处理' });
213
+ return true;
214
+ } finally {
215
+ active -= 1;
216
+ per_account.set(name, per_account.get(name) - 1);
217
+ }
218
+ };
219
+ }
@@ -18,6 +18,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
18
18
  import { parseArgs } from 'node:util';
19
19
 
20
20
  import { ENTRY_KEY_PATTERN, verified_connection } from '../runner/entry_client.mjs';
21
+ import { create_direct } from './direct.mjs';
21
22
  import { login_page } from './login_page.mjs';
22
23
 
23
24
  const SESSION_COOKIE = 'codiscuss_entry';
@@ -417,6 +418,8 @@ export function instance_key(data, name) {
417
418
  export function create_gateway({ data, now = Date.now }) {
418
419
  const sessions = load_sessions(data, now());
419
420
  const failures = new Map();
421
+ // External members' computers reach hosted accounts on the owner's domain without the online relay (#5588).
422
+ const direct = create_direct({ data, read_accounts, entry_settings, instance_home, now });
420
423
  const save_sessions = () => write_json(join(data, SESSIONS_FILE), Object.fromEntries(sessions));
421
424
 
422
425
  /** The account a request's session still grants, or null; a session that no longer grants access is dropped. */
@@ -462,6 +465,7 @@ export function create_gateway({ data, now = Date.now }) {
462
465
  return send(response, 303, { Location: LOGIN_PATH, 'Set-Cookie': cookie_header(request, '', 0) });
463
466
  }
464
467
  const account = account_of(request);
468
+ if (await direct(request, response, Boolean(account))) return;
465
469
  // The site asks this to tell a page opened through the entry from one opened at the instance itself.
466
470
  if (path === SESSION_PATH && request.method === 'GET') return account ? send_json(response, 200, { signed_in: true }) : send_json(response, 401, { error: '请先登录' });
467
471
  if (account) return forward(request, response, account.port, { protected: account.protected === true, key: account.protected === true ? instance_key(data, account.name) : '' });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.90",
3
+ "version": "0.4.91",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -15,6 +15,8 @@
15
15
  * status the skills installed, the prompt, and whether the layout is complete.
16
16
  * skills install the skill folders in <job>/skills/ (replacing a copy of the same name) and remove request.remove.
17
17
  * prompt write request.prompt as the system prompt of all three.
18
+ * direct create (request.site, the owner's domain) or remove (request.remove) the direct identity of the service
19
+ * home request.home, with which external members reach this account on that domain; sealed for this user.
18
20
  * site bind the service home request.home to the online site request.site with the one-time child token
19
21
  * request.setup_key, or remove that binding (request.unbind); the binding file is sealed for this user.
20
22
  */
@@ -153,13 +155,20 @@ async function site(request) {
153
155
  return { machine: await bind_machine(request.home, request.site, request.setup_key) };
154
156
  }
155
157
 
158
+ /** Create or remove this user's direct identity; the panel records which computer id is which account. */
159
+ async function direct(request) {
160
+ const { create_direct_link, remove_direct_link } = await import('./remote_launch.mjs');
161
+ if (request.remove) { remove_direct_link(request.home); return { ok: true }; }
162
+ return { machine: create_direct_link(request.home, request.site).id };
163
+ }
164
+
156
165
  async function main() {
157
166
  const [action, job] = process.argv.slice(2);
158
167
  const path = join(job, 'request.json');
159
168
  const request = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
160
169
  // The job folder is the owner's; the request goes when the owner removes it.
161
170
  try { rmSync(path, { force: true }); } catch { /* removed with the job folder */ }
162
- const run = { init, status, skills: () => skills(job, request), prompt, site }[action];
171
+ const run = { init, status, skills: () => skills(job, request), prompt, site, direct }[action];
163
172
  if (!run) throw new Error(`未知操作:${action}`);
164
173
  process.stdout.write(`${JSON.stringify(await run(request))}\n`);
165
174
  }
@@ -24,6 +24,7 @@ import { API_PROVIDERS, save_api_key } from './discussion_api.mjs';
24
24
  import { STT_PROVIDERS, TTS_PROVIDERS } from './tts_providers.mjs';
25
25
  import { ensure_tunnel, start_tunnel_setup, tunnel_setup_state, tunnel_status } from './hosting_tunnel.mjs';
26
26
  import { machine_links } from './remote_launch.mjs';
27
+ import { DIRECT_ACCOUNTS_FILE } from '../gateway/direct.mjs';
27
28
  import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
28
29
  import { clear_instance_flag, create_os_user, install_shared_runtime, instance_key_file, place_instance_key, read_os_users, remove_os_user, run_as_user, shared_cli_state, shared_executables, shared_paths,
29
30
  start_instance_as_user } from './os_users.mjs';
@@ -741,7 +742,10 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
741
742
  return op.entry_overview(data);
742
743
  }
743
744
  // How people outside reach the entry, the relay's entry address, and binding this computer to an online site.
744
- if (method === 'POST' && section === 'entry' && name === 'way') return op.set_entry_way(data, String(body.way || ''), body.enabled === true);
745
+ if (method === 'POST' && section === 'entry' && name === 'way') {
746
+ if (body.way === 'tunnel' && body.enabled !== true) keep_direct_domain(data);
747
+ return op.set_entry_way(data, String(body.way || ''), body.enabled === true);
748
+ }
745
749
  if (method === 'POST' && section === 'entry' && name === 'relay') return op.set_relay_url(data, body.url);
746
750
  // The access code: made on the computer that deployed the online site, pasted on a hosting computer.
747
751
  if (method === 'GET' && section === 'site' && name === 'code') return { ...deploy_settings(data), site: deploy_settings(data).site || bound_site(data)?.site || '' };
@@ -750,6 +754,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
750
754
  // The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
751
755
  if (section === 'tunnel' && name === 'setup') {
752
756
  if (method === 'GET') return tunnel_setup_state(data);
757
+ // Another domain would leave the accounts reached through this one with invites to the old address.
758
+ if (method === 'POST' && String(body.host || '').toLowerCase() !== String(entry_settings(data).tunnel?.host || '').toLowerCase()) keep_direct_domain(data);
753
759
  if (method === 'POST') return op.start_tunnel_setup(data, body.host, body.name);
754
760
  }
755
761
  if (method === 'POST' && section === 'entry' && name === 'settings') { save_entry_settings(data, { public_url: body.public_url }); return op.entry_overview(data); }
@@ -1043,7 +1049,8 @@ function disconnect_site(data) {
1043
1049
  const bound = bound_site(data);
1044
1050
  if (!bound) return { disconnected: '' };
1045
1051
  if (entry_settings(data).relay_enabled) throw panel_error('托管账号入口的线上网站还开着,请先关闭它');
1046
- if (Object.keys(read_account_sites(data)).length) throw panel_error('还有托管账号开着“允许邀请外部专家”,请先在“账号”页关闭');
1052
+ // Accounts reached on the owner's domain do not use the online site; only the ones bound to it hold it (#5617).
1053
+ if (Object.values(read_account_sites(data)).some(record => !record.direct)) throw panel_error('还有托管账号开着“允许邀请外部专家”,请先在“账号”页关闭');
1047
1054
  save_site_connection(data, bound.site);
1048
1055
  return { disconnected: bound.site };
1049
1056
  }
@@ -1064,12 +1071,20 @@ function read_account_sites(data) {
1064
1071
  * under the cap comes back; a failure stops here for a retry), then the account's own binding is removed. An account
1065
1072
  * being removed lets go of the record whatever happens. Off by default.
1066
1073
  */
1067
- async function set_account_external(data, name, on, bind = bind_account_site, { removing = false } = {}) {
1074
+ async function set_account_external(data, name, on, bind = bind_account_site, { removing = false, direct = direct_account_site } = {}) {
1068
1075
  const sites = read_account_sites(data);
1069
1076
  const save = () => write_settings(join(data, ACCOUNT_SITES_FILE), sites);
1070
1077
  if (!on) {
1071
1078
  const record = sites[name];
1072
1079
  if (!record) return { external: false };
1080
+ if (record.direct) {
1081
+ // Reached on the owner's domain: the entry stops answering for it first, then its direct identity goes.
1082
+ write_direct_accounts(data, Object.fromEntries(Object.entries(read_direct_accounts(data)).filter(([, account]) => account !== name)));
1083
+ try { await direct(data, name, { site: record.site, remove: true }); } catch (error) { if (!removing) throw error; }
1084
+ delete sites[name];
1085
+ save();
1086
+ return { external: false };
1087
+ }
1073
1088
  // The site's slot first: a failure stops here so it can be retried, never leaving a slot held with nothing bound.
1074
1089
  // An account being removed lets go of the record whatever happens, or the owner could never unbind afterwards.
1075
1090
  try { await release_account_site(data, record); } catch (error) { if (!removing) throw error; }
@@ -1078,6 +1093,24 @@ async function set_account_external(data, name, on, bind = bind_account_site, {
1078
1093
  save();
1079
1094
  return { external: false };
1080
1095
  }
1096
+ // With the owner's domain on, external members reach the account through it, never the online relay (#5588).
1097
+ const settings = entry_settings(data);
1098
+ const wants_direct = Boolean(settings.tunnel_enabled && settings.tunnel?.host);
1099
+ // Already on: the same way stays; the other way is turned off first, so no slot or identity is left behind (#5617).
1100
+ if (sites[name]) {
1101
+ if (Boolean(sites[name].direct) === wants_direct) return { external: true, site: sites[name].site };
1102
+ await set_account_external(data, name, false, bind, { direct });
1103
+ delete sites[name];
1104
+ }
1105
+ if (wants_direct) {
1106
+ const site = `https://${settings.tunnel.host}`;
1107
+ const result = await direct(data, name, { site });
1108
+ if (!/^[0-9a-f]{32}$/.test(String(result.machine || ''))) throw panel_error('没有建立直连身份');
1109
+ write_direct_accounts(data, { ...Object.fromEntries(Object.entries(read_direct_accounts(data)).filter(([, account]) => account !== name)), [result.machine]: name });
1110
+ sites[name] = { site, machine: result.machine, direct: true, at: Date.now() };
1111
+ save();
1112
+ return { external: true, site };
1113
+ }
1081
1114
  const bound = bound_site(data);
1082
1115
  if (!bound) throw panel_error('这台电脑未绑定线上网站,请在管理面板“本机 → 线上网站”处绑定');
1083
1116
  const answer = await fetch_outside(`${bound.site}/api/machines/${bound.machine}/setup`, OUTSIDE_TIMEOUT_MS,
@@ -1097,6 +1130,30 @@ async function set_account_external(data, name, on, bind = bind_account_site, {
1097
1130
  return { external: true, site: bound.site };
1098
1131
  }
1099
1132
 
1133
+ /** Refuse a change to the owner's domain while accounts are reached through it: their members would be cut off (#5617). */
1134
+ function keep_direct_domain(data) {
1135
+ if (Object.values(read_account_sites(data)).some(record => record.direct)) {
1136
+ throw panel_error('还有托管账号经自有域名邀请外部专家,请先在“账号”页关闭它们的“允许邀请外部专家”');
1137
+ }
1138
+ }
1139
+
1140
+ /** Which computer id is which account on the owner's domain, for the sign-in entry (gateway/direct.mjs). */
1141
+ function read_direct_accounts(data) {
1142
+ try { return JSON.parse(readFileSync(join(data, DIRECT_ACCOUNTS_FILE), 'utf8')); } catch { return {}; }
1143
+ }
1144
+ function write_direct_accounts(data, mapping) {
1145
+ write_settings(join(data, DIRECT_ACCOUNTS_FILE), mapping);
1146
+ }
1147
+
1148
+ /** Create or remove an account's direct identity, as its own Windows user when it has one (the identity is sealed for it). */
1149
+ async function direct_account_site(data, name, { site, remove = false }) {
1150
+ const home = instance_home(data, name);
1151
+ if (read_os_users(data)[name]) return account_env(data, name, 'direct', { home, site, remove });
1152
+ const { create_direct_link, remove_direct_link } = await import('./remote_launch.mjs');
1153
+ if (remove) { remove_direct_link(home); return { ok: true }; }
1154
+ return { machine: create_direct_link(home, site).id };
1155
+ }
1156
+
1100
1157
  /** Ask the online site to let go of an account's computer; a site without this (older) or without it any more is done. */
1101
1158
  async function release_account_site(data, record) {
1102
1159
  const owner = machine_links(data).sites[record.site];