openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 8.69 kB
JavaScript
import{a as asOptionalRecord,l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as safeParseJsonRecord}from"./json-coercion-DNNwq4_v.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{i as isSilentReplyText,n as SILENT_REPLY_TOKEN}from"./tokens-DD0Y_anD.mjs";import{r as stripMixedSilentReplyTokens}from"./tagged-reply-control-DSg5HbyD.mjs";import{t as captureSessionActorStorageOwner}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import{s as resolveToolUseId,t as isToolCallBlock}from"./tool-content-FhKUiJzR.mjs";import{a as prepareAgentRunTerminalReply}from"./agent-run-terminal-reply-DTaPwlVH.mjs";import"./session-accessor-CY8UYP4m.mjs";import{l as waitForSessionTranscriptProjection}from"./session-transcript-reconcile-BewE5zNm.mjs";import{n as cliBackendLog}from"./log-CF03K_DW.mjs";import{D as isClaudeToolUseBlockType,E as isClaudeToolResultBlockType,S as isClaudeCliProvider}from"./cli-live-session-registry-Cr_avKfh.mjs";import{i as messageToolOwnsVisibleReply}from"./source-reply-delivery-mode-B6NT-zZ-.mjs";import{t as resolveClaudeCliProjectDirForWorkspace}from"./claude-cli-project-dir-PHqOOfKz.mjs";import{r as readClaudeCliFallbackSeed}from"./cli-session-history.claude-Bmfw0g4U.mjs";import path from"node:path";import fs from"node:fs/promises";import readline from"node:readline";
//!src/agents/command/attempt-execution.helpers.ts
const CLAUDE_CLI_TRANSCRIPT_MAX_RECORDS=500;function normalizeClaudeCliSessionId(e){const t=e?.trim();if(!t||t.includes(`\0`)||t.includes(`/`)||t.includes(`\\`))return;return t}async function readCliTranscriptFile(e,t,n){try{const r=await fs.lstat(e);if(r.isSymbolicLink()||!r.isFile())return t;const i=await fs.open(e,`r`);try{return await n(i,r.size)}finally{await i.close()}}catch{return t}}async function scanJsonlFile(e){return await readCliTranscriptFile(e,{fileExists:false,hasAssistant:false},async e=>{const t=readline.createInterface({input:e.createReadStream({encoding:`utf-8`})});let n=0;for await(const e of t){if(!e.trim())continue;n++;if(n>CLAUDE_CLI_TRANSCRIPT_MAX_RECORDS)break;const t=safeParseJsonRecord(e)?.message;if(isRecord(t)&&t.role===`assistant`)return{fileExists:true,hasAssistant:true}}return{fileExists:true,hasAssistant:false}})}async function sessionTranscriptHasContent(e,t){if(!e)return false;t?.throwIfAborted();const n=captureSessionActorStorageOwner(e,{assertCurrent(){t?.throwIfAborted()},authorize(){}});const r={...e,...n?{storePath:n.path}:{}};await waitForSessionTranscriptProjection(r,t);const{readSessionTranscriptBoundedMessageTailPageAsync:i}=await import(`./session-transcript-readers-DsWhXxDi.mjs`);const{events:a}=await i(r,{maxBytes:5242880,maxMessages:500,offset:0},t);return a.some(({event:e})=>isRecord(e)&&e.type===`message`&&isRecord(e.message)&&e.message.role===`assistant`)}function claudeCliSessionTranscriptPath(e){const t=normalizeClaudeCliSessionId(e.sessionId);if(!t)return null;const n=e.workspaceDir?.trim();if(!n)return null;return path.join(resolveClaudeCliProjectDirForWorkspace({workspaceDir:n,homeDir:e.homeDir}),`${t}.jsonl`)}const CLAUDE_CLI_TRANSCRIPT_FLUSH_GRACE_MS=250;const CLAUDE_CLI_ORPHAN_PROBE_TAIL_BYTES=1048576;async function claudeCliSessionTranscriptHasContent(e){const t=claudeCliSessionTranscriptPath(e);if(!t)return false;if((await scanJsonlFile(t)).hasAssistant)return true;await sleep(CLAUDE_CLI_TRANSCRIPT_FLUSH_GRACE_MS);const n=await scanJsonlFile(t);if(n.hasAssistant)return true;const r=normalizeClaudeCliSessionId(e.sessionId);cliBackendLog.warn(`claude-cli transcript check v4 miss (sessionId-deterministic path, grace ${CLAUDE_CLI_TRANSCRIPT_FLUSH_GRACE_MS}ms): sessionId=${r??``} expectedPath=${t} fileExists=${n.fileExists}`);return false}function toToolContentBlocks(e){if(!Array.isArray(e))return;return e.filter(e=>Boolean(e&&typeof e===`object`))}async function claudeCliSessionTranscriptHasOrphanedToolUse(e){const t=claudeCliSessionTranscriptPath(e);if(!t)return false;return await readCliTranscriptFile(t,false,async(e,t)=>{const n=Math.min(t,CLAUDE_CLI_ORPHAN_PROBE_TAIL_BYTES);const r=t-n;const i=Buffer.alloc(n);const{bytesRead:a}=await e.read(i,0,n,r);let o=i.toString(`utf-8`,0,a);if(r>0){const e=o.indexOf(`
`);o=e===-1?``:o.slice(e+1)}let s=/* @__PURE__ */ new Set;let c=/* @__PURE__ */ new Set;for(const e of o.split(/\r?\n/)){if(!e.trim())continue;const t=safeParseJsonRecord(e);if(t?.isSidechain===true||t?.type!==`user`&&t?.type!==`assistant`)continue;const n=asOptionalRecord(t?.message);const r=n?.role;if(r===`assistant`){s=/* @__PURE__ */ new Set;c=/* @__PURE__ */ new Set}else if(r!==`user`)continue;for(const e of toToolContentBlocks(n?.content)??[]){const t=r===`assistant`&&isClaudeToolUseBlockType(e.type)?s:isClaudeToolResultBlockType(e.type)?c:void 0;if(t){const n=resolveToolUseId(e);if(n)t.add(n)}}}for(const e of s)if(!c.has(e))return true;return false})}function resolveFallbackRetryPrompt(e){if(!e.isFallbackRetry)return e.body;const t=e.priorContextPrelude?.trim();if(!e.sessionHasHistory&&!t)return e.body;const n=`[Retry after the previous model attempt failed or timed out]\n\n${e.body}`;return t?`${t}\n\n${n}`:n}const CLAUDE_CLI_FALLBACK_PRELUDE_MIN_TURN_CHARS=64;function extractFallbackTurnText(e){const t=e.content;if(typeof t===`string`)return t;if(!Array.isArray(t))return``;const n=[];for(const e of t){if(typeof e===`string`){n.push(e);continue}if(!e||typeof e!==`object`)continue;const t=e;if(typeof t.text===`string`){n.push(t.text);continue}if(isToolCallBlock(t)&&typeof t.name===`string`){n.push(`(tool call: ${t.name})`);continue}if(t.type===`tool_result`){const e=typeof t.content===`string`?t.content:void 0;if(e)n.push(`(tool result: ${e})`);else n.push(`(tool result)`)}}return n.join(`
`).trim()}function formatFallbackTurns(e,t){if(e.length===0||t<=0)return``;const n=[];let r=0;for(let i=e.length-1;i>=0;i-=1){const a=e[i];if(!a||typeof a!==`object`)continue;const o=a.role;if(o!==`user`&&o!==`assistant`)continue;const s=extractFallbackTurnText(a);if(!s)continue;const c=`${o}: ${s}`;if(r+c.length+1>t)break;n.push(c);r+=c.length+1}n.reverse();return n.join(`
`)}async function buildClaudeCliFallbackContextPrelude(e){const t=e.cliSessionId?.trim();if(!t)return``;const n=await readClaudeCliFallbackSeed({cliSessionId:t});if(!n)return``;const r=[`## Prior session context (from claude-cli)`];let i=7958;if(n.summaryText){const e=`\nSummary of earlier conversation:\n${n.summaryText}`;if(e.length<=i){r.push(e);i-=e.length}else{const e=truncateUtf16Safe(n.summaryText,Math.max(0,i-64));const t=e.lastIndexOf(` `);const a=t>0?e.slice(0,t).trimEnd():e.trimEnd();r.push(`\nSummary of earlier conversation (truncated):\n${a} …`);i=0}}if(i>CLAUDE_CLI_FALLBACK_PRELUDE_MIN_TURN_CHARS&&n.recentTurns.length>0){const e=formatFallbackTurns(n.recentTurns,i-32);if(e)r.push(`\nRecent turns:\n${e}`)}if(r.length===1)return``;return r.join(`
`)}function createAcpVisibleTextAccumulator(){let e=``;let t=``;let n=false;let r;const finalize=()=>r??=prepareAgentRunTerminalReply({rawText:t});return{consume(r){if(!r)return null;const i=t&&r.startsWith(t)&&r.length>t.length?r.slice(t.length):r;t+=i;if(!n){const r=t.trimStart().toUpperCase();const i=stripMixedSilentReplyTokens(t);if(`NO_REPLY`.startsWith(r)||isSilentReplyText(r)){if(i===null)return null}n=true;e=i??t;return e?{text:e,delta:e}:null}e+=i;return{text:e,delta:i}},finalize(){return finalize().text},finalizeRaw(){return t},finalizeReplySnapshot(){return finalize().terminalReply}}}function rebaseExecApprovalContinuationPromptRange(e){if(!e.range)return;if(!e.prompt.endsWith(e.body))throw new Error(`exec approval continuation prompt range could not be rebased`);const t=e.prompt.length-e.body.length;return{start:t+e.range.start,end:t+e.range.end}}function resolveCompletionToolPolicy(e){const{run:t,completionNeedsMessageDelivery:n,isSubagentAnnounceHandoff:r}=e;const i=e.trustedSubagentAnnounceHandoff&&!e.isRawModelRun&&(!e.isCliExecutionProvider||isClaudeCliProvider(e.cliExecutionProvider)&&t.sessionEntry?.execHost!==`node`&&!t.opts.trustedInternalHandoff?.settleBatch&&!messageToolOwnsVisibleReply(t.opts))&&(!messageToolOwnsVisibleReply(t.opts)||n);return{completionRetainsRequesterTools:i,runtimeToolsAllow:r?i?t.opts.toolsAllow:n?[`message`]:void 0:t.opts.toolsAllow,disableTools:t.opts.modelRun===true||r&&!i&&!n}}export{rebaseExecApprovalContinuationPromptRange as a,sessionTranscriptHasContent as c,createAcpVisibleTextAccumulator as i,claudeCliSessionTranscriptHasContent as n,resolveCompletionToolPolicy as o,claudeCliSessionTranscriptHasOrphanedToolUse as r,resolveFallbackRetryPrompt as s,buildClaudeCliFallbackContextPrelude as t};