@codelia/runtime 0.1.72 → 0.1.74

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.
@@ -1929,6 +1929,7 @@ import path3 from "path";
1929
1929
 
1930
1930
  // src/tasks/shell-executor.ts
1931
1931
  import { spawn as spawn3 } from "child_process";
1932
+ import { performance } from "perf_hooks";
1932
1933
 
1933
1934
  // src/tools/bash-utils.ts
1934
1935
  import { spawn as spawn2 } from "child_process";
@@ -1952,6 +1953,10 @@ var summarizeCommand = (command) => {
1952
1953
  var DEFAULT_EXCERPT_LINES = 80;
1953
1954
  var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
1954
1955
  var FORCE_KILL_DELAY_MS = 2e3;
1956
+ var MAX_STDIN_WRITE_BYTES = 64 * 1024;
1957
+ var DEFAULT_STDIN_WRITE_TIMEOUT_MS = 3e4;
1958
+ var defaultMonotonicNowMs = () => performance.now();
1959
+ var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
1955
1960
  var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
1956
1961
  var truncateUtf8Prefix = (value, maxBytes) => {
1957
1962
  if (maxBytes <= 0 || value.length === 0) return "";
@@ -2044,19 +2049,20 @@ var buildShellTaskResult = async (outputCache, options) => {
2044
2049
  ...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
2045
2050
  };
2046
2051
  };
2047
- var spawnShellProcess = (command, cwd) => {
2052
+ var spawnShellProcess = (command, cwd, stdinMode) => {
2053
+ const stdin = stdinMode === "pipe" ? "pipe" : "ignore";
2048
2054
  const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
2049
2055
  if (shellPath) {
2050
2056
  return spawn3(shellPath, ["-lc", command], {
2051
2057
  cwd,
2052
- stdio: ["ignore", "pipe", "pipe"],
2058
+ stdio: [stdin, "pipe", "pipe"],
2053
2059
  detached: true
2054
2060
  });
2055
2061
  }
2056
2062
  return spawn3(command, {
2057
2063
  cwd,
2058
2064
  shell: true,
2059
- stdio: ["ignore", "pipe", "pipe"],
2065
+ stdio: [stdin, "pipe", "pipe"],
2060
2066
  detached: process.platform !== "win32"
2061
2067
  });
2062
2068
  };
@@ -2081,11 +2087,18 @@ var startShellTask = (options) => {
2081
2087
  }
2082
2088
  const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
2083
2089
  const forceKillDelayMs = options.forceKillDelayMs ?? FORCE_KILL_DELAY_MS;
2084
- const startedAt = Date.now();
2090
+ const monotonicNowMs = options.monotonicNowMs ?? defaultMonotonicNowMs;
2091
+ const stdinMode = options.stdinMode ?? "closed";
2092
+ const stdinWriteTimeoutMs = options.stdinWriteTimeoutMs ?? DEFAULT_STDIN_WRITE_TIMEOUT_MS;
2093
+ const monotonicStartedAt = monotonicNowMs();
2085
2094
  const child = (options.spawnProcess ?? spawnShellProcess)(
2086
2095
  options.command,
2087
- options.cwd
2096
+ options.cwd,
2097
+ stdinMode
2088
2098
  );
2099
+ if (stdinMode === "pipe" && child.stdin === null) {
2100
+ throw new Error("stdin_mode=pipe requires a writable child stdin stream");
2101
+ }
2089
2102
  const metadata = typeof child.pid === "number" ? {
2090
2103
  executor_pid: child.pid,
2091
2104
  executor_pgid: process.platform === "win32" ? void 0 : child.pid
@@ -2097,6 +2110,51 @@ var startShellTask = (options) => {
2097
2110
  let cancelRequested = false;
2098
2111
  let timeoutHandle;
2099
2112
  let forceKillHandle;
2113
+ let stdinClosed = stdinMode === "closed";
2114
+ let stdinWriteQueue = Promise.resolve();
2115
+ const markStdinClosed = () => {
2116
+ if (stdinClosed) return;
2117
+ stdinClosed = true;
2118
+ };
2119
+ const invalidateStdin = () => {
2120
+ if (stdinClosed) return;
2121
+ markStdinClosed();
2122
+ child.stdin?.destroy();
2123
+ };
2124
+ const performStdinWrite = async (input) => {
2125
+ if (stdinMode !== "pipe" || child.stdin === null) {
2126
+ throw new Error("stdin was not opened as a pipe");
2127
+ }
2128
+ const stdin = child.stdin;
2129
+ if (settled) throw new Error("task is already terminal");
2130
+ if (stdinClosed || stdin.destroyed || stdin.writableEnded) {
2131
+ throw new Error("stdin is already closed");
2132
+ }
2133
+ const bytesWritten = utf8ByteLength(input.text);
2134
+ if (bytesWritten > MAX_STDIN_WRITE_BYTES) {
2135
+ throw new Error(
2136
+ `stdin write exceeds ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes`
2137
+ );
2138
+ }
2139
+ if (bytesWritten > 0) {
2140
+ await new Promise((resolve, reject) => {
2141
+ const timer = setTimeout(() => {
2142
+ invalidateStdin();
2143
+ reject(new Error("stdin write timed out waiting for backpressure"));
2144
+ }, stdinWriteTimeoutMs);
2145
+ stdin.write(input.text, "utf8", (error) => {
2146
+ clearTimeout(timer);
2147
+ if (error) reject(error);
2148
+ else resolve();
2149
+ });
2150
+ });
2151
+ }
2152
+ if (input.close) {
2153
+ markStdinClosed();
2154
+ stdin.end();
2155
+ }
2156
+ return { bytes_written: bytesWritten, stdin_closed: stdinClosed };
2157
+ };
2100
2158
  const clearForceKillHandle = () => {
2101
2159
  if (!forceKillHandle) return;
2102
2160
  clearTimeout(forceKillHandle);
@@ -2113,7 +2171,12 @@ var startShellTask = (options) => {
2113
2171
  const settle = async (outcome) => {
2114
2172
  if (settled) return;
2115
2173
  settled = true;
2174
+ invalidateStdin();
2116
2175
  if (timeoutHandle) clearTimeout(timeoutHandle);
2176
+ const durationMs = elapsedMilliseconds(
2177
+ monotonicStartedAt,
2178
+ monotonicNowMs
2179
+ );
2117
2180
  let result;
2118
2181
  try {
2119
2182
  result = await buildShellTaskResult(options.outputCache, {
@@ -2123,7 +2186,7 @@ var startShellTask = (options) => {
2123
2186
  rawStderr: stderr,
2124
2187
  exitCode: outcome.exitCode,
2125
2188
  signal: outcome.signal,
2126
- durationMs: Date.now() - startedAt
2189
+ durationMs
2127
2190
  });
2128
2191
  } catch {
2129
2192
  result = buildShellTaskResultBase({
@@ -2131,7 +2194,7 @@ var startShellTask = (options) => {
2131
2194
  rawStderr: stderr,
2132
2195
  exitCode: outcome.exitCode,
2133
2196
  signal: outcome.signal,
2134
- durationMs: Date.now() - startedAt
2197
+ durationMs
2135
2198
  });
2136
2199
  }
2137
2200
  resolve({
@@ -2214,8 +2277,19 @@ var startShellTask = (options) => {
2214
2277
  metadata,
2215
2278
  wait,
2216
2279
  readOutput: async (stream) => stream === "stdout" ? stdout : stderr,
2280
+ ...stdinMode === "pipe" ? {
2281
+ writeInput: (input) => {
2282
+ const write = stdinWriteQueue.then(() => performStdinWrite(input));
2283
+ stdinWriteQueue = write.then(
2284
+ () => void 0,
2285
+ () => void 0
2286
+ );
2287
+ return write;
2288
+ }
2289
+ } : {},
2217
2290
  cancel: async () => {
2218
2291
  if (settled) return;
2292
+ invalidateStdin();
2219
2293
  cancelRequested = true;
2220
2294
  terminateChild(child, "SIGTERM");
2221
2295
  scheduleForceKill();
@@ -3577,6 +3651,7 @@ var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
3577
3651
  "shell_wait",
3578
3652
  "shell_result",
3579
3653
  "shell_cancel",
3654
+ "shell_stdin_write",
3580
3655
  "lane_list",
3581
3656
  "lane_status",
3582
3657
  "done"
@@ -5384,11 +5459,40 @@ var createDoneTool = () => defineTool3({
5384
5459
  });
5385
5460
 
5386
5461
  // src/tools/edit.ts
5387
- import crypto4 from "crypto";
5388
5462
  import { promises as fs8 } from "fs";
5389
5463
  import path10 from "path";
5390
5464
  import { defineTool as defineTool4 } from "@codelia/core";
5465
+ import { z as z6 } from "zod";
5466
+
5467
+ // src/tools/content-hash.ts
5468
+ import crypto4 from "crypto";
5391
5469
  import { z as z5 } from "zod";
5470
+ var CONTENT_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5471
+ var expectedContentHashSchema = z5.string().regex(
5472
+ CONTENT_SHA256_PATTERN,
5473
+ "expected_hash must be a lowercase 64-character SHA-256 hash"
5474
+ ).nullable().default(null).describe(
5475
+ "Current full-content SHA-256 guard. Copy content_sha256 from a current read/read_line result or explicitly compute the same UTF-8 content hash."
5476
+ );
5477
+ var hashUtf8Content = (content) => crypto4.createHash("sha256").update(content).digest("hex");
5478
+ var assertExpectedContentHash = (input) => {
5479
+ if (!input.expectedHash) return;
5480
+ if (!input.fileExists) {
5481
+ throw new Error(
5482
+ `Expected hash provided but file not found: ${input.filePath}`
5483
+ );
5484
+ }
5485
+ if (hashUtf8Content(input.content) !== input.expectedHash) {
5486
+ throw new Error(
5487
+ `Hash mismatch for ${input.filePath}. The file changed since it was read; read it again and retry with the new content_sha256.`
5488
+ );
5489
+ }
5490
+ };
5491
+ var appendReadMetadata = (output, content) => `${output}
5492
+
5493
+ [read_metadata] content_sha256=${hashUtf8Content(content)}`;
5494
+
5495
+ // src/tools/edit.ts
5392
5496
  var trimLine = (line) => line.replace(/\r$/, "").trim();
5393
5497
  var lineRangeToIndices = (lines, startLine, lineCount) => {
5394
5498
  let startIndex = 0;
@@ -5495,25 +5599,24 @@ var applyReplacements = (content, matches, replacement) => {
5495
5599
  }
5496
5600
  return next;
5497
5601
  };
5498
- var hashContent = (content) => crypto4.createHash("sha256").update(content).digest("hex");
5499
5602
  var createEditTool = (sandboxKey, outputCacheStore) => defineTool4({
5500
5603
  name: "edit",
5501
5604
  description: "Edit a file by replacing matched text with new text; supports guarded match modes and dry-run preview.",
5502
- input: z5.object({
5503
- file_path: z5.string().describe(
5605
+ input: z6.object({
5606
+ file_path: z6.string().describe(
5504
5607
  "File path. Sandbox-bounded unless full-access mode is active."
5505
5608
  ),
5506
- old_string: z5.string().describe(
5609
+ old_string: z6.string().describe(
5507
5610
  "Text to find. Use empty string to replace the whole file content."
5508
5611
  ),
5509
- new_string: z5.string().describe("Replacement text."),
5510
- replace_all: z5.boolean().optional().describe("Replace all matches when true. Default false."),
5511
- match_mode: z5.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
5612
+ new_string: z6.string().describe("Replacement text."),
5613
+ replace_all: z6.boolean().optional().describe("Replace all matches when true. Default false."),
5614
+ match_mode: z6.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
5512
5615
  "Match strategy: exact, line_trimmed, block_anchor, or auto (tries exact -> line_trimmed -> block_anchor). Default auto."
5513
5616
  ),
5514
- expected_replacements: z5.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5515
- dry_run: z5.boolean().optional().describe("Preview diff only when true. Default false."),
5516
- expected_hash: z5.string().optional().describe("Optional SHA-256 hash guard for current file content.")
5617
+ expected_replacements: z6.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5618
+ dry_run: z6.boolean().optional().describe("Preview diff only when true. Default false."),
5619
+ expected_hash: expectedContentHashSchema
5517
5620
  }),
5518
5621
  execute: async (input, ctx) => {
5519
5622
  let resolved;
@@ -5549,17 +5652,12 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool4({
5549
5652
  throw new Error(`File not found: ${input.file_path}`);
5550
5653
  }
5551
5654
  }
5552
- if (input.expected_hash) {
5553
- if (!fileExists) {
5554
- throw new Error(
5555
- `Expected hash provided but file not found: ${input.file_path}`
5556
- );
5557
- }
5558
- const currentHash = hashContent(content);
5559
- if (currentHash !== input.expected_hash) {
5560
- throw new Error(`Hash mismatch for ${input.file_path}`);
5561
- }
5562
- }
5655
+ assertExpectedContentHash({
5656
+ expectedHash: input.expected_hash,
5657
+ fileExists,
5658
+ content,
5659
+ filePath: input.file_path
5660
+ });
5563
5661
  let replacements = 0;
5564
5662
  let modeUsed = "exact";
5565
5663
  let nextContent = content;
@@ -5635,7 +5733,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool4({
5635
5733
 
5636
5734
  // src/tools/lane.ts
5637
5735
  import { defineTool as defineTool5 } from "@codelia/core";
5638
- import { z as z6 } from "zod";
5736
+ import { z as z7 } from "zod";
5639
5737
 
5640
5738
  // src/lanes/manager.ts
5641
5739
  import crypto5 from "crypto";
@@ -6207,7 +6305,7 @@ var LaneManager = class {
6207
6305
 
6208
6306
  // src/tools/lane.ts
6209
6307
  var laneManager = new LaneManager();
6210
- var backendSchema = z6.enum(["tmux", "zellij"]);
6308
+ var backendSchema = z7.enum(["tmux", "zellij"]);
6211
6309
  var formatError = (error) => {
6212
6310
  if (error instanceof LaneManagerError) {
6213
6311
  return new Error(`${error.code}: ${error.message}`);
@@ -6237,14 +6335,14 @@ var buildLaneHints = (lane) => {
6237
6335
  var createLaneCreateTool = (sandboxKey) => defineTool5({
6238
6336
  name: "lane_create",
6239
6337
  description: "Create a Task lane (worktree slot) and start autonomous execution in tmux/zellij.",
6240
- input: z6.object({
6241
- task_id: z6.string().describe("Task identifier."),
6242
- base_ref: z6.string().optional().describe("Base git ref. Default: HEAD."),
6243
- worktree_path: z6.string().optional().describe(
6338
+ input: z7.object({
6339
+ task_id: z7.string().describe("Task identifier."),
6340
+ base_ref: z7.string().optional().describe("Base git ref. Default: HEAD."),
6341
+ worktree_path: z7.string().optional().describe(
6244
6342
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
6245
6343
  ),
6246
6344
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
6247
- seed_context: z6.string().optional().describe("Optional initial text context.")
6345
+ seed_context: z7.string().optional().describe("Optional initial text context.")
6248
6346
  }),
6249
6347
  execute: async (input, ctx) => {
6250
6348
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6272,8 +6370,8 @@ var createLaneCreateTool = (sandboxKey) => defineTool5({
6272
6370
  var createLaneListTool = (sandboxKey) => defineTool5({
6273
6371
  name: "lane_list",
6274
6372
  description: "List Task lanes (worktree slots) and current states.",
6275
- input: z6.object({
6276
- include_closed: z6.boolean().optional().describe("Include closed lanes. Default: false.")
6373
+ input: z7.object({
6374
+ include_closed: z7.boolean().optional().describe("Include closed lanes. Default: false.")
6277
6375
  }),
6278
6376
  execute: async (input, ctx) => {
6279
6377
  await getSandboxContext(ctx, sandboxKey);
@@ -6296,8 +6394,8 @@ var createLaneListTool = (sandboxKey) => defineTool5({
6296
6394
  var createLaneStatusTool = (sandboxKey) => defineTool5({
6297
6395
  name: "lane_status",
6298
6396
  description: "Get Task lane status and backend liveness.",
6299
- input: z6.object({
6300
- lane_id: z6.string().describe("Lane id.")
6397
+ input: z7.object({
6398
+ lane_id: z7.string().describe("Lane id.")
6301
6399
  }),
6302
6400
  execute: async (input, ctx) => {
6303
6401
  await getSandboxContext(ctx, sandboxKey);
@@ -6315,10 +6413,10 @@ var createLaneStatusTool = (sandboxKey) => defineTool5({
6315
6413
  var createLaneCloseTool = (sandboxKey) => defineTool5({
6316
6414
  name: "lane_close",
6317
6415
  description: "Close a Task lane and optionally remove its worktree.",
6318
- input: z6.object({
6319
- lane_id: z6.string().describe("Lane id."),
6320
- remove_worktree: z6.boolean().optional().describe("Remove worktree. Default: true."),
6321
- force: z6.boolean().optional().describe("Force close/cleanup. Default: false.")
6416
+ input: z7.object({
6417
+ lane_id: z7.string().describe("Lane id."),
6418
+ remove_worktree: z7.boolean().optional().describe("Remove worktree. Default: true."),
6419
+ force: z7.boolean().optional().describe("Force close/cleanup. Default: false.")
6322
6420
  }),
6323
6421
  execute: async (input, ctx) => {
6324
6422
  await getSandboxContext(ctx, sandboxKey);
@@ -6340,10 +6438,10 @@ var createLaneCloseTool = (sandboxKey) => defineTool5({
6340
6438
  var createLaneGcTool = (sandboxKey) => defineTool5({
6341
6439
  name: "lane_gc",
6342
6440
  description: "Close stale finished/error lanes after idle TTL.",
6343
- input: z6.object({
6344
- idle_ttl_minutes: z6.number().int().positive().describe("Idle TTL in minutes."),
6345
- remove_worktree: z6.boolean().optional().describe("Remove worktree on close. Default: false."),
6346
- force: z6.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
6441
+ input: z7.object({
6442
+ idle_ttl_minutes: z7.number().int().positive().describe("Idle TTL in minutes."),
6443
+ remove_worktree: z7.boolean().optional().describe("Remove worktree on close. Default: false."),
6444
+ force: z7.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
6347
6445
  }),
6348
6446
  execute: async (input, ctx) => {
6349
6447
  await getSandboxContext(ctx, sandboxKey);
@@ -6362,7 +6460,7 @@ var createLaneGcTool = (sandboxKey) => defineTool5({
6362
6460
  // src/tools/read.ts
6363
6461
  import { promises as fs11 } from "fs";
6364
6462
  import { defineTool as defineTool6 } from "@codelia/core";
6365
- import { z as z7 } from "zod";
6463
+ import { z as z8 } from "zod";
6366
6464
  var DEFAULT_READ_LIMIT = 2e3;
6367
6465
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
6368
6466
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -6418,13 +6516,13 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
6418
6516
  };
6419
6517
  var createReadTool = (sandboxKey) => defineTool6({
6420
6518
  name: "read",
6421
- description: "Read a bounded text-file preview by 0-based line offset/limit; large output is truncated and long lines should fall back to read_line.",
6422
- input: z7.object({
6423
- file_path: z7.string().describe(
6519
+ description: "Read a bounded text-file preview by 0-based line offset/limit and return the full UTF-8 content SHA-256 metadata for edit.expected_hash; large output is truncated and long lines should fall back to read_line.",
6520
+ input: z8.object({
6521
+ file_path: z8.string().describe(
6424
6522
  "Text file path. Sandbox-bounded unless full-access mode is active."
6425
6523
  ),
6426
- offset: z7.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6427
- limit: z7.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
6524
+ offset: z8.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6525
+ limit: z8.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
6428
6526
  }),
6429
6527
  execute: async (input, ctx) => {
6430
6528
  let resolved;
@@ -6514,7 +6612,7 @@ ${truncatedLinesSummary}`;
6514
6612
 
6515
6613
  For full long-line content, use read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
6516
6614
  }
6517
- return output;
6615
+ return appendReadMetadata(output, content);
6518
6616
  } catch (error) {
6519
6617
  return `Error reading file: ${String(error)}`;
6520
6618
  }
@@ -6524,7 +6622,7 @@ For full long-line content, use read_line({"file_path":${JSON.stringify(input.fi
6524
6622
  // src/tools/read-line.ts
6525
6623
  import { promises as fs12 } from "fs";
6526
6624
  import { defineTool as defineTool7 } from "@codelia/core";
6527
- import { z as z8 } from "zod";
6625
+ import { z as z9 } from "zod";
6528
6626
  var DEFAULT_CHAR_LIMIT = 1e4;
6529
6627
  var MAX_CHAR_LIMIT = 1e5;
6530
6628
  var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
@@ -6533,14 +6631,14 @@ var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
6533
6631
  var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
6534
6632
  var createReadLineTool = (sandboxKey) => defineTool7({
6535
6633
  name: "read_line",
6536
- description: "Read one physical line as paged grapheme-based text by 1-based line number and 0-based char offset.",
6537
- input: z8.object({
6538
- file_path: z8.string().describe(
6634
+ description: "Read one physical line as paged grapheme-based text by 1-based line number and 0-based char offset, with the full UTF-8 content SHA-256 metadata for edit.expected_hash.",
6635
+ input: z9.object({
6636
+ file_path: z9.string().describe(
6539
6637
  "Text file path. Sandbox-bounded unless full-access mode is active."
6540
6638
  ),
6541
- line_number: z8.number().int().positive().describe("1-based line number to read."),
6542
- char_offset: z8.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6543
- char_limit: z8.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
6639
+ line_number: z9.number().int().positive().describe("1-based line number to read."),
6640
+ char_offset: z9.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6641
+ char_limit: z9.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
6544
6642
  `Max graphemes to return. Default 10000, Max ${MAX_CHAR_LIMIT}.`
6545
6643
  )
6546
6644
  }),
@@ -6592,7 +6690,7 @@ Use char_offset=${endOffset} to continue.`;
6592
6690
  output += `
6593
6691
  read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
6594
6692
  }
6595
- return output;
6693
+ return appendReadMetadata(output, content);
6596
6694
  } catch (error) {
6597
6695
  return `Error reading file: ${String(error)}`;
6598
6696
  }
@@ -6601,7 +6699,7 @@ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.
6601
6699
 
6602
6700
  // src/tools/search.ts
6603
6701
  import { defineTool as defineTool8 } from "@codelia/core";
6604
- import { z as z9 } from "zod";
6702
+ import { z as z10 } from "zod";
6605
6703
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
6606
6704
  var shouldKeepUrl = (url, allowedDomains) => {
6607
6705
  if (!allowedDomains.length) return true;
@@ -6720,11 +6818,11 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
6720
6818
  var createSearchTool = (options) => defineTool8({
6721
6819
  name: "search",
6722
6820
  description: "Search the web and return concise source candidates.",
6723
- input: z9.object({
6724
- query: z9.string().min(1).describe("Search query."),
6725
- max_results: z9.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
6726
- backend: z9.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
6727
- allowed_domains: z9.array(z9.string().min(1)).optional().describe("Optional allowlist of domains.")
6821
+ input: z10.object({
6822
+ query: z10.string().min(1).describe("Search query."),
6823
+ max_results: z10.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
6824
+ backend: z10.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
6825
+ allowed_domains: z10.array(z10.string().min(1)).optional().describe("Optional allowlist of domains.")
6728
6826
  }),
6729
6827
  execute: async (input) => {
6730
6828
  const backend = input.backend ?? options.defaultBackend;
@@ -6762,7 +6860,7 @@ var createSearchTool = (options) => defineTool8({
6762
6860
  import crypto7 from "crypto";
6763
6861
  import { defineTool as defineTool9 } from "@codelia/core";
6764
6862
  import { ToolOutputCacheStoreImpl } from "@codelia/storage";
6765
- import { z as z10 } from "zod";
6863
+ import { z as z11 } from "zod";
6766
6864
 
6767
6865
  // src/tasks/manager.ts
6768
6866
  import crypto6 from "crypto";
@@ -7151,6 +7249,42 @@ var TaskManager = class {
7151
7249
  }
7152
7250
  return active.handle.readOutput(stream);
7153
7251
  }
7252
+ async writeInput(taskId, input) {
7253
+ const task = await this.requireTask(taskId);
7254
+ if (isTerminalTaskState(task.state)) {
7255
+ throw new TaskManagerError(
7256
+ "task_input_unavailable",
7257
+ `Task ${taskId} is already ${task.state}.`
7258
+ );
7259
+ }
7260
+ if (task.owner_runtime_id !== this.runtimeId) {
7261
+ throw new TaskManagerError(
7262
+ "task_owned_by_other_runtime",
7263
+ `Task ${taskId} is owned by another runtime.`
7264
+ );
7265
+ }
7266
+ if (task.parent_session_id !== void 0 && task.parent_session_id !== input.sessionId) {
7267
+ throw new TaskManagerError(
7268
+ "task_owned_by_other_session",
7269
+ `Task ${taskId} belongs to another agent session.`
7270
+ );
7271
+ }
7272
+ const active = this.activeTasks.get(taskId);
7273
+ if (!active?.handle.writeInput) {
7274
+ throw new TaskManagerError(
7275
+ "task_input_unavailable",
7276
+ `Task ${taskId} has no live local stdin pipe.`
7277
+ );
7278
+ }
7279
+ const result = await active.handle.writeInput({
7280
+ text: input.text,
7281
+ close: input.close
7282
+ });
7283
+ return {
7284
+ task: await this.status(taskId) ?? task,
7285
+ result
7286
+ };
7287
+ }
7154
7288
  async wait(taskId, options = {}) {
7155
7289
  const active = this.activeTasks.get(taskId);
7156
7290
  if (active) {
@@ -7300,37 +7434,48 @@ var SHELL_LIST_DEFAULT_LIMIT = 20;
7300
7434
  var SHELL_LIST_MAX_LIMIT = 100;
7301
7435
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
7302
7436
  var SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT = false;
7303
- var shellStateSchema = z10.enum([
7437
+ var shellStdinModeSchema = z11.enum(["closed", "pipe"]);
7438
+ var shellStateSchema = z11.enum([
7304
7439
  "queued",
7305
7440
  "running",
7306
7441
  "completed",
7307
7442
  "failed",
7308
7443
  "cancelled"
7309
7444
  ]);
7310
- var shellRunSchema = z10.object({
7311
- command: z10.string().describe(
7445
+ var shellRunSchema = z11.object({
7446
+ command: z11.string().describe(
7312
7447
  "Shell command to execute as a runtime-managed child process in the current workspace."
7313
7448
  ),
7314
- label: z10.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
7449
+ label: z11.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
7315
7450
  `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
7316
7451
  ),
7317
- timeout: z10.number().int().positive().optional().describe(
7452
+ timeout: z11.number().int().positive().optional().describe(
7318
7453
  `Execution timeout in seconds. Foreground default: ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Detached-wait mode accepts larger values up to ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit to keep the managed child job running until completion, cancel, or runtime exit.`
7319
7454
  ),
7320
- detached_wait: z10.boolean().optional().describe(
7455
+ detached_wait: z11.boolean().optional().describe(
7321
7456
  "Skip the attached wait and return the task key immediately. The runtime still owns the child process. Use this only for finite jobs you will later inspect, wait on, or cancel. If you need a service-style process to keep running independently, start it with an explicit OS/shell-native out-of-process method such as `nohup`, `setsid`, `disown`, a service manager, or `docker compose up -d`, and verify readiness separately. Default: false."
7322
7457
  ),
7323
- include_stderr_on_success: z10.boolean().optional().describe(
7458
+ stdin_mode: shellStdinModeSchema.optional().describe(
7459
+ "Child stdin behavior. Default: closed (immediate EOF). Use pipe only with detached_wait=true, then send bounded UTF-8 text with shell_stdin_write."
7460
+ ),
7461
+ include_stderr_on_success: z11.boolean().optional().describe(
7324
7462
  `Include stderr when the command succeeds. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}. Set true to include success-case stderr in terminal results.`
7325
7463
  )
7326
7464
  }).superRefine((input, ctx) => {
7465
+ if (input.stdin_mode === "pipe" && input.detached_wait !== true) {
7466
+ ctx.addIssue({
7467
+ code: z11.ZodIssueCode.custom,
7468
+ path: ["stdin_mode"],
7469
+ message: "stdin_mode=pipe requires detached_wait=true."
7470
+ });
7471
+ }
7327
7472
  if (input.timeout === void 0) {
7328
7473
  return;
7329
7474
  }
7330
7475
  if (input.detached_wait ?? false) {
7331
7476
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
7332
7477
  ctx.addIssue({
7333
- code: z10.ZodIssueCode.custom,
7478
+ code: z11.ZodIssueCode.custom,
7334
7479
  path: ["timeout"],
7335
7480
  message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
7336
7481
  });
@@ -7339,39 +7484,61 @@ var shellRunSchema = z10.object({
7339
7484
  }
7340
7485
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
7341
7486
  ctx.addIssue({
7342
- code: z10.ZodIssueCode.custom,
7487
+ code: z11.ZodIssueCode.custom,
7343
7488
  path: ["timeout"],
7344
7489
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
7345
7490
  });
7346
7491
  }
7347
7492
  });
7348
- var shellTaskKeySchema = z10.object({
7349
- key: z10.string().describe("Canonical shell task key returned by shell or shell_list.")
7493
+ var shellTaskKeySchema = z11.object({
7494
+ key: z11.string().describe("Canonical shell task key returned by shell or shell_list.")
7495
+ });
7496
+ var shellStdinWriteSchema = shellTaskKeySchema.extend({
7497
+ text: z11.string().describe("UTF-8 text to write to the task stdin pipe."),
7498
+ append_newline: z11.boolean().optional().describe("Append one newline before writing. Default: false."),
7499
+ close: z11.boolean().optional().describe("Close stdin after this write completes. Default: false.")
7500
+ }).superRefine((input, ctx) => {
7501
+ const close = input.close ?? false;
7502
+ const text = `${input.text}${input.append_newline ? "\n" : ""}`;
7503
+ if (text.length === 0 && !close) {
7504
+ ctx.addIssue({
7505
+ code: z11.ZodIssueCode.custom,
7506
+ path: ["text"],
7507
+ message: "text must be non-empty unless close=true."
7508
+ });
7509
+ }
7510
+ if (utf8ByteLength3(text) > MAX_STDIN_WRITE_BYTES) {
7511
+ ctx.addIssue({
7512
+ code: z11.ZodIssueCode.custom,
7513
+ path: ["text"],
7514
+ message: `stdin writes are limited to ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes after append_newline.`
7515
+ });
7516
+ }
7350
7517
  });
7351
7518
  var shellSuccessStderrSchema = {
7352
- include_stderr_on_success: z10.boolean().optional().describe(
7519
+ include_stderr_on_success: z11.boolean().optional().describe(
7353
7520
  `Include stderr when the command succeeds. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}. Set true to include success-case stderr in terminal results.`
7354
7521
  )
7355
7522
  };
7356
7523
  var shellWaitSchema = shellTaskKeySchema.extend({
7357
- wait_timeout: z10.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
7524
+ wait_timeout: z11.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
7358
7525
  `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. If the task is still running when the window expires, the tool returns compact status JSON instead of hanging.`
7359
7526
  ),
7360
7527
  ...shellSuccessStderrSchema
7361
7528
  });
7362
7529
  var shellResultSchema = shellTaskKeySchema.extend(shellSuccessStderrSchema);
7363
- var shellStreamSchema = z10.enum(["stdout", "stderr"]);
7364
- var shellListSchema = z10.object({
7365
- limit: z10.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
7530
+ var shellStreamSchema = z11.enum(["stdout", "stderr"]);
7531
+ var shellListSchema = z11.object({
7532
+ limit: z11.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
7366
7533
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
7367
7534
  ),
7368
7535
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
7369
- include_terminal: z10.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
7536
+ include_terminal: z11.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
7370
7537
  });
7371
- var shellLogsSchema = z10.object({
7372
- key: z10.string().describe("Canonical shell task key returned by shell or shell_list."),
7538
+ var shellLogsSchema = z11.object({
7539
+ key: z11.string().describe("Canonical shell task key returned by shell or shell_list."),
7373
7540
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
7374
- tail_lines: z10.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
7541
+ tail_lines: z11.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
7375
7542
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
7376
7543
  )
7377
7544
  });
@@ -7724,7 +7891,7 @@ var createShellTool = (sandboxKey, options = {}) => {
7724
7891
  const shared = getSharedDeps(options);
7725
7892
  return defineTool9({
7726
7893
  name: "shell",
7727
- description: "Run a shell command as a runtime-managed child process in the sandbox. Terminal results use `stdout`/`stderr` stream fields; successful results suppress `stderr` by default unless `include_stderr_on_success=true`, and `shell_logs` is available when you need explicit stream reads. By default wait for completion; with `detached_wait=true`, skip the attached wait and return compact JSON with the task key for follow-up tools.",
7894
+ description: "Run a shell command as a runtime-managed child process in the sandbox. Terminal results use `stdout`/`stderr` stream fields; successful results suppress `stderr` by default unless `include_stderr_on_success=true`, and `shell_logs` is available when you need explicit stream reads. By default wait for completion with stdin closed; with `detached_wait=true`, skip the attached wait and return compact JSON with the task key. Set stdin_mode=pipe only for detached tasks that need bounded follow-up writes through shell_stdin_write.",
7728
7895
  input: shellRunSchema,
7729
7896
  execute: async (input, ctx) => {
7730
7897
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -7735,6 +7902,7 @@ var createShellTool = (sandboxKey, options = {}) => {
7735
7902
  }
7736
7903
  const label = normalizeOptionalLabel(input.label);
7737
7904
  const detachedWait = input.detached_wait ?? false;
7905
+ const stdinMode = input.stdin_mode ?? "closed";
7738
7906
  const timeoutSeconds = resolveShellTimeoutSeconds(
7739
7907
  input.timeout,
7740
7908
  detachedWait
@@ -7763,7 +7931,8 @@ var createShellTool = (sandboxKey, options = {}) => {
7763
7931
  cwd: sandbox.workingDir,
7764
7932
  timeoutSeconds,
7765
7933
  toolName: "shell",
7766
- outputCache: shared.outputCacheStore
7934
+ outputCache: shared.outputCacheStore,
7935
+ stdinMode
7767
7936
  })
7768
7937
  );
7769
7938
  if (detachedWait) {
@@ -7786,6 +7955,34 @@ var createShellTool = (sandboxKey, options = {}) => {
7786
7955
  }
7787
7956
  });
7788
7957
  };
7958
+ var createShellStdinWriteTool = (options = {}) => {
7959
+ const shared = getSharedDeps(options);
7960
+ return defineTool9({
7961
+ name: "shell_stdin_write",
7962
+ description: "Write at most 64 KiB of UTF-8 text to a live local shell task started with detached_wait=true and stdin_mode=pipe. Writes are serialized and restricted to the same runtime and originating agent session. Use shell_logs to inspect output and shell_wait for completion.",
7963
+ input: shellStdinWriteSchema,
7964
+ execute: async (input, ctx) => {
7965
+ try {
7966
+ const task = await resolveShellTask(shared.tasks, input);
7967
+ const sessionContext = options.sessionContextKey ? await getToolSessionContext(ctx, options.sessionContextKey) : null;
7968
+ const text = `${input.text}${input.append_newline ? "\n" : ""}`;
7969
+ const written = await shared.tasks.writeInput(task.task_id, {
7970
+ text,
7971
+ close: input.close ?? false,
7972
+ sessionId: sessionContext?.sessionId ?? void 0
7973
+ });
7974
+ return {
7975
+ key: getShellTaskKey(written.task),
7976
+ state: written.task.state,
7977
+ bytes_written: written.result.bytes_written,
7978
+ stdin_closed: written.result.stdin_closed
7979
+ };
7980
+ } catch (error) {
7981
+ throw formatTaskError(error);
7982
+ }
7983
+ }
7984
+ });
7985
+ };
7789
7986
  var createShellListTool = (options = {}) => {
7790
7987
  const shared = getSharedDeps(options);
7791
7988
  return defineTool9({
@@ -7931,10 +8128,10 @@ var createShellCancelTool = (options = {}) => {
7931
8128
 
7932
8129
  // src/tools/skill-load.ts
7933
8130
  import { defineTool as defineTool10 } from "@codelia/core";
7934
- import { z as z11 } from "zod";
7935
- var SkillLoadInputSchema = z11.object({
7936
- name: z11.string().min(1).optional().describe("Exact skill name to load."),
7937
- path: z11.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
8131
+ import { z as z12 } from "zod";
8132
+ var SkillLoadInputSchema = z12.object({
8133
+ name: z12.string().min(1).optional().describe("Exact skill name to load."),
8134
+ path: z12.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
7938
8135
  }).refine((value) => !!value.name || !!value.path, {
7939
8136
  message: "name or path is required",
7940
8137
  path: ["name"]
@@ -7986,16 +8183,16 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
7986
8183
 
7987
8184
  // src/tools/skill-search.ts
7988
8185
  import { defineTool as defineTool11 } from "@codelia/core";
7989
- import { z as z12 } from "zod";
8186
+ import { z as z13 } from "zod";
7990
8187
  var createSkillSearchTool = (skillsResolverKey) => defineTool11({
7991
8188
  name: "skill_search",
7992
8189
  description: "Search installed local skills by name, description, or path.",
7993
- input: z12.object({
7994
- query: z12.string().min(1).describe("Search query text."),
7995
- limit: z12.number().int().positive().optional().describe(
8190
+ input: z13.object({
8191
+ query: z13.string().min(1).describe("Search query text."),
8192
+ limit: z13.number().int().positive().optional().describe(
7996
8193
  "Optional max result count. Higher values may be clamped by config."
7997
8194
  ),
7998
- scope: z12.enum(["repo", "user"]).optional().describe("Optional scope filter.")
8195
+ scope: z13.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7999
8196
  }),
8000
8197
  execute: async (input, ctx) => {
8001
8198
  try {
@@ -8019,7 +8216,7 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
8019
8216
 
8020
8217
  // src/tools/todo-mutate.ts
8021
8218
  import { defineTool as defineTool12 } from "@codelia/core";
8022
- import { z as z13 } from "zod";
8219
+ import { z as z14 } from "zod";
8023
8220
 
8024
8221
  // src/tools/todo-store.ts
8025
8222
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -8129,37 +8326,37 @@ var pickNextTodo = (todos) => {
8129
8326
  var todoStore = /* @__PURE__ */ new Map();
8130
8327
 
8131
8328
  // src/tools/todo-mutate.ts
8132
- var todoStatusSchema = z13.enum(["pending", "in_progress", "completed"]);
8133
- var todoPrioritySchema = z13.number().int().min(1).max(5);
8134
- var todoItemSchema = z13.object({
8135
- id: z13.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
8136
- content: z13.string().min(1).describe("Todo item text."),
8329
+ var todoStatusSchema = z14.enum(["pending", "in_progress", "completed"]);
8330
+ var todoPrioritySchema = z14.number().int().min(1).max(5);
8331
+ var todoItemSchema = z14.object({
8332
+ id: z14.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
8333
+ content: z14.string().min(1).describe("Todo item text."),
8137
8334
  status: todoStatusSchema.describe("Todo status."),
8138
8335
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
8139
- notes: z13.string().optional().describe("Optional implementation notes."),
8140
- activeForm: z13.string().optional().describe("Optional in-progress phrasing for UI display.")
8336
+ notes: z14.string().optional().describe("Optional implementation notes."),
8337
+ activeForm: z14.string().optional().describe("Optional in-progress phrasing for UI display.")
8141
8338
  });
8142
- var todoPatchItemSchema = z13.object({
8143
- id: z13.string().min(1).describe("Target todo ID."),
8144
- remove: z13.boolean().optional().describe("Set true to remove the todo item."),
8145
- content: z13.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
8339
+ var todoPatchItemSchema = z14.object({
8340
+ id: z14.string().min(1).describe("Target todo ID."),
8341
+ remove: z14.boolean().optional().describe("Set true to remove the todo item."),
8342
+ content: z14.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
8146
8343
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
8147
8344
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
8148
- notes: z13.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
8149
- activeForm: z13.string().nullable().default(null).describe(
8345
+ notes: z14.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
8346
+ activeForm: z14.string().nullable().default(null).describe(
8150
8347
  "Updated in-progress phrasing (null keeps current, empty clears)."
8151
8348
  )
8152
8349
  });
8153
- var todoNewInputSchema = z13.object({
8154
- todos: z13.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
8350
+ var todoNewInputSchema = z14.object({
8351
+ todos: z14.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
8155
8352
  }).strict();
8156
- var todoAppendInputSchema = z13.object({
8157
- todos: z13.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
8353
+ var todoAppendInputSchema = z14.object({
8354
+ todos: z14.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
8158
8355
  }).strict();
8159
- var todoPatchInputSchema = z13.object({
8160
- updates: z13.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
8356
+ var todoPatchInputSchema = z14.object({
8357
+ updates: z14.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
8161
8358
  }).strict();
8162
- var todoClearInputSchema = z13.object({}).strict();
8359
+ var todoClearInputSchema = z14.object({}).strict();
8163
8360
  var statusSymbol = {
8164
8361
  pending: "[ ]",
8165
8362
  in_progress: "[>]",
@@ -8310,7 +8507,7 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
8310
8507
 
8311
8508
  // src/tools/todo-read.ts
8312
8509
  import { defineTool as defineTool13 } from "@codelia/core";
8313
- import { z as z14 } from "zod";
8510
+ import { z as z15 } from "zod";
8314
8511
  var statusSymbol2 = {
8315
8512
  pending: "[ ]",
8316
8513
  in_progress: "[>]",
@@ -8319,7 +8516,7 @@ var statusSymbol2 = {
8319
8516
  var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
8320
8517
  name: "todo_read",
8321
8518
  description: "Read the in-session todo plan with execution order and next step.",
8322
- input: z14.object({}),
8519
+ input: z15.object({}),
8323
8520
  execute: async (_input, ctx) => {
8324
8521
  const sandbox = await getSandboxContext(ctx, sandboxKey);
8325
8522
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -8356,14 +8553,14 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
8356
8553
 
8357
8554
  // src/tools/tool-output-cache.ts
8358
8555
  import { defineTool as defineTool14 } from "@codelia/core";
8359
- import { z as z15 } from "zod";
8556
+ import { z as z16 } from "zod";
8360
8557
  var createToolOutputCacheTool = (store) => defineTool14({
8361
8558
  name: "tool_output_cache",
8362
8559
  description: "Read cached tool output by ref_id.",
8363
- input: z15.object({
8364
- ref_id: z15.string().describe("Tool output reference ID."),
8365
- offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
8366
- limit: z15.number().int().positive().optional().describe("Optional max number of lines to return.")
8560
+ input: z16.object({
8561
+ ref_id: z16.string().describe("Tool output reference ID."),
8562
+ offset: z16.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
8563
+ limit: z16.number().int().positive().optional().describe("Optional max number of lines to return.")
8367
8564
  }),
8368
8565
  execute: async (input) => {
8369
8566
  if (!store.read) {
@@ -8382,11 +8579,11 @@ var createToolOutputCacheTool = (store) => defineTool14({
8382
8579
  var createToolOutputCacheLineTool = (store) => defineTool14({
8383
8580
  name: "tool_output_cache_line",
8384
8581
  description: "Read a single cached output line segment by line number and char offset.",
8385
- input: z15.object({
8386
- ref_id: z15.string().describe("Tool output reference ID."),
8387
- line_number: z15.number().int().positive().describe("1-based line number to read."),
8388
- char_offset: z15.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
8389
- char_limit: z15.number().int().positive().optional().describe("Max chars to return.")
8582
+ input: z16.object({
8583
+ ref_id: z16.string().describe("Tool output reference ID."),
8584
+ line_number: z16.number().int().positive().describe("1-based line number to read."),
8585
+ char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
8586
+ char_limit: z16.number().int().positive().optional().describe("Max chars to return.")
8390
8587
  }),
8391
8588
  execute: async (input) => {
8392
8589
  if (!store.readLine) {
@@ -8406,13 +8603,13 @@ var createToolOutputCacheLineTool = (store) => defineTool14({
8406
8603
  var createToolOutputCacheGrepTool = (store) => defineTool14({
8407
8604
  name: "tool_output_cache_grep",
8408
8605
  description: "Search cached tool output by ref_id.",
8409
- input: z15.object({
8410
- ref_id: z15.string().describe("Tool output reference ID."),
8411
- pattern: z15.string().describe("Text or regex pattern to search for."),
8412
- regex: z15.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8413
- before: z15.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8414
- after: z15.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8415
- max_matches: z15.number().int().positive().optional().describe("Maximum number of matches to return.")
8606
+ input: z16.object({
8607
+ ref_id: z16.string().describe("Tool output reference ID."),
8608
+ pattern: z16.string().describe("Text or regex pattern to search for."),
8609
+ regex: z16.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8610
+ before: z16.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8611
+ after: z16.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8612
+ max_matches: z16.number().int().positive().optional().describe("Maximum number of matches to return.")
8416
8613
  }),
8417
8614
  execute: async (input) => {
8418
8615
  if (!store.grep) {
@@ -8436,7 +8633,7 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
8436
8633
  import { promises as fs13 } from "fs";
8437
8634
  import path13 from "path";
8438
8635
  import { defineTool as defineTool15 } from "@codelia/core";
8439
- import { z as z16 } from "zod";
8636
+ import { z as z17 } from "zod";
8440
8637
  var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
8441
8638
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
8442
8639
  var MIME_BY_EXTENSION = {
@@ -8452,14 +8649,14 @@ var resolveImageMime = (filePath) => {
8452
8649
  var createViewImageTool = (sandboxKey) => defineTool15({
8453
8650
  name: "view_image",
8454
8651
  description: "Load one local png/jpeg/webp/gif image (default max 5MB) for multimodal inspection.",
8455
- input: z16.object({
8456
- file_path: z16.string().describe(
8652
+ input: z17.object({
8653
+ file_path: z17.string().describe(
8457
8654
  "Single local png/jpeg/webp/gif image path. Sandbox-bounded unless full-access mode is active."
8458
8655
  ),
8459
- detail: z16.enum(["auto", "low", "high"]).optional().describe(
8656
+ detail: z17.enum(["auto", "low", "high"]).optional().describe(
8460
8657
  "Model image-detail hint (`auto`/`low`/`high`). Default auto."
8461
8658
  ),
8462
- max_bytes: z16.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
8659
+ max_bytes: z17.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
8463
8660
  }),
8464
8661
  execute: async (input, ctx) => {
8465
8662
  let resolved;
@@ -8510,7 +8707,7 @@ var createViewImageTool = (sandboxKey) => defineTool15({
8510
8707
 
8511
8708
  // src/tools/webfetch.ts
8512
8709
  import { defineTool as defineTool16 } from "@codelia/core";
8513
- import { z as z17 } from "zod";
8710
+ import { z as z18 } from "zod";
8514
8711
  var DEFAULT_TIMEOUT_MS3 = 1e4;
8515
8712
  var MAX_TIMEOUT_MS = 3e4;
8516
8713
  var DEFAULT_MAX_BYTES3 = 2e5;
@@ -8766,13 +8963,13 @@ var classifyFetchError = (error, timeoutMs) => {
8766
8963
  var createWebfetchTool = () => defineTool16({
8767
8964
  name: "webfetch",
8768
8965
  description: "Fetch an HTTP(S) URL and return bounded normalized markdown/text/html for textual content, not binary downloads.",
8769
- input: z17.object({
8770
- url: z17.string().min(1).describe("HTTP(S) URL to fetch."),
8771
- output_format: z17.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8772
- timeout_ms: z17.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
8966
+ input: z18.object({
8967
+ url: z18.string().min(1).describe("HTTP(S) URL to fetch."),
8968
+ output_format: z18.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8969
+ timeout_ms: z18.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
8773
8970
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS3}, Max ${MAX_TIMEOUT_MS}.`
8774
8971
  ),
8775
- max_bytes: z17.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8972
+ max_bytes: z18.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8776
8973
  `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
8777
8974
  )
8778
8975
  }),
@@ -8846,15 +9043,16 @@ var createWebfetchTool = () => defineTool16({
8846
9043
  import { promises as fs14 } from "fs";
8847
9044
  import path14 from "path";
8848
9045
  import { defineTool as defineTool17 } from "@codelia/core";
8849
- import { z as z18 } from "zod";
9046
+ import { z as z19 } from "zod";
8850
9047
  var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
8851
9048
  name: "write",
8852
- description: "Write full UTF-8 text to a file, replacing any existing contents and creating parent directories if needed.",
8853
- input: z18.object({
8854
- file_path: z18.string().describe(
9049
+ description: "Write full UTF-8 text to a file, replacing any existing contents and creating parent directories if needed; supports the same full-content hash guard as edit.",
9050
+ input: z19.object({
9051
+ file_path: z19.string().describe(
8855
9052
  "File path. Sandbox-bounded unless full-access mode is active."
8856
9053
  ),
8857
- content: z18.string().describe("Full replacement UTF-8 text content to write.")
9054
+ content: z19.string().describe("Full replacement UTF-8 text content to write."),
9055
+ expected_hash: expectedContentHashSchema
8858
9056
  }),
8859
9057
  execute: async (input, ctx) => {
8860
9058
  let resolved;
@@ -8866,13 +9064,21 @@ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
8866
9064
  }
8867
9065
  try {
8868
9066
  let before = "";
9067
+ let fileExists = false;
8869
9068
  try {
8870
9069
  before = await fs14.readFile(resolved, "utf8");
9070
+ fileExists = true;
8871
9071
  } catch (error) {
8872
9072
  if (error.code !== "ENOENT") {
8873
9073
  throw error;
8874
9074
  }
8875
9075
  }
9076
+ assertExpectedContentHash({
9077
+ expectedHash: input.expected_hash,
9078
+ fileExists,
9079
+ content: before,
9080
+ filePath: input.file_path
9081
+ });
8876
9082
  await fs14.mkdir(path14.dirname(resolved), { recursive: true });
8877
9083
  await fs14.writeFile(resolved, input.content, "utf8");
8878
9084
  const diffPayload = await buildDiffPayload({
@@ -8902,6 +9108,11 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
8902
9108
  outputCacheStore: options.toolOutputCacheStore,
8903
9109
  sessionContextKey: options.todoSessionContextKey
8904
9110
  }),
9111
+ createShellStdinWriteTool({
9112
+ taskManager: options.taskManager,
9113
+ outputCacheStore: options.toolOutputCacheStore,
9114
+ sessionContextKey: options.todoSessionContextKey
9115
+ }),
8905
9116
  createShellListTool({
8906
9117
  taskManager: options.taskManager,
8907
9118
  outputCacheStore: options.toolOutputCacheStore