beeos-claw 0.6.66-cloud.2 → 0.6.66-cloud.3
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 +12 -13
- package/dist/a2a/tools.js +1 -1
- package/dist/acp-gateway/beeos-file-resolver.js +1 -1
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/local-session-history.js +1 -1
- package/dist/acp-gateway/mcp-desired-state-controller.js +1 -1
- package/dist/acp-gateway/mcp-desired-state-store.js +1 -1
- package/dist/acp-gateway/mcp-service.js +1 -1
- package/dist/acp-server.js +1 -1
- package/dist/agent-sync.js +1 -1
- package/dist/approval/gate.js +1 -0
- package/dist/approval/journal.js +1 -0
- package/dist/approval/presentation.js +1 -0
- package/dist/approval/protocol.generated.js +1 -0
- package/dist/approval/turn-policy.js +1 -0
- package/dist/auto-reply-tokens.js +1 -1
- package/dist/automation/tools.js +1 -1
- package/dist/canvas/relay-client.js +1 -1
- package/dist/canvas/static-html.js +1 -0
- package/dist/canvas/tools.js +1 -1
- package/dist/canvas/ws-provider.js +1 -1
- package/dist/canvas-orchestrator.js +1 -1
- package/dist/chat-envelope.js +1 -0
- package/dist/connectors/managed-connector-tools.js +1 -0
- package/dist/files/fetch-tool.js +1 -1
- package/dist/files/list-tool.js +1 -1
- package/dist/gateway-client.js +1 -1
- package/dist/im-inbound-handler.js +1 -1
- package/dist/im-runtime-dispatch.js +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp-connector-proxy.js +1 -1
- package/dist/media/arouter-config.js +1 -1
- package/dist/media/image-provider.js +1 -1
- package/dist/media/video-provider.js +1 -1
- package/dist/message-client-composition.js +1 -1
- package/dist/message-projection-inbound-consumer.js +1 -1
- package/dist/plugin-registration-plan.js +1 -1
- package/dist/runtime/agent-projection-production.js +1 -1
- package/dist/runtime/callback-queue.js +1 -1
- package/dist/runtime/chat-handler-port.js +1 -0
- package/dist/runtime/conversation-title.js +1 -1
- package/dist/runtime/core-execution-attempt-context.js +1 -1
- package/dist/runtime/deepseek-reasoning-stream.js +1 -1
- package/dist/runtime/im-reply-sink.js +1 -1
- package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
- package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
- package/dist/runtime/message-service-cron-delivery-http-authority.js +1 -1
- package/dist/runtime/message-service-runtime-authenticated-fetch.js +1 -1
- package/dist/runtime/message-service-runtime-claim-authority.js +1 -1
- package/dist/runtime/message-service-runtime-message-channel.js +1 -1
- package/dist/runtime/message-service-session-model-http-authority.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
- package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
- package/dist/runtime/native-cloud-chat-composition.js +1 -0
- package/dist/runtime/native-cloud-prompt-bridge.js +1 -0
- package/dist/runtime/native-input-files-http.js +1 -0
- package/dist/runtime/native-input-files.js +1 -0
- package/dist/runtime/native-output-file-attempt.js +1 -0
- package/dist/runtime/native-prompt-authority.js +1 -0
- package/dist/runtime/native-prompt-preflight.js +1 -0
- package/dist/runtime/native-session-new-bridge.js +1 -0
- package/dist/runtime/openclaw-runtime-capabilities.js +1 -1
- package/dist/runtime/openclaw-session-model.js +1 -0
- package/dist/runtime/openclaw-session-write-quiescence.js +1 -1
- package/dist/runtime/reply-router.js +1 -1
- package/dist/runtime/runtime-command-dispatcher.js +1 -1
- package/dist/runtime/runtime-command-journal.js +1 -1
- package/dist/runtime/runtime-error-part.js +1 -0
- package/dist/runtime/runtime-local-parity-matrix.js +1 -1
- package/dist/runtime/runtime-message-channel-contract.js +1 -1
- package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
- package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
- package/dist/runtime/runtime-parity-manifest.js +1 -1
- package/dist/runtime/runtime-production-authority.js +1 -1
- package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
- package/dist/runtime/runtime-service-production-candidate.js +1 -1
- package/dist/runtime/runtime-session-control-service.js +1 -1
- package/dist/runtime/runtime-skills-service.js +1 -1
- package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
- package/dist/runtime/session-set-model-mapping.js +1 -1
- package/dist/runtime/write-runtime-failure.js +1 -1
- package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
- package/dist/upload/desktop-screenshot-tool.js +1 -1
- package/dist/upload/finalize-hook.js +1 -1
- package/dist/upload/native-output-tool-hook.js +1 -0
- package/dist/upload/tool-artifact-enrichment.js +1 -1
- package/dist/upload/tool.js +1 -1
- package/dist/upload/upload-file.js +1 -1
- package/openclaw.plugin.json +7 -2
- package/package.json +11 -11
- package/runtime-service-wire-identity.v1.json +12 -12
- package/scripts/runtime-blackbox-worker-main.mjs +5 -2
- package/dist/agent-auth.js +0 -1
- package/dist/bridge-discovery.js +0 -1
- package/dist/contracts/question/codec.js +0 -1
- package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +0 -1
- package/dist/runtime/message-service-runtime-invocation-authority.js +0 -1
- package/dist/runtime/message-service-session-reasoning-http-authority.js +0 -1
- package/dist/runtime/openclaw-native-sessions.js +0 -1
- package/dist/runtime/openclaw-question-adapter.js +0 -1
- package/dist/runtime/openclaw-title-provider.js +0 -1
- package/dist/runtime/question-wire.js +0 -1
- package/dist/runtime/requested-model.js +0 -1
- package/dist/runtime/runtime-jwks-verifier.js +0 -1
- package/dist/runtime/runtime-reasoning.js +0 -1
- package/dist/runtime/runtime-registration.js +0 -1
- package/dist/runtime/runtime-transport-failure-policy.js +0 -1
- package/dist/runtime/split-runtime-authorization-verifier.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
const TITLE_SYSTEM_PROMPT_BASE='You are a conversation title generator. Your task is to generate a concise, human-readable title summarizing the topic of the user\'s question together with the assistant\'s answer.\n\n### Rules:\n- Length: 3-6 words in English, or 6-20 characters in Chinese/Japanese/Korean/Thai (up to 24 if needed to keep all key domain terms intact).\n- Language: When a Client UI locale is provided below, write the title in THAT language even if the user wrote in a different language (translate the topic). Otherwise match the user\'s input language exactly. Mixed zh/en input → use the dominant language. Do NOT switch languages away from the required locale.\n- Extract the core topic (noun-centric) of the Q&A exchange, not the action verb.\n- Use the assistant\'s answer to disambiguate or enrich the topic when the question alone is vague (e.g. "帮我看下" + an answer about x402 → "x402 支付集成").\n- No punctuation, no quotation marks, no emojis, no markdown.\n- No prefix like "Title:" or "Here is". Output the title only.\n- Avoid generic words: "help", "question", "chat", "problem", "task".\n- Greetings and self-introductions ARE concrete topics — never treat them as vague. Prefer the locale-native self-intro title from the Client UI locale section when present.\n- NEVER return placeholder / empty-chat titles such as "新会话", "新對話", "New chat", "New Conversation", "新しいチャット", "새 채팅", "แชตใหม่". Always invent a concrete noun-centric topic from whatever words are present.\n\n### Input Format:\nThe user message will contain both the question and the assistant\'s answer, delimited like this:\n[User Question]\n...question text...\n\n[Assistant Answer]\n...answer text (may be truncated with "..." in the middle)...\n\n### Output Format:\nRespond ONLY with valid JSON, no other text:\n{"title": "<your title here>"}\n\n### Examples:\nInput:\n[User Question]\n帮我写一个关于BeeOS设备接入的PRD\n\n[Assistant Answer]\n好的,这是 BeeOS 设备接入 PRD 的草稿:1. 目标 ...\nOutput: {"title": "BeeOS 设备接入 PRD"}\n\nInput:\n[User Question]\n帮我看下\n\n[Assistant Answer]\n你说的 x402 支付协议是一个基于 HTTP 402 的链上支付标准 ...\nOutput: {"title": "x402 支付协议解析"}\n\nInput:\n[User Question]\nWhat\'s the best way to integrate x402 payment protocol?\n\n[Assistant Answer]\nYou have three options: 1. Use the official SDK ...\nOutput: {"title": "x402 Payment Integration"}\n\nInput:\n[User Question]\n用一句话介绍一下你自己。\n\n[Assistant Answer]\n我是 BeeOS 智能助手,可以帮助你完成设备控制与任务协作。\nOutput: {"title": "自我介绍"}\n\nInput:\n[User Question]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "Greeting"}',PLACEHOLDER_TITLES=new Set(["new chat","new conversation","新会话","新對話","新しいチャット","새 채팅","แชตใหม่"]);export function isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();return!t||(!!PLACEHOLDER_TITLES.has(t.toLowerCase())||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t))))}function truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}function truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}export async function generateTitleFromQA(e,t,n){const r=n.
|
|
1
|
+
import{randomUUID}from"node:crypto";const TITLE_SYSTEM_PROMPT_BASE='You are a conversation title generator. Your task is to generate a concise, human-readable title summarizing the topic of the user\'s question together with the assistant\'s answer.\n\n### Rules:\n- Length: 3-6 words in English, or 6-20 characters in Chinese/Japanese/Korean/Thai (up to 24 if needed to keep all key domain terms intact).\n- Language: When a Client UI locale is provided below, write the title in THAT language even if the user wrote in a different language (translate the topic). Otherwise match the user\'s input language exactly. Mixed zh/en input → use the dominant language. Do NOT switch languages away from the required locale.\n- Extract the core topic (noun-centric) of the Q&A exchange, not the action verb.\n- Use the assistant\'s answer to disambiguate or enrich the topic when the question alone is vague (e.g. "帮我看下" + an answer about x402 → "x402 支付集成").\n- No punctuation, no quotation marks, no emojis, no markdown.\n- No prefix like "Title:" or "Here is". Output the title only.\n- Avoid generic words: "help", "question", "chat", "problem", "task".\n- Greetings and self-introductions ARE concrete topics — never treat them as vague. Prefer the locale-native self-intro title from the Client UI locale section when present.\n- NEVER return placeholder / empty-chat titles such as "新会话", "新對話", "New chat", "New Conversation", "新しいチャット", "새 채팅", "แชตใหม่". Always invent a concrete noun-centric topic from whatever words are present.\n\n### Input Format:\nThe user message will contain both the question and the assistant\'s answer, delimited like this:\n[User Question]\n...question text...\n\n[Assistant Answer]\n...answer text (may be truncated with "..." in the middle)...\n\n### Output Format:\nRespond ONLY with valid JSON, no other text:\n{"title": "<your title here>"}\n\n### Examples:\nInput:\n[User Question]\n帮我写一个关于BeeOS设备接入的PRD\n\n[Assistant Answer]\n好的,这是 BeeOS 设备接入 PRD 的草稿:1. 目标 ...\nOutput: {"title": "BeeOS 设备接入 PRD"}\n\nInput:\n[User Question]\n帮我看下\n\n[Assistant Answer]\n你说的 x402 支付协议是一个基于 HTTP 402 的链上支付标准 ...\nOutput: {"title": "x402 支付协议解析"}\n\nInput:\n[User Question]\nWhat\'s the best way to integrate x402 payment protocol?\n\n[Assistant Answer]\nYou have three options: 1. Use the official SDK ...\nOutput: {"title": "x402 Payment Integration"}\n\nInput:\n[User Question]\n用一句话介绍一下你自己。\n\n[Assistant Answer]\n我是 BeeOS 智能助手,可以帮助你完成设备控制与任务协作。\nOutput: {"title": "自我介绍"}\n\nInput:\n[User Question]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "Greeting"}',SELF_INTRO_BY_LOCALE={zh:"自我介绍","zh-TW":"自我介紹",ja:"自己紹介",ko:"자기소개",th:"แนะนำตัว",en:"Self Introduction"},SELF_INTRO_ALIASES=new Set(Object.values(SELF_INTRO_BY_LOCALE).map(e=>e.toLowerCase())),LOCALE_PROMPT_HINT={zh:'zh (简体中文) — write the title in Simplified Chinese. Self-intro → "自我介绍".',"zh-TW":'zh-TW (繁體中文) — write the title in Traditional Chinese. Self-intro → "自我介紹".',ja:'ja (日本語) — write the title in Japanese. Self-intro → "自己紹介". Never use Chinese "自我介绍".',ko:'ko (한국어) — write the title in Korean. Self-intro → "자기소개".',th:'th (ไทย) — write the title in Thai. Self-intro → "แนะนำตัว".',en:'en (English) — write the title in English. Self-intro → "Self Introduction".'},TITLE_TEMPLATES=[{match:["今日日报","日报"],zh:"今日工作日报",en:"Daily Work Log"},{match:["周报","周报总结","本周周报"],zh:"本周工作周报",en:"Weekly Work Report"},{match:["月报","月度汇报","月度总结"],zh:"本月工作月报",en:"Monthly Work Report"},{match:["工作日志","日志"],zh:"工作日志整理",en:"Work Log Review"},{match:["晨会","今日晨会"],zh:"今日晨会纪要",en:"Daily Standup Notes"},{match:["复盘","今日复盘"],zh:"今日工作复盘",en:"Daily Retrospective"}],PLACEHOLDER_TITLES=new Set(["new chat","new conversation","新会话","新對話","新しいチャット","새 채팅","แชตใหม่"]),PLACEHOLDER_TO_LOCALE={"new chat":"en","new conversation":"en","新会话":"zh","新對話":"zh-TW","新しいチャット":"ja","새 채팅":"ko","แชตใหม่":"th"};export function inferTitleLocaleFromPlaceholder(e){if(!e)return;const t=e.trim().toLowerCase();return PLACEHOLDER_TO_LOCALE[t]??PLACEHOLDER_TO_LOCALE[e.trim()]}export function buildTitleSystemPrompt(e){return e?`${TITLE_SYSTEM_PROMPT_BASE}\n\n### Client UI locale\n${LOCALE_PROMPT_HINT[e]}\nCRITICAL: The title language MUST match this locale, even when [User Question] is in another language.`:TITLE_SYSTEM_PROMPT_BASE}export function alignTitleWithLocale(e,t){return t&&SELF_INTRO_ALIASES.has(e.trim().toLowerCase())?SELF_INTRO_BY_LOCALE[t]:e}export function isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();return!t||(!!PLACEHOLDER_TITLES.has(t.toLowerCase())||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t))))}export function isGuardMessage(e){const t=e.trim();return[...t].length<3||[...t].every(e=>/[\p{P}\p{S}\s]/u.test(e))}export function matchTitleTemplate(e){const t=e.trim().toLowerCase();for(const n of TITLE_TEMPLATES)if(n.match.some(e=>e.toLowerCase()===t))return/[\u4e00-\u9fff]/.test(e)?n.zh:n.en}function truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}function truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}export function fallbackTitleFromQuestion(e){const t=e.replace(/[\r\n\t]+/g," ").replace(/[。!?.!?…]+$/u,"").trim();if(!t||isGuardMessage(t)||isPlaceholderTitle(t))return;const n=[...t];return n.length<=20?t:n.slice(0,18).join("")}export async function generateTitleFromQA(e,t,n,i="title-gen"){let o,r,a=i;if(n&&("locale"in n||"logPrefix"in n||"logger"in n)){const e=n;o=e.logger,a=e.logPrefix??"title-gen",r=e.locale}else o=n;if(isGuardMessage(e))return void o?.info?.(`[${a}] SKIP guard message`);const s=matchTitleTemplate(e);if(s){const e=alignTitleWithLocale(s,r);return o?.info?.(`[${a}] template title="${e}"`),e}const l=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),c=process.env.AROUTER_API_KEY||"";if(!l||!c)return void o?.info?.(`[${a}] SKIP: no AROUTER env vars`);const u=`[User Question]\n${truncateQuestionForTitle(e)}\n\n[Assistant Answer]\n${truncateAnswerForTitle(t)}`;o?.info?.(`[${a}] CALLING LLM q="${e.slice(0,60)}" aLen=${t.length}${r?` locale=${r}`:""}`);try{const t=await fetch(`${l}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({model:"openai/gpt-4o-mini",max_tokens:32,temperature:.3,messages:[{role:"system",content:buildTitleSystemPrompt(r)},{role:"user",content:u}]})});if(!t.ok){const e=await t.text().catch(()=>"");return void o?.info?.(`[${a}] FAILED status=${t.status} body=${e.slice(0,300)}`)}const n=await t.json(),i=n.choices?.[0]?.message?.content?.trim();if(!i)return;const s=i.replace(/^```json\s*/,"").replace(/```$/,"").trim();let h;try{h=JSON.parse(s).title?.trim()??""}catch{return void o?.debug?.(`[${a}] JSON parse failed: ${s}`)}if(!h||isPlaceholderTitle(h)){const t=fallbackTitleFromQuestion(e);if(t){const n=alignTitleWithLocale(t,r),i=r&&n===t&&/介绍一下你自己|介紹一下你自己|introduce yourself|自己紹介|자기소개/i.test(e)?SELF_INTRO_BY_LOCALE[r]:n;return o?.info?.(`[${a}] discarded placeholder/empty title="${h}"; fallback="${i}"`),i}return void o?.info?.(`[${a}] discarded placeholder/empty title="${h}"`)}const d=alignTitleWithLocale(h,r);return o?.info?.(d!==h?`[${a}] OK title="${h}" → locale-aligned="${d}"`:`[${a}] OK title="${h}"`),d}catch(e){return void o?.info?.(`[${a}] ERROR: ${e instanceof Error?e.message:e}`)}}export function createConversationTitleRenameIntent(e,t){return Object.freeze({conversationId:e,title:t,commandId:randomUUID()})}export async function patchMsConversationTitle(e,t){const n=e.conversations;if(!n)throw new Error("conversation title administration is unavailable");await n.update({conversationId:t.conversationId,title:t.title,idempotencyKey:t.commandId})}export async function maybeRenameImConversationTitle(e){const{client:t,conversationId:n,question:i,answer:o,logger:r}=e,a=`im-title-gen conv=${n}`;if(!n||!i.trim()||!o.trim())return void r?.debug?.(`[${a}] SKIP missing conversation/q/a`);const s=t.conversations;if(!s)return void r?.debug?.(`[${a}] SKIP conversation admin unavailable`);let l;try{l=(await s.get(n)).title}catch(e){return void r?.info?.(`[${a}] GET conversation failed: ${e instanceof Error?e.message:e}`)}if(!isPlaceholderTitle(l))return void r?.debug?.(`[${a}] SKIP non-placeholder title="${l}"`);const c=inferTitleLocaleFromPlaceholder(l),u=await generateTitleFromQA(i,o,{logger:r,logPrefix:a,locale:c});if(!u)return;const h=createConversationTitleRenameIntent(n,u);try{return await patchMsConversationTitle(t,h),r?.info?.(`[${a}] PATCH MS title OK title="${u}"`),u}catch(e){return void r?.info?.(`[${a}] PATCH MS title FAILED: ${e instanceof Error?e.message:e}`)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{canonicalizeJcs,verifyAndDeriveCoreExecutionAttempt}from"@beeos-ai/beeos-types/runtime";const TRUSTED_CORE_ATTEMPT=Symbol("beeos.trusted-core-attempt"),VERIFIED_MESSAGE_GRANT=Symbol("beeos.verified-message-grant");export function createAcpCoreExecutionAttempt(e){if(e.historyBoundary&&"local"!==e.historyBoundary.kind)throw new Error("ACP attempt cannot use a Message Service history boundary");return Object.freeze({...e,origin:"acp",[TRUSTED_CORE_ATTEMPT]:!0})}export async function verifyAndCreateServiceCoreExecutionAttempt(e){let t;try{t=verifyAndDeriveCoreExecutionAttempt(e.authorization,e.derivationContext,e.verifier)}catch{return{ok:!1,violations:["MALFORMED_EXECUTION_AUTHORIZATION"]}}if(!t.ok)return t;await e.recordVerifiedAttempt(t.attempt);const o=await e.resolvePorts();if(o.historyBoundary&&"message-service"!==o.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(o.sessionModelProjection&&o.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");return{ok:!0,context:Object.freeze({operationId:e.operationId,runtimeEpoch:e.runtimeEpoch,fence:e.fence,resources:o.resources,...o.historyBoundary?{historyBoundary:o.historyBoundary}:{},...o.sessionModelProjection?{sessionModelProjection:o.sessionModelProjection}:{},...o.
|
|
1
|
+
import{canonicalizeJcs,isCloudRuntimeExecutionGrant,verifyAndDeriveCoreExecutionAttempt}from"@beeos-ai/beeos-types/runtime";const TRUSTED_CORE_ATTEMPT=Symbol("beeos.trusted-core-attempt"),VERIFIED_MESSAGE_GRANT=Symbol("beeos.verified-message-grant");export function createAcpCoreExecutionAttempt(e){if(e.historyBoundary&&"local"!==e.historyBoundary.kind)throw new Error("ACP attempt cannot use a Message Service history boundary");return Object.freeze({...e,origin:"acp",[TRUSTED_CORE_ATTEMPT]:!0})}export async function verifyAndCreateServiceCoreExecutionAttempt(e){let t;try{t=verifyAndDeriveCoreExecutionAttempt(e.authorization,e.derivationContext,e.verifier)}catch{return{ok:!1,violations:["MALFORMED_EXECUTION_AUTHORIZATION"]}}if(!t.ok)return t;await e.recordVerifiedAttempt(t.attempt);const o=await e.resolvePorts();if(o.historyBoundary&&"message-service"!==o.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(o.sessionModelProjection&&o.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");return{ok:!0,context:Object.freeze({operationId:e.operationId,runtimeEpoch:e.runtimeEpoch,fence:e.fence,resources:o.resources,...o.historyBoundary?{historyBoundary:o.historyBoundary}:{},...o.sessionModelProjection?{sessionModelProjection:o.sessionModelProjection}:{},...o.canvasControl?{canvasControl:o.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedAttempt:t.attempt,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export async function verifyAndCreateMessageServiceCoreExecutionAttempt(e){const t=e.verifier.verifyAndDecodeGrant(e.executionGrant);if(!t)return{ok:!1,violations:["GRANT_SIGNATURE_INVALID"]};if(t.compactHash!==e.request.executionGrantHash)return{ok:!1,violations:["GRANT_HASH_MISMATCH"]};const o=e.nowEpochSeconds??Math.floor(Date.now()/1e3),n=t.claims,r=e.request,i=2===e.request.schemaVersion?isCloudRuntimeExecutionGrant(t.claims,e.request,{...e.lease,leaseId:e.lease.leaseId??""},o,{allowExpiredAfterRetainedStart:!0===e.allowExpiredGrant&&("models/list"===r.method||"skills/list"===r.method)})?[]:["CLOUD_GRANT_REQUEST_MISMATCH"]:validateMessageGrant(n,e.request,e.lease,o,!0===e.allowExpiredGrant);if(i.length)return{ok:!1,violations:i};const s=await e.resolvePorts();if(s.historyBoundary&&"message-service"!==s.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(s.sessionModelProjection&&s.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");const a=Object.freeze({[VERIFIED_MESSAGE_GRANT]:!0,claims:Object.freeze({...n}),compactHash:t.compactHash});return{ok:!0,grant:a,context:Object.freeze({operationId:e.request.operationId,runtimeEpoch:e.runtimeEpoch,resources:s.resources,...s.historyBoundary?{historyBoundary:s.historyBoundary}:{},...s.sessionModelProjection?{sessionModelProjection:s.sessionModelProjection}:{},...s.canvasControl?{canvasControl:s.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedMessageGrant:a,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export function assertTrustedCoreExecutionAttempt(e,t){if(!e||!0!==e[TRUSTED_CORE_ATTEMPT]||e.operationId!==t.operationId||e.runtimeEpoch!==t.runtimeEpoch)throw new Error("untrusted or mismatched Core execution attempt context");if(!("service"!==e.origin||e.verifiedMessageGrant||e.fence&&e.verifiedAttempt))throw new Error("Service Core execution attempt lacks verified authorization")}function validateMessageGrant(e,t,o,n,r){if(!e||"object"!=typeof e)return["MALFORMED_EXECUTION_GRANT"];const i="historyGeneration"in e?e.historyGeneration:void 0,s="instance"===e.scope&&"runtimeAgentUid"in e?e.runtimeAgentUid:void 0;if(!exactKeys(e,["iss","aud","purpose","sub","jti","iat","exp","operationId","requestMessageId","instanceId","handlerIdentity","dispatchEpoch","method","requestHash","paramsHash","commandHash","idempotencyKeyHash","callerUserId","callerIdentityId","scope","command","executionMode",..."instance"===e.scope?void 0!==s?["runtimeAgentUid"]:[]:"agent"===e.scope?["platformAgentId","runtimeAgentUid"]:"conversation"===e.scope?["platformConversationId","runtimeConversationUid","runtimeSessionKey","platformAgentId","runtimeAgentUid",...void 0!==i?["historyGeneration"]:[]]:[]]))return["GRANT_FIELDS_INVALID"];const a=[];"beeos-gateway"===e.iss&&"beeos-runtime-command"===e.aud&&"runtime-execution-grant"===e.purpose&&e.sub===t.runtimeHandlerIdentity&&e.handlerIdentity===t.runtimeHandlerIdentity&&"start"===e.executionMode||a.push("GRANT_IDENTITY_MISMATCH"),(!Number.isSafeInteger(e.iat)||!Number.isSafeInteger(e.exp)||"string"!=typeof e.jti||0===e.jti.length||e.iat>n||e.exp<=e.iat||!r&&e.exp<=n||e.exp-e.iat>60)&&a.push("GRANT_TIME_INVALID");if([[e.operationId,t.operationId],[e.requestMessageId,t.requestMessageId],[e.instanceId,t.instanceId],[e.dispatchEpoch,t.dispatchEpoch],[e.method,t.method],[e.requestHash,t.requestHash],[e.paramsHash,t.paramsHash],[e.commandHash,t.commandHash],[e.idempotencyKeyHash,t.idempotencyKeyHash],[e.callerUserId,t.callerUserId],[e.callerIdentityId,t.callerIdentityId],[o.instanceId,t.instanceId],[o.handlerIdentity,t.runtimeHandlerIdentity],[o.runtimeEpoch,t.dispatchEpoch]].some(([e,t])=>e!==t)&&a.push("GRANT_REQUEST_MISMATCH"),semanticEqual(e.command,t.command)||a.push("GRANT_COMMAND_MISMATCH"),targetMatches(e,t)||a.push("GRANT_TARGET_MISMATCH"),"conversation"===e.scope){const o=t.command.context,n=o?.agent;o&&"conversation"===o.scope&&n?.platformAgentId===e.platformAgentId&&n?.runtimeAgentUid===e.runtimeAgentUid||a.push("GRANT_TARGET_MISMATCH");const r=o?.historyGeneration;"session/cancel"===e.method?"string"==typeof i&&0!==i.length&&i===r||a.push("GRANT_HISTORY_GENERATION_MISMATCH"):void 0!==i&&a.push("GRANT_HISTORY_GENERATION_MISMATCH")}return a}function semanticEqual(e,t){try{return canonicalizeJcs(e)===canonicalizeJcs(t)}catch{return!1}}function targetMatches(e,t){const o=t.command.context,n=t.request.params;if(!o||o.scope!==e.scope)return!1;if("instance"===o.scope){if(!("runtimeAgentUid"in e))return!0;const o=e.runtimeAgentUid;if("string"!=typeof o||0===o.length)return!1;const n=t.command.params;return n?.runtimeAgentUid===o}if("agent"===o.scope)return o.agent.runtimeAgentUid===e.runtimeAgentUid&&null!==n&&"object"==typeof n&&!Array.isArray(n)&&n.platformAgentId===e.platformAgentId;const r=null===n||"object"!=typeof n||Array.isArray(n)?void 0:"string"==typeof n.conversationId?n.conversationId:"string"==typeof n.sessionId?n.sessionId:void 0;return o.conversation.runtimeConversationUid===e.runtimeConversationUid&&o.conversation?.runtimeSessionKey===e.runtimeSessionKey&&r===e.platformConversationId}function exactKeys(e,t){const o=Object.keys(e).sort(),n=[...t].sort();return o.length===n.length&&o.every((e,t)=>e===n[t])}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const AROUTER_PROVIDER_ID="arouter";export const DEEPSEEK_REASONING_MODEL_ID="deepseek/deepseek-v4-flash";export const DEEPSEEK_REASONING_MODEL_KEY=`arouter/${DEEPSEEK_REASONING_MODEL_ID}`;function isRecord(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}export function enableDeepseekReasoningStream(e){if(!e)return;const r=isRecord(e.models)?e.models:void 0,o=isRecord(r?.providers)?r.providers:void 0,s=isRecord(o?.arouter)?o.arouter:void 0,
|
|
1
|
+
const AROUTER_PROVIDER_ID="arouter";export const DEEPSEEK_REASONING_MODEL_ID="deepseek/deepseek-v4-flash";export const DEEPSEEK_REASONING_MODEL_KEY=`arouter/${DEEPSEEK_REASONING_MODEL_ID}`;function isRecord(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}export function enableDeepseekReasoningStream(e){if(!e)return;const r=isRecord(e.models)?e.models:void 0,o=isRecord(r?.providers)?r.providers:void 0,s=isRecord(o?.arouter)?o.arouter:void 0,t=Array.isArray(s?.models)?s.models:void 0;if(!t)return e;let n=!1;const E=t.map(e=>isRecord(e)&&e.id===DEEPSEEK_REASONING_MODEL_ID?(n=!0,{...e,reasoning:!0}):e);if(!n)return e;const a=isRecord(e.agents)?e.agents:{},i=isRecord(a.defaults)?a.defaults:{},d="string"==typeof i.reasoningDefault;return{...e,agents:{...a,defaults:{...i,reasoningDefault:d?i.reasoningDefault:"stream"}},models:{...r,providers:{...o,[AROUTER_PROVIDER_ID]:{...s,models:E}}}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const s=new Map,n=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let m;const c={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const f=new Map,h=new Map,v=[],_=[],y=new Map,b=new Map;let I=0;const S=new Map;let q=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),$=new Set,w=new Set,P=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},T=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,ue("body_preview_flush",()=>{m===e&&(e=>{o.text!==e.targetBody&&(P(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},k=e=>{const t=m;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(P(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):P(e)},E=t=>{if(void 0!==t.partIndex)return;const r=I,s=q;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:x(s)})),t.partIndex=r,I+=1,q+=1},C=()=>{if(!d){d=!0;for(const e of g)E(e)}},M=e=>{const t={text:e};g.push(t),d&&E(t)},R=(t,r)=>{for(const s of t){const t=b.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const n={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:n.toolUseId,_seq:n.displaySeq,data:x(n.displaySeq)})),b.set(s.url,n);continue}const n={...s,partIndex:I,displaySeq:q,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:r,_seq:n.displaySeq,data:x(n.displaySeq)})),b.set(s.url,n),I+=1,q+=1,ie.source+=1}},O=(e,t,r,s)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==s?{_duration_ms:s}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),A=t=>{C();const r={partIndex:I,displaySeq:q,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(O(r,t,"streaming")),I+=1,q+=1,p=r,r},N=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,ue("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,O(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},U=()=>{const r=p;if(!r)return;void 0!==r.publishTimer&&(clearTimeout(r.publishTimer),r.publishTimer=void 0);const s=Math.max(0,Math.round(performance.now()-r.startedAtMonotonicMs));e.stream.replacePart(r.partIndex,O(r,r.text,"done",s)),p=void 0,logChatLatency(e.logger,"claw.reasoning.settled",e.requestId,t,{reasoning_duration_ms:s,reasoning_chars:r.text.length,reasoning_snapshot_count:r.receivedSnapshotCount,reasoning_streaming_publish_count:r.streamingPublishCount,reasoning_coalesced_snapshot_count:Math.max(0,r.receivedSnapshotCount-r.streamingPublishCount),reasoning_publish_interval_ms:200})},j=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},L=e=>{const t=e?v.filter(t=>f.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},B=e=>{const t=_.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:s}]=t;return _.splice(s,1),r},F=(e,t)=>{if(h.set(e,t),e===t)return;const r=y.get(e);if(!r)return;const s=Q(t);J(s,r),y.delete(e);const n=f.get(t);n&&(Z(n,s),y.delete(t))},z=e=>h.get(e)??e,D=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),Q=e=>{let t=y.get(e);return t||(t={},y.set(e,t)),t},W=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const n of[...e??[],...t??[]]){const e=s.get(n.url);void 0===e?(s.set(n.url,r.length),r.push(n)):r[e]=mergeSearchSource(r[e],n)}return r},J=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.sources=W(e.sources,t.sources)},H=(t,r,s)=>{const n="tool"===t.name&&"tool"!==r?r:t.name,o=!D(t.arguments)&&D(s)?s:t.arguments;n===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:n,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=n,t.arguments=o)},K=(t,r,s,n)=>{const o=f.get(t);if(o)return H(o,r,s),n&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;C();const a=y.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=D(s)?s:a?.arguments??s,d=((t,r,s)=>{const n=I,o=q;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:o,data:x(o)})),I+=1,q+=1,{partIndex:n,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return f.set(t,u),(n||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&Z(u,a),y.delete(t),u},G=(e,t)=>{const r=(e=>{const t=h.get(e);return t?f.get(t):f.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||H(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const s=Q(e);void 0!==t.name&&(s.name=t.name),void 0!==t.arguments&&(s.arguments=t.arguments),t.toolStartObserved&&(s.toolStartObserved=!0),t.itemEventObserved&&(s.itemEventObserved=!0)},V=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},X=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(X).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${X(t)}`).join(",")}}`},Y=(t,r,s)=>{const n=`${s?"1":"0"}:${X(r)}`;if(t.progressSignature===n)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...s?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=I;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=n,void(I+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=n},Z=(e,t)=>{if(t.progress?.length){for(const r of t.progress)Y(e,r.content,r.isError);V(e),j(e.id)}t.sources?.length&&R(t.sources,e.id)},ee=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],te=(e,t=[])=>{const r=[...new Set([...ee(e),...t])];return isNonEmptyString(e.text)&&r.length>0?{text:e.text,media_urls:r}:isNonEmptyString(e.text)?e.text:1===r.length?r[0]:r.length>1?{media_urls:r}:!0===e.isError?"Tool execution failed.":""},re=t=>{for(const r of t)e.stream.addPart(toMessagePart({type:"resource_link",uri:r.uri,name:r.name,...r.mimeType?{mimeType:r.mimeType}:{}})),I+=1},se=e=>{$.add(e),e.finally(()=>{$.delete(e)})},ne=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const s=pickRawResultFromPayload(r),n=(async()=>{let n=[];try{n=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:s,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:ee(r)})}catch(r){const s=r instanceof Error?r.message:String(r);return void e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}0!==n.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${n.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise(s=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const s=n.map(e=>e.uri);Y(t,te(r,s),!0===r.isError),((t,r,s)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),s),I+=1,re(r))})(t,n,!0===r.isError)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}finally{s()}})})):e.logger.debug?.(`[im-sink] tool artifact enrichment found no links requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`)})().catch(r=>{const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)});se(n)},oe=(e,t,r)=>{const s=h.get(e);if(s)return G(s,{name:t,arguments:r});const n=G(e,{name:t,arguments:r});if(n)return n;const o=L(t);if(o)return F(e,o),G(o,{name:t,arguments:r});G(e,{name:t,arguments:r})},ae=(e,t)=>{const r=h.get(e);if(r)return G(r,{name:t,itemEventObserved:!0,pending:!0});const s=G(e,{name:t,itemEventObserved:!0,pending:!0});if(s)return s;const n=(e=>{const t=v.filter(t=>{const r=f.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(n)return F(e,n),G(n,{name:t,itemEventObserved:!0,pending:!0});const o=B(t);G(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},ie={tool:0,block:0,final:0,source:0};let le,de=!1;const ue=(t,r)=>{e.callbackQueue.enqueueSync(()=>{if((t=>e.abortSignal.aborted?(e.logger.debug?.(`[im-sink] ${t} ignored after abort requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):e.stream.isTerminated?(e.logger.debug?.(`[im-sink] ${t} ignored after stream_terminated requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):!de||(e.logger.debug?.(`[im-sink] ${t} ignored after mark_complete requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1))(t))try{r()}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] ${t} mapping failed requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId} error=${s}`)}})};return{dispatcher:{sendToolResult:t=>(ue("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),n=resolveRuntimeToolArguments(t),o=te(t),a=!0===t.isError;let i;if(r){if(i=oe(r,s,n),!i){const e=Q(r);return s&&(e.name=s),D(n)&&(e.arguments=n),e.progress=[...e.progress??[],{content:o,isError:a}],void(ie.tool+=1)}}else{const t=s?L(s):L();if(!t)return B(s),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${v.length}`);i=G(t,{name:s,arguments:n})}i&&(ie.tool+=1,Y(i,o,a),V(i),j(i.id),ne(i,t))}),!0),sendBlockReply:e=>(ue("block_reply",()=>{ie.block+=1,isNonEmptyString(e.text)&&(le=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(ue("final_reply",()=>{var r;(ie.final+=1,!0!==t.isError)?((t=>{const r=ee(t).filter(e=>!w.has(e));if(0===r.length)return;for(const e of r)w.add(e);const s=(async()=>{let t=[];try{t=await resolveToolArtifactLinks({toolCallId:`final:${e.runId??e.requestId}`,toolName:"final_reply_media",payloadMediaUrls:r})}catch(t){for(const e of r)w.delete(e);return void e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}if(0!==t.length)await new Promise(r=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;re(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}finally{r()}})});else for(const e of r)w.delete(e)})();se(s)})(t),isNonEmptyString(t.text)&&(le=void 0,l||(r=t.text,i="",a+=r,k(a),M(r),l=!0))):le=t.text}),!0),waitForIdle:async()=>{for(let t=0;t<16&&(await e.callbackQueue.waitForIdle(),0!==$.size);t++)await Promise.allSettled([...$]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&re(t)},getQueuedCounts:()=>({tool:ie.tool,block:ie.block,final:ie.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>le,markComplete:r=>{U(),(_.length>0||y.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${_.length} buffered=${y.size}`),i="",k(a),c.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:c.receivedSnapshotCount,text_preview_streaming_publish_count:c.streamingPublishCount,text_preview_terminal_publish_count:c.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,c.receivedSnapshotCount-c.streamingPublishCount-c.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of f.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&ne(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&V(t),j(t.id)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool finalization failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}_.length=0,y.clear(),de=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:s=>{ue("partial",()=>{"string"==typeof s.text&&(!r&&s.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=s.text,(e=>{const t=m;if(!t){if(o.text===e)return;return P(e),void(m={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,T(t))})(a+i))})},onReasoningStream:e=>{ue("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??A(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,N(r)):(U(),A(t))))})},onReasoningEnd:()=>{ue("reasoning_end",()=>{U()})},onAssistantMessageStart:()=>{ue("assistant_message_start",()=>{i="",l=!1,k(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{ue("tool_start",()=>{const n="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===n)return void(a&&G(z(a),{name:o,arguments:i,pending:!0}));if(a&&e.onQuestionToolStart?.(o,a),a&&s.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){G(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=L(o);return void(e&&e!==a&&!h.has(a)&&(F(a,e),G(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>f.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void G(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...y.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?_.push({name:o,arguments:i}):G(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{ue("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",s=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),n=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);s&&n&&("update"!==r?ae(s,n):G(z(s),{name:n,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{ue("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,le=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,k(a);for(const t of e.segments)"text"!==t.type?K(t.id,t.name,t.arguments,!0):M(t.text)})},projectUserInputStatus:t=>ue("user_input_status",()=>{const r=t.response_message_id??t.submission_message_id,s="string"==typeof r&&["accepted","cancelled","rejected","unconfirmed"].includes(String(t.status)),n=["accepted","cancelled","expired","answered_elsewhere","unavailable","unsupported"].includes(String(t.status))||"answered"===t.native_status||"cancelled"===t.native_status,o="string"==typeof t.request_id?S.get(t.request_id):void 0;s&&n&&o&&e.stream.replacePart(o.index,toMessagePart({type:"custom",_seq:o.seq,kind:"question_wait",data:{...x(o.seq),request_id:t.request_id,status:t.status,observed_at_ms:t.updated_at_ms},value:{...t,type:"user_input_resolution"}}));const a=s?`receipt:${r}`:t.request_id;if("string"!=typeof a||!a)return;C();let i=S.get(a);const l=!i;i||(i={index:I++,seq:q++},S.set(a,i));const d=toMessagePart({type:"custom",_seq:i.seq,kind:s?"message_processing_receipt":"question_wait",data:{...x(i.seq),request_id:t.request_id,status:s&&"cancelled"===t.status?"accepted":t.status,observed_at_ms:t.updated_at_ms,...s?{response_message_id:r,..."cancelled"===t.status?{outcome:"cancelled"}:{}}:{},...t.error_code?{error_code:t.error_code}:{}},value:{...t,type:n?"user_input_resolution":"user_input_wait"}});l?e.stream.addPart(d):e.stream.replacePart(i.index,d)}),observeToolResult:r=>{ue("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;if(!n.has(o)){n.add(o);const i=s.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}const i=searchSourceProvider(r.rawResult)??"unknown";let l=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(l=t.length,0===l)return;const s=oe(o,a);if(s)R(t,s.id);else{const e=Q(z(o));e.name??=a,e.sources=W(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}})},getSourceCount:()=>ie.source}}
|
|
1
|
+
import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}},observedToolResultText=e=>{if(!isPlainRecord(e)||!Array.isArray(e.content))return;const t=e.content.filter(e=>isPlainRecord(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text.trim()).filter(Boolean);return t.length>0?t.join("\n"):void 0};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const s=new Map,n=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let c;const m={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const f=new Map,h=new Map,v=[],b=[],y=new Map,I=new Map;let _=0,S=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),k=new Set,$=new Set,q=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},w=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,de("body_preview_flush",()=>{c===e&&(e=>{o.text!==e.targetBody&&(q(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},C=e=>{const t=c;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(q(e),t.terminalPublishCount+=1),m.receivedSnapshotCount+=t.receivedSnapshotCount,m.streamingPublishCount+=t.streamingPublishCount,m.terminalPublishCount+=t.terminalPublishCount,c=void 0):q(e)},E=t=>{if(void 0!==t.partIndex)return;const r=_,s=S;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:x(s)})),t.partIndex=r,_+=1,S+=1},T=()=>{if(!d){d=!0;for(const e of g)E(e)}},P=e=>{const t={text:e};g.push(t),d&&E(t)},R=(t,r)=>{for(const s of t){const t=I.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const n={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:n.toolUseId,_seq:n.displaySeq,data:x(n.displaySeq)})),I.set(s.url,n);continue}const n={...s,partIndex:_,displaySeq:S,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:r,_seq:n.displaySeq,data:x(n.displaySeq)})),I.set(s.url,n),_+=1,S+=1,ae.source+=1}},M=(e,t,r,s)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==s?{_duration_ms:s}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),O=t=>{T();const r={partIndex:_,displaySeq:S,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(M(r,t,"streaming")),_+=1,S+=1,p=r,r},A=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,de("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,M(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},F=()=>{const r=p;if(!r)return;void 0!==r.publishTimer&&(clearTimeout(r.publishTimer),r.publishTimer=void 0);const s=Math.max(0,Math.round(performance.now()-r.startedAtMonotonicMs));e.stream.replacePart(r.partIndex,M(r,r.text,"done",s)),p=void 0,logChatLatency(e.logger,"claw.reasoning.settled",e.requestId,t,{reasoning_duration_ms:s,reasoning_chars:r.text.length,reasoning_snapshot_count:r.receivedSnapshotCount,reasoning_streaming_publish_count:r.streamingPublishCount,reasoning_coalesced_snapshot_count:Math.max(0,r.receivedSnapshotCount-r.streamingPublishCount),reasoning_publish_interval_ms:200})},N=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},U=e=>{const t=e?v.filter(t=>f.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},j=e=>{const t=b.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:s}]=t;return b.splice(s,1),r},L=(e,t)=>{if(h.set(e,t),e===t)return;const r=y.get(e);if(!r)return;const s=D(t);W(s,r),y.delete(e);const n=f.get(t);n&&(Y(n,s),y.delete(t))},B=e=>h.get(e)??e,z=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),D=e=>{let t=y.get(e);return t||(t={},y.set(e,t)),t},Q=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const n of[...e??[],...t??[]]){const e=s.get(n.url);void 0===e?(s.set(n.url,r.length),r.push(n)):r[e]=mergeSearchSource(r[e],n)}return r},W=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.observedResult??=t.observedResult,e.sources=Q(e.sources,t.sources)},J=(t,r,s)=>{const n="tool"===t.name&&"tool"!==r?r:t.name,o=!z(t.arguments)&&z(s)?s:t.arguments;n===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:n,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=n,t.arguments=o)},H=(t,r,s,n)=>{const o=f.get(t);if(o)return J(o,r,s),n&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;T();const a=y.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=z(s)?s:a?.arguments??s,d=((t,r,s)=>{const n=_,o=S;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:o,data:x(o)})),_+=1,S+=1,{partIndex:n,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return f.set(t,u),(n||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&Y(u,a),y.delete(t),u},K=(e,t)=>{const r=(e=>{const t=h.get(e);return t?f.get(t):f.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||J(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const s=D(e);void 0!==t.name&&(s.name=t.name),void 0!==t.arguments&&(s.arguments=t.arguments),t.toolStartObserved&&(s.toolStartObserved=!0),t.itemEventObserved&&(s.itemEventObserved=!0)},G=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},V=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${V(t)}`).join(",")}}`},X=(t,r,s)=>{const n=`${s?"1":"0"}:${V(r)}`;if(t.progressSignature===n)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...s?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=_;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=n,void(_+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=n},Y=(e,t)=>{if(t.progress?.length)for(const r of t.progress)X(e,r.content,r.isError);t.observedResult&&(X(e,t.observedResult.content,t.observedResult.isError),e.observedResult=t.observedResult),(t.progress?.length||t.observedResult)&&(G(e),N(e.id)),t.sources?.length&&R(t.sources,e.id)},Z=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],ee=(e,t=[])=>{const r=[...new Set([...Z(e),...t])];return isNonEmptyString(e.text)&&r.length>0?{text:e.text,media_urls:r}:isNonEmptyString(e.text)?e.text:1===r.length?r[0]:r.length>1?{media_urls:r}:!0===e.isError?"Tool execution failed.":""},te=t=>{for(const r of t)e.stream.addPart(toMessagePart({type:"resource_link",uri:r.uri,name:r.name,...r.mimeType?{mimeType:r.mimeType}:{}})),_+=1},re=t=>{k.add(t);const r=()=>{k.delete(t)};e.onCallbackFailure?t.then(r,r):t.finally(r)},se=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const s=pickRawResultFromPayload(r),n=(async()=>{let n=[];try{n=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:s,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:Z(r)})}catch(r){const s=r instanceof Error?r.message:String(r);if(e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r;return}0!==n.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${n.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise((s,o)=>{!1===e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const s=n.map(e=>e.uri);t.artifactMediaUrls=s;const o=t.observedResult;X(t,ee(o?{text:o.content,isError:o.isError}:r,s),o?.isError??!0===r.isError),((t,r,s)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),s),_+=1,te(r))})(t,n,o?.isError??!0===r.isError)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure&&o(r)}finally{s()}})&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(s,o)})):e.logger.debug?.(`[im-sink] tool artifact enrichment found no links requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`)})().catch(r=>{const s=r instanceof Error?r.message:String(r);if(e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r});re(n)},ne=(e,t,r)=>{const s=h.get(e);if(s)return K(s,{name:t,arguments:r});const n=K(e,{name:t,arguments:r});if(n)return n;const o=U(t);if(o)return L(e,o),K(o,{name:t,arguments:r});K(e,{name:t,arguments:r})},oe=(e,t)=>{const r=h.get(e);if(r)return K(r,{name:t,itemEventObserved:!0,pending:!0});const s=K(e,{name:t,itemEventObserved:!0,pending:!0});if(s)return s;const n=(e=>{const t=v.filter(t=>{const r=f.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(n)return L(e,n),K(n,{name:t,itemEventObserved:!0,pending:!0});const o=j(t);K(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},ae={tool:0,block:0,final:0,source:0};let ie,le=!1;const de=(t,r)=>{e.callbackQueue.enqueueSync(()=>{if((t=>e.abortSignal.aborted?(e.logger.debug?.(`[im-sink] ${t} ignored after abort requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):e.stream.isTerminated?(e.logger.debug?.(`[im-sink] ${t} ignored after stream_terminated requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):!le||(e.logger.debug?.(`[im-sink] ${t} ignored after mark_complete requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1))(t))try{r()}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] ${t} mapping failed requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId} error=${s}`),e.onCallbackFailure?.(r)}})};return{dispatcher:{sendToolResult:t=>(de("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),n=resolveRuntimeToolArguments(t),o=ee(t),a=!0===t.isError;let i;if(r){if(i=ne(r,s,n),!i){const e=D(r);return s&&(e.name=s),z(n)&&(e.arguments=n),e.progress=[...e.progress??[],{content:o,isError:a}],void(ae.tool+=1)}}else{const t=s?U(s):U();if(!t)return j(s),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${v.length}`);i=K(t,{name:s,arguments:n})}i&&(ae.tool+=1,i.observedResult||X(i,o,a),G(i),N(i.id),se(i,t))}),!0),sendBlockReply:e=>(de("block_reply",()=>{ae.block+=1,isNonEmptyString(e.text)&&(ie=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(de("final_reply",()=>{var r;(ae.final+=1,!0!==t.isError)?((t=>{const r=Z(t).filter(e=>!$.has(e));if(0===r.length)return;for(const e of r)$.add(e);const s=(async()=>{let t=[];try{t=await resolveToolArtifactLinks({toolCallId:`final:${e.runId??e.requestId}`,toolName:"final_reply_media",payloadMediaUrls:r})}catch(t){for(const e of r)$.delete(e);if(e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure)throw t;return}if(0!==t.length)await new Promise((r,s)=>{!1===e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;te(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure&&s(t)}finally{r()}})&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(r,s)});else for(const e of r)$.delete(e)})();re(s)})(t),isNonEmptyString(t.text)&&(ie=void 0,l||(r=t.text,i="",a+=r,C(a),P(r),l=!0))):ie=t.text}),!0),waitForIdle:async()=>{for(let t=0;(e.onCallbackFailure||t<16)&&(await e.callbackQueue.waitForIdle(),0!==k.size);t++)e.onCallbackFailure?await Promise.all([...k]):await Promise.allSettled([...k]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&te(t)},getQueuedCounts:()=>({tool:ae.tool,block:ae.block,final:ae.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>ie,markComplete:r=>{F(),(b.length>0||y.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${b.length} buffered=${y.size}`),i="",C(a),m.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:m.receivedSnapshotCount,text_preview_streaming_publish_count:m.streamingPublishCount,text_preview_terminal_publish_count:m.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,m.receivedSnapshotCount-m.streamingPublishCount-m.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of f.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&se(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&G(t),N(t.id)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool finalization failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}b.length=0,y.clear(),le=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:s=>{de("partial",()=>{"string"==typeof s.text&&(!r&&s.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=s.text,(e=>{const t=c;if(!t){if(o.text===e)return;return q(e),void(c={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,w(t))})(a+i))})},onReasoningStream:e=>{de("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??O(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,A(r)):(F(),O(t))))})},onReasoningEnd:()=>{de("reasoning_end",()=>{F()})},onAssistantMessageStart:()=>{de("assistant_message_start",()=>{i="",l=!1,C(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{de("tool_start",()=>{const n="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===n)return void(a&&K(B(a),{name:o,arguments:i,pending:!0}));if(a&&s.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){K(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=U(o);return void(e&&e!==a&&!h.has(a)&&(L(a,e),K(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>f.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void K(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...y.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?b.push({name:o,arguments:i}):K(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{de("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",s=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),n=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);s&&n&&("update"!==r?oe(s,n):K(B(s),{name:n,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{de("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,ie=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,C(a);for(const t of e.segments)"text"!==t.type?H(t.id,t.name,t.arguments,!0):P(t.text)})},observeToolResult:r=>{de("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;const i=!n.has(o);if(i){n.add(o);const i=s.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}if(e.persistObservedToolResults&&i){const e=observedToolResultText(r.rawResult);if(void 0!==e){const t=ne(o,a);if(t)X(t,ee({text:e,isError:r.isError},t.artifactMediaUrls),r.isError),t.observedResult={content:e,isError:r.isError},G(t),N(t.id);else{const t=D(B(o));t.name??=a,t.observedResult={content:e,isError:r.isError}}}}const l=searchSourceProvider(r.rawResult)??"unknown";let d=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(d=t.length,0===d)return;const s=ne(o,a);if(s)R(t,s.id);else{const e=D(B(o));e.name??=a,e.sources=Q(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${l} source_count=${d}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${l} source_count=${d}`)}})},getSourceCount:()=>ae.source}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";export class MessageServiceConversationClearHttpAuthority{options;
|
|
1
|
+
import{RUNTIME_HASH_DOMAINS,validateClearResetConvergence,validateConversationClearIntent}from"@beeos-ai/beeos-types/runtime";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export class MessageServiceConversationClearHttpAuthority{options;requests=new Map;plane;constructor(e){this.options=e,this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async prepare(e){const t={...e,requestHash:e.requestHash??"",requestMessageId:e.requestMessageId??e.fence.claimId},n=await this.post(t,"prepare");return this.requests.set(n.intent.intentId,t),n}async markResetting(e){return await this.post(this.binding(e),"resetting",{boundaryToken:e.intent.intentId,runConvergence:e.runConvergence,...e.activeRunRegistrationId?{activeRunRegistrationId:e.activeRunRegistrationId}:{}})}async markResetDone(e){return await this.transition(e,"reset_done")}async commit(e){const t=this.binding(e),n=await this.get({conversationId:e.intent.conversationId,intentId:e.intent.intentId});if("committed"===n.intent.state)return n;if("reset_done"!==n.intent.state||n.intent.version!==e.intent.version)throw unknown("clear commit requires the exact durable reset_done version");const r={cleared:!0,historyGeneration:n.intent.toGeneration,runConvergence:n.runConvergence},i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:"session/clear",result:r}),o={schemaVersion:1,operationId:e.intent.operationId,method:"session/clear",coreResultRef:`sha256:${i}`,coreResultHash:i},s=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o),a={schemaVersion:1,operationId:e.intent.operationId,requestMessageId:e.requestMessageId,requestHash:t.requestHash,dispatchEpoch:e.fence.runtimeEpoch,method:"session/clear",effectRecord:o,effectRecordHash:s,committedAt:(new Date).toISOString()};return await this.post(t,"commit",{boundaryToken:n.intent.intentId,effectReceipt:a})}async abortPrepared(e){return await this.transition(e,"abort")}async get(e){const t=this.requests.get(e.intentId);if(!t||t.conversationId!==e.conversationId)throw unknown("clear durable read requires a prepared request binding");return await this.post(t,"reconcile",{boundaryToken:e.intentId})}async transition(e,t,n={}){return await this.post(this.binding(e),t,{boundaryToken:e.intent.intentId,...n})}binding(e){const t=this.requests.get(e.intent.intentId);if(!t||t.operationId!==e.intent.operationId||t.conversationId!==e.intent.conversationId||t.requestMessageId!==e.requestMessageId||e.fence.runtimeEpoch!==t.fence.runtimeEpoch)throw unknown("clear request binding mismatch or unavailable");return{...t,fence:e.fence}}async post(e,t,n={}){const r={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,...this.options.runtimeLeaseCredential?{runtimeLeaseCredential:this.options.runtimeLeaseCredential}:{},...n};let i;try{i=await this.plane.historyBoundary({runtimeLeaseCredential:this.options.runtimeLeaseCredential??""},e.conversationId,t,r)}catch(e){if(e instanceof HarnessProtocolError)throw unknown(`Message Service clear authority failed (${e.status})`);throw e}if("string"==typeof i||void 0===i)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is not JSON");if(!record(i)||!record(i.intent))throw unknown("Message Service omitted canonical clear intent");const o=i.intent;if(!["intentId","operationId","conversationId","runtimeEpoch","createdAt","updatedAt"].every(e=>"string"==typeof o[e]&&o[e].length>0)||!["prepared","resetting","reset_done","committed","aborted"].includes(o.state)||!["fromGeneration","toGeneration","boundaryOffset","version"].every(e=>"string"==typeof o[e]&&/^\d+$/.test(o[e]))||void 0!==o.boundaryMessageId&&"string"!=typeof o.boundaryMessageId||!Number.isFinite(Date.parse(o.createdAt))||!Number.isFinite(Date.parse(o.updatedAt)))throw unknown("Message Service returned an incomplete canonical clear intent");const s=o;if(i.status!==s.state||i.conversationId!==s.conversationId||i.boundaryToken!==s.intentId||"string"!=typeof i.disposition||i.historyGeneration!==("committed"===s.state?s.toGeneration:s.fromGeneration)||i.boundaryOffset!==s.boundaryOffset)throw unknown("Message Service clear receipt summary disagrees with canonical intent");if(s.operationId!==e.operationId||s.conversationId!==e.conversationId||s.runtimeEpoch!==e.fence.runtimeEpoch||void 0!==n.boundaryToken&&s.intentId!==n.boundaryToken||validateConversationClearIntent(s).length)throw unknown("Message Service clear intent identity/fence mismatch");const a=i.runConvergence,c=i.activeRunRegistrationId;if(["resetting","reset_done","committed"].includes(s.state)&&!record(a))throw unknown("durable clear convergence receipt is missing");if(void 0!==a){if(!record(a)||!["no_active_run","already_terminal","terminal_observed"].includes(a.state)||!record(a.quiescence)||"verified"!==a.quiescence.state||"string"!=typeof a.quiescence.observedAt||"no_active_run"!==a.state&&("string"!=typeof a.runtimeRunId||0===a.runtimeRunId.length||!["completed","failed","cancelled"].includes(a.terminalState)||"string"!=typeof c||0===c.length)||"terminal_observed"===a.state&&(!record(a.abortObservation)||!["target_acknowledged","already_stopped","transport_unknown"].includes(a.abortObservation.state)||"transport_unknown"!==a.abortObservation.state&&(!Array.isArray(a.abortObservation.runIds)||!a.abortObservation.runIds.every(e=>"string"==typeof e))||"target_acknowledged"===a.abortObservation.state&&(!0!==a.abortObservation.aborted||!0!==a.abortObservation.targetRunAcknowledged)||"already_stopped"===a.abortObservation.state&&!1!==a.abortObservation.aborted)||"no_active_run"===a.state&&void 0!==c||validateClearResetConvergence(a,s.createdAt).length)throw unknown("durable clear convergence or active run registration is invalid")}else if(void 0!==c&&("string"!=typeof c||0===c.length))throw unknown("durable clear active run registration is invalid");return{intent:s,...void 0!==a?{runConvergence:a}:{},...void 0!==c?{activeRunRegistrationId:c}:{}}}}function unknown(e){return new RuntimeCommandError("OUTCOME_UNKNOWN",e)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export class MessageServiceConversationRunBoundary{options;constructor(t){this.options=t}async start(t){const
|
|
1
|
+
export class MessageServiceConversationRunBoundary{options;constructor(t){this.options=t}async start(t){const s=await this.post("start",t);if(isStartResult(s))return s;throw new Error("Message Service returned an invalid conversation run start result")}async finish(t){const s=await this.post("finish",t);if(isFinishResult(s))return s;throw new Error("Message Service returned an invalid conversation run finish result")}async post(t,s){let e;if("transport"in this.options)e="start"===t?await this.options.transport.start(s):await this.options.transport.finish(s);else{const i="start"===t?this.options.startUrl(s.conversationId):this.options.finishUrl(s.conversationId);e=await this.options.fetchAuthorized(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}if(!e.ok)throw new Error(`Message Service conversation run ${t} failed (${e.status})`);return await e.json()}}function isStartResult(t){if(!isRecord(t))return!1;if("registered"===t.status)return exactKeys(t,["status","activeRunRegistrationId","historyGeneration"])&&isString(t.activeRunRegistrationId)&&isDecimal(t.historyGeneration);if("rejected"!==t.status||!["HISTORY_GENERATION_MISMATCH","CONVERSATION_CLEARING","ACTIVE_RUN_CONFLICT"].includes(t.reason))return!1;const s=void 0===t.currentGeneration?["status","reason"]:["status","reason","currentGeneration"];return exactKeys(t,s)&&(void 0===t.currentGeneration||isDecimal(t.currentGeneration))}function isFinishResult(t){if(!isRecord(t))return!1;if("finished"===t.status||"idempotent"===t.status)return exactKeys(t,["status","activeRunRegistrationId"])&&isString(t.activeRunRegistrationId);if("rejected"!==t.status||!["ACTIVE_RUN_MISMATCH","HISTORY_GENERATION_MISMATCH","RUNTIME_EPOCH_MISMATCH"].includes(t.reason))return!1;const s=void 0===t.activeRunRegistrationId?["status","reason"]:["status","reason","activeRunRegistrationId"];return exactKeys(t,s)&&(void 0===t.activeRunRegistrationId||isString(t.activeRunRegistrationId))}const isRecord=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),isString=t=>"string"==typeof t&&t.length>0,isDecimal=t=>"string"==typeof t&&/^(0|[1-9][0-9]*)$/.test(t),exactKeys=(t,s)=>{const e=Object.keys(t).sort(),i=[...s].sort();return e.length===i.length&&e.every((t,s)=>t===i[s])};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export class MessageServiceCronDeliveryHttpAuthority{options;constructor(e){this.options=e
|
|
1
|
+
import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class MessageServiceCronDeliveryHttpAuthority{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("cron delivery requires X-Runtime-Delivery-Key");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async deliver(e){const r={schemaVersion:1,jobId:e.jobId,...e.runId?{runId:e.runId}:{},...void 0!==e.runAtMs?{runAtMs:e.runAtMs}:{},...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body,...e.status?{status:e.status}:{},runtimeLeaseCredential:e.runtimeLeaseCredential};let s;try{s=await this.plane.deliverCron({runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey},e.conversationId,r)}catch(e){if(e instanceof HarnessProtocolError)throw cronFailure(e);throw e}const t=record(s)&&record(s.data)?s.data:s;if(!record(t)||"delivered"!==t.status||"created"!==t.disposition&&"reused"!==t.disposition||t.conversationId!==e.conversationId||"string"!=typeof t.messageId||!t.messageId)throw new Error("Message Service cron conversation delivery receipt mismatch");return{status:"delivered",disposition:t.disposition,conversationId:e.conversationId,messageId:t.messageId}}}function cronFailure(e){const r=harnessDetail(e);return new Error(`Message Service cron conversation delivery failed (${e.status})${r}`)}function harnessDetail(e){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}return record(r)&&"string"==typeof r.message&&r.message?`: ${r.code??"error"}: ${r.message}`:""}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFAULT_FETCH_TIMEOUT_MS=8e3,DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS=[200,500],TRANSIENT_STATUSES=new Set([502,503,504]);export class MessageServiceRuntimeAuthenticatedFetch{options;cached;inflight;constructor(e){this.options=e}async ready(){const e=await this.token();return{serviceUrl:this.serviceUrl(e),identityId:e.identityId}}async fetch(e,t={}){let i=await this.token(),r=await this.execute(e,t,i);return 401!==r.status||(this.cached?.token===i.token&&(this.cached=void 0),i=await this.token(),r=await this.execute(e,t,i)),r}async fetchRuntimeChannel(e,t,i={},r){const n=await this.token(),s=
|
|
1
|
+
import{RuntimeLeaseHttp}from"@beeos-ai/cloud-harness-sdk";const DEFAULT_FETCH_TIMEOUT_MS=8e3,DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS=[200,500],TRANSIENT_STATUSES=new Set([502,503,504]);export class MessageServiceRuntimeAuthenticatedFetch{options;cached;inflight;constructor(e){this.options=e}async ready(){const e=await this.token();return{serviceUrl:this.serviceUrl(e),identityId:e.identityId}}async fetch(e,t={}){let i=await this.token(),r=await this.execute(e,t,i);return 401!==r.status||(this.cached?.token===i.token&&(this.cached=void 0),i=await this.token(),r=await this.execute(e,t,i)),r}async fetchRuntimeChannel(e,t,i={},r){const n=await this.token(),s=new URL(this.serviceUrl(n)),o={runtimeLeaseCredential:t.runtimeLeaseCredential,...t.scopedDeliveryKey?{scopedDeliveryKey:t.scopedDeliveryKey}:{},...t.executionGrant?{executionGrant:t.executionGrant}:{}},a=new RuntimeLeaseHttp({origin:s.origin,fetch:(e,t)=>this.fetchBounded(e instanceof Request?e.url:e,t)});return await a.fetch(e,o,i,{retry:!0===r?.retryTransientStatus})}async fetchBounded(e,t={}){const i=await this.token(),r=new URL(e),n=new URL(this.serviceUrl(i));if(r.origin!==n.origin)throw new Error("Message Service runtime authority cannot be sent to another origin");const s=this.options.fetchTimeoutMs??8e3,o=AbortSignal.timeout(s),a=t.signal?AbortSignal.any([t.signal,o]):o,c=await(this.options.fetcher??fetch)(r,{...t,signal:a});if(c.url&&new URL(c.url).origin!==n.origin)throw new Error("Message Service runtime response origin changed");return c}async token(){const e=Math.floor((this.options.now??Date.now)()/1e3),t=this.options.refreshSkewSeconds??15;return this.cached&&this.cached.expiresAt>e+t?this.cached:(this.inflight||(this.inflight=this.options.tokenProvider(this.options.identityHint??"").then(t=>{if(!t?.token||!t.identityId||!Number.isSafeInteger(t.expiresAt)||t.expiresAt<=e||!this.serviceUrl(t))throw new Error("Message Service runtime credential response is incomplete or expired");return this.cached=t,t}).finally(()=>{this.inflight=void 0})),await this.inflight)}serviceUrl(e){const t=this.options.configuredServiceUrl?.trim(),i=e.serviceUrl?.trim();if(!t&&!i)throw new Error("Message Service runtime URL is unavailable");const r=t?new URL(t):void 0,n=i?new URL(i):void 0;if(r&&n&&r.origin!==n.origin)throw new Error("Message Service configured and credential origins do not match");return(r??n).toString()}async execute(e,t,i){const r="string"==typeof e?new URL(e):e,n=new URL(this.serviceUrl(i));if(r.origin!==n.origin)throw new Error("Message Service runtime credential cannot be sent to another origin");const s=new Headers(t.headers);s.set("authorization",`Bearer ${i.token}`),s.set("sender-identity",i.identityId);const o=await this.fetchResilient(r,{...t,headers:s,redirect:"error"});if(o.url&&new URL(o.url).origin!==n.origin)throw new Error("Message Service authenticated response origin changed");return o}async fetchResilient(e,t,i){const r=this.options.fetcher??fetch,n=this.options.fetchTimeoutMs??8e3,s=this.options.transientRetryBackoffsMs??DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS,o=i?.retryTransientStatus??!0,a=s.length+1;for(let i=1;i<=a;i++){const c=AbortSignal.timeout(n),h=t.signal?AbortSignal.any([t.signal,c]):c;let u;try{u=await r(e,{...t,signal:h})}catch(e){if(!isTransientTransportError(e)||i===a)throw i===a&&e instanceof Error&&(e.message=`${e.message} (Message Service runtime request failed after ${i} attempts)`),e;await delay(s[i-1]);continue}if(!o||!TRANSIENT_STATUSES.has(u.status))return u;if(i===a)throw new Error(`Message Service runtime request failed after ${i} attempts (last status ${u.status})`);await delay(s[i-1])}throw new Error("Message Service runtime request resilience loop exited without a result")}}function isTransientTransportError(e){return e instanceof TypeError||e instanceof DOMException&&("TimeoutError"===e.name||"AbortError"===e.name)}const delay=e=>new Promise(t=>setTimeout(t,e));export function runtimeLeaseHttp(e,t){return new RuntimeLeaseHttp({origin:e,fetch:(e,i)=>t(e instanceof Request?e.url:e,i)})}export function fetchRuntimeLeaseAttempt(e,t={}){const i=AbortSignal.timeout(8e3),r=t.signal?AbortSignal.any([t.signal,i]):i;return fetch(e,{...t,signal:r})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{HarnessProtocolError,RuntimeClaimClient}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class RuntimeClaimAuthorityProtocolError extends Error{constructor(e){super(e),this.name="RuntimeClaimAuthorityProtocolError"}}export class MessageServiceRuntimeClaimHttpAuthority{claims;constructor(e){this.claims=new RuntimeClaimClient(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async claimNext(e){const t=await this.call("Message Service returned an invalid claim-next result",!1,()=>this.claims.claimNext(credential(e.runtimeLeaseCredential),e));return assertClaimNextResult(t,e),t}async claimExact(e){const t=await this.call("Message Service returned an invalid exact-claim result",!1,()=>this.claims.claimExact(credential(e.runtimeLeaseCredential),e));return assertClaimExactResult(t,e),t}async renewClaim(e){const t=await this.call("Message Service returned an invalid claim renew result",!1,()=>this.claims.renewClaim(credential(e.runtimeLeaseCredential),e));if(!t||!["renewed","fenced","expired","terminal"].includes(t.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim renew result");return t}async releaseClaim(e){await this.call("Message Service claim release failed",!0,()=>this.claims.releaseClaim(credential(e.runtimeLeaseCredential),e))}async call(e,t,r){try{return await r()}catch(r){if(!(r instanceof HarnessProtocolError))throw r;if(void 0!==r.status)throw new RuntimeClaimAuthorityProtocolError(t?`Message Service claim release failed (${r.status})`:`Message Service claim authority failed (${r.status})`);throw new RuntimeClaimAuthorityProtocolError(e)}}}function credential(e){return{runtimeLeaseCredential:e}}function assertClaimNextResult(e,t){if(!e||!["claimed","empty","fenced"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim-next result");if("claimed"!==e.status)return;const r=e.request.payload.command;if(e.request.payload.instanceId!==t.instanceId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration||r.context.dispatchEpoch!==t.runtimeEpoch)throw new RuntimeClaimAuthorityProtocolError("Message Service claim-next result does not match the request lease binding")}function assertClaimExactResult(e,t){if(!e||!["claimed","already_claimed","fenced","epoch_handoff_required","terminal"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid exact-claim result");if("claimed"===e.status&&(e.request.operationId!==t.operationId||e.request.messageId!==t.requestMessageId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration))throw new RuntimeClaimAuthorityProtocolError("Message Service exact-claim result does not match the recovery request")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";export class RuntimeMessageChannelProtocolError extends Error{status;code;constructor(e,t,o){super(e),this.status=t,this.code=o,this.name="RuntimeMessageChannelProtocolError"}}export class MessageServiceRuntimeMessageChannel{options;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("Message runtime delivery credential is required")}async read(e){const t=await this.post("/api/v1/runtime/deliveries/read",e.lease,{schemaVersion:1,maxCount:e.maxCount,blockMs:e.blockMs},void 0,e.signal);if(!record(t)||"deliveries"!==t.status||!Array.isArray(t.deliveries)||t.deliveries.length>e.maxCount||!t.deliveries.every(isDelivery)||new Set(t.deliveries.map(e=>e.deliveryId)).size!==t.deliveries.length)throw new RuntimeMessageChannelProtocolError("Message Service returned invalid runtime deliveries");return t.deliveries}async renew(e){const t=await this.post("/api/v1/runtime/deliveries/renew",e.lease,{schemaVersion:1,deliveryIds:e.deliveryIds});if(!(record(t)&&"renewed"===t.status&&strings(t.renewed)&&strings(t.notPending)&&exactIdPartition(e.deliveryIds,t.renewed,t.notPending)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery renewal");return{renewed:t.renewed,notPending:t.notPending}}async acknowledge(e){const t=await this.post("/api/v1/runtime/deliveries/ack",e.lease,{schemaVersion:1,deliveryIds:e.deliveryIds});if(!record(t)||"acknowledged"!==t.status||!strings(t.deliveryIds)||!sameIds(t.deliveryIds,e.deliveryIds))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery acknowledgement")}async history(e){const t=`/api/v1/runtime/operations/${encodeURIComponent(e.operationId)}/history`,o=await this.fetch(t,e.lease,{method:"GET"});if(404===o.status)return{status:"not_found"};if(410===o.status)return{status:"expired"};const r=await responseJson(o);if(!o.ok)throw protocolFailure(o,r,"runtime history read failed");if(!isHistory(r,e.operationId))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return{status:"found",snapshot:r}}async append(e){const t=`/api/v1/runtime/operations/${encodeURIComponent(e.operationId)}/messages`,o=appendResult(await this.post(t,e.lease,{schemaVersion:1,type:e.type,payload:e.payload},e.executionGrant)),r="runtime_rpc_response"===e.type?e.payload.requestMessageId:void 0;if(o.message.channel_id!==e.operationId||o.message.type!==e.type||o.message.in_reply_to!==r||!semanticEqual(o.message.payload,e.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return o}async post(e,t,o,r,n){const i=await this.fetch(e,t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),...n?{signal:n}:{}},r),s=await responseJson(i);if(!i.ok)throw protocolFailure(i,s,`runtime message-channel POST ${e} failed`);return s}async fetch(e,t,o,r){return await this.options.transport.fetchRuntimeChannel(new URL(e,this.options.serviceUrl),{runtimeLeaseCredential:t.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey,...r?{executionGrant:r}:{}},o,{retryTransientStatus:!1})}}export function decodeRuntimeBrokerDelivery(e){if(!isDelivery(e))throw new RuntimeMessageChannelProtocolError("Message Service returned an invalid runtime delivery");return e}export function decodeRuntimeOperationHistory(e,t){if(!isHistory(e,t))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return e}export function decodeRuntimeAppendMessage(e,t){if(!envelope(e))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");const o="runtime_rpc_response"===t.type?t.payload.requestMessageId:void 0;if(e.channel_id!==t.operationId||e.type!==t.type||e.in_reply_to!==o||!semanticEqual(e.payload,t.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return e}function appendResult(e){if(!record(e)||"persisted"!==e.status||"created"!==e.disposition&&"reused"!==e.disposition||!envelope(e.message))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");return{disposition:e.disposition,message:e.message}}function protocolFailure(e,t,o){const r=record(t)&&"string"==typeof t.code?t.code:void 0,n=record(t)&&"string"==typeof t.message?t.message:o;return new RuntimeMessageChannelProtocolError(`${n} (${e.status})`,e.status,r)}async function responseJson(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function strings(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function sameIds(e,t){return e.length===t.length&&[...e].sort().every((e,o)=>e===[...t].sort()[o])}function exactIdPartition(e,...t){return new Set(e).size===e.length&&!t.some(e=>new Set(e).size!==e.length)&&sameIds(t.flat(),e)}function envelope(e){return!!record(e)&&("string"==typeof e.message_id&&Number.isInteger(e.offset)&&e.offset>=1&&"string"==typeof e.channel_id&&(void 0===e.in_reply_to||"string"==typeof e.in_reply_to)&&["runtime_rpc_request","runtime_operation_started","runtime_operation_progress","runtime_effect_committed","runtime_projection_pending","runtime_projection_synced","runtime_projection_blocked","runtime_rpc_response","runtime_operation_cancel_requested"].includes(e.type)&&record(e.payload)&&"string"==typeof e.publisher_id&&"string"==typeof e.idempotency_key&&"string"==typeof e.created_at&&"completed"===e.state)}function isDelivery(e){return record(e)&&"string"==typeof e.deliveryId&&"boolean"==typeof e.redelivered&&Number.isInteger(e.idleMs)&&e.idleMs>=0&&envelope(e.message)&&(void 0===e.executionGrant||"string"==typeof e.executionGrant&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.executionGrant))&&["runtime_rpc_request","runtime_operation_cancel_requested"].includes(e.message.type)}function isHistory(e,t){if(!record(e))return!1;if(!(1===e.schemaVersion&&"string"==typeof e.operationId&&e.operationId===t&&"string"==typeof e.requestMessageId&&"string"==typeof e.requestHash&&["queued","running","runtime_committed","projection_pending","projection_blocked","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status)&&["","committed"].includes(e.effectState)&&"boolean"==typeof e.terminal&&["none","final_message","deadline"].includes(e.terminalSource)&&"boolean"==typeof e.cancelRequested&&["","reserved","pending","synced","blocked","not_applicable"].includes(e.projectionState)&&Array.isArray(e.messages)&&e.messages.every(envelope)&&Number.isInteger(e.latestOffset)&&!(e.latestOffset<1)))return!1;const o=validateRuntimeRequestEnvelope(e.request);if(!o.ok||e.request.channel_id!==e.operationId||o.envelope.payload.operationId!==e.operationId||o.envelope.payload.requestMessageId!==e.requestMessageId||o.envelope.payload.requestHash!==e.requestHash)return!1;const r=o.envelope.payload;if(void 0!==e.started&&!correlatedEnvelope(e.started,"runtime_operation_started",r,["schemaVersion","operationId","requestMessageId","requestHash","executionGrantHash","handlerIdentity","dispatchEpoch","method","executionMode","claimedAt"]))return!1;if(void 0!==e.latestProgress&&!correlatedEnvelope(e.latestProgress,"runtime_operation_progress",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","phase","progress"]))return!1;if(!(void 0===e.effectCommitted||correlatedEnvelope(e.effectCommitted,"runtime_effect_committed",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","effectRecord","effectRecordHash","committedAt"])&&validEffectCommitted(e.effectCommitted.payload,r)))return!1;if(void 0!==e.projectionPending&&!correlatedEnvelope(e.projectionPending,"runtime_projection_pending",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionSynced&&!correlatedEnvelope(e.projectionSynced,"runtime_projection_synced",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionBlocked&&!correlatedEnvelope(e.projectionBlocked,"runtime_projection_blocked",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision","errorCode"]))return!1;if(void 0!==e.cancel){const t=validateRuntimeCancelEnvelope(e.cancel);if(!t.ok||!sameCorrelation(t.envelope,r))return!1}if(void 0!==e.final&&!correlatedEnvelope(e.final,"runtime_rpc_response",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","outcome","response","completedAt"]))return!1;const n=e.messages;if(0===n.length||e.latestOffset!==n.length||n.some((t,o)=>t.offset!==o+1||t.channel_id!==e.operationId)||!semanticEqual(n[0],e.request)||!historyMessagesMatchSummaries(n,e)||!projectionStateMatches(e))return!1;if(e.terminal!==("none"!==e.terminalSource)||"committed"===e.effectState!=(void 0!==e.effectCommitted)||void 0!==e.effectCommitted&&void 0===e.started||"queued"===e.status&&(void 0!==e.started||void 0!==e.effectCommitted)||["running","runtime_committed","projection_pending","projection_blocked"].includes(e.status)&&void 0===e.started)return!1;if("none"===e.terminalSource)return void 0===e.final&&["queued","running","runtime_committed","projection_pending","projection_blocked"].includes(e.status);if("deadline"===e.terminalSource)return void 0===e.final&&(void 0===e.started?"expired"===e.status:"outcome_unknown"===e.status);if(!envelope(e.final))return!1;const i=e.final.payload.outcome,s="succeeded"===i?"succeeded":"cancelled"===i?"cancelled":"expired"===i?"expired":"outcome_unknown"===i?"outcome_unknown":"projection_blocked"===i?"projection_blocked":"failed"===i?"failed":void 0;return e.status===s}function validEffectCommitted(e,t){const o=e.effectRecord;return!!(record(o)&&1===o.schemaVersion&&o.operationId===t.operationId&&o.method===t.method&&"string"==typeof o.coreResultRef&&0!==o.coreResultRef.length&&"string"==typeof o.coreResultHash&&/^[0-9a-f]{64}$/.test(o.coreResultHash)&&(void 0===o.projectionRevision||"string"==typeof o.projectionRevision&&/^(0|[1-9][0-9]*)$/.test(o.projectionRevision))&&"string"==typeof e.effectRecordHash&&/^[0-9a-f]{64}$/.test(e.effectRecordHash)&&runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o)===e.effectRecordHash&&"string"==typeof e.committedAt&&Number.isFinite(Date.parse(e.committedAt)))}function projectionStateMatches(e){const t=e.effectCommitted?.payload?.effectRecord?.projectionRevision,o="deadline"===e.terminalSource,r=e=>record(e)&&record(e.payload)&&e.payload.revision===t;switch(e.projectionState){case"":return void 0===e.effectCommitted&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||["queued","running","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status));case"not_applicable":return void 0!==e.effectCommitted&&void 0===t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||["runtime_committed","succeeded","outcome_unknown"].includes(e.status));case"reserved":return void 0!==e.effectCommitted&&void 0!==t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||"runtime_committed"===e.status);case"pending":return void 0!==t&&r(e.projectionPending)&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||"projection_pending"===e.status);case"synced":return void 0!==t&&r(e.projectionPending)&&r(e.projectionSynced)&&void 0===e.projectionBlocked&&(o||["runtime_committed","succeeded"].includes(e.status));case"blocked":return void 0!==t&&r(e.projectionPending)&&void 0===e.projectionSynced&&r(e.projectionBlocked)&&(o||"projection_blocked"===e.status);default:return!1}}function historyMessagesMatchSummaries(e,t){const o=t=>e.filter(e=>e.type===t),r=(e,t,r=1)=>{const n=o(e);return n.length<=r&&(void 0===t?0===n.length:n.length>0&&semanticEqual(t,n.at(-1)))};if(!(r("runtime_rpc_request",t.request)&&r("runtime_operation_started",t.started)&&r("runtime_effect_committed",t.effectCommitted)&&r("runtime_projection_pending",t.projectionPending)&&r("runtime_projection_synced",t.projectionSynced)&&r("runtime_projection_blocked",t.projectionBlocked)&&r("runtime_operation_cancel_requested",t.cancel)&&r("runtime_rpc_response",t.final)))return!1;const n=o("runtime_operation_progress");if(void 0===t.latestProgress?0!==n.length:0===n.length||!semanticEqual(t.latestProgress,n.at(-1)))return!1;if(t.cancelRequested!==(void 0!==t.cancel))return!1;const i=e.findIndex(e=>"runtime_rpc_response"===e.type);return-1===i||i===e.length-1}function correlatedEnvelope(e,t,o,r){const n="runtime_rpc_response"===t?o.requestMessageId:void 0;return!(!envelope(e)||e.type!==t||!hasKeys(e.payload,r)||e.in_reply_to!==n)&&sameCorrelation(e,o)}function sameCorrelation(e,t){const o=e.payload;return e.channel_id===t.operationId&&o.operationId===t.operationId&&o.requestMessageId===t.requestMessageId&&o.requestHash===t.requestHash&&o.dispatchEpoch===t.dispatchEpoch&&o.method===t.method}function hasKeys(e,t){return t.every(t=>void 0!==e[t])}
|
|
1
|
+
import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{isDeepStrictEqual}from"node:util";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";import{retainedVerifiedNativePrompt}from"./native-prompt-authority.js";import{runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";export class RuntimeMessageChannelProtocolError extends Error{status;code;constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="RuntimeMessageChannelProtocolError"}}export class MessageServiceRuntimeMessageChannel{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("Message runtime delivery credential is required");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.serviceUrl,(t,r)=>e.transport.fetchBounded(t,r)))}async read(e){const t=await this.invoke(()=>this.plane.readDeliveries(this.credential(e.lease),{maxCount:e.maxCount,blockMs:e.blockMs},e.signal),"runtime delivery read failed");if(!record(t)||"deliveries"!==t.status||!Array.isArray(t.deliveries)||t.deliveries.length>e.maxCount||!t.deliveries.every(isDelivery)||new Set(t.deliveries.map(e=>e.deliveryId)).size!==t.deliveries.length)throw new RuntimeMessageChannelProtocolError("Message Service returned invalid runtime deliveries");return t.deliveries}async renew(e){const t=await this.invoke(()=>this.plane.renewDeliveries(this.credential(e.lease),e.deliveryIds),"runtime delivery renew failed");if(!(record(t)&&"renewed"===t.status&&strings(t.renewed)&&strings(t.notPending)&&exactIdPartition(e.deliveryIds,t.renewed,t.notPending)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery renewal");return{renewed:t.renewed,notPending:t.notPending}}async acknowledge(e){const t=await this.invoke(()=>this.plane.ackDeliveries(this.credential(e.lease),e.deliveryIds),"runtime delivery ack failed");if(!record(t)||"acknowledged"!==t.status||!strings(t.deliveryIds)||!sameIds(t.deliveryIds,e.deliveryIds))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery acknowledgement")}async history(e){let t;try{t=await this.plane.operationHistory(this.credential(e.lease),e.operationId)}catch(e){if(!(e instanceof HarnessProtocolError))throw e;if(404===e.status)return{status:"not_found"};if(410===e.status)return{status:"expired"};throw harnessFailure(e,"runtime history read failed")}if(!isHistory(t,e.operationId))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return{status:"found",snapshot:t}}async append(e){const t=appendResult(await this.invoke(()=>this.plane.appendOperationMessage(this.credential(e.lease,e.executionGrant),e.operationId,{type:e.type,payload:e.payload}),"runtime message-channel append failed")),r="runtime_rpc_response"===e.type?e.payload.requestMessageId:void 0;if(t.message.channel_id!==e.operationId||t.message.type!==e.type||t.message.in_reply_to!==r||!semanticEqual(t.message.payload,e.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return t}credential(e,t){return{runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey,...t?{executionGrant:t}:{}}}async invoke(e,t){try{return await e()}catch(e){if(e instanceof HarnessProtocolError)throw harnessFailure(e,t);throw e}}}export function decodeRuntimeBrokerDelivery(e){if(!isDelivery(e))throw new RuntimeMessageChannelProtocolError("Message Service returned an invalid runtime delivery");return e}export function decodeRuntimeOperationHistory(e,t){if(!isHistory(e,t))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return e}export function decodeNativePromptOperationHistory(e,t){const r=retainedVerifiedNativePrompt(t);if(!(r&&record(e)&&envelope(e.request)&&"runtime_rpc_request"===e.request.type&&void 0===e.request.in_reply_to&&e.request.message_id===r.request.requestMessageId&&e.request.channel_id===r.request.operationId&&isDeepStrictEqual(e.request.payload,r.request)&&isHistory(e,r.request.operationId,e.request)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid native prompt operation history");if(void 0!==e.runBoundary&&!validNativeRunObservation(e.runBoundary,r))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid native run audit");return e}function validNativeRunObservation(e,t){if(!record(e))return!1;const r=t.params,n=t.request,o=["operationId","requestMessageId","requestHash","conversationId","runtimeRunId","taskRequestMessageId","replyMessageId","historyGeneration"];if(o.some(t=>"string"!=typeof e[t])||Object.keys(e).some(e=>![...o,"registration","finishedReceipt"].includes(e))||e.operationId!==n.operationId||e.requestMessageId!==n.requestMessageId||e.requestHash!==n.requestHash||e.conversationId!==r.conversationId||e.runtimeRunId!==r.runtimeRunId||e.taskRequestMessageId!==r.taskRequestMessageId||e.replyMessageId!==r.replyMessageId||e.historyGeneration!==t.historyGeneration)return!1;const i=(e,t)=>{if(!record(e)||e.activeRunRegistrationId!==r.taskId||!["active","finished"].includes(e.state)||t&&"finished"!==e.state||Object.keys(e).some(e=>!["activeRunRegistrationId","state","terminalState","source","replyState","replyStopReason","replyUpdatedAt","finishedAt"].includes(e)))return!1;if("active"===e.state)return 2===Object.keys(e).length;const n=e=>"string"==typeof e&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Date.parse(e)>0,o=e=>{const t=e.match(/\.(\d{1,9})/)?.[1]??"";return 1000000n*BigInt(Date.parse(e))+BigInt(t.padEnd(9,"0").slice(3))};return["completed","failed","cancelled"].includes(e.terminalState)&&["runtime","recovery"].includes(e.source)&&["completed","failed","refused","cancelled"].includes(e.replyState)&&("refused"===e.replyState?"failed":e.replyState)===e.terminalState&&"string"==typeof e.replyStopReason&&e.replyStopReason.length>0&&n(e.replyUpdatedAt)&&n(e.finishedAt)&&o(e.finishedAt)>=o(e.replyUpdatedAt)};return(void 0===e.registration||i(e.registration,!1))&&(void 0===e.finishedReceipt||i(e.finishedReceipt,!0))}export function decodeRuntimeAppendMessage(e,t){if(!envelope(e))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");const r="runtime_rpc_response"===t.type?t.payload.requestMessageId:void 0;if(e.channel_id!==t.operationId||e.type!==t.type||e.in_reply_to!==r||!semanticEqual(e.payload,t.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return e}function appendResult(e){if(!record(e)||"persisted"!==e.status||"created"!==e.disposition&&"reused"!==e.disposition||!envelope(e.message))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");return{disposition:e.disposition,message:e.message}}function harnessFailure(e,t){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}const n=record(r)&&"string"==typeof r.code?r.code:void 0,o=record(r)&&"string"==typeof r.message?r.message:t;return new RuntimeMessageChannelProtocolError(`${o} (${e.status})`,e.status,n)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function strings(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function sameIds(e,t){return e.length===t.length&&[...e].sort().every((e,r)=>e===[...t].sort()[r])}function exactIdPartition(e,...t){return new Set(e).size===e.length&&!t.some(e=>new Set(e).size!==e.length)&&sameIds(t.flat(),e)}function envelope(e){return!!record(e)&&("string"==typeof e.message_id&&Number.isInteger(e.offset)&&e.offset>=1&&"string"==typeof e.channel_id&&(void 0===e.in_reply_to||"string"==typeof e.in_reply_to)&&["runtime_rpc_request","runtime_operation_started","runtime_operation_progress","runtime_effect_committed","runtime_projection_pending","runtime_projection_synced","runtime_projection_blocked","runtime_rpc_response","runtime_operation_cancel_requested"].includes(e.type)&&record(e.payload)&&"string"==typeof e.publisher_id&&"string"==typeof e.idempotency_key&&"string"==typeof e.created_at&&"completed"===e.state)}function isDelivery(e){return record(e)&&"string"==typeof e.deliveryId&&"boolean"==typeof e.redelivered&&Number.isInteger(e.idleMs)&&e.idleMs>=0&&envelope(e.message)&&(void 0===e.executionGrant||"string"==typeof e.executionGrant&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.executionGrant))&&["runtime_rpc_request","runtime_operation_cancel_requested"].includes(e.message.type)}function isHistory(e,t,r){if(!record(e))return!1;if(!(1===e.schemaVersion&&"string"==typeof e.operationId&&e.operationId===t&&"string"==typeof e.requestMessageId&&"string"==typeof e.requestHash&&["queued","running","runtime_committed","projection_pending","projection_blocked","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status)&&["","committed"].includes(e.effectState)&&"boolean"==typeof e.terminal&&["none","final_message","deadline"].includes(e.terminalSource)&&"boolean"==typeof e.cancelRequested&&["","reserved","pending","synced","blocked","not_applicable"].includes(e.projectionState)&&Array.isArray(e.messages)&&e.messages.every(envelope)&&Number.isInteger(e.latestOffset)&&!(e.latestOffset<1)))return!1;const n=r?{ok:!0,envelope:r}:validateRuntimeRequestEnvelope(e.request);if(!n.ok||e.request.channel_id!==e.operationId||n.envelope.payload.operationId!==e.operationId||n.envelope.payload.requestMessageId!==e.requestMessageId||n.envelope.payload.requestHash!==e.requestHash)return!1;const o=n.envelope.payload;if(void 0!==e.started&&!correlatedEnvelope(e.started,"runtime_operation_started",o,["schemaVersion","operationId","requestMessageId","requestHash","executionGrantHash","handlerIdentity","dispatchEpoch","method","executionMode","claimedAt"]))return!1;if(void 0!==e.latestProgress&&!correlatedEnvelope(e.latestProgress,"runtime_operation_progress",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","phase","progress"]))return!1;if(!(void 0===e.effectCommitted||correlatedEnvelope(e.effectCommitted,"runtime_effect_committed",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","effectRecord","effectRecordHash","committedAt"])&&validEffectCommitted(e.effectCommitted.payload,o)))return!1;if(void 0!==e.projectionPending&&!correlatedEnvelope(e.projectionPending,"runtime_projection_pending",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionSynced&&!correlatedEnvelope(e.projectionSynced,"runtime_projection_synced",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionBlocked&&!correlatedEnvelope(e.projectionBlocked,"runtime_projection_blocked",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision","errorCode"]))return!1;if(void 0!==e.cancel){const t=validateRuntimeCancelEnvelope(e.cancel);if(!t.ok||!sameCorrelation(t.envelope,o))return!1}if(void 0!==e.final&&!correlatedEnvelope(e.final,"runtime_rpc_response",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","outcome","response","completedAt"]))return!1;const i=e.messages;if(0===i.length||e.latestOffset!==i.length||i.some((t,r)=>t.offset!==r+1||t.channel_id!==e.operationId)||!semanticEqual(i[0],e.request)||!historyMessagesMatchSummaries(i,e)||!projectionStateMatches(e))return!1;if(e.terminal!==("none"!==e.terminalSource)||"committed"===e.effectState!=(void 0!==e.effectCommitted)||void 0!==e.effectCommitted&&void 0===e.started||"queued"===e.status&&(void 0!==e.started||void 0!==e.effectCommitted)||["running","runtime_committed","projection_pending","projection_blocked"].includes(e.status)&&void 0===e.started)return!1;if("none"===e.terminalSource)return void 0===e.final&&["queued","running","runtime_committed","projection_pending","projection_blocked"].includes(e.status);if("deadline"===e.terminalSource)return void 0===e.final&&(void 0===e.started?"expired"===e.status:"outcome_unknown"===e.status);if(!envelope(e.final))return!1;const s=e.final.payload.outcome,a="succeeded"===s?"succeeded":"cancelled"===s?"cancelled":"expired"===s?"expired":"outcome_unknown"===s?"outcome_unknown":"projection_blocked"===s?"projection_blocked":"failed"===s?"failed":void 0;return e.status===a}function validEffectCommitted(e,t){const r=e.effectRecord;return!!(record(r)&&1===r.schemaVersion&&r.operationId===t.operationId&&r.method===t.method&&"string"==typeof r.coreResultRef&&0!==r.coreResultRef.length&&"string"==typeof r.coreResultHash&&/^[0-9a-f]{64}$/.test(r.coreResultHash)&&(void 0===r.projectionRevision||"string"==typeof r.projectionRevision&&/^(0|[1-9][0-9]*)$/.test(r.projectionRevision))&&"string"==typeof e.effectRecordHash&&/^[0-9a-f]{64}$/.test(e.effectRecordHash)&&runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,r)===e.effectRecordHash&&"string"==typeof e.committedAt&&Number.isFinite(Date.parse(e.committedAt)))}function projectionStateMatches(e){const t=e.effectCommitted?.payload?.effectRecord?.projectionRevision,r="deadline"===e.terminalSource,n=e=>record(e)&&record(e.payload)&&e.payload.revision===t;switch(e.projectionState){case"":return void 0===e.effectCommitted&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||["queued","running","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status));case"not_applicable":return void 0!==e.effectCommitted&&void 0===t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||["runtime_committed","succeeded","outcome_unknown"].includes(e.status));case"reserved":return void 0!==e.effectCommitted&&void 0!==t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||"runtime_committed"===e.status);case"pending":return void 0!==t&&n(e.projectionPending)&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||"projection_pending"===e.status);case"synced":return void 0!==t&&n(e.projectionPending)&&n(e.projectionSynced)&&void 0===e.projectionBlocked&&(r||["runtime_committed","succeeded"].includes(e.status));case"blocked":return void 0!==t&&n(e.projectionPending)&&void 0===e.projectionSynced&&n(e.projectionBlocked)&&(r||"projection_blocked"===e.status);default:return!1}}function historyMessagesMatchSummaries(e,t){const r=t=>e.filter(e=>e.type===t),n=(e,t,n=1)=>{const o=r(e);return o.length<=n&&(void 0===t?0===o.length:o.length>0&&semanticEqual(t,o.at(-1)))};if(!(n("runtime_rpc_request",t.request)&&n("runtime_operation_started",t.started)&&n("runtime_effect_committed",t.effectCommitted)&&n("runtime_projection_pending",t.projectionPending)&&n("runtime_projection_synced",t.projectionSynced)&&n("runtime_projection_blocked",t.projectionBlocked)&&n("runtime_operation_cancel_requested",t.cancel)&&n("runtime_rpc_response",t.final)))return!1;const o=r("runtime_operation_progress");if(void 0===t.latestProgress?0!==o.length:0===o.length||!semanticEqual(t.latestProgress,o.at(-1)))return!1;if(t.cancelRequested!==(void 0!==t.cancel))return!1;const i=e.findIndex(e=>"runtime_rpc_response"===e.type);return-1===i||i===e.length-1}function correlatedEnvelope(e,t,r,n){const o="runtime_rpc_response"===t?r.requestMessageId:void 0;return!(!envelope(e)||e.type!==t||!hasKeys(e.payload,n)||e.in_reply_to!==o)&&sameCorrelation(e,r)}function sameCorrelation(e,t){const r=e.payload;return e.channel_id===t.operationId&&r.operationId===t.operationId&&r.requestMessageId===t.requestMessageId&&r.requestHash===t.requestHash&&r.dispatchEpoch===t.dispatchEpoch&&r.method===t.method}function hasKeys(e,t){return t.every(t=>void 0!==e[t])}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{performance}from"node:perf_hooks";export class MessageServiceSessionModelHttpAuthority{options;constructor(e){this.options=e}async project(e){const
|
|
1
|
+
import{performance}from"node:perf_hooks";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class MessageServiceSessionModelHttpAuthority{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("session model requires X-Runtime-Delivery-Key");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async project(e){const r=performance.now();let o="succeeded";try{let r;try{r=await this.plane.projectSessionModel({runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey},e.conversationId,{schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,modelOverrideId:e.modelOverrideId,runtimeLeaseCredential:e.runtimeLeaseCredential})}catch(e){if(e instanceof HarnessProtocolError)throw sessionModelFailure(e);throw e}const o=record(r)&&record(r.data)?r.data:r;if(!record(o)||"projected"!==o.status||"created"!==o.disposition&&"reused"!==o.disposition||o.conversationId!==e.conversationId)throw new Error("Message Service session model projection receipt mismatch");const s=void 0===o.modelOverrideId||null===o.modelOverrideId?null:"string"==typeof o.modelOverrideId?o.modelOverrideId:void 0;if(void 0===s||s!==e.modelOverrideId)throw new Error("Message Service session model projection modelOverrideId mismatch");return{status:"projected",disposition:o.disposition,conversationId:e.conversationId,modelOverrideId:s}}catch(e){throw o="failed",e}finally{process.stderr.write(`[MODEL_SWITCH_TIMING] component=runtime operationId=${e.operationId} stage=message_service_project_model outcome=${o} durationMs=${(performance.now()-r).toFixed(1)}\n`)}}}function sessionModelFailure(e){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}const o=record(r)&&"string"==typeof r.message&&r.message?`: ${r.code??"error"}: ${r.message}`:"";return new Error(`Message Service session model projection failed (${e.status})${o}`)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";const leaseStarvationReportIntervalMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,o,a,n,r,i){if(this.dispatcher=e,this.channel=t,this.verifier=o,this.ports=a,this.journal=n,this.getLease=r,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.externalDeliveryOwner)return void this.externalDeliveryOwner.start();if(this.running)return;const e=new AbortController;this.controller=e;const t=this.loop(e.signal).catch(t=>{e.signal.aborted||this.observeDeliveryError(t)}).finally(()=>{this.running===t&&(this.running=void 0)});this.running=t}async stop(e){this.controller?.abort();for(const e of this.workers.values())e.cancel?.();if(this.externalDeliveryOwner)return await this.externalDeliveryOwner.stop(e),void await Promise.allSettled([...this.workers.values()].map(e=>e.completion));this.running&&await abortable(this.running,e)}attachExternalDeliveryOwner(e){if(this.running||this.externalDeliveryOwner)throw new Error("runtime delivery owner is already attached");this.externalDeliveryOwner=e}async acceptDelivery(e,t,o){if(this.currentLease(t),e.message.type===RUNTIME_MESSAGE_TYPES.cancel)return void await this.handleCancel(e,t);const a=validateRuntimeRequestEnvelope(e.message),n=a.ok?a.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(n))return;const r={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};r.completion=this.handleRequest(e,t,o,e=>{r.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(n)}),this.workers.set(n,r),await r.completion}async acceptPoisonDelivery(e,t,o){await this.handlePoison(e,t,o)}async readOperationHistory(e){const t=this.getLease();if(!t)return{status:"unavailable"};try{return await this.channel.history({operationId:e.operationId,lease:t})}catch{return{status:"unavailable"}}}async loop(e){let t;(()=>{t||(t=setInterval(()=>{this.renewActive().catch(e=>this.observeDeliveryError(e))},this.options.renewIntervalMs??2e4),t.unref?.())})();try{for(;!e.aborted;){const t=this.getLease();if(!t){this.observeLeaseStarvation(),await delay(this.options.idleDelayMs??500,e);continue}let o;this.observeLeaseRestored();try{o=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const a of o){if(e.aborted)break;if(a.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(a,t).catch(e=>this.observeDeliveryError(e));continue}const o=a.message.channel_id;if(this.workers.has(o))continue;const n={deliveryId:a.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(a,t,e,e=>{n.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,n)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}observeLeaseStarvation(){const e=Date.now();this.leaseStarvedSince??=e;const t=e-this.leaseStarvedSince;if(!(t<3e4||this.leaseStarvationReportedAt&&e-this.leaseStarvationReportedAt<3e4)){this.leaseStarvationReportedAt=e;try{this.options.onLeaseStarvation?.({starvedForMs:t,recovered:!1})}catch{}}}observeLeaseRestored(){const e=this.leaseStarvedSince;if(void 0===e)return;this.leaseStarvedSince=void 0;const t=this.leaseStarvationReportedAt;if(this.leaseStarvationReportedAt=0,t)try{this.options.onLeaseStarvation?.({starvedForMs:Date.now()-e,recovered:!0})}catch{}}observeRequestFailure(e,t,o){try{this.options.onRequestFailure?.({operationId:e,method:t,error:o})}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const o of this.workers.values())sameLeaseBinding(o.claimedLease,e)?t.push(o.deliveryId):o.cancel?.();if(!t.length)return;let o;try{o=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),o.notPending.length){const e=new Set(o.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const o=validateRuntimeCancelEnvelope(e.message);if(!o.ok)return void await this.handlePoison(e,`invalid_cancel:${o.reason}`,t);const a=o.envelope.payload,n=await this.channel.history({operationId:a.operationId,lease:t});if("found"===n.status&&n.snapshot.terminal&&"final_message"===n.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===n.status||"expired"===n.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const r=n.snapshot.request.payload;r.operationId===a.operationId&&r.requestMessageId===a.requestMessageId&&r.requestHash===a.requestHash&&r.dispatchEpoch===a.dispatchEpoch&&r.method===a.method?(await this.journal.observeCancellation({operationId:a.operationId,requestMessageId:a.requestMessageId,requestHash:a.requestHash,eventId:a.eventId}),this.workers.get(a.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,o,a){const n=validateRuntimeRequestEnvelope(e.message);if(!n.ok)return void await this.handlePoison(e,`invalid_request:${n.reason}`,t);const r=n.envelope.payload,i=e.executionGrant,s=createRuntimeAppendTimingRecorder("runtime-op",{operationId:r.operationId,method:r.method}),c=new AbortController;a(()=>c.abort());const d=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),s.mark("ack")},l=await this.channel.history({operationId:r.operationId,lease:t});if(s.mark("history"),"not_found"===l.status||"expired"===l.status)return void await d();if(l.snapshot.terminal&&"final_message"===l.snapshot.terminalSource)return void await d();if(this.options.allowedMethods&&!this.options.allowedMethods.has(r.method))return await this.reject(r,"unsupported_method",t),void await d();if("deadline"===l.snapshot.terminalSource||Date.parse(r.executionDeadlineAt)<=Date.now()||!l.snapshot.started&&Date.parse(r.claimDeadlineAt)<=Date.now())return await this.reject(r,"execution_deadline_exceeded",t),void await d();const p=await this.journal.getCancellation(r.operationId);s.mark("journal-cancel-read");const u=l.snapshot.cancelRequested||null!==p;if(u&&"queued"===l.snapshot.status)return await this.reject(r,"cancelled_before_dispatch",t),void await d();if(r.instanceId!==t.instanceId||r.runtimeHandlerIdentity!==t.handlerIdentity||r.dispatchEpoch!==t.runtimeEpoch)return await this.reject(r,"authority_mismatch",t),void await d();const m=l.snapshot.request.payload;if(l.snapshot.operationId!==r.operationId||l.snapshot.requestMessageId!==r.requestMessageId||l.snapshot.requestHash!==r.requestHash||!semanticEqual(m,r))return void await this.handlePoison(e,"request_history_mismatch",t);const h=l.snapshot.started?.payload,I=void 0!==h&&h.operationId===r.operationId&&h.requestMessageId===r.requestMessageId&&h.requestHash===r.requestHash&&h.executionGrantHash===r.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===r.method,E=await this.journal.get(r.operationId);s.mark("journal-prior");const v=runtimeCommandIsReplayableQuery(r.command.name),f=v?ephemeralQueryAccept(r):await this.journal.acceptMessageRequest({operationId:r.operationId,command:r.command.name,paramsHash:r.paramsHash,runtimeEpoch:r.dispatchEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash});s.mark("journal-accept");const R=I?E:f,y=v?"execute":decideMessageServiceRecovery(l.snapshot,r,R,I);if("already_terminal"===y)return void await d();if(!CORE_RECOVERY_DECISIONS.has(y))return v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${y}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await d();if(await this.verifier.refresh(),s.mark("verifier-refresh"),!i)return I?await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(r,"invalid_execution_grant",t),void await d();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>c.abort();let w;o.addEventListener("abort",_,{once:!0});try{w=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:r,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:I,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:r,executionGrant:i,command:r.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:f,abortSignal:c.signal})})}catch(e){if(o.removeEventListener("abort",_),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(r,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await d()}if(!w.ok)return o.removeEventListener("abort",_),c.abort(),I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(r,"invalid_execution_grant",t),void await d();if(!u||"prepared"!==f.phase&&"started"!==f.phase||c.abort(),c.signal.aborted&&!I)return o.removeEventListener("abort",_),await this.reject(r,"cancelled_before_dispatch",t),void await d();s.mark("attempt"),I?this.currentLease(t):(await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(r),executionMode:"start",executionGrantHash:r.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:f.messageBinding?.acceptedAt??f.updatedAt}}),s.mark("append-started"));const g=this.dispatcher.dispatch(r.command,w.context);g.completion.catch(()=>{}),a(()=>{c.abort(),g.cancel()}),c.signal.aborted&&g.cancel();const M=this.forwardProgress(r,g.progress,t).catch(()=>{});let S,O=!1;try{if(("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(g)){const e=await g.effectCommitted;if(e){if(e.operationId!==r.operationId||e.method!==r.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const o=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:e.result}),a={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${o}`,coreResultHash:o};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,a),O=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:a,effectRecordHash:S,committedAt:e.committedAt}}),await g.acknowledgeEffectReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:S})}}const o=await g.completion;if(await M,s.mark("core"),v){const a=(new Date).toISOString();let n;try{n=sanitizeRuntimeServiceResult(r.method,o,w.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:n}),c=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:n},serviceResultHash:i,completedAt:a}});return s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,c.message),await d(),void this.observeRequestAcknowledged(e.deliveryId,c.message)}const a=await this.journal.get(r.operationId);if(s.mark("journal-after-core"),!a||!isCommittedCorePhase(a.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const n=a.updatedAt;let i,c;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[r.method]){const e=isAgentProjectionMethod(r.method),c=g.getSnapshot().projection,l=a.agentProjectionIntent??a.agentProjectionPreparationFailure;if(e&&!l)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!S&&"session/clear"!==r.method){const e=l?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:o}),i=a.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(r.method)?c?.revision??`${Math.max(0,a.revision)}`:void 0),d={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,d),O=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:d,effectRecordHash:S,committedAt:n}}),s.mark("append-effect")}let p=e?await awaitRuntimeProjection(g):c;if("session/set_model"!==r.method&&"session/set_reasoning"!==r.method||"synced"===p?.state||(p=await this.projectSessionModelAfterEffect(r,w.context,a,p,o),s.mark("set-model-projection")),e&&a.agentProjectionIntent&&(!p||p.revision!==a.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===p?.state)return void await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(r),revision:p.revision}});if("synced"===p?.state&&await this.publishProjectionSynced(r,t,{...p,state:"synced"}),"blocked"===p?.state){await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(r),revision:p.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:r.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:r.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:S,completedAt:n}}),void await d()}i=e?p?.platformAgentId:void 0}try{c=sanitizeRuntimeServiceResult(r.method,o,w.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const l=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:c});O=!0;const p=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:c},serviceResultHash:l,...S?{effectRecordHash:S}:{},completedAt:n}});if(s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,p.message),("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(g)&&"function"==typeof g.acknowledgeTerminalReceipt){if(!S)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await g.acknowledgeTerminalReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:S,terminalMessageId:p.message.message_id})}await d(),this.observeRequestAcknowledged(e.deliveryId,p.message)}catch(e){const o=await this.journal.get(r.operationId);if(o&&isCommittedCorePhase(o.phase)&&O)throw e;const a=!o||!isCommittedCorePhase(o.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(r.operationId,r.method,a);const n=failurePayload(r,a,o?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:n}),s.mark("append-terminal-failure"),await d()}finally{s.finish(),c.abort(),o.removeEventListener("abort",_)}}async handlePoison(e,t,o){this.currentLease(o);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(o)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,o){for await(const a of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:a.phase,progress:a}})}async reject(e,t,o){await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,o,a,n){const r=Object.freeze({state:"pending",revision:a?.revision??`${Math.max(0,o.revision)}`}),i=e.command;if("conversation"!==i.context.scope)return r;if("session.setModel"!==i.name&&"session.setReasoning"!==i.name)return r;try{const e=i.context.conversation.runtimeConversationUid;if("session.setReasoning"===i.name){if(!t.sessionReasoningProjection||!n)return r;await t.sessionReasoningProjection.project({conversationId:e,reasoning:n})}else{if(!t.sessionModelProjection)return r;await t.sessionModelProjection.project({conversationId:e,modelOverrideId:i.params.modelOverrideId})}const a=Object.freeze({state:"synced",revision:r.revision});try{const e=await this.journal.get(o.operationId)??o;if("projection_committed"===e.phase&&"synced"===e.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:e.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"projection_committed",projectionSnapshot:a})}catch{}return a}catch(e){return this.observeDeliveryError(e),r}}async publishProjectionSynced(e,t,o){const a=this.currentLease(t),n=await this.channel.history({operationId:e.operationId,lease:a});if("found"===n.status&&"synced"===n.snapshot.projectionState)return;const r={...runtimeMessageBase(e),revision:o.revision};("found"!==n.status||"reserved"===n.snapshot.projectionState||"pending"!==n.snapshot.projectionState&&void 0===n.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:a,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:r}),await this.channel.append({operationId:e.operationId,lease:a,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...r,...o.platformAgentId?{platformAgentId:o.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,o,a){const n=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),r=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":a?"running":"queued",i="failed"===o?.phase||"outcome_unknown"===o?.phase?"terminal":o?.phase,s=o&&o.runtimeEpoch===t.dispatchEpoch&&(void 0===o.messageBinding||o.messageBinding.requestMessageId===t.requestMessageId&&o.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:n?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(n?.projectionRequired??!1),messageServicePhase:r,executionBoundaryCrossed:a,lineageContinuity:s,journalState:o?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,o,a){if("session/clear"===e)return serviceClearResult(t,o?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,o);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const n="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,n,{...a?{platformAgentId:a}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const o=t;if(!o.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:o.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const o=t.verifiedMessageGrant?.claims.command;if(!o||"session.setModel"!==o.name||"conversation"!==o.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const a=o.params.modelOverrideId;return{conversationId:o.context.conversation.runtimeConversationUid,...null===a?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:a,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e||"session/set_reasoning"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,o){const a=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",n=a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED",r="OUTCOME_UNKNOWN"===n||"INSTANCE_EPOCH_MISMATCH"===n?"outcome_unknown":"COMMAND_EXPIRED"===n?"expired":"OPERATION_CANCELLED"===n?"cancelled":"failed",i="outcome_unknown"===r?"OUTCOME_UNKNOWN":n,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===r?"outcome_unknown":r;return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:o}}function prestartFailurePayload(e,t){const o="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",a=RUNTIME_ERROR_DESCRIPTORS[o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED"],n="COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:a.jsonRpcCode,message:o,data:{code:o,operationId:e.operationId,effectState:n,retryMode:a.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((o,a)=>{const n=()=>o();t.addEventListener("abort",n,{once:!0}),e.then(()=>{t.removeEventListener("abort",n),o()},e=>{t.removeEventListener("abort",n),a(e)})}):e}function delay(e,t){return new Promise(o=>{if(t?.aborted)return o();const a=()=>{clearTimeout(n),o()},n=setTimeout(()=>{t?.removeEventListener("abort",a),o()},e);t?.addEventListener("abort",a,{once:!0})})}
|
|
1
|
+
import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"@beeos-ai/cloud-harness-sdk";import{NativePromptExecutionFailure,nativePromptCancellationReason,nativePromptUnknownReason}from"./native-cloud-prompt-bridge.js";const leaseStarvationReportIntervalMs=3e4,maxReadBackoffMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;readTransportFailurePolicy=new RuntimeTransportFailurePolicy;readBackoffMs=0;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,a,r,o,n,i){if(this.dispatcher=e,this.channel=t,this.verifier=a,this.ports=r,this.journal=o,this.getLease=n,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.externalDeliveryOwner)return void this.externalDeliveryOwner.start();if(this.running)return;const e=new AbortController;this.controller=e;const t=this.loop(e.signal).catch(t=>{e.signal.aborted||this.observeDeliveryError(t)}).finally(()=>{this.running===t&&(this.running=void 0)});this.running=t}async stop(e){this.controller?.abort();for(const e of this.workers.values())this.cancelWorker(e);if(this.externalDeliveryOwner)return await this.externalDeliveryOwner.stop(e),void await Promise.allSettled([...this.workers.values()].map(e=>e.completion));this.running&&await abortable(this.running,e)}attachExternalDeliveryOwner(e){if(this.running||this.externalDeliveryOwner)throw new Error("runtime delivery owner is already attached");this.externalDeliveryOwner=e}async acceptDelivery(e,t,a){if(this.currentLease(t),e.message.type===RUNTIME_MESSAGE_TYPES.cancel)return void await this.handleCancel(e,t);const r=validateRuntimeRequestEnvelope(e.message),o=r.ok?r.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(o))return;const n={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(e,t,a,e=>{this.setWorkerCancel(n,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,n),await n.completion}async acceptPoisonDelivery(e,t,a){await this.handlePoison(e,t,a)}async readOperationHistory(e){const t=this.getLease();if(!t)return{status:"unavailable"};try{return await this.channel.history({operationId:e.operationId,lease:t})}catch{return{status:"unavailable"}}}async loop(e){let t;(()=>{t||(t=setInterval(()=>{this.renewActive().catch(e=>this.observeDeliveryError(e))},this.options.renewIntervalMs??2e4),t.unref?.())})();try{for(;!e.aborted;){const t=this.getLease();if(!t){this.observeLeaseStarvation(),await delay(this.options.idleDelayMs??500,e);continue}let a;this.observeLeaseRestored();try{a=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.readFailureDelayMs(t),e);continue}this.readTransportFailurePolicy.recordSuccess(),this.readBackoffMs=0;for(const r of a){if(e.aborted)break;if(r.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(r,t).catch(e=>this.observeDeliveryError(e));continue}const a=r.message.channel_id;if(this.workers.has(a))continue;const o={deliveryId:r.deliveryId,claimedLease:t,completion:Promise.resolve()};o.completion=this.handleRequest(r,t,e,e=>{this.setWorkerCancel(o,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(a)}),this.workers.set(a,o)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}readFailureDelayMs(e){const t=this.options.idleDelayMs??500,a=e instanceof RuntimeMessageChannelProtocolError?e.status:void 0;return 401===a||403===a||this.readTransportFailurePolicy.recordFailure()?(this.readBackoffMs=Math.min(this.readBackoffMs?2*this.readBackoffMs:2*t,3e4),this.readBackoffMs):t}observeLeaseStarvation(){const e=Date.now();this.leaseStarvedSince??=e;const t=e-this.leaseStarvedSince;if(!(t<3e4||this.leaseStarvationReportedAt&&e-this.leaseStarvationReportedAt<3e4)){this.leaseStarvationReportedAt=e;try{this.options.onLeaseStarvation?.({starvedForMs:t,recovered:!1})}catch{}}}observeLeaseRestored(){const e=this.leaseStarvedSince;if(void 0===e)return;this.leaseStarvedSince=void 0;const t=this.leaseStarvationReportedAt;if(this.leaseStarvationReportedAt=0,t)try{this.options.onLeaseStarvation?.({starvedForMs:Date.now()-e,recovered:!0})}catch{}}observeRequestFailure(e,t,a){try{this.options.onRequestFailure?.({operationId:e,method:t,error:a})}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const a of this.workers.values())sameLeaseBinding(a.claimedLease,e)?t.push(a.deliveryId):this.cancelWorker(a);if(!t.length)return;let a;try{a=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&this.cancelWorker(t)}return}if(this.renewTransportFailurePolicy.recordSuccess(),a.notPending.length){const e=new Set(a.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&this.cancelWorker(t)}}cancelWorker(e,t){e.cancelRequested||(e.cancelRequested=!0,e.cancelReason=t),e.cancel?.(e.cancelReason)}setWorkerCancel(e,t){const a=e.cancelRequested&&void 0===e.cancel;e.cancel=t,a&&t(e.cancelReason)}async handleCancel(e,t){const a=validateRuntimeCancelEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_cancel:${a.reason}`,t);const r=a.envelope.payload,o=await this.channel.history({operationId:r.operationId,lease:t});if("found"===o.status&&o.snapshot.terminal&&"final_message"===o.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===o.status||"expired"===o.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const n=o.snapshot.request.payload;if(n.operationId!==r.operationId||n.requestMessageId!==r.requestMessageId||n.requestHash!==r.requestHash||n.dispatchEpoch!==r.dispatchEpoch||n.method!==r.method)return void await this.handlePoison(e,"cancel_history_mismatch",t);await this.journal.observeCancellation({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,eventId:r.eventId});const i=n,s=2===i.schemaVersion&&"session/prompt"===i.method,d=this.workers.get(r.operationId);d&&this.cancelWorker(d,s?nativePromptCancellationReason:void 0),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})}async handleRequest(e,t,a,r){const o=e.message.payload;if(2===o.schemaVersion&&"session/prompt"===o.method&&this.options.nativePromptBridge){let o;try{o=await this.options.nativePromptBridge.execute({delivery:e,lease:t,signal:a,setCancel:r})}catch(a){if(!(a instanceof NativePromptExecutionFailure))throw a;a.failure instanceof RuntimeCommandError&&Object.prototype.hasOwnProperty.call(RUNTIME_ERROR_DESCRIPTORS,a.failure.code)&&a.failure.code;const r=await this.channel.append({operationId:a.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(a.request,a.failure,(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,r.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,r.message)}if(o.replayedFinal)return this.observeRequestTerminalAccepted(e.deliveryId,o.replayedFinal),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,o.replayedFinal);if("succeeded"!==o.outcome){const a=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(o.request,new RuntimeCommandError("cancelled"===o.outcome?"OPERATION_CANCELLED":"EXECUTION_FAILED","native durable reply reports non-success"),(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,a.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,a.message)}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:o.request.method,result:o.result}),i={schemaVersion:1,operationId:o.request.operationId,method:o.request.method,coreResultRef:`sha256:${n}`,coreResultHash:n},s=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,i);await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(o.request),effectRecord:i,effectRecordHash:s,committedAt:(new Date).toISOString()}});const d=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(o.request),outcome:o.outcome,response:{jsonrpc:"2.0",id:o.request.request.id,result:o.result},serviceResultHash:runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:o.request.method,result:o.result}),effectRecordHash:s,completedAt:(new Date).toISOString()}});return this.options.onRequestTerminalAccepted?.({deliveryId:e.deliveryId,message:d.message}),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.options.onRequestAcknowledged?.({deliveryId:e.deliveryId,message:d.message})}const n=validateRuntimeRequestEnvelope(e.message);if(!n.ok)return void await this.handlePoison(e,`invalid_request:${n.reason}`,t);if(n.envelope.payload.schemaVersion!==(this.options.requestSchemaVersion??1))return void await this.handlePoison(e,"request_realm_mismatch",t);const i=n.envelope.payload,s=e.executionGrant,d=createRuntimeAppendTimingRecorder("runtime-op",{operationId:i.operationId,method:i.method}),c=new AbortController;r(()=>c.abort());const l=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),d.mark("ack")},u=await this.channel.history({operationId:i.operationId,lease:t});if(d.mark("history"),"not_found"===u.status||"expired"===u.status)return void await l();if(u.snapshot.terminal&&"final_message"===u.snapshot.terminalSource)return void await l();if(this.options.allowedMethods&&!this.options.allowedMethods.has(i.method))return await this.reject(i,"unsupported_method",t),void await l();if("deadline"===u.snapshot.terminalSource||Date.parse(i.executionDeadlineAt)<=Date.now()||!u.snapshot.started&&Date.parse(i.claimDeadlineAt)<=Date.now())return await this.reject(i,"execution_deadline_exceeded",t),void await l();const p=await this.journal.getCancellation(i.operationId);d.mark("journal-cancel-read");const h=u.snapshot.cancelRequested||null!==p;if(h&&"queued"===u.snapshot.status)return await this.reject(i,"cancelled_before_dispatch",t),void await l();if(i.instanceId!==t.instanceId||i.runtimeHandlerIdentity!==t.handlerIdentity||i.dispatchEpoch!==t.runtimeEpoch)return await this.reject(i,"authority_mismatch",t),void await l();const m=u.snapshot.request.payload;if(u.snapshot.operationId!==i.operationId||u.snapshot.requestMessageId!==i.requestMessageId||u.snapshot.requestHash!==i.requestHash||!semanticEqual(m,i))return void await this.handlePoison(e,"request_history_mismatch",t);const I=u.snapshot.started?.payload,v=void 0!==I&&I.operationId===i.operationId&&I.requestMessageId===i.requestMessageId&&I.requestHash===i.requestHash&&I.executionGrantHash===i.executionGrantHash&&I.handlerIdentity===t.handlerIdentity&&I.dispatchEpoch===t.runtimeEpoch&&I.method===i.method,E=await this.journal.get(i.operationId);d.mark("journal-prior");const f=runtimeCommandIsReplayableQuery(i.command.name),R=f?ephemeralQueryAccept(i):await this.journal.acceptMessageRequest({operationId:i.operationId,command:i.command.name,paramsHash:i.paramsHash,runtimeEpoch:i.dispatchEpoch,requestMessageId:i.requestMessageId,requestHash:i.requestHash});d.mark("journal-accept");const y=v?E:R,w=f?"execute":decideMessageServiceRecovery(u.snapshot,i,y,v);if("already_terminal"===w)return void await l();if(!CORE_RECOVERY_DECISIONS.has(w))return f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${w}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await l();if(await this.verifier.refresh(),d.mark("verifier-refresh"),!s)return v?await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(i,"invalid_execution_grant",t),void await l();this.verifier.verifyAndDecodeGrant(s)||await this.verifier.refresh(!0);const g=()=>c.abort();let _;a.addEventListener("abort",g,{once:!0});try{_=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:i,executionGrant:s,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:v,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:i,executionGrant:s,command:i.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:R,abortSignal:c.signal})})}catch(e){if(a.removeEventListener("abort",g),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if(this.observeRequestFailure(i.operationId,i.method,e),"transient"===e.kind)return;return v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(i,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await l()}if(!_.ok)return a.removeEventListener("abort",g),c.abort(),this.observeRequestFailure(i.operationId,i.method,new Error(`execution grant rejected: ${_.violations.join(",")}`)),v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(i,"invalid_execution_grant",t),void await l();if(!h||"prepared"!==R.phase&&"started"!==R.phase||c.abort(),c.signal.aborted&&!v)return a.removeEventListener("abort",g),await this.reject(i,"cancelled_before_dispatch",t),void await l();d.mark("attempt"),v?this.currentLease(t):(await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),executionGrant:s,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(i),executionMode:"start",executionGrantHash:i.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:R.messageBinding?.acceptedAt??R.updatedAt}}),d.mark("append-started"));const M=this.dispatcher.dispatch(i.command,_.context);M.completion.catch(()=>{}),r(()=>{c.abort(),M.cancel()}),c.signal.aborted&&M.cancel();const S=this.forwardProgress(i,M.progress,t).catch(()=>{});let N,O=!1;try{if(("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)){const e=await M.effectCommitted;if(e){if(e.operationId!==i.operationId||e.method!==i.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:e.result}),r={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${a}`,coreResultHash:a};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,r),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:r,effectRecordHash:N,committedAt:e.committedAt}}),await M.acknowledgeEffectReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N})}}const a=await M.completion;if(await S,d.mark("core"),f){const r=(new Date).toISOString();let o;try{o=sanitizeRuntimeServiceResult(i.method,a,_.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:o}),s=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:o},serviceResultHash:n,completedAt:r}});return d.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,s.message),await l(),void this.observeRequestAcknowledged(e.deliveryId,s.message)}const r=await this.journal.get(i.operationId);if(d.mark("journal-after-core"),!r||!isCommittedCorePhase(r.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const o=r.updatedAt;let n,s;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[i.method]){const e=isAgentProjectionMethod(i.method),s=M.getSnapshot().projection,c=r.agentProjectionIntent??r.agentProjectionPreparationFailure;if(e&&!c)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!N&&"session/clear"!==i.method){const e=c?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:a}),n=r.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(i.method)?s?.revision??`${Math.max(0,r.revision)}`:void 0),l={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...n?{projectionRevision:n}:{}};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,l),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:l,effectRecordHash:N,committedAt:o}}),d.mark("append-effect")}let u=e?await awaitRuntimeProjection(M):s;if("session/set_model"===i.method&&"synced"!==u?.state&&(u=await this.projectSessionModelAfterEffect(i,_.context,r,u),d.mark("set-model-projection")),e&&r.agentProjectionIntent&&(!u||u.revision!==r.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===u?.state)return void await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(i),revision:u.revision}});if("synced"===u?.state&&await this.publishProjectionSynced(i,t,{...u,state:"synced"}),"blocked"===u?.state){await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(i),revision:u.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:i.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:i.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:N,completedAt:o}}),void await l()}n=e?u?.platformAgentId:void 0}try{s=sanitizeRuntimeServiceResult(i.method,a,_.context,n)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const c=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:s});O=!0;const u=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:s},serviceResultHash:c,...N?{effectRecordHash:N}:{},completedAt:o}});if(d.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,u.message),("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)&&"function"==typeof M.acknowledgeTerminalReceipt){if(!N)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await M.acknowledgeTerminalReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N,terminalMessageId:u.message.message_id})}await l(),this.observeRequestAcknowledged(e.deliveryId,u.message)}catch(e){const a=await this.journal.get(i.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const r=!a||!isCommittedCorePhase(a.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(i.operationId,i.method,r);const o=failurePayload(i,r,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:o}),d.mark("append-terminal-failure"),await l()}finally{d.finish(),c.abort(),a.removeEventListener("abort",g)}}async handlePoison(e,t,a){this.currentLease(a);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(a)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,a){for await(const r of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:r.phase,progress:r}})}async reject(e,t,a){await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,a,r){const o=Object.freeze({state:"pending",revision:r?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return o;const i=t.sessionModelProjection;if(!i)return o;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:o.revision});try{const t=await this.journal.get(a.operationId)??a;if("projection_committed"===t.phase&&"synced"===t.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:t.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:t.operationId,expectedRevision:t.revision,phase:"projection_committed",projectionSnapshot:e})}catch{}return e}catch(e){return this.observeDeliveryError(e),o}}async publishProjectionSynced(e,t,a){const r=this.currentLease(t),o=await this.channel.history({operationId:e.operationId,lease:r});if("found"===o.status&&"synced"===o.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==o.status||"reserved"===o.snapshot.projectionState||"pending"!==o.snapshot.projectionState&&void 0===o.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:r,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:r,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...n,...a.platformAgentId?{platformAgentId:a.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,a,r){const o=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),n=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":r?"running":"queued",i="failed"===a?.phase||"outcome_unknown"===a?.phase?"terminal":a?.phase,s=a&&a.runtimeEpoch===t.dispatchEpoch&&(void 0===a.messageBinding||a.messageBinding.requestMessageId===t.requestMessageId&&a.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:o?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(o?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:r,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,r){if("session/clear"===e)return serviceClearResult(t,a?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,a);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const o="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,o,{...r?{platformAgentId:r}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const a=t;if(!a.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:a.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const a=t.verifiedMessageGrant?.claims.command;if(!a||"session.setModel"!==a.name||"conversation"!==a.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const r=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===r?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:r,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,a){const r=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",o=r in RUNTIME_ERROR_DESCRIPTORS?r:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===o||"INSTANCE_EPOCH_MISMATCH"===o?"outcome_unknown":"COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":o,s=RUNTIME_ERROR_DESCRIPTORS[i],d="outcome_unknown"===n?"outcome_unknown":n;return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:d,retryMode:s.retryMode}}},completedAt:a}}function prestartFailurePayload(e,t){const a="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",r=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],o="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:o,response:{jsonrpc:"2.0",id:e.request.id,error:{code:r.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:o,retryMode:r.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,r)=>{const o=()=>a();t.addEventListener("abort",o,{once:!0}),e.then(()=>{t.removeEventListener("abort",o),a()},e=>{t.removeEventListener("abort",o),r(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const r=()=>{clearTimeout(o),a()},o=setTimeout(()=>{t?.removeEventListener("abort",r),a()},e);t?.addEventListener("abort",r,{once:!0})})}
|