@oyasmi/pipiclaw 0.9.3-beta.6 → 0.9.4-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 (118) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.js +137 -61
  4. package/dist/agent/command-extension.js +47 -34
  5. package/dist/agent/job-manager.js +31 -11
  6. package/dist/agent/model-fallback.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.js +4 -1
  10. package/dist/agent/run-queue.js +7 -2
  11. package/dist/agent/session-adapter.js +1 -1
  12. package/dist/agent/session-events.js +17 -6
  13. package/dist/agent/session-resource-gate.js +3 -1
  14. package/dist/agent/status-render.d.ts +0 -1
  15. package/dist/agent/status-render.js +4 -16
  16. package/dist/agent/turn-error.d.ts +31 -0
  17. package/dist/agent/turn-error.js +68 -0
  18. package/dist/app-services.js +7 -4
  19. package/dist/channel/channel-index.d.ts +9 -2
  20. package/dist/channel/channel-index.js +29 -7
  21. package/dist/channel/project-scope-store.js +1 -1
  22. package/dist/commands/catalog.d.ts +21 -4
  23. package/dist/commands/catalog.js +88 -41
  24. package/dist/commands/reply-limits.d.ts +6 -0
  25. package/dist/commands/reply-limits.js +24 -0
  26. package/dist/events/event-commands.js +94 -44
  27. package/dist/events/event-validation.d.ts +13 -2
  28. package/dist/events/event-validation.js +17 -9
  29. package/dist/events/events.js +77 -32
  30. package/dist/executor.js +2 -2
  31. package/dist/log.d.ts +12 -2
  32. package/dist/log.js +26 -34
  33. package/dist/main.js +1 -1
  34. package/dist/memory/commands.js +29 -23
  35. package/dist/memory/lifecycle.js +26 -5
  36. package/dist/memory/maintenance-state.js +4 -1
  37. package/dist/memory/scheduler.js +3 -1
  38. package/dist/models/auth-cli.js +3 -2
  39. package/dist/paths.d.ts +2 -0
  40. package/dist/paths.js +9 -0
  41. package/dist/playbooks/agent-delegation.md +2 -2
  42. package/dist/runtime/app-home.d.ts +6 -0
  43. package/dist/runtime/app-home.js +21 -3
  44. package/dist/runtime/bootstrap.js +192 -64
  45. package/dist/runtime/channel-queue.js +1 -1
  46. package/dist/runtime/delivery.js +29 -15
  47. package/dist/runtime/dingtalk.js +96 -42
  48. package/dist/runtime/durable-dispatch.d.ts +27 -1
  49. package/dist/runtime/durable-dispatch.js +111 -3
  50. package/dist/runtime/project-commands.js +16 -15
  51. package/dist/runtime/proxy.js +4 -2
  52. package/dist/runtime/report-commands.js +1 -1
  53. package/dist/runtime/skill-commands.d.ts +1 -1
  54. package/dist/runtime/skill-commands.js +17 -10
  55. package/dist/runtime/subagent-commands.d.ts +5 -4
  56. package/dist/runtime/subagent-commands.js +116 -77
  57. package/dist/runtime/task-commands.d.ts +1 -1
  58. package/dist/runtime/task-commands.js +110 -64
  59. package/dist/runtime/task-driver.d.ts +6 -3
  60. package/dist/runtime/task-driver.js +57 -22
  61. package/dist/runtime/task-migration.d.ts +7 -2
  62. package/dist/runtime/task-migration.js +247 -61
  63. package/dist/runtime/task-spawn.js +12 -5
  64. package/dist/runtime/wake-coalescing.d.ts +18 -0
  65. package/dist/runtime/wake-coalescing.js +29 -0
  66. package/dist/security/block-message.d.ts +22 -1
  67. package/dist/security/block-message.js +66 -1
  68. package/dist/security/network.d.ts +2 -1
  69. package/dist/security/network.js +3 -2
  70. package/dist/security/path-guard-check.js +2 -2
  71. package/dist/settings.d.ts +3 -2
  72. package/dist/settings.js +4 -1
  73. package/dist/shared/format.d.ts +12 -0
  74. package/dist/shared/format.js +37 -0
  75. package/dist/shared/host-process.js +15 -3
  76. package/dist/shared/with-timeout.d.ts +3 -2
  77. package/dist/shared/with-timeout.js +14 -3
  78. package/dist/subagents/external/claude-code.js +23 -1
  79. package/dist/subagents/external/progress-tail.d.ts +17 -0
  80. package/dist/subagents/external/progress-tail.js +64 -17
  81. package/dist/subagents/external/run.d.ts +3 -0
  82. package/dist/subagents/external/run.js +21 -7
  83. package/dist/subagents/external/settlement.d.ts +3 -0
  84. package/dist/subagents/external/settlement.js +1 -1
  85. package/dist/subagents/runs.d.ts +21 -1
  86. package/dist/subagents/runs.js +137 -32
  87. package/dist/subagents/tool.d.ts +22 -15
  88. package/dist/subagents/tool.js +226 -32
  89. package/dist/subagents/workspace-summary.d.ts +16 -4
  90. package/dist/subagents/workspace-summary.js +74 -18
  91. package/dist/tasks/board.d.ts +8 -1
  92. package/dist/tasks/board.js +37 -2
  93. package/dist/tasks/frontmatter.d.ts +5 -0
  94. package/dist/tasks/frontmatter.js +8 -0
  95. package/dist/tasks/log.d.ts +11 -1
  96. package/dist/tasks/log.js +58 -2
  97. package/dist/tasks/store.d.ts +18 -1
  98. package/dist/tasks/store.js +61 -9
  99. package/dist/tasks/ticket.d.ts +3 -1
  100. package/dist/tasks/ticket.js +19 -1
  101. package/dist/tools/bash.js +2 -2
  102. package/dist/tools/index.d.ts +2 -0
  103. package/dist/tools/index.js +1 -0
  104. package/dist/tools/memory-manage.js +4 -1
  105. package/dist/tools/subagent-manage.d.ts +1 -1
  106. package/dist/tools/subagent-manage.js +16 -11
  107. package/dist/tools/task-manage/step-end.js +4 -1
  108. package/dist/tools/tool-details.d.ts +10 -2
  109. package/dist/tools/tool-details.js +39 -2
  110. package/dist/tui/cli.js +2 -2
  111. package/dist/tui/commands.js +4 -4
  112. package/dist/tui/pitui-frontend.js +1 -1
  113. package/dist/tui/renderer.js +3 -2
  114. package/dist/tui/turn-controller.d.ts +2 -0
  115. package/dist/tui/turn-controller.js +36 -21
  116. package/dist/usage/ledger.js +3 -1
  117. package/dist/usage/render.js +3 -1
  118. package/package.json +1 -1
@@ -14,3 +14,9 @@ export interface CapReplyResult {
14
14
  truncated: boolean;
15
15
  }
16
16
  export declare function capReply(text: string, options: CapReplyOptions): CapReplyResult;
17
+ /**
18
+ * Reshape a markdown file for a chat reply (rule 3/4): `#` headings become a bold line and
19
+ * indentation is dropped, since DingTalk keeps neither. Fenced code blocks pass through as-is.
20
+ * Used where a reply quotes a file the user wrote (a task contract, a skill body).
21
+ */
22
+ export declare function flattenMarkdownForChat(text: string): string;
@@ -15,3 +15,27 @@ export function capReply(text, options) {
15
15
  const head = text.slice(0, cut).trimEnd();
16
16
  return { text: `${head}\n\n(内容过长已截断;${options.nextStepHint})`, truncated: true };
17
17
  }
18
+ /**
19
+ * Reshape a markdown file for a chat reply (rule 3/4): `#` headings become a bold line and
20
+ * indentation is dropped, since DingTalk keeps neither. Fenced code blocks pass through as-is.
21
+ * Used where a reply quotes a file the user wrote (a task contract, a skill body).
22
+ */
23
+ export function flattenMarkdownForChat(text) {
24
+ const out = [];
25
+ let fenced = false;
26
+ for (const raw of text.split("\n")) {
27
+ if (/^\s*```/.test(raw)) {
28
+ fenced = !fenced;
29
+ out.push(raw.trim());
30
+ continue;
31
+ }
32
+ if (fenced) {
33
+ out.push(raw);
34
+ continue;
35
+ }
36
+ const trimmed = raw.trim();
37
+ const heading = /^#{1,6}\s+(.*)$/.exec(trimmed);
38
+ out.push(heading ? `**${heading[1]}**` : trimmed);
39
+ }
40
+ return out.join("\n").replace(/\n{3,}/g, "\n\n");
41
+ }
@@ -5,6 +5,7 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
5
5
  import { capReply } from "../commands/reply-limits.js";
6
6
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
7
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
+ import { EventDefinitionError, validateScheduledEvent } from "./event-validation.js";
8
9
  import { describeEventPayload, parseScheduledEventContent, } from "./events.js";
9
10
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
10
11
  const DEFAULT_HISTORY_LIMIT = 20;
@@ -37,7 +38,7 @@ export function parseEventsCommand(args) {
37
38
  throw new Error("用法:/events history [name]");
38
39
  return name ? { action, name } : { action };
39
40
  }
40
- throw new Error(`未知的 /events 动作:${action}`);
41
+ throw new Error(`未知子命令 \`${action}\`。`);
41
42
  }
42
43
  function eventsDir(workspaceDir) {
43
44
  return join(workspaceDir, "events");
@@ -56,60 +57,91 @@ function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
56
57
  return sharedClipText(text, maxChars, { headRatio: 1, omitHint: "...", collapseWhitespace: true });
57
58
  }
58
59
  function formatEventSummary(name, event) {
59
- const lines = [`**${name}**`, `- 类型:${event.type}`, `- channelId:${event.channelId}`];
60
+ const lines = [`**${name}**`, `- 类型:${event.type}`, `- 频道(channelId):${event.channelId}`];
60
61
  if (event.type === "one-shot") {
61
62
  lines.push(`- 触发时间:${event.at}`);
62
63
  }
63
64
  if (event.type === "periodic") {
64
- lines.push(`- schedule:${event.schedule}`);
65
+ lines.push(`- 时间表(schedule):${event.schedule}`);
65
66
  }
66
67
  lines.push(`- 内容:${clipText(describeEventPayload(event))}`);
67
68
  return lines.join("\n");
68
69
  }
70
+ /**
71
+ * Why a definition is invalid, in the user's terms (spec 053, D2). The error's own message is
72
+ * English text for the model (`event_manage`), so it is never pasted here.
73
+ */
74
+ const PROBLEM_TEXT = {
75
+ malformed: "文件不是有效的 JSON",
76
+ "missing-field": "缺少必填字段(type、channelId、at 或 schedule,以及 text 或 task 之一)",
77
+ payload: "text 和 task 必须恰好填一个",
78
+ "task-template": "task 模板无效",
79
+ "pre-action": "preAction 配置无效",
80
+ immediate: "不再支持 immediate 类型",
81
+ "unknown-type": "未知的事件类型",
82
+ "one-shot-time": "at 不是有效的时间",
83
+ "one-shot-too-soon": "at 距现在不足 2 分钟",
84
+ "one-shot-too-far": "at 超过约 24.8 天,更远的时间请改用 periodic",
85
+ "cron-invalid": "schedule 不是有效的 cron 表达式",
86
+ "cadence-too-frequent": "触发过于频繁(没有 preAction 时至少间隔 30 分钟,有 preAction 时至少 5 分钟)",
87
+ "pre-action-blocked": "preAction 命令被安全策略拦截",
88
+ };
89
+ function describeEventProblem(error, name) {
90
+ if (error instanceof EventDefinitionError)
91
+ return PROBLEM_TEXT[error.kind];
92
+ return `定义无效,用 \`/events show ${name}\` 查看`;
93
+ }
94
+ const EMPTY_EVENTS = "暂无定时事件。\n在对话里告诉我要定时做什么,我会创建事件。";
69
95
  async function listEvents(workspaceDir) {
70
96
  const dir = eventsDir(workspaceDir);
71
- if (!existsSync(dir)) {
72
- return "**定时事件**\n\n没有找到 events 目录。";
73
- }
97
+ if (!existsSync(dir))
98
+ return EMPTY_EVENTS;
74
99
  const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".json")).sort();
75
- if (filenames.length === 0) {
76
- return "**定时事件**\n\n暂无事件文件。";
77
- }
100
+ if (filenames.length === 0)
101
+ return EMPTY_EVENTS;
78
102
  const blocks = [];
79
103
  for (const filename of filenames) {
80
104
  const eventPath = join(dir, filename);
81
105
  const name = eventNameFromFilename(filename);
82
106
  try {
83
107
  const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
108
+ // The same definition rules the watcher applies, so "listed as fine" means "will run".
109
+ // The lead-time rule is creation-only (an overdue one-shot is a legitimate recovery).
110
+ validateScheduledEvent(event, { enforceOneShotLead: false });
84
111
  blocks.push(formatEventSummary(name, event));
85
112
  }
86
113
  catch (error) {
87
- const message = errorMessage(error);
88
- blocks.push(`**${name}**\n- ⚠ 无效:${message}`);
114
+ blocks.push(`**${name}**\n- ⚠️ 无效:${describeEventProblem(error, name)}`);
89
115
  }
90
116
  }
91
117
  return capReply(`**定时事件**\n\n${blocks.join("\n\n")}`, {
92
118
  nextStepHint: "用 `/events show <name>` 查看单个事件",
93
119
  }).text;
94
120
  }
121
+ function eventNotFound(eventName) {
122
+ return `未找到事件 \`${eventName}\`。用 \`/events list\` 查看。`;
123
+ }
95
124
  async function showEvent(workspaceDir, name) {
96
125
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
97
- if (!existsSync(eventPath)) {
98
- return `找不到事件:${eventName}`;
99
- }
126
+ if (!existsSync(eventPath))
127
+ return eventNotFound(eventName);
100
128
  const raw = await readFile(eventPath, "utf-8");
101
- const parsed = JSON.parse(raw);
102
- return `**事件 ${eventName}**
103
-
104
- \`\`\`json
105
- ${JSON.stringify(parsed, null, 2)}
106
- \`\`\``;
129
+ let body;
130
+ try {
131
+ body = JSON.stringify(JSON.parse(raw), null, 2);
132
+ }
133
+ catch {
134
+ // Show the bytes as they are: an unparseable file is exactly the case the user needs to see.
135
+ body = raw;
136
+ }
137
+ return capReply(`**事件 ${eventName}**\n\n\`\`\`json\n${body}\n\`\`\``, {
138
+ nextStepHint: `完整文件在 \`${eventPath}\``,
139
+ }).text;
107
140
  }
108
141
  async function deleteEvent(workspaceDir, name) {
109
142
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
110
- if (!existsSync(eventPath)) {
111
- return `找不到事件:${eventName}`;
112
- }
143
+ if (!existsSync(eventPath))
144
+ return eventNotFound(eventName);
113
145
  // Read before deleting so the reply carries what was removed (review 2026-08-24 §3.4):
114
146
  // an accidental delete stays recoverable from chat history instead of a bare confirmation.
115
147
  let summary;
@@ -121,7 +153,7 @@ async function deleteEvent(workspaceDir, name) {
121
153
  // Unparseable content is still safe to delete; just skip the summary.
122
154
  }
123
155
  await unlink(eventPath);
124
- return summary ? `已删除事件:\n\n${summary}` : `已删除事件:${eventName}`;
156
+ return summary ? `已删除事件:\n\n${summary}` : `已删除事件 \`${eventName}\`。`;
125
157
  }
126
158
  function parseHistoryLine(line) {
127
159
  try {
@@ -135,28 +167,45 @@ function parseHistoryLine(line) {
135
167
  return null;
136
168
  }
137
169
  }
170
+ const HISTORY_ACTION = {
171
+ loaded: "已加载",
172
+ scheduled: "已排程",
173
+ triggered: "已触发",
174
+ skipped: "已跳过",
175
+ enqueued: "已送达频道",
176
+ queue_full: "频道队列已满",
177
+ deleted: "已删除",
178
+ invalid: "无效",
179
+ pre_action_started: "preAction 开始",
180
+ pre_action_passed: "preAction 通过",
181
+ pre_action_blocked: "preAction 未通过",
182
+ pre_action_failed: "preAction 出错",
183
+ cancelled: "已取消",
184
+ };
185
+ const HISTORY_RESULT = { ok: "成功", error: "失败", skipped: "跳过" };
186
+ /** `2026-10-11T14:02:33.000+08:00` → `10-11 14:02`. */
187
+ function minuteStamp(ts) {
188
+ const match = /^\d{4}-(\d{2}-\d{2})T(\d{2}:\d{2})/.exec(ts);
189
+ return match ? `${match[1]} ${match[2]}` : ts;
190
+ }
191
+ /** One flat bullet per record; the operator detail (`reason`) is quoted as-is, it is a log entry. */
138
192
  function formatHistoryRecord(record) {
139
- const details = [];
140
- if (record.channelId)
141
- details.push(`- channelId:${record.channelId}`);
142
- if (record.schedule)
143
- details.push(`- schedule:${record.schedule}`);
144
- if (record.at)
145
- details.push(`- 触发时间:${record.at}`);
193
+ const action = HISTORY_ACTION[record.action] ?? record.action;
194
+ const result = HISTORY_RESULT[record.result] ?? record.result;
195
+ const bits = [`${minuteStamp(record.ts)} ${record.eventName}`, `${action}(${result})`];
146
196
  if (record.nextRunAt)
147
- details.push(`- 下次运行:${record.nextRunAt}`);
197
+ bits.push(`下次 ${minuteStamp(record.nextRunAt)}`);
148
198
  if (record.reason)
149
- details.push(`- 原因:${record.reason}`);
150
- if (record.textPreview)
151
- details.push(`- 内容:${clipText(record.textPreview)}`);
152
- const header = `**${record.ts} ${record.eventName}** ${record.action} · ${record.result}`;
153
- return details.length > 0 ? `${header}\n${details.join("\n")}` : header;
199
+ bits.push(`详情:\`${clipText(record.reason.replace(/`/g, "'"))}\``);
200
+ return `- ${bits.join(" · ")}`;
154
201
  }
155
202
  async function showHistory(historyPath, name) {
156
203
  const eventName = name ? normalizeEventName(name) : undefined;
157
- if (!existsSync(historyPath)) {
158
- return "**事件历史**\n\n暂无事件历史。";
159
- }
204
+ const empty = eventName
205
+ ? `暂无事件 \`${eventName}\` 的触发记录。\n事件触发后会记录在这里。`
206
+ : "暂无事件触发记录。\n事件触发后会记录在这里。";
207
+ if (!existsSync(historyPath))
208
+ return empty;
160
209
  const raw = await readFile(historyPath, "utf-8");
161
210
  const records = raw
162
211
  .split("\n")
@@ -167,11 +216,12 @@ async function showHistory(historyPath, name) {
167
216
  .filter((record) => !eventName || record.eventName === eventName)
168
217
  .slice(-DEFAULT_HISTORY_LIMIT)
169
218
  .reverse();
170
- if (records.length === 0) {
171
- return eventName ? `**事件历史**\n\n未找到事件 ${eventName} 的历史。` : "**事件历史**\n\n暂无事件历史。";
172
- }
219
+ if (records.length === 0)
220
+ return empty;
173
221
  const suffix = eventName ? ` · ${eventName}` : "";
174
- return `**事件历史**${suffix}\n\n${records.map(formatHistoryRecord).join("\n\n")}`;
222
+ return capReply(`**事件历史**${suffix}(最近 ${records.length} 条)\n\n${records.map(formatHistoryRecord).join("\n")}`, {
223
+ nextStepHint: `用 \`/events history <name>\` 只看一个事件;完整记录在 \`${historyPath}\``,
224
+ }).text;
175
225
  }
176
226
  export async function handleEventsCommand(options) {
177
227
  let command;
@@ -24,10 +24,21 @@ export declare const MIN_PERIODIC_INTERVAL_MS: number;
24
24
  export declare const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS: number;
25
25
  /** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
26
26
  export declare const MAX_EVENT_FILES = 50;
27
- export declare class EventValidationError extends Error {
27
+ /**
28
+ * What is wrong with an event definition, as data (spec 053, D2). The error `message` is English
29
+ * and written for the model (`event_manage` returns it as a recoverable rejection); `/events list`
30
+ * renders `kind` in the user's terms instead of pasting that text into the chat.
31
+ */
32
+ export type EventProblemKind = "malformed" | "missing-field" | "payload" | "task-template" | "pre-action" | "immediate" | "unknown-type" | "one-shot-time" | "one-shot-too-soon" | "one-shot-too-far" | "cron-invalid" | "cadence-too-frequent" | "pre-action-blocked";
33
+ /** A definition the file parser rejects. Kept distinct from `EventValidationError`, which the tool treats as model-fixable. */
34
+ export declare class EventDefinitionError extends Error {
35
+ readonly kind: EventProblemKind;
36
+ constructor(kind: EventProblemKind, message: string);
37
+ }
38
+ export declare class EventValidationError extends EventDefinitionError {
28
39
  /** Whether the model can usefully retry with a corrected definition. */
29
40
  readonly recoverable: boolean;
30
- constructor(message: string, recoverable?: boolean);
41
+ constructor(kind: EventProblemKind, message: string, recoverable?: boolean);
31
42
  }
32
43
  export declare function validateOneShotLead(event: ScheduledEvent & {
33
44
  type: "one-shot";
@@ -26,9 +26,17 @@ export const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
26
26
  export const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
27
27
  /** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
28
28
  export const MAX_EVENT_FILES = 50;
29
- export class EventValidationError extends Error {
30
- constructor(message, recoverable = true) {
29
+ /** A definition the file parser rejects. Kept distinct from `EventValidationError`, which the tool treats as model-fixable. */
30
+ export class EventDefinitionError extends Error {
31
+ constructor(kind, message) {
31
32
  super(message);
33
+ this.kind = kind;
34
+ this.name = "EventDefinitionError";
35
+ }
36
+ }
37
+ export class EventValidationError extends EventDefinitionError {
38
+ constructor(kind, message, recoverable = true) {
39
+ super(kind, message);
32
40
  this.name = "EventValidationError";
33
41
  this.recoverable = recoverable;
34
42
  }
@@ -36,19 +44,19 @@ export class EventValidationError extends Error {
36
44
  export function validateOneShotLead(event, now = Date.now()) {
37
45
  const atTime = parseLocalTime(event.at);
38
46
  if (atTime === undefined) {
39
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
47
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
40
48
  }
41
49
  if (atTime < now + MIN_ONE_SHOT_LEAD_MS) {
42
- throw new EventValidationError("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
50
+ throw new EventValidationError("one-shot-too-soon", "one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
43
51
  }
44
52
  }
45
53
  function validateOneShotMaximumDelay(event, now = Date.now()) {
46
54
  const atTime = parseLocalTime(event.at);
47
55
  if (atTime === undefined) {
48
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
56
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
49
57
  }
50
58
  if (atTime - now > MAX_ONE_SHOT_DELAY_MS) {
51
- throw new EventValidationError("one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
59
+ throw new EventValidationError("one-shot-too-far", "one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
52
60
  }
53
61
  }
54
62
  export function validatePeriodicCadence(event) {
@@ -59,7 +67,7 @@ export function validatePeriodicCadence(event) {
59
67
  cron.stop();
60
68
  }
61
69
  catch (error) {
62
- throw new EventValidationError(`Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
70
+ throw new EventValidationError("cron-invalid", `Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
63
71
  }
64
72
  // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
65
73
  // without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
@@ -68,7 +76,7 @@ export function validatePeriodicCadence(event) {
68
76
  // Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
69
77
  for (let i = 1; i < runs.length; i++) {
70
78
  if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
71
- throw new EventValidationError(`periodic events must fire no more often than every ${floorMinutes} minutes` +
79
+ throw new EventValidationError("cadence-too-frequent", `periodic events must fire no more often than every ${floorMinutes} minutes` +
72
80
  `${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
73
81
  }
74
82
  }
@@ -78,7 +86,7 @@ export function validatePreActionCommand(event, commandGuardConfig) {
78
86
  return;
79
87
  const result = guardCommand(event.preAction.command, commandGuardConfig);
80
88
  if (!result.allowed) {
81
- throw new EventValidationError(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
89
+ throw new EventValidationError("pre-action-blocked", `preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
82
90
  }
83
91
  }
84
92
  /** Apply every admission rule that depends only on the definition itself. */
@@ -10,7 +10,7 @@ import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
10
10
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
11
  import { isPlainObject } from "../shared/type-guards.js";
12
12
  import { validateTaskContractInput } from "../tasks/contract-input.js";
13
- import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
+ import { EventDefinitionError, MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent, } from "./event-validation.js";
14
14
  // ============================================================================
15
15
  // EventsWatcher
16
16
  // ============================================================================
@@ -30,7 +30,7 @@ function truncateTextPreview(text) {
30
30
  function readRequiredString(data, field, filename) {
31
31
  const value = data[field];
32
32
  if (typeof value !== "string" || value.trim().length === 0) {
33
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
33
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
34
34
  }
35
35
  return value;
36
36
  }
@@ -39,7 +39,7 @@ function parsePayload(data, filename) {
39
39
  const hasText = typeof data.text === "string" && data.text.trim().length > 0;
40
40
  const hasTask = data.task !== undefined;
41
41
  if (hasText === hasTask) {
42
- throw new Error(`An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
42
+ throw new EventDefinitionError("payload", `An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
43
43
  }
44
44
  if (hasText)
45
45
  return { text: data.text };
@@ -47,25 +47,25 @@ function parsePayload(data, filename) {
47
47
  return { task: validateTaskContractInput(data.task) };
48
48
  }
49
49
  catch (error) {
50
- throw new Error(`Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
50
+ throw new EventDefinitionError("task-template", `Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
51
51
  }
52
52
  }
53
53
  function parsePreAction(data, filename) {
54
54
  if (!data.preAction)
55
55
  return undefined;
56
56
  if (!isPlainObject(data.preAction)) {
57
- throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
57
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction' field in ${filename}, expected an object`);
58
58
  }
59
59
  const action = data.preAction;
60
60
  if (action.type !== "bash") {
61
- throw new Error(`Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
61
+ throw new EventDefinitionError("pre-action", `Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
62
62
  }
63
63
  if (typeof action.command !== "string" || action.command.trim().length === 0) {
64
- throw new Error(`Missing or empty 'preAction.command' in ${filename}`);
64
+ throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
65
65
  }
66
66
  if (action.timeout !== undefined) {
67
67
  if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
68
- throw new Error(`Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
68
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
69
69
  }
70
70
  }
71
71
  return {
@@ -75,9 +75,15 @@ function parsePreAction(data, filename) {
75
75
  };
76
76
  }
77
77
  export function parseScheduledEventContent(content, filename) {
78
- const data = JSON.parse(content);
78
+ let data;
79
+ try {
80
+ data = JSON.parse(content);
81
+ }
82
+ catch (error) {
83
+ throw new EventDefinitionError("malformed", `Invalid JSON in ${filename}: ${errorMessage(error)}`);
84
+ }
79
85
  if (!isPlainObject(data)) {
80
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
86
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
81
87
  }
82
88
  const type = readRequiredString(data, "type", filename);
83
89
  const channelId = readRequiredString(data, "channelId", filename);
@@ -89,17 +95,17 @@ export function parseScheduledEventContent(content, filename) {
89
95
  // one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
90
96
  // enforced, since the events directory is agent-writable.
91
97
  case "immediate":
92
- throw new Error(`Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
98
+ throw new EventDefinitionError("immediate", `Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
93
99
  "or schedule a one-shot at least 2 minutes out via event_manage.");
94
100
  case "one-shot": {
95
101
  if (typeof data.at !== "string" || data.at.trim().length === 0) {
96
- throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
102
+ throw new EventDefinitionError("missing-field", `Missing 'at' field for one-shot event in ${filename}`);
97
103
  }
98
104
  return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
99
105
  }
100
106
  case "periodic": {
101
107
  if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
102
- throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
108
+ throw new EventDefinitionError("missing-field", `Missing 'schedule' field for periodic event in ${filename}`);
103
109
  }
104
110
  return {
105
111
  type,
@@ -110,7 +116,7 @@ export function parseScheduledEventContent(content, filename) {
110
116
  };
111
117
  }
112
118
  default:
113
- throw new Error(`Unknown event type '${type}' in ${filename}`);
119
+ throw new EventDefinitionError("unknown-type", `Unknown event type '${type}' in ${filename}`);
114
120
  }
115
121
  }
116
122
  /**
@@ -208,7 +214,7 @@ export class EventsWatcher {
208
214
  chmodSync(this.options.historyPath, 0o600);
209
215
  }
210
216
  catch (err) {
211
- log.logWarning("Failed to initialize event history file", String(err));
217
+ log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
212
218
  }
213
219
  }
214
220
  appendHistory(record) {
@@ -223,7 +229,7 @@ export class EventsWatcher {
223
229
  ...rest,
224
230
  };
225
231
  if (!this.historyAppender?.tryAppend(fullRecord, "critical")) {
226
- log.logWarning("Failed to queue event history", "Retry after pending event history writes drain");
232
+ log.logWarn("events.history.queue_full", "Event history write dropped while earlier writes drain");
227
233
  }
228
234
  }
229
235
  appendEventHistory(filename, event, action, result, extra = {}) {
@@ -255,7 +261,7 @@ export class EventsWatcher {
255
261
  files = readdirSync(this.eventsDir).filter((f) => f.endsWith(".json"));
256
262
  }
257
263
  catch (err) {
258
- log.logWarning("Failed to read events directory", String(err));
264
+ log.logWarn("events.dir.read_failed", "Events directory read failed", { reason: String(err) });
259
265
  return;
260
266
  }
261
267
  for (let offset = 0; this.started && offset < files.length; offset += SCAN_CONCURRENCY) {
@@ -264,7 +270,10 @@ export class EventsWatcher {
264
270
  await this.handleFile(filename);
265
271
  }
266
272
  catch (err) {
267
- log.logWarning(`Failed to restore event file: ${filename}`, errorMessage(err));
273
+ log.logWarn("events.file.restore_failed", "Event file restore failed", {
274
+ reason: errorMessage(err),
275
+ fields: { file: filename },
276
+ });
268
277
  }
269
278
  }));
270
279
  }
@@ -290,7 +299,10 @@ export class EventsWatcher {
290
299
  */
291
300
  handleFileSafely(filename) {
292
301
  void this.handleFile(filename).catch((err) => {
293
- log.logWarning(`Failed to load event file: ${filename}`, errorMessage(err));
302
+ log.logWarn("events.file.load_failed", "Event file load failed", {
303
+ reason: errorMessage(err),
304
+ fields: { file: filename },
305
+ });
294
306
  });
295
307
  }
296
308
  handleDelete(filename) {
@@ -348,7 +360,10 @@ export class EventsWatcher {
348
360
  }
349
361
  }
350
362
  if (!event) {
351
- log.logWarning(`Failed to parse event file after ${MAX_RETRIES} retries: ${filename}`, lastError?.message);
363
+ log.logWarn("events.file.parse_failed", "Event file parse failed", {
364
+ reason: lastError?.message,
365
+ fields: { file: filename, attempts: MAX_RETRIES },
366
+ });
352
367
  this.appendHistory({
353
368
  filename,
354
369
  eventType: "unknown",
@@ -361,7 +376,7 @@ export class EventsWatcher {
361
376
  }
362
377
  const rejection = this.admissionFailure(filename, event);
363
378
  if (rejection) {
364
- log.logWarning(`Rejected event file: ${filename}`, rejection);
379
+ log.logWarn("events.file.rejected", "Event file rejected", { reason: rejection, fields: { file: filename } });
365
380
  this.appendEventHistory(filename, event, "invalid", "error", { reason: rejection });
366
381
  this.markInvalid(filename, rejection);
367
382
  return;
@@ -416,7 +431,9 @@ export class EventsWatcher {
416
431
  const atTime = parseLocalTime(event.at);
417
432
  const now = Date.now();
418
433
  if (atTime === undefined) {
419
- log.logWarning(`Invalid one-shot time for ${filename}: ${event.at}`);
434
+ log.logWarn("events.oneshot.invalid_time", "One-shot event time invalid", {
435
+ fields: { file: filename, at: event.at },
436
+ });
420
437
  this.appendEventHistory(filename, event, "invalid", "error", { reason: `Invalid one-shot time: ${event.at}` });
421
438
  this.markInvalid(filename, `Invalid one-shot time: ${event.at}`);
422
439
  return;
@@ -431,7 +448,9 @@ export class EventsWatcher {
431
448
  }
432
449
  const delay = atTime - now;
433
450
  if (delay > MAX_ONE_SHOT_DELAY_MS) {
434
- log.logWarning(`One-shot event exceeds maximum supported delay for ${filename}: ${event.at}. Use a periodic cron event instead.`);
451
+ log.logWarn("events.oneshot.too_far", "One-shot event exceeds the maximum delay; use a periodic event", {
452
+ fields: { file: filename, at: event.at },
453
+ });
435
454
  this.appendEventHistory(filename, event, "skipped", "skipped", {
436
455
  reason: `One-shot event exceeds maximum supported delay: ${event.at}`,
437
456
  });
@@ -450,7 +469,10 @@ export class EventsWatcher {
450
469
  await this.execute(filename, event);
451
470
  }
452
471
  catch (err) {
453
- log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
472
+ log.logWarn("events.oneshot.failed", "One-shot event execution failed", {
473
+ reason: String(err),
474
+ fields: { file: filename },
475
+ });
454
476
  this.appendEventHistory(filename, event, "skipped", "error", {
455
477
  reason: errorMessage(err),
456
478
  });
@@ -468,7 +490,10 @@ export class EventsWatcher {
468
490
  await this.execute(filename, event, false, cron.currentRun() ?? new Date());
469
491
  }
470
492
  catch (err) {
471
- log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
493
+ log.logWarn("events.periodic.failed", "Periodic event execution failed", {
494
+ reason: String(err),
495
+ fields: { file: filename },
496
+ });
472
497
  this.appendEventHistory(filename, event, "skipped", "error", {
473
498
  reason: errorMessage(err),
474
499
  });
@@ -480,7 +505,10 @@ export class EventsWatcher {
480
505
  this.appendEventHistory(filename, event, "scheduled", "ok", next ? { nextRunAt: formatLocalTime(next) } : {});
481
506
  }
482
507
  catch (err) {
483
- log.logWarning(`Invalid cron schedule for ${filename}: ${event.schedule}`, String(err));
508
+ log.logWarn("events.periodic.invalid_cron", "Periodic event cron invalid", {
509
+ reason: String(err),
510
+ fields: { file: filename, schedule: event.schedule },
511
+ });
484
512
  this.appendEventHistory(filename, event, "invalid", "error", {
485
513
  reason: `Invalid cron schedule: ${event.schedule}\n${String(err)}`,
486
514
  });
@@ -572,7 +600,9 @@ export class EventsWatcher {
572
600
  // next tick, so just warn. One-shot/immediate events would otherwise be
573
601
  // GC'd as "past" with no trace, so leave a visible error marker (and keep
574
602
  // the source file) making the loss auditable rather than a silent hole.
575
- log.logWarning(`Event queue full, could not enqueue: ${filename}`);
603
+ log.logWarn("events.enqueue.queue_full", "Event not enqueued: channel queue full", {
604
+ fields: { file: filename },
605
+ });
576
606
  this.appendEventHistory(filename, event, "queue_full", "error", {
577
607
  reason: "channel queue full",
578
608
  queue: { accepted: false },
@@ -612,7 +642,10 @@ export class EventsWatcher {
612
642
  }
613
643
  catch (err) {
614
644
  const reason = errorMessage(err);
615
- log.logWarning(`Could not spawn a task for event: ${filename}`, reason);
645
+ log.logWarn("events.task_spawn.failed", "Task spawn for event failed", {
646
+ reason: reason,
647
+ fields: { file: filename },
648
+ });
616
649
  this.appendEventHistory(filename, event, "skipped", "error", { reason });
617
650
  if (deleteAfter) {
618
651
  this.markInvalid(filename, `Could not create the task instance at ${new Date().toISOString()}: ${reason}`);
@@ -624,7 +657,10 @@ export class EventsWatcher {
624
657
  if (this.commandGuardConfig?.enabled) {
625
658
  const guardResult = guardCommand(action.command, this.commandGuardConfig);
626
659
  if (!guardResult.allowed) {
627
- log.logWarning(`Pre-action command blocked by guard for ${filename}: ${guardResult.reason}`);
660
+ log.logWarn("events.preaction.blocked", "Event pre-action blocked by guard", {
661
+ reason: guardResult.reason,
662
+ fields: { file: filename },
663
+ });
628
664
  throw new EventPreActionError("blocked", `guard: ${guardResult.reason}`, {
629
665
  durationMs: Date.now() - startedAt,
630
666
  });
@@ -656,7 +692,10 @@ export class EventsWatcher {
656
692
  }
657
693
  catch (err) {
658
694
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
659
- log.logWarning(`Failed to delete event file: ${filename}`, String(err));
695
+ log.logWarn("events.file.delete_failed", "Event file delete failed", {
696
+ reason: String(err),
697
+ fields: { file: filename },
698
+ });
660
699
  }
661
700
  }
662
701
  this.clearInvalidMarker(filename);
@@ -676,7 +715,10 @@ export class EventsWatcher {
676
715
  writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
677
716
  }
678
717
  catch (err) {
679
- log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
718
+ log.logWarn("events.marker.write_failed", "Event error marker write failed", {
719
+ reason: String(err),
720
+ fields: { file: filename },
721
+ });
680
722
  }
681
723
  this.knownFiles.add(filename);
682
724
  }
@@ -687,7 +729,10 @@ export class EventsWatcher {
687
729
  }
688
730
  catch (err) {
689
731
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
690
- log.logWarning(`Failed to delete event error marker: ${filename}`, String(err));
732
+ log.logWarn("events.marker.delete_failed", "Event error marker delete failed", {
733
+ reason: String(err),
734
+ fields: { file: filename },
735
+ });
691
736
  }
692
737
  }
693
738
  }