@gakr-gakr/diffs 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/README.md +217 -0
- package/api.ts +10 -0
- package/assets/viewer-runtime.js +1888 -0
- package/autobot.plugin.json +218 -0
- package/index.ts +11 -0
- package/package.json +50 -0
- package/runtime-api.ts +1 -0
- package/skills/diffs/SKILL.md +23 -0
- package/src/browser.ts +564 -0
- package/src/config.ts +443 -0
- package/src/http.ts +324 -0
- package/src/language-hints.ts +117 -0
- package/src/pierre-themes.ts +59 -0
- package/src/plugin.ts +73 -0
- package/src/prompt-guidance.ts +7 -0
- package/src/render.ts +557 -0
- package/src/store.ts +387 -0
- package/src/tool.ts +547 -0
- package/src/types.ts +127 -0
- package/src/url.ts +60 -0
- package/src/viewer-assets.ts +103 -0
- package/src/viewer-client.ts +353 -0
- package/src/viewer-payload.ts +94 -0
- package/tsconfig.json +16 -0
package/src/http.ts
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { normalizeLowercaseStringOrEmpty } from "autobot/plugin-sdk/string-coerce-runtime";
|
|
3
|
+
import type { PluginLogger } from "../api.js";
|
|
4
|
+
import { resolveRequestClientIp } from "../runtime-api.js";
|
|
5
|
+
import type { DiffArtifactStore } from "./store.js";
|
|
6
|
+
import { DIFF_ARTIFACT_ID_PATTERN, DIFF_ARTIFACT_TOKEN_PATTERN } from "./types.js";
|
|
7
|
+
import { VIEWER_ASSET_PREFIX, getServedViewerAsset } from "./viewer-assets.js";
|
|
8
|
+
|
|
9
|
+
const VIEW_PREFIX = "/plugins/diffs/view/";
|
|
10
|
+
const VIEWER_MAX_FAILURES_PER_WINDOW = 40;
|
|
11
|
+
const VIEWER_FAILURE_WINDOW_MS = 60_000;
|
|
12
|
+
const VIEWER_LOCKOUT_MS = 60_000;
|
|
13
|
+
const VIEWER_LIMITER_MAX_KEYS = 2_048;
|
|
14
|
+
const VIEWER_CONTENT_SECURITY_POLICY = [
|
|
15
|
+
"default-src 'none'",
|
|
16
|
+
"script-src 'self'",
|
|
17
|
+
"style-src 'unsafe-inline'",
|
|
18
|
+
"img-src 'self' data:",
|
|
19
|
+
"font-src 'self' data:",
|
|
20
|
+
"connect-src 'none'",
|
|
21
|
+
"base-uri 'none'",
|
|
22
|
+
"frame-ancestors 'self'",
|
|
23
|
+
"object-src 'none'",
|
|
24
|
+
].join("; ");
|
|
25
|
+
|
|
26
|
+
export function createDiffsHttpHandler(params: {
|
|
27
|
+
store: DiffArtifactStore;
|
|
28
|
+
logger?: PluginLogger;
|
|
29
|
+
allowRemoteViewer?: boolean;
|
|
30
|
+
trustedProxies?: readonly string[];
|
|
31
|
+
allowRealIpFallback?: boolean;
|
|
32
|
+
resolveAccessConfig?: () => {
|
|
33
|
+
allowRemoteViewer?: boolean;
|
|
34
|
+
trustedProxies?: readonly string[];
|
|
35
|
+
allowRealIpFallback?: boolean;
|
|
36
|
+
};
|
|
37
|
+
}) {
|
|
38
|
+
const viewerFailureLimiter = new ViewerFailureLimiter();
|
|
39
|
+
|
|
40
|
+
return async (req: IncomingMessage, res: ServerResponse): Promise<boolean> => {
|
|
41
|
+
const parsed = parseRequestUrl(req.url);
|
|
42
|
+
if (!parsed) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (parsed.pathname.startsWith(VIEWER_ASSET_PREFIX)) {
|
|
47
|
+
return await serveAsset(req, res, parsed.pathname, params.logger);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (!parsed.pathname.startsWith(VIEW_PREFIX)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const accessConfig = params.resolveAccessConfig?.() ?? {
|
|
55
|
+
allowRemoteViewer: params.allowRemoteViewer,
|
|
56
|
+
trustedProxies: params.trustedProxies,
|
|
57
|
+
allowRealIpFallback: params.allowRealIpFallback,
|
|
58
|
+
};
|
|
59
|
+
const access = resolveViewerAccess(req, {
|
|
60
|
+
trustedProxies: accessConfig.trustedProxies,
|
|
61
|
+
allowRealIpFallback: accessConfig.allowRealIpFallback,
|
|
62
|
+
});
|
|
63
|
+
if (!access.localRequest && accessConfig.allowRemoteViewer !== true) {
|
|
64
|
+
respondText(res, 404, "Diff not found");
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
69
|
+
respondText(res, 405, "Method not allowed");
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (!access.localRequest) {
|
|
74
|
+
const throttled = viewerFailureLimiter.check(access.remoteKey);
|
|
75
|
+
if (!throttled.allowed) {
|
|
76
|
+
res.statusCode = 429;
|
|
77
|
+
setSharedHeaders(res, "text/plain; charset=utf-8");
|
|
78
|
+
res.setHeader("Retry-After", String(Math.max(1, Math.ceil(throttled.retryAfterMs / 1000))));
|
|
79
|
+
res.end("Too Many Requests");
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const pathParts = parsed.pathname.split("/").filter(Boolean);
|
|
85
|
+
const id = pathParts[3];
|
|
86
|
+
const token = pathParts[4];
|
|
87
|
+
if (
|
|
88
|
+
!id ||
|
|
89
|
+
!token ||
|
|
90
|
+
!DIFF_ARTIFACT_ID_PATTERN.test(id) ||
|
|
91
|
+
!DIFF_ARTIFACT_TOKEN_PATTERN.test(token)
|
|
92
|
+
) {
|
|
93
|
+
recordRemoteFailure(viewerFailureLimiter, access);
|
|
94
|
+
respondText(res, 404, "Diff not found");
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const artifact = await params.store.getArtifact(id, token);
|
|
99
|
+
if (!artifact) {
|
|
100
|
+
recordRemoteFailure(viewerFailureLimiter, access);
|
|
101
|
+
respondText(res, 404, "Diff not found or expired");
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const html = await params.store.readHtml(id);
|
|
107
|
+
resetRemoteFailures(viewerFailureLimiter, access);
|
|
108
|
+
res.statusCode = 200;
|
|
109
|
+
setSharedHeaders(res, "text/html; charset=utf-8");
|
|
110
|
+
res.setHeader("content-security-policy", VIEWER_CONTENT_SECURITY_POLICY);
|
|
111
|
+
if (req.method === "HEAD") {
|
|
112
|
+
res.end();
|
|
113
|
+
} else {
|
|
114
|
+
res.end(html);
|
|
115
|
+
}
|
|
116
|
+
return true;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
recordRemoteFailure(viewerFailureLimiter, access);
|
|
119
|
+
params.logger?.warn(`Failed to serve diff artifact ${id}: ${String(error)}`);
|
|
120
|
+
respondText(res, 500, "Failed to load diff");
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function parseRequestUrl(rawUrl?: string): URL | null {
|
|
127
|
+
if (!rawUrl) {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
return new URL(rawUrl, "http://127.0.0.1");
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function serveAsset(
|
|
138
|
+
req: IncomingMessage,
|
|
139
|
+
res: ServerResponse,
|
|
140
|
+
pathname: string,
|
|
141
|
+
logger?: PluginLogger,
|
|
142
|
+
): Promise<boolean> {
|
|
143
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
144
|
+
respondText(res, 405, "Method not allowed");
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
const asset = await getServedViewerAsset(pathname);
|
|
150
|
+
if (!asset) {
|
|
151
|
+
respondText(res, 404, "Asset not found");
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
res.statusCode = 200;
|
|
156
|
+
setSharedHeaders(res, asset.contentType);
|
|
157
|
+
if (req.method === "HEAD") {
|
|
158
|
+
res.end();
|
|
159
|
+
} else {
|
|
160
|
+
res.end(asset.body);
|
|
161
|
+
}
|
|
162
|
+
return true;
|
|
163
|
+
} catch (error) {
|
|
164
|
+
logger?.warn(`Failed to serve diffs asset ${pathname}: ${String(error)}`);
|
|
165
|
+
respondText(res, 500, "Failed to load asset");
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function respondText(res: ServerResponse, statusCode: number, body: string): void {
|
|
171
|
+
res.statusCode = statusCode;
|
|
172
|
+
setSharedHeaders(res, "text/plain; charset=utf-8");
|
|
173
|
+
res.end(body);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function setSharedHeaders(res: ServerResponse, contentType: string): void {
|
|
177
|
+
res.setHeader("cache-control", "no-store, max-age=0");
|
|
178
|
+
res.setHeader("content-type", contentType);
|
|
179
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
180
|
+
res.setHeader("referrer-policy", "no-referrer");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function normalizeRemoteClientKey(remoteAddress: string | undefined): string {
|
|
184
|
+
const normalized = normalizeLowercaseStringOrEmpty(remoteAddress);
|
|
185
|
+
if (!normalized) {
|
|
186
|
+
return "unknown";
|
|
187
|
+
}
|
|
188
|
+
return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function isLoopbackClientIp(clientIp: string): boolean {
|
|
192
|
+
return clientIp === "127.0.0.1" || clientIp === "::1";
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function hasProxyForwardingHints(req: IncomingMessage): boolean {
|
|
196
|
+
const headers = req.headers ?? {};
|
|
197
|
+
return Boolean(
|
|
198
|
+
headers["x-forwarded-for"] ||
|
|
199
|
+
headers["x-real-ip"] ||
|
|
200
|
+
headers.forwarded ||
|
|
201
|
+
headers["x-forwarded-host"] ||
|
|
202
|
+
headers["x-forwarded-proto"],
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function resolveViewerAccess(
|
|
207
|
+
req: IncomingMessage,
|
|
208
|
+
params: {
|
|
209
|
+
trustedProxies?: readonly string[];
|
|
210
|
+
allowRealIpFallback?: boolean;
|
|
211
|
+
},
|
|
212
|
+
): {
|
|
213
|
+
remoteKey: string;
|
|
214
|
+
localRequest: boolean;
|
|
215
|
+
} {
|
|
216
|
+
const proxyHintsPresent = hasProxyForwardingHints(req);
|
|
217
|
+
const clientIp =
|
|
218
|
+
proxyHintsPresent || (params.trustedProxies?.length ?? 0) > 0
|
|
219
|
+
? // Reuse gateway proxy trust rules and fail closed when a trusted proxy hop
|
|
220
|
+
// does not provide usable client-origin headers.
|
|
221
|
+
resolveRequestClientIp(
|
|
222
|
+
req,
|
|
223
|
+
params.trustedProxies ? [...params.trustedProxies] : undefined,
|
|
224
|
+
params.allowRealIpFallback === true,
|
|
225
|
+
)
|
|
226
|
+
: req.socket?.remoteAddress;
|
|
227
|
+
const remoteKey = normalizeRemoteClientKey(clientIp ?? req.socket?.remoteAddress);
|
|
228
|
+
const localRequest =
|
|
229
|
+
!proxyHintsPresent && typeof clientIp === "string" && isLoopbackClientIp(remoteKey);
|
|
230
|
+
return { remoteKey, localRequest };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function recordRemoteFailure(
|
|
234
|
+
limiter: ViewerFailureLimiter,
|
|
235
|
+
access: { remoteKey: string; localRequest: boolean },
|
|
236
|
+
): void {
|
|
237
|
+
if (!access.localRequest) {
|
|
238
|
+
limiter.recordFailure(access.remoteKey);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function resetRemoteFailures(
|
|
243
|
+
limiter: ViewerFailureLimiter,
|
|
244
|
+
access: { remoteKey: string; localRequest: boolean },
|
|
245
|
+
): void {
|
|
246
|
+
if (!access.localRequest) {
|
|
247
|
+
limiter.reset(access.remoteKey);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
type RateLimitCheckResult = {
|
|
252
|
+
allowed: boolean;
|
|
253
|
+
retryAfterMs: number;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
type ViewerFailureState = {
|
|
257
|
+
windowStartMs: number;
|
|
258
|
+
failures: number;
|
|
259
|
+
lockUntilMs: number;
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
class ViewerFailureLimiter {
|
|
263
|
+
private readonly failures = new Map<string, ViewerFailureState>();
|
|
264
|
+
|
|
265
|
+
check(key: string): RateLimitCheckResult {
|
|
266
|
+
this.prune();
|
|
267
|
+
const state = this.failures.get(key);
|
|
268
|
+
if (!state) {
|
|
269
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
270
|
+
}
|
|
271
|
+
const now = Date.now();
|
|
272
|
+
if (state.lockUntilMs > now) {
|
|
273
|
+
return { allowed: false, retryAfterMs: state.lockUntilMs - now };
|
|
274
|
+
}
|
|
275
|
+
if (now - state.windowStartMs >= VIEWER_FAILURE_WINDOW_MS) {
|
|
276
|
+
this.failures.delete(key);
|
|
277
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
278
|
+
}
|
|
279
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
recordFailure(key: string): void {
|
|
283
|
+
this.prune();
|
|
284
|
+
const now = Date.now();
|
|
285
|
+
const current = this.failures.get(key);
|
|
286
|
+
const next =
|
|
287
|
+
!current || now - current.windowStartMs >= VIEWER_FAILURE_WINDOW_MS
|
|
288
|
+
? {
|
|
289
|
+
windowStartMs: now,
|
|
290
|
+
failures: 1,
|
|
291
|
+
lockUntilMs: 0,
|
|
292
|
+
}
|
|
293
|
+
: {
|
|
294
|
+
...current,
|
|
295
|
+
failures: current.failures + 1,
|
|
296
|
+
};
|
|
297
|
+
if (next.failures >= VIEWER_MAX_FAILURES_PER_WINDOW) {
|
|
298
|
+
next.lockUntilMs = now + VIEWER_LOCKOUT_MS;
|
|
299
|
+
}
|
|
300
|
+
this.failures.set(key, next);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
reset(key: string): void {
|
|
304
|
+
this.failures.delete(key);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
private prune(): void {
|
|
308
|
+
if (this.failures.size < VIEWER_LIMITER_MAX_KEYS) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const now = Date.now();
|
|
312
|
+
for (const [key, state] of this.failures) {
|
|
313
|
+
if (state.lockUntilMs <= now && now - state.windowStartMs >= VIEWER_FAILURE_WINDOW_MS) {
|
|
314
|
+
this.failures.delete(key);
|
|
315
|
+
}
|
|
316
|
+
if (this.failures.size < VIEWER_LIMITER_MAX_KEYS) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (this.failures.size >= VIEWER_LIMITER_MAX_KEYS) {
|
|
321
|
+
this.failures.clear();
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { resolveLanguage } from "@pierre/diffs";
|
|
2
|
+
import type { FileContents, FileDiffMetadata, SupportedLanguages } from "@pierre/diffs";
|
|
3
|
+
import { normalizeOptionalString } from "autobot/plugin-sdk/string-coerce-runtime";
|
|
4
|
+
import type { DiffViewerPayload } from "./types.js";
|
|
5
|
+
|
|
6
|
+
const PASSTHROUGH_LANGUAGE_HINTS = new Set<SupportedLanguages>(["ansi", "text"]);
|
|
7
|
+
type DiffPayloadFile = FileContents | FileDiffMetadata;
|
|
8
|
+
|
|
9
|
+
export async function normalizeSupportedLanguageHint(
|
|
10
|
+
value?: string,
|
|
11
|
+
): Promise<SupportedLanguages | undefined> {
|
|
12
|
+
const normalized = normalizeOptionalString(value);
|
|
13
|
+
if (!normalized) {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
if (PASSTHROUGH_LANGUAGE_HINTS.has(normalized as SupportedLanguages)) {
|
|
17
|
+
return normalized as SupportedLanguages;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
await resolveLanguage(normalized as Exclude<SupportedLanguages, "text" | "ansi">);
|
|
21
|
+
return normalized as SupportedLanguages;
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function filterSupportedLanguageHints(
|
|
28
|
+
values: Iterable<string>,
|
|
29
|
+
): Promise<SupportedLanguages[]> {
|
|
30
|
+
return normalizeSupportedLanguageHints(values, { fallbackToText: true });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function normalizeSupportedLanguageHints(
|
|
34
|
+
values: Iterable<string>,
|
|
35
|
+
options: { fallbackToText: boolean },
|
|
36
|
+
): Promise<SupportedLanguages[]> {
|
|
37
|
+
const supported = new Set<SupportedLanguages>();
|
|
38
|
+
for (const value of values) {
|
|
39
|
+
const normalized = await normalizeSupportedLanguageHint(value);
|
|
40
|
+
if (!normalized) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
supported.add(normalized);
|
|
44
|
+
}
|
|
45
|
+
if (options.fallbackToText && supported.size === 0) {
|
|
46
|
+
supported.add("text");
|
|
47
|
+
}
|
|
48
|
+
return [...supported];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function collectDiffPayloadLanguageHints(payload: {
|
|
52
|
+
fileDiff?: FileDiffMetadata;
|
|
53
|
+
oldFile?: FileContents;
|
|
54
|
+
newFile?: FileContents;
|
|
55
|
+
}): SupportedLanguages[] {
|
|
56
|
+
const langs = new Set<SupportedLanguages>();
|
|
57
|
+
if (payload.fileDiff?.lang) {
|
|
58
|
+
langs.add(payload.fileDiff.lang);
|
|
59
|
+
}
|
|
60
|
+
if (payload.oldFile?.lang) {
|
|
61
|
+
langs.add(payload.oldFile.lang);
|
|
62
|
+
}
|
|
63
|
+
if (payload.newFile?.lang) {
|
|
64
|
+
langs.add(payload.newFile.lang);
|
|
65
|
+
}
|
|
66
|
+
return [...langs];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function normalizeDiffPayloadFileLanguage(
|
|
70
|
+
file: DiffPayloadFile | undefined,
|
|
71
|
+
): Promise<DiffPayloadFile | undefined> {
|
|
72
|
+
if (!file) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
if (typeof file.lang !== "string") {
|
|
76
|
+
return file;
|
|
77
|
+
}
|
|
78
|
+
const normalized = await normalizeSupportedLanguageHint(file.lang);
|
|
79
|
+
if (file.lang === normalized) {
|
|
80
|
+
return file;
|
|
81
|
+
}
|
|
82
|
+
if (!normalized) {
|
|
83
|
+
return {
|
|
84
|
+
...file,
|
|
85
|
+
lang: "text",
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
...file,
|
|
90
|
+
lang: normalized,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function normalizeDiffViewerPayloadLanguages(
|
|
95
|
+
payload: DiffViewerPayload,
|
|
96
|
+
): Promise<DiffViewerPayload> {
|
|
97
|
+
const [fileDiff, oldFile, newFile, payloadLangs] = await Promise.all([
|
|
98
|
+
normalizeDiffPayloadFileLanguage(payload.fileDiff) as Promise<FileDiffMetadata | undefined>,
|
|
99
|
+
normalizeDiffPayloadFileLanguage(payload.oldFile) as Promise<FileContents | undefined>,
|
|
100
|
+
normalizeDiffPayloadFileLanguage(payload.newFile) as Promise<FileContents | undefined>,
|
|
101
|
+
normalizeSupportedLanguageHints(payload.langs, { fallbackToText: false }),
|
|
102
|
+
]);
|
|
103
|
+
const langs = new Set<SupportedLanguages>(payloadLangs);
|
|
104
|
+
for (const lang of collectDiffPayloadLanguageHints({ fileDiff, oldFile, newFile })) {
|
|
105
|
+
langs.add(lang);
|
|
106
|
+
}
|
|
107
|
+
if (langs.size === 0) {
|
|
108
|
+
langs.add("text");
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
...payload,
|
|
112
|
+
fileDiff,
|
|
113
|
+
oldFile,
|
|
114
|
+
newFile,
|
|
115
|
+
langs: [...langs],
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import type { ThemeRegistrationResolved } from "@pierre/diffs";
|
|
3
|
+
import { RegisteredCustomThemes, ResolvedThemes, ResolvingThemes } from "@pierre/diffs";
|
|
4
|
+
import { readJsonFileWithFallback } from "autobot/plugin-sdk/json-store";
|
|
5
|
+
|
|
6
|
+
type PierreThemeName = "pierre-dark" | "pierre-light";
|
|
7
|
+
const themeRequire = createRequire(import.meta.url);
|
|
8
|
+
const PIERRE_THEME_SPECS = [
|
|
9
|
+
["pierre-dark", "@pierre/theme/themes/pierre-dark.json"],
|
|
10
|
+
["pierre-light", "@pierre/theme/themes/pierre-light.json"],
|
|
11
|
+
] as const satisfies ReadonlyArray<readonly [PierreThemeName, string]>;
|
|
12
|
+
|
|
13
|
+
function createThemeLoader(
|
|
14
|
+
themeName: PierreThemeName,
|
|
15
|
+
themeSpecifier: string,
|
|
16
|
+
): () => Promise<ThemeRegistrationResolved> {
|
|
17
|
+
let cachedTheme: ThemeRegistrationResolved | undefined;
|
|
18
|
+
return async () => {
|
|
19
|
+
if (cachedTheme) {
|
|
20
|
+
return cachedTheme;
|
|
21
|
+
}
|
|
22
|
+
const themePath = themeRequire.resolve(themeSpecifier);
|
|
23
|
+
const { value: theme } = await readJsonFileWithFallback<Record<string, unknown>>(themePath, {});
|
|
24
|
+
cachedTheme = {
|
|
25
|
+
...theme,
|
|
26
|
+
name: themeName,
|
|
27
|
+
} as ThemeRegistrationResolved;
|
|
28
|
+
return cachedTheme;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const PIERRE_THEME_LOADERS = new Map(
|
|
33
|
+
PIERRE_THEME_SPECS.map(([themeName, themeSpecifier]) => [
|
|
34
|
+
themeName,
|
|
35
|
+
createThemeLoader(themeName, themeSpecifier),
|
|
36
|
+
]),
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
export function ensurePierreThemesRegistered(): void {
|
|
40
|
+
let replacedThemeLoader = false;
|
|
41
|
+
|
|
42
|
+
for (const [themeName, loader] of PIERRE_THEME_LOADERS) {
|
|
43
|
+
if (RegisteredCustomThemes.get(themeName) !== loader) {
|
|
44
|
+
RegisteredCustomThemes.set(themeName, loader);
|
|
45
|
+
replacedThemeLoader = true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!replacedThemeLoader) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// If another path swapped these loaders, clear the resolver caches so the
|
|
54
|
+
// next render rehydrates the highlighter with the Node-safe theme source.
|
|
55
|
+
for (const [themeName] of PIERRE_THEME_LOADERS) {
|
|
56
|
+
ResolvedThemes.delete(themeName);
|
|
57
|
+
ResolvingThemes.delete(themeName);
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { resolveLivePluginConfigObject } from "autobot/plugin-sdk/plugin-config-runtime";
|
|
3
|
+
import {
|
|
4
|
+
resolvePreferredAutoBotTmpDir,
|
|
5
|
+
type AutoBotConfig,
|
|
6
|
+
type AutoBotPluginApi,
|
|
7
|
+
} from "../api.js";
|
|
8
|
+
import {
|
|
9
|
+
resolveDiffsPluginDefaults,
|
|
10
|
+
resolveDiffsPluginSecurity,
|
|
11
|
+
resolveDiffsPluginViewerBaseUrl,
|
|
12
|
+
} from "./config.js";
|
|
13
|
+
import { createDiffsHttpHandler } from "./http.js";
|
|
14
|
+
import { DIFFS_AGENT_GUIDANCE } from "./prompt-guidance.js";
|
|
15
|
+
import { DiffArtifactStore } from "./store.js";
|
|
16
|
+
import { createDiffsTool } from "./tool.js";
|
|
17
|
+
|
|
18
|
+
export function registerDiffsPlugin(api: AutoBotPluginApi): void {
|
|
19
|
+
const store = new DiffArtifactStore({
|
|
20
|
+
rootDir: path.join(resolvePreferredAutoBotTmpDir(), "autobot-diffs"),
|
|
21
|
+
logger: api.logger,
|
|
22
|
+
});
|
|
23
|
+
const resolveCurrentPluginConfig = () =>
|
|
24
|
+
resolveLivePluginConfigObject(
|
|
25
|
+
api.runtime.config?.current
|
|
26
|
+
? () => api.runtime.config.current() as AutoBotConfig
|
|
27
|
+
: undefined,
|
|
28
|
+
"diffs",
|
|
29
|
+
api.pluginConfig as Record<string, unknown>,
|
|
30
|
+
) ?? {};
|
|
31
|
+
const resolveCurrentAccessConfig = () => {
|
|
32
|
+
const currentConfig = (api.runtime.config?.current?.() ?? api.config) as AutoBotConfig;
|
|
33
|
+
const pluginConfig = resolveCurrentPluginConfig();
|
|
34
|
+
return {
|
|
35
|
+
allowRemoteViewer: resolveDiffsPluginSecurity(pluginConfig).allowRemoteViewer,
|
|
36
|
+
trustedProxies: currentConfig.gateway?.trustedProxies,
|
|
37
|
+
allowRealIpFallback: currentConfig.gateway?.allowRealIpFallback === true,
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
const initialAccessConfig = resolveCurrentAccessConfig();
|
|
41
|
+
|
|
42
|
+
api.registerTool(
|
|
43
|
+
(ctx) => {
|
|
44
|
+
const pluginConfig = resolveCurrentPluginConfig();
|
|
45
|
+
return createDiffsTool({
|
|
46
|
+
api,
|
|
47
|
+
store,
|
|
48
|
+
defaults: resolveDiffsPluginDefaults(pluginConfig),
|
|
49
|
+
viewerBaseUrl: resolveDiffsPluginViewerBaseUrl(pluginConfig),
|
|
50
|
+
context: ctx,
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: "diffs",
|
|
55
|
+
},
|
|
56
|
+
);
|
|
57
|
+
api.registerHttpRoute({
|
|
58
|
+
path: "/plugins/diffs",
|
|
59
|
+
auth: "plugin",
|
|
60
|
+
match: "prefix",
|
|
61
|
+
handler: createDiffsHttpHandler({
|
|
62
|
+
store,
|
|
63
|
+
logger: api.logger,
|
|
64
|
+
allowRemoteViewer: initialAccessConfig.allowRemoteViewer,
|
|
65
|
+
trustedProxies: initialAccessConfig.trustedProxies,
|
|
66
|
+
allowRealIpFallback: initialAccessConfig.allowRealIpFallback,
|
|
67
|
+
resolveAccessConfig: resolveCurrentAccessConfig,
|
|
68
|
+
}),
|
|
69
|
+
});
|
|
70
|
+
api.on("before_prompt_build", async () => ({
|
|
71
|
+
prependSystemContext: DIFFS_AGENT_GUIDANCE,
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const DIFFS_AGENT_GUIDANCE = [
|
|
2
|
+
"When you need to show edits as a real diff, prefer the `diffs` tool instead of writing a manual summary.",
|
|
3
|
+
"It accepts either `before` + `after` text or a unified `patch`.",
|
|
4
|
+
"`mode=view` returns `details.viewerUrl` for canvas use; `mode=file` returns `details.filePath`; `mode=both` returns both.",
|
|
5
|
+
"If you need to send the rendered file, use the `message` tool with `path` or `filePath`.",
|
|
6
|
+
"Include `path` when you know the filename, and omit presentation overrides unless needed.",
|
|
7
|
+
].join("\n");
|