@agentknight/sdk 0.9.56 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,16 +2,22 @@ import {
2
2
  SessionImageRelayUrlSchema,
3
3
  SessionImagesConfigSchema
4
4
  } from "./chunk-IJPJQF7S.js";
5
+ import {
6
+ ConversationNormalizer,
7
+ ConversationToolLifecycles,
8
+ assistantMessageId
9
+ } from "./chunk-ZDKBJFA2.js";
5
10
  import {
6
11
  isContentfulAssistant
7
- } from "./chunk-5J7BK2Y7.js";
12
+ } from "./chunk-NDEJOXSX.js";
8
13
  import {
9
14
  SessionOperationError
10
- } from "./chunk-L3A736SO.js";
15
+ } from "./chunk-3OIHMMDF.js";
11
16
  import {
12
- CONVERSATION_SOURCE_ID_LIMIT,
13
17
  IdSchema,
14
18
  SESSION_DIRECTORY_LIST_OPERATION,
19
+ SESSION_DIRECTORY_MAX_ENTRIES,
20
+ SESSION_DIRECTORY_MAX_RESPONSE_BYTES,
15
21
  SESSION_FILE_DOWNLOAD_OPERATION,
16
22
  SESSION_FILE_READ_OPERATION,
17
23
  SESSION_IMAGE_API_PATH,
@@ -30,20 +36,25 @@ import {
30
36
  TIMELINE_SYNC_OPERATION,
31
37
  TimelineResyncReasonSchema,
32
38
  WORKBENCH_OPERATIONS,
39
+ WORKBENCH_REASONING_PAGE_SIZE,
40
+ WORKBENCH_REASONING_TEXT_LIMIT,
33
41
  WorkbenchAskResultSchema,
34
42
  WorkbenchCommandResultSchema,
35
43
  WorkbenchCommandSchema,
36
44
  WorkbenchCompactResultSchema,
37
45
  WorkbenchInsightsSchema,
38
46
  WorkbenchQueueMutationResultSchema,
39
- WorkbenchQueueSnapshotSchema
40
- } from "./chunk-K5CMKBW6.js";
47
+ WorkbenchQueueSnapshotSchema,
48
+ WorkbenchReasoningPageSchema,
49
+ WorkbenchReasoningRequestSchema,
50
+ isSafeSessionDirectoryPath
51
+ } from "./chunk-LO4ZRE77.js";
41
52
 
42
53
  // src/session-image-uploader.ts
43
54
  import { createHash } from "node:crypto";
44
55
  import { setTimeout as delay } from "node:timers/promises";
45
56
  import { z } from "zod";
46
- var MAX_ACTIVE_UPLOADS = 3;
57
+ var MAX_ACTIVE_UPLOADS = 16;
47
58
  var MAX_JSON_BYTES = 16 * 1024;
48
59
  var REQUEST_TIMEOUT_MS = 2e4;
49
60
  var UPLOAD_TIMEOUT_MS = 7e4;
@@ -55,8 +66,12 @@ var UploaderConfigSchema = z.object({
55
66
  machineId: IdSchema,
56
67
  storageAccount: SessionImagesConfigSchema.shape.storageAccount,
57
68
  storageContainer: SessionImagesConfigSchema.shape.storageContainer,
58
- mode: SessionImageStorageSchema.shape.mode.optional()
59
- });
69
+ mode: SessionImageStorageSchema.shape.mode.optional(),
70
+ clientVerifiedUploads: z.boolean().default(false)
71
+ }).refine(
72
+ (value) => !value.clientVerifiedUploads || value.mode === "direct",
73
+ "Client-verified uploads require negotiated direct storage"
74
+ );
60
75
  function safeCause(error) {
61
76
  if (error instanceof SessionImageUploadError) return error;
62
77
  if (error instanceof z.ZodError) return new Error("Schema validation failed.");
@@ -158,7 +173,11 @@ var SessionImageUploader = class {
158
173
  const bytes = Buffer.from(source);
159
174
  const dimensions = await this.#dimensions(bytes);
160
175
  const hash = digest(bytes);
161
- const request = parse(SessionImageUploadRequestSchema, { ...scope, sizeBytes: bytes.length }, "source");
176
+ const request = parse(SessionImageUploadRequestSchema, {
177
+ ...scope,
178
+ sizeBytes: bytes.length,
179
+ ...this.#config.clientVerifiedUploads ? { verifiedContent: { ...dimensions, sha256: hash } } : {}
180
+ }, "source");
162
181
  revalidate("reserve");
163
182
  const upload = await this.#json(
164
183
  `${SESSION_IMAGE_API_PATH}/uploads`,
@@ -238,6 +257,7 @@ var SessionImageUploader = class {
238
257
  try {
239
258
  const metadata = await decoder.metadata();
240
259
  assert(metadata.format === "webp" && metadata.width !== void 0 && metadata.height !== void 0 && metadata.width > 0 && metadata.height > 0 && (metadata.pages ?? 1) === 1 && metadata.width * metadata.height <= SESSION_IMAGE_MAX_PIXELS, "IMAGE_CONTENT_INVALID", "source");
260
+ if (this.#config.clientVerifiedUploads) await decoder.stats();
241
261
  return { width: metadata.width, height: metadata.height };
242
262
  } finally {
243
263
  decoder.destroy();
@@ -267,7 +287,8 @@ var SessionImageUploader = class {
267
287
  }
268
288
  const { storageAccount, storageContainer, userId, machineId } = this.#config;
269
289
  const host = `${storageAccount}.blob.core.windows.net`;
270
- const path = `/${storageContainer}/uploads/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
290
+ const prefix = this.#config.clientVerifiedUploads ? "images" : "uploads";
291
+ const path = `/${storageContainer}/${prefix}/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
271
292
  const url = new URL(upload.uploadUrl);
272
293
  const query = url.searchParams;
273
294
  const allowed = /* @__PURE__ */ new Set(["sv", "spr", "st", "se", "sr", "sp", "sig", "skoid", "sktid", "skt", "ske", "sks", "skv"]);
@@ -353,7 +374,7 @@ var SessionImageUploader = class {
353
374
  try {
354
375
  return await this.#attempt(url, init, stage, signal, consume);
355
376
  } catch (error) {
356
- const retryable = error instanceof SessionImageUploadError && error.code !== "IMAGE_QUOTA_EXCEEDED" && (error.status === 429 && error.retryAfterMs !== void 0 && (stage !== "reserve" || error.code === "IMAGE_CAPACITY_EXCEEDED") || stage !== "reserve" && (error.status === 503 || error.status === 500 || stage === "complete" && error.status === 409 && error.code === "IMAGE_BUSY"));
377
+ const retryable = error instanceof SessionImageUploadError && error.code !== "IMAGE_QUOTA_EXCEEDED" && (error.status === 429 && error.retryAfterMs !== void 0 && (stage !== "reserve" || error.code === "IMAGE_CAPACITY_EXCEEDED") || (stage === "reserve" || stage === "complete") && error.status === 409 && error.code === "IMAGE_BUSY" || stage !== "reserve" && (error.status === 503 || error.status === 500));
357
378
  if (!retryable || attempt >= 2 || signal.aborted) throw error;
358
379
  const wait = Math.max(error.retryAfterMs ?? 0, 250 * 2 ** attempt + Math.floor(Math.random() * 250));
359
380
  if (wait > 5e3) throw error;
@@ -753,1213 +774,6 @@ var OperationMetrics = class {
753
774
  }
754
775
  };
755
776
 
756
- // src/conversation-normalizer.ts
757
- import { createHash as createHash3 } from "node:crypto";
758
- var SUMMARY_LIMIT = 4096;
759
- var IDENTIFIER_LIMIT = 256;
760
- var TASK_COMPLETE_TOOL_NAME = "task_complete";
761
- var MAX_INLINE_IMAGE_BYTES = 3 * 1024 * 1024;
762
- var MAX_INLINE_IMAGE_MESSAGE_BYTES = 3 * 1024 * 1024;
763
- var MAX_INLINE_IMAGES_PER_MESSAGE = 4;
764
- var SUPPORTED_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set([
765
- "image/gif",
766
- "image/jpeg",
767
- "image/png",
768
- "image/webp"
769
- ]);
770
- function splitToolImages(images) {
771
- const groups = [];
772
- let group = [];
773
- let groupBytes = 0;
774
- for (const image of images) {
775
- const imageBytes = image.attachment.byteLength ?? 0;
776
- if (group.length > 0 && (group.length >= MAX_INLINE_IMAGES_PER_MESSAGE || groupBytes + imageBytes > MAX_INLINE_IMAGE_MESSAGE_BYTES)) {
777
- groups.push(group);
778
- group = [];
779
- groupBytes = 0;
780
- }
781
- group.push(image);
782
- groupBytes += imageBytes;
783
- }
784
- if (group.length > 0) {
785
- groups.push(group);
786
- }
787
- return groups;
788
- }
789
- function protocolId(value) {
790
- if (value.length <= IDENTIFIER_LIMIT) {
791
- return value;
792
- }
793
- const digest2 = createHash3("sha256").update(value).digest("hex");
794
- return `sha256:${digest2}`;
795
- }
796
- function scopedId(scope, value) {
797
- const id = `${scope}:${value}`;
798
- if (id.length <= IDENTIFIER_LIMIT) {
799
- return id;
800
- }
801
- const digest2 = createHash3("sha256").update(value).digest("hex");
802
- return `${scope}:sha256:${digest2}`;
803
- }
804
- function assistantMessageId(data) {
805
- return scopedId("assistant", data.apiCallId ?? data.messageId);
806
- }
807
- function eventRevision(timestamp, previousRevision) {
808
- const timestampRevision = Date.parse(timestamp);
809
- if (!Number.isSafeInteger(timestampRevision) || timestampRevision < 0) {
810
- throw new Error(`Invalid SDK event timestamp: ${timestamp}`);
811
- }
812
- const revision = previousRevision === void 0 || timestampRevision > previousRevision ? timestampRevision : previousRevision + 1;
813
- if (!Number.isSafeInteger(revision)) {
814
- throw new Error(`SDK event revision exceeds the safe integer range: ${timestamp}`);
815
- }
816
- return revision;
817
- }
818
- function removeInternalMarkup(value) {
819
- return value.replace(
820
- /<skill-context\b[^>]*>[\s\S]*?<\/skill-context\s*>/giu,
821
- " "
822
- ).replace(/<skill-context\b[^>]*>[\s\S]*/giu, " ").replace(/<\/?system_notification\b[^>]*>/giu, " ");
823
- }
824
- function stripInternalMarkup(value) {
825
- return removeInternalMarkup(value).replace(/\s+/gu, " ").trim();
826
- }
827
- function limitSummary(value, limit = SUMMARY_LIMIT) {
828
- if (value.length <= limit) {
829
- return value;
830
- }
831
- return `${value.slice(0, limit - 1)}\u2026`;
832
- }
833
- function boundedText(value, limit, fallback) {
834
- const normalized = stripInternalMarkup(value);
835
- return limitSummary(normalized.length === 0 ? fallback : normalized, limit);
836
- }
837
- function boundedOptionalText(value, limit) {
838
- if (value === void 0) {
839
- return void 0;
840
- }
841
- const normalized = stripInternalMarkup(value);
842
- return normalized.length === 0 ? void 0 : limitSummary(normalized, limit);
843
- }
844
- function boundedOptionalMessageContent(value, limit) {
845
- if (value === void 0) {
846
- return void 0;
847
- }
848
- const normalized = removeInternalMarkup(value).trim();
849
- return normalized.length === 0 ? void 0 : limitSummary(normalized, limit);
850
- }
851
- function appendSourceEventId(sourceEventIds, eventId) {
852
- return [...sourceEventIds, eventId].slice(-CONVERSATION_SOURCE_ID_LIMIT);
853
- }
854
- function appendOptionalSourceId(sourceIds, sourceId) {
855
- if (sourceId === void 0) {
856
- return sourceIds === void 0 ? void 0 : [...sourceIds];
857
- }
858
- return [...sourceIds ?? [], sourceId].filter((candidate, index, all) => all.indexOf(candidate) === index).slice(-CONVERSATION_SOURCE_ID_LIMIT);
859
- }
860
- function appendAssistantContent(existing, next) {
861
- const combined = existing.length > 0 && next.length > 0 ? `${existing}
862
-
863
- ${next}` : existing || next;
864
- if (combined.length <= 5e5) {
865
- return combined;
866
- }
867
- return `\u2026${combined.slice(combined.length - 499999)}`;
868
- }
869
- function boundAttachment(attachment) {
870
- return {
871
- ...attachment,
872
- name: boundedText(attachment.name, 1024, "Attachment"),
873
- ...attachment.mimeType === void 0 ? {} : {
874
- mimeType: boundedText(
875
- attachment.mimeType,
876
- 256,
877
- "application/octet-stream"
878
- )
879
- },
880
- ...attachment.uri === void 0 ? {} : { uri: boundedText(attachment.uri, 32768, "unknown") }
881
- };
882
- }
883
- function summarizeUnknown(value) {
884
- if (typeof value === "string") {
885
- return limitSummary(stripInternalMarkup(value));
886
- }
887
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
888
- return String(value);
889
- }
890
- if (value === null) {
891
- return "null";
892
- }
893
- try {
894
- return limitSummary(stripInternalMarkup(JSON.stringify(value)));
895
- } catch {
896
- return "[unserializable]";
897
- }
898
- }
899
- function isDisplayableHumanMessage(event) {
900
- if (event.type !== "user.message" || event.agentId !== void 0) {
901
- return false;
902
- }
903
- const source = event.data.source;
904
- return event.data.isAutopilotContinuation !== true && (source === void 0 || source === "user" || source === "mobile" || /^schedule-[1-9]\d*$/.test(source));
905
- }
906
- function projectAttachment(attachment) {
907
- switch (attachment.type) {
908
- case "file":
909
- return {
910
- kind: attachment.mimeType?.startsWith("image/") ? "image" : "file",
911
- name: attachment.displayName,
912
- ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },
913
- uri: attachment.path
914
- };
915
- case "directory":
916
- return {
917
- kind: "file",
918
- name: attachment.displayName,
919
- uri: attachment.path
920
- };
921
- case "selection":
922
- return {
923
- kind: "selection",
924
- name: attachment.displayName,
925
- uri: attachment.filePath
926
- };
927
- case "github_reference":
928
- return {
929
- kind: "github-reference",
930
- name: attachment.title,
931
- uri: attachment.url
932
- };
933
- case "github_commit":
934
- return {
935
- kind: "github-reference",
936
- name: attachment.message,
937
- uri: attachment.url
938
- };
939
- case "github_release":
940
- return {
941
- kind: "github-reference",
942
- name: attachment.name,
943
- uri: attachment.url
944
- };
945
- case "github_actions_job":
946
- return {
947
- kind: "github-reference",
948
- name: attachment.jobName,
949
- uri: attachment.url
950
- };
951
- case "github_repository":
952
- return {
953
- kind: "github-reference",
954
- name: `${attachment.repo.owner}/${attachment.repo.name}`,
955
- uri: attachment.url
956
- };
957
- case "github_file_diff":
958
- return {
959
- kind: "github-reference",
960
- name: "GitHub file diff",
961
- uri: attachment.url
962
- };
963
- case "github_tree_comparison":
964
- return {
965
- kind: "github-reference",
966
- name: "GitHub tree comparison",
967
- uri: attachment.url
968
- };
969
- case "github_url":
970
- return {
971
- kind: "github-reference",
972
- name: attachment.url,
973
- uri: attachment.url
974
- };
975
- case "github_file":
976
- case "github_snippet":
977
- return {
978
- kind: "github-reference",
979
- name: attachment.path,
980
- uri: attachment.url
981
- };
982
- case "blob":
983
- return {
984
- kind: attachment.mimeType.startsWith("image/") ? "image" : "file",
985
- name: attachment.displayName ?? "Attachment",
986
- mimeType: attachment.mimeType
987
- };
988
- case "extension_context":
989
- return {
990
- kind: "unknown",
991
- name: attachment.title
992
- };
993
- }
994
- }
995
- function projectCitation(source) {
996
- if (source.url !== void 0) {
997
- return {
998
- kind: "github-reference",
999
- name: source.title ?? source.path ?? source.id,
1000
- uri: source.url
1001
- };
1002
- }
1003
- if (source.path !== void 0) {
1004
- return {
1005
- kind: "file",
1006
- name: source.title ?? source.path,
1007
- uri: source.path
1008
- };
1009
- }
1010
- return {
1011
- kind: "unknown",
1012
- name: source.title ?? source.id
1013
- };
1014
- }
1015
- function normalizeImageMimeType(value) {
1016
- return value.toLowerCase() === "image/jpg" ? "image/jpeg" : value.toLowerCase();
1017
- }
1018
- function hasImageSignature(bytes, mimeType) {
1019
- switch (mimeType) {
1020
- case "image/jpeg":
1021
- return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1022
- case "image/png":
1023
- return bytes.length >= 8 && bytes.subarray(0, 8).equals(
1024
- Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
1025
- );
1026
- case "image/webp":
1027
- return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
1028
- case "image/gif":
1029
- return bytes.length >= 6 && (bytes.subarray(0, 6).toString("ascii") === "GIF87a" || bytes.subarray(0, 6).toString("ascii") === "GIF89a");
1030
- default:
1031
- return false;
1032
- }
1033
- }
1034
- function decodeImageBase64(value, expectedMimeType) {
1035
- const dataUrlMatch = /^data:([^;,]+);base64,(.*)$/isu.exec(value);
1036
- if (dataUrlMatch !== null && normalizeImageMimeType(dataUrlMatch[1] ?? "") !== expectedMimeType) {
1037
- return void 0;
1038
- }
1039
- const payload = dataUrlMatch?.[2] ?? value;
1040
- const normalized = payload.replaceAll("-", "+").replaceAll("_", "/");
1041
- if (normalized.length === 0 || normalized.length % 4 === 1 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized)) {
1042
- return void 0;
1043
- }
1044
- const bytes = Buffer.from(normalized, "base64");
1045
- return bytes.toString("base64").replace(/=+$/u, "") === normalized.replace(/=+$/u, "") ? bytes : void 0;
1046
- }
1047
- function projectInlineToolImage(data, mimeTypeValue, name, expectedByteLength, source = "binary-result") {
1048
- const mimeType = normalizeImageMimeType(mimeTypeValue);
1049
- const metadata = {
1050
- kind: "image",
1051
- name: boundedText(name, 1024, "Copilot image"),
1052
- mimeType: boundedText(mimeType, 256, "application/octet-stream")
1053
- };
1054
- if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) {
1055
- return {
1056
- attachment: metadata,
1057
- failure: { source, reason: "mime-unsupported", mimeType }
1058
- };
1059
- }
1060
- const bytes = decodeImageBase64(data, mimeType);
1061
- if (bytes === void 0) {
1062
- return {
1063
- attachment: metadata,
1064
- failure: { source, reason: "data-invalid", mimeType }
1065
- };
1066
- }
1067
- if (bytes.length === 0) {
1068
- return {
1069
- attachment: metadata,
1070
- failure: { source, reason: "data-empty", mimeType, actualByteLength: 0 }
1071
- };
1072
- }
1073
- if (bytes.length > MAX_INLINE_IMAGE_BYTES) {
1074
- return {
1075
- attachment: metadata,
1076
- failure: {
1077
- source,
1078
- reason: "data-too-large",
1079
- mimeType,
1080
- actualByteLength: bytes.length
1081
- }
1082
- };
1083
- }
1084
- if (expectedByteLength !== void 0 && bytes.length !== expectedByteLength) {
1085
- return {
1086
- attachment: metadata,
1087
- failure: {
1088
- source,
1089
- reason: "length-mismatch",
1090
- mimeType,
1091
- expectedByteLength,
1092
- actualByteLength: bytes.length
1093
- }
1094
- };
1095
- }
1096
- if (!hasImageSignature(bytes, mimeType)) {
1097
- return {
1098
- attachment: metadata,
1099
- failure: {
1100
- source,
1101
- reason: "signature-mismatch",
1102
- mimeType,
1103
- actualByteLength: bytes.length
1104
- }
1105
- };
1106
- }
1107
- return {
1108
- attachment: {
1109
- ...metadata,
1110
- data: bytes.toString("base64"),
1111
- byteLength: bytes.length,
1112
- sha256: createHash3("sha256").update(bytes).digest("hex")
1113
- }
1114
- };
1115
- }
1116
- function projectToolBinaryResult(result, name, assets) {
1117
- if (result.type !== "image") {
1118
- return void 0;
1119
- }
1120
- if ("data" in result) {
1121
- return projectInlineToolImage(
1122
- result.data,
1123
- result.mimeType,
1124
- result.description ?? name
1125
- );
1126
- }
1127
- if ("assetId" in result) {
1128
- const asset = assets.get(result.assetId);
1129
- if (asset === void 0 || asset.data.type !== "image") {
1130
- return {
1131
- attachment: {
1132
- kind: "image",
1133
- name: boundedText(result.description ?? name, 1024, "Copilot image"),
1134
- mimeType: boundedText(
1135
- normalizeImageMimeType(result.mimeType),
1136
- 256,
1137
- "application/octet-stream"
1138
- )
1139
- },
1140
- failure: {
1141
- source: "binary-asset",
1142
- reason: "asset-missing",
1143
- mimeType: normalizeImageMimeType(result.mimeType),
1144
- expectedByteLength: result.byteLength
1145
- }
1146
- };
1147
- }
1148
- const projected = projectInlineToolImage(
1149
- asset.data.data,
1150
- asset.data.mimeType,
1151
- result.description ?? asset.data.description ?? name,
1152
- void 0,
1153
- "binary-asset"
1154
- );
1155
- const attachment = projected.attachment;
1156
- if (projected.failure !== void 0) {
1157
- return { ...projected, sourceEventId: asset.eventId, sourceTimestamp: asset.timestamp };
1158
- }
1159
- if (attachment.sha256 !== void 0 && result.assetId !== `sha256:${attachment.sha256}`) {
1160
- return {
1161
- attachment: {
1162
- kind: "image",
1163
- name: attachment.name,
1164
- ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType }
1165
- },
1166
- sourceEventId: asset.eventId,
1167
- sourceTimestamp: asset.timestamp,
1168
- failure: {
1169
- source: "binary-asset",
1170
- reason: "asset-hash-mismatch",
1171
- mimeType: attachment.mimeType ?? "application/octet-stream",
1172
- expectedByteLength: result.byteLength,
1173
- ...attachment.byteLength === void 0 ? {} : { actualByteLength: attachment.byteLength }
1174
- }
1175
- };
1176
- }
1177
- return {
1178
- attachment,
1179
- sourceEventId: asset.eventId,
1180
- sourceTimestamp: asset.timestamp
1181
- };
1182
- }
1183
- return {
1184
- attachment: {
1185
- kind: "image",
1186
- name: boundedText(result.description ?? name, 1024, "Copilot image"),
1187
- mimeType: boundedText(
1188
- normalizeImageMimeType(result.mimeType),
1189
- 256,
1190
- "application/octet-stream"
1191
- )
1192
- },
1193
- failure: {
1194
- source: "binary-result",
1195
- reason: "asset-missing",
1196
- mimeType: normalizeImageMimeType(result.mimeType),
1197
- expectedByteLength: result.byteLength
1198
- }
1199
- };
1200
- }
1201
- function projectToolContentImage(image, name) {
1202
- return projectInlineToolImage(
1203
- image.data,
1204
- image.mimeType,
1205
- name,
1206
- void 0,
1207
- "content"
1208
- );
1209
- }
1210
- function permissionName(kind) {
1211
- const words = kind.replaceAll("_", " ").replaceAll("-", " ");
1212
- return `${words.charAt(0).toUpperCase()}${words.slice(1)} permission`;
1213
- }
1214
- var ConversationToolLifecycles = class {
1215
- #starts = /* @__PURE__ */ new Map();
1216
- get(toolCallId) {
1217
- return this.#starts.get(toolCallId);
1218
- }
1219
- remember(toolCallId, start) {
1220
- const previous = this.#starts.get(toolCallId);
1221
- const lifecycle = previous?.sourceEventId === start.sourceEventId && !start.hasTurnContext ? previous : start;
1222
- this.#starts.delete(toolCallId);
1223
- this.#starts.set(toolCallId, lifecycle);
1224
- while (this.#starts.size > 1024) {
1225
- const oldest = this.#starts.keys().next().value;
1226
- if (oldest === void 0) break;
1227
- this.#starts.delete(oldest);
1228
- }
1229
- return lifecycle;
1230
- }
1231
- clear() {
1232
- this.#starts.clear();
1233
- }
1234
- };
1235
- var ConversationNormalizer = class {
1236
- constructor(onImageFailure, toolLifecycles = new ConversationToolLifecycles(), resolveInputProvenance) {
1237
- this.onImageFailure = onImageFailure;
1238
- this.toolLifecycles = toolLifecycles;
1239
- this.resolveInputProvenance = resolveInputProvenance;
1240
- }
1241
- onImageFailure;
1242
- toolLifecycles;
1243
- resolveInputProvenance;
1244
- #items = /* @__PURE__ */ new Map();
1245
- #binaryAssets = /* @__PURE__ */ new Map();
1246
- #pendingToolImages = /* @__PURE__ */ new Map();
1247
- #toolTurns = /* @__PURE__ */ new Map();
1248
- #taskCompletionToolCalls = /* @__PURE__ */ new Map();
1249
- #subagentTurns = /* @__PURE__ */ new Map();
1250
- #permissionTurns = /* @__PURE__ */ new Map();
1251
- #loopTurns = /* @__PURE__ */ new Map();
1252
- #currentTurnId;
1253
- #hasCurrentTurnContext = false;
1254
- #reportedImageFailures = /* @__PURE__ */ new Set();
1255
- apply(events) {
1256
- const changed = [];
1257
- for (const event of events) {
1258
- if (event.type === "session.binary_asset" && event.data.type === "image") {
1259
- this.#binaryAssets.set(event.data.assetId, {
1260
- eventId: event.id,
1261
- timestamp: event.timestamp,
1262
- data: event.data
1263
- });
1264
- }
1265
- if (event.type === "tool.execution_start" && event.data.toolName === TASK_COMPLETE_TOOL_NAME) {
1266
- this.#taskCompletionToolCalls.set(
1267
- event.data.toolCallId,
1268
- event.agentId !== void 0 || event.data.parentToolCallId !== void 0 || this.#taskCompletionToolCalls.get(event.data.toolCallId) === "subagent" ? "subagent" : "assistant"
1269
- );
1270
- }
1271
- }
1272
- for (const event of events) {
1273
- if (event.type === "session.binary_asset") {
1274
- const pending = this.#pendingToolImages.get(event.data.assetId);
1275
- if (pending !== void 0) {
1276
- for (const projection of pending.values()) {
1277
- if (this.#unresolvedToolImageAssetIds(projection.event).length === 0) {
1278
- this.#removePendingToolImage(projection.event);
1279
- changed.push(
1280
- ...this.#projectToolImages(
1281
- projection.event,
1282
- projection.turnId,
1283
- projection.toolName
1284
- )
1285
- );
1286
- }
1287
- }
1288
- }
1289
- continue;
1290
- }
1291
- const inputProvenance = event.type === "user.message" && event.agentId === void 0 && event.data.isAutopilotContinuation !== true ? this.resolveInputProvenance?.(event) : void 0;
1292
- if (event.type === "user.message" && (inputProvenance !== void 0 || isDisplayableHumanMessage(event))) {
1293
- const turnId = protocolId(event.data.interactionId ?? event.id);
1294
- const item = {
1295
- id: scopedId("message", event.id),
1296
- revision: 1,
1297
- turnId,
1298
- timestamp: event.timestamp,
1299
- ...inputProvenance?.actor === "subagent" ? {
1300
- kind: "assistant-message",
1301
- actor: "subagent",
1302
- agentId: inputProvenance.agentId,
1303
- final: true,
1304
- sourceMessageIds: [event.id]
1305
- } : { kind: "human-message", actor: "human" },
1306
- sourceEventIds: [event.id],
1307
- ...event.data.messageId === void 0 ? {} : { sourceMessageIds: [protocolId(event.data.messageId)] },
1308
- ...event.data.interactionId === void 0 ? {} : { sourceInteractionIds: [protocolId(event.data.interactionId)] },
1309
- content: limitSummary(event.data.content, 1e5),
1310
- attachments: event.data.attachments?.slice(0, 100).map(projectAttachment).map(boundAttachment) ?? []
1311
- };
1312
- this.#currentTurnId = turnId;
1313
- this.#hasCurrentTurnContext = true;
1314
- this.#items.set(item.id, item);
1315
- changed.push(item);
1316
- continue;
1317
- }
1318
- if (event.type === "assistant.turn_start") {
1319
- if (event.agentId !== void 0) {
1320
- this.#loopTurns.set(event.data.turnId, {
1321
- turnId: protocolId(
1322
- this.#currentTurnId ?? event.data.interactionId ?? event.data.turnId
1323
- ),
1324
- hasTurnContext: this.#currentTurnId === void 0 ? event.data.interactionId !== void 0 : this.#hasCurrentTurnContext
1325
- });
1326
- continue;
1327
- }
1328
- const turnId = protocolId(
1329
- event.data.interactionId ?? this.#currentTurnId ?? event.data.turnId
1330
- );
1331
- const hasTurnContext = event.data.interactionId !== void 0 || this.#hasCurrentTurnContext;
1332
- this.#loopTurns.set(event.data.turnId, { turnId, hasTurnContext });
1333
- this.#currentTurnId = turnId;
1334
- this.#hasCurrentTurnContext = hasTurnContext;
1335
- continue;
1336
- }
1337
- if (event.type === "skill.invoked") {
1338
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1339
- const step = {
1340
- id: scopedId("skill", event.id),
1341
- kind: "skill",
1342
- name: boundedText(event.data.name, 256, "Skill"),
1343
- ...boundedOptionalText(event.data.description, 2048) === void 0 ? {} : {
1344
- description: boundedOptionalText(
1345
- event.data.description,
1346
- 2048
1347
- )
1348
- },
1349
- status: "completed",
1350
- ...boundedOptionalText(event.data.source, 256) === void 0 ? {} : { source: boundedOptionalText(event.data.source, 256) }
1351
- };
1352
- const item = this.#upsertActivityStep(
1353
- event.id,
1354
- event.timestamp,
1355
- turnId,
1356
- step
1357
- );
1358
- changed.push(item);
1359
- continue;
1360
- }
1361
- if (event.type === "tool.execution_start") {
1362
- const lifecycle = this.toolLifecycles.remember(event.data.toolCallId, {
1363
- sourceEventId: protocolId(event.id),
1364
- timestamp: event.timestamp,
1365
- turnId: this.#resolveTurnId(
1366
- event.data.turnId,
1367
- this.#currentTurnId ?? protocolId(event.id)
1368
- ),
1369
- hasTurnContext: event.data.turnId === void 0 ? this.#hasCurrentTurnContext : this.#loopTurns.get(event.data.turnId)?.hasTurnContext ?? false,
1370
- name: boundedText(event.data.toolName, 256, "Tool"),
1371
- actor: event.agentId !== void 0 || event.data.parentToolCallId !== void 0 ? "subagent" : "assistant"
1372
- });
1373
- const turnId = lifecycle.turnId;
1374
- this.#toolTurns.set(event.data.toolCallId, turnId);
1375
- if (event.data.toolName === TASK_COMPLETE_TOOL_NAME) {
1376
- continue;
1377
- }
1378
- const step = {
1379
- id: scopedId("tool", event.data.toolCallId),
1380
- kind: "tool",
1381
- name: lifecycle.name,
1382
- status: "running"
1383
- };
1384
- changed.push(
1385
- this.#upsertActivityStep(
1386
- protocolId(event.id),
1387
- event.timestamp,
1388
- turnId,
1389
- step
1390
- )
1391
- );
1392
- continue;
1393
- }
1394
- if (event.type === "tool.execution_complete") {
1395
- const lifecycle = this.toolLifecycles.get(event.data.toolCallId);
1396
- const turnId = lifecycle?.turnId ?? this.#resolveTurnId(
1397
- event.data.turnId,
1398
- this.#toolTurns.get(event.data.toolCallId) ?? this.#currentTurnId ?? event.id
1399
- );
1400
- if (this.#taskCompletionToolCalls.has(event.data.toolCallId) || lifecycle?.name === TASK_COMPLETE_TOOL_NAME || event.data.toolDescription?.name === TASK_COMPLETE_TOOL_NAME) {
1401
- if (lifecycle !== void 0) {
1402
- this.#taskCompletionToolCalls.set(event.data.toolCallId, lifecycle.actor);
1403
- }
1404
- const taskCompletion = this.#projectTaskCompletion(event, turnId);
1405
- if (taskCompletion !== void 0) {
1406
- changed.push(taskCompletion);
1407
- continue;
1408
- }
1409
- const step2 = {
1410
- id: scopedId("tool", event.data.toolCallId),
1411
- kind: "tool",
1412
- name: TASK_COMPLETE_TOOL_NAME,
1413
- status: event.data.success ? "completed" : "failed"
1414
- };
1415
- changed.push(
1416
- this.#upsertActivityStep(
1417
- event.id,
1418
- event.timestamp,
1419
- turnId,
1420
- step2
1421
- )
1422
- );
1423
- continue;
1424
- }
1425
- const existingStep = this.#findActivityStep(
1426
- scopedId("tool", event.data.toolCallId)
1427
- );
1428
- const step = {
1429
- id: scopedId("tool", event.data.toolCallId),
1430
- kind: "tool",
1431
- name: lifecycle?.name ?? (existingStep?.kind === "tool" ? existingStep.name : boundedText(event.data.toolDescription?.name ?? "unknown-tool", 256, "Tool")),
1432
- status: event.data.success ? "completed" : "failed"
1433
- };
1434
- changed.push(
1435
- this.#upsertActivityStep(
1436
- event.id,
1437
- event.timestamp,
1438
- turnId,
1439
- step,
1440
- lifecycle
1441
- )
1442
- );
1443
- const toolName = lifecycle?.name ?? existingStep?.name ?? "Copilot tool";
1444
- const unresolvedAssetIds = this.#unresolvedToolImageAssetIds(event);
1445
- if (unresolvedAssetIds.length > 0) {
1446
- const projection = { event, turnId, toolName };
1447
- for (const assetId of unresolvedAssetIds) {
1448
- let projections = this.#pendingToolImages.get(assetId);
1449
- if (projections === void 0) {
1450
- projections = /* @__PURE__ */ new Map();
1451
- this.#pendingToolImages.set(assetId, projections);
1452
- }
1453
- projections.set(event.data.toolCallId, projection);
1454
- }
1455
- } else {
1456
- changed.push(
1457
- ...this.#projectToolImages(event, turnId, toolName)
1458
- );
1459
- }
1460
- continue;
1461
- }
1462
- if (event.type === "subagent.started") {
1463
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1464
- const subagentId = event.agentId ?? event.data.toolCallId;
1465
- this.#subagentTurns.set(subagentId, turnId);
1466
- const step = {
1467
- id: scopedId("subagent", subagentId),
1468
- kind: "subagent",
1469
- name: boundedText(event.data.agentDisplayName, 256, "Subagent"),
1470
- status: "running",
1471
- description: boundedText(
1472
- event.data.agentDescription,
1473
- 2048,
1474
- "Subagent task"
1475
- ),
1476
- ...boundedOptionalText(event.data.model, 256) === void 0 ? {} : { model: boundedOptionalText(event.data.model, 256) }
1477
- };
1478
- changed.push(
1479
- this.#upsertActivityStep(
1480
- event.id,
1481
- event.timestamp,
1482
- turnId,
1483
- step
1484
- )
1485
- );
1486
- continue;
1487
- }
1488
- if (event.type === "subagent.completed") {
1489
- const subagentId = event.agentId ?? event.data.toolCallId;
1490
- const turnId = this.#subagentTurns.get(subagentId) ?? this.#currentTurnId ?? protocolId(event.id);
1491
- const existingStep = this.#findActivityStep(
1492
- scopedId("subagent", subagentId)
1493
- );
1494
- const step = {
1495
- id: scopedId("subagent", subagentId),
1496
- kind: "subagent",
1497
- name: boundedText(event.data.agentDisplayName, 256, "Subagent"),
1498
- status: "completed",
1499
- ...existingStep?.kind === "subagent" && existingStep.description !== void 0 ? { description: existingStep.description } : {},
1500
- ...event.data.model === void 0 ? existingStep?.kind === "subagent" && existingStep.model !== void 0 ? { model: existingStep.model } : {} : {
1501
- model: boundedText(event.data.model, 256, "unknown-model")
1502
- },
1503
- ...event.data.durationMs === void 0 ? {} : { durationMs: event.data.durationMs }
1504
- };
1505
- changed.push(
1506
- this.#upsertActivityStep(
1507
- event.id,
1508
- event.timestamp,
1509
- turnId,
1510
- step
1511
- )
1512
- );
1513
- continue;
1514
- }
1515
- if (event.type === "subagent.failed") {
1516
- const subagentId = event.agentId ?? event.data.toolCallId;
1517
- const turnId = this.#subagentTurns.get(subagentId) ?? this.#currentTurnId ?? protocolId(event.id);
1518
- const existingStep = this.#findActivityStep(
1519
- scopedId("subagent", subagentId)
1520
- );
1521
- const step = {
1522
- id: scopedId("subagent", subagentId),
1523
- kind: "subagent",
1524
- name: boundedText(event.data.agentDisplayName, 256, "Subagent"),
1525
- status: "failed",
1526
- ...existingStep?.kind === "subagent" && existingStep.description !== void 0 ? { description: existingStep.description } : {},
1527
- ...event.data.model === void 0 ? existingStep?.kind === "subagent" && existingStep.model !== void 0 ? { model: existingStep.model } : {} : {
1528
- model: boundedText(event.data.model, 256, "unknown-model")
1529
- },
1530
- ...event.data.durationMs === void 0 ? {} : { durationMs: event.data.durationMs },
1531
- error: summarizeUnknown(event.data.error)
1532
- };
1533
- changed.push(
1534
- this.#upsertActivityStep(
1535
- event.id,
1536
- event.timestamp,
1537
- turnId,
1538
- step
1539
- )
1540
- );
1541
- continue;
1542
- }
1543
- if (event.type === "permission.requested") {
1544
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1545
- const request = event.data.permissionRequest;
1546
- this.#permissionTurns.set(event.data.requestId, turnId);
1547
- const step = {
1548
- id: scopedId("permission", event.data.requestId),
1549
- kind: "permission",
1550
- name: permissionName(request.kind),
1551
- status: "running",
1552
- ...request.kind === "shell" ? {
1553
- description: boundedText(
1554
- request.intention,
1555
- 2048,
1556
- "Shell command"
1557
- )
1558
- } : {}
1559
- };
1560
- changed.push(
1561
- this.#upsertActivityStep(
1562
- event.id,
1563
- event.timestamp,
1564
- turnId,
1565
- step
1566
- )
1567
- );
1568
- continue;
1569
- }
1570
- if (event.type === "permission.completed") {
1571
- const turnId = this.#permissionTurns.get(event.data.requestId) ?? this.#currentTurnId ?? protocolId(event.id);
1572
- const stepId = scopedId("permission", event.data.requestId);
1573
- const existingStep = this.#findActivityStep(stepId);
1574
- const result = event.data.result.kind;
1575
- const failed = result === "cancelled" || result.startsWith("denied");
1576
- const step = {
1577
- id: stepId,
1578
- kind: "permission",
1579
- name: existingStep?.kind === "permission" ? existingStep.name : "Permission",
1580
- status: failed ? "failed" : "completed",
1581
- ...existingStep?.kind === "permission" && existingStep.description !== void 0 ? { description: existingStep.description } : {},
1582
- resultSummary: result
1583
- };
1584
- changed.push(
1585
- this.#upsertActivityStep(
1586
- event.id,
1587
- event.timestamp,
1588
- turnId,
1589
- step
1590
- )
1591
- );
1592
- continue;
1593
- }
1594
- if (event.type === "user_input.requested") {
1595
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1596
- this.#permissionTurns.set(event.data.requestId, turnId);
1597
- const step = {
1598
- id: scopedId("permission", event.data.requestId),
1599
- kind: "permission",
1600
- name: "User input",
1601
- status: "running",
1602
- description: boundedText(event.data.question, 2048, "User input")
1603
- };
1604
- changed.push(
1605
- this.#upsertActivityStep(
1606
- event.id,
1607
- event.timestamp,
1608
- turnId,
1609
- step
1610
- )
1611
- );
1612
- continue;
1613
- }
1614
- if (event.type === "user_input.completed") {
1615
- const turnId = this.#permissionTurns.get(event.data.requestId) ?? this.#currentTurnId ?? protocolId(event.id);
1616
- const stepId = scopedId("permission", event.data.requestId);
1617
- const existingStep = this.#findActivityStep(stepId);
1618
- const step = {
1619
- id: stepId,
1620
- kind: "permission",
1621
- name: "User input",
1622
- status: "completed",
1623
- ...existingStep?.kind === "permission" && existingStep.description !== void 0 ? { description: existingStep.description } : {},
1624
- resultSummary: event.data.answer === void 0 ? "completed" : boundedText(event.data.answer, 4096, "completed")
1625
- };
1626
- changed.push(
1627
- this.#upsertActivityStep(
1628
- event.id,
1629
- event.timestamp,
1630
- turnId,
1631
- step
1632
- )
1633
- );
1634
- continue;
1635
- }
1636
- if (event.type === "session.warning") {
1637
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1638
- const warningType = event.data.warningType.replaceAll("_", " ");
1639
- const warningLabel = boundedText(warningType, 240, "Session");
1640
- const item = {
1641
- id: scopedId("notice", event.id),
1642
- kind: "notice",
1643
- revision: 1,
1644
- turnId,
1645
- timestamp: event.timestamp,
1646
- actor: event.agentId === void 0 ? "system" : "subagent",
1647
- sourceEventIds: [event.id],
1648
- severity: "warning",
1649
- title: limitSummary(
1650
- `${warningLabel.charAt(0).toUpperCase()}${warningLabel.slice(1)} warning`,
1651
- 256
1652
- ),
1653
- content: boundedText(event.data.message, 4096, "Session warning")
1654
- };
1655
- this.#items.set(item.id, item);
1656
- changed.push(item);
1657
- continue;
1658
- }
1659
- if (event.type === "session.error") {
1660
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1661
- const errorType = event.data.errorType.replaceAll("_", " ");
1662
- const errorLabel = boundedText(errorType, 240, "Session");
1663
- const title = `${errorLabel.charAt(0).toUpperCase()}${errorLabel.slice(1)} error`;
1664
- const item = {
1665
- id: scopedId("notice", event.id),
1666
- kind: "notice",
1667
- revision: 1,
1668
- turnId,
1669
- timestamp: event.timestamp,
1670
- actor: event.agentId === void 0 ? "system" : "subagent",
1671
- sourceEventIds: [event.id],
1672
- severity: "error",
1673
- title: limitSummary(
1674
- event.data.errorCode === void 0 ? title : `${title} \xB7 ${event.data.errorCode}`,
1675
- 256
1676
- ),
1677
- content: boundedText(event.data.message, 4096, "Session error")
1678
- };
1679
- this.#items.set(item.id, item);
1680
- changed.push(item);
1681
- continue;
1682
- }
1683
- if (event.type === "system.notification" && event.data.kind.type === "shell_completed") {
1684
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1685
- const kind = event.data.kind;
1686
- const description = boundedText(
1687
- kind.description ?? `Shell ${kind.shellId}`,
1688
- 4096,
1689
- "Shell completed"
1690
- );
1691
- const item = {
1692
- id: scopedId("notice", event.id),
1693
- kind: "notice",
1694
- revision: 1,
1695
- turnId,
1696
- timestamp: event.timestamp,
1697
- actor: event.agentId === void 0 ? "system" : "subagent",
1698
- sourceEventIds: [event.id],
1699
- severity: kind.exitCode === void 0 || kind.exitCode === 0 ? "success" : "error",
1700
- title: "Shell completed",
1701
- content: kind.exitCode === void 0 ? description : limitSummary(`${description} \xB7 exit ${kind.exitCode}`, 4096)
1702
- };
1703
- this.#items.set(item.id, item);
1704
- changed.push(item);
1705
- continue;
1706
- }
1707
- if (event.type === "session.plan_changed") {
1708
- const turnId = this.#currentTurnId ?? protocolId(event.id);
1709
- const id = scopedId("plan", turnId);
1710
- const existing = this.#items.get(id);
1711
- const operation = event.data.operation === "create" ? "created" : event.data.operation === "update" ? "updated" : "deleted";
1712
- const item = {
1713
- id,
1714
- kind: "plan-update",
1715
- revision: eventRevision(
1716
- event.timestamp,
1717
- existing?.kind === "plan-update" ? existing.revision : void 0
1718
- ),
1719
- turnId,
1720
- timestamp: existing?.kind === "plan-update" ? existing.timestamp : event.timestamp,
1721
- actor: event.agentId === void 0 ? "assistant" : "subagent",
1722
- sourceEventIds: existing?.kind === "plan-update" ? appendSourceEventId(existing.sourceEventIds, event.id) : [event.id],
1723
- operation,
1724
- content: `Plan ${operation}`,
1725
- todos: []
1726
- };
1727
- this.#items.set(id, item);
1728
- changed.push(item);
1729
- continue;
1730
- }
1731
- if (event.type === "assistant.message") {
1732
- if (event.agentId !== void 0 || event.data.parentToolCallId !== void 0) {
1733
- continue;
1734
- }
1735
- if (event.data.content.trim().length === 0 && (event.data.citations?.sources.length ?? 0) === 0) {
1736
- continue;
1737
- }
1738
- const turnId = protocolId(
1739
- event.data.interactionId ?? (event.data.turnId === void 0 ? this.#currentTurnId : this.#loopTurns.get(event.data.turnId)?.turnId) ?? event.data.turnId ?? event.id
1740
- );
1741
- const id = assistantMessageId(event.data);
1742
- const existing = this.#items.get(id);
1743
- const citationAttachments = event.data.citations?.sources.slice(0, 100).map(projectCitation).map(boundAttachment) ?? [];
1744
- const attachments = [
1745
- ...existing?.kind === "assistant-message" ? existing.attachments ?? [] : [],
1746
- ...citationAttachments
1747
- ].filter(
1748
- (attachment, index, all) => all.findIndex(
1749
- (candidate) => candidate.kind === attachment.kind && candidate.name === attachment.name && candidate.uri === attachment.uri
1750
- ) === index
1751
- ).slice(-100);
1752
- const sourceMessageIds = appendOptionalSourceId(
1753
- existing?.kind === "assistant-message" ? existing.sourceMessageIds : void 0,
1754
- protocolId(event.data.messageId)
1755
- );
1756
- const sourceInteractionIds = appendOptionalSourceId(
1757
- existing?.kind === "assistant-message" ? existing.sourceInteractionIds : void 0,
1758
- event.data.interactionId === void 0 ? void 0 : protocolId(event.data.interactionId)
1759
- );
1760
- const item = {
1761
- id,
1762
- kind: "assistant-message",
1763
- revision: eventRevision(
1764
- event.timestamp,
1765
- existing?.kind === "assistant-message" ? existing.revision : void 0
1766
- ),
1767
- turnId,
1768
- timestamp: existing?.kind === "assistant-message" ? existing.timestamp : event.timestamp,
1769
- actor: "assistant",
1770
- sourceEventIds: existing?.kind === "assistant-message" ? appendSourceEventId(existing.sourceEventIds, event.id) : [event.id],
1771
- ...sourceMessageIds === void 0 ? {} : { sourceMessageIds },
1772
- ...sourceInteractionIds === void 0 ? {} : { sourceInteractionIds },
1773
- content: appendAssistantContent(
1774
- existing?.kind === "assistant-message" ? existing.content : "",
1775
- event.data.content
1776
- ),
1777
- ...attachments.length === 0 ? {} : { attachments },
1778
- ...event.data.model === void 0 ? existing?.kind === "assistant-message" && existing.model !== void 0 ? { model: existing.model } : {} : {
1779
- model: boundedText(event.data.model, 256, "unknown-model")
1780
- },
1781
- final: event.data.chunkCount === void 0 || event.data.chunkIndex === void 0 || event.data.chunkIndex + 1 >= event.data.chunkCount
1782
- };
1783
- this.#currentTurnId = turnId;
1784
- this.#hasCurrentTurnContext = event.data.interactionId !== void 0 || (event.data.turnId === void 0 ? this.#hasCurrentTurnContext : this.#loopTurns.get(event.data.turnId)?.hasTurnContext ?? false);
1785
- this.#items.set(id, item);
1786
- changed.push(item);
1787
- }
1788
- }
1789
- return changed;
1790
- }
1791
- snapshot() {
1792
- return [...this.#items.values()];
1793
- }
1794
- pendingImageAssetIds() {
1795
- return [...this.#pendingToolImages.keys()];
1796
- }
1797
- #projectTaskCompletion(event, turnId) {
1798
- if (!event.data.success) {
1799
- return void 0;
1800
- }
1801
- const content = boundedOptionalMessageContent(
1802
- event.data.result?.content,
1803
- 4096
1804
- );
1805
- if (content === void 0) {
1806
- return void 0;
1807
- }
1808
- const id = scopedId("notice", event.data.toolCallId);
1809
- const existing = this.#items.get(id);
1810
- const item = {
1811
- id,
1812
- kind: "notice",
1813
- revision: eventRevision(
1814
- event.timestamp,
1815
- existing?.kind === "notice" ? existing.revision : void 0
1816
- ),
1817
- turnId,
1818
- timestamp: existing?.kind === "notice" ? existing.timestamp : event.timestamp,
1819
- actor: event.agentId !== void 0 || event.data.parentToolCallId !== void 0 || this.#taskCompletionToolCalls.get(event.data.toolCallId) === "subagent" || existing?.kind === "notice" && existing.actor === "subagent" ? "subagent" : "assistant",
1820
- sourceEventIds: existing?.kind === "notice" ? appendSourceEventId(existing.sourceEventIds, event.id) : [event.id],
1821
- severity: "success",
1822
- title: "Task completed",
1823
- content
1824
- };
1825
- this.#items.set(id, item);
1826
- return item;
1827
- }
1828
- #unresolvedToolImageAssetIds(event) {
1829
- return (event.data.result?.binaryResultsForLlm?.filter(
1830
- (result) => result.type === "image" && "assetId" in result
1831
- ).map((result) => result.assetId).filter((assetId) => !this.#binaryAssets.has(assetId)) ?? []).filter((assetId, index, all) => all.indexOf(assetId) === index);
1832
- }
1833
- #removePendingToolImage(event) {
1834
- for (const [assetId, projections] of this.#pendingToolImages) {
1835
- projections.delete(event.data.toolCallId);
1836
- if (projections.size === 0) {
1837
- this.#pendingToolImages.delete(assetId);
1838
- }
1839
- }
1840
- }
1841
- #projectToolImages(event, turnId, toolName) {
1842
- const binaryImages = event.data.result?.binaryResultsForLlm?.map(
1843
- (result, index) => projectToolBinaryResult(
1844
- result,
1845
- `${toolName} image ${index + 1}`,
1846
- this.#binaryAssets
1847
- )
1848
- ).filter(
1849
- (image) => image !== void 0
1850
- ) ?? [];
1851
- const contentImages = event.data.result?.contents?.filter(
1852
- (content) => content.type === "image"
1853
- ).map(
1854
- (image, index) => projectToolContentImage(
1855
- image,
1856
- `${toolName} image ${binaryImages.length + index + 1}`
1857
- )
1858
- ) ?? [];
1859
- const projectedImages = [...binaryImages, ...contentImages].filter(
1860
- (image, index, all) => all.findIndex(
1861
- (candidate) => [
1862
- candidate.attachment.mimeType,
1863
- candidate.attachment.sha256 ?? candidate.attachment.data ?? candidate.attachment.name
1864
- ].join("\0") === [
1865
- image.attachment.mimeType,
1866
- image.attachment.sha256 ?? image.attachment.data ?? image.attachment.name
1867
- ].join("\0")
1868
- ) === index
1869
- );
1870
- for (const image of projectedImages) {
1871
- if (image.failure === void 0) {
1872
- continue;
1873
- }
1874
- const fingerprint = [
1875
- event.data.toolCallId,
1876
- image.failure.source,
1877
- image.failure.reason,
1878
- image.failure.mimeType,
1879
- image.failure.expectedByteLength,
1880
- image.failure.actualByteLength
1881
- ].join("\0");
1882
- if (this.#reportedImageFailures.has(fingerprint)) {
1883
- continue;
1884
- }
1885
- this.#reportedImageFailures.add(fingerprint);
1886
- this.onImageFailure?.({
1887
- ...image.failure,
1888
- toolCallId: event.data.toolCallId,
1889
- toolName
1890
- });
1891
- }
1892
- const imageGroups = splitToolImages(projectedImages);
1893
- return imageGroups.map((imageGroup, groupIndex) => {
1894
- const multipleGroups = imageGroups.length > 1;
1895
- const id = scopedId(
1896
- "tool-image",
1897
- multipleGroups ? `${event.data.toolCallId}:${groupIndex + 1}` : event.data.toolCallId
1898
- );
1899
- const existing = this.#items.get(id);
1900
- const imageItem = {
1901
- id,
1902
- kind: "assistant-message",
1903
- // The same source events must produce the same revision in live and batched history reads.
1904
- revision: Math.max(
1905
- eventRevision(event.timestamp, existing?.kind === "assistant-message" ? existing.revision : void 0),
1906
- ...imageGroup.flatMap((image) => image.sourceTimestamp === void 0 ? [] : [eventRevision(image.sourceTimestamp)])
1907
- ),
1908
- turnId,
1909
- timestamp: existing?.kind === "assistant-message" ? existing.timestamp : event.timestamp,
1910
- actor: event.agentId !== void 0 || event.data.parentToolCallId !== void 0 || this.toolLifecycles.get(event.data.toolCallId)?.actor === "subagent" ? "subagent" : "assistant",
1911
- sourceEventIds: [
1912
- ...imageGroup.flatMap(
1913
- (image) => image.sourceEventId === void 0 ? [] : [image.sourceEventId]
1914
- ),
1915
- event.id
1916
- ].filter(
1917
- (sourceEventId, index, all) => all.indexOf(sourceEventId) === index
1918
- ),
1919
- content: "",
1920
- attachments: imageGroup.map((image) => image.attachment),
1921
- ...event.agentId === void 0 ? {} : { agentId: protocolId(event.agentId) },
1922
- final: true
1923
- };
1924
- this.#items.set(imageItem.id, imageItem);
1925
- return imageItem;
1926
- });
1927
- }
1928
- #resolveTurnId(loopTurnId, fallback) {
1929
- return protocolId(
1930
- (loopTurnId === void 0 ? void 0 : this.#loopTurns.get(loopTurnId)?.turnId) ?? loopTurnId ?? fallback
1931
- );
1932
- }
1933
- #findActivityStep(stepId) {
1934
- const activity = this.#items.get(scopedId("activity", stepId));
1935
- return activity?.kind === "activity-group" ? activity.steps[0] : void 0;
1936
- }
1937
- #upsertActivityStep(eventId, timestamp, turnId, step, lifecycle) {
1938
- const id = scopedId("activity", step.id);
1939
- const existing = this.#items.get(id);
1940
- const existingGroup = existing?.kind === "activity-group" ? existing : void 0;
1941
- const item = {
1942
- id,
1943
- kind: "activity-group",
1944
- revision: eventRevision(
1945
- timestamp,
1946
- existingGroup?.revision ?? (lifecycle === void 0 ? void 0 : Date.parse(lifecycle.timestamp))
1947
- ),
1948
- turnId,
1949
- timestamp: lifecycle?.timestamp ?? existingGroup?.timestamp ?? timestamp,
1950
- actor: "assistant",
1951
- sourceEventIds: existingGroup === void 0 ? lifecycle === void 0 ? [eventId] : appendSourceEventId([lifecycle.sourceEventId], eventId) : appendSourceEventId(existingGroup.sourceEventIds, eventId),
1952
- status: step.status,
1953
- steps: [{
1954
- ...step,
1955
- timestamp: lifecycle?.timestamp ?? existingGroup?.steps[0]?.timestamp ?? timestamp
1956
- }]
1957
- };
1958
- this.#items.set(id, item);
1959
- return item;
1960
- }
1961
- };
1962
-
1963
777
  // src/session-runtime.ts
1964
778
  import { randomUUID as randomUUID2 } from "node:crypto";
1965
779
 
@@ -2449,6 +1263,222 @@ ${state.deltaContent}`).slice(0, 4096),
2449
1263
  }
2450
1264
  };
2451
1265
 
1266
+ // src/session-directory.ts
1267
+ import { createHash as createHash3 } from "node:crypto";
1268
+ import { lstat, opendir, realpath, stat } from "node:fs/promises";
1269
+ import { isAbsolute, join, relative, sep } from "node:path";
1270
+ var SESSION_DIRECTORY_CONCURRENCY = 4;
1271
+ var SESSION_DIRECTORY_TIMEOUT_MS = 5e3;
1272
+ var SessionDirectoryError = class extends Error {
1273
+ constructor(code, message, options) {
1274
+ super(message, options);
1275
+ this.code = code;
1276
+ }
1277
+ code;
1278
+ };
1279
+ function fail(code, message) {
1280
+ throw new SessionDirectoryError(code, message);
1281
+ }
1282
+ function contained(root, candidate) {
1283
+ const path = relative(root, candidate);
1284
+ return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
1285
+ }
1286
+ function sessionRootIdentity(root, info) {
1287
+ return `${root}\0${info.dev}\0${info.ino}`;
1288
+ }
1289
+ var SessionDirectoryLister = class {
1290
+ constructor(metadata) {
1291
+ this.metadata = metadata;
1292
+ }
1293
+ metadata;
1294
+ #active = 0;
1295
+ #storageCache = /* @__PURE__ */ new Map();
1296
+ async storage(sessionId) {
1297
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) fail("DIRECTORY_BUSY", "Too many directory requests");
1298
+ this.#active++;
1299
+ try {
1300
+ const metadata = await this.metadata(sessionId);
1301
+ const path = metadata?.sessionStateDirectory;
1302
+ if (path === void 0) return void 0;
1303
+ if (!isAbsolute(path)) fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1304
+ const info = await lstat(path, { bigint: true });
1305
+ if (!info.isDirectory() || info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be measured");
1306
+ const root = await realpath(path), identity = sessionRootIdentity(root, info);
1307
+ const cached = this.#storageCache.get(sessionId);
1308
+ if (cached?.identity === identity && cached.expires > Date.now()) return cached.value;
1309
+ const pending = [root], deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1310
+ let bytes = 0, files = 0, visited = 0, partial = false;
1311
+ while (pending.length > 0 && visited < 1e4 && Date.now() < deadline) {
1312
+ const target = pending.pop();
1313
+ if (target === void 0) break;
1314
+ if ((await lstat(target)).isSymbolicLink() || !contained(root, await realpath(target))) {
1315
+ fail("DIRECTORY_BLOCKED", "The storage directory changed");
1316
+ }
1317
+ const directory = await opendir(target, { bufferSize: 32 });
1318
+ try {
1319
+ while (visited < 1e4 && Date.now() < deadline) {
1320
+ const entry = await directory.read();
1321
+ if (entry === null) break;
1322
+ visited++;
1323
+ const child = join(target, entry.name);
1324
+ const childInfo = await lstat(child);
1325
+ if (childInfo.isSymbolicLink()) {
1326
+ partial = true;
1327
+ continue;
1328
+ }
1329
+ if (childInfo.isDirectory()) pending.push(child);
1330
+ else if (childInfo.isFile()) {
1331
+ bytes += childInfo.size;
1332
+ files++;
1333
+ } else partial = true;
1334
+ if (!Number.isSafeInteger(bytes)) fail("DIRECTORY_LIMIT_EXCEEDED", "Storage size exceeds the supported range");
1335
+ }
1336
+ } finally {
1337
+ await directory.close();
1338
+ }
1339
+ }
1340
+ partial ||= pending.length > 0 || visited >= 1e4 || Date.now() >= deadline;
1341
+ const latest = await this.metadata(sessionId);
1342
+ const latestInfo = await lstat(path, { bigint: true });
1343
+ if (latest?.sessionStateDirectory !== path || latestInfo.isSymbolicLink() || sessionRootIdentity(await realpath(path), latestInfo) !== identity) {
1344
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1345
+ }
1346
+ const value = { bytes, files, partial, sampledAt: (/* @__PURE__ */ new Date()).toISOString() };
1347
+ this.#storageCache.delete(sessionId);
1348
+ if (this.#storageCache.size >= 32) {
1349
+ const oldest = this.#storageCache.keys().next().value;
1350
+ if (oldest !== void 0) this.#storageCache.delete(oldest);
1351
+ }
1352
+ this.#storageCache.set(sessionId, { identity, value, expires: Date.now() + 3e4 });
1353
+ return value;
1354
+ } catch (error) {
1355
+ if (error instanceof SessionDirectoryError) throw error;
1356
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "Session storage measurement failed", { cause: error });
1357
+ } finally {
1358
+ this.#active--;
1359
+ }
1360
+ }
1361
+ async list(sessionId, path, space) {
1362
+ if (!isSafeSessionDirectoryPath(path)) {
1363
+ fail("INVALID_DIRECTORY_PATH", "The directory path is not allowed");
1364
+ }
1365
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) {
1366
+ fail("DIRECTORY_BUSY", "Too many directory requests");
1367
+ }
1368
+ this.#active++;
1369
+ const deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1370
+ const checkDeadline = () => {
1371
+ if (Date.now() >= deadline) fail("DIRECTORY_TIMEOUT", "The directory request timed out");
1372
+ };
1373
+ const work = this.#list(sessionId, path, checkDeadline, space).finally(() => {
1374
+ this.#active--;
1375
+ });
1376
+ let timer;
1377
+ try {
1378
+ return await Promise.race([
1379
+ work,
1380
+ new Promise((_, reject) => {
1381
+ timer = setTimeout(() => reject(new SessionDirectoryError(
1382
+ "DIRECTORY_TIMEOUT",
1383
+ "The directory request timed out"
1384
+ )), SESSION_DIRECTORY_TIMEOUT_MS);
1385
+ })
1386
+ ]);
1387
+ } catch (error) {
1388
+ if (error instanceof SessionDirectoryError) throw error;
1389
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "The directory is unavailable", { cause: error });
1390
+ } finally {
1391
+ clearTimeout(timer);
1392
+ }
1393
+ }
1394
+ async #list(sessionId, path, checkDeadline, space) {
1395
+ const metadata = await this.metadata(sessionId);
1396
+ checkDeadline();
1397
+ if (metadata === void 0) fail("SESSION_NOT_FOUND", "The session is unavailable");
1398
+ const workingDirectory = space === "session" ? metadata.sessionStateDirectory : metadata.workingDirectory;
1399
+ if (!workingDirectory || !isAbsolute(workingDirectory)) {
1400
+ fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1401
+ }
1402
+ let root;
1403
+ let rootIdentity2;
1404
+ try {
1405
+ if (space === "session" && (await lstat(workingDirectory)).isSymbolicLink()) {
1406
+ fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1407
+ }
1408
+ root = await realpath(workingDirectory);
1409
+ const info = await stat(root, { bigint: true });
1410
+ if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1411
+ rootIdentity2 = sessionRootIdentity(root, info);
1412
+ } catch (error) {
1413
+ throw new SessionDirectoryError(
1414
+ "SESSION_ROOT_UNAVAILABLE",
1415
+ "The session working directory is unavailable",
1416
+ { cause: error }
1417
+ );
1418
+ }
1419
+ checkDeadline();
1420
+ let target = root;
1421
+ for (const segment of path === "" ? [] : path.split("/")) {
1422
+ target = join(target, segment);
1423
+ const info = await lstat(target);
1424
+ checkDeadline();
1425
+ if (info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be opened");
1426
+ if (!info.isDirectory()) fail("NOT_A_DIRECTORY", "The selected entry is not a directory");
1427
+ if (!contained(root, await realpath(target))) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1428
+ checkDeadline();
1429
+ }
1430
+ const canonicalTarget = await realpath(target);
1431
+ if (!contained(root, canonicalTarget)) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1432
+ checkDeadline();
1433
+ const directory = await opendir(target, { bufferSize: 32 });
1434
+ const entries = [];
1435
+ let bytes = 8192 + (space === "session" ? Buffer.byteLength(JSON.stringify(workingDirectory), "utf8") : 0);
1436
+ try {
1437
+ checkDeadline();
1438
+ for (; ; ) {
1439
+ const entry = await directory.read();
1440
+ checkDeadline();
1441
+ if (entry === null) break;
1442
+ if (entries.length >= SESSION_DIRECTORY_MAX_ENTRIES) {
1443
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory has too many entries");
1444
+ }
1445
+ let kind = "blocked";
1446
+ if (isSafeSessionDirectoryPath(entry.name) && !entry.name.includes("/")) {
1447
+ const child = join(target, entry.name);
1448
+ const info = await lstat(child);
1449
+ checkDeadline();
1450
+ if (!info.isSymbolicLink() && contained(root, await realpath(child))) {
1451
+ kind = info.isDirectory() ? "directory" : info.isFile() ? "file" : "blocked";
1452
+ }
1453
+ }
1454
+ const result = { name: entry.name, kind };
1455
+ bytes += Buffer.byteLength(JSON.stringify(result), "utf8") + 1;
1456
+ if (bytes > SESSION_DIRECTORY_MAX_RESPONSE_BYTES) {
1457
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory listing is too large");
1458
+ }
1459
+ entries.push(result);
1460
+ }
1461
+ const latestMetadata = await this.metadata(sessionId);
1462
+ const latestRoot = await realpath(workingDirectory);
1463
+ const latestInfo = await stat(latestRoot, { bigint: true });
1464
+ if ((space === "session" ? latestMetadata?.sessionStateDirectory : latestMetadata?.workingDirectory) !== workingDirectory || sessionRootIdentity(latestRoot, latestInfo) !== rootIdentity2 || await realpath(target) !== canonicalTarget) {
1465
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1466
+ }
1467
+ checkDeadline();
1468
+ } finally {
1469
+ await directory.close();
1470
+ }
1471
+ const order = { directory: 0, file: 1, blocked: 2 };
1472
+ entries.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
1473
+ return {
1474
+ rootRevision: createHash3("sha256").update(rootIdentity2).digest("base64url"),
1475
+ entries,
1476
+ // SDK links can use a configured home reached through a parent junction.
1477
+ ...space === "session" ? { rootPath: workingDirectory } : {}
1478
+ };
1479
+ }
1480
+ };
1481
+
2452
1482
  // src/git-remote-url.ts
2453
1483
  function sanitizeGitRemoteUrl(value) {
2454
1484
  const remote = value.trim();
@@ -2479,8 +1509,8 @@ function sanitizeGitRemoteUrl(value) {
2479
1509
  // src/git-project-identity.ts
2480
1510
  import { execFile } from "node:child_process";
2481
1511
  import { createHash as createHash4 } from "node:crypto";
2482
- import { realpath } from "node:fs/promises";
2483
- import { isAbsolute, resolve } from "node:path";
1512
+ import { realpath as realpath2 } from "node:fs/promises";
1513
+ import { isAbsolute as isAbsolute2, resolve } from "node:path";
2484
1514
  import { promisify } from "node:util";
2485
1515
  var execFileAsync = promisify(execFile);
2486
1516
  var NotGitDirectoryError = class extends Error {
@@ -2517,13 +1547,13 @@ async function git(args, env) {
2517
1547
  return stdout;
2518
1548
  }
2519
1549
  function absoluteGitPath(value) {
2520
- if (!value || value.includes("\0") || !isAbsolute(value)) {
1550
+ if (!value || value.includes("\0") || !isAbsolute2(value)) {
2521
1551
  throw new Error("Git did not return an absolute repository path");
2522
1552
  }
2523
1553
  return resolve(value);
2524
1554
  }
2525
1555
  async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment()) {
2526
- if (!isAbsolute(workingDirectory) || workingDirectory.includes("\0")) {
1556
+ if (!isAbsolute2(workingDirectory) || workingDirectory.includes("\0")) {
2527
1557
  throw new Error("Git project inspection requires an absolute working directory");
2528
1558
  }
2529
1559
  let output;
@@ -2544,8 +1574,8 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
2544
1574
  }
2545
1575
  const roots = output.replace(/\r?\n$/, "").split(/\r?\n/);
2546
1576
  if (roots.length !== 2) throw new Error("Git returned ambiguous repository paths");
2547
- const worktreeRoot = await realpath(absoluteGitPath(roots[0]));
2548
- const commonGitDirectory = await realpath(absoluteGitPath(roots[1]));
1577
+ const worktreeRoot = await realpath2(absoluteGitPath(roots[0]));
1578
+ const commonGitDirectory = await realpath2(absoluteGitPath(roots[1]));
2549
1579
  const worktrees = await git(["-C", workingDirectory, "worktree", "list", "--porcelain", "-z"], env);
2550
1580
  if (!worktrees.endsWith("\0\0")) throw new Error("Git returned an incomplete worktree list");
2551
1581
  const primary = worktrees.split("\0\0", 1)[0]?.split("\0");
@@ -2587,8 +1617,8 @@ var PromptPreparationError = class extends Error {
2587
1617
  };
2588
1618
 
2589
1619
  // src/session-project-identity.ts
2590
- import { realpath as realpath2, stat } from "node:fs/promises";
2591
- import { isAbsolute as isAbsolute2 } from "node:path";
1620
+ import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
1621
+ import { isAbsolute as isAbsolute3 } from "node:path";
2592
1622
  var SESSION_PROJECT_IDENTITY_CONCURRENCY = 20;
2593
1623
  var errors = {
2594
1624
  SESSION_NOT_FOUND: "The session is unavailable",
@@ -2605,8 +1635,8 @@ var SessionProjectIdentityError = class extends Error {
2605
1635
  code;
2606
1636
  };
2607
1637
  async function rootIdentity(workingDirectory) {
2608
- const root = await realpath2(workingDirectory);
2609
- const info = await stat(root);
1638
+ const root = await realpath3(workingDirectory);
1639
+ const info = await stat2(root);
2610
1640
  if (!info.isDirectory()) throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
2611
1641
  return { path: root, key: `${root}\0${info.dev}\0${info.ino}` };
2612
1642
  }
@@ -2628,7 +1658,7 @@ var SessionProjectIdentityReader = class {
2628
1658
  const metadata = await this.metadata(sessionId);
2629
1659
  if (metadata === void 0) throw new SessionProjectIdentityError("SESSION_NOT_FOUND");
2630
1660
  const cwd = metadata.workingDirectory;
2631
- if (!cwd || !isAbsolute2(cwd) || cwd.includes("\0")) {
1661
+ if (!cwd || !isAbsolute3(cwd) || cwd.includes("\0")) {
2632
1662
  throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
2633
1663
  }
2634
1664
  let initialRoot;
@@ -2718,6 +1748,100 @@ function nanoAiu(value) {
2718
1748
  }
2719
1749
  return value.toString();
2720
1750
  }
1751
+ function decisionNodes(events) {
1752
+ const nodes = [];
1753
+ const starts = /* @__PURE__ */ new Map();
1754
+ for (const event of events) {
1755
+ if (event.ephemeral === true) continue;
1756
+ let kind;
1757
+ let status = "recorded";
1758
+ let title;
1759
+ let content = "";
1760
+ let invocation;
1761
+ switch (event.type) {
1762
+ case "assistant.reasoning":
1763
+ if (event.data.content.trim().length === 0) continue;
1764
+ kind = "rationale";
1765
+ content = event.data.content;
1766
+ title = content.trim().split(/\r?\n/u)[0] ?? "Rationale";
1767
+ break;
1768
+ case "session.plan_changed":
1769
+ kind = "plan";
1770
+ title = `Plan ${event.data.operation === "create" ? "created" : event.data.operation === "update" ? "updated" : "deleted"}`;
1771
+ break;
1772
+ case "tool.execution_start": {
1773
+ const args = event.data.arguments;
1774
+ const description = args !== null && typeof args === "object" && !Array.isArray(args) && typeof args.description === "string" ? args.description.trim() : void 0;
1775
+ kind = "tool";
1776
+ title = description || event.data.toolTitle?.trim() || event.data.toolName;
1777
+ status = "started";
1778
+ invocation = `tool:${event.data.toolCallId}`;
1779
+ break;
1780
+ }
1781
+ case "tool.execution_complete":
1782
+ kind = "tool";
1783
+ title = event.data.toolDescription?.name ?? "Tool result";
1784
+ status = event.data.success ? "completed" : "failed";
1785
+ content = event.data.error?.message ?? "";
1786
+ invocation = `tool:${event.data.toolCallId}`;
1787
+ break;
1788
+ case "subagent.started":
1789
+ case "subagent.completed":
1790
+ case "subagent.failed":
1791
+ kind = "subagent";
1792
+ title = event.data.agentDisplayName;
1793
+ status = event.type === "subagent.started" ? "started" : event.type === "subagent.completed" ? "completed" : "failed";
1794
+ content = event.type === "subagent.started" ? event.data.agentDescription : event.type === "subagent.failed" ? event.data.error : "";
1795
+ invocation = `subagent:${event.data.toolCallId}`;
1796
+ break;
1797
+ case "assistant.message":
1798
+ if (event.data.content.trim().length === 0 || (event.data.toolRequests?.length ?? 0) > 0) continue;
1799
+ kind = "response";
1800
+ title = "Response";
1801
+ content = event.data.content;
1802
+ break;
1803
+ case "session.compaction_complete":
1804
+ kind = "compaction";
1805
+ status = event.data.success ? "completed" : "failed";
1806
+ title = "Compact context";
1807
+ content = [
1808
+ event.data.preCompactionTokens === void 0 ? void 0 : `Before: ${event.data.preCompactionTokens} tokens`,
1809
+ event.data.postCompactionTokens === void 0 ? void 0 : `After: ${event.data.postCompactionTokens} tokens`,
1810
+ event.data.tokensRemoved === void 0 ? void 0 : `Released: ${event.data.tokensRemoved} tokens`,
1811
+ event.data.trigger,
1812
+ event.data.error
1813
+ ].filter((part) => part !== void 0).join("\n\n");
1814
+ break;
1815
+ default:
1816
+ continue;
1817
+ }
1818
+ const previousIndex = invocation === void 0 ? void 0 : starts.get(invocation);
1819
+ const previous = previousIndex === void 0 ? void 0 : nodes[previousIndex];
1820
+ if (previous !== void 0 && previousIndex !== void 0) {
1821
+ nodes[previousIndex] = {
1822
+ ...previous,
1823
+ status,
1824
+ ...content.length === 0 ? {} : {
1825
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1826
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1827
+ }
1828
+ };
1829
+ } else {
1830
+ if (invocation !== void 0) starts.set(invocation, nodes.length);
1831
+ nodes.push({
1832
+ id: event.id,
1833
+ timestamp: event.timestamp,
1834
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId },
1835
+ kind,
1836
+ title: title.trim().slice(0, 256) || kind,
1837
+ status,
1838
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1839
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1840
+ });
1841
+ }
1842
+ }
1843
+ return nodes;
1844
+ }
2721
1845
  async function readWorkbenchMetrics(rpc) {
2722
1846
  if (rpc.usage === void 0 || rpc.model === void 0 || rpc.metadata?.contextInfo === void 0) {
2723
1847
  throw new WorkbenchRuntimeError("unsupported", "Runtime usage/context inspection is unavailable");
@@ -2734,6 +1858,7 @@ async function readWorkbenchMetrics(rpc) {
2734
1858
  outputTokenLimit: attributed === void 0 || attributed === null ? 0 : Math.max(0, attributed.limit - attributed.promptTokenLimit),
2735
1859
  ...modelId === void 0 ? {} : { selectedModel: modelId }
2736
1860
  });
1861
+ const heaviest = await rpc.metadata.getContextHeaviestMessages?.({ limit: 10 });
2737
1862
  return {
2738
1863
  ...modelId === void 0 ? {} : { modelId },
2739
1864
  totalPremiumRequestCost: usage.totalPremiumRequestCost,
@@ -2750,7 +1875,31 @@ async function readWorkbenchMetrics(rpc) {
2750
1875
  premiumRequestCost: metric.requests.cost,
2751
1876
  ...metric.totalNanoAiu === void 0 ? {} : { totalNanoAiu: nanoAiu(metric.totalNanoAiu) }
2752
1877
  }]),
2753
- context: contextInfo ?? null
1878
+ context: contextInfo ?? null,
1879
+ ...attributed === void 0 || attributed === null ? {} : {
1880
+ composition: [
1881
+ { kind: "System", count: attributed.categories.systemPrompt },
1882
+ { kind: "Instructions", count: attributed.categories.customInstructions },
1883
+ { kind: "Conversation", count: attributed.categories.messages },
1884
+ { kind: "Tools", count: attributed.categories.systemTools },
1885
+ { kind: "MCP", count: attributed.categories.mcpTools }
1886
+ ],
1887
+ sources: [...attributed.entries].sort((a, b) => b.tokens - a.tokens).slice(0, 24).map((entry) => ({
1888
+ id: entry.id.slice(0, 256),
1889
+ kind: entry.kind.slice(0, 256),
1890
+ label: entry.label.slice(0, 256),
1891
+ tokens: entry.tokens,
1892
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId.slice(0, 256) }
1893
+ })),
1894
+ sourcesTruncated: attributed.entries.length > 24,
1895
+ ...attributed.compactions === void 0 ? {} : { compactionCount: attributed.compactions.count }
1896
+ },
1897
+ ...heaviest === void 0 ? {} : { heaviestMessages: heaviest.messages.slice(0, 10).map((message) => ({
1898
+ id: message.id.slice(0, 256),
1899
+ kind: message.role.slice(0, 256),
1900
+ label: message.label.slice(0, 256),
1901
+ tokens: message.tokens
1902
+ })) }
2754
1903
  };
2755
1904
  }
2756
1905
  function projectWorkbenchInsights(result) {
@@ -2776,11 +1925,20 @@ function projectWorkbenchInsights(result) {
2776
1925
  ...result.context === null ? {} : { context: {
2777
1926
  currentTokens: result.context.totalTokens,
2778
1927
  tokenLimit: result.context.promptTokenLimit,
1928
+ displayLimit: result.context.limit,
1929
+ compactionThreshold: result.context.compactionThreshold,
2779
1930
  systemTokens: result.context.systemTokens,
2780
1931
  conversationTokens: result.context.conversationTokens,
2781
1932
  toolTokens: result.context.toolDefinitionsTokens
2782
1933
  } },
2783
1934
  canCompact: result.compactAllowed,
1935
+ ...result.composition === void 0 ? {} : { composition: result.composition },
1936
+ ...result.sources === void 0 ? {} : { sources: result.sources },
1937
+ ...result.sourcesTruncated === void 0 ? {} : { sourcesTruncated: result.sourcesTruncated },
1938
+ ...result.heaviestMessages === void 0 ? {} : { heaviestMessages: result.heaviestMessages },
1939
+ ...result.compactionCount === void 0 ? {} : { compactionCount: result.compactionCount },
1940
+ ...result.telemetry === void 0 ? {} : { telemetry: result.telemetry },
1941
+ ...result.storage === void 0 ? {} : { storage: result.storage },
2784
1942
  ...result.compactDisabledReason === void 0 ? {} : { compactUnavailableReason: result.compactDisabledReason }
2785
1943
  });
2786
1944
  }
@@ -2808,6 +1966,55 @@ var SessionWorkbenchRuntime = class {
2808
1966
  throw new WorkbenchOutcomeUncertainError("Session runtime changed during the operation; do not replay mutations");
2809
1967
  }
2810
1968
  }
1969
+ async reasoning(sessionId, request) {
1970
+ WorkbenchReasoningRequestSchema.parse(request);
1971
+ this.dependencies.assertAvailable(sessionId);
1972
+ const current2 = this.dependencies.currentSession(sessionId);
1973
+ if (current2 === void 0) {
1974
+ throw new WorkbenchRuntimeError("unsupported", "Open the session before reading its thinking history");
1975
+ }
1976
+ const generation = this.#generation(this.dependencies.getRuntime(sessionId));
1977
+ const session = await current2;
1978
+ this.#assertGeneration(sessionId, generation);
1979
+ if (session.rpc.eventLog === void 0) {
1980
+ throw new WorkbenchRuntimeError("unsupported", "Runtime thinking history is unavailable");
1981
+ }
1982
+ const page = await session.rpc.eventLog.read({
1983
+ ...request.cursor === void 0 ? {} : { cursor: request.cursor },
1984
+ direction: "backward",
1985
+ max: WORKBENCH_REASONING_PAGE_SIZE,
1986
+ types: [
1987
+ "assistant.reasoning",
1988
+ "session.plan_changed",
1989
+ "tool.execution_start",
1990
+ "tool.execution_complete",
1991
+ "subagent.started",
1992
+ "subagent.completed",
1993
+ "subagent.failed",
1994
+ "assistant.message",
1995
+ "session.compaction_complete"
1996
+ ],
1997
+ agentScope: "all",
1998
+ includeEphemeral: false
1999
+ });
2000
+ this.#assertGeneration(sessionId, generation);
2001
+ if (page.cursorStatus !== "ok") {
2002
+ throw new WorkbenchRuntimeError("stale-runtime", "Thinking history changed. Refresh to read it again.");
2003
+ }
2004
+ const nodes = decisionNodes(page.events);
2005
+ return WorkbenchReasoningPageSchema.parse({
2006
+ nodes,
2007
+ blocks: nodes.filter((node) => node.kind === "rationale").map((node) => ({
2008
+ id: node.id,
2009
+ timestamp: node.timestamp,
2010
+ ...node.agentId === void 0 ? {} : { agentId: node.agentId },
2011
+ content: node.content,
2012
+ truncated: node.truncated
2013
+ })),
2014
+ cursor: page.cursor,
2015
+ hasMore: page.hasMore
2016
+ });
2017
+ }
2811
2018
  async ask(sessionId, question) {
2812
2019
  z3.string().trim().min(1).max(16 * 1024).parse(question);
2813
2020
  this.dependencies.assertAvailable(sessionId);
@@ -2991,6 +2198,10 @@ var SessionWorkbenchRuntime = class {
2991
2198
  async readInsights(sessionId) {
2992
2199
  const { session, runtime, generation } = await this.#session(sessionId);
2993
2200
  const metrics = await readWorkbenchMetrics(session.rpc);
2201
+ const [telemetry, storage] = await Promise.all([
2202
+ this.dependencies.telemetry?.(sessionId),
2203
+ this.dependencies.storage?.(sessionId)
2204
+ ]);
2994
2205
  const reason = runtime.workbench.compacting ? "Context compaction is in progress" : await this.#compactionDisabledReason(sessionId, session, runtime);
2995
2206
  this.#assertGeneration(sessionId, generation);
2996
2207
  return {
@@ -2998,6 +2209,8 @@ var SessionWorkbenchRuntime = class {
2998
2209
  runtimeGeneration: generation,
2999
2210
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
3000
2211
  compactAllowed: reason === void 0,
2212
+ ...telemetry === void 0 ? {} : { telemetry },
2213
+ ...storage === void 0 ? {} : { storage },
3001
2214
  ...reason === void 0 ? {} : { compactDisabledReason: reason }
3002
2215
  };
3003
2216
  }
@@ -3144,11 +2357,13 @@ export {
3144
2357
  recordOperationTimelineRead,
3145
2358
  OperationDiagnostics,
3146
2359
  OperationMetrics,
3147
- isDisplayableHumanMessage,
3148
- ConversationNormalizer,
3149
2360
  SessionRuntime,
3150
2361
  SessionRuntimeRegistry,
3151
2362
  LiveTimelineProjection,
2363
+ SessionDirectoryError,
2364
+ contained,
2365
+ sessionRootIdentity,
2366
+ SessionDirectoryLister,
3152
2367
  sanitizeGitRemoteUrl,
3153
2368
  NotGitDirectoryError,
3154
2369
  resolveGitProjectIdentity,