borgmcp 4.2.1 → 4.2.3

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.
@@ -123,8 +123,116 @@ export function getLastDeliveredAt(): number | null {
123
123
  return lastDeliveredAt;
124
124
  }
125
125
 
126
+ // client#89: delivery-state observability. The Codex wake-path health surface
127
+ // must distinguish "bridge armed" from "delivery healthy" — a wake deferred
128
+ // (mid-turn) or failed and being retried is NOT a healthy wake path, even
129
+ // though the app-server socket is alive. These module-scoped fields track the
130
+ // last injection attempt/result and the last failure (a secret-free error
131
+ // code/class only — never message contents); the deferred-queue state is read
132
+ // live from the existing retry-drain fields. Same process as the health probe
133
+ // (the wake path and stream-status run in the same MCP-client child), so the
134
+ // snapshot is directly visible. NONE of this changes the wake mechanism.
135
+ type CodexInjectionResult = 'delivered' | 'deferred' | 'failed';
136
+ // HISTORICAL reporting — the last injection attempt/result/failure. These are
137
+ // surfaced on the status surface for diagnosis; they are NOT used to decide
138
+ // health, because a historical result does not self-clear when work is drained
139
+ // by another path (manual read, server read-cursor recovery). Health keys off
140
+ // the LIVE signals below.
141
+ let lastInjectionAt: number | null = null;
142
+ let lastInjectionResult: CodexInjectionResult | null = null;
143
+ let lastInjectionFailureCode: string | null = null;
144
+ let lastTargetThreadId: string | null = null;
145
+ // client#89: a LIVE marker for undelivered directed wakes NOT tracked by the
146
+ // retry-drain queue (retryDrainActive / deferredEntryCount cover that queue and
147
+ // self-clear on prune/deliver). SET at every injection exit where an
148
+ // authoritatively-pending wake could not be delivered and is not queued: the
149
+ // heartbeat mid-turn skip / no-target return / transient failure, the per-entry
150
+ // no-target return for a still-pending scoped entry, and the retry-drain age-out
151
+ // hand-off. CLEARED when any delivery lands (markDelivered) and when the
152
+ // heartbeat authoritatively finds no pending work. It is a LIVE signal, not a
153
+ // historical result, so a seat that recovers by any path returns to healthy.
154
+ let deliveryDeferred = false;
155
+
156
+ export interface CodexDeliveryState {
157
+ /** Opaque thread id of the last-resolved wake target (never a socket path). */
158
+ lastTargetThreadId: string | null;
159
+ /** HISTORICAL last attempt time (reporting only; not a health input). */
160
+ lastInjectionAt: number | null;
161
+ /** HISTORICAL last attempt result (reporting only; not a health input). */
162
+ lastInjectionResult: CodexInjectionResult | null;
163
+ /** Secret-free error code/class of the last failed injection; never contents. */
164
+ lastInjectionFailureCode: string | null;
165
+ /** LIVE: entries currently deferred/retrying (not yet confirmed delivered). */
166
+ deferredEntryCount: number;
167
+ /** LIVE: a coalesced retry-drain loop is currently retrying deferred/missed wakes. */
168
+ retryDrainActive: boolean;
169
+ /** LIVE: an undelivered directed wake not tracked by the retry-drain queue. */
170
+ deliveryDeferred: boolean;
171
+ lastDeliveredAt: number | null;
172
+ }
173
+
174
+ /** Snapshot of the Codex wake-path delivery state for the health/status surface. */
175
+ export function getCodexDeliveryState(): CodexDeliveryState {
176
+ return {
177
+ lastTargetThreadId,
178
+ lastInjectionAt,
179
+ lastInjectionResult,
180
+ lastInjectionFailureCode,
181
+ deferredEntryCount: retryDrainSourceEntryIds.size + (retryDrainHasUnscopedWork ? 1 : 0),
182
+ retryDrainActive: retryDrainInFlight,
183
+ deliveryDeferred,
184
+ lastDeliveredAt,
185
+ };
186
+ }
187
+
188
+ /** Reduce a caught error to a secret-free code/class — never its message. */
189
+ function injectionFailureCode(err: unknown): string {
190
+ const code = (err as { code?: unknown } | null)?.code;
191
+ if (typeof code === 'string' && code.length > 0) return code;
192
+ if (err instanceof Error && err.name) return err.name;
193
+ return 'unknown';
194
+ }
195
+
196
+ function recordInjectionResult(
197
+ result: CodexInjectionResult,
198
+ now: () => number,
199
+ failureCode?: string,
200
+ ): void {
201
+ lastInjectionAt = now();
202
+ lastInjectionResult = result;
203
+ lastInjectionFailureCode = result === 'failed' ? (failureCode ?? 'unknown') : null;
204
+ }
205
+
206
+ /**
207
+ * client#89: pure wake-path health for Codex, folding the LIVE delivery state
208
+ * into the raw "bridge armed" probe. A wake still pending redelivery — a live
209
+ * retry-drain, a non-empty deferred queue, or an undelivered heartbeat pending
210
+ * — is NOT a confirmed-healthy path (returns null = degraded). A positively-
211
+ * dead bridge dominates (false). Historical last-attempt results are NOT used
212
+ * here: they do not self-clear when work is drained by another path, so keying
213
+ * health off them would leave a recovered seat permanently degraded.
214
+ */
215
+ export function codexWakePathHealthy(
216
+ armed: boolean | null,
217
+ state: CodexDeliveryState,
218
+ ): boolean | null {
219
+ if (armed === false) return false; // positively-dead bridge
220
+ if (armed === null) return null; // could not probe → indeterminate
221
+ // Bridge armed. Degraded while any LIVE signal shows an unconfirmed delivery.
222
+ if (
223
+ state.retryDrainActive ||
224
+ state.deferredEntryCount > 0 ||
225
+ state.deliveryDeferred
226
+ ) {
227
+ return null;
228
+ }
229
+ return true;
230
+ }
231
+
126
232
  function markDelivered(deps: CodexWakeDeps): void {
127
233
  lastDeliveredAt = (deps.now ?? Date.now)();
234
+ // client#89: any confirmed delivery clears the live heartbeat-pending marker.
235
+ deliveryDeferred = false;
128
236
  }
129
237
 
130
238
  // gh#857 WI-2: a single-in-flight guard for the heartbeat tick (mirrors
@@ -327,8 +435,18 @@ async function wakeCodexTargeted(
327
435
  // gh#855: resolve FRESH (live env socket + re-resolved thread), falling back
328
436
  // to the launch-recorded file only when the env socket is absent.
329
437
  const resolved = await resolveFreshCodexWakeTarget(active, deps);
330
- if (!resolved) return;
438
+ if (!resolved) {
439
+ // client#89: a scoped entry passed the pending check above but no target
440
+ // resolves — undeliverable, and this path does NOT schedule a retry-drain
441
+ // (the design leaves it to the next wake / the heartbeat backstop). Mark
442
+ // the deferral live so health reads degraded rather than armed. An
443
+ // unscoped wake carries no authoritative pending signal, so it does not
444
+ // set the marker. Retry behavior is unchanged.
445
+ if (sourceEntryId) deliveryDeferred = true;
446
+ return;
447
+ }
331
448
  const { socketPath, threadId } = resolved;
449
+ lastTargetThreadId = threadId; // client#89: record the selected target
332
450
  const wakeKey = `${threadId}\0${deliveryIdentity ?? reason}`;
333
451
  if (deliveredWakeKeys.has(wakeKey)) return; // dedup before opening the wake socket
334
452
  const client = makeCodexClient(socketPath, deps);
@@ -340,21 +458,24 @@ async function wakeCodexTargeted(
340
458
  // now. Schedule the retry-drain (coalesced, retried-until-delivered) so
341
459
  // the burst's entries are drained once the thread goes idle; codex has no
342
460
  // on-disk tail fallback like Claude's borg-inbox-monitor.
461
+ recordInjectionResult('deferred', deps.now ?? Date.now); // client#89
343
462
  scheduleRetryDrain(deps, sourceEntryId);
344
463
  return;
345
464
  }
346
465
  if (sourceEntryId && !(await pendingEntry(active, sourceEntryId))) return;
347
466
  await client.startTurn(threadId, reason);
348
467
  rememberDeliveredWake(wakeKey);
468
+ recordInjectionResult('delivered', deps.now ?? Date.now); // client#89
349
469
  markDelivered(deps);
350
470
  } finally {
351
471
  client.close();
352
472
  }
353
- } catch {
473
+ } catch (err) {
354
474
  // gh#857: a transient connect/read/startTurn failure must NOT be silently
355
475
  // swallowed (the old best-effort drop let a single blip lose an entry).
356
476
  // Schedule the retry-drain so the wake is retried-until-delivered; the SSE
357
477
  // stream is never broken (this is fire-and-forget).
478
+ recordInjectionResult('failed', deps.now ?? Date.now, injectionFailureCode(err)); // client#89
358
479
  scheduleRetryDrain(deps, sourceEntryId);
359
480
  } finally {
360
481
  releaseInjectLock();
@@ -414,11 +535,13 @@ async function runRetryDrainLoop(deps: CodexWakeDeps): Promise<void> {
414
535
  const resolved = await resolveFreshCodexWakeTarget(active, deps);
415
536
  if (!resolved) continue; // thread not loaded yet → retry (age-capped)
416
537
  const { socketPath, threadId } = resolved;
538
+ lastTargetThreadId = threadId; // client#89: record the selected target
417
539
  const client = makeCodexClient(socketPath, deps);
418
540
  await client.connect();
419
541
  try {
420
542
  const thread = await client.readThread(threadId);
421
543
  if (thread?.status?.type === 'active') {
544
+ recordInjectionResult('deferred', now); // client#89
422
545
  continue; // re-defer: still mid-turn (backoff before next poll)
423
546
  }
424
547
  for (const entryId of retryDrainSourceEntryIds) {
@@ -428,19 +551,31 @@ async function runRetryDrainLoop(deps: CodexWakeDeps): Promise<void> {
428
551
  await client.startTurn(threadId, CODEX_CATCHUP_PROMPT);
429
552
  retryDrainSourceEntryIds.clear();
430
553
  retryDrainHasUnscopedWork = false;
554
+ recordInjectionResult('delivered', now); // client#89
431
555
  markDelivered(deps);
432
556
  return; // drain delivered → server read-cursor drains all unread → done
433
557
  } finally {
434
558
  client.close();
435
559
  }
436
- } catch {
560
+ } catch (err) {
437
561
  // transient socket/read error must not abort the loop — keep retrying with
438
562
  // backoff until reachable+idle or the age cap; never throws into SSE.
563
+ recordInjectionResult('failed', now, injectionFailureCode(err)); // client#89
439
564
  } finally {
440
565
  releaseInjectLock();
441
566
  }
442
567
  }
443
568
  // aged out: the gh#857 WI-2 periodic heartbeat is the ultimate backstop.
569
+ // client#89: if obligations remain unfinished (the thread stayed mid-turn
570
+ // through the age cap), the loop is gone but the entries are still pending.
571
+ // Hand off to the live marker and clear the retry-drain set, so health stays
572
+ // degraded (not stuck via a stale deferredEntryCount after the loop exits)
573
+ // and clears when a delivery lands or the unread authoritatively empties.
574
+ if (retryDrainSourceEntryIds.size > 0 || retryDrainHasUnscopedWork) {
575
+ retryDrainSourceEntryIds.clear();
576
+ retryDrainHasUnscopedWork = false;
577
+ deliveryDeferred = true;
578
+ }
444
579
  }
445
580
 
446
581
  /**
@@ -484,16 +619,41 @@ export async function fireCodexHeartbeatTick(
484
619
  // authoritative unread state without advancing its cursor; only then touch
485
620
  // the app-server socket or resolve a thread.
486
621
  const hasPendingWork = deps.hasPendingWork ?? hasPendingWakeActivity;
487
- if (!(await hasPendingWork(active))) return;
622
+ if (!(await hasPendingWork(active))) {
623
+ // client#89: authoritative unread is empty → no undelivered wake remains.
624
+ // Clear the live heartbeat-pending marker so a seat that recovered by any
625
+ // path (manual read, server read-cursor drain) returns to healthy.
626
+ deliveryDeferred = false;
627
+ return;
628
+ }
488
629
  const resolved = await resolveFreshCodexWakeTarget(active, deps);
489
- if (!resolved) return; // thread not loaded yet → next tick retries
630
+ if (!resolved) {
631
+ // client#89: authoritative pending work exists but no fresh target/thread
632
+ // resolves — the wake is UNDELIVERABLE this tick. The persisted-target
633
+ // probe can still read armed, so mark the deferral live (health degraded)
634
+ // until a target resolves and delivers, or the unread authoritatively
635
+ // clears. Cadence/retry behavior is unchanged (the next tick still tries).
636
+ deliveryDeferred = true;
637
+ return; // thread not loaded yet → next tick retries
638
+ }
639
+ lastTargetThreadId = resolved.threadId; // client#89: record the selected target
490
640
  const client = makeCodexClient(resolved.socketPath, deps);
491
641
  await client.connect();
492
642
  try {
493
643
  const thread = await client.readThread(resolved.threadId);
494
- if (thread?.status?.type === 'active') return; // mid-turn → skip; next tick retries
644
+ if (thread?.status?.type === 'active') {
645
+ // client#89: we passed hasPendingWork above, so a mid-turn thread here
646
+ // means a directed entry is deferred. Mark it LIVE-pending (the heartbeat
647
+ // does not queue into the retry-drain) so the health surface reads
648
+ // degraded until a delivery lands or the unread authoritatively clears.
649
+ // Skip semantics are unchanged — the next tick still retries.
650
+ recordInjectionResult('deferred', deps.now ?? Date.now);
651
+ deliveryDeferred = true;
652
+ return; // mid-turn → skip; next tick retries
653
+ }
495
654
  await client.startTurn(resolved.threadId, CODEX_CATCHUP_PROMPT);
496
- // markDelivered updates local heartbeat-gating state only.
655
+ // markDelivered clears the live heartbeat-pending marker.
656
+ recordInjectionResult('delivered', deps.now ?? Date.now); // client#89
497
657
  markDelivered(deps);
498
658
  } finally {
499
659
  client.close();
@@ -503,6 +663,11 @@ export async function fireCodexHeartbeatTick(
503
663
  // path is gone; signal teardown so the timer stops ticking against a dead
504
664
  // socket (re-armed when an active cube returns). Other (transient) errors are
505
665
  // best-effort skips — never break the SSE stream; next tick retries.
666
+ // client#89: we passed hasPendingWork, so a failure here leaves pending work
667
+ // undelivered → mark it live-pending (a dead bridge is separately false via
668
+ // the armed probe). Clears on the next authoritative-empty tick or delivery.
669
+ recordInjectionResult('failed', deps.now ?? Date.now, injectionFailureCode(err)); // client#89
670
+ deliveryDeferred = true;
506
671
  if (isAppServerDeadError(err)) deps.onAppServerSocketDead?.();
507
672
  } finally {
508
673
  heartbeatInFlight = false;
@@ -552,6 +717,12 @@ export function resetCodexWakeForTests(): void {
552
717
  lastDeliveredAt = null;
553
718
  heartbeatInFlight = false;
554
719
  injectInFlight = false;
720
+ // client#89 delivery-state observability
721
+ lastInjectionAt = null;
722
+ lastInjectionResult = null;
723
+ lastInjectionFailureCode = null;
724
+ lastTargetThreadId = null;
725
+ deliveryDeferred = false;
555
726
  }
556
727
 
557
728
  function rememberDeliveredWake(key: string): void {
package/src/index.ts CHANGED
@@ -253,6 +253,18 @@ export function formatUpdatedRoleResult(role: { name: string; id: string; role_c
253
253
  return appendServerAdvisory(`Updated role **${role.name}**${tag} (id: ${role.id}).`, advisory);
254
254
  }
255
255
 
256
+ // gh#501: the borg_tool dispatcher only requires its inner arguments to be an
257
+ // object, so the direct-tool enum schema does not guard borg_ack.kind. Resolve
258
+ // it explicitly: ONLY a missing kind (undefined) defaults to 'ack' (the
259
+ // documented default). A valid kind passes through; every present value —
260
+ // including an explicit null — that is not 'ack'/'claim' is REFUSED rather
261
+ // than silently coerced into a state-changing acknowledgement.
262
+ export function resolveAckKind(raw: unknown): 'ack' | 'claim' {
263
+ if (raw === undefined) return 'ack';
264
+ if (raw === 'ack' || raw === 'claim') return raw;
265
+ throw new Error('kind must be "ack" or "claim" when provided');
266
+ }
267
+
256
268
  // gh#496: the unread drain runs on every wake, so its structured payload must
257
269
  // stay proportional to the entries it returns. Rosters are deliberately NOT
258
270
  // included — entries already carry drone_label/role_name, and borg_roster
@@ -1082,10 +1094,10 @@ export async function main() {
1082
1094
  if (!entryId || typeof entryId !== 'string') {
1083
1095
  throw new Error('entry_id is required');
1084
1096
  }
1085
- // gh#418: default 'ack'. Only 'claim' is the other allowed kind; the
1086
- // worker re-validates at the Zod boundary so an unknown value is
1087
- // rejected server-side, but normalize here to keep the wire clean.
1088
- const kind: 'ack' | 'claim' = args?.kind === 'claim' ? 'claim' : 'ack';
1097
+ // gh#418/gh#501: absent kind defaults to 'ack'; a present invalid
1098
+ // value is refused here (not coerced) so a dispatcher call cannot
1099
+ // turn a typo into a state-changing acknowledgement.
1100
+ const kind: 'ack' | 'claim' = resolveAckKind(args?.kind);
1089
1101
  const active = await requireActiveCube();
1090
1102
  await ackLogEntry(
1091
1103
  active.sessionToken,
@@ -277,6 +277,20 @@ export function renderStreamStatus(inputs: RenderInputs): string {
277
277
  );
278
278
  }
279
279
 
280
+ // client#89: Codex remote-control delivery state — distinct from SSE health.
281
+ // Surfaces the selected target, last bounded injection attempt/result,
282
+ // deferred-queue state, and last failure (a secret-free code/class only).
283
+ if (wakePath.agentKind === 'codex' && wakePath.codex) {
284
+ const d = wakePath.codex;
285
+ lines.push(`- **Codex wake target thread**: ${d.lastTargetThreadId ?? '_(none resolved yet)_'}`);
286
+ lines.push(`- **Codex last injection**: ${d.lastInjectionResult ?? '_(none yet)_'}${d.lastInjectionAt ? ` at ${new Date(d.lastInjectionAt).toISOString()}` : ''}`);
287
+ lines.push(`- **Codex deferred/retrying entries**: ${d.deferredEntryCount}${d.retryDrainActive ? ' (retry-drain active)' : ''}${d.deliveryDeferred ? ' — undelivered wake pending' : ''}`);
288
+ lines.push(`- **Codex last failure code**: ${d.lastInjectionFailureCode ?? '_(none)_'}`);
289
+ lines.push(
290
+ '- **Codex delivery-state meaning**: a deferred or retrying wake means a directed entry has not yet been confirmed delivered to the model — the wake path reads degraded (not healthy) until the wake is delivered or the unread log is drained, even though the app-server bridge is armed.'
291
+ );
292
+ }
293
+
280
294
  // Runtime-specific wake-path warning. The wire-down case takes
281
295
  // precedence above; an indeterminate signal remains honest and silent.
282
296
  if (status.connected && wakePathHealthy === false) {
@@ -7,7 +7,7 @@
7
7
  * CONTRACT-BACKED DATA — imports only published scalar contract constants, with
8
8
  * no client runtime side effects.
9
9
  */
10
- import { DECISION_TEXT_MAX_BYTES, DOCUMENT_CONTENT_TYPES } from 'borgmcp-shared/protocol';
10
+ import { DECISION_TEXT_MAX_BYTES, DEFAULT_MAX_LOG_ENTRY_BYTES, DOCUMENT_CONTENT_TYPES } from 'borgmcp-shared/protocol';
11
11
 
12
12
  /**
13
13
  * gh#492: JSON Schema contract for a tool's `structuredContent`. Success
@@ -420,7 +420,7 @@ const BASE_TOOL_MANIFEST: ToolManifestEntry[] = [
420
420
  inputSchema: {
421
421
  type: 'object',
422
422
  properties: {
423
- message: { type: 'string', description: 'The log message (max 10KB).' },
423
+ message: { type: 'string', description: `The log message. Default limit ${DEFAULT_MAX_LOG_ENTRY_BYTES} bytes (server-configurable); a longer post is refused — store the detail as a document and cite it.` },
424
424
  // Keep this required value schema combinator-free for flat tool
425
425
  // serializers. normalizeLogAudience remains the strict boundary.
426
426
  to: {
@@ -879,7 +879,9 @@ export const TOOL_OUTPUT_SCHEMAS: Record<string, OutputSchema> = {
879
879
  },
880
880
  },
881
881
  wake_path: { type: 'object', description: 'Runtime-specific wake-path inspection.' },
882
- inbox_monitor_healthy: { type: 'boolean' },
882
+ // gh#500: null when wake-path health is indeterminate (a real state,
883
+ // distinct from false=determined-unhealthy); the source is boolean|null.
884
+ inbox_monitor_healthy: { type: ['boolean', 'null'] },
883
885
  inbox_path: { type: ['string', 'null'] },
884
886
  monitor_state_root: { type: ['string', 'null'] },
885
887
  drone_label: { type: ['string', 'null'] },
@@ -1173,7 +1175,8 @@ export const TOOL_OUTPUT_SCHEMAS: Record<string, OutputSchema> = {
1173
1175
  decision_topics: { type: 'array', items: { type: 'string' } },
1174
1176
  running_version: { type: 'string' },
1175
1177
  on_disk_version: { type: ['string', 'null'] },
1176
- wake_path_healthy: { type: 'boolean' },
1178
+ // gh#500: null when wake-path health is indeterminate (boolean|null source).
1179
+ wake_path_healthy: { type: ['boolean', 'null'] },
1177
1180
  },
1178
1181
  required: ['connected'],
1179
1182
  },
@@ -1,4 +1,9 @@
1
- import { probeCodexBridgeArmed } from './codex-app-wake.js';
1
+ import {
2
+ probeCodexBridgeArmed,
3
+ getCodexDeliveryState,
4
+ codexWakePathHealthy,
5
+ type CodexDeliveryState,
6
+ } from './codex-app-wake.js';
2
7
  import { checkInboxMonitorHealthy } from './stream-status.js';
3
8
  import {
4
9
  getOpenCodeConnectionState,
@@ -10,6 +15,8 @@ export interface WakePathSnapshot {
10
15
  agentKind: AgentKind;
11
16
  healthy: boolean | null;
12
17
  openCode: OpenCodeConnectionState | null;
18
+ // client#89: Codex remote-control delivery state, distinct from SSE health.
19
+ codex?: CodexDeliveryState | null;
13
20
  }
14
21
 
15
22
  interface InspectWakePathInputs {
@@ -22,6 +29,7 @@ interface InspectWakePathInputs {
22
29
  interface InspectWakePathDeps {
23
30
  checkClaudeMonitor?: typeof checkInboxMonitorHealthy;
24
31
  probeCodex?: typeof probeCodexBridgeArmed;
32
+ getCodexDelivery?: typeof getCodexDeliveryState;
25
33
  getOpenCodeState?: typeof getOpenCodeConnectionState;
26
34
  }
27
35
 
@@ -67,11 +75,18 @@ export async function inspectWakePath(
67
75
  }
68
76
 
69
77
  if (inputs.agentKind === 'codex') {
78
+ // client#89: fold the delivery state into health so a deferred, retrying,
79
+ // or failed injection surfaces as degraded — never as armed/healthy — even
80
+ // while the app-server socket is alive. SSE health is not the discriminator.
70
81
  const probe = deps.probeCodex ?? probeCodexBridgeArmed;
82
+ const getDelivery = deps.getCodexDelivery ?? getCodexDeliveryState;
83
+ const armed = await probe(inputs.active);
84
+ const codex = getDelivery();
71
85
  return {
72
86
  agentKind: inputs.agentKind,
73
- healthy: await probe(inputs.active),
87
+ healthy: codexWakePathHealthy(armed, codex),
74
88
  openCode: null,
89
+ codex,
75
90
  };
76
91
  }
77
92