@tangle-network/sdk-provider-codex 0.4.106 → 0.4.108

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.
package/dist/index.d.mts CHANGED
@@ -226,7 +226,7 @@ declare abstract class CodexSecretProfileAdapter extends CodexNativeLaunchAdapte
226
226
  private readNativeControls;
227
227
  protected nativeArgs(input: AgentExecutionInput & {
228
228
  managedQuoteVersion?: string;
229
- }, plan: WorkspacePlanApplication | undefined, mcp?: Record<string, unknown>): string[];
229
+ }, plan: WorkspacePlanApplication | undefined, mcp?: Record<string, unknown>, strictConfig?: boolean): string[];
230
230
  protected prepareSecretCodexTurn(input: AgentExecutionInput, plan: WorkspacePlanApplication, sessionId: string, mcpInput: AgentExecutionInput, retainRelease: (release: SecretProfileMcpLease) => void, shared?: {
231
231
  args: string[];
232
232
  env: Record<string, string | undefined>;
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { InteractionKind, ProxySecretBindingSchema, ProxySecretGrantSchema, ProxySecretReceiptSchema, ProxySecretUpdateControlsSchema, ProxySecretsSchema, isProxySecretScopeAttenuation, ownPropertyRecordSchema, proxySecretPresentationsEqual, resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
3
3
  import { z } from "zod";
4
4
  import { HELD_SPARE_IDLE_MS, createDeferredParser, createHeldSpareRegistry, launchDifferences, resolveRawCapturePath, spawnRpcBridge } from "@tangle-network/sdk-cli-runner";
5
- import { CODEX_DISABLED_FEATURE_ARGS, CliProviderAdapterBase, InteractionBroker, McpInteractionSupport, NATIVE_SESSION_CONTRACTS, PROMPT_SECTION_SEPARATOR, SEALED_NATIVE_HOME_LAYOUT, SECRET_REFERENCE_PREFIX, assertSealedNativeHome, assertSealedNativeSearchPath, codexDeveloperInstructionArgs, deriveFilePart, directStdioMcpServers, executionCorrelationHeaders, failureAfterCleanup, forgetSessionScopes, interactionToggleEnabled, isLoopbackEndpoint, isPlainRecord, jsonEventParser, localMcpArgv, localMcpEnv, nativeEffortArgs, partitionImageAttachments, provenStoreBinary, reasoningEvents, recordCliTokenUsage, refuseSecretLaunch, resolveExecutableRealpath, secretMcpScope, secretSessionTurnQueue, servableMcpServer, servableStdioServer, sessionObservedEvents, sharedSecretMcpRefused, spawnUnderSecretMcpLease, streamPartBase, textDeltaEvents, toolResultEvents, toolStartEvents, trackFilePart, turnEndReason, untilSettledOrAborted, withTurnInteractions } from "@tangle-network/sdk-provider-cli-base";
5
+ import { CODEX_DISABLED_FEATURE_ARGS, CliProviderAdapterBase, InteractionBroker, McpInteractionSupport, NATIVE_SESSION_CONTRACTS, PROMPT_SECTION_SEPARATOR, SEALED_NATIVE_HOME_LAYOUT, SECRET_REFERENCE_PREFIX, TurnObserver, assertSealedNativeHome, assertSealedNativeSearchPath, codexDeveloperInstructionArgs, createExecutionState, deriveFilePart, directStdioMcpServers, endFailedTurn, executionCorrelationHeaders, failureAfterCleanup, forgetSessionScopes, interactionToggleEnabled, isLoopbackEndpoint, isPlainRecord, jsonEventParser, localMcpArgv, localMcpEnv, nativeEffortArgs, partitionImageAttachments, provenStoreBinary, reasoningEvents, recordCliTokenUsage, recordTurnInterruption, refuseSecretLaunch, resolveExecutableRealpath, secretMcpScope, secretSessionTurnQueue, servableMcpServer, servableStdioServer, sessionObservedEvents, sharedSecretMcpRefused, spawnUnderSecretMcpLease, streamPartBase, textDeltaEvents, toolResultEvents, toolStartEvents, trackFilePart, turnEndReason, untilSettledOrAborted, withTurnInteractions } from "@tangle-network/sdk-provider-cli-base";
6
6
  import { existsSync } from "node:fs";
7
7
  import path, { join } from "node:path";
8
8
  import { isDeepStrictEqual } from "node:util";
@@ -644,7 +644,7 @@ function registerDeniedApprovals(bridge, onEvent) {
644
644
  */
645
645
  function registerUserInputQuestions(bridge, permissions, sessionId, interactionBinding, questions, onEvent) {
646
646
  bridge.onRequest("item/tool/requestUserInput", async (p) => {
647
- if (!questions) {
647
+ if (!questions || !interactionBinding) {
648
648
  onEvent?.({
649
649
  type: "warning",
650
650
  code: "CODEX_UNEXPECTED_QUESTION",
@@ -677,7 +677,7 @@ function registerUserInputQuestions(bridge, permissions, sessionId, interactionB
677
677
  });
678
678
  }
679
679
  function registerAppServerInteractions(bridge, permissions, sessionId, interactionBinding, interactive, questions, onEvent) {
680
- const approve = (id, toolName, raw) => permissions.request({
680
+ if (interactive && interactionBinding) registerBrokeredApprovals(bridge, (id, toolName, raw) => permissions.request({
681
681
  id: id && id.length > 0 ? id : randomUUID(),
682
682
  sessionId,
683
683
  binding: interactionBinding,
@@ -685,8 +685,7 @@ function registerAppServerInteractions(bridge, permissions, sessionId, interacti
685
685
  input: raw,
686
686
  allowlistGrant: "deny",
687
687
  emit: onEvent
688
- });
689
- if (interactive) registerBrokeredApprovals(bridge, approve);
688
+ }));
690
689
  else registerDeniedApprovals(bridge, onEvent);
691
690
  registerUserInputQuestions(bridge, permissions, sessionId, interactionBinding, questions, onEvent);
692
691
  }
@@ -721,7 +720,259 @@ function initialThreadId(input) {
721
720
  return continuation.providerState.threadId;
722
721
  }
723
722
  //#endregion
723
+ //#region src/codex-exec-events.ts
724
+ function mapCodexEventToStreamEvents(event, state, provider, logger) {
725
+ switch (event.type) {
726
+ case "session_started": return mapSessionStartedEvent(event, state);
727
+ case "thread.started": return mapThreadStartedEvent(event, state, provider);
728
+ case "message": return mapMessageEvent(event, state, logger);
729
+ case "item.started": return mapToolItem(event.item, state, false) ?? [{
730
+ type: "raw",
731
+ backend: provider,
732
+ event
733
+ }];
734
+ case "item.completed": return mapToolItem(event.item, state, true) ?? mapItemCompletedEvent(event, state, provider, logger);
735
+ case "turn.completed":
736
+ recordCliTokenUsage(state, event.usage);
737
+ return [{
738
+ type: "raw",
739
+ backend: provider,
740
+ event
741
+ }];
742
+ case "task_started": return mapTaskStartedEvent(event);
743
+ case "error": return mapErrorEvent(event);
744
+ default: return [{
745
+ type: "raw",
746
+ backend: provider,
747
+ event
748
+ }];
749
+ }
750
+ }
751
+ /**
752
+ * A tool the agent ran, as `codex exec --json` reports it: an item that
753
+ * starts and then completes. A completion without a start emits both.
754
+ * Undefined for an item that is not a tool.
755
+ */
756
+ function mapToolItem(item, state, completed) {
757
+ const call = codexToolCall(item);
758
+ if (!call) return void 0;
759
+ const events = state.toolCalls.has(call.id) ? [] : toolStartEvents(state, call);
760
+ if (!completed) return events;
761
+ const failed = item.status === "failed" || item.status === "declined" || typeof item.exit_code === "number" && item.exit_code !== 0 || item.error !== void 0 && item.error !== null;
762
+ return [...events, ...toolResultEvents(state, {
763
+ id: call.id,
764
+ content: item.aggregated_output ?? item.result ?? item.error ?? item.status,
765
+ isError: failed
766
+ })];
767
+ }
768
+ function codexToolCall(item) {
769
+ const id = item.id;
770
+ if (typeof id !== "string" || id.length === 0) return void 0;
771
+ switch (item.type) {
772
+ case "command_execution": return {
773
+ id,
774
+ name: "bash",
775
+ input: { command: item.command ?? "" }
776
+ };
777
+ case "mcp_tool_call":
778
+ if (!item.server && !item.tool) return void 0;
779
+ return {
780
+ id,
781
+ name: `mcp__${item.server ?? ""}__${item.tool ?? ""}`,
782
+ input: item.arguments ?? {}
783
+ };
784
+ case "web_search": return {
785
+ id,
786
+ name: "websearch",
787
+ input: { query: item.query ?? "" }
788
+ };
789
+ default: return;
790
+ }
791
+ }
792
+ function mapItemCompletedEvent(event, state, provider, logger) {
793
+ if (event.item?.type === "file_change") {
794
+ const fileEvents = mapFileChangeCompleted(event.item, state, logger);
795
+ if (fileEvents !== null) return fileEvents;
796
+ return [{
797
+ type: "raw",
798
+ backend: provider,
799
+ event
800
+ }];
801
+ }
802
+ if (event.item?.type !== "agent_message" || typeof event.item.text !== "string") return [{
803
+ type: "raw",
804
+ backend: provider,
805
+ event
806
+ }];
807
+ const nextText = event.item.text;
808
+ const previousLength = state.textBuffer.length;
809
+ const delta = nextText.startsWith(state.textBuffer) ? nextText.slice(previousLength) : void 0;
810
+ state.textBuffer = nextText;
811
+ state.textPartId ??= randomUUID();
812
+ return [{
813
+ type: "message.part.updated",
814
+ part: {
815
+ ...streamPartBase(state, state.textPartId),
816
+ type: "text",
817
+ text: state.textBuffer
818
+ },
819
+ ...delta ? { delta } : {}
820
+ }];
821
+ }
822
+ function mapFileChangeCompleted(item, state, logger) {
823
+ if (!Array.isArray(item.changes)) {
824
+ logger.debug("file_change item.completed without a changes array", { itemId: item.id });
825
+ return null;
826
+ }
827
+ if (item.status !== void 0 && item.status !== "completed") return null;
828
+ const events = [];
829
+ for (const change of item.changes) {
830
+ if (typeof change?.path !== "string" || change.path.length === 0) {
831
+ logger.debug("malformed change in file_change item", { itemId: item.id });
832
+ continue;
833
+ }
834
+ if (change.kind == null) {
835
+ logger.debug("change without a kind in file_change item", {
836
+ itemId: item.id,
837
+ path: change.path
838
+ });
839
+ continue;
840
+ }
841
+ const tracked = trackFilePart(state, {
842
+ path: change.path,
843
+ changeKind: normalizeChangeKind(change.kind) ?? "update"
844
+ });
845
+ if (!tracked) continue;
846
+ events.push(filePartUpdated(state, tracked));
847
+ }
848
+ return events.length > 0 ? events : null;
849
+ }
850
+ function mapSessionStartedEvent(event, state) {
851
+ return [...sessionObservedEvents(state, "codex", event.session_id), {
852
+ type: "status",
853
+ status: "processing",
854
+ detail: "Session started"
855
+ }];
856
+ }
857
+ function mapThreadStartedEvent(event, state, provider) {
858
+ return [...sessionObservedEvents(state, "codex", event.thread_id), {
859
+ type: "raw",
860
+ backend: provider,
861
+ event
862
+ }];
863
+ }
864
+ function mapMessageEvent(event, state, logger) {
865
+ if (event.role !== "assistant" || !event.message.content) return [];
866
+ const events = [];
867
+ for (const block of event.message.content) events.push(...mapContentBlock(block, state, logger));
868
+ return events;
869
+ }
870
+ function mapContentBlock(block, state, logger) {
871
+ switch (block.type) {
872
+ case "text": return textDeltaEvents(state, block.text);
873
+ case "thinking": return reasoningEvents(state, block.thinking, { signalPhase: true });
874
+ case "tool_use": return toolStartEvents(state, block);
875
+ case "tool_result": return toolResultEvents(state, {
876
+ id: block.tool_use_id,
877
+ content: block.content,
878
+ isError: Boolean(block.is_error),
879
+ afterSuccess: (toolCall) => detectFileParts(toolCall, block.content, state, logger)
880
+ });
881
+ default: return [];
882
+ }
883
+ }
884
+ function detectFileParts(toolCall, raw, state, logger) {
885
+ const events = [];
886
+ if (!toolCall.name.startsWith("mcp__") || !Array.isArray(raw)) return events;
887
+ for (const block of raw) {
888
+ if (typeof block !== "object" || block === null || block.type !== "image") continue;
889
+ const { data, mimeType } = block;
890
+ if (typeof data !== "string" || typeof mimeType !== "string" || !/^[a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+$/.test(mimeType)) {
891
+ logger.debug("malformed image block in MCP tool result", { tool: toolCall.name });
892
+ continue;
893
+ }
894
+ const tracked = trackFilePart(state, {
895
+ dataUri: `data:${mimeType};base64,${data}`,
896
+ mediaType: mimeType
897
+ });
898
+ if (!tracked) continue;
899
+ events.push(filePartUpdated(state, tracked));
900
+ }
901
+ return events;
902
+ }
903
+ function mapTaskStartedEvent(event) {
904
+ return [{
905
+ type: "status",
906
+ status: "processing",
907
+ detail: `Task ${event.task_type ?? event.task_id} started`
908
+ }];
909
+ }
910
+ function mapErrorEvent(event) {
911
+ return [{
912
+ type: "warning",
913
+ code: event.code ?? "CODEX_ERROR",
914
+ message: event.message
915
+ }];
916
+ }
917
+ /** The complete emitted part for either native-path or MCP image observations. */
918
+ function filePartUpdated(state, tracked) {
919
+ return {
920
+ type: "message.part.updated",
921
+ part: {
922
+ ...streamPartBase(state, tracked.id),
923
+ type: "file",
924
+ ...tracked.filename ? { filename: tracked.filename } : {},
925
+ ...tracked.mediaType ? { mediaType: tracked.mediaType } : {},
926
+ url: tracked.url
927
+ }
928
+ };
929
+ }
930
+ //#endregion
724
931
  //#region src/app-server-items.ts
932
+ function execToolItem(item) {
933
+ const status = item.status === "inProgress" ? "in_progress" : typeof item.status === "string" ? item.status : void 0;
934
+ if (isTool(item)) {
935
+ if (item.type === "commandExecution") return {
936
+ type: "command_execution",
937
+ id: item.id,
938
+ status,
939
+ command: item.command,
940
+ aggregated_output: item.aggregatedOutput ?? "",
941
+ exit_code: item.exitCode
942
+ };
943
+ return {
944
+ type: "file_change",
945
+ id: item.id,
946
+ status: status === "declined" ? "failed" : status,
947
+ changes: item.changes.map((change) => ({
948
+ path: change.path,
949
+ kind: normalizeChangeKind(change.kind) ?? (change.kind == null ? void 0 : "update")
950
+ }))
951
+ };
952
+ }
953
+ if (item.type === "mcpToolCall" && typeof item.server === "string" && typeof item.tool === "string") {
954
+ const result = item.result;
955
+ return {
956
+ id: item.id,
957
+ type: "mcp_tool_call",
958
+ server: item.server,
959
+ tool: item.tool,
960
+ arguments: item.arguments,
961
+ status,
962
+ result: result ? {
963
+ content: result.content,
964
+ ...result._meta != null ? { _meta: result._meta } : {},
965
+ structured_content: result.structuredContent ?? null
966
+ } : null,
967
+ error: item.error
968
+ };
969
+ }
970
+ if (item.type === "webSearch" && typeof item.query === "string") return {
971
+ type: "web_search",
972
+ id: item.id,
973
+ query: item.query
974
+ };
975
+ }
725
976
  function isTool(item) {
726
977
  return item.type === "commandExecution" || item.type === "fileChange";
727
978
  }
@@ -730,9 +981,32 @@ var AppServerItemMapper = class {
730
981
  tools = /* @__PURE__ */ new Map();
731
982
  reasoning = /* @__PURE__ */ new Map();
732
983
  emittedThinking = false;
733
- constructor(ids, logger) {
984
+ exec;
985
+ constructor(ids, logger, execState) {
734
986
  this.ids = ids;
735
987
  this.logger = logger;
988
+ if (execState && logger) this.exec = {
989
+ state: execState,
990
+ logger,
991
+ pending: /* @__PURE__ */ new Set()
992
+ };
993
+ }
994
+ execToolEvents(params, type) {
995
+ const item = execToolItem(params.item);
996
+ if (!item || !this.exec) return [];
997
+ if (item.id) if (type === "item.started") this.exec.pending.add(item.id);
998
+ else this.exec.pending.delete(item.id);
999
+ return mapCodexEventToStreamEvents({
1000
+ type,
1001
+ item
1002
+ }, this.exec.state, "codex", this.exec.logger);
1003
+ }
1004
+ reconcileTurnItems({ threadId, turn }) {
1005
+ return (turn.items ?? []).flatMap((item) => item.id && this.exec?.pending.has(item.id) ? this.execToolEvents({
1006
+ threadId,
1007
+ turnId: turn.id,
1008
+ item
1009
+ }, "item.completed") : []);
736
1010
  }
737
1011
  partBase(id) {
738
1012
  return {
@@ -788,6 +1062,7 @@ var AppServerItemMapper = class {
788
1062
  };
789
1063
  }
790
1064
  onItemStarted(params) {
1065
+ if (this.exec) return this.execToolEvents(params, "item.started");
791
1066
  const item = params.item;
792
1067
  if (!isTool(item)) return [];
793
1068
  const state = {
@@ -810,6 +1085,7 @@ var AppServerItemMapper = class {
810
1085
  }];
811
1086
  }
812
1087
  onItemCompleted(params) {
1088
+ if (this.exec) return this.execToolEvents(params, "item.completed");
813
1089
  const item = params.item;
814
1090
  if (!isTool(item)) {
815
1091
  if (item.type === "reasoning" && typeof item.id === "string") this.reasoning.delete(item.id);
@@ -858,6 +1134,7 @@ var AppServerItemMapper = class {
858
1134
  if (!params.delta) return [];
859
1135
  const text = (this.reasoning.get(params.itemId) ?? "") + params.delta;
860
1136
  this.reasoning.set(params.itemId, text);
1137
+ if (this.exec) return reasoningEvents(this.exec.state, text, { signalPhase: true });
861
1138
  const part = {
862
1139
  ...this.partBase(params.itemId),
863
1140
  type: "reasoning",
@@ -879,6 +1156,12 @@ var AppServerItemMapper = class {
879
1156
  return events;
880
1157
  }
881
1158
  toolInvocations() {
1159
+ if (this.exec) return [...this.exec.state.toolCalls.values()].map((call) => ({
1160
+ toolName: call.name,
1161
+ input: call.input,
1162
+ result: call.output,
1163
+ ...call.status === "failed" ? { isError: true } : {}
1164
+ }));
882
1165
  return [...this.tools.values()].map((state) => ({
883
1166
  toolName: state.tool,
884
1167
  input: state.input,
@@ -900,11 +1183,11 @@ var CodexAppServerTurn = class {
900
1183
  submittedPlan;
901
1184
  planInteractions;
902
1185
  text = "";
1186
+ textItemId;
903
1187
  tokenUsage;
904
1188
  activeTurnId;
905
1189
  closeEnd;
906
- pendingTurnCompletions = [];
907
- pendingTurnErrors = [];
1190
+ pendingTurnEvents;
908
1191
  planInterruptRequested = false;
909
1192
  terminalSettled = false;
910
1193
  resolveTurn;
@@ -913,6 +1196,12 @@ var CodexAppServerTurn = class {
913
1196
  items;
914
1197
  constructor(turn) {
915
1198
  this.turn = turn;
1199
+ if (turn.execState) turn.execState.tokenUsage = this.tokenUsage = {
1200
+ inputTokens: 0,
1201
+ outputTokens: 0,
1202
+ cacheReadInputTokens: 0,
1203
+ reasoningTokens: 0
1204
+ };
916
1205
  this.turnDone = new Promise((resolve, reject) => {
917
1206
  this.resolveTurn = resolve;
918
1207
  this.rejectTurn = reject;
@@ -921,7 +1210,7 @@ var CodexAppServerTurn = class {
921
1210
  this.items = new AppServerItemMapper({
922
1211
  sessionId: turn.sessionId,
923
1212
  messageId: turn.messageId
924
- }, turn.logger);
1213
+ }, turn.logger, turn.execState);
925
1214
  }
926
1215
  planProviderState() {
927
1216
  if (!this.activeThreadId) throw new Error("Codex thread identity was unavailable during plan submission");
@@ -932,16 +1221,34 @@ var CodexAppServerTurn = class {
932
1221
  };
933
1222
  }
934
1223
  subscribe(bridge) {
1224
+ const listen = (method, handle) => bridge.onNotification(method, (params) => {
1225
+ if (!params || !this.activeThreadId) return;
1226
+ const { threadId } = params;
1227
+ const turnId = params.turnId ?? params.turn?.id;
1228
+ const legacy = !this.turn.execState && (method === "item/agentMessage/delta" || method === "error") && threadId === void 0 && turnId === void 0;
1229
+ if (!legacy && threadId !== this.activeThreadId) return;
1230
+ const deliver = () => {
1231
+ if (!this.terminalSettled && (legacy || this.activeTurnId && turnId === this.activeTurnId)) handle(params);
1232
+ };
1233
+ if (this.pendingTurnEvents) this.pendingTurnEvents.push(deliver);
1234
+ else if (this.activeTurnId) deliver();
1235
+ });
935
1236
  const unsubscribers = [
936
- ...this.subscribeItems(bridge),
937
- this.subscribeAgentMessage(bridge),
938
- this.subscribeTokenUsage(bridge),
939
- bridge.onNotification("turn/completed", (p) => {
940
- this.handleTurnCompleted(p);
1237
+ listen("item/started", (p) => this.forward(this.items.onItemStarted(p))),
1238
+ listen("item/completed", (p) => {
1239
+ this.handleItemCompleted(bridge, p).catch((error) => this.failTurn(error));
1240
+ }),
1241
+ listen("item/commandExecution/outputDelta", (p) => this.forward(this.items.onCommandOutputDelta(p))),
1242
+ ...["item/reasoning/textDelta", "item/reasoning/summaryTextDelta"].map((method) => listen(method, (p) => this.forward(this.items.onReasoningDelta(p)))),
1243
+ listen("item/agentMessage/delta", (p) => {
1244
+ const delta = p.delta ?? p.text;
1245
+ if (delta) this.updateText(p.itemId, delta, true);
941
1246
  }),
942
- bridge.onNotification("error", (p) => this.handleErrorNotification(p)),
1247
+ listen("thread/tokenUsage/updated", (p) => this.updateUsage(p)),
1248
+ listen("turn/completed", (p) => this.handleTurnCompleted(p)),
1249
+ listen("error", (p) => this.handleErrorNotification(p)),
943
1250
  bridge.onClose((reason) => {
944
- if (this.activeTurnId === void 0 && this.pendingTurnCompletions.length > 0) {
1251
+ if (this.activeTurnId === void 0 && this.pendingTurnEvents?.length) {
945
1252
  queueMicrotask(() => this.failFromClose(reason));
946
1253
  return;
947
1254
  }
@@ -968,7 +1275,7 @@ var CodexAppServerTurn = class {
968
1275
  this.submittedPlan = await this.planInteractions.confirmSubmittedPlan();
969
1276
  }
970
1277
  return {
971
- text: this.text,
1278
+ text: this.turn.execState?.textBuffer ?? this.text,
972
1279
  toolInvocations: this.items.toolInvocations(),
973
1280
  sessionId,
974
1281
  outcome: this.submittedPlan ? {
@@ -1000,15 +1307,16 @@ var CodexAppServerTurn = class {
1000
1307
  const previous = this.activeThreadId;
1001
1308
  const { thread } = await bridge.request(previous ? "thread/resume" : "thread/start", {
1002
1309
  ...previous ? { threadId: previous } : {},
1003
- cwd: params.cwd,
1310
+ ...previous || !this.turn.execState ? { cwd: params.cwd } : {},
1004
1311
  model: params.model,
1005
1312
  approvalPolicy: params.approvalPolicy,
1006
- sandbox: params.sandbox
1313
+ ...params.sandbox ? { sandbox: params.sandbox } : {}
1007
1314
  });
1008
1315
  if (previous && thread.id !== previous) throw new Error("Codex resumed a different thread");
1009
1316
  this.activeThreadId = thread.id;
1010
1317
  await this.turn.onNativeSession?.(thread.id);
1011
- this.turn.onEvent?.({
1318
+ if (this.turn.execState) this.forward(sessionObservedEvents(this.turn.execState, "codex", thread.id));
1319
+ else this.turn.onEvent?.({
1012
1320
  type: "native.session.observed",
1013
1321
  provider: "codex",
1014
1322
  nativeSessionId: thread.id
@@ -1018,20 +1326,26 @@ var CodexAppServerTurn = class {
1018
1326
  async startTurn(bridge, params) {
1019
1327
  const { input, plans } = this.turn;
1020
1328
  const turnMessage = [durablePlanInstruction(input.planContinuation, plans), params.promptText].filter((part) => typeof part === "string" && part.length > 0).join(PROMPT_SECTION_SEPARATOR);
1329
+ this.pendingTurnEvents = [];
1021
1330
  const startedTurn = await bridge.request("turn/start", {
1022
1331
  threadId: this.activeThreadId,
1023
- input: [{
1332
+ input: [...(params.imagePaths ?? []).map((path) => ({
1333
+ type: "localImage",
1334
+ path
1335
+ })), {
1024
1336
  type: "text",
1025
1337
  text: turnMessage,
1026
1338
  text_elements: []
1027
1339
  }],
1028
1340
  cwd: params.cwd,
1029
1341
  approvalPolicy: params.approvalPolicy,
1030
- sandboxPolicy: sandboxModeToPolicy(params.sandbox, params.cwd),
1342
+ ...!this.turn.execState && params.sandbox ? { sandboxPolicy: sandboxModeToPolicy(params.sandbox, params.cwd) } : {},
1031
1343
  model: params.model
1032
1344
  });
1033
1345
  this.activeTurnId = startedTurn.turn.id;
1034
- this.drainPendingTurnEvents();
1346
+ const events = this.pendingTurnEvents;
1347
+ this.pendingTurnEvents = void 0;
1348
+ for (const deliver of events) deliver();
1035
1349
  }
1036
1350
  completeTurn() {
1037
1351
  if (this.terminalSettled) return;
@@ -1046,23 +1360,11 @@ var CodexAppServerTurn = class {
1046
1360
  forward(events) {
1047
1361
  for (const event of events) this.turn.onEvent?.(event);
1048
1362
  }
1049
- subscribeItems(bridge) {
1050
- return [
1051
- bridge.onNotification("item/started", (p) => this.forward(this.items.onItemStarted(p))),
1052
- bridge.onNotification("item/completed", (p) => this.handleItemCompleted(bridge, p)),
1053
- bridge.onNotification("item/commandExecution/outputDelta", (p) => this.forward(this.items.onCommandOutputDelta(p))),
1054
- bridge.onNotification("item/reasoning/textDelta", (p) => this.forward(this.items.onReasoningDelta(p))),
1055
- bridge.onNotification("item/reasoning/summaryTextDelta", (p) => this.forward(this.items.onReasoningDelta(p)))
1056
- ];
1057
- }
1058
1363
  async handleItemCompleted(bridge, lifecycle) {
1364
+ if (lifecycle.item.type === "agentMessage" && typeof lifecycle.item.text === "string") this.updateText(lifecycle.item.id, lifecycle.item.text, false);
1059
1365
  this.forward(this.items.onItemCompleted(lifecycle));
1060
1366
  const item = lifecycle.item;
1061
1367
  if (!this.turn.plans || item.type !== "mcpToolCall" || item.server !== "tangle-interaction" || item.tool !== "request_plan") return;
1062
- if (lifecycle.threadId !== this.activeThreadId || lifecycle.turnId !== this.activeTurnId) {
1063
- this.failTurn(/* @__PURE__ */ new Error("Codex completed request_plan for a different thread or turn"));
1064
- return;
1065
- }
1066
1368
  if (item.status !== "completed" || !this.submittedPlan) {
1067
1369
  this.failTurn(/* @__PURE__ */ new Error("Codex request_plan completed without a durable plan receipt"));
1068
1370
  return;
@@ -1078,43 +1380,53 @@ var CodexAppServerTurn = class {
1078
1380
  this.failTurn(error);
1079
1381
  }
1080
1382
  }
1081
- subscribeAgentMessage(bridge) {
1082
- const { sessionId, messageId, onEvent } = this.turn;
1083
- return bridge.onNotification("item/agentMessage/delta", (p) => {
1084
- const delta = p.delta ?? p.text ?? "";
1085
- if (!delta) return;
1086
- this.text += delta;
1087
- const part = {
1088
- id: messageId,
1089
- sessionID: sessionId,
1090
- messageID: messageId,
1091
- type: "text",
1092
- text: this.text
1093
- };
1094
- onEvent?.({
1095
- type: "message.part.updated",
1096
- part,
1097
- delta
1098
- });
1383
+ updateText(itemId, value, append) {
1384
+ const { sessionId, messageId, onEvent, execState, logger } = this.turn;
1385
+ if (execState) {
1386
+ const sameItem = this.textItemId === itemId;
1387
+ this.textItemId = itemId;
1388
+ if (append && (sameItem || !execState.textBuffer)) this.forward(textDeltaEvents(execState, value));
1389
+ else if (!sameItem || execState.textBuffer !== value) this.forward(mapCodexEventToStreamEvents({
1390
+ type: "item.completed",
1391
+ item: {
1392
+ type: "agent_message",
1393
+ text: value
1394
+ }
1395
+ }, execState, "codex", logger));
1396
+ return;
1397
+ }
1398
+ if (!append) return;
1399
+ this.text += value;
1400
+ const part = {
1401
+ id: messageId,
1402
+ sessionID: sessionId,
1403
+ messageID: messageId,
1404
+ type: "text",
1405
+ text: this.text
1406
+ };
1407
+ onEvent?.({
1408
+ type: "message.part.updated",
1409
+ part,
1410
+ delta: value
1099
1411
  });
1100
1412
  }
1101
- subscribeTokenUsage(bridge) {
1102
- return bridge.onNotification("thread/tokenUsage/updated", (p) => {
1103
- const total = p.tokenUsage?.total;
1104
- if (!total) return;
1105
- this.tokenUsage = {
1106
- inputTokens: total.inputTokens ?? 0,
1107
- outputTokens: total.outputTokens ?? 0,
1108
- cacheReadInputTokens: total.cachedInputTokens
1109
- };
1110
- });
1413
+ updateUsage(params) {
1414
+ const total = params.tokenUsage?.total;
1415
+ if (!total) return;
1416
+ this.tokenUsage = {
1417
+ inputTokens: total.inputTokens ?? 0,
1418
+ outputTokens: total.outputTokens ?? 0,
1419
+ cacheReadInputTokens: total.cachedInputTokens,
1420
+ ...this.turn.execState ? { reasoningTokens: total.reasoningOutputTokens } : {}
1421
+ };
1422
+ if (this.turn.execState) this.turn.execState.tokenUsage = this.tokenUsage;
1111
1423
  }
1112
1424
  handleTurnCompleted(completed) {
1113
- if (this.activeThreadId === void 0 || this.activeTurnId === void 0) {
1114
- this.pendingTurnCompletions.push(completed);
1115
- return;
1425
+ if (this.turn.execState && completed.turn.items) {
1426
+ this.forward(this.items.reconcileTurnItems(completed));
1427
+ const final = completed.turn.items.filter((item) => item.type === "agentMessage").at(-1);
1428
+ if (final && typeof final.text === "string") this.updateText(final.id, final.text, false);
1116
1429
  }
1117
- if (completed.threadId !== this.activeThreadId || completed.turn.id !== this.activeTurnId) return;
1118
1430
  if (this.submittedPlan) {
1119
1431
  if (!this.planInterruptRequested || completed.turn.status !== "interrupted") {
1120
1432
  this.failTurn(/* @__PURE__ */ new Error(`Codex planning turn ended as ${completed.turn.status} before its durable plan was interrupted`));
@@ -1138,15 +1450,7 @@ var CodexAppServerTurn = class {
1138
1450
  });
1139
1451
  this.failTurn(error);
1140
1452
  }
1141
- drainPendingTurnEvents() {
1142
- if (this.activeThreadId === void 0 || this.activeTurnId === void 0) return;
1143
- const pendingCompletions = this.pendingTurnCompletions.splice(0);
1144
- for (const completed of pendingCompletions) this.handleTurnCompleted(completed);
1145
- const pendingErrors = this.pendingTurnErrors.splice(0);
1146
- for (const pending of pendingErrors) this.reportTurnError(pending.error, pending.warning);
1147
- }
1148
- handleErrorNotification(p) {
1149
- const e = p;
1453
+ handleErrorNotification(e) {
1150
1454
  const base = e.error?.message ?? "codex turn error";
1151
1455
  const warning = e.error?.additionalDetails ? `${base} (${e.error.additionalDetails})` : base;
1152
1456
  if (e.willRetry === true) {
@@ -1157,17 +1461,9 @@ var CodexAppServerTurn = class {
1157
1461
  });
1158
1462
  return;
1159
1463
  }
1160
- if (this.activeTurnId === void 0 && this.pendingTurnCompletions.length > 0) {
1161
- this.pendingTurnErrors.push({
1162
- error: new Error(base),
1163
- warning
1164
- });
1165
- return;
1166
- }
1167
1464
  this.reportTurnError(new Error(base), warning);
1168
1465
  }
1169
1466
  failFromClose(reason) {
1170
- this.drainPendingTurnEvents();
1171
1467
  if (this.terminalSettled) return;
1172
1468
  const error = reason.error ?? /* @__PURE__ */ new Error(`Codex app-server closed before the matching turn completed (${reason.reason}): send the next turn to resume its thread`);
1173
1469
  this.closeEnd = turnEndReason({
@@ -1425,7 +1721,7 @@ var CodexSecretProfileAdapter = class extends CodexNativeLaunchAdapter {
1425
1721
  }))) this.refuse("native MCP controls differ", cwd);
1426
1722
  return servers;
1427
1723
  }
1428
- nativeArgs(input, plan, mcp) {
1724
+ nativeArgs(input, plan, mcp, strictConfig = true) {
1429
1725
  const prompts = {
1430
1726
  ...this.resolveProfilePrompts(input, plan),
1431
1727
  correlationHeaders: executionCorrelationHeaders(input.interactionBinding, input.traceId, input.managedQuoteVersion)
@@ -1438,7 +1734,7 @@ var CodexSecretProfileAdapter = class extends CodexNativeLaunchAdapter {
1438
1734
  const flags = (plan?.spawn.flags ?? []).filter((flag, index, all) => mcp === void 0 || !(flag === "-c" ? all[index + 1] : flag)?.startsWith("mcp_servers="));
1439
1735
  return [
1440
1736
  "app-server",
1441
- "--strict-config",
1737
+ ...strictConfig ? ["--strict-config"] : [],
1442
1738
  ...CODEX_DISABLED_FEATURE_ARGS,
1443
1739
  ...this.nativeConfigArgs(this.config, connection, prompts, flags),
1444
1740
  ...mcp === void 0 ? [] : ["-c", `mcp_servers=${inlineToml(mcp)}`]
@@ -1583,14 +1879,15 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1583
1879
  await this.seedNativeSessionForResume(input, nativeResume.nativeSessionId);
1584
1880
  }
1585
1881
  const { interactive, questions, plans } = appServerPolicy(this.config, input);
1586
- if (!this.config.secretProfileRevisionRoot && !interactive && !questions && !plans && !input.planContinuation) return super.execute(input, services, onEvent);
1882
+ const execOutput = !this.config.secretProfileRevisionRoot && !interactive && !questions && !plans && !input.planContinuation;
1883
+ if (execOutput && (process.env.CODEX_STREAM !== "1" || this.launcher || this.config.extraFlags?.length || input.managedQuoteVersion !== void 0)) return super.execute(input, services, onEvent);
1587
1884
  return this.withExecution(input.abortSignal, (signal) => this.executeViaAppServer({
1588
1885
  ...input,
1589
1886
  abortSignal: signal
1590
- }, services, onEvent, input));
1887
+ }, services, onEvent, input, execOutput));
1591
1888
  }
1592
- async executeViaAppServer(input, services, onEvent, mcpInput = input) {
1593
- const prepared = await this.prepareAppServerTurn(input, services, onEvent, mcpInput);
1889
+ async executeViaAppServer(input, services, onEvent, mcpInput, execOutput) {
1890
+ const prepared = await this.prepareAppServerTurn(input, services, onEvent, mcpInput, execOutput);
1594
1891
  if (prepared.cached !== void 0) return prepared.cached;
1595
1892
  const queue = this.config.secretProfileRevisionRoot ? secretSessionTurnQueue(this.secretProfileSessionView(prepared.sessionId).view) : this.secretProfileReferences(prepared.profilePlan) ? secretSessionTurnQueue(secretMcpScope(prepared.sessionId, this.subprocessIdentity()?.uid, this.mcpOwner)) : void 0;
1596
1893
  let bridge;
@@ -1609,10 +1906,47 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1609
1906
  bridge = await this.launchAppServerTurn(prepared);
1610
1907
  result = await this.runAppServerTurn(prepared, bridge);
1611
1908
  } catch (error) {
1612
- throw closing ? error : await failureAfterCleanup(error, "Codex app-server turn and its close failed", close);
1909
+ let cause = error;
1910
+ if (prepared.exec && bridge) {
1911
+ const { state, observer } = prepared.exec;
1912
+ state.endReason ??= error?.reason;
1913
+ state.lastDiagnostic = state.endReason === "repeated_tool_failure" ? state.lastDiagnostic : error instanceof Error ? error.message : String(error);
1914
+ const exitResult = {
1915
+ success: false,
1916
+ code: bridge.process?.exitCode ?? null,
1917
+ signal: bridge.process?.signalCode ?? null,
1918
+ timedOut: state.endReason === "timeout"
1919
+ };
1920
+ const { errorMessage, failure } = endFailedTurn({
1921
+ provider: this.provider,
1922
+ state,
1923
+ exitResult,
1924
+ stderr: "",
1925
+ aborted: input.abortSignal?.aborted === true,
1926
+ command: this.getCliPath(),
1927
+ nixBinPath: prepared.env.NIX_BIN_PATH,
1928
+ startTime: prepared.startTime,
1929
+ endTime: Date.now()
1930
+ });
1931
+ onEvent?.({
1932
+ type: "status",
1933
+ status: "failed",
1934
+ detail: errorMessage
1935
+ });
1936
+ await recordTurnInterruption({
1937
+ recorder: services.recorder,
1938
+ observer,
1939
+ logger: this.logger,
1940
+ errorMessage,
1941
+ exitResult,
1942
+ failure
1943
+ });
1944
+ cause = failure;
1945
+ }
1946
+ throw closing ? cause : await failureAfterCleanup(cause, "Codex app-server turn and its close failed", close);
1613
1947
  }
1614
1948
  if (!closing) await close();
1615
- await services.recorder.markTurnCompleted?.({ result });
1949
+ if (!prepared.exec) await services.recorder.markTurnCompleted?.({ result });
1616
1950
  onEvent?.({
1617
1951
  type: "status",
1618
1952
  status: "completed"
@@ -1621,45 +1955,79 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1621
1955
  }
1622
1956
  /** Capture session binding, profile/prompt and native callbacks before acquiring resources.
1623
1957
  * Field construction stays one preparation record; launch/run/cleanup have separate owners. */
1624
- async prepareAppServerTurn(input, services, onEvent, mcpInput) {
1958
+ async prepareAppServerTurn(input, services, onEvent, mcpInput, execOutput) {
1625
1959
  this.ensureInitialized();
1626
- const opened = await this.openTurnSession({
1960
+ const startTime = Date.now();
1961
+ const opened = await this.openTurnSession(execOutput ? input : {
1627
1962
  ...input,
1628
1963
  sessionId: input.sessionId ?? input.interactionBinding?.sessionId
1629
1964
  }, services.recorder, onEvent);
1630
1965
  if (opened.cached) return { cached: opened.cached };
1631
1966
  const { sessionId } = opened;
1632
- const interactionBinding = this.interactionExecutionBinding(input, sessionId);
1967
+ const interactionBinding = execOutput ? void 0 : this.interactionExecutionBinding(input, sessionId);
1633
1968
  const workspace = input.workspaceRoot ?? this.storagePath;
1634
1969
  const { profilePlan } = await this.materializeTurnProfile(input, sessionId);
1635
- const { promptText } = await this.recordTurnPrompt(input, opened, services.recorder, {
1970
+ const { promptText, preparedInput } = await this.recordTurnPrompt(input, opened, services.recorder, execOutput ? void 0 : {
1636
1971
  nativeAttachmentKinds: [],
1637
1972
  inlineImageBudgetBytes: 0
1638
1973
  });
1974
+ const images = execOutput ? partitionImageAttachments({
1975
+ message: promptText,
1976
+ attachments: preparedInput.attachments,
1977
+ qualifies: (attachment) => attachment.path !== void 0
1978
+ }) : void 0;
1979
+ const env = execOutput ? this.buildTurnEnvironment(this.withProfilePlan(this.config, profilePlan), profilePlan, workspace, executionCorrelationHeaders(input.interactionBinding, input.traceId)) : this.buildAppServerEnv(profilePlan, workspace);
1639
1980
  const connection = resolveCodexConnection(this.config, this.resolveProfileModel(input.model?.model) ?? this.config.model);
1640
1981
  const policy = appServerPolicy(this.config, input);
1641
1982
  const run = {
1642
- promptText,
1983
+ promptText: images?.message ?? promptText,
1984
+ imagePaths: images?.native.map((attachment) => attachment.path),
1643
1985
  cwd: workspace,
1644
1986
  model: connection.model,
1645
- ...policy
1987
+ ...policy,
1988
+ sandbox: execOutput && this.config.bypassPermissions === false ? this.config.sandboxMode : policy.sandbox
1646
1989
  };
1990
+ const messageId = opened.providerMessageIds?.assistantMessageId ?? randomUUID();
1991
+ const state = execOutput ? createExecutionState(sessionId, messageId, workspace) : void 0;
1992
+ const exec = state ? {
1993
+ state,
1994
+ observer: new TurnObserver({
1995
+ provider: this.provider,
1996
+ state,
1997
+ sessionId,
1998
+ getRuntimeHome: () => this.config.runtimeHome,
1999
+ recorder: services.recorder,
2000
+ getSessionStore: () => this.getSessionStore(),
2001
+ logger: this.logger,
2002
+ repairToolNames: this.toolCallRepairToolNames(),
2003
+ onEvent
2004
+ })
2005
+ } : void 0;
1647
2006
  const turn = new CodexAppServerTurn({
1648
2007
  sessionId,
1649
- messageId: opened.providerMessageIds?.assistantMessageId ?? randomUUID(),
2008
+ messageId,
1650
2009
  input,
1651
- onEvent,
2010
+ execState: state,
2011
+ onEvent: exec ? (event) => {
2012
+ if (event.type === "session.updated" || event.type === "native.session.observed") onEvent?.(event);
2013
+ else exec.observer.onEvent(event);
2014
+ } : onEvent,
1652
2015
  logger: this.logger,
1653
2016
  plans: policy.plans,
1654
2017
  onNativeSession: async (providerSessionId) => {
1655
- await this.getSessionStore().update(opened.sessionId, {
2018
+ const updated = await this.getSessionStore().update(opened.sessionId, {
1656
2019
  providerSessionId,
1657
2020
  ...this.config.runtimeHome ? { providerSessionHome: this.config.runtimeHome } : {}
1658
2021
  });
2022
+ if (exec && !updated) throw new Error(`Session ${sessionId} disappeared before its provider session could be persisted`);
1659
2023
  }
1660
2024
  });
1661
2025
  turn.activeThreadId = initialThreadId(input) ?? opened.providerSessionId;
1662
2026
  return {
2027
+ exec,
2028
+ env,
2029
+ startTime,
2030
+ providerMessageIds: opened.providerMessageIds,
1663
2031
  releaseMcp: void 0,
1664
2032
  mcpInput,
1665
2033
  input,
@@ -1675,16 +2043,17 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1675
2043
  }
1676
2044
  async launchAppServerTurn(context) {
1677
2045
  const { input, profilePlan, run } = context;
2046
+ const argsForTurn = () => this.nativeArgs(input, profilePlan, void 0, !context.exec);
1678
2047
  const secret = profilePlan && (this.config.secretProfileRevisionRoot || this.secretProfileReferences(profilePlan)) ? await this.prepareSecretCodexTurn(input, profilePlan, context.sessionId, context.mcpInput, (release) => {
1679
2048
  context.releaseMcp = release;
1680
2049
  }, this.config.secretProfileRevisionRoot ? void 0 : {
1681
- args: this.nativeArgs(input, profilePlan),
1682
- env: this.buildAppServerEnv(profilePlan, run.cwd),
2050
+ args: argsForTurn(),
2051
+ env: context.env,
1683
2052
  cwd: run.cwd
1684
2053
  }) : void 0;
1685
- const env = secret?.env ?? this.buildAppServerEnv(profilePlan, run.cwd);
2054
+ const env = secret?.env ?? context.env;
1686
2055
  run.cwd = secret?.cwd ?? run.cwd;
1687
- const args = secret?.args ?? this.nativeArgs(input, profilePlan);
2056
+ const args = secret?.args ?? argsForTurn();
1688
2057
  const extraMcp = await this.bindPlanMcp(context, args, env);
1689
2058
  if (secret?.validate) run.initialize = async (initialized) => {
1690
2059
  await secret.validate?.(initialized, extraMcp);
@@ -1717,8 +2086,28 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1717
2086
  const { turn, run, sessionId, services, onEvent, interactionBinding } = context;
1718
2087
  registerAppServerInteractions(bridge, this.permissions, sessionId, interactionBinding, context.policy.interactive, context.policy.questions, onEvent);
1719
2088
  const unsubscribe = turn.subscribe(bridge);
2089
+ const { exec } = context;
2090
+ exec?.observer.attachProcess({ kill: () => {
2091
+ bridge.close().catch((error) => this.logger.warn("Failed to close stopped Codex turn", { error: String(error) }));
2092
+ return true;
2093
+ } });
2094
+ const liveness = context.input.abortSignal && exec?.observer.startLiveness(context.input.abortSignal, context.startTime);
1720
2095
  try {
1721
2096
  const result = await turn.run(bridge, run);
2097
+ if (exec) {
2098
+ if (exec.state.endReason) throw new Error(exec.state.lastDiagnostic ?? exec.state.endReason);
2099
+ return await this.completeTurn({
2100
+ input: context.input,
2101
+ sessionId,
2102
+ state: exec.state,
2103
+ observer: exec.observer,
2104
+ recorder: services.recorder,
2105
+ providerMessageIds: context.providerMessageIds,
2106
+ profilePlan: context.profilePlan,
2107
+ startTime: context.startTime,
2108
+ endTime: Date.now()
2109
+ });
2110
+ }
1722
2111
  await services.recorder.appendAssistantParts([{
1723
2112
  id: randomUUID(),
1724
2113
  type: "text",
@@ -1734,6 +2123,7 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1734
2123
  });
1735
2124
  return result;
1736
2125
  } finally {
2126
+ clearInterval(liveness);
1737
2127
  unsubscribe();
1738
2128
  }
1739
2129
  }
@@ -1741,7 +2131,7 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1741
2131
  try {
1742
2132
  await context.turn.planInteractions?.stop(context.sessionId);
1743
2133
  } finally {
1744
- this.permissions.failSession(context.sessionId);
2134
+ if (context.interactionBinding) this.permissions.failSession(context.sessionId);
1745
2135
  try {
1746
2136
  await bridge?.close();
1747
2137
  } finally {
@@ -1754,6 +2144,7 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1754
2144
  if (!context.policy.plans) return {};
1755
2145
  const { turn, sessionId, interactionBinding, services, onEvent } = context;
1756
2146
  turn.planInteractions = new McpInteractionSupport(CODEX_PLAN_MCP_NAME, [InteractionKind.Plan]);
2147
+ if (!interactionBinding) throw new Error("Codex plan MCP requires an interaction binding");
1757
2148
  const planMcp = await turn.planInteractions.start(sessionId, interactionBinding, onEvent, {
1758
2149
  planHost: services.planHost,
1759
2150
  providerState: () => turn.planProviderState(),
@@ -1774,214 +2165,6 @@ var CodexAppServerAdapter = class extends CodexSecretProfileAdapter {
1774
2165
  }
1775
2166
  };
1776
2167
  //#endregion
1777
- //#region src/codex-exec-events.ts
1778
- function mapCodexEventToStreamEvents(event, state, provider, logger) {
1779
- switch (event.type) {
1780
- case "session_started": return mapSessionStartedEvent(event, state);
1781
- case "thread.started": return mapThreadStartedEvent(event, state, provider);
1782
- case "message": return mapMessageEvent(event, state, logger);
1783
- case "item.started": return mapToolItem(event.item, state, false) ?? [{
1784
- type: "raw",
1785
- backend: provider,
1786
- event
1787
- }];
1788
- case "item.completed": return mapToolItem(event.item, state, true) ?? mapItemCompletedEvent(event, state, provider, logger);
1789
- case "turn.completed":
1790
- recordCliTokenUsage(state, event.usage);
1791
- return [{
1792
- type: "raw",
1793
- backend: provider,
1794
- event
1795
- }];
1796
- case "task_started": return mapTaskStartedEvent(event);
1797
- case "error": return mapErrorEvent(event);
1798
- default: return [{
1799
- type: "raw",
1800
- backend: provider,
1801
- event
1802
- }];
1803
- }
1804
- }
1805
- /**
1806
- * A tool the agent ran, as `codex exec --json` reports it: an item that
1807
- * starts and then completes. A completion without a start emits both.
1808
- * Undefined for an item that is not a tool.
1809
- */
1810
- function mapToolItem(item, state, completed) {
1811
- const call = codexToolCall(item);
1812
- if (!call) return void 0;
1813
- const events = state.toolCalls.has(call.id) ? [] : toolStartEvents(state, call);
1814
- if (!completed) return events;
1815
- const failed = item.status === "failed" || item.status === "declined" || typeof item.exit_code === "number" && item.exit_code !== 0 || item.error !== void 0 && item.error !== null;
1816
- return [...events, ...toolResultEvents(state, {
1817
- id: call.id,
1818
- content: item.aggregated_output ?? item.result ?? item.error ?? item.status,
1819
- isError: failed
1820
- })];
1821
- }
1822
- function codexToolCall(item) {
1823
- const id = item.id;
1824
- if (typeof id !== "string" || id.length === 0) return void 0;
1825
- switch (item.type) {
1826
- case "command_execution": return {
1827
- id,
1828
- name: "bash",
1829
- input: { command: item.command ?? "" }
1830
- };
1831
- case "mcp_tool_call":
1832
- if (!item.server && !item.tool) return void 0;
1833
- return {
1834
- id,
1835
- name: `mcp__${item.server ?? ""}__${item.tool ?? ""}`,
1836
- input: item.arguments ?? {}
1837
- };
1838
- case "web_search": return {
1839
- id,
1840
- name: "websearch",
1841
- input: { query: item.query ?? "" }
1842
- };
1843
- default: return;
1844
- }
1845
- }
1846
- function mapItemCompletedEvent(event, state, provider, logger) {
1847
- if (event.item?.type === "file_change") {
1848
- const fileEvents = mapFileChangeCompleted(event.item, state, logger);
1849
- if (fileEvents !== null) return fileEvents;
1850
- return [{
1851
- type: "raw",
1852
- backend: provider,
1853
- event
1854
- }];
1855
- }
1856
- if (event.item?.type !== "agent_message" || typeof event.item.text !== "string") return [{
1857
- type: "raw",
1858
- backend: provider,
1859
- event
1860
- }];
1861
- const nextText = event.item.text;
1862
- const previousLength = state.textBuffer.length;
1863
- const delta = nextText.startsWith(state.textBuffer) ? nextText.slice(previousLength) : void 0;
1864
- state.textBuffer = nextText;
1865
- state.textPartId ??= randomUUID();
1866
- return [{
1867
- type: "message.part.updated",
1868
- part: {
1869
- ...streamPartBase(state, state.textPartId),
1870
- type: "text",
1871
- text: state.textBuffer
1872
- },
1873
- ...delta ? { delta } : {}
1874
- }];
1875
- }
1876
- function mapFileChangeCompleted(item, state, logger) {
1877
- if (!Array.isArray(item.changes)) {
1878
- logger.debug("file_change item.completed without a changes array", { itemId: item.id });
1879
- return null;
1880
- }
1881
- if (item.status !== void 0 && item.status !== "completed") return null;
1882
- const events = [];
1883
- for (const change of item.changes) {
1884
- if (typeof change?.path !== "string" || change.path.length === 0) {
1885
- logger.debug("malformed change in file_change item", { itemId: item.id });
1886
- continue;
1887
- }
1888
- if (change.kind == null) {
1889
- logger.debug("change without a kind in file_change item", {
1890
- itemId: item.id,
1891
- path: change.path
1892
- });
1893
- continue;
1894
- }
1895
- const tracked = trackFilePart(state, {
1896
- path: change.path,
1897
- changeKind: normalizeChangeKind(change.kind) ?? "update"
1898
- });
1899
- if (!tracked) continue;
1900
- events.push(filePartUpdated(state, tracked));
1901
- }
1902
- return events.length > 0 ? events : null;
1903
- }
1904
- function mapSessionStartedEvent(event, state) {
1905
- return [...sessionObservedEvents(state, "codex", event.session_id), {
1906
- type: "status",
1907
- status: "processing",
1908
- detail: "Session started"
1909
- }];
1910
- }
1911
- function mapThreadStartedEvent(event, state, provider) {
1912
- return [...sessionObservedEvents(state, "codex", event.thread_id), {
1913
- type: "raw",
1914
- backend: provider,
1915
- event
1916
- }];
1917
- }
1918
- function mapMessageEvent(event, state, logger) {
1919
- if (event.role !== "assistant" || !event.message.content) return [];
1920
- const events = [];
1921
- for (const block of event.message.content) events.push(...mapContentBlock(block, state, logger));
1922
- return events;
1923
- }
1924
- function mapContentBlock(block, state, logger) {
1925
- switch (block.type) {
1926
- case "text": return textDeltaEvents(state, block.text);
1927
- case "thinking": return reasoningEvents(state, block.thinking, { signalPhase: true });
1928
- case "tool_use": return toolStartEvents(state, block);
1929
- case "tool_result": return toolResultEvents(state, {
1930
- id: block.tool_use_id,
1931
- content: block.content,
1932
- isError: Boolean(block.is_error),
1933
- afterSuccess: (toolCall) => detectFileParts(toolCall, block.content, state, logger)
1934
- });
1935
- default: return [];
1936
- }
1937
- }
1938
- function detectFileParts(toolCall, raw, state, logger) {
1939
- const events = [];
1940
- if (!toolCall.name.startsWith("mcp__") || !Array.isArray(raw)) return events;
1941
- for (const block of raw) {
1942
- if (typeof block !== "object" || block === null || block.type !== "image") continue;
1943
- const { data, mimeType } = block;
1944
- if (typeof data !== "string" || typeof mimeType !== "string" || !/^[a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+$/.test(mimeType)) {
1945
- logger.debug("malformed image block in MCP tool result", { tool: toolCall.name });
1946
- continue;
1947
- }
1948
- const tracked = trackFilePart(state, {
1949
- dataUri: `data:${mimeType};base64,${data}`,
1950
- mediaType: mimeType
1951
- });
1952
- if (!tracked) continue;
1953
- events.push(filePartUpdated(state, tracked));
1954
- }
1955
- return events;
1956
- }
1957
- function mapTaskStartedEvent(event) {
1958
- return [{
1959
- type: "status",
1960
- status: "processing",
1961
- detail: `Task ${event.task_type ?? event.task_id} started`
1962
- }];
1963
- }
1964
- function mapErrorEvent(event) {
1965
- return [{
1966
- type: "warning",
1967
- code: event.code ?? "CODEX_ERROR",
1968
- message: event.message
1969
- }];
1970
- }
1971
- /** The complete emitted part for either native-path or MCP image observations. */
1972
- function filePartUpdated(state, tracked) {
1973
- return {
1974
- type: "message.part.updated",
1975
- part: {
1976
- ...streamPartBase(state, tracked.id),
1977
- type: "file",
1978
- ...tracked.filename ? { filename: tracked.filename } : {},
1979
- ...tracked.mediaType ? { mediaType: tracked.mediaType } : {},
1980
- url: tracked.url
1981
- }
1982
- };
1983
- }
1984
- //#endregion
1985
2168
  //#region src/held-spare.ts
1986
2169
  /**
1987
2170
  * The Codex process started before the turn that uses it (the shared
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-provider-codex",
3
- "version": "0.4.106",
3
+ "version": "0.4.108",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -18,8 +18,8 @@
18
18
  "@tangle-network/agent-backend-types": "1.3.4",
19
19
  "@tangle-network/agent-interface": "^5.10.28",
20
20
  "@tangle-network/sdk-cli-runner": "0.3.14",
21
- "@tangle-network/sdk-provider-cli-base": "0.13.129",
22
- "@tangle-network/sdk-session-persistence": "0.7.15",
21
+ "@tangle-network/sdk-provider-cli-base": "0.13.133",
22
+ "@tangle-network/sdk-session-persistence": "0.7.16",
23
23
  "smol-toml": "^1.9.0",
24
24
  "zod": "4.6.7"
25
25
  },
@@ -35,8 +35,8 @@
35
35
  "registry": "https://registry.npmjs.org"
36
36
  },
37
37
  "tangleRelease": {
38
- "sourceSha": "00ce0b3b3f5971bae76607ff9949a42cdf1f4b25",
39
- "mergedAt": "2026-11-19T17:55:16-08:00"
38
+ "sourceSha": "a3279e5ca9286d7b244f65b1b5d3517dc77e8b99",
39
+ "mergedAt": "2026-11-19T19:14:53-08:00"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsdown",