@moxt-ai/mobius 0.0.430 → 0.0.432

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 (33) hide show
  1. package/dist/{chunk-6DTIQNQZ.js → chunk-JQTOOWQD.js} +995 -953
  2. package/dist/{chunk-6DTIQNQZ.js.map → chunk-JQTOOWQD.js.map} +4 -4
  3. package/dist/{chunk-BMTH2ZGL.js → chunk-XGIXOFFC.js} +2 -2
  4. package/dist/{chunk-BMTH2ZGL.js.map → chunk-XGIXOFFC.js.map} +1 -1
  5. package/dist/{cli-BSEEN4KA.js → cli-3COT67TX.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/adapter/codex/adapter.d.ts.map +1 -1
  8. package/dist/engine/acp/adapter/codex/adapter.js +2 -2
  9. package/dist/engine/acp/adapter/codex/adapter.js.map +1 -1
  10. package/dist/engine/acp/adapter/session-events.d.ts +6 -0
  11. package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/session-events.js +23 -7
  13. package/dist/engine/acp/adapter/session-events.js.map +1 -1
  14. package/dist/engine/acp/harness/codex/app-server-protocol.d.ts +4 -0
  15. package/dist/engine/acp/harness/codex/app-server-protocol.d.ts.map +1 -1
  16. package/dist/engine/acp/harness/codex/app-server-protocol.js +11 -0
  17. package/dist/engine/acp/harness/codex/app-server-protocol.js.map +1 -1
  18. package/dist/engine/acp/harness/codex/borrowed-agent.d.ts.map +1 -1
  19. package/dist/engine/acp/harness/codex/borrowed-agent.js +9 -6
  20. package/dist/engine/acp/harness/codex/borrowed-agent.js.map +1 -1
  21. package/dist/engine/acp/harness/codex/history.js +2 -2
  22. package/dist/engine/acp/harness/codex/history.js.map +1 -1
  23. package/dist/engine/acp/harness/codex/items.d.ts +3 -0
  24. package/dist/engine/acp/harness/codex/items.d.ts.map +1 -1
  25. package/dist/engine/acp/harness/codex/items.js +6 -0
  26. package/dist/engine/acp/harness/codex/items.js.map +1 -1
  27. package/dist/engine/acp/harness/codex/owned-agent.d.ts +2 -1
  28. package/dist/engine/acp/harness/codex/owned-agent.d.ts.map +1 -1
  29. package/dist/engine/acp/harness/codex/owned-agent.js +4 -3
  30. package/dist/engine/acp/harness/codex/owned-agent.js.map +1 -1
  31. package/dist/engine.js +2 -2
  32. package/package.json +2 -2
  33. /package/dist/{cli-BSEEN4KA.js.map → cli-3COT67TX.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-BMTH2ZGL.js";
6
+ } from "./chunk-XGIXOFFC.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -20669,9 +20669,17 @@ var contentChunkFields = {
20669
20669
  content: contentBlockSchema,
20670
20670
  messageId: shortString.nullable().optional()
20671
20671
  };
20672
+ var agentQuestionSchema = external_exports.object({
20673
+ options: external_exports.array(shortString).max(MAX_COLLECTION_SIZE2).readonly(),
20674
+ question: boundedString2
20675
+ }).readonly();
20672
20676
  var acpSessionUpdateSchema = external_exports.discriminatedUnion("sessionUpdate", [
20673
20677
  external_exports.object({ ...contentChunkFields, sessionUpdate: external_exports.literal("user_message_chunk") }).readonly(),
20674
- external_exports.object({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_message_chunk") }).readonly(),
20678
+ external_exports.object({
20679
+ ...contentChunkFields,
20680
+ questions: external_exports.array(agentQuestionSchema).min(1).max(MAX_COLLECTION_SIZE2).readonly().optional(),
20681
+ sessionUpdate: external_exports.literal("agent_message_chunk")
20682
+ }).readonly(),
20675
20683
  external_exports.object({
20676
20684
  ...contentChunkFields,
20677
20685
  meta: external_exports.object({ truncated: external_exports.boolean().optional() }).readonly().optional(),
@@ -71991,6 +71999,12 @@ var imageGenerationItemSchema = external_exports.object({
71991
71999
  resetsAt: external_exports.number().nullish()
71992
72000
  }).nullish()
71993
72001
  });
72002
+ var agentMessageQuestionsSchema = external_exports.array(
72003
+ external_exports.object({
72004
+ options: external_exports.array(boundedText(2048)).max(100).nullish(),
72005
+ title: boundedText(32768).min(1)
72006
+ })
72007
+ ).max(100).nullish().catch(null);
71994
72008
  var threadItemSchema = external_exports.discriminatedUnion("type", [
71995
72009
  imageGenerationItemSchema,
71996
72010
  external_exports.object({ type: external_exports.literal("imageView"), id: boundedText(256), path: boundedText(32768).refine(isAbsolute8) }),
@@ -71998,7 +72012,8 @@ var threadItemSchema = external_exports.discriminatedUnion("type", [
71998
72012
  id: boundedText(256),
71999
72013
  text: boundedText(1e6),
72000
72014
  type: external_exports.literal("agentMessage"),
72001
- phase: messagePhaseSchema.nullish()
72015
+ phase: messagePhaseSchema.nullish(),
72016
+ questions: agentMessageQuestionsSchema
72002
72017
  }),
72003
72018
  external_exports.object({
72004
72019
  content: external_exports.array(external_exports.unknown()).max(1e4),
@@ -72470,7 +72485,7 @@ var CodexAppServerClient = class {
72470
72485
  };
72471
72486
 
72472
72487
  // src/engine/acp/harness/codex/borrowed-agent.ts
72473
- import { randomUUID as randomUUID7 } from "node:crypto";
72488
+ import { randomUUID as randomUUID8 } from "node:crypto";
72474
72489
 
72475
72490
  // src/engine/util/timer.ts
72476
72491
  var SystemTimer = class {
@@ -72697,6 +72712,9 @@ function decodeThreadItem(value) {
72697
72712
  const decoded = threadItemSchema.safeParse(value);
72698
72713
  return decoded.success ? decoded.data : null;
72699
72714
  }
72715
+ function messageQuestions(item) {
72716
+ return item.type === "agentMessage" ? (item.questions ?? []).map((question) => ({ options: question.options ?? [], question: question.title })) : [];
72717
+ }
72700
72718
  function reasoningText(item) {
72701
72719
  if (item.type !== "reasoning") {
72702
72720
  return null;
@@ -72704,6 +72722,10 @@ function reasoningText(item) {
72704
72722
  return boundedParagraphs(item.content.length > 0 ? item.content : item.summary, TOOL_OUTPUT_CHARACTER_LIMIT);
72705
72723
  }
72706
72724
 
72725
+ // src/engine/acp/harness/codex/owned-agent.ts
72726
+ import { randomUUID as randomUUID7 } from "node:crypto";
72727
+ import { setTimeout as delay } from "node:timers/promises";
72728
+
72707
72729
  // src/engine/acp/harness/codex/session-update.ts
72708
72730
  async function promptResultWithMessageId2(result, messageId) {
72709
72731
  try {
@@ -72760,837 +72782,278 @@ function userMessageUpdates(item, submitted) {
72760
72782
  });
72761
72783
  }
72762
72784
 
72763
- // src/engine/acp/harness/codex/borrowed-agent.ts
72764
- var REQUEST_TIMEOUT = 3e4;
72765
- var POLL_INTERVAL = 500;
72766
- var UNANSWERED_READ_LIMIT = 3;
72767
- var queueResponseSchema = external_exports.object({
72768
- queuedSubmission: external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })
72769
- });
72770
- var queuePageSchema = external_exports.object({
72771
- data: external_exports.array(external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })).max(100),
72772
- nextCursor: external_exports.string().nullish()
72773
- });
72774
- function turnRunning(turn) {
72775
- return turn.status === "inProgress" || turn.status === "interrupted" && turn.completedAt == null;
72776
- }
72777
- function waitForNextPoll(timer, signal) {
72778
- signal.throwIfAborted();
72779
- return new Promise((resolve19, reject2) => {
72780
- const poll = timer.schedule(() => {
72781
- signal.removeEventListener("abort", abort);
72782
- resolve19();
72783
- }, POLL_INTERVAL);
72784
- const abort = () => {
72785
- poll.cancel();
72786
- reject2(signal.reason);
72787
- };
72788
- signal.addEventListener("abort", abort, { once: true });
72789
- });
72790
- }
72791
- var CodexBorrowedAcpAgent = class {
72792
- steeringSupported = false;
72793
- runsTurns = false;
72794
- #client;
72795
- #threadId;
72796
- #emit;
72797
- #onDelegation;
72798
- #closed = new AbortController();
72799
- #seen = /* @__PURE__ */ new Map();
72800
- #pending = null;
72801
- #watch = null;
72802
- #lifecycle = { kind: "following" };
72803
- constructor(client2, threadId, emit, onDelegation) {
72804
- this.#client = client2;
72805
- this.#threadId = threadId;
72806
- this.#emit = emit;
72807
- this.#onDelegation = onDelegation;
72785
+ // src/engine/acp/harness/codex/owned-agent.ts
72786
+ var APPROVAL_REASON_CHARACTER_LIMIT = 500;
72787
+ var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
72788
+ var COMPACT_TIMEOUT_MILLISECONDS = 36e5;
72789
+ var COMPACT_ITEM_WAIT_MILLISECONDS = 6e5;
72790
+ var THREAD_NOTIFICATIONS = /* @__PURE__ */ new Set([
72791
+ "item/agentMessage/delta",
72792
+ "item/completed",
72793
+ "item/reasoning/summaryTextDelta",
72794
+ "item/reasoning/textDelta",
72795
+ "item/started",
72796
+ "thread/compacted",
72797
+ "thread/name/updated",
72798
+ "thread/settings/updated",
72799
+ "turn/completed",
72800
+ "turn/plan/updated",
72801
+ "turn/started"
72802
+ ]);
72803
+ var APPROVAL_OPTIONS = Object.freeze([
72804
+ { kind: "allow_once", name: "Allow once", optionId: "accept" },
72805
+ { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
72806
+ { kind: "reject_once", name: "Deny", optionId: "decline" }
72807
+ ]);
72808
+ function permissionDecision(optionId) {
72809
+ if (optionId === "accept" || optionId === "acceptForSession" || optionId === "decline") {
72810
+ return optionId;
72808
72811
  }
72809
- #reportDelegation = async (pending, stage) => {
72810
- pending.delegation = pending.delegation.then(async () => await this.#onDelegation(stage));
72811
- await pending.delegation;
72812
- };
72813
- initialize = async (signal) => {
72814
- queuePageSchema.parse(
72815
- await this.#client.request(
72816
- "thread/queue/list",
72817
- { threadId: this.#threadId },
72818
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72819
- )
72820
- );
72821
- await this.#apply(await this.#read(signal, true), true);
72822
- this.#watch = this.#follow();
72823
- };
72824
- #follow = async () => {
72825
- const signal = this.#closed.signal;
72826
- let unansweredReads = 0;
72827
- try {
72828
- for (; ; ) {
72829
- await waitForNextPoll(systemTimer, signal);
72830
- let pages;
72831
- try {
72832
- pages = await this.#read(signal, false);
72833
- } catch (cause) {
72834
- unansweredReads += 1;
72835
- if (!(cause instanceof DOMException && cause.name === "TimeoutError") || unansweredReads === UNANSWERED_READ_LIMIT) {
72836
- throw cause;
72837
- }
72838
- console.warn("Codex thread history read timed out; following continues", {
72839
- threadId: this.#threadId
72840
- });
72841
- continue;
72842
- }
72843
- unansweredReads = 0;
72844
- await this.#apply(pages, false);
72812
+ return "cancel";
72813
+ }
72814
+ function steeringPrompt(prompt) {
72815
+ const blocks = [];
72816
+ for (const block of prompt) {
72817
+ if (typeof block !== "object" || block === null) {
72818
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72819
+ }
72820
+ const type = Reflect.get(block, "type");
72821
+ if (type === "text") {
72822
+ const text2 = Reflect.get(block, "text");
72823
+ if (typeof text2 !== "string") {
72824
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72845
72825
  }
72846
- } catch (cause) {
72847
- if (!signal.aborted) {
72848
- const error62 = new AcpExecutionError(
72849
- "The owning Codex session could not be followed",
72850
- { cause },
72851
- "codex_queue_follow_failed"
72852
- );
72853
- this.#lifecycle = { kind: "failed", error: error62 };
72854
- this.#pending?.completion.reject(error62);
72826
+ blocks.push({ content: { text: text2, type: "text" }, input: { text: text2, text_elements: [], type: "text" } });
72827
+ continue;
72828
+ }
72829
+ if (type === "image") {
72830
+ const data = Reflect.get(block, "data");
72831
+ const mimeType = Reflect.get(block, "mimeType");
72832
+ if (typeof data !== "string" || typeof mimeType !== "string") {
72833
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72855
72834
  }
72835
+ blocks.push({
72836
+ content: { data, mimeType, type: "image" },
72837
+ input: { type: "image", url: `data:${mimeType};base64,${data}` }
72838
+ });
72839
+ continue;
72856
72840
  }
72857
- };
72858
- #read = async (signal, baseline) => {
72859
- let cursor = null;
72860
- const pages = [];
72861
- const cursors = /* @__PURE__ */ new Set();
72862
- do {
72863
- const page = threadTurnsPageSchema.parse(
72864
- await this.#client.request(
72865
- "thread/turns/list",
72866
- {
72867
- threadId: this.#threadId,
72868
- limit: CODEX_HISTORY_TURN_PAGE_LIMIT,
72869
- sortDirection: "desc",
72870
- itemsView: "full",
72871
- ...cursor === null ? {} : { cursor }
72872
- },
72873
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72874
- )
72875
- );
72876
- pages.push(page.data);
72877
- cursor = page.nextCursor ?? null;
72878
- if (cursor !== null && cursors.has(cursor)) {
72879
- throw new AcpExecutionError("Codex repeated a history cursor", {}, "invalid_native_session_response");
72841
+ if (type === "resource") {
72842
+ const resource = Reflect.get(block, "resource");
72843
+ if (typeof resource !== "object" || resource === null) {
72844
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72880
72845
  }
72881
- if (cursor !== null) {
72882
- cursors.add(cursor);
72846
+ const uri = Reflect.get(resource, "uri");
72847
+ const text2 = Reflect.get(resource, "text");
72848
+ const blob2 = Reflect.get(resource, "blob");
72849
+ const mimeType = Reflect.get(resource, "mimeType");
72850
+ if (typeof uri !== "string" || typeof text2 !== "string" && typeof blob2 !== "string" || text2 !== void 0 && typeof text2 !== "string" || blob2 !== void 0 && typeof blob2 !== "string" || mimeType !== void 0 && typeof mimeType !== "string") {
72851
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72883
72852
  }
72884
- } while (cursor !== null && (baseline || this.#pending !== null));
72885
- return pages;
72853
+ blocks.push({
72854
+ content: typeof text2 === "string" ? {
72855
+ resource: { text: text2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
72856
+ type: "resource"
72857
+ } : {
72858
+ resource: { blob: blob2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
72859
+ type: "resource"
72860
+ },
72861
+ input: { text: text2 ?? "", text_elements: [], type: "text" }
72862
+ });
72863
+ continue;
72864
+ }
72865
+ if (type === "resource_link") {
72866
+ const name2 = Reflect.get(block, "name");
72867
+ const uri = Reflect.get(block, "uri");
72868
+ if (typeof name2 !== "string" || typeof uri !== "string") {
72869
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
72870
+ }
72871
+ blocks.push({
72872
+ content: { name: name2, type: "resource_link", uri },
72873
+ input: { text: `Resource: ${uri}`, text_elements: [], type: "text" }
72874
+ });
72875
+ continue;
72876
+ }
72877
+ throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
72878
+ }
72879
+ return blocks;
72880
+ }
72881
+ function agentMessageUpdate(messageId, text2, questions = []) {
72882
+ return {
72883
+ content: { text: text2, type: "text" },
72884
+ messageId,
72885
+ sessionUpdate: "agent_message_chunk",
72886
+ ...questions.length === 0 ? {} : { _meta: { "mobius.questions": questions } }
72886
72887
  };
72887
- #apply = async (pages, baseline) => {
72888
- for (const turns of [...pages].reverse()) {
72889
- for (const turn of [...turns].reverse()) {
72890
- let matches = false;
72891
- for (const raw of turn.items) {
72892
- const item = decodeThreadItem(raw);
72893
- if (item === null) {
72894
- continue;
72895
- }
72896
- const key = `${turn.id ?? ""}:${item.id}`;
72897
- if (item.type === "userMessage") {
72898
- const clientId = typeof raw === "object" && raw !== null ? Reflect.get(raw, "clientId") : void 0;
72899
- matches ||= clientId === this.#pending?.clientId;
72900
- if (this.#pending !== null && clientId === this.#pending.clientId) {
72901
- const started = this.#pending.input.kind === "awaiting";
72902
- this.#pending.input = { kind: "identified", messageId: item.id };
72903
- if (started) {
72904
- await this.#reportDelegation(this.#pending, "started");
72905
- }
72906
- }
72907
- const text2 = item.content.flatMap(
72908
- (block) => typeof block === "object" && block !== null && Reflect.get(block, "type") === "text" && typeof Reflect.get(block, "text") === "string" ? [String(Reflect.get(block, "text"))] : []
72909
- ).join("");
72910
- if (!baseline && !this.#seen.has(key)) {
72911
- for (const update of userMessageUpdates(
72912
- item,
72913
- this.#pending !== null && clientId === this.#pending.clientId ? this.#pending.content : void 0
72914
- )) {
72915
- await this.#emit(update);
72916
- }
72917
- }
72918
- this.#seen.set(key, text2);
72919
- continue;
72920
- }
72921
- if (item.type === "plan" && turnRunning(turn)) {
72922
- continue;
72923
- }
72924
- const previous = this.#seen.get(key);
72925
- const value = item.type === "agentMessage" || item.type === "plan" ? item.text : reasoningText(item) ?? JSON.stringify(item);
72926
- this.#seen.set(key, value);
72927
- if (baseline || value === previous) {
72928
- continue;
72929
- }
72930
- if (item.type === "agentMessage" || item.type === "plan" || reasoningText(item) !== null) {
72931
- const text2 = previous !== void 0 && value.startsWith(previous) ? value.slice(previous.length) : value;
72932
- if (text2.length > 0) {
72933
- await this.#emit({
72934
- sessionUpdate: item.type === "reasoning" ? "agent_thought_chunk" : "agent_message_chunk",
72935
- messageId: item.id,
72936
- content: { type: "text", text: text2 }
72937
- });
72938
- }
72939
- } else {
72940
- const update = toolCallUpdate(item, "snapshot");
72941
- if (update !== null) {
72942
- if (previous === void 0) {
72943
- await this.#emit({ ...update, sessionUpdate: "tool_call" });
72944
- } else {
72945
- await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
72946
- }
72947
- }
72948
- }
72949
- }
72950
- if (matches && turn.status !== void 0 && !turnRunning(turn)) {
72951
- if (turn.status === "failed") {
72952
- this.#pending?.completion.reject(
72953
- new AcpExecutionError("The owning Codex turn failed", {}, "codex_turn_failed")
72954
- );
72955
- } else {
72956
- this.#pending?.completion.resolve({
72957
- stopReason: turn.status === "interrupted" ? "cancelled" : "end_turn"
72958
- });
72959
- }
72960
- }
72888
+ }
72889
+ function userInputSchema(questions) {
72890
+ const properties = {};
72891
+ const required2 = [];
72892
+ for (const question of questions) {
72893
+ required2.push(question.id);
72894
+ properties[question.id] = {
72895
+ description: question.question,
72896
+ title: question.header,
72897
+ type: "string",
72898
+ ...question.options == null || question.options.length === 0 ? {} : {
72899
+ oneOf: question.options.map((option) => ({
72900
+ const: option.label,
72901
+ description: option.description,
72902
+ title: option.label
72903
+ }))
72961
72904
  }
72905
+ };
72906
+ }
72907
+ return { properties, required: required2, type: "object" };
72908
+ }
72909
+ var CodexOwnedAcpAgent = class {
72910
+ steeringSupported = true;
72911
+ runsTurns = true;
72912
+ #context;
72913
+ #appServer;
72914
+ #settings;
72915
+ #streamedReasoningSources = /* @__PURE__ */ new Map();
72916
+ #agentMessages = /* @__PURE__ */ new Map();
72917
+ #turn = null;
72918
+ #nativeTurnId = null;
72919
+ #runningCommands = /* @__PURE__ */ new Map();
72920
+ #updateTail = Promise.resolve();
72921
+ // The compaction whose contextCompaction item/started has been reported but whose
72922
+ // terminal state has not. Exactly one may be open: Codex compacts sequentially,
72923
+ // and a second start cannot begin before the first settles. Cleared only through
72924
+ // #finishCompaction, which emits the terminal update — turn failure,
72925
+ // interruption, and endpoint loss all settle it so no client is left with a
72926
+ // compaction stuck in_progress.
72927
+ #openCompaction = null;
72928
+ // Set when the turn machinery (turn/completed or cancel) settled this turn's
72929
+ // compaction, so the compact error path does not report a second terminal
72930
+ // update for the same failure.
72931
+ #turnSettledCompaction = false;
72932
+ constructor(context) {
72933
+ this.#context = context;
72934
+ this.#appServer = context.client;
72935
+ this.#settings = context.settings;
72936
+ }
72937
+ nativeTurnId = () => this.#nativeTurnId;
72938
+ onTerminated = (termination) => {
72939
+ if (this.#turn !== null) {
72940
+ this.#turn.steeringContent.clear();
72962
72941
  }
72942
+ this.#turn?.completion.reject(acpEndpointTerminationError(termination));
72943
+ this.#settleCompaction("cancelled");
72963
72944
  };
72964
- prompt = async (input2, signal, content) => {
72965
- signal.throwIfAborted();
72966
- if (this.#lifecycle.kind === "failed") {
72967
- throw this.#lifecycle.error;
72945
+ close = async () => {
72946
+ if (this.#turn !== null) {
72947
+ this.#turn.steeringContent.clear();
72968
72948
  }
72969
- if (this.#lifecycle.kind === "closed") {
72970
- throw new AcpExecutionError("The Codex queue connection is closed", {}, "acp_endpoint_closed");
72949
+ this.#turn?.completion.reject(new AcpExecutionError("The Codex endpoint is closed", {}, "acp_endpoint_closed"));
72950
+ this.#settleCompaction("cancelled");
72951
+ };
72952
+ /** Emits the terminal compaction update for the open compaction, if any, and
72953
+ * wakes a manual /compact waiting on it. A terminal update may patch an
72954
+ * already-terminal entity (the app-server can race an item/completed past a
72955
+ * cancellation), which clients merge idempotently. The wake rides the enqueued
72956
+ * emission so the waiting prompt's response never precedes the update. */
72957
+ #settleCompaction = (status, error62) => {
72958
+ const open6 = this.#openCompaction;
72959
+ if (open6 === null) {
72960
+ return null;
72971
72961
  }
72972
- if (this.#pending !== null) {
72973
- throw new AcpExecutionError("Another prompt is already running", {}, "session_busy");
72962
+ const update = {
72963
+ compactionId: open6.compactionId,
72964
+ ...status === "failed" && error62 !== void 0 ? { error: error62 } : {},
72965
+ sessionUpdate: "compaction_update",
72966
+ status
72967
+ };
72968
+ this.#finishCompaction(async () => {
72969
+ await this.#context.emit(update);
72970
+ });
72971
+ return open6;
72972
+ };
72973
+ /** Clears the tracked compaction and emits the terminal update. Used by both
72974
+ * #settleCompaction and the item/completed handler, which emits its own
72975
+ * terminal update. */
72976
+ #finishCompaction = (emit) => {
72977
+ this.#openCompaction = null;
72978
+ void this.#enqueue(emit).catch((cause) => {
72979
+ console.error("The Codex compaction settlement could not be delivered", cause);
72980
+ });
72981
+ };
72982
+ /** Manual /compact: drives thread/compact/start, which the app-server executes
72983
+ * as its own turn. The turn is registered like a prompt's so every terminal
72984
+ * path is owned: turn/completed(failed) settles the open compaction as failed
72985
+ * and rejects, turn/completed(interrupted) and Stop settle it as cancelled,
72986
+ * and endpoint loss settles it through onTerminated. The contextCompaction
72987
+ * item the server streams is the lifecycle clients see — started/completed
72988
+ * under the item's id — and its completed resolves the wait. A bounded wait
72989
+ * guards servers that accept the compact but never report a result; expiry is
72990
+ * a failure, never a success. */
72991
+ compact = async (signal) => {
72992
+ signal.throwIfAborted();
72993
+ if (this.#turn !== null) {
72994
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
72974
72995
  }
72975
- const pending = {
72976
- content,
72996
+ if (this.#openCompaction !== null) {
72997
+ throw new AcpExecutionError(
72998
+ "Another compaction is already running in this conversation",
72999
+ {},
73000
+ "session_busy"
73001
+ );
73002
+ }
73003
+ const completion = Promise.withResolvers();
73004
+ void completion.promise.catch(() => {
73005
+ });
73006
+ const aborted2 = () => {
73007
+ completion.reject(signal.reason);
73008
+ };
73009
+ signal.addEventListener("abort", aborted2, { once: true });
73010
+ const waitExpired = new AbortController();
73011
+ const turn = {
73012
+ completion,
73013
+ content: [],
73014
+ steeringContent: /* @__PURE__ */ new Map(),
72977
73015
  clientId: randomUUID7(),
72978
- completion: Promise.withResolvers(),
72979
- settled: Promise.withResolvers(),
72980
73016
  input: { kind: "awaiting" },
72981
- delegation: Promise.resolve()
73017
+ turn: { id: "" }
72982
73018
  };
72983
- this.#pending = pending;
72984
- void pending.completion.promise.catch(() => {
72985
- });
72986
- const abort = () => pending.completion.reject(signal.reason);
72987
- signal.addEventListener("abort", abort, { once: true });
72988
- let outcome = "cancelled";
73019
+ this.#turn = turn;
72989
73020
  try {
72990
- const queued = queueResponseSchema.parse(
72991
- await this.#client.request(
72992
- "thread/queue/add",
72993
- {
72994
- threadId: this.#threadId,
72995
- input: input2,
72996
- clientUserMessageId: pending.clientId
72997
- },
72998
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72999
- )
73021
+ await this.#appServer.request(
73022
+ "thread/compact/start",
73023
+ { threadId: this.#context.threadId() },
73024
+ AbortSignal.any([signal, AbortSignal.timeout(COMPACT_TIMEOUT_MILLISECONDS)])
73000
73025
  );
73001
- if (queued.queuedSubmission.clientUserMessageId !== pending.clientId) {
73002
- throw new AcpExecutionError(
73003
- "Codex queued an unexpected message",
73004
- {},
73005
- "invalid_native_session_response"
73006
- );
73007
- }
73008
- await this.#reportDelegation(pending, "queued");
73009
- const result = await pending.completion.promise;
73010
- outcome = result.stopReason === "cancelled" ? "cancelled" : "completed";
73011
- return pending.input.kind === "identified" ? await promptResultWithMessageId2(Promise.resolve(result), pending.input.messageId) : result;
73026
+ return await Promise.race([
73027
+ completion.promise,
73028
+ delay(COMPACT_ITEM_WAIT_MILLISECONDS, void 0, { signal: waitExpired.signal }).then(() => {
73029
+ throw new AcpExecutionError(
73030
+ "The Codex compaction did not report a result",
73031
+ {},
73032
+ "codex_compaction_unreported"
73033
+ );
73034
+ })
73035
+ ]);
73012
73036
  } catch (cause) {
73013
- if (pending.input.kind === "identified" && !signal.aborted) {
73014
- return await promptResultWithMessageId2(Promise.reject(cause), pending.input.messageId);
73037
+ signal.throwIfAborted();
73038
+ const open6 = this.#settleCompaction("failed", cause instanceof Error ? cause.message : String(cause));
73039
+ if (open6 === null && !this.#turnSettledCompaction) {
73040
+ const compactionId = randomUUID7();
73041
+ await this.#enqueue(async () => {
73042
+ await this.#context.emit({
73043
+ compactionId,
73044
+ error: cause instanceof Error ? cause.message : String(cause),
73045
+ sessionUpdate: "compaction_update",
73046
+ status: "failed"
73047
+ });
73048
+ });
73015
73049
  }
73050
+ this.#turnSettledCompaction = false;
73016
73051
  throw cause;
73017
73052
  } finally {
73018
- signal.removeEventListener("abort", abort);
73019
- if (outcome === "cancelled") {
73020
- try {
73021
- await this.#removeQueuedInput(pending.clientId);
73022
- } catch (cause) {
73023
- console.error("The cancelled Codex queued input could not be removed", cause);
73024
- }
73025
- }
73026
- this.#pending = null;
73027
- pending.settled.resolve();
73028
- }
73029
- };
73030
- /** Withdraws this client's submission while the owner has not taken it; false once the owner has. */
73031
- #removeQueuedInput = async (clientId) => {
73032
- const signal = AbortSignal.timeout(REQUEST_TIMEOUT);
73033
- let cursor = null;
73034
- const cursors = /* @__PURE__ */ new Set();
73035
- do {
73036
- const page = queuePageSchema.parse(
73037
- await this.#client.request(
73038
- "thread/queue/list",
73039
- { threadId: this.#threadId, limit: 100, ...cursor === null ? {} : { cursor } },
73040
- signal
73041
- )
73042
- );
73043
- for (const queued of page.data) {
73044
- if (queued.clientUserMessageId === clientId) {
73045
- await this.#client.request(
73046
- "thread/queue/delete",
73047
- { threadId: this.#threadId, queuedSubmissionId: queued.id },
73048
- signal
73049
- );
73050
- return true;
73051
- }
73052
- }
73053
- cursor = page.nextCursor ?? null;
73054
- if (cursor !== null && cursors.has(cursor)) {
73055
- throw new AcpExecutionError("Codex repeated a queue cursor", {}, "invalid_native_session_response");
73056
- }
73057
- if (cursor !== null) {
73058
- cursors.add(cursor);
73059
- }
73060
- } while (cursor !== null);
73061
- return false;
73062
- };
73063
- nativeTurnId = () => null;
73064
- steer = async (_params, signal) => {
73065
- signal.throwIfAborted();
73066
- throw new AcpExecutionError("This Codex session only supports queued input", {}, "steering_unsupported");
73067
- };
73068
- // The reader connection cannot receive or control the owner's live turn.
73069
- onNotification = async (_method, _params) => {
73070
- };
73071
- onServerRequest = async (request) => {
73072
- this.#client.respondWithError(request.id, -32601, "Borrowed sessions cannot handle owner requests");
73073
- };
73074
- onTerminated = (termination) => {
73075
- const error62 = acpEndpointTerminationError(termination);
73076
- this.#lifecycle = { kind: "failed", error: error62 };
73077
- this.#pending?.completion.reject(error62);
73078
- this.#closed.abort();
73079
- };
73080
- // A remote Stop must never interrupt another client's owning turn.
73081
- compact = async (_signal) => {
73082
- throw new AcpExecutionError(
73083
- "This Codex session is attached read-only and cannot be compacted",
73084
- {},
73085
- "native_session_unsupported"
73086
- );
73087
- };
73088
- /**
73089
- * Withdraws the prompt while it waits in the owner's queue. Once the owner runs it, only the owner can stop it,
73090
- * so the prompt keeps running and following reports how the owner ends it.
73091
- */
73092
- cancel = async () => {
73093
- const pending = this.#pending;
73094
- if (pending === null || pending.input.kind === "identified") {
73095
- return;
73096
- }
73097
- if (await this.#removeQueuedInput(pending.clientId)) {
73098
- pending.completion.resolve({ stopReason: "cancelled" });
73099
- await pending.settled.promise;
73100
- }
73101
- };
73102
- close = async () => {
73103
- this.#lifecycle = { kind: "closed" };
73104
- this.#closed.abort();
73105
- const pending = this.#pending;
73106
- if (pending !== null) {
73107
- pending.completion.resolve({ stopReason: "cancelled" });
73108
- await pending.settled.promise;
73109
- }
73110
- await this.#watch;
73111
- };
73112
- };
73113
-
73114
- // src/engine/acp/harness/codex/history.ts
73115
- import { createHash as createHash2 } from "node:crypto";
73116
-
73117
- // src/engine/acp/content/raster.ts
73118
- import { basename as basename4, isAbsolute as isAbsolute9, normalize } from "node:path";
73119
- import { fileURLToPath } from "node:url";
73120
- var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
73121
- var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
73122
- var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
73123
- var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
73124
- var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
73125
- var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
73126
- var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
73127
- var LocalRasterImage = class {
73128
- mimeType;
73129
- name;
73130
- sourceUri;
73131
- constructor(name2, mimeType, sourceUri) {
73132
- this.mimeType = mimeType;
73133
- this.name = name2;
73134
- this.sourceUri = sourceUri;
73135
- }
73136
- base64 = async () => Buffer.from(await readFileBytes(this.sourceUri)).toString("base64");
73137
- };
73138
- function startsWith(bytes, signature, offset = 0) {
73139
- if (bytes.byteLength < offset + signature.byteLength) {
73140
- return false;
73141
- }
73142
- return signature.every((value, index2) => bytes[offset + index2] === value);
73143
- }
73144
- function sniffRasterMime(bytes) {
73145
- if (startsWith(bytes, PNG_SIGNATURE)) {
73146
- return "image/png";
73147
- }
73148
- if (startsWith(bytes, JPEG_SIGNATURE)) {
73149
- return "image/jpeg";
73150
- }
73151
- if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
73152
- return "image/gif";
73153
- }
73154
- if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
73155
- return "image/webp";
73156
- }
73157
- return null;
73158
- }
73159
- async function resolveCanonicalPath(requested, signal) {
73160
- signal.throwIfAborted();
73161
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize(requested) !== requested) {
73162
- return null;
73163
- }
73164
- try {
73165
- const target = await canonicalPath(requested);
73166
- signal.throwIfAborted();
73167
- if (!isAbsolute9(target) || normalize(target) !== target) {
73168
- return null;
73169
- }
73170
- return target;
73171
- } catch (cause) {
73172
- signal.throwIfAborted();
73173
- if (cause instanceof Error && cause.name === "AbortError") {
73174
- throw cause;
73175
- }
73176
- return null;
73177
- }
73178
- }
73179
- function parseLocalImageUri(uri) {
73180
- const trimmed = uri.trim();
73181
- if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
73182
- return null;
73183
- }
73184
- if (trimmed.startsWith("data:")) {
73185
- return null;
73186
- }
73187
- if (trimmed.startsWith("file:")) {
73188
- try {
73189
- const url2 = new URL(trimmed);
73190
- if (url2.protocol !== "file:" || url2.host.length > 0) {
73191
- return null;
73192
- }
73193
- return fileURLToPath(url2);
73194
- } catch {
73195
- return null;
73196
- }
73197
- }
73198
- if (!isAbsolute9(trimmed) && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
73199
- return null;
73200
- }
73201
- return trimmed;
73202
- }
73203
- async function readLocalRaster(uri, signal) {
73204
- signal.throwIfAborted();
73205
- const requested = parseLocalImageUri(uri);
73206
- if (requested === null) {
73207
- return null;
73208
- }
73209
- const target = await resolveCanonicalPath(requested, signal);
73210
- if (target === null) {
73211
- return null;
73212
- }
73213
- const targetMetadata = await readPathMetadata(target);
73214
- signal.throwIfAborted();
73215
- if (targetMetadata.kind !== "file" || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
73216
- return null;
73217
- }
73218
- const header = await readFileStart(target, 12);
73219
- signal.throwIfAborted();
73220
- const mimeType = sniffRasterMime(header);
73221
- if (mimeType === null) {
73222
- return null;
73223
- }
73224
- return new LocalRasterImage(basename4(target) || "Image", mimeType, target);
73225
- }
73226
-
73227
- // src/engine/acp/native-history/codex/history-images.ts
73228
- var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
73229
- var DATA_IMAGE_HEADER = /^data:(image\/[a-z+]+);base64,/;
73230
- var BASE_64 = /^[A-Za-z0-9+/]*={0,2}$/;
73231
- var SESSION_HISTORY_IMAGE_CHARACTER_LIMIT = 4e6;
73232
- function isRasterMime(value) {
73233
- return value === "image/png" || value === "image/jpeg" || value === "image/gif" || value === "image/webp";
73234
- }
73235
- function parseNativeHistoryImage(uri) {
73236
- const header = DATA_IMAGE_HEADER.exec(uri);
73237
- if (header === null) {
73238
- return null;
73239
- }
73240
- const mimeType = header[1] ?? "";
73241
- const data = uri.slice(header[0].length);
73242
- if (!isRasterMime(mimeType) || data.length < 4 || data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73243
- return null;
73244
- }
73245
- if (data.length % 4 !== 0 || !BASE_64.test(data)) {
73246
- return null;
73247
- }
73248
- return { data, mimeType, name: "" };
73249
- }
73250
- async function embedLocalHistoryImages(history, signal) {
73251
- if (history.status !== "available") {
73252
- return history;
73253
- }
73254
- const messages = [];
73255
- let imageCharacters = 0;
73256
- for (const message of history.messages) {
73257
- signal.throwIfAborted();
73258
- const resolved = await resolveMessageImages(message, imageCharacters, signal);
73259
- imageCharacters += (resolved.images ?? []).reduce((size, image) => size + image.data.length, 0);
73260
- messages.push(resolved);
73261
- }
73262
- return {
73263
- ...history,
73264
- messages
73265
- };
73266
- }
73267
- async function resolveMessageImages(message, usedCharacters, signal) {
73268
- const images = [...message.images ?? []];
73269
- let imageCharacters = images.reduce((size, image) => size + image.data.length, 0);
73270
- const text2 = await replaceImageMarkers(message.text, async (uri) => {
73271
- if (images.length >= 8 || usedCharacters + imageCharacters >= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73272
- return "[Image unavailable]";
73273
- }
73274
- const embedded = parseNativeHistoryImage(uri);
73275
- if (embedded !== null) {
73276
- if (usedCharacters + imageCharacters + embedded.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73277
- return "[Image unavailable]";
73278
- }
73279
- images.push({ ...embedded, name: `Image ${(images.length + 1).toString()}` });
73280
- imageCharacters += embedded.data.length;
73281
- return "";
73282
- }
73283
- const local = await readLocalRaster(uri, signal);
73284
- if (local === null) {
73285
- return "[Image unavailable]";
73286
- }
73287
- const data = await local.base64();
73288
- if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73289
- return "[Image unavailable]";
73290
- }
73291
- images.push({
73292
- data,
73293
- mimeType: local.mimeType,
73294
- name: local.name
73295
- });
73296
- imageCharacters += data.length;
73297
- return "";
73298
- });
73299
- return {
73300
- ...message,
73301
- text: text2,
73302
- ...images.length > 0 ? { images } : {}
73303
- };
73304
- }
73305
- async function replaceImageMarkers(text2, replace) {
73306
- const matches = [...text2.matchAll(IMAGE_MARKER)];
73307
- if (matches.length === 0) {
73308
- return text2;
73309
- }
73310
- let cursor = 0;
73311
- let rewritten = "";
73312
- for (const match of matches) {
73313
- const index2 = match.index ?? 0;
73314
- rewritten += text2.slice(cursor, index2);
73315
- rewritten += await replace(match[1] ?? "");
73316
- cursor = index2 + match[0].length;
73317
- }
73318
- return `${rewritten}${text2.slice(cursor)}`;
73319
- }
73320
-
73321
- // src/engine/acp/harness/codex/owned-agent.ts
73322
- import { randomUUID as randomUUID8 } from "node:crypto";
73323
- import { setTimeout as delay } from "node:timers/promises";
73324
- var APPROVAL_REASON_CHARACTER_LIMIT = 500;
73325
- var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
73326
- var COMPACT_TIMEOUT_MILLISECONDS = 36e5;
73327
- var COMPACT_ITEM_WAIT_MILLISECONDS = 6e5;
73328
- var THREAD_NOTIFICATIONS = /* @__PURE__ */ new Set([
73329
- "item/agentMessage/delta",
73330
- "item/completed",
73331
- "item/reasoning/summaryTextDelta",
73332
- "item/reasoning/textDelta",
73333
- "item/started",
73334
- "thread/compacted",
73335
- "thread/name/updated",
73336
- "thread/settings/updated",
73337
- "turn/completed",
73338
- "turn/plan/updated",
73339
- "turn/started"
73340
- ]);
73341
- var APPROVAL_OPTIONS = Object.freeze([
73342
- { kind: "allow_once", name: "Allow once", optionId: "accept" },
73343
- { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
73344
- { kind: "reject_once", name: "Deny", optionId: "decline" }
73345
- ]);
73346
- function permissionDecision(optionId) {
73347
- if (optionId === "accept" || optionId === "acceptForSession" || optionId === "decline") {
73348
- return optionId;
73349
- }
73350
- return "cancel";
73351
- }
73352
- function steeringPrompt(prompt) {
73353
- const blocks = [];
73354
- for (const block of prompt) {
73355
- if (typeof block !== "object" || block === null) {
73356
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73357
- }
73358
- const type = Reflect.get(block, "type");
73359
- if (type === "text") {
73360
- const text2 = Reflect.get(block, "text");
73361
- if (typeof text2 !== "string") {
73362
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73363
- }
73364
- blocks.push({ content: { text: text2, type: "text" }, input: { text: text2, text_elements: [], type: "text" } });
73365
- continue;
73366
- }
73367
- if (type === "image") {
73368
- const data = Reflect.get(block, "data");
73369
- const mimeType = Reflect.get(block, "mimeType");
73370
- if (typeof data !== "string" || typeof mimeType !== "string") {
73371
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73372
- }
73373
- blocks.push({
73374
- content: { data, mimeType, type: "image" },
73375
- input: { type: "image", url: `data:${mimeType};base64,${data}` }
73376
- });
73377
- continue;
73378
- }
73379
- if (type === "resource") {
73380
- const resource = Reflect.get(block, "resource");
73381
- if (typeof resource !== "object" || resource === null) {
73382
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73383
- }
73384
- const uri = Reflect.get(resource, "uri");
73385
- const text2 = Reflect.get(resource, "text");
73386
- const blob2 = Reflect.get(resource, "blob");
73387
- const mimeType = Reflect.get(resource, "mimeType");
73388
- if (typeof uri !== "string" || typeof text2 !== "string" && typeof blob2 !== "string" || text2 !== void 0 && typeof text2 !== "string" || blob2 !== void 0 && typeof blob2 !== "string" || mimeType !== void 0 && typeof mimeType !== "string") {
73389
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73390
- }
73391
- blocks.push({
73392
- content: typeof text2 === "string" ? {
73393
- resource: { text: text2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
73394
- type: "resource"
73395
- } : {
73396
- resource: { blob: blob2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
73397
- type: "resource"
73398
- },
73399
- input: { text: text2 ?? "", text_elements: [], type: "text" }
73400
- });
73401
- continue;
73402
- }
73403
- if (type === "resource_link") {
73404
- const name2 = Reflect.get(block, "name");
73405
- const uri = Reflect.get(block, "uri");
73406
- if (typeof name2 !== "string" || typeof uri !== "string") {
73407
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73408
- }
73409
- blocks.push({
73410
- content: { name: name2, type: "resource_link", uri },
73411
- input: { text: `Resource: ${uri}`, text_elements: [], type: "text" }
73412
- });
73413
- continue;
73414
- }
73415
- throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
73416
- }
73417
- return blocks;
73418
- }
73419
- function agentMessageUpdate(messageId, text2) {
73420
- return {
73421
- content: { text: text2, type: "text" },
73422
- messageId,
73423
- sessionUpdate: "agent_message_chunk"
73424
- };
73425
- }
73426
- function userInputSchema(questions) {
73427
- const properties = {};
73428
- const required2 = [];
73429
- for (const question of questions) {
73430
- required2.push(question.id);
73431
- properties[question.id] = {
73432
- description: question.question,
73433
- title: question.header,
73434
- type: "string",
73435
- ...question.options == null || question.options.length === 0 ? {} : {
73436
- oneOf: question.options.map((option) => ({
73437
- const: option.label,
73438
- description: option.description,
73439
- title: option.label
73440
- }))
73441
- }
73442
- };
73443
- }
73444
- return { properties, required: required2, type: "object" };
73445
- }
73446
- var CodexOwnedAcpAgent = class {
73447
- steeringSupported = true;
73448
- runsTurns = true;
73449
- #context;
73450
- #appServer;
73451
- #settings;
73452
- #streamedReasoningSources = /* @__PURE__ */ new Map();
73453
- #agentMessages = /* @__PURE__ */ new Map();
73454
- #turn = null;
73455
- #nativeTurnId = null;
73456
- #runningCommands = /* @__PURE__ */ new Map();
73457
- #updateTail = Promise.resolve();
73458
- // The compaction whose contextCompaction item/started has been reported but whose
73459
- // terminal state has not. Exactly one may be open: Codex compacts sequentially,
73460
- // and a second start cannot begin before the first settles. Cleared only through
73461
- // #finishCompaction, which emits the terminal update — turn failure,
73462
- // interruption, and endpoint loss all settle it so no client is left with a
73463
- // compaction stuck in_progress.
73464
- #openCompaction = null;
73465
- // Set when the turn machinery (turn/completed or cancel) settled this turn's
73466
- // compaction, so the compact error path does not report a second terminal
73467
- // update for the same failure.
73468
- #turnSettledCompaction = false;
73469
- constructor(context) {
73470
- this.#context = context;
73471
- this.#appServer = context.client;
73472
- this.#settings = context.settings;
73473
- }
73474
- nativeTurnId = () => this.#nativeTurnId;
73475
- onTerminated = (termination) => {
73476
- if (this.#turn !== null) {
73477
- this.#turn.steeringContent.clear();
73478
- }
73479
- this.#turn?.completion.reject(acpEndpointTerminationError(termination));
73480
- this.#settleCompaction("cancelled");
73481
- };
73482
- close = async () => {
73483
- if (this.#turn !== null) {
73484
- this.#turn.steeringContent.clear();
73485
- }
73486
- this.#turn?.completion.reject(new AcpExecutionError("The Codex endpoint is closed", {}, "acp_endpoint_closed"));
73487
- this.#settleCompaction("cancelled");
73488
- };
73489
- /** Emits the terminal compaction update for the open compaction, if any, and
73490
- * wakes a manual /compact waiting on it. A terminal update may patch an
73491
- * already-terminal entity (the app-server can race an item/completed past a
73492
- * cancellation), which clients merge idempotently. The wake rides the enqueued
73493
- * emission so the waiting prompt's response never precedes the update. */
73494
- #settleCompaction = (status, error62) => {
73495
- const open6 = this.#openCompaction;
73496
- if (open6 === null) {
73497
- return null;
73498
- }
73499
- const update = {
73500
- compactionId: open6.compactionId,
73501
- ...status === "failed" && error62 !== void 0 ? { error: error62 } : {},
73502
- sessionUpdate: "compaction_update",
73503
- status
73504
- };
73505
- this.#finishCompaction(async () => {
73506
- await this.#context.emit(update);
73507
- });
73508
- return open6;
73509
- };
73510
- /** Clears the tracked compaction and emits the terminal update. Used by both
73511
- * #settleCompaction and the item/completed handler, which emits its own
73512
- * terminal update. */
73513
- #finishCompaction = (emit) => {
73514
- this.#openCompaction = null;
73515
- void this.#enqueue(emit).catch((cause) => {
73516
- console.error("The Codex compaction settlement could not be delivered", cause);
73517
- });
73518
- };
73519
- /** Manual /compact: drives thread/compact/start, which the app-server executes
73520
- * as its own turn. The turn is registered like a prompt's so every terminal
73521
- * path is owned: turn/completed(failed) settles the open compaction as failed
73522
- * and rejects, turn/completed(interrupted) and Stop settle it as cancelled,
73523
- * and endpoint loss settles it through onTerminated. The contextCompaction
73524
- * item the server streams is the lifecycle clients see — started/completed
73525
- * under the item's id — and its completed resolves the wait. A bounded wait
73526
- * guards servers that accept the compact but never report a result; expiry is
73527
- * a failure, never a success. */
73528
- compact = async (signal) => {
73529
- signal.throwIfAborted();
73530
- if (this.#turn !== null) {
73531
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
73532
- }
73533
- if (this.#openCompaction !== null) {
73534
- throw new AcpExecutionError(
73535
- "Another compaction is already running in this conversation",
73536
- {},
73537
- "session_busy"
73538
- );
73539
- }
73540
- const completion = Promise.withResolvers();
73541
- void completion.promise.catch(() => {
73542
- });
73543
- const aborted2 = () => {
73544
- completion.reject(signal.reason);
73545
- };
73546
- signal.addEventListener("abort", aborted2, { once: true });
73547
- const waitExpired = new AbortController();
73548
- const turn = {
73549
- completion,
73550
- content: [],
73551
- steeringContent: /* @__PURE__ */ new Map(),
73552
- clientId: randomUUID8(),
73553
- input: { kind: "awaiting" },
73554
- turn: { id: "" }
73555
- };
73556
- this.#turn = turn;
73557
- try {
73558
- await this.#appServer.request(
73559
- "thread/compact/start",
73560
- { threadId: this.#context.threadId() },
73561
- AbortSignal.any([signal, AbortSignal.timeout(COMPACT_TIMEOUT_MILLISECONDS)])
73562
- );
73563
- return await Promise.race([
73564
- completion.promise,
73565
- delay(COMPACT_ITEM_WAIT_MILLISECONDS, void 0, { signal: waitExpired.signal }).then(() => {
73566
- throw new AcpExecutionError(
73567
- "The Codex compaction did not report a result",
73568
- {},
73569
- "codex_compaction_unreported"
73570
- );
73571
- })
73572
- ]);
73573
- } catch (cause) {
73574
- signal.throwIfAborted();
73575
- const open6 = this.#settleCompaction("failed", cause instanceof Error ? cause.message : String(cause));
73576
- if (open6 === null && !this.#turnSettledCompaction) {
73577
- const compactionId = randomUUID8();
73578
- await this.#enqueue(async () => {
73579
- await this.#context.emit({
73580
- compactionId,
73581
- error: cause instanceof Error ? cause.message : String(cause),
73582
- sessionUpdate: "compaction_update",
73583
- status: "failed"
73584
- });
73585
- });
73586
- }
73587
- this.#turnSettledCompaction = false;
73588
- throw cause;
73589
- } finally {
73590
- signal.removeEventListener("abort", aborted2);
73591
- waitExpired.abort();
73592
- if (this.#turn === turn) {
73593
- this.#turn = null;
73053
+ signal.removeEventListener("abort", aborted2);
73054
+ waitExpired.abort();
73055
+ if (this.#turn === turn) {
73056
+ this.#turn = null;
73594
73057
  }
73595
73058
  }
73596
73059
  };
@@ -73752,7 +73215,7 @@ var CodexOwnedAcpAgent = class {
73752
73215
  return;
73753
73216
  }
73754
73217
  await this.#enqueue(async () => {
73755
- await this.#context.emit(agentMessageUpdate(item.id, item.text));
73218
+ await this.#context.emit(agentMessageUpdate(item.id, item.text, messageQuestions(item)));
73756
73219
  });
73757
73220
  return;
73758
73221
  }
@@ -73928,170 +73391,734 @@ var CodexOwnedAcpAgent = class {
73928
73391
  this.#appServer.respond(request.id, { action: response2.action });
73929
73392
  return;
73930
73393
  }
73931
- const response = await connection.client.request(
73932
- methods.client.elicitation.create,
73933
- {
73934
- message: params.message,
73935
- mode: "form",
73936
- requestedSchema: params.requestedSchema ?? { properties: {}, required: [], type: "object" },
73937
- sessionId: this.#context.threadId()
73938
- },
73939
- { cancellationSignal: signal }
73940
- );
73941
- const content = response.action === "accept" ? Reflect.get(response, "content") ?? null : null;
73942
- this.#appServer.respond(request.id, { action: response.action, content });
73394
+ const response = await connection.client.request(
73395
+ methods.client.elicitation.create,
73396
+ {
73397
+ message: params.message,
73398
+ mode: "form",
73399
+ requestedSchema: params.requestedSchema ?? { properties: {}, required: [], type: "object" },
73400
+ sessionId: this.#context.threadId()
73401
+ },
73402
+ { cancellationSignal: signal }
73403
+ );
73404
+ const content = response.action === "accept" ? Reflect.get(response, "content") ?? null : null;
73405
+ this.#appServer.respond(request.id, { action: response.action, content });
73406
+ };
73407
+ prompt = async (input2, signal, content) => {
73408
+ signal.throwIfAborted();
73409
+ if (this.#turn !== null) {
73410
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
73411
+ }
73412
+ const completion = Promise.withResolvers();
73413
+ void completion.promise.catch(() => {
73414
+ });
73415
+ const aborted2 = () => {
73416
+ completion.reject(signal.reason);
73417
+ void this.#context.close().catch((cause) => {
73418
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
73419
+ });
73420
+ };
73421
+ signal.addEventListener("abort", aborted2, { once: true });
73422
+ const turn = {
73423
+ completion,
73424
+ content,
73425
+ steeringContent: /* @__PURE__ */ new Map(),
73426
+ clientId: randomUUID7(),
73427
+ input: { kind: "awaiting" },
73428
+ turn: { id: "" }
73429
+ };
73430
+ this.#agentMessages.clear();
73431
+ this.#streamedReasoningSources.clear();
73432
+ this.#turn = turn;
73433
+ this.#nativeTurnId = null;
73434
+ try {
73435
+ const started = turnSchema.parse(
73436
+ (await this.#appServer.request(
73437
+ "turn/start",
73438
+ {
73439
+ ...this.#settings.turnParameters(),
73440
+ input: input2,
73441
+ clientUserMessageId: turn.clientId,
73442
+ threadId: this.#context.threadId()
73443
+ },
73444
+ signal
73445
+ )).turn
73446
+ );
73447
+ if (this.#turn === turn) {
73448
+ turn.turn.id = started.id;
73449
+ this.#nativeTurnId = started.id;
73450
+ }
73451
+ try {
73452
+ const result = await completion.promise;
73453
+ return turn.input.kind === "identified" ? await promptResultWithMessageId2(Promise.resolve(result), turn.input.messageId) : result;
73454
+ } catch (cause) {
73455
+ if (turn.input.kind === "identified" && !signal.aborted) {
73456
+ return await promptResultWithMessageId2(Promise.reject(cause), turn.input.messageId);
73457
+ }
73458
+ throw cause;
73459
+ }
73460
+ } finally {
73461
+ signal.removeEventListener("abort", aborted2);
73462
+ if (this.#turn === turn) {
73463
+ turn.steeringContent.clear();
73464
+ this.#turn = null;
73465
+ this.#agentMessages.clear();
73466
+ this.#streamedReasoningSources.clear();
73467
+ }
73468
+ }
73469
+ };
73470
+ steer = async (params, signal) => {
73471
+ if (typeof params !== "object" || params === null) {
73472
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
73473
+ }
73474
+ const sessionId = Reflect.get(params, "sessionId");
73475
+ const prompt = Reflect.get(params, "prompt");
73476
+ if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
73477
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
73478
+ }
73479
+ const active = this.#turn;
73480
+ if (sessionId !== this.#context.threadId() || active === null || active.turn.id.length === 0) {
73481
+ return { outcome: "promptRequired", reason: "noRunningTurn" };
73482
+ }
73483
+ const steering = steeringPrompt(prompt);
73484
+ if (steering.length === 0) {
73485
+ throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
73486
+ }
73487
+ if (active.steeringContent.size >= 100) {
73488
+ throw new AcpExecutionError("Too many steering requests are pending consumption", {}, "session_busy");
73489
+ }
73490
+ const submitted = steering.map((block) => block.content);
73491
+ const clientId = randomUUID7();
73492
+ active.steeringContent.set(clientId, submitted);
73493
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)]);
73494
+ try {
73495
+ const response = turnSteerResponseSchema.parse(
73496
+ await this.#appServer.request(
73497
+ "turn/steer",
73498
+ {
73499
+ expectedTurnId: active.turn.id,
73500
+ clientUserMessageId: clientId,
73501
+ input: steering.map((block) => block.input),
73502
+ threadId: this.#context.threadId()
73503
+ },
73504
+ bounded
73505
+ )
73506
+ );
73507
+ if (response.turnId !== active.turn.id) {
73508
+ throw new AcpExecutionError("Codex steered an unexpected turn", {}, "steering_target_unavailable");
73509
+ }
73510
+ return { outcome: "injected" };
73511
+ } catch (cause) {
73512
+ active.steeringContent.delete(clientId);
73513
+ throw cause;
73514
+ }
73515
+ };
73516
+ cancel = async () => {
73517
+ const turn = this.#turn;
73518
+ if (turn === null) {
73519
+ return;
73520
+ }
73521
+ this.#turn = null;
73522
+ turn.steeringContent.clear();
73523
+ if (turn.turn.id.length > 0) {
73524
+ try {
73525
+ await this.#appServer.request(
73526
+ "turn/interrupt",
73527
+ { threadId: this.#context.threadId(), turnId: turn.turn.id },
73528
+ AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)
73529
+ );
73530
+ } catch {
73531
+ }
73532
+ }
73533
+ this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
73534
+ turn.completion.resolve({ stopReason: "cancelled" });
73535
+ };
73536
+ #completeTurn = async (turn) => {
73537
+ const active = this.#turn;
73538
+ if (active === null || active.turn.id !== turn.id) {
73539
+ return;
73540
+ }
73541
+ active.steeringContent.clear();
73542
+ await this.#updateTail;
73543
+ if (turn.status === "failed") {
73544
+ this.#turnSettledCompaction = this.#settleCompaction("failed", turn.error?.message ?? "The Codex turn failed") !== null;
73545
+ active.completion.reject(
73546
+ new AcpExecutionError(turn.error?.message ?? "The Codex turn failed", {}, "codex_turn_failed")
73547
+ );
73548
+ return;
73549
+ }
73550
+ if (turn.status === "interrupted") {
73551
+ this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
73552
+ active.completion.resolve({ stopReason: "cancelled" });
73553
+ return;
73554
+ }
73555
+ active.completion.resolve({ stopReason: "end_turn" });
73556
+ };
73557
+ };
73558
+
73559
+ // src/engine/acp/harness/codex/borrowed-agent.ts
73560
+ var REQUEST_TIMEOUT = 3e4;
73561
+ var POLL_INTERVAL = 500;
73562
+ var UNANSWERED_READ_LIMIT = 3;
73563
+ var queueResponseSchema = external_exports.object({
73564
+ queuedSubmission: external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })
73565
+ });
73566
+ var queuePageSchema = external_exports.object({
73567
+ data: external_exports.array(external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })).max(100),
73568
+ nextCursor: external_exports.string().nullish()
73569
+ });
73570
+ function turnRunning(turn) {
73571
+ return turn.status === "inProgress" || turn.status === "interrupted" && turn.completedAt == null;
73572
+ }
73573
+ function waitForNextPoll(timer, signal) {
73574
+ signal.throwIfAborted();
73575
+ return new Promise((resolve19, reject2) => {
73576
+ const poll = timer.schedule(() => {
73577
+ signal.removeEventListener("abort", abort);
73578
+ resolve19();
73579
+ }, POLL_INTERVAL);
73580
+ const abort = () => {
73581
+ poll.cancel();
73582
+ reject2(signal.reason);
73583
+ };
73584
+ signal.addEventListener("abort", abort, { once: true });
73585
+ });
73586
+ }
73587
+ var CodexBorrowedAcpAgent = class {
73588
+ steeringSupported = false;
73589
+ runsTurns = false;
73590
+ #client;
73591
+ #threadId;
73592
+ #emit;
73593
+ #onDelegation;
73594
+ #closed = new AbortController();
73595
+ #seen = /* @__PURE__ */ new Map();
73596
+ #pending = null;
73597
+ #watch = null;
73598
+ #lifecycle = { kind: "following" };
73599
+ constructor(client2, threadId, emit, onDelegation) {
73600
+ this.#client = client2;
73601
+ this.#threadId = threadId;
73602
+ this.#emit = emit;
73603
+ this.#onDelegation = onDelegation;
73604
+ }
73605
+ #reportDelegation = async (pending, stage) => {
73606
+ pending.delegation = pending.delegation.then(async () => await this.#onDelegation(stage));
73607
+ await pending.delegation;
73608
+ };
73609
+ initialize = async (signal) => {
73610
+ queuePageSchema.parse(
73611
+ await this.#client.request(
73612
+ "thread/queue/list",
73613
+ { threadId: this.#threadId },
73614
+ AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
73615
+ )
73616
+ );
73617
+ await this.#apply(await this.#read(signal, true), true);
73618
+ this.#watch = this.#follow();
73619
+ };
73620
+ #follow = async () => {
73621
+ const signal = this.#closed.signal;
73622
+ let unansweredReads = 0;
73623
+ try {
73624
+ for (; ; ) {
73625
+ await waitForNextPoll(systemTimer, signal);
73626
+ let pages;
73627
+ try {
73628
+ pages = await this.#read(signal, false);
73629
+ } catch (cause) {
73630
+ unansweredReads += 1;
73631
+ if (!(cause instanceof DOMException && cause.name === "TimeoutError") || unansweredReads === UNANSWERED_READ_LIMIT) {
73632
+ throw cause;
73633
+ }
73634
+ console.warn("Codex thread history read timed out; following continues", {
73635
+ threadId: this.#threadId
73636
+ });
73637
+ continue;
73638
+ }
73639
+ unansweredReads = 0;
73640
+ await this.#apply(pages, false);
73641
+ }
73642
+ } catch (cause) {
73643
+ if (!signal.aborted) {
73644
+ const error62 = new AcpExecutionError(
73645
+ "The owning Codex session could not be followed",
73646
+ { cause },
73647
+ "codex_queue_follow_failed"
73648
+ );
73649
+ this.#lifecycle = { kind: "failed", error: error62 };
73650
+ this.#pending?.completion.reject(error62);
73651
+ }
73652
+ }
73653
+ };
73654
+ #read = async (signal, baseline) => {
73655
+ let cursor = null;
73656
+ const pages = [];
73657
+ const cursors = /* @__PURE__ */ new Set();
73658
+ do {
73659
+ const page = threadTurnsPageSchema.parse(
73660
+ await this.#client.request(
73661
+ "thread/turns/list",
73662
+ {
73663
+ threadId: this.#threadId,
73664
+ limit: CODEX_HISTORY_TURN_PAGE_LIMIT,
73665
+ sortDirection: "desc",
73666
+ itemsView: "full",
73667
+ ...cursor === null ? {} : { cursor }
73668
+ },
73669
+ AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
73670
+ )
73671
+ );
73672
+ pages.push(page.data);
73673
+ cursor = page.nextCursor ?? null;
73674
+ if (cursor !== null && cursors.has(cursor)) {
73675
+ throw new AcpExecutionError("Codex repeated a history cursor", {}, "invalid_native_session_response");
73676
+ }
73677
+ if (cursor !== null) {
73678
+ cursors.add(cursor);
73679
+ }
73680
+ } while (cursor !== null && (baseline || this.#pending !== null));
73681
+ return pages;
73682
+ };
73683
+ #apply = async (pages, baseline) => {
73684
+ for (const turns of [...pages].reverse()) {
73685
+ for (const turn of [...turns].reverse()) {
73686
+ let matches = false;
73687
+ for (const raw of turn.items) {
73688
+ const item = decodeThreadItem(raw);
73689
+ if (item === null) {
73690
+ continue;
73691
+ }
73692
+ const key = `${turn.id ?? ""}:${item.id}`;
73693
+ if (item.type === "userMessage") {
73694
+ const clientId = typeof raw === "object" && raw !== null ? Reflect.get(raw, "clientId") : void 0;
73695
+ matches ||= clientId === this.#pending?.clientId;
73696
+ if (this.#pending !== null && clientId === this.#pending.clientId) {
73697
+ const started = this.#pending.input.kind === "awaiting";
73698
+ this.#pending.input = { kind: "identified", messageId: item.id };
73699
+ if (started) {
73700
+ await this.#reportDelegation(this.#pending, "started");
73701
+ }
73702
+ }
73703
+ const text2 = item.content.flatMap(
73704
+ (block) => typeof block === "object" && block !== null && Reflect.get(block, "type") === "text" && typeof Reflect.get(block, "text") === "string" ? [String(Reflect.get(block, "text"))] : []
73705
+ ).join("");
73706
+ if (!baseline && !this.#seen.has(key)) {
73707
+ for (const update of userMessageUpdates(
73708
+ item,
73709
+ this.#pending !== null && clientId === this.#pending.clientId ? this.#pending.content : void 0
73710
+ )) {
73711
+ await this.#emit(update);
73712
+ }
73713
+ }
73714
+ this.#seen.set(key, text2);
73715
+ continue;
73716
+ }
73717
+ if (item.type === "plan" && turnRunning(turn)) {
73718
+ continue;
73719
+ }
73720
+ const previous = this.#seen.get(key);
73721
+ const value = item.type === "agentMessage" || item.type === "plan" ? item.text : reasoningText(item) ?? JSON.stringify(item);
73722
+ this.#seen.set(key, value);
73723
+ if (baseline || value === previous) {
73724
+ continue;
73725
+ }
73726
+ if (item.type === "agentMessage" || item.type === "plan" || reasoningText(item) !== null) {
73727
+ const text2 = previous !== void 0 && value.startsWith(previous) ? value.slice(previous.length) : value;
73728
+ if (text2.length > 0) {
73729
+ await this.#emit(
73730
+ item.type === "reasoning" ? {
73731
+ sessionUpdate: "agent_thought_chunk",
73732
+ messageId: item.id,
73733
+ content: { type: "text", text: text2 }
73734
+ } : agentMessageUpdate(
73735
+ item.id,
73736
+ text2,
73737
+ previous === void 0 ? messageQuestions(item) : []
73738
+ )
73739
+ );
73740
+ }
73741
+ } else {
73742
+ const update = toolCallUpdate(item, "snapshot");
73743
+ if (update !== null) {
73744
+ if (previous === void 0) {
73745
+ await this.#emit({ ...update, sessionUpdate: "tool_call" });
73746
+ } else {
73747
+ await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
73748
+ }
73749
+ }
73750
+ }
73751
+ }
73752
+ if (matches && turn.status !== void 0 && !turnRunning(turn)) {
73753
+ if (turn.status === "failed") {
73754
+ this.#pending?.completion.reject(
73755
+ new AcpExecutionError("The owning Codex turn failed", {}, "codex_turn_failed")
73756
+ );
73757
+ } else {
73758
+ this.#pending?.completion.resolve({
73759
+ stopReason: turn.status === "interrupted" ? "cancelled" : "end_turn"
73760
+ });
73761
+ }
73762
+ }
73763
+ }
73764
+ }
73943
73765
  };
73944
73766
  prompt = async (input2, signal, content) => {
73945
73767
  signal.throwIfAborted();
73946
- if (this.#turn !== null) {
73947
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
73768
+ if (this.#lifecycle.kind === "failed") {
73769
+ throw this.#lifecycle.error;
73948
73770
  }
73949
- const completion = Promise.withResolvers();
73950
- void completion.promise.catch(() => {
73951
- });
73952
- const aborted2 = () => {
73953
- completion.reject(signal.reason);
73954
- void this.#context.close().catch((cause) => {
73955
- console.error("The cancelled Codex endpoint could not release its process tree", cause);
73956
- });
73957
- };
73958
- signal.addEventListener("abort", aborted2, { once: true });
73959
- const turn = {
73960
- completion,
73771
+ if (this.#lifecycle.kind === "closed") {
73772
+ throw new AcpExecutionError("The Codex queue connection is closed", {}, "acp_endpoint_closed");
73773
+ }
73774
+ if (this.#pending !== null) {
73775
+ throw new AcpExecutionError("Another prompt is already running", {}, "session_busy");
73776
+ }
73777
+ const pending = {
73961
73778
  content,
73962
- steeringContent: /* @__PURE__ */ new Map(),
73963
73779
  clientId: randomUUID8(),
73780
+ completion: Promise.withResolvers(),
73781
+ settled: Promise.withResolvers(),
73964
73782
  input: { kind: "awaiting" },
73965
- turn: { id: "" }
73783
+ delegation: Promise.resolve()
73966
73784
  };
73967
- this.#agentMessages.clear();
73968
- this.#streamedReasoningSources.clear();
73969
- this.#turn = turn;
73970
- this.#nativeTurnId = null;
73785
+ this.#pending = pending;
73786
+ void pending.completion.promise.catch(() => {
73787
+ });
73788
+ const abort = () => pending.completion.reject(signal.reason);
73789
+ signal.addEventListener("abort", abort, { once: true });
73790
+ let outcome = "cancelled";
73971
73791
  try {
73972
- const started = turnSchema.parse(
73973
- (await this.#appServer.request(
73974
- "turn/start",
73792
+ const queued = queueResponseSchema.parse(
73793
+ await this.#client.request(
73794
+ "thread/queue/add",
73975
73795
  {
73976
- ...this.#settings.turnParameters(),
73796
+ threadId: this.#threadId,
73977
73797
  input: input2,
73978
- clientUserMessageId: turn.clientId,
73979
- threadId: this.#context.threadId()
73798
+ clientUserMessageId: pending.clientId
73980
73799
  },
73981
- signal
73982
- )).turn
73800
+ AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
73801
+ )
73983
73802
  );
73984
- if (this.#turn === turn) {
73985
- turn.turn.id = started.id;
73986
- this.#nativeTurnId = started.id;
73803
+ if (queued.queuedSubmission.clientUserMessageId !== pending.clientId) {
73804
+ throw new AcpExecutionError(
73805
+ "Codex queued an unexpected message",
73806
+ {},
73807
+ "invalid_native_session_response"
73808
+ );
73987
73809
  }
73988
- try {
73989
- const result = await completion.promise;
73990
- return turn.input.kind === "identified" ? await promptResultWithMessageId2(Promise.resolve(result), turn.input.messageId) : result;
73991
- } catch (cause) {
73992
- if (turn.input.kind === "identified" && !signal.aborted) {
73993
- return await promptResultWithMessageId2(Promise.reject(cause), turn.input.messageId);
73994
- }
73995
- throw cause;
73810
+ await this.#reportDelegation(pending, "queued");
73811
+ const result = await pending.completion.promise;
73812
+ outcome = result.stopReason === "cancelled" ? "cancelled" : "completed";
73813
+ return pending.input.kind === "identified" ? await promptResultWithMessageId2(Promise.resolve(result), pending.input.messageId) : result;
73814
+ } catch (cause) {
73815
+ if (pending.input.kind === "identified" && !signal.aborted) {
73816
+ return await promptResultWithMessageId2(Promise.reject(cause), pending.input.messageId);
73996
73817
  }
73818
+ throw cause;
73997
73819
  } finally {
73998
- signal.removeEventListener("abort", aborted2);
73999
- if (this.#turn === turn) {
74000
- turn.steeringContent.clear();
74001
- this.#turn = null;
74002
- this.#agentMessages.clear();
74003
- this.#streamedReasoningSources.clear();
73820
+ signal.removeEventListener("abort", abort);
73821
+ if (outcome === "cancelled") {
73822
+ try {
73823
+ await this.#removeQueuedInput(pending.clientId);
73824
+ } catch (cause) {
73825
+ console.error("The cancelled Codex queued input could not be removed", cause);
73826
+ }
74004
73827
  }
73828
+ this.#pending = null;
73829
+ pending.settled.resolve();
74005
73830
  }
74006
73831
  };
74007
- steer = async (params, signal) => {
74008
- if (typeof params !== "object" || params === null) {
74009
- throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
73832
+ /** Withdraws this client's submission while the owner has not taken it; false once the owner has. */
73833
+ #removeQueuedInput = async (clientId) => {
73834
+ const signal = AbortSignal.timeout(REQUEST_TIMEOUT);
73835
+ let cursor = null;
73836
+ const cursors = /* @__PURE__ */ new Set();
73837
+ do {
73838
+ const page = queuePageSchema.parse(
73839
+ await this.#client.request(
73840
+ "thread/queue/list",
73841
+ { threadId: this.#threadId, limit: 100, ...cursor === null ? {} : { cursor } },
73842
+ signal
73843
+ )
73844
+ );
73845
+ for (const queued of page.data) {
73846
+ if (queued.clientUserMessageId === clientId) {
73847
+ await this.#client.request(
73848
+ "thread/queue/delete",
73849
+ { threadId: this.#threadId, queuedSubmissionId: queued.id },
73850
+ signal
73851
+ );
73852
+ return true;
73853
+ }
73854
+ }
73855
+ cursor = page.nextCursor ?? null;
73856
+ if (cursor !== null && cursors.has(cursor)) {
73857
+ throw new AcpExecutionError("Codex repeated a queue cursor", {}, "invalid_native_session_response");
73858
+ }
73859
+ if (cursor !== null) {
73860
+ cursors.add(cursor);
73861
+ }
73862
+ } while (cursor !== null);
73863
+ return false;
73864
+ };
73865
+ nativeTurnId = () => null;
73866
+ steer = async (_params, signal) => {
73867
+ signal.throwIfAborted();
73868
+ throw new AcpExecutionError("This Codex session only supports queued input", {}, "steering_unsupported");
73869
+ };
73870
+ // The reader connection cannot receive or control the owner's live turn.
73871
+ onNotification = async (_method, _params) => {
73872
+ };
73873
+ onServerRequest = async (request) => {
73874
+ this.#client.respondWithError(request.id, -32601, "Borrowed sessions cannot handle owner requests");
73875
+ };
73876
+ onTerminated = (termination) => {
73877
+ const error62 = acpEndpointTerminationError(termination);
73878
+ this.#lifecycle = { kind: "failed", error: error62 };
73879
+ this.#pending?.completion.reject(error62);
73880
+ this.#closed.abort();
73881
+ };
73882
+ // A remote Stop must never interrupt another client's owning turn.
73883
+ compact = async (_signal) => {
73884
+ throw new AcpExecutionError(
73885
+ "This Codex session is attached read-only and cannot be compacted",
73886
+ {},
73887
+ "native_session_unsupported"
73888
+ );
73889
+ };
73890
+ /**
73891
+ * Withdraws the prompt while it waits in the owner's queue. Once the owner runs it, only the owner can stop it,
73892
+ * so the prompt keeps running and following reports how the owner ends it.
73893
+ */
73894
+ cancel = async () => {
73895
+ const pending = this.#pending;
73896
+ if (pending === null || pending.input.kind === "identified") {
73897
+ return;
74010
73898
  }
74011
- const sessionId = Reflect.get(params, "sessionId");
74012
- const prompt = Reflect.get(params, "prompt");
74013
- if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
74014
- throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
73899
+ if (await this.#removeQueuedInput(pending.clientId)) {
73900
+ pending.completion.resolve({ stopReason: "cancelled" });
73901
+ await pending.settled.promise;
74015
73902
  }
74016
- const active = this.#turn;
74017
- if (sessionId !== this.#context.threadId() || active === null || active.turn.id.length === 0) {
74018
- return { outcome: "promptRequired", reason: "noRunningTurn" };
73903
+ };
73904
+ close = async () => {
73905
+ this.#lifecycle = { kind: "closed" };
73906
+ this.#closed.abort();
73907
+ const pending = this.#pending;
73908
+ if (pending !== null) {
73909
+ pending.completion.resolve({ stopReason: "cancelled" });
73910
+ await pending.settled.promise;
74019
73911
  }
74020
- const steering = steeringPrompt(prompt);
74021
- if (steering.length === 0) {
74022
- throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
73912
+ await this.#watch;
73913
+ };
73914
+ };
73915
+
73916
+ // src/engine/acp/harness/codex/history.ts
73917
+ import { createHash as createHash2 } from "node:crypto";
73918
+
73919
+ // src/engine/acp/content/raster.ts
73920
+ import { basename as basename4, isAbsolute as isAbsolute9, normalize } from "node:path";
73921
+ import { fileURLToPath } from "node:url";
73922
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
73923
+ var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
73924
+ var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
73925
+ var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
73926
+ var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
73927
+ var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
73928
+ var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
73929
+ var LocalRasterImage = class {
73930
+ mimeType;
73931
+ name;
73932
+ sourceUri;
73933
+ constructor(name2, mimeType, sourceUri) {
73934
+ this.mimeType = mimeType;
73935
+ this.name = name2;
73936
+ this.sourceUri = sourceUri;
73937
+ }
73938
+ base64 = async () => Buffer.from(await readFileBytes(this.sourceUri)).toString("base64");
73939
+ };
73940
+ function startsWith(bytes, signature, offset = 0) {
73941
+ if (bytes.byteLength < offset + signature.byteLength) {
73942
+ return false;
73943
+ }
73944
+ return signature.every((value, index2) => bytes[offset + index2] === value);
73945
+ }
73946
+ function sniffRasterMime(bytes) {
73947
+ if (startsWith(bytes, PNG_SIGNATURE)) {
73948
+ return "image/png";
73949
+ }
73950
+ if (startsWith(bytes, JPEG_SIGNATURE)) {
73951
+ return "image/jpeg";
73952
+ }
73953
+ if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
73954
+ return "image/gif";
73955
+ }
73956
+ if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
73957
+ return "image/webp";
73958
+ }
73959
+ return null;
73960
+ }
73961
+ async function resolveCanonicalPath(requested, signal) {
73962
+ signal.throwIfAborted();
73963
+ if (!isAbsolute9(requested) || requested.includes("\0") || normalize(requested) !== requested) {
73964
+ return null;
73965
+ }
73966
+ try {
73967
+ const target = await canonicalPath(requested);
73968
+ signal.throwIfAborted();
73969
+ if (!isAbsolute9(target) || normalize(target) !== target) {
73970
+ return null;
74023
73971
  }
74024
- if (active.steeringContent.size >= 100) {
74025
- throw new AcpExecutionError("Too many steering requests are pending consumption", {}, "session_busy");
73972
+ return target;
73973
+ } catch (cause) {
73974
+ signal.throwIfAborted();
73975
+ if (cause instanceof Error && cause.name === "AbortError") {
73976
+ throw cause;
74026
73977
  }
74027
- const submitted = steering.map((block) => block.content);
74028
- const clientId = randomUUID8();
74029
- active.steeringContent.set(clientId, submitted);
74030
- const bounded = AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)]);
73978
+ return null;
73979
+ }
73980
+ }
73981
+ function parseLocalImageUri(uri) {
73982
+ const trimmed = uri.trim();
73983
+ if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
73984
+ return null;
73985
+ }
73986
+ if (trimmed.startsWith("data:")) {
73987
+ return null;
73988
+ }
73989
+ if (trimmed.startsWith("file:")) {
74031
73990
  try {
74032
- const response = turnSteerResponseSchema.parse(
74033
- await this.#appServer.request(
74034
- "turn/steer",
74035
- {
74036
- expectedTurnId: active.turn.id,
74037
- clientUserMessageId: clientId,
74038
- input: steering.map((block) => block.input),
74039
- threadId: this.#context.threadId()
74040
- },
74041
- bounded
74042
- )
74043
- );
74044
- if (response.turnId !== active.turn.id) {
74045
- throw new AcpExecutionError("Codex steered an unexpected turn", {}, "steering_target_unavailable");
73991
+ const url2 = new URL(trimmed);
73992
+ if (url2.protocol !== "file:" || url2.host.length > 0) {
73993
+ return null;
74046
73994
  }
74047
- return { outcome: "injected" };
74048
- } catch (cause) {
74049
- active.steeringContent.delete(clientId);
74050
- throw cause;
73995
+ return fileURLToPath(url2);
73996
+ } catch {
73997
+ return null;
74051
73998
  }
73999
+ }
74000
+ if (!isAbsolute9(trimmed) && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
74001
+ return null;
74002
+ }
74003
+ return trimmed;
74004
+ }
74005
+ async function readLocalRaster(uri, signal) {
74006
+ signal.throwIfAborted();
74007
+ const requested = parseLocalImageUri(uri);
74008
+ if (requested === null) {
74009
+ return null;
74010
+ }
74011
+ const target = await resolveCanonicalPath(requested, signal);
74012
+ if (target === null) {
74013
+ return null;
74014
+ }
74015
+ const targetMetadata = await readPathMetadata(target);
74016
+ signal.throwIfAborted();
74017
+ if (targetMetadata.kind !== "file" || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
74018
+ return null;
74019
+ }
74020
+ const header = await readFileStart(target, 12);
74021
+ signal.throwIfAborted();
74022
+ const mimeType = sniffRasterMime(header);
74023
+ if (mimeType === null) {
74024
+ return null;
74025
+ }
74026
+ return new LocalRasterImage(basename4(target) || "Image", mimeType, target);
74027
+ }
74028
+
74029
+ // src/engine/acp/native-history/codex/history-images.ts
74030
+ var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
74031
+ var DATA_IMAGE_HEADER = /^data:(image\/[a-z+]+);base64,/;
74032
+ var BASE_64 = /^[A-Za-z0-9+/]*={0,2}$/;
74033
+ var SESSION_HISTORY_IMAGE_CHARACTER_LIMIT = 4e6;
74034
+ function isRasterMime(value) {
74035
+ return value === "image/png" || value === "image/jpeg" || value === "image/gif" || value === "image/webp";
74036
+ }
74037
+ function parseNativeHistoryImage(uri) {
74038
+ const header = DATA_IMAGE_HEADER.exec(uri);
74039
+ if (header === null) {
74040
+ return null;
74041
+ }
74042
+ const mimeType = header[1] ?? "";
74043
+ const data = uri.slice(header[0].length);
74044
+ if (!isRasterMime(mimeType) || data.length < 4 || data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
74045
+ return null;
74046
+ }
74047
+ if (data.length % 4 !== 0 || !BASE_64.test(data)) {
74048
+ return null;
74049
+ }
74050
+ return { data, mimeType, name: "" };
74051
+ }
74052
+ async function embedLocalHistoryImages(history, signal) {
74053
+ if (history.status !== "available") {
74054
+ return history;
74055
+ }
74056
+ const messages = [];
74057
+ let imageCharacters = 0;
74058
+ for (const message of history.messages) {
74059
+ signal.throwIfAborted();
74060
+ const resolved = await resolveMessageImages(message, imageCharacters, signal);
74061
+ imageCharacters += (resolved.images ?? []).reduce((size, image) => size + image.data.length, 0);
74062
+ messages.push(resolved);
74063
+ }
74064
+ return {
74065
+ ...history,
74066
+ messages
74052
74067
  };
74053
- cancel = async () => {
74054
- const turn = this.#turn;
74055
- if (turn === null) {
74056
- return;
74068
+ }
74069
+ async function resolveMessageImages(message, usedCharacters, signal) {
74070
+ const images = [...message.images ?? []];
74071
+ let imageCharacters = images.reduce((size, image) => size + image.data.length, 0);
74072
+ const text2 = await replaceImageMarkers(message.text, async (uri) => {
74073
+ if (images.length >= 8 || usedCharacters + imageCharacters >= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
74074
+ return "[Image unavailable]";
74057
74075
  }
74058
- this.#turn = null;
74059
- turn.steeringContent.clear();
74060
- if (turn.turn.id.length > 0) {
74061
- try {
74062
- await this.#appServer.request(
74063
- "turn/interrupt",
74064
- { threadId: this.#context.threadId(), turnId: turn.turn.id },
74065
- AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)
74066
- );
74067
- } catch {
74076
+ const embedded = parseNativeHistoryImage(uri);
74077
+ if (embedded !== null) {
74078
+ if (usedCharacters + imageCharacters + embedded.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
74079
+ return "[Image unavailable]";
74068
74080
  }
74081
+ images.push({ ...embedded, name: `Image ${(images.length + 1).toString()}` });
74082
+ imageCharacters += embedded.data.length;
74083
+ return "";
74069
74084
  }
74070
- this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
74071
- turn.completion.resolve({ stopReason: "cancelled" });
74072
- };
74073
- #completeTurn = async (turn) => {
74074
- const active = this.#turn;
74075
- if (active === null || active.turn.id !== turn.id) {
74076
- return;
74077
- }
74078
- active.steeringContent.clear();
74079
- await this.#updateTail;
74080
- if (turn.status === "failed") {
74081
- this.#turnSettledCompaction = this.#settleCompaction("failed", turn.error?.message ?? "The Codex turn failed") !== null;
74082
- active.completion.reject(
74083
- new AcpExecutionError(turn.error?.message ?? "The Codex turn failed", {}, "codex_turn_failed")
74084
- );
74085
- return;
74085
+ const local = await readLocalRaster(uri, signal);
74086
+ if (local === null) {
74087
+ return "[Image unavailable]";
74086
74088
  }
74087
- if (turn.status === "interrupted") {
74088
- this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
74089
- active.completion.resolve({ stopReason: "cancelled" });
74090
- return;
74089
+ const data = await local.base64();
74090
+ if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
74091
+ return "[Image unavailable]";
74091
74092
  }
74092
- active.completion.resolve({ stopReason: "end_turn" });
74093
+ images.push({
74094
+ data,
74095
+ mimeType: local.mimeType,
74096
+ name: local.name
74097
+ });
74098
+ imageCharacters += data.length;
74099
+ return "";
74100
+ });
74101
+ return {
74102
+ ...message,
74103
+ text: text2,
74104
+ ...images.length > 0 ? { images } : {}
74093
74105
  };
74094
- };
74106
+ }
74107
+ async function replaceImageMarkers(text2, replace) {
74108
+ const matches = [...text2.matchAll(IMAGE_MARKER)];
74109
+ if (matches.length === 0) {
74110
+ return text2;
74111
+ }
74112
+ let cursor = 0;
74113
+ let rewritten = "";
74114
+ for (const match of matches) {
74115
+ const index2 = match.index ?? 0;
74116
+ rewritten += text2.slice(cursor, index2);
74117
+ rewritten += await replace(match[1] ?? "");
74118
+ cursor = index2 + match[0].length;
74119
+ }
74120
+ return `${rewritten}${text2.slice(cursor)}`;
74121
+ }
74095
74122
 
74096
74123
  // src/engine/acp/harness/codex/history.ts
74097
74124
  async function replayCodexHistory(client2, threadId, emit, signal) {
@@ -74160,7 +74187,7 @@ async function replayCodexHistory(client2, threadId, emit, signal) {
74160
74187
  }
74161
74188
  }
74162
74189
  } else if (item.type === "agentMessage" || item.type === "plan") {
74163
- await emit(agentMessageUpdate(item.id, item.text));
74190
+ await emit(agentMessageUpdate(item.id, item.text, messageQuestions(item)));
74164
74191
  } else if (item.type === "reasoning") {
74165
74192
  const text2 = reasoningText(item);
74166
74193
  if (text2 !== null && text2.length > 0) {
@@ -80265,6 +80292,24 @@ function applyConfigurationChanges(base, changes) {
80265
80292
  }
80266
80293
 
80267
80294
  // src/engine/acp/adapter/session-events.ts
80295
+ function withMobiusFields(update, eventUpdate) {
80296
+ if (typeof eventUpdate !== "object" || eventUpdate === null) {
80297
+ return eventUpdate;
80298
+ }
80299
+ switch (update.sessionUpdate) {
80300
+ case "tool_call":
80301
+ case "tool_call_update": {
80302
+ const backgroundTask = update._meta?.["mobius.backgroundTask"];
80303
+ return backgroundTask === void 0 ? eventUpdate : { ...eventUpdate, backgroundTask };
80304
+ }
80305
+ case "agent_message_chunk": {
80306
+ const questions = update._meta?.["mobius.questions"];
80307
+ return questions === void 0 ? eventUpdate : { ...eventUpdate, questions };
80308
+ }
80309
+ default:
80310
+ return eventUpdate;
80311
+ }
80312
+ }
80268
80313
  var AdapterSessionConnection = class {
80269
80314
  #connection;
80270
80315
  #onBackgroundActivity;
@@ -80294,13 +80339,8 @@ var AdapterSessionConnection = class {
80294
80339
  signal.throwIfAborted();
80295
80340
  const update = externalized.agent;
80296
80341
  for (const eventUpdate of externalized.events) {
80297
- const backgroundTask = update._meta?.["mobius.backgroundTask"];
80298
80342
  const payload = decodeAcpSessionUpdate(
80299
- JSON.stringify(
80300
- normalizeEvent(
80301
- (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") && backgroundTask !== void 0 && typeof eventUpdate === "object" && eventUpdate !== null ? { ...eventUpdate, backgroundTask } : eventUpdate
80302
- )
80303
- )
80343
+ JSON.stringify(normalizeEvent(withMobiusFields(update, eventUpdate)))
80304
80344
  );
80305
80345
  let event;
80306
80346
  switch (update.sessionUpdate) {
@@ -87500,7 +87540,9 @@ var CodexAdapter = class {
87500
87540
  for (const event of externalized.events) {
87501
87541
  events.push({
87502
87542
  type: "acp",
87503
- payload: decodeAcpSessionUpdate(JSON.stringify(fitCodexToolEvent(event)))
87543
+ payload: decodeAcpSessionUpdate(
87544
+ JSON.stringify(fitCodexToolEvent(withMobiusFields(update, event)))
87545
+ )
87504
87546
  });
87505
87547
  }
87506
87548
  },
@@ -97833,4 +97875,4 @@ export {
97833
97875
  * MIT Licensed
97834
97876
  *)
97835
97877
  */
97836
- //# sourceMappingURL=chunk-6DTIQNQZ.js.map
97878
+ //# sourceMappingURL=chunk-JQTOOWQD.js.map