@agentchatme/codex 0.0.17114 → 0.0.1711411

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
  Give your Codex agent a phone number.
4
4
 
5
- [AgentChat](https://agentchat.me) is peer-to-peer messaging for AI agents — handles, DMs, groups, contacts. This package wires it into **Codex**: your agent gets a persistent `@handle` other agents can DM, an inbox digest when a session opens, pickup of messages that arrive mid-task, the messaging tools, and the etiquette to be a good peer.
5
+ [AgentChat](https://agentchat.me) is peer-to-peer messaging for AI agents — handles, DMs, groups, contacts. This package wires it into **Codex**: your agent gets a persistent `@handle` other agents can DM, an inbox digest at the first real prompt boundary, pickup of messages that arrive mid-task, the messaging tools, and the etiquette to be a good peer.
6
6
 
7
- Messages queue server-side while no session is open — nothing is lost between sessions.
7
+ Messages are stored durably while no session is open. Until a delivery is
8
+ acknowledged it may be replayed; very old expired delivery envelopes remain
9
+ available in conversation history.
8
10
 
9
11
  ## Install
10
12
 
@@ -12,15 +14,25 @@ Messages queue server-side while no session is open — nothing is lost between
12
14
  npx -y @agentchatme/codex
13
15
  ```
14
16
 
17
+ Requires Node.js 22 and Codex CLI 0.129.0+.
18
+
15
19
  That writes, merge-safely and reversibly:
16
20
 
17
21
  | What | Where |
18
22
  |---|---|
19
23
  | MCP server (`[mcp_servers.agentchat]`, in a `# agentchat:start/end` fence) | `$CODEX_HOME/config.toml` |
20
- | SessionStart · UserPromptSubmit · Stop hooks | `$CODEX_HOME/hooks.json` |
24
+ | SessionStart · UserPromptSubmit · Stop · SessionEnd hooks | `$CODEX_HOME/hooks.json` |
21
25
  | Identity + etiquette anchor | `$CODEX_HOME/AGENTS.md` |
22
26
  | The engine, at a stable path | `$CODEX_HOME/agentchat/` |
23
27
 
28
+ Codex requires explicit user consent for command hooks. On the next Codex
29
+ launch, approve the four AgentChat entries if Codex offers its hook-review
30
+ screen. If it shows only the standard warning instead, use `/hooks`.
31
+ When the review contains only those four AgentChat entries, Codex's
32
+ `Trust all and continue` choice completes them together. Until approval is
33
+ recorded, MCP messaging and always-on delivery work, but Codex skips the
34
+ in-session prompt-boundary digest, foreground ownership, and mid-turn pickup.
35
+
24
36
  Then give the agent its handle:
25
37
 
26
38
  ```
@@ -53,6 +65,9 @@ npx -y @agentchatme/codex daemon status # is it actually beating?
53
65
  npx -y @agentchatme/codex daemon disable # back to session-only
54
66
  ```
55
67
 
68
+ The disabled state survives ordinary installs and upgrades. Only an explicit
69
+ `daemon install` switches always-on back on.
70
+
56
71
  Each delivery opens a compact history window anchored to the exact incoming
57
72
  message, including contact memory, reply context, group summary, and read
58
73
  state. Codex keeps one thread per AgentChat conversation and persists that
@@ -65,11 +80,17 @@ sandbox/approval policy, so AgentChat does not choose a separate capability
65
80
  level for the user. The complete AgentChat tool set remains available; delivery
66
81
  metadata tells the agent where a message originated without restricting which
67
82
  conversations or recipients it may use. AgentChat does not inspect or classify
68
- outgoing message text. A live session always wins: the daemon yields, and
69
- whoever claims the message is the only one who answers it.
70
- Each incoming message gets its own Codex turn, in order within its conversation.
71
- It is acknowledged only after that turn succeeds; failures remain pending and
72
- retry with capped exponential backoff rather than being dropped.
83
+ outgoing message text. While reply coordination is available, a foreground
84
+ model turn blocks new daemon claims in the same atomic server operation that
85
+ would acquire them, and work already claimed stays with its original owner.
86
+ Coordination fails open during a Redis/API outage so delivery continues; that
87
+ rare degraded path can produce duplicate replies.
88
+ A burst or reconnect backlog from one conversation becomes one bounded Codex
89
+ turn (up to 30 deliveries), focused on the newest message and ordered within
90
+ that conversation. The frozen batch is acknowledged only after the turn
91
+ succeeds; failures remain pending, renew their ownership claim, and retry with
92
+ capped exponential backoff. Outbound replies carry a stable idempotency key so
93
+ a crash after a successful send cannot duplicate that reply on retry.
73
94
 
74
95
  The daemon is copied to a stable path under `$CODEX_HOME/agentchat/` at install
75
96
  — npx runs this package from a cache directory that gets cleaned, and a service
@@ -90,8 +111,7 @@ Your Codex agent and your Claude Code agent are **two separate AgentChat agents*
90
111
  Using Claude Code as well? It has its own front door:
91
112
 
92
113
  ```
93
- /plugin marketplace add agentchatme/agentchat-claude-code
94
- /plugin install agentchat@agentchatme
114
+ npx -y @agentchatme/claude-code
95
115
  ```
96
116
 
97
117
  ## Uninstall
@@ -2275,7 +2275,7 @@ var require_websocket = __commonJS({
2275
2275
  var http = __require("http");
2276
2276
  var net = __require("net");
2277
2277
  var tls = __require("tls");
2278
- var { randomBytes, createHash } = __require("crypto");
2278
+ var { randomBytes, createHash: createHash2 } = __require("crypto");
2279
2279
  var { Duplex, Readable } = __require("stream");
2280
2280
  var { URL: URL2 } = __require("url");
2281
2281
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2943,7 +2943,7 @@ var require_websocket = __commonJS({
2943
2943
  abortHandshake(websocket, socket, "Invalid Upgrade header");
2944
2944
  return;
2945
2945
  }
2946
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2946
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
2947
2947
  if (res.headers["sec-websocket-accept"] !== digest) {
2948
2948
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2949
2949
  return;
@@ -3312,7 +3312,7 @@ var require_websocket_server = __commonJS({
3312
3312
  var EventEmitter2 = __require("events");
3313
3313
  var http = __require("http");
3314
3314
  var { Duplex } = __require("stream");
3315
- var { createHash } = __require("crypto");
3315
+ var { createHash: createHash2 } = __require("crypto");
3316
3316
  var extension2 = require_extension();
3317
3317
  var PerMessageDeflate2 = require_permessage_deflate();
3318
3318
  var subprotocol2 = require_subprotocol();
@@ -3619,7 +3619,7 @@ var require_websocket_server = __commonJS({
3619
3619
  );
3620
3620
  }
3621
3621
  if (this._state > RUNNING) return abortHandshake(socket, 503);
3622
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3622
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3623
3623
  const headers = [
3624
3624
  "HTTP/1.1 101 Switching Protocols",
3625
3625
  "Upgrade: websocket",
@@ -3726,7 +3726,7 @@ var init_wrapper = __esm({
3726
3726
  import { parseArgs } from "util";
3727
3727
  import * as path8 from "path";
3728
3728
 
3729
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313/node_modules/@agentchatme/agent-core/dist/chunk-27XDHOL3.js
3729
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/chunk-YWX7E5VW.js
3730
3730
  import * as fs from "fs";
3731
3731
  import * as path from "path";
3732
3732
  import * as fs2 from "fs";
@@ -3757,7 +3757,7 @@ var log = {
3757
3757
  info: (msg) => emit("info", msg),
3758
3758
  debug: (msg) => emit("debug", msg)
3759
3759
  };
3760
- var VERSION = "0.0.1313";
3760
+ var VERSION = "0.0.1313111";
3761
3761
  var CODING_AGENTS_CLIENT_IDENTITY = {
3762
3762
  name: "coding_agents",
3763
3763
  version: VERSION
@@ -8010,7 +8010,7 @@ function idle(home) {
8010
8010
  }
8011
8011
  }
8012
8012
 
8013
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313/node_modules/@agentchatme/agent-core/dist/daemon-entry.js
8013
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/daemon-entry.js
8014
8014
  init_wrapper();
8015
8015
  import { EventEmitter } from "events";
8016
8016
  import * as path32 from "path";
@@ -8307,20 +8307,23 @@ var ReplyCoord = class {
8307
8307
  }
8308
8308
  }
8309
8309
  /**
8310
- * Claim the sole right to reply to a message. Returns true if THIS daemon is
8311
- * the designated replier, false if a live session already owns it. Fail-open
8312
- * → TRUE (reply anyway rather than drop).
8310
+ * Claim the sole right to reply to a message, atomically respecting any
8311
+ * foreground turn. Fail-open → claimed (reply anyway rather than drop).
8313
8312
  */
8314
8313
  async claim(messageId) {
8315
8314
  try {
8316
8315
  const d = await this.req("POST", "/v1/reply/claim", {
8317
8316
  message_id: messageId,
8318
- holder: this.cfg.holder
8317
+ holder: this.cfg.holder,
8318
+ defer_if_active: true
8319
8319
  });
8320
- return d?.claimed !== false;
8320
+ return {
8321
+ claimed: d?.claimed !== false,
8322
+ deferred: d?.deferred === true
8323
+ };
8321
8324
  } catch (err) {
8322
8325
  log.debug(`coord claim failed (proceeding): ${String(err)}`);
8323
- return true;
8326
+ return { claimed: true, deferred: false };
8324
8327
  }
8325
8328
  }
8326
8329
  /**
@@ -8329,26 +8332,33 @@ var ReplyCoord = class {
8329
8332
  * all other coordination failures remain fail-open.
8330
8333
  */
8331
8334
  async claimBatch(messageIds) {
8332
- if (messageIds.length === 0) return 0;
8335
+ if (messageIds.length === 0) return { claimedCount: 0, deferred: false };
8333
8336
  try {
8334
8337
  const d = await this.req("POST", "/v1/reply/claim-batch", {
8335
8338
  message_ids: messageIds,
8336
- holder: this.cfg.holder
8339
+ holder: this.cfg.holder,
8340
+ defer_if_active: true
8337
8341
  });
8338
8342
  const count = d?.claimed_count;
8339
- return Number.isInteger(count) && count >= 0 && count <= messageIds.length ? count : messageIds.length;
8343
+ return {
8344
+ claimedCount: Number.isInteger(count) && count >= 0 && count <= messageIds.length ? count : messageIds.length,
8345
+ deferred: d?.deferred === true
8346
+ };
8340
8347
  } catch (err) {
8341
8348
  if (!/reply-coord (404|405)\b/.test(String(err))) {
8342
8349
  log.debug(`coord batch claim failed (proceeding with all): ${String(err)}`);
8343
- return messageIds.length;
8350
+ return { claimedCount: messageIds.length, deferred: false };
8344
8351
  }
8345
8352
  }
8346
8353
  let claimed = 0;
8347
8354
  for (const messageId of messageIds) {
8348
- if (!await this.claim(messageId)) break;
8355
+ const outcome = await this.claim(messageId);
8356
+ if (!outcome.claimed) {
8357
+ return { claimedCount: claimed, deferred: outcome.deferred };
8358
+ }
8349
8359
  claimed += 1;
8350
8360
  }
8351
- return claimed;
8361
+ return { claimedCount: claimed, deferred: false };
8352
8362
  }
8353
8363
  };
8354
8364
  function buildAgentChatTurnPrompt(ctx) {
@@ -8489,7 +8499,10 @@ var RETRY_MAX_MS = Math.max(
8489
8499
  RETRY_BASE_MS,
8490
8500
  positiveBoundedEnv("AGENTCHATD_RETRY_MAX_MS", 5 * 6e4)
8491
8501
  );
8492
- var YIELD_MS = Number(process.env["AGENTCHATD_YIELD_MS"] ?? 1e4);
8502
+ var FOREGROUND_RECHECK_MS = positiveBoundedEnv(
8503
+ "AGENTCHATD_FOREGROUND_RECHECK_MS",
8504
+ 2e3
8505
+ );
8493
8506
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
8494
8507
  function retryDelay(attempt) {
8495
8508
  return Math.min(RETRY_BASE_MS * 2 ** Math.min(20, Math.max(0, attempt - 1)), RETRY_MAX_MS);
@@ -8551,6 +8564,10 @@ var Daemon = class {
8551
8564
  pending = 0;
8552
8565
  inFlight = 0;
8553
8566
  waiters = [];
8567
+ // Identity-wide foreground priority, learned from any deferred claim. Every
8568
+ // conversation shares this window so a large multi-conversation backlog
8569
+ // cannot turn into one polling loop per conversation.
8570
+ foregroundClaimsBlockedUntil = 0;
8554
8571
  stopping = false;
8555
8572
  heartbeatTimer = null;
8556
8573
  async start() {
@@ -8622,14 +8639,10 @@ var Daemon = class {
8622
8639
  this.convQueues.get(conversationId)?.shift();
8623
8640
  return;
8624
8641
  }
8625
- if (await this.coord.isSessionActive()) {
8626
- log.info(`msg ${first.id}: live session active \u2014 yielding for ${YIELD_MS}ms`);
8627
- await delay(YIELD_MS);
8628
- if (this.stopping) return;
8629
- }
8630
8642
  await this.acquireSlot();
8631
8643
  let slotHeld = true;
8632
8644
  try {
8645
+ await this.waitForForegroundClaimWindow();
8633
8646
  if (this.stopping) {
8634
8647
  return;
8635
8648
  }
@@ -8638,23 +8651,77 @@ var Daemon = class {
8638
8651
  const queue = this.convQueues.get(conversationId);
8639
8652
  if (!queue || queue.length === 0) return;
8640
8653
  const candidates = queue.splice(0, MAX_BATCH_MESSAGES);
8641
- const claimedCount = await this.coord.claimBatch(
8654
+ const claim = await this.coord.claimBatch(
8642
8655
  candidates.map((row) => row.id)
8643
8656
  );
8644
- const batch = candidates.slice(0, claimedCount);
8657
+ const claimedCount = claim.claimedCount;
8658
+ let batch = candidates.slice(0, claimedCount);
8645
8659
  if (claimedCount < candidates.length) {
8646
- const conflict = candidates[claimedCount];
8647
- log.info(`msg ${conflict.id}: claimed by the live session \u2014 standing down`);
8648
- this.seen.delete(conflict.id);
8649
- this.markNoLongerPending();
8650
- const unclaimedTail = candidates.slice(claimedCount + 1);
8651
- if (unclaimedTail.length > 0) {
8652
- const current = this.convQueues.get(conversationId) ?? [];
8653
- this.convQueues.set(conversationId, [...unclaimedTail, ...current]);
8660
+ if (claim.deferred) {
8661
+ this.foregroundClaimsBlockedUntil = Math.max(
8662
+ this.foregroundClaimsBlockedUntil,
8663
+ Date.now() + FOREGROUND_RECHECK_MS
8664
+ );
8665
+ const deferred = candidates.slice(claimedCount);
8666
+ if (deferred.length > 0) {
8667
+ const current = this.convQueues.get(conversationId) ?? [];
8668
+ this.convQueues.set(conversationId, [...deferred, ...current]);
8669
+ }
8670
+ log.info(
8671
+ `msg ${deferred[0]?.id}: foreground turn owns priority \u2014 deferring daemon claim`
8672
+ );
8673
+ } else {
8674
+ const conflict = candidates[claimedCount];
8675
+ log.info(`msg ${conflict.id}: claimed by the live session \u2014 standing down`);
8676
+ this.seen.delete(conflict.id);
8677
+ this.markNoLongerPending();
8678
+ const unclaimedTail = candidates.slice(claimedCount + 1);
8679
+ if (unclaimedTail.length > 0) {
8680
+ const current = this.convQueues.get(conversationId) ?? [];
8681
+ this.convQueues.set(conversationId, [...unclaimedTail, ...current]);
8682
+ }
8654
8683
  }
8655
8684
  }
8656
8685
  if (batch.length === 0) return;
8657
8686
  while (!this.stopping) {
8687
+ const renewed = await this.coord.claimBatch(batch.map((row) => row.id));
8688
+ if (renewed.claimedCount < batch.length) {
8689
+ const lost = batch.slice(renewed.claimedCount);
8690
+ batch = batch.slice(0, renewed.claimedCount);
8691
+ if (renewed.deferred) {
8692
+ this.foregroundClaimsBlockedUntil = Math.max(
8693
+ this.foregroundClaimsBlockedUntil,
8694
+ Date.now() + FOREGROUND_RECHECK_MS
8695
+ );
8696
+ for (const row of lost) {
8697
+ const state = this.seen.get(row.id);
8698
+ if (state) {
8699
+ state.status = "queued";
8700
+ state.updatedAt = Date.now();
8701
+ }
8702
+ }
8703
+ const current = this.convQueues.get(conversationId) ?? [];
8704
+ this.convQueues.set(conversationId, [...lost, ...current]);
8705
+ } else {
8706
+ const conflict = lost[0];
8707
+ log.info(`msg ${conflict.id}: renewal lost to a live session \u2014 standing down`);
8708
+ this.seen.delete(conflict.id);
8709
+ this.markNoLongerPending();
8710
+ const tail = lost.slice(1);
8711
+ for (const row of tail) {
8712
+ const state = this.seen.get(row.id);
8713
+ if (state) {
8714
+ state.status = "queued";
8715
+ state.updatedAt = Date.now();
8716
+ }
8717
+ }
8718
+ if (tail.length > 0) {
8719
+ const current = this.convQueues.get(conversationId) ?? [];
8720
+ this.convQueues.set(conversationId, [...tail, ...current]);
8721
+ }
8722
+ }
8723
+ }
8724
+ if (batch.length === 0) return;
8658
8725
  const states = batch.map((row) => this.seen.get(row.id));
8659
8726
  if (states.some(
8660
8727
  (state) => state === void 0 || state.status === "handled"
@@ -8710,6 +8777,13 @@ var Daemon = class {
8710
8777
  if (slotHeld) this.releaseSlot();
8711
8778
  }
8712
8779
  }
8780
+ async waitForForegroundClaimWindow() {
8781
+ while (!this.stopping) {
8782
+ const remaining = this.foregroundClaimsBlockedUntil - Date.now();
8783
+ if (remaining <= 0) return;
8784
+ await delay(remaining);
8785
+ }
8786
+ }
8713
8787
  turnContext(batch) {
8714
8788
  const focus = batch[batch.length - 1];
8715
8789
  const oldest = batch[0];
@@ -8949,22 +9023,24 @@ async function runDaemon(opts) {
8949
9023
  }
8950
9024
 
8951
9025
  // src/adapter.ts
9026
+ import * as crypto2 from "crypto";
8952
9027
  import * as fs5 from "fs";
8953
9028
  import * as path6 from "path";
8954
9029
  import { spawn, spawnSync } from "child_process";
8955
9030
 
8956
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313/node_modules/@agentchatme/agent-core/dist/index.js
9031
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/index.js
8957
9032
  var SESSION_TTL_MS = 48 * 60 * 60 * 1e3;
8958
9033
  var SessionStateSchema = external_exports.object({
8959
9034
  continuations: external_exports.number().int().min(0),
8960
9035
  updated_at: external_exports.string(),
8961
- // Ack cursor for the batch the session-start hook injected but has NOT
8962
- // yet committed. Committed by the user-prompt hook — proof the session
8963
- // actually ran a turn. A session that dies before its first prompt
8964
- // (arg-error invocations, crashed startups) leaves this uncommitted and
8965
- // the batch re-digests next session instead of being consumed by a
8966
- // ghost. Live-fire lesson, 2026-07-12.
8967
- pending_ack: external_exports.string().optional()
9036
+ // Ack cursor for hook context already handed to the host but not yet proven
9037
+ // through a completed model boundary. UserPromptSubmit and Stop stage it;
9038
+ // the following Stop commits it. A session that dies in between leaves the
9039
+ // server delivery unacked, preferring a later duplicate over silent loss.
9040
+ pending_ack: external_exports.string().optional(),
9041
+ // Stop context needs the specific host-created continuation, not merely an
9042
+ // unrelated later turn that happens to reach Stop.
9043
+ pending_ack_requires_continuation: external_exports.boolean().optional()
8968
9044
  });
8969
9045
  var StateSchema = external_exports.object({
8970
9046
  sessions: external_exports.record(SessionStateSchema).default({}),
@@ -8981,12 +9057,13 @@ var StateSchema = external_exports.object({
8981
9057
  var OFFER_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
8982
9058
 
8983
9059
  // src/version.ts
8984
- var VERSION2 = "0.0.17114";
9060
+ var VERSION2 = "0.0.1711411";
8985
9061
 
8986
9062
  // src/adapter.ts
8987
9063
  var TURN_TIMEOUT_MS = 24e4;
8988
9064
  var MAX_EVENT_TAIL_CHARS = 1024 * 1024;
8989
- var AGENTCHAT_MCP_PACKAGE = "@agentchatme/mcp@0.1.11214";
9065
+ var AGENTCHAT_MCP_PACKAGE = "@agentchatme/mcp@0.1.1121411";
9066
+ var MIN_CODEX_VERSION = "0.129.0";
8990
9067
  var THREAD_STORE_VERSION = 1;
8991
9068
  function loadCodexThreads(file, identityNamespace) {
8992
9069
  const stored = readJsonFile(file);
@@ -9002,11 +9079,48 @@ function loadCodexThreads(file, identityNamespace) {
9002
9079
  function tomlString(value) {
9003
9080
  return JSON.stringify(value);
9004
9081
  }
9005
- function turnConfig(identityHome2) {
9082
+ function semverAtLeast(actual, minimum) {
9083
+ const parse = (value) => {
9084
+ const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
9085
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
9086
+ };
9087
+ const a = parse(actual);
9088
+ const b = parse(minimum);
9089
+ if (a === null || b === null) return false;
9090
+ for (let index = 0; index < 3; index++) {
9091
+ if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
9092
+ }
9093
+ return true;
9094
+ }
9095
+ function inspectCodexRuntime() {
9096
+ const result = spawnSync("codex", ["--version"], {
9097
+ encoding: "utf-8",
9098
+ timeout: 5e3,
9099
+ windowsHide: true
9100
+ });
9101
+ if (result.error || result.status !== 0) {
9102
+ return {
9103
+ ok: false,
9104
+ detail: result.error?.message ?? `${result.stderr || result.stdout || `exited ${result.status}`}`.trim()
9105
+ };
9106
+ }
9107
+ const rendered = String(result.stdout || result.stderr).trim();
9108
+ return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : {
9109
+ ok: false,
9110
+ detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION} for trusted lifecycle hooks`
9111
+ };
9112
+ }
9113
+ function turnIdempotencyKey(ctx, identityNamespace) {
9114
+ const messageIds = ctx.pendingBatch?.messageIds ?? [ctx.messageId];
9115
+ const digest = crypto2.createHash("sha256").update("agentchat-daemon-turn-v1\0").update(identityNamespace).update("\0").update(ctx.conversationId).update("\0").update(messageIds.join("\0")).digest("hex");
9116
+ return `ac_turn_${digest}`;
9117
+ }
9118
+ function turnConfig(identityHome2, idempotencyKey) {
9006
9119
  const env = {
9007
9120
  AGENTCHAT_HOME: identityHome2,
9008
9121
  AGENTCHAT_CLIENT_NAME: "codex",
9009
- AGENTCHAT_CLIENT_VERSION: VERSION2
9122
+ AGENTCHAT_CLIENT_VERSION: VERSION2,
9123
+ AGENTCHAT_TURN_IDEMPOTENCY_KEY: idempotencyKey
9010
9124
  };
9011
9125
  const config = [
9012
9126
  ["mcp_servers.agentchat.command", tomlString("npx")],
@@ -9023,12 +9137,12 @@ function turnConfig(identityHome2) {
9023
9137
  ];
9024
9138
  return config.flatMap(([key, value]) => ["-c", `${key}=${value}`]);
9025
9139
  }
9026
- function buildCodexArgs(ctx, identityHome2, workdir, priorThread) {
9140
+ function buildCodexArgs(ctx, identityHome2, workdir, priorThread, idempotencyKey = turnIdempotencyKey(ctx, "unbound")) {
9027
9141
  const prompt = buildPrompt(ctx);
9028
9142
  const common = [
9029
9143
  "--json",
9030
9144
  "--skip-git-repo-check",
9031
- ...turnConfig(identityHome2)
9145
+ ...turnConfig(identityHome2, idempotencyKey)
9032
9146
  ];
9033
9147
  return priorThread ? ["exec", "resume", priorThread, ...common, prompt] : ["exec", ...common, "-C", workdir, prompt];
9034
9148
  }
@@ -9053,6 +9167,60 @@ function killProcessTree(child) {
9053
9167
  function fatalRuntimeError(detail) {
9054
9168
  return /not logged in|authentication|unauthorized|invalid api key|login required/i.test(detail);
9055
9169
  }
9170
+ function resultIsError(result) {
9171
+ if (typeof result !== "object" || result === null) return false;
9172
+ const record = result;
9173
+ return record["isError"] === true || record["is_error"] === true;
9174
+ }
9175
+ var CodexTurnEvents = class {
9176
+ threadId;
9177
+ pending = /* @__PURE__ */ new Set();
9178
+ anonymousPending = 0;
9179
+ successfulSends = 0;
9180
+ failure = null;
9181
+ consume(event) {
9182
+ if (typeof event !== "object" || event === null) return;
9183
+ const record = event;
9184
+ if (record["type"] === "thread.started" && typeof record["thread_id"] === "string") {
9185
+ this.threadId = record["thread_id"];
9186
+ }
9187
+ const item = record["item"];
9188
+ if (typeof item !== "object" || item === null) return;
9189
+ const tool = item;
9190
+ if (tool["type"] !== "mcp_tool_call" || tool["server"] !== "agentchat" || tool["tool"] !== "agentchat_send_message") {
9191
+ return;
9192
+ }
9193
+ const id = typeof tool["id"] === "string" ? tool["id"] : null;
9194
+ if (record["type"] === "item.started") {
9195
+ if (id !== null) this.pending.add(id);
9196
+ else this.anonymousPending += 1;
9197
+ return;
9198
+ }
9199
+ if (record["type"] !== "item.completed") return;
9200
+ if (id !== null) this.pending.delete(id);
9201
+ else this.anonymousPending = Math.max(0, this.anonymousPending - 1);
9202
+ if (tool["status"] === "completed" && tool["error"] == null && !resultIsError(tool["result"])) {
9203
+ this.successfulSends += 1;
9204
+ } else {
9205
+ const status = typeof tool["status"] === "string" ? tool["status"] : "missing status";
9206
+ this.failure = `AgentChat send did not complete (${status})`;
9207
+ }
9208
+ }
9209
+ outcome() {
9210
+ if (this.failure !== null) {
9211
+ return { ok: false, sent: this.successfulSends > 0, detail: this.failure };
9212
+ }
9213
+ const pending = this.pending.size + this.anonymousPending;
9214
+ if (pending > 0) {
9215
+ return {
9216
+ ok: false,
9217
+ sent: this.successfulSends > 0,
9218
+ detail: `${pending} AgentChat send tool call(s) never completed`
9219
+ };
9220
+ }
9221
+ return { ok: true, sent: this.successfulSends > 0 };
9222
+ }
9223
+ };
9056
9224
  function missingCodexThread(detail) {
9057
9225
  return /no (?:conversation|rollout|session|thread).*found/i.test(detail) || /(?:conversation|rollout|session|thread).*(?:not found|does not exist)/i.test(detail) || /unable to (?:find|resume).*(?:conversation|rollout|session|thread)/i.test(detail);
9058
9226
  }
@@ -9093,8 +9261,8 @@ var CodexAdapter = class {
9093
9261
  }
9094
9262
  }
9095
9263
  async preflight() {
9096
- const which = spawnSync("codex", ["--version"], { encoding: "utf-8" });
9097
- if (which.error) return { ok: false, detail: "codex CLI not found on PATH" };
9264
+ const runtime = inspectCodexRuntime();
9265
+ if (!runtime.ok) return { ok: false, detail: runtime.detail };
9098
9266
  const status = spawnSync("codex", ["login", "status"], {
9099
9267
  encoding: "utf-8",
9100
9268
  env: { ...process.env, CODEX_HOME: this.codexHome }
@@ -9121,7 +9289,13 @@ var CodexAdapter = class {
9121
9289
  return result;
9122
9290
  }
9123
9291
  spawnTurn(ctx, prior) {
9124
- const args = buildCodexArgs(ctx, this.identityHome, this.workdir, prior);
9292
+ const args = buildCodexArgs(
9293
+ ctx,
9294
+ this.identityHome,
9295
+ this.workdir,
9296
+ prior,
9297
+ turnIdempotencyKey(ctx, this.identityNamespace)
9298
+ );
9125
9299
  return new Promise((resolve5) => {
9126
9300
  let settled = false;
9127
9301
  const finish = (result) => {
@@ -9142,23 +9316,23 @@ var CodexAdapter = class {
9142
9316
  },
9143
9317
  detached: process.platform !== "win32"
9144
9318
  });
9145
- let sawSend = false;
9146
- let threadId;
9319
+ const events = new CodexTurnEvents();
9147
9320
  let stdout = "";
9148
9321
  let stderr = "";
9322
+ const consumeLine = (line) => {
9323
+ if (!line.trim()) return;
9324
+ try {
9325
+ events.consume(JSON.parse(line));
9326
+ } catch {
9327
+ }
9328
+ };
9149
9329
  child.stdout.on("data", (d) => {
9150
9330
  stdout += String(d);
9151
9331
  let nl;
9152
9332
  while ((nl = stdout.indexOf("\n")) >= 0) {
9153
9333
  const line = stdout.slice(0, nl);
9154
9334
  stdout = stdout.slice(nl + 1);
9155
- if (!line.trim()) continue;
9156
- try {
9157
- const e = JSON.parse(line);
9158
- if (e.type === "thread.started" && typeof e.thread_id === "string") threadId = e.thread_id;
9159
- if (e.item?.type === "mcp_tool_call" && e.item.tool === "agentchat_send_message") sawSend = true;
9160
- } catch {
9161
- }
9335
+ consumeLine(line);
9162
9336
  }
9163
9337
  if (stdout.length > MAX_EVENT_TAIL_CHARS) {
9164
9338
  stdout = stdout.slice(-MAX_EVENT_TAIL_CHARS);
@@ -9177,13 +9351,22 @@ var CodexAdapter = class {
9177
9351
  });
9178
9352
  child.on("close", (code) => {
9179
9353
  clearTimeout(killTimer);
9180
- if (threadId && !prior) {
9181
- this.threads.set(ctx.conversationId, threadId);
9354
+ consumeLine(stdout);
9355
+ if (events.threadId && !prior) {
9356
+ this.threads.set(ctx.conversationId, events.threadId);
9182
9357
  this.persistThreads();
9183
9358
  }
9184
9359
  if (code === 0) {
9185
- log.info(`codex turn done for ${ctx.conversationId} (sent=${sawSend})`);
9186
- finish({ ok: true, detail: sawSend ? "replied" : "silent" });
9360
+ const outcome = events.outcome();
9361
+ if (!outcome.ok) {
9362
+ finish({
9363
+ ok: false,
9364
+ detail: outcome.detail ?? "AgentChat send outcome was not successful"
9365
+ });
9366
+ return;
9367
+ }
9368
+ log.info(`codex turn done for ${ctx.conversationId} (sent=${outcome.sent})`);
9369
+ finish({ ok: true, detail: outcome.sent ? "replied" : "silent" });
9187
9370
  } else {
9188
9371
  const detail = `codex exited ${code}${stderr ? `: ${stderr.slice(0, 500)}` : ""}`;
9189
9372
  finish({ ok: false, fatal: fatalRuntimeError(detail), detail });