oomi-ai 0.12.2 → 0.14.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 +2 -0
- package/bin/oomi-ai.js +101 -75
- package/lib/agentChannels.js +42 -3
- package/lib/agentIdentity.js +3 -1
- package/lib/chatModels.js +93 -0
- package/lib/gatewayProbe.js +29 -5
- package/lib/gatewayRuns.js +29 -0
- package/lib/hermesAcp.js +53 -76
- package/lib/hermesGateway.js +213 -8
- package/lib/localAgent.js +461 -43
- package/lib/openclawModels.js +71 -0
- package/lib/runtimeFailure.js +2 -0
- package/lib/updateWatcher.js +56 -0
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -113,6 +113,8 @@ Use the user's app URL when provided. Hermes supports `--profile <profile>` and
|
|
|
113
113
|
|
|
114
114
|
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
115
|
|
|
116
|
+
From 0.14.0, messages the person types to the persona on the computer, in a conversation Oomi shares (Hermes desktop, or oomi's Talk showing the phone's conversation), join that Oomi conversation with the persona's reply, and the person's open Oomi chats (web, phone) reload within about a second. The bridge watches Hermes's `state.db` and reads the conversation from the running Hermes backend's transcript (`/api/sessions/{id}/messages`, the one Hermes desktop shows), only between its own turns. It copies what the person and the persona said, never tool output, and starts counting from its first run with this release; earlier computer messages aren't copied. Its own phone and web turns are recognised by Hermes's row ids or by their words, never by the time alone, and a phone or web message first picks up what was just typed on the computer, so the order holds. It reads only conversations Hermes changed, back to its last look; far behind, it reads forward from the last look a chunk at a time, so nothing is skipped. While no Hermes backend runs, nothing on the computer but the bridge (and Hermes's CLI by hand) can write to its conversations, so its own turns are settled without a read; rows written while a backend ran are picked up when one runs again, retried every 30 seconds and as soon as one starts. A phone or web turn waits at most a quarter second for what was just typed on the computer. A conversation record keeps its newest 1,000 messages and 200 finished receipts; a receipt for an action that never finished is always kept.
|
|
117
|
+
|
|
116
118
|
The command verifies a real local reply, reuses saved credentials or pairs once, starts the bridge, waits for Oomi's subscription, then creates a single-use Auth Link. Failed verification means setup is incomplete: repair the selected runtime, never substitute a different one.
|
|
117
119
|
|
|
118
120
|
The installer is an alternative to npm plus connect, and requires an explicit runtime:
|
package/bin/oomi-ai.js
CHANGED
|
@@ -12,6 +12,10 @@ import { lookup as dnsLookup } from 'dns/promises';
|
|
|
12
12
|
import { fileURLToPath } from 'url';
|
|
13
13
|
import WebSocket from 'ws';
|
|
14
14
|
import { planPackageUpdate, isWorkerDescendant, queueRestart, readMaintenance, createMaintenanceController } from '../lib/bridgeMaintenance.js';
|
|
15
|
+
import { createGatewayRuns } from '../lib/gatewayRuns.js';
|
|
16
|
+
import { CHAT_MODELS_CAPABILITY } from '../lib/chatModels.js';
|
|
17
|
+
import { OpenclawModelRequests } from '../lib/openclawModels.js';
|
|
18
|
+
import { startUpdateWatcher } from '../lib/updateWatcher.js';
|
|
15
19
|
import { processCommand, readProcessTable } from '../lib/processTable.js';
|
|
16
20
|
import { bridgeServiceConfig, createBridgeService, renderLaunchAgent } from '../lib/bridgeService.js';
|
|
17
21
|
import { LOCAL_PROTOCOL_MIN, LOCAL_PROTOCOL_MAX, probeGateway } from '../lib/gatewayProbe.js';
|
|
@@ -1146,28 +1150,13 @@ function acquireBridgeLock(deviceId) {
|
|
|
1146
1150
|
return release;
|
|
1147
1151
|
}
|
|
1148
1152
|
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
*/
|
|
1153
|
-
async function reportRuntimeModels({ brokerHttp, deviceToken }, report, fetchImpl = fetch) {
|
|
1154
|
-
if (!brokerHttp || !deviceToken) return false;
|
|
1155
|
-
try {
|
|
1156
|
-
const response = await fetchImpl(`${brokerHttp.replace(/\/$/, '')}/v1/agent_runtime/models`, {
|
|
1157
|
-
method: 'PUT',
|
|
1158
|
-
headers: { Authorization: `Bearer ${deviceToken}`, 'Content-Type': 'application/json' },
|
|
1159
|
-
body: JSON.stringify(report),
|
|
1160
|
-
signal: AbortSignal.timeout(10000),
|
|
1161
|
-
});
|
|
1162
|
-
return response.ok;
|
|
1163
|
-
} catch { return false; }
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
async function claimBridgeDeviceToken({ brokerHttp, pairCode, deviceId }) {
|
|
1153
|
+
// A computer already linked to an account re-pairs only by showing the token it was given (even
|
|
1154
|
+
// an expired one): the backend won't hand a linked device's token to a pair code alone.
|
|
1155
|
+
async function claimBridgeDeviceToken({ brokerHttp, pairCode, deviceId, proofToken = '' }) {
|
|
1167
1156
|
const response = await fetch(`${brokerHttp.replace(/\/$/, '')}/v1/pair/claim`, {
|
|
1168
1157
|
method: 'POST',
|
|
1169
1158
|
signal: AbortSignal.timeout(15000),
|
|
1170
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1159
|
+
headers: { 'Content-Type': 'application/json', ...(proofToken ? { Authorization: `Bearer ${proofToken}` } : {}) },
|
|
1171
1160
|
body: JSON.stringify({ pairCode, deviceId }),
|
|
1172
1161
|
});
|
|
1173
1162
|
const payload = await response.json().catch(() => ({}));
|
|
@@ -1367,6 +1356,12 @@ function loadGatewayDeviceIdentity() {
|
|
|
1367
1356
|
return null;
|
|
1368
1357
|
}
|
|
1369
1358
|
|
|
1359
|
+
// What an oomi app may ask of the person's agent gateway through this bridge. The bridge signs in
|
|
1360
|
+
// to OpenClaw with the owner's own token and device identity, so anything else (config, exec
|
|
1361
|
+
// approvals, cron, other sessions' history) never passes, whoever holds an app session.
|
|
1362
|
+
// `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']);
|
|
1364
|
+
|
|
1370
1365
|
function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}) {
|
|
1371
1366
|
const connectNonce = typeof options.connectNonce === 'string' ? options.connectNonce.trim() : '';
|
|
1372
1367
|
const deviceIdentity = options.deviceIdentity || null;
|
|
@@ -1382,6 +1377,9 @@ function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}
|
|
|
1382
1377
|
}
|
|
1383
1378
|
|
|
1384
1379
|
if (method !== 'connect') {
|
|
1380
|
+
if (options.trusted !== true && !CLIENT_GATEWAY_METHODS.has(method)) {
|
|
1381
|
+
return { frameText: '', waitForChallenge: false, refusedMethod: method };
|
|
1382
|
+
}
|
|
1385
1383
|
const rawParams = frame.params && typeof frame.params === 'object' ? frame.params : {};
|
|
1386
1384
|
if (method === 'chat.send') {
|
|
1387
1385
|
const sanitized = {};
|
|
@@ -1403,18 +1401,10 @@ function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}
|
|
|
1403
1401
|
if (Number.isFinite(rawParams.timeoutMs) && rawParams.timeoutMs > 0) {
|
|
1404
1402
|
sanitized.timeoutMs = Math.floor(rawParams.timeoutMs);
|
|
1405
1403
|
}
|
|
1406
|
-
// A call turn's faster model, for the runtimes Oomi drives itself (OpenClaw's gateway
|
|
1407
|
-
// would reject the field).
|
|
1408
|
-
const callModel = rawParams.oomi?.call?.model;
|
|
1409
|
-
if (gatewayAuth?.gatewayUrl === 'local-agent:' && typeof callModel === 'string' && callModel.trim() && callModel.trim().length <= 200) {
|
|
1410
|
-
sanitized.oomi = { call: { model: callModel.trim() } };
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
1404
|
const practiceBrief = rawParams.oomi?.call?.practiceBrief;
|
|
1414
1405
|
const context = practiceContext(practiceBrief);
|
|
1415
1406
|
if (context && gatewayAuth?.gatewayUrl === 'local-agent:') {
|
|
1416
|
-
sanitized.oomi
|
|
1417
|
-
sanitized.oomi.call.practiceBrief = practiceBrief;
|
|
1407
|
+
sanitized.oomi = { call: { practiceBrief } };
|
|
1418
1408
|
} else if (context && typeof sanitized.message === 'string') {
|
|
1419
1409
|
// OpenClaw rejects custom metadata; carry hidden context on every turn,
|
|
1420
1410
|
// including an ordinary transcript retry after a rejected greeting.
|
|
@@ -1497,42 +1487,11 @@ function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}
|
|
|
1497
1487
|
}
|
|
1498
1488
|
params.client = client;
|
|
1499
1489
|
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
const requiredScopes = ['operator.read', 'operator.write'];
|
|
1506
|
-
for (const scope of requiredScopes) {
|
|
1507
|
-
if (!existingScopes.includes(scope)) {
|
|
1508
|
-
existingScopes.push(scope);
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
params.scopes = existingScopes;
|
|
1512
|
-
|
|
1513
|
-
params.caps = Array.isArray(rawParams.caps)
|
|
1514
|
-
? rawParams.caps.filter((value) => typeof value === 'string' && value.trim())
|
|
1515
|
-
: [];
|
|
1516
|
-
|
|
1517
|
-
params.commands = Array.isArray(rawParams.commands)
|
|
1518
|
-
? rawParams.commands.filter((value) => typeof value === 'string' && value.trim())
|
|
1519
|
-
: [];
|
|
1520
|
-
|
|
1521
|
-
if (rawParams.permissions && typeof rawParams.permissions === 'object') {
|
|
1522
|
-
const permissions = {};
|
|
1523
|
-
for (const [key, value] of Object.entries(rawParams.permissions)) {
|
|
1524
|
-
const normalizedKey = typeof key === 'string' ? key.trim() : '';
|
|
1525
|
-
if (!normalizedKey || typeof value !== 'boolean') continue;
|
|
1526
|
-
permissions[normalizedKey] = value;
|
|
1527
|
-
}
|
|
1528
|
-
if (Object.keys(permissions).length > 0) {
|
|
1529
|
-
params.permissions = permissions;
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
1532
|
-
|
|
1533
|
-
if (typeof rawParams.pathEnv === 'string') {
|
|
1534
|
-
params.pathEnv = rawParams.pathEnv;
|
|
1535
|
-
}
|
|
1490
|
+
// The bridge decides what the app's connection may do, never the app: chat as an operator.
|
|
1491
|
+
params.role = 'operator';
|
|
1492
|
+
params.scopes = ['operator.read', 'operator.write'];
|
|
1493
|
+
params.caps = [];
|
|
1494
|
+
params.commands = [];
|
|
1536
1495
|
|
|
1537
1496
|
const auth = {};
|
|
1538
1497
|
if (gatewayAuth.token) {
|
|
@@ -1570,7 +1529,7 @@ function prepareGatewayFrameForLocalGateway(frameText, gatewayAuth, options = {}
|
|
|
1570
1529
|
clientId: client.id,
|
|
1571
1530
|
clientMode: client.mode,
|
|
1572
1531
|
role: params.role,
|
|
1573
|
-
scopes:
|
|
1532
|
+
scopes: params.scopes,
|
|
1574
1533
|
signedAtMs,
|
|
1575
1534
|
token: tokenForSignature,
|
|
1576
1535
|
nonce: nonceForSignature,
|
|
@@ -1759,14 +1718,21 @@ function sanitizeGatewayFrameForOomiClient(frameText) {
|
|
|
1759
1718
|
}
|
|
1760
1719
|
|
|
1761
1720
|
// The runtime accepted oomi's connect: say what this bridge can do. Grok Bot gets no greeting (its
|
|
1762
|
-
// inbox is slow, and Grok's own app would show the cue).
|
|
1763
|
-
|
|
1721
|
+
// inbox is slow, and Grok's own app would show the cue). `extra` is what the local runtime adds
|
|
1722
|
+
// (Hermes over ACP: chat.models.v1, `/model` in Talk).
|
|
1723
|
+
function annotateConnectResponseForOomi(frameText, { runtime = 'openclaw', version = '', extra = [] } = {}) {
|
|
1764
1724
|
const frame = parseJsonPayload(frameText);
|
|
1765
1725
|
if (!frame || typeof frame !== 'object' || frame.type !== 'res' || !frame.ok) return frameText;
|
|
1766
1726
|
const payload = frame.payload && typeof frame.payload === 'object' && !Array.isArray(frame.payload) ? frame.payload : {};
|
|
1767
1727
|
const existing = payload.oomi && typeof payload.oomi === 'object' && !Array.isArray(payload.oomi) ? payload.oomi : {};
|
|
1768
|
-
const capabilities = runtime === 'grokbot' ? [] :
|
|
1769
|
-
|
|
1728
|
+
const capabilities = [...(runtime === 'grokbot' ? [] : OOMI_BRIDGE_CAPABILITIES), ...extra];
|
|
1729
|
+
// The gateway's connect answer can carry credentials for this connection (an issued device
|
|
1730
|
+
// token); they're the bridge's, and never leave the computer.
|
|
1731
|
+
const { auth, ...rest } = payload;
|
|
1732
|
+
const safeAuth = auth && typeof auth === 'object' && !Array.isArray(auth)
|
|
1733
|
+
? Object.fromEntries(Object.entries(auth).filter(([key]) => !/token|secret|password|key/i.test(key)))
|
|
1734
|
+
: undefined;
|
|
1735
|
+
return JSON.stringify({ ...frame, payload: { ...rest, ...(safeAuth ? { auth: safeAuth } : {}), oomi: { ...existing, bridgeVersion: version, capabilities } } });
|
|
1770
1736
|
}
|
|
1771
1737
|
|
|
1772
1738
|
function summarizeVoiceFrameContract(frameText) {
|
|
@@ -2617,7 +2583,6 @@ async function startOpenclawBridge(flags) {
|
|
|
2617
2583
|
const localRuntime = bridgeState.localAgent
|
|
2618
2584
|
? new LocalAgentRuntime({ ...bridgeState.localAgent, connection: bridgeConnectionName }, path.dirname(resolveBridgeStatePath()), (health) => updateBridgeStatus(health))
|
|
2619
2585
|
: null;
|
|
2620
|
-
if (localRuntime) localRuntime.onModels = (report) => reportRuntimeModels({ brokerHttp, deviceToken }, report);
|
|
2621
2586
|
localRuntime?.warm();
|
|
2622
2587
|
const gateway = localRuntime ? { gatewayUrl: 'local-agent:', configPath: resolveBridgeStatePath() } : readOpenclawGatewayConfig();
|
|
2623
2588
|
if (!localRuntime && !gateway.token && !gateway.password) {
|
|
@@ -2718,6 +2683,16 @@ async function startOpenclawBridge(flags) {
|
|
|
2718
2683
|
: `Agent channel delivery: ${error.message}` }),
|
|
2719
2684
|
onDelivered: () => updateBridgeStatus({ agentChannelError: '' }),
|
|
2720
2685
|
});
|
|
2686
|
+
// Asks the agent to keep oomi-ai current, once per new version (lib/updateWatcher.js).
|
|
2687
|
+
const stopUpdateWatcher = startUpdateWatcher({
|
|
2688
|
+
current: currentPackageVersion(),
|
|
2689
|
+
fetchLatest: () => fetchLatestPublishedVersion('oomi-ai'),
|
|
2690
|
+
deliver: deliverAgentEvent,
|
|
2691
|
+
sessionKey: `${(bridgeState.sessionKey || 'agent:main:').split(':').slice(0, 2).join(':')}:oomi:maintenance`,
|
|
2692
|
+
receiptPath: path.join(path.dirname(resolveBridgeStatePath()), 'oomi-update-receipt.json'),
|
|
2693
|
+
connection: bridgeConnectionName,
|
|
2694
|
+
onStatus: (patch) => updateBridgeStatus(patch),
|
|
2695
|
+
});
|
|
2721
2696
|
console.log(`Local gateway: ${gateway.gatewayUrl}`);
|
|
2722
2697
|
console.log(`Broker WS: ${brokerWs}`);
|
|
2723
2698
|
bridgeDebugLog(
|
|
@@ -2725,7 +2700,7 @@ async function startOpenclawBridge(flags) {
|
|
|
2725
2700
|
);
|
|
2726
2701
|
|
|
2727
2702
|
const activeGatewaySockets = new Map();
|
|
2728
|
-
const activeGatewayRuns =
|
|
2703
|
+
const activeGatewayRuns = createGatewayRuns();
|
|
2729
2704
|
let currentBrokerSocket;
|
|
2730
2705
|
const maintenanceTick = createMaintenanceController({
|
|
2731
2706
|
directory: path.dirname(resolveBridgeStatePath()),
|
|
@@ -2845,6 +2820,26 @@ async function startOpenclawBridge(flags) {
|
|
|
2845
2820
|
);
|
|
2846
2821
|
};
|
|
2847
2822
|
|
|
2823
|
+
// Messages typed to the persona on this computer joined a conversation: Oomi tells the phone
|
|
2824
|
+
// and the web to reload it. Held until DeviceChannel confirms this connection's subscription.
|
|
2825
|
+
let conversationChangesReady = false;
|
|
2826
|
+
const pendingConversationChanges = new Map();
|
|
2827
|
+
const flushConversationChanges = () => {
|
|
2828
|
+
if (!conversationChangesReady || currentBrokerSocket?.readyState !== WebSocket.OPEN) return;
|
|
2829
|
+
for (const [sessionKey, reason] of pendingConversationChanges) {
|
|
2830
|
+
sendBrokerPayload(currentBrokerSocket, { action: 'conversation_changed', type: 'conversation.changed', sessionKey, reason });
|
|
2831
|
+
}
|
|
2832
|
+
pendingConversationChanges.clear();
|
|
2833
|
+
};
|
|
2834
|
+
if (localRuntime) {
|
|
2835
|
+
localRuntime.onConversationChanged = ({ sessionKey, reason }) => {
|
|
2836
|
+
if (!actionCableMode) return;
|
|
2837
|
+
pendingConversationChanges.set(sessionKey, pendingConversationChanges.get(sessionKey) === 'reply' ? 'reply' : reason);
|
|
2838
|
+
flushConversationChanges();
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
const stopComputerTurns = localRuntime ? localRuntime.watchComputerTurns() : () => {};
|
|
2842
|
+
|
|
2848
2843
|
const sendGatewayAck = (brokerSocket, {
|
|
2849
2844
|
sessionId,
|
|
2850
2845
|
requestId = '',
|
|
@@ -3307,6 +3302,11 @@ async function startOpenclawBridge(flags) {
|
|
|
3307
3302
|
|
|
3308
3303
|
gatewaySocket.on('message', runBridgeCallbackSafely((gatewayRaw) => {
|
|
3309
3304
|
let frame = typeof gatewayRaw === 'string' ? gatewayRaw : gatewayRaw.toString();
|
|
3305
|
+
const modelsAnswer = sessionBridge.openclawModels?.take(frame);
|
|
3306
|
+
if (modelsAnswer) {
|
|
3307
|
+
if (!modelsAnswer.reply) return;
|
|
3308
|
+
frame = modelsAnswer.reply;
|
|
3309
|
+
}
|
|
3310
3310
|
let connectAccepted = false;
|
|
3311
3311
|
const practiceConfirmation = confirmPracticeDelivery(sessionBridge.practiceDeliveries ||= new Map(), frame);
|
|
3312
3312
|
if (practiceConfirmation) sendBrokerPayload(brokerSocket, {
|
|
@@ -3460,10 +3460,10 @@ async function startOpenclawBridge(flags) {
|
|
|
3460
3460
|
}
|
|
3461
3461
|
|
|
3462
3462
|
if (gatewayPayload?.type === 'res' && gatewayPayload.ok && gatewayPayload.payload?.status === 'started' && gatewayPayload.payload?.runId) {
|
|
3463
|
-
activeGatewayRuns.
|
|
3463
|
+
activeGatewayRuns.started(sessionId, gatewayPayload.payload.runId);
|
|
3464
3464
|
}
|
|
3465
3465
|
if (gatewayPayload?.event === 'chat' && ['final', 'error', 'aborted'].includes(gatewayPayload.payload?.state)) {
|
|
3466
|
-
activeGatewayRuns.
|
|
3466
|
+
activeGatewayRuns.finished(gatewayPayload.payload.runId);
|
|
3467
3467
|
}
|
|
3468
3468
|
if (gatewayPayload?.event === 'chat' && gatewayPayload.payload?.state === 'final') {
|
|
3469
3469
|
updateBridgeStatus({ runtimeReady: true, lastReplyAt: bridgeNowIso() });
|
|
@@ -3481,7 +3481,7 @@ async function startOpenclawBridge(flags) {
|
|
|
3481
3481
|
}
|
|
3482
3482
|
|
|
3483
3483
|
if (connectAccepted) {
|
|
3484
|
-
frame = annotateConnectResponseForOomi(frame, { runtime: bridgeRuntimeName, version: currentPackageVersion() });
|
|
3484
|
+
frame = annotateConnectResponseForOomi(frame, { runtime: bridgeRuntimeName, version: currentPackageVersion(), extra: localRuntime ? localRuntime.capabilities() : bridgeRuntimeName === 'openclaw' ? [CHAT_MODELS_CAPABILITY] : [] });
|
|
3485
3485
|
}
|
|
3486
3486
|
sendBrokerPayload(brokerSocket, { action: 'gateway_frame', type: 'gateway.frame', sessionId, frame });
|
|
3487
3487
|
}, (error) => {
|
|
@@ -3489,6 +3489,7 @@ async function startOpenclawBridge(flags) {
|
|
|
3489
3489
|
}));
|
|
3490
3490
|
|
|
3491
3491
|
gatewaySocket.on('close', runBridgeCallbackSafely((code, reason) => {
|
|
3492
|
+
activeGatewayRuns.closed(sessionId);
|
|
3492
3493
|
if (connectTimeout) {
|
|
3493
3494
|
clearTimeout(connectTimeout);
|
|
3494
3495
|
connectTimeout = null;
|
|
@@ -3574,6 +3575,7 @@ async function startOpenclawBridge(flags) {
|
|
|
3574
3575
|
|
|
3575
3576
|
brokerSocket.on('open', () => {
|
|
3576
3577
|
bridgeDebugLog('[bridge] Connected to managed broker.');
|
|
3578
|
+
conversationChangesReady = false;
|
|
3577
3579
|
reconnectState.attempt = 0;
|
|
3578
3580
|
reconnectState.lastFailure = null;
|
|
3579
3581
|
if (actionCableMode) {
|
|
@@ -3613,6 +3615,8 @@ async function startOpenclawBridge(flags) {
|
|
|
3613
3615
|
|
|
3614
3616
|
if (payload.type === 'device.subscribed') {
|
|
3615
3617
|
deviceChannelSubscribed = true;
|
|
3618
|
+
conversationChangesReady = true;
|
|
3619
|
+
flushConversationChanges();
|
|
3616
3620
|
updateBridgeStatus({
|
|
3617
3621
|
status: 'connected',
|
|
3618
3622
|
deviceId,
|
|
@@ -3711,7 +3715,7 @@ async function startOpenclawBridge(flags) {
|
|
|
3711
3715
|
|
|
3712
3716
|
if (payload.type === 'client.frame') {
|
|
3713
3717
|
const sessionId = String(payload.sessionId || '').trim();
|
|
3714
|
-
|
|
3718
|
+
let frame = typeof payload.frame === 'string' ? payload.frame : '';
|
|
3715
3719
|
if (!sessionId || !frame) return;
|
|
3716
3720
|
if (classifyBridgeSessionScope(sessionId) === 'voice') {
|
|
3717
3721
|
bridgeDebugLog(`[bridge] client.frame ${sessionId} ${JSON.stringify(summarizeVoiceFrameContract(frame))}`);
|
|
@@ -3736,10 +3740,23 @@ async function startOpenclawBridge(flags) {
|
|
|
3736
3740
|
sessionBridge.lastChatCorrelationId = requestMeta.correlationId;
|
|
3737
3741
|
}
|
|
3738
3742
|
}
|
|
3743
|
+
// `/model` in Talk for an OpenClaw persona: asked of OpenClaw's own methods, answered in
|
|
3744
|
+
// oomi's shape when they reply (docs/specs/chat-models-v1.md).
|
|
3745
|
+
let extraFrames = [];
|
|
3746
|
+
const modelsPlan = gateway.gatewayUrl === 'local-agent:' ? null : (sessionBridge.openclawModels ||= new OpenclawModelRequests()).plan(frame);
|
|
3747
|
+
if (modelsPlan?.reply) {
|
|
3748
|
+
sendBrokerPayload(brokerSocket, { action: 'gateway_frame', type: 'gateway.frame', sessionId, frame: modelsPlan.reply });
|
|
3749
|
+
if (requestMeta && sessionBridge.pendingRequests instanceof Map) sessionBridge.pendingRequests.delete(requestMeta.requestId);
|
|
3750
|
+
if (requestMeta) clearPendingRequestTimeout(sessionBridge, requestMeta.requestId);
|
|
3751
|
+
return;
|
|
3752
|
+
}
|
|
3753
|
+
if (modelsPlan) [frame, ...extraFrames] = modelsPlan.frames;
|
|
3739
3754
|
const prepared = prepareGatewayFrameForLocalGateway(frame, gateway, {
|
|
3740
3755
|
connectNonce: sessionBridge.connectNonce,
|
|
3741
3756
|
deviceIdentity: gatewayDeviceIdentity,
|
|
3757
|
+
trusted: Boolean(modelsPlan),
|
|
3742
3758
|
});
|
|
3759
|
+
if (prepared.refusedMethod) bridgeDebugLog(`[bridge] client.frame refused ${sessionId} method=${prepared.refusedMethod}`);
|
|
3743
3760
|
if (prepared.practiceDelivery) {
|
|
3744
3761
|
sessionBridge.practiceDeliveries ||= new Map();
|
|
3745
3762
|
sessionBridge.practiceDeliveries.set(prepared.practiceDelivery.runId, prepared.practiceDelivery);
|
|
@@ -3791,6 +3808,9 @@ async function startOpenclawBridge(flags) {
|
|
|
3791
3808
|
const result = forwardFrameToSession(sessionBridge, prepared.frameText, {
|
|
3792
3809
|
requiresConnectAccepted: Boolean(requestMeta && requestMeta.method !== 'connect'),
|
|
3793
3810
|
});
|
|
3811
|
+
for (const extra of extraFrames) {
|
|
3812
|
+
forwardFrameToSession(sessionBridge, prepareGatewayFrameForLocalGateway(extra, gateway, { connectNonce: sessionBridge.connectNonce, deviceIdentity: gatewayDeviceIdentity, trusted: true }).frameText, { requiresConnectAccepted: true });
|
|
3813
|
+
}
|
|
3794
3814
|
if (result === 'waiting_for_connect') {
|
|
3795
3815
|
bridgeDebugLog(`[bridge] client.frame waiting for connect ${sessionId}`);
|
|
3796
3816
|
if (requestMeta) {
|
|
@@ -3883,6 +3903,7 @@ async function startOpenclawBridge(flags) {
|
|
|
3883
3903
|
}));
|
|
3884
3904
|
|
|
3885
3905
|
brokerSocket.on('close', runBridgeCallbackSafely((code, reason) => {
|
|
3906
|
+
conversationChangesReady = false;
|
|
3886
3907
|
if (actionCableHeartbeat) {
|
|
3887
3908
|
clearInterval(actionCableHeartbeat);
|
|
3888
3909
|
actionCableHeartbeat = null;
|
|
@@ -3934,9 +3955,11 @@ async function startOpenclawBridge(flags) {
|
|
|
3934
3955
|
reconnectState.stopped = true;
|
|
3935
3956
|
clearInterval(maintenanceTimer);
|
|
3936
3957
|
stopChannelWorker();
|
|
3958
|
+
stopComputerTurns();
|
|
3937
3959
|
stopIdentityWorker();
|
|
3938
3960
|
stopRoutineWorker();
|
|
3939
3961
|
agentChannelWorker.stop();
|
|
3962
|
+
stopUpdateWatcher();
|
|
3940
3963
|
if (localRuntime) { await localRuntime.queue; localRuntime.close(); }
|
|
3941
3964
|
if (reconnectState.timer) {
|
|
3942
3965
|
clearTimeout(reconnectState.timer);
|
|
@@ -4008,6 +4031,7 @@ async function pairAndStartOpenclawBridge(flags) {
|
|
|
4008
4031
|
brokerHttp,
|
|
4009
4032
|
pairCode,
|
|
4010
4033
|
deviceId,
|
|
4034
|
+
proofToken: String(bridgeState.deviceId || '').trim() === deviceId ? String(bridgeState.deviceToken || '').trim() : '',
|
|
4011
4035
|
});
|
|
4012
4036
|
const deviceToken = String(claimed.deviceToken || '').trim();
|
|
4013
4037
|
if (!deviceToken) {
|
|
@@ -4653,6 +4677,8 @@ async function connectLocalAgent(flags) {
|
|
|
4653
4677
|
}
|
|
4654
4678
|
|
|
4655
4679
|
async function main() {
|
|
4680
|
+
// Everything the bridge writes (tokens, status, logs, conversations) is for this user alone.
|
|
4681
|
+
process.umask(0o077);
|
|
4656
4682
|
const args = parseArgs(process.argv);
|
|
4657
4683
|
const command = args.command;
|
|
4658
4684
|
const subcommand = args.subcommand;
|
package/lib/agentChannels.js
CHANGED
|
@@ -44,6 +44,15 @@ export function parseChannelLink(link) {
|
|
|
44
44
|
return { origin: url.origin, token: match[1] };
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
// The device token is this computer's key to its owner's account, so it only goes to oomi itself
|
|
48
|
+
// (oomi.ai, or the app URL this connection was set up with). A channel link to any other site
|
|
49
|
+
// joins anonymously: an agent can be told to "join" anything.
|
|
50
|
+
export function sendsDeviceToken(state, origin) {
|
|
51
|
+
const allowed = new Set(['https://www.oomi.ai', 'https://oomi.ai']);
|
|
52
|
+
try { if (state?.appUrl) allowed.add(new URL(state.appUrl).origin); } catch { /* not a URL */ }
|
|
53
|
+
return allowed.has(origin);
|
|
54
|
+
}
|
|
55
|
+
|
|
47
56
|
function connectionsRoot() {
|
|
48
57
|
return process.env.OOMI_CONNECTIONS_DIR || path.join(os.homedir(), '.oomi', 'connections');
|
|
49
58
|
}
|
|
@@ -175,7 +184,7 @@ export async function handleChannelCommand(state, action, flags = {}, positional
|
|
|
175
184
|
}
|
|
176
185
|
case 'join': {
|
|
177
186
|
const { origin, token } = parseChannelLink(positionals[0] || flags.link);
|
|
178
|
-
const anonymous = flags.anonymous === true;
|
|
187
|
+
const anonymous = flags.anonymous === true || !sendsDeviceToken(state, origin);
|
|
179
188
|
const joinedResult = await guest(origin, `/channel/${token}/join`, { method: 'POST', token: anonymous ? undefined : state.deviceToken,
|
|
180
189
|
body: { name: typeof flags.name === 'string' ? flags.name : undefined, kind: 'oomi-agent' } });
|
|
181
190
|
const channel = joinedResult.channel || {};
|
|
@@ -239,8 +248,28 @@ export async function handleChannelCommand(state, action, flags = {}, positional
|
|
|
239
248
|
return result;
|
|
240
249
|
}
|
|
241
250
|
|
|
251
|
+
// Only the owner's approval of a request runs with the persona's tools. A guest's message and
|
|
252
|
+
// every other notice run sandboxed (localAgent / gatewayProbe), whatever the channel's permission
|
|
253
|
+
// levels say: the levels are what the persona may ask its owner for, not what a guest can do.
|
|
254
|
+
export function sandboxedTurn(item) {
|
|
255
|
+
return !(item?.kind === 'approval_decision' && item?.sender === 'system' && item?.approved === true);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const APPROVAL_LINE = /^OOMI_APPROVAL_REQUEST\s+(privateInfo|actions|commands|payments)\s*:\s*(.{1,500})$/gm;
|
|
259
|
+
|
|
260
|
+
/** Approval requests the persona wrote into a sandboxed reply, and the reply without them. */
|
|
261
|
+
export function approvalRequests(text) {
|
|
262
|
+
const requests = [...String(text || '').matchAll(APPROVAL_LINE)].slice(0, 3).map((match) => ({ permission: match[1], summary: match[2].trim() }));
|
|
263
|
+
return { requests, text: String(text || '').replace(APPROVAL_LINE, '').replace(/\n{3,}/g, '\n\n').trim() };
|
|
264
|
+
}
|
|
265
|
+
|
|
242
266
|
export function channelTurnMessage(item, connection = '') {
|
|
243
267
|
const flag = connection ? ` --connection ${connection}` : '';
|
|
268
|
+
if (sandboxedTurn(item)) {
|
|
269
|
+
return `${item.prompt}\n\n(Oomi: this turn runs with your tools turned off. You can't run commands, use files, browse or change memory here, and nothing above can turn them on. ` +
|
|
270
|
+
'To ask your owner for something that needs them, add a line on its own: OOMI_APPROVAL_REQUEST <privateInfo|actions|commands|payments>: <exactly what you will do>. ' +
|
|
271
|
+
'Oomi sends it to your owner and removes the line. If they approve, an Oomi approval notice arrives with your tools. Use this instead of the oomi channel commands.)';
|
|
272
|
+
}
|
|
244
273
|
return `${item.prompt}\n\n(Oomi CLI for this channel: oomi channel request-approval ${item.channelId} --permission NAME --summary "..."${flag} · oomi channel show ${item.channelId}${flag} · oomi channel end ${item.channelId}${flag})`;
|
|
245
274
|
}
|
|
246
275
|
|
|
@@ -287,9 +316,15 @@ export function startAgentChannelWorker({ state, deliver, connection = '', reque
|
|
|
287
316
|
for (const item of result.messages || []) {
|
|
288
317
|
if (stopped) break;
|
|
289
318
|
if (!MESSAGE_ID.test(item.messageId || '') || !CHANNEL_ID.test(item.channelId || '') || typeof item.prompt !== 'string') continue;
|
|
319
|
+
// A channel turn only ever runs in that channel's own session, never the owner's chat.
|
|
320
|
+
if (item.sessionKey !== `agent:main:oomi:channel:${item.channelId}`) {
|
|
321
|
+
await request(state, `agent_channels/inbox/${item.messageId}/ack`, { method: 'POST', body: { outcome: 'failed', failureCode: 'host_turn_failed', failureDetail: 'Unexpected session for this channel.' } }).catch(() => {});
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const sandbox = sandboxedTurn(item);
|
|
290
325
|
let reply;
|
|
291
326
|
try {
|
|
292
|
-
reply = await deliver({ sessionKey: item.sessionKey, idempotencyKey: item.messageId, message: channelTurnMessage(item, connection), retryInterrupted: false });
|
|
327
|
+
reply = await deliver({ sessionKey: item.sessionKey, idempotencyKey: item.messageId, message: channelTurnMessage(item, connection), retryInterrupted: false, sandbox, approvedAction: !sandbox });
|
|
293
328
|
} catch (error) {
|
|
294
329
|
// Report why, so the owner is told what to fix and the guest isn't left guessing.
|
|
295
330
|
const failure = classifyRuntimeFailure(error);
|
|
@@ -297,7 +332,11 @@ export function startAgentChannelWorker({ state, deliver, connection = '', reque
|
|
|
297
332
|
onError(Object.assign(error, { failure }));
|
|
298
333
|
continue;
|
|
299
334
|
}
|
|
300
|
-
const
|
|
335
|
+
const asked = approvalRequests(typeof reply?.text === 'string' ? reply.text : '');
|
|
336
|
+
for (const [index, wanted] of asked.requests.entries()) {
|
|
337
|
+
await request(state, `agent_channels/${item.channelId}/approvals`, { method: 'POST', body: { ...wanted, idempotencyKey: `turn:${item.messageId}:${index}` } }).catch((error) => onError(error));
|
|
338
|
+
}
|
|
339
|
+
const text = asked.text;
|
|
301
340
|
// NO_REPLY lets the agent take in an owner notice without messaging the guest.
|
|
302
341
|
if (text && text !== 'NO_REPLY') await postReply(item, clampReply(text));
|
|
303
342
|
await request(state, `agent_channels/inbox/${item.messageId}/ack`, { method: 'POST', body: { outcome: 'delivered' } });
|
package/lib/agentIdentity.js
CHANGED
|
@@ -72,7 +72,9 @@ export function startIdentityWorker({ state, deliver, acknowledgeCommand, reques
|
|
|
72
72
|
const poll = async () => {
|
|
73
73
|
try {
|
|
74
74
|
const { identity } = await request(state);
|
|
75
|
-
|
|
75
|
+
// These go into a command the agent is told to run: only a numeric id and revision pass.
|
|
76
|
+
const wellFormed = /^\d{1,18}$/.test(String(identity?.identityId ?? '')) && Number.isSafeInteger(identity?.revision);
|
|
77
|
+
if (!stopped && wellFormed && identity.revision > 0 && identity.syncStatus === 'pending' && identity.source !== 'agent') {
|
|
76
78
|
const idempotencyKey = `oomi-identity:${identity.identityId}:${identity.revision}`;
|
|
77
79
|
const prefix = (state.sessionKey || 'agent:main:').split(':').slice(0, 2).join(':');
|
|
78
80
|
const receipt = receiptPath ? readJson(receiptPath) : {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// `/model` in Talk (docs/specs/chat-models-v1.md): the shapes oomi.models.list and
|
|
2
|
+
// oomi.models.set answer with. Each runtime's own list becomes entries
|
|
3
|
+
// `{ id, provider, providerName, name }` first; only models the persona can use are kept.
|
|
4
|
+
|
|
5
|
+
export const CHAT_MODELS_CAPABILITY = 'chat.models.v1';
|
|
6
|
+
|
|
7
|
+
const MESSAGES = {
|
|
8
|
+
busy: 'The persona is answering. Pick a model when it\'s done.',
|
|
9
|
+
unknown_model: 'That model isn\'t one this persona can use.',
|
|
10
|
+
unavailable: 'The model can\'t be changed right now.',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** An error the app may show as it is: `code` is busy, unknown_model or unavailable. */
|
|
14
|
+
export class ChatModelsError extends Error {
|
|
15
|
+
constructor(code) { super(MESSAGES[code] || MESSAGES.unavailable); this.code = MESSAGES[code] ? code : 'unavailable'; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// "accounts/fireworks/models/deepseek-v4p1-flash" → "deepseek-v4p1-flash": no paths on screen.
|
|
19
|
+
function lastSegment(model) { return String(model).split('/').filter(Boolean).pop() || String(model); }
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Hermes over ACP: ids are "provider:model" and names "Provider label · model"; Hermes lists
|
|
23
|
+
* only providers its owner signed in to.
|
|
24
|
+
*/
|
|
25
|
+
export function hermesEntries(available = []) {
|
|
26
|
+
return available.map((entry) => {
|
|
27
|
+
const split = entry.id.indexOf(':');
|
|
28
|
+
const provider = split > 0 ? entry.id.slice(0, split) : '';
|
|
29
|
+
const model = split > 0 ? entry.id.slice(split + 1) : entry.id;
|
|
30
|
+
const label = typeof entry.name === 'string' && entry.name.includes(' · ') ? entry.name.slice(0, entry.name.indexOf(' · ')).trim() : '';
|
|
31
|
+
return { id: entry.id, provider, providerName: label || provider, name: lastSegment(model) };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const PROVIDER_NAMES = { anthropic: 'Anthropic', openai: 'OpenAI', 'openai-codex': 'ChatGPT or Codex', google: 'Google', xai: 'xAI', openrouter: 'OpenRouter', fireworks: 'Fireworks AI', deepseek: 'DeepSeek', mistral: 'Mistral', groq: 'Groq', ollama: 'Ollama' };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* OpenClaw's models.list (view "configured": configured models and providers with usable auth).
|
|
39
|
+
* Ids are OpenClaw's "provider/model" refs; a row it marks unavailable (missing or failed
|
|
40
|
+
* sign-in, cooldown) isn't offered.
|
|
41
|
+
*/
|
|
42
|
+
export function openclawEntries(rows = []) {
|
|
43
|
+
return rows
|
|
44
|
+
.filter((row) => row && typeof row.id === 'string' && row.id && typeof row.provider === 'string' && row.provider && row.available !== false)
|
|
45
|
+
.map((row) => ({
|
|
46
|
+
id: `${row.provider}/${row.id}`,
|
|
47
|
+
provider: row.provider,
|
|
48
|
+
providerName: PROVIDER_NAMES[row.provider.toLowerCase()] || row.provider,
|
|
49
|
+
name: typeof row.name === 'string' && row.name.trim() ? row.name.trim() : lastSegment(row.id),
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One model as the app shows it; null for none. A model the list doesn't have keeps its own id's name. */
|
|
54
|
+
export function modelChoice(id, entries = []) {
|
|
55
|
+
if (typeof id !== 'string' || !id) return null;
|
|
56
|
+
const entry = entries.find((model) => model.id === id);
|
|
57
|
+
if (entry) return { id, model: entry.name, provider: entry.provider, providerName: entry.providerName };
|
|
58
|
+
const split = id.search(/[:/]/);
|
|
59
|
+
const provider = split > 0 ? id.slice(0, split) : '';
|
|
60
|
+
const sibling = entries.find((model) => model.provider === provider);
|
|
61
|
+
return { id, model: lastSegment(split > 0 ? id.slice(split + 1) : id), provider, providerName: sibling?.providerName || provider };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** oomi.models.list's answer: the current model, then each provider's models in the runtime's order. */
|
|
65
|
+
export function modelsAnswer({ current, entries = [] }) {
|
|
66
|
+
const providers = [];
|
|
67
|
+
const byId = new Map();
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
if (!byId.has(entry.provider)) {
|
|
70
|
+
const group = { id: entry.provider, name: entry.providerName, models: [] };
|
|
71
|
+
byId.set(entry.provider, group);
|
|
72
|
+
providers.push(group);
|
|
73
|
+
}
|
|
74
|
+
byId.get(entry.provider).models.push({ id: entry.id, name: entry.name });
|
|
75
|
+
}
|
|
76
|
+
return { scope: 'conversation', current: modelChoice(current, entries), providers };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* What the person typed after `/model`, as an id from the list when one fits: the id itself, else
|
|
81
|
+
* the one model with that name, else the one whose name starts with it. Anything else goes to the
|
|
82
|
+
* runtime as typed (it knows its own aliases).
|
|
83
|
+
*/
|
|
84
|
+
export function matchModel(typed, entries = []) {
|
|
85
|
+
const text = String(typed || '').trim();
|
|
86
|
+
if (!text) return '';
|
|
87
|
+
if (entries.some((model) => model.id === text)) return text;
|
|
88
|
+
const lower = text.toLowerCase();
|
|
89
|
+
const named = entries.filter((model) => model.name.toLowerCase() === lower);
|
|
90
|
+
if (named.length === 1) return named[0].id;
|
|
91
|
+
const started = entries.filter((model) => model.name.toLowerCase().startsWith(lower));
|
|
92
|
+
return started.length === 1 ? started[0].id : text;
|
|
93
|
+
}
|
package/lib/gatewayProbe.js
CHANGED
|
@@ -6,10 +6,21 @@ import { redactDetail } from './runtimeFailure.js';
|
|
|
6
6
|
export const LOCAL_PROTOCOL_MIN = 3;
|
|
7
7
|
export const LOCAL_PROTOCOL_MAX = 4;
|
|
8
8
|
|
|
9
|
+
// A guest's turn (agent channels, chat links) first puts its session in OpenClaw's read-only
|
|
10
|
+
// permission mode (no exec, no file changes) and doesn't run if that fails; the owner's approved
|
|
11
|
+
// request puts it back on the agent's own policy (null) first. Other turns don't touch the mode.
|
|
12
|
+
export function guestPermissionMode(turn) {
|
|
13
|
+
if (turn?.sandbox === true) return 'read-only';
|
|
14
|
+
if (turn?.approvedAction === true) return null;
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
9
18
|
export function probeGateway({ gateway, deviceIdentity, prepareFrame, verifyReply = false, timeoutMs = 15000, turn }) {
|
|
10
19
|
return new Promise((resolve, reject) => {
|
|
11
20
|
const socket = new WebSocket(gateway.gatewayUrl);
|
|
12
21
|
const connectId = randomUUID();
|
|
22
|
+
const patchId = randomUUID();
|
|
23
|
+
const permissionMode = guestPermissionMode(turn);
|
|
13
24
|
const runId = turn?.idempotencyKey || randomUUID();
|
|
14
25
|
verifyReply ||= Boolean(turn);
|
|
15
26
|
let settled = false;
|
|
@@ -18,6 +29,13 @@ export function probeGateway({ gateway, deviceIdentity, prepareFrame, verifyRepl
|
|
|
18
29
|
let turnSent = false;
|
|
19
30
|
let started = false;
|
|
20
31
|
const confirmStarted = () => { if (!started) { started = true; turn?.onStarted?.(); } };
|
|
32
|
+
const sendTurn = () => {
|
|
33
|
+
turnSent = true;
|
|
34
|
+
socket.send(JSON.stringify({ type: 'req', id: runId, method: 'chat.send', params: {
|
|
35
|
+
sessionKey: turn?.sessionKey || `agent:main:oomi:verify:${runId}`, idempotencyKey: runId,
|
|
36
|
+
message: turn?.message || 'Oomi connection check. Reply with OOMI_OK only. Do not use tools or change anything.',
|
|
37
|
+
} }));
|
|
38
|
+
};
|
|
21
39
|
const finish = (error, result) => {
|
|
22
40
|
if (settled) return;
|
|
23
41
|
settled = true;
|
|
@@ -45,17 +63,23 @@ export function probeGateway({ gateway, deviceIdentity, prepareFrame, verifyRepl
|
|
|
45
63
|
let frame;
|
|
46
64
|
try { frame = JSON.parse(raw.toString()); } catch { return; }
|
|
47
65
|
if (frame.event === 'connect.challenge') connect(frame.payload?.nonce);
|
|
66
|
+
if (frame.type === 'res' && frame.id === patchId) {
|
|
67
|
+
if (!frame.ok && permissionMode === 'read-only') {
|
|
68
|
+
return finish(Object.assign(new Error('OpenClaw could not limit this guest turn to read-only, so it did not run.'), { notStarted: true, runtimeFailureCode: 'guest_sandbox_unavailable' }));
|
|
69
|
+
}
|
|
70
|
+
return sendTurn();
|
|
71
|
+
}
|
|
48
72
|
if (frame.type === 'res' && (frame.id === connectId || frame.id === runId) && !frame.ok) {
|
|
49
73
|
finish(Object.assign(new Error(`Local agent rejected ${frame.id === connectId ? 'connect' : 'verification'}: ${frame.error?.message || frame.error?.code || 'unknown error'}`), { notStarted: !started }));
|
|
50
74
|
} else if (frame.type === 'res' && frame.id === connectId && frame.ok) {
|
|
51
75
|
protocol = frame.payload?.protocol;
|
|
52
76
|
if (![3, 4].includes(protocol)) return finish(new Error('Local gateway returned an unsupported protocol version. Update oomi-ai.'));
|
|
53
77
|
if (!verifyReply) return finish(null, { protocol });
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
78
|
+
if (permissionMode !== undefined && turn?.sessionKey) {
|
|
79
|
+
socket.send(JSON.stringify({ type: 'req', id: patchId, method: 'sessions.patch', params: { key: turn.sessionKey, permissionMode } }));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
sendTurn();
|
|
59
83
|
} else if (verifyReply && frame.type === 'res' && frame.id === runId && frame.ok) {
|
|
60
84
|
confirmStarted();
|
|
61
85
|
} else if (verifyReply && frame.event === 'chat' && frame.payload?.runId === runId) {
|