openmausbot 0.1.58 → 0.1.60

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.
@@ -8,7 +8,7 @@
8
8
  // codex-cli 0.144.4 by agentcal.
9
9
  //
10
10
  // resumeCursor is the codex thread id; a later turn tries thread/resume
11
- // and falls back to a fresh thread/start.
11
+ // and preserves that history or reports a failed resume.
12
12
  import { existsSync } from "node:fs";
13
13
  import { homedir } from "node:os";
14
14
  import { stripWorkspaceCredentialEnv } from "../config.js";
@@ -22,6 +22,7 @@ import { codexLocalProviderArgs } from "./local-inject.js";
22
22
  import { augmentedPath, splitCliString } from "../env-path.js";
23
23
  import { classifyError, computeBackoff, RETRY_MAX_ATTEMPTS } from "./retry.js";
24
24
  import { appendNative } from "./native.js";
25
+ import { codexDeveloperInstructions, syncCodexInstructions } from "./codex-instructions.js";
25
26
  export { decodeCodexSelection, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.js";
26
27
  const DRIVER_KIND = "codex";
27
28
  const ASTRA_MODEL_ID = "gpt-6-astra";
@@ -300,18 +301,24 @@ function permissionProfileUnsupported(error) {
300
301
  const message = error instanceof Error ? error.message : String(error);
301
302
  return /(?:experimental api|invalid params|unknown field|unknown.*permissions|permissions.*(?:unsupported|sandbox)|cannot.*permissions)/i.test(message);
302
303
  }
303
- /** Keep private host paths out of diagnostics while preserving enough of the
304
- * app-server input shape to debug image delivery. The unmodified request is
304
+ /** Keep native instructions and private host paths out of diagnostics while
305
+ * preserving enough of the input shape to debug delivery. The unmodified request is
305
306
  * still written to the provider immediately after this log copy is made. */
306
307
  function codexNativeLogMessage(message) {
307
308
  if (!message || typeof message !== "object" || Array.isArray(message))
308
309
  return message;
309
310
  const record = message;
310
- if (record.method !== "turn/start")
311
- return message;
312
311
  const params = record.params;
313
312
  if (!params || typeof params !== "object" || Array.isArray(params))
314
313
  return message;
314
+ if (record.method === "thread/start" || record.method === "thread/resume") {
315
+ return { ...record, params: { ...params, developerInstructions: "[developer instructions omitted]" } };
316
+ }
317
+ if (record.method === "thread/inject_items") {
318
+ return { ...record, params: { ...params, items: "[developer instruction update omitted]" } };
319
+ }
320
+ if (record.method !== "turn/start")
321
+ return message;
315
322
  const input = params.input;
316
323
  if (!Array.isArray(input))
317
324
  return message;
@@ -547,11 +554,13 @@ export const CodexDriver = {
547
554
  });
548
555
  send({ jsonrpc: "2.0", id, method, params });
549
556
  });
557
+ let stopping;
558
+ const terminate = () => stopping ??= killCliTree(child);
550
559
  const stop = () => {
551
560
  stopRequested = true;
552
- killCliTree(child);
561
+ return terminate();
553
562
  };
554
- const settle = (ok, stopReason) => {
563
+ const settle = async (ok, stopReason) => {
555
564
  if (state.settled)
556
565
  return;
557
566
  state.settled = true;
@@ -560,9 +569,22 @@ export const CodexDriver = {
560
569
  for (const p of rpcPending.values())
561
570
  p.reject(new Error("turn settled"));
562
571
  rpcPending.clear();
563
- active.delete(threadId);
564
- emit({ ...base(threadId, turnId), type: "turn.completed", ok, stopReason, cost: null, ...(state.usage ? { usage: state.usage } : {}) });
565
- stop(); // the app-server never exits on its own
572
+ const complete = () => {
573
+ if (active.get(threadId)?.stop !== stop)
574
+ return;
575
+ active.delete(threadId);
576
+ emit({ ...base(threadId, turnId), type: "turn.completed", ok, stopReason, cost: null, ...(state.usage ? { usage: state.usage } : {}) });
577
+ };
578
+ if (await stop()) {
579
+ complete();
580
+ }
581
+ else {
582
+ emit({ ...base(threadId, turnId), type: "runtime.error", message: "codex did not shut down after termination was requested" });
583
+ if (child.exitCode !== null || child.signalCode !== null)
584
+ complete();
585
+ else
586
+ child.once("close", complete);
587
+ }
566
588
  };
567
589
  // server→client approval request → canonical request.opened
568
590
  // Host-scope tagging mirrors claude.ts: when this turn mounts the real
@@ -789,7 +811,7 @@ export const CodexDriver = {
789
811
  }
790
812
  case "turn/completed": {
791
813
  const t = p.turn ?? {};
792
- settle(t.status === "completed", t.status === "completed" ? null : (t.error?.message ?? t.status ?? "failed"));
814
+ void settle(t.status === "completed", t.status === "completed" ? null : (t.error?.message ?? t.status ?? "failed"));
793
815
  break;
794
816
  }
795
817
  case "error":
@@ -808,9 +830,11 @@ export const CodexDriver = {
808
830
  // multibyte characters that straddle two reads and corrupts the text
809
831
  child.stdout.setEncoding("utf8");
810
832
  child.stdout.on("data", (chunk) => {
833
+ if (abandoned || state.settled)
834
+ return;
811
835
  buf += chunk;
812
836
  let nl;
813
- while ((nl = buf.indexOf("\n")) !== -1) {
837
+ while (!state.settled && (nl = buf.indexOf("\n")) !== -1) {
814
838
  const line = buf.slice(0, nl);
815
839
  buf = buf.slice(nl + 1);
816
840
  if (!line.trim())
@@ -852,7 +876,7 @@ export const CodexDriver = {
852
876
  if (abandoned)
853
877
  return;
854
878
  emit({ ...base(threadId, turnId), type: "runtime.error", ...describeSpawnFailure(e, config.cli) });
855
- settle(false, "spawn_error");
879
+ void settle(false, "spawn_error");
856
880
  });
857
881
  child.on("close", (code) => {
858
882
  if (abandoned)
@@ -863,7 +887,7 @@ export const CodexDriver = {
863
887
  type: "runtime.error",
864
888
  message: `codex exited ${code} before turn/completed${stderr ? `: ${stderr.trim().slice(-300)}` : ""}`,
865
889
  });
866
- settle(false, "exit_before_result");
890
+ void settle(false, "exit_before_result");
867
891
  }
868
892
  });
869
893
  active.set(threadId, { stop, turnId, asks });
@@ -883,26 +907,28 @@ export const CodexDriver = {
883
907
  capabilities: { experimentalApi: true },
884
908
  });
885
909
  send({ jsonrpc: "2.0", method: "initialized", params: {} });
910
+ // developerInstructions replaces, rather than appends to, native
911
+ // config. Read it for every approval mode so existing rules survive.
912
+ // request() already redacts config/read responses from native logs.
913
+ let effectiveConfig;
914
+ try {
915
+ const configured = await request("config/read", {
916
+ cwd: turn.cwd ?? homedir(),
917
+ includeLayers: false,
918
+ });
919
+ effectiveConfig = configured?.config;
920
+ }
921
+ catch {
922
+ // Do not expose a possibly secret-bearing native config error or
923
+ // overwrite unknown instructions with an empty fallback.
924
+ throw new Error("Could not read Codex configuration; cannot safely update bot instructions. Retry after checking Codex.");
925
+ }
926
+ const developerInstructions = codexDeveloperInstructions(effectiveConfig, turn.system ?? "");
886
927
  let approvalParams;
887
928
  if (approvalMode === "custom") {
888
929
  // config/read returns the effective global + project config for this
889
930
  // cwd. Reasserting those values is essential: simply omitting them
890
931
  // on a resumed thread would keep the previous named mode sticky.
891
- let effectiveConfig;
892
- try {
893
- const configured = await request("config/read", {
894
- cwd: turn.cwd ?? homedir(),
895
- includeLayers: false,
896
- });
897
- effectiveConfig = configured?.config;
898
- }
899
- catch {
900
- // Older app-servers and transient failures cannot prove the
901
- // user's configured sandbox. Fall back to interactive read-only
902
- // instead of inheriting stale Full or silently broadening a
903
- // possibly read-only config to workspace write.
904
- effectiveConfig = {};
905
- }
906
932
  approvalParams = customApprovalParams(effectiveConfig);
907
933
  }
908
934
  else {
@@ -913,6 +939,9 @@ export const CodexDriver = {
913
939
  // mode may synthesize approvals; Custom must preserve the sandbox
914
940
  // boundary from config.toml (for example never + read-only).
915
941
  autoAcceptPermissions = approvalMode === "full";
942
+ // Each turn launches a new app-server. Reassert current bot instructions
943
+ // on start AND resume so Codex owns their lifetime through compaction.
944
+ // Removed bot rules are cleared without dropping native configured rules.
916
945
  const cursor = typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;
917
946
  let codexThreadId = null;
918
947
  let startedModel = null;
@@ -920,6 +949,7 @@ export const CodexDriver = {
920
949
  try {
921
950
  const resumed = await request("thread/resume", {
922
951
  threadId: cursor,
952
+ developerInstructions,
923
953
  ...approvalParams.thread,
924
954
  });
925
955
  codexThreadId = resumed?.thread?.id ?? cursor;
@@ -930,23 +960,22 @@ export const CodexDriver = {
930
960
  // profile selector. Retry the same resume safely rather than
931
961
  // losing the native thread or inheriting its previous mode.
932
962
  approvalParams = approvalParams.fallback;
933
- try {
934
- const resumed = await request("thread/resume", {
935
- threadId: cursor,
936
- ...approvalParams.thread,
937
- });
938
- codexThreadId = resumed?.thread?.id ?? cursor;
939
- }
940
- catch {
941
- /* thread gone or resume unsupported — start fresh below */
942
- }
963
+ const resumed = await request("thread/resume", {
964
+ threadId: cursor,
965
+ developerInstructions,
966
+ ...approvalParams.thread,
967
+ });
968
+ codexThreadId = resumed?.thread?.id ?? cursor;
969
+ }
970
+ else {
971
+ throw error;
943
972
  }
944
- /* thread gone or resume unsupported — start fresh below */
945
973
  }
946
974
  }
947
975
  if (!codexThreadId) {
948
976
  const selection = decodeCodexSelection(turn.model);
949
977
  const startThread = () => request("thread/start", {
978
+ developerInstructions,
950
979
  cwd: turn.cwd ?? homedir(),
951
980
  model: selection.model,
952
981
  ...(selection.modelProvider ? { modelProvider: selection.modelProvider } : {}),
@@ -966,8 +995,11 @@ export const CodexDriver = {
966
995
  codexThreadId = started?.thread?.id ?? null;
967
996
  startedModel = started?.model ?? null;
968
997
  }
998
+ if (!codexThreadId)
999
+ throw new Error("Codex did not return a native thread id");
1000
+ await syncCodexInstructions(threadId, codexThreadId, developerInstructions, Boolean(cursor), request);
969
1001
  emit({ ...base(threadId, turnId), type: "session.started", sessionId: codexThreadId, model: startedModel ?? turn.model ?? null });
970
- const promptText = turn.system ? `${turn.system}\n\n${turn.text}` : turn.text;
1002
+ const promptText = turn.text;
971
1003
  const turnInput = [
972
1004
  ...(promptText ? [{ type: "text", text: promptText }] : []),
973
1005
  ...(turn.images ?? []).map((image) => ({ type: "localImage", path: image.path })),
@@ -1015,7 +1047,10 @@ export const CodexDriver = {
1015
1047
  // This app-server never exits by itself. Retire the failed attempt
1016
1048
  // and silence its late handlers before the replacement launches.
1017
1049
  abandoned = true;
1018
- killCliTree(child);
1050
+ if (!await terminate()) {
1051
+ void settle(false, "shutdown_timeout");
1052
+ return;
1053
+ }
1019
1054
  await new Promise((resolve) => {
1020
1055
  const timer = setTimeout(resolve, Math.max(1, Math.round(delayMs * retryScale)));
1021
1056
  timer.unref?.();
@@ -1024,7 +1059,7 @@ export const CodexDriver = {
1024
1059
  void launchAttempt(attempt).catch(() => { });
1025
1060
  }
1026
1061
  else {
1027
- settle(false, "interrupted");
1062
+ await settle(false, "interrupted");
1028
1063
  }
1029
1064
  return;
1030
1065
  }
@@ -1035,7 +1070,7 @@ export const CodexDriver = {
1035
1070
  message,
1036
1071
  ...(needsAuth ? { setup: true } : {}),
1037
1072
  });
1038
- settle(false, needsAuth ? "auth_required" : "rpc_error");
1073
+ await settle(false, needsAuth ? "auth_required" : "rpc_error");
1039
1074
  }
1040
1075
  }
1041
1076
  };
@@ -1087,7 +1122,9 @@ export const CodexDriver = {
1087
1122
  effortLevels: ["low", "medium", "high", "xhigh", "max"],
1088
1123
  },
1089
1124
  sendTurn,
1090
- interruptTurn: async (threadId) => active.get(threadId)?.stop(),
1125
+ interruptTurn: async (threadId) => {
1126
+ await active.get(threadId)?.stop();
1127
+ },
1091
1128
  respondToRequest: async (threadId, requestId, decision) => {
1092
1129
  const turn = active.get(threadId);
1093
1130
  const finish = turn?.asks.get(requestId);
@@ -1098,8 +1135,7 @@ export const CodexDriver = {
1098
1135
  },
1099
1136
  hasSession: (threadId) => active.has(threadId),
1100
1137
  stopAll: async () => {
1101
- for (const { stop } of active.values())
1102
- stop();
1138
+ await Promise.all([...active.values()].map(({ stop }) => stop()));
1103
1139
  },
1104
1140
  onEvent: (listener) => {
1105
1141
  listeners.add(listener);
@@ -1107,8 +1143,7 @@ export const CodexDriver = {
1107
1143
  },
1108
1144
  },
1109
1145
  dispose: async () => {
1110
- for (const { stop } of active.values())
1111
- stop();
1146
+ await Promise.all([...active.values()].map(({ stop }) => stop()));
1112
1147
  listeners.clear();
1113
1148
  },
1114
1149
  };