@codelia/runtime 0.1.72 → 0.1.75

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.
package/dist/sdk.cjs CHANGED
@@ -1935,6 +1935,7 @@ var import_node_path3 = __toESM(require("path"), 1);
1935
1935
 
1936
1936
  // src/tasks/shell-executor.ts
1937
1937
  var import_node_child_process3 = require("child_process");
1938
+ var import_node_perf_hooks = require("perf_hooks");
1938
1939
 
1939
1940
  // src/tools/bash-utils.ts
1940
1941
  var import_node_child_process2 = require("child_process");
@@ -1958,6 +1959,10 @@ var summarizeCommand = (command) => {
1958
1959
  var DEFAULT_EXCERPT_LINES = 80;
1959
1960
  var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
1960
1961
  var FORCE_KILL_DELAY_MS = 2e3;
1962
+ var MAX_STDIN_WRITE_BYTES = 64 * 1024;
1963
+ var DEFAULT_STDIN_WRITE_TIMEOUT_MS = 3e4;
1964
+ var defaultMonotonicNowMs = () => import_node_perf_hooks.performance.now();
1965
+ var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
1961
1966
  var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
1962
1967
  var truncateUtf8Prefix = (value, maxBytes) => {
1963
1968
  if (maxBytes <= 0 || value.length === 0) return "";
@@ -2050,19 +2055,20 @@ var buildShellTaskResult = async (outputCache, options) => {
2050
2055
  ...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
2051
2056
  };
2052
2057
  };
2053
- var spawnShellProcess = (command, cwd) => {
2058
+ var spawnShellProcess = (command, cwd, stdinMode) => {
2059
+ const stdin = stdinMode === "pipe" ? "pipe" : "ignore";
2054
2060
  const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
2055
2061
  if (shellPath) {
2056
2062
  return (0, import_node_child_process3.spawn)(shellPath, ["-lc", command], {
2057
2063
  cwd,
2058
- stdio: ["ignore", "pipe", "pipe"],
2064
+ stdio: [stdin, "pipe", "pipe"],
2059
2065
  detached: true
2060
2066
  });
2061
2067
  }
2062
2068
  return (0, import_node_child_process3.spawn)(command, {
2063
2069
  cwd,
2064
2070
  shell: true,
2065
- stdio: ["ignore", "pipe", "pipe"],
2071
+ stdio: [stdin, "pipe", "pipe"],
2066
2072
  detached: process.platform !== "win32"
2067
2073
  });
2068
2074
  };
@@ -2087,11 +2093,18 @@ var startShellTask = (options) => {
2087
2093
  }
2088
2094
  const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
2089
2095
  const forceKillDelayMs = options.forceKillDelayMs ?? FORCE_KILL_DELAY_MS;
2090
- const startedAt = Date.now();
2096
+ const monotonicNowMs = options.monotonicNowMs ?? defaultMonotonicNowMs;
2097
+ const stdinMode = options.stdinMode ?? "closed";
2098
+ const stdinWriteTimeoutMs = options.stdinWriteTimeoutMs ?? DEFAULT_STDIN_WRITE_TIMEOUT_MS;
2099
+ const monotonicStartedAt = monotonicNowMs();
2091
2100
  const child = (options.spawnProcess ?? spawnShellProcess)(
2092
2101
  options.command,
2093
- options.cwd
2102
+ options.cwd,
2103
+ stdinMode
2094
2104
  );
2105
+ if (stdinMode === "pipe" && child.stdin === null) {
2106
+ throw new Error("stdin_mode=pipe requires a writable child stdin stream");
2107
+ }
2095
2108
  const metadata = typeof child.pid === "number" ? {
2096
2109
  executor_pid: child.pid,
2097
2110
  executor_pgid: process.platform === "win32" ? void 0 : child.pid
@@ -2103,6 +2116,51 @@ var startShellTask = (options) => {
2103
2116
  let cancelRequested = false;
2104
2117
  let timeoutHandle;
2105
2118
  let forceKillHandle;
2119
+ let stdinClosed = stdinMode === "closed";
2120
+ let stdinWriteQueue = Promise.resolve();
2121
+ const markStdinClosed = () => {
2122
+ if (stdinClosed) return;
2123
+ stdinClosed = true;
2124
+ };
2125
+ const invalidateStdin = () => {
2126
+ if (stdinClosed) return;
2127
+ markStdinClosed();
2128
+ child.stdin?.destroy();
2129
+ };
2130
+ const performStdinWrite = async (input) => {
2131
+ if (stdinMode !== "pipe" || child.stdin === null) {
2132
+ throw new Error("stdin was not opened as a pipe");
2133
+ }
2134
+ const stdin = child.stdin;
2135
+ if (settled) throw new Error("task is already terminal");
2136
+ if (stdinClosed || stdin.destroyed || stdin.writableEnded) {
2137
+ throw new Error("stdin is already closed");
2138
+ }
2139
+ const bytesWritten = utf8ByteLength(input.text);
2140
+ if (bytesWritten > MAX_STDIN_WRITE_BYTES) {
2141
+ throw new Error(
2142
+ `stdin write exceeds ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes`
2143
+ );
2144
+ }
2145
+ if (bytesWritten > 0) {
2146
+ await new Promise((resolve, reject) => {
2147
+ const timer = setTimeout(() => {
2148
+ invalidateStdin();
2149
+ reject(new Error("stdin write timed out waiting for backpressure"));
2150
+ }, stdinWriteTimeoutMs);
2151
+ stdin.write(input.text, "utf8", (error) => {
2152
+ clearTimeout(timer);
2153
+ if (error) reject(error);
2154
+ else resolve();
2155
+ });
2156
+ });
2157
+ }
2158
+ if (input.close) {
2159
+ markStdinClosed();
2160
+ stdin.end();
2161
+ }
2162
+ return { bytes_written: bytesWritten, stdin_closed: stdinClosed };
2163
+ };
2106
2164
  const clearForceKillHandle = () => {
2107
2165
  if (!forceKillHandle) return;
2108
2166
  clearTimeout(forceKillHandle);
@@ -2119,7 +2177,12 @@ var startShellTask = (options) => {
2119
2177
  const settle = async (outcome) => {
2120
2178
  if (settled) return;
2121
2179
  settled = true;
2180
+ invalidateStdin();
2122
2181
  if (timeoutHandle) clearTimeout(timeoutHandle);
2182
+ const durationMs = elapsedMilliseconds(
2183
+ monotonicStartedAt,
2184
+ monotonicNowMs
2185
+ );
2123
2186
  let result;
2124
2187
  try {
2125
2188
  result = await buildShellTaskResult(options.outputCache, {
@@ -2129,7 +2192,7 @@ var startShellTask = (options) => {
2129
2192
  rawStderr: stderr,
2130
2193
  exitCode: outcome.exitCode,
2131
2194
  signal: outcome.signal,
2132
- durationMs: Date.now() - startedAt
2195
+ durationMs
2133
2196
  });
2134
2197
  } catch {
2135
2198
  result = buildShellTaskResultBase({
@@ -2137,7 +2200,7 @@ var startShellTask = (options) => {
2137
2200
  rawStderr: stderr,
2138
2201
  exitCode: outcome.exitCode,
2139
2202
  signal: outcome.signal,
2140
- durationMs: Date.now() - startedAt
2203
+ durationMs
2141
2204
  });
2142
2205
  }
2143
2206
  resolve({
@@ -2220,8 +2283,19 @@ var startShellTask = (options) => {
2220
2283
  metadata,
2221
2284
  wait,
2222
2285
  readOutput: async (stream) => stream === "stdout" ? stdout : stderr,
2286
+ ...stdinMode === "pipe" ? {
2287
+ writeInput: (input) => {
2288
+ const write = stdinWriteQueue.then(() => performStdinWrite(input));
2289
+ stdinWriteQueue = write.then(
2290
+ () => void 0,
2291
+ () => void 0
2292
+ );
2293
+ return write;
2294
+ }
2295
+ } : {},
2223
2296
  cancel: async () => {
2224
2297
  if (settled) return;
2298
+ invalidateStdin();
2225
2299
  cancelRequested = true;
2226
2300
  terminateChild(child, "SIGTERM");
2227
2301
  scheduleForceKill();
@@ -3574,6 +3648,7 @@ var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
3574
3648
  "shell_wait",
3575
3649
  "shell_result",
3576
3650
  "shell_cancel",
3651
+ "shell_stdin_write",
3577
3652
  "lane_list",
3578
3653
  "lane_status",
3579
3654
  "done"
@@ -5381,11 +5456,40 @@ var createDoneTool = () => (0, import_core6.defineTool)({
5381
5456
  });
5382
5457
 
5383
5458
  // src/tools/edit.ts
5384
- var import_node_crypto4 = __toESM(require("crypto"), 1);
5385
5459
  var import_node_fs8 = require("fs");
5386
5460
  var import_node_path10 = __toESM(require("path"), 1);
5387
5461
  var import_core7 = require("@codelia/core");
5462
+ var import_zod6 = require("zod");
5463
+
5464
+ // src/tools/content-hash.ts
5465
+ var import_node_crypto4 = __toESM(require("crypto"), 1);
5388
5466
  var import_zod5 = require("zod");
5467
+ var CONTENT_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5468
+ var expectedContentHashSchema = import_zod5.z.string().regex(
5469
+ CONTENT_SHA256_PATTERN,
5470
+ "expected_hash must be a lowercase 64-character SHA-256 hash"
5471
+ ).optional().describe(
5472
+ "Current full-content SHA-256 guard from read/read_line metadata. Omit when unavailable."
5473
+ );
5474
+ var hashUtf8Content = (content) => import_node_crypto4.default.createHash("sha256").update(content).digest("hex");
5475
+ var assertExpectedContentHash = (input) => {
5476
+ if (!input.expectedHash) return;
5477
+ if (!input.fileExists) {
5478
+ throw new Error(
5479
+ `Expected hash provided but file not found: ${input.filePath}`
5480
+ );
5481
+ }
5482
+ if (hashUtf8Content(input.content) !== input.expectedHash) {
5483
+ throw new Error(
5484
+ `Hash mismatch for ${input.filePath}. The file changed since it was read; read it again and retry with the new content_sha256.`
5485
+ );
5486
+ }
5487
+ };
5488
+ var appendReadMetadata = (output, content) => `${output}
5489
+
5490
+ [read_metadata] content_sha256=${hashUtf8Content(content)}`;
5491
+
5492
+ // src/tools/edit.ts
5389
5493
  var trimLine = (line) => line.replace(/\r$/, "").trim();
5390
5494
  var lineRangeToIndices = (lines, startLine, lineCount) => {
5391
5495
  let startIndex = 0;
@@ -5492,25 +5596,24 @@ var applyReplacements = (content, matches, replacement) => {
5492
5596
  }
5493
5597
  return next;
5494
5598
  };
5495
- var hashContent = (content) => import_node_crypto4.default.createHash("sha256").update(content).digest("hex");
5496
5599
  var createEditTool = (sandboxKey, outputCacheStore) => (0, import_core7.defineTool)({
5497
5600
  name: "edit",
5498
5601
  description: "Edit a file by replacing matched text with new text; supports guarded match modes and dry-run preview.",
5499
- input: import_zod5.z.object({
5500
- file_path: import_zod5.z.string().describe(
5602
+ input: import_zod6.z.object({
5603
+ file_path: import_zod6.z.string().describe(
5501
5604
  "File path. Sandbox-bounded unless full-access mode is active."
5502
5605
  ),
5503
- old_string: import_zod5.z.string().describe(
5606
+ old_string: import_zod6.z.string().describe(
5504
5607
  "Text to find. Use empty string to replace the whole file content."
5505
5608
  ),
5506
- new_string: import_zod5.z.string().describe("Replacement text."),
5507
- replace_all: import_zod5.z.boolean().optional().describe("Replace all matches when true. Default false."),
5508
- match_mode: import_zod5.z.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
5609
+ new_string: import_zod6.z.string().describe("Replacement text."),
5610
+ replace_all: import_zod6.z.boolean().optional().describe("Replace all matches when true. Default false."),
5611
+ match_mode: import_zod6.z.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
5509
5612
  "Match strategy: exact, line_trimmed, block_anchor, or auto (tries exact -> line_trimmed -> block_anchor). Default auto."
5510
5613
  ),
5511
- expected_replacements: import_zod5.z.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5512
- dry_run: import_zod5.z.boolean().optional().describe("Preview diff only when true. Default false."),
5513
- expected_hash: import_zod5.z.string().optional().describe("Optional SHA-256 hash guard for current file content.")
5614
+ expected_replacements: import_zod6.z.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5615
+ dry_run: import_zod6.z.boolean().optional().describe("Preview diff only when true. Default false."),
5616
+ expected_hash: expectedContentHashSchema
5514
5617
  }),
5515
5618
  execute: async (input, ctx) => {
5516
5619
  let resolved;
@@ -5546,17 +5649,12 @@ var createEditTool = (sandboxKey, outputCacheStore) => (0, import_core7.defineTo
5546
5649
  throw new Error(`File not found: ${input.file_path}`);
5547
5650
  }
5548
5651
  }
5549
- if (input.expected_hash) {
5550
- if (!fileExists) {
5551
- throw new Error(
5552
- `Expected hash provided but file not found: ${input.file_path}`
5553
- );
5554
- }
5555
- const currentHash = hashContent(content);
5556
- if (currentHash !== input.expected_hash) {
5557
- throw new Error(`Hash mismatch for ${input.file_path}`);
5558
- }
5559
- }
5652
+ assertExpectedContentHash({
5653
+ expectedHash: input.expected_hash,
5654
+ fileExists,
5655
+ content,
5656
+ filePath: input.file_path
5657
+ });
5560
5658
  let replacements = 0;
5561
5659
  let modeUsed = "exact";
5562
5660
  let nextContent = content;
@@ -5632,7 +5730,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => (0, import_core7.defineTo
5632
5730
 
5633
5731
  // src/tools/lane.ts
5634
5732
  var import_core8 = require("@codelia/core");
5635
- var import_zod6 = require("zod");
5733
+ var import_zod7 = require("zod");
5636
5734
 
5637
5735
  // src/lanes/manager.ts
5638
5736
  var import_node_crypto5 = __toESM(require("crypto"), 1);
@@ -6204,7 +6302,7 @@ var LaneManager = class {
6204
6302
 
6205
6303
  // src/tools/lane.ts
6206
6304
  var laneManager = new LaneManager();
6207
- var backendSchema = import_zod6.z.enum(["tmux", "zellij"]);
6305
+ var backendSchema = import_zod7.z.enum(["tmux", "zellij"]);
6208
6306
  var formatError = (error) => {
6209
6307
  if (error instanceof LaneManagerError) {
6210
6308
  return new Error(`${error.code}: ${error.message}`);
@@ -6234,14 +6332,14 @@ var buildLaneHints = (lane) => {
6234
6332
  var createLaneCreateTool = (sandboxKey) => (0, import_core8.defineTool)({
6235
6333
  name: "lane_create",
6236
6334
  description: "Create a Task lane (worktree slot) and start autonomous execution in tmux/zellij.",
6237
- input: import_zod6.z.object({
6238
- task_id: import_zod6.z.string().describe("Task identifier."),
6239
- base_ref: import_zod6.z.string().optional().describe("Base git ref. Default: HEAD."),
6240
- worktree_path: import_zod6.z.string().optional().describe(
6335
+ input: import_zod7.z.object({
6336
+ task_id: import_zod7.z.string().describe("Task identifier."),
6337
+ base_ref: import_zod7.z.string().optional().describe("Base git ref. Default: HEAD."),
6338
+ worktree_path: import_zod7.z.string().optional().describe(
6241
6339
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
6242
6340
  ),
6243
6341
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
6244
- seed_context: import_zod6.z.string().optional().describe("Optional initial text context.")
6342
+ seed_context: import_zod7.z.string().optional().describe("Optional initial text context.")
6245
6343
  }),
6246
6344
  execute: async (input, ctx) => {
6247
6345
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6269,8 +6367,8 @@ var createLaneCreateTool = (sandboxKey) => (0, import_core8.defineTool)({
6269
6367
  var createLaneListTool = (sandboxKey) => (0, import_core8.defineTool)({
6270
6368
  name: "lane_list",
6271
6369
  description: "List Task lanes (worktree slots) and current states.",
6272
- input: import_zod6.z.object({
6273
- include_closed: import_zod6.z.boolean().optional().describe("Include closed lanes. Default: false.")
6370
+ input: import_zod7.z.object({
6371
+ include_closed: import_zod7.z.boolean().optional().describe("Include closed lanes. Default: false.")
6274
6372
  }),
6275
6373
  execute: async (input, ctx) => {
6276
6374
  await getSandboxContext(ctx, sandboxKey);
@@ -6293,8 +6391,8 @@ var createLaneListTool = (sandboxKey) => (0, import_core8.defineTool)({
6293
6391
  var createLaneStatusTool = (sandboxKey) => (0, import_core8.defineTool)({
6294
6392
  name: "lane_status",
6295
6393
  description: "Get Task lane status and backend liveness.",
6296
- input: import_zod6.z.object({
6297
- lane_id: import_zod6.z.string().describe("Lane id.")
6394
+ input: import_zod7.z.object({
6395
+ lane_id: import_zod7.z.string().describe("Lane id.")
6298
6396
  }),
6299
6397
  execute: async (input, ctx) => {
6300
6398
  await getSandboxContext(ctx, sandboxKey);
@@ -6312,10 +6410,10 @@ var createLaneStatusTool = (sandboxKey) => (0, import_core8.defineTool)({
6312
6410
  var createLaneCloseTool = (sandboxKey) => (0, import_core8.defineTool)({
6313
6411
  name: "lane_close",
6314
6412
  description: "Close a Task lane and optionally remove its worktree.",
6315
- input: import_zod6.z.object({
6316
- lane_id: import_zod6.z.string().describe("Lane id."),
6317
- remove_worktree: import_zod6.z.boolean().optional().describe("Remove worktree. Default: true."),
6318
- force: import_zod6.z.boolean().optional().describe("Force close/cleanup. Default: false.")
6413
+ input: import_zod7.z.object({
6414
+ lane_id: import_zod7.z.string().describe("Lane id."),
6415
+ remove_worktree: import_zod7.z.boolean().optional().describe("Remove worktree. Default: true."),
6416
+ force: import_zod7.z.boolean().optional().describe("Force close/cleanup. Default: false.")
6319
6417
  }),
6320
6418
  execute: async (input, ctx) => {
6321
6419
  await getSandboxContext(ctx, sandboxKey);
@@ -6337,10 +6435,10 @@ var createLaneCloseTool = (sandboxKey) => (0, import_core8.defineTool)({
6337
6435
  var createLaneGcTool = (sandboxKey) => (0, import_core8.defineTool)({
6338
6436
  name: "lane_gc",
6339
6437
  description: "Close stale finished/error lanes after idle TTL.",
6340
- input: import_zod6.z.object({
6341
- idle_ttl_minutes: import_zod6.z.number().int().positive().describe("Idle TTL in minutes."),
6342
- remove_worktree: import_zod6.z.boolean().optional().describe("Remove worktree on close. Default: false."),
6343
- force: import_zod6.z.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
6438
+ input: import_zod7.z.object({
6439
+ idle_ttl_minutes: import_zod7.z.number().int().positive().describe("Idle TTL in minutes."),
6440
+ remove_worktree: import_zod7.z.boolean().optional().describe("Remove worktree on close. Default: false."),
6441
+ force: import_zod7.z.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
6344
6442
  }),
6345
6443
  execute: async (input, ctx) => {
6346
6444
  await getSandboxContext(ctx, sandboxKey);
@@ -6359,7 +6457,7 @@ var createLaneGcTool = (sandboxKey) => (0, import_core8.defineTool)({
6359
6457
  // src/tools/read.ts
6360
6458
  var import_node_fs11 = require("fs");
6361
6459
  var import_core9 = require("@codelia/core");
6362
- var import_zod7 = require("zod");
6460
+ var import_zod8 = require("zod");
6363
6461
  var DEFAULT_READ_LIMIT = 2e3;
6364
6462
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
6365
6463
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -6415,13 +6513,13 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
6415
6513
  };
6416
6514
  var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
6417
6515
  name: "read",
6418
- 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.",
6419
- input: import_zod7.z.object({
6420
- file_path: import_zod7.z.string().describe(
6516
+ 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.",
6517
+ input: import_zod8.z.object({
6518
+ file_path: import_zod8.z.string().describe(
6421
6519
  "Text file path. Sandbox-bounded unless full-access mode is active."
6422
6520
  ),
6423
- offset: import_zod7.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6424
- limit: import_zod7.z.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
6521
+ offset: import_zod8.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6522
+ limit: import_zod8.z.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
6425
6523
  }),
6426
6524
  execute: async (input, ctx) => {
6427
6525
  let resolved;
@@ -6511,7 +6609,7 @@ ${truncatedLinesSummary}`;
6511
6609
 
6512
6610
  For full long-line content, use read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
6513
6611
  }
6514
- return output;
6612
+ return appendReadMetadata(output, content);
6515
6613
  } catch (error) {
6516
6614
  return `Error reading file: ${String(error)}`;
6517
6615
  }
@@ -6521,7 +6619,7 @@ For full long-line content, use read_line({"file_path":${JSON.stringify(input.fi
6521
6619
  // src/tools/read-line.ts
6522
6620
  var import_node_fs12 = require("fs");
6523
6621
  var import_core10 = require("@codelia/core");
6524
- var import_zod8 = require("zod");
6622
+ var import_zod9 = require("zod");
6525
6623
  var DEFAULT_CHAR_LIMIT = 1e4;
6526
6624
  var MAX_CHAR_LIMIT = 1e5;
6527
6625
  var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
@@ -6530,14 +6628,14 @@ var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
6530
6628
  var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
6531
6629
  var createReadLineTool = (sandboxKey) => (0, import_core10.defineTool)({
6532
6630
  name: "read_line",
6533
- description: "Read one physical line as paged grapheme-based text by 1-based line number and 0-based char offset.",
6534
- input: import_zod8.z.object({
6535
- file_path: import_zod8.z.string().describe(
6631
+ 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.",
6632
+ input: import_zod9.z.object({
6633
+ file_path: import_zod9.z.string().describe(
6536
6634
  "Text file path. Sandbox-bounded unless full-access mode is active."
6537
6635
  ),
6538
- line_number: import_zod8.z.number().int().positive().describe("1-based line number to read."),
6539
- char_offset: import_zod8.z.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6540
- char_limit: import_zod8.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
6636
+ line_number: import_zod9.z.number().int().positive().describe("1-based line number to read."),
6637
+ char_offset: import_zod9.z.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6638
+ char_limit: import_zod9.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
6541
6639
  `Max graphemes to return. Default 10000, Max ${MAX_CHAR_LIMIT}.`
6542
6640
  )
6543
6641
  }),
@@ -6589,7 +6687,7 @@ Use char_offset=${endOffset} to continue.`;
6589
6687
  output += `
6590
6688
  read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
6591
6689
  }
6592
- return output;
6690
+ return appendReadMetadata(output, content);
6593
6691
  } catch (error) {
6594
6692
  return `Error reading file: ${String(error)}`;
6595
6693
  }
@@ -6598,7 +6696,7 @@ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.
6598
6696
 
6599
6697
  // src/tools/search.ts
6600
6698
  var import_core11 = require("@codelia/core");
6601
- var import_zod9 = require("zod");
6699
+ var import_zod10 = require("zod");
6602
6700
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
6603
6701
  var shouldKeepUrl = (url, allowedDomains) => {
6604
6702
  if (!allowedDomains.length) return true;
@@ -6717,11 +6815,11 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
6717
6815
  var createSearchTool = (options) => (0, import_core11.defineTool)({
6718
6816
  name: "search",
6719
6817
  description: "Search the web and return concise source candidates.",
6720
- input: import_zod9.z.object({
6721
- query: import_zod9.z.string().min(1).describe("Search query."),
6722
- max_results: import_zod9.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
6723
- backend: import_zod9.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
6724
- allowed_domains: import_zod9.z.array(import_zod9.z.string().min(1)).optional().describe("Optional allowlist of domains.")
6818
+ input: import_zod10.z.object({
6819
+ query: import_zod10.z.string().min(1).describe("Search query."),
6820
+ max_results: import_zod10.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
6821
+ backend: import_zod10.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
6822
+ allowed_domains: import_zod10.z.array(import_zod10.z.string().min(1)).optional().describe("Optional allowlist of domains.")
6725
6823
  }),
6726
6824
  execute: async (input) => {
6727
6825
  const backend = input.backend ?? options.defaultBackend;
@@ -6759,7 +6857,7 @@ var createSearchTool = (options) => (0, import_core11.defineTool)({
6759
6857
  var import_node_crypto7 = __toESM(require("crypto"), 1);
6760
6858
  var import_core12 = require("@codelia/core");
6761
6859
  var import_storage7 = require("@codelia/storage");
6762
- var import_zod10 = require("zod");
6860
+ var import_zod11 = require("zod");
6763
6861
 
6764
6862
  // src/tasks/manager.ts
6765
6863
  var import_node_crypto6 = __toESM(require("crypto"), 1);
@@ -7146,6 +7244,42 @@ var TaskManager = class {
7146
7244
  }
7147
7245
  return active.handle.readOutput(stream);
7148
7246
  }
7247
+ async writeInput(taskId, input) {
7248
+ const task = await this.requireTask(taskId);
7249
+ if (isTerminalTaskState(task.state)) {
7250
+ throw new TaskManagerError(
7251
+ "task_input_unavailable",
7252
+ `Task ${taskId} is already ${task.state}.`
7253
+ );
7254
+ }
7255
+ if (task.owner_runtime_id !== this.runtimeId) {
7256
+ throw new TaskManagerError(
7257
+ "task_owned_by_other_runtime",
7258
+ `Task ${taskId} is owned by another runtime.`
7259
+ );
7260
+ }
7261
+ if (task.parent_session_id !== void 0 && task.parent_session_id !== input.sessionId) {
7262
+ throw new TaskManagerError(
7263
+ "task_owned_by_other_session",
7264
+ `Task ${taskId} belongs to another agent session.`
7265
+ );
7266
+ }
7267
+ const active = this.activeTasks.get(taskId);
7268
+ if (!active?.handle.writeInput) {
7269
+ throw new TaskManagerError(
7270
+ "task_input_unavailable",
7271
+ `Task ${taskId} has no live local stdin pipe.`
7272
+ );
7273
+ }
7274
+ const result = await active.handle.writeInput({
7275
+ text: input.text,
7276
+ close: input.close
7277
+ });
7278
+ return {
7279
+ task: await this.status(taskId) ?? task,
7280
+ result
7281
+ };
7282
+ }
7149
7283
  async wait(taskId, options = {}) {
7150
7284
  const active = this.activeTasks.get(taskId);
7151
7285
  if (active) {
@@ -7295,37 +7429,48 @@ var SHELL_LIST_DEFAULT_LIMIT = 20;
7295
7429
  var SHELL_LIST_MAX_LIMIT = 100;
7296
7430
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
7297
7431
  var SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT = false;
7298
- var shellStateSchema = import_zod10.z.enum([
7432
+ var shellStdinModeSchema = import_zod11.z.enum(["closed", "pipe"]);
7433
+ var shellStateSchema = import_zod11.z.enum([
7299
7434
  "queued",
7300
7435
  "running",
7301
7436
  "completed",
7302
7437
  "failed",
7303
7438
  "cancelled"
7304
7439
  ]);
7305
- var shellRunSchema = import_zod10.z.object({
7306
- command: import_zod10.z.string().describe(
7440
+ var shellRunSchema = import_zod11.z.object({
7441
+ command: import_zod11.z.string().describe(
7307
7442
  "Shell command to execute as a runtime-managed child process in the current workspace."
7308
7443
  ),
7309
- label: import_zod10.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
7310
- `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
7444
+ label: import_zod11.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
7445
+ `Short label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
7446
+ ),
7447
+ timeout: import_zod11.z.number().int().positive().optional().describe(
7448
+ `Execution timeout in seconds. Foreground: default ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Detached: max ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit for no execution timer.`
7311
7449
  ),
7312
- timeout: import_zod10.z.number().int().positive().optional().describe(
7313
- `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.`
7450
+ detached_wait: import_zod11.z.boolean().optional().describe(
7451
+ "Return a task key immediately instead of waiting. The runtime owns the child until completion, cancellation, or runtime exit; use follow-up shell tools. Default: false."
7314
7452
  ),
7315
- detached_wait: import_zod10.z.boolean().optional().describe(
7316
- "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."
7453
+ stdin_mode: shellStdinModeSchema.optional().describe(
7454
+ "Child stdin: closed (default) or pipe. pipe requires detached_wait=true and shell_stdin_write."
7317
7455
  ),
7318
- include_stderr_on_success: import_zod10.z.boolean().optional().describe(
7319
- `Include stderr when the command succeeds. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}. Set true to include success-case stderr in terminal results.`
7456
+ include_stderr_on_success: import_zod11.z.boolean().optional().describe(
7457
+ `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
7320
7458
  )
7321
7459
  }).superRefine((input, ctx) => {
7460
+ if (input.stdin_mode === "pipe" && input.detached_wait !== true) {
7461
+ ctx.addIssue({
7462
+ code: import_zod11.z.ZodIssueCode.custom,
7463
+ path: ["stdin_mode"],
7464
+ message: "stdin_mode=pipe requires detached_wait=true."
7465
+ });
7466
+ }
7322
7467
  if (input.timeout === void 0) {
7323
7468
  return;
7324
7469
  }
7325
7470
  if (input.detached_wait ?? false) {
7326
7471
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
7327
7472
  ctx.addIssue({
7328
- code: import_zod10.z.ZodIssueCode.custom,
7473
+ code: import_zod11.z.ZodIssueCode.custom,
7329
7474
  path: ["timeout"],
7330
7475
  message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
7331
7476
  });
@@ -7334,39 +7479,61 @@ var shellRunSchema = import_zod10.z.object({
7334
7479
  }
7335
7480
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
7336
7481
  ctx.addIssue({
7337
- code: import_zod10.z.ZodIssueCode.custom,
7482
+ code: import_zod11.z.ZodIssueCode.custom,
7338
7483
  path: ["timeout"],
7339
7484
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
7340
7485
  });
7341
7486
  }
7342
7487
  });
7343
- var shellTaskKeySchema = import_zod10.z.object({
7344
- key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list.")
7488
+ var shellTaskKeySchema = import_zod11.z.object({
7489
+ key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list.")
7490
+ });
7491
+ var shellStdinWriteSchema = shellTaskKeySchema.extend({
7492
+ text: import_zod11.z.string().describe("UTF-8 text to write to the task stdin pipe."),
7493
+ append_newline: import_zod11.z.boolean().optional().describe("Append one newline before writing. Default: false."),
7494
+ close: import_zod11.z.boolean().optional().describe("Close stdin after this write completes. Default: false.")
7495
+ }).superRefine((input, ctx) => {
7496
+ const close = input.close ?? false;
7497
+ const text = `${input.text}${input.append_newline ? "\n" : ""}`;
7498
+ if (text.length === 0 && !close) {
7499
+ ctx.addIssue({
7500
+ code: import_zod11.z.ZodIssueCode.custom,
7501
+ path: ["text"],
7502
+ message: "text must be non-empty unless close=true."
7503
+ });
7504
+ }
7505
+ if (utf8ByteLength3(text) > MAX_STDIN_WRITE_BYTES) {
7506
+ ctx.addIssue({
7507
+ code: import_zod11.z.ZodIssueCode.custom,
7508
+ path: ["text"],
7509
+ message: `stdin writes are limited to ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes after append_newline.`
7510
+ });
7511
+ }
7345
7512
  });
7346
7513
  var shellSuccessStderrSchema = {
7347
- include_stderr_on_success: import_zod10.z.boolean().optional().describe(
7348
- `Include stderr when the command succeeds. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}. Set true to include success-case stderr in terminal results.`
7514
+ include_stderr_on_success: import_zod11.z.boolean().optional().describe(
7515
+ `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
7349
7516
  )
7350
7517
  };
7351
7518
  var shellWaitSchema = shellTaskKeySchema.extend({
7352
- wait_timeout: import_zod10.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
7519
+ wait_timeout: import_zod11.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
7353
7520
  `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.`
7354
7521
  ),
7355
7522
  ...shellSuccessStderrSchema
7356
7523
  });
7357
7524
  var shellResultSchema = shellTaskKeySchema.extend(shellSuccessStderrSchema);
7358
- var shellStreamSchema = import_zod10.z.enum(["stdout", "stderr"]);
7359
- var shellListSchema = import_zod10.z.object({
7360
- limit: import_zod10.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
7525
+ var shellStreamSchema = import_zod11.z.enum(["stdout", "stderr"]);
7526
+ var shellListSchema = import_zod11.z.object({
7527
+ limit: import_zod11.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
7361
7528
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
7362
7529
  ),
7363
7530
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
7364
- include_terminal: import_zod10.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
7531
+ include_terminal: import_zod11.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
7365
7532
  });
7366
- var shellLogsSchema = import_zod10.z.object({
7367
- key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list."),
7533
+ var shellLogsSchema = import_zod11.z.object({
7534
+ key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list."),
7368
7535
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
7369
- tail_lines: import_zod10.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
7536
+ tail_lines: import_zod11.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
7370
7537
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
7371
7538
  )
7372
7539
  });
@@ -7719,7 +7886,7 @@ var createShellTool = (sandboxKey, options = {}) => {
7719
7886
  const shared = getSharedDeps(options);
7720
7887
  return (0, import_core12.defineTool)({
7721
7888
  name: "shell",
7722
- 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.",
7889
+ description: "Run a shell command as a managed child process in the sandbox. It waits with stdin closed by default; use detached_wait for a task key and stdin_mode=pipe only when follow-up shell_stdin_write calls are needed.",
7723
7890
  input: shellRunSchema,
7724
7891
  execute: async (input, ctx) => {
7725
7892
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -7730,6 +7897,7 @@ var createShellTool = (sandboxKey, options = {}) => {
7730
7897
  }
7731
7898
  const label = normalizeOptionalLabel(input.label);
7732
7899
  const detachedWait = input.detached_wait ?? false;
7900
+ const stdinMode = input.stdin_mode ?? "closed";
7733
7901
  const timeoutSeconds = resolveShellTimeoutSeconds(
7734
7902
  input.timeout,
7735
7903
  detachedWait
@@ -7758,7 +7926,8 @@ var createShellTool = (sandboxKey, options = {}) => {
7758
7926
  cwd: sandbox.workingDir,
7759
7927
  timeoutSeconds,
7760
7928
  toolName: "shell",
7761
- outputCache: shared.outputCacheStore
7929
+ outputCache: shared.outputCacheStore,
7930
+ stdinMode
7762
7931
  })
7763
7932
  );
7764
7933
  if (detachedWait) {
@@ -7781,6 +7950,34 @@ var createShellTool = (sandboxKey, options = {}) => {
7781
7950
  }
7782
7951
  });
7783
7952
  };
7953
+ var createShellStdinWriteTool = (options = {}) => {
7954
+ const shared = getSharedDeps(options);
7955
+ return (0, import_core12.defineTool)({
7956
+ name: "shell_stdin_write",
7957
+ description: "Write up to 64 KiB of UTF-8 text to a live shell task started with detached_wait=true and stdin_mode=pipe; use shell_logs or shell_wait afterward.",
7958
+ input: shellStdinWriteSchema,
7959
+ execute: async (input, ctx) => {
7960
+ try {
7961
+ const task = await resolveShellTask(shared.tasks, input);
7962
+ const sessionContext = options.sessionContextKey ? await getToolSessionContext(ctx, options.sessionContextKey) : null;
7963
+ const text = `${input.text}${input.append_newline ? "\n" : ""}`;
7964
+ const written = await shared.tasks.writeInput(task.task_id, {
7965
+ text,
7966
+ close: input.close ?? false,
7967
+ sessionId: sessionContext?.sessionId ?? void 0
7968
+ });
7969
+ return {
7970
+ key: getShellTaskKey(written.task),
7971
+ state: written.task.state,
7972
+ bytes_written: written.result.bytes_written,
7973
+ stdin_closed: written.result.stdin_closed
7974
+ };
7975
+ } catch (error) {
7976
+ throw formatTaskError(error);
7977
+ }
7978
+ }
7979
+ });
7980
+ };
7784
7981
  var createShellListTool = (options = {}) => {
7785
7982
  const shared = getSharedDeps(options);
7786
7983
  return (0, import_core12.defineTool)({
@@ -7854,7 +8051,7 @@ var createShellWaitTool = (options = {}) => {
7854
8051
  const shared = getSharedDeps(options);
7855
8052
  return (0, import_core12.defineTool)({
7856
8053
  name: "shell_wait",
7857
- description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or a terminal result with `stdout`/`stderr` stream fields. Successful terminal results suppress `stderr` by default unless `include_stderr_on_success=true`; use `shell_logs` for explicit stream reads.",
8054
+ description: "Wait within a bounded window for a shell task, returning compact running status or its terminal stdout/stderr result.",
7858
8055
  input: shellWaitSchema,
7859
8056
  execute: async (input, ctx) => {
7860
8057
  try {
@@ -7889,7 +8086,7 @@ var createShellResultTool = (options = {}) => {
7889
8086
  const shared = getSharedDeps(options);
7890
8087
  return (0, import_core12.defineTool)({
7891
8088
  name: "shell_result",
7892
- description: "Read the retained terminal result for a shell task as compact JSON with `stdout`/`stderr` stream fields. Successful terminal results suppress `stderr` by default unless `include_stderr_on_success=true`; use `shell_logs` for explicit stream reads.",
8089
+ description: "Read a shell task's retained terminal stdout/stderr result, or its current status if still running.",
7893
8090
  input: shellResultSchema,
7894
8091
  execute: async (input) => {
7895
8092
  try {
@@ -7926,10 +8123,10 @@ var createShellCancelTool = (options = {}) => {
7926
8123
 
7927
8124
  // src/tools/skill-load.ts
7928
8125
  var import_core13 = require("@codelia/core");
7929
- var import_zod11 = require("zod");
7930
- var SkillLoadInputSchema = import_zod11.z.object({
7931
- name: import_zod11.z.string().min(1).optional().describe("Exact skill name to load."),
7932
- path: import_zod11.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
8126
+ var import_zod12 = require("zod");
8127
+ var SkillLoadInputSchema = import_zod12.z.object({
8128
+ name: import_zod12.z.string().min(1).optional().describe("Exact skill name to load."),
8129
+ path: import_zod12.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
7933
8130
  }).refine((value) => !!value.name || !!value.path, {
7934
8131
  message: "name or path is required",
7935
8132
  path: ["name"]
@@ -7981,16 +8178,16 @@ var createSkillLoadTool = (skillsResolverKey) => (0, import_core13.defineTool)({
7981
8178
 
7982
8179
  // src/tools/skill-search.ts
7983
8180
  var import_core14 = require("@codelia/core");
7984
- var import_zod12 = require("zod");
8181
+ var import_zod13 = require("zod");
7985
8182
  var createSkillSearchTool = (skillsResolverKey) => (0, import_core14.defineTool)({
7986
8183
  name: "skill_search",
7987
8184
  description: "Search installed local skills by name, description, or path.",
7988
- input: import_zod12.z.object({
7989
- query: import_zod12.z.string().min(1).describe("Search query text."),
7990
- limit: import_zod12.z.number().int().positive().optional().describe(
8185
+ input: import_zod13.z.object({
8186
+ query: import_zod13.z.string().min(1).describe("Search query text."),
8187
+ limit: import_zod13.z.number().int().positive().optional().describe(
7991
8188
  "Optional max result count. Higher values may be clamped by config."
7992
8189
  ),
7993
- scope: import_zod12.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
8190
+ scope: import_zod13.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7994
8191
  }),
7995
8192
  execute: async (input, ctx) => {
7996
8193
  try {
@@ -8014,7 +8211,7 @@ var createSkillSearchTool = (skillsResolverKey) => (0, import_core14.defineTool)
8014
8211
 
8015
8212
  // src/tools/todo-mutate.ts
8016
8213
  var import_core15 = require("@codelia/core");
8017
- var import_zod13 = require("zod");
8214
+ var import_zod14 = require("zod");
8018
8215
 
8019
8216
  // src/tools/todo-store.ts
8020
8217
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -8124,37 +8321,39 @@ var pickNextTodo = (todos) => {
8124
8321
  var todoStore = /* @__PURE__ */ new Map();
8125
8322
 
8126
8323
  // src/tools/todo-mutate.ts
8127
- var todoStatusSchema = import_zod13.z.enum(["pending", "in_progress", "completed"]);
8128
- var todoPrioritySchema = import_zod13.z.number().int().min(1).max(5);
8129
- var todoItemSchema = import_zod13.z.object({
8130
- id: import_zod13.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
8131
- content: import_zod13.z.string().min(1).describe("Todo item text."),
8324
+ var todoStatusSchema = import_zod14.z.enum(["pending", "in_progress", "completed"]);
8325
+ var todoPrioritySchema = import_zod14.z.number().int().min(1).max(5);
8326
+ var todoItemSchema = import_zod14.z.object({
8327
+ id: import_zod14.z.string().min(1).optional().describe(
8328
+ "Stable ID. Omit to generate one; preserve the existing ID when replacing a known item."
8329
+ ),
8330
+ content: import_zod14.z.string().min(1).describe("Todo item text."),
8132
8331
  status: todoStatusSchema.describe("Todo status."),
8133
8332
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
8134
- notes: import_zod13.z.string().optional().describe("Optional implementation notes."),
8135
- activeForm: import_zod13.z.string().optional().describe("Optional in-progress phrasing for UI display.")
8333
+ notes: import_zod14.z.string().optional().describe("Implementation notes."),
8334
+ activeForm: import_zod14.z.string().optional().describe("In-progress phrasing for UI display.")
8136
8335
  });
8137
- var todoPatchItemSchema = import_zod13.z.object({
8138
- id: import_zod13.z.string().min(1).describe("Target todo ID."),
8139
- remove: import_zod13.z.boolean().optional().describe("Set true to remove the todo item."),
8140
- content: import_zod13.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
8141
- status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
8142
- priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
8143
- notes: import_zod13.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
8144
- activeForm: import_zod13.z.string().nullable().default(null).describe(
8145
- "Updated in-progress phrasing (null keeps current, empty clears)."
8336
+ var todoPatchItemSchema = import_zod14.z.object({
8337
+ id: import_zod14.z.string().min(1).describe("Target todo ID."),
8338
+ remove: import_zod14.z.boolean().optional().describe("Set true to remove the todo item."),
8339
+ content: import_zod14.z.string().min(1).optional().describe("New todo text; omit to keep the current value."),
8340
+ status: todoStatusSchema.optional().describe("New status; omit to keep the current value."),
8341
+ priority: todoPrioritySchema.optional().describe("New priority; omit to keep the current value."),
8342
+ notes: import_zod14.z.string().optional().describe("New notes; omit to keep the current value, empty clears."),
8343
+ activeForm: import_zod14.z.string().optional().describe(
8344
+ "New in-progress phrasing; omit to keep the current value, empty clears."
8146
8345
  )
8147
8346
  });
8148
- var todoNewInputSchema = import_zod13.z.object({
8149
- todos: import_zod13.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
8347
+ var todoNewInputSchema = import_zod14.z.object({
8348
+ todos: import_zod14.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
8150
8349
  }).strict();
8151
- var todoAppendInputSchema = import_zod13.z.object({
8152
- todos: import_zod13.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
8350
+ var todoAppendInputSchema = import_zod14.z.object({
8351
+ todos: import_zod14.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
8153
8352
  }).strict();
8154
- var todoPatchInputSchema = import_zod13.z.object({
8155
- updates: import_zod13.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
8353
+ var todoPatchInputSchema = import_zod14.z.object({
8354
+ updates: import_zod14.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
8156
8355
  }).strict();
8157
- var todoClearInputSchema = import_zod13.z.object({}).strict();
8356
+ var todoClearInputSchema = import_zod14.z.object({}).strict();
8158
8357
  var statusSymbol = {
8159
8358
  pending: "[ ]",
8160
8359
  in_progress: "[>]",
@@ -8209,11 +8408,11 @@ var withPatchApplied = (currentTodos, updates) => {
8209
8408
  const previous = nextInputs[index];
8210
8409
  nextInputs[index] = {
8211
8410
  ...previous,
8212
- content: update.content !== null ? update.content : previous.content,
8213
- status: update.status !== null ? update.status : previous.status,
8214
- priority: update.priority !== null ? update.priority : previous.priority,
8215
- notes: update.notes !== null ? update.notes : previous.notes,
8216
- activeForm: update.activeForm !== null ? update.activeForm : previous.activeForm
8411
+ content: update.content !== void 0 ? update.content : previous.content,
8412
+ status: update.status !== void 0 ? update.status : previous.status,
8413
+ priority: update.priority !== void 0 ? update.priority : previous.priority,
8414
+ notes: update.notes !== void 0 ? update.notes : previous.notes,
8415
+ activeForm: update.activeForm !== void 0 ? update.activeForm : previous.activeForm
8217
8416
  };
8218
8417
  }
8219
8418
  return { todos: normalizeTodoItems(nextInputs) };
@@ -8305,7 +8504,7 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
8305
8504
 
8306
8505
  // src/tools/todo-read.ts
8307
8506
  var import_core16 = require("@codelia/core");
8308
- var import_zod14 = require("zod");
8507
+ var import_zod15 = require("zod");
8309
8508
  var statusSymbol2 = {
8310
8509
  pending: "[ ]",
8311
8510
  in_progress: "[>]",
@@ -8314,7 +8513,7 @@ var statusSymbol2 = {
8314
8513
  var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.defineTool)({
8315
8514
  name: "todo_read",
8316
8515
  description: "Read the in-session todo plan with execution order and next step.",
8317
- input: import_zod14.z.object({}),
8516
+ input: import_zod15.z.object({}),
8318
8517
  execute: async (_input, ctx) => {
8319
8518
  const sandbox = await getSandboxContext(ctx, sandboxKey);
8320
8519
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -8351,14 +8550,14 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.de
8351
8550
 
8352
8551
  // src/tools/tool-output-cache.ts
8353
8552
  var import_core17 = require("@codelia/core");
8354
- var import_zod15 = require("zod");
8553
+ var import_zod16 = require("zod");
8355
8554
  var createToolOutputCacheTool = (store) => (0, import_core17.defineTool)({
8356
8555
  name: "tool_output_cache",
8357
8556
  description: "Read cached tool output by ref_id.",
8358
- input: import_zod15.z.object({
8359
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
8360
- offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
8361
- limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return.")
8557
+ input: import_zod16.z.object({
8558
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
8559
+ offset: import_zod16.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
8560
+ limit: import_zod16.z.number().int().positive().optional().describe("Optional max number of lines to return.")
8362
8561
  }),
8363
8562
  execute: async (input) => {
8364
8563
  if (!store.read) {
@@ -8377,11 +8576,11 @@ var createToolOutputCacheTool = (store) => (0, import_core17.defineTool)({
8377
8576
  var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
8378
8577
  name: "tool_output_cache_line",
8379
8578
  description: "Read a single cached output line segment by line number and char offset.",
8380
- input: import_zod15.z.object({
8381
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
8382
- line_number: import_zod15.z.number().int().positive().describe("1-based line number to read."),
8383
- char_offset: import_zod15.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
8384
- char_limit: import_zod15.z.number().int().positive().optional().describe("Max chars to return.")
8579
+ input: import_zod16.z.object({
8580
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
8581
+ line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
8582
+ char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
8583
+ char_limit: import_zod16.z.number().int().positive().optional().describe("Max chars to return.")
8385
8584
  }),
8386
8585
  execute: async (input) => {
8387
8586
  if (!store.readLine) {
@@ -8401,13 +8600,13 @@ var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
8401
8600
  var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
8402
8601
  name: "tool_output_cache_grep",
8403
8602
  description: "Search cached tool output by ref_id.",
8404
- input: import_zod15.z.object({
8405
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
8406
- pattern: import_zod15.z.string().describe("Text or regex pattern to search for."),
8407
- regex: import_zod15.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8408
- before: import_zod15.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8409
- after: import_zod15.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8410
- max_matches: import_zod15.z.number().int().positive().optional().describe("Maximum number of matches to return.")
8603
+ input: import_zod16.z.object({
8604
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
8605
+ pattern: import_zod16.z.string().describe("Text or regex pattern to search for."),
8606
+ regex: import_zod16.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8607
+ before: import_zod16.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8608
+ after: import_zod16.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8609
+ max_matches: import_zod16.z.number().int().positive().optional().describe("Maximum number of matches to return.")
8411
8610
  }),
8412
8611
  execute: async (input) => {
8413
8612
  if (!store.grep) {
@@ -8431,7 +8630,7 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
8431
8630
  var import_node_fs13 = require("fs");
8432
8631
  var import_node_path13 = __toESM(require("path"), 1);
8433
8632
  var import_core18 = require("@codelia/core");
8434
- var import_zod16 = require("zod");
8633
+ var import_zod17 = require("zod");
8435
8634
  var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
8436
8635
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
8437
8636
  var MIME_BY_EXTENSION = {
@@ -8447,14 +8646,14 @@ var resolveImageMime = (filePath) => {
8447
8646
  var createViewImageTool = (sandboxKey) => (0, import_core18.defineTool)({
8448
8647
  name: "view_image",
8449
8648
  description: "Load one local png/jpeg/webp/gif image (default max 5MB) for multimodal inspection.",
8450
- input: import_zod16.z.object({
8451
- file_path: import_zod16.z.string().describe(
8649
+ input: import_zod17.z.object({
8650
+ file_path: import_zod17.z.string().describe(
8452
8651
  "Single local png/jpeg/webp/gif image path. Sandbox-bounded unless full-access mode is active."
8453
8652
  ),
8454
- detail: import_zod16.z.enum(["auto", "low", "high"]).optional().describe(
8653
+ detail: import_zod17.z.enum(["auto", "low", "high"]).optional().describe(
8455
8654
  "Model image-detail hint (`auto`/`low`/`high`). Default auto."
8456
8655
  ),
8457
- max_bytes: import_zod16.z.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
8656
+ max_bytes: import_zod17.z.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
8458
8657
  }),
8459
8658
  execute: async (input, ctx) => {
8460
8659
  let resolved;
@@ -8505,7 +8704,7 @@ var createViewImageTool = (sandboxKey) => (0, import_core18.defineTool)({
8505
8704
 
8506
8705
  // src/tools/webfetch.ts
8507
8706
  var import_core19 = require("@codelia/core");
8508
- var import_zod17 = require("zod");
8707
+ var import_zod18 = require("zod");
8509
8708
  var DEFAULT_TIMEOUT_MS3 = 1e4;
8510
8709
  var MAX_TIMEOUT_MS = 3e4;
8511
8710
  var DEFAULT_MAX_BYTES3 = 2e5;
@@ -8761,13 +8960,13 @@ var classifyFetchError = (error, timeoutMs) => {
8761
8960
  var createWebfetchTool = () => (0, import_core19.defineTool)({
8762
8961
  name: "webfetch",
8763
8962
  description: "Fetch an HTTP(S) URL and return bounded normalized markdown/text/html for textual content, not binary downloads.",
8764
- input: import_zod17.z.object({
8765
- url: import_zod17.z.string().min(1).describe("HTTP(S) URL to fetch."),
8766
- output_format: import_zod17.z.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8767
- timeout_ms: import_zod17.z.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
8963
+ input: import_zod18.z.object({
8964
+ url: import_zod18.z.string().min(1).describe("HTTP(S) URL to fetch."),
8965
+ output_format: import_zod18.z.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8966
+ timeout_ms: import_zod18.z.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
8768
8967
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS3}, Max ${MAX_TIMEOUT_MS}.`
8769
8968
  ),
8770
- max_bytes: import_zod17.z.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8969
+ max_bytes: import_zod18.z.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8771
8970
  `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
8772
8971
  )
8773
8972
  }),
@@ -8841,15 +9040,16 @@ var createWebfetchTool = () => (0, import_core19.defineTool)({
8841
9040
  var import_node_fs14 = require("fs");
8842
9041
  var import_node_path14 = __toESM(require("path"), 1);
8843
9042
  var import_core20 = require("@codelia/core");
8844
- var import_zod18 = require("zod");
9043
+ var import_zod19 = require("zod");
8845
9044
  var createWriteTool = (sandboxKey, outputCacheStore) => (0, import_core20.defineTool)({
8846
9045
  name: "write",
8847
- description: "Write full UTF-8 text to a file, replacing any existing contents and creating parent directories if needed.",
8848
- input: import_zod18.z.object({
8849
- file_path: import_zod18.z.string().describe(
9046
+ 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.",
9047
+ input: import_zod19.z.object({
9048
+ file_path: import_zod19.z.string().describe(
8850
9049
  "File path. Sandbox-bounded unless full-access mode is active."
8851
9050
  ),
8852
- content: import_zod18.z.string().describe("Full replacement UTF-8 text content to write.")
9051
+ content: import_zod19.z.string().describe("Full replacement UTF-8 text content to write."),
9052
+ expected_hash: expectedContentHashSchema
8853
9053
  }),
8854
9054
  execute: async (input, ctx) => {
8855
9055
  let resolved;
@@ -8861,13 +9061,21 @@ var createWriteTool = (sandboxKey, outputCacheStore) => (0, import_core20.define
8861
9061
  }
8862
9062
  try {
8863
9063
  let before = "";
9064
+ let fileExists = false;
8864
9065
  try {
8865
9066
  before = await import_node_fs14.promises.readFile(resolved, "utf8");
9067
+ fileExists = true;
8866
9068
  } catch (error) {
8867
9069
  if (error.code !== "ENOENT") {
8868
9070
  throw error;
8869
9071
  }
8870
9072
  }
9073
+ assertExpectedContentHash({
9074
+ expectedHash: input.expected_hash,
9075
+ fileExists,
9076
+ content: before,
9077
+ filePath: input.file_path
9078
+ });
8871
9079
  await import_node_fs14.promises.mkdir(import_node_path14.default.dirname(resolved), { recursive: true });
8872
9080
  await import_node_fs14.promises.writeFile(resolved, input.content, "utf8");
8873
9081
  const diffPayload = await buildDiffPayload({
@@ -8897,6 +9105,11 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
8897
9105
  outputCacheStore: options.toolOutputCacheStore,
8898
9106
  sessionContextKey: options.todoSessionContextKey
8899
9107
  }),
9108
+ createShellStdinWriteTool({
9109
+ taskManager: options.taskManager,
9110
+ outputCacheStore: options.toolOutputCacheStore,
9111
+ sessionContextKey: options.todoSessionContextKey
9112
+ }),
8900
9113
  createShellListTool({
8901
9114
  taskManager: options.taskManager,
8902
9115
  outputCacheStore: options.toolOutputCacheStore