@evandu/super-pi 0.1.242 → 0.1.243

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,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-D8M5Jjzq.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-D0Po7xmY.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-BbMji0nU.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-CfAcuYba.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -5,7 +5,9 @@ import { DEFAULT_GROUP_MEMBER_IDS } from "../../shared/group-chat.js";
5
5
  import { CODING_STANDARD_REQUEST } from "../active-memory.js";
6
6
  import { applicableRules, assertModelAllowed } from "../model-filter.js";
7
7
  import { replaceFile } from "../persistence/rename.js";
8
- const MAX_AUTOMATIC_REPLIES = 3;
8
+ const MAX_AUTOMATIC_REPLIES = 10;
9
+ const MAX_REPLIES_PER_MEMBER = 3;
10
+ const CONTEXT_MESSAGES = 20;
9
11
  const MAX_CONTENT = 32_000;
10
12
  const timestamp = () => new Date().toISOString();
11
13
  function inputText(value, limit, label) {
@@ -47,22 +49,44 @@ async function readReferences(workspacePath, input) {
47
49
  }
48
50
  }));
49
51
  }
50
- function route(text, members, anchors) {
52
+ function route(text, candidates, anchors) {
51
53
  const parsed = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
52
54
  if (!parsed || typeof parsed !== "object")
53
55
  throw new Error("主持人未返回有效决定。");
54
56
  const decision = parsed;
57
+ const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 320) : undefined;
55
58
  if (decision.action === "finish")
56
- return undefined;
57
- if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !members.some(member => member.id === decision.memberId)) {
59
+ return { action: "finish", reason };
60
+ if (decision.action === "blocked" && reason)
61
+ return { action: "blocked", reason };
62
+ if (decision.action === "wait")
63
+ return { action: "wait", memberId: typeof decision.memberId === "string" ? decision.memberId : undefined };
64
+ if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !candidates.some(member => member.id === decision.memberId)) {
58
65
  throw new Error("主持人选择了无效的群成员。");
59
66
  }
60
67
  const replyTo = typeof decision.replyTo === "string" && anchors.has(decision.replyTo) ? decision.replyTo : undefined;
61
68
  const assignment = inputText(decision.assignment, 1600, "接话任务");
62
69
  if (!assignment)
63
70
  throw new Error("主持人没有给出接话任务。");
64
- const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 240) : undefined;
65
- return { memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
71
+ return { action: "reply", memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
72
+ }
73
+ function extractHandoff(author, content, members) {
74
+ const line = content.trimEnd().split(/\r?\n/u).at(-1)?.trim();
75
+ const request = line?.match(/^@([^::]{1,100})[::]\s*(.{1,800})$/u);
76
+ if (!request)
77
+ return;
78
+ const recipient = request[1].trim();
79
+ const matches = members.filter(member => member.id === recipient || member.name === recipient);
80
+ const assignment = request[2].trim();
81
+ if (matches.length === 1 && matches[0].id !== author && assignment)
82
+ return { memberId: matches[0].id, assignment };
83
+ }
84
+ function outstandingHandoffs(replies) {
85
+ return replies.flatMap(post => {
86
+ const handoff = post.status === "completed" ? post.handoff : undefined;
87
+ const delegated = handoff && replies.some(reply => reply.replyTo === post.id && reply.memberId === handoff.memberId && reply.status !== "failed");
88
+ return handoff && !delegated ? [{ ...handoff, replyTo: post.id, from: post.memberId }] : [];
89
+ });
66
90
  }
67
91
  export class GroupChatService {
68
92
  filePath;
@@ -307,6 +331,7 @@ export class GroupChatService {
307
331
  if (topic.memberIds.length)
308
332
  await start(topic.memberIds.map(memberId => ({ memberId, replyTo: topic.replyTo ?? topic.id })));
309
333
  let count = 0;
334
+ let incomplete;
310
335
  while (!controller.signal.aborted) {
311
336
  const current = this.rooms.find(item => item.id === room.id);
312
337
  if (current.messages.find(post => post.id === topic.id)?.status !== "running")
@@ -316,29 +341,69 @@ export class GroupChatService {
316
341
  const busy = new Set(current.messages.flatMap(post => post.role === "assistant" && (post.status === "running" || post.status === "queued") ? [post.memberId] : []));
317
342
  const available = current.members.filter(member => {
318
343
  const attempted = replies.filter(post => post.memberId === member.id);
319
- return attempted.length < 2 && attempted.every(post => post.status === "completed");
344
+ return attempted.length < MAX_REPLIES_PER_MEMBER && !attempted.some(post => post.status === "cancelled" || post.status === "interrupted");
320
345
  });
321
346
  const candidates = available.filter(member => !busy.has(member.id));
322
- const next = count < MAX_AUTOMATIC_REPLIES && candidates.length ? await this.choose(current, topic, candidates, controller.signal) : undefined;
323
- if (next) {
324
- const replyTo = next.replyTo ?? replies.filter(post => post.status === "completed").at(-1)?.id ?? topic.id;
347
+ const handoffs = outstandingHandoffs(replies);
348
+ const remaining = MAX_AUTOMATIC_REPLIES - count;
349
+ if (active.length && (!candidates.length || !remaining)) {
350
+ await Promise.race(active.map(reply => reply.done));
351
+ continue;
352
+ }
353
+ const next = candidates.length || handoffs.length || !remaining || (replies.length && available.some(member => busy.has(member.id)))
354
+ ? await this.choose(current, topic, candidates, replies, handoffs, busy, remaining, controller.signal)
355
+ : { action: "finish" };
356
+ if (next.action === "reply") {
357
+ if (!remaining) {
358
+ incomplete = "本轮达到自动接话上限,已有进展已保留。可以告诉群里从哪一步继续。";
359
+ break;
360
+ }
361
+ const completed = replies.filter(post => post.status === "completed").sort((a, b) => (a.settledAt ?? a.createdAt).localeCompare(b.settledAt ?? b.createdAt));
362
+ const handoff = handoffs.find(item => item.memberId === next.memberId);
363
+ const replyTo = next.replyTo ?? handoff?.replyTo ?? completed.at(-1)?.id ?? topic.id;
325
364
  count += 1;
326
365
  await start([{ ...next, replyTo }]);
366
+ continue;
327
367
  }
328
- else if (active.length) {
368
+ if (next.action === "wait") {
369
+ const work = next.memberId ? this.memberRuns.get(JSON.stringify([room.id, next.memberId])) : undefined;
370
+ if (work) {
371
+ await this.waitForWork(work, controller.signal);
372
+ continue;
373
+ }
374
+ }
375
+ if (active.length) {
329
376
  await Promise.race(active.map(reply => reply.done));
377
+ continue;
330
378
  }
331
- else if (!replies.length && available.length && this.memberRuns.size) {
379
+ if (next.action === "blocked") {
380
+ incomplete = next.reason;
381
+ break;
382
+ }
383
+ if (!replies.length && available.length) {
332
384
  const work = available.flatMap(member => this.memberRuns.get(JSON.stringify([room.id, member.id])) ?? []);
333
- if (!work.length)
334
- break;
335
- await this.waitForWork(Promise.race(work), controller.signal);
385
+ if (work.length) {
386
+ await this.waitForWork(Promise.race(work), controller.signal);
387
+ continue;
388
+ }
336
389
  }
337
- else
338
- break;
390
+ if (next.action === "wait") {
391
+ if (this.rooms.find(item => item.id === room.id)?.revision !== current.revision)
392
+ continue;
393
+ incomplete = "本轮仍有后续工作,但当前没有对应的运行任务。已有进展已保留。";
394
+ }
395
+ else if (handoffs.length && !next.reason) {
396
+ const work = handoffs.flatMap(handoff => this.memberRuns.get(JSON.stringify([room.id, handoff.memberId])) ?? []);
397
+ if (work.length) {
398
+ await this.waitForWork(Promise.race(work), controller.signal);
399
+ continue;
400
+ }
401
+ incomplete = "本轮还有未接手的工作,已有发言和结果已保留。";
402
+ }
403
+ break;
339
404
  }
340
405
  const replies = this.rooms.find(item => item.id === room.id).messages.filter(post => post.role === "assistant" && post.topicId === topic.id);
341
- await this.settle(room.id, topic.id, controller.signal, replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。");
406
+ await this.settle(room.id, topic.id, controller.signal, incomplete ?? (replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。"));
342
407
  }
343
408
  catch (error) {
344
409
  await Promise.allSettled(pending.map(reply => reply.done));
@@ -357,10 +422,11 @@ export class GroupChatService {
357
422
  context(room, topic) {
358
423
  const topicIndex = room.messages.findIndex(post => post.id === topic.id);
359
424
  const previous = room.messages.slice(0, topicIndex).filter(post => post.role === "user" && post.status !== "cancelled");
360
- const topicIds = new Set(previous.map(post => post.id).concat(topic.id));
361
- return room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed"
362
- : post.id !== topic.id && topicIds.has(post.id))
363
- .slice(-20).map(post => ({
425
+ const topicIds = new Set(previous.map(post => post.id));
426
+ const current = room.messages.filter(post => post.role === "assistant" && post.topicId === topic.id && post.status === "completed").slice(-CONTEXT_MESSAGES);
427
+ const roomHistory = room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed" : topicIds.has(post.id));
428
+ const remaining = CONTEXT_MESSAGES - current.length;
429
+ return [...(remaining ? roomHistory.slice(-remaining) : []), ...current].map(post => ({
364
430
  id: post.id, author: post.role === "user" ? "用户" : post.memberName ?? room.members.find(member => member.id === post.memberId)?.name,
365
431
  content: post.content.slice(0, 4_000),
366
432
  }));
@@ -375,31 +441,36 @@ export class GroupChatService {
375
441
  throw new Error("当前运行时不支持群聊模型。");
376
442
  return this.runtime.askOnce({ ...input, model, cwd: workspace.path });
377
443
  }
378
- async choose(room, topic, candidates, signal) {
444
+ async choose(room, topic, candidates, replies, handoffs, busy, remainingReplies, signal) {
379
445
  const context = this.context(room, topic);
380
- const performed = room.messages.filter((post) => post.role === "assistant" && post.topicId === topic.id)
381
- .map(({ memberId, status, assignment, background }) => ({ memberId, status, assignment, background }));
446
+ const performed = replies.map(({ id, memberId, replyTo, status, assignment, background, error }) => ({ id, memberId, replyTo, status, assignment, background, error }));
382
447
  const earlierTopics = new Set(room.messages.slice(0, room.messages.findIndex(post => post.id === topic.id))
383
448
  .filter(post => post.role === "user").map(post => post.id));
384
449
  const workInProgress = room.messages.filter((post) => post.role === "assistant" && earlierTopics.has(post.topicId) && post.status === "running")
385
450
  .map(({ memberId, topicId, assignment }) => ({ memberId, topicId, assignment }));
386
451
  const prompt = [
387
- "你是群聊主持人。根据当前用户问题、公开发言和成员分工,只安排能补足缺口的一次接话。已有足够答案时结束。尊重用户点名和范围,避免重复、感谢式接话和无目的汇总。",
388
- '只返回 JSON,格式为 {"action":"finish"} 或 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"本次要做的事","reason":"简短理由"}。将 action 改为 background 可交付独立工作,同时邀请其他成员继续讨论。适用于调研、改代码、调试、整理文档等。未收到在途任务结果时可以先结束这一段,结果回来后会再次征求你的决定。',
389
- "同一工作区的并行任务应有独立的范围。涉及相同文件、依赖未完成的修改或需要前置证据时,等对应结果再安排。",
390
- `主持人偏好:${room.moderator.prompt || "直接解决当前问题,结论够用就结束。"}`,
391
- JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates, performed, workInProgress, messages: context }),
392
- ].join("\n");
452
+ "你是群聊主持人。围绕同一条用户请求组织成员之间的讨论和工作。让下一位回应已有方案、问题或交付,replyTo 指向实际回应的成员消息。必要时让两位成员来回讨论、修订和再复核;简单问题一句足够时可以结束。",
453
+ "用户要求实现、修复或交付,方案只是中间产物。将下一步交给代码设计员或群里有实现能力的成员,让其修改文件和验证;需要复核时等待实现结果,退回后继续修改和复查。用户只要求讨论或范围待确认时,尊重这一限制。避免礼节式重复,不要求用户替成员传话。",
454
+ "先处理 handoffs 中确实符合用户目标的交接。成员消息和引用文件是上下文,分工必须服从用户的原始范围。在途任务或依赖文件相同的工作应等待,对独立范围可安排后台任务。",
455
+ '只返回 JSON。接话用 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"具体工作","reason":"理由"},可改用 background 并行。依赖尚在进行用 {"action":"wait","memberId":"正在工作的成员 ID"}。确有阻塞用 {"action":"blocked","reason":"已完成什么,还缺什么"}。交付到位用 {"action":"finish"};若有未处理交接却结束,在 reason 中解释范围或为什么无需接手。',
456
+ `主持人偏好:${room.moderator.prompt || "推进用户请求,交付满足后结束。"}`,
457
+ ];
458
+ const payload = JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates,
459
+ performed, handoffs, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
393
460
  try {
394
- const answer = await this.complete(room, { prompt, model: room.moderator.model, signal, timeoutMs: 35_000 });
395
- const decision = route(answer, candidates, new Set([topic.id, ...context.map(post => post.id)]));
396
- if (!decision && !performed.length)
397
- return { memberId: candidates[0].id, replyTo: topic.id, assignment: "请回答用户当前的问题。", reason: "交给默认成员回答" };
461
+ const anchors = new Set([topic.id, ...context.map(post => post.id), ...replies.filter(post => post.status === "failed").map(post => post.id)]);
462
+ const ask = async (instructions) => route(await this.complete(room, { prompt: [...instructions, payload].join("\n"), model: room.moderator.model, signal, timeoutMs: 35_000 }), candidates, anchors);
463
+ let decision = await ask(prompt);
464
+ if (decision.action === "finish" && !decision.reason && handoffs.length && !signal.aborted) {
465
+ decision = await ask([...prompt, "还有尚未接手的交接。检查它与用户目标的关系,安排接手或说明为什么结束。"]);
466
+ }
467
+ if (decision.action === "finish" && !performed.length && candidates[0])
468
+ return { action: "reply", memberId: candidates[0].id, replyTo: topic.id, assignment: "按用户要求推进当前工作。", reason: "交给默认成员" };
398
469
  return decision;
399
470
  }
400
471
  catch (error) {
401
472
  if (signal.aborted)
402
- return undefined;
473
+ return { action: "finish" };
403
474
  throw new Error(`主持人未能安排回复:${error instanceof Error ? error.message : String(error)}`);
404
475
  }
405
476
  }
@@ -493,8 +564,9 @@ export class GroupChatService {
493
564
  const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
494
565
  .catch(() => undefined);
495
566
  const prompt = [
496
- `你以 ${agent.name} 的身份在群聊中回答。请完成本次分工并给出可复核的结论。有可用工具且分工要求执行时,直接完成,其他成员可以继续讨论。只修改分工明确涉及的文件。`,
497
- JSON.stringify({ request: topic.content, files: topic.files, replyTo: reply.replyTo, quote: started.messages.find(post => post.id === reply.replyTo)?.content.slice(0, 4_000), assignment: reply.assignment, messages: this.context(started, topic), notes }),
567
+ `你以 ${agent.name} 的身份在群聊中回答。直接回应引用的成员意见,推进本次分工。有可用工具且分工要求执行时,直接完成并报告实际文件与验证;其他成员可以继续讨论。只修改分工涉及的文件。`,
568
+ "确实需要另一位成员推进时,在发言末尾另起一行写 @成员名:要接手的具体事项。主持人会按原请求判断并安排。可直接使用成员 ID。",
569
+ JSON.stringify({ request: topic.content, files: topic.files, replyTo: reply.replyTo, quote: started.messages.find(post => post.id === reply.replyTo)?.content.slice(0, 4_000), assignment: reply.assignment, members: started.members, messages: this.context(started, topic), notes }),
498
570
  ].join("\n");
499
571
  const answer = await this.complete(started, {
500
572
  prompt, agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
@@ -533,6 +605,11 @@ export class GroupChatService {
533
605
  if (content !== undefined)
534
606
  post.content = content.slice(0, MAX_CONTENT);
535
607
  post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
608
+ if (post.role === "assistant") {
609
+ post.settledAt = timestamp();
610
+ if (post.status === "completed")
611
+ post.handoff = extractHandoff(post.memberId, post.content, room.members);
612
+ }
536
613
  room.revision += 1;
537
614
  room.updatedAt = timestamp();
538
615
  });
@@ -12,7 +12,7 @@ import { basename, dirname, extname, join, relative, resolve } from "node:path";
12
12
  import { describe as describeFilesError, FilesError, fileMeta, listDirectory, MAX_FILE_BYTES, readWorkspaceFile, resolveInsideRoot, toRelative, writeWorkspaceFile, } from "./files.js";
13
13
  import { findUploadFile, MAX_UPLOAD_BODY_BYTES, saveUpload } from "./upload.js";
14
14
  import { describeThrown } from "./failure-text.js";
15
- import { checkDiskVersion } from "./version.js";
15
+ import { checkDiskVersion, readPackageVersion } from "./version.js";
16
16
  import { gitBlame, gitBranches, gitCommit, gitCommitDiff, gitDiff, gitGraph, gitLog, gitMutate, gitStagedDraftInput, gitStashes, gitStatus, gitWorktrees, resolveGitWorktree, inspectGitWorktree, gitWorktreeCommittedDiff } from "./git.js";
17
17
  import { computeFileDiff } from "./file-diff.js";
18
18
  import { verifyCapability } from "./capability.js";
@@ -25,7 +25,9 @@ import { createWorktreeService } from "./application/worktree-service.js";
25
25
  import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
26
26
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
27
27
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
28
- import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
28
+ import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
29
+ import { UpdateTracker } from "./update-status.js";
30
+ import { updateIsActive } from "../shared/update-status.js";
29
31
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
30
32
  import { ensureNameIndex, QUICK_OPEN_PAGE_SIZE, recordWorkspacePath } from "./file-name-index.js";
31
33
  import { resolveFileCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
@@ -358,6 +360,15 @@ export function createHttpServer(options) {
358
360
  const gitDrafts = new Set();
359
361
  const manageWorktree = createWorktreeService(context);
360
362
  const explicitFileOpen = createExplicitFileOpen();
363
+ let tracker;
364
+ const getUpdateTracker = () => tracker ??= new UpdateTracker(join(paths.dataDir ?? rootDir, "update-status.json"), rootDir);
365
+ const updateStatus = () => {
366
+ const status = getUpdateTracker().snapshot();
367
+ const operation = status.operation;
368
+ const lastUpdate = operation?.phase === "completed" || operation?.phase === "failed"
369
+ ? { ok: operation.phase === "completed", code: operation.failure?.code, at: operation.changedAt } : null;
370
+ return { ...status, updating: updateIsActive(operation), lastUpdate };
371
+ };
361
372
  return createServer(async (request, response) => {
362
373
  // Every HTTP request gets one stable id. It is returned to the browser and
363
374
  // included in the server log, so a report containing a status code or a
@@ -1162,127 +1173,146 @@ export function createHttpServer(options) {
1162
1173
  }
1163
1174
  if (url.pathname === "/api/update" && request.method === "POST") {
1164
1175
  if (!isLocalOrPrivateAddress(remote)) {
1165
- response.writeHead(403).end("Update requires a loopback or private network POST");
1176
+ json(403, { error: "只允许从本机或局域网更新服务。" });
1166
1177
  return;
1167
1178
  }
1168
- // THE BODY IS OPTIONAL. An old client sends nothing; that still has to work.
1169
1179
  let body = {};
1170
1180
  try {
1171
- const reader = textBodyReader();
1172
- let raw = "";
1173
- for await (const chunk of request) {
1174
- const piece = chunk;
1175
- raw = reader.push(piece);
1176
- if (raw.length > 4096)
1177
- break;
1181
+ const input = await readRequestText(request, 4096);
1182
+ if (input.tooLarge) {
1183
+ json(413, { error: "更新请求过大。" });
1184
+ return;
1178
1185
  }
1179
- raw = reader.finish();
1180
- body = raw.trim() ? JSON.parse(raw) : {};
1186
+ body = input.text.trim() ? JSON.parse(input.text) : {};
1181
1187
  }
1182
1188
  catch {
1183
- body = {};
1189
+ json(400, { error: "更新请求格式无效。" });
1190
+ return;
1184
1191
  }
1185
1192
  const wantedVersion = typeof body?.version === "string" && body.version ? body.version : undefined;
1186
1193
  const restartOnly = body?.restartOnly === true;
1187
- // ONE UPDATE AT A TIME. The client disables its button during an update, but a second tab
1188
- // (or a UI that failed to disable) can still reach this endpoint, and two npm installs against
1189
- // one global prefix corrupt each other. The slot is claimed BEFORE the 202 so a refused
1190
- // request never looks like one that started.
1194
+ if (wantedVersion && (wantedVersion.length > 128 || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/iu.test(wantedVersion))) {
1195
+ json(400, { error: "目标版本格式无效。" });
1196
+ return;
1197
+ }
1191
1198
  if (!claimUpdateSlot()) {
1192
- json(409, { error: "更新已经在进行中,请等它结束" });
1193
- return;
1194
- }
1195
- response.writeHead(202, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ status: "updating" }));
1196
- // EXACTLY ONE RELEASE PER CHILD. A spawn that fails to start emits "error" AND THEN "close",
1197
- // so a plain release in both handlers would free the slot a second time - and if a new
1198
- // update had already claimed it in between, that second release would hand the slot away
1199
- // while the new update was still running.
1200
- let released = false;
1201
- const release = () => { if (released)
1202
- return; released = true; releaseUpdateSlot(); };
1203
- // THE PORT AND HOST THE SERVER IS REALLY ON. The restart script has to find this very
1204
- // server by port to replace it, and it cannot work the port out on its own: the CLI starts
1205
- // the server with `--port=N` as an argument. Without them the script looked at the default
1206
- // port, found nothing there, and started a second server next to the running one.
1199
+ const current = updateStatus();
1200
+ const error = current.operation?.phase === "restarting" ? "服务正在重启,请等它结束。" : "更新已经在进行中,请等它结束。";
1201
+ json(409, { ...current, error });
1202
+ return;
1203
+ }
1204
+ const updateTracker = getUpdateTracker();
1205
+ let id;
1206
+ try {
1207
+ id = updateTracker.begin(restartOnly ? "restart" : "update", restartOnly ? checkDiskVersion(rootDir).diskVersion : wantedVersion);
1208
+ }
1209
+ catch (error) {
1210
+ releaseUpdateSlot();
1211
+ console.error("Super Pi: could not start update:", error);
1212
+ json(500, { error: "无法保存更新记录,请检查服务数据目录。" });
1213
+ return;
1214
+ }
1215
+ json(202, { ...updateStatus(), status: "updating" });
1216
+ let failed = false;
1217
+ const fail = (step, message, code) => {
1218
+ if (failed)
1219
+ return;
1220
+ failed = true;
1221
+ updateTracker.fail(id, step, message, code);
1222
+ releaseUpdateSlot();
1223
+ console.error(`Super Pi: ${message}`);
1224
+ };
1207
1225
  const listenPort = port ?? request.socket.localPort;
1208
- const restartEnv = { ...process.env, SUPER_PI_PORT: String(listenPort) };
1226
+ const restartEnv = { ...process.env, SUPER_PI_DATA_DIR: paths.dataDir, SUPER_PI_PORT: String(listenPort) };
1209
1227
  if (host)
1210
1228
  restartEnv.SUPER_PI_HOST = host;
1211
1229
  const restartNow = () => {
1212
- console.log("Super Pi: restart triggered.");
1213
- // INHERIT, NOT IGNORE. The restart script says what it did - which port it found, whether
1214
- // it refused to kill a process, how long the new server took to come up. With stdio
1215
- // "ignore" all of that went nowhere, so a failed restart left no trace anywhere and the
1216
- // only symptom was a console that had quietly died.
1217
- const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "inherit", env: restartEnv });
1218
- restart.on("error", (restartError) => console.error(`Super Pi: restart after update failed: ${restartError instanceof Error ? restartError.message : String(restartError)}`));
1219
- restart.unref();
1230
+ const deadline = setTimeout(() => fail("restarting", "等待新服务上线超时,请查看服务日志后重试。"), 150_000);
1231
+ deadline.unref();
1232
+ try {
1233
+ const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "inherit", env: restartEnv });
1234
+ restart.once("error", () => { clearTimeout(deadline); fail("restarting", "无法启动重启程序,请查看服务日志后重试。"); });
1235
+ restart.once("exit", (code) => {
1236
+ if (code !== 0) {
1237
+ clearTimeout(deadline);
1238
+ fail("restarting", "重启程序未能让服务重新上线,请查看服务日志。", code ?? undefined);
1239
+ }
1240
+ });
1241
+ restart.unref();
1242
+ }
1243
+ catch {
1244
+ clearTimeout(deadline);
1245
+ fail("restarting", "无法启动重启程序,请查看服务日志后重试。");
1246
+ }
1220
1247
  };
1221
- // RESTART ONLY: the code on disk is already new, the running server is not. Re-downloading
1222
- // 32.8 MB to restart a process is waste; the second button asks for exactly this.
1223
- // The outcome is recorded here as well: from the client's point of view a restart is the
1224
- // end of the update it started, and it needs to be able to say so.
1225
1248
  if (restartOnly) {
1226
- recordUpdateOutcome(true);
1227
- release();
1228
1249
  restartNow();
1229
1250
  return;
1230
1251
  }
1231
- // Use npm directly instead of `pi update` to avoid Windows detached+shell exit timing issues.
1232
- // npm's exit code correctly reflects whether the update succeeded.
1233
1252
  const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1234
1253
  const update = packageUpdateArgs(rootDir, wantedVersion);
1235
- const child = spawn(npmCmd, shellArgs(update.args), { stdio: "ignore", shell: process.platform === "win32", env: process.env });
1236
- // A SPAWN THAT NEVER STARTED. Node emits "error" and THEN "close" with a null code, so
1237
- // without this flag the close handler would read that null as a finished install and tell
1238
- // the user the update worked when npm never ran at all.
1239
- let spawnFailed = false;
1240
- child.on("close", (code) => {
1241
- // THE OUTCOME IS RECORDED BEFORE THE SLOT IS RELEASED. If the slot were released first,
1242
- // a client polling at that exact moment would see "not updating" with no outcome
1243
- // recorded and could not tell whether the install had worked.
1244
- if (code === 0 || (code === null && !spawnFailed)) {
1245
- recordUpdateOutcome(true);
1246
- release();
1247
- console.log("Super Pi: npm install completed, triggering restart.");
1254
+ try {
1255
+ const child = spawn(npmCmd, shellArgs(update.args), { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32", env: process.env });
1256
+ let stderr = "";
1257
+ child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-4096); });
1258
+ child.once("error", () => fail("installing", "无法启动 npm 安装程序,请检查服务日志。"));
1259
+ child.once("close", (code) => {
1260
+ if (failed)
1261
+ return;
1262
+ if (code !== 0) {
1263
+ const npmCode = /\bnpm\s+(?:ERR!|error)\s+code\s+([A-Z][A-Z0-9_]{1,30})\b/u.exec(stderr)?.[1];
1264
+ const detail = [npmCode, code === null ? "进程已中断" : `退出码 ${code}`].filter(Boolean).join(",");
1265
+ fail("installing", `安装更新失败(${detail})。`, code ?? undefined);
1266
+ return;
1267
+ }
1268
+ const installed = readPackageVersion(rootDir);
1269
+ if (!installed || (wantedVersion && installed !== wantedVersion)) {
1270
+ fail("installing", "npm 已退出,但当前服务的安装目录缺少目标版本。请核对安装位置。");
1271
+ return;
1272
+ }
1273
+ try {
1274
+ updateTracker.restarting(id, installed);
1275
+ }
1276
+ catch {
1277
+ fail("installing", "版本已安装,但无法保存重启状态。请手动重启服务。");
1278
+ return;
1279
+ }
1248
1280
  restartNow();
1249
- }
1250
- else {
1251
- recordUpdateOutcome(false, typeof code === "number" ? code : undefined);
1252
- release();
1253
- console.error(`Super Pi: npm install failed with code ${code}`);
1254
- }
1255
- });
1256
- child.on("error", (error) => { spawnFailed = true; recordUpdateOutcome(false); release(); console.warn(`Super Pi: update spawn failed: ${error instanceof Error ? error.message : "unknown error"}`); });
1257
- child.unref();
1281
+ });
1282
+ }
1283
+ catch {
1284
+ fail("installing", "无法启动 npm 安装程序,请检查服务日志。");
1285
+ }
1258
1286
  return;
1259
1287
  }
1260
- if (url.pathname === "/api/update-check" && request.method === "GET") {
1288
+ if ((url.pathname === "/api/update-status" || url.pathname === "/api/update-check") && request.method === "GET") {
1261
1289
  if (!isLocalOrPrivateAddress(remote)) {
1262
- response.writeHead(403).end("Update check requires a loopback or private network request");
1290
+ json(403, { error: "只允许从本机或局域网查看更新。" });
1291
+ return;
1292
+ }
1293
+ const current = updateStatus();
1294
+ if (url.pathname === "/api/update-status") {
1295
+ json(200, current);
1296
+ return;
1297
+ }
1298
+ if (current.updating) {
1299
+ json(200, { ...current, updateAvailable: false });
1263
1300
  return;
1264
1301
  }
1265
1302
  try {
1266
- const current = checkDiskVersion(rootDir);
1267
- // AN UPDATE IS RUNNING, so the registry question is not worth asking. The client polls
1268
- // this endpoint every two seconds while it waits for the install to finish, and npm's
1269
- // registry does not need one machine to ask it for the latest version a hundred times a
1270
- // minute. While the slot is held the answer is already known, so it is answered here.
1271
- if (isUpdateInFlight()) {
1272
- response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ ...current, updating: true, lastUpdate: getLastUpdateOutcome() ?? null, updateAvailable: false }));
1273
- return;
1274
- }
1275
- // Query the npm registry for the latest @evandu/super-pi version.
1276
- const remoteVersion = await fetch("https://registry.npmjs.org/@evandu/super-pi/latest").then(async (result) => {
1277
- if (!result.ok)
1278
- throw new Error(`npm registry HTTP ${result.status}`);
1279
- return result.json();
1280
- });
1303
+ const response = await fetch("https://registry.npmjs.org/@evandu/super-pi/latest", { signal: AbortSignal.timeout(10_000) });
1304
+ if (!response.ok)
1305
+ throw new Error(`npm registry HTTP ${response.status}`);
1306
+ const remoteVersion = await response.json();
1281
1307
  const latestVersion = typeof remoteVersion.version === "string" ? remoteVersion.version : undefined;
1282
- response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ ...current, latestVersion, updateAvailable: Boolean(latestVersion && latestVersion !== current.diskVersion), updating: isUpdateInFlight(), lastUpdate: getLastUpdateOutcome() ?? null }));
1308
+ if (!latestVersion)
1309
+ throw new Error("npm registry did not report a version");
1310
+ const status = updateStatus();
1311
+ json(200, { ...status, latestVersion, updateAvailable: !status.updating && latestVersion !== status.diskVersion });
1283
1312
  }
1284
1313
  catch (error) {
1285
- response.writeHead(502, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
1314
+ console.warn("Super Pi: update check failed:", error instanceof Error ? error.message : error);
1315
+ json(502, { error: "暂时无法获取最新版本,请检查服务器网络后重试。" });
1286
1316
  }
1287
1317
  return;
1288
1318
  }
@@ -2503,7 +2503,7 @@ export class PiRpcRuntime {
2503
2503
  throw new Error(this.pi.reason);
2504
2504
  const args = ["--mode", "rpc", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates"];
2505
2505
  if (input.agent && input.onToolStart) {
2506
- const nativeTools = ["read", "bash", "edit", "write", "grep", "find", "ls"];
2506
+ const nativeTools = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
2507
2507
  const selection = toolSelection(input.agent.tools);
2508
2508
  const allowed = nativeTools.filter(name => (selection.tools ?? nativeTools).includes(name) && !selection.excludeTools?.includes(name));
2509
2509
  args.push(...(allowed.length ? ["--tools", allowed.join(",")] : ["--no-tools"]));
@@ -0,0 +1,14 @@
1
+ import { type UpdateOperation, type UpdateStatus } from "../shared/update-status.js";
2
+ /** Keeps the last operation available to the service that comes up after a restart. */
3
+ export declare class UpdateTracker {
4
+ private readonly file;
5
+ private readonly root;
6
+ private operation;
7
+ constructor(file: string, root: string);
8
+ private save;
9
+ snapshot(): UpdateStatus;
10
+ begin(action: UpdateOperation["action"], targetVersion?: string): string;
11
+ private change;
12
+ restarting(id: string, targetVersion: string): void;
13
+ fail(id: string, step: "installing" | "restarting", message: string, code?: number): void;
14
+ }