ai_co_discuss 0.4.64 → 0.4.65
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/.agents/skills/discuss-host/SKILL.md +1 -1
- package/.agents/skills/discuss-participant/SKILL.md +1 -0
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/backend/free_room.py +6 -1
- package/backend/schema.sql +2 -2
- package/backend/server.py +1 -1
- package/docs/architecture.md +1 -0
- package/docs/en/architecture.md +1 -0
- package/docs/en/runner.md +35 -1
- package/docs/runner.md +35 -1
- package/frontend/locales/en/external.json +34 -7
- package/package.json +2 -2
- package/runner/adapters/claude.mjs +5 -3
- package/runner/discussion_launch.mjs +3 -1
- package/runner/expert_prompts.mjs +7 -3
- package/runner/external_client.mjs +132 -62
- package/runner/external_gateway.mjs +70 -49
- package/runner/i18n_en.mjs +2 -1
- package/runner/remote_policy.mjs +7 -0
- package/runner/repo_read.mjs +6 -4
- package/runner/scheduler.mjs +3 -2
- package/web/admin.js +1 -1
- package/web/i18n.js +1 -1
- package/web/join.html +61 -29
- package/web/modern.css +1 -1
- package/web/modern.js +239 -46
|
@@ -29,6 +29,11 @@ export const BORROW_DEFAULTS = { max_wakes: 20, hours: 24 };
|
|
|
29
29
|
const MAX_WAKES_LIMIT = 1000;
|
|
30
30
|
const MAX_HOURS = 720;
|
|
31
31
|
const HISTORY_LIMIT = 50;
|
|
32
|
+
// What this computer keeps of each request its AI received and each answer it gave, so the history still reads after the
|
|
33
|
+
// inviting room can no longer be reached.
|
|
34
|
+
const TEXT_LIMIT = 4000;
|
|
35
|
+
// How often a pass also reads the member's current grant (`/view`) when nothing is woken; a wake and the room view always read it.
|
|
36
|
+
const VIEW_REFRESH_MS = 60000;
|
|
32
37
|
const HOUR_MS = 3600000;
|
|
33
38
|
// The website gives up on a relayed request after 9 seconds; ask for an answer within that.
|
|
34
39
|
const RELAY_WAIT_MS = 8000;
|
|
@@ -75,6 +80,23 @@ let secret_codec = process.platform === 'win32' ? DPAPI_CODEC : PLAIN_CODEC;
|
|
|
75
80
|
/** Tests replace the Windows sealing, which starts PowerShell, with the plain file form. */
|
|
76
81
|
export function use_plain_secrets() { secret_codec = PLAIN_CODEC; }
|
|
77
82
|
|
|
83
|
+
/**
|
|
84
|
+
* An error the page can show in its own language: the Chinese template and its parameters (`error_text`, as the
|
|
85
|
+
* website's errors carry) and a stable `code`, beside the message in this command line's language.
|
|
86
|
+
*/
|
|
87
|
+
function failure(code, template, params, extra = {}) {
|
|
88
|
+
return Object.assign(new Error(t(template, params)), { code, error_text: { template, params: params || {} }, ...extra });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** An error refused by the other side, keeping its own text, template and code when it gave them. */
|
|
92
|
+
function remote_failure(body, code, template, params, extra = {}) {
|
|
93
|
+
if (!body?.error) return failure(code, template, params, extra);
|
|
94
|
+
return Object.assign(new Error(body.error), { code: body.code || code, ...(body.error_text ? { error_text: body.error_text } : {}), ...extra });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** What a failure leaves for the page beside its message. */
|
|
98
|
+
const failure_fields = error => ({ ...(error?.code && typeof error.code === 'string' ? { code: error.code } : {}), ...(error?.error_text ? { error_text: error.error_text } : {}) });
|
|
99
|
+
|
|
78
100
|
// ---- Store ----
|
|
79
101
|
|
|
80
102
|
function external_home(home) {
|
|
@@ -110,7 +132,7 @@ function with_store(home, task) {
|
|
|
110
132
|
try { writeFileSync(lock, String(process.pid), { flag: 'wx' }); break; } catch (error) {
|
|
111
133
|
if (error.code !== 'EEXIST') throw error;
|
|
112
134
|
try { if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) { rmSync(lock, { force: true }); continue; } } catch { continue; }
|
|
113
|
-
if (Date.now() > deadline) throw
|
|
135
|
+
if (Date.now() > deadline) throw failure('store_busy', '被邀请记录正被占用,请稍后重试');
|
|
114
136
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
115
137
|
}
|
|
116
138
|
}
|
|
@@ -135,7 +157,7 @@ export function record_view(record, store) {
|
|
|
135
157
|
|
|
136
158
|
function find_record(store, id) {
|
|
137
159
|
const record = store.records[String(id || '')];
|
|
138
|
-
if (!record) throw
|
|
160
|
+
if (!record) throw failure('record_not_found', '没有这条被邀请记录:{id}', { id });
|
|
139
161
|
return record;
|
|
140
162
|
}
|
|
141
163
|
|
|
@@ -151,7 +173,7 @@ function change_record(home, id, change) {
|
|
|
151
173
|
|
|
152
174
|
function clean_site(value) {
|
|
153
175
|
const url = new URL(String(value || ''));
|
|
154
|
-
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw
|
|
176
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw failure('invalid_site', '站点地址无效');
|
|
155
177
|
return url.origin;
|
|
156
178
|
}
|
|
157
179
|
|
|
@@ -160,7 +182,7 @@ function invite_fields(fragment) {
|
|
|
160
182
|
const value = JSON.parse(Buffer.from(fragment.replace(/^#/, ''), 'base64url').toString('utf8'));
|
|
161
183
|
if (value && typeof value === 'object') return value;
|
|
162
184
|
} catch { /* Not an invitation payload. */ }
|
|
163
|
-
throw
|
|
185
|
+
throw failure('invalid_link', '邀请链接无效,请向对方重新索取');
|
|
164
186
|
}
|
|
165
187
|
|
|
166
188
|
/**
|
|
@@ -177,12 +199,12 @@ export function parse_invite(invite, { site = '', machine = '' } = {}) {
|
|
|
177
199
|
fields.site ||= url.origin;
|
|
178
200
|
} else fields = { code: text, site, machine };
|
|
179
201
|
const code = String(fields.code || '').toUpperCase().replace(/[^0-9A-Z]/g, '');
|
|
180
|
-
if (!CODE_PATTERN.test(code)) throw
|
|
181
|
-
if (!fields.site) throw
|
|
202
|
+
if (!CODE_PATTERN.test(code)) throw failure('invalid_code', '配对码格式不对:应为 12 位字母数字');
|
|
203
|
+
if (!fields.site) throw failure('site_required', '配对码须同时给出对方的线上站点(--site)');
|
|
182
204
|
const machine_id = String(fields.machine || machine || '');
|
|
183
|
-
if (machine_id && !HEX32.test(machine_id)) throw
|
|
205
|
+
if (machine_id && !HEX32.test(machine_id)) throw failure('invalid_machine', '电脑编号格式不对');
|
|
184
206
|
const fingerprint = String(fields.fp || '');
|
|
185
|
-
if (fingerprint && !HEX32.test(fingerprint)) throw
|
|
207
|
+
if (fingerprint && !HEX32.test(fingerprint)) throw failure('invalid_fingerprint', '邀请链接里的电脑指纹无效');
|
|
186
208
|
return { site: clean_site(fields.site), machine: machine_id, fingerprint, code, room_name: String(fields.room_name || ''),
|
|
187
209
|
machine_name: String(fields.machine_name || ''), level: ['read', 'discuss'].includes(fields.level) ? fields.level : '', expires_at: Number(fields.expires_at) || null };
|
|
188
210
|
}
|
|
@@ -212,12 +234,12 @@ export function invite_proof(code, machine, jwk) {
|
|
|
212
234
|
export async function machine_keys(site, machine, { fetcher = fetch } = {}) {
|
|
213
235
|
let response;
|
|
214
236
|
try { response = await fetcher(`${site}/api/machines`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); }
|
|
215
|
-
catch (error) { throw Object.assign(
|
|
237
|
+
catch (error) { throw Object.assign(failure('site_unreachable', '连不上对方的线上站点 {site}:{reason}', { site, reason: error.message }), { offline: true }); }
|
|
216
238
|
const body = await response.json().catch(() => ({}));
|
|
217
239
|
const list = (Array.isArray(body) ? body : body.machines || []).filter(item => item?.public_key && item?.sign_key);
|
|
218
|
-
if (!machine && list.length > 1) throw
|
|
240
|
+
if (!machine && list.length > 1) throw failure('machine_required', '对方站点连着多台电脑,请用 --machine 指定电脑编号:{ids}', { ids: list.map(item => `${item.id}(${item.name || ''})`).join('、') });
|
|
219
241
|
const found = machine ? list.find(item => item.id === machine) : list[0];
|
|
220
|
-
if (!found) throw
|
|
242
|
+
if (!found) throw failure('machine_not_found', '对方站点上找不到这台电脑,或它还没有连接中转');
|
|
221
243
|
return { id: found.id, public_key: found.public_key, sign_key: found.sign_key, name: String(found.name || ''), fingerprint: fingerprint_of(found.public_key, found.sign_key) };
|
|
222
244
|
}
|
|
223
245
|
|
|
@@ -274,13 +296,13 @@ export async function relay_send(target, identity, action, payload, { fetcher =
|
|
|
274
296
|
response = await fetcher(`${target.site}${route}`, { method: 'POST', headers, body: JSON.stringify({ id, envelope, wait }),
|
|
275
297
|
signal: AbortSignal.timeout(wait + REQUEST_TIMEOUT_MS) });
|
|
276
298
|
} catch (error) {
|
|
277
|
-
if (error.name === 'TimeoutError' || error.name === 'AbortError') throw Object.assign(
|
|
278
|
-
throw Object.assign(
|
|
299
|
+
if (error.name === 'TimeoutError' || error.name === 'AbortError') throw Object.assign(failure('unconfirmed', '对方电脑未在限时内答复,结果待确认'), { unconfirmed: true });
|
|
300
|
+
throw Object.assign(failure('site_unreachable', '连不上对方的线上站点 {site}:{reason}', { site: target.site, reason: error.message }), { offline: true });
|
|
279
301
|
}
|
|
280
302
|
const result = await response.json().catch(() => ({}));
|
|
281
|
-
if (!response.ok) throw
|
|
282
|
-
if (result.status === 'offline') throw Object.assign(
|
|
283
|
-
if (result.status !== 'done') throw Object.assign(
|
|
303
|
+
if (!response.ok) throw remote_failure(result, 'site_refused', '对方站点拒绝了请求(HTTP {status})', { status: response.status }, { status: response.status });
|
|
304
|
+
if (result.status === 'offline') throw Object.assign(failure('offline', '对方电脑不在线:它可能关机或没有运行 codiscuss'), { offline: true });
|
|
305
|
+
if (result.status !== 'done') throw Object.assign(failure('unconfirmed', '对方电脑未在限时内答复,结果待确认'), { unconfirmed: true });
|
|
284
306
|
const sealed = result.response;
|
|
285
307
|
const opened = Buffer.from(await subtle.decrypt({ name: 'AES-GCM', iv: Buffer.from(sealed.iv, 'base64'), additionalData: encoder.encode(`${id}:response`) },
|
|
286
308
|
key, Buffer.from(sealed.data, 'base64')));
|
|
@@ -288,12 +310,12 @@ export async function relay_send(target, identity, action, payload, { fetcher =
|
|
|
288
310
|
}
|
|
289
311
|
|
|
290
312
|
/** Record how the last exchange went, so a computer that is off reads as offline and an ended membership as ended. */
|
|
291
|
-
function note_contact(home, id, state, error =
|
|
313
|
+
function note_contact(home, id, state, error = null, ended = '') {
|
|
292
314
|
try {
|
|
293
315
|
with_store(home, (store, secrets, now) => {
|
|
294
316
|
const record = store.records[id];
|
|
295
317
|
if (!record) return;
|
|
296
|
-
record.contact = { at: now, state, error: String(error).slice(0, 300) };
|
|
318
|
+
record.contact = { at: now, state, error: String(error?.message || '').slice(0, 300), ...failure_fields(error) };
|
|
297
319
|
if (ended && record.status === 'active') { record.status = 'ended'; record.end_reason = ended; remember(record, { outcome: 'ended', reason: ended }, now); }
|
|
298
320
|
});
|
|
299
321
|
} catch { /* A busy store only delays the status line. */ }
|
|
@@ -303,24 +325,24 @@ function note_contact(home, id, state, error = '', ended = '') {
|
|
|
303
325
|
async function record_send(home, id, action, payload, deps = {}) {
|
|
304
326
|
const record = find_record(read_store(home), id);
|
|
305
327
|
const secret = read_secrets(home)[id];
|
|
306
|
-
if (!secret) throw
|
|
328
|
+
if (!secret) throw failure('key_missing', '这条被邀请记录已没有密钥,请重新加入');
|
|
307
329
|
let answer;
|
|
308
330
|
try {
|
|
309
331
|
answer = await relay_send({ site: record.site, machine: record.machine, machine_key: record.machine_key },
|
|
310
332
|
{ key_id: record.key_id, private_key: secret.private_key, room: record.room }, action, { ...payload, token: secret.token }, deps);
|
|
311
333
|
} catch (error) {
|
|
312
|
-
note_contact(home, id, error.offline ? 'offline' : 'error', error
|
|
334
|
+
note_contact(home, id, error.offline ? 'offline' : 'error', error);
|
|
313
335
|
throw error;
|
|
314
336
|
}
|
|
315
337
|
// Revoked, expired or left there: the inviting room is the judge (子Task1 CONTRACT §0).
|
|
316
|
-
note_contact(home, id, 'online',
|
|
338
|
+
note_contact(home, id, 'online', null, answer.status === 403 && answer.body?.code === 'external_ended' ? answer.body.reason || 'revoked' : '');
|
|
317
339
|
return answer;
|
|
318
340
|
}
|
|
319
341
|
|
|
320
342
|
/** One member-scope request to the inviting room (`external-api`); a refusal throws with its status and reason. */
|
|
321
343
|
export async function member_api(home, id, method, path, body, deps = {}) {
|
|
322
344
|
const answer = await record_send(home, id, 'external-api', { method, path, ...(body === undefined ? {} : { body }) }, deps);
|
|
323
|
-
if (answer.status >= 400) throw
|
|
345
|
+
if (answer.status >= 400) throw remote_failure(answer.body, 'remote_refused', '对方拒绝了请求(HTTP {status})', { status: answer.status }, { status: answer.status, body: answer.body });
|
|
324
346
|
return answer.body;
|
|
325
347
|
}
|
|
326
348
|
|
|
@@ -331,7 +353,7 @@ function check_ai(input) {
|
|
|
331
353
|
const profile = adapter_profile(adapter);
|
|
332
354
|
// The AI reaches the other room only through this computer's codiscuss (a CLI) or this module (the model API's room
|
|
333
355
|
// and repo tools); App windows do neither.
|
|
334
|
-
if (!['cli', 'api'].includes(profile?.kind)) throw
|
|
356
|
+
if (!['cli', 'api'].includes(profile?.kind)) throw failure('ai_unsupported', '外部成员只能派命令行软件(如 Claude Code)或模型 API');
|
|
335
357
|
return { adapter, model: String(input.model || ''), effort: String(input.effort || '') };
|
|
336
358
|
}
|
|
337
359
|
|
|
@@ -341,17 +363,17 @@ export async function join_invite(home, input, deps = {}) {
|
|
|
341
363
|
const ai = check_ai(input);
|
|
342
364
|
const keys = await machine_keys(invite.site, invite.machine, deps);
|
|
343
365
|
if (invite.fingerprint && invite.fingerprint !== keys.fingerprint) {
|
|
344
|
-
throw
|
|
366
|
+
throw failure('fingerprint_mismatch', '这不是邀请你的那台电脑:指纹不符,已停止加入。请向对方确认链接');
|
|
345
367
|
}
|
|
346
368
|
const pair = key_pair(), key_id = key_id_of(pair.public_key);
|
|
347
369
|
const answer = await relay_send({ site: invite.site, machine: keys.id, machine_key: keys.public_key }, { key_id, private_key: pair.private_key }, 'external-redeem',
|
|
348
370
|
{ public_key: pair.public_key, proof: invite_proof(invite.code, keys.id, pair.public_key), label: String(input.label || hostname()).slice(0, 80),
|
|
349
371
|
// The model API has no platform name of its own; the inviting room names it as a custom AI.
|
|
350
372
|
platform: adapter_profile(ai.adapter).platform || 'Custom', adapter: ai.adapter }, deps);
|
|
351
|
-
if (answer.status >= 400) throw
|
|
373
|
+
if (answer.status >= 400) throw remote_failure(answer.body, 'invite_invalid', '邀请无效或已过期');
|
|
352
374
|
const joined = answer.body || {};
|
|
353
375
|
if (!ROOM_ID.test(joined.room?.id || '') || typeof joined.member?.name !== 'string' || typeof joined.token !== 'string') {
|
|
354
|
-
throw
|
|
376
|
+
throw failure('join_incomplete', '对方返回的加入结果不完整');
|
|
355
377
|
}
|
|
356
378
|
return with_store(home, (store, secrets, now) => {
|
|
357
379
|
const id = randomBytes(8).toString('hex');
|
|
@@ -372,13 +394,13 @@ export async function join_invite(home, input, deps = {}) {
|
|
|
372
394
|
|
|
373
395
|
function bounded(value, max, label) {
|
|
374
396
|
const number = Number(value);
|
|
375
|
-
if (!Number.isInteger(number) || number < 1 || number > max) throw
|
|
397
|
+
if (!Number.isInteger(number) || number < 1 || number > max) throw failure('invalid_number', '{label} 须为 1–{max} 的整数', { label, max });
|
|
376
398
|
return number;
|
|
377
399
|
}
|
|
378
400
|
|
|
379
401
|
/** Set the trust of the record's computer and, for 完全借用, the record's own limits (counted afresh from now). */
|
|
380
402
|
export function set_trust(home, { id, trust, max_wakes, hours, until }) {
|
|
381
|
-
if (!TRUST_LEVELS.includes(trust)) throw
|
|
403
|
+
if (!TRUST_LEVELS.includes(trust)) throw failure('invalid_trust', '信任等级只能是 default、borrow 或 trusted');
|
|
382
404
|
return change_record(home, id, (record, now, store) => {
|
|
383
405
|
const machine = store.machines[record.machine_fingerprint] ||= { machine: record.machine, site: record.site };
|
|
384
406
|
Object.assign(machine, { trust, updated_at: now });
|
|
@@ -386,7 +408,7 @@ export function set_trust(home, { id, trust, max_wakes, hours, until }) {
|
|
|
386
408
|
const limit = max_wakes === undefined ? record.limits?.max_wakes ?? BORROW_DEFAULTS.max_wakes : bounded(max_wakes, MAX_WAKES_LIMIT, 'max_wakes');
|
|
387
409
|
const end = until !== undefined ? Number(until) : hours !== undefined ? now + bounded(hours, MAX_HOURS, 'hours') * HOUR_MS
|
|
388
410
|
: record.limits?.until > now ? record.limits.until : now + BORROW_DEFAULTS.hours * HOUR_MS;
|
|
389
|
-
if (!Number.isFinite(end) || end <= now) throw
|
|
411
|
+
if (!Number.isFinite(end) || end <= now) throw failure('invalid_deadline', '借用期限须晚于现在');
|
|
390
412
|
record.limits = { max_wakes: limit, until: end, used: 0 };
|
|
391
413
|
}
|
|
392
414
|
return { record: record_view(record, store) };
|
|
@@ -414,7 +436,7 @@ async function decline(home, id, request_ids, reason, deps) {
|
|
|
414
436
|
function settle_approval(home, id, approval, outcome) {
|
|
415
437
|
return change_record(home, id, (record, now) => {
|
|
416
438
|
const item = (record.approvals || []).find(entry => entry.id === approval && entry.status === 'waiting');
|
|
417
|
-
if (!item) throw
|
|
439
|
+
if (!item) throw failure('approval_not_found', '这条待确认请求不存在或已处理');
|
|
418
440
|
item.status = outcome;
|
|
419
441
|
if (outcome === 'refused') remember(record, { request_ids: item.request_ids, message_ids: item.message_ids, outcome }, now);
|
|
420
442
|
return item;
|
|
@@ -454,22 +476,53 @@ export async function leave(home, { id }, deps = {}) {
|
|
|
454
476
|
});
|
|
455
477
|
}
|
|
456
478
|
|
|
479
|
+
/** Keep the record in line with what the inviting room grants now (`/view` `me`): level, deadline and opened directories. */
|
|
480
|
+
function apply_grant(home, id, me, now = Date.now()) {
|
|
481
|
+
if (!me || typeof me !== 'object') return;
|
|
482
|
+
change_record(home, id, record => {
|
|
483
|
+
if (['read', 'discuss'].includes(me.scope)) record.open_level = me.scope;
|
|
484
|
+
if (Number(me.expires_at)) record.expires_at = Number(me.expires_at) * 1000;
|
|
485
|
+
if (Array.isArray(me.directories)) record.directories = me.directories.map(({ root, name }) => ({ root, name }));
|
|
486
|
+
record.grant_checked_at = now;
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async function refresh_grant(home, id, deps) {
|
|
491
|
+
const record = find_record(read_store(home), id);
|
|
492
|
+
const view = await member_api(home, id, 'GET', MEMBER_API.view(record.room), undefined, deps);
|
|
493
|
+
apply_grant(home, id, view?.me, deps.now?.() ?? Date.now());
|
|
494
|
+
return view;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const clip = text => String(text ?? '').slice(0, TEXT_LIMIT);
|
|
498
|
+
|
|
499
|
+
/** The requests and answers this computer kept, as messages, for when the inviting room cannot be read. */
|
|
500
|
+
function kept_messages(record) {
|
|
501
|
+
const messages = new Map();
|
|
502
|
+
for (const entry of record.history || []) {
|
|
503
|
+
for (const item of entry.request_texts || []) messages.set(item.id, { ...item, kept: true });
|
|
504
|
+
if (entry.answer) messages.set(entry.answer.id, { ...entry.answer, execution_id: entry.execution_id, kept: true });
|
|
505
|
+
}
|
|
506
|
+
return [...messages.values()].sort((a, b) => a.id - b.id);
|
|
507
|
+
}
|
|
508
|
+
|
|
457
509
|
/** The record with what the inviting room shows this member, when it can be reached. */
|
|
458
510
|
export async function room_view(home, { id }, deps = {}) {
|
|
459
511
|
const record = find_record(read_store(home), id);
|
|
460
|
-
let room = null,
|
|
512
|
+
let room = null, problem = null;
|
|
461
513
|
let messages = [];
|
|
462
514
|
try {
|
|
463
|
-
room = await
|
|
515
|
+
room = await refresh_grant(home, id, deps);
|
|
464
516
|
// What the page shows in the middle: requests naming this AI and this AI's own answers, oldest first.
|
|
465
517
|
const query = field => `${MEMBER_API.messages(record.room)}?${new URLSearchParams({ [field]: record.member })}`;
|
|
466
518
|
const pages = await Promise.all(['mention', 'author'].map(field => member_api(home, id, 'GET', query(field), undefined, deps)));
|
|
467
519
|
const unique = new Map(pages.flatMap(page => page.messages || []).map(message => [message.id, message]));
|
|
468
520
|
messages = [...unique.values()].sort((a, b) => a.id - b.id);
|
|
469
|
-
} catch (
|
|
521
|
+
} catch (error) { problem = error; messages = kept_messages(record); }
|
|
470
522
|
const store = read_store(home);
|
|
471
523
|
// Also under `room`, where the page (子Task6) looks for them.
|
|
472
|
-
return { record: record_view(store.records[id], store), room: room ? { ...room, messages } : null, messages,
|
|
524
|
+
return { record: record_view(store.records[id], store), room: room ? { ...room, messages } : null, messages,
|
|
525
|
+
...(problem ? { error: problem.message, ...failure_fields(problem) } : {}) };
|
|
473
526
|
}
|
|
474
527
|
|
|
475
528
|
/**
|
|
@@ -491,7 +544,7 @@ export async function invited_command(home, action, input = {}, deps = {}) {
|
|
|
491
544
|
if (action === 'invited-refuse') return refuse_approval(home, input, deps);
|
|
492
545
|
if (action === 'invited-leave') return leave(home, input, deps);
|
|
493
546
|
if (action === 'invited-room') return room_view(home, input, deps);
|
|
494
|
-
throw
|
|
547
|
+
throw failure('unknown_action', '未知的被邀请记录操作:{action}', { action });
|
|
495
548
|
}
|
|
496
549
|
|
|
497
550
|
export const INVITED_ACTIONS = new Set(['invited-list', 'invited-join', 'invited-trust', 'invited-ai', 'invited-pause', 'invited-approve',
|
|
@@ -524,26 +577,35 @@ function software_profile(home, ai) {
|
|
|
524
577
|
export async function wake(home, id, request_ids, deps = {}, { only = false } = {}) {
|
|
525
578
|
const store = read_store(home), record = find_record(store, id);
|
|
526
579
|
const lockdown = record_view(record, store).lockdown;
|
|
527
|
-
const refuse = async (reason,
|
|
528
|
-
change_record(home, id, (current, now) => remember(current, { request_ids, outcome: reason, reason:
|
|
580
|
+
const refuse = async (reason, template, params) => {
|
|
581
|
+
change_record(home, id, (current, now) => remember(current, { request_ids, outcome: reason, reason: t(template, params), reason_text: { template, params } }, now));
|
|
529
582
|
await decline(home, id, request_ids, reason, deps);
|
|
530
583
|
return null;
|
|
531
584
|
};
|
|
532
585
|
const support = lockdown_support(record.ai.adapter);
|
|
533
586
|
if (lockdown && !support.supported) {
|
|
534
|
-
return refuse('lockdown_unsupported',
|
|
587
|
+
return refuse('lockdown_unsupported', '该软件不能收窄到只用 codiscuss 命令,只能在“信任设备”等级下服务:{reason}', { reason: support.reason });
|
|
535
588
|
}
|
|
536
589
|
const software = deps.software ?? software_profile(home, record.ai);
|
|
537
|
-
if (!software) return refuse('ai_unavailable',
|
|
590
|
+
if (!software) return refuse('ai_unavailable', '这台电脑还没有配置 {adapter}', { adapter: adapter_profile(record.ai.adapter)?.label || record.ai.adapter });
|
|
591
|
+
// The AI is told what the other side opens now, not what it opened at joining.
|
|
592
|
+
await refresh_grant(home, id, deps).catch(error => deps.log?.(error.message));
|
|
538
593
|
let execution;
|
|
539
594
|
try {
|
|
540
595
|
const claimed = await member_api(home, id, 'POST', MEMBER_API.claim(record.room), { client_id: `ext-${record.id}-${randomBytes(6).toString('hex')}`, ...(only ? { request_ids } : {}) }, deps);
|
|
541
596
|
execution = claimed.execution || claimed;
|
|
542
597
|
} catch (error) {
|
|
543
|
-
change_record(home, id, (current, now) => remember(current, { request_ids, outcome: 'failed', reason: error.message }, now));
|
|
598
|
+
change_record(home, id, (current, now) => remember(current, { request_ids, outcome: 'failed', reason: error.message, ...failure_fields(error) }, now));
|
|
544
599
|
return null;
|
|
545
600
|
}
|
|
546
601
|
const claimed_ids = (execution.requests || []).map(item => item.id);
|
|
602
|
+
// The request texts are kept here (CONTRACT §1.1 history), so the history still reads once that room cannot be.
|
|
603
|
+
const request_texts = [];
|
|
604
|
+
for (const message_id of new Set((execution.requests || []).map(item => item.message_id).filter(Number.isInteger))) {
|
|
605
|
+
const read = await member_api(home, id, 'GET', `${MEMBER_API.messages(record.room)}/${message_id}`, undefined, deps).catch(() => null);
|
|
606
|
+
const message = read?.message || read;
|
|
607
|
+
if (message?.id === message_id) request_texts.push({ id: message_id, author: String(message.author || ''), text: clip(message.text) });
|
|
608
|
+
}
|
|
547
609
|
change_record(home, id, (current, now) => {
|
|
548
610
|
current.wakes = (current.wakes || 0) + 1;
|
|
549
611
|
current.last_wake_at = now;
|
|
@@ -551,9 +613,9 @@ export async function wake(home, id, request_ids, deps = {}, { only = false } =
|
|
|
551
613
|
current.running = { execution_id: execution.id, started_at: now, last_renew: deps.now?.() ?? now };
|
|
552
614
|
// Approvals whose requests this execution took are settled by it.
|
|
553
615
|
current.approvals = (current.approvals || []).filter(item => item.status === 'waiting' && !item.request_ids.every(request => claimed_ids.includes(request)));
|
|
554
|
-
remember(current, { request_ids: claimed_ids, message_ids: (execution.requests || []).map(item => item.message_id), outcome: 'woken', execution_id: execution.id }, now);
|
|
616
|
+
remember(current, { request_ids: claimed_ids, message_ids: (execution.requests || []).map(item => item.message_id), outcome: 'woken', execution_id: execution.id, request_texts }, now);
|
|
555
617
|
});
|
|
556
|
-
await deliver_external(home,
|
|
618
|
+
await deliver_external(home, find_record(read_store(home), id), execution, { lockdown, software }, deps);
|
|
557
619
|
return execution.id;
|
|
558
620
|
}
|
|
559
621
|
|
|
@@ -586,11 +648,12 @@ async function start_run(home, record, execution, { lockdown, software, end }, d
|
|
|
586
648
|
const cli = process.platform === 'win32' ? adapter?.windows_command || 'codiscuss.cmd' : 'codiscuss';
|
|
587
649
|
const requests = execution.requests || [];
|
|
588
650
|
const messages = requests.map(item => `#${item.message_id}`).join('、');
|
|
589
|
-
const
|
|
651
|
+
const directories = record.open_level === 'read' ? record.directories || [] : [];
|
|
652
|
+
const { instructions, prompt } = external_task_text({ name: record.member, messages, requests, cli, access_file: access_path, task_path, lockdown, draft_directory: drafts, directories });
|
|
590
653
|
const skills_directory = join(PACKAGE_ROOT, '.agents', 'skills');
|
|
591
654
|
atomic_json(task_path, { site: record.site, room: record.room, mode: 'free', member: record.member, external: true,
|
|
592
655
|
execution_id: execution.id, requests, request_messages: requests.map(item => item.message_id), read_after: execution.read_until ?? null,
|
|
593
|
-
role: 'member', cwd: null, project_access: 'read', draft_directory: drafts,
|
|
656
|
+
role: 'member', cwd: null, project_access: 'read', draft_directory: drafts, open_level: record.open_level, directories,
|
|
594
657
|
skills: ['discuss-participant/SKILL.md', 'discuss-participant/references/room.md'].map(file => join(skills_directory, file)),
|
|
595
658
|
cli, subcommands: TASK_SUBCOMMANDS, access_file: access_path, tool_lockdown: lockdown, instructions });
|
|
596
659
|
const profile = { adapter: record.ai.adapter, ...software, model: record.ai.model || software.model || '', effort: record.ai.effort, cwd: workdir, project_access: 'read' };
|
|
@@ -622,22 +685,27 @@ function bind_session(home, id, session_id) {
|
|
|
622
685
|
}
|
|
623
686
|
|
|
624
687
|
/**
|
|
625
|
-
* A run ended: free the record
|
|
626
|
-
*
|
|
688
|
+
* A run ended: free the record, then ask the inviting room how it went there, since only it knows whether an answer bound
|
|
689
|
+
* to this execution arrived (red line 4). Answered → recorded as answered, even when the process ended with an error (kept
|
|
690
|
+
* as a note); still open there → failed, and the room is told why, as the room runner does; closed there without an
|
|
691
|
+
* answer (cancelled, retracted) → ended.
|
|
627
692
|
*/
|
|
628
693
|
async function finish(home, id, execution_id, reason, deps) {
|
|
629
|
-
change_record(home, id, (record
|
|
630
|
-
if (record.running?.execution_id === execution_id) record.running = null;
|
|
631
|
-
remember(record, { execution_id, outcome: reason ? 'failed' : 'ended', ...(reason ? { reason } : {}) }, now);
|
|
632
|
-
});
|
|
694
|
+
change_record(home, id, record => { if (record.running?.execution_id === execution_id) record.running = null; });
|
|
633
695
|
const record = read_store(home).records[id];
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
696
|
+
const answers = await member_api(home, id, 'GET', `${MEMBER_API.messages(record.room)}?${new URLSearchParams({ author: record.member })}`, undefined, deps)
|
|
697
|
+
.catch(() => null);
|
|
698
|
+
const answer = (answers?.messages || []).find(message => message.execution_id === execution_id);
|
|
699
|
+
const answered = Boolean(answer);
|
|
700
|
+
const inbox = answered ? null : await member_api(home, id, 'GET', MEMBER_API.inbox(record.room), undefined, deps).catch(() => null);
|
|
701
|
+
// Unknown (the other computer not reachable) counts as open, so the failure is reported once it can be.
|
|
702
|
+
const open = !answered && (!inbox || (inbox.executions || []).some(item => item.id === execution_id));
|
|
703
|
+
const outcome = answered ? 'answered' : open ? 'failed' : 'ended';
|
|
640
704
|
const text = reason || t('{member} 会话已结束,但未提交本次回答', { member: record.member });
|
|
705
|
+
change_record(home, id, (current, now) => remember(current, { execution_id, outcome,
|
|
706
|
+
...(answer ? { answer: { id: answer.id, author: String(answer.author || record.member), text: clip(answer.text) } } : {}),
|
|
707
|
+
...(reason ? { reason } : open ? { reason: text, reason_text: { template: '{member} 会话已结束,但未提交本次回答', params: { member: record.member } } } : {}) }, now));
|
|
708
|
+
if (!open) return;
|
|
641
709
|
try { await member_api(home, id, 'POST', MEMBER_API.execution(record.room, execution_id), { action: 'fail', reason: text.slice(0, 400) }, deps); }
|
|
642
710
|
catch (error) { if (error.status !== 409) deps.log?.(t('未能向对方上报执行 #{execution} 的结束:{reason}', { execution: execution_id, reason: error.message })); }
|
|
643
711
|
}
|
|
@@ -672,6 +740,8 @@ export async function poll_record(home, id, deps = {}) {
|
|
|
672
740
|
}
|
|
673
741
|
if (record.paused) return { skipped: true };
|
|
674
742
|
const inbox = await member_api(home, id, 'GET', MEMBER_API.inbox(record.room), undefined, deps);
|
|
743
|
+
if (Number(inbox.member?.expires_at)) change_record(home, id, current => { current.expires_at = Number(inbox.member.expires_at) * 1000; });
|
|
744
|
+
if (!(now - (record.grant_checked_at || 0) < VIEW_REFRESH_MS)) await refresh_grant(home, id, deps);
|
|
675
745
|
const pending = (inbox.pending || []).filter(item => Number.isInteger(item.id));
|
|
676
746
|
const pending_ids = new Set(pending.map(item => item.id));
|
|
677
747
|
// An approved request that is gone there (cancelled meanwhile) needs nothing more.
|
|
@@ -713,7 +783,7 @@ export function start_external_client(home, { log = () => {}, signal, deps = {}
|
|
|
713
783
|
|
|
714
784
|
function external_access(access) {
|
|
715
785
|
if (access?.transport !== 'external' || !RECORD_ID.test(String(access.record || ''))) {
|
|
716
|
-
throw
|
|
786
|
+
throw failure('not_external', '只有经另一台电脑加入的成员才能这样访问;请用任务给出的 --access-file');
|
|
717
787
|
}
|
|
718
788
|
return access;
|
|
719
789
|
}
|
|
@@ -762,12 +832,12 @@ const REPO_REASONS = {
|
|
|
762
832
|
/** `codiscuss repo ls|read|grep`: read the other computer's opened project through its relay (子Task2 CONTRACT §4.3). */
|
|
763
833
|
export async function repo_command(home, op, options, access, deps = {}) {
|
|
764
834
|
external_access(access);
|
|
765
|
-
if (!['ls', 'read', 'grep'].includes(op)) throw
|
|
835
|
+
if (!['ls', 'read', 'grep'].includes(op)) throw failure('repo_usage', '用法:codiscuss repo ls [目录] | read 文件 | grep 关键词');
|
|
766
836
|
const answer = await record_send(home, access.record, 'external-repo', { op, ...options }, deps);
|
|
767
837
|
const body = answer.body || {};
|
|
768
838
|
if (answer.status >= 400 || body.ok === false) {
|
|
769
839
|
const reason = body.reason || '';
|
|
770
|
-
throw
|
|
840
|
+
throw REPO_REASONS[reason] ? failure(`repo_${reason}`, REPO_REASONS[reason], undefined, { reason }) : remote_failure(body, 'repo_refused', '读取被拒绝', undefined, { reason });
|
|
771
841
|
}
|
|
772
842
|
return body;
|
|
773
843
|
}
|
|
@@ -782,8 +852,8 @@ const LAUNCH_FILE_FLAGS = new Set(['--file', '--draft', '--dir']);
|
|
|
782
852
|
*/
|
|
783
853
|
export function lockdown_launch_guard(args, env = process.env) {
|
|
784
854
|
if (env.CODISCUSS_TOOL_LOCKDOWN !== '1') return;
|
|
785
|
-
if (args[0] === 'image') throw
|
|
786
|
-
if (args.includes('--stdin')) throw
|
|
855
|
+
if (args[0] === 'image') throw failure('lockdown_image', '本次运行已收窄,不能使用 launch image(它会读取本机文件)');
|
|
856
|
+
if (args.includes('--stdin')) throw failure('lockdown_stdin', '本次运行已收窄,不能从标准输入读取;请先把内容写进草稿目录,再用文件参数传入');
|
|
787
857
|
const real = path => { try { return realpathSync(path); } catch { return resolve(path); } };
|
|
788
858
|
const folder = env.CODISCUSS_LOCKDOWN_DIRECTORY ? real(env.CODISCUSS_LOCKDOWN_DIRECTORY) : '';
|
|
789
859
|
args.forEach((arg, index) => {
|
|
@@ -792,7 +862,7 @@ export function lockdown_launch_guard(args, env = process.env) {
|
|
|
792
862
|
const value = inline ?? args[index + 1] ?? '';
|
|
793
863
|
const target = value === '-' ? '' : real(value);
|
|
794
864
|
const inside = folder && target && (target === folder || target.startsWith(`${folder}${sep}`));
|
|
795
|
-
if (!inside) throw
|
|
865
|
+
if (!inside) throw failure('lockdown_path', '本次运行已收窄,只能读取草稿目录 {folder} 里的文件', { folder: folder || '-' });
|
|
796
866
|
});
|
|
797
867
|
}
|
|
798
868
|
|