oomi-ai 0.14.0 → 0.15.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.
package/README.md CHANGED
@@ -109,7 +109,9 @@ oomi connect --runtime hermes --name hermes --app-url https://www.oomi.ai
109
109
  oomi connect --runtime command --name my-agent --command '["/absolute/path/to/adapter"]' --app-url https://www.oomi.ai
110
110
  ```
111
111
 
112
- Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, an Oomi-owned conversation (no `--resume`) runs on a warm `hermes acp` process with oomi-ai 0.9.0+: replies stream as they are written and stop when the person interrupts. From 0.9.1 the bridge starts Hermes and reopens recent conversations ahead of time (at bridge start and when a call opens), so the first message doesn't wait for Hermes to start. Hermes permission requests are denied, as `chat --quiet` denies dangerous commands; ordinary file edits run as they do in quiet mode. A conversation moving from the CLI starts a new Hermes session that receives the recent Oomi history. `--resume` conversations, Hermes without ACP, and `--hermes-transport cli` use `chat --quiet --query-file -` and resume the exact returned `session_id` on subsequent turns.
112
+ If your person's message has a pairing code or an `oomi.ai/pair/...` link, add `--pair CODE` to that command; the code or the whole link both work. An older package does not know `--pair`: update with `npm install -g oomi-ai@latest` first. You then ask to join their oomi account instead of handing them a link: the command says hello, connects as usual, and waits up to five minutes for them to say yes in oomi. Tell them "I've asked to join. Say yes in oomi." `Connected.` means they said yes. `Still waiting` means the bridge is running and they can still say yes while the prompt lasts. `Not connected` means they declined, cancelled, or the code expired; ask them before trying again. If the command prints an Auth Link instead (an expired code, a code another agent used, or a server that doesn't take codes), send that link to your person. The code works for one agent, so never pass it on. Your person sees the name and runtime you registered and this computer's host name, so they can tell it's you; `--computer "Desk PC"` shows a different label.
113
+
114
+ Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, an Oomi-owned conversation (no `--resume`) runs on a warm `hermes acp` process with oomi-ai 0.9.0+: replies stream as they are written and stop when the person interrupts. From 0.9.1 the bridge starts Hermes and reopens recent conversations ahead of time (at bridge start and when a call opens), so the first message doesn't wait for Hermes to start. Hermes permission requests are denied, as `chat --quiet` denies dangerous commands; ordinary file edits run as they do in quiet mode. A conversation moving from the CLI starts a new Hermes session that receives the recent Oomi history. `--resume` conversations, Hermes without ACP, and `--hermes-transport cli` use `chat --quiet --query-file -` and resume the exact returned `session_id` on subsequent turns. If the connection check gets no answer over ACP and you did not pass `--hermes-transport`, `connect` retries once over the quiet CLI and keeps that connection on it; an explicit `--hermes-transport acp` fails instead.
113
115
 
114
116
  Shared desktop conversations require Hermes's loopback WebSocket gateway, active-session discovery, and durable prompt/reply row IDs. Busy conversations ask you to retry after the current task. If a simultaneous desktop send queues your message without a reply receipt, or the connection drops after sending, check the same Hermes chat before resending. Oomi cannot safely repeat an uncertain action. Human approvals stay in the existing Hermes desktop UI. Shared photo submission is not yet supported; use Hermes desktop for that photo. Older or terminal-only owners without a shared gateway receive an actionable error, never a competing process. The shared owner keeps its existing environment, so use the explicit Oomi `--connection NAME` for account commands.
115
117
 
@@ -171,7 +173,7 @@ oomi bridge repair --name hermes
171
173
  oomi invite --name hermes --app-url https://www.oomi.ai
172
174
  ```
173
175
 
174
- Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd or Linux systemd user. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance; native Windows does not yet have an automatic service installer. A sleeping, powered-off, or disconnected computer remains unavailable.
176
+ Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd, Linux systemd user, or (from 0.15.0) on Windows oomi's own supervisor, started from your Run key at sign-in. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance. Native Windows needs no administrator rights: the bridge runs while you are signed in to Windows and stops when you sign out. `--no-sign-in` keeps that worker recovery without writing the Run key (`--sign-in` turns it back on), and a Run key that Windows refuses no longer keeps the bridge from starting; `oomi status` says which of the two protections hold. A bridge started from inside another app, such as the Claude desktop app, stops whenever that app updates or restarts until sign-in starts it again, so start it from your own terminal or sign out and back in once. A sleeping, powered-off, or disconnected computer remains unavailable.
175
177
 
176
178
  Run `oomi bridge list` to find saved connection names and their startup protection on this computer. To update an existing connection on **each computer**, follow Updating Oomi safely above. Repair preserves pairing and conversations. On a running 0.8.1+ supervised bridge it queues a safe restart and reports pending work; on a stopped bridge it installs/starts supervision and waits for the broker connection. It does not send a model probe or switch agents. Do not copy connection credentials between computers.
177
179
 
@@ -356,7 +358,7 @@ Bridge status meanings:
356
358
  - `reconnecting`: transport dropped and retry is scheduled
357
359
  - `degraded`: bridge caught a runtime fault but is still alive
358
360
  - `error`: startup or auth failure blocked useful operation
359
- - `stopped`: not running or intentionally stopped
361
+ - `stopped`: not running or intentionally stopped. When the recorded process has ended without writing anything (a crash, `SIGKILL`, or Windows ending it outright), `oomi status` and `oomi bridge list` report `stopped` with `unrecordedExit: true` and `lastPid`, whatever the file last said
360
362
 
361
363
  ## Troubleshooting
362
364
 
@@ -203,6 +203,8 @@ oomi connect --runtime hermes --name hermes --app-url https://www.oomi.ai
203
203
  oomi connect --runtime command --name my-agent --command '["/absolute/path/to/adapter"]' --app-url https://www.oomi.ai
204
204
  ```
205
205
 
206
+ If your person's message has a pairing code or an `oomi.ai/pair/...` link, add `--pair CODE` to that command; the code or the whole link both work. An older package does not know `--pair`: update with `npm install -g oomi-ai@latest` first. You then ask to join their oomi account instead of handing them a link: the command says hello, connects as usual, and waits up to five minutes for them to say yes in oomi. Tell them "I've asked to join. Say yes in oomi." `Connected.` means they said yes. `Still waiting` means the bridge is running and they can still say yes while the prompt lasts. `Not connected` means they declined, cancelled, or the code expired; ask them before trying again. If the command prints an Auth Link instead (an expired code, a code another agent used, or a server that doesn't take codes), send that link to your person. The code works for one agent, so never pass it on. Your person sees the name and runtime you registered and this computer's host name, so they can tell it's you; `--computer "Desk PC"` shows a different label.
207
+
206
208
  Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, Hermes uses `chat --quiet --query-file -` and resumes the exact returned `session_id` on subsequent turns.
207
209
 
208
210
  Shared desktop conversations require Hermes's loopback WebSocket gateway, active-session discovery, and durable prompt/reply row IDs. Busy conversations ask you to retry after the current task. If a simultaneous desktop send queues your message without a reply receipt, or the connection drops after sending, check the same Hermes chat before resending. Oomi cannot safely repeat an uncertain action. Human approvals stay in the existing Hermes desktop UI. Shared photo submission is not yet supported; use Hermes desktop for that photo. Older or terminal-only owners without a shared gateway receive an actionable error, never a competing process. The shared owner keeps its existing environment, so use the explicit Oomi `--connection NAME` for account commands.
@@ -263,7 +265,7 @@ oomi bridge repair --name hermes
263
265
  oomi invite --name hermes --app-url https://www.oomi.ai
264
266
  ```
265
267
 
266
- Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd or Linux systemd user. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance; native Windows does not yet have an automatic service installer. A sleeping, powered-off, or disconnected computer remains unavailable.
268
+ Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd, Linux systemd user, or (from 0.15.0) on Windows oomi's own supervisor, started from your Run key at sign-in. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance. Native Windows needs no administrator rights: the bridge runs while you are signed in to Windows and stops when you sign out. `--no-sign-in` keeps that worker recovery without writing the Run key (`--sign-in` turns it back on), and a Run key that Windows refuses no longer keeps the bridge from starting; `oomi status` says which of the two protections hold. A bridge started from inside another app, such as the Claude desktop app, stops whenever that app updates or restarts until sign-in starts it again, so start it from your own terminal or sign out and back in once. A sleeping, powered-off, or disconnected computer remains unavailable.
267
269
 
268
270
  Run `oomi bridge list` to find saved connection names and their startup protection on this computer. To update an existing connection on **each computer**, follow Updating Oomi safely above. Repair preserves pairing and conversations. On a running 0.8.1+ supervised bridge it queues a safe restart and reports pending work; on a stopped bridge it installs/starts supervision and waits for the broker connection. It does not send a model probe or switch agents. Do not copy connection credentials between computers.
269
271
 
package/bin/oomi-ai.js CHANGED
@@ -16,16 +16,17 @@ import { createGatewayRuns } from '../lib/gatewayRuns.js';
16
16
  import { CHAT_MODELS_CAPABILITY } from '../lib/chatModels.js';
17
17
  import { OpenclawModelRequests } from '../lib/openclawModels.js';
18
18
  import { startUpdateWatcher } from '../lib/updateWatcher.js';
19
- import { processCommand, readProcessTable } from '../lib/processTable.js';
19
+ import { processCommand, readProcessTable, isBridgeWorkerCommand as matchesBridgeWorker, liveBridgeStatus } from '../lib/processTable.js';
20
20
  import { bridgeServiceConfig, createBridgeService, renderLaunchAgent } from '../lib/bridgeService.js';
21
21
  import { LOCAL_PROTOCOL_MIN, LOCAL_PROTOCOL_MAX, probeGateway } from '../lib/gatewayProbe.js';
22
- import { LocalAgentRuntime, practiceContext, localAgentConfig, runLocalAgent, writePrivateJson, startChannelWorker } from '../lib/localAgent.js';
22
+ import { LocalAgentRuntime, practiceContext, localAgentConfig, runLocalAgent, hermesCliFallbackApplies, writePrivateJson, startChannelWorker } from '../lib/localAgent.js';
23
23
  import { validateAgentName, identityRequest, startIdentityWorker, handleIdentityCommand } from '../lib/agentIdentity.js';
24
24
  import { handleSpacesCommand, compactHealth } from '../lib/spaces.js';
25
25
  import { handleObjectivesCommand } from '../lib/objectives.js';
26
26
  import { handleRoutinesCommand, startRoutineEventWorker } from '../lib/routines.js';
27
27
  import { handleChannelCommand, startAgentChannelWorker } from '../lib/agentChannels.js';
28
28
  import { classifyRuntimeFailure } from '../lib/runtimeFailure.js';
29
+ import { parsePairCode, formatPairCode, pairHello, pairAnswer, waitForPairApproval, describePairOutcome, PAIR_POLL_MS, PAIR_WAIT_MS } from '../lib/pairingRequest.js';
29
30
  import { createPersonaApiClient } from '../lib/personaApiClient.js';
30
31
  import { inferSpokenMetadataFromContent, normalizeSpokenMetadata } from '../lib/spokenMetadata.js';
31
32
  import {
@@ -214,14 +215,18 @@ function usage() {
214
215
  Commands:
215
216
  update
216
217
  Check for a newer package and return a safe, approval-preserving update plan.
217
- connect --runtime openclaw|hermes|grokbot|command [--name CONNECTION] [--agent-name "Your name"] [--app-url URL]
218
+ connect --runtime openclaw|hermes|grokbot|command [--name CONNECTION] [--agent-name "Your name"] [--app-url URL] [--pair CODE]
218
219
  Verify the selected local agent, pair once, start its bridge, and return an Auth Link.
220
+ --pair CODE (or the oomi.ai/pair/CODE link from your person's prompt) asks to join their account instead:
221
+ the command waits up to 5 minutes for their yes and prints Connected. If the code can't be used, you get the Auth Link.
219
222
  Hermes: --hermes-home DIR --profile PROFILE [--hermes-command JSON_ARGV] [--resume SESSION_ID]
220
223
  Hermes: --profile PROFILE and --resume SESSION select the intended agent/session.
221
- Hermes: --hermes-transport auto|acp|cli (default auto streams replies over ACP when Hermes supports it).
224
+ Hermes: --hermes-transport auto|acp|cli (default auto streams replies over ACP when Hermes supports it,
225
+ and keeps the connection on the quiet CLI when the connection check gets no answer over ACP).
222
226
  Other agents: --command '["/absolute/path/to/adapter"]' (JSON stdin / JSON stdout).
223
227
  --cwd PATH selects the agent working directory; --name isolates multiple agents.
224
- Installs automatic startup on macOS/Linux. --no-service opts into external supervision.
228
+ Installs automatic startup on macOS, Linux and Windows. --no-service opts into external supervision.
229
+ Windows: --no-sign-in keeps worker recovery but doesn't start the bridge at sign-in (--sign-in turns it back on).
225
230
  status [--name NAME]
226
231
  Show broker connection and verified local agent health separately.
227
232
  verify [--name NAME]
@@ -235,8 +240,8 @@ Commands:
235
240
  Generate a fresh Auth Link from saved pairing without changing agents.
236
241
  bridge [start|ensure|stop|restart|repair|list|ps] [--name NAME] [--detach]
237
242
  Manage only the named agent's bridge. Repair restores supervision without re-pairing.
238
- bridge service [install|start|stop|restart|status|uninstall] [--name NAME]
239
- Manage automatic restart and startup (macOS launchd / Linux systemd user).
243
+ bridge service [install|start|stop|restart|status|uninstall] [--name NAME] [--sign-in|--no-sign-in]
244
+ Manage automatic restart and startup (macOS launchd / Linux systemd user / Windows sign-in).
240
245
 
241
246
  init
242
247
  Install Oomi agent instructions into OpenClaw AGENTS.md.
@@ -891,6 +896,9 @@ function currentBridgeService(runtime = readBridgeState().runtime) {
891
896
  logPath: resolveBridgeLiveLogPath(), scriptPath: fileURLToPath(import.meta.url),
892
897
  });
893
898
  const system = createBridgeService(config);
899
+ // Windows has neither launchd nor systemd: oomi's own supervisor restarts the worker, and the
900
+ // person's Run key starts it again at sign-in.
901
+ if (process.platform === 'win32') return createHostProcessService(config);
894
902
  if (runtime === 'grokbot' && process.platform === 'linux') {
895
903
  const host = createHostProcessService(config);
896
904
  if (fs.existsSync(host.config.file) || (!fs.existsSync(config.file) && !system.availability().available)) return host;
@@ -1045,12 +1053,7 @@ function isPidAlive(pid) {
1045
1053
  }
1046
1054
 
1047
1055
  function isBridgeWorkerCommand(command, connectionName = bridgeConnectionName) {
1048
- const text = String(command || '').trim().toLowerCase();
1049
- if (!/(?:oomi(?:-ai\.(?:js|mjs))?|openclaw)\s+bridge\b/.test(text)) return false;
1050
- const connection = text.match(/--(?:connection|name)[=\s]+([a-z0-9_-]+)/)?.[1] || '';
1051
- if (connection !== connectionName) return false;
1052
- if (/\bbridge\s+(ps|stop|restart|ensure|service)\b/.test(text)) return false;
1053
- return /\bbridge(?:\s+start)?(?:\s+--|$)/.test(text);
1056
+ return matchesBridgeWorker(command, connectionName);
1054
1057
  }
1055
1058
 
1056
1059
  function isBridgeProcess(pid) {
@@ -1064,6 +1067,12 @@ function isBridgeProcess(pid) {
1064
1067
  return isBridgeWorkerCommand(command);
1065
1068
  }
1066
1069
 
1070
+ // What the status file says, corrected by what is running: a bridge that died without writing
1071
+ // "stopped" is not connected (lib/processTable.js liveBridgeStatus).
1072
+ function readLiveBridgeStatus() {
1073
+ return liveBridgeStatus(readBridgeStatus(), isBridgeProcess);
1074
+ }
1075
+
1067
1076
  function readBridgeLock() {
1068
1077
  return readJsonSafe(resolveBridgeLockPath()) || {};
1069
1078
  }
@@ -2277,6 +2286,23 @@ function classifyBridgeFailure({ err, reason = '', code = '', forceClass = '' }
2277
2286
  };
2278
2287
  }
2279
2288
 
2289
+ // ActionCable uses disconnect for both planned restarts and refused credentials.
2290
+ // An explicit reconnect flag wins; older servers without one retry non-auth notices.
2291
+ function classifyBrokerDisconnect(payload = {}) {
2292
+ const reason = String(payload.reason || 'broker requested disconnect');
2293
+ const authFailure = /unauthorized|forbidden|invalid.?token|token.?expired/i.test(reason);
2294
+ const retryable = payload.reconnect === true || (payload.reconnect !== false && !authFailure);
2295
+ return {
2296
+ errorCode: retryable ? 'BROKER_DISCONNECT_RETRY' : 'BROKER_DISCONNECT_STOP',
2297
+ message: reason,
2298
+ failureClass: retryable ? 'network' : authFailure ? 'auth_rejected' : 'broker_disconnect_terminal',
2299
+ retryable,
2300
+ hint: retryable ? 'Broker requested a reconnect; retrying with backoff.'
2301
+ : 'Broker refused reconnect. Check the connection with its owner before re-pairing.',
2302
+ baseDelayMs: BRIDGE_RECONNECT_BASE_MS,
2303
+ };
2304
+ }
2305
+
2280
2306
  function computeReconnectDelayMs(attempt, baseDelayMs) {
2281
2307
  const growth = Math.min(BRIDGE_RECONNECT_MAX_MS, Math.round(baseDelayMs * (2 ** Math.max(0, attempt - 1))));
2282
2308
  const jitter = Math.floor(growth * (Math.random() * 0.25));
@@ -2645,6 +2671,8 @@ async function startOpenclawBridge(flags) {
2645
2671
  lastErrorMessage: '',
2646
2672
  consecutiveFailures: 0,
2647
2673
  pid: process.pid,
2674
+ // How an earlier process stopped says nothing about this one.
2675
+ stopSignal: null,
2648
2676
  startedAt: bridgeNowIso(),
2649
2677
  packageVersion: currentPackageVersion(),
2650
2678
  maintenanceProtocol: 1,
@@ -3033,6 +3061,7 @@ async function startOpenclawBridge(flags) {
3033
3061
  return {
3034
3062
  type: 'broker.disconnect',
3035
3063
  reason: String(payload.reason || ''),
3064
+ reconnect: payload.reconnect,
3036
3065
  };
3037
3066
  }
3038
3067
  if (payload.type === 'reject_subscription') {
@@ -3635,10 +3664,34 @@ async function startOpenclawBridge(flags) {
3635
3664
  }
3636
3665
 
3637
3666
  if (payload.type === 'broker.disconnect') {
3638
- reconnectState.lastFailure = classifyBridgeFailure({
3639
- reason: String(payload.reason || 'unauthorized'),
3640
- forceClass: 'auth_rejected',
3641
- });
3667
+ // ActionCable sends this notice for a planned restart too (audit C3/R6). That one reconnects
3668
+ // with backoff in this same process; only a refusal (an auth failure, or reconnect:false) stops it.
3669
+ const disconnect = classifyBrokerDisconnect(payload);
3670
+ if (disconnect.retryable) {
3671
+ reconnectState.lastFailure = disconnect;
3672
+ console.error(`[bridge] ${disconnect.hint}`);
3673
+ updateBridgeStatus({
3674
+ status: 'reconnecting',
3675
+ deviceId,
3676
+ brokerWs,
3677
+ brokerHttp,
3678
+ gatewayUrl: gateway.gatewayUrl,
3679
+ lastDisconnectAt: bridgeNowIso(),
3680
+ lastErrorCode: disconnect.errorCode,
3681
+ lastErrorClass: disconnect.failureClass,
3682
+ lastErrorMessage: disconnect.message,
3683
+ hint: disconnect.hint,
3684
+ consecutiveFailures: reconnectState.attempt + 1,
3685
+ pid: process.pid,
3686
+ });
3687
+ try {
3688
+ brokerSocket.close(1012, 'broker_restart');
3689
+ } catch {
3690
+ // The close handler schedules the reconnect either way.
3691
+ }
3692
+ return;
3693
+ }
3694
+ reconnectState.lastFailure = disconnect;
3642
3695
  reconnectState.stopped = true;
3643
3696
  console.error(`[bridge] Broker rejected connection: ${String(payload.reason || 'unauthorized')}`);
3644
3697
  console.error(`[bridge] ${reconnectState.lastFailure.hint}`);
@@ -4174,8 +4227,8 @@ async function createOpenclawInviteLink(flags) {
4174
4227
 
4175
4228
  function printOpenclawBridgeStatus(flags) {
4176
4229
  const bridgeState = readBridgeState();
4177
- const runtimeStatus = readBridgeStatus();
4178
- if (runtimeStatus.pid && !isBridgeProcess(runtimeStatus.pid)) { runtimeStatus.status = 'stopped'; runtimeStatus.runtimeReady = false; }
4230
+ const runtimeStatus = readLiveBridgeStatus();
4231
+ const named = bridgeConnectionName ? ` --name ${bridgeConnectionName}` : '';
4179
4232
  const jsonOutput = isTruthyFlag(flags.json);
4180
4233
  const redactToken = (value) => {
4181
4234
  const text = String(value || '').trim();
@@ -4208,8 +4261,16 @@ function printOpenclawBridgeStatus(flags) {
4208
4261
  if (payload.maintenance) console.log(`Maintenance: ${payload.maintenance.status} — ${payload.maintenance.message || ''}`);
4209
4262
  console.log('Oomi Bridge Status');
4210
4263
  const supervision = payload.supervision;
4211
- console.log(supervision.manager === 'host-process' ? `Worker recovery: ${supervision.enabled ? 'on' : 'off'} for this host session; reconnect after a cloud computer restart.` : `Automatic startup: ${supervision.installed && supervision.enabled ? supervision.manager + ' (' + supervision.startsAt + ')' : 'off'}`);
4212
- if (!supervision.installed || !supervision.enabled || !supervision.running) console.log(`Repair on this computer: oomi bridge repair${bridgeConnectionName ? ' --name ' + bridgeConnectionName : ''}`);
4264
+ if (supervision.manager === 'windows-logon') {
4265
+ // Two separate promises on Windows: the supervisor restarts the worker while the person stays
4266
+ // signed in, and the Run key starts the supervisor at the next sign-in. Say which ones hold.
4267
+ console.log(`Worker recovery: ${supervision.enabled && supervision.loaded ? 'on' : 'off'} while you are signed in to Windows.`);
4268
+ console.log(supervision.enabled && supervision.startsAfterHostRestart ? 'Automatic startup: at Windows sign-in.'
4269
+ : `Automatic startup: off at Windows sign-in.${supervision.enabled ? ` To turn it on: oomi bridge service start${named} --sign-in` : ''}`);
4270
+ } else {
4271
+ console.log(supervision.manager === 'host-process' ? `Worker recovery: ${supervision.enabled ? 'on' : 'off'} for this host session; reconnect after a cloud computer restart.` : `Automatic startup: ${supervision.installed && supervision.enabled ? supervision.manager + ' (' + supervision.startsAt + ')' : 'off'}`);
4272
+ }
4273
+ if (!supervision.installed || !supervision.enabled || !supervision.running) console.log(`Repair on this computer: oomi bridge repair${named}`);
4213
4274
  if (supervision.reason) console.log(supervision.reason);
4214
4275
  console.log('------------------');
4215
4276
  console.log(`Bridge state: ${payload.bridgeStatePath}`);
@@ -4222,6 +4283,15 @@ function printOpenclawBridgeStatus(flags) {
4222
4283
  }
4223
4284
  if (payload.runtime && typeof payload.runtime === 'object' && Object.keys(payload.runtime).length > 0) {
4224
4285
  console.log(`Bridge state: ${String(payload.runtime.status || 'unknown')}`);
4286
+ if (payload.runtime.unrecordedExit) {
4287
+ console.log(` Its process (pid ${payload.runtime.lastPid}) has ended without recording why; its last update was at ${payload.runtime.updatedAt || 'an unknown time'}. Nothing answers for this connection until it starts again.`);
4288
+ }
4289
+ // A paired computer that no account has claimed connects fine, but no one can call or message it.
4290
+ if (/not linked/i.test(String(payload.runtime.agentChannelError || ''))) {
4291
+ console.log(`Account: this computer isn't linked to an oomi account yet. Make a fresh Auth Link with oomi invite${named} and open it while signed in to oomi.`);
4292
+ } else if (payload.runtime.agentChannelError) {
4293
+ console.log(`Chat links: ${payload.runtime.agentChannelError}`);
4294
+ }
4225
4295
  console.log(`Agent runtime: ${bridgeState.runtime || 'openclaw'}${bridgeState.localAgent?.profile ? ` (profile ${bridgeState.localAgent.profile})` : ''}`);
4226
4296
  console.log(`Local reply verified: ${payload.runtime.runtimeReady ? 'yes' : 'no'}${payload.runtime.verifiedAt ? ` at ${payload.runtime.verifiedAt}` : ''}`);
4227
4297
  if (payload.runtime.lastConnectedAt) {
@@ -4338,7 +4408,8 @@ function listLocalBridgeConnections() {
4338
4408
  const state = readBridgeState();
4339
4409
  const running = findRunningBridgeProcess();
4340
4410
  return { name: name || null, runtime: state.runtime || 'openclaw', deviceId: state.deviceId || null,
4341
- running: Boolean(running), supervision: currentBridgeService().status(),
4411
+ running: Boolean(running), status: liveBridgeStatus(readBridgeStatus(), (pid) => pid === running?.pid || isBridgeProcess(pid)).status || null,
4412
+ supervision: currentBridgeService().status(),
4342
4413
  repairCommand: `oomi bridge repair${name ? ' --name ' + name : ''}` };
4343
4414
  });
4344
4415
  } finally { bridgeConnectionName = selected; }
@@ -4387,15 +4458,17 @@ async function handleBridgeServiceCommand(actionRaw = '', flags = {}) {
4387
4458
  if (['install', 'start', 'restart'].includes(action)) requireSavedBridge();
4388
4459
  if (['install', 'restart'].includes(action) && !isTruthyFlag(flags['no-start']) && deferLiveRestart()) return;
4389
4460
  if (action !== 'start') assertIndependentMaintenance();
4461
+ const signIn = signInChoice(flags);
4462
+ let started;
4390
4463
  if (action === 'install') {
4391
- service.install({ noStart: true });
4464
+ service.install({ noStart: true, signIn });
4392
4465
  await stopSupervisedBridge(service);
4393
- if (!isTruthyFlag(flags['no-start'])) service.start();
4466
+ if (!isTruthyFlag(flags['no-start'])) started = service.start({ signIn });
4394
4467
  } else if (action === 'start') {
4395
- service.start(); // Idempotent: do not interrupt a healthy worker.
4468
+ started = service.start({ signIn }); // Idempotent: do not interrupt a healthy worker.
4396
4469
  } else if (action === 'restart') {
4397
4470
  await stopSupervisedBridge(service);
4398
- service.start({ rewrite: true });
4471
+ started = service.start({ rewrite: true, signIn });
4399
4472
  incrementBridgeMetric('bridge_restart_count');
4400
4473
  } else if (action === 'stop') {
4401
4474
  await stopSupervisedBridge(service);
@@ -4404,7 +4477,30 @@ async function handleBridgeServiceCommand(actionRaw = '', flags = {}) {
4404
4477
  service.uninstall();
4405
4478
  }
4406
4479
  const result = service.status();
4407
- console.log(JSON.stringify({ action, ...result }, null, 2));
4480
+ console.log(JSON.stringify({ action, ...result, ...(started?.signInError ? { signInError: started.signInError } : {}) }, null, 2));
4481
+ }
4482
+
4483
+ // Windows: --sign-in or --no-sign-in records whether the connection's supervisor also starts at
4484
+ // Windows sign-in (the person's Run key). Without either flag the saved choice stands (default on).
4485
+ function signInChoice(flags = {}) {
4486
+ if (isTruthyFlag(flags['no-sign-in'])) return false;
4487
+ if (isTruthyFlag(flags['sign-in'])) return true;
4488
+ return undefined;
4489
+ }
4490
+
4491
+ // What will bring this connection's bridge back, as its service reports it rather than as hoped.
4492
+ function describeSupervision(service, started = null) {
4493
+ const status = service.status();
4494
+ if (status.manager === 'host-process') return 'Worker recovery: enabled for this host session. After a cloud computer restart, rerun oomi connect; boot recovery is unavailable on this host.';
4495
+ if (status.manager !== 'windows-logon') return `Automatic startup: ${service.config.platform === 'darwin' ? 'macOS login service' : 'Linux user service'}; restarts after worker exits.`;
4496
+ const named = bridgeConnectionName ? ` --name ${bridgeConnectionName}` : '';
4497
+ const why = started?.signInError ? ` (${started.signInError})` : status.signIn === false ? ' (--no-sign-in)' : '';
4498
+ return [
4499
+ 'Worker recovery: on while you are signed in to Windows; the bridge restarts after its worker exits.',
4500
+ status.startsAfterHostRestart ? 'Automatic startup: at Windows sign-in.' : `Automatic startup: off at Windows sign-in${why}. To turn it on: oomi bridge service start${named} --sign-in`,
4501
+ // processSupervisor.js: a supervisor started by a command lives in the job of the program that ran it.
4502
+ "Started from inside an app (the Claude desktop app is one), it stops when that app updates or restarts, until it is started again at sign-in or from a terminal of your own.",
4503
+ ].join('\n');
4408
4504
  }
4409
4505
 
4410
4506
  async function repairBridge(flags = {}) {
@@ -4413,7 +4509,9 @@ async function repairBridge(flags = {}) {
4413
4509
  await handleBridgeServiceCommand('install', flags);
4414
4510
  if (!isTruthyFlag(flags['no-start'])) {
4415
4511
  await waitForBridgeConnection({});
4416
- console.log(currentBridgeService().status().manager === 'host-process' ? 'Oomi bridge restored with worker recovery for this host session. Reconnect after a cloud computer restart. Pairing and conversations preserved.' : 'Oomi bridge restored with automatic startup. Pairing and conversations preserved.');
4512
+ const service = currentBridgeService();
4513
+ if (service.status().manager === 'windows-logon') console.log(`Oomi bridge restored. Pairing and conversations preserved.\n${describeSupervision(service)}`);
4514
+ else console.log(service.status().manager === 'host-process' ? 'Oomi bridge restored with worker recovery for this host session. Reconnect after a cloud computer restart. Pairing and conversations preserved.' : 'Oomi bridge restored with automatic startup. Pairing and conversations preserved.');
4417
4515
  }
4418
4516
  }
4419
4517
 
@@ -4439,8 +4537,9 @@ async function startBridgeLifecycle(flags = {}) {
4439
4537
  const service = currentBridgeService();
4440
4538
  if (service.status().installed) {
4441
4539
  if (isTruthyFlag(flags.detach)) throw new Error('This connection has a supervisor. Use bridge start, or uninstall its service before using --detach.');
4442
- service.start();
4540
+ const started = service.start({ signIn: signInChoice(flags) });
4443
4541
  console.log(`Bridge service started: ${service.config.target}`);
4542
+ if (started?.signInError) console.warn(`Windows sign-in startup was not set: ${started.signInError}`);
4444
4543
  return;
4445
4544
  }
4446
4545
  }
@@ -4587,6 +4686,7 @@ function refreshSelectedSkill(state, flags = {}) {
4587
4686
  async function connectLocalAgent(flags) {
4588
4687
  assertIndependentMaintenance();
4589
4688
  const agentName = flags['agent-name'] === undefined ? undefined : validateAgentName(flags['agent-name']);
4689
+ const pairCode = flags.pair === undefined ? '' : parsePairCode(flags.pair);
4590
4690
  const runtime = String(flags.runtime || '');
4591
4691
  if (!['openclaw', 'hermes', 'grokbot', 'command'].includes(runtime)) throw new Error('Specify --runtime for your own agent: openclaw, hermes, grokbot, or command. An unlisted brand may use an adapter; read oomi capabilities. Never select a different agent just because it is installed.');
4592
4692
  const service = currentBridgeService(runtime);
@@ -4623,10 +4723,29 @@ async function connectLocalAgent(flags) {
4623
4723
  const identity = ({ hermesTransport, ...rest } = {}) => JSON.stringify(rest);
4624
4724
  if (saved && identity(saved) !== identity(state.localAgent)) throw new Error('This name already identifies a different agent configuration. Use a new --name to change its command, profile, session, or working directory.');
4625
4725
  }
4726
+ // A pairing code from the person's prompt: say hello first, so their waiting screen moves.
4727
+ let pairing = null;
4728
+ if (pairCode) {
4729
+ if (!state.brokerHttp) {
4730
+ const config = await fetchManagedGatewayConfig({ appUrl });
4731
+ state.brokerHttp = rewriteLoopbackBrokerUrlForAppHost(config.brokerHttpUrl, appUrl);
4732
+ state.brokerWs = rewriteLoopbackBrokerUrlForAppHost(config.brokerDeviceWsUrl, appUrl);
4733
+ }
4734
+ pairing = await pairHello({ backendHttp: state.brokerHttp, code: pairCode });
4735
+ }
4626
4736
  if (!previous.verifiedAt || isTruthyFlag(flags.verify)) {
4627
4737
  console.log(`Verifying ${runtime}${state.localAgent?.profile ? ` profile ${state.localAgent.profile}` : ''} with a local test message...`);
4628
4738
  try {
4629
- const verified = await verifyLocalAgent(state);
4739
+ let verified;
4740
+ try { verified = await verifyLocalAgent(state); }
4741
+ catch (err) {
4742
+ // Some Hermes installs never answer over ACP. Unless the person chose the transport, the
4743
+ // quiet CLI gets one try, and the connection keeps it so later turns don't wait on ACP again.
4744
+ if (!hermesCliFallbackApplies(state.localAgent, err)) throw err;
4745
+ console.log("Hermes didn't answer over its streaming connection; using its command line for this connection.");
4746
+ state.localAgent = { ...state.localAgent, hermesTransport: 'cli' };
4747
+ verified = await verifyLocalAgent(state);
4748
+ }
4630
4749
  state.verifiedAt = verified.verifiedAt;
4631
4750
  } catch (err) {
4632
4751
  const explained = explainVerificationFailure(err);
@@ -4637,6 +4756,7 @@ async function connectLocalAgent(flags) {
4637
4756
  console.log(`Reusing the verified ${runtime} runtime. No model test message sent. Use oomi verify for an explicit paid-model probe.`);
4638
4757
  }
4639
4758
  writeBridgeState(state); // Keep successful verification even if pairing later needs a retry.
4759
+ if (pairing && !pairing.ok) console.log(`${pairing.message} Connecting anyway; you'll get an Auth Link to send to your person instead.`);
4640
4760
  if (!state.deviceToken) {
4641
4761
  const config = await fetchManagedGatewayConfig({ appUrl });
4642
4762
  state.brokerHttp = rewriteLoopbackBrokerUrlForAppHost(config.brokerHttpUrl, appUrl);
@@ -4657,23 +4777,43 @@ async function connectLocalAgent(flags) {
4657
4777
  console.warn('This Oomi server does not support agent settings yet. Connecting without shared settings.');
4658
4778
  }
4659
4779
  // Install/update only this connection's supervisor, retaining its saved identity and session.
4660
- if (!unmanaged) service.install({ noStart: true });
4780
+ if (!unmanaged) service.install({ noStart: true, signIn: signInChoice(flags) });
4661
4781
  const stopped = unmanaged ? await stopBridgeProcesses() : await stopSupervisedBridge(service);
4662
4782
  if (stopped.stillAlive?.length) throw new Error('The existing bridge did not stop. Resolve it before reconnecting.');
4663
4783
  writeBridgeState(state);
4664
4784
  updateBridgeStatus({ status: 'starting', runtime, runtimeReady: true, verifiedAt: state.verifiedAt, lastErrorMessage: '' });
4665
- const child = unmanaged ? startBridgeDetachedProcess({ 'app-url': appUrl }) : (service.start(), {});
4785
+ const started = unmanaged ? null : service.start({ signIn: signInChoice(flags) });
4786
+ const child = unmanaged ? startBridgeDetachedProcess({ 'app-url': appUrl }) : {};
4666
4787
  await waitForBridgeConnection(child);
4667
- console.log(unmanaged ? 'Automatic startup: off (--no-service); your host supervisor must manage recovery.'
4668
- : service.status().manager === 'host-process' ? 'Worker recovery: enabled for this host session. After a cloud computer restart, rerun oomi connect; boot recovery is unavailable on this host.'
4669
- : `Automatic startup: ${service.config.platform === 'darwin' ? 'macOS login service' : 'Linux user service'}; restarts after worker exits.`);
4788
+ console.log(unmanaged ? 'Automatic startup: off (--no-service); your host supervisor must manage recovery.' : describeSupervision(service, started));
4670
4789
  const invite = await requestConnectInviteLink({ backendHttp: state.brokerHttp, appUrl, sessionKey: state.sessionKey, deviceToken: state.deviceToken });
4671
4790
  refreshSelectedSkill(state, flags);
4791
+ const ready = { status: 'ready', runtime, agentId: state.localAgent?.agentId, verifiedAt: state.verifiedAt, inviteUrl: invite.inviteUrl };
4792
+ if (pairing?.ok) {
4793
+ // Ask to join: the Auth Link goes to oomi against the code, and the person says yes there.
4794
+ const asked = await pairAnswer({ backendHttp: state.brokerHttp, code: pairCode, inviteUrl: invite.inviteUrl, deviceToken: state.deviceToken, computer: String(flags.computer || os.hostname() || '') });
4795
+ if (asked.ok) {
4796
+ console.log(`Verified agent: ${runtime}${state.localAgent?.profile ? ` (${state.localAgent.profile})` : ''}`);
4797
+ // Grok Bot's setup runs in the background; its reply command passes this on without waiting.
4798
+ if (flags['setup-worker']) return { ...ready, pairing: { status: 'answered', code: formatPairCode(pairCode) } };
4799
+ console.log('Asked to join. Waiting for your person to say yes in oomi…');
4800
+ const outcome = await waitForPairApproval({
4801
+ backendHttp: state.brokerHttp, code: pairCode, deviceToken: state.deviceToken,
4802
+ intervalMs: Number(process.env.OOMI_PAIR_POLL_MS) || PAIR_POLL_MS,
4803
+ timeoutMs: Number(process.env.OOMI_PAIR_WAIT_MS) || PAIR_WAIT_MS,
4804
+ });
4805
+ const described = describePairOutcome(outcome);
4806
+ console.log(described.line);
4807
+ if (described.exitCode) process.exitCode = described.exitCode;
4808
+ return { ...ready, pairing: { status: outcome.status } };
4809
+ }
4810
+ console.log(`${asked.message} Send this Auth Link to your person instead.`);
4811
+ }
4672
4812
  console.log(`Verified agent: ${runtime}${state.localAgent?.profile ? ` (${state.localAgent.profile})` : ''}`);
4673
4813
  console.log('Oomi Connect Ready');
4674
4814
  console.log(`Auth Link: ${invite.inviteUrl}`);
4675
4815
  console.log('Open the Auth Link to approve ownership, then send a message in Oomi to verify delivery end to end.');
4676
- return { status: 'ready', runtime, agentId: state.localAgent?.agentId, verifiedAt: state.verifiedAt, inviteUrl: invite.inviteUrl };
4816
+ return ready;
4677
4817
  }
4678
4818
 
4679
4819
  async function main() {
@@ -4744,7 +4884,8 @@ async function main() {
4744
4884
  console.log(JSON.stringify(receipt));
4745
4885
  if (receipt.verification) {
4746
4886
  const setup = await waitConnectionSetup(directory, args.flags['agent-id']);
4747
- if (setup?.status === 'ready') console.log(`Verified agent: grokbot (${args.flags['agent-id']})\nOomi Connect Ready\nAuth Link: ${setup.inviteUrl}`);
4887
+ if (setup?.status === 'ready' && setup.pairing?.status === 'answered') console.log(`Verified agent: grokbot (${args.flags['agent-id']})\nAsked to join. Tell your person: "I've asked to join. Say yes in oomi."`);
4888
+ else if (setup?.status === 'ready') console.log(`Verified agent: grokbot (${args.flags['agent-id']})\nOomi Connect Ready\nAuth Link: ${setup.inviteUrl}`);
4748
4889
  else if (setup) console.log(JSON.stringify(setup));
4749
4890
  }
4750
4891
  return;
@@ -4757,6 +4898,7 @@ async function main() {
4757
4898
  const directory = connectionDirectory();
4758
4899
  const config = grokbotConfig({ ...args.flags, 'agent-id': args.flags['agent-id'] || saved?.agentId, 'grokbot-config': args.flags['grokbot-config'] || saved?.configFile, 'grokbot-gateway': args.flags['grokbot-gateway'] || saved?.gatewayFile }, directory);
4759
4900
  if (!args.flags['setup-worker']) {
4901
+ if (args.flags.pair !== undefined) parsePairCode(args.flags.pair); // Refuse a mistyped code now, not in the background.
4760
4902
  if (!isTruthyFlag(args.flags['no-service'])) currentBridgeService('grokbot').preflight();
4761
4903
  console.log(JSON.stringify(queueConnectionSetup({ directory, agentId: config.agentId, cli: process.argv[1], args: process.argv.slice(2) }), null, 2));
4762
4904
  return;
@@ -4954,6 +5096,7 @@ export {
4954
5096
  handleOpenclawProfileCommand,
4955
5097
  buildBridgeLaunchAgentPlist,
4956
5098
  classifyBridgeFailure,
5099
+ classifyBrokerDisconnect,
4957
5100
  classifyBridgeSessionScope,
4958
5101
  createBridgeProcessFaultHandler,
4959
5102
  computeReconnectDelayMs,
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { readJson, writePrivateJson } from './localAgent.js';
6
6
  import { classifyRuntimeFailure } from './runtimeFailure.js';
7
+ import { isBridgeWorker, liveBridgeStatus } from './processTable.js';
7
8
 
8
9
  // Owner-visible conversations between this agent and one other agent.
9
10
  // Host side uses the device token against the Oomi API. Guest side (after
@@ -83,12 +84,16 @@ export function explainConnectionError(error, directory) {
83
84
  }
84
85
 
85
86
  // A link only helps if this agent can answer; warn before handing one out.
86
- export function bridgeWarnings(directory) {
87
+ // A status file can say "connected" for a bridge that has since been ended outright, so the
88
+ // recorded pid must still be this connection's running bridge (lib/processTable.js).
89
+ export function bridgeWarnings(directory, { isRunning } = {}) {
87
90
  if (!directory) return [];
88
- const status = readJson(path.join(directory, 'oomi-bridge-status.json'), null);
91
+ const connection = path.resolve(path.dirname(directory)) === path.resolve(connectionsRoot()) ? path.basename(directory) : '';
92
+ const status = liveBridgeStatus(readJson(path.join(directory, 'oomi-bridge-status.json'), null), isRunning || ((pid) => isBridgeWorker(pid, connection)));
89
93
  if (!status) return ['No oomi bridge status was found for this connection. Run oomi bridge repair for it, or guest messages will wait unanswered.'];
90
94
  const warnings = [];
91
- if (['error', 'degraded', 'failed', 'stopped'].includes(status.status)) warnings.push(`Your oomi bridge reports "${status.status}"${status.lastErrorMessage ? `: ${String(status.lastErrorMessage).replace(/\.\s*$/, '')}` : ''}.`);
95
+ if (status.unrecordedExit) warnings.push(`Your oomi bridge isn't running: its process (pid ${status.lastPid}) ended without recording why. Run oomi bridge repair${connection ? ` --name ${connection}` : ''} on this computer.`);
96
+ else if (['error', 'degraded', 'failed', 'stopped'].includes(status.status)) warnings.push(`Your oomi bridge reports "${status.status}"${status.lastErrorMessage ? `: ${String(status.lastErrorMessage).replace(/\.\s*$/, '')}` : ''}.`);
92
97
  if (status.agentChannelError) warnings.push(status.agentChannelError);
93
98
  return warnings;
94
99
  }
package/lib/localAgent.js CHANGED
@@ -213,6 +213,16 @@ function usesHermesAcp(config) {
213
213
  return config.hermesTransport === 'acp' || hermesAcpAvailable(config);
214
214
  }
215
215
 
216
+ // The connection check may retry over the quiet CLI when ACP itself failed (no answer, a refused
217
+ // request, a Hermes that exited) and the person did not ask for ACP. A pinned session never used
218
+ // ACP, and an explicit --hermes-transport acp must keep failing where the person can see it.
219
+ const ACP_FAILURES = new Set(['hermes_acp_timeout', 'hermes_acp_rpc', 'hermes_acp_exited', 'hermes_acp_unavailable']);
220
+ export function hermesCliFallbackApplies(config, err) {
221
+ if (!config || config.runtime !== 'hermes' || config.resume) return false;
222
+ if (config.hermesTransport && config.hermesTransport !== 'auto') return false;
223
+ return ACP_FAILURES.has(err?.code);
224
+ }
225
+
216
226
  // A guest's turn (agent channels, chat links) runs with the persona's tools off: Hermes as
217
227
  // `hermes chat --toolsets clarify` (no terminal, files, browser, memory, skills or MCP servers;
218
228
  // Hermes freezes the toolsets into the session), a command adapter told `sandbox: true`. Grok
@@ -0,0 +1,107 @@
1
+ // `oomi connect --pair <code>` (docs/specs/pairing-prompt-v1.md). The person's oomi account made
2
+ // a short code and sent it in a prompt. The agent says hello with it, connects as it always has,
3
+ // hands its Auth Link to oomi against the code, and waits for the person to say yes. The code
4
+ // grants nothing by itself, and anything that goes wrong here falls back to printing the Auth Link.
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+
7
+ const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
8
+ const CODE = new RegExp(`^[${ALPHABET}]{8}$`);
9
+
10
+ export const PAIR_POLL_MS = 3000;
11
+ export const PAIR_WAIT_MS = 5 * 60 * 1000;
12
+
13
+ // "7k4m-q2xd", "7K4MQ2XD" and "https://www.oomi.ai/pair/7K4M-Q2XD" are the same code.
14
+ export function parsePairCode(raw) {
15
+ let value = typeof raw === 'string' ? raw.trim() : '';
16
+ const link = value.match(/\/pair\/([^/?#]+)/i);
17
+ if (link) value = link[1].replace(/\.txt$/i, '');
18
+ value = value.toUpperCase().replace(/[\s-]/g, '');
19
+ if (!CODE.test(value)) throw new Error("Use --pair with the code or link from your person's prompt, like --pair 7K4M-Q2XD.");
20
+ return value;
21
+ }
22
+
23
+ export const formatPairCode = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
24
+
25
+ async function call(fetchImpl, url, { method = 'GET', body, deviceToken } = {}) {
26
+ try {
27
+ const response = await fetchImpl(url, {
28
+ method,
29
+ signal: AbortSignal.timeout(15000),
30
+ headers: {
31
+ Accept: 'application/json',
32
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
33
+ ...(deviceToken ? { Authorization: `Bearer ${deviceToken}` } : {}),
34
+ },
35
+ ...(body ? { body: JSON.stringify(body) } : {}),
36
+ });
37
+ const payload = await response.json().catch(() => ({}));
38
+ return { httpStatus: response.status, payload: payload && typeof payload === 'object' ? payload : {} };
39
+ } catch {
40
+ return { httpStatus: 0, payload: {} };
41
+ }
42
+ }
43
+
44
+ // Why hello or answer didn't go through, in words an agent can pass on.
45
+ function refusal({ httpStatus, payload }) {
46
+ const reasonCode = typeof payload.reasonCode === 'string' ? payload.reasonCode : '';
47
+ if (httpStatus === 0) return { reason: 'unreachable', reasonCode, message: "oomi couldn't be reached to use the pairing code." };
48
+ // A server from before pairing prompts answers 404 with no pairing reason.
49
+ if (httpStatus === 404 && !reasonCode.startsWith('pairing_request_')) return { reason: 'unsupported', reasonCode, message: "This oomi server doesn't take pairing codes yet." };
50
+ const messages = {
51
+ pairing_request_invalid: "The pairing code isn't valid any more.",
52
+ pairing_request_expired: 'The pairing code has expired.',
53
+ pairing_request_already_answered: 'Another agent already asked to join with this pairing code.',
54
+ pairing_request_declined: "Your person turned this computer's request down, so it can't ask again with this code.",
55
+ pairing_request_invite_mismatch: "oomi didn't accept this connection's Auth Link for the pairing code.",
56
+ };
57
+ return { reason: 'refused', reasonCode, message: messages[reasonCode] || `oomi didn't accept the pairing code (${httpStatus}).` };
58
+ }
59
+
60
+ const endpoint = (backendHttp, path) => `${String(backendHttp).replace(/\/$/, '')}/v1/pairing_requests/${path}`;
61
+
62
+ // Step 1: the person's waiting screen shows that an agent started setting up.
63
+ export async function pairHello({ backendHttp, code, fetchImpl = fetch }) {
64
+ const result = await call(fetchImpl, endpoint(backendHttp, 'hello'), { method: 'POST', body: { code } });
65
+ if (result.httpStatus === 200 && result.payload.ok) return { ok: true, expiresAt: result.payload.expiresAt || null };
66
+ return { ok: false, ...refusal(result) };
67
+ }
68
+
69
+ // Step 3: ask to join. The Auth Link goes to oomi against the code; the person never sees it.
70
+ export async function pairAnswer({ backendHttp, code, inviteUrl, deviceToken, computer = '', fetchImpl = fetch }) {
71
+ const inviteToken = String(inviteUrl || '').split('/connect/').pop().split(/[?#]/)[0];
72
+ const result = await call(fetchImpl, endpoint(backendHttp, 'answer'), {
73
+ method: 'POST',
74
+ deviceToken,
75
+ body: { code, inviteToken, ...(computer ? { computer: String(computer).slice(0, 80) } : {}) },
76
+ });
77
+ if (result.httpStatus === 200 && result.payload.ok) return { ok: true, expiresAt: result.payload.expiresAt || null };
78
+ return { ok: false, ...refusal(result) };
79
+ }
80
+
81
+ // Step 4: wait for the yes. Resolves with approved, declined, expired or cancelled, or with
82
+ // waiting when the time is up and the person hasn't answered. A dropped request is tried again.
83
+ export async function waitForPairApproval({ backendHttp, code, deviceToken, intervalMs = PAIR_POLL_MS, timeoutMs = PAIR_WAIT_MS, fetchImpl = fetch, now = Date.now }) {
84
+ const url = `${endpoint(backendHttp, 'status')}?code=${encodeURIComponent(code)}`;
85
+ const end = now() + timeoutMs;
86
+ let expiresAt = null;
87
+ for (;;) {
88
+ const { httpStatus, payload } = await call(fetchImpl, url, { deviceToken });
89
+ if (payload.expiresAt) expiresAt = payload.expiresAt;
90
+ if (httpStatus === 200 && ['approved', 'declined', 'expired', 'cancelled'].includes(payload.status)) return { status: payload.status, expiresAt };
91
+ if (httpStatus === 410) return { status: 'expired', expiresAt };
92
+ if (httpStatus === 404) return { status: 'cancelled', expiresAt };
93
+ if (now() + intervalMs > end) return { status: 'waiting', expiresAt };
94
+ await delay(intervalMs);
95
+ }
96
+ }
97
+
98
+ // The one line the command prints for each way the wait ends, and its exit code.
99
+ export function describePairOutcome({ status, expiresAt }, now = Date.now()) {
100
+ if (status === 'approved') return { exitCode: 0, line: 'Connected.' };
101
+ if (status === 'declined') return { exitCode: 1, line: "Not connected: your person said this agent isn't theirs. Ask them before trying again." };
102
+ if (status === 'expired') return { exitCode: 1, line: 'Not connected: the pairing code expired before your person said yes. Ask them for a new prompt.' };
103
+ if (status === 'cancelled') return { exitCode: 1, line: 'Not connected: your person cancelled the request. Ask them for a new prompt.' };
104
+ const minutes = Math.floor((Date.parse(expiresAt || '') - now) / 60000);
105
+ const window = Number.isFinite(minutes) && minutes >= 1 ? ` any time in the next ${minutes} minute${minutes === 1 ? '' : 's'}` : ' while the prompt lasts';
106
+ return { exitCode: 0, line: `Still waiting. Your person can say yes in oomi${window}.` };
107
+ }
@@ -5,10 +5,14 @@ import { randomUUID } from 'node:crypto';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
 
8
+ const windows = process.platform === 'win32';
9
+
8
10
  function read(file) {
9
11
  try {
10
12
  const stat = fs.lstatSync(file);
11
- if (!stat.isFile() || stat.size > 65536 || (stat.mode & 0o077) || stat.uid !== process.getuid()) throw new Error('Invalid private service file.');
13
+ // Windows keeps a profile's files private through ACLs; POSIX mode bits and uids mean nothing there.
14
+ const foreign = !windows && ((stat.mode & 0o077) || stat.uid !== process.getuid());
15
+ if (!stat.isFile() || stat.size > 65536 || foreign) throw new Error('Invalid private service file.');
12
16
  return JSON.parse(fs.readFileSync(file, 'utf8'));
13
17
  } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
14
18
  }
@@ -16,36 +20,94 @@ function save(file, data) {
16
20
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
17
21
  const tmp = `${file}.${randomUUID()}.tmp`;
18
22
  fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600, flag: 'wx' });
19
- fs.renameSync(tmp, file);
23
+ // Windows refuses to replace a file for the instant another process (the supervisor, a scanner) has it open.
24
+ for (let attempt = 0; ; attempt += 1) {
25
+ try { fs.renameSync(tmp, file); return; }
26
+ catch (error) {
27
+ if (!windows || attempt >= 40 || !['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) { try { fs.unlinkSync(tmp); } catch { /* the rename's error is the one to report */ } throw error; }
28
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
29
+ }
30
+ }
31
+ }
32
+
33
+ // A process's start time tells a live worker from a later process that reused its pid. Windows has
34
+ // no cheap way to read it, so one PowerShell call is remembered for as long as that pid stays alive.
35
+ const windowsStarts = new Map();
36
+ function windowsIdentity(pid) {
37
+ if (windowsStarts.has(pid)) return windowsStarts.get(pid);
38
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
39
+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`], { encoding: 'utf8', timeout: 15000, windowsHide: true });
40
+ const started = result.status === 0 ? String(result.stdout).trim() : '';
41
+ if (!/^\d+$/.test(started)) return null;
42
+ windowsStarts.set(pid, started);
43
+ return started;
20
44
  }
21
45
  function identity(pid) {
22
46
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
23
47
  try {
24
48
  process.kill(pid, 0);
49
+ if (windows) return windowsIdentity(pid);
25
50
  if (process.platform === 'linux') {
26
51
  const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
27
52
  return fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() + ':' + stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];
28
53
  }
29
54
  const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8', timeout: 2000 });
30
55
  return result.status === 0 ? result.stdout.trim() || null : null;
31
- } catch { return null; }
56
+ } catch { windowsStarts.delete(pid); return null; }
32
57
  }
33
58
  function owner(file) {
34
59
  const state = read(`${file}.owner`);
35
60
  return state && state.identity && identity(state.pid) === state.identity ? state : null;
36
61
  }
37
62
 
38
- // A host-session supervisor, explicitly distinct from an OS boot service. It
39
- // recovers worker exits on container hosts without modifying their init system.
40
- export function createHostProcessService(base) {
63
+ // Windows starts the supervisor again at sign-in from the person's own Run key: no administrator
64
+ // rights, nothing installed system-wide, and conhost's headless mode keeps Node from opening a window.
65
+ const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
66
+ // Windows ignores a Run value longer than this.
67
+ const RUN_VALUE_LIMIT = 259;
68
+ export function windowsLogonCommand(file, { nodePath = process.execPath, scriptPath = fileURLToPath(import.meta.url), systemRoot = process.env.SystemRoot || 'C:\\Windows' } = {}) {
69
+ const quoted = [path.win32.join(systemRoot, 'System32', 'conhost.exe'), nodePath, scriptPath, file].map((part) => {
70
+ if (part.includes('"')) throw new Error('Windows startup paths cannot contain quotation marks.');
71
+ return `"${part}"`;
72
+ });
73
+ return `${quoted[0]} --headless ${quoted[1]} ${quoted[2]} --run ${quoted[3]}`;
74
+ }
75
+
76
+ // A supervisor for one connection's worker, where the host has no launchd or systemd to do it.
77
+ // On Linux containers it lasts for the host session. On Windows it also comes back at sign-in,
78
+ // unless the person chose --no-sign-in (saved as signIn:false in the definition).
79
+ export function createHostProcessService(base, { run = spawnSync } = {}) {
80
+ const logon = base.platform === 'win32';
41
81
  const config = { ...base, file: path.join(base.directory, 'oomi-process-service.json'), target: base.label };
42
- const availability = () => ({ available: config.platform === 'linux', reason: config.platform === 'linux' ? null : 'Host-session supervision requires Linux.' });
82
+ const supported = config.platform === 'linux' || logon;
83
+ const availability = () => ({ available: supported, reason: supported ? null : 'Host-session supervision requires Linux or Windows.' });
84
+ const registry = (args) => {
85
+ const result = run('reg.exe', args, { encoding: 'utf8', timeout: 15000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
86
+ return { code: Number.isInteger(result.status) ? result.status : 1, stdout: String(result.stdout || ''), stderr: String(result.stderr || result.error?.message || '').trim() };
87
+ };
88
+ const logonCommand = () => windowsLogonCommand(config.file, { nodePath: config.args[0] });
89
+ // Registered means the Run value starts this connection's definition, not just that some value has this name.
90
+ const registered = () => logon && registry(['query', RUN_KEY, '/v', config.label]).stdout.includes(config.file);
91
+ function register() {
92
+ const command = logonCommand();
93
+ // Windows ignores a longer Run value; refuse it here rather than write one that never starts.
94
+ if (command.length > RUN_VALUE_LIMIT) throw new Error(`Windows sign-in startup allows a command of ${RUN_VALUE_LIMIT} characters; this one is ${command.length}. Install oomi-ai or keep the connection in a shorter path.`);
95
+ const result = registry(['add', RUN_KEY, '/v', config.label, '/t', 'REG_SZ', '/d', command, '/f']);
96
+ if (result.code) throw new Error(`Could not register Windows sign-in startup: ${result.stderr || 'reg.exe failed'}`);
97
+ }
98
+ function unregister() {
99
+ if (!registered()) return;
100
+ const result = registry(['delete', RUN_KEY, '/v', config.label, '/f']);
101
+ if (result.code) throw new Error(`Could not remove Windows sign-in startup: ${result.stderr || 'reg.exe failed'}`);
102
+ }
43
103
  function preflight() {
44
104
  if (!availability().available) throw new Error(availability().reason);
45
105
  const existing = read(config.file);
46
106
  if (existing && existing.directory !== config.directory) throw new Error('This supervisor belongs to another connection.');
47
107
  if (config.args[1].split(path.sep).includes('_npx')) throw new Error('Install oomi-ai before starting host-session supervision; an npx cache is temporary.');
48
108
  for (const file of config.args.slice(0, 2)) fs.accessSync(file, fs.constants.R_OK);
109
+ // The Run value's length limit belongs to sign-in startup alone (register): worker recovery,
110
+ // and a connection that chose --no-sign-in, don't depend on it.
49
111
  }
50
112
  function update(fields) {
51
113
  preflight();
@@ -56,29 +118,50 @@ export function createHostProcessService(base) {
56
118
  function status() {
57
119
  const saved = read(config.file), supervisor = owner(config.file), child = read(`${config.file}.status`);
58
120
  const current = child?.instance === supervisor?.instance;
59
- return { ...availability(), manager: 'host-process', connection: config.name, target: config.target, file: config.file,
121
+ return { ...availability(), manager: logon ? 'windows-logon' : 'host-process', connection: config.name, target: config.target, file: config.file,
60
122
  installed: Boolean(saved), enabled: saved?.enabled === true, loaded: Boolean(supervisor),
61
123
  running: Boolean(saved?.enabled && current && child?.childIdentity && identity(child.childPid) === child.childIdentity),
62
- pid: current ? child?.childPid || null : null, startsAt: 'host-session', persistsWithoutLogin: true, startsAfterHostRestart: false };
124
+ pid: current ? child?.childPid || null : null, startsAt: logon ? 'login' : 'host-session',
125
+ ...(logon ? { signIn: saved?.signIn !== false } : {}),
126
+ persistsWithoutLogin: !logon, startsAfterHostRestart: registered() };
127
+ }
128
+ // signIn (Windows): true or false records the person's choice; undefined keeps the saved one.
129
+ // The worker starts first, so a registry that refuses the Run key can't keep the bridge from
130
+ // running: start returns that refusal as signInError for the caller to show.
131
+ function start({ rewrite = false, signIn } = {}) {
132
+ update({ enabled: true, ...(logon && typeof signIn === 'boolean' ? { signIn } : {}),
133
+ ...(rewrite ? { args: config.args, environment: config.environment, generation: randomUUID(), ...(logon ? { logPath: config.logPath } : {}) } : {}) });
134
+ if (!owner(config.file)) launchSupervisor();
135
+ if (!logon) return {};
136
+ try {
137
+ if (read(config.file)?.signIn === false) unregister(); else register();
138
+ return { signInError: null };
139
+ } catch (error) { return { signInError: error.message }; }
63
140
  }
64
- function start({ rewrite = false } = {}) {
65
- update({ enabled: true, ...(rewrite ? { args: config.args, environment: config.environment, generation: randomUUID() } : {}) });
66
- if (owner(config.file)) return;
141
+ // A supervisor started here is a child of whatever ran this command, and on Windows it lives in
142
+ // that program's job: when a packaged app such as the Claude desktop app updates, Windows ends its
143
+ // whole job, this supervisor included (2026-11-14). Started by the Run key at sign-in, it is not.
144
+ function launchSupervisor() {
67
145
  fs.mkdirSync(path.dirname(config.logPath), { recursive: true, mode: 0o700 });
68
146
  const fd = fs.openSync(config.logPath, 'a', 0o600);
69
- fs.fchmodSync(fd, 0o600);
147
+ if (!windows) fs.fchmodSync(fd, 0o600);
70
148
  try {
71
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--run', config.file], { detached: true, stdio: ['ignore', fd, fd], env: { ...process.env, OOMI_CONNECTION: config.name } });
149
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--run', config.file], { detached: true, windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, OOMI_CONNECTION: config.name } });
72
150
  child.on('error', () => {}); // The connection readiness check reports failure.
73
151
  child.unref();
74
152
  } finally { fs.closeSync(fd); }
75
153
  }
76
- function install({ noStart = false } = {}) {
154
+ function install({ noStart = false, signIn } = {}) {
77
155
  preflight();
78
- save(config.file, { directory: config.directory, args: config.args, environment: config.environment, enabled: false, generation: randomUUID() });
79
- if (!noStart) start();
156
+ const previous = read(config.file);
157
+ const keepSignIn = typeof signIn === 'boolean' ? signIn : previous?.signIn;
158
+ // The sign-in start has no terminal, so the definition says where the worker's output goes.
159
+ save(config.file, { directory: config.directory, args: config.args, environment: config.environment, enabled: false, generation: randomUUID(),
160
+ ...(logon ? { logPath: config.logPath, ...(typeof keepSignIn === 'boolean' ? { signIn: keepSignIn } : {}) } : {}) });
161
+ return noStart ? {} : start();
80
162
  }
81
- const stop = () => { if (read(config.file)) update({ enabled: false }); };
163
+ // Stopped means stopped across a sign-in too: a disabled connection must not come back by itself.
164
+ const stop = () => { if (read(config.file)) update({ enabled: false }); if (logon) unregister(); };
82
165
  const restart = () => { if (!status().enabled || !owner(config.file)) throw new Error('Repair the connection supervisor before restarting.'); update({ generation: randomUUID() }); };
83
166
  const uninstall = () => { stop(); if (fs.existsSync(config.file)) fs.unlinkSync(config.file); };
84
167
  return { config, availability, preflight, status, install, start, stop, restart, uninstall };
@@ -114,7 +197,14 @@ async function supervise(file) {
114
197
  if (!ending && saved.enabled && !child && Date.now() >= nextStart) {
115
198
  if (saved.directory !== path.dirname(file) || !Array.isArray(saved.args) || saved.args.length < 2) throw new Error('Invalid supervisor definition.');
116
199
  generation = saved.generation; stoppingAt = 0;
117
- const worker = spawn(saved.args[0], saved.args.slice(1), { cwd: saved.directory, env: { ...process.env, ...saved.environment }, stdio: ['ignore', 'inherit', 'inherit'] });
200
+ // Started at sign-in there is no terminal to inherit: the worker writes to the connection's log.
201
+ let log = null;
202
+ if (saved.logPath) { fs.mkdirSync(path.dirname(saved.logPath), { recursive: true, mode: 0o700 }); log = fs.openSync(saved.logPath, 'a', 0o600); }
203
+ let worker;
204
+ try {
205
+ worker = spawn(saved.args[0], saved.args.slice(1), { cwd: saved.directory, env: { ...process.env, ...saved.environment }, windowsHide: true,
206
+ stdio: ['ignore', log ?? 'inherit', log ?? 'inherit'] });
207
+ } finally { if (log !== null) fs.closeSync(log); }
118
208
  child = worker;
119
209
  const finished = () => { if (child === worker) { child = null; nextStart = Date.now() + 1000; stoppingAt = 0; } };
120
210
  worker.once('error', finished); worker.once('exit', finished);
@@ -50,6 +50,52 @@ export function processCommand(pid, { run = spawnSync, platform = process.platfo
50
50
  }
51
51
  }
52
52
 
53
+ /**
54
+ * Whether a command line is the bridge worker of one connection ('' is the default OpenClaw one).
55
+ * Windows quotes a script path that has spaces in it: "C:\Users\A Person\...\oomi-ai.js" bridge start.
56
+ */
57
+ export function isBridgeWorkerCommand(command, connectionName = '') {
58
+ const text = String(command || '').trim().toLowerCase();
59
+ if (!/(?:oomi(?:-ai\.(?:js|mjs))?|openclaw)"?\s+bridge\b/.test(text)) return false;
60
+ const connection = text.match(/--(?:connection|name)[=\s]+"?([a-z0-9_-]+)/)?.[1] || '';
61
+ if (connection !== connectionName) return false;
62
+ if (/\bbridge\s+(ps|stop|restart|ensure|service)\b/.test(text)) return false;
63
+ return /\bbridge(?:\s+start)?(?:\s+--|$)/.test(text);
64
+ }
65
+
66
+ const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
67
+
68
+ /**
69
+ * Whether pid is a running bridge worker of that connection. A pid the host reused for another
70
+ * program is not; a live pid whose command line the host won't give is taken as the bridge.
71
+ */
72
+ export function isBridgeWorker(pid, connectionName = '', { run = spawnSync, platform = process.platform, alive = pidAlive } = {}) {
73
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !alive(pid)) return false;
74
+ const command = processCommand(pid, { run, platform });
75
+ return !command || isBridgeWorkerCommand(command, connectionName);
76
+ }
77
+
78
+ /**
79
+ * A bridge status file as it stands now. A bridge that was ended outright never writes "stopped":
80
+ * Windows ends processes without a signal they can catch, and a SIGKILL, crash or power cut does the
81
+ * same anywhere. So a recorded pid that is no longer a running bridge means the bridge is not running,
82
+ * whatever the file last said, and a stop signal kept from an earlier run says nothing about this one.
83
+ */
84
+ export function liveBridgeStatus(status, isRunning) {
85
+ if (!status || typeof status !== 'object') return status;
86
+ const pid = Number(status.pid);
87
+ if (!Number.isSafeInteger(pid) || pid <= 0 || isRunning(pid)) return status;
88
+ const recorded = status.status === 'stopped' || status.status === 'error';
89
+ return {
90
+ ...status,
91
+ status: recorded ? status.status : 'stopped',
92
+ runtimeReady: false,
93
+ pid: null,
94
+ lastPid: pid,
95
+ ...(recorded ? {} : { unrecordedExit: true, stopSignal: null }),
96
+ };
97
+ }
98
+
53
99
  /** When the process started, as the host states it (a reused pid starts at another time), or null. */
54
100
  export function processStartTime(pid, { run = spawnSync, platform = process.platform } = {}) {
55
101
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
@@ -274,6 +274,26 @@ async function postJson({ url, token, body, timeoutMs }) {
274
274
  }
275
275
  }
276
276
 
277
+ // The Oomi bridge is its own process (a LaunchAgent on macOS, a systemd user
278
+ // service on Linux, oomi's supervisor on Windows); this plugin never starts it.
279
+ // OpenClaw counts a channel account as running only while gateway.startAccount
280
+ // is pending, and treats a resolved start as "channel exited". So the start is
281
+ // passive: mark the account ready, then wait for the gateway's abort signal.
282
+ function waitForAbort(signal) {
283
+ if (!signal) return new Promise(() => {});
284
+ if (signal.aborted) return Promise.resolve();
285
+ return new Promise((resolve) => {
286
+ signal.addEventListener('abort', () => resolve(), { once: true });
287
+ });
288
+ }
289
+
290
+ async function startAccount(ctx = {}) {
291
+ const accountId = toString(ctx.accountId, 'default');
292
+ ctx.log?.info?.(`[${accountId}] oomi channel ready; the Oomi bridge runs as its own service`);
293
+ ctx.setStatus?.({ accountId, running: true, lifecycle: 'ready', lastError: null });
294
+ await waitForAbort(ctx.abortSignal);
295
+ }
296
+
277
297
  const oomiChannelPlugin = {
278
298
  id: CHANNEL_ID,
279
299
  meta: {
@@ -313,6 +333,10 @@ const oomiChannelPlugin = {
313
333
  },
314
334
  },
315
335
 
336
+ gateway: {
337
+ startAccount,
338
+ },
339
+
316
340
  outbound: {
317
341
  deliveryMode: 'direct',
318
342
 
@@ -2,13 +2,103 @@
2
2
  "id": "oomi-ai",
3
3
  "name": "Oomi Channel Plugin",
4
4
  "description": "Oomi connection, Spaces, health context and routines. Run oomi capabilities and oomi instructions; ordinary state updates do not invoke a model.",
5
- "version": "0.7.1",
5
+ "version": "0.15.0",
6
6
  "author": "Oomi",
7
7
  "license": "MIT",
8
8
  "openclawVersion": ">=0.5.0",
9
9
  "channels": [
10
10
  "oomi"
11
11
  ],
12
+ "channelConfigs": {
13
+ "oomi": {
14
+ "schema": {
15
+ "type": "object",
16
+ "additionalProperties": true,
17
+ "properties": {
18
+ "enabled": {
19
+ "type": "boolean"
20
+ },
21
+ "defaultAccountId": {
22
+ "type": "string"
23
+ },
24
+ "healthMonitor": {
25
+ "type": "object",
26
+ "additionalProperties": true,
27
+ "properties": {
28
+ "enabled": {
29
+ "type": "boolean"
30
+ }
31
+ }
32
+ },
33
+ "accounts": {
34
+ "type": "object",
35
+ "additionalProperties": {
36
+ "type": "object",
37
+ "additionalProperties": true,
38
+ "properties": {
39
+ "enabled": {
40
+ "type": "boolean"
41
+ },
42
+ "backendUrl": {
43
+ "type": "string"
44
+ },
45
+ "deviceToken": {
46
+ "type": "string"
47
+ },
48
+ "defaultSessionKey": {
49
+ "type": "string"
50
+ },
51
+ "requestTimeoutMs": {
52
+ "type": "number"
53
+ },
54
+ "healthMonitor": {
55
+ "type": "object",
56
+ "additionalProperties": true,
57
+ "properties": {
58
+ "enabled": {
59
+ "type": "boolean"
60
+ }
61
+ }
62
+ },
63
+ "modelRelay": {
64
+ "type": "object",
65
+ "additionalProperties": true,
66
+ "properties": {
67
+ "enabled": {
68
+ "type": "boolean"
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ },
77
+ "label": "Oomi",
78
+ "description": "Managed channel transport for Oomi chat. The Oomi bridge runs as its own service; run oomi connect to set it up.",
79
+ "uiHints": {
80
+ "defaultAccountId": {
81
+ "label": "Default account",
82
+ "advanced": true
83
+ },
84
+ "accounts.*.backendUrl": {
85
+ "label": "Oomi backend URL"
86
+ },
87
+ "accounts.*.deviceToken": {
88
+ "label": "Device token",
89
+ "sensitive": true
90
+ },
91
+ "accounts.*.defaultSessionKey": {
92
+ "label": "Default session key",
93
+ "advanced": true
94
+ },
95
+ "accounts.*.requestTimeoutMs": {
96
+ "label": "Request timeout (ms)",
97
+ "advanced": true
98
+ }
99
+ }
100
+ }
101
+ },
12
102
  "configSchema": {
13
103
  "type": "object",
14
104
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oomi-ai",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Connect OpenClaw, Hermes, Grok Bot, and other agents to Oomi with verified runtime adapters",
5
5
  "bin": {
6
6
  "oomi": "bin/oomi-ai.js"
@@ -49,7 +49,7 @@
49
49
  "url": "https://github.com/crispcode-io/oomi/issues"
50
50
  },
51
51
  "scripts": {
52
- "check": "node --check bin/oomi-ai.js && node --check lib/bridgeService.js && node --check lib/bridgeMaintenance.js && node --check lib/gatewayRuns.js && node --check lib/processTable.js && node --check lib/localAgent.js && node --check lib/chatModels.js && node --check lib/openclawModels.js && node --check lib/updateWatcher.js && node --check lib/hermesGateway.js && node --check lib/hermesAcp.js && node --check lib/grokbotRuntime.js && node --check lib/connectionSetup.js && node --check lib/processSupervisor.js && node --check lib/agentChannels.js && node --check lib/runtimeFailure.js",
52
+ "check": "node --check bin/oomi-ai.js && node --check lib/bridgeService.js && node --check lib/bridgeMaintenance.js && node --check lib/gatewayRuns.js && node --check lib/processTable.js && node --check lib/localAgent.js && node --check lib/chatModels.js && node --check lib/openclawModels.js && node --check lib/updateWatcher.js && node --check lib/hermesGateway.js && node --check lib/hermesAcp.js && node --check lib/grokbotRuntime.js && node --check lib/connectionSetup.js && node --check lib/processSupervisor.js && node --check lib/agentChannels.js && node --check lib/runtimeFailure.js && node --check lib/pairingRequest.js",
53
53
  "test": "node --test test/*.test.mjs",
54
54
  "prepublishOnly": "npm run check && node --test test/packageFiles.test.mjs"
55
55
  },
@@ -92,6 +92,7 @@
92
92
  "lib/processTable.js",
93
93
  "lib/agentChannels.js",
94
94
  "lib/runtimeFailure.js",
95
+ "lib/pairingRequest.js",
95
96
  "skills/oomi-delivery/SKILL.md"
96
97
  ]
97
98
  }
@@ -239,7 +239,9 @@ oomi connect --runtime hermes --name hermes --app-url https://www.oomi.ai
239
239
  oomi connect --runtime command --name my-agent --command '["/absolute/path/to/adapter"]' --app-url https://www.oomi.ai
240
240
  ```
241
241
 
242
- Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, an Oomi-owned conversation (no `--resume`) runs on a warm `hermes acp` process with oomi-ai 0.9.0+: replies stream as they are written and stop when the person interrupts. From 0.9.1 the bridge starts Hermes and reopens recent conversations ahead of time (at bridge start and when a call opens), so the first message doesn't wait for Hermes to start. Hermes permission requests are denied, as `chat --quiet` denies dangerous commands; ordinary file edits run as they do in quiet mode. A conversation moving from the CLI starts a new Hermes session that receives the recent Oomi history. `--resume` conversations, Hermes without ACP, and `--hermes-transport cli` use `chat --quiet --query-file -` and resume the exact returned `session_id` on subsequent turns.
242
+ If your person's message has a pairing code or an `oomi.ai/pair/...` link, add `--pair CODE` to that command; the code or the whole link both work. An older package does not know `--pair`: update with `npm install -g oomi-ai@latest` first. You then ask to join their oomi account instead of handing them a link: the command says hello, connects as usual, and waits up to five minutes for them to say yes in oomi. Tell them "I've asked to join. Say yes in oomi." `Connected.` means they said yes. `Still waiting` means the bridge is running and they can still say yes while the prompt lasts. `Not connected` means they declined, cancelled, or the code expired; ask them before trying again. If the command prints an Auth Link instead (an expired code, a code another agent used, or a server that doesn't take codes), send that link to your person. The code works for one agent, so never pass it on. Your person sees the name and runtime you registered and this computer's host name, so they can tell it's you; `--computer "Desk PC"` shows a different label.
243
+
244
+ Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, an Oomi-owned conversation (no `--resume`) runs on a warm `hermes acp` process with oomi-ai 0.9.0+: replies stream as they are written and stop when the person interrupts. From 0.9.1 the bridge starts Hermes and reopens recent conversations ahead of time (at bridge start and when a call opens), so the first message doesn't wait for Hermes to start. Hermes permission requests are denied, as `chat --quiet` denies dangerous commands; ordinary file edits run as they do in quiet mode. A conversation moving from the CLI starts a new Hermes session that receives the recent Oomi history. `--resume` conversations, Hermes without ACP, and `--hermes-transport cli` use `chat --quiet --query-file -` and resume the exact returned `session_id` on subsequent turns. If the connection check gets no answer over ACP and you did not pass `--hermes-transport`, `connect` retries once over the quiet CLI and keeps that connection on it; an explicit `--hermes-transport acp` fails instead.
243
245
 
244
246
  Shared desktop conversations require Hermes's loopback WebSocket gateway, active-session discovery, and durable prompt/reply row IDs. Busy conversations ask you to retry after the current task. If a simultaneous desktop send queues your message without a reply receipt, or the connection drops after sending, check the same Hermes chat before resending. Oomi cannot safely repeat an uncertain action. Human approvals stay in the existing Hermes desktop UI. Shared photo submission is not yet supported; use Hermes desktop for that photo. Older or terminal-only owners without a shared gateway receive an actionable error, never a competing process. The shared owner keeps its existing environment, so use the explicit Oomi `--connection NAME` for account commands.
245
247
 
@@ -299,7 +301,7 @@ oomi bridge repair --name hermes
299
301
  oomi invite --name hermes --app-url https://www.oomi.ai
300
302
  ```
301
303
 
302
- Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd or Linux systemd user. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance; native Windows does not yet have an automatic service installer. A sleeping, powered-off, or disconnected computer remains unavailable.
304
+ Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd, Linux systemd user, or (from 0.15.0) on Windows oomi's own supervisor, started from your Run key at sign-in. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance. Native Windows needs no administrator rights: the bridge runs while you are signed in to Windows and stops when you sign out. `--no-sign-in` keeps that worker recovery without writing the Run key (`--sign-in` turns it back on), and a Run key that Windows refuses no longer keeps the bridge from starting; `oomi status` says which of the two protections hold. A bridge started from inside another app, such as the Claude desktop app, stops whenever that app updates or restarts until sign-in starts it again, so start it from your own terminal or sign out and back in once. A sleeping, powered-off, or disconnected computer remains unavailable.
303
305
 
304
306
  Run `oomi bridge list` to find saved connection names and their startup protection on this computer. To update an existing connection on **each computer**, follow Updating Oomi safely above. Repair preserves pairing and conversations. On a running 0.8.1+ supervised bridge it queues a safe restart and reports pending work; on a stopped bridge it installs/starts supervision and waits for the broker connection. It does not send a model probe or switch agents. Do not copy connection credentials between computers.
305
307
 
@@ -203,6 +203,8 @@ oomi connect --runtime hermes --name hermes --app-url https://www.oomi.ai
203
203
  oomi connect --runtime command --name my-agent --command '["/absolute/path/to/adapter"]' --app-url https://www.oomi.ai
204
204
  ```
205
205
 
206
+ If your person's message has a pairing code or an `oomi.ai/pair/...` link, add `--pair CODE` to that command; the code or the whole link both work. An older package does not know `--pair`: update with `npm install -g oomi-ai@latest` first. You then ask to join their oomi account instead of handing them a link: the command says hello, connects as usual, and waits up to five minutes for them to say yes in oomi. Tell them "I've asked to join. Say yes in oomi." `Connected.` means they said yes. `Still waiting` means the bridge is running and they can still say yes while the prompt lasts. `Not connected` means they declined, cancelled, or the code expired; ask them before trying again. If the command prints an Auth Link instead (an expired code, a code another agent used, or a server that doesn't take codes), send that link to your person. The code works for one agent, so never pass it on. Your person sees the name and runtime you registered and this computer's host name, so they can tell it's you; `--computer "Desk PC"` shows a different label.
207
+
206
208
  Use the user's app URL when provided. Hermes supports `--profile <profile>` and `--resume <exact-session-id>`. Without `--resume`, Oomi starts a persistent conversation with the same configured agent. Do not use `latest` or claim that an existing chat session was transferred unless its exact ID was selected. With oomi-ai 0.8.2+, an already-open Hermes conversation uses its existing local gateway owner and exact profile/session. Oomi attaches as another client; it never closes desktop, clears history, deletes a session lock, or substitutes a new chat. When no live owner exists, Hermes uses `chat --quiet --query-file -` and resumes the exact returned `session_id` on subsequent turns.
207
209
 
208
210
  Shared desktop conversations require Hermes's loopback WebSocket gateway, active-session discovery, and durable prompt/reply row IDs. Busy conversations ask you to retry after the current task. If a simultaneous desktop send queues your message without a reply receipt, or the connection drops after sending, check the same Hermes chat before resending. Oomi cannot safely repeat an uncertain action. Human approvals stay in the existing Hermes desktop UI. Shared photo submission is not yet supported; use Hermes desktop for that photo. Older or terminal-only owners without a shared gateway receive an actionable error, never a competing process. The shared owner keeps its existing environment, so use the explicit Oomi `--connection NAME` for account commands.
@@ -263,7 +265,7 @@ oomi bridge repair --name hermes
263
265
  oomi invite --name hermes --app-url https://www.oomi.ai
264
266
  ```
265
267
 
266
- Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd or Linux systemd user. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance; native Windows does not yet have an automatic service installer. A sleeping, powered-off, or disconnected computer remains unavailable.
268
+ Do not pair again to refresh an expired Auth Link. Re-running `connect` reuses saved pairing and verification; only the first connection or an explicit `oomi verify` sends a model probe. A different command, profile, or working directory requires a new connection name, so one agent cannot silently replace another. Named connections store private state and logs under `~/.oomi/connections/<name>`; default OpenClaw keeps `~/.openclaw`. Since 0.8.0, `connect` installs a separate automatic-start service for each connection: macOS launchd, Linux systemd user, or (from 0.15.0) on Windows oomi's own supervisor, started from your Run key at sign-in. It restarts an exited worker and starts at the next login/user session. Linux servers can start at boot and remain running after logout when the host administrator enables user lingering (`loginctl enable-linger <user>`); `oomi bridge service status --name hermes` reports whether this is enabled. WSL needs systemd and a running WSL instance. Native Windows needs no administrator rights: the bridge runs while you are signed in to Windows and stops when you sign out. `--no-sign-in` keeps that worker recovery without writing the Run key (`--sign-in` turns it back on), and a Run key that Windows refuses no longer keeps the bridge from starting; `oomi status` says which of the two protections hold. A bridge started from inside another app, such as the Claude desktop app, stops whenever that app updates or restarts until sign-in starts it again, so start it from your own terminal or sign out and back in once. A sleeping, powered-off, or disconnected computer remains unavailable.
267
269
 
268
270
  Run `oomi bridge list` to find saved connection names and their startup protection on this computer. To update an existing connection on **each computer**, follow Updating Oomi safely above. Repair preserves pairing and conversations. On a running 0.8.1+ supervised bridge it queues a safe restart and reports pending work; on a stopped bridge it installs/starts supervision and waits for the broker connection. It does not send a model probe or switch agents. Do not copy connection credentials between computers.
269
271