clay-server 5.3.0-beta.4 → 5.3.0-beta.5
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/lib/ask-user-request-identity.js +18 -1
- package/lib/project-delegated-follow-up.js +18 -9
- package/lib/public/css/right-workbench.css +26 -3
- package/lib/public/css/shared-browser.css +21 -0
- package/lib/public/css/sticky-notes.css +3 -2
- package/lib/public/index.html +2 -2
- package/lib/public/modules/app-header.js +24 -2
- package/lib/public/modules/app-messages.js +1 -1
- package/lib/public/modules/clay-session-links.js +1 -1
- package/lib/public/modules/filebrowser.js +2 -2
- package/lib/public/modules/pane-activation.js +3 -0
- package/lib/public/modules/pane-browser-bridge.js +15 -5
- package/lib/public/modules/pane-header-runtime.js +18 -0
- package/lib/public/modules/right-workbench.js +92 -62
- package/lib/public/modules/shared-browser.js +6 -0
- package/lib/public/modules/split-pane-renderer.js +6 -8
- package/lib/public/modules/split-pane-runtime.js +23 -0
- package/lib/public/modules/split-view.js +8 -14
- package/lib/public/modules/sticky-notes.js +8 -10
- package/lib/public/modules/terminal.js +7 -2
- package/lib/public/modules/theme.js +5 -0
- package/lib/public/modules/workspace-assignment-card.js +9 -6
- package/lib/public/pane-assets/{app-ED2VCGNQ.js → app-6H5S2Y3Z.js} +1 -1
- package/lib/public/pane-assets/chunk-3QV5SDC4.js +1 -0
- package/lib/public/pane-assets/{chunk-JAEQCN5S.js → chunk-4FM3U3DW.js} +1 -1
- package/lib/public/pane-assets/{chunk-6SM2WQJX.js → chunk-7GZH3FZY.js} +1 -1
- package/lib/public/pane-assets/chunk-AGJTF5WQ.js +1 -0
- package/lib/public/pane-assets/chunk-NPKRTUNG.js +2 -0
- package/lib/public/pane-assets/{chunk-IYFILQHZ.js → chunk-VGA2Y3D2.js} +1 -1
- package/lib/public/pane-assets/{chunk-IZ2ZANEY.js → chunk-WKO3T75E.js} +89 -89
- package/lib/public/pane-assets/manifest.json +361 -359
- package/lib/public/pane-assets/{style-JVCOCG3W.css → style-TSRDU54Z.css} +1 -1
- package/lib/server.js +1 -0
- package/lib/workspace-assignment-service.js +56 -11
- package/lib/workspace-follow-up-queue.js +92 -0
- package/lib/workspace-query-mcp-server.js +1 -1
- package/package.json +1 -1
- package/lib/public/pane-assets/chunk-6D4DPE5X.js +0 -1
- package/lib/public/pane-assets/chunk-7H36SUZA.js +0 -2
- package/lib/public/pane-assets/chunk-ST2Q62ET.js +0 -1
package/lib/server.js
CHANGED
|
@@ -317,6 +317,7 @@ function createServer(opts) {
|
|
|
317
317
|
|
|
318
318
|
// --- Project registry ---
|
|
319
319
|
var assignmentService = attachWorkspaceAssignmentService({
|
|
320
|
+
resolveMate: function (owner, id) { return mates.getMate(mates.buildMateCtx(users.isMultiUser() ? owner : null), id); },
|
|
320
321
|
getPresentation: function (principal) {
|
|
321
322
|
var project = projects.get(principal.sourceProjectSlug), manager = project && project.getSessionManager(), status = project && project.getStatus();
|
|
322
323
|
var session = manager && manager.sessions.get(principal.sourceSessionId);
|
|
@@ -2,7 +2,7 @@ var fs = require("fs");
|
|
|
2
2
|
var path = require("path");
|
|
3
3
|
var crypto = require("crypto");
|
|
4
4
|
|
|
5
|
-
var ACTIVE = { proposed: true, starting: true, running: true };
|
|
5
|
+
var ACTIVE = { proposed: true, queued: true, starting: true, running: true };
|
|
6
6
|
var MAX_RUNNING = 3;
|
|
7
7
|
|
|
8
8
|
function clean(value, max) {
|
|
@@ -21,6 +21,8 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
21
21
|
var pendingRestartReplay = {};
|
|
22
22
|
var presentations = new WeakMap();
|
|
23
23
|
var presentationTargets = new WeakMap();
|
|
24
|
+
var followUps = require('./workspace-follow-up-queue').createFollowUpQueue({ records: records,
|
|
25
|
+
exactSource: exactSource, exactTarget: exactTarget, settle: settle, approve: approve });
|
|
24
26
|
|
|
25
27
|
function recordFile(userId) {
|
|
26
28
|
return storageDir ? path.join(storageDir, userStorageKey(userId)) : null;
|
|
@@ -44,12 +46,13 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
44
46
|
if (!files[i].endsWith(".json") || files[i].indexOf(".tmp.") !== -1) continue;
|
|
45
47
|
try {
|
|
46
48
|
var loaded = JSON.parse(fs.readFileSync(path.join(storageDir, files[i]), "utf8"));
|
|
47
|
-
if (Array.isArray(loaded)) records
|
|
49
|
+
if (Array.isArray(loaded)) records.push.apply(records, loaded);
|
|
48
50
|
} catch (e) {}
|
|
49
51
|
}
|
|
50
52
|
var changedUsers = {};
|
|
51
53
|
for (var j = 0; j < records.length; j++) {
|
|
52
|
-
if (records[j].status !== "starting" && records[j].status !== "running") continue;
|
|
54
|
+
if (records[j].status !== "queued" && records[j].status !== "starting" && records[j].status !== "running") continue;
|
|
55
|
+
records[j].deliveryState = records[j].status === "queued" ? "not_sent" : "unknown";
|
|
53
56
|
records[j].status = "interrupted";
|
|
54
57
|
records[j].error = "Clay restarted before this assignment completed.";
|
|
55
58
|
records[j].updatedAt = Date.now();
|
|
@@ -90,6 +93,8 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
90
93
|
title: record.title,
|
|
91
94
|
task: record.task,
|
|
92
95
|
status: record.status,
|
|
96
|
+
deliveryState: record.deliveryState || null,
|
|
97
|
+
parentAssignmentId: record.parentAssignmentId || null,
|
|
93
98
|
sourceProjectSlug: record.sourceProjectSlug,
|
|
94
99
|
sourceSessionRef: record.sourceSessionRef,
|
|
95
100
|
targetSessionRef: record.targetSessionRef || null,
|
|
@@ -119,6 +124,8 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
119
124
|
var status = project.getStatus();
|
|
120
125
|
if (!status || status.isMate !== true || status.mateId !== record.sourceMateId) return null;
|
|
121
126
|
if (ctx.isMultiUser() && status.projectOwnerId !== record.userId) return null;
|
|
127
|
+
var mate = ctx.resolveMate && ctx.resolveMate(status.projectOwnerId || null, record.sourceMateId);
|
|
128
|
+
if (ctx.resolveMate && (!mate || mate.id !== record.sourceMateId || ctx.isMultiUser() && mate.createdBy !== record.userId)) return null;
|
|
122
129
|
var manager = project.getSessionManager();
|
|
123
130
|
var session = null;
|
|
124
131
|
if (manager && manager.sessions) {
|
|
@@ -129,7 +136,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
129
136
|
if (!session) return null;
|
|
130
137
|
if (ctx.isMultiUser() && session.ownerId !== record.userId) return null;
|
|
131
138
|
if (!ctx.isMultiUser() && session.ownerId && session.ownerId !== record.singleUserOwnerId) return null;
|
|
132
|
-
return { project: project, manager: manager, session: session };
|
|
139
|
+
return { project: project, manager: manager, session: session, mate: mate || null };
|
|
133
140
|
}
|
|
134
141
|
|
|
135
142
|
function present(record, principal) {
|
|
@@ -149,7 +156,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
149
156
|
function emit(record, eventType) {
|
|
150
157
|
var observer = presentations.get(record);
|
|
151
158
|
if (observer) {
|
|
152
|
-
if (record.status === 'starting') observer.phase('queued');
|
|
159
|
+
if (record.status === 'starting' || record.status === 'queued') observer.phase('queued');
|
|
153
160
|
else if (record.status === 'running') observer.phase('running');
|
|
154
161
|
else if (record.status !== 'proposed') { observer.finish({ status: record.status === 'interrupted' ? 'failed' : record.status, outcome: record.status === 'interrupted' ? 'uncertain' : undefined }); presentations.delete(record); }
|
|
155
162
|
}
|
|
@@ -232,12 +239,16 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
232
239
|
var idempotency = crypto.createHash("sha256").update(key + "\u0000follow_up\u0000" + projectSlug + "\u0000" + targetSessionRef + "\u0000" + title + "\u0000" + task).digest("hex");
|
|
233
240
|
for (var i = 0; i < records.length; i++) {
|
|
234
241
|
if (records[i].idempotencyKey === idempotency) return publicRecord(records[i]);
|
|
235
|
-
if (records[i].sourceKey === key && ACTIVE[records[i].status]
|
|
242
|
+
if (records[i].sourceKey === key && ACTIVE[records[i].status] &&
|
|
243
|
+
(records[i].targetProjectSlug !== projectSlug || records[i].targetSessionRef !== targetSessionRef)) throw new Error("An active assignment already exists. Send this update to that exact Driver session.");
|
|
236
244
|
}
|
|
237
245
|
var candidate = { userId: principal.userId || null, singleUserOwnerId: principal.singleUserOwnerId || null, targetProjectSlug: projectSlug };
|
|
238
246
|
var target = exactTarget(candidate);
|
|
239
247
|
if (!target || typeof target.inspectDelegatedFollowUp !== "function") throw new Error("Target project is unavailable for follow-ups.");
|
|
240
|
-
|
|
248
|
+
if (records.filter(function (item) { return item.sourceKey === key && item.delivery === 'follow_up' && ACTIVE[item.status]; }).length >= 16) throw new Error('There are already 16 pending follow-ups. Wait for or cancel a review.');
|
|
249
|
+
var candidateInput = { userId: principal.userId || null, sourceKey: key, targetProjectSlug: projectSlug, targetSessionRef: targetSessionRef,
|
|
250
|
+
sourceMateId: principal.mateId, sourceProjectSlug: principal.sourceProjectSlug, sourceSessionRef: principal.sourceSessionRef };
|
|
251
|
+
var inspected = followUps.inspect(candidateInput, target);
|
|
241
252
|
var now = Date.now();
|
|
242
253
|
var targetStatus = target.getStatus();
|
|
243
254
|
var record = {
|
|
@@ -250,6 +261,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
250
261
|
title: title, task: task, delivery: "follow_up", status: "proposed", createdAt: now, updatedAt: now,
|
|
251
262
|
};
|
|
252
263
|
if (!exactSource(record)) throw new Error("Source conversation is no longer available.");
|
|
264
|
+
followUps.remember(record, target, inspected);
|
|
253
265
|
records.push(record);
|
|
254
266
|
saveUser(record.userId);
|
|
255
267
|
present(record, principal);
|
|
@@ -279,7 +291,9 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
279
291
|
|
|
280
292
|
function settle(record, status, session, error) {
|
|
281
293
|
if (!ACTIVE[record.status]) return publicRecord(record);
|
|
294
|
+
if (record.delivery === "follow_up" && record.deliveryState !== "accepted") record.deliveryState = record.status === "starting" ? "unknown" : "not_sent";
|
|
282
295
|
record.status = status;
|
|
296
|
+
followUps.cleanup(record);
|
|
283
297
|
record.resultSummary = status === "completed" ? summarize(session) : "";
|
|
284
298
|
record.error = clean(error || "", 800);
|
|
285
299
|
record.updatedAt = Date.now();
|
|
@@ -287,12 +301,19 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
287
301
|
delete unsubscribers[record.assignmentId];
|
|
288
302
|
saveUser(record.userId);
|
|
289
303
|
emit(record);
|
|
304
|
+
followUps.wake(record);
|
|
290
305
|
return publicRecord(record);
|
|
291
306
|
}
|
|
292
307
|
|
|
293
308
|
function watch(record, manager, session) {
|
|
294
309
|
var view = presentationTargets.get(record); if (view) { view.session = session; view.origin = session.sessionOriginId; var observer = presentations.get(record); if (observer && observer.target) observer.target({ kind: 'session', projectSlug: record.targetProjectSlug, sessionId: session.localId, sessionOriginId: session.sessionOriginId }); }
|
|
310
|
+
if (unsubscribers[record.assignmentId]) unsubscribers[record.assignmentId]();
|
|
295
311
|
var unsubscribe = manager.subscribeSession(session.localId, function (event) {
|
|
312
|
+
if (record.status === 'queued') {
|
|
313
|
+
if (event.type === 'error') settle(record, 'failed', session, event.text || 'Driver failed before follow-up delivery.');
|
|
314
|
+
else if (event.type === 'done' || event.type === 'result') followUps.schedule(record);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
296
317
|
if (event.type === "session_id") {
|
|
297
318
|
record.targetSessionRef = ctx.sessionRef(record.targetProjectSlug, session);
|
|
298
319
|
record.updatedAt = Date.now();
|
|
@@ -301,6 +322,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
301
322
|
} else if (event.type === "error") {
|
|
302
323
|
settle(record, "failed", session, event.text || "Assignment failed.");
|
|
303
324
|
} else if (event.type === "done" || event.type === "result") {
|
|
325
|
+
if (record.delivery === "follow_up") record.deliveryState = "accepted";
|
|
304
326
|
settle(record, session._lastTurnInterrupted ? "interrupted" : "completed", session, "");
|
|
305
327
|
}
|
|
306
328
|
});
|
|
@@ -308,17 +330,32 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
308
330
|
}
|
|
309
331
|
|
|
310
332
|
async function approve(record) {
|
|
311
|
-
if (record.status !== "proposed") return publicRecord(record);
|
|
333
|
+
if (record.status !== "proposed" && record.status !== "queued") return publicRecord(record);
|
|
312
334
|
var running = records.filter(function (item) {
|
|
313
335
|
return item.userId === record.userId && (item.status === "starting" || item.status === "running");
|
|
314
336
|
}).length;
|
|
315
|
-
if (running >= MAX_RUNNING) throw new Error("Too many assignments are already running.");
|
|
316
337
|
if (!exactSource(record)) throw new Error("Source conversation is no longer available.");
|
|
317
338
|
var target = exactTarget(record);
|
|
318
339
|
var followUp = record.delivery === "follow_up";
|
|
319
340
|
if (!target || (followUp ? typeof target.dispatchDelegatedFollowUp !== "function" : typeof target.createDelegatedSession !== "function")) throw new Error("Target project is no longer available.");
|
|
341
|
+
if (followUp) {
|
|
342
|
+
var inspected;
|
|
343
|
+
try { inspected = followUps.validate(record, target, followUps.inspect(record, target)); }
|
|
344
|
+
catch (error) { return settle(record, 'failed', null, error.message); }
|
|
345
|
+
if (followUps.busy(inspected.session) || (followUps.first(record) && followUps.first(record) !== record)) {
|
|
346
|
+
var beforeQueue = Object.assign({}, record, { decision: record.decision, deliveryState: record.deliveryState, queueOrder: record.queueOrder });
|
|
347
|
+
if (record.status === 'proposed') record.queueOrder = records.reduce(function (max, item) { return Math.max(max, item.queueOrder || 0); }, 0) + 1;
|
|
348
|
+
record.decision = 'approve'; record.status = 'queued'; record.deliveryState = 'queued'; record.updatedAt = Date.now();
|
|
349
|
+
try { saveUser(record.userId); } catch (error) { Object.assign(record, beforeQueue); throw error; }
|
|
350
|
+
watch(record, target.getSessionManager(), inspected.session); followUps.track(record); emit(record); followUps.schedule(record);
|
|
351
|
+
return publicRecord(record);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (running >= MAX_RUNNING) throw new Error("Too many assignments are already running.");
|
|
355
|
+
followUps.cleanup(record);
|
|
320
356
|
record.decision = "approve";
|
|
321
357
|
record.status = "starting";
|
|
358
|
+
if (followUp) record.deliveryState = "dispatching";
|
|
322
359
|
record.updatedAt = Date.now();
|
|
323
360
|
saveUser(record.userId);
|
|
324
361
|
emit(record);
|
|
@@ -329,10 +366,11 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
329
366
|
sourceMateId: record.sourceMateId,
|
|
330
367
|
sourceProjectSlug: record.sourceProjectSlug,
|
|
331
368
|
sourceSessionRef: record.sourceSessionRef,
|
|
369
|
+
parentAssignmentId: record.parentAssignmentId || null,
|
|
332
370
|
};
|
|
333
371
|
var session;
|
|
334
372
|
if (followUp) {
|
|
335
|
-
session = await target.dispatchDelegatedFollowUp({ userId: record.userId }, record.targetSessionRef, record.task, metadata, function (existing) { watch(record, target.getSessionManager(), existing); });
|
|
373
|
+
session = await target.dispatchDelegatedFollowUp({ userId: record.userId, sourceMateId: record.sourceMateId, sourceProjectSlug: record.sourceProjectSlug, sourceSessionRef: record.sourceSessionRef }, record.targetSessionRef, record.task, metadata, function (existing) { followUps.validate(record, exactTarget(record), followUps.inspect(record, target)); watch(record, target.getSessionManager(), existing); });
|
|
336
374
|
} else {
|
|
337
375
|
session = await target.createDelegatedSession({ userId: record.userId }, record.task, metadata, function (created) { watch(record, target.getSessionManager(), created); });
|
|
338
376
|
}
|
|
@@ -340,6 +378,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
340
378
|
record.targetSessionRef = ctx.sessionRef(record.targetProjectSlug, session);
|
|
341
379
|
record.targetSessionId = session.localId;
|
|
342
380
|
record.status = "running";
|
|
381
|
+
if (followUp) record.deliveryState = "accepted";
|
|
343
382
|
record.updatedAt = Date.now();
|
|
344
383
|
saveUser(record.userId);
|
|
345
384
|
emit(record);
|
|
@@ -350,12 +389,17 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
350
389
|
}
|
|
351
390
|
|
|
352
391
|
function cancel(record) {
|
|
353
|
-
if (record.status !== "proposed") return publicRecord(record);
|
|
392
|
+
if (record.status !== "proposed" && record.status !== "queued") return publicRecord(record);
|
|
393
|
+
followUps.cleanup(record);
|
|
394
|
+
if (unsubscribers[record.assignmentId]) unsubscribers[record.assignmentId]();
|
|
395
|
+
delete unsubscribers[record.assignmentId];
|
|
396
|
+
record.deliveryState = 'not_sent';
|
|
354
397
|
record.decision = "cancel";
|
|
355
398
|
record.status = "cancelled";
|
|
356
399
|
record.updatedAt = Date.now();
|
|
357
400
|
saveUser(record.userId);
|
|
358
401
|
emit(record);
|
|
402
|
+
followUps.wake(record);
|
|
359
403
|
return publicRecord(record);
|
|
360
404
|
}
|
|
361
405
|
|
|
@@ -396,6 +440,7 @@ function attachWorkspaceAssignmentService(ctx) {
|
|
|
396
440
|
validateResponseSource(ws, msg, record, routedProjectSlug);
|
|
397
441
|
var action = msg.action === "approve" ? "approve" : (msg.action === "cancel" ? "cancel" : "");
|
|
398
442
|
if (!action) throw new Error("Choose approve or cancel.");
|
|
443
|
+
if (record.status === "queued" && action === "cancel") return cancel(record);
|
|
399
444
|
if (record.status !== "proposed") {
|
|
400
445
|
if (record.decision === action) return publicRecord(record);
|
|
401
446
|
throw new Error("Assignment proposal has already been resolved.");
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Reviewed assignment updates share the existing follow-up dispatch service.
|
|
2
|
+
function createFollowUpQueue(ctx) {
|
|
3
|
+
var snapshots = new WeakMap(), scheduled = new WeakSet(), sourceWatches = new WeakMap();
|
|
4
|
+
function source(record) {
|
|
5
|
+
var current = ctx.exactSource(record);
|
|
6
|
+
if (!current || current.session.taskStopRequested || current.session._pendingMessageDrainPaused || current.session._lastTurnInterrupted || current.session.abortController && current.session.abortController.signal.aborted || current.session._mentionInProgress || current.session.spawn) throw new Error('Source conversation stopped or changed. Request a new review.');
|
|
7
|
+
return current;
|
|
8
|
+
}
|
|
9
|
+
function inspect(record, project) {
|
|
10
|
+
var parent = ctx.records.find(function (item) {
|
|
11
|
+
return item.sourceKey === record.sourceKey && item.delivery !== 'follow_up' && item.targetProjectSlug === record.targetProjectSlug &&
|
|
12
|
+
item.targetSessionRef === record.targetSessionRef && (!record.parentAssignmentId || item.assignmentId === record.parentAssignmentId);
|
|
13
|
+
});
|
|
14
|
+
return project.inspectDelegatedFollowUp({ userId: record.userId, sourceMateId: record.sourceMateId,
|
|
15
|
+
sourceProjectSlug: record.sourceProjectSlug, sourceSessionRef: record.sourceSessionRef }, record.targetSessionRef,
|
|
16
|
+
{ allowBusy: true, parentAssignmentId: parent && parent.assignmentId || null });
|
|
17
|
+
}
|
|
18
|
+
function remember(record, project, inspected) {
|
|
19
|
+
var current = source(record);
|
|
20
|
+
snapshots.set(record, { project: project, session: inspected.session, origin: inspected.session.sessionOriginId,
|
|
21
|
+
linuxUser: inspected.linuxUser || null, source: current.session, sourceProject: current.project });
|
|
22
|
+
record.targetSessionOriginId = inspected.session.sessionOriginId || null;
|
|
23
|
+
record.targetLinuxUser = inspected.linuxUser || null;
|
|
24
|
+
record.targetDirectory = project.getStatus().path || null;
|
|
25
|
+
record.sourceDirectory = current.project.getStatus().path || null;
|
|
26
|
+
record.sourceVisibility = current.session.sessionVisibility || null;
|
|
27
|
+
record.sourceBuiltinKey = current.mate && current.mate.builtinKey || null;
|
|
28
|
+
record.sourceSessionOriginId = current.session.sessionOriginId || null;
|
|
29
|
+
record.sourceQueryGeneration = current.session._sdkQueryGeneration || null;
|
|
30
|
+
var parent = ctx.records.find(function (item) { return item.sourceKey === record.sourceKey && item.delivery !== 'follow_up' &&
|
|
31
|
+
item.targetProjectSlug === record.targetProjectSlug && item.targetSessionRef === record.targetSessionRef; });
|
|
32
|
+
record.parentAssignmentId = parent && parent.assignmentId || null;
|
|
33
|
+
}
|
|
34
|
+
function validate(record, project, inspected) {
|
|
35
|
+
var current = source(record), saved = snapshots.get(record);
|
|
36
|
+
if (saved && (saved.project !== project || saved.session !== inspected.session || saved.origin !== inspected.session.sessionOriginId ||
|
|
37
|
+
saved.linuxUser !== (inspected.linuxUser || null) || saved.source !== current.session || saved.sourceProject !== current.project) ||
|
|
38
|
+
record.targetSessionOriginId && record.targetSessionOriginId !== inspected.session.sessionOriginId ||
|
|
39
|
+
record.sourceSessionOriginId && record.sourceSessionOriginId !== current.session.sessionOriginId ||
|
|
40
|
+
record.parentAssignmentId && (!inspected.session.assignment || inspected.session.assignment.assignmentId !== record.parentAssignmentId) ||
|
|
41
|
+
record.sourceVisibility !== (current.session.sessionVisibility || null) ||
|
|
42
|
+
record.targetDirectory !== (project.getStatus().path || null) || record.sourceDirectory !== (current.project.getStatus().path || null) ||
|
|
43
|
+
record.sourceBuiltinKey !== (current.mate && current.mate.builtinKey || null) ||
|
|
44
|
+
(record.targetLinuxUser || null) !== (inspected.linuxUser || null) ||
|
|
45
|
+
(record.sourceQueryGeneration || null) !== (current.session._sdkQueryGeneration || null)) throw new Error('Follow-up identity or OS mapping changed. Request a new review.');
|
|
46
|
+
return inspected;
|
|
47
|
+
}
|
|
48
|
+
function busy(session) { return !!(session.isProcessing || session._queryStarting || session._awaitingTurnResult); }
|
|
49
|
+
function cleanup(record) {
|
|
50
|
+
var unsubscribe = sourceWatches.get(record);
|
|
51
|
+
if (unsubscribe) unsubscribe();
|
|
52
|
+
sourceWatches.delete(record);
|
|
53
|
+
}
|
|
54
|
+
function track(record) {
|
|
55
|
+
if (sourceWatches.has(record)) return;
|
|
56
|
+
var current = source(record);
|
|
57
|
+
if (typeof current.manager.subscribeSession !== 'function') return;
|
|
58
|
+
var unsubscribe = current.manager.subscribeSession(current.session.localId, function () {
|
|
59
|
+
if (record.status !== 'queued') return;
|
|
60
|
+
try { validate(record, ctx.exactTarget(record), inspect(record, ctx.exactTarget(record))); } catch (error) { stop(record, 'interrupted', error); }
|
|
61
|
+
});
|
|
62
|
+
if (unsubscribe) sourceWatches.set(record, unsubscribe);
|
|
63
|
+
}
|
|
64
|
+
function first(record) {
|
|
65
|
+
return ctx.records.filter(function (item) { return item.status === 'queued' && item.userId === record.userId &&
|
|
66
|
+
item.targetProjectSlug === record.targetProjectSlug && item.targetSessionRef === record.targetSessionRef; })
|
|
67
|
+
.sort(function (a, b) { return a.queueOrder - b.queueOrder; })[0];
|
|
68
|
+
}
|
|
69
|
+
function wake(record) { var next = first(record); if (next) schedule(next); }
|
|
70
|
+
function stop(record, status, error) {
|
|
71
|
+
try { ctx.settle(record, status, null, error.message); }
|
|
72
|
+
catch (failure) { console.error('Follow-up status could not be persisted:', failure.message); }
|
|
73
|
+
}
|
|
74
|
+
function schedule(record) {
|
|
75
|
+
if (record.status !== 'queued' || scheduled.has(record)) return;
|
|
76
|
+
scheduled.add(record);
|
|
77
|
+
setImmediate(function () {
|
|
78
|
+
scheduled.delete(record);
|
|
79
|
+
if (record.status !== 'queued') return;
|
|
80
|
+
try {
|
|
81
|
+
var project = ctx.exactTarget(record);
|
|
82
|
+
if (!project) throw new Error('Target project access changed.');
|
|
83
|
+
var inspected = validate(record, project, inspect(record, project));
|
|
84
|
+
if (inspected.session._lastTurnInterrupted) throw new Error('Driver was stopped; explicit owner resumption is required.');
|
|
85
|
+
if (first(record) !== record || busy(inspected.session)) return;
|
|
86
|
+
Promise.resolve(ctx.approve(record)).catch(function (error) { stop(record, 'failed', error); });
|
|
87
|
+
} catch (error) { stop(record, 'interrupted', error); }
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return { inspect: inspect, remember: remember, validate: validate, busy: busy, track: track, schedule: schedule, first: first, wake: wake, cleanup: cleanup };
|
|
91
|
+
}
|
|
92
|
+
module.exports = { createFollowUpQueue: createFollowUpQueue };
|
|
@@ -90,7 +90,7 @@ function commonTools(bound) {
|
|
|
90
90
|
},
|
|
91
91
|
{
|
|
92
92
|
name: "propose_project_follow_up",
|
|
93
|
-
description: "Propose
|
|
93
|
+
description: "Propose reviewed instructions for an exact existing private Driver session, including an update to your active assignment. Busy Drivers queue approved instructions for their next turn; stopped sessions require explicit owner resumption. No target work occurs before human approval.",
|
|
94
94
|
inputSchema: shape({
|
|
95
95
|
projectSlug: field("string", "Exact owned target project slug."),
|
|
96
96
|
targetSessionRef: field("string", "Durable opaque session reference returned by list_project_sessions."),
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l as a,m as b,n as c,o as d}from"./chunk-IZ2ZANEY.js";import"./chunk-7H36SUZA.js";import"./chunk-DGOFGEUK.js";export{a as closeLinear,c as handleLinearResult,d as initLinearPanel,b as openLinear};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as i,c as h}from"./chunk-DGOFGEUK.js";function S(e,t,n){var r=document.createElement("div");if(r.className="toast",t&&r.classList.add("toast-"+t),r.textContent=e,n){var o=document.createElement("div");o.style.cssText="font-size:11px;opacity:0.7;margin-top:4px;max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap",o.textContent=n.split(`
|
|
2
|
-
`)[0],r.appendChild(o)}document.body.appendChild(r),requestAnimationFrame(function(){r.classList.add("visible")});var s=t==="warn"?5e3:1500;setTimeout(function(){r.classList.remove("visible"),setTimeout(function(){r.remove()},300)},s)}var je=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function it(e){var t;if(je){var n=document.createElement("textarea");n.value=e,n.style.cssText="position:fixed;left:-9999px;opacity:0",document.body.appendChild(n),n.focus(),n.setSelectionRange(0,n.value.length),document.execCommand("copy"),document.body.removeChild(n),t=Promise.resolve()}else if(navigator.clipboard&&navigator.clipboard.writeText)t=navigator.clipboard.writeText(e);else{var r=document.createElement("textarea");r.value=e,r.style.cssText="position:fixed;left:-9999px;opacity:0",document.body.appendChild(r),r.focus(),r.setSelectionRange(0,r.value.length),document.execCommand("copy"),document.body.removeChild(r),t=Promise.resolve()}return t.then(function(){S("Copied to clipboard")})}function ge(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function j(e){var t=i.snap();return e&&t.connected&&e.socket===h()&&e.ownerId===(t.myUserId||null)&&e.slug===t.currentSlug&&e.sessionId===t.activeSessionId&&e.origin===t.sessionOriginId&&e.runtime===t.controlRuntimeId}function pe(e){var t=i.get("studioDocumentSource");t&&clearTimeout(t.timer),t&&j(t)&&t.socket.send(JSON.stringify({type:"fs_unwatch"}));var n=i.snap(),r={token:crypto.randomUUID(),socket:h(),ownerId:n.myUserId||null,slug:n.currentSlug,sessionId:n.activeSessionId,origin:n.sessionOriginId,runtime:n.controlRuntimeId,path:e.path,expires:Date.now()+3e5};return r.timer=setTimeout(function(){i.get("studioDocumentSource")===r&&(j(r)&&r.socket.send(JSON.stringify({type:"fs_unwatch"})),i.set({studioDocumentSource:null}))},3e5),i.set({studioDocumentSource:r}),j(r)&&r.socket.send(JSON.stringify({type:"fs_watch",path:r.path})),Object.assign({},e,{studioDocument:{token:r.token,sourceSlug:r.slug,sourceSessionId:r.sessionId,sourceOrigin:r.origin,runtimeId:r.runtime,expires:r.expires,path:r.path}})}function ct(e,t,n){var r=t.message&&t.message.studioDocument;if(!(!n||!r||r.path!==t.message.path||r.sourceSlug!==t.studioSource.slug||r.sourceSessionId!==t.studioSource.sessionId||r.sourceOrigin!==t.studioSource.origin||r.runtimeId!==t.studioSource.runtime)){fe();var o=h();o&&o.readyState===1&&o.send(JSON.stringify({type:"fs_unwatch"})),i.set({fileReadRequest:null,pendingFileNavigation:null});var s={descriptor:r,frame:n,document:n.contentDocument,source:e.source,owner:i.get("myUserId"),context:i.get("currentSlug")};s.timer=setTimeout(function(){i.get("studioDocumentView")===s&&i.set({studioDocumentView:{descriptor:s.descriptor,invalidated:!0}})},Math.max(0,r.expires-Date.now())),i.set({studioDocumentView:s})}}function We(e){var t=i.get("studioDocumentView");if(!t||t.invalidated||!t.frame||Date.now()>t.descriptor.expires||t.descriptor.path!==e)return null;var n=t.frame.clayStudioSource,r=n&&n.document===t.frame.contentDocument&&n.window===t.source&&n.identity();return r&&r.connected&&r.ownerId===t.owner&&r.slug===t.descriptor.sourceSlug&&r.sessionId===t.descriptor.sourceSessionId&&r.origin===t.descriptor.sourceOrigin&&r.runtime===t.descriptor.runtimeId&&t.document===t.frame.contentDocument&&t.source===t.frame.contentWindow&&t.owner===i.get("myUserId")&&t.context===i.get("currentSlug")?t:null}function ut(e){var t=i.get("studioDocumentView");if(!t||t.descriptor.path!==e)return!1;var n=We(e);return n?(n.source.postMessage({type:"clay-studio-document-refresh",token:n.descriptor.token},location.origin),!0):(S("The source connection changed. Reopen this document from its conversation."),!0)}function fe(){var e=i.get("studioDocumentView");e&&clearTimeout(e.timer),e&&e.frame&&e.source===e.frame.contentWindow&&e.document===e.frame.contentDocument&&e.source.postMessage({type:"clay-studio-document-close",token:e.descriptor.token},location.origin),i.set({studioDocumentView:null})}function lt(e){var t=i.get("studioDocumentSource");return!j(t)||Date.now()>t.expires||e.path!==t.path||e.type!=="fs_file_changed"&&!(e.type==="fs_read_result"&&e.requestId===t.requestId)?!1:(window.parent.postMessage({type:"clay-studio-document-update",token:t.token,message:e},location.origin),!0)}function gt(){window.addEventListener("message",function(t){var n=t.data,r=i.get("studioDocumentSource");t.origin!==location.origin||t.source!==window.parent||!n||!r||n.token!==r.token||!j(r)||(n.type==="clay-studio-document-close"&&(clearTimeout(r.timer),r.socket.send(JSON.stringify({type:"fs_unwatch"})),i.set({studioDocumentSource:null})),n.type==="clay-studio-document-refresh"&&Date.now()<=r.expires&&(r.requestId="studio-document-"+crypto.randomUUID(),r.socket.send(JSON.stringify({type:"fs_read",path:r.path,requestId:r.requestId,projectSlug:r.slug,sessionId:String(r.sessionId),accountId:r.ownerId}))))});function e(){var t=i.get("studioDocumentSource");t&&clearTimeout(t.timer),j(t)&&t.socket.send(JSON.stringify({type:"fs_unwatch"})),i.set({studioDocumentSource:null});var n=i.get("studioDocumentView");fe(),n&&i.set({studioDocumentView:{descriptor:n.descriptor,invalidated:!0}})}i.subscribe(function(t,n){(!t.connected&&n.connected||t.currentSlug!==n.currentSlug||t.activeSessionId!==n.activeSessionId||t.myUserId!==n.myUserId)&&e()}),document.addEventListener("contextual-ask-stopped",e,!0),document.addEventListener("click",function(t){t.target.closest("#generation-stop, #autonomous-run-stop, #send-btn.stop")&&e()},!0)}function Ne(){var e=i.snap();return{projectSlug:e.currentSlug,ownerId:e.myUserId,sessionId:e.activeSessionId,origin:e.sessionOriginId,socket:h(),binding:e.paneCommittedBinding||null,epoch:e.sessionActionEpoch||0}}function _e(e,t){var n=i.snap();return!!e&&e.socket===h()&&n.connected&&e.projectSlug===n.currentSlug&&e.ownerId===n.myUserId&&e.sessionId===n.activeSessionId&&e.origin===n.sessionOriginId&&e.epoch===(n.sessionActionEpoch||0)&&(t||!n.deferredSessionSwitch)&&!n.panePendingBinding&&!n.paneSuspended&&(e.binding?n.paneReady&&G(e.binding,n.paneCommittedBinding):!n.paneCommittedBinding)}function mt(e,t){var n=Ne();return function(){if(_e(n,t)){var r=i.get("paneCallbackBinding");i.set({paneCallbackBinding:n.binding});try{return e.apply(this,arguments)}finally{i.set({paneCallbackBinding:r})}}}}function G(e,t){return!!e&&!!t&&["requestId","generation","projectSlug","viewerId","ownerId","sessionId","sessionOriginId","role","workerGeneration","groupStamp","parentSessionOriginId"].every(function(n){return e[n]===t[n]})}function Fe(e,t){return!!e&&!!t&&["projectSlug","viewerId","ownerId","sessionId","sessionOriginId","role","workerGeneration","groupStamp","parentSessionOriginId"].every(function(n){return e[n]===t[n]})}function ze(e,t,n){var r=(t||[]).find(function(a){return a.id===n});if(!r||r.isMate||!r.sessionOriginId||(r.runtimeMode||r.mode||"gui")!=="gui"||r.tuiSuspended)return null;var o=(e.splitGroups||[]).find(function(a){return a.members.indexOf(n)>=0}),s=r.sessionRole==="worker"&&t.find(function(a){return a.id===r.parentSessionId});return r.sessionRole==="worker"&&(!s||!r.parentAvailable||!Number.isSafeInteger(r.workerGeneration)||!s.sessionOriginId||s.ownerId!==r.ownerId||!o||!o.pair||o.pair.driverId!==s.id)?null:{projectSlug:e.currentSlug,viewerId:e.myUserId||null,ownerId:r.ownerId||null,sessionId:r.id,sessionOriginId:r.sessionOriginId,role:r.sessionRole==="worker"?"worker":"driver",workerGeneration:r.workerGeneration||null,parentSessionOriginId:s?s.sessionOriginId:null,groupStamp:o?JSON.stringify({id:o.id,members:o.members,pair:o.pair||null}):null}}function N(e,t){if(!e||!e.clayPane||e.closest&&e.closest(".split-pane-cached"))return!1;var n=e.clayPane,r=n.identity(),o=i.snap(),s=o.splitPanes;if(!o.connected)return!1;var a=r&&ze(o,o.paneBindingSessions||[],r.sessionId),d=!!(r&&s&&s.panes.some(function(l){return l.slug===r.projectSlug&&l.sessionId===r.sessionId})),c=(o.projectSplitViews||[]).find(function(l){return l.id===o.projectSplitViewActiveId}),u=!!(r&&r.binding&&!s&&c&&c.sessions.some(function(l){return l.id===r.sessionId&&l.sessionOriginId===r.binding.sessionOriginId})),g=!!(r&&r.binding&&!s&&!c&&o.projectSplitViewSingletonOrigin===r.binding.sessionOriginId&&r.sessionId===Number(e.dataset.sessionId)&&r.binding.sessionOriginId===e.dataset.sessionOriginId);return n.source===e.contentWindow&&n.document===e.contentDocument&&r&&r.ready&&Fe(a,r.binding)&&r.ownerId===(o.myUserId||null)&&r.projectSlug===o.currentSlug&&(d||u||g)&&(!t||G(r.binding,t.paneBinding))}function K(){return i.get("paneReady")&&!i.get("paneSuspended")?i.get("paneCommittedBinding"):null}function wt(e){return!e||!e.paneBinding?!0:e.isConnected!==!1&&i.get("paneReady")&&!i.get("paneSuspended")&&G(e.paneBinding,i.get("paneCommittedBinding"))}function vt(e){if(i.get("paneSuspended"))return!1;var t=i.get("panePendingBinding")||i.get("paneCommittedBinding");return t?G(t,e):!e}function Ve(e){var t=(i.get("cachedMatesList")||[]).find(function(o){return o&&o.id===e});if(!t||t.archived||t.contentAccess===!1||t.accessible===!1)return null;var n=i.get("myUserId");if(n&&t.createdBy&&t.createdBy!==n)return null;var r=(i.get("projectsHubList")||[]).find(function(o){return o.slug==="mate-"+e});return r&&r.contentAccess===!1?null:t}function Z(e){return JSON.stringify([e.id,e.createdBy||null,e.createdAt||null,e.builtinKey||null])}function St(e,t){var n=e||(i.get("contextualClay")||{}).mateId,r=i.get("contextualClay")||{};if(!t&&r.mateId===n&&r.startingAsk)return null;var o=t||r.mateId===n&&r.sessionId||(i.get("contextualSessionSelection")||{})[n];return Array.from(document.querySelectorAll("#contextual-clay iframe")).find(function(s){return s.dataset.mateId===n&&(!o||String(o)===s.dataset.sessionId)})||null}function It(e){var t=Ve(e||(i.get("contextualClay")||{}).mateId);return t&&t.builtinKey!=="clay"?document.querySelector('.icon-strip-project-mate[data-mate-id="'+CSS.escape(t.id)+'"]'):document.querySelector(".icon-strip-brand")}function xt(e){if(!e||!e.isConnected||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;var t=e.getBoundingClientRect(),n=getComputedStyle(e);if(n.visibility!=="visible"||Number(n.opacity)===0||!t.width||!t.height||t.left<0||t.top<0||t.right>innerWidth||t.bottom>innerHeight)return!1;for(var r=e.parentElement;r;r=r.parentElement)if(Number(getComputedStyle(r).opacity)===0)return!1;return[t.left+2,t.left+t.width/2,t.right-2].every(function(o){var s=document.elementFromPoint(o,t.top+t.height/2);return s&&e.contains(s)})}function X(e){var t=/^[a-f0-9-]{36}$/;return e&&e.version===1&&t.test(e.id)&&t.test(e.token)&&/^activity:[a-f0-9-]{36}$/.test(e.activityId)&&Number.isSafeInteger(e.deadline)&&e.target&&["document","sketch","browser"].indexOf(e.target.surface)>=0&&typeof e.target.key=="string"&&e.target.key.length<=400&&/^[a-f0-9]{64}$/.test(e.target.revision)}function ee(e,t){return X(e)&&e.mateId===t.activeProjectMateId&&e.sourceSlug==="mate-"+e.mateId&&e.ownerId===(t.myUserId||null)&&e.runtimeId===t.controlRuntimeId&&e.sourceSlug===t.currentSlug&&e.sourceSessionId===t.activeSessionId&&e.sourceSessionOriginId===t.sessionOriginId&&(t.cachedMatesList||[]).some(function(n){return n.id===e.mateId&&n.builtinKey==="clay"&&!n.archived&&!n.lifecycleDeletion&&Z(n)===e.sourceMateStamp})}function te(e){var t=i.get("clayControlActivity"),n=i.get("clayControlForwarded"),r=i.get("paneMode")?n:t&&t.message;return r&&r.id===e.activityId&&r.mateId===e.mateId&&r.sourceSlug===e.sourceSlug&&r.sourceSessionId===e.sourceSessionId&&r.sourceSessionOriginId===e.sourceSessionOriginId&&r.sourceMateStamp===e.sourceMateStamp&&r.sourceQueryGeneration===e.sourceQueryGeneration&&r.phase!=="clear"&&!(i.get("clayControlReceipts")||[]).some(function(o){return o.id===e.activityId&&o.stopped})}function Je(){return{window,document,identity:function(){var e=i.snap();return{ownerId:e.myUserId||null,slug:e.currentSlug,sessionId:e.activeSessionId,origin:e.sessionOriginId,connected:e.connected,runtime:e.controlRuntimeId,mateId:e.activeProjectMateId}}}}function Pt(e,t){if(!i.get("paneMode")||window.parent===window)return!1;var n=window.frameElement;if(!n)return!1;n.clayStudioSource=Je();var r=e.controlPresentation;if(r&&(!ee(r,i.snap())||!te(r)))return!0;t==="clay-pane-present-markdown"&&(e=pe(e));var o=Object.assign({},i.get("clayStudioRelays")||{});return Object.keys(o).forEach(function(s){Date.now()>o[s].evidence.deadline&&delete o[s]}),Object.keys(o).length>=100||(r&&(o[r.id]={evidence:r,socket:h()}),i.set({clayStudioRelays:o}),window.parent.postMessage({type:t,message:e,paneBinding:K(),studioSource:n.clayStudioSource.identity()},location.origin)),!0}function he(e,t){if(e.origin!==location.origin||!t||!t.studioSource)return null;var n=Array.from(document.querySelectorAll("#contextual-clay iframe, .split-pane-frame")).find(function(g){return g.contentWindow===e.source}),r=n&&n.clayStudioSource,o=r&&r.window===n.contentWindow&&r.document===n.contentDocument&&r.identity(),s=t.studioSource;if(!o||!o.connected||o.ownerId!==(i.get("myUserId")||null)||o.ownerId!==s.ownerId||o.slug!==s.slug||o.sessionId!==s.sessionId||o.origin!==s.origin||o.runtime!==s.runtime||new URL(n.src,location.href).pathname!=="/p/"+encodeURIComponent(o.slug)+"/")return null;if(n.classList.contains("split-pane-frame")){if(n.clayPane&&!N(n,t))return null;var a=i.get("splitPanes");if(!a||!a.panes.some(function(g){return g.slug===o.slug&&String(g.sessionId)===String(o.sessionId)}))return null}else{var d=n.conversation,c=d&&d.document===n.contentDocument&&d.source===n.contentWindow&&d.identity();if(!c||!c.connected||!c.available||c.ownerId!==o.ownerId||c.sessionId!==o.sessionId||c.sessionOriginId!==o.origin)return null}var u=t.message&&t.message.controlPresentation;return u&&(!X(u)||u.sourceSlug!=="mate-"+u.mateId||u.mateId!==o.mateId||!(i.get("cachedMatesList")||[]).some(function(g){return g.id===u.mateId&&g.builtinKey==="clay"&&!g.archived&&!g.lifecycleDeletion&&Z(g)===u.sourceMateStamp})||u.sourceSlug!==o.slug||u.sourceSessionId!==o.sessionId||u.sourceSessionOriginId!==o.origin||u.ownerId!==o.ownerId||u.runtimeId!==o.runtime)?null:n}function At(e,t){var n=he(e,t),r=t.message&&t.message.controlPresentation;if(!n||!r||!te(r)||Date.now()>r.deadline)return!1;var o=Object.assign({},i.get("clayStudioForwarded")||{});return Object.keys(o).forEach(function(s){Date.now()>o[s].evidence.deadline&&delete o[s]}),Object.keys(o).length>=100?!1:(o[r.id]={frame:n,document:n.contentDocument,window:e.source,data:t,evidence:r},i.set({clayStudioForwarded:o}),!0)}function Ge(e){var t=h(),n=i.get("myUserId"),r=i.get("currentSlug"),o=(i.get("clayStudioForwarded")||{})[e.id];return{valid:function(){return Date.now()>e.deadline||!te(e)||!i.get("connected")||n!==i.get("myUserId")||r!==i.get("currentSlug")||h()!==t?!1:o?o.document===o.frame.contentDocument&&o.window===o.frame.contentWindow&&!!he({origin:location.origin,source:o.window},o.data):ee(e,i.snap())},send:function(s){var a={type:"clay_studio_rendered",id:e.id,token:e.token,sessionOriginId:e.sourceSessionOriginId,revision:e.target.revision,visible:s};o?o.document===o.frame.contentDocument&&o.window.postMessage({type:"clay-studio-receipt",message:a},location.origin):h()===t&&t&&t.readyState===1&&t.send(JSON.stringify(a))}}}async function Ke(e){var t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(e)));return Array.from(new Uint8Array(t)).map(function(n){return n.toString(16).padStart(2,"0")}).join("")}function me(e,t,n,r){if(!t)return;delete t.dataset.controlSurface;var o=e.controlPresentation;if(!X(o))return;var s=Ge(o),a=!1,d,c,u=0,g={painted:!1,evidence:o,target:o.target,element:t,valid:s.valid};t.dataset.controlSurface=o.id;var l=Object.assign({},i.get("clayStudioSurfaces")||{});Object.keys(l).forEach(function(f){(!l[f].element.isConnected||l[f].element===t||Date.now()>l[f].evidence.deadline+6e3)&&delete l[f]}),l[o.id]=g,i.set({clayStudioSurfaces:l});function p(f){a||(a=!0,clearTimeout(c),cancelAnimationFrame(d),document.removeEventListener("visibilitychange",m),s.send(f))}g.cancel=function(){p(!1)};function m(){document.hidden&&p(!1)}document.addEventListener("visibilitychange",m),c=setTimeout(function(){p(!1)},Math.max(0,o.deadline-Date.now()));var D=o.target.surface==="document"?{content:e.content,exists:e.exists,size:e.size}:o.target.surface==="sketch"?e.source:e.data;Promise.all([Promise.resolve(n),Ke(D)]).then(function(f){if(f[1]!==o.target.revision){p(!1);return}function k(){if(!a){if(!s.valid()||document.hidden||t.dataset.controlSurface!==o.id){p(!1);return}u=Ye(r||t)?u+1:0,u>=2?(g.painted=!0,p(!0)):d=requestAnimationFrame(k)}}d=requestAnimationFrame(k)}).catch(function(){p(!1)})}function Ye(e){if(!e||!e.isConnected||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;var t=e.getBoundingClientRect(),n=getComputedStyle(e);if(n.visibility!=="visible"||Number(n.opacity)===0)return!1;for(var r=e.parentElement;r;r=r.parentElement){var o=getComputedStyle(r);if(o.visibility!=="visible"||Number(o.opacity)===0)return!1}var s=Math.max(0,t.left),a=Math.min(innerWidth,t.right),d=Math.max(0,t.top),c=Math.min(innerHeight,t.bottom);return a<=s||c<=d?!1:[.2,.5,.8].some(function(u){return[.2,.5,.8].some(function(g){var l=document.elementFromPoint(s+(a-s)*u,d+(c-d)*g);return l&&e.contains(l)})})}function Dt(e){var t=i.get("clayStudioSurfaces")||{},n=Object.values(t).find(function(r){return r.painted&&r.target.surface===e.surface&&r.target.key===e.key&&r.target.revision===e.revision&&r.target.runtimeId===e.runtimeId&&r.target.sourceSessionOriginId===e.sourceSessionOriginId&&r.target.sourceSessionId===e.sourceSessionId&&r.target.sourceSlug===e.sourceSlug&&r.element.dataset.controlSurface===r.evidence.id&&r.valid()});return n&&n.element}function Rt(){window.addEventListener("message",function(t){if(!(t.origin!==location.origin||t.source!==window.parent||!t.data||t.data.type!=="clay-studio-receipt")){var n=t.data.message,r=Object.assign({},i.get("clayStudioRelays")||{}),o=n&&r[n.id];!o||o.evidence.token!==n.token||!ee(o.evidence,i.snap())||h()!==o.socket||o.socket.readyState!==1||Date.now()>o.evidence.deadline||(delete r[n.id],i.set({clayStudioRelays:r}),o.socket.send(JSON.stringify(n)))}});function e(){Object.values(i.get("clayStudioSurfaces")||{}).forEach(function(t){delete t.element.dataset.controlSurface,t.cancel&&t.cancel()}),i.set({clayStudioRelays:{},clayStudioForwarded:{},clayStudioSurfaces:{}})}document.addEventListener("contextual-ask-stopped",e,!0),document.addEventListener("click",function(t){t.target.closest("#generation-stop, #autonomous-run-stop, #send-btn.stop")&&e()},!0),i.subscribe(function(t,n){(!t.connected&&n.connected||t.currentSlug!==n.currentSlug||t.activeSessionId!==n.activeSessionId||t.myUserId!==n.myUserId)&&e()})}var re=null;function O(){re||(re=requestAnimationFrame(function(){re=null,lucide.createIcons()}))}function w(e,t){return t?'<span class="'+t+'"><i data-lucide="'+e+'"></i></span>':'<i data-lucide="'+e+'"></i>'}function we(e){return!i.get("paneMode")||window.parent===window?!1:(window.parent.postMessage({type:"clay-pane-open-browser",paneBinding:K(),url:e,projectSlug:i.get("currentSlug"),sessionId:String(i.get("activeSessionId"))},window.location.origin),!0)}function _t(e,t){if(!e||e.origin!==window.location.origin||!t||!e.data||e.data.type!=="clay-pane-open-browser")return!1;var n=e.data,r=i.snap(),o=Array.from(t.querySelectorAll(".split-pane-frame")).find(function(c){return c.contentWindow===e.source}),s=o&&r.splitPanes&&r.splitPanes.panes&&r.splitPanes.panes.find(function(c){return String(c.slug)===o.dataset.projectSlug&&String(c.sessionId)===o.dataset.sessionId});if(!s||n.projectSlug!==r.currentSlug||n.projectSlug!==o.dataset.projectSlug||String(n.sessionId)!==o.dataset.sessionId)return!0;var a=new URL("/p/"+encodeURIComponent(s.slug)+"/?pane=1&session="+encodeURIComponent(s.sessionId),window.location.href).href;if(o.clayPane?!N(o,n):o.src!==a)return!0;var d=o.clayPane&&o.clayPane.identity().binding;return import("./chunk-6SM2WQJX.js").then(function(c){d&&(!N(o,n)||o.clayPane.identity().binding!==d)||c.openSharedBrowserAt(n.url)}).catch(function(c){S(c.message||"Could not open the browser.","warn")}),!0}function _(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Y(e){if(typeof e!="string"||!e.startsWith("browser:")||e.length>8200)return null;var t=e.slice(8);if(!/^https?:\/\//i.test(t)||/[\u0000-\u0020]/.test(t))return null;try{var n=new URL(t);return n.username||n.password||!["http:","https:"].includes(n.protocol)?null:n.href}catch{return null}}function $e(e,t,n){var r=Y(e);if(!r)return null;var o=String(n||"").replace(/<[^>]*>/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").trim();return(!o||o===e||o===r)&&(o=new URL(r).host),'<button type="button" class="clay-browser-link clayos-record-link" data-browser-url="'+_(r)+'" data-browser-project="'+_(i.get("currentSlug")||"")+'" title="'+_("Open in Clay Browser \xB7 "+r)+'" aria-label="'+_("Open in Clay Browser: "+o)+'">'+w("globe")+"<span>Browser</span><small>"+_(o)+"</small></button>"}function Kt(e){!e||typeof document>"u"||(e.querySelectorAll("a[href]").forEach(function(t){if(!t.closest("pre, code, button")){var n=$e(t.getAttribute("href"),"",t.textContent);if(n){var r=document.createElement("template");r.innerHTML=n,t.replaceWith(r.content)}}}),ne(),O())}function ne(){i.get("browserLinksBound")||(i.set({browserLinksBound:!0}),document.addEventListener("click",function(e){var t=e.target.closest&&e.target.closest(".clay-browser-link");if(t){e.preventDefault(),e.stopPropagation();var n=Y("browser:"+t.dataset.browserUrl);if(!n){S("This browser link is invalid.","warn");return}if(t.dataset.browserProject&&t.dataset.browserProject!==i.get("currentSlug")){S("Open this link from its original project.","warn");return}we(n)||import("./chunk-6SM2WQJX.js").then(function(r){r.openSharedBrowserAt(n)}).catch(function(r){S(r.message||"Could not open the browser.","warn")})}}))}function b(e){return ge(String(e)).replace(/"/g,""").replace(/'/g,"'")}function B(){return i.get("sharedBrowserSettings")||{}}function x(e){i.set({sharedBrowserSettings:Object.assign({},B(),e)})}function E(){return document.getElementById("shared-browser-settings")}function T(e,t,n,r){return'<button type="button" data-settings-action="'+t+'" data-target="'+b(n||"")+'" data-label="'+b(r||n||"")+'">'+b(e)+"</button>"}function ie(e,t){var n=h();if(!n||n.readyState!==1){x({error:"Reconnect to manage browser data.",pending:!1}),L();return}var r=crypto.randomUUID();x({pending:!0,requestId:r,error:"",notice:""}),n.send(JSON.stringify({type:"shared_browser_settings",sessionId:i.get("activeSessionId"),requestId:r,operation:e,target:t})),L(),setTimeout(function(){B().requestId===r&&B().pending&&(x({pending:!1,error:"The request timed out. Refresh to check the saved state."}),L())},15e3)}function F(e){var t=!!B().open;x({open:!1,review:null}),L();var n=document.querySelector('[data-action="settings"]');n&&t&&e!==!1&&n.focus()}function ve(){return'<section id="shared-browser-settings" class="shared-browser-settings" aria-label="Browser settings" hidden></section>'}function be(e){e.querySelector('[data-action="settings"]').onclick=function(){x({open:!0,page:"sites",data:null,review:null,filter:""}),ie("list"),E().querySelector('[data-settings-action="back"]').focus()},E().addEventListener("keydown",function(t){t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),F())}),E().addEventListener("input",function(t){t.target.matches("[data-settings-filter]")&&(x({filter:t.target.value}),ye(),E().dataset.key=JSON.stringify([B(),i.get("connected")]))}),E().addEventListener("click",function(t){var n=t.target.closest("[data-settings-action]");if(!(!n||n.disabled)){var r=n.dataset.settingsAction;if(r==="back"){F();return}if(r==="sites"||r==="history"){x({page:r,filter:"",review:null,notice:"",error:""}),L();return}if(r==="refresh"){ie("list");return}if(r==="cancel"){x({review:null}),L(),E().querySelector('[data-settings-action="refresh"]').focus();return}if(r==="confirm"){var o=B().review;o&&ie(o.action,o.target);return}x({notice:"",error:"",review:{action:r,target:n.dataset.target,label:n.dataset.label||n.dataset.target}}),L(),E().querySelector('[data-settings-action="cancel"]').focus()}})}function ye(){var e=E(),t=B();if(!(!e||!t.open)){var n=e.querySelector(".browser-settings-rows");if(n){var r=(t.filter||"").toLowerCase(),o=t.data||{sites:[],history:[]};t.page==="history"?n.innerHTML=o.history.filter(function(s){return s.url.toLowerCase().includes(r)}).map(function(s){return'<div class="browser-settings-row"><div><span class="browser-settings-url">'+b(s.url)+"</span><small>"+b(new Date(s.at).toLocaleString())+"</small></div>"+T("Remove","delete_history",s.id,s.url)+"</div>"}).join(""):n.innerHTML=o.sites.filter(function(s){return s.host.toLowerCase().includes(r)}).map(function(s){return"<details><summary>"+b(s.host)+"<small>"+s.cookies.length+(s.cookies.length===1?" cookie \xB7 ":" cookies \xB7 ")+s.origins.length+(s.origins.length===1?" storage origin":" storage origins")+'</small></summary><div class="browser-settings-row"><span>Cookies and site storage</span>'+T("Remove site data","delete_site",s.host)+"</div>"+s.origins.map(function(a){return'<p class="browser-settings-origin">'+b(a.origin)+"<small>"+a.localStorage+" localStorage entries \xB7 "+a.databases+" IndexedDB databases</small></p>"}).join("")+s.cookies.map(function(a){var d=a.domain+a.path+" \xB7 "+(a.expires===-1?"Session cookie":"Expires "+new Date(a.expires*1e3).toLocaleDateString())+(a.httpOnly?" \xB7 HttpOnly":"")+(a.secure?" \xB7 Secure":"")+(a.partitioned?" \xB7 Partitioned":"");return'<div class="browser-settings-row"><div><span>'+b(a.name)+"</span><small>"+b(d)+"</small></div>"+T("Remove cookie","delete_cookie",a.id,a.name+" \xB7 "+a.domain+a.path)+"</div>"}).join("")+"</details>"}).join(""),n.innerHTML||(n.innerHTML='<p class="browser-settings-muted">'+(t.pending&&!t.data?"Loading saved data\u2026":r?"No matching entries.":t.page==="history"?"No saved browsing history.":"No saved cookies or site data.")+"</p>"),n.querySelectorAll("button").forEach(function(s){s.disabled=!!t.pending||!i.get("connected")})}}}function L(){var e=E();if(e){var t=B(),n=e.closest(".shared-browser-panel"),r=i.get("sharedBrowser"),o=n.querySelector('[data-action="settings"]');if(o.hidden=!(r&&r.personalCookiesAvailable),o.disabled=!i.get("connected"),o.setAttribute("aria-expanded",String(!!t.open)),e.hidden=!t.open,n.classList.toggle("browser-settings-open",!!t.open),!!t.open){var s=JSON.stringify([t,i.get("connected")]);if(e.dataset.key!==s){e.dataset.key=s;var a=t.page||"sites";e.innerHTML='<div class="browser-settings-heading">'+T("Back to browser","back")+'<h3>Browser settings</h3></div><p class="browser-settings-muted">Personal \xB7 Shared across your Mates. Incognito tabs do not save data here.</p><nav aria-label="Browser settings sections">'+T("Cookies & site data","sites")+T("History","history")+'</nav><p class="browser-settings-muted">'+(a==="sites"?"Cookies, localStorage and IndexedDB are saved for your account. New personal tabs restore saved site storage. Removing data may sign you out. Removals also apply to open personal tabs. Sites may create new data afterwards.":"Your latest 500 page visits. Clearing this list leaves open tabs, their Back/Forward navigation and conversation activity unchanged.")+'</p><div class="browser-settings-tools"><input data-settings-filter aria-label="Filter saved browser data" placeholder="'+(a==="sites"?"Find a site":"Find a page")+'" value="'+b(t.filter||"")+'">'+T("Refresh","refresh")+T(a==="sites"?"Clear all site data":"Clear history",a==="sites"?"clear_data":"clear_history")+'</div><p class="browser-settings-feedback" role="status">'+b(t.error||(i.get("connected")?t.pending?"Updating\u2026":t.notice||"":"Disconnected. Reconnect and refresh to see current saved data."))+"</p>"+(t.review?'<div class="browser-settings-review" role="group" aria-label="Confirm removal"><strong>'+(t.review.action.includes("history")?"Remove browsing history?":"Remove saved site data?")+"</strong><p>"+(t.review.action.includes("history")?"This removes "+(t.review.action==="clear_history"?"all saved visits":"this saved visit")+" from your personal history.":t.review.action==="delete_cookie"?"This removes "+b(t.review.label)+" across your personal Mate browsers and may sign you out.":"This removes "+(t.review.action==="clear_data"?"all cookies and site storage":"cookies and storage for "+b(t.review.target))+" across your personal Mate browsers and may sign you out.")+"</p>"+T("Cancel","cancel")+T("Remove","confirm")+"</div>":"")+'<div class="browser-settings-rows"></div>',e.querySelector('[data-settings-action="'+a+'"]').setAttribute("aria-current","page"),e.querySelectorAll("button").forEach(function(d){d.disabled=d.dataset.settingsAction!=="back"&&(!!t.pending||!i.get("connected"))}),ye()}}}}function Se(e){if(!e.requestId||e.requestId!==B().requestId)return!1;if(e.type==="shared_browser_settings"){var t=!!B().review;x({data:e.settings,pending:!1,review:null,error:"",notice:t?"Removed from your saved browser data.":""})}else if(e.type==="shared_browser_error")x({pending:!1,error:e.error});else return!1;return L(),B().open&&t&&E().querySelector('[data-settings-action="refresh"]').focus(),!0}function Ie(e,t,n){var r=e.querySelector(".shared-browser-tabs"),o=i.get("sharedBrowsers")||[],s=i.get("sharedBrowser"),a=JSON.stringify([o.map(function(u){return[u.id,u.url,u.control,u.phase,u.incognito,u.personalCookiesAvailable]}),s&&s.id,i.get("connected")]);if(r.dataset.key!==a){r.dataset.key=a,r.replaceChildren(),o.forEach(function(u,g){var l=document.createElement("div");l.className="shared-browser-tab";var p=document.createElement("button");p.type="button",p.setAttribute("role","tab"),p.setAttribute("aria-selected",String(!!s&&s.id===u.id));var m="Tab "+(g+1);try{u.url&&(m=new URL(u.url).hostname)}catch{}var D=document.createElement("span");D.textContent=m+(u.personalCookiesAvailable&&u.incognito?" \xB7 Incognito":"");var f=document.createElement("small");f.textContent=u.phase==="ended"?"Ended":u.control==="agent"?"Shared":"You only",p.append(D,f),p.title=m+" \xB7 "+(u.incognito===!1?"Personal browser":"Incognito")+" \xB7 "+(u.phase==="ended"?"Ended":u.control==="agent"?"You and Clay can control this tab":"Only you can control this tab. Clay is paused."),p.onclick=function(){t(u.id)},p.onkeydown=function(y){var R=y.key==="ArrowRight"?(g+1)%o.length:y.key==="ArrowLeft"?(g+o.length-1)%o.length:y.key==="Home"?0:y.key==="End"?o.length-1:-1;R<0||(y.preventDefault(),t(o[R].id),r.querySelectorAll('[role="tab"]')[R].focus())};var k=document.createElement("button");k.type="button",k.textContent="\xD7",k.setAttribute("aria-label","Close browser tab "+(g+1)),k.disabled=!i.get("connected"),k.onclick=function(){n("close",{browserId:u.id})},l.append(p,k),r.appendChild(l)});var d=document.createElement("button");if(d.type="button",d.textContent="+",d.setAttribute("aria-label","New browser tab"),d.disabled=!i.get("connected"),d.title=s&&s.personalCookiesAvailable?"New tab \xB7 Personal browser":"New incognito tab",d.onclick=function(){n("open",{newTab:!0})},r.appendChild(d),s&&s.personalCookiesAvailable){var c=document.createElement("button");c.type="button",c.innerHTML=w("glasses"),c.setAttribute("aria-label","New incognito tab"),c.title="New incognito tab \xB7 Site data is not saved",c.disabled=!i.get("connected"),c.onclick=function(){n("open",{newTab:!0,incognito:!0})},r.appendChild(c),O()}}}var oe={},Qe={terminal:"terminal-container",browser:"shared-browser-panel","file-viewer":"file-viewer","project-logs":"project-logs-panel",you:"you-panel",issues:"issues-panel",linear:"linear-panel","notes-browser":"notes-browser","scheduled-tasks":"scheduled-tasks-panel",debates:"debates-workbench","mcp-skills":"mcp-skills-workbench","mate-knowledge":"mate-knowledge-workbench",wireframe:"wireframe-panel"};function ke(){var e=i.get("myUserId"),t=i.get("currentSlug");return import("./chunk-I57URYSL.js").then(function(n){return e!==i.get("myUserId")||t!==i.get("currentSlug")?!1:n.ensureWorkbenchLayoutPreference()}).catch(function(){return e!==i.get("myUserId")||t!==i.get("currentSlug")||i.set({workbenchLayoutPreference:Object.assign({},i.get("workbenchLayoutPreference")||{},{loading:!1,saving:!1,error:"Workbench layout could not be loaded. Try again."})}),!1})}function xe(){if(!(typeof document>"u")){var e=document.getElementById("main-panels");if(e){var t=i.get("workbenchLayoutPreference")||{},n=t.mode==="docked";e.dataset.workbenchMode=n?"docked":"overlay";var r=document.getElementById(Qe[i.get("rightWorkbenchOwner")]);if(r){var o=r.querySelector(":scope > header, :scope > .file-viewer-header .file-viewer-tabbar, :scope > .terminal-header");if(o){var s=r.querySelector(".workbench-layout-toggle");if(!s){var a=o.querySelector('[class*="window-actions"], .terminal-header-actions, .shared-browser-window, :scope.mcp-skills-header > div')||o;s=document.createElement("button"),s.type="button",s.className="workbench-layout-toggle",s.addEventListener("click",function(){var c=i.get("workbenchLayoutPreference")||{};if(!c.ready||c.loading||c.saving){ke();return}var u=i.get("myUserId"),g=i.get("currentSlug");function l(){return s.isConnected&&u===i.get("myUserId")&&g===i.get("currentSlug")}import("./chunk-I57URYSL.js").then(function(p){var m=i.get("workbenchLayoutPreference")||{};return!l()||m.mode!==c.mode||m.revision!==c.revision||m.loading||m.saving||!m.ready?!1:p.saveWorkbenchLayoutMode(c.mode==="docked"?"overlay":"docked")}).then(function(p){p===!1&&l()&&S((i.get("workbenchLayoutPreference")||{}).error||"Workbench layout could not be saved. Try again.","error")}).catch(function(p){l()&&S(p.message||"Workbench layout could not be saved. Try again.","error")})});var d=a===o?o.querySelector("[data-knowledge-wide]"):a.firstElementChild;a.insertBefore(s,d||null)}s.dataset.mode!==(n?"docked":"overlay")&&(s.dataset.mode=n?"docked":"overlay",s.innerHTML=w(n?"layers-2":"panel-right"),O()),s.setAttribute("aria-label",n?"Float workbench over sessions":"Dock workbench beside sessions"),s.title=t.error||s.getAttribute("aria-label"),s.setAttribute("aria-pressed",n?"true":"false"),s.disabled=!!t.loading||!!t.saving,s.setAttribute("aria-busy",t.loading||t.saving?"true":"false")}}}}}function Be(e,t){!e||typeof t!="function"||(oe[e]=t)}function $(e){typeof document<"u"&&ke();var t=i.get("rightWorkbenchRevision")||0,n=t+1;se(e,n);for(var r=Object.keys(oe),o=0;o<r.length;o++)if(r[o]!==e)try{oe[r[o]]()}catch{}return typeof requestAnimationFrame=="function"&&requestAnimationFrame(xe),n}function se(e,t){i.set({rightWorkbenchOwner:e,rightWorkbenchRevision:t})}function ae(e){i.get("rightWorkbenchOwner")===e&&se(null,(i.get("rightWorkbenchRevision")||0)+1)}function sr(e,t){return i.get("rightWorkbenchOwner")===e&&i.get("rightWorkbenchRevision")===t}function Ze(){se(null,(i.get("rightWorkbenchRevision")||0)+1)}i.subscribe(function(e,t){(e.workbenchLayoutPreference!==t.workbenchLayoutPreference||e.rightWorkbenchOwner!==t.rightWorkbenchOwner)&&xe(),!(e.currentSlug===t.currentSlug&&e.myUserId===t.myUserId)&&Ze()});function q(){var e=i.get("sharedBrowser");return e&&!e.handoff&&e.phase==="live"&&i.get("connected")}var Ce=50,Oe=2e3;function M(e){i.set({sharedBrowserUi:Object.assign({},i.get("sharedBrowserUi"),e)})}function z(){var e=i.get("sharedBrowserUi")||{};clearTimeout(e.moveTimer),clearTimeout(e.wheelTimer),M({moveTimer:null,move:null,wheelTimer:null,wheelDelta:0,pointer:null,composing:!1})}function Ee(e,t){function n(a){var d=e.getBoundingClientRect(),c=Math.min(d.width/e.width,d.height/e.height),u=(a.clientX-d.left-(d.width-e.width*c)/2)/c,g=(a.clientY-d.top-(d.height-e.height*c)/2)/c;return{x:Math.max(0,Math.min(e.width-1,u)),y:Math.max(0,Math.min(e.height-1,g))}}function r(){var a=i.get("sharedBrowserUi")||{};clearTimeout(a.moveTimer);var d=a.move;M({move:null,moveTimer:null}),d&&q()&&I(Object.assign({kind:"move"},d))}function o(){var a=i.get("sharedBrowserUi")||{};clearTimeout(a.wheelTimer);var d=a.wheelDelta||0;if(!q()){M({wheelDelta:0,wheelTimer:null});return}var c=Math.max(-Oe,Math.min(Oe,d)),u=d-c;M({wheelDelta:u,wheelTimer:u?setTimeout(o,Ce):null}),c&&I({kind:"wheel",deltaY:c})}e.addEventListener("pointermove",function(a){if(q()){var d=i.get("sharedBrowserUi")||{};M({move:n(a),moveTimer:d.moveTimer||setTimeout(r,40)})}}),e.addEventListener("pointerdown",function(a){!q()||a.button!==0||(a.preventDefault(),r(),o(),e.setPointerCapture(a.pointerId),M({pointer:a.pointerId}),t.focus({preventScroll:!0}),I(Object.assign({kind:"down"},n(a))))});function s(a){var d=i.get("sharedBrowserUi")||{};d.pointer===a.pointerId&&(r(),M({pointer:null}),q()&&I(Object.assign({kind:"up"},n(a))),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId))}e.addEventListener("pointerup",s),e.addEventListener("pointercancel",s),e.addEventListener("lostpointercapture",s),e.addEventListener("wheel",function(a){if(q()){a.preventDefault();var d=i.get("sharedBrowserUi")||{};M({wheelDelta:(d.wheelDelta||0)+a.deltaY,wheelTimer:d.wheelTimer||setTimeout(o,Ce)})}},{passive:!1}),e.addEventListener("focus",function(){q()&&t.focus({preventScroll:!0})}),t.addEventListener("compositionstart",function(){M({composing:!0})}),t.addEventListener("compositionend",function(){M({composing:!1}),q()&&t.value&&I({kind:"text",text:t.value}),t.value=""}),t.addEventListener("input",function(){(i.get("sharedBrowserUi")||{}).composing||(q()&&t.value&&I({kind:"text",text:t.value}),t.value="")}),t.addEventListener("keydown",function(a){if(!(!q()||a.isComposing)){var d=a.key;(a.ctrlKey||a.metaKey)&&d.toLowerCase()==="a"?d="ControlOrMeta+A":d==="Tab"&&a.shiftKey&&(d="Shift+Tab"),/^(Tab|Shift\+Tab|Enter|Backspace|Delete|Escape|ArrowLeft|ArrowRight|ArrowUp|ArrowDown|Home|End|ControlOrMeta\+A)$/.test(d)&&(a.preventDefault(),I({kind:"key",key:d}))}})}function Te(){return'<div class="shared-browser-activity"><div class="shared-browser-caption-history" role="log" aria-live="off" aria-label="Browser caption history" tabindex="0"></div><button type="button" class="shared-browser-caption-latest" hidden>Back to live \u2193</button><span class="shared-browser-caption-announcement" role="status" aria-live="polite"></span></div>'}function de(e){i.set({sharedBrowserUi:Object.assign({},i.get("sharedBrowserUi"),e)})}function Xe(e,t,n){var r=e.querySelector(".shared-browser-activity"),o=e.querySelector(".shared-browser-caption-history"),s=e.querySelector(".shared-browser-caption-latest");o.dataset.bound||(o.dataset.bound="true",o.addEventListener("scroll",function(){var f=o.scrollHeight-o.clientHeight-o.scrollTop<20;de({captionPinned:f}),r.dataset.reviewing=String(!f),s.hidden=f}),s.onclick=function(){o.scrollTop=o.scrollHeight,de({captionPinned:!0}),s.hidden=!0,r.dataset.reviewing="false"});var a=t&&t.activityHistory||[];r.hidden=!a.length;var d=a[a.length-1],c=t&&t.id+":"+a.length+":"+(d?d.id+":"+d.phase+":"+d.text:"empty"),u=i.get("sharedBrowserUi")||{};if(u.captionHistoryKey!==c){var g=u.captionBrowserId!==(t&&t.id),l=g||u.captionPinned!==!1,p=o.scrollTop;o.replaceChildren(),a.forEach(function(f,k){var y=document.createElement("div");y.className="shared-browser-caption-row",y.dataset.age=String(Math.min(a.length-k-1,3));var R=document.createElement("span");if(R.className="shared-browser-activity-text",R.textContent=f.text,y.appendChild(R),f.phase==="failed"||f.phase==="interrupted"){var le=document.createElement("small");le.textContent=f.phase==="failed"?"This step could not be completed.":"This step was interrupted.",y.appendChild(le)}o.appendChild(y)}),de({captionHistoryKey:c,captionBrowserId:t&&t.id,captionPinned:l}),o.scrollTop=l?o.scrollHeight:p,s.hidden=l,r.dataset.reviewing=String(!l);var m=e.querySelector(".shared-browser-caption-announcement"),D=n&&d?d.text+(d.phase==="failed"?" This step could not be completed.":""):"";m.textContent!==D&&(m.textContent=D)}}function Le(e,t,n){var r=t&&t.phase==="live"&&t.control==="agent"&&!t.handoff&&n;Xe(e,t,r);var o=e.querySelector("canvas"),s=r&&t.pointer,a=e.querySelector(".shared-browser-pointer");if(a.hidden=!s||s.width!==o.width||s.height!==o.height,!a.hidden){a.style.left=100*s.x/o.width+"%",a.style.top=100*s.y/o.height+"%";var d=t.id+":"+t.epoch+":"+s.sequence;(i.get("sharedBrowserUi")||{}).pointerAnimationKey!==d&&(i.set({sharedBrowserUi:Object.assign({},i.get("sharedBrowserUi"),{pointerAnimationKey:d})}),s.clicked&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&a.querySelector("i").animate([{opacity:.8,transform:"scale(.3)"},{opacity:0,transform:"scale(1.8)"}],{duration:650}))}}var ce=["1280,800","1440,900","1024,768","800,600","375,667","390,844"];function et(){return document.getElementById("shared-browser-resolution")}function qe(e){i.set({sharedBrowserUi:Object.assign({},i.get("sharedBrowserUi"),{viewportMenuOpen:e})});var t=et();t&&(t.querySelector("[data-viewport-trigger]").setAttribute("aria-expanded",String(e)),t.querySelector('[role="menu"]').hidden=!e)}function P(){qe(!1)}function Me(){return'<div id="shared-browser-resolution" class="shared-browser-resolution"><button type="button" data-viewport-trigger aria-label="Browser viewport" aria-haspopup="menu" aria-expanded="false" aria-controls="shared-browser-resolutions"><span>1280 \xD7 800</span>'+w("chevron-up")+'</button><div id="shared-browser-resolutions" class="shared-browser-resolution-menu" role="menu" aria-label="Browser resolutions" hidden></div></div>'}function Pe(e,t,n){var r=e.querySelector(".shared-browser-resolution"),o=r.querySelector("[data-viewport-trigger]");o.disabled=!n,(!n||!i.get("sharedBrowserOpen"))&&P();var s=t?t.width+","+t.height:"1280,800";o.querySelector("span").textContent=s.replace(","," \xD7 ");var a=r.querySelector('[role="menu"]');if(a.dataset.size!==s){a.dataset.size=s;var d=ce.includes(s)?ce:ce.concat([s]);a.replaceChildren(),d.forEach(function(c){var u=document.createElement("button");u.type="button",u.setAttribute("role","menuitemradio"),u.setAttribute("aria-checked",String(c===s)),u.dataset.size=c,u.tabIndex=-1,u.textContent=c.replace(","," \xD7 "),u.setAttribute("aria-label",u.textContent),a.appendChild(u)})}}function Ae(e){var t=e.querySelector(".shared-browser-resolution"),n=t.querySelector("[data-viewport-trigger]"),r=t.querySelector('[role="menu"]');function o(s){if(!n.disabled){qe(!0);var a=r.querySelectorAll("button"),d=r.querySelector('[aria-checked="true"]');(s?a[a.length-1]:d||a[0]).focus()}}n.onclick=function(){(i.get("sharedBrowserUi")||{}).viewportMenuOpen?P():o(!1)},n.onkeydown=function(s){(s.key==="ArrowDown"||s.key==="ArrowUp")&&(s.preventDefault(),o(s.key==="ArrowUp"))},r.onclick=function(s){var a=s.target.closest("[data-size]");if(!(!a||n.disabled)){var d=a.dataset.size.split(",");P(),n.focus(),I({kind:"resize",width:Number(d[0]),height:Number(d[1])})}},t.addEventListener("keydown",function(s){if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),P(),n.focus();return}if(s.key==="Tab"){P();return}if(!(s.target===n||!["ArrowDown","ArrowUp","Home","End"].includes(s.key))){s.preventDefault();var a=Array.from(r.querySelectorAll("button")),d=a.indexOf(document.activeElement);d=s.key==="Home"?0:s.key==="End"?a.length-1:(d+(s.key==="ArrowDown"?1:-1)+a.length)%a.length,a[d].focus()}}),document.addEventListener("pointerdown",function(s){t.contains(s.target)||P()}),t.addEventListener("focusout",function(s){t.contains(s.relatedTarget)||P()})}function H(){return window.matchMedia("(min-width: 1024px)").matches}function Re(){var e=i.get("permissions");return H()&&!!i.get("currentSlug")&&!i.get("dmMode")&&(!e||e.terminal!==!1)}function J(){return Re()&&!!i.get("activeSessionId")}function W(){return document.getElementById("shared-browser-panel")}function A(e){i.set({sharedBrowserUi:Object.assign({},i.get("sharedBrowserUi"),e)})}function v(e,t){var n=h();if(!n||n.readyState!==1||!i.get("activeSessionId"))return!1;var r=i.get("sharedBrowser");return n.send(JSON.stringify(Object.assign({type:"shared_browser_"+e,sessionId:i.get("activeSessionId"),browserId:r&&r.id,epoch:r&&r.epoch},t||{}))),!0}function I(e){A({error:""}),v("input",{event:e})}function Ue(){var e=W();if(!(!e||!i.get("sharedBrowserOpen"))){var t=e.querySelector(".shared-browser-viewport"),n=e.querySelector("canvas"),r=n.width===800&&n.height===600?"mac":n.width===1024&&n.height===768?"crt":n.width<n.height?"phone":"laptop";t.dataset.skin=r;var o=Math.min((t.clientWidth-96)/n.width,(t.clientHeight-140-e.querySelector(".shared-browser-caption").offsetHeight)/n.height,1);if(!(o<=0)){var s=e.querySelector(".shared-browser-monitor");s.style.width=Math.floor(n.width*o)+"px",s.style.height=Math.floor(n.height*o)+"px",e.querySelector(".shared-browser-monitor-label").textContent=n.width+" \xD7 "+n.height+" \xB7 "+Math.round(o*100)+"%"}}}function U(e,t,n){return'<button type="button" data-action="'+e+'" title="'+n+'" aria-label="'+n+'">'+w(t)+"</button>"}function ue(){if(!W()){var e=document.getElementById("main-panels");if(e){var t=document.createElement("section");t.id="shared-browser-panel",t.className="shared-browser-panel hidden",t.setAttribute("aria-label","Shared browser"),t.innerHTML='<header class="shared-browser-header"><span class="shared-browser-title">'+w("globe")+'Browser</span><span class="shared-browser-phase" role="status">Ready</span><div class="shared-browser-window">'+U("settings","settings-2","Browser settings")+U("wide","chevrons-left-right","Widen browser panel")+U("fullscreen","maximize-2","Toggle browser fullscreen")+U("hide","x","Hide browser panel")+'</div></header><div class="shared-browser-tabs" role="tablist" aria-label="Browser tabs"></div><form class="shared-browser-address">'+U("back","arrow-left","Back")+U("forward","arrow-right","Forward")+U("reload","rotate-cw","Reload")+'<input aria-label="Browser address" placeholder="Enter a URL" type="text" autocomplete="off" spellcheck="false"><button type="submit" aria-label="Open address">'+w("arrow-right")+"</button></form>"+ve()+'<div class="shared-browser-viewport"><div class="shared-browser-monitor"><div class="shared-browser-pointer-layer" aria-hidden="true"><div class="shared-browser-pointer" hidden><svg viewBox="0 0 24 28"><path d="M3 2 L3 22 L8 17 L12 26 L16 24 L12 15 L20 15 Z"/></svg><i></i></div></div><canvas width="1280" height="800" tabindex="0" aria-label="Shared browser page"></canvas><div class="shared-browser-empty">'+w("globe")+'<h3>A browser you can use with Clay</h3><p>Enter an address to browse together.<br>Localhost connects to the Clay host.</p><p class="shared-browser-private">Site data lasts only for this browser session.</p></div><textarea class="shared-browser-keyboard" aria-label="Type into shared browser" autocomplete="off" autocapitalize="off" spellcheck="false"></textarea><span class="shared-browser-monitor-brand" aria-hidden="true">Clay Studio</span><span class="shared-browser-monitor-detail" aria-hidden="true"></span><span class="shared-browser-monitor-stand" aria-hidden="true"></span></div><div class="shared-browser-caption"><span class="shared-browser-monitor-label"></span>'+Te()+'</div></div><p class="shared-browser-error hidden" role="status"></p><footer class="shared-browser-footer"><div class="shared-browser-control"><span class="shared-browser-control-status" role="status" aria-live="polite">You and Clay can control this browser</span><button type="button" data-action="control" aria-pressed="false"></button></div><div class="shared-browser-details"><span class="shared-browser-cookie-mode"></span>'+Me()+'<button type="button" data-action="end">End browser</button></div></footer>',e.appendChild(t),t.querySelector('[data-action="hide"]').onclick=V,t.querySelector('[data-action="wide"]').onclick=function(){var r=!(i.get("sharedBrowserUi")||{}).wide;A({wide:r}),C()},t.querySelector('[data-action="fullscreen"]').onclick=function(){var r=!(i.get("sharedBrowserUi")||{}).fullscreen;A({fullscreen:r}),C()},["back","forward","reload"].forEach(function(r){t.querySelector('[data-action="'+r+'"]').onclick=function(){I({kind:r})}}),t.querySelector("form").onsubmit=function(r){r.preventDefault(),I({kind:"navigate",url:t.querySelector("form input").value})},t.querySelector('[data-action="control"]').onclick=function(){var r=i.get("sharedBrowser");r&&v("control",{control:r.control==="user"?"agent":"user"})},t.querySelector('[data-action="end"]').onclick=function(){var r=i.get("sharedBrowser");v(r&&r.phase==="ended"?"open":"end",r&&r.phase==="ended"?{incognito:r.incognito}:void 0)},Ae(t),be(t);var n=new ResizeObserver(Ue);n.observe(t.querySelector(".shared-browser-viewport")),Ee(t.querySelector("canvas"),t.querySelector("textarea")),O()}}}function Q(){var e=i.get("sharedBrowser"),t=!!i.get("connected")&&!!i.get("activeSessionId"),n=i.get("connected")?i.get("activeSessionId")?e?"View browser":"Open browser":"Browser \xB7 Loading session\u2026":"Browser \xB7 Connecting\u2026";["shared-browser-btn","shared-browser-toggle-btn"].forEach(function(r){var o=document.getElementById(r);if(o){var s=r==="shared-browser-toggle-btn"&&t&&i.get("sharedBrowserOpen")?"Hide browser":n;o.classList.toggle("hidden",!Re()),o.title=t&&e?s+" \xB7 "+e.phase:s,o.setAttribute("aria-label",s),o.setAttribute("aria-expanded",String(!!i.get("sharedBrowserOpen"))),o.disabled=!t}})}function tt(e,t,n){return n?t?e.handoff?"Switching control\u2026":e.control==="user"?"Only you can control this browser. Clay is paused.":e.activity&&e.activity.phase==="running"?"Clay is working. You can also use this browser":"You and Clay can control this browser":e&&e.phase==="starting"?"Starting\u2026":"Ended":"Disconnected. Status returns on reconnect."}function rt(e,t,n,r){var o=e.querySelector(".shared-browser-control-status"),s=tt(t,n,r);o.textContent!==s&&(o.textContent=s);var a=e.querySelector('[data-action="control"]'),d=!!t&&t.control==="user",c=String(d);a.dataset.mode!==c&&(a.dataset.mode=c,a.innerHTML=w(d?"lock":"lock-open")+"<span>"+(d?"Resume shared control":"Pause Clay control")+"</span>",O()),a.title=d?"Let Clay act in this browser again. You keep control too.":"Make this browser exclusively yours until you resume shared control. You can use it either way.",a.setAttribute("aria-pressed",String(d))}function C(){Q();var e=W();if(e){Ie(e,nt,v);var t=i.get("sharedBrowser"),n=i.get("sharedBrowserUi")||{},r=i.get("connected"),o=t&&t.phase==="live",s=o&&!t.handoff&&r;e.classList.toggle("hidden",!i.get("sharedBrowserOpen")||!J()),e.classList.toggle("shared-browser-wide",!!n.wide),e.classList.toggle("panel-fullscreen",!!n.fullscreen),e.querySelector('[data-action="wide"]').setAttribute("aria-pressed",n.wide?"true":"false"),e.querySelector('[data-action="fullscreen"]').setAttribute("aria-pressed",n.fullscreen?"true":"false"),e.querySelector(".shared-browser-phase").textContent=r?t?{starting:"Starting\u2026",live:"Live",ended:"Ended \xB7 Last frame"}[t.phase]:"Ready":"Disconnected",e.querySelector(".shared-browser-phase").dataset.live=o&&r?"true":"false",e.querySelector(".shared-browser-monitor").dataset.live=o&&r?"true":"false";var a=e.querySelector("form input");document.activeElement!==a&&(a.value=t?t.url:""),e.querySelectorAll("form input, form button").forEach(function(u){u.disabled=!s}),e.querySelector("textarea").disabled=!s,e.querySelector("canvas").style.cursor=s?"default":"not-allowed",rt(e,t,o,r),e.querySelector('[data-action="control"]').disabled=!o||!!t.handoff||!r,e.querySelector('[data-action="control"]').hidden=!o,e.querySelector('[data-action="end"]').disabled=!t||!r,e.querySelector('[data-action="end"]').textContent=t&&t.phase==="ended"?"New browser":"End browser";var d=t&&t.incognito===!1;e.querySelector(".shared-browser-cookie-mode").textContent=d?"Personal browser":"Incognito",e.querySelector(".shared-browser-cookie-mode").title=d?"Cookies and site storage are saved for your account across your Mates.":"Cookies and site storage are isolated and discarded when this tab ends.",e.querySelector(".shared-browser-private").textContent=d?"Your cookies and site storage are remembered across your Mates and browser restarts.":"Site data lasts only for this browser session.";var c=n.error||t&&t.error||"";e.querySelector(".shared-browser-error").textContent=c,e.querySelector(".shared-browser-error").classList.toggle("hidden",!c),e.querySelector(".shared-browser-empty").classList.toggle("hidden",!!(t&&t.url&&n.hasFrame)),Pe(e,t,s),L(),Le(e,t,r),Ue()}}function He(e){var t=i.get("sharedBrowser");if(i.set({sharedBrowser:e}),!t||!e||t.id!==e.id){z(),P(),A({hasFrame:!1,error:"",decoding:!1,captionHistoryKey:null});var n=W();n&&n.querySelector("canvas").getContext("2d").clearRect(0,0,1920,1200)}else t.epoch!==e.epoch&&z()}function nt(e){var t=(i.get("sharedBrowsers")||[]).find(function(n){return n.id===e});t&&(He(t),v("view",{visible:H()&&!document.hidden}),C())}function Er(e){var t=Y("browser:"+e);if(!t)throw new Error("Enter a valid HTTP or HTTPS browser address.");if(!H())throw new Error("Clay Browser is available on desktop screens.");if(!J())throw new Error("Browser access is unavailable in this conversation.");if(!i.get("connected"))throw new Error("Reconnect before opening this browser link.");ue(),F(!1),$("browser"),i.set({sharedBrowserOpen:!0}),A({error:""}),v("open",{url:t}),C()}function De(){if(!(!J()||!i.get("connected"))){ue(),$("browser"),i.set({sharedBrowserOpen:!0});var e=i.get("sharedBrowser");e?v("view",{visible:!0}):v("open"),C()}}function V(){P(),F(),z(),i.get("sharedBrowserOpen")&&v("view",{visible:!1}),i.set({sharedBrowserOpen:!1}),ae("browser"),C()}function Tr(e){if(!e.type||e.type.indexOf("shared_browser_")!==0)return!1;if(String(e.sessionId)!==String(i.get("activeSessionId"))||Se(e))return!0;if(e.type==="shared_browser_state"){var t=i.get("sharedBrowser"),n=e.browsers||(e.browser?[e.browser]:[]);i.set({sharedBrowsers:n});var r=!e.focus&&t&&n.find(function(d){return d.id===t.id});r=r||e.browser||n[0]||null,He(r),e.present&&J()&&(ue(),$("browser"),i.set({sharedBrowserOpen:!0})),i.get("sharedBrowserOpen")&&r&&v("view",{visible:H()&&!document.hidden}),C()}else if(e.type==="shared_browser_error")A({error:e.error}),C();else if(e.type==="shared_browser_frame"){var o=i.get("sharedBrowser");if(!H()||!i.get("sharedBrowserOpen")||!o||o.id!==e.browserId||(i.get("sharedBrowserUi")||{}).decoding)return!0;var s=i.get("activeSessionId");A({decoding:!0});var a=new Image;a.onload=function(){var d=i.get("sharedBrowser");if(d&&d.id===e.browserId&&i.get("activeSessionId")===s&&W()){var c=W().querySelector("canvas");c.width=a.naturalWidth,c.height=a.naturalHeight,c.getContext("2d").drawImage(a,0,0),A({decoding:!1,hasFrame:!0}),C(),me(e,c,null,c)}},a.onerror=function(){i.get("activeSessionId")===s&&A({decoding:!1})},a.src="data:image/jpeg;base64,"+e.data}return!0}function Lr(){ne();var e=document.getElementById("shared-browser-btn");e&&(e.onclick=De);var t=document.getElementById("shared-browser-toggle-btn");t&&(t.onclick=function(){i.get("sharedBrowserOpen")?V():De()}),window.matchMedia("(min-width: 1024px)").addEventListener("change",function(){H()||V(),Q()}),document.addEventListener("visibilitychange",function(){i.get("sharedBrowserOpen")&&v("view",{visible:!document.hidden&&H()})}),O(),Q(),i.get("connected")&&v("state_request")}Be("browser",V);i.subscribe(function(e,t){e.currentSlug!==t.currentSlug||e.activeSessionId!==t.activeSessionId||e.myUserId!==t.myUserId?(z(),ae("browser"),i.set({sharedBrowser:null,sharedBrowsers:[],sharedBrowserOpen:!1,sharedBrowserUi:{},sharedBrowserSettings:{}}),e.connected&&v("state_request"),C()):e.connected!==t.connected?(e.connected&&v("state_request"),C()):(e.permissions!==t.permissions||e.dmMode!==t.dmMode)&&(J()||V(),Q())});export{S as a,it as b,ge as c,ct as d,We as e,ut as f,fe as g,lt as h,gt as i,Ne as j,_e as k,mt as l,G as m,Fe as n,ze as o,N as p,K as q,wt as r,vt as s,Ve as t,Z as u,St as v,It as w,xt as x,Pt as y,he as z,At as A,me as B,Dt as C,Rt as D,O as E,w as F,Be as G,$ as H,ae as I,sr as J,I as K,Er as L,De as M,V as N,Tr as O,Lr as P,_t as Q,$e as R,Kt as S};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as b,B as c,z as a}from"./chunk-IZ2ZANEY.js";import"./chunk-7H36SUZA.js";import"./chunk-DGOFGEUK.js";export{a as closeLoginBrowser,c as handleLoginBrowserMessage,b as openLoginBrowser};
|