@murmurv2/cli 2.11.0 → 2.13.0

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 (69) hide show
  1. package/README.md +85 -19
  2. package/package.json +8 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +193 -81
  5. package/runtime/package.json +1 -1
  6. package/runtime/packages/mcp-server/dist/src/agent-config.js +1 -0
  7. package/runtime/packages/setup/bin/murmur.mjs +6 -3
  8. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  9. package/runtime/packages/setup/dist/src/backups.js +128 -0
  10. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  11. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  12. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  13. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  14. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  15. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  16. package/runtime/packages/setup/dist/src/cli.d.ts +1 -1
  17. package/runtime/packages/setup/dist/src/cli.js +111 -14
  18. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  19. package/runtime/packages/setup/dist/src/clients.js +166 -26
  20. package/runtime/packages/setup/dist/src/commands.d.ts +3 -1
  21. package/runtime/packages/setup/dist/src/commands.js +18 -7
  22. package/runtime/packages/setup/dist/src/config.d.ts +10 -0
  23. package/runtime/packages/setup/dist/src/config.js +119 -10
  24. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  25. package/runtime/packages/setup/dist/src/connect.js +126 -0
  26. package/runtime/packages/setup/dist/src/doctor.d.ts +42 -0
  27. package/runtime/packages/setup/dist/src/doctor.js +89 -10
  28. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  29. package/runtime/packages/setup/dist/src/installation.js +89 -0
  30. package/runtime/packages/setup/dist/src/invitation-server.d.ts +2 -0
  31. package/runtime/packages/setup/dist/src/invitation-server.js +45 -0
  32. package/runtime/packages/setup/dist/src/message-status.d.ts +5 -0
  33. package/runtime/packages/setup/dist/src/message-status.js +13 -0
  34. package/runtime/packages/setup/dist/src/onboarding.d.ts +28 -10
  35. package/runtime/packages/setup/dist/src/onboarding.js +129 -34
  36. package/runtime/packages/setup/dist/src/outbox-attention.js +3 -21
  37. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  38. package/runtime/packages/setup/dist/src/paths.js +39 -24
  39. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  40. package/runtime/packages/setup/dist/src/platform/darwin.js +241 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +152 -17
  42. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  43. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  44. package/runtime/packages/setup/dist/src/platform/windows.js +89 -4
  45. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  46. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  47. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  48. package/runtime/packages/setup/dist/src/state.js +65 -1
  49. package/runtime/packages/setup/dist/src/status.d.ts +26 -2
  50. package/runtime/packages/setup/dist/src/status.js +84 -20
  51. package/runtime/packages/setup/dist/src/types.d.ts +21 -1
  52. package/runtime/packages/setup/dist/src/verdict.js +4 -2
  53. package/runtime/packages/setup/dist/src/wake-attention.d.ts +11 -0
  54. package/runtime/packages/setup/dist/src/wake-attention.js +44 -0
  55. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  56. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  57. package/runtime/packages/setup/package.json +1 -1
  58. package/runtime/scripts/auth-security.mjs +93 -0
  59. package/runtime/scripts/codex-app-server-wake.mjs +182 -32
  60. package/runtime/scripts/daemon-contacts.mjs +56 -0
  61. package/runtime/scripts/daemon-flush-tick.mjs +25 -0
  62. package/runtime/scripts/daemon-link-watch.mjs +60 -0
  63. package/runtime/scripts/daemon-observation.mjs +74 -18
  64. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  65. package/runtime/scripts/murmur-daemon.mjs +66 -36
  66. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  67. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  68. package/runtime/scripts/wake-drain-claude.mjs +193 -39
  69. package/runtime/scripts/wake-monitor.mjs +46 -18
@@ -59,7 +59,7 @@ export function statusVerdict(input, now = Date.now()) {
59
59
  return out("grey", invalid);
60
60
  if (typeof s.schema !== "string" || !/^murmur\.status\/1(?:\.\d+)?$/.test(s.schema))
61
61
  return out("grey", "schema.unknown");
62
- unread = count(s.inbox?.unread) && s.inbox.unread > 0;
62
+ unread = count(s.wake?.delivery?.pendingUndelivered) && s.wake.delivery.pendingUndelivered > 0;
63
63
  const stamp = typeof s.generatedAt === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(s.generatedAt) ? Date.parse(s.generatedAt) : NaN;
64
64
  if (!Number.isFinite(stamp) || !Number.isFinite(now))
65
65
  return out("grey", "snapshot.unparsable");
@@ -69,7 +69,7 @@ export function statusVerdict(input, now = Date.now()) {
69
69
  return out("grey", "snapshot.future");
70
70
  if (s.service?.state === "stopped")
71
71
  return out("grey", "service.stopped");
72
- if (!["running", "failed"].includes(s.service?.state))
72
+ if (!["running", "running-unmanaged", "failed"].includes(s.service?.state))
73
73
  return out("grey", "service.unknown");
74
74
  if (s.service.state === "failed")
75
75
  return out("red", "service.failed");
@@ -101,6 +101,8 @@ export function statusVerdict(input, now = Date.now()) {
101
101
  note(name, "source-unreadable");
102
102
  switch (s.broker?.state) {
103
103
  case "unauthorized": return out("yellow", "broker.unauthorized");
104
+ // #276 — the client gave up for good; only a restart brings the link back.
105
+ case "closed": return out("red", "broker.closed");
104
106
  case "connected": break;
105
107
  case null:
106
108
  case undefined:
@@ -0,0 +1,11 @@
1
+ import type { ServiceContext } from './types.js';
2
+ /** Acknowledge an unknown accepted outcome; never replay it or claim it was read. */
3
+ export declare function dismissWake(c: ServiceContext, msgId: string, expectedAgent: string): Promise<{
4
+ schema: string;
5
+ agentId: string;
6
+ msgIds: import("node:sqlite").SQLOutputValue[];
7
+ status: string;
8
+ reason: string;
9
+ executed: boolean;
10
+ historyPreserved: boolean;
11
+ }>;
@@ -0,0 +1,44 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { lstat, mkdir, rmdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { loadConfig, validAgentId } from './config.js';
5
+ /** Acknowledge an unknown accepted outcome; never replay it or claim it was read. */
6
+ export async function dismissWake(c, msgId, expectedAgent) {
7
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,150}$/.test(msgId) || !validAgentId(expectedAgent))
8
+ throw new Error('wake.selection-invalid');
9
+ const lock = path.join(c.dataDir, '.setup-write.lock');
10
+ await mkdir(lock, { mode: 0o700 });
11
+ try {
12
+ const config = await loadConfig(c);
13
+ if (config.agentId !== expectedAgent)
14
+ throw new Error('wake.identity-changed');
15
+ const file = await lstat(c.storePath);
16
+ if (!file.isFile() || file.isSymbolicLink() || (typeof process.getuid === 'function' && file.uid !== process.getuid())) {
17
+ throw new Error('wake.store-invalid');
18
+ }
19
+ const db = new DatabaseSync(c.storePath);
20
+ try {
21
+ db.exec('PRAGMA busy_timeout=1000; BEGIN IMMEDIATE');
22
+ const row = db.prepare("SELECT wake_batch_id FROM local_messages WHERE direction='inbound' AND msg_id=?").get(msgId);
23
+ if (!row)
24
+ throw new Error('wake.dismiss-not-eligible');
25
+ const rows = db.prepare(`SELECT msg_id,wake_status,wake_error FROM local_messages WHERE direction='inbound'
26
+ AND (msg_id=? OR (wake_batch_id IS NOT NULL AND wake_batch_id=?))`).all(msgId, row.wake_batch_id);
27
+ if (rows.some(r => !['dlq', 'muted'].includes(String(r.wake_status)) || r.wake_error !== 'accepted-turn-unobservable')) {
28
+ throw new Error('wake.dismiss-not-eligible');
29
+ }
30
+ const update = db.prepare("UPDATE local_messages SET wake_status='muted',wake_next_at=NULL,wake_updated_at=? WHERE direction='inbound' AND msg_id=?");
31
+ for (const r of rows)
32
+ update.run(new Date().toISOString(), r.msg_id);
33
+ db.exec('COMMIT');
34
+ return { schema: 'murmur.wake-dismiss/1', agentId: config.agentId, msgIds: rows.map(r => r.msg_id),
35
+ status: 'muted', reason: 'accepted-turn-unobservable', executed: false, historyPreserved: true };
36
+ }
37
+ finally {
38
+ db.close();
39
+ }
40
+ }
41
+ finally {
42
+ await rmdir(lock);
43
+ }
44
+ }
@@ -0,0 +1,12 @@
1
+ import type { ServiceContext } from './types.js';
2
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
3
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
4
+ export declare function readWakeReaders(c: ServiceContext, home?: string): Promise<{
5
+ active: number | null;
6
+ measuredAt: string;
7
+ unknownReason: string;
8
+ } | {
9
+ active: number;
10
+ measuredAt: string;
11
+ unknownReason: null;
12
+ }>;
@@ -0,0 +1,65 @@
1
+ import { readdir, readFile, lstat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ const run = promisify(execFile);
8
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
9
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
10
+ export async function readWakeReaders(c, home = homedir()) {
11
+ const measuredAt = new Date().toISOString();
12
+ const unknown = (reason) => ({ active: null, measuredAt, unknownReason: reason });
13
+ if (!['linux', 'darwin'].includes(process.platform))
14
+ return unknown('wake.readers-platform-unavailable');
15
+ const store = path.resolve(c.storePath);
16
+ const key = createHash('sha256').update(store).digest('hex').slice(0, 8);
17
+ let files;
18
+ try {
19
+ files = (await readdir(home)).filter(name => new RegExp(`^\\.murmur-wake-lock-${key}(?:-[A-Za-z0-9_-]{1,8})?$`).test(name));
20
+ }
21
+ catch {
22
+ return unknown('wake.readers-directory-unavailable');
23
+ }
24
+ let active = 0;
25
+ for (const name of files) {
26
+ const file = path.join(home, name);
27
+ try {
28
+ const info = await lstat(file);
29
+ if (!info.isFile() || info.size > 64)
30
+ return unknown('wake.reader-lock-unverified');
31
+ const raw = await readFile(file, 'utf8'), pid = Number(raw.trim());
32
+ if (!Number.isSafeInteger(pid) || pid <= 0)
33
+ return unknown('wake.reader-lock-unverified');
34
+ try {
35
+ process.kill(pid, 0);
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ESRCH')
39
+ continue;
40
+ return unknown('wake.reader-process-unavailable');
41
+ }
42
+ let matches = false;
43
+ if (process.platform === 'linux') {
44
+ const args = (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\0');
45
+ matches = args.some(arg => arg.endsWith('/wake-drain-claude.mjs'))
46
+ && args[args.indexOf('--db') + 1] === store;
47
+ }
48
+ else {
49
+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'command='], { timeout: 2000, maxBuffer: 32768 });
50
+ matches = stdout.includes('/wake-drain-claude.mjs ') && stdout.includes(`--db ${store} `);
51
+ }
52
+ if (await readFile(file, 'utf8') !== raw)
53
+ return unknown('wake.reader-lock-changed');
54
+ if (!matches)
55
+ return unknown('wake.reader-process-unverified');
56
+ active++;
57
+ }
58
+ catch (error) {
59
+ if (error.code !== 'ENOENT')
60
+ return unknown('wake.reader-inspection-failed');
61
+ // The reader can finish between listing its lock and inspecting the process.
62
+ }
63
+ }
64
+ return { active, measuredAt, unknownReason: null };
65
+ }
@@ -1 +1 @@
1
- {"name":"@murmurv2/cli","private":true,"version":"2.11.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
1
+ {"name":"@murmurv2/cli","private":true,"version":"2.13.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
@@ -0,0 +1,93 @@
1
+ import path from "node:path";
2
+ import { RosterStore, authorizeInbound, parseAddress } from "@murmurv2/federation";
3
+ import { readPrivateJson } from "./secure-state.mjs";
4
+
5
+ export function normalizeAuthSecurity(config = {}, env = process.env, dataDir = ".") {
6
+ const settings = config.authz ?? {};
7
+ const rawEnforce = env.MURMUR_ENFORCE_AUTH ?? settings.enforce;
8
+ let enforce = false;
9
+ if (rawEnforce !== undefined) {
10
+ if (env.MURMUR_ENFORCE_AUTH !== undefined) {
11
+ if (rawEnforce === "1" || rawEnforce === "true") enforce = true;
12
+ else if (rawEnforce === "0" || rawEnforce === "false") enforce = false;
13
+ else throw new Error("auth-security-invalid:enforce");
14
+ } else if (typeof rawEnforce === "boolean") {
15
+ enforce = rawEnforce;
16
+ } else {
17
+ throw new Error("auth-security-invalid:enforce");
18
+ }
19
+ }
20
+ const localOrg = String(env.MURMUR_AUTH_LOCAL_ORG ?? settings.localOrg ?? "local").trim();
21
+ const agentId = String(config.agentId ?? "probe").trim();
22
+ const audience = parseAddress(agentId, localOrg);
23
+ const explicitRoster = env.MURMUR_ROSTER_PATH ?? settings.rosterPath;
24
+ const rosterPath = explicitRoster
25
+ ? path.resolve(dataDir, String(explicitRoster))
26
+ : path.join(dataDir, "federation-roster.json");
27
+ const rawScopes = settings.requiredScopes ?? ["murmur:send"];
28
+ if (!Array.isArray(rawScopes) || rawScopes.length === 0 || !rawScopes.every((s) => typeof s === "string" && s.length > 0)) {
29
+ throw new Error("auth-security-invalid:requiredScopes");
30
+ }
31
+ return {
32
+ enforce,
33
+ localOrg,
34
+ audience,
35
+ rosterPath,
36
+ rosterExplicit: Boolean(explicitRoster),
37
+ requiredScopes: [...rawScopes],
38
+ };
39
+ }
40
+
41
+ export async function loadRosterStoreFromBundle(rosterPath) {
42
+ const bundle = await readPrivateJson(rosterPath);
43
+ if (!bundle || typeof bundle !== "object" || typeof bundle.pinnedOrgKeys !== "object" || bundle.pinnedOrgKeys === null || !Array.isArray(bundle.rosters)) {
44
+ throw new Error("auth-roster-bundle-invalid");
45
+ }
46
+ const store = new RosterStore(bundle.pinnedOrgKeys);
47
+ for (const roster of bundle.rosters) {
48
+ const offered = await store.offer(roster);
49
+ if (!offered.accepted) {
50
+ throw new Error(`auth-roster-rejected:${roster?.org ?? "unknown"}:${offered.reason ?? "denied"}`);
51
+ }
52
+ }
53
+ return store;
54
+ }
55
+
56
+ export async function createDaemonInboundAuthorizer({ config = {}, env = process.env, dataDir = ".", log = () => {} }) {
57
+ const policy = normalizeAuthSecurity(config, env, dataDir);
58
+ if (!policy.enforce && !policy.rosterExplicit) {
59
+ return {
60
+ summary: { enforce: false, active: false, localOrg: policy.localOrg },
61
+ authorize: undefined,
62
+ };
63
+ }
64
+ const rosters = await loadRosterStoreFromBundle(policy.rosterPath);
65
+ const authorize = async (envelope) => {
66
+ const verdict = await authorizeInbound(envelope, rosters, {
67
+ localOrg: policy.localOrg,
68
+ audience: policy.audience,
69
+ requiredScopes: policy.requiredScopes,
70
+ enforce: policy.enforce,
71
+ });
72
+ if (!verdict.accepted) {
73
+ // Never log envelope.authToken; record only msgId, sender, audience and reject reason.
74
+ log("warn", "Inbound authorization rejected", {
75
+ reason: verdict.reason ?? "denied",
76
+ senderId: envelope.senderAgentId,
77
+ msgId: envelope.msgId,
78
+ conversationId: envelope.conversationId,
79
+ });
80
+ }
81
+ return verdict;
82
+ };
83
+ return {
84
+ summary: {
85
+ enforce: policy.enforce,
86
+ active: true,
87
+ localOrg: policy.localOrg,
88
+ rosterPath: policy.rosterPath,
89
+ requiredScopes: policy.requiredScopes,
90
+ },
91
+ authorize,
92
+ };
93
+ }
@@ -10,8 +10,10 @@ import path from "node:path";
10
10
  const DEFAULT_TIMEOUT_MS = 10000;
11
11
  const INITIALIZE_TIMEOUT_MS = 10000;
12
12
  const DEFAULT_TURN_COMPLETION_TIMEOUT_MS = 180000;
13
+ const DEFAULT_UNOBSERVABLE_TIMEOUT_MS = 300000;
13
14
  const SESSION_LOG_POLL_INTERVAL_MS = 1000;
14
15
  const SESSION_LOG_TAIL_BYTES = 8 * 1024 * 1024;
16
+ export const NO_REPLY_REQUIRED = '[[MURMUR_NO_REPLY_REQUIRED]]';
15
17
 
16
18
  const shellQuote = (value) => `'${String(value ?? "").replace(/'/g, "'\\''")}'`;
17
19
 
@@ -22,6 +24,7 @@ const buildReplyHint = (payload, peer = {}) => {
22
24
  "[MURMUR REPLY RELAY]",
23
25
  "If this Murmur message asks for a reply, put only the reply body in your final answer.",
24
26
  "Do not call tools to send Murmur yourself; the local daemon will relay your final answer back through Murmur.",
27
+ `If the message requires no substantive reply under the existing owner instructions (for example ACK, thanks, or an explicit no-reply notice), return exactly ${NO_REPLY_REQUIRED} as your final answer. This is a local completion receipt and is never sent to the peer. Do not use it for an unanswered question, missing access, or a failed task.`,
25
28
  ];
26
29
  }
27
30
 
@@ -87,15 +90,16 @@ const readSessionLogTail = (sessionPath) => {
87
90
  }
88
91
  };
89
92
 
90
- export const readFinalAnswerFromSessionLog = (sessionPath, turnId) => {
91
- if (!sessionPath || !turnId) return "";
93
+ const readTurnFromSessionLog = (sessionPath, turnId) => {
94
+ if (!sessionPath || !turnId) return null;
92
95
  let data = "";
93
96
  try {
94
97
  data = readSessionLogTail(sessionPath);
95
98
  } catch {
96
- return "";
99
+ return null;
97
100
  }
98
101
 
102
+ let finalText = '';
99
103
  const lines = data.split("\n").filter(Boolean);
100
104
  for (let index = lines.length - 1; index >= 0; index -= 1) {
101
105
  const line = lines[index];
@@ -110,7 +114,9 @@ export const readFinalAnswerFromSessionLog = (sessionPath, turnId) => {
110
114
 
111
115
  const payload = entry?.payload || {};
112
116
  if (entry.type === "event_msg" && payload.type === "task_complete" && payload.turn_id === turnId) {
113
- return typeof payload.last_agent_message === "string" ? payload.last_agent_message : "";
117
+ return { turnId, status: payload.error == null ? 'completed' : 'failed',
118
+ error: typeof payload.error === 'string' ? { message: payload.error } : payload.error ?? null,
119
+ finalText: typeof payload.last_agent_message === "string" ? payload.last_agent_message : finalText };
114
120
  }
115
121
 
116
122
  const metadataTurnId = payload?.internal_chat_message_metadata_passthrough?.turn_id;
@@ -121,12 +127,14 @@ export const readFinalAnswerFromSessionLog = (sessionPath, turnId) => {
121
127
  && metadataTurnId === turnId
122
128
  && Array.isArray(payload.content)
123
129
  ) {
124
- return payload.content.map((part) => part?.text || "").join("\n").trim();
130
+ finalText ||= payload.content.map((part) => part?.text || "").join("\n").trim();
125
131
  }
126
132
  }
127
- return "";
133
+ return finalText ? { turnId, status: 'inProgress', finalText } : null;
128
134
  };
129
135
 
136
+ export const readFinalAnswerFromSessionLog = (sessionPath, turnId) => readTurnFromSessionLog(sessionPath, turnId)?.finalText ?? '';
137
+
130
138
  export const buildThreadStartParams = (binding = null, peer = null) => ({
131
139
  model: binding?.model ?? peer?.model ?? null,
132
140
  modelProvider: null,
@@ -259,13 +267,24 @@ export class CodexAppServerClient {
259
267
  startTurnAndWaitForFinal(params, {
260
268
  completionTimeoutMs = DEFAULT_TURN_COMPLETION_TIMEOUT_MS,
261
269
  sessionPath = null,
270
+ acceptedTurn = null,
271
+ onAccepted = () => {},
272
+ onWorking = () => {},
273
+ onObservation = () => {},
274
+ unobservableTimeoutMs = DEFAULT_UNOBSERVABLE_TIMEOUT_MS,
275
+ pollIntervalMs = SESSION_LOG_POLL_INTERVAL_MS,
276
+ maxPollIntervalMs = 30000,
262
277
  } = {}) {
263
278
  return new Promise((resolve, reject) => {
264
279
  let settled = false;
265
280
  let initialized = false;
266
- let turnId = null;
281
+ let turnId = acceptedTurn?.turnId ?? null;
267
282
  let startResult = null;
268
283
  let finalText = "";
284
+ let receipt = Promise.resolve();
285
+ let observing = Boolean(turnId), polling = false, reported = null;
286
+ let unobservableSince = acceptedTurn?.unobservableSince ?? null;
287
+ let unobservableTimer = null, sessionLogTimer = null, pollDelay = pollIntervalMs;
269
288
  const requestId = this.nextId++;
270
289
  const initId = `init-${this.nextId++}`;
271
290
  const url = `ws+unix://${this.socketPath}:/`;
@@ -273,29 +292,86 @@ export class CodexAppServerClient {
273
292
  perMessageDeflate: false,
274
293
  handshakeTimeout: Math.min(this.timeoutMs, INITIALIZE_TIMEOUT_MS),
275
294
  });
276
- const timer = setTimeout(() => {
277
- finish(new Error(`codex-app-server-turn-completion-timeout:${this.socketPath}:${turnId || "unknown"}`));
278
- }, completionTimeoutMs);
279
- const sessionLogTimer = setInterval(() => {
280
- if (settled || !sessionPath || !turnId) return;
281
- const text = readFinalAnswerFromSessionLog(sessionPath, turnId);
282
- if (!text) return;
283
- finalText = finalText || text;
284
- finish(null, { ...startResult, finalText, turnId, source: "session-log" });
285
- }, SESSION_LOG_POLL_INTERVAL_MS);
295
+ const working = (reason) => {
296
+ observing = true;
297
+ if (reported !== reason) { reported = reason; onWorking({ threadId: params.threadId, turnId, reason }); }
298
+ };
299
+ const recordObservation = (since) => {
300
+ if (since === unobservableSince) return;
301
+ unobservableSince = since;
302
+ receipt = receipt.then(() => onObservation({ unobservableSince: since }));
303
+ receipt.catch(() => {});
304
+ };
305
+ const unavailable = () => {
306
+ if (settled) return;
307
+ if (!unobservableSince) recordObservation(new Date().toISOString());
308
+ working('accepted-turn-unobservable');
309
+ if (unobservableTimer === null) {
310
+ const remaining = unobservableTimeoutMs - (Date.now() - Date.parse(unobservableSince));
311
+ unobservableTimer = setTimeout(() => finish(Object.assign(
312
+ new Error('accepted-turn-unobservable'), { retryable: false })), Math.max(0, remaining));
313
+ }
314
+ };
315
+ const observable = () => {
316
+ clearTimeout(unobservableTimer); unobservableTimer = null;
317
+ recordObservation(null);
318
+ };
319
+ let timer = setTimeout(() => {
320
+ if (turnId) working('completion-window-elapsed');
321
+ else finish(new Error('codex-app-server-turn-start-timeout'));
322
+ }, turnId ? completionTimeoutMs : this.timeoutMs);
323
+ const accept = (id) => {
324
+ if (!id || turnId) return;
325
+ turnId = id;
326
+ try { receipt = Promise.resolve(onAccepted({ threadId: params.threadId, turnId, sessionPath })); }
327
+ catch (error) { receipt = Promise.reject(error); }
328
+ // Observe receipt-write failures immediately, without losing the accepted ID.
329
+ receipt.catch(() => {});
330
+ clearTimeout(timer);
331
+ timer = setTimeout(() => working('completion-window-elapsed'), completionTimeoutMs);
332
+ };
333
+ const inspect = async () => {
334
+ if (settled || !turnId || polling) return;
335
+ const savedTurn = sessionPath && readTurnFromSessionLog(sessionPath, turnId);
336
+ if (savedTurn && ['completed', 'failed'].includes(savedTurn.status)) {
337
+ finish(null, { ...startResult, ...savedTurn, finalText: finalText || savedTurn.finalText, source: "session-log" });
338
+ return;
339
+ }
340
+ if (!observing) return;
341
+ polling = true;
342
+ try {
343
+ const turn = await this.readTurn(params.threadId, turnId);
344
+ if (settled) return;
345
+ if (!turn || !['inProgress', 'completed', 'failed', 'interrupted'].includes(turn.status)) { unavailable(); return; }
346
+ observable();
347
+ if (turn.status === 'inProgress') return;
348
+ const answer = turn.items?.filter(item => item.type === 'agentMessage' && item.phase === 'final_answer')
349
+ .map(item => item.text ?? '').join('\n').trim();
350
+ finish(null, { finalText: finalText || answer || '', turnId, status: turn.status,
351
+ error: turn.error ?? null, source: 'app-server-read' });
352
+ } catch { unavailable(); }
353
+ finally { polling = false; }
354
+ };
355
+ const poll = async () => {
356
+ await inspect();
357
+ if (settled) return;
358
+ pollDelay = Math.min(maxPollIntervalMs, pollDelay * 2);
359
+ sessionLogTimer = setTimeout(poll, pollDelay);
360
+ };
361
+ sessionLogTimer = setTimeout(poll, pollDelay);
286
362
 
287
363
  const finish = (err, result) => {
288
364
  if (settled) return;
289
365
  settled = true;
290
366
  clearTimeout(timer);
291
- clearInterval(sessionLogTimer);
367
+ clearTimeout(sessionLogTimer);
368
+ clearTimeout(unobservableTimer);
292
369
  try {
293
370
  socket.close();
294
371
  } catch {
295
372
  // Ignore close races; the request already has a terminal result.
296
373
  }
297
- if (err) reject(err);
298
- else resolve(result);
374
+ receipt.then(() => err ? reject(err) : resolve(result), reject);
299
375
  };
300
376
 
301
377
  const sendJson = (message) => socket.send(JSON.stringify(message));
@@ -342,12 +418,17 @@ export class CodexAppServerClient {
342
418
 
343
419
  if (message.id === initId) {
344
420
  if (message.error) {
421
+ if (turnId) { unavailable(); return; }
345
422
  finish(new Error(`codex-app-server-initialize-error:${message.error.message || JSON.stringify(message.error)}`));
346
423
  return;
347
424
  }
348
425
  initialized = true;
349
426
  sendJson({ method: "initialized" });
350
- sendJson({ id: requestId, method: "turn/start", params });
427
+ if (acceptedTurn) {
428
+ // Subscribe to the existing thread; never submit this letter again.
429
+ sendJson({ id: requestId, method: "thread/resume", params: { threadId: params.threadId } });
430
+ void inspect();
431
+ } else sendJson({ id: requestId, method: "turn/start", params });
351
432
  return;
352
433
  }
353
434
 
@@ -355,37 +436,38 @@ export class CodexAppServerClient {
355
436
 
356
437
  if (message.id === requestId) {
357
438
  if (message.error) {
439
+ if (turnId) { unavailable(); return; }
358
440
  finish(new Error(`codex-app-server-error:${message.error.message || JSON.stringify(message.error)}`));
359
441
  return;
360
442
  }
361
443
  startResult = message.result;
362
- turnId = message.result?.turn?.id || turnId;
444
+ if (acceptedTurn) sessionPath = message.result?.thread?.path || sessionPath;
445
+ else accept(message.result?.turn?.id);
363
446
  return;
364
447
  }
365
448
 
449
+ if (!turnId || (message.params?.threadId && message.params.threadId !== params.threadId)) return;
366
450
  if (message.method === "turn/started" && message.params?.turn?.id) {
367
- turnId = turnId || message.params.turn.id;
368
451
  return;
369
452
  }
370
453
 
371
454
  if (message.method === "item/completed" && message.params?.turnId) {
372
- turnId = turnId || message.params.turnId;
373
455
  if (message.params.turnId !== turnId) return;
456
+ observable();
374
457
  const item = message.params.item;
375
458
  if (item?.type === "agentMessage" && item.phase === "final_answer" && typeof item.text === "string") {
376
459
  finalText = item.text;
377
- finish(null, { ...startResult, finalText, turnId, source: "app-server-final-item" });
378
460
  }
379
461
  return;
380
462
  }
381
463
 
382
464
  if (message.method === "turn/completed" && message.params?.turn?.id) {
383
- turnId = turnId || message.params.turn.id;
384
465
  if (message.params.turn.id !== turnId) return;
385
466
  // #106 — `turn.status` (completed | interrupted | failed | inProgress) and
386
467
  // `turn.error` are part of the notification; a caller that ignores them cannot
387
468
  // tell a finished turn from a broken one.
388
469
  const turn = message.params.turn;
470
+ if (turn.status === 'inProgress') { observable(); working('turn-in-progress'); return; }
389
471
  finish(null, {
390
472
  ...startResult,
391
473
  finalText,
@@ -397,13 +479,38 @@ export class CodexAppServerClient {
397
479
  }
398
480
  });
399
481
  socket.on("error", (err) => {
482
+ if (settled) return;
483
+ if (turnId) { unavailable(); return; }
400
484
  finish(new Error(`codex-app-server-connect-failed:${this.socketPath}:${err.message}`));
401
485
  });
402
486
  socket.on("close", () => {
487
+ if (settled) return;
488
+ if (turnId) { unavailable(); return; }
403
489
  if (!settled) finish(new Error(`codex-app-server-closed-before-response:${this.socketPath}:${initialized ? "after-initialize" : "before-initialize"}`));
404
490
  });
405
491
  });
406
492
  }
493
+
494
+ async readTurn(threadId, turnId) {
495
+ try {
496
+ const result = await this.request('thread/read', { threadId, includeTurns: true });
497
+ if (result?.thread?.id !== threadId) return null;
498
+ const turn = result.thread.turns?.find(turn => turn.id === turnId);
499
+ if (turn) return turn;
500
+ } catch (error) {
501
+ // New paginated threads reject the legacy full-history read.
502
+ if (!/paginat|includeTurns|full.history/i.test(error.message)) throw error;
503
+ }
504
+ let cursor;
505
+ for (let page = 0; page < 20; page++) {
506
+ const result = await this.request('thread/turns/list', { threadId, limit: 50, sortDirection: 'desc', itemsView: 'full', ...(cursor ? { cursor } : {}) });
507
+ const turn = result?.data?.find(turn => turn.id === turnId);
508
+ if (turn) return turn;
509
+ if (!result?.nextCursor || result.nextCursor === cursor) return null;
510
+ cursor = result.nextCursor;
511
+ }
512
+ return null;
513
+ }
407
514
  }
408
515
 
409
516
  /**
@@ -536,6 +643,15 @@ export const createCodexAppServerInjector = ({
536
643
  // so the mapping survives restarts; without one it still lives per conversation, only
537
644
  // in memory. A static `peer.threadId` is an explicit pin and is never written here.
538
645
  const memoryThreads = new Map();
646
+ const memoryTurns = new Map();
647
+ const turns = {
648
+ get: async msgId => memoryTurns.get(msgId) ?? await threadStore?.getWakeTurn?.(msgId),
649
+ set: async record => { memoryTurns.set(record.msgId, record); await threadStore?.setWakeTurn?.(record); },
650
+ delete: async (msgId, turnId) => {
651
+ await threadStore?.deleteWakeTurn?.(msgId, turnId);
652
+ if (memoryTurns.get(msgId)?.turnId === turnId) memoryTurns.delete(msgId);
653
+ },
654
+ };
539
655
  const threads = threadStore ?? {
540
656
  getWakeThread: async (peerId, conversationId) => memoryThreads.get(`${peerId}|${conversationId}`),
541
657
  setWakeThread: async (record) => { memoryThreads.set(`${record.peerId}|${record.conversationId}`, record); },
@@ -559,12 +675,17 @@ export const createCodexAppServerInjector = ({
559
675
  return { finalText: null, turnId: null, source: "relay-idempotent", replyMsgId };
560
676
  }
561
677
 
678
+ const accepted = await turns.get(payload.msgId);
679
+ if (accepted && (accepted.peerId !== String(payload.from ?? '')
680
+ || accepted.conversationId !== String(payload.conversationId ?? '') || accepted.socketPath !== socketPath)) {
681
+ throw Object.assign(new Error('codex-app-server-accepted-turn-binding-changed'), { retryable: false });
682
+ }
562
683
  const client = new Client({ socketPath, timeoutMs });
563
684
  const text = buildCodexTurnText(payload, peer);
564
685
  const threadStartBinding = peer?.threadStartBinding ?? (resolveThreadStartBinding ? await resolveThreadStartBinding(payload, peer) : null);
565
686
  const bindingMetadata = threadStartBinding?.metadata ?? {};
566
687
  const shouldResumeThread = peer?.resume === true || (peer?.resume !== false && peer?.relayFinalToMurmur === true);
567
- let threadPath = null;
688
+ let threadPath = accepted?.sessionPath ?? null;
568
689
  const resumeThread = async (threadId) => {
569
690
  if (!threadId || peer?.resume === false) return;
570
691
  try {
@@ -592,13 +713,30 @@ export const createCodexAppServerInjector = ({
592
713
  },
593
714
  });
594
715
  const startTurn = async (threadId) => {
595
- if (relayEnabled) {
716
+ // A configuration change must not turn an accepted receipt back into a
717
+ // fire-and-forget start. Observe it even if reply relay was disabled later.
718
+ if (relayEnabled || accepted) {
596
719
  const result = await client.startTurnAndWaitForFinal(turnParams(threadId), {
597
720
  completionTimeoutMs: Number(peer?.replyTimeoutMs) || DEFAULT_TURN_COMPLETION_TIMEOUT_MS,
598
721
  sessionPath: threadPath,
722
+ acceptedTurn: accepted,
723
+ unobservableTimeoutMs: peer?.unobservableTimeoutMs ?? DEFAULT_UNOBSERVABLE_TIMEOUT_MS,
724
+ onAccepted: async receipt => {
725
+ await turns.set({ ...receipt, msgId: payload.msgId, peerId: String(payload.from ?? ''),
726
+ conversationId: String(payload.conversationId ?? ''), socketPath });
727
+ log('info', 'Codex app-server wake turn accepted', { msgId: payload.msgId, threadId, turnId: receipt.turnId });
728
+ },
729
+ onWorking: ({ turnId, reason }) => log(reason === 'accepted-turn-unobservable' ? 'warn' : 'info',
730
+ reason === 'accepted-turn-unobservable' ? 'Codex accepted turn outcome unavailable; wake retained' : 'Codex Assistant still working; wake retained',
731
+ { msgId: payload.msgId, threadId, turnId, reason }),
732
+ onObservation: async ({ unobservableSince }) => {
733
+ const receipt = await turns.get(payload.msgId);
734
+ if (receipt) await turns.set({ ...receipt, unobservableSince });
735
+ },
599
736
  });
600
737
  const status = typeof result?.status === "string" ? result.status : null;
601
738
  if (status && status !== "completed") {
739
+ if (status === 'failed' && result.turnId) await turns.delete(payload.msgId, result.turnId);
602
740
  // #106 — a turn that failed or was interrupted is not a success, whatever text
603
741
  // it left behind. `failed` may clear on a retry (model/provider hiccup);
604
742
  // `interrupted` means someone stopped it on purpose — do not run it again.
@@ -616,7 +754,19 @@ export const createCodexAppServerInjector = ({
616
754
  { retryable: status === "failed" },
617
755
  );
618
756
  }
757
+ if (!relayEnabled) return result;
619
758
  const finalText = String(result?.finalText || "").trim();
759
+ if (finalText === NO_REPLY_REQUIRED && result?.status !== 'completed') {
760
+ throw Object.assign(new Error('codex-app-server-no-reply-completion-unverified'), {retryable:false});
761
+ }
762
+ if (finalText === NO_REPLY_REQUIRED) {
763
+ const receipt = await turns.get(payload.msgId);
764
+ if (receipt) await turns.set({...receipt, outcome:'no_reply_required'});
765
+ log('info', 'Codex app-server wake completed without a reply by explicit decision', {
766
+ msgId: payload.msgId, threadId, turnId: result.turnId, source: result.source,
767
+ });
768
+ return { ...result, finalText: null, replyMsgId: null, outcome: 'no_reply_required' };
769
+ }
620
770
  if (!finalText) {
621
771
  // #106 — the turn ended and there is nothing to relay. That is not a relay;
622
772
  // logging it as one is how the peer waited six hours believing it was answered.
@@ -670,9 +820,9 @@ export const createCodexAppServerInjector = ({
670
820
 
671
821
  // Resolution order: a remembered thread for this conversation, unless it was seeded to
672
822
  // replace a pin that has since changed; then the static pin; then a fresh seed.
673
- const remembered = await threads.getWakeThread(threadKey.peerId, threadKey.conversationId);
823
+ const remembered = accepted ? null : await threads.getWakeThread(threadKey.peerId, threadKey.conversationId);
674
824
  const rememberedUsable = remembered && (!peer?.threadId || !remembered.replacesThreadId || remembered.replacesThreadId === peer.threadId);
675
- let threadId = rememberedUsable ? remembered.threadId : peer?.threadId;
825
+ let threadId = accepted?.threadId ?? (rememberedUsable ? remembered.threadId : peer?.threadId);
676
826
  if (rememberedUsable && remembered.threadPath) threadPath = remembered.threadPath;
677
827
  let seededHere = false;
678
828
  if (!threadId) {
@@ -682,11 +832,11 @@ export const createCodexAppServerInjector = ({
682
832
 
683
833
  let result;
684
834
  try {
685
- if (shouldResumeThread && !seededHere) await resumeThread(threadId);
835
+ if (shouldResumeThread && !seededHere && !accepted) await resumeThread(threadId);
686
836
  result = await startTurn(threadId);
687
837
  } catch (err) {
688
838
  const e = err instanceof Error ? err : new Error(String(err));
689
- if (!e.message.startsWith("codex-app-server-error:thread not found:")) throw e;
839
+ if (accepted || !e.message.startsWith("codex-app-server-error:thread not found:")) throw e;
690
840
  threadId = await seedThread("re-seeded");
691
841
  result = await startTurn(threadId);
692
842
  }