@makaio/framework 1.0.0-dev-1789404058608 → 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.
Files changed (117) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/{adapter-C4v_gNTI.mjs → adapter-DSRgsh2d.mjs} +1 -1
  3. package/dist/adapters/claude/index.d.mts +24 -24
  4. package/dist/adapters/claude/index.mjs +3 -3
  5. package/dist/bus/index.mjs +1 -1
  6. package/dist/bus-BOGcnhgA.mjs +9 -0
  7. package/dist/client-DqfP7BeX.mjs +1 -0
  8. package/dist/clients/index.d.mts +152 -11
  9. package/dist/clients/index.mjs +1 -1
  10. package/dist/contracts/adapter/index.d.mts +2 -2
  11. package/dist/contracts/adapter/index.mjs +1 -1
  12. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  13. package/dist/contracts/artifact/index.d.mts +2 -2
  14. package/dist/contracts/capabilities/index.d.mts +1 -1
  15. package/dist/contracts/client/index.d.mts +3 -3
  16. package/dist/contracts/client/index.mjs +1 -1
  17. package/dist/contracts/extension/index.d.mts +4 -4
  18. package/dist/contracts/index.d.mts +35 -35
  19. package/dist/contracts/index.mjs +1 -1
  20. package/dist/contracts/materialization/index.d.mts +1 -1
  21. package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
  22. package/dist/contracts/session/index.d.mts +2 -2
  23. package/dist/contracts/session/index.mjs +1 -1
  24. package/dist/contracts/shared/index.d.mts +1 -1
  25. package/dist/contracts/variant/index.d.mts +1 -1
  26. package/dist/contracts/worker/index.d.mts +1 -1
  27. package/dist/contracts/workflow/index.d.mts +2 -2
  28. package/dist/drizzle/0040_session_generation.sql +1 -0
  29. package/dist/drizzle/meta/_journal.json +7 -0
  30. package/dist/{framework-packages-Bg4edkkM.mjs → framework-packages-BNFG51Td.mjs} +1 -1
  31. package/dist/{hook-responses-Dq16X3Cb.d.mts → hook-responses-CQ2q0aPE.d.mts} +47 -4
  32. package/dist/{index-DaAWCLe9.d.mts → index-B-u0Tu8X.d.mts} +24 -24
  33. package/dist/{index-C1nSuiG0.d.mts → index-B6WkHnCQ.d.mts} +1 -1
  34. package/dist/{index-Du4wUv9q.d.mts → index-BS-Fhlux.d.mts} +48 -13
  35. package/dist/{index-BArnbdj6.d.mts → index-Bh57xARQ.d.mts} +65 -65
  36. package/dist/{index-DH0m01hJ2.d.mts → index-CXpgL3gz2.d.mts} +3 -3
  37. package/dist/{index-n1hV8uFw2.d.mts → index-CdWxSwhQ2.d.mts} +11 -11
  38. package/dist/{index-DjQebquc.d.mts → index-ClKwF6LE.d.mts} +291 -291
  39. package/dist/{index-BUC9P6Q12.d.mts → index-CztxEJrG2.d.mts} +51 -8
  40. package/dist/{index-BEi6nx1S2.d.mts → index-De_oh9M-2.d.mts} +1 -1
  41. package/dist/{index-N3f65Z_S.d.mts → index-Dn23R_ck.d.mts} +9 -9
  42. package/dist/{index-gu4mzfTr.d.mts → index-Hnsy6XhM.d.mts} +1 -1
  43. package/dist/{index-CWlvL7GB.d.mts → index-nkix3hP7.d.mts} +6 -6
  44. package/dist/{index-CGxjX4fw.d.mts → index-p1l00SGS.d.mts} +320 -12
  45. package/dist/{index-T-aAKybB.d.mts → index-xsaaa85T.d.mts} +8 -8
  46. package/dist/{index-HMb0RcTG2.d.mts → index-zEkS2L862.d.mts} +18 -12
  47. package/dist/kernel/extension/index.d.mts +1 -1
  48. package/dist/kernel/index.d.mts +2 -2
  49. package/dist/kernel/observability/index.d.mts +1 -1
  50. package/dist/{namespace-DQpBf2CK.d.mts → namespace-B5IFLQc-.d.mts} +6 -6
  51. package/dist/{namespace-Cmu-5_P9.d.mts → namespace-BR03HE8G.d.mts} +42 -0
  52. package/dist/{namespace-uCaKZm89.d.mts → namespace-BqfzcRkL.d.mts} +3 -3
  53. package/dist/{namespace-CPGTaFqO.d.mts → namespace-Phxf0Lep.d.mts} +2 -2
  54. package/dist/{namespace-D2RZfl0a.d.mts → namespace-UFcDEBJB.d.mts} +2 -2
  55. package/dist/{namespace-DSRoDmT6.d.mts → namespace-rJ3ycPMg.d.mts} +2 -2
  56. package/dist/{orchestrator-shared-CtPB6PAr.mjs → orchestrator-shared-CxO1lfpP.mjs} +1 -1
  57. package/dist/ownership-memory-handler-BOhmmlJj.mjs +1 -0
  58. package/dist/{package-D-oIvXJD.d.mts → package-CDj3F-L3.d.mts} +1 -1
  59. package/dist/package.json +1 -1
  60. package/dist/{registry-DNMjJ-Oj.mjs → registry-DtaRGU8i.mjs} +1 -0
  61. package/dist/{schema-BA1cHBbc.d.mts → schema-DqKCg5Ec.d.mts} +30 -0
  62. package/dist/{schemas-CJKDu4Kt.d.mts → schemas-2_D4iVbb.d.mts} +1 -1
  63. package/dist/{schemas-BQsXr4FF.d.mts → schemas-CFciElld.d.mts} +7 -7
  64. package/dist/{schemas-BcynDWi-.d.mts → schemas-Cj6Gbqch.d.mts} +7 -7
  65. package/dist/schemas-CkxAK13D.mjs +1 -0
  66. package/dist/{schemas-e8o4JGBu.d.mts → schemas-Cq1d5tid.d.mts} +2 -2
  67. package/dist/services/adapter-runtime/index.d.mts +3 -3
  68. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  69. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  70. package/dist/services/agent-runtime/index.d.mts +2 -2
  71. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  72. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  73. package/dist/services/execution-target/index.d.mts +1 -1
  74. package/dist/services/filesystem/namespace.d.mts +6 -6
  75. package/dist/services/filesystem/schemas.d.mts +3 -3
  76. package/dist/services/index.d.mts +28 -28
  77. package/dist/services/index.mjs +1 -1
  78. package/dist/services/session/index.d.mts +4 -4
  79. package/dist/services/session/index.mjs +1 -1
  80. package/dist/services/session/messages/namespace.d.mts +1 -1
  81. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  82. package/dist/services/session/storage/namespace.d.mts +1 -1
  83. package/dist/services/session/storage/schema.d.mts +1 -1
  84. package/dist/services/session/storage/schema.mjs +1 -1
  85. package/dist/services/session/testing/index.mjs +2 -1
  86. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  87. package/dist/services/settings/namespace.d.mts +4 -4
  88. package/dist/services/subagent-template/index.d.mts +2 -2
  89. package/dist/services/subagent-template/namespace.d.mts +1 -1
  90. package/dist/services/subagent-template/schemas.d.mts +1 -1
  91. package/dist/services/tool-approval/index.mjs +1 -1
  92. package/dist/services/tools/index.mjs +1 -1
  93. package/dist/services/tray-menu/index.d.mts +2 -2
  94. package/dist/services/tray-menu/namespace.d.mts +1 -1
  95. package/dist/services/tray-menu/schemas.d.mts +1 -1
  96. package/dist/services/workflow-transitions/index.mjs +1 -1
  97. package/dist/session-BP5aq2kt.mjs +95 -0
  98. package/dist/{session-BB0s7c2B.mjs → session-BcArFp9M.mjs} +1 -1
  99. package/dist/{session-lineage-BQimcKsh.d.mts → session-lineage-C3myyt5x.d.mts} +1 -1
  100. package/dist/storage/drizzle/client.mjs +1 -1
  101. package/dist/storage/drizzle/index.mjs +1 -1
  102. package/dist/{tool-approval-service-pbkGcAV8.mjs → tool-approval-service-CXTklh3T.mjs} +1 -1
  103. package/dist/{tools-C5Gy0IQG.mjs → tools-hiFv-jJn.mjs} +1 -1
  104. package/dist/{transition-JmAdtcwW.d.mts → transition-D-Lgbp1j.d.mts} +1 -1
  105. package/dist/{types-C5MnkQv6.d.mts → types-D5kqrOad.d.mts} +18 -9
  106. package/dist/{view-builder-ByHQ4Oop.d.mts → view-builder-CHUTXJDl.d.mts} +2 -2
  107. package/dist/workflow-engine/index.d.mts +34 -34
  108. package/dist/workflow-engine/package.d.mts +1 -1
  109. package/dist/{workflow-transitions-C0sg3kar.mjs → workflow-transitions-BalNKTtE.mjs} +1 -1
  110. package/package.json +1 -1
  111. package/dist/bus-DlTN167w.mjs +0 -9
  112. package/dist/client-CgtNXGXg.mjs +0 -1
  113. package/dist/ownership-memory-handler-xex7sLiX.mjs +0 -1
  114. package/dist/schemas-ClkcU_N5.mjs +0 -1
  115. package/dist/session-6UG5udTX.mjs +0 -95
  116. package/dist/{index-CCH0Dnty2.d.mts → index-Htfr-K5U2.d.mts} +6 -6
  117. package/dist/{schemas-lAb9QH1A.d.mts → schemas-JjyFxrC0.d.mts} +8 -8
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "fingerprint": "a016f0dbd6bf2815f0ce792c2d723d49c5d125590c7fc89e1af5d100ef17acae",
4
- "builtAt": "2026-09-14T16:42:08.836Z",
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-ClkcU_N5.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
+ 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};
@@ -4993,16 +4993,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
4993
4993
  adapterId: z.ZodString;
4994
4994
  agentId: z.ZodString;
4995
4995
  oldState: z.ZodEnum<{
4996
- paused: "paused";
4997
4996
  idle: "idle";
4997
+ paused: "paused";
4998
4998
  turn_started: "turn_started";
4999
4999
  step_started: "step_started";
5000
5000
  step_finished: "step_finished";
5001
5001
  turn_finished: "turn_finished";
5002
5002
  }>;
5003
5003
  newState: z.ZodEnum<{
5004
- paused: "paused";
5005
5004
  idle: "idle";
5005
+ paused: "paused";
5006
5006
  turn_started: "turn_started";
5007
5007
  step_started: "step_started";
5008
5008
  step_finished: "step_finished";
@@ -5014,16 +5014,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5014
5014
  adapterId: z.ZodString;
5015
5015
  agentId: z.ZodString;
5016
5016
  oldState: z.ZodEnum<{
5017
- paused: "paused";
5018
5017
  idle: "idle";
5018
+ paused: "paused";
5019
5019
  turn_started: "turn_started";
5020
5020
  step_started: "step_started";
5021
5021
  step_finished: "step_finished";
5022
5022
  turn_finished: "turn_finished";
5023
5023
  }>;
5024
5024
  newState: z.ZodEnum<{
5025
- paused: "paused";
5026
5025
  idle: "idle";
5026
+ paused: "paused";
5027
5027
  turn_started: "turn_started";
5028
5028
  step_started: "step_started";
5029
5029
  step_finished: "step_finished";
@@ -5035,16 +5035,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5035
5035
  adapterId: z.ZodString;
5036
5036
  agentId: z.ZodString;
5037
5037
  oldState: z.ZodEnum<{
5038
- paused: "paused";
5039
5038
  idle: "idle";
5039
+ paused: "paused";
5040
5040
  turn_started: "turn_started";
5041
5041
  step_started: "step_started";
5042
5042
  step_finished: "step_finished";
5043
5043
  turn_finished: "turn_finished";
5044
5044
  }>;
5045
5045
  newState: z.ZodEnum<{
5046
- paused: "paused";
5047
5046
  idle: "idle";
5047
+ paused: "paused";
5048
5048
  turn_started: "turn_started";
5049
5049
  step_started: "step_started";
5050
5050
  step_finished: "step_finished";
@@ -5056,16 +5056,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5056
5056
  adapterId: z.ZodString;
5057
5057
  agentId: z.ZodString;
5058
5058
  oldState: z.ZodEnum<{
5059
- paused: "paused";
5060
5059
  idle: "idle";
5060
+ paused: "paused";
5061
5061
  turn_started: "turn_started";
5062
5062
  step_started: "step_started";
5063
5063
  step_finished: "step_finished";
5064
5064
  turn_finished: "turn_finished";
5065
5065
  }>;
5066
5066
  newState: z.ZodEnum<{
5067
- paused: "paused";
5068
5067
  idle: "idle";
5068
+ paused: "paused";
5069
5069
  turn_started: "turn_started";
5070
5070
  step_started: "step_started";
5071
5071
  step_finished: "step_finished";
@@ -5077,16 +5077,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5077
5077
  adapterId: z.ZodString;
5078
5078
  agentId: z.ZodString;
5079
5079
  oldState: z.ZodEnum<{
5080
- paused: "paused";
5081
5080
  idle: "idle";
5081
+ paused: "paused";
5082
5082
  turn_started: "turn_started";
5083
5083
  step_started: "step_started";
5084
5084
  step_finished: "step_finished";
5085
5085
  turn_finished: "turn_finished";
5086
5086
  }>;
5087
5087
  newState: z.ZodEnum<{
5088
- paused: "paused";
5089
5088
  idle: "idle";
5089
+ paused: "paused";
5090
5090
  turn_started: "turn_started";
5091
5091
  step_started: "step_started";
5092
5092
  step_finished: "step_finished";
@@ -5098,16 +5098,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5098
5098
  adapterId: z.ZodString;
5099
5099
  agentId: z.ZodString;
5100
5100
  oldState: z.ZodEnum<{
5101
- paused: "paused";
5102
5101
  idle: "idle";
5102
+ paused: "paused";
5103
5103
  turn_started: "turn_started";
5104
5104
  step_started: "step_started";
5105
5105
  step_finished: "step_finished";
5106
5106
  turn_finished: "turn_finished";
5107
5107
  }>;
5108
5108
  newState: z.ZodEnum<{
5109
- paused: "paused";
5110
5109
  idle: "idle";
5110
+ paused: "paused";
5111
5111
  turn_started: "turn_started";
5112
5112
  step_started: "step_started";
5113
5113
  step_finished: "step_finished";
@@ -7620,16 +7620,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7620
7620
  adapterId: z.ZodString;
7621
7621
  agentId: z.ZodString;
7622
7622
  oldState: z.ZodEnum<{
7623
- paused: "paused";
7624
7623
  idle: "idle";
7624
+ paused: "paused";
7625
7625
  turn_started: "turn_started";
7626
7626
  step_started: "step_started";
7627
7627
  step_finished: "step_finished";
7628
7628
  turn_finished: "turn_finished";
7629
7629
  }>;
7630
7630
  newState: z.ZodEnum<{
7631
- paused: "paused";
7632
7631
  idle: "idle";
7632
+ paused: "paused";
7633
7633
  turn_started: "turn_started";
7634
7634
  step_started: "step_started";
7635
7635
  step_finished: "step_finished";
@@ -7641,16 +7641,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7641
7641
  adapterId: z.ZodString;
7642
7642
  agentId: z.ZodString;
7643
7643
  oldState: z.ZodEnum<{
7644
- paused: "paused";
7645
7644
  idle: "idle";
7645
+ paused: "paused";
7646
7646
  turn_started: "turn_started";
7647
7647
  step_started: "step_started";
7648
7648
  step_finished: "step_finished";
7649
7649
  turn_finished: "turn_finished";
7650
7650
  }>;
7651
7651
  newState: z.ZodEnum<{
7652
- paused: "paused";
7653
7652
  idle: "idle";
7653
+ paused: "paused";
7654
7654
  turn_started: "turn_started";
7655
7655
  step_started: "step_started";
7656
7656
  step_finished: "step_finished";
@@ -7662,16 +7662,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7662
7662
  adapterId: z.ZodString;
7663
7663
  agentId: z.ZodString;
7664
7664
  oldState: z.ZodEnum<{
7665
- paused: "paused";
7666
7665
  idle: "idle";
7666
+ paused: "paused";
7667
7667
  turn_started: "turn_started";
7668
7668
  step_started: "step_started";
7669
7669
  step_finished: "step_finished";
7670
7670
  turn_finished: "turn_finished";
7671
7671
  }>;
7672
7672
  newState: z.ZodEnum<{
7673
- paused: "paused";
7674
7673
  idle: "idle";
7674
+ paused: "paused";
7675
7675
  turn_started: "turn_started";
7676
7676
  step_started: "step_started";
7677
7677
  step_finished: "step_finished";
@@ -7683,16 +7683,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7683
7683
  adapterId: z.ZodString;
7684
7684
  agentId: z.ZodString;
7685
7685
  oldState: z.ZodEnum<{
7686
- paused: "paused";
7687
7686
  idle: "idle";
7687
+ paused: "paused";
7688
7688
  turn_started: "turn_started";
7689
7689
  step_started: "step_started";
7690
7690
  step_finished: "step_finished";
7691
7691
  turn_finished: "turn_finished";
7692
7692
  }>;
7693
7693
  newState: z.ZodEnum<{
7694
- paused: "paused";
7695
7694
  idle: "idle";
7695
+ paused: "paused";
7696
7696
  turn_started: "turn_started";
7697
7697
  step_started: "step_started";
7698
7698
  step_finished: "step_finished";
@@ -7704,16 +7704,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7704
7704
  adapterId: z.ZodString;
7705
7705
  agentId: z.ZodString;
7706
7706
  oldState: z.ZodEnum<{
7707
- paused: "paused";
7708
7707
  idle: "idle";
7708
+ paused: "paused";
7709
7709
  turn_started: "turn_started";
7710
7710
  step_started: "step_started";
7711
7711
  step_finished: "step_finished";
7712
7712
  turn_finished: "turn_finished";
7713
7713
  }>;
7714
7714
  newState: z.ZodEnum<{
7715
- paused: "paused";
7716
7715
  idle: "idle";
7716
+ paused: "paused";
7717
7717
  turn_started: "turn_started";
7718
7718
  step_started: "step_started";
7719
7719
  step_finished: "step_finished";
@@ -7725,16 +7725,16 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
7725
7725
  adapterId: z.ZodString;
7726
7726
  agentId: z.ZodString;
7727
7727
  oldState: z.ZodEnum<{
7728
- paused: "paused";
7729
7728
  idle: "idle";
7729
+ paused: "paused";
7730
7730
  turn_started: "turn_started";
7731
7731
  step_started: "step_started";
7732
7732
  step_finished: "step_finished";
7733
7733
  turn_finished: "turn_finished";
7734
7734
  }>;
7735
7735
  newState: z.ZodEnum<{
7736
- paused: "paused";
7737
7736
  idle: "idle";
7737
+ paused: "paused";
7738
7738
  turn_started: "turn_started";
7739
7739
  step_started: "step_started";
7740
7740
  step_finished: "step_finished";
@@ -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 te,BaseConnectorTurn as ne,ScopedToolApprovalSchema as re,createAdapterNamespace as ie,createToolApprovalHandler as ae,defineDiscriminatedHandlers as oe,formatContextBlockAsText as se,isTextLikeMimeType as ce,mergeScopedToolApproval as l,normalizeMimeType as u,processDiscriminatedItems as le,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 ue(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 ae(t.can_use_tool,p,e=>e)(e,n,r)}async function de(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=oe(`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 fe(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 pe(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)+e.output_tokens}async function me(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(!he(n))continue;let r=n.tool_use_id,i=ge(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 he(e){return typeof e==`object`&&!!e&&e.type===`tool_result`}function ge(e){return typeof e==`string`?e:[e?.stdout,e?.stderr].filter(Boolean).join(`
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`},{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:`SubagentStop`},{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 _n(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 vn(e){let t=e.subtype===`success`&&e.is_error,n=gn(e);return hn(e.subtype,n,e.result)||(t&&typeof e.result==`string`?_n(e.result)||e.result:n)}function yn(e,t,n){let r={type:`text`,text:se(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 bn(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 xn(e){return`structured_output`in e&&e.structured_output!==void 0?JSON.stringify(e.structured_output):e.result??``}function Sn(e,t){return e}export{ye as AsyncQuerySource,h as CONTENT_BLOCK_HANDLERS,ve as ClaudeCodeAgent,be as ClaudeConnectorTurn,B as SDKMessageSchema,pn as TERMINAL_RESULT_DRAIN_TIMEOUT_MS,$ as blocksToContentBlocks,tn as claudeReasoningLevels,ln as createClaudeConnectorNamespace,Y as decodeBase64Text,mn as extractTextFromMessage,ue as fromGlobalToolApproval,vn as parseResultError,yn as prependContextBlock,m as registerToolApprovalHandler,de as requestToolApproval,xn as resolveResultMessage,bn as sdkUserMessageFromNormalized,p as toGlobalToolApproval,Sn as unwrapBlockFromMessage};
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};
@@ -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-DlTN167w.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};