@agentknight/sdk 0.9.68 → 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 (27) hide show
  1. package/dist/chunks/{acp-adapter-RZX5SUB3.js → acp-adapter-VJ2OUSBS.js} +41 -4
  2. package/dist/chunks/{chunk-FY4XTWUF.js → chunk-2D34UDII.js} +4 -13
  3. package/dist/chunks/{chunk-AWVC5NX4.js → chunk-5QYL6NKJ.js} +1 -1
  4. package/dist/chunks/{chunk-B777YB6E.js → chunk-ES2N66EH.js} +1 -1
  5. package/dist/chunks/{chunk-DWTXWVIA.js → chunk-F5YCEWE4.js} +3 -0
  6. package/dist/chunks/{chunk-CFQQOAQV.js → chunk-IRYEOV62.js} +2 -2
  7. package/dist/chunks/{chunk-UHRUQM4D.js → chunk-J63A5OLO.js} +1 -1
  8. package/dist/chunks/{chunk-Y6NCJB55.js → chunk-LA6A4TUM.js} +3 -3
  9. package/dist/chunks/{chunk-EDYVCZIR.js → chunk-LU73CEHE.js} +2 -2
  10. package/dist/chunks/chunk-MB34W52S.js +78 -0
  11. package/dist/chunks/{chunk-Q5OUZJCZ.js → chunk-MH7FDSTY.js} +1 -1
  12. package/dist/chunks/{chunk-MB3H6HEI.js → chunk-Q5NNNSU2.js} +2 -2
  13. package/dist/chunks/chunk-UTF7KLMJ.js +11 -0
  14. package/dist/chunks/{chunk-4XT65OSG.js → chunk-WAPJZKUK.js} +46 -3
  15. package/dist/chunks/{chunk-LCA2MWOQ.js → chunk-ZAU2MYQI.js} +2 -2
  16. package/dist/chunks/{claude-adapter-FQSQIYUY.js → claude-adapter-FZNLF5XN.js} +240 -27
  17. package/dist/chunks/{codex-adapter-TOXSRT2W.js → codex-adapter-5ZVOAT6O.js} +249 -66
  18. package/dist/chunks/{copilot-adapter-KUCX7XQW.js → copilot-adapter-V6RAQ4WK.js} +13 -12
  19. package/dist/chunks/{managed-agent-adapter-LGBRXDGP.js → managed-agent-adapter-THUSTKRW.js} +9 -7
  20. package/dist/chunks/{pi-adapter-RXNZSE4F.js → pi-adapter-EHCSR5I2.js} +6 -8
  21. package/dist/configuration.js +4 -4
  22. package/dist/index.d.ts +15 -8
  23. package/dist/index.js +35 -22
  24. package/dist/runtime.js +2 -2
  25. package/dist/session-analytics-worker.js +5 -6
  26. package/package.json +3 -3
  27. package/dist/chunks/chunk-IXGVSREH.js +0 -48
@@ -1,22 +1,35 @@
1
1
  import {
2
- latestPreviewItems
3
- } from "./chunk-IXGVSREH.js";
2
+ prepareNativePrompt,
3
+ projectNativeImage,
4
+ projectNativeImageUrl
5
+ } from "./chunk-MB34W52S.js";
4
6
  import {
5
- UnsupportedAgentOperationError
6
- } from "./chunk-CFQQOAQV.js";
7
- import "./chunk-UHRUQM4D.js";
7
+ PromptPreparationError
8
+ } from "./chunk-UTF7KLMJ.js";
9
+ import "./chunk-ES2N66EH.js";
10
+ import "./chunk-35OF2ZNS.js";
11
+ import {
12
+ latestPreviewItems,
13
+ splitTimelineImages
14
+ } from "./chunk-WAPJZKUK.js";
15
+ import {
16
+ SessionDeletionRejectedError,
17
+ UnsupportedAgentOperationError,
18
+ validateSessionName
19
+ } from "./chunk-IRYEOV62.js";
20
+ import "./chunk-J63A5OLO.js";
8
21
  import {
9
22
  ConversationItemSchema,
10
23
  InteractionRequestSchema,
11
24
  SESSION_TIMELINE_PAGE_SIZE,
12
25
  SessionSummarySchema
13
- } from "./chunk-DWTXWVIA.js";
26
+ } from "./chunk-F5YCEWE4.js";
14
27
 
15
28
  // src/codex-adapter.ts
16
29
  import { randomUUID } from "node:crypto";
17
30
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
18
31
  import { isAbsolute, join as join2, resolve } from "node:path";
19
- import { z as z4 } from "zod";
32
+ import { z as z5 } from "zod";
20
33
 
21
34
  // src/adapters/codex/rpc.ts
22
35
  import { spawn } from "node:child_process";
@@ -302,7 +315,8 @@ var ModelList = z3.object({
302
315
  hidden: z3.boolean().optional(),
303
316
  isDefault: z3.boolean().optional(),
304
317
  supportedReasoningEfforts: z3.array(z3.object({ reasoningEffort: NativeEffort })).max(99).optional(),
305
- defaultReasoningEffort: NativeEffort.optional()
318
+ defaultReasoningEffort: NativeEffort.optional(),
319
+ inputModalities: z3.array(z3.string()).optional()
306
320
  })),
307
321
  nextCursor: z3.string().nullable()
308
322
  });
@@ -325,12 +339,15 @@ var NativeItem = z3.object({
325
339
  type: z3.string(),
326
340
  clientId: z3.string().nullable().optional(),
327
341
  text: z3.string().optional(),
328
- content: z3.array(z3.object({ type: z3.string(), text: z3.string().optional() })).optional(),
342
+ content: z3.array(z3.object({ type: z3.string(), text: z3.string().optional(), url: z3.string().optional() })).optional(),
329
343
  command: z3.string().optional(),
330
344
  tool: z3.string().optional(),
331
345
  status: z3.string().optional(),
332
346
  aggregatedOutput: z3.string().nullable().optional(),
333
- changes: z3.array(z3.object({ path: z3.string(), diff: z3.string() })).optional()
347
+ changes: z3.array(z3.object({ path: z3.string(), diff: z3.string() })).optional(),
348
+ result: z3.object({ content: z3.array(z3.unknown()).optional() }).nullish(),
349
+ contentItems: z3.array(z3.unknown()).nullish(),
350
+ output: z3.unknown().optional()
334
351
  });
335
352
  var NativeTurn = z3.object({
336
353
  id: NativeId,
@@ -349,6 +366,10 @@ var ThreadResult = z3.object({
349
366
  collaborationMode: CollaborationMode.nullable().optional()
350
367
  });
351
368
  var EventContext = z3.object({ threadId: NativeId, turnId: NativeId });
369
+ var PlanEvent = EventContext.extend({
370
+ explanation: z3.string().nullish(),
371
+ plan: z3.array(z3.object({ step: z3.string(), status: z3.enum(["pending", "inProgress", "completed"]) }))
372
+ });
352
373
  var ItemEvent = EventContext.extend({ item: NativeItem });
353
374
  var DeltaEvent = EventContext.extend({ itemId: NativeId, delta: z3.string() });
354
375
  var TurnEvent = z3.object({ threadId: NativeId, turn: NativeTurn });
@@ -370,6 +391,7 @@ var Questions = EventContext.extend({
370
391
 
371
392
  // src/adapters/codex/timeline.ts
372
393
  import { createHash } from "node:crypto";
394
+ import { z as z4 } from "zod";
373
395
  var hash = (value) => createHash("sha256").update(value).digest("hex");
374
396
  var itemId = (threadId, nativeId) => `codex:${hash(`${threadId}:${nativeId}`)}`;
375
397
  function base(threadId, turnId, nativeId) {
@@ -389,8 +411,11 @@ function projectItem(threadId, turnId, item, completed, timestamp) {
389
411
  ...common,
390
412
  kind: "human-message",
391
413
  actor: "human",
392
- content: (item.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n"),
393
- attachments: [],
414
+ content: (item.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n").slice(0, 1e5),
415
+ attachments: splitTimelineImages((item.content ?? []).flatMap((part) => {
416
+ const image = part.type === "image" ? projectNativeImageUrl(part.url) : void 0;
417
+ return image ? [image] : [];
418
+ }), (image) => image.byteLength ?? 0)[0] ?? [],
394
419
  sourceMessageIds: item.clientId ? [item.id, item.clientId] : [item.id]
395
420
  });
396
421
  case "agentMessage":
@@ -401,8 +426,18 @@ function projectItem(threadId, turnId, item, completed, timestamp) {
401
426
  content: item.text ?? "",
402
427
  final: completed
403
428
  });
429
+ case "plan":
430
+ return ConversationItemSchema.parse({
431
+ ...common,
432
+ kind: "plan-update",
433
+ actor: "assistant",
434
+ operation: "updated",
435
+ content: (item.text ?? "").slice(0, 1e5),
436
+ todos: []
437
+ });
404
438
  case "commandExecution":
405
439
  case "fileChange":
440
+ case "functionCallOutput":
406
441
  case "mcpToolCall":
407
442
  case "dynamicToolCall":
408
443
  case "collabAgentToolCall": {
@@ -426,24 +461,51 @@ function projectItem(threadId, turnId, item, completed, timestamp) {
426
461
  return void 0;
427
462
  }
428
463
  }
464
+ var ToolContent = z4.object({
465
+ type: z4.string(),
466
+ data: z4.string().optional(),
467
+ mimeType: z4.string().optional(),
468
+ imageUrl: z4.string().optional(),
469
+ image_url: z4.string().optional()
470
+ });
471
+ function projectToolImages(threadId, turnId, item, timestamp) {
472
+ const content = item.type === "mcpToolCall" ? item.result?.content : item.type === "dynamicToolCall" ? item.contentItems : item.type === "functionCallOutput" && Array.isArray(item.output) ? item.output : void 0;
473
+ const images = (content ?? []).flatMap((value) => {
474
+ const parsed = ToolContent.safeParse(value);
475
+ if (!parsed.success) return [];
476
+ const part = parsed.data;
477
+ const image = part.type === "image" && part.data && part.mimeType ? projectNativeImage(part.data, part.mimeType) : part.type === "inputImage" || part.type === "input_image" ? projectNativeImageUrl(part.imageUrl ?? part.image_url) : void 0;
478
+ return image ? [image] : [];
479
+ });
480
+ const unique = [...new Map(images.map((image) => [image.sha256, image])).values()];
481
+ return splitTimelineImages(unique, (image) => image.byteLength ?? 0).map((attachments, index) => ConversationItemSchema.parse({
482
+ ...base(threadId, turnId, `${item.id}:images:${index}`),
483
+ ...timestamp ? { timestamp } : {},
484
+ kind: "assistant-message",
485
+ actor: "assistant",
486
+ content: "",
487
+ final: true,
488
+ attachments
489
+ }));
490
+ }
429
491
 
430
492
  // src/codex-adapter.ts
431
493
  var CODEX_DEFAULT_MODEL_ID = "codex:agent-default";
432
494
  var EFFORT_OPTION = "codex:reasoning-effort";
433
495
  var MODE_OPTION = "codex:collaboration-mode";
434
- var StoredSession = z4.object({
496
+ var StoredSession = z5.object({
435
497
  summary: SessionSummarySchema,
436
- modelId: z4.string(),
437
- items: z4.array(ConversationItemSchema),
438
- uncertain: z4.boolean(),
439
- native: z4.boolean().optional(),
498
+ modelId: z5.string(),
499
+ items: z5.array(ConversationItemSchema),
500
+ uncertain: z5.boolean(),
501
+ native: z5.boolean().optional(),
440
502
  reasoningEffort: NativeEffort.nullable().optional(),
441
503
  collaborationMode: CollaborationMode.optional()
442
504
  });
443
- var Inventory = z4.object({
444
- version: z4.literal(1),
445
- identity: z4.string(),
446
- sessions: z4.array(StoredSession)
505
+ var Inventory = z5.object({
506
+ version: z5.literal(1),
507
+ identity: z5.string(),
508
+ sessions: z5.array(StoredSession)
447
509
  });
448
510
  var CodexCodingAgentAdapter = class {
449
511
  agentId = "codex";
@@ -451,8 +513,11 @@ var CodexCodingAgentAdapter = class {
451
513
  agentModes = ["interactive"];
452
514
  // Codex reasoning values use opaque configOptions, not the legacy Copilot enum.
453
515
  supportsReasoningEffort = false;
454
- supportsFileAttachments = false;
455
- supportsSessionDelete = false;
516
+ supportsFileAttachments = true;
517
+ #nativeLifecycle = false;
518
+ get supportsSessionDelete() {
519
+ return this.#nativeLifecycle;
520
+ }
456
521
  supportsSessionListUpdates = true;
457
522
  supportsAssistantPreview = true;
458
523
  groupChatEnabled = false;
@@ -462,6 +527,7 @@ var CodexCodingAgentAdapter = class {
462
527
  #sessions = /* @__PURE__ */ new Map();
463
528
  #discovered = /* @__PURE__ */ new Map();
464
529
  #retiredSessions = /* @__PURE__ */ new Set();
530
+ #deletedSessions = /* @__PURE__ */ new Set();
465
531
  #pending = /* @__PURE__ */ new Map();
466
532
  #callbacks;
467
533
  #rpc;
@@ -611,7 +677,7 @@ var CodexCodingAgentAdapter = class {
611
677
  (this.#options.spawn ?? spawnCodex)(this.#options.command ?? "codex", this.#options.args ?? ["app-server"]),
612
678
  {
613
679
  timeoutMs: this.#options.requestTimeoutMs ?? 3e4,
614
- maxFrameBytes: this.#options.maxFrameBytes ?? 4 * 1024 * 1024,
680
+ maxFrameBytes: this.#options.maxFrameBytes ?? 8 * 1024 * 1024,
615
681
  onMessage: (method, params, id) => this.#message(method, params, id),
616
682
  onFailure: (error) => this.#fail(error),
617
683
  ...this.#options.onDiagnostic ? { onDiagnostic: this.#options.onDiagnostic } : {}
@@ -623,7 +689,9 @@ var CodexCodingAgentAdapter = class {
623
689
  clientInfo: { name: "agentknight", title: "AgentKnight", version: "1" },
624
690
  capabilities: { experimentalApi: true, requestAttestation: false, explicitGatewayOauth: true }
625
691
  });
626
- z4.object({ userAgent: z4.string() }).parse(response);
692
+ const { userAgent } = z5.object({ userAgent: z5.string() }).parse(response);
693
+ const version = /\bcodex[\w-]*\/(\d+)\.(\d+)\.\d+\b/u.exec(userAgent);
694
+ this.#nativeLifecycle = !!version && (Number(version[1]) > 0 || Number(version[2]) >= 160);
627
695
  this.#ready();
628
696
  rpc.notify("initialized");
629
697
  return rpc;
@@ -644,6 +712,7 @@ var CodexCodingAgentAdapter = class {
644
712
  for (const session of this.#sessions.values()) {
645
713
  if (session.active || session.sending) session.uncertain = true;
646
714
  session.queue = [];
715
+ session.media?.clear();
647
716
  for (const resolve2 of session.settled) resolve2();
648
717
  session.settled.clear();
649
718
  this.#events?.onSyncError(session.summary.sessionId, error);
@@ -720,9 +789,9 @@ var CodexCodingAgentAdapter = class {
720
789
  const seen = /* @__PURE__ */ new Set();
721
790
  let changed = false;
722
791
  do {
723
- const result = z4.object({
724
- data: z4.array(z4.object({ id: NativeId, preview: z4.string().optional(), name: z4.string().nullable().optional() })),
725
- nextCursor: z4.string().nullable()
792
+ const result = z5.object({
793
+ data: z5.array(z5.object({ id: NativeId, preview: z5.string().optional(), name: z5.string().nullable().optional() })),
794
+ nextCursor: z5.string().nullable()
726
795
  }).parse(await rpc.request("thread/list", {
727
796
  cursor,
728
797
  limit: 100,
@@ -731,6 +800,7 @@ var CodexCodingAgentAdapter = class {
731
800
  }));
732
801
  this.#ready();
733
802
  for (const entry of result.data) {
803
+ if (this.#deletedSessions.has(entry.id)) continue;
734
804
  const session = owned.find((candidate) => candidate.summary.sessionId === entry.id);
735
805
  if (!session || !session.summary.isRemote) continue;
736
806
  const summary = (entry.name ?? entry.preview)?.slice(0, 4096);
@@ -761,17 +831,17 @@ var CodexCodingAgentAdapter = class {
761
831
  const present = /* @__PURE__ */ new Set();
762
832
  let cursor = null;
763
833
  do {
764
- const result = z4.object({
765
- data: z4.array(z4.object({
834
+ const result = z5.object({
835
+ data: z5.array(z5.object({
766
836
  id: NativeId,
767
- name: z4.string().nullable().optional(),
768
- preview: z4.string(),
769
- cwd: z4.string(),
770
- createdAt: z4.number(),
771
- updatedAt: z4.number(),
772
- model: z4.string().nullable().optional()
837
+ name: z5.string().nullable().optional(),
838
+ preview: z5.string(),
839
+ cwd: z5.string(),
840
+ createdAt: z5.number(),
841
+ updatedAt: z5.number(),
842
+ model: z5.string().nullable().optional()
773
843
  })),
774
- nextCursor: z4.string().nullable()
844
+ nextCursor: z5.string().nullable()
775
845
  }).parse(await rpc.request("thread/list", { cursor, limit: 100, sortKey: "updated_at", useStateDbOnly: true }));
776
846
  this.#ready();
777
847
  for (const entry of result.data) {
@@ -789,7 +859,7 @@ var CodexCodingAgentAdapter = class {
789
859
  createdAt: new Date(entry.createdAt * 1e3).toISOString(),
790
860
  modifiedAt: new Date(entry.updatedAt * 1e3).toISOString(),
791
861
  isRemote: existing?.summary.isRemote ?? true,
792
- renameSupported: false
862
+ renameSupported: this.#nativeLifecycle
793
863
  });
794
864
  if (existing) {
795
865
  existing.summary = summary;
@@ -815,7 +885,7 @@ var CodexCodingAgentAdapter = class {
815
885
  }
816
886
  this.#discovered.clear();
817
887
  for (const [id, session] of next) {
818
- if (!this.#sessions.has(id)) this.#discovered.set(id, session);
888
+ if (!this.#sessions.has(id) && !this.#deletedSessions.has(id)) this.#discovered.set(id, session);
819
889
  }
820
890
  let removed = false;
821
891
  for (const [id, session] of this.#sessions) {
@@ -892,7 +962,7 @@ var CodexCodingAgentAdapter = class {
892
962
  createdAt: now,
893
963
  modifiedAt: now,
894
964
  isRemote: true,
895
- renameSupported: false
965
+ renameSupported: this.#nativeLifecycle
896
966
  });
897
967
  const session = this.#runtime({
898
968
  summary,
@@ -963,7 +1033,7 @@ var CodexCodingAgentAdapter = class {
963
1033
  };
964
1034
  let applied = false;
965
1035
  try {
966
- z4.object({}).parse(await rpc.request("thread/settings/update", params));
1036
+ z5.object({}).parse(await rpc.request("thread/settings/update", params));
967
1037
  applied = true;
968
1038
  const result = ThreadResult.required({ model: true, reasoningEffort: true }).parse(await rpc.request("thread/resume", { threadId: id }));
969
1039
  this.#known(id);
@@ -1028,14 +1098,27 @@ var CodexCodingAgentAdapter = class {
1028
1098
  };
1029
1099
  }
1030
1100
  #acceptConfiguration(session, result) {
1101
+ const previouslyAcceptedImages = this.#models.get(session.modelId)?.inputModalities?.includes("image") ?? true;
1031
1102
  if (result.model !== void 0) session.modelId = result.model;
1032
1103
  if (result.reasoningEffort !== void 0) session.reasoningEffort = result.reasoningEffort;
1033
1104
  if (result.collaborationMode != null) session.collaborationMode = result.collaborationMode;
1105
+ if (previouslyAcceptedImages !== (this.#models.get(session.modelId)?.inputModalities?.includes("image") ?? true) && this.#sessions.has(session.summary.sessionId)) this.#events?.onSessionInventoryChanged(session.summary.sessionId);
1034
1106
  }
1035
1107
  async getSessionDirectoryMetadata(id) {
1036
1108
  const cwd = this.#known(id).summary.workingDirectory;
1037
1109
  return cwd === void 0 ? {} : { workingDirectory: cwd };
1038
1110
  }
1111
+ getSessionCapabilities(id) {
1112
+ const session = id === void 0 ? void 0 : this.#known(id);
1113
+ const model = session === void 0 ? void 0 : this.#models.get(session.modelId);
1114
+ return {
1115
+ agentModes: this.agentModes,
1116
+ supportsReasoningEffort: false,
1117
+ supportsFileAttachments: true,
1118
+ supportsImageAttachments: model?.inputModalities?.includes("image") ?? true,
1119
+ supportsSessionDelete: this.supportsSessionDelete && !session?.native
1120
+ };
1121
+ }
1039
1122
  async getSessionEnvironment(id) {
1040
1123
  this.#known(id);
1041
1124
  return { tools: [], skills: [], slashCommands: [] };
@@ -1061,8 +1144,69 @@ var CodexCodingAgentAdapter = class {
1061
1144
  if (!watched && this.#retiredSessions.has(id)) return;
1062
1145
  this.#known(id);
1063
1146
  }
1064
- async readSessionPlan(_id) {
1065
- return this.#unsupported("plan documents");
1147
+ async readSessionPlan(id) {
1148
+ const session = this.#known(id);
1149
+ if (session.native && !session.active && !session.sending && !session.queue.length) {
1150
+ await this.readSessionTimelinePage(id, { metadataOnly: true });
1151
+ }
1152
+ return [...session.items].reverse().find((item) => item.kind === "plan-update") ?? ConversationItemSchema.parse({
1153
+ ...base(id, id, "empty-plan"),
1154
+ kind: "plan-update",
1155
+ actor: "assistant",
1156
+ operation: "deleted",
1157
+ content: "",
1158
+ todos: []
1159
+ });
1160
+ }
1161
+ async renameSession(id, name, assertAccess) {
1162
+ const session = this.#known(id);
1163
+ const title = validateSessionName(name);
1164
+ return this.#locked(session, async () => {
1165
+ this.#checkConfigure(session);
1166
+ const rpc = await this.#native();
1167
+ if (!this.#nativeLifecycle) this.#unsupported("native session renaming");
1168
+ this.#checkConfigure(session);
1169
+ assertAccess?.();
1170
+ await rpc.request("thread/name/set", { threadId: id, name: title });
1171
+ this.#known(id);
1172
+ session.summary.summary = title;
1173
+ await this.#save();
1174
+ this.#events?.onSessionInventoryChanged(id);
1175
+ return title;
1176
+ });
1177
+ }
1178
+ async deleteSession(id) {
1179
+ const session = this.#known(id);
1180
+ if (session.native) throw new SessionDeletionRejectedError("Delete threads created in standalone Codex there");
1181
+ return this.#locked(session, async () => {
1182
+ let rpc;
1183
+ try {
1184
+ this.#checkConfigure(session);
1185
+ rpc = await this.#native();
1186
+ if (!this.#nativeLifecycle) this.#unsupported("native session deletion");
1187
+ const { thread } = ThreadResult.parse(await rpc.request("thread/read", { threadId: id, includeTurns: true }));
1188
+ this.#checkConfigure(session);
1189
+ if (thread.id !== id || !["idle", "notLoaded"].includes(thread.status.type) || thread.turns.some((turn) => turn.status === "inProgress")) throw new Error("Codex session is not verifiably idle");
1190
+ } catch (error) {
1191
+ throw new SessionDeletionRejectedError(error instanceof Error ? error.message : "Codex session could not be verified");
1192
+ }
1193
+ try {
1194
+ z5.object({}).parse(await rpc.request("thread/delete", { threadId: id }));
1195
+ } catch (error) {
1196
+ if (error instanceof CodexRpcError && error.code === -32601) {
1197
+ this.#nativeLifecycle = false;
1198
+ this.#events?.onSessionInventoryChanged(id);
1199
+ throw new SessionDeletionRejectedError("This Codex runtime does not support session deletion");
1200
+ }
1201
+ throw error;
1202
+ }
1203
+ this.#deletedSessions.add(id);
1204
+ this.#retiredSessions.add(id);
1205
+ this.#sessions.delete(id);
1206
+ this.#discovered.delete(id);
1207
+ await this.#save();
1208
+ this.#events?.onSessionInventoryChanged(id);
1209
+ });
1066
1210
  }
1067
1211
  async setGroupChatEnabled(enabled) {
1068
1212
  if (enabled) this.#unsupported("group chat");
@@ -1109,16 +1253,20 @@ var CodexCodingAgentAdapter = class {
1109
1253
  for (const native of turn.items) {
1110
1254
  const old = previous.get(itemId(session.summary.sessionId, native.id));
1111
1255
  const projected = projectItem(session.summary.sessionId, turn.id, native, turn.status !== "inProgress", old?.timestamp ?? timestamp);
1112
- if (!projected) continue;
1113
- const item = { ...projected, revision: old?.revision ?? 1 };
1114
- const changed = JSON.stringify(item) !== JSON.stringify(old);
1115
- if (old && changed) item.revision++;
1116
- items.push(item);
1117
- previous.delete(item.id);
1118
- if (changed) updates.push(item);
1256
+ const images = turn.status === "inProgress" ? [] : projectToolImages(session.summary.sessionId, turn.id, native, timestamp);
1257
+ for (const value of [...projected ? [projected] : [], ...images]) {
1258
+ const prior = previous.get(value.id);
1259
+ const enriched = this.#withPromptMedia(session, value, prior);
1260
+ const item = { ...enriched, timestamp: prior?.timestamp ?? enriched.timestamp, revision: prior?.revision ?? 1 };
1261
+ const changed = JSON.stringify(item) !== JSON.stringify(prior);
1262
+ if (prior && changed) item.revision++;
1263
+ items.push(item);
1264
+ previous.delete(item.id);
1265
+ if (changed) updates.push(item);
1266
+ }
1119
1267
  }
1120
1268
  }
1121
- session.items = [...items, ...[...previous.values()].filter((item) => publish || item.kind === "notice")];
1269
+ session.items = [...items, ...[...previous.values()].filter((item) => publish || item.kind === "notice" || item.kind === "plan-update")];
1122
1270
  if (publish && session.summary.isRemote) {
1123
1271
  for (const item of updates) this.#events?.onConversationItem(session.summary.sessionId, structuredClone(item));
1124
1272
  }
@@ -1171,15 +1319,18 @@ var CodexCodingAgentAdapter = class {
1171
1319
  }
1172
1320
  async sendPrompt(id, prompt, mode, attachments = [], _persistInteractions = true, files = [], _operationId, persona) {
1173
1321
  const session = this.#known(id);
1174
- if (attachments.length || files.length) this.#unsupported("attachments");
1175
1322
  if (persona !== void 0) this.#unsupported("avatar personas");
1176
1323
  if (mode !== "enqueue" && mode !== "immediate") this.#unsupported("delivery mode");
1177
- if (!prompt.trim() || prompt.length > 1e5) throw new Error("Invalid Codex prompt length");
1178
- const job = { id: randomUUID(), text: prompt, epoch: session.epoch };
1324
+ if (!prompt.trim() && !attachments.length && !files.length || prompt.length > 1e5) throw new Error("Invalid Codex prompt length");
1325
+ const epoch = session.epoch;
1179
1326
  return this.#locked(session, async () => {
1180
- this.#checkSend(session, job, mode === "enqueue" && session.active !== void 0);
1327
+ const admission = { epoch };
1328
+ this.#checkSend(session, admission, mode === "enqueue" && session.active !== void 0);
1329
+ if (mode === "enqueue" && session.queue.length >= 100) throw new Error("Codex host queue is full");
1330
+ const media = await prepareNativePrompt(this.#directory, hash(id), prompt, attachments, files);
1331
+ const job = { id: randomUUID(), text: prompt, epoch, media };
1332
+ this.#checkSend(session, admission, mode === "enqueue" && session.active !== void 0);
1181
1333
  if (mode === "enqueue" && (session.active || session.queue.length)) {
1182
- if (session.queue.length >= 100) throw new Error("Codex host queue is full");
1183
1334
  session.queue.push(job);
1184
1335
  return { messageId: job.id, deliveryState: "queued" };
1185
1336
  }
@@ -1199,6 +1350,9 @@ var CodexCodingAgentAdapter = class {
1199
1350
  this.#checkSend(session, job);
1200
1351
  await this.#load(session);
1201
1352
  this.#checkSend(session, job);
1353
+ if (job.media.images.length && this.#models.get(session.modelId)?.inputModalities?.includes("image") === false) {
1354
+ throw new PromptPreparationError(new Error("The selected Codex model does not accept images"));
1355
+ }
1202
1356
  const rpc = await this.#native();
1203
1357
  this.#checkSend(session, job);
1204
1358
  const expectedTurnId = session.active;
@@ -1209,18 +1363,23 @@ var CodexCodingAgentAdapter = class {
1209
1363
  await this.#save();
1210
1364
  this.#checkSend(session, job);
1211
1365
  const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
1212
- const input = [{ type: "text", text: job.text, text_elements: [] }];
1366
+ const input = [
1367
+ ...job.media.text ? [{ type: "text", text: job.media.text, text_elements: [] }] : [],
1368
+ ...job.media.images.map(({ mimeType, data }) => ({ type: "image", url: `data:${mimeType};base64,${data}` }))
1369
+ ];
1370
+ if (job.media.attachments.length) (session.media ??= /* @__PURE__ */ new Map()).set(job.id, job);
1213
1371
  transmitted = true;
1214
1372
  const response = expectedTurnId ? await rpc.request("turn/steer", { threadId: session.summary.sessionId, expectedTurnId, clientUserMessageId: job.id, input }) : await rpc.request("turn/start", { threadId: session.summary.sessionId, clientUserMessageId: job.id, input });
1215
1373
  this.#ready();
1216
- const startedTurn = expectedTurnId ? void 0 : z4.object({ turn: NativeTurn }).parse(response).turn;
1217
- const turnId = startedTurn?.id ?? z4.object({ turnId: NativeId }).parse(response).turnId;
1374
+ const startedTurn = expectedTurnId ? void 0 : z5.object({ turn: NativeTurn }).parse(response).turn;
1375
+ const turnId = startedTurn?.id ?? z5.object({ turnId: NativeId }).parse(response).turnId;
1218
1376
  if (expectedTurnId && turnId !== expectedTurnId) throw new Error("Codex steer changed the expected turn");
1219
1377
  if (startedTurn && startedTurn.status !== "inProgress") this.#complete(session, startedTurn);
1220
1378
  else if (!session.completed.has(turnId)) session.active = turnId;
1221
1379
  session.uncertain = session.active !== void 0;
1222
1380
  return { messageId: job.id, deliveryState: "processing", submittedAt };
1223
1381
  } catch (error) {
1382
+ if (!transmitted || error instanceof CodexRpcError) session.media?.delete(job.id);
1224
1383
  if (!transmitted || error instanceof CodexRpcError) {
1225
1384
  session.uncertain = session.active !== void 0;
1226
1385
  } else {
@@ -1311,7 +1470,7 @@ var CodexCodingAgentAdapter = class {
1311
1470
  this.#request(method, params, rpcId);
1312
1471
  return;
1313
1472
  }
1314
- const context = z4.object({ threadId: NativeId }).safeParse(params);
1473
+ const context = z5.object({ threadId: NativeId }).safeParse(params);
1315
1474
  if (!context.success) return;
1316
1475
  const session = this.#sessions.get(context.data.threadId);
1317
1476
  if (session?.loaded && method === "thread/settings/updated") {
@@ -1326,14 +1485,14 @@ var CodexCodingAgentAdapter = class {
1326
1485
  return;
1327
1486
  }
1328
1487
  if (session && method === "serverRequest/resolved") {
1329
- const resolved = z4.object({ requestId: z4.union([z4.string(), z4.number().int()]) }).parse(params);
1488
+ const resolved = z5.object({ requestId: z5.union([z5.string(), z5.number().int()]) }).parse(params);
1330
1489
  for (const [id, pending] of this.#pending) {
1331
1490
  if (pending.session === session && pending.rpcId === resolved.requestId) this.#finish(id, void 0, false);
1332
1491
  }
1333
1492
  return;
1334
1493
  }
1335
1494
  if (session?.loaded && method === "thread/status/changed") {
1336
- const status = z4.object({ status: z4.object({ type: z4.string() }) }).parse(params).status.type;
1495
+ const status = z5.object({ status: z5.object({ type: z5.string() }) }).parse(params).status.type;
1337
1496
  if (status === "systemError" || status === "active" && !session.active && !session.sending) {
1338
1497
  session.uncertain = true;
1339
1498
  this.#fail(new Error("Codex owned thread has unverifiable native activity"));
@@ -1369,7 +1528,8 @@ var CodexCodingAgentAdapter = class {
1369
1528
  const { turnId, item } = ItemEvent.parse(params);
1370
1529
  if (method === "item/started" && session.items.some((existing) => existing.id === itemId(session.summary.sessionId, item.id))) return;
1371
1530
  const projected = projectItem(session.summary.sessionId, turnId, item, method === "item/completed");
1372
- if (projected) this.#upsert(session, projected);
1531
+ if (projected) this.#upsert(session, this.#withPromptMedia(session, projected));
1532
+ if (method === "item/completed") for (const image of projectToolImages(event.data.threadId, turnId, item)) this.#upsert(session, image);
1373
1533
  if (item.aggregatedOutput) this.#output(session, turnId, `${item.id}:output`, "Tool output", item.aggregatedOutput);
1374
1534
  if (item.changes) this.#output(
1375
1535
  session,
@@ -1401,13 +1561,28 @@ ${change.diff}`).join("\n")
1401
1561
  "Tool output",
1402
1562
  (old?.kind === "notice" ? old.content : "") + delta.delta
1403
1563
  );
1564
+ } else if (method === "turn/plan/updated") {
1565
+ const { plan, explanation, turnId, threadId } = PlanEvent.parse(params);
1566
+ this.#upsert(session, ConversationItemSchema.parse({
1567
+ ...base(threadId, turnId, `${turnId}:tasks`),
1568
+ kind: "plan-update",
1569
+ actor: "assistant",
1570
+ operation: "updated",
1571
+ content: (explanation ?? "").slice(0, 1e5),
1572
+ todos: plan.filter(({ step }) => step.trim()).slice(0, 1e3).map(({ step, status }, index) => ({
1573
+ id: hash(`${turnId}:task:${index}`),
1574
+ title: step.trim().slice(0, 1024),
1575
+ status: status === "completed" ? "done" : status === "inProgress" ? "in_progress" : "pending",
1576
+ dependsOn: []
1577
+ }))
1578
+ }));
1404
1579
  } else if (method === "turn/diff/updated") {
1405
- const diff = EventContext.extend({ diff: z4.string() }).parse(params);
1580
+ const diff = EventContext.extend({ diff: z5.string() }).parse(params);
1406
1581
  this.#output(session, diff.turnId, `${diff.turnId}:diff`, "Turn diff", diff.diff);
1407
1582
  } else if (method === "item/fileChange/patchUpdated") {
1408
1583
  const patch = EventContext.extend({
1409
1584
  itemId: NativeId,
1410
- changes: z4.array(z4.object({ path: z4.string(), diff: z4.string() }))
1585
+ changes: z5.array(z5.object({ path: z5.string(), diff: z5.string() }))
1411
1586
  }).parse(params);
1412
1587
  this.#output(
1413
1588
  session,
@@ -1438,8 +1613,10 @@ ${change.diff}`).join("\n")
1438
1613
  session.uncertain = false;
1439
1614
  for (const item of turn.items) {
1440
1615
  const projected = projectItem(session.summary.sessionId, turn.id, item, true);
1441
- if (projected) this.#upsert(session, projected);
1616
+ if (projected) this.#upsert(session, this.#withPromptMedia(session, projected));
1617
+ for (const image of projectToolImages(session.summary.sessionId, turn.id, item)) this.#upsert(session, image);
1442
1618
  }
1619
+ session.media?.clear();
1443
1620
  for (const item of [...session.items]) {
1444
1621
  if (item.turnId !== turn.id) continue;
1445
1622
  if (item.kind === "assistant-message" && !item.final) {
@@ -1454,6 +1631,12 @@ ${change.diff}`).join("\n")
1454
1631
  session.settled.clear();
1455
1632
  this.#events?.onSessionActivity?.(session.summary.sessionId, "idle", (/* @__PURE__ */ new Date()).toISOString());
1456
1633
  }
1634
+ #withPromptMedia(session, item, previous = session.items.find(({ id }) => id === item.id)) {
1635
+ if (item.kind !== "human-message") return item;
1636
+ const job = item.sourceMessageIds?.map((id) => session.media?.get(id)).find((candidate) => candidate !== void 0);
1637
+ if (job) return { ...item, content: job.text, attachments: job.media.attachments };
1638
+ return previous?.kind === "human-message" && previous.attachments?.length ? { ...item, content: previous.content, attachments: previous.attachments } : item;
1639
+ }
1457
1640
  #request(method, params, rpcId) {
1458
1641
  const context = EventContext.safeParse(params);
1459
1642
  const session = context.success ? this.#sessions.get(context.data.threadId) : void 0;
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  LiveTimelineProjection,
3
3
  NotGitDirectoryError,
4
- PromptPreparationError,
5
4
  SESSION_PROJECT_IDENTITY_CONCURRENCY,
6
5
  SessionDirectoryLister,
7
6
  SessionProjectIdentityError,
@@ -18,47 +17,49 @@ import {
18
17
  recordTimelineSyncDiagnostic,
19
18
  resolveGitProjectIdentity,
20
19
  sanitizeGitRemoteUrl
21
- } from "./chunk-FY4XTWUF.js";
20
+ } from "./chunk-2D34UDII.js";
22
21
  import "./chunk-IJPJQF7S.js";
23
22
  import {
24
23
  AnalyticsIndexResultSchema,
25
24
  AnalyticsReplySchema,
26
25
  openSessionEventLog,
27
26
  readSessionUpdatePage
28
- } from "./chunk-Y6NCJB55.js";
27
+ } from "./chunk-LA6A4TUM.js";
29
28
  import {
30
29
  ConversationNormalizer,
31
30
  isDisplayableHumanMessage
32
- } from "./chunk-EDYVCZIR.js";
31
+ } from "./chunk-LU73CEHE.js";
33
32
  import {
34
33
  assertMainSessionId,
35
34
  isResearchSessionId
36
- } from "./chunk-AWVC5NX4.js";
35
+ } from "./chunk-5QYL6NKJ.js";
37
36
  import {
38
37
  GroupChatError,
39
38
  GroupChatMessageSchema,
40
39
  GroupChatRuntime
41
- } from "./chunk-MB3H6HEI.js";
40
+ } from "./chunk-Q5NNNSU2.js";
41
+ import {
42
+ PromptPreparationError
43
+ } from "./chunk-UTF7KLMJ.js";
42
44
  import {
43
45
  deletePromptAttachments,
44
46
  stagePromptAttachments,
45
47
  validatePromptAttachments
46
- } from "./chunk-B777YB6E.js";
48
+ } from "./chunk-ES2N66EH.js";
47
49
  import {
48
50
  CopilotSessionCompatibilityClient,
49
51
  resolveCopilotSessionDirectory,
50
52
  resumeWithCopilotSessionCompatibility
51
53
  } from "./chunk-35OF2ZNS.js";
52
- import "./chunk-4XT65OSG.js";
53
- import "./chunk-IXGVSREH.js";
54
+ import "./chunk-WAPJZKUK.js";
54
55
  import {
55
56
  AgentSessionRenameError,
56
57
  TimelinePageBudgetError,
57
58
  validateSessionName
58
- } from "./chunk-CFQQOAQV.js";
59
+ } from "./chunk-IRYEOV62.js";
59
60
  import {
60
61
  SessionOperationError
61
- } from "./chunk-UHRUQM4D.js";
62
+ } from "./chunk-J63A5OLO.js";
62
63
  import {
63
64
  ConversationItemSchema,
64
65
  CopilotModelOptionSchema,
@@ -80,7 +81,7 @@ import {
80
81
  WorkbenchScheduleProposalSchema,
81
82
  WorkbenchScheduleSnapshotSchema,
82
83
  WorkbenchTelemetrySchema
83
- } from "./chunk-DWTXWVIA.js";
84
+ } from "./chunk-F5YCEWE4.js";
84
85
 
85
86
  // src/copilot-adapter.ts
86
87
  import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";