openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 7.35 kB
JavaScript
import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{o as isSqliteLockError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as SqliteSchemaVersionError}from"./sqlite-user-version-DaJ6mdUV.mjs";import{a as isPidDefinitelyDead}from"./pid-alive-DDtSxW5l.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{t as restoreNativeErrorResponse}from"./native-error-response-vI2qu5y2.mjs";import{t as setSafeTimeout}from"./timer-delay-MMasSg9I.mjs";import{a as readNativeHookRelayProvider,i as readNativeHookRelayEvent,o as readNonEmptyString,r as normalizePositiveInteger}from"./native-hook-relay-utils-BshMn1ot.mjs";import path from"node:path";import{request}from"node:http";
//!src/agents/harness/native-hook-relay-constants.ts
const DEFAULT_RELAY_TIMEOUT_MS=5e3;const NATIVE_HOOK_INEXACT_NUMBER_PATHS_FIELD=`openclaw_inexact_number_paths`;
//!src/agents/harness/native-hook-relay-response-codec.ts
function renderJsonResponse(e){return{stdout:`${JSON.stringify(e)}\n`,stderr:``,exitCode:0}}const codexNativeHookRelayResponseCodec={renderNoopResponse(){return{stdout:``,stderr:``,exitCode:0}},renderPreToolUseBlockResponse(e,t){return{...renderJsonResponse({hookSpecificOutput:{hookEventName:`PreToolUse`,permissionDecision:`deny`,permissionDecisionReason:e}}),...t?{failureDisposition:t}:{}}},renderPreToolUseUpdatedInputResponse(e){return renderJsonResponse({hookSpecificOutput:{hookEventName:`PreToolUse`,permissionDecision:`allow`,updatedInput:e}})},renderPermissionDecisionResponse(e,t){return renderJsonResponse({hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:e===`allow`?{behavior:`allow`}:{behavior:`deny`,message:t?.trim()||`Denied by OpenClaw`}}})},renderBeforeAgentFinalizeReviseResponse:e=>renderJsonResponse({decision:`block`,reason:e}),renderBeforeAgentFinalizeStopResponse:e=>renderJsonResponse({continue:false,...e?.trim()?{stopReason:e.trim()}:{}})};
//!src/agents/harness/native-hook-relay-client-store.ts
async function readNativeHookRelayClientBridgeRecord(e){e.signal?.throwIfAborted();const t=path.resolve(e.stateDbPath??resolveOpenClawStateSqlitePath());const n={relayId:e.relayId,stateDbPath:t};if(!process.versions.bun){const{readNativeHookRelayClientRecord:t}=await import(`./native-hook-relay-client-read-BPBwpKaZ.mjs`);e.signal?.throwIfAborted();return t(n,0)}const[{WorkerTaskPool:r},{resolveRuntimeProcessEntrypointUrl:i}]=await Promise.all([import(`./worker-task-pool-rzaYfBJL.mjs`),import(`./runtime-process-url-2KN-4FwE.mjs`)]);const a=new r({workerUrl:i(`nativeHookRelayClient`),workerClass:`singleton`});try{const r=await a.run(n,{inputBytes:2*(e.relayId.length+t.length),signal:e.signal});if(!r.ok)throw r.newerSchema?new SqliteSchemaVersionError(r.error.message):restoreNativeErrorResponse(r.error);return r.record}finally{await a.close()}}
//!src/agents/harness/native-hook-relay-client.ts
const MAX_NATIVE_HOOK_BRIDGE_RESPONSE_BYTES=5e6;const NATIVE_HOOK_BRIDGE_RETRY_INTERVAL_MS=25;const NATIVE_HOOK_BRIDGE_REPLACEMENT_RECORD_GRACE_MS=250;const NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR=`native hook relay bridge stale registration`;async function invokeNativeHookRelayBridge(e){const t=readNativeHookRelayProvider(e.provider);const n=readNonEmptyString(e.relayId,`relayId`);const r=readNativeHookRelayEvent(e.event);const i=normalizePositiveInteger(e.timeoutMs,DEFAULT_RELAY_TIMEOUT_MS);const a=normalizePositiveInteger(e.registrationTimeoutMs,i);const o=performance.now();const s=new AbortController;const c=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal;const l=setSafeTimeout(()=>s.abort(/* @__PURE__ */ new Error(`native hook relay bridge timed out`)),i);l.unref();let u=/* @__PURE__ */ new Error(`native hook relay bridge not found`);try{while(performance.now()-o<i){c.throwIfAborted();try{const a=await readNativeHookRelayClientBridgeRecord({relayId:n,stateDbPath:e.stateDbPath,signal:c});c.throwIfAborted();if(!a||isPidDefinitelyDead(a.pid))throw new Error(`native hook relay bridge not found`);if(Date.now()>a.expiresAtMs)throw new Error(`native hook relay bridge expired`);if(performance.now()-o>=i)throw new Error(`native hook relay bridge timed out`);const s=await postNativeHookRelayBridgeRecord({record:a,signal:c,payload:{provider:t,relayId:n,event:r,generation:e.generation,rawPayload:e.rawPayload}});c.throwIfAborted();if(performance.now()-o>=i)throw new Error(`native hook relay bridge timed out`);return s}catch(e){c.throwIfAborted();u=e;const t=performance.now()-o;if(e instanceof Error&&e.message===`native hook relay bridge not found`&&t>=a)break;if(!isRetryableNativeHookRelayBridgeLookupError({error:e,elapsedMs:t}))break;await sleep(Math.min(NATIVE_HOOK_BRIDGE_RETRY_INTERVAL_MS,i-t),c)}}c.throwIfAborted();throw u instanceof Error?u:new Error(String(u))}finally{clearTimeout(l)}}function postNativeHookRelayBridgeRecord(e){e.signal.throwIfAborted();const t=JSON.stringify(e.payload);return new Promise((n,r)=>{let i;const fail=e=>{i??={ok:false,error:toErrorObject(e,`Non-Error rejection`)};a.destroy()};const a=request({hostname:e.record.hostname,method:`POST`,path:`/invoke`,port:e.record.port,agent:false,signal:e.signal,headers:{authorization:`Bearer ${e.record.token}`,"content-type":`application/json`,"content-length":Buffer.byteLength(t)}},e=>{let t=``;let n=0;e.setEncoding(`utf8`);e.on(`data`,e=>{n+=Buffer.byteLength(e);if(n>MAX_NATIVE_HOOK_BRIDGE_RESPONSE_BYTES){fail(/* @__PURE__ */ new Error(`native hook relay bridge response too large`));return}t+=e});e.on(`error`,fail);e.on(`end`,()=>{if(i)return;try{const e=JSON.parse(t);if(e.ok)i={ok:true,value:e.result};else fail(new Error(e.error||`native hook relay bridge failed`))}catch(e){fail(e)}})});a.on(`error`,fail);a.once(`close`,()=>{if(i?.ok)n(i.value);else r(i?.error??/* @__PURE__ */ new Error(`native hook relay bridge closed before its response`))});a.end(t)})}function isRetryableNativeHookRelayBridgeError(e){const t=e.code;return t===`ENOENT`||t===`ECONNREFUSED`||t===`EAGAIN`||isSqliteLockError(e)||e instanceof Error&&e.message===`native hook relay bridge not found`}function isRetryableNativeHookRelayBridgeLookupError(e){return isRetryableNativeHookRelayBridgeError(e.error)||e.elapsedMs<250&&isNativeHookRelayBridgeStaleRegistrationError(e.error)}function isNativeHookRelayBridgeStaleRegistrationError(e){return e instanceof Error&&e.message===`native hook relay bridge stale registration`}function renderNativeHookRelayUnavailableResponse(e){readNativeHookRelayProvider(e.provider);const t=readNativeHookRelayEvent(e.event);const n=e.message?.trim()||`Native hook relay unavailable`;if(t===`pre_tool_use`){if(e.preToolUseUnavailable===`noop`)return codexNativeHookRelayResponseCodec.renderNoopResponse();return codexNativeHookRelayResponseCodec.renderPreToolUseBlockResponse(n)}if(t===`permission_request`)return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse(`deny`,n);return codexNativeHookRelayResponseCodec.renderNoopResponse()}export{codexNativeHookRelayResponseCodec as a,renderNativeHookRelayUnavailableResponse as i,invokeNativeHookRelayBridge as n,DEFAULT_RELAY_TIMEOUT_MS as o,isNativeHookRelayBridgeStaleRegistrationError as r,NATIVE_HOOK_INEXACT_NUMBER_PATHS_FIELD as s,NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR as t};