sentinelayer-cli 0.1.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 (124) hide show
  1. package/README.md +996 -0
  2. package/bin/create-sentinelayer.js +5 -0
  3. package/bin/sentinelayer-cli.js +5 -0
  4. package/bin/sl.js +5 -0
  5. package/package.json +54 -0
  6. package/src/agents/jules/config/definition.js +209 -0
  7. package/src/agents/jules/config/system-prompt.js +175 -0
  8. package/src/agents/jules/error-intake.js +51 -0
  9. package/src/agents/jules/fix-cycle.js +377 -0
  10. package/src/agents/jules/loop.js +367 -0
  11. package/src/agents/jules/pulse.js +319 -0
  12. package/src/agents/jules/stream.js +186 -0
  13. package/src/agents/jules/swarm/file-scanner.js +74 -0
  14. package/src/agents/jules/swarm/index.js +11 -0
  15. package/src/agents/jules/swarm/orchestrator.js +362 -0
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -0
  17. package/src/agents/jules/swarm/sub-agent.js +308 -0
  18. package/src/agents/jules/tools/auth-audit.js +222 -0
  19. package/src/agents/jules/tools/dispatch.js +327 -0
  20. package/src/agents/jules/tools/file-edit.js +180 -0
  21. package/src/agents/jules/tools/file-read.js +100 -0
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -0
  23. package/src/agents/jules/tools/glob.js +168 -0
  24. package/src/agents/jules/tools/grep.js +228 -0
  25. package/src/agents/jules/tools/index.js +29 -0
  26. package/src/agents/jules/tools/path-guards.js +161 -0
  27. package/src/agents/jules/tools/runtime-audit.js +409 -0
  28. package/src/agents/jules/tools/shell.js +383 -0
  29. package/src/ai/aidenid.js +945 -0
  30. package/src/ai/client.js +508 -0
  31. package/src/ai/domain-target-store.js +268 -0
  32. package/src/ai/identity-store.js +270 -0
  33. package/src/ai/site-store.js +145 -0
  34. package/src/audit/agents/architecture.js +180 -0
  35. package/src/audit/agents/compliance.js +179 -0
  36. package/src/audit/agents/documentation.js +165 -0
  37. package/src/audit/agents/performance.js +145 -0
  38. package/src/audit/agents/security.js +215 -0
  39. package/src/audit/agents/testing.js +172 -0
  40. package/src/audit/orchestrator.js +557 -0
  41. package/src/audit/package.js +204 -0
  42. package/src/audit/registry.js +284 -0
  43. package/src/audit/replay.js +103 -0
  44. package/src/auth/http.js +113 -0
  45. package/src/auth/service.js +848 -0
  46. package/src/auth/session-store.js +345 -0
  47. package/src/cli.js +244 -0
  48. package/src/commands/ai/identity-lifecycle.js +1337 -0
  49. package/src/commands/ai/provision-governance.js +1246 -0
  50. package/src/commands/ai/shared.js +147 -0
  51. package/src/commands/ai.js +11 -0
  52. package/src/commands/apply.js +19 -0
  53. package/src/commands/audit.js +1147 -0
  54. package/src/commands/auth.js +366 -0
  55. package/src/commands/chat.js +191 -0
  56. package/src/commands/config.js +184 -0
  57. package/src/commands/cost.js +311 -0
  58. package/src/commands/daemon/core.js +850 -0
  59. package/src/commands/daemon/extended.js +1048 -0
  60. package/src/commands/daemon/shared.js +213 -0
  61. package/src/commands/daemon.js +11 -0
  62. package/src/commands/guide.js +174 -0
  63. package/src/commands/ingest.js +58 -0
  64. package/src/commands/init.js +55 -0
  65. package/src/commands/legacy-args.js +30 -0
  66. package/src/commands/mcp.js +404 -0
  67. package/src/commands/omargate.js +21 -0
  68. package/src/commands/persona.js +27 -0
  69. package/src/commands/plugin.js +260 -0
  70. package/src/commands/policy.js +132 -0
  71. package/src/commands/prompt.js +238 -0
  72. package/src/commands/review.js +704 -0
  73. package/src/commands/scan.js +788 -0
  74. package/src/commands/spec.js +716 -0
  75. package/src/commands/swarm.js +651 -0
  76. package/src/commands/telemetry.js +202 -0
  77. package/src/commands/watch.js +510 -0
  78. package/src/config/agent-dictionary.js +182 -0
  79. package/src/config/io.js +56 -0
  80. package/src/config/paths.js +18 -0
  81. package/src/config/schema.js +55 -0
  82. package/src/config/service.js +184 -0
  83. package/src/cost/budget.js +235 -0
  84. package/src/cost/history.js +188 -0
  85. package/src/cost/tracker.js +171 -0
  86. package/src/daemon/artifact-lineage.js +534 -0
  87. package/src/daemon/assignment-ledger.js +770 -0
  88. package/src/daemon/ast-parser-layer.js +258 -0
  89. package/src/daemon/budget-governor.js +633 -0
  90. package/src/daemon/callgraph-overlay.js +646 -0
  91. package/src/daemon/error-worker.js +626 -0
  92. package/src/daemon/hybrid-mapper.js +929 -0
  93. package/src/daemon/jira-lifecycle.js +632 -0
  94. package/src/daemon/operator-control.js +657 -0
  95. package/src/daemon/reliability-lane.js +471 -0
  96. package/src/daemon/watchdog.js +971 -0
  97. package/src/guide/generator.js +316 -0
  98. package/src/ingest/engine.js +918 -0
  99. package/src/legacy-cli.js +2435 -0
  100. package/src/mcp/registry.js +695 -0
  101. package/src/memory/blackboard.js +301 -0
  102. package/src/memory/retrieval.js +581 -0
  103. package/src/plugin/manifest.js +553 -0
  104. package/src/policy/packs.js +144 -0
  105. package/src/prompt/generator.js +106 -0
  106. package/src/review/ai-review.js +669 -0
  107. package/src/review/local-review.js +1284 -0
  108. package/src/review/replay.js +235 -0
  109. package/src/review/report.js +664 -0
  110. package/src/review/spec-binding.js +487 -0
  111. package/src/scan/generator.js +351 -0
  112. package/src/spec/generator.js +519 -0
  113. package/src/spec/regenerate.js +237 -0
  114. package/src/spec/templates.js +91 -0
  115. package/src/swarm/dashboard.js +247 -0
  116. package/src/swarm/factory.js +363 -0
  117. package/src/swarm/pentest.js +934 -0
  118. package/src/swarm/registry.js +419 -0
  119. package/src/swarm/report.js +158 -0
  120. package/src/swarm/runtime.js +576 -0
  121. package/src/swarm/scenario-dsl.js +272 -0
  122. package/src/telemetry/ledger.js +302 -0
  123. package/src/ui/markdown.js +220 -0
  124. package/src/ui/progress.js +100 -0
@@ -0,0 +1,327 @@
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 { fileRead } from "./file-read.js";
8
+ import { grep } from "./grep.js";
9
+ import { glob } from "./glob.js";
10
+ import { shell } from "./shell.js";
11
+ import { fileEdit } from "./file-edit.js";
12
+ import { frontendAnalyze } from "./frontend-analyze.js";
13
+ import { runtimeAudit } from "./runtime-audit.js";
14
+ import { authAudit } from "./auth-audit.js";
15
+
16
+ /**
17
+ * Central tool dispatcher for Jules agents.
18
+ * Every tool call: budget check → telemetry emit → execute → telemetry result → return.
19
+ */
20
+
21
+ const TOOL_MAP = {
22
+ FileRead: fileRead,
23
+ Grep: grep,
24
+ Glob: glob,
25
+ Shell: shell,
26
+ FileEdit: fileEdit,
27
+ FrontendAnalyze: frontendAnalyze,
28
+ RuntimeAudit: runtimeAudit,
29
+ AuthAudit: authAudit,
30
+ };
31
+
32
+ const READ_ONLY_TOOLS = new Set(["FileRead", "Grep", "Glob", "FrontendAnalyze", "RuntimeAudit", "AuthAudit"]);
33
+
34
+ const RESULT_PERSIST_THRESHOLD = 5000;
35
+
36
+ /**
37
+ * @param {string} toolName
38
+ * @param {object} input
39
+ * @param {AgentContext} ctx
40
+ * @returns {Promise<ToolResult>}
41
+ */
42
+ export async function dispatchTool(toolName, input, ctx) {
43
+ const handler = TOOL_MAP[toolName];
44
+ if (!handler) {
45
+ throw new ToolDispatchError(`Unknown tool: ${toolName}`);
46
+ }
47
+
48
+ // 1. Pre-flight budget check
49
+ const budgetCheck = evaluateBudget({
50
+ maxCostUsd: ctx.budget.maxCostUsd,
51
+ maxOutputTokens: ctx.budget.maxOutputTokens,
52
+ maxRuntimeMs: ctx.budget.maxRuntimeMs,
53
+ maxToolCalls: ctx.budget.maxToolCalls,
54
+ warningThresholdPercent: ctx.budget.warningThresholdPercent ?? 70,
55
+ maxNoProgress: 0,
56
+ sessionSummary: {
57
+ costUsd: ctx.usage.costUsd,
58
+ outputTokens: ctx.usage.outputTokens,
59
+ durationMs: Date.now() - ctx.startedAt,
60
+ toolCalls: ctx.usage.toolCalls + 1,
61
+ noProgressStreak: 0,
62
+ },
63
+ });
64
+
65
+ if (budgetCheck.blocking) {
66
+ const stopEvent = {
67
+ eventType: "run_stop",
68
+ sessionId: ctx.sessionId,
69
+ runId: ctx.runId,
70
+ stop: {
71
+ stopClass: budgetCheck.reasons[0]?.code || "MAX_TOOL_CALLS_EXCEEDED",
72
+ blocking: true,
73
+ reasonCodes: budgetCheck.reasons.map((r) => r.code),
74
+ },
75
+ usage: snapshotUsage(ctx),
76
+ metadata: { tool: toolName, phase: "pre_flight" },
77
+ };
78
+ await safeAppendEvent(ctx, stopEvent);
79
+
80
+ if (ctx.onEvent) {
81
+ ctx.onEvent({
82
+ stream: "sl_event",
83
+ event: "budget_stop",
84
+ agent: ctx.agentIdentity,
85
+ payload: {
86
+ stopClass: stopEvent.stop.stopClass,
87
+ reasons: budgetCheck.reasons,
88
+ },
89
+ usage: snapshotUsage(ctx),
90
+ });
91
+ }
92
+
93
+ throw new BudgetExhaustedError(budgetCheck);
94
+ }
95
+
96
+ // Emit budget warnings
97
+ if (budgetCheck.warnings.length > 0 && ctx.onEvent) {
98
+ ctx.onEvent({
99
+ stream: "sl_event",
100
+ event: "budget_warning",
101
+ agent: ctx.agentIdentity,
102
+ payload: { warnings: budgetCheck.warnings },
103
+ usage: snapshotUsage(ctx),
104
+ });
105
+ }
106
+
107
+ // 2. Emit tool_call event
108
+ const eventId = randomUUID();
109
+ const callEvent = {
110
+ eventType: "tool_call",
111
+ sessionId: ctx.sessionId,
112
+ runId: ctx.runId,
113
+ metadata: {
114
+ eventId,
115
+ tool: toolName,
116
+ input: sanitizeInput(toolName, input),
117
+ agentId: ctx.agentIdentity?.id,
118
+ persona: ctx.agentIdentity?.persona,
119
+ },
120
+ };
121
+ await safeAppendEvent(ctx, callEvent);
122
+
123
+ if (ctx.onEvent) {
124
+ ctx.onEvent({
125
+ stream: "sl_event",
126
+ event: "tool_call",
127
+ agent: ctx.agentIdentity,
128
+ payload: { tool: toolName, input: sanitizeInput(toolName, input) },
129
+ usage: snapshotUsage(ctx),
130
+ });
131
+ }
132
+
133
+ // 3. Execute
134
+ const startMs = Date.now();
135
+ let result;
136
+ let error;
137
+ try {
138
+ result = handler(input);
139
+ } catch (err) {
140
+ error = err;
141
+ }
142
+ const durationMs = Date.now() - startMs;
143
+
144
+ // 4. Update accumulated usage
145
+ ctx.usage.toolCalls++;
146
+ ctx.usage.runtimeMs = Date.now() - ctx.startedAt;
147
+ ctx.lastToolCallAt = Date.now();
148
+ ctx.lastToolName = toolName;
149
+
150
+ // 5. Emit tool_result event
151
+ const resultEvent = {
152
+ eventType: "tool_call",
153
+ sessionId: ctx.sessionId,
154
+ runId: ctx.runId,
155
+ usage: {
156
+ durationMs,
157
+ toolCalls: 1,
158
+ },
159
+ metadata: {
160
+ eventId,
161
+ phase: "result",
162
+ tool: toolName,
163
+ success: !error,
164
+ error: error?.message,
165
+ agentId: ctx.agentIdentity?.id,
166
+ },
167
+ };
168
+ await safeAppendEvent(ctx, resultEvent);
169
+
170
+ if (ctx.onEvent) {
171
+ ctx.onEvent({
172
+ stream: "sl_event",
173
+ event: "tool_result",
174
+ agent: ctx.agentIdentity,
175
+ payload: {
176
+ tool: toolName,
177
+ durationMs,
178
+ success: !error,
179
+ error: error?.message,
180
+ },
181
+ usage: snapshotUsage(ctx),
182
+ });
183
+ }
184
+
185
+ if (error) throw error;
186
+
187
+ // 6. Large result persistence
188
+ const serialized = JSON.stringify(result);
189
+ if (serialized.length > RESULT_PERSIST_THRESHOLD && ctx.artifactDir) {
190
+ const refPath = `${ctx.artifactDir}/tool-results/${eventId}.json`;
191
+ const fsp = await import("node:fs/promises");
192
+ await fsp.mkdir(`${ctx.artifactDir}/tool-results`, { recursive: true });
193
+ await fsp.writeFile(refPath, serialized, "utf-8");
194
+ return {
195
+ _persisted: true,
196
+ _refPath: refPath,
197
+ _summary: summarizeResult(toolName, result),
198
+ };
199
+ }
200
+
201
+ return result;
202
+ }
203
+
204
+ /**
205
+ * Register an additional tool (e.g., FrontendAnalyze from PR J-2).
206
+ */
207
+ export function registerTool(name, handler, { readOnly = false } = {}) {
208
+ TOOL_MAP[name] = handler;
209
+ if (readOnly) READ_ONLY_TOOLS.add(name);
210
+ }
211
+
212
+ /**
213
+ * Check if a tool is read-only (safe for concurrent execution).
214
+ */
215
+ export function isReadOnlyTool(toolName) {
216
+ return READ_ONLY_TOOLS.has(toolName);
217
+ }
218
+
219
+ /**
220
+ * Get list of available tool names.
221
+ */
222
+ export function listTools() {
223
+ return Object.keys(TOOL_MAP);
224
+ }
225
+
226
+ /**
227
+ * Create an agent context for tool dispatch.
228
+ */
229
+ export function createAgentContext({
230
+ agentIdentity,
231
+ budget,
232
+ sessionId,
233
+ runId,
234
+ artifactDir,
235
+ onEvent,
236
+ }) {
237
+ return {
238
+ agentIdentity,
239
+ budget: {
240
+ maxCostUsd: budget?.maxCostUsd ?? 5.0,
241
+ maxOutputTokens: budget?.maxOutputTokens ?? 12000,
242
+ maxRuntimeMs: budget?.maxRuntimeMs ?? 300000,
243
+ maxToolCalls: budget?.maxToolCalls ?? 150,
244
+ warningThresholdPercent: budget?.warningThresholdPercent ?? 70,
245
+ },
246
+ usage: {
247
+ costUsd: 0,
248
+ outputTokens: 0,
249
+ toolCalls: 0,
250
+ runtimeMs: 0,
251
+ },
252
+ sessionId: sessionId || randomUUID(),
253
+ runId: runId || `jules-${Date.now()}-${randomUUID().slice(0, 8)}`,
254
+ artifactDir,
255
+ startedAt: Date.now(),
256
+ lastToolCallAt: Date.now(),
257
+ lastToolName: null,
258
+ onEvent,
259
+ };
260
+ }
261
+
262
+ function snapshotUsage(ctx) {
263
+ return {
264
+ costUsd: ctx.usage.costUsd,
265
+ outputTokens: ctx.usage.outputTokens,
266
+ toolCalls: ctx.usage.toolCalls,
267
+ durationMs: Date.now() - ctx.startedAt,
268
+ };
269
+ }
270
+
271
+ function sanitizeInput(toolName, input) {
272
+ // Strip file content from telemetry (only log metadata)
273
+ const sanitized = { ...input };
274
+ if (sanitized.content && sanitized.content.length > 200) {
275
+ sanitized.content = `[${sanitized.content.length} chars]`;
276
+ }
277
+ return sanitized;
278
+ }
279
+
280
+ function summarizeResult(toolName, result) {
281
+ if (toolName === "FileRead") {
282
+ return `Read ${result.numLines} lines from ${result.filePath}`;
283
+ }
284
+ if (toolName === "Grep") {
285
+ return `${result.numMatches} matches in ${result.numFiles} files`;
286
+ }
287
+ if (toolName === "Glob") {
288
+ return `${result.numFiles} files matched`;
289
+ }
290
+ if (toolName === "Shell") {
291
+ return `Exit ${result.exitCode} in ${result.durationMs}ms`;
292
+ }
293
+ return `${toolName} completed`;
294
+ }
295
+
296
+ async function safeAppendEvent(ctx, eventData) {
297
+ try {
298
+ const normalized = normalizeRunEvent({
299
+ ...eventData,
300
+ sessionId: ctx.sessionId,
301
+ runId: ctx.runId,
302
+ });
303
+ if (ctx.artifactDir) {
304
+ await appendRunEvent(
305
+ { targetPath: ctx.artifactDir, outputDir: ctx.artifactDir },
306
+ normalized,
307
+ );
308
+ }
309
+ } catch {
310
+ // Telemetry failures must not block tool execution
311
+ }
312
+ }
313
+
314
+ export class ToolDispatchError extends Error {
315
+ constructor(message) {
316
+ super(message);
317
+ this.name = "ToolDispatchError";
318
+ }
319
+ }
320
+
321
+ export class BudgetExhaustedError extends Error {
322
+ constructor(budgetCheck) {
323
+ super(`Budget exhausted: ${budgetCheck.reasons.map((r) => r.code).join(", ")}`);
324
+ this.name = "BudgetExhaustedError";
325
+ this.budgetCheck = budgetCheck;
326
+ }
327
+ }
@@ -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
+ }