@makaio/framework 1.0.0-dev-1789609124644 → 1.0.0-dev-1789642522820
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/{adapter-C4v_gNTI.mjs → adapter-DSRgsh2d.mjs} +1 -1
- package/dist/adapters/claude/index.mjs +3 -3
- package/dist/bus/index.mjs +1 -1
- package/dist/bus-BOGcnhgA.mjs +9 -0
- package/dist/client-DqfP7BeX.mjs +1 -0
- package/dist/clients/index.d.mts +152 -11
- package/dist/clients/index.mjs +1 -1
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/client/index.d.mts +3 -3
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/index.d.mts +15 -15
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/drizzle/0040_session_generation.sql +1 -0
- package/dist/drizzle/meta/_journal.json +7 -0
- package/dist/{framework-packages-Bg4edkkM.mjs → framework-packages-BNFG51Td.mjs} +1 -1
- package/dist/{hook-responses-Dq16X3Cb.d.mts → hook-responses-CQ2q0aPE.d.mts} +47 -4
- package/dist/{index-7CVumCjj.d.mts → index-BS-Fhlux.d.mts} +42 -7
- package/dist/{index-C6e9cwAl2.d.mts → index-CdWxSwhQ2.d.mts} +4 -4
- package/dist/{index-iVisrVdC2.d.mts → index-CztxEJrG2.d.mts} +46 -3
- package/dist/{index-Bg3WVL8n.d.mts → index-Dn23R_ck.d.mts} +2 -2
- package/dist/{index-D_j_T3nS.d.mts → index-Hnsy6XhM.d.mts} +1 -1
- package/dist/{index-CRZ1jrxp.d.mts → index-p1l00SGS.d.mts} +86 -7
- package/dist/{index-mTaFX2HH2.d.mts → index-zEkS2L862.d.mts} +6 -0
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{namespace-Cmu-5_P9.d.mts → namespace-BR03HE8G.d.mts} +42 -0
- package/dist/{namespace-BEbQb19g.d.mts → namespace-BqfzcRkL.d.mts} +5 -5
- package/dist/{orchestrator-shared-CtPB6PAr.mjs → orchestrator-shared-CxO1lfpP.mjs} +1 -1
- package/dist/ownership-memory-handler-BOhmmlJj.mjs +1 -0
- package/dist/package.json +1 -1
- package/dist/{registry-DNMjJ-Oj.mjs → registry-DtaRGU8i.mjs} +1 -0
- package/dist/{schema-BA1cHBbc.d.mts → schema-DqKCg5Ec.d.mts} +30 -0
- package/dist/{schemas-CaYEFzK_.d.mts → schemas-CFciElld.d.mts} +2 -2
- package/dist/schemas-CkxAK13D.mjs +1 -0
- package/dist/services/index.d.mts +6 -6
- package/dist/services/index.mjs +1 -1
- package/dist/services/session/index.d.mts +4 -4
- package/dist/services/session/index.mjs +1 -1
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/orchestrator-testing/index.mjs +1 -1
- package/dist/services/session/storage/namespace.d.mts +1 -1
- package/dist/services/session/storage/schema.d.mts +1 -1
- package/dist/services/session/storage/schema.mjs +1 -1
- package/dist/services/session/testing/index.mjs +2 -1
- package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
- package/dist/services/settings/namespace.d.mts +2 -2
- package/dist/services/subagent-template/index.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/services/tool-approval/index.mjs +1 -1
- package/dist/services/tools/index.mjs +1 -1
- package/dist/services/workflow-transitions/index.mjs +1 -1
- package/dist/session-BP5aq2kt.mjs +95 -0
- package/dist/{session-BB0s7c2B.mjs → session-BcArFp9M.mjs} +1 -1
- package/dist/storage/drizzle/client.mjs +1 -1
- package/dist/storage/drizzle/index.mjs +1 -1
- package/dist/{tool-approval-service-pbkGcAV8.mjs → tool-approval-service-CXTklh3T.mjs} +1 -1
- package/dist/{tools-C5Gy0IQG.mjs → tools-hiFv-jJn.mjs} +1 -1
- package/dist/{types-DhbllltK.d.mts → types-D5kqrOad.d.mts} +9 -0
- package/dist/{workflow-transitions-C0sg3kar.mjs → workflow-transitions-BalNKTtE.mjs} +1 -1
- package/package.json +1 -1
- package/dist/bus-BQ64i3DN.mjs +0 -9
- package/dist/client-Bg3_IdaF.mjs +0 -1
- package/dist/ownership-memory-handler-xex7sLiX.mjs +0 -1
- package/dist/schemas-ClkcU_N5.mjs +0 -1
- package/dist/session-6UG5udTX.mjs +0 -95
package/dist/.makaio-build.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"fingerprint": "
|
|
4
|
-
"builtAt": "2026-09-
|
|
3
|
+
"fingerprint": "556c827d9cc37a0dac37b06a5ea896d6c0351ceeee4d8bace27c9999ee83f19e",
|
|
4
|
+
"builtAt": "2026-09-17T10:56:37.025Z",
|
|
5
5
|
"declarations": true,
|
|
6
6
|
"declarationBackend": "tsc"
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as e,E as t,T as n,c as r,d as i,f as a,g as o,h as s,k as c,l,m as u,o as d,p as f,s as p,t as m,u as h,v as g,wn as _,y as v}from"./schemas-
|
|
1
|
+
import{D as e,E as t,T as n,c as r,d as i,f as a,g as o,h as s,k as c,l,m as u,o as d,p as f,s as p,t as m,u as h,v as g,wn as _,y as v}from"./schemas-CkxAK13D.mjs";import"./compression-CPrVeC42.mjs";import"./provider-context-DFTB8rsU.mjs";import"./contracts/adapter/schemas/session-lineage.mjs";import{createBusNamespace as y}from"@makaio/framework/core";const b={getCapabilities:_,startAgent:c,infer:e,listAgents:t,getAgent:n,stopAgent:v,rehydrateAgent:g,acknowledgeCallerSettlement:o,getConfigSchema:s,"agent.created":u,"session.created":f,"session.discovered":m,"session.usage":a,"session.closed":i,log:h,error:l,initialized:r,deinitialized:p,quota:d},x=y(`adapter`,b),S=x.subjects;export{S as n,b as r,x as t};
|
|
@@ -1,3 +1,3 @@
|
|
|
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{AIAgent as
|
|
2
|
-
`)}function _e(e){return e.type!==`tool_use`||!e.id||!e.name?null:{toolCallId:e.id,toolName:e.name}}var ve=class extends te{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 le(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=_e(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(fe(t,e.total_cost_usd)),await this.emitContextWindowUpdate({currentTokens:pe(t),maxTokens:this.getContextWindowSize()??2e5,cachedTokens:t.cache_read_input_tokens})}}async handleUserEvent(e,t){await me({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))}},ye=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=[]}},be=class extends ne{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`]},{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`},{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()}),xe=e.object({ephemeral_1h_input_tokens:e.number(),ephemeral_5m_input_tokens:e.number()}),x=e.object({cache_creation:xe.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()}),Se=e.object({data:e.string(),media_type:e.enum([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),type:e.literal(`base64`)}),Ce=e.object({type:e.literal(`url`),url:e.string()}),we=e.object({file_id:e.string(),type:e.literal(`file`)}),Te=e.discriminatedUnion(`type`,[Se,Ce,we]),Ee=e.object({data:e.string(),media_type:e.literal(`application/pdf`),type:e.literal(`base64`)}),De=e.object({type:e.literal(`url`),url:e.string()}),Oe=e.object({file_id:e.string(),type:e.literal(`file`)}),ke=e.object({data:e.string(),media_type:e.literal(`text/plain`),type:e.literal(`text`)}),Ae=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`)}),je=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`)}),Me=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`)}),Ne=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`)}),Pe=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`)}),Fe=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`)}),Ie=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()}),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(),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`)}),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`)}),C=e.discriminatedUnion(`type`,[Ae,Me,Pe,Ie,Re]),Be=e.discriminatedUnion(`type`,[je,Ne,Fe,Le,ze]);e.object({citation:C,type:e.literal(`citations_delta`)});const w=e.object({enabled:e.boolean().optional()}),Ve=e.object({id:e.string(),expires_at:e.string()}),He=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(Be).nullable().optional()}),E=e.object({source:Te,type:e.literal(`image`),cache_control:S.nullable().optional()}),Ue=e.object({content:e.union([e.string(),e.array(e.union([T,E]))]),type:e.literal(`content`)}),We=e.object({source:e.union([Ee,ke,Ue,De,Oe]),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`)}),Ge=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),Ke=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),type:e.literal(`tool_use`)}),qe=e.object({id:e.string(),input:e.looseObject({}),name:e.enum([`web_search`,`code_execution`]),type:e.literal(`server_tool_use`)}),Je=e.object({encrypted_content:e.string(),page_age:e.string().nullable().optional(),title:e.string(),type:e.literal(`web_search_result`),url:e.string()}),Ye=e.enum([`invalid_tool_input`,`unavailable`,`max_uses_exceeded`,`too_many_requests`,`query_too_long`]),Xe=e.object({error_code:Ye,type:e.literal(`web_search_tool_result_error`)}),Ze=e.union([Xe,e.array(Je)]),Qe=e.object({content:Ze,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`)}),$e=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),et=e.object({content:e.array($e),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),tt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),nt=e.union([tt,et]),rt=e.object({content:nt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`)}),it=e.object({id:e.string(),input:e.looseObject({}),name:e.string(),server_name:e.string(),type:e.literal(`mcp_tool_use`)}),at=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`)}),ot=e.object({file_id:e.string(),type:e.literal(`container_upload`)}),A=e.discriminatedUnion(`type`,[O,k,Ge,Ke,qe,Qe,rt,it,at,ot]),st=k.extend({}),ct=e.object({data:e.string(),type:e.literal(`redacted_thinking`)}),lt=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()}),ut=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()}),dt=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()}),ft=e.object({encrypted_content:e.string(),title:e.string(),type:e.literal(`web_search_result`),url:e.string(),page_age:e.string().nullable().optional()}),pt=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`)}),mt=e.union([e.array(ft),pt]),ht=e.object({content:mt,tool_use_id:e.string(),type:e.literal(`web_search_tool_result`),cache_control:S.nullable().optional()}),gt=e.object({file_id:e.string(),type:e.literal(`code_execution_output`)}),_t=e.object({content:e.array(gt),return_code:e.number(),stderr:e.string(),stdout:e.string(),type:e.literal(`code_execution_result`)}),vt=e.object({error_code:y,type:e.literal(`code_execution_tool_result_error`)}),yt=e.union([vt,_t]),bt=e.object({content:yt,tool_use_id:e.string(),type:e.literal(`code_execution_tool_result`),cache_control:S.nullable().optional()}),xt=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()}),St=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()}),Ct=e.object({file_id:e.string(),type:e.literal(`container_upload`),cache_control:S.nullable().optional()}),j=e.discriminatedUnion(`type`,[T,E,We,D,st,ct,lt,ut,dt,ht,bt,xt,St,Ct]),wt=e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`),model:e.string(),content:e.array(A),stop_reason:He.nullable().optional(),stop_sequence:e.string().nullable().optional(),usage:x,container:Ve.nullable().optional()}),M=v.extend({type:e.literal(`assistant`),message:wt}),Tt=e.object({role:e.enum([`user`,`assistant`]),content:e.union([e.string(),e.array(j)])}),Et=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`])}),Dt=e.object({inputTokens:e.number(),outputTokens:e.number(),cacheReadInputTokens:e.number(),cacheCreationInputTokens:e.number(),webSearchRequests:e.number(),costUSD:e.number(),contextWindow:e.number()}),Ot=e.object({tool_name:e.string(),tool_use_id:e.string(),tool_input:e.unknown()}),N=_.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:Et,modelUsage:e.record(e.string(),Dt),permission_denials:e.array(Ot)}),kt=N.extend({subtype:e.literal(`success`),result:e.string(),structured_output:c.optional()}),At=N.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()}),P=e.discriminatedUnion(`subtype`,[kt,At]),jt=e.object({type:e.literal(`message_start`),message:e.object({id:e.string(),type:e.literal(`message`),role:e.literal(`assistant`)})}),Mt=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}),Nt=e.object({type:e.literal(`message_stop`)}),Pt=e.object({type:e.literal(`content_block_start`),index:e.number(),content_block:A}),Ft=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()})])}),It=e.object({type:e.literal(`content_block_stop`),index:e.number()}),Lt=e.discriminatedUnion(`type`,[jt,Mt,Nt,Pt,Ft,It]),F=v.extend({type:e.literal(`stream_event`),event:Lt}),Rt=[`init`,`compact_boundary`],zt=e.enum([`user`,`project`,`org`,`temporary`,`none`]),Bt=e.enum([`default`,`acceptEdits`,`bypassPermissions`,`plan`]),Vt=e.object({name:e.string(),status:e.string()}),Ht=e.object({trigger:e.enum([`manual`,`auto`]),pre_tokens:e.number()}),Ut=_.extend({type:e.literal(`system`),subtype:e.literal(`init`),agents:e.array(e.string()).optional(),apiKeySource:zt,cwd:e.string(),tools:e.array(e.string()),mcp_servers:e.array(Vt),model:e.string(),permissionMode:Bt,slash_commands:e.array(e.string()),output_style:e.string()}),Wt=_.extend({type:e.literal(`system`),subtype:e.literal(`compact_boundary`),compact_metadata:Ht}),Gt=e.discriminatedUnion(`subtype`,[Ut,Wt]),Kt=_.extend({type:e.literal(`system`),subtype:e.string().refine(e=>!Rt.some(t=>t===e))}).passthrough(),I=e.union([Gt,Kt]),L=v.extend({type:e.literal(`user`),message:Tt,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`]}),R=e.enum([`idle`,`turn_started`,`step_started`,`step_finished`,`turn_finished`,`paused`]),z=e.object({adapterId:e.string(),agentId:e.string(),oldState:R,newState:R,timestamp:e.number()}),qt=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()}),Jt=_.extend({type:e.literal(`rate_limit_event`),rate_limit_info:qt}),Yt=_.extend({type:e.literal(`command_lifecycle`),subtype:e.string(),command_uuid:e.string().optional()}).passthrough(),B=e.union([I,M,L,P,F,Jt,Yt]);e.intersection(B,e.object({agentId:e.string()}));const V=e.object({used_percentage:e.number().optional(),resets_at:e.number().optional()}).passthrough(),Xt=e.object({five_hour:V.optional(),seven_day:V.optional()}).passthrough(),Zt=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:Zt.nullable().optional()}).passthrough().nullable().optional(),exceeds_200k_tokens:e.boolean().optional(),rate_limits:Xt.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 H=e.enum([`user`,`project`,`local`]),U=e.object({type:e.literal(`command`),command:e.string().min(1),padding:e.number().optional()}),W=e.object({type:e.literal(`command`),command:e.string().min(1),timeout:e.number().optional()}),G=e.object({matcher:e.string().optional(),hooks:e.array(W)}),K=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(),Qt=e.object({scope:H,path:e.string(),value:U.nullable()}),$t=e.object({scope:H,path:e.string(),events:e.record(e.string(),e.array(G))}),en=e.object({name:e.string().min(1),enabled:e.boolean(),scope:H});e.object({projectDir:f.optional()}),e.object({effective:U.nullable(),perScope:e.array(Qt)}),e.object({scope:H,projectDir:f.optional(),value:U}).refine(e=>e.scope===`user`||e.projectDir!==void 0,{message:`projectDir is required when scope is project or local`,path:[`projectDir`]}),e.object({previous:U.nullable(),applied:U}),e.object({eventName:e.string().optional(),projectDir:f.optional()}),e.object({effective:e.record(e.string(),e.array(G)),perScope:e.array($t)}),e.object({scope:H,projectDir:f.optional(),eventName:e.string().min(1),matcher:e.string().min(1).optional(),hook:W}).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:H,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(en)}),e.object({projectDir:f}),e.object({servers:e.record(e.string(),K)}),e.object({projectDir:f,name:e.string().min(1),server:K}),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:H,projectDir:f.optional(),makaioCommand:e.string().min(1),envPairs:e.array(e.string()).optional(),configDir:f.optional(),skipDangerousModePermissionPrompt:e.boolean().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:H,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 tn={none:0,low:4e3,medium:8e3,high:16e3,"extra-high":32e3},nn=e.intersection(B,e.object({originatingMessageId:e.string().optional()})),rn=/(?:api[_-]?key|authorization|bearer|credential|password|private[_-]?key|secret|token|(?:^|[_-])key(?:$|[_-])|(?:^|[_-])pat(?:$|[_-]))/i,an=/^(?:message|content|prompt|text|output)$/i;function on(e){return e.length>80?`${e.slice(0,80)}... [redacted-text]`:`[redacted-text]`}function q(e){return Array.isArray(e.errors)?e.errors.flatMap(e=>Array.isArray(e)?e.flatMap(e=>q(e)):[]):[`${e.path?.map(String).join(`.`)||`(root)`}: ${e.message??`Invalid input`}`]}function J(e,t){if(e&&e!==`apiKeySource`&&rn.test(e))return`[redacted]`;if(typeof t==`string`&&(e&&an.test(e)||t.length>80))return on(t);if(Array.isArray(t))return t.map(e=>J(void 0,e));if(t&&typeof t==`object`){let e={};for(let[n,r]of Object.entries(t))e[n]=J(n,r);return e}return t}function sn(e){let t=J(void 0,e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function cn(e){let t={subject:e.subject,issues:e.issues.flatMap(e=>q(e)),sample:sn(e.payload)};console.warn(`[BUS:VIOLATION] ${JSON.stringify(t)}`)}function ln(e,t){return ie(e,{"sdk.event":nn,can_use_tool:re,system:I,assistant:M,user:L,result:P,stream_event:F,"turn.state_changed":z,"turn.turn_started":z,"turn.step_started":z,"turn.step_finished":z,"turn.turn_finished":z,"turn.paused":z},t??{busValidationMode:`lenient`,onSchemaViolation:cn})}function Y(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}catch{return``}}const X=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`];function un(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:un(t??u(e.mimeType),X,`image/jpeg`)}}:{type:`image`,source:{type:`url`,url:e.url}}}function Q(e){return{type:`text`,data:e,media_type:`text/plain`}}function dn(e){return e.type===`base64`?u(e.mimeType)===`text/plain`?{type:`document`,source:Q(Y(e.data))}:{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`}}:{type:`document`,source:{type:`url`,url:e.url}}}function fn(e){let{source:t}=e;if(t.type===`base64`){let e=u(t.mimeType);if(X.includes(e))return Z(t,e);if(e===`application/pdf`)return{type:`document`,source:{type:`base64`,data:t.data,media_type:`application/pdf`}};if(ce(e))return{type:`document`,source:Q(Y(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 dn(e.source);case`attachment`:return fn(e);default:return{type:`text`,text:d(e)}}})}const pn=250;function mn(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 hn(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 gn(e){return e.subtype!==`success`&&e.errors&&e.errors.length>0?e.errors.join(`
|
|
3
|
-
`):e.subtype===`success`&&e.is_error&&e.result?e.result:e.subtype}function
|
|
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(`
|
|
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};
|
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 f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-BQ64i3DN.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 E(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 v(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 o)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=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(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 y(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 y(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 n(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(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(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 v(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 be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(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,g(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,g(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??g(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 xe=_(`bus:lifecycle`,ue).subjects;function Q(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 Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(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{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){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 Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(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 Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(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{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me 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 f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-BOGcnhgA.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 E(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 v(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 o)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=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(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 y(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 y(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 n(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(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(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 v(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 be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(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,g(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,g(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??g(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 xe=_(`bus:lifecycle`,ue).subjects;function Q(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 Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(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{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){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 Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(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 Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(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{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me as waitForSubscriptionPropagation};
|