@agentknight/sdk 0.9.57 → 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.
Files changed (23) hide show
  1. package/dist/chunks/{acp-adapter-WYDK3PLS.js → acp-adapter-OGD5QSNI.js} +4 -4
  2. package/dist/chunks/{chunk-WPVH7HKC.js → chunk-2MERNOK6.js} +1 -1
  3. package/dist/chunks/{chunk-7ZYBES47.js → chunk-3OIHMMDF.js} +1 -1
  4. package/dist/chunks/{chunk-3LEPYV7Y.js → chunk-5DVJ7Y5W.js} +2 -2
  5. package/dist/chunks/{chunk-USI66MEF.js → chunk-AREU4R62.js} +3 -2
  6. package/dist/chunks/{chunk-ZLKFFKAX.js → chunk-DP5KVGWF.js} +4 -3
  7. package/dist/chunks/{chunk-DAKDVZ7X.js → chunk-FDUJP3WA.js} +2 -2
  8. package/dist/chunks/{chunk-KBI5IWPR.js → chunk-LO4ZRE77.js} +747 -513
  9. package/dist/chunks/{chunk-OOCAIULD.js → chunk-LWJNDBIM.js} +431 -21
  10. package/dist/chunks/{chunk-IPJWNGNK.js → chunk-NDEJOXSX.js} +1 -1
  11. package/dist/chunks/{chunk-EDZPP6SJ.js → chunk-X3ZG6WMN.js} +2 -3
  12. package/dist/chunks/{chunk-LT5ULDVT.js → chunk-ZDKBJFA2.js} +1 -1
  13. package/dist/chunks/{claude-adapter-GCH36EZ6.js → claude-adapter-DGZBZSWJ.js} +209 -59
  14. package/dist/chunks/{codex-adapter-CXD4SVCE.js → codex-adapter-2W7RRER3.js} +4 -4
  15. package/dist/chunks/{copilot-adapter-SYFGOAGE.js → copilot-adapter-ZEHU6CFQ.js} +109 -14
  16. package/dist/chunks/{managed-agent-adapter-ODCNYYO6.js → managed-agent-adapter-CGJPJZ2Z.js} +20 -6
  17. package/dist/chunks/{pi-adapter-XLY46UDL.js → pi-adapter-WOVSWBGG.js} +4 -4
  18. package/dist/configuration.js +4 -4
  19. package/dist/index.d.ts +126 -1
  20. package/dist/index.js +1447 -562
  21. package/dist/runtime.js +2 -2
  22. package/dist/session-analytics-worker.js +162 -51
  23. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  PeerChatRequestSchema,
11
11
  PeerChatResultSchema,
12
12
  validateDataDirectory
13
- } from "./chunks/chunk-USI66MEF.js";
13
+ } from "./chunks/chunk-AREU4R62.js";
14
14
  import {
15
15
  DeviceIdentitySchema,
16
16
  codingAgentPresentation,
@@ -20,16 +20,19 @@ import {
20
20
  AgentSelectionSchema,
21
21
  assertSelectionSnapshotFits,
22
22
  supportsAgentSelection
23
- } from "./chunks/chunk-DAKDVZ7X.js";
23
+ } from "./chunks/chunk-FDUJP3WA.js";
24
24
  import {
25
25
  LiveTimelineProjection,
26
26
  OperationDiagnostics,
27
27
  OperationMetrics,
28
28
  PromptPreparationError,
29
+ SessionDirectoryError,
30
+ SessionDirectoryLister,
29
31
  SessionImageUploadError,
30
32
  SessionImageUploader,
31
33
  SessionProjectIdentityError,
32
34
  SessionRuntime,
35
+ contained,
33
36
  diagnosticError,
34
37
  diagnosticReference,
35
38
  diagnosticRequest,
@@ -41,8 +44,9 @@ import {
41
44
  recordTimelineSyncDiagnostic,
42
45
  resolveGitProjectIdentity,
43
46
  sessionRestoreFailure,
47
+ sessionRootIdentity,
44
48
  validateOperationResponse
45
- } from "./chunks/chunk-OOCAIULD.js";
49
+ } from "./chunks/chunk-LWJNDBIM.js";
46
50
  import {
47
51
  SessionImageRelayUrlSchema,
48
52
  SessionImagesConfigSchema
@@ -50,16 +54,15 @@ import {
50
54
  import {
51
55
  ConversationNormalizer,
52
56
  isDisplayableHumanMessage
53
- } from "./chunks/chunk-LT5ULDVT.js";
57
+ } from "./chunks/chunk-ZDKBJFA2.js";
54
58
  import {
55
- GROUP_CHAT_MAX_TURNS,
56
59
  GroupChatError
57
- } from "./chunks/chunk-EDZPP6SJ.js";
60
+ } from "./chunks/chunk-X3ZG6WMN.js";
58
61
  import {
59
62
  assistantPreview,
60
63
  isContentfulAssistant,
61
64
  userPreview
62
- } from "./chunks/chunk-IPJWNGNK.js";
65
+ } from "./chunks/chunk-NDEJOXSX.js";
63
66
  import {
64
67
  AgentModelListingError,
65
68
  AgentSessionRenameError,
@@ -67,13 +70,15 @@ import {
67
70
  TimelinePageBudgetError,
68
71
  UnsupportedAgentOperationError,
69
72
  captureResearchAccess,
70
- captureWorkbenchAccess
71
- } from "./chunks/chunk-3LEPYV7Y.js";
73
+ captureWorkbenchAccess,
74
+ validateSessionName
75
+ } from "./chunks/chunk-5DVJ7Y5W.js";
72
76
  import {
73
77
  SessionOperationError,
74
78
  SessionOperations
75
- } from "./chunks/chunk-7ZYBES47.js";
79
+ } from "./chunks/chunk-3OIHMMDF.js";
76
80
  import {
81
+ A2A_BODY_MAX_LENGTH,
77
82
  A2aRelayRequestSchema,
78
83
  A2aRelayResponseSchema,
79
84
  AGENT_CONTROLS_CAPABILITY,
@@ -90,11 +95,19 @@ import {
90
95
  DEVICE_TEXT_INPUT_VERSION,
91
96
  DeviceTextInputDataSchema,
92
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,
93
105
  GROUP_CHAT_CREATE_CAPABILITY,
94
106
  GROUP_CHAT_CREATE_OPERATION,
95
107
  GROUP_CHAT_CREATE_VERSION,
96
108
  GroupChatCreateDataSchema,
97
109
  GroupChatCreateResultDataSchema,
110
+ GroupChatInfoSchema,
98
111
  INTERACTION_DISMISS_RESPONSE_CAPABILITY,
99
112
  INTERACTION_SUPERSEDED_ERROR_CODE,
100
113
  IdSchema,
@@ -115,6 +128,7 @@ import {
115
128
  PAIRING_URI_HOST,
116
129
  PAIRING_URI_SCHEME,
117
130
  PC_A2A_CAPABILITY,
131
+ PC_ENCRYPTED_PEER_CAPABILITY,
118
132
  PC_IMAGE_BLOB_POLICY_CAPABILITY,
119
133
  PC_PEER_CHAT_CAPABILITY,
120
134
  PROTOCOL_VERSION,
@@ -137,8 +151,6 @@ import {
137
151
  SESSION_DELETE_CAPABILITY,
138
152
  SESSION_DIRECTORY_LIST_OPERATION,
139
153
  SESSION_DIRECTORY_LIST_VERSION,
140
- SESSION_DIRECTORY_MAX_ENTRIES,
141
- SESSION_DIRECTORY_MAX_RESPONSE_BYTES,
142
154
  SESSION_FILE_ATTACHMENTS_CAPABILITY,
143
155
  SESSION_FILE_DOWNLOAD_MAX_ORIGINAL_BYTES,
144
156
  SESSION_FILE_DOWNLOAD_OPERATION,
@@ -178,6 +190,7 @@ import {
178
190
  SESSION_RESOURCE_MAX_ORIGINAL_BYTES,
179
191
  SESSION_RESOURCE_READ_OPERATION,
180
192
  SESSION_RESOURCE_READ_VERSION,
193
+ SESSION_STATE_FILES_CAPABILITY,
181
194
  SESSION_TIMELINE_PAGE_SIZE,
182
195
  SESSION_WORKTREE_CREATION_CAPABILITY,
183
196
  SecureMessageSchema,
@@ -216,6 +229,7 @@ import {
216
229
  SessionRenameResultDataSchema,
217
230
  SessionResourceReadDataSchema,
218
231
  SessionResourceReadResultDataSchema,
232
+ SessionSummarySchema,
219
233
  SessionTimelineInvalidatedSchema,
220
234
  SessionTimelinePageRequestSchema,
221
235
  SessionTimelinePageSchema,
@@ -253,6 +267,8 @@ import {
253
267
  WorkbenchQueueMutationRequestSchema,
254
268
  WorkbenchQueueMutationResultSchema,
255
269
  WorkbenchQueueSnapshotSchema,
270
+ WorkbenchReasoningPageSchema,
271
+ WorkbenchReasoningRequestSchema,
256
272
  WorkbenchResearchCreateRequestSchema,
257
273
  WorkbenchResearchCreateResultSchema,
258
274
  WorkbenchResearchListResultSchema,
@@ -270,12 +286,12 @@ import {
270
286
  sessionCommunicationError,
271
287
  sessionCommunicationOperationCapability,
272
288
  workbenchCapability
273
- } from "./chunks/chunk-KBI5IWPR.js";
289
+ } from "./chunks/chunk-LO4ZRE77.js";
274
290
 
275
291
  // src/initialize.ts
276
- import { createHash as createHash16 } from "node:crypto";
277
- import { readFile as readFile4 } from "node:fs/promises";
278
- import { z as z10 } from "zod";
292
+ import { createHash as createHash18 } from "node:crypto";
293
+ import { readFile as readFile6 } from "node:fs/promises";
294
+ import { z as z12 } from "zod";
279
295
 
280
296
  // src/coding-agent-factory.ts
281
297
  import { resolve } from "node:path";
@@ -290,7 +306,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
290
306
  switch (engine.kind) {
291
307
  case "managed": {
292
308
  if (owner === void 0) throw new Error("Managed coding agents require the PC owner identity");
293
- const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-ODCNYYO6.js");
309
+ const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-CGJPJZ2Z.js");
294
310
  return new ManagedCodingAgentAdapter({
295
311
  dataDirectory: config.dataDirectory,
296
312
  owner,
@@ -332,7 +348,13 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
332
348
  id: "claude",
333
349
  name: codingAgentPresentation("claude").name,
334
350
  detect: detectClaude,
335
- create: () => createCodingAgentAdapter({ ...config, codingAgent: { kind: "claude" } }, onDiagnostic, owner)
351
+ create: () => createCodingAgentAdapter({
352
+ ...config,
353
+ codingAgent: {
354
+ kind: "claude",
355
+ ...engine.claudeCommand === void 0 ? {} : { command: engine.claudeCommand }
356
+ }
357
+ }, onDiagnostic, owner)
336
358
  },
337
359
  {
338
360
  id: "acp",
@@ -347,7 +369,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
347
369
  });
348
370
  }
349
371
  case "copilot": {
350
- const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-SYFGOAGE.js");
372
+ const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-ZEHU6CFQ.js");
351
373
  if (owner !== void 0) {
352
374
  return new GithubCopilotAdapter(
353
375
  void 0,
@@ -376,13 +398,13 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
376
398
  }
377
399
  case "pi": {
378
400
  assertPiRuntimeSupported();
379
- const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-XLY46UDL.js");
401
+ const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-WOVSWBGG.js");
380
402
  return new PiCodingAgentAdapter(
381
403
  engine.agentDirectory === void 0 ? {} : { agentDirectory: resolve(engine.agentDirectory) }
382
404
  );
383
405
  }
384
406
  case "codex": {
385
- const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-CXD4SVCE.js");
407
+ const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-2W7RRER3.js");
386
408
  return new CodexCodingAgentAdapter({
387
409
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
388
410
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
@@ -391,15 +413,16 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
391
413
  });
392
414
  }
393
415
  case "claude": {
394
- const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-GCH36EZ6.js");
416
+ const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-DGZBZSWJ.js");
395
417
  return new ClaudeCodingAgentAdapter({
396
418
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
419
+ ...engine.command === void 0 ? {} : { command: engine.command },
397
420
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
398
421
  ...onDiagnostic === void 0 ? {} : { onDiagnostic }
399
422
  });
400
423
  }
401
424
  case "acp": {
402
- const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-WYDK3PLS.js");
425
+ const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-OGD5QSNI.js");
403
426
  return new AcpCodingAgentAdapter({
404
427
  command: engine.command,
405
428
  args: engine.args,
@@ -524,7 +547,7 @@ async function loadOrCreateContentKey(dataDirectory) {
524
547
  await rename(temporaryPath, path);
525
548
  return material;
526
549
  }
527
- async function createPersistentContentCipher(dataDirectory, key) {
550
+ async function createPersistentContentCipher(dataDirectory, key, options = {}) {
528
551
  await mkdir(dataDirectory, { recursive: true });
529
552
  const path = join(dataDirectory, "content-replay.log");
530
553
  let processedMessages = /* @__PURE__ */ new Map();
@@ -536,10 +559,12 @@ async function createPersistentContentCipher(dataDirectory, key) {
536
559
  compactOnNextWrite = entries.some((entry) => entry.keyId !== key.keyId);
537
560
  for (const entry of entries) {
538
561
  if (entry.keyId === key.keyId) {
562
+ if (options.rejectReplayOverflow && entry.sentAt < Date.now() - DEFAULT_REPLAY_WINDOW_MS) continue;
539
563
  processedMessages.set(entry.messageId, entry.sentAt);
540
564
  }
541
565
  }
542
566
  while (processedMessages.size > MAX_REPLAY_ENTRIES) {
567
+ if (options.rejectReplayOverflow) throw new Error("Encrypted replay journal exceeds its capacity");
543
568
  const oldest = processedMessages.keys().next().value;
544
569
  if (oldest === void 0) {
545
570
  break;
@@ -553,6 +578,7 @@ async function createPersistentContentCipher(dataDirectory, key) {
553
578
  }
554
579
  let writesSinceCompaction = 0;
555
580
  return new ContentCipher(key, {
581
+ ...options,
556
582
  processedMessages,
557
583
  persistProcessedMessages: (entries) => {
558
584
  const newest = [...entries].at(-1);
@@ -618,6 +644,7 @@ var ContentCipher = class {
618
644
  #randomBytes;
619
645
  #createMessageId;
620
646
  #replayWindowMs;
647
+ #rejectReplayOverflow;
621
648
  #processedMessages;
622
649
  #persistProcessedMessages;
623
650
  constructor(key, options = {}) {
@@ -626,6 +653,7 @@ var ContentCipher = class {
626
653
  this.#randomBytes = options.randomBytes ?? randomBytes;
627
654
  this.#createMessageId = options.createMessageId ?? randomUUID;
628
655
  this.#replayWindowMs = options.replayWindowMs ?? DEFAULT_REPLAY_WINDOW_MS;
656
+ this.#rejectReplayOverflow = options.rejectReplayOverflow === true;
629
657
  this.#processedMessages = new Map(options.processedMessages);
630
658
  this.#persistProcessedMessages = options.persistProcessedMessages;
631
659
  }
@@ -730,6 +758,9 @@ var ContentCipher = class {
730
758
  });
731
759
  }
732
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
+ }
733
764
  while (activeReplayEntries.size >= MAX_REPLAY_ENTRIES) {
734
765
  const oldest = activeReplayEntries.keys().next().value;
735
766
  if (oldest === void 0) {
@@ -943,163 +974,18 @@ var ApprovedPairingProvider = class extends CachedPairingProvider {
943
974
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
944
975
 
945
976
  // src/research-tools.ts
946
- import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
947
- import { lstat as lstat3, realpath as realpath3, stat as stat3 } from "node:fs/promises";
948
- import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
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";
949
980
  import { gunzipSync } from "node:zlib";
950
981
  import { z as z4 } from "zod";
951
982
 
952
- // src/session-directory.ts
953
- import { createHash as createHash2 } from "node:crypto";
954
- import { lstat, opendir, realpath, stat } from "node:fs/promises";
955
- import { isAbsolute, join as join2, relative, sep } from "node:path";
956
- var SESSION_DIRECTORY_CONCURRENCY = 4;
957
- var SESSION_DIRECTORY_TIMEOUT_MS = 5e3;
958
- var SessionDirectoryError = class extends Error {
959
- constructor(code, message, options) {
960
- super(message, options);
961
- this.code = code;
962
- }
963
- code;
964
- };
965
- function fail(code, message) {
966
- throw new SessionDirectoryError(code, message);
967
- }
968
- function contained(root, candidate) {
969
- const path = relative(root, candidate);
970
- return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
971
- }
972
- function sessionRootIdentity(root, info) {
973
- return `${root}\0${info.dev}\0${info.ino}`;
974
- }
975
- var SessionDirectoryLister = class {
976
- constructor(metadata) {
977
- this.metadata = metadata;
978
- }
979
- metadata;
980
- #active = 0;
981
- async list(sessionId, path) {
982
- if (!isSafeSessionDirectoryPath(path)) {
983
- fail("INVALID_DIRECTORY_PATH", "The directory path is not allowed");
984
- }
985
- if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) {
986
- fail("DIRECTORY_BUSY", "Too many directory requests");
987
- }
988
- this.#active++;
989
- const deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
990
- const checkDeadline = () => {
991
- if (Date.now() >= deadline) fail("DIRECTORY_TIMEOUT", "The directory request timed out");
992
- };
993
- const work = this.#list(sessionId, path, checkDeadline).finally(() => {
994
- this.#active--;
995
- });
996
- let timer;
997
- try {
998
- return await Promise.race([
999
- work,
1000
- new Promise((_, reject) => {
1001
- timer = setTimeout(() => reject(new SessionDirectoryError(
1002
- "DIRECTORY_TIMEOUT",
1003
- "The directory request timed out"
1004
- )), SESSION_DIRECTORY_TIMEOUT_MS);
1005
- })
1006
- ]);
1007
- } catch (error) {
1008
- if (error instanceof SessionDirectoryError) throw error;
1009
- throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "The directory is unavailable", { cause: error });
1010
- } finally {
1011
- clearTimeout(timer);
1012
- }
1013
- }
1014
- async #list(sessionId, path, checkDeadline) {
1015
- const metadata = await this.metadata(sessionId);
1016
- checkDeadline();
1017
- if (metadata === void 0) fail("SESSION_NOT_FOUND", "The session is unavailable");
1018
- const workingDirectory = metadata.workingDirectory;
1019
- if (!workingDirectory || !isAbsolute(workingDirectory)) {
1020
- fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1021
- }
1022
- let root;
1023
- let rootIdentity;
1024
- try {
1025
- root = await realpath(workingDirectory);
1026
- const info = await stat(root, { bigint: true });
1027
- if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1028
- rootIdentity = sessionRootIdentity(root, info);
1029
- } catch (error) {
1030
- throw new SessionDirectoryError(
1031
- "SESSION_ROOT_UNAVAILABLE",
1032
- "The session working directory is unavailable",
1033
- { cause: error }
1034
- );
1035
- }
1036
- checkDeadline();
1037
- let target = root;
1038
- for (const segment of path === "" ? [] : path.split("/")) {
1039
- target = join2(target, segment);
1040
- const info = await lstat(target);
1041
- checkDeadline();
1042
- if (info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be opened");
1043
- if (!info.isDirectory()) fail("NOT_A_DIRECTORY", "The selected entry is not a directory");
1044
- if (!contained(root, await realpath(target))) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1045
- checkDeadline();
1046
- }
1047
- const canonicalTarget = await realpath(target);
1048
- if (!contained(root, canonicalTarget)) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1049
- checkDeadline();
1050
- const directory = await opendir(target, { bufferSize: 32 });
1051
- const entries = [];
1052
- let bytes = 8192;
1053
- try {
1054
- checkDeadline();
1055
- for (; ; ) {
1056
- const entry = await directory.read();
1057
- checkDeadline();
1058
- if (entry === null) break;
1059
- if (entries.length >= SESSION_DIRECTORY_MAX_ENTRIES) {
1060
- fail("DIRECTORY_LIMIT_EXCEEDED", "The directory has too many entries");
1061
- }
1062
- let kind = "blocked";
1063
- if (isSafeSessionDirectoryPath(entry.name) && !entry.name.includes("/")) {
1064
- const child = join2(target, entry.name);
1065
- const info = await lstat(child);
1066
- checkDeadline();
1067
- if (!info.isSymbolicLink() && contained(root, await realpath(child))) {
1068
- kind = info.isDirectory() ? "directory" : info.isFile() ? "file" : "blocked";
1069
- }
1070
- }
1071
- const result = { name: entry.name, kind };
1072
- bytes += Buffer.byteLength(JSON.stringify(result), "utf8") + 1;
1073
- if (bytes > SESSION_DIRECTORY_MAX_RESPONSE_BYTES) {
1074
- fail("DIRECTORY_LIMIT_EXCEEDED", "The directory listing is too large");
1075
- }
1076
- entries.push(result);
1077
- }
1078
- const latestMetadata = await this.metadata(sessionId);
1079
- const latestRoot = await realpath(workingDirectory);
1080
- const latestInfo = await stat(latestRoot, { bigint: true });
1081
- if (latestMetadata?.workingDirectory !== workingDirectory || sessionRootIdentity(latestRoot, latestInfo) !== rootIdentity || await realpath(target) !== canonicalTarget) {
1082
- fail("SESSION_ROOT_CHANGED", "The session directory changed");
1083
- }
1084
- checkDeadline();
1085
- } finally {
1086
- await directory.close();
1087
- }
1088
- const order = { directory: 0, file: 1, blocked: 2 };
1089
- entries.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
1090
- return {
1091
- rootRevision: createHash2("sha256").update(rootIdentity).digest("base64url"),
1092
- entries
1093
- };
1094
- }
1095
- };
1096
-
1097
983
  // src/session-file.ts
1098
984
  import { isUtf8 } from "node:buffer";
1099
- import { createHash as createHash3 } from "node:crypto";
985
+ import { createHash as createHash2 } from "node:crypto";
1100
986
  import { constants as constants2 } from "node:fs";
1101
- import { lstat as lstat2, open, realpath as realpath2, stat as stat2 } from "node:fs/promises";
1102
- import { extname, isAbsolute as isAbsolute2, join as join3 } from "node:path";
987
+ import { lstat, open, realpath, stat } from "node:fs/promises";
988
+ import { extname, isAbsolute, join as join2 } from "node:path";
1103
989
  import { promisify } from "node:util";
1104
990
  import { gzip } from "node:zlib";
1105
991
 
@@ -1258,7 +1144,7 @@ var SessionFileReadError = class extends Error {
1258
1144
  }
1259
1145
  code;
1260
1146
  };
1261
- function fail2(code) {
1147
+ function fail(code) {
1262
1148
  throw new SessionFileReadError(code);
1263
1149
  }
1264
1150
  function fileIdentity(info, includeChangeTime = true) {
@@ -1296,9 +1182,9 @@ function isPreviewableText(bytes) {
1296
1182
  function rejectAnimatedPng(bytes) {
1297
1183
  for (let offset = 8; offset + 12 <= bytes.length; ) {
1298
1184
  const size = bytes.readUInt32BE(offset);
1299
- if (size > bytes.length - offset - 12) fail2("FILE_UNSUPPORTED");
1185
+ if (size > bytes.length - offset - 12) fail("FILE_UNSUPPORTED");
1300
1186
  const type = bytes.toString("ascii", offset + 4, offset + 8);
1301
- if (type === "acTL") fail2("FILE_UNSUPPORTED");
1187
+ if (type === "acTL") fail("FILE_UNSUPPORTED");
1302
1188
  offset += size + 12;
1303
1189
  if (type === "IEND") break;
1304
1190
  }
@@ -1311,14 +1197,14 @@ async function imagePreview(bytes, extension, checkDeadline) {
1311
1197
  const metadata = await sharp(bytes, options).metadata();
1312
1198
  checkDeadline();
1313
1199
  const expected = extension === ".png" ? "png" : extension === ".webp" ? "webp" : "jpeg";
1314
- if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_FILE_MAX_IMAGE_PIXELS) fail2("FILE_UNSUPPORTED");
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");
1315
1201
  if (metadata.format === "png") rejectAnimatedPng(bytes);
1316
1202
  for (const [edge, quality] of [[SESSION_FILE_MAX_IMAGE_EDGE, 75], [1024, 60], [768, 45], [512, 30]]) {
1317
1203
  const result = await sharp(bytes, options).rotate().resize({ width: edge, height: edge, fit: "inside", withoutEnlargement: true }).webp({ quality, effort: 3 }).toBuffer();
1318
1204
  checkDeadline();
1319
1205
  if (result.length <= SESSION_FILE_MAX_IMAGE_BYTES) return result;
1320
1206
  }
1321
- return fail2("FILE_TOO_LARGE");
1207
+ return fail("FILE_TOO_LARGE");
1322
1208
  } catch (error) {
1323
1209
  if (error instanceof SessionFileReadError) throw error;
1324
1210
  throw new SessionFileReadError("FILE_UNSUPPORTED", { cause: error });
@@ -1339,7 +1225,7 @@ function resourceMediaType(extension) {
1339
1225
  case ".mjs":
1340
1226
  return "text/javascript";
1341
1227
  default:
1342
- return fail2("FILE_UNSUPPORTED");
1228
+ return fail("FILE_UNSUPPORTED");
1343
1229
  }
1344
1230
  }
1345
1231
  async function validateRawImage(bytes, extension, checkDeadline) {
@@ -1350,37 +1236,37 @@ async function validateRawImage(bytes, extension, checkDeadline) {
1350
1236
  const metadata = await sharp(bytes, options).metadata();
1351
1237
  checkDeadline();
1352
1238
  const expected = extension === ".png" ? "png" : extension === ".webp" ? "webp" : "jpeg";
1353
- if (metadata.format !== expected || (metadata.pages ?? 1) !== 1 || !metadata.width || !metadata.height || metadata.width * metadata.height > SESSION_RESOURCE_MAX_IMAGE_PIXELS) fail2("FILE_UNSUPPORTED");
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");
1354
1240
  if (expected === "png") {
1355
1241
  rejectAnimatedPng(bytes);
1356
1242
  let offset = 8;
1357
1243
  let ended = false;
1358
1244
  while (offset + 12 <= bytes.length) {
1359
1245
  const size = bytes.readUInt32BE(offset);
1360
- if (size > bytes.length - offset - 12) fail2("FILE_UNSUPPORTED");
1246
+ if (size > bytes.length - offset - 12) fail("FILE_UNSUPPORTED");
1361
1247
  const type = bytes.toString("ascii", offset + 4, offset + 8);
1362
- if (type === "fcTL" || type === "fdAT") fail2("FILE_UNSUPPORTED");
1248
+ if (type === "fcTL" || type === "fdAT") fail("FILE_UNSUPPORTED");
1363
1249
  offset += size + 12;
1364
1250
  if (type === "IEND") {
1365
1251
  ended = size === 0;
1366
1252
  break;
1367
1253
  }
1368
1254
  }
1369
- if (!ended || offset !== bytes.length) fail2("FILE_UNSUPPORTED");
1255
+ if (!ended || offset !== bytes.length) fail("FILE_UNSUPPORTED");
1370
1256
  }
1371
1257
  if (expected === "jpeg" && (bytes.length < 4 || bytes.readUInt16BE(bytes.length - 2) !== 65497)) {
1372
- fail2("FILE_UNSUPPORTED");
1258
+ fail("FILE_UNSUPPORTED");
1373
1259
  }
1374
1260
  if (expected === "webp") {
1375
- if (bytes.length < 20 || bytes.readUInt32LE(4) !== bytes.length - 8) fail2("FILE_UNSUPPORTED");
1261
+ if (bytes.length < 20 || bytes.readUInt32LE(4) !== bytes.length - 8) fail("FILE_UNSUPPORTED");
1376
1262
  let offset = 12;
1377
1263
  while (offset + 8 <= bytes.length) {
1378
1264
  const type = bytes.toString("ascii", offset, offset + 4);
1379
1265
  const size = bytes.readUInt32LE(offset + 4);
1380
- if (size > bytes.length - offset - 8 || type === "ANIM" || type === "ANMF" || type === "VP8X" && (size !== 10 || (bytes[offset + 8] & 2) !== 0)) fail2("FILE_UNSUPPORTED");
1266
+ if (size > bytes.length - offset - 8 || type === "ANIM" || type === "ANMF" || type === "VP8X" && (size !== 10 || (bytes[offset + 8] & 2) !== 0)) fail("FILE_UNSUPPORTED");
1381
1267
  offset += 8 + size + (size & 1);
1382
1268
  }
1383
- if (offset !== bytes.length) fail2("FILE_UNSUPPORTED");
1269
+ if (offset !== bytes.length) fail("FILE_UNSUPPORTED");
1384
1270
  }
1385
1271
  await sharp(bytes, options).stats();
1386
1272
  checkDeadline();
@@ -1395,32 +1281,32 @@ var SessionFileReader = class {
1395
1281
  }
1396
1282
  metadata;
1397
1283
  #active = 0;
1398
- async read(sessionId, path, rootRevision, version = SESSION_FILE_READ_VERSION) {
1399
- if (version !== SESSION_FILE_READ_VERSION && version !== SESSION_FILE_READ_V2_VERSION) fail2("UNSUPPORTED_OPERATION_VERSION");
1400
- if (!SessionFileReadDataSchema.safeParse({ path, rootRevision }).success) fail2("INVALID_FILE_PATH");
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");
1401
1287
  const schema = version === SESSION_FILE_READ_V2_VERSION ? SessionFileReadV2ResultDataSchema : SessionFileReadResultDataSchema;
1402
1288
  return schema.parse(await this.#run(
1403
- (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "preview", version)
1289
+ (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "preview", version, space)
1404
1290
  ));
1405
1291
  }
1406
- async readResource(sessionId, path, rootRevision) {
1407
- if (!SessionResourceReadDataSchema.safeParse({ path, rootRevision }).success) fail2("INVALID_FILE_PATH");
1292
+ async readResource(sessionId, path, rootRevision, space) {
1293
+ if (!SessionResourceReadDataSchema.safeParse({ path, rootRevision }).success) fail("INVALID_FILE_PATH");
1408
1294
  return SessionResourceReadResultDataSchema.parse(await this.#run(
1409
- (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "resource")
1295
+ (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "resource", SESSION_FILE_READ_VERSION, space)
1410
1296
  ));
1411
1297
  }
1412
- async download(sessionId, path, rootRevision) {
1413
- if (!SessionFileDownloadDataSchema.safeParse({ path, rootRevision }).success) fail2("INVALID_FILE_PATH");
1298
+ async download(sessionId, path, rootRevision, space) {
1299
+ if (!SessionFileDownloadDataSchema.safeParse({ path, rootRevision }).success) fail("INVALID_FILE_PATH");
1414
1300
  return SessionFileDownloadResultDataSchema.parse(await this.#run(
1415
- (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "download")
1301
+ (checkDeadline) => this.#read(sessionId, path, rootRevision, checkDeadline, "download", SESSION_FILE_READ_VERSION, space)
1416
1302
  ));
1417
1303
  }
1418
1304
  async #run(read) {
1419
- if (this.#active >= SESSION_FILE_CONCURRENCY) fail2("FILE_BUSY");
1305
+ if (this.#active >= SESSION_FILE_CONCURRENCY) fail("FILE_BUSY");
1420
1306
  this.#active++;
1421
1307
  const deadline = Date.now() + SESSION_FILE_TIMEOUT_MS;
1422
1308
  const checkDeadline = () => {
1423
- if (Date.now() >= deadline) fail2("FILE_TIMEOUT");
1309
+ if (Date.now() >= deadline) fail("FILE_TIMEOUT");
1424
1310
  };
1425
1311
  const work = read(checkDeadline).finally(() => {
1426
1312
  this.#active--;
@@ -1440,59 +1326,59 @@ var SessionFileReader = class {
1440
1326
  clearTimeout(timer);
1441
1327
  }
1442
1328
  }
1443
- 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) {
1444
1330
  const resource = mode === "resource";
1445
1331
  const download = mode === "download";
1446
1332
  const metadata = await this.metadata(sessionId);
1447
1333
  checkDeadline();
1448
- if (metadata === void 0) fail2("SESSION_NOT_FOUND");
1449
- const workingDirectory = metadata.workingDirectory;
1450
- if (!workingDirectory || !isAbsolute2(workingDirectory)) fail2("SESSION_ROOT_UNAVAILABLE");
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");
1451
1337
  let root;
1452
1338
  let rootIdentity;
1453
1339
  try {
1454
- if ((await lstat2(workingDirectory)).isSymbolicLink()) fail2("FILE_UNAVAILABLE");
1455
- root = await realpath2(workingDirectory);
1456
- const info = await stat2(root, { bigint: true });
1457
- if (!info.isDirectory()) fail2("SESSION_ROOT_UNAVAILABLE");
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");
1458
1344
  rootIdentity = sessionRootIdentity(root, info);
1459
1345
  } catch (error) {
1460
1346
  if (error instanceof SessionFileReadError) throw error;
1461
1347
  throw new SessionFileReadError("SESSION_ROOT_UNAVAILABLE", { cause: error });
1462
1348
  }
1463
- if (createHash3("sha256").update(rootIdentity).digest("base64url") !== rootRevision) fail2("SESSION_ROOT_CHANGED");
1349
+ if (createHash2("sha256").update(rootIdentity).digest("base64url") !== rootRevision) fail("SESSION_ROOT_CHANGED");
1464
1350
  checkDeadline();
1465
- const target = join3(root, ...path.split("/"));
1351
+ const target = join2(root, ...path.split("/"));
1466
1352
  const inspectPath = async () => {
1467
1353
  let current = root;
1468
1354
  const segments = path.split("/");
1469
1355
  let file;
1470
1356
  for (const [index, segment] of segments.entries()) {
1471
- current = join3(current, segment);
1472
- const info = await lstat2(current, { bigint: true });
1357
+ current = join2(current, segment);
1358
+ const info = await lstat(current, { bigint: true });
1473
1359
  checkDeadline();
1474
1360
  if (info.isSymbolicLink() || (index === segments.length - 1 ? !info.isFile() : !info.isDirectory())) {
1475
- fail2("FILE_UNAVAILABLE");
1361
+ fail("FILE_UNAVAILABLE");
1476
1362
  }
1477
- const canonical = await realpath2(current);
1363
+ const canonical = await realpath(current);
1478
1364
  const samePath2 = canonical === current || resource && process.platform === "win32" && canonical.toLowerCase() === current.toLowerCase();
1479
- if (!contained(root, canonical) || !samePath2) fail2("FILE_UNAVAILABLE");
1365
+ if (!contained(root, canonical) || !samePath2) fail("FILE_UNAVAILABLE");
1480
1366
  checkDeadline();
1481
1367
  file = info;
1482
1368
  }
1483
- if (file === void 0) fail2("INVALID_FILE_PATH");
1369
+ if (file === void 0) fail("INVALID_FILE_PATH");
1484
1370
  return file;
1485
1371
  };
1486
1372
  const before = await inspectPath();
1487
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;
1488
- if (before.size > BigInt(maxOriginalBytes)) fail2("FILE_TOO_LARGE");
1374
+ if (before.size > BigInt(maxOriginalBytes)) fail("FILE_TOO_LARGE");
1489
1375
  const extension = extname(path).toLowerCase();
1490
1376
  const resourceType = resource ? resourceMediaType(extension) : void 0;
1491
1377
  const handle = await open(target, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0));
1492
1378
  try {
1493
1379
  const opened = await handle.stat({ bigint: true });
1494
1380
  const includeChangeTime = process.platform !== "win32";
1495
- if (!opened.isFile() || fileIdentity(opened, includeChangeTime) !== fileIdentity(before, includeChangeTime)) fail2("FILE_CHANGED");
1381
+ if (!opened.isFile() || fileIdentity(opened, includeChangeTime) !== fileIdentity(before, includeChangeTime)) fail("FILE_CHANGED");
1496
1382
  const originalByteLength = Number(before.size);
1497
1383
  const readOriginal = async () => {
1498
1384
  const original = Buffer.alloc(originalByteLength + 1);
@@ -1503,7 +1389,7 @@ var SessionFileReader = class {
1503
1389
  if (bytesRead === 0) break;
1504
1390
  offset += bytesRead;
1505
1391
  }
1506
- if (offset !== originalByteLength) fail2("FILE_CHANGED");
1392
+ if (offset !== originalByteLength) fail("FILE_CHANGED");
1507
1393
  return original.subarray(0, originalByteLength);
1508
1394
  };
1509
1395
  const bytes = await readOriginal();
@@ -1516,7 +1402,7 @@ var SessionFileReader = class {
1516
1402
  mediaType = resourceType;
1517
1403
  if (resourceType.startsWith("image/")) {
1518
1404
  await validateRawImage(bytes, extension, checkDeadline);
1519
- } else if (!isPreviewableText(bytes)) fail2("FILE_UNSUPPORTED");
1405
+ } else if (!isPreviewableText(bytes)) fail("FILE_UNSUPPORTED");
1520
1406
  canonical = bytes;
1521
1407
  } else if (isPreviewableText(bytes)) {
1522
1408
  mediaType = textMediaType(path);
@@ -1539,7 +1425,7 @@ var SessionFileReader = class {
1539
1425
  mediaType = "image/webp";
1540
1426
  canonical = await imagePreview(bytes, `.${detected.ext}`, checkDeadline);
1541
1427
  } else if (detected?.mime === "video/mp4" || detected?.mime === "video/webm") {
1542
- if (version !== SESSION_FILE_READ_V2_VERSION || extension !== (detected.mime === "video/mp4" ? ".mp4" : ".webm")) fail2("FILE_UNSUPPORTED");
1428
+ if (version !== SESSION_FILE_READ_V2_VERSION || extension !== (detected.mime === "video/mp4" ? ".mp4" : ".webm")) fail("FILE_UNSUPPORTED");
1543
1429
  mediaType = detected.mime;
1544
1430
  try {
1545
1431
  validateSessionVideo(bytes, mediaType);
@@ -1547,7 +1433,7 @@ var SessionFileReader = class {
1547
1433
  throw new SessionFileReadError("FILE_UNSUPPORTED", { cause: error });
1548
1434
  }
1549
1435
  canonical = bytes;
1550
- } else fail2("FILE_UNSUPPORTED");
1436
+ } else fail("FILE_UNSUPPORTED");
1551
1437
  }
1552
1438
  const threshold = resource ? SESSION_RESOURCE_GZIP_THRESHOLD_BYTES : SESSION_FILE_GZIP_THRESHOLD_BYTES;
1553
1439
  const encoding = originalByteLength >= threshold ? "gzip" : "identity";
@@ -1555,17 +1441,17 @@ var SessionFileReader = class {
1555
1441
  const latestMetadata = await this.metadata(sessionId);
1556
1442
  checkDeadline();
1557
1443
  try {
1558
- const latestRoot = await realpath2(workingDirectory);
1559
- const latestRootInfo = await stat2(latestRoot, { bigint: true });
1560
- if (latestMetadata?.workingDirectory !== workingDirectory || (await lstat2(workingDirectory)).isSymbolicLink() || sessionRootIdentity(latestRoot, latestRootInfo) !== rootIdentity) fail2("SESSION_ROOT_CHANGED");
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");
1561
1447
  } catch (error) {
1562
1448
  if (error instanceof SessionFileReadError) throw error;
1563
1449
  throw new SessionFileReadError("SESSION_ROOT_CHANGED", { cause: error });
1564
1450
  }
1565
1451
  try {
1566
1452
  const latest = await inspectPath();
1567
- if (fileIdentity(latest, includeChangeTime) !== fileIdentity(opened, includeChangeTime) || !includeChangeTime && !(await readOriginal()).equals(bytes)) fail2("FILE_CHANGED");
1568
- if (fileIdentity(await handle.stat({ bigint: true }), includeChangeTime) !== fileIdentity(latest, includeChangeTime)) fail2("FILE_CHANGED");
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");
1569
1455
  } catch (error) {
1570
1456
  if (error instanceof SessionFileReadError && error.code === "FILE_TIMEOUT") throw error;
1571
1457
  throw new SessionFileReadError("FILE_CHANGED", { cause: error });
@@ -1897,6 +1783,15 @@ function createWorkbenchOperations(options) {
1897
1783
  route("context.compact", WorkbenchSubmitRequestSchema, (data, request2) => submit(request2, data, async () => output(WorkbenchCompactResultSchema, await runtime.compact(request2.sessionId))))
1898
1784
  );
1899
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
+ }
1900
1795
  if (runtime?.analytics !== void 0) {
1901
1796
  const analytics = runtime.analytics.bind(runtime);
1902
1797
  routes.push(route("analytics.read", SessionAnalyticsRequestSchema, async (data, request2) => output(SessionAnalyticsResultSchema, await analytics(request2.sessionId, data))));
@@ -1944,15 +1839,15 @@ var ResearchError = class extends Error {
1944
1839
  code;
1945
1840
  };
1946
1841
  async function researchRoot(workingDirectory) {
1947
- if (!isAbsolute3(workingDirectory)) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
1842
+ if (!isAbsolute2(workingDirectory)) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
1948
1843
  try {
1949
- if ((await lstat3(workingDirectory)).isSymbolicLink()) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
1950
- const root = await realpath3(workingDirectory);
1951
- const info = await stat3(root, { bigint: true });
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 });
1952
1847
  if (!info.isDirectory()) throw new ResearchError("SESSION_ROOT_UNAVAILABLE");
1953
1848
  return {
1954
1849
  workingDirectory: root,
1955
- rootIdentity: createHash4("sha256").update(sessionRootIdentity(root, info)).digest("base64url")
1850
+ rootIdentity: createHash3("sha256").update(sessionRootIdentity(root, info)).digest("base64url")
1956
1851
  };
1957
1852
  } catch (error) {
1958
1853
  if (error instanceof ResearchError) throw error;
@@ -2066,7 +1961,7 @@ var ResearchTools = class {
2066
1961
  }
2067
1962
  async #validate(path) {
2068
1963
  const source = await this.#source();
2069
- const target = join4(this.root.workingDirectory, ...path.split("/"));
1964
+ const target = join3(this.root.workingDirectory, ...path.split("/"));
2070
1965
  if (sensitiveSegments(this.root.workingDirectory.split(/[\\/]/u)) || !allowedPath(path, source.excludedPaths ?? []) || this.privateDirectories.some((directory) => contained(directory, target))) {
2071
1966
  throw new ResearchError("RESEARCH_PATH_BLOCKED", "The requested path is excluded from research");
2072
1967
  }
@@ -2111,7 +2006,7 @@ var ResearchTools = class {
2111
2006
  const source = await this.#source();
2112
2007
  return result.entries.filter((entry) => {
2113
2008
  const child = path ? `${path}/${entry.name}` : entry.name;
2114
- return entry.kind !== "blocked" && allowedPath(child, source.excludedPaths ?? []) && !this.privateDirectories.some((directory) => contained(directory, join4(this.root.workingDirectory, ...child.split("/"))));
2009
+ return entry.kind !== "blocked" && allowedPath(child, source.excludedPaths ?? []) && !this.privateDirectories.some((directory) => contained(directory, join3(this.root.workingDirectory, ...child.split("/"))));
2115
2010
  });
2116
2011
  }
2117
2012
  async list(input) {
@@ -2153,7 +2048,7 @@ var ResearchTools = class {
2153
2048
  return {
2154
2049
  text: bytes.toString("utf8"),
2155
2050
  bytes: bytes.length,
2156
- version: createHash4("sha256").update(bytes).digest("base64url")
2051
+ version: createHash3("sha256").update(bytes).digest("base64url")
2157
2052
  };
2158
2053
  }
2159
2054
  async read(input) {
@@ -2211,8 +2106,8 @@ var ResearchTools = class {
2211
2106
  if (path === void 0) break;
2212
2107
  inspected++;
2213
2108
  await this.#validate(path);
2214
- const target = join4(this.root.workingDirectory, ...path.split("/"));
2215
- const info = await lstat3(target);
2109
+ const target = join3(this.root.workingDirectory, ...path.split("/"));
2110
+ const info = await lstat2(target);
2216
2111
  if (info.isSymbolicLink()) {
2217
2112
  skippedFiles++;
2218
2113
  continue;
@@ -2444,8 +2339,9 @@ function researchAwareCodingAgentAdapter(inner, research) {
2444
2339
  }
2445
2340
 
2446
2341
  // src/pc-agent.ts
2447
- import { randomUUID as randomUUID9 } from "node:crypto";
2342
+ import { createHash as createHash16, randomUUID as randomUUID11 } from "node:crypto";
2448
2343
  import { platform as platform2 } from "node:os";
2344
+ import { join as join12 } from "node:path";
2449
2345
  import { performance as performance5 } from "node:perf_hooks";
2450
2346
 
2451
2347
  // ../node/dist/index.js
@@ -2574,8 +2470,8 @@ var AuthorizedRelaySocket = class {
2574
2470
 
2575
2471
  // src/service/requests/session-communication.ts
2576
2472
  import { AsyncLocalStorage } from "node:async_hooks";
2577
- import { createHash as createHash7 } from "node:crypto";
2578
- import { join as join6 } from "node:path";
2473
+ import { createHash as createHash6 } from "node:crypto";
2474
+ import { join as join5 } from "node:path";
2579
2475
  import { performance as performance2 } from "node:perf_hooks";
2580
2476
 
2581
2477
  // src/repeated-error-diagnostics.ts
@@ -2847,10 +2743,10 @@ import { constants as constants4, gzip as gzip3 } from "node:zlib";
2847
2743
 
2848
2744
  // src/session-git-diff.ts
2849
2745
  import { execFile } from "node:child_process";
2850
- import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
2746
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
2851
2747
  import { constants as constants3 } from "node:fs";
2852
- import { chmod, lstat as lstat4, mkdir as mkdir2, open as open2, readlink, realpath as realpath4, rm, stat as stat4, writeFile as writeFile2 } from "node:fs/promises";
2853
- import { dirname, isAbsolute as isAbsolute4, join as join5, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
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";
2854
2750
 
2855
2751
  // src/git-repository-error.ts
2856
2752
  function isGitRepositoryUnavailableError(error) {
@@ -2874,7 +2770,7 @@ var SessionGitDiffError = class extends Error {
2874
2770
  }
2875
2771
  code;
2876
2772
  };
2877
- function fail3(code, message) {
2773
+ function fail2(code, message) {
2878
2774
  throw new SessionGitDiffError(code, message);
2879
2775
  }
2880
2776
  function fileError(error) {
@@ -2900,10 +2796,10 @@ async function forFile(path, work, operation) {
2900
2796
  }
2901
2797
  }
2902
2798
  function changed() {
2903
- return fail3("DIFF_CHANGED", "The project diff changed; refresh the changed-file list");
2799
+ return fail2("DIFF_CHANGED", "The project diff changed; refresh the changed-file list");
2904
2800
  }
2905
2801
  function limit() {
2906
- return fail3("DIFF_LIMIT_EXCEEDED", "The project diff is too large");
2802
+ return fail2("DIFF_LIMIT_EXCEEDED", "The project diff is too large");
2907
2803
  }
2908
2804
  function samePath(a, b) {
2909
2805
  return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
@@ -2969,7 +2865,7 @@ var Work = class {
2969
2865
  const drivers = /* @__PURE__ */ new Set();
2970
2866
  for (const name of names) {
2971
2867
  const match = /^filter\.([^=\r\n]+)\.[^.]+$/u.exec(name);
2972
- if (!match?.[1]) fail3("DIFF_BLOCKED", "The project contains an unsupported filter configuration");
2868
+ if (!match?.[1]) fail2("DIFF_BLOCKED", "The project contains an unsupported filter configuration");
2973
2869
  drivers.add(match[1]);
2974
2870
  }
2975
2871
  this.#filterConfig = [...drivers].flatMap((name) => [
@@ -2983,7 +2879,7 @@ var Work = class {
2983
2879
  if (this.#filterConfig.join(" ").length > 16384) limit();
2984
2880
  }
2985
2881
  check() {
2986
- if (Date.now() >= this.deadline) fail3("DIFF_TIMEOUT", "The project diff request timed out");
2882
+ if (Date.now() >= this.deadline) fail2("DIFF_TIMEOUT", "The project diff request timed out");
2987
2883
  }
2988
2884
  async git(cwd, args, options = {}) {
2989
2885
  this.check();
@@ -3007,10 +2903,10 @@ var Work = class {
3007
2903
  ...this.env,
3008
2904
  ...options.objectDirectory === void 0 ? {} : { GIT_OBJECT_DIRECTORY: options.objectDirectory },
3009
2905
  ...options.isolated ? {
3010
- GIT_DIR: join5(cwd, "no-repository"),
2906
+ GIT_DIR: join4(cwd, "no-repository"),
3011
2907
  GIT_CONFIG_NOSYSTEM: "1",
3012
2908
  GIT_ATTR_NOSYSTEM: "1",
3013
- GIT_CONFIG_GLOBAL: join5(cwd, "gitconfig")
2909
+ GIT_CONFIG_GLOBAL: join4(cwd, "gitconfig")
3014
2910
  } : {}
3015
2911
  }
3016
2912
  }, (error, output2, stderr) => {
@@ -3034,14 +2930,14 @@ function identity(info) {
3034
2930
  return `${info.dev}\0${info.ino}\0${info.size}\0${info.mtimeNs}\0${info.mode}\0${info.nlink}`;
3035
2931
  }
3036
2932
  async function inspect(root, path, work, kind = "file") {
3037
- if (!safePath(path)) fail3("DIFF_BLOCKED", "The selected path cannot be compared");
2933
+ if (!safePath(path)) fail2("DIFF_BLOCKED", "The selected path cannot be compared");
3038
2934
  let current = root;
3039
2935
  const segments = path.split("/");
3040
2936
  for (const [index, segment] of segments.entries()) {
3041
- current = join5(current, segment);
2937
+ current = join4(current, segment);
3042
2938
  let info;
3043
2939
  try {
3044
- info = await lstat4(current, { bigint: true });
2940
+ info = await lstat3(current, { bigint: true });
3045
2941
  } catch (error) {
3046
2942
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
3047
2943
  throw error;
@@ -3050,11 +2946,11 @@ async function inspect(root, path, work, kind = "file") {
3050
2946
  const last = index === segments.length - 1;
3051
2947
  if (last && kind === "link" && info.isSymbolicLink()) return info;
3052
2948
  if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) {
3053
- fail3("DIFF_BLOCKED", "Links, submodules and special files cannot be compared");
2949
+ fail2("DIFF_BLOCKED", "Links, submodules and special files cannot be compared");
3054
2950
  }
3055
- const canonical = await realpath4(current);
2951
+ const canonical = await realpath3(current);
3056
2952
  if (!contained(root, canonical) || !samePath(canonical, current)) {
3057
- fail3("DIFF_BLOCKED", "The selected path is outside the session");
2953
+ fail2("DIFF_BLOCKED", "The selected path is outside the session");
3058
2954
  }
3059
2955
  work.check();
3060
2956
  if (info.isDirectory() !== (!last || kind === "directory")) return void 0;
@@ -3067,10 +2963,10 @@ async function readCurrent(root, path, algorithm, work, keepBytes = false) {
3067
2963
  const before = await inspect(root, path, work, kind);
3068
2964
  if (before === void 0) return void 0;
3069
2965
  if (before.isSymbolicLink()) {
3070
- const bytes = Buffer.from(await readlink(join5(root, ...path.split("/"))), "utf8");
2966
+ const bytes = Buffer.from(await readlink(join4(root, ...path.split("/"))), "utf8");
3071
2967
  const latest = await inspect(root, path, work, "link");
3072
2968
  if (latest === void 0 || identity(latest) !== identity(before)) changed();
3073
- const oid = createHash5(algorithm).update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
2969
+ const oid = createHash4(algorithm).update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
3074
2970
  return {
3075
2971
  oid,
3076
2972
  rawOid: oid,
@@ -3082,13 +2978,13 @@ async function readCurrent(root, path, algorithm, work, keepBytes = false) {
3082
2978
  if (before.size > BigInt(MAX_SCAN_BYTES - work.bytes) || keepBytes && before.size > BigInt(SESSION_GIT_DIFF_MAX_SOURCE_BYTES)) limit();
3083
2979
  work.bytes += Number(before.size);
3084
2980
  const handle = await open2(
3085
- join5(root, ...path.split("/")),
2981
+ join4(root, ...path.split("/")),
3086
2982
  constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0)
3087
2983
  );
3088
2984
  try {
3089
2985
  const opened = await handle.stat({ bigint: true });
3090
2986
  if (!opened.isFile() || identity(opened) !== identity(before)) changed();
3091
- const hash2 = createHash5(algorithm).update(`blob ${before.size}\0`);
2987
+ const hash2 = createHash4(algorithm).update(`blob ${before.size}\0`);
3092
2988
  const buffer = Buffer.alloc(64 * 1024);
3093
2989
  const chunks = [];
3094
2990
  let offset = 0;
@@ -3128,28 +3024,28 @@ async function base(repository, work) {
3128
3024
  ], { allowExitOne: true })).trim();
3129
3025
  if (!commit) continue;
3130
3026
  if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(commit)) {
3131
- fail3("DIFF_BASE_UNAVAILABLE", "The main branch could not be resolved");
3027
+ fail2("DIFF_BASE_UNAVAILABLE", "The main branch could not be resolved");
3132
3028
  }
3133
3029
  const baseCommit = decode(await work.git(repository, ["merge-base", "--all", "HEAD", commit], {
3134
3030
  allowExitOne: true
3135
3031
  })).trim();
3136
3032
  if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(baseCommit)) {
3137
- fail3("DIFF_BASE_UNAVAILABLE", "The session and main do not have a unique merge base");
3033
+ fail2("DIFF_BASE_UNAVAILABLE", "The session and main do not have a unique merge base");
3138
3034
  }
3139
3035
  return { baseRef, baseCommit };
3140
3036
  }
3141
- return fail3("DIFF_MAIN_UNAVAILABLE", "No local origin/main or main reference is available");
3037
+ return fail2("DIFF_MAIN_UNAVAILABLE", "No local origin/main or main reference is available");
3142
3038
  }
3143
3039
  function scopedPath(context, path) {
3144
3040
  const prefix = context.prefix === "" ? "" : `${context.prefix}/`;
3145
- if (!path.startsWith(prefix)) fail3("DIFF_BLOCKED", "Git returned a path outside the session");
3041
+ if (!path.startsWith(prefix)) fail2("DIFF_BLOCKED", "Git returned a path outside the session");
3146
3042
  const scoped = path.slice(prefix.length);
3147
3043
  return scoped;
3148
3044
  }
3149
3045
  function records(output2) {
3150
3046
  const text = decode(output2);
3151
3047
  if (text === "") return [];
3152
- if (!text.endsWith("\0")) fail3("DIFF_UNAVAILABLE", "Git returned an incomplete file list");
3048
+ if (!text.endsWith("\0")) fail2("DIFF_UNAVAILABLE", "Git returned an incomplete file list");
3153
3049
  return text.slice(0, -1).split("\0");
3154
3050
  }
3155
3051
  async function changes(context, work) {
@@ -3175,7 +3071,7 @@ async function changes(context, work) {
3175
3071
  };
3176
3072
  for (const record of tree) {
3177
3073
  const match = /^(\d{6}) (blob|commit) ([a-f0-9]{40}|[a-f0-9]{64})\t([\s\S]+)$/u.exec(record);
3178
- if (!match?.[1] || !match[3] || !match[4]) fail3("DIFF_UNAVAILABLE", "Git returned an invalid tree");
3074
+ if (!match?.[1] || !match[3] || !match[4]) fail2("DIFF_UNAVAILABLE", "Git returned an invalid tree");
3179
3075
  blobs.set(scoped(match[4]), { mode: match[1], oid: match[3] });
3180
3076
  }
3181
3077
  for (const record of records(await work.git(context.repository, [
@@ -3187,7 +3083,7 @@ async function changes(context, work) {
3187
3083
  ...paths
3188
3084
  ]))) {
3189
3085
  const match = /^(\d{6}) ([a-f0-9]{40}|[a-f0-9]{64}) [0-3]\t([\s\S]+)$/u.exec(record);
3190
- if (!match?.[1] || !match[2] || !match[3]) fail3("DIFF_UNAVAILABLE", "Git returned an invalid index");
3086
+ if (!match?.[1] || !match[2] || !match[3]) fail2("DIFF_UNAVAILABLE", "Git returned an invalid index");
3191
3087
  tracked.set(scoped(match[3]), { mode: match[1], oid: match[2] });
3192
3088
  }
3193
3089
  for (const path of scanned) {
@@ -3234,7 +3130,7 @@ async function changes(context, work) {
3234
3130
  for (const path of [...candidates].sort()) {
3235
3131
  work.check();
3236
3132
  try {
3237
- if (!safePath(path)) fail3("DIFF_BLOCKED", "This path cannot be safely accessed on the PC");
3133
+ if (!safePath(path)) fail2("DIFF_BLOCKED", "This path cannot be safely accessed on the PC");
3238
3134
  const original = blobs.get(path);
3239
3135
  const indexed = tracked.get(path);
3240
3136
  if ([original?.mode, indexed?.mode].some((mode) => mode !== void 0 && mode !== "100644" && mode !== "100755" && !(work.partial && mode === "120000"))) {
@@ -3317,13 +3213,13 @@ async function changes(context, work) {
3317
3213
  return result;
3318
3214
  }
3319
3215
  async function unchangedSpecial(context, path, original, indexed, work) {
3320
- const blocked = () => fail3("DIFF_BLOCKED", "Changed links and submodules cannot be compared");
3216
+ const blocked = () => fail2("DIFF_BLOCKED", "Changed links and submodules cannot be compared");
3321
3217
  if (original === void 0 || indexed?.mode !== original.mode || indexed.oid !== original.oid) return blocked();
3322
3218
  if (original.mode === "160000") {
3323
3219
  if (await inspect(context.root, path, work, "directory") === void 0) blocked();
3324
- const target = join5(context.root, ...path.split("/"));
3220
+ const target = join4(context.root, ...path.split("/"));
3325
3221
  try {
3326
- await lstat4(join5(target, ".git"));
3222
+ await lstat3(join4(target, ".git"));
3327
3223
  } catch (error) {
3328
3224
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
3329
3225
  throw error;
@@ -3335,8 +3231,8 @@ async function unchangedSpecial(context, path, original, indexed, work) {
3335
3231
  const algorithm = context.baseCommit.length === 64 ? "sha256" : "sha1";
3336
3232
  let oid;
3337
3233
  if (info.isSymbolicLink()) {
3338
- const target = Buffer.from(await readlink(join5(context.root, ...path.split("/"))), "utf8");
3339
- oid = createHash5(algorithm).update(`blob ${target.length}\0`).update(target).digest("hex");
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");
3340
3236
  } else {
3341
3237
  oid = (await readCurrent(context.root, path, algorithm, work))?.rawOid;
3342
3238
  }
@@ -3378,19 +3274,19 @@ async function patch(context, change, work, scratchDirectory) {
3378
3274
  }
3379
3275
  const directory = resolve2(scratchDirectory);
3380
3276
  if (contained(context.repository, directory)) {
3381
- fail3("DIFF_UNAVAILABLE", "Project diff storage must be outside the session repository");
3277
+ fail2("DIFF_UNAVAILABLE", "Project diff storage must be outside the session repository");
3382
3278
  }
3383
3279
  await mkdir2(directory, { recursive: true, mode: 448 });
3384
- if ((await lstat4(directory)).isSymbolicLink() || !samePath(await realpath4(directory), directory)) {
3385
- fail3("DIFF_UNAVAILABLE", "Project diff storage cannot use links");
3280
+ if ((await lstat3(directory)).isSymbolicLink() || !samePath(await realpath3(directory), directory)) {
3281
+ fail2("DIFF_UNAVAILABLE", "Project diff storage cannot use links");
3386
3282
  }
3387
- const scratch = join5(directory, randomUUID3());
3283
+ const scratch = join4(directory, randomUUID3());
3388
3284
  await mkdir2(scratch, { mode: 448 });
3389
3285
  let text;
3390
3286
  try {
3391
3287
  let bytes = current?.bytes ?? Buffer.alloc(0);
3392
3288
  if (current !== void 0 && current.mode !== "120000") {
3393
- const objectDirectory = join5(scratch, "objects");
3289
+ const objectDirectory = join4(scratch, "objects");
3394
3290
  await mkdir2(objectDirectory);
3395
3291
  const path = [context.prefix, change.entry.path].filter(Boolean).join("/");
3396
3292
  const oid = decode(await work.git(context.repository, ["hash-object", "-w", "--stdin", `--path=${path}`], {
@@ -3404,18 +3300,18 @@ async function patch(context, change, work, scratchDirectory) {
3404
3300
  });
3405
3301
  }
3406
3302
  if (binary(original) || binary(bytes)) return { patch: "", binary: true };
3407
- for (const side of ["a", "b"]) await mkdir2(join5(scratch, side));
3303
+ for (const side of ["a", "b"]) await mkdir2(join4(scratch, side));
3408
3304
  for (const [side, content, mode] of [
3409
3305
  ["a", original, change.base?.mode],
3410
3306
  ["b", bytes, current?.mode]
3411
3307
  ]) {
3412
3308
  if (mode === void 0) continue;
3413
- const file = join5(scratch, side, ...change.entry.path.split("/"));
3309
+ const file = join4(scratch, side, ...change.entry.path.split("/"));
3414
3310
  await mkdir2(dirname(file), { recursive: true });
3415
3311
  await writeFile2(file, content, { flag: "wx", mode: 384 });
3416
3312
  if (process.platform !== "win32") await chmod(file, mode === "100755" ? 448 : 384);
3417
3313
  }
3418
- await writeFile2(join5(scratch, "gitconfig"), "", { flag: "wx", mode: 384 });
3314
+ await writeFile2(join4(scratch, "gitconfig"), "", { flag: "wx", mode: 384 });
3419
3315
  text = decode(await work.git(scratch, [
3420
3316
  "-c",
3421
3317
  "core.quotePath=false",
@@ -3462,9 +3358,9 @@ var SessionGitDiffReader = class {
3462
3358
  #active = 0;
3463
3359
  async read(sessionId, data, version = SESSION_GIT_DIFF_PARTIAL_VERSION) {
3464
3360
  if (!SessionGitDiffDataSchema.safeParse(data).success || data.path !== void 0 && !safePath(data.path)) {
3465
- fail3("INVALID_DIFF_PATH", "The project diff request is invalid");
3361
+ fail2("INVALID_DIFF_PATH", "The project diff request is invalid");
3466
3362
  }
3467
- if (this.#active >= SESSION_GIT_DIFF_CONCURRENCY) fail3("DIFF_BUSY", "Too many project diff requests");
3363
+ if (this.#active >= SESSION_GIT_DIFF_CONCURRENCY) fail2("DIFF_BUSY", "Too many project diff requests");
3468
3364
  this.#active++;
3469
3365
  const work = new Work(version >= SESSION_GIT_DIFF_PARTIAL_VERSION);
3470
3366
  const pending = this.#read(sessionId, data, work, version).finally(() => {
@@ -3491,33 +3387,33 @@ var SessionGitDiffReader = class {
3491
3387
  async #context(sessionId, rootRevision, work) {
3492
3388
  const metadata = await this.metadata(sessionId);
3493
3389
  work.check();
3494
- if (metadata === void 0) fail3("SESSION_NOT_FOUND", "The session is unavailable");
3390
+ if (metadata === void 0) fail2("SESSION_NOT_FOUND", "The session is unavailable");
3495
3391
  const workingDirectory = metadata.workingDirectory;
3496
- if (!workingDirectory || !isAbsolute4(workingDirectory)) {
3497
- fail3("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
3392
+ if (!workingDirectory || !isAbsolute3(workingDirectory)) {
3393
+ fail2("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
3498
3394
  }
3499
3395
  let root;
3500
3396
  let rootIdentity;
3501
3397
  try {
3502
- root = await realpath4(workingDirectory);
3503
- if ((await lstat4(workingDirectory)).isSymbolicLink() || !samePath(root, resolve2(workingDirectory))) {
3504
- fail3("DIFF_BLOCKED", "Links cannot be compared");
3398
+ root = await realpath3(workingDirectory);
3399
+ if ((await lstat3(workingDirectory)).isSymbolicLink() || !samePath(root, resolve2(workingDirectory))) {
3400
+ fail2("DIFF_BLOCKED", "Links cannot be compared");
3505
3401
  }
3506
- const info = await stat4(root, { bigint: true });
3507
- if (!info.isDirectory()) fail3("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
3402
+ const info = await stat3(root, { bigint: true });
3403
+ if (!info.isDirectory()) fail2("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
3508
3404
  rootIdentity = sessionRootIdentity(root, info);
3509
3405
  } catch (error) {
3510
3406
  if (error instanceof SessionGitDiffError) throw error;
3511
3407
  throw new SessionGitDiffError("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable", { cause: error });
3512
3408
  }
3513
- if (createHash5("sha256").update(rootIdentity).digest("base64url") !== rootRevision) {
3514
- fail3("SESSION_ROOT_CHANGED", "The session directory changed");
3409
+ if (createHash4("sha256").update(rootIdentity).digest("base64url") !== rootRevision) {
3410
+ fail2("SESSION_ROOT_CHANGED", "The session directory changed");
3515
3411
  }
3516
3412
  let repository;
3517
3413
  try {
3518
3414
  const top = decode(await work.git(root, ["rev-parse", "--show-toplevel"])).replace(/\r?\n$/u, "");
3519
- if (!isAbsolute4(top)) fail3("DIFF_UNAVAILABLE", "Git returned an invalid repository");
3520
- repository = await realpath4(top);
3415
+ if (!isAbsolute3(top)) fail2("DIFF_UNAVAILABLE", "Git returned an invalid repository");
3416
+ repository = await realpath3(top);
3521
3417
  } catch (error) {
3522
3418
  if (error instanceof SessionGitDiffError) throw error;
3523
3419
  if (isGitRepositoryUnavailableError(error)) {
@@ -3529,9 +3425,9 @@ var SessionGitDiffReader = class {
3529
3425
  }
3530
3426
  throw error;
3531
3427
  }
3532
- if (!contained(repository, root)) fail3("DIFF_BLOCKED", "The repository is outside the session root");
3428
+ if (!contained(repository, root)) fail2("DIFF_BLOCKED", "The repository is outside the session root");
3533
3429
  if (decode(await work.git(root, ["rev-parse", "--show-superproject-working-tree"])).trim() !== "") {
3534
- fail3("DIFF_BLOCKED", "Submodule content cannot be compared");
3430
+ fail2("DIFF_BLOCKED", "Submodule content cannot be compared");
3535
3431
  }
3536
3432
  return {
3537
3433
  root,
@@ -3539,8 +3435,8 @@ var SessionGitDiffReader = class {
3539
3435
  rootIdentity,
3540
3436
  workingDirectory,
3541
3437
  repository,
3542
- repositoryIdentity: sessionRootIdentity(repository, await stat4(repository, { bigint: true })),
3543
- prefix: relative2(repository, root).split(sep2).join("/"),
3438
+ repositoryIdentity: sessionRootIdentity(repository, await stat3(repository, { bigint: true })),
3439
+ prefix: relative(repository, root).split(sep).join("/"),
3544
3440
  ...await base(repository, work)
3545
3441
  };
3546
3442
  }
@@ -3559,7 +3455,7 @@ var SessionGitDiffReader = class {
3559
3455
  if (selected === void 0) changed();
3560
3456
  if (selected.entry.error !== void 0) {
3561
3457
  const error = selected.entry.error;
3562
- fail3(
3458
+ fail2(
3563
3459
  work.partial && error.code === "DIFF_BLOCKED" ? "DIFF_FILE_BLOCKED" : error.code,
3564
3460
  `${data.path}: ${error.message}`
3565
3461
  );
@@ -3573,7 +3469,7 @@ var SessionGitDiffReader = class {
3573
3469
  }
3574
3470
  if (version < SESSION_GIT_DIFF_PARTIAL_VERSION) {
3575
3471
  const blocked = files.find(({ entry }) => entry.error !== void 0)?.entry;
3576
- if (blocked?.error !== void 0) fail3(blocked.error.code, `${blocked.path}: ${blocked.error.message}`);
3472
+ if (blocked?.error !== void 0) fail2(blocked.error.code, `${blocked.path}: ${blocked.error.message}`);
3577
3473
  }
3578
3474
  let latest;
3579
3475
  try {
@@ -3588,7 +3484,7 @@ var SessionGitDiffReader = class {
3588
3484
  throw error;
3589
3485
  }
3590
3486
  if (latest.workingDirectory !== context.workingDirectory || latest.rootIdentity !== context.rootIdentity) {
3591
- fail3("SESSION_ROOT_CHANGED", "The session directory changed");
3487
+ fail2("SESSION_ROOT_CHANGED", "The session directory changed");
3592
3488
  }
3593
3489
  if (latest.repositoryIdentity !== context.repositoryIdentity || latest.baseRef !== context.baseRef || latest.baseCommit !== context.baseCommit) changed();
3594
3490
  if (selected !== void 0) {
@@ -3608,7 +3504,7 @@ var SessionGitDiffReader = class {
3608
3504
  };
3609
3505
 
3610
3506
  // src/timeline-image-cache.ts
3611
- import { createHash as createHash6 } from "node:crypto";
3507
+ import { createHash as createHash5 } from "node:crypto";
3612
3508
  var TimelineAssetError = class extends Error {
3613
3509
  constructor(code, message, options) {
3614
3510
  super(message, options);
@@ -3677,7 +3573,7 @@ var TimelineImageCache = class {
3677
3573
  if (attachment.kind !== "image" || attachment.data === void 0) return attachment;
3678
3574
  const parsed = ConversationAttachmentSchema.parse(attachment);
3679
3575
  const bytes = Buffer.from(attachment.data, "base64");
3680
- if (bytes.length !== parsed.byteLength || createHash6("sha256").update(bytes).digest("hex") !== parsed.sha256 || !hasSignature(bytes, parsed.mimeType)) {
3576
+ if (bytes.length !== parsed.byteLength || createHash5("sha256").update(bytes).digest("hex") !== parsed.sha256 || !hasSignature(bytes, parsed.mimeType)) {
3681
3577
  throw new TimelineAssetError("IMAGE_INVALID", "Image content does not match its metadata");
3682
3578
  }
3683
3579
  const key = JSON.stringify([sessionId, parsed.sha256]);
@@ -3733,8 +3629,43 @@ function createCommunicationOperations(options) {
3733
3629
  const gitDiffReader = new SessionGitDiffReader(async (sessionId) => adapter.getSessionDirectoryMetadata?.(sessionId), options.gitDiffDirectory);
3734
3630
  const getSessionProjectIdentity = adapter.getSessionProjectIdentity?.bind(adapter);
3735
3631
  const createGroupChat = adapter.createGroupChat?.bind(adapter);
3632
+ const createEncryptedGroupChat = adapter.createEncryptedGroupChat?.bind(adapter);
3633
+ const authorizeEncryptedPeer = options.authorizeEncryptedPeer;
3736
3634
  const renameSession = adapter.renameSession?.bind(adapter);
3737
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
+ ],
3738
3669
  ...options.workbenchOperations,
3739
3670
  ...imageBlob === void 0 ? [] : [
3740
3671
  sessionCommunicationOperation({
@@ -3824,17 +3755,17 @@ function createCommunicationOperations(options) {
3824
3755
  operation: SESSION_DIRECTORY_LIST_OPERATION,
3825
3756
  version: SESSION_DIRECTORY_LIST_VERSION,
3826
3757
  schema: SessionDirectoryListDataSchema,
3827
- handle: async ({ path }, request2) => SessionDirectoryListResultDataSchema.parse({
3758
+ handle: async ({ path, space }, request2) => SessionCommunicationDataSchema.parse(SessionDirectoryListResultDataSchema.parse({
3828
3759
  path,
3829
- ...await directoryLister.list(request2.sessionId, path)
3830
- }),
3760
+ ...await directoryLister.list(request2.sessionId, path, space)
3761
+ })),
3831
3762
  onError: (error) => unsupportedOperation(error) ?? (error instanceof SessionDirectoryError ? { code: error.code, message: error.message } : { code: "DIRECTORY_UNAVAILABLE", message: "The directory is unavailable" })
3832
3763
  }),
3833
3764
  ...[SESSION_FILE_READ_VERSION, SESSION_FILE_READ_V2_VERSION].map((version) => sessionCommunicationOperation({
3834
3765
  operation: SESSION_FILE_READ_OPERATION,
3835
3766
  version,
3836
3767
  schema: SessionFileReadDataSchema,
3837
- 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),
3838
3769
  onError: (error) => unsupportedOperation(error) ?? {
3839
3770
  code: error instanceof SessionFileReadError ? error.code : "FILE_UNAVAILABLE",
3840
3771
  message: "The file preview is unavailable"
@@ -3844,10 +3775,10 @@ function createCommunicationOperations(options) {
3844
3775
  operation: SESSION_FILE_DOWNLOAD_OPERATION,
3845
3776
  version: SESSION_FILE_DOWNLOAD_VERSION,
3846
3777
  schema: SessionFileDownloadDataSchema,
3847
- handle: async ({ path, rootRevision }, request2) => {
3778
+ handle: async ({ path, rootRevision, space }, request2) => {
3848
3779
  const assertAccess = options.captureRequestAccess();
3849
3780
  assertAccess();
3850
- const result = await fileReader.download(request2.sessionId, path, rootRevision);
3781
+ const result = await fileReader.download(request2.sessionId, path, rootRevision, space);
3851
3782
  assertAccess();
3852
3783
  return result;
3853
3784
  },
@@ -3860,7 +3791,7 @@ function createCommunicationOperations(options) {
3860
3791
  operation: SESSION_RESOURCE_READ_OPERATION,
3861
3792
  version: SESSION_RESOURCE_READ_VERSION,
3862
3793
  schema: SessionResourceReadDataSchema,
3863
- handle: ({ path, rootRevision }, request2) => fileReader.readResource(request2.sessionId, path, rootRevision),
3794
+ handle: ({ path, rootRevision, space }, request2) => fileReader.readResource(request2.sessionId, path, rootRevision, space),
3864
3795
  onError: (error) => unsupportedOperation(error) ?? {
3865
3796
  code: error instanceof SessionFileReadError ? error.code : "FILE_UNAVAILABLE",
3866
3797
  message: "The resource is unavailable"
@@ -3902,14 +3833,21 @@ var SessionCommunicationHandler = class {
3902
3833
  const workbench = adapter.agentId === "copilot" || adapter.agentId === "managed" ? adapter.workbench : void 0;
3903
3834
  const researchWorkbench = workbench === void 0 ? void 0 : research;
3904
3835
  this.#operations = workbench === void 0 && researchWorkbench === void 0 ? void 0 : new SessionOperations({
3905
- directory: join6(config.dataDirectory, "workbench"),
3836
+ directory: join5(config.dataDirectory, "workbench"),
3906
3837
  agentRunId,
3907
3838
  namespace: `${config.userId}\0${machineId}`,
3908
3839
  onError: operationError
3909
3840
  });
3910
3841
  this.#dispatcher = new SessionCommunicationDispatcher(createCommunicationOperations({
3911
3842
  adapter,
3912
- gitDiffDirectory: join6(config.dataDirectory, "git-diff"),
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"),
3913
3851
  publications: options.publications,
3914
3852
  captureRequestAccess: () => {
3915
3853
  const assertCurrent = this.#requestContext.getStore()?.assertRequestCurrent;
@@ -3953,6 +3891,7 @@ var SessionCommunicationHandler = class {
3953
3891
  return [
3954
3892
  ...this.#dispatcher.capabilities.filter((capability) => (capability !== GROUP_CHAT_CREATE_CAPABILITY || this.options.adapter.groupChatEnabled !== false) && (schedulesAvailable || !SCHEDULE_OPERATIONS.some((operation) => capability === workbenchCapability(operation)))),
3955
3893
  ...this.options.research?.chat === void 0 ? [] : [RESEARCH_CHAT_CAPABILITY],
3894
+ ...this.options.adapter.getSessionDirectoryMetadata === void 0 ? [] : [SESSION_STATE_FILES_CAPABILITY],
3956
3895
  ...schedulesAvailable ? [SCHEDULES_CAPABILITY] : []
3957
3896
  ];
3958
3897
  }
@@ -4086,7 +4025,7 @@ var SessionCommunicationHandler = class {
4086
4025
  }
4087
4026
  const clientId = scope.clientId;
4088
4027
  const owner = [config.userId, machineId, clientId, request2.sessionId];
4089
- const key = (parts) => createHash7("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24);
4028
+ const key = (parts) => createHash6("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24);
4090
4029
  const knownSource = this.#researchParents.get(request2.sessionId) ?? adapter.sessionPublicationSource?.(request2.sessionId) ?? request2.sessionId;
4091
4030
  const arrivalPublication = adapter.isSessionVisible?.(knownSource) === true ? publications.capture(knownSource) : void 0;
4092
4031
  let researchParent = this.#researchParents.get(request2.sessionId);
@@ -4266,11 +4205,11 @@ var SessionCommunicationHandler = class {
4266
4205
  };
4267
4206
 
4268
4207
  // src/service/requests/device-text-input.ts
4269
- import { createHash as createHash8 } from "node:crypto";
4208
+ import { createHash as createHash7 } from "node:crypto";
4270
4209
 
4271
4210
  // src/windows-text-input.ts
4272
4211
  import { spawn } from "node:child_process";
4273
- import { join as join7 } from "node:path";
4212
+ import { join as join6 } from "node:path";
4274
4213
  var TextInputError = class extends Error {
4275
4214
  constructor(code) {
4276
4215
  super(code);
@@ -4354,7 +4293,7 @@ function createWindowsTextInput() {
4354
4293
  if (process.platform !== "win32") return void 0;
4355
4294
  const root = process.env["SystemRoot"];
4356
4295
  if (root === void 0) return void 0;
4357
- const executable = join7(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
4296
+ const executable = join6(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
4358
4297
  return (data) => runWindowsTextInput(executable, data);
4359
4298
  }
4360
4299
  function runWindowsTextInput(executable, data) {
@@ -4371,32 +4310,32 @@ function runWindowsTextInput(executable, data) {
4371
4310
  ], { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
4372
4311
  let stdout = "";
4373
4312
  let finished = false;
4374
- const fail4 = (code) => {
4313
+ const fail3 = (code) => {
4375
4314
  if (finished) return;
4376
4315
  finished = true;
4377
4316
  clearTimeout(timer);
4378
4317
  child.kill();
4379
4318
  reject(new TextInputError(code));
4380
4319
  };
4381
- const timer = setTimeout(() => fail4("TEXT_INPUT_TIMEOUT"), timeout);
4382
- child.on("error", () => fail4("TEXT_INPUT_UNAVAILABLE"));
4383
- child.stdin.on("error", () => fail4("TEXT_INPUT_UNAVAILABLE"));
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"));
4384
4323
  child.stdout.setEncoding("utf8");
4385
4324
  child.stdout.on("data", (chunk) => {
4386
4325
  stdout += chunk;
4387
- if (stdout.length > 4096) fail4("INVALID_TEXT_INPUT_RESULT");
4326
+ if (stdout.length > 4096) fail3("INVALID_TEXT_INPUT_RESULT");
4388
4327
  });
4389
4328
  child.stderr.resume();
4390
4329
  child.on("close", (code) => {
4391
4330
  if (finished) return;
4392
- if (code !== 0) return fail4("TEXT_INPUT_UNAVAILABLE");
4331
+ if (code !== 0) return fail3("TEXT_INPUT_UNAVAILABLE");
4393
4332
  try {
4394
4333
  const result = DeviceTextInputResultSchema.parse(JSON.parse(stdout));
4395
4334
  finished = true;
4396
4335
  clearTimeout(timer);
4397
4336
  resolve5(result);
4398
4337
  } catch {
4399
- fail4("INVALID_TEXT_INPUT_RESULT");
4338
+ fail3("INVALID_TEXT_INPUT_RESULT");
4400
4339
  }
4401
4340
  });
4402
4341
  child.stdin.end(JSON.stringify(data), "utf8");
@@ -4426,7 +4365,7 @@ var DeviceTextInputHandler = class {
4426
4365
  const now = Date.now();
4427
4366
  for (const [key2, item] of this.requests) if (item.expiresAt <= now) this.requests.delete(key2);
4428
4367
  const key = JSON.stringify([scope.clientId, request2.requestId]);
4429
- const fingerprint = createHash8("sha256").update(JSON.stringify(data.data)).digest("hex");
4368
+ const fingerprint = createHash7("sha256").update(JSON.stringify(data.data)).digest("hex");
4430
4369
  const cached = this.requests.get(key);
4431
4370
  if (cached !== void 0) return cached.fingerprint === fingerprint ? cached.response : error("REQUEST_ID_REUSED");
4432
4371
  if (data.data.expiresAt <= now || data.data.expiresAt > now + DEVICE_TEXT_INPUT_TTL_MS + MAX_CLOCK_SKEW_MS) {
@@ -4458,23 +4397,23 @@ function textInputErrorMessage(code) {
4458
4397
  }
4459
4398
 
4460
4399
  // src/desktop-workspaces.ts
4461
- import { createHash as createHash9 } from "node:crypto";
4462
- import { readdir, realpath as realpath5, stat as stat5 } from "node:fs/promises";
4400
+ import { createHash as createHash8 } from "node:crypto";
4401
+ import { readdir, realpath as realpath4, stat as stat4 } from "node:fs/promises";
4463
4402
  import { homedir } from "node:os";
4464
- import { basename, join as join8, normalize } from "node:path";
4403
+ import { basename, join as join7, normalize } from "node:path";
4465
4404
  function desktopRootCandidates(environment2 = process.env) {
4466
4405
  const candidates = [
4467
4406
  environment2.AGENTKNIGHT_WORKSPACE_ROOT,
4468
- environment2.OneDrive === void 0 ? void 0 : join8(environment2.OneDrive, "Desktop"),
4469
- environment2.OneDriveCommercial === void 0 ? void 0 : join8(environment2.OneDriveCommercial, "Desktop"),
4470
- environment2.OneDriveConsumer === void 0 ? void 0 : join8(environment2.OneDriveConsumer, "Desktop"),
4471
- join8(environment2.USERPROFILE ?? homedir(), "Desktop")
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")
4472
4411
  ];
4473
4412
  return [...new Set(candidates.filter((path) => path !== void 0))];
4474
4413
  }
4475
4414
  function workspaceId(path) {
4476
4415
  const normalizedPath = workspacePathKey(path);
4477
- return createHash9("sha256").update(normalizedPath).digest("base64url").slice(0, 32);
4416
+ return createHash8("sha256").update(normalizedPath).digest("base64url").slice(0, 32);
4478
4417
  }
4479
4418
  function workspacePathKey(path) {
4480
4419
  const normalizedPath = normalize(path);
@@ -4486,8 +4425,8 @@ function isMissingPathError(error) {
4486
4425
  async function findDesktopRoot(candidates) {
4487
4426
  for (const candidate of candidates) {
4488
4427
  try {
4489
- const resolved = await realpath5(candidate);
4490
- if ((await stat5(resolved)).isDirectory()) {
4428
+ const resolved = await realpath4(candidate);
4429
+ if ((await stat4(resolved)).isDirectory()) {
4491
4430
  return resolved;
4492
4431
  }
4493
4432
  } catch (error) {
@@ -4509,7 +4448,7 @@ async function listDesktopWorkspaces(rootOverride) {
4509
4448
  const workspaces = entries.filter(
4510
4449
  (entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name.trim().length > 0
4511
4450
  ).map((entry) => {
4512
- const path = join8(root, entry.name);
4451
+ const path = join7(root, entry.name);
4513
4452
  return {
4514
4453
  id: workspaceId(path),
4515
4454
  name: entry.name,
@@ -4529,8 +4468,8 @@ async function resolveSessionWorkspace(path) {
4529
4468
  return void 0;
4530
4469
  }
4531
4470
  try {
4532
- const resolved = await realpath5(candidate);
4533
- if (!(await stat5(resolved)).isDirectory()) {
4471
+ const resolved = await realpath4(candidate);
4472
+ if (!(await stat4(resolved)).isDirectory()) {
4534
4473
  return void 0;
4535
4474
  }
4536
4475
  return {
@@ -4579,9 +4518,9 @@ async function resolveSelectableWorkspace(id, sessionWorkingDirectories, rootOve
4579
4518
  // src/git-session-worktree.ts
4580
4519
  import { execFile as execFile2 } from "node:child_process";
4581
4520
  import { randomUUID as randomUUID4 } from "node:crypto";
4582
- import { lstat as lstat5, mkdir as mkdir3, realpath as realpath6, rmdir } from "node:fs/promises";
4521
+ import { lstat as lstat4, mkdir as mkdir3, realpath as realpath5, rmdir } from "node:fs/promises";
4583
4522
  import { devNull } from "node:os";
4584
- import { dirname as dirname2, isAbsolute as isAbsolute5, join as join9, relative as relative3 } from "node:path";
4523
+ import { dirname as dirname2, isAbsolute as isAbsolute4, join as join8, relative as relative2 } from "node:path";
4585
4524
  import { promisify as promisify3 } from "node:util";
4586
4525
  var execFileAsync = promisify3(execFile2);
4587
4526
  function creationEnvironment() {
@@ -4591,8 +4530,8 @@ function creationEnvironment() {
4591
4530
  return { ...env, LC_ALL: "C" };
4592
4531
  }
4593
4532
  function inside(root, path) {
4594
- const difference = relative3(root, path);
4595
- return difference === "" || !isAbsolute5(difference) && difference !== ".." && !difference.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
4533
+ const difference = relative2(root, path);
4534
+ return difference === "" || !isAbsolute4(difference) && difference !== ".." && !difference.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
4596
4535
  }
4597
4536
  async function git(env, ...args) {
4598
4537
  const { stdout } = await execFileAsync("git", [
@@ -4686,23 +4625,23 @@ async function createSessionWorktree(sourceDirectory, requestedBranchName, reque
4686
4625
  exists = false;
4687
4626
  }
4688
4627
  if (exists) throw new Error(`Git branch "${branchName}" already exists. Choose a new branch name.`);
4689
- const primary = await realpath6(identity2.mainWorktreeRoot ?? identity2.worktreeRoot);
4628
+ const primary = await realpath5(identity2.mainWorktreeRoot ?? identity2.worktreeRoot);
4690
4629
  const parent = dirname2(primary);
4691
4630
  if (inside(identity2.worktreeRoot, parent)) {
4692
4631
  throw new Error("Cannot create a sibling worktree outside the source checkout. Move the repository and retry.");
4693
4632
  }
4694
- const path = join9(parent, `agentknight-worktree-${suffix}`);
4633
+ const path = join8(parent, `agentknight-worktree-${suffix}`);
4695
4634
  if (path.length > 640) {
4696
4635
  throw new Error("The repository path is too long to report worktree recovery safely. Use a checkout closer to the filesystem root.");
4697
4636
  }
4698
4637
  await mkdir3(path, { mode: 448 });
4699
- const reserved = await lstat5(path);
4638
+ const reserved = await lstat4(path);
4700
4639
  try {
4701
4640
  await git(env, "-C", identity2.worktreeRoot, "worktree", "add", "-b", branchName, "--", path, head);
4702
4641
  } catch (cause) {
4703
4642
  let cleanupError;
4704
4643
  try {
4705
- const current = await lstat5(path);
4644
+ const current = await lstat4(path);
4706
4645
  if (current.dev === reserved.dev && current.ino === reserved.ino) await rmdir(path);
4707
4646
  } catch (error) {
4708
4647
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) cleanupError = error;
@@ -4986,9 +4925,9 @@ var OperationDeduplicator = class {
4986
4925
  let reject = () => {
4987
4926
  throw new Error("Operation not initialized");
4988
4927
  };
4989
- const promise = new Promise((accept, fail4) => {
4928
+ const promise = new Promise((accept, fail3) => {
4990
4929
  resolve5 = accept;
4991
- reject = fail4;
4930
+ reject = fail3;
4992
4931
  });
4993
4932
  const entry = {
4994
4933
  fingerprint: options.fingerprint,
@@ -5264,9 +5203,9 @@ var SessionCommandsHandler = class {
5264
5203
  };
5265
5204
 
5266
5205
  // src/service/requests/session-prompt.ts
5267
- import { createHash as createHash10 } from "node:crypto";
5206
+ import { createHash as createHash9 } from "node:crypto";
5268
5207
  function promptOperationFingerprint(request2) {
5269
- const fingerprint = createHash10("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 }) => ({
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 }) => ({
5270
5209
  name,
5271
5210
  mimeType,
5272
5211
  sha256
@@ -5578,58 +5517,99 @@ var A2aPeerClient = class {
5578
5517
  this.options = options;
5579
5518
  }
5580
5519
  options;
5581
- conversation(target) {
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
+ }
5582
5524
  const endpoint = relayEndpoint(this.options.relayUrl, target);
5583
5525
  const cardUrl = `${endpoint.href}/agent-card.json`;
5584
- let contextId;
5585
- const exchanges = [];
5586
- let client;
5587
- const createClient = async (signal) => {
5588
- const fetchImpl = async (input, init) => {
5589
- const url = input instanceof Request ? input.url : String(input);
5590
- if (url !== endpoint.href && url !== cardUrl) throw new Error("A2A endpoint differs from the configured peer.");
5591
- const headers = new Headers(input instanceof Request ? input.headers : void 0);
5592
- new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
5593
- headers.set("authorization", `Bearer ${await relayRequestToken(this.options)}`);
5594
- headers.set("x-agentknight-user-id", this.options.userId);
5595
- headers.set("x-agentknight-machine-id", this.options.machineId);
5596
- const timeout = new AbortController();
5597
- const timer = setTimeout(() => timeout.abort(new Error("A2A HTTP request timed out; execution will not be retried.")), HTTP_TIMEOUT_MS);
5598
- const callSignal = init?.signal ?? (input instanceof Request ? input.signal : void 0) ?? signal;
5599
- try {
5600
- const response = await fetch(input, {
5601
- ...init,
5602
- headers,
5603
- redirect: "error",
5604
- signal: AbortSignal.any([callSignal, timeout.signal])
5605
- });
5606
- if (!response.ok) {
5607
- await response.body?.cancel();
5608
- 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.";
5609
- throw new Error(`A2A HTTP ${response.status}: ${reason}`);
5610
- }
5611
- const reader = response.body?.getReader();
5612
- const chunks = [];
5613
- let size = 0;
5614
- if (reader !== void 0) {
5615
- try {
5616
- for (; ; ) {
5617
- const chunk = await reader.read();
5618
- if (chunk.done) break;
5619
- size += chunk.value.byteLength;
5620
- if (size > MAX_RESPONSE_BYTES) throw new Error("A2A response exceeds the text budget.");
5621
- chunks.push(chunk.value);
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.");
5622
5570
  }
5623
- } finally {
5624
- await reader.cancel();
5625
- reader.releaseLock();
5571
+ chunks.push(chunk.value);
5626
5572
  }
5573
+ } finally {
5574
+ await reader.cancel();
5575
+ reader.releaseLock();
5627
5576
  }
5628
- return new Response(Buffer.concat(chunks), { status: response.status, statusText: response.statusText, headers: response.headers });
5629
- } finally {
5630
- clearTimeout(timer);
5631
5577
  }
5632
- };
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);
5633
5613
  const factory = new ClientFactory({
5634
5614
  transports: [new JsonRpcTransportFactory({ fetchImpl })],
5635
5615
  cardResolver: new DefaultAgentCardResolver({ fetchImpl })
@@ -5712,7 +5692,9 @@ var A2aPeerClient = class {
5712
5692
  };
5713
5693
 
5714
5694
  // src/a2a-server.ts
5715
- import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
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";
5716
5698
  import {
5717
5699
  AgentCard,
5718
5700
  Role as Role2,
@@ -5743,7 +5725,6 @@ var MAX_ACTIVE = 4;
5743
5725
  var MAX_TASKS = 128;
5744
5726
  var MAX_RECEIPTS = 256;
5745
5727
  var TASK_TTL_MS = 10 * 6e4;
5746
- var TURN_TIMEOUT_MS = 12e4;
5747
5728
  var SHORT_REQUEST_TIMEOUT_MS = 9e3;
5748
5729
  var MAX_TEXT2 = 16e3;
5749
5730
  var TASK_WIRE_BUDGET = 6e4;
@@ -5900,6 +5881,8 @@ var A2aPeerServer = class {
5900
5881
  #fencedSessions = /* @__PURE__ */ new Set();
5901
5882
  #buses = new DefaultExecutionEventBusManager();
5902
5883
  #store;
5884
+ // Context ownership must outlive cached task bodies without an unbounded context map.
5885
+ #contextKey = randomBytes2(32);
5903
5886
  #generation = 0;
5904
5887
  #closed = false;
5905
5888
  get busy() {
@@ -6014,7 +5997,7 @@ var A2aPeerServer = class {
6014
5997
  if (message === void 0) throw new RequestMalformedError("A message is required.");
6015
5998
  const scope = scopedOwner(context);
6016
5999
  const key = JSON.stringify([scope, message.messageId]);
6017
- const fingerprint = createHash11("sha256").update(JSON.stringify(SendMessageRequest.toJSON(params))).digest("hex");
6000
+ const fingerprint = createHash10("sha256").update(JSON.stringify(SendMessageRequest.toJSON(params))).digest("hex");
6018
6001
  const previous = this.#receipts.get(key);
6019
6002
  if (previous !== void 0) {
6020
6003
  if (previous.fingerprint !== fingerprint) throw new RequestMalformedError("messageId was already used with different content.");
@@ -6029,18 +6012,31 @@ var A2aPeerServer = class {
6029
6012
  if (task === void 0) throw new TaskNotFoundError("This message's task expired; it will not be replayed.");
6030
6013
  return taskWithHistory(task, params.configuration?.historyLength);
6031
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
+ }
6032
6025
  if (message.taskId) {
6033
6026
  if (await this.#store.load(message.taskId, context) === void 0) throw new TaskNotFoundError();
6034
6027
  throw new UnsupportedOperationError("Tasks cannot be resumed. Send a fresh message in the same context.");
6035
6028
  }
6036
- if (message.contextId && ![...this.#tasks.values()].some((entry) => entry.scope === scope && entry.generation === this.#generation && entry.task.contextId === message.contextId)) {
6029
+ if (message.contextId && !this.#validContext(message.contextId, scope)) {
6037
6030
  throw new RequestMalformedError("Unknown or expired context for this authenticated session.");
6038
6031
  }
6039
6032
  if (this.#active.size >= MAX_ACTIVE || this.#fencedSessions.has(envelope.targetSessionId) || [...this.#active].some((work2) => work2.sessionId === envelope.targetSessionId)) {
6040
6033
  throw new UnsupportedOperationError("The native peer session is busy or its stop is unconfirmed.");
6041
6034
  }
6042
- if (this.#receipts.size >= MAX_RECEIPTS) throw new UnsupportedOperationError("This online server's message receipt limit was reached.");
6043
- const probe = workingTask(randomUUID6(), message.contextId || randomUUID6(), message);
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);
6044
6040
  if (JSON.stringify(Task.toJSON(probe)).length > TASK_WIRE_BUDGET - 1024) {
6045
6041
  throw new ContentTypeNotSupportedError("Text exceeds the response transport budget.");
6046
6042
  }
@@ -6054,14 +6050,18 @@ var A2aPeerServer = class {
6054
6050
  controller,
6055
6051
  done: deferred(),
6056
6052
  saved: deferred(),
6057
- expired: false,
6058
- cancellationMessage: "Native execution settled after cancellation.",
6059
- timer: setTimeout(() => {
6060
- work.expired = true;
6061
- controller.abort(new Error("The A2A native turn exceeded its deadline."));
6062
- }, TURN_TIMEOUT_MS)
6053
+ cancellationMessage: "Native execution settled after cancellation."
6063
6054
  };
6064
- work.timer.unref();
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
+ }
6065
6065
  this.#receipts.set(key, receipt2);
6066
6066
  this.#active.add(work);
6067
6067
  context.state.set("a2aWork", work);
@@ -6077,6 +6077,7 @@ var A2aPeerServer = class {
6077
6077
  this.#assertReady();
6078
6078
  controller.signal.throwIfAborted();
6079
6079
  if (work.generation !== this.#generation) throw new UnsupportedOperationError("The peer connection changed.");
6080
+ message.contextId = contextId;
6080
6081
  dispatched = true;
6081
6082
  const operation = dispatch();
6082
6083
  this.#jobs.add(operation);
@@ -6103,6 +6104,18 @@ var A2aPeerServer = class {
6103
6104
  throw error;
6104
6105
  }
6105
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
+ }
6106
6119
  async #execute(request2, bus) {
6107
6120
  const work = [...this.#active].find((entry) => entry === request2.context.state.get("a2aWork"));
6108
6121
  if (work === void 0) throw new UnsupportedOperationError("Native task ownership is unavailable.");
@@ -6118,14 +6131,14 @@ var A2aPeerServer = class {
6118
6131
  const prompt = request2.userMessage.parts.map((part) => part.content?.$case === "text" ? part.content.value : "").join("\n");
6119
6132
  text = await this.host.runTurn(work.sessionId, prompt, { signal: work.controller.signal, awaitNativeSettlement: true });
6120
6133
  if (work.controller.signal.aborted) {
6121
- state = work.expired ? TaskState2.TASK_STATE_FAILED : TaskState2.TASK_STATE_CANCELED;
6122
- text = work.expired ? "Native execution settled after its deadline." : work.cancellationMessage;
6134
+ state = TaskState2.TASK_STATE_CANCELED;
6135
+ text = work.cancellationMessage;
6123
6136
  } else if (typeof text !== "string" || text.trim().length === 0 || text.length > MAX_TEXT2) {
6124
6137
  throw new InvalidAgentResponseError("Native execution returned empty or oversized text.");
6125
6138
  }
6126
6139
  } catch (error) {
6127
6140
  const canceled = work.controller.signal.aborted && error === work.controller.signal.reason;
6128
- state = canceled && !work.expired ? TaskState2.TASK_STATE_CANCELED : TaskState2.TASK_STATE_FAILED;
6141
+ state = canceled ? TaskState2.TASK_STATE_CANCELED : TaskState2.TASK_STATE_FAILED;
6129
6142
  text = state === TaskState2.TASK_STATE_CANCELED ? work.cancellationMessage : "Native peer execution failed.";
6130
6143
  if (work.controller.signal.aborted && !canceled) {
6131
6144
  this.#fencedSessions.add(work.sessionId);
@@ -6201,7 +6214,6 @@ var A2aPeerServer = class {
6201
6214
  }
6202
6215
  }
6203
6216
  #finish(work) {
6204
- clearTimeout(work.timer);
6205
6217
  this.#active.delete(work);
6206
6218
  work.done.resolve();
6207
6219
  }
@@ -6286,8 +6298,758 @@ var A2aPeerServer = class {
6286
6298
  }
6287
6299
  };
6288
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
+
6289
7051
  // src/peer-chat.ts
6290
- import { randomUUID as randomUUID7 } from "node:crypto";
7052
+ import { randomUUID as randomUUID9 } from "node:crypto";
6291
7053
  var MAX_ACTIVE_TURNS = 4;
6292
7054
  var MAX_SEEN_REQUESTS = 2048;
6293
7055
  function peerError(error) {
@@ -6306,7 +7068,7 @@ var PeerChatRuntime = class {
6306
7068
  get busy() {
6307
7069
  return this.#runs.size > 0 || this.#jobs.size > 0;
6308
7070
  }
6309
- async run(rawRequest, signal) {
7071
+ async run(rawRequest, signal, observer) {
6310
7072
  const request2 = PeerChatRequestSchema.parse(rawRequest);
6311
7073
  this.host.assertReady();
6312
7074
  signal.throwIfAborted();
@@ -6317,10 +7079,7 @@ var PeerChatRuntime = class {
6317
7079
  this.#runs.add(controller);
6318
7080
  const abort = () => controller.abort(signal.reason);
6319
7081
  signal.addEventListener("abort", abort, { once: true });
6320
- const deadline = Date.now() + PEER_CHAT_TIMEOUT_MS;
6321
- const timer = setTimeout(() => controller.abort(new Error("Peer conversation timed out; execution will not be replayed.")), PEER_CHAT_TIMEOUT_MS);
6322
7082
  const peerReplies = [];
6323
- let requests = 0;
6324
7083
  let lastExchange;
6325
7084
  const job = (async () => {
6326
7085
  const reply = await this.host.runTurn(request2.sessionId, [
@@ -6334,10 +7093,11 @@ var PeerChatRuntime = class {
6334
7093
  const exchange = async () => {
6335
7094
  try {
6336
7095
  controller.signal.throwIfAborted();
6337
- if (++requests > GROUP_CHAT_MAX_TURNS) throw new Error("Peer conversation reached its turn limit.");
6338
- const remaining = deadline - Date.now();
6339
- if (remaining < 1e3) throw new Error("Peer conversation timed out.");
7096
+ if (observer !== void 0) await observer.request(content);
7097
+ controller.signal.throwIfAborted();
6340
7098
  const response = await conversation.request(content, controller.signal);
7099
+ if (observer !== void 0) await observer.reply(response);
7100
+ controller.signal.throwIfAborted();
6341
7101
  peerReplies.push(response);
6342
7102
  return response;
6343
7103
  } catch (error) {
@@ -6358,7 +7118,6 @@ var PeerChatRuntime = class {
6358
7118
  try {
6359
7119
  return await job;
6360
7120
  } finally {
6361
- clearTimeout(timer);
6362
7121
  signal.removeEventListener("abort", abort);
6363
7122
  controller.abort(new Error("Peer conversation ended."));
6364
7123
  this.#runs.delete(controller);
@@ -6411,7 +7170,7 @@ var PeerChatRuntime = class {
6411
7170
  if (generation !== this.#generation) throw new Error("Peer connection changed; old result will not be replayed.");
6412
7171
  return this.host.send(PeerMessageSchema.parse({
6413
7172
  version: 1,
6414
- messageId: randomUUID7(),
7173
+ messageId: randomUUID9(),
6415
7174
  requestId: message.messageId,
6416
7175
  sourceSessionId: message.targetSessionId,
6417
7176
  targetSessionId: message.sourceSessionId,
@@ -6889,7 +7648,7 @@ var SessionInventory = class {
6889
7648
  };
6890
7649
 
6891
7650
  // src/snapshot-audience.ts
6892
- import { createHash as createHash12 } from "node:crypto";
7651
+ import { createHash as createHash13 } from "node:crypto";
6893
7652
  var SnapshotAudience = class {
6894
7653
  constructor(send) {
6895
7654
  this.send = send;
@@ -6918,7 +7677,7 @@ var SnapshotAudience = class {
6918
7677
  async publish(snapshot, recipient) {
6919
7678
  const generation = this.#generation;
6920
7679
  const { sequence: _sequence, generatedAt: _generatedAt, ...content } = snapshot;
6921
- const digest = createHash12("sha256").update(JSON.stringify(content)).digest("base64url");
7680
+ const digest = createHash13("sha256").update(JSON.stringify(content)).digest("base64url");
6922
7681
  if (recipient !== void 0) {
6923
7682
  await this.#direct(snapshot, recipient, digest, generation);
6924
7683
  return;
@@ -7050,7 +7809,7 @@ var ConversationAudience = class {
7050
7809
  };
7051
7810
 
7052
7811
  // src/timeline-incremental-transport.ts
7053
- import { createHash as createHash13, randomUUID as randomUUID8 } from "node:crypto";
7812
+ import { createHash as createHash14, randomUUID as randomUUID10 } from "node:crypto";
7054
7813
  import { isDeepStrictEqual } from "node:util";
7055
7814
  function journalDiagnostic(state) {
7056
7815
  return {
@@ -7184,7 +7943,7 @@ var TimelineIncrementalTransport = class {
7184
7943
  }
7185
7944
  #observeColdStep(state, upsert) {
7186
7945
  const cold = state.coldSteps;
7187
- const key = createHash13("sha256").update(JSON.stringify([upsert.activityId, upsert.step.id])).digest("hex");
7946
+ const key = createHash14("sha256").update(JSON.stringify([upsert.activityId, upsert.step.id])).digest("hex");
7188
7947
  const revision = cold.revisions.get(key);
7189
7948
  if (revision !== void 0 && upsert.revision < revision) return false;
7190
7949
  cold.revisions.delete(key);
@@ -7194,7 +7953,7 @@ var TimelineIncrementalTransport = class {
7194
7953
  if (oldest === void 0) break;
7195
7954
  cold.revisions.delete(oldest);
7196
7955
  }
7197
- const fingerprint = createHash13("sha256").update(JSON.stringify(upsert)).digest("hex");
7956
+ const fingerprint = createHash14("sha256").update(JSON.stringify(upsert)).digest("hex");
7198
7957
  const observed = cold.fingerprints.has(fingerprint);
7199
7958
  cold.fingerprints.delete(fingerprint);
7200
7959
  cold.fingerprints.add(fingerprint);
@@ -7327,7 +8086,7 @@ var TimelineIncrementalTransport = class {
7327
8086
  let state = this.#sessions.get(sessionId);
7328
8087
  if (state === void 0) {
7329
8088
  state = {
7330
- epoch: randomUUID8(),
8089
+ epoch: randomUUID10(),
7331
8090
  sequence: 0,
7332
8091
  reason: "initial",
7333
8092
  events: [],
@@ -7476,7 +8235,7 @@ function canAppend(previous, item) {
7476
8235
  }
7477
8236
 
7478
8237
  // src/timeline-image-blob.ts
7479
- import { createHash as createHash14 } from "node:crypto";
8238
+ import { createHash as createHash15 } from "node:crypto";
7480
8239
  var MAX_ACTIVE_PUBLICATIONS = 16;
7481
8240
  var MAX_QUEUED_PUBLICATIONS = 16;
7482
8241
  var QUEUE_TIMEOUT_MS = 15e3;
@@ -7598,7 +8357,7 @@ var TimelineImageBlobPublisher = class {
7598
8357
  const asset = this.images.readAsset(sessionId, sha256);
7599
8358
  const extension = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" }[asset.mimeType];
7600
8359
  if (extension === void 0) throw new TimelineAssetError("IMAGE_BLOB_UNSUPPORTED", "This image requires encrypted transfer");
7601
- if (createHash14("sha256").update(asset.bytes).digest("hex") !== sha256) {
8360
+ if (createHash15("sha256").update(asset.bytes).digest("hex") !== sha256) {
7602
8361
  throw new TimelineAssetError("IMAGE_INVALID", "Image content does not match its reference");
7603
8362
  }
7604
8363
  let bytes;
@@ -8131,11 +8890,26 @@ var PcAgent = class {
8131
8890
  this.research = research;
8132
8891
  this.onPairing = onPairing;
8133
8892
  this.textInputWriter = textInputWriter;
8893
+ this.#encryptedPeers = new EncryptedPeerStore(config.dataDirectory, {
8894
+ userId: config.userId,
8895
+ machineId: identity2.machineId
8896
+ });
8134
8897
  this.#textInput = new DeviceTextInputHandler(textInputWriter);
8135
8898
  if (research?.chat !== void 0) {
8136
8899
  adapter = researchAwareCodingAgentAdapter(adapter, research.chat);
8137
8900
  this.adapter = adapter;
8138
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
+ }
8139
8913
  this.#stopped = new Promise((resolve5) => {
8140
8914
  this.#resolveStopped = resolve5;
8141
8915
  });
@@ -8180,6 +8954,27 @@ var PcAgent = class {
8180
8954
  const handlerOptions = { adapter, config, machineId: identity2.machineId, logger, emit };
8181
8955
  this.#communication = new SessionCommunicationHandler({
8182
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
+ },
8183
8978
  agentRunId: this.#agentRunId,
8184
8979
  enabled: () => this.#communicationNegotiated && this.#machineRegistered,
8185
8980
  publications: this.#publication,
@@ -8326,7 +9121,7 @@ var PcAgent = class {
8326
9121
  return adapter.runPeerTurn(sessionId, prompt, options);
8327
9122
  });
8328
9123
  const reportPeerError = (error) => logger.warn({ error: toErrorDetails(error) }, "peer-chat.failed");
8329
- const a2aClient = new A2aPeerClient({
9124
+ this.#a2aClient = new A2aPeerClient({
8330
9125
  relayUrl: config.relayUrl,
8331
9126
  relayToken: config.relayToken,
8332
9127
  userId: config.userId,
@@ -8338,13 +9133,24 @@ var PcAgent = class {
8338
9133
  machineId: identity2.machineId,
8339
9134
  assertReady: assertPeerReady,
8340
9135
  send: (message) => this.#sendPeerMessage(message),
8341
- createConversation: (request2) => a2aClient.conversation(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
+ },
8342
9146
  runTurn: runPeerTurn,
8343
9147
  reportError: reportPeerError
8344
9148
  });
8345
- this.#a2aServer = new A2aPeerServer({
9149
+ const receiptOwner = createHash16("sha256").update(JSON.stringify([config.userId, identity2.machineId])).digest("hex");
9150
+ this.#createEncryptedServer = (groupId = "legacy") => new A2aPeerServer({
8346
9151
  userId: config.userId,
8347
9152
  appVersion,
9153
+ receiptDirectory: join12(config.dataDirectory, "a2a-receipts", receiptOwner, groupId),
8348
9154
  assertReady: () => {
8349
9155
  assertPeerReady();
8350
9156
  if (!this.#a2aNegotiated) throw new Error("Relay has not negotiated A2A support.");
@@ -8357,6 +9163,7 @@ var PcAgent = class {
8357
9163
  runTurn: runPeerTurn,
8358
9164
  reportError: reportPeerError
8359
9165
  });
9166
+ this.#a2aServer = this.#createEncryptedServer();
8360
9167
  this.#inventoryPublisher = new InventoryPublisher({
8361
9168
  inventory: this.#inventory,
8362
9169
  send: (snapshot, recipient) => this.#sendSnapshot(snapshot, recipient),
@@ -8466,7 +9273,7 @@ var PcAgent = class {
8466
9273
  onInteractionDismissed: (sessionId, interactionRequestId) => {
8467
9274
  const payload = InteractionRespondResultSchema.parse({
8468
9275
  ok: false,
8469
- requestId: randomUUID9(),
9276
+ requestId: randomUUID11(),
8470
9277
  interactionRequestId,
8471
9278
  machineId: this.identity.machineId,
8472
9279
  sessionId,
@@ -8564,8 +9371,8 @@ var PcAgent = class {
8564
9371
  research;
8565
9372
  onPairing;
8566
9373
  textInputWriter;
8567
- #agentRunId = randomUUID9();
8568
- #clientId = randomUUID9();
9374
+ #agentRunId = randomUUID11();
9375
+ #clientId = randomUUID11();
8569
9376
  #socket;
8570
9377
  #relayDiagnostics = new RelayConnectionDiagnostics();
8571
9378
  #cipher;
@@ -8609,11 +9416,21 @@ var PcAgent = class {
8609
9416
  #peerNegotiated = false;
8610
9417
  #peerTransportNegotiated = false;
8611
9418
  #a2aNegotiated = false;
9419
+ #encryptedPeerNegotiated = false;
9420
+ #encryptedOnly = false;
9421
+ #legacyPeerStopped;
8612
9422
  #peerChatEnabled;
8613
9423
  #peerPreferenceRevision = 0;
8614
9424
  #peerRegistrationRevision = -1;
8615
9425
  #peerChat;
8616
9426
  #a2aServer;
9427
+ #encryptedPeers;
9428
+ #encryptedA2aServers = /* @__PURE__ */ new Map();
9429
+ #createEncryptedServer;
9430
+ #a2aClient;
9431
+ #revocationAbort = new AbortController();
9432
+ #revocationWork;
9433
+ #revocationTimer;
8617
9434
  #communication;
8618
9435
  #textInput;
8619
9436
  #textInputClients = /* @__PURE__ */ new Map();
@@ -8654,6 +9471,7 @@ var PcAgent = class {
8654
9471
  );
8655
9472
  try {
8656
9473
  await this.pairingProvider.enableApproval?.();
9474
+ await this.#encryptedPeers.start();
8657
9475
  await this.adapter.start();
8658
9476
  this.logger.info({ codingAgent: this.adapter.agentId }, "coding-agent.started");
8659
9477
  if (!this.#stopping) {
@@ -8716,6 +9534,59 @@ var PcAgent = class {
8716
9534
  }
8717
9535
  return this.#peerChat.run(request2, signal);
8718
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
+ }
8719
9590
  async setPeerChatEnabled(enabled) {
8720
9591
  if (this.adapter.setPeerChatEnabled === void 0 || this.adapter.runPeerTurn === void 0) {
8721
9592
  throw new Error("This coding agent does not support peer chat.");
@@ -8727,6 +9598,7 @@ var PcAgent = class {
8727
9598
  const reason = new Error("Peer chat is disabled on this PC.");
8728
9599
  this.#peerChat.reset(reason, true);
8729
9600
  this.#a2aServer.reset(reason);
9601
+ for (const server of this.#encryptedA2aServers.values()) server.reset(reason);
8730
9602
  }
8731
9603
  this.#peerNegotiated = false;
8732
9604
  try {
@@ -8755,24 +9627,24 @@ var PcAgent = class {
8755
9627
  return Promise.reject(new Error("Peer channel is offline or unsupported; nothing will be queued."));
8756
9628
  }
8757
9629
  return new Promise((resolve5, reject) => {
8758
- const timer = setTimeout(() => fail4(new Error("Peer forwarding acknowledgement timed out; delivery is unknown.")), ACK_TIMEOUT_MS);
8759
- const fail4 = (error) => {
9630
+ const timer = setTimeout(() => fail3(new Error("Peer forwarding acknowledgement timed out; delivery is unknown.")), ACK_TIMEOUT_MS);
9631
+ const fail3 = (error) => {
8760
9632
  clearTimeout(timer);
8761
- this.#pendingAcks.delete(fail4);
9633
+ this.#pendingAcks.delete(fail3);
8762
9634
  reject(error);
8763
9635
  };
8764
- this.#pendingAcks.add(fail4);
9636
+ this.#pendingAcks.add(fail3);
8765
9637
  try {
8766
9638
  this.#socket.emit("peer.message", message, (rawAck) => {
8767
9639
  clearTimeout(timer);
8768
- if (!this.#pendingAcks.delete(fail4)) return;
9640
+ if (!this.#pendingAcks.delete(fail3)) return;
8769
9641
  const ack = OperationAckSchema.safeParse(rawAck);
8770
9642
  if (!ack.success) reject(new Error("Relay sent an invalid peer forwarding acknowledgement."));
8771
9643
  else if (!ack.data.ok) reject(new Error(`${ack.data.code}: ${ack.data.message}`));
8772
9644
  else resolve5();
8773
9645
  });
8774
9646
  } catch (error) {
8775
- fail4(error instanceof Error ? error : new Error(String(error)));
9647
+ fail3(error instanceof Error ? error : new Error(String(error)));
8776
9648
  }
8777
9649
  });
8778
9650
  }
@@ -8874,7 +9746,7 @@ var PcAgent = class {
8874
9746
  }
8875
9747
  }
8876
9748
  #hasPendingUpgradeWork() {
8877
- 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;
8878
9750
  }
8879
9751
  async #admitRequest(request2, event, handle) {
8880
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 ?? "")) {
@@ -8911,9 +9783,12 @@ var PcAgent = class {
8911
9783
  return this.#stopped;
8912
9784
  }
8913
9785
  this.#stopping = true;
9786
+ clearTimeout(this.#revocationTimer);
9787
+ this.#revocationAbort.abort(new Error("PC Agent stopped"));
8914
9788
  const imagesStopped = this.#imageBlob?.close();
8915
9789
  const peerStopped = this.#peerChat.close();
8916
9790
  const a2aStopped = this.#a2aServer.close();
9791
+ const encryptedStopped = Promise.all([...this.#encryptedA2aServers.values()].map((server) => server.close()));
8917
9792
  this.#machineRegistered = false;
8918
9793
  this.#textInputClients.clear();
8919
9794
  this.#initialSyncGeneration = void 0;
@@ -8921,6 +9796,7 @@ var PcAgent = class {
8921
9796
  this.#peerNegotiated = false;
8922
9797
  this.#peerTransportNegotiated = false;
8923
9798
  this.#a2aNegotiated = false;
9799
+ this.#encryptedPeerNegotiated = false;
8924
9800
  this.#connectionGeneration += 1;
8925
9801
  this.#cancelSnapshotSync();
8926
9802
  this.#clearRelayReconnect();
@@ -8940,6 +9816,8 @@ var PcAgent = class {
8940
9816
  this.adapter.stop(),
8941
9817
  peerStopped,
8942
9818
  a2aStopped,
9819
+ encryptedStopped,
9820
+ ...this.#revocationWork === void 0 ? [] : [this.#revocationWork],
8943
9821
  ...imagesStopped === void 0 ? [] : [imagesStopped],
8944
9822
  ...this.research === void 0 ? [] : [this.research.stop()]
8945
9823
  ]);
@@ -9001,11 +9879,15 @@ var PcAgent = class {
9001
9879
  this.#peerNegotiated = false;
9002
9880
  this.#peerTransportNegotiated = false;
9003
9881
  this.#a2aNegotiated = false;
9882
+ this.#encryptedPeerNegotiated = false;
9004
9883
  this.#peerChat.reset(new Error("Relay disconnected; peer conversation will not be replayed."));
9005
9884
  this.#imageBlob?.reset();
9006
9885
  this.#imageStorage = void 0;
9007
9886
  this.#imagePolicyRevision += 1;
9008
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
+ }
9009
9891
  this.#conversationAudience.reset();
9010
9892
  this.#cancelSnapshotSync();
9011
9893
  this.#persistentInteractionClients.clear();
@@ -9053,6 +9935,7 @@ var PcAgent = class {
9053
9935
  });
9054
9936
  this.#socket.on("peer.message", (delivery) => {
9055
9937
  try {
9938
+ if (this.#encryptedOnly || this.#encryptedPeers.requiresEncryption) throw new Error("Plaintext peer delivery is disabled");
9056
9939
  this.#peerChat.receive(delivery);
9057
9940
  } catch (error) {
9058
9941
  this.logger.warn({ error: toErrorDetails(error) }, "peer-chat.delivery-rejected");
@@ -9143,8 +10026,8 @@ var PcAgent = class {
9143
10026
  this.logger.warn("a2a.request.missing-ack");
9144
10027
  return;
9145
10028
  }
9146
- void this.#a2aServer.handle(request2).then(ack, (error) => {
9147
- this.logger.warn({ error: toErrorDetails(error) }, "a2a.request.failed");
10029
+ void this.#handleA2aRequest(request2).then(ack, () => {
10030
+ this.logger.warn("a2a.request.failed");
9148
10031
  ack({ status: 500, body: JSON.stringify({ error: "A2A request failed on the PC." }) });
9149
10032
  });
9150
10033
  });
@@ -9298,6 +10181,8 @@ var PcAgent = class {
9298
10181
  this.#peerTransportNegotiated = hello.capabilities?.includes(PC_PEER_CHAT_CAPABILITY) === true && ack.capabilities?.includes(PC_PEER_CHAT_CAPABILITY) === true;
9299
10182
  this.#peerNegotiated = this.#peerChatEnabled && peerRevision === this.#peerPreferenceRevision && this.#peerTransportNegotiated;
9300
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();
9301
10186
  this.#relayRegistrationStatus = { state: "registered" };
9302
10187
  this.#flushBufferedConversationItems();
9303
10188
  this.#flushBufferedInteractionRequests();
@@ -9318,7 +10203,7 @@ var PcAgent = class {
9318
10203
  SESSION_IMAGE_CLIENT_VERIFIED_CAPABILITY,
9319
10204
  ...this.#sessionImagesEnabled && this.sessionImageStorage !== void 0 ? [PC_IMAGE_BLOB_POLICY_CAPABILITY, TIMELINE_IMAGE_BLOB_CAPABILITY] : [],
9320
10205
  ...this.#peerChatEnabled && this.adapter.runPeerTurn !== void 0 ? [PC_PEER_CHAT_CAPABILITY] : [],
9321
- ...this.adapter.runPeerTurn !== void 0 ? [PC_A2A_CAPABILITY] : [],
10206
+ ...this.adapter.runPeerTurn !== void 0 ? [PC_A2A_CAPABILITY, PC_ENCRYPTED_PEER_CAPABILITY] : [],
9322
10207
  SESSION_PROMPT_SUBMISSION_TIME_CAPABILITY,
9323
10208
  ...this.adapter.supportsAssistantPreview === true ? [SESSION_ASSISTANT_PREVIEW_CAPABILITY] : [],
9324
10209
  ...this.#communication.capabilities.filter((capability) => capability !== TIMELINE_IMAGE_BLOB_CAPABILITY),
@@ -9692,17 +10577,17 @@ var PcAgent = class {
9692
10577
  return;
9693
10578
  }
9694
10579
  const timer = setTimeout(() => {
9695
- fail4(new Error(`${event} acknowledgement timed out`));
10580
+ fail3(new Error(`${event} acknowledgement timed out`));
9696
10581
  }, ACK_TIMEOUT_MS);
9697
- const fail4 = (error) => {
10582
+ const fail3 = (error) => {
9698
10583
  clearTimeout(timer);
9699
- this.#pendingAcks.delete(fail4);
10584
+ this.#pendingAcks.delete(fail3);
9700
10585
  reject(error);
9701
10586
  };
9702
- this.#pendingAcks.add(fail4);
10587
+ this.#pendingAcks.add(fail3);
9703
10588
  const receiveAck = (ack) => {
9704
10589
  clearTimeout(timer);
9705
- this.#pendingAcks.delete(fail4);
10590
+ this.#pendingAcks.delete(fail3);
9706
10591
  resolve5(ack);
9707
10592
  };
9708
10593
  try {
@@ -9717,7 +10602,7 @@ var PcAgent = class {
9717
10602
  }
9718
10603
  } catch (error) {
9719
10604
  clearTimeout(timer);
9720
- this.#pendingAcks.delete(fail4);
10605
+ this.#pendingAcks.delete(fail3);
9721
10606
  reject(error);
9722
10607
  }
9723
10608
  });
@@ -9829,45 +10714,45 @@ function contextItem(item) {
9829
10714
 
9830
10715
  // src/research-sessions.ts
9831
10716
  import { execFile as execFile3 } from "node:child_process";
9832
- import { createHash as createHash15, randomUUID as randomUUID12 } from "node:crypto";
9833
- import { mkdir as mkdir5, lstat as lstat8, realpath as realpath8 } from "node:fs/promises";
9834
- import { join as join12, resolve as resolve4 } from "node:path";
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";
9835
10720
  import { promisify as promisify4 } from "node:util";
9836
- import { z as z9 } from "zod";
10721
+ import { z as z11 } from "zod";
9837
10722
 
9838
10723
  // src/research-thread-store.ts
9839
- import { randomUUID as randomUUID10 } from "node:crypto";
9840
- import { mkdir as mkdir4, readFile as readFile2, rename as rename2, rm as rm2, lstat as lstat6, realpath as realpath7, writeFile as writeFile3 } from "node:fs/promises";
9841
- import { join as join10, resolve as resolve3 } from "node:path";
9842
- import { z as z7 } from "zod";
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";
9843
10728
  var RESEARCH_PROFILE = "research-readonly";
9844
10729
  var RESEARCH_PROFILE_VERSION = 1;
9845
10730
  var MAX_THREADS = 256;
9846
- var recordSchema = z7.object({
9847
- threadId: z7.string().uuid(),
9848
- researchSessionId: z7.string().uuid(),
9849
- parentSessionId: z7.string().min(1).max(256),
9850
- operationId: z7.string().min(1).max(256),
9851
- fingerprint: z7.string().min(1).max(128),
9852
- title: z7.string().min(1).max(200),
9853
- profile: z7.literal(RESEARCH_PROFILE),
9854
- profileVersion: z7.literal(RESEARCH_PROFILE_VERSION),
9855
- workingDirectory: z7.string().min(1).max(8192),
9856
- rootIdentity: z7.string().min(1).max(128),
9857
- contextAnchor: z7.string().min(1).max(256),
9858
- contextSampledAt: z7.string().datetime(),
9859
- contextTruncated: z7.boolean(),
9860
- chatVersion: z7.literal(1).optional(),
9861
- createdAt: z7.string().datetime(),
9862
- state: z7.enum(["creating", "ready", "uncertain", "failed", "deleting"]),
9863
- errorCode: z7.string().max(128).optional()
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()
9864
10749
  }).strict();
9865
- var documentSchema = z7.object({
9866
- version: z7.literal(1),
9867
- threads: z7.array(recordSchema).max(MAX_THREADS),
9868
- tombstones: z7.array(z7.object({
9869
- researchSessionId: z7.string().uuid(),
9870
- parentSessionId: z7.string().min(1).max(256)
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)
9871
10756
  }).strict()).max(1e5).optional()
9872
10757
  }).strict();
9873
10758
  var ResearchThreadStore = class {
@@ -9879,21 +10764,21 @@ var ResearchThreadStore = class {
9879
10764
  #mutation = Promise.resolve();
9880
10765
  constructor(dataDirectory) {
9881
10766
  this.directory = resolve3(dataDirectory, "research");
9882
- this.#file = join10(this.directory, "threads.json");
10767
+ this.#file = join13(this.directory, "threads.json");
9883
10768
  }
9884
10769
  initialize() {
9885
10770
  this.#loaded ??= this.#load();
9886
10771
  return this.#loaded;
9887
10772
  }
9888
10773
  async #load() {
9889
- await mkdir4(this.directory, { recursive: true, mode: 448 });
10774
+ await mkdir6(this.directory, { recursive: true, mode: 448 });
9890
10775
  if ((await lstat6(this.directory)).isSymbolicLink() || await realpath7(this.directory) !== this.directory) {
9891
10776
  throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
9892
10777
  }
9893
10778
  try {
9894
10779
  const metadata = await lstat6(this.#file);
9895
10780
  if (metadata.isSymbolicLink() || metadata.size > 32 * 1024 * 1024) throw new ResearchError("RESEARCH_STORE_INVALID");
9896
- const parsed = JSON.parse(await readFile2(this.#file, "utf8"));
10781
+ const parsed = JSON.parse(await readFile4(this.#file, "utf8"));
9897
10782
  const data = documentSchema.parse(parsed);
9898
10783
  for (const tombstone of data.tombstones ?? []) {
9899
10784
  if (this.#tombstones.has(tombstone.researchSessionId)) throw new ResearchError("RESEARCH_STORE_INVALID");
@@ -9913,18 +10798,18 @@ var ResearchThreadStore = class {
9913
10798
  }
9914
10799
  }
9915
10800
  async #write(records2, tombstones = this.#tombstones) {
9916
- const staging = join10(this.directory, `threads-${randomUUID10()}.pending`);
10801
+ const staging = join13(this.directory, `threads-${randomUUID12()}.pending`);
9917
10802
  try {
9918
- await writeFile3(staging, JSON.stringify({
10803
+ await writeFile5(staging, JSON.stringify({
9919
10804
  version: 1,
9920
10805
  threads: [...records2.values()],
9921
10806
  tombstones: [...tombstones].map(([researchSessionId, parentSessionId]) => ({ researchSessionId, parentSessionId }))
9922
10807
  }), { flag: "wx", mode: 384 });
9923
- await rename2(staging, this.#file);
10808
+ await rename4(staging, this.#file);
9924
10809
  this.#records = records2;
9925
10810
  this.#tombstones = tombstones;
9926
10811
  } finally {
9927
- await rm2(staging, { force: true });
10812
+ await rm4(staging, { force: true });
9928
10813
  }
9929
10814
  }
9930
10815
  async #serialized(work) {
@@ -9946,8 +10831,8 @@ var ResearchThreadStore = class {
9946
10831
  }
9947
10832
  const record = recordSchema.parse({
9948
10833
  ...input,
9949
- threadId: randomUUID10(),
9950
- researchSessionId: randomUUID10(),
10834
+ threadId: randomUUID12(),
10835
+ researchSessionId: randomUUID12(),
9951
10836
  profile: RESEARCH_PROFILE,
9952
10837
  profileVersion: RESEARCH_PROFILE_VERSION,
9953
10838
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -10001,27 +10886,27 @@ var ResearchThreadStore = class {
10001
10886
  };
10002
10887
 
10003
10888
  // src/research-chat-store.ts
10004
- import { randomUUID as randomUUID11 } from "node:crypto";
10005
- import { lstat as lstat7, readFile as readFile3, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
10006
- import { join as join11 } from "node:path";
10007
- import { z as z8 } from "zod";
10008
- var receipt = z8.object({
10009
- operationId: z8.string().min(1).max(256),
10010
- fingerprint: z8.string().min(1).max(128),
10011
- promptHash: z8.string().min(1).max(128),
10012
- ordinal: z8.number().int().nonnegative(),
10013
- submittedAt: z8.string().datetime(),
10014
- state: z8.enum(["sending", "accepted"]),
10015
- messageId: z8.string().min(1).max(256).optional(),
10016
- deliveryState: z8.enum(["queued", "processing"])
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"])
10017
10902
  }).strict();
10018
- var stateSchema = z8.object({
10019
- version: z8.literal(1),
10020
- modelId: z8.string().min(1).max(256).optional(),
10021
- reasoningEffort: z8.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
10022
- seed: z8.string().max(3e5).optional(),
10023
- seedState: z8.enum(["pending", "submitted", "none"]),
10024
- receipts: z8.array(receipt).max(1e4)
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)
10025
10910
  }).strict().superRefine((state, ctx) => {
10026
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) {
10027
10912
  ctx.addIssue({ code: "custom", message: "Invalid research chat state" });
@@ -10037,7 +10922,7 @@ var ResearchChatStore = class {
10037
10922
  return this.#states.get(sessionId);
10038
10923
  }
10039
10924
  #file(sessionId) {
10040
- return join11(this.directory, `chat-${z8.string().uuid().parse(sessionId)}.json`);
10925
+ return join14(this.directory, `chat-${z10.string().uuid().parse(sessionId)}.json`);
10041
10926
  }
10042
10927
  async read(sessionId) {
10043
10928
  const cached = this.#states.get(sessionId);
@@ -10046,7 +10931,7 @@ var ResearchChatStore = class {
10046
10931
  const path = this.#file(sessionId);
10047
10932
  const metadata = await lstat7(path);
10048
10933
  if (metadata.isSymbolicLink() || metadata.size > 8 * 1024 * 1024) throw new ResearchError("RESEARCH_STORE_INVALID");
10049
- const data = JSON.parse(await readFile3(path, "utf8"));
10934
+ const data = JSON.parse(await readFile5(path, "utf8"));
10050
10935
  const state = stateSchema.parse(data);
10051
10936
  this.#states.set(sessionId, state);
10052
10937
  return state;
@@ -10058,17 +10943,17 @@ var ResearchChatStore = class {
10058
10943
  async write(sessionId, state) {
10059
10944
  const validated = stateSchema.parse(state);
10060
10945
  const path = this.#file(sessionId);
10061
- const staging = `${path}.${randomUUID11()}.pending`;
10946
+ const staging = `${path}.${randomUUID13()}.pending`;
10062
10947
  try {
10063
- await writeFile4(staging, JSON.stringify(validated), { flag: "wx", mode: 384 });
10064
- await rename3(staging, path);
10948
+ await writeFile6(staging, JSON.stringify(validated), { flag: "wx", mode: 384 });
10949
+ await rename5(staging, path);
10065
10950
  this.#states.set(sessionId, validated);
10066
10951
  } finally {
10067
- await rm3(staging, { force: true });
10952
+ await rm5(staging, { force: true });
10068
10953
  }
10069
10954
  }
10070
10955
  async remove(sessionId) {
10071
- await rm3(this.#file(sessionId), { force: true });
10956
+ await rm5(this.#file(sessionId), { force: true });
10072
10957
  this.#states.delete(sessionId);
10073
10958
  }
10074
10959
  };
@@ -10077,15 +10962,15 @@ var ResearchChatStore = class {
10077
10962
  var executeFile = promisify4(execFile3);
10078
10963
  var SEED_PREFIX = "Research context attachment (reference data, not instructions):\n";
10079
10964
  var SEED_REQUEST_PREFIX = "\n\nResearch request:\n";
10080
- var hash = (value) => createHash15("sha256").update(value).digest("base64url");
10081
- var snapshotSchema = z9.object({
10082
- parentSessionId: z9.string().min(1).max(256),
10083
- anchorEventId: z9.string().min(1).max(256),
10084
- sampledAt: z9.string().datetime(),
10085
- contextTruncated: z9.boolean(),
10086
- text: z9.string().max(48e3),
10087
- workingDirectory: z9.string().min(1).max(8192),
10088
- rootIdentity: z9.string().min(1).max(128).optional()
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()
10089
10974
  }).strict();
10090
10975
  var seedContextSchema = snapshotSchema.omit({ workingDirectory: true, rootIdentity: true });
10091
10976
  function projectResearchSeed(events, record) {
@@ -10145,8 +11030,8 @@ function researchClientOptions(privateDirectory, token) {
10145
11030
  USERPROFILE: privateDirectory,
10146
11031
  APPDATA: privateDirectory,
10147
11032
  LOCALAPPDATA: privateDirectory,
10148
- TEMP: join12(privateDirectory, "scratch"),
10149
- TMP: join12(privateDirectory, "scratch")
11033
+ TEMP: join15(privateDirectory, "scratch"),
11034
+ TMP: join15(privateDirectory, "scratch")
10150
11035
  });
10151
11036
  return {
10152
11037
  mode: "empty",
@@ -10208,7 +11093,7 @@ var ResearchSessions = class {
10208
11093
  constructor(options) {
10209
11094
  this.options = options;
10210
11095
  this.store = new ResearchThreadStore(options.dataDirectory);
10211
- this.#privateDirectory = join12(this.store.directory, "runtime");
11096
+ this.#privateDirectory = join15(this.store.directory, "runtime");
10212
11097
  this.#chat = new ResearchChatStore(this.store.directory);
10213
11098
  this.#projection = new LiveTimelineProjection({
10214
11099
  state: (id) => this.#state(id),
@@ -10229,7 +11114,7 @@ var ResearchSessions = class {
10229
11114
  });
10230
11115
  }
10231
11116
  options;
10232
- #generation = randomUUID12();
11117
+ #generation = randomUUID14();
10233
11118
  store;
10234
11119
  #privateDirectory;
10235
11120
  #active = /* @__PURE__ */ new Map();
@@ -10298,7 +11183,7 @@ var ResearchSessions = class {
10298
11183
  this.#failedClient = void 0;
10299
11184
  }
10300
11185
  await this.store.initialize();
10301
- await mkdir5(join12(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
11186
+ await mkdir7(join15(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
10302
11187
  if ((await lstat8(this.#privateDirectory)).isSymbolicLink() || await realpath8(this.#privateDirectory) !== resolve4(this.#privateDirectory)) {
10303
11188
  throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
10304
11189
  }
@@ -10486,9 +11371,9 @@ var ResearchSessions = class {
10486
11371
  assertAccess?.();
10487
11372
  const snapshot = snapshotSchema.parse(input.snapshot);
10488
11373
  if (snapshot.parentSessionId !== input.parentSessionId) throw new ResearchError("RESEARCH_SOURCE_MISMATCH");
10489
- const title = z9.string().trim().min(1).max(200).parse(input.title ?? "Research");
10490
- const prompt = z9.string().trim().min(1).max(16e3).parse(input.prompt ?? "Acknowledge the context briefly and wait for my research question.");
10491
- const fingerprint = createHash15("sha256").update(JSON.stringify({
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({
10492
11377
  parentSessionId: input.parentSessionId,
10493
11378
  title,
10494
11379
  prompt,
@@ -10522,7 +11407,7 @@ var ResearchSessions = class {
10522
11407
  let session;
10523
11408
  try {
10524
11409
  const configuration = input.configuration ?? await this.options.sourceConfiguration?.(input.parentSessionId);
10525
- const reasoning = z9.enum(["low", "medium", "high", "xhigh", "max"]).safeParse(configuration?.reasoningEffort);
11410
+ const reasoning = z11.enum(["low", "medium", "high", "xhigh", "max"]).safeParse(configuration?.reasoningEffort);
10526
11411
  if (configuration !== void 0 && !reasoning.success && !["default", "unknown"].includes(configuration.reasoningEffort)) {
10527
11412
  throw new ResearchError("RESEARCH_CONFIGURATION_UNSUPPORTED");
10528
11413
  }
@@ -10646,7 +11531,7 @@ var ResearchSessions = class {
10646
11531
  const assertAccess = this.#capture(record);
10647
11532
  assertAccess();
10648
11533
  if (options.metadataOnly === true) throw new ResearchError("RESEARCH_SESSION_ISOLATED");
10649
- const pageSize = z9.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
11534
+ const pageSize = z11.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
10650
11535
  const result = await this.#state(sessionId).timelineReads.read({
10651
11536
  ...options.cursor === void 0 ? {} : { cursor: options.cursor },
10652
11537
  pageSize,
@@ -10689,13 +11574,13 @@ var ResearchSessions = class {
10689
11574
  compactDisabledReason: "Research context compaction is unavailable"
10690
11575
  });
10691
11576
  }
10692
- async send(sessionId, text, operationId = randomUUID12()) {
11577
+ async send(sessionId, text, operationId = randomUUID14()) {
10693
11578
  if (this.#active.get(sessionId)?.runtime.activity.busy) throw new ResearchError("RESEARCH_BUSY");
10694
11579
  return (await this.sendPrompt(sessionId, text, "immediate", operationId)).messageId;
10695
11580
  }
10696
11581
  async sendPrompt(sessionId, text, mode, operationId) {
10697
- const prompt = z9.string().trim().min(1).max(16e3).parse(text);
10698
- z9.string().min(1).max(256).parse(operationId);
11582
+ const prompt = z11.string().trim().min(1).max(16e3).parse(text);
11583
+ z11.string().min(1).max(256).parse(operationId);
10699
11584
  const fingerprint = hash(JSON.stringify({ prompt, mode }));
10700
11585
  const running = this.#sending.get(sessionId);
10701
11586
  if (running !== void 0 && running.operationId === operationId) {
@@ -10984,23 +11869,23 @@ function createResearchWorkbench(options) {
10984
11869
  }
10985
11870
 
10986
11871
  // src/initialize.ts
10987
- var ConfigSchema = z10.object({
10988
- dataDirectory: z10.string().min(1),
10989
- relayUrl: z10.url().refine((value) => ["https:", "http:"].includes(new URL(value).protocol)),
10990
- relayToken: z10.string().min(24),
10991
- userId: z10.string().trim().min(1).max(256),
10992
- workspaceRoot: z10.string().optional(),
10993
- refreshIntervalMs: z10.number().int().min(5e3).max(36e5).default(3e4),
10994
- heartbeatIntervalMs: z10.number().int().min(5e3).max(12e4).default(15e3),
10995
- exitAfterSnapshot: z10.boolean().default(false),
10996
- groupChatEnabled: z10.boolean().optional(),
10997
- peerChatEnabled: z10.boolean().optional(),
10998
- snapshotSuppressionEnabled: z10.boolean().optional(),
10999
- timelineCompressionEnabled: z10.boolean().optional(),
11000
- timelineIncrementalEnabled: z10.boolean().optional(),
11001
- secureMessagePacketBudget: z10.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).optional(),
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(),
11002
11887
  sessionImages: SessionImagesConfigSchema.optional(),
11003
- sessionImagesEnabled: z10.boolean().optional()
11888
+ sessionImagesEnabled: z12.boolean().optional()
11004
11889
  }).superRefine((config, context) => {
11005
11890
  if ((config.sessionImages !== void 0 || config.sessionImagesEnabled === true) && !SessionImageRelayUrlSchema.safeParse(config.relayUrl).success) {
11006
11891
  context.addIssue({
@@ -11037,7 +11922,7 @@ async function initialize(options) {
11037
11922
  ...options.codingAgent === void 0 ? {} : { codingAgent: options.codingAgent }
11038
11923
  };
11039
11924
  const identity2 = DeviceIdentitySchema.parse(options.identity);
11040
- const appVersion = options.appVersion ?? z10.object({ version: z10.string().min(1) }).parse(JSON.parse(await readFile4(new URL("../package.json", import.meta.url), "utf8"))).version;
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;
11041
11926
  const lease = options.directoryLease ?? await DataDirectoryLease.acquire(dataDirectory);
11042
11927
  let detach;
11043
11928
  let adapter;
@@ -11093,7 +11978,7 @@ async function initialize(options) {
11093
11978
  }, "research.operation.failed")
11094
11979
  });
11095
11980
  class InitializedAgent extends PcAgent {
11096
- identityHash = createHash16("sha256").update(`${config.userId}:${identity2.machineId}:${contentKey.keyId}`).digest("hex");
11981
+ identityHash = createHash18("sha256").update(`${config.userId}:${identity2.machineId}:${contentKey.keyId}`).digest("hex");
11097
11982
  #started;
11098
11983
  #starting;
11099
11984
  #closed;