@moxt-ai/mobius 0.0.429 → 0.0.431

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 (54) hide show
  1. package/dist/{chunk-NRP5QMEO.js → chunk-JRGUX5C6.js} +2 -2
  2. package/dist/{chunk-NRP5QMEO.js.map → chunk-JRGUX5C6.js.map} +1 -1
  3. package/dist/{chunk-JRH5V326.js → chunk-RWCLUO5M.js} +1060 -934
  4. package/dist/{chunk-JRH5V326.js.map → chunk-RWCLUO5M.js.map} +4 -4
  5. package/dist/{cli-B4BKARN2.js → cli-IN6O4PIQ.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/adapter/codex/adapter.d.ts +0 -5
  8. package/dist/engine/acp/adapter/codex/adapter.d.ts.map +1 -1
  9. package/dist/engine/acp/adapter/codex/adapter.js +22 -2
  10. package/dist/engine/acp/adapter/codex/adapter.js.map +1 -1
  11. package/dist/engine/acp/adapter/codex/agent-connection.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/codex/agent-connection.js +1 -0
  13. package/dist/engine/acp/adapter/codex/agent-connection.js.map +1 -1
  14. package/dist/engine/acp/adapter/execution-connections.d.ts +3 -1
  15. package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -1
  16. package/dist/engine/acp/adapter/execution-connections.js +3 -0
  17. package/dist/engine/acp/adapter/execution-connections.js.map +1 -1
  18. package/dist/engine/acp/adapter/session-events.d.ts +9 -1
  19. package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
  20. package/dist/engine/acp/adapter/session-events.js +28 -7
  21. package/dist/engine/acp/adapter/session-events.js.map +1 -1
  22. package/dist/engine/acp/agent/in-process-endpoint.d.ts +7 -1
  23. package/dist/engine/acp/agent/in-process-endpoint.d.ts.map +1 -1
  24. package/dist/engine/acp/connection/agent-connection.d.ts +2 -1
  25. package/dist/engine/acp/connection/agent-connection.d.ts.map +1 -1
  26. package/dist/engine/acp/harness/codex/agent.d.ts.map +1 -1
  27. package/dist/engine/acp/harness/codex/agent.js +12 -3
  28. package/dist/engine/acp/harness/codex/agent.js.map +1 -1
  29. package/dist/engine/acp/harness/codex/app-server-protocol.d.ts +4 -0
  30. package/dist/engine/acp/harness/codex/app-server-protocol.d.ts.map +1 -1
  31. package/dist/engine/acp/harness/codex/app-server-protocol.js +11 -0
  32. package/dist/engine/acp/harness/codex/app-server-protocol.js.map +1 -1
  33. package/dist/engine/acp/harness/codex/borrowed-agent.d.ts +7 -2
  34. package/dist/engine/acp/harness/codex/borrowed-agent.d.ts.map +1 -1
  35. package/dist/engine/acp/harness/codex/borrowed-agent.js +42 -11
  36. package/dist/engine/acp/harness/codex/borrowed-agent.js.map +1 -1
  37. package/dist/engine/acp/harness/codex/history.js +2 -2
  38. package/dist/engine/acp/harness/codex/history.js.map +1 -1
  39. package/dist/engine/acp/harness/codex/items.d.ts +3 -0
  40. package/dist/engine/acp/harness/codex/items.d.ts.map +1 -1
  41. package/dist/engine/acp/harness/codex/items.js +6 -0
  42. package/dist/engine/acp/harness/codex/items.js.map +1 -1
  43. package/dist/engine/acp/harness/codex/owned-agent.d.ts +3 -1
  44. package/dist/engine/acp/harness/codex/owned-agent.d.ts.map +1 -1
  45. package/dist/engine/acp/harness/codex/owned-agent.js +5 -3
  46. package/dist/engine/acp/harness/codex/owned-agent.js.map +1 -1
  47. package/dist/engine/acp/harness/codex/session-agent.d.ts +2 -0
  48. package/dist/engine/acp/harness/codex/session-agent.d.ts.map +1 -1
  49. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  50. package/dist/engine/session/live/agent-session.js +22 -1
  51. package/dist/engine/session/live/agent-session.js.map +1 -1
  52. package/dist/engine.js +2 -2
  53. package/package.json +2 -2
  54. /package/dist/{cli-B4BKARN2.js.map → cli-IN6O4PIQ.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-NRP5QMEO.js";
6
+ } from "./chunk-JRGUX5C6.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(),
@@ -20772,6 +20780,12 @@ var lifecycleMetadataSchema = external_exports.discriminatedUnion("kind", [
20772
20780
  targetCommandId: identifierStringSchema.optional()
20773
20781
  }).readonly(),
20774
20782
  external_exports.object({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
20783
+ // The Runtime did not run this prompt itself: it handed it to the native session's owner, another client of the
20784
+ // Agent such as the Codex app, which runs queued input on its own terms. `queued`: the owner holds the prompt and
20785
+ // may keep holding it; Codex pauses its queue after an interrupted turn until its user continues. `started`: the
20786
+ // owner began running it, so only the owner can stop it and cancelling it here leaves it running. Runtimes before
20787
+ // this event never delegate.
20788
+ external_exports.object({ ...lifecycleBase, kind: external_exports.literal("prompt.delegated"), stage: external_exports.enum(["queued", "started"]) }).readonly(),
20775
20789
  promptCompletedSchema,
20776
20790
  external_exports.object({
20777
20791
  ...lifecycleBase,
@@ -20789,6 +20803,7 @@ var isPromptTerminal = (payload) => {
20789
20803
  return true;
20790
20804
  case "prompt.requested":
20791
20805
  case "prompt.started":
20806
+ case "prompt.delegated":
20792
20807
  case "session.queue.changed":
20793
20808
  case "session.permission.requested":
20794
20809
  case "session.permission.resolved":
@@ -71984,6 +71999,12 @@ var imageGenerationItemSchema = external_exports.object({
71984
71999
  resetsAt: external_exports.number().nullish()
71985
72000
  }).nullish()
71986
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);
71987
72008
  var threadItemSchema = external_exports.discriminatedUnion("type", [
71988
72009
  imageGenerationItemSchema,
71989
72010
  external_exports.object({ type: external_exports.literal("imageView"), id: boundedText(256), path: boundedText(32768).refine(isAbsolute8) }),
@@ -71991,7 +72012,8 @@ var threadItemSchema = external_exports.discriminatedUnion("type", [
71991
72012
  id: boundedText(256),
71992
72013
  text: boundedText(1e6),
71993
72014
  type: external_exports.literal("agentMessage"),
71994
- phase: messagePhaseSchema.nullish()
72015
+ phase: messagePhaseSchema.nullish(),
72016
+ questions: agentMessageQuestionsSchema
71995
72017
  }),
71996
72018
  external_exports.object({
71997
72019
  content: external_exports.array(external_exports.unknown()).max(1e4),
@@ -72463,7 +72485,7 @@ var CodexAppServerClient = class {
72463
72485
  };
72464
72486
 
72465
72487
  // src/engine/acp/harness/codex/borrowed-agent.ts
72466
- import { randomUUID as randomUUID7 } from "node:crypto";
72488
+ import { randomUUID as randomUUID8 } from "node:crypto";
72467
72489
 
72468
72490
  // src/engine/util/timer.ts
72469
72491
  var SystemTimer = class {
@@ -72690,6 +72712,9 @@ function decodeThreadItem(value) {
72690
72712
  const decoded = threadItemSchema.safeParse(value);
72691
72713
  return decoded.success ? decoded.data : null;
72692
72714
  }
72715
+ function messageQuestions(item) {
72716
+ return item.type === "agentMessage" ? (item.questions ?? []).map((question) => ({ options: question.options ?? [], question: question.title })) : [];
72717
+ }
72693
72718
  function reasoningText(item) {
72694
72719
  if (item.type !== "reasoning") {
72695
72720
  return null;
@@ -72697,6 +72722,10 @@ function reasoningText(item) {
72697
72722
  return boundedParagraphs(item.content.length > 0 ? item.content : item.summary, TOOL_OUTPUT_CHARACTER_LIMIT);
72698
72723
  }
72699
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
+
72700
72729
  // src/engine/acp/harness/codex/session-update.ts
72701
72730
  async function promptResultWithMessageId2(result, messageId) {
72702
72731
  try {
@@ -72753,810 +72782,278 @@ function userMessageUpdates(item, submitted) {
72753
72782
  });
72754
72783
  }
72755
72784
 
72756
- // src/engine/acp/harness/codex/borrowed-agent.ts
72757
- var REQUEST_TIMEOUT = 3e4;
72758
- var POLL_INTERVAL = 500;
72759
- var UNANSWERED_READ_LIMIT = 3;
72760
- var queueResponseSchema = external_exports.object({
72761
- queuedSubmission: external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })
72762
- });
72763
- var queuePageSchema = external_exports.object({
72764
- data: external_exports.array(external_exports.object({ id: external_exports.string().min(1), clientUserMessageId: external_exports.string().min(1) })).max(100),
72765
- nextCursor: external_exports.string().nullish()
72766
- });
72767
- function turnRunning(turn) {
72768
- return turn.status === "inProgress" || turn.status === "interrupted" && turn.completedAt == null;
72769
- }
72770
- function waitForNextPoll(timer, signal) {
72771
- signal.throwIfAborted();
72772
- return new Promise((resolve19, reject2) => {
72773
- const poll = timer.schedule(() => {
72774
- signal.removeEventListener("abort", abort);
72775
- resolve19();
72776
- }, POLL_INTERVAL);
72777
- const abort = () => {
72778
- poll.cancel();
72779
- reject2(signal.reason);
72780
- };
72781
- signal.addEventListener("abort", abort, { once: true });
72782
- });
72783
- }
72784
- var CodexBorrowedAcpAgent = class {
72785
- steeringSupported = false;
72786
- #client;
72787
- #threadId;
72788
- #emit;
72789
- #closed = new AbortController();
72790
- #seen = /* @__PURE__ */ new Map();
72791
- #pending = null;
72792
- #watch = null;
72793
- #lifecycle = { kind: "following" };
72794
- constructor(client2, threadId, emit) {
72795
- this.#client = client2;
72796
- this.#threadId = threadId;
72797
- this.#emit = emit;
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;
72798
72811
  }
72799
- initialize = async (signal) => {
72800
- queuePageSchema.parse(
72801
- await this.#client.request(
72802
- "thread/queue/list",
72803
- { threadId: this.#threadId },
72804
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72805
- )
72806
- );
72807
- await this.#apply(await this.#read(signal, true), true);
72808
- this.#watch = this.#follow();
72809
- };
72810
- #follow = async () => {
72811
- const signal = this.#closed.signal;
72812
- let unansweredReads = 0;
72813
- try {
72814
- for (; ; ) {
72815
- await waitForNextPoll(systemTimer, signal);
72816
- let pages;
72817
- try {
72818
- pages = await this.#read(signal, false);
72819
- } catch (cause) {
72820
- unansweredReads += 1;
72821
- if (!(cause instanceof DOMException && cause.name === "TimeoutError") || unansweredReads === UNANSWERED_READ_LIMIT) {
72822
- throw cause;
72823
- }
72824
- console.warn("Codex thread history read timed out; following continues", {
72825
- threadId: this.#threadId
72826
- });
72827
- continue;
72828
- }
72829
- unansweredReads = 0;
72830
- 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");
72831
72825
  }
72832
- } catch (cause) {
72833
- if (!signal.aborted) {
72834
- const error62 = new AcpExecutionError(
72835
- "The owning Codex session could not be followed",
72836
- { cause },
72837
- "codex_queue_follow_failed"
72838
- );
72839
- this.#lifecycle = { kind: "failed", error: error62 };
72840
- 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");
72841
72834
  }
72835
+ blocks.push({
72836
+ content: { data, mimeType, type: "image" },
72837
+ input: { type: "image", url: `data:${mimeType};base64,${data}` }
72838
+ });
72839
+ continue;
72842
72840
  }
72843
- };
72844
- #read = async (signal, baseline) => {
72845
- let cursor = null;
72846
- const pages = [];
72847
- const cursors = /* @__PURE__ */ new Set();
72848
- do {
72849
- const page = threadTurnsPageSchema.parse(
72850
- await this.#client.request(
72851
- "thread/turns/list",
72852
- {
72853
- threadId: this.#threadId,
72854
- limit: CODEX_HISTORY_TURN_PAGE_LIMIT,
72855
- sortDirection: "desc",
72856
- itemsView: "full",
72857
- ...cursor === null ? {} : { cursor }
72858
- },
72859
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72860
- )
72861
- );
72862
- pages.push(page.data);
72863
- cursor = page.nextCursor ?? null;
72864
- if (cursor !== null && cursors.has(cursor)) {
72865
- 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");
72866
72845
  }
72867
- if (cursor !== null) {
72868
- 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");
72869
72852
  }
72870
- } while (cursor !== null && (baseline || this.#pending !== null));
72871
- 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 } }
72872
72887
  };
72873
- #apply = async (pages, baseline) => {
72874
- for (const turns of [...pages].reverse()) {
72875
- for (const turn of [...turns].reverse()) {
72876
- let matches = false;
72877
- for (const raw of turn.items) {
72878
- const item = decodeThreadItem(raw);
72879
- if (item === null) {
72880
- continue;
72881
- }
72882
- const key = `${turn.id ?? ""}:${item.id}`;
72883
- if (item.type === "userMessage") {
72884
- const clientId = typeof raw === "object" && raw !== null ? Reflect.get(raw, "clientId") : void 0;
72885
- matches ||= clientId === this.#pending?.clientId;
72886
- if (this.#pending !== null && clientId === this.#pending.clientId) {
72887
- this.#pending.input = { kind: "identified", messageId: item.id };
72888
- }
72889
- const text2 = item.content.flatMap(
72890
- (block) => typeof block === "object" && block !== null && Reflect.get(block, "type") === "text" && typeof Reflect.get(block, "text") === "string" ? [String(Reflect.get(block, "text"))] : []
72891
- ).join("");
72892
- if (!baseline && !this.#seen.has(key)) {
72893
- for (const update of userMessageUpdates(
72894
- item,
72895
- this.#pending !== null && clientId === this.#pending.clientId ? this.#pending.content : void 0
72896
- )) {
72897
- await this.#emit(update);
72898
- }
72899
- }
72900
- this.#seen.set(key, text2);
72901
- continue;
72902
- }
72903
- if (item.type === "plan" && turnRunning(turn)) {
72904
- continue;
72905
- }
72906
- const previous = this.#seen.get(key);
72907
- const value = item.type === "agentMessage" || item.type === "plan" ? item.text : reasoningText(item) ?? JSON.stringify(item);
72908
- this.#seen.set(key, value);
72909
- if (baseline || value === previous) {
72910
- continue;
72911
- }
72912
- if (item.type === "agentMessage" || item.type === "plan" || reasoningText(item) !== null) {
72913
- const text2 = previous !== void 0 && value.startsWith(previous) ? value.slice(previous.length) : value;
72914
- if (text2.length > 0) {
72915
- await this.#emit({
72916
- sessionUpdate: item.type === "reasoning" ? "agent_thought_chunk" : "agent_message_chunk",
72917
- messageId: item.id,
72918
- content: { type: "text", text: text2 }
72919
- });
72920
- }
72921
- } else {
72922
- const update = toolCallUpdate(item, "snapshot");
72923
- if (update !== null) {
72924
- if (previous === void 0) {
72925
- await this.#emit({ ...update, sessionUpdate: "tool_call" });
72926
- } else {
72927
- await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
72928
- }
72929
- }
72930
- }
72931
- }
72932
- if (matches && turn.status !== void 0 && !turnRunning(turn)) {
72933
- if (turn.status === "failed") {
72934
- this.#pending?.completion.reject(
72935
- new AcpExecutionError("The owning Codex turn failed", {}, "codex_turn_failed")
72936
- );
72937
- } else {
72938
- this.#pending?.completion.resolve({
72939
- stopReason: turn.status === "interrupted" ? "cancelled" : "end_turn"
72940
- });
72941
- }
72942
- }
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
+ }))
72943
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();
72944
72941
  }
72942
+ this.#turn?.completion.reject(acpEndpointTerminationError(termination));
72943
+ this.#settleCompaction("cancelled");
72945
72944
  };
72946
- prompt = async (input2, signal, content) => {
72947
- signal.throwIfAborted();
72948
- if (this.#lifecycle.kind === "failed") {
72949
- throw this.#lifecycle.error;
72945
+ close = async () => {
72946
+ if (this.#turn !== null) {
72947
+ this.#turn.steeringContent.clear();
72950
72948
  }
72951
- if (this.#lifecycle.kind === "closed") {
72952
- 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;
72953
72961
  }
72954
- if (this.#pending !== null) {
72955
- 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");
72956
72995
  }
72957
- const pending = {
72958
- 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(),
72959
73015
  clientId: randomUUID7(),
72960
- completion: Promise.withResolvers(),
72961
- settled: Promise.withResolvers(),
72962
- input: { kind: "awaiting" }
73016
+ input: { kind: "awaiting" },
73017
+ turn: { id: "" }
72963
73018
  };
72964
- this.#pending = pending;
72965
- void pending.completion.promise.catch(() => {
72966
- });
72967
- const abort = () => pending.completion.reject(signal.reason);
72968
- signal.addEventListener("abort", abort, { once: true });
72969
- let outcome = "cancelled";
73019
+ this.#turn = turn;
72970
73020
  try {
72971
- const queued = queueResponseSchema.parse(
72972
- await this.#client.request(
72973
- "thread/queue/add",
72974
- {
72975
- threadId: this.#threadId,
72976
- input: input2,
72977
- clientUserMessageId: pending.clientId
72978
- },
72979
- AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
72980
- )
73021
+ await this.#appServer.request(
73022
+ "thread/compact/start",
73023
+ { threadId: this.#context.threadId() },
73024
+ AbortSignal.any([signal, AbortSignal.timeout(COMPACT_TIMEOUT_MILLISECONDS)])
72981
73025
  );
72982
- if (queued.queuedSubmission.clientUserMessageId !== pending.clientId) {
72983
- throw new AcpExecutionError(
72984
- "Codex queued an unexpected message",
72985
- {},
72986
- "invalid_native_session_response"
72987
- );
72988
- }
72989
- const result = await pending.completion.promise;
72990
- outcome = result.stopReason === "cancelled" ? "cancelled" : "completed";
72991
- 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
+ ]);
72992
73036
  } catch (cause) {
72993
- if (pending.input.kind === "identified" && !signal.aborted) {
72994
- 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
+ });
72995
73049
  }
73050
+ this.#turnSettledCompaction = false;
72996
73051
  throw cause;
72997
73052
  } finally {
72998
- signal.removeEventListener("abort", abort);
72999
- if (outcome === "cancelled") {
73000
- try {
73001
- await this.#removeQueuedInput(pending.clientId);
73002
- } catch (cause) {
73003
- console.error("The cancelled Codex queued input could not be removed", cause);
73004
- }
73005
- }
73006
- this.#pending = null;
73007
- pending.settled.resolve();
73008
- }
73009
- };
73010
- #removeQueuedInput = async (clientId) => {
73011
- const signal = AbortSignal.timeout(REQUEST_TIMEOUT);
73012
- let cursor = null;
73013
- const cursors = /* @__PURE__ */ new Set();
73014
- do {
73015
- const page = queuePageSchema.parse(
73016
- await this.#client.request(
73017
- "thread/queue/list",
73018
- { threadId: this.#threadId, limit: 100, ...cursor === null ? {} : { cursor } },
73019
- signal
73020
- )
73021
- );
73022
- for (const queued of page.data) {
73023
- if (queued.clientUserMessageId === clientId) {
73024
- await this.#client.request(
73025
- "thread/queue/delete",
73026
- { threadId: this.#threadId, queuedSubmissionId: queued.id },
73027
- signal
73028
- );
73029
- return;
73030
- }
73031
- }
73032
- cursor = page.nextCursor ?? null;
73033
- if (cursor !== null && cursors.has(cursor)) {
73034
- throw new AcpExecutionError("Codex repeated a queue cursor", {}, "invalid_native_session_response");
73035
- }
73036
- if (cursor !== null) {
73037
- cursors.add(cursor);
73038
- }
73039
- } while (cursor !== null);
73040
- };
73041
- nativeTurnId = () => null;
73042
- steer = async (_params, signal) => {
73043
- signal.throwIfAborted();
73044
- throw new AcpExecutionError("This Codex session only supports queued input", {}, "steering_unsupported");
73045
- };
73046
- // The reader connection cannot receive or control the owner's live turn.
73047
- onNotification = async (_method, _params) => {
73048
- };
73049
- onServerRequest = async (request) => {
73050
- this.#client.respondWithError(request.id, -32601, "Borrowed sessions cannot handle owner requests");
73051
- };
73052
- onTerminated = (termination) => {
73053
- const error62 = acpEndpointTerminationError(termination);
73054
- this.#lifecycle = { kind: "failed", error: error62 };
73055
- this.#pending?.completion.reject(error62);
73056
- this.#closed.abort();
73057
- };
73058
- // A remote Stop must never interrupt another client's owning turn.
73059
- compact = async (_signal) => {
73060
- throw new AcpExecutionError(
73061
- "This Codex session is attached read-only and cannot be compacted",
73062
- {},
73063
- "native_session_unsupported"
73064
- );
73065
- };
73066
- cancel = async () => {
73067
- const pending = this.#pending;
73068
- if (pending !== null) {
73069
- pending.completion.resolve({ stopReason: "cancelled" });
73070
- await pending.settled.promise;
73071
- }
73072
- };
73073
- close = async () => {
73074
- this.#lifecycle = { kind: "closed" };
73075
- this.#closed.abort();
73076
- await this.cancel();
73077
- await this.#watch;
73078
- };
73079
- };
73080
-
73081
- // src/engine/acp/harness/codex/history.ts
73082
- import { createHash as createHash2 } from "node:crypto";
73083
-
73084
- // src/engine/acp/content/raster.ts
73085
- import { basename as basename4, isAbsolute as isAbsolute9, normalize } from "node:path";
73086
- import { fileURLToPath } from "node:url";
73087
- var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
73088
- var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
73089
- var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
73090
- var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
73091
- var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
73092
- var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
73093
- var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
73094
- var LocalRasterImage = class {
73095
- mimeType;
73096
- name;
73097
- sourceUri;
73098
- constructor(name2, mimeType, sourceUri) {
73099
- this.mimeType = mimeType;
73100
- this.name = name2;
73101
- this.sourceUri = sourceUri;
73102
- }
73103
- base64 = async () => Buffer.from(await readFileBytes(this.sourceUri)).toString("base64");
73104
- };
73105
- function startsWith(bytes, signature, offset = 0) {
73106
- if (bytes.byteLength < offset + signature.byteLength) {
73107
- return false;
73108
- }
73109
- return signature.every((value, index2) => bytes[offset + index2] === value);
73110
- }
73111
- function sniffRasterMime(bytes) {
73112
- if (startsWith(bytes, PNG_SIGNATURE)) {
73113
- return "image/png";
73114
- }
73115
- if (startsWith(bytes, JPEG_SIGNATURE)) {
73116
- return "image/jpeg";
73117
- }
73118
- if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
73119
- return "image/gif";
73120
- }
73121
- if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
73122
- return "image/webp";
73123
- }
73124
- return null;
73125
- }
73126
- async function resolveCanonicalPath(requested, signal) {
73127
- signal.throwIfAborted();
73128
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize(requested) !== requested) {
73129
- return null;
73130
- }
73131
- try {
73132
- const target = await canonicalPath(requested);
73133
- signal.throwIfAborted();
73134
- if (!isAbsolute9(target) || normalize(target) !== target) {
73135
- return null;
73136
- }
73137
- return target;
73138
- } catch (cause) {
73139
- signal.throwIfAborted();
73140
- if (cause instanceof Error && cause.name === "AbortError") {
73141
- throw cause;
73142
- }
73143
- return null;
73144
- }
73145
- }
73146
- function parseLocalImageUri(uri) {
73147
- const trimmed = uri.trim();
73148
- if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
73149
- return null;
73150
- }
73151
- if (trimmed.startsWith("data:")) {
73152
- return null;
73153
- }
73154
- if (trimmed.startsWith("file:")) {
73155
- try {
73156
- const url2 = new URL(trimmed);
73157
- if (url2.protocol !== "file:" || url2.host.length > 0) {
73158
- return null;
73159
- }
73160
- return fileURLToPath(url2);
73161
- } catch {
73162
- return null;
73163
- }
73164
- }
73165
- if (!isAbsolute9(trimmed) && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
73166
- return null;
73167
- }
73168
- return trimmed;
73169
- }
73170
- async function readLocalRaster(uri, signal) {
73171
- signal.throwIfAborted();
73172
- const requested = parseLocalImageUri(uri);
73173
- if (requested === null) {
73174
- return null;
73175
- }
73176
- const target = await resolveCanonicalPath(requested, signal);
73177
- if (target === null) {
73178
- return null;
73179
- }
73180
- const targetMetadata = await readPathMetadata(target);
73181
- signal.throwIfAborted();
73182
- if (targetMetadata.kind !== "file" || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
73183
- return null;
73184
- }
73185
- const header = await readFileStart(target, 12);
73186
- signal.throwIfAborted();
73187
- const mimeType = sniffRasterMime(header);
73188
- if (mimeType === null) {
73189
- return null;
73190
- }
73191
- return new LocalRasterImage(basename4(target) || "Image", mimeType, target);
73192
- }
73193
-
73194
- // src/engine/acp/native-history/codex/history-images.ts
73195
- var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
73196
- var DATA_IMAGE_HEADER = /^data:(image\/[a-z+]+);base64,/;
73197
- var BASE_64 = /^[A-Za-z0-9+/]*={0,2}$/;
73198
- var SESSION_HISTORY_IMAGE_CHARACTER_LIMIT = 4e6;
73199
- function isRasterMime(value) {
73200
- return value === "image/png" || value === "image/jpeg" || value === "image/gif" || value === "image/webp";
73201
- }
73202
- function parseNativeHistoryImage(uri) {
73203
- const header = DATA_IMAGE_HEADER.exec(uri);
73204
- if (header === null) {
73205
- return null;
73206
- }
73207
- const mimeType = header[1] ?? "";
73208
- const data = uri.slice(header[0].length);
73209
- if (!isRasterMime(mimeType) || data.length < 4 || data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73210
- return null;
73211
- }
73212
- if (data.length % 4 !== 0 || !BASE_64.test(data)) {
73213
- return null;
73214
- }
73215
- return { data, mimeType, name: "" };
73216
- }
73217
- async function embedLocalHistoryImages(history, signal) {
73218
- if (history.status !== "available") {
73219
- return history;
73220
- }
73221
- const messages = [];
73222
- let imageCharacters = 0;
73223
- for (const message of history.messages) {
73224
- signal.throwIfAborted();
73225
- const resolved = await resolveMessageImages(message, imageCharacters, signal);
73226
- imageCharacters += (resolved.images ?? []).reduce((size, image) => size + image.data.length, 0);
73227
- messages.push(resolved);
73228
- }
73229
- return {
73230
- ...history,
73231
- messages
73232
- };
73233
- }
73234
- async function resolveMessageImages(message, usedCharacters, signal) {
73235
- const images = [...message.images ?? []];
73236
- let imageCharacters = images.reduce((size, image) => size + image.data.length, 0);
73237
- const text2 = await replaceImageMarkers(message.text, async (uri) => {
73238
- if (images.length >= 8 || usedCharacters + imageCharacters >= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73239
- return "[Image unavailable]";
73240
- }
73241
- const embedded = parseNativeHistoryImage(uri);
73242
- if (embedded !== null) {
73243
- if (usedCharacters + imageCharacters + embedded.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73244
- return "[Image unavailable]";
73245
- }
73246
- images.push({ ...embedded, name: `Image ${(images.length + 1).toString()}` });
73247
- imageCharacters += embedded.data.length;
73248
- return "";
73249
- }
73250
- const local = await readLocalRaster(uri, signal);
73251
- if (local === null) {
73252
- return "[Image unavailable]";
73253
- }
73254
- const data = await local.base64();
73255
- if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
73256
- return "[Image unavailable]";
73257
- }
73258
- images.push({
73259
- data,
73260
- mimeType: local.mimeType,
73261
- name: local.name
73262
- });
73263
- imageCharacters += data.length;
73264
- return "";
73265
- });
73266
- return {
73267
- ...message,
73268
- text: text2,
73269
- ...images.length > 0 ? { images } : {}
73270
- };
73271
- }
73272
- async function replaceImageMarkers(text2, replace) {
73273
- const matches = [...text2.matchAll(IMAGE_MARKER)];
73274
- if (matches.length === 0) {
73275
- return text2;
73276
- }
73277
- let cursor = 0;
73278
- let rewritten = "";
73279
- for (const match of matches) {
73280
- const index2 = match.index ?? 0;
73281
- rewritten += text2.slice(cursor, index2);
73282
- rewritten += await replace(match[1] ?? "");
73283
- cursor = index2 + match[0].length;
73284
- }
73285
- return `${rewritten}${text2.slice(cursor)}`;
73286
- }
73287
-
73288
- // src/engine/acp/harness/codex/owned-agent.ts
73289
- import { randomUUID as randomUUID8 } from "node:crypto";
73290
- import { setTimeout as delay } from "node:timers/promises";
73291
- var APPROVAL_REASON_CHARACTER_LIMIT = 500;
73292
- var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
73293
- var COMPACT_TIMEOUT_MILLISECONDS = 36e5;
73294
- var COMPACT_ITEM_WAIT_MILLISECONDS = 6e5;
73295
- var THREAD_NOTIFICATIONS = /* @__PURE__ */ new Set([
73296
- "item/agentMessage/delta",
73297
- "item/completed",
73298
- "item/reasoning/summaryTextDelta",
73299
- "item/reasoning/textDelta",
73300
- "item/started",
73301
- "thread/compacted",
73302
- "thread/name/updated",
73303
- "thread/settings/updated",
73304
- "turn/completed",
73305
- "turn/plan/updated",
73306
- "turn/started"
73307
- ]);
73308
- var APPROVAL_OPTIONS = Object.freeze([
73309
- { kind: "allow_once", name: "Allow once", optionId: "accept" },
73310
- { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
73311
- { kind: "reject_once", name: "Deny", optionId: "decline" }
73312
- ]);
73313
- function permissionDecision(optionId) {
73314
- if (optionId === "accept" || optionId === "acceptForSession" || optionId === "decline") {
73315
- return optionId;
73316
- }
73317
- return "cancel";
73318
- }
73319
- function steeringPrompt(prompt) {
73320
- const blocks = [];
73321
- for (const block of prompt) {
73322
- if (typeof block !== "object" || block === null) {
73323
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73324
- }
73325
- const type = Reflect.get(block, "type");
73326
- if (type === "text") {
73327
- const text2 = Reflect.get(block, "text");
73328
- if (typeof text2 !== "string") {
73329
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73330
- }
73331
- blocks.push({ content: { text: text2, type: "text" }, input: { text: text2, text_elements: [], type: "text" } });
73332
- continue;
73333
- }
73334
- if (type === "image") {
73335
- const data = Reflect.get(block, "data");
73336
- const mimeType = Reflect.get(block, "mimeType");
73337
- if (typeof data !== "string" || typeof mimeType !== "string") {
73338
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73339
- }
73340
- blocks.push({
73341
- content: { data, mimeType, type: "image" },
73342
- input: { type: "image", url: `data:${mimeType};base64,${data}` }
73343
- });
73344
- continue;
73345
- }
73346
- if (type === "resource") {
73347
- const resource = Reflect.get(block, "resource");
73348
- if (typeof resource !== "object" || resource === null) {
73349
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73350
- }
73351
- const uri = Reflect.get(resource, "uri");
73352
- const text2 = Reflect.get(resource, "text");
73353
- const blob2 = Reflect.get(resource, "blob");
73354
- const mimeType = Reflect.get(resource, "mimeType");
73355
- 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") {
73356
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73357
- }
73358
- blocks.push({
73359
- content: typeof text2 === "string" ? {
73360
- resource: { text: text2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
73361
- type: "resource"
73362
- } : {
73363
- resource: { blob: blob2, uri, ...typeof mimeType === "string" ? { mimeType } : {} },
73364
- type: "resource"
73365
- },
73366
- input: { text: text2 ?? "", text_elements: [], type: "text" }
73367
- });
73368
- continue;
73369
- }
73370
- if (type === "resource_link") {
73371
- const name2 = Reflect.get(block, "name");
73372
- const uri = Reflect.get(block, "uri");
73373
- if (typeof name2 !== "string" || typeof uri !== "string") {
73374
- throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
73375
- }
73376
- blocks.push({
73377
- content: { name: name2, type: "resource_link", uri },
73378
- input: { text: `Resource: ${uri}`, text_elements: [], type: "text" }
73379
- });
73380
- continue;
73381
- }
73382
- throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
73383
- }
73384
- return blocks;
73385
- }
73386
- function agentMessageUpdate(messageId, text2) {
73387
- return {
73388
- content: { text: text2, type: "text" },
73389
- messageId,
73390
- sessionUpdate: "agent_message_chunk"
73391
- };
73392
- }
73393
- function userInputSchema(questions) {
73394
- const properties = {};
73395
- const required2 = [];
73396
- for (const question of questions) {
73397
- required2.push(question.id);
73398
- properties[question.id] = {
73399
- description: question.question,
73400
- title: question.header,
73401
- type: "string",
73402
- ...question.options == null || question.options.length === 0 ? {} : {
73403
- oneOf: question.options.map((option) => ({
73404
- const: option.label,
73405
- description: option.description,
73406
- title: option.label
73407
- }))
73408
- }
73409
- };
73410
- }
73411
- return { properties, required: required2, type: "object" };
73412
- }
73413
- var CodexOwnedAcpAgent = class {
73414
- steeringSupported = true;
73415
- #context;
73416
- #appServer;
73417
- #settings;
73418
- #streamedReasoningSources = /* @__PURE__ */ new Map();
73419
- #agentMessages = /* @__PURE__ */ new Map();
73420
- #turn = null;
73421
- #nativeTurnId = null;
73422
- #runningCommands = /* @__PURE__ */ new Map();
73423
- #updateTail = Promise.resolve();
73424
- // The compaction whose contextCompaction item/started has been reported but whose
73425
- // terminal state has not. Exactly one may be open: Codex compacts sequentially,
73426
- // and a second start cannot begin before the first settles. Cleared only through
73427
- // #finishCompaction, which emits the terminal update — turn failure,
73428
- // interruption, and endpoint loss all settle it so no client is left with a
73429
- // compaction stuck in_progress.
73430
- #openCompaction = null;
73431
- // Set when the turn machinery (turn/completed or cancel) settled this turn's
73432
- // compaction, so the compact error path does not report a second terminal
73433
- // update for the same failure.
73434
- #turnSettledCompaction = false;
73435
- constructor(context) {
73436
- this.#context = context;
73437
- this.#appServer = context.client;
73438
- this.#settings = context.settings;
73439
- }
73440
- nativeTurnId = () => this.#nativeTurnId;
73441
- onTerminated = (termination) => {
73442
- if (this.#turn !== null) {
73443
- this.#turn.steeringContent.clear();
73444
- }
73445
- this.#turn?.completion.reject(acpEndpointTerminationError(termination));
73446
- this.#settleCompaction("cancelled");
73447
- };
73448
- close = async () => {
73449
- if (this.#turn !== null) {
73450
- this.#turn.steeringContent.clear();
73451
- }
73452
- this.#turn?.completion.reject(new AcpExecutionError("The Codex endpoint is closed", {}, "acp_endpoint_closed"));
73453
- this.#settleCompaction("cancelled");
73454
- };
73455
- /** Emits the terminal compaction update for the open compaction, if any, and
73456
- * wakes a manual /compact waiting on it. A terminal update may patch an
73457
- * already-terminal entity (the app-server can race an item/completed past a
73458
- * cancellation), which clients merge idempotently. The wake rides the enqueued
73459
- * emission so the waiting prompt's response never precedes the update. */
73460
- #settleCompaction = (status, error62) => {
73461
- const open6 = this.#openCompaction;
73462
- if (open6 === null) {
73463
- return null;
73464
- }
73465
- const update = {
73466
- compactionId: open6.compactionId,
73467
- ...status === "failed" && error62 !== void 0 ? { error: error62 } : {},
73468
- sessionUpdate: "compaction_update",
73469
- status
73470
- };
73471
- this.#finishCompaction(async () => {
73472
- await this.#context.emit(update);
73473
- });
73474
- return open6;
73475
- };
73476
- /** Clears the tracked compaction and emits the terminal update. Used by both
73477
- * #settleCompaction and the item/completed handler, which emits its own
73478
- * terminal update. */
73479
- #finishCompaction = (emit) => {
73480
- this.#openCompaction = null;
73481
- void this.#enqueue(emit).catch((cause) => {
73482
- console.error("The Codex compaction settlement could not be delivered", cause);
73483
- });
73484
- };
73485
- /** Manual /compact: drives thread/compact/start, which the app-server executes
73486
- * as its own turn. The turn is registered like a prompt's so every terminal
73487
- * path is owned: turn/completed(failed) settles the open compaction as failed
73488
- * and rejects, turn/completed(interrupted) and Stop settle it as cancelled,
73489
- * and endpoint loss settles it through onTerminated. The contextCompaction
73490
- * item the server streams is the lifecycle clients see — started/completed
73491
- * under the item's id — and its completed resolves the wait. A bounded wait
73492
- * guards servers that accept the compact but never report a result; expiry is
73493
- * a failure, never a success. */
73494
- compact = async (signal) => {
73495
- signal.throwIfAborted();
73496
- if (this.#turn !== null) {
73497
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
73498
- }
73499
- if (this.#openCompaction !== null) {
73500
- throw new AcpExecutionError(
73501
- "Another compaction is already running in this conversation",
73502
- {},
73503
- "session_busy"
73504
- );
73505
- }
73506
- const completion = Promise.withResolvers();
73507
- void completion.promise.catch(() => {
73508
- });
73509
- const aborted2 = () => {
73510
- completion.reject(signal.reason);
73511
- };
73512
- signal.addEventListener("abort", aborted2, { once: true });
73513
- const waitExpired = new AbortController();
73514
- const turn = {
73515
- completion,
73516
- content: [],
73517
- steeringContent: /* @__PURE__ */ new Map(),
73518
- clientId: randomUUID8(),
73519
- input: { kind: "awaiting" },
73520
- turn: { id: "" }
73521
- };
73522
- this.#turn = turn;
73523
- try {
73524
- await this.#appServer.request(
73525
- "thread/compact/start",
73526
- { threadId: this.#context.threadId() },
73527
- AbortSignal.any([signal, AbortSignal.timeout(COMPACT_TIMEOUT_MILLISECONDS)])
73528
- );
73529
- return await Promise.race([
73530
- completion.promise,
73531
- delay(COMPACT_ITEM_WAIT_MILLISECONDS, void 0, { signal: waitExpired.signal }).then(() => {
73532
- throw new AcpExecutionError(
73533
- "The Codex compaction did not report a result",
73534
- {},
73535
- "codex_compaction_unreported"
73536
- );
73537
- })
73538
- ]);
73539
- } catch (cause) {
73540
- signal.throwIfAborted();
73541
- const open6 = this.#settleCompaction("failed", cause instanceof Error ? cause.message : String(cause));
73542
- if (open6 === null && !this.#turnSettledCompaction) {
73543
- const compactionId = randomUUID8();
73544
- await this.#enqueue(async () => {
73545
- await this.#context.emit({
73546
- compactionId,
73547
- error: cause instanceof Error ? cause.message : String(cause),
73548
- sessionUpdate: "compaction_update",
73549
- status: "failed"
73550
- });
73551
- });
73552
- }
73553
- this.#turnSettledCompaction = false;
73554
- throw cause;
73555
- } finally {
73556
- signal.removeEventListener("abort", aborted2);
73557
- waitExpired.abort();
73558
- if (this.#turn === turn) {
73559
- this.#turn = null;
73053
+ signal.removeEventListener("abort", aborted2);
73054
+ waitExpired.abort();
73055
+ if (this.#turn === turn) {
73056
+ this.#turn = null;
73560
73057
  }
73561
73058
  }
73562
73059
  };
@@ -73718,7 +73215,7 @@ var CodexOwnedAcpAgent = class {
73718
73215
  return;
73719
73216
  }
73720
73217
  await this.#enqueue(async () => {
73721
- await this.#context.emit(agentMessageUpdate(item.id, item.text));
73218
+ await this.#context.emit(agentMessageUpdate(item.id, item.text, messageQuestions(item)));
73722
73219
  });
73723
73220
  return;
73724
73221
  }
@@ -73894,170 +73391,734 @@ var CodexOwnedAcpAgent = class {
73894
73391
  this.#appServer.respond(request.id, { action: response2.action });
73895
73392
  return;
73896
73393
  }
73897
- const response = await connection.client.request(
73898
- methods.client.elicitation.create,
73899
- {
73900
- message: params.message,
73901
- mode: "form",
73902
- requestedSchema: params.requestedSchema ?? { properties: {}, required: [], type: "object" },
73903
- sessionId: this.#context.threadId()
73904
- },
73905
- { cancellationSignal: signal }
73906
- );
73907
- const content = response.action === "accept" ? Reflect.get(response, "content") ?? null : null;
73908
- 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
+ }
73909
73765
  };
73910
73766
  prompt = async (input2, signal, content) => {
73911
73767
  signal.throwIfAborted();
73912
- if (this.#turn !== null) {
73913
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
73768
+ if (this.#lifecycle.kind === "failed") {
73769
+ throw this.#lifecycle.error;
73914
73770
  }
73915
- const completion = Promise.withResolvers();
73916
- void completion.promise.catch(() => {
73917
- });
73918
- const aborted2 = () => {
73919
- completion.reject(signal.reason);
73920
- void this.#context.close().catch((cause) => {
73921
- console.error("The cancelled Codex endpoint could not release its process tree", cause);
73922
- });
73923
- };
73924
- signal.addEventListener("abort", aborted2, { once: true });
73925
- const turn = {
73926
- 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 = {
73927
73778
  content,
73928
- steeringContent: /* @__PURE__ */ new Map(),
73929
73779
  clientId: randomUUID8(),
73780
+ completion: Promise.withResolvers(),
73781
+ settled: Promise.withResolvers(),
73930
73782
  input: { kind: "awaiting" },
73931
- turn: { id: "" }
73783
+ delegation: Promise.resolve()
73932
73784
  };
73933
- this.#agentMessages.clear();
73934
- this.#streamedReasoningSources.clear();
73935
- this.#turn = turn;
73936
- 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";
73937
73791
  try {
73938
- const started = turnSchema.parse(
73939
- (await this.#appServer.request(
73940
- "turn/start",
73792
+ const queued = queueResponseSchema.parse(
73793
+ await this.#client.request(
73794
+ "thread/queue/add",
73941
73795
  {
73942
- ...this.#settings.turnParameters(),
73796
+ threadId: this.#threadId,
73943
73797
  input: input2,
73944
- clientUserMessageId: turn.clientId,
73945
- threadId: this.#context.threadId()
73798
+ clientUserMessageId: pending.clientId
73946
73799
  },
73947
- signal
73948
- )).turn
73800
+ AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT)])
73801
+ )
73949
73802
  );
73950
- if (this.#turn === turn) {
73951
- turn.turn.id = started.id;
73952
- 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
+ );
73953
73809
  }
73954
- try {
73955
- const result = await completion.promise;
73956
- return turn.input.kind === "identified" ? await promptResultWithMessageId2(Promise.resolve(result), turn.input.messageId) : result;
73957
- } catch (cause) {
73958
- if (turn.input.kind === "identified" && !signal.aborted) {
73959
- return await promptResultWithMessageId2(Promise.reject(cause), turn.input.messageId);
73960
- }
73961
- 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);
73962
73817
  }
73818
+ throw cause;
73963
73819
  } finally {
73964
- signal.removeEventListener("abort", aborted2);
73965
- if (this.#turn === turn) {
73966
- turn.steeringContent.clear();
73967
- this.#turn = null;
73968
- this.#agentMessages.clear();
73969
- 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
+ }
73970
73827
  }
73828
+ this.#pending = null;
73829
+ pending.settled.resolve();
73971
73830
  }
73972
73831
  };
73973
- steer = async (params, signal) => {
73974
- if (typeof params !== "object" || params === null) {
73975
- 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;
73976
73898
  }
73977
- const sessionId = Reflect.get(params, "sessionId");
73978
- const prompt = Reflect.get(params, "prompt");
73979
- if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
73980
- 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;
73981
73902
  }
73982
- const active = this.#turn;
73983
- if (sessionId !== this.#context.threadId() || active === null || active.turn.id.length === 0) {
73984
- 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;
73985
73911
  }
73986
- const steering = steeringPrompt(prompt);
73987
- if (steering.length === 0) {
73988
- 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;
73989
73971
  }
73990
- if (active.steeringContent.size >= 100) {
73991
- 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;
73992
73977
  }
73993
- const submitted = steering.map((block) => block.content);
73994
- const clientId = randomUUID8();
73995
- active.steeringContent.set(clientId, submitted);
73996
- 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:")) {
73997
73990
  try {
73998
- const response = turnSteerResponseSchema.parse(
73999
- await this.#appServer.request(
74000
- "turn/steer",
74001
- {
74002
- expectedTurnId: active.turn.id,
74003
- clientUserMessageId: clientId,
74004
- input: steering.map((block) => block.input),
74005
- threadId: this.#context.threadId()
74006
- },
74007
- bounded
74008
- )
74009
- );
74010
- if (response.turnId !== active.turn.id) {
74011
- 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;
74012
73994
  }
74013
- return { outcome: "injected" };
74014
- } catch (cause) {
74015
- active.steeringContent.delete(clientId);
74016
- throw cause;
73995
+ return fileURLToPath(url2);
73996
+ } catch {
73997
+ return null;
74017
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
74018
74067
  };
74019
- cancel = async () => {
74020
- const turn = this.#turn;
74021
- if (turn === null) {
74022
- 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]";
74023
74075
  }
74024
- this.#turn = null;
74025
- turn.steeringContent.clear();
74026
- if (turn.turn.id.length > 0) {
74027
- try {
74028
- await this.#appServer.request(
74029
- "turn/interrupt",
74030
- { threadId: this.#context.threadId(), turnId: turn.turn.id },
74031
- AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)
74032
- );
74033
- } 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]";
74034
74080
  }
74081
+ images.push({ ...embedded, name: `Image ${(images.length + 1).toString()}` });
74082
+ imageCharacters += embedded.data.length;
74083
+ return "";
74035
74084
  }
74036
- this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
74037
- turn.completion.resolve({ stopReason: "cancelled" });
74038
- };
74039
- #completeTurn = async (turn) => {
74040
- const active = this.#turn;
74041
- if (active === null || active.turn.id !== turn.id) {
74042
- return;
74043
- }
74044
- active.steeringContent.clear();
74045
- await this.#updateTail;
74046
- if (turn.status === "failed") {
74047
- this.#turnSettledCompaction = this.#settleCompaction("failed", turn.error?.message ?? "The Codex turn failed") !== null;
74048
- active.completion.reject(
74049
- new AcpExecutionError(turn.error?.message ?? "The Codex turn failed", {}, "codex_turn_failed")
74050
- );
74051
- return;
74085
+ const local = await readLocalRaster(uri, signal);
74086
+ if (local === null) {
74087
+ return "[Image unavailable]";
74052
74088
  }
74053
- if (turn.status === "interrupted") {
74054
- this.#turnSettledCompaction = this.#settleCompaction("cancelled") !== null;
74055
- active.completion.resolve({ stopReason: "cancelled" });
74056
- return;
74089
+ const data = await local.base64();
74090
+ if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
74091
+ return "[Image unavailable]";
74057
74092
  }
74058
- 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 } : {}
74059
74105
  };
74060
- };
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
+ }
74061
74122
 
74062
74123
  // src/engine/acp/harness/codex/history.ts
74063
74124
  async function replayCodexHistory(client2, threadId, emit, signal) {
@@ -74126,7 +74187,7 @@ async function replayCodexHistory(client2, threadId, emit, signal) {
74126
74187
  }
74127
74188
  }
74128
74189
  } else if (item.type === "agentMessage" || item.type === "plan") {
74129
- await emit(agentMessageUpdate(item.id, item.text));
74190
+ await emit(agentMessageUpdate(item.id, item.text, messageQuestions(item)));
74130
74191
  } else if (item.type === "reasoning") {
74131
74192
  const text2 = reasoningText(item);
74132
74193
  if (text2 !== null && text2.length > 0) {
@@ -74622,11 +74683,13 @@ var CodexAcpAgent = class {
74622
74683
  #settings;
74623
74684
  #onSessionUpdate;
74624
74685
  #onBackgroundActivity;
74686
+ #onPromptDelegation;
74625
74687
  #nativeSessionId = "";
74626
74688
  #sessionAgent;
74627
74689
  constructor(options) {
74628
74690
  this.#onSessionUpdate = options.onSessionUpdate;
74629
74691
  this.#onBackgroundActivity = options.onBackgroundActivity;
74692
+ this.#onPromptDelegation = options.onPromptDelegation;
74630
74693
  this.#appServer = new CodexAppServerClient({
74631
74694
  command: options.command,
74632
74695
  cwd: options.cwd,
@@ -74699,7 +74762,7 @@ var CodexAcpAgent = class {
74699
74762
  await this.#replaySavedHistory(context.signal);
74700
74763
  this.#advertiseCompactCommand();
74701
74764
  return {
74702
- _meta: { steering: { supported: this.#sessionAgent.steeringSupported } },
74765
+ _meta: this.#sessionMeta(),
74703
74766
  configOptions: this.#settings.configOptions()
74704
74767
  };
74705
74768
  }).onRequest(methods.agent.session.fork, async (context) => {
@@ -74725,7 +74788,7 @@ var CodexAcpAgent = class {
74725
74788
  await this.#resume(context.params.sessionId, context.params.cwd, context.signal);
74726
74789
  this.#advertiseCompactCommand();
74727
74790
  return {
74728
- _meta: { steering: { supported: this.#sessionAgent.steeringSupported } },
74791
+ _meta: this.#sessionMeta(),
74729
74792
  configOptions: this.#settings.configOptions()
74730
74793
  };
74731
74794
  }).onRequest(methods.agent.session.prompt, async (context) => {
@@ -74837,7 +74900,9 @@ var CodexAcpAgent = class {
74837
74900
  AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS3)])
74838
74901
  )
74839
74902
  );
74840
- const queued = new CodexBorrowedAcpAgent(this.#appServer, threadId, this.#emit);
74903
+ const queued = new CodexBorrowedAcpAgent(this.#appServer, threadId, this.#emit, async (stage) => {
74904
+ await this.#onPromptDelegation?.(stage);
74905
+ });
74841
74906
  await queued.initialize(signal);
74842
74907
  this.#nativeSessionId = threadId;
74843
74908
  this.#settings.selectRestoredThread({
@@ -74853,6 +74918,11 @@ var CodexAcpAgent = class {
74853
74918
  this.#settings.selectRestoredThread(resumed);
74854
74919
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, signal);
74855
74920
  };
74921
+ /** What the session response tells Mobius about the session behavior selected while opening it. */
74922
+ #sessionMeta = () => ({
74923
+ steering: { supported: this.#sessionAgent.steeringSupported },
74924
+ codex: { runsTurns: this.#sessionAgent.runsTurns }
74925
+ });
74856
74926
  // ACP load requires chronological replay. Resume only restores execution;
74857
74927
  // native pages supply history without a single full-transcript response.
74858
74928
  #replaySavedHistory = async (signal) => {
@@ -74897,7 +74967,8 @@ var CodexAgentConnection = class extends EndpointAgentConnection {
74897
74967
  cwd: options.cwd,
74898
74968
  environment: options.environment,
74899
74969
  onSessionUpdate: options.client.onUpdate,
74900
- onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity)
74970
+ onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
74971
+ onPromptDelegation: async (stage) => await options.onPromptDelegation?.(stage)
74901
74972
  });
74902
74973
  super(endpoint, options.client);
74903
74974
  }
@@ -80221,6 +80292,24 @@ function applyConfigurationChanges(base, changes) {
80221
80292
  }
80222
80293
 
80223
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
+ }
80224
80313
  var AdapterSessionConnection = class {
80225
80314
  #connection;
80226
80315
  #onBackgroundActivity;
@@ -80250,13 +80339,8 @@ var AdapterSessionConnection = class {
80250
80339
  signal.throwIfAborted();
80251
80340
  const update = externalized.agent;
80252
80341
  for (const eventUpdate of externalized.events) {
80253
- const backgroundTask = update._meta?.["mobius.backgroundTask"];
80254
80342
  const payload = decodeAcpSessionUpdate(
80255
- JSON.stringify(
80256
- normalizeEvent(
80257
- (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") && backgroundTask !== void 0 && typeof eventUpdate === "object" && eventUpdate !== null ? { ...eventUpdate, backgroundTask } : eventUpdate
80258
- )
80259
- )
80343
+ JSON.stringify(normalizeEvent(withMobiusFields(update, eventUpdate)))
80260
80344
  );
80261
80345
  let event;
80262
80346
  switch (update.sessionUpdate) {
@@ -80343,6 +80427,11 @@ var AdapterSessionConnection = class {
80343
80427
  }
80344
80428
  this.#backgroundActivity = activity;
80345
80429
  this.#onBackgroundActivity(activity);
80430
+ },
80431
+ onPromptDelegation: async (stage) => {
80432
+ if (!this.#lifetime.signal.aborted) {
80433
+ await options.onPromptDelegation?.(stage);
80434
+ }
80346
80435
  }
80347
80436
  });
80348
80437
  }
@@ -80522,6 +80611,7 @@ var AcpExecutionConnections = class {
80522
80611
  ...params.scope.externalizeUpdate === void 0 ? {} : { externalizeUpdate: params.scope.externalizeUpdate },
80523
80612
  onEvent: (event) => params.onSessionEvent(connection.events.sessionId(), event),
80524
80613
  ...params.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: params.onBackgroundActivity },
80614
+ ...params.onPromptDelegation === void 0 ? {} : { onPromptDelegation: params.onPromptDelegation },
80525
80615
  interactions: params.interactions
80526
80616
  },
80527
80617
  this.#externalizer,
@@ -80594,6 +80684,8 @@ var AcpExecutionConnections = class {
80594
80684
  }
80595
80685
  return session;
80596
80686
  };
80687
+ /** The open writer's connection for this native session, if any. */
80688
+ connection = (target) => this.#find(target)?.connection;
80597
80689
  cancel = async ({ signal, ...target }) => {
80598
80690
  const bounded = AbortSignal.any([signal, AbortSignal.timeout(3e4)]);
80599
80691
  bounded.throwIfAborted();
@@ -87247,11 +87339,15 @@ function fitCodexToolEvent(event) {
87247
87339
  }
87248
87340
 
87249
87341
  // src/engine/acp/adapter/codex/adapter.ts
87342
+ var sessionTurnOwnershipSchema = external_exports.object({
87343
+ _meta: external_exports.object({ codex: external_exports.object({ runsTurns: external_exports.boolean() }).optional() }).optional()
87344
+ });
87250
87345
  var CodexAdapter = class {
87251
87346
  #agent;
87252
87347
  #queryProcesses;
87253
87348
  #connector;
87254
87349
  #executionConnections;
87350
+ #queueingConnections = /* @__PURE__ */ new WeakSet();
87255
87351
  #dependencies;
87256
87352
  #contentExternalizer;
87257
87353
  #previewCache = null;
@@ -87329,6 +87425,7 @@ var CodexAdapter = class {
87329
87425
  "ACP agent exited while resuming a session",
87330
87426
  signal
87331
87427
  );
87428
+ this.#recordTurnOwnership(connection, response);
87332
87429
  return normalizeOpenedSession(execution, nativeSessionId, response, signal);
87333
87430
  });
87334
87431
  openSessionWithReplay = (params) => this.#executionConnections.withConnection(this.#executionParams(params), async (execution, signal) => {
@@ -87345,12 +87442,23 @@ var CodexAdapter = class {
87345
87442
  signal
87346
87443
  );
87347
87444
  await connection.race(connection.events.drained(), "ACP agent exited while loading a session", signal);
87445
+ this.#recordTurnOwnership(connection, response);
87348
87446
  return normalizeOpenedSession(execution, nativeSessionId, response, signal);
87349
87447
  });
87350
87448
  cancel = async (params) => {
87449
+ const connection = this.#executionConnections.connection(params);
87450
+ if (connection !== void 0 && this.#queueingConnections.has(connection)) {
87451
+ return await this.#executionConnections.cancel(params);
87452
+ }
87351
87453
  await this.#executionConnections.closeSession(params);
87352
87454
  return "closed";
87353
87455
  };
87456
+ /** A connection keeps the turn ownership its harness chose while opening the thread. */
87457
+ #recordTurnOwnership = (connection, response) => {
87458
+ if (sessionTurnOwnershipSchema.parse(response)._meta?.codex?.runsTurns === false) {
87459
+ this.#queueingConnections.add(connection);
87460
+ }
87461
+ };
87354
87462
  closeSession = (...args) => this.#executionConnections.closeSession(...args);
87355
87463
  releaseSession = (params) => this.#executionConnections.releaseSession(params);
87356
87464
  // Codex admits one active writer per thread; another client borrows the thread instead.
@@ -87432,7 +87540,9 @@ var CodexAdapter = class {
87432
87540
  for (const event of externalized.events) {
87433
87541
  events.push({
87434
87542
  type: "acp",
87435
- payload: decodeAcpSessionUpdate(JSON.stringify(fitCodexToolEvent(event)))
87543
+ payload: decodeAcpSessionUpdate(
87544
+ JSON.stringify(fitCodexToolEvent(withMobiusFields(update, event)))
87545
+ )
87436
87546
  });
87437
87547
  }
87438
87548
  },
@@ -89997,6 +90107,8 @@ var AgentSession = class _AgentSession {
89997
90107
  }
89998
90108
  hasBackgroundActivity = () => this.#backgroundActivity !== "none";
89999
90109
  #backgroundActivity = "none";
90110
+ /** The command whose prompt the Agent is running, which only the Agent can report as delegated. */
90111
+ #delegableCommandId = null;
90000
90112
  #modelEffort = null;
90001
90113
  #scope;
90002
90114
  #subscriber;
@@ -90076,6 +90188,15 @@ var AgentSession = class _AgentSession {
90076
90188
  void this.#recordNativeHistoryRevision();
90077
90189
  }
90078
90190
  },
90191
+ onPromptDelegation: async (stage) => {
90192
+ const commandId = this.#delegableCommandId;
90193
+ if (commandId !== null) {
90194
+ await this.recordLifecycleEvent({
90195
+ payload: { commandId, kind: "prompt.delegated", stage },
90196
+ type: "lifecycle-metadata"
90197
+ });
90198
+ }
90199
+ },
90079
90200
  interactions: {
90080
90201
  onPermission: this.#interactions.onPermission,
90081
90202
  onElicitation: this.#interactions.onElicitation,
@@ -90527,10 +90648,15 @@ var AgentSession = class _AgentSession {
90527
90648
  type: "lifecycle-metadata"
90528
90649
  });
90529
90650
  }
90651
+ this.#delegableCommandId = lifecycle === void 0 ? null : options.commandId;
90530
90652
  try {
90531
- const result = await this.#writeNativeHistory(
90532
- async () => await this.#adapter.prompt({ ...this.#target(), content: options, signal: options.signal })
90533
- );
90653
+ const result = await this.#writeNativeHistory(async () => {
90654
+ try {
90655
+ return await this.#adapter.prompt({ ...this.#target(), content: options, signal: options.signal });
90656
+ } finally {
90657
+ this.#delegableCommandId = null;
90658
+ }
90659
+ });
90534
90660
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
90535
90661
  if (lifecycle !== void 0) {
90536
90662
  const messageId = result._meta?.messageId;
@@ -97749,4 +97875,4 @@ export {
97749
97875
  * MIT Licensed
97750
97876
  *)
97751
97877
  */
97752
- //# sourceMappingURL=chunk-JRH5V326.js.map
97878
+ //# sourceMappingURL=chunk-RWCLUO5M.js.map