@codelia/runtime 0.1.35 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.cjs +296 -57
  2. package/dist/index.js +283 -43
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -27,8 +27,8 @@ var import_node_path17 = __toESM(require("path"), 1);
27
27
  var import_storage11 = require("@codelia/storage");
28
28
 
29
29
  // src/agent-factory.ts
30
- var import_node_fs15 = require("fs");
31
- var import_core18 = require("@codelia/core");
30
+ var import_node_fs16 = require("fs");
31
+ var import_core19 = require("@codelia/core");
32
32
  var import_model_metadata2 = require("@codelia/model-metadata");
33
33
  var import_shared_types2 = require("@codelia/shared-types");
34
34
  var import_storage6 = require("@codelia/storage");
@@ -1762,6 +1762,26 @@ var toPositiveInteger = (value) => {
1762
1762
  }
1763
1763
  return Math.trunc(value);
1764
1764
  };
1765
+ var resolveDefaultRegistrySpec = (provider, model) => {
1766
+ const normalized = stripProviderPrefix(provider, model);
1767
+ const candidates = [model, normalized, `${provider}/${normalized}`].filter(
1768
+ (value, index, array) => array.indexOf(value) === index
1769
+ );
1770
+ for (const candidate of candidates) {
1771
+ const spec = (0, import_core2.resolveModel)(import_core2.DEFAULT_MODEL_REGISTRY, candidate, provider);
1772
+ if (spec?.provider === provider) {
1773
+ return spec;
1774
+ }
1775
+ }
1776
+ const normalizedLower = normalized.toLowerCase();
1777
+ for (const spec of Object.values(import_core2.DEFAULT_MODEL_REGISTRY.modelsById)) {
1778
+ if (spec.provider !== provider) continue;
1779
+ if (spec.id.toLowerCase() === normalizedLower) {
1780
+ return spec;
1781
+ }
1782
+ }
1783
+ return void 0;
1784
+ };
1765
1785
  var withOpenRouterDynamicModel = (registry, llm, entry) => {
1766
1786
  if (llm.provider !== "openrouter") {
1767
1787
  return registry;
@@ -1820,7 +1840,8 @@ var buildModelRegistry = async (llm, options = {}) => {
1820
1840
  );
1821
1841
  }
1822
1842
  if (!resolvedEntry) {
1823
- if (strict) {
1843
+ const fallbackSpec = resolveDefaultRegistrySpec(llm.provider, llm.model);
1844
+ if (strict && !fallbackSpec) {
1824
1845
  throw new Error(
1825
1846
  `Model metadata not found for ${llm.provider}/${llm.model} after refresh`
1826
1847
  );
@@ -2314,11 +2335,13 @@ var parseRawArgsForPrompt = (rawArgs) => parseRawArgsObject(rawArgs);
2314
2335
  // src/permissions/service.ts
2315
2336
  var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2316
2337
  "read",
2338
+ "read_line",
2317
2339
  "grep",
2318
2340
  "glob_search",
2319
2341
  "todo_read",
2320
2342
  "todo_write",
2321
2343
  "tool_output_cache",
2344
+ "tool_output_cache_line",
2322
2345
  "tool_output_cache_grep",
2323
2346
  "agents_resolve",
2324
2347
  "skill_search",
@@ -4722,15 +4745,76 @@ var import_node_fs13 = require("fs");
4722
4745
  var import_core10 = require("@codelia/core");
4723
4746
  var import_zod9 = require("zod");
4724
4747
  var DEFAULT_READ_LIMIT = 2e3;
4725
- var MAX_LINE_LENGTH = 2e3;
4726
- var MAX_BYTES = 50 * 1024;
4748
+ var DEFAULT_MAX_LINE_LENGTH = 5e4;
4749
+ var DEFAULT_MAX_BYTES = 64 * 1024;
4750
+ var parsePositiveIntEnv = (key, fallback) => {
4751
+ const raw = process.env[key];
4752
+ if (!raw) return fallback;
4753
+ const parsed = Number.parseInt(raw, 10);
4754
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
4755
+ return parsed;
4756
+ };
4757
+ var MAX_LINE_LENGTH = parsePositiveIntEnv(
4758
+ "CODELIA_READ_MAX_LINE_LENGTH",
4759
+ DEFAULT_MAX_LINE_LENGTH
4760
+ );
4761
+ var MAX_BYTES = parsePositiveIntEnv("CODELIA_READ_MAX_BYTES", DEFAULT_MAX_BYTES);
4762
+ var clipLongLine = (line) => {
4763
+ if (line.length <= MAX_LINE_LENGTH) {
4764
+ return line;
4765
+ }
4766
+ return `${line.slice(0, MAX_LINE_LENGTH)}...`;
4767
+ };
4768
+ var clipUtf8ToBytes = (value, maxBytes) => {
4769
+ if (maxBytes <= 0 || value.length === 0) return "";
4770
+ let bytes = 0;
4771
+ let out = "";
4772
+ for (const ch of value) {
4773
+ const next = Buffer.byteLength(ch, "utf8");
4774
+ if (bytes + next > maxBytes) break;
4775
+ out += ch;
4776
+ bytes += next;
4777
+ }
4778
+ return out;
4779
+ };
4780
+ var clipLineToByteBudget = (line, maxBytes) => {
4781
+ if (maxBytes <= 0) return "";
4782
+ if (Buffer.byteLength(line, "utf8") <= maxBytes) return line;
4783
+ const suffix = "...";
4784
+ const suffixBytes = Buffer.byteLength(suffix, "utf8");
4785
+ if (maxBytes <= suffixBytes) {
4786
+ return clipUtf8ToBytes(line, maxBytes);
4787
+ }
4788
+ return `${clipUtf8ToBytes(line, maxBytes - suffixBytes)}${suffix}`;
4789
+ };
4790
+ var buildTooLargeToReadError = (options) => [
4791
+ `TOO_LARGE_TO_READ: output exceeds per-call limit (${MAX_BYTES} bytes).`,
4792
+ `file_path=${options.filePath} offset=${options.offset} limit=${options.limit}`,
4793
+ "Try split reads:",
4794
+ `- read({"file_path":"${options.filePath}","offset":${options.offset},"limit":2000})`,
4795
+ `- read({"file_path":"${options.filePath}","offset":${options.nextOffset},"limit":2000})`
4796
+ ].join("\n").trim();
4797
+ var buildSingleLineByteCapError = (options) => [
4798
+ `TOO_LARGE_TO_READ: requested line ${options.lineNumber} exceeds per-call byte limit (${MAX_BYTES} bytes).`,
4799
+ `file_path=${options.filePath} line_number=${options.lineNumber}`,
4800
+ "Offset-based pagination cannot continue within one physical line.",
4801
+ "Use read_line for char-based paging or retry with allow_truncate=true.",
4802
+ `read_line({"file_path":"${options.filePath}","line_number":${options.lineNumber},"char_offset":0,"char_limit":10000})`
4803
+ ].join("\n").trim();
4804
+ var buildLineTooLongError = (options) => [
4805
+ `LINE_TOO_LONG: line ${options.lineNumber} has ${options.lineLength} chars (max ${MAX_LINE_LENGTH}).`,
4806
+ `file_path=${options.filePath}`,
4807
+ "Use read_line for char-based paging or retry with allow_truncate=true.",
4808
+ `read_line({"file_path":"${options.filePath}","line_number":${options.lineNumber},"char_offset":0,"char_limit":10000})`
4809
+ ].join("\n").trim();
4727
4810
  var createReadTool = (sandboxKey) => (0, import_core10.defineTool)({
4728
4811
  name: "read",
4729
4812
  description: "Read a text file with optional 0-based line offset and line limit.",
4730
4813
  input: import_zod9.z.object({
4731
4814
  file_path: import_zod9.z.string().describe("File path under the sandbox root."),
4732
4815
  offset: import_zod9.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4733
- limit: import_zod9.z.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4816
+ limit: import_zod9.z.number().int().positive().optional().describe("Max lines to read. Default 2000."),
4817
+ allow_truncate: import_zod9.z.boolean().optional().describe("Allow truncation when output is too large. Default false.")
4734
4818
  }),
4735
4819
  execute: async (input, ctx) => {
4736
4820
  let resolved;
@@ -4756,34 +4840,91 @@ var createReadTool = (sandboxKey) => (0, import_core10.defineTool)({
4756
4840
  }
4757
4841
  const offset = input.offset ?? 0;
4758
4842
  const limit = input.limit ?? DEFAULT_READ_LIMIT;
4843
+ const allowTruncate = input.allow_truncate ?? false;
4759
4844
  if (offset >= lines.length) {
4760
- return `Offset exceeds file length: ${input.file_path}`;
4845
+ return `Offset exceeds output length: ${input.file_path}`;
4761
4846
  }
4762
- const raw = [];
4847
+ const outputLines = [];
4763
4848
  let bytes = 0;
4764
4849
  let truncatedByBytes = false;
4850
+ let clipped = false;
4851
+ let firstClippedLineNumber = null;
4765
4852
  for (let index = offset; index < Math.min(lines.length, offset + limit); index += 1) {
4766
- const line = lines[index].length > MAX_LINE_LENGTH ? `${lines[index].slice(0, MAX_LINE_LENGTH)}...` : lines[index];
4767
- const size = Buffer.byteLength(line, "utf8") + (raw.length > 0 ? 1 : 0);
4853
+ const originalLine = lines[index] ?? "";
4854
+ if (originalLine.length > MAX_LINE_LENGTH && !allowTruncate) {
4855
+ return buildLineTooLongError({
4856
+ filePath: input.file_path,
4857
+ lineNumber: index + 1,
4858
+ lineLength: originalLine.length
4859
+ });
4860
+ }
4861
+ const line = allowTruncate ? clipLongLine(originalLine) : originalLine;
4862
+ if (line.length !== originalLine.length) {
4863
+ clipped = true;
4864
+ if (firstClippedLineNumber === null) {
4865
+ firstClippedLineNumber = index + 1;
4866
+ }
4867
+ }
4868
+ const numberedLine = `${String(index + 1).padStart(5, " ")} ${line}`;
4869
+ const size = Buffer.byteLength(numberedLine, "utf8") + (outputLines.length > 0 ? 1 : 0);
4768
4870
  if (bytes + size > MAX_BYTES) {
4871
+ if (!allowTruncate) {
4872
+ if (outputLines.length === 0) {
4873
+ return buildSingleLineByteCapError({
4874
+ filePath: input.file_path,
4875
+ lineNumber: index + 1
4876
+ });
4877
+ }
4878
+ return buildTooLargeToReadError({
4879
+ filePath: input.file_path,
4880
+ offset,
4881
+ limit,
4882
+ nextOffset: Math.max(offset + outputLines.length, offset + 1)
4883
+ });
4884
+ }
4885
+ if (outputLines.length === 0) {
4886
+ const prefix = `${String(index + 1).padStart(5, " ")} `;
4887
+ const budget = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
4888
+ const clippedByBytes = clipLineToByteBudget(line, budget);
4889
+ if (clippedByBytes.length > 0) {
4890
+ outputLines.push(clippedByBytes);
4891
+ bytes = Buffer.byteLength(
4892
+ `${prefix}${clippedByBytes}`,
4893
+ "utf8"
4894
+ );
4895
+ clipped = true;
4896
+ if (firstClippedLineNumber === null) {
4897
+ firstClippedLineNumber = index + 1;
4898
+ }
4899
+ }
4900
+ }
4769
4901
  truncatedByBytes = true;
4770
4902
  break;
4771
4903
  }
4772
- raw.push(line);
4904
+ outputLines.push(line);
4773
4905
  bytes += size;
4774
4906
  }
4775
- const numbered = raw.map(
4907
+ const numbered = outputLines.map(
4776
4908
  (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4777
4909
  );
4778
- const lastReadLine = offset + raw.length;
4910
+ const lastReadLine = offset + outputLines.length;
4779
4911
  const hasMoreLines = lines.length > lastReadLine;
4780
- const truncated = truncatedByBytes || hasMoreLines;
4781
4912
  let output = numbered.join("\n");
4782
- if (truncated) {
4783
- const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "File has more lines.";
4913
+ if (truncatedByBytes || hasMoreLines) {
4914
+ const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "Output has more lines.";
4784
4915
  output += `
4785
4916
 
4786
4917
  ${reason} Use offset to read beyond line ${lastReadLine}.`;
4918
+ }
4919
+ if (clipped) {
4920
+ output += `
4921
+
4922
+ Long physical lines are clipped at ${MAX_LINE_LENGTH} chars.`;
4923
+ }
4924
+ if (allowTruncate && firstClippedLineNumber !== null) {
4925
+ output += `
4926
+
4927
+ For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
4787
4928
  }
4788
4929
  return output;
4789
4930
  } catch (error) {
@@ -5236,14 +5377,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5236
5377
  ctx.addIssue({
5237
5378
  code: import_zod14.z.ZodIssueCode.custom,
5238
5379
  path: ["updates"],
5239
- message: "patch mode requires at least one update item."
5380
+ message: "patch mode requires at least one item in updates."
5240
5381
  });
5241
5382
  }
5242
5383
  if (input.todos.length > 0) {
5243
5384
  ctx.addIssue({
5244
5385
  code: import_zod14.z.ZodIssueCode.custom,
5245
5386
  path: ["todos"],
5246
- message: "patch mode does not accept todos."
5387
+ message: "patch mode uses updates only; leave todos empty."
5247
5388
  });
5248
5389
  }
5249
5390
  return;
@@ -5253,14 +5394,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5253
5394
  ctx.addIssue({
5254
5395
  code: import_zod14.z.ZodIssueCode.custom,
5255
5396
  path: ["todos"],
5256
- message: "clear mode does not accept todos."
5397
+ message: "clear mode does not accept todos; omit todos and updates."
5257
5398
  });
5258
5399
  }
5259
5400
  if (input.updates.length > 0) {
5260
5401
  ctx.addIssue({
5261
5402
  code: import_zod14.z.ZodIssueCode.custom,
5262
5403
  path: ["updates"],
5263
- message: "clear mode does not accept updates."
5404
+ message: "clear mode does not accept updates; omit todos and updates."
5264
5405
  });
5265
5406
  }
5266
5407
  return;
@@ -5269,14 +5410,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5269
5410
  ctx.addIssue({
5270
5411
  code: import_zod14.z.ZodIssueCode.custom,
5271
5412
  path: ["todos"],
5272
- message: `${input.mode} mode requires at least one todo item.`
5413
+ message: `${input.mode} mode requires at least one item in todos.`
5273
5414
  });
5274
5415
  }
5275
5416
  if (input.updates.length > 0) {
5276
5417
  ctx.addIssue({
5277
5418
  code: import_zod14.z.ZodIssueCode.custom,
5278
5419
  path: ["updates"],
5279
- message: `${input.mode} mode does not accept updates.`
5420
+ message: `${input.mode} mode uses todos only; leave updates empty.`
5280
5421
  });
5281
5422
  }
5282
5423
  });
@@ -5319,9 +5460,10 @@ var withPatchApplied = (currentTodos, updates) => {
5319
5460
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
5320
5461
  const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5321
5462
  if (missingIds.length > 0) {
5463
+ const knownIds = currentTodos.map((todo) => todo.id);
5322
5464
  return {
5323
5465
  todos: [...currentTodos],
5324
- error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}`
5466
+ error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}. Existing id(s): ${knownIds.length ? knownIds.join(", ") : "(none)"}. Run todo_read to inspect the current plan before patching.`
5325
5467
  };
5326
5468
  }
5327
5469
  let nextInputs = currentTodos.map((todo) => ({ ...todo }));
@@ -5375,7 +5517,8 @@ var createTodoWriteTool = (sandboxKey, sessionContextKey) => (0, import_core15.d
5375
5517
  }
5376
5518
  const inProgressCount = countInProgressTodos(nextTodos);
5377
5519
  if (inProgressCount > 1) {
5378
- return `Invalid todo state: ${inProgressCount} items are in_progress. Keep at most one item in_progress so tasks can be handled one-by-one.`;
5520
+ const inProgressIds = nextTodos.filter((todo) => todo.status === "in_progress").map((todo) => todo.id);
5521
+ return `Invalid todo state: ${inProgressCount} items are in_progress (${inProgressIds.join(", ")}). Keep at most one item in_progress so tasks can be handled one-by-one.`;
5379
5522
  }
5380
5523
  if (nextTodos.length === 0) {
5381
5524
  clearTodosForSession(todoSessionId);
@@ -5395,7 +5538,8 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
5395
5538
  input: import_zod15.z.object({
5396
5539
  ref_id: import_zod15.z.string().describe("Tool output reference ID."),
5397
5540
  offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
5398
- limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return.")
5541
+ limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return."),
5542
+ allow_truncate: import_zod15.z.boolean().optional().describe("Allow truncation when output is too large. Default false.")
5399
5543
  }),
5400
5544
  execute: async (input) => {
5401
5545
  if (!store.read) {
@@ -5404,13 +5548,38 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
5404
5548
  try {
5405
5549
  return await store.read(input.ref_id, {
5406
5550
  offset: input.offset,
5407
- limit: input.limit
5551
+ limit: input.limit,
5552
+ allow_truncate: input.allow_truncate
5408
5553
  });
5409
5554
  } catch (error) {
5410
5555
  return `Error reading tool output cache: ${String(error)}`;
5411
5556
  }
5412
5557
  }
5413
5558
  });
5559
+ var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
5560
+ name: "tool_output_cache_line",
5561
+ description: "Read a single cached output line segment by line number and char offset.",
5562
+ input: import_zod15.z.object({
5563
+ ref_id: import_zod15.z.string().describe("Tool output reference ID."),
5564
+ line_number: import_zod15.z.number().int().positive().describe("1-based line number to read."),
5565
+ char_offset: import_zod15.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5566
+ char_limit: import_zod15.z.number().int().positive().optional().describe("Max chars to return.")
5567
+ }),
5568
+ execute: async (input) => {
5569
+ if (!store.readLine) {
5570
+ return "tool_output_cache_line is unavailable.";
5571
+ }
5572
+ try {
5573
+ return await store.readLine(input.ref_id, {
5574
+ line_number: input.line_number,
5575
+ char_offset: input.char_offset,
5576
+ char_limit: input.char_limit
5577
+ });
5578
+ } catch (error) {
5579
+ return `Error reading cache line: ${String(error)}`;
5580
+ }
5581
+ }
5582
+ });
5414
5583
  var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
5415
5584
  name: "tool_output_cache_grep",
5416
5585
  description: "Search cached tool output by ref_id.",
@@ -5440,11 +5609,79 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
5440
5609
  }
5441
5610
  });
5442
5611
 
5443
- // src/tools/write.ts
5612
+ // src/tools/read-line.ts
5444
5613
  var import_node_fs14 = require("fs");
5445
- var import_node_path13 = __toESM(require("path"), 1);
5446
5614
  var import_core17 = require("@codelia/core");
5447
5615
  var import_zod16 = require("zod");
5616
+ var DEFAULT_CHAR_LIMIT = 1e4;
5617
+ var MAX_CHAR_LIMIT = 1e5;
5618
+ var createReadLineTool = (sandboxKey) => (0, import_core17.defineTool)({
5619
+ name: "read_line",
5620
+ description: "Read a single line segment by 1-based line number and 0-based char offset.",
5621
+ input: import_zod16.z.object({
5622
+ file_path: import_zod16.z.string().describe("File path under the sandbox root."),
5623
+ line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
5624
+ char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5625
+ char_limit: import_zod16.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5626
+ }),
5627
+ execute: async (input, ctx) => {
5628
+ let resolved;
5629
+ try {
5630
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
5631
+ resolved = sandbox.resolvePath(input.file_path);
5632
+ } catch (error) {
5633
+ return `Security error: ${String(error)}`;
5634
+ }
5635
+ try {
5636
+ const stat = await import_node_fs14.promises.stat(resolved);
5637
+ if (stat.isDirectory()) {
5638
+ return `Path is a directory: ${input.file_path}`;
5639
+ }
5640
+ } catch {
5641
+ return `File not found: ${input.file_path}`;
5642
+ }
5643
+ try {
5644
+ const content = await import_node_fs14.promises.readFile(resolved, "utf8");
5645
+ const lines = content.split(/\r?\n/);
5646
+ const lineIndex = input.line_number - 1;
5647
+ if (lineIndex >= lines.length) {
5648
+ return `Line number out of range: ${input.line_number} (total ${lines.length})`;
5649
+ }
5650
+ const line = lines[lineIndex] ?? "";
5651
+ const charOffset = input.char_offset ?? 0;
5652
+ const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5653
+ if (charOffset > line.length) {
5654
+ return `char_offset out of range: ${charOffset} (line length ${line.length})`;
5655
+ }
5656
+ const segment = line.slice(charOffset, charOffset + charLimit);
5657
+ const endOffset = charOffset + segment.length;
5658
+ const hasMore = endOffset < line.length;
5659
+ const header = [
5660
+ `line_number=${input.line_number}`,
5661
+ `line_length=${line.length}`,
5662
+ `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5663
+ ].join(" ");
5664
+ let output = `${header}
5665
+ ${segment}`;
5666
+ if (hasMore) {
5667
+ output += `
5668
+
5669
+ Use char_offset=${endOffset} to continue.`;
5670
+ output += `
5671
+ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5672
+ }
5673
+ return output;
5674
+ } catch (error) {
5675
+ return `Error reading file: ${String(error)}`;
5676
+ }
5677
+ }
5678
+ });
5679
+
5680
+ // src/tools/write.ts
5681
+ var import_node_fs15 = require("fs");
5682
+ var import_node_path13 = __toESM(require("path"), 1);
5683
+ var import_core18 = require("@codelia/core");
5684
+ var import_zod17 = require("zod");
5448
5685
  var buildDiffPreview = (content, filePath) => {
5449
5686
  const diff = createUnifiedDiff(filePath, "", content);
5450
5687
  if (!diff) {
@@ -5454,12 +5691,12 @@ var buildDiffPreview = (content, filePath) => {
5454
5691
  }
5455
5692
  return diff;
5456
5693
  };
5457
- var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5694
+ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
5458
5695
  name: "write",
5459
5696
  description: "Write text to a file, creating parent directories if needed.",
5460
- input: import_zod16.z.object({
5461
- file_path: import_zod16.z.string().describe("File path under the sandbox root."),
5462
- content: import_zod16.z.string().describe("UTF-8 text content to write.")
5697
+ input: import_zod17.z.object({
5698
+ file_path: import_zod17.z.string().describe("File path under the sandbox root."),
5699
+ content: import_zod17.z.string().describe("UTF-8 text content to write.")
5463
5700
  }),
5464
5701
  execute: async (input, ctx) => {
5465
5702
  let resolved;
@@ -5470,8 +5707,8 @@ var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5470
5707
  return `Security error: ${String(error)}`;
5471
5708
  }
5472
5709
  try {
5473
- await import_node_fs14.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
5474
- await import_node_fs14.promises.writeFile(resolved, input.content, "utf8");
5710
+ await import_node_fs15.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
5711
+ await import_node_fs15.promises.writeFile(resolved, input.content, "utf8");
5475
5712
  const diff = buildDiffPreview(input.content, input.file_path);
5476
5713
  return {
5477
5714
  summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
@@ -5488,6 +5725,7 @@ var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5488
5725
  var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {}) => [
5489
5726
  createBashTool(sandboxKey),
5490
5727
  createReadTool(sandboxKey),
5728
+ createReadLineTool(sandboxKey),
5491
5729
  createWriteTool(sandboxKey),
5492
5730
  createEditTool(sandboxKey),
5493
5731
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
@@ -5498,6 +5736,7 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
5498
5736
  createGrepTool(sandboxKey),
5499
5737
  ...options.toolOutputCacheStore ? [
5500
5738
  createToolOutputCacheTool(options.toolOutputCacheStore),
5739
+ createToolOutputCacheLineTool(options.toolOutputCacheStore),
5501
5740
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
5502
5741
  ] : [],
5503
5742
  createTodoReadTool(sandboxKey, options.todoSessionContextKey),
@@ -6038,14 +6277,14 @@ var createAgentFactory = (state, options = {}) => {
6038
6277
  const requestedReasoning = resolveReasoningEffort(modelConfig.reasoning) ?? "medium";
6039
6278
  switch (provider) {
6040
6279
  case "openai": {
6041
- const modelName = modelConfig.name ?? import_core18.OPENAI_DEFAULT_MODEL;
6280
+ const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
6042
6281
  const reasoning = resolveResponsesReasoning({
6043
6282
  model: modelName,
6044
6283
  requested: requestedReasoning
6045
6284
  });
6046
6285
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
6047
6286
  const websocketMode = modelConfig.experimental?.openai?.websocket_mode;
6048
- llm = new import_core18.ChatOpenAI({
6287
+ llm = new import_core19.ChatOpenAI({
6049
6288
  clientOptions: buildOpenAiClientOptions(authResolver, providerAuth),
6050
6289
  model: modelName,
6051
6290
  reasoningEffort: reasoning.effort,
@@ -6058,13 +6297,13 @@ var createAgentFactory = (state, options = {}) => {
6058
6297
  break;
6059
6298
  }
6060
6299
  case "openrouter": {
6061
- const modelName = modelConfig.name ?? import_core18.OPENAI_DEFAULT_MODEL;
6300
+ const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
6062
6301
  const reasoning = resolveResponsesReasoning({
6063
6302
  model: modelName,
6064
6303
  requested: requestedReasoning
6065
6304
  });
6066
6305
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
6067
- llm = new import_core18.ChatOpenRouter({
6306
+ llm = new import_core19.ChatOpenRouter({
6068
6307
  clientOptions: buildOpenRouterClientOptions(providerAuth),
6069
6308
  model: modelName,
6070
6309
  reasoningEffort: reasoning.effort,
@@ -6076,7 +6315,7 @@ var createAgentFactory = (state, options = {}) => {
6076
6315
  break;
6077
6316
  }
6078
6317
  case "anthropic": {
6079
- const modelName = modelConfig.name ?? import_core18.ANTHROPIC_DEFAULT_MODEL;
6318
+ const modelName = modelConfig.name ?? import_core19.ANTHROPIC_DEFAULT_MODEL;
6080
6319
  const reasoning = resolveAnthropicReasoning({
6081
6320
  model: modelName,
6082
6321
  requested: requestedReasoning,
@@ -6096,7 +6335,7 @@ var createAgentFactory = (state, options = {}) => {
6096
6335
  `anthropic model '${modelName}' max token limit (${modelMaxTokens}) is not above thinking budget (${reasoning.thinking.budget_tokens}); using max_tokens=${maxTokens} to satisfy API constraint`
6097
6336
  );
6098
6337
  }
6099
- llm = new import_core18.ChatAnthropic({
6338
+ llm = new import_core19.ChatAnthropic({
6100
6339
  clientOptions: {
6101
6340
  apiKey: requireApiKeyAuth("Anthropic", providerAuth)
6102
6341
  },
@@ -6121,12 +6360,12 @@ var createAgentFactory = (state, options = {}) => {
6121
6360
  const totalBudgetTrimEnabled = envTruthy(
6122
6361
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
6123
6362
  );
6124
- const agent = new import_core18.Agent({
6363
+ const agent = new import_core19.Agent({
6125
6364
  llm,
6126
6365
  tools,
6127
6366
  hostedTools: hostedSearchDefinitions,
6128
6367
  systemPrompt,
6129
- modelRegistry: modelRegistry ?? import_core18.DEFAULT_MODEL_REGISTRY,
6368
+ modelRegistry: modelRegistry ?? import_core19.DEFAULT_MODEL_REGISTRY,
6130
6369
  toolOutputCache: {
6131
6370
  totalBudgetTrim: totalBudgetTrimEnabled
6132
6371
  },
@@ -6182,9 +6421,9 @@ var createAgentFactory = (state, options = {}) => {
6182
6421
  const resolved = sandbox.resolvePath(filePath);
6183
6422
  let before = "";
6184
6423
  try {
6185
- const stat = await import_node_fs15.promises.stat(resolved);
6424
+ const stat = await import_node_fs16.promises.stat(resolved);
6186
6425
  if (!stat.isDirectory()) {
6187
- before = await import_node_fs15.promises.readFile(resolved, "utf8");
6426
+ before = await import_node_fs16.promises.readFile(resolved, "utf8");
6188
6427
  }
6189
6428
  } catch {
6190
6429
  before = "";
@@ -7597,7 +7836,7 @@ var createContextHandlers = ({
7597
7836
  };
7598
7837
 
7599
7838
  // src/rpc/history.ts
7600
- var import_node_fs16 = require("fs");
7839
+ var import_node_fs17 = require("fs");
7601
7840
  var import_node_path14 = __toESM(require("path"), 1);
7602
7841
  var import_node_readline2 = require("readline");
7603
7842
  var import_protocol3 = require("@codelia/protocol");
@@ -7640,7 +7879,7 @@ var parseRunHeader = (headerLine) => {
7640
7879
  }
7641
7880
  };
7642
7881
  var readFirstLine = async (filePath) => {
7643
- const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
7882
+ const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
7644
7883
  const reader = (0, import_node_readline2.createInterface)({
7645
7884
  input: stream,
7646
7885
  crlfDelay: Number.POSITIVE_INFINITY
@@ -7660,7 +7899,7 @@ var collectRunCandidates = async (log2) => {
7660
7899
  const sessionsDir = paths.sessionsDir;
7661
7900
  let yearEntries;
7662
7901
  try {
7663
- yearEntries = await import_node_fs16.promises.readdir(sessionsDir, {
7902
+ yearEntries = await import_node_fs17.promises.readdir(sessionsDir, {
7664
7903
  withFileTypes: true,
7665
7904
  encoding: "utf8"
7666
7905
  });
@@ -7675,7 +7914,7 @@ var collectRunCandidates = async (log2) => {
7675
7914
  const yearPath = import_node_path14.default.join(sessionsDir, yearEntry.name);
7676
7915
  let monthEntries;
7677
7916
  try {
7678
- monthEntries = await import_node_fs16.promises.readdir(yearPath, {
7917
+ monthEntries = await import_node_fs17.promises.readdir(yearPath, {
7679
7918
  withFileTypes: true,
7680
7919
  encoding: "utf8"
7681
7920
  });
@@ -7688,7 +7927,7 @@ var collectRunCandidates = async (log2) => {
7688
7927
  const monthPath = import_node_path14.default.join(yearPath, monthEntry.name);
7689
7928
  let dayEntries;
7690
7929
  try {
7691
- dayEntries = await import_node_fs16.promises.readdir(monthPath, {
7930
+ dayEntries = await import_node_fs17.promises.readdir(monthPath, {
7692
7931
  withFileTypes: true,
7693
7932
  encoding: "utf8"
7694
7933
  });
@@ -7701,7 +7940,7 @@ var collectRunCandidates = async (log2) => {
7701
7940
  const dayPath = import_node_path14.default.join(monthPath, dayEntry.name);
7702
7941
  let files;
7703
7942
  try {
7704
- files = await import_node_fs16.promises.readdir(dayPath, {
7943
+ files = await import_node_fs17.promises.readdir(dayPath, {
7705
7944
  withFileTypes: true,
7706
7945
  encoding: "utf8"
7707
7946
  });
@@ -7713,7 +7952,7 @@ var collectRunCandidates = async (log2) => {
7713
7952
  if (!file.name.endsWith(".jsonl")) continue;
7714
7953
  const filePath = import_node_path14.default.join(dayPath, file.name);
7715
7954
  try {
7716
- const stat = await import_node_fs16.promises.stat(filePath);
7955
+ const stat = await import_node_fs17.promises.stat(filePath);
7717
7956
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
7718
7957
  } catch {
7719
7958
  }
@@ -7751,7 +7990,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
7751
7990
  return runs;
7752
7991
  };
7753
7992
  var readJsonl = async function* (filePath) {
7754
- const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
7993
+ const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
7755
7994
  let buffer = "";
7756
7995
  for await (const chunk of stream) {
7757
7996
  buffer += chunk;
@@ -7869,7 +8108,7 @@ var createHistoryHandlers = ({
7869
8108
  };
7870
8109
 
7871
8110
  // src/rpc/model.ts
7872
- var import_core19 = require("@codelia/core");
8111
+ var import_core20 = require("@codelia/core");
7873
8112
  var import_model_metadata3 = require("@codelia/model-metadata");
7874
8113
  var import_protocol4 = require("@codelia/protocol");
7875
8114
  var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter";
@@ -8113,7 +8352,7 @@ var buildProviderModelList = async ({
8113
8352
  }
8114
8353
  }
8115
8354
  const models = sortModelsByReleaseDate(
8116
- (0, import_core19.listModels)(import_core19.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
8355
+ (0, import_core20.listModels)(import_core20.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
8117
8356
  provider,
8118
8357
  providerEntries
8119
8358
  );
@@ -8237,7 +8476,7 @@ var createModelHandlers = ({
8237
8476
  return;
8238
8477
  }
8239
8478
  if (provider !== "openrouter") {
8240
- const spec = (0, import_core19.resolveModel)(import_core19.DEFAULT_MODEL_REGISTRY, name, provider);
8479
+ const spec = (0, import_core20.resolveModel)(import_core20.DEFAULT_MODEL_REGISTRY, name, provider);
8241
8480
  if (!spec) {
8242
8481
  sendError(id, {
8243
8482
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
@@ -8281,7 +8520,7 @@ var createModelHandlers = ({
8281
8520
  var import_protocol5 = require("@codelia/protocol");
8282
8521
 
8283
8522
  // src/rpc/run-debug.ts
8284
- var import_core20 = require("@codelia/core");
8523
+ var import_core21 = require("@codelia/core");
8285
8524
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
8286
8525
  var DEBUG_MAX_LOG_CHARS = 2e4;
8287
8526
  var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
@@ -8303,7 +8542,7 @@ var stringifyUnknown = (value) => {
8303
8542
  }
8304
8543
  };
8305
8544
  var contentToDebugText = (content, maxChars) => {
8306
- const text = (0, import_core20.stringifyContent)(content, {
8545
+ const text = (0, import_core21.stringifyContent)(content, {
8307
8546
  mode: "log",
8308
8547
  joiner: "\n",
8309
8548
  includeOtherPayload: true
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import path17 from "path";
3
3
  import { SessionStateStoreImpl as SessionStateStoreImpl2 } from "@codelia/storage";
4
4
 
5
5
  // src/agent-factory.ts
6
- import { promises as fs15 } from "fs";
6
+ import { promises as fs16 } from "fs";
7
7
  import {
8
8
  Agent,
9
9
  ANTHROPIC_DEFAULT_MODEL,
@@ -1723,6 +1723,7 @@ var resolveAnthropicMaxTokens = ({
1723
1723
  import {
1724
1724
  applyModelMetadata,
1725
1725
  DEFAULT_MODEL_REGISTRY,
1726
+ resolveModel,
1726
1727
  registerModels
1727
1728
  } from "@codelia/core";
1728
1729
  import { ModelMetadataServiceImpl } from "@codelia/model-metadata";
@@ -1761,6 +1762,26 @@ var toPositiveInteger = (value) => {
1761
1762
  }
1762
1763
  return Math.trunc(value);
1763
1764
  };
1765
+ var resolveDefaultRegistrySpec = (provider, model) => {
1766
+ const normalized = stripProviderPrefix(provider, model);
1767
+ const candidates = [model, normalized, `${provider}/${normalized}`].filter(
1768
+ (value, index, array) => array.indexOf(value) === index
1769
+ );
1770
+ for (const candidate of candidates) {
1771
+ const spec = resolveModel(DEFAULT_MODEL_REGISTRY, candidate, provider);
1772
+ if (spec?.provider === provider) {
1773
+ return spec;
1774
+ }
1775
+ }
1776
+ const normalizedLower = normalized.toLowerCase();
1777
+ for (const spec of Object.values(DEFAULT_MODEL_REGISTRY.modelsById)) {
1778
+ if (spec.provider !== provider) continue;
1779
+ if (spec.id.toLowerCase() === normalizedLower) {
1780
+ return spec;
1781
+ }
1782
+ }
1783
+ return void 0;
1784
+ };
1764
1785
  var withOpenRouterDynamicModel = (registry, llm, entry) => {
1765
1786
  if (llm.provider !== "openrouter") {
1766
1787
  return registry;
@@ -1819,7 +1840,8 @@ var buildModelRegistry = async (llm, options = {}) => {
1819
1840
  );
1820
1841
  }
1821
1842
  if (!resolvedEntry) {
1822
- if (strict) {
1843
+ const fallbackSpec = resolveDefaultRegistrySpec(llm.provider, llm.model);
1844
+ if (strict && !fallbackSpec) {
1823
1845
  throw new Error(
1824
1846
  `Model metadata not found for ${llm.provider}/${llm.model} after refresh`
1825
1847
  );
@@ -2313,11 +2335,13 @@ var parseRawArgsForPrompt = (rawArgs) => parseRawArgsObject(rawArgs);
2313
2335
  // src/permissions/service.ts
2314
2336
  var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2315
2337
  "read",
2338
+ "read_line",
2316
2339
  "grep",
2317
2340
  "glob_search",
2318
2341
  "todo_read",
2319
2342
  "todo_write",
2320
2343
  "tool_output_cache",
2344
+ "tool_output_cache_line",
2321
2345
  "tool_output_cache_grep",
2322
2346
  "agents_resolve",
2323
2347
  "skill_search",
@@ -4721,15 +4745,76 @@ import { promises as fs13 } from "fs";
4721
4745
  import { defineTool as defineTool8 } from "@codelia/core";
4722
4746
  import { z as z9 } from "zod";
4723
4747
  var DEFAULT_READ_LIMIT = 2e3;
4724
- var MAX_LINE_LENGTH = 2e3;
4725
- var MAX_BYTES = 50 * 1024;
4748
+ var DEFAULT_MAX_LINE_LENGTH = 5e4;
4749
+ var DEFAULT_MAX_BYTES = 64 * 1024;
4750
+ var parsePositiveIntEnv = (key, fallback) => {
4751
+ const raw = process.env[key];
4752
+ if (!raw) return fallback;
4753
+ const parsed = Number.parseInt(raw, 10);
4754
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
4755
+ return parsed;
4756
+ };
4757
+ var MAX_LINE_LENGTH = parsePositiveIntEnv(
4758
+ "CODELIA_READ_MAX_LINE_LENGTH",
4759
+ DEFAULT_MAX_LINE_LENGTH
4760
+ );
4761
+ var MAX_BYTES = parsePositiveIntEnv("CODELIA_READ_MAX_BYTES", DEFAULT_MAX_BYTES);
4762
+ var clipLongLine = (line) => {
4763
+ if (line.length <= MAX_LINE_LENGTH) {
4764
+ return line;
4765
+ }
4766
+ return `${line.slice(0, MAX_LINE_LENGTH)}...`;
4767
+ };
4768
+ var clipUtf8ToBytes = (value, maxBytes) => {
4769
+ if (maxBytes <= 0 || value.length === 0) return "";
4770
+ let bytes = 0;
4771
+ let out = "";
4772
+ for (const ch of value) {
4773
+ const next = Buffer.byteLength(ch, "utf8");
4774
+ if (bytes + next > maxBytes) break;
4775
+ out += ch;
4776
+ bytes += next;
4777
+ }
4778
+ return out;
4779
+ };
4780
+ var clipLineToByteBudget = (line, maxBytes) => {
4781
+ if (maxBytes <= 0) return "";
4782
+ if (Buffer.byteLength(line, "utf8") <= maxBytes) return line;
4783
+ const suffix = "...";
4784
+ const suffixBytes = Buffer.byteLength(suffix, "utf8");
4785
+ if (maxBytes <= suffixBytes) {
4786
+ return clipUtf8ToBytes(line, maxBytes);
4787
+ }
4788
+ return `${clipUtf8ToBytes(line, maxBytes - suffixBytes)}${suffix}`;
4789
+ };
4790
+ var buildTooLargeToReadError = (options) => [
4791
+ `TOO_LARGE_TO_READ: output exceeds per-call limit (${MAX_BYTES} bytes).`,
4792
+ `file_path=${options.filePath} offset=${options.offset} limit=${options.limit}`,
4793
+ "Try split reads:",
4794
+ `- read({"file_path":"${options.filePath}","offset":${options.offset},"limit":2000})`,
4795
+ `- read({"file_path":"${options.filePath}","offset":${options.nextOffset},"limit":2000})`
4796
+ ].join("\n").trim();
4797
+ var buildSingleLineByteCapError = (options) => [
4798
+ `TOO_LARGE_TO_READ: requested line ${options.lineNumber} exceeds per-call byte limit (${MAX_BYTES} bytes).`,
4799
+ `file_path=${options.filePath} line_number=${options.lineNumber}`,
4800
+ "Offset-based pagination cannot continue within one physical line.",
4801
+ "Use read_line for char-based paging or retry with allow_truncate=true.",
4802
+ `read_line({"file_path":"${options.filePath}","line_number":${options.lineNumber},"char_offset":0,"char_limit":10000})`
4803
+ ].join("\n").trim();
4804
+ var buildLineTooLongError = (options) => [
4805
+ `LINE_TOO_LONG: line ${options.lineNumber} has ${options.lineLength} chars (max ${MAX_LINE_LENGTH}).`,
4806
+ `file_path=${options.filePath}`,
4807
+ "Use read_line for char-based paging or retry with allow_truncate=true.",
4808
+ `read_line({"file_path":"${options.filePath}","line_number":${options.lineNumber},"char_offset":0,"char_limit":10000})`
4809
+ ].join("\n").trim();
4726
4810
  var createReadTool = (sandboxKey) => defineTool8({
4727
4811
  name: "read",
4728
4812
  description: "Read a text file with optional 0-based line offset and line limit.",
4729
4813
  input: z9.object({
4730
4814
  file_path: z9.string().describe("File path under the sandbox root."),
4731
4815
  offset: z9.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4732
- limit: z9.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4816
+ limit: z9.number().int().positive().optional().describe("Max lines to read. Default 2000."),
4817
+ allow_truncate: z9.boolean().optional().describe("Allow truncation when output is too large. Default false.")
4733
4818
  }),
4734
4819
  execute: async (input, ctx) => {
4735
4820
  let resolved;
@@ -4755,34 +4840,91 @@ var createReadTool = (sandboxKey) => defineTool8({
4755
4840
  }
4756
4841
  const offset = input.offset ?? 0;
4757
4842
  const limit = input.limit ?? DEFAULT_READ_LIMIT;
4843
+ const allowTruncate = input.allow_truncate ?? false;
4758
4844
  if (offset >= lines.length) {
4759
- return `Offset exceeds file length: ${input.file_path}`;
4845
+ return `Offset exceeds output length: ${input.file_path}`;
4760
4846
  }
4761
- const raw = [];
4847
+ const outputLines = [];
4762
4848
  let bytes = 0;
4763
4849
  let truncatedByBytes = false;
4850
+ let clipped = false;
4851
+ let firstClippedLineNumber = null;
4764
4852
  for (let index = offset; index < Math.min(lines.length, offset + limit); index += 1) {
4765
- const line = lines[index].length > MAX_LINE_LENGTH ? `${lines[index].slice(0, MAX_LINE_LENGTH)}...` : lines[index];
4766
- const size = Buffer.byteLength(line, "utf8") + (raw.length > 0 ? 1 : 0);
4853
+ const originalLine = lines[index] ?? "";
4854
+ if (originalLine.length > MAX_LINE_LENGTH && !allowTruncate) {
4855
+ return buildLineTooLongError({
4856
+ filePath: input.file_path,
4857
+ lineNumber: index + 1,
4858
+ lineLength: originalLine.length
4859
+ });
4860
+ }
4861
+ const line = allowTruncate ? clipLongLine(originalLine) : originalLine;
4862
+ if (line.length !== originalLine.length) {
4863
+ clipped = true;
4864
+ if (firstClippedLineNumber === null) {
4865
+ firstClippedLineNumber = index + 1;
4866
+ }
4867
+ }
4868
+ const numberedLine = `${String(index + 1).padStart(5, " ")} ${line}`;
4869
+ const size = Buffer.byteLength(numberedLine, "utf8") + (outputLines.length > 0 ? 1 : 0);
4767
4870
  if (bytes + size > MAX_BYTES) {
4871
+ if (!allowTruncate) {
4872
+ if (outputLines.length === 0) {
4873
+ return buildSingleLineByteCapError({
4874
+ filePath: input.file_path,
4875
+ lineNumber: index + 1
4876
+ });
4877
+ }
4878
+ return buildTooLargeToReadError({
4879
+ filePath: input.file_path,
4880
+ offset,
4881
+ limit,
4882
+ nextOffset: Math.max(offset + outputLines.length, offset + 1)
4883
+ });
4884
+ }
4885
+ if (outputLines.length === 0) {
4886
+ const prefix = `${String(index + 1).padStart(5, " ")} `;
4887
+ const budget = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
4888
+ const clippedByBytes = clipLineToByteBudget(line, budget);
4889
+ if (clippedByBytes.length > 0) {
4890
+ outputLines.push(clippedByBytes);
4891
+ bytes = Buffer.byteLength(
4892
+ `${prefix}${clippedByBytes}`,
4893
+ "utf8"
4894
+ );
4895
+ clipped = true;
4896
+ if (firstClippedLineNumber === null) {
4897
+ firstClippedLineNumber = index + 1;
4898
+ }
4899
+ }
4900
+ }
4768
4901
  truncatedByBytes = true;
4769
4902
  break;
4770
4903
  }
4771
- raw.push(line);
4904
+ outputLines.push(line);
4772
4905
  bytes += size;
4773
4906
  }
4774
- const numbered = raw.map(
4907
+ const numbered = outputLines.map(
4775
4908
  (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4776
4909
  );
4777
- const lastReadLine = offset + raw.length;
4910
+ const lastReadLine = offset + outputLines.length;
4778
4911
  const hasMoreLines = lines.length > lastReadLine;
4779
- const truncated = truncatedByBytes || hasMoreLines;
4780
4912
  let output = numbered.join("\n");
4781
- if (truncated) {
4782
- const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "File has more lines.";
4913
+ if (truncatedByBytes || hasMoreLines) {
4914
+ const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "Output has more lines.";
4783
4915
  output += `
4784
4916
 
4785
4917
  ${reason} Use offset to read beyond line ${lastReadLine}.`;
4918
+ }
4919
+ if (clipped) {
4920
+ output += `
4921
+
4922
+ Long physical lines are clipped at ${MAX_LINE_LENGTH} chars.`;
4923
+ }
4924
+ if (allowTruncate && firstClippedLineNumber !== null) {
4925
+ output += `
4926
+
4927
+ For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
4786
4928
  }
4787
4929
  return output;
4788
4930
  } catch (error) {
@@ -5235,14 +5377,14 @@ var todoWriteInputSchema = z14.object({
5235
5377
  ctx.addIssue({
5236
5378
  code: z14.ZodIssueCode.custom,
5237
5379
  path: ["updates"],
5238
- message: "patch mode requires at least one update item."
5380
+ message: "patch mode requires at least one item in updates."
5239
5381
  });
5240
5382
  }
5241
5383
  if (input.todos.length > 0) {
5242
5384
  ctx.addIssue({
5243
5385
  code: z14.ZodIssueCode.custom,
5244
5386
  path: ["todos"],
5245
- message: "patch mode does not accept todos."
5387
+ message: "patch mode uses updates only; leave todos empty."
5246
5388
  });
5247
5389
  }
5248
5390
  return;
@@ -5252,14 +5394,14 @@ var todoWriteInputSchema = z14.object({
5252
5394
  ctx.addIssue({
5253
5395
  code: z14.ZodIssueCode.custom,
5254
5396
  path: ["todos"],
5255
- message: "clear mode does not accept todos."
5397
+ message: "clear mode does not accept todos; omit todos and updates."
5256
5398
  });
5257
5399
  }
5258
5400
  if (input.updates.length > 0) {
5259
5401
  ctx.addIssue({
5260
5402
  code: z14.ZodIssueCode.custom,
5261
5403
  path: ["updates"],
5262
- message: "clear mode does not accept updates."
5404
+ message: "clear mode does not accept updates; omit todos and updates."
5263
5405
  });
5264
5406
  }
5265
5407
  return;
@@ -5268,14 +5410,14 @@ var todoWriteInputSchema = z14.object({
5268
5410
  ctx.addIssue({
5269
5411
  code: z14.ZodIssueCode.custom,
5270
5412
  path: ["todos"],
5271
- message: `${input.mode} mode requires at least one todo item.`
5413
+ message: `${input.mode} mode requires at least one item in todos.`
5272
5414
  });
5273
5415
  }
5274
5416
  if (input.updates.length > 0) {
5275
5417
  ctx.addIssue({
5276
5418
  code: z14.ZodIssueCode.custom,
5277
5419
  path: ["updates"],
5278
- message: `${input.mode} mode does not accept updates.`
5420
+ message: `${input.mode} mode uses todos only; leave updates empty.`
5279
5421
  });
5280
5422
  }
5281
5423
  });
@@ -5318,9 +5460,10 @@ var withPatchApplied = (currentTodos, updates) => {
5318
5460
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
5319
5461
  const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5320
5462
  if (missingIds.length > 0) {
5463
+ const knownIds = currentTodos.map((todo) => todo.id);
5321
5464
  return {
5322
5465
  todos: [...currentTodos],
5323
- error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}`
5466
+ error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}. Existing id(s): ${knownIds.length ? knownIds.join(", ") : "(none)"}. Run todo_read to inspect the current plan before patching.`
5324
5467
  };
5325
5468
  }
5326
5469
  let nextInputs = currentTodos.map((todo) => ({ ...todo }));
@@ -5374,7 +5517,8 @@ var createTodoWriteTool = (sandboxKey, sessionContextKey) => defineTool13({
5374
5517
  }
5375
5518
  const inProgressCount = countInProgressTodos(nextTodos);
5376
5519
  if (inProgressCount > 1) {
5377
- return `Invalid todo state: ${inProgressCount} items are in_progress. Keep at most one item in_progress so tasks can be handled one-by-one.`;
5520
+ const inProgressIds = nextTodos.filter((todo) => todo.status === "in_progress").map((todo) => todo.id);
5521
+ return `Invalid todo state: ${inProgressCount} items are in_progress (${inProgressIds.join(", ")}). Keep at most one item in_progress so tasks can be handled one-by-one.`;
5378
5522
  }
5379
5523
  if (nextTodos.length === 0) {
5380
5524
  clearTodosForSession(todoSessionId);
@@ -5394,7 +5538,8 @@ var createToolOutputCacheTool = (store) => defineTool14({
5394
5538
  input: z15.object({
5395
5539
  ref_id: z15.string().describe("Tool output reference ID."),
5396
5540
  offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
5397
- limit: z15.number().int().positive().optional().describe("Optional max number of lines to return.")
5541
+ limit: z15.number().int().positive().optional().describe("Optional max number of lines to return."),
5542
+ allow_truncate: z15.boolean().optional().describe("Allow truncation when output is too large. Default false.")
5398
5543
  }),
5399
5544
  execute: async (input) => {
5400
5545
  if (!store.read) {
@@ -5403,13 +5548,38 @@ var createToolOutputCacheTool = (store) => defineTool14({
5403
5548
  try {
5404
5549
  return await store.read(input.ref_id, {
5405
5550
  offset: input.offset,
5406
- limit: input.limit
5551
+ limit: input.limit,
5552
+ allow_truncate: input.allow_truncate
5407
5553
  });
5408
5554
  } catch (error) {
5409
5555
  return `Error reading tool output cache: ${String(error)}`;
5410
5556
  }
5411
5557
  }
5412
5558
  });
5559
+ var createToolOutputCacheLineTool = (store) => defineTool14({
5560
+ name: "tool_output_cache_line",
5561
+ description: "Read a single cached output line segment by line number and char offset.",
5562
+ input: z15.object({
5563
+ ref_id: z15.string().describe("Tool output reference ID."),
5564
+ line_number: z15.number().int().positive().describe("1-based line number to read."),
5565
+ char_offset: z15.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5566
+ char_limit: z15.number().int().positive().optional().describe("Max chars to return.")
5567
+ }),
5568
+ execute: async (input) => {
5569
+ if (!store.readLine) {
5570
+ return "tool_output_cache_line is unavailable.";
5571
+ }
5572
+ try {
5573
+ return await store.readLine(input.ref_id, {
5574
+ line_number: input.line_number,
5575
+ char_offset: input.char_offset,
5576
+ char_limit: input.char_limit
5577
+ });
5578
+ } catch (error) {
5579
+ return `Error reading cache line: ${String(error)}`;
5580
+ }
5581
+ }
5582
+ });
5413
5583
  var createToolOutputCacheGrepTool = (store) => defineTool14({
5414
5584
  name: "tool_output_cache_grep",
5415
5585
  description: "Search cached tool output by ref_id.",
@@ -5439,11 +5609,79 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
5439
5609
  }
5440
5610
  });
5441
5611
 
5442
- // src/tools/write.ts
5612
+ // src/tools/read-line.ts
5443
5613
  import { promises as fs14 } from "fs";
5444
- import path13 from "path";
5445
5614
  import { defineTool as defineTool15 } from "@codelia/core";
5446
5615
  import { z as z16 } from "zod";
5616
+ var DEFAULT_CHAR_LIMIT = 1e4;
5617
+ var MAX_CHAR_LIMIT = 1e5;
5618
+ var createReadLineTool = (sandboxKey) => defineTool15({
5619
+ name: "read_line",
5620
+ description: "Read a single line segment by 1-based line number and 0-based char offset.",
5621
+ input: z16.object({
5622
+ file_path: z16.string().describe("File path under the sandbox root."),
5623
+ line_number: z16.number().int().positive().describe("1-based line number to read."),
5624
+ char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5625
+ char_limit: z16.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5626
+ }),
5627
+ execute: async (input, ctx) => {
5628
+ let resolved;
5629
+ try {
5630
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
5631
+ resolved = sandbox.resolvePath(input.file_path);
5632
+ } catch (error) {
5633
+ return `Security error: ${String(error)}`;
5634
+ }
5635
+ try {
5636
+ const stat = await fs14.stat(resolved);
5637
+ if (stat.isDirectory()) {
5638
+ return `Path is a directory: ${input.file_path}`;
5639
+ }
5640
+ } catch {
5641
+ return `File not found: ${input.file_path}`;
5642
+ }
5643
+ try {
5644
+ const content = await fs14.readFile(resolved, "utf8");
5645
+ const lines = content.split(/\r?\n/);
5646
+ const lineIndex = input.line_number - 1;
5647
+ if (lineIndex >= lines.length) {
5648
+ return `Line number out of range: ${input.line_number} (total ${lines.length})`;
5649
+ }
5650
+ const line = lines[lineIndex] ?? "";
5651
+ const charOffset = input.char_offset ?? 0;
5652
+ const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5653
+ if (charOffset > line.length) {
5654
+ return `char_offset out of range: ${charOffset} (line length ${line.length})`;
5655
+ }
5656
+ const segment = line.slice(charOffset, charOffset + charLimit);
5657
+ const endOffset = charOffset + segment.length;
5658
+ const hasMore = endOffset < line.length;
5659
+ const header = [
5660
+ `line_number=${input.line_number}`,
5661
+ `line_length=${line.length}`,
5662
+ `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5663
+ ].join(" ");
5664
+ let output = `${header}
5665
+ ${segment}`;
5666
+ if (hasMore) {
5667
+ output += `
5668
+
5669
+ Use char_offset=${endOffset} to continue.`;
5670
+ output += `
5671
+ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5672
+ }
5673
+ return output;
5674
+ } catch (error) {
5675
+ return `Error reading file: ${String(error)}`;
5676
+ }
5677
+ }
5678
+ });
5679
+
5680
+ // src/tools/write.ts
5681
+ import { promises as fs15 } from "fs";
5682
+ import path13 from "path";
5683
+ import { defineTool as defineTool16 } from "@codelia/core";
5684
+ import { z as z17 } from "zod";
5447
5685
  var buildDiffPreview = (content, filePath) => {
5448
5686
  const diff = createUnifiedDiff(filePath, "", content);
5449
5687
  if (!diff) {
@@ -5453,12 +5691,12 @@ var buildDiffPreview = (content, filePath) => {
5453
5691
  }
5454
5692
  return diff;
5455
5693
  };
5456
- var createWriteTool = (sandboxKey) => defineTool15({
5694
+ var createWriteTool = (sandboxKey) => defineTool16({
5457
5695
  name: "write",
5458
5696
  description: "Write text to a file, creating parent directories if needed.",
5459
- input: z16.object({
5460
- file_path: z16.string().describe("File path under the sandbox root."),
5461
- content: z16.string().describe("UTF-8 text content to write.")
5697
+ input: z17.object({
5698
+ file_path: z17.string().describe("File path under the sandbox root."),
5699
+ content: z17.string().describe("UTF-8 text content to write.")
5462
5700
  }),
5463
5701
  execute: async (input, ctx) => {
5464
5702
  let resolved;
@@ -5469,8 +5707,8 @@ var createWriteTool = (sandboxKey) => defineTool15({
5469
5707
  return `Security error: ${String(error)}`;
5470
5708
  }
5471
5709
  try {
5472
- await fs14.mkdir(path13.dirname(resolved), { recursive: true });
5473
- await fs14.writeFile(resolved, input.content, "utf8");
5710
+ await fs15.mkdir(path13.dirname(resolved), { recursive: true });
5711
+ await fs15.writeFile(resolved, input.content, "utf8");
5474
5712
  const diff = buildDiffPreview(input.content, input.file_path);
5475
5713
  return {
5476
5714
  summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
@@ -5487,6 +5725,7 @@ var createWriteTool = (sandboxKey) => defineTool15({
5487
5725
  var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {}) => [
5488
5726
  createBashTool(sandboxKey),
5489
5727
  createReadTool(sandboxKey),
5728
+ createReadLineTool(sandboxKey),
5490
5729
  createWriteTool(sandboxKey),
5491
5730
  createEditTool(sandboxKey),
5492
5731
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
@@ -5497,6 +5736,7 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
5497
5736
  createGrepTool(sandboxKey),
5498
5737
  ...options.toolOutputCacheStore ? [
5499
5738
  createToolOutputCacheTool(options.toolOutputCacheStore),
5739
+ createToolOutputCacheLineTool(options.toolOutputCacheStore),
5500
5740
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
5501
5741
  ] : [],
5502
5742
  createTodoReadTool(sandboxKey, options.todoSessionContextKey),
@@ -6181,9 +6421,9 @@ var createAgentFactory = (state, options = {}) => {
6181
6421
  const resolved = sandbox.resolvePath(filePath);
6182
6422
  let before = "";
6183
6423
  try {
6184
- const stat = await fs15.stat(resolved);
6424
+ const stat = await fs16.stat(resolved);
6185
6425
  if (!stat.isDirectory()) {
6186
- before = await fs15.readFile(resolved, "utf8");
6426
+ before = await fs16.readFile(resolved, "utf8");
6187
6427
  }
6188
6428
  } catch {
6189
6429
  before = "";
@@ -7612,7 +7852,7 @@ var createContextHandlers = ({
7612
7852
  };
7613
7853
 
7614
7854
  // src/rpc/history.ts
7615
- import { createReadStream, promises as fs16 } from "fs";
7855
+ import { createReadStream, promises as fs17 } from "fs";
7616
7856
  import path14 from "path";
7617
7857
  import { createInterface as createInterface2 } from "readline";
7618
7858
  import {
@@ -7677,7 +7917,7 @@ var collectRunCandidates = async (log2) => {
7677
7917
  const sessionsDir = paths.sessionsDir;
7678
7918
  let yearEntries;
7679
7919
  try {
7680
- yearEntries = await fs16.readdir(sessionsDir, {
7920
+ yearEntries = await fs17.readdir(sessionsDir, {
7681
7921
  withFileTypes: true,
7682
7922
  encoding: "utf8"
7683
7923
  });
@@ -7692,7 +7932,7 @@ var collectRunCandidates = async (log2) => {
7692
7932
  const yearPath = path14.join(sessionsDir, yearEntry.name);
7693
7933
  let monthEntries;
7694
7934
  try {
7695
- monthEntries = await fs16.readdir(yearPath, {
7935
+ monthEntries = await fs17.readdir(yearPath, {
7696
7936
  withFileTypes: true,
7697
7937
  encoding: "utf8"
7698
7938
  });
@@ -7705,7 +7945,7 @@ var collectRunCandidates = async (log2) => {
7705
7945
  const monthPath = path14.join(yearPath, monthEntry.name);
7706
7946
  let dayEntries;
7707
7947
  try {
7708
- dayEntries = await fs16.readdir(monthPath, {
7948
+ dayEntries = await fs17.readdir(monthPath, {
7709
7949
  withFileTypes: true,
7710
7950
  encoding: "utf8"
7711
7951
  });
@@ -7718,7 +7958,7 @@ var collectRunCandidates = async (log2) => {
7718
7958
  const dayPath = path14.join(monthPath, dayEntry.name);
7719
7959
  let files;
7720
7960
  try {
7721
- files = await fs16.readdir(dayPath, {
7961
+ files = await fs17.readdir(dayPath, {
7722
7962
  withFileTypes: true,
7723
7963
  encoding: "utf8"
7724
7964
  });
@@ -7730,7 +7970,7 @@ var collectRunCandidates = async (log2) => {
7730
7970
  if (!file.name.endsWith(".jsonl")) continue;
7731
7971
  const filePath = path14.join(dayPath, file.name);
7732
7972
  try {
7733
- const stat = await fs16.stat(filePath);
7973
+ const stat = await fs17.stat(filePath);
7734
7974
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
7735
7975
  } catch {
7736
7976
  }
@@ -7889,7 +8129,7 @@ var createHistoryHandlers = ({
7889
8129
  import {
7890
8130
  DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY3,
7891
8131
  listModels,
7892
- resolveModel
8132
+ resolveModel as resolveModel2
7893
8133
  } from "@codelia/core";
7894
8134
  import { ModelMetadataServiceImpl as ModelMetadataServiceImpl3 } from "@codelia/model-metadata";
7895
8135
  import {
@@ -8260,7 +8500,7 @@ var createModelHandlers = ({
8260
8500
  return;
8261
8501
  }
8262
8502
  if (provider !== "openrouter") {
8263
- const spec = resolveModel(DEFAULT_MODEL_REGISTRY3, name, provider);
8503
+ const spec = resolveModel2(DEFAULT_MODEL_REGISTRY3, name, provider);
8264
8504
  if (!spec) {
8265
8505
  sendError(id, {
8266
8506
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/runtime",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20 <25"
@@ -23,14 +23,14 @@
23
23
  "typecheck": "tsc --noEmit"
24
24
  },
25
25
  "dependencies": {
26
- "@codelia/config": "0.1.35",
27
- "@codelia/config-loader": "0.1.35",
28
- "@codelia/core": "0.1.35",
29
- "@codelia/logger": "0.1.35",
30
- "@codelia/model-metadata": "0.1.35",
31
- "@codelia/protocol": "0.1.35",
32
- "@codelia/shared-types": "0.1.35",
33
- "@codelia/storage": "0.1.35",
26
+ "@codelia/config": "0.1.37",
27
+ "@codelia/config-loader": "0.1.37",
28
+ "@codelia/core": "0.1.37",
29
+ "@codelia/logger": "0.1.37",
30
+ "@codelia/model-metadata": "0.1.37",
31
+ "@codelia/protocol": "0.1.37",
32
+ "@codelia/shared-types": "0.1.37",
33
+ "@codelia/storage": "0.1.37",
34
34
  "eventsource-parser": "^3.0.6",
35
35
  "oauth4webapi": "^3.8.4",
36
36
  "zod": "^4.3.5"