@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.3

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 (79) hide show
  1. package/dist/agent/job-manager.d.ts +9 -0
  2. package/dist/agent/job-manager.js +20 -6
  3. package/dist/agent/prompt/builder.d.ts +1 -1
  4. package/dist/agent/prompt/builder.js +1 -1
  5. package/dist/agent/prompt/sections.js +3 -3
  6. package/dist/executor.d.ts +5 -1
  7. package/dist/executor.js +35 -5
  8. package/dist/file-store.d.ts +4 -1
  9. package/dist/file-store.js +5 -0
  10. package/dist/memory/journal.d.ts +13 -0
  11. package/dist/memory/journal.js +47 -4
  12. package/dist/memory/search.js +13 -6
  13. package/dist/memory/session-corpus.d.ts +11 -0
  14. package/dist/memory/session-corpus.js +15 -4
  15. package/dist/memory/session-search.d.ts +3 -0
  16. package/dist/memory/session-search.js +45 -8
  17. package/dist/memory/store.d.ts +9 -0
  18. package/dist/memory/store.js +25 -2
  19. package/dist/playbooks/agent-delegation.md +35 -76
  20. package/dist/playbooks/background-jobs.md +14 -16
  21. package/dist/playbooks/event-scheduling.md +20 -25
  22. package/dist/playbooks/memory-and-learning.md +28 -61
  23. package/dist/playbooks/outbound-media.md +10 -12
  24. package/dist/playbooks/runtime-orientation.md +34 -53
  25. package/dist/playbooks/task-loop.md +49 -69
  26. package/dist/runtime/bootstrap.js +25 -11
  27. package/dist/security/path-guard-filter.d.ts +22 -0
  28. package/dist/security/path-guard-filter.js +35 -0
  29. package/dist/subagents/discovery.d.ts +2 -3
  30. package/dist/subagents/discovery.js +3 -1
  31. package/dist/subagents/tool.d.ts +6 -0
  32. package/dist/subagents/tool.js +10 -2
  33. package/dist/tasks/brief.d.ts +1 -1
  34. package/dist/tasks/brief.js +11 -2
  35. package/dist/tasks/log.d.ts +4 -0
  36. package/dist/tasks/log.js +13 -1
  37. package/dist/tools/bash.d.ts +13 -0
  38. package/dist/tools/bash.js +123 -20
  39. package/dist/tools/edit.js +36 -5
  40. package/dist/tools/event-manage.d.ts +25 -4
  41. package/dist/tools/event-manage.js +81 -33
  42. package/dist/tools/glob.js +57 -4
  43. package/dist/tools/grep.d.ts +2 -0
  44. package/dist/tools/grep.js +187 -14
  45. package/dist/tools/job.js +16 -4
  46. package/dist/tools/memory-manage.js +80 -41
  47. package/dist/tools/read.js +42 -5
  48. package/dist/tools/registry.d.ts +6 -0
  49. package/dist/tools/registry.js +4 -1
  50. package/dist/tools/send-media.js +6 -4
  51. package/dist/tools/session-search.js +4 -1
  52. package/dist/tools/skill.d.ts +2 -0
  53. package/dist/tools/skill.js +12 -0
  54. package/dist/tools/subagent-manage.js +1 -1
  55. package/dist/tools/subagent-tool-names.d.ts +11 -0
  56. package/dist/tools/subagent-tool-names.js +19 -0
  57. package/dist/tools/task-manage/log-view.js +6 -3
  58. package/dist/tools/task-manage/schema.d.ts +6 -6
  59. package/dist/tools/task-manage/schema.js +5 -12
  60. package/dist/tools/task-manage/shared.js +16 -2
  61. package/dist/tools/task-manage/step-end.js +22 -5
  62. package/dist/tools/task-manage.js +9 -1
  63. package/dist/tools/web-cache.d.ts +11 -3
  64. package/dist/tools/web-cache.js +26 -8
  65. package/dist/tools/web-fetch.d.ts +1 -0
  66. package/dist/tools/web-fetch.js +68 -15
  67. package/dist/tools/write.js +3 -0
  68. package/dist/web/fetch.d.ts +5 -0
  69. package/dist/web/fetch.js +36 -1
  70. package/examples/sub-agents/README.md +14 -4
  71. package/examples/sub-agents/builder-hard.md +12 -34
  72. package/examples/sub-agents/builder.md +11 -31
  73. package/examples/sub-agents/explorer.md +10 -16
  74. package/examples/sub-agents/git-committer.md +15 -20
  75. package/examples/sub-agents/planner.md +11 -21
  76. package/examples/sub-agents/reviewer.md +10 -31
  77. package/examples/sub-agents/verifier.md +12 -27
  78. package/examples/sub-agents/worker.md +11 -35
  79. package/package.json +7 -3
@@ -1,7 +1,9 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { unlink } from "node:fs/promises";
2
+ import { mkdir, open, readdir, stat, unlink } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
3
5
  import { Type } from "typebox";
4
- import { CommandTerminatedError } from "../executor.js";
6
+ import { CommandTerminatedError, EXECUTOR_SHELL_IS_BASH } from "../executor.js";
5
7
  import { formatBlockMessage } from "../security/block-message.js";
6
8
  import { guardCommand } from "../security/command-guard.js";
7
9
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
@@ -17,14 +19,52 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "
17
19
  * Callers that legitimately need longer must pass an explicit `timeout`.
18
20
  */
19
21
  export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
22
+ /** Subdirectory of the channel dir where full bash/job output spills live. */
23
+ const BASH_LOG_DIR_NAME = "logs";
24
+ /** Spill files kept per channel before the oldest are pruned on the next tool build. */
25
+ const BASH_LOG_RETENTION = 40;
26
+ /** Bytes read back from the spill file when the in-memory capture was truncated (D2.3). */
27
+ const TAIL_FROM_SPILL_BYTES = DEFAULT_MAX_BYTES * 4;
20
28
  /**
21
- * Generate a unique spill file path for full bash output. It lives under `/tmp` so the
22
- * path we report back is reachable by the same `read`/`bash` tools the model uses to
23
- * open it.
29
+ * Where the "full output" spill file for a command goes. Under `<channelDir>/logs/` on the main
30
+ * path, which the model's `read` can open under both `boundary: "project"` and `unbounded` — a
31
+ * `/tmp/...` pointer is unreadable under `boundary: "project"` (fix plan §2.2). Sub-agents get no
32
+ * channel dir, so they fall back to the OS temp dir as before.
24
33
  */
25
- function getSpillFilePath() {
34
+ function getSpillFilePath(channelDir) {
26
35
  const id = randomBytes(8).toString("hex");
27
- return `/tmp/pipiclaw-bash-${id}.log`;
36
+ const dir = channelDir ? join(channelDir, BASH_LOG_DIR_NAME) : tmpdir();
37
+ return join(dir, `pipiclaw-bash-${id}.log`);
38
+ }
39
+ /** Best-effort: keep the channel's `logs/` dir from growing without bound. */
40
+ async function pruneBashLogs(channelDir) {
41
+ const dir = join(channelDir, BASH_LOG_DIR_NAME);
42
+ let names;
43
+ try {
44
+ names = (await readdir(dir)).filter((n) => n.startsWith("pipiclaw-bash-") && n.endsWith(".log"));
45
+ }
46
+ catch {
47
+ return;
48
+ }
49
+ if (names.length <= BASH_LOG_RETENTION)
50
+ return;
51
+ const withMtime = await Promise.all(names.map(async (n) => ({ n, m: (await stat(join(dir, n)).catch(() => null))?.mtimeMs ?? 0 })));
52
+ withMtime.sort((a, b) => b.m - a.m);
53
+ await Promise.all(withMtime.slice(BASH_LOG_RETENTION).map(({ n }) => unlink(join(dir, n)).catch(() => undefined)));
54
+ }
55
+ /** Read the last `maxBytes` of a file as UTF-8 text (used when the in-memory capture is only a head). */
56
+ async function readFileTail(path, maxBytes) {
57
+ const size = (await stat(path)).size;
58
+ const start = Math.max(0, size - maxBytes);
59
+ const fh = await open(path, "r");
60
+ try {
61
+ const buf = Buffer.alloc(size - start);
62
+ await fh.read(buf, 0, buf.length, start);
63
+ return buf.toString("utf-8");
64
+ }
65
+ finally {
66
+ await fh.close();
67
+ }
28
68
  }
29
69
  const bashSchema = Type.Object({
30
70
  command: Type.String({ description: "Bash command to execute" }),
@@ -42,6 +82,12 @@ const bashSchema = Type.Object({
42
82
  description: "For async jobs: the task this job advances, so the completion wake lands in that context.",
43
83
  })),
44
84
  });
85
+ /** Schema shown when background execution is unavailable (sub-agent path): the async trio is
86
+ * dropped so the model is never offered a parameter its context cannot honor (fix plan §3.2). */
87
+ const bashSchemaNoJobs = Type.Omit(bashSchema, ["async", "notify", "taskId"]);
88
+ /** Schema shown inside a task session: `taskId` is bound by the runtime, so the model never
89
+ * supplies (or misfills) it (fix plan §3.3). */
90
+ const bashSchemaBoundTask = Type.Omit(bashSchema, ["taskId"]);
45
91
  /**
46
92
  * Bare shell patterns that a dedicated tool handles better (with truncation, grouping, or a diff).
47
93
  * Deliberately narrow — only unambiguous bare forms, never piped/compound commands — so a legitimate
@@ -61,7 +107,15 @@ const BASH_INTERCEPTOR_RULES = [
61
107
  tool: "grep",
62
108
  why: "it groups, paginates, and bounds output instead of flooding the context",
63
109
  },
64
- { test: /^\s*rg\b[^|&;]*$/, tool: "grep", why: "it groups, paginates, and bounds output" },
110
+ {
111
+ // Only a *pure content* `rg` (no output-shape flag) has a `grep`-tool equivalent. Let
112
+ // `rg --files`, `rg -l`/`--files-with-matches`, `rg -c`/`--count`, `rg --type*` through —
113
+ // forms the grep tool cannot express (fix plan §3.5). Erring toward passing a command
114
+ // through is the safe direction.
115
+ test: /^\s*rg\b(?![^|&;]*\s-{1,2}\S*[lct])[^|&;]*$/,
116
+ tool: "grep",
117
+ why: "it groups, paginates, and bounds output",
118
+ },
65
119
  {
66
120
  test: /^\s*find\s+[^|&;<>`$()]*-name\b[^|&;<>`$()]*$/,
67
121
  tool: "glob",
@@ -73,7 +127,10 @@ const BASH_INTERCEPTOR_RULES = [
73
127
  why: "it discovers file paths without listing directories, and bounds/sorts the result",
74
128
  },
75
129
  {
76
- test: /\b(?:sed|perl)\b[^|&;]*\s-i\b/,
130
+ // Only a *single-file* in-place `sed`/`perl` maps to what `edit` does: flags, `-i`, a script
131
+ // arg, then exactly one non-glob path. A multi-file batch replace (two paths, or a glob) is
132
+ // something `edit` cannot do, so let it through (fix plan §3.5).
133
+ test: /\b(?:sed|perl)\b(?:\s+-\S+)*\s+-i\S*\s+(?:'[^']*'|"[^"]*"|\S+)\s+[^\s|&;*?[\]]+\s*$/,
77
134
  tool: "edit",
78
135
  why: "it verifies a unique match and echoes a diff of the change",
79
136
  },
@@ -99,11 +156,24 @@ export function createBashTool(executor, options = {}) {
99
156
  agentWorkspaceDir: process.cwd(),
100
157
  projectRoot: process.cwd(),
101
158
  };
159
+ if (options.channelDir) {
160
+ void pruneBashLogs(options.channelDir);
161
+ }
102
162
  return {
103
163
  name: "bash",
104
164
  label: "bash",
105
- description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
106
- parameters: bashSchema,
165
+ // A bash command can write any file, so running it alongside a concurrent `edit`/`write` in
166
+ // the same batch reopens the lost-update window that `checkFingerprintUnchanged` cannot close
167
+ // (both calls pass the pre-write fingerprint check, then each rewrites the whole file). This
168
+ // is a process-local measure only: external sub-agents are separate host processes and are
169
+ // not serialized by it. The SDK serializes the whole batch if *any* tool in it is sequential.
170
+ executionMode: "sequential",
171
+ description: `Execute a ${EXECUTOR_SHELL_IS_BASH ? "bash" : "POSIX sh (no bash on this host)"} command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a file whose path is included. Commands time out after ${options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
172
+ parameters: (options.jobManager
173
+ ? options.boundTaskId
174
+ ? bashSchemaBoundTask
175
+ : bashSchema
176
+ : bashSchemaNoJobs),
107
177
  execute: async (_toolCallId, { command, timeout, async: runAsync, notify, taskId, }, signal) => {
108
178
  if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
109
179
  const guardResult = guardCommand(command, securityConfig.commandGuard);
@@ -137,16 +207,25 @@ export function createBashTool(executor, options = {}) {
137
207
  // Background execution: hand off to the channel's job manager and return immediately so
138
208
  // the run queue is not held for the command's duration. Gated by `tools.jobs.enabled`
139
209
  // (the main path supplies a jobManager; the sub-agent path never does).
210
+ // Inside a task session the runtime owns the task id; a conflicting one supplied through a
211
+ // non-schema path is rejected before anything launches (fix plan §3.3).
212
+ if (options.boundTaskId && taskId && taskId !== options.boundTaskId) {
213
+ throw new RecoverableToolError(`This is task ${options.boundTaskId}'s session — drop taskId (it is bound automatically); "${taskId}" does not belong here.`);
214
+ }
215
+ const effectiveTaskId = options.boundTaskId ?? taskId;
140
216
  if (runAsync) {
217
+ if (effectiveTaskId && notify === false) {
218
+ throw new RecoverableToolError("Task-owned jobs must notify their task when they finish. Keep notify=true (the default); only use notify=false for fire-and-forget work with no taskId.");
219
+ }
141
220
  if (!options.jobManager) {
142
- throw new RecoverableToolError("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
221
+ throw new RecoverableToolError("This context does not support background execution (sub-agents never get it). Run the command without async, or split it into shorter steps.");
143
222
  }
144
223
  const willNotify = notify ?? true;
145
224
  const jobLabel = clipText(effectiveCommand, 60, { collapseWhitespace: true });
146
225
  const job = await options.jobManager.start(effectiveCommand, jobLabel, effectiveTimeout, {
147
226
  signal,
148
227
  notify: willNotify,
149
- ...(taskId ? { taskId } : {}),
228
+ ...(effectiveTaskId ? { taskId: effectiveTaskId } : {}),
150
229
  });
151
230
  return {
152
231
  content: [
@@ -154,8 +233,8 @@ export function createBashTool(executor, options = {}) {
154
233
  type: "text",
155
234
  text: `Background job ${job.id} started: ${jobLabel}\n` +
156
235
  (willNotify
157
- ? "It runs off-turn; end your turn now. You will be woken automatically when it finishes, " +
158
- "with its exit code and output — do not schedule a check-in for it."
236
+ ? "Complete any independent work, then end the turn when only waiting remains. Completion wakes this channel with the exit code and output; do not poll or schedule a check-in. " +
237
+ "Inside a task step, park with task_step_end on this job id."
159
238
  : "It runs off-turn and will NOT wake you when it finishes; check it with the job tool (op:poll/list)."),
160
239
  },
161
240
  ],
@@ -172,7 +251,7 @@ export function createBashTool(executor, options = {}) {
172
251
  // the 10MB capture bound, so it is the one place that can honestly be called "full
173
252
  // output" for a command whose real output exceeds that cap. It is deleted below when it
174
253
  // turns out not to be needed.
175
- const buildOutputText = async (stdout, stderr, spillPath) => {
254
+ const buildOutputText = async (stdout, stderr, spillPath, captureTruncated) => {
176
255
  let output = "";
177
256
  if (stdout)
178
257
  output += stdout;
@@ -181,6 +260,27 @@ export function createBashTool(executor, options = {}) {
181
260
  output += "\n";
182
261
  output += stderr;
183
262
  }
263
+ // When the executor's 10MB in-memory capture was itself truncated, `output` is only
264
+ // the *head* of the stream, so `truncateTail(output)` would return the middle of the
265
+ // command's output and label it the tail (fix plan §2.3). Read the real tail from the
266
+ // spill file — the one uncapped copy — and never quote a total line count we never saw.
267
+ if (captureTruncated) {
268
+ let tailSource = output;
269
+ try {
270
+ tailSource = await readFileTail(spillPath, TAIL_FROM_SPILL_BYTES);
271
+ }
272
+ catch {
273
+ // Spill unreadable: fall back to the capped head's tail; still bounded.
274
+ }
275
+ const tailTrunc = truncateTail(tailSource);
276
+ const shownBytes = Buffer.byteLength(tailTrunc.content, "utf-8");
277
+ const text = `${tailTrunc.content || "(no output)"}\n\n` +
278
+ `[Output capture was cut off at ${formatSize(DEFAULT_MAX_BYTES)}+; showing the last ${formatSize(shownBytes)} of the complete output. Full output: ${spillPath}]`;
279
+ return {
280
+ text,
281
+ details: { truncation: tailTrunc, fullOutputPath: spillPath, producedOutput: true },
282
+ };
283
+ }
184
284
  const truncation = truncateTail(output);
185
285
  let text = truncation.content || "(no output)";
186
286
  let details;
@@ -203,19 +303,22 @@ export function createBashTool(executor, options = {}) {
203
303
  else {
204
304
  // No truncation happened after all -- the spill file was insurance against the
205
305
  // in-memory capture cap, not a promised artifact; clean it up rather than leaving
206
- // tmp clutter behind on every single bash call.
306
+ // clutter behind on every single bash call.
207
307
  await unlink(spillPath).catch(() => undefined);
208
308
  }
209
309
  return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
210
310
  };
211
- const spillPath = getSpillFilePath();
311
+ const spillPath = getSpillFilePath(options.channelDir);
312
+ if (options.channelDir) {
313
+ await mkdir(join(options.channelDir, BASH_LOG_DIR_NAME), { recursive: true }).catch(() => undefined);
314
+ }
212
315
  try {
213
316
  const result = await executor.exec(effectiveCommand, {
214
317
  timeout: effectiveTimeout,
215
318
  signal,
216
319
  spillTo: spillPath,
217
320
  });
218
- const built = await buildOutputText(result.stdout, result.stderr, spillPath);
321
+ const built = await buildOutputText(result.stdout, result.stderr, spillPath, result.stdoutTruncated === true || result.stderrTruncated === true);
219
322
  let outputText = built.text;
220
323
  // A non-zero exit code is a normal result, not a tool failure: commands like
221
324
  // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
@@ -233,7 +336,7 @@ export function createBashTool(executor, options = {}) {
233
336
  if (!(error instanceof CommandTerminatedError)) {
234
337
  throw error;
235
338
  }
236
- const built = await buildOutputText(error.stdout, error.stderr, spillPath);
339
+ const built = await buildOutputText(error.stdout, error.stderr, spillPath, error.captureTruncated);
237
340
  const nextStep = error.reason === "timeout"
238
341
  ? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
239
342
  : "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
@@ -88,6 +88,8 @@ const editSchema = Type.Object({
88
88
  });
89
89
  /** Max diff lines echoed back to the model in the success result before eliding the rest. */
90
90
  const DIFF_ECHO_MAX_LINES = 40;
91
+ /** Byte ceiling on the echoed diff — 40 lines of a minified single-line file can be hundreds of KB. */
92
+ const DIFF_ECHO_MAX_BYTES = 8 * 1024;
91
93
  /** Consecutive byte-identical no-ops of the same payload before the soft error escalates to a hard stop. */
92
94
  const NOOP_HARD_LIMIT = 3;
93
95
  /** Above this, `edit` switches from "read whole file into memory" to the streaming two-pass path (D2.2). */
@@ -108,11 +110,20 @@ const DIFF_WINDOW_BYTES = 2000;
108
110
  const MAX_DIFF_WINDOWS = 5;
109
111
  function clampDiffForEcho(diff) {
110
112
  const lines = diff.split("\n");
111
- if (lines.length <= DIFF_ECHO_MAX_LINES) {
113
+ if (lines.length <= DIFF_ECHO_MAX_LINES && Buffer.byteLength(diff, "utf-8") <= DIFF_ECHO_MAX_BYTES) {
112
114
  return diff;
113
115
  }
114
- const shown = lines.slice(0, DIFF_ECHO_MAX_LINES).join("\n");
115
- return `${shown}\n[diff truncated, ${lines.length - DIFF_ECHO_MAX_LINES} more lines]`;
116
+ let kept = lines.slice(0, DIFF_ECHO_MAX_LINES);
117
+ while (kept.length > 1 && Buffer.byteLength(kept.join("\n"), "utf-8") > DIFF_ECHO_MAX_BYTES) {
118
+ kept = kept.slice(0, -1);
119
+ }
120
+ let shown = kept.join("\n");
121
+ if (Buffer.byteLength(shown, "utf-8") > DIFF_ECHO_MAX_BYTES) {
122
+ // A single line still over budget: hard-cut on a UTF-8 boundary.
123
+ shown = Buffer.from(shown, "utf-8").subarray(0, DIFF_ECHO_MAX_BYTES).toString("utf-8");
124
+ }
125
+ const omitted = lines.length - kept.length;
126
+ return `${shown}\n[diff truncated${omitted > 0 ? `, ${omitted} more line(s)` : ""}; the full diff is in the tool result details]`;
116
127
  }
117
128
  /** All non-overlapping byte offsets of `needle` in `haystack`, left to right (mirrors `String.split`). */
118
129
  function findAllOffsets(haystack, needle) {
@@ -152,6 +163,12 @@ async function scanOccurrences(stream, needle, maxOffsets) {
152
163
  let windowBaseOffset = 0;
153
164
  let newlinesBeforeWindow = 0;
154
165
  let count = 0;
166
+ // Absolute byte position just past the last accepted match. A window carries the last
167
+ // `overlapLen` bytes of its predecessor, so without this guard a match that ended inside the
168
+ // carry region would be re-found (from a fresh `from = 0`) and reported as a second, overlapping
169
+ // offset -- which `spliceBuffer` then turns into a corrupt file. Verified against a non-overlapping
170
+ // `Buffer.indexOf` reference over 165 boundary combinations.
171
+ let nextAllowed = 0;
155
172
  let offsets = [];
156
173
  const lineNumbers = new Map();
157
174
  let looksBinary = false;
@@ -166,14 +183,15 @@ async function scanOccurrences(stream, needle, maxOffsets) {
166
183
  sniffed += take.length;
167
184
  }
168
185
  const window = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
169
- let from = 0;
186
+ let from = Math.max(0, nextAllowed - windowBaseOffset);
170
187
  while (true) {
171
188
  const idx = window.indexOf(needle, from);
172
189
  if (idx === -1)
173
190
  break;
191
+ const absoluteOffset = windowBaseOffset + idx;
174
192
  count++;
193
+ nextAllowed = absoluteOffset + needle.length;
175
194
  if (offsets && offsets.length < maxOffsets) {
176
- const absoluteOffset = windowBaseOffset + idx;
177
195
  offsets.push(absoluteOffset);
178
196
  const lineNumber = newlinesBeforeWindow + countNewlines(window, 0, idx) + 1;
179
197
  lineNumbers.set(absoluteOffset, lineNumber);
@@ -252,6 +270,10 @@ export function createEditTool(fileStore, options = {}) {
252
270
  return {
253
271
  name: "edit",
254
272
  label: "edit",
273
+ // Serialize with other mutating tools in the same batch. `checkFingerprintUnchanged` runs
274
+ // before the write, so two concurrent edits can both pass it and then overwrite each other's
275
+ // result; running the batch one tool at a time closes that window (spec: batch 1.3).
276
+ executionMode: "sequential",
255
277
  description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
256
278
  parameters: editSchema,
257
279
  execute: async (_toolCallId, { path, oldText, newText, replaceAll, }, signal) => {
@@ -262,6 +284,15 @@ export function createEditTool(fileStore, options = {}) {
262
284
  tool: "edit",
263
285
  channelId: options.channelId,
264
286
  });
287
+ // `edit` rewrites the file in place, so it must clear the *write* guard too (spec 044,
288
+ // D1.1). Pass the original `path`, never the realpath'd `target`: the guard's
289
+ // symlink-write check lstats the pre-symlink-resolution path, and handing it a resolved
290
+ // value would blind it to "the path itself is a symlink". Both calls return the same
291
+ // `resolvedPath` for read and write, so `target` stays the one value we open.
292
+ await checkPathGuard(path, "write", securityConfig, securityContext, {
293
+ tool: "edit",
294
+ channelId: options.channelId,
295
+ });
265
296
  const before = await fileStore.stat(target);
266
297
  if (!before || !before.isFile) {
267
298
  throw new RecoverableToolError(`File not found: ${path}`);
@@ -3,11 +3,32 @@ import { Type } from "typebox";
3
3
  import { type ScheduledEvent } from "../runtime/events.js";
4
4
  import type { SecurityConfig } from "../security/types.js";
5
5
  declare const eventManageSchema: Type.TObject<{
6
- action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
6
+ action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"show">, Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
7
7
  name: Type.TOptional<Type.TString>;
8
- definition: Type.TOptional<Type.TString>;
8
+ definition: Type.TOptional<Type.TObject<{
9
+ type: Type.TUnion<[Type.TLiteral<"one-shot">, Type.TLiteral<"periodic">, Type.TLiteral<"immediate">]>;
10
+ text: Type.TString;
11
+ at: Type.TOptional<Type.TString>;
12
+ schedule: Type.TOptional<Type.TString>;
13
+ preAction: Type.TOptional<Type.TObject<{
14
+ type: Type.TLiteral<"bash">;
15
+ command: Type.TString;
16
+ timeoutMs: Type.TOptional<Type.TInteger>;
17
+ }>>;
18
+ }>>;
9
19
  }>;
10
- export type EventManageAction = "list" | "create" | "update" | "delete";
20
+ export type EventManageAction = "list" | "show" | "create" | "update" | "delete";
21
+ export type EventDefinitionInput = {
22
+ type: "one-shot" | "periodic" | "immediate";
23
+ text: string;
24
+ at?: string;
25
+ schedule?: string;
26
+ preAction?: {
27
+ type: "bash";
28
+ command: string;
29
+ timeoutMs?: number;
30
+ };
31
+ };
11
32
  export interface EventManageListEntry {
12
33
  name: string;
13
34
  line: string;
@@ -28,7 +49,7 @@ export interface EventManageResult {
28
49
  export interface EventManageRequest {
29
50
  action: EventManageAction;
30
51
  name?: string;
31
- definition?: string;
52
+ definition?: EventDefinitionInput;
32
53
  }
33
54
  export interface EventManageToolOptions {
34
55
  workspaceDir: string;
@@ -8,23 +8,41 @@ import { parseScheduledEventContent } from "../runtime/events.js";
8
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
9
  import { RecoverableToolError } from "../shared/recoverable-error.js";
10
10
  import { clipText, errorMessage } from "../shared/text-utils.js";
11
- import { isRecord } from "../shared/type-guards.js";
11
+ const eventDefinitionSchema = Type.Object({
12
+ type: Type.Union([Type.Literal("one-shot"), Type.Literal("periodic"), Type.Literal("immediate")], {
13
+ description: '"one-shot" (needs `at`), "periodic" (needs cron `schedule`). "immediate" is always rejected.',
14
+ }),
15
+ text: Type.String({ description: "Message delivered to the channel when the event fires." }),
16
+ at: Type.Optional(Type.String({ description: "one-shot local time, e.g. 2026-07-27T07:30:00+08:00 (2 min to ~24.8 days out)." })),
17
+ schedule: Type.Optional(Type.String({ description: "periodic 5-field cron, in the host timezone." })),
18
+ preAction: Type.Optional(Type.Object({
19
+ type: Type.Literal("bash"),
20
+ command: Type.String({
21
+ description: "Command run just before delivery; exit 0 = fire, non-zero = skip.",
22
+ }),
23
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout in milliseconds (not s)." })),
24
+ }, { description: "Optional gate/sensor command." })),
25
+ }, { description: "The event to create/update. Channel is bound automatically — do not pass channelId." });
12
26
  const eventManageSchema = Type.Object({
13
- action: Type.Union([Type.Literal("list"), Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
14
- description: '"list" this channel\'s events, or "create" / "update" / "delete" one by name.',
27
+ action: Type.Union([
28
+ Type.Literal("list"),
29
+ Type.Literal("show"),
30
+ Type.Literal("create"),
31
+ Type.Literal("update"),
32
+ Type.Literal("delete"),
33
+ ], {
34
+ description: '"list" this channel\'s events, "show" one event\'s full definition (for a safe update), or "create" / "update" / "delete" one by name.',
15
35
  }),
16
36
  name: Type.Optional(Type.String({
17
- description: "Event name (filename without .json); required for create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
18
- })),
19
- definition: Type.Optional(Type.String({
20
- description: "Full event JSON (required for create/update). one-shot / periodic only; one-shots 2 minutes to about 24.8 days out. channelId defaults to the current channel.",
37
+ description: "Event name (filename without .json); required for show/create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
21
38
  })),
39
+ definition: Type.Optional(eventDefinitionSchema),
22
40
  });
23
41
  function parseAction(action) {
24
- if (action === "list" || action === "create" || action === "update" || action === "delete") {
42
+ if (action === "list" || action === "show" || action === "create" || action === "update" || action === "delete") {
25
43
  return action;
26
44
  }
27
- throw new RecoverableToolError('Unsupported event action. Use "list", "create", "update", or "delete".');
45
+ throw new RecoverableToolError('Unsupported event action. Use "list", "show", "create", "update", or "delete".');
28
46
  }
29
47
  /** One line per event; unparseable files are listed and flagged so the model can still clean them up. */
30
48
  async function listOwnedEvents(options) {
@@ -62,30 +80,45 @@ async function listOwnedEvents(options) {
62
80
  * the watcher (spec 031, D4); this layer only adds tool-specific framing (channel ownership,
63
81
  * and turning validation failures into recoverable tool errors the model can retry).
64
82
  */
65
- function validateDefinition(rawDefinition, name, options) {
66
- let data;
67
- try {
68
- data = JSON.parse(rawDefinition);
69
- }
70
- catch (error) {
71
- const message = errorMessage(error);
72
- throw new RecoverableToolError(`definition is not valid JSON: ${message}`);
83
+ function validateDefinition(definition, name, options) {
84
+ if (definition.type === "immediate") {
85
+ throw new RecoverableToolError("event_manage cannot create or update immediate events (self-triggering loop guard); " +
86
+ "do the work in the current turn instead.");
73
87
  }
74
- if (!isRecord(data)) {
75
- throw new RecoverableToolError("definition must be a JSON object.");
88
+ if (definition.type === "one-shot" && !definition.at?.trim()) {
89
+ throw new RecoverableToolError('A one-shot event needs "at" (a local time 2 minutes to ~24.8 days out).');
76
90
  }
77
- const providedChannelId = data.channelId;
78
- if (providedChannelId === undefined || providedChannelId === null || providedChannelId === "") {
79
- data.channelId = options.channelId;
91
+ if (definition.type === "periodic" && !definition.schedule?.trim()) {
92
+ throw new RecoverableToolError('A periodic event needs "schedule" (a 5-field cron expression).');
80
93
  }
81
- else if (providedChannelId !== options.channelId) {
82
- throw new RecoverableToolError(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
94
+ // Assemble the on-disk shape. `channelId` is bound here, never taken from the model; the
95
+ // preAction timeout field is `timeout` (ms) on disk but `timeoutMs` in the schema so the unit
96
+ // is unambiguous (fix plan §3.6).
97
+ const onDisk = {
98
+ type: definition.type,
99
+ channelId: options.channelId,
100
+ text: definition.text,
101
+ ...(definition.type === "one-shot" ? { at: definition.at } : { schedule: definition.schedule }),
102
+ ...(definition.preAction
103
+ ? {
104
+ preAction: {
105
+ type: "bash",
106
+ command: definition.preAction.command,
107
+ ...(definition.preAction.timeoutMs !== undefined ? { timeout: definition.preAction.timeoutMs } : {}),
108
+ },
109
+ }
110
+ : {}),
111
+ };
112
+ // Both the parse and the schedule validation become recoverable: a missing/malformed field is
113
+ // something the model can fix itself, and `parseScheduledEventContent` used to throw a plain
114
+ // Error that bypassed the recoverable wrapper (fix plan §3.6).
115
+ let event;
116
+ try {
117
+ event = parseScheduledEventContent(JSON.stringify(onDisk), `${name}.json`);
83
118
  }
84
- if (data.type === "immediate") {
85
- throw new RecoverableToolError("event_manage cannot create or update immediate events (self-triggering loop guard); " +
86
- "do the work in the current turn instead.");
119
+ catch (error) {
120
+ throw new RecoverableToolError(`Invalid event definition: ${errorMessage(error)}`);
87
121
  }
88
- const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
89
122
  try {
90
123
  validateScheduledEvent(event, { commandGuardConfig: options.commandGuardConfig });
91
124
  }
@@ -133,6 +166,20 @@ export async function manageEvent(options, request) {
133
166
  }
134
167
  const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
135
168
  const eventsDir = join(options.workspaceDir, "events");
169
+ if (request.action === "show") {
170
+ if (!existsSync(eventPath)) {
171
+ throw new RecoverableToolError(`Event "${eventName}" does not exist. Use action "list" to see what's here.`);
172
+ }
173
+ const existing = await readOwnedEvent(eventPath, eventName, options);
174
+ return {
175
+ action: "show",
176
+ name: eventName,
177
+ path: eventPath,
178
+ eventType: existing.type,
179
+ channelId: existing.channelId,
180
+ notice: JSON.stringify(existing, null, 2),
181
+ };
182
+ }
136
183
  if (request.action === "delete") {
137
184
  if (!existsSync(eventPath)) {
138
185
  return {
@@ -153,8 +200,8 @@ export async function manageEvent(options, request) {
153
200
  notice: `已删除事件 \`${eventName}\`。`,
154
201
  };
155
202
  }
156
- if (!request.definition || request.definition.trim().length === 0) {
157
- throw new RecoverableToolError(`${request.action} requires a non-empty definition.`);
203
+ if (!request.definition || !request.definition.type || !request.definition.text?.trim()) {
204
+ throw new RecoverableToolError(`${request.action} requires a definition with at least "type" and "text".`);
158
205
  }
159
206
  if (request.action === "create") {
160
207
  if (existsSync(eventPath)) {
@@ -196,8 +243,9 @@ export function createEventManageTool(options) {
196
243
  return {
197
244
  name: "event_manage",
198
245
  label: "event_manage",
199
- description: "List, create, update, or delete scheduled events that wake this channel later (one-shot check-ins and periodic " +
200
- "cadences). List to recover real event names before a reschedule or close-out. immediate events are rejected.",
246
+ description: "List, show, create, update, or delete scheduled events that wake this channel later (one-shot check-ins and " +
247
+ "periodic cadences). Use list to recover event names, and show to read an event's full definition before an " +
248
+ "update. immediate events are rejected.",
201
249
  parameters: eventManageSchema,
202
250
  execute: async (_toolCallId, args) => {
203
251
  const result = await manageEvent(options, {
@@ -205,7 +253,7 @@ export function createEventManageTool(options) {
205
253
  name: args.name,
206
254
  definition: args.definition,
207
255
  });
208
- const text = result.action === "list" ? result.notice : JSON.stringify(result, null, 2);
256
+ const text = result.action === "list" || result.action === "show" ? result.notice : JSON.stringify(result, null, 2);
209
257
  return {
210
258
  content: [{ type: "text", text }],
211
259
  details: { ...result },