@codelia/runtime 0.1.36 → 0.1.38

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 +340 -126
  2. package/dist/index.js +328 -112
  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,38 +4745,68 @@ 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;
4727
- var splitLongLine = (line) => {
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) => {
4728
4763
  if (line.length <= MAX_LINE_LENGTH) {
4729
- return [line];
4730
- }
4731
- const chunks = [];
4732
- for (let start = 0; start < line.length; start += MAX_LINE_LENGTH) {
4733
- chunks.push(line.slice(start, start + MAX_LINE_LENGTH));
4734
- }
4735
- return chunks;
4736
- };
4737
- var toDisplayLines = (physicalLines, wrapLongLines) => {
4738
- let wrapped = false;
4739
- let clipped = false;
4740
- const display = [];
4741
- for (const line of physicalLines) {
4742
- if (wrapLongLines) {
4743
- const chunks = splitLongLine(line);
4744
- if (chunks.length > 1) wrapped = true;
4745
- display.push(...chunks);
4746
- continue;
4747
- }
4748
- if (line.length > MAX_LINE_LENGTH) {
4749
- clipped = true;
4750
- display.push(`${line.slice(0, MAX_LINE_LENGTH)}...`);
4751
- continue;
4752
- }
4753
- display.push(line);
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;
4754
4777
  }
4755
- return { lines: display, wrapped, clipped };
4778
+ return out;
4756
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();
4757
4810
  var createReadTool = (sandboxKey) => (0, import_core10.defineTool)({
4758
4811
  name: "read",
4759
4812
  description: "Read a text file with optional 0-based line offset and line limit.",
@@ -4761,7 +4814,7 @@ var createReadTool = (sandboxKey) => (0, import_core10.defineTool)({
4761
4814
  file_path: import_zod9.z.string().describe("File path under the sandbox root."),
4762
4815
  offset: import_zod9.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4763
4816
  limit: import_zod9.z.number().int().positive().optional().describe("Max lines to read. Default 2000."),
4764
- wrap_long_lines: import_zod9.z.boolean().optional().describe("Enable to paginate very long single-line output. Default false.")
4817
+ allow_truncate: import_zod9.z.boolean().optional().describe("Allow truncation when output is too large. Default false.")
4765
4818
  }),
4766
4819
  execute: async (input, ctx) => {
4767
4820
  let resolved;
@@ -4781,53 +4834,97 @@ var createReadTool = (sandboxKey) => (0, import_core10.defineTool)({
4781
4834
  }
4782
4835
  try {
4783
4836
  const content = await import_node_fs13.promises.readFile(resolved, "utf8");
4784
- const physicalLines = content.split(/\r?\n/);
4785
- if (physicalLines.length === 0) {
4837
+ const lines = content.split(/\r?\n/);
4838
+ if (lines.length === 0) {
4786
4839
  return "";
4787
4840
  }
4788
- const wrapLongLines = input.wrap_long_lines ?? false;
4789
- const display = toDisplayLines(physicalLines, wrapLongLines);
4790
4841
  const offset = input.offset ?? 0;
4791
4842
  const limit = input.limit ?? DEFAULT_READ_LIMIT;
4792
- if (offset >= display.lines.length) {
4843
+ const allowTruncate = input.allow_truncate ?? false;
4844
+ if (offset >= lines.length) {
4793
4845
  return `Offset exceeds output length: ${input.file_path}`;
4794
4846
  }
4795
- const raw = [];
4847
+ const outputLines = [];
4796
4848
  let bytes = 0;
4797
4849
  let truncatedByBytes = false;
4798
- for (let index = offset; index < Math.min(display.lines.length, offset + limit); index += 1) {
4799
- const line = display.lines[index] ?? "";
4850
+ let clipped = false;
4851
+ let firstClippedLineNumber = null;
4852
+ for (let index = offset; index < Math.min(lines.length, offset + limit); index += 1) {
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
+ }
4800
4868
  const numberedLine = `${String(index + 1).padStart(5, " ")} ${line}`;
4801
- const size = Buffer.byteLength(numberedLine, "utf8") + (raw.length > 0 ? 1 : 0);
4869
+ const size = Buffer.byteLength(numberedLine, "utf8") + (outputLines.length > 0 ? 1 : 0);
4802
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
+ }
4803
4901
  truncatedByBytes = true;
4804
4902
  break;
4805
4903
  }
4806
- raw.push(line);
4904
+ outputLines.push(line);
4807
4905
  bytes += size;
4808
4906
  }
4809
- const numbered = raw.map(
4907
+ const numbered = outputLines.map(
4810
4908
  (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4811
4909
  );
4812
- const lastReadLine = offset + raw.length;
4813
- const hasMoreLines = display.lines.length > lastReadLine;
4814
- const truncated = truncatedByBytes || hasMoreLines;
4910
+ const lastReadLine = offset + outputLines.length;
4911
+ const hasMoreLines = lines.length > lastReadLine;
4815
4912
  let output = numbered.join("\n");
4816
- if (truncated) {
4913
+ if (truncatedByBytes || hasMoreLines) {
4817
4914
  const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "Output has more lines.";
4818
4915
  output += `
4819
4916
 
4820
4917
  ${reason} Use offset to read beyond line ${lastReadLine}.`;
4821
4918
  }
4822
- if (display.wrapped) {
4919
+ if (clipped) {
4823
4920
  output += `
4824
4921
 
4825
- Long physical lines are wrapped at ${MAX_LINE_LENGTH} chars per display line. Wrapped chunks are display-only and may not match exact source text for edit.`;
4922
+ Long physical lines are clipped at ${MAX_LINE_LENGTH} chars.`;
4826
4923
  }
4827
- if (display.clipped) {
4924
+ if (allowTruncate && firstClippedLineNumber !== null) {
4828
4925
  output += `
4829
4926
 
4830
- Long physical lines are clipped at ${MAX_LINE_LENGTH} chars. Set wrap_long_lines=true to paginate full lines. Clipped output is display-only and may not match exact source text for edit.`;
4927
+ For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
4831
4928
  }
4832
4929
  return output;
4833
4930
  } catch (error) {
@@ -5280,14 +5377,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5280
5377
  ctx.addIssue({
5281
5378
  code: import_zod14.z.ZodIssueCode.custom,
5282
5379
  path: ["updates"],
5283
- message: "patch mode requires at least one update item."
5380
+ message: "patch mode requires at least one item in updates."
5284
5381
  });
5285
5382
  }
5286
5383
  if (input.todos.length > 0) {
5287
5384
  ctx.addIssue({
5288
5385
  code: import_zod14.z.ZodIssueCode.custom,
5289
5386
  path: ["todos"],
5290
- message: "patch mode does not accept todos."
5387
+ message: "patch mode uses updates only; leave todos empty."
5291
5388
  });
5292
5389
  }
5293
5390
  return;
@@ -5297,14 +5394,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5297
5394
  ctx.addIssue({
5298
5395
  code: import_zod14.z.ZodIssueCode.custom,
5299
5396
  path: ["todos"],
5300
- message: "clear mode does not accept todos."
5397
+ message: "clear mode does not accept todos; omit todos and updates."
5301
5398
  });
5302
5399
  }
5303
5400
  if (input.updates.length > 0) {
5304
5401
  ctx.addIssue({
5305
5402
  code: import_zod14.z.ZodIssueCode.custom,
5306
5403
  path: ["updates"],
5307
- message: "clear mode does not accept updates."
5404
+ message: "clear mode does not accept updates; omit todos and updates."
5308
5405
  });
5309
5406
  }
5310
5407
  return;
@@ -5313,14 +5410,14 @@ var todoWriteInputSchema = import_zod14.z.object({
5313
5410
  ctx.addIssue({
5314
5411
  code: import_zod14.z.ZodIssueCode.custom,
5315
5412
  path: ["todos"],
5316
- message: `${input.mode} mode requires at least one todo item.`
5413
+ message: `${input.mode} mode requires at least one item in todos.`
5317
5414
  });
5318
5415
  }
5319
5416
  if (input.updates.length > 0) {
5320
5417
  ctx.addIssue({
5321
5418
  code: import_zod14.z.ZodIssueCode.custom,
5322
5419
  path: ["updates"],
5323
- message: `${input.mode} mode does not accept updates.`
5420
+ message: `${input.mode} mode uses todos only; leave updates empty.`
5324
5421
  });
5325
5422
  }
5326
5423
  });
@@ -5363,9 +5460,10 @@ var withPatchApplied = (currentTodos, updates) => {
5363
5460
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
5364
5461
  const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5365
5462
  if (missingIds.length > 0) {
5463
+ const knownIds = currentTodos.map((todo) => todo.id);
5366
5464
  return {
5367
5465
  todos: [...currentTodos],
5368
- 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.`
5369
5467
  };
5370
5468
  }
5371
5469
  let nextInputs = currentTodos.map((todo) => ({ ...todo }));
@@ -5419,7 +5517,8 @@ var createTodoWriteTool = (sandboxKey, sessionContextKey) => (0, import_core15.d
5419
5517
  }
5420
5518
  const inProgressCount = countInProgressTodos(nextTodos);
5421
5519
  if (inProgressCount > 1) {
5422
- 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.`;
5423
5522
  }
5424
5523
  if (nextTodos.length === 0) {
5425
5524
  clearTodosForSession(todoSessionId);
@@ -5440,7 +5539,7 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
5440
5539
  ref_id: import_zod15.z.string().describe("Tool output reference ID."),
5441
5540
  offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
5442
5541
  limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return."),
5443
- wrap_long_lines: import_zod15.z.boolean().optional().describe("Enable to paginate very long single-line output. Default false.")
5542
+ allow_truncate: import_zod15.z.boolean().optional().describe("Allow truncation when output is too large. Default false.")
5444
5543
  }),
5445
5544
  execute: async (input) => {
5446
5545
  if (!store.read) {
@@ -5450,13 +5549,37 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
5450
5549
  return await store.read(input.ref_id, {
5451
5550
  offset: input.offset,
5452
5551
  limit: input.limit,
5453
- wrap_long_lines: input.wrap_long_lines
5552
+ allow_truncate: input.allow_truncate
5454
5553
  });
5455
5554
  } catch (error) {
5456
5555
  return `Error reading tool output cache: ${String(error)}`;
5457
5556
  }
5458
5557
  }
5459
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
+ });
5460
5583
  var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
5461
5584
  name: "tool_output_cache_grep",
5462
5585
  description: "Search cached tool output by ref_id.",
@@ -5486,11 +5609,79 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
5486
5609
  }
5487
5610
  });
5488
5611
 
5489
- // src/tools/write.ts
5612
+ // src/tools/read-line.ts
5490
5613
  var import_node_fs14 = require("fs");
5491
- var import_node_path13 = __toESM(require("path"), 1);
5492
5614
  var import_core17 = require("@codelia/core");
5493
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");
5494
5685
  var buildDiffPreview = (content, filePath) => {
5495
5686
  const diff = createUnifiedDiff(filePath, "", content);
5496
5687
  if (!diff) {
@@ -5500,12 +5691,12 @@ var buildDiffPreview = (content, filePath) => {
5500
5691
  }
5501
5692
  return diff;
5502
5693
  };
5503
- var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5694
+ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
5504
5695
  name: "write",
5505
5696
  description: "Write text to a file, creating parent directories if needed.",
5506
- input: import_zod16.z.object({
5507
- file_path: import_zod16.z.string().describe("File path under the sandbox root."),
5508
- 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.")
5509
5700
  }),
5510
5701
  execute: async (input, ctx) => {
5511
5702
  let resolved;
@@ -5516,8 +5707,8 @@ var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5516
5707
  return `Security error: ${String(error)}`;
5517
5708
  }
5518
5709
  try {
5519
- await import_node_fs14.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
5520
- 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");
5521
5712
  const diff = buildDiffPreview(input.content, input.file_path);
5522
5713
  return {
5523
5714
  summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
@@ -5534,6 +5725,7 @@ var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
5534
5725
  var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {}) => [
5535
5726
  createBashTool(sandboxKey),
5536
5727
  createReadTool(sandboxKey),
5728
+ createReadLineTool(sandboxKey),
5537
5729
  createWriteTool(sandboxKey),
5538
5730
  createEditTool(sandboxKey),
5539
5731
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
@@ -5544,6 +5736,7 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
5544
5736
  createGrepTool(sandboxKey),
5545
5737
  ...options.toolOutputCacheStore ? [
5546
5738
  createToolOutputCacheTool(options.toolOutputCacheStore),
5739
+ createToolOutputCacheLineTool(options.toolOutputCacheStore),
5547
5740
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
5548
5741
  ] : [],
5549
5742
  createTodoReadTool(sandboxKey, options.todoSessionContextKey),
@@ -6084,14 +6277,14 @@ var createAgentFactory = (state, options = {}) => {
6084
6277
  const requestedReasoning = resolveReasoningEffort(modelConfig.reasoning) ?? "medium";
6085
6278
  switch (provider) {
6086
6279
  case "openai": {
6087
- const modelName = modelConfig.name ?? import_core18.OPENAI_DEFAULT_MODEL;
6280
+ const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
6088
6281
  const reasoning = resolveResponsesReasoning({
6089
6282
  model: modelName,
6090
6283
  requested: requestedReasoning
6091
6284
  });
6092
6285
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
6093
6286
  const websocketMode = modelConfig.experimental?.openai?.websocket_mode;
6094
- llm = new import_core18.ChatOpenAI({
6287
+ llm = new import_core19.ChatOpenAI({
6095
6288
  clientOptions: buildOpenAiClientOptions(authResolver, providerAuth),
6096
6289
  model: modelName,
6097
6290
  reasoningEffort: reasoning.effort,
@@ -6104,13 +6297,13 @@ var createAgentFactory = (state, options = {}) => {
6104
6297
  break;
6105
6298
  }
6106
6299
  case "openrouter": {
6107
- const modelName = modelConfig.name ?? import_core18.OPENAI_DEFAULT_MODEL;
6300
+ const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
6108
6301
  const reasoning = resolveResponsesReasoning({
6109
6302
  model: modelName,
6110
6303
  requested: requestedReasoning
6111
6304
  });
6112
6305
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
6113
- llm = new import_core18.ChatOpenRouter({
6306
+ llm = new import_core19.ChatOpenRouter({
6114
6307
  clientOptions: buildOpenRouterClientOptions(providerAuth),
6115
6308
  model: modelName,
6116
6309
  reasoningEffort: reasoning.effort,
@@ -6122,7 +6315,7 @@ var createAgentFactory = (state, options = {}) => {
6122
6315
  break;
6123
6316
  }
6124
6317
  case "anthropic": {
6125
- const modelName = modelConfig.name ?? import_core18.ANTHROPIC_DEFAULT_MODEL;
6318
+ const modelName = modelConfig.name ?? import_core19.ANTHROPIC_DEFAULT_MODEL;
6126
6319
  const reasoning = resolveAnthropicReasoning({
6127
6320
  model: modelName,
6128
6321
  requested: requestedReasoning,
@@ -6142,7 +6335,7 @@ var createAgentFactory = (state, options = {}) => {
6142
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`
6143
6336
  );
6144
6337
  }
6145
- llm = new import_core18.ChatAnthropic({
6338
+ llm = new import_core19.ChatAnthropic({
6146
6339
  clientOptions: {
6147
6340
  apiKey: requireApiKeyAuth("Anthropic", providerAuth)
6148
6341
  },
@@ -6167,12 +6360,12 @@ var createAgentFactory = (state, options = {}) => {
6167
6360
  const totalBudgetTrimEnabled = envTruthy(
6168
6361
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
6169
6362
  );
6170
- const agent = new import_core18.Agent({
6363
+ const agent = new import_core19.Agent({
6171
6364
  llm,
6172
6365
  tools,
6173
6366
  hostedTools: hostedSearchDefinitions,
6174
6367
  systemPrompt,
6175
- modelRegistry: modelRegistry ?? import_core18.DEFAULT_MODEL_REGISTRY,
6368
+ modelRegistry: modelRegistry ?? import_core19.DEFAULT_MODEL_REGISTRY,
6176
6369
  toolOutputCache: {
6177
6370
  totalBudgetTrim: totalBudgetTrimEnabled
6178
6371
  },
@@ -6228,9 +6421,9 @@ var createAgentFactory = (state, options = {}) => {
6228
6421
  const resolved = sandbox.resolvePath(filePath);
6229
6422
  let before = "";
6230
6423
  try {
6231
- const stat = await import_node_fs15.promises.stat(resolved);
6424
+ const stat = await import_node_fs16.promises.stat(resolved);
6232
6425
  if (!stat.isDirectory()) {
6233
- before = await import_node_fs15.promises.readFile(resolved, "utf8");
6426
+ before = await import_node_fs16.promises.readFile(resolved, "utf8");
6234
6427
  }
6235
6428
  } catch {
6236
6429
  before = "";
@@ -7643,7 +7836,7 @@ var createContextHandlers = ({
7643
7836
  };
7644
7837
 
7645
7838
  // src/rpc/history.ts
7646
- var import_node_fs16 = require("fs");
7839
+ var import_node_fs17 = require("fs");
7647
7840
  var import_node_path14 = __toESM(require("path"), 1);
7648
7841
  var import_node_readline2 = require("readline");
7649
7842
  var import_protocol3 = require("@codelia/protocol");
@@ -7686,7 +7879,7 @@ var parseRunHeader = (headerLine) => {
7686
7879
  }
7687
7880
  };
7688
7881
  var readFirstLine = async (filePath) => {
7689
- const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
7882
+ const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
7690
7883
  const reader = (0, import_node_readline2.createInterface)({
7691
7884
  input: stream,
7692
7885
  crlfDelay: Number.POSITIVE_INFINITY
@@ -7706,7 +7899,7 @@ var collectRunCandidates = async (log2) => {
7706
7899
  const sessionsDir = paths.sessionsDir;
7707
7900
  let yearEntries;
7708
7901
  try {
7709
- yearEntries = await import_node_fs16.promises.readdir(sessionsDir, {
7902
+ yearEntries = await import_node_fs17.promises.readdir(sessionsDir, {
7710
7903
  withFileTypes: true,
7711
7904
  encoding: "utf8"
7712
7905
  });
@@ -7721,7 +7914,7 @@ var collectRunCandidates = async (log2) => {
7721
7914
  const yearPath = import_node_path14.default.join(sessionsDir, yearEntry.name);
7722
7915
  let monthEntries;
7723
7916
  try {
7724
- monthEntries = await import_node_fs16.promises.readdir(yearPath, {
7917
+ monthEntries = await import_node_fs17.promises.readdir(yearPath, {
7725
7918
  withFileTypes: true,
7726
7919
  encoding: "utf8"
7727
7920
  });
@@ -7734,7 +7927,7 @@ var collectRunCandidates = async (log2) => {
7734
7927
  const monthPath = import_node_path14.default.join(yearPath, monthEntry.name);
7735
7928
  let dayEntries;
7736
7929
  try {
7737
- dayEntries = await import_node_fs16.promises.readdir(monthPath, {
7930
+ dayEntries = await import_node_fs17.promises.readdir(monthPath, {
7738
7931
  withFileTypes: true,
7739
7932
  encoding: "utf8"
7740
7933
  });
@@ -7747,7 +7940,7 @@ var collectRunCandidates = async (log2) => {
7747
7940
  const dayPath = import_node_path14.default.join(monthPath, dayEntry.name);
7748
7941
  let files;
7749
7942
  try {
7750
- files = await import_node_fs16.promises.readdir(dayPath, {
7943
+ files = await import_node_fs17.promises.readdir(dayPath, {
7751
7944
  withFileTypes: true,
7752
7945
  encoding: "utf8"
7753
7946
  });
@@ -7759,7 +7952,7 @@ var collectRunCandidates = async (log2) => {
7759
7952
  if (!file.name.endsWith(".jsonl")) continue;
7760
7953
  const filePath = import_node_path14.default.join(dayPath, file.name);
7761
7954
  try {
7762
- const stat = await import_node_fs16.promises.stat(filePath);
7955
+ const stat = await import_node_fs17.promises.stat(filePath);
7763
7956
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
7764
7957
  } catch {
7765
7958
  }
@@ -7797,7 +7990,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
7797
7990
  return runs;
7798
7991
  };
7799
7992
  var readJsonl = async function* (filePath) {
7800
- const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
7993
+ const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
7801
7994
  let buffer = "";
7802
7995
  for await (const chunk of stream) {
7803
7996
  buffer += chunk;
@@ -7871,14 +8064,9 @@ var createHistoryHandlers = ({
7871
8064
  return;
7872
8065
  }
7873
8066
  const runs = await collectSessionRuns(sessionId, maxRuns, log2);
7874
- let eventsSent = 0;
7875
- let truncated = false;
8067
+ const replayEvents = [];
7876
8068
  for (const run of runs) {
7877
8069
  for await (const line of readJsonl(run.path)) {
7878
- if (eventsSent >= maxEvents) {
7879
- truncated = true;
7880
- break;
7881
- }
7882
8070
  let record = null;
7883
8071
  try {
7884
8072
  record = JSON.parse(line);
@@ -7889,24 +8077,34 @@ var createHistoryHandlers = ({
7889
8077
  if (record.type === "run.start") {
7890
8078
  const input = runStartInputToHiddenMessage(record.input);
7891
8079
  if (input) {
7892
- sendHistoryEvent(record.run_id, -1, {
7893
- type: "hidden_user_message",
7894
- content: input
8080
+ replayEvents.push({
8081
+ runId: record.run_id,
8082
+ seq: -1,
8083
+ event: {
8084
+ type: "hidden_user_message",
8085
+ content: input
8086
+ }
7895
8087
  });
7896
- eventsSent += 1;
7897
8088
  }
7898
8089
  continue;
7899
8090
  }
7900
8091
  if (record.type === "agent.event") {
7901
- sendHistoryEvent(record.run_id, record.seq, record.event);
7902
- eventsSent += 1;
8092
+ replayEvents.push({
8093
+ runId: record.run_id,
8094
+ seq: record.seq,
8095
+ event: record.event
8096
+ });
7903
8097
  }
7904
8098
  }
7905
- if (truncated) break;
8099
+ }
8100
+ const truncated = replayEvents.length > maxEvents;
8101
+ const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
8102
+ for (const event of selectedEvents) {
8103
+ sendHistoryEvent(event.runId, event.seq, event.event);
7906
8104
  }
7907
8105
  const result = {
7908
8106
  runs: runs.length,
7909
- events_sent: eventsSent,
8107
+ events_sent: selectedEvents.length,
7910
8108
  ...truncated ? { truncated: true } : {}
7911
8109
  };
7912
8110
  sendResult(id, result);
@@ -7915,7 +8113,7 @@ var createHistoryHandlers = ({
7915
8113
  };
7916
8114
 
7917
8115
  // src/rpc/model.ts
7918
- var import_core19 = require("@codelia/core");
8116
+ var import_core20 = require("@codelia/core");
7919
8117
  var import_model_metadata3 = require("@codelia/model-metadata");
7920
8118
  var import_protocol4 = require("@codelia/protocol");
7921
8119
  var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter";
@@ -7936,27 +8134,27 @@ var normalizeUsdPer1M = (value) => {
7936
8134
  }
7937
8135
  return value;
7938
8136
  };
7939
- var buildModelListDetail = (entry) => {
7940
- if (!entry) return null;
8137
+ var buildModelListDetail = (entry, registry, provider, model) => {
8138
+ const spec = (0, import_core20.resolveModel)(registry, model, provider);
8139
+ if (!entry && !spec) return null;
7941
8140
  const detail = {};
7942
- if (entry.releaseDate?.trim()) {
8141
+ if (entry?.releaseDate?.trim()) {
7943
8142
  detail.release_date = entry.releaseDate.trim();
7944
8143
  }
7945
- const limits = entry.limits;
7946
- if (typeof limits?.contextWindow === "number" && Number.isFinite(limits.contextWindow) && limits.contextWindow > 0) {
7947
- detail.context_window = limits.contextWindow;
8144
+ if (typeof spec?.contextWindow === "number" && Number.isFinite(spec.contextWindow) && spec.contextWindow > 0) {
8145
+ detail.context_window = spec.contextWindow;
7948
8146
  }
7949
- if (typeof limits?.inputTokens === "number" && Number.isFinite(limits.inputTokens) && limits.inputTokens > 0) {
7950
- detail.max_input_tokens = limits.inputTokens;
8147
+ if (typeof spec?.maxInputTokens === "number" && Number.isFinite(spec.maxInputTokens) && spec.maxInputTokens > 0) {
8148
+ detail.max_input_tokens = spec.maxInputTokens;
7951
8149
  }
7952
- if (typeof limits?.outputTokens === "number" && Number.isFinite(limits.outputTokens) && limits.outputTokens > 0) {
7953
- detail.max_output_tokens = limits.outputTokens;
8150
+ if (typeof spec?.maxOutputTokens === "number" && Number.isFinite(spec.maxOutputTokens) && spec.maxOutputTokens > 0) {
8151
+ detail.max_output_tokens = spec.maxOutputTokens;
7954
8152
  }
7955
- const inputCost = normalizeUsdPer1M(entry.cost?.input);
8153
+ const inputCost = normalizeUsdPer1M(entry?.cost?.input);
7956
8154
  if (inputCost !== void 0) {
7957
8155
  detail.cost_per_1m_input_tokens_usd = inputCost;
7958
8156
  }
7959
- const outputCost = normalizeUsdPer1M(entry.cost?.output);
8157
+ const outputCost = normalizeUsdPer1M(entry?.cost?.output);
7960
8158
  if (outputCost !== void 0) {
7961
8159
  detail.cost_per_1m_output_tokens_usd = outputCost;
7962
8160
  }
@@ -8145,31 +8343,47 @@ var buildProviderModelList = async ({
8145
8343
  provider,
8146
8344
  includeDetails,
8147
8345
  state,
8148
- log: log2
8346
+ log: log2,
8347
+ providerEntriesOverride
8149
8348
  }) => {
8150
8349
  if (provider === "openrouter") {
8151
8350
  return buildOpenRouterModelList({ includeDetails, state, log: log2 });
8152
8351
  }
8153
8352
  let providerEntries = null;
8154
- try {
8155
- providerEntries = await loadProviderModelEntries(provider);
8156
- } catch (error) {
8157
- if (includeDetails) {
8158
- log2(`model.list details error: ${error}`);
8353
+ if (providerEntriesOverride !== void 0) {
8354
+ providerEntries = providerEntriesOverride;
8355
+ } else {
8356
+ try {
8357
+ providerEntries = await loadProviderModelEntries(provider);
8358
+ } catch (error) {
8359
+ if (includeDetails) {
8360
+ log2(`model.list details error: ${error}`);
8361
+ }
8159
8362
  }
8160
8363
  }
8161
8364
  const models = sortModelsByReleaseDate(
8162
- (0, import_core19.listModels)(import_core19.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
8365
+ (0, import_core20.listModels)(import_core20.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
8163
8366
  provider,
8164
8367
  providerEntries
8165
8368
  );
8166
8369
  if (!includeDetails || !providerEntries) {
8167
8370
  return { models };
8168
8371
  }
8372
+ const mergedRegistry = (0, import_core20.applyModelMetadata)(import_core20.DEFAULT_MODEL_REGISTRY, {
8373
+ models: {
8374
+ openai: provider === "openai" ? providerEntries : {},
8375
+ anthropic: provider === "anthropic" ? providerEntries : {},
8376
+ openrouter: {},
8377
+ google: {}
8378
+ }
8379
+ });
8169
8380
  const details = {};
8170
8381
  for (const model of models) {
8171
8382
  const detail = buildModelListDetail(
8172
- resolveProviderModelEntry2(providerEntries, provider, model)
8383
+ resolveProviderModelEntry2(providerEntries, provider, model),
8384
+ mergedRegistry,
8385
+ provider,
8386
+ model
8173
8387
  );
8174
8388
  if (detail) {
8175
8389
  details[model] = detail;
@@ -8283,7 +8497,7 @@ var createModelHandlers = ({
8283
8497
  return;
8284
8498
  }
8285
8499
  if (provider !== "openrouter") {
8286
- const spec = (0, import_core19.resolveModel)(import_core19.DEFAULT_MODEL_REGISTRY, name, provider);
8500
+ const spec = (0, import_core20.resolveModel)(import_core20.DEFAULT_MODEL_REGISTRY, name, provider);
8287
8501
  if (!spec) {
8288
8502
  sendError(id, {
8289
8503
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
@@ -8327,7 +8541,7 @@ var createModelHandlers = ({
8327
8541
  var import_protocol5 = require("@codelia/protocol");
8328
8542
 
8329
8543
  // src/rpc/run-debug.ts
8330
- var import_core20 = require("@codelia/core");
8544
+ var import_core21 = require("@codelia/core");
8331
8545
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
8332
8546
  var DEBUG_MAX_LOG_CHARS = 2e4;
8333
8547
  var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
@@ -8349,7 +8563,7 @@ var stringifyUnknown = (value) => {
8349
8563
  }
8350
8564
  };
8351
8565
  var contentToDebugText = (content, maxChars) => {
8352
- const text = (0, import_core20.stringifyContent)(content, {
8566
+ const text = (0, import_core21.stringifyContent)(content, {
8353
8567
  mode: "log",
8354
8568
  joiner: "\n",
8355
8569
  includeOtherPayload: true