@spotpatch/dev-server 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.
- package/LICENSE +21 -0
- package/README.md +31 -0
- package/dist/index.cjs +2447 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +201 -0
- package/dist/index.d.ts +201 -0
- package/dist/index.js +2438 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2438 @@
|
|
|
1
|
+
// src/agent/job-manager.ts
|
|
2
|
+
import { createHash, randomBytes } from "crypto";
|
|
3
|
+
import {
|
|
4
|
+
applyPreparedAgentChange,
|
|
5
|
+
executeAgentChange,
|
|
6
|
+
inspectAgentWorkspace,
|
|
7
|
+
probeProviderCapability,
|
|
8
|
+
resolveProviderCredential,
|
|
9
|
+
revertPreparedAgentChange
|
|
10
|
+
} from "@spotpatch/agent";
|
|
11
|
+
import {
|
|
12
|
+
ERROR_CODES,
|
|
13
|
+
SpotPatchError
|
|
14
|
+
} from "@spotpatch/shared";
|
|
15
|
+
var MAX_RETAINED_JOBS = 32;
|
|
16
|
+
var MAX_RETAINED_EVENTS = 512;
|
|
17
|
+
var JOB_ID_PATTERN = /^[A-Za-z0-9_-]{22,128}$/;
|
|
18
|
+
var ACTIVE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
19
|
+
"queued",
|
|
20
|
+
"preparing",
|
|
21
|
+
"running",
|
|
22
|
+
"validating",
|
|
23
|
+
"awaiting-review",
|
|
24
|
+
"applying",
|
|
25
|
+
"cancelling",
|
|
26
|
+
"reverting"
|
|
27
|
+
]);
|
|
28
|
+
var CANCELLABLE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
29
|
+
"queued",
|
|
30
|
+
"preparing",
|
|
31
|
+
"running",
|
|
32
|
+
"validating",
|
|
33
|
+
"awaiting-review"
|
|
34
|
+
]);
|
|
35
|
+
var PRUNABLE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
36
|
+
"completed",
|
|
37
|
+
"cancelled",
|
|
38
|
+
"reverted",
|
|
39
|
+
"failed"
|
|
40
|
+
]);
|
|
41
|
+
var DEFAULT_DEPENDENCIES = Object.freeze({
|
|
42
|
+
applyChange: applyPreparedAgentChange,
|
|
43
|
+
createJobId: () => randomBytes(16).toString("base64url"),
|
|
44
|
+
executeChange: executeAgentChange,
|
|
45
|
+
inspectWorkspace: inspectAgentWorkspace,
|
|
46
|
+
now: () => (/* @__PURE__ */ new Date()).toISOString(),
|
|
47
|
+
probeCapability: probeProviderCapability,
|
|
48
|
+
resolveCredential: resolveProviderCredential,
|
|
49
|
+
revertChange: revertPreparedAgentChange
|
|
50
|
+
});
|
|
51
|
+
function normalizeError(error) {
|
|
52
|
+
return error instanceof SpotPatchError ? error : new SpotPatchError(ERROR_CODES.INTERNAL_ERROR, void 0, { cause: error });
|
|
53
|
+
}
|
|
54
|
+
function isActive(status) {
|
|
55
|
+
return ACTIVE_JOB_STATUSES.has(status);
|
|
56
|
+
}
|
|
57
|
+
function snapshot(job) {
|
|
58
|
+
const base = {
|
|
59
|
+
jobId: job.id,
|
|
60
|
+
status: job.status,
|
|
61
|
+
providerProfileId: job.provider.id,
|
|
62
|
+
providerLabel: job.provider.label,
|
|
63
|
+
modelProfileId: job.model.id,
|
|
64
|
+
modelLabel: job.model.label,
|
|
65
|
+
phaseMessage: job.phaseMessage,
|
|
66
|
+
createdAt: job.createdAt,
|
|
67
|
+
updatedAt: job.updatedAt,
|
|
68
|
+
canCancel: CANCELLABLE_JOB_STATUSES.has(job.status),
|
|
69
|
+
canApply: job.status === "awaiting-review" && job.preparedChange?.validationPassed === true && job.result !== void 0 && job.result.diff.length > 0,
|
|
70
|
+
canRevert: job.status === "applied"
|
|
71
|
+
};
|
|
72
|
+
return Object.freeze(
|
|
73
|
+
job.errorCode === void 0 ? base : { ...base, errorCode: job.errorCode }
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
function capabilityCacheKey(provider, model) {
|
|
77
|
+
const configurationDigest = createHash("sha256").update(provider.baseURL).update("\0").update(provider.protocol).update("\0").update(provider.authentication).digest("hex");
|
|
78
|
+
return `${provider.id}:${model.id}:${configurationDigest}`;
|
|
79
|
+
}
|
|
80
|
+
function freezeEvent(event) {
|
|
81
|
+
return Object.freeze(event);
|
|
82
|
+
}
|
|
83
|
+
function createAgentJobManager(options) {
|
|
84
|
+
const dependencies = Object.freeze({
|
|
85
|
+
...DEFAULT_DEPENDENCIES,
|
|
86
|
+
...options.dependencies
|
|
87
|
+
});
|
|
88
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
89
|
+
const capabilityCache = /* @__PURE__ */ new Map();
|
|
90
|
+
const providerConsents = /* @__PURE__ */ new Set();
|
|
91
|
+
let closed = false;
|
|
92
|
+
const resolveSelection = (providerProfileId, modelProfileId) => {
|
|
93
|
+
const provider = options.ai.providers[providerProfileId];
|
|
94
|
+
if (provider === void 0) {
|
|
95
|
+
throw new SpotPatchError(ERROR_CODES.PROVIDER_NOT_CONFIGURED);
|
|
96
|
+
}
|
|
97
|
+
const model = provider.models[modelProfileId];
|
|
98
|
+
if (model === void 0) {
|
|
99
|
+
throw new SpotPatchError(ERROR_CODES.MODEL_NOT_ALLOWED);
|
|
100
|
+
}
|
|
101
|
+
const credential = dependencies.resolveCredential(
|
|
102
|
+
provider.apiKeyEnv,
|
|
103
|
+
options.environment
|
|
104
|
+
);
|
|
105
|
+
return Object.freeze({ credential, model, provider });
|
|
106
|
+
};
|
|
107
|
+
const requireJob = (jobId) => {
|
|
108
|
+
if (!JOB_ID_PATTERN.test(jobId)) {
|
|
109
|
+
throw new SpotPatchError(ERROR_CODES.INVALID_REQUEST);
|
|
110
|
+
}
|
|
111
|
+
const job = jobs.get(jobId);
|
|
112
|
+
if (job === void 0) {
|
|
113
|
+
throw new SpotPatchError(ERROR_CODES.INVALID_REQUEST);
|
|
114
|
+
}
|
|
115
|
+
return job;
|
|
116
|
+
};
|
|
117
|
+
const appendEvent = (job, event) => {
|
|
118
|
+
job.events.push(event);
|
|
119
|
+
if (job.events.length > MAX_RETAINED_EVENTS) {
|
|
120
|
+
job.events.splice(0, job.events.length - MAX_RETAINED_EVENTS);
|
|
121
|
+
}
|
|
122
|
+
for (const listener of job.listeners) {
|
|
123
|
+
listener(event);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const eventBase = (job) => {
|
|
127
|
+
job.sequence += 1;
|
|
128
|
+
return {
|
|
129
|
+
schemaVersion: 2,
|
|
130
|
+
sequence: job.sequence,
|
|
131
|
+
jobId: job.id,
|
|
132
|
+
status: job.status,
|
|
133
|
+
timestamp: dependencies.now()
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
const emitSnapshot = (job) => {
|
|
137
|
+
appendEvent(
|
|
138
|
+
job,
|
|
139
|
+
freezeEvent({
|
|
140
|
+
...eventBase(job),
|
|
141
|
+
type: "snapshot",
|
|
142
|
+
data: Object.freeze({ snapshot: snapshot(job) })
|
|
143
|
+
})
|
|
144
|
+
);
|
|
145
|
+
};
|
|
146
|
+
const emitPhase = (job, message) => {
|
|
147
|
+
appendEvent(
|
|
148
|
+
job,
|
|
149
|
+
freezeEvent({
|
|
150
|
+
...eventBase(job),
|
|
151
|
+
type: "phase",
|
|
152
|
+
data: Object.freeze({ message })
|
|
153
|
+
})
|
|
154
|
+
);
|
|
155
|
+
};
|
|
156
|
+
const emitError = (job, code) => {
|
|
157
|
+
appendEvent(
|
|
158
|
+
job,
|
|
159
|
+
freezeEvent({
|
|
160
|
+
...eventBase(job),
|
|
161
|
+
type: "error",
|
|
162
|
+
data: Object.freeze({ code, message: "The Agent job failed." })
|
|
163
|
+
})
|
|
164
|
+
);
|
|
165
|
+
};
|
|
166
|
+
const transition = (job, status, phaseMessage, errorCode) => {
|
|
167
|
+
job.status = status;
|
|
168
|
+
job.phaseMessage = phaseMessage;
|
|
169
|
+
job.errorCode = errorCode;
|
|
170
|
+
job.updatedAt = dependencies.now();
|
|
171
|
+
emitSnapshot(job);
|
|
172
|
+
emitPhase(job, phaseMessage);
|
|
173
|
+
};
|
|
174
|
+
const probeResolved = async (selection, signal) => {
|
|
175
|
+
const key = capabilityCacheKey(selection.provider, selection.model);
|
|
176
|
+
const cached = capabilityCache.get(key);
|
|
177
|
+
if (cached !== void 0) {
|
|
178
|
+
return cached;
|
|
179
|
+
}
|
|
180
|
+
const capability = await dependencies.probeCapability({
|
|
181
|
+
provider: selection.provider,
|
|
182
|
+
modelProfileId: selection.model.id,
|
|
183
|
+
limits: options.ai.execution.limits,
|
|
184
|
+
credential: selection.credential,
|
|
185
|
+
signal,
|
|
186
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
187
|
+
});
|
|
188
|
+
if (capability.state !== "agent-ready") {
|
|
189
|
+
throw new SpotPatchError(ERROR_CODES.MODEL_TOOL_CALL_UNSUPPORTED);
|
|
190
|
+
}
|
|
191
|
+
capabilityCache.set(key, capability);
|
|
192
|
+
return capability;
|
|
193
|
+
};
|
|
194
|
+
const finishWithError = (job, error) => {
|
|
195
|
+
const normalized = normalizeError(error);
|
|
196
|
+
const cancelled = job.controller.signal.aborted || normalized.code === ERROR_CODES.AGENT_CANCELLED;
|
|
197
|
+
transition(
|
|
198
|
+
job,
|
|
199
|
+
cancelled ? "cancelled" : "failed",
|
|
200
|
+
cancelled ? "Agent job cancelled." : "Agent job failed.",
|
|
201
|
+
cancelled ? ERROR_CODES.AGENT_CANCELLED : normalized.code
|
|
202
|
+
);
|
|
203
|
+
if (!cancelled) {
|
|
204
|
+
emitError(job, normalized.code);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const applyChange = async (job, preparedChange) => {
|
|
208
|
+
transition(job, "applying", "Applying validated changes to the project.");
|
|
209
|
+
try {
|
|
210
|
+
await dependencies.applyChange(preparedChange);
|
|
211
|
+
transition(job, "applied", "Changes were applied to local project files.");
|
|
212
|
+
} catch (error) {
|
|
213
|
+
const normalized = normalizeError(error);
|
|
214
|
+
transition(job, "failed", "Agent change could not be applied.", normalized.code);
|
|
215
|
+
emitError(job, normalized.code);
|
|
216
|
+
throw normalized;
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const runJob = async (job) => {
|
|
220
|
+
try {
|
|
221
|
+
transition(job, "preparing", "Verifying provider and model capabilities.");
|
|
222
|
+
await probeResolved(
|
|
223
|
+
Object.freeze({
|
|
224
|
+
credential: job.credential,
|
|
225
|
+
model: job.model,
|
|
226
|
+
provider: job.provider
|
|
227
|
+
}),
|
|
228
|
+
job.controller.signal
|
|
229
|
+
);
|
|
230
|
+
const callbacks = {
|
|
231
|
+
onCheck(result) {
|
|
232
|
+
appendEvent(
|
|
233
|
+
job,
|
|
234
|
+
freezeEvent({
|
|
235
|
+
...eventBase(job),
|
|
236
|
+
type: "check",
|
|
237
|
+
data: Object.freeze({ result })
|
|
238
|
+
})
|
|
239
|
+
);
|
|
240
|
+
},
|
|
241
|
+
onPhase(event) {
|
|
242
|
+
transition(job, event.phase, event.message);
|
|
243
|
+
},
|
|
244
|
+
onTool(event) {
|
|
245
|
+
appendEvent(
|
|
246
|
+
job,
|
|
247
|
+
freezeEvent({
|
|
248
|
+
...eventBase(job),
|
|
249
|
+
type: "tool",
|
|
250
|
+
data: Object.freeze({ ...event })
|
|
251
|
+
})
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const preparedChange = await dependencies.executeChange({
|
|
256
|
+
annotation: job.annotation,
|
|
257
|
+
callbacks,
|
|
258
|
+
credential: job.credential,
|
|
259
|
+
execution: options.ai.execution,
|
|
260
|
+
jobId: job.id,
|
|
261
|
+
model: job.model,
|
|
262
|
+
provider: job.provider,
|
|
263
|
+
root: options.root,
|
|
264
|
+
signal: job.controller.signal,
|
|
265
|
+
workingTreeMode: job.workingTreeMode,
|
|
266
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
267
|
+
});
|
|
268
|
+
job.preparedChange = preparedChange;
|
|
269
|
+
job.result = preparedChange.result;
|
|
270
|
+
appendEvent(
|
|
271
|
+
job,
|
|
272
|
+
freezeEvent({
|
|
273
|
+
...eventBase(job),
|
|
274
|
+
type: "result-ready",
|
|
275
|
+
data: Object.freeze({ hasResult: true })
|
|
276
|
+
})
|
|
277
|
+
);
|
|
278
|
+
if (!preparedChange.validationPassed) {
|
|
279
|
+
transition(
|
|
280
|
+
job,
|
|
281
|
+
"failed",
|
|
282
|
+
"Required validation checks failed.",
|
|
283
|
+
ERROR_CODES.VALIDATION_FAILED
|
|
284
|
+
);
|
|
285
|
+
emitError(job, ERROR_CODES.VALIDATION_FAILED);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (preparedChange.result.diff.length === 0) {
|
|
289
|
+
transition(job, "completed", "No source changes were proposed.");
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (options.ai.execution.applyMode === "auto" && preparedChange.autoApplyEligible) {
|
|
293
|
+
try {
|
|
294
|
+
await applyChange(job, preparedChange);
|
|
295
|
+
} catch {
|
|
296
|
+
}
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
transition(job, "awaiting-review", "Validated changes are ready for review.");
|
|
300
|
+
} catch (error) {
|
|
301
|
+
finishWithError(job, error);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
const hasActiveJob = (excludedJobId) => [...jobs.values()].some((job) => job.id !== excludedJobId && isActive(job.status));
|
|
305
|
+
const pruneJobs = () => {
|
|
306
|
+
if (jobs.size < MAX_RETAINED_JOBS) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
for (const [jobId, job] of jobs) {
|
|
310
|
+
if (PRUNABLE_JOB_STATUSES.has(job.status)) {
|
|
311
|
+
jobs.delete(jobId);
|
|
312
|
+
}
|
|
313
|
+
if (jobs.size < MAX_RETAINED_JOBS) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
return Object.freeze({
|
|
319
|
+
async apply(jobId) {
|
|
320
|
+
const job = requireJob(jobId);
|
|
321
|
+
if (job.status !== "awaiting-review" || job.preparedChange === void 0 || !job.preparedChange.validationPassed || job.result?.diff.length === 0) {
|
|
322
|
+
throw new SpotPatchError(ERROR_CODES.PATCH_REJECTED);
|
|
323
|
+
}
|
|
324
|
+
await applyChange(job, job.preparedChange);
|
|
325
|
+
return snapshot(job);
|
|
326
|
+
},
|
|
327
|
+
cancel(jobId) {
|
|
328
|
+
const job = requireJob(jobId);
|
|
329
|
+
if (!CANCELLABLE_JOB_STATUSES.has(job.status)) {
|
|
330
|
+
return snapshot(job);
|
|
331
|
+
}
|
|
332
|
+
if (job.status === "awaiting-review") {
|
|
333
|
+
job.preparedChange = void 0;
|
|
334
|
+
job.controller.abort("agent-review-cancelled");
|
|
335
|
+
transition(
|
|
336
|
+
job,
|
|
337
|
+
"cancelled",
|
|
338
|
+
"Agent review was closed without applying changes.",
|
|
339
|
+
ERROR_CODES.AGENT_CANCELLED
|
|
340
|
+
);
|
|
341
|
+
return snapshot(job);
|
|
342
|
+
}
|
|
343
|
+
transition(job, "cancelling", "Cancelling Agent job.");
|
|
344
|
+
job.controller.abort("agent-job-cancelled");
|
|
345
|
+
return snapshot(job);
|
|
346
|
+
},
|
|
347
|
+
async close() {
|
|
348
|
+
if (closed) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
closed = true;
|
|
352
|
+
for (const job of jobs.values()) {
|
|
353
|
+
if (CANCELLABLE_JOB_STATUSES.has(job.status)) {
|
|
354
|
+
job.controller.abort("vite-server-closed");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
await Promise.allSettled(
|
|
358
|
+
[...jobs.values()].map((job) => job.runPromise).filter((promise) => promise !== void 0)
|
|
359
|
+
);
|
|
360
|
+
capabilityCache.clear();
|
|
361
|
+
providerConsents.clear();
|
|
362
|
+
jobs.clear();
|
|
363
|
+
},
|
|
364
|
+
create(request) {
|
|
365
|
+
if (closed) {
|
|
366
|
+
throw new SpotPatchError(ERROR_CODES.AI_DISABLED);
|
|
367
|
+
}
|
|
368
|
+
if (hasActiveJob()) {
|
|
369
|
+
throw new SpotPatchError(ERROR_CODES.AGENT_BUSY);
|
|
370
|
+
}
|
|
371
|
+
pruneJobs();
|
|
372
|
+
if (jobs.size >= MAX_RETAINED_JOBS) {
|
|
373
|
+
throw new SpotPatchError(ERROR_CODES.AGENT_BUSY);
|
|
374
|
+
}
|
|
375
|
+
const selection = resolveSelection(
|
|
376
|
+
request.providerProfileId,
|
|
377
|
+
request.modelProfileId
|
|
378
|
+
);
|
|
379
|
+
providerConsents.add(selection.provider.id);
|
|
380
|
+
const id = dependencies.createJobId();
|
|
381
|
+
if (!JOB_ID_PATTERN.test(id) || jobs.has(id)) {
|
|
382
|
+
throw new SpotPatchError(ERROR_CODES.INTERNAL_ERROR);
|
|
383
|
+
}
|
|
384
|
+
const timestamp = dependencies.now();
|
|
385
|
+
const job = {
|
|
386
|
+
annotation: request.annotation,
|
|
387
|
+
controller: new AbortController(),
|
|
388
|
+
createdAt: timestamp,
|
|
389
|
+
credential: selection.credential,
|
|
390
|
+
errorCode: void 0,
|
|
391
|
+
events: [],
|
|
392
|
+
id,
|
|
393
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
394
|
+
model: selection.model,
|
|
395
|
+
phaseMessage: "Agent job queued.",
|
|
396
|
+
preparedChange: void 0,
|
|
397
|
+
provider: selection.provider,
|
|
398
|
+
result: void 0,
|
|
399
|
+
runPromise: void 0,
|
|
400
|
+
sequence: 0,
|
|
401
|
+
status: "queued",
|
|
402
|
+
updatedAt: timestamp,
|
|
403
|
+
workingTreeMode: request.workingTreeMode
|
|
404
|
+
};
|
|
405
|
+
jobs.set(id, job);
|
|
406
|
+
emitSnapshot(job);
|
|
407
|
+
emitPhase(job, job.phaseMessage);
|
|
408
|
+
job.runPromise = Promise.resolve().then(async () => runJob(job));
|
|
409
|
+
return snapshot(job);
|
|
410
|
+
},
|
|
411
|
+
events(jobId) {
|
|
412
|
+
return Object.freeze([...requireJob(jobId).events]);
|
|
413
|
+
},
|
|
414
|
+
async probe(request, signal) {
|
|
415
|
+
if (closed) {
|
|
416
|
+
throw new SpotPatchError(ERROR_CODES.AI_DISABLED);
|
|
417
|
+
}
|
|
418
|
+
return probeResolved(
|
|
419
|
+
resolveSelection(request.providerProfileId, request.modelProfileId),
|
|
420
|
+
signal
|
|
421
|
+
);
|
|
422
|
+
},
|
|
423
|
+
result(jobId) {
|
|
424
|
+
const job = requireJob(jobId);
|
|
425
|
+
const response = job.result === void 0 ? { snapshot: snapshot(job) } : { snapshot: snapshot(job), result: job.result };
|
|
426
|
+
return Object.freeze(response);
|
|
427
|
+
},
|
|
428
|
+
async revert(jobId) {
|
|
429
|
+
const job = requireJob(jobId);
|
|
430
|
+
if (job.status !== "applied" || job.preparedChange === void 0 || hasActiveJob(job.id)) {
|
|
431
|
+
throw new SpotPatchError(
|
|
432
|
+
hasActiveJob(job.id) ? ERROR_CODES.AGENT_BUSY : ERROR_CODES.APPLY_CONFLICT
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
transition(job, "reverting", "Reverting the applied Agent change.");
|
|
436
|
+
try {
|
|
437
|
+
await dependencies.revertChange(job.preparedChange);
|
|
438
|
+
transition(job, "reverted", "The Agent change was safely reverted.");
|
|
439
|
+
} catch (error) {
|
|
440
|
+
const normalized = normalizeError(error);
|
|
441
|
+
transition(
|
|
442
|
+
job,
|
|
443
|
+
"applied",
|
|
444
|
+
"Revert was rejected because project files changed.",
|
|
445
|
+
normalized.code
|
|
446
|
+
);
|
|
447
|
+
emitError(job, normalized.code);
|
|
448
|
+
throw normalized;
|
|
449
|
+
}
|
|
450
|
+
return snapshot(job);
|
|
451
|
+
},
|
|
452
|
+
subscribe(jobId, listener) {
|
|
453
|
+
const job = requireJob(jobId);
|
|
454
|
+
job.listeners.add(listener);
|
|
455
|
+
return () => {
|
|
456
|
+
job.listeners.delete(listener);
|
|
457
|
+
};
|
|
458
|
+
},
|
|
459
|
+
workspaceHealth(signal) {
|
|
460
|
+
if (closed) {
|
|
461
|
+
throw new SpotPatchError(ERROR_CODES.AI_DISABLED);
|
|
462
|
+
}
|
|
463
|
+
return dependencies.inspectWorkspace(options.root, signal);
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// src/environment-ai.ts
|
|
469
|
+
var AI_ENVIRONMENT_NAMES = Object.freeze({
|
|
470
|
+
authentication: "SPOTPATCH_AI_AUTHENTICATION",
|
|
471
|
+
baseURL: "SPOTPATCH_AI_BASE_URL",
|
|
472
|
+
credential: "SPOTPATCH_AI_API_KEY",
|
|
473
|
+
model: "SPOTPATCH_AI_MODEL",
|
|
474
|
+
protocol: "SPOTPATCH_AI_PROTOCOL"
|
|
475
|
+
});
|
|
476
|
+
function resolveCredentialEnvironment(options, environment) {
|
|
477
|
+
if (options.ai === false) {
|
|
478
|
+
return Object.freeze({});
|
|
479
|
+
}
|
|
480
|
+
const names = new Set(
|
|
481
|
+
Object.values(options.ai.providers).map((provider) => provider.apiKeyEnv)
|
|
482
|
+
);
|
|
483
|
+
const missing = [...names].filter((name) => {
|
|
484
|
+
const value = environment[name];
|
|
485
|
+
return value === void 0 || value.trim().length === 0;
|
|
486
|
+
});
|
|
487
|
+
if (missing.length > 0) {
|
|
488
|
+
throw new RangeError(
|
|
489
|
+
`SpotPatch AI credential environment is missing ${missing.join(", ")}.`
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
return Object.freeze(
|
|
493
|
+
Object.fromEntries(
|
|
494
|
+
[...names].map((name) => {
|
|
495
|
+
const value = environment[name];
|
|
496
|
+
if (value === void 0) {
|
|
497
|
+
throw new RangeError("SpotPatch AI credential resolution failed.");
|
|
498
|
+
}
|
|
499
|
+
return [name, value];
|
|
500
|
+
})
|
|
501
|
+
)
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
function normalizedValue(environment, name) {
|
|
505
|
+
const value = environment[name];
|
|
506
|
+
if (value === void 0 || value.trim().length === 0) {
|
|
507
|
+
return void 0;
|
|
508
|
+
}
|
|
509
|
+
return value.trim();
|
|
510
|
+
}
|
|
511
|
+
function resolveEnvironmentAiConfiguration(environment) {
|
|
512
|
+
const baseURL = normalizedValue(environment, AI_ENVIRONMENT_NAMES.baseURL);
|
|
513
|
+
const model = normalizedValue(environment, AI_ENVIRONMENT_NAMES.model);
|
|
514
|
+
const credential = normalizedValue(environment, AI_ENVIRONMENT_NAMES.credential);
|
|
515
|
+
const protocol = normalizedValue(environment, AI_ENVIRONMENT_NAMES.protocol);
|
|
516
|
+
const authentication = normalizedValue(
|
|
517
|
+
environment,
|
|
518
|
+
AI_ENVIRONMENT_NAMES.authentication
|
|
519
|
+
);
|
|
520
|
+
const configuredValues = [baseURL, model, credential, protocol, authentication];
|
|
521
|
+
if (configuredValues.every((value) => value === void 0)) {
|
|
522
|
+
return Object.freeze({ ai: false });
|
|
523
|
+
}
|
|
524
|
+
const missing = [
|
|
525
|
+
[AI_ENVIRONMENT_NAMES.baseURL, baseURL],
|
|
526
|
+
[AI_ENVIRONMENT_NAMES.model, model],
|
|
527
|
+
[AI_ENVIRONMENT_NAMES.credential, credential]
|
|
528
|
+
].filter((entry) => entry[1] === void 0).map(([name]) => name);
|
|
529
|
+
if (missing.length > 0) {
|
|
530
|
+
throw new RangeError(
|
|
531
|
+
`SpotPatch AI environment configuration is incomplete; missing ${missing.join(", ")}.`
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
if (baseURL === void 0 || model === void 0 || credential === void 0) {
|
|
535
|
+
throw new RangeError("SpotPatch AI environment configuration is incomplete.");
|
|
536
|
+
}
|
|
537
|
+
if (protocol !== void 0 && protocol !== "responses" && protocol !== "chat-completions") {
|
|
538
|
+
throw new RangeError(
|
|
539
|
+
"SpotPatch SPOTPATCH_AI_PROTOCOL must be responses or chat-completions."
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
if (authentication !== void 0 && authentication !== "bearer" && authentication !== "x-api-key") {
|
|
543
|
+
throw new RangeError(
|
|
544
|
+
"SpotPatch SPOTPATCH_AI_AUTHENTICATION must be bearer or x-api-key."
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
return Object.freeze({
|
|
548
|
+
ai: Object.freeze({
|
|
549
|
+
baseURL,
|
|
550
|
+
model,
|
|
551
|
+
...protocol === void 0 ? {} : { protocol },
|
|
552
|
+
...authentication === void 0 ? {} : { authentication }
|
|
553
|
+
})
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// src/options.ts
|
|
558
|
+
import {
|
|
559
|
+
DEFAULT_AGENT_LIMITS,
|
|
560
|
+
MAX_ANNOTATION_TARGETS,
|
|
561
|
+
SPOTPATCH_EDITOR_PREFERENCES,
|
|
562
|
+
SPOTPATCH_LOCALE_PREFERENCES
|
|
563
|
+
} from "@spotpatch/shared";
|
|
564
|
+
import { z } from "zod";
|
|
565
|
+
var DEFAULT_EXCLUDE = Object.freeze([
|
|
566
|
+
/node_modules/,
|
|
567
|
+
/\.test\.[jt]sx$/,
|
|
568
|
+
/\.spec\.[jt]sx$/,
|
|
569
|
+
/\.stories\.[jt]sx$/,
|
|
570
|
+
/(?:^|\/)dist(?:\/|$)/,
|
|
571
|
+
/(?:^|\/)coverage(?:\/|$)/
|
|
572
|
+
]);
|
|
573
|
+
var DEFAULT_INCLUDE = Object.freeze([/(?:^|[/\\])src[/\\].+\.(?:jsx|tsx)$/]);
|
|
574
|
+
var DEFAULT_BUDGET = Object.freeze({
|
|
575
|
+
totalCharacters: 16e3,
|
|
576
|
+
domCharacters: 3e3,
|
|
577
|
+
cssCharacters: 4e3,
|
|
578
|
+
codeCharacters: 7e3,
|
|
579
|
+
maxCodeLines: 80,
|
|
580
|
+
maxComponentDepth: 8
|
|
581
|
+
});
|
|
582
|
+
var DEFAULT_OPTIONS = Object.freeze({
|
|
583
|
+
enabled: true,
|
|
584
|
+
include: DEFAULT_INCLUDE,
|
|
585
|
+
exclude: DEFAULT_EXCLUDE,
|
|
586
|
+
editor: "auto",
|
|
587
|
+
redact: true,
|
|
588
|
+
budget: DEFAULT_BUDGET,
|
|
589
|
+
shortcut: "Mod+Shift+S",
|
|
590
|
+
allowLan: false,
|
|
591
|
+
debug: false,
|
|
592
|
+
locale: "auto",
|
|
593
|
+
maxTargets: 8,
|
|
594
|
+
ai: false
|
|
595
|
+
});
|
|
596
|
+
var PROFILE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
597
|
+
var ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{1,127}$/;
|
|
598
|
+
var agentLimitsSchema = z.strictObject({
|
|
599
|
+
maxTurns: z.number().optional(),
|
|
600
|
+
maxToolCalls: z.number().optional(),
|
|
601
|
+
maxChangedFiles: z.number().optional(),
|
|
602
|
+
maxDiffBytes: z.number().optional(),
|
|
603
|
+
maxReadBytesPerFile: z.number().optional(),
|
|
604
|
+
maxToolOutputCharacters: z.number().optional(),
|
|
605
|
+
maxProviderResponseBytes: z.number().optional(),
|
|
606
|
+
providerConnectTimeoutMs: z.number().optional(),
|
|
607
|
+
providerFirstByteTimeoutMs: z.number().optional(),
|
|
608
|
+
providerIdleTimeoutMs: z.number().optional(),
|
|
609
|
+
checkTimeoutMs: z.number().optional(),
|
|
610
|
+
jobTimeoutMs: z.number().optional()
|
|
611
|
+
}).optional();
|
|
612
|
+
var agentCheckSchema = z.strictObject({
|
|
613
|
+
label: z.string(),
|
|
614
|
+
command: z.string(),
|
|
615
|
+
args: z.array(z.string()).optional(),
|
|
616
|
+
required: z.boolean().optional(),
|
|
617
|
+
timeoutMs: z.number().optional()
|
|
618
|
+
});
|
|
619
|
+
var aiOptionsSchema = z.strictObject({
|
|
620
|
+
providers: z.record(
|
|
621
|
+
z.string(),
|
|
622
|
+
z.strictObject({
|
|
623
|
+
type: z.literal("openai-compatible"),
|
|
624
|
+
label: z.string(),
|
|
625
|
+
protocol: z.enum(["responses", "chat-completions"]),
|
|
626
|
+
authentication: z.enum(["bearer", "x-api-key"]).optional(),
|
|
627
|
+
baseURL: z.string(),
|
|
628
|
+
apiKeyEnv: z.string(),
|
|
629
|
+
models: z.record(
|
|
630
|
+
z.string(),
|
|
631
|
+
z.strictObject({ label: z.string(), model: z.string() })
|
|
632
|
+
),
|
|
633
|
+
defaultModel: z.string()
|
|
634
|
+
})
|
|
635
|
+
),
|
|
636
|
+
defaultProvider: z.string(),
|
|
637
|
+
execution: z.strictObject({
|
|
638
|
+
isolation: z.literal("git-worktree").optional(),
|
|
639
|
+
applyMode: z.enum(["review", "auto"]).optional(),
|
|
640
|
+
checks: z.record(z.string(), agentCheckSchema).optional(),
|
|
641
|
+
limits: agentLimitsSchema
|
|
642
|
+
}).optional()
|
|
643
|
+
});
|
|
644
|
+
var simpleAiOptionsSchema = z.strictObject({
|
|
645
|
+
baseURL: z.string(),
|
|
646
|
+
model: z.string(),
|
|
647
|
+
apiKeyEnv: z.string().optional(),
|
|
648
|
+
protocol: z.enum(["responses", "chat-completions"]).optional(),
|
|
649
|
+
authentication: z.enum(["bearer", "x-api-key"]).optional(),
|
|
650
|
+
providerLabel: z.string().optional(),
|
|
651
|
+
modelLabel: z.string().optional(),
|
|
652
|
+
execution: aiOptionsSchema.shape.execution
|
|
653
|
+
});
|
|
654
|
+
function assertIdentifier(value, label) {
|
|
655
|
+
if (!PROFILE_ID_PATTERN.test(value)) {
|
|
656
|
+
throw new RangeError(
|
|
657
|
+
`SpotPatch ${label} must contain only letters, numbers, dot, underscore, or hyphen.`
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
function nonEmpty(value, label, maximum = 256) {
|
|
662
|
+
const normalized = value.trim();
|
|
663
|
+
if (normalized.length === 0 || normalized.length > maximum || value.includes("\0")) {
|
|
664
|
+
throw new RangeError(`SpotPatch ${label} is invalid.`);
|
|
665
|
+
}
|
|
666
|
+
return normalized;
|
|
667
|
+
}
|
|
668
|
+
function normalizeProviderBaseURL(value) {
|
|
669
|
+
let url;
|
|
670
|
+
try {
|
|
671
|
+
url = new URL(value);
|
|
672
|
+
} catch {
|
|
673
|
+
throw new RangeError("SpotPatch AI provider baseURL must be a valid URL.");
|
|
674
|
+
}
|
|
675
|
+
const loopbackHosts = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
676
|
+
const allowedProtocol = url.protocol === "https:" || url.protocol === "http:" && loopbackHosts.has(url.hostname);
|
|
677
|
+
if (!allowedProtocol || url.username.length > 0 || url.password.length > 0 || url.search.length > 0 || url.hash.length > 0) {
|
|
678
|
+
throw new RangeError("SpotPatch AI provider baseURL violates URL policy.");
|
|
679
|
+
}
|
|
680
|
+
url.pathname = url.pathname.replace(/\/{2,}/g, "/").replace(/\/$/, "");
|
|
681
|
+
return url.toString().replace(/\/$/, "");
|
|
682
|
+
}
|
|
683
|
+
function resolveLimits(limits) {
|
|
684
|
+
const resolved = Object.freeze({
|
|
685
|
+
maxTurns: limits?.maxTurns ?? DEFAULT_AGENT_LIMITS.maxTurns,
|
|
686
|
+
maxToolCalls: limits?.maxToolCalls ?? DEFAULT_AGENT_LIMITS.maxToolCalls,
|
|
687
|
+
maxChangedFiles: limits?.maxChangedFiles ?? DEFAULT_AGENT_LIMITS.maxChangedFiles,
|
|
688
|
+
maxDiffBytes: limits?.maxDiffBytes ?? DEFAULT_AGENT_LIMITS.maxDiffBytes,
|
|
689
|
+
maxReadBytesPerFile: limits?.maxReadBytesPerFile ?? DEFAULT_AGENT_LIMITS.maxReadBytesPerFile,
|
|
690
|
+
maxToolOutputCharacters: limits?.maxToolOutputCharacters ?? DEFAULT_AGENT_LIMITS.maxToolOutputCharacters,
|
|
691
|
+
maxProviderResponseBytes: limits?.maxProviderResponseBytes ?? DEFAULT_AGENT_LIMITS.maxProviderResponseBytes,
|
|
692
|
+
providerConnectTimeoutMs: limits?.providerConnectTimeoutMs ?? DEFAULT_AGENT_LIMITS.providerConnectTimeoutMs,
|
|
693
|
+
providerFirstByteTimeoutMs: limits?.providerFirstByteTimeoutMs ?? DEFAULT_AGENT_LIMITS.providerFirstByteTimeoutMs,
|
|
694
|
+
providerIdleTimeoutMs: limits?.providerIdleTimeoutMs ?? DEFAULT_AGENT_LIMITS.providerIdleTimeoutMs,
|
|
695
|
+
checkTimeoutMs: limits?.checkTimeoutMs ?? DEFAULT_AGENT_LIMITS.checkTimeoutMs,
|
|
696
|
+
jobTimeoutMs: limits?.jobTimeoutMs ?? DEFAULT_AGENT_LIMITS.jobTimeoutMs
|
|
697
|
+
});
|
|
698
|
+
for (const [name, value] of Object.entries(resolved)) {
|
|
699
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
700
|
+
throw new RangeError(`SpotPatch AI limit ${name} must be a positive integer.`);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return resolved;
|
|
704
|
+
}
|
|
705
|
+
function resolveModels(models) {
|
|
706
|
+
const entries = Object.entries(models);
|
|
707
|
+
if (entries.length === 0) {
|
|
708
|
+
throw new RangeError("SpotPatch AI provider must declare at least one model.");
|
|
709
|
+
}
|
|
710
|
+
return Object.freeze(
|
|
711
|
+
Object.fromEntries(
|
|
712
|
+
entries.map(([id, model]) => {
|
|
713
|
+
assertIdentifier(id, "model profile id");
|
|
714
|
+
return [
|
|
715
|
+
id,
|
|
716
|
+
Object.freeze({
|
|
717
|
+
id,
|
|
718
|
+
label: nonEmpty(model.label, "model label", 100),
|
|
719
|
+
model: nonEmpty(model.model, "provider model name")
|
|
720
|
+
})
|
|
721
|
+
];
|
|
722
|
+
})
|
|
723
|
+
)
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
function resolveProviders(providers) {
|
|
727
|
+
const entries = Object.entries(providers);
|
|
728
|
+
if (entries.length === 0) {
|
|
729
|
+
throw new RangeError("SpotPatch AI must declare at least one provider.");
|
|
730
|
+
}
|
|
731
|
+
return Object.freeze(
|
|
732
|
+
Object.fromEntries(
|
|
733
|
+
entries.map(([id, provider]) => {
|
|
734
|
+
assertIdentifier(id, "provider profile id");
|
|
735
|
+
if (!ENV_NAME_PATTERN.test(provider.apiKeyEnv) || provider.apiKeyEnv.startsWith("VITE_")) {
|
|
736
|
+
throw new RangeError(
|
|
737
|
+
"SpotPatch AI apiKeyEnv must be an uppercase non-VITE environment name."
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
const models = resolveModels(provider.models);
|
|
741
|
+
if (!(provider.defaultModel in models)) {
|
|
742
|
+
throw new RangeError(
|
|
743
|
+
"SpotPatch AI provider defaultModel must reference a configured model."
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
return [
|
|
747
|
+
id,
|
|
748
|
+
Object.freeze({
|
|
749
|
+
id,
|
|
750
|
+
type: provider.type,
|
|
751
|
+
label: nonEmpty(provider.label, "provider label", 100),
|
|
752
|
+
protocol: provider.protocol,
|
|
753
|
+
authentication: provider.authentication ?? "bearer",
|
|
754
|
+
baseURL: normalizeProviderBaseURL(provider.baseURL),
|
|
755
|
+
apiKeyEnv: provider.apiKeyEnv,
|
|
756
|
+
models,
|
|
757
|
+
defaultModel: provider.defaultModel
|
|
758
|
+
})
|
|
759
|
+
];
|
|
760
|
+
})
|
|
761
|
+
)
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
function resolveChecks(checks, defaultTimeoutMs) {
|
|
765
|
+
return Object.freeze(
|
|
766
|
+
Object.fromEntries(
|
|
767
|
+
Object.entries(checks ?? {}).map(([id, check]) => {
|
|
768
|
+
assertIdentifier(id, "check id");
|
|
769
|
+
const timeoutMs = check.timeoutMs ?? defaultTimeoutMs;
|
|
770
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
|
|
771
|
+
throw new RangeError("SpotPatch AI check timeout must be positive.");
|
|
772
|
+
}
|
|
773
|
+
const args = Object.freeze(
|
|
774
|
+
[...check.args ?? []].map(
|
|
775
|
+
(argument) => nonEmpty(argument, "check argument", 4096)
|
|
776
|
+
)
|
|
777
|
+
);
|
|
778
|
+
return [
|
|
779
|
+
id,
|
|
780
|
+
Object.freeze({
|
|
781
|
+
id,
|
|
782
|
+
label: nonEmpty(check.label, "check label", 100),
|
|
783
|
+
command: nonEmpty(check.command, "check command", 1024),
|
|
784
|
+
args,
|
|
785
|
+
required: check.required ?? true,
|
|
786
|
+
timeoutMs
|
|
787
|
+
})
|
|
788
|
+
];
|
|
789
|
+
})
|
|
790
|
+
)
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
function resolveAiOptions(options) {
|
|
794
|
+
if (options === void 0 || options === false) {
|
|
795
|
+
return false;
|
|
796
|
+
}
|
|
797
|
+
const expanded = "providers" in options ? options : (() => {
|
|
798
|
+
const simple = simpleAiOptionsSchema.safeParse(options);
|
|
799
|
+
if (!simple.success) {
|
|
800
|
+
throw new RangeError("SpotPatch AI configuration is invalid.");
|
|
801
|
+
}
|
|
802
|
+
const providerId = "default";
|
|
803
|
+
const modelId = "default";
|
|
804
|
+
return {
|
|
805
|
+
providers: {
|
|
806
|
+
[providerId]: {
|
|
807
|
+
type: "openai-compatible",
|
|
808
|
+
label: simple.data.providerLabel ?? "AI provider",
|
|
809
|
+
protocol: simple.data.protocol ?? "chat-completions",
|
|
810
|
+
authentication: simple.data.authentication ?? "bearer",
|
|
811
|
+
baseURL: simple.data.baseURL,
|
|
812
|
+
apiKeyEnv: simple.data.apiKeyEnv ?? "SPOTPATCH_AI_API_KEY",
|
|
813
|
+
models: {
|
|
814
|
+
[modelId]: {
|
|
815
|
+
label: simple.data.modelLabel ?? "AI model",
|
|
816
|
+
model: simple.data.model
|
|
817
|
+
}
|
|
818
|
+
},
|
|
819
|
+
defaultModel: modelId
|
|
820
|
+
}
|
|
821
|
+
},
|
|
822
|
+
defaultProvider: providerId,
|
|
823
|
+
...simple.data.execution === void 0 ? {} : { execution: simple.data.execution }
|
|
824
|
+
};
|
|
825
|
+
})();
|
|
826
|
+
const parsed = aiOptionsSchema.safeParse(expanded);
|
|
827
|
+
if (!parsed.success) {
|
|
828
|
+
throw new RangeError("SpotPatch AI configuration is invalid.");
|
|
829
|
+
}
|
|
830
|
+
const validated = parsed.data;
|
|
831
|
+
const limits = resolveLimits(validated.execution?.limits);
|
|
832
|
+
const checks = resolveChecks(validated.execution?.checks, limits.checkTimeoutMs);
|
|
833
|
+
const applyMode = validated.execution?.applyMode ?? "review";
|
|
834
|
+
if (applyMode === "auto" && !Object.values(checks).some((check) => check.required)) {
|
|
835
|
+
throw new RangeError("SpotPatch AI auto mode requires a required check.");
|
|
836
|
+
}
|
|
837
|
+
const providers = resolveProviders(validated.providers);
|
|
838
|
+
if (!(validated.defaultProvider in providers)) {
|
|
839
|
+
throw new RangeError(
|
|
840
|
+
"SpotPatch AI defaultProvider must reference a configured provider."
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
return Object.freeze({
|
|
844
|
+
providers,
|
|
845
|
+
defaultProvider: validated.defaultProvider,
|
|
846
|
+
execution: Object.freeze({
|
|
847
|
+
isolation: "git-worktree",
|
|
848
|
+
applyMode,
|
|
849
|
+
checks,
|
|
850
|
+
limits
|
|
851
|
+
})
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
function createRuntimeAiConfig(options) {
|
|
855
|
+
if (options === false) {
|
|
856
|
+
return Object.freeze({ enabled: false });
|
|
857
|
+
}
|
|
858
|
+
return Object.freeze({
|
|
859
|
+
enabled: true,
|
|
860
|
+
defaultProvider: options.defaultProvider,
|
|
861
|
+
applyMode: options.execution.applyMode,
|
|
862
|
+
providers: Object.freeze(
|
|
863
|
+
Object.values(options.providers).map(
|
|
864
|
+
(provider) => Object.freeze({
|
|
865
|
+
id: provider.id,
|
|
866
|
+
label: provider.label,
|
|
867
|
+
protocol: provider.protocol,
|
|
868
|
+
defaultModel: provider.defaultModel,
|
|
869
|
+
models: Object.freeze(
|
|
870
|
+
Object.values(provider.models).map(
|
|
871
|
+
(model) => Object.freeze({ id: model.id, label: model.label })
|
|
872
|
+
)
|
|
873
|
+
)
|
|
874
|
+
})
|
|
875
|
+
)
|
|
876
|
+
)
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
function assertPositiveBudget(budget) {
|
|
880
|
+
for (const [name, value] of Object.entries(budget)) {
|
|
881
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
882
|
+
throw new RangeError(`SpotPatch budget ${name} must be a positive integer.`);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
function resolveOptions(options = {}, environmentAi) {
|
|
887
|
+
const budget = Object.freeze({
|
|
888
|
+
...DEFAULT_OPTIONS.budget,
|
|
889
|
+
...options.budget
|
|
890
|
+
});
|
|
891
|
+
assertPositiveBudget(budget);
|
|
892
|
+
const maxTargets = options.maxTargets ?? DEFAULT_OPTIONS.maxTargets;
|
|
893
|
+
const locale = options.locale ?? DEFAULT_OPTIONS.locale;
|
|
894
|
+
const editor = options.editor ?? DEFAULT_OPTIONS.editor;
|
|
895
|
+
if (!SPOTPATCH_LOCALE_PREFERENCES.includes(locale)) {
|
|
896
|
+
throw new RangeError("SpotPatch locale must be auto, en-US, or zh-CN.");
|
|
897
|
+
}
|
|
898
|
+
if (!SPOTPATCH_EDITOR_PREFERENCES.includes(editor)) {
|
|
899
|
+
throw new RangeError("SpotPatch editor must be auto, vscode, or cursor.");
|
|
900
|
+
}
|
|
901
|
+
if (!Number.isSafeInteger(maxTargets) || maxTargets < 1 || maxTargets > MAX_ANNOTATION_TARGETS) {
|
|
902
|
+
throw new RangeError(
|
|
903
|
+
`SpotPatch maxTargets must be an integer between 1 and ${String(MAX_ANNOTATION_TARGETS)}.`
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
const resolved = {
|
|
907
|
+
enabled: options.enabled ?? DEFAULT_OPTIONS.enabled,
|
|
908
|
+
include: Object.freeze([...options.include ?? DEFAULT_OPTIONS.include]),
|
|
909
|
+
exclude: Object.freeze([...options.exclude ?? DEFAULT_OPTIONS.exclude]),
|
|
910
|
+
editor,
|
|
911
|
+
redact: options.redact ?? DEFAULT_OPTIONS.redact,
|
|
912
|
+
budget,
|
|
913
|
+
shortcut: options.shortcut ?? DEFAULT_OPTIONS.shortcut,
|
|
914
|
+
allowLan: options.allowLan ?? DEFAULT_OPTIONS.allowLan,
|
|
915
|
+
debug: options.debug ?? DEFAULT_OPTIONS.debug,
|
|
916
|
+
locale,
|
|
917
|
+
maxTargets,
|
|
918
|
+
ai: resolveAiOptions(options.ai ?? environmentAi)
|
|
919
|
+
};
|
|
920
|
+
if (resolved.shortcut.trim().length === 0 || resolved.shortcut.length > 128 || resolved.shortcut.includes("\0")) {
|
|
921
|
+
throw new RangeError("SpotPatch shortcut is invalid.");
|
|
922
|
+
}
|
|
923
|
+
return Object.freeze(resolved);
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// src/registry/source-registry.ts
|
|
927
|
+
import path from "path";
|
|
928
|
+
|
|
929
|
+
// src/registry/source-id.ts
|
|
930
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
931
|
+
var SOURCE_ID_BYTES = 8;
|
|
932
|
+
var createRandomSourceId = () => randomBytes2(SOURCE_ID_BYTES).toString("base64url");
|
|
933
|
+
|
|
934
|
+
// src/registry/source-registry.ts
|
|
935
|
+
function normalizeAbsolutePath(absolutePath) {
|
|
936
|
+
return path.normalize(path.resolve(absolutePath));
|
|
937
|
+
}
|
|
938
|
+
function createSourceRegistry(options = {}) {
|
|
939
|
+
const createId = options.createId ?? createRandomSourceId;
|
|
940
|
+
const pathToId = /* @__PURE__ */ new Map();
|
|
941
|
+
const idToPath = /* @__PURE__ */ new Map();
|
|
942
|
+
return Object.freeze({
|
|
943
|
+
register(absolutePath) {
|
|
944
|
+
const normalizedPath = normalizeAbsolutePath(absolutePath);
|
|
945
|
+
const existingId = pathToId.get(normalizedPath);
|
|
946
|
+
if (existingId !== void 0) {
|
|
947
|
+
return existingId;
|
|
948
|
+
}
|
|
949
|
+
let fileId = createId();
|
|
950
|
+
while (idToPath.has(fileId)) {
|
|
951
|
+
fileId = createId();
|
|
952
|
+
}
|
|
953
|
+
pathToId.set(normalizedPath, fileId);
|
|
954
|
+
idToPath.set(fileId, normalizedPath);
|
|
955
|
+
return fileId;
|
|
956
|
+
},
|
|
957
|
+
resolve(fileId) {
|
|
958
|
+
return idToPath.get(fileId);
|
|
959
|
+
},
|
|
960
|
+
clear() {
|
|
961
|
+
pathToId.clear();
|
|
962
|
+
idToPath.clear();
|
|
963
|
+
}
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// src/server/middleware.ts
|
|
968
|
+
import {
|
|
969
|
+
ERROR_CODES as ERROR_CODES9,
|
|
970
|
+
SPOTPATCH_API_BASE,
|
|
971
|
+
SPOTPATCH_ENDPOINTS as SPOTPATCH_ENDPOINTS2,
|
|
972
|
+
SpotPatchError as SpotPatchError9,
|
|
973
|
+
openEditorRequestSchema,
|
|
974
|
+
sourceContextRequestSchema
|
|
975
|
+
} from "@spotpatch/shared";
|
|
976
|
+
|
|
977
|
+
// src/server/agent-http.ts
|
|
978
|
+
import {
|
|
979
|
+
ERROR_CODES as ERROR_CODES6,
|
|
980
|
+
SPOTPATCH_ENDPOINTS,
|
|
981
|
+
SpotPatchError as SpotPatchError6,
|
|
982
|
+
agentCapabilityRequestSchema,
|
|
983
|
+
agentJobActionRequestSchema,
|
|
984
|
+
agentJobCreateRequestSchema,
|
|
985
|
+
agentWorkspaceHealthRequestSchema
|
|
986
|
+
} from "@spotpatch/shared";
|
|
987
|
+
|
|
988
|
+
// src/server/agent-request.ts
|
|
989
|
+
import { realpath as realpath3 } from "fs/promises";
|
|
990
|
+
import path4 from "path";
|
|
991
|
+
import {
|
|
992
|
+
ERROR_CODES as ERROR_CODES4,
|
|
993
|
+
SpotPatchError as SpotPatchError4
|
|
994
|
+
} from "@spotpatch/shared";
|
|
995
|
+
|
|
996
|
+
// src/server/source-context.ts
|
|
997
|
+
import { readFile, realpath as realpath2 } from "fs/promises";
|
|
998
|
+
import path3 from "path";
|
|
999
|
+
import {
|
|
1000
|
+
ERROR_CODES as ERROR_CODES3,
|
|
1001
|
+
SpotPatchError as SpotPatchError3
|
|
1002
|
+
} from "@spotpatch/shared";
|
|
1003
|
+
|
|
1004
|
+
// src/server/extract-code-context.ts
|
|
1005
|
+
import {
|
|
1006
|
+
parseSync,
|
|
1007
|
+
Visitor
|
|
1008
|
+
} from "oxc-parser";
|
|
1009
|
+
function isComponentName(name) {
|
|
1010
|
+
return /^[A-Z]/u.test(name);
|
|
1011
|
+
}
|
|
1012
|
+
function unwrapTypeExpression(expression) {
|
|
1013
|
+
switch (expression.type) {
|
|
1014
|
+
case "TSAsExpression":
|
|
1015
|
+
case "TSSatisfiesExpression":
|
|
1016
|
+
case "TSTypeAssertion":
|
|
1017
|
+
case "TSNonNullExpression":
|
|
1018
|
+
case "TSInstantiationExpression":
|
|
1019
|
+
return unwrapTypeExpression(expression.expression);
|
|
1020
|
+
default:
|
|
1021
|
+
return expression;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
function calleeName(expression) {
|
|
1025
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1026
|
+
if (unwrapped.type === "Identifier") {
|
|
1027
|
+
return unwrapped.name;
|
|
1028
|
+
}
|
|
1029
|
+
if (unwrapped.type === "MemberExpression" && !unwrapped.computed) {
|
|
1030
|
+
return unwrapped.property.type === "Identifier" ? unwrapped.property.name : void 0;
|
|
1031
|
+
}
|
|
1032
|
+
return void 0;
|
|
1033
|
+
}
|
|
1034
|
+
function isFunctionExpression(expression) {
|
|
1035
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1036
|
+
return unwrapped.type === "ArrowFunctionExpression" || unwrapped.type === "FunctionExpression";
|
|
1037
|
+
}
|
|
1038
|
+
function isSupportedComponentInitializer(expression) {
|
|
1039
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1040
|
+
if (isFunctionExpression(unwrapped)) {
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
if (unwrapped.type !== "CallExpression") {
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
const name = calleeName(unwrapped.callee);
|
|
1047
|
+
if (name !== "memo" && name !== "forwardRef") {
|
|
1048
|
+
return false;
|
|
1049
|
+
}
|
|
1050
|
+
const firstArgument = unwrapped.arguments[0];
|
|
1051
|
+
return firstArgument !== void 0 && firstArgument.type !== "SpreadElement" && (isFunctionExpression(firstArgument) || isSupportedComponentInitializer(firstArgument));
|
|
1052
|
+
}
|
|
1053
|
+
function variableComponent(node) {
|
|
1054
|
+
if (node.id.type !== "Identifier" || !isComponentName(node.id.name) || node.init === null || !isSupportedComponentInitializer(node.init)) {
|
|
1055
|
+
return void 0;
|
|
1056
|
+
}
|
|
1057
|
+
return Object.freeze({ start: node.start, end: node.end, name: node.id.name });
|
|
1058
|
+
}
|
|
1059
|
+
function functionComponent(node) {
|
|
1060
|
+
return node.id !== null && isComponentName(node.id.name) && node.body !== null ? Object.freeze({ start: node.start, end: node.end, name: node.id.name }) : void 0;
|
|
1061
|
+
}
|
|
1062
|
+
function isReactComponentSuperclass(expression) {
|
|
1063
|
+
if (expression === null) {
|
|
1064
|
+
return false;
|
|
1065
|
+
}
|
|
1066
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1067
|
+
if (unwrapped.type === "Identifier") {
|
|
1068
|
+
return unwrapped.name === "Component" || unwrapped.name === "PureComponent";
|
|
1069
|
+
}
|
|
1070
|
+
return unwrapped.type === "MemberExpression" && !unwrapped.computed && unwrapped.object.type === "Identifier" && unwrapped.object.name === "React" && (unwrapped.property.name === "Component" || unwrapped.property.name === "PureComponent");
|
|
1071
|
+
}
|
|
1072
|
+
function classComponent(node) {
|
|
1073
|
+
return node.id !== null && isComponentName(node.id.name) && isReactComponentSuperclass(node.superClass) ? Object.freeze({ start: node.start, end: node.end, name: node.id.name }) : void 0;
|
|
1074
|
+
}
|
|
1075
|
+
function selectedOffset(source, line, column) {
|
|
1076
|
+
const lines = source.split(/\r?\n/u);
|
|
1077
|
+
if (line < 1 || line > lines.length) {
|
|
1078
|
+
return void 0;
|
|
1079
|
+
}
|
|
1080
|
+
const lineStart = lines.slice(0, line - 1).reduce((total, value) => total + value.length + 1, 0);
|
|
1081
|
+
const lineLength = lines[line - 1]?.length ?? 0;
|
|
1082
|
+
return lineStart + Math.min(Math.max(0, column - 1), lineLength);
|
|
1083
|
+
}
|
|
1084
|
+
function findComponentSpan(options) {
|
|
1085
|
+
const offset = selectedOffset(options.source, options.line, options.column);
|
|
1086
|
+
if (offset === void 0) {
|
|
1087
|
+
return void 0;
|
|
1088
|
+
}
|
|
1089
|
+
let parseResult;
|
|
1090
|
+
try {
|
|
1091
|
+
parseResult = parseSync(options.sourcePath, options.source, {
|
|
1092
|
+
sourceType: "module"
|
|
1093
|
+
});
|
|
1094
|
+
} catch {
|
|
1095
|
+
return void 0;
|
|
1096
|
+
}
|
|
1097
|
+
if (parseResult.errors.length > 0) {
|
|
1098
|
+
return void 0;
|
|
1099
|
+
}
|
|
1100
|
+
const jsxNodes = [];
|
|
1101
|
+
const components = [];
|
|
1102
|
+
const visitor = new Visitor({
|
|
1103
|
+
JSXElement(node) {
|
|
1104
|
+
jsxNodes.push(node);
|
|
1105
|
+
},
|
|
1106
|
+
JSXFragment(node) {
|
|
1107
|
+
jsxNodes.push(node);
|
|
1108
|
+
},
|
|
1109
|
+
FunctionDeclaration(node) {
|
|
1110
|
+
const candidate = functionComponent(node);
|
|
1111
|
+
if (candidate !== void 0) {
|
|
1112
|
+
components.push(candidate);
|
|
1113
|
+
}
|
|
1114
|
+
},
|
|
1115
|
+
VariableDeclarator(node) {
|
|
1116
|
+
const candidate = variableComponent(node);
|
|
1117
|
+
if (candidate !== void 0) {
|
|
1118
|
+
components.push(candidate);
|
|
1119
|
+
}
|
|
1120
|
+
},
|
|
1121
|
+
ClassDeclaration(node) {
|
|
1122
|
+
const candidate = classComponent(node);
|
|
1123
|
+
if (candidate !== void 0) {
|
|
1124
|
+
components.push(candidate);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
});
|
|
1128
|
+
visitor.visit(parseResult.program);
|
|
1129
|
+
const selectedJsx = jsxNodes.filter((node) => node.start <= offset && node.end >= offset).sort((left, right) => left.end - left.start - (right.end - right.start))[0];
|
|
1130
|
+
if (selectedJsx === void 0) {
|
|
1131
|
+
return void 0;
|
|
1132
|
+
}
|
|
1133
|
+
return components.filter(
|
|
1134
|
+
(component) => component.start <= selectedJsx.start && component.end >= selectedJsx.end
|
|
1135
|
+
).sort((left, right) => left.end - left.start - (right.end - right.start))[0];
|
|
1136
|
+
}
|
|
1137
|
+
function lineAtOffset(source, offset) {
|
|
1138
|
+
let line = 1;
|
|
1139
|
+
for (let index = 0; index < offset; index += 1) {
|
|
1140
|
+
if (source[index] === "\n") {
|
|
1141
|
+
line += 1;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return line;
|
|
1145
|
+
}
|
|
1146
|
+
function componentRange(source, component) {
|
|
1147
|
+
return Object.freeze({
|
|
1148
|
+
startLine: lineAtOffset(source, component.start),
|
|
1149
|
+
endLine: lineAtOffset(source, Math.max(component.start, component.end - 1))
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
function truncateSelectedLine(line, column, maxCharacters) {
|
|
1153
|
+
if (line.length <= maxCharacters) {
|
|
1154
|
+
return line;
|
|
1155
|
+
}
|
|
1156
|
+
if (maxCharacters === 1) {
|
|
1157
|
+
return "\u2026";
|
|
1158
|
+
}
|
|
1159
|
+
const contentCharacters = maxCharacters - 2;
|
|
1160
|
+
const desiredStart = Math.max(0, column - 1 - Math.floor(contentCharacters / 2));
|
|
1161
|
+
const start = Math.min(desiredStart, line.length - contentCharacters);
|
|
1162
|
+
const end = start + contentCharacters;
|
|
1163
|
+
return `${start > 0 ? "\u2026" : ""}${line.slice(start, end)}${end < line.length ? "\u2026" : ""}`.slice(
|
|
1164
|
+
0,
|
|
1165
|
+
maxCharacters
|
|
1166
|
+
);
|
|
1167
|
+
}
|
|
1168
|
+
function boundedRange(lines, selectedLine, column, initialStart, initialEnd, maxCharacters) {
|
|
1169
|
+
let startLine = initialStart;
|
|
1170
|
+
let endLine = initialEnd;
|
|
1171
|
+
let excerpt = lines.slice(startLine - 1, endLine).join("\n");
|
|
1172
|
+
while (excerpt.length > maxCharacters && startLine < endLine) {
|
|
1173
|
+
if (endLine - selectedLine >= selectedLine - startLine) {
|
|
1174
|
+
endLine -= 1;
|
|
1175
|
+
} else {
|
|
1176
|
+
startLine += 1;
|
|
1177
|
+
}
|
|
1178
|
+
excerpt = lines.slice(startLine - 1, endLine).join("\n");
|
|
1179
|
+
}
|
|
1180
|
+
if (excerpt.length > maxCharacters) {
|
|
1181
|
+
startLine = selectedLine;
|
|
1182
|
+
endLine = selectedLine;
|
|
1183
|
+
excerpt = truncateSelectedLine(
|
|
1184
|
+
lines[selectedLine - 1] ?? "",
|
|
1185
|
+
column,
|
|
1186
|
+
maxCharacters
|
|
1187
|
+
);
|
|
1188
|
+
}
|
|
1189
|
+
return Object.freeze({ startLine, endLine, excerpt });
|
|
1190
|
+
}
|
|
1191
|
+
function nearbyContext(options) {
|
|
1192
|
+
const lines = options.source.split(/\r?\n/u);
|
|
1193
|
+
const initialStart = Math.max(1, options.line - Math.floor(options.maxLines / 2));
|
|
1194
|
+
const initialEnd = Math.min(lines.length, initialStart + options.maxLines - 1);
|
|
1195
|
+
const startLine = Math.max(1, initialEnd - options.maxLines + 1);
|
|
1196
|
+
const bounded = boundedRange(
|
|
1197
|
+
lines,
|
|
1198
|
+
options.line,
|
|
1199
|
+
options.column,
|
|
1200
|
+
startLine,
|
|
1201
|
+
initialEnd,
|
|
1202
|
+
options.maxCharacters
|
|
1203
|
+
);
|
|
1204
|
+
return Object.freeze({
|
|
1205
|
+
relativePath: options.relativePath,
|
|
1206
|
+
language: options.language,
|
|
1207
|
+
startLine: bounded.startLine,
|
|
1208
|
+
endLine: bounded.endLine,
|
|
1209
|
+
excerpt: bounded.excerpt,
|
|
1210
|
+
boundary: "nearby-lines"
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
function extractCodeContext(options) {
|
|
1214
|
+
const component = findComponentSpan(options);
|
|
1215
|
+
if (component !== void 0) {
|
|
1216
|
+
const range = componentRange(options.source, component);
|
|
1217
|
+
const lineCount = range.endLine - range.startLine + 1;
|
|
1218
|
+
const excerpt = options.source.split(/\r?\n/u).slice(range.startLine - 1, range.endLine).join("\n");
|
|
1219
|
+
if (lineCount <= options.maxLines && excerpt.length <= options.maxCharacters) {
|
|
1220
|
+
return Object.freeze({
|
|
1221
|
+
relativePath: options.relativePath,
|
|
1222
|
+
language: options.language,
|
|
1223
|
+
startLine: range.startLine,
|
|
1224
|
+
endLine: range.endLine,
|
|
1225
|
+
excerpt,
|
|
1226
|
+
boundary: "component"
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
return nearbyContext(options);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// src/server/source-file.ts
|
|
1234
|
+
import { realpath, stat } from "fs/promises";
|
|
1235
|
+
import path2 from "path";
|
|
1236
|
+
import { ERROR_CODES as ERROR_CODES2, SpotPatchError as SpotPatchError2 } from "@spotpatch/shared";
|
|
1237
|
+
|
|
1238
|
+
// src/server/constants.ts
|
|
1239
|
+
var MAX_REQUEST_BODY_BYTES = 32 * 1024;
|
|
1240
|
+
var MAX_AGENT_REQUEST_BODY_BYTES = 256 * 1024;
|
|
1241
|
+
var MAX_SOURCE_FILE_BYTES = 1024 * 1024;
|
|
1242
|
+
|
|
1243
|
+
// src/server/source-file.ts
|
|
1244
|
+
var ALLOWED_EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx"]);
|
|
1245
|
+
function isMissingFileError(error) {
|
|
1246
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
|
|
1247
|
+
}
|
|
1248
|
+
async function assertInsideRoot(root, candidate) {
|
|
1249
|
+
let realRoot;
|
|
1250
|
+
let realCandidate;
|
|
1251
|
+
try {
|
|
1252
|
+
[realRoot, realCandidate] = await Promise.all([
|
|
1253
|
+
realpath(root),
|
|
1254
|
+
realpath(candidate)
|
|
1255
|
+
]);
|
|
1256
|
+
} catch (error) {
|
|
1257
|
+
if (isMissingFileError(error)) {
|
|
1258
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_NOT_FOUND, void 0, {
|
|
1259
|
+
cause: error
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
throw error;
|
|
1263
|
+
}
|
|
1264
|
+
const relative = path2.relative(realRoot, realCandidate);
|
|
1265
|
+
const outside = relative.startsWith(`..${path2.sep}`) || relative === ".." || path2.isAbsolute(relative);
|
|
1266
|
+
if (outside) {
|
|
1267
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_OUTSIDE_ROOT);
|
|
1268
|
+
}
|
|
1269
|
+
return realCandidate;
|
|
1270
|
+
}
|
|
1271
|
+
async function resolveSourceFile(options) {
|
|
1272
|
+
const registeredPath = options.registry.resolve(options.fileId);
|
|
1273
|
+
if (registeredPath === void 0) {
|
|
1274
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_NOT_FOUND);
|
|
1275
|
+
}
|
|
1276
|
+
const sourcePath = await assertInsideRoot(options.root, registeredPath);
|
|
1277
|
+
if (!ALLOWED_EXTENSIONS.has(path2.extname(sourcePath).toLowerCase())) {
|
|
1278
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_NOT_FOUND);
|
|
1279
|
+
}
|
|
1280
|
+
let sourceStat;
|
|
1281
|
+
try {
|
|
1282
|
+
sourceStat = await stat(sourcePath);
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
if (isMissingFileError(error)) {
|
|
1285
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_NOT_FOUND, void 0, {
|
|
1286
|
+
cause: error
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
throw error;
|
|
1290
|
+
}
|
|
1291
|
+
if (!sourceStat.isFile()) {
|
|
1292
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_NOT_FOUND);
|
|
1293
|
+
}
|
|
1294
|
+
if (sourceStat.size > MAX_SOURCE_FILE_BYTES) {
|
|
1295
|
+
throw new SpotPatchError2(ERROR_CODES2.SOURCE_TOO_LARGE);
|
|
1296
|
+
}
|
|
1297
|
+
return sourcePath;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// src/server/source-context.ts
|
|
1301
|
+
function toDisplayPath(root, sourcePath) {
|
|
1302
|
+
return path3.relative(root, sourcePath).split(path3.sep).join("/");
|
|
1303
|
+
}
|
|
1304
|
+
async function readSourceContext(options) {
|
|
1305
|
+
const sourcePath = await resolveSourceFile({
|
|
1306
|
+
fileId: options.request.fileId,
|
|
1307
|
+
registry: options.registry,
|
|
1308
|
+
root: options.root
|
|
1309
|
+
});
|
|
1310
|
+
let source;
|
|
1311
|
+
try {
|
|
1312
|
+
source = await readFile(sourcePath, "utf8");
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
1315
|
+
throw new SpotPatchError3(ERROR_CODES3.SOURCE_NOT_FOUND, void 0, {
|
|
1316
|
+
cause: error
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
throw error;
|
|
1320
|
+
}
|
|
1321
|
+
const lines = source.split(/\r?\n/);
|
|
1322
|
+
if (options.request.line > lines.length) {
|
|
1323
|
+
throw new SpotPatchError3(ERROR_CODES3.INVALID_REQUEST);
|
|
1324
|
+
}
|
|
1325
|
+
const extension = path3.extname(sourcePath).toLowerCase();
|
|
1326
|
+
return extractCodeContext({
|
|
1327
|
+
source,
|
|
1328
|
+
sourcePath,
|
|
1329
|
+
relativePath: toDisplayPath(await realpath2(options.root), sourcePath),
|
|
1330
|
+
language: extension === ".tsx" ? "tsx" : "jsx",
|
|
1331
|
+
line: options.request.line,
|
|
1332
|
+
column: options.request.column,
|
|
1333
|
+
maxLines: Math.min(options.request.maxLines, options.maxLines),
|
|
1334
|
+
maxCharacters: options.maxCharacters
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// src/server/agent-request.ts
|
|
1339
|
+
function compactSourceRef(source) {
|
|
1340
|
+
return Object.freeze({
|
|
1341
|
+
origin: source.origin,
|
|
1342
|
+
confidence: source.confidence,
|
|
1343
|
+
...source.fileId === void 0 ? {} : { fileId: source.fileId },
|
|
1344
|
+
...source.relativePath === void 0 ? {} : { relativePath: source.relativePath },
|
|
1345
|
+
...source.line === void 0 ? {} : { line: source.line },
|
|
1346
|
+
...source.column === void 0 ? {} : { column: source.column }
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
async function authorizeSourceRef(source, registry, root) {
|
|
1350
|
+
const markerOrigin = source.origin === "jsx-host" || source.origin === "dom-ancestor";
|
|
1351
|
+
if (markerOrigin && (source.fileId === void 0 || source.line === void 0 || source.column === void 0)) {
|
|
1352
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1353
|
+
}
|
|
1354
|
+
if (source.fileId === void 0) {
|
|
1355
|
+
if (source.origin === "none" && source.relativePath !== void 0) {
|
|
1356
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1357
|
+
}
|
|
1358
|
+
return compactSourceRef(source);
|
|
1359
|
+
}
|
|
1360
|
+
const sourcePath = await resolveSourceFile({
|
|
1361
|
+
fileId: source.fileId,
|
|
1362
|
+
registry,
|
|
1363
|
+
root
|
|
1364
|
+
});
|
|
1365
|
+
const relativePath = path4.relative(await realpath3(root), sourcePath).split(path4.sep).join("/");
|
|
1366
|
+
if (source.relativePath !== void 0 && source.relativePath !== relativePath) {
|
|
1367
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1368
|
+
}
|
|
1369
|
+
return Object.freeze({
|
|
1370
|
+
...compactSourceRef(source),
|
|
1371
|
+
relativePath
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
function freezeMatchedRule(rule) {
|
|
1375
|
+
return Object.freeze({
|
|
1376
|
+
selector: rule.selector,
|
|
1377
|
+
declarations: rule.declarations,
|
|
1378
|
+
...rule.source === void 0 ? {} : { source: rule.source },
|
|
1379
|
+
...rule.media === void 0 ? {} : { media: rule.media }
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
function targetIdentity(target) {
|
|
1383
|
+
const source = target.source;
|
|
1384
|
+
if (source.fileId !== void 0 && source.line !== void 0 && source.column !== void 0) {
|
|
1385
|
+
return `source:${source.fileId}:${String(source.line)}:${String(source.column)}`;
|
|
1386
|
+
}
|
|
1387
|
+
return [
|
|
1388
|
+
"element",
|
|
1389
|
+
source.origin,
|
|
1390
|
+
source.relativePath ?? "",
|
|
1391
|
+
target.element.selector,
|
|
1392
|
+
target.element.sanitizedHtml
|
|
1393
|
+
].join("\0");
|
|
1394
|
+
}
|
|
1395
|
+
async function authorizeTarget(target, input) {
|
|
1396
|
+
const source = await authorizeSourceRef(target.source, input.registry, input.root);
|
|
1397
|
+
const reactSourceInput = target.react.source;
|
|
1398
|
+
const reactSource = reactSourceInput === void 0 ? void 0 : await authorizeSourceRef(reactSourceInput, input.registry, input.root);
|
|
1399
|
+
const marker = source.fileId === void 0 || source.line === void 0 || source.column === void 0 ? void 0 : Object.freeze({
|
|
1400
|
+
fileId: source.fileId,
|
|
1401
|
+
line: source.line,
|
|
1402
|
+
column: source.column,
|
|
1403
|
+
maxLines: input.options.budget.maxCodeLines
|
|
1404
|
+
});
|
|
1405
|
+
if (marker === void 0 && target.code !== void 0) {
|
|
1406
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1407
|
+
}
|
|
1408
|
+
const code = marker === void 0 ? void 0 : await readSourceContext({
|
|
1409
|
+
request: marker,
|
|
1410
|
+
registry: input.registry,
|
|
1411
|
+
root: input.root,
|
|
1412
|
+
maxCharacters: input.options.budget.codeCharacters,
|
|
1413
|
+
maxLines: input.options.budget.maxCodeLines
|
|
1414
|
+
});
|
|
1415
|
+
if (target.code !== void 0 && target.code.relativePath !== code?.relativePath) {
|
|
1416
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1417
|
+
}
|
|
1418
|
+
return Object.freeze({
|
|
1419
|
+
instruction: target.instruction,
|
|
1420
|
+
source,
|
|
1421
|
+
react: Object.freeze({
|
|
1422
|
+
supported: target.react.supported,
|
|
1423
|
+
...target.react.version === void 0 ? {} : { version: target.react.version },
|
|
1424
|
+
...target.react.componentName === void 0 ? {} : { componentName: target.react.componentName },
|
|
1425
|
+
componentStack: Object.freeze([...target.react.componentStack]),
|
|
1426
|
+
...reactSource === void 0 ? {} : { source: reactSource }
|
|
1427
|
+
}),
|
|
1428
|
+
element: Object.freeze({
|
|
1429
|
+
tagName: target.element.tagName,
|
|
1430
|
+
selector: target.element.selector,
|
|
1431
|
+
sanitizedHtml: target.element.sanitizedHtml,
|
|
1432
|
+
...target.element.textPreview === void 0 ? {} : { textPreview: target.element.textPreview },
|
|
1433
|
+
...target.element.role === void 0 ? {} : { role: target.element.role },
|
|
1434
|
+
rect: Object.freeze({ ...target.element.rect })
|
|
1435
|
+
}),
|
|
1436
|
+
styles: Object.freeze({
|
|
1437
|
+
classNames: Object.freeze([...target.styles.classNames]),
|
|
1438
|
+
...target.styles.inlineStyle === void 0 ? {} : { inlineStyle: target.styles.inlineStyle },
|
|
1439
|
+
matchedRules: Object.freeze(target.styles.matchedRules.map(freezeMatchedRule)),
|
|
1440
|
+
computed: Object.freeze({ ...target.styles.computed }),
|
|
1441
|
+
warnings: Object.freeze([...target.styles.warnings])
|
|
1442
|
+
}),
|
|
1443
|
+
...code === void 0 ? {} : { code: Object.freeze({ ...code }) },
|
|
1444
|
+
warnings: Object.freeze([...target.warnings])
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
async function authorizeAgentJobRequest(input) {
|
|
1448
|
+
const requestedTargets = input.request.annotation.targets;
|
|
1449
|
+
if (requestedTargets.length > input.options.maxTargets) {
|
|
1450
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1451
|
+
}
|
|
1452
|
+
const identities = requestedTargets.map(targetIdentity);
|
|
1453
|
+
if (new Set(identities).size !== identities.length) {
|
|
1454
|
+
throw new SpotPatchError4(ERROR_CODES4.INVALID_REQUEST);
|
|
1455
|
+
}
|
|
1456
|
+
const targets = Object.freeze(
|
|
1457
|
+
await Promise.all(requestedTargets.map((target) => authorizeTarget(target, input)))
|
|
1458
|
+
);
|
|
1459
|
+
const annotation = Object.freeze({
|
|
1460
|
+
schemaVersion: 3,
|
|
1461
|
+
id: input.request.annotation.id,
|
|
1462
|
+
locale: input.request.annotation.locale,
|
|
1463
|
+
page: Object.freeze({ ...input.request.annotation.page }),
|
|
1464
|
+
targets,
|
|
1465
|
+
createdAt: input.request.annotation.createdAt
|
|
1466
|
+
});
|
|
1467
|
+
return Object.freeze({
|
|
1468
|
+
annotation,
|
|
1469
|
+
providerProfileId: input.request.providerProfileId,
|
|
1470
|
+
modelProfileId: input.request.modelProfileId,
|
|
1471
|
+
providerDataConsent: true,
|
|
1472
|
+
workingTreeMode: input.request.workingTreeMode
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// src/server/request-body.ts
|
|
1477
|
+
import { ERROR_CODES as ERROR_CODES5, SpotPatchError as SpotPatchError5 } from "@spotpatch/shared";
|
|
1478
|
+
function isJsonContentType(value) {
|
|
1479
|
+
return value?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
|
|
1480
|
+
}
|
|
1481
|
+
async function readJsonRequestBody(request, maximumBytes = MAX_REQUEST_BODY_BYTES) {
|
|
1482
|
+
if (!isJsonContentType(request.headers["content-type"])) {
|
|
1483
|
+
throw new SpotPatchError5(ERROR_CODES5.INVALID_REQUEST);
|
|
1484
|
+
}
|
|
1485
|
+
const declaredLength = Number(request.headers["content-length"]);
|
|
1486
|
+
if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
|
|
1487
|
+
throw new SpotPatchError5(ERROR_CODES5.INVALID_REQUEST);
|
|
1488
|
+
}
|
|
1489
|
+
const chunks = [];
|
|
1490
|
+
let byteLength = 0;
|
|
1491
|
+
let exceededLimit = false;
|
|
1492
|
+
for await (const rawChunk of request) {
|
|
1493
|
+
const chunk = rawChunk;
|
|
1494
|
+
if (typeof chunk !== "string" && !(chunk instanceof Uint8Array)) {
|
|
1495
|
+
throw new SpotPatchError5(ERROR_CODES5.INVALID_REQUEST);
|
|
1496
|
+
}
|
|
1497
|
+
const buffer = Buffer.from(chunk);
|
|
1498
|
+
byteLength += buffer.byteLength;
|
|
1499
|
+
if (byteLength > maximumBytes) {
|
|
1500
|
+
exceededLimit = true;
|
|
1501
|
+
continue;
|
|
1502
|
+
}
|
|
1503
|
+
chunks.push(buffer);
|
|
1504
|
+
}
|
|
1505
|
+
if (exceededLimit || byteLength === 0) {
|
|
1506
|
+
throw new SpotPatchError5(ERROR_CODES5.INVALID_REQUEST);
|
|
1507
|
+
}
|
|
1508
|
+
try {
|
|
1509
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1510
|
+
} catch (error) {
|
|
1511
|
+
throw new SpotPatchError5(ERROR_CODES5.INVALID_REQUEST, void 0, {
|
|
1512
|
+
cause: error
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/server/agent-http.ts
|
|
1518
|
+
var AGENT_JOB_ID_PATTERN = /^[A-Za-z0-9_-]{22,128}$/;
|
|
1519
|
+
var AGENT_JOB_ACTIONS = /* @__PURE__ */ new Set([
|
|
1520
|
+
"events",
|
|
1521
|
+
"result",
|
|
1522
|
+
"cancel",
|
|
1523
|
+
"apply",
|
|
1524
|
+
"revert"
|
|
1525
|
+
]);
|
|
1526
|
+
var EVENT_STREAM_END_STATUSES = /* @__PURE__ */ new Set([
|
|
1527
|
+
"awaiting-review",
|
|
1528
|
+
"applied",
|
|
1529
|
+
"completed",
|
|
1530
|
+
"cancelled",
|
|
1531
|
+
"reverted",
|
|
1532
|
+
"failed"
|
|
1533
|
+
]);
|
|
1534
|
+
function matchAgentRequestPath(path6) {
|
|
1535
|
+
if (path6 === SPOTPATCH_ENDPOINTS.agentCapability) {
|
|
1536
|
+
return Object.freeze({ kind: "capability" });
|
|
1537
|
+
}
|
|
1538
|
+
if (path6 === SPOTPATCH_ENDPOINTS.agentWorkspaceHealth) {
|
|
1539
|
+
return Object.freeze({ kind: "workspace-health" });
|
|
1540
|
+
}
|
|
1541
|
+
if (path6 === SPOTPATCH_ENDPOINTS.agentJobs) {
|
|
1542
|
+
return Object.freeze({ kind: "create-job" });
|
|
1543
|
+
}
|
|
1544
|
+
const prefix = `${SPOTPATCH_ENDPOINTS.agentJobs}/`;
|
|
1545
|
+
if (!path6.startsWith(prefix)) {
|
|
1546
|
+
return void 0;
|
|
1547
|
+
}
|
|
1548
|
+
const segments = path6.slice(prefix.length).split("/");
|
|
1549
|
+
const jobId = segments[0];
|
|
1550
|
+
const action = segments[1];
|
|
1551
|
+
if (segments.length !== 2 || jobId === void 0 || !AGENT_JOB_ID_PATTERN.test(jobId) || action === void 0 || !AGENT_JOB_ACTIONS.has(action)) {
|
|
1552
|
+
return void 0;
|
|
1553
|
+
}
|
|
1554
|
+
return Object.freeze({
|
|
1555
|
+
kind: "job-action",
|
|
1556
|
+
action,
|
|
1557
|
+
jobId
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
function requireAgentManager(options) {
|
|
1561
|
+
if (options.agentManager === void 0 || options.options.ai === false) {
|
|
1562
|
+
throw new SpotPatchError6(ERROR_CODES6.AI_DISABLED);
|
|
1563
|
+
}
|
|
1564
|
+
return options.agentManager;
|
|
1565
|
+
}
|
|
1566
|
+
function writeNdjsonEvent(response, event) {
|
|
1567
|
+
response.write(`${JSON.stringify(event)}
|
|
1568
|
+
`);
|
|
1569
|
+
}
|
|
1570
|
+
function streamAgentJobEvents(response, manager, jobId) {
|
|
1571
|
+
const events = manager.events(jobId);
|
|
1572
|
+
const current = manager.result(jobId).snapshot;
|
|
1573
|
+
response.statusCode = 200;
|
|
1574
|
+
response.setHeader("Cache-Control", "no-store");
|
|
1575
|
+
response.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
|
|
1576
|
+
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
1577
|
+
for (const event of events) {
|
|
1578
|
+
writeNdjsonEvent(response, event);
|
|
1579
|
+
}
|
|
1580
|
+
if (EVENT_STREAM_END_STATUSES.has(current.status)) {
|
|
1581
|
+
response.end();
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
let settled = false;
|
|
1585
|
+
let unsubscribe = () => void 0;
|
|
1586
|
+
const heartbeat = setInterval(() => {
|
|
1587
|
+
if (!settled) {
|
|
1588
|
+
response.write("\n");
|
|
1589
|
+
}
|
|
1590
|
+
}, 15e3);
|
|
1591
|
+
heartbeat.unref();
|
|
1592
|
+
const cleanup = () => {
|
|
1593
|
+
if (settled) {
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
settled = true;
|
|
1597
|
+
clearInterval(heartbeat);
|
|
1598
|
+
unsubscribe();
|
|
1599
|
+
};
|
|
1600
|
+
unsubscribe = manager.subscribe(jobId, (event) => {
|
|
1601
|
+
if (settled) {
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
writeNdjsonEvent(response, event);
|
|
1605
|
+
if (event.type === "snapshot" && EVENT_STREAM_END_STATUSES.has(event.data.snapshot.status)) {
|
|
1606
|
+
cleanup();
|
|
1607
|
+
response.end();
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
response.once("close", cleanup);
|
|
1611
|
+
response.once("error", cleanup);
|
|
1612
|
+
}
|
|
1613
|
+
async function handleCapability(request, response, options, writeSuccess) {
|
|
1614
|
+
if (request.method !== "POST") {
|
|
1615
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1616
|
+
}
|
|
1617
|
+
const parsed = agentCapabilityRequestSchema.safeParse(
|
|
1618
|
+
await readJsonRequestBody(request)
|
|
1619
|
+
);
|
|
1620
|
+
if (!parsed.success) {
|
|
1621
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1622
|
+
}
|
|
1623
|
+
const controller = new AbortController();
|
|
1624
|
+
const abort = () => {
|
|
1625
|
+
controller.abort("agent-capability-client-disconnected");
|
|
1626
|
+
};
|
|
1627
|
+
response.once("close", abort);
|
|
1628
|
+
try {
|
|
1629
|
+
const data = await requireAgentManager(options).probe(
|
|
1630
|
+
parsed.data,
|
|
1631
|
+
controller.signal
|
|
1632
|
+
);
|
|
1633
|
+
writeSuccess(response, 200, data);
|
|
1634
|
+
} finally {
|
|
1635
|
+
response.removeListener("close", abort);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
async function handleCreateJob(request, response, options, writeSuccess) {
|
|
1639
|
+
if (request.method !== "POST") {
|
|
1640
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1641
|
+
}
|
|
1642
|
+
const parsed = agentJobCreateRequestSchema.safeParse(
|
|
1643
|
+
await readJsonRequestBody(request, MAX_AGENT_REQUEST_BODY_BYTES)
|
|
1644
|
+
);
|
|
1645
|
+
if (!parsed.success) {
|
|
1646
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1647
|
+
}
|
|
1648
|
+
const authorizedRequest = await authorizeAgentJobRequest({
|
|
1649
|
+
request: parsed.data,
|
|
1650
|
+
options: options.options,
|
|
1651
|
+
registry: options.registry,
|
|
1652
|
+
root: options.root
|
|
1653
|
+
});
|
|
1654
|
+
const data = requireAgentManager(options).create(authorizedRequest);
|
|
1655
|
+
writeSuccess(response, 202, data);
|
|
1656
|
+
}
|
|
1657
|
+
async function handleWorkspaceHealth(request, response, options, writeSuccess) {
|
|
1658
|
+
if (request.method !== "POST") {
|
|
1659
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1660
|
+
}
|
|
1661
|
+
const parsed = agentWorkspaceHealthRequestSchema.safeParse(
|
|
1662
|
+
await readJsonRequestBody(request)
|
|
1663
|
+
);
|
|
1664
|
+
if (!parsed.success) {
|
|
1665
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1666
|
+
}
|
|
1667
|
+
const controller = new AbortController();
|
|
1668
|
+
const abort = () => {
|
|
1669
|
+
controller.abort("agent-workspace-health-client-disconnected");
|
|
1670
|
+
};
|
|
1671
|
+
response.once("close", abort);
|
|
1672
|
+
try {
|
|
1673
|
+
const data = await requireAgentManager(options).workspaceHealth(controller.signal);
|
|
1674
|
+
writeSuccess(response, 200, data);
|
|
1675
|
+
} finally {
|
|
1676
|
+
response.removeListener("close", abort);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
async function handleJobAction(request, response, options, route, writeSuccess) {
|
|
1680
|
+
const manager = requireAgentManager(options);
|
|
1681
|
+
if (request.method !== "POST") {
|
|
1682
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1683
|
+
}
|
|
1684
|
+
const parsed = agentJobActionRequestSchema.safeParse(
|
|
1685
|
+
await readJsonRequestBody(request)
|
|
1686
|
+
);
|
|
1687
|
+
if (!parsed.success) {
|
|
1688
|
+
throw new SpotPatchError6(ERROR_CODES6.INVALID_REQUEST);
|
|
1689
|
+
}
|
|
1690
|
+
if (route.action === "events") {
|
|
1691
|
+
streamAgentJobEvents(response, manager, route.jobId);
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1694
|
+
if (route.action === "result") {
|
|
1695
|
+
writeSuccess(response, 200, manager.result(route.jobId));
|
|
1696
|
+
return;
|
|
1697
|
+
}
|
|
1698
|
+
const data = route.action === "cancel" ? manager.cancel(route.jobId) : route.action === "apply" ? await manager.apply(route.jobId) : await manager.revert(route.jobId);
|
|
1699
|
+
writeSuccess(response, 200, data);
|
|
1700
|
+
}
|
|
1701
|
+
async function handleAgentRequest(request, response, options, route, writeSuccess) {
|
|
1702
|
+
if (route.kind === "capability") {
|
|
1703
|
+
await handleCapability(request, response, options, writeSuccess);
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
if (route.kind === "create-job") {
|
|
1707
|
+
await handleCreateJob(request, response, options, writeSuccess);
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
if (route.kind === "workspace-health") {
|
|
1711
|
+
await handleWorkspaceHealth(request, response, options, writeSuccess);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
await handleJobAction(request, response, options, route, writeSuccess);
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
// src/server/editor.ts
|
|
1718
|
+
import { spawn } from "child_process";
|
|
1719
|
+
import launchEditor from "launch-editor";
|
|
1720
|
+
var EDITOR_STARTUP_GRACE_MS = 300;
|
|
1721
|
+
function normalizedEditorEnvironment(environment) {
|
|
1722
|
+
return [
|
|
1723
|
+
environment.TERM_PROGRAM,
|
|
1724
|
+
environment.VSCODE_GIT_ASKPASS_NODE,
|
|
1725
|
+
environment.VSCODE_GIT_ASKPASS_MAIN,
|
|
1726
|
+
environment.GIT_ASKPASS
|
|
1727
|
+
].filter((value) => typeof value === "string").join("\n").replaceAll("\\", "/").toLowerCase();
|
|
1728
|
+
}
|
|
1729
|
+
function detectIntegratedEditor(environment) {
|
|
1730
|
+
const signature = normalizedEditorEnvironment(environment);
|
|
1731
|
+
if (signature === "cursor" || signature.includes("/cursor")) {
|
|
1732
|
+
return "cursor";
|
|
1733
|
+
}
|
|
1734
|
+
if (signature === "vscode" || signature.includes("visual studio code") || /(^|\/)(code|code-insiders)(\.exe)?($|\/)/u.test(signature)) {
|
|
1735
|
+
return "vscode";
|
|
1736
|
+
}
|
|
1737
|
+
return void 0;
|
|
1738
|
+
}
|
|
1739
|
+
function editorCommand(editor) {
|
|
1740
|
+
return editor === "cursor" ? "cursor" : "code";
|
|
1741
|
+
}
|
|
1742
|
+
var DEFAULT_DEPENDENCIES2 = Object.freeze({
|
|
1743
|
+
environment: process.env,
|
|
1744
|
+
fallbackLauncher: launchEditor,
|
|
1745
|
+
processSpawner: (command, arguments_, options) => spawn(command, [...arguments_], options),
|
|
1746
|
+
startupGraceMs: EDITOR_STARTUP_GRACE_MS
|
|
1747
|
+
});
|
|
1748
|
+
function createEditorLauncher(dependencies = DEFAULT_DEPENDENCIES2) {
|
|
1749
|
+
return (target, configuredEditor) => {
|
|
1750
|
+
const integratedEditor = detectIntegratedEditor(dependencies.environment);
|
|
1751
|
+
const resolvedEditor = configuredEditor === "auto" ? integratedEditor : configuredEditor;
|
|
1752
|
+
return new Promise((resolve, reject) => {
|
|
1753
|
+
let settled = false;
|
|
1754
|
+
const settle = (error, editor = resolvedEditor ?? "auto") => {
|
|
1755
|
+
if (settled) {
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1758
|
+
settled = true;
|
|
1759
|
+
clearTimeout(startupTimer);
|
|
1760
|
+
if (error === void 0) {
|
|
1761
|
+
resolve(editor);
|
|
1762
|
+
} else {
|
|
1763
|
+
reject(error);
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
const startupTimer = setTimeout(settle, dependencies.startupGraceMs);
|
|
1767
|
+
const rejectStartup = () => {
|
|
1768
|
+
settle(new Error("The configured editor could not be started."));
|
|
1769
|
+
};
|
|
1770
|
+
try {
|
|
1771
|
+
if (resolvedEditor === void 0) {
|
|
1772
|
+
dependencies.fallbackLauncher(target, void 0, rejectStartup);
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
const child = dependencies.processSpawner(
|
|
1776
|
+
editorCommand(resolvedEditor),
|
|
1777
|
+
["--goto", target],
|
|
1778
|
+
{
|
|
1779
|
+
env: dependencies.environment,
|
|
1780
|
+
stdio: "ignore",
|
|
1781
|
+
windowsHide: true
|
|
1782
|
+
}
|
|
1783
|
+
);
|
|
1784
|
+
child.once("error", rejectStartup);
|
|
1785
|
+
child.once("exit", (code, signal) => {
|
|
1786
|
+
if (code === 0) {
|
|
1787
|
+
settle(void 0, resolvedEditor);
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
if (code !== null || signal !== null) {
|
|
1791
|
+
rejectStartup();
|
|
1792
|
+
}
|
|
1793
|
+
});
|
|
1794
|
+
} catch {
|
|
1795
|
+
rejectStartup();
|
|
1796
|
+
}
|
|
1797
|
+
});
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
var launchConfiguredEditor = createEditorLauncher();
|
|
1801
|
+
|
|
1802
|
+
// src/server/request-security.ts
|
|
1803
|
+
import { timingSafeEqual } from "crypto";
|
|
1804
|
+
import { isIP } from "net";
|
|
1805
|
+
import { ERROR_CODES as ERROR_CODES7, SPOTPATCH_TOKEN_HEADER, SpotPatchError as SpotPatchError7 } from "@spotpatch/shared";
|
|
1806
|
+
function getSingleHeader(request, name) {
|
|
1807
|
+
const value = request.headers[name.toLowerCase()];
|
|
1808
|
+
return Array.isArray(value) ? value[0] : value;
|
|
1809
|
+
}
|
|
1810
|
+
function tokensMatch(actual, expected) {
|
|
1811
|
+
if (actual === void 0) {
|
|
1812
|
+
return false;
|
|
1813
|
+
}
|
|
1814
|
+
const actualBytes = Buffer.from(actual);
|
|
1815
|
+
const expectedBytes = Buffer.from(expected);
|
|
1816
|
+
return actualBytes.byteLength === expectedBytes.byteLength && timingSafeEqual(actualBytes, expectedBytes);
|
|
1817
|
+
}
|
|
1818
|
+
function isLoopbackHostname(hostname) {
|
|
1819
|
+
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
1820
|
+
if (normalized === "localhost" || normalized.endsWith(".localhost")) {
|
|
1821
|
+
return true;
|
|
1822
|
+
}
|
|
1823
|
+
if (normalized === "::1") {
|
|
1824
|
+
return true;
|
|
1825
|
+
}
|
|
1826
|
+
if (isIP(normalized) === 4) {
|
|
1827
|
+
return normalized.split(".")[0] === "127";
|
|
1828
|
+
}
|
|
1829
|
+
return normalized.startsWith("::ffff:127.");
|
|
1830
|
+
}
|
|
1831
|
+
function parseHost(value) {
|
|
1832
|
+
try {
|
|
1833
|
+
return new URL(`http://${value}`);
|
|
1834
|
+
} catch {
|
|
1835
|
+
return void 0;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
function parseOrigin(value) {
|
|
1839
|
+
try {
|
|
1840
|
+
const origin = new URL(value);
|
|
1841
|
+
if (origin.protocol !== "http:" && origin.protocol !== "https:" || origin.username.length > 0 || origin.password.length > 0 || origin.origin === "null") {
|
|
1842
|
+
return void 0;
|
|
1843
|
+
}
|
|
1844
|
+
return origin;
|
|
1845
|
+
} catch {
|
|
1846
|
+
return void 0;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
function assertRequestAuthorized(request, options) {
|
|
1850
|
+
const actualToken = getSingleHeader(request, SPOTPATCH_TOKEN_HEADER);
|
|
1851
|
+
if (!tokensMatch(actualToken, options.sessionToken)) {
|
|
1852
|
+
throw new SpotPatchError7(ERROR_CODES7.INVALID_TOKEN);
|
|
1853
|
+
}
|
|
1854
|
+
const hostHeader = getSingleHeader(request, "host");
|
|
1855
|
+
const originHeader = getSingleHeader(request, "origin");
|
|
1856
|
+
const host = hostHeader === void 0 ? void 0 : parseHost(hostHeader);
|
|
1857
|
+
const origin = originHeader === void 0 ? void 0 : parseOrigin(originHeader);
|
|
1858
|
+
if (host === void 0 || origin === void 0) {
|
|
1859
|
+
throw new SpotPatchError7(ERROR_CODES7.ORIGIN_NOT_ALLOWED);
|
|
1860
|
+
}
|
|
1861
|
+
const hostIsLoopback = isLoopbackHostname(host.hostname);
|
|
1862
|
+
const originIsLoopback = isLoopbackHostname(origin.hostname);
|
|
1863
|
+
if (!options.allowLan) {
|
|
1864
|
+
if (!hostIsLoopback || !originIsLoopback) {
|
|
1865
|
+
throw new SpotPatchError7(ERROR_CODES7.ORIGIN_NOT_ALLOWED);
|
|
1866
|
+
}
|
|
1867
|
+
return;
|
|
1868
|
+
}
|
|
1869
|
+
if (!originIsLoopback && origin.host.toLowerCase() !== host.host.toLowerCase()) {
|
|
1870
|
+
throw new SpotPatchError7(ERROR_CODES7.ORIGIN_NOT_ALLOWED);
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// src/server/runtime-bootstrap.ts
|
|
1875
|
+
import {
|
|
1876
|
+
ERROR_CODES as ERROR_CODES8,
|
|
1877
|
+
SpotPatchError as SpotPatchError8,
|
|
1878
|
+
runtimeBootstrapRequestSchema,
|
|
1879
|
+
runtimeConfigSchema
|
|
1880
|
+
} from "@spotpatch/shared";
|
|
1881
|
+
function getSingleHeader2(request, name) {
|
|
1882
|
+
const value = request.headers[name.toLowerCase()];
|
|
1883
|
+
return Array.isArray(value) ? value[0] : value;
|
|
1884
|
+
}
|
|
1885
|
+
function resolveRuntimeBootstrapOptions(options) {
|
|
1886
|
+
let expectedOrigin;
|
|
1887
|
+
try {
|
|
1888
|
+
expectedOrigin = new URL(options.expectedOrigin);
|
|
1889
|
+
} catch {
|
|
1890
|
+
throw new TypeError("The SpotPatch bootstrap origin is invalid.");
|
|
1891
|
+
}
|
|
1892
|
+
if (expectedOrigin.origin !== options.expectedOrigin || expectedOrigin.protocol !== "http:" || !isLoopbackHostname(expectedOrigin.hostname)) {
|
|
1893
|
+
throw new TypeError("The SpotPatch bootstrap origin must be a loopback origin.");
|
|
1894
|
+
}
|
|
1895
|
+
const parsedConfig = runtimeConfigSchema.safeParse(options.runtimeConfig);
|
|
1896
|
+
if (!parsedConfig.success) {
|
|
1897
|
+
throw new TypeError("The SpotPatch Runtime configuration is invalid.");
|
|
1898
|
+
}
|
|
1899
|
+
return Object.freeze({
|
|
1900
|
+
expectedOrigin: expectedOrigin.origin,
|
|
1901
|
+
runtimeConfig: parsedConfig.data
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
function assertRuntimeBootstrapRequest(request, expectedOrigin) {
|
|
1905
|
+
const contentType = getSingleHeader2(request, "content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
1906
|
+
if (request.method !== "POST" || contentType !== "application/json") {
|
|
1907
|
+
throw new SpotPatchError8(ERROR_CODES8.INVALID_REQUEST);
|
|
1908
|
+
}
|
|
1909
|
+
const host = getSingleHeader2(request, "host");
|
|
1910
|
+
let hostIsLoopback = false;
|
|
1911
|
+
if (host !== void 0) {
|
|
1912
|
+
try {
|
|
1913
|
+
hostIsLoopback = isLoopbackHostname(new URL(`http://${host}`).hostname);
|
|
1914
|
+
} catch {
|
|
1915
|
+
hostIsLoopback = false;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
if (!hostIsLoopback || getSingleHeader2(request, "origin") !== expectedOrigin || getSingleHeader2(request, "sec-fetch-site") !== "same-origin") {
|
|
1919
|
+
throw new SpotPatchError8(ERROR_CODES8.ORIGIN_NOT_ALLOWED);
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
async function readRuntimeBootstrap(request, options) {
|
|
1923
|
+
assertRuntimeBootstrapRequest(request, options.expectedOrigin);
|
|
1924
|
+
const parsedBody = runtimeBootstrapRequestSchema.safeParse(
|
|
1925
|
+
await readJsonRequestBody(request)
|
|
1926
|
+
);
|
|
1927
|
+
if (!parsedBody.success) {
|
|
1928
|
+
throw new SpotPatchError8(ERROR_CODES8.INVALID_REQUEST);
|
|
1929
|
+
}
|
|
1930
|
+
return options.runtimeConfig;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// src/server/middleware.ts
|
|
1934
|
+
var STATUS_BY_ERROR = Object.freeze({
|
|
1935
|
+
[ERROR_CODES9.INVALID_REQUEST]: 400,
|
|
1936
|
+
[ERROR_CODES9.INVALID_TOKEN]: 401,
|
|
1937
|
+
[ERROR_CODES9.ORIGIN_NOT_ALLOWED]: 403,
|
|
1938
|
+
[ERROR_CODES9.SOURCE_NOT_FOUND]: 404,
|
|
1939
|
+
[ERROR_CODES9.SOURCE_OUTSIDE_ROOT]: 403,
|
|
1940
|
+
[ERROR_CODES9.SOURCE_TOO_LARGE]: 413,
|
|
1941
|
+
[ERROR_CODES9.EDITOR_OPEN_FAILED]: 500,
|
|
1942
|
+
[ERROR_CODES9.AI_DISABLED]: 404,
|
|
1943
|
+
[ERROR_CODES9.PROVIDER_NOT_CONFIGURED]: 503,
|
|
1944
|
+
[ERROR_CODES9.PROVIDER_AUTH_FAILED]: 502,
|
|
1945
|
+
[ERROR_CODES9.PROVIDER_PROTOCOL_UNSUPPORTED]: 502,
|
|
1946
|
+
[ERROR_CODES9.MODEL_NOT_ALLOWED]: 400,
|
|
1947
|
+
[ERROR_CODES9.MODEL_TOOL_CALL_UNSUPPORTED]: 422,
|
|
1948
|
+
[ERROR_CODES9.PROVIDER_RATE_LIMITED]: 429,
|
|
1949
|
+
[ERROR_CODES9.AGENT_BUSY]: 409,
|
|
1950
|
+
[ERROR_CODES9.AGENT_LIMIT_EXCEEDED]: 413,
|
|
1951
|
+
[ERROR_CODES9.AGENT_CANCELLED]: 409,
|
|
1952
|
+
[ERROR_CODES9.WORKTREE_DIRTY]: 409,
|
|
1953
|
+
[ERROR_CODES9.WORKTREE_NOT_REPOSITORY]: 409,
|
|
1954
|
+
[ERROR_CODES9.WORKTREE_OPERATION_IN_PROGRESS]: 409,
|
|
1955
|
+
[ERROR_CODES9.WORKTREE_CONFLICTED]: 409,
|
|
1956
|
+
[ERROR_CODES9.WORKTREE_LOCAL_CHANGES_TOO_LARGE]: 413,
|
|
1957
|
+
[ERROR_CODES9.WORKTREE_UNTRACKED_UNSUPPORTED]: 409,
|
|
1958
|
+
[ERROR_CODES9.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]: 409,
|
|
1959
|
+
[ERROR_CODES9.TOOL_DENIED]: 403,
|
|
1960
|
+
[ERROR_CODES9.TOOL_INPUT_INVALID]: 422,
|
|
1961
|
+
[ERROR_CODES9.TOOL_ARGUMENTS_INVALID]: 422,
|
|
1962
|
+
[ERROR_CODES9.TOOL_CALL_ID_CONFLICT]: 422,
|
|
1963
|
+
[ERROR_CODES9.TOOL_PATH_DENIED]: 403,
|
|
1964
|
+
[ERROR_CODES9.PATCH_REJECTED]: 422,
|
|
1965
|
+
[ERROR_CODES9.VALIDATION_FAILED]: 422,
|
|
1966
|
+
[ERROR_CODES9.APPLY_CONFLICT]: 409,
|
|
1967
|
+
[ERROR_CODES9.INTERNAL_ERROR]: 500
|
|
1968
|
+
});
|
|
1969
|
+
var PUBLIC_MESSAGES = Object.freeze({
|
|
1970
|
+
[ERROR_CODES9.INVALID_REQUEST]: "The request is invalid.",
|
|
1971
|
+
[ERROR_CODES9.INVALID_TOKEN]: "The session token is invalid.",
|
|
1972
|
+
[ERROR_CODES9.ORIGIN_NOT_ALLOWED]: "The request origin is not allowed.",
|
|
1973
|
+
[ERROR_CODES9.SOURCE_NOT_FOUND]: "The source file is unavailable.",
|
|
1974
|
+
[ERROR_CODES9.SOURCE_OUTSIDE_ROOT]: "The source file is outside the project root.",
|
|
1975
|
+
[ERROR_CODES9.SOURCE_TOO_LARGE]: "The source file exceeds the size limit.",
|
|
1976
|
+
[ERROR_CODES9.EDITOR_OPEN_FAILED]: "The editor request could not be started.",
|
|
1977
|
+
[ERROR_CODES9.AI_DISABLED]: "AI execution is not enabled.",
|
|
1978
|
+
[ERROR_CODES9.PROVIDER_NOT_CONFIGURED]: "The AI provider is unavailable.",
|
|
1979
|
+
[ERROR_CODES9.PROVIDER_AUTH_FAILED]: "The AI provider rejected authentication.",
|
|
1980
|
+
[ERROR_CODES9.PROVIDER_PROTOCOL_UNSUPPORTED]: "The AI provider protocol is unsupported.",
|
|
1981
|
+
[ERROR_CODES9.MODEL_NOT_ALLOWED]: "The selected model is not allowed.",
|
|
1982
|
+
[ERROR_CODES9.MODEL_TOOL_CALL_UNSUPPORTED]: "The selected model cannot run SpotPatch tools.",
|
|
1983
|
+
[ERROR_CODES9.PROVIDER_RATE_LIMITED]: "The AI provider is rate limited.",
|
|
1984
|
+
[ERROR_CODES9.AGENT_BUSY]: "Another Agent job is already running.",
|
|
1985
|
+
[ERROR_CODES9.AGENT_LIMIT_EXCEEDED]: "The Agent job exceeded a safety limit.",
|
|
1986
|
+
[ERROR_CODES9.AGENT_CANCELLED]: "The Agent job was cancelled.",
|
|
1987
|
+
[ERROR_CODES9.WORKTREE_DIRTY]: "Local changes require explicit inclusion consent.",
|
|
1988
|
+
[ERROR_CODES9.WORKTREE_NOT_REPOSITORY]: "The project root is not a Git repository.",
|
|
1989
|
+
[ERROR_CODES9.WORKTREE_OPERATION_IN_PROGRESS]: "A Git operation is currently in progress.",
|
|
1990
|
+
[ERROR_CODES9.WORKTREE_CONFLICTED]: "The local workspace contains unresolved merge conflicts.",
|
|
1991
|
+
[ERROR_CODES9.WORKTREE_LOCAL_CHANGES_TOO_LARGE]: "The local workspace exceeds the safe isolation size limit.",
|
|
1992
|
+
[ERROR_CODES9.WORKTREE_UNTRACKED_UNSUPPORTED]: "An untracked path cannot be isolated safely.",
|
|
1993
|
+
[ERROR_CODES9.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]: "The local workspace state cannot be isolated safely.",
|
|
1994
|
+
[ERROR_CODES9.TOOL_DENIED]: "The Agent tool request was denied.",
|
|
1995
|
+
[ERROR_CODES9.TOOL_INPUT_INVALID]: "The Agent tool input was invalid.",
|
|
1996
|
+
[ERROR_CODES9.TOOL_ARGUMENTS_INVALID]: "The Agent tool arguments are invalid.",
|
|
1997
|
+
[ERROR_CODES9.TOOL_CALL_ID_CONFLICT]: "A tool call ID conflicts within one Agent turn.",
|
|
1998
|
+
[ERROR_CODES9.TOOL_PATH_DENIED]: "The Agent tool path was denied.",
|
|
1999
|
+
[ERROR_CODES9.PATCH_REJECTED]: "The proposed patch was rejected.",
|
|
2000
|
+
[ERROR_CODES9.VALIDATION_FAILED]: "The proposed change failed validation.",
|
|
2001
|
+
[ERROR_CODES9.APPLY_CONFLICT]: "The change conflicts with the current worktree.",
|
|
2002
|
+
[ERROR_CODES9.INTERNAL_ERROR]: "The request could not be completed."
|
|
2003
|
+
});
|
|
2004
|
+
function writeJson(response, status, payload) {
|
|
2005
|
+
response.statusCode = status;
|
|
2006
|
+
response.setHeader("Cache-Control", "no-store");
|
|
2007
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
2008
|
+
response.end(JSON.stringify(payload));
|
|
2009
|
+
}
|
|
2010
|
+
function asSpotPatchError(error) {
|
|
2011
|
+
return error instanceof SpotPatchError9 ? error : new SpotPatchError9(ERROR_CODES9.INTERNAL_ERROR, void 0, { cause: error });
|
|
2012
|
+
}
|
|
2013
|
+
function writeError(response, error, logger) {
|
|
2014
|
+
const normalized = asSpotPatchError(error);
|
|
2015
|
+
if (normalized.code === ERROR_CODES9.INTERNAL_ERROR) {
|
|
2016
|
+
logger?.warn("[spotpatch:server] Internal request failure.");
|
|
2017
|
+
}
|
|
2018
|
+
writeJson(response, STATUS_BY_ERROR[normalized.code], {
|
|
2019
|
+
ok: false,
|
|
2020
|
+
error: {
|
|
2021
|
+
code: normalized.code,
|
|
2022
|
+
message: PUBLIC_MESSAGES[normalized.code]
|
|
2023
|
+
}
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
function requestPath(request) {
|
|
2027
|
+
try {
|
|
2028
|
+
return new URL(request.url ?? "/", "http://spotpatch.invalid").pathname;
|
|
2029
|
+
} catch {
|
|
2030
|
+
return "";
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
async function handleSourceContext(request, options) {
|
|
2034
|
+
const parsed = sourceContextRequestSchema.safeParse(
|
|
2035
|
+
await readJsonRequestBody(request)
|
|
2036
|
+
);
|
|
2037
|
+
if (!parsed.success) {
|
|
2038
|
+
throw new SpotPatchError9(ERROR_CODES9.INVALID_REQUEST);
|
|
2039
|
+
}
|
|
2040
|
+
return readSourceContext({
|
|
2041
|
+
request: parsed.data,
|
|
2042
|
+
registry: options.registry,
|
|
2043
|
+
root: options.root,
|
|
2044
|
+
maxCharacters: options.options.budget.codeCharacters,
|
|
2045
|
+
maxLines: options.options.budget.maxCodeLines
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
async function handleOpenEditor(request, options) {
|
|
2049
|
+
const parsed = openEditorRequestSchema.safeParse(await readJsonRequestBody(request));
|
|
2050
|
+
if (!parsed.success) {
|
|
2051
|
+
throw new SpotPatchError9(ERROR_CODES9.INVALID_REQUEST);
|
|
2052
|
+
}
|
|
2053
|
+
const body = parsed.data;
|
|
2054
|
+
const sourcePath = await resolveSourceFile({
|
|
2055
|
+
fileId: body.fileId,
|
|
2056
|
+
registry: options.registry,
|
|
2057
|
+
root: options.root
|
|
2058
|
+
});
|
|
2059
|
+
const target = `${sourcePath}:${String(body.line)}:${String(body.column)}`;
|
|
2060
|
+
const editorLauncher = options.editorLauncher ?? launchConfiguredEditor;
|
|
2061
|
+
try {
|
|
2062
|
+
const editor = await editorLauncher(target, options.options.editor);
|
|
2063
|
+
return Object.freeze({ editor });
|
|
2064
|
+
} catch (error) {
|
|
2065
|
+
options.logger?.warn(
|
|
2066
|
+
`[spotpatch:server] ${options.options.editor === "auto" ? "The detected editor" : options.options.editor} rejected an editor request.`
|
|
2067
|
+
);
|
|
2068
|
+
throw new SpotPatchError9(ERROR_CODES9.EDITOR_OPEN_FAILED, void 0, {
|
|
2069
|
+
cause: error
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
function createSpotPatchMiddleware(options) {
|
|
2074
|
+
const bootstrap = options.bootstrap === void 0 ? void 0 : resolveRuntimeBootstrapOptions(options.bootstrap);
|
|
2075
|
+
return (request, response, next) => {
|
|
2076
|
+
const path6 = requestPath(request);
|
|
2077
|
+
const agentRoute = matchAgentRequestPath(path6);
|
|
2078
|
+
if (path6 !== SPOTPATCH_ENDPOINTS2.sourceContext && path6 !== SPOTPATCH_ENDPOINTS2.openEditor && agentRoute === void 0 && !path6.startsWith(`${SPOTPATCH_API_BASE}/`)) {
|
|
2079
|
+
next();
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
const handle = async () => {
|
|
2083
|
+
if (path6 === SPOTPATCH_ENDPOINTS2.bootstrap && bootstrap !== void 0) {
|
|
2084
|
+
const data = await readRuntimeBootstrap(
|
|
2085
|
+
request,
|
|
2086
|
+
bootstrap
|
|
2087
|
+
);
|
|
2088
|
+
writeJson(response, 200, { ok: true, data });
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
assertRequestAuthorized(request, {
|
|
2092
|
+
allowLan: options.options.allowLan,
|
|
2093
|
+
sessionToken: options.session.token
|
|
2094
|
+
});
|
|
2095
|
+
if (path6 === SPOTPATCH_ENDPOINTS2.sourceContext) {
|
|
2096
|
+
if (request.method !== "POST") {
|
|
2097
|
+
throw new SpotPatchError9(ERROR_CODES9.INVALID_REQUEST);
|
|
2098
|
+
}
|
|
2099
|
+
const data = await handleSourceContext(request, options);
|
|
2100
|
+
writeJson(response, 200, { ok: true, data });
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
if (path6 === SPOTPATCH_ENDPOINTS2.openEditor) {
|
|
2104
|
+
if (request.method !== "POST") {
|
|
2105
|
+
throw new SpotPatchError9(ERROR_CODES9.INVALID_REQUEST);
|
|
2106
|
+
}
|
|
2107
|
+
const data = await handleOpenEditor(request, options);
|
|
2108
|
+
writeJson(response, 200, { ok: true, data });
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
if (agentRoute === void 0) {
|
|
2112
|
+
throw new SpotPatchError9(ERROR_CODES9.INVALID_REQUEST);
|
|
2113
|
+
}
|
|
2114
|
+
await handleAgentRequest(
|
|
2115
|
+
request,
|
|
2116
|
+
response,
|
|
2117
|
+
options,
|
|
2118
|
+
agentRoute,
|
|
2119
|
+
(target, status, data) => {
|
|
2120
|
+
writeJson(target, status, { ok: true, data });
|
|
2121
|
+
}
|
|
2122
|
+
);
|
|
2123
|
+
};
|
|
2124
|
+
void handle().catch((error) => {
|
|
2125
|
+
writeError(response, error, options.logger);
|
|
2126
|
+
});
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
// src/server/source-registration.ts
|
|
2131
|
+
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
2132
|
+
import { lstat, realpath as realpath4 } from "fs/promises";
|
|
2133
|
+
import path5 from "path";
|
|
2134
|
+
import { createSourceFilter } from "@spotpatch/compiler";
|
|
2135
|
+
import { z as z2 } from "zod";
|
|
2136
|
+
var REGISTRATION_BODY_LIMIT_BYTES = 4096;
|
|
2137
|
+
var REGISTRATION_IDENTITY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/u;
|
|
2138
|
+
var INTERNAL_SECRET_HEADER = "x-spotpatch-internal";
|
|
2139
|
+
var FORBIDDEN_SOURCE_SEGMENTS = /* @__PURE__ */ new Set([".next", "node_modules"]);
|
|
2140
|
+
var registrationRequestSchema = z2.strictObject({
|
|
2141
|
+
epoch: z2.string().regex(REGISTRATION_IDENTITY_PATTERN),
|
|
2142
|
+
resourcePath: z2.string().min(1).max(3072)
|
|
2143
|
+
});
|
|
2144
|
+
function getSingleHeader3(request, name) {
|
|
2145
|
+
const value = request.headers[name.toLowerCase()];
|
|
2146
|
+
return Array.isArray(value) ? value[0] : value;
|
|
2147
|
+
}
|
|
2148
|
+
function identitiesMatch(actual, expected) {
|
|
2149
|
+
if (actual === void 0) {
|
|
2150
|
+
return false;
|
|
2151
|
+
}
|
|
2152
|
+
const actualBytes = Buffer.from(actual);
|
|
2153
|
+
const expectedBytes = Buffer.from(expected);
|
|
2154
|
+
return actualBytes.byteLength === expectedBytes.byteLength && timingSafeEqual2(actualBytes, expectedBytes);
|
|
2155
|
+
}
|
|
2156
|
+
function isWithinRoot(root, candidate) {
|
|
2157
|
+
const relative = path5.relative(root, candidate);
|
|
2158
|
+
return relative === "" || !relative.startsWith(`..${path5.sep}`) && relative !== ".." && !path5.isAbsolute(relative);
|
|
2159
|
+
}
|
|
2160
|
+
function hasForbiddenSegment(root, candidate) {
|
|
2161
|
+
return path5.relative(root, candidate).split(path5.sep).some((segment) => FORBIDDEN_SOURCE_SEGMENTS.has(segment));
|
|
2162
|
+
}
|
|
2163
|
+
function writeJson2(response, statusCode, payload) {
|
|
2164
|
+
const body = JSON.stringify(payload);
|
|
2165
|
+
response.statusCode = statusCode;
|
|
2166
|
+
response.setHeader("Cache-Control", "no-store");
|
|
2167
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
2168
|
+
response.setHeader("Content-Length", Buffer.byteLength(body));
|
|
2169
|
+
response.end(body);
|
|
2170
|
+
}
|
|
2171
|
+
function requestComesFromLoopbackWorker(request) {
|
|
2172
|
+
const host = getSingleHeader3(request, "host");
|
|
2173
|
+
if (host === void 0 || getSingleHeader3(request, "origin") !== void 0) {
|
|
2174
|
+
return false;
|
|
2175
|
+
}
|
|
2176
|
+
try {
|
|
2177
|
+
return isLoopbackHostname(new URL(`http://${host}`).hostname);
|
|
2178
|
+
} catch {
|
|
2179
|
+
return false;
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
async function resolveAuthorizedSource(root, requestedPath, shouldTransform) {
|
|
2183
|
+
if (!path5.isAbsolute(requestedPath) || requestedPath.includes("\0")) {
|
|
2184
|
+
return void 0;
|
|
2185
|
+
}
|
|
2186
|
+
try {
|
|
2187
|
+
const sourceStat = await lstat(requestedPath);
|
|
2188
|
+
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
|
|
2189
|
+
return void 0;
|
|
2190
|
+
}
|
|
2191
|
+
const resolvedPath = await realpath4(requestedPath);
|
|
2192
|
+
if (!isWithinRoot(root, resolvedPath) || hasForbiddenSegment(root, resolvedPath) || !shouldTransform(resolvedPath)) {
|
|
2193
|
+
return void 0;
|
|
2194
|
+
}
|
|
2195
|
+
return resolvedPath;
|
|
2196
|
+
} catch {
|
|
2197
|
+
return void 0;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
async function createSourceRegistrationService(input) {
|
|
2201
|
+
if (!REGISTRATION_IDENTITY_PATTERN.test(input.internalSecret) || !REGISTRATION_IDENTITY_PATTERN.test(input.registryEpoch)) {
|
|
2202
|
+
throw new TypeError("The source registration identity is invalid.");
|
|
2203
|
+
}
|
|
2204
|
+
const root = await realpath4(input.root);
|
|
2205
|
+
const sourceFilter = createSourceFilter(root, input.options);
|
|
2206
|
+
const handler = (request, response) => {
|
|
2207
|
+
const handle = async () => {
|
|
2208
|
+
const contentType = getSingleHeader3(request, "content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
2209
|
+
if (request.method !== "POST" || contentType !== "application/json" || !requestComesFromLoopbackWorker(request) || !identitiesMatch(
|
|
2210
|
+
getSingleHeader3(request, INTERNAL_SECRET_HEADER),
|
|
2211
|
+
input.internalSecret
|
|
2212
|
+
)) {
|
|
2213
|
+
writeJson2(response, 403, { ok: false });
|
|
2214
|
+
return;
|
|
2215
|
+
}
|
|
2216
|
+
const parsed = registrationRequestSchema.safeParse(
|
|
2217
|
+
await readJsonRequestBody(request, REGISTRATION_BODY_LIMIT_BYTES)
|
|
2218
|
+
);
|
|
2219
|
+
if (!parsed.success || parsed.data.epoch !== input.registryEpoch) {
|
|
2220
|
+
writeJson2(response, 400, { ok: false });
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
const sourcePath = await resolveAuthorizedSource(
|
|
2224
|
+
root,
|
|
2225
|
+
parsed.data.resourcePath,
|
|
2226
|
+
(absolutePath) => sourceFilter.shouldTransform(absolutePath, "<")
|
|
2227
|
+
);
|
|
2228
|
+
if (sourcePath === void 0) {
|
|
2229
|
+
writeJson2(response, 403, { ok: false });
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2232
|
+
writeJson2(response, 200, {
|
|
2233
|
+
epoch: input.registryEpoch,
|
|
2234
|
+
fileId: input.registry.register(sourcePath)
|
|
2235
|
+
});
|
|
2236
|
+
};
|
|
2237
|
+
void handle().catch(() => {
|
|
2238
|
+
if (!response.headersSent) {
|
|
2239
|
+
writeJson2(response, 400, { ok: false });
|
|
2240
|
+
} else {
|
|
2241
|
+
response.destroy();
|
|
2242
|
+
}
|
|
2243
|
+
});
|
|
2244
|
+
};
|
|
2245
|
+
return Object.freeze({ handler, root });
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
// src/session/session.ts
|
|
2249
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
2250
|
+
function createSession() {
|
|
2251
|
+
return Object.freeze({
|
|
2252
|
+
token: randomBytes3(16).toString("base64url")
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
// src/transport-options.ts
|
|
2257
|
+
var OPTION_KEYS = Object.freeze([
|
|
2258
|
+
"ai",
|
|
2259
|
+
"allowLan",
|
|
2260
|
+
"budget",
|
|
2261
|
+
"debug",
|
|
2262
|
+
"editor",
|
|
2263
|
+
"enabled",
|
|
2264
|
+
"exclude",
|
|
2265
|
+
"include",
|
|
2266
|
+
"locale",
|
|
2267
|
+
"maxTargets",
|
|
2268
|
+
"redact",
|
|
2269
|
+
"shortcut"
|
|
2270
|
+
]);
|
|
2271
|
+
var BUDGET_KEYS = Object.freeze([
|
|
2272
|
+
"totalCharacters",
|
|
2273
|
+
"domCharacters",
|
|
2274
|
+
"cssCharacters",
|
|
2275
|
+
"codeCharacters",
|
|
2276
|
+
"maxCodeLines",
|
|
2277
|
+
"maxComponentDepth"
|
|
2278
|
+
]);
|
|
2279
|
+
var REGEXP_FLAGS_PATTERN = /^(?!.*(.).*\1)[dgimsuvy]*$/u;
|
|
2280
|
+
function isRecord(value) {
|
|
2281
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2282
|
+
}
|
|
2283
|
+
function hasExactKeys(value, keys) {
|
|
2284
|
+
const actual = Object.keys(value).sort();
|
|
2285
|
+
const expected = [...keys].sort();
|
|
2286
|
+
return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
|
|
2287
|
+
}
|
|
2288
|
+
function serializeFilter(entry) {
|
|
2289
|
+
return typeof entry === "string" ? Object.freeze({ kind: "string", value: entry }) : Object.freeze({
|
|
2290
|
+
flags: entry.flags,
|
|
2291
|
+
kind: "regexp",
|
|
2292
|
+
source: entry.source
|
|
2293
|
+
});
|
|
2294
|
+
}
|
|
2295
|
+
function serializeAiOptions(options) {
|
|
2296
|
+
return Object.freeze({
|
|
2297
|
+
providers: Object.freeze(
|
|
2298
|
+
Object.fromEntries(
|
|
2299
|
+
Object.entries(options.providers).map(([id, provider]) => [
|
|
2300
|
+
id,
|
|
2301
|
+
Object.freeze({
|
|
2302
|
+
type: provider.type,
|
|
2303
|
+
label: provider.label,
|
|
2304
|
+
protocol: provider.protocol,
|
|
2305
|
+
authentication: provider.authentication,
|
|
2306
|
+
baseURL: provider.baseURL,
|
|
2307
|
+
apiKeyEnv: provider.apiKeyEnv,
|
|
2308
|
+
models: Object.freeze(
|
|
2309
|
+
Object.fromEntries(
|
|
2310
|
+
Object.entries(provider.models).map(([modelId, model]) => [
|
|
2311
|
+
modelId,
|
|
2312
|
+
Object.freeze({ label: model.label, model: model.model })
|
|
2313
|
+
])
|
|
2314
|
+
)
|
|
2315
|
+
),
|
|
2316
|
+
defaultModel: provider.defaultModel
|
|
2317
|
+
})
|
|
2318
|
+
])
|
|
2319
|
+
)
|
|
2320
|
+
),
|
|
2321
|
+
defaultProvider: options.defaultProvider,
|
|
2322
|
+
execution: Object.freeze({
|
|
2323
|
+
isolation: options.execution.isolation,
|
|
2324
|
+
applyMode: options.execution.applyMode,
|
|
2325
|
+
checks: Object.freeze(
|
|
2326
|
+
Object.fromEntries(
|
|
2327
|
+
Object.entries(options.execution.checks).map(([id, check]) => [
|
|
2328
|
+
id,
|
|
2329
|
+
Object.freeze({
|
|
2330
|
+
label: check.label,
|
|
2331
|
+
command: check.command,
|
|
2332
|
+
args: check.args,
|
|
2333
|
+
required: check.required,
|
|
2334
|
+
timeoutMs: check.timeoutMs
|
|
2335
|
+
})
|
|
2336
|
+
])
|
|
2337
|
+
)
|
|
2338
|
+
),
|
|
2339
|
+
limits: options.execution.limits
|
|
2340
|
+
})
|
|
2341
|
+
});
|
|
2342
|
+
}
|
|
2343
|
+
function serializeResolvedSpotPatchOptions(options) {
|
|
2344
|
+
return Object.freeze({
|
|
2345
|
+
ai: options.ai === false ? false : serializeAiOptions(options.ai),
|
|
2346
|
+
allowLan: options.allowLan,
|
|
2347
|
+
budget: options.budget,
|
|
2348
|
+
debug: options.debug,
|
|
2349
|
+
editor: options.editor,
|
|
2350
|
+
enabled: options.enabled,
|
|
2351
|
+
exclude: Object.freeze(options.exclude.map(serializeFilter)),
|
|
2352
|
+
include: Object.freeze(options.include.map(serializeFilter)),
|
|
2353
|
+
locale: options.locale,
|
|
2354
|
+
maxTargets: options.maxTargets,
|
|
2355
|
+
redact: options.redact,
|
|
2356
|
+
shortcut: options.shortcut
|
|
2357
|
+
});
|
|
2358
|
+
}
|
|
2359
|
+
function parseFilterList(value) {
|
|
2360
|
+
if (!Array.isArray(value) || value.length > 256) {
|
|
2361
|
+
throw new TypeError("The SpotPatch filter transport is invalid.");
|
|
2362
|
+
}
|
|
2363
|
+
return Object.freeze(
|
|
2364
|
+
value.map((entry) => {
|
|
2365
|
+
if (!isRecord(entry)) {
|
|
2366
|
+
throw new TypeError("The SpotPatch filter transport is invalid.");
|
|
2367
|
+
}
|
|
2368
|
+
if (entry.kind === "string" && hasExactKeys(entry, ["kind", "value"]) && typeof entry.value === "string" && entry.value.length > 0 && entry.value.length <= 1024 && !entry.value.includes("\0")) {
|
|
2369
|
+
return entry.value;
|
|
2370
|
+
}
|
|
2371
|
+
if (entry.kind === "regexp" && hasExactKeys(entry, ["flags", "kind", "source"]) && typeof entry.source === "string" && entry.source.length <= 1024 && typeof entry.flags === "string" && REGEXP_FLAGS_PATTERN.test(entry.flags)) {
|
|
2372
|
+
try {
|
|
2373
|
+
return new RegExp(entry.source, entry.flags);
|
|
2374
|
+
} catch {
|
|
2375
|
+
throw new TypeError("The SpotPatch filter transport is invalid.");
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
throw new TypeError("The SpotPatch filter transport is invalid.");
|
|
2379
|
+
})
|
|
2380
|
+
);
|
|
2381
|
+
}
|
|
2382
|
+
function parseBudget(value) {
|
|
2383
|
+
if (!isRecord(value) || !hasExactKeys(value, BUDGET_KEYS)) {
|
|
2384
|
+
throw new TypeError("The SpotPatch budget transport is invalid.");
|
|
2385
|
+
}
|
|
2386
|
+
const budget = Object.fromEntries(
|
|
2387
|
+
BUDGET_KEYS.map((key) => [key, value[key]])
|
|
2388
|
+
);
|
|
2389
|
+
return Object.freeze(budget);
|
|
2390
|
+
}
|
|
2391
|
+
function parseSerializedSpotPatchOptions(value) {
|
|
2392
|
+
if (!isRecord(value) || !hasExactKeys(value, OPTION_KEYS)) {
|
|
2393
|
+
throw new TypeError("The SpotPatch options transport is invalid.");
|
|
2394
|
+
}
|
|
2395
|
+
if (typeof value.enabled !== "boolean" || typeof value.redact !== "boolean" || typeof value.allowLan !== "boolean" || typeof value.debug !== "boolean" || typeof value.shortcut !== "string" || typeof value.maxTargets !== "number" || typeof value.editor !== "string" || typeof value.locale !== "string" || value.ai !== false && !isRecord(value.ai)) {
|
|
2396
|
+
throw new TypeError("The SpotPatch options transport is invalid.");
|
|
2397
|
+
}
|
|
2398
|
+
try {
|
|
2399
|
+
return resolveOptions({
|
|
2400
|
+
ai: value.ai,
|
|
2401
|
+
allowLan: value.allowLan,
|
|
2402
|
+
budget: parseBudget(value.budget),
|
|
2403
|
+
debug: value.debug,
|
|
2404
|
+
editor: value.editor,
|
|
2405
|
+
enabled: value.enabled,
|
|
2406
|
+
exclude: parseFilterList(value.exclude),
|
|
2407
|
+
include: parseFilterList(value.include),
|
|
2408
|
+
locale: value.locale,
|
|
2409
|
+
maxTargets: value.maxTargets,
|
|
2410
|
+
redact: value.redact,
|
|
2411
|
+
shortcut: value.shortcut
|
|
2412
|
+
});
|
|
2413
|
+
} catch (error) {
|
|
2414
|
+
throw new TypeError("The SpotPatch options transport is invalid.", {
|
|
2415
|
+
cause: error
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
export {
|
|
2420
|
+
DEFAULT_EXCLUDE,
|
|
2421
|
+
DEFAULT_OPTIONS,
|
|
2422
|
+
createAgentJobManager,
|
|
2423
|
+
createRuntimeAiConfig,
|
|
2424
|
+
createSession,
|
|
2425
|
+
createSourceRegistrationService,
|
|
2426
|
+
createSourceRegistry,
|
|
2427
|
+
createSpotPatchMiddleware,
|
|
2428
|
+
isLoopbackHostname,
|
|
2429
|
+
parseSerializedSpotPatchOptions,
|
|
2430
|
+
readJsonRequestBody,
|
|
2431
|
+
readRuntimeBootstrap,
|
|
2432
|
+
resolveCredentialEnvironment,
|
|
2433
|
+
resolveEnvironmentAiConfiguration,
|
|
2434
|
+
resolveOptions,
|
|
2435
|
+
resolveRuntimeBootstrapOptions,
|
|
2436
|
+
serializeResolvedSpotPatchOptions
|
|
2437
|
+
};
|
|
2438
|
+
//# sourceMappingURL=index.js.map
|