@agentknight/sdk 0.9.56 → 0.9.57

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,14 +2,18 @@ import {
2
2
  SessionImageRelayUrlSchema,
3
3
  SessionImagesConfigSchema
4
4
  } from "./chunk-IJPJQF7S.js";
5
+ import {
6
+ ConversationNormalizer,
7
+ ConversationToolLifecycles,
8
+ assistantMessageId
9
+ } from "./chunk-LT5ULDVT.js";
5
10
  import {
6
11
  isContentfulAssistant
7
- } from "./chunk-5J7BK2Y7.js";
12
+ } from "./chunk-IPJWNGNK.js";
8
13
  import {
9
14
  SessionOperationError
10
- } from "./chunk-L3A736SO.js";
15
+ } from "./chunk-7ZYBES47.js";
11
16
  import {
12
- CONVERSATION_SOURCE_ID_LIMIT,
13
17
  IdSchema,
14
18
  SESSION_DIRECTORY_LIST_OPERATION,
15
19
  SESSION_FILE_DOWNLOAD_OPERATION,
@@ -37,13 +41,13 @@ import {
37
41
  WorkbenchInsightsSchema,
38
42
  WorkbenchQueueMutationResultSchema,
39
43
  WorkbenchQueueSnapshotSchema
40
- } from "./chunk-K5CMKBW6.js";
44
+ } from "./chunk-KBI5IWPR.js";
41
45
 
42
46
  // src/session-image-uploader.ts
43
47
  import { createHash } from "node:crypto";
44
48
  import { setTimeout as delay } from "node:timers/promises";
45
49
  import { z } from "zod";
46
- var MAX_ACTIVE_UPLOADS = 3;
50
+ var MAX_ACTIVE_UPLOADS = 16;
47
51
  var MAX_JSON_BYTES = 16 * 1024;
48
52
  var REQUEST_TIMEOUT_MS = 2e4;
49
53
  var UPLOAD_TIMEOUT_MS = 7e4;
@@ -55,8 +59,12 @@ var UploaderConfigSchema = z.object({
55
59
  machineId: IdSchema,
56
60
  storageAccount: SessionImagesConfigSchema.shape.storageAccount,
57
61
  storageContainer: SessionImagesConfigSchema.shape.storageContainer,
58
- mode: SessionImageStorageSchema.shape.mode.optional()
59
- });
62
+ mode: SessionImageStorageSchema.shape.mode.optional(),
63
+ clientVerifiedUploads: z.boolean().default(false)
64
+ }).refine(
65
+ (value) => !value.clientVerifiedUploads || value.mode === "direct",
66
+ "Client-verified uploads require negotiated direct storage"
67
+ );
60
68
  function safeCause(error) {
61
69
  if (error instanceof SessionImageUploadError) return error;
62
70
  if (error instanceof z.ZodError) return new Error("Schema validation failed.");
@@ -158,7 +166,11 @@ var SessionImageUploader = class {
158
166
  const bytes = Buffer.from(source);
159
167
  const dimensions = await this.#dimensions(bytes);
160
168
  const hash = digest(bytes);
161
- const request = parse(SessionImageUploadRequestSchema, { ...scope, sizeBytes: bytes.length }, "source");
169
+ const request = parse(SessionImageUploadRequestSchema, {
170
+ ...scope,
171
+ sizeBytes: bytes.length,
172
+ ...this.#config.clientVerifiedUploads ? { verifiedContent: { ...dimensions, sha256: hash } } : {}
173
+ }, "source");
162
174
  revalidate("reserve");
163
175
  const upload = await this.#json(
164
176
  `${SESSION_IMAGE_API_PATH}/uploads`,
@@ -238,6 +250,7 @@ var SessionImageUploader = class {
238
250
  try {
239
251
  const metadata = await decoder.metadata();
240
252
  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");
253
+ if (this.#config.clientVerifiedUploads) await decoder.stats();
241
254
  return { width: metadata.width, height: metadata.height };
242
255
  } finally {
243
256
  decoder.destroy();
@@ -267,7 +280,8 @@ var SessionImageUploader = class {
267
280
  }
268
281
  const { storageAccount, storageContainer, userId, machineId } = this.#config;
269
282
  const host = `${storageAccount}.blob.core.windows.net`;
270
- const path = `/${storageContainer}/uploads/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
283
+ const prefix = this.#config.clientVerifiedUploads ? "images" : "uploads";
284
+ const path = `/${storageContainer}/${prefix}/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
271
285
  const url = new URL(upload.uploadUrl);
272
286
  const query = url.searchParams;
273
287
  const allowed = /* @__PURE__ */ new Set(["sv", "spr", "st", "se", "sr", "sp", "sig", "skoid", "sktid", "skt", "ske", "sks", "skv"]);
@@ -353,7 +367,7 @@ var SessionImageUploader = class {
353
367
  try {
354
368
  return await this.#attempt(url, init, stage, signal, consume);
355
369
  } 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"));
370
+ 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
371
  if (!retryable || attempt >= 2 || signal.aborted) throw error;
358
372
  const wait = Math.max(error.retryAfterMs ?? 0, 250 * 2 ** attempt + Math.floor(Math.random() * 250));
359
373
  if (wait > 5e3) throw error;
@@ -753,1213 +767,6 @@ var OperationMetrics = class {
753
767
  }
754
768
  };
755
769
 
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
770
  // src/session-runtime.ts
1964
771
  import { randomUUID as randomUUID2 } from "node:crypto";
1965
772
 
@@ -2478,7 +1285,7 @@ function sanitizeGitRemoteUrl(value) {
2478
1285
 
2479
1286
  // src/git-project-identity.ts
2480
1287
  import { execFile } from "node:child_process";
2481
- import { createHash as createHash4 } from "node:crypto";
1288
+ import { createHash as createHash3 } from "node:crypto";
2482
1289
  import { realpath } from "node:fs/promises";
2483
1290
  import { isAbsolute, resolve } from "node:path";
2484
1291
  import { promisify } from "node:util";
@@ -2572,7 +1379,7 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
2572
1379
  return {
2573
1380
  worktreeRoot,
2574
1381
  commonGitDirectory,
2575
- localRepositoryKey: createHash4("sha256").update(commonGitDirectory).digest("base64url"),
1382
+ localRepositoryKey: createHash3("sha256").update(commonGitDirectory).digest("base64url"),
2576
1383
  ...mainWorktreeRoot === void 0 ? {} : { mainWorktreeRoot },
2577
1384
  ...gitRemoteUrl === void 0 ? {} : { gitRemoteUrl }
2578
1385
  };
@@ -2685,7 +1492,7 @@ var SessionProjectIdentityReader = class {
2685
1492
  };
2686
1493
 
2687
1494
  // src/session-workbench-runtime.ts
2688
- import { createHash as createHash5 } from "node:crypto";
1495
+ import { createHash as createHash4 } from "node:crypto";
2689
1496
  import { z as z3 } from "zod";
2690
1497
  var WorkbenchRuntimeError = class extends SessionOperationError {
2691
1498
  constructor(code, message) {
@@ -2861,7 +1668,7 @@ var SessionWorkbenchRuntime = class {
2861
1668
  }
2862
1669
  return {
2863
1670
  runtimeGeneration: generation,
2864
- revision: createHash5("sha256").update(JSON.stringify(pending)).digest("hex"),
1671
+ revision: createHash4("sha256").update(JSON.stringify(pending)).digest("hex"),
2865
1672
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
2866
1673
  items: [...groups.values()],
2867
1674
  steeringMessages: pending.steeringMessages
@@ -3144,8 +1951,6 @@ export {
3144
1951
  recordOperationTimelineRead,
3145
1952
  OperationDiagnostics,
3146
1953
  OperationMetrics,
3147
- isDisplayableHumanMessage,
3148
- ConversationNormalizer,
3149
1954
  SessionRuntime,
3150
1955
  SessionRuntimeRegistry,
3151
1956
  LiveTimelineProjection,