@agfpd/iapeer 0.4.106 → 0.4.107

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.
@@ -56,7 +56,20 @@ iapeer add-runtime codex --peer assistant # for one peer
56
56
  iapeer add-runtime codex --all # for all peers
57
57
  ```
58
58
 
59
- Adds an agent runtime to existing peers: appends it to `runtimes`, scaffolds the runtime space, and does the full Codex setup (pre-trusting the folder, the native-memory lever, attaching memory, MCP). The command **doesn't touch** `default_runtime` — this is extending options, not changing routing. Idempotent. Infrastructure peers are skipped: giving them an agent runtime is an operator decision via `create`, not a bulk operation.
59
+ Adds a runtime to existing peers: appends it to `runtimes`, scaffolds the runtime space, and does the full Codex setup (pre-trusting the folder, the native-memory lever, attaching memory, MCP). The command **doesn't touch** `default_runtime` — this is extending options, not changing routing. Idempotent. A peer whose default is infrastructure is skipped when the runtime being added is an *agent* one: giving a router peer an agent runtime is an operator decision via `create`, not a bulk operation.
60
+
61
+ An **infrastructure** runtime can also be added this way, but only to one named peer:
62
+
63
+ ```bash
64
+ iapeer add-runtime voicetalk --peer arthur # attach a second always-on channel
65
+ iapeer connect voicetalk arthur # the same thing, said the way `connect` taught you
66
+ ```
67
+
68
+ This is the operator path for the multi-channel scheme above — giving an *existing* personality another always-on presence. It resolves the peer's folder from the registry, installs the per-runtime plist, runs the runtime package's own `selfConfig` hook (which owns `interfaces.<runtime>`), and loads the job. `--all` is refused for an infrastructure runtime: every channel is a launchd job, and fanning them across the fleet is never what an operator means.
69
+
70
+ `create` cannot do this. It resolves a peer by **location** (`~/.iapeer/peers/<name>` unless `--path` is given), so for a peer whose folder lives elsewhere it never reaches the existing record — it would scaffold a second, bogus folder instead.
71
+
72
+ Declaration and reality can diverge: `runtimes` only *declares* the channel, the plist *realizes* it. If the record declares the runtime but the plist is gone, the command re-provisions it rather than reporting "already" for a channel that does not exist.
60
73
 
61
74
  ### default-runtime — switch the primary
62
75
 
@@ -69,7 +82,7 @@ Switches the primary runtime — where routing goes and which runtime comes up f
69
82
 
70
83
  The routing choice is strict: a send without an explicit `runtime` always targets `default_runtime`. A live session on another declared runtime does not capture that send; if the default session is asleep, the daemon wakes it. Passing `runtime` explicitly remains the way to target a non-default surface.
71
84
 
72
- ## Connecting Telegram: connect
85
+ ## Connecting a channel: connect
73
86
 
74
87
  ```bash
75
88
  iapeer connect telegram assistant --token <bot-token>
@@ -79,6 +92,8 @@ Connects a Telegram bot to a peer in one pass: registers the bot, writes it into
79
92
 
80
93
  The command is idempotent, and behavior depends on the token. **The same token** is a clean no-op: the bot's credentials file doesn't change, the live router already runs on these credentials, no restart. **A new or changed token** requires a router restart (credentials are read only at start) — a second's pause in delivery for all Telegram peers; inbound messages aren't lost (long-polling remembers the offset, Telegram holds messages for up to 24 hours). An invalid token is rejected at once, with the verbatim reason from Telegram.
81
94
 
95
+ `connect` is not Telegram-only. `iapeer connect <runtime> <peer>` attaches any presence channel: Telegram keeps its bespoke flow (it owes a bot token, a `@BotFather` round-trip and a credential store), while every other infrastructure runtime takes the generic bind — the same per-peer path as `add-runtime <runtime> --peer <peer>`. The runtime package must be installed on the host first (`install-runtime`), which the command checks before touching anything.
96
+
82
97
  ## Runtime packages
83
98
 
84
99
  Infrastructure runtimes ship as separate npm packages (`*-runtime`). The core installs and updates them:
@@ -49,7 +49,7 @@ The full list of `iapeer <command>`. General rules: `--help` / `-h` anywhere in
49
49
  | `attach <peer> [runtime]` | Bring up (if asleep), resume the conversation, open the session under the supervisor in the terminal (detach — `Ctrl-]`). |
50
50
  | `interrupt <peer> [runtime]` | Interrupt the current turn (Escape), context intact. |
51
51
  | `compact <peer> [runtime]` | Compact the conversation; a sleeper is resumed first after idle sleep. |
52
- | `add-runtime <runtime> (--peer <p> \| --all)` | Add an agent runtime to existing peers. Doesn't touch `default_runtime`. |
52
+ | `add-runtime <runtime> (--peer <p> \| --all)` | Add a runtime to existing peers. Doesn't touch `default_runtime`. An infrastructure runtime attaches an always-on channel and is `--peer`-only (never an `--all` sweep). |
53
53
  | `default-runtime <runtime> (--peer <p> \| --all)` | Switch the primary runtime (routing / first bring-up). Refuses if the runtime isn't declared. |
54
54
 
55
55
  `stop`/`start`/`new` refuse to touch peers under a foreign launchd plist — the core doesn't intervene in what it doesn't manage.
@@ -69,6 +69,7 @@ The full list of `iapeer <command>`. General rules: `--help` / `-h` anywhere in
69
69
  |---|---|
70
70
  | `<runtime>` (e.g. `iapeer claude`) | Launch the current folder's peer on this runtime — always as a fresh session. |
71
71
  | `connect telegram <peer> [--token <t>]` | Connect a Telegram bot to a peer: register the bot → write into the profile → restart the router. Asks only for the token. |
72
+ | `connect <runtime> <peer>` | Attach any other presence channel (web, voicetalk, …) to an existing peer: per-runtime plist → the package's `selfConfig` hook → load. Same path as `add-runtime <runtime> --peer <peer>`. |
72
73
 
73
74
  ## Extensions and memory
74
75
 
@@ -56,7 +56,20 @@ iapeer add-runtime codex --peer assistant # одному пиру
56
56
  iapeer add-runtime codex --all # всем пирам
57
57
  ```
58
58
 
59
- Добавляет агентский рантайм существующим пирам: дописывает его в `runtimes`, разворачивает пространство рантайма и проводит полную настройку для Codex (предварительное доверие к папке, рычаг родной памяти, подключение памяти, MCP). `default_runtime` команда **не трогает** — это расширение возможностей, не смена маршрутизации. Идемпотентна. Инфраструктурные пиры пропускаются: добавить им агентский рантайм — решение оператора через `create`, а не массовая операция.
59
+ Добавляет рантайм существующим пирам: дописывает его в `runtimes`, разворачивает пространство рантайма и проводит полную настройку для Codex (предварительное доверие к папке, рычаг родной памяти, подключение памяти, MCP). `default_runtime` команда **не трогает** — это расширение возможностей, не смена маршрутизации. Идемпотентна. Пир с инфраструктурным дефолтом пропускается, когда добавляется *агентский* рантайм: дать роутер-пиру агентский рантайм — решение оператора через `create`, а не массовая операция.
60
+
61
+ **Инфраструктурный** рантайм тоже добавляется этой командой, но только одному названному пиру:
62
+
63
+ ```bash
64
+ iapeer add-runtime voicetalk --peer arthur # прицепить второй always-on канал
65
+ iapeer connect voicetalk arthur # то же самое в привычной по connect форме
66
+ ```
67
+
68
+ Это операторский путь для описанной выше мультиканальной схемы — дать *существующей* личности ещё одно постоянное присутствие. Команда резолвит папку пира из реестра, ставит пер-рантаймовый плист, вызывает собственный хук `selfConfig` рантайм-пакета (он владеет `interfaces.<рантайм>`) и загружает job. `--all` для инфраструктурного рантайма отвергается: каждый канал — это launchd-job, и разворачивать их по всему флоту оператор не имеет в виду никогда.
69
+
70
+ `create` так не умеет. Он резолвит пира по **расположению** (`~/.iapeer/peers/<имя>`, если не передан `--path`), поэтому до записи пира, чья папка лежит в другом месте, не дотягивается вовсе — вместо этого создал бы вторую, ложную папку.
71
+
72
+ Объявление и реальность расходятся: `runtimes` только *объявляет* канал, а *реализует* его плист. Если запись рантайм объявляет, а плиста нет — команда переставляет канал, а не рапортует «already» о канале, которого не существует.
60
73
 
61
74
  ### default-runtime — переключить основной
62
75
 
@@ -69,7 +82,7 @@ iapeer default-runtime codex --all # все пиры
69
82
 
70
83
  Выбор для маршрутизации строгий: отправка без явного `runtime` всегда целится в `default_runtime`. Живая сессия на другом объявленном рантайме не перехватывает такую отправку; если дефолтная сессия спит, демон будит её. Явный `runtime` по-прежнему выбирает конкретную недефолтную поверхность.
71
84
 
72
- ## Подключение Telegram: connect
85
+ ## Подключение канала: connect
73
86
 
74
87
  ```bash
75
88
  iapeer connect telegram assistant --token <токен-бота>
@@ -79,6 +92,8 @@ iapeer connect telegram assistant --token <токен-бота>
79
92
 
80
93
  Команда идемпотентна, и поведение зависит от токена. **Тот же токен** — чистый no-op: файл учётных данных бота не меняется, живой роутер уже работает на этих данных, перезапуска нет. **Новый или изменённый токен** требует перезапуска роутера (учётные данные читаются только при старте) — это секундная пауза в доставке для всех Telegram-пиров; входящие при этом не теряются (long-polling помнит смещение, Telegram держит сообщения до 24 часов). Неверный токен отсекается сразу, с дословной причиной от Telegram.
81
94
 
95
+ `connect` не только про Telegram. `iapeer connect <рантайм> <пир>` цепляет любой presence-канал: у Telegram остаётся его особый поток (нужны токен, поход к `@BotFather` и хранилище учётных данных), а любой другой инфраструктурный рантайм идёт по генеричной привязке — тот же пер-пировый путь, что и `add-runtime <рантайм> --peer <пир>`. Рантайм-пакет должен быть предварительно установлен на хосте (`install-runtime`); команда проверяет это до того, как что-либо тронуть.
96
+
82
97
  ## Рантайм-пакеты
83
98
 
84
99
  Инфраструктурные рантаймы поставляются отдельными npm-пакетами (`*-runtime`). Ставит и обновляет их ядро:
@@ -49,7 +49,7 @@
49
49
  | `attach <пир> [рантайм]` | Поднять (если спит), продолжить диалог, открыть сессию под супервизором в терминале (отсоединиться — `Ctrl-]`). |
50
50
  | `interrupt <пир> [рантайм]` | Прервать текущий ход (Escape), контекст цел. |
51
51
  | `compact <пир> [рантайм]` | Сжать диалог; спящего после усыпления сначала продолжить. |
52
- | `add-runtime <рантайм> (--peer <p> \| --all)` | Добавить агентский рантайм существующим пирам. `default_runtime` не трогает. |
52
+ | `add-runtime <рантайм> (--peer <p> \| --all)` | Добавить рантайм существующим пирам. `default_runtime` не трогает. Инфраструктурный рантайм цепляет always-on канал и работает только с `--peer` (никогда не сметает `--all`). |
53
53
  | `default-runtime <рантайм> (--peer <p> \| --all)` | Переключить основной рантайм (маршрутизация/первый подъём). Откажет, если рантайм не объявлен. |
54
54
 
55
55
  `stop`/`start`/`new` отказываются трогать пиров под чужим launchd-плистом — ядро не вмешивается в то, чем управляет не оно.
@@ -69,6 +69,7 @@
69
69
  |---|---|
70
70
  | `<рантайм>` (например `iapeer claude`) | Запустить пир текущей папки в этом рантайме — всегда свежей сессией. |
71
71
  | `connect telegram <пир> [--token <t>]` | Подключить Telegram-бота к пиру: регистрация бота → запись в профиль → перезапуск роутера. Спрашивает только токен. |
72
+ | `connect <рантайм> <пир>` | Прицепить любой другой presence-канал (web, voicetalk, …) существующему пиру: пер-рантаймовый плист → хук `selfConfig` пакета → загрузка. Тот же путь, что `add-runtime <рантайм> --peer <пир>`. |
72
73
 
73
74
  ## Расширения и память
74
75
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agfpd/iapeer",
3
- "version": "0.4.106",
3
+ "version": "0.4.107",
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",
package/src/cli/index.ts CHANGED
@@ -15,6 +15,7 @@ import { existsSync, readFileSync, renameSync, rmSync } from 'fs'
15
15
  import { fileURLToPath } from 'url'
16
16
  import { dirname, join } from 'path'
17
17
  import {
18
+ INFRA_RUNTIME_LIST,
18
19
  isInfraRuntime,
19
20
  isRuntime,
20
21
  type Intelligence,
@@ -53,6 +54,7 @@ import { getAdapter } from '../launch/index.ts'
53
54
  import { hostRunDir } from '../launch/ptyHost.ts' // pty-only: attach via the supervisor client
54
55
  import { runSupervisorClient } from '../supervisor/client.ts' // @xterm-free attach client (both reattach port-deps baked in)
55
56
  import {
57
+ bootstrapFailed,
56
58
  cycleDaemon,
57
59
  existingAlwaysOnPlists,
58
60
  launchctlBootstrap,
@@ -195,7 +197,7 @@ export function formatListTable(rows: PeerListing[]): string {
195
197
  export interface StopStartOutcome {
196
198
  personality: string
197
199
  runtime: Runtime
198
- action: 'stopped' | 'started' | 'bootout' | 'bootstrap' | 'refused-foreign-launchd'
200
+ action: 'stopped' | 'started' | 'bootout' | 'bootstrap' | 'refused-foreign-launchd' | 'no-plist'
199
201
  reason?: string
200
202
  }
201
203
 
@@ -320,6 +322,18 @@ export function startPeer(personality: string, runtime: string | undefined, opts
320
322
  // every attempt is LOUD with the manual rescue recipe. (Also gains the
321
323
  // sentinel fleet-guard + sandbox guard the raw spawn never had.)
322
324
  const r = launchctlBootstrap(personality, plist, env)
325
+ // NO PLIST ≠ FOREIGN PLIST. The peer declares this infra runtime but no always-on
326
+ // plist was ever provisioned for the (personality, runtime) channel — there is
327
+ // nothing to bootstrap, and the honest answer is the verb that PROVISIONS it, not
328
+ // a fleet-guard refusal (which is what the missing file used to be misread as).
329
+ if (r.state === 'missing-plist') {
330
+ const reason =
331
+ `no always-on plist for the "${rt}" channel (${plist}) — nothing to start. ` +
332
+ `Provision the channel first: \`iapeer add-runtime ${rt} --peer ${personality}\``
333
+ out.push({ personality, runtime: rt, action: 'no-plist', reason })
334
+ appendLifecycleEvent(cfg.eventLogDir, { ev: 'started', identity, personality, runtime: rt, action: 'no-plist', reason }, { env })
335
+ continue
336
+ }
323
337
  const ok = r.state === 'loaded' || r.state === 'already-loaded' || r.state === 'skipped-sandbox'
324
338
  const reason = ok
325
339
  ? undefined
@@ -380,16 +394,25 @@ export interface AddRuntimeOutcome {
380
394
 
381
395
  /**
382
396
  * add-runtime <runtime> (--peer <p> | --all) — give EXISTING peers an additional
383
- * AGENTIC runtime in one command (the fleet-switch enabler — a claude-only peer
384
- * has nothing to switch to).
397
+ * runtime in one command. Two shapes:
398
+ * • AGENTIC runtime (claude/codex) — the fleet-switch enabler (a claude-only peer
399
+ * has nothing to switch to); works per-peer or as an `--all` sweep.
400
+ * • INFRA/presence runtime (telegram/web/voicetalk/notifier) — attach ANOTHER
401
+ * always-on CHANNEL to an existing personality (`--peer` only, never a sweep).
402
+ * This is the operator path the multi-plist scheme (docs/09 §Plist scheme)
403
+ * always implied but nothing implemented: `create` resolves a peer by LOCATION
404
+ * (default `~/.iapeer/peers/<p>`), so for a peer whose cwd lives elsewhere it
405
+ * cannot reach the existing record at all — it would scaffold a second, bogus
406
+ * folder. add-runtime resolves the cwd from the REGISTRY, which is exactly the
407
+ * resolution this needs.
385
408
  * Per target: initPeer({cwd, runtime}) — ensurePeerProfile MERGES runtimes (the
386
409
  * default_runtime lever is deliberately untouched — capability ≠ routing flip; see
387
- * `default-runtime`), scaffolds the runtime scope, and the codex side runs its
388
- * whole birth chain: cwd pre-trust, native-memory lever, memory provision
389
- * (occasion=birth), host-wide MCP block + update-check-off. Idempotent by
390
- * construction (merge + append-if-absent everywhere). Infra PEERS (telegram/
391
- * notifier defaults) are skipped — adding an agentic runtime to a router peer is
392
- * an operator decision, not a sweep.
410
+ * `default-runtime`), scaffolds the runtime scope, and for infra installs the
411
+ * per-runtime always-on plist, runs the runtime package's own selfConfig hook (which
412
+ * owns `interfaces.<runtime>`), then bootstraps it. The codex side runs its whole
413
+ * birth chain: cwd pre-trust, native-memory lever, memory provision (occasion=birth),
414
+ * host-wide MCP block + update-check-off. Idempotent by construction (merge +
415
+ * append-if-absent everywhere).
393
416
  */
394
417
  export async function addRuntime(
395
418
  runtime: string,
@@ -397,8 +420,16 @@ export async function addRuntime(
397
420
  ): Promise<AddRuntimeOutcome[]> {
398
421
  const env = opts.env ?? process.env
399
422
  if (!isRuntime(runtime)) throw new Error(`invalid runtime "${runtime}"`)
400
- if (isInfraRuntime(runtime)) {
401
- throw new Error(`"${runtime}" is an infra runtime — infra presence is operator-add via \`iapeer create\` (plist semantics), not a sweep`)
423
+ // The real invariant behind the old blanket infra refusal is "an always-on channel is
424
+ // never provisioned by a SWEEP" — each plist is a launchd job, and fanning them across
425
+ // the whole fleet is never what an operator means. That is a guard on `--all`, NOT on
426
+ // the runtime class: attaching one channel to ONE named peer is precisely the operator
427
+ // path the multi-plist scheme exists for, and it had no verb at all.
428
+ if (isInfraRuntime(runtime) && opts.all === true) {
429
+ throw new Error(
430
+ `"${runtime}" is an infra runtime — an always-on channel is provisioned per peer, never as an --all sweep; ` +
431
+ `target one peer: \`iapeer add-runtime ${runtime} --peer <peer>\``,
432
+ )
402
433
  }
403
434
  const index = readPeersIndex({ env })
404
435
  const targets = opts.all === true ? index.peers : index.peers.filter(p => p.personality === opts.peer)
@@ -414,18 +445,36 @@ export async function addRuntime(
414
445
  const { initPeer } = await import('../init/index.ts')
415
446
  const out: AddRuntimeOutcome[] = []
416
447
  for (const p of targets) {
417
- if (isInfraRuntime(p.runtime)) {
448
+ // Skip an infra-DEFAULT peer only when the runtime being added is AGENTIC: giving a
449
+ // router peer (a human on telegram) an agent runtime is meaningless. Adding another
450
+ // CHANNEL to that same human is the whole point of this path, so it must not be
451
+ // caught by the same guard — the old check keyed on the peer alone and swallowed it.
452
+ if (isInfraRuntime(p.runtime) && !isInfraRuntime(runtime)) {
418
453
  out.push({ personality: p.personality, action: 'skipped-infra-peer', detail: `default runtime "${p.runtime}" is infra` })
419
454
  continue
420
455
  }
421
- if (p.runtimes.includes(runtime as Runtime)) {
456
+ // DECLARED ≠ REALIZED. For an infra channel the record's `runtimes` is only the
457
+ // DECLARATION; the always-on plist is what actually realizes it, and the two can
458
+ // diverge (a hand-built bind, a torn-down plist, a record restored from backup).
459
+ // Short-circuiting on the declaration alone would report "already" while the channel
460
+ // does not exist — so for infra, converge: a missing plist means there IS work to do.
461
+ // initPeer is idempotent, so the repair costs nothing when everything is in place.
462
+ const realized = isInfraRuntime(runtime)
463
+ ? existsSync(resolveAlwaysOnTarget(p.personality, runtime as Runtime, env).path)
464
+ : true
465
+ if (p.runtimes.includes(runtime as Runtime) && realized) {
422
466
  out.push({ personality: p.personality, action: 'already' })
423
467
  continue
424
468
  }
425
469
  try {
426
470
  const warns: string[] = []
471
+ const repair = p.runtimes.includes(runtime as Runtime)
427
472
  await initPeer({ cwd: p.cwd, runtime: runtime as Runtime, env: cleanEnv, warn: m => warns.push(m) })
428
- out.push({ personality: p.personality, action: 'added', detail: warns.length ? warns.join(' | ') : undefined })
473
+ out.push({
474
+ personality: p.personality,
475
+ action: 'added',
476
+ detail: [repair ? 'declared but no plist — channel re-provisioned' : undefined, ...warns].filter(Boolean).join(' | ') || undefined,
477
+ })
429
478
  } catch (e) {
430
479
  out.push({ personality: p.personality, action: 'failed', detail: e instanceof Error ? e.message : String(e) })
431
480
  }
@@ -1037,6 +1086,52 @@ async function connectTelegramVerb(
1037
1086
  return rs.state === 'restarted' ? 0 : 1
1038
1087
  }
1039
1088
 
1089
+ /**
1090
+ * `connect <runtime> <peer>` for a NON-telegram presence runtime — attach one always-on
1091
+ * channel to an EXISTING personality. Thin surface over addRuntime's per-peer infra path
1092
+ * (registry-resolved cwd → initPeer → per-runtime plist + the package's selfConfig hook
1093
+ * that owns `interfaces.<runtime>` → bootstrap); this exists so the operator reaches it
1094
+ * by the same verb telegram taught them. Returns the process exit code.
1095
+ */
1096
+ async function connectChannelVerb(
1097
+ runtime: string,
1098
+ peer: string,
1099
+ env: NodeJS.ProcessEnv,
1100
+ out: (s: string) => void,
1101
+ errOut: (s: string) => void,
1102
+ ): Promise<number> {
1103
+ // A channel whose runtime package was never installed would provision a plist whose
1104
+ // launcher does not resolve — provisionPeer refuses, but late and obscurely. Say it here.
1105
+ const { isRuntimeInstalled } = await import('../init/index.ts')
1106
+ if (!isRuntimeInstalled(runtime as Runtime, env)) {
1107
+ errOut(`connect ${runtime} ${peer}: runtime "${runtime}" is not installed on this host — \`iapeer install-runtime ${runtime}\` first\n`)
1108
+ return 1
1109
+ }
1110
+ let outcomes: AddRuntimeOutcome[]
1111
+ try {
1112
+ outcomes = await addRuntime(runtime, { peer, env })
1113
+ } catch (e) {
1114
+ errOut(`connect ${runtime} ${peer}: ${e instanceof Error ? e.message : String(e)}\n`)
1115
+ return 1
1116
+ }
1117
+ const o = outcomes.find(x => x.personality === peer) ?? outcomes[0]
1118
+ if (!o || o.action === 'failed') {
1119
+ errOut(`connect ${runtime} ${peer}: ${o?.detail ?? 'failed'}\n`)
1120
+ return 1
1121
+ }
1122
+ if (o.action === 'skipped-infra-peer') {
1123
+ errOut(`connect ${runtime} ${peer}: ${o.detail ?? 'skipped'}\n`)
1124
+ return 1
1125
+ }
1126
+ const plist = resolveAlwaysOnTarget(peer, runtime as Runtime, env)
1127
+ out(
1128
+ o.action === 'already'
1129
+ ? `"${peer}" already carries the "${runtime}" channel (${plist.label}) — nothing to do\n`
1130
+ : `connected "${runtime}" to "${peer}": plist ${plist.path} (${plist.label}) installed + loaded${o.detail ? `; ${o.detail}` : ''}\n`,
1131
+ )
1132
+ return 0
1133
+ }
1134
+
1040
1135
  // ─────────────────────────────────────────────────────────────────────────────
1041
1136
  // rename — first-class peer-identity rename (parity with remove/create). Wraps
1042
1137
  // renamePeer (registry + per-cwd profile, atomic, inside the lock) and KEEPS the
@@ -1381,6 +1476,7 @@ const VERBS: ReadonlyArray<{ sig: string; desc: string }> = [
1381
1476
  },
1382
1477
  { sig: '<runtime>', desc: "launch the cwd's peer FRESH; on a TTY drop into it (like attach), else detached" },
1383
1478
  { sig: 'connect telegram <peer> [--token <t>]', desc: 'attach a telegram bot to a peer (bot add → interface → router restart; asks only the token). Alias: `iapeer enable telegram <peer>`' },
1479
+ { sig: 'connect <runtime> <peer>', desc: 'attach another always-on presence channel (web, voicetalk, …) to an EXISTING peer: per-runtime plist → the package self-config hook → load. Same as `add-runtime <runtime> --peer <peer>`' },
1384
1480
  { sig: 'enable <plugin> [peer] [--no-setup]', desc: 'install + enable an agfpd capability for a peer' },
1385
1481
  {
1386
1482
  sig: 'new <peer> [runtime]',
@@ -1883,7 +1979,7 @@ export async function runCli(argv: string[], env: NodeJS.ProcessEnv = process.en
1883
1979
  // В47 — a failed runtime self-config means initPeer deliberately did NOT bootstrap:
1884
1980
  // the always-on peer is not running. Exit 0 here read as success to automation.
1885
1981
  if (r.selfConfig?.state === 'failed') return 1
1886
- return r.bootstrapped && (r.bootstrapped.state === 'failed' || r.bootstrapped.state === 'refused-foreign') ? 1 : 0
1982
+ return r.bootstrapped && bootstrapFailed(r.bootstrapped.state) ? 1 : 0
1887
1983
  }
1888
1984
  case 'create': {
1889
1985
  // cwd-INDEPENDENT: resolve a location (default ~/.iapeer/peers/<p> or --path),
@@ -1957,7 +2053,7 @@ export async function runCli(argv: string[], env: NodeJS.ProcessEnv = process.en
1957
2053
  // always-on peer is NOT running; `create x --runtime telegram` with a broken hook
1958
2054
  // exited 0 and automation read a dead telegram router as provisioned.
1959
2055
  if (r.selfConfig?.state === 'failed') return 1
1960
- return r.bootstrapped && (r.bootstrapped.state === 'failed' || r.bootstrapped.state === 'refused-foreign') ? 1 : 0
2056
+ return r.bootstrapped && bootstrapFailed(r.bootstrapped.state) ? 1 : 0
1961
2057
  }
1962
2058
  case 'list': {
1963
2059
  // tty + no --json → the live Ink dashboard (Фаза 3: host header · live peer
@@ -2075,7 +2171,7 @@ export async function runCli(argv: string[], env: NodeJS.ProcessEnv = process.en
2075
2171
  // Fleet-switch enabler (codex-parity audit): add an agentic runtime to
2076
2172
  // existing peer(s) — full codex birth chain per target, idempotent.
2077
2173
  const rt = positionals[0]
2078
- if (!rt) return argErr(errOut, 'add-runtime needs a runtime — usage: iapeer add-runtime <runtime> (--peer <p> | --all)')
2174
+ if (!rt) return argErr(errOut, 'add-runtime needs a runtime — usage: iapeer add-runtime <runtime> (--peer <p> | --all); an infra/presence runtime is --peer only')
2079
2175
  const peerName = typeof flags.peer === 'string' ? flags.peer : undefined
2080
2176
  if (flags.all !== true && !peerName) return argErr(errOut, 'add-runtime needs a target — pass --peer <p> or --all')
2081
2177
  const outcomes = await addRuntime(rt, { peer: peerName, all: flags.all === true, env })
@@ -2123,7 +2219,11 @@ export async function runCli(argv: string[], env: NodeJS.ProcessEnv = process.en
2123
2219
  for (const o of outcomes) out(`${o.personality} (${o.runtime}): ${o.action}${o.reason ? ` — ${o.reason}` : ''}\n`)
2124
2220
  // В48 — a failed launchctl bootstrap (reason set) means the always-on peer is NOT
2125
2221
  // started; exit 0 here let automation read a dead telegram/notifier as running.
2126
- return outcomes.some(o => o.action === 'refused-foreign-launchd' || (o.action === 'bootstrap' && o.reason !== undefined)) ? 1 : 0
2222
+ return outcomes.some(
2223
+ o => o.action === 'refused-foreign-launchd' || o.action === 'no-plist' || (o.action === 'bootstrap' && o.reason !== undefined),
2224
+ )
2225
+ ? 1
2226
+ : 0
2127
2227
  }
2128
2228
  case 'refresh': {
2129
2229
  // LAZY soft-reload (fleet doctrine refresh): arm `.fresh-next` so each agentic peer comes up FRESH
@@ -2651,8 +2751,24 @@ export async function runCli(argv: string[], env: NodeJS.ProcessEnv = process.en
2651
2751
  // `connect telegram <peer> [--token <t>]`. The human owes only the token;
2652
2752
  // alias/bot-add/interface/router-restart are resolved by the system. The
2653
2753
  // FIRST message from the human to the bot activates the chat (platform rule).
2654
- if (positionals[0] !== 'telegram' || !positionals[1]) return argErr(errOut, 'connect needs "telegram <peer>" — usage: iapeer connect telegram <peer> [--token <t>] (e.g. iapeer connect telegram boris)')
2655
- return await connectTelegramVerb(positionals[1], typeof flags.token === 'string' ? flags.token : undefined, env, out, errOut)
2754
+ // GENERALIZED (was telegram-only): `connect <runtime> <peer>` attaches ANY
2755
+ // presence channel. telegram keeps its bespoke flow (it owes a bot token, a
2756
+ // @BotFather round-trip and a credential store); every other infra runtime is
2757
+ // the generic bind — add-runtime's per-peer infra path. Same verb, same shape,
2758
+ // so "give this person a voicetalk channel" is discoverable where the operator
2759
+ // already looks.
2760
+ const channel = positionals[0]
2761
+ const channelPeer = positionals[1]
2762
+ if (!channel || !channelPeer) {
2763
+ return argErr(errOut, 'connect needs "<runtime> <peer>" — usage: iapeer connect telegram <peer> [--token <t>] | iapeer connect <runtime> <peer> (e.g. iapeer connect voicetalk arthur)')
2764
+ }
2765
+ if (channel === 'telegram') {
2766
+ return await connectTelegramVerb(channelPeer, typeof flags.token === 'string' ? flags.token : undefined, env, out, errOut)
2767
+ }
2768
+ if (!isRuntime(channel) || !isInfraRuntime(channel)) {
2769
+ return argErr(errOut, `connect: "${channel}" is not a presence runtime — connect attaches an always-on CHANNEL (${INFRA_RUNTIME_LIST.join(', ')}); for an agent runtime use \`iapeer add-runtime ${channel} --peer ${channelPeer}\``)
2770
+ }
2771
+ return await connectChannelVerb(channel, channelPeer, env, out, errOut)
2656
2772
  }
2657
2773
  case 'enable': {
2658
2774
  // DISCOVERABILITY ALIAS: `enable telegram <peer>` → `connect telegram <peer>`
package/src/init/index.ts CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  } from '../storage/index.ts'
31
31
  import { provisionPeer, type ProvisionResult } from '../provision/index.ts'
32
32
  import { claudeSettingsPath } from '../launch/nativeMemory.ts'
33
- import { launchctlBootstrap, resolveAlwaysOnTarget, type BootstrapResult } from '../launch/launchd.ts'
33
+ import { bootstrapFailed, launchctlBootstrap, resolveAlwaysOnTarget, type BootstrapResult } from '../launch/launchd.ts'
34
34
  import { runtimeSelfConfig, type SelfConfigResult } from '../runtime/index.ts'
35
35
  import type { Intelligence } from '../core/constants.ts'
36
36
 
@@ -576,7 +576,7 @@ export async function initPeer(opts: InitPeerOptions): Promise<InitPeerResult> {
576
576
  resolveAlwaysOnTarget(provisioned.personality, provisioned.runtime, env).path,
577
577
  env,
578
578
  )
579
- if (bootstrapped.state === 'failed' || bootstrapped.state === 'refused-foreign') {
579
+ if (bootstrapFailed(bootstrapped.state)) {
580
580
  opts.warn?.(`bootstrap ${bootstrapped.state}: ${bootstrapped.detail ?? ''}`)
581
581
  }
582
582
  }
@@ -320,7 +320,8 @@ export type BootstrapState =
320
320
  | 'loaded' // bootstrapped now (was not loaded)
321
321
  | 'already-loaded' // service already in the gui domain → no-op (idempotent)
322
322
  | 'skipped-sandbox' // IAPEER_TEST_SANDBOX=1 → never touch the real launchd
323
- | 'refused-foreign' // the plist is not foundation-owned → never load someone else's
323
+ | 'refused-foreign' // the plist EXISTS but is not foundation-owned → never load someone else's
324
+ | 'missing-plist' // no plist at that path at all — nothing to load (NOT a foreign plist)
324
325
  | 'failed' // launchctl bootstrap exited non-zero
325
326
 
326
327
  export interface BootstrapResult {
@@ -329,6 +330,14 @@ export interface BootstrapResult {
329
330
  detail?: string
330
331
  }
331
332
 
333
+ /** Did a bootstrap attempt leave the job NOT running? The single definition every caller
334
+ * shares, so adding a state can never silently pass someone's hand-rolled failure check
335
+ * (`state === 'failed' || state === 'refused-foreign'` had to be edited in three places).
336
+ * `skipped-sandbox` is a deliberate no-op, not a failure. */
337
+ export function bootstrapFailed(state: BootstrapState): boolean {
338
+ return state === 'failed' || state === 'refused-foreign' || state === 'missing-plist'
339
+ }
340
+
332
341
  /** Is `com.iapeer.<personality>` already loaded in the gui domain? (`launchctl print`
333
342
  * exits 0 when the service exists.) Used to make bootstrap idempotent. */
334
343
  function isLaunchdLoaded(label: string, uid: string): boolean {
@@ -632,6 +641,20 @@ export function launchctlBootstrap(
632
641
  // (Deriving from `personality` alone would mis-label a per-runtime plist.)
633
642
  const base = plistPath.slice(plistPath.lastIndexOf('/') + 1)
634
643
  const label = base.endsWith('.plist') ? base.slice(0, -'.plist'.length) : launchdLabel(personality)
644
+ // ABSENT ≠ FOREIGN. isFoundationOwnedPlist reads the file and returns false on ANY
645
+ // read error, so a plist that simply does not exist used to be reported as "not
646
+ // foundation-owned (no sentinel) — refusing a foreign plist": a sentinel verdict on a
647
+ // file that was never there. That is a FALSE ownership accusation, and it sent the
648
+ // operator hunting for a foreign fleet plist instead of the real cause (no channel
649
+ // provisioned yet). Discriminate first — the caller turns this into an actionable
650
+ // "provision it with <verb>" instead of a fleet-guard refusal.
651
+ if (!existsSync(plistPath)) {
652
+ return {
653
+ state: 'missing-plist',
654
+ label,
655
+ detail: `${plistPath} does not exist — no always-on plist has been provisioned for peer "${personality}" on this channel`,
656
+ }
657
+ }
635
658
  if (!isFoundationOwnedPlist(plistPath)) {
636
659
  return {
637
660
  state: 'refused-foreign',
@@ -799,8 +822,16 @@ export function installAlwaysOnPlist(opts: InstallAlwaysOnPlistOptions): string
799
822
  programArguments: [...(opts.entrypointArgv ?? defaultEntrypointArgv(env)), opts.personality, opts.runtime],
800
823
  workingDirectory: opts.cwd,
801
824
  environment,
802
- stdoutPath: join(logDir, 'launchd-stdout.log'),
803
- stderrPath: join(logDir, 'launchd-stderr.log'),
825
+ // MULTI-INFRA log separation: the log dir is PERSONALITY-scoped, so with a second
826
+ // always-on channel both plists pointed at the SAME launchd-stdout/stderr.log and the
827
+ // two routers interleaved into one file (live on this host: arthur's telegram and web
828
+ // channels shared it) — unreadable, and a crash-loop in one channel looks like noise
829
+ // from the other. The per-runtime plist gets a per-runtime file. The LEGACY BASE plist
830
+ // keeps the unsuffixed names: it is the personality's original single channel, and
831
+ // renaming its log on an unrelated regeneration would orphan the operator's existing
832
+ // tails for no gain (same no-forced-migration rule resolveAlwaysOnTarget follows).
833
+ stdoutPath: join(logDir, target.scheme === 'per-runtime' ? `launchd-${opts.runtime}-stdout.log` : 'launchd-stdout.log'),
834
+ stderrPath: join(logDir, target.scheme === 'per-runtime' ? `launchd-${opts.runtime}-stderr.log` : 'launchd-stderr.log'),
804
835
  throttleIntervalSecs: opts.throttleIntervalSecs,
805
836
  }
806
837
  mkdirSync(launchAgentsDir(env), { recursive: true })