ai_co_discuss 0.4.65 → 0.4.67

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.
@@ -365,7 +365,18 @@ export async function join_invite(home, input, deps = {}) {
365
365
  if (invite.fingerprint && invite.fingerprint !== keys.fingerprint) {
366
366
  throw failure('fingerprint_mismatch', '这不是邀请你的那台电脑:指纹不符,已停止加入。请向对方确认链接');
367
367
  }
368
- const pair = key_pair(), key_id = key_id_of(pair.public_key);
368
+ const attempt_key = `join:${createHash('sha256').update(`${invite.site}:${keys.id}:${invite.code}`).digest('hex')}`;
369
+ const attempt = with_store(home, (store, secrets) => {
370
+ const values = secrets.get();
371
+ if (!values[attempt_key]) {
372
+ values[attempt_key] = { pair: key_pair(), id: randomBytes(8).toString('hex') };
373
+ secrets.changed = true;
374
+ }
375
+ return values[attempt_key];
376
+ });
377
+ const existing = read_store(home);
378
+ if (existing.records[attempt.id] && read_secrets(home)[attempt.id]?.token) return { record: record_view(existing.records[attempt.id], existing) };
379
+ const pair = attempt.pair, key_id = key_id_of(pair.public_key);
369
380
  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',
370
381
  { public_key: pair.public_key, proof: invite_proof(invite.code, keys.id, pair.public_key), label: String(input.label || hostname()).slice(0, 80),
371
382
  // The model API has no platform name of its own; the inviting room names it as a custom AI.
@@ -376,7 +387,7 @@ export async function join_invite(home, input, deps = {}) {
376
387
  throw failure('join_incomplete', '对方返回的加入结果不完整');
377
388
  }
378
389
  return with_store(home, (store, secrets, now) => {
379
- const id = randomBytes(8).toString('hex');
390
+ const id = attempt.id;
380
391
  const name = joined.machine?.name || keys.name || invite.machine_name;
381
392
  const machine = store.machines[keys.fingerprint] ||= { trust: 'default' };
382
393
  Object.assign(machine, { machine: keys.id, site: invite.site, machine_name: name, updated_at: now });
@@ -471,6 +482,9 @@ export async function leave(home, { id }, deps = {}) {
471
482
  Object.assign(record, { status: 'left', approvals: [], paused: true });
472
483
  remember(record, { outcome: 'left', remote }, now);
473
484
  delete secrets.get()[id];
485
+ for (const [key, value] of Object.entries(secrets.get())) {
486
+ if (key.startsWith('join:') && value.id === id) delete secrets.get()[key];
487
+ }
474
488
  secrets.changed = true;
475
489
  return { record: record_view(record, store), remote };
476
490
  });
@@ -24,6 +24,7 @@ const DAY_MS = 86400000;
24
24
  const HOUR_MS = 3600000;
25
25
  export const INVITE_MS = 10 * 60000;
26
26
  const INVITE_ATTEMPTS = 5;
27
+ const GLOBAL_INVITE_ATTEMPTS = 1000;
27
28
  // The website lets an external key through this long after it joined; a key in use is extended when this close to the end.
28
29
  const KEY_DAYS = 30;
29
30
  const KEY_REFRESH_DAYS = 7;
@@ -70,6 +71,7 @@ function with_registry(home, task) {
70
71
  const now = Date.now();
71
72
  for (const [key, invite] of Object.entries(registry.invites)) if (invite.expires_at <= now) delete registry.invites[key];
72
73
  for (const [key, entry] of Object.entries(registry.externals)) if (entry.key_expires_at <= now) delete registry.externals[key];
74
+ for (const [key, entry] of Object.entries(registry.redemptions || {})) if (entry.member_expires_at * 1000 <= now) delete registry.redemptions[key];
73
75
  // Saved even when the task refuses: a used invite or a counted failure must not come back.
74
76
  try { return task(registry, now); } finally { atomic_json(file, registry); }
75
77
  } finally { rmSync(path, { force: true }); }
@@ -189,8 +191,15 @@ async function invite_site(home, site_url) {
189
191
  * Issue an invite for one room: a 12-character code valid ten minutes, kept here only as its hash, and the link that
190
192
  * carries it with this computer's key fingerprint. The code and link are returned this once.
191
193
  */
192
- export async function create_invite(home, { room_id, token, level = 'read', folders, duration = '1h', site_url, by = 'computer' }, { fetcher } = {}) {
194
+ export async function create_invite(home, { room_id, token, level = 'read', folders, duration = '1h', site_url, member_id, by = 'computer' }, { fetcher } = {}) {
193
195
  const room = await owned_room(home, room_id, token, fetcher);
196
+ if (member_id) {
197
+ const current = await local_call(room, 'GET', `/api/rooms/${encodeURIComponent(room_id)}/external-members/${member_id}`, { token, fetcher });
198
+ if (current.status !== 200) throw new GatewayError(current.status, current.body?.error || '外部成员不存在');
199
+ level = current.body.scope;
200
+ duration = current.body.duration;
201
+ folders = current.body.directories.map(path => room.directories.indexOf(path));
202
+ }
194
203
  if (!LEVELS.has(level)) throw new GatewayError(400, '开放等级须为 discuss 或 read');
195
204
  if (!DURATIONS.has(duration)) throw new GatewayError(400, '有效期须为 1h、today 或 3d');
196
205
  const chosen = level === 'discuss' ? [] : folders === undefined ? [0] : folders;
@@ -198,15 +207,41 @@ export async function create_invite(home, { room_id, token, level = 'read', fold
198
207
  || new Set(chosen).size !== chosen.length) {
199
208
  throw new GatewayError(400, '开放目录须为本房间项目目录的序号');
200
209
  }
201
- const { site, link } = await invite_site(home, site_url);
210
+ const base = `/api/rooms/${encodeURIComponent(room_id)}/external-members`;
211
+ const call = async (method, path, body) => {
212
+ const result = await local_call(room, method, path, { token, body, fetcher });
213
+ if (result.status >= 400) throw new GatewayError(result.status, result.body?.error || '外部成员不存在');
214
+ return result.body;
215
+ };
216
+ if (!member_id) {
217
+ const listed = await call('GET', base);
218
+ const view = await call('GET', `/api/rooms/${encodeURIComponent(room_id)}`);
219
+ const taken = new Set([...(view.free?.members || []), ...(listed.members || [])].map(member => member.name));
220
+ const created = await call('POST', base, { pending: true, revision: listed.revision,
221
+ name: external_name('Custom', taken), scope: level, duration, directories: chosen.map(index => room.directories[index]) });
222
+ member_id = created.member.member_id;
223
+ }
224
+ let site, link;
225
+ try { ({ site, link } = await invite_site(home, site_url)); }
226
+ catch (error) {
227
+ if (!['site_missing', 'site_required'].includes(error.code)) throw error;
228
+ return { room_id, member_id, pending: true, reason: error.message, reason_text: error.error_text };
229
+ }
230
+ const seat = await call('POST', `${base}/${member_id}`, { action: 'invite' });
202
231
  let room_name = '';
203
232
  try { const view = await local_call(room, 'GET', `/api/rooms/${encodeURIComponent(room_id)}`, { token, fetcher }); room_name = String(view.body?.title ?? view.body?.room?.title ?? '').slice(0, 80); } catch { /* The name is only shown. */ }
204
233
  const code = Array.from(randomBytes(CODE_LENGTH), byte => CODE_ALPHABET[byte & 31]).join('');
205
234
  const fingerprint = machine_fingerprint(link);
206
235
  const invite = with_registry(home, (registry, now) => {
207
236
  const invite_id = randomBytes(8).toString('hex');
208
- registry.invites[invite_id] = { code_hash: invite_code_hash(code), room_id, level, folders: chosen, duration, site, by, created_at: now, expires_at: now + INVITE_MS, failures: 0 };
209
- return { invite_id, expires_at: now + INVITE_MS };
237
+ if ([...Object.values(registry.invites), ...Object.values(registry.redemptions || {})].some(previous => previous.room_id === room_id && previous.member_id === member_id && previous.invite_version > seat.invite_version)) {
238
+ throw new GatewayError(409, '邀请已更新,请重新生成链接');
239
+ }
240
+ for (const [key, previous] of Object.entries(registry.invites)) {
241
+ if (previous.room_id === room_id && previous.member_id === member_id) delete registry.invites[key];
242
+ }
243
+ registry.invites[invite_id] = { member_id, invite_version: seat.invite_version, code_hash: invite_code_hash(code), room_id, level, folders: chosen, duration, site, by, created_at: now, expires_at: now + INVITE_MS, failures: 0 };
244
+ return { invite_id, member_id, expires_at: now + INVITE_MS };
210
245
  });
211
246
  audit(home, { event: 'invite.created', room: room_id, invite: invite.invite_id, level, by });
212
247
  const payload = { v: 1, site, machine: link.id, machine_name: link.name, fp: fingerprint, code, room_name, level, expires_at: invite.expires_at };
@@ -251,9 +286,10 @@ export function external_entries(home, site) {
251
286
  /** Forget an external member's key, so the website stops letting it through. */
252
287
  async function drop_external(home, ctx, external_id, reason) {
253
288
  const dropped = with_registry(home, registry => {
254
- if (!registry.externals[external_id]) return false;
289
+ const existed = Boolean(registry.externals[external_id]);
255
290
  delete registry.externals[external_id];
256
- return true;
291
+ for (const [id, entry] of Object.entries(registry.redemptions || {})) if (entry.external_id === external_id) delete registry.redemptions[id];
292
+ return existed;
257
293
  });
258
294
  if (dropped) {
259
295
  audit(home, { event: reason === 'left' ? 'external.left' : 'external.dropped', external: external_id, reason });
@@ -261,18 +297,39 @@ async function drop_external(home, ctx, external_id, reason) {
261
297
  }
262
298
  }
263
299
 
264
- /** Take the invite whose code proves this key, counting a wrong proof against every waiting invite. */
300
+ /** Take a proven invite; failed guesses cool down the signer without consuming any invitation. */
265
301
  function take_invite(home, machine_id, public_key, proof) {
266
- const taken = with_registry(home, registry => {
302
+ const taken = with_registry(home, (registry, now) => {
267
303
  const supplied = Buffer.from(String(proof || ''));
304
+ registry.redemptions ||= {};
305
+ const external_id = device_id_of(public_key);
306
+ if (!registry.guesses || registry.guesses.until <= now) registry.guesses = { count: 0, until: now + INVITE_MS };
307
+ if (registry.guesses.count >= GLOBAL_INVITE_ATTEMPTS) throw new GatewayError(429, '尝试次数过多,请十分钟后重试');
308
+ registry.guesses.count++;
309
+ registry.attempts ||= {};
310
+ for (const [key, entry] of Object.entries(registry.attempts)) if (entry.until <= now) delete registry.attempts[key];
311
+ const attempt = registry.attempts[external_id] ||= { count: 0, until: now + INVITE_MS };
312
+ if (attempt.count >= INVITE_ATTEMPTS) throw new GatewayError(429, '尝试次数过多,请十分钟后重试');
313
+ for (const [id, invite] of Object.entries(registry.redemptions)) {
314
+ const expected = Buffer.from(proof_from_hash(invite.code_hash, machine_id, public_key));
315
+ if (expected.length === supplied.length && timingSafeEqual(expected, supplied)) {
316
+ if (invite.external_id !== external_id) throw new GatewayError(409, '席位已被认领,请让房主重新生成邀请', {}, 'seat_claimed');
317
+ return { invite_id: id, ...invite };
318
+ }
319
+ }
268
320
  for (const [id, invite] of Object.entries(registry.invites)) {
269
321
  const expected = Buffer.from(proof_from_hash(invite.code_hash, machine_id, public_key));
270
322
  if (expected.length === supplied.length && timingSafeEqual(expected, supplied)) {
323
+ if (registry.externals[external_id]) {
324
+ throw new GatewayError(409, '这把密钥已经加入过房间,请为新的邀请生成新密钥', {}, 'key_used');
325
+ }
326
+ registry.redemptions[id] = { ...invite, external_id,
327
+ member_expires_at: membership_end(invite.duration, Date.now()) };
271
328
  delete registry.invites[id];
272
- return { invite_id: id, ...invite };
329
+ return { invite_id: id, ...registry.redemptions[id] };
273
330
  }
274
331
  }
275
- for (const [id, invite] of Object.entries(registry.invites)) if (++invite.failures >= INVITE_ATTEMPTS) delete registry.invites[id];
332
+ attempt.count++;
276
333
  return null;
277
334
  });
278
335
  if (!taken) throw new GatewayError(400, '邀请码不对或已过期,请让对方重新生成邀请', {}, 'invite_invalid');
@@ -295,27 +352,34 @@ async function redeem(home, ctx, id, sealed, request) {
295
352
  try { external_id = device_id_of(public_key); } catch { throw new GatewayError(400, '外部成员公钥须为 P-256'); }
296
353
  if (!await verify_signature(public_key, sealed.signature, `${id}\n${sealed.body}`)) throw new GatewayError(400, '外部成员签名无效', {}, 'bad_signature');
297
354
  if (typeof platform !== 'string' || !/^[A-Za-z]{2,20}$/.test(platform)) throw new GatewayError(400, '请说明派来的是哪个 AI');
298
- if (read_registry(home).externals[external_id]) throw new GatewayError(409, '这把密钥已经加入过房间,请为新的邀请生成新密钥', {}, 'key_used');
355
+ const previous = read_registry(home).externals[external_id];
356
+ if (previous) {
357
+ const previous_room = local_room(home, previous.room_id);
358
+ const status = await local_call(previous_room, 'GET', `/api/rooms/${encodeURIComponent(previous.room_id)}/external-members/${previous.member_id}`, { token: previous_room.token, fetcher: ctx.fetcher });
359
+ if (status.status === 404 || status.body?.status === 'removed') await drop_external(home, ctx, external_id, 'ended');
360
+ }
299
361
  const invite = take_invite(home, ctx.machine_id, public_key, proof);
300
362
  const room = local_room(home, invite.room_id);
301
363
  if (!room) throw new GatewayError(404, '邀请对应的房间已不在这台电脑上');
302
364
  const directories = invite.folders.map(index => room.directories[index]);
303
365
  if (directories.some(directory => !directory)) throw new GatewayError(409, '邀请开放的项目目录已不在房间里,请重新邀请');
304
366
  const base = `/api/rooms/${encodeURIComponent(room.id)}`;
305
- const listed = await local_call(room, 'GET', `${base}/external-members`, { token: room.token, fetcher: ctx.fetcher });
306
- if (listed.status !== 200) return { status: listed.status, body: listed.body ?? text_of('读取房间成员失败') };
307
367
  const view = await local_call(room, 'GET', base, { token: room.token, fetcher: ctx.fetcher });
308
- const taken = new Set([...(view.body?.free?.members ?? []), ...(listed.body.members ?? [])].map(member => member?.name).filter(Boolean));
309
- const token = randomBytes(32).toString('hex'), clean_label = String(label || '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, LABEL_LIMIT);
310
- const created = await local_call(room, 'POST', `${base}/external-members`, { token: room.token, fetcher: ctx.fetcher, body: {
311
- revision: listed.body.revision, name: external_name(platform, taken), adapter: String(adapter || '').slice(0, 40), token,
312
- machine: `ext:${external_id}`, machine_label: clean_label, scope: invite.level, directories, expires_at: membership_end(invite.duration, Date.now()) } });
313
- if (![200, 201].includes(created.status)) return { status: created.status, body: created.body ?? text_of('建立外部成员失败') };
314
- const member = created.body.member;
368
+ const token = createHmac('sha256', invite.code_hash).update(`seat-token-v1:${invite.invite_id}:${external_id}`).digest('hex');
369
+ const clean_label = String(label || '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, LABEL_LIMIT);
370
+ const binding = { invite_version: invite.invite_version, token, machine: `ext:${external_id}`,
371
+ machine_label: clean_label, adapter: String(adapter || '').slice(0, 40), expires_at: invite.member_expires_at };
372
+ const seat_path = `${base}/external-members/${invite.member_id}`;
373
+ const created = await local_call(room, 'POST', seat_path, { token: room.token, fetcher: ctx.fetcher,
374
+ body: { action: 'bind', ...binding } });
375
+ if (created.status !== 200) return { status: created.status, body: created.body };
376
+ const member = created.body;
315
377
  with_registry(home, (registry, now) => {
316
378
  registry.externals[external_id] = { public_key: { kty: 'EC', crv: 'P-256', x: public_key.x, y: public_key.y }, room_id: room.id, member_id: member.member_id,
317
379
  member_name: member.name, token_hash: sha256(token), label: clean_label, site: invite.site, created_at: now, key_expires_at: now + KEY_DAYS * DAY_MS };
318
380
  });
381
+ const activated = await local_call(room, 'POST', seat_path, { token: room.token, fetcher: ctx.fetcher, body: { action: 'activate', ...binding } });
382
+ if (activated.status !== 200) return { status: activated.status, body: activated.body };
319
383
  audit(home, { event: 'external.joined', room: room.id, external: external_id, member: member.name, invite: invite.invite_id });
320
384
  await ctx.on_change?.();
321
385
  return { status: 200, body: { external_id, site: invite.site, machine: { id: ctx.machine_id, name: ctx.link?.name ?? '', fingerprint: ctx.link ? machine_fingerprint(ctx.link) : '' },
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Line diffs of the files one execution changed, for the "edited N files +a -b" card on its message: each file's added
3
+ * and removed line counts and a unified patch, measured against the file as it stood when the execution began (the
4
+ * Git version when it was clean then). Node built-ins only; large or binary files report no lines.
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ // Files larger than this are listed without lines; patches are kept short enough to travel with the room.
11
+ const MAX_DIFF_BYTES = 256 * 1024;
12
+ const MAX_PATCH_LINES = 400;
13
+ const MAX_TOTAL_PATCH_CHARS = 400 * 1024;
14
+ const MAX_FILES = 200;
15
+ // Above this many differing lines the middle of a file is shown as replaced whole rather than aligned line by line.
16
+ const MAX_EDIT_DISTANCE = 4000;
17
+ const CONTEXT_LINES = 3;
18
+ const GIT_TIMEOUT_MS = 15_000;
19
+
20
+ /** A file's text, or a marker why it has no lines: missing, too large, or binary. */
21
+ function read_text(file) {
22
+ let size;
23
+ try { size = statSync(file).size; } catch { return { missing: true }; }
24
+ if (size > MAX_DIFF_BYTES) return { skipped: 'large' };
25
+ const bytes = readFileSync(file);
26
+ return bytes.includes(0) ? { skipped: 'binary' } : { text: bytes.toString('utf8') };
27
+ }
28
+
29
+ /**
30
+ * Keep the text of every file already changed when an execution begins (the snapshot's paths), so its diff counts only
31
+ * what the execution itself did to it. Files clean then are compared with Git at the end.
32
+ * @returns {Map<string, {text?: string, missing?: boolean, skipped?: string}>}
33
+ */
34
+ export function capture_base(directory, before) {
35
+ const base = new Map();
36
+ if (!directory || !before) return base;
37
+ for (const path of before.keys()) base.set(path, read_text(join(directory, path)));
38
+ return base;
39
+ }
40
+
41
+ /** The file as Git has it (the last commit), or missing when Git does not track it. */
42
+ function committed(directory, path) {
43
+ const result = spawnSync('git', ['-C', directory, 'show', `HEAD:${path}`], { maxBuffer: MAX_DIFF_BYTES * 2, windowsHide: true, timeout: GIT_TIMEOUT_MS });
44
+ if (result.status !== 0) return { missing: true };
45
+ if (result.stdout.length > MAX_DIFF_BYTES) return { skipped: 'large' };
46
+ return result.stdout.includes(0) ? { skipped: 'binary' } : { text: result.stdout.toString('utf8') };
47
+ }
48
+
49
+ const lines_of = (text) => (text ? text.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n') : []);
50
+
51
+ /** Myers' shortest edit script between two line arrays, as ['=', '-', '+', line] steps; null once it grows too long. */
52
+ function edit_script(a, b) {
53
+ const n = a.length, m = b.length, max = Math.min(n + m, MAX_EDIT_DISTANCE);
54
+ const offset = max + 1;
55
+ let v = new Int32Array(2 * max + 3);
56
+ const trace = [];
57
+ for (let d = 0; d <= max; d++) {
58
+ trace.push(v.slice());
59
+ for (let k = -d; k <= d; k += 2) {
60
+ let x = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? v[offset + k + 1] : v[offset + k - 1] + 1;
61
+ let y = x - k;
62
+ while (x < n && y < m && a[x] === b[y]) { x++; y++; }
63
+ v[offset + k] = x;
64
+ if (x >= n && y >= m) return backtrack(trace, a, b, offset, d);
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+
70
+ function backtrack(trace, a, b, offset, last) {
71
+ const steps = [];
72
+ let x = a.length, y = b.length;
73
+ for (let d = last; d >= 0; d--) {
74
+ const v = trace[d], k = x - y;
75
+ const previous = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? k + 1 : k - 1;
76
+ const px = d === 0 ? 0 : v[offset + previous], py = d === 0 ? 0 : px - previous;
77
+ while (x > px && y > py) { steps.push(['=', a[x - 1]]); x--; y--; }
78
+ if (d > 0) steps.push(x === px ? ['+', b[y - 1]] : ['-', a[x - 1]]);
79
+ if (d > 0) { x = px; y = py; }
80
+ }
81
+ return steps.reverse();
82
+ }
83
+
84
+ /** The steps from one text to the other: common ends kept, the middle aligned, or replaced whole when too different. */
85
+ function steps_between(before, after) {
86
+ const a = lines_of(before), b = lines_of(after);
87
+ let start = 0;
88
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
89
+ let end = 0;
90
+ while (end < a.length - start && end < b.length - start && a[a.length - 1 - end] === b[b.length - 1 - end]) end++;
91
+ const middle_a = a.slice(start, a.length - end), middle_b = b.slice(start, b.length - end);
92
+ const middle = edit_script(middle_a, middle_b)
93
+ || [...middle_a.map(line => ['-', line]), ...middle_b.map(line => ['+', line])];
94
+ return [...a.slice(0, start).map(line => ['=', line]), ...middle, ...a.slice(a.length - end).map(line => ['=', line])];
95
+ }
96
+
97
+ /** Unified-diff hunks with a few lines of context, cut at MAX_PATCH_LINES. */
98
+ function patch_of(steps) {
99
+ const lines = [];
100
+ let old_line = 1, new_line = 1, truncated = false;
101
+ const changed = steps.map(step => step[0] !== '=');
102
+ for (let index = 0; index < steps.length;) {
103
+ if (!changed[index]) { old_line++; new_line++; index++; continue; }
104
+ const from = Math.max(0, index - CONTEXT_LINES);
105
+ let to = index;
106
+ // A hunk runs on while changes come within twice the context of each other.
107
+ while (to < steps.length) {
108
+ let next = to;
109
+ while (next < steps.length && changed[next]) next++;
110
+ let gap = next;
111
+ while (gap < steps.length && !changed[gap] && gap - next < CONTEXT_LINES * 2) gap++;
112
+ if (gap < steps.length && changed[gap]) { to = gap; continue; }
113
+ to = Math.min(steps.length, next + CONTEXT_LINES);
114
+ break;
115
+ }
116
+ const lead = index - from;
117
+ let old_start = old_line - lead, new_start = new_line - lead, old_count = 0, new_count = 0;
118
+ const body = [];
119
+ for (let at = from; at < to; at++) {
120
+ const [kind, text] = steps[at];
121
+ body.push(`${kind === '=' ? ' ' : kind}${text}`);
122
+ if (kind !== '+') old_count++;
123
+ if (kind !== '-') new_count++;
124
+ }
125
+ for (let at = index; at < to; at++) {
126
+ if (steps[at][0] !== '+') old_line++;
127
+ if (steps[at][0] !== '-') new_line++;
128
+ }
129
+ lines.push(`@@ -${old_start},${old_count} +${new_start},${new_count} @@`, ...body);
130
+ index = to;
131
+ if (lines.length >= MAX_PATCH_LINES) { truncated = true; break; }
132
+ }
133
+ return { patch: lines.slice(0, MAX_PATCH_LINES).join('\n'), truncated: truncated || lines.length > MAX_PATCH_LINES };
134
+ }
135
+
136
+ /**
137
+ * Each changed path's `{path, added, removed, patch, truncated}`, or `{path, skipped}` for a large or binary file.
138
+ * @param {string} directory The working tree the paths are relative to.
139
+ * @param {string[]} paths The paths the execution changed.
140
+ * @param {Map} base What capture_base kept when the execution began.
141
+ */
142
+ export function file_diffs(directory, paths, base = new Map()) {
143
+ const results = [];
144
+ let total = 0;
145
+ for (const path of paths.slice(0, MAX_FILES)) {
146
+ const before = base.has(path) ? base.get(path) : committed(directory, path);
147
+ const after = read_text(join(directory, path));
148
+ const skipped = before.skipped || after.skipped;
149
+ if (skipped) { results.push({ path, skipped }); continue; }
150
+ const steps = steps_between(before.text || '', after.text || '');
151
+ const added = steps.filter(step => step[0] === '+').length, removed = steps.filter(step => step[0] === '-').length;
152
+ let { patch, truncated } = patch_of(steps);
153
+ if (total + patch.length > MAX_TOTAL_PATCH_CHARS) { patch = ''; truncated = true; }
154
+ total += patch.length;
155
+ results.push({ path, added, removed, patch, truncated, ...(before.missing ? { created: true } : {}), ...(after.missing ? { deleted: true } : {}) });
156
+ }
157
+ return results;
158
+ }
@@ -6,6 +6,7 @@ import { basename, join, resolve } from 'node:path';
6
6
  import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, session_exists, stored_delivery, takes_images } from './adapters/index.mjs';
7
7
  import { api as raw_api, overlapping_directories, read_rule } from './discussion_runner.mjs';
8
8
  import { SegmentLog } from './execution_progress.mjs';
9
+ import { capture_base, file_diffs } from './file_diff.mjs';
9
10
  import { free_task_text, TASK_SUBCOMMANDS, with_expert_prompt } from './expert_prompts.mjs';
10
11
  import { entry_access, site_fetch } from './entry_client.mjs';
11
12
  import { atomic_json } from './files.mjs';
@@ -1032,7 +1033,10 @@ export class FreeRoomRunner {
1032
1033
  const extras = member_extra_directories(this.config, adapter).filter(item => item.access === 'write')
1033
1034
  .map(item => ({ directory: item.path, before: workspace_snapshot(item.path) })).filter(item => item.before);
1034
1035
  // A resumed execution keeps the snapshot of its first delivery, so changes made before the pause are reported too.
1035
- if ((before || extras.length) && !this.snapshots.has(execution.id)) this.snapshots.set(execution.id, { member: member.name, directory, before, extras });
1036
+ if ((before || extras.length) && !this.snapshots.has(execution.id)) {
1037
+ // The text of files already changed, so the card's line counts cover only what this execution did to them.
1038
+ this.snapshots.set(execution.id, { member: member.name, directory, before, extras, base: capture_base(directory, before) });
1039
+ }
1036
1040
  const generation = (this.generations.get(execution.id) || 0) + 1;
1037
1041
  this.generations.set(execution.id, generation);
1038
1042
  // The turn's events follow it when a keep_working dispatch moves it onto a new execution.
@@ -1287,8 +1291,9 @@ export class FreeRoomRunner {
1287
1291
  for (const set of [this.denied, this.not_started, this.not_retryable]) if (set.delete(old)) set.add(id);
1288
1292
  if (this.failure_classes.has(old)) { this.failure_classes.set(id, this.failure_classes.get(old)); this.failure_classes.delete(old); }
1289
1293
  const snapshot = this.snapshots.get(old);
1294
+ const moved_before = snapshot?.before ? workspace_snapshot(snapshot.directory) : null;
1290
1295
  if (snapshot) this.snapshots.set(id, { member: snapshot.member, directory: snapshot.directory,
1291
- before: snapshot.before ? workspace_snapshot(snapshot.directory) : null,
1296
+ before: moved_before, base: capture_base(snapshot.directory, moved_before),
1292
1297
  extras: (snapshot.extras || []).map(item => ({ directory: item.directory, before: workspace_snapshot(item.directory) })),
1293
1298
  ...(snapshot.edited ? { edited: new Set() } : {}) });
1294
1299
  for (const prefix of ['owner', 'delivery']) {
@@ -1480,10 +1485,14 @@ export class FreeRoomRunner {
1480
1485
  const current = workspace_snapshot(item.directory);
1481
1486
  return current ? changed_between(item.before, current).map(path => extra_change(item.directory, path)) : [];
1482
1487
  });
1483
- const changes = [...(after ? changed_between(snapshot.before, after) : []), ...extra].slice(0, 200);
1488
+ const own = after ? changed_between(snapshot.before, after) : [];
1489
+ const changes = [...own, ...extra].slice(0, 200);
1484
1490
  // `edited` is sent only when the adapter tracked edits; without it the site cannot tell who wrote a shared file.
1485
1491
  const edited = snapshot.edited ? { edited: edited_changes(changes, snapshot.edited) } : {};
1486
- try { await api(this.config, `/executions/${execution_id}`, { action: 'report', changes, ...edited }); }
1492
+ // Line counts and patches of the files in the member's own working tree, for the card's "edited N files".
1493
+ let diffs = [];
1494
+ try { diffs = file_diffs(snapshot.directory, own.slice(0, 200), snapshot.base); } catch { /* The card then lists names only. */ }
1495
+ try { await api(this.config, `/executions/${execution_id}`, { action: 'report', changes, ...edited, ...(diffs.length ? { diffs } : {}) }); }
1487
1496
  catch (error) { if (!/HTTP (404|409)/.test(error.message)) throw error; }
1488
1497
  }
1489
1498
  }
@@ -1,5 +1,6 @@
1
1
  /** English CLI strings. */
2
2
  export default {
3
+ "room-invite 创建待签到席位并签发邀请;提供 member_id 时重发该席位链接,旧链接失效。须提供 room_id、token,可选 level(discuss/read)、folders、duration(1h/today/3d)、site_url;程序先读名单 revision 再建席位。链接有效 10 分钟,未签到席位 7 天结束;未绑定线上站点时只建立席位。": "room-invite reserves a seat and issues an invitation; member_id regenerates that seat's link and invalidates the old one. Requires room_id and token; optional level (discuss/read), folders, duration (1h/today/3d), site_url. The runner reads the roster revision before creating a seat. Links last 10 minutes; unclaimed seats end after 7 days. Without a connected hosted site, only the seat is created.",
3
4
  "连不上 {host}:{seconds} 秒内没有响应,请检查这台电脑的网络或代理后重试": "Cannot connect to {host}: no response within {seconds} seconds. Check this computer's network or proxy and try again",
4
5
  "连不上 {host}:连接被断开({reason}),请检查这台电脑的网络或代理后重试": "Cannot connect to {host}: the connection was closed ({reason}). Check this computer's network or proxy and try again",
5
6
  "实例启动失败(退出码 {code})": "Instance failed to start (exit code {code})",
@@ -499,6 +500,9 @@ export default {
499
500
  "邀请对应的房间已不在这台电脑上": "The invited room is no longer on this computer",
500
501
  "邀请开放的项目目录已不在房间里,请重新邀请": "A project folder opened by the invite is no longer in the room. Send a new invite",
501
502
  "邀请码不对或已过期,请让对方重新生成邀请": "The invite code is wrong or has expired. Ask for a new invite",
503
+ "邀请已更新,请重新生成链接": "The invitation has changed. Generate a new link",
504
+ "尝试次数过多,请十分钟后重试": "Too many attempts. Try again in ten minutes",
505
+ "席位已被认领,请让房主重新生成邀请": "This seat has already been claimed. Ask the owner to generate a new invitation",
502
506
  "需要本房间的控制凭据,且房间须在这台电脑上": "This needs the room's control credential, and the room must be on this computer",
503
507
  "邀请链接无效,请向对方重新索取": "The invitation link is invalid; ask the other side for a new one",
504
508
  "电脑编号格式不对": "Invalid computer id",