@oyasmi/pipiclaw 0.9.3-beta.1 → 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 (95) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +16 -0
  4. package/dist/agent/channel-runner.js +47 -6
  5. package/dist/agent/job-manager.d.ts +9 -0
  6. package/dist/agent/job-manager.js +20 -6
  7. package/dist/agent/prompt/builder.d.ts +1 -1
  8. package/dist/agent/prompt/builder.js +1 -1
  9. package/dist/agent/prompt/sections.js +3 -3
  10. package/dist/executor.d.ts +5 -1
  11. package/dist/executor.js +35 -5
  12. package/dist/file-store.d.ts +4 -1
  13. package/dist/file-store.js +5 -0
  14. package/dist/memory/journal.d.ts +13 -0
  15. package/dist/memory/journal.js +47 -4
  16. package/dist/memory/render.d.ts +5 -0
  17. package/dist/memory/render.js +9 -2
  18. package/dist/memory/search.js +13 -6
  19. package/dist/memory/session-corpus.d.ts +11 -0
  20. package/dist/memory/session-corpus.js +15 -4
  21. package/dist/memory/session-search.d.ts +3 -0
  22. package/dist/memory/session-search.js +45 -8
  23. package/dist/memory/store.d.ts +9 -0
  24. package/dist/memory/store.js +25 -2
  25. package/dist/memory/transcript.js +12 -5
  26. package/dist/playbooks/agent-delegation.md +35 -50
  27. package/dist/playbooks/background-jobs.md +14 -16
  28. package/dist/playbooks/event-scheduling.md +20 -25
  29. package/dist/playbooks/memory-and-learning.md +28 -44
  30. package/dist/playbooks/outbound-media.md +10 -12
  31. package/dist/playbooks/runtime-orientation.md +34 -53
  32. package/dist/playbooks/task-loop.md +50 -48
  33. package/dist/runtime/bootstrap.js +25 -11
  34. package/dist/security/path-guard-filter.d.ts +22 -0
  35. package/dist/security/path-guard-filter.js +35 -0
  36. package/dist/subagents/discovery.d.ts +2 -3
  37. package/dist/subagents/discovery.js +3 -1
  38. package/dist/subagents/tool.d.ts +6 -0
  39. package/dist/subagents/tool.js +10 -2
  40. package/dist/tasks/brief.d.ts +1 -1
  41. package/dist/tasks/brief.js +11 -2
  42. package/dist/tasks/log.d.ts +4 -0
  43. package/dist/tasks/log.js +13 -1
  44. package/dist/tasks/rounds.d.ts +0 -2
  45. package/dist/tasks/rounds.js +0 -4
  46. package/dist/tasks/verification.d.ts +31 -0
  47. package/dist/tasks/verification.js +20 -0
  48. package/dist/tools/bash.d.ts +13 -0
  49. package/dist/tools/bash.js +123 -20
  50. package/dist/tools/edit.js +36 -5
  51. package/dist/tools/event-manage.d.ts +25 -4
  52. package/dist/tools/event-manage.js +81 -33
  53. package/dist/tools/glob.js +57 -4
  54. package/dist/tools/grep.d.ts +2 -0
  55. package/dist/tools/grep.js +187 -14
  56. package/dist/tools/job.js +16 -4
  57. package/dist/tools/memory-manage.js +80 -41
  58. package/dist/tools/read.js +42 -5
  59. package/dist/tools/registry.d.ts +6 -0
  60. package/dist/tools/registry.js +4 -1
  61. package/dist/tools/send-media.js +6 -4
  62. package/dist/tools/session-search.js +4 -1
  63. package/dist/tools/skill.d.ts +2 -0
  64. package/dist/tools/skill.js +12 -0
  65. package/dist/tools/subagent-manage.js +1 -1
  66. package/dist/tools/subagent-tool-names.d.ts +11 -0
  67. package/dist/tools/subagent-tool-names.js +19 -0
  68. package/dist/tools/task-manage/lifecycle.js +2 -6
  69. package/dist/tools/task-manage/log-view.js +6 -3
  70. package/dist/tools/task-manage/schema.d.ts +6 -6
  71. package/dist/tools/task-manage/schema.js +5 -12
  72. package/dist/tools/task-manage/shared.d.ts +11 -0
  73. package/dist/tools/task-manage/shared.js +43 -2
  74. package/dist/tools/task-manage/step-end.js +28 -13
  75. package/dist/tools/task-manage.js +9 -1
  76. package/dist/tools/web-cache.d.ts +11 -3
  77. package/dist/tools/web-cache.js +26 -8
  78. package/dist/tools/web-fetch.d.ts +1 -0
  79. package/dist/tools/web-fetch.js +68 -15
  80. package/dist/tools/write.js +3 -0
  81. package/dist/web/fetch.d.ts +5 -0
  82. package/dist/web/fetch.js +36 -1
  83. package/examples/sub-agents/README.md +65 -39
  84. package/examples/sub-agents/builder-hard.md +12 -25
  85. package/examples/sub-agents/builder.md +12 -24
  86. package/examples/sub-agents/explorer.md +13 -17
  87. package/examples/sub-agents/git-committer.md +16 -19
  88. package/examples/sub-agents/planner.md +11 -20
  89. package/examples/sub-agents/reviewer.md +11 -30
  90. package/examples/sub-agents/verifier.md +13 -22
  91. package/examples/sub-agents/worker.md +12 -20
  92. package/package.json +7 -3
  93. package/examples/sub-agents/documenter.md +0 -50
  94. package/examples/sub-agents/log-sifter.md +0 -47
  95. package/examples/sub-agents/scout.md +0 -34
@@ -81,3 +81,34 @@ export declare function attestationRejectionReason(input: {
81
81
  trustedWorkingDirectory?: string;
82
82
  fallbackWorkingDirectory?: string;
83
83
  }): Promise<string | undefined>;
84
+ /**
85
+ * How a cycle's rework rounds are consumed when deciding whether a task may close (spec 051, D7).
86
+ *
87
+ * Recording a round at settlement proved the attestation *then*. It cannot prove it *now*: the
88
+ * task Markdown and the workspace are both agent-writable between the verifier's PASS and the
89
+ * close, so a contract edit or a further code change after the PASS would sail through a check
90
+ * that only asks "did a PASS ever land in this cycle". That was the shape of the hole — both
91
+ * close entry points asked exactly that.
92
+ *
93
+ * Two rules, deliberately simple:
94
+ * - The candidate is the cycle's *last* round, not any PASS in it. A later FAIL is newer evidence
95
+ * about the same artifact and must not be overridden by an earlier PASS.
96
+ * - That candidate's attestation is re-checked against the contract and the checkout as they are
97
+ * at close time, reusing `attestationRejectionReason` rather than a second proof model.
98
+ */
99
+ export interface CompletionVerificationInput {
100
+ channelDir: string;
101
+ taskId: string;
102
+ taskBody: string;
103
+ cycleId: string | undefined;
104
+ /**
105
+ * The checkout persisted for a verify run, from the sub-agent run registry. The attestation
106
+ * file names its own `subjectDir`, but that file is evidence, not the authority for which
107
+ * checkout was verified — so a run whose record is gone fails closed rather than falling back
108
+ * to whatever directory the daemon happens to be in.
109
+ */
110
+ findRunWorkingDirectory: (runId: string) => string | undefined;
111
+ fallbackWorkingDirectory?: string;
112
+ }
113
+ /** Why this task may not be closed as done, or `undefined` when its verification still holds. */
114
+ export declare function completionVerificationBlockReason(input: CompletionVerificationInput): Promise<string | undefined>;
@@ -7,6 +7,7 @@ import { parseLocalTime } from "../shared/local-time.js";
7
7
  import { errorMessage } from "../shared/text-utils.js";
8
8
  import { workspaceSubjectHash } from "./artifact-subject.js";
9
9
  import { taskBodyHash } from "./ledger.js";
10
+ import { readCycleRounds } from "./rounds.js";
10
11
  import { readStoredTask } from "./store.js";
11
12
  const FULL_COMMIT_PATTERN = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i;
12
13
  function attestationFilename(runId) {
@@ -204,3 +205,22 @@ export async function attestationRejectionReason(input) {
204
205
  }
205
206
  return undefined;
206
207
  }
208
+ /** Why this task may not be closed as done, or `undefined` when its verification still holds. */
209
+ export async function completionVerificationBlockReason(input) {
210
+ const rounds = await readCycleRounds(input.channelDir, input.taskId, input.cycleId);
211
+ const latest = rounds.at(-1);
212
+ if (!latest)
213
+ return "no verification round has landed in this cycle";
214
+ if (latest.verdict !== "pass") {
215
+ return `the latest verification round (#${latest.n}) is a FAIL${latest.reason ? `: ${latest.reason}` : ""}`;
216
+ }
217
+ const rejection = await attestationRejectionReason({
218
+ channelDir: input.channelDir,
219
+ taskId: input.taskId,
220
+ runId: latest.verifyRunId,
221
+ taskBody: input.taskBody,
222
+ trustedWorkingDirectory: input.findRunWorkingDirectory(latest.verifyRunId),
223
+ fallbackWorkingDirectory: input.fallbackWorkingDirectory,
224
+ });
225
+ return rejection ? `the PASS from round #${latest.n} no longer holds: ${rejection}` : undefined;
226
+ }
@@ -22,6 +22,12 @@ export interface BashToolOptions {
22
22
  securityConfig?: SecurityConfig;
23
23
  securityContext?: SecurityRuntimeContext;
24
24
  channelId?: string;
25
+ /**
26
+ * The channel directory. When set, the "full output" spill file lives under
27
+ * `<channelDir>/logs/` so the pointer the tool hands back is one the model's `read` can open
28
+ * under both path-guard boundaries. Absent on the sub-agent path (spill falls back to tmpdir).
29
+ */
30
+ channelDir?: string;
25
31
  /**
26
32
  * When true, route each command through the `rtk` command optimizer before executing
27
33
  * (best-effort; falls back to the raw command when rtk is unavailable or declines).
@@ -33,6 +39,13 @@ export interface BashToolOptions {
33
39
  * background execution. Absent on the sub-agent path, so sub-agents cannot background jobs.
34
40
  */
35
41
  jobManager?: ChannelJobManager;
42
+ /**
43
+ * Set inside a task cycle's session. A background job started here belongs to this task, so the
44
+ * runtime binds the id rather than asking the model to repeat it (and rejects a conflicting one
45
+ * before the job launches — the old "relaunch with taskId=…" told the model to re-run a command
46
+ * that may have side effects). Chat sessions leave this unset and keep the optional `taskId`.
47
+ */
48
+ boundTaskId?: string;
36
49
  /**
37
50
  * When true (`tools.bashInterceptor.enabled`), block a few bare shell patterns that have a
38
51
  * better dedicated tool and steer the model to it. Off by default; main path only.
@@ -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;