@evandu/super-pi 0.1.242 → 0.1.244

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.
@@ -0,0 +1,77 @@
1
+ const MAX_STEPS = 48;
2
+ const MAX_THINKING_CHARS = 8000;
3
+ export function finishGroupExecution(trace) {
4
+ return { ...trace, steps: trace.steps.map(step => step.status === "running" ? { ...step, status: "interrupted" } : step) };
5
+ }
6
+ export class GroupExecutionRecorder {
7
+ sequence = 0;
8
+ thinkingChars = 0;
9
+ currentThinking;
10
+ changed = 0;
11
+ trace = { steps: [] };
12
+ get revision() { return this.changed; }
13
+ get activity() {
14
+ const tool = this.trace.steps.filter(step => step.kind === "tool" && step.status === "running").at(-1);
15
+ if (tool?.kind === "tool")
16
+ return { kind: "tool", name: tool.name, detail: tool.detail };
17
+ return this.currentThinking ? { kind: "thinking" } : undefined;
18
+ }
19
+ add(step) {
20
+ if (this.trace.steps.length === MAX_STEPS) {
21
+ const settled = this.trace.steps.findIndex(item => item.status !== "running");
22
+ this.trace.steps.splice(Math.max(settled, 0), 1);
23
+ this.trace.truncated = true;
24
+ }
25
+ this.trace.steps.push(step);
26
+ }
27
+ endThinking() {
28
+ if (!this.currentThinking)
29
+ return false;
30
+ this.currentThinking.status = "completed";
31
+ this.currentThinking = undefined;
32
+ return true;
33
+ }
34
+ record(event) {
35
+ if (event.kind === "thinking" && event.phase === "end") {
36
+ if (!this.endThinking())
37
+ return false;
38
+ }
39
+ else if (event.kind === "thinking") {
40
+ if (!this.currentThinking) {
41
+ this.currentThinking = { kind: "thinking", id: `thinking:${++this.sequence}`, startedAt: new Date().toISOString(), text: "", status: "running" };
42
+ this.add(this.currentThinking);
43
+ }
44
+ if (event.delta) {
45
+ const retained = event.delta.slice(0, MAX_THINKING_CHARS - this.thinkingChars);
46
+ if (!retained && this.trace.truncated)
47
+ return false;
48
+ this.currentThinking.text += retained;
49
+ this.thinkingChars += retained.length;
50
+ if (retained.length !== event.delta.length)
51
+ this.trace.truncated = true;
52
+ }
53
+ }
54
+ else {
55
+ const { name, detail, status, durationMs } = event.call;
56
+ const id = `tool:${event.call.id}`;
57
+ let step = this.trace.steps.find((item) => item.kind === "tool" && item.id === id);
58
+ const at = new Date().toISOString();
59
+ if (event.phase === "start")
60
+ this.endThinking();
61
+ if (!step) {
62
+ step = { kind: "tool", id, name, detail, startedAt: at, status: "running" };
63
+ this.add(step);
64
+ }
65
+ if (detail)
66
+ step.detail = detail;
67
+ if (event.phase === "update")
68
+ step.lastUpdateAt = at;
69
+ if (event.phase === "end") {
70
+ step.status = status === "error" ? "failed" : "completed";
71
+ step.durationMs = durationMs;
72
+ }
73
+ }
74
+ this.changed += 1;
75
+ return true;
76
+ }
77
+ }
@@ -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";
@@ -22,10 +22,13 @@ import { MAX_KNOWLEDGE_REQUEST_BYTES } from "./knowledge.js";
22
22
  import { MAX_DOCUMENT_REQUEST_BYTES } from "./application/document-service.js";
23
23
  import { parseMessageDeliveryMode } from "./application/run-service.js";
24
24
  import { createWorktreeService } from "./application/worktree-service.js";
25
+ import { GroupChatNotFoundError } from "./application/group-chat-service.js";
25
26
  import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
26
27
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
27
28
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
28
- import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
29
+ import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
30
+ import { UpdateTracker } from "./update-status.js";
31
+ import { updateIsActive } from "../shared/update-status.js";
29
32
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
30
33
  import { ensureNameIndex, QUICK_OPEN_PAGE_SIZE, recordWorkspacePath } from "./file-name-index.js";
31
34
  import { resolveFileCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
@@ -358,6 +361,15 @@ export function createHttpServer(options) {
358
361
  const gitDrafts = new Set();
359
362
  const manageWorktree = createWorktreeService(context);
360
363
  const explicitFileOpen = createExplicitFileOpen();
364
+ let tracker;
365
+ const getUpdateTracker = () => tracker ??= new UpdateTracker(join(paths.dataDir ?? rootDir, "update-status.json"), rootDir);
366
+ const updateStatus = () => {
367
+ const status = getUpdateTracker().snapshot();
368
+ const operation = status.operation;
369
+ const lastUpdate = operation?.phase === "completed" || operation?.phase === "failed"
370
+ ? { ok: operation.phase === "completed", code: operation.failure?.code, at: operation.changedAt } : null;
371
+ return { ...status, updating: updateIsActive(operation), lastUpdate };
372
+ };
361
373
  return createServer(async (request, response) => {
362
374
  // Every HTTP request gets one stable id. It is returned to the browser and
363
375
  // included in the server log, so a report containing a status code or a
@@ -405,15 +417,20 @@ export function createHttpServer(options) {
405
417
  const roomId = url.searchParams.get("id");
406
418
  try {
407
419
  if (request.method === "GET") {
420
+ const executionId = url.searchParams.get("execution");
421
+ if (executionId && !roomId) {
422
+ json(400, { error: "查看执行详情需要群聊 ID。" });
423
+ return;
424
+ }
408
425
  if (!roomId) {
409
426
  json(200, groups.list(workspaceId));
410
427
  return;
411
428
  }
412
- const room = groups.get(workspaceId, roomId);
413
- if (room.revision === url.searchParams.get("revision"))
429
+ const snapshot = executionId ? groups.execution(workspaceId, roomId, executionId) : groups.get(workspaceId, roomId);
430
+ if (snapshot.revision === url.searchParams.get("revision"))
414
431
  response.writeHead(204, { "cache-control": "no-store" }).end();
415
432
  else
416
- json(200, room);
433
+ json(200, snapshot);
417
434
  return;
418
435
  }
419
436
  if (request.method === "POST") {
@@ -435,6 +452,15 @@ export function createHttpServer(options) {
435
452
  json(200, await groups.configure(workspaceId, roomId, body));
436
453
  return;
437
454
  }
455
+ if (body?.action === "archive" || body?.action === "restore") {
456
+ json(200, await groups.setArchived(workspaceId, roomId, body.action === "archive"));
457
+ return;
458
+ }
459
+ if (body?.action === "delete") {
460
+ await groups.deleteArchived(workspaceId, roomId);
461
+ response.writeHead(204, { "cache-control": "no-store" }).end();
462
+ return;
463
+ }
438
464
  if (body?.action === "stop" && typeof body.postId === "string") {
439
465
  json(200, await groups.stop(workspaceId, roomId, body.postId));
440
466
  return;
@@ -445,7 +471,7 @@ export function createHttpServer(options) {
445
471
  response.writeHead(405, { allow: "GET, POST" }).end();
446
472
  }
447
473
  catch (error) {
448
- json(400, { error: describeThrown(error) || "群聊操作失败。" });
474
+ json(error instanceof GroupChatNotFoundError ? 404 : 400, { error: describeThrown(error) || "群聊操作失败。" });
449
475
  }
450
476
  return;
451
477
  }
@@ -1162,127 +1188,146 @@ export function createHttpServer(options) {
1162
1188
  }
1163
1189
  if (url.pathname === "/api/update" && request.method === "POST") {
1164
1190
  if (!isLocalOrPrivateAddress(remote)) {
1165
- response.writeHead(403).end("Update requires a loopback or private network POST");
1191
+ json(403, { error: "只允许从本机或局域网更新服务。" });
1166
1192
  return;
1167
1193
  }
1168
- // THE BODY IS OPTIONAL. An old client sends nothing; that still has to work.
1169
1194
  let body = {};
1170
1195
  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;
1196
+ const input = await readRequestText(request, 4096);
1197
+ if (input.tooLarge) {
1198
+ json(413, { error: "更新请求过大。" });
1199
+ return;
1178
1200
  }
1179
- raw = reader.finish();
1180
- body = raw.trim() ? JSON.parse(raw) : {};
1201
+ body = input.text.trim() ? JSON.parse(input.text) : {};
1181
1202
  }
1182
1203
  catch {
1183
- body = {};
1204
+ json(400, { error: "更新请求格式无效。" });
1205
+ return;
1184
1206
  }
1185
1207
  const wantedVersion = typeof body?.version === "string" && body.version ? body.version : undefined;
1186
1208
  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.
1209
+ if (wantedVersion && (wantedVersion.length > 128 || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/iu.test(wantedVersion))) {
1210
+ json(400, { error: "目标版本格式无效。" });
1211
+ return;
1212
+ }
1191
1213
  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.
1214
+ const current = updateStatus();
1215
+ const error = current.operation?.phase === "restarting" ? "服务正在重启,请等它结束。" : "更新已经在进行中,请等它结束。";
1216
+ json(409, { ...current, error });
1217
+ return;
1218
+ }
1219
+ const updateTracker = getUpdateTracker();
1220
+ let id;
1221
+ try {
1222
+ id = updateTracker.begin(restartOnly ? "restart" : "update", restartOnly ? checkDiskVersion(rootDir).diskVersion : wantedVersion);
1223
+ }
1224
+ catch (error) {
1225
+ releaseUpdateSlot();
1226
+ console.error("Super Pi: could not start update:", error);
1227
+ json(500, { error: "无法保存更新记录,请检查服务数据目录。" });
1228
+ return;
1229
+ }
1230
+ json(202, { ...updateStatus(), status: "updating" });
1231
+ let failed = false;
1232
+ const fail = (step, message, code) => {
1233
+ if (failed)
1234
+ return;
1235
+ failed = true;
1236
+ updateTracker.fail(id, step, message, code);
1237
+ releaseUpdateSlot();
1238
+ console.error(`Super Pi: ${message}`);
1239
+ };
1207
1240
  const listenPort = port ?? request.socket.localPort;
1208
- const restartEnv = { ...process.env, SUPER_PI_PORT: String(listenPort) };
1241
+ const restartEnv = { ...process.env, SUPER_PI_DATA_DIR: paths.dataDir, SUPER_PI_PORT: String(listenPort) };
1209
1242
  if (host)
1210
1243
  restartEnv.SUPER_PI_HOST = host;
1211
1244
  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();
1245
+ const deadline = setTimeout(() => fail("restarting", "等待新服务上线超时,请查看服务日志后重试。"), 150_000);
1246
+ deadline.unref();
1247
+ try {
1248
+ const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "inherit", env: restartEnv });
1249
+ restart.once("error", () => { clearTimeout(deadline); fail("restarting", "无法启动重启程序,请查看服务日志后重试。"); });
1250
+ restart.once("exit", (code) => {
1251
+ if (code !== 0) {
1252
+ clearTimeout(deadline);
1253
+ fail("restarting", "重启程序未能让服务重新上线,请查看服务日志。", code ?? undefined);
1254
+ }
1255
+ });
1256
+ restart.unref();
1257
+ }
1258
+ catch {
1259
+ clearTimeout(deadline);
1260
+ fail("restarting", "无法启动重启程序,请查看服务日志后重试。");
1261
+ }
1220
1262
  };
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
1263
  if (restartOnly) {
1226
- recordUpdateOutcome(true);
1227
- release();
1228
1264
  restartNow();
1229
1265
  return;
1230
1266
  }
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
1267
  const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1234
1268
  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.");
1269
+ try {
1270
+ const child = spawn(npmCmd, shellArgs(update.args), { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32", env: process.env });
1271
+ let stderr = "";
1272
+ child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-4096); });
1273
+ child.once("error", () => fail("installing", "无法启动 npm 安装程序,请检查服务日志。"));
1274
+ child.once("close", (code) => {
1275
+ if (failed)
1276
+ return;
1277
+ if (code !== 0) {
1278
+ const npmCode = /\bnpm\s+(?:ERR!|error)\s+code\s+([A-Z][A-Z0-9_]{1,30})\b/u.exec(stderr)?.[1];
1279
+ const detail = [npmCode, code === null ? "进程已中断" : `退出码 ${code}`].filter(Boolean).join(",");
1280
+ fail("installing", `安装更新失败(${detail})。`, code ?? undefined);
1281
+ return;
1282
+ }
1283
+ const installed = readPackageVersion(rootDir);
1284
+ if (!installed || (wantedVersion && installed !== wantedVersion)) {
1285
+ fail("installing", "npm 已退出,但当前服务的安装目录缺少目标版本。请核对安装位置。");
1286
+ return;
1287
+ }
1288
+ try {
1289
+ updateTracker.restarting(id, installed);
1290
+ }
1291
+ catch {
1292
+ fail("installing", "版本已安装,但无法保存重启状态。请手动重启服务。");
1293
+ return;
1294
+ }
1248
1295
  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();
1296
+ });
1297
+ }
1298
+ catch {
1299
+ fail("installing", "无法启动 npm 安装程序,请检查服务日志。");
1300
+ }
1258
1301
  return;
1259
1302
  }
1260
- if (url.pathname === "/api/update-check" && request.method === "GET") {
1303
+ if ((url.pathname === "/api/update-status" || url.pathname === "/api/update-check") && request.method === "GET") {
1261
1304
  if (!isLocalOrPrivateAddress(remote)) {
1262
- response.writeHead(403).end("Update check requires a loopback or private network request");
1305
+ json(403, { error: "只允许从本机或局域网查看更新。" });
1306
+ return;
1307
+ }
1308
+ const current = updateStatus();
1309
+ if (url.pathname === "/api/update-status") {
1310
+ json(200, current);
1311
+ return;
1312
+ }
1313
+ if (current.updating) {
1314
+ json(200, { ...current, updateAvailable: false });
1263
1315
  return;
1264
1316
  }
1265
1317
  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
- });
1318
+ const response = await fetch("https://registry.npmjs.org/@evandu/super-pi/latest", { signal: AbortSignal.timeout(10_000) });
1319
+ if (!response.ok)
1320
+ throw new Error(`npm registry HTTP ${response.status}`);
1321
+ const remoteVersion = await response.json();
1281
1322
  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 }));
1323
+ if (!latestVersion)
1324
+ throw new Error("npm registry did not report a version");
1325
+ const status = updateStatus();
1326
+ json(200, { ...status, latestVersion, updateAvailable: !status.updating && latestVersion !== status.diskVersion });
1283
1327
  }
1284
1328
  catch (error) {
1285
- response.writeHead(502, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
1329
+ console.warn("Super Pi: update check failed:", error instanceof Error ? error.message : error);
1330
+ json(502, { error: "暂时无法获取最新版本,请检查服务器网络后重试。" });
1286
1331
  }
1287
1332
  return;
1288
1333
  }
@@ -345,7 +345,7 @@ const projectService = new ProjectService(store, sessionOrchestratorService, {
345
345
  void sessionOrchestratorService.restoreWatchdogs().catch((error) => {
346
346
  console.warn("Super Pi: restoring watchdogs failed:", error instanceof Error ? error.message : String(error));
347
347
  });
348
- const groupChatService = await GroupChatService.open(join(dataDir, "group-chats.json"), store, runtime, memory);
348
+ const groupChatService = await GroupChatService.open(join(dataDir, "group-chats.json"), store, runtime, memory, update => broadcaster.broadcast({ type: "group.activity", ...update }));
349
349
  const serverContext = {
350
350
  memory,
351
351
  knowledge,
@@ -249,6 +249,15 @@ export type ForkOutcome = {
249
249
  /** Entry lines copied, header excluded. */
250
250
  entriesCopied: number;
251
251
  };
252
+ export type IsolatedExecutionEvent = {
253
+ kind: "thinking";
254
+ phase: "start" | "delta" | "end";
255
+ delta?: string;
256
+ } | {
257
+ kind: "tool";
258
+ phase: "start" | "update" | "end";
259
+ call: Pick<ToolCallNotice, "id" | "name" | "detail" | "status" | "durationMs">;
260
+ };
252
261
  export type IsolatedCompletionInput = {
253
262
  prompt: string;
254
263
  timeoutMs: number;
@@ -258,6 +267,7 @@ export type IsolatedCompletionInput = {
258
267
  agent?: AgentDefinition;
259
268
  onText?: (text: string) => void;
260
269
  onToolStart?: () => void;
270
+ onExecution?: (event: IsolatedExecutionEvent) => void;
261
271
  };
262
272
  export interface AgentRuntime {
263
273
  answer(input: AnswerInput): AsyncIterable<string>;
@@ -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"]));
@@ -2535,6 +2535,12 @@ export class PiRpcRuntime {
2535
2535
  let failure;
2536
2536
  const splitter = new InlineThinkingSplitter();
2537
2537
  const append = (parts) => {
2538
+ for (const part of parts) {
2539
+ if (part.kind === "thinking")
2540
+ input.onExecution?.({ kind: "thinking", phase: "delta", delta: part.text });
2541
+ else if (part.kind === "thinking-end")
2542
+ input.onExecution?.({ kind: "thinking", phase: "end" });
2543
+ }
2538
2544
  const delta = parts.filter(part => part.kind === "text").map(part => part.text).join("");
2539
2545
  if (!delta)
2540
2546
  return;
@@ -2554,10 +2560,29 @@ export class PiRpcRuntime {
2554
2560
  continue;
2555
2561
  if (record.type === "tool_execution_start")
2556
2562
  input.onToolStart?.();
2563
+ if (input.onExecution && record.toolCallId && (record.type === "tool_execution_start" || record.type === "tool_execution_update" || record.type === "tool_execution_end")) {
2564
+ const phase = record.type === "tool_execution_start" ? "start" : record.type === "tool_execution_update" ? "update" : "end";
2565
+ const name = (record.toolName ?? "tool").slice(0, 64);
2566
+ // Keep file targets and simple executable names. Command arguments and tool output stay in Pi.
2567
+ const detail = ["read", "write", "edit", "grep", "find", "ls"].includes(name)
2568
+ ? describeToolCall("read", record.args)
2569
+ : name === "bash" || name === "powershell" ? describeToolCall(name, record.args)?.match(/^[a-z][a-z\d_.-]{0,31}(?=\s|$)/i)?.[0] : undefined;
2570
+ input.onExecution({ kind: "tool", phase, call: {
2571
+ id: record.toolCallId.slice(0, 160), name, detail,
2572
+ status: phase === "end" ? record.isError === true ? "error" : "ok" : undefined,
2573
+ durationMs: typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? Math.max(0, Math.round(record.durationMs)) : undefined,
2574
+ } });
2575
+ }
2557
2576
  if (record.type === "message_update") {
2558
2577
  const event = record.assistantMessageEvent;
2559
2578
  if (event?.type === "text_delta")
2560
2579
  append(splitter.push(event.delta ?? ""));
2580
+ else if (event?.type === "thinking_start")
2581
+ input.onExecution?.({ kind: "thinking", phase: "start" });
2582
+ else if (event?.type === "thinking_delta")
2583
+ input.onExecution?.({ kind: "thinking", phase: "delta", delta: event.delta });
2584
+ else if (event?.type === "thinking_end")
2585
+ input.onExecution?.({ kind: "thinking", phase: "end" });
2561
2586
  if (event?.type === "done" || event?.type === "error")
2562
2587
  noteOutcome(event.message, event.type === "error" ? "error" : event.reason);
2563
2588
  }
@@ -6,6 +6,7 @@ export type ModelFilterRule = {
6
6
  };
7
7
  import type { WorkflowRun } from "./workflow.js";
8
8
  import type { BackgroundTaskDetails } from "../shared/background-task.js";
9
+ import type { GroupActivityUpdate } from "../shared/group-chat.js";
9
10
  import type { ScheduledTask } from "./scheduled-tasks.js";
10
11
  import type { ThinkingLevelMap } from "../shared/thinking-levels.js";
11
12
  import type { TerminalCommand, TerminalEvent } from "../shared/terminal-protocol.js";
@@ -1992,7 +1993,9 @@ export type ServerEvent = {
1992
1993
  type: "message.accepted";
1993
1994
  conversationId: string;
1994
1995
  clientId: string;
1995
- } | {
1996
+ } | ({
1997
+ type: "group.activity";
1998
+ } & GroupActivityUpdate) | {
1996
1999
  type: "run.stopping";
1997
2000
  conversationId: string;
1998
2001
  } | {
@@ -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
+ }
@@ -0,0 +1,69 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { updateIsActive } from "../shared/update-status.js";
4
+ import { checkDiskVersion } from "./version.js";
5
+ /** Keeps the last operation available to the service that comes up after a restart. */
6
+ export class UpdateTracker {
7
+ file;
8
+ root;
9
+ operation = null;
10
+ constructor(file, root) {
11
+ this.file = file;
12
+ this.root = root;
13
+ try {
14
+ const value = JSON.parse(readFileSync(file, "utf8"));
15
+ if (value?.id && ["installing", "restarting", "completed", "failed"].includes(value.phase))
16
+ this.operation = value;
17
+ }
18
+ catch { /* A new service has no update history. */ }
19
+ const previous = this.operation;
20
+ if (!previous || !updateIsActive(previous))
21
+ return;
22
+ const versions = checkDiskVersion(this.root);
23
+ if (previous.phase === "restarting" && previous.targetVersion === versions.runningVersion && !versions.needsRestart) {
24
+ this.change(previous.id, { phase: "completed" });
25
+ }
26
+ else if (previous.phase === "restarting") {
27
+ this.fail(previous.id, "restarting", `服务已重新启动,当前运行 v${versions.runningVersion}。请核对已安装版本。`);
28
+ }
29
+ else
30
+ this.fail(previous.id, "installing", "上一次安装期间服务退出。请检查已安装版本后重试。");
31
+ }
32
+ save(operation) {
33
+ const temporary = `${this.file}.${process.pid}.tmp`;
34
+ writeFileSync(temporary, JSON.stringify(operation), { encoding: "utf8", mode: 0o600 });
35
+ renameSync(temporary, this.file);
36
+ }
37
+ snapshot() { return { ...checkDiskVersion(this.root), operation: this.operation }; }
38
+ begin(action, targetVersion) {
39
+ const { runningVersion } = checkDiskVersion(this.root);
40
+ const startedAt = new Date().toISOString();
41
+ const operation = { id: randomUUID(), action, phase: action === "update" ? "installing" : "restarting",
42
+ fromVersion: runningVersion, targetVersion, startedAt, changedAt: startedAt };
43
+ this.save(operation);
44
+ this.operation = operation;
45
+ return operation.id;
46
+ }
47
+ change(id, change) {
48
+ if (this.operation?.id !== id || !updateIsActive(this.operation))
49
+ return;
50
+ const operation = { ...this.operation, ...change, changedAt: new Date().toISOString() };
51
+ this.operation = operation;
52
+ try {
53
+ this.save(operation);
54
+ }
55
+ catch (error) {
56
+ console.warn("Super Pi: could not save update status:", error);
57
+ }
58
+ }
59
+ restarting(id, targetVersion) {
60
+ if (this.operation?.id !== id || this.operation.phase !== "installing")
61
+ return;
62
+ const operation = { ...this.operation, phase: "restarting", targetVersion, changedAt: new Date().toISOString() };
63
+ this.save(operation);
64
+ this.operation = operation;
65
+ }
66
+ fail(id, step, message, code) {
67
+ this.change(id, { phase: "failed", failure: { step, message, code } });
68
+ }
69
+ }
@@ -41,20 +41,3 @@ export declare function packageUpdateArgs(rootDir: string, version?: string, pla
41
41
  export declare function claimUpdateSlot(): boolean;
42
42
  /** Releases the update slot, so the next update can start. */
43
43
  export declare function releaseUpdateSlot(): void;
44
- /**
45
- * Whether an update is running RIGHT NOW.
46
- *
47
- * The client used to keep its buttons disabled only for as long as its own request was in
48
- * flight, which ended the moment the server answered 202 - while npm was still installing.
49
- * The server knew the whole time (it holds the slot above), so it says so out loud and the
50
- * client asks.
51
- */
52
- export declare function isUpdateInFlight(): boolean;
53
- /** Records the outcome of an update attempt. */
54
- export declare function recordUpdateOutcome(ok: boolean, code?: number): void;
55
- /** The most recent update outcome, or undefined when no update has run in this process. */
56
- export declare function getLastUpdateOutcome(): {
57
- ok: boolean;
58
- code?: number;
59
- at: string;
60
- } | undefined;