@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-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 (189) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -1
  2. package/dist/agent/channel-runner.js +51 -18
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/effect-ledger.js +9 -2
  7. package/dist/agent/job-manager.d.ts +4 -0
  8. package/dist/agent/job-manager.js +17 -2
  9. package/dist/agent/prompt/manifest.d.ts +1 -1
  10. package/dist/agent/prompt/manifest.js +6 -7
  11. package/dist/agent/prompt/sections.js +9 -5
  12. package/dist/agent/reply-limits.d.ts +16 -0
  13. package/dist/agent/reply-limits.js +17 -0
  14. package/dist/agent/session-events.d.ts +2 -0
  15. package/dist/agent/session-events.js +29 -14
  16. package/dist/agent/status-render.js +12 -12
  17. package/dist/agent/turn-recovery.js +2 -2
  18. package/dist/agent/type-guards.js +5 -1
  19. package/dist/agent/workspace-resources.d.ts +2 -2
  20. package/dist/agent/workspace-resources.js +41 -3
  21. package/dist/executor.d.ts +28 -0
  22. package/dist/executor.js +120 -18
  23. package/dist/file-store.d.ts +96 -0
  24. package/dist/file-store.js +189 -0
  25. package/dist/main.js +3 -4
  26. package/dist/memory/commands.js +79 -38
  27. package/dist/memory/consolidation.d.ts +5 -1
  28. package/dist/memory/consolidation.js +35 -38
  29. package/dist/memory/extraction.d.ts +8 -1
  30. package/dist/memory/extraction.js +47 -4
  31. package/dist/memory/files.d.ts +0 -1
  32. package/dist/memory/files.js +31 -12
  33. package/dist/memory/lifecycle.js +9 -2
  34. package/dist/memory/maintenance-jobs.js +16 -38
  35. package/dist/memory/maintenance-state.js +2 -1
  36. package/dist/memory/metadata.d.ts +3 -0
  37. package/dist/memory/metadata.js +7 -0
  38. package/dist/memory/recall.d.ts +19 -0
  39. package/dist/memory/recall.js +116 -24
  40. package/dist/memory/review-log.d.ts +0 -2
  41. package/dist/memory/review-log.js +0 -0
  42. package/dist/memory/session-corpus.js +5 -0
  43. package/dist/memory/session-search.js +15 -22
  44. package/dist/memory/sidecar-worker.js +4 -0
  45. package/dist/memory/source-window.d.ts +0 -1
  46. package/dist/memory/source-window.js +0 -5
  47. package/dist/memory/transcript.d.ts +10 -0
  48. package/dist/memory/transcript.js +39 -0
  49. package/dist/playbooks/agent-delegation.md +34 -25
  50. package/dist/playbooks/background-jobs.md +8 -16
  51. package/dist/playbooks/catalog.d.ts +1 -1
  52. package/dist/playbooks/catalog.js +1 -1
  53. package/dist/playbooks/event-scheduling.md +15 -15
  54. package/dist/playbooks/memory-and-learning.md +30 -23
  55. package/dist/playbooks/outbound-media.md +15 -8
  56. package/dist/playbooks/runtime-orientation.md +40 -37
  57. package/dist/playbooks/task-driving.md +36 -38
  58. package/dist/playbooks/task-planning.md +21 -21
  59. package/dist/runtime/app-home.d.ts +6 -0
  60. package/dist/runtime/app-home.js +16 -7
  61. package/dist/runtime/bootstrap.js +54 -13
  62. package/dist/runtime/channel-context.d.ts +2 -1
  63. package/dist/runtime/delivery.js +3 -3
  64. package/dist/runtime/dingtalk.d.ts +9 -1
  65. package/dist/runtime/dingtalk.js +30 -15
  66. package/dist/runtime/durable-dispatch.d.ts +26 -1
  67. package/dist/runtime/durable-dispatch.js +51 -5
  68. package/dist/runtime/event-commands.d.ts +15 -0
  69. package/dist/runtime/event-commands.js +55 -56
  70. package/dist/runtime/events.d.ts +4 -2
  71. package/dist/runtime/events.js +15 -20
  72. package/dist/runtime/project-commands.d.ts +16 -0
  73. package/dist/runtime/project-commands.js +13 -17
  74. package/dist/runtime/subagent-commands.d.ts +20 -0
  75. package/dist/runtime/subagent-commands.js +61 -58
  76. package/dist/runtime/task-commands.d.ts +37 -0
  77. package/dist/runtime/task-commands.js +108 -66
  78. package/dist/runtime/task-driver.js +2 -2
  79. package/dist/security/block-message.d.ts +11 -0
  80. package/dist/security/block-message.js +12 -0
  81. package/dist/security/path-guard-check.d.ts +13 -0
  82. package/dist/security/path-guard-check.js +39 -0
  83. package/dist/security/path-guard.js +61 -12
  84. package/dist/security/types.d.ts +9 -0
  85. package/dist/settings.js +3 -2
  86. package/dist/shared/atomic-file.d.ts +17 -1
  87. package/dist/shared/atomic-file.js +50 -3
  88. package/dist/shared/duration.d.ts +2 -0
  89. package/dist/shared/duration.js +7 -0
  90. package/dist/shared/safe-id.d.ts +19 -0
  91. package/dist/shared/safe-id.js +24 -0
  92. package/dist/shared/text-utils.d.ts +1 -1
  93. package/dist/shared/text-utils.js +3 -8
  94. package/dist/shared/type-guards.d.ts +2 -0
  95. package/dist/shared/type-guards.js +4 -0
  96. package/dist/subagents/discovery.d.ts +51 -19
  97. package/dist/subagents/discovery.js +93 -98
  98. package/dist/subagents/external/claude-code.js +40 -2
  99. package/dist/subagents/external/harness.d.ts +1 -1
  100. package/dist/subagents/external/run.js +61 -8
  101. package/dist/subagents/format.d.ts +3 -2
  102. package/dist/subagents/format.js +3 -7
  103. package/dist/subagents/runs.d.ts +1 -1
  104. package/dist/subagents/runs.js +10 -9
  105. package/dist/subagents/tool.d.ts +31 -18
  106. package/dist/subagents/tool.js +592 -562
  107. package/dist/subagents/workspace-lease.js +1 -1
  108. package/dist/tasks/control.js +7 -9
  109. package/dist/tasks/ledger.d.ts +2 -2
  110. package/dist/tasks/ledger.js +3 -7
  111. package/dist/tasks/transitions.d.ts +5 -1
  112. package/dist/tasks/transitions.js +2 -2
  113. package/dist/tasks/verification.d.ts +7 -5
  114. package/dist/tools/bash.d.ts +1 -2
  115. package/dist/tools/bash.js +99 -76
  116. package/dist/tools/config.d.ts +6 -1
  117. package/dist/tools/config.js +9 -0
  118. package/dist/tools/edit.d.ts +2 -3
  119. package/dist/tools/edit.js +276 -75
  120. package/dist/tools/event-manage.d.ts +13 -7
  121. package/dist/tools/event-manage.js +52 -14
  122. package/dist/tools/glob-match.d.ts +11 -0
  123. package/dist/tools/glob-match.js +75 -0
  124. package/dist/tools/glob.d.ts +15 -0
  125. package/dist/tools/glob.js +113 -0
  126. package/dist/tools/grep.d.ts +0 -1
  127. package/dist/tools/grep.js +60 -44
  128. package/dist/tools/ignore-dirs.d.ts +6 -0
  129. package/dist/tools/ignore-dirs.js +15 -0
  130. package/dist/tools/index.d.ts +3 -0
  131. package/dist/tools/index.js +54 -40
  132. package/dist/tools/job.d.ts +0 -1
  133. package/dist/tools/job.js +3 -9
  134. package/dist/tools/line-index.d.ts +16 -0
  135. package/dist/tools/line-index.js +76 -0
  136. package/dist/tools/memory-manage.d.ts +21 -8
  137. package/dist/tools/memory-manage.js +114 -103
  138. package/dist/tools/presentation.d.ts +2 -0
  139. package/dist/tools/presentation.js +109 -0
  140. package/dist/tools/read.d.ts +2 -2
  141. package/dist/tools/read.js +100 -120
  142. package/dist/tools/registry.d.ts +4 -1
  143. package/dist/tools/registry.js +89 -22
  144. package/dist/tools/send-media.d.ts +6 -6
  145. package/dist/tools/send-media.js +21 -43
  146. package/dist/tools/session-search.d.ts +0 -1
  147. package/dist/tools/session-search.js +0 -1
  148. package/dist/tools/skill-security.d.ts +0 -2
  149. package/dist/tools/skill-security.js +1 -25
  150. package/dist/tools/skill.d.ts +31 -0
  151. package/dist/tools/skill.js +153 -0
  152. package/dist/tools/subagent-manage.d.ts +6 -5
  153. package/dist/tools/subagent-manage.js +47 -47
  154. package/dist/tools/task-manage/create.d.ts +2 -2
  155. package/dist/tools/task-manage/create.js +1 -3
  156. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  157. package/dist/tools/task-manage/lifecycle.js +49 -56
  158. package/dist/tools/task-manage/schema.d.ts +27 -15
  159. package/dist/tools/task-manage/schema.js +58 -74
  160. package/dist/tools/task-manage/shared.d.ts +11 -6
  161. package/dist/tools/task-manage/shared.js +30 -21
  162. package/dist/tools/task-manage/types.d.ts +14 -15
  163. package/dist/tools/task-manage/verification.d.ts +4 -4
  164. package/dist/tools/task-manage/verification.js +6 -8
  165. package/dist/tools/task-manage.d.ts +8 -11
  166. package/dist/tools/task-manage.js +63 -50
  167. package/dist/tools/tool-details.d.ts +17 -1
  168. package/dist/tools/tool-details.js +24 -0
  169. package/dist/tools/truncate.d.ts +8 -0
  170. package/dist/tools/truncate.js +8 -0
  171. package/dist/tools/web-fetch.d.ts +0 -1
  172. package/dist/tools/web-fetch.js +9 -2
  173. package/dist/tools/web-search.d.ts +0 -1
  174. package/dist/tools/web-search.js +0 -1
  175. package/dist/tools/write-content.d.ts +3 -3
  176. package/dist/tools/write-content.js +12 -41
  177. package/dist/tools/write.d.ts +2 -3
  178. package/dist/tools/write.js +3 -4
  179. package/dist/tui/app.js +1 -1
  180. package/dist/tui/commands.d.ts +1 -1
  181. package/dist/tui/commands.js +1 -1
  182. package/dist/tui/turn-controller.d.ts +1 -1
  183. package/dist/tui/turn-controller.js +14 -4
  184. package/dist/usage/ledger.js +7 -4
  185. package/dist/usage/render.js +10 -8
  186. package/examples/sub-agents/README.md +2 -0
  187. package/package.json +3 -2
  188. package/dist/tools/skill-manage.d.ts +0 -41
  189. package/dist/tools/skill-manage.js +0 -231
@@ -9,10 +9,11 @@
9
9
  */
10
10
  import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
12
+ import { existsSync, mkdirSync, readFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
14
  import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
16
17
  import { errorMessage } from "../shared/text-utils.js";
17
18
  import { isRecord } from "../shared/type-guards.js";
18
19
  import { getChannelDir } from "./channel-paths.js";
@@ -683,16 +684,22 @@ export class DingTalkBot {
683
684
  *
684
685
  * Only the message shape is decided here; the DM-vs-group routing and the POST itself belong to
685
686
  * `sendRobotMessage`, which every other outbound message type already goes through.
687
+ *
688
+ * `opts` lets a caller that already knows what it produced (a command reply) state the format
689
+ * and a real title instead of the regex guess below, which exists only for callers — free-form
690
+ * notices, `replaceWithFinal` — that do not know their own content ahead of time (review
691
+ * 2026-08-24 §1.3c).
686
692
  */
687
- async sendPlain(channelId, text) {
693
+ async sendPlain(channelId, text, opts) {
688
694
  const meta = this.getConversationMeta(channelId);
689
695
  if (!meta) {
690
696
  log.logWarning(`No conversation metadata for ${channelId}, cannot send plain message`);
691
697
  return false;
692
698
  }
693
- const hasMarkdown = /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
699
+ const hasMarkdown = opts?.markdown ?? /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
700
+ const title = opts?.title ?? "Bot";
694
701
  const msgKey = hasMarkdown ? "sampleMarkdown" : "sampleText";
695
- const msgParam = hasMarkdown ? JSON.stringify({ text, title: "Bot" }) : JSON.stringify({ content: text });
702
+ const msgParam = hasMarkdown ? JSON.stringify({ text, title }) : JSON.stringify({ content: text });
696
703
  return this.sendRobotMessage(meta, msgKey, msgParam);
697
704
  }
698
705
  // ==========================================================================
@@ -1082,13 +1089,16 @@ export class DingTalkBot {
1082
1089
  if (builtInCommand) {
1083
1090
  switch (builtInCommand.name) {
1084
1091
  case "help":
1085
- await this.sendPlain(channelId, renderBuiltInHelp());
1092
+ await this.sendPlain(channelId, renderBuiltInHelp(builtInCommand.args), {
1093
+ title: "/help",
1094
+ markdown: true,
1095
+ });
1086
1096
  return;
1087
1097
  case "stop": {
1088
1098
  const outcome = await this.handler.handleStop(channelId, this);
1089
1099
  await this.sendPlain(channelId, outcome.pausedTaskId
1090
1100
  ? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
1091
- : "已停止当前回合。");
1101
+ : "已停止当前回合。", { title: "/stop", markdown: true });
1092
1102
  return;
1093
1103
  }
1094
1104
  case "steer":
@@ -1100,15 +1110,20 @@ export class DingTalkBot {
1100
1110
  }
1101
1111
  return;
1102
1112
  }
1103
- case "events":
1104
- case "tasks":
1105
- case "status":
1106
- case "usage":
1107
- case "context":
1108
- case "subagents":
1109
- case "project": {
1113
+ default: {
1114
+ // Every remaining BuiltInCommandName is a stateless report (events/tasks/status/usage/
1115
+ // context/subagents/project), narrowed to RuntimeCommandName by TS after the four
1116
+ // cases above. Busy has no sendCommandReply-style retry semantics, so `/context` is
1117
+ // answered here like the rest instead of the runner-handled path idle uses for it
1118
+ // (see the IDLE_RUNTIME_COMMAND_NAMES comment in bootstrap.ts).
1110
1119
  const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
1111
- await this.sendPlain(channelId, response);
1120
+ const delivered = await this.sendPlain(channelId, response, {
1121
+ title: `/${builtInCommand.name}`,
1122
+ markdown: true,
1123
+ });
1124
+ if (!delivered) {
1125
+ log.logWarning(`[${channelId}] Failed to deliver /${builtInCommand.name} reply`, `${response.length} chars`);
1126
+ }
1112
1127
  return;
1113
1128
  }
1114
1129
  }
@@ -1192,7 +1207,7 @@ export class DingTalkBot {
1192
1207
  return;
1193
1208
  try {
1194
1209
  mkdirSync(dirname(metaPath), { recursive: true });
1195
- writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf-8");
1210
+ writeFileAtomicallySync(metaPath, JSON.stringify(meta, null, 2));
1196
1211
  }
1197
1212
  catch (err) {
1198
1213
  log.logWarning(`Failed to persist conversation metadata for ${channelId}`, errorMessage(err));
@@ -1,10 +1,28 @@
1
1
  import type { ChannelEvent } from "./channel-event.js";
2
2
  import type { DingTalkBot } from "./dingtalk.js";
3
+ type DispatchStatus = "pending" | "queued" | "running" | "exhausted";
4
+ export interface DurableDispatchRecord {
5
+ version: 1;
6
+ id: string;
7
+ createdAt: string;
8
+ status: DispatchStatus;
9
+ event: ChannelEvent;
10
+ deliveries: number;
11
+ leaseExpiresAt?: string;
12
+ /** Set by `markRetryable` to back off a repeatedly-failing structured wake instead of
13
+ * redelivering on the very next drain tick (spec 031's redelivery has no such gate). */
14
+ nextAttemptAt?: string;
15
+ }
3
16
  export interface DurableDispatchOptions {
4
17
  stateDir: string;
5
18
  bot: Pick<DingTalkBot, "enqueueEvent">;
6
19
  leaseMs?: number;
7
20
  intervalMs?: number;
21
+ /** Called once, at most, when a dispatch id hits `MAX_DELIVERIES` without ever completing —
22
+ * e.g. a structured wake whose claim/finish step fails deterministically (disk full,
23
+ * permissions). The record is left on disk (not deleted) so the failure is inspectable; the
24
+ * caller is expected to notify the channel. */
25
+ onExhausted?: (record: DurableDispatchRecord) => void | Promise<void>;
8
26
  }
9
27
  /**
10
28
  * Tiny file-backed outbox for synthetic work. It intentionally provides
@@ -37,10 +55,17 @@ export declare class DurableDispatchService {
37
55
  markCompleted(id: string | undefined): Promise<void>;
38
56
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
39
57
  * wake activation uses this for transient task/job/run persistence failures so the next drain
40
- * can retry the same dispatch id instead of losing the only completion signal. */
58
+ * can retry the same dispatch id instead of losing the only completion signal.
59
+ *
60
+ * A failure here means the handler itself is broken for this wake (a claim or finish step
61
+ * threw), not that the outbox lost a race — redelivering on the very next 30s tick would just
62
+ * repeat the same failure forever. Back off exponentially by delivery count instead; `deliveries`
63
+ * doubles as the poison-pill counter in `drainRecord`, so a wake that keeps failing here still
64
+ * eventually hits `MAX_DELIVERIES` and stops. */
41
65
  markRetryable(id: string | undefined): Promise<void>;
42
66
  drainOnce(now?: number): Promise<void>;
43
67
  private drainRecord;
44
68
  private read;
45
69
  private write;
46
70
  }
71
+ export {};
@@ -1,11 +1,18 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import * as log from "../log.js";
4
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
6
  import { createSerialQueue } from "../shared/serial-queue.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
6
8
  import { isRecord } from "../shared/type-guards.js";
7
9
  const DEFAULT_LEASE_MS = 15 * 60_000;
8
10
  const DEFAULT_INTERVAL_MS = 30_000;
11
+ /** Total delivery attempts (crash-lease redelivery and `markRetryable` failures combined) before
12
+ * a dispatch id is given up on as a poison pill rather than retried forever. */
13
+ const MAX_DELIVERIES = 8;
14
+ const MIN_RETRY_BACKOFF_MS = 30_000;
15
+ const MAX_RETRY_BACKOFF_MS = 10 * 60_000;
9
16
  function recordPath(stateDir, id) {
10
17
  return join(stateDir, `${id}.json`);
11
18
  }
@@ -40,11 +47,15 @@ function parseRecord(raw) {
40
47
  value.version !== 1 ||
41
48
  typeof value.id !== "string" ||
42
49
  typeof value.createdAt !== "string" ||
43
- (value.status !== "pending" && value.status !== "queued" && value.status !== "running") ||
50
+ (value.status !== "pending" &&
51
+ value.status !== "queued" &&
52
+ value.status !== "running" &&
53
+ value.status !== "exhausted") ||
44
54
  !isRecord(value.event) ||
45
55
  typeof value.event.channelId !== "string" ||
46
56
  typeof value.event.text !== "string" ||
47
- typeof value.deliveries !== "number") {
57
+ typeof value.deliveries !== "number" ||
58
+ (value.nextAttemptAt !== undefined && typeof value.nextAttemptAt !== "string")) {
48
59
  return undefined;
49
60
  }
50
61
  return value;
@@ -109,9 +120,13 @@ export class DurableDispatchService {
109
120
  // channel's outstanding record just to learn the outcome of the one just written.
110
121
  await this.drainRecord(id, Date.now());
111
122
  // The record is gone (delivered+completed already) or no longer "pending"
112
- // (drainRecord only reverts to "pending" when bot.enqueueEvent rejected it).
123
+ // (drainRecord only reverts to "pending" when bot.enqueueEvent rejected it). "exhausted"
124
+ // is reported as not-accepted too: the poison pill is durably recorded and its owner
125
+ // notified via onExhausted, but this dispatch id will never be delivered again.
113
126
  const after = await this.read(id);
114
- return after?.status !== "pending";
127
+ if (!after)
128
+ return true;
129
+ return after.status !== "pending" && after.status !== "exhausted";
115
130
  }
116
131
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
117
132
  async cancelChannel(channelId) {
@@ -164,7 +179,13 @@ export class DurableDispatchService {
164
179
  }
165
180
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
166
181
  * wake activation uses this for transient task/job/run persistence failures so the next drain
167
- * can retry the same dispatch id instead of losing the only completion signal. */
182
+ * can retry the same dispatch id instead of losing the only completion signal.
183
+ *
184
+ * A failure here means the handler itself is broken for this wake (a claim or finish step
185
+ * threw), not that the outbox lost a race — redelivering on the very next 30s tick would just
186
+ * repeat the same failure forever. Back off exponentially by delivery count instead; `deliveries`
187
+ * doubles as the poison-pill counter in `drainRecord`, so a wake that keeps failing here still
188
+ * eventually hits `MAX_DELIVERIES` and stops. */
168
189
  async markRetryable(id) {
169
190
  if (!id)
170
191
  return;
@@ -173,8 +194,10 @@ export class DurableDispatchService {
173
194
  const record = await this.read(id);
174
195
  if (!record)
175
196
  return;
197
+ const backoffMs = Math.min(MIN_RETRY_BACKOFF_MS * 2 ** Math.max(0, record.deliveries - 1), MAX_RETRY_BACKOFF_MS);
176
198
  record.status = "pending";
177
199
  record.leaseExpiresAt = undefined;
200
+ record.nextAttemptAt = new Date(Date.now() + backoffMs).toISOString();
178
201
  await this.write(record);
179
202
  });
180
203
  }
@@ -196,6 +219,10 @@ export class DurableDispatchService {
196
219
  const record = await this.read(id);
197
220
  if (!record)
198
221
  return;
222
+ // A poison pill: give up on redelivery for good, once. Left on disk (not deleted) so
223
+ // `onExhausted`'s notice stays inspectable and the record is available for manual retry.
224
+ if (record.status === "exhausted")
225
+ return;
199
226
  // The turn is still running in this process: renew its lease rather than treating a
200
227
  // long turn as a lost one and redelivering the wake underneath it (D2).
201
228
  if (record.status === "running" && this.running.has(id)) {
@@ -212,9 +239,28 @@ export class DurableDispatchService {
212
239
  const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
213
240
  if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
214
241
  return;
242
+ // markRetryable's backoff window; a plain enqueueEvent-rejected "pending" (no
243
+ // nextAttemptAt) still retries on the very next tick, as before.
244
+ const nextAttemptMs = record.nextAttemptAt ? new Date(record.nextAttemptAt).getTime() : undefined;
245
+ if (record.status === "pending" && nextAttemptMs && nextAttemptMs > now)
246
+ return;
247
+ if (record.deliveries >= MAX_DELIVERIES) {
248
+ record.status = "exhausted";
249
+ record.leaseExpiresAt = undefined;
250
+ record.nextAttemptAt = undefined;
251
+ await this.write(record);
252
+ try {
253
+ await this.options.onExhausted?.(record);
254
+ }
255
+ catch (err) {
256
+ log.logWarning(`Dispatch onExhausted handler failed for ${id}`, errorMessage(err));
257
+ }
258
+ return;
259
+ }
215
260
  record.status = "queued";
216
261
  record.deliveries++;
217
262
  record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
263
+ record.nextAttemptAt = undefined;
218
264
  await this.write(record);
219
265
  const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
220
266
  if (accepted)
@@ -3,9 +3,24 @@ export interface HandleEventsCommandOptions {
3
3
  workspaceDir: string;
4
4
  historyPath: string;
5
5
  }
6
+ type EventsCommand = {
7
+ action: "list";
8
+ } | {
9
+ action: "show";
10
+ name: string;
11
+ } | {
12
+ action: "delete";
13
+ name: string;
14
+ } | {
15
+ action: "history";
16
+ name?: string;
17
+ };
18
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
19
+ export declare function parseEventsCommand(args: string): EventsCommand;
6
20
  export declare function normalizeEventName(name: string): string;
7
21
  export declare function resolveEventPath(workspaceDir: string, name: string): {
8
22
  eventName: string;
9
23
  eventPath: string;
10
24
  };
11
25
  export declare function handleEventsCommand(options: HandleEventsCommandOptions): Promise<string>;
26
+ export {};
@@ -1,90 +1,79 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
- import { join, resolve, sep } from "path";
4
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
3
+ import { join } from "path";
4
+ import { renderSubcommandUsage } from "../agent/commands.js";
5
+ import { capReply } from "../agent/reply-limits.js";
6
+ import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
+ import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
5
8
  import { parseScheduledEventContent } from "./events.js";
6
9
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
7
10
  const DEFAULT_HISTORY_LIMIT = 20;
8
11
  const TEXT_PREVIEW_MAX_CHARS = 100;
9
12
  function usage() {
10
- return `# Events
11
-
12
- Usage:
13
-
14
- - \`/events list\`
15
- - \`/events show <name>\`
16
- - \`/events delete <name>\`
17
- - \`/events history [name]\``;
13
+ return renderSubcommandUsage("events");
18
14
  }
19
- function parseEventsCommand(args) {
15
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
16
+ export function parseEventsCommand(args) {
20
17
  const parts = args.trim().split(/\s+/).filter(Boolean);
21
18
  const action = parts[0];
22
19
  const name = parts[1];
23
20
  if (!action || action === "list") {
24
21
  if (parts.length > 1)
25
- throw new Error("Usage: /events list");
22
+ throw new Error("用法:/events list");
26
23
  return { action: "list" };
27
24
  }
28
25
  if (action === "show") {
29
26
  if (!name || parts.length > 2)
30
- throw new Error("Usage: /events show <name>");
27
+ throw new Error("用法:/events show <name>");
31
28
  return { action, name };
32
29
  }
33
30
  if (action === "delete") {
34
31
  if (!name || parts.length > 2)
35
- throw new Error("Usage: /events delete <name>");
32
+ throw new Error("用法:/events delete <name>");
36
33
  return { action, name };
37
34
  }
38
35
  if (action === "history") {
39
36
  if (parts.length > 2)
40
- throw new Error("Usage: /events history [name]");
37
+ throw new Error("用法:/events history [name]");
41
38
  return name ? { action, name } : { action };
42
39
  }
43
- throw new Error(`Unknown /events action: ${action}`);
40
+ throw new Error(`未知的 /events 动作:${action}`);
44
41
  }
45
42
  function eventsDir(workspaceDir) {
46
43
  return join(workspaceDir, "events");
47
44
  }
45
+ const SAFE_ID_OPTIONS = { suffix: ".json", pattern: EVENT_NAME_PATTERN, label: "event name" };
46
+ // English on purpose: shared with the model-facing `event_manage` tool (src/tools/event-manage.ts),
47
+ // which follows the tool-error convention elsewhere in the codebase, not the command-reply one.
48
48
  export function normalizeEventName(name) {
49
- const trimmed = name.trim();
50
- const normalized = trimmed.endsWith(".json") ? trimmed.slice(0, -".json".length) : trimmed;
51
- if (!normalized || normalized === "." || normalized === ".." || !EVENT_NAME_PATTERN.test(normalized)) {
52
- throw new Error(`Invalid event name: ${name}`);
53
- }
54
- return normalized;
49
+ return normalizeSafeId(name, SAFE_ID_OPTIONS);
55
50
  }
56
51
  export function resolveEventPath(workspaceDir, name) {
57
- const eventName = normalizeEventName(name);
58
- const dir = resolve(eventsDir(workspaceDir));
59
- const eventPath = resolve(dir, `${eventName}.json`);
60
- if (eventPath !== join(dir, `${eventName}.json`) || !eventPath.startsWith(`${dir}${sep}`)) {
61
- throw new Error(`Invalid event name: ${name}`);
62
- }
52
+ const { id: eventName, path: eventPath } = resolveSafeIdPath(eventsDir(workspaceDir), name, SAFE_ID_OPTIONS);
63
53
  return { eventName, eventPath };
64
54
  }
65
55
  function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
66
- const normalized = text.replace(/\s+/g, " ").trim();
67
- return normalized.length > maxChars ? `${normalized.slice(0, maxChars - 1)}...` : normalized;
56
+ return sharedClipText(text, maxChars, { headRatio: 1, omitHint: "...", collapseWhitespace: true });
68
57
  }
69
58
  function formatEventSummary(name, event) {
70
- const lines = [`- ${name}`, ` type: ${event.type}`, ` channelId: ${event.channelId}`];
59
+ const lines = [`**${name}**`, `- 类型:${event.type}`, `- channelId:${event.channelId}`];
71
60
  if (event.type === "one-shot") {
72
- lines.push(` at: ${event.at}`);
61
+ lines.push(`- 触发时间:${event.at}`);
73
62
  }
74
63
  if (event.type === "periodic") {
75
- lines.push(` schedule: ${event.schedule}`);
64
+ lines.push(`- schedule:${event.schedule}`);
76
65
  }
77
- lines.push(` text: ${clipText(event.text)}`);
66
+ lines.push(`- 内容:${clipText(event.text)}`);
78
67
  return lines.join("\n");
79
68
  }
80
69
  async function listEvents(workspaceDir) {
81
70
  const dir = eventsDir(workspaceDir);
82
71
  if (!existsSync(dir)) {
83
- return "# Events\n\nNo events directory found.";
72
+ return "**定时事件**\n\n没有找到 events 目录。";
84
73
  }
85
74
  const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".json")).sort();
86
75
  if (filenames.length === 0) {
87
- return "# Events\n\nNo event files found.";
76
+ return "**定时事件**\n\n暂无事件文件。";
88
77
  }
89
78
  const blocks = [];
90
79
  for (const filename of filenames) {
@@ -96,19 +85,21 @@ async function listEvents(workspaceDir) {
96
85
  }
97
86
  catch (error) {
98
87
  const message = errorMessage(error);
99
- blocks.push(`- ${name}\n invalid: ${message}`);
88
+ blocks.push(`**${name}**\n- ⚠ 无效:${message}`);
100
89
  }
101
90
  }
102
- return `# Events\n\n${blocks.join("\n\n")}`;
91
+ return capReply(`**定时事件**\n\n${blocks.join("\n\n")}`, {
92
+ nextStepHint: "用 `/events show <name>` 查看单个事件",
93
+ }).text;
103
94
  }
104
95
  async function showEvent(workspaceDir, name) {
105
96
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
106
97
  if (!existsSync(eventPath)) {
107
- return `Event not found: ${eventName}`;
98
+ return `找不到事件:${eventName}`;
108
99
  }
109
100
  const raw = await readFile(eventPath, "utf-8");
110
101
  const parsed = JSON.parse(raw);
111
- return `# Event: ${eventName}
102
+ return `**事件 ${eventName}**
112
103
 
113
104
  \`\`\`json
114
105
  ${JSON.stringify(parsed, null, 2)}
@@ -117,10 +108,20 @@ ${JSON.stringify(parsed, null, 2)}
117
108
  async function deleteEvent(workspaceDir, name) {
118
109
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
119
110
  if (!existsSync(eventPath)) {
120
- return `Event not found: ${eventName}`;
111
+ return `找不到事件:${eventName}`;
112
+ }
113
+ // Read before deleting so the reply carries what was removed (review 2026-08-24 §3.4):
114
+ // an accidental delete stays recoverable from chat history instead of a bare confirmation.
115
+ let summary;
116
+ try {
117
+ const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), `${eventName}.json`);
118
+ summary = formatEventSummary(eventName, event);
119
+ }
120
+ catch {
121
+ // Unparseable content is still safe to delete; just skip the summary.
121
122
  }
122
123
  await unlink(eventPath);
123
- return `Deleted event: ${eventName}`;
124
+ return summary ? `已删除事件:\n\n${summary}` : `已删除事件:${eventName}`;
124
125
  }
125
126
  function parseHistoryLine(line) {
126
127
  try {
@@ -137,24 +138,24 @@ function parseHistoryLine(line) {
137
138
  function formatHistoryRecord(record) {
138
139
  const details = [];
139
140
  if (record.channelId)
140
- details.push(` channelId: ${record.channelId}`);
141
+ details.push(`- channelId:${record.channelId}`);
141
142
  if (record.schedule)
142
- details.push(` schedule: ${record.schedule}`);
143
+ details.push(`- schedule:${record.schedule}`);
143
144
  if (record.at)
144
- details.push(` at: ${record.at}`);
145
+ details.push(`- 触发时间:${record.at}`);
145
146
  if (record.nextRunAt)
146
- details.push(` nextRunAt: ${record.nextRunAt}`);
147
+ details.push(`- 下次运行:${record.nextRunAt}`);
147
148
  if (record.reason)
148
- details.push(` reason: ${record.reason}`);
149
+ details.push(`- 原因:${record.reason}`);
149
150
  if (record.textPreview)
150
- details.push(` text: ${clipText(record.textPreview)}`);
151
- const header = `- ${record.ts} ${record.eventName} ${record.action} ${record.result}`;
151
+ details.push(`- 内容:${clipText(record.textPreview)}`);
152
+ const header = `**${record.ts} ${record.eventName}** ${record.action} · ${record.result}`;
152
153
  return details.length > 0 ? `${header}\n${details.join("\n")}` : header;
153
154
  }
154
155
  async function showHistory(historyPath, name) {
155
156
  const eventName = name ? normalizeEventName(name) : undefined;
156
157
  if (!existsSync(historyPath)) {
157
- return "# Event History\n\nNo event history found.";
158
+ return "**事件历史**\n\n暂无事件历史。";
158
159
  }
159
160
  const raw = await readFile(historyPath, "utf-8");
160
161
  const records = raw
@@ -167,12 +168,10 @@ async function showHistory(historyPath, name) {
167
168
  .slice(-DEFAULT_HISTORY_LIMIT)
168
169
  .reverse();
169
170
  if (records.length === 0) {
170
- return eventName
171
- ? `# Event History\n\nNo history found for event: ${eventName}`
172
- : "# Event History\n\nNo history found.";
171
+ return eventName ? `**事件历史**\n\n未找到事件 ${eventName} 的历史。` : "**事件历史**\n\n暂无事件历史。";
173
172
  }
174
- const suffix = eventName ? `: ${eventName}` : "";
175
- return `# Event History${suffix}\n\n${records.map(formatHistoryRecord).join("\n\n")}`;
173
+ const suffix = eventName ? ` · ${eventName}` : "";
174
+ return `**事件历史**${suffix}\n\n${records.map(formatHistoryRecord).join("\n\n")}`;
176
175
  }
177
176
  export async function handleEventsCommand(options) {
178
177
  let command;
@@ -197,6 +196,6 @@ export async function handleEventsCommand(options) {
197
196
  }
198
197
  catch (error) {
199
198
  const message = errorMessage(error);
200
- return `Could not ${command.action} events: ${message}`;
199
+ return `执行 /events ${command.action} 失败:${message}`;
201
200
  }
202
201
  }
@@ -102,8 +102,10 @@ export declare class EventsWatcher {
102
102
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
103
103
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
104
104
  *
105
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
106
- * from the event definition and only the task id is parsed out of the remainder.
105
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
106
+ * owning channel is taken from the event definition and the id is parsed with the same
107
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
108
+ * split that would cut a dotted task id short.
107
109
  */
108
110
  private orphanedOwnerReason;
109
111
  private execute;
@@ -4,11 +4,13 @@ import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
7
8
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
8
9
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
10
+ import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
+ import { isPlainObject } from "../shared/type-guards.js";
10
12
  import { parseTaskFrontmatter } from "../tasks/ledger.js";
11
- import { taskEventPrefix } from "../tasks/task-events.js";
13
+ import { parseTaskEventName } from "../tasks/task-events.js";
12
14
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
15
  // ============================================================================
14
16
  // EventsWatcher
@@ -20,13 +22,7 @@ const SCAN_CONCURRENCY = 4;
20
22
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
21
23
  const TEXT_PREVIEW_MAX_CHARS = 160;
22
24
  function truncateTextPreview(text) {
23
- const normalized = text.replace(/\s+/g, " ").trim();
24
- return normalized.length > TEXT_PREVIEW_MAX_CHARS
25
- ? `${normalized.slice(0, TEXT_PREVIEW_MAX_CHARS - 1)}…`
26
- : normalized;
27
- }
28
- function isRecord(value) {
29
- return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
30
26
  }
31
27
  function readRequiredString(data, field, filename) {
32
28
  const value = data[field];
@@ -38,7 +34,7 @@ function readRequiredString(data, field, filename) {
38
34
  function parsePreAction(data, filename) {
39
35
  if (!data.preAction)
40
36
  return undefined;
41
- if (!isRecord(data.preAction)) {
37
+ if (!isPlainObject(data.preAction)) {
42
38
  throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
43
39
  }
44
40
  const action = data.preAction;
@@ -61,7 +57,7 @@ function parsePreAction(data, filename) {
61
57
  }
62
58
  export function parseScheduledEventContent(content, filename) {
63
59
  const data = JSON.parse(content);
64
- if (!isRecord(data)) {
60
+ if (!isPlainObject(data)) {
65
61
  throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
66
62
  }
67
63
  const type = readRequiredString(data, "type", filename);
@@ -479,17 +475,16 @@ export class EventsWatcher {
479
475
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
480
476
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
481
477
  *
482
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
483
- * from the event definition and only the task id is parsed out of the remainder.
478
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
479
+ * owning channel is taken from the event definition and the id is parsed with the same
480
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
481
+ * split that would cut a dotted task id short.
484
482
  */
485
483
  async orphanedOwnerReason(filename, event) {
486
- const prefix = taskEventPrefix(event.channelId);
487
- const name = eventNameFromFilename(filename);
488
- if (!name.startsWith(prefix))
489
- return undefined;
490
- const taskId = name.slice(prefix.length).split(".")[0];
491
- if (!taskId)
484
+ const parsed = parseTaskEventName(eventNameFromFilename(filename), event.channelId);
485
+ if (!parsed)
492
486
  return undefined;
487
+ const taskId = parsed.id;
493
488
  const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
494
489
  let content;
495
490
  try {
@@ -655,7 +650,7 @@ export class EventsWatcher {
655
650
  }
656
651
  markInvalid(filename, message) {
657
652
  try {
658
- writeFileSync(this.getInvalidMarkerPath(filename), [`timestamp: ${new Date().toISOString()}`, `file: ${filename}`, "", message.trim()].join("\n"), "utf-8");
653
+ writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
659
654
  }
660
655
  catch (err) {
661
656
  log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
@@ -1,3 +1,16 @@
1
+ /**
2
+ * `/project` — the human control path for a channel's project scope (spec 043, D7). Mirrors
3
+ * `task-commands.ts`/`subagent-commands.ts`'s shape: pure-ish functions returning markdown, no
4
+ * bot/event coupling. Mutations never reach the model.
5
+ */
6
+ type ProjectCommand = {
7
+ action: "show";
8
+ } | {
9
+ action: "set";
10
+ path: string;
11
+ } | {
12
+ action: "reset";
13
+ };
1
14
  export interface HandleProjectCommandOptions {
2
15
  args: string;
3
16
  channelId: string;
@@ -13,4 +26,7 @@ export interface HandleProjectCommandOptions {
13
26
  * and let the next access rebuild it under the new scope (D4.2). Not called on any failure path. */
14
27
  onScopeChanged?: () => Promise<void> | void;
15
28
  }
29
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
30
+ export declare function parseProjectCommand(args: string): ProjectCommand;
16
31
  export declare function handleProjectCommand(options: HandleProjectCommandOptions): Promise<string>;
32
+ export {};