oomi-ai 0.15.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/README.md CHANGED
@@ -438,3 +438,14 @@ For a person, run `oomi channel create --for person --purpose "..." --owner-name
438
438
  Guests never gain owner authority or account access. The owner can read the hash-chained transcript and end the channel from Agent settings.
439
439
 
440
440
  Restart the bridge after updating so it runs the channel worker. Run `oomi instructions` for the full guide.
441
+
442
+ ## Computer windows on the headset (computer.windows.v1, Windows)
443
+
444
+ The person's oomi headset can show this computer's app windows as separate panels, each playing that app's own sound. The bridge sets this up; pixels and sound go straight between the headset and this computer over an encrypted WebRTC connection, and oomi carries only the setup messages.
445
+
446
+ - **Turned on only at this computer.** `oomi windows on spotify chrome` (or `--all`, every app except the never-shared ones) asks for Windows Hello. An agent running the command can't pass it, and nothing that arrives over the network can turn sharing on. `oomi windows allow APP` also asks; `deny`, `off` and `stop` never do.
447
+ - **Never shared:** password managers, Windows sign-in, UAC and credential prompts, Windows Security, oomi itself, and windows that ask not to be captured.
448
+ - **Visible while sharing:** Windows' yellow capture border, a tray icon with Stop all and Turn off, and `oomi windows status`.
449
+ - **Check this computer:** `oomi windows check`. The native helper ships as the optional package `oomi-ai-window-host-win32-x64`, pinned to this version and checked against its SHA-256 before it runs.
450
+
451
+ The bridge says `computer.windows.v1` on connect when the helper is installed. Two personas on one computer share one window session.
package/bin/oomi-ai.js CHANGED
@@ -26,7 +26,11 @@ 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';
29
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';
30
34
  import { createPersonaApiClient } from '../lib/personaApiClient.js';
31
35
  import { inferSpokenMetadataFromContent, normalizeSpokenMetadata } from '../lib/spokenMetadata.js';
32
36
  import {
@@ -339,6 +343,17 @@ Commands:
339
343
  interrupting them for; say everything else in chat. Limited per hour. Turns started
340
344
  by an Oomi bridge already use their own connection (OOMI_CONNECTION).
341
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
+
342
357
  Common flags:
343
358
  --agents-file PATH Override AGENTS.md path
344
359
  --workspace PATH Override OpenClaw workspace root
@@ -1369,7 +1384,7 @@ function loadGatewayDeviceIdentity() {
1369
1384
  // to OpenClaw with the owner's own token and device identity, so anything else (config, exec
1370
1385
  // approvals, cron, other sessions' history) never passes, whoever holds an app session.
1371
1386
  // `trusted` frames are the bridge's own (the /model translator's models.list / sessions.patch).
1372
- 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']);
1373
1388
 
1374
1389
  function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}) {
1375
1390
  const connectNonce = typeof options.connectNonce === 'string' ? options.connectNonce.trim() : '';
@@ -1638,7 +1653,8 @@ function shouldSuppressOomiVisibleText(value) {
1638
1653
  // (a call's "they're calling you, pick up" cue): never the person's words on any screen.
1639
1654
  const OOMI_CUE_PREFIX = '[oomi:cue:';
1640
1655
  // What this bridge does for oomi, said on each connect (the backend greets a call only through
1641
- // 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).
1642
1658
  const OOMI_BRIDGE_CAPABILITIES = ['call.greeting.v1', 'call.language.v1'];
1643
1659
 
1644
1660
  function sanitizeGatewayMessageForOomi(message) {
@@ -2363,6 +2379,22 @@ async function runBridgePreflight({ brokerWs, gatewayUrl, gatewayConfigPath }) {
2363
2379
  await assertTcpReachable(parsedGatewayUrl.toString());
2364
2380
  }
2365
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
+
2366
2398
  function buildBridgeDetachArgs(rawFlags = {}) {
2367
2399
  const orderedKeys = [
2368
2400
  'broker-http',
@@ -2370,8 +2402,9 @@ function buildBridgeDetachArgs(rawFlags = {}) {
2370
2402
  'pair-code',
2371
2403
  'app-url',
2372
2404
  'device-id',
2373
- 'device-token',
2374
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.
2375
2408
  const args = [process.argv[1], 'openclaw', 'bridge'];
2376
2409
  if (bridgeConnectionName) args.push('--connection', bridgeConnectionName);
2377
2410
 
@@ -2408,9 +2441,13 @@ function startBridgeDetachedProcess(rawFlags = {}) {
2408
2441
  ensureDir(path.dirname(logPath));
2409
2442
  fs.appendFileSync(logPath, `[${new Date().toISOString()}] [bridge-supervisor] starting detached bridge\n`);
2410
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];
2411
2447
  const child = spawn(process.execPath, args, {
2412
2448
  detached: true,
2413
2449
  stdio: ['ignore', logFd, logFd],
2450
+ env,
2414
2451
  });
2415
2452
  child.unref();
2416
2453
  try {
@@ -2570,7 +2607,10 @@ async function startOpenclawBridge(flags) {
2570
2607
  const brokerWs = runtimeConfig.brokerWs;
2571
2608
  const deviceId = resolveDeviceId(flags, bridgeState);
2572
2609
  const pairCode = String(flags['pair-code'] || '').trim().toUpperCase();
2573
- 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();
2574
2614
  const releaseBridgeLock = acquireBridgeLock(deviceId);
2575
2615
  let deviceToken = explicitDeviceToken;
2576
2616
  if (!deviceToken && String(bridgeState.deviceId || '').trim() === deviceId) {
@@ -2730,10 +2770,12 @@ async function startOpenclawBridge(flags) {
2730
2770
  const activeGatewaySockets = new Map();
2731
2771
  const activeGatewayRuns = createGatewayRuns();
2732
2772
  let currentBrokerSocket;
2773
+ let windowHost;
2733
2774
  const maintenanceTick = createMaintenanceController({
2734
2775
  directory: path.dirname(resolveBridgeStatePath()),
2776
+ // A headset watching this computer's windows also holds a restart for an update.
2735
2777
  isIdle: () => !backgroundTurns && !localRuntime?.active.size && !localRuntime?.deliveries && !activeGatewayRuns.size
2736
- && !currentBrokerSocket?.bufferedAmount
2778
+ && !currentBrokerSocket?.bufferedAmount && !windowHost?.sessions.size
2737
2779
  && [...activeGatewaySockets.values()].every((session) => !session.pendingRequests?.size),
2738
2780
  isConnected: () => readBridgeStatus().status === 'connected',
2739
2781
  restart: () => currentBridgeService().restart(),
@@ -2868,6 +2910,22 @@ async function startOpenclawBridge(flags) {
2868
2910
  }
2869
2911
  const stopComputerTurns = localRuntime ? localRuntime.watchComputerTurns() : () => {};
2870
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
+
2871
2929
  const sendGatewayAck = (brokerSocket, {
2872
2930
  sessionId,
2873
2931
  requestId = '',
@@ -3113,9 +3171,12 @@ async function startOpenclawBridge(flags) {
3113
3171
  const wsUrl = new URL(brokerWs);
3114
3172
  wsUrl.searchParams.set('token', deviceToken);
3115
3173
 
3116
- const brokerSocket = new WebSocket(wsUrl.toString());
3174
+ const brokerSocket = new WebSocket(wsUrl.toString(), { handshakeTimeout: BROKER_HANDSHAKE_TIMEOUT_MS });
3117
3175
  currentBrokerSocket = brokerSocket;
3118
3176
  let actionCableHeartbeat = null;
3177
+ let livenessTimer = null;
3178
+ let lastBrokerFrameAt = Date.now();
3179
+ const brokerFrameArrived = () => { lastBrokerFrameAt = Date.now(); };
3119
3180
 
3120
3181
  const clearChallengeTimer = (sessionBridge) => {
3121
3182
  if (sessionBridge && sessionBridge.connectChallengeTimer) {
@@ -3510,7 +3571,7 @@ async function startOpenclawBridge(flags) {
3510
3571
  }
3511
3572
 
3512
3573
  if (connectAccepted) {
3513
- 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()] });
3514
3575
  }
3515
3576
  sendBrokerPayload(brokerSocket, { action: 'gateway_frame', type: 'gateway.frame', sessionId, frame });
3516
3577
  }, (error) => {
@@ -3604,6 +3665,20 @@ async function startOpenclawBridge(flags) {
3604
3665
 
3605
3666
  brokerSocket.on('open', () => {
3606
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?.();
3607
3682
  conversationChangesReady = false;
3608
3683
  reconnectState.attempt = 0;
3609
3684
  reconnectState.lastFailure = null;
@@ -3637,7 +3712,9 @@ async function startOpenclawBridge(flags) {
3637
3712
  });
3638
3713
  });
3639
3714
 
3715
+ brokerSocket.on('pong', brokerFrameArrived);
3640
3716
  brokerSocket.on('message', runBridgeCallbackSafely((rawData) => {
3717
+ brokerFrameArrived();
3641
3718
  const text = typeof rawData === 'string' ? rawData : rawData.toString();
3642
3719
  const payload = parseBrokerEnvelope(text);
3643
3720
  if (!payload || typeof payload.type !== 'string') return;
@@ -3646,6 +3723,7 @@ async function startOpenclawBridge(flags) {
3646
3723
  deviceChannelSubscribed = true;
3647
3724
  conversationChangesReady = true;
3648
3725
  flushConversationChanges();
3726
+ windowHost.signalingRestored();
3649
3727
  updateBridgeStatus({
3650
3728
  status: 'connected',
3651
3729
  deviceId,
@@ -3693,6 +3771,8 @@ async function startOpenclawBridge(flags) {
3693
3771
  }
3694
3772
  reconnectState.lastFailure = disconnect;
3695
3773
  reconnectState.stopped = true;
3774
+ // oomi refused this computer (a revoked link or token): no window session outlives that.
3775
+ windowHost.revoked('revoked').catch(() => {});
3696
3776
  console.error(`[bridge] Broker rejected connection: ${String(payload.reason || 'unauthorized')}`);
3697
3777
  console.error(`[bridge] ${reconnectState.lastFailure.hint}`);
3698
3778
  updateBridgeStatus({
@@ -3719,6 +3799,7 @@ async function startOpenclawBridge(flags) {
3719
3799
 
3720
3800
  if (payload.type === 'broker.reject_subscription') {
3721
3801
  console.error('[bridge] Broker rejected DeviceChannel subscription.');
3802
+ windowHost.revoked('revoked').catch(() => {});
3722
3803
  reconnectState.lastFailure = classifyBridgeFailure({
3723
3804
  reason: 'broker rejected DeviceChannel subscription',
3724
3805
  forceClass: 'auth_rejected',
@@ -3770,6 +3851,12 @@ async function startOpenclawBridge(flags) {
3770
3851
  const sessionId = String(payload.sessionId || '').trim();
3771
3852
  let frame = typeof payload.frame === 'string' ? payload.frame : '';
3772
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
+ }
3773
3860
  if (classifyBridgeSessionScope(sessionId) === 'voice') {
3774
3861
  bridgeDebugLog(`[bridge] client.frame ${sessionId} ${JSON.stringify(summarizeVoiceFrameContract(frame))}`);
3775
3862
  } else {
@@ -3939,6 +4026,8 @@ async function startOpenclawBridge(flags) {
3939
4026
  if (payload.type === 'client.close') {
3940
4027
  const sessionId = String(payload.sessionId || '').trim();
3941
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);
3942
4031
  const sessionBridge = activeGatewaySockets.get(sessionId);
3943
4032
  if (sessionBridge && sessionBridge.socket) {
3944
4033
  clearChallengeTimer(sessionBridge);
@@ -3957,10 +4046,17 @@ async function startOpenclawBridge(flags) {
3957
4046
 
3958
4047
  brokerSocket.on('close', runBridgeCallbackSafely((code, reason) => {
3959
4048
  conversationChangesReady = false;
4049
+ // Windows keep streaming while oomi is out of reach, for 10 minutes at most.
4050
+ windowHost.signalingLost();
3960
4051
  if (actionCableHeartbeat) {
3961
4052
  clearInterval(actionCableHeartbeat);
3962
4053
  actionCableHeartbeat = null;
3963
4054
  }
4055
+ if (livenessTimer) {
4056
+ clearInterval(livenessTimer);
4057
+ livenessTimer = null;
4058
+ }
4059
+ deviceChannelSubscribed = false;
3964
4060
  const reasonText = reason ? reason.toString() : '';
3965
4061
  bridgeDebugLog(`[bridge] Broker disconnected (${code}) ${reasonText}`);
3966
4062
  incrementBridgeMetric('bridge_disconnect_count');
@@ -4013,6 +4109,7 @@ async function startOpenclawBridge(flags) {
4013
4109
  stopRoutineWorker();
4014
4110
  agentChannelWorker.stop();
4015
4111
  stopUpdateWatcher();
4112
+ await Promise.race([windowHost.stop('bridge_stopped'), new Promise((resolve) => setTimeout(resolve, 3000))]);
4016
4113
  if (localRuntime) { await localRuntime.queue; localRuntime.close(); }
4017
4114
  if (reconnectState.timer) {
4018
4115
  clearTimeout(reconnectState.timer);
@@ -4261,6 +4358,9 @@ function printOpenclawBridgeStatus(flags) {
4261
4358
  if (payload.maintenance) console.log(`Maintenance: ${payload.maintenance.status} — ${payload.maintenance.message || ''}`);
4262
4359
  console.log('Oomi Bridge Status');
4263
4360
  const supervision = payload.supervision;
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
+ }
4264
4364
  if (supervision.manager === 'windows-logon') {
4265
4365
  // Two separate promises on Windows: the supervisor restarts the worker while the person stays
4266
4366
  // signed in, and the Run key starts the supervisor at the next sign-in. Say which ones hold.
@@ -4428,9 +4528,20 @@ function assertIndependentMaintenance() {
4428
4528
 
4429
4529
  function deferLiveRestart({ print = true } = {}) {
4430
4530
  const status = readBridgeStatus();
4431
- const service = currentBridgeService().status();
4531
+ const manager = currentBridgeService();
4532
+ const service = manager.status();
4432
4533
  if (status.maintenanceProtocol !== 1 || !status.pid || !isBridgeProcess(status.pid)
4433
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
+ }
4434
4545
  const request = queueRestart(path.dirname(resolveBridgeStatePath()), status.pid);
4435
4546
  if (print) console.log(JSON.stringify(request, null, 2));
4436
4547
  return request;
@@ -4492,6 +4603,11 @@ function signInChoice(flags = {}) {
4492
4603
  function describeSupervision(service, started = null) {
4493
4604
  const status = service.status();
4494
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
+ }
4495
4611
  if (status.manager !== 'windows-logon') return `Automatic startup: ${service.config.platform === 'darwin' ? 'macOS login service' : 'Linux user service'}; restarts after worker exits.`;
4496
4612
  const named = bridgeConnectionName ? ` --name ${bridgeConnectionName}` : '';
4497
4613
  const why = started?.signInError ? ` (${started.signInError})` : status.signIn === false ? ' (--no-sign-in)' : '';
@@ -4511,7 +4627,8 @@ async function repairBridge(flags = {}) {
4511
4627
  await waitForBridgeConnection({});
4512
4628
  const service = currentBridgeService();
4513
4629
  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.');
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)}`);
4515
4632
  }
4516
4633
  }
4517
4634
 
@@ -4663,10 +4780,16 @@ async function verifyLocalAgent(state) {
4663
4780
  if (state.openclawHome) process.env.OPENCLAW_HOME = state.openclawHome;
4664
4781
  let result;
4665
4782
  if (state.localAgent) {
4666
- const reply = await runLocalAgent(state.localAgent, {
4667
- sessionKey: `oomi:verify:${randomUUID()}`, idempotencyKey: randomUUID(), history: [],
4668
- message: state.runtime === 'grokbot' ? 'Oomi connection check.' : 'Oomi connection check. Reply with OOMI_OK only. Do not use tools or change anything.',
4669
- });
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
+ }
4670
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.');
4671
4794
  result = { verifiedAt: new Date().toISOString() };
4672
4795
  } else {
@@ -4850,6 +4973,8 @@ async function main() {
4850
4973
  routines: 'oomi routines list; oomi routines context', identity: 'oomi identity get', updates: 'oomi updates',
4851
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' },
4852
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' },
4853
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' }
4854
4979
  }, null, 2)); return;
4855
4980
  }
@@ -4914,6 +5039,8 @@ async function main() {
4914
5039
  }
4915
5040
  return;
4916
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);
4917
5044
  if (command === 'identity') return handleIdentityCommand(readBridgeState(), subcommand, args.flags);
4918
5045
  if (command === 'routines') return handleRoutinesCommand(readBridgeState(), subcommand, args.flags, args.positionals);
4919
5046
  if (command === 'verify') {
@@ -5085,6 +5212,8 @@ if (__isDirectExecution) {
5085
5212
 
5086
5213
  export {
5087
5214
  annotateConnectResponseForOomi,
5215
+ brokerSocketSilent,
5216
+ buildBridgeDetachArgs,
5088
5217
  prepareGatewayFrameForLocalGateway,
5089
5218
  sanitizeGatewayFrameForOomiClient,
5090
5219
  sanitizeUserVisibleText,
@@ -20,9 +20,9 @@ export function planPackageUpdate(current, latest) {
20
20
  : { instruction: 'Already current. Do not reinstall or restart. Check oomi status only if the user also reports a connection problem.' }) };
21
21
  }
22
22
 
23
- export function isWorkerDescendant(workerPid, { pid = process.pid, run = spawnSync, platform = process.platform } = {}) {
23
+ export function isWorkerDescendant(workerPid, { pid = process.pid, run = spawnSync, platform = process.platform, proc = '/proc' } = {}) {
24
24
  if (!Number.isInteger(workerPid) || workerPid <= 0) return false;
25
- const table = readProcessTable({ run, platform });
25
+ const table = readProcessTable({ run, platform, proc });
26
26
  if (!table) throw new Error('Cannot establish whether this command would stop its own agent. Run maintenance from an independent host terminal.');
27
27
  const parents = new Map(table.map((row) => [row.pid, row.ppid]));
28
28
  const visited = new Set();
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
- import { spawnSync } from 'node:child_process';
4
+ import { spawn, spawnSync } from 'node:child_process';
5
5
 
6
6
  const xml = (value) => String(value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }[c]));
7
7
  // systemd performs specifier expansion even inside quotes; ExecStart also expands $.
@@ -13,7 +13,34 @@ function unitPath(value) {
13
13
  return String(value).replace(/%/g, '%%');
14
14
  }
15
15
 
16
- export function bridgeServiceConfig({ name = '', stateDirectory, logPath, scriptPath, nodePath = process.execPath,
16
+ /**
17
+ * A path to this Node that survives upgrades. process.execPath is the resolved binary, which on
18
+ * Homebrew is Cellar/node/<version>/bin/node: `brew upgrade` deletes it, and a service still naming it
19
+ * fails at its next start, every 10 s, without a word in oomi's log. Homebrew's opt/<formula> link,
20
+ * snap's current revision, or a link to this binary on PATH follows the installed version. nvm,
21
+ * fnm and volta have no such link, so their path stays as it is.
22
+ */
23
+ export function stableNodePath(execPath = process.execPath, { env = process.env, platform = process.platform,
24
+ realpath = (file) => fs.realpathSync(file), exists = (file) => fs.existsSync(file), tmpdir = os.tmpdir() } = {}) {
25
+ if (platform === 'win32') return execPath;
26
+ let real;
27
+ try { real = realpath(execPath); } catch { return execPath; }
28
+ const same = (candidate) => { try { return exists(candidate) && realpath(candidate) === real; } catch { return false; } };
29
+ const brew = real.match(/^(.*)\/Cellar\/([^/]+)\/[^/]+\/(.+)$/);
30
+ if (brew && same(`${brew[1]}/opt/${brew[2]}/${brew[3]}`)) return `${brew[1]}/opt/${brew[2]}/${brew[3]}`;
31
+ const snap = real.match(/^\/snap\/([^/]+)\/[^/]+\/(.+)$/);
32
+ if (snap && same(`/snap/${snap[1]}/current/${snap[2]}`)) return `/snap/${snap[1]}/current/${snap[2]}`;
33
+ // A link on PATH, unless the link itself is temporary (fnm's per-shell folders, the runtime dir).
34
+ const temporary = [env.XDG_RUNTIME_DIR, tmpdir, '/tmp', '/run/user'].filter(Boolean);
35
+ for (const dir of String(env.PATH || '').split(':')) {
36
+ if (!dir.startsWith('/') || dir.includes('fnm_multishells') || temporary.some((root) => dir === root || dir.startsWith(`${root}/`))) continue;
37
+ const candidate = path.posix.join(dir, 'node');
38
+ if (candidate !== real && same(candidate)) return candidate;
39
+ }
40
+ return execPath;
41
+ }
42
+
43
+ export function bridgeServiceConfig({ name = '', stateDirectory, logPath, scriptPath, nodePath = stableNodePath(),
17
44
  platform = process.platform, home = os.homedir(), env = process.env, uid = process.getuid?.() } = {}) {
18
45
  if (name && !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) throw new Error('Invalid connection name.');
19
46
  const label = `ai.oomi.bridge${name ? '.' + name : ''}`;
@@ -72,12 +99,14 @@ WantedBy=default.target
72
99
 
73
100
  // No credentials, runtime commands or arbitrary environment are copied into service files.
74
101
  // Use injectable process execution so lifecycle failures can be tested without real user services.
75
- export function createBridgeService(config, { run = spawnSync } = {}) {
102
+ export function createBridgeService(config, { run = spawnSync, spawnImpl = spawn } = {}) {
76
103
  const mac = config.platform === 'darwin';
77
104
  const supported = mac || config.platform === 'linux';
78
105
  const command = mac ? 'launchctl' : 'systemctl';
79
106
  function invoke(args, allowFailure = false) {
80
- const result = run(command, mac ? args : ['--user', ...args], { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'pipe'] });
107
+ // Longer than the service's own stop timeout (TimeoutStopSec, launchd's 20 s): a stop that waits
108
+ // for a turn to finish must not be reported as a failure while the service manager still works on it.
109
+ const result = run(command, mac ? args : ['--user', ...args], { encoding: 'utf8', timeout: 45000, stdio: ['ignore', 'pipe', 'pipe'] });
81
110
  const code = Number.isInteger(result.status) ? result.status : 1;
82
111
  const stdout = String(result.stdout || '').trim();
83
112
  if (code && !allowFailure) throw new Error(`${command} ${args[0]} failed: ${String(result.stderr || result.error?.message || stdout || 'service manager unavailable').trim()}`);
@@ -91,9 +120,11 @@ export function createBridgeService(config, { run = spawnSync } = {}) {
91
120
  function assertAvailable() { const result = availability(); if (!result.available) throw new Error(result.reason); }
92
121
  function status() {
93
122
  const available = availability();
123
+ const installed = supported && fs.existsSync(config.file);
94
124
  const base = { manager: mac ? 'launchd' : config.platform === 'linux' ? 'systemd' : null,
95
- connection: config.name || null, target: config.target, file: config.file, installed: supported && fs.existsSync(config.file),
96
- ...available, loaded: false, running: false, enabled: false, pid: null, startsAt: mac ? 'login' : 'user-session' };
125
+ connection: config.name || null, target: config.target, file: config.file, installed,
126
+ ...available, loaded: false, running: false, enabled: false, pid: null, startsAt: mac ? 'login' : 'user-session',
127
+ ...(installed && missingProgram().length ? { missingProgram: missingProgram() } : {}) };
97
128
  if (!available.available) return base;
98
129
  if (mac) {
99
130
  const printed = invoke(['print', config.target], true);
@@ -159,6 +190,41 @@ export function createBridgeService(config, { run = spawnSync } = {}) {
159
190
  else if (!current.running) invoke(['kickstart', config.target]);
160
191
  } else invoke(['enable', '--now', config.target]);
161
192
  }
193
+ /**
194
+ * Writes the definition again when this version renders it differently (a new Node path, a newer
195
+ * template). systemd reloads it, so the next restart uses it; launchd keeps the copy it loaded,
196
+ * so on macOS the caller must load it again (reloadDetached). Returns whether it changed.
197
+ */
198
+ function refreshDefinition() {
199
+ preflight();
200
+ const content = mac ? renderLaunchAgent(config) : renderSystemdUnit(config);
201
+ let existing = null;
202
+ try { existing = fs.readFileSync(config.file, 'utf8'); } catch { existing = null; }
203
+ if (existing === null || existing === content) return { changed: false };
204
+ writeDefinition();
205
+ return { changed: true };
206
+ }
207
+ /**
208
+ * launchd: unload and load the job again from a process outside it. bootout ends the job's process
209
+ * group, which holds the bridge, its agent, and an agent's own `oomi bridge repair`; a new session
210
+ * (detached) is not in it.
211
+ */
212
+ function reloadDetached() {
213
+ if (!mac) throw new Error('Only launchd needs a detached reload.');
214
+ const child = spawnImpl('/bin/sh', ['-c', 'sleep 1; launchctl bootout "$1" >/dev/null 2>&1; launchctl bootstrap "$2" "$3"', 'oomi-reload', config.target, `gui/${config.uid}`, config.file],
215
+ { detached: true, stdio: 'ignore' });
216
+ child.unref?.();
217
+ }
218
+ /** The program and script an installed definition names that no longer exist (an upgrade removed them). */
219
+ function missingProgram() {
220
+ let text;
221
+ try { text = fs.readFileSync(config.file, 'utf8'); } catch { return []; }
222
+ const decode = (value) => value.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
223
+ const program = mac
224
+ ? [...(text.match(/<key>ProgramArguments<\/key><array>(.*?)<\/array>/s)?.[1] || '').matchAll(/<string>(.*?)<\/string>/g)].slice(0, 2).map((m) => decode(m[1]))
225
+ : [...(text.match(/^ExecStart=(.*)$/m)?.[1] || '').matchAll(/"((?:[^"\\]|\\.)*)"/g)].slice(0, 2).map((m) => m[1].replace(/\\(.)/g, '$1').replace(/\$\$/g, '$').replace(/%%/g, '%'));
226
+ return program.filter((file) => file.startsWith('/') && !fs.existsSync(file));
227
+ }
162
228
  function restart() {
163
229
  preflight();
164
230
  const current = status();
@@ -177,5 +243,5 @@ export function createBridgeService(config, { run = spawnSync } = {}) {
177
243
  if (fs.existsSync(config.file)) fs.unlinkSync(config.file);
178
244
  if (!mac) invoke(['daemon-reload']);
179
245
  }
180
- return { config, availability, preflight, status, install, start, stop, restart, uninstall };
246
+ return { config, availability, preflight, status, install, start, stop, restart, uninstall, refreshDefinition, reloadDetached };
181
247
  }