@agentknight/sdk 0.9.56 → 0.9.59
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/dist/chunks/{acp-adapter-HUNUQGUF.js → acp-adapter-OGD5QSNI.js} +4 -3
- package/dist/chunks/{chunk-E7QL4CBT.js → chunk-2MERNOK6.js} +1 -1
- package/dist/chunks/{chunk-L3A736SO.js → chunk-3OIHMMDF.js} +2 -66
- package/dist/chunks/chunk-5DVJ7Y5W.js +72 -0
- package/dist/chunks/{chunk-Z5STULMQ.js → chunk-AREU4R62.js} +3 -2
- package/dist/chunks/chunk-DP5KVGWF.js +572 -0
- package/dist/chunks/{chunk-NTFNQYQ3.js → chunk-FDUJP3WA.js} +2 -2
- package/dist/chunks/{chunk-K5CMKBW6.js → chunk-LO4ZRE77.js} +799 -433
- package/dist/chunks/{chunk-6ZPE7VIE.js → chunk-LWJNDBIM.js} +447 -1232
- package/dist/chunks/{chunk-5J7BK2Y7.js → chunk-NDEJOXSX.js} +1 -1
- package/dist/chunks/{chunk-HFVA7ZOD.js → chunk-X3ZG6WMN.js} +2 -3
- package/dist/chunks/chunk-ZDKBJFA2.js +1217 -0
- package/dist/chunks/{claude-adapter-G6YTPXRP.js → claude-adapter-DGZBZSWJ.js} +209 -58
- package/dist/chunks/{codex-adapter-ELYJE2A2.js → codex-adapter-2W7RRER3.js} +4 -3
- package/dist/chunks/{copilot-adapter-2QAIOSEK.js → copilot-adapter-ZEHU6CFQ.js} +554 -635
- package/dist/chunks/{managed-agent-adapter-KEXZFLGA.js → managed-agent-adapter-CGJPJZ2Z.js} +28 -6
- package/dist/chunks/{pi-adapter-5BFIJTPD.js → pi-adapter-WOVSWBGG.js} +4 -3
- package/dist/configuration.js +4 -3
- package/dist/index.d.ts +177 -1
- package/dist/index.js +1494 -581
- package/dist/runtime.js +2 -2
- package/dist/session-analytics-worker.js +585 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
detectClaude,
|
|
3
|
+
detectCopilot,
|
|
4
|
+
detectPi,
|
|
5
|
+
hasLocalExecutable
|
|
6
|
+
} from "./chunks/chunk-T6226JFS.js";
|
|
1
7
|
import {
|
|
2
8
|
DataDirectoryLease,
|
|
3
9
|
PEER_CHAT_TIMEOUT_MS,
|
|
4
10
|
PeerChatRequestSchema,
|
|
5
11
|
PeerChatResultSchema,
|
|
6
12
|
validateDataDirectory
|
|
7
|
-
} from "./chunks/chunk-
|
|
13
|
+
} from "./chunks/chunk-AREU4R62.js";
|
|
8
14
|
import {
|
|
9
15
|
DeviceIdentitySchema,
|
|
10
16
|
codingAgentPresentation,
|
|
@@ -14,21 +20,22 @@ import {
|
|
|
14
20
|
AgentSelectionSchema,
|
|
15
21
|
assertSelectionSnapshotFits,
|
|
16
22
|
supportsAgentSelection
|
|
17
|
-
} from "./chunks/chunk-
|
|
23
|
+
} from "./chunks/chunk-FDUJP3WA.js";
|
|
18
24
|
import {
|
|
19
|
-
ConversationNormalizer,
|
|
20
25
|
LiveTimelineProjection,
|
|
21
26
|
OperationDiagnostics,
|
|
22
27
|
OperationMetrics,
|
|
23
28
|
PromptPreparationError,
|
|
29
|
+
SessionDirectoryError,
|
|
30
|
+
SessionDirectoryLister,
|
|
24
31
|
SessionImageUploadError,
|
|
25
32
|
SessionImageUploader,
|
|
26
33
|
SessionProjectIdentityError,
|
|
27
34
|
SessionRuntime,
|
|
35
|
+
contained,
|
|
28
36
|
diagnosticError,
|
|
29
37
|
diagnosticReference,
|
|
30
38
|
diagnosticRequest,
|
|
31
|
-
isDisplayableHumanMessage,
|
|
32
39
|
isSessionRestoreFailure,
|
|
33
40
|
measureOperationPhase,
|
|
34
41
|
projectWorkbenchInsights,
|
|
@@ -37,39 +44,41 @@ import {
|
|
|
37
44
|
recordTimelineSyncDiagnostic,
|
|
38
45
|
resolveGitProjectIdentity,
|
|
39
46
|
sessionRestoreFailure,
|
|
47
|
+
sessionRootIdentity,
|
|
40
48
|
validateOperationResponse
|
|
41
|
-
} from "./chunks/chunk-
|
|
49
|
+
} from "./chunks/chunk-LWJNDBIM.js";
|
|
42
50
|
import {
|
|
43
51
|
SessionImageRelayUrlSchema,
|
|
44
52
|
SessionImagesConfigSchema
|
|
45
53
|
} from "./chunks/chunk-IJPJQF7S.js";
|
|
46
54
|
import {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
} from "./chunks/chunk-
|
|
55
|
+
ConversationNormalizer,
|
|
56
|
+
isDisplayableHumanMessage
|
|
57
|
+
} from "./chunks/chunk-ZDKBJFA2.js";
|
|
50
58
|
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
detectPi,
|
|
54
|
-
hasLocalExecutable
|
|
55
|
-
} from "./chunks/chunk-T6226JFS.js";
|
|
59
|
+
GroupChatError
|
|
60
|
+
} from "./chunks/chunk-X3ZG6WMN.js";
|
|
56
61
|
import {
|
|
57
62
|
assistantPreview,
|
|
58
63
|
isContentfulAssistant,
|
|
59
64
|
userPreview
|
|
60
|
-
} from "./chunks/chunk-
|
|
65
|
+
} from "./chunks/chunk-NDEJOXSX.js";
|
|
61
66
|
import {
|
|
62
67
|
AgentModelListingError,
|
|
63
68
|
AgentSessionRenameError,
|
|
64
69
|
CODING_AGENT_IDS,
|
|
65
|
-
SessionOperationError,
|
|
66
|
-
SessionOperations,
|
|
67
70
|
TimelinePageBudgetError,
|
|
68
71
|
UnsupportedAgentOperationError,
|
|
69
72
|
captureResearchAccess,
|
|
70
|
-
captureWorkbenchAccess
|
|
71
|
-
|
|
73
|
+
captureWorkbenchAccess,
|
|
74
|
+
validateSessionName
|
|
75
|
+
} from "./chunks/chunk-5DVJ7Y5W.js";
|
|
76
|
+
import {
|
|
77
|
+
SessionOperationError,
|
|
78
|
+
SessionOperations
|
|
79
|
+
} from "./chunks/chunk-3OIHMMDF.js";
|
|
72
80
|
import {
|
|
81
|
+
A2A_BODY_MAX_LENGTH,
|
|
73
82
|
A2aRelayRequestSchema,
|
|
74
83
|
A2aRelayResponseSchema,
|
|
75
84
|
AGENT_CONTROLS_CAPABILITY,
|
|
@@ -86,11 +95,19 @@ import {
|
|
|
86
95
|
DEVICE_TEXT_INPUT_VERSION,
|
|
87
96
|
DeviceTextInputDataSchema,
|
|
88
97
|
DeviceTextInputResultSchema,
|
|
98
|
+
ENCRYPTED_GROUP_CREATE_OPERATION,
|
|
99
|
+
ENCRYPTED_PEER_AUTHORIZE_OPERATION,
|
|
100
|
+
ENCRYPTED_PEER_MAX_LENGTH,
|
|
101
|
+
ENCRYPTED_PEER_VERSION,
|
|
102
|
+
EncryptedGroupCreateSchema,
|
|
103
|
+
EncryptedPeerAuthorizationSchema,
|
|
104
|
+
EncryptedPeerMessageSchema,
|
|
89
105
|
GROUP_CHAT_CREATE_CAPABILITY,
|
|
90
106
|
GROUP_CHAT_CREATE_OPERATION,
|
|
91
107
|
GROUP_CHAT_CREATE_VERSION,
|
|
92
108
|
GroupChatCreateDataSchema,
|
|
93
109
|
GroupChatCreateResultDataSchema,
|
|
110
|
+
GroupChatInfoSchema,
|
|
94
111
|
INTERACTION_DISMISS_RESPONSE_CAPABILITY,
|
|
95
112
|
INTERACTION_SUPERSEDED_ERROR_CODE,
|
|
96
113
|
IdSchema,
|
|
@@ -111,6 +128,7 @@ import {
|
|
|
111
128
|
PAIRING_URI_HOST,
|
|
112
129
|
PAIRING_URI_SCHEME,
|
|
113
130
|
PC_A2A_CAPABILITY,
|
|
131
|
+
PC_ENCRYPTED_PEER_CAPABILITY,
|
|
114
132
|
PC_IMAGE_BLOB_POLICY_CAPABILITY,
|
|
115
133
|
PC_PEER_CHAT_CAPABILITY,
|
|
116
134
|
PROTOCOL_VERSION,
|
|
@@ -133,8 +151,6 @@ import {
|
|
|
133
151
|
SESSION_DELETE_CAPABILITY,
|
|
134
152
|
SESSION_DIRECTORY_LIST_OPERATION,
|
|
135
153
|
SESSION_DIRECTORY_LIST_VERSION,
|
|
136
|
-
SESSION_DIRECTORY_MAX_ENTRIES,
|
|
137
|
-
SESSION_DIRECTORY_MAX_RESPONSE_BYTES,
|
|
138
154
|
SESSION_FILE_ATTACHMENTS_CAPABILITY,
|
|
139
155
|
SESSION_FILE_DOWNLOAD_MAX_ORIGINAL_BYTES,
|
|
140
156
|
SESSION_FILE_DOWNLOAD_OPERATION,
|
|
@@ -157,6 +173,7 @@ import {
|
|
|
157
173
|
SESSION_GIT_DIFF_OPERATION,
|
|
158
174
|
SESSION_GIT_DIFF_PARTIAL_VERSION,
|
|
159
175
|
SESSION_GIT_DIFF_VERSION,
|
|
176
|
+
SESSION_IMAGE_CLIENT_VERIFIED_CAPABILITY,
|
|
160
177
|
SESSION_IMAGE_MAX_BYTES,
|
|
161
178
|
SESSION_IMAGE_MAX_PIXELS,
|
|
162
179
|
SESSION_IMAGE_STORAGE_CAPABILITY,
|
|
@@ -173,11 +190,14 @@ import {
|
|
|
173
190
|
SESSION_RESOURCE_MAX_ORIGINAL_BYTES,
|
|
174
191
|
SESSION_RESOURCE_READ_OPERATION,
|
|
175
192
|
SESSION_RESOURCE_READ_VERSION,
|
|
193
|
+
SESSION_STATE_FILES_CAPABILITY,
|
|
176
194
|
SESSION_TIMELINE_PAGE_SIZE,
|
|
177
195
|
SESSION_WORKTREE_CREATION_CAPABILITY,
|
|
178
196
|
SecureMessageSchema,
|
|
179
197
|
SessionAbortRequestSchema,
|
|
180
198
|
SessionActivityUpdateSchema,
|
|
199
|
+
SessionAnalyticsRequestSchema,
|
|
200
|
+
SessionAnalyticsResultSchema,
|
|
181
201
|
SessionCommunicationDataSchema,
|
|
182
202
|
SessionCommunicationRequestSchema,
|
|
183
203
|
SessionCommunicationSchema,
|
|
@@ -209,6 +229,7 @@ import {
|
|
|
209
229
|
SessionRenameResultDataSchema,
|
|
210
230
|
SessionResourceReadDataSchema,
|
|
211
231
|
SessionResourceReadResultDataSchema,
|
|
232
|
+
SessionSummarySchema,
|
|
212
233
|
SessionTimelineInvalidatedSchema,
|
|
213
234
|
SessionTimelinePageRequestSchema,
|
|
214
235
|
SessionTimelinePageSchema,
|
|
@@ -246,6 +267,8 @@ import {
|
|
|
246
267
|
WorkbenchQueueMutationRequestSchema,
|
|
247
268
|
WorkbenchQueueMutationResultSchema,
|
|
248
269
|
WorkbenchQueueSnapshotSchema,
|
|
270
|
+
WorkbenchReasoningPageSchema,
|
|
271
|
+
WorkbenchReasoningRequestSchema,
|
|
249
272
|
WorkbenchResearchCreateRequestSchema,
|
|
250
273
|
WorkbenchResearchCreateResultSchema,
|
|
251
274
|
WorkbenchResearchListResultSchema,
|
|
@@ -263,12 +286,12 @@ import {
|
|
|
263
286
|
sessionCommunicationError,
|
|
264
287
|
sessionCommunicationOperationCapability,
|
|
265
288
|
workbenchCapability
|
|
266
|
-
} from "./chunks/chunk-
|
|
289
|
+
} from "./chunks/chunk-LO4ZRE77.js";
|
|
267
290
|
|
|
268
291
|
// src/initialize.ts
|
|
269
|
-
import { createHash as
|
|
270
|
-
import { readFile as
|
|
271
|
-
import { z as
|
|
292
|
+
import { createHash as createHash18 } from "node:crypto";
|
|
293
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
294
|
+
import { z as z12 } from "zod";
|
|
272
295
|
|
|
273
296
|
// src/coding-agent-factory.ts
|
|
274
297
|
import { resolve } from "node:path";
|
|
@@ -283,7 +306,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
|
|
|
283
306
|
switch (engine.kind) {
|
|
284
307
|
case "managed": {
|
|
285
308
|
if (owner === void 0) throw new Error("Managed coding agents require the PC owner identity");
|
|
286
|
-
const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-
|
|
309
|
+
const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-CGJPJZ2Z.js");
|
|
287
310
|
return new ManagedCodingAgentAdapter({
|
|
288
311
|
dataDirectory: config.dataDirectory,
|
|
289
312
|
owner,
|
|
@@ -325,7 +348,13 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
|
|
|
325
348
|
id: "claude",
|
|
326
349
|
name: codingAgentPresentation("claude").name,
|
|
327
350
|
detect: detectClaude,
|
|
328
|
-
create: () => createCodingAgentAdapter({
|
|
351
|
+
create: () => createCodingAgentAdapter({
|
|
352
|
+
...config,
|
|
353
|
+
codingAgent: {
|
|
354
|
+
kind: "claude",
|
|
355
|
+
...engine.claudeCommand === void 0 ? {} : { command: engine.claudeCommand }
|
|
356
|
+
}
|
|
357
|
+
}, onDiagnostic, owner)
|
|
329
358
|
},
|
|
330
359
|
{
|
|
331
360
|
id: "acp",
|
|
@@ -340,13 +369,21 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
|
|
|
340
369
|
});
|
|
341
370
|
}
|
|
342
371
|
case "copilot": {
|
|
343
|
-
const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-
|
|
372
|
+
const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-ZEHU6CFQ.js");
|
|
344
373
|
if (owner !== void 0) {
|
|
345
|
-
return new GithubCopilotAdapter(
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
374
|
+
return new GithubCopilotAdapter(
|
|
375
|
+
void 0,
|
|
376
|
+
void 0,
|
|
377
|
+
void 0,
|
|
378
|
+
{
|
|
379
|
+
dataDirectory: config.dataDirectory,
|
|
380
|
+
owner,
|
|
381
|
+
enabled: config.groupChatEnabled ?? true
|
|
382
|
+
},
|
|
383
|
+
config.peerChatEnabled !== false,
|
|
384
|
+
resolve(config.dataDirectory, "schedule-drafts"),
|
|
385
|
+
resolve(config.dataDirectory, "analytics")
|
|
386
|
+
);
|
|
350
387
|
}
|
|
351
388
|
if (config.groupChatEnabled) throw new Error("Group chat requires the PC owner identity");
|
|
352
389
|
return new GithubCopilotAdapter(
|
|
@@ -355,18 +392,19 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
|
|
|
355
392
|
void 0,
|
|
356
393
|
void 0,
|
|
357
394
|
config.peerChatEnabled !== false,
|
|
358
|
-
resolve(config.dataDirectory, "schedule-drafts")
|
|
395
|
+
resolve(config.dataDirectory, "schedule-drafts"),
|
|
396
|
+
resolve(config.dataDirectory, "analytics")
|
|
359
397
|
);
|
|
360
398
|
}
|
|
361
399
|
case "pi": {
|
|
362
400
|
assertPiRuntimeSupported();
|
|
363
|
-
const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-
|
|
401
|
+
const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-WOVSWBGG.js");
|
|
364
402
|
return new PiCodingAgentAdapter(
|
|
365
403
|
engine.agentDirectory === void 0 ? {} : { agentDirectory: resolve(engine.agentDirectory) }
|
|
366
404
|
);
|
|
367
405
|
}
|
|
368
406
|
case "codex": {
|
|
369
|
-
const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-
|
|
407
|
+
const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-2W7RRER3.js");
|
|
370
408
|
return new CodexCodingAgentAdapter({
|
|
371
409
|
dataDirectory: resolve(config.dataDirectory, "coding-agents"),
|
|
372
410
|
...owner === void 0 ? {} : { nativeSessionOwner: owner },
|
|
@@ -375,15 +413,16 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
|
|
|
375
413
|
});
|
|
376
414
|
}
|
|
377
415
|
case "claude": {
|
|
378
|
-
const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-
|
|
416
|
+
const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-DGZBZSWJ.js");
|
|
379
417
|
return new ClaudeCodingAgentAdapter({
|
|
380
418
|
dataDirectory: resolve(config.dataDirectory, "coding-agents"),
|
|
419
|
+
...engine.command === void 0 ? {} : { command: engine.command },
|
|
381
420
|
...owner === void 0 ? {} : { nativeSessionOwner: owner },
|
|
382
421
|
...onDiagnostic === void 0 ? {} : { onDiagnostic }
|
|
383
422
|
});
|
|
384
423
|
}
|
|
385
424
|
case "acp": {
|
|
386
|
-
const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-
|
|
425
|
+
const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-OGD5QSNI.js");
|
|
387
426
|
return new AcpCodingAgentAdapter({
|
|
388
427
|
command: engine.command,
|
|
389
428
|
args: engine.args,
|
|
@@ -508,7 +547,7 @@ async function loadOrCreateContentKey(dataDirectory) {
|
|
|
508
547
|
await rename(temporaryPath, path);
|
|
509
548
|
return material;
|
|
510
549
|
}
|
|
511
|
-
async function createPersistentContentCipher(dataDirectory, key) {
|
|
550
|
+
async function createPersistentContentCipher(dataDirectory, key, options = {}) {
|
|
512
551
|
await mkdir(dataDirectory, { recursive: true });
|
|
513
552
|
const path = join(dataDirectory, "content-replay.log");
|
|
514
553
|
let processedMessages = /* @__PURE__ */ new Map();
|
|
@@ -520,10 +559,12 @@ async function createPersistentContentCipher(dataDirectory, key) {
|
|
|
520
559
|
compactOnNextWrite = entries.some((entry) => entry.keyId !== key.keyId);
|
|
521
560
|
for (const entry of entries) {
|
|
522
561
|
if (entry.keyId === key.keyId) {
|
|
562
|
+
if (options.rejectReplayOverflow && entry.sentAt < Date.now() - DEFAULT_REPLAY_WINDOW_MS) continue;
|
|
523
563
|
processedMessages.set(entry.messageId, entry.sentAt);
|
|
524
564
|
}
|
|
525
565
|
}
|
|
526
566
|
while (processedMessages.size > MAX_REPLAY_ENTRIES) {
|
|
567
|
+
if (options.rejectReplayOverflow) throw new Error("Encrypted replay journal exceeds its capacity");
|
|
527
568
|
const oldest = processedMessages.keys().next().value;
|
|
528
569
|
if (oldest === void 0) {
|
|
529
570
|
break;
|
|
@@ -537,6 +578,7 @@ async function createPersistentContentCipher(dataDirectory, key) {
|
|
|
537
578
|
}
|
|
538
579
|
let writesSinceCompaction = 0;
|
|
539
580
|
return new ContentCipher(key, {
|
|
581
|
+
...options,
|
|
540
582
|
processedMessages,
|
|
541
583
|
persistProcessedMessages: (entries) => {
|
|
542
584
|
const newest = [...entries].at(-1);
|
|
@@ -602,6 +644,7 @@ var ContentCipher = class {
|
|
|
602
644
|
#randomBytes;
|
|
603
645
|
#createMessageId;
|
|
604
646
|
#replayWindowMs;
|
|
647
|
+
#rejectReplayOverflow;
|
|
605
648
|
#processedMessages;
|
|
606
649
|
#persistProcessedMessages;
|
|
607
650
|
constructor(key, options = {}) {
|
|
@@ -610,6 +653,7 @@ var ContentCipher = class {
|
|
|
610
653
|
this.#randomBytes = options.randomBytes ?? randomBytes;
|
|
611
654
|
this.#createMessageId = options.createMessageId ?? randomUUID;
|
|
612
655
|
this.#replayWindowMs = options.replayWindowMs ?? DEFAULT_REPLAY_WINDOW_MS;
|
|
656
|
+
this.#rejectReplayOverflow = options.rejectReplayOverflow === true;
|
|
613
657
|
this.#processedMessages = new Map(options.processedMessages);
|
|
614
658
|
this.#persistProcessedMessages = options.persistProcessedMessages;
|
|
615
659
|
}
|
|
@@ -714,6 +758,9 @@ var ContentCipher = class {
|
|
|
714
758
|
});
|
|
715
759
|
}
|
|
716
760
|
const payload = decode2(plaintext);
|
|
761
|
+
if (this.#rejectReplayOverflow && activeReplayEntries.size >= MAX_REPLAY_ENTRIES) {
|
|
762
|
+
throw new Error("Encrypted replay protection is full; wait for its time window to expire");
|
|
763
|
+
}
|
|
717
764
|
while (activeReplayEntries.size >= MAX_REPLAY_ENTRIES) {
|
|
718
765
|
const oldest = activeReplayEntries.keys().next().value;
|
|
719
766
|
if (oldest === void 0) {
|
|
@@ -927,163 +974,18 @@ var ApprovedPairingProvider = class extends CachedPairingProvider {
|
|
|
927
974
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
928
975
|
|
|
929
976
|
// src/research-tools.ts
|
|
930
|
-
import { createHash as
|
|
931
|
-
import { lstat as
|
|
932
|
-
import { isAbsolute as
|
|
977
|
+
import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
|
|
978
|
+
import { lstat as lstat2, realpath as realpath2, stat as stat2 } from "node:fs/promises";
|
|
979
|
+
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
933
980
|
import { gunzipSync } from "node:zlib";
|
|
934
981
|
import { z as z4 } from "zod";
|
|
935
982
|
|
|
936
|
-
// src/session-directory.ts
|
|
937
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
938
|
-
import { lstat, opendir, realpath, stat } from "node:fs/promises";
|
|
939
|
-
import { isAbsolute, join as join2, relative, sep } from "node:path";
|
|
940
|
-
var SESSION_DIRECTORY_CONCURRENCY = 4;
|
|
941
|
-
var SESSION_DIRECTORY_TIMEOUT_MS = 5e3;
|
|
942
|
-
var SessionDirectoryError = class extends Error {
|
|
943
|
-
constructor(code, message, options) {
|
|
944
|
-
super(message, options);
|
|
945
|
-
this.code = code;
|
|
946
|
-
}
|
|
947
|
-
code;
|
|
948
|
-
};
|
|
949
|
-
function fail(code, message) {
|
|
950
|
-
throw new SessionDirectoryError(code, message);
|
|
951
|
-
}
|
|
952
|
-
function contained(root, candidate) {
|
|
953
|
-
const path = relative(root, candidate);
|
|
954
|
-
return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
|
|
955
|
-
}
|
|
956
|
-
function sessionRootIdentity(root, info) {
|
|
957
|
-
return `${root}\0${info.dev}\0${info.ino}`;
|
|
958
|
-
}
|
|
959
|
-
var SessionDirectoryLister = class {
|
|
960
|
-
constructor(metadata) {
|
|
961
|
-
this.metadata = metadata;
|
|
962
|
-
}
|
|
963
|
-
metadata;
|
|
964
|
-
#active = 0;
|
|
965
|
-
async list(sessionId, path) {
|
|
966
|
-
if (!isSafeSessionDirectoryPath(path)) {
|
|
967
|
-
fail("INVALID_DIRECTORY_PATH", "The directory path is not allowed");
|
|
968
|
-
}
|
|
969
|
-
if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) {
|
|
970
|
-
fail("DIRECTORY_BUSY", "Too many directory requests");
|
|
971
|
-
}
|
|
972
|
-
this.#active++;
|
|
973
|
-
const deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
|
|
974
|
-
const checkDeadline = () => {
|
|
975
|
-
if (Date.now() >= deadline) fail("DIRECTORY_TIMEOUT", "The directory request timed out");
|
|
976
|
-
};
|
|
977
|
-
const work = this.#list(sessionId, path, checkDeadline).finally(() => {
|
|
978
|
-
this.#active--;
|
|
979
|
-
});
|
|
980
|
-
let timer;
|
|
981
|
-
try {
|
|
982
|
-
return await Promise.race([
|
|
983
|
-
work,
|
|
984
|
-
new Promise((_, reject) => {
|
|
985
|
-
timer = setTimeout(() => reject(new SessionDirectoryError(
|
|
986
|
-
"DIRECTORY_TIMEOUT",
|
|
987
|
-
"The directory request timed out"
|
|
988
|
-
)), SESSION_DIRECTORY_TIMEOUT_MS);
|
|
989
|
-
})
|
|
990
|
-
]);
|
|
991
|
-
} catch (error) {
|
|
992
|
-
if (error instanceof SessionDirectoryError) throw error;
|
|
993
|
-
throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "The directory is unavailable", { cause: error });
|
|
994
|
-
} finally {
|
|
995
|
-
clearTimeout(timer);
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
async #list(sessionId, path, checkDeadline) {
|
|
999
|
-
const metadata = await this.metadata(sessionId);
|
|
1000
|
-
checkDeadline();
|
|
1001
|
-
if (metadata === void 0) fail("SESSION_NOT_FOUND", "The session is unavailable");
|
|
1002
|
-
const workingDirectory = metadata.workingDirectory;
|
|
1003
|
-
if (!workingDirectory || !isAbsolute(workingDirectory)) {
|
|
1004
|
-
fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
|
|
1005
|
-
}
|
|
1006
|
-
let root;
|
|
1007
|
-
let rootIdentity;
|
|
1008
|
-
try {
|
|
1009
|
-
root = await realpath(workingDirectory);
|
|
1010
|
-
const info = await stat(root, { bigint: true });
|
|
1011
|
-
if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
|
|
1012
|
-
rootIdentity = sessionRootIdentity(root, info);
|
|
1013
|
-
} catch (error) {
|
|
1014
|
-
throw new SessionDirectoryError(
|
|
1015
|
-
"SESSION_ROOT_UNAVAILABLE",
|
|
1016
|
-
"The session working directory is unavailable",
|
|
1017
|
-
{ cause: error }
|
|
1018
|
-
);
|
|
1019
|
-
}
|
|
1020
|
-
checkDeadline();
|
|
1021
|
-
let target = root;
|
|
1022
|
-
for (const segment of path === "" ? [] : path.split("/")) {
|
|
1023
|
-
target = join2(target, segment);
|
|
1024
|
-
const info = await lstat(target);
|
|
1025
|
-
checkDeadline();
|
|
1026
|
-
if (info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be opened");
|
|
1027
|
-
if (!info.isDirectory()) fail("NOT_A_DIRECTORY", "The selected entry is not a directory");
|
|
1028
|
-
if (!contained(root, await realpath(target))) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
|
|
1029
|
-
checkDeadline();
|
|
1030
|
-
}
|
|
1031
|
-
const canonicalTarget = await realpath(target);
|
|
1032
|
-
if (!contained(root, canonicalTarget)) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
|
|
1033
|
-
checkDeadline();
|
|
1034
|
-
const directory = await opendir(target, { bufferSize: 32 });
|
|
1035
|
-
const entries = [];
|
|
1036
|
-
let bytes = 8192;
|
|
1037
|
-
try {
|
|
1038
|
-
checkDeadline();
|
|
1039
|
-
for (; ; ) {
|
|
1040
|
-
const entry = await directory.read();
|
|
1041
|
-
checkDeadline();
|
|
1042
|
-
if (entry === null) break;
|
|
1043
|
-
if (entries.length >= SESSION_DIRECTORY_MAX_ENTRIES) {
|
|
1044
|
-
fail("DIRECTORY_LIMIT_EXCEEDED", "The directory has too many entries");
|
|
1045
|
-
}
|
|
1046
|
-
let kind = "blocked";
|
|
1047
|
-
if (isSafeSessionDirectoryPath(entry.name) && !entry.name.includes("/")) {
|
|
1048
|
-
const child = join2(target, entry.name);
|
|
1049
|
-
const info = await lstat(child);
|
|
1050
|
-
checkDeadline();
|
|
1051
|
-
if (!info.isSymbolicLink() && contained(root, await realpath(child))) {
|
|
1052
|
-
kind = info.isDirectory() ? "directory" : info.isFile() ? "file" : "blocked";
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
const result = { name: entry.name, kind };
|
|
1056
|
-
bytes += Buffer.byteLength(JSON.stringify(result), "utf8") + 1;
|
|
1057
|
-
if (bytes > SESSION_DIRECTORY_MAX_RESPONSE_BYTES) {
|
|
1058
|
-
fail("DIRECTORY_LIMIT_EXCEEDED", "The directory listing is too large");
|
|
1059
|
-
}
|
|
1060
|
-
entries.push(result);
|
|
1061
|
-
}
|
|
1062
|
-
const latestMetadata = await this.metadata(sessionId);
|
|
1063
|
-
const latestRoot = await realpath(workingDirectory);
|
|
1064
|
-
const latestInfo = await stat(latestRoot, { bigint: true });
|
|
1065
|
-
if (latestMetadata?.workingDirectory !== workingDirectory || sessionRootIdentity(latestRoot, latestInfo) !== rootIdentity || await realpath(target) !== canonicalTarget) {
|
|
1066
|
-
fail("SESSION_ROOT_CHANGED", "The session directory changed");
|
|
1067
|
-
}
|
|
1068
|
-
checkDeadline();
|
|
1069
|
-
} finally {
|
|
1070
|
-
await directory.close();
|
|
1071
|
-
}
|
|
1072
|
-
const order = { directory: 0, file: 1, blocked: 2 };
|
|
1073
|
-
entries.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
|
|
1074
|
-
return {
|
|
1075
|
-
rootRevision: createHash2("sha256").update(rootIdentity).digest("base64url"),
|
|
1076
|
-
entries
|
|
1077
|
-
};
|
|
1078
|
-
}
|
|
1079
|
-
};
|
|
1080
|
-
|
|
1081
983
|
// src/session-file.ts
|
|
1082
984
|
import { isUtf8 } from "node:buffer";
|
|
1083
|
-
import { createHash as
|
|
985
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1084
986
|
import { constants as constants2 } from "node:fs";
|
|
1085
|
-
import { lstat
|
|
1086
|
-
import { extname, isAbsolute
|
|
987
|
+
import { lstat, open, realpath, stat } from "node:fs/promises";
|
|
988
|
+
import { extname, isAbsolute, join as join2 } from "node:path";
|
|
1087
989
|
import { promisify } from "node:util";
|
|
1088
990
|
import { gzip } from "node:zlib";
|
|
1089
991
|
|
|
@@ -1242,7 +1144,7 @@ var SessionFileReadError = class extends Error {
|
|
|
1242
1144
|
}
|
|
1243
1145
|
code;
|
|
1244
1146
|
};
|
|
1245
|
-
function
|
|
1147
|
+
function fail(code) {
|
|
1246
1148
|
throw new SessionFileReadError(code);
|
|
1247
1149
|
}
|
|
1248
1150
|
function fileIdentity(info, includeChangeTime = true) {
|
|
@@ -1280,9 +1182,9 @@ function isPreviewableText(bytes) {
|
|
|
1280
1182
|
function rejectAnimatedPng(bytes) {
|
|
1281
1183
|
for (let offset = 8; offset + 12 <= bytes.length; ) {
|
|
1282
1184
|
const size = bytes.readUInt32BE(offset);
|
|
1283
|
-
if (size > bytes.length - offset - 12)
|
|
1185
|
+
if (size > bytes.length - offset - 12) fail("FILE_UNSUPPORTED");
|
|
1284
1186
|
const type = bytes.toString("ascii", offset + 4, offset + 8);
|
|
1285
|
-
if (type === "acTL")
|
|
1187
|
+
if (type === "acTL") fail("FILE_UNSUPPORTED");
|
|
1286
1188
|
offset += size + 12;
|
|
1287
1189
|
if (type === "IEND") break;
|
|
1288
1190
|
}
|
|
@@ -1295,14 +1197,14 @@ async function imagePreview(bytes, extension, checkDeadline) {
|
|
|
1295
1197
|
const metadata = await sharp(bytes, options).metadata();
|
|
1296
1198
|
checkDeadline();
|
|
1297
1199
|
const expected = extension === ".png" ? "png" : extension === ".webp" ? "webp" : "jpeg";
|
|
1298
|
-
if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_FILE_MAX_IMAGE_PIXELS)
|
|
1200
|
+
if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_FILE_MAX_IMAGE_PIXELS) fail("FILE_UNSUPPORTED");
|
|
1299
1201
|
if (metadata.format === "png") rejectAnimatedPng(bytes);
|
|
1300
1202
|
for (const [edge, quality] of [[SESSION_FILE_MAX_IMAGE_EDGE, 75], [1024, 60], [768, 45], [512, 30]]) {
|
|
1301
1203
|
const result = await sharp(bytes, options).rotate().resize({ width: edge, height: edge, fit: "inside", withoutEnlargement: true }).webp({ quality, effort: 3 }).toBuffer();
|
|
1302
1204
|
checkDeadline();
|
|
1303
1205
|
if (result.length <= SESSION_FILE_MAX_IMAGE_BYTES) return result;
|
|
1304
1206
|
}
|
|
1305
|
-
return
|
|
1207
|
+
return fail("FILE_TOO_LARGE");
|
|
1306
1208
|
} catch (error) {
|
|
1307
1209
|
if (error instanceof SessionFileReadError) throw error;
|
|
1308
1210
|
throw new SessionFileReadError("FILE_UNSUPPORTED", { cause: error });
|
|
@@ -1323,7 +1225,7 @@ function resourceMediaType(extension) {
|
|
|
1323
1225
|
case ".mjs":
|
|
1324
1226
|
return "text/javascript";
|
|
1325
1227
|
default:
|
|
1326
|
-
return
|
|
1228
|
+
return fail("FILE_UNSUPPORTED");
|
|
1327
1229
|
}
|
|
1328
1230
|
}
|
|
1329
1231
|
async function validateRawImage(bytes, extension, checkDeadline) {
|
|
@@ -1334,37 +1236,37 @@ async function validateRawImage(bytes, extension, checkDeadline) {
|
|
|
1334
1236
|
const metadata = await sharp(bytes, options).metadata();
|
|
1335
1237
|
checkDeadline();
|
|
1336
1238
|
const expected = extension === ".png" ? "png" : extension === ".webp" ? "webp" : "jpeg";
|
|
1337
|
-
if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_RESOURCE_MAX_IMAGE_PIXELS)
|
|
1239
|
+
if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_RESOURCE_MAX_IMAGE_PIXELS) fail("FILE_UNSUPPORTED");
|
|
1338
1240
|
if (expected === "png") {
|
|
1339
1241
|
rejectAnimatedPng(bytes);
|
|
1340
1242
|
let offset = 8;
|
|
1341
1243
|
let ended = false;
|
|
1342
1244
|
while (offset + 12 <= bytes.length) {
|
|
1343
1245
|
const size = bytes.readUInt32BE(offset);
|
|
1344
|
-
if (size > bytes.length - offset - 12)
|
|
1246
|
+
if (size > bytes.length - offset - 12) fail("FILE_UNSUPPORTED");
|
|
1345
1247
|
const type = bytes.toString("ascii", offset + 4, offset + 8);
|
|
1346
|
-
if (type === "fcTL" || type === "fdAT")
|
|
1248
|
+
if (type === "fcTL" || type === "fdAT") fail("FILE_UNSUPPORTED");
|
|
1347
1249
|
offset += size + 12;
|
|
1348
1250
|
if (type === "IEND") {
|
|
1349
1251
|
ended = size === 0;
|
|
1350
1252
|
break;
|
|
1351
1253
|
}
|
|
1352
1254
|
}
|
|
1353
|
-
if (!ended || offset !== bytes.length)
|
|
1255
|
+
if (!ended || offset !== bytes.length) fail("FILE_UNSUPPORTED");
|
|
1354
1256
|
}
|
|
1355
1257
|
if (expected === "jpeg" && (bytes.length < 4 || bytes.readUInt16BE(bytes.length - 2) !== 65497)) {
|
|
1356
|
-
|
|
1258
|
+
fail("FILE_UNSUPPORTED");
|
|
1357
1259
|
}
|
|
1358
1260
|
if (expected === "webp") {
|
|
1359
|
-
if (bytes.length < 20 || bytes.readUInt32LE(4) !== bytes.length - 8)
|
|
1261
|
+
if (bytes.length < 20 || bytes.readUInt32LE(4) !== bytes.length - 8) fail("FILE_UNSUPPORTED");
|
|
1360
1262
|
let offset = 12;
|
|
1361
1263
|
while (offset + 8 <= bytes.length) {
|
|
1362
1264
|
const type = bytes.toString("ascii", offset, offset + 4);
|
|
1363
1265
|
const size = bytes.readUInt32LE(offset + 4);
|
|
1364
|
-
if (size > bytes.length - offset - 8 || type === "ANIM" || type === "ANMF" || type === "VP8X" && (size !== 10 || (bytes[offset + 8] & 2) !== 0))
|
|
1266
|
+
if (size > bytes.length - offset - 8 || type === "ANIM" || type === "ANMF" || type === "VP8X" && (size !== 10 || (bytes[offset + 8] & 2) !== 0)) fail("FILE_UNSUPPORTED");
|
|
1365
1267
|
offset += 8 + size + (size & 1);
|
|
1366
1268
|
}
|
|
1367
|
-
if (offset !== bytes.length)
|
|
1269
|
+
if (offset !== bytes.length) fail("FILE_UNSUPPORTED");
|
|
1368
1270
|
}
|
|
1369
1271
|
await sharp(bytes, options).stats();
|
|
1370
1272
|
checkDeadline();
|
|
@@ -1379,32 +1281,32 @@ var SessionFileReader = class {
|
|
|
1379
1281
|
}
|
|
1380
1282
|
metadata;
|
|
1381
1283
|
#active = 0;
|
|
1382
|
-
async read(sessionId, path, rootRevision, version = SESSION_FILE_READ_VERSION) {
|
|
1383
|
-
if (version !== SESSION_FILE_READ_VERSION && version !== SESSION_FILE_READ_V2_VERSION)
|
|
1384
|
-
if (!SessionFileReadDataSchema.safeParse({ path, rootRevision }).success)
|
|
1284
|
+
async read(sessionId, path, rootRevision, version = SESSION_FILE_READ_VERSION, space) {
|
|
1285
|
+
if (version !== SESSION_FILE_READ_VERSION && version !== SESSION_FILE_READ_V2_VERSION) fail("UNSUPPORTED_OPERATION_VERSION");
|
|
1286
|
+
if (!SessionFileReadDataSchema.safeParse({ path, rootRevision }).success) fail("INVALID_FILE_PATH");
|
|
1385
1287
|
const schema = version === SESSION_FILE_READ_V2_VERSION ? SessionFileReadV2ResultDataSchema : SessionFileReadResultDataSchema;
|
|
1386
1288
|
return schema.parse(await this.#run(
|
|
1387
|
-
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "preview", version)
|
|
1289
|
+
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "preview", version, space)
|
|
1388
1290
|
));
|
|
1389
1291
|
}
|
|
1390
|
-
async readResource(sessionId, path, rootRevision) {
|
|
1391
|
-
if (!SessionResourceReadDataSchema.safeParse({ path, rootRevision }).success)
|
|
1292
|
+
async readResource(sessionId, path, rootRevision, space) {
|
|
1293
|
+
if (!SessionResourceReadDataSchema.safeParse({ path, rootRevision }).success) fail("INVALID_FILE_PATH");
|
|
1392
1294
|
return SessionResourceReadResultDataSchema.parse(await this.#run(
|
|
1393
|
-
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "resource")
|
|
1295
|
+
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "resource", SESSION_FILE_READ_VERSION, space)
|
|
1394
1296
|
));
|
|
1395
1297
|
}
|
|
1396
|
-
async download(sessionId, path, rootRevision) {
|
|
1397
|
-
if (!SessionFileDownloadDataSchema.safeParse({ path, rootRevision }).success)
|
|
1298
|
+
async download(sessionId, path, rootRevision, space) {
|
|
1299
|
+
if (!SessionFileDownloadDataSchema.safeParse({ path, rootRevision }).success) fail("INVALID_FILE_PATH");
|
|
1398
1300
|
return SessionFileDownloadResultDataSchema.parse(await this.#run(
|
|
1399
|
-
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "download")
|
|
1301
|
+
(checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "download", SESSION_FILE_READ_VERSION, space)
|
|
1400
1302
|
));
|
|
1401
1303
|
}
|
|
1402
1304
|
async #run(read) {
|
|
1403
|
-
if (this.#active >= SESSION_FILE_CONCURRENCY)
|
|
1305
|
+
if (this.#active >= SESSION_FILE_CONCURRENCY) fail("FILE_BUSY");
|
|
1404
1306
|
this.#active++;
|
|
1405
1307
|
const deadline = Date.now() + SESSION_FILE_TIMEOUT_MS;
|
|
1406
1308
|
const checkDeadline = () => {
|
|
1407
|
-
if (Date.now() >= deadline)
|
|
1309
|
+
if (Date.now() >= deadline) fail("FILE_TIMEOUT");
|
|
1408
1310
|
};
|
|
1409
1311
|
const work = read(checkDeadline).finally(() => {
|
|
1410
1312
|
this.#active--;
|
|
@@ -1424,59 +1326,59 @@ var SessionFileReader = class {
|
|
|
1424
1326
|
clearTimeout(timer);
|
|
1425
1327
|
}
|
|
1426
1328
|
}
|
|
1427
|
-
async #read(sessionId, path, rootRevision, checkDeadline, mode, version = SESSION_FILE_READ_VERSION) {
|
|
1329
|
+
async #read(sessionId, path, rootRevision, checkDeadline, mode, version = SESSION_FILE_READ_VERSION, space) {
|
|
1428
1330
|
const resource = mode === "resource";
|
|
1429
1331
|
const download = mode === "download";
|
|
1430
1332
|
const metadata = await this.metadata(sessionId);
|
|
1431
1333
|
checkDeadline();
|
|
1432
|
-
if (metadata === void 0)
|
|
1433
|
-
const workingDirectory = metadata.workingDirectory;
|
|
1434
|
-
if (!workingDirectory || !
|
|
1334
|
+
if (metadata === void 0) fail("SESSION_NOT_FOUND");
|
|
1335
|
+
const workingDirectory = space === "session" ? metadata.sessionStateDirectory : metadata.workingDirectory;
|
|
1336
|
+
if (!workingDirectory || !isAbsolute(workingDirectory)) fail("SESSION_ROOT_UNAVAILABLE");
|
|
1435
1337
|
let root;
|
|
1436
1338
|
let rootIdentity;
|
|
1437
1339
|
try {
|
|
1438
|
-
if ((await
|
|
1439
|
-
root = await
|
|
1440
|
-
const info = await
|
|
1441
|
-
if (!info.isDirectory())
|
|
1340
|
+
if ((await lstat(workingDirectory)).isSymbolicLink()) fail("FILE_UNAVAILABLE");
|
|
1341
|
+
root = await realpath(workingDirectory);
|
|
1342
|
+
const info = await stat(root, { bigint: true });
|
|
1343
|
+
if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE");
|
|
1442
1344
|
rootIdentity = sessionRootIdentity(root, info);
|
|
1443
1345
|
} catch (error) {
|
|
1444
1346
|
if (error instanceof SessionFileReadError) throw error;
|
|
1445
1347
|
throw new SessionFileReadError("SESSION_ROOT_UNAVAILABLE", { cause: error });
|
|
1446
1348
|
}
|
|
1447
|
-
if (
|
|
1349
|
+
if (createHash2("sha256").update(rootIdentity).digest("base64url") !== rootRevision) fail("SESSION_ROOT_CHANGED");
|
|
1448
1350
|
checkDeadline();
|
|
1449
|
-
const target =
|
|
1351
|
+
const target = join2(root, ...path.split("/"));
|
|
1450
1352
|
const inspectPath = async () => {
|
|
1451
1353
|
let current = root;
|
|
1452
1354
|
const segments = path.split("/");
|
|
1453
1355
|
let file;
|
|
1454
1356
|
for (const [index, segment] of segments.entries()) {
|
|
1455
|
-
current =
|
|
1456
|
-
const info = await
|
|
1357
|
+
current = join2(current, segment);
|
|
1358
|
+
const info = await lstat(current, { bigint: true });
|
|
1457
1359
|
checkDeadline();
|
|
1458
1360
|
if (info.isSymbolicLink() || (index === segments.length - 1 ? !info.isFile() : !info.isDirectory())) {
|
|
1459
|
-
|
|
1361
|
+
fail("FILE_UNAVAILABLE");
|
|
1460
1362
|
}
|
|
1461
|
-
const canonical = await
|
|
1363
|
+
const canonical = await realpath(current);
|
|
1462
1364
|
const samePath2 = canonical === current || resource && process.platform === "win32" && canonical.toLowerCase() === current.toLowerCase();
|
|
1463
|
-
if (!contained(root, canonical) || !samePath2)
|
|
1365
|
+
if (!contained(root, canonical) || !samePath2) fail("FILE_UNAVAILABLE");
|
|
1464
1366
|
checkDeadline();
|
|
1465
1367
|
file = info;
|
|
1466
1368
|
}
|
|
1467
|
-
if (file === void 0)
|
|
1369
|
+
if (file === void 0) fail("INVALID_FILE_PATH");
|
|
1468
1370
|
return file;
|
|
1469
1371
|
};
|
|
1470
1372
|
const before = await inspectPath();
|
|
1471
1373
|
const maxOriginalBytes = download ? SESSION_FILE_DOWNLOAD_MAX_ORIGINAL_BYTES : resource ? SESSION_RESOURCE_MAX_ORIGINAL_BYTES : version === SESSION_FILE_READ_V2_VERSION ? SESSION_FILE_V2_MAX_ORIGINAL_BYTES : SESSION_FILE_MAX_ORIGINAL_BYTES;
|
|
1472
|
-
if (before.size > BigInt(maxOriginalBytes))
|
|
1374
|
+
if (before.size > BigInt(maxOriginalBytes)) fail("FILE_TOO_LARGE");
|
|
1473
1375
|
const extension = extname(path).toLowerCase();
|
|
1474
1376
|
const resourceType = resource ? resourceMediaType(extension) : void 0;
|
|
1475
1377
|
const handle = await open(target, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0));
|
|
1476
1378
|
try {
|
|
1477
1379
|
const opened = await handle.stat({ bigint: true });
|
|
1478
1380
|
const includeChangeTime = process.platform !== "win32";
|
|
1479
|
-
if (!opened.isFile() || fileIdentity(opened, includeChangeTime) !== fileIdentity(before, includeChangeTime))
|
|
1381
|
+
if (!opened.isFile() || fileIdentity(opened, includeChangeTime) !== fileIdentity(before, includeChangeTime)) fail("FILE_CHANGED");
|
|
1480
1382
|
const originalByteLength = Number(before.size);
|
|
1481
1383
|
const readOriginal = async () => {
|
|
1482
1384
|
const original = Buffer.alloc(originalByteLength + 1);
|
|
@@ -1487,7 +1389,7 @@ var SessionFileReader = class {
|
|
|
1487
1389
|
if (bytesRead === 0) break;
|
|
1488
1390
|
offset += bytesRead;
|
|
1489
1391
|
}
|
|
1490
|
-
if (offset !== originalByteLength)
|
|
1392
|
+
if (offset !== originalByteLength) fail("FILE_CHANGED");
|
|
1491
1393
|
return original.subarray(0, originalByteLength);
|
|
1492
1394
|
};
|
|
1493
1395
|
const bytes = await readOriginal();
|
|
@@ -1500,7 +1402,7 @@ var SessionFileReader = class {
|
|
|
1500
1402
|
mediaType = resourceType;
|
|
1501
1403
|
if (resourceType.startsWith("image/")) {
|
|
1502
1404
|
await validateRawImage(bytes, extension, checkDeadline);
|
|
1503
|
-
} else if (!isPreviewableText(bytes))
|
|
1405
|
+
} else if (!isPreviewableText(bytes)) fail("FILE_UNSUPPORTED");
|
|
1504
1406
|
canonical = bytes;
|
|
1505
1407
|
} else if (isPreviewableText(bytes)) {
|
|
1506
1408
|
mediaType = textMediaType(path);
|
|
@@ -1523,7 +1425,7 @@ var SessionFileReader = class {
|
|
|
1523
1425
|
mediaType = "image/webp";
|
|
1524
1426
|
canonical = await imagePreview(bytes, `.${detected.ext}`, checkDeadline);
|
|
1525
1427
|
} else if (detected?.mime === "video/mp4" || detected?.mime === "video/webm") {
|
|
1526
|
-
if (version !== SESSION_FILE_READ_V2_VERSION || extension !== (detected.mime === "video/mp4" ? ".mp4" : ".webm"))
|
|
1428
|
+
if (version !== SESSION_FILE_READ_V2_VERSION || extension !== (detected.mime === "video/mp4" ? ".mp4" : ".webm")) fail("FILE_UNSUPPORTED");
|
|
1527
1429
|
mediaType = detected.mime;
|
|
1528
1430
|
try {
|
|
1529
1431
|
validateSessionVideo(bytes, mediaType);
|
|
@@ -1531,7 +1433,7 @@ var SessionFileReader = class {
|
|
|
1531
1433
|
throw new SessionFileReadError("FILE_UNSUPPORTED", { cause: error });
|
|
1532
1434
|
}
|
|
1533
1435
|
canonical = bytes;
|
|
1534
|
-
} else
|
|
1436
|
+
} else fail("FILE_UNSUPPORTED");
|
|
1535
1437
|
}
|
|
1536
1438
|
const threshold = resource ? SESSION_RESOURCE_GZIP_THRESHOLD_BYTES : SESSION_FILE_GZIP_THRESHOLD_BYTES;
|
|
1537
1439
|
const encoding = originalByteLength >= threshold ? "gzip" : "identity";
|
|
@@ -1539,17 +1441,17 @@ var SessionFileReader = class {
|
|
|
1539
1441
|
const latestMetadata = await this.metadata(sessionId);
|
|
1540
1442
|
checkDeadline();
|
|
1541
1443
|
try {
|
|
1542
|
-
const latestRoot = await
|
|
1543
|
-
const latestRootInfo = await
|
|
1544
|
-
if (latestMetadata?.workingDirectory !== workingDirectory || (await
|
|
1444
|
+
const latestRoot = await realpath(workingDirectory);
|
|
1445
|
+
const latestRootInfo = await stat(latestRoot, { bigint: true });
|
|
1446
|
+
if ((space === "session" ? latestMetadata?.sessionStateDirectory : latestMetadata?.workingDirectory) !== workingDirectory || (await lstat(workingDirectory)).isSymbolicLink() || sessionRootIdentity(latestRoot, latestRootInfo) !== rootIdentity) fail("SESSION_ROOT_CHANGED");
|
|
1545
1447
|
} catch (error) {
|
|
1546
1448
|
if (error instanceof SessionFileReadError) throw error;
|
|
1547
1449
|
throw new SessionFileReadError("SESSION_ROOT_CHANGED", { cause: error });
|
|
1548
1450
|
}
|
|
1549
1451
|
try {
|
|
1550
1452
|
const latest = await inspectPath();
|
|
1551
|
-
if (fileIdentity(latest, includeChangeTime) !== fileIdentity(opened, includeChangeTime) || !includeChangeTime && !(await readOriginal()).equals(bytes))
|
|
1552
|
-
if (fileIdentity(await handle.stat({ bigint: true }), includeChangeTime) !== fileIdentity(latest, includeChangeTime))
|
|
1453
|
+
if (fileIdentity(latest, includeChangeTime) !== fileIdentity(opened, includeChangeTime) || !includeChangeTime && !(await readOriginal()).equals(bytes)) fail("FILE_CHANGED");
|
|
1454
|
+
if (fileIdentity(await handle.stat({ bigint: true }), includeChangeTime) !== fileIdentity(latest, includeChangeTime)) fail("FILE_CHANGED");
|
|
1553
1455
|
} catch (error) {
|
|
1554
1456
|
if (error instanceof SessionFileReadError && error.code === "FILE_TIMEOUT") throw error;
|
|
1555
1457
|
throw new SessionFileReadError("FILE_CHANGED", { cause: error });
|
|
@@ -1728,7 +1630,10 @@ var diagnosticCodes = /* @__PURE__ */ new Set([
|
|
|
1728
1630
|
"SCHEDULE_DRAFT_STORE_UNAVAILABLE",
|
|
1729
1631
|
"SCHEDULE_DRAFT_NOT_FOUND",
|
|
1730
1632
|
"SCHEDULE_DRAFT_LIMIT",
|
|
1731
|
-
"SCHEDULE_OUTCOME_UNCERTAIN"
|
|
1633
|
+
"SCHEDULE_OUTCOME_UNCERTAIN",
|
|
1634
|
+
"ANALYTICS_INVALID",
|
|
1635
|
+
"ANALYTICS_UNAVAILABLE",
|
|
1636
|
+
"ANALYTICS_UNSUPPORTED"
|
|
1732
1637
|
]);
|
|
1733
1638
|
var diagnosticNames = /* @__PURE__ */ new Set([
|
|
1734
1639
|
"Error",
|
|
@@ -1878,6 +1783,19 @@ function createWorkbenchOperations(options) {
|
|
|
1878
1783
|
route("context.compact", WorkbenchSubmitRequestSchema, (data, request2) => submit(request2, data, async () => output(WorkbenchCompactResultSchema, await runtime.compact(request2.sessionId))))
|
|
1879
1784
|
);
|
|
1880
1785
|
const research = options.research;
|
|
1786
|
+
if (runtime?.reasoning !== void 0) {
|
|
1787
|
+
const reasoning = runtime.reasoning.bind(runtime);
|
|
1788
|
+
routes.push(route("reasoning.read", WorkbenchReasoningRequestSchema, async (data, request2) => {
|
|
1789
|
+
if (options.isResearchSession?.() === true || await options.research?.parentSessionId(request2.sessionId) !== void 0) {
|
|
1790
|
+
throw new SessionOperationError("AGENT_OPERATION_UNSUPPORTED", "Thinking history is available only in the main Copilot session");
|
|
1791
|
+
}
|
|
1792
|
+
return output(WorkbenchReasoningPageSchema, await reasoning(request2.sessionId, data));
|
|
1793
|
+
}));
|
|
1794
|
+
}
|
|
1795
|
+
if (runtime?.analytics !== void 0) {
|
|
1796
|
+
const analytics = runtime.analytics.bind(runtime);
|
|
1797
|
+
routes.push(route("analytics.read", SessionAnalyticsRequestSchema, async (data, request2) => output(SessionAnalyticsResultSchema, await analytics(request2.sessionId, data))));
|
|
1798
|
+
}
|
|
1881
1799
|
if (research !== void 0) routes.push(
|
|
1882
1800
|
route("research.create", WorkbenchResearchCreateRequestSchema, (data, request2) => submit(request2, data, async () => output(WorkbenchResearchCreateResultSchema, {
|
|
1883
1801
|
thread: await research.create({
|
|
@@ -1921,15 +1839,15 @@ var ResearchError = class extends Error {
|
|
|
1921
1839
|
code;
|
|
1922
1840
|
};
|
|
1923
1841
|
async function researchRoot(workingDirectory) {
|
|
1924
|
-
if (!
|
|
1842
|
+
if (!isAbsolute2(workingDirectory)) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
|
|
1925
1843
|
try {
|
|
1926
|
-
if ((await
|
|
1927
|
-
const root = await
|
|
1928
|
-
const info = await
|
|
1844
|
+
if ((await lstat2(workingDirectory)).isSymbolicLink()) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
|
|
1845
|
+
const root = await realpath2(workingDirectory);
|
|
1846
|
+
const info = await stat2(root, { bigint: true });
|
|
1929
1847
|
if (!info.isDirectory()) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
|
|
1930
1848
|
return {
|
|
1931
1849
|
workingDirectory: root,
|
|
1932
|
-
rootIdentity:
|
|
1850
|
+
rootIdentity: createHash3("sha256").update(sessionRootIdentity(root, info)).digest("base64url")
|
|
1933
1851
|
};
|
|
1934
1852
|
} catch (error) {
|
|
1935
1853
|
if (error instanceof ResearchError) throw error;
|
|
@@ -2043,7 +1961,7 @@ var ResearchTools = class {
|
|
|
2043
1961
|
}
|
|
2044
1962
|
async #validate(path) {
|
|
2045
1963
|
const source = await this.#source();
|
|
2046
|
-
const target =
|
|
1964
|
+
const target = join3(this.root.workingDirectory, ...path.split("/"));
|
|
2047
1965
|
if (sensitiveSegments(this.root.workingDirectory.split(/[\\/]/u)) || !allowedPath(path, source.excludedPaths ?? []) || this.privateDirectories.some((directory) => contained(directory, target))) {
|
|
2048
1966
|
throw new ResearchError("RESEARCH_PATH_BLOCKED", "The requested path is excluded from research");
|
|
2049
1967
|
}
|
|
@@ -2088,7 +2006,7 @@ var ResearchTools = class {
|
|
|
2088
2006
|
const source = await this.#source();
|
|
2089
2007
|
return result.entries.filter((entry) => {
|
|
2090
2008
|
const child = path ? `${path}/${entry.name}` : entry.name;
|
|
2091
|
-
return entry.kind !== "blocked" && allowedPath(child, source.excludedPaths ?? []) && !this.privateDirectories.some((directory) => contained(directory,
|
|
2009
|
+
return entry.kind !== "blocked" && allowedPath(child, source.excludedPaths ?? []) && !this.privateDirectories.some((directory) => contained(directory, join3(this.root.workingDirectory, ...child.split("/"))));
|
|
2092
2010
|
});
|
|
2093
2011
|
}
|
|
2094
2012
|
async list(input) {
|
|
@@ -2130,7 +2048,7 @@ var ResearchTools = class {
|
|
|
2130
2048
|
return {
|
|
2131
2049
|
text: bytes.toString("utf8"),
|
|
2132
2050
|
bytes: bytes.length,
|
|
2133
|
-
version:
|
|
2051
|
+
version: createHash3("sha256").update(bytes).digest("base64url")
|
|
2134
2052
|
};
|
|
2135
2053
|
}
|
|
2136
2054
|
async read(input) {
|
|
@@ -2188,8 +2106,8 @@ var ResearchTools = class {
|
|
|
2188
2106
|
if (path === void 0) break;
|
|
2189
2107
|
inspected++;
|
|
2190
2108
|
await this.#validate(path);
|
|
2191
|
-
const target =
|
|
2192
|
-
const info = await
|
|
2109
|
+
const target = join3(this.root.workingDirectory, ...path.split("/"));
|
|
2110
|
+
const info = await lstat2(target);
|
|
2193
2111
|
if (info.isSymbolicLink()) {
|
|
2194
2112
|
skippedFiles++;
|
|
2195
2113
|
continue;
|
|
@@ -2421,8 +2339,9 @@ function researchAwareCodingAgentAdapter(inner, research) {
|
|
|
2421
2339
|
}
|
|
2422
2340
|
|
|
2423
2341
|
// src/pc-agent.ts
|
|
2424
|
-
import { randomUUID as
|
|
2342
|
+
import { createHash as createHash16, randomUUID as randomUUID11 } from "node:crypto";
|
|
2425
2343
|
import { platform as platform2 } from "node:os";
|
|
2344
|
+
import { join as join12 } from "node:path";
|
|
2426
2345
|
import { performance as performance5 } from "node:perf_hooks";
|
|
2427
2346
|
|
|
2428
2347
|
// ../node/dist/index.js
|
|
@@ -2551,8 +2470,8 @@ var AuthorizedRelaySocket = class {
|
|
|
2551
2470
|
|
|
2552
2471
|
// src/service/requests/session-communication.ts
|
|
2553
2472
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2554
|
-
import { createHash as
|
|
2555
|
-
import { join as
|
|
2473
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2474
|
+
import { join as join5 } from "node:path";
|
|
2556
2475
|
import { performance as performance2 } from "node:perf_hooks";
|
|
2557
2476
|
|
|
2558
2477
|
// src/repeated-error-diagnostics.ts
|
|
@@ -2824,10 +2743,10 @@ import { constants as constants4, gzip as gzip3 } from "node:zlib";
|
|
|
2824
2743
|
|
|
2825
2744
|
// src/session-git-diff.ts
|
|
2826
2745
|
import { execFile } from "node:child_process";
|
|
2827
|
-
import { createHash as
|
|
2746
|
+
import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
|
|
2828
2747
|
import { constants as constants3 } from "node:fs";
|
|
2829
|
-
import { chmod, lstat as
|
|
2830
|
-
import { dirname, isAbsolute as
|
|
2748
|
+
import { chmod, lstat as lstat3, mkdir as mkdir2, open as open2, readlink, realpath as realpath3, rm, stat as stat3, writeFile as writeFile2 } from "node:fs/promises";
|
|
2749
|
+
import { dirname, isAbsolute as isAbsolute3, join as join4, relative, resolve as resolve2, sep } from "node:path";
|
|
2831
2750
|
|
|
2832
2751
|
// src/git-repository-error.ts
|
|
2833
2752
|
function isGitRepositoryUnavailableError(error) {
|
|
@@ -2851,7 +2770,7 @@ var SessionGitDiffError = class extends Error {
|
|
|
2851
2770
|
}
|
|
2852
2771
|
code;
|
|
2853
2772
|
};
|
|
2854
|
-
function
|
|
2773
|
+
function fail2(code, message) {
|
|
2855
2774
|
throw new SessionGitDiffError(code, message);
|
|
2856
2775
|
}
|
|
2857
2776
|
function fileError(error) {
|
|
@@ -2877,10 +2796,10 @@ async function forFile(path, work, operation) {
|
|
|
2877
2796
|
}
|
|
2878
2797
|
}
|
|
2879
2798
|
function changed() {
|
|
2880
|
-
return
|
|
2799
|
+
return fail2("DIFF_CHANGED", "The project diff changed; refresh the changed-file list");
|
|
2881
2800
|
}
|
|
2882
2801
|
function limit() {
|
|
2883
|
-
return
|
|
2802
|
+
return fail2("DIFF_LIMIT_EXCEEDED", "The project diff is too large");
|
|
2884
2803
|
}
|
|
2885
2804
|
function samePath(a, b) {
|
|
2886
2805
|
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
@@ -2946,7 +2865,7 @@ var Work = class {
|
|
|
2946
2865
|
const drivers = /* @__PURE__ */ new Set();
|
|
2947
2866
|
for (const name of names) {
|
|
2948
2867
|
const match = /^filter\.([^=\r\n]+)\.[^.]+$/u.exec(name);
|
|
2949
|
-
if (!match?.[1])
|
|
2868
|
+
if (!match?.[1]) fail2("DIFF_BLOCKED", "The project contains an unsupported filter configuration");
|
|
2950
2869
|
drivers.add(match[1]);
|
|
2951
2870
|
}
|
|
2952
2871
|
this.#filterConfig = [...drivers].flatMap((name) => [
|
|
@@ -2960,7 +2879,7 @@ var Work = class {
|
|
|
2960
2879
|
if (this.#filterConfig.join(" ").length > 16384) limit();
|
|
2961
2880
|
}
|
|
2962
2881
|
check() {
|
|
2963
|
-
if (Date.now() >= this.deadline)
|
|
2882
|
+
if (Date.now() >= this.deadline) fail2("DIFF_TIMEOUT", "The project diff request timed out");
|
|
2964
2883
|
}
|
|
2965
2884
|
async git(cwd, args, options = {}) {
|
|
2966
2885
|
this.check();
|
|
@@ -2984,10 +2903,10 @@ var Work = class {
|
|
|
2984
2903
|
...this.env,
|
|
2985
2904
|
...options.objectDirectory === void 0 ? {} : { GIT_OBJECT_DIRECTORY: options.objectDirectory },
|
|
2986
2905
|
...options.isolated ? {
|
|
2987
|
-
GIT_DIR:
|
|
2906
|
+
GIT_DIR: join4(cwd, "no-repository"),
|
|
2988
2907
|
GIT_CONFIG_NOSYSTEM: "1",
|
|
2989
2908
|
GIT_ATTR_NOSYSTEM: "1",
|
|
2990
|
-
GIT_CONFIG_GLOBAL:
|
|
2909
|
+
GIT_CONFIG_GLOBAL: join4(cwd, "gitconfig")
|
|
2991
2910
|
} : {}
|
|
2992
2911
|
}
|
|
2993
2912
|
}, (error, output2, stderr) => {
|
|
@@ -3011,14 +2930,14 @@ function identity(info) {
|
|
|
3011
2930
|
return `${info.dev}\0${info.ino}\0${info.size}\0${info.mtimeNs}\0${info.mode}\0${info.nlink}`;
|
|
3012
2931
|
}
|
|
3013
2932
|
async function inspect(root, path, work, kind = "file") {
|
|
3014
|
-
if (!safePath(path))
|
|
2933
|
+
if (!safePath(path)) fail2("DIFF_BLOCKED", "The selected path cannot be compared");
|
|
3015
2934
|
let current = root;
|
|
3016
2935
|
const segments = path.split("/");
|
|
3017
2936
|
for (const [index, segment] of segments.entries()) {
|
|
3018
|
-
current =
|
|
2937
|
+
current = join4(current, segment);
|
|
3019
2938
|
let info;
|
|
3020
2939
|
try {
|
|
3021
|
-
info = await
|
|
2940
|
+
info = await lstat3(current, { bigint: true });
|
|
3022
2941
|
} catch (error) {
|
|
3023
2942
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
|
|
3024
2943
|
throw error;
|
|
@@ -3027,11 +2946,11 @@ async function inspect(root, path, work, kind = "file") {
|
|
|
3027
2946
|
const last = index === segments.length - 1;
|
|
3028
2947
|
if (last && kind === "link" && info.isSymbolicLink()) return info;
|
|
3029
2948
|
if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) {
|
|
3030
|
-
|
|
2949
|
+
fail2("DIFF_BLOCKED", "Links, submodules and special files cannot be compared");
|
|
3031
2950
|
}
|
|
3032
|
-
const canonical = await
|
|
2951
|
+
const canonical = await realpath3(current);
|
|
3033
2952
|
if (!contained(root, canonical) || !samePath(canonical, current)) {
|
|
3034
|
-
|
|
2953
|
+
fail2("DIFF_BLOCKED", "The selected path is outside the session");
|
|
3035
2954
|
}
|
|
3036
2955
|
work.check();
|
|
3037
2956
|
if (info.isDirectory() !== (!last || kind === "directory")) return void 0;
|
|
@@ -3044,10 +2963,10 @@ async function readCurrent(root, path, algorithm, work, keepBytes = false) {
|
|
|
3044
2963
|
const before = await inspect(root, path, work, kind);
|
|
3045
2964
|
if (before === void 0) return void 0;
|
|
3046
2965
|
if (before.isSymbolicLink()) {
|
|
3047
|
-
const bytes = Buffer.from(await readlink(
|
|
2966
|
+
const bytes = Buffer.from(await readlink(join4(root, ...path.split("/"))), "utf8");
|
|
3048
2967
|
const latest = await inspect(root, path, work, "link");
|
|
3049
2968
|
if (latest === void 0 || identity(latest) !== identity(before)) changed();
|
|
3050
|
-
const oid =
|
|
2969
|
+
const oid = createHash4(algorithm).update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
|
|
3051
2970
|
return {
|
|
3052
2971
|
oid,
|
|
3053
2972
|
rawOid: oid,
|
|
@@ -3059,13 +2978,13 @@ async function readCurrent(root, path, algorithm, work, keepBytes = false) {
|
|
|
3059
2978
|
if (before.size > BigInt(MAX_SCAN_BYTES - work.bytes) || keepBytes && before.size > BigInt(SESSION_GIT_DIFF_MAX_SOURCE_BYTES)) limit();
|
|
3060
2979
|
work.bytes += Number(before.size);
|
|
3061
2980
|
const handle = await open2(
|
|
3062
|
-
|
|
2981
|
+
join4(root, ...path.split("/")),
|
|
3063
2982
|
constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0)
|
|
3064
2983
|
);
|
|
3065
2984
|
try {
|
|
3066
2985
|
const opened = await handle.stat({ bigint: true });
|
|
3067
2986
|
if (!opened.isFile() || identity(opened) !== identity(before)) changed();
|
|
3068
|
-
const hash2 =
|
|
2987
|
+
const hash2 = createHash4(algorithm).update(`blob ${before.size}\0`);
|
|
3069
2988
|
const buffer = Buffer.alloc(64 * 1024);
|
|
3070
2989
|
const chunks = [];
|
|
3071
2990
|
let offset = 0;
|
|
@@ -3105,28 +3024,28 @@ async function base(repository, work) {
|
|
|
3105
3024
|
], { allowExitOne: true })).trim();
|
|
3106
3025
|
if (!commit) continue;
|
|
3107
3026
|
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(commit)) {
|
|
3108
|
-
|
|
3027
|
+
fail2("DIFF_BASE_UNAVAILABLE", "The main branch could not be resolved");
|
|
3109
3028
|
}
|
|
3110
3029
|
const baseCommit = decode(await work.git(repository, ["merge-base", "--all", "HEAD", commit], {
|
|
3111
3030
|
allowExitOne: true
|
|
3112
3031
|
})).trim();
|
|
3113
3032
|
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(baseCommit)) {
|
|
3114
|
-
|
|
3033
|
+
fail2("DIFF_BASE_UNAVAILABLE", "The session and main do not have a unique merge base");
|
|
3115
3034
|
}
|
|
3116
3035
|
return { baseRef, baseCommit };
|
|
3117
3036
|
}
|
|
3118
|
-
return
|
|
3037
|
+
return fail2("DIFF_MAIN_UNAVAILABLE", "No local origin/main or main reference is available");
|
|
3119
3038
|
}
|
|
3120
3039
|
function scopedPath(context, path) {
|
|
3121
3040
|
const prefix = context.prefix === "" ? "" : `${context.prefix}/`;
|
|
3122
|
-
if (!path.startsWith(prefix))
|
|
3041
|
+
if (!path.startsWith(prefix)) fail2("DIFF_BLOCKED", "Git returned a path outside the session");
|
|
3123
3042
|
const scoped = path.slice(prefix.length);
|
|
3124
3043
|
return scoped;
|
|
3125
3044
|
}
|
|
3126
3045
|
function records(output2) {
|
|
3127
3046
|
const text = decode(output2);
|
|
3128
3047
|
if (text === "") return [];
|
|
3129
|
-
if (!text.endsWith("\0"))
|
|
3048
|
+
if (!text.endsWith("\0")) fail2("DIFF_UNAVAILABLE", "Git returned an incomplete file list");
|
|
3130
3049
|
return text.slice(0, -1).split("\0");
|
|
3131
3050
|
}
|
|
3132
3051
|
async function changes(context, work) {
|
|
@@ -3152,7 +3071,7 @@ async function changes(context, work) {
|
|
|
3152
3071
|
};
|
|
3153
3072
|
for (const record of tree) {
|
|
3154
3073
|
const match = /^(\d{6}) (blob|commit) ([a-f0-9]{40}|[a-f0-9]{64})\t([\s\S]+)$/u.exec(record);
|
|
3155
|
-
if (!match?.[1] || !match[3] || !match[4])
|
|
3074
|
+
if (!match?.[1] || !match[3] || !match[4]) fail2("DIFF_UNAVAILABLE", "Git returned an invalid tree");
|
|
3156
3075
|
blobs.set(scoped(match[4]), { mode: match[1], oid: match[3] });
|
|
3157
3076
|
}
|
|
3158
3077
|
for (const record of records(await work.git(context.repository, [
|
|
@@ -3164,7 +3083,7 @@ async function changes(context, work) {
|
|
|
3164
3083
|
...paths
|
|
3165
3084
|
]))) {
|
|
3166
3085
|
const match = /^(\d{6}) ([a-f0-9]{40}|[a-f0-9]{64}) [0-3]\t([\s\S]+)$/u.exec(record);
|
|
3167
|
-
if (!match?.[1] || !match[2] || !match[3])
|
|
3086
|
+
if (!match?.[1] || !match[2] || !match[3]) fail2("DIFF_UNAVAILABLE", "Git returned an invalid index");
|
|
3168
3087
|
tracked.set(scoped(match[3]), { mode: match[1], oid: match[2] });
|
|
3169
3088
|
}
|
|
3170
3089
|
for (const path of scanned) {
|
|
@@ -3211,7 +3130,7 @@ async function changes(context, work) {
|
|
|
3211
3130
|
for (const path of [...candidates].sort()) {
|
|
3212
3131
|
work.check();
|
|
3213
3132
|
try {
|
|
3214
|
-
if (!safePath(path))
|
|
3133
|
+
if (!safePath(path)) fail2("DIFF_BLOCKED", "This path cannot be safely accessed on the PC");
|
|
3215
3134
|
const original = blobs.get(path);
|
|
3216
3135
|
const indexed = tracked.get(path);
|
|
3217
3136
|
if ([original?.mode, indexed?.mode].some((mode) => mode !== void 0 && mode !== "100644" && mode !== "100755" && !(work.partial && mode === "120000"))) {
|
|
@@ -3294,13 +3213,13 @@ async function changes(context, work) {
|
|
|
3294
3213
|
return result;
|
|
3295
3214
|
}
|
|
3296
3215
|
async function unchangedSpecial(context, path, original, indexed, work) {
|
|
3297
|
-
const blocked = () =>
|
|
3216
|
+
const blocked = () => fail2("DIFF_BLOCKED", "Changed links and submodules cannot be compared");
|
|
3298
3217
|
if (original === void 0 || indexed?.mode !== original.mode || indexed.oid !== original.oid) return blocked();
|
|
3299
3218
|
if (original.mode === "160000") {
|
|
3300
3219
|
if (await inspect(context.root, path, work, "directory") === void 0) blocked();
|
|
3301
|
-
const target =
|
|
3220
|
+
const target = join4(context.root, ...path.split("/"));
|
|
3302
3221
|
try {
|
|
3303
|
-
await
|
|
3222
|
+
await lstat3(join4(target, ".git"));
|
|
3304
3223
|
} catch (error) {
|
|
3305
3224
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
|
|
3306
3225
|
throw error;
|
|
@@ -3312,8 +3231,8 @@ async function unchangedSpecial(context, path, original, indexed, work) {
|
|
|
3312
3231
|
const algorithm = context.baseCommit.length === 64 ? "sha256" : "sha1";
|
|
3313
3232
|
let oid;
|
|
3314
3233
|
if (info.isSymbolicLink()) {
|
|
3315
|
-
const target = Buffer.from(await readlink(
|
|
3316
|
-
oid =
|
|
3234
|
+
const target = Buffer.from(await readlink(join4(context.root, ...path.split("/"))), "utf8");
|
|
3235
|
+
oid = createHash4(algorithm).update(`blob ${target.length}\0`).update(target).digest("hex");
|
|
3317
3236
|
} else {
|
|
3318
3237
|
oid = (await readCurrent(context.root, path, algorithm, work))?.rawOid;
|
|
3319
3238
|
}
|
|
@@ -3355,19 +3274,19 @@ async function patch(context, change, work, scratchDirectory) {
|
|
|
3355
3274
|
}
|
|
3356
3275
|
const directory = resolve2(scratchDirectory);
|
|
3357
3276
|
if (contained(context.repository, directory)) {
|
|
3358
|
-
|
|
3277
|
+
fail2("DIFF_UNAVAILABLE", "Project diff storage must be outside the session repository");
|
|
3359
3278
|
}
|
|
3360
3279
|
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
3361
|
-
if ((await
|
|
3362
|
-
|
|
3280
|
+
if ((await lstat3(directory)).isSymbolicLink() || !samePath(await realpath3(directory), directory)) {
|
|
3281
|
+
fail2("DIFF_UNAVAILABLE", "Project diff storage cannot use links");
|
|
3363
3282
|
}
|
|
3364
|
-
const scratch =
|
|
3283
|
+
const scratch = join4(directory, randomUUID3());
|
|
3365
3284
|
await mkdir2(scratch, { mode: 448 });
|
|
3366
3285
|
let text;
|
|
3367
3286
|
try {
|
|
3368
3287
|
let bytes = current?.bytes ?? Buffer.alloc(0);
|
|
3369
3288
|
if (current !== void 0 && current.mode !== "120000") {
|
|
3370
|
-
const objectDirectory =
|
|
3289
|
+
const objectDirectory = join4(scratch, "objects");
|
|
3371
3290
|
await mkdir2(objectDirectory);
|
|
3372
3291
|
const path = [context.prefix, change.entry.path].filter(Boolean).join("/");
|
|
3373
3292
|
const oid = decode(await work.git(context.repository, ["hash-object", "-w", "--stdin", `--path=${path}`], {
|
|
@@ -3381,18 +3300,18 @@ async function patch(context, change, work, scratchDirectory) {
|
|
|
3381
3300
|
});
|
|
3382
3301
|
}
|
|
3383
3302
|
if (binary(original) || binary(bytes)) return { patch: "", binary: true };
|
|
3384
|
-
for (const side of ["a", "b"]) await mkdir2(
|
|
3303
|
+
for (const side of ["a", "b"]) await mkdir2(join4(scratch, side));
|
|
3385
3304
|
for (const [side, content, mode] of [
|
|
3386
3305
|
["a", original, change.base?.mode],
|
|
3387
3306
|
["b", bytes, current?.mode]
|
|
3388
3307
|
]) {
|
|
3389
3308
|
if (mode === void 0) continue;
|
|
3390
|
-
const file =
|
|
3309
|
+
const file = join4(scratch, side, ...change.entry.path.split("/"));
|
|
3391
3310
|
await mkdir2(dirname(file), { recursive: true });
|
|
3392
3311
|
await writeFile2(file, content, { flag: "wx", mode: 384 });
|
|
3393
3312
|
if (process.platform !== "win32") await chmod(file, mode === "100755" ? 448 : 384);
|
|
3394
3313
|
}
|
|
3395
|
-
await writeFile2(
|
|
3314
|
+
await writeFile2(join4(scratch, "gitconfig"), "", { flag: "wx", mode: 384 });
|
|
3396
3315
|
text = decode(await work.git(scratch, [
|
|
3397
3316
|
"-c",
|
|
3398
3317
|
"core.quotePath=false",
|
|
@@ -3439,9 +3358,9 @@ var SessionGitDiffReader = class {
|
|
|
3439
3358
|
#active = 0;
|
|
3440
3359
|
async read(sessionId, data, version = SESSION_GIT_DIFF_PARTIAL_VERSION) {
|
|
3441
3360
|
if (!SessionGitDiffDataSchema.safeParse(data).success || data.path !== void 0 && !safePath(data.path)) {
|
|
3442
|
-
|
|
3361
|
+
fail2("INVALID_DIFF_PATH", "The project diff request is invalid");
|
|
3443
3362
|
}
|
|
3444
|
-
if (this.#active >= SESSION_GIT_DIFF_CONCURRENCY)
|
|
3363
|
+
if (this.#active >= SESSION_GIT_DIFF_CONCURRENCY) fail2("DIFF_BUSY", "Too many project diff requests");
|
|
3445
3364
|
this.#active++;
|
|
3446
3365
|
const work = new Work(version >= SESSION_GIT_DIFF_PARTIAL_VERSION);
|
|
3447
3366
|
const pending = this.#read(sessionId, data, work, version).finally(() => {
|
|
@@ -3468,33 +3387,33 @@ var SessionGitDiffReader = class {
|
|
|
3468
3387
|
async #context(sessionId, rootRevision, work) {
|
|
3469
3388
|
const metadata = await this.metadata(sessionId);
|
|
3470
3389
|
work.check();
|
|
3471
|
-
if (metadata === void 0)
|
|
3390
|
+
if (metadata === void 0) fail2("SESSION_NOT_FOUND", "The session is unavailable");
|
|
3472
3391
|
const workingDirectory = metadata.workingDirectory;
|
|
3473
|
-
if (!workingDirectory || !
|
|
3474
|
-
|
|
3392
|
+
if (!workingDirectory || !isAbsolute3(workingDirectory)) {
|
|
3393
|
+
fail2("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
|
|
3475
3394
|
}
|
|
3476
3395
|
let root;
|
|
3477
3396
|
let rootIdentity;
|
|
3478
3397
|
try {
|
|
3479
|
-
root = await
|
|
3480
|
-
if ((await
|
|
3481
|
-
|
|
3398
|
+
root = await realpath3(workingDirectory);
|
|
3399
|
+
if ((await lstat3(workingDirectory)).isSymbolicLink() || !samePath(root, resolve2(workingDirectory))) {
|
|
3400
|
+
fail2("DIFF_BLOCKED", "Links cannot be compared");
|
|
3482
3401
|
}
|
|
3483
|
-
const info = await
|
|
3484
|
-
if (!info.isDirectory())
|
|
3402
|
+
const info = await stat3(root, { bigint: true });
|
|
3403
|
+
if (!info.isDirectory()) fail2("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
|
|
3485
3404
|
rootIdentity = sessionRootIdentity(root, info);
|
|
3486
3405
|
} catch (error) {
|
|
3487
3406
|
if (error instanceof SessionGitDiffError) throw error;
|
|
3488
3407
|
throw new SessionGitDiffError("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable", { cause: error });
|
|
3489
3408
|
}
|
|
3490
|
-
if (
|
|
3491
|
-
|
|
3409
|
+
if (createHash4("sha256").update(rootIdentity).digest("base64url") !== rootRevision) {
|
|
3410
|
+
fail2("SESSION_ROOT_CHANGED", "The session directory changed");
|
|
3492
3411
|
}
|
|
3493
3412
|
let repository;
|
|
3494
3413
|
try {
|
|
3495
3414
|
const top = decode(await work.git(root, ["rev-parse", "--show-toplevel"])).replace(/\r?\n$/u, "");
|
|
3496
|
-
if (!
|
|
3497
|
-
repository = await
|
|
3415
|
+
if (!isAbsolute3(top)) fail2("DIFF_UNAVAILABLE", "Git returned an invalid repository");
|
|
3416
|
+
repository = await realpath3(top);
|
|
3498
3417
|
} catch (error) {
|
|
3499
3418
|
if (error instanceof SessionGitDiffError) throw error;
|
|
3500
3419
|
if (isGitRepositoryUnavailableError(error)) {
|
|
@@ -3506,9 +3425,9 @@ var SessionGitDiffReader = class {
|
|
|
3506
3425
|
}
|
|
3507
3426
|
throw error;
|
|
3508
3427
|
}
|
|
3509
|
-
if (!contained(repository, root))
|
|
3428
|
+
if (!contained(repository, root)) fail2("DIFF_BLOCKED", "The repository is outside the session root");
|
|
3510
3429
|
if (decode(await work.git(root, ["rev-parse", "--show-superproject-working-tree"])).trim() !== "") {
|
|
3511
|
-
|
|
3430
|
+
fail2("DIFF_BLOCKED", "Submodule content cannot be compared");
|
|
3512
3431
|
}
|
|
3513
3432
|
return {
|
|
3514
3433
|
root,
|
|
@@ -3516,8 +3435,8 @@ var SessionGitDiffReader = class {
|
|
|
3516
3435
|
rootIdentity,
|
|
3517
3436
|
workingDirectory,
|
|
3518
3437
|
repository,
|
|
3519
|
-
repositoryIdentity: sessionRootIdentity(repository, await
|
|
3520
|
-
prefix:
|
|
3438
|
+
repositoryIdentity: sessionRootIdentity(repository, await stat3(repository, { bigint: true })),
|
|
3439
|
+
prefix: relative(repository, root).split(sep).join("/"),
|
|
3521
3440
|
...await base(repository, work)
|
|
3522
3441
|
};
|
|
3523
3442
|
}
|
|
@@ -3536,7 +3455,7 @@ var SessionGitDiffReader = class {
|
|
|
3536
3455
|
if (selected === void 0) changed();
|
|
3537
3456
|
if (selected.entry.error !== void 0) {
|
|
3538
3457
|
const error = selected.entry.error;
|
|
3539
|
-
|
|
3458
|
+
fail2(
|
|
3540
3459
|
work.partial && error.code === "DIFF_BLOCKED" ? "DIFF_FILE_BLOCKED" : error.code,
|
|
3541
3460
|
`${data.path}: ${error.message}`
|
|
3542
3461
|
);
|
|
@@ -3550,7 +3469,7 @@ var SessionGitDiffReader = class {
|
|
|
3550
3469
|
}
|
|
3551
3470
|
if (version < SESSION_GIT_DIFF_PARTIAL_VERSION) {
|
|
3552
3471
|
const blocked = files.find(({ entry }) => entry.error !== void 0)?.entry;
|
|
3553
|
-
if (blocked?.error !== void 0)
|
|
3472
|
+
if (blocked?.error !== void 0) fail2(blocked.error.code, `${blocked.path}: ${blocked.error.message}`);
|
|
3554
3473
|
}
|
|
3555
3474
|
let latest;
|
|
3556
3475
|
try {
|
|
@@ -3565,7 +3484,7 @@ var SessionGitDiffReader = class {
|
|
|
3565
3484
|
throw error;
|
|
3566
3485
|
}
|
|
3567
3486
|
if (latest.workingDirectory !== context.workingDirectory || latest.rootIdentity !== context.rootIdentity) {
|
|
3568
|
-
|
|
3487
|
+
fail2("SESSION_ROOT_CHANGED", "The session directory changed");
|
|
3569
3488
|
}
|
|
3570
3489
|
if (latest.repositoryIdentity !== context.repositoryIdentity || latest.baseRef !== context.baseRef || latest.baseCommit !== context.baseCommit) changed();
|
|
3571
3490
|
if (selected !== void 0) {
|
|
@@ -3585,7 +3504,7 @@ var SessionGitDiffReader = class {
|
|
|
3585
3504
|
};
|
|
3586
3505
|
|
|
3587
3506
|
// src/timeline-image-cache.ts
|
|
3588
|
-
import { createHash as
|
|
3507
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
3589
3508
|
var TimelineAssetError = class extends Error {
|
|
3590
3509
|
constructor(code, message, options) {
|
|
3591
3510
|
super(message, options);
|
|
@@ -3654,7 +3573,7 @@ var TimelineImageCache = class {
|
|
|
3654
3573
|
if (attachment.kind !== "image" || attachment.data === void 0) return attachment;
|
|
3655
3574
|
const parsed = ConversationAttachmentSchema.parse(attachment);
|
|
3656
3575
|
const bytes = Buffer.from(attachment.data, "base64");
|
|
3657
|
-
if (bytes.length !== parsed.byteLength ||
|
|
3576
|
+
if (bytes.length !== parsed.byteLength || createHash5("sha256").update(bytes).digest("hex") !== parsed.sha256 || !hasSignature(bytes, parsed.mimeType)) {
|
|
3658
3577
|
throw new TimelineAssetError("IMAGE_INVALID", "Image content does not match its metadata");
|
|
3659
3578
|
}
|
|
3660
3579
|
const key = JSON.stringify([sessionId, parsed.sha256]);
|
|
@@ -3710,8 +3629,43 @@ function createCommunicationOperations(options) {
|
|
|
3710
3629
|
const gitDiffReader = new SessionGitDiffReader(async (sessionId) => adapter.getSessionDirectoryMetadata?.(sessionId), options.gitDiffDirectory);
|
|
3711
3630
|
const getSessionProjectIdentity = adapter.getSessionProjectIdentity?.bind(adapter);
|
|
3712
3631
|
const createGroupChat = adapter.createGroupChat?.bind(adapter);
|
|
3632
|
+
const createEncryptedGroupChat = adapter.createEncryptedGroupChat?.bind(adapter);
|
|
3633
|
+
const authorizeEncryptedPeer = options.authorizeEncryptedPeer;
|
|
3713
3634
|
const renameSession = adapter.renameSession?.bind(adapter);
|
|
3714
3635
|
return [
|
|
3636
|
+
...createEncryptedGroupChat === void 0 ? [] : [
|
|
3637
|
+
sessionCommunicationOperation({
|
|
3638
|
+
operation: ENCRYPTED_GROUP_CREATE_OPERATION,
|
|
3639
|
+
version: ENCRYPTED_PEER_VERSION,
|
|
3640
|
+
schema: EncryptedGroupCreateSchema,
|
|
3641
|
+
handle: async (data, request2) => {
|
|
3642
|
+
const assertAccess = options.captureRequestAccess();
|
|
3643
|
+
assertAccess();
|
|
3644
|
+
const session = await createEncryptedGroupChat(request2.sessionId, data, assertAccess);
|
|
3645
|
+
assertAccess();
|
|
3646
|
+
return SessionCommunicationDataSchema.parse(GroupChatCreateResultDataSchema.parse({ session }));
|
|
3647
|
+
},
|
|
3648
|
+
onError: (error) => unsupportedOperation(error) ?? (error instanceof SessionOperationError || error instanceof GroupChatError || error instanceof SessionNotSharedError ? { code: error.code, message: error.message } : { code: "ENCRYPTED_GROUP_CREATE_FAILED", message: "The encrypted group could not be created. Check both paired PCs and retry." })
|
|
3649
|
+
})
|
|
3650
|
+
],
|
|
3651
|
+
...authorizeEncryptedPeer === void 0 ? [] : [
|
|
3652
|
+
sessionCommunicationOperation({
|
|
3653
|
+
operation: ENCRYPTED_PEER_AUTHORIZE_OPERATION,
|
|
3654
|
+
version: ENCRYPTED_PEER_VERSION,
|
|
3655
|
+
schema: EncryptedPeerAuthorizationSchema,
|
|
3656
|
+
handle: async (data, request2) => {
|
|
3657
|
+
const assertAccess = options.captureRequestAccess();
|
|
3658
|
+
assertAccess();
|
|
3659
|
+
const result = await authorizeEncryptedPeer(request2.sessionId, data, assertAccess);
|
|
3660
|
+
assertAccess();
|
|
3661
|
+
return result;
|
|
3662
|
+
},
|
|
3663
|
+
onError: (error) => unsupportedOperation(error) ?? (error instanceof GroupChatError || error instanceof SessionNotSharedError ? { code: error.code, message: error.message } : {
|
|
3664
|
+
code: "ENCRYPTED_PEER_AUTHORIZATION_FAILED",
|
|
3665
|
+
message: "Encrypted peer authorization failed. Check both paired PCs and retry."
|
|
3666
|
+
})
|
|
3667
|
+
})
|
|
3668
|
+
],
|
|
3715
3669
|
...options.workbenchOperations,
|
|
3716
3670
|
...imageBlob === void 0 ? [] : [
|
|
3717
3671
|
sessionCommunicationOperation({
|
|
@@ -3801,17 +3755,17 @@ function createCommunicationOperations(options) {
|
|
|
3801
3755
|
operation: SESSION_DIRECTORY_LIST_OPERATION,
|
|
3802
3756
|
version: SESSION_DIRECTORY_LIST_VERSION,
|
|
3803
3757
|
schema: SessionDirectoryListDataSchema,
|
|
3804
|
-
handle: async ({ path }, request2) => SessionDirectoryListResultDataSchema.parse({
|
|
3758
|
+
handle: async ({ path, space }, request2) => SessionCommunicationDataSchema.parse(SessionDirectoryListResultDataSchema.parse({
|
|
3805
3759
|
path,
|
|
3806
|
-
...await directoryLister.list(request2.sessionId, path)
|
|
3807
|
-
}),
|
|
3760
|
+
...await directoryLister.list(request2.sessionId, path, space)
|
|
3761
|
+
})),
|
|
3808
3762
|
onError: (error) => unsupportedOperation(error) ?? (error instanceof SessionDirectoryError ? { code: error.code, message: error.message } : { code: "DIRECTORY_UNAVAILABLE", message: "The directory is unavailable" })
|
|
3809
3763
|
}),
|
|
3810
3764
|
...[SESSION_FILE_READ_VERSION, SESSION_FILE_READ_V2_VERSION].map((version) => sessionCommunicationOperation({
|
|
3811
3765
|
operation: SESSION_FILE_READ_OPERATION,
|
|
3812
3766
|
version,
|
|
3813
3767
|
schema: SessionFileReadDataSchema,
|
|
3814
|
-
handle: ({ path, rootRevision }, request2) => fileReader.read(request2.sessionId, path, rootRevision, version),
|
|
3768
|
+
handle: ({ path, rootRevision, space }, request2) => fileReader.read(request2.sessionId, path, rootRevision, version, space),
|
|
3815
3769
|
onError: (error) => unsupportedOperation(error) ?? {
|
|
3816
3770
|
code: error instanceof SessionFileReadError ? error.code : "FILE_UNAVAILABLE",
|
|
3817
3771
|
message: "The file preview is unavailable"
|
|
@@ -3821,10 +3775,10 @@ function createCommunicationOperations(options) {
|
|
|
3821
3775
|
operation: SESSION_FILE_DOWNLOAD_OPERATION,
|
|
3822
3776
|
version: SESSION_FILE_DOWNLOAD_VERSION,
|
|
3823
3777
|
schema: SessionFileDownloadDataSchema,
|
|
3824
|
-
handle: async ({ path, rootRevision }, request2) => {
|
|
3778
|
+
handle: async ({ path, rootRevision, space }, request2) => {
|
|
3825
3779
|
const assertAccess = options.captureRequestAccess();
|
|
3826
3780
|
assertAccess();
|
|
3827
|
-
const result = await fileReader.download(request2.sessionId, path, rootRevision);
|
|
3781
|
+
const result = await fileReader.download(request2.sessionId, path, rootRevision, space);
|
|
3828
3782
|
assertAccess();
|
|
3829
3783
|
return result;
|
|
3830
3784
|
},
|
|
@@ -3837,7 +3791,7 @@ function createCommunicationOperations(options) {
|
|
|
3837
3791
|
operation: SESSION_RESOURCE_READ_OPERATION,
|
|
3838
3792
|
version: SESSION_RESOURCE_READ_VERSION,
|
|
3839
3793
|
schema: SessionResourceReadDataSchema,
|
|
3840
|
-
handle: ({ path, rootRevision }, request2) => fileReader.readResource(request2.sessionId, path, rootRevision),
|
|
3794
|
+
handle: ({ path, rootRevision, space }, request2) => fileReader.readResource(request2.sessionId, path, rootRevision, space),
|
|
3841
3795
|
onError: (error) => unsupportedOperation(error) ?? {
|
|
3842
3796
|
code: error instanceof SessionFileReadError ? error.code : "FILE_UNAVAILABLE",
|
|
3843
3797
|
message: "The resource is unavailable"
|
|
@@ -3879,14 +3833,21 @@ var SessionCommunicationHandler = class {
|
|
|
3879
3833
|
const workbench = adapter.agentId === "copilot" || adapter.agentId === "managed" ? adapter.workbench : void 0;
|
|
3880
3834
|
const researchWorkbench = workbench === void 0 ? void 0 : research;
|
|
3881
3835
|
this.#operations = workbench === void 0 && researchWorkbench === void 0 ? void 0 : new SessionOperations({
|
|
3882
|
-
directory:
|
|
3836
|
+
directory: join5(config.dataDirectory, "workbench"),
|
|
3883
3837
|
agentRunId,
|
|
3884
3838
|
namespace: `${config.userId}\0${machineId}`,
|
|
3885
3839
|
onError: operationError
|
|
3886
3840
|
});
|
|
3887
3841
|
this.#dispatcher = new SessionCommunicationDispatcher(createCommunicationOperations({
|
|
3888
3842
|
adapter,
|
|
3889
|
-
|
|
3843
|
+
...options.authorizeEncryptedPeer === void 0 ? {} : {
|
|
3844
|
+
authorizeEncryptedPeer: (sessionId, data, check) => {
|
|
3845
|
+
const clientId = this.#requestContext.getStore()?.clientId;
|
|
3846
|
+
if (clientId === void 0 || options.authorizeEncryptedPeer === void 0) throw new SessionNotSharedError();
|
|
3847
|
+
return options.authorizeEncryptedPeer(sessionId, data, clientId, check);
|
|
3848
|
+
}
|
|
3849
|
+
},
|
|
3850
|
+
gitDiffDirectory: join5(config.dataDirectory, "git-diff"),
|
|
3890
3851
|
publications: options.publications,
|
|
3891
3852
|
captureRequestAccess: () => {
|
|
3892
3853
|
const assertCurrent = this.#requestContext.getStore()?.assertRequestCurrent;
|
|
@@ -3930,6 +3891,7 @@ var SessionCommunicationHandler = class {
|
|
|
3930
3891
|
return [
|
|
3931
3892
|
...this.#dispatcher.capabilities.filter((capability) => (capability !== GROUP_CHAT_CREATE_CAPABILITY || this.options.adapter.groupChatEnabled !== false) && (schedulesAvailable || !SCHEDULE_OPERATIONS.some((operation) => capability === workbenchCapability(operation)))),
|
|
3932
3893
|
...this.options.research?.chat === void 0 ? [] : [RESEARCH_CHAT_CAPABILITY],
|
|
3894
|
+
...this.options.adapter.getSessionDirectoryMetadata === void 0 ? [] : [SESSION_STATE_FILES_CAPABILITY],
|
|
3933
3895
|
...schedulesAvailable ? [SCHEDULES_CAPABILITY] : []
|
|
3934
3896
|
];
|
|
3935
3897
|
}
|
|
@@ -4063,7 +4025,7 @@ var SessionCommunicationHandler = class {
|
|
|
4063
4025
|
}
|
|
4064
4026
|
const clientId = scope.clientId;
|
|
4065
4027
|
const owner = [config.userId, machineId, clientId, request2.sessionId];
|
|
4066
|
-
const key = (parts) =>
|
|
4028
|
+
const key = (parts) => createHash6("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24);
|
|
4067
4029
|
const knownSource = this.#researchParents.get(request2.sessionId) ?? adapter.sessionPublicationSource?.(request2.sessionId) ?? request2.sessionId;
|
|
4068
4030
|
const arrivalPublication = adapter.isSessionVisible?.(knownSource) === true ? publications.capture(knownSource) : void 0;
|
|
4069
4031
|
let researchParent = this.#researchParents.get(request2.sessionId);
|
|
@@ -4097,7 +4059,7 @@ var SessionCommunicationHandler = class {
|
|
|
4097
4059
|
if (researchParent !== void 0) {
|
|
4098
4060
|
if (lifecycle !== void 0) lifecycle.preflightPhase = "isolation";
|
|
4099
4061
|
const unifiedSync = research?.chat !== void 0 && this.options.supportsResearchChat?.(clientId) === true && (request2.operation === TIMELINE_SYNC_OPERATION || request2.operation === TIMELINE_IMAGE_OPERATION || request2.operation === TIMELINE_IMAGE_BLOB_OPERATION);
|
|
4100
|
-
if (!unifiedSync && !["research.timeline", "research.send", "research.abort", "research.delete", "operation.get", "insights.read"].includes(request2.operation)) {
|
|
4062
|
+
if (!unifiedSync && !["research.timeline", "research.send", "research.abort", "research.delete", "operation.get", "insights.read", "analytics.read"].includes(request2.operation)) {
|
|
4101
4063
|
reject("research-isolated");
|
|
4102
4064
|
emit("session.communication", sessionCommunicationError(request2, {
|
|
4103
4065
|
code: "RESEARCH_SESSION_ISOLATED",
|
|
@@ -4243,11 +4205,11 @@ var SessionCommunicationHandler = class {
|
|
|
4243
4205
|
};
|
|
4244
4206
|
|
|
4245
4207
|
// src/service/requests/device-text-input.ts
|
|
4246
|
-
import { createHash as
|
|
4208
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
4247
4209
|
|
|
4248
4210
|
// src/windows-text-input.ts
|
|
4249
4211
|
import { spawn } from "node:child_process";
|
|
4250
|
-
import { join as
|
|
4212
|
+
import { join as join6 } from "node:path";
|
|
4251
4213
|
var TextInputError = class extends Error {
|
|
4252
4214
|
constructor(code) {
|
|
4253
4215
|
super(code);
|
|
@@ -4331,7 +4293,7 @@ function createWindowsTextInput() {
|
|
|
4331
4293
|
if (process.platform !== "win32") return void 0;
|
|
4332
4294
|
const root = process.env["SystemRoot"];
|
|
4333
4295
|
if (root === void 0) return void 0;
|
|
4334
|
-
const executable =
|
|
4296
|
+
const executable = join6(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
4335
4297
|
return (data) => runWindowsTextInput(executable, data);
|
|
4336
4298
|
}
|
|
4337
4299
|
function runWindowsTextInput(executable, data) {
|
|
@@ -4348,32 +4310,32 @@ function runWindowsTextInput(executable, data) {
|
|
|
4348
4310
|
], { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
4349
4311
|
let stdout = "";
|
|
4350
4312
|
let finished = false;
|
|
4351
|
-
const
|
|
4313
|
+
const fail3 = (code) => {
|
|
4352
4314
|
if (finished) return;
|
|
4353
4315
|
finished = true;
|
|
4354
4316
|
clearTimeout(timer);
|
|
4355
4317
|
child.kill();
|
|
4356
4318
|
reject(new TextInputError(code));
|
|
4357
4319
|
};
|
|
4358
|
-
const timer = setTimeout(() =>
|
|
4359
|
-
child.on("error", () =>
|
|
4360
|
-
child.stdin.on("error", () =>
|
|
4320
|
+
const timer = setTimeout(() => fail3("TEXT_INPUT_TIMEOUT"), timeout);
|
|
4321
|
+
child.on("error", () => fail3("TEXT_INPUT_UNAVAILABLE"));
|
|
4322
|
+
child.stdin.on("error", () => fail3("TEXT_INPUT_UNAVAILABLE"));
|
|
4361
4323
|
child.stdout.setEncoding("utf8");
|
|
4362
4324
|
child.stdout.on("data", (chunk) => {
|
|
4363
4325
|
stdout += chunk;
|
|
4364
|
-
if (stdout.length > 4096)
|
|
4326
|
+
if (stdout.length > 4096) fail3("INVALID_TEXT_INPUT_RESULT");
|
|
4365
4327
|
});
|
|
4366
4328
|
child.stderr.resume();
|
|
4367
4329
|
child.on("close", (code) => {
|
|
4368
4330
|
if (finished) return;
|
|
4369
|
-
if (code !== 0) return
|
|
4331
|
+
if (code !== 0) return fail3("TEXT_INPUT_UNAVAILABLE");
|
|
4370
4332
|
try {
|
|
4371
4333
|
const result = DeviceTextInputResultSchema.parse(JSON.parse(stdout));
|
|
4372
4334
|
finished = true;
|
|
4373
4335
|
clearTimeout(timer);
|
|
4374
4336
|
resolve5(result);
|
|
4375
4337
|
} catch {
|
|
4376
|
-
|
|
4338
|
+
fail3("INVALID_TEXT_INPUT_RESULT");
|
|
4377
4339
|
}
|
|
4378
4340
|
});
|
|
4379
4341
|
child.stdin.end(JSON.stringify(data), "utf8");
|
|
@@ -4403,7 +4365,7 @@ var DeviceTextInputHandler = class {
|
|
|
4403
4365
|
const now = Date.now();
|
|
4404
4366
|
for (const [key2, item] of this.requests) if (item.expiresAt <= now) this.requests.delete(key2);
|
|
4405
4367
|
const key = JSON.stringify([scope.clientId, request2.requestId]);
|
|
4406
|
-
const fingerprint =
|
|
4368
|
+
const fingerprint = createHash7("sha256").update(JSON.stringify(data.data)).digest("hex");
|
|
4407
4369
|
const cached = this.requests.get(key);
|
|
4408
4370
|
if (cached !== void 0) return cached.fingerprint === fingerprint ? cached.response : error("REQUEST_ID_REUSED");
|
|
4409
4371
|
if (data.data.expiresAt <= now || data.data.expiresAt > now + DEVICE_TEXT_INPUT_TTL_MS + MAX_CLOCK_SKEW_MS) {
|
|
@@ -4435,23 +4397,23 @@ function textInputErrorMessage(code) {
|
|
|
4435
4397
|
}
|
|
4436
4398
|
|
|
4437
4399
|
// src/desktop-workspaces.ts
|
|
4438
|
-
import { createHash as
|
|
4439
|
-
import { readdir, realpath as
|
|
4400
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
4401
|
+
import { readdir, realpath as realpath4, stat as stat4 } from "node:fs/promises";
|
|
4440
4402
|
import { homedir } from "node:os";
|
|
4441
|
-
import { basename, join as
|
|
4403
|
+
import { basename, join as join7, normalize } from "node:path";
|
|
4442
4404
|
function desktopRootCandidates(environment2 = process.env) {
|
|
4443
4405
|
const candidates = [
|
|
4444
4406
|
environment2.AGENTKNIGHT_WORKSPACE_ROOT,
|
|
4445
|
-
environment2.OneDrive === void 0 ? void 0 :
|
|
4446
|
-
environment2.OneDriveCommercial === void 0 ? void 0 :
|
|
4447
|
-
environment2.OneDriveConsumer === void 0 ? void 0 :
|
|
4448
|
-
|
|
4407
|
+
environment2.OneDrive === void 0 ? void 0 : join7(environment2.OneDrive, "Desktop"),
|
|
4408
|
+
environment2.OneDriveCommercial === void 0 ? void 0 : join7(environment2.OneDriveCommercial, "Desktop"),
|
|
4409
|
+
environment2.OneDriveConsumer === void 0 ? void 0 : join7(environment2.OneDriveConsumer, "Desktop"),
|
|
4410
|
+
join7(environment2.USERPROFILE ?? homedir(), "Desktop")
|
|
4449
4411
|
];
|
|
4450
4412
|
return [...new Set(candidates.filter((path) => path !== void 0))];
|
|
4451
4413
|
}
|
|
4452
4414
|
function workspaceId(path) {
|
|
4453
4415
|
const normalizedPath = workspacePathKey(path);
|
|
4454
|
-
return
|
|
4416
|
+
return createHash8("sha256").update(normalizedPath).digest("base64url").slice(0, 32);
|
|
4455
4417
|
}
|
|
4456
4418
|
function workspacePathKey(path) {
|
|
4457
4419
|
const normalizedPath = normalize(path);
|
|
@@ -4463,8 +4425,8 @@ function isMissingPathError(error) {
|
|
|
4463
4425
|
async function findDesktopRoot(candidates) {
|
|
4464
4426
|
for (const candidate of candidates) {
|
|
4465
4427
|
try {
|
|
4466
|
-
const resolved = await
|
|
4467
|
-
if ((await
|
|
4428
|
+
const resolved = await realpath4(candidate);
|
|
4429
|
+
if ((await stat4(resolved)).isDirectory()) {
|
|
4468
4430
|
return resolved;
|
|
4469
4431
|
}
|
|
4470
4432
|
} catch (error) {
|
|
@@ -4486,7 +4448,7 @@ async function listDesktopWorkspaces(rootOverride) {
|
|
|
4486
4448
|
const workspaces = entries.filter(
|
|
4487
4449
|
(entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name.trim().length > 0
|
|
4488
4450
|
).map((entry) => {
|
|
4489
|
-
const path =
|
|
4451
|
+
const path = join7(root, entry.name);
|
|
4490
4452
|
return {
|
|
4491
4453
|
id: workspaceId(path),
|
|
4492
4454
|
name: entry.name,
|
|
@@ -4506,8 +4468,8 @@ async function resolveSessionWorkspace(path) {
|
|
|
4506
4468
|
return void 0;
|
|
4507
4469
|
}
|
|
4508
4470
|
try {
|
|
4509
|
-
const resolved = await
|
|
4510
|
-
if (!(await
|
|
4471
|
+
const resolved = await realpath4(candidate);
|
|
4472
|
+
if (!(await stat4(resolved)).isDirectory()) {
|
|
4511
4473
|
return void 0;
|
|
4512
4474
|
}
|
|
4513
4475
|
return {
|
|
@@ -4556,9 +4518,9 @@ async function resolveSelectableWorkspace(id, sessionWorkingDirectories, rootOve
|
|
|
4556
4518
|
// src/git-session-worktree.ts
|
|
4557
4519
|
import { execFile as execFile2 } from "node:child_process";
|
|
4558
4520
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4559
|
-
import { lstat as
|
|
4521
|
+
import { lstat as lstat4, mkdir as mkdir3, realpath as realpath5, rmdir } from "node:fs/promises";
|
|
4560
4522
|
import { devNull } from "node:os";
|
|
4561
|
-
import { dirname as dirname2, isAbsolute as
|
|
4523
|
+
import { dirname as dirname2, isAbsolute as isAbsolute4, join as join8, relative as relative2 } from "node:path";
|
|
4562
4524
|
import { promisify as promisify3 } from "node:util";
|
|
4563
4525
|
var execFileAsync = promisify3(execFile2);
|
|
4564
4526
|
function creationEnvironment() {
|
|
@@ -4568,8 +4530,8 @@ function creationEnvironment() {
|
|
|
4568
4530
|
return { ...env, LC_ALL: "C" };
|
|
4569
4531
|
}
|
|
4570
4532
|
function inside(root, path) {
|
|
4571
|
-
const difference =
|
|
4572
|
-
return difference === "" || !
|
|
4533
|
+
const difference = relative2(root, path);
|
|
4534
|
+
return difference === "" || !isAbsolute4(difference) && difference !== ".." && !difference.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
|
|
4573
4535
|
}
|
|
4574
4536
|
async function git(env, ...args) {
|
|
4575
4537
|
const { stdout } = await execFileAsync("git", [
|
|
@@ -4663,23 +4625,23 @@ async function createSessionWorktree(sourceDirectory, requestedBranchName, reque
|
|
|
4663
4625
|
exists = false;
|
|
4664
4626
|
}
|
|
4665
4627
|
if (exists) throw new Error(`Git branch "${branchName}" already exists. Choose a new branch name.`);
|
|
4666
|
-
const primary = await
|
|
4628
|
+
const primary = await realpath5(identity2.mainWorktreeRoot ?? identity2.worktreeRoot);
|
|
4667
4629
|
const parent = dirname2(primary);
|
|
4668
4630
|
if (inside(identity2.worktreeRoot, parent)) {
|
|
4669
4631
|
throw new Error("Cannot create a sibling worktree outside the source checkout. Move the repository and retry.");
|
|
4670
4632
|
}
|
|
4671
|
-
const path =
|
|
4633
|
+
const path = join8(parent, `agentknight-worktree-${suffix}`);
|
|
4672
4634
|
if (path.length > 640) {
|
|
4673
4635
|
throw new Error("The repository path is too long to report worktree recovery safely. Use a checkout closer to the filesystem root.");
|
|
4674
4636
|
}
|
|
4675
4637
|
await mkdir3(path, { mode: 448 });
|
|
4676
|
-
const reserved = await
|
|
4638
|
+
const reserved = await lstat4(path);
|
|
4677
4639
|
try {
|
|
4678
4640
|
await git(env, "-C", identity2.worktreeRoot, "worktree", "add", "-b", branchName, "--", path, head);
|
|
4679
4641
|
} catch (cause) {
|
|
4680
4642
|
let cleanupError;
|
|
4681
4643
|
try {
|
|
4682
|
-
const current = await
|
|
4644
|
+
const current = await lstat4(path);
|
|
4683
4645
|
if (current.dev === reserved.dev && current.ino === reserved.ino) await rmdir(path);
|
|
4684
4646
|
} catch (error) {
|
|
4685
4647
|
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) cleanupError = error;
|
|
@@ -4963,9 +4925,9 @@ var OperationDeduplicator = class {
|
|
|
4963
4925
|
let reject = () => {
|
|
4964
4926
|
throw new Error("Operation not initialized");
|
|
4965
4927
|
};
|
|
4966
|
-
const promise = new Promise((accept,
|
|
4928
|
+
const promise = new Promise((accept, fail3) => {
|
|
4967
4929
|
resolve5 = accept;
|
|
4968
|
-
reject =
|
|
4930
|
+
reject = fail3;
|
|
4969
4931
|
});
|
|
4970
4932
|
const entry = {
|
|
4971
4933
|
fingerprint: options.fingerprint,
|
|
@@ -5241,9 +5203,9 @@ var SessionCommandsHandler = class {
|
|
|
5241
5203
|
};
|
|
5242
5204
|
|
|
5243
5205
|
// src/service/requests/session-prompt.ts
|
|
5244
|
-
import { createHash as
|
|
5206
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
5245
5207
|
function promptOperationFingerprint(request2) {
|
|
5246
|
-
const fingerprint =
|
|
5208
|
+
const fingerprint = createHash9("sha256").update(request2.sessionId).update("\0").update(request2.mode).update("\0").update(request2.prompt).update("\0").update(request2.attachments?.map((attachment) => attachment.sha256).join(",") ?? "").update("\0").update(JSON.stringify(request2.fileAttachments?.map(({ name, mimeType, sha256 }) => ({
|
|
5247
5209
|
name,
|
|
5248
5210
|
mimeType,
|
|
5249
5211
|
sha256
|
|
@@ -5555,58 +5517,99 @@ var A2aPeerClient = class {
|
|
|
5555
5517
|
this.options = options;
|
|
5556
5518
|
}
|
|
5557
5519
|
options;
|
|
5558
|
-
|
|
5520
|
+
#transport(target, encrypted, signal, revocation = false) {
|
|
5521
|
+
if (encrypted !== void 0 && (encrypted.binding.machineId !== this.options.machineId || encrypted.binding.userId !== this.options.userId || encrypted.binding.sessionId !== target.sessionId || encrypted.binding.peerMachineId !== target.targetMachineId || encrypted.binding.peerSessionId !== target.targetSessionId)) {
|
|
5522
|
+
throw new Error("Encrypted peer authorization does not match the requested conversation");
|
|
5523
|
+
}
|
|
5559
5524
|
const endpoint = relayEndpoint(this.options.relayUrl, target);
|
|
5560
5525
|
const cardUrl = `${endpoint.href}/agent-card.json`;
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
|
|
5565
|
-
|
|
5566
|
-
|
|
5567
|
-
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5572
|
-
|
|
5573
|
-
const
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
5581
|
-
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5526
|
+
return async (input, init) => {
|
|
5527
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
5528
|
+
if (url !== endpoint.href && url !== cardUrl) throw new Error("A2A endpoint differs from the configured peer.");
|
|
5529
|
+
const headers = new Headers(input instanceof Request ? input.headers : void 0);
|
|
5530
|
+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
5531
|
+
headers.set("authorization", `Bearer ${await relayRequestToken(this.options)}`);
|
|
5532
|
+
headers.set("x-agentknight-user-id", this.options.userId);
|
|
5533
|
+
headers.set("x-agentknight-machine-id", this.options.machineId);
|
|
5534
|
+
const timeout = new AbortController();
|
|
5535
|
+
const timer = setTimeout(() => timeout.abort(new Error("A2A HTTP request timed out; execution will not be retried.")), HTTP_TIMEOUT_MS);
|
|
5536
|
+
const callSignal = init?.signal ?? (input instanceof Request ? input.signal : void 0) ?? signal;
|
|
5537
|
+
try {
|
|
5538
|
+
const sealed = encrypted?.sealRequest({
|
|
5539
|
+
kind: revocation ? "revoke" : url === cardUrl ? "card" : "rpc",
|
|
5540
|
+
body: revocation || url === cardUrl ? "" : z5.string().parse(init?.body),
|
|
5541
|
+
...headers.get("a2a-version") === null ? {} : { protocolVersion: headers.get("a2a-version") ?? "" }
|
|
5542
|
+
});
|
|
5543
|
+
if (sealed !== void 0) {
|
|
5544
|
+
headers.set("x-agentknight-encrypted-peer", "1");
|
|
5545
|
+
headers.set("content-type", "application/json");
|
|
5546
|
+
}
|
|
5547
|
+
const response = await fetch(sealed === void 0 ? input : endpoint.href, {
|
|
5548
|
+
...init,
|
|
5549
|
+
...sealed === void 0 ? {} : { method: "POST", body: JSON.stringify(sealed) },
|
|
5550
|
+
headers,
|
|
5551
|
+
redirect: "error",
|
|
5552
|
+
signal: AbortSignal.any([callSignal, timeout.signal])
|
|
5553
|
+
});
|
|
5554
|
+
if (!response.ok) {
|
|
5555
|
+
await response.body?.cancel();
|
|
5556
|
+
const reason = response.status === 401 ? "Relay authentication failed." : response.status === 403 ? "Peer communication is disabled or not permitted." : response.status === 404 ? "Peer endpoint is unavailable; the Relay may require an upgrade." : "Check peer availability and Relay compatibility.";
|
|
5557
|
+
throw new Error(`A2A HTTP ${response.status}: ${reason}`);
|
|
5558
|
+
}
|
|
5559
|
+
const reader = response.body?.getReader();
|
|
5560
|
+
const chunks = [];
|
|
5561
|
+
let size = 0;
|
|
5562
|
+
if (reader !== void 0) {
|
|
5563
|
+
try {
|
|
5564
|
+
for (; ; ) {
|
|
5565
|
+
const chunk = await reader.read();
|
|
5566
|
+
if (chunk.done) break;
|
|
5567
|
+
size += chunk.value.byteLength;
|
|
5568
|
+
if (size > (sealed === void 0 ? MAX_RESPONSE_BYTES : ENCRYPTED_PEER_MAX_LENGTH + 4096)) {
|
|
5569
|
+
throw new Error("A2A response exceeds the text budget.");
|
|
5599
5570
|
}
|
|
5600
|
-
|
|
5601
|
-
await reader.cancel();
|
|
5602
|
-
reader.releaseLock();
|
|
5571
|
+
chunks.push(chunk.value);
|
|
5603
5572
|
}
|
|
5573
|
+
} finally {
|
|
5574
|
+
await reader.cancel();
|
|
5575
|
+
reader.releaseLock();
|
|
5604
5576
|
}
|
|
5605
|
-
return new Response(Buffer.concat(chunks), { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
5606
|
-
} finally {
|
|
5607
|
-
clearTimeout(timer);
|
|
5608
5577
|
}
|
|
5609
|
-
|
|
5578
|
+
const body = Buffer.concat(chunks);
|
|
5579
|
+
if (encrypted !== void 0 && sealed !== void 0) {
|
|
5580
|
+
const opened = encrypted.openResponse(A2aRelayResponseSchema.parse({
|
|
5581
|
+
status: response.status,
|
|
5582
|
+
encrypted: true,
|
|
5583
|
+
body: body.toString("utf8")
|
|
5584
|
+
}), sealed.messageId);
|
|
5585
|
+
return new Response(opened.body || null, { status: opened.status, headers: { "content-type": "application/json" } });
|
|
5586
|
+
}
|
|
5587
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
5588
|
+
} finally {
|
|
5589
|
+
clearTimeout(timer);
|
|
5590
|
+
}
|
|
5591
|
+
};
|
|
5592
|
+
}
|
|
5593
|
+
async revoke(channel, signal = AbortSignal.timeout(HTTP_TIMEOUT_MS)) {
|
|
5594
|
+
const target = {
|
|
5595
|
+
sessionId: channel.binding.sessionId,
|
|
5596
|
+
targetMachineId: channel.binding.peerMachineId,
|
|
5597
|
+
targetSessionId: channel.binding.peerSessionId,
|
|
5598
|
+
prompt: ""
|
|
5599
|
+
};
|
|
5600
|
+
const response = await this.#transport(target, channel, signal, true)(
|
|
5601
|
+
relayEndpoint(this.options.relayUrl, target).href
|
|
5602
|
+
);
|
|
5603
|
+
if (response.status !== 204) throw new Error("Peer did not confirm encrypted group revocation");
|
|
5604
|
+
}
|
|
5605
|
+
conversation(target, encrypted) {
|
|
5606
|
+
const endpoint = relayEndpoint(this.options.relayUrl, target);
|
|
5607
|
+
const cardUrl = `${endpoint.href}/agent-card.json`;
|
|
5608
|
+
let contextId;
|
|
5609
|
+
const exchanges = [];
|
|
5610
|
+
let client;
|
|
5611
|
+
const createClient = async (signal) => {
|
|
5612
|
+
const fetchImpl = this.#transport(target, encrypted, signal);
|
|
5610
5613
|
const factory = new ClientFactory({
|
|
5611
5614
|
transports: [new JsonRpcTransportFactory({ fetchImpl })],
|
|
5612
5615
|
cardResolver: new DefaultAgentCardResolver({ fetchImpl })
|
|
@@ -5689,7 +5692,9 @@ var A2aPeerClient = class {
|
|
|
5689
5692
|
};
|
|
5690
5693
|
|
|
5691
5694
|
// src/a2a-server.ts
|
|
5692
|
-
import { createHash as
|
|
5695
|
+
import { createHash as createHash10, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID6, timingSafeEqual } from "node:crypto";
|
|
5696
|
+
import { mkdirSync, readFileSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
5697
|
+
import { dirname as dirname3, join as join9 } from "node:path";
|
|
5693
5698
|
import {
|
|
5694
5699
|
AgentCard,
|
|
5695
5700
|
Role as Role2,
|
|
@@ -5720,7 +5725,6 @@ var MAX_ACTIVE = 4;
|
|
|
5720
5725
|
var MAX_TASKS = 128;
|
|
5721
5726
|
var MAX_RECEIPTS = 256;
|
|
5722
5727
|
var TASK_TTL_MS = 10 * 6e4;
|
|
5723
|
-
var TURN_TIMEOUT_MS = 12e4;
|
|
5724
5728
|
var SHORT_REQUEST_TIMEOUT_MS = 9e3;
|
|
5725
5729
|
var MAX_TEXT2 = 16e3;
|
|
5726
5730
|
var TASK_WIRE_BUDGET = 6e4;
|
|
@@ -5877,6 +5881,8 @@ var A2aPeerServer = class {
|
|
|
5877
5881
|
#fencedSessions = /* @__PURE__ */ new Set();
|
|
5878
5882
|
#buses = new DefaultExecutionEventBusManager();
|
|
5879
5883
|
#store;
|
|
5884
|
+
// Context ownership must outlive cached task bodies without an unbounded context map.
|
|
5885
|
+
#contextKey = randomBytes2(32);
|
|
5880
5886
|
#generation = 0;
|
|
5881
5887
|
#closed = false;
|
|
5882
5888
|
get busy() {
|
|
@@ -5991,7 +5997,7 @@ var A2aPeerServer = class {
|
|
|
5991
5997
|
if (message === void 0) throw new RequestMalformedError("A message is required.");
|
|
5992
5998
|
const scope = scopedOwner(context);
|
|
5993
5999
|
const key = JSON.stringify([scope, message.messageId]);
|
|
5994
|
-
const fingerprint =
|
|
6000
|
+
const fingerprint = createHash10("sha256").update(JSON.stringify(SendMessageRequest.toJSON(params))).digest("hex");
|
|
5995
6001
|
const previous = this.#receipts.get(key);
|
|
5996
6002
|
if (previous !== void 0) {
|
|
5997
6003
|
if (previous.fingerprint !== fingerprint) throw new RequestMalformedError("messageId was already used with different content.");
|
|
@@ -6006,18 +6012,31 @@ var A2aPeerServer = class {
|
|
|
6006
6012
|
if (task === void 0) throw new TaskNotFoundError("This message's task expired; it will not be replayed.");
|
|
6007
6013
|
return taskWithHistory(task, params.configuration?.historyLength);
|
|
6008
6014
|
}
|
|
6015
|
+
const receiptPath = this.host.receiptDirectory === void 0 ? void 0 : join9(this.host.receiptDirectory, createHash10("sha256").update(key).digest("hex"));
|
|
6016
|
+
if (receiptPath !== void 0) {
|
|
6017
|
+
try {
|
|
6018
|
+
const saved = readFileSync(receiptPath, "utf8");
|
|
6019
|
+
if (saved !== fingerprint) throw new RequestMalformedError("messageId was already used with different content.");
|
|
6020
|
+
throw new TaskNotFoundError("This message's task expired; it will not be replayed.");
|
|
6021
|
+
} catch (error) {
|
|
6022
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
6023
|
+
}
|
|
6024
|
+
}
|
|
6009
6025
|
if (message.taskId) {
|
|
6010
6026
|
if (await this.#store.load(message.taskId, context) === void 0) throw new TaskNotFoundError();
|
|
6011
6027
|
throw new UnsupportedOperationError("Tasks cannot be resumed. Send a fresh message in the same context.");
|
|
6012
6028
|
}
|
|
6013
|
-
if (message.contextId && !
|
|
6029
|
+
if (message.contextId && !this.#validContext(message.contextId, scope)) {
|
|
6014
6030
|
throw new RequestMalformedError("Unknown or expired context for this authenticated session.");
|
|
6015
6031
|
}
|
|
6016
6032
|
if (this.#active.size >= MAX_ACTIVE || this.#fencedSessions.has(envelope.targetSessionId) || [...this.#active].some((work2) => work2.sessionId === envelope.targetSessionId)) {
|
|
6017
6033
|
throw new UnsupportedOperationError("The native peer session is busy or its stop is unconfirmed.");
|
|
6018
6034
|
}
|
|
6019
|
-
if (this.#receipts.size >= MAX_RECEIPTS)
|
|
6020
|
-
|
|
6035
|
+
if (receiptPath === void 0 && this.#receipts.size >= MAX_RECEIPTS) {
|
|
6036
|
+
throw new UnsupportedOperationError("Persistent message receipts are required for more peer work.");
|
|
6037
|
+
}
|
|
6038
|
+
const contextId = message.contextId || this.#newContext(scope);
|
|
6039
|
+
const probe = workingTask(randomUUID6(), contextId, message);
|
|
6021
6040
|
if (JSON.stringify(Task.toJSON(probe)).length > TASK_WIRE_BUDGET - 1024) {
|
|
6022
6041
|
throw new ContentTypeNotSupportedError("Text exceeds the response transport budget.");
|
|
6023
6042
|
}
|
|
@@ -6031,14 +6050,18 @@ var A2aPeerServer = class {
|
|
|
6031
6050
|
controller,
|
|
6032
6051
|
done: deferred(),
|
|
6033
6052
|
saved: deferred(),
|
|
6034
|
-
|
|
6035
|
-
cancellationMessage: "Native execution settled after cancellation.",
|
|
6036
|
-
timer: setTimeout(() => {
|
|
6037
|
-
work.expired = true;
|
|
6038
|
-
controller.abort(new Error("The A2A native turn exceeded its deadline."));
|
|
6039
|
-
}, TURN_TIMEOUT_MS)
|
|
6053
|
+
cancellationMessage: "Native execution settled after cancellation."
|
|
6040
6054
|
};
|
|
6041
|
-
|
|
6055
|
+
if (receiptPath !== void 0) {
|
|
6056
|
+
mkdirSync(dirname3(receiptPath), { recursive: true, mode: 448 });
|
|
6057
|
+
writeFileSync2(receiptPath, fingerprint, { flag: "wx", mode: 384, flush: true });
|
|
6058
|
+
if (this.#receipts.size >= MAX_RECEIPTS) {
|
|
6059
|
+
for (const [id, entry] of this.#receipts) {
|
|
6060
|
+
if (this.#receipts.size < MAX_TASKS) break;
|
|
6061
|
+
if (![...this.#active].some((active) => active.receipt === entry)) this.#receipts.delete(id);
|
|
6062
|
+
}
|
|
6063
|
+
}
|
|
6064
|
+
}
|
|
6042
6065
|
this.#receipts.set(key, receipt2);
|
|
6043
6066
|
this.#active.add(work);
|
|
6044
6067
|
context.state.set("a2aWork", work);
|
|
@@ -6054,6 +6077,7 @@ var A2aPeerServer = class {
|
|
|
6054
6077
|
this.#assertReady();
|
|
6055
6078
|
controller.signal.throwIfAborted();
|
|
6056
6079
|
if (work.generation !== this.#generation) throw new UnsupportedOperationError("The peer connection changed.");
|
|
6080
|
+
message.contextId = contextId;
|
|
6057
6081
|
dispatched = true;
|
|
6058
6082
|
const operation = dispatch();
|
|
6059
6083
|
this.#jobs.add(operation);
|
|
@@ -6080,6 +6104,18 @@ var A2aPeerServer = class {
|
|
|
6080
6104
|
throw error;
|
|
6081
6105
|
}
|
|
6082
6106
|
}
|
|
6107
|
+
#contextSignature(scope, nonce) {
|
|
6108
|
+
return createHmac("sha256", this.#contextKey).update(JSON.stringify([scope, this.#generation, nonce])).digest("hex");
|
|
6109
|
+
}
|
|
6110
|
+
#newContext(scope) {
|
|
6111
|
+
const nonce = randomUUID6();
|
|
6112
|
+
return `${nonce}.${this.#contextSignature(scope, nonce)}`;
|
|
6113
|
+
}
|
|
6114
|
+
#validContext(contextId, scope) {
|
|
6115
|
+
const [nonce, signature, extra] = contextId.split(".");
|
|
6116
|
+
if (nonce === void 0 || signature === void 0 || extra !== void 0 || !/^[0-9a-f]{64}$/u.test(signature)) return false;
|
|
6117
|
+
return timingSafeEqual(Buffer.from(signature, "hex"), Buffer.from(this.#contextSignature(scope, nonce), "hex"));
|
|
6118
|
+
}
|
|
6083
6119
|
async #execute(request2, bus) {
|
|
6084
6120
|
const work = [...this.#active].find((entry) => entry === request2.context.state.get("a2aWork"));
|
|
6085
6121
|
if (work === void 0) throw new UnsupportedOperationError("Native task ownership is unavailable.");
|
|
@@ -6095,14 +6131,14 @@ var A2aPeerServer = class {
|
|
|
6095
6131
|
const prompt = request2.userMessage.parts.map((part) => part.content?.$case === "text" ? part.content.value : "").join("\n");
|
|
6096
6132
|
text = await this.host.runTurn(work.sessionId, prompt, { signal: work.controller.signal, awaitNativeSettlement: true });
|
|
6097
6133
|
if (work.controller.signal.aborted) {
|
|
6098
|
-
state =
|
|
6099
|
-
text = work.
|
|
6134
|
+
state = TaskState2.TASK_STATE_CANCELED;
|
|
6135
|
+
text = work.cancellationMessage;
|
|
6100
6136
|
} else if (typeof text !== "string" || text.trim().length === 0 || text.length > MAX_TEXT2) {
|
|
6101
6137
|
throw new InvalidAgentResponseError("Native execution returned empty or oversized text.");
|
|
6102
6138
|
}
|
|
6103
6139
|
} catch (error) {
|
|
6104
6140
|
const canceled = work.controller.signal.aborted && error === work.controller.signal.reason;
|
|
6105
|
-
state = canceled
|
|
6141
|
+
state = canceled ? TaskState2.TASK_STATE_CANCELED : TaskState2.TASK_STATE_FAILED;
|
|
6106
6142
|
text = state === TaskState2.TASK_STATE_CANCELED ? work.cancellationMessage : "Native peer execution failed.";
|
|
6107
6143
|
if (work.controller.signal.aborted && !canceled) {
|
|
6108
6144
|
this.#fencedSessions.add(work.sessionId);
|
|
@@ -6178,7 +6214,6 @@ var A2aPeerServer = class {
|
|
|
6178
6214
|
}
|
|
6179
6215
|
}
|
|
6180
6216
|
#finish(work) {
|
|
6181
|
-
clearTimeout(work.timer);
|
|
6182
6217
|
this.#active.delete(work);
|
|
6183
6218
|
work.done.resolve();
|
|
6184
6219
|
}
|
|
@@ -6263,8 +6298,758 @@ var A2aPeerServer = class {
|
|
|
6263
6298
|
}
|
|
6264
6299
|
};
|
|
6265
6300
|
|
|
6301
|
+
// src/encrypted-peer.ts
|
|
6302
|
+
import { createHash as createHash11, randomUUID as randomUUID7 } from "node:crypto";
|
|
6303
|
+
import { mkdir as mkdir4, readFile as readFile2, readdir as readdir2, rename as rename2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
6304
|
+
import { join as join10 } from "node:path";
|
|
6305
|
+
import { z as z7 } from "zod";
|
|
6306
|
+
var RequestSchema = z7.object({
|
|
6307
|
+
kind: z7.enum(["card", "rpc", "revoke"]),
|
|
6308
|
+
body: z7.string().max(A2A_BODY_MAX_LENGTH),
|
|
6309
|
+
protocolVersion: z7.string().max(32).optional()
|
|
6310
|
+
}).strict().refine((request2) => request2.kind === "rpc" || request2.body === "");
|
|
6311
|
+
var BindingSchema = EncryptedPeerAuthorizationSchema.extend({
|
|
6312
|
+
userId: IdSchema,
|
|
6313
|
+
machineId: IdSchema,
|
|
6314
|
+
sessionId: IdSchema,
|
|
6315
|
+
ownerClientId: IdSchema
|
|
6316
|
+
}).strict();
|
|
6317
|
+
var StoredBindingSchema = BindingSchema.extend({
|
|
6318
|
+
revoked: z7.boolean().optional(),
|
|
6319
|
+
cleanupPending: z7.boolean().optional()
|
|
6320
|
+
}).refine((binding) => !binding.cleanupPending || binding.revoked === true);
|
|
6321
|
+
var PayloadSchema = z7.object({
|
|
6322
|
+
groupId: z7.uuid(),
|
|
6323
|
+
sourceSessionId: IdSchema,
|
|
6324
|
+
request: RequestSchema.optional(),
|
|
6325
|
+
response: A2aRelayResponseSchema.optional(),
|
|
6326
|
+
replyTo: IdSchema.optional()
|
|
6327
|
+
}).strict().refine(
|
|
6328
|
+
(payload) => payload.request !== void 0 ? payload.response === void 0 && payload.replyTo === void 0 : payload.response !== void 0 && payload.response.encrypted === void 0 && payload.replyTo !== void 0
|
|
6329
|
+
);
|
|
6330
|
+
var EncryptedPeerChannel = class {
|
|
6331
|
+
constructor(binding, cipher) {
|
|
6332
|
+
this.binding = binding;
|
|
6333
|
+
this.cipher = cipher;
|
|
6334
|
+
}
|
|
6335
|
+
binding;
|
|
6336
|
+
cipher;
|
|
6337
|
+
get keyId() {
|
|
6338
|
+
return this.cipher.keyId;
|
|
6339
|
+
}
|
|
6340
|
+
sealRequest(request2) {
|
|
6341
|
+
return this.#seal({ request: RequestSchema.parse(request2) });
|
|
6342
|
+
}
|
|
6343
|
+
openRequest(message, sourceMachineId, targetSessionId) {
|
|
6344
|
+
const payload = this.#open(message, sourceMachineId, targetSessionId);
|
|
6345
|
+
if (payload.request === void 0) throw new Error("Expected an encrypted A2A request");
|
|
6346
|
+
return payload.request;
|
|
6347
|
+
}
|
|
6348
|
+
sealResponse(response, replyTo) {
|
|
6349
|
+
const message = this.#seal({ response: A2aRelayResponseSchema.parse(response), replyTo });
|
|
6350
|
+
return { status: 200, encrypted: true, body: JSON.stringify(message) };
|
|
6351
|
+
}
|
|
6352
|
+
openResponse(response, requestId) {
|
|
6353
|
+
if (response.encrypted !== true || response.status !== 200) {
|
|
6354
|
+
throw new Error("The peer did not return an encrypted response; plaintext fallback is forbidden");
|
|
6355
|
+
}
|
|
6356
|
+
const payload = this.#open(JSON.parse(response.body), this.binding.peerMachineId, this.binding.sessionId);
|
|
6357
|
+
if (payload.response === void 0 || payload.replyTo !== requestId) {
|
|
6358
|
+
throw new Error("Encrypted peer response does not belong to this request");
|
|
6359
|
+
}
|
|
6360
|
+
return payload.response;
|
|
6361
|
+
}
|
|
6362
|
+
#seal(value) {
|
|
6363
|
+
const payload = PayloadSchema.parse({
|
|
6364
|
+
groupId: this.binding.groupId,
|
|
6365
|
+
sourceSessionId: this.binding.sessionId,
|
|
6366
|
+
...value
|
|
6367
|
+
});
|
|
6368
|
+
return EncryptedPeerMessageSchema.parse(this.cipher.seal(
|
|
6369
|
+
"session.communication",
|
|
6370
|
+
"pc",
|
|
6371
|
+
this.binding.peerMachineId,
|
|
6372
|
+
this.binding.machineId,
|
|
6373
|
+
this.binding.peerSessionId,
|
|
6374
|
+
payload
|
|
6375
|
+
));
|
|
6376
|
+
}
|
|
6377
|
+
#open(raw, sourceMachineId, targetSessionId) {
|
|
6378
|
+
const message = EncryptedPeerMessageSchema.parse(raw);
|
|
6379
|
+
const binding = this.binding;
|
|
6380
|
+
if (sourceMachineId !== binding.peerMachineId || targetSessionId !== binding.sessionId || message.clientId !== sourceMachineId || message.machineId !== binding.machineId || message.recipientClientId !== binding.sessionId) {
|
|
6381
|
+
throw new Error("Encrypted peer route does not match the authorized sessions");
|
|
6382
|
+
}
|
|
6383
|
+
const payload = PayloadSchema.parse(this.cipher.open(message));
|
|
6384
|
+
if (payload.groupId !== binding.groupId || payload.sourceSessionId !== binding.peerSessionId) {
|
|
6385
|
+
throw new Error("Encrypted peer content does not match the authorized group");
|
|
6386
|
+
}
|
|
6387
|
+
return payload;
|
|
6388
|
+
}
|
|
6389
|
+
};
|
|
6390
|
+
var EncryptedPeerStore = class {
|
|
6391
|
+
constructor(directory, owner) {
|
|
6392
|
+
this.owner = owner;
|
|
6393
|
+
const namespace = createHash11("sha256").update(JSON.stringify([owner.userId, owner.machineId])).digest("hex");
|
|
6394
|
+
this.#directory = join10(directory, "encrypted-peers", namespace);
|
|
6395
|
+
}
|
|
6396
|
+
owner;
|
|
6397
|
+
#requiresEncryption = false;
|
|
6398
|
+
get requiresEncryption() {
|
|
6399
|
+
return this.#requiresEncryption;
|
|
6400
|
+
}
|
|
6401
|
+
#channels = /* @__PURE__ */ new Map();
|
|
6402
|
+
#revoked = /* @__PURE__ */ new Set();
|
|
6403
|
+
#cleanupPending = /* @__PURE__ */ new Set();
|
|
6404
|
+
#writes = Promise.resolve();
|
|
6405
|
+
#directory;
|
|
6406
|
+
async start() {
|
|
6407
|
+
let entries;
|
|
6408
|
+
try {
|
|
6409
|
+
entries = await readdir2(this.#directory, { withFileTypes: true });
|
|
6410
|
+
} catch (error) {
|
|
6411
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
|
|
6412
|
+
throw error;
|
|
6413
|
+
}
|
|
6414
|
+
for (const entry of entries) {
|
|
6415
|
+
if (entry.name === "encrypted-only") this.#requiresEncryption = true;
|
|
6416
|
+
if (!entry.isFile() || !/^[0-9a-f-]{36}\.json$/u.test(entry.name)) continue;
|
|
6417
|
+
const { revoked, cleanupPending, ...binding } = StoredBindingSchema.parse(
|
|
6418
|
+
JSON.parse(await readFile2(join10(this.#directory, entry.name), "utf8"))
|
|
6419
|
+
);
|
|
6420
|
+
if (binding.userId !== this.owner.userId || binding.machineId !== this.owner.machineId || entry.name !== `${binding.groupId}.json`) throw new Error("Encrypted peer authorization belongs to another owner");
|
|
6421
|
+
this.#channels.set(binding.groupId, await this.#channel(binding));
|
|
6422
|
+
if (revoked) this.#revoked.add(binding.groupId);
|
|
6423
|
+
if (cleanupPending) this.#cleanupPending.add(binding.groupId);
|
|
6424
|
+
this.#requiresEncryption = true;
|
|
6425
|
+
}
|
|
6426
|
+
}
|
|
6427
|
+
authorize(sessionId, input, ownerClientId, assertAccess) {
|
|
6428
|
+
const binding = BindingSchema.parse({ ...input, ...this.owner, sessionId, ownerClientId });
|
|
6429
|
+
const work = this.#writes.then(async () => {
|
|
6430
|
+
assertAccess();
|
|
6431
|
+
if (binding.peerMachineId === this.owner.machineId) throw new Error("Encrypted peer authorization requires a different PC");
|
|
6432
|
+
const previous = this.#channels.get(binding.groupId);
|
|
6433
|
+
if (previous !== void 0) {
|
|
6434
|
+
if (this.#revoked.has(binding.groupId)) throw new Error("This group authorization was revoked; create a new group");
|
|
6435
|
+
if (JSON.stringify(previous.binding) !== JSON.stringify(binding)) {
|
|
6436
|
+
throw new Error("This group already has a different encrypted peer authorization");
|
|
6437
|
+
}
|
|
6438
|
+
return { groupId: binding.groupId, keyId: previous.keyId };
|
|
6439
|
+
}
|
|
6440
|
+
if ([...this.#channels.values()].some((channel2) => channel2.keyId === parseContentKey(binding.key).keyId)) {
|
|
6441
|
+
throw new Error("Each encrypted group requires a fresh key");
|
|
6442
|
+
}
|
|
6443
|
+
const channel = await this.#channel(binding);
|
|
6444
|
+
await mkdir4(this.#directory, { recursive: true, mode: 448 });
|
|
6445
|
+
await writeFile3(join10(this.#directory, "encrypted-only"), "", { mode: 384 });
|
|
6446
|
+
this.#requiresEncryption = true;
|
|
6447
|
+
await this.#save(binding, assertAccess);
|
|
6448
|
+
this.#channels.set(binding.groupId, channel);
|
|
6449
|
+
return { groupId: binding.groupId, keyId: channel.keyId };
|
|
6450
|
+
});
|
|
6451
|
+
this.#writes = work.catch(() => void 0);
|
|
6452
|
+
return work;
|
|
6453
|
+
}
|
|
6454
|
+
outbound(groupId, sourceSessionId, peerMachineId, peerSessionId) {
|
|
6455
|
+
const channel = this.#channels.get(groupId);
|
|
6456
|
+
if (channel === void 0 || this.#revoked.has(groupId) || channel.binding.sessionId !== sourceSessionId || channel.binding.peerMachineId !== peerMachineId || channel.binding.peerSessionId !== peerSessionId) {
|
|
6457
|
+
throw new Error("These sessions have no encrypted peer authorization; pair and authorize them first");
|
|
6458
|
+
}
|
|
6459
|
+
return channel;
|
|
6460
|
+
}
|
|
6461
|
+
forSessions(sourceSessionId, peerMachineId, peerSessionId) {
|
|
6462
|
+
return [...this.#channels.values()].filter((channel) => !this.#revoked.has(channel.binding.groupId) && channel.binding.sessionId === sourceSessionId && channel.binding.peerMachineId === peerMachineId && channel.binding.peerSessionId === peerSessionId).sort((a, b) => a.binding.groupId.localeCompare(b.binding.groupId))[0];
|
|
6463
|
+
}
|
|
6464
|
+
isRevoked(groupId) {
|
|
6465
|
+
return this.#revoked.has(groupId);
|
|
6466
|
+
}
|
|
6467
|
+
pendingRevocations() {
|
|
6468
|
+
return [...this.#channels.values()].filter((channel) => this.#cleanupPending.has(channel.binding.groupId));
|
|
6469
|
+
}
|
|
6470
|
+
revoke(groupId, notifyPeer = false) {
|
|
6471
|
+
const work = this.#writes.then(async () => {
|
|
6472
|
+
z7.uuid().parse(groupId);
|
|
6473
|
+
const channel = this.#channels.get(groupId);
|
|
6474
|
+
if (channel === void 0) return;
|
|
6475
|
+
const pending = this.#cleanupPending.has(groupId) || notifyPeer && !this.#revoked.has(groupId);
|
|
6476
|
+
await this.#save({ ...channel.binding, revoked: true, cleanupPending: pending });
|
|
6477
|
+
this.#revoked.add(groupId);
|
|
6478
|
+
if (pending) this.#cleanupPending.add(groupId);
|
|
6479
|
+
});
|
|
6480
|
+
this.#writes = work.catch(() => void 0);
|
|
6481
|
+
return work;
|
|
6482
|
+
}
|
|
6483
|
+
confirmRevocation(groupId) {
|
|
6484
|
+
const work = this.#writes.then(async () => {
|
|
6485
|
+
const channel = this.#channels.get(groupId);
|
|
6486
|
+
if (channel === void 0 || !this.#revoked.has(groupId)) throw new Error("No pending revoked group");
|
|
6487
|
+
await this.#save({ ...channel.binding, revoked: true, cleanupPending: false });
|
|
6488
|
+
this.#cleanupPending.delete(groupId);
|
|
6489
|
+
});
|
|
6490
|
+
this.#writes = work.catch(() => void 0);
|
|
6491
|
+
return work;
|
|
6492
|
+
}
|
|
6493
|
+
async #save(binding, assertAccess) {
|
|
6494
|
+
const path = join10(this.#directory, `${binding.groupId}.json`), staging = `${path}.${randomUUID7()}.staging`;
|
|
6495
|
+
try {
|
|
6496
|
+
await writeFile3(staging, JSON.stringify(binding), { mode: 384, flag: "wx" });
|
|
6497
|
+
assertAccess?.();
|
|
6498
|
+
await rename2(staging, path);
|
|
6499
|
+
} finally {
|
|
6500
|
+
await rm2(staging, { force: true });
|
|
6501
|
+
}
|
|
6502
|
+
}
|
|
6503
|
+
incoming(request2) {
|
|
6504
|
+
if (request2.kind !== "encrypted" || request2.userId !== this.owner.userId) throw new Error("Expected an encrypted request for this owner");
|
|
6505
|
+
const message = EncryptedPeerMessageSchema.parse(JSON.parse(request2.body));
|
|
6506
|
+
const channel = [...this.#channels.values()].find((entry) => entry.keyId === message.keyId && entry.binding.sessionId === request2.targetSessionId && entry.binding.peerMachineId === request2.sourceMachineId);
|
|
6507
|
+
if (channel === void 0) throw new Error("No matching encrypted peer authorization");
|
|
6508
|
+
return { channel, message };
|
|
6509
|
+
}
|
|
6510
|
+
async #channel(binding) {
|
|
6511
|
+
return new EncryptedPeerChannel(binding, await createPersistentContentCipher(
|
|
6512
|
+
join10(this.#directory, binding.groupId),
|
|
6513
|
+
parseContentKey(binding.key),
|
|
6514
|
+
{ rejectReplayOverflow: true }
|
|
6515
|
+
));
|
|
6516
|
+
}
|
|
6517
|
+
};
|
|
6518
|
+
|
|
6519
|
+
// src/encrypted-group-sessions.ts
|
|
6520
|
+
import { createHash as createHash12, randomUUID as randomUUID8 } from "node:crypto";
|
|
6521
|
+
import { chmod as chmod2, lstat as lstat5, mkdir as mkdir5, open as open3, readFile as readFile3, realpath as realpath6, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
|
|
6522
|
+
import { join as join11 } from "node:path";
|
|
6523
|
+
import { z as z8 } from "zod";
|
|
6524
|
+
var Prefix = "encrypted-group:";
|
|
6525
|
+
var GroupSessionSchema = SessionSummarySchema.extend({ groupChat: GroupChatInfoSchema });
|
|
6526
|
+
var GroupSchema = z8.object({
|
|
6527
|
+
session: GroupSessionSchema,
|
|
6528
|
+
sourceId: z8.string(),
|
|
6529
|
+
peer: EncryptedGroupCreateSchema,
|
|
6530
|
+
queue: z8.array(z8.object({ text: z8.string(), turnId: z8.string() })).default([])
|
|
6531
|
+
});
|
|
6532
|
+
var OperationSchema = z8.object({ id: z8.string(), digest: z8.string(), messageId: z8.string() });
|
|
6533
|
+
var LegacyJournalSchema = z8.object({
|
|
6534
|
+
version: z8.literal(1),
|
|
6535
|
+
groups: z8.array(GroupSchema.extend({
|
|
6536
|
+
items: z8.array(ConversationItemSchema),
|
|
6537
|
+
operations: z8.array(OperationSchema)
|
|
6538
|
+
}))
|
|
6539
|
+
}).strict();
|
|
6540
|
+
var JsonRow = z8.object({ data: z8.string() });
|
|
6541
|
+
function unavailable(message = "This action is unavailable on an encrypted group") {
|
|
6542
|
+
throw new SessionOperationError("GROUP_CHAT_UNAVAILABLE", message);
|
|
6543
|
+
}
|
|
6544
|
+
var EncryptedGroupSessions = class {
|
|
6545
|
+
constructor(inner, directory, owner, keys, run, revocationPending) {
|
|
6546
|
+
this.inner = inner;
|
|
6547
|
+
this.owner = owner;
|
|
6548
|
+
this.keys = keys;
|
|
6549
|
+
this.run = run;
|
|
6550
|
+
this.revocationPending = revocationPending;
|
|
6551
|
+
const namespace = createHash12("sha256").update(JSON.stringify(owner)).digest("hex");
|
|
6552
|
+
this.#directory = join11(directory, "encrypted-groups", namespace);
|
|
6553
|
+
}
|
|
6554
|
+
inner;
|
|
6555
|
+
owner;
|
|
6556
|
+
keys;
|
|
6557
|
+
run;
|
|
6558
|
+
revocationPending;
|
|
6559
|
+
#groups = [];
|
|
6560
|
+
#writes = Promise.resolve();
|
|
6561
|
+
#callbacks;
|
|
6562
|
+
#watched = /* @__PURE__ */ new Set();
|
|
6563
|
+
#jobs = /* @__PURE__ */ new Map();
|
|
6564
|
+
#generations = /* @__PURE__ */ new Map();
|
|
6565
|
+
#directory;
|
|
6566
|
+
#database;
|
|
6567
|
+
#stopping = false;
|
|
6568
|
+
async start() {
|
|
6569
|
+
const db = await this.#db();
|
|
6570
|
+
this.#groups = db.prepare("SELECT data FROM groups ORDER BY rowid").all().map((row) => GroupSchema.parse(JSON.parse(JsonRow.parse(row).data)));
|
|
6571
|
+
for (const group of this.#groups) {
|
|
6572
|
+
if (group.session.userId !== this.owner.userId || group.session.machineId !== this.owner.machineId || group.session.sessionId !== `${Prefix}${group.peer.groupId}`) unavailable("Encrypted group belongs to another owner");
|
|
6573
|
+
}
|
|
6574
|
+
await this.#update((groups) => {
|
|
6575
|
+
for (const group of groups) {
|
|
6576
|
+
if (group.session.groupChat.state === "running" || group.queue.length > 0) {
|
|
6577
|
+
group.items.push(this.#item("notice", "system", "The PC restarted. Interrupted and queued goals were not replayed; send a new message to continue.", void 0));
|
|
6578
|
+
}
|
|
6579
|
+
group.queue = [];
|
|
6580
|
+
group.session.groupChat.state = "paused";
|
|
6581
|
+
}
|
|
6582
|
+
});
|
|
6583
|
+
}
|
|
6584
|
+
owns(id) {
|
|
6585
|
+
return id.startsWith(Prefix);
|
|
6586
|
+
}
|
|
6587
|
+
source(id) {
|
|
6588
|
+
return this.#group(id).sourceId;
|
|
6589
|
+
}
|
|
6590
|
+
get busy() {
|
|
6591
|
+
return this.#jobs.size > 0;
|
|
6592
|
+
}
|
|
6593
|
+
visible(id) {
|
|
6594
|
+
const group = this.#groups.find((entry) => entry.session.sessionId === id);
|
|
6595
|
+
return group !== void 0 && this.inner.isSessionVisible?.(group.sourceId) !== false;
|
|
6596
|
+
}
|
|
6597
|
+
list() {
|
|
6598
|
+
return this.#groups.filter((group) => this.visible(group.session.sessionId)).map((group) => structuredClone(group.session));
|
|
6599
|
+
}
|
|
6600
|
+
setCallbacks(callbacks) {
|
|
6601
|
+
this.#callbacks = callbacks;
|
|
6602
|
+
}
|
|
6603
|
+
async create(sourceId, raw, check) {
|
|
6604
|
+
const peer = EncryptedGroupCreateSchema.parse(raw);
|
|
6605
|
+
check();
|
|
6606
|
+
if (this.inner.groupChatEnabled === false || this.inner.runPeerTurn === void 0 || this.#stopping) unavailable();
|
|
6607
|
+
const source = (await this.inner.listSessions(this.owner.userId, this.owner.machineId)).find((session) => session.sessionId === sourceId && session.userId === this.owner.userId && session.machineId === this.owner.machineId && session.groupChat === void 0);
|
|
6608
|
+
if (source === void 0 || this.inner.isSessionVisible?.(sourceId) === false) unavailable("The source session is no longer shared");
|
|
6609
|
+
this.inner.assertPeerSession?.(sourceId);
|
|
6610
|
+
this.keys.outbound(peer.groupId, sourceId, peer.peerMachineId, peer.peerSessionId);
|
|
6611
|
+
return this.#update((groups) => {
|
|
6612
|
+
check();
|
|
6613
|
+
const previous = groups.find((group) => group.peer.groupId === peer.groupId);
|
|
6614
|
+
if (previous !== void 0) {
|
|
6615
|
+
if (previous.sourceId !== sourceId || previous.peer.peerMachineId !== peer.peerMachineId || previous.peer.peerSessionId !== peer.peerSessionId) unavailable("Group creation conflicts with an earlier request");
|
|
6616
|
+
return structuredClone(previous.session);
|
|
6617
|
+
}
|
|
6618
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
6619
|
+
const session = GroupSessionSchema.parse({
|
|
6620
|
+
...this.owner,
|
|
6621
|
+
sessionId: `${Prefix}${peer.groupId}`,
|
|
6622
|
+
summary: `Group: ${source.summary || sourceId} + ${peer.peerTitle}`,
|
|
6623
|
+
isRemote: false,
|
|
6624
|
+
renameSupported: true,
|
|
6625
|
+
createdAt: now,
|
|
6626
|
+
modifiedAt: now,
|
|
6627
|
+
groupChat: { state: "ready", participants: [
|
|
6628
|
+
{ sessionId: sourceId, title: (source.summary || sourceId).slice(0, 260) },
|
|
6629
|
+
// A local proxy identity avoids collisions between equal native IDs on different PCs.
|
|
6630
|
+
{ sessionId: `encrypted-peer:${peer.groupId}`, title: peer.peerTitle }
|
|
6631
|
+
] }
|
|
6632
|
+
});
|
|
6633
|
+
groups.push({ session, sourceId, peer, items: [], queue: [] });
|
|
6634
|
+
return structuredClone(session);
|
|
6635
|
+
}, check);
|
|
6636
|
+
}
|
|
6637
|
+
async prompt(id, text, operationId) {
|
|
6638
|
+
const prompt = z8.string().trim().min(1).max(16e3).parse(text);
|
|
6639
|
+
if (operationId === void 0) unavailable("A stable prompt operation ID is required");
|
|
6640
|
+
const digest = createHash12("sha256").update(prompt).digest("hex");
|
|
6641
|
+
const generation = this.#generations.get(id) ?? 0;
|
|
6642
|
+
const result = await this.#update((groups, db) => {
|
|
6643
|
+
const group = this.#group(id, groups);
|
|
6644
|
+
if (generation !== (this.#generations.get(id) ?? 0)) unavailable("This prompt was cancelled before admission");
|
|
6645
|
+
const stored = db.prepare("SELECT data FROM operations WHERE session=? AND id=?").get(id, operationId);
|
|
6646
|
+
const previous = stored === void 0 ? void 0 : OperationSchema.parse(JSON.parse(JsonRow.parse(stored).data));
|
|
6647
|
+
if (previous !== void 0) {
|
|
6648
|
+
if (previous.digest !== digest) unavailable("The prompt operation ID was already used for different content");
|
|
6649
|
+
return { messageId: previous.messageId, deliveryState: "queued" };
|
|
6650
|
+
}
|
|
6651
|
+
if (this.#stopping || this.inner.groupChatEnabled === false || !this.visible(id)) unavailable();
|
|
6652
|
+
if (this.#jobs.get(id)?.controller.signal.aborted) unavailable("The group is still pausing; wait for native cancellation before sending a new goal");
|
|
6653
|
+
this.keys.outbound(group.peer.groupId, group.sourceId, group.peer.peerMachineId, group.peer.peerSessionId);
|
|
6654
|
+
const item = this.#item("human-message", "human", prompt, void 0);
|
|
6655
|
+
group.items.push(ConversationItemSchema.parse({ ...item, operationId }));
|
|
6656
|
+
db.prepare("INSERT INTO operations(session,id,data) VALUES(?,?,?)").run(id, operationId, JSON.stringify({ id: operationId, digest, messageId: item.id }));
|
|
6657
|
+
const deliveryState = group.session.groupChat.state === "running" ? "queued" : "processing";
|
|
6658
|
+
group.queue.push({ text: prompt, turnId: item.id });
|
|
6659
|
+
group.session.groupChat.state = "running";
|
|
6660
|
+
return { messageId: item.id, deliveryState };
|
|
6661
|
+
});
|
|
6662
|
+
if (generation === (this.#generations.get(id) ?? 0)) {
|
|
6663
|
+
if (this.#stopping || this.inner.groupChatEnabled === false || !this.visible(id)) {
|
|
6664
|
+
await this.abort(id);
|
|
6665
|
+
} else {
|
|
6666
|
+
this.#schedule(id, generation);
|
|
6667
|
+
}
|
|
6668
|
+
}
|
|
6669
|
+
return result;
|
|
6670
|
+
}
|
|
6671
|
+
#schedule(id, generation) {
|
|
6672
|
+
if (this.#jobs.has(id) || this.#stopping || generation !== (this.#generations.get(id) ?? 0) || this.#group(id).session.groupChat.state !== "running" || this.#group(id).queue.length === 0) return;
|
|
6673
|
+
const controller = new AbortController();
|
|
6674
|
+
const done = this.#drain(id, controller);
|
|
6675
|
+
this.#jobs.set(id, { controller, done });
|
|
6676
|
+
void done.then(() => {
|
|
6677
|
+
this.#jobs.delete(id);
|
|
6678
|
+
if (!controller.signal.aborted) this.#schedule(id, generation);
|
|
6679
|
+
}, (error) => {
|
|
6680
|
+
this.#jobs.delete(id);
|
|
6681
|
+
if (!controller.signal.aborted || error !== controller.signal.reason) this.#callbacks?.onSyncError(id, error);
|
|
6682
|
+
});
|
|
6683
|
+
}
|
|
6684
|
+
async #drain(id, controller) {
|
|
6685
|
+
while (!controller.signal.aborted && !this.#stopping) {
|
|
6686
|
+
const next = await this.#update((groups) => {
|
|
6687
|
+
controller.signal.throwIfAborted();
|
|
6688
|
+
const group = this.#group(id, groups);
|
|
6689
|
+
if (group.session.groupChat.state !== "running") return void 0;
|
|
6690
|
+
return group.queue.shift();
|
|
6691
|
+
});
|
|
6692
|
+
if (next === void 0 || !await this.#execute(id, next.text, next.turnId, controller)) return;
|
|
6693
|
+
}
|
|
6694
|
+
}
|
|
6695
|
+
async #execute(id, prompt, turnId, controller) {
|
|
6696
|
+
const group = this.#group(id);
|
|
6697
|
+
const record = (content, participant) => this.#update((groups) => {
|
|
6698
|
+
controller.signal.throwIfAborted();
|
|
6699
|
+
if (!this.visible(id)) unavailable("The source session is no longer shared");
|
|
6700
|
+
const current = this.#group(id, groups);
|
|
6701
|
+
current.items.push(this.#item(
|
|
6702
|
+
"assistant-message",
|
|
6703
|
+
"subagent",
|
|
6704
|
+
content,
|
|
6705
|
+
turnId,
|
|
6706
|
+
current.session.groupChat.participants[participant]?.sessionId
|
|
6707
|
+
));
|
|
6708
|
+
});
|
|
6709
|
+
try {
|
|
6710
|
+
controller.signal.throwIfAborted();
|
|
6711
|
+
if (this.#stopping || this.inner.groupChatEnabled === false || !this.visible(id)) unavailable();
|
|
6712
|
+
const result = await this.run({
|
|
6713
|
+
sessionId: group.sourceId,
|
|
6714
|
+
targetMachineId: group.peer.peerMachineId,
|
|
6715
|
+
targetSessionId: group.peer.peerSessionId,
|
|
6716
|
+
encryptedGroupId: group.peer.groupId,
|
|
6717
|
+
prompt
|
|
6718
|
+
}, controller.signal, {
|
|
6719
|
+
request: (content) => record(content, 0),
|
|
6720
|
+
reply: (content) => record(content, 1)
|
|
6721
|
+
});
|
|
6722
|
+
await record(result.reply, 0);
|
|
6723
|
+
await this.#update((groups) => {
|
|
6724
|
+
controller.signal.throwIfAborted();
|
|
6725
|
+
const group2 = this.#group(id, groups);
|
|
6726
|
+
group2.session.groupChat.state = group2.queue.length > 0 ? "running" : "ready";
|
|
6727
|
+
});
|
|
6728
|
+
return true;
|
|
6729
|
+
} catch (error) {
|
|
6730
|
+
await this.#update((groups) => {
|
|
6731
|
+
const current = this.#group(id, groups);
|
|
6732
|
+
current.session.groupChat.state = controller.signal.aborted ? "paused" : "blocked";
|
|
6733
|
+
current.queue = [];
|
|
6734
|
+
const item = this.#item(
|
|
6735
|
+
"notice",
|
|
6736
|
+
"system",
|
|
6737
|
+
"The group task stopped. Unknown work was not replayed; send a new message to continue.",
|
|
6738
|
+
turnId
|
|
6739
|
+
);
|
|
6740
|
+
current.items.push(item);
|
|
6741
|
+
});
|
|
6742
|
+
if (!controller.signal.aborted) this.#callbacks?.onSyncError(id, error);
|
|
6743
|
+
return false;
|
|
6744
|
+
}
|
|
6745
|
+
}
|
|
6746
|
+
#item(kind, actor, content, turnId, agentId) {
|
|
6747
|
+
const id = randomUUID8();
|
|
6748
|
+
return ConversationItemSchema.parse({
|
|
6749
|
+
id,
|
|
6750
|
+
revision: 1,
|
|
6751
|
+
turnId: turnId ?? id,
|
|
6752
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6753
|
+
sourceEventIds: [id],
|
|
6754
|
+
sourceMessageIds: [id],
|
|
6755
|
+
kind,
|
|
6756
|
+
actor,
|
|
6757
|
+
content,
|
|
6758
|
+
...kind === "human-message" ? { attachments: [] } : {},
|
|
6759
|
+
...kind === "assistant-message" ? { final: true, agentId } : {},
|
|
6760
|
+
...kind === "notice" ? { title: "Group conversation interrupted", severity: "error" } : {}
|
|
6761
|
+
});
|
|
6762
|
+
}
|
|
6763
|
+
async abort(id) {
|
|
6764
|
+
this.#generations.set(id, (this.#generations.get(id) ?? 0) + 1);
|
|
6765
|
+
const job = this.#jobs.get(id);
|
|
6766
|
+
job?.controller.abort(new Error("Group paused by the user"));
|
|
6767
|
+
await job?.done.catch((error) => {
|
|
6768
|
+
if (!job.controller.signal.aborted) throw error;
|
|
6769
|
+
});
|
|
6770
|
+
await this.#update((groups) => {
|
|
6771
|
+
const group = this.#group(id, groups);
|
|
6772
|
+
if (group.queue.length > 0) {
|
|
6773
|
+
group.items.push(this.#item("notice", "system", "Queued goals were cancelled.", void 0));
|
|
6774
|
+
}
|
|
6775
|
+
group.queue = [];
|
|
6776
|
+
group.session.groupChat.state = "paused";
|
|
6777
|
+
});
|
|
6778
|
+
}
|
|
6779
|
+
async pauseAll() {
|
|
6780
|
+
await Promise.all(this.#groups.filter((group) => group.session.groupChat.state === "running").map((group) => this.abort(group.session.sessionId)));
|
|
6781
|
+
}
|
|
6782
|
+
async stop() {
|
|
6783
|
+
this.#stopping = true;
|
|
6784
|
+
for (const job of this.#jobs.values()) job.controller.abort(new Error("PC stopped"));
|
|
6785
|
+
await Promise.allSettled([...this.#jobs.values()].map((job) => job.done));
|
|
6786
|
+
await this.#writes;
|
|
6787
|
+
this.#database?.close();
|
|
6788
|
+
this.#database = void 0;
|
|
6789
|
+
}
|
|
6790
|
+
async delete(id) {
|
|
6791
|
+
await this.abort(id);
|
|
6792
|
+
await this.keys.revoke(this.#group(id).peer.groupId, true);
|
|
6793
|
+
this.revocationPending?.();
|
|
6794
|
+
await this.#update((groups) => {
|
|
6795
|
+
const index = groups.findIndex((group) => group.session.sessionId === id);
|
|
6796
|
+
if (index >= 0) groups.splice(index, 1);
|
|
6797
|
+
});
|
|
6798
|
+
this.#watched.delete(id);
|
|
6799
|
+
this.#callbacks?.onSessionInventoryChanged(id);
|
|
6800
|
+
}
|
|
6801
|
+
async rename(id, name, check) {
|
|
6802
|
+
const value = validateSessionName(name);
|
|
6803
|
+
await this.#update((groups) => {
|
|
6804
|
+
check?.();
|
|
6805
|
+
this.#group(id, groups).session.summary = value;
|
|
6806
|
+
}, check);
|
|
6807
|
+
return value;
|
|
6808
|
+
}
|
|
6809
|
+
watch(id, watched) {
|
|
6810
|
+
this.#group(id);
|
|
6811
|
+
if (watched) this.#watched.add(id);
|
|
6812
|
+
else this.#watched.delete(id);
|
|
6813
|
+
}
|
|
6814
|
+
page(id, options = {}) {
|
|
6815
|
+
this.#group(id);
|
|
6816
|
+
const db = this.#database;
|
|
6817
|
+
if (db === void 0) unavailable("Encrypted group history is not open");
|
|
6818
|
+
const count = this.#itemCount(db, id), prefix = `${id}:`;
|
|
6819
|
+
const size = z8.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
|
|
6820
|
+
const offset = options.cursor?.startsWith(prefix) ? Number(options.cursor.slice(prefix.length)) : NaN;
|
|
6821
|
+
const valid = Number.isInteger(offset) && offset >= 0 && offset <= count;
|
|
6822
|
+
const end = options.cursor === void 0 || !valid ? count : offset, start = Math.max(0, end - size);
|
|
6823
|
+
const items = db.prepare("SELECT data FROM items WHERE session=? AND seq>? AND seq<=? ORDER BY seq").all(id, start, end).map((row) => ConversationItemSchema.parse(JSON.parse(JsonRow.parse(row).data)));
|
|
6824
|
+
return {
|
|
6825
|
+
items,
|
|
6826
|
+
cursor: `${prefix}${start}`,
|
|
6827
|
+
hasMore: start > 0,
|
|
6828
|
+
cursorStatus: options.cursor === void 0 || valid ? "ok" : "expired"
|
|
6829
|
+
};
|
|
6830
|
+
}
|
|
6831
|
+
#group(id, groups = this.#groups) {
|
|
6832
|
+
return groups.find((group) => group.session.sessionId === id) ?? unavailable("The encrypted group no longer exists");
|
|
6833
|
+
}
|
|
6834
|
+
#update(action, check) {
|
|
6835
|
+
const work = this.#writes.then(async () => {
|
|
6836
|
+
const db = await this.#db();
|
|
6837
|
+
const groups = this.#groups.map((group) => ({ ...structuredClone(group), items: [] }));
|
|
6838
|
+
const changed2 = [];
|
|
6839
|
+
db.exec("BEGIN IMMEDIATE");
|
|
6840
|
+
let result;
|
|
6841
|
+
try {
|
|
6842
|
+
result = action(groups, db);
|
|
6843
|
+
for (const group of groups) {
|
|
6844
|
+
const { items, ...metadata } = group;
|
|
6845
|
+
if (items.length === 0 && JSON.stringify(metadata) === JSON.stringify(this.#groups.find((old) => old.session.sessionId === group.session.sessionId))) continue;
|
|
6846
|
+
if (this.#groups.some((previous) => previous.session.sessionId === group.session.sessionId)) {
|
|
6847
|
+
group.session.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
6848
|
+
}
|
|
6849
|
+
db.prepare("INSERT INTO groups(id,data) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data").run(group.session.sessionId, JSON.stringify(GroupSchema.parse(group)));
|
|
6850
|
+
let count = this.#itemCount(db, group.session.sessionId);
|
|
6851
|
+
for (const item of items) db.prepare("INSERT INTO items(session,seq,data) VALUES(?,?,?)").run(group.session.sessionId, ++count, JSON.stringify(ConversationItemSchema.parse(item)));
|
|
6852
|
+
changed2.push(group);
|
|
6853
|
+
}
|
|
6854
|
+
for (const previous of this.#groups) {
|
|
6855
|
+
if (groups.some((group) => group.session.sessionId === previous.session.sessionId)) continue;
|
|
6856
|
+
for (const table of ["groups", "items", "operations"]) {
|
|
6857
|
+
db.prepare(`DELETE FROM ${table} WHERE ${table === "groups" ? "id" : "session"}=?`).run(previous.session.sessionId);
|
|
6858
|
+
}
|
|
6859
|
+
}
|
|
6860
|
+
check?.();
|
|
6861
|
+
db.exec("COMMIT");
|
|
6862
|
+
} catch (error) {
|
|
6863
|
+
db.exec("ROLLBACK");
|
|
6864
|
+
throw error;
|
|
6865
|
+
}
|
|
6866
|
+
this.#groups = groups.map((group) => GroupSchema.parse(group));
|
|
6867
|
+
for (const group of changed2) {
|
|
6868
|
+
const id = group.session.sessionId;
|
|
6869
|
+
try {
|
|
6870
|
+
if (this.#watched.has(id)) {
|
|
6871
|
+
for (const item of group.items) this.#callbacks?.onConversationItem(id, item);
|
|
6872
|
+
}
|
|
6873
|
+
this.#callbacks?.onSessionInventoryChanged(id);
|
|
6874
|
+
this.#callbacks?.onSessionActivity?.(id, group.session.groupChat.state === "running" ? "working" : "idle", group.session.modifiedAt);
|
|
6875
|
+
} catch (error) {
|
|
6876
|
+
this.#callbacks?.onSyncError(id, error);
|
|
6877
|
+
}
|
|
6878
|
+
}
|
|
6879
|
+
return result;
|
|
6880
|
+
});
|
|
6881
|
+
this.#writes = work.catch(() => void 0);
|
|
6882
|
+
return work;
|
|
6883
|
+
}
|
|
6884
|
+
#itemCount(db, id) {
|
|
6885
|
+
return z8.object({ count: z8.number() }).parse(
|
|
6886
|
+
db.prepare("SELECT COALESCE(MAX(seq),0) AS count FROM items WHERE session=?").get(id)
|
|
6887
|
+
).count;
|
|
6888
|
+
}
|
|
6889
|
+
async #db() {
|
|
6890
|
+
if (this.#database !== void 0) return this.#database;
|
|
6891
|
+
await mkdir5(this.#directory, { recursive: true, mode: 448 });
|
|
6892
|
+
const root = await lstat5(this.#directory);
|
|
6893
|
+
if (!root.isDirectory() || root.isSymbolicLink()) unavailable("Encrypted group directory must not be a symbolic link");
|
|
6894
|
+
const path = join11(await realpath6(this.#directory), "groups.sqlite");
|
|
6895
|
+
for (const suffix of ["", "-journal"]) {
|
|
6896
|
+
try {
|
|
6897
|
+
const info = await lstat5(`${path}${suffix}`);
|
|
6898
|
+
if (info.isSymbolicLink() || !info.isFile()) unavailable("Invalid encrypted group database file");
|
|
6899
|
+
} catch (error) {
|
|
6900
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
6901
|
+
}
|
|
6902
|
+
}
|
|
6903
|
+
const file = await open3(path, "a", 384);
|
|
6904
|
+
await file.close();
|
|
6905
|
+
await chmod2(path, 384);
|
|
6906
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
6907
|
+
const db = new DatabaseSync(path);
|
|
6908
|
+
try {
|
|
6909
|
+
db.exec("PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL; PRAGMA secure_delete=ON;");
|
|
6910
|
+
const version = z8.object({ user_version: z8.number() }).parse(db.prepare("PRAGMA user_version").get()).user_version;
|
|
6911
|
+
if (version > 1) unavailable("Encrypted group history requires a newer PC Agent");
|
|
6912
|
+
if (version === 0) {
|
|
6913
|
+
let legacy;
|
|
6914
|
+
try {
|
|
6915
|
+
legacy = LegacyJournalSchema.parse(JSON.parse(await readFile3(join11(this.#directory, "groups.json"), "utf8")));
|
|
6916
|
+
} catch (error) {
|
|
6917
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
6918
|
+
}
|
|
6919
|
+
db.exec(`BEGIN IMMEDIATE;
|
|
6920
|
+
CREATE TABLE groups(id TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
6921
|
+
CREATE TABLE items(session TEXT NOT NULL, seq INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(session,seq));
|
|
6922
|
+
CREATE TABLE operations(session TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, PRIMARY KEY(session,id));`);
|
|
6923
|
+
try {
|
|
6924
|
+
for (const group of legacy?.groups ?? []) {
|
|
6925
|
+
const id = group.session.sessionId;
|
|
6926
|
+
db.prepare("INSERT INTO groups(id,data) VALUES(?,?)").run(id, JSON.stringify(GroupSchema.parse(group)));
|
|
6927
|
+
for (const [index, item] of group.items.entries()) db.prepare("INSERT INTO items(session,seq,data) VALUES(?,?,?)").run(id, index + 1, JSON.stringify(item));
|
|
6928
|
+
for (const operation of group.operations) db.prepare("INSERT INTO operations(session,id,data) VALUES(?,?,?)").run(id, operation.id, JSON.stringify(operation));
|
|
6929
|
+
}
|
|
6930
|
+
db.exec("PRAGMA user_version=1; COMMIT;");
|
|
6931
|
+
} catch (error) {
|
|
6932
|
+
db.exec("ROLLBACK");
|
|
6933
|
+
throw error;
|
|
6934
|
+
}
|
|
6935
|
+
}
|
|
6936
|
+
const marker = join11(this.#directory, `${randomUUID8()}.staging`);
|
|
6937
|
+
try {
|
|
6938
|
+
await writeFile4(marker, JSON.stringify({ version: 2 }), { flag: "wx", mode: 384 });
|
|
6939
|
+
await rename3(marker, join11(this.#directory, "groups.json"));
|
|
6940
|
+
} finally {
|
|
6941
|
+
await rm3(marker, { force: true });
|
|
6942
|
+
}
|
|
6943
|
+
this.#database = db;
|
|
6944
|
+
return db;
|
|
6945
|
+
} catch (error) {
|
|
6946
|
+
db.close();
|
|
6947
|
+
throw error;
|
|
6948
|
+
}
|
|
6949
|
+
}
|
|
6950
|
+
};
|
|
6951
|
+
function encryptedGroupAdapter(inner, groups) {
|
|
6952
|
+
const normal = (id) => {
|
|
6953
|
+
if (groups.owns(id)) unavailable();
|
|
6954
|
+
};
|
|
6955
|
+
const overrides = {
|
|
6956
|
+
start: async () => {
|
|
6957
|
+
await groups.start();
|
|
6958
|
+
await inner.start();
|
|
6959
|
+
},
|
|
6960
|
+
stop: async () => {
|
|
6961
|
+
await groups.stop();
|
|
6962
|
+
await inner.stop();
|
|
6963
|
+
},
|
|
6964
|
+
canUpgrade: async () => !groups.busy && await inner.canUpgrade?.() === true,
|
|
6965
|
+
isSessionVisible: (id) => groups.owns(id) ? groups.visible(id) : inner.isSessionVisible?.(id) !== false,
|
|
6966
|
+
sessionPublicationSource: (id) => groups.owns(id) ? groups.source(id) : inner.sessionPublicationSource?.(id) ?? id,
|
|
6967
|
+
listSessions: async (userId, machineId) => [...await inner.listSessions(userId, machineId), ...groups.list()],
|
|
6968
|
+
setSessionCallbacks: (callbacks) => {
|
|
6969
|
+
inner.setSessionCallbacks(callbacks);
|
|
6970
|
+
groups.setCallbacks(callbacks);
|
|
6971
|
+
},
|
|
6972
|
+
createEncryptedGroupChat: (source, peer, check) => groups.create(source, peer, check),
|
|
6973
|
+
assertPeerSession: (id) => {
|
|
6974
|
+
normal(id);
|
|
6975
|
+
inner.assertPeerSession?.(id);
|
|
6976
|
+
},
|
|
6977
|
+
...inner.setGroupChatEnabled === void 0 ? {} : {
|
|
6978
|
+
setGroupChatEnabled: async (enabled) => {
|
|
6979
|
+
const stopping = enabled ? Promise.resolve() : groups.pauseAll();
|
|
6980
|
+
await inner.setGroupChatEnabled?.(enabled);
|
|
6981
|
+
await stopping;
|
|
6982
|
+
}
|
|
6983
|
+
},
|
|
6984
|
+
readSessionTimelinePage: (id, options) => groups.owns(id) ? Promise.resolve(groups.page(id, options)) : inner.readSessionTimelinePage(id, options),
|
|
6985
|
+
watchSession: async (id, watching) => {
|
|
6986
|
+
if (groups.owns(id)) groups.watch(id, watching);
|
|
6987
|
+
else await inner.watchSession(id, watching);
|
|
6988
|
+
},
|
|
6989
|
+
sendPrompt: (id, prompt, mode, images, persist, files, operationId, persona) => {
|
|
6990
|
+
if (!groups.owns(id)) return inner.sendPrompt(id, prompt, mode, images, persist, files, operationId, persona);
|
|
6991
|
+
if (images?.length || files?.length || persona !== void 0) unavailable("Encrypted groups accept text only");
|
|
6992
|
+
return groups.prompt(id, prompt, operationId);
|
|
6993
|
+
},
|
|
6994
|
+
abortSession: (id) => groups.owns(id) ? groups.abort(id) : inner.abortSession(id),
|
|
6995
|
+
deleteSession: (id) => groups.owns(id) ? groups.delete(id) : inner.deleteSession?.(id) ?? Promise.reject(new Error("Session deletion is unsupported")),
|
|
6996
|
+
renameSession: (id, name, check) => groups.owns(id) ? groups.rename(id, name, check) : inner.renameSession?.(id, name, check) ?? Promise.reject(new Error("Session rename is unsupported")),
|
|
6997
|
+
getSessionCapabilities: (id) => id !== void 0 && groups.owns(id) ? { agentModes: ["interactive"], supportsReasoningEffort: false, supportsFileAttachments: false, supportsPlanRead: false } : inner.getSessionCapabilities?.(id) ?? inner,
|
|
6998
|
+
getSessionConfiguration: (id) => groups.owns(id) ? Promise.resolve({ agentMode: "interactive", reasoningEffort: "default" }) : inner.getSessionConfiguration(id),
|
|
6999
|
+
listModels: (id) => inner.listModels(id !== void 0 && groups.owns(id) ? groups.source(id) : id),
|
|
7000
|
+
configureSession: (id, options) => {
|
|
7001
|
+
normal(id);
|
|
7002
|
+
return inner.configureSession(id, options);
|
|
7003
|
+
},
|
|
7004
|
+
getSessionEnvironment: (id) => groups.owns(id) ? Promise.resolve({ tools: [], slashCommands: [], skills: [] }) : inner.getSessionEnvironment(id),
|
|
7005
|
+
getSessionRemoteStatus: (id) => groups.owns(id) ? Promise.resolve({ state: "off", steerable: false }) : inner.getSessionRemoteStatus(id),
|
|
7006
|
+
setSessionRemote: (id, enabled) => {
|
|
7007
|
+
normal(id);
|
|
7008
|
+
return inner.setSessionRemote(id, enabled);
|
|
7009
|
+
},
|
|
7010
|
+
...inner.getSessionDirectoryMetadata === void 0 ? {} : {
|
|
7011
|
+
getSessionDirectoryMetadata: (id) => {
|
|
7012
|
+
normal(id);
|
|
7013
|
+
return inner.getSessionDirectoryMetadata?.(id) ?? Promise.resolve(void 0);
|
|
7014
|
+
}
|
|
7015
|
+
},
|
|
7016
|
+
...inner.getSessionProjectIdentity === void 0 ? {} : {
|
|
7017
|
+
getSessionProjectIdentity: (id) => {
|
|
7018
|
+
normal(id);
|
|
7019
|
+
return inner.getSessionProjectIdentity?.(id) ?? Promise.resolve(void 0);
|
|
7020
|
+
}
|
|
7021
|
+
},
|
|
7022
|
+
captureWorkbenchAccess: (id) => {
|
|
7023
|
+
normal(id);
|
|
7024
|
+
return captureWorkbenchAccess(inner, id);
|
|
7025
|
+
},
|
|
7026
|
+
captureResearchAccess: (id) => {
|
|
7027
|
+
normal(id);
|
|
7028
|
+
return captureResearchAccess(inner, id);
|
|
7029
|
+
},
|
|
7030
|
+
...inner.runPeerTurn === void 0 ? {} : {
|
|
7031
|
+
runPeerTurn: (...args) => {
|
|
7032
|
+
normal(args[0]);
|
|
7033
|
+
return inner.runPeerTurn?.(...args) ?? Promise.reject(new Error("Peer turns are unsupported"));
|
|
7034
|
+
}
|
|
7035
|
+
},
|
|
7036
|
+
...inner.readSessionPlan === void 0 ? {} : {
|
|
7037
|
+
readSessionPlan: (id) => {
|
|
7038
|
+
normal(id);
|
|
7039
|
+
return inner.readSessionPlan?.(id) ?? Promise.reject(new Error("Session plans are unsupported"));
|
|
7040
|
+
}
|
|
7041
|
+
}
|
|
7042
|
+
};
|
|
7043
|
+
return new Proxy(inner, {
|
|
7044
|
+
get(target, property) {
|
|
7045
|
+
const value = Reflect.get(overrides, property) ?? Reflect.get(target, property, target);
|
|
7046
|
+
return typeof value === "function" ? value.bind(property in overrides ? overrides : target) : value;
|
|
7047
|
+
}
|
|
7048
|
+
});
|
|
7049
|
+
}
|
|
7050
|
+
|
|
6266
7051
|
// src/peer-chat.ts
|
|
6267
|
-
import { randomUUID as
|
|
7052
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
6268
7053
|
var MAX_ACTIVE_TURNS = 4;
|
|
6269
7054
|
var MAX_SEEN_REQUESTS = 2048;
|
|
6270
7055
|
function peerError(error) {
|
|
@@ -6283,7 +7068,7 @@ var PeerChatRuntime = class {
|
|
|
6283
7068
|
get busy() {
|
|
6284
7069
|
return this.#runs.size > 0 || this.#jobs.size > 0;
|
|
6285
7070
|
}
|
|
6286
|
-
async run(rawRequest, signal) {
|
|
7071
|
+
async run(rawRequest, signal, observer) {
|
|
6287
7072
|
const request2 = PeerChatRequestSchema.parse(rawRequest);
|
|
6288
7073
|
this.host.assertReady();
|
|
6289
7074
|
signal.throwIfAborted();
|
|
@@ -6294,10 +7079,7 @@ var PeerChatRuntime = class {
|
|
|
6294
7079
|
this.#runs.add(controller);
|
|
6295
7080
|
const abort = () => controller.abort(signal.reason);
|
|
6296
7081
|
signal.addEventListener("abort", abort, { once: true });
|
|
6297
|
-
const deadline = Date.now() + PEER_CHAT_TIMEOUT_MS;
|
|
6298
|
-
const timer = setTimeout(() => controller.abort(new Error("Peer conversation timed out; execution will not be replayed.")), PEER_CHAT_TIMEOUT_MS);
|
|
6299
7082
|
const peerReplies = [];
|
|
6300
|
-
let requests = 0;
|
|
6301
7083
|
let lastExchange;
|
|
6302
7084
|
const job = (async () => {
|
|
6303
7085
|
const reply = await this.host.runTurn(request2.sessionId, [
|
|
@@ -6311,10 +7093,11 @@ var PeerChatRuntime = class {
|
|
|
6311
7093
|
const exchange = async () => {
|
|
6312
7094
|
try {
|
|
6313
7095
|
controller.signal.throwIfAborted();
|
|
6314
|
-
if (
|
|
6315
|
-
|
|
6316
|
-
if (remaining < 1e3) throw new Error("Peer conversation timed out.");
|
|
7096
|
+
if (observer !== void 0) await observer.request(content);
|
|
7097
|
+
controller.signal.throwIfAborted();
|
|
6317
7098
|
const response = await conversation.request(content, controller.signal);
|
|
7099
|
+
if (observer !== void 0) await observer.reply(response);
|
|
7100
|
+
controller.signal.throwIfAborted();
|
|
6318
7101
|
peerReplies.push(response);
|
|
6319
7102
|
return response;
|
|
6320
7103
|
} catch (error) {
|
|
@@ -6335,7 +7118,6 @@ var PeerChatRuntime = class {
|
|
|
6335
7118
|
try {
|
|
6336
7119
|
return await job;
|
|
6337
7120
|
} finally {
|
|
6338
|
-
clearTimeout(timer);
|
|
6339
7121
|
signal.removeEventListener("abort", abort);
|
|
6340
7122
|
controller.abort(new Error("Peer conversation ended."));
|
|
6341
7123
|
this.#runs.delete(controller);
|
|
@@ -6388,7 +7170,7 @@ var PeerChatRuntime = class {
|
|
|
6388
7170
|
if (generation !== this.#generation) throw new Error("Peer connection changed; old result will not be replayed.");
|
|
6389
7171
|
return this.host.send(PeerMessageSchema.parse({
|
|
6390
7172
|
version: 1,
|
|
6391
|
-
messageId:
|
|
7173
|
+
messageId: randomUUID9(),
|
|
6392
7174
|
requestId: message.messageId,
|
|
6393
7175
|
sourceSessionId: message.targetSessionId,
|
|
6394
7176
|
targetSessionId: message.sourceSessionId,
|
|
@@ -6866,7 +7648,7 @@ var SessionInventory = class {
|
|
|
6866
7648
|
};
|
|
6867
7649
|
|
|
6868
7650
|
// src/snapshot-audience.ts
|
|
6869
|
-
import { createHash as
|
|
7651
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
6870
7652
|
var SnapshotAudience = class {
|
|
6871
7653
|
constructor(send) {
|
|
6872
7654
|
this.send = send;
|
|
@@ -6895,7 +7677,7 @@ var SnapshotAudience = class {
|
|
|
6895
7677
|
async publish(snapshot, recipient) {
|
|
6896
7678
|
const generation = this.#generation;
|
|
6897
7679
|
const { sequence: _sequence, generatedAt: _generatedAt, ...content } = snapshot;
|
|
6898
|
-
const digest =
|
|
7680
|
+
const digest = createHash13("sha256").update(JSON.stringify(content)).digest("base64url");
|
|
6899
7681
|
if (recipient !== void 0) {
|
|
6900
7682
|
await this.#direct(snapshot, recipient, digest, generation);
|
|
6901
7683
|
return;
|
|
@@ -7027,7 +7809,7 @@ var ConversationAudience = class {
|
|
|
7027
7809
|
};
|
|
7028
7810
|
|
|
7029
7811
|
// src/timeline-incremental-transport.ts
|
|
7030
|
-
import { createHash as
|
|
7812
|
+
import { createHash as createHash14, randomUUID as randomUUID10 } from "node:crypto";
|
|
7031
7813
|
import { isDeepStrictEqual } from "node:util";
|
|
7032
7814
|
function journalDiagnostic(state) {
|
|
7033
7815
|
return {
|
|
@@ -7161,7 +7943,7 @@ var TimelineIncrementalTransport = class {
|
|
|
7161
7943
|
}
|
|
7162
7944
|
#observeColdStep(state, upsert) {
|
|
7163
7945
|
const cold = state.coldSteps;
|
|
7164
|
-
const key =
|
|
7946
|
+
const key = createHash14("sha256").update(JSON.stringify([upsert.activityId, upsert.step.id])).digest("hex");
|
|
7165
7947
|
const revision = cold.revisions.get(key);
|
|
7166
7948
|
if (revision !== void 0 && upsert.revision < revision) return false;
|
|
7167
7949
|
cold.revisions.delete(key);
|
|
@@ -7171,7 +7953,7 @@ var TimelineIncrementalTransport = class {
|
|
|
7171
7953
|
if (oldest === void 0) break;
|
|
7172
7954
|
cold.revisions.delete(oldest);
|
|
7173
7955
|
}
|
|
7174
|
-
const fingerprint =
|
|
7956
|
+
const fingerprint = createHash14("sha256").update(JSON.stringify(upsert)).digest("hex");
|
|
7175
7957
|
const observed = cold.fingerprints.has(fingerprint);
|
|
7176
7958
|
cold.fingerprints.delete(fingerprint);
|
|
7177
7959
|
cold.fingerprints.add(fingerprint);
|
|
@@ -7304,7 +8086,7 @@ var TimelineIncrementalTransport = class {
|
|
|
7304
8086
|
let state = this.#sessions.get(sessionId);
|
|
7305
8087
|
if (state === void 0) {
|
|
7306
8088
|
state = {
|
|
7307
|
-
epoch:
|
|
8089
|
+
epoch: randomUUID10(),
|
|
7308
8090
|
sequence: 0,
|
|
7309
8091
|
reason: "initial",
|
|
7310
8092
|
events: [],
|
|
@@ -7453,8 +8235,8 @@ function canAppend(previous, item) {
|
|
|
7453
8235
|
}
|
|
7454
8236
|
|
|
7455
8237
|
// src/timeline-image-blob.ts
|
|
7456
|
-
import { createHash as
|
|
7457
|
-
var MAX_ACTIVE_PUBLICATIONS =
|
|
8238
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
8239
|
+
var MAX_ACTIVE_PUBLICATIONS = 16;
|
|
7458
8240
|
var MAX_QUEUED_PUBLICATIONS = 16;
|
|
7459
8241
|
var QUEUE_TIMEOUT_MS = 15e3;
|
|
7460
8242
|
var PUBLICATION_TIMEOUT_MS = 85e3;
|
|
@@ -7575,7 +8357,7 @@ var TimelineImageBlobPublisher = class {
|
|
|
7575
8357
|
const asset = this.images.readAsset(sessionId, sha256);
|
|
7576
8358
|
const extension = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" }[asset.mimeType];
|
|
7577
8359
|
if (extension === void 0) throw new TimelineAssetError("IMAGE_BLOB_UNSUPPORTED", "This image requires encrypted transfer");
|
|
7578
|
-
if (
|
|
8360
|
+
if (createHash15("sha256").update(asset.bytes).digest("hex") !== sha256) {
|
|
7579
8361
|
throw new TimelineAssetError("IMAGE_INVALID", "Image content does not match its reference");
|
|
7580
8362
|
}
|
|
7581
8363
|
let bytes;
|
|
@@ -8108,11 +8890,26 @@ var PcAgent = class {
|
|
|
8108
8890
|
this.research = research;
|
|
8109
8891
|
this.onPairing = onPairing;
|
|
8110
8892
|
this.textInputWriter = textInputWriter;
|
|
8893
|
+
this.#encryptedPeers = new EncryptedPeerStore(config.dataDirectory, {
|
|
8894
|
+
userId: config.userId,
|
|
8895
|
+
machineId: identity2.machineId
|
|
8896
|
+
});
|
|
8111
8897
|
this.#textInput = new DeviceTextInputHandler(textInputWriter);
|
|
8112
8898
|
if (research?.chat !== void 0) {
|
|
8113
8899
|
adapter = researchAwareCodingAgentAdapter(adapter, research.chat);
|
|
8114
8900
|
this.adapter = adapter;
|
|
8115
8901
|
}
|
|
8902
|
+
if (adapter.runPeerTurn !== void 0) {
|
|
8903
|
+
adapter = encryptedGroupAdapter(adapter, new EncryptedGroupSessions(
|
|
8904
|
+
adapter,
|
|
8905
|
+
config.dataDirectory,
|
|
8906
|
+
{ userId: config.userId, machineId: identity2.machineId },
|
|
8907
|
+
this.#encryptedPeers,
|
|
8908
|
+
(request2, signal, observer) => this.#peerChat.run(request2, signal, observer),
|
|
8909
|
+
() => this.#retryPeerRevocations()
|
|
8910
|
+
));
|
|
8911
|
+
this.adapter = adapter;
|
|
8912
|
+
}
|
|
8116
8913
|
this.#stopped = new Promise((resolve5) => {
|
|
8117
8914
|
this.#resolveStopped = resolve5;
|
|
8118
8915
|
});
|
|
@@ -8157,6 +8954,27 @@ var PcAgent = class {
|
|
|
8157
8954
|
const handlerOptions = { adapter, config, machineId: identity2.machineId, logger, emit };
|
|
8158
8955
|
this.#communication = new SessionCommunicationHandler({
|
|
8159
8956
|
...handlerOptions,
|
|
8957
|
+
...adapter.runPeerTurn === void 0 ? {} : {
|
|
8958
|
+
authorizeEncryptedPeer: async (sessionId, data, clientId, assertAccess) => {
|
|
8959
|
+
if (!this.#encryptedPeerNegotiated || !this.#peerNegotiated || !this.#peerChatEnabled) {
|
|
8960
|
+
throw new GroupChatError("GROUP_CHAT_UNAVAILABLE", "Enable cross-PC communication on both PCs and use a Relay with encrypted peer support.");
|
|
8961
|
+
}
|
|
8962
|
+
const check = () => {
|
|
8963
|
+
assertAccess();
|
|
8964
|
+
if (!this.#encryptedPeerNegotiated || !this.#peerNegotiated || !this.#peerChatEnabled || adapter.isSessionVisible?.(sessionId) === false) {
|
|
8965
|
+
throw new GroupChatError("GROUP_CHAT_UNAVAILABLE", "Peer access changed. Check that this session is shared and cross-PC communication is enabled.");
|
|
8966
|
+
}
|
|
8967
|
+
};
|
|
8968
|
+
check();
|
|
8969
|
+
adapter.assertPeerSession?.(sessionId);
|
|
8970
|
+
if (!this.#encryptedOnly && !this.#encryptedPeers.requiresEncryption) {
|
|
8971
|
+
this.#encryptedOnly = true;
|
|
8972
|
+
this.#legacyPeerStopped = Promise.all([this.#peerChat.close(), this.#a2aServer.close()]).then(() => void 0);
|
|
8973
|
+
}
|
|
8974
|
+
await this.#legacyPeerStopped;
|
|
8975
|
+
return this.#encryptedPeers.authorize(sessionId, data, clientId, check);
|
|
8976
|
+
}
|
|
8977
|
+
},
|
|
8160
8978
|
agentRunId: this.#agentRunId,
|
|
8161
8979
|
enabled: () => this.#communicationNegotiated && this.#machineRegistered,
|
|
8162
8980
|
publications: this.#publication,
|
|
@@ -8303,7 +9121,7 @@ var PcAgent = class {
|
|
|
8303
9121
|
return adapter.runPeerTurn(sessionId, prompt, options);
|
|
8304
9122
|
});
|
|
8305
9123
|
const reportPeerError = (error) => logger.warn({ error: toErrorDetails(error) }, "peer-chat.failed");
|
|
8306
|
-
|
|
9124
|
+
this.#a2aClient = new A2aPeerClient({
|
|
8307
9125
|
relayUrl: config.relayUrl,
|
|
8308
9126
|
relayToken: config.relayToken,
|
|
8309
9127
|
userId: config.userId,
|
|
@@ -8315,13 +9133,24 @@ var PcAgent = class {
|
|
|
8315
9133
|
machineId: identity2.machineId,
|
|
8316
9134
|
assertReady: assertPeerReady,
|
|
8317
9135
|
send: (message) => this.#sendPeerMessage(message),
|
|
8318
|
-
createConversation: (request2) =>
|
|
9136
|
+
createConversation: (request2) => {
|
|
9137
|
+
const channel = request2.encryptedGroupId === void 0 ? this.#encryptedPeers.forSessions(request2.sessionId, request2.targetMachineId, request2.targetSessionId) : this.#encryptedPeers.outbound(request2.encryptedGroupId, request2.sessionId, request2.targetMachineId, request2.targetSessionId);
|
|
9138
|
+
if (channel === void 0 && (this.#encryptedOnly || this.#encryptedPeers.requiresEncryption)) {
|
|
9139
|
+
throw new Error("Authorize these two sessions in a paired phone's encrypted group first; plaintext fallback is forbidden");
|
|
9140
|
+
}
|
|
9141
|
+
if (channel !== void 0 && !this.#encryptedPeerNegotiated) {
|
|
9142
|
+
throw new Error("Relay has not negotiated encrypted peer communication; plaintext fallback is forbidden");
|
|
9143
|
+
}
|
|
9144
|
+
return this.#a2aClient.conversation(request2, channel);
|
|
9145
|
+
},
|
|
8319
9146
|
runTurn: runPeerTurn,
|
|
8320
9147
|
reportError: reportPeerError
|
|
8321
9148
|
});
|
|
8322
|
-
|
|
9149
|
+
const receiptOwner = createHash16("sha256").update(JSON.stringify([config.userId, identity2.machineId])).digest("hex");
|
|
9150
|
+
this.#createEncryptedServer = (groupId = "legacy") => new A2aPeerServer({
|
|
8323
9151
|
userId: config.userId,
|
|
8324
9152
|
appVersion,
|
|
9153
|
+
receiptDirectory: join12(config.dataDirectory, "a2a-receipts", receiptOwner, groupId),
|
|
8325
9154
|
assertReady: () => {
|
|
8326
9155
|
assertPeerReady();
|
|
8327
9156
|
if (!this.#a2aNegotiated) throw new Error("Relay has not negotiated A2A support.");
|
|
@@ -8334,6 +9163,7 @@ var PcAgent = class {
|
|
|
8334
9163
|
runTurn: runPeerTurn,
|
|
8335
9164
|
reportError: reportPeerError
|
|
8336
9165
|
});
|
|
9166
|
+
this.#a2aServer = this.#createEncryptedServer();
|
|
8337
9167
|
this.#inventoryPublisher = new InventoryPublisher({
|
|
8338
9168
|
inventory: this.#inventory,
|
|
8339
9169
|
send: (snapshot, recipient) => this.#sendSnapshot(snapshot, recipient),
|
|
@@ -8443,7 +9273,7 @@ var PcAgent = class {
|
|
|
8443
9273
|
onInteractionDismissed: (sessionId, interactionRequestId) => {
|
|
8444
9274
|
const payload = InteractionRespondResultSchema.parse({
|
|
8445
9275
|
ok: false,
|
|
8446
|
-
requestId:
|
|
9276
|
+
requestId: randomUUID11(),
|
|
8447
9277
|
interactionRequestId,
|
|
8448
9278
|
machineId: this.identity.machineId,
|
|
8449
9279
|
sessionId,
|
|
@@ -8541,8 +9371,8 @@ var PcAgent = class {
|
|
|
8541
9371
|
research;
|
|
8542
9372
|
onPairing;
|
|
8543
9373
|
textInputWriter;
|
|
8544
|
-
#agentRunId =
|
|
8545
|
-
#clientId =
|
|
9374
|
+
#agentRunId = randomUUID11();
|
|
9375
|
+
#clientId = randomUUID11();
|
|
8546
9376
|
#socket;
|
|
8547
9377
|
#relayDiagnostics = new RelayConnectionDiagnostics();
|
|
8548
9378
|
#cipher;
|
|
@@ -8557,6 +9387,7 @@ var PcAgent = class {
|
|
|
8557
9387
|
#conversationAudience = new ConversationAudience();
|
|
8558
9388
|
#timelineIncremental;
|
|
8559
9389
|
#imageBlob;
|
|
9390
|
+
#imageClientVerified = false;
|
|
8560
9391
|
#imageStorage;
|
|
8561
9392
|
#sessionImagesEnabled;
|
|
8562
9393
|
#imagePolicyRevision = 0;
|
|
@@ -8585,11 +9416,21 @@ var PcAgent = class {
|
|
|
8585
9416
|
#peerNegotiated = false;
|
|
8586
9417
|
#peerTransportNegotiated = false;
|
|
8587
9418
|
#a2aNegotiated = false;
|
|
9419
|
+
#encryptedPeerNegotiated = false;
|
|
9420
|
+
#encryptedOnly = false;
|
|
9421
|
+
#legacyPeerStopped;
|
|
8588
9422
|
#peerChatEnabled;
|
|
8589
9423
|
#peerPreferenceRevision = 0;
|
|
8590
9424
|
#peerRegistrationRevision = -1;
|
|
8591
9425
|
#peerChat;
|
|
8592
9426
|
#a2aServer;
|
|
9427
|
+
#encryptedPeers;
|
|
9428
|
+
#encryptedA2aServers = /* @__PURE__ */ new Map();
|
|
9429
|
+
#createEncryptedServer;
|
|
9430
|
+
#a2aClient;
|
|
9431
|
+
#revocationAbort = new AbortController();
|
|
9432
|
+
#revocationWork;
|
|
9433
|
+
#revocationTimer;
|
|
8593
9434
|
#communication;
|
|
8594
9435
|
#textInput;
|
|
8595
9436
|
#textInputClients = /* @__PURE__ */ new Map();
|
|
@@ -8630,6 +9471,7 @@ var PcAgent = class {
|
|
|
8630
9471
|
);
|
|
8631
9472
|
try {
|
|
8632
9473
|
await this.pairingProvider.enableApproval?.();
|
|
9474
|
+
await this.#encryptedPeers.start();
|
|
8633
9475
|
await this.adapter.start();
|
|
8634
9476
|
this.logger.info({ codingAgent: this.adapter.agentId }, "coding-agent.started");
|
|
8635
9477
|
if (!this.#stopping) {
|
|
@@ -8692,6 +9534,59 @@ var PcAgent = class {
|
|
|
8692
9534
|
}
|
|
8693
9535
|
return this.#peerChat.run(request2, signal);
|
|
8694
9536
|
}
|
|
9537
|
+
async #handleA2aRequest(request2) {
|
|
9538
|
+
if (request2.kind !== "encrypted") {
|
|
9539
|
+
if (this.#encryptedOnly || this.#encryptedPeers.requiresEncryption) {
|
|
9540
|
+
return { status: 403, body: JSON.stringify({ error: "Encrypted peer authorization is required" }) };
|
|
9541
|
+
}
|
|
9542
|
+
return this.#a2aServer.handle(request2);
|
|
9543
|
+
}
|
|
9544
|
+
if (!this.#encryptedPeerNegotiated || !this.#machineRegistered || this.#stopping) {
|
|
9545
|
+
throw new Error("Encrypted peer transport is unavailable");
|
|
9546
|
+
}
|
|
9547
|
+
const { channel, message } = this.#encryptedPeers.incoming(request2);
|
|
9548
|
+
const opened = channel.openRequest(message, request2.sourceMachineId, request2.targetSessionId);
|
|
9549
|
+
if (opened.kind === "revoke") {
|
|
9550
|
+
await this.#encryptedPeers.revoke(channel.binding.groupId);
|
|
9551
|
+
await this.#encryptedA2aServers.get(channel.binding.groupId)?.close();
|
|
9552
|
+
this.#encryptedA2aServers.delete(channel.binding.groupId);
|
|
9553
|
+
return channel.sealResponse({ status: 204, body: "" }, message.messageId);
|
|
9554
|
+
}
|
|
9555
|
+
if (this.#encryptedPeers.isRevoked(channel.binding.groupId)) {
|
|
9556
|
+
return channel.sealResponse({ status: 403, body: "Encrypted group authorization was revoked" }, message.messageId);
|
|
9557
|
+
}
|
|
9558
|
+
let server = this.#encryptedA2aServers.get(channel.binding.groupId);
|
|
9559
|
+
if (server === void 0) {
|
|
9560
|
+
server = this.#createEncryptedServer(channel.binding.groupId);
|
|
9561
|
+
this.#encryptedA2aServers.set(channel.binding.groupId, server);
|
|
9562
|
+
}
|
|
9563
|
+
const response = await server.handle({ ...request2, ...opened });
|
|
9564
|
+
return channel.sealResponse(response, message.messageId);
|
|
9565
|
+
}
|
|
9566
|
+
#retryPeerRevocations() {
|
|
9567
|
+
if (this.#stopping || this.#revocationWork !== void 0 || !this.#encryptedPeerNegotiated || !this.#machineRegistered) return;
|
|
9568
|
+
clearTimeout(this.#revocationTimer);
|
|
9569
|
+
this.#revocationTimer = void 0;
|
|
9570
|
+
this.#revocationWork = (async () => {
|
|
9571
|
+
for (const channel of this.#encryptedPeers.pendingRevocations()) {
|
|
9572
|
+
if (this.#stopping) break;
|
|
9573
|
+
try {
|
|
9574
|
+
await this.#encryptedA2aServers.get(channel.binding.groupId)?.close();
|
|
9575
|
+
this.#encryptedA2aServers.delete(channel.binding.groupId);
|
|
9576
|
+
await this.#a2aClient.revoke(channel, this.#revocationAbort.signal);
|
|
9577
|
+
await this.#encryptedPeers.confirmRevocation(channel.binding.groupId);
|
|
9578
|
+
} catch (error) {
|
|
9579
|
+
this.logger.warn({ groupId: channel.binding.groupId, error: toErrorDetails(error) }, "peer-chat.revocation.pending");
|
|
9580
|
+
}
|
|
9581
|
+
}
|
|
9582
|
+
})().finally(() => {
|
|
9583
|
+
this.#revocationWork = void 0;
|
|
9584
|
+
if (!this.#stopping && this.#encryptedPeers.pendingRevocations().length > 0) {
|
|
9585
|
+
this.#revocationTimer = setTimeout(() => this.#retryPeerRevocations(), 6e4);
|
|
9586
|
+
this.#revocationTimer.unref();
|
|
9587
|
+
}
|
|
9588
|
+
});
|
|
9589
|
+
}
|
|
8695
9590
|
async setPeerChatEnabled(enabled) {
|
|
8696
9591
|
if (this.adapter.setPeerChatEnabled === void 0 || this.adapter.runPeerTurn === void 0) {
|
|
8697
9592
|
throw new Error("This coding agent does not support peer chat.");
|
|
@@ -8703,6 +9598,7 @@ var PcAgent = class {
|
|
|
8703
9598
|
const reason = new Error("Peer chat is disabled on this PC.");
|
|
8704
9599
|
this.#peerChat.reset(reason, true);
|
|
8705
9600
|
this.#a2aServer.reset(reason);
|
|
9601
|
+
for (const server of this.#encryptedA2aServers.values()) server.reset(reason);
|
|
8706
9602
|
}
|
|
8707
9603
|
this.#peerNegotiated = false;
|
|
8708
9604
|
try {
|
|
@@ -8731,24 +9627,24 @@ var PcAgent = class {
|
|
|
8731
9627
|
return Promise.reject(new Error("Peer channel is offline or unsupported; nothing will be queued."));
|
|
8732
9628
|
}
|
|
8733
9629
|
return new Promise((resolve5, reject) => {
|
|
8734
|
-
const timer = setTimeout(() =>
|
|
8735
|
-
const
|
|
9630
|
+
const timer = setTimeout(() => fail3(new Error("Peer forwarding acknowledgement timed out; delivery is unknown.")), ACK_TIMEOUT_MS);
|
|
9631
|
+
const fail3 = (error) => {
|
|
8736
9632
|
clearTimeout(timer);
|
|
8737
|
-
this.#pendingAcks.delete(
|
|
9633
|
+
this.#pendingAcks.delete(fail3);
|
|
8738
9634
|
reject(error);
|
|
8739
9635
|
};
|
|
8740
|
-
this.#pendingAcks.add(
|
|
9636
|
+
this.#pendingAcks.add(fail3);
|
|
8741
9637
|
try {
|
|
8742
9638
|
this.#socket.emit("peer.message", message, (rawAck) => {
|
|
8743
9639
|
clearTimeout(timer);
|
|
8744
|
-
if (!this.#pendingAcks.delete(
|
|
9640
|
+
if (!this.#pendingAcks.delete(fail3)) return;
|
|
8745
9641
|
const ack = OperationAckSchema.safeParse(rawAck);
|
|
8746
9642
|
if (!ack.success) reject(new Error("Relay sent an invalid peer forwarding acknowledgement."));
|
|
8747
9643
|
else if (!ack.data.ok) reject(new Error(`${ack.data.code}: ${ack.data.message}`));
|
|
8748
9644
|
else resolve5();
|
|
8749
9645
|
});
|
|
8750
9646
|
} catch (error) {
|
|
8751
|
-
|
|
9647
|
+
fail3(error instanceof Error ? error : new Error(String(error)));
|
|
8752
9648
|
}
|
|
8753
9649
|
});
|
|
8754
9650
|
}
|
|
@@ -8850,7 +9746,7 @@ var PcAgent = class {
|
|
|
8850
9746
|
}
|
|
8851
9747
|
}
|
|
8852
9748
|
#hasPendingUpgradeWork() {
|
|
8853
|
-
return this.#stopping || this.#starting || this.#connecting > 0 || this.#activeRequests > 0 || this.#watches.busy || this.#inventory.busy || this.#pendingAcks.size > 0 || this.#communication.hasActiveOperations || this.#peerChat.busy || this.#a2aServer.busy || this.research !== void 0 && this.research.canUpgrade?.() !== true || this.#bufferedInteractionRequests.size > 0 || this.#bufferedPermissionRequests.size > 0;
|
|
9749
|
+
return this.#stopping || this.#starting || this.#connecting > 0 || this.#activeRequests > 0 || this.#watches.busy || this.#inventory.busy || this.#pendingAcks.size > 0 || this.#communication.hasActiveOperations || this.#peerChat.busy || this.#a2aServer.busy || [...this.#encryptedA2aServers.values()].some((server) => server.busy) || this.research !== void 0 && this.research.canUpgrade?.() !== true || this.#bufferedInteractionRequests.size > 0 || this.#bufferedPermissionRequests.size > 0;
|
|
8854
9750
|
}
|
|
8855
9751
|
async #admitRequest(request2, event, handle) {
|
|
8856
9752
|
if (event !== "session.options.result" && "sessionId" in request2 && typeof request2.sessionId === "string" && !("operation" in request2) && this.research?.chat !== void 0 && this.research.chat.store.parent(request2.sessionId) !== void 0 && !this.#researchChatClients.has(this.#requestContext.getStore()?.clientId ?? "")) {
|
|
@@ -8887,9 +9783,12 @@ var PcAgent = class {
|
|
|
8887
9783
|
return this.#stopped;
|
|
8888
9784
|
}
|
|
8889
9785
|
this.#stopping = true;
|
|
9786
|
+
clearTimeout(this.#revocationTimer);
|
|
9787
|
+
this.#revocationAbort.abort(new Error("PC Agent stopped"));
|
|
8890
9788
|
const imagesStopped = this.#imageBlob?.close();
|
|
8891
9789
|
const peerStopped = this.#peerChat.close();
|
|
8892
9790
|
const a2aStopped = this.#a2aServer.close();
|
|
9791
|
+
const encryptedStopped = Promise.all([...this.#encryptedA2aServers.values()].map((server) => server.close()));
|
|
8893
9792
|
this.#machineRegistered = false;
|
|
8894
9793
|
this.#textInputClients.clear();
|
|
8895
9794
|
this.#initialSyncGeneration = void 0;
|
|
@@ -8897,6 +9796,7 @@ var PcAgent = class {
|
|
|
8897
9796
|
this.#peerNegotiated = false;
|
|
8898
9797
|
this.#peerTransportNegotiated = false;
|
|
8899
9798
|
this.#a2aNegotiated = false;
|
|
9799
|
+
this.#encryptedPeerNegotiated = false;
|
|
8900
9800
|
this.#connectionGeneration += 1;
|
|
8901
9801
|
this.#cancelSnapshotSync();
|
|
8902
9802
|
this.#clearRelayReconnect();
|
|
@@ -8916,6 +9816,8 @@ var PcAgent = class {
|
|
|
8916
9816
|
this.adapter.stop(),
|
|
8917
9817
|
peerStopped,
|
|
8918
9818
|
a2aStopped,
|
|
9819
|
+
encryptedStopped,
|
|
9820
|
+
...this.#revocationWork === void 0 ? [] : [this.#revocationWork],
|
|
8919
9821
|
...imagesStopped === void 0 ? [] : [imagesStopped],
|
|
8920
9822
|
...this.research === void 0 ? [] : [this.research.stop()]
|
|
8921
9823
|
]);
|
|
@@ -8977,11 +9879,15 @@ var PcAgent = class {
|
|
|
8977
9879
|
this.#peerNegotiated = false;
|
|
8978
9880
|
this.#peerTransportNegotiated = false;
|
|
8979
9881
|
this.#a2aNegotiated = false;
|
|
9882
|
+
this.#encryptedPeerNegotiated = false;
|
|
8980
9883
|
this.#peerChat.reset(new Error("Relay disconnected; peer conversation will not be replayed."));
|
|
8981
9884
|
this.#imageBlob?.reset();
|
|
8982
9885
|
this.#imageStorage = void 0;
|
|
8983
9886
|
this.#imagePolicyRevision += 1;
|
|
8984
9887
|
this.#a2aServer.reset(new Error("Relay disconnected; A2A execution will not be replayed."));
|
|
9888
|
+
for (const server of this.#encryptedA2aServers.values()) {
|
|
9889
|
+
server.reset(new Error("Relay disconnected; encrypted peer execution will not be replayed."));
|
|
9890
|
+
}
|
|
8985
9891
|
this.#conversationAudience.reset();
|
|
8986
9892
|
this.#cancelSnapshotSync();
|
|
8987
9893
|
this.#persistentInteractionClients.clear();
|
|
@@ -9029,6 +9935,7 @@ var PcAgent = class {
|
|
|
9029
9935
|
});
|
|
9030
9936
|
this.#socket.on("peer.message", (delivery) => {
|
|
9031
9937
|
try {
|
|
9938
|
+
if (this.#encryptedOnly || this.#encryptedPeers.requiresEncryption) throw new Error("Plaintext peer delivery is disabled");
|
|
9032
9939
|
this.#peerChat.receive(delivery);
|
|
9033
9940
|
} catch (error) {
|
|
9034
9941
|
this.logger.warn({ error: toErrorDetails(error) }, "peer-chat.delivery-rejected");
|
|
@@ -9119,8 +10026,8 @@ var PcAgent = class {
|
|
|
9119
10026
|
this.logger.warn("a2a.request.missing-ack");
|
|
9120
10027
|
return;
|
|
9121
10028
|
}
|
|
9122
|
-
void this.#
|
|
9123
|
-
this.logger.warn(
|
|
10029
|
+
void this.#handleA2aRequest(request2).then(ack, () => {
|
|
10030
|
+
this.logger.warn("a2a.request.failed");
|
|
9124
10031
|
ack({ status: 500, body: JSON.stringify({ error: "A2A request failed on the PC." }) });
|
|
9125
10032
|
});
|
|
9126
10033
|
});
|
|
@@ -9246,16 +10153,19 @@ var PcAgent = class {
|
|
|
9246
10153
|
throw new RelayRegistrationError(ack);
|
|
9247
10154
|
}
|
|
9248
10155
|
const storage = ack.sessionImageStorage === void 0 ? void 0 : SessionImageStorageSchema.parse(ack.sessionImageStorage);
|
|
9249
|
-
|
|
10156
|
+
const clientVerifiedUploads = storage?.mode === "direct" && ack.capabilities?.includes(SESSION_IMAGE_CLIENT_VERIFIED_CAPABILITY) === true;
|
|
10157
|
+
if (JSON.stringify(storage) !== JSON.stringify(this.#imageStorage) || clientVerifiedUploads !== this.#imageClientVerified) {
|
|
9250
10158
|
this.#imagePolicyRevision += 1;
|
|
9251
10159
|
this.#imageBlob?.reset();
|
|
9252
10160
|
this.#imageStorage = storage;
|
|
10161
|
+
this.#imageClientVerified = clientVerifiedUploads;
|
|
9253
10162
|
this.#imageBlob = storage === void 0 || !SessionImageRelayUrlSchema.safeParse(this.config.relayUrl).success ? void 0 : new TimelineImageBlobPublisher(this.#timelineIncremental.images, new SessionImageUploader({
|
|
9254
10163
|
relayUrl: this.config.relayUrl,
|
|
9255
10164
|
relayToken: this.config.relayToken,
|
|
9256
10165
|
userId: this.config.userId,
|
|
9257
10166
|
machineId: this.identity.machineId,
|
|
9258
|
-
...storage
|
|
10167
|
+
...storage,
|
|
10168
|
+
clientVerifiedUploads
|
|
9259
10169
|
}));
|
|
9260
10170
|
}
|
|
9261
10171
|
this.#registrationCapabilities = JSON.stringify(hello.capabilities);
|
|
@@ -9271,6 +10181,8 @@ var PcAgent = class {
|
|
|
9271
10181
|
this.#peerTransportNegotiated = hello.capabilities?.includes(PC_PEER_CHAT_CAPABILITY) === true && ack.capabilities?.includes(PC_PEER_CHAT_CAPABILITY) === true;
|
|
9272
10182
|
this.#peerNegotiated = this.#peerChatEnabled && peerRevision === this.#peerPreferenceRevision && this.#peerTransportNegotiated;
|
|
9273
10183
|
this.#a2aNegotiated = hello.capabilities?.includes(PC_A2A_CAPABILITY) === true && ack.capabilities?.includes(PC_A2A_CAPABILITY) === true;
|
|
10184
|
+
this.#encryptedPeerNegotiated = hello.capabilities?.includes(PC_ENCRYPTED_PEER_CAPABILITY) === true && ack.capabilities?.includes(PC_ENCRYPTED_PEER_CAPABILITY) === true;
|
|
10185
|
+
this.#retryPeerRevocations();
|
|
9274
10186
|
this.#relayRegistrationStatus = { state: "registered" };
|
|
9275
10187
|
this.#flushBufferedConversationItems();
|
|
9276
10188
|
this.#flushBufferedInteractionRequests();
|
|
@@ -9288,9 +10200,10 @@ var PcAgent = class {
|
|
|
9288
10200
|
SESSION_COMMUNICATION_CAPABILITY,
|
|
9289
10201
|
...this.textInputWriter === void 0 ? [] : [DEVICE_TEXT_INPUT_CAPABILITY],
|
|
9290
10202
|
SESSION_IMAGE_STORAGE_CAPABILITY,
|
|
10203
|
+
SESSION_IMAGE_CLIENT_VERIFIED_CAPABILITY,
|
|
9291
10204
|
...this.#sessionImagesEnabled && this.sessionImageStorage !== void 0 ? [PC_IMAGE_BLOB_POLICY_CAPABILITY, TIMELINE_IMAGE_BLOB_CAPABILITY] : [],
|
|
9292
10205
|
...this.#peerChatEnabled && this.adapter.runPeerTurn !== void 0 ? [PC_PEER_CHAT_CAPABILITY] : [],
|
|
9293
|
-
...this.adapter.runPeerTurn !== void 0 ? [PC_A2A_CAPABILITY] : [],
|
|
10206
|
+
...this.adapter.runPeerTurn !== void 0 ? [PC_A2A_CAPABILITY, PC_ENCRYPTED_PEER_CAPABILITY] : [],
|
|
9294
10207
|
SESSION_PROMPT_SUBMISSION_TIME_CAPABILITY,
|
|
9295
10208
|
...this.adapter.supportsAssistantPreview === true ? [SESSION_ASSISTANT_PREVIEW_CAPABILITY] : [],
|
|
9296
10209
|
...this.#communication.capabilities.filter((capability) => capability !== TIMELINE_IMAGE_BLOB_CAPABILITY),
|
|
@@ -9664,17 +10577,17 @@ var PcAgent = class {
|
|
|
9664
10577
|
return;
|
|
9665
10578
|
}
|
|
9666
10579
|
const timer = setTimeout(() => {
|
|
9667
|
-
|
|
10580
|
+
fail3(new Error(`${event} acknowledgement timed out`));
|
|
9668
10581
|
}, ACK_TIMEOUT_MS);
|
|
9669
|
-
const
|
|
10582
|
+
const fail3 = (error) => {
|
|
9670
10583
|
clearTimeout(timer);
|
|
9671
|
-
this.#pendingAcks.delete(
|
|
10584
|
+
this.#pendingAcks.delete(fail3);
|
|
9672
10585
|
reject(error);
|
|
9673
10586
|
};
|
|
9674
|
-
this.#pendingAcks.add(
|
|
10587
|
+
this.#pendingAcks.add(fail3);
|
|
9675
10588
|
const receiveAck = (ack) => {
|
|
9676
10589
|
clearTimeout(timer);
|
|
9677
|
-
this.#pendingAcks.delete(
|
|
10590
|
+
this.#pendingAcks.delete(fail3);
|
|
9678
10591
|
resolve5(ack);
|
|
9679
10592
|
};
|
|
9680
10593
|
try {
|
|
@@ -9689,7 +10602,7 @@ var PcAgent = class {
|
|
|
9689
10602
|
}
|
|
9690
10603
|
} catch (error) {
|
|
9691
10604
|
clearTimeout(timer);
|
|
9692
|
-
this.#pendingAcks.delete(
|
|
10605
|
+
this.#pendingAcks.delete(fail3);
|
|
9693
10606
|
reject(error);
|
|
9694
10607
|
}
|
|
9695
10608
|
});
|
|
@@ -9801,45 +10714,45 @@ function contextItem(item) {
|
|
|
9801
10714
|
|
|
9802
10715
|
// src/research-sessions.ts
|
|
9803
10716
|
import { execFile as execFile3 } from "node:child_process";
|
|
9804
|
-
import { createHash as
|
|
9805
|
-
import { mkdir as
|
|
9806
|
-
import { join as
|
|
10717
|
+
import { createHash as createHash17, randomUUID as randomUUID14 } from "node:crypto";
|
|
10718
|
+
import { mkdir as mkdir7, lstat as lstat8, realpath as realpath8 } from "node:fs/promises";
|
|
10719
|
+
import { join as join15, resolve as resolve4 } from "node:path";
|
|
9807
10720
|
import { promisify as promisify4 } from "node:util";
|
|
9808
|
-
import { z as
|
|
10721
|
+
import { z as z11 } from "zod";
|
|
9809
10722
|
|
|
9810
10723
|
// src/research-thread-store.ts
|
|
9811
|
-
import { randomUUID as
|
|
9812
|
-
import { mkdir as
|
|
9813
|
-
import { join as
|
|
9814
|
-
import { z as
|
|
10724
|
+
import { randomUUID as randomUUID12 } from "node:crypto";
|
|
10725
|
+
import { mkdir as mkdir6, readFile as readFile4, rename as rename4, rm as rm4, lstat as lstat6, realpath as realpath7, writeFile as writeFile5 } from "node:fs/promises";
|
|
10726
|
+
import { join as join13, resolve as resolve3 } from "node:path";
|
|
10727
|
+
import { z as z9 } from "zod";
|
|
9815
10728
|
var RESEARCH_PROFILE = "research-readonly";
|
|
9816
10729
|
var RESEARCH_PROFILE_VERSION = 1;
|
|
9817
10730
|
var MAX_THREADS = 256;
|
|
9818
|
-
var recordSchema =
|
|
9819
|
-
threadId:
|
|
9820
|
-
researchSessionId:
|
|
9821
|
-
parentSessionId:
|
|
9822
|
-
operationId:
|
|
9823
|
-
fingerprint:
|
|
9824
|
-
title:
|
|
9825
|
-
profile:
|
|
9826
|
-
profileVersion:
|
|
9827
|
-
workingDirectory:
|
|
9828
|
-
rootIdentity:
|
|
9829
|
-
contextAnchor:
|
|
9830
|
-
contextSampledAt:
|
|
9831
|
-
contextTruncated:
|
|
9832
|
-
chatVersion:
|
|
9833
|
-
createdAt:
|
|
9834
|
-
state:
|
|
9835
|
-
errorCode:
|
|
10731
|
+
var recordSchema = z9.object({
|
|
10732
|
+
threadId: z9.string().uuid(),
|
|
10733
|
+
researchSessionId: z9.string().uuid(),
|
|
10734
|
+
parentSessionId: z9.string().min(1).max(256),
|
|
10735
|
+
operationId: z9.string().min(1).max(256),
|
|
10736
|
+
fingerprint: z9.string().min(1).max(128),
|
|
10737
|
+
title: z9.string().min(1).max(200),
|
|
10738
|
+
profile: z9.literal(RESEARCH_PROFILE),
|
|
10739
|
+
profileVersion: z9.literal(RESEARCH_PROFILE_VERSION),
|
|
10740
|
+
workingDirectory: z9.string().min(1).max(8192),
|
|
10741
|
+
rootIdentity: z9.string().min(1).max(128),
|
|
10742
|
+
contextAnchor: z9.string().min(1).max(256),
|
|
10743
|
+
contextSampledAt: z9.string().datetime(),
|
|
10744
|
+
contextTruncated: z9.boolean(),
|
|
10745
|
+
chatVersion: z9.literal(1).optional(),
|
|
10746
|
+
createdAt: z9.string().datetime(),
|
|
10747
|
+
state: z9.enum(["creating", "ready", "uncertain", "failed", "deleting"]),
|
|
10748
|
+
errorCode: z9.string().max(128).optional()
|
|
9836
10749
|
}).strict();
|
|
9837
|
-
var documentSchema =
|
|
9838
|
-
version:
|
|
9839
|
-
threads:
|
|
9840
|
-
tombstones:
|
|
9841
|
-
researchSessionId:
|
|
9842
|
-
parentSessionId:
|
|
10750
|
+
var documentSchema = z9.object({
|
|
10751
|
+
version: z9.literal(1),
|
|
10752
|
+
threads: z9.array(recordSchema).max(MAX_THREADS),
|
|
10753
|
+
tombstones: z9.array(z9.object({
|
|
10754
|
+
researchSessionId: z9.string().uuid(),
|
|
10755
|
+
parentSessionId: z9.string().min(1).max(256)
|
|
9843
10756
|
}).strict()).max(1e5).optional()
|
|
9844
10757
|
}).strict();
|
|
9845
10758
|
var ResearchThreadStore = class {
|
|
@@ -9851,21 +10764,21 @@ var ResearchThreadStore = class {
|
|
|
9851
10764
|
#mutation = Promise.resolve();
|
|
9852
10765
|
constructor(dataDirectory) {
|
|
9853
10766
|
this.directory = resolve3(dataDirectory, "research");
|
|
9854
|
-
this.#file =
|
|
10767
|
+
this.#file = join13(this.directory, "threads.json");
|
|
9855
10768
|
}
|
|
9856
10769
|
initialize() {
|
|
9857
10770
|
this.#loaded ??= this.#load();
|
|
9858
10771
|
return this.#loaded;
|
|
9859
10772
|
}
|
|
9860
10773
|
async #load() {
|
|
9861
|
-
await
|
|
10774
|
+
await mkdir6(this.directory, { recursive: true, mode: 448 });
|
|
9862
10775
|
if ((await lstat6(this.directory)).isSymbolicLink() || await realpath7(this.directory) !== this.directory) {
|
|
9863
10776
|
throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
|
|
9864
10777
|
}
|
|
9865
10778
|
try {
|
|
9866
10779
|
const metadata = await lstat6(this.#file);
|
|
9867
10780
|
if (metadata.isSymbolicLink() || metadata.size > 32 * 1024 * 1024) throw new ResearchError("RESEARCH_STORE_INVALID");
|
|
9868
|
-
const parsed = JSON.parse(await
|
|
10781
|
+
const parsed = JSON.parse(await readFile4(this.#file, "utf8"));
|
|
9869
10782
|
const data = documentSchema.parse(parsed);
|
|
9870
10783
|
for (const tombstone of data.tombstones ?? []) {
|
|
9871
10784
|
if (this.#tombstones.has(tombstone.researchSessionId)) throw new ResearchError("RESEARCH_STORE_INVALID");
|
|
@@ -9885,18 +10798,18 @@ var ResearchThreadStore = class {
|
|
|
9885
10798
|
}
|
|
9886
10799
|
}
|
|
9887
10800
|
async #write(records2, tombstones = this.#tombstones) {
|
|
9888
|
-
const staging =
|
|
10801
|
+
const staging = join13(this.directory, `threads-${randomUUID12()}.pending`);
|
|
9889
10802
|
try {
|
|
9890
|
-
await
|
|
10803
|
+
await writeFile5(staging, JSON.stringify({
|
|
9891
10804
|
version: 1,
|
|
9892
10805
|
threads: [...records2.values()],
|
|
9893
10806
|
tombstones: [...tombstones].map(([researchSessionId, parentSessionId]) => ({ researchSessionId, parentSessionId }))
|
|
9894
10807
|
}), { flag: "wx", mode: 384 });
|
|
9895
|
-
await
|
|
10808
|
+
await rename4(staging, this.#file);
|
|
9896
10809
|
this.#records = records2;
|
|
9897
10810
|
this.#tombstones = tombstones;
|
|
9898
10811
|
} finally {
|
|
9899
|
-
await
|
|
10812
|
+
await rm4(staging, { force: true });
|
|
9900
10813
|
}
|
|
9901
10814
|
}
|
|
9902
10815
|
async #serialized(work) {
|
|
@@ -9918,8 +10831,8 @@ var ResearchThreadStore = class {
|
|
|
9918
10831
|
}
|
|
9919
10832
|
const record = recordSchema.parse({
|
|
9920
10833
|
...input,
|
|
9921
|
-
threadId:
|
|
9922
|
-
researchSessionId:
|
|
10834
|
+
threadId: randomUUID12(),
|
|
10835
|
+
researchSessionId: randomUUID12(),
|
|
9923
10836
|
profile: RESEARCH_PROFILE,
|
|
9924
10837
|
profileVersion: RESEARCH_PROFILE_VERSION,
|
|
9925
10838
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -9973,27 +10886,27 @@ var ResearchThreadStore = class {
|
|
|
9973
10886
|
};
|
|
9974
10887
|
|
|
9975
10888
|
// src/research-chat-store.ts
|
|
9976
|
-
import { randomUUID as
|
|
9977
|
-
import { lstat as lstat7, readFile as
|
|
9978
|
-
import { join as
|
|
9979
|
-
import { z as
|
|
9980
|
-
var receipt =
|
|
9981
|
-
operationId:
|
|
9982
|
-
fingerprint:
|
|
9983
|
-
promptHash:
|
|
9984
|
-
ordinal:
|
|
9985
|
-
submittedAt:
|
|
9986
|
-
state:
|
|
9987
|
-
messageId:
|
|
9988
|
-
deliveryState:
|
|
10889
|
+
import { randomUUID as randomUUID13 } from "node:crypto";
|
|
10890
|
+
import { lstat as lstat7, readFile as readFile5, rename as rename5, rm as rm5, writeFile as writeFile6 } from "node:fs/promises";
|
|
10891
|
+
import { join as join14 } from "node:path";
|
|
10892
|
+
import { z as z10 } from "zod";
|
|
10893
|
+
var receipt = z10.object({
|
|
10894
|
+
operationId: z10.string().min(1).max(256),
|
|
10895
|
+
fingerprint: z10.string().min(1).max(128),
|
|
10896
|
+
promptHash: z10.string().min(1).max(128),
|
|
10897
|
+
ordinal: z10.number().int().nonnegative(),
|
|
10898
|
+
submittedAt: z10.string().datetime(),
|
|
10899
|
+
state: z10.enum(["sending", "accepted"]),
|
|
10900
|
+
messageId: z10.string().min(1).max(256).optional(),
|
|
10901
|
+
deliveryState: z10.enum(["queued", "processing"])
|
|
9989
10902
|
}).strict();
|
|
9990
|
-
var stateSchema =
|
|
9991
|
-
version:
|
|
9992
|
-
modelId:
|
|
9993
|
-
reasoningEffort:
|
|
9994
|
-
seed:
|
|
9995
|
-
seedState:
|
|
9996
|
-
receipts:
|
|
10903
|
+
var stateSchema = z10.object({
|
|
10904
|
+
version: z10.literal(1),
|
|
10905
|
+
modelId: z10.string().min(1).max(256).optional(),
|
|
10906
|
+
reasoningEffort: z10.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
|
|
10907
|
+
seed: z10.string().max(3e5).optional(),
|
|
10908
|
+
seedState: z10.enum(["pending", "submitted", "none"]),
|
|
10909
|
+
receipts: z10.array(receipt).max(1e4)
|
|
9997
10910
|
}).strict().superRefine((state, ctx) => {
|
|
9998
10911
|
if (new Set(state.receipts.map((item) => item.operationId)).size !== state.receipts.length || new Set(state.receipts.map((item) => item.ordinal)).size !== state.receipts.length || state.seedState === "pending" && state.seed === void 0) {
|
|
9999
10912
|
ctx.addIssue({ code: "custom", message: "Invalid research chat state" });
|
|
@@ -10009,7 +10922,7 @@ var ResearchChatStore = class {
|
|
|
10009
10922
|
return this.#states.get(sessionId);
|
|
10010
10923
|
}
|
|
10011
10924
|
#file(sessionId) {
|
|
10012
|
-
return
|
|
10925
|
+
return join14(this.directory, `chat-${z10.string().uuid().parse(sessionId)}.json`);
|
|
10013
10926
|
}
|
|
10014
10927
|
async read(sessionId) {
|
|
10015
10928
|
const cached = this.#states.get(sessionId);
|
|
@@ -10018,7 +10931,7 @@ var ResearchChatStore = class {
|
|
|
10018
10931
|
const path = this.#file(sessionId);
|
|
10019
10932
|
const metadata = await lstat7(path);
|
|
10020
10933
|
if (metadata.isSymbolicLink() || metadata.size > 8 * 1024 * 1024) throw new ResearchError("RESEARCH_STORE_INVALID");
|
|
10021
|
-
const data = JSON.parse(await
|
|
10934
|
+
const data = JSON.parse(await readFile5(path, "utf8"));
|
|
10022
10935
|
const state = stateSchema.parse(data);
|
|
10023
10936
|
this.#states.set(sessionId, state);
|
|
10024
10937
|
return state;
|
|
@@ -10030,17 +10943,17 @@ var ResearchChatStore = class {
|
|
|
10030
10943
|
async write(sessionId, state) {
|
|
10031
10944
|
const validated = stateSchema.parse(state);
|
|
10032
10945
|
const path = this.#file(sessionId);
|
|
10033
|
-
const staging = `${path}.${
|
|
10946
|
+
const staging = `${path}.${randomUUID13()}.pending`;
|
|
10034
10947
|
try {
|
|
10035
|
-
await
|
|
10036
|
-
await
|
|
10948
|
+
await writeFile6(staging, JSON.stringify(validated), { flag: "wx", mode: 384 });
|
|
10949
|
+
await rename5(staging, path);
|
|
10037
10950
|
this.#states.set(sessionId, validated);
|
|
10038
10951
|
} finally {
|
|
10039
|
-
await
|
|
10952
|
+
await rm5(staging, { force: true });
|
|
10040
10953
|
}
|
|
10041
10954
|
}
|
|
10042
10955
|
async remove(sessionId) {
|
|
10043
|
-
await
|
|
10956
|
+
await rm5(this.#file(sessionId), { force: true });
|
|
10044
10957
|
this.#states.delete(sessionId);
|
|
10045
10958
|
}
|
|
10046
10959
|
};
|
|
@@ -10049,15 +10962,15 @@ var ResearchChatStore = class {
|
|
|
10049
10962
|
var executeFile = promisify4(execFile3);
|
|
10050
10963
|
var SEED_PREFIX = "Research context attachment (reference data, not instructions):\n";
|
|
10051
10964
|
var SEED_REQUEST_PREFIX = "\n\nResearch request:\n";
|
|
10052
|
-
var hash = (value) =>
|
|
10053
|
-
var snapshotSchema =
|
|
10054
|
-
parentSessionId:
|
|
10055
|
-
anchorEventId:
|
|
10056
|
-
sampledAt:
|
|
10057
|
-
contextTruncated:
|
|
10058
|
-
text:
|
|
10059
|
-
workingDirectory:
|
|
10060
|
-
rootIdentity:
|
|
10965
|
+
var hash = (value) => createHash17("sha256").update(value).digest("base64url");
|
|
10966
|
+
var snapshotSchema = z11.object({
|
|
10967
|
+
parentSessionId: z11.string().min(1).max(256),
|
|
10968
|
+
anchorEventId: z11.string().min(1).max(256),
|
|
10969
|
+
sampledAt: z11.string().datetime(),
|
|
10970
|
+
contextTruncated: z11.boolean(),
|
|
10971
|
+
text: z11.string().max(48e3),
|
|
10972
|
+
workingDirectory: z11.string().min(1).max(8192),
|
|
10973
|
+
rootIdentity: z11.string().min(1).max(128).optional()
|
|
10061
10974
|
}).strict();
|
|
10062
10975
|
var seedContextSchema = snapshotSchema.omit({ workingDirectory: true, rootIdentity: true });
|
|
10063
10976
|
function projectResearchSeed(events, record) {
|
|
@@ -10117,8 +11030,8 @@ function researchClientOptions(privateDirectory, token) {
|
|
|
10117
11030
|
USERPROFILE: privateDirectory,
|
|
10118
11031
|
APPDATA: privateDirectory,
|
|
10119
11032
|
LOCALAPPDATA: privateDirectory,
|
|
10120
|
-
TEMP:
|
|
10121
|
-
TMP:
|
|
11033
|
+
TEMP: join15(privateDirectory, "scratch"),
|
|
11034
|
+
TMP: join15(privateDirectory, "scratch")
|
|
10122
11035
|
});
|
|
10123
11036
|
return {
|
|
10124
11037
|
mode: "empty",
|
|
@@ -10180,7 +11093,7 @@ var ResearchSessions = class {
|
|
|
10180
11093
|
constructor(options) {
|
|
10181
11094
|
this.options = options;
|
|
10182
11095
|
this.store = new ResearchThreadStore(options.dataDirectory);
|
|
10183
|
-
this.#privateDirectory =
|
|
11096
|
+
this.#privateDirectory = join15(this.store.directory, "runtime");
|
|
10184
11097
|
this.#chat = new ResearchChatStore(this.store.directory);
|
|
10185
11098
|
this.#projection = new LiveTimelineProjection({
|
|
10186
11099
|
state: (id) => this.#state(id),
|
|
@@ -10201,7 +11114,7 @@ var ResearchSessions = class {
|
|
|
10201
11114
|
});
|
|
10202
11115
|
}
|
|
10203
11116
|
options;
|
|
10204
|
-
#generation =
|
|
11117
|
+
#generation = randomUUID14();
|
|
10205
11118
|
store;
|
|
10206
11119
|
#privateDirectory;
|
|
10207
11120
|
#active = /* @__PURE__ */ new Map();
|
|
@@ -10270,7 +11183,7 @@ var ResearchSessions = class {
|
|
|
10270
11183
|
this.#failedClient = void 0;
|
|
10271
11184
|
}
|
|
10272
11185
|
await this.store.initialize();
|
|
10273
|
-
await
|
|
11186
|
+
await mkdir7(join15(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
|
|
10274
11187
|
if ((await lstat8(this.#privateDirectory)).isSymbolicLink() || await realpath8(this.#privateDirectory) !== resolve4(this.#privateDirectory)) {
|
|
10275
11188
|
throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
|
|
10276
11189
|
}
|
|
@@ -10458,9 +11371,9 @@ var ResearchSessions = class {
|
|
|
10458
11371
|
assertAccess?.();
|
|
10459
11372
|
const snapshot = snapshotSchema.parse(input.snapshot);
|
|
10460
11373
|
if (snapshot.parentSessionId !== input.parentSessionId) throw new ResearchError("RESEARCH_SOURCE_MISMATCH");
|
|
10461
|
-
const title =
|
|
10462
|
-
const prompt =
|
|
10463
|
-
const fingerprint =
|
|
11374
|
+
const title = z11.string().trim().min(1).max(200).parse(input.title ?? "Research");
|
|
11375
|
+
const prompt = z11.string().trim().min(1).max(16e3).parse(input.prompt ?? "Acknowledge the context briefly and wait for my research question.");
|
|
11376
|
+
const fingerprint = createHash17("sha256").update(JSON.stringify({
|
|
10464
11377
|
parentSessionId: input.parentSessionId,
|
|
10465
11378
|
title,
|
|
10466
11379
|
prompt,
|
|
@@ -10494,7 +11407,7 @@ var ResearchSessions = class {
|
|
|
10494
11407
|
let session;
|
|
10495
11408
|
try {
|
|
10496
11409
|
const configuration = input.configuration ?? await this.options.sourceConfiguration?.(input.parentSessionId);
|
|
10497
|
-
const reasoning =
|
|
11410
|
+
const reasoning = z11.enum(["low", "medium", "high", "xhigh", "max"]).safeParse(configuration?.reasoningEffort);
|
|
10498
11411
|
if (configuration !== void 0 && !reasoning.success && !["default", "unknown"].includes(configuration.reasoningEffort)) {
|
|
10499
11412
|
throw new ResearchError("RESEARCH_CONFIGURATION_UNSUPPORTED");
|
|
10500
11413
|
}
|
|
@@ -10618,7 +11531,7 @@ var ResearchSessions = class {
|
|
|
10618
11531
|
const assertAccess = this.#capture(record);
|
|
10619
11532
|
assertAccess();
|
|
10620
11533
|
if (options.metadataOnly === true) throw new ResearchError("RESEARCH_SESSION_ISOLATED");
|
|
10621
|
-
const pageSize =
|
|
11534
|
+
const pageSize = z11.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
|
|
10622
11535
|
const result = await this.#state(sessionId).timelineReads.read({
|
|
10623
11536
|
...options.cursor === void 0 ? {} : { cursor: options.cursor },
|
|
10624
11537
|
pageSize,
|
|
@@ -10661,13 +11574,13 @@ var ResearchSessions = class {
|
|
|
10661
11574
|
compactDisabledReason: "Research context compaction is unavailable"
|
|
10662
11575
|
});
|
|
10663
11576
|
}
|
|
10664
|
-
async send(sessionId, text, operationId =
|
|
11577
|
+
async send(sessionId, text, operationId = randomUUID14()) {
|
|
10665
11578
|
if (this.#active.get(sessionId)?.runtime.activity.busy) throw new ResearchError("RESEARCH_BUSY");
|
|
10666
11579
|
return (await this.sendPrompt(sessionId, text, "immediate", operationId)).messageId;
|
|
10667
11580
|
}
|
|
10668
11581
|
async sendPrompt(sessionId, text, mode, operationId) {
|
|
10669
|
-
const prompt =
|
|
10670
|
-
|
|
11582
|
+
const prompt = z11.string().trim().min(1).max(16e3).parse(text);
|
|
11583
|
+
z11.string().min(1).max(256).parse(operationId);
|
|
10671
11584
|
const fingerprint = hash(JSON.stringify({ prompt, mode }));
|
|
10672
11585
|
const running = this.#sending.get(sessionId);
|
|
10673
11586
|
if (running !== void 0 && running.operationId === operationId) {
|
|
@@ -10956,23 +11869,23 @@ function createResearchWorkbench(options) {
|
|
|
10956
11869
|
}
|
|
10957
11870
|
|
|
10958
11871
|
// src/initialize.ts
|
|
10959
|
-
var ConfigSchema =
|
|
10960
|
-
dataDirectory:
|
|
10961
|
-
relayUrl:
|
|
10962
|
-
relayToken:
|
|
10963
|
-
userId:
|
|
10964
|
-
workspaceRoot:
|
|
10965
|
-
refreshIntervalMs:
|
|
10966
|
-
heartbeatIntervalMs:
|
|
10967
|
-
exitAfterSnapshot:
|
|
10968
|
-
groupChatEnabled:
|
|
10969
|
-
peerChatEnabled:
|
|
10970
|
-
snapshotSuppressionEnabled:
|
|
10971
|
-
timelineCompressionEnabled:
|
|
10972
|
-
timelineIncrementalEnabled:
|
|
10973
|
-
secureMessagePacketBudget:
|
|
11872
|
+
var ConfigSchema = z12.object({
|
|
11873
|
+
dataDirectory: z12.string().min(1),
|
|
11874
|
+
relayUrl: z12.url().refine((value) => ["https:", "http:"].includes(new URL(value).protocol)),
|
|
11875
|
+
relayToken: z12.string().min(24),
|
|
11876
|
+
userId: z12.string().trim().min(1).max(256),
|
|
11877
|
+
workspaceRoot: z12.string().optional(),
|
|
11878
|
+
refreshIntervalMs: z12.number().int().min(5e3).max(36e5).default(3e4),
|
|
11879
|
+
heartbeatIntervalMs: z12.number().int().min(5e3).max(12e4).default(15e3),
|
|
11880
|
+
exitAfterSnapshot: z12.boolean().default(false),
|
|
11881
|
+
groupChatEnabled: z12.boolean().optional(),
|
|
11882
|
+
peerChatEnabled: z12.boolean().optional(),
|
|
11883
|
+
snapshotSuppressionEnabled: z12.boolean().optional(),
|
|
11884
|
+
timelineCompressionEnabled: z12.boolean().optional(),
|
|
11885
|
+
timelineIncrementalEnabled: z12.boolean().optional(),
|
|
11886
|
+
secureMessagePacketBudget: z12.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).optional(),
|
|
10974
11887
|
sessionImages: SessionImagesConfigSchema.optional(),
|
|
10975
|
-
sessionImagesEnabled:
|
|
11888
|
+
sessionImagesEnabled: z12.boolean().optional()
|
|
10976
11889
|
}).superRefine((config, context) => {
|
|
10977
11890
|
if ((config.sessionImages !== void 0 || config.sessionImagesEnabled === true) && !SessionImageRelayUrlSchema.safeParse(config.relayUrl).success) {
|
|
10978
11891
|
context.addIssue({
|
|
@@ -11009,7 +11922,7 @@ async function initialize(options) {
|
|
|
11009
11922
|
...options.codingAgent === void 0 ? {} : { codingAgent: options.codingAgent }
|
|
11010
11923
|
};
|
|
11011
11924
|
const identity2 = DeviceIdentitySchema.parse(options.identity);
|
|
11012
|
-
const appVersion = options.appVersion ??
|
|
11925
|
+
const appVersion = options.appVersion ?? z12.object({ version: z12.string().min(1) }).parse(JSON.parse(await readFile6(new URL("../package.json", import.meta.url), "utf8"))).version;
|
|
11013
11926
|
const lease = options.directoryLease ?? await DataDirectoryLease.acquire(dataDirectory);
|
|
11014
11927
|
let detach;
|
|
11015
11928
|
let adapter;
|
|
@@ -11065,7 +11978,7 @@ async function initialize(options) {
|
|
|
11065
11978
|
}, "research.operation.failed")
|
|
11066
11979
|
});
|
|
11067
11980
|
class InitializedAgent extends PcAgent {
|
|
11068
|
-
identityHash =
|
|
11981
|
+
identityHash = createHash18("sha256").update(`${config.userId}:${identity2.machineId}:${contentKey.keyId}`).digest("hex");
|
|
11069
11982
|
#started;
|
|
11070
11983
|
#starting;
|
|
11071
11984
|
#closed;
|