@oyasmi/pipiclaw 0.9.6-beta.1 → 0.9.6-beta.2

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.
Files changed (258) hide show
  1. package/README.en.md +279 -215
  2. package/README.md +274 -213
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +3 -2
  6. package/dist/agent/channel-runner.js +16 -27
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +1 -1
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/event-guards.d.ts +2 -1
  23. package/dist/agent/session/event-guards.js +6 -0
  24. package/dist/agent/session/model-selection.d.ts +2 -1
  25. package/dist/agent/session/model-selection.js +5 -5
  26. package/dist/agent/session/session-events.js +31 -4
  27. package/dist/agent/session/session-host.d.ts +4 -2
  28. package/dist/agent/session/session-host.js +17 -15
  29. package/dist/agent/status-render.js +3 -0
  30. package/dist/agent/turn/task-digest.d.ts +2 -5
  31. package/dist/agent/turn/task-digest.js +25 -45
  32. package/dist/agent/turn/turn-context.js +4 -6
  33. package/dist/agent/turn/turn-error.d.ts +1 -1
  34. package/dist/agent/turn/turn-error.js +9 -0
  35. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  36. package/dist/agent/turn/turn-pipeline.js +36 -7
  37. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  38. package/dist/agent/turn/turn-prompt.js +2 -1
  39. package/dist/agent/turn/turn-recovery.js +4 -1
  40. package/dist/agent/types.d.ts +20 -2
  41. package/dist/agent/types.js +2 -0
  42. package/dist/app/auth-command.d.ts +25 -0
  43. package/dist/app/auth-command.js +200 -67
  44. package/dist/app/home.d.ts +7 -8
  45. package/dist/app/home.js +143 -56
  46. package/dist/channel/channel-context.d.ts +6 -0
  47. package/dist/channel/config.d.ts +3 -0
  48. package/dist/channel/config.js +11 -5
  49. package/dist/commands/catalog.js +22 -6
  50. package/dist/desk/commands.d.ts +31 -4
  51. package/dist/desk/commands.js +101 -15
  52. package/dist/desk/paths.d.ts +6 -0
  53. package/dist/desk/paths.js +21 -1
  54. package/dist/desk/registry.d.ts +11 -0
  55. package/dist/desk/registry.js +53 -9
  56. package/dist/desk/types.d.ts +66 -1
  57. package/dist/dingtalk/config.js +10 -10
  58. package/dist/dingtalk/delivery.js +2 -0
  59. package/dist/dingtalk/inbound.js +2 -3
  60. package/dist/events/watcher.d.ts +1 -1
  61. package/dist/events/watcher.js +2 -2
  62. package/dist/main.js +15 -3
  63. package/dist/memory/boundary-work.d.ts +2 -1
  64. package/dist/memory/boundary-work.js +1 -1
  65. package/dist/memory/lifecycle.d.ts +2 -1
  66. package/dist/memory/lifecycle.js +2 -2
  67. package/dist/memory/reflect-job.d.ts +2 -1
  68. package/dist/memory/reflect-job.js +1 -1
  69. package/dist/memory/reflect.d.ts +2 -1
  70. package/dist/memory/reflect.js +2 -1
  71. package/dist/memory/scheduler.d.ts +2 -1
  72. package/dist/memory/scheduler.js +1 -1
  73. package/dist/memory/session-corpus.js +7 -1
  74. package/dist/memory/session-search.d.ts +2 -1
  75. package/dist/memory/session-search.js +1 -1
  76. package/dist/memory/sidecar-worker.d.ts +2 -1
  77. package/dist/memory/sidecar-worker.js +2 -4
  78. package/dist/models/credential-work.d.ts +7 -0
  79. package/dist/models/credential-work.js +36 -0
  80. package/dist/models/login-ui.js +4 -4
  81. package/dist/models/provider-login.js +7 -6
  82. package/dist/models/requests.d.ts +8 -0
  83. package/dist/models/requests.js +69 -0
  84. package/dist/models/runtime.d.ts +3 -1
  85. package/dist/models/runtime.js +9 -2
  86. package/dist/playbooks/agent-delegation.md +19 -45
  87. package/dist/playbooks/background-jobs.md +1 -1
  88. package/dist/playbooks/catalog.js +1 -1
  89. package/dist/playbooks/delegation-inline.md +25 -0
  90. package/dist/playbooks/delegation-recovery.md +28 -0
  91. package/dist/playbooks/event-scheduling.md +18 -37
  92. package/dist/playbooks/event-sensors.md +26 -0
  93. package/dist/playbooks/event-task-template.md +22 -0
  94. package/dist/playbooks/learning-and-skills.md +26 -0
  95. package/dist/playbooks/memory-operations.md +36 -0
  96. package/dist/playbooks/outbound-media.md +2 -2
  97. package/dist/playbooks/runtime-files.md +29 -0
  98. package/dist/playbooks/runtime-operations.md +25 -0
  99. package/dist/playbooks/runtime-orientation.md +18 -53
  100. package/dist/playbooks/task-lead.md +22 -68
  101. package/dist/playbooks/task-manage.md +38 -0
  102. package/dist/playbooks/task-recovery.md +24 -0
  103. package/dist/playbooks/task-verify.md +22 -0
  104. package/dist/runtime/bootstrap.d.ts +4 -0
  105. package/dist/runtime/bootstrap.js +82 -22
  106. package/dist/runtime/daemon-lock.js +3 -3
  107. package/dist/runtime/desk-runtime.d.ts +33 -6
  108. package/dist/runtime/desk-runtime.js +302 -47
  109. package/dist/runtime/ingress-commands.js +24 -4
  110. package/dist/runtime/shutdown.d.ts +3 -1
  111. package/dist/runtime/shutdown.js +1 -0
  112. package/dist/runtime/task-close.d.ts +1 -1
  113. package/dist/runtime/task-close.js +6 -3
  114. package/dist/runtime/task-control.d.ts +1 -3
  115. package/dist/runtime/task-control.js +15 -11
  116. package/dist/runtime/task-input.js +1 -1
  117. package/dist/runtime/task-lane-types.d.ts +12 -2
  118. package/dist/runtime/task-lane-types.js +9 -0
  119. package/dist/runtime/task-lane.d.ts +1 -0
  120. package/dist/runtime/task-lane.js +17 -14
  121. package/dist/runtime/task-step.d.ts +3 -3
  122. package/dist/runtime/task-step.js +23 -14
  123. package/dist/runtime/transports.js +6 -5
  124. package/dist/security/command-guard.js +23 -1
  125. package/dist/subagents/commands.js +14 -5
  126. package/dist/subagents/completion-wake.js +6 -0
  127. package/dist/subagents/dispatch.js +20 -18
  128. package/dist/subagents/external/dispatch.js +20 -14
  129. package/dist/subagents/external/run.js +10 -20
  130. package/dist/subagents/external/settlement.js +5 -1
  131. package/dist/subagents/internal/outcome.js +19 -12
  132. package/dist/subagents/internal/provider-retry.js +1 -3
  133. package/dist/subagents/internal/run.d.ts +1 -1
  134. package/dist/subagents/internal/run.js +27 -4
  135. package/dist/subagents/internal/state.d.ts +1 -3
  136. package/dist/subagents/internal/state.js +1 -2
  137. package/dist/subagents/internal/worker.js +17 -9
  138. package/dist/subagents/result.d.ts +5 -2
  139. package/dist/subagents/result.js +35 -6
  140. package/dist/subagents/run-record.d.ts +21 -0
  141. package/dist/subagents/run-record.js +5 -0
  142. package/dist/subagents/runs.d.ts +4 -7
  143. package/dist/subagents/runs.js +24 -35
  144. package/dist/subagents/task-envelope.js +5 -0
  145. package/dist/subagents/task-settlement.js +1 -0
  146. package/dist/subagents/types.d.ts +14 -4
  147. package/dist/subagents/workspace-lease.d.ts +37 -10
  148. package/dist/subagents/workspace-lease.js +121 -13
  149. package/dist/subagents/worktree.d.ts +47 -5
  150. package/dist/subagents/worktree.js +316 -30
  151. package/dist/tasks/brief.d.ts +5 -1
  152. package/dist/tasks/brief.js +19 -5
  153. package/dist/tasks/commands.d.ts +3 -1
  154. package/dist/tasks/commands.js +17 -6
  155. package/dist/tasks/control.d.ts +9 -0
  156. package/dist/tasks/loop-log.d.ts +10 -0
  157. package/dist/tasks/loop-log.js +1 -1
  158. package/dist/tasks/receipts.d.ts +7 -3
  159. package/dist/tasks/receipts.js +34 -5
  160. package/dist/tools/bash.d.ts +3 -0
  161. package/dist/tools/bash.js +27 -15
  162. package/dist/tools/contract/presentation.js +4 -1
  163. package/dist/tools/edit-diff.d.ts +11 -0
  164. package/dist/tools/edit-diff.js +148 -0
  165. package/dist/tools/edit-match.d.ts +18 -0
  166. package/dist/tools/edit-match.js +242 -0
  167. package/dist/tools/edit.d.ts +10 -2
  168. package/dist/tools/edit.js +91 -361
  169. package/dist/tools/event-manage.d.ts +1 -2
  170. package/dist/tools/event-manage.js +27 -38
  171. package/dist/tools/file-observations.d.ts +9 -0
  172. package/dist/tools/file-observations.js +50 -0
  173. package/dist/tools/glob-match.d.ts +3 -1
  174. package/dist/tools/glob-match.js +40 -17
  175. package/dist/tools/glob.d.ts +1 -0
  176. package/dist/tools/glob.js +39 -19
  177. package/dist/tools/grep-command.d.ts +13 -0
  178. package/dist/tools/grep-command.js +77 -0
  179. package/dist/tools/grep.js +96 -201
  180. package/dist/tools/index.d.ts +4 -1
  181. package/dist/tools/index.js +7 -4
  182. package/dist/tools/job.js +12 -11
  183. package/dist/tools/read.d.ts +2 -0
  184. package/dist/tools/read.js +10 -2
  185. package/dist/tools/registry.d.ts +16 -11
  186. package/dist/tools/registry.js +29 -11
  187. package/dist/tools/session-search.d.ts +2 -1
  188. package/dist/tools/session-search.js +14 -4
  189. package/dist/tools/skill.js +13 -12
  190. package/dist/tools/subagent-manage.js +10 -3
  191. package/dist/tools/subagent.d.ts +22 -2
  192. package/dist/tools/subagent.js +19 -18
  193. package/dist/tools/task-manage/control-tools.js +1 -1
  194. package/dist/tools/task-manage/factory.d.ts +2 -2
  195. package/dist/tools/task-manage/factory.js +39 -3
  196. package/dist/tools/task-manage/lifecycle.d.ts +2 -2
  197. package/dist/tools/task-manage/lifecycle.js +7 -4
  198. package/dist/tools/task-manage/shared.d.ts +1 -1
  199. package/dist/tools/task-manage/types.d.ts +1 -0
  200. package/dist/tools/write-content.d.ts +7 -1
  201. package/dist/tools/write-content.js +18 -6
  202. package/dist/tools/write.d.ts +3 -0
  203. package/dist/tools/write.js +6 -2
  204. package/dist/tui/cli.d.ts +5 -0
  205. package/dist/tui/cli.js +97 -31
  206. package/dist/tui/client.d.ts +5 -0
  207. package/dist/tui/client.js +63 -21
  208. package/dist/tui/frontend.d.ts +2 -0
  209. package/dist/tui/pitui-frontend.d.ts +4 -0
  210. package/dist/tui/pitui-frontend.js +27 -0
  211. package/dist/tui/render.d.ts +1 -0
  212. package/dist/tui/render.js +5 -0
  213. package/dist/tui/session.js +6 -0
  214. package/dist/web/client.d.ts +1 -0
  215. package/dist/web/client.js +11 -0
  216. package/dist/web/fetch.js +6 -3
  217. package/dist/webapi/auth.d.ts +0 -3
  218. package/dist/webapi/auth.js +3 -7
  219. package/dist/webapi/config.js +17 -14
  220. package/dist/webapi/key-command.js +41 -41
  221. package/dist/webapi/response-state.d.ts +7 -1
  222. package/dist/webapi/response-state.js +166 -3
  223. package/dist/webapi/routes/websocket.js +24 -1
  224. package/dist/webapi/server.d.ts +3 -1
  225. package/dist/webapi/server.js +32 -1
  226. package/dist/webapi/service.js +8 -0
  227. package/dist/webapi/transport.d.ts +2 -0
  228. package/dist/webapi/transport.js +11 -1
  229. package/examples/sub-agents/README.md +9 -7
  230. package/examples/sub-agents/agy-main.md +21 -0
  231. package/examples/sub-agents/claude-high.md +21 -0
  232. package/examples/sub-agents/claude-main.md +21 -0
  233. package/examples/sub-agents/codex-flash.md +21 -0
  234. package/examples/sub-agents/codex-high.md +21 -0
  235. package/examples/sub-agents/codex-main.md +21 -0
  236. package/examples/sub-agents/codex-review.md +20 -0
  237. package/examples/sub-agents/cursor-high.md +20 -0
  238. package/examples/sub-agents/cursor-main.md +20 -0
  239. package/examples/sub-agents/glm-flash.md +21 -0
  240. package/examples/sub-agents/glm-high.md +21 -0
  241. package/examples/sub-agents/pi-scout.md +20 -0
  242. package/package.json +8 -9
  243. package/dist/agent/session/request-tools.d.ts +0 -3
  244. package/dist/agent/session/request-tools.js +0 -20
  245. package/dist/models/api-keys.d.ts +0 -11
  246. package/dist/models/api-keys.js +0 -22
  247. package/dist/playbooks/memory-and-learning.md +0 -55
  248. package/examples/sub-agents/agents/agy-main.md +0 -23
  249. package/examples/sub-agents/agents/claude-high.md +0 -23
  250. package/examples/sub-agents/agents/claude-main.md +0 -23
  251. package/examples/sub-agents/agents/codex-flash.md +0 -23
  252. package/examples/sub-agents/agents/codex-high.md +0 -23
  253. package/examples/sub-agents/agents/codex-main.md +0 -23
  254. package/examples/sub-agents/agents/codex-review.md +0 -23
  255. package/examples/sub-agents/agents/cursor-high.md +0 -22
  256. package/examples/sub-agents/agents/cursor-main.md +0 -22
  257. package/examples/sub-agents/agents/glm-flash.md +0 -23
  258. package/examples/sub-agents/agents/glm-high.md +0 -23
@@ -1,6 +1,8 @@
1
1
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
2
2
  import { checkPathGuard } from "../security/path-guard-check.js";
3
+ import { assertPathWritableUnderLease } from "../subagents/workspace-lease.js";
3
4
  import { preserveTaskFields, withTaskFileMutation } from "../tasks/file-mutation.js";
5
+ import { observeCurrentFile } from "./file-observations.js";
4
6
  export async function writeContent(fileStore, path, content, signal, options) {
5
7
  const createParentDir = options?.createParentDir ?? false;
6
8
  const securityConfig = options?.securityConfig ?? DEFAULT_SECURITY_CONFIG;
@@ -12,15 +14,25 @@ export async function writeContent(fileStore, path, content, signal, options) {
12
14
  tool: options?.toolName ?? "write",
13
15
  channelId: options?.channelId,
14
16
  });
17
+ assertPathWritableUnderLease(target, {
18
+ deskDir: options?.deskDir,
19
+ excludeRunId: options?.leaseOwnerRunId,
20
+ });
15
21
  // Atomic write via a same-directory temp file + rename, with fsync (spec 044, D3): `writeAtomic`
16
22
  // preserves the existing file's permission bits across the rename, exactly as the old
17
23
  // `cp -p` + `cat > tmp && mv` shell script did, but content now goes straight to `node:fs`
18
24
  // instead of a stdin pipe into `sh -c` -- it never exists in memory twice, and there is no
19
25
  // shell script to escape or an EPIPE to swallow.
20
- await withTaskFileMutation(options?.deskDir, target, (document) => fileStore.writeAtomic(target, preserveTaskFields(document, content), {
21
- createParentDir,
22
- preserveMode: true,
23
- signal,
24
- }));
25
- return target;
26
+ return withTaskFileMutation(options?.deskDir, target, async (document) => {
27
+ const observations = options?.observations;
28
+ const before = observations ? await fileStore.stat(target).catch(() => undefined) : undefined;
29
+ const note = observations?.describeWriteNote(target, path, before);
30
+ await fileStore.writeAtomic(target, preserveTaskFields(document, content), {
31
+ createParentDir,
32
+ preserveMode: true,
33
+ signal,
34
+ });
35
+ await observeCurrentFile(observations, fileStore, target);
36
+ return { target, note };
37
+ });
26
38
  }
@@ -2,6 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { FileStore } from "../file-store.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
+ import type { FileObservations } from "./file-observations.js";
5
6
  declare const writeSchema: Type.TObject<{
6
7
  path: Type.TString;
7
8
  content: Type.TString;
@@ -11,6 +12,8 @@ export interface WriteToolOptions {
11
12
  securityConfig?: SecurityConfig;
12
13
  securityContext?: SecurityRuntimeContext;
13
14
  channelId?: string;
15
+ leaseOwnerRunId?: string;
16
+ observations?: FileObservations;
14
17
  }
15
18
  export declare function createWriteTool(fileStore: FileStore, options?: WriteToolOptions): AgentTool<typeof writeSchema>;
16
19
  export {};
@@ -14,17 +14,21 @@ export function createWriteTool(fileStore, options = {}) {
14
14
  description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
15
15
  parameters: writeSchema,
16
16
  execute: async (_toolCallId, { path, content }, signal) => {
17
- const target = await writeContent(fileStore, path, content, signal, {
17
+ const { target, note } = await writeContent(fileStore, path, content, signal, {
18
18
  deskDir: options.deskDir,
19
19
  createParentDir: true,
20
20
  securityConfig: options.securityConfig,
21
21
  securityContext: options.securityContext,
22
22
  channelId: options.channelId,
23
23
  toolName: "write",
24
+ leaseOwnerRunId: options.leaseOwnerRunId,
25
+ observations: options.observations,
24
26
  });
25
27
  const bytesWritten = Buffer.byteLength(content, "utf-8");
26
28
  return {
27
- content: [{ type: "text", text: `Successfully wrote ${bytesWritten} bytes to ${path}` }],
29
+ content: [
30
+ { type: "text", text: `Successfully wrote ${bytesWritten} bytes to ${path}${note ? `\n${note}` : ""}` },
31
+ ],
28
32
  details: { path: target },
29
33
  };
30
34
  },
package/dist/tui/cli.d.ts CHANGED
@@ -3,6 +3,7 @@ export type ParsedTui = {
3
3
  kind: "run";
4
4
  desk?: string;
5
5
  cwd?: string;
6
+ here: boolean;
6
7
  create: boolean;
7
8
  fresh: boolean;
8
9
  print: boolean;
@@ -26,5 +27,9 @@ export interface EmbeddedRuntimeHandle {
26
27
  export interface TuiHooks {
27
28
  /** Start the runtime in this process, or `undefined` when a daemon already holds the app home. */
28
29
  startEmbeddedRuntime(paths: BootstrapPaths, io: BootstrapIO): Promise<EmbeddedRuntimeHandle | undefined>;
30
+ /** Override TTY interactivity detection (for deterministic unit tests). */
31
+ interactive?: boolean;
32
+ confirmModelLogin?: () => Promise<boolean>;
33
+ performModelLogin?: () => Promise<void>;
29
34
  }
30
35
  export declare function runTui(argv: string[], hooks: TuiHooks, io?: BootstrapIO, paths?: BootstrapPaths): Promise<void>;
package/dist/tui/cli.js CHANGED
@@ -4,10 +4,12 @@
4
4
  * the daemon's socket, or — when no daemon is running — to a runtime it starts inside this
5
5
  * process (D26, `startEmbeddedRuntime`, supplied by the entry so `tui/` never imports `runtime/`).
6
6
  */
7
+ import { homedir } from "node:os";
7
8
  import { resolve } from "node:path";
8
- import { BootstrapExitError, DEFAULT_BOOTSTRAP_PATHS, readCliVersion, } from "../app/home.js";
9
+ import { ensureModelOnboarding } from "../app/auth-command.js";
10
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../app/home.js";
9
11
  import { PipiclawSettingsManager } from "../config/settings.js";
10
- import { DEFAULT_DESK, normalizeDeskName } from "../desk/paths.js";
12
+ import { getDeskDir } from "../desk/paths.js";
11
13
  import { resolveDeskCwdSync } from "../desk/registry.js";
12
14
  import * as log from "../log.js";
13
15
  import { errorMessage } from "../shared/text-utils.js";
@@ -20,6 +22,7 @@ import { TuiSession } from "./session.js";
20
22
  export function parseTuiArgs(args) {
21
23
  let desk;
22
24
  let cwd;
25
+ let here = false;
23
26
  let create = false;
24
27
  let fresh = false;
25
28
  let print = false;
@@ -31,7 +34,7 @@ export function parseTuiArgs(args) {
31
34
  if (arg === "--desk") {
32
35
  desk = args[index + 1];
33
36
  if (!desk || desk.startsWith("-"))
34
- return { kind: "error", message: "--desk needs a name; omit it to open default." };
37
+ return { kind: "error", message: "--desk 需要指定工位名称;省略时默认打开 default 工位。" };
35
38
  index += 1;
36
39
  }
37
40
  else if (arg.startsWith("--desk=")) {
@@ -40,12 +43,15 @@ export function parseTuiArgs(args) {
40
43
  else if (arg === "--cwd") {
41
44
  cwd = args[index + 1];
42
45
  if (!cwd || cwd.startsWith("-"))
43
- return { kind: "error", message: "--cwd needs a directory path." };
46
+ return { kind: "error", message: "--cwd 需要指定目录路径。" };
44
47
  index += 1;
45
48
  }
46
49
  else if (arg.startsWith("--cwd=")) {
47
50
  cwd = arg.slice("--cwd=".length);
48
51
  }
52
+ else if (arg === "--here") {
53
+ here = true;
54
+ }
49
55
  else if (arg === "--create") {
50
56
  create = true;
51
57
  }
@@ -70,16 +76,23 @@ export function parseTuiArgs(args) {
70
76
  else if (arg.startsWith("--")) {
71
77
  // An unknown long option is a typo, not part of the prompt — reject it
72
78
  // instead of silently sending `--pritn` to the model as prompt text.
73
- return { kind: "error", message: `Unknown option: ${arg}` };
79
+ return { kind: "error", message: `未知参数:${arg}` };
74
80
  }
75
81
  else {
76
82
  positional.push(arg);
77
83
  }
78
84
  }
85
+ if (here && (desk !== undefined || cwd !== undefined)) {
86
+ return {
87
+ kind: "error",
88
+ message: "--here 会自动打开或创建当前目录对应的工位,不能与 --desk 或 --cwd 同时指定。",
89
+ };
90
+ }
79
91
  return {
80
92
  kind: "run",
81
93
  desk,
82
94
  ...(cwd !== undefined ? { cwd } : {}),
95
+ here,
83
96
  create,
84
97
  fresh,
85
98
  print,
@@ -89,25 +102,24 @@ export function parseTuiArgs(args) {
89
102
  };
90
103
  }
91
104
  function printTuiHelp(io) {
92
- io.log("Usage: pipiclaw tui [options] [prompt]");
105
+ io.log("用法:pipiclaw tui [options] [prompt]");
93
106
  io.log("");
94
- io.log("Chat with the pipiclaw agent in the terminal, using the same config and the");
95
- io.log("same assistant as the DingTalk runtime.");
107
+ io.log("在终端中与 Pipiclaw 助手对话(与后台服务共享同一套配置、记忆、任务与文件)。");
96
108
  io.log("");
97
- io.log("The terminal is a client of the Web API's local socket. With a daemon running it");
98
- io.log("connects to it; otherwise it runs the runtime itself until you exit. It opens the");
99
- io.log("default desk and resumes this desk's last conversation, sharing the desk's memory,");
100
- io.log("tasks and files with the channels bound to it.");
109
+ io.log("终端通过本机 Web API socket 连接服务:若后台服务已在运行则直接连接;");
110
+ io.log("否则在当前终端进程内自动启动运行时,退出终端时一并关闭。");
111
+ io.log("默认打开 default 工位并续接该工位上次的终端会话。");
101
112
  io.log("");
102
- io.log("Options:");
103
- io.log(" --desk <name> Open a desk (default: default)");
104
- io.log(" --cwd <dir> Set the desk's working directory (repo path)");
105
- io.log(" --create Create the desk first (like `/desk new`)");
106
- io.log(" --new Start a new conversation instead of resuming");
107
- io.log(" --print, -p One-shot: run [prompt] (or stdin), print the answer, exit");
108
- io.log(" --plain Use the line-based frontend instead of the full-screen UI");
109
- io.log(" --quiet, -q Print only the final answer, no progress (implies --plain)");
110
- io.log(" --version Print the version and exit");
113
+ io.log("选项:");
114
+ io.log(" --here 打开或自动创建当前目录对应的专属工位(自动绑定工作目录)");
115
+ io.log(" --desk <名称> 打开指定工位(默认:default)");
116
+ io.log(" --cwd <目录> 设置该工位的工作目录(如 `--cwd .` 绑定当前仓库)");
117
+ io.log(" --create 先新建该工位(等价于 `/desk new`)");
118
+ io.log(" --new 开启全新会话而非续接上次会话");
119
+ io.log(" --print, -p 单次执行:运行 [prompt](或标准输入),输出结果后退出");
120
+ io.log(" --plain 使用行模式输出替代全屏终端界面");
121
+ io.log(" --quiet, -q 仅输出最终回复,不展示中间进度(自动启用 --plain)");
122
+ io.log(" --version 输出当前版本号并退出");
111
123
  }
112
124
  async function readStdin() {
113
125
  const chunks = [];
@@ -128,22 +140,52 @@ export async function runTui(argv, hooks, io = console, paths = DEFAULT_BOOTSTRA
128
140
  }
129
141
  if (parsed.kind === "error") {
130
142
  io.error(parsed.message);
131
- io.error(`Run \`pipiclaw tui --help\` for usage.`);
143
+ io.error("运行 `pipiclaw tui --help` 查看用法。");
132
144
  throw new BootstrapExitError(1);
133
145
  }
134
146
  let initialPrompt = parsed.positional.join(" ").trim() || undefined;
135
147
  if (parsed.print && !initialPrompt && process.stdin.isTTY !== true) {
136
148
  initialPrompt = (await readStdin()).trim() || undefined;
137
149
  }
150
+ const boot = bootstrapAppHome(paths);
151
+ printBootstrapSummary(boot, io, paths);
152
+ let readiness;
153
+ if (!parsed.print) {
154
+ const interactive = hooks.interactive ?? (io === console && process.stdin.isTTY === true && process.stderr.isTTY === true);
155
+ readiness = await ensureModelOnboarding({
156
+ paths,
157
+ io,
158
+ interactive,
159
+ confirmLogin: hooks.confirmModelLogin,
160
+ performLogin: hooks.performModelLogin,
161
+ });
162
+ }
138
163
  // The pi-tui frontend owns stdout; the plain frontend prints only the final answer. Either way
139
164
  // the console log sink would corrupt the output, so logging goes to its file sink only.
140
165
  log.setConsoleLoggingEnabled(false);
141
166
  const embedded = await hooks.startEmbeddedRuntime(paths, io);
167
+ let stoppingEmbedded = false;
168
+ const stopEmbedded = async () => {
169
+ if (!embedded || stoppingEmbedded)
170
+ return;
171
+ stoppingEmbedded = true;
172
+ process.stderr.write("正在关闭运行时…\n");
173
+ await embedded.stop();
174
+ };
175
+ const onSignal = () => {
176
+ void stopEmbedded().finally(() => {
177
+ process.exitCode = 0;
178
+ });
179
+ };
180
+ if (embedded) {
181
+ process.once("SIGTERM", onSignal);
182
+ process.once("SIGHUP", onSignal);
183
+ }
142
184
  try {
143
185
  if (!embedded)
144
186
  requireSocket(paths, io);
145
187
  try {
146
- await runClient(parsed, initialPrompt, paths, io);
188
+ await runClient(parsed, initialPrompt, paths, io, boot.initialWebApiKey, readiness);
147
189
  }
148
190
  catch (error) {
149
191
  if (error instanceof BootstrapExitError)
@@ -155,15 +197,22 @@ export async function runTui(argv, hooks, io = console, paths = DEFAULT_BOOTSTRA
155
197
  }
156
198
  finally {
157
199
  if (embedded) {
158
- process.stderr.write("正在关闭运行时…\n");
159
- await embedded.stop();
200
+ process.off("SIGTERM", onSignal);
201
+ process.off("SIGHUP", onSignal);
202
+ await stopEmbedded();
160
203
  }
161
204
  }
162
205
  }
163
- async function runClient(parsed, initialPrompt, paths, io) {
206
+ async function runClient(parsed, initialPrompt, paths, io, initialWebApiKey, readiness) {
164
207
  const client = createSocketClient(paths);
165
208
  const resolvedCwdArg = parsed.cwd ? resolve(parsed.cwd) : undefined;
166
- const { id, replies } = await openConversation(client, paths, { desk: parsed.desk, cwd: resolvedCwdArg, create: parsed.create, fresh: parsed.fresh }, io);
209
+ const { id, desk: deskName, replies, } = await openConversation(client, paths, {
210
+ desk: parsed.desk,
211
+ cwd: resolvedCwdArg,
212
+ here: parsed.here,
213
+ create: parsed.create,
214
+ fresh: parsed.fresh,
215
+ }, io);
167
216
  if (parsed.print) {
168
217
  const frontend = createFrontend({ plain: true, quiet: parsed.quiet, interactive: false });
169
218
  for (const reply of replies)
@@ -173,21 +222,38 @@ async function runClient(parsed, initialPrompt, paths, io) {
173
222
  frontend.stop();
174
223
  return;
175
224
  }
176
- const deskName = normalizeDeskName(parsed.desk ?? DEFAULT_DESK);
225
+ const deskCwd = resolveDeskCwdSync(paths.workspaceDir, deskName);
226
+ const defaultDeskDir = getDeskDir(paths.workspaceDir, deskName);
227
+ const notices = [...replies];
228
+ if (initialWebApiKey) {
229
+ notices.unshift(`🔑 已自动生成本机 Web API 默认密钥(仅展示一次,请保存):\`${initialWebApiKey}\`(接口:http://127.0.0.1:8787/v1)`);
230
+ }
231
+ if (readiness && !readiness.ready) {
232
+ notices.push("⚠️ 当前尚未配置可用模型凭据;可退出后执行 `pipiclaw auth login`,或配置环境变量 / `models.json` 后发送 `/reload`。");
233
+ }
234
+ const launchCwd = process.cwd();
235
+ if (!parsed.cwd &&
236
+ !parsed.here &&
237
+ deskCwd === defaultDeskDir &&
238
+ launchCwd !== deskCwd &&
239
+ launchCwd !== homedir() &&
240
+ !launchCwd.startsWith(paths.appHomeDir)) {
241
+ notices.push(`💡 当前工位工作目录为默认目录;如需操作当前终端所在目录,可发送 \`/desk cwd ${launchCwd}\`(或下次用 \`pipiclaw tui --here\` 打开当前目录专属工位)。`);
242
+ }
177
243
  const frontend = createFrontend({
178
244
  plain: parsed.plain,
179
245
  quiet: parsed.quiet,
180
246
  interactive: true,
181
247
  commands: TUI_SLASH_COMMANDS,
182
- basePath: resolveDeskCwdSync(paths.workspaceDir, deskName),
248
+ basePath: deskCwd,
183
249
  });
184
250
  const traits = traitsOf(new PipiclawSettingsManager(paths.appHomeDir).getTuiSettings().responseMode);
185
251
  const session = new TuiSession({
186
252
  link: createLink(client, paths, id),
187
253
  frontend,
188
254
  traits,
189
- label: `终端 · ${parsed.desk ?? "default"}`,
190
- notices: replies,
255
+ label: `终端 · 工位 ${deskName} · 目录 ${deskCwd}`,
256
+ notices,
191
257
  });
192
258
  await session.startInteractive(initialPrompt);
193
259
  }
@@ -6,6 +6,10 @@ export interface OpenOptions {
6
6
  desk?: string;
7
7
  /** Optional repository / working directory to configure on the desk (`--cwd`). */
8
8
  cwd?: string;
9
+ /** Automatically open or create a desk dedicated to `hereDir ?? process.cwd()` (`--here`). */
10
+ here?: boolean;
11
+ /** Override `process.cwd()` for `--here` in deterministic tests. */
12
+ hereDir?: string;
9
13
  /** Create the desk first — an explicit creation, like `/desk new`. */
10
14
  create: boolean;
11
15
  /** Start a new conversation instead of resuming the desk's last one. */
@@ -22,6 +26,7 @@ export declare function createLink(client: OpenAI, paths: BootstrapPaths, conver
22
26
  */
23
27
  export declare function openConversation(client: OpenAI, paths: BootstrapPaths, options: OpenOptions, io: BootstrapIO): Promise<{
24
28
  id: string;
29
+ desk: string;
25
30
  replies: string[];
26
31
  }>;
27
32
  /** `--print`: one synchronous request, the answer on stdout. */
@@ -6,13 +6,14 @@
6
6
  */
7
7
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
8
8
  import { connect } from "node:net";
9
- import { dirname, join } from "node:path";
9
+ import { dirname, join, resolve } from "node:path";
10
10
  import OpenAI from "openai";
11
11
  import { ResponsesWS } from "openai/resources/responses/ws";
12
12
  import { Agent, fetch as undiciFetch } from "undici";
13
13
  import { BootstrapExitError } from "../app/home.js";
14
14
  import { loadBindings } from "../desk/bindings.js";
15
- import { DEFAULT_DESK, isDeskName, normalizeDeskName } from "../desk/paths.js";
15
+ import { DEFAULT_DESK, deriveDeskNameFromPath, isDeskName, normalizeDeskName } from "../desk/paths.js";
16
+ import { listDesks, readDeskRecordSync } from "../desk/registry.js";
16
17
  import { webapiSocketPath } from "../paths.js";
17
18
  import { writeFileAtomically } from "../shared/atomic-file.js";
18
19
  import { isPlainObject } from "../shared/type-guards.js";
@@ -51,11 +52,22 @@ export function requireSocket(paths, io) {
51
52
  const socketPath = webapiSocketPath(paths.appHomeDir);
52
53
  if (existsSync(socketPath))
53
54
  return;
55
+ let lockDetail = "";
56
+ try {
57
+ const raw = JSON.parse(readFileSync(join(paths.appHomeDir, "state", "daemon.lock"), "utf-8"));
58
+ if (isPlainObject(raw) && typeof raw.pid === "number") {
59
+ const started = typeof raw.startedAt === "string" ? `,启动于 ${raw.startedAt}` : "";
60
+ lockDetail = `(进程 PID ${raw.pid}${started})`;
61
+ }
62
+ }
63
+ catch {
64
+ // Lock file unreadable or absent; omit holder details.
65
+ }
54
66
  io.error([
55
- `Cannot reach the Web API socket (${socketPath}).`,
56
- "A Pipiclaw daemon is running, but it has no Web API socket. Either:",
57
- ' - set `"webapi": { "enabled": true, "socket": true }` in channel.json and restart the daemon, or',
58
- " - stop the daemon, and `pipiclaw tui` will run the runtime itself.",
67
+ `无法连接本机 Web API socket(${socketPath})。`,
68
+ `检测到后台已有 Pipiclaw 服务正在运行${lockDetail},但未开启本机 socket。你可以:`,
69
+ ` 1) 在 ${paths.channelConfigPath} 中设置 \`"webapi": { "enabled": true, "socket": true }\` 并重启后台服务;或`,
70
+ " 2) 先停止后台服务,再直接运行 `pipiclaw tui`(由终端内嵌启动运行时)。",
59
71
  ].join("\n"));
60
72
  throw new BootstrapExitError(1);
61
73
  }
@@ -112,6 +124,30 @@ async function ask(client, conversationId, input) {
112
124
  }
113
125
  return response.output_text;
114
126
  }
127
+ async function resolveHereTarget(paths, targetCwd, fail) {
128
+ const desks = await listDesks(paths.workspaceDir);
129
+ const matchedByCwd = desks.find((entry) => entry.availability === "available" && (entry.record?.cwd ?? entry.deskDir) === targetCwd);
130
+ if (matchedByCwd) {
131
+ return { desk: matchedByCwd.name, create: false };
132
+ }
133
+ const slug = deriveDeskNameFromPath(targetCwd);
134
+ const summary = readDeskRecordSync(paths.workspaceDir, slug);
135
+ if (summary.availability === "missing") {
136
+ const { bindings } = await loadBindings(paths.workspaceDir);
137
+ if (Object.values(bindings).some((binding) => binding.desk === slug)) {
138
+ fail(`工位 "${slug}" 已有绑定但记录缺失,请联系部署者恢复,或改用 \`--desk <新名称> --create --cwd .\`。`);
139
+ }
140
+ return { desk: slug, cwd: targetCwd, create: true };
141
+ }
142
+ if (!summary.record) {
143
+ fail(`工位 "${slug}" 当前不可用(desk.json 有误),请检查后再试,或改用 \`--desk <新名称> --create --cwd .\`。`);
144
+ }
145
+ const existingCwd = summary.record.cwd ?? summary.deskDir;
146
+ if (existingCwd !== targetCwd) {
147
+ fail(`同名工位 "${slug}" 已存在且绑定到其他目录(${existingCwd})。请改用 \`pipiclaw tui --desk <新名称> --create --cwd .\` 指定不重名的工位。`);
148
+ }
149
+ return { desk: slug, create: false };
150
+ }
115
151
  /**
116
152
  * Find or make the conversation for `--desk`: resume the desk's last one while it is still bound
117
153
  * to that desk, else start one and bind it (`/desk new` first with `--create`). Returns the
@@ -122,43 +158,49 @@ export async function openConversation(client, paths, options, io) {
122
158
  io.error(message);
123
159
  throw new BootstrapExitError(1);
124
160
  };
125
- const desk = normalizeDeskName(options.desk ?? DEFAULT_DESK);
161
+ const resolvedHere = options.here
162
+ ? await resolveHereTarget(paths, resolve(options.hereDir ?? process.cwd()), fail)
163
+ : undefined;
164
+ const desk = resolvedHere ? resolvedHere.desk : normalizeDeskName(options.desk ?? DEFAULT_DESK);
165
+ const create = resolvedHere ? resolvedHere.create : options.create;
166
+ const cwd = resolvedHere ? resolvedHere.cwd : options.cwd;
126
167
  if (!isDeskName(desk)) {
127
- fail(`Invalid desk name "${desk}": use 1-32 lowercase letters, digits or hyphens, not starting or ending with "-".`);
168
+ fail(`工位名称 "${desk}" 不合法:请使用 1–32 位小写字母、数字或连字符 '-',且首尾不能为 '-'。`);
128
169
  }
129
170
  const state = readState(paths);
130
- if (!options.fresh && !options.create && state[desk]) {
171
+ if (!options.fresh && !create && state[desk]) {
131
172
  const id = state[desk];
132
173
  const exists = await client.conversations.retrieve(id).then(() => true, (error) => (error.status === 404 ? false : Promise.reject(error)));
133
174
  // A conversation rebound to another desk since is not this desk's any more.
134
175
  const bound = exists ? await boundDesk(paths, id) : undefined;
135
- if (exists && (bound === desk || (bound === undefined && desk === DEFAULT_DESK))) {
136
- const replies = options.cwd ? [await ask(client, id, `/desk cwd ${options.cwd}`)] : [];
137
- return { id, replies };
176
+ const isArchived = Boolean(readDeskRecordSync(paths.workspaceDir, desk).record?.archivedAt);
177
+ if (!isArchived && exists && (bound === desk || (bound === undefined && desk === DEFAULT_DESK))) {
178
+ const replies = cwd ? [await ask(client, id, `/desk cwd ${cwd}`)] : [];
179
+ return { id, desk, replies };
138
180
  }
139
181
  }
140
182
  const id = (await client.conversations.create({})).id;
141
183
  const replies = [];
142
184
  // A conversation starts on the default desk by itself; any other desk is an explicit request.
143
- if (desk !== DEFAULT_DESK || options.create) {
144
- if (options.create) {
145
- replies.push(await ask(client, id, options.cwd ? `/desk new ${desk} ${options.cwd}` : `/desk new ${desk}`));
185
+ if (desk !== DEFAULT_DESK || create) {
186
+ if (create) {
187
+ replies.push(await ask(client, id, cwd ? `/desk new ${desk} ${cwd}` : `/desk new ${desk}`));
146
188
  }
147
189
  replies.push(await ask(client, id, `/desk bind ${desk}`));
148
190
  if ((await boundDesk(paths, id)) !== desk) {
149
191
  for (const reply of replies)
150
192
  io.error(reply);
151
- fail(`Could not open desk "${desk}".`);
193
+ fail(`无法打开工位 "${desk}"。`);
152
194
  }
153
- if (options.cwd && !options.create) {
154
- replies.push(await ask(client, id, `/desk cwd ${options.cwd}`));
195
+ if (cwd && !create) {
196
+ replies.push(await ask(client, id, `/desk cwd ${cwd}`));
155
197
  }
156
198
  }
157
- else if (options.cwd) {
158
- replies.push(await ask(client, id, `/desk cwd ${options.cwd}`));
199
+ else if (cwd) {
200
+ replies.push(await ask(client, id, `/desk cwd ${cwd}`));
159
201
  }
160
202
  await writeState(paths, { ...state, [desk]: id });
161
- return { id, replies };
203
+ return { id, desk, replies };
162
204
  }
163
205
  /** `--print`: one synchronous request, the answer on stdout. */
164
206
  export async function printOnce(client, conversationId, prompt) {
@@ -13,6 +13,8 @@
13
13
  export interface TranscriptRenderer {
14
14
  /** A streamed progress line (tool call, thinking, assistant increment, error). */
15
15
  appendProgress(text: string): void;
16
+ /** Incremental assistant text delta for live preview before the message completes. */
17
+ streamText?(delta: string): void;
16
18
  /** The final answer for a turn, rendered prominently (Markdown where supported). */
17
19
  showFinal(markdown: string): void;
18
20
  /** A side notice (skill change, model fallback), rendered subtly. */
@@ -26,6 +26,8 @@ export declare class PiTuiFrontend implements Frontend {
26
26
  private readonly loader;
27
27
  private readonly editorContainer;
28
28
  private turnProgress;
29
+ private streamPreview;
30
+ private streamBuffer;
29
31
  private removeInputListener;
30
32
  private spinnerShown;
31
33
  constructor(options?: PiTuiFrontendOptions);
@@ -34,9 +36,11 @@ export declare class PiTuiFrontend implements Frontend {
34
36
  /** Echo the user's submitted message into the transcript. */
35
37
  showUser(text: string): void;
36
38
  appendProgress(text: string): void;
39
+ streamText(delta: string): void;
37
40
  showFinal(markdown: string): void;
38
41
  showNotice(text: string): void;
39
42
  clearProgress(): void;
43
+ private clearStreamPreview;
40
44
  setWorking(on: boolean): void;
41
45
  setStatus(text: string): void;
42
46
  setBusy(busy: boolean): void;
@@ -44,6 +44,7 @@ export class PiTuiFrontend {
44
44
  this.spinnerContainer = new Container();
45
45
  this.editorContainer = new Container();
46
46
  this.turnProgress = [];
47
+ this.streamBuffer = "";
47
48
  this.spinnerShown = false;
48
49
  this.ui = new TuiMainScreen(new ProcessTerminal(), true);
49
50
  this.editor = new Editor(this.ui, EDITOR_THEME, { paddingX: 1 });
@@ -93,12 +94,27 @@ export class PiTuiFrontend {
93
94
  this.ui.requestRender();
94
95
  }
95
96
  appendProgress(text) {
97
+ this.clearStreamPreview();
96
98
  const line = new Text(dim(text), 1, 0);
97
99
  this.transcript.addChild(line);
98
100
  this.turnProgress.push(line);
99
101
  this.ui.requestRender();
100
102
  }
103
+ streamText(delta) {
104
+ if (!delta)
105
+ return;
106
+ this.streamBuffer += delta;
107
+ if (!this.streamPreview) {
108
+ this.streamPreview = new Markdown(this.streamBuffer, 1, 1, MARKDOWN_THEME, undefined, { renderLatex: false });
109
+ this.transcript.addChild(this.streamPreview);
110
+ }
111
+ else {
112
+ this.streamPreview.setText(this.streamBuffer);
113
+ }
114
+ this.ui.requestRender();
115
+ }
101
116
  showFinal(markdown) {
117
+ this.clearStreamPreview();
102
118
  this.transcript.addChild(new Markdown(markdown, 1, 1, MARKDOWN_THEME, undefined, { renderLatex: false }));
103
119
  // The turn's progress becomes permanent scrollback; stop tracking it so a
104
120
  // later clearProgress cannot retract it.
@@ -106,16 +122,25 @@ export class PiTuiFrontend {
106
122
  this.ui.requestRender();
107
123
  }
108
124
  showNotice(text) {
125
+ this.clearStreamPreview();
109
126
  this.transcript.addChild(new Text(gray(text), 1, 0));
110
127
  this.ui.requestRender();
111
128
  }
112
129
  clearProgress() {
130
+ this.clearStreamPreview();
113
131
  for (const component of this.turnProgress) {
114
132
  this.transcript.removeChild(component);
115
133
  }
116
134
  this.turnProgress = [];
117
135
  this.ui.requestRender();
118
136
  }
137
+ clearStreamPreview() {
138
+ if (this.streamPreview) {
139
+ this.transcript.removeChild(this.streamPreview);
140
+ this.streamPreview = undefined;
141
+ }
142
+ this.streamBuffer = "";
143
+ }
119
144
  setWorking(on) {
120
145
  this.showSpinner(on);
121
146
  }
@@ -124,6 +149,8 @@ export class PiTuiFrontend {
124
149
  this.ui.requestRender();
125
150
  }
126
151
  setBusy(busy) {
152
+ if (!busy)
153
+ this.clearStreamPreview();
127
154
  this.showSpinner(busy);
128
155
  }
129
156
  showSpinner(on) {
@@ -14,6 +14,7 @@ export declare function traitsOf(mode: TuiResponseMode): DeliveryTraits;
14
14
  /** The parts of a Response event the terminal reads (the SDK's union is much wider). */
15
15
  export interface StreamEvent {
16
16
  type: string;
17
+ delta?: string;
17
18
  item?: {
18
19
  id?: string;
19
20
  type?: string;
@@ -48,6 +48,11 @@ export class EventRenderer {
48
48
  this.progress("tool", describeToolCall(event.item.name ?? "", parseArguments(event.item.arguments)));
49
49
  }
50
50
  return;
51
+ case "response.output_text.delta":
52
+ if (this.traits.finalDelivery === "plain" && !this.answered && event.delta) {
53
+ this.out.streamText?.(event.delta);
54
+ }
55
+ return;
51
56
  case "response.output_item.done":
52
57
  this.itemDone(event.item);
53
58
  return;
@@ -152,10 +152,12 @@ export class TuiSession {
152
152
  }
153
153
  stop() {
154
154
  const connection = this.connection;
155
+ const target = this.lastSteerTarget;
155
156
  this.connection = undefined;
156
157
  this.connectionId++;
157
158
  this.resetCounters();
158
159
  this.followups.length = 0;
160
+ connection?.send({ type: "response.cancel", ...(target ? { response_id: target } : {}) });
159
161
  connection?.close();
160
162
  this.options.frontend.showNotice("已停止。");
161
163
  this.afterStateChange();
@@ -168,6 +170,10 @@ export class TuiSession {
168
170
  }
169
171
  // ---- events ----------------------------------------------------------------------------
170
172
  onEvent(event) {
173
+ const errorCode = event.error?.code;
174
+ if (event.type === "error" && errorCode === "websocket_connection_limit_reached" && !this.busy) {
175
+ return;
176
+ }
171
177
  this.renderer.handle(event);
172
178
  if (event.type === "response.output_item.done" && event.item?.id)
173
179
  this.shown.add(event.item.id);