UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 9.86 kB
import{v as floorPositiveFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import"./utils-Dlk0IYAa.mjs";import{w as isSubagentSessionKey,x as isCronSessionKey}from"./session-key-BPgKfU2m.mjs";import{n as deriveContextPromptTokens}from"./usage-BBN9S-zv.mjs";import{S as shouldPreserveUserFacingSessionStateForInputProvenance,v as normalizeInputProvenance}from"./input-provenance-TIcSrNt5.mjs";import{g as joinPresentTextSegments}from"./hooks-Bu2gwS_g.mjs";import{n as resolveEffectiveToolFsWorkspaceOnly}from"./tool-fs-policy-BoL1Z1rU.mjs";import{t as log}from"./logger-DQkQvjpf.mjs";import{n as resolveProcessToolScopeKey}from"./bash-process-scope-Dsojdjsr.mjs";import{s as resolveContextEngineCapabilities}from"./context-engine-assembly-attempt-CVa79Nqo.mjs";import{n as resolvePluginTurnContext}from"./plugin-turn-context-BjJCWA-U.mjs";import{t as listActiveProcessSessionReferences}from"./bash-process-references-O2zrHq5Y.mjs";import{t as resolveModelCallUrgency}from"./run-trigger-NFOOospS.mjs";import{t as buildEmbeddedCompactionRuntimeContext}from"./compaction-runtime-context-DPUiHaNA.mjs";import{normalizeStructuredPromptSection}from"@openclaw/ai/internal/shared"; //!src/agents/hook-system-context-boundary.ts const HOOK_SYSTEM_CONTEXT_HEADER=`OpenClaw plugin-injected system context. This block is not workspace file content.`;function wrapPluginSystemContextSection(e){if(typeof e!==`string`)return;const t=normalizeStructuredPromptSection(e);if(!t)return;return`---\n\n${HOOK_SYSTEM_CONTEXT_HEADER}\n\n${t}\n\n---`} //!src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts async function resolvePromptBuildHookResult(e){const t=await resolvePluginTurnContext(e);const logHookFailure=e=>t=>{log.warn(`${e} hook failed: ${String(t)}`)};const n=e.hookRunner?.hasHooks(`before_prompt_build`)?await e.hookRunner.runBeforePromptBuild({prompt:e.prompt,messages:e.messages},e.hookCtx).catch(logHookFailure(`before_prompt_build`)):void 0;const r=n?Object.fromEntries([`systemPrompt`,`prependContext`,`appendContext`,`prependSystemContext`,`appendSystemContext`].flatMap(e=>typeof n[e]===`string`?[[e,n[e]]]:[])):void 0;const i=[t];const joinContext=e=>joinPresentTextSegments([...i,n].map(t=>t?.[e]));return{hasPendingNonPromptBuildContext:i.some(e=>e?.prependContext?.trim()||e?.appendContext?.trim()),...r&&Object.keys(r).length>0?{decisionPromptBuildFields:r}:{},systemPrompt:n?.systemPrompt,...n?.toolsAllow!==void 0?{toolsAllow:n.toolsAllow}:{},prependContext:joinContext(`prependContext`),appendContext:joinContext(`appendContext`),prependSystemContext:wrapPluginSystemContextSection(n?.prependSystemContext),appendSystemContext:wrapPluginSystemContextSection(n?.appendSystemContext)}}function resolvePromptModeForSession(e){return isSubagentSessionKey(e)||isCronSessionKey(e)?`minimal`:`full`}function shouldWarnOnOrphanedUserRepair(e){return e===`user`||e===`manual`}const QUEUED_USER_MESSAGE_MARKER=`[Earlier unanswered user message. Address this request alongside the current input; follow the latest user instruction if they conflict.]`;const QUEUED_INTER_SESSION_MESSAGE_MARKER=`[Queued user message from a previous active turn; preserved as context only. Continue with the active prompt below.]`;const MAX_STRUCTURED_MEDIA_REF_CHARS=300;const MAX_STRUCTURED_JSON_STRING_CHARS=300;const MAX_STRUCTURED_JSON_DEPTH=4;const MAX_STRUCTURED_JSON_ARRAY_ITEMS=16;const MAX_STRUCTURED_JSON_OBJECT_KEYS=32;function summarizeStructuredMediaRef(e,t){if(typeof t!==`string`)return;const n=t.trim();if(!n)return;const r=n.match(/^data:([^;,]+)?(?:;[^,]*)?,/i);if(r)return`[${e}] inline data URI (${r[1]?.trim()||`unknown`}, ${n.length} chars)`;if(n.length>MAX_STRUCTURED_MEDIA_REF_CHARS)return`[${e}] ${truncateUtf16Safe(n,MAX_STRUCTURED_MEDIA_REF_CHARS)}... (${n.length} chars)`;return`[${e}] ${n}`}function summarizeStructuredJsonString(e){const t=summarizeStructuredMediaRef(`value`,e);if(t?.includes(`inline data URI`))return t;const n=e.trim();if(n.length>MAX_STRUCTURED_JSON_STRING_CHARS)return`${truncateUtf16Safe(n,MAX_STRUCTURED_JSON_STRING_CHARS)}... (${n.length} chars)`;return e}function sanitizeStructuredJsonValue(e,t=0,n=/* @__PURE__ */ new WeakSet){if(typeof e===`string`)return summarizeStructuredJsonString(e);if(!e||typeof e!==`object`)return e;if(n.has(e))return`[circular]`;if(t>=MAX_STRUCTURED_JSON_DEPTH)return`[max depth]`;n.add(e);if(Array.isArray(e)){const r=e.slice(0,MAX_STRUCTURED_JSON_ARRAY_ITEMS).map(e=>sanitizeStructuredJsonValue(e,t+1,n));if(e.length>MAX_STRUCTURED_JSON_ARRAY_ITEMS)r.push(`[${e.length-MAX_STRUCTURED_JSON_ARRAY_ITEMS} more items]`);n.delete(e);return r}const r={};let i=0;for(const a in e){if(!Object.hasOwn(e,a))continue;i+=1;if(i<=MAX_STRUCTURED_JSON_OBJECT_KEYS)r[a]=sanitizeStructuredJsonValue(e[a],t+1,n)}if(i>MAX_STRUCTURED_JSON_OBJECT_KEYS)r[`__truncated`]=`${i-MAX_STRUCTURED_JSON_OBJECT_KEYS} more keys`;n.delete(e);return r}function stringifyStructuredJsonFallback(e){try{const t=JSON.stringify(sanitizeStructuredJsonValue(e));if(!t||t===`{}`)return;const n=t.replace(/data:[^"'\\\s]+/gi,e=>`[inline data URI: ${e.length} chars]`);return n.length>1e3?`${truncateUtf16Safe(n,1e3)}... (${n.length} chars)`:n}catch{return}}function stringifyStructuredContentPart(e){if(!e||typeof e!==`object`)return;const t=e;if(t.type===`text`)return(typeof t.text===`string`?t.text.trim():``)||void 0;if(t.type===`image_url`){const e=t.image_url;return summarizeStructuredMediaRef(`image_url`,typeof e===`string`?e:e&&typeof e===`object`?e.url:void 0)}if(t.type===`image`||t.type===`input_image`)return summarizeStructuredMediaRef(t.type,t.url)??summarizeStructuredMediaRef(t.type,t.source);if(typeof t.type===`string`){const e=summarizeStructuredMediaRef(t.type,t.audio_url)??summarizeStructuredMediaRef(t.type,t.media_url)??summarizeStructuredMediaRef(t.type,t.url)??summarizeStructuredMediaRef(t.type,t.source);if(e)return e}return stringifyStructuredJsonFallback(e)}function extractUserMessagePromptText(e){if(typeof e===`string`)return e.trim()||void 0;if(!Array.isArray(e))return;return e.flatMap(e=>{const t=stringifyStructuredContentPart(e);return t?[t]:[]}).join(` `).trim()||void 0}function promptAlreadyIncludesQueuedUserMessage(e,t){const n=e.replace(/\r\n/g,` `);const r=t.replace(/\r\n/g,` `).trim();return r.length>0&&`\n${n}\n`.includes(`\n${r}\n`)}function mergeOrphanedTrailingUserPrompt(e){const t=extractUserMessagePromptText(e.leafMessage.content);if(!t||e.prompt.trim().length>0&&shouldPreserveUserFacingSessionStateForInputProvenance(e.leafMessage.provenance))return{prompt:e.prompt,merged:false,removeLeaf:true};if(promptAlreadyIncludesQueuedUserMessage(e.prompt,t))return{prompt:e.prompt,merged:false,removeLeaf:false};const n=normalizeInputProvenance(e.leafMessage.provenance);return{prompt:[!n||n.kind===`external_user`?QUEUED_USER_MESSAGE_MARKER:QUEUED_INTER_SESSION_MESSAGE_MARKER,t,``,e.prompt].join(` `),merged:true,removeLeaf:false}}function resolveAttemptFsWorkspaceOnly(e){return resolveEffectiveToolFsWorkspaceOnly({cfg:e.config,agentId:e.sessionAgentId})}function buildAfterTurnRuntimeContext(e){const t=e.attempt.sessionTarget;const n=t?.agentId??e.activeAgentId;const r=t?.sessionId??e.attempt.sessionId;const i=t?.sessionKey??e.attempt.sessionKey;const a=n||r||i||t?.storePath||t?.threadId!==void 0?{...n?{agentId:n}:{},...r?{sessionId:r}:{},...i?{sessionKey:i}:{},...t?.storePath?{storePath:t.storePath}:{},...t?.threadId!==void 0?{threadId:t.threadId}:{}}:void 0;const o=floorPositiveFiniteNumber(e.tokenBudget);const s=floorPositiveFiniteNumber(e.currentTokenCount);return{...buildEmbeddedCompactionRuntimeContext({sessionKey:e.attempt.sessionKey,sandboxSessionKey:e.attempt.sandboxSessionKey,sandboxAgentId:e.attempt.sandboxAgentId,messageChannel:e.attempt.messageChannel,messageProvider:e.attempt.messageProvider,agentAccountId:e.attempt.agentAccountId,currentChannelId:e.attempt.currentChannelId,currentThreadTs:e.attempt.currentThreadTs,currentMessageId:e.attempt.currentMessageId,authProfileId:e.attempt.authProfileId,authProfileIdSource:e.attempt.authProfileIdSource,modelSelectionLocked:e.attempt.modelSelectionLocked,config:e.attempt.config,toolsAllow:e.attempt.toolsAllow,skillsSnapshot:e.attempt.skillsSnapshot,senderId:e.attempt.senderId,provider:e.attempt.provider,modelId:e.attempt.modelId,thinkLevel:e.attempt.thinkLevel,reasoningLevel:e.attempt.reasoningLevel,bashElevated:e.attempt.bashElevated,extraSystemPrompt:e.attempt.extraSystemPrompt,ownerNumbers:e.attempt.ownerNumbers,modelCallUrgency:resolveModelCallUrgency(e.attempt),runtimeAuthPlan:e.attempt.runtimePlan?.auth,workspaceDir:e.workspaceDir,cwd:e.cwd,agentDir:e.agentDir,harnessRuntime:e.attempt.agentHarnessId,activeProcessSessions:listActiveProcessSessionReferences({scopeKey:resolveProcessToolScopeKey({sessionKey:e.attempt.sessionKey,sessionId:e.attempt.sessionId,agentId:e.activeAgentId})})},`after-turn`),...resolveContextEngineCapabilities({config:e.attempt.config,sessionKey:e.attempt.sessionKey,explicitAgentId:e.attempt.contextEngineAgentId,authProfileId:e.attempt.authProfileId,contextEnginePluginId:e.contextEnginePluginId,purpose:`context-engine.after-turn`}),...o!==void 0?{tokenBudget:o}:{},...s!==void 0?{currentTokenCount:s}:{},...e.promptCache?{promptCache:e.promptCache}:{},transcriptStorage:{kind:`sqlite`},...a?{sessionTarget:a}:{}}}function buildAfterTurnRuntimeContextFromUsage(e){return buildAfterTurnRuntimeContext({...e,currentTokenCount:deriveContextPromptTokens({lastCallUsage:e.lastCallUsage})})}export{resolvePromptBuildHookResult as a,wrapPluginSystemContextSection as c,resolveAttemptFsWorkspaceOnly as i,buildAfterTurnRuntimeContextFromUsage as n,resolvePromptModeForSession as o,mergeOrphanedTrailingUserPrompt as r,shouldWarnOnOrphanedUserRepair as s,buildAfterTurnRuntimeContext as t};