@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
@@ -32,6 +32,7 @@ export interface WebHttpRequestOptions {
32
32
  export declare class WebHttpClient {
33
33
  private readonly context;
34
34
  constructor(context: WebRuntimeContext);
35
+ validateTarget(url: string): Promise<void>;
35
36
  request(options: WebHttpRequestOptions): Promise<WebHttpResponse>;
36
37
  requestJson<T>(options: WebHttpRequestOptions): Promise<{
37
38
  response: WebHttpResponse;
@@ -112,6 +112,17 @@ export class WebHttpClient {
112
112
  constructor(context) {
113
113
  this.context = context;
114
114
  }
115
+ async validateTarget(url) {
116
+ try {
117
+ await validateNetworkTarget(url, { config: this.context.securityConfig });
118
+ }
119
+ catch (error) {
120
+ if (error instanceof NetworkGuardError) {
121
+ await logBlockedRequest(this.context, error);
122
+ }
123
+ throw error;
124
+ }
125
+ }
115
126
  async request(options) {
116
127
  const maxRedirects = options.maxRedirects ?? this.context.securityConfig.networkGuard.maxRedirects;
117
128
  let currentUrl = buildUrlWithParams(options.url, options.params);
package/dist/web/fetch.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { NetworkGuardError } from "../security/network.js";
1
2
  import { RecoverableToolError } from "../shared/recoverable-error.js";
2
3
  import { createWebHttpClient } from "./client.js";
3
4
  import { extractReadableContent } from "./extract.js";
@@ -55,6 +56,7 @@ async function tryFetchViaJina(context, url, maxChars, maxResponseBytes, signal)
55
56
  workspaceDir: context.workspaceDir,
56
57
  channelId: context.channelId,
57
58
  });
59
+ await client.validateTarget(url);
58
60
  const headers = { Accept: "application/json" };
59
61
  if (context.webConfig.search.apiKey && context.webConfig.search.provider === "jina") {
60
62
  headers.Authorization = `Bearer ${context.webConfig.search.apiKey}`;
@@ -171,9 +173,10 @@ export async function runWebFetch(context, request, signal) {
171
173
  return await fetchDirect(context, request.url, request.extractMode, request.maxChars, request.maxImageBytes, request.maxResponseBytes, signal);
172
174
  }
173
175
  catch (error) {
174
- // A binary payload is a definitive answer, not a transient direct-fetch failure — jina would
175
- // just return the same non-text content.
176
- if (error instanceof WebFetchBinaryError || !request.enableJinaFallback) {
176
+ // A binary payload or a network-guard refusal is a definitive answer, not a transient
177
+ // direct-fetch failure — falling back to Jina on a blocked target would leak internal URLs
178
+ // and bypass the SSRF guard.
179
+ if (error instanceof WebFetchBinaryError || error instanceof NetworkGuardError || !request.enableJinaFallback) {
177
180
  throw error;
178
181
  }
179
182
  const jinaResult = await tryFetchViaJina(context, request.url, request.maxChars, request.maxResponseBytes, signal);
@@ -7,7 +7,4 @@ export interface Principal {
7
7
  local: boolean;
8
8
  }
9
9
  export declare const LOCAL_PRINCIPAL: Principal;
10
- export declare const hashKey: (key: string) => string;
11
- /** A new key: `pk_` and 256 random bits. Shown once; only its hash is kept. */
12
- export declare function generateKey(): string;
13
10
  export declare function authenticate(authorization: string | undefined, keys: readonly WebApiKey[]): Principal | undefined;
@@ -3,13 +3,9 @@
3
3
  * a TCP request must carry a bearer key whose SHA-256 matches a configured one. The comparison
4
4
  * visits every stored hash, so how long it takes does not say which key was close.
5
5
  */
6
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
6
+ import { timingSafeEqual } from "node:crypto";
7
+ import { hashWebApiKey } from "../channel/config.js";
7
8
  export const LOCAL_PRINCIPAL = { name: "local", local: true };
8
- export const hashKey = (key) => createHash("sha256").update(key).digest("hex");
9
- /** A new key: `pk_` and 256 random bits. Shown once; only its hash is kept. */
10
- export function generateKey() {
11
- return `pk_${randomBytes(32).toString("base64url")}`;
12
- }
13
9
  function bearerToken(header) {
14
10
  const match = /^Bearer[ \t]+(\S+)$/i.exec(header ?? "");
15
11
  return match?.[1];
@@ -18,7 +14,7 @@ export function authenticate(authorization, keys) {
18
14
  const token = bearerToken(authorization);
19
15
  if (token === undefined)
20
16
  return undefined;
21
- const presented = Buffer.from(hashKey(token), "hex");
17
+ const presented = Buffer.from(hashWebApiKey(token), "hex");
22
18
  let match;
23
19
  for (const key of keys) {
24
20
  // Every stored hash is compared, whether or not an earlier one already matched.
@@ -39,55 +39,58 @@ export function parseWebApiConfig(section) {
39
39
  const raw = isPlainObject(section) ? section : {};
40
40
  const socket = raw.socket === undefined ? true : raw.socket;
41
41
  if (typeof socket !== "boolean")
42
- issues.push("webapi: `socket` must be true or false.");
42
+ issues.push("webapi: `socket` 必须是布尔值(true 或 false)。");
43
43
  let tcp;
44
- if (raw.tcp !== undefined) {
44
+ if (raw.tcp !== undefined && raw.tcp !== null && raw.tcp !== "") {
45
45
  tcp = typeof raw.tcp === "string" ? parseTcpAddress(raw.tcp) : undefined;
46
46
  if (!tcp)
47
- issues.push("webapi: `tcp` must be `host:port` (an IPv6 host in brackets, e.g. `[::1]:8787`).");
47
+ issues.push("webapi: `tcp` 格式必须是 `host:port`(如 `127.0.0.1:8787`,IPv6 需加方括号如 `[::1]:8787`),或设为 null 关闭 TCP 监听。");
48
48
  }
49
49
  let tls;
50
- if (raw.tls !== undefined) {
50
+ if (raw.tls !== undefined && raw.tls !== null) {
51
51
  const cert = isPlainObject(raw.tls) ? raw.tls.cert : undefined;
52
52
  const key = isPlainObject(raw.tls) ? raw.tls.key : undefined;
53
- if (typeof cert === "string" && typeof key === "string" && isAbsolute(cert) && isAbsolute(key)) {
53
+ if (cert === "" && key === "") {
54
+ tls = undefined;
55
+ }
56
+ else if (typeof cert === "string" && typeof key === "string" && isAbsolute(cert) && isAbsolute(key)) {
54
57
  tls = { cert, key };
55
58
  }
56
59
  else {
57
- issues.push("webapi: `tls` needs absolute `cert` and `key` paths.");
60
+ issues.push("webapi: `tls` 需要填写绝对路径的 `cert` 与 `key`(不启用 TLS 请设为 null)。");
58
61
  }
59
62
  }
60
63
  if (socket === false && !tcp && issues.length === 0) {
61
- issues.push("webapi: nothing to listen on — set `socket` to true, or give `tcp` an address.");
64
+ issues.push("webapi: 未开启任何监听地址——请将 `socket` 设为 true,或为 `tcp` 配置 `host:port`。");
62
65
  }
63
66
  const keys = [];
64
67
  if (raw.keys !== undefined && !Array.isArray(raw.keys)) {
65
- issues.push("webapi: `keys` must be an array.");
68
+ issues.push("webapi: `keys` 必须是数组。");
66
69
  }
67
70
  const seen = new Set();
68
71
  for (const [index, entry] of (Array.isArray(raw.keys) ? raw.keys : []).entries()) {
69
72
  const where = `webapi: keys[${index}]`;
70
73
  if (!isPlainObject(entry)) {
71
- issues.push(`${where} must be an object.`);
74
+ issues.push(`${where} 必须是 JSON 对象。`);
72
75
  continue;
73
76
  }
74
77
  const { name, sha256, desks } = entry;
75
78
  if (typeof name !== "string" || !KEY_NAME_PATTERN.test(name)) {
76
- issues.push(`${where}.name must match ${KEY_NAME_PATTERN}.`);
79
+ issues.push(`${where}.name 必须匹配 ${KEY_NAME_PATTERN}。`);
77
80
  }
78
81
  else if (name === RESERVED_KEY_NAME) {
79
- issues.push(`${where}.name \`${name}\` is reserved for the local socket.`);
82
+ issues.push(`${where}.name \`${name}\` 为本机 socket 保留名称,不可用于 TCP key。`);
80
83
  }
81
84
  else if (seen.has(name)) {
82
- issues.push(`${where}.name \`${name}\` is used twice.`);
85
+ issues.push(`${where}.name \`${name}\` 重复定义。`);
83
86
  }
84
87
  if (typeof sha256 !== "string" || !SHA256_HEX.test(sha256)) {
85
- issues.push(`${where}.sha256 must be 64 lower-case hex characters.`);
88
+ issues.push(`${where}.sha256 必须是 64 位小写十六进制字符(请使用 \`pipiclaw webapi key add\` 生成)。`);
86
89
  }
87
90
  if (!Array.isArray(desks) ||
88
91
  desks.length === 0 ||
89
92
  !desks.every((desk) => typeof desk === "string" && isDeskName(desk))) {
90
- issues.push(`${where}.desks must list at least one valid desk name.`);
93
+ issues.push(`${where}.desks 必须至少包含一个合法的工位名称(如 ["default"])。`);
91
94
  }
92
95
  if (typeof name === "string" && typeof sha256 === "string" && Array.isArray(desks)) {
93
96
  seen.add(name);
@@ -1,21 +1,20 @@
1
1
  /**
2
2
  * `pipiclaw webapi key add|list|remove` (spec 061, D3): the deployer's way to manage the keys in
3
- * `channel.json`. A key is generated here, printed once, and only its hash is written down. The
4
- * running daemon reads keys at start, so a change takes effect on its next restart.
3
+ * `channel.json`. A key is generated here, printed once, and only its hash is written down.
5
4
  */
6
5
  import { readFileSync } from "node:fs";
7
- import { BootstrapExitError, DEFAULT_BOOTSTRAP_PATHS } from "../app/home.js";
8
- import { isDeskName } from "../desk/paths.js";
6
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, } from "../app/home.js";
7
+ import { generateWebApiKey, hashWebApiKey } from "../channel/config.js";
8
+ import { DEFAULT_DESK, isDeskName } from "../desk/paths.js";
9
9
  import { writeFileAtomically } from "../shared/atomic-file.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
11
  import { isPlainObject } from "../shared/type-guards.js";
12
- import { generateKey, hashKey } from "./auth.js";
13
12
  import { KEY_NAME_PATTERN, RESERVED_KEY_NAME } from "./config.js";
14
13
  const USAGE = [
15
- "Usage:",
16
- " pipiclaw webapi key add <name> --desk <desk> [--desk <desk>…] Create a key (shown once)",
17
- " pipiclaw webapi key list List key names and their desks",
18
- " pipiclaw webapi key remove <name> Delete a key",
14
+ "用法:",
15
+ " pipiclaw webapi key add <名称> [--desk <工位>…] 创建访问密钥(明文仅展示一次;省略 --desk 时默认授权 default 工位)",
16
+ " pipiclaw webapi key list 查看已创建的密钥名称及授权工位",
17
+ " pipiclaw webapi key remove <名称> 删除指定密钥",
19
18
  ];
20
19
  function fail(io, message) {
21
20
  io.error(message);
@@ -26,15 +25,17 @@ function readConfig(paths, io) {
26
25
  const parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
27
26
  if (isPlainObject(parsed))
28
27
  return parsed;
29
- return fail(io, `${paths.channelConfigPath} is not a JSON object.`);
28
+ return fail(io, `${paths.channelConfigPath} 内容不是合法的 JSON 对象。`);
30
29
  }
31
30
  catch (error) {
32
- return fail(io, `Cannot read ${paths.channelConfigPath}: ${errorMessage(error)}`);
31
+ return fail(io, `无法读取 ${paths.channelConfigPath}:${errorMessage(error)}`);
33
32
  }
34
33
  }
35
34
  /** The `webapi.keys` array of `config`, created (with the section) when absent. */
36
35
  function keysOf(config) {
37
- const section = isPlainObject(config.webapi) ? config.webapi : { enabled: false, socket: true };
36
+ const section = isPlainObject(config.webapi)
37
+ ? config.webapi
38
+ : { enabled: true, socket: true, tcp: "127.0.0.1:8787" };
38
39
  config.webapi = section;
39
40
  const keys = Array.isArray(section.keys) ? section.keys : [];
40
41
  section.keys = keys;
@@ -48,63 +49,62 @@ function parseDesks(args, io) {
48
49
  const desks = [];
49
50
  for (let index = 0; index < args.length; index += 1) {
50
51
  if (args[index] !== "--desk")
51
- fail(io, `Unexpected argument: ${args[index]}\n${USAGE.join("\n")}`);
52
+ fail(io, `未知参数:${args[index]}\n${USAGE.join("\n")}`);
52
53
  const desk = args[++index];
53
54
  if (!desk || !isDeskName(desk))
54
- fail(io, `--desk needs a valid desk name (lower-case letters, digits, '-'), got: ${desk ?? "nothing"}`);
55
+ fail(io, `--desk 需要合法的工位名称(小写字母、数字、连字符 '-'),收到:${desk ?? "空"}`);
55
56
  if (!desks.includes(desk))
56
57
  desks.push(desk);
57
58
  }
58
- return desks;
59
+ return desks.length > 0 ? desks : [DEFAULT_DESK];
59
60
  }
60
61
  export async function runWebApiCommand(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
61
62
  const [group, action, name, ...rest] = argv.slice(3);
62
63
  if (argv[2] !== "webapi" || group !== "key")
63
64
  fail(io, USAGE.join("\n"));
65
+ if (action !== "list" && action !== "add" && action !== "remove") {
66
+ fail(io, USAGE.join("\n"));
67
+ }
68
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
64
69
  if (action === "list") {
65
70
  const keys = keysOf(readConfig(paths, io));
66
71
  if (keys.length === 0)
67
- io.log("No keys. Create one with `pipiclaw webapi key add <name> --desk <desk>`.");
72
+ io.log("当前未配置任何密钥。可执行 `pipiclaw webapi key add default` 创建。");
68
73
  for (const key of keys)
69
- io.log(`${key.name}\tdesks: ${key.desks.join(", ")}`);
74
+ io.log(`${key.name}\t工位: ${key.desks.join(", ")}`);
70
75
  return;
71
76
  }
72
77
  if (action === "add") {
73
78
  if (name === RESERVED_KEY_NAME) {
74
- fail(io, `The name '${RESERVED_KEY_NAME}' is reserved for the local socket.`);
79
+ fail(io, `名称 '${RESERVED_KEY_NAME}' 为本机 socket 保留标识,请换一个名称。`);
75
80
  }
76
81
  if (!name || !KEY_NAME_PATTERN.test(name)) {
77
- fail(io, `A key name is 1–32 characters of a-z, 0-9 and '-', starting with a letter or digit.\n${USAGE.join("\n")}`);
82
+ fail(io, `密钥名称需为 1–32 位的小写字母、数字或 '-',且以字母或数字开头。\n${USAGE.join("\n")}`);
78
83
  }
79
84
  const desks = parseDesks(rest, io);
80
- if (desks.length === 0)
81
- fail(io, `Give at least one desk the key may use: --desk <desk>.\n${USAGE.join("\n")}`);
82
85
  const config = readConfig(paths, io);
83
86
  const keys = keysOf(config);
84
- if (keys.some((key) => key.name === name))
85
- fail(io, `A key named "${name}" already exists; remove it first.`);
86
- const key = generateKey();
87
- keys.push({ name, sha256: hashKey(key), desks });
87
+ if (keys.some((key) => key.name === name)) {
88
+ fail(io, `名为 "${name}" 的密钥已存在;如需重置请先执行 \`pipiclaw webapi key remove ${name}\`。`);
89
+ }
90
+ const key = generateWebApiKey();
91
+ keys.push({ name, sha256: hashWebApiKey(key), desks });
88
92
  await save(paths, config);
89
- io.log(`Key for "${name}" (desks: ${desks.join(", ")}). It is shown once; store it now:`);
93
+ io.log(`✅ 已创建密钥 "${name}"(授权工位:${desks.join(", ")})。明文仅显示这一次,请立即保存:`);
90
94
  io.log("");
91
95
  io.log(` ${key}`);
92
96
  io.log("");
93
- io.log(`Restart the daemon to load it. A key is only used on the TCP listener (webapi.tcp), which is off by default.`);
97
+ io.log("已写入 channel.json,正在运行的服务会自动加载生效。");
94
98
  return;
95
99
  }
96
- if (action === "remove") {
97
- if (!name || rest.length > 0)
98
- fail(io, USAGE.join("\n"));
99
- const config = readConfig(paths, io);
100
- const keys = keysOf(config);
101
- const index = keys.findIndex((key) => key.name === name);
102
- if (index < 0)
103
- fail(io, `No key named "${name}".`);
104
- keys.splice(index, 1);
105
- await save(paths, config);
106
- io.log(`Removed key "${name}". Restart the daemon for it to stop working.`);
107
- return;
108
- }
109
- fail(io, USAGE.join("\n"));
100
+ if (!name || rest.length > 0)
101
+ fail(io, USAGE.join("\n"));
102
+ const config = readConfig(paths, io);
103
+ const keys = keysOf(config);
104
+ const index = keys.findIndex((key) => key.name === name);
105
+ if (index < 0)
106
+ fail(io, `未找到名为 "${name}" 的密钥。`);
107
+ keys.splice(index, 1);
108
+ await save(paths, config);
109
+ io.log(`已移除密钥 "${name}",正在运行的服务会自动生效。`);
110
110
  }
@@ -29,6 +29,8 @@ export declare class LiveResponse {
29
29
  private announced;
30
30
  private readonly subscribers;
31
31
  private readonly toolItems;
32
+ private streamingReasoning?;
33
+ private streamingMessage?;
32
34
  private readonly ended;
33
35
  private resolveEnded;
34
36
  private persisting;
@@ -64,8 +66,12 @@ export declare class LiveResponse {
64
66
  /** A tool call begins: an `mcp_call` item, in progress, with its arguments. */
65
67
  beginToolCall(callId: string, name: string, args: unknown): void;
66
68
  endToolCall(callId: string, ok: boolean, output: string, failure?: string): void;
69
+ /** Stream an incremental reasoning delta before the reasoning block finishes. */
70
+ appendReasoning(delta: string): void;
67
71
  /** The model's reasoning, as a reasoning item with a one-part summary. */
68
72
  addReasoning(text: string): void;
73
+ /** Stream an incremental assistant text delta before the message finishes. */
74
+ appendText(delta: string): void;
69
75
  /** A finished assistant message: commentary between tool calls, or the final answer. */
70
76
  addMessage(phase: "commentary" | "final_answer", text: string, level?: CommentaryLevel): void;
71
77
  /** Output items produced so far, for a caller that needs to know whether the turn said anything. */
@@ -84,7 +90,7 @@ export declare class LiveResponse {
84
90
  /** The response is over: store the final record and let waiters go. */
85
91
  private settle;
86
92
  private save;
87
- /** Tool calls still running when the response ends are closed as `incomplete`, with their `done` events. */
93
+ /** Tool calls or streaming items still running when the response ends are closed as `incomplete`. */
88
94
  private closeDanglingCalls;
89
95
  private markDanglingCallsIncomplete;
90
96
  }
@@ -166,9 +166,68 @@ export class LiveResponse {
166
166
  });
167
167
  this.emit({ type: "response.output_item.done", output_index: index, item: structuredClone(item) });
168
168
  }
169
+ /** Stream an incremental reasoning delta before the reasoning block finishes. */
170
+ appendReasoning(delta) {
171
+ if (this.terminal || !delta)
172
+ return;
173
+ if (!this.streamingReasoning) {
174
+ if (!delta.trim())
175
+ return;
176
+ const item = { id: newId("rs"), type: "reasoning", summary: [], status: "in_progress" };
177
+ const index = this.record.output.push(item) - 1;
178
+ this.streamingReasoning = { index, item, text: "" };
179
+ this.emit({ type: "response.output_item.added", output_index: index, item: structuredClone(item) });
180
+ this.emit({
181
+ type: "response.reasoning_summary_part.added",
182
+ output_index: index,
183
+ item_id: item.id,
184
+ summary_index: 0,
185
+ part: { type: "summary_text", text: "" },
186
+ });
187
+ }
188
+ const active = this.streamingReasoning;
189
+ active.text += delta;
190
+ this.emit({
191
+ type: "response.reasoning_summary_text.delta",
192
+ output_index: active.index,
193
+ item_id: active.item.id,
194
+ summary_index: 0,
195
+ delta,
196
+ });
197
+ }
169
198
  /** The model's reasoning, as a reasoning item with a one-part summary. */
170
199
  addReasoning(text) {
171
- if (this.terminal || !text.trim())
200
+ if (this.terminal)
201
+ return;
202
+ if (this.streamingReasoning) {
203
+ const active = this.streamingReasoning;
204
+ this.streamingReasoning = undefined;
205
+ const finalText = text.trim() ? text : active.text;
206
+ this.emit({
207
+ type: "response.reasoning_summary_text.done",
208
+ output_index: active.index,
209
+ item_id: active.item.id,
210
+ summary_index: 0,
211
+ text: finalText,
212
+ });
213
+ const part = { type: "summary_text", text: finalText };
214
+ this.emit({
215
+ type: "response.reasoning_summary_part.done",
216
+ output_index: active.index,
217
+ item_id: active.item.id,
218
+ summary_index: 0,
219
+ part,
220
+ });
221
+ active.item.summary = [part];
222
+ active.item.status = "completed";
223
+ this.emit({
224
+ type: "response.output_item.done",
225
+ output_index: active.index,
226
+ item: structuredClone(active.item),
227
+ });
228
+ return;
229
+ }
230
+ if (!text.trim())
172
231
  return;
173
232
  const item = { id: newId("rs"), type: "reasoning", summary: [], status: "in_progress" };
174
233
  const index = this.record.output.push(item) - 1;
@@ -206,9 +265,79 @@ export class LiveResponse {
206
265
  item.status = "completed";
207
266
  this.emit({ type: "response.output_item.done", output_index: index, item: structuredClone(item) });
208
267
  }
268
+ /** Stream an incremental assistant text delta before the message finishes. */
269
+ appendText(delta) {
270
+ if (this.terminal || !delta)
271
+ return;
272
+ if (!this.streamingMessage) {
273
+ if (!delta.trim())
274
+ return;
275
+ const id = newId("msg");
276
+ const item = {
277
+ id,
278
+ type: "message",
279
+ role: "assistant",
280
+ status: "in_progress",
281
+ phase: "final_answer",
282
+ content: [],
283
+ };
284
+ const index = this.record.output.push(item) - 1;
285
+ this.streamingMessage = { index, item, text: "" };
286
+ this.emit({ type: "response.output_item.added", output_index: index, item: structuredClone(item) });
287
+ this.emit({
288
+ type: "response.content_part.added",
289
+ output_index: index,
290
+ item_id: id,
291
+ content_index: 0,
292
+ part: { type: "output_text", text: "", annotations: [] },
293
+ });
294
+ }
295
+ const active = this.streamingMessage;
296
+ active.text += delta;
297
+ this.emit({
298
+ type: "response.output_text.delta",
299
+ output_index: active.index,
300
+ item_id: active.item.id,
301
+ content_index: 0,
302
+ delta,
303
+ logprobs: [],
304
+ });
305
+ }
209
306
  /** A finished assistant message: commentary between tool calls, or the final answer. */
210
307
  addMessage(phase, text, level) {
211
- if (this.terminal || !text.trim())
308
+ if (this.terminal)
309
+ return;
310
+ if (level === undefined && this.streamingMessage) {
311
+ const active = this.streamingMessage;
312
+ this.streamingMessage = undefined;
313
+ const finalText = text.trim() ? text : active.text;
314
+ active.item.phase = phase;
315
+ this.emit({
316
+ type: "response.output_text.done",
317
+ output_index: active.index,
318
+ item_id: active.item.id,
319
+ content_index: 0,
320
+ text: finalText,
321
+ logprobs: [],
322
+ });
323
+ const part = { type: "output_text", text: finalText, annotations: [] };
324
+ this.emit({
325
+ type: "response.content_part.done",
326
+ output_index: active.index,
327
+ item_id: active.item.id,
328
+ content_index: 0,
329
+ part,
330
+ });
331
+ active.item.content = [part];
332
+ active.item.status = "completed";
333
+ this.emit({
334
+ type: "response.output_item.done",
335
+ output_index: active.index,
336
+ item: structuredClone(active.item),
337
+ });
338
+ return;
339
+ }
340
+ if (!text.trim())
212
341
  return;
213
342
  const id = newId("msg");
214
343
  const empty = {
@@ -326,8 +455,30 @@ export class LiveResponse {
326
455
  });
327
456
  this.persisting = Promise.all([this.persisting, written]).then(() => undefined);
328
457
  }
329
- /** Tool calls still running when the response ends are closed as `incomplete`, with their `done` events. */
458
+ /** Tool calls or streaming items still running when the response ends are closed as `incomplete`. */
330
459
  closeDanglingCalls() {
460
+ if (this.streamingReasoning) {
461
+ const active = this.streamingReasoning;
462
+ this.streamingReasoning = undefined;
463
+ active.item.summary = [{ type: "summary_text", text: active.text }];
464
+ active.item.status = "incomplete";
465
+ this.emit({
466
+ type: "response.output_item.done",
467
+ output_index: active.index,
468
+ item: structuredClone(active.item),
469
+ });
470
+ }
471
+ if (this.streamingMessage) {
472
+ const active = this.streamingMessage;
473
+ this.streamingMessage = undefined;
474
+ active.item.content = [{ type: "output_text", text: active.text, annotations: [] }];
475
+ active.item.status = "incomplete";
476
+ this.emit({
477
+ type: "response.output_item.done",
478
+ output_index: active.index,
479
+ item: structuredClone(active.item),
480
+ });
481
+ }
331
482
  for (const [callId, index] of [...this.toolItems]) {
332
483
  this.toolItems.delete(callId);
333
484
  const item = this.record.output[index];
@@ -336,6 +487,18 @@ export class LiveResponse {
336
487
  }
337
488
  }
338
489
  markDanglingCallsIncomplete() {
490
+ if (this.streamingReasoning) {
491
+ this.streamingReasoning.item.summary = [{ type: "summary_text", text: this.streamingReasoning.text }];
492
+ this.streamingReasoning.item.status = "incomplete";
493
+ this.streamingReasoning = undefined;
494
+ }
495
+ if (this.streamingMessage) {
496
+ this.streamingMessage.item.content = [
497
+ { type: "output_text", text: this.streamingMessage.text, annotations: [] },
498
+ ];
499
+ this.streamingMessage.item.status = "incomplete";
500
+ this.streamingMessage = undefined;
501
+ }
339
502
  for (const [callId, index] of [...this.toolItems]) {
340
503
  this.toolItems.delete(callId);
341
504
  this.record.output[index].status = "incomplete";
@@ -94,8 +94,11 @@ class Connection {
94
94
  case "response.steer":
95
95
  await this.steer(event);
96
96
  return;
97
+ case "response.cancel":
98
+ await this.cancel(event);
99
+ return;
97
100
  default:
98
- throw badRequest("invalid_value", "Only `response.create` and `response.steer` events are accepted.", "type");
101
+ throw badRequest("invalid_value", "Only `response.create`, `response.steer`, and `response.cancel` events are accepted.", "type");
99
102
  }
100
103
  }
101
104
  catch (error) {
@@ -306,6 +309,26 @@ class Connection {
306
309
  // The response it follows has already been forwarded to its end: start a new forwarding.
307
310
  void this.follow(successor, this.laneOf.get(target.id));
308
311
  }
312
+ // ---- response.cancel -------------------------------------------------------------------
313
+ async cancel(event) {
314
+ const targetId = event.response_id;
315
+ if (targetId !== undefined) {
316
+ if (typeof targetId !== "string" || !targetId) {
317
+ throw badRequest("invalid_value", "`response_id` must be a non-empty string.", "response_id");
318
+ }
319
+ const target = this.responses.get(targetId);
320
+ if (!target) {
321
+ throw badRequest("response_not_found", "That response is not on this connection.", "response_id");
322
+ }
323
+ if (!target.terminal)
324
+ await this.service.cancel(target);
325
+ return;
326
+ }
327
+ for (const live of this.responses.values()) {
328
+ if (!live.terminal)
329
+ await this.service.cancel(live);
330
+ }
331
+ }
309
332
  }
310
333
  export function registerWebSocketRoute(app, context) {
311
334
  const { service, maxWebSocketMs } = context;
@@ -1,6 +1,6 @@
1
1
  import { type FastifyInstance } from "fastify";
2
2
  import type { SecurityLogEvent } from "../security/types.js";
3
- import type { WebApiConfig } from "./config.js";
3
+ import { type WebApiConfig } from "./config.js";
4
4
  import { type Listener } from "./http.js";
5
5
  import type { WebApiService } from "./service.js";
6
6
  export interface ServerDeps {
@@ -8,6 +8,8 @@ export interface ServerDeps {
8
8
  service: WebApiService;
9
9
  /** Where the local socket is created; its directory is made private. */
10
10
  socketPath: string;
11
+ /** When present, `webapi.keys` is reloaded whenever `channel.json`'s file stamp changes. */
12
+ channelConfigPath?: string;
11
13
  audit: (event: SecurityLogEvent) => void;
12
14
  maxWebSocketMs?: number;
13
15
  }