oomi-ai 0.14.0 → 0.16.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/bin/oomi-ai.js CHANGED
@@ -16,16 +16,21 @@ 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 { closeHermesAcpClients } from '../lib/hermesAcp.js';
30
+ import { parsePairCode, formatPairCode, pairHello, pairAnswer, waitForPairApproval, describePairOutcome, PAIR_POLL_MS, PAIR_WAIT_MS } from '../lib/pairingRequest.js';
31
+ import { createIceServerSource, createWindowHost } from '../lib/windowHost.js';
32
+ import { handleWindowsCommand } from '../lib/windowsCommand.js';
33
+ import { handleControlCommand } from '../lib/controlCommand.js';
29
34
  import { createPersonaApiClient } from '../lib/personaApiClient.js';
30
35
  import { inferSpokenMetadataFromContent, normalizeSpokenMetadata } from '../lib/spokenMetadata.js';
31
36
  import {
@@ -214,14 +219,18 @@ function usage() {
214
219
  Commands:
215
220
  update
216
221
  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]
222
+ connect --runtime openclaw|hermes|grokbot|command [--name CONNECTION] [--agent-name "Your name"] [--app-url URL] [--pair CODE]
218
223
  Verify the selected local agent, pair once, start its bridge, and return an Auth Link.
224
+ --pair CODE (or the oomi.ai/pair/CODE link from your person's prompt) asks to join their account instead:
225
+ 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
226
  Hermes: --hermes-home DIR --profile PROFILE [--hermes-command JSON_ARGV] [--resume SESSION_ID]
220
227
  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).
228
+ Hermes: --hermes-transport auto|acp|cli (default auto streams replies over ACP when Hermes supports it,
229
+ and keeps the connection on the quiet CLI when the connection check gets no answer over ACP).
222
230
  Other agents: --command '["/absolute/path/to/adapter"]' (JSON stdin / JSON stdout).
223
231
  --cwd PATH selects the agent working directory; --name isolates multiple agents.
224
- Installs automatic startup on macOS/Linux. --no-service opts into external supervision.
232
+ Installs automatic startup on macOS, Linux and Windows. --no-service opts into external supervision.
233
+ Windows: --no-sign-in keeps worker recovery but doesn't start the bridge at sign-in (--sign-in turns it back on).
225
234
  status [--name NAME]
226
235
  Show broker connection and verified local agent health separately.
227
236
  verify [--name NAME]
@@ -235,8 +244,8 @@ Commands:
235
244
  Generate a fresh Auth Link from saved pairing without changing agents.
236
245
  bridge [start|ensure|stop|restart|repair|list|ps] [--name NAME] [--detach]
237
246
  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).
247
+ bridge service [install|start|stop|restart|status|uninstall] [--name NAME] [--sign-in|--no-sign-in]
248
+ Manage automatic restart and startup (macOS launchd / Linux systemd user / Windows sign-in).
240
249
 
241
250
  init
242
251
  Install Oomi agent instructions into OpenClaw AGENTS.md.
@@ -334,6 +343,17 @@ Commands:
334
343
  interrupting them for; say everything else in chat. Limited per hour. Turns started
335
344
  by an Oomi bridge already use their own connection (OOMI_CONNECTION).
336
345
 
346
+ windows on [APP ...] [--all] [--max-windows N]
347
+ Show these apps' windows, with their sound, on your oomi headset. Confirmed at this
348
+ computer with Windows Hello; an agent can't turn it on.
349
+ windows allow|deny APP ... | off | stop | list | status [--json] | check
350
+ Change the shared apps, turn sharing off, stop the current session, or check this computer.
351
+
352
+ control on | off | status [--json]
353
+ Let your personas click, type and press keys on this computer when you ask them from
354
+ oomi, so "play me some music" ends with it playing. Confirmed at this computer with
355
+ Windows Hello; an agent can't turn it on.
356
+
337
357
  Common flags:
338
358
  --agents-file PATH Override AGENTS.md path
339
359
  --workspace PATH Override OpenClaw workspace root
@@ -891,6 +911,9 @@ function currentBridgeService(runtime = readBridgeState().runtime) {
891
911
  logPath: resolveBridgeLiveLogPath(), scriptPath: fileURLToPath(import.meta.url),
892
912
  });
893
913
  const system = createBridgeService(config);
914
+ // Windows has neither launchd nor systemd: oomi's own supervisor restarts the worker, and the
915
+ // person's Run key starts it again at sign-in.
916
+ if (process.platform === 'win32') return createHostProcessService(config);
894
917
  if (runtime === 'grokbot' && process.platform === 'linux') {
895
918
  const host = createHostProcessService(config);
896
919
  if (fs.existsSync(host.config.file) || (!fs.existsSync(config.file) && !system.availability().available)) return host;
@@ -1045,12 +1068,7 @@ function isPidAlive(pid) {
1045
1068
  }
1046
1069
 
1047
1070
  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);
1071
+ return matchesBridgeWorker(command, connectionName);
1054
1072
  }
1055
1073
 
1056
1074
  function isBridgeProcess(pid) {
@@ -1064,6 +1082,12 @@ function isBridgeProcess(pid) {
1064
1082
  return isBridgeWorkerCommand(command);
1065
1083
  }
1066
1084
 
1085
+ // What the status file says, corrected by what is running: a bridge that died without writing
1086
+ // "stopped" is not connected (lib/processTable.js liveBridgeStatus).
1087
+ function readLiveBridgeStatus() {
1088
+ return liveBridgeStatus(readBridgeStatus(), isBridgeProcess);
1089
+ }
1090
+
1067
1091
  function readBridgeLock() {
1068
1092
  return readJsonSafe(resolveBridgeLockPath()) || {};
1069
1093
  }
@@ -1360,7 +1384,7 @@ function loadGatewayDeviceIdentity() {
1360
1384
  // to OpenClaw with the owner's own token and device identity, so anything else (config, exec
1361
1385
  // approvals, cron, other sessions' history) never passes, whoever holds an app session.
1362
1386
  // `trusted` frames are the bridge's own (the /model translator's models.list / sessions.patch).
1363
- const CLIENT_GATEWAY_METHODS = new Set(['chat.send', 'chat.history', 'chat.abort', 'oomi.models.list', 'oomi.models.set']);
1387
+ const CLIENT_GATEWAY_METHODS = new Set(['chat.send', 'chat.history', 'chat.abort', 'oomi.models.list', 'oomi.models.set', 'oomi.chat.steer']);
1364
1388
 
1365
1389
  function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}) {
1366
1390
  const connectNonce = typeof options.connectNonce === 'string' ? options.connectNonce.trim() : '';
@@ -1629,7 +1653,8 @@ function shouldSuppressOomiVisibleText(value) {
1629
1653
  // (a call's "they're calling you, pick up" cue): never the person's words on any screen.
1630
1654
  const OOMI_CUE_PREFIX = '[oomi:cue:';
1631
1655
  // What this bridge does for oomi, said on each connect (the backend greets a call only through
1632
- // a bridge that keeps the cue out of the conversation).
1656
+ // a bridge that keeps the cue out of the conversation). `computer.windows.v1` is added per
1657
+ // computer, when its window helper is installed and verified (lib/windowHost.js).
1633
1658
  const OOMI_BRIDGE_CAPABILITIES = ['call.greeting.v1', 'call.language.v1'];
1634
1659
 
1635
1660
  function sanitizeGatewayMessageForOomi(message) {
@@ -2277,6 +2302,23 @@ function classifyBridgeFailure({ err, reason = '', code = '', forceClass = '' }
2277
2302
  };
2278
2303
  }
2279
2304
 
2305
+ // ActionCable uses disconnect for both planned restarts and refused credentials.
2306
+ // An explicit reconnect flag wins; older servers without one retry non-auth notices.
2307
+ function classifyBrokerDisconnect(payload = {}) {
2308
+ const reason = String(payload.reason || 'broker requested disconnect');
2309
+ const authFailure = /unauthorized|forbidden|invalid.?token|token.?expired/i.test(reason);
2310
+ const retryable = payload.reconnect === true || (payload.reconnect !== false && !authFailure);
2311
+ return {
2312
+ errorCode: retryable ? 'BROKER_DISCONNECT_RETRY' : 'BROKER_DISCONNECT_STOP',
2313
+ message: reason,
2314
+ failureClass: retryable ? 'network' : authFailure ? 'auth_rejected' : 'broker_disconnect_terminal',
2315
+ retryable,
2316
+ hint: retryable ? 'Broker requested a reconnect; retrying with backoff.'
2317
+ : 'Broker refused reconnect. Check the connection with its owner before re-pairing.',
2318
+ baseDelayMs: BRIDGE_RECONNECT_BASE_MS,
2319
+ };
2320
+ }
2321
+
2280
2322
  function computeReconnectDelayMs(attempt, baseDelayMs) {
2281
2323
  const growth = Math.min(BRIDGE_RECONNECT_MAX_MS, Math.round(baseDelayMs * (2 ** Math.max(0, attempt - 1))));
2282
2324
  const jitter = Math.floor(growth * (Math.random() * 0.25));
@@ -2337,6 +2379,22 @@ async function runBridgePreflight({ brokerWs, gatewayUrl, gatewayConfigPath }) {
2337
2379
  await assertTcpReachable(parsedGatewayUrl.toString());
2338
2380
  }
2339
2381
 
2382
+ // The broker connection is alive only while frames arrive: ActionCable pings every 3 s and answers
2383
+ // websocket pings. A socket left open by sleep, a network change or a stalled proxy is ended so
2384
+ // the bridge reconnects, instead of looking connected for the minutes TCP takes to give up.
2385
+ const BROKER_HANDSHAKE_TIMEOUT_MS = 15000;
2386
+ // OOMI_BROKER_SILENCE_MS shortens it for tests.
2387
+ const BROKER_SILENCE_MS = Number(process.env.OOMI_BROKER_SILENCE_MS) > 0 ? Number(process.env.OOMI_BROKER_SILENCE_MS) : 30000;
2388
+ const BROKER_LIVENESS_CHECK_MS = Math.min(5000, Math.max(100, Math.floor(BROKER_SILENCE_MS / 3)));
2389
+
2390
+ /** Whether a broker socket has been silent too long to be trusted (the clock may have jumped across a sleep). */
2391
+ function brokerSocketSilent(lastFrameAt, now = Date.now(), silenceMs = BROKER_SILENCE_MS) {
2392
+ return now - lastFrameAt > silenceMs;
2393
+ }
2394
+
2395
+ // A device token handed to a detached bridge: only this user can read a process's environment.
2396
+ const BRIDGE_HANDOFF_TOKEN = 'OOMI_BRIDGE_HANDOFF_TOKEN';
2397
+
2340
2398
  function buildBridgeDetachArgs(rawFlags = {}) {
2341
2399
  const orderedKeys = [
2342
2400
  'broker-http',
@@ -2344,8 +2402,9 @@ function buildBridgeDetachArgs(rawFlags = {}) {
2344
2402
  'pair-code',
2345
2403
  'app-url',
2346
2404
  'device-id',
2347
- 'device-token',
2348
2405
  ];
2406
+ // Never the device token: a long-lived process's arguments are readable by every user of the
2407
+ // computer (ps). startBridgeDetachedProcess hands it over in the environment instead.
2349
2408
  const args = [process.argv[1], 'openclaw', 'bridge'];
2350
2409
  if (bridgeConnectionName) args.push('--connection', bridgeConnectionName);
2351
2410
 
@@ -2382,9 +2441,13 @@ function startBridgeDetachedProcess(rawFlags = {}) {
2382
2441
  ensureDir(path.dirname(logPath));
2383
2442
  fs.appendFileSync(logPath, `[${new Date().toISOString()}] [bridge-supervisor] starting detached bridge\n`);
2384
2443
  const logFd = fs.openSync(logPath, 'a');
2444
+ const env = { ...process.env };
2445
+ const handedToken = String(rawFlags['device-token'] || '').trim();
2446
+ if (handedToken) env[BRIDGE_HANDOFF_TOKEN] = handedToken; else delete env[BRIDGE_HANDOFF_TOKEN];
2385
2447
  const child = spawn(process.execPath, args, {
2386
2448
  detached: true,
2387
2449
  stdio: ['ignore', logFd, logFd],
2450
+ env,
2388
2451
  });
2389
2452
  child.unref();
2390
2453
  try {
@@ -2544,7 +2607,10 @@ async function startOpenclawBridge(flags) {
2544
2607
  const brokerWs = runtimeConfig.brokerWs;
2545
2608
  const deviceId = resolveDeviceId(flags, bridgeState);
2546
2609
  const pairCode = String(flags['pair-code'] || '').trim().toUpperCase();
2547
- const explicitDeviceToken = String(flags['device-token'] || '').trim();
2610
+ const handedToken = String(process.env[BRIDGE_HANDOFF_TOKEN] || '').trim();
2611
+ // Read once and dropped, so the agents this bridge starts never inherit it.
2612
+ delete process.env[BRIDGE_HANDOFF_TOKEN];
2613
+ const explicitDeviceToken = String(flags['device-token'] || handedToken).trim();
2548
2614
  const releaseBridgeLock = acquireBridgeLock(deviceId);
2549
2615
  let deviceToken = explicitDeviceToken;
2550
2616
  if (!deviceToken && String(bridgeState.deviceId || '').trim() === deviceId) {
@@ -2645,6 +2711,8 @@ async function startOpenclawBridge(flags) {
2645
2711
  lastErrorMessage: '',
2646
2712
  consecutiveFailures: 0,
2647
2713
  pid: process.pid,
2714
+ // How an earlier process stopped says nothing about this one.
2715
+ stopSignal: null,
2648
2716
  startedAt: bridgeNowIso(),
2649
2717
  packageVersion: currentPackageVersion(),
2650
2718
  maintenanceProtocol: 1,
@@ -2702,10 +2770,12 @@ async function startOpenclawBridge(flags) {
2702
2770
  const activeGatewaySockets = new Map();
2703
2771
  const activeGatewayRuns = createGatewayRuns();
2704
2772
  let currentBrokerSocket;
2773
+ let windowHost;
2705
2774
  const maintenanceTick = createMaintenanceController({
2706
2775
  directory: path.dirname(resolveBridgeStatePath()),
2776
+ // A headset watching this computer's windows also holds a restart for an update.
2707
2777
  isIdle: () => !backgroundTurns && !localRuntime?.active.size && !localRuntime?.deliveries && !activeGatewayRuns.size
2708
- && !currentBrokerSocket?.bufferedAmount
2778
+ && !currentBrokerSocket?.bufferedAmount && !windowHost?.sessions.size
2709
2779
  && [...activeGatewaySockets.values()].every((session) => !session.pendingRequests?.size),
2710
2780
  isConnected: () => readBridgeStatus().status === 'connected',
2711
2781
  restart: () => currentBridgeService().restart(),
@@ -2840,6 +2910,22 @@ async function startOpenclawBridge(flags) {
2840
2910
  }
2841
2911
  const stopComputerTurns = localRuntime ? localRuntime.watchComputerTurns() : () => {};
2842
2912
 
2913
+ // computer.windows.v1: this computer's app windows on the person's headset. The bridge answers
2914
+ // oomi.windows.* itself and runs the window helper only while a headset watches (lib/windowHost.js).
2915
+ windowHost = createWindowHost({
2916
+ connection: bridgeConnectionName,
2917
+ deviceId,
2918
+ send: (sessionId, frame) => {
2919
+ if (currentBrokerSocket?.readyState !== WebSocket.OPEN) return false;
2920
+ sendBrokerPayload(currentBrokerSocket, { action: 'gateway_frame', type: 'gateway.frame', sessionId, frame });
2921
+ return true;
2922
+ },
2923
+ iceServers: createIceServerSource({ brokerHttp, deviceId, deviceToken, log: (message) => bridgeDebugLog(`[windows] ${message}`) }),
2924
+ log: (message) => bridgeDebugLog(message),
2925
+ warn: (message) => console.warn(message),
2926
+ });
2927
+ windowHost.recoverAudio().catch(() => {});
2928
+
2843
2929
  const sendGatewayAck = (brokerSocket, {
2844
2930
  sessionId,
2845
2931
  requestId = '',
@@ -3033,6 +3119,7 @@ async function startOpenclawBridge(flags) {
3033
3119
  return {
3034
3120
  type: 'broker.disconnect',
3035
3121
  reason: String(payload.reason || ''),
3122
+ reconnect: payload.reconnect,
3036
3123
  };
3037
3124
  }
3038
3125
  if (payload.type === 'reject_subscription') {
@@ -3084,9 +3171,12 @@ async function startOpenclawBridge(flags) {
3084
3171
  const wsUrl = new URL(brokerWs);
3085
3172
  wsUrl.searchParams.set('token', deviceToken);
3086
3173
 
3087
- const brokerSocket = new WebSocket(wsUrl.toString());
3174
+ const brokerSocket = new WebSocket(wsUrl.toString(), { handshakeTimeout: BROKER_HANDSHAKE_TIMEOUT_MS });
3088
3175
  currentBrokerSocket = brokerSocket;
3089
3176
  let actionCableHeartbeat = null;
3177
+ let livenessTimer = null;
3178
+ let lastBrokerFrameAt = Date.now();
3179
+ const brokerFrameArrived = () => { lastBrokerFrameAt = Date.now(); };
3090
3180
 
3091
3181
  const clearChallengeTimer = (sessionBridge) => {
3092
3182
  if (sessionBridge && sessionBridge.connectChallengeTimer) {
@@ -3481,7 +3571,7 @@ async function startOpenclawBridge(flags) {
3481
3571
  }
3482
3572
 
3483
3573
  if (connectAccepted) {
3484
- frame = annotateConnectResponseForOomi(frame, { runtime: bridgeRuntimeName, version: currentPackageVersion(), extra: localRuntime ? localRuntime.capabilities() : bridgeRuntimeName === 'openclaw' ? [CHAT_MODELS_CAPABILITY] : [] });
3574
+ frame = annotateConnectResponseForOomi(frame, { runtime: bridgeRuntimeName, version: currentPackageVersion(), extra: [...(localRuntime ? localRuntime.capabilities() : bridgeRuntimeName === 'openclaw' ? [CHAT_MODELS_CAPABILITY] : []), ...windowHost.capabilities()] });
3485
3575
  }
3486
3576
  sendBrokerPayload(brokerSocket, { action: 'gateway_frame', type: 'gateway.frame', sessionId, frame });
3487
3577
  }, (error) => {
@@ -3575,6 +3665,20 @@ async function startOpenclawBridge(flags) {
3575
3665
 
3576
3666
  brokerSocket.on('open', () => {
3577
3667
  bridgeDebugLog('[bridge] Connected to managed broker.');
3668
+ // A new socket: its device channel isn't confirmed until the broker says so on it.
3669
+ deviceChannelSubscribed = false;
3670
+ brokerFrameArrived();
3671
+ livenessTimer = setInterval(() => {
3672
+ if (brokerSocket.readyState !== WebSocket.OPEN) return;
3673
+ if (brokerSocketSilent(lastBrokerFrameAt)) {
3674
+ bridgeDebugLog(`[bridge] Nothing from the broker for ${Math.round((Date.now() - lastBrokerFrameAt) / 1000)} s; reconnecting.`);
3675
+ incrementBridgeMetric('bridge_broker_silent_count');
3676
+ brokerSocket.terminate();
3677
+ return;
3678
+ }
3679
+ try { brokerSocket.ping(); } catch { /* Closing. */ }
3680
+ }, BROKER_LIVENESS_CHECK_MS);
3681
+ livenessTimer.unref?.();
3578
3682
  conversationChangesReady = false;
3579
3683
  reconnectState.attempt = 0;
3580
3684
  reconnectState.lastFailure = null;
@@ -3608,7 +3712,9 @@ async function startOpenclawBridge(flags) {
3608
3712
  });
3609
3713
  });
3610
3714
 
3715
+ brokerSocket.on('pong', brokerFrameArrived);
3611
3716
  brokerSocket.on('message', runBridgeCallbackSafely((rawData) => {
3717
+ brokerFrameArrived();
3612
3718
  const text = typeof rawData === 'string' ? rawData : rawData.toString();
3613
3719
  const payload = parseBrokerEnvelope(text);
3614
3720
  if (!payload || typeof payload.type !== 'string') return;
@@ -3617,6 +3723,7 @@ async function startOpenclawBridge(flags) {
3617
3723
  deviceChannelSubscribed = true;
3618
3724
  conversationChangesReady = true;
3619
3725
  flushConversationChanges();
3726
+ windowHost.signalingRestored();
3620
3727
  updateBridgeStatus({
3621
3728
  status: 'connected',
3622
3729
  deviceId,
@@ -3635,11 +3742,37 @@ async function startOpenclawBridge(flags) {
3635
3742
  }
3636
3743
 
3637
3744
  if (payload.type === 'broker.disconnect') {
3638
- reconnectState.lastFailure = classifyBridgeFailure({
3639
- reason: String(payload.reason || 'unauthorized'),
3640
- forceClass: 'auth_rejected',
3641
- });
3745
+ // ActionCable sends this notice for a planned restart too (audit C3/R6). That one reconnects
3746
+ // with backoff in this same process; only a refusal (an auth failure, or reconnect:false) stops it.
3747
+ const disconnect = classifyBrokerDisconnect(payload);
3748
+ if (disconnect.retryable) {
3749
+ reconnectState.lastFailure = disconnect;
3750
+ console.error(`[bridge] ${disconnect.hint}`);
3751
+ updateBridgeStatus({
3752
+ status: 'reconnecting',
3753
+ deviceId,
3754
+ brokerWs,
3755
+ brokerHttp,
3756
+ gatewayUrl: gateway.gatewayUrl,
3757
+ lastDisconnectAt: bridgeNowIso(),
3758
+ lastErrorCode: disconnect.errorCode,
3759
+ lastErrorClass: disconnect.failureClass,
3760
+ lastErrorMessage: disconnect.message,
3761
+ hint: disconnect.hint,
3762
+ consecutiveFailures: reconnectState.attempt + 1,
3763
+ pid: process.pid,
3764
+ });
3765
+ try {
3766
+ brokerSocket.close(1012, 'broker_restart');
3767
+ } catch {
3768
+ // The close handler schedules the reconnect either way.
3769
+ }
3770
+ return;
3771
+ }
3772
+ reconnectState.lastFailure = disconnect;
3642
3773
  reconnectState.stopped = true;
3774
+ // oomi refused this computer (a revoked link or token): no window session outlives that.
3775
+ windowHost.revoked('revoked').catch(() => {});
3643
3776
  console.error(`[bridge] Broker rejected connection: ${String(payload.reason || 'unauthorized')}`);
3644
3777
  console.error(`[bridge] ${reconnectState.lastFailure.hint}`);
3645
3778
  updateBridgeStatus({
@@ -3666,6 +3799,7 @@ async function startOpenclawBridge(flags) {
3666
3799
 
3667
3800
  if (payload.type === 'broker.reject_subscription') {
3668
3801
  console.error('[bridge] Broker rejected DeviceChannel subscription.');
3802
+ windowHost.revoked('revoked').catch(() => {});
3669
3803
  reconnectState.lastFailure = classifyBridgeFailure({
3670
3804
  reason: 'broker rejected DeviceChannel subscription',
3671
3805
  forceClass: 'auth_rejected',
@@ -3717,6 +3851,12 @@ async function startOpenclawBridge(flags) {
3717
3851
  const sessionId = String(payload.sessionId || '').trim();
3718
3852
  let frame = typeof payload.frame === 'string' ? payload.frame : '';
3719
3853
  if (!sessionId || !frame) return;
3854
+ // computer.windows.v1 is answered here, like `/model` below; it never reaches the agent.
3855
+ if (windowHost.handles(frame)) {
3856
+ bridgeDebugLog(`[bridge] client.frame ${sessionId} windows`);
3857
+ windowHost.handleClientFrame(sessionId, frame).catch((error) => reportBridgeRuntimeFault({ phase: 'windows.frame', sessionId, error }));
3858
+ return;
3859
+ }
3720
3860
  if (classifyBridgeSessionScope(sessionId) === 'voice') {
3721
3861
  bridgeDebugLog(`[bridge] client.frame ${sessionId} ${JSON.stringify(summarizeVoiceFrameContract(frame))}`);
3722
3862
  } else {
@@ -3886,6 +4026,8 @@ async function startOpenclawBridge(flags) {
3886
4026
  if (payload.type === 'client.close') {
3887
4027
  const sessionId = String(payload.sessionId || '').trim();
3888
4028
  bridgeDebugLog(`[bridge] client.close ${sessionId}`);
4029
+ // A headset's window session waits the resume grace for it to come back.
4030
+ windowHost.clientClosed(sessionId);
3889
4031
  const sessionBridge = activeGatewaySockets.get(sessionId);
3890
4032
  if (sessionBridge && sessionBridge.socket) {
3891
4033
  clearChallengeTimer(sessionBridge);
@@ -3904,10 +4046,17 @@ async function startOpenclawBridge(flags) {
3904
4046
 
3905
4047
  brokerSocket.on('close', runBridgeCallbackSafely((code, reason) => {
3906
4048
  conversationChangesReady = false;
4049
+ // Windows keep streaming while oomi is out of reach, for 10 minutes at most.
4050
+ windowHost.signalingLost();
3907
4051
  if (actionCableHeartbeat) {
3908
4052
  clearInterval(actionCableHeartbeat);
3909
4053
  actionCableHeartbeat = null;
3910
4054
  }
4055
+ if (livenessTimer) {
4056
+ clearInterval(livenessTimer);
4057
+ livenessTimer = null;
4058
+ }
4059
+ deviceChannelSubscribed = false;
3911
4060
  const reasonText = reason ? reason.toString() : '';
3912
4061
  bridgeDebugLog(`[bridge] Broker disconnected (${code}) ${reasonText}`);
3913
4062
  incrementBridgeMetric('bridge_disconnect_count');
@@ -3960,6 +4109,7 @@ async function startOpenclawBridge(flags) {
3960
4109
  stopRoutineWorker();
3961
4110
  agentChannelWorker.stop();
3962
4111
  stopUpdateWatcher();
4112
+ await Promise.race([windowHost.stop('bridge_stopped'), new Promise((resolve) => setTimeout(resolve, 3000))]);
3963
4113
  if (localRuntime) { await localRuntime.queue; localRuntime.close(); }
3964
4114
  if (reconnectState.timer) {
3965
4115
  clearTimeout(reconnectState.timer);
@@ -4174,8 +4324,8 @@ async function createOpenclawInviteLink(flags) {
4174
4324
 
4175
4325
  function printOpenclawBridgeStatus(flags) {
4176
4326
  const bridgeState = readBridgeState();
4177
- const runtimeStatus = readBridgeStatus();
4178
- if (runtimeStatus.pid && !isBridgeProcess(runtimeStatus.pid)) { runtimeStatus.status = 'stopped'; runtimeStatus.runtimeReady = false; }
4327
+ const runtimeStatus = readLiveBridgeStatus();
4328
+ const named = bridgeConnectionName ? ` --name ${bridgeConnectionName}` : '';
4179
4329
  const jsonOutput = isTruthyFlag(flags.json);
4180
4330
  const redactToken = (value) => {
4181
4331
  const text = String(value || '').trim();
@@ -4208,8 +4358,19 @@ function printOpenclawBridgeStatus(flags) {
4208
4358
  if (payload.maintenance) console.log(`Maintenance: ${payload.maintenance.status} — ${payload.maintenance.message || ''}`);
4209
4359
  console.log('Oomi Bridge Status');
4210
4360
  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 : ''}`);
4361
+ if (supervision?.missingProgram?.length) {
4362
+ console.log(`Automatic startup is broken: it starts ${supervision.missingProgram.join(' and ')}, which no longer exists (an upgrade removed it). Fix: oomi bridge repair${named}`);
4363
+ }
4364
+ if (supervision.manager === 'windows-logon') {
4365
+ // Two separate promises on Windows: the supervisor restarts the worker while the person stays
4366
+ // signed in, and the Run key starts the supervisor at the next sign-in. Say which ones hold.
4367
+ console.log(`Worker recovery: ${supervision.enabled && supervision.loaded ? 'on' : 'off'} while you are signed in to Windows.`);
4368
+ console.log(supervision.enabled && supervision.startsAfterHostRestart ? 'Automatic startup: at Windows sign-in.'
4369
+ : `Automatic startup: off at Windows sign-in.${supervision.enabled ? ` To turn it on: oomi bridge service start${named} --sign-in` : ''}`);
4370
+ } else {
4371
+ 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'}`);
4372
+ }
4373
+ if (!supervision.installed || !supervision.enabled || !supervision.running) console.log(`Repair on this computer: oomi bridge repair${named}`);
4213
4374
  if (supervision.reason) console.log(supervision.reason);
4214
4375
  console.log('------------------');
4215
4376
  console.log(`Bridge state: ${payload.bridgeStatePath}`);
@@ -4222,6 +4383,15 @@ function printOpenclawBridgeStatus(flags) {
4222
4383
  }
4223
4384
  if (payload.runtime && typeof payload.runtime === 'object' && Object.keys(payload.runtime).length > 0) {
4224
4385
  console.log(`Bridge state: ${String(payload.runtime.status || 'unknown')}`);
4386
+ if (payload.runtime.unrecordedExit) {
4387
+ 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.`);
4388
+ }
4389
+ // A paired computer that no account has claimed connects fine, but no one can call or message it.
4390
+ if (/not linked/i.test(String(payload.runtime.agentChannelError || ''))) {
4391
+ 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.`);
4392
+ } else if (payload.runtime.agentChannelError) {
4393
+ console.log(`Chat links: ${payload.runtime.agentChannelError}`);
4394
+ }
4225
4395
  console.log(`Agent runtime: ${bridgeState.runtime || 'openclaw'}${bridgeState.localAgent?.profile ? ` (profile ${bridgeState.localAgent.profile})` : ''}`);
4226
4396
  console.log(`Local reply verified: ${payload.runtime.runtimeReady ? 'yes' : 'no'}${payload.runtime.verifiedAt ? ` at ${payload.runtime.verifiedAt}` : ''}`);
4227
4397
  if (payload.runtime.lastConnectedAt) {
@@ -4338,7 +4508,8 @@ function listLocalBridgeConnections() {
4338
4508
  const state = readBridgeState();
4339
4509
  const running = findRunningBridgeProcess();
4340
4510
  return { name: name || null, runtime: state.runtime || 'openclaw', deviceId: state.deviceId || null,
4341
- running: Boolean(running), supervision: currentBridgeService().status(),
4511
+ running: Boolean(running), status: liveBridgeStatus(readBridgeStatus(), (pid) => pid === running?.pid || isBridgeProcess(pid)).status || null,
4512
+ supervision: currentBridgeService().status(),
4342
4513
  repairCommand: `oomi bridge repair${name ? ' --name ' + name : ''}` };
4343
4514
  });
4344
4515
  } finally { bridgeConnectionName = selected; }
@@ -4357,9 +4528,20 @@ function assertIndependentMaintenance() {
4357
4528
 
4358
4529
  function deferLiveRestart({ print = true } = {}) {
4359
4530
  const status = readBridgeStatus();
4360
- const service = currentBridgeService().status();
4531
+ const manager = currentBridgeService();
4532
+ const service = manager.status();
4361
4533
  if (status.maintenanceProtocol !== 1 || !status.pid || !isBridgeProcess(status.pid)
4362
4534
  || !service.running || service.pid !== status.pid || !service.enabled) return false;
4535
+ // The running worker restarts itself with its own (perhaps older) code, so a definition this
4536
+ // version renders differently (a stable Node path, a newer template) is written here first.
4537
+ // systemd reloads it for that restart; launchd keeps its loaded copy, so it loads it again instead.
4538
+ const definition = manager.refreshDefinition ? manager.refreshDefinition() : { changed: false };
4539
+ if (definition.changed && manager.reloadDetached && process.platform === 'darwin') {
4540
+ manager.reloadDetached();
4541
+ const reloading = { status: 'reloading', reason: 'service_definition_changed', message: 'The service definition changed; launchd loads it again in a moment. Check with: oomi status' };
4542
+ if (print) console.log(JSON.stringify(reloading, null, 2));
4543
+ return reloading;
4544
+ }
4363
4545
  const request = queueRestart(path.dirname(resolveBridgeStatePath()), status.pid);
4364
4546
  if (print) console.log(JSON.stringify(request, null, 2));
4365
4547
  return request;
@@ -4387,15 +4569,17 @@ async function handleBridgeServiceCommand(actionRaw = '', flags = {}) {
4387
4569
  if (['install', 'start', 'restart'].includes(action)) requireSavedBridge();
4388
4570
  if (['install', 'restart'].includes(action) && !isTruthyFlag(flags['no-start']) && deferLiveRestart()) return;
4389
4571
  if (action !== 'start') assertIndependentMaintenance();
4572
+ const signIn = signInChoice(flags);
4573
+ let started;
4390
4574
  if (action === 'install') {
4391
- service.install({ noStart: true });
4575
+ service.install({ noStart: true, signIn });
4392
4576
  await stopSupervisedBridge(service);
4393
- if (!isTruthyFlag(flags['no-start'])) service.start();
4577
+ if (!isTruthyFlag(flags['no-start'])) started = service.start({ signIn });
4394
4578
  } else if (action === 'start') {
4395
- service.start(); // Idempotent: do not interrupt a healthy worker.
4579
+ started = service.start({ signIn }); // Idempotent: do not interrupt a healthy worker.
4396
4580
  } else if (action === 'restart') {
4397
4581
  await stopSupervisedBridge(service);
4398
- service.start({ rewrite: true });
4582
+ started = service.start({ rewrite: true, signIn });
4399
4583
  incrementBridgeMetric('bridge_restart_count');
4400
4584
  } else if (action === 'stop') {
4401
4585
  await stopSupervisedBridge(service);
@@ -4404,7 +4588,35 @@ async function handleBridgeServiceCommand(actionRaw = '', flags = {}) {
4404
4588
  service.uninstall();
4405
4589
  }
4406
4590
  const result = service.status();
4407
- console.log(JSON.stringify({ action, ...result }, null, 2));
4591
+ console.log(JSON.stringify({ action, ...result, ...(started?.signInError ? { signInError: started.signInError } : {}) }, null, 2));
4592
+ }
4593
+
4594
+ // Windows: --sign-in or --no-sign-in records whether the connection's supervisor also starts at
4595
+ // Windows sign-in (the person's Run key). Without either flag the saved choice stands (default on).
4596
+ function signInChoice(flags = {}) {
4597
+ if (isTruthyFlag(flags['no-sign-in'])) return false;
4598
+ if (isTruthyFlag(flags['sign-in'])) return true;
4599
+ return undefined;
4600
+ }
4601
+
4602
+ // What will bring this connection's bridge back, as its service reports it rather than as hoped.
4603
+ function describeSupervision(service, started = null) {
4604
+ const status = service.status();
4605
+ 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.';
4606
+ if (status.manager === 'systemd' && status.persistsWithoutLogin === false) {
4607
+ // Without lingering, systemd ends a user's services when their last session closes (an SSH
4608
+ // logout on a headless machine) and starts them only once they log in again.
4609
+ return 'Automatic startup: Linux user service, only while you are logged in; restarts after worker exits. To keep it running after logout and start it at boot: loginctl enable-linger $USER';
4610
+ }
4611
+ if (status.manager !== 'windows-logon') return `Automatic startup: ${service.config.platform === 'darwin' ? 'macOS login service' : 'Linux user service'}; restarts after worker exits.`;
4612
+ const named = bridgeConnectionName ? ` --name ${bridgeConnectionName}` : '';
4613
+ const why = started?.signInError ? ` (${started.signInError})` : status.signIn === false ? ' (--no-sign-in)' : '';
4614
+ return [
4615
+ 'Worker recovery: on while you are signed in to Windows; the bridge restarts after its worker exits.',
4616
+ 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`,
4617
+ // processSupervisor.js: a supervisor started by a command lives in the job of the program that ran it.
4618
+ "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.",
4619
+ ].join('\n');
4408
4620
  }
4409
4621
 
4410
4622
  async function repairBridge(flags = {}) {
@@ -4413,7 +4625,10 @@ async function repairBridge(flags = {}) {
4413
4625
  await handleBridgeServiceCommand('install', flags);
4414
4626
  if (!isTruthyFlag(flags['no-start'])) {
4415
4627
  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.');
4628
+ const service = currentBridgeService();
4629
+ if (service.status().manager === 'windows-logon') console.log(`Oomi bridge restored. Pairing and conversations preserved.\n${describeSupervision(service)}`);
4630
+ 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. Pairing and conversations preserved.
4631
+ ${describeSupervision(service)}`);
4417
4632
  }
4418
4633
  }
4419
4634
 
@@ -4439,8 +4654,9 @@ async function startBridgeLifecycle(flags = {}) {
4439
4654
  const service = currentBridgeService();
4440
4655
  if (service.status().installed) {
4441
4656
  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();
4657
+ const started = service.start({ signIn: signInChoice(flags) });
4443
4658
  console.log(`Bridge service started: ${service.config.target}`);
4659
+ if (started?.signInError) console.warn(`Windows sign-in startup was not set: ${started.signInError}`);
4444
4660
  return;
4445
4661
  }
4446
4662
  }
@@ -4564,10 +4780,16 @@ async function verifyLocalAgent(state) {
4564
4780
  if (state.openclawHome) process.env.OPENCLAW_HOME = state.openclawHome;
4565
4781
  let result;
4566
4782
  if (state.localAgent) {
4567
- const reply = await runLocalAgent(state.localAgent, {
4568
- sessionKey: `oomi:verify:${randomUUID()}`, idempotencyKey: randomUUID(), history: [],
4569
- message: state.runtime === 'grokbot' ? 'Oomi connection check.' : 'Oomi connection check. Reply with OOMI_OK only. Do not use tools or change anything.',
4570
- });
4783
+ let reply;
4784
+ try {
4785
+ reply = await runLocalAgent(state.localAgent, {
4786
+ sessionKey: `oomi:verify:${randomUUID()}`, idempotencyKey: randomUUID(), history: [],
4787
+ message: state.runtime === 'grokbot' ? 'Oomi connection check.' : 'Oomi connection check. Reply with OOMI_OK only. Do not use tools or change anything.',
4788
+ });
4789
+ } finally {
4790
+ // The check's warm Hermes ACP process holds this command open; the bridge starts its own.
4791
+ closeHermesAcpClients();
4792
+ }
4571
4793
  if (state.runtime === 'grokbot' && reply.text.trim() !== 'OOMI_OK') throw new Error('Grok Bot did not return the expected verification response. No Auth Link was created.');
4572
4794
  result = { verifiedAt: new Date().toISOString() };
4573
4795
  } else {
@@ -4587,6 +4809,7 @@ function refreshSelectedSkill(state, flags = {}) {
4587
4809
  async function connectLocalAgent(flags) {
4588
4810
  assertIndependentMaintenance();
4589
4811
  const agentName = flags['agent-name'] === undefined ? undefined : validateAgentName(flags['agent-name']);
4812
+ const pairCode = flags.pair === undefined ? '' : parsePairCode(flags.pair);
4590
4813
  const runtime = String(flags.runtime || '');
4591
4814
  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
4815
  const service = currentBridgeService(runtime);
@@ -4623,10 +4846,29 @@ async function connectLocalAgent(flags) {
4623
4846
  const identity = ({ hermesTransport, ...rest } = {}) => JSON.stringify(rest);
4624
4847
  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
4848
  }
4849
+ // A pairing code from the person's prompt: say hello first, so their waiting screen moves.
4850
+ let pairing = null;
4851
+ if (pairCode) {
4852
+ if (!state.brokerHttp) {
4853
+ const config = await fetchManagedGatewayConfig({ appUrl });
4854
+ state.brokerHttp = rewriteLoopbackBrokerUrlForAppHost(config.brokerHttpUrl, appUrl);
4855
+ state.brokerWs = rewriteLoopbackBrokerUrlForAppHost(config.brokerDeviceWsUrl, appUrl);
4856
+ }
4857
+ pairing = await pairHello({ backendHttp: state.brokerHttp, code: pairCode });
4858
+ }
4626
4859
  if (!previous.verifiedAt || isTruthyFlag(flags.verify)) {
4627
4860
  console.log(`Verifying ${runtime}${state.localAgent?.profile ? ` profile ${state.localAgent.profile}` : ''} with a local test message...`);
4628
4861
  try {
4629
- const verified = await verifyLocalAgent(state);
4862
+ let verified;
4863
+ try { verified = await verifyLocalAgent(state); }
4864
+ catch (err) {
4865
+ // Some Hermes installs never answer over ACP. Unless the person chose the transport, the
4866
+ // quiet CLI gets one try, and the connection keeps it so later turns don't wait on ACP again.
4867
+ if (!hermesCliFallbackApplies(state.localAgent, err)) throw err;
4868
+ console.log("Hermes didn't answer over its streaming connection; using its command line for this connection.");
4869
+ state.localAgent = { ...state.localAgent, hermesTransport: 'cli' };
4870
+ verified = await verifyLocalAgent(state);
4871
+ }
4630
4872
  state.verifiedAt = verified.verifiedAt;
4631
4873
  } catch (err) {
4632
4874
  const explained = explainVerificationFailure(err);
@@ -4637,6 +4879,7 @@ async function connectLocalAgent(flags) {
4637
4879
  console.log(`Reusing the verified ${runtime} runtime. No model test message sent. Use oomi verify for an explicit paid-model probe.`);
4638
4880
  }
4639
4881
  writeBridgeState(state); // Keep successful verification even if pairing later needs a retry.
4882
+ if (pairing && !pairing.ok) console.log(`${pairing.message} Connecting anyway; you'll get an Auth Link to send to your person instead.`);
4640
4883
  if (!state.deviceToken) {
4641
4884
  const config = await fetchManagedGatewayConfig({ appUrl });
4642
4885
  state.brokerHttp = rewriteLoopbackBrokerUrlForAppHost(config.brokerHttpUrl, appUrl);
@@ -4657,23 +4900,43 @@ async function connectLocalAgent(flags) {
4657
4900
  console.warn('This Oomi server does not support agent settings yet. Connecting without shared settings.');
4658
4901
  }
4659
4902
  // Install/update only this connection's supervisor, retaining its saved identity and session.
4660
- if (!unmanaged) service.install({ noStart: true });
4903
+ if (!unmanaged) service.install({ noStart: true, signIn: signInChoice(flags) });
4661
4904
  const stopped = unmanaged ? await stopBridgeProcesses() : await stopSupervisedBridge(service);
4662
4905
  if (stopped.stillAlive?.length) throw new Error('The existing bridge did not stop. Resolve it before reconnecting.');
4663
4906
  writeBridgeState(state);
4664
4907
  updateBridgeStatus({ status: 'starting', runtime, runtimeReady: true, verifiedAt: state.verifiedAt, lastErrorMessage: '' });
4665
- const child = unmanaged ? startBridgeDetachedProcess({ 'app-url': appUrl }) : (service.start(), {});
4908
+ const started = unmanaged ? null : service.start({ signIn: signInChoice(flags) });
4909
+ const child = unmanaged ? startBridgeDetachedProcess({ 'app-url': appUrl }) : {};
4666
4910
  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.`);
4911
+ console.log(unmanaged ? 'Automatic startup: off (--no-service); your host supervisor must manage recovery.' : describeSupervision(service, started));
4670
4912
  const invite = await requestConnectInviteLink({ backendHttp: state.brokerHttp, appUrl, sessionKey: state.sessionKey, deviceToken: state.deviceToken });
4671
4913
  refreshSelectedSkill(state, flags);
4914
+ const ready = { status: 'ready', runtime, agentId: state.localAgent?.agentId, verifiedAt: state.verifiedAt, inviteUrl: invite.inviteUrl };
4915
+ if (pairing?.ok) {
4916
+ // Ask to join: the Auth Link goes to oomi against the code, and the person says yes there.
4917
+ const asked = await pairAnswer({ backendHttp: state.brokerHttp, code: pairCode, inviteUrl: invite.inviteUrl, deviceToken: state.deviceToken, computer: String(flags.computer || os.hostname() || '') });
4918
+ if (asked.ok) {
4919
+ console.log(`Verified agent: ${runtime}${state.localAgent?.profile ? ` (${state.localAgent.profile})` : ''}`);
4920
+ // Grok Bot's setup runs in the background; its reply command passes this on without waiting.
4921
+ if (flags['setup-worker']) return { ...ready, pairing: { status: 'answered', code: formatPairCode(pairCode) } };
4922
+ console.log('Asked to join. Waiting for your person to say yes in oomi…');
4923
+ const outcome = await waitForPairApproval({
4924
+ backendHttp: state.brokerHttp, code: pairCode, deviceToken: state.deviceToken,
4925
+ intervalMs: Number(process.env.OOMI_PAIR_POLL_MS) || PAIR_POLL_MS,
4926
+ timeoutMs: Number(process.env.OOMI_PAIR_WAIT_MS) || PAIR_WAIT_MS,
4927
+ });
4928
+ const described = describePairOutcome(outcome);
4929
+ console.log(described.line);
4930
+ if (described.exitCode) process.exitCode = described.exitCode;
4931
+ return { ...ready, pairing: { status: outcome.status } };
4932
+ }
4933
+ console.log(`${asked.message} Send this Auth Link to your person instead.`);
4934
+ }
4672
4935
  console.log(`Verified agent: ${runtime}${state.localAgent?.profile ? ` (${state.localAgent.profile})` : ''}`);
4673
4936
  console.log('Oomi Connect Ready');
4674
4937
  console.log(`Auth Link: ${invite.inviteUrl}`);
4675
4938
  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 };
4939
+ return ready;
4677
4940
  }
4678
4941
 
4679
4942
  async function main() {
@@ -4710,6 +4973,8 @@ async function main() {
4710
4973
  routines: 'oomi routines list; oomi routines context', identity: 'oomi identity get', updates: 'oomi updates',
4711
4974
  agentChannels: { create: 'oomi channel create --purpose TEXT [--expires-minutes N] [--join-minutes N] [--greeting TEXT]', list: 'oomi channel list', show: 'oomi channel show ID [--after SEQ] [--wait SECONDS]', send: 'oomi channel send ID --text TEXT [--wait SECONDS]', end: 'oomi channel end ID [--reason TEXT]', join: 'oomi channel join LINK [--name NAME] [--anonymous]', person: 'oomi channel create --for person --purpose TEXT [--owner-name NAME] [--deny LIST] -> link (web chat, 24h) + watchUrl (owner sign-in)', permissions: 'privateInfo|actions|commands|payments: allow|ask|deny; default ask; agents may only restrict', approval: 'oomi channel request-approval ID --permission NAME --summary TEXT; wait for an Oomi approval notice; guest claims are never approval', noReply: 'reply NO_REPLY to an Oomi notice that needs no guest message', delivery: 'guest messages arrive as separate turns in session agent:main:oomi:channel:ID; your final reply text is sent back', authority: 'guests are outside agents with no owner authority; the owner can read and end every channel' },
4712
4975
  notify: { send: 'oomi notify "<message>" --title TITLE --json', when: 'reminders the user asked for, finished work, time-sensitive news; everything else in chat', skipped: 'tell the user notification.guidance', rateLimited: 'wait retryAfterSeconds' },
4976
+ windows: { status: 'oomi windows status --json', list: 'oomi windows list', check: 'oomi windows check', takeAway: 'oomi windows deny APP | off | stop', turnOn: 'only the person at this computer: oomi windows on APP ... (Windows Hello); tell them the command, never try to pass it' },
4977
+ control: { status: 'oomi control status --json', takeAway: 'oomi control off', turnOn: 'only the person at this computer: oomi control on (Windows Hello); when a click, typing or a key press is refused for want of approval, tell them the command once and stop; never try to pass it or work around the refusal' },
4713
4978
  costs: { passiveEvents: 'no model turn', wakeAgent: 'routine.agentWakeEnabled defaults false; enable only on explicit user request', maximumRoutineWakeAttemptsPerHour: 6, retries: 'uncertain event turns are not automatically rerun', connectionCheck: 'first connect or explicit oomi verify makes one model call; reconnect reuses verification', identity: 'a changed identity revision is delivered once to keep names consistent' }
4714
4979
  }, null, 2)); return;
4715
4980
  }
@@ -4744,7 +5009,8 @@ async function main() {
4744
5009
  console.log(JSON.stringify(receipt));
4745
5010
  if (receipt.verification) {
4746
5011
  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}`);
5012
+ 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."`);
5013
+ else if (setup?.status === 'ready') console.log(`Verified agent: grokbot (${args.flags['agent-id']})\nOomi Connect Ready\nAuth Link: ${setup.inviteUrl}`);
4748
5014
  else if (setup) console.log(JSON.stringify(setup));
4749
5015
  }
4750
5016
  return;
@@ -4757,6 +5023,7 @@ async function main() {
4757
5023
  const directory = connectionDirectory();
4758
5024
  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
5025
  if (!args.flags['setup-worker']) {
5026
+ if (args.flags.pair !== undefined) parsePairCode(args.flags.pair); // Refuse a mistyped code now, not in the background.
4760
5027
  if (!isTruthyFlag(args.flags['no-service'])) currentBridgeService('grokbot').preflight();
4761
5028
  console.log(JSON.stringify(queueConnectionSetup({ directory, agentId: config.agentId, cli: process.argv[1], args: process.argv.slice(2) }), null, 2));
4762
5029
  return;
@@ -4772,6 +5039,8 @@ async function main() {
4772
5039
  }
4773
5040
  return;
4774
5041
  }
5042
+ if (command === 'windows') return handleWindowsCommand(subcommand || 'status', args.flags, args.positionals);
5043
+ if (command === 'control') return handleControlCommand(subcommand || 'status', args.flags, args.positionals);
4775
5044
  if (command === 'identity') return handleIdentityCommand(readBridgeState(), subcommand, args.flags);
4776
5045
  if (command === 'routines') return handleRoutinesCommand(readBridgeState(), subcommand, args.flags, args.positionals);
4777
5046
  if (command === 'verify') {
@@ -4943,6 +5212,8 @@ if (__isDirectExecution) {
4943
5212
 
4944
5213
  export {
4945
5214
  annotateConnectResponseForOomi,
5215
+ brokerSocketSilent,
5216
+ buildBridgeDetachArgs,
4946
5217
  prepareGatewayFrameForLocalGateway,
4947
5218
  sanitizeGatewayFrameForOomiClient,
4948
5219
  sanitizeUserVisibleText,
@@ -4954,6 +5225,7 @@ export {
4954
5225
  handleOpenclawProfileCommand,
4955
5226
  buildBridgeLaunchAgentPlist,
4956
5227
  classifyBridgeFailure,
5228
+ classifyBrokerDisconnect,
4957
5229
  classifyBridgeSessionScope,
4958
5230
  createBridgeProcessFaultHandler,
4959
5231
  computeReconnectDelayMs,