context-drop 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/MIT-LICENSE +21 -0
  2. package/README.md +710 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +9949 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +53 -0
  5. package/dist/app/javascript/context_drop/api-client.js +470 -0
  6. package/dist/app/javascript/context_drop/element-picker.d.ts +111 -0
  7. package/dist/app/javascript/context_drop/element-picker.js +1428 -0
  8. package/dist/app/javascript/context_drop/icons.d.ts +34 -0
  9. package/dist/app/javascript/context_drop/icons.js +34 -0
  10. package/dist/app/javascript/context_drop/index.d.ts +7 -0
  11. package/dist/app/javascript/context_drop/index.js +9 -0
  12. package/dist/app/javascript/context_drop/markdown.d.ts +7 -0
  13. package/dist/app/javascript/context_drop/markdown.js +129 -0
  14. package/dist/app/javascript/context_drop/sanitizer.d.ts +38 -0
  15. package/dist/app/javascript/context_drop/sanitizer.js +769 -0
  16. package/dist/app/javascript/context_drop/screenshot.d.ts +21 -0
  17. package/dist/app/javascript/context_drop/screenshot.js +245 -0
  18. package/dist/app/javascript/context_drop/styles.d.ts +1 -0
  19. package/dist/app/javascript/context_drop/styles.js +2196 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +316 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +206 -0
  23. package/dist/app/javascript/context_drop/widget.js +3752 -0
  24. package/dist/src/cli.d.ts +3 -0
  25. package/dist/src/cli.js +207 -0
  26. package/dist/src/index.d.ts +5 -0
  27. package/dist/src/index.js +5 -0
  28. package/dist/src/mcp/dispatcher.d.ts +42 -0
  29. package/dist/src/mcp/dispatcher.js +895 -0
  30. package/dist/src/mcp/environment-router.d.ts +38 -0
  31. package/dist/src/mcp/environment-router.js +174 -0
  32. package/dist/src/mcp/index.d.ts +24 -0
  33. package/dist/src/mcp/index.js +75 -0
  34. package/dist/src/mcp/remote-client.d.ts +25 -0
  35. package/dist/src/mcp/remote-client.js +98 -0
  36. package/dist/src/next/index.d.ts +13 -0
  37. package/dist/src/next/index.js +25 -0
  38. package/dist/src/next/server.d.ts +1 -0
  39. package/dist/src/next/server.js +1 -0
  40. package/dist/src/react/index.d.ts +104 -0
  41. package/dist/src/react/index.js +144 -0
  42. package/dist/src/server/handler.d.ts +48 -0
  43. package/dist/src/server/handler.js +1180 -0
  44. package/dist/src/server/index.d.ts +8 -0
  45. package/dist/src/server/index.js +8 -0
  46. package/dist/src/server/sanitizer.d.ts +15 -0
  47. package/dist/src/server/sanitizer.js +201 -0
  48. package/dist/src/server/storage/local.d.ts +22 -0
  49. package/dist/src/server/storage/local.js +827 -0
  50. package/dist/src/server/storage/memory.d.ts +8 -0
  51. package/dist/src/server/storage/memory.js +387 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +629 -0
  54. package/dist/src/server/types.d.ts +227 -0
  55. package/dist/src/server/types.js +7 -0
  56. package/dist/src/server/upload-validator.d.ts +16 -0
  57. package/dist/src/server/upload-validator.js +196 -0
  58. package/dist/src/widget/index.d.ts +1 -0
  59. package/dist/src/widget/index.js +1 -0
  60. package/package.json +99 -4
@@ -0,0 +1,53 @@
1
+ import type { AgentChatRequestPayload, AgentChatResponse, AgentKeysUpdatePayload, AgentKeysUpdateResponse, AgentStatusResponse, ContextDropApiClientOptions, CrossEnvFeedbackListResponse, FeedbackDeleteResponse, FeedbackSubmissionPayload, FeedbackSubmissionResponse, FeedbackUpdatePayload, FeedbackUpdateResponse, OwnFeedbackListResponse, ProposedFileEdit, WidgetConfig } from "./types.js";
2
+ export declare class ContextDropApiClient {
3
+ private baseUrl;
4
+ private credentials;
5
+ private customHeaders;
6
+ private cachedCsrfToken;
7
+ private configFetched;
8
+ private inFlightConfigPromise;
9
+ private memoryOwnershipTokens;
10
+ constructor(baseUrl?: string, options?: ContextDropApiClientOptions);
11
+ getBaseUrl(): string;
12
+ setCredentials(credentials: RequestCredentials): void;
13
+ setHeaders(headers: Record<string, string>): void;
14
+ private isCrossOriginEndpoint;
15
+ private mergeClientHeaders;
16
+ getCsrfToken(): string | null;
17
+ setCsrfToken(token: string | null): void;
18
+ private getMetaCsrfToken;
19
+ fetchConfig(): Promise<WidgetConfig>;
20
+ resolveCsrfToken(forceRefresh?: boolean): Promise<string | null>;
21
+ private isCsrfError;
22
+ private executeWithCsrfRetry;
23
+ private buildJsonHeaders;
24
+ uploadAttachment(file: Blob, filename: string): Promise<{
25
+ signed_blob_id: string;
26
+ }>;
27
+ private ownershipScopedKey;
28
+ private readStoredTokenMap;
29
+ private writeStoredTokenMap;
30
+ getOwnershipToken(id: number | string): string | null;
31
+ setOwnershipToken(id: number | string, token: string): void;
32
+ removeOwnershipToken(id: number | string): void;
33
+ getAllOwnershipTokens(): string[];
34
+ buildAttachmentPreviewUrl(feedbackId: number | string, attachmentId: number | string, ownershipToken?: string | null): string;
35
+ submitFeedback(payload: FeedbackSubmissionPayload): Promise<FeedbackSubmissionResponse>;
36
+ fetchOwnFeedbacks(limit?: number): Promise<OwnFeedbackListResponse>;
37
+ updateFeedback(id: number | string, payload: FeedbackUpdatePayload, ownershipToken?: string | null): Promise<FeedbackUpdateResponse>;
38
+ deleteFeedback(id: number | string, ownershipToken?: string | null): Promise<FeedbackDeleteResponse>;
39
+ fetchAgentStatus(): Promise<AgentStatusResponse>;
40
+ saveAgentKeys(payload: AgentKeysUpdatePayload): Promise<AgentKeysUpdateResponse>;
41
+ deleteAgentKeys(provider?: string): Promise<AgentKeysUpdateResponse>;
42
+ fetchAgentFeedbacks(environment?: string, status?: string): Promise<CrossEnvFeedbackListResponse>;
43
+ sendAgentChat(payload: AgentChatRequestPayload): Promise<AgentChatResponse>;
44
+ applyEdit(editId: string): Promise<{
45
+ edit: ProposedFileEdit;
46
+ }>;
47
+ rejectEdit(editId: string): Promise<{
48
+ edit: ProposedFileEdit;
49
+ }>;
50
+ revertEdit(editId: string): Promise<{
51
+ edit: ProposedFileEdit;
52
+ }>;
53
+ }
@@ -0,0 +1,470 @@
1
+ const OWNERSHIP_STORAGE_KEY = "context_drop_ownership_tokens";
2
+ const MAX_STORED_OWNERSHIP_TOKENS = 50;
3
+ function getBrowserLocalStorage() {
4
+ try {
5
+ if (typeof window !== "undefined" && "localStorage" in window) {
6
+ const store = window.localStorage;
7
+ if (store && typeof store.getItem === "function" && typeof store.setItem === "function") {
8
+ return store;
9
+ }
10
+ }
11
+ }
12
+ catch {
13
+ // Storage unavailable or restricted by browser privacy policy
14
+ }
15
+ return null;
16
+ }
17
+ export class ContextDropApiClient {
18
+ baseUrl;
19
+ credentials;
20
+ customHeaders;
21
+ cachedCsrfToken = null;
22
+ configFetched = false;
23
+ inFlightConfigPromise = null;
24
+ memoryOwnershipTokens = new Map();
25
+ constructor(baseUrl = "/context_drop", options = {}) {
26
+ this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
27
+ this.credentials = options.credentials || "same-origin";
28
+ this.customHeaders = options.headers ? { ...options.headers } : {};
29
+ }
30
+ getBaseUrl() {
31
+ return this.baseUrl;
32
+ }
33
+ setCredentials(credentials) {
34
+ this.credentials = credentials;
35
+ }
36
+ setHeaders(headers) {
37
+ this.customHeaders = { ...headers };
38
+ }
39
+ isCrossOriginEndpoint() {
40
+ if (!/^https?:\/\//i.test(this.baseUrl)) {
41
+ return false;
42
+ }
43
+ if (typeof window === "undefined" || !window.location || !window.location.origin) {
44
+ return true;
45
+ }
46
+ try {
47
+ return new URL(this.baseUrl, window.location.origin).origin !== window.location.origin;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ mergeClientHeaders(base) {
54
+ const merged = {
55
+ ...this.customHeaders,
56
+ ...base
57
+ };
58
+ if (this.isCrossOriginEndpoint()) {
59
+ merged["X-Context-Drop-Client"] = "1";
60
+ }
61
+ return merged;
62
+ }
63
+ getCsrfToken() {
64
+ const metaToken = this.getMetaCsrfToken();
65
+ if (metaToken) {
66
+ return metaToken;
67
+ }
68
+ return this.cachedCsrfToken;
69
+ }
70
+ setCsrfToken(token) {
71
+ this.cachedCsrfToken = token ? token.trim() : null;
72
+ }
73
+ getMetaCsrfToken() {
74
+ if (typeof document === "undefined")
75
+ return null;
76
+ const meta = document.querySelector('meta[name="csrf-token"]');
77
+ const content = meta ? meta.getAttribute("content") : null;
78
+ return content && content.trim().length > 0 ? content.trim() : null;
79
+ }
80
+ async fetchConfig() {
81
+ if (this.inFlightConfigPromise) {
82
+ return this.inFlightConfigPromise;
83
+ }
84
+ this.inFlightConfigPromise = (async () => {
85
+ try {
86
+ const response = await fetch(`${this.baseUrl}/config`, {
87
+ method: "GET",
88
+ credentials: this.credentials,
89
+ headers: this.mergeClientHeaders({
90
+ Accept: "application/json"
91
+ })
92
+ });
93
+ if (!response.ok) {
94
+ throw new Error(`Failed to fetch ContextDrop config (${response.status})`);
95
+ }
96
+ const config = (await response.json());
97
+ this.configFetched = true;
98
+ if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
99
+ this.cachedCsrfToken = config.csrf_token.trim();
100
+ if (typeof document !== "undefined") {
101
+ const meta = document.querySelector('meta[name="csrf-token"]');
102
+ if (meta) {
103
+ meta.setAttribute("content", this.cachedCsrfToken);
104
+ }
105
+ }
106
+ }
107
+ return config;
108
+ }
109
+ finally {
110
+ this.inFlightConfigPromise = null;
111
+ }
112
+ })();
113
+ return this.inFlightConfigPromise;
114
+ }
115
+ async resolveCsrfToken(forceRefresh = false) {
116
+ if (!forceRefresh) {
117
+ const metaToken = this.getMetaCsrfToken();
118
+ if (metaToken) {
119
+ return metaToken;
120
+ }
121
+ if (this.cachedCsrfToken) {
122
+ return this.cachedCsrfToken;
123
+ }
124
+ if (this.configFetched) {
125
+ return null;
126
+ }
127
+ }
128
+ try {
129
+ const config = await this.fetchConfig();
130
+ if (config && config.csrf_token) {
131
+ return config.csrf_token.trim();
132
+ }
133
+ }
134
+ catch {
135
+ // Continue and fall back to current token or null
136
+ }
137
+ return this.cachedCsrfToken || this.getMetaCsrfToken();
138
+ }
139
+ isCsrfError(status, message) {
140
+ if (status !== 422)
141
+ return false;
142
+ return /csrf|authenticity/i.test(message);
143
+ }
144
+ async executeWithCsrfRetry(requestFn, defaultErrorMessage) {
145
+ let csrfToken = await this.resolveCsrfToken(false);
146
+ let response = await requestFn(csrfToken);
147
+ if (response.ok) {
148
+ return (await response.json());
149
+ }
150
+ if (response.status === 422) {
151
+ const rawText = await response.text();
152
+ let parsedError = null;
153
+ try {
154
+ const json = JSON.parse(rawText);
155
+ if (json && typeof json.error === "string") {
156
+ parsedError = json.error;
157
+ }
158
+ }
159
+ catch {
160
+ // Not JSON
161
+ }
162
+ const errorMessage = parsedError || rawText || "";
163
+ const shouldRetryCsrf = this.isCsrfError(response.status, errorMessage) ||
164
+ (!csrfToken && !this.configFetched && response.status === 422);
165
+ if (shouldRetryCsrf) {
166
+ csrfToken = await this.resolveCsrfToken(true);
167
+ response = await requestFn(csrfToken);
168
+ if (response.ok) {
169
+ return (await response.json());
170
+ }
171
+ const retryErrBody = await response.json().catch(() => ({}));
172
+ throw new Error(retryErrBody.error || `${defaultErrorMessage} (${response.status})`);
173
+ }
174
+ throw new Error(parsedError || errorMessage || `${defaultErrorMessage} (${response.status})`);
175
+ }
176
+ const errBody = await response.json().catch(() => ({}));
177
+ throw new Error(errBody.error || `${defaultErrorMessage} (${response.status})`);
178
+ }
179
+ buildJsonHeaders(csrfToken) {
180
+ const headers = {
181
+ "Content-Type": "application/json",
182
+ Accept: "application/json"
183
+ };
184
+ if (csrfToken) {
185
+ headers["X-CSRF-Token"] = csrfToken;
186
+ }
187
+ return this.mergeClientHeaders(headers);
188
+ }
189
+ async uploadAttachment(file, filename) {
190
+ const makeRequest = async (csrfToken) => {
191
+ const formData = new FormData();
192
+ formData.append("file", file, filename);
193
+ const headers = {
194
+ Accept: "application/json"
195
+ };
196
+ if (csrfToken) {
197
+ headers["X-CSRF-Token"] = csrfToken;
198
+ }
199
+ return fetch(`${this.baseUrl}/attachments`, {
200
+ method: "POST",
201
+ credentials: this.credentials,
202
+ headers: this.mergeClientHeaders(headers),
203
+ body: formData
204
+ });
205
+ };
206
+ return this.executeWithCsrfRetry(makeRequest, "Upload failed");
207
+ }
208
+ ownershipScopedKey(id) {
209
+ return `${this.baseUrl}::${String(id)}`;
210
+ }
211
+ readStoredTokenMap() {
212
+ const store = getBrowserLocalStorage();
213
+ if (!store) {
214
+ const out = {};
215
+ for (const [k, v] of this.memoryOwnershipTokens.entries()) {
216
+ out[k] = v;
217
+ }
218
+ return out;
219
+ }
220
+ try {
221
+ const raw = store.getItem(OWNERSHIP_STORAGE_KEY);
222
+ if (!raw)
223
+ return {};
224
+ const parsed = JSON.parse(raw);
225
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
226
+ return {};
227
+ }
228
+ const clean = {};
229
+ for (const [k, v] of Object.entries(parsed)) {
230
+ if (typeof v === "string" && v.trim().length > 0) {
231
+ clean[k] = v.trim();
232
+ }
233
+ }
234
+ return clean;
235
+ }
236
+ catch {
237
+ return {};
238
+ }
239
+ }
240
+ writeStoredTokenMap(map) {
241
+ const entries = Object.entries(map);
242
+ const trimmedEntries = entries.length > MAX_STORED_OWNERSHIP_TOKENS
243
+ ? entries.slice(entries.length - MAX_STORED_OWNERSHIP_TOKENS)
244
+ : entries;
245
+ this.memoryOwnershipTokens.clear();
246
+ const bounded = {};
247
+ for (const [k, v] of trimmedEntries) {
248
+ bounded[k] = v;
249
+ this.memoryOwnershipTokens.set(k, v);
250
+ }
251
+ const store = getBrowserLocalStorage();
252
+ if (store) {
253
+ try {
254
+ store.setItem(OWNERSHIP_STORAGE_KEY, JSON.stringify(bounded));
255
+ }
256
+ catch {
257
+ // Non-fatal if storage quota exceeded
258
+ }
259
+ }
260
+ }
261
+ getOwnershipToken(id) {
262
+ const map = this.readStoredTokenMap();
263
+ const scoped = map[this.ownershipScopedKey(id)];
264
+ if (scoped)
265
+ return scoped;
266
+ const plain = map[String(id)];
267
+ return plain || null;
268
+ }
269
+ setOwnershipToken(id, token) {
270
+ const trimmed = typeof token === "string" ? token.trim() : "";
271
+ if (!trimmed)
272
+ return;
273
+ const map = this.readStoredTokenMap();
274
+ const key = this.ownershipScopedKey(id);
275
+ delete map[key];
276
+ map[key] = trimmed;
277
+ this.writeStoredTokenMap(map);
278
+ }
279
+ removeOwnershipToken(id) {
280
+ const map = this.readStoredTokenMap();
281
+ const scopedKey = this.ownershipScopedKey(id);
282
+ const plainKey = String(id);
283
+ if (!(scopedKey in map) && !(plainKey in map))
284
+ return;
285
+ delete map[scopedKey];
286
+ delete map[plainKey];
287
+ this.writeStoredTokenMap(map);
288
+ }
289
+ getAllOwnershipTokens() {
290
+ const map = this.readStoredTokenMap();
291
+ const prefix = `${this.baseUrl}::`;
292
+ const tokens = [];
293
+ for (const [k, v] of Object.entries(map)) {
294
+ if ((k.startsWith(prefix) || !k.includes("::")) && v && !tokens.includes(v)) {
295
+ tokens.push(v);
296
+ }
297
+ }
298
+ return tokens;
299
+ }
300
+ buildAttachmentPreviewUrl(feedbackId, attachmentId, ownershipToken) {
301
+ const token = ownershipToken || this.getOwnershipToken(feedbackId);
302
+ const base = `${this.baseUrl}/feedback/${encodeURIComponent(String(feedbackId))}/attachments/${encodeURIComponent(String(attachmentId))}`;
303
+ return token ? `${base}?ownership_token=${encodeURIComponent(token)}` : base;
304
+ }
305
+ async submitFeedback(payload) {
306
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/feedback`, {
307
+ method: "POST",
308
+ credentials: this.credentials,
309
+ headers: this.buildJsonHeaders(csrfToken),
310
+ body: JSON.stringify({ feedback: payload })
311
+ });
312
+ const response = await this.executeWithCsrfRetry(makeRequest, "Submission failed");
313
+ const token = response?.ownership_token || response?.feedback?.ownership_token;
314
+ if (response?.id !== undefined && token) {
315
+ this.setOwnershipToken(response.id, token);
316
+ }
317
+ return response;
318
+ }
319
+ async fetchOwnFeedbacks(limit = 30) {
320
+ const headers = {
321
+ Accept: "application/json"
322
+ };
323
+ const tokens = this.getAllOwnershipTokens();
324
+ if (tokens.length > 0) {
325
+ headers["X-Context-Drop-Ownership-Tokens"] = tokens.join(",");
326
+ }
327
+ const qs = limit > 0 ? `?limit=${encodeURIComponent(String(limit))}` : "";
328
+ const response = await fetch(`${this.baseUrl}/feedback${qs}`, {
329
+ method: "GET",
330
+ credentials: this.credentials,
331
+ headers: this.mergeClientHeaders(headers)
332
+ });
333
+ if (!response.ok) {
334
+ const errBody = await response.json().catch(() => ({}));
335
+ throw new Error(errBody.error || `Failed to load own feedbacks (${response.status})`);
336
+ }
337
+ const parsed = (await response.json().catch(() => ({})));
338
+ const feedbacks = Array.isArray(parsed?.feedbacks) ? parsed.feedbacks : [];
339
+ for (const item of feedbacks) {
340
+ if (item && item.id !== undefined && typeof item.ownership_token === "string") {
341
+ this.setOwnershipToken(item.id, item.ownership_token);
342
+ }
343
+ }
344
+ return {
345
+ total_count: typeof parsed?.total_count === "number" ? parsed.total_count : feedbacks.length,
346
+ feedbacks
347
+ };
348
+ }
349
+ async updateFeedback(id, payload, ownershipToken) {
350
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
351
+ const makeRequest = async (csrfToken) => {
352
+ const headers = this.buildJsonHeaders(csrfToken);
353
+ if (resolvedToken) {
354
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
355
+ }
356
+ const bodyPayload = { feedback: payload };
357
+ if (resolvedToken) {
358
+ bodyPayload.ownership_token = resolvedToken;
359
+ }
360
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
361
+ method: "PATCH",
362
+ credentials: this.credentials,
363
+ headers,
364
+ body: JSON.stringify(bodyPayload)
365
+ });
366
+ };
367
+ const response = await this.executeWithCsrfRetry(makeRequest, "Update failed");
368
+ const nextToken = response?.ownership_token || response?.feedback?.ownership_token;
369
+ if (response?.id !== undefined && nextToken) {
370
+ this.setOwnershipToken(response.id, nextToken);
371
+ }
372
+ return response;
373
+ }
374
+ async deleteFeedback(id, ownershipToken) {
375
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
376
+ const makeRequest = async (csrfToken) => {
377
+ const headers = this.buildJsonHeaders(csrfToken);
378
+ if (resolvedToken) {
379
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
380
+ }
381
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
382
+ method: "DELETE",
383
+ credentials: this.credentials,
384
+ headers
385
+ });
386
+ };
387
+ const response = await this.executeWithCsrfRetry(makeRequest, "Delete failed");
388
+ this.removeOwnershipToken(id);
389
+ return response;
390
+ }
391
+ async fetchAgentStatus() {
392
+ const response = await fetch(`${this.baseUrl}/agent/status`, {
393
+ method: "GET",
394
+ credentials: this.credentials,
395
+ headers: this.mergeClientHeaders({
396
+ Accept: "application/json"
397
+ })
398
+ });
399
+ if (!response.ok) {
400
+ const errBody = await response.json().catch(() => ({}));
401
+ throw new Error(errBody.error || `Failed to load agent status (${response.status})`);
402
+ }
403
+ return (await response.json());
404
+ }
405
+ async saveAgentKeys(payload) {
406
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/keys`, {
407
+ method: "POST",
408
+ credentials: this.credentials,
409
+ headers: this.buildJsonHeaders(csrfToken),
410
+ body: JSON.stringify(payload)
411
+ });
412
+ return this.executeWithCsrfRetry(makeRequest, "Failed to save BYOK settings");
413
+ }
414
+ async deleteAgentKeys(provider = "all") {
415
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/keys?provider=${encodeURIComponent(provider)}`, {
416
+ method: "DELETE",
417
+ credentials: this.credentials,
418
+ headers: this.buildJsonHeaders(csrfToken)
419
+ });
420
+ return this.executeWithCsrfRetry(makeRequest, "Failed to clear BYOK key");
421
+ }
422
+ async fetchAgentFeedbacks(environment = "all", status = "new") {
423
+ const qs = `environment=${encodeURIComponent(environment)}&status=${encodeURIComponent(status)}`;
424
+ const response = await fetch(`${this.baseUrl}/agent/feedbacks?${qs}`, {
425
+ method: "GET",
426
+ credentials: this.credentials,
427
+ headers: this.mergeClientHeaders({
428
+ Accept: "application/json"
429
+ })
430
+ });
431
+ if (!response.ok) {
432
+ const errBody = await response.json().catch(() => ({}));
433
+ throw new Error(errBody.error || `Failed to load feedbacks (${response.status})`);
434
+ }
435
+ return (await response.json());
436
+ }
437
+ async sendAgentChat(payload) {
438
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/chat`, {
439
+ method: "POST",
440
+ credentials: this.credentials,
441
+ headers: this.buildJsonHeaders(csrfToken),
442
+ body: JSON.stringify(payload)
443
+ });
444
+ return this.executeWithCsrfRetry(makeRequest, "Agent request failed");
445
+ }
446
+ async applyEdit(editId) {
447
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/apply`, {
448
+ method: "POST",
449
+ credentials: this.credentials,
450
+ headers: this.buildJsonHeaders(csrfToken)
451
+ });
452
+ return this.executeWithCsrfRetry(makeRequest, "Failed to apply file edit");
453
+ }
454
+ async rejectEdit(editId) {
455
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/reject`, {
456
+ method: "POST",
457
+ credentials: this.credentials,
458
+ headers: this.buildJsonHeaders(csrfToken)
459
+ });
460
+ return this.executeWithCsrfRetry(makeRequest, "Failed to reject file edit");
461
+ }
462
+ async revertEdit(editId) {
463
+ const makeRequest = async (csrfToken) => fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/revert`, {
464
+ method: "POST",
465
+ credentials: this.credentials,
466
+ headers: this.buildJsonHeaders(csrfToken)
467
+ });
468
+ return this.executeWithCsrfRetry(makeRequest, "Failed to revert file edit");
469
+ }
470
+ }
@@ -0,0 +1,111 @@
1
+ import type { ElementCandidateInfo, ElementReferenceSnapshot, SelectionMode } from "./types.js";
2
+ export interface PinnedElementEntry {
3
+ clientRef: string;
4
+ selector: string;
5
+ friendlyLabel?: string;
6
+ element: Element;
7
+ }
8
+ export interface ElementPickerStateSnapshot {
9
+ active: boolean;
10
+ anchored: boolean;
11
+ scrubbing: boolean;
12
+ activeCandidate: ElementCandidateInfo | null;
13
+ candidateStack: ElementCandidateInfo[];
14
+ ancestors: Element[];
15
+ lastAction?: {
16
+ kind: "pinned" | "unpinned";
17
+ selector: string;
18
+ } | null;
19
+ }
20
+ export interface ElementPickerCallbacks {
21
+ onSelect: (snapshot: ElementReferenceSnapshot, element: Element) => void;
22
+ onUnselect?: (clientRef: string, element: Element) => void;
23
+ onExit: () => void;
24
+ canSelectMore: () => boolean;
25
+ getExcludedSelectors: () => string[];
26
+ getSelectionMode?: () => SelectionMode;
27
+ getPinnedElements?: () => PinnedElementEntry[];
28
+ onStateChange?: (state: ElementPickerStateSnapshot) => void;
29
+ }
30
+ export declare class ElementPicker {
31
+ private active;
32
+ private suppressCursorPin;
33
+ private isScrubbingLayers;
34
+ private scrubOriginX;
35
+ private scrubOriginY;
36
+ private lastPointerX;
37
+ private lastPointerY;
38
+ private wheelAccumulator;
39
+ private lastWheelStepAt;
40
+ private callbacks;
41
+ private overlayEl;
42
+ private leafOutlineEl;
43
+ private hudEl;
44
+ private pinMarkerEl;
45
+ private pinnedMarkersContainerEl;
46
+ private toastEl;
47
+ private previewOverlayEl;
48
+ private pulseTimer;
49
+ private nudgeTimer;
50
+ private toastTimer;
51
+ private candidateStack;
52
+ private activeCandidateIndex;
53
+ private leafElement;
54
+ private lastAction;
55
+ private previousCursor;
56
+ private boundMouseMove;
57
+ private boundClickCapture;
58
+ private boundPointerCapture;
59
+ private boundBlurSuppression;
60
+ private boundWheelCapture;
61
+ private boundKeyDown;
62
+ private boundScrollOrResize;
63
+ constructor(callbacks: ElementPickerCallbacks);
64
+ isActive(): boolean;
65
+ isAnchored(): boolean;
66
+ isScrubbing(): boolean;
67
+ private isSmartMode;
68
+ getActiveCandidate(): ElementCandidateInfo | null;
69
+ getCandidateStack(): ElementCandidateInfo[];
70
+ start(options?: {
71
+ suppressCursorPin?: boolean;
72
+ }): void;
73
+ stop(options?: {
74
+ silent?: boolean;
75
+ }): void;
76
+ highlightAtPoint(x: number, y: number, event?: Event): void;
77
+ clearCandidateHighlight(): void;
78
+ commitActiveCandidate(x?: number, y?: number): boolean;
79
+ focusCandidateElement(el: Element): void;
80
+ selectElementDirectly(el: Element): boolean;
81
+ refreshPinnedMarkers(): void;
82
+ showExternalPreview(el: Element | null): void;
83
+ hideExternalPreview(): void;
84
+ cycleDepth(delta: number, revealStack?: boolean): void;
85
+ private clearTimers;
86
+ private findPinnedIndex;
87
+ private notifyStateChange;
88
+ private mountSelectionUi;
89
+ private unmountSelectionUi;
90
+ private isInternalUiEvent;
91
+ private collectPointElements;
92
+ private updateCandidatesFromPoint;
93
+ private handleViewportScrollOrResize;
94
+ private handleMouseMove;
95
+ private createSpanEl;
96
+ private createKbdEl;
97
+ private renderSmartHudContent;
98
+ private renderCompactHudContent;
99
+ private renderScrubbingHudContent;
100
+ private positionHudElement;
101
+ private updateOverlayPosition;
102
+ private triggerHudBoundaryNudge;
103
+ private flashSelectionPulse;
104
+ private showCursorToast;
105
+ private commitCandidateSelection;
106
+ private handleWheelCapture;
107
+ private handlePointerSuppression;
108
+ private handleBlurSuppression;
109
+ private handleClickCapture;
110
+ private handleKeyDown;
111
+ }