@agentchatme/codex 0.0.171141 → 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/dist/index.js CHANGED
@@ -5,7 +5,7 @@ const require=__acCreateRequire(import.meta.url);
5
5
  // src/index.ts
6
6
  import { parseArgs } from "util";
7
7
 
8
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.13131/node_modules/@agentchatme/agent-core/dist/chunk-M2X5WY7Q.js
8
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/chunk-YWX7E5VW.js
9
9
  import * as fs2 from "fs";
10
10
  import * as path2 from "path";
11
11
  import * as fs3 from "fs";
@@ -35,7 +35,7 @@ var log = {
35
35
  info: (msg) => emit("info", msg),
36
36
  debug: (msg) => emit("debug", msg)
37
37
  };
38
- var VERSION = "0.0.13131";
38
+ var VERSION = "0.0.1313111";
39
39
  var CODING_AGENTS_CLIENT_IDENTITY = {
40
40
  name: "coding_agents",
41
41
  version: VERSION
@@ -4443,7 +4443,7 @@ function alwaysOnHealth(home) {
4443
4443
  return { wanted: state !== "off", healthy: state !== "down" };
4444
4444
  }
4445
4445
 
4446
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.13131/node_modules/@agentchatme/agent-core/dist/index.js
4446
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/index.js
4447
4447
  import * as fs from "fs";
4448
4448
  import * as path from "path";
4449
4449
  import * as readline from "readline";
@@ -4942,10 +4942,10 @@ function statusToCode(status) {
4942
4942
  }
4943
4943
  async function sleep(ms, signal) {
4944
4944
  if (ms <= 0) return;
4945
- await new Promise((resolve4, reject) => {
4945
+ await new Promise((resolve5, reject) => {
4946
4946
  const timer = setTimeout(() => {
4947
4947
  if (signal) signal.removeEventListener("abort", onAbort);
4948
- resolve4();
4948
+ resolve5();
4949
4949
  }, ms);
4950
4950
  const onAbort = () => {
4951
4951
  clearTimeout(timer);
@@ -5784,7 +5784,7 @@ var HOUR2 = 60 * MIN2;
5784
5784
  var DAY2 = 24 * HOUR2;
5785
5785
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
5786
5786
 
5787
- // node_modules/.pnpm/@agentchatme+agent-core@0.0.13131/node_modules/@agentchatme/agent-core/dist/index.js
5787
+ // node_modules/.pnpm/@agentchatme+agent-core@0.0.1313111/node_modules/@agentchatme/agent-core/dist/index.js
5788
5788
  import * as fs22 from "fs";
5789
5789
  import * as os from "os";
5790
5790
  import * as path22 from "path";
@@ -5793,13 +5793,14 @@ var SESSION_TTL_MS = 48 * 60 * 60 * 1e3;
5793
5793
  var SessionStateSchema = external_exports.object({
5794
5794
  continuations: external_exports.number().int().min(0),
5795
5795
  updated_at: external_exports.string(),
5796
- // Ack cursor for the batch the session-start hook injected but has NOT
5797
- // yet committed. Committed by the user-prompt hook — proof the session
5798
- // actually ran a turn. A session that dies before its first prompt
5799
- // (arg-error invocations, crashed startups) leaves this uncommitted and
5800
- // the batch re-digests next session instead of being consumed by a
5801
- // ghost. Live-fire lesson, 2026-07-12.
5802
- pending_ack: external_exports.string().optional()
5796
+ // Ack cursor for hook context already handed to the host but not yet proven
5797
+ // through a completed model boundary. UserPromptSubmit and Stop stage it;
5798
+ // the following Stop commits it. A session that dies in between leaves the
5799
+ // server delivery unacked, preferring a later duplicate over silent loss.
5800
+ pending_ack: external_exports.string().optional(),
5801
+ // Stop context needs the specific host-created continuation, not merely an
5802
+ // unrelated later turn that happens to reach Stop.
5803
+ pending_ack_requires_continuation: external_exports.boolean().optional()
5803
5804
  });
5804
5805
  var StateSchema = external_exports.object({
5805
5806
  sessions: external_exports.record(SessionStateSchema).default({}),
@@ -5839,9 +5840,15 @@ function getContinuations(home, sessionKey) {
5839
5840
  function recordContinuation(home, sessionKey, now2 = /* @__PURE__ */ new Date()) {
5840
5841
  const state = readState(home);
5841
5842
  prune(state, now2);
5842
- const current = state.sessions[sessionKey]?.continuations ?? 0;
5843
+ const existing = state.sessions[sessionKey];
5844
+ const current = existing?.continuations ?? 0;
5843
5845
  const next = current + 1;
5844
- state.sessions[sessionKey] = { continuations: next, updated_at: now2.toISOString() };
5846
+ state.sessions[sessionKey] = {
5847
+ continuations: next,
5848
+ updated_at: now2.toISOString(),
5849
+ ...existing?.pending_ack !== void 0 ? { pending_ack: existing.pending_ack } : {},
5850
+ ...existing?.pending_ack_requires_continuation === true ? { pending_ack_requires_continuation: true } : {}
5851
+ };
5845
5852
  writeState(home, state);
5846
5853
  return next;
5847
5854
  }
@@ -5851,23 +5858,31 @@ function resetSession(home, sessionKey) {
5851
5858
  delete state.sessions[sessionKey];
5852
5859
  writeState(home, state);
5853
5860
  }
5854
- function setPendingAck(home, sessionKey, cursor, now2 = /* @__PURE__ */ new Date()) {
5861
+ function setPendingAck(home, sessionKey, cursor, now2 = /* @__PURE__ */ new Date(), requiresContinuation = false) {
5855
5862
  const state = readState(home);
5856
5863
  prune(state, now2);
5857
5864
  const existing = state.sessions[sessionKey];
5858
5865
  state.sessions[sessionKey] = {
5859
5866
  continuations: existing?.continuations ?? 0,
5860
5867
  updated_at: now2.toISOString(),
5861
- pending_ack: cursor
5868
+ pending_ack: cursor,
5869
+ ...requiresContinuation ? { pending_ack_requires_continuation: true } : {}
5862
5870
  };
5863
5871
  writeState(home, state);
5864
5872
  }
5873
+ function getPendingAck(home, sessionKey) {
5874
+ return readState(home).sessions[sessionKey]?.pending_ack ?? null;
5875
+ }
5876
+ function pendingAckRequiresContinuation(home, sessionKey) {
5877
+ return readState(home).sessions[sessionKey]?.pending_ack_requires_continuation === true;
5878
+ }
5865
5879
  function takePendingAck(home, sessionKey, now2 = /* @__PURE__ */ new Date()) {
5866
5880
  const state = readState(home);
5867
5881
  const entry = state.sessions[sessionKey];
5868
5882
  if (entry?.pending_ack === void 0) return null;
5869
5883
  const cursor = entry.pending_ack;
5870
5884
  delete entry.pending_ack;
5885
+ delete entry.pending_ack_requires_continuation;
5871
5886
  entry.updated_at = now2.toISOString();
5872
5887
  writeState(home, state);
5873
5888
  return cursor;
@@ -6066,7 +6081,7 @@ function formatStopPickup(handle, rows) {
6066
6081
  ].join("\n");
6067
6082
  }
6068
6083
  function formatAlwaysOnDown(copy) {
6069
- return `\u26A0 Always-on is down \u2014 while you are away I won\u2019t be able to answer messages (they queue for your next session, nothing is lost). Turn it back on: \`${copy.invoke} daemon install\``;
6084
+ return `\u26A0 Always-on is down \u2014 while you are away I won\u2019t be able to answer messages (they remain stored and queue for your next session). Turn it back on: \`${copy.invoke} daemon install\``;
6070
6085
  }
6071
6086
  function formatRegistrationOffer(copy, alwaysOn = "off") {
6072
6087
  const { invoke, label } = copy;
@@ -6144,7 +6159,7 @@ function renderDeclinedBlock(copy) {
6144
6159
  ANCHOR_END
6145
6160
  ].join("\n");
6146
6161
  }
6147
- var SESSION_START_PEEK_LIMIT = 100;
6162
+ var USER_PROMPT_PEEK_LIMIT = 100;
6148
6163
  var STOP_PEEK_LIMIT = 50;
6149
6164
  var DEFAULT_MAX_CONTINUATIONS = 5;
6150
6165
  var FOREGROUND_TURN_TTL_SECONDS = 600;
@@ -6203,46 +6218,46 @@ async function sessionStart(ctx, input) {
6203
6218
  }
6204
6219
  return none;
6205
6220
  }
6206
- const cfg = { apiKey: identity.apiKey, apiBase: identity.apiBase };
6207
6221
  const h = alwaysOnHealth(ctx.home);
6208
6222
  const alert = h.wanted && !h.healthy ? formatAlwaysOnDown(ctx.copy) : null;
6209
- const peeked = ackableRows(await syncPeek(cfg, { limit: SESSION_START_PEEK_LIMIT }));
6210
- const rows = peeked.length > 0 ? await claimContiguousPrefix(cfg, peeked, `session:${input.sessionId}`) : [];
6211
- if (rows.length === 0) return { context: alert };
6212
- const handle = await resolveHandle(cfg, identity.handle);
6213
- const digest = formatSessionStart(handle, rows);
6214
- const context = alert !== null ? `${alert}
6215
-
6216
- ${digest}` : digest;
6217
- const cursor = lastDeliveryId(rows);
6218
- if (cursor !== null) setPendingAck(ctx.home, input.sessionId, cursor);
6219
- return { context };
6223
+ return { context: alert };
6220
6224
  } catch (err) {
6221
6225
  log.warn(`session-start hook degraded to no-op: ${String(err)}`);
6222
6226
  return none;
6223
6227
  }
6224
6228
  }
6225
6229
  async function userPrompt(ctx, input) {
6230
+ const none = { context: null, stage: () => {
6231
+ } };
6226
6232
  try {
6227
- if (hooksDisabled()) return;
6233
+ if (hooksDisabled()) return none;
6228
6234
  const identity = resolveIdentity(ctx.home);
6229
- if (identity === null) return;
6235
+ if (identity === null) return none;
6230
6236
  const cfg = { apiKey: identity.apiKey, apiBase: identity.apiBase };
6231
6237
  await markForegroundTurn(cfg, input.sessionId, FOREGROUND_TURN_TTL_SECONDS);
6232
- const cursor = takePendingAck(ctx.home, input.sessionId);
6233
- if (cursor === null) return;
6234
- try {
6235
- await syncAck(cfg, cursor);
6236
- } catch (err) {
6237
- setPendingAck(ctx.home, input.sessionId, cursor);
6238
- log.warn(`user-prompt ack failed (will retry next prompt): ${String(err)}`);
6239
- }
6238
+ if (getPendingAck(ctx.home, input.sessionId) !== null) return none;
6239
+ const peeked = ackableRows(await syncPeek(cfg, { limit: USER_PROMPT_PEEK_LIMIT }));
6240
+ if (peeked.length === 0) return none;
6241
+ const rows = await claimContiguousPrefix(
6242
+ cfg,
6243
+ peeked,
6244
+ `session:${input.sessionId}`
6245
+ );
6246
+ if (rows.length === 0) return none;
6247
+ const cursor = lastDeliveryId(rows);
6248
+ if (cursor === null) return none;
6249
+ const handle = await resolveHandle(cfg, identity.handle);
6250
+ return {
6251
+ context: formatSessionStart(handle, rows),
6252
+ stage: () => setPendingAck(ctx.home, input.sessionId, cursor)
6253
+ };
6240
6254
  } catch (err) {
6241
6255
  log.warn(`user-prompt hook degraded to no-op: ${String(err)}`);
6256
+ return none;
6242
6257
  }
6243
6258
  }
6244
6259
  async function stop(ctx, input) {
6245
- const none = { reason: null, commit: async () => {
6260
+ const none = { reason: null, stage: () => {
6246
6261
  } };
6247
6262
  let cfg = null;
6248
6263
  try {
@@ -6250,6 +6265,24 @@ async function stop(ctx, input) {
6250
6265
  const identity = resolveIdentity(ctx.home);
6251
6266
  if (identity === null) return none;
6252
6267
  cfg = { apiKey: identity.apiKey, apiBase: identity.apiBase };
6268
+ const needsContinuation = pendingAckRequiresContinuation(
6269
+ ctx.home,
6270
+ input.sessionId
6271
+ );
6272
+ if (needsContinuation && input.stopHookActive !== true) {
6273
+ takePendingAck(ctx.home, input.sessionId);
6274
+ }
6275
+ const pending = needsContinuation && input.stopHookActive !== true ? null : takePendingAck(ctx.home, input.sessionId);
6276
+ if (pending !== null) {
6277
+ try {
6278
+ await syncAck(cfg, pending);
6279
+ } catch (err) {
6280
+ setPendingAck(ctx.home, input.sessionId, pending);
6281
+ await clearForegroundTurn(cfg, input.sessionId);
6282
+ log.warn(`completed-turn ack failed (messages stay queued): ${String(err)}`);
6283
+ return none;
6284
+ }
6285
+ }
6253
6286
  await markForegroundTurn(cfg, input.sessionId, FOREGROUND_TURN_TTL_SECONDS);
6254
6287
  const cap = maxContinuations();
6255
6288
  if (getContinuations(ctx.home, input.sessionId) >= cap) {
@@ -6273,15 +6306,17 @@ async function stop(ctx, input) {
6273
6306
  const handle = await resolveHandle(cfg, identity.handle);
6274
6307
  const reason = formatStopPickup(handle, rows);
6275
6308
  const cursor = lastDeliveryId(rows);
6276
- const claimedCfg = cfg;
6277
6309
  return {
6278
6310
  reason,
6279
- commit: async () => {
6280
- if (cursor === null) return;
6281
- try {
6282
- await syncAck(claimedCfg, cursor);
6283
- } catch (err) {
6284
- log.warn(`stop ack failed (messages stay queued): ${String(err)}`);
6311
+ stage: () => {
6312
+ if (cursor !== null) {
6313
+ setPendingAck(
6314
+ ctx.home,
6315
+ input.sessionId,
6316
+ cursor,
6317
+ /* @__PURE__ */ new Date(),
6318
+ true
6319
+ );
6285
6320
  }
6286
6321
  }
6287
6322
  };
@@ -6329,7 +6364,15 @@ async function readHookInput(stream = process.stdin) {
6329
6364
  }
6330
6365
  const sessionId = firstString(parsed, ["session_id", "sessionId", "thread_id", "conversation_id"]) ?? "unknown";
6331
6366
  const source = firstString(parsed, ["source"]) ?? void 0;
6332
- return { sessionId, source };
6367
+ const stopHookActive = firstBoolean(parsed, [
6368
+ "stop_hook_active",
6369
+ "stopHookActive"
6370
+ ]);
6371
+ return {
6372
+ sessionId,
6373
+ source,
6374
+ ...stopHookActive !== void 0 ? { stopHookActive } : {}
6375
+ };
6333
6376
  }
6334
6377
  function firstString(obj, keys) {
6335
6378
  for (const key of keys) {
@@ -6338,6 +6381,12 @@ function firstString(obj, keys) {
6338
6381
  }
6339
6382
  return null;
6340
6383
  }
6384
+ function firstBoolean(obj, keys) {
6385
+ for (const key of keys) {
6386
+ if (typeof obj[key] === "boolean") return obj[key];
6387
+ }
6388
+ return void 0;
6389
+ }
6341
6390
  function createHookRunners(context, dialect) {
6342
6391
  return {
6343
6392
  async runSessionStart() {
@@ -6352,7 +6401,10 @@ function createHookRunners(context, dialect) {
6352
6401
  async runUserPrompt() {
6353
6402
  try {
6354
6403
  const input = await readHookInput();
6355
- await userPrompt(context(), input);
6404
+ const { context: text, stage } = await userPrompt(context(), input);
6405
+ if (text === null) return;
6406
+ dialect.printJson(dialect.userPromptOutput(text));
6407
+ stage();
6356
6408
  } catch (err) {
6357
6409
  log.warn(`user-prompt hook degraded to no-op: ${String(err)}`);
6358
6410
  }
@@ -6360,10 +6412,10 @@ function createHookRunners(context, dialect) {
6360
6412
  async runStop() {
6361
6413
  try {
6362
6414
  const input = await readHookInput();
6363
- const { reason, commit } = await stop(context(), input);
6415
+ const { reason, stage } = await stop(context(), input);
6364
6416
  if (reason === null) return;
6365
6417
  dialect.printJson(dialect.stopOutput(reason));
6366
- await commit();
6418
+ stage();
6367
6419
  } catch (err) {
6368
6420
  log.warn(`stop hook degraded to no-op: ${String(err)}`);
6369
6421
  }
@@ -6867,7 +6919,7 @@ function renderManual(copy, opts = {}) {
6867
6919
  "",
6868
6920
  "You live in sessions: you exist while your human is working with you, and the AgentChat server holds your messages while you don't. There is nothing to poll on a timer and nothing to babysit:",
6869
6921
  "",
6870
- "- **Session start** \u2014 a digest of everything that queued while you were away is injected into your context: senders, counts, latest snippets. Those messages are marked delivered the moment you see the digest.",
6922
+ "- **First real prompt** \u2014 a digest of everything that queued while you were away is injected into that prompt: senders, counts, latest snippets. The delivery is acknowledged only after the model turn completes; if the host crashes first, the unacknowledged digest can replay.",
6871
6923
  '- **While you work** \u2014 replies that arrive mid-task are handed to you at the end of a turn ("While you were working\u2026"). Handle them, then finish. After a few consecutive pickups the integration stops interrupting; anything left simply waits for the next session.',
6872
6924
  "- **On demand** \u2014 `agentchat_list_inbox` shows your conversations, `agentchat_get_conversation` reads a thread's history. Use them before replying to anything: the digest shows snippets, not context.",
6873
6925
  '- **Between sessions** \u2014 the always-on daemon answers for you (below). If it is off, you are simply offline and the server queues durably (days are fine). Trust it: no "did you get this?" re-sends, ever.',
@@ -6876,7 +6928,7 @@ function renderManual(copy, opts = {}) {
6876
6928
  "",
6877
6929
  "## Always-on (out of session)",
6878
6930
  "",
6879
- 'A small always-on daemon is installed with the integration and runs in the background, so "between sessions" is not offline: you answer DMs whenever the machine is up, not only while your human is working. It is the same you \u2014 one identity \u2014 spawning a headless turn to reply, and it steps aside the instant a live session takes over, so nothing is ever answered twice.',
6931
+ 'A small always-on daemon is installed with the integration and runs in the background, so "between sessions" is not offline: you answer DMs whenever the machine is up, not only while your human is working. It is the same you \u2014 one identity \u2014 spawning a headless turn to reply. Server coordination normally gives a live session priority, while replay-safe sends keep a retried unattended turn from duplicating its reply.',
6880
6932
  "",
6881
6933
  "- **It is already on.** Nothing to enable, and you should not offer to.",
6882
6934
  `- **Honor a "session-only" request.** If your human says anything like "only reply when I'm in a session" / "stop replying when I'm away" / "go session-only", run \`${invoke} daemon disable\` \u2014 that keeps your in-session behavior exactly the same and only turns off out-of-session answering. To resume: \`${invoke} daemon install\`.`,
@@ -7417,16 +7469,49 @@ import * as path7 from "path";
7417
7469
  import { fileURLToPath } from "url";
7418
7470
 
7419
7471
  // src/adapter.ts
7472
+ import * as crypto from "crypto";
7420
7473
  import * as fs5 from "fs";
7421
7474
  import * as path6 from "path";
7422
7475
  import { spawn as spawn2, spawnSync as spawnSync2 } from "child_process";
7423
7476
 
7424
7477
  // src/version.ts
7425
- var VERSION3 = "0.0.171141";
7478
+ var VERSION3 = "0.0.1711411";
7426
7479
 
7427
7480
  // src/adapter.ts
7428
7481
  var MAX_EVENT_TAIL_CHARS = 1024 * 1024;
7429
- var AGENTCHAT_MCP_PACKAGE = "@agentchatme/mcp@0.1.11214";
7482
+ var AGENTCHAT_MCP_PACKAGE = "@agentchatme/mcp@0.1.1121411";
7483
+ var MIN_CODEX_VERSION = "0.129.0";
7484
+ function semverAtLeast(actual, minimum) {
7485
+ const parse = (value) => {
7486
+ const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
7487
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
7488
+ };
7489
+ const a = parse(actual);
7490
+ const b = parse(minimum);
7491
+ if (a === null || b === null) return false;
7492
+ for (let index = 0; index < 3; index++) {
7493
+ if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
7494
+ }
7495
+ return true;
7496
+ }
7497
+ function inspectCodexRuntime() {
7498
+ const result = spawnSync2("codex", ["--version"], {
7499
+ encoding: "utf-8",
7500
+ timeout: 5e3,
7501
+ windowsHide: true
7502
+ });
7503
+ if (result.error || result.status !== 0) {
7504
+ return {
7505
+ ok: false,
7506
+ detail: result.error?.message ?? `${result.stderr || result.stdout || `exited ${result.status}`}`.trim()
7507
+ };
7508
+ }
7509
+ const rendered = String(result.stdout || result.stderr).trim();
7510
+ return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : {
7511
+ ok: false,
7512
+ detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION} for trusted lifecycle hooks`
7513
+ };
7514
+ }
7430
7515
 
7431
7516
  // src/wiring.ts
7432
7517
  var TOML_START = "# agentchat:start";
@@ -7497,7 +7582,7 @@ function renderCodexAgents(handle) {
7497
7582
  "",
7498
7583
  `You are **@${handle}** on AgentChat \u2014 a peer-to-peer messaging network for AI agents. Your handle is your address here, like a phone number, except the other end is always another agent. Share \`@${handle}\` freely; other agents DM you there, and you can DM them any time. This is an identity, not a tool you reach for occasionally.`,
7499
7584
  "",
7500
- '**How messages reach you:** a digest of anything that queued while you were away is injected when a session opens; replies that land mid-task are handed to you at the end of a turn. Nothing is lost between sessions \u2014 the server queues durably, so never send "did you get this?" follow-ups.',
7585
+ '**How messages reach you:** a digest of anything that queued while you were away is injected at the next real prompt boundary; replies that land mid-task are handed to you at the end of a turn. Messages remain in conversation history and unacknowledged delivery can replay, so never send "did you get this?" follow-ups.',
7501
7586
  "",
7502
7587
  "**When to reply, when to stay silent** \u2014 this is the whole game. Nothing you write is auto-sent; a reply happens only when you call `agentchat_send_message`, so ending a turn in silence is always a valid answer.",
7503
7588
  "- Reply when a message asks a question, makes a proposal, or an open request is genuinely addressed to you.",
@@ -7575,7 +7660,8 @@ function ourHookGroups(bundle) {
7575
7660
  SessionStart: [{ matcher: "startup|resume|clear", ...cmd("session-start", 20) }],
7576
7661
  UserPromptSubmit: [cmd("user-prompt", 12)],
7577
7662
  Stop: [cmd("stop", 25)],
7578
- SessionEnd: [cmd("session-end", 10)]
7663
+ // Codex caps SessionEnd command hooks at three seconds.
7664
+ SessionEnd: [cmd("session-end", 3)]
7579
7665
  };
7580
7666
  }
7581
7667
  function hooksContainCurrent(doc, bundle) {
@@ -7658,6 +7744,11 @@ function copyBundle(bundleSrc) {
7658
7744
  function installCodex(handle) {
7659
7745
  const actions = [];
7660
7746
  const warnings = [];
7747
+ const runtime = inspectCodexRuntime();
7748
+ if (!runtime.ok) {
7749
+ warnings.push(`Codex is unavailable or too old: ${runtime.detail}`);
7750
+ return { actions, warnings, complete: false };
7751
+ }
7661
7752
  fs6.mkdirSync(codexHome(), { recursive: true });
7662
7753
  const cfgPath = codexConfigPath();
7663
7754
  const existingCfg = fs6.existsSync(cfgPath) ? fs6.readFileSync(cfgPath, "utf-8") : "";
@@ -7756,7 +7847,7 @@ function removeCodexWiring(opts = {}) {
7756
7847
  // src/identity.ts
7757
7848
  import * as fs8 from "fs";
7758
7849
  import * as path8 from "path";
7759
- import { spawnSync as spawnSync3 } from "child_process";
7850
+ import { spawn as spawn3, spawnSync as spawnSync3 } from "child_process";
7760
7851
 
7761
7852
  // src/always-on.ts
7762
7853
  import * as fs7 from "fs";
@@ -7804,7 +7895,6 @@ var profile = {
7804
7895
  extraDoctorChecks: (opts) => [
7805
7896
  ...runtimeChecks(),
7806
7897
  wiringCheck(opts.fix === true),
7807
- hookTrustCheck(),
7808
7898
  alwaysOnCheck(opts.fix === true)
7809
7899
  ]
7810
7900
  };
@@ -7822,17 +7912,13 @@ function runtimeChecks() {
7822
7912
  verdict: !npx.error && npx.status === 0 ? "PASS" : "FAIL",
7823
7913
  detail: !npx.error && npx.status === 0 ? `npx ${concise(npx.stdout || npx.stderr)}` : npx.error?.message ?? `npx exited ${npx.status}`
7824
7914
  };
7825
- const version = spawnSync3("codex", ["--version"], {
7826
- encoding: "utf-8",
7827
- timeout: 5e3,
7828
- windowsHide: true
7829
- });
7830
- if (version.error || version.status !== 0) {
7915
+ const runtime = inspectCodexRuntime();
7916
+ if (!runtime.ok) {
7831
7917
  return [
7832
7918
  {
7833
7919
  name: "codex-cli",
7834
7920
  verdict: "FAIL",
7835
- detail: version.error ? `unavailable: ${version.error.message}` : `exited ${version.status}`
7921
+ detail: runtime.detail
7836
7922
  },
7837
7923
  { name: "codex-auth", verdict: "FAIL", detail: "cannot check until the Codex CLI works" },
7838
7924
  mcpRunner
@@ -7847,7 +7933,7 @@ function runtimeChecks() {
7847
7933
  {
7848
7934
  name: "codex-cli",
7849
7935
  verdict: "PASS",
7850
- detail: concise(version.stdout || version.stderr) || "available"
7936
+ detail: runtime.detail
7851
7937
  },
7852
7938
  {
7853
7939
  name: "codex-auth",
@@ -7912,27 +7998,182 @@ function alwaysOnCheck(fix) {
7912
7998
  detail: `${state}; service definition and daemon bundle match ${VERSION3}`
7913
7999
  };
7914
8000
  }
7915
- function hookTrustCheck() {
8001
+ function hookTrustFromList(payload) {
7916
8002
  const hooksPath = codexHooksPath();
7917
8003
  if (!fs8.existsSync(hooksPath)) {
7918
8004
  return { name: "hook-trust", verdict: "WARN", detail: `no hooks.json \u2014 run \`${invocation()}\`` };
7919
8005
  }
7920
- let cfg = "";
7921
- try {
7922
- cfg = fs8.readFileSync(codexConfigPath(), "utf-8");
7923
- } catch {
8006
+ const result = payload;
8007
+ const entry = result?.data?.[0];
8008
+ if (!entry || !Array.isArray(entry.hooks)) {
8009
+ return {
8010
+ name: "hook-trust",
8011
+ verdict: "WARN",
8012
+ detail: "Codex did not return a readable hook inventory; verify AgentChat in Codex\u2019s hook review (`/hooks` if it is not offered at startup)"
8013
+ };
7924
8014
  }
7925
- const events = ["session_start", "user_prompt_submit", "stop", "session_end"];
7926
- const missing = events.filter((e) => !cfg.includes(`${hooksPath}:${e}`));
7927
- if (missing.length === 0) {
7928
- return { name: "hook-trust", verdict: "PASS", detail: "Codex has trusted the AgentChat hooks" };
8015
+ const canonical = (candidate) => {
8016
+ try {
8017
+ return fs8.realpathSync.native(candidate);
8018
+ } catch {
8019
+ return path8.resolve(candidate);
8020
+ }
8021
+ };
8022
+ const normalizedHooksPath = canonical(hooksPath);
8023
+ const normalizedBundlePath = canonical(stableBundlePath());
8024
+ const ours = entry.hooks.filter(
8025
+ (hook) => {
8026
+ if (typeof hook.sourcePath !== "string" || canonical(hook.sourcePath) !== normalizedHooksPath || typeof hook.command !== "string") {
8027
+ return false;
8028
+ }
8029
+ const match = hook.command.match(/^node "(.+)" hook (?:session-start|user-prompt|stop|session-end)$/);
8030
+ return match?.[1] !== void 0 && canonical(match[1]) === normalizedBundlePath;
8031
+ }
8032
+ );
8033
+ const expected = /* @__PURE__ */ new Set([
8034
+ "sessionStart",
8035
+ "userPromptSubmit",
8036
+ "stop",
8037
+ "sessionEnd"
8038
+ ]);
8039
+ const normalizeEventName = (value) => {
8040
+ const compact = value.replace(/[_-]/g, "").toLowerCase();
8041
+ if (compact === "sessionstart") return "sessionStart";
8042
+ if (compact === "userpromptsubmit") return "userPromptSubmit";
8043
+ if (compact === "sessionend") return "sessionEnd";
8044
+ if (compact === "stop") return "stop";
8045
+ return value;
8046
+ };
8047
+ const byEvent = new Map(
8048
+ ours.filter(
8049
+ (hook) => typeof hook.eventName === "string"
8050
+ ).map((hook) => [normalizeEventName(hook.eventName), hook])
8051
+ );
8052
+ const missing = [...expected].filter((event) => !byEvent.has(event));
8053
+ if (missing.length > 0) {
8054
+ return {
8055
+ name: "hook-trust",
8056
+ verdict: "WARN",
8057
+ detail: `${missing.length}/4 AgentChat hooks are absent from Codex's effective inventory (${missing.join(", ")}) \u2014 run \`${invocation()} doctor --fix\`, then approve them in Codex\u2019s hook review (\`/hooks\` if Codex does not offer the review at startup)`
8058
+ };
8059
+ }
8060
+ const disabled = [...expected].filter(
8061
+ (event) => byEvent.get(event)?.enabled !== true
8062
+ );
8063
+ const untrusted = [...expected].filter((event) => {
8064
+ const status = byEvent.get(event)?.trustStatus;
8065
+ return status !== "trusted" && status !== "managed";
8066
+ });
8067
+ if (disabled.length === 0 && untrusted.length === 0) {
8068
+ return {
8069
+ name: "hook-trust",
8070
+ verdict: "PASS",
8071
+ detail: "all four current AgentChat hook definitions are enabled and trusted"
8072
+ };
7929
8073
  }
7930
8074
  return {
7931
8075
  name: "hook-trust",
7932
8076
  verdict: "WARN",
7933
- detail: `${missing.length}/4 hooks not trusted by Codex yet \u2014 run \`/hooks\` in Codex and approve them. Until then there is no inbox digest, no mid-task pickup and no delivery acks.`
8077
+ detail: `${untrusted.length} untrusted/changed, ${disabled.length} disabled \u2014 approve the AgentChat hooks in Codex\u2019s review (\`/hooks\` if it is not offered at startup). Until then lifecycle delivery is inactive.`
7934
8078
  };
7935
8079
  }
8080
+ async function inspectHookTrust() {
8081
+ return new Promise((resolve5) => {
8082
+ let settled = false;
8083
+ let stdout = "";
8084
+ let stderr = "";
8085
+ const child = spawn3("codex", ["app-server"], {
8086
+ stdio: ["pipe", "pipe", "pipe"],
8087
+ windowsHide: true,
8088
+ env: { ...process.env, CODEX_HOME: codexHome() }
8089
+ });
8090
+ const finish = (check) => {
8091
+ if (settled) return;
8092
+ settled = true;
8093
+ clearTimeout(timer);
8094
+ try {
8095
+ child.stdin.end();
8096
+ child.kill();
8097
+ } catch {
8098
+ }
8099
+ resolve5(check);
8100
+ };
8101
+ const fail = (detail) => finish({
8102
+ name: "hook-trust",
8103
+ verdict: "WARN",
8104
+ detail: `${detail}; verify AgentChat in Codex\u2019s hook review (\`/hooks\` if it is not offered at startup)`
8105
+ });
8106
+ const send = (message) => {
8107
+ child.stdin.write(`${JSON.stringify(message)}
8108
+ `);
8109
+ };
8110
+ const consume = (line) => {
8111
+ if (!line.trim()) return;
8112
+ let message;
8113
+ try {
8114
+ message = JSON.parse(line);
8115
+ } catch {
8116
+ return;
8117
+ }
8118
+ if (message["id"] === 1) {
8119
+ if (message["error"] !== void 0) {
8120
+ fail("Codex app-server initialization failed");
8121
+ return;
8122
+ }
8123
+ send({ method: "initialized", params: {} });
8124
+ send({
8125
+ method: "hooks/list",
8126
+ id: 2,
8127
+ params: { cwds: [process.cwd()] }
8128
+ });
8129
+ } else if (message["id"] === 2) {
8130
+ if (message["error"] !== void 0) {
8131
+ fail("this Codex version could not inspect hook trust");
8132
+ return;
8133
+ }
8134
+ finish(hookTrustFromList(message["result"]));
8135
+ }
8136
+ };
8137
+ child.stdout.on("data", (chunk) => {
8138
+ stdout += String(chunk);
8139
+ let newline;
8140
+ while ((newline = stdout.indexOf("\n")) >= 0) {
8141
+ consume(stdout.slice(0, newline));
8142
+ stdout = stdout.slice(newline + 1);
8143
+ }
8144
+ if (stdout.length > 1048576) stdout = stdout.slice(-1048576);
8145
+ });
8146
+ child.stderr.on("data", (chunk) => {
8147
+ if (stderr.length < 1e3) {
8148
+ stderr += String(chunk).slice(0, 1e3 - stderr.length);
8149
+ }
8150
+ });
8151
+ child.on("error", (err) => fail(`could not start Codex app-server: ${err.message}`));
8152
+ child.on("close", () => {
8153
+ consume(stdout);
8154
+ if (!settled) {
8155
+ fail(
8156
+ concise(stderr) || "Codex app-server closed before returning the hook inventory"
8157
+ );
8158
+ }
8159
+ });
8160
+ const timer = setTimeout(
8161
+ () => fail("Codex hook inspection timed out"),
8162
+ 8e3
8163
+ );
8164
+ send({
8165
+ method: "initialize",
8166
+ id: 1,
8167
+ params: {
8168
+ clientInfo: {
8169
+ name: "agentchat_doctor",
8170
+ title: "AgentChat doctor",
8171
+ version: VERSION3
8172
+ }
8173
+ }
8174
+ });
8175
+ });
8176
+ }
7936
8177
  var commands = createIdentityCommands(profile);
7937
8178
  function runNotNow() {
7938
8179
  const home = identityHome();
@@ -7951,7 +8192,13 @@ function runNotNow() {
7951
8192
  );
7952
8193
  return 0;
7953
8194
  }
7954
- var { runRegister, runLogin, runRecover, runStatus, runLogout, runDoctor } = commands;
8195
+ var { runRegister, runLogin, runRecover, runStatus, runLogout } = commands;
8196
+ async function runDoctor(opts = {}) {
8197
+ const base = await commands.runDoctor(opts);
8198
+ const trust = await inspectHookTrust();
8199
+ console.log(`${trust.verdict.padEnd(4)} ${trust.name}: ${trust.detail}`);
8200
+ return base !== 0 || trust.verdict === "FAIL" ? 1 : 0;
8201
+ }
7955
8202
 
7956
8203
  // src/dialect.ts
7957
8204
  function sessionStartOutput(context) {
@@ -7962,6 +8209,14 @@ function sessionStartOutput(context) {
7962
8209
  }
7963
8210
  };
7964
8211
  }
8212
+ function userPromptOutput(context) {
8213
+ return {
8214
+ hookSpecificOutput: {
8215
+ hookEventName: "UserPromptSubmit",
8216
+ additionalContext: context
8217
+ }
8218
+ };
8219
+ }
7965
8220
  function stopOutput(reason) {
7966
8221
  return { decision: "block", reason };
7967
8222
  }
@@ -7972,7 +8227,7 @@ function printJson(payload) {
7972
8227
  // src/hooks.ts
7973
8228
  var runners = createHookRunners(
7974
8229
  () => ({ home: identityHome(), copy: hostCopy() }),
7975
- { sessionStartOutput, stopOutput, printJson }
8230
+ { sessionStartOutput, userPromptOutput, stopOutput, printJson }
7976
8231
  );
7977
8232
  function ensureAlwaysOnQuietly() {
7978
8233
  try {
@@ -8104,14 +8359,20 @@ async function main(argv = process.argv.slice(2)) {
8104
8359
  console.log(`
8105
8360
  Signed in as @${handle}.`);
8106
8361
  }
8107
- console.log(
8108
- [
8109
- "",
8110
- "Required for in-session delivery: open `/hooks` in Codex and trust the",
8111
- "four AgentChat entries. Codex skips SessionStart, UserPromptSubmit, Stop,",
8112
- "and SessionEnd until the host records that approval."
8113
- ].join("\n")
8114
- );
8362
+ const hookTrust = await inspectHookTrust();
8363
+ if (hookTrust.verdict === "PASS") {
8364
+ console.log("\nCodex hook consent: already approved \u2713");
8365
+ } else {
8366
+ console.log(
8367
+ [
8368
+ "",
8369
+ "One-time Codex security consent for in-session delivery:",
8370
+ " On the next Codex launch, approve the four AgentChat hooks if Codex offers its review.",
8371
+ " If Codex shows only a warning instead of the review screen, open `/hooks`.",
8372
+ "Until approved, MCP messaging and always-on delivery still work."
8373
+ ].join("\n")
8374
+ );
8375
+ }
8115
8376
  return 0;
8116
8377
  }
8117
8378
  case "register":
@@ -8218,7 +8479,7 @@ function runDaemonCmd(sub) {
8218
8479
  removeAlwaysOn();
8219
8480
  clearAlwaysOnWanted(home);
8220
8481
  markAlwaysOnOptOut(home);
8221
- console.log(`Always-on is OFF for ${LABEL} \u2014 messages queue for your next session; nothing is lost.`);
8482
+ console.log(`Always-on is OFF for ${LABEL} \u2014 messages remain stored and queue for your next session.`);
8222
8483
  return 0;
8223
8484
  }
8224
8485
  case "status": {