ai_co_discuss 0.3.73 → 0.3.74

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.
@@ -8,6 +8,17 @@ const directory = resolve(process.env.CODISCUSS_IPC_DIRECTORY || process.cwd());
8
8
  const agentapi = process.env.ANTIGRAVITY_AGENTAPI_EXE;
9
9
  if (!agentapi) throw new Error('此程序必须由 Antigravity App Sidecar 启动');
10
10
 
11
+ /** Send only while the room still has this execution dispatched with a live lease. */
12
+ async function check_execution(access, event_id) {
13
+ const response = await fetch(`${access.site}/api/rooms/${access.room}/executions/${event_id}`, {
14
+ method: 'GET', redirect: 'error', signal: AbortSignal.timeout(10000),
15
+ headers: { 'Content-Type': 'application/json', 'X-Discussion-Token': access.token },
16
+ });
17
+ const event = await response.json();
18
+ if (!response.ok || event.status !== 'dispatched') throw new Error('请求已撤销或状态不明,未调用软件');
19
+ if (event.lease_until <= Math.floor(Date.now() / 1000)) throw new Error('执行租约已到期,未调用软件');
20
+ }
21
+
11
22
  /** Consume each request once; a crash after claim leaves an explicit uncertain result. */
12
23
  async function process_request(name) {
13
24
  const request = JSON.parse(readFileSync(join(directory, name), 'utf8'));
@@ -18,13 +29,8 @@ async function process_request(name) {
18
29
  writeFileSync(claim, String(process.pid), { flag: 'wx', mode: 0o600 });
19
30
  try {
20
31
  const access = JSON.parse(readFileSync(request.access_path, 'utf8'));
21
- const response = await fetch(`${access.site}/api/rooms/${access.room}/executions/${request.event_id}`, {
22
- method: 'GET', redirect: 'error', signal: AbortSignal.timeout(10000),
23
- headers: { 'Content-Type': 'application/json', 'X-Discussion-Token': access.token },
24
- });
25
- const event = await response.json();
26
- if (!response.ok || event.status !== 'dispatched') throw new Error('请求已撤销或状态不明,未调用软件');
27
- if (event.lease_until <= Math.floor(Date.now() / 1000)) throw new Error('执行租约已到期,未调用软件');
32
+ // A private chat line is not a room execution; the runner checked it just before writing the request.
33
+ if (!request.chat) await check_execution(access, request.event_id);
28
34
  const args = request.session_id ? ['send-message', request.session_id, request.prompt] : ['new-conversation', request.prompt];
29
35
  const raw = execFileSync(agentapi, ['agentapi', ...args], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
30
36
  const result = JSON.parse(raw);
@@ -44,6 +50,29 @@ async function scan_requests() {
44
50
  }
45
51
  }
46
52
 
47
- atomic_json(join(directory, 'ready.json'), { pid: process.pid, ready_at: Date.now(), project_id: process.env.ANTIGRAVITY_PROJECT_ID || '' });
48
- scan_requests();
49
- setInterval(scan_requests, 1000);
53
+ // The App's local language server and its per-launch token, the two variables agentapi itself connects with; the runner
54
+ // follows a private chat turn through them (antigravity_app.mjs). Left out when the App does not pass them.
55
+ const language_server = process.env.ANTIGRAVITY_LS_ADDRESS && process.env.ANTIGRAVITY_CSRF_TOKEN
56
+ ? { address: process.env.ANTIGRAVITY_LS_ADDRESS, csrf_token: process.env.ANTIGRAVITY_CSRF_TOKEN } : null;
57
+ atomic_json(join(directory, 'ready.json'), { pid: process.pid, ready_at: Date.now(), project_id: process.env.ANTIGRAVITY_PROJECT_ID || '',
58
+ ...(language_server ? { language_server } : {}) });
59
+
60
+ /**
61
+ * Whether this Sidecar has been replaced and must stop: a newer one of this directory rewrote ready.json with its own
62
+ * pid (the App restarted), or the App's server that started this one has exited. Restarting the App does not end the
63
+ * old Sidecar, which would otherwise keep claiming requests with its old code.
64
+ */
65
+ function superseded() {
66
+ try { if (JSON.parse(readFileSync(join(directory, 'ready.json'), 'utf8')).pid !== process.pid) return true; }
67
+ catch { /* Being rewritten or removed: the parent check still decides. */ }
68
+ try { process.kill(process.ppid, 0); return false; }
69
+ catch (error) { return error.code === 'ESRCH'; }
70
+ }
71
+
72
+ /** Check before every scan, so a replaced Sidecar claims nothing more. */
73
+ function tick() {
74
+ if (superseded()) process.exit(0);
75
+ scan_requests();
76
+ }
77
+ tick();
78
+ setInterval(tick, 1000);
@@ -379,11 +379,81 @@ export async function api_delivery(profile, binding, task) {
379
379
 
380
380
  // The call is the runner's own, so it can be aborted and its tool steps are seen.
381
381
  const API_CALL = { stoppable: true, progress: true };
382
+ // Tools a private chat may use: reading the room and the project; it answers in text, not through room writes.
383
+ const CHAT_ROOM_TOOLS = ['read_room', 'read_messages', 'read_message'];
384
+
385
+ /** One earlier private chat line and its reply as protocol messages, so the model keeps the conversation. */
386
+ function chat_messages(profile, history) {
387
+ return history.flatMap(({ text, reply }) => profile.api_protocol === 'gemini'
388
+ ? [{ role: 'user', parts: [{ text }] }, { role: 'model', parts: [{ text: reply }] }]
389
+ : [{ role: 'user', content: text }, { role: 'assistant', content: reply }]);
390
+ }
391
+
392
+ /**
393
+ * A private chat turn for a model API member, which keeps no session of its own: the earlier lines are its context.
394
+ * It may read the room and the project with tools and answers in plain text; each tool step is logged as an entry
395
+ * the chat page shows, and interjections join before the next model request.
396
+ */
397
+ async function api_chat(profile, binding, task) {
398
+ const key = read_api_key(task.api_context.home, profile);
399
+ const controller = new AbortController();
400
+ const child = new EventEmitter();
401
+ child.kill = () => { controller.abort(); return true; };
402
+ const context = { ...task.api_context, participant: task.participant, directory: task.directory, task_id: task.id,
403
+ signal: controller.signal, on_edits: task.on_edits, project: open_project(task.api_context, [task.api_context.home, task.directory]) };
404
+ const log_path = resolve(task.directory, `api-${task.id}.log`);
405
+ const log = entry => task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.entry', entry })}\n`);
406
+ const interjections = [];
407
+ let running = true;
408
+ task.on_process?.(child);
409
+ setImmediate(async () => {
410
+ try {
411
+ const tools = participant_tools(context).filter(item => CHAT_ROOM_TOOLS.includes(item.name) || is_file_tool(item.name));
412
+ const system = [`你是协作房间的成员 ${task.participant}。房主正在私聊窗口直接和你对话,其他成员看不到。直接用文字回答;需要时可以用工具读取房间消息${context.project ? '或项目文件' : ''}。`,
413
+ expert_prompt(profile)].filter(Boolean).join('\n\n');
414
+ const state = { system, tools, history: [...chat_messages(profile, task.chat_history || []), ...api_history(profile, task.prompt)] };
415
+ const turns = max_requests(context);
416
+ for (let index = 0; !turns || index < turns; index++) {
417
+ for (const text of interjections.splice(0)) add_user_text(profile, state.history, `用户插话:${text}`);
418
+ task.on_activity?.('thinking');
419
+ const calls = await generate_with_retry(profile, key, state, controller.signal);
420
+ const remark = last_reply_text(state.history, Infinity);
421
+ if (!calls.length) {
422
+ if (!remark) throw new Error('模型没有给出文字回复');
423
+ task.on_note?.(remark);
424
+ return task.on_exit?.();
425
+ }
426
+ if (remark) log({ kind: 'message', body: remark });
427
+ const results = [];
428
+ for (const call of calls) {
429
+ controller.signal.throwIfAborted();
430
+ // A chat only reads, so a tool that fails (the site unreachable for a moment) goes back to the model as its
431
+ // result instead of ending the turn; a stop still ends it.
432
+ const outcome = await execute_tool(context, call, tools).catch(error => {
433
+ if (controller.signal.aborted) throw error;
434
+ return { result: { error: String(error.message || error).replaceAll(key, '[已隐藏]') } };
435
+ });
436
+ const body = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result);
437
+ log({ id: `call-${call.id}`, kind: WRITE_TOOLS.includes(call.name) ? 'edit' : 'tool', title: `${call.name} ${typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments || {})}`,
438
+ state: outcome.result?.error ? 'failed' : 'done', body });
439
+ results.push({ ...call, result: outcome.result });
440
+ }
441
+ api_tool_results(profile, state.history, results);
442
+ }
443
+ throw new Error(`私聊超过 ${turns} 次模型请求,已停止`);
444
+ } catch (error) {
445
+ task.on_failure?.(controller.signal.aborted ? '已停止' : error.message.replaceAll(key, '[已隐藏]'));
446
+ } finally { running = false; child.emit('close', 0); }
447
+ });
448
+ const steer = text => { if (!running) return false; interjections.push(text); return true; };
449
+ return { status: 'accepted', session_id: binding.session_id || '', capabilities: API_CALL, steer };
450
+ }
382
451
 
383
452
  /** The model API's behaviour; its static facts are in profiles.mjs. */
384
453
  export const api = {
385
454
  id: 'api',
386
455
  deliver: api_delivery,
456
+ chat: api_chat,
387
457
  session: null,
388
458
  models: null,
389
459
  };