@makaio/framework 1.0.0-dev-1790585290134 → 1.0.0-dev-1790598955306
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/dist/.makaio-build.json +2 -2
- package/dist/adapters/claude/index.mjs +1 -1
- package/dist/artifact-XE82Q2bH.mjs +1 -0
- package/dist/bus/index.mjs +1 -1
- package/dist/bus--m38BS3i.mjs +9 -0
- package/dist/contracts/adapter/index.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +3 -3
- package/dist/contracts/artifact/index.mjs +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/extension/index.mjs +1 -1
- package/dist/contracts/index.d.mts +51 -51
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +2 -2
- package/dist/contracts/materialization/index.mjs +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/{extension-CeZwB88e.mjs → extension-DeTvdQIB.mjs} +1 -1
- package/dist/{index-DvdBCT0Z.d.mts → index-CGM0-mt2.d.mts} +37 -37
- package/dist/{index-DxtUM-qd.d.mts → index-CLwnkYRD.d.mts} +1 -1
- package/dist/{index-DdA7SmMH2.d.mts → index-CPOJqxrf2.d.mts} +8 -8
- package/dist/{index-BM53WQaQ.d.mts → index-CVRQS5jk.d.mts} +1 -1
- package/dist/{index-DFa6C6wt.d.mts → index-CXroIgOA.d.mts} +3 -3
- package/dist/{index-CJDZBc-p.d.mts → index-CZIFCrMc.d.mts} +14 -14
- package/dist/{index-CoD7P-IS.d.mts → index-CpaWzUE5.d.mts} +1 -1
- package/dist/{index-DyequYaC.d.mts → index-CtwkMknv.d.mts} +1 -1
- package/dist/{index-CfELOEbZ.d.mts → index-DrfwkH1x.d.mts} +5 -5
- package/dist/{index-H_oth7rJ.d.mts → index-bXozN5vc.d.mts} +61 -2
- package/dist/{index-v9Tsvlnu.d.mts → index-e3AB0Iyv.d.mts} +43 -43
- package/dist/kind-registration-CdjmVxY_.mjs +1 -0
- package/dist/{materialization-6Whrkf5D.mjs → materialization-BzSgnv2R.mjs} +1 -1
- package/dist/{namespace-ybTsfz1t.d.mts → namespace-B9iQN3FQ.d.mts} +2 -2
- package/dist/{namespace-h7gq_v5U.d.mts → namespace-CHSwZhH7.d.mts} +2 -2
- package/dist/{namespace-D6W4Erwp.d.mts → namespace-DAzOxaux.d.mts} +2 -2
- package/dist/package.json +1 -1
- package/dist/{schemas-B2fs9-uF.d.mts → schemas-BNQtL3Ln.d.mts} +22 -2
- package/dist/{schemas-BTJvvq9Y.d.mts → schemas-BXkSHQaF.d.mts} +2 -2
- package/dist/{schemas-D6ZdMKo3.mjs → schemas-BvDsO8Is.mjs} +1 -1
- package/dist/{schemas-Cb9OJ9va.d.mts → schemas-CBDNnyz4.d.mts} +1 -1
- package/dist/{schemas-CYjPZwlQ.d.mts → schemas-DnyXA-9o.d.mts} +2 -2
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- package/dist/services/execution-target/index.d.mts +2 -2
- package/dist/services/execution-target/namespace.d.mts +1 -1
- package/dist/services/execution-target/schemas.d.mts +1 -1
- package/dist/services/index.d.mts +13 -13
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/index.d.mts +3 -3
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +2 -2
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/subagent-template/index.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/{transition-ClMo_PUJ.d.mts → transition-DK43U3QJ.d.mts} +1 -1
- package/dist/{view-builder-B8WSU6WT.d.mts → view-builder-Nffvg8MI.d.mts} +1 -1
- package/dist/{worker-CIhuGZx1.mjs → worker-toBnRJ0A.mjs} +1 -1
- package/dist/{workflow-Co4YAyPP.mjs → workflow-BDDB6EJi.mjs} +1 -1
- package/dist/workflow-engine/index.d.mts +31 -31
- package/package.json +1 -1
- package/dist/artifact-z-GlRNax.mjs +0 -1
- package/dist/bus-_RyFr-xv.mjs +0 -9
- package/dist/kind-registration-XiS6z3mC.mjs +0 -1
package/dist/.makaio-build.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"fingerprint": "
|
|
4
|
-
"builtAt": "2026-09-
|
|
3
|
+
"fingerprint": "55149456e2a8d00a163496f8ca30cbae062c75f70560254f47f96282ce7b585d",
|
|
4
|
+
"builtAt": "2026-09-28T12:37:04.206Z",
|
|
5
5
|
"declarations": true,
|
|
6
6
|
"declarationBackend": "tsc"
|
|
7
7
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{z as e}from"zod";import{DeferredPromise as t}from"@makaio/framework/utils";import{AuthenticationError as n,InvalidModelError as r,ModelUnavailableError as i,QuotaExceededError as a,RateLimitError as o}from"@makaio/framework/core";import{AgentSubjects as s,JsonValueSchema as c,createClientDefinition as ee}from"@makaio/framework/contracts";import{CANONICAL_HOOK_RESPONSE_CAPABILITIES as te}from"@makaio/framework/contracts/client";import{AIAgent as ne,BaseConnectorTurn as re,ScopedToolApprovalSchema as ie,createAdapterNamespace as ae,createToolApprovalHandler as oe,defineDiscriminatedHandlers as se,formatContextBlockAsText as ce,isTextLikeMimeType as le,mergeScopedToolApproval as l,normalizeMimeType as u,processDiscriminatedItems as ue,serializeBlockToText as d}from"@makaio/framework/adapters";import{AbsolutePathSchema as f}from"@makaio/framework/clients";function p(e,t){return l(e,t,`claude-shared`)}function de(e){return e.action===`allow`?{behavior:`allow`,updatedInput:e.updatedInput,updatedPermissions:e.updatedPermissions}:{behavior:`deny`,message:e.message,interrupt:e.shouldAbort??!1}}function m(e,t,n,r){return oe(t.can_use_tool,p,e=>e)(e,n,r)}async function fe(e,t,n,r={}){let i=l(t,n??{},`claude-shared`,{allowPayloadSessionFallback:r.allowPayloadSessionFallback??!1,allowPayloadIdentityFallback:r.allowPayloadIdentityFallback??!1});return e.request(s.toolApprove,i)}const h=se(`type`,{text:(e,t)=>t(s.message,{content:e.text}),thinking:(e,t)=>t(s.reasoning,{content:e.thinking}),tool_use:(e,t)=>t(s.tool.use,{toolName:e.name,args:e.input,toolCallId:e.id}),server_tool_use:(e,t)=>t(s.tool.started,{toolName:e.name,toolCallId:e.id}),web_search_tool_result:(e,t)=>{let n=!Array.isArray(e.content);return t(s.tool.completed,{toolName:`web_search`,result:e.content,success:!n,toolCallId:e.tool_use_id})},code_execution_tool_result:(e,t)=>{let n=e.content,r=n.type===`code_execution_result`&&n.return_code===0;return t(s.tool.completed,{toolName:`code_execution`,result:n,success:r,toolCallId:e.tool_use_id})},redacted_thinking:(e,t)=>{},mcp_tool_use:(e,t)=>{},mcp_tool_result:(e,t)=>{},container_upload:(e,t)=>{}});function pe(e,t){return{provider:`anthropic`,granularity:`query-aggregate`,inputTokens:e.input_tokens,inputCachedTokens:e.cache_read_input_tokens??0,cacheWriteTokens:e.cache_creation_input_tokens,outputTokens:e.output_tokens,reasoningTokens:0,totalTokens:e.input_tokens+(e.cache_read_input_tokens??0)+e.output_tokens,costUnits:1,costUnitType:`requests`,...t===void 0?{}:{cost:t,costProvenance:`provider-reported`},serviceTier:e.service_tier}}function me(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)+e.output_tokens}async function he(e){let{messageId:t}=e;if(t===void 0)return;let n=e.payload.message?.content,r=Array.isArray(n)?n:n?[n]:[];for(let n of r){if(!ge(n))continue;let r=n.tool_use_id,i=_e(e.payload.tool_use_result),a=await e.resolveToolOutput(t,i,r);await e.emitToolCompleted({messageId:t,toolName:a.toolName,args:a.args,result:{content:n.content??{}},success:!n.is_error,toolCallId:a.toolCallId}),await e.emitToolStepFinished({blockIndex:e.consumeToolBlockIndex(r),toolCallId:a.toolCallId,output:i,isError:n.is_error??!1})}}function ge(e){return typeof e==`object`&&!!e&&e.type===`tool_result`}function _e(e){return typeof e==`string`?e:[e?.stdout,e?.stderr].filter(Boolean).join(`
|
|
2
|
-
`)}function ve(e){return e.type!==`tool_use`||!e.id||!e.name?null:{toolCallId:e.id,toolName:e.name}}var ye=class extends ne{supportsNativeResume(){return!0}supportsNativeFork(){return!0}currentStepType=`text`;currentTextContent=``;currentReasoningContent=``;currentToolCall=null;toolBlockIndexMap=new Map;currentToolArgsJson=``;wireEvents(e){let t=e;this.wireConnectorEvents(t),this.wireToolApprovalRpc(e)}subscribeClaudeConnector(e,t,n,r){this.addConnectorWiringCleanup(e.on(t,n,r))}wireConnectorEvents(e){let t=this.getSubjects();this.subscribeClaudeConnector(e,t.sdk.event,async e=>{let t=e.payload,n=t.originatingMessageId;switch(t.type){case`system`:t.subtype===`init`&&await this.emitStart();break;case`assistant`:{let e=t.message?.content;if(!e)break;await ue(e,h,async(e,t)=>{if(e.subject===`tool.use`){if(n===void 0)return;let e=t;await this.emitToolUse(n,e.toolName,e.args,e.toolCallId)}else if(e.subject===`tool.started`||e.subject===`tool.completed`){if(n===void 0)return;await this.emitGlobal(e,{...t,messageId:n})}else await this.emitGlobal(e,t)});break}case`stream_event`:{let e=t.event;e.type===`content_block_start`?await this.handleContentBlockStart(e,n):e.type===`content_block_stop`?await this.handleContentBlockStop(e):e.type===`content_block_delta`&&await this.handleContentBlockDelta(e);break}case`result`:await this.handleResultEvent(t);break;case`user`:await this.handleUserEvent(t,n);break}})}async handleContentBlockStart(e,t){let n=e.content_block,r=ve(n),i=n.type===`thinking`?`reasoning`:n.type===`tool_use`?`tool_use`:`text`;this.currentStepType=i,this.currentTextContent=``,this.currentReasoningContent=``,this.currentToolArgsJson=``,this.currentToolCall=null;let a=r?{type:`tool_use`,toolName:r.toolName,toolCallId:r.toolCallId}:n.type===`tool_use`?void 0:{type:i},o;if(r&&(this.currentToolCall={toolCallId:r.toolCallId,name:r.toolName,args:{}},this.toolBlockIndexMap.set(r.toolCallId,e.index),o={type:`tool_call`,toolCallId:r.toolCallId,name:r.toolName,args:{}}),n.type===`tool_use`&&!r&&console.warn(`[ClaudeCodeAdapter] Received tool_use block without id or name; skipping tool correlation setup`),r&&t===void 0){console.warn(`[ClaudeCodeAdapter] Received tool_use block without originating message identity; skipping tool events`);return}await this.emitGlobal(s.step.started,{...t!==void 0&&{messageId:t},stepType:i,blockIndex:e.index,blockData:a,content:o}),r&&await this.emitGlobal(s.tool.started,{...t!==void 0&&{messageId:t},toolName:r.toolName,toolCallId:r.toolCallId})}async handleContentBlockStop(e){if(this.currentStepType!==`tool_use`){let t=this.currentStepType===`text`?{type:`text`,content:this.currentTextContent}:{type:`reasoning`,content:this.currentReasoningContent};await this.emitGlobal(s.step.finished,{stepType:this.currentStepType,blockIndex:e.index,content:t})}else if(this.currentToolCall&&this.currentToolArgsJson)try{this.currentToolCall.args=JSON.parse(this.currentToolArgsJson)}catch{}}async handleContentBlockDelta(e){let t=e.delta;switch(t.type){case`text_delta`:this.currentTextContent+=t.text,await this.emitGlobal(s.message_delta,{text:t.text});break;case`thinking_delta`:this.currentReasoningContent+=t.thinking,await this.emitGlobal(s.reasoning_delta,{content:t.thinking});break;case`input_json_delta`:`partial_json`in t&&(this.currentToolArgsJson+=t.partial_json);break}}async handleResultEvent(e){if(e.usage){let t=e.usage;await this.trackUsage(pe(t,e.total_cost_usd)),await this.emitContextWindowUpdate({currentTokens:me(t),maxTokens:this.getContextWindowSize()??2e5,cachedTokens:t.cache_read_input_tokens})}}async handleUserEvent(e,t){await he({messageId:t,payload:e,resolveToolOutput:async(e,t,n)=>await this.emitToolOutput(e,t,{nativeId:n}),emitToolCompleted:async e=>await this.emitGlobal(s.tool.completed,e),emitToolStepFinished:async e=>await this.emitGlobal(s.step.finished,{stepType:`tool_use`,blockIndex:e.blockIndex,content:{type:`tool_output`,toolCallId:e.toolCallId,output:e.output,isError:e.isError}}),consumeToolBlockIndex:e=>this.consumeToolBlockIndex(e)})}consumeToolBlockIndex(e){if(e===void 0)return-1;let t=this.toolBlockIndexMap.get(e);return this.toolBlockIndexMap.delete(e),t===void 0&&console.warn(`[ClaudeCodeAdapter] toolCallId ${e} not found in toolBlockIndexMap - possible state mismatch`),t??-1}wireToolApprovalRpc(e){this.addConnectorWiringCleanup(m(e,this.getSubjects(),async()=>({adapterId:this.adapterId,adapterName:this.adapterName,agentId:this.agentId,adapterSessionId:await this.getAdapterSessionId(),sessionId:this.sessionId}),this.globalBus))}},be=class{queue=[];resolvers=[];done=!1;async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else yield await new Promise(e=>{this.resolvers.push(t=>{t.done||e(t.value)})})}push(e){if(this.done)throw Error(`Cannot push to completed source`);this.resolvers.length>0?this.resolvers.shift()({value:e,done:!1}):this.queue.push(e)}complete(){this.done=!0;for(let e of this.resolvers)e({value:void 0,done:!0});this.resolvers=[]}clear(){this.queue=[]}},xe=class extends re{queryInstance;activeMessageHandle;pausedDeferred;isPausedFlag=!1;connectorBus;subjects;agentId;expectingInterruptResult=!1;constructor(e,t,n,r,i,a,o){super(e,n,r,`idle`),this.connectorBus=e,this.subjects=t,this.agentId=i,this.queryInstance=a,this.activeMessageHandle=o}setActiveMessageHandle(e){this.activeMessageHandle=e}async emitStateChange(e,t){let n={adapterId:this.adapterId,agentId:this.agentId,oldState:e,newState:t,timestamp:Date.now()};switch(await this.connectorBus.emit(this.subjects.turn.state_changed,n),t){case`turn_started`:await this.connectorBus.emit(this.subjects.turn.turn_started,n);break;case`step_started`:await this.connectorBus.emit(this.subjects.turn.step_started,n);break;case`step_finished`:await this.connectorBus.emit(this.subjects.turn.step_finished,n);break;case`turn_finished`:await this.connectorBus.emit(this.subjects.turn.turn_finished,n);break;case`paused`:await this.connectorBus.emit(this.subjects.turn.paused,n);break}}async start(){await this.transitionTo(`turn_started`)}async pause(){if(this.state===`turn_finished`)return{stateBeforePause:this.state,turnEnded:!0};if(this.isPausedFlag)return{stateBeforePause:this.state,turnEnded:!1};if(this.state!==`step_finished`&&(await this.waitForStepFinished(),this.getState()===`turn_finished`)||(await this.queryInstance.interrupt(),this.getState()===`turn_finished`))return{stateBeforePause:this.state,turnEnded:!0};this.expectingInterruptResult=!0,this.isPausedFlag=!0;let e=this.state;return await this.transitionTo(`paused`),{stateBeforePause:e,turnEnded:!1}}async resume(e){if(!this.isPausedFlag)throw Error(`Cannot resume - turn not paused`);this.isPausedFlag=!1,await this.transitionTo(`step_started`)}isPaused(){return this.isPausedFlag}async handleSdkEvent(e){if(e.type===`stream_event`)e.event.type===`content_block_start`?await this.transitionTo(`step_started`):e.event.type===`content_block_stop`&&(await this.transitionTo(`step_finished`),this.pausedDeferred?.resolve());else if(e.type===`result`){if(this.expectingInterruptResult){this.expectingInterruptResult=!1;return}await this.transitionTo(`turn_finished`)}}isExpectingInterruptResult(){return this.expectingInterruptResult}async finishOnError(){this.pausedDeferred?.resolve(),this.pausedDeferred=void 0,this.isPausedFlag=!1,this.expectingInterruptResult=!1,this.state!==`turn_finished`&&await this.transitionTo(`turn_finished`)}async waitForStepFinished(){if(this.state!==`step_finished`){this.pausedDeferred=new t;try{await this.pausedDeferred.getPromise()}finally{this.pausedDeferred=void 0}}}isCompleted(){return this.state===`turn_finished`}canAcceptImmediate(){return this.state!==`turn_finished`&&!this.isPausedFlag}};const g=Object.freeze({approve:`claude-code.tool-response.approve`,deny:`claude-code.tool-response.deny`});ee({id:`claude-code`,name:`Claude Code`,version:`0.1.0`,description:`Anthropic Claude Code CLI — an agentic coding assistant`,binary:{name:`claude`,supportedVersions:`^2.1.0`},managedInstall:{type:`signed-binary-bucket`,version:`2.1.219`,config:{baseUrl:`https://downloads.claude.ai/claude-code-releases`,manifestPathTemplate:`{version}/manifest.json`,manifestSignaturePathTemplate:`{version}/manifest.json.sig`,publicKeyUrl:`https://downloads.claude.ai/keys/claude-code.asc`,publicKeyFingerprint:`31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`,binaryPathTemplate:`{version}/{platform}/{binary}`,platforms:{"darwin-arm64":`darwin-arm64`,"darwin-x64":`darwin-x64`,"linux-arm64":`linux-arm64`,"linux-x64":`linux-x64`,"linux-arm64-musl":`linux-arm64-musl`,"linux-x64-musl":`linux-x64-musl`,"win32-arm64":`win32-arm64`,"win32-x64":`win32-x64`}}},versionCommand:{executable:{default:`claude`,win32:`claude.exe`},args:[`--version`]},configIsolation:{envVar:`CLAUDE_CONFIG_DIR`,defaultPath:`~/.claude`},nativeTools:[{name:`bash`,friendlyName:`Terminal`,description:`Execute shell commands`,category:`System`,capabilities:[{tag:`shell.execute`},{tag:`file.read`},{tag:`file.write`},{tag:`file.delete`},{tag:`network.request`},{tag:`process.manage`}]},{name:`text_editor`,friendlyName:`Text Editor`,description:`View and edit files`,category:`Files`,capabilities:[{tag:`file.read`},{tag:`file.write`}]},{name:`list_directory`,friendlyName:`List Directory`,description:`List directory contents`,category:`Files`,capabilities:[{tag:`file.read`},{tag:`search.files`}]},{name:`read_file`,friendlyName:`Read File`,description:`Read file contents`,category:`Files`,capabilities:[{tag:`file.read`}]},{name:`write_file`,friendlyName:`Write File`,description:`Write content to a file`,category:`Files`,capabilities:[{tag:`file.write`}]}],defaultApprovalPolicy:`full-access`,authMethods:[{id:`native`,mode:`inferred`,label:`Native account`},{id:`oauth-token`,mode:`explicit`,label:`OAuth token`,fields:[{id:`oauthToken`,label:`OAuth token`,required:!0,secret:!0,sourceHints:[{kind:`environment`,variable:`CLAUDE_CODE_OAUTH_TOKEN`}]}]}],defaultAuth:{providerDefinitionId:`anthropic-oauth`,methodId:`native`},runtimeCapabilities:{supportsHooks:!0,supportsStatusline:!0,supportsSupervisorLaunch:!1,supportsManagedBinary:!0,hookEvents:[{name:`SessionStart`,frameworkSubject:`client.session.started`,responseCapabilities:[`context.append`,te.sessionToken]},{name:`UserPromptSubmit`,frameworkSubject:`client.session.userPrompt.submitted`,responseCapabilities:[`context.append`]},{name:`PreToolUse`,frameworkSubject:`client.session.tool.pre`,responseCapabilities:[g.approve,g.deny,`context.append`]},{name:`PostToolUse`,frameworkSubject:`client.session.tool.post`},{name:`Stop`,frameworkSubject:`client.session.turn.completed`},{name:`SubagentStart`,frameworkSubject:`client.session.subagent.started`,responseCapabilities:[`context.append`]},{name:`SubagentStop`,frameworkSubject:`client.session.subagent.completed`},{name:`PreCompact`,frameworkSubject:`client.session.compaction.pre`},{name:`PostCompact`,minimumVersion:`2.1.76`},{name:`Notification`},{name:`MCPServerStart`},{name:`MCPServerStop`}]}});const _=e.object({uuid:e.string(),session_id:e.string(),type:e.string(),correlation_id:e.string().optional(),agentId:e.string().optional(),timestamp:e.string().optional(),cwd:e.string().optional()}),v=_.extend({parent_tool_use_id:e.string().nullable().optional()});_.required({agentId:!0}).extend({parent_tool_use_id:e.string().nullable().optional()});const y=e.enum([`invalid_tool_input`,`unavailable`,`too_many_requests`,`execution_time_exceeded`]),b=e.object({web_search_requests:e.number()}),Se=e.object({ephemeral_1h_input_tokens:e.number(),ephemeral_5m_input_tokens:e.number()}),x=e.object({cache_creation:Se.nullable().optional(),cache_creation_input_tokens:e.number().nullable().optional(),cache_read_input_tokens:e.number().nullable().optional(),input_tokens:e.number(),output_tokens:e.number(),server_tool_use:b.nullable().optional(),service_tier:e.enum([`standard`,`priority`,`batch`]).nullable().optional()});e.object({cache_creation_input_tokens:e.number().nullable().optional(),cache_read_input_tokens:e.number().nullable().optional(),input_tokens:e.number().nullable().optional(),output_tokens:e.number(),server_tool_use:b.nullable().optional()});const S=e.object({type:e.literal(`ephemeral`),ttl:e.enum([`5m`,`1h`]).optional()}),Ce=e.object({data:e.string(),media_type:e.enum([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),type:e.literal(`base64`)}),we=e.object({type:e.literal(`url`),url:e.string()}),Te=e.object({file_id:e.string(),type:e.literal(`file`)}),Ee=e.discriminatedUnion(`type`,[Ce,we,Te]),De=e.object({data:e.string(),media_type:e.literal(`application/pdf`),type:e.literal(`base64`)}),Oe=e.object({type:e.literal(`url`),url:e.string()}),ke=e.object({file_id:e.string(),type:e.literal(`file`)}),Ae=e.object({data:e.string(),media_type:e.literal(`text/plain`),type:e.literal(`text`)}),je=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_char_index:e.number(),file_id:e.string().nullable().optional(),start_char_index:e.number(),type:e.literal(`char_location`)}),Me=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_char_index:e.number(),start_char_index:e.number(),type:e.literal(`char_location`)}),Ne=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_page_number:e.number(),file_id:e.string().nullable().optional(),start_page_number:e.number(),type:e.literal(`page_location`)}),Pe=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_page_number:e.number(),start_page_number:e.number(),type:e.literal(`page_location`)}),Fe=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_block_index:e.number(),file_id:e.string().nullable().optional(),start_block_index:e.number(),type:e.literal(`content_block_location`)}),Ie=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_block_index:e.number(),start_block_index:e.number(),type:e.literal(`content_block_location`)}),Le=e.object({cited_text:e.string(),encrypted_index:e.string(),title:e.string().nullable().optional(),type:e.literal(`web_search_result_location`),url:e.string()}),Re=e.object({cited_text:e.string(),encrypted_index:e.string(),title:e.string().nullable().optional(),type:e.literal(`web_search_result_location`),url:e.string()}),ze=e.object({cited_text:e.string(),end_block_index:e.number(),search_result_index:e.number(),source:e.string(),start_block_index:e.number(),title:e.string().nullable().optional(),type:e.literal(`search_result_location`)}),Be=e.object({cited_text:e.string(),end_block_index:e.number(),search_result_index:e.number(),source:e.string(),start_block_index:e.number(),title:e.string().nullable().optional(),type:e.literal(`search_result_location`)}),C=e.discriminatedUnion(`type`,[je,Ne,Fe,Le,ze]),Ve=e.discriminatedUnion(`type`,[Me,Pe,Ie,Re,Be]);e.object({citation:C,type:e.literal(`citations_delta`)});const w=e.object({enabled:e.boolean().optional()}),He=e.object({id:e.string(),expires_at:e.string()}),Ue=e.enum([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`pause_turn`,`refusal`]),T=e.object({text:e.string(),type:e.literal(`text`),cache_control:S.nullable().optional(),citations:e.array(Ve).nullable().optional()}),E=e.object({source:Ee,type:e.literal(`image`),cache_control:S.nullable().optional()}),We=e.object({content:e.union([e.string(),e.array(e.union([T,E]))]),type:e.literal(`content`)}),Ge=e.object({source:e.union([De,Ae,We,Oe,ke]),type:e.literal(`document`),cache_control:S.nullable().optional(),citations:w.optional(),context:e.string().nullable().optional(),title:e.string().nullable().optional()}),D=e.object({content:e.array(T),source:e.string(),title:e.string(),type:e.literal(`search_result`),cache_control:S.nullable().optional(),citations:w.optional()}),O=e.object({citations:e.array(C).nullable().optional(),text:e.string(),type:e.literal(`text`)}),k=e.object({signature:e.string(),thinking:e.string(),type:e.literal(`thinking`)}),Ke=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),qe=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),type:e.literal(`tool_use`)}),Je=e.object({id:e.string(),input:e.looseObject({}),name:e.enum([`web_search`,`code_execution`]),type:e.literal(`server_tool_use`)}),Ye=e.object({encrypted_content:e.string(),page_age:e.string().nullable().optional(),title:e.string(),type:e.literal(`web_search_result`),url:e.string()}),Xe=e.enum([`invalid_tool_input`,`unavailable`,`max_uses_exceeded`,`too_many_requests`,`query_too_long`]),Ze=e.object({error_code:Xe,type:e.literal(`web_search_tool_result_error`)}),Qe=e.union([Ze,e.array(Ye)]),$e=e.object({content:Qe,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`)}),et=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),tt=e.object({content:e.array(et),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),nt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),rt=e.union([nt,tt]),it=e.object({content:rt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`)}),at=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),server_name:e.string(),type:e.literal(`mcp_tool_use`)}),ot=e.object({content:e.union([e.string(),e.array(O)]),is_error:e.boolean(),tool_use_id:e.string(),type:e.literal(`mcp_tool_result`)}),st=e.object({file_id:e.string(),type:e.literal(`container_upload`)}),A=e.discriminatedUnion(`type`,[O,k,Ke,qe,Je,$e,it,at,ot,st]),ct=k.extend({}),lt=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),ut=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.string(),type:e.literal(`tool_use`),cache_control:S.nullable().optional()}),dt=e.object({tool_use_id:e.string(),type:e.literal(`tool_result`),cache_control:S.nullable().optional(),content:e.union([e.string(),e.array(e.union([T,E,D]))]).optional(),is_error:e.boolean().optional()}),ft=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.enum([`web_search`,`code_execution`]),type:e.literal(`server_tool_use`),cache_control:S.nullable().optional()}),pt=e.object({encrypted_content:e.string(),title:e.string(),type:e.literal(`web_search_result`),url:e.string(),page_age:e.string().nullable().optional()}),mt=e.object({error_code:e.enum([`invalid_tool_input`,`unavailable`,`max_uses_exceeded`,`too_many_requests`,`query_too_long`]),type:e.literal(`web_search_tool_result_error`)}),ht=e.union([e.array(pt),mt]),gt=e.object({content:ht,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`),cache_control:S.nullable().optional()}),_t=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),vt=e.object({content:e.array(_t),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),yt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),bt=e.union([yt,vt]),xt=e.object({content:bt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`),cache_control:S.nullable().optional()}),St=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.string(),server_name:e.string(),type:e.literal(`mcp_tool_use`),cache_control:S.nullable().optional()}),Ct=e.object({tool_use_id:e.string(),type:e.literal(`mcp_tool_result`),cache_control:S.nullable().optional(),content:e.union([e.string(),e.array(T)]).optional(),is_error:e.boolean().optional()}),wt=e.object({file_id:e.string(),type:e.literal(`container_upload`),cache_control:S.nullable().optional()}),Tt=e.discriminatedUnion(`type`,[T,E,Ge,D,ct,lt,ut,dt,ft,gt,xt,St,Ct,wt]),Et=e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`),model:e.string(),content:e.array(A),stop_reason:Ue.nullable().optional(),stop_sequence:e.string().nullable().optional(),usage:x,container:He.nullable().optional()}),j=v.extend({type:e.literal(`assistant`),message:Et}),Dt=e.object({role:e.enum([`user`,`assistant`]),content:e.union([e.string(),e.array(Tt)])}),Ot=x.extend({cache_creation:x.shape.cache_creation.unwrap(),cache_creation_input_tokens:e.number(),cache_read_input_tokens:e.number(),server_tool_use:x.shape.server_tool_use.unwrap(),service_tier:e.enum([`standard`,`priority`,`batch`])}),kt=e.object({inputTokens:e.number(),outputTokens:e.number(),cacheReadInputTokens:e.number(),cacheCreationInputTokens:e.number(),webSearchRequests:e.number(),costUSD:e.number(),contextWindow:e.number()}),At=e.object({tool_name:e.string(),tool_use_id:e.string(),tool_input:e.unknown()}),M=_.extend({type:e.literal(`result`),duration_ms:e.number(),duration_api_ms:e.number(),is_error:e.boolean(),num_turns:e.number(),total_cost_usd:e.number(),usage:Ot,modelUsage:e.record(e.string(),kt),permission_denials:e.array(At)}),jt=M.extend({subtype:e.literal(`success`),result:e.string(),structured_output:c.optional()}),Mt=M.extend({subtype:e.enum([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),errors:e.array(e.string()),stop_reason:e.string().nullable()}),N=e.discriminatedUnion(`subtype`,[jt,Mt]),Nt=e.object({type:e.literal(`message_start`),message:e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`)})}),Pt=e.object({type:e.literal(`message_delta`),delta:e.object({stop_reason:e.string().nullable().optional(),stop_sequence:e.string().nullable().optional(),container:e.object({id:e.string(),expires_at:e.string()}).nullable().optional()}),usage:x}),Ft=e.object({type:e.literal(`message_stop`)}),It=e.object({type:e.literal(`content_block_start`),index:e.number(),content_block:A}),Lt=e.object({type:e.literal(`content_block_delta`),index:e.number(),delta:e.discriminatedUnion(`type`,[e.object({type:e.literal(`text_delta`),text:e.string()}),e.object({type:e.literal(`thinking_delta`),thinking:e.string()}),e.object({type:e.literal(`input_json_delta`),partial_json:e.string()}),e.object({type:e.literal(`citations_delta`),citation:C}),e.object({type:e.literal(`signature_delta`),signature:e.string()})])}),Rt=e.object({type:e.literal(`content_block_stop`),index:e.number()}),zt=e.discriminatedUnion(`type`,[Nt,Pt,Ft,It,Lt,Rt]),P=v.extend({type:e.literal(`stream_event`),event:zt}),Bt=[`init`,`compact_boundary`],Vt=e.enum([`user`,`project`,`org`,`temporary`,`none`]),Ht=e.enum([`default`,`acceptEdits`,`bypassPermissions`,`plan`]),Ut=e.object({name:e.string(),status:e.string()}),Wt=e.object({trigger:e.enum([`manual`,`auto`]),pre_tokens:e.number()}),Gt=_.extend({type:e.literal(`system`),subtype:e.literal(`init`),agents:e.array(e.string()).optional(),apiKeySource:Vt,cwd:e.string(),tools:e.array(e.string()),mcp_servers:e.array(Ut),model:e.string(),permissionMode:Ht,slash_commands:e.array(e.string()),output_style:e.string()}),Kt=_.extend({type:e.literal(`system`),subtype:e.literal(`compact_boundary`),compact_metadata:Wt}),qt=e.discriminatedUnion(`subtype`,[Gt,Kt]),Jt=_.extend({type:e.literal(`system`),subtype:e.string().refine(e=>!Bt.some(t=>t===e))}).passthrough(),F=e.union([qt,Jt]),I=v.extend({type:e.literal(`user`),message:Dt,isSynthetic:e.boolean().optional(),isCompactSummary:e.boolean().optional(),tool_use_result:e.object({stdout:e.string().optional(),stderr:e.string().optional(),interrupted:e.boolean().optional(),isImage:e.boolean().optional()}).or(e.string()).optional()}).refine(e=>!e.isCompactSummary||e.isSynthetic===!0,{message:`Compact summary messages must be synthetic`,path:[`isCompactSummary`]}),L=e.enum([`idle`,`turn_started`,`step_started`,`step_finished`,`turn_finished`,`paused`]),R=e.object({adapterId:e.string(),agentId:e.string(),oldState:L,newState:L,timestamp:e.number()}),Yt=e.object({status:e.enum([`allowed`,`allowed_warning`,`rejected`]),resetsAt:e.number().optional(),rateLimitType:e.enum([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:e.number().optional(),overageStatus:e.enum([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:e.number().optional(),overageDisabledReason:e.enum([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`no_limits_configured`,`fetch_error`,`unknown`]).optional(),isUsingOverage:e.boolean().optional(),surpassedThreshold:e.number().optional()}),Xt=_.extend({type:e.literal(`rate_limit_event`),rate_limit_info:Yt}),Zt=_.extend({type:e.literal(`command_lifecycle`),subtype:e.string(),command_uuid:e.string().optional()}).passthrough(),z=e.union([F,j,I,N,P,Xt,Zt]);e.intersection(z,e.object({agentId:e.string()}));const B=e.object({used_percentage:e.number().optional(),resets_at:e.number().optional()}).passthrough(),Qt=e.object({five_hour:B.optional(),seven_day:B.optional()}).passthrough(),$t=e.object({input_tokens:e.number().optional(),output_tokens:e.number().optional(),cache_creation_input_tokens:e.number().optional(),cache_read_input_tokens:e.number().optional()}).passthrough();e.object({cwd:e.string().optional(),session_id:e.string().optional(),session_name:e.string().optional(),transcript_path:e.string().optional(),model:e.object({id:e.string().optional(),display_name:e.string().optional(),family:e.string().optional()}).passthrough().optional(),workspace:e.object({current_dir:e.string().optional(),project_dir:e.string().optional(),added_dirs:e.array(e.string()).optional(),git_worktree:e.string().optional()}).passthrough().optional(),version:e.string().optional(),output_style:e.object({name:e.string().optional(),variant:e.string().optional()}).passthrough().optional(),cost:e.object({total_cost_usd:e.number().optional(),total_duration_ms:e.number().optional(),total_api_duration_ms:e.number().optional(),total_lines_added:e.number().optional(),total_lines_removed:e.number().optional(),total_edits:e.number().optional()}).passthrough().optional(),context_window:e.object({total_input_tokens:e.number().optional(),total_output_tokens:e.number().optional(),context_window_size:e.number().optional(),used_percentage:e.number().nullable().optional(),remaining_percentage:e.number().nullable().optional(),current_usage:$t.nullable().optional()}).passthrough().nullable().optional(),exceeds_200k_tokens:e.boolean().optional(),rate_limits:Qt.optional(),vim:e.object({mode:e.string().optional()}).passthrough().optional(),agent:e.object({name:e.string().optional(),kind:e.string().optional()}).passthrough().optional(),worktree:e.object({name:e.string().optional(),path:e.string().optional(),branch:e.string().optional(),original_cwd:e.string().optional(),original_branch:e.string().optional(),provider:e.string().optional()}).passthrough().optional()}).passthrough();const V=e.enum([`user`,`project`,`local`]),H=e.object({type:e.literal(`command`),command:e.string().min(1),padding:e.number().optional()}),U=e.object({type:e.literal(`command`),command:e.string().min(1),timeout:e.number().optional()}),W=e.object({matcher:e.string().optional(),hooks:e.array(U)}),G=e.object({type:e.string().min(1),url:e.string().optional(),command:e.string().optional(),args:e.array(e.string()).optional(),env:e.record(e.string(),e.string()).optional()}).passthrough(),en=e.object({scope:V,path:e.string(),value:H.nullable()}),tn=e.object({scope:V,path:e.string(),events:e.record(e.string(),e.array(W))}),nn=e.object({name:e.string().min(1),enabled:e.boolean(),scope:V});e.object({projectDir:f.optional()}),e.object({effective:H.nullable(),perScope:e.array(en)}),e.object({scope:V,projectDir:f.optional(),value:H}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({previous:H.nullable(),applied:H}),e.object({eventName:e.string().optional(),projectDir:f.optional()}),e.object({effective:e.record(e.string(),e.array(W)),perScope:e.array(tn)}),e.object({scope:V,projectDir:f.optional(),eventName:e.string().min(1),matcher:e.string().min(1).optional(),hook:U}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({added:e.boolean()}),e.object({scope:V,projectDir:f.optional(),eventName:e.string().min(1),match:e.object({commandContains:e.string().min(1)})}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({removed:e.number()}),e.object({projectDir:f.optional()}),e.object({plugins:e.array(nn)}),e.object({projectDir:f}),e.object({servers:e.record(e.string(),G)}),e.object({projectDir:f,name:e.string().min(1),server:G}),e.object({added:e.boolean(),replaced:e.boolean()}),e.object({projectDir:f,name:e.string().min(1)}),e.object({removed:e.boolean()}),e.object({projectDir:f.optional(),makaioCommand:e.string().min(1),envPairs:e.array(e.string()).optional()}),e.object({scope:V,projectDir:f.optional(),makaioCommand:e.string().min(1),envPairs:e.array(e.string()).optional(),configDir:f.optional(),skipDangerousModePermissionPrompt:e.boolean().optional(),binaryVersion:e.string().nullable().optional()}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({scope:V,projectDir:f.optional()}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]});const rn={none:0,low:4e3,medium:8e3,high:16e3,"extra-high":32e3},an=e.intersection(z,e.object({originatingMessageId:e.string().optional()})),on=/(?:api[_-]?key|authorization|bearer|credential|password|private[_-]?key|secret|token|(?:^|[_-])key(?:$|[_-])|(?:^|[_-])pat(?:$|[_-]))/i,sn=/^(?:message|content|prompt|text|output)$/i;function cn(e){return e.length>80?`${e.slice(0,80)}... [redacted-text]`:`[redacted-text]`}function K(e){return Array.isArray(e.errors)?e.errors.flatMap(e=>Array.isArray(e)?e.flatMap(e=>K(e)):[]):[`${e.path?.map(String).join(`.`)||`(root)`}: ${e.message??`Invalid input`}`]}function q(e,t){if(e&&e!==`apiKeySource`&&on.test(e))return`[redacted]`;if(typeof t==`string`&&(e&&sn.test(e)||t.length>80))return cn(t);if(Array.isArray(t))return t.map(e=>q(void 0,e));if(t&&typeof t==`object`){let e={};for(let[n,r]of Object.entries(t))e[n]=q(n,r);return e}return t}function ln(e){let t=q(void 0,e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function un(e){let t={subject:e.subject,issues:e.issues.flatMap(e=>K(e)),sample:ln(e.payload)};console.warn(`[BUS:VIOLATION] ${JSON.stringify(t)}`)}function dn(e,t){return ae(e,{"sdk.event":an,can_use_tool:ie,system:F,assistant:j,user:I,result:N,stream_event:P,"turn.state_changed":R,"turn.turn_started":R,"turn.step_started":R,"turn.step_finished":R,"turn.turn_finished":R,"turn.paused":R},t??{busValidationMode:`lenient`,onSchemaViolation:un})}function J(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}catch{return``}}const Y=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`];function X(e,t,n){return e!==void 0&&t.includes(e)?e:n}function Z(e,t){return e.type===`base64`?{type:`image`,source:{type:`base64`,data:e.data,media_type:X(t??u(e.mimeType),Y,`image/jpeg`)}}:{type:`image`,source:{type:`url`,url:e.url}}}function Q(e){return{type:`text`,data:e,media_type:`text/plain`}}function fn(e){return e.type===`base64`?u(e.mimeType)===`text/plain`?{type:`document`,source:Q(J(e.data))}:{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`}}:{type:`document`,source:{type:`url`,url:e.url}}}function pn(e){let{source:t}=e;if(t.type===`base64`){let e=u(t.mimeType);if(Y.includes(e))return Z(t,e);if(e===`application/pdf`)return{type:`document`,source:{type:`base64`,data:t.data,media_type:`application/pdf`}};if(le(e))return{type:`document`,source:Q(J(t.data))}}return{type:`text`,text:d(e)}}function $(e){return e.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.content};case`image`:{let t=e.source.type===`base64`?u(e.source.mimeType):void 0;return Z(e.source,t)}case`document`:return fn(e.source);case`attachment`:return pn(e);default:return{type:`text`,text:d(e)}}})}const mn=250;function hn(e){if(e.type!==`assistant`)return``;let t=e.message.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):``}function gn(e,t,s){let c=typeof t==`string`?t:``;switch(e){case`rate_limit_error`:return new o(c||`Rate limit exceeded`);case`authentication_error`:case`permission_error`:return new n(c||`Authentication failed`);case`overloaded_error`:return new a(c||`Service overloaded`);case`not_found_error`:{let e=typeof s==`string`?s.match(/model: ([^"]*)/)?.[1]:null;return e?new r(e):new i(c||`Model not found`)}default:return null}}function _n(e){return e.subtype!==`success`&&e.errors&&e.errors.length>0?e.errors.join(`
|
|
2
|
+
`)}function ve(e){return e.type!==`tool_use`||!e.id||!e.name?null:{toolCallId:e.id,toolName:e.name}}var ye=class extends ne{supportsNativeResume(){return!0}supportsNativeFork(){return!0}currentStepType=`text`;currentTextContent=``;currentReasoningContent=``;currentToolCall=null;toolBlockIndexMap=new Map;currentToolArgsJson=``;wireEvents(e){let t=e;this.wireConnectorEvents(t),this.wireToolApprovalRpc(e)}subscribeClaudeConnector(e,t,n,r){this.addConnectorWiringCleanup(e.on(t,n,r))}wireConnectorEvents(e){let t=this.getSubjects();this.subscribeClaudeConnector(e,t.sdk.event,async e=>{let t=e.payload,n=t.originatingMessageId;switch(t.type){case`system`:t.subtype===`init`&&await this.emitStart();break;case`assistant`:{let e=t.message?.content;if(!e)break;await ue(e,h,async(e,t)=>{if(e.subject===`tool.use`){if(n===void 0)return;let e=t;await this.emitToolUse(n,e.toolName,e.args,e.toolCallId)}else if(e.subject===`tool.started`||e.subject===`tool.completed`){if(n===void 0)return;await this.emitGlobal(e,{...t,messageId:n})}else await this.emitGlobal(e,t)});break}case`stream_event`:{let e=t.event;e.type===`content_block_start`?await this.handleContentBlockStart(e,n):e.type===`content_block_stop`?await this.handleContentBlockStop(e):e.type===`content_block_delta`&&await this.handleContentBlockDelta(e);break}case`result`:await this.handleResultEvent(t);break;case`user`:await this.handleUserEvent(t,n);break}})}async handleContentBlockStart(e,t){let n=e.content_block,r=ve(n),i=n.type===`thinking`?`reasoning`:n.type===`tool_use`?`tool_use`:`text`;this.currentStepType=i,this.currentTextContent=``,this.currentReasoningContent=``,this.currentToolArgsJson=``,this.currentToolCall=null;let a=r?{type:`tool_use`,toolName:r.toolName,toolCallId:r.toolCallId}:n.type===`tool_use`?void 0:{type:i},o;if(r&&(this.currentToolCall={toolCallId:r.toolCallId,name:r.toolName,args:{}},this.toolBlockIndexMap.set(r.toolCallId,e.index),o={type:`tool_call`,toolCallId:r.toolCallId,name:r.toolName,args:{}}),n.type===`tool_use`&&!r&&console.warn(`[ClaudeCodeAdapter] Received tool_use block without id or name; skipping tool correlation setup`),r&&t===void 0){console.warn(`[ClaudeCodeAdapter] Received tool_use block without originating message identity; skipping tool events`);return}await this.emitGlobal(s.step.started,{...t!==void 0&&{messageId:t},stepType:i,blockIndex:e.index,blockData:a,content:o}),r&&await this.emitGlobal(s.tool.started,{...t!==void 0&&{messageId:t},toolName:r.toolName,toolCallId:r.toolCallId})}async handleContentBlockStop(e){if(this.currentStepType!==`tool_use`){let t=this.currentStepType===`text`?{type:`text`,content:this.currentTextContent}:{type:`reasoning`,content:this.currentReasoningContent};await this.emitGlobal(s.step.finished,{stepType:this.currentStepType,blockIndex:e.index,content:t})}else if(this.currentToolCall&&this.currentToolArgsJson)try{this.currentToolCall.args=JSON.parse(this.currentToolArgsJson)}catch{}}async handleContentBlockDelta(e){let t=e.delta;switch(t.type){case`text_delta`:this.currentTextContent+=t.text,await this.emitGlobal(s.message_delta,{text:t.text});break;case`thinking_delta`:this.currentReasoningContent+=t.thinking,await this.emitGlobal(s.reasoning_delta,{content:t.thinking});break;case`input_json_delta`:`partial_json`in t&&(this.currentToolArgsJson+=t.partial_json);break}}async handleResultEvent(e){if(e.usage){let t=e.usage;await this.trackUsage(pe(t,e.total_cost_usd)),await this.emitContextWindowUpdate({currentTokens:me(t),maxTokens:this.getContextWindowSize()??2e5,cachedTokens:t.cache_read_input_tokens})}}async handleUserEvent(e,t){await he({messageId:t,payload:e,resolveToolOutput:async(e,t,n)=>await this.emitToolOutput(e,t,{nativeId:n}),emitToolCompleted:async e=>await this.emitGlobal(s.tool.completed,e),emitToolStepFinished:async e=>await this.emitGlobal(s.step.finished,{stepType:`tool_use`,blockIndex:e.blockIndex,content:{type:`tool_output`,toolCallId:e.toolCallId,output:e.output,isError:e.isError}}),consumeToolBlockIndex:e=>this.consumeToolBlockIndex(e)})}consumeToolBlockIndex(e){if(e===void 0)return-1;let t=this.toolBlockIndexMap.get(e);return this.toolBlockIndexMap.delete(e),t===void 0&&console.warn(`[ClaudeCodeAdapter] toolCallId ${e} not found in toolBlockIndexMap - possible state mismatch`),t??-1}wireToolApprovalRpc(e){this.addConnectorWiringCleanup(m(e,this.getSubjects(),async()=>({adapterId:this.adapterId,adapterName:this.adapterName,agentId:this.agentId,adapterSessionId:await this.getAdapterSessionId(),sessionId:this.sessionId}),this.globalBus))}},be=class{queue=[];resolvers=[];done=!1;async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else yield await new Promise(e=>{this.resolvers.push(t=>{t.done||e(t.value)})})}push(e){if(this.done)throw Error(`Cannot push to completed source`);this.resolvers.length>0?this.resolvers.shift()({value:e,done:!1}):this.queue.push(e)}complete(){this.done=!0;for(let e of this.resolvers)e({value:void 0,done:!0});this.resolvers=[]}clear(){this.queue=[]}},xe=class extends re{queryInstance;activeMessageHandle;pausedDeferred;isPausedFlag=!1;connectorBus;subjects;agentId;expectingInterruptResult=!1;constructor(e,t,n,r,i,a,o){super(e,n,r,`idle`),this.connectorBus=e,this.subjects=t,this.agentId=i,this.queryInstance=a,this.activeMessageHandle=o}setActiveMessageHandle(e){this.activeMessageHandle=e}async emitStateChange(e,t){let n={adapterId:this.adapterId,agentId:this.agentId,oldState:e,newState:t,timestamp:Date.now()};switch(await this.connectorBus.emit(this.subjects.turn.state_changed,n),t){case`turn_started`:await this.connectorBus.emit(this.subjects.turn.turn_started,n);break;case`step_started`:await this.connectorBus.emit(this.subjects.turn.step_started,n);break;case`step_finished`:await this.connectorBus.emit(this.subjects.turn.step_finished,n);break;case`turn_finished`:await this.connectorBus.emit(this.subjects.turn.turn_finished,n);break;case`paused`:await this.connectorBus.emit(this.subjects.turn.paused,n);break}}async start(){await this.transitionTo(`turn_started`)}async pause(){if(this.state===`turn_finished`)return{stateBeforePause:this.state,turnEnded:!0};if(this.isPausedFlag)return{stateBeforePause:this.state,turnEnded:!1};if(this.state!==`step_finished`&&(await this.waitForStepFinished(),this.getState()===`turn_finished`)||(await this.queryInstance.interrupt(),this.getState()===`turn_finished`))return{stateBeforePause:this.state,turnEnded:!0};this.expectingInterruptResult=!0,this.isPausedFlag=!0;let e=this.state;return await this.transitionTo(`paused`),{stateBeforePause:e,turnEnded:!1}}async resume(e){if(!this.isPausedFlag)throw Error(`Cannot resume - turn not paused`);this.isPausedFlag=!1,await this.transitionTo(`step_started`)}isPaused(){return this.isPausedFlag}async handleSdkEvent(e){if(e.type===`stream_event`)e.event.type===`content_block_start`?await this.transitionTo(`step_started`):e.event.type===`content_block_stop`&&(await this.transitionTo(`step_finished`),this.pausedDeferred?.resolve());else if(e.type===`result`){if(this.expectingInterruptResult){this.expectingInterruptResult=!1;return}await this.transitionTo(`turn_finished`)}}isExpectingInterruptResult(){return this.expectingInterruptResult}async finishOnError(){this.pausedDeferred?.resolve(),this.pausedDeferred=void 0,this.isPausedFlag=!1,this.expectingInterruptResult=!1,this.state!==`turn_finished`&&await this.transitionTo(`turn_finished`)}async waitForStepFinished(){if(this.state!==`step_finished`){this.pausedDeferred=new t;try{await this.pausedDeferred.getPromise()}finally{this.pausedDeferred=void 0}}}isCompleted(){return this.state===`turn_finished`}canAcceptImmediate(){return this.state!==`turn_finished`&&!this.isPausedFlag}};const g=Object.freeze({approve:`claude-code.tool-response.approve`,deny:`claude-code.tool-response.deny`});ee({id:`claude-code`,name:`Claude Code`,version:`0.1.0`,description:`Anthropic Claude Code CLI — an agentic coding assistant`,binary:{name:`claude`,supportedVersions:`^2.1.283`},managedInstall:{type:`signed-binary-bucket`,version:`2.1.283`,config:{baseUrl:`https://downloads.claude.ai/claude-code-releases`,manifestPathTemplate:`{version}/manifest.json`,manifestSignaturePathTemplate:`{version}/manifest.json.sig`,publicKeyUrl:`https://downloads.claude.ai/keys/claude-code.asc`,publicKeyFingerprint:`31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`,binaryPathTemplate:`{version}/{platform}/{binary}`,platforms:{"darwin-arm64":`darwin-arm64`,"darwin-x64":`darwin-x64`,"linux-arm64":`linux-arm64`,"linux-x64":`linux-x64`,"linux-arm64-musl":`linux-arm64-musl`,"linux-x64-musl":`linux-x64-musl`,"win32-arm64":`win32-arm64`,"win32-x64":`win32-x64`}}},versionCommand:{executable:{default:`claude`,win32:`claude.exe`},args:[`--version`]},configIsolation:{envVar:`CLAUDE_CONFIG_DIR`,defaultPath:`~/.claude`},nativeTools:[{name:`bash`,friendlyName:`Terminal`,description:`Execute shell commands`,category:`System`,capabilities:[{tag:`shell.execute`},{tag:`file.read`},{tag:`file.write`},{tag:`file.delete`},{tag:`network.request`},{tag:`process.manage`}]},{name:`text_editor`,friendlyName:`Text Editor`,description:`View and edit files`,category:`Files`,capabilities:[{tag:`file.read`},{tag:`file.write`}]},{name:`list_directory`,friendlyName:`List Directory`,description:`List directory contents`,category:`Files`,capabilities:[{tag:`file.read`},{tag:`search.files`}]},{name:`read_file`,friendlyName:`Read File`,description:`Read file contents`,category:`Files`,capabilities:[{tag:`file.read`}]},{name:`write_file`,friendlyName:`Write File`,description:`Write content to a file`,category:`Files`,capabilities:[{tag:`file.write`}]}],defaultApprovalPolicy:`full-access`,authMethods:[{id:`native`,mode:`inferred`,label:`Native account`},{id:`oauth-token`,mode:`explicit`,label:`OAuth token`,fields:[{id:`oauthToken`,label:`OAuth token`,required:!0,secret:!0,sourceHints:[{kind:`environment`,variable:`CLAUDE_CODE_OAUTH_TOKEN`}]}]}],defaultAuth:{providerDefinitionId:`anthropic-oauth`,methodId:`native`},runtimeCapabilities:{supportsHooks:!0,supportsStatusline:!0,supportsSupervisorLaunch:!1,supportsManagedBinary:!0,hookEvents:[{name:`SessionStart`,frameworkSubject:`client.session.started`,responseCapabilities:[`context.append`,te.sessionToken]},{name:`UserPromptSubmit`,frameworkSubject:`client.session.userPrompt.submitted`,responseCapabilities:[`context.append`]},{name:`PreToolUse`,frameworkSubject:`client.session.tool.pre`,responseCapabilities:[g.approve,g.deny,`context.append`]},{name:`PostToolUse`,frameworkSubject:`client.session.tool.post`,responseCapabilities:[`context.append`]},{name:`Stop`,frameworkSubject:`client.session.turn.completed`},{name:`SubagentStart`,frameworkSubject:`client.session.subagent.started`,responseCapabilities:[`context.append`]},{name:`SubagentStop`,frameworkSubject:`client.session.subagent.completed`},{name:`PreCompact`,frameworkSubject:`client.session.compaction.pre`},{name:`PostCompact`,minimumVersion:`2.1.76`},{name:`Notification`},{name:`MCPServerStart`},{name:`MCPServerStop`}]}});const _=e.object({uuid:e.string(),session_id:e.string(),type:e.string(),correlation_id:e.string().optional(),agentId:e.string().optional(),timestamp:e.string().optional(),cwd:e.string().optional()}),v=_.extend({parent_tool_use_id:e.string().nullable().optional()});_.required({agentId:!0}).extend({parent_tool_use_id:e.string().nullable().optional()});const y=e.enum([`invalid_tool_input`,`unavailable`,`too_many_requests`,`execution_time_exceeded`]),b=e.object({web_search_requests:e.number()}),Se=e.object({ephemeral_1h_input_tokens:e.number(),ephemeral_5m_input_tokens:e.number()}),x=e.object({cache_creation:Se.nullable().optional(),cache_creation_input_tokens:e.number().nullable().optional(),cache_read_input_tokens:e.number().nullable().optional(),input_tokens:e.number(),output_tokens:e.number(),server_tool_use:b.nullable().optional(),service_tier:e.enum([`standard`,`priority`,`batch`]).nullable().optional()});e.object({cache_creation_input_tokens:e.number().nullable().optional(),cache_read_input_tokens:e.number().nullable().optional(),input_tokens:e.number().nullable().optional(),output_tokens:e.number(),server_tool_use:b.nullable().optional()});const S=e.object({type:e.literal(`ephemeral`),ttl:e.enum([`5m`,`1h`]).optional()}),Ce=e.object({data:e.string(),media_type:e.enum([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),type:e.literal(`base64`)}),we=e.object({type:e.literal(`url`),url:e.string()}),Te=e.object({file_id:e.string(),type:e.literal(`file`)}),Ee=e.discriminatedUnion(`type`,[Ce,we,Te]),De=e.object({data:e.string(),media_type:e.literal(`application/pdf`),type:e.literal(`base64`)}),Oe=e.object({type:e.literal(`url`),url:e.string()}),ke=e.object({file_id:e.string(),type:e.literal(`file`)}),Ae=e.object({data:e.string(),media_type:e.literal(`text/plain`),type:e.literal(`text`)}),je=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_char_index:e.number(),file_id:e.string().nullable().optional(),start_char_index:e.number(),type:e.literal(`char_location`)}),Me=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_char_index:e.number(),start_char_index:e.number(),type:e.literal(`char_location`)}),Ne=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_page_number:e.number(),file_id:e.string().nullable().optional(),start_page_number:e.number(),type:e.literal(`page_location`)}),Pe=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_page_number:e.number(),start_page_number:e.number(),type:e.literal(`page_location`)}),Fe=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_block_index:e.number(),file_id:e.string().nullable().optional(),start_block_index:e.number(),type:e.literal(`content_block_location`)}),Ie=e.object({cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),end_block_index:e.number(),start_block_index:e.number(),type:e.literal(`content_block_location`)}),Le=e.object({cited_text:e.string(),encrypted_index:e.string(),title:e.string().nullable().optional(),type:e.literal(`web_search_result_location`),url:e.string()}),Re=e.object({cited_text:e.string(),encrypted_index:e.string(),title:e.string().nullable().optional(),type:e.literal(`web_search_result_location`),url:e.string()}),ze=e.object({cited_text:e.string(),end_block_index:e.number(),search_result_index:e.number(),source:e.string(),start_block_index:e.number(),title:e.string().nullable().optional(),type:e.literal(`search_result_location`)}),Be=e.object({cited_text:e.string(),end_block_index:e.number(),search_result_index:e.number(),source:e.string(),start_block_index:e.number(),title:e.string().nullable().optional(),type:e.literal(`search_result_location`)}),C=e.discriminatedUnion(`type`,[je,Ne,Fe,Le,ze]),Ve=e.discriminatedUnion(`type`,[Me,Pe,Ie,Re,Be]);e.object({citation:C,type:e.literal(`citations_delta`)});const w=e.object({enabled:e.boolean().optional()}),He=e.object({id:e.string(),expires_at:e.string()}),Ue=e.enum([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`pause_turn`,`refusal`]),T=e.object({text:e.string(),type:e.literal(`text`),cache_control:S.nullable().optional(),citations:e.array(Ve).nullable().optional()}),E=e.object({source:Ee,type:e.literal(`image`),cache_control:S.nullable().optional()}),We=e.object({content:e.union([e.string(),e.array(e.union([T,E]))]),type:e.literal(`content`)}),Ge=e.object({source:e.union([De,Ae,We,Oe,ke]),type:e.literal(`document`),cache_control:S.nullable().optional(),citations:w.optional(),context:e.string().nullable().optional(),title:e.string().nullable().optional()}),D=e.object({content:e.array(T),source:e.string(),title:e.string(),type:e.literal(`search_result`),cache_control:S.nullable().optional(),citations:w.optional()}),O=e.object({citations:e.array(C).nullable().optional(),text:e.string(),type:e.literal(`text`)}),k=e.object({signature:e.string(),thinking:e.string(),type:e.literal(`thinking`)}),Ke=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),qe=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),type:e.literal(`tool_use`)}),Je=e.object({id:e.string(),input:e.looseObject({}),name:e.enum([`web_search`,`code_execution`]),type:e.literal(`server_tool_use`)}),Ye=e.object({encrypted_content:e.string(),page_age:e.string().nullable().optional(),title:e.string(),type:e.literal(`web_search_result`),url:e.string()}),Xe=e.enum([`invalid_tool_input`,`unavailable`,`max_uses_exceeded`,`too_many_requests`,`query_too_long`]),Ze=e.object({error_code:Xe,type:e.literal(`web_search_tool_result_error`)}),Qe=e.union([Ze,e.array(Ye)]),$e=e.object({content:Qe,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`)}),et=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),tt=e.object({content:e.array(et),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),nt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),rt=e.union([nt,tt]),it=e.object({content:rt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`)}),at=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),server_name:e.string(),type:e.literal(`mcp_tool_use`)}),ot=e.object({content:e.union([e.string(),e.array(O)]),is_error:e.boolean(),tool_use_id:e.string(),type:e.literal(`mcp_tool_result`)}),st=e.object({file_id:e.string(),type:e.literal(`container_upload`)}),A=e.discriminatedUnion(`type`,[O,k,Ke,qe,Je,$e,it,at,ot,st]),ct=k.extend({}),lt=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),ut=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.string(),type:e.literal(`tool_use`),cache_control:S.nullable().optional()}),dt=e.object({tool_use_id:e.string(),type:e.literal(`tool_result`),cache_control:S.nullable().optional(),content:e.union([e.string(),e.array(e.union([T,E,D]))]).optional(),is_error:e.boolean().optional()}),ft=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.enum([`web_search`,`code_execution`]),type:e.literal(`server_tool_use`),cache_control:S.nullable().optional()}),pt=e.object({encrypted_content:e.string(),title:e.string(),type:e.literal(`web_search_result`),url:e.string(),page_age:e.string().nullable().optional()}),mt=e.object({error_code:e.enum([`invalid_tool_input`,`unavailable`,`max_uses_exceeded`,`too_many_requests`,`query_too_long`]),type:e.literal(`web_search_tool_result_error`)}),ht=e.union([e.array(pt),mt]),gt=e.object({content:ht,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`),cache_control:S.nullable().optional()}),_t=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),vt=e.object({content:e.array(_t),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),yt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),bt=e.union([yt,vt]),xt=e.object({content:bt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`),cache_control:S.nullable().optional()}),St=e.object({id:e.string(),input:e.record(e.string(),e.unknown()),name:e.string(),server_name:e.string(),type:e.literal(`mcp_tool_use`),cache_control:S.nullable().optional()}),Ct=e.object({tool_use_id:e.string(),type:e.literal(`mcp_tool_result`),cache_control:S.nullable().optional(),content:e.union([e.string(),e.array(T)]).optional(),is_error:e.boolean().optional()}),wt=e.object({file_id:e.string(),type:e.literal(`container_upload`),cache_control:S.nullable().optional()}),Tt=e.discriminatedUnion(`type`,[T,E,Ge,D,ct,lt,ut,dt,ft,gt,xt,St,Ct,wt]),Et=e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`),model:e.string(),content:e.array(A),stop_reason:Ue.nullable().optional(),stop_sequence:e.string().nullable().optional(),usage:x,container:He.nullable().optional()}),j=v.extend({type:e.literal(`assistant`),message:Et}),Dt=e.object({role:e.enum([`user`,`assistant`]),content:e.union([e.string(),e.array(Tt)])}),Ot=x.extend({cache_creation:x.shape.cache_creation.unwrap(),cache_creation_input_tokens:e.number(),cache_read_input_tokens:e.number(),server_tool_use:x.shape.server_tool_use.unwrap(),service_tier:e.enum([`standard`,`priority`,`batch`])}),kt=e.object({inputTokens:e.number(),outputTokens:e.number(),cacheReadInputTokens:e.number(),cacheCreationInputTokens:e.number(),webSearchRequests:e.number(),costUSD:e.number(),contextWindow:e.number()}),At=e.object({tool_name:e.string(),tool_use_id:e.string(),tool_input:e.unknown()}),M=_.extend({type:e.literal(`result`),duration_ms:e.number(),duration_api_ms:e.number(),is_error:e.boolean(),num_turns:e.number(),total_cost_usd:e.number(),usage:Ot,modelUsage:e.record(e.string(),kt),permission_denials:e.array(At)}),jt=M.extend({subtype:e.literal(`success`),result:e.string(),structured_output:c.optional()}),Mt=M.extend({subtype:e.enum([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),errors:e.array(e.string()),stop_reason:e.string().nullable()}),N=e.discriminatedUnion(`subtype`,[jt,Mt]),Nt=e.object({type:e.literal(`message_start`),message:e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`)})}),Pt=e.object({type:e.literal(`message_delta`),delta:e.object({stop_reason:e.string().nullable().optional(),stop_sequence:e.string().nullable().optional(),container:e.object({id:e.string(),expires_at:e.string()}).nullable().optional()}),usage:x}),Ft=e.object({type:e.literal(`message_stop`)}),It=e.object({type:e.literal(`content_block_start`),index:e.number(),content_block:A}),Lt=e.object({type:e.literal(`content_block_delta`),index:e.number(),delta:e.discriminatedUnion(`type`,[e.object({type:e.literal(`text_delta`),text:e.string()}),e.object({type:e.literal(`thinking_delta`),thinking:e.string()}),e.object({type:e.literal(`input_json_delta`),partial_json:e.string()}),e.object({type:e.literal(`citations_delta`),citation:C}),e.object({type:e.literal(`signature_delta`),signature:e.string()})])}),Rt=e.object({type:e.literal(`content_block_stop`),index:e.number()}),zt=e.discriminatedUnion(`type`,[Nt,Pt,Ft,It,Lt,Rt]),P=v.extend({type:e.literal(`stream_event`),event:zt}),Bt=[`init`,`compact_boundary`],Vt=e.enum([`user`,`project`,`org`,`temporary`,`none`]),Ht=e.enum([`default`,`acceptEdits`,`bypassPermissions`,`plan`]),Ut=e.object({name:e.string(),status:e.string()}),Wt=e.object({trigger:e.enum([`manual`,`auto`]),pre_tokens:e.number()}),Gt=_.extend({type:e.literal(`system`),subtype:e.literal(`init`),agents:e.array(e.string()).optional(),apiKeySource:Vt,cwd:e.string(),tools:e.array(e.string()),mcp_servers:e.array(Ut),model:e.string(),permissionMode:Ht,slash_commands:e.array(e.string()),output_style:e.string()}),Kt=_.extend({type:e.literal(`system`),subtype:e.literal(`compact_boundary`),compact_metadata:Wt}),qt=e.discriminatedUnion(`subtype`,[Gt,Kt]),Jt=_.extend({type:e.literal(`system`),subtype:e.string().refine(e=>!Bt.some(t=>t===e))}).passthrough(),F=e.union([qt,Jt]),I=v.extend({type:e.literal(`user`),message:Dt,isSynthetic:e.boolean().optional(),isCompactSummary:e.boolean().optional(),tool_use_result:e.object({stdout:e.string().optional(),stderr:e.string().optional(),interrupted:e.boolean().optional(),isImage:e.boolean().optional()}).or(e.string()).optional()}).refine(e=>!e.isCompactSummary||e.isSynthetic===!0,{message:`Compact summary messages must be synthetic`,path:[`isCompactSummary`]}),L=e.enum([`idle`,`turn_started`,`step_started`,`step_finished`,`turn_finished`,`paused`]),R=e.object({adapterId:e.string(),agentId:e.string(),oldState:L,newState:L,timestamp:e.number()}),Yt=e.object({status:e.enum([`allowed`,`allowed_warning`,`rejected`]),resetsAt:e.number().optional(),rateLimitType:e.enum([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:e.number().optional(),overageStatus:e.enum([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:e.number().optional(),overageDisabledReason:e.enum([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`no_limits_configured`,`fetch_error`,`unknown`]).optional(),isUsingOverage:e.boolean().optional(),surpassedThreshold:e.number().optional()}),Xt=_.extend({type:e.literal(`rate_limit_event`),rate_limit_info:Yt}),Zt=_.extend({type:e.literal(`command_lifecycle`),subtype:e.string(),command_uuid:e.string().optional()}).passthrough(),z=e.union([F,j,I,N,P,Xt,Zt]);e.intersection(z,e.object({agentId:e.string()}));const B=e.object({used_percentage:e.number().optional(),resets_at:e.number().optional()}).passthrough(),Qt=e.object({five_hour:B.optional(),seven_day:B.optional()}).passthrough(),$t=e.object({input_tokens:e.number().optional(),output_tokens:e.number().optional(),cache_creation_input_tokens:e.number().optional(),cache_read_input_tokens:e.number().optional()}).passthrough();e.object({cwd:e.string().optional(),session_id:e.string().optional(),session_name:e.string().optional(),transcript_path:e.string().optional(),model:e.object({id:e.string().optional(),display_name:e.string().optional(),family:e.string().optional()}).passthrough().optional(),workspace:e.object({current_dir:e.string().optional(),project_dir:e.string().optional(),added_dirs:e.array(e.string()).optional(),git_worktree:e.string().optional()}).passthrough().optional(),version:e.string().optional(),output_style:e.object({name:e.string().optional(),variant:e.string().optional()}).passthrough().optional(),cost:e.object({total_cost_usd:e.number().optional(),total_duration_ms:e.number().optional(),total_api_duration_ms:e.number().optional(),total_lines_added:e.number().optional(),total_lines_removed:e.number().optional(),total_edits:e.number().optional()}).passthrough().optional(),context_window:e.object({total_input_tokens:e.number().optional(),total_output_tokens:e.number().optional(),context_window_size:e.number().optional(),used_percentage:e.number().nullable().optional(),remaining_percentage:e.number().nullable().optional(),current_usage:$t.nullable().optional()}).passthrough().nullable().optional(),exceeds_200k_tokens:e.boolean().optional(),rate_limits:Qt.optional(),vim:e.object({mode:e.string().optional()}).passthrough().optional(),agent:e.object({name:e.string().optional(),kind:e.string().optional()}).passthrough().optional(),worktree:e.object({name:e.string().optional(),path:e.string().optional(),branch:e.string().optional(),original_cwd:e.string().optional(),original_branch:e.string().optional(),provider:e.string().optional()}).passthrough().optional()}).passthrough();const V=e.enum([`user`,`project`,`local`]),H=e.object({type:e.literal(`command`),command:e.string().min(1),padding:e.number().optional()}),U=e.object({type:e.literal(`command`),command:e.string().min(1),timeout:e.number().optional()}),W=e.object({matcher:e.string().optional(),hooks:e.array(U)}),G=e.object({type:e.string().min(1),url:e.string().optional(),command:e.string().optional(),args:e.array(e.string()).optional(),env:e.record(e.string(),e.string()).optional()}).passthrough(),en=e.object({scope:V,path:e.string(),value:H.nullable()}),tn=e.object({scope:V,path:e.string(),events:e.record(e.string(),e.array(W))}),nn=e.object({name:e.string().min(1),enabled:e.boolean(),scope:V});e.object({projectDir:f.optional()}),e.object({effective:H.nullable(),perScope:e.array(en)}),e.object({scope:V,projectDir:f.optional(),value:H}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({previous:H.nullable(),applied:H}),e.object({eventName:e.string().optional(),projectDir:f.optional()}),e.object({effective:e.record(e.string(),e.array(W)),perScope:e.array(tn)}),e.object({scope:V,projectDir:f.optional(),eventName:e.string().min(1),matcher:e.string().min(1).optional(),hook:U}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({added:e.boolean()}),e.object({scope:V,projectDir:f.optional(),eventName:e.string().min(1),match:e.object({commandContains:e.string().min(1)})}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({removed:e.number()}),e.object({projectDir:f.optional()}),e.object({plugins:e.array(nn)}),e.object({projectDir:f}),e.object({servers:e.record(e.string(),G)}),e.object({projectDir:f,name:e.string().min(1),server:G}),e.object({added:e.boolean(),replaced:e.boolean()}),e.object({projectDir:f,name:e.string().min(1)}),e.object({removed:e.boolean()}),e.object({projectDir:f.optional(),makaioCommand:e.string().min(1),envPairs:e.array(e.string()).optional()}),e.object({scope:V,projectDir:f.optional(),makaioCommand:e.string().min(1),envPairs:e.array(e.string()).optional(),configDir:f.optional(),skipDangerousModePermissionPrompt:e.boolean().optional(),binaryVersion:e.string().nullable().optional()}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({scope:V,projectDir:f.optional()}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]});const rn={none:0,low:4e3,medium:8e3,high:16e3,"extra-high":32e3},an=e.intersection(z,e.object({originatingMessageId:e.string().optional()})),on=/(?:api[_-]?key|authorization|bearer|credential|password|private[_-]?key|secret|token|(?:^|[_-])key(?:$|[_-])|(?:^|[_-])pat(?:$|[_-]))/i,sn=/^(?:message|content|prompt|text|output)$/i;function cn(e){return e.length>80?`${e.slice(0,80)}... [redacted-text]`:`[redacted-text]`}function K(e){return Array.isArray(e.errors)?e.errors.flatMap(e=>Array.isArray(e)?e.flatMap(e=>K(e)):[]):[`${e.path?.map(String).join(`.`)||`(root)`}: ${e.message??`Invalid input`}`]}function q(e,t){if(e&&e!==`apiKeySource`&&on.test(e))return`[redacted]`;if(typeof t==`string`&&(e&&sn.test(e)||t.length>80))return cn(t);if(Array.isArray(t))return t.map(e=>q(void 0,e));if(t&&typeof t==`object`){let e={};for(let[n,r]of Object.entries(t))e[n]=q(n,r);return e}return t}function ln(e){let t=q(void 0,e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function un(e){let t={subject:e.subject,issues:e.issues.flatMap(e=>K(e)),sample:ln(e.payload)};console.warn(`[BUS:VIOLATION] ${JSON.stringify(t)}`)}function dn(e,t){return ae(e,{"sdk.event":an,can_use_tool:ie,system:F,assistant:j,user:I,result:N,stream_event:P,"turn.state_changed":R,"turn.turn_started":R,"turn.step_started":R,"turn.step_finished":R,"turn.turn_finished":R,"turn.paused":R},t??{busValidationMode:`lenient`,onSchemaViolation:un})}function J(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}catch{return``}}const Y=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`];function X(e,t,n){return e!==void 0&&t.includes(e)?e:n}function Z(e,t){return e.type===`base64`?{type:`image`,source:{type:`base64`,data:e.data,media_type:X(t??u(e.mimeType),Y,`image/jpeg`)}}:{type:`image`,source:{type:`url`,url:e.url}}}function Q(e){return{type:`text`,data:e,media_type:`text/plain`}}function fn(e){return e.type===`base64`?u(e.mimeType)===`text/plain`?{type:`document`,source:Q(J(e.data))}:{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`}}:{type:`document`,source:{type:`url`,url:e.url}}}function pn(e){let{source:t}=e;if(t.type===`base64`){let e=u(t.mimeType);if(Y.includes(e))return Z(t,e);if(e===`application/pdf`)return{type:`document`,source:{type:`base64`,data:t.data,media_type:`application/pdf`}};if(le(e))return{type:`document`,source:Q(J(t.data))}}return{type:`text`,text:d(e)}}function $(e){return e.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.content};case`image`:{let t=e.source.type===`base64`?u(e.source.mimeType):void 0;return Z(e.source,t)}case`document`:return fn(e.source);case`attachment`:return pn(e);default:return{type:`text`,text:d(e)}}})}const mn=250;function hn(e){if(e.type!==`assistant`)return``;let t=e.message.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):``}function gn(e,t,s){let c=typeof t==`string`?t:``;switch(e){case`rate_limit_error`:return new o(c||`Rate limit exceeded`);case`authentication_error`:case`permission_error`:return new n(c||`Authentication failed`);case`overloaded_error`:return new a(c||`Service overloaded`);case`not_found_error`:{let e=typeof s==`string`?s.match(/model: ([^"]*)/)?.[1]:null;return e?new r(e):new i(c||`Model not found`)}default:return null}}function _n(e){return e.subtype!==`success`&&e.errors&&e.errors.length>0?e.errors.join(`
|
|
3
3
|
`):e.subtype===`success`&&e.is_error&&e.result?e.result:e.subtype}function vn(e){let t=e.toLowerCase();return t.includes(`rate limit`)||t.includes(`rate_limit`)?new o(e):t.includes(`quota`)||t.includes(`overloaded`)?new a(e):t.includes(`authentication`)||t.includes(`unauthorized`)||t.includes(`permission`)?new n(e):t.includes(`model`)&&(t.includes(`not found`)||t.includes(`unavailable`))?new i(e):null}function yn(e){let t=e.subtype===`success`&&e.is_error,n=_n(e);return gn(e.subtype,n,e.result)||(t&&typeof e.result==`string`?vn(e.result)||e.result:n)}function bn(e,t,n){let r={type:`text`,text:ce(t,n)},i=e.message.content,a=Array.isArray(i)?i:[{type:`text`,text:i}];return{...e,isSynthetic:!0,message:{...e.message,content:[r,...a]}}}function xn(e,t,n,r){return{uuid:e,session_id:t,agentId:n,type:`user`,parent_tool_use_id:null,isSynthetic:!1,message:{role:`user`,content:typeof r.message==`string`?r.message:$(r.blocks)}}}function Sn(e){return`structured_output`in e&&e.structured_output!==void 0?JSON.stringify(e.structured_output):e.result??``}function Cn(e,t){return e}export{be as AsyncQuerySource,h as CONTENT_BLOCK_HANDLERS,ye as ClaudeCodeAgent,xe as ClaudeConnectorTurn,z as SDKMessageSchema,mn as TERMINAL_RESULT_DRAIN_TIMEOUT_MS,$ as blocksToContentBlocks,rn as claudeReasoningLevels,dn as createClaudeConnectorNamespace,J as decodeBase64Text,hn as extractTextFromMessage,de as fromGlobalToolApproval,yn as parseResultError,bn as prependContextBlock,m as registerToolApprovalHandler,fe as requestToolApproval,Sn as resolveResultMessage,xn as sdkUserMessageFromNormalized,p as toGlobalToolApproval,Cn as unwrapBlockFromMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./chunk-DTipWd-i.mjs";import{n as t,o as n,s as r}from"./json-value-DM-EjTC1.mjs";import{C as i,_ as a,a as o,b as s,c,d as l,i as u,l as d,n as ee,p as te,r as ne,t as re,u as ie,w as f,x as ae,y as oe}from"./schemas-BvDsO8Is.mjs";import{C as se,M as ce,a as p,d as m,h as le,k as ue,r as de,s as h,t as g,x as fe}from"./kind-registration-CdjmVxY_.mjs";import{t as pe}from"./zod-json-schema-ZUmGtQhT.mjs";import{t as me}from"./ajv-Cvnmw2yn.mjs";import{t as he}from"./2020-CRfgqanb.mjs";import{t as ge}from"./dist-onY7e-pd.mjs";import{z as _}from"zod";import{createBusNamespace as _e}from"@makaio/framework/core";const ve=_.strictObject({evidence:i}),v=_.strictObject({kind:_.literal(`text`),text:_.string()}),[ye,be,xe]=i.options,Se=_.union([ye.pick({source:!0,location:!0}).extend({content:v}),be.pick({source:!0,location:!0}).extend({content:v}),xe.pick({source:!0,location:!0}).extend({content:v})]);function y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function Ce(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=y(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:y(r);return i===void 0?void 0:{node:i,pointer:n}}function x(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:y(n)?.[t],typeof y(n)?.$id==`string`)return!0}return!1}function we(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let r=i.safeParse(t);if(!r.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:r.data,dataPath:n}}function Te(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=Ce(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&S(e,i.node,n,x(e,i.pointer))}function S(e,t,n=new WeakSet,r=!1){let i=y(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||Te(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>S(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>S(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>S(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=y(i[t]);if(r&&Object.values(r).some(t=>S(e,t,n,a)))return!0}return!1}var Ee=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(x(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=Ce(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=we(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=y(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:y(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=y(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=y(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=y(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${b(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(S(this.dataSchema,e[r],void 0,x(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=y(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?y(e.additionalItems):y(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=y(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=y(e.properties),a=y(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=b(o),c=i!==void 0&&Object.hasOwn(i,o),l=y(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let u=this.visitPatterns(a,o,s,`${n}/${t}`,r),d=y(e.additionalProperties);!c&&!u&&d&&this.visit(d,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=y(s);e&&this.visit(e,n,r,`${i}/patternProperties/${b(o)}`)}return a}};function De(e,t,n){return new Ee(e,n.matchesSchema).extract(t)}function Oe(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...pe(t)};ue(i);let a=p.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=_.fromJSONSchema(a.dataSchema),s=_.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{Object.hasOwn(e,`slug`)&&t.addIssue({code:`custom`,path:[fe],message:se});try{ce(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var ke=e(me(),1),Ae=e(he(),1),je=e(ge(),1);function C(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new Ae.default(t):new ke.default(t);return(0,je.default)(n),n.addKeyword({keyword:ae,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function Me(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Ne(e){let t=e.instancePath.split(`/`).slice(1).map(Me),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function Pe(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Fe=n.array();function Ie(e){if(e.keyword!==`enum`)return;let t=Fe.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function Le(e){return(e??[]).map(e=>{let t=Pe(e),n=Ie(e);return{path:Ne(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function w(e){return typeof e==`object`&&!!e&&Object.hasOwn(e,`slug`)}const Re={path:fe,reason:se};function ze(e){let t=C(e);return e=>t(e)&&!w(e)}function Be(e){let t=C(e);return e=>{let n=t(e)?[]:Le(t.errors);return w(e)&&n.push(Re),n.length===0?{valid:!0}:{valid:!1,issues:n}}}function Ve(e){return{hooks:[...e.hooks]}}const He=[`inline`,`summary`,`link`,`omit`],Ue=[`outbound`,`inbound`],T=_.string().min(1),E=_.enum(Ue),We=_.object({kinds:_.array(_.string().min(1)).optional(),hint:T.optional(),depth:_.number().int().min(1).max(20).optional(),nested:_.lazy(()=>D).optional(),direction:E.optional()}),D=_.record(_.string().min(1),We);function O(e){return JSON.stringify([e.kind,e.id,e.revision])}const Ge=_.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),Ke=_.object({target:d,sourceRef:f,relationType:_.string().min(1),sourceLocalId:c.shape.sourceLocalId,direction:E.optional(),hint:T,status:_.enum([`resolved`,`unresolved`]),reason:Ge.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:_.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),k=_.object({rootRef:f,refs:_.array(Ke),resolved:_.array(l)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(O));n.has(O(e.rootRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(O(e.sourceRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(O(e.target))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function qe(e){let t=k.parse(e),n=new Map(t.resolved.map(e=>[O(e),e])),r=new Map;for(let e of t.refs){let t=O(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(O(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${O(t.rootRef)}'`);let a=Je(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return Ze(a,e),e}}}function Je(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:Xe(e,r,i,new Set([O(e)]))}}function Ye(e,t,n,r,i,a,o,s,c){let l=O(e),u=new Set(c);return u.add(l),{status:`resolved`,ref:e,artifact:t,relation:n,sourceLocalId:r,direction:i,hint:a,children:Xe(e,o,s,u)}}function Xe(e,t,n,r){return(t.get(O(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,sourceLocalId:e.sourceLocalId,direction:e.direction,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=O(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,sourceLocalId:e.sourceLocalId,direction:e.direction,hint:e.hint,reason:`cycle-detected`}:Ye(e.target,a,e.relationType,e.sourceLocalId,e.direction,e.hint,t,n,r)})}function Ze(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)Ze(n,t)}}const A=[`$set`,`$unset`,`$push`,`$pull`],j=`[A-Za-z_$][A-Za-z0-9_$]*`,M=`[A-Za-z_$][A-Za-z0-9_$-]*`,Qe=`(?:0|[1-9][0-9]*)`,$e=`(?:${`\\$\\[${j}\\]`}|${Qe}|${M})`,et=RegExp(`^${M}(?:\\.${$e})*$`),tt=RegExp(`^${j}(?:\\.${M})*$`),nt=RegExp(`^${Qe}$`),rt=RegExp(`^\\$\\[(${j})\\]$`),N=_.string().regex(et,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function it(e){let t=rt.exec(e);return t?.[1]===void 0?nt.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function at(e){return e.split(`.`).map(it)}function ot(e){return at(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const st=r(_.record(_.string().regex(tt,`Expected a filter key of the form name or name.field.path`),n),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function ct(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function P(e,t){return r(_.record(N,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const lt=_.literal(!0),ut=_.strictObject({$set:P(`$set`,n).optional(),$unset:P(`$unset`,lt).optional(),$push:P(`$push`,n).optional(),$pull:P(`$pull`,n).optional(),arrayFilters:_.array(st).optional()});function F(e){return A.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function dt(e,t){let n=F(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=ct(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of ot(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const ft=ut.superRefine(dt).superRefine((e,t)=>{F(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${A.join(`, `)}`})}),pt=ut.superRefine(dt),mt=_.strictObject({kind:f.shape.kind,id:f.shape.id}),ht=_.strictObject({ref:mt,baseRevision:f.shape.revision,patch:pt,dryRun:_.boolean().optional(),schemaVersion:m.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:te.optional(),representations:ie.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&F(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${A.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),gt=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`PAYLOAD_INVARIANT_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],_t=_.strictObject({path:_.string(),reason:_.string().min(1),expectedType:_.string().min(1).optional(),allowedValues:_.array(n).optional()}),vt=_.strictObject({code:_.enum(gt),message:_.string().min(1),operator:_.enum(A).optional(),path:N.optional(),currentRevision:f.shape.revision.optional(),issues:_.array(_t).optional(),repair:_.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:_.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),yt=_.strictObject({operator:_.enum(A),path:N,matched:_.number().int().positive()}),bt=_.strictObject({from:m,to:m}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),xt=_.strictObject({ok:_.literal(!0),base:f,operations:_.array(yt),migration:bt.optional()});function St(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const Ct=xt.extend({dryRun:_.literal(!0)}).superRefine(St),wt=xt.extend({dryRun:_.literal(!1),artifact:f}).superRefine(St),Tt=_.discriminatedUnion(`dryRun`,[Ct,wt]),Et=_.strictObject({ok:_.literal(!1),error:vt}),Dt=_.union([Tt,Et]),Ot=_.object({ref:oe}),kt=_.union([_.strictObject({ok:_.literal(!0),ref:oe,areaPath:de,part:t}),_.strictObject({ok:_.literal(!1),error:le})]),I=f.pick({kind:!0,id:!0}),L=_.number().int().positive(),R=L,z={knowledge:`valid`,commitment:`proposed`,interaction:`open`},B=_.discriminatedUnion(`category`,[_.strictObject({category:_.literal(`knowledge`),state:_.enum(g.knowledge),version:R}),_.strictObject({category:_.literal(`commitment`),state:_.enum(g.commitment),version:R}),_.strictObject({category:_.literal(`interaction`),state:_.enum(g.interaction),version:R})]).superRefine((e,t)=>{e.version===1&&e.state!==z[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),V=_.union([B,_.strictObject({category:_.literal(`record`)})]),H=_.string().trim().min(1),At=_.strictObject({kind:H,ref:H}),U=_.discriminatedUnion(`kind`,[_.strictObject({kind:_.literal(`revision-assessment`),assessedRevision:f.shape.revision,source:At.optional()}),_.strictObject({kind:_.literal(`handover`),source:At})]),jt={artifact:I,expectedVersion:R,state:h,situation:U,reason:H.optional()},W=_.strictObject(jt),Mt=_.strictObject({...jt,actor:re}),Nt={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function G(e,t){return Nt[e].includes(t)}const Pt={artifact:I,lifecycle:B,actor:re,timestamp:_.number().int().nonnegative(),observedRevision:f.shape.revision},Ft=_.strictObject({...Pt,operation:_.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==z[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function It(e,t){return t===`retired`||e===`retired`&&t===`valid`}const Lt=`Retiring or reinstating knowledge requires a reason`,K=_.strictObject({...Pt,operation:_.literal(`transitioned`),previousState:h,situation:U,reason:W.shape.reason}).superRefine((e,t)=>{(!G(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),It(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:Lt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Rt=_.discriminatedUnion(`operation`,[Ft,K]),q=_.discriminatedUnion(`reason`,[_.strictObject({reason:_.literal(`lifecycle-version-conflict`),expectedVersion:R,current:B,requestedState:h}),_.strictObject({reason:_.literal(`content-basis-conflict`),assessedRevision:f.shape.revision,currentRevision:f.shape.revision}),_.strictObject({reason:_.literal(`invalid-transition`),current:V,requestedState:h}),_.strictObject({reason:_.literal(`precondition-failed`),current:B,requestedState:h})]),J=`artifact-lifecycle-rejected`;var Y=class extends Error{code=J;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=q.parse(t)}};function zt(e){return e===`record`?{category:`record`}:B.parse({category:e,state:z[e],version:1})}function Bt(e){let t=V.parse(e.current),n=f.shape.revision.parse(e.currentRevision),r=Mt.parse(e.command);if(t.category===`record`)throw new Y(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new Y(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new Y(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!G(t.state,r.state))throw new Y(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(It(t.state,r.state)&&!r.reason)throw new Y(Lt,{reason:`precondition-failed`,current:t,requestedState:r.state});return B.parse({...t,state:r.state,version:t.version+1})}const Vt=_.strictObject({artifact:I}),Ht=_.strictObject({lifecycle:V}),Ut=_.strictObject({artifact:I,afterVersion:L.optional(),limit:_.number().int().min(1).max(100).default(50)}),Wt=_.strictObject({entries:_.array(Rt).max(100),nextCursor:L.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),X=_.strictObject({entry:K}),Gt=X,Kt=_.strictObject({code:_.literal(J),message:_.string().min(1),data:q});function qt(e){return{code:e.code,message:e.message,data:e.data}}function Jt(e,t){switch(t.reason){case`content-basis-conflict`:return Xt(e,t);case`lifecycle-version-conflict`:return[...Z(e,t),...Yt(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Z(e,t),...Zt(e,t)]}}function Z(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function Yt(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function Xt(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function Zt(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=G(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const Qt=_.strictObject({transition:W,error:Kt}).superRefine(({transition:e,error:t},n)=>{for(let r of Jt(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),$t={"lifecycle.get":{request:Vt,response:Ht},"lifecycle.history":{request:Ut,response:Wt},"lifecycle.transition":{request:W,response:X},"lifecycle.committed":Gt,"lifecycle.rejected":Qt},en=l.omit({id:!0,slug:!0,revision:!0,timestamp:!0}),tn={...$t,"kind.register":{request:p,response:_.object({registered:_.boolean()})},"kind.list":{request:_.object({kind:_.string().min(1).optional()}),response:_.object({kinds:_.array(p)})},"relation-type.register":{request:s,response:_.object({registered:_.boolean()})},"relation-type.list":{request:_.object({type:_.string().min(1).optional()}),response:_.object({relationTypes:_.array(s)})},create:{request:en.extend({id:f.shape.id.optional(),slug:l.shape.slug.optional()}),response:_.object({artifact:l})},revise:{request:_.object({previous:f,statusPath:te.optional(),revision:en}),response:_.object({artifact:l})},patch:{request:ht,response:Dt},resolve:{request:_.object({ref:f}),response:_.object({artifact:l.nullable()})},resolvePart:{request:Ot,response:kt},query:{request:o,response:_.object({artifacts:_.array(l)})},compare:{request:ee,response:ne},"evidence.resolve":{request:ve,response:Se},resolveContext:{request:_.object({ref:f,selectors:D.optional(),maxDepth:_.number().int().min(1).max(20).default(5)}),response:_.object({context:k})},created:_.object({artifact:l}),revised:_.object({previous:f,artifact:l}),"relation.added":_.object({artifact:f,relation:c}),"observation.added":_.object({artifact:f,observation:u}),"status.changed":_.object({artifact:f,path:_.string().min(1),previous:_.unknown().optional(),current:_.unknown().optional()}),"kind.changed":_.object({kind:_.string().min(1),schemaVersion:m})},nn=_e(`artifact`,tn),rn=nn.subjects,an=_.discriminatedUnion(`refClass`,[f.omit({revision:!0}),a]);function Q(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function $(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function on(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const sn=[`relation-target`,`data`];function cn(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!sn.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function ln(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n)||!Object.hasOwn(n,e))return;n=Reflect.get(n,e)}return{value:n}}function un(e,t,n,r){let{path:i}=e,a=ln(t,i);if(a===void 0||a.value===null||a.value===void 0)return{ruleIndex:n,selectorIndex:r,reason:`missing-value`,dataPath:i,message:`rule #${n}, selector #${r}, data path '${i}': no value found`};let{value:o}=a;return typeof o!=`string`&&typeof o!=`number`&&typeof o!=`boolean`?{ruleIndex:n,selectorIndex:r,reason:`unsupported-value-type`,dataPath:i,message:`rule #${n}, selector #${r}, data path '${i}': value must be a scalar (string, number, or boolean)`}:{path:i,value:o}}function dn(e,t,n,r,i){if(e.kind===`data`)return un(e,n,r,i);let{relationType:a}=e,o=t.filter(e=>e.type===a&&e.sourceLocalId===void 0),s=new Set,c,l;for(let e of o){let t=Q(e.target);if(t===void 0){l=e.target.refClass;break}s.add($(t)),c=t}return l===void 0?c===void 0?{ruleIndex:r,selectorIndex:i,reason:`missing-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': no relations of this type found`}:s.size>1?{ruleIndex:r,selectorIndex:i,reason:`ambiguous-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': ${s.size} distinct targets; expected exactly one`}:{type:a,target:c}:{ruleIndex:r,selectorIndex:i,reason:`unsupported-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': found a relation with refClass '${l}'; only artifact and entity targets are supported`}}function fn(e){return`target`in e?[`relation-target`,e.type,$(e.target)]:[`data`,e.path,e.value]}function pn(e,t,n){let r=[],i=[];for(let[a,o]of e.entries()){let e=o.by.map((e,r)=>dn(e,t,n,a,r)),s=e.filter(e=>`reason`in e);if(s.length>0){i.push(...s);continue}let c=e.filter(e=>!(`reason`in e)),l=JSON.stringify(c.map(e=>fn(e)));r.push({rule:o,ruleIndex:a,parts:c,serialized:l})}return{keys:r,issues:i}}function mn(e){return e.parts.map(e=>`target`in e?`${e.type} → ${on(e.target)}`:`${e.path} → ${JSON.stringify(e.value)}`).join(`; `)}function hn(e,t,n){let r=[];for(let[i,a]of(e??[]).entries()){if(!gn(a,n))continue;let e=_n(a,t);e<a.minItems&&r.push({index:i,requirement:a,reason:`below-min-items`,count:e}),a.maxItems!==void 0&&e>a.maxItems&&r.push({index:i,requirement:a,reason:`above-max-items`,count:e})}return r}function gn(e,t){return e.when===void 0?!0:ln(t,e.when.path)?.value===e.when.equals}function _n(e,t){let n=new Set;for(let r of t){if(r.sourceLocalId!==void 0||r.type!==e.relationType)continue;let t=Q(r.target);t?.refClass===`artifact`&&(e.targetKinds?.length&&!e.targetKinds.includes(t.kind)||n.add($(t)))}return n.size}export{Dt as $,B as A,gt as B,V as C,ve as Ct,Ft as D,I as E,Bt as F,vt as G,st as H,zt as I,bt as J,Et as K,G as L,W as M,K as N,q as O,L as P,ht as Q,Ot as R,J as S,De as St,Rt as T,ft as U,A as V,Ct as W,N as X,yt as Y,wt as Z,Wt as _,D as _t,an as a,it as at,X as b,ze as bt,$ as c,Ke as ct,rn as d,O as dt,Tt as et,Gt as f,Ue as ft,Ut as g,T as gt,Ht as h,We as ht,mn as i,ot as it,Mt as j,U as k,nn as l,Ge as lt,Vt as m,E as mt,cn as n,ct as nt,Q as o,at as ot,Kt as p,He as pt,_t as q,pn as r,F as rt,on as s,qe as st,hn as t,mt as tt,tn as u,k as ut,Qt as v,Ve as vt,Y as w,Se as wt,qt as x,Oe as xt,$t as y,Be as yt,kt as z};
|
package/dist/bus/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as te,N as f,O as ne,P as re,Q as p,R as m,S as h,T as ie,U as ae,V as g,W as oe,X as se,Y as ce,Z as le,_ as ue,a as de,at as fe,b as pe,d as _,et as me,f as he,g as v,h as y,i as ge,it as b,j as x,k as S,l as C,m as w,nt as T,o as E,p as D,q as O,r as k,rt as A,s as j,t as M,tt as N,u as P,v as F,w as I,x as L,y as _e,z as ve}from"../bus-_RyFr-xv.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await w(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await _(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof l)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>w(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new g(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new g(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(p(`system`,z)).subjects.channel.open}function ye(e,t,n,r){let i=v(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new c(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),l=globalThis.crypto.randomUUID(),u=new Set(e.transportRegistry.names()),d=new X(l,s,e,(i.payload.transports??[]).filter(e=>u.has(e)));try{n(d),i.setResult({channelId:l,endpointPubKey:await U(a)})}catch(e){throw d.close(),e}});return{name:t,token:r.token,close:i}}async function be(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await _(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var xe=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(s(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,s(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,s(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??s(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const Se=p(`bus:lifecycle`,de).subjects;function Ce(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function we(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Q(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{...p(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function Te(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Ee=x.fact.$meta.namespace,De=x.fact.subject;function Oe(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function ke(e,t,n,r,i,a){let o=y({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Ee,subject:De,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function Ae(e,t,n,r,i){return async function(a,o){if(!Oe(a))return!0;if(await ke(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function je(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:Ae(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{ae as BusAbortError,d as BusError,Se as BusLifecycle,m as CONNECTION_LOST_ERROR_CODE,c as ChannelAuthError,g as ChannelClosedError,n as ChannelOnlyError,ve as ConnectionLostError,xe as CorrelationTracker,he as DEFAULT_READINESS_TIMEOUT_MS,D as DEFAULT_REQUEST_TIMEOUT_MS,pe as LOCAL_ORIGIN,ee as LocalSubjectError,M as MakaioBus,o as NO_HANDLER_ERROR_CODE,l as NoHandlerError,P as OnceAbortError,L as REMOTE_ORIGIN,re as RequestError,z as SystemChannelSchemas,f as TimeoutError,te as ValidationError,F as __resetWarnedSubjects,Ce as buildSubscribeMessage,we as buildUnsubscribeMessage,b as channelSubject,me as collectorOnlySubject,k as createBusContext,ge as createBusInstance,ye as createChannelEndpoint,Q as createExtensionNamespace,C as createFilteredBus,je as createProjectedTelemetryTransport,Te as createSubjectTelemetryProjectorRegistry,N as defaultTransports,E as defineSubjectExtension,a as deserializeTransportError,j as extendSubject,i as findInErrorChain,e as getFullSubjectForSubjectDefinition,O as getPath,ne as getSubjectFromBusMessage,h as handleCorrelationResponse,T as hostLocalRequest,S as isNoHandlerErrorForSubject,oe as isRequestCancellation,fe as isRequestSchema,A as localSubject,se as matchesAnySubscription,u as matchesFilter,le as matchesSubscription,ce as mergeFilters,be as openChannel,_e as parseBusUrl,y as projectSubjectTelemetryFacts,r as serializeTransportError,I as shouldReceiveMessage,ie as trackMessageCorrelation,t as transportErrorData,ue as waitForSubscriptionPropagation};
|
|
1
|
+
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as te,N as f,O as ne,P as re,Q as p,R as m,S as h,T as ie,U as ae,V as g,W as oe,X as se,Y as ce,Z as le,_ as ue,a as de,at as fe,b as pe,d as _,et as me,f as he,g as v,h as y,i as ge,it as b,j as x,k as S,l as C,m as w,nt as T,o as E,p as D,q as O,r as k,rt as A,s as j,t as M,tt as N,u as P,v as F,w as I,x as L,y as _e,z as ve}from"../bus--m38BS3i.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await w(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await _(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof l)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>w(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new g(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new g(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(p(`system`,z)).subjects.channel.open}function ye(e,t,n,r){let i=v(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new c(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),l=globalThis.crypto.randomUUID(),u=new Set(e.transportRegistry.names()),d=new X(l,s,e,(i.payload.transports??[]).filter(e=>u.has(e)));try{n(d),i.setResult({channelId:l,endpointPubKey:await U(a)})}catch(e){throw d.close(),e}});return{name:t,token:r.token,close:i}}async function be(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await _(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var xe=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(s(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,s(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,s(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??s(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const Se=p(`bus:lifecycle`,de).subjects;function Ce(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function we(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Q(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{...p(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function Te(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Ee=x.fact.$meta.namespace,De=x.fact.subject;function Oe(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function ke(e,t,n,r,i,a){let o=y({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Ee,subject:De,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function Ae(e,t,n,r,i){return async function(a,o){if(!Oe(a))return!0;if(await ke(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function je(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:Ae(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{ae as BusAbortError,d as BusError,Se as BusLifecycle,m as CONNECTION_LOST_ERROR_CODE,c as ChannelAuthError,g as ChannelClosedError,n as ChannelOnlyError,ve as ConnectionLostError,xe as CorrelationTracker,he as DEFAULT_READINESS_TIMEOUT_MS,D as DEFAULT_REQUEST_TIMEOUT_MS,pe as LOCAL_ORIGIN,ee as LocalSubjectError,M as MakaioBus,o as NO_HANDLER_ERROR_CODE,l as NoHandlerError,P as OnceAbortError,L as REMOTE_ORIGIN,re as RequestError,z as SystemChannelSchemas,f as TimeoutError,te as ValidationError,F as __resetWarnedSubjects,Ce as buildSubscribeMessage,we as buildUnsubscribeMessage,b as channelSubject,me as collectorOnlySubject,k as createBusContext,ge as createBusInstance,ye as createChannelEndpoint,Q as createExtensionNamespace,C as createFilteredBus,je as createProjectedTelemetryTransport,Te as createSubjectTelemetryProjectorRegistry,N as defaultTransports,E as defineSubjectExtension,a as deserializeTransportError,j as extendSubject,i as findInErrorChain,e as getFullSubjectForSubjectDefinition,O as getPath,ne as getSubjectFromBusMessage,h as handleCorrelationResponse,T as hostLocalRequest,S as isNoHandlerErrorForSubject,oe as isRequestCancellation,fe as isRequestSchema,A as localSubject,se as matchesAnySubscription,u as matchesFilter,le as matchesSubscription,ce as mergeFilters,be as openChannel,_e as parseBusUrl,y as projectSubjectTelemetryFacts,r as serializeTransportError,I as shouldReceiveMessage,ie as trackMessageCorrelation,t as transportErrorData,ue as waitForSubscriptionPropagation};
|