UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

608 lines (607 loc) • 23.6 kB
import "./redact-BDinS1q9.js"; import "./errors-BxyFnvP3.js"; import "./unhandled-rejections-CDJ8dOVP.js"; import "./logger-kwZIqwuw.js"; import "./paths-ViKUYWUK.js"; import "./tmp-openclaw-dir-idKIOMmb.js"; import "./theme-CdOoMzRk.js"; import "./globals-DBUMOBZ8.js"; import { m as defaultRuntime } from "./subsystem-DISldKSB.js"; import "./ansi-BEJF8NKS.js"; import "./boolean-C3GkJetE.js"; import "./env-Dnra1IpT.js"; import "./warning-filter-CBhOcgHd.js"; import "./utils-CS0Ikux6.js"; import "./links-8xRhWBQL.js"; import "./paths-C4Oy7wjk.js"; import "./auth-profiles-DRuJBw5y.js"; import { l as normalizeMainKey, p as scopedHeartbeatWakeOptions } from "./session-key-DAhnzjyr.js"; import "./agent-scope-bjWqU22i.js"; import "./boundary-path-Dm0QJ7-y.js"; import "./boundary-file-read-DcZxlWD8.js"; import "./logger-BmpSCz93.js"; import "./exec-B5_AYfQG.js"; import "./workspace-D4K6QX9X.js"; import "./model-selection-BnFtDmP7.js"; import { s as loadConfig } from "./io-y3Az_Onx.js"; import "./shell-env-BOu7XeT_.js"; import "./safe-text-yavot2qw.js"; import "./version-CD3oP1-d.js"; import "./env-substitution-O6uabUmO.js"; import "./includes-Bj3eLUWH.js"; import "./zod-schema.providers-core-COy5nBQ0.js"; import "./legacy-web-search-BB-ZHEhz.js"; import "./registry-C5UkPpaO.js"; import "./config-state-Br0ucqMb.js"; import "./min-host-version-RMBWtIAR.js"; import "./manifest-registry-B5JNQdOM.js"; import "./runtime-guard-PhQ6PwQa.js"; import "./avatar-policy-B5nOfso_.js"; import "./ip-Ce8EDTBZ.js"; import "./zod-schema.agent-runtime-Dtg4Jy6G.js"; import "./zod-schema.core-BuVz8Rk7.js"; import "./config-D4zN4BRl.js"; import "./file-lock-DEiVq2ow.js"; import "./audit-fs-DTQIjp2r.js"; import "./resolve-B7S4PlnO.js"; import "./profiles-COPO-hHI.js"; import "./tailscale-CxY-91GZ.js"; import "./tailnet-DHiKSG7V.js"; import "./net-JAg9zL0G.js"; import "./auth-Buq0Niri.js"; import "./credentials-D8pfRimu.js"; import "./message-channel-BliByQBl.js"; import { l as updateSessionStore } from "./store-C5UK26Ce.js"; import "./runtime-Iz8uZ7EU.js"; import { l as normalizeChannelId } from "./plugins-B09-vgme.js"; import "./sessions-D9ZgHCHb.js"; import "./paths-rhN9LKM_.js"; import "./session-write-lock-va3qZE6f.js"; import { dn as loadOrCreateDeviceIdentity } from "./method-scopes-BiEi0X2g.js"; import "./call-CQbSO4Fr.js"; import "./prompt-style-C4CV4Y_p.js"; import "./ports-lsof-BLEgL_Gn.js"; import "./restart-stale-pids-BsPvlGJd.js"; import "./ports-FldL_Lhq.js"; import "./logging-CznuqaMu.js"; import "./commands-C6oAw_H-.js"; import "./issue-format-BtLIwOtN.js"; import "./identity-Dp-UIak4.js"; import "./heartbeat-Bdfr_onc.js"; import { Ds as loadSessionEntry, Gy as resolveOutboundTarget, Hp as requestHeartbeatNow, Os as migrateAndPruneGatewaySessionStoreKey, Sd as deliverOutboundPayloads, aa as createOutboundSendDeps, ta as agentCommandFromIngress, xd as buildOutboundSessionContext } from "./pi-embedded-CbCYZxIb.js"; import "./internal-hooks-CIUghoK4.js"; import "./multimodal-B8yEZcl5.js"; import "./memory-search-B_aq08y5.js"; import "./provider-catalog-rVN7ZbR5.js"; import "./secret-input-DXoOLNgb.js"; import "./bindings-CFudGB9Z.js"; import "./resolve-route-DwFWP4JW.js"; import "./routing-zOQ0wwtV.js"; import "./identity-file-DVLib087.js"; import "./outbound-runtime-m-y0nd6F.js"; import "./provider-env-vars-CpUJqT5v.js"; import "./provider-auth-input-Bus9W_qh.js"; import "./provider-model-minimax-DSmX4BNO.js"; import "./provider-models-BKjzpTsb.js"; import "./anthropic-vertex-provider-B2x4YywE.js"; import "./provider-catalog-BTgF8VyO.js"; import "./provider-catalog-D0IlX18O.js"; import "./provider-catalog-BTmUX0Mp.js"; import "./provider-catalog-sph_Rl63.js"; import "./provider-catalog-C7tUyBwV.js"; import "./provider-catalog-C8dPZpHW.js"; import "./provider-catalog-BJNff1VI.js"; import "./provider-catalog-IAdymoqT.js"; import "./provider-catalog-Bjc7evzh.js"; import "./models-config.providers.discovery-CjkO08q6.js"; import "./text-runtime-DVXt5xhi.js"; import "./tool-catalog-BjSY4C4F.js"; import "./docker-Bhjg8g2t.js"; import "./sandbox-DTlKNieF.js"; import "./common-zReYuoMM.js"; import "./image-ops-By4YfyWa.js"; import "./thinking-CJoSRIGR.js"; import "./path-alias-guards-CwRM04O1.js"; import "./sandbox-paths-Cn8i8Jxm.js"; import "./channel-actions-fV93bLjV.js"; import "./mime-CsUtzcn2.js"; import "./ssrf-0bPJMoZR.js"; import "./fetch-guard-CYl1q2XH.js"; import "./provider-web-search-COZNygbd.js"; import "./manager-Bw8JrihM.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import "./status-helpers-Cflmo90d.js"; import "./conversation-runtime-nmWgJSXS.js"; import "./runtime-whatsapp-boundary-XjdkYMz_.js"; import "./pairing-store-BGKLrjo6.js"; import "./json-store--JDX3zNL.js"; import "./secret-file-Bif7RlZ-.js"; import "./channel-config-schema-CgpS17zB.js"; import "./setup-binary-C2MYZTCc.js"; import "./archive-pOxyr9r4.js"; import "./fs-safe-DZyOgpPN.js"; import "./signal-cli-install-fVOL9FvX.js"; import "./setup-wizard-proxy-DoOpOF8S.js"; import "./setup-BI3ohdrT.js"; import "./dm-policy-shared-DtcQProI.js"; import "./runtime-env-DQOYrXVl.js"; import "./temp-path-B91lt0LF.js"; import "./diagnostic-CDTtMQBT.js"; import "./logging-CCTKg_fh.js"; import "./config-runtime-BYNizC50.js"; import "./level-overrides-DzIzQ3ZY.js"; import "./exec-approvals-BF_Qfdq8.js"; import "./webhook-ingress-D-H5frou.js"; import { r as enqueueSystemEvent } from "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import "./hook-runtime-BUYmDbaA.js"; import "./templating-BDXRiJUh.js"; import "./channel-reply-pipeline-BxH4-AP2.js"; import "./reply-history-n7nOPLta.js"; import "./commands-registry.data-BFXJWoqi.js"; import "./commands-registry-Bh9pJ817.js"; import "./frontmatter-CP5371Rm.js"; import "./env-overrides-BNSo89u5.js"; import "./skills-M0AZJeXx.js"; import "./skills-remote-BHxDA4Jw.js"; import "./workspace-dirs-DqDLiRvZ.js"; import "./pairing-token-DAszGmwD.js"; import "./skill-commands-D73dGR_l.js"; import "./config-CLRQPUSt.js"; import "./routes-XT2JfvT-.js"; import "./ssh-tunnel-LM52qY6N.js"; import "./server-middleware-BP59C6FL.js"; import "./provider-auth-ref-CQEp9sp3.js"; import "./provider-auth-helpers-Do3RFvdi.js"; import "./provider-api-key-auth-BEeRW3dq.js"; import "./pairing-labels-D27Y4Vv6.js"; import "./directory-runtime-D9Y42mW-.js"; import "./read-only-account-inspect-CJPRBFj7.js"; import "./src-BoNU6eQs.js"; import "./web-media-PKy3RbRG.js"; import "./media-understanding-BDOSvuM9.js"; import "./web-media-CiSbdGPs.js"; import "./state-paths-Dvb3Mfl3.js"; import "./llm-task-Br6Ixjlh.js"; import "./pi-model-discovery-DO3tFksS.js"; import "./exec-inline-eval-CpmxWJsW.js"; import "./target-registry-9OUOvlxj.js"; import "./external-content-DZI9vlJn.js"; import "./brave-onFD06fq.js"; import "./duckduckgo-CZuAOfiQ.js"; import "./exa-5bwgY04k.js"; import "./security-runtime-xlw0Fxx2.js"; import "./provider-usage-ClxTGn5c.js"; import "./provider-models-Bjv0V4OP.js"; import "./media-understanding-provider-DllGbg-v.js"; import "./media-understanding-provider-BDq4rFL-.js"; import "./provider-onboard-CSnPvkMM.js"; import "./onboard-BU8aRvq7.js"; import "./perplexity-web-search-provider-CI38RNUU.js"; import "./perplexity-CMZbsreI.js"; import "./model-definitions-CLagLj0g.js"; import "./onboard-0P7GBI2D.js"; import "./provider-catalog-CKHo9CRM.js"; import "./provider-models-Dmjtw6kn.js"; import "./stream-C-KGzzT0.js"; import "./web-search-CO1hvu_l.js"; import "./stagger-CFqdtCYL.js"; import "./command-secret-targets-DLs8jC2H.js"; import "./delivery-queue-DHURMSqX.js"; import "./channel-summary-Ctrv7moa.js"; import "./follow-redirects-CVAaqIk4.js"; import "./tool-policy-match-DQWWRSN4.js"; import "./runtime-CAdCdG-M.js"; import "./channel-status-BfM90KqH.js"; import "./discord-core-DLbIyXWy.js"; import "./cli-runtime-Cx1v7N7v.js"; import "./config-presence-DA3j8Nmi.js"; import "./query-expansion-BOJBTXsp.js"; import "./search-manager-DNBHwaee.js"; import "./acp-runtime-BHZj-SLU.js"; import "./telegram-core-DD8gCuaX.js"; import "./audit-BI48Fi3j.js"; import "./gateway-runtime-Dn2qAGY7.js"; import "./connection-auth-Nl2a3tDb.js"; import "./mcp-config-CDIWSqVk.js"; import "./agent-DtXXgp1u.js"; import { d as parseMessageWithAttachments, f as formatForLog, i as registerApnsRegistration, u as normalizeRpcAttachmentsToChatAttachments } from "./push-apns-nhUon0wk.js"; import { randomUUID } from "node:crypto"; //#region src/gateway/server-node-events.ts const MAX_EXEC_EVENT_OUTPUT_CHARS = 180; const MAX_NOTIFICATION_EVENT_TEXT_CHARS = 120; const VOICE_TRANSCRIPT_DEDUPE_WINDOW_MS = 1500; const MAX_RECENT_VOICE_TRANSCRIPTS = 200; const recentVoiceTranscripts = /* @__PURE__ */ new Map(); function normalizeNonEmptyString(value) { if (typeof value !== "string") return null; const trimmed = value.trim(); return trimmed.length > 0 ? trimmed : null; } function normalizeFiniteInteger(value) { return typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : null; } function resolveVoiceTranscriptFingerprint(obj, text) { const eventId = normalizeNonEmptyString(obj.eventId) ?? normalizeNonEmptyString(obj.providerEventId) ?? normalizeNonEmptyString(obj.transcriptId); if (eventId) return `event:${eventId}`; const callId = normalizeNonEmptyString(obj.providerCallId) ?? normalizeNonEmptyString(obj.callId); const sequence = normalizeFiniteInteger(obj.sequence) ?? normalizeFiniteInteger(obj.seq); if (callId && sequence !== null) return `call-seq:${callId}:${sequence}`; const eventTimestamp = normalizeFiniteInteger(obj.timestamp) ?? normalizeFiniteInteger(obj.ts) ?? normalizeFiniteInteger(obj.eventTimestamp); if (callId && eventTimestamp !== null) return `call-ts:${callId}:${eventTimestamp}`; if (eventTimestamp !== null) return `timestamp:${eventTimestamp}|text:${text}`; return `text:${text}`; } function shouldDropDuplicateVoiceTranscript(params) { const previous = recentVoiceTranscripts.get(params.sessionKey); if (previous && previous.fingerprint === params.fingerprint && params.now - previous.ts <= VOICE_TRANSCRIPT_DEDUPE_WINDOW_MS) return true; recentVoiceTranscripts.set(params.sessionKey, { fingerprint: params.fingerprint, ts: params.now }); if (recentVoiceTranscripts.size > MAX_RECENT_VOICE_TRANSCRIPTS) { const cutoff = params.now - VOICE_TRANSCRIPT_DEDUPE_WINDOW_MS * 2; for (const [key, value] of recentVoiceTranscripts) { if (value.ts < cutoff) recentVoiceTranscripts.delete(key); if (recentVoiceTranscripts.size <= MAX_RECENT_VOICE_TRANSCRIPTS) break; } while (recentVoiceTranscripts.size > MAX_RECENT_VOICE_TRANSCRIPTS) { const oldestKey = recentVoiceTranscripts.keys().next().value; if (oldestKey === void 0) break; recentVoiceTranscripts.delete(oldestKey); } } return false; } function compactExecEventOutput(raw) { const normalized = raw.replace(/\s+/g, " ").trim(); if (!normalized) return ""; if (normalized.length <= MAX_EXEC_EVENT_OUTPUT_CHARS) return normalized; const safe = Math.max(1, MAX_EXEC_EVENT_OUTPUT_CHARS - 1); return `${normalized.slice(0, safe)}…`; } function compactNotificationEventText(raw) { const normalized = raw.replace(/\s+/g, " ").trim(); if (!normalized) return ""; if (normalized.length <= MAX_NOTIFICATION_EVENT_TEXT_CHARS) return normalized; const safe = Math.max(1, MAX_NOTIFICATION_EVENT_TEXT_CHARS - 1); return `${normalized.slice(0, safe)}…`; } async function touchSessionStore(params) { const { storePath } = params; if (!storePath) return; await updateSessionStore(storePath, (store) => { const { primaryKey } = migrateAndPruneGatewaySessionStoreKey({ cfg: params.cfg, key: params.sessionKey, store }); store[primaryKey] = { sessionId: params.sessionId, updatedAt: params.now, thinkingLevel: params.entry?.thinkingLevel, fastMode: params.entry?.fastMode, verboseLevel: params.entry?.verboseLevel, reasoningLevel: params.entry?.reasoningLevel, systemSent: params.entry?.systemSent, sendPolicy: params.entry?.sendPolicy, lastChannel: params.entry?.lastChannel, lastTo: params.entry?.lastTo }; }); } function queueSessionStoreTouch(params) { touchSessionStore({ cfg: params.cfg, sessionKey: params.sessionKey, storePath: params.storePath, canonicalKey: params.canonicalKey, entry: params.entry, sessionId: params.sessionId, now: params.now }).catch((err) => { params.ctx.logGateway.warn("voice session-store update failed: " + formatForLog(err)); }); } function parseSessionKeyFromPayloadJSON(payloadJSON) { let payload; try { payload = JSON.parse(payloadJSON); } catch { return null; } if (typeof payload !== "object" || payload === null) return null; const obj = payload; const sessionKey = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : ""; return sessionKey.length > 0 ? sessionKey : null; } function parsePayloadObject(payloadJSON) { if (!payloadJSON) return null; let payload; try { payload = JSON.parse(payloadJSON); } catch { return null; } return typeof payload === "object" && payload !== null ? payload : null; } async function sendReceiptAck(params) { const resolved = resolveOutboundTarget({ channel: params.channel, to: params.to, cfg: params.cfg, mode: "explicit" }); if (!resolved.ok) throw new Error(String(resolved.error)); const session = buildOutboundSessionContext({ cfg: params.cfg, sessionKey: params.sessionKey }); await deliverOutboundPayloads({ cfg: params.cfg, channel: params.channel, to: resolved.to, payloads: [{ text: params.text }], session, bestEffort: true, deps: createOutboundSendDeps(params.deps) }); } const handleNodeEvent = async (ctx, nodeId, evt) => { switch (evt.event) { case "voice.transcript": { const obj = parsePayloadObject(evt.payloadJSON); if (!obj) return; const text = typeof obj.text === "string" ? obj.text.trim() : ""; if (!text) return; if (text.length > 2e4) return; const sessionKeyRaw = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : ""; const cfg = loadConfig(); const rawMainKey = normalizeMainKey(cfg.session?.mainKey); const sessionKey = sessionKeyRaw.length > 0 ? sessionKeyRaw : rawMainKey; const { storePath, entry, canonicalKey } = loadSessionEntry(sessionKey); const now = Date.now(); if (shouldDropDuplicateVoiceTranscript({ sessionKey: canonicalKey, fingerprint: resolveVoiceTranscriptFingerprint(obj, text), now })) return; const sessionId = entry?.sessionId ?? randomUUID(); queueSessionStoreTouch({ ctx, cfg, sessionKey, storePath, canonicalKey, entry, sessionId, now }); const runId = randomUUID(); ctx.addChatRun(runId, { sessionKey: canonicalKey, clientRunId: `voice-${randomUUID()}` }); agentCommandFromIngress({ runId, message: text, sessionId, sessionKey: canonicalKey, thinking: "low", deliver: false, messageChannel: "node", inputProvenance: { kind: "external_user", sourceChannel: "voice", sourceTool: "gateway.voice.transcript" }, senderIsOwner: false, allowModelOverride: false }, defaultRuntime, ctx.deps).catch((err) => { ctx.logGateway.warn(`agent failed node=${nodeId}: ${formatForLog(err)}`); }); return; } case "agent.request": { if (!evt.payloadJSON) return; let link = null; try { link = JSON.parse(evt.payloadJSON); } catch { return; } let message = (link?.message ?? "").trim(); const normalizedAttachments = normalizeRpcAttachmentsToChatAttachments(link?.attachments ?? void 0); let images = []; if (normalizedAttachments.length > 0) try { const parsed = await parseMessageWithAttachments(message, normalizedAttachments, { maxBytes: 5e6, log: ctx.logGateway }); message = parsed.message.trim(); images = parsed.images; } catch { return; } if (!message) return; if (message.length > 2e4) return; let channel = normalizeChannelId(typeof link?.channel === "string" ? link.channel.trim() : "") ?? void 0; let to = typeof link?.to === "string" && link.to.trim() ? link.to.trim() : void 0; const deliverRequested = Boolean(link?.deliver); const wantsReceipt = Boolean(link?.receipt); const receiptText = (typeof link?.receiptText === "string" ? link.receiptText.trim() : "") || "Just received your iOS share + request, working on it."; const sessionKeyRaw = (link?.sessionKey ?? "").trim(); const sessionKey = sessionKeyRaw.length > 0 ? sessionKeyRaw : `node-${nodeId}`; const cfg = loadConfig(); const { storePath, entry, canonicalKey } = loadSessionEntry(sessionKey); const now = Date.now(); const sessionId = entry?.sessionId ?? randomUUID(); await touchSessionStore({ cfg, sessionKey, storePath, canonicalKey, entry, sessionId, now }); if (deliverRequested && (!channel || !to)) { const entryChannel = typeof entry?.lastChannel === "string" ? normalizeChannelId(entry.lastChannel) : void 0; const entryTo = typeof entry?.lastTo === "string" ? entry.lastTo.trim() : ""; if (!channel && entryChannel) channel = entryChannel; if (!to && entryTo) to = entryTo; } const deliver = deliverRequested && Boolean(channel && to); const deliveryChannel = deliver ? channel : void 0; const deliveryTo = deliver ? to : void 0; if (deliverRequested && !deliver) ctx.logGateway.warn(`agent delivery disabled node=${nodeId}: missing session delivery route (channel=${channel ?? "-"} to=${to ?? "-"})`); if (wantsReceipt && deliveryChannel && deliveryTo) sendReceiptAck({ cfg, deps: ctx.deps, sessionKey: canonicalKey, channel: deliveryChannel, to: deliveryTo, text: receiptText }).catch((err) => { ctx.logGateway.warn(`agent receipt failed node=${nodeId}: ${formatForLog(err)}`); }); else if (wantsReceipt) ctx.logGateway.warn(`agent receipt skipped node=${nodeId}: missing delivery route (channel=${deliveryChannel ?? "-"} to=${deliveryTo ?? "-"})`); agentCommandFromIngress({ runId: sessionId, message, images, sessionId, sessionKey: canonicalKey, thinking: link?.thinking ?? void 0, deliver, to: deliveryTo, channel: deliveryChannel, timeout: typeof link?.timeoutSeconds === "number" ? link.timeoutSeconds.toString() : void 0, messageChannel: "node", senderIsOwner: false, allowModelOverride: false }, defaultRuntime, ctx.deps).catch((err) => { ctx.logGateway.warn(`agent failed node=${nodeId}: ${formatForLog(err)}`); }); return; } case "notifications.changed": { const obj = parsePayloadObject(evt.payloadJSON); if (!obj) return; const change = normalizeNonEmptyString(obj.change)?.toLowerCase(); if (change !== "posted" && change !== "removed") return; const key = normalizeNonEmptyString(obj.key); if (!key) return; const { canonicalKey: sessionKey } = loadSessionEntry(normalizeNonEmptyString(obj.sessionKey) ?? `node-${nodeId}`); const packageName = normalizeNonEmptyString(obj.packageName); const title = compactNotificationEventText(normalizeNonEmptyString(obj.title) ?? ""); const text = compactNotificationEventText(normalizeNonEmptyString(obj.text) ?? ""); let summary = `Notification ${change} (node=${nodeId} key=${key}`; if (packageName) summary += ` package=${packageName}`; summary += ")"; if (change === "posted") { const messageParts = [title, text].filter(Boolean); if (messageParts.length > 0) summary += `: ${messageParts.join(" - ")}`; } if (enqueueSystemEvent(summary, { sessionKey, contextKey: `notification:${key}` })) requestHeartbeatNow({ reason: "notifications-event", sessionKey }); return; } case "chat.subscribe": { if (!evt.payloadJSON) return; const sessionKey = parseSessionKeyFromPayloadJSON(evt.payloadJSON); if (!sessionKey) return; ctx.nodeSubscribe(nodeId, sessionKey); return; } case "chat.unsubscribe": { if (!evt.payloadJSON) return; const sessionKey = parseSessionKeyFromPayloadJSON(evt.payloadJSON); if (!sessionKey) return; ctx.nodeUnsubscribe(nodeId, sessionKey); return; } case "exec.started": case "exec.finished": case "exec.denied": { const obj = parsePayloadObject(evt.payloadJSON); if (!obj) return; const sessionKey = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : `node-${nodeId}`; if (!sessionKey) return; if (!(loadConfig().tools?.exec?.notifyOnExit !== false)) return; if (obj.suppressNotifyOnExit === true) return; const runId = typeof obj.runId === "string" ? obj.runId.trim() : ""; const command = typeof obj.command === "string" ? obj.command.trim() : ""; const exitCode = typeof obj.exitCode === "number" && Number.isFinite(obj.exitCode) ? obj.exitCode : void 0; const timedOut = obj.timedOut === true; const output = typeof obj.output === "string" ? obj.output.trim() : ""; const reason = typeof obj.reason === "string" ? obj.reason.trim() : ""; let text = ""; if (evt.event === "exec.started") { text = `Exec started (node=${nodeId}${runId ? ` id=${runId}` : ""})`; if (command) text += `: ${command}`; } else if (evt.event === "exec.finished") { const exitLabel = timedOut ? "timeout" : `code ${exitCode ?? "?"}`; const compactOutput = compactExecEventOutput(output); if (!(timedOut || exitCode !== 0 || compactOutput.length > 0)) return; text = `Exec finished (node=${nodeId}${runId ? ` id=${runId}` : ""}, ${exitLabel})`; if (compactOutput) text += `\n${compactOutput}`; } else { text = `Exec denied (node=${nodeId}${runId ? ` id=${runId}` : ""}${reason ? `, ${reason}` : ""})`; if (command) text += `: ${command}`; } enqueueSystemEvent(text, { sessionKey, contextKey: runId ? `exec:${runId}` : "exec" }); requestHeartbeatNow(scopedHeartbeatWakeOptions(sessionKey, { reason: "exec-event" })); return; } case "push.apns.register": { const obj = parsePayloadObject(evt.payloadJSON); if (!obj) return; const transport = typeof obj.transport === "string" ? obj.transport.trim().toLowerCase() : "direct"; const topic = typeof obj.topic === "string" ? obj.topic : ""; const environment = obj.environment; try { if (transport === "relay") { const gatewayDeviceId = typeof obj.gatewayDeviceId === "string" ? obj.gatewayDeviceId.trim() : ""; const currentGatewayDeviceId = loadOrCreateDeviceIdentity().deviceId; if (!gatewayDeviceId || gatewayDeviceId !== currentGatewayDeviceId) { ctx.logGateway.warn(`push relay register rejected node=${nodeId}: gateway identity mismatch`); return; } await registerApnsRegistration({ nodeId, transport: "relay", relayHandle: typeof obj.relayHandle === "string" ? obj.relayHandle : "", sendGrant: typeof obj.sendGrant === "string" ? obj.sendGrant : "", installationId: typeof obj.installationId === "string" ? obj.installationId : "", topic, environment, distribution: obj.distribution, tokenDebugSuffix: obj.tokenDebugSuffix }); } else await registerApnsRegistration({ nodeId, transport: "direct", token: typeof obj.token === "string" ? obj.token : "", topic, environment }); } catch (err) { ctx.logGateway.warn(`push apns register failed node=${nodeId}: ${formatForLog(err)}`); } return; } default: return; } }; //#endregion export { handleNodeEvent };