@oyasmi/pipiclaw 0.9.5-beta.4 → 0.9.6-beta.1

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 (185) hide show
  1. package/README.en.md +220 -126
  2. package/README.md +217 -123
  3. package/dist/agent/channel-runner.d.ts +1 -1
  4. package/dist/agent/channel-runner.js +1 -1
  5. package/dist/agent/prompt/sections.js +1 -1
  6. package/dist/agent/prompt/types.d.ts +2 -1
  7. package/dist/agent/session/compaction.d.ts +2 -0
  8. package/dist/agent/session/compaction.js +22 -14
  9. package/dist/agent/session/session-host.d.ts +1 -1
  10. package/dist/agent/session/session-host.js +3 -1
  11. package/dist/agent/stop-watchdog.js +5 -1
  12. package/dist/agent/turn/turn-state.d.ts +2 -0
  13. package/dist/agent/turn/turn-state.js +2 -1
  14. package/dist/agent/types.d.ts +3 -1
  15. package/dist/channel/attachments.d.ts +4 -0
  16. package/dist/channel/attachments.js +4 -0
  17. package/dist/channel/store.d.ts +1 -1
  18. package/dist/commands/catalog.js +25 -9
  19. package/dist/commands/router.js +5 -1
  20. package/dist/desk/commands.d.ts +14 -2
  21. package/dist/desk/commands.js +68 -20
  22. package/dist/desk/registry.d.ts +6 -2
  23. package/dist/desk/registry.js +70 -4
  24. package/dist/desk/types.d.ts +17 -0
  25. package/dist/dingtalk/bot.d.ts +1 -1
  26. package/dist/dingtalk/bot.js +4 -3
  27. package/dist/dingtalk/delivery.js +13 -8
  28. package/dist/dingtalk/inbound-media.d.ts +36 -14
  29. package/dist/dingtalk/inbound-media.js +71 -12
  30. package/dist/dingtalk/inbound.d.ts +9 -2
  31. package/dist/dingtalk/inbound.js +18 -2
  32. package/dist/dingtalk/media.d.ts +4 -10
  33. package/dist/dingtalk/media.js +58 -32
  34. package/dist/events/commands.d.ts +2 -0
  35. package/dist/events/commands.js +13 -8
  36. package/dist/events/history.d.ts +9 -0
  37. package/dist/events/history.js +66 -0
  38. package/dist/events/parse.js +7 -3
  39. package/dist/events/types.d.ts +3 -0
  40. package/dist/events/watcher.d.ts +3 -7
  41. package/dist/events/watcher.js +51 -56
  42. package/dist/jobs/kill.d.ts +23 -0
  43. package/dist/jobs/kill.js +65 -0
  44. package/dist/jobs/manager.d.ts +19 -18
  45. package/dist/jobs/manager.js +36 -103
  46. package/dist/memory/reflect.js +23 -3
  47. package/dist/memory/session-corpus.d.ts +1 -1
  48. package/dist/memory/session-corpus.js +70 -1
  49. package/dist/memory/session-search.js +13 -11
  50. package/dist/memory/store.d.ts +2 -0
  51. package/dist/memory/store.js +19 -9
  52. package/dist/playbooks/agent-delegation.md +34 -44
  53. package/dist/playbooks/memory-and-learning.md +4 -4
  54. package/dist/playbooks/runtime-orientation.md +1 -1
  55. package/dist/playbooks/task-lead.md +48 -64
  56. package/dist/runtime/bootstrap.d.ts +6 -0
  57. package/dist/runtime/bootstrap.js +11 -7
  58. package/dist/runtime/desk-runtime.d.ts +8 -2
  59. package/dist/runtime/desk-runtime.js +35 -4
  60. package/dist/runtime/durable-dispatch.d.ts +14 -2
  61. package/dist/runtime/durable-dispatch.js +207 -65
  62. package/dist/runtime/ingress-busy.js +17 -8
  63. package/dist/runtime/ingress-deps.d.ts +4 -1
  64. package/dist/runtime/ingress.js +6 -1
  65. package/dist/runtime/request-execution.js +7 -6
  66. package/dist/runtime/shutdown.d.ts +1 -0
  67. package/dist/runtime/shutdown.js +87 -35
  68. package/dist/runtime/task-control.d.ts +1 -0
  69. package/dist/runtime/task-control.js +25 -2
  70. package/dist/runtime/task-lane.d.ts +1 -0
  71. package/dist/runtime/task-lane.js +21 -6
  72. package/dist/runtime/task-spawn.d.ts +3 -2
  73. package/dist/runtime/task-spawn.js +3 -2
  74. package/dist/runtime/task-step.js +11 -2
  75. package/dist/runtime/turn-run.js +103 -66
  76. package/dist/security/command-guard.d.ts +1 -1
  77. package/dist/security/command-guard.js +237 -314
  78. package/dist/security/path-guard.js +48 -7
  79. package/dist/security/shell-parse.d.ts +10 -0
  80. package/dist/security/shell-parse.js +224 -0
  81. package/dist/security/types.d.ts +2 -0
  82. package/dist/subagents/commands.d.ts +1 -1
  83. package/dist/subagents/detached-discovery.d.ts +1 -1
  84. package/dist/subagents/discovery.d.ts +18 -199
  85. package/dist/subagents/discovery.js +35 -289
  86. package/dist/subagents/dispatch.d.ts +1 -2
  87. package/dist/subagents/dispatch.js +39 -20
  88. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  89. package/dist/subagents/external/antigravity-cli.js +517 -0
  90. package/dist/subagents/external/claude-code.js +8 -17
  91. package/dist/subagents/external/codex-cli.js +8 -18
  92. package/dist/subagents/external/cursor-cli.js +34 -31
  93. package/dist/subagents/external/dispatch.d.ts +21 -7
  94. package/dist/subagents/external/dispatch.js +139 -11
  95. package/dist/subagents/external/exec.js +3 -0
  96. package/dist/subagents/external/harness.d.ts +57 -33
  97. package/dist/subagents/external/harness.js +69 -40
  98. package/dist/subagents/external/reconciliation.js +1 -0
  99. package/dist/subagents/external/registry.js +4 -1
  100. package/dist/subagents/external/role-warnings.d.ts +4 -13
  101. package/dist/subagents/external/role-warnings.js +4 -28
  102. package/dist/subagents/external/run.d.ts +1 -2
  103. package/dist/subagents/external/run.js +11 -11
  104. package/dist/subagents/external/settlement.d.ts +2 -0
  105. package/dist/subagents/external/settlement.js +8 -2
  106. package/dist/subagents/format.d.ts +1 -1
  107. package/dist/subagents/format.js +1 -1
  108. package/dist/subagents/internal/outcome.d.ts +1 -2
  109. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  110. package/dist/subagents/internal/provider-retry.js +1 -1
  111. package/dist/subagents/internal/run.d.ts +1 -2
  112. package/dist/subagents/internal/state.d.ts +1 -2
  113. package/dist/subagents/internal/worker.d.ts +1 -2
  114. package/dist/subagents/internal/worker.js +3 -1
  115. package/dist/subagents/resolve.d.ts +56 -0
  116. package/dist/subagents/resolve.js +202 -0
  117. package/dist/subagents/result.d.ts +1 -2
  118. package/dist/subagents/result.js +7 -3
  119. package/dist/subagents/run-record.d.ts +33 -2
  120. package/dist/subagents/run-record.js +2 -0
  121. package/dist/subagents/runs.d.ts +2 -24
  122. package/dist/subagents/runs.js +6 -0
  123. package/dist/subagents/task-envelope.d.ts +1 -2
  124. package/dist/subagents/task-envelope.js +8 -4
  125. package/dist/subagents/types.d.ts +93 -4
  126. package/dist/subagents/types.js +16 -1
  127. package/dist/subagents/workspace-lease.d.ts +11 -21
  128. package/dist/subagents/workspace-lease.js +48 -21
  129. package/dist/subagents/worktree.d.ts +10 -0
  130. package/dist/subagents/worktree.js +77 -0
  131. package/dist/tasks/archive.js +4 -0
  132. package/dist/tasks/commands.d.ts +3 -0
  133. package/dist/tasks/commands.js +16 -2
  134. package/dist/tasks/control.d.ts +2 -0
  135. package/dist/tasks/delivery.d.ts +2 -0
  136. package/dist/tasks/delivery.js +141 -21
  137. package/dist/tasks/loop-log.d.ts +2 -0
  138. package/dist/tasks/loop-log.js +9 -0
  139. package/dist/tools/bash.js +2 -0
  140. package/dist/tools/contract/presentation.js +3 -4
  141. package/dist/tools/event-manage.d.ts +2 -0
  142. package/dist/tools/event-manage.js +20 -2
  143. package/dist/tools/index.d.ts +2 -1
  144. package/dist/tools/index.js +2 -0
  145. package/dist/tools/registry.js +3 -1
  146. package/dist/tools/send-media.js +9 -5
  147. package/dist/tools/session-search.js +1 -1
  148. package/dist/tools/subagent-manage.d.ts +1 -1
  149. package/dist/tools/subagent-manage.js +15 -149
  150. package/dist/tools/subagent.d.ts +2 -0
  151. package/dist/tools/subagent.js +6 -1
  152. package/dist/tools/task-manage/factory.js +2 -2
  153. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  154. package/dist/tools/task-manage/lifecycle.js +49 -9
  155. package/dist/tools/task-manage/schema.d.ts +4 -1
  156. package/dist/tools/task-manage/schema.js +4 -1
  157. package/dist/tools/task-manage/types.d.ts +4 -1
  158. package/dist/tui/cli.d.ts +1 -6
  159. package/dist/tui/cli.js +29 -3
  160. package/dist/tui/client.d.ts +2 -0
  161. package/dist/tui/client.js +13 -4
  162. package/dist/usage/ledger.d.ts +1 -1
  163. package/dist/usage/render.js +1 -1
  164. package/examples/sub-agents/README.md +39 -73
  165. package/examples/sub-agents/agents/agy-main.md +23 -0
  166. package/examples/sub-agents/agents/claude-high.md +9 -9
  167. package/examples/sub-agents/agents/claude-main.md +9 -9
  168. package/examples/sub-agents/agents/codex-flash.md +9 -9
  169. package/examples/sub-agents/agents/codex-high.md +9 -9
  170. package/examples/sub-agents/agents/codex-main.md +9 -9
  171. package/examples/sub-agents/agents/codex-review.md +9 -9
  172. package/examples/sub-agents/agents/cursor-high.md +9 -9
  173. package/examples/sub-agents/agents/cursor-main.md +9 -9
  174. package/examples/sub-agents/agents/glm-flash.md +9 -9
  175. package/examples/sub-agents/agents/glm-high.md +9 -9
  176. package/package.json +8 -8
  177. package/examples/sub-agents/agents/scout.md +0 -30
  178. package/examples/sub-agents/roles/builder-hard.md +0 -34
  179. package/examples/sub-agents/roles/builder.md +0 -34
  180. package/examples/sub-agents/roles/explorer.md +0 -39
  181. package/examples/sub-agents/roles/git-committer.md +0 -43
  182. package/examples/sub-agents/roles/planner.md +0 -33
  183. package/examples/sub-agents/roles/reviewer.md +0 -33
  184. package/examples/sub-agents/roles/verifier.md +0 -35
  185. package/examples/sub-agents/roles/worker.md +0 -34
@@ -17,8 +17,8 @@ import type { DeskJobManager } from "../../jobs/manager.js";
17
17
  import type { MemoryLifecycle } from "../../memory/lifecycle.js";
18
18
  import type { LoadedSecurityConfig } from "../../security/config.js";
19
19
  import type { PipiclawSkillsResult } from "../../skills/types.js";
20
- import { type SubAgentDiscoveryResult } from "../../subagents/discovery.js";
21
20
  import type { SubAgentRunManager } from "../../subagents/runs.js";
21
+ import type { SubAgentDiscoveryResult } from "../../subagents/types.js";
22
22
  import type { TaskControl } from "../../tasks/control.js";
23
23
  import type { UsageLedger } from "../../usage/ledger.js";
24
24
  import { type WorkspacePromptResources } from "../prompt/resources.js";
@@ -104,6 +104,7 @@ export class SessionHost {
104
104
  ledger: this.ledger,
105
105
  getRunState: () => this.runState,
106
106
  isEnabled: () => this.settingsManager.getCompactionEnabled(),
107
+ isTaskSession: deps.profile?.kind === "task",
107
108
  onPersistenceFault: (session, error) => this.markContextFault(session, error, "background-compaction"),
108
109
  onAdopt: () => {
109
110
  this.firstTurnMemoryBootstrapPending = true;
@@ -251,7 +252,7 @@ export class SessionHost {
251
252
  this.currentSkills = loadPipiclawSkills({
252
253
  workspaceDir: this.workspaceDir,
253
254
  securityConfig: this.loadSecurityConfig().config,
254
- securityContext: { agentWorkspaceDir: this.workspaceDir, cwd: this.cwd },
255
+ securityContext: { agentWorkspaceDir: this.workspaceDir, cwd: this.cwd, appHomeDir: this.appHomeDir },
255
256
  });
256
257
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
257
258
  if (this.retired)
@@ -528,6 +529,7 @@ export class SessionHost {
528
529
  getAvailableModels: () => this.modelRegistry.getAvailable(),
529
530
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
530
531
  workspaceDir: this.workspaceDir,
532
+ appHomeDir: this.appHomeDir,
531
533
  cwd: this.cwd,
532
534
  desk: this.conversation.desk,
533
535
  deskDir: this.deskDir,
@@ -19,7 +19,11 @@ export async function forceEndStuckTurnAfterStop(input) {
19
19
  const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
20
20
  const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
21
21
  const deadline = Date.now() + graceMs;
22
- const stopped = () => input.runner.isBusy() && input.runner.getTurnStatus().stopRequested && (input.isCurrent?.() ?? true);
22
+ const generation = input.runner.getTurnStatus().generation;
23
+ const stopped = () => input.runner.isBusy() &&
24
+ input.runner.getTurnStatus().generation === generation &&
25
+ input.runner.getTurnStatus().stopRequested &&
26
+ (input.isCurrent?.() ?? true);
23
27
  while (stopped() && Date.now() < deadline) {
24
28
  await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
25
29
  }
@@ -6,6 +6,7 @@ import type { TurnPhase, TurnStatus } from "../types.js";
6
6
  */
7
7
  export interface TurnHandle {
8
8
  phase: TurnPhase;
9
+ generation?: number;
9
10
  stopRequested: boolean;
10
11
  taskText?: string;
11
12
  }
@@ -31,6 +32,7 @@ export interface TurnHandle {
31
32
  export declare class TurnStateMachine {
32
33
  private readonly onWarn;
33
34
  private turn;
35
+ private generation;
34
36
  /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
35
37
  private abandoned;
36
38
  constructor(onWarn?: (message: string, detail?: string) => void);
@@ -24,6 +24,7 @@ export class TurnStateMachine {
24
24
  constructor(onWarn = () => { }) {
25
25
  this.onWarn = onWarn;
26
26
  this.turn = idleTurn();
27
+ this.generation = 0;
27
28
  /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
28
29
  this.abandoned = 0;
29
30
  }
@@ -32,7 +33,7 @@ export class TurnStateMachine {
32
33
  if (this.turn.phase !== "idle") {
33
34
  this.onWarn(`beginTurn while phase=${this.turn.phase}; turns must be serialized`);
34
35
  }
35
- this.turn = { phase: "dispatching", stopRequested: false, taskText };
36
+ this.turn = { phase: "dispatching", stopRequested: false, taskText, generation: ++this.generation };
36
37
  }
37
38
  /** Release the turn. Ignored when the turn was already released by `forceEnd`. */
38
39
  end() {
@@ -10,8 +10,8 @@ import type { FileStore } from "../file-store.js";
10
10
  import type { DeskJobManager } from "../jobs/manager.js";
11
11
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
12
12
  import type { LoadedSecurityConfig } from "../security/config.js";
13
- import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
14
13
  import type { SubAgentRunManager } from "../subagents/runs.js";
14
+ import type { SubAgentDiscoveryResult } from "../subagents/types.js";
15
15
  import type { TaskControl, TaskSessionContext } from "../tasks/control.js";
16
16
  import { type UsageTotals } from "../usage/totals.js";
17
17
  import type { TurnOutput } from "./turn/turn-output.js";
@@ -39,6 +39,8 @@ export interface RunnerStatusSnapshot {
39
39
  */
40
40
  export type TurnPhase = "idle" | "dispatching" | "preparing" | "streaming" | "finishing";
41
41
  export interface TurnStatus {
42
+ /** Monotonic identity within a runner; a watchdog never follows a later turn. */
43
+ generation?: number;
42
44
  phase: TurnPhase;
43
45
  stopRequested: boolean;
44
46
  /** The message text this turn is processing (set by beginTurn). */
@@ -14,6 +14,10 @@
14
14
  export declare const MAX_INBOUND_IMAGE_BYTES: number;
15
15
  /** Defensive hard cap on how many images one inbound message can carry. */
16
16
  export declare const MAX_INBOUND_IMAGES_PER_MESSAGE = 10;
17
+ /** Inbound file attachment cap (matches DingTalk's 20MB robot file limit). */
18
+ export declare const MAX_INBOUND_FILE_BYTES: number;
19
+ /** Defensive hard cap on how many non-image file attachments one inbound message can carry. */
20
+ export declare const MAX_INBOUND_FILES_PER_MESSAGE = 4;
17
21
  /**
18
22
  * Identify a downloaded file's real format from its magic bytes rather than trusting the
19
23
  * `Content-Type` DingTalk's CDN happens to answer with (spec 049 D8) — the four formats `read`
@@ -14,6 +14,10 @@
14
14
  export const MAX_INBOUND_IMAGE_BYTES = 10 * 1024 * 1024;
15
15
  /** Defensive hard cap on how many images one inbound message can carry. */
16
16
  export const MAX_INBOUND_IMAGES_PER_MESSAGE = 10;
17
+ /** Inbound file attachment cap (matches DingTalk's 20MB robot file limit). */
18
+ export const MAX_INBOUND_FILE_BYTES = 20 * 1024 * 1024;
19
+ /** Defensive hard cap on how many non-image file attachments one inbound message can carry. */
20
+ export const MAX_INBOUND_FILES_PER_MESSAGE = 4;
17
21
  /**
18
22
  * Identify a downloaded file's real format from its magic bytes rather than trusting the
19
23
  * `Content-Type` DingTalk's CDN happens to answer with (spec 049 D8) — the four formats `read`
@@ -41,7 +41,7 @@ export interface LoggedSubAgentRun {
41
41
  /** Spec 040, D7: the run this entry archives, and its lifecycle context. Only set on terminal archiving. */
42
42
  runId?: string;
43
43
  runtime?: "internal" | "external";
44
- harness?: "claude-code" | "codex-cli" | "cursor-cli" | "exec";
44
+ harness?: string;
45
45
  status?: "completed" | "failed" | "cancelled" | "lost";
46
46
  taskId?: string;
47
47
  artifactDir?: string;
@@ -50,19 +50,30 @@ export const BUILT_IN_COMMANDS = [
50
50
  },
51
51
  {
52
52
  name: "desk",
53
- argumentHint: "[list|new <名字>|bind <名字>]",
54
- description: "进阶:创建工位,或把本频道切换到另一个工位",
55
- // list/new answer mid-turn; bind refuses by itself while this channel is busy (spec 058, D5).
53
+ argumentHint: "[list|new <名字> [目录]|bind <名字>|cwd [目录|--reset]]",
54
+ description: "进阶:创建工位、配置工位仓库目录,或把本频道切换到另一个工位",
55
+ // list/new/cwd answer mid-turn; bind refuses by itself while this channel is busy (spec 058, D5).
56
56
  availableWhileBusy: true,
57
57
  subcommands: [
58
- { name: "list", description: "列出所有工位和各自绑定的频道(默认动作,可省略)", example: "/desk" },
59
- { name: "new", args: "<名字>", description: "创建一个空工位,不绑定任何频道", example: "/desk new research" },
58
+ { name: "list", description: "列出所有工位、工作目录和各自绑定的频道(默认动作,可省略)", example: "/desk" },
59
+ {
60
+ name: "new",
61
+ args: "<名字> [目录绝对路径]",
62
+ description: "创建一个空工位(可选指定代码仓库绝对路径),不绑定任何频道",
63
+ example: "/desk new research",
64
+ },
60
65
  {
61
66
  name: "bind",
62
67
  args: "<名字>",
63
68
  description: "把本频道绑定到这个工位,同时解除原来的绑定;回合进行中不能执行",
64
69
  example: "/desk bind research",
65
70
  },
71
+ {
72
+ name: "cwd",
73
+ args: "[目录绝对路径|--reset]",
74
+ description: "查看或设置当前工位的工作目录(状态仍保存在工位目录中)",
75
+ example: "/desk cwd /srv/repo",
76
+ },
66
77
  ],
67
78
  },
68
79
  {
@@ -89,8 +100,8 @@ export const BUILT_IN_COMMANDS = [
89
100
  },
90
101
  {
91
102
  name: "tasks",
92
- argumentHint: "[show <id>|log <id>|msg <id> <内容>|pause <id>|resume <id> [+steps N|+usd X]|cancel <id>|archive|doctor]",
93
- description: "查看、对话、暂停与取消本工位在后台执行的长程任务;任务与聊天互不占用",
103
+ argumentHint: "[show <id>|log <id>|msg <id> <内容>|adopt <id>|pause <id>|resume <id> [+steps N|+usd X]|cancel <id>|archive|doctor]",
104
+ description: "查看、对话、接管、暂停与取消本工位在后台执行的长程任务;任务与聊天互不占用",
94
105
  availableWhileBusy: true,
95
106
  subcommands: [
96
107
  { name: "list", description: "列出本工位进行中的任务(默认动作,可省略)", example: "/tasks" },
@@ -106,13 +117,18 @@ export const BUILT_IN_COMMANDS = [
106
117
  description: "查看该任务的记录(含每次委派的开始与结束)",
107
118
  example: "/tasks log weekly-report",
108
119
  },
109
- { name: "archive", description: "列出已归档(已关闭)的任务", example: "/tasks archive" },
110
120
  {
111
121
  name: "msg",
112
122
  args: "<id> <内容>",
113
123
  description: "对任务说话:步骤执行中直接送进当前步骤,否则排给下一步;也是回答任务提问的方式",
114
124
  example: "/tasks msg weekly-report 先跑一遍 npm run check",
115
125
  },
126
+ {
127
+ name: "adopt",
128
+ args: "<id>",
129
+ description: "把任务的汇报频道改到当前频道,解冻因原频道切走而暂停的任务",
130
+ example: "/tasks adopt weekly-report",
131
+ },
116
132
  {
117
133
  name: "pause",
118
134
  args: "<id>",
@@ -194,7 +210,7 @@ export const BUILT_IN_COMMANDS = [
194
210
  name: "roles",
195
211
  args: "[name]",
196
212
  description: "角色目录;带 name 时查看单个角色的详情",
197
- example: "/subagents roles builder-hard",
213
+ example: "/subagents roles codex-high",
198
214
  },
199
215
  ],
200
216
  },
@@ -1,6 +1,7 @@
1
1
  import { renderStatus } from "../agent/status-render.js";
2
2
  import { handleDeskCommand } from "../desk/commands.js";
3
3
  import { handleEventsCommand } from "../events/commands.js";
4
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
4
5
  import { handleSkillsCommand } from "../skills/commands.js";
5
6
  import { handleSubagentsCommand } from "../subagents/commands.js";
6
7
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
@@ -15,14 +16,17 @@ export async function runReportCommand(context, name, args) {
15
16
  const { conversation, paths } = context;
16
17
  const { channelId, desk, deskDir } = conversation;
17
18
  switch (name) {
18
- case "events":
19
+ case "events": {
20
+ const security = loadSecurityConfigWithDiagnostics(paths.appHomeDir).config;
19
21
  return handleEventsCommand({
20
22
  args,
21
23
  desk,
22
24
  deskDir,
23
25
  historyPath: paths.eventHistoryPath,
26
+ commandGuardConfig: security.enabled ? security.commandGuard : undefined,
24
27
  describeChannel: context.describeChannel,
25
28
  });
29
+ }
26
30
  case "tasks":
27
31
  return handleTasksCommand({
28
32
  args,
@@ -1,12 +1,17 @@
1
- import type { BindingsFile, CreateDeskOutcome, DeskAvailability, DeskSummary } from "./types.js";
1
+ import type { BindingsFile, CreateDeskOutcome, DeskAvailability, DeskCwdOutcome, DeskSummary } from "./types.js";
2
2
  type DeskCommand = {
3
3
  action: "list";
4
4
  } | {
5
5
  action: "new";
6
6
  name: string;
7
+ cwd?: string;
7
8
  } | {
8
9
  action: "bind";
9
10
  name: string;
11
+ } | {
12
+ action: "cwd";
13
+ cwd?: string;
14
+ reset?: boolean;
10
15
  };
11
16
  /** One channel bound to a desk, as `/desk list` shows it. */
12
17
  export interface DeskListChannel {
@@ -20,6 +25,8 @@ export interface DeskListItem {
20
25
  channels: DeskListChannel[];
21
26
  /** The desk the asking channel is bound to (or, in the TUI, the desk it opened). */
22
27
  current: boolean;
28
+ /** Custom working directory when `desk.json` overrides `deskDir`. */
29
+ cwd?: string;
23
30
  }
24
31
  export type BindOutcome = {
25
32
  kind: "bound";
@@ -59,9 +66,14 @@ export interface DeskCommandPort {
59
66
  list(): Promise<DeskListItem[]>;
60
67
  /** Absolute path of `CHANNELS.md`, where a truncated `/desk list` sends the reader. */
61
68
  channelIndexPath: string;
62
- create(name: string): Promise<CreateDeskOutcome>;
69
+ create(name: string, cwd?: string): Promise<CreateDeskOutcome>;
63
70
  /** Absent in the TUI, which never writes bindings (D18). */
64
71
  bind?(name: string): Promise<BindOutcome>;
72
+ /** Inspect or update the current desk's working directory (`desk.json` `cwd`). */
73
+ cwd?(input: {
74
+ cwd?: string;
75
+ reset?: boolean;
76
+ }): Promise<DeskCwdOutcome>;
65
77
  }
66
78
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
67
79
  export declare function parseDeskCommand(args: string): DeskCommand;
@@ -13,20 +13,26 @@ import { normalizeDeskName } from "./paths.js";
13
13
  * owns channel ids); `current` is the asking channel's desk.
14
14
  */
15
15
  export function buildDeskList(desks, bindings, current, label) {
16
- const onDisk = new Map(desks.map((summary) => [summary.name, summary.availability]));
17
- const names = [...new Set([...onDisk.keys(), ...Object.values(bindings).map((binding) => binding.desk)])].sort();
18
- return names.map((name) => ({
19
- name,
20
- availability: onDisk.get(name) ?? "missing",
21
- current: name === current,
22
- channels: Object.entries(bindings)
23
- .filter(([, binding]) => binding.desk === name)
24
- .map(([channelId]) => ({ channelId, label: label(channelId) })),
25
- }));
16
+ const summaries = new Map(desks.map((summary) => [summary.name, summary]));
17
+ const names = [...new Set([...summaries.keys(), ...Object.values(bindings).map((binding) => binding.desk)])].sort();
18
+ return names.map((name) => {
19
+ const summary = summaries.get(name);
20
+ const customCwd = summary?.record?.cwd && summary.record.cwd !== summary.deskDir ? summary.record.cwd : undefined;
21
+ return {
22
+ name,
23
+ availability: summary?.availability ?? "missing",
24
+ current: name === current,
25
+ channels: Object.entries(bindings)
26
+ .filter(([, binding]) => binding.desk === name)
27
+ .map(([channelId]) => ({ channelId, label: label(channelId) })),
28
+ ...(customCwd ? { cwd: customCwd } : {}),
29
+ };
30
+ });
26
31
  }
27
32
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
28
33
  export function parseDeskCommand(args) {
29
- const parts = args.trim().split(/\s+/).filter(Boolean);
34
+ const trimmed = args.trim();
35
+ const parts = trimmed.split(/\s+/).filter(Boolean);
30
36
  if (parts.length === 0)
31
37
  return { action: "list" };
32
38
  const [action, ...rest] = parts;
@@ -35,10 +41,27 @@ export function parseDeskCommand(args) {
35
41
  throw new Error("用法:/desk list");
36
42
  return { action: "list" };
37
43
  }
38
- if (action === "new" || action === "bind") {
44
+ if (action === "new") {
45
+ const match = /^new\s+(\S+)(?:\s+([\s\S]+))?$/.exec(trimmed);
46
+ if (!match)
47
+ throw new Error("用法:/desk new <名字> [目录绝对路径]");
48
+ const name = normalizeDeskName(match[1]);
49
+ const cwd = match[2]?.trim();
50
+ return cwd ? { action: "new", name, cwd } : { action: "new", name };
51
+ }
52
+ if (action === "bind") {
39
53
  if (rest.length !== 1)
40
- throw new Error(`用法:/desk ${action} <名字>`);
41
- return { action, name: normalizeDeskName(rest[0]) };
54
+ throw new Error("用法:/desk bind <名字>");
55
+ return { action: "bind", name: normalizeDeskName(rest[0]) };
56
+ }
57
+ if (action === "cwd") {
58
+ const match = /^cwd(?:\s+([\s\S]+))?$/.exec(trimmed);
59
+ const target = match?.[1]?.trim();
60
+ if (!target)
61
+ return { action: "cwd" };
62
+ if (target === "--reset" || target === "reset")
63
+ return { action: "cwd", reset: true };
64
+ return { action: "cwd", cwd: target };
42
65
  }
43
66
  throw new Error(`未知子命令 \`${action}\`。`);
44
67
  }
@@ -57,7 +80,8 @@ function renderList(items, channelIndexPath, canBind) {
57
80
  }
58
81
  const lines = ["**工位列表**"];
59
82
  for (const item of items) {
60
- const head = `- \`${item.name}\`${item.current ? (canBind ? "(本频道)" : "(当前打开)") : ""}`;
83
+ const cwdNote = item.cwd ? ` · 目录 \`${item.cwd}\`` : "";
84
+ const head = `- \`${item.name}\`${item.current ? (canBind ? "(本频道)" : "(当前打开)") : ""}${cwdNote}`;
61
85
  if (item.availability !== "available") {
62
86
  lines.push(`${head}:不可用(目录缺失或 desk.json 有误),需要部署者在服务器上检查`);
63
87
  }
@@ -76,15 +100,32 @@ function renderCreate(outcome, canBind) {
76
100
  switch (outcome.kind) {
77
101
  case "invalid":
78
102
  return `工位名不合法:\`${outcome.name}\`。${NAME_RULE}。`;
103
+ case "invalid_cwd":
104
+ return `工作目录无效:${outcome.reason}。`;
79
105
  case "unavailable":
80
106
  return `工位 \`${outcome.name}\` 已有绑定但记录缺失,请联系部署者从备份恢复。`;
81
107
  case "exists":
82
108
  return `工位 \`${outcome.name}\` 已经存在。用 \`/desk\` 查看已有的工位。`;
83
109
  case "created": {
84
110
  const name = outcome.record.name;
111
+ const cwdNote = outcome.record.cwd ? `(工作目录:\`${outcome.record.cwd}\`)` : "";
85
112
  return canBind
86
- ? `已创建工位 \`${name}\`。用 \`/desk bind ${name}\` 把本频道绑定到它。`
87
- : `已创建工位 \`${name}\`。在钉钉频道里用 \`/desk bind ${name}\` 绑定。`;
113
+ ? `已创建工位 \`${name}\`${cwdNote}。用 \`/desk bind ${name}\` 把本频道绑定到它。`
114
+ : `已创建工位 \`${name}\`${cwdNote}。在钉钉频道里用 \`/desk bind ${name}\` 绑定。`;
115
+ }
116
+ }
117
+ }
118
+ function renderCwd(outcome, isQuery) {
119
+ switch (outcome.kind) {
120
+ case "invalid_cwd":
121
+ return `工作目录无效:${outcome.reason}。`;
122
+ case "unavailable":
123
+ return `当前频道没有可用的工位,无法查看或修改工作目录。用 \`/desk\` 查看工位状态。`;
124
+ case "ok": {
125
+ const suffix = outcome.isDefault ? "(工位默认目录)" : "(自定义仓库目录,状态仍保存在工位目录)";
126
+ return isQuery
127
+ ? `工位 \`${outcome.desk}\` 当前工作目录:\`${outcome.cwd}\`${suffix}。用 \`/desk cwd <绝对路径>\` 切换目录,或 \`/desk cwd --reset\` 恢复默认。`
128
+ : `已将工位 \`${outcome.desk}\` 的工作目录设为 \`${outcome.cwd}\`${suffix}。`;
88
129
  }
89
130
  }
90
131
  }
@@ -105,7 +146,7 @@ function renderBind(outcome) {
105
146
  case "bound": {
106
147
  const lines = [`本频道已绑定到工位 \`${outcome.desk}\`。`];
107
148
  if (outcome.previousDesk && outcome.previousDeskDormant) {
108
- lines.push(`原工位 \`${outcome.previousDesk}\` 已没有绑定的频道,它的定时事件和任务已暂停,重新绑定后自动恢复。`);
149
+ lines.push(`原工位 \`${outcome.previousDesk}\` 已没有绑定的频道,它的定时事件和任务已暂停;重新绑定或打开 \`pipiclaw tui --desk ${outcome.previousDesk}\` 后自动恢复。`);
109
150
  }
110
151
  else if (outcome.previousDesk && ((outcome.suspendedTasks ?? 0) > 0 || (outcome.suspendedEvents ?? 0) > 0)) {
111
152
  const parts = [];
@@ -113,7 +154,10 @@ function renderBind(outcome) {
113
154
  parts.push(`${outcome.suspendedTasks} 个任务`);
114
155
  if (outcome.suspendedEvents)
115
156
  parts.push(`${outcome.suspendedEvents} 个定时事件`);
116
- lines.push(`原工位 \`${outcome.previousDesk}\` 中以本频道为投递频道的 ${parts.join("、")}已暂停。`);
157
+ const adoptHint = outcome.suspendedTasks
158
+ ? `可在已绑定 \`${outcome.previousDesk}\` 的其他频道或终端里执行 \`/tasks adopt <id>\` 接管汇报并继续执行。`
159
+ : "";
160
+ lines.push(`原工位 \`${outcome.previousDesk}\` 中以本频道为投递频道的 ${parts.join("、")}已暂停。${adoptHint}`);
117
161
  }
118
162
  return lines.join("\n");
119
163
  }
@@ -132,11 +176,15 @@ export async function handleDeskCommand(args, port) {
132
176
  case "list":
133
177
  return renderList(await port.list(), port.channelIndexPath, port.bind !== undefined);
134
178
  case "new":
135
- return renderCreate(await port.create(command.name), port.bind !== undefined);
179
+ return renderCreate(await port.create(command.name, command.cwd), port.bind !== undefined);
136
180
  case "bind":
137
181
  if (!port.bind)
138
182
  return "终端不支持绑定,用 `--desk` 选择工位。";
139
183
  return renderBind(await port.bind(command.name));
184
+ case "cwd":
185
+ if (!port.cwd)
186
+ return "当前入口不支持直接设置工作目录,请在对话频道或守护进程连接下执行 `/desk cwd`。";
187
+ return renderCwd(await port.cwd({ cwd: command.cwd, reset: command.reset }), !command.cwd && !command.reset);
140
188
  }
141
189
  }
142
190
  catch (error) {
@@ -1,10 +1,14 @@
1
- import type { ConversationKind, CreateDeskOutcome, DeskConversation, DeskRecord, DeskSummary } from "./types.js";
1
+ import type { ConversationKind, CreateDeskOutcome, DeskConversation, DeskCwdOutcome, DeskRecord, DeskSummary } from "./types.js";
2
2
  /** Read one desk's record, classifying it the way `/desk` and binding resolution need. */
3
3
  export declare function readDeskRecord(workspaceDir: string, name: string): Promise<DeskSummary>;
4
4
  /** Every directory under `desk-`, each classified. A directory with an illegal name is reported invalid. */
5
5
  export declare function listDesks(workspaceDir: string): Promise<DeskSummary[]>;
6
6
  /** Create an empty desk without binding it, publishing it atomically. Holds no conversation lock. */
7
- export declare function createDeskRecord(workspaceDir: string, name: string, now: Date): CreateDeskOutcome;
7
+ export declare function createDeskRecord(workspaceDir: string, name: string, now: Date, cwd?: string): CreateDeskOutcome;
8
+ /** Update or reset (`cwd: null`) a desk's custom `cwd` under `desk-json.lock`. */
9
+ export declare function setDeskCwd(workspaceDir: string, desk: string, cwd: string | null): Promise<DeskCwdOutcome>;
10
+ /** Read-only lookup of a desk's effective working directory (`desk.json` `cwd`, else `deskDir`). */
11
+ export declare function resolveDeskCwdSync(workspaceDir: string, desk: string): string;
8
12
  /**
9
13
  * The conversation directory a channel uses in this desk, allocating it on first use (INV-7):
10
14
  * `<kind>-<n>` with `n` one past the largest index of that kind already in `desk.json`. Idempotent —
@@ -9,9 +9,9 @@
9
9
  * Channel ids are only JSON keys here; this module never parses them — callers pass the
10
10
  * conversation kind (the format rules live in `channel/channel-id.ts`).
11
11
  */
12
- import { lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
13
13
  import { mkdir, readdir, readFile } from "node:fs/promises";
14
- import { isAbsolute, join } from "node:path";
14
+ import { isAbsolute, join, resolve } from "node:path";
15
15
  import { syncDirectoryBestEffort, writeFileAtomically } from "../shared/atomic-file.js";
16
16
  import { withFileLock } from "../shared/file-lock.js";
17
17
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -100,10 +100,33 @@ export async function listDesks(workspaceDir) {
100
100
  const summaries = await Promise.all(entries.sort().map((name) => readDeskRecord(workspaceDir, name)));
101
101
  return summaries;
102
102
  }
103
+ function validateCustomCwd(rawCwd) {
104
+ const trimmed = rawCwd.trim();
105
+ if (!trimmed || !isAbsolute(trimmed)) {
106
+ return { ok: false, reason: "目录路径必须是绝对路径(例如 `/srv/repo`)" };
107
+ }
108
+ const normalized = resolve(trimmed);
109
+ try {
110
+ if (!statSync(normalized).isDirectory()) {
111
+ return { ok: false, reason: `路径不是目录:\`${normalized}\`` };
112
+ }
113
+ }
114
+ catch {
115
+ return { ok: false, reason: `目录不存在或无法访问:\`${normalized}\`` };
116
+ }
117
+ return { ok: true, cwd: normalized };
118
+ }
103
119
  /** Create an empty desk without binding it, publishing it atomically. Holds no conversation lock. */
104
- export function createDeskRecord(workspaceDir, name, now) {
120
+ export function createDeskRecord(workspaceDir, name, now, cwd) {
105
121
  if (!isDeskName(name))
106
122
  return { kind: "invalid", name };
123
+ let validatedCwd;
124
+ if (cwd !== undefined) {
125
+ const checked = validateCustomCwd(cwd);
126
+ if (!checked.ok)
127
+ return { kind: "invalid_cwd", cwd, reason: checked.reason };
128
+ validatedCwd = checked.cwd;
129
+ }
107
130
  const bindings = initializeBindings(workspaceDir);
108
131
  const deskDir = getDeskDir(workspaceDir, name);
109
132
  try {
@@ -118,7 +141,13 @@ export function createDeskRecord(workspaceDir, name, now) {
118
141
  return { kind: "unavailable", name };
119
142
  mkdirSync(workspaceDir, { recursive: true });
120
143
  const staging = mkdtempSync(join(workspaceDir, `.desk-init-${name}-`));
121
- const record = { version: 1, name, createdAt: now.toISOString(), conversations: {} };
144
+ const record = {
145
+ version: 1,
146
+ name,
147
+ createdAt: now.toISOString(),
148
+ conversations: {},
149
+ ...(validatedCwd && validatedCwd !== deskDir ? { cwd: validatedCwd } : {}),
150
+ };
122
151
  try {
123
152
  writeFileSync(recordPath(staging), `${JSON.stringify(record, null, "\t")}\n`, { flush: true });
124
153
  syncDirectoryBestEffort(staging);
@@ -137,6 +166,43 @@ export function createDeskRecord(workspaceDir, name, now) {
137
166
  rmSync(staging, { recursive: true, force: true });
138
167
  }
139
168
  }
169
+ /** Update or reset (`cwd: null`) a desk's custom `cwd` under `desk-json.lock`. */
170
+ export async function setDeskCwd(workspaceDir, desk, cwd) {
171
+ if (!isDeskName(desk))
172
+ return { kind: "unavailable", desk };
173
+ let nextCwd;
174
+ if (cwd !== null) {
175
+ const checked = validateCustomCwd(cwd);
176
+ if (!checked.ok)
177
+ return { kind: "invalid_cwd", cwd, reason: checked.reason };
178
+ nextCwd = checked.cwd;
179
+ }
180
+ const deskDir = getDeskDir(workspaceDir, desk);
181
+ return withFileLock(getDeskLockPath(deskDir, "desk-json.lock"), () => writeQueue.run(recordPath(deskDir), async () => {
182
+ const summary = await readDeskRecord(workspaceDir, desk);
183
+ if (!summary.record)
184
+ return { kind: "unavailable", desk };
185
+ const { cwd: _prev, ...rest } = summary.record;
186
+ const effective = nextCwd && nextCwd !== deskDir ? nextCwd : undefined;
187
+ const updated = effective ? { ...rest, cwd: effective } : rest;
188
+ await writeJson(recordPath(deskDir), updated);
189
+ return { kind: "ok", desk, cwd: effective ?? deskDir, isDefault: effective === undefined };
190
+ }), { timeoutMs: DESK_RECORD_LOCK_TIMEOUT_MS });
191
+ }
192
+ /** Read-only lookup of a desk's effective working directory (`desk.json` `cwd`, else `deskDir`). */
193
+ export function resolveDeskCwdSync(workspaceDir, desk) {
194
+ const deskDir = getDeskDir(workspaceDir, desk);
195
+ try {
196
+ const parsed = JSON.parse(readFileSync(recordPath(deskDir), "utf-8"));
197
+ if (isPlainObject(parsed) && typeof parsed.cwd === "string" && isAbsolute(parsed.cwd)) {
198
+ return parsed.cwd;
199
+ }
200
+ }
201
+ catch {
202
+ // Fall back to the desk directory when `desk.json` is absent or unreadable.
203
+ }
204
+ return deskDir;
205
+ }
140
206
  /**
141
207
  * The conversation directory a channel uses in this desk, allocating it on first use (INV-7):
142
208
  * `<kind>-<n>` with `n` one past the largest index of that kind already in `desk.json`. Idempotent —
@@ -63,6 +63,10 @@ export type CreateDeskOutcome = {
63
63
  } | {
64
64
  kind: "invalid";
65
65
  name: string;
66
+ } | {
67
+ kind: "invalid_cwd";
68
+ cwd: string;
69
+ reason: string;
66
70
  } | {
67
71
  kind: "exists";
68
72
  name: string;
@@ -70,3 +74,16 @@ export type CreateDeskOutcome = {
70
74
  kind: "unavailable";
71
75
  name: string;
72
76
  };
77
+ export type DeskCwdOutcome = {
78
+ kind: "ok";
79
+ desk: string;
80
+ cwd: string;
81
+ isDefault: boolean;
82
+ } | {
83
+ kind: "invalid_cwd";
84
+ cwd: string;
85
+ reason: string;
86
+ } | {
87
+ kind: "unavailable";
88
+ desk: string;
89
+ };
@@ -74,7 +74,7 @@ export declare class DingTalkBot implements DeliveryPort {
74
74
  * deterministic e2e harness can override it and run the inbound path with zero network, the
75
75
  * same pattern `HarnessDingTalkBot` already uses for outbound calls.
76
76
  */
77
- protected downloadMessageFile(downloadCode: string): Promise<{
77
+ protected downloadMessageFile(downloadCode: string, maxBytes?: number): Promise<{
78
78
  data: Buffer;
79
79
  } | null>;
80
80
  private touchChannel;
@@ -41,7 +41,7 @@ export class DingTalkBot {
41
41
  getAccessToken,
42
42
  getConversationMeta: (channelId) => this.conversations.get(channelId),
43
43
  sendRobotMessage: sendRobot,
44
- downloadMessageFile: (downloadCode) => this.downloadMessageFile(downloadCode),
44
+ downloadMessageFile: (downloadCode, maxBytes) => this.downloadMessageFile(downloadCode, maxBytes),
45
45
  });
46
46
  this.connection = new StreamConnection({
47
47
  clientId: this.config.clientId,
@@ -56,6 +56,7 @@ export class DingTalkBot {
56
56
  isStopped: () => this.isStopped,
57
57
  ack: (messageId) => this.connection.ack(messageId),
58
58
  collectAttachments: (parsed) => this.media.collectInboundAttachments(parsed),
59
+ sendPlain: (channelId, text) => this.sendPlain(channelId, text),
59
60
  });
60
61
  }
61
62
  get busyMessageDefault() {
@@ -188,8 +189,8 @@ export class DingTalkBot {
188
189
  * deterministic e2e harness can override it and run the inbound path with zero network, the
189
190
  * same pattern `HarnessDingTalkBot` already uses for outbound calls.
190
191
  */
191
- downloadMessageFile(downloadCode) {
192
- return this.media.downloadMessageFile(downloadCode);
192
+ downloadMessageFile(downloadCode, maxBytes) {
193
+ return this.media.downloadMessageFile(downloadCode, maxBytes);
193
194
  }
194
195
  touchChannel(channelId) {
195
196
  this.channelLastActiveAt.set(channelId, Date.now());