sentinelayer-cli 0.4.5 → 0.8.0

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 (72) hide show
  1. package/README.md +16 -18
  2. package/package.json +7 -6
  3. package/src/agents/jules/config/definition.js +13 -62
  4. package/src/agents/jules/config/system-prompt.js +8 -1
  5. package/src/agents/jules/fix-cycle.js +12 -372
  6. package/src/agents/jules/loop.js +116 -26
  7. package/src/agents/jules/pulse.js +10 -327
  8. package/src/agents/jules/stream.js +13 -12
  9. package/src/agents/jules/swarm/orchestrator.js +3 -3
  10. package/src/agents/jules/swarm/sub-agent.js +6 -3
  11. package/src/agents/jules/tools/aidenid-email.js +189 -0
  12. package/src/agents/jules/tools/auth-audit.js +1187 -45
  13. package/src/agents/jules/tools/dispatch.js +25 -12
  14. package/src/agents/jules/tools/file-edit.js +2 -180
  15. package/src/agents/jules/tools/file-read.js +2 -100
  16. package/src/agents/jules/tools/glob.js +2 -168
  17. package/src/agents/jules/tools/grep.js +2 -228
  18. package/src/agents/jules/tools/path-guards.js +2 -161
  19. package/src/agents/jules/tools/runtime-audit.js +6 -2
  20. package/src/agents/jules/tools/shell.js +2 -383
  21. package/src/agents/persona-visuals.js +64 -0
  22. package/src/agents/shared-tools/dispatch-core.js +320 -0
  23. package/src/agents/shared-tools/file-edit.js +180 -0
  24. package/src/agents/shared-tools/file-read.js +100 -0
  25. package/src/agents/shared-tools/glob.js +168 -0
  26. package/src/agents/shared-tools/grep.js +228 -0
  27. package/src/agents/shared-tools/index.js +46 -0
  28. package/src/agents/shared-tools/path-guards.js +161 -0
  29. package/src/agents/shared-tools/shell.js +383 -0
  30. package/src/ai/aidenid.js +56 -7
  31. package/src/ai/client.js +45 -0
  32. package/src/ai/proxy.js +137 -0
  33. package/src/auth/gate.js +290 -16
  34. package/src/auth/http.js +450 -39
  35. package/src/auth/service.js +262 -47
  36. package/src/auth/session-store.js +475 -21
  37. package/src/cli.js +5 -0
  38. package/src/commands/audit.js +13 -8
  39. package/src/commands/auth.js +53 -9
  40. package/src/commands/omargate.js +10 -2
  41. package/src/commands/scan.js +10 -4
  42. package/src/commands/session.js +590 -0
  43. package/src/commands/spec.js +62 -0
  44. package/src/commands/watch.js +3 -2
  45. package/src/daemon/assignment-ledger.js +196 -0
  46. package/src/daemon/error-worker.js +599 -16
  47. package/src/daemon/fix-cycle.js +384 -0
  48. package/src/daemon/ingest-refresh.js +10 -9
  49. package/src/daemon/jira-lifecycle.js +135 -0
  50. package/src/daemon/pulse.js +327 -0
  51. package/src/daemon/scope-engine.js +1068 -0
  52. package/src/events/schema.js +190 -0
  53. package/src/interactive/index.js +18 -16
  54. package/src/legacy-cli.js +606 -37
  55. package/src/prompt/generator.js +19 -1
  56. package/src/review/ai-review.js +11 -1
  57. package/src/review/local-review.js +75 -19
  58. package/src/review/omargate-interactive.js +68 -0
  59. package/src/review/omargate-orchestrator.js +404 -0
  60. package/src/review/persona-prompts.js +296 -0
  61. package/src/review/scan-modes.js +48 -0
  62. package/src/scan/generator.js +1 -1
  63. package/src/session/agent-registry.js +352 -0
  64. package/src/session/daemon.js +801 -0
  65. package/src/session/paths.js +33 -0
  66. package/src/session/runtime-bridge.js +739 -0
  67. package/src/session/store.js +388 -0
  68. package/src/session/stream.js +325 -0
  69. package/src/spec/generator.js +100 -0
  70. package/src/telemetry/session-tracker.js +148 -32
  71. package/src/telemetry/sync.js +6 -2
  72. package/src/ui/command-hints.js +13 -0
@@ -0,0 +1,320 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { evaluateBudget } from "../../cost/budget.js";
3
+ import {
4
+ normalizeRunEvent,
5
+ appendRunEvent,
6
+ } from "../../telemetry/ledger.js";
7
+ import { createAgentEvent } from "../../events/schema.js";
8
+
9
+ /**
10
+ * Shared tool dispatch infrastructure.
11
+ *
12
+ * Each persona builds its own TOOL_MAP (shared tools + domain tools)
13
+ * and creates a dispatcher via createToolDispatcher(). This avoids
14
+ * duplicating budget enforcement, telemetry, and result persistence.
15
+ */
16
+
17
+ const RESULT_PERSIST_THRESHOLD = 5000;
18
+
19
+ /**
20
+ * Create a tool dispatcher bound to a specific TOOL_MAP.
21
+ *
22
+ * @param {Record<string, Function>} toolMap - { ToolName: handler }
23
+ * @param {Set<string>} [readOnlyTools] - tool names safe for concurrent use
24
+ * @returns {{ dispatchTool, registerTool, isReadOnlyTool, listTools }}
25
+ */
26
+ export function createToolDispatcher(toolMap, readOnlyTools) {
27
+ const TOOL_MAP = { ...toolMap };
28
+ const READ_ONLY_TOOLS = new Set(readOnlyTools || []);
29
+
30
+ async function dispatchTool(toolName, input, ctx) {
31
+ const handler = TOOL_MAP[toolName];
32
+ if (!handler) {
33
+ throw new ToolDispatchError(`Unknown tool: ${toolName}`);
34
+ }
35
+
36
+ // 1. Pre-flight budget check
37
+ const budgetCheck = evaluateBudget({
38
+ maxCostUsd: ctx.budget.maxCostUsd,
39
+ maxOutputTokens: ctx.budget.maxOutputTokens,
40
+ maxRuntimeMs: ctx.budget.maxRuntimeMs,
41
+ maxToolCalls: ctx.budget.maxToolCalls,
42
+ warningThresholdPercent: ctx.budget.warningThresholdPercent ?? 70,
43
+ maxNoProgress: 0,
44
+ sessionSummary: {
45
+ costUsd: ctx.usage.costUsd,
46
+ outputTokens: ctx.usage.outputTokens,
47
+ durationMs: Date.now() - ctx.startedAt,
48
+ toolCalls: ctx.usage.toolCalls + 1,
49
+ noProgressStreak: 0,
50
+ },
51
+ });
52
+
53
+ if (budgetCheck.blocking) {
54
+ const stopEvent = {
55
+ eventType: "run_stop",
56
+ sessionId: ctx.sessionId,
57
+ runId: ctx.runId,
58
+ stop: {
59
+ stopClass: budgetCheck.reasons[0]?.code || "MAX_TOOL_CALLS_EXCEEDED",
60
+ blocking: true,
61
+ reasonCodes: budgetCheck.reasons.map((r) => r.code),
62
+ },
63
+ usage: snapshotUsage(ctx),
64
+ metadata: { tool: toolName, phase: "pre_flight" },
65
+ };
66
+ await safeAppendEvent(ctx, stopEvent);
67
+
68
+ if (ctx.onEvent) {
69
+ ctx.onEvent(createAgentEvent({
70
+ event: "budget_stop",
71
+ agent: ctx.agentIdentity,
72
+ payload: {
73
+ stopClass: stopEvent.stop.stopClass,
74
+ reasons: budgetCheck.reasons,
75
+ },
76
+ usage: snapshotUsage(ctx),
77
+ sessionId: ctx.sessionId,
78
+ runId: ctx.runId,
79
+ }));
80
+ }
81
+
82
+ throw new BudgetExhaustedError(budgetCheck);
83
+ }
84
+
85
+ // Emit budget warnings
86
+ if (budgetCheck.warnings.length > 0 && ctx.onEvent) {
87
+ ctx.onEvent(createAgentEvent({
88
+ event: "budget_warning",
89
+ agent: ctx.agentIdentity,
90
+ payload: { warnings: budgetCheck.warnings },
91
+ usage: snapshotUsage(ctx),
92
+ sessionId: ctx.sessionId,
93
+ runId: ctx.runId,
94
+ }));
95
+ }
96
+
97
+ // 2. Emit tool_call event
98
+ const eventId = randomUUID();
99
+ const callEvent = {
100
+ eventType: "tool_call",
101
+ sessionId: ctx.sessionId,
102
+ runId: ctx.runId,
103
+ metadata: {
104
+ eventId,
105
+ tool: toolName,
106
+ input: sanitizeInput(toolName, input),
107
+ agentId: ctx.agentIdentity?.id,
108
+ persona: ctx.agentIdentity?.persona,
109
+ },
110
+ };
111
+ await safeAppendEvent(ctx, callEvent);
112
+
113
+ if (ctx.onEvent) {
114
+ ctx.onEvent(createAgentEvent({
115
+ event: "tool_call",
116
+ agent: ctx.agentIdentity,
117
+ payload: { tool: toolName, input: sanitizeInput(toolName, input) },
118
+ usage: snapshotUsage(ctx),
119
+ sessionId: ctx.sessionId,
120
+ runId: ctx.runId,
121
+ }));
122
+ }
123
+
124
+ // 3. Execute
125
+ const startMs = Date.now();
126
+ let result;
127
+ let error;
128
+ try {
129
+ result = handler(input);
130
+ } catch (err) {
131
+ error = err;
132
+ }
133
+ const durationMs = Date.now() - startMs;
134
+
135
+ // 4. Update accumulated usage
136
+ ctx.usage.toolCalls++;
137
+ ctx.usage.runtimeMs = Date.now() - ctx.startedAt;
138
+ ctx.lastToolCallAt = Date.now();
139
+ ctx.lastToolName = toolName;
140
+
141
+ // Track confirmed file reads for coverage accounting
142
+ if (!error && toolName === "FileRead") {
143
+ const readPath = input?.file_path || input?.filePath || input?.path || "";
144
+ if (readPath && ctx.usage.filesRead) ctx.usage.filesRead.add(readPath);
145
+ }
146
+
147
+ // 5. Emit tool_result event
148
+ const resultEvent = {
149
+ eventType: "tool_call",
150
+ sessionId: ctx.sessionId,
151
+ runId: ctx.runId,
152
+ usage: {
153
+ durationMs,
154
+ toolCalls: 1,
155
+ },
156
+ metadata: {
157
+ eventId,
158
+ phase: "result",
159
+ tool: toolName,
160
+ success: !error,
161
+ error: error?.message,
162
+ agentId: ctx.agentIdentity?.id,
163
+ },
164
+ };
165
+ await safeAppendEvent(ctx, resultEvent);
166
+
167
+ if (ctx.onEvent) {
168
+ ctx.onEvent(createAgentEvent({
169
+ event: "tool_result",
170
+ agent: ctx.agentIdentity,
171
+ payload: {
172
+ tool: toolName,
173
+ durationMs,
174
+ success: !error,
175
+ error: error?.message,
176
+ },
177
+ usage: snapshotUsage(ctx),
178
+ sessionId: ctx.sessionId,
179
+ runId: ctx.runId,
180
+ }));
181
+ }
182
+
183
+ if (error) throw error;
184
+
185
+ // 6. Large result persistence
186
+ const serialized = JSON.stringify(result);
187
+ if (serialized.length > RESULT_PERSIST_THRESHOLD && ctx.artifactDir) {
188
+ const refPath = `${ctx.artifactDir}/tool-results/${eventId}.json`;
189
+ const fsp = await import("node:fs/promises");
190
+ await fsp.mkdir(`${ctx.artifactDir}/tool-results`, { recursive: true });
191
+ await fsp.writeFile(refPath, serialized, "utf-8");
192
+ return {
193
+ _persisted: true,
194
+ _refPath: refPath,
195
+ _summary: summarizeResult(toolName, result),
196
+ };
197
+ }
198
+
199
+ return result;
200
+ }
201
+
202
+ function registerTool(name, handler, { readOnly = false } = {}) {
203
+ TOOL_MAP[name] = handler;
204
+ if (readOnly) READ_ONLY_TOOLS.add(name);
205
+ }
206
+
207
+ function isReadOnlyTool(toolName) {
208
+ return READ_ONLY_TOOLS.has(toolName);
209
+ }
210
+
211
+ function listTools() {
212
+ return Object.keys(TOOL_MAP);
213
+ }
214
+
215
+ return { dispatchTool, registerTool, isReadOnlyTool, listTools };
216
+ }
217
+
218
+ /**
219
+ * Create an agent context for tool dispatch.
220
+ */
221
+ export function createAgentContext({
222
+ agentIdentity,
223
+ budget,
224
+ sessionId,
225
+ runId,
226
+ artifactDir,
227
+ onEvent,
228
+ }) {
229
+ return {
230
+ agentIdentity,
231
+ budget: {
232
+ maxCostUsd: budget?.maxCostUsd ?? 5.0,
233
+ maxOutputTokens: budget?.maxOutputTokens ?? 12000,
234
+ maxRuntimeMs: budget?.maxRuntimeMs ?? 300000,
235
+ maxToolCalls: budget?.maxToolCalls ?? 150,
236
+ warningThresholdPercent: budget?.warningThresholdPercent ?? 70,
237
+ },
238
+ usage: {
239
+ costUsd: 0,
240
+ outputTokens: 0,
241
+ toolCalls: 0,
242
+ runtimeMs: 0,
243
+ filesRead: new Set(),
244
+ },
245
+ sessionId: sessionId || randomUUID(),
246
+ runId: runId || `agent-${Date.now()}-${randomUUID().slice(0, 8)}`,
247
+ artifactDir,
248
+ startedAt: Date.now(),
249
+ lastToolCallAt: Date.now(),
250
+ lastToolName: null,
251
+ onEvent,
252
+ };
253
+ }
254
+
255
+ function snapshotUsage(ctx) {
256
+ return {
257
+ costUsd: ctx.usage.costUsd,
258
+ outputTokens: ctx.usage.outputTokens,
259
+ toolCalls: ctx.usage.toolCalls,
260
+ durationMs: Date.now() - ctx.startedAt,
261
+ filesRead: [...(ctx.usage.filesRead || [])],
262
+ };
263
+ }
264
+
265
+ function sanitizeInput(toolName, input) {
266
+ const sanitized = { ...input };
267
+ if (sanitized.content && sanitized.content.length > 200) {
268
+ sanitized.content = `[${sanitized.content.length} chars]`;
269
+ }
270
+ return sanitized;
271
+ }
272
+
273
+ function summarizeResult(toolName, result) {
274
+ if (toolName === "FileRead") {
275
+ return `Read ${result.numLines} lines from ${result.filePath}`;
276
+ }
277
+ if (toolName === "Grep") {
278
+ return `${result.numMatches} matches in ${result.numFiles} files`;
279
+ }
280
+ if (toolName === "Glob") {
281
+ return `${result.numFiles} files matched`;
282
+ }
283
+ if (toolName === "Shell") {
284
+ return `Exit ${result.exitCode} in ${result.durationMs}ms`;
285
+ }
286
+ return `${toolName} completed`;
287
+ }
288
+
289
+ async function safeAppendEvent(ctx, eventData) {
290
+ try {
291
+ const normalized = normalizeRunEvent({
292
+ ...eventData,
293
+ sessionId: ctx.sessionId,
294
+ runId: ctx.runId,
295
+ });
296
+ if (ctx.artifactDir) {
297
+ await appendRunEvent(
298
+ { targetPath: ctx.artifactDir, outputDir: ctx.artifactDir },
299
+ normalized,
300
+ );
301
+ }
302
+ } catch {
303
+ // Telemetry failures must not block tool execution
304
+ }
305
+ }
306
+
307
+ export class ToolDispatchError extends Error {
308
+ constructor(message) {
309
+ super(message);
310
+ this.name = "ToolDispatchError";
311
+ }
312
+ }
313
+
314
+ export class BudgetExhaustedError extends Error {
315
+ constructor(budgetCheck) {
316
+ super(`Budget exhausted: ${budgetCheck.reasons.map((r) => r.code).join(", ")}`);
317
+ this.name = "BudgetExhaustedError";
318
+ this.budgetCheck = budgetCheck;
319
+ }
320
+ }
@@ -0,0 +1,180 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { PathGuardError, resolveGuardedPath } from "./path-guards.js";
5
+
6
+ /**
7
+ * String replacement in files with uniqueness enforcement and diff generation.
8
+ * Designed for use inside a worktree — validates path is within allowed directory.
9
+ *
10
+ * @param {object} input
11
+ * @param {string} input.file_path - Absolute path to the file to modify.
12
+ * @param {string} input.old_string - Exact text to replace.
13
+ * @param {string} input.new_string - Replacement text (must differ from old_string).
14
+ * @param {boolean} [input.replace_all] - Replace all occurrences (default: false).
15
+ * @param {string} [input.allowed_root] - Root directory edits are permitted in (worktree guard).
16
+ * @returns {{ filePath, diff, occurrencesFound, occurrencesReplaced, linesChanged }}
17
+ */
18
+ export function fileEdit(input) {
19
+ if (!input.old_string && input.old_string !== "") {
20
+ throw new FileEditError("old_string is required.");
21
+ }
22
+ if (input.new_string === undefined || input.new_string === null) {
23
+ throw new FileEditError("new_string is required.");
24
+ }
25
+ if (input.old_string === input.new_string) {
26
+ throw new FileEditError("old_string and new_string must be different.");
27
+ }
28
+
29
+ let filePath;
30
+ try {
31
+ const guarded = resolveGuardedPath({
32
+ filePath: input.file_path,
33
+ allowedRoot: input.allowed_root || undefined,
34
+ });
35
+ filePath = guarded.resolvedPath;
36
+ } catch (error) {
37
+ if (error instanceof PathGuardError) {
38
+ throw new FileEditError(error.message);
39
+ }
40
+ if (error instanceof FileEditError) {
41
+ throw error;
42
+ }
43
+ throw new FileEditError(`Cannot access path: ${error.message}`);
44
+ }
45
+
46
+ // Read current content
47
+ let content;
48
+ try {
49
+ content = fs.readFileSync(filePath, "utf-8");
50
+ } catch (err) {
51
+ if (err.code === "ENOENT") {
52
+ throw new FileEditError(`File not found: ${filePath}`);
53
+ }
54
+ throw new FileEditError(`Cannot read file: ${err.message}`);
55
+ }
56
+
57
+ // Count occurrences
58
+ const occurrences = countOccurrences(content, input.old_string);
59
+ if (occurrences === 0) {
60
+ throw new FileEditError(
61
+ `old_string not found in ${filePath}. Verify the exact text including whitespace and indentation.`,
62
+ );
63
+ }
64
+ if (occurrences > 1 && !input.replace_all) {
65
+ throw new FileEditError(
66
+ `old_string found ${occurrences} times in ${filePath}. Use replace_all: true to replace all, or provide more surrounding context to make it unique.`,
67
+ );
68
+ }
69
+
70
+ // Perform replacement
71
+ const replaceCount = input.replace_all ? occurrences : 1;
72
+ let newContent;
73
+ if (input.replace_all) {
74
+ newContent = content.split(input.old_string).join(input.new_string);
75
+ } else {
76
+ const idx = content.indexOf(input.old_string);
77
+ newContent =
78
+ content.slice(0, idx) +
79
+ input.new_string +
80
+ content.slice(idx + input.old_string.length);
81
+ }
82
+
83
+ // Generate unified diff for display
84
+ const diff = generateUnifiedDiff(filePath, content, newContent);
85
+
86
+ // Count changed lines
87
+ const oldLines = content.split("\n").length;
88
+ const newLines = newContent.split("\n").length;
89
+ const linesChanged = Math.abs(newLines - oldLines) +
90
+ countDiffLines(content, newContent);
91
+
92
+ // Write atomically: temp file + rename
93
+ const tmpPath = filePath + `.sl-edit-${Date.now()}`;
94
+ fs.writeFileSync(tmpPath, newContent, "utf-8");
95
+ fs.renameSync(tmpPath, filePath);
96
+
97
+ return {
98
+ filePath,
99
+ diff,
100
+ occurrencesFound: occurrences,
101
+ occurrencesReplaced: replaceCount,
102
+ linesChanged,
103
+ beforeHash: hashContent(content),
104
+ afterHash: hashContent(newContent),
105
+ };
106
+ }
107
+
108
+ function countOccurrences(haystack, needle) {
109
+ if (!needle) return 0;
110
+ let count = 0;
111
+ let idx = 0;
112
+ while ((idx = haystack.indexOf(needle, idx)) !== -1) {
113
+ count++;
114
+ idx += needle.length;
115
+ }
116
+ return count;
117
+ }
118
+
119
+ function generateUnifiedDiff(filePath, oldContent, newContent) {
120
+ const oldLines = oldContent.split("\n");
121
+ const newLines = newContent.split("\n");
122
+ const diffLines = [];
123
+
124
+ diffLines.push(`--- a/${path.basename(filePath)}`);
125
+ diffLines.push(`+++ b/${path.basename(filePath)}`);
126
+
127
+ // Simple line-by-line diff (not full Myers — sufficient for review display)
128
+ const maxLines = Math.max(oldLines.length, newLines.length);
129
+ let chunkStart = -1;
130
+ let chunkOld = [];
131
+ let chunkNew = [];
132
+
133
+ for (let i = 0; i < maxLines; i++) {
134
+ const oldLine = i < oldLines.length ? oldLines[i] : undefined;
135
+ const newLine = i < newLines.length ? newLines[i] : undefined;
136
+
137
+ if (oldLine !== newLine) {
138
+ if (chunkStart === -1) chunkStart = i;
139
+ if (oldLine !== undefined) chunkOld.push(`-${oldLine}`);
140
+ if (newLine !== undefined) chunkNew.push(`+${newLine}`);
141
+ } else if (chunkStart !== -1) {
142
+ // Flush chunk
143
+ diffLines.push(`@@ -${chunkStart + 1},${chunkOld.length} +${chunkStart + 1},${chunkNew.length} @@`);
144
+ diffLines.push(...chunkOld, ...chunkNew);
145
+ chunkStart = -1;
146
+ chunkOld = [];
147
+ chunkNew = [];
148
+ }
149
+ }
150
+
151
+ // Flush final chunk
152
+ if (chunkStart !== -1) {
153
+ diffLines.push(`@@ -${chunkStart + 1},${chunkOld.length} +${chunkStart + 1},${chunkNew.length} @@`);
154
+ diffLines.push(...chunkOld, ...chunkNew);
155
+ }
156
+
157
+ return diffLines.join("\n");
158
+ }
159
+
160
+ function countDiffLines(oldContent, newContent) {
161
+ const oldLines = oldContent.split("\n");
162
+ const newLines = newContent.split("\n");
163
+ let changed = 0;
164
+ const max = Math.min(oldLines.length, newLines.length);
165
+ for (let i = 0; i < max; i++) {
166
+ if (oldLines[i] !== newLines[i]) changed++;
167
+ }
168
+ return changed;
169
+ }
170
+
171
+ function hashContent(content) {
172
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
173
+ }
174
+
175
+ export class FileEditError extends Error {
176
+ constructor(message) {
177
+ super(message);
178
+ this.name = "FileEditError";
179
+ }
180
+ }
@@ -0,0 +1,100 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { PathGuardError, resolveGuardedPath } from "./path-guards.js";
4
+
5
+ const MAX_RESULT_CHARS = 5000;
6
+ const BINARY_EXTENSIONS = new Set([
7
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".ico", ".svg",
8
+ ".woff", ".woff2", ".ttf", ".eot", ".otf",
9
+ ".mp3", ".mp4", ".ogg", ".webm", ".wav",
10
+ ".zip", ".tar", ".gz", ".br", ".zst",
11
+ ".pdf", ".wasm", ".node", ".exe", ".dll", ".so", ".dylib",
12
+ ]);
13
+
14
+ /**
15
+ * Read a file with line numbers, offset/limit pagination, and binary detection.
16
+ * Returns { filePath, content, numLines, startLine, totalLines, truncated }.
17
+ */
18
+ export function fileRead(input) {
19
+ const filePath = resolveAndValidatePath(input.file_path, input.allowed_root);
20
+ const ext = path.extname(filePath).toLowerCase();
21
+
22
+ if (BINARY_EXTENSIONS.has(ext)) {
23
+ const stat = fs.statSync(filePath);
24
+ return {
25
+ filePath,
26
+ content: `[Binary file: ${ext}, ${stat.size} bytes. Use a specialized viewer.]`,
27
+ numLines: 0,
28
+ startLine: 0,
29
+ totalLines: 0,
30
+ truncated: false,
31
+ binary: true,
32
+ };
33
+ }
34
+
35
+ let raw;
36
+ try {
37
+ raw = fs.readFileSync(filePath, "utf-8");
38
+ } catch (err) {
39
+ if (err.code === "ENOENT") {
40
+ throw new FileReadError(`File not found: ${filePath}`);
41
+ }
42
+ if (err.code === "EISDIR") {
43
+ throw new FileReadError(`Path is a directory, not a file: ${filePath}`);
44
+ }
45
+ throw new FileReadError(`Cannot read file: ${err.message}`);
46
+ }
47
+
48
+ const allLines = raw.split("\n");
49
+ const totalLines = allLines.length;
50
+ const offset = Math.max(0, input.offset ?? 0);
51
+ const limit = input.limit ?? 2000;
52
+ const sliced = allLines.slice(offset, offset + limit);
53
+ const startLine = offset + 1;
54
+
55
+ const numbered = sliced.map(
56
+ (line, i) => `${String(startLine + i).padStart(6)}\t${line}`,
57
+ );
58
+ let content = numbered.join("\n");
59
+ let truncated = false;
60
+
61
+ if (content.length > MAX_RESULT_CHARS) {
62
+ content = content.slice(0, MAX_RESULT_CHARS) + "\n[... truncated]";
63
+ truncated = true;
64
+ }
65
+
66
+ return {
67
+ filePath,
68
+ content,
69
+ numLines: sliced.length,
70
+ startLine,
71
+ totalLines,
72
+ truncated,
73
+ binary: false,
74
+ };
75
+ }
76
+
77
+ export class FileReadError extends Error {
78
+ constructor(message) {
79
+ super(message);
80
+ this.name = "FileReadError";
81
+ }
82
+ }
83
+
84
+ function resolveAndValidatePath(filePath, allowedRoot) {
85
+ try {
86
+ const guarded = resolveGuardedPath({
87
+ filePath,
88
+ allowedRoot: allowedRoot || undefined,
89
+ });
90
+ return guarded.resolvedPath;
91
+ } catch (error) {
92
+ if (error instanceof PathGuardError) {
93
+ throw new FileReadError(error.message);
94
+ }
95
+ if (error instanceof FileReadError) {
96
+ throw error;
97
+ }
98
+ throw new FileReadError(`Cannot access path: ${error.message}`);
99
+ }
100
+ }