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