@codelia/runtime 0.1.36 → 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 +286 -93
  2. package/dist/index.js +273 -79
  3. package/package.json +9 -9
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,38 +4745,68 @@ 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;
4726
- 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) => {
4727
4763
  if (line.length <= MAX_LINE_LENGTH) {
4728
- return [line];
4729
- }
4730
- const chunks = [];
4731
- for (let start = 0; start < line.length; start += MAX_LINE_LENGTH) {
4732
- chunks.push(line.slice(start, start + MAX_LINE_LENGTH));
4733
- }
4734
- return chunks;
4735
- };
4736
- var toDisplayLines = (physicalLines, wrapLongLines) => {
4737
- let wrapped = false;
4738
- let clipped = false;
4739
- const display = [];
4740
- for (const line of physicalLines) {
4741
- if (wrapLongLines) {
4742
- const chunks = splitLongLine(line);
4743
- if (chunks.length > 1) wrapped = true;
4744
- display.push(...chunks);
4745
- continue;
4746
- }
4747
- if (line.length > MAX_LINE_LENGTH) {
4748
- clipped = true;
4749
- display.push(`${line.slice(0, MAX_LINE_LENGTH)}...`);
4750
- continue;
4751
- }
4752
- 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;
4753
4777
  }
4754
- return { lines: display, wrapped, clipped };
4778
+ return out;
4755
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();
4756
4810
  var createReadTool = (sandboxKey) => defineTool8({
4757
4811
  name: "read",
4758
4812
  description: "Read a text file with optional 0-based line offset and line limit.",
@@ -4760,7 +4814,7 @@ var createReadTool = (sandboxKey) => defineTool8({
4760
4814
  file_path: z9.string().describe("File path under the sandbox root."),
4761
4815
  offset: z9.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4762
4816
  limit: z9.number().int().positive().optional().describe("Max lines to read. Default 2000."),
4763
- wrap_long_lines: z9.boolean().optional().describe("Enable to paginate very long single-line output. Default false.")
4817
+ allow_truncate: z9.boolean().optional().describe("Allow truncation when output is too large. Default false.")
4764
4818
  }),
4765
4819
  execute: async (input, ctx) => {
4766
4820
  let resolved;
@@ -4780,53 +4834,97 @@ var createReadTool = (sandboxKey) => defineTool8({
4780
4834
  }
4781
4835
  try {
4782
4836
  const content = await fs13.readFile(resolved, "utf8");
4783
- const physicalLines = content.split(/\r?\n/);
4784
- if (physicalLines.length === 0) {
4837
+ const lines = content.split(/\r?\n/);
4838
+ if (lines.length === 0) {
4785
4839
  return "";
4786
4840
  }
4787
- const wrapLongLines = input.wrap_long_lines ?? false;
4788
- const display = toDisplayLines(physicalLines, wrapLongLines);
4789
4841
  const offset = input.offset ?? 0;
4790
4842
  const limit = input.limit ?? DEFAULT_READ_LIMIT;
4791
- if (offset >= display.lines.length) {
4843
+ const allowTruncate = input.allow_truncate ?? false;
4844
+ if (offset >= lines.length) {
4792
4845
  return `Offset exceeds output length: ${input.file_path}`;
4793
4846
  }
4794
- const raw = [];
4847
+ const outputLines = [];
4795
4848
  let bytes = 0;
4796
4849
  let truncatedByBytes = false;
4797
- for (let index = offset; index < Math.min(display.lines.length, offset + limit); index += 1) {
4798
- 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
+ }
4799
4868
  const numberedLine = `${String(index + 1).padStart(5, " ")} ${line}`;
4800
- const size = Buffer.byteLength(numberedLine, "utf8") + (raw.length > 0 ? 1 : 0);
4869
+ const size = Buffer.byteLength(numberedLine, "utf8") + (outputLines.length > 0 ? 1 : 0);
4801
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
+ }
4802
4901
  truncatedByBytes = true;
4803
4902
  break;
4804
4903
  }
4805
- raw.push(line);
4904
+ outputLines.push(line);
4806
4905
  bytes += size;
4807
4906
  }
4808
- const numbered = raw.map(
4907
+ const numbered = outputLines.map(
4809
4908
  (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4810
4909
  );
4811
- const lastReadLine = offset + raw.length;
4812
- const hasMoreLines = display.lines.length > lastReadLine;
4813
- const truncated = truncatedByBytes || hasMoreLines;
4910
+ const lastReadLine = offset + outputLines.length;
4911
+ const hasMoreLines = lines.length > lastReadLine;
4814
4912
  let output = numbered.join("\n");
4815
- if (truncated) {
4913
+ if (truncatedByBytes || hasMoreLines) {
4816
4914
  const reason = truncatedByBytes ? `Output truncated at ${MAX_BYTES} bytes.` : "Output has more lines.";
4817
4915
  output += `
4818
4916
 
4819
4917
  ${reason} Use offset to read beyond line ${lastReadLine}.`;
4820
4918
  }
4821
- if (display.wrapped) {
4919
+ if (clipped) {
4822
4920
  output += `
4823
4921
 
4824
- 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.`;
4825
4923
  }
4826
- if (display.clipped) {
4924
+ if (allowTruncate && firstClippedLineNumber !== null) {
4827
4925
  output += `
4828
4926
 
4829
- 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}).`;
4830
4928
  }
4831
4929
  return output;
4832
4930
  } catch (error) {
@@ -5279,14 +5377,14 @@ var todoWriteInputSchema = z14.object({
5279
5377
  ctx.addIssue({
5280
5378
  code: z14.ZodIssueCode.custom,
5281
5379
  path: ["updates"],
5282
- message: "patch mode requires at least one update item."
5380
+ message: "patch mode requires at least one item in updates."
5283
5381
  });
5284
5382
  }
5285
5383
  if (input.todos.length > 0) {
5286
5384
  ctx.addIssue({
5287
5385
  code: z14.ZodIssueCode.custom,
5288
5386
  path: ["todos"],
5289
- message: "patch mode does not accept todos."
5387
+ message: "patch mode uses updates only; leave todos empty."
5290
5388
  });
5291
5389
  }
5292
5390
  return;
@@ -5296,14 +5394,14 @@ var todoWriteInputSchema = z14.object({
5296
5394
  ctx.addIssue({
5297
5395
  code: z14.ZodIssueCode.custom,
5298
5396
  path: ["todos"],
5299
- message: "clear mode does not accept todos."
5397
+ message: "clear mode does not accept todos; omit todos and updates."
5300
5398
  });
5301
5399
  }
5302
5400
  if (input.updates.length > 0) {
5303
5401
  ctx.addIssue({
5304
5402
  code: z14.ZodIssueCode.custom,
5305
5403
  path: ["updates"],
5306
- message: "clear mode does not accept updates."
5404
+ message: "clear mode does not accept updates; omit todos and updates."
5307
5405
  });
5308
5406
  }
5309
5407
  return;
@@ -5312,14 +5410,14 @@ var todoWriteInputSchema = z14.object({
5312
5410
  ctx.addIssue({
5313
5411
  code: z14.ZodIssueCode.custom,
5314
5412
  path: ["todos"],
5315
- message: `${input.mode} mode requires at least one todo item.`
5413
+ message: `${input.mode} mode requires at least one item in todos.`
5316
5414
  });
5317
5415
  }
5318
5416
  if (input.updates.length > 0) {
5319
5417
  ctx.addIssue({
5320
5418
  code: z14.ZodIssueCode.custom,
5321
5419
  path: ["updates"],
5322
- message: `${input.mode} mode does not accept updates.`
5420
+ message: `${input.mode} mode uses todos only; leave updates empty.`
5323
5421
  });
5324
5422
  }
5325
5423
  });
@@ -5362,9 +5460,10 @@ var withPatchApplied = (currentTodos, updates) => {
5362
5460
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
5363
5461
  const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5364
5462
  if (missingIds.length > 0) {
5463
+ const knownIds = currentTodos.map((todo) => todo.id);
5365
5464
  return {
5366
5465
  todos: [...currentTodos],
5367
- 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.`
5368
5467
  };
5369
5468
  }
5370
5469
  let nextInputs = currentTodos.map((todo) => ({ ...todo }));
@@ -5418,7 +5517,8 @@ var createTodoWriteTool = (sandboxKey, sessionContextKey) => defineTool13({
5418
5517
  }
5419
5518
  const inProgressCount = countInProgressTodos(nextTodos);
5420
5519
  if (inProgressCount > 1) {
5421
- 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.`;
5422
5522
  }
5423
5523
  if (nextTodos.length === 0) {
5424
5524
  clearTodosForSession(todoSessionId);
@@ -5439,7 +5539,7 @@ var createToolOutputCacheTool = (store) => defineTool14({
5439
5539
  ref_id: z15.string().describe("Tool output reference ID."),
5440
5540
  offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
5441
5541
  limit: z15.number().int().positive().optional().describe("Optional max number of lines to return."),
5442
- wrap_long_lines: z15.boolean().optional().describe("Enable to paginate very long single-line output. Default false.")
5542
+ allow_truncate: z15.boolean().optional().describe("Allow truncation when output is too large. Default false.")
5443
5543
  }),
5444
5544
  execute: async (input) => {
5445
5545
  if (!store.read) {
@@ -5449,13 +5549,37 @@ var createToolOutputCacheTool = (store) => defineTool14({
5449
5549
  return await store.read(input.ref_id, {
5450
5550
  offset: input.offset,
5451
5551
  limit: input.limit,
5452
- wrap_long_lines: input.wrap_long_lines
5552
+ allow_truncate: input.allow_truncate
5453
5553
  });
5454
5554
  } catch (error) {
5455
5555
  return `Error reading tool output cache: ${String(error)}`;
5456
5556
  }
5457
5557
  }
5458
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
+ });
5459
5583
  var createToolOutputCacheGrepTool = (store) => defineTool14({
5460
5584
  name: "tool_output_cache_grep",
5461
5585
  description: "Search cached tool output by ref_id.",
@@ -5485,11 +5609,79 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
5485
5609
  }
5486
5610
  });
5487
5611
 
5488
- // src/tools/write.ts
5612
+ // src/tools/read-line.ts
5489
5613
  import { promises as fs14 } from "fs";
5490
- import path13 from "path";
5491
5614
  import { defineTool as defineTool15 } from "@codelia/core";
5492
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";
5493
5685
  var buildDiffPreview = (content, filePath) => {
5494
5686
  const diff = createUnifiedDiff(filePath, "", content);
5495
5687
  if (!diff) {
@@ -5499,12 +5691,12 @@ var buildDiffPreview = (content, filePath) => {
5499
5691
  }
5500
5692
  return diff;
5501
5693
  };
5502
- var createWriteTool = (sandboxKey) => defineTool15({
5694
+ var createWriteTool = (sandboxKey) => defineTool16({
5503
5695
  name: "write",
5504
5696
  description: "Write text to a file, creating parent directories if needed.",
5505
- input: z16.object({
5506
- file_path: z16.string().describe("File path under the sandbox root."),
5507
- 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.")
5508
5700
  }),
5509
5701
  execute: async (input, ctx) => {
5510
5702
  let resolved;
@@ -5515,8 +5707,8 @@ var createWriteTool = (sandboxKey) => defineTool15({
5515
5707
  return `Security error: ${String(error)}`;
5516
5708
  }
5517
5709
  try {
5518
- await fs14.mkdir(path13.dirname(resolved), { recursive: true });
5519
- await fs14.writeFile(resolved, input.content, "utf8");
5710
+ await fs15.mkdir(path13.dirname(resolved), { recursive: true });
5711
+ await fs15.writeFile(resolved, input.content, "utf8");
5520
5712
  const diff = buildDiffPreview(input.content, input.file_path);
5521
5713
  return {
5522
5714
  summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
@@ -5533,6 +5725,7 @@ var createWriteTool = (sandboxKey) => defineTool15({
5533
5725
  var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {}) => [
5534
5726
  createBashTool(sandboxKey),
5535
5727
  createReadTool(sandboxKey),
5728
+ createReadLineTool(sandboxKey),
5536
5729
  createWriteTool(sandboxKey),
5537
5730
  createEditTool(sandboxKey),
5538
5731
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
@@ -5543,6 +5736,7 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
5543
5736
  createGrepTool(sandboxKey),
5544
5737
  ...options.toolOutputCacheStore ? [
5545
5738
  createToolOutputCacheTool(options.toolOutputCacheStore),
5739
+ createToolOutputCacheLineTool(options.toolOutputCacheStore),
5546
5740
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
5547
5741
  ] : [],
5548
5742
  createTodoReadTool(sandboxKey, options.todoSessionContextKey),
@@ -6227,9 +6421,9 @@ var createAgentFactory = (state, options = {}) => {
6227
6421
  const resolved = sandbox.resolvePath(filePath);
6228
6422
  let before = "";
6229
6423
  try {
6230
- const stat = await fs15.stat(resolved);
6424
+ const stat = await fs16.stat(resolved);
6231
6425
  if (!stat.isDirectory()) {
6232
- before = await fs15.readFile(resolved, "utf8");
6426
+ before = await fs16.readFile(resolved, "utf8");
6233
6427
  }
6234
6428
  } catch {
6235
6429
  before = "";
@@ -7658,7 +7852,7 @@ var createContextHandlers = ({
7658
7852
  };
7659
7853
 
7660
7854
  // src/rpc/history.ts
7661
- import { createReadStream, promises as fs16 } from "fs";
7855
+ import { createReadStream, promises as fs17 } from "fs";
7662
7856
  import path14 from "path";
7663
7857
  import { createInterface as createInterface2 } from "readline";
7664
7858
  import {
@@ -7723,7 +7917,7 @@ var collectRunCandidates = async (log2) => {
7723
7917
  const sessionsDir = paths.sessionsDir;
7724
7918
  let yearEntries;
7725
7919
  try {
7726
- yearEntries = await fs16.readdir(sessionsDir, {
7920
+ yearEntries = await fs17.readdir(sessionsDir, {
7727
7921
  withFileTypes: true,
7728
7922
  encoding: "utf8"
7729
7923
  });
@@ -7738,7 +7932,7 @@ var collectRunCandidates = async (log2) => {
7738
7932
  const yearPath = path14.join(sessionsDir, yearEntry.name);
7739
7933
  let monthEntries;
7740
7934
  try {
7741
- monthEntries = await fs16.readdir(yearPath, {
7935
+ monthEntries = await fs17.readdir(yearPath, {
7742
7936
  withFileTypes: true,
7743
7937
  encoding: "utf8"
7744
7938
  });
@@ -7751,7 +7945,7 @@ var collectRunCandidates = async (log2) => {
7751
7945
  const monthPath = path14.join(yearPath, monthEntry.name);
7752
7946
  let dayEntries;
7753
7947
  try {
7754
- dayEntries = await fs16.readdir(monthPath, {
7948
+ dayEntries = await fs17.readdir(monthPath, {
7755
7949
  withFileTypes: true,
7756
7950
  encoding: "utf8"
7757
7951
  });
@@ -7764,7 +7958,7 @@ var collectRunCandidates = async (log2) => {
7764
7958
  const dayPath = path14.join(monthPath, dayEntry.name);
7765
7959
  let files;
7766
7960
  try {
7767
- files = await fs16.readdir(dayPath, {
7961
+ files = await fs17.readdir(dayPath, {
7768
7962
  withFileTypes: true,
7769
7963
  encoding: "utf8"
7770
7964
  });
@@ -7776,7 +7970,7 @@ var collectRunCandidates = async (log2) => {
7776
7970
  if (!file.name.endsWith(".jsonl")) continue;
7777
7971
  const filePath = path14.join(dayPath, file.name);
7778
7972
  try {
7779
- const stat = await fs16.stat(filePath);
7973
+ const stat = await fs17.stat(filePath);
7780
7974
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
7781
7975
  } catch {
7782
7976
  }
@@ -7935,7 +8129,7 @@ var createHistoryHandlers = ({
7935
8129
  import {
7936
8130
  DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY3,
7937
8131
  listModels,
7938
- resolveModel
8132
+ resolveModel as resolveModel2
7939
8133
  } from "@codelia/core";
7940
8134
  import { ModelMetadataServiceImpl as ModelMetadataServiceImpl3 } from "@codelia/model-metadata";
7941
8135
  import {
@@ -8306,7 +8500,7 @@ var createModelHandlers = ({
8306
8500
  return;
8307
8501
  }
8308
8502
  if (provider !== "openrouter") {
8309
- const spec = resolveModel(DEFAULT_MODEL_REGISTRY3, name, provider);
8503
+ const spec = resolveModel2(DEFAULT_MODEL_REGISTRY3, name, provider);
8310
8504
  if (!spec) {
8311
8505
  sendError(id, {
8312
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.36",
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.36",
27
- "@codelia/config-loader": "0.1.36",
28
- "@codelia/core": "0.1.36",
29
- "@codelia/logger": "0.1.36",
30
- "@codelia/model-metadata": "0.1.36",
31
- "@codelia/protocol": "0.1.36",
32
- "@codelia/shared-types": "0.1.36",
33
- "@codelia/storage": "0.1.36",
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"