@agfpd/iapeer 0.4.44 → 0.4.46

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agfpd/iapeer",
3
- "version": "0.4.44",
3
+ "version": "0.4.46",
4
4
  "description": "Run Claude Code and Codex CLI as local background agents that message each other, wake on demand, and share one memory.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "agfpd",
@@ -200,6 +200,9 @@ function errResult(text: string): ToolResult {
200
200
  /** Injected seams for callTool — all OPTIONAL, all wired by the composition point
201
201
  * (daemon/main.ts); library/test callers omit them and stay hermetic. */
202
202
  export interface CallToolDeps {
203
+ /** Б7 — injected env for the request-path registry read + routeSend (daemon:286 isolation). Default
204
+ * process.env; the production daemon threads its startDaemon env here. */
205
+ env?: NodeJS.ProcessEnv
203
206
  /** Wake-on-miss primitive (Ф2) — see StartDaemonOptions.wake. */
204
207
  wake?: WakeFn
205
208
  /** Per-delivery outcome log dir (Ф-#8a) — see StartDaemonOptions.deliveryLogDir. */
@@ -243,6 +246,7 @@ export async function callTool(
243
246
  }
244
247
  const t0 = Date.now()
245
248
  const sent = await routeSend(caller, input, {
249
+ env: deps.env,
246
250
  wake: deps.wake,
247
251
  ephemeral: deps.ephemeral,
248
252
  noteLiveTopic: deps.noteLiveTopic,
@@ -311,7 +315,7 @@ export function createMcpServer(deps: CallToolDeps = {}): Server {
311
315
  const headerIdentity = headerFromRequestInfo(extra as never)
312
316
  let caller: ResolvedCaller
313
317
  try {
314
- caller = resolveCallerFromHeader(headerIdentity, readPeersIndex())
318
+ caller = resolveCallerFromHeader(headerIdentity, readPeersIndex({ env: deps.env }))
315
319
  } catch (e) {
316
320
  // No silent default — reject the CallTool when identity is missing/invalid.
317
321
  if (process.env.IAPEER_DAEMON_LOG) {
@@ -459,6 +463,7 @@ export async function startDaemon(opts: StartDaemonOptions = {}): Promise<Daemon
459
463
  return
460
464
  }
461
465
  const server = createMcpServer({
466
+ env: opts.env, // Б7 — thread the daemon's storage env into the request path (registry read + routeSend)
462
467
  wake: opts.wake,
463
468
  deliveryLogDir: opts.deliveryLogDir,
464
469
  onDelivered: opts.onDelivered,
@@ -66,16 +66,38 @@ const CLAUDE_BOOT_DIALOG_MARKERS = [
66
66
  // lowercase "bypass permissions on" (a DISTINCT string), so this marker vanishes —
67
67
  // it never falsely traps isInputReady, and a re-launch is dialog-free (verified).
68
68
  'Bypass Permissions mode',
69
- // Project MCP-server approval ("N new MCP servers found in this project", servers
70
- // pre-checked [✔]) — shown when cwd carries a .mcp.json the config has not yet
71
- // approved. Suppressed at the source by enableAllProjectMcpServers in
72
- // <cwd>/.claude/settings.json (init writes it); bootDialogKeys Enter-confirms it as
73
- // a backstop. Substring matches both "1 new MCP server" and "N new MCP servers".
74
- 'new MCP server',
75
69
  ] as const
76
70
 
71
+ // В39 — Project MCP-server approval ("N new MCP servers found in this project", servers pre-checked
72
+ // [✔]). This one is NOT a plain substring marker: agents on this fleet mention "new MCP server" in
73
+ // NORMAL conversation, and a resumed session replays that tail into the viewport → the old substring
74
+ // gated isInputReady forever, the wake failed 'never-became-ready', the message was lost (live
75
+ // incident). Require the dialog's DISTINGUISHING context ("found in this project") too — a
76
+ // conversational mention of the topic phrase does not carry it. Suppressed at the source by
77
+ // enableAllProjectMcpServers (init); Enter-confirmed here as a backstop.
78
+ function mcpApprovalActive(pane: string): boolean {
79
+ return pane.includes('new MCP server') && pane.includes('found in')
80
+ }
81
+
77
82
  function anyBootDialog(pane: string): boolean {
78
- return CLAUDE_BOOT_DIALOG_MARKERS.some(m => pane.includes(m))
83
+ return CLAUDE_BOOT_DIALOG_MARKERS.some(m => pane.includes(m)) || mcpApprovalActive(pane)
84
+ }
85
+
86
+ // В40 — the fullscreen-renderer nag needles are BUILT from fragments so this SOURCE FILE never contains
87
+ // the verbatim modal text. A nag-watcher reads a peer's live VIEWPORT; if this file's text (a peer
88
+ // editing/reviewing it) carried the contiguous phrase, viewing it would self-trigger the very bug — which
89
+ // is exactly what happened live while this fix was being written. Split literals keep the match working at
90
+ // runtime while making the source inert.
91
+ const NAG_TITLE = 'Try the new fullscreen render' + 'er?'
92
+ const NAG_OPTION_YES = 'Yes, ' + 'try it'
93
+ /** Does the pane carry the fullscreen-renderer nag at all (cheap gate)? */
94
+ function isFullscreenNagText(pane: string): boolean {
95
+ return pane.includes(NAG_TITLE)
96
+ }
97
+ /** Is THIS row the modal's LIVE selected option (cursor `❯` on "1. Yes, try it")? The bottom-most `❯`
98
+ * row of a live modal is this; a mere quote of the modal has the ready composer `❯` below it instead. */
99
+ function isFullscreenNagOptionRow(row: string): boolean {
100
+ return row.includes('❯') && (row.includes(NAG_OPTION_YES) || /❯\s*1\.\s*Yes/.test(row))
79
101
  }
80
102
 
81
103
  // ─────────────────────────────────────────────────────────────────────────────
@@ -226,10 +248,10 @@ export const claudeAdapter: RuntimeAdapter = {
226
248
  pane.includes('trust this folder') ||
227
249
  pane.includes('Allow external CLAUDE.md file imports?') ||
228
250
  pane.includes('I am using this for local development') ||
229
- // Project MCP-server approval (servers pre-checked [✔]; Enter confirms, Esc
230
- // rejects all). enableAllProjectMcpServers normally suppresses it; this is the
231
- // backstop. Matches both "1 new MCP server" and "N new MCP servers".
232
- pane.includes('new MCP server') ||
251
+ // Project MCP-server approval (servers pre-checked [✔]; Enter confirms, Esc rejects all).
252
+ // enableAllProjectMcpServers normally suppresses it; this is the backstop. В39: full-signature
253
+ // (topic + "found in") so a conversational mention never triggers a stray Enter.
254
+ mcpApprovalActive(pane) ||
233
255
  // First-run theme picker (clean host): the default-highlighted row is always a
234
256
  // valid theme (any choice is harmless for a headless peer), so a bare Enter
235
257
  // accepts it. Without this the picker blocks the boot forever on a fresh host.
@@ -246,35 +268,35 @@ export const claudeAdapter: RuntimeAdapter = {
246
268
  },
247
269
 
248
270
  /**
249
- * MID-SESSION nag/upsell auto-dismiss (livability — distinct from bootDialogKeys,
250
- * which the supervisor drives only until ready). claude pops a ONE-TIME interactive
251
- * upsell modal AFTER the session is live that BLOCKS a headless peer (no human to
252
- * answer):
253
- *
254
- * Try the new fullscreen renderer?
255
- * · Flicker-free output …
256
- * ❯ 1. Yes, try it
257
- * 2. Not now
258
- * Enter to confirm · Esc to cancel
271
+ * MID-SESSION nag/upsell auto-dismiss (livability — distinct from bootDialogKeys, which the supervisor
272
+ * drives only until ready). claude pops a ONE-TIME interactive upsell modal AFTER the session is live —
273
+ * the fullscreen-renderer offer — that BLOCKS a headless peer (no human to answer). Its default cursor
274
+ * is on the ACCEPT option, so a bare Enter would enable the alt-screen renderer and change the surface
275
+ * the pane-log model / composer-occupancy / ready-gate all read off. We DECLINE by selecting the "not
276
+ * now" option ('2' then Enter — '2' is emitted verbatim, not a named key). VERIFIED-SAFE on the live
277
+ * fleet ('2'+Enter cleared it on boris/doc; an arrow-step+Enter mis-fired into fullscreen on scriber; Esc/
278
+ * 'n' unverified) — so this is the ONLY accepted sequence.
259
279
  *
260
- * The default cursor sits on "1. Yes, try it", so a BARE Enter would ENABLE the
261
- * fullscreen renderer — which switches claude to the alt-screen TUI and changes the
262
- * surface the pane-log model + composer-occupancy + ready-gate all read off. We must
263
- * DECLINE: type the literal '2' then Enter ('2','Enter' → "2\r"; '2' is not a named/
264
- * cursor key, so it is emitted verbatim without a `-l` literal switch — and `-l`
265
- * would wrongly make the following 'Enter' literal too). VERIFIED-SAFE on the live
266
- * fleet: '2'+Enter cleared the modal on boris and doc and returned them to the
267
- * composer; an arrow-step+Enter MIS-FIRED into "tui":"fullscreen" on scriber, and Esc/
268
- * 'n' are unverified — so this is the ONLY accepted sequence. Match the FULL signature
269
- * (title AND the "2. Not now" decline row) so a transcript merely DISCUSSING the
270
- * fullscreen renderer can never trigger a stray keystroke. Future one-time CC upsells
271
- * of this class extend the match here (each with its own verified-safe decline key).
280
+ * В40 — the match is POSITION-based, NOT phrase-based: the needles are built from fragments (this file
281
+ * never carries the verbatim modal text, or a peer editing/reviewing it would self-trigger — observed
282
+ * live), and it fires ONLY when the BOTTOM-MOST cursor row is the modal's live option (a mere quote of
283
+ * the modal has the ready composer below it). NB text-matching still cannot fully distinguish a live
284
+ * claude modal from an agent RENDERING the modal glyphs at its viewport bottom — the correct fix is a
285
+ * rendering-level signal (the alt-screen switch), tracked as a HIGH-priority follow-up (В59).
272
286
  */
273
287
  nagDismissKeys(pane: string): string[] | null {
274
- if (pane.includes('Try the new fullscreen renderer?') && pane.includes('2. Not now')) {
275
- return ['2', 'Enter']
276
- }
277
- return null
288
+ // В40 — a text-only match fired '2'+Enter into a LIVE composer whenever the peer merely displayed the
289
+ // modal text (a code review of this file, a forwarded bug report — or, live-observed, the peer editing
290
+ // THIS adapter). Discriminate by POSITION, not phrases: claude's live modal REPLACES the composer, so
291
+ // the BOTTOM-MOST cursor row (`❯`) sits on the modal's option. A mere quote of the modal has the READY
292
+ // composer `❯` rendered BELOW it as the bottom-most cursor row. So: fire only when the last `❯`-bearing
293
+ // row is the modal's selected option — a displayed quote never is.
294
+ if (!isFullscreenNagText(pane)) return null
295
+ let lastCursorRow = ''
296
+ for (const line of pane.split(/\r?\n/)) if (line.includes('❯')) lastCursorRow = line
297
+ // the live modal's bottom-most cursor sits on option 1 ("Yes, try it"); the ready composer's `❯` does
298
+ // not carry the option text, so a quote (composer below) fails this.
299
+ return isFullscreenNagOptionRow(lastCursorRow) ? ['2', 'Enter'] : null
278
300
  },
279
301
 
280
302
  /**
@@ -107,8 +107,11 @@ export function resolveDeliveryTarget(args: {
107
107
  personality: string
108
108
  runtime?: string
109
109
  sockDir?: string
110
+ /** Б7 — injected env sandboxes the liveness reads (supervisor run-dir); default process.env (prod). */
111
+ env?: NodeJS.ProcessEnv
110
112
  }): Result<DeliveryTarget> {
111
- const sockDir = args.sockDir ?? resolveSockDir()
113
+ const env = args.env ?? process.env
114
+ const sockDir = args.sockDir ?? resolveSockDir(env)
112
115
  if (!isValidName(args.personality)) {
113
116
  return err(`invalid personality "${args.personality}" — must match /^[a-z][a-z0-9-]{0,31}$/`)
114
117
  }
@@ -117,12 +120,12 @@ export function resolveDeliveryTarget(args: {
117
120
  const runtime = args.runtime
118
121
  const socketPath = buildSocketPath(runtime, args.personality, sockDir)
119
122
  const address = buildProcessAddress(runtime, args.personality)
120
- if (!sessionAlive(socketPath, address)) {
123
+ if (!sessionAlive(socketPath, address, env)) {
121
124
  return err(`peer offline: ${args.personality} (${args.runtime})`)
122
125
  }
123
126
  return ok({ runtime, personality: args.personality, address, socketPath })
124
127
  }
125
- const matches = listOnlinePeers(sockDir).filter(peer => peer.personality === args.personality)
128
+ const matches = listOnlinePeers(sockDir, env).filter(peer => peer.personality === args.personality)
126
129
  if (matches.length === 0) return err(`peer offline: ${args.personality}`)
127
130
  if (matches.length > 1) {
128
131
  return err(
@@ -145,13 +148,14 @@ export function resolvePeerDeliveryTarget(
145
148
  personality: string,
146
149
  runtime: string | undefined,
147
150
  peer: PeerRecord,
151
+ env: NodeJS.ProcessEnv = process.env,
148
152
  ): Result<DeliveryTarget> {
149
- if (runtime) return resolveDeliveryTarget({ personality, runtime })
153
+ if (runtime) return resolveDeliveryTarget({ personality, runtime, env })
150
154
  if (peer.runtime) {
151
- const exactDefault = resolveDeliveryTarget({ personality, runtime: peer.runtime })
155
+ const exactDefault = resolveDeliveryTarget({ personality, runtime: peer.runtime, env })
152
156
  if (exactDefault.ok) return exactDefault
153
157
  }
154
- return resolveDeliveryTarget({ personality })
158
+ return resolveDeliveryTarget({ personality, env })
155
159
  }
156
160
 
157
161
  // Confirm poll interval — how often deliverViaHost re-reads the transcript for a NEW record carrying
@@ -232,13 +236,14 @@ export async function deliverWarm(
232
236
  envelope: string,
233
237
  cwd?: string,
234
238
  seam: WarmDeliverSeam = {},
239
+ env: NodeJS.ProcessEnv = process.env,
235
240
  ): Promise<Result<void>> {
236
241
  const address = target.address
237
242
  const prev = deliverTails.get(address) ?? Promise.resolve()
238
243
  // run AFTER prev settles (success or failure) — a prior delivery's error must not stall the chain
239
244
  const run = prev.then(
240
- () => deliverViaHost(target, envelope, cwd, seam),
241
- () => deliverViaHost(target, envelope, cwd, seam),
245
+ () => deliverViaHost(target, envelope, cwd, seam, env),
246
+ () => deliverViaHost(target, envelope, cwd, seam, env),
242
247
  )
243
248
  deliverTails.set(
244
249
  address,
@@ -255,6 +260,7 @@ async function deliverViaHost(
255
260
  envelope: string,
256
261
  cwd: string | undefined,
257
262
  seam: WarmDeliverSeam,
263
+ env: NodeJS.ProcessEnv = process.env,
258
264
  ): Promise<Result<void>> {
259
265
  const adapter = getAdapter(target.runtime)
260
266
  // Baseline the transcript/session-jsonl file SIZES BEFORE delivery (per-runtime candidate files).
@@ -264,8 +270,9 @@ async function deliverViaHost(
264
270
  // socket-ack runtimes (codex) return before it — computing it for them recursively scanned all of
265
271
  // ~/.codex/sessions (full-file read per session) on every delivery for nothing.
266
272
  const usesBaseline = adapter.kind !== 'router' && adapter.deliveryConfirm !== 'socket-ack'
267
- const baseline = cwd && usesBaseline ? compactDoneBaseline(target.runtime, cwd) : null
268
- const send = seam.deliverHosted ?? deliverHosted
273
+ const baseline = cwd && usesBaseline ? compactDoneBaseline(target.runtime, cwd, { env }) : null
274
+ // Б7 — the default deliverHosted resolves the supervisor run-dir from env (sandboxed under a test root).
275
+ const send = seam.deliverHosted ?? ((identity: string, msg: string) => deliverHosted(identity, msg, env))
269
276
  const sent = await send(target.address, envelope)
270
277
  if (!sent.ok) {
271
278
  return err(
@@ -892,6 +899,11 @@ export interface ComposerQueueRouteDeps {
892
899
  }
893
900
 
894
901
  export interface RouteDeps {
902
+ /** Б7 — injected env sandboxes ALL of routeSend's env-resolved reads (the registry, the supervisor
903
+ * run-dir liveness/delivery). Default process.env (prod: env === process.env). Closes the daemon:286
904
+ * isolation invariant — a library/test daemon with an injected root no longer reads the real registry
905
+ * or the real fleet's live sessions. */
906
+ env?: NodeJS.ProcessEnv
895
907
  /** On a miss, wake the dead peer instead of returning offline (Ф2). */
896
908
  wake?: WakeFn
897
909
  /** Ephemeral-target serial-queue delivery (M3); absent → normal routing. */
@@ -1275,7 +1287,8 @@ export async function routeSend(
1275
1287
  return err(`message exceeds ${MAX_MESSAGE_LEN} char limit (got ${message.length})`)
1276
1288
  }
1277
1289
 
1278
- const index = readPeersIndex()
1290
+ const env = deps.env ?? process.env
1291
+ const index = readPeersIndex({ env })
1279
1292
  const peer = findPeer(index, personality)
1280
1293
  if (!peer) {
1281
1294
  return err(`peer "${personality}" is not in the iapeer peers index; message NOT delivered`)
@@ -1309,7 +1322,7 @@ export async function routeSend(
1309
1322
  return deps.ephemeral.deliver({ peer, envelope, topic, runtime })
1310
1323
  }
1311
1324
 
1312
- const target = resolvePeerDeliveryTarget(personality, runtime, peer)
1325
+ const target = resolvePeerDeliveryTarget(personality, runtime, peer, env)
1313
1326
  if (target.ok) {
1314
1327
  if (target.value.address === caller.address) return err('cannot send to self')
1315
1328
  // Telegram sender policy — RESOLVED channel (the only-live-session fallback can
@@ -1321,7 +1334,7 @@ export async function routeSend(
1321
1334
  // peer.cwd enables the Ф-B transcript-mtime liveness probe (busy-session case).
1322
1335
  // deliverWarm is HOST-AWARE (spawn-flip Ф0b-2): a supervisor-hosted target delivers over its
1323
1336
  // socket, any other target keeps the tmux path. Flag-off → byte-identical to deliverViaTmux.
1324
- const delivered = await deliverWarm(target.value, envelope, peer.cwd)
1337
+ const delivered = await deliverWarm(target.value, envelope, peer.cwd, {}, env)
1325
1338
  if (!delivered.ok) return delivered
1326
1339
  noteTopic(deps, target.value.address, topic)
1327
1340
  noteDelivered(deps, target.value.address) // В7 — floor the idle proxy so this delivery isn't reaped away
@@ -1349,12 +1362,12 @@ export async function routeSend(
1349
1362
  const reviveDeadline = monotonicMs() + launchdReviveGraceMs()
1350
1363
  while (monotonicMs() < reviveDeadline) {
1351
1364
  await sleep(LAUNCHD_REVIVE_POLL_MS)
1352
- const revived = resolvePeerDeliveryTarget(personality, runtime, peer)
1365
+ const revived = resolvePeerDeliveryTarget(personality, runtime, peer, env)
1353
1366
  if (!revived.ok) continue // not back yet — keep polling until the deadline
1354
1367
  if (revived.value.address === caller.address) return err('cannot send to self')
1355
1368
  const reviveGuard = telegramSenderGuard(caller, revived.value.runtime, personality)
1356
1369
  if (!reviveGuard.ok) return reviveGuard
1357
- const delivered = await deliverWarm(revived.value, envelope, peer.cwd)
1370
+ const delivered = await deliverWarm(revived.value, envelope, peer.cwd, {}, env)
1358
1371
  if (delivered.ok) {
1359
1372
  noteTopic(deps, revived.value.address, topic)
1360
1373
  return ok({
@@ -1399,7 +1412,7 @@ export async function routeSend(
1399
1412
  if (woke.taskDelivered === false) {
1400
1413
  const queued = await deps.composerQueue?.tryEnqueue({ caller, peer, target: live.value, envelope, topic })
1401
1414
  if (queued) return queued
1402
- const delivered = await deliverWarm(live.value, envelope, peer.cwd)
1415
+ const delivered = await deliverWarm(live.value, envelope, peer.cwd, {}, env)
1403
1416
  if (!delivered.ok) return delivered
1404
1417
  noteTopic(deps, live.value.address, topic)
1405
1418
  return ok({