@agentknight/sdk 0.9.64 → 0.9.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/chunks/{acp-adapter-MBYKOCA2.js → acp-adapter-VJ2OUSBS.js} +41 -4
  2. package/dist/chunks/{chunk-3AMFPDE5.js → chunk-2D34UDII.js} +4 -13
  3. package/dist/chunks/chunk-35OF2ZNS.js +275 -0
  4. package/dist/chunks/{chunk-A4YCCQ3I.js → chunk-5QYL6NKJ.js} +1 -1
  5. package/dist/chunks/chunk-ES2N66EH.js +109 -0
  6. package/dist/chunks/{chunk-P2PH5KMV.js → chunk-F5YCEWE4.js} +9 -0
  7. package/dist/chunks/{chunk-7CNBPLNE.js → chunk-IRYEOV62.js} +5 -2
  8. package/dist/chunks/{chunk-7OGTK7KB.js → chunk-J63A5OLO.js} +1 -1
  9. package/dist/chunks/chunk-LA6A4TUM.js +302 -0
  10. package/dist/chunks/{chunk-ZNQ2I5EF.js → chunk-LU73CEHE.js} +11 -132
  11. package/dist/chunks/chunk-MB34W52S.js +78 -0
  12. package/dist/chunks/{chunk-CHKNC6PD.js → chunk-MH7FDSTY.js} +1 -1
  13. package/dist/chunks/{chunk-ALUQLM54.js → chunk-Q5NNNSU2.js} +2 -2
  14. package/dist/chunks/chunk-UTF7KLMJ.js +11 -0
  15. package/dist/chunks/chunk-WAPJZKUK.js +115 -0
  16. package/dist/chunks/{chunk-SIFCCGXF.js → chunk-ZAU2MYQI.js} +2 -2
  17. package/dist/chunks/{claude-adapter-D3JWXMNX.js → claude-adapter-FZNLF5XN.js} +240 -27
  18. package/dist/chunks/{codex-adapter-655KHW7H.js → codex-adapter-5ZVOAT6O.js} +249 -66
  19. package/dist/chunks/{copilot-adapter-EZUXHBE3.js → copilot-adapter-V6RAQ4WK.js} +58 -149
  20. package/dist/chunks/{managed-agent-adapter-RIXRCURU.js → managed-agent-adapter-THUSTKRW.js} +35 -24
  21. package/dist/chunks/{pi-adapter-LAD5GOCP.js → pi-adapter-EHCSR5I2.js} +329 -54
  22. package/dist/configuration.js +4 -4
  23. package/dist/index.d.ts +15 -8
  24. package/dist/index.js +37 -35
  25. package/dist/runtime.js +2 -2
  26. package/dist/session-analytics-worker.js +6 -5
  27. package/package.json +3 -3
  28. package/dist/chunks/chunk-CM5LVXVL.js +0 -572
  29. package/dist/chunks/chunk-H4SHMWQ6.js +0 -48
@@ -0,0 +1,302 @@
1
+ import {
2
+ ConversationNormalizer
3
+ } from "./chunk-LU73CEHE.js";
4
+ import {
5
+ resolveCopilotSessionDirectory
6
+ } from "./chunk-35OF2ZNS.js";
7
+ import {
8
+ isContentfulAssistant
9
+ } from "./chunk-WAPJZKUK.js";
10
+ import {
11
+ SessionAnalyticsRequestSchema,
12
+ SessionTimelinePageSchema
13
+ } from "./chunk-F5YCEWE4.js";
14
+
15
+ // src/session-analytics-messages.ts
16
+ import { z } from "zod";
17
+ var AnalyticsEventSchema = z.object({
18
+ id: z.string().min(1).max(1024),
19
+ timestamp: z.iso.datetime({ offset: true }),
20
+ type: z.string(),
21
+ agentId: z.string().optional(),
22
+ data: z.record(z.string(), z.unknown())
23
+ });
24
+ var SessionId = z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
25
+ var Observation = z.object({ sessionId: SessionId, event: AnalyticsEventSchema });
26
+ var Gap = z.object({ sessionId: SessionId, since: z.number(), count: z.number().int().nonnegative() });
27
+ var History = {
28
+ sessionId: SessionId,
29
+ environment: z.object({ COPILOT_HOME: z.string().optional() }),
30
+ allowMissingEventLog: z.boolean()
31
+ };
32
+ var AnalyticsCommandSchema = z.discriminatedUnion("operation", [
33
+ z.object({ operation: z.literal("observe"), observations: z.array(Observation).max(32), gaps: z.array(Gap) }),
34
+ z.object({ operation: z.literal("index"), ...History }),
35
+ z.object({ operation: z.literal("read"), ...History, request: SessionAnalyticsRequestSchema }),
36
+ z.object({ operation: z.literal("telemetry"), ...History }),
37
+ z.object({ operation: z.literal("remove"), sessionId: SessionId }),
38
+ z.object({ operation: z.literal("close") })
39
+ ]);
40
+ var AnalyticsReplySchema = z.object({
41
+ id: z.number().int(),
42
+ result: z.unknown().optional(),
43
+ error: z.object({ code: z.string(), message: z.string() }).optional()
44
+ });
45
+ var AnalyticsIndexResultSchema = z.object({ complete: z.boolean(), catchUp: z.boolean() });
46
+
47
+ // src/session-update-reader.ts
48
+ import { lstat, open, realpath } from "node:fs/promises";
49
+ import { resolve } from "node:path";
50
+ import { z as z2 } from "zod";
51
+ var MAX_HEAD_BYTES = 8 * 1024 * 1024;
52
+ var EnvelopeSchema = z2.object({
53
+ id: z2.string(),
54
+ type: z2.string(),
55
+ timestamp: z2.iso.datetime({ offset: true }),
56
+ agentId: z2.string().optional(),
57
+ data: z2.unknown()
58
+ });
59
+ var HumanSchema = z2.object({
60
+ content: z2.string(),
61
+ messageId: z2.string().optional(),
62
+ interactionId: z2.string().optional(),
63
+ source: z2.string().optional(),
64
+ isAutopilotContinuation: z2.boolean().optional()
65
+ });
66
+ var AssistantSchema = z2.object({
67
+ messageId: z2.string(),
68
+ content: z2.string(),
69
+ parentToolCallId: z2.string().optional(),
70
+ apiCallId: z2.string().optional(),
71
+ chunkIndex: z2.number().int().nonnegative().optional(),
72
+ chunkCount: z2.number().int().positive().optional(),
73
+ interactionId: z2.string().optional(),
74
+ turnId: z2.string().optional()
75
+ });
76
+ var ToolStartSchema = z2.object({
77
+ toolCallId: z2.string(),
78
+ toolName: z2.string(),
79
+ parentToolCallId: z2.string().optional()
80
+ });
81
+ var ImageSchema = z2.object({
82
+ type: z2.literal("image"),
83
+ data: z2.string(),
84
+ mimeType: z2.string()
85
+ });
86
+ var ImageReferenceSchema = z2.object({
87
+ type: z2.literal("image"),
88
+ assetId: z2.string(),
89
+ mimeType: z2.string(),
90
+ byteLength: z2.number()
91
+ });
92
+ var ToolCompleteSchema = z2.object({
93
+ toolCallId: z2.string(),
94
+ success: z2.boolean(),
95
+ result: z2.object({
96
+ content: z2.string().optional(),
97
+ binaryResultsForLlm: z2.array(z2.unknown()).optional(),
98
+ contents: z2.array(z2.unknown()).optional()
99
+ }).optional(),
100
+ toolDescription: z2.object({ name: z2.string() }).optional(),
101
+ parentToolCallId: z2.string().optional()
102
+ });
103
+ var NoticeSchema = z2.object({ message: z2.string() });
104
+ var NotificationSchema = z2.object({ kind: z2.object({ type: z2.string() }).passthrough() });
105
+ var ShellCompletedSchema = z2.object({
106
+ type: z2.literal("shell_completed"),
107
+ shellId: z2.string(),
108
+ exitCode: z2.number().int().optional()
109
+ });
110
+ function metadataEvent(value, preview = false) {
111
+ const event = EnvelopeSchema.parse(value);
112
+ const toolEvent = event.type === "tool.execution_start" || event.type === "tool.execution_complete";
113
+ if (event.agentId !== void 0 && !toolEvent) return void 0;
114
+ const base = {
115
+ id: event.id,
116
+ timestamp: event.timestamp,
117
+ parentId: null,
118
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId }
119
+ };
120
+ switch (event.type) {
121
+ case "session.binary_asset": {
122
+ if (!preview) return void 0;
123
+ const parsed = ImageSchema.extend({ assetId: z2.string(), byteLength: z2.number() }).safeParse(event.data);
124
+ return parsed.success ? { ...base, type: "session.binary_asset", data: parsed.data } : void 0;
125
+ }
126
+ case "user.message": {
127
+ const data = HumanSchema.parse(event.data);
128
+ if (data.isAutopilotContinuation === true) return void 0;
129
+ return { ...base, type: "user.message", data: {
130
+ content: data.content,
131
+ ...data.messageId === void 0 ? {} : { messageId: data.messageId },
132
+ ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
133
+ ...data.source === void 0 ? {} : { source: data.source }
134
+ } };
135
+ }
136
+ case "assistant.message": {
137
+ const data = AssistantSchema.parse(event.data);
138
+ if (data.parentToolCallId !== void 0) return void 0;
139
+ return { ...base, type: "assistant.message", data: {
140
+ messageId: data.messageId,
141
+ content: data.content,
142
+ ...data.apiCallId === void 0 ? {} : { apiCallId: data.apiCallId },
143
+ ...data.chunkIndex === void 0 ? {} : { chunkIndex: data.chunkIndex },
144
+ ...data.chunkCount === void 0 ? {} : { chunkCount: data.chunkCount },
145
+ ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
146
+ ...data.turnId === void 0 ? {} : { turnId: data.turnId }
147
+ } };
148
+ }
149
+ case "tool.execution_start": {
150
+ const data = ToolStartSchema.parse(event.data);
151
+ return preview || data.toolName === "task_complete" ? {
152
+ ...base,
153
+ type: "tool.execution_start",
154
+ data: {
155
+ toolCallId: data.toolCallId,
156
+ toolName: data.toolName,
157
+ ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
158
+ }
159
+ } : void 0;
160
+ }
161
+ case "tool.execution_complete": {
162
+ const data = ToolCompleteSchema.parse(event.data);
163
+ const images = preview ? data.result?.binaryResultsForLlm?.flatMap((value2) => {
164
+ const parsed = z2.union([ImageSchema, ImageReferenceSchema]).safeParse(value2);
165
+ return parsed.success ? [parsed.data] : [];
166
+ }) ?? [] : [];
167
+ const contents = preview ? data.result?.contents?.flatMap((value2) => {
168
+ const parsed = ImageSchema.safeParse(value2);
169
+ return parsed.success ? [parsed.data] : [];
170
+ }) ?? [] : [];
171
+ return {
172
+ ...base,
173
+ type: "tool.execution_complete",
174
+ data: {
175
+ toolCallId: data.toolCallId,
176
+ success: data.success,
177
+ ...data.result === void 0 ? {} : { result: {
178
+ content: data.result.content ?? "",
179
+ binaryResultsForLlm: images,
180
+ contents
181
+ } },
182
+ ...data.toolDescription === void 0 ? {} : { toolDescription: data.toolDescription },
183
+ ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
184
+ }
185
+ };
186
+ }
187
+ case "session.error": {
188
+ const data = NoticeSchema.extend({ errorType: z2.string() }).parse(event.data);
189
+ return { ...base, type: "session.error", data };
190
+ }
191
+ case "session.warning": {
192
+ const data = NoticeSchema.extend({ warningType: z2.string() }).parse(event.data);
193
+ return { ...base, type: "session.warning", data };
194
+ }
195
+ case "system.notification": {
196
+ const { kind } = NotificationSchema.parse(event.data);
197
+ if (kind.type !== "shell_completed") return void 0;
198
+ const shell = ShellCompletedSchema.parse(kind);
199
+ return {
200
+ ...base,
201
+ type: "system.notification",
202
+ data: {
203
+ content: "",
204
+ kind: {
205
+ type: "shell_completed",
206
+ shellId: shell.shellId,
207
+ ...shell.exitCode === void 0 ? {} : { exitCode: shell.exitCode }
208
+ }
209
+ }
210
+ };
211
+ }
212
+ default:
213
+ return void 0;
214
+ }
215
+ }
216
+ async function openSessionEventLog(sessionId, environment = process.env, options = {}) {
217
+ const directory = await realpath(resolveCopilotSessionDirectory(sessionId, environment));
218
+ const expectedPath = resolve(directory, "events.jsonl");
219
+ if (options.allowMissingEventLog?.() === true) {
220
+ try {
221
+ await lstat(expectedPath);
222
+ } catch (error) {
223
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
224
+ await realpath(directory);
225
+ if (options.allowMissingEventLog?.() !== true) throw error;
226
+ return void 0;
227
+ }
228
+ }
229
+ const path = await realpath(expectedPath);
230
+ if (path !== expectedPath) throw new Error("Session event log must not be a symbolic link");
231
+ return open(path, "r");
232
+ }
233
+ async function readSessionUpdatePage(sessionId, environment = process.env, resolveInputProvenance, options = {}) {
234
+ const file = await openSessionEventLog(sessionId, environment, options);
235
+ if (file === void 0) return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
236
+ try {
237
+ const { size } = await file.stat();
238
+ if (size === 0) {
239
+ options.onEventLogRead?.();
240
+ return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
241
+ }
242
+ const start = Math.max(0, size - MAX_HEAD_BYTES);
243
+ const buffer = Buffer.alloc(size - start);
244
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
245
+ const text = buffer.subarray(0, bytesRead).toString("utf8");
246
+ const first = start === 0 ? 0 : text.indexOf("\n") + 1;
247
+ const end = text.lastIndexOf("\n");
248
+ if (first === 0 && start > 0 || end < first) {
249
+ throw new Error("Session event log has no complete records in its metadata window");
250
+ }
251
+ const events = text.slice(first, end).split("\n").filter((line) => line.trim().length > 0).map((line) => metadataEvent(JSON.parse(line), options.assistantPreview === true)).filter((event) => event !== void 0);
252
+ const toolStarts = events.filter((event) => event.type === "tool.execution_start");
253
+ const taskCompletionCallIdsWithStart = new Set(events.flatMap((event) => event.type === "tool.execution_start" && event.data.toolName === "task_complete" ? [event.data.toolCallId] : []));
254
+ const rootTools = new Set(toolStarts.filter((event) => event.agentId === void 0 && event.data.parentToolCallId === void 0).map((event) => event.data.toolCallId));
255
+ const childTools = new Set(toolStarts.filter((event) => event.agentId !== void 0 || event.data.parentToolCallId !== void 0).map((event) => event.data.toolCallId));
256
+ const hasCompleteHistory = start === 0;
257
+ const eventsForMetadata = events.filter((event) => {
258
+ if (event.type === "tool.execution_start" && event.data.toolName !== "task_complete") return false;
259
+ if (event.type !== "tool.execution_complete") {
260
+ return true;
261
+ }
262
+ if (options.assistantPreview === true && event.agentId === void 0 && event.data.parentToolCallId === void 0 && !childTools.has(event.data.toolCallId) && (hasCompleteHistory || rootTools.has(event.data.toolCallId)) && ((event.data.result?.binaryResultsForLlm?.length ?? 0) > 0 || (event.data.result?.contents?.length ?? 0) > 0)) return true;
263
+ if (taskCompletionCallIdsWithStart.has(event.data.toolCallId)) {
264
+ return true;
265
+ }
266
+ if (!hasCompleteHistory) {
267
+ return false;
268
+ }
269
+ return event.data.toolDescription?.name === "task_complete";
270
+ });
271
+ const normalizer = new ConversationNormalizer(void 0, void 0, resolveInputProvenance);
272
+ normalizer.apply(eventsForMetadata);
273
+ const items = normalizer.snapshot().filter((item) => (item.kind === "human-message" || item.kind === "assistant-message" || item.kind === "notice") && (item.actor === "human" || item.actor === "assistant" || item.actor === "system" || item.kind === "assistant-message" && item.actor === "subagent"));
274
+ const latest = items.at(-1);
275
+ const assistant = options.assistantPreview === true ? [...items].reverse().find(isContentfulAssistant) : void 0;
276
+ const human = options.assistantPreview === true ? [...items].reverse().find((item) => item.kind === "human-message" && item.actor === "human") : void 0;
277
+ const completion = [...items].reverse().find((item) => item.kind === "notice" && item.actor === "assistant" && item.severity === "success" && item.title === "Task completed");
278
+ const page = SessionTimelinePageSchema.parse({
279
+ items: [completion, latest, assistant, human].filter((item, index, all) => item !== void 0 && all.findIndex((candidate) => candidate?.id === item.id) === index).map((item) => item?.kind === "human-message" || item?.kind === "assistant-message" ? {
280
+ ...item,
281
+ content: item.id === assistant?.id || item.id === human?.id ? item.content.slice(0, 4096) : "",
282
+ attachments: item.id === assistant?.id ? item.attachments ?? [] : []
283
+ } : { ...item, content: item?.kind === "notice" && item.id === assistant?.id ? item.content.slice(0, 4096) : "" }),
284
+ hasMore: start > 0,
285
+ cursor: "",
286
+ cursorStatus: "ok"
287
+ });
288
+ options.onEventLogRead?.();
289
+ return page;
290
+ } finally {
291
+ await file.close();
292
+ }
293
+ }
294
+
295
+ export {
296
+ openSessionEventLog,
297
+ readSessionUpdatePage,
298
+ AnalyticsEventSchema,
299
+ AnalyticsCommandSchema,
300
+ AnalyticsReplySchema,
301
+ AnalyticsIndexResultSchema
302
+ };
@@ -1,40 +1,17 @@
1
+ import {
2
+ decodeTimelineImage,
3
+ normalizeImageMimeType,
4
+ splitTimelineImages
5
+ } from "./chunk-WAPJZKUK.js";
1
6
  import {
2
7
  CONVERSATION_SOURCE_ID_LIMIT
3
- } from "./chunk-P2PH5KMV.js";
8
+ } from "./chunk-F5YCEWE4.js";
4
9
 
5
10
  // src/conversation-normalizer.ts
6
11
  import { createHash } from "node:crypto";
7
12
  var SUMMARY_LIMIT = 4096;
8
13
  var IDENTIFIER_LIMIT = 256;
9
14
  var TASK_COMPLETE_TOOL_NAME = "task_complete";
10
- var MAX_INLINE_IMAGE_BYTES = 3 * 1024 * 1024;
11
- var MAX_INLINE_IMAGE_MESSAGE_BYTES = 3 * 1024 * 1024;
12
- var MAX_INLINE_IMAGES_PER_MESSAGE = 4;
13
- var SUPPORTED_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set([
14
- "image/gif",
15
- "image/jpeg",
16
- "image/png",
17
- "image/webp"
18
- ]);
19
- function splitToolImages(images) {
20
- const groups = [];
21
- let group = [];
22
- let groupBytes = 0;
23
- for (const image of images) {
24
- const imageBytes = image.attachment.byteLength ?? 0;
25
- if (group.length > 0 && (group.length >= MAX_INLINE_IMAGES_PER_MESSAGE || groupBytes + imageBytes > MAX_INLINE_IMAGE_MESSAGE_BYTES)) {
26
- groups.push(group);
27
- group = [];
28
- groupBytes = 0;
29
- }
30
- group.push(image);
31
- groupBytes += imageBytes;
32
- }
33
- if (group.length > 0) {
34
- groups.push(group);
35
- }
36
- return groups;
37
- }
38
15
  function protocolId(value) {
39
16
  if (value.length <= IDENTIFIER_LIMIT) {
40
17
  return value;
@@ -261,106 +238,15 @@ function projectCitation(source) {
261
238
  name: source.title ?? source.id
262
239
  };
263
240
  }
264
- function normalizeImageMimeType(value) {
265
- return value.toLowerCase() === "image/jpg" ? "image/jpeg" : value.toLowerCase();
266
- }
267
- function hasImageSignature(bytes, mimeType) {
268
- switch (mimeType) {
269
- case "image/jpeg":
270
- return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
271
- case "image/png":
272
- return bytes.length >= 8 && bytes.subarray(0, 8).equals(
273
- Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
274
- );
275
- case "image/webp":
276
- return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
277
- case "image/gif":
278
- return bytes.length >= 6 && (bytes.subarray(0, 6).toString("ascii") === "GIF87a" || bytes.subarray(0, 6).toString("ascii") === "GIF89a");
279
- default:
280
- return false;
281
- }
282
- }
283
- function decodeImageBase64(value, expectedMimeType) {
284
- const dataUrlMatch = /^data:([^;,]+);base64,(.*)$/isu.exec(value);
285
- if (dataUrlMatch !== null && normalizeImageMimeType(dataUrlMatch[1] ?? "") !== expectedMimeType) {
286
- return void 0;
287
- }
288
- const payload = dataUrlMatch?.[2] ?? value;
289
- const normalized = payload.replaceAll("-", "+").replaceAll("_", "/");
290
- if (normalized.length === 0 || normalized.length % 4 === 1 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized)) {
291
- return void 0;
292
- }
293
- const bytes = Buffer.from(normalized, "base64");
294
- return bytes.toString("base64").replace(/=+$/u, "") === normalized.replace(/=+$/u, "") ? bytes : void 0;
295
- }
296
- function projectInlineToolImage(data, mimeTypeValue, name, expectedByteLength, source = "binary-result") {
241
+ function projectInlineToolImage(data, mimeTypeValue, name, source = "binary-result") {
297
242
  const mimeType = normalizeImageMimeType(mimeTypeValue);
298
243
  const metadata = {
299
244
  kind: "image",
300
245
  name: boundedText(name, 1024, "Copilot image"),
301
246
  mimeType: boundedText(mimeType, 256, "application/octet-stream")
302
247
  };
303
- if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) {
304
- return {
305
- attachment: metadata,
306
- failure: { source, reason: "mime-unsupported", mimeType }
307
- };
308
- }
309
- const bytes = decodeImageBase64(data, mimeType);
310
- if (bytes === void 0) {
311
- return {
312
- attachment: metadata,
313
- failure: { source, reason: "data-invalid", mimeType }
314
- };
315
- }
316
- if (bytes.length === 0) {
317
- return {
318
- attachment: metadata,
319
- failure: { source, reason: "data-empty", mimeType, actualByteLength: 0 }
320
- };
321
- }
322
- if (bytes.length > MAX_INLINE_IMAGE_BYTES) {
323
- return {
324
- attachment: metadata,
325
- failure: {
326
- source,
327
- reason: "data-too-large",
328
- mimeType,
329
- actualByteLength: bytes.length
330
- }
331
- };
332
- }
333
- if (expectedByteLength !== void 0 && bytes.length !== expectedByteLength) {
334
- return {
335
- attachment: metadata,
336
- failure: {
337
- source,
338
- reason: "length-mismatch",
339
- mimeType,
340
- expectedByteLength,
341
- actualByteLength: bytes.length
342
- }
343
- };
344
- }
345
- if (!hasImageSignature(bytes, mimeType)) {
346
- return {
347
- attachment: metadata,
348
- failure: {
349
- source,
350
- reason: "signature-mismatch",
351
- mimeType,
352
- actualByteLength: bytes.length
353
- }
354
- };
355
- }
356
- return {
357
- attachment: {
358
- ...metadata,
359
- data: bytes.toString("base64"),
360
- byteLength: bytes.length,
361
- sha256: createHash("sha256").update(bytes).digest("hex")
362
- }
363
- };
248
+ const image = decodeTimelineImage(data, mimeType, source);
249
+ return "failure" in image ? { attachment: metadata, failure: image.failure } : { attachment: { ...metadata, ...image } };
364
250
  }
365
251
  function projectToolBinaryResult(result, name, assets) {
366
252
  if (result.type !== "image") {
@@ -398,7 +284,6 @@ function projectToolBinaryResult(result, name, assets) {
398
284
  asset.data.data,
399
285
  asset.data.mimeType,
400
286
  result.description ?? asset.data.description ?? name,
401
- void 0,
402
287
  "binary-asset"
403
288
  );
404
289
  const attachment = projected.attachment;
@@ -448,13 +333,7 @@ function projectToolBinaryResult(result, name, assets) {
448
333
  };
449
334
  }
450
335
  function projectToolContentImage(image, name) {
451
- return projectInlineToolImage(
452
- image.data,
453
- image.mimeType,
454
- name,
455
- void 0,
456
- "content"
457
- );
336
+ return projectInlineToolImage(image.data, image.mimeType, name, "content");
458
337
  }
459
338
  function permissionName(kind) {
460
339
  const words = kind.replaceAll("_", " ").replaceAll("-", " ");
@@ -1138,7 +1017,7 @@ var ConversationNormalizer = class {
1138
1017
  toolName
1139
1018
  });
1140
1019
  }
1141
- const imageGroups = splitToolImages(projectedImages);
1020
+ const imageGroups = splitTimelineImages(projectedImages, (image) => image.attachment.byteLength ?? 0);
1142
1021
  return imageGroups.map((imageGroup, groupIndex) => {
1143
1022
  const multipleGroups = imageGroups.length > 1;
1144
1023
  const id = scopedId(
@@ -0,0 +1,78 @@
1
+ import {
2
+ PromptPreparationError
3
+ } from "./chunk-UTF7KLMJ.js";
4
+ import {
5
+ stagePromptAttachments,
6
+ validatePromptAttachments
7
+ } from "./chunk-ES2N66EH.js";
8
+ import {
9
+ decodeTimelineImage,
10
+ normalizeImageMimeType
11
+ } from "./chunk-WAPJZKUK.js";
12
+ import {
13
+ SessionPromptRequestSchema
14
+ } from "./chunk-F5YCEWE4.js";
15
+
16
+ // src/adapters/prompt-media.ts
17
+ import { join } from "node:path";
18
+ async function prepareNativePrompt(root, sessionKey, text, images, files) {
19
+ try {
20
+ if (images.length || files.length) {
21
+ SessionPromptRequestSchema.parse({
22
+ machineId: "local",
23
+ sessionId: sessionKey,
24
+ requestId: "prepare",
25
+ operationId: "prepare",
26
+ prompt: text,
27
+ attachments: images,
28
+ fileAttachments: files
29
+ });
30
+ }
31
+ const validated = validatePromptAttachments(images, files);
32
+ for (const image of images) {
33
+ if ("failure" in decodeTimelineImage(image.data, image.mimeType, "content")) throw new Error("Invalid prompt image");
34
+ }
35
+ const staged = await stagePromptAttachments(
36
+ sessionKey,
37
+ { images: [], files: validated.files },
38
+ join(root, "uploads", sessionKey)
39
+ );
40
+ const fileParts = staged.flatMap((item) => item.type === "file" ? [item] : []);
41
+ const attachments = [
42
+ ...images.map(({ name, mimeType, byteLength, data, sha256 }) => ({ kind: "image", name, mimeType, byteLength, data, sha256 })),
43
+ ...fileParts.map((item, index) => {
44
+ const file = validated.files[index]?.attachment;
45
+ if (!file) throw new Error("Missing staged attachment");
46
+ return { kind: "file", name: file.name, mimeType: file.mimeType, uri: item.path };
47
+ })
48
+ ];
49
+ return {
50
+ attachments,
51
+ text: fileParts.length ? `${text}
52
+
53
+ Uploaded files (name and local path):
54
+ ${fileParts.map(
55
+ (file) => JSON.stringify({ name: file.displayName, path: file.path })
56
+ ).join("\n")}` : text,
57
+ images
58
+ };
59
+ } catch (error) {
60
+ throw new PromptPreparationError(error);
61
+ }
62
+ }
63
+ function projectNativeImage(data, type, name = "Image") {
64
+ const mimeType = normalizeImageMimeType(type);
65
+ const image = decodeTimelineImage(data, mimeType, "content");
66
+ return "failure" in image ? void 0 : { kind: "image", name, mimeType, ...image };
67
+ }
68
+ function projectNativeImageUrl(url) {
69
+ if (typeof url !== "string") return void 0;
70
+ const match = /^data:(image\/[a-z]+);base64,/iu.exec(url);
71
+ return match?.[1] === void 0 ? void 0 : projectNativeImage(url, match[1]);
72
+ }
73
+
74
+ export {
75
+ prepareNativePrompt,
76
+ projectNativeImage,
77
+ projectNativeImageUrl
78
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  IdSchema
3
- } from "./chunk-P2PH5KMV.js";
3
+ } from "./chunk-F5YCEWE4.js";
4
4
 
5
5
  // src/data-directory.ts
6
6
  import { randomUUID } from "node:crypto";
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  AgentSessionRenameError,
3
3
  validateSessionName
4
- } from "./chunk-7CNBPLNE.js";
4
+ } from "./chunk-IRYEOV62.js";
5
5
  import {
6
6
  ConversationItemSchema,
7
7
  GroupChatInfoSchema,
8
8
  GroupChatParticipantSchema,
9
9
  SESSION_TIMELINE_PAGE_SIZE,
10
10
  SessionSummarySchema
11
- } from "./chunk-P2PH5KMV.js";
11
+ } from "./chunk-F5YCEWE4.js";
12
12
 
13
13
  // src/group-chat.ts
14
14
  import { createHash, randomUUID } from "node:crypto";
@@ -0,0 +1,11 @@
1
+ // src/prompt-preparation-error.ts
2
+ var PromptPreparationError = class extends Error {
3
+ constructor(cause) {
4
+ super(cause instanceof Error ? cause.message : "Prompt preparation failed", { cause });
5
+ this.name = "PromptPreparationError";
6
+ }
7
+ };
8
+
9
+ export {
10
+ PromptPreparationError
11
+ };