@cursor/bdk 0.2.12 → 0.2.13

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 (152) hide show
  1. package/dist/channels/github/index.d.ts +22 -12
  2. package/dist/channels/github/index.d.ts.map +1 -1
  3. package/dist/channels/github/index.js +11 -12
  4. package/dist/channels/origin/index.d.ts +21 -11
  5. package/dist/channels/origin/index.d.ts.map +1 -1
  6. package/dist/channels/origin/index.js +10 -11
  7. package/dist/docs/404.html +2 -2
  8. package/dist/docs/assets/{app.CKta5zX1.js → app.CaLG1pPt.js} +4 -4
  9. package/dist/docs/assets/chunks/{@localSearchIndexroot.DtlCe4t6.js → @localSearchIndexroot.DvlKuIO-.js} +1 -1
  10. package/dist/docs/assets/chunks/{VPLocalSearchBox.4vRM3EDG.js → VPLocalSearchBox.YsP_2wqD.js} +1 -1
  11. package/dist/docs/assets/chunks/{arc.CofbA8tA.js → arc.C2j9hR7c.js} +1 -1
  12. package/dist/docs/assets/chunks/{architectureDiagram-Q4EWVU46.Mt2UV5M-.js → architectureDiagram-Q4EWVU46.C5qkGp7y.js} +1 -1
  13. package/dist/docs/assets/chunks/{baseUniq.C_W0Aqp4.js → baseUniq.U6GgTHOD.js} +1 -1
  14. package/dist/docs/assets/chunks/{blockDiagram-DXYQGD6D.dAc4goE-.js → blockDiagram-DXYQGD6D.D51mJop2.js} +1 -1
  15. package/dist/docs/assets/chunks/{c4Diagram-AHTNJAMY.dnbRC3Dm.js → c4Diagram-AHTNJAMY.w1d6QxV7.js} +1 -1
  16. package/dist/docs/assets/chunks/channel.BRSFxCcD.js +1 -0
  17. package/dist/docs/assets/chunks/{chunk-4BX2VUAB.B42ltSTd.js → chunk-4BX2VUAB.B_A815un.js} +1 -1
  18. package/dist/docs/assets/chunks/{chunk-4TB4RGXK.2GbAul_E.js → chunk-4TB4RGXK.DMrm-ZCb.js} +1 -1
  19. package/dist/docs/assets/chunks/{chunk-55IACEB6.pjzY-v-B.js → chunk-55IACEB6.8qw6Xdal.js} +1 -1
  20. package/dist/docs/assets/chunks/{chunk-EDXVE4YY.BB1GXLj2.js → chunk-EDXVE4YY.Cq_nHODn.js} +1 -1
  21. package/dist/docs/assets/chunks/{chunk-FMBD7UC4.B2WxZkoA.js → chunk-FMBD7UC4.B67ohCYn.js} +1 -1
  22. package/dist/docs/assets/chunks/{chunk-OYMX7WX6.BMvb2w73.js → chunk-OYMX7WX6.Bo8rQI8F.js} +1 -1
  23. package/dist/docs/assets/chunks/{chunk-QZHKN3VN.Bmu_2lNr.js → chunk-QZHKN3VN.BERUMfE9.js} +1 -1
  24. package/dist/docs/assets/chunks/{chunk-YZCP3GAM.Cth65EaC.js → chunk-YZCP3GAM.DWG2tXIX.js} +1 -1
  25. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.Cmtm6WkN.js +1 -0
  26. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.Cmtm6WkN.js +1 -0
  27. package/dist/docs/assets/chunks/clone.JMC96Eo6.js +1 -0
  28. package/dist/docs/assets/chunks/{cose-bilkent-S5V4N54A.CrfA7Iw_.js → cose-bilkent-S5V4N54A.tezXBs9b.js} +1 -1
  29. package/dist/docs/assets/chunks/{dagre-KV5264BT.PCD6KQDb.js → dagre-KV5264BT.aSbEUwT7.js} +1 -1
  30. package/dist/docs/assets/chunks/{diagram-5BDNPKRD.CGNlYlP1.js → diagram-5BDNPKRD.vnT6aJ57.js} +1 -1
  31. package/dist/docs/assets/chunks/{diagram-G4DWMVQ6.C0cvryPD.js → diagram-G4DWMVQ6.hGYdrDa2.js} +1 -1
  32. package/dist/docs/assets/chunks/{diagram-MMDJMWI5.DHlkZHNV.js → diagram-MMDJMWI5.CmdSUP6L.js} +1 -1
  33. package/dist/docs/assets/chunks/{diagram-TYMM5635.DDGqH_4B.js → diagram-TYMM5635.BbAnLEBB.js} +1 -1
  34. package/dist/docs/assets/chunks/{erDiagram-SMLLAGMA.4gOY_C3v.js → erDiagram-SMLLAGMA.H40W4HWE.js} +1 -1
  35. package/dist/docs/assets/chunks/{flowDiagram-DWJPFMVM.8i7zsxuh.js → flowDiagram-DWJPFMVM.BFMtUSv-.js} +1 -1
  36. package/dist/docs/assets/chunks/{ganttDiagram-T4ZO3ILL.BEKHYdM-.js → ganttDiagram-T4ZO3ILL.CbYiu7Dt.js} +1 -1
  37. package/dist/docs/assets/chunks/{gitGraphDiagram-UUTBAWPF.ACzeLGiB.js → gitGraphDiagram-UUTBAWPF.Cyc5mzZD.js} +1 -1
  38. package/dist/docs/assets/chunks/{graph.08C3hS6m.js → graph.BRptDG1H.js} +1 -1
  39. package/dist/docs/assets/chunks/{infoDiagram-42DDH7IO.D8R9obOH.js → infoDiagram-42DDH7IO.Bz6KCA3a.js} +1 -1
  40. package/dist/docs/assets/chunks/{ishikawaDiagram-UXIWVN3A.CmgYpCWL.js → ishikawaDiagram-UXIWVN3A.DDJ_7_Fq.js} +1 -1
  41. package/dist/docs/assets/chunks/{journeyDiagram-VCZTEJTY.DUzjGfoZ.js → journeyDiagram-VCZTEJTY.D0t_ltlb.js} +1 -1
  42. package/dist/docs/assets/chunks/{kanban-definition-6JOO6SKY.DbcW2iZ0.js → kanban-definition-6JOO6SKY.DyyNsMfi.js} +1 -1
  43. package/dist/docs/assets/chunks/{layout.BaDEpJzu.js → layout.Cbxq-Rhp.js} +1 -1
  44. package/dist/docs/assets/chunks/{linear.B_zRQgCU.js → linear.DxGYL0MP.js} +1 -1
  45. package/dist/docs/assets/chunks/{min.BYscCdSu.js → min.DA5KL8wu.js} +1 -1
  46. package/dist/docs/assets/chunks/{mindmap-definition-QFDTVHPH.Ggu0jg86.js → mindmap-definition-QFDTVHPH.Bc72Utls.js} +1 -1
  47. package/dist/docs/assets/chunks/{pieDiagram-DEJITSTG.D_q4SVDT.js → pieDiagram-DEJITSTG.BtpHnIB_.js} +1 -1
  48. package/dist/docs/assets/chunks/{quadrantDiagram-34T5L4WZ.D3zGj5ok.js → quadrantDiagram-34T5L4WZ.Cx4oCSRR.js} +1 -1
  49. package/dist/docs/assets/chunks/{requirementDiagram-MS252O5E.DVTg7zr2.js → requirementDiagram-MS252O5E.BC0hXWlW.js} +1 -1
  50. package/dist/docs/assets/chunks/{sankeyDiagram-XADWPNL6.D3X8jm57.js → sankeyDiagram-XADWPNL6.Dg8T1SEp.js} +1 -1
  51. package/dist/docs/assets/chunks/{sequenceDiagram-FGHM5R23.Dpjai9YP.js → sequenceDiagram-FGHM5R23.CWSdHYAF.js} +1 -1
  52. package/dist/docs/assets/chunks/{stateDiagram-FHFEXIEX.D_AbQBuP.js → stateDiagram-FHFEXIEX.0MVPRI28.js} +1 -1
  53. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.N4Am6sXd.js +1 -0
  54. package/dist/docs/assets/chunks/{theme.BcgOnbZ6.js → theme.DO1avLBn.js} +2 -2
  55. package/dist/docs/assets/chunks/{timeline-definition-GMOUNBTQ.Cp3DKBe2.js → timeline-definition-GMOUNBTQ.BuRinAVi.js} +1 -1
  56. package/dist/docs/assets/chunks/{vennDiagram-DHZGUBPP.Bcvg-Aqu.js → vennDiagram-DHZGUBPP.DXf0PCoJ.js} +1 -1
  57. package/dist/docs/assets/chunks/{wardley-RL74JXVD.CCpdcUSq.js → wardley-RL74JXVD._eATmGtu.js} +1 -1
  58. package/dist/docs/assets/chunks/{wardleyDiagram-NUSXRM2D.L0yehCc5.js → wardleyDiagram-NUSXRM2D.T4ThngYV.js} +1 -1
  59. package/dist/docs/assets/chunks/{xychartDiagram-5P7HB3ND.Cw8-tJmw.js → xychartDiagram-5P7HB3ND.b4pZF3D5.js} +1 -1
  60. package/dist/docs/assets/{reference_skills.md.ClkMoQsV.js → reference_skills.md.C0guGcH0.js} +3 -3
  61. package/dist/docs/building-with-agents.html +35 -35
  62. package/dist/docs/deployment.html +35 -35
  63. package/dist/docs/evals.html +35 -35
  64. package/dist/docs/guides/agent-to-agent.html +35 -35
  65. package/dist/docs/guides/bitbucket.html +35 -35
  66. package/dist/docs/guides/cloud-agents.html +35 -35
  67. package/dist/docs/guides/convert-automation.html +35 -35
  68. package/dist/docs/guides/github.html +35 -35
  69. package/dist/docs/guides/gitlab.html +35 -35
  70. package/dist/docs/guides/grokbot-agents.html +35 -35
  71. package/dist/docs/guides/hooks.html +35 -35
  72. package/dist/docs/guides/improve.html +35 -35
  73. package/dist/docs/guides/jev.html +35 -35
  74. package/dist/docs/guides/mcp-oauth.html +35 -35
  75. package/dist/docs/guides/migrate.html +35 -35
  76. package/dist/docs/guides/opentelemetry.html +35 -35
  77. package/dist/docs/guides/slack.html +35 -35
  78. package/dist/docs/guides/webhooks.html +35 -35
  79. package/dist/docs/hashmap.json +1 -1
  80. package/dist/docs/hillclimbing.html +35 -35
  81. package/dist/docs/index.html +35 -35
  82. package/dist/docs/quickstart.html +35 -35
  83. package/dist/docs/reference/agent-config.html +35 -35
  84. package/dist/docs/reference/artifacts.html +35 -35
  85. package/dist/docs/reference/channels.html +35 -35
  86. package/dist/docs/reference/cli.html +35 -35
  87. package/dist/docs/reference/connections.html +35 -35
  88. package/dist/docs/reference/evals.html +35 -35
  89. package/dist/docs/reference/extensions.html +35 -35
  90. package/dist/docs/reference/hooks.html +35 -35
  91. package/dist/docs/reference/http-api.html +35 -35
  92. package/dist/docs/reference/instructions.html +35 -35
  93. package/dist/docs/reference/playground.html +35 -35
  94. package/dist/docs/reference/project-layout.html +35 -35
  95. package/dist/docs/reference/prompt.html +35 -35
  96. package/dist/docs/reference/schedules.html +35 -35
  97. package/dist/docs/reference/sessions.html +35 -35
  98. package/dist/docs/reference/skills.html +38 -38
  99. package/dist/docs/reference/subagents.html +35 -35
  100. package/dist/docs/reference/tools.html +35 -35
  101. package/dist/docs/templates/agentic-owners.html +35 -35
  102. package/dist/docs/templates/grokbot-agents.html +35 -35
  103. package/dist/docs/templates/security-reviewer.html +35 -35
  104. package/dist/docs/templates/thermo-quality-review.html +35 -35
  105. package/dist/docs/templates/thermo-review.html +35 -35
  106. package/dist/docs/templates/triage.html +35 -35
  107. package/dist/docs/troubleshooting.html +35 -35
  108. package/dist/internal/authored-alias-hooks.d.ts +4 -3
  109. package/dist/internal/authored-alias-hooks.d.ts.map +1 -1
  110. package/dist/internal/authored-alias-hooks.js +15 -6
  111. package/dist/internal/authored-loaders.d.ts.map +1 -1
  112. package/dist/internal/authored-loaders.js +21 -5
  113. package/dist/internal/deploy-manifest.d.ts +14 -0
  114. package/dist/internal/deploy-manifest.d.ts.map +1 -1
  115. package/dist/internal/deploy-manifest.js +23 -0
  116. package/dist/internal/evals-client.d.ts.map +1 -1
  117. package/dist/internal/hosted-delivery-protocol.d.ts +24 -0
  118. package/dist/internal/hosted-delivery-protocol.d.ts.map +1 -1
  119. package/dist/internal/hosted-delivery-protocol.js +44 -0
  120. package/dist/internal/hosted-delivery.d.ts +6 -0
  121. package/dist/internal/hosted-delivery.d.ts.map +1 -1
  122. package/dist/internal/hosted-delivery.js +41 -4
  123. package/dist/internal/hosted-managed-automation.d.ts +3 -3
  124. package/dist/internal/hosted-managed-automation.js +3 -3
  125. package/dist/internal/reminder-runner.d.ts.map +1 -1
  126. package/dist/internal/schedule-runner.d.ts +13 -2
  127. package/dist/internal/schedule-runner.d.ts.map +1 -1
  128. package/dist/internal/schedule-runner.js +42 -3
  129. package/dist/internal/sdk-runner.d.ts +2 -1
  130. package/dist/internal/sdk-runner.d.ts.map +1 -1
  131. package/dist/internal/sdk-runner.js +7 -2
  132. package/dist/internal/server.d.ts.map +1 -1
  133. package/dist/internal/server.js +8 -4
  134. package/dist/internal/session-live-publisher.d.ts +4 -2
  135. package/dist/internal/session-live-publisher.d.ts.map +1 -1
  136. package/dist/internal/session-live-publisher.js +73 -10
  137. package/dist/internal/testing/conversation-identity-vectors.d.ts +48 -0
  138. package/dist/internal/testing/conversation-identity-vectors.d.ts.map +1 -0
  139. package/dist/internal/testing/conversation-identity-vectors.js +136 -0
  140. package/dist/playground/assets/index-CzttDc-d.css +1 -0
  141. package/dist/playground/assets/{index-HN5lOuAX.js → index-DIiKbZ25.js} +2 -2
  142. package/dist/playground/index.html +2 -2
  143. package/dist/types.d.ts +6 -4
  144. package/dist/types.d.ts.map +1 -1
  145. package/package.json +1 -1
  146. package/dist/docs/assets/chunks/channel.DpljPUVU.js +0 -1
  147. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.DFNHq2OM.js +0 -1
  148. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.DFNHq2OM.js +0 -1
  149. package/dist/docs/assets/chunks/clone.DssygCzX.js +0 -1
  150. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CWKWRxRx.js +0 -1
  151. package/dist/playground/assets/index-JY1wKCMg.css +0 -1
  152. /package/dist/docs/assets/{reference_skills.md.ClkMoQsV.lean.js → reference_skills.md.C0guGcH0.lean.js} +0 -0
@@ -14,11 +14,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
14
14
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LH(e,t){if(e){if(typeof e=="string")return GT(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?GT(e,t):void 0}}function GT(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function jH(e,t){for(var n=DH(e),r;!(r=n()).done;){var s=r.value;if(t(s))return s;for(var a=s.split("-");a.length>1;)if(a.pop(),s=a.join("-"),t(s))return s}throw new Error("No locale data has been registered for any of the locales: ".concat(e.join(", ")))}function zH(){var e=(typeof Intl>"u"?"undefined":sv(Intl))==="object";return e&&typeof Intl.DateTimeFormat=="function"}function ov(e){"@babel/helpers - typeof";return ov=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ov(e)}function PH(e){return BH(e)&&(Array.isArray(e.steps)||Array.isArray(e.gradation)||Array.isArray(e.flavour)||typeof e.flavour=="string"||Array.isArray(e.labels)||typeof e.labels=="string"||Array.isArray(e.units)||typeof e.custom=="function")}var $H={}.constructor;function BH(e){return ov(e)!==void 0&&e!==null&&e.constructor===$H}var ks=60,rh=60*ks,ia=24*rh,av=7*ia,lv=30.44*ia,FI=146097/400*ia;function kl(e){switch(e){case"second":return 1;case"minute":return ks;case"hour":return rh;case"day":return ia;case"week":return av;case"month":return lv;case"year":return FI}}function UI(e){return e.factor!==void 0?e.factor:kl(e.unit||e.formatAs)||1}function Oc(e){return e==="floor"?Math.floor:Math.round}function u0(e){return e==="floor"?1:.5}function uv(e){"@babel/helpers - typeof";return uv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},uv(e)}function qI(e,t){var n=t.prevStep,r=t.timestamp,s=t.now,a=t.future,l=t.round,c;return n&&(n.id||n.unit)&&(c=e["threshold_for_".concat(n.id||n.unit)]),c===void 0&&e.threshold!==void 0&&(c=e.threshold,typeof c=="function"&&(c=c(s,a))),c===void 0&&(c=e.minTime),uv(c)==="object"&&(n&&n.id&&c[n.id]!==void 0?c=c[n.id]:c=c.default),typeof c=="function"&&(c=c(r,{future:a,getMinTimeForUnit:function(d,h){return WT(d,h||n&&n.formatAs,{round:l})}})),c===void 0&&e.test&&(e.test(r,{now:s,future:a})?c=0:c=9007199254740991),c===void 0&&(n?e.formatAs&&n.formatAs&&(c=WT(e.formatAs,n.formatAs,{round:l})):c=0),c===void 0&&console.warn("[javascript-time-ago] A step should specify `minTime`:\n"+JSON.stringify(e,null,2)),c}function WT(e,t,n){var r=n.round,s=kl(e),a=kl(t==="now"?e:t);if(s!==void 0&&a!==void 0)return s-a*(1-u0(r))}function Ic(e){"@babel/helpers - typeof";return Ic=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ic(e)}function KT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function FH(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?KT(Object(n),!0).forEach(function(r){UH(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):KT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function UH(e,t,n){return(t=qH(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qH(e){var t=HH(e,"string");return Ic(t)=="symbol"?t:t+""}function HH(e,t){if(Ic(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Ic(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function VH(e,t,n){var r=n.now,s=n.future,a=n.round,l=n.units;e=WH(e,l);var c=GH(e,t,{now:r,future:s,round:a});{if(c){var f=e[e.indexOf(c)-1],d=e[e.indexOf(c)+1];return[f,c,d]}return[void 0,void 0,e[0]]}}function GH(e,t,n){var r=n.now,s=n.future,a=n.round;if(e.length!==0){var l=HI(e,t,{now:r,future:s||t<0,round:a});if(l!==-1){var c=e[l];if(c.granularity){var f=Oc(a)(Math.abs(t)/UI(c)/c.granularity)*c.granularity;if(f===0&&l>0)return e[l-1]}return c}}}function HI(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=qI(e[r],FH({prevStep:e[r-1],timestamp:n.now-t*1e3},n));return s===void 0||Math.abs(t)<s?r-1:r===e.length-1?r:HI(e,t,n,r+1)}function WH(e,t){return e.filter(function(n){var r=n.unit,s=n.formatAs;return r=r||s,r?t.indexOf(r)>=0:!0})}function KH(e,t,n){var r=n.now,s=n.round;if(kl(e)){var a=kl(e)*1e3,l=t>r,c=Math.abs(t-r),f=Oc(s)(c/a)*a;return l?f>0?c-f+XH(s,a):c-f+1:-(c-f)+YH(s,a)}}function YH(e,t){return u0(e)*t}function XH(e,t){return(1-u0(e))*t+1}var ZH=365*24*60*60*1e3,VI=1e3*ZH;function QH(e,t,n){var r=n.prevStep,s=n.nextStep,a=n.now,l=n.future,c=n.round,f=e.getTime?e.getTime():e,d=function(k){return KH(k,f,{now:a,round:c})},h=eV(l?t:s,f,{future:l,now:a,round:c,prevStep:l?r:t});if(h!==void 0){var m;if(t&&(t.getTimeToNextUpdate&&(m=t.getTimeToNextUpdate(f,{getTimeToNextUpdateForUnit:d,getRoundFunction:Oc,now:a,future:l,round:c})),m===void 0)){var b=t.unit||t.formatAs;b&&(m=d(b))}return m===void 0?h:Math.min(m,h)}}function JH(e,t,n){var r=n.now,s=n.future,a=n.round,l=n.prevStep,c=qI(e,{timestamp:t,now:r,future:s,round:a,prevStep:l});if(c!==void 0)return s?t-c*1e3+1:c===0&&t===r?VI:t+c*1e3}function eV(e,t,n){var r=n.now,s=n.future,a=n.round,l=n.prevStep;if(e){var c=JH(e,t,{now:r,future:s,round:a,prevStep:l});return c===void 0?void 0:c-r}else return s?t-r+1:VI}var GI={};function gl(e){return GI[e]}function WI(e){if(!e)throw new Error("[javascript-time-ago] No locale data passed.");GI[e.locale]=e}const tV=[{formatAs:"now"},{formatAs:"second"},{formatAs:"minute"},{formatAs:"hour"},{formatAs:"day"},{formatAs:"week"},{formatAs:"month"},{formatAs:"year"}],cv={steps:tV,labels:"long"};function Mc(e){"@babel/helpers - typeof";return Mc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mc(e)}function YT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function XT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?YT(Object(n),!0).forEach(function(r){nV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):YT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function nV(e,t,n){return(t=rV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rV(e){var t=iV(e,"string");return Mc(t)=="symbol"?t:t+""}function iV(e,t){if(Mc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Mc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const fv=XT(XT({},cv),{},{steps:cv.steps.filter(function(e){return e.formatAs!=="second"})}),KI=[{factor:1,unit:"now"},{threshold:1,threshold_for_now:45.5,factor:1,unit:"second"},{threshold:45.5,factor:ks,unit:"minute"},{threshold:2.5*ks,granularity:5,factor:ks,unit:"minute"},{threshold:22.5*ks,factor:.5*rh,unit:"half-hour"},{threshold:42.5*ks,threshold_for_minute:52.5*ks,factor:rh,unit:"hour"},{threshold:20.5/24*ia,factor:ia,unit:"day"},{threshold:5.5*ia,factor:av,unit:"week"},{threshold:3.5*av,factor:lv,unit:"month"},{threshold:10.5*lv,factor:FI,unit:"year"}],ZT={gradation:KI,flavour:"long",units:["now","minute","hour","day","week","month","year"]},sV={gradation:KI,flavour:"long-time",units:["now","minute","hour","day","week","month","year"]};function YI(e){return e instanceof Date?e:new Date(e)}var dv=[{formatAs:"second"},{formatAs:"minute"},{formatAs:"hour"}],qi={},oV={minTime:function(t,n){n.future;var r=n.getMinTimeForUnit;return r("day")},format:function(t,n){return qi[n]||(qi[n]={}),qi[n].dayMonth||(qi[n].dayMonth=new Intl.DateTimeFormat(n,{month:"short",day:"numeric"})),qi[n].dayMonth.format(YI(t))}},aV={minTime:function(t,n){var r=n.future;if(r){var s=new Date(new Date(t).getFullYear(),0).getTime()-1;return(t-s)/1e3}else{var a=new Date(new Date(t).getFullYear()+1,0).getTime();return(a-t)/1e3}},format:function(t,n){return qi[n]||(qi[n]={}),qi[n].dayMonthYear||(qi[n].dayMonthYear=new Intl.DateTimeFormat(n,{year:"numeric",month:"short",day:"numeric"})),qi[n].dayMonthYear.format(YI(t))}};zH()?dv.push(oV,aV):dv.push({formatAs:"day"},{formatAs:"week"},{formatAs:"month"},{formatAs:"year"});const fa={steps:dv,labels:["mini","short-time","narrow","short"]};function Dc(e){"@babel/helpers - typeof";return Dc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dc(e)}function QT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function JT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?QT(Object(n),!0).forEach(function(r){lV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):QT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function lV(e,t,n){return(t=uV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function uV(e){var t=cV(e,"string");return Dc(t)=="symbol"?t:t+""}function cV(e,t){if(Dc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Dc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const fV=JT(JT({},fa),{},{steps:[{formatAs:"now"}].concat(fa.steps)});function Lc(e){"@babel/helpers - typeof";return Lc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lc(e)}function eR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function tR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?eR(Object(n),!0).forEach(function(r){dV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):eR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function dV(e,t,n){return(t=pV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function pV(e){var t=hV(e,"string");return Lc(t)=="symbol"?t:t+""}function hV(e,t){if(Lc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Lc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const pv=tR(tR({},fa),{},{steps:fa.steps.filter(function(e){return e.formatAs!=="second"})});function jc(e){"@babel/helpers - typeof";return jc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},jc(e)}function nR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function rR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?nR(Object(n),!0).forEach(function(r){mV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function mV(e,t,n){return(t=gV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function gV(e){var t=bV(e,"string");return jc(t)=="symbol"?t:t+""}function bV(e,t){if(jc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(jc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const yV=rR(rR({},pv),{},{steps:[{formatAs:"now"}].concat(pv.steps)});function zc(e){"@babel/helpers - typeof";return zc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zc(e)}function iR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function Jd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?iR(Object(n),!0).forEach(function(r){vV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function vV(e,t,n){return(t=xV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xV(e){var t=kV(e,"string");return zc(t)=="symbol"?t:t+""}function kV(e,t){if(zc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(zc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const SV=Jd(Jd({},fa),{},{steps:fa.steps.filter(function(e){return e.formatAs!=="second"}).map(function(e){return e.formatAs==="minute"?Jd(Jd({},e),{},{minTime:ks}):e})}),Pc={steps:[{formatAs:"second"},{formatAs:"minute"},{formatAs:"hour"},{formatAs:"day"},{formatAs:"month"},{formatAs:"year"}],labels:["mini","short-time","narrow","short"]};function $c(e){"@babel/helpers - typeof";return $c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$c(e)}function sR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function oR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sR(Object(n),!0).forEach(function(r){wV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function wV(e,t,n){return(t=EV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function EV(e){var t=TV(e,"string");return $c(t)=="symbol"?t:t+""}function TV(e,t){if($c(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if($c(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const RV=oR(oR({},Pc),{},{steps:[{formatAs:"now"}].concat(Pc.steps)});function Bc(e){"@babel/helpers - typeof";return Bc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bc(e)}function aR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function lR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?aR(Object(n),!0).forEach(function(r){CV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function CV(e,t,n){return(t=_V(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _V(e){var t=AV(e,"string");return Bc(t)=="symbol"?t:t+""}function AV(e,t){if(Bc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Bc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const hv=lR(lR({},Pc),{},{steps:Pc.steps.filter(function(e){return e.formatAs!=="second"})});function Fc(e){"@babel/helpers - typeof";return Fc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fc(e)}function uR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function cR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?uR(Object(n),!0).forEach(function(r){NV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):uR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function NV(e,t,n){return(t=OV(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function OV(e){var t=IV(e,"string");return Fc(t)=="symbol"?t:t+""}function IV(e,t){if(Fc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Fc(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}const MV=cR(cR({},hv),{},{steps:[{formatAs:"now"}].concat(hv.steps)});function DV(e){switch(e){case"default":case"round":return cv;case"round-minute":return fv;case"approximate":return ZT;case"time":case"approximate-time":return sV;case"mini":return Pc;case"mini-now":return RV;case"mini-minute":return hv;case"mini-minute-now":return MV;case"twitter":return fa;case"twitter-now":return fV;case"twitter-minute":return pv;case"twitter-minute-now":return yV;case"twitter-first-minute":return SV;default:return ZT}}function da(e){"@babel/helpers - typeof";return da=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},da(e)}function LV(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=XI(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
15
15
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jV(e,t){return $V(e)||PV(e,t)||XI(e,t)||zV()}function zV(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
16
16
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function XI(e,t){if(e){if(typeof e=="string")return fR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?fR(e,t):void 0}}function fR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function PV(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,a,l,c=[],f=!0,d=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(f=(r=a.call(n)).done)&&(c.push(r.value),c.length!==t);f=!0);}catch(h){d=!0,s=h}finally{try{if(!f&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(d)throw s}}return c}}function $V(e){if(Array.isArray(e))return e}function BV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function FV(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,qV(r.key),r)}}function UV(e,t,n){return t&&FV(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function qV(e){var t=HV(e,"string");return da(t)=="symbol"?t:t+""}function HV(e,t){if(da(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(da(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var jr=(function(){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n.polyfill;BV(this,e),typeof t=="string"&&(t=[t]),this.locale=jH(t.concat(e.getDefaultLocale()),gl),typeof Intl<"u"&&Intl.NumberFormat&&(this.numberFormat=new Intl.NumberFormat(this.locale)),r===!1?(this.IntlRelativeTimeFormat=Intl.RelativeTimeFormat,this.IntlPluralRules=Intl.PluralRules):(this.IntlRelativeTimeFormat=Ns,this.IntlPluralRules=Ns.PluralRules),this.relativeTimeFormatCache=new VT,this.pluralRulesCache=new VT}return UV(e,[{key:"format",value:function(n,r,s){var a=this;s||(r&&!YV(r)?(s=r,r=void 0):s={}),r||(r=fv),typeof r=="string"&&(r=DV(r));var l=VV(n),c=this.getLabels(r.flavour||r.labels),f=c.labels,d=c.labelsType,h=s.round||r.round,m,b=Date.now();r.now!==void 0&&(m=r.now),m===void 0&&s.now!==void 0&&(m=s.now),m===void 0&&(m=b);var y=function(A){var I=A.now,P=(I-l)/1e3,$=s.future||P<0,O=KV(f,gl(a.locale).now,gl(a.locale).long,$);if(r.custom){var Y=r.custom({now:I,date:new Date(l),time:l,elapsed:P,locale:a.locale});if(Y!==void 0)return{getText:function(){return Y},getTextRefreshDelay:function(){throw new Error('`getTimeToNextUpdate: true` feature is not supported by legacy "styles" that have a `custom` function')}}}var U=WV(r.units,f,O),B=VH(r.gradation||r.steps||fv.steps,P,{now:I,units:U,round:h,future:$}),j=jV(B,3),q=j[0],H=j[1],W=j[2],F=function(){return a.formatDateForStep(l,H,P,{labels:f,labelsType:d,nowLabel:O,now:I,future:$,round:h})||""},K=function(){var z=QH(l,H,{nextStep:W,prevStep:q,now:I,future:$,round:h});if(typeof z=="number")return s.getTimeToNextUpdateUncapped?z:QI(z)};return{getText:F,getTextRefreshDelay:K}},k=y({now:m}),S=k.getText,R=k.getTextRefreshDelay;if(s.getTimeToNextUpdate)return[S(),R()];if(s.refresh){var E=6e4,T,C=function D(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E;T=XV(function(){var I=y({now:m+(Date.now()-b)}),P=I.getText,$=I.getTextRefreshDelay;s.refresh(P()),D($())},A)};C(R());var _=function(){clearTimeout(T)};return[S(),_]}return S()}},{key:"formatDateForStep",value:function(n,r,s,a){var l=this,c=a.labels,f=a.labelsType,d=a.nowLabel,h=a.now,m=a.future,b=a.round;if(r){if(r.format)return r.format(n,this.locale,{formatAs:function(E,T){return l.formatValue(T,E,{labels:c,future:m})},now:h,future:m});var y=r.unit||r.formatAs;if(!y)throw new Error("[javascript-time-ago] Each step must define either `formatAs` or `format()`. Step: ".concat(JSON.stringify(r)));if(y==="now")return d;var k=Math.abs(s)/UI(r);r.granularity&&(k=Oc(b)(k/r.granularity)*r.granularity);var S=-1*Math.sign(s)*Oc(b)(k);switch(S===0&&(m?S=0:S=-0),f){case"long":case"short":case"narrow":return this.getFormatter(f).format(S,y);default:return this.formatValue(S,y,{labels:c,future:m})}}}},{key:"formatValue",value:function(n,r,s){var a=s.labels,l=s.future;return this.getFormattingRule(a,r,n,{future:l}).replace("{0}",this.formatNumber(Math.abs(n)))}},{key:"getFormattingRule",value:function(n,r,s,a){var l=a.future;if(this.locale,n=n[r],typeof n=="string")return n;var c=s===0?l?"future":"past":s<0?"past":"future",f=n[c]||n;if(typeof f=="string")return f;var d=this.getPluralRules().select(Math.abs(s));return f[d]||f.other}},{key:"formatNumber",value:function(n){return this.numberFormat?this.numberFormat.format(n):String(n)}},{key:"getFormatter",value:function(n){return this.relativeTimeFormatCache.get(this.locale,n)||this.relativeTimeFormatCache.put(this.locale,n,new this.IntlRelativeTimeFormat(this.locale,{style:n}))}},{key:"getPluralRules",value:function(){return this.pluralRulesCache.get(this.locale)||this.pluralRulesCache.put(this.locale,new this.IntlPluralRules(this.locale))}},{key:"getLabels",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];typeof n=="string"&&(n=[n]),n=n.map(function(c){switch(c){case"tiny":case"mini-time":return"mini";default:return c}}),n=n.concat("long");for(var r=gl(this.locale),s=LV(n),a;!(a=s()).done;){var l=a.value;if(r[l])return{labelsType:l,labels:r[l]}}}}]),e})(),ZI="en";jr.getDefaultLocale=function(){return ZI};jr.setDefaultLocale=function(e){mv=!0,ZI=e};jr.addDefaultLocale=function(e){mv&&jr.getDefaultLocale()!==e.locale&&console.warn(`[javascript-time-ago] You're adding "`.concat(e.locale,'" as the default locale but you have already added "').concat(jr.getDefaultLocale(),'" as the default locale. "').concat(e.locale,'" is the default locale now.')),mv=!0,jr.addLocale(e),jr.setDefaultLocale(e.locale)};var mv=!1;jr.addLocale=function(e){WI(e),Ns.addLocale(e)};jr.locale=jr.addLocale;jr.addLabels=function(e,t,n){var r=gl(e);r||(WI({locale:e}),r=gl(e)),r[t]=n};function VV(e){if(e.constructor===Date||GV(e))return e.getTime();if(typeof e=="number")return e;throw new Error("Unsupported relative time formatter input: ".concat(da(e),", ").concat(e))}function GV(e){return da(e)==="object"&&typeof e.getTime=="function"}function WV(e,t,n){var r=Object.keys(t);return n&&r.push("now"),e&&(r=e.filter(function(s){return s==="now"||r.indexOf(s)>=0})),r}function KV(e,t,n,r){var s=e.now||t&&t.now;if(s)return typeof s=="string"?s:r?s.future:s.past;if(n&&n.second&&n.second.current)return n.second.current}function YV(e){return typeof e=="string"||PH(e)}function XV(e,t){return setTimeout(e,QI(t))}function QI(e){return Math.min(e,ZV)}var ZV=2147483647;const JI={locale:"en",long:{year:{previous:"last year",current:"this year",next:"next year",past:{one:"{0} year ago",other:"{0} years ago"},future:{one:"in {0} year",other:"in {0} years"}},quarter:{previous:"last quarter",current:"this quarter",next:"next quarter",past:{one:"{0} quarter ago",other:"{0} quarters ago"},future:{one:"in {0} quarter",other:"in {0} quarters"}},month:{previous:"last month",current:"this month",next:"next month",past:{one:"{0} month ago",other:"{0} months ago"},future:{one:"in {0} month",other:"in {0} months"}},week:{previous:"last week",current:"this week",next:"next week",past:{one:"{0} week ago",other:"{0} weeks ago"},future:{one:"in {0} week",other:"in {0} weeks"}},day:{previous:"yesterday",current:"today",next:"tomorrow",past:{one:"{0} day ago",other:"{0} days ago"},future:{one:"in {0} day",other:"in {0} days"}},hour:{current:"this hour",past:{one:"{0} hour ago",other:"{0} hours ago"},future:{one:"in {0} hour",other:"in {0} hours"}},minute:{current:"this minute",past:{one:"{0} minute ago",other:"{0} minutes ago"},future:{one:"in {0} minute",other:"in {0} minutes"}},second:{current:"now",past:{one:"{0} second ago",other:"{0} seconds ago"},future:{one:"in {0} second",other:"in {0} seconds"}}},short:{year:{previous:"last yr.",current:"this yr.",next:"next yr.",past:"{0} yr. ago",future:"in {0} yr."},quarter:{previous:"last qtr.",current:"this qtr.",next:"next qtr.",past:{one:"{0} qtr. ago",other:"{0} qtrs. ago"},future:{one:"in {0} qtr.",other:"in {0} qtrs."}},month:{previous:"last mo.",current:"this mo.",next:"next mo.",past:"{0} mo. ago",future:"in {0} mo."},week:{previous:"last wk.",current:"this wk.",next:"next wk.",past:"{0} wk. ago",future:"in {0} wk."},day:{previous:"yesterday",current:"today",next:"tomorrow",past:{one:"{0} day ago",other:"{0} days ago"},future:{one:"in {0} day",other:"in {0} days"}},hour:{current:"this hour",past:"{0} hr. ago",future:"in {0} hr."},minute:{current:"this minute",past:"{0} min. ago",future:"in {0} min."},second:{current:"now",past:"{0} sec. ago",future:"in {0} sec."}},narrow:{year:{previous:"last yr.",current:"this yr.",next:"next yr.",past:"{0}y ago",future:"in {0}y"},quarter:{previous:"last qtr.",current:"this qtr.",next:"next qtr.",past:"{0}q ago",future:"in {0}q"},month:{previous:"last mo.",current:"this mo.",next:"next mo.",past:"{0}mo ago",future:"in {0}mo"},week:{previous:"last wk.",current:"this wk.",next:"next wk.",past:"{0}w ago",future:"in {0}w"},day:{previous:"yesterday",current:"today",next:"tomorrow",past:"{0}d ago",future:"in {0}d"},hour:{current:"this hour",past:"{0}h ago",future:"in {0}h"},minute:{current:"this minute",past:"{0}m ago",future:"in {0}m"},second:{current:"now",past:"{0}s ago",future:"in {0}s"}},now:{now:{current:"now",future:"in a moment",past:"just now"}},mini:{year:"{0}yr",month:"{0}mo",week:"{0}wk",day:"{0}d",hour:"{0}h",minute:"{0}m",second:"{0}s",now:"now"},"short-time":{year:"{0} yr.",month:"{0} mo.",week:"{0} wk.",day:{one:"{0} day",other:"{0} days"},hour:"{0} hr.",minute:"{0} min.",second:"{0} sec."},"long-time":{year:{one:"{0} year",other:"{0} years"},month:{one:"{0} month",other:"{0} months"},week:{one:"{0} week",other:"{0} weeks"},day:{one:"{0} day",other:"{0} days"},hour:{one:"{0} hour",other:"{0} hours"},minute:{one:"{0} minute",other:"{0} minutes"},second:{one:"{0} second",other:"{0} seconds"}}};jr.addLocale(JI);jr.addDefaultLocale(JI);const QV=new jr("en-US");function zn(e,t){let n=typeof e=="string"?e:JSON.stringify(e);return n===void 0&&(n=""),n.length>t?`${n.slice(0,t-1)}…`:n}function Jr(e,t){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function JV(e,t){const n=String(e??"").replace(/\s+/g," ").trim();if(n.length<=t)return n;const r=t-1,s=Math.max(1,Math.floor(r*.35)),a=Math.max(1,r-s);return`${n.slice(0,s)}…${n.slice(n.length-a)}`}function Sl(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Ii(e){return e==null||!Number.isFinite(e)?"—":rH(e)}function c0(e){const t=Math.ceil(e/1e3);if(e<1e3)return"1s";if(t<60)return`${t}s`;if(t>=3600){const s=Math.floor(t/3600),a=Math.floor(t%3600/60);return a>0?`${s}h ${a}m`:`${s}h`}const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}const eG=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,hour12:!1});function dR(e){return e==null||!Number.isFinite(e)?"—":eG.format(e)}function gv(e,t=Date.now()){const n=Sl(e);return n===null?null:QV.format(Math.min(n,t),"mini",{now:t})}function Eo(e,t=8e3){if(e==null)return"";let n;try{n=typeof e=="string"?e:JSON.stringify(e,null,2)}catch{n=String(e)}return n.length>t?`${n.slice(0,t-1)}…`:n}const tG=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1});function ih(e){return e==null||!Number.isFinite(e)?"0":tG.format(e)}function f0(e){return e==null||!Number.isFinite(e)?"—":e===0?"$0.00":e>=.1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function eM(e){if(e?.redacted===!0)return null;const t=e?.text;return typeof t=="string"&&t!==""?t:null}function bv(e){const t=String(e||"").trim();if(!t)return[];if(t.charAt(0)==="[")try{const r=JSON.parse(t);return Array.isArray(r)?r:[]}catch{return[]}const n=[];for(const r of t.split(/\n/)){const s=r.trim();if(s)try{n.push(JSON.parse(s))}catch{}}return n}const nG=new Set(["review.cursor.com"]);function tM(e){try{const t=new URL(e),n=t.pathname.split("/").filter(Boolean);return t.hostname==="github.com"&&n.length>=4&&n[2]==="pull"||t.hostname==="cursor.com"&&n[0]==="codebase"&&n.length>=5&&n[3]==="pull"||nG.has(t.hostname)&&n[0]==="pr"?!0:(/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(t.hostname)||t.hostname==="localhost")&&n.length>=4&&n[2]==="github"}catch{return!1}}function rG(e){return typeof e=="string"?e:e&&typeof e=="object"&&typeof e.id=="string"?e.id:e?JSON.stringify(e):""}function nM(e){return e!=="http"}const iG=new Set(["chat","trace","raw","artifacts"]);function sG(e){if(!e.seeded||!e.embedded)return{action:"none"};const n=e.sessions.filter(s=>!e.knownIds.has(s.sessionId)&&nM(s.channelId)&&s.running===!0)[0];return n===void 0?{action:"none"}:e.currentSessionId===null&&iG.has(e.view)?{action:"select",sessionId:n.sessionId}:{action:"reveal",sessionId:n.sessionId}}function oG(e){return e.filter(t=>nM(t.channelId)&&t.running===!0).length}function pR(e,t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?e+t.delta:e}const aG=new Set(["github","slack"]);function lG(e){return/^\s*\//.test(e)}function Jh(e){const t=[];for(const n of e??[])if(n.id!=="http"&&!(n.kind!==void 0&&aG.has(n.kind)))for(const r of n.routes??[]){const s=pG(n.id,r.path);if(s===null)continue;const a={name:s,channelId:n.id,method:r.method.toUpperCase(),url:r.url,path:r.path};r.description!==void 0&&(a.description=r.description),r.bodySchema!==void 0&&(a.bodySchema=r.bodySchema),r.querySchema!==void 0&&(a.querySchema=r.querySchema),t.push(a)}return t.sort((n,r)=>{const s=n.name.localeCompare(r.name);return s!==0?s:sh(n.method)-sh(r.method)}),t}function rM(e){const t=new Set,n=[];for(const r of e)t.has(r.name)||(t.add(r.name),n.push(r.name));return n}function uG(e,t){const n=e.trim().toLowerCase();if(!n.startsWith("/"))return[];const r=new Set,s=[];for(const a of t)a.name.toLowerCase().startsWith(n)&&(r.has(a.name)||(r.add(a.name),s.push(a)));return s}function cG(e){if(e.length===0)return"No channel slash commands on this agent. Send a normal message to chat on http.";const t=["Channel slash commands (from `/v1/info` routes):",""],n=new Map;for(const r of e){const s=n.get(r.name)??[];s.push(r),n.set(r.name,s)}for(const[r,s]of n){const a=s.map(d=>d.method).join("|"),l=s.find(d=>d.description)?.description??"",c=d0(s[0]),f=iM(c);t.push(f?`- \`${r}\` (${a}) — ${l}${l?" ":""}${f}`:`- \`${r}\` (${a})${l?` — ${l}`:""}`)}return t.push("","Args: JSON object, `key=value` flags, or a positional value for the first required string field."),t.join(`
17
- `)}function fG(e,t){const n=e.trim(),r=/^(\/[^\s]+)(?:\s+([\s\S]*))?$/.exec(n);if(r===null)return{ok:!1,error:"Expected `/command` optionally followed by args."};const s=r[1],a=(r[2]??"").trim(),l=t.filter(m=>m.name===s);if(l.length===0){const m=rM(t);return{ok:!1,error:m.length===0?`Unknown command \`${s}\`. No channel commands on this agent.`:`Unknown command \`${s}\`. Try ${m.map(b=>`\`${b}\``).join(", ")} or \`/help\`.`,commandName:s}}const c=dG(l,a),f=d0(c),d=gG(a,f);if(!d.ok)return{ok:!1,error:d.error,commandName:s};const h=hG(f,d.value);return h.length>0?{ok:!1,error:`Missing required field${h.length>1?"s":""}: ${h.join(", ")}. ${iM(f)||""}`.trim(),commandName:s}:c.method==="GET"||c.method==="HEAD"?{ok:!0,command:c,query:vG(d.value)}:{ok:!0,command:c,body:d.value,query:c.querySchema!==void 0?xG(d.value,c.querySchema):void 0}}function dG(e,t){if(e.length===1)return e[0];const n=[...e].sort((a,l)=>sh(a.method)-sh(l.method)),r=sM(t);if(r!==null){let a=null,l=-1;for(const c of n){const f=d0(c),d=mG(f,r);d>l&&(l=d,a=c)}if(a!==null&&l>0)return a}const s=n.find(a=>a.method==="GET");return s!==void 0?s:n[0]}function pG(e,t){const n=e.trim();if(n==="")return null;const r=t===""||t==="/"?"":t.startsWith("/")?t.replace(/\/+$/,""):`/${t.replace(/\/+$/,"")}`;return r.includes(":")?null:`/${n}${r}`}function sh(e){switch(e.toUpperCase()){case"GET":return 0;case"POST":return 1;case"PUT":return 2;case"PATCH":return 3;case"DELETE":return 4;default:return 9}}function d0(e){return e.method==="GET"||e.method==="HEAD"?e.querySchema:e.bodySchema??e.querySchema}function iM(e){if(e===void 0)return"";const t=em(e);if(t===void 0)return"";const n=tm(e),r=[];for(const s of n)t[s]?.type==="string"?r.push(`<${s}>`):r.push(`${s}=…`);for(const s of Object.keys(t))n.has(s)||r.push(`[${s}=…]`);return r.length>0?`Usage: ${r.join(" ")}`:""}function em(e){if(e===void 0||e.type!=="object")return;const t=e.properties;if(!(typeof t!="object"||t===null||Array.isArray(t)))return t}function tm(e){return e===void 0||!Array.isArray(e.required)?new Set:new Set(e.required.filter(t=>typeof t=="string"))}function hG(e,t){const n=tm(e),r=[];for(const s of n){const a=t[s];(a==null||typeof a=="string"&&a.trim()==="")&&r.push(s)}return r}function mG(e,t){const n=em(e);if(n===void 0)return 0;let r=0;for(const s of Object.keys(t))s in n?r+=2:r-=1;for(const s of tm(e))s in t&&(r+=3);return r}function sM(e){const t=e.trim();if(!t.startsWith("{"))return null;try{const n=JSON.parse(t);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{return null}return null}function gG(e,t){if(e==="")return{ok:!0,value:{}};const n=sM(e);if(n!==null)return{ok:!0,value:n};if(e.startsWith("{"))return{ok:!1,error:"Args look like JSON but failed to parse."};const r=em(t),s={},a=[];for(const l of bG(e)){const c=l.indexOf("=");if(c>0){const f=l.slice(0,c),d=l.slice(c+1);s[f]=yG(d,r?.[f])}else a.push(l)}if(a.length>0){const l=[...tm(t)],c=(l.length>0?l:Object.keys(r??{})).filter(d=>{const h=r?.[d];return h===void 0||h.type==="string"||h.type===void 0}),f=c.find(d=>s[d]===void 0)??c[0];if(f===void 0)return{ok:!1,error:`Unexpected positional args: ${a.join(" ")}`};a.length===1?s[f]=a[0]:s[f]=a.join(" ")}return{ok:!0,value:s}}function bG(e){const t=[];let n="",r=null;for(let s=0;s<e.length;s++){const a=e[s];if(r!==null){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){n!==""&&(t.push(n),n="");continue}n+=a}return n!==""&&t.push(n),t}function yG(e,t){const n=t?.type;if(n==="number"||n==="integer"){const r=Number(e);return Number.isFinite(r)?r:e}if(n==="boolean"){if(e==="true")return!0;if(e==="false")return!1}if(n==="array"||n==="object")try{return JSON.parse(e)}catch{return e}return e}function vG(e){const t={};for(const[n,r]of Object.entries(e))r!=null&&(t[n]=typeof r=="string"?r:String(r));return t}function xG(e,t){const n=em(t);if(n===void 0)return;const r={};for(const s of Object.keys(n)){const a=e[s];a!=null&&(r[s]=typeof a=="string"?a:String(a))}return Object.keys(r).length>0?r:void 0}class kG{constructor(t,n,r=()=>""){this.basePath=t,this.getToken=n,this.getAliasToken=r}url(t){return(this.basePath||"")+t}headers(t){const n={...t},r=this.getToken().trim();r&&(n.authorization=`Bearer ${r}`);const s=this.getAliasToken().trim();return s&&(n["x-agent-alias-token"]=s),n}async request(t,n={}){const r=await fetch(this.url(t),{...n,headers:this.headers(n.headers)}),s=await r.text();let a=null;try{a=s?JSON.parse(s):null}catch{a=null}return{status:r.status,ok:r.ok,body:a}}postJson(t,n){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}health(){return this.request("/v1/health")}info(){return this.request("/v1/info")}logs(t=-1){const n=t<0?"":`?after=${t}`;return this.request(`/v1/logs${n}`)}meta(){return this.request("/v1/meta")}sessions(){return this.request("/v1/sessions")}artifacts(t={}){const n=new URLSearchParams;t.sessionId!==void 0&&t.sessionId!==""&&n.set("sessionId",t.sessionId),t.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString();return this.request(`/v1/artifacts${r===""?"":`?${r}`}`)}async artifactContent(t,n){const r=await fetch(this.url(`/v1/artifacts/${encodeURIComponent(t)}/content`),{headers:this.headers()}),s=r.headers.get("content-type")??void 0;if(!r.ok||r.body===null)return await r.body?.cancel().catch(()=>{}),{status:r.status,ok:!1,contentType:s,bytes:new Uint8Array(0),truncated:!1};const a=r.body.getReader(),l=[];let c=0,f=!1;for(;;){const{done:m,value:b}=await a.read();if(m)break;if(b!==void 0){if(c+b.length>n){l.push(b.slice(0,n-c)),c=n,f=!0,await a.cancel().catch(()=>{});break}l.push(b),c+=b.length}}const d=new Uint8Array(c);let h=0;for(const m of l)d.set(m,h),h+=m.length;return{status:r.status,ok:!0,contentType:s,bytes:d,truncated:f}}createSession(t){return this.postJson("/v1/session",{message:t})}followUp(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}`,{message:n,continuationToken:r})}stopSession(t){return this.postJson(`/v1/session/${encodeURIComponent(t)}/stop`,{})}resolveApproval(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}`,{decision:r})}resolveAuth(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}/auths/${encodeURIComponent(n)}`,{decision:r})}dispatchSchedule(t){return this.request(`/v1/dev/schedules/${encodeURIComponent(t)}`,{method:"POST"})}evalsList(){return this.request("/v1/dev/evals")}evalsListRuns(){return this.request("/v1/dev/evals/runs")}evalsStartRun(t={}){return this.postJson("/v1/dev/evals/runs",t)}evalsRunStatus(t){return this.request(`/v1/dev/evals/runs/${encodeURIComponent(t)}`)}evalsCancelRun(t){return this.postJson(`/v1/dev/evals/runs/${encodeURIComponent(t)}/cancel`,{})}channelRequest(t,n,r={}){let s=n;if(r.query!==void 0){const l=new URLSearchParams;for(const[f,d]of Object.entries(r.query))d!==""&&l.set(f,d);const c=l.toString();c!==""&&(s=`${n}?${c}`)}const a={method:t.toUpperCase()};return r.body!==void 0&&(a.headers={"content-type":"application/json"},a.body=JSON.stringify(r.body)),this.request(s,a)}streamFetch(t,n,r){return fetch(this.url(`/v1/session/${encodeURIComponent(t)}/stream?startIndex=${n}`),{signal:r,headers:this.headers()})}eventsText(t){return fetch(this.url(`/v1/session/${encodeURIComponent(t)}/events`),{headers:this.headers()})}sessionCost(t){return this.request(`/v1/session/${encodeURIComponent(t)}/cost`)}}const yt={infoRead:"info.read",sessionRead:"session.read",sessionStart:"session.start",sessionFollowUp:"session.followUp",sessionStop:"session.stop",sessionStream:"session.stream",eventRead:"event.read",sessionCost:"session.cost",approvalResolve:"approval.resolve",authResolve:"auth.resolve",logRead:"log.read",artifactRead:"artifact.read",artifactContent:"artifact.content",scheduleDispatch:"schedule.dispatch",evalRead:"eval.read",evalRun:"eval.run",evalCancel:"eval.cancel",channelInvoke:"channel.invoke"},SG=new Set(Object.values(yt));class wG{constructor(t){this.client=t,this.capabilities=SG,this.health=()=>this.client.health(),this.info=()=>this.client.info(),this.meta=()=>this.client.meta(),this.logs=n=>this.client.logs(n),this.sessions=()=>this.client.sessions(),this.createSession=n=>this.client.createSession(n),this.followUp=(n,r,s)=>this.client.followUp(n,r,s),this.stopSession=n=>this.client.stopSession(n),this.subscribeEvents=(n,r,s)=>this.client.streamFetch(n,r,s),this.eventsText=n=>this.client.eventsText(n),this.sessionCost=n=>this.client.sessionCost(n),this.resolveApproval=(n,r,s)=>this.client.resolveApproval(n,r,s),this.resolveAuth=(n,r,s)=>this.client.resolveAuth(n,r,s),this.artifacts=n=>this.client.artifacts(n),this.artifactContent=(n,r)=>this.client.artifactContent(n,r),this.dispatchSchedule=n=>this.client.dispatchSchedule(n),this.evalsList=()=>this.client.evalsList(),this.evalsListRuns=()=>this.client.evalsListRuns(),this.evalsStartRun=n=>this.client.evalsStartRun(n),this.evalsRunStatus=n=>this.client.evalsRunStatus(n),this.evalsCancelRun=n=>this.client.evalsCancelRun(n),this.channelRequest=(n,r,s)=>this.client.channelRequest(n,r,s),this.url=n=>this.client.url(n)}}const EG="agent-sdk-playground-boot";function TG(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RG(e){const t=e.getElementById(EG);if(t===null)return{kind:"local"};let n;try{n=JSON.parse(t.textContent??"")}catch{throw new Error("Playground boot document is not valid JSON.")}if(!TG(n)||n.transport!=="hosted")throw new Error("Playground boot document has an unknown transport.");if(typeof n.teamId!="number"||!Number.isSafeInteger(n.teamId)||n.teamId<=0||typeof n.deploymentSlug!="string"||n.deploymentSlug.length===0||n.evals!==void 0&&typeof n.evals!="boolean")throw new Error("Playground hosted transport configuration is invalid.");return{kind:"hosted",teamId:n.teamId,deploymentSlug:n.deploymentSlug,evals:n.evals===!0}}const oM=new Set([yt.infoRead,yt.sessionRead,yt.sessionStart,yt.sessionFollowUp,yt.sessionStream,yt.eventRead,yt.logRead]),CG=new Set([...oM,yt.evalRead,yt.evalRun]),hR=18e4,_G=1e3,mR=500;function AG(e){return Math.min(100*2**e,_G)}const NG=2e4,OG=5e3,IG=100,MG=e=>new Promise(t=>globalThis.setTimeout(t,e));function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DG(e){return!gn(e)||typeof e.slug!="string"?null:{slug:e.slug,cliVersion:typeof e.manifestCliVersion=="string"?e.manifestCliVersion:void 0}}function LG(e){if(!gn(e)||!Array.isArray(e.components))return null;const t=e.components.filter(n=>gn(n)&&typeof n.componentKey=="string"&&gn(n.info));return(t.find(n=>n.componentKey==="default")??t[0])?.info??null}function jG(e){return!gn(e)||typeof e.deliveryId!="string"||e.deliveryId===""||e.sessionId!==void 0&&(typeof e.sessionId!="string"||e.sessionId==="")?null:{deliveryId:e.deliveryId,sessionId:e.sessionId}}function zG(e){return gn(e)?e.status==="pending"?{status:"pending"}:e.status==="allocated"&&typeof e.sessionId=="string"&&e.sessionId!==""?{status:"allocated",sessionId:e.sessionId}:e.status==="skipped"||e.status==="failed"?{status:e.status}:null:null}function PG(e){switch(e){case"unbound":case"creating":case"active":case"hibernated":case"failed":case"deleting":return e;default:return null}}function $G(e){if(!gn(e))return null;const t=PG(e.phase);return t===null||typeof e.sessionId!="string"||typeof e.channelId!="string"||typeof e.mode!="string"||typeof e.createdAt!="string"||typeof e.lastActivityAt!="string"||e.lastError!==null&&typeof e.lastError!="string"||e.customer!==void 0&&typeof e.customer!="boolean"?null:{sessionId:e.sessionId,channelId:e.channelId,mode:e.mode,phase:t,createdAt:e.createdAt,lastActivityAt:e.lastActivityAt,lastError:e.lastError,customer:e.customer===!0}}function BG(e){if(!gn(e)||!Array.isArray(e.sessions))return null;const t=[];for(const n of e.sessions){const r=$G(n);if(r===null)return null;t.push(r)}return e.nextCursor===null?{sessions:t,nextCursor:null}:!gn(e.nextCursor)||typeof e.nextCursor.lastActivityAt!="string"||typeof e.nextCursor.id!="string"?null:{sessions:t,nextCursor:{lastActivityAt:e.nextCursor.lastActivityAt,id:e.nextCursor.id}}}function aM(e){return!gn(e)||typeof e.type!="string"||e.index!==void 0&&typeof e.index!="number"||e.at!==void 0&&typeof e.at!="string"||e.turnId!==void 0&&typeof e.turnId!="string"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.data!==void 0&&!gn(e.data)?null:{index:e.index,type:e.type,at:e.at,turnId:e.turnId,sessionId:e.sessionId,data:e.data}}function FG(e){if(!gn(e)||!Array.isArray(e.events))return null;const t=[];for(const n of e.events){const r=aM(n);if(r===null)return null;t.push(r)}return t}function UG(e){if(!gn(e)||!Array.isArray(e.events)||typeof e.unreadableChunks!="number")return null;const t=[];for(const r of e.events){const s=aM(r);if(s===null)return null;t.push(s)}let n=null;if(e.execution!==null){if(!gn(e.execution)||typeof e.execution.executionId!="string"||typeof e.execution.turnStatus!="string")return null;n={executionId:e.execution.executionId,turnStatus:e.execution.turnStatus}}return{events:t,execution:n,unreadableChunks:e.unreadableChunks}}function qG(e){if(!gn(e)||!Array.isArray(e.sessions))return null;const t=[];for(const n of e.sessions){if(!gn(n)||typeof n.sessionId!="string"||!Array.isArray(n.lines)||!n.lines.every(r=>typeof r=="string"))return null;t.push({sessionId:n.sessionId,channelId:typeof n.channelId=="string"?n.channelId:void 0,lines:n.lines})}return t}function HG(e,t){for(let n=Math.min(e.length,t.length);n>0;n--){const r=e.length-n;let s=0;for(;s<n&&t[s]===e[r+s];)s++;if(s===n)return t.slice(n)}return[...t]}function VG(e,t,n){e.delete(t),e.set(t,n);for(const r of e.keys()){if(e.size<=IG)return;e.delete(r)}}function GG(e){if(e.lastError!==null||e.phase==="failed")return"Failed";switch(e.phase){case"unbound":case"creating":return"Creating";case"active":return"Active";case"hibernated":return"Hibernated";case"deleting":return"Deleting"}}const WG=100;function KG(e){if(!gn(e)||!gn(e.session))return null;const t=e.session;if(typeof t.sessionId!="string"||t.sessionId==="")return null;const n=typeof t.channelId=="string"?t.channelId:"http",r=typeof t.mode=="string"?t.mode:"chat";return{sessionId:t.sessionId,channelId:n,mode:r,followUpAllowed:!1,title:`${t.sessionId} · History`,running:t.running===!0,turnCount:typeof t.turnCount=="number"?t.turnCount:void 0,createdAt:typeof t.createdAt=="string"?t.createdAt:void 0,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:void 0}}const lM=new Set(["creating","active"]);function YG(e,t){return{sessionId:e.sessionId,channelId:e.channelId,mode:e.mode,followUpAllowed:e.channelId==="http"&&!e.customer,title:`${e.sessionId} · ${GG(e)}`,running:lM.has(e.phase),turnCount:t,createdAt:e.createdAt,updatedAt:e.lastActivityAt}}function gR(e){return`${e.lastActivityAt}|${e.phase}`}const XG=3e4;function ZG(e){if(!gn(e)||!gn(e.turnCounts))return null;const t=new Map;for(const[n,r]of Object.entries(e.turnCounts)){if(typeof r!="number")return null;t.set(n,r)}return t}const QG=new Set(["running","completed","failed","cancelled"]),JG=new Set(["pending","running","done"]);function eW(e){return!gn(e)||typeof e.id!="string"||typeof e.fileId!="string"?null:{id:e.id,fileId:e.fileId,description:typeof e.description=="string"?e.description:void 0,tags:Array.isArray(e.tags)?e.tags.filter(t=>typeof t=="string"):void 0}}function tW(e){if(!gn(e)||!Array.isArray(e.evals)||!gn(e.config))return null;const t=[];for(const n of e.evals){const r=eW(n);if(r===null)return null;t.push(r)}return{evals:t,config:e.config}}function yv(e){if(!gn(e)||typeof e.runId!="string"||!QG.has(e.status)||typeof e.startedAt!="string"||!gn(e.summary)||typeof e.summary.passed!="number"||typeof e.summary.failed!="number"||typeof e.summary.total!="number"||typeof e.summary.done!="number"||!Array.isArray(e.cases)||!gn(e.config))return null;for(const t of e.cases)if(!gn(t)||typeof t.id!="string"||typeof t.fileId!="string"||!JG.has(t.status))return null;return e}function nW(e){if(!gn(e)||!Array.isArray(e.runs)||e.activeRunId!==void 0&&typeof e.activeRunId!="string")return null;const t=[];for(const n of e.runs){const r=yv(n);if(r===null)return null;t.push(r)}return e.activeRunId===void 0?{runs:t}:{runs:t,activeRunId:e.activeRunId}}function co(){return Promise.resolve({status:501,ok:!1,body:null})}class rW{constructor(t,n,r={}){this.teamId=t,this.bootstrapRequest=null,this.composedSessionIds=new Set,this.writableSessionIds=new Set,this.logTails=new Map,this.logIndex=-1,this.logsReadAt=Number.NEGATIVE_INFINITY,this.logsReading=!1,this.turnCounts=new Map,this.turnCountsReading=!1,this.health=async()=>{const s=await this.bootstrap();return{status:s.status,ok:s.ok,body:s.ok?{ok:!0}:null}},this.meta=async()=>{const s=await this.bootstrap();return{status:s.status,ok:s.ok,body:s.body===null?null:{name:s.body.slug,dev:!1,basePath:"",version:s.body.cliVersion,readonly:!1}}},this.info=async()=>{const[s,a]=await Promise.all([this.bootstrap(),this.request("/info",LG).catch(()=>null)]);return{status:s.status,ok:s.ok,body:s.body===null?null:{...a?.body,name:s.body.slug,runtime:"cloud"}}},this.sessions=async()=>{const s=new URLSearchParams({limit:String(WG)}),a=await this.request(`/sessions?${s.toString()}`,BG);if(!a.ok||a.body===null)return{status:a.status,ok:!1,body:null};const l=a.body.sessions,c=l.map(f=>YG(f,this.turnCounts.get(f.sessionId)?.count));return this.writableSessionIds=new Set([...this.composedSessionIds,...c.filter(f=>f.followUpAllowed===!0).map(f=>f.sessionId)]),this.readTurnCounts(l),{status:200,ok:!0,body:{sessions:c}}},this.sessionById=async s=>{const a=await this.request(`/sessions/${encodeURIComponent(s)}`,KG);return a.ok?{status:a.status,ok:!0,body:{session:a.body}}:{status:a.status,ok:!1,body:null}},this.eventsText=async s=>{const a=await this.request(`/sessions/${encodeURIComponent(s)}`,FG);if(!a.ok||a.body===null)return new Response(null,{status:a.status});const l=a.body.map(c=>JSON.stringify(c)).join(`
17
+ `)}function fG(e,t){const n=e.trim(),r=/^(\/[^\s]+)(?:\s+([\s\S]*))?$/.exec(n);if(r===null)return{ok:!1,error:"Expected `/command` optionally followed by args."};const s=r[1],a=(r[2]??"").trim(),l=t.filter(m=>m.name===s);if(l.length===0){const m=rM(t);return{ok:!1,error:m.length===0?`Unknown command \`${s}\`. No channel commands on this agent.`:`Unknown command \`${s}\`. Try ${m.map(b=>`\`${b}\``).join(", ")} or \`/help\`.`,commandName:s}}const c=dG(l,a),f=d0(c),d=gG(a,f);if(!d.ok)return{ok:!1,error:d.error,commandName:s};const h=hG(f,d.value);return h.length>0?{ok:!1,error:`Missing required field${h.length>1?"s":""}: ${h.join(", ")}. ${iM(f)||""}`.trim(),commandName:s}:c.method==="GET"||c.method==="HEAD"?{ok:!0,command:c,query:vG(d.value)}:{ok:!0,command:c,body:d.value,query:c.querySchema!==void 0?xG(d.value,c.querySchema):void 0}}function dG(e,t){if(e.length===1)return e[0];const n=[...e].sort((a,l)=>sh(a.method)-sh(l.method)),r=sM(t);if(r!==null){let a=null,l=-1;for(const c of n){const f=d0(c),d=mG(f,r);d>l&&(l=d,a=c)}if(a!==null&&l>0)return a}const s=n.find(a=>a.method==="GET");return s!==void 0?s:n[0]}function pG(e,t){const n=e.trim();if(n==="")return null;const r=t===""||t==="/"?"":t.startsWith("/")?t.replace(/\/+$/,""):`/${t.replace(/\/+$/,"")}`;return r.includes(":")?null:`/${n}${r}`}function sh(e){switch(e.toUpperCase()){case"GET":return 0;case"POST":return 1;case"PUT":return 2;case"PATCH":return 3;case"DELETE":return 4;default:return 9}}function d0(e){return e.method==="GET"||e.method==="HEAD"?e.querySchema:e.bodySchema??e.querySchema}function iM(e){if(e===void 0)return"";const t=em(e);if(t===void 0)return"";const n=tm(e),r=[];for(const s of n)t[s]?.type==="string"?r.push(`<${s}>`):r.push(`${s}=…`);for(const s of Object.keys(t))n.has(s)||r.push(`[${s}=…]`);return r.length>0?`Usage: ${r.join(" ")}`:""}function em(e){if(e===void 0||e.type!=="object")return;const t=e.properties;if(!(typeof t!="object"||t===null||Array.isArray(t)))return t}function tm(e){return e===void 0||!Array.isArray(e.required)?new Set:new Set(e.required.filter(t=>typeof t=="string"))}function hG(e,t){const n=tm(e),r=[];for(const s of n){const a=t[s];(a==null||typeof a=="string"&&a.trim()==="")&&r.push(s)}return r}function mG(e,t){const n=em(e);if(n===void 0)return 0;let r=0;for(const s of Object.keys(t))s in n?r+=2:r-=1;for(const s of tm(e))s in t&&(r+=3);return r}function sM(e){const t=e.trim();if(!t.startsWith("{"))return null;try{const n=JSON.parse(t);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{return null}return null}function gG(e,t){if(e==="")return{ok:!0,value:{}};const n=sM(e);if(n!==null)return{ok:!0,value:n};if(e.startsWith("{"))return{ok:!1,error:"Args look like JSON but failed to parse."};const r=em(t),s={},a=[];for(const l of bG(e)){const c=l.indexOf("=");if(c>0){const f=l.slice(0,c),d=l.slice(c+1);s[f]=yG(d,r?.[f])}else a.push(l)}if(a.length>0){const l=[...tm(t)],c=(l.length>0?l:Object.keys(r??{})).filter(d=>{const h=r?.[d];return h===void 0||h.type==="string"||h.type===void 0}),f=c.find(d=>s[d]===void 0)??c[0];if(f===void 0)return{ok:!1,error:`Unexpected positional args: ${a.join(" ")}`};a.length===1?s[f]=a[0]:s[f]=a.join(" ")}return{ok:!0,value:s}}function bG(e){const t=[];let n="",r=null;for(let s=0;s<e.length;s++){const a=e[s];if(r!==null){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){n!==""&&(t.push(n),n="");continue}n+=a}return n!==""&&t.push(n),t}function yG(e,t){const n=t?.type;if(n==="number"||n==="integer"){const r=Number(e);return Number.isFinite(r)?r:e}if(n==="boolean"){if(e==="true")return!0;if(e==="false")return!1}if(n==="array"||n==="object")try{return JSON.parse(e)}catch{return e}return e}function vG(e){const t={};for(const[n,r]of Object.entries(e))r!=null&&(t[n]=typeof r=="string"?r:String(r));return t}function xG(e,t){const n=em(t);if(n===void 0)return;const r={};for(const s of Object.keys(n)){const a=e[s];a!=null&&(r[s]=typeof a=="string"?a:String(a))}return Object.keys(r).length>0?r:void 0}class kG{constructor(t,n,r=()=>""){this.basePath=t,this.getToken=n,this.getAliasToken=r}url(t){return(this.basePath||"")+t}headers(t){const n={...t},r=this.getToken().trim();r&&(n.authorization=`Bearer ${r}`);const s=this.getAliasToken().trim();return s&&(n["x-agent-alias-token"]=s),n}async request(t,n={}){const r=await fetch(this.url(t),{...n,headers:this.headers(n.headers)}),s=await r.text();let a=null;try{a=s?JSON.parse(s):null}catch{a=null}return{status:r.status,ok:r.ok,body:a}}postJson(t,n){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}health(){return this.request("/v1/health")}info(){return this.request("/v1/info")}logs(t=-1){const n=t<0?"":`?after=${t}`;return this.request(`/v1/logs${n}`)}meta(){return this.request("/v1/meta")}sessions(){return this.request("/v1/sessions")}artifacts(t={}){const n=new URLSearchParams;t.sessionId!==void 0&&t.sessionId!==""&&n.set("sessionId",t.sessionId),t.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString();return this.request(`/v1/artifacts${r===""?"":`?${r}`}`)}async artifactContent(t,n){const r=await fetch(this.url(`/v1/artifacts/${encodeURIComponent(t)}/content`),{headers:this.headers()}),s=r.headers.get("content-type")??void 0;if(!r.ok||r.body===null)return await r.body?.cancel().catch(()=>{}),{status:r.status,ok:!1,contentType:s,bytes:new Uint8Array(0),truncated:!1};const a=r.body.getReader(),l=[];let c=0,f=!1;for(;;){const{done:m,value:b}=await a.read();if(m)break;if(b!==void 0){if(c+b.length>n){l.push(b.slice(0,n-c)),c=n,f=!0,await a.cancel().catch(()=>{});break}l.push(b),c+=b.length}}const d=new Uint8Array(c);let h=0;for(const m of l)d.set(m,h),h+=m.length;return{status:r.status,ok:!0,contentType:s,bytes:d,truncated:f}}createSession(t){return this.postJson("/v1/session",{message:t})}followUp(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}`,{message:n,continuationToken:r})}stopSession(t){return this.postJson(`/v1/session/${encodeURIComponent(t)}/stop`,{})}resolveApproval(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}`,{decision:r})}resolveAuth(t,n,r){return this.postJson(`/v1/session/${encodeURIComponent(t)}/auths/${encodeURIComponent(n)}`,{decision:r})}dispatchSchedule(t){return this.request(`/v1/dev/schedules/${encodeURIComponent(t)}`,{method:"POST"})}evalsList(){return this.request("/v1/dev/evals")}evalsListRuns(){return this.request("/v1/dev/evals/runs")}evalsStartRun(t={}){return this.postJson("/v1/dev/evals/runs",t)}evalsRunStatus(t){return this.request(`/v1/dev/evals/runs/${encodeURIComponent(t)}`)}evalsCancelRun(t){return this.postJson(`/v1/dev/evals/runs/${encodeURIComponent(t)}/cancel`,{})}channelRequest(t,n,r={}){let s=n;if(r.query!==void 0){const l=new URLSearchParams;for(const[f,d]of Object.entries(r.query))d!==""&&l.set(f,d);const c=l.toString();c!==""&&(s=`${n}?${c}`)}const a={method:t.toUpperCase()};return r.body!==void 0&&(a.headers={"content-type":"application/json"},a.body=JSON.stringify(r.body)),this.request(s,a)}streamFetch(t,n,r){return fetch(this.url(`/v1/session/${encodeURIComponent(t)}/stream?startIndex=${n}`),{signal:r,headers:this.headers()})}eventsText(t){return fetch(this.url(`/v1/session/${encodeURIComponent(t)}/events`),{headers:this.headers()})}sessionCost(t){return this.request(`/v1/session/${encodeURIComponent(t)}/cost`)}}const yt={infoRead:"info.read",sessionRead:"session.read",sessionStart:"session.start",sessionFollowUp:"session.followUp",sessionStop:"session.stop",sessionStream:"session.stream",eventRead:"event.read",sessionCost:"session.cost",approvalResolve:"approval.resolve",authResolve:"auth.resolve",logRead:"log.read",artifactRead:"artifact.read",artifactContent:"artifact.content",scheduleDispatch:"schedule.dispatch",evalRead:"eval.read",evalRun:"eval.run",evalCancel:"eval.cancel",channelInvoke:"channel.invoke"},SG=new Set(Object.values(yt));class wG{constructor(t){this.client=t,this.capabilities=SG,this.health=()=>this.client.health(),this.info=()=>this.client.info(),this.meta=()=>this.client.meta(),this.logs=n=>this.client.logs(n),this.sessions=()=>this.client.sessions(),this.createSession=n=>this.client.createSession(n),this.followUp=(n,r,s)=>this.client.followUp(n,r,s),this.stopSession=n=>this.client.stopSession(n),this.subscribeEvents=(n,r,s)=>this.client.streamFetch(n,r,s),this.eventsText=n=>this.client.eventsText(n),this.sessionCost=n=>this.client.sessionCost(n),this.resolveApproval=(n,r,s)=>this.client.resolveApproval(n,r,s),this.resolveAuth=(n,r,s)=>this.client.resolveAuth(n,r,s),this.artifacts=n=>this.client.artifacts(n),this.artifactContent=(n,r)=>this.client.artifactContent(n,r),this.dispatchSchedule=n=>this.client.dispatchSchedule(n),this.evalsList=()=>this.client.evalsList(),this.evalsListRuns=()=>this.client.evalsListRuns(),this.evalsStartRun=n=>this.client.evalsStartRun(n),this.evalsRunStatus=n=>this.client.evalsRunStatus(n),this.evalsCancelRun=n=>this.client.evalsCancelRun(n),this.channelRequest=(n,r,s)=>this.client.channelRequest(n,r,s),this.url=n=>this.client.url(n)}}const EG="agent-sdk-playground-boot";function TG(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RG(e){const t=e.getElementById(EG);if(t===null)return{kind:"local"};let n;try{n=JSON.parse(t.textContent??"")}catch{throw new Error("Playground boot document is not valid JSON.")}if(!TG(n)||n.transport!=="hosted")throw new Error("Playground boot document has an unknown transport.");if(typeof n.teamId!="number"||!Number.isSafeInteger(n.teamId)||n.teamId<=0||typeof n.deploymentSlug!="string"||n.deploymentSlug.length===0||n.evals!==void 0&&typeof n.evals!="boolean")throw new Error("Playground hosted transport configuration is invalid.");return{kind:"hosted",teamId:n.teamId,deploymentSlug:n.deploymentSlug,evals:n.evals===!0}}const oM=new Set([yt.infoRead,yt.sessionRead,yt.sessionStart,yt.sessionFollowUp,yt.sessionStream,yt.eventRead,yt.logRead]),CG=new Set([...oM,yt.evalRead,yt.evalRun]),hR=18e4,_G=1e3,mR=500;function AG(e){return Math.min(100*2**e,_G)}const NG=2e4,OG=5e3,IG=100,MG=e=>new Promise(t=>globalThis.setTimeout(t,e));function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DG(e){return!gn(e)||typeof e.slug!="string"?null:{slug:e.slug,cliVersion:typeof e.manifestCliVersion=="string"?e.manifestCliVersion:void 0}}function LG(e){if(!gn(e)||!Array.isArray(e.components))return null;const t=e.components.filter(n=>gn(n)&&typeof n.componentKey=="string"&&gn(n.info));return(t.find(n=>n.componentKey==="default")??t[0])?.info??null}function jG(e){return!gn(e)||typeof e.deliveryId!="string"||e.deliveryId===""||e.sessionId!==void 0&&(typeof e.sessionId!="string"||e.sessionId==="")?null:{deliveryId:e.deliveryId,sessionId:e.sessionId}}function zG(e){return gn(e)?e.status==="pending"?{status:"pending"}:e.status==="allocated"&&typeof e.sessionId=="string"&&e.sessionId!==""?{status:"allocated",sessionId:e.sessionId}:e.status==="skipped"||e.status==="failed"?{status:e.status}:null:null}function PG(e){switch(e){case"unbound":case"creating":case"active":case"hibernated":case"failed":case"deleting":return e;default:return null}}function $G(e){if(!gn(e))return null;const t=PG(e.phase);return t===null||typeof e.sessionId!="string"||typeof e.channelId!="string"||typeof e.mode!="string"||typeof e.createdAt!="string"||typeof e.lastActivityAt!="string"||e.lastError!==null&&typeof e.lastError!="string"||e.customer!==void 0&&typeof e.customer!="boolean"?null:{sessionId:e.sessionId,channelId:e.channelId,mode:e.mode,phase:t,createdAt:e.createdAt,lastActivityAt:e.lastActivityAt,lastError:e.lastError,customer:e.customer===!0}}function BG(e){if(!gn(e)||!Array.isArray(e.sessions))return null;const t=[];for(const n of e.sessions){const r=$G(n);if(r===null)return null;t.push(r)}return e.nextCursor===null?{sessions:t,nextCursor:null}:!gn(e.nextCursor)||typeof e.nextCursor.lastActivityAt!="string"||typeof e.nextCursor.id!="string"?null:{sessions:t,nextCursor:{lastActivityAt:e.nextCursor.lastActivityAt,id:e.nextCursor.id}}}function aM(e){return!gn(e)||typeof e.type!="string"||e.index!==void 0&&typeof e.index!="number"||e.at!==void 0&&typeof e.at!="string"||e.turnId!==void 0&&typeof e.turnId!="string"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.data!==void 0&&!gn(e.data)?null:{index:e.index,type:e.type,at:e.at,turnId:e.turnId,sessionId:e.sessionId,data:e.data,liveTruncated:e.liveTruncated===!0?!0:void 0}}function FG(e){if(!gn(e)||!Array.isArray(e.events))return null;const t=[];for(const n of e.events){const r=aM(n);if(r===null)return null;t.push(r)}return t}function UG(e){if(!gn(e)||!Array.isArray(e.events)||typeof e.unreadableChunks!="number")return null;const t=[];for(const r of e.events){const s=aM(r);if(s===null)return null;t.push(s)}let n=null;if(e.execution!==null){if(!gn(e.execution)||typeof e.execution.executionId!="string"||typeof e.execution.turnStatus!="string")return null;n={executionId:e.execution.executionId,turnStatus:e.execution.turnStatus}}return{events:t,execution:n,unreadableChunks:e.unreadableChunks}}function qG(e){if(!gn(e)||!Array.isArray(e.sessions))return null;const t=[];for(const n of e.sessions){if(!gn(n)||typeof n.sessionId!="string"||!Array.isArray(n.lines)||!n.lines.every(r=>typeof r=="string"))return null;t.push({sessionId:n.sessionId,channelId:typeof n.channelId=="string"?n.channelId:void 0,lines:n.lines})}return t}function HG(e,t){for(let n=Math.min(e.length,t.length);n>0;n--){const r=e.length-n;let s=0;for(;s<n&&t[s]===e[r+s];)s++;if(s===n)return t.slice(n)}return[...t]}function VG(e,t,n){e.delete(t),e.set(t,n);for(const r of e.keys()){if(e.size<=IG)return;e.delete(r)}}function GG(e){if(e.lastError!==null||e.phase==="failed")return"Failed";switch(e.phase){case"unbound":case"creating":return"Creating";case"active":return"Active";case"hibernated":return"Hibernated";case"deleting":return"Deleting"}}const WG=100;function KG(e){if(!gn(e)||!gn(e.session))return null;const t=e.session;if(typeof t.sessionId!="string"||t.sessionId==="")return null;const n=typeof t.channelId=="string"?t.channelId:"http",r=typeof t.mode=="string"?t.mode:"chat";return{sessionId:t.sessionId,channelId:n,mode:r,followUpAllowed:!1,title:`${t.sessionId} · History`,running:t.running===!0,turnCount:typeof t.turnCount=="number"?t.turnCount:void 0,createdAt:typeof t.createdAt=="string"?t.createdAt:void 0,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:void 0}}const lM=new Set(["creating","active"]);function YG(e,t){return{sessionId:e.sessionId,channelId:e.channelId,mode:e.mode,followUpAllowed:e.channelId==="http"&&!e.customer,title:`${e.sessionId} · ${GG(e)}`,running:lM.has(e.phase),turnCount:t,createdAt:e.createdAt,updatedAt:e.lastActivityAt}}function gR(e){return`${e.lastActivityAt}|${e.phase}`}const XG=3e4;function ZG(e){if(!gn(e)||!gn(e.turnCounts))return null;const t=new Map;for(const[n,r]of Object.entries(e.turnCounts)){if(typeof r!="number")return null;t.set(n,r)}return t}const QG=new Set(["running","completed","failed","cancelled"]),JG=new Set(["pending","running","done"]);function eW(e){return!gn(e)||typeof e.id!="string"||typeof e.fileId!="string"?null:{id:e.id,fileId:e.fileId,description:typeof e.description=="string"?e.description:void 0,tags:Array.isArray(e.tags)?e.tags.filter(t=>typeof t=="string"):void 0}}function tW(e){if(!gn(e)||!Array.isArray(e.evals)||!gn(e.config))return null;const t=[];for(const n of e.evals){const r=eW(n);if(r===null)return null;t.push(r)}return{evals:t,config:e.config}}function yv(e){if(!gn(e)||typeof e.runId!="string"||!QG.has(e.status)||typeof e.startedAt!="string"||!gn(e.summary)||typeof e.summary.passed!="number"||typeof e.summary.failed!="number"||typeof e.summary.total!="number"||typeof e.summary.done!="number"||!Array.isArray(e.cases)||!gn(e.config))return null;for(const t of e.cases)if(!gn(t)||typeof t.id!="string"||typeof t.fileId!="string"||!JG.has(t.status))return null;return e}function nW(e){if(!gn(e)||!Array.isArray(e.runs)||e.activeRunId!==void 0&&typeof e.activeRunId!="string")return null;const t=[];for(const n of e.runs){const r=yv(n);if(r===null)return null;t.push(r)}return e.activeRunId===void 0?{runs:t}:{runs:t,activeRunId:e.activeRunId}}function co(){return Promise.resolve({status:501,ok:!1,body:null})}class rW{constructor(t,n,r={}){this.teamId=t,this.bootstrapRequest=null,this.composedSessionIds=new Set,this.writableSessionIds=new Set,this.logTails=new Map,this.logIndex=-1,this.logsReadAt=Number.NEGATIVE_INFINITY,this.logsReading=!1,this.turnCounts=new Map,this.turnCountsReading=!1,this.health=async()=>{const s=await this.bootstrap();return{status:s.status,ok:s.ok,body:s.ok?{ok:!0}:null}},this.meta=async()=>{const s=await this.bootstrap();return{status:s.status,ok:s.ok,body:s.body===null?null:{name:s.body.slug,dev:!1,basePath:"",version:s.body.cliVersion,readonly:!1}}},this.info=async()=>{const[s,a]=await Promise.all([this.bootstrap(),this.request("/info",LG).catch(()=>null)]);return{status:s.status,ok:s.ok,body:s.body===null?null:{...a?.body,name:s.body.slug,runtime:"cloud"}}},this.sessions=async()=>{const s=new URLSearchParams({limit:String(WG)}),a=await this.request(`/sessions?${s.toString()}`,BG);if(!a.ok||a.body===null)return{status:a.status,ok:!1,body:null};const l=a.body.sessions,c=l.map(f=>YG(f,this.turnCounts.get(f.sessionId)?.count));return this.writableSessionIds=new Set([...this.composedSessionIds,...c.filter(f=>f.followUpAllowed===!0).map(f=>f.sessionId)]),this.readTurnCounts(l),{status:200,ok:!0,body:{sessions:c}}},this.sessionById=async s=>{const a=await this.request(`/sessions/${encodeURIComponent(s)}`,KG);return a.ok?{status:a.status,ok:!0,body:{session:a.body}}:{status:a.status,ok:!1,body:null}},this.eventsText=async s=>{const a=await this.request(`/sessions/${encodeURIComponent(s)}`,FG);if(!a.ok||a.body===null)return new Response(null,{status:a.status});const l=a.body.map(c=>JSON.stringify(c)).join(`
18
18
  `);return new Response(l===""?"":`${l}
19
19
  `,{status:a.status,headers:{"content-type":"application/x-ndjson"}})},this.subscribeEvents=async(s,a,l)=>{const c=await this.request(`/sessions/${encodeURIComponent(s)}/events?afterEventIndex=${a-1}&waitMs=${NG}`,UG,{signal:l});if(!c.ok||c.body===null)return new Response(null,{status:c.status});const f=c.body.events.map(d=>JSON.stringify(d)).join(`
20
20
  `);return new Response(f===""?"":`${f}
21
- `,{status:c.status,headers:{"content-type":"application/x-ndjson"}})},this.logs=async(s=-1)=>{const a=this.logsFailure===void 0?{status:200,ok:!0,body:{entries:[],nextAfter:this.logIndex}}:{status:this.logsFailure,ok:!1,body:null};if(this.logsReading)return a;if(s<this.logIndex)this.logTails.clear(),this.logSessionId=void 0,this.logIndex=s;else if(Date.now()-this.logsReadAt<OG)return a;this.logsReadAt=Date.now(),this.logsReading=!0;const l=await this.request("/logs",qG).finally(()=>{this.logsReading=!1});if(!l.ok||l.body===null)return this.logsFailure=l.status===404?501:l.status,{status:this.logsFailure,ok:!1,body:null};this.logsFailure=void 0;const c=[];for(const f of l.body){if(f.lines.length===0)continue;const d=HG(this.logTails.get(f.sessionId)??[],f.lines);if(VG(this.logTails,f.sessionId,f.lines),d.length!==0){if(this.logSessionId!==f.sessionId){this.logSessionId=f.sessionId;const h=f.channelId===void 0?"":` (${f.channelId})`;c.push({index:++this.logIndex,at:"",line:`==> ${f.sessionId}${h} <==`})}for(const h of d)c.push({index:++this.logIndex,at:"",line:h})}}return{status:200,ok:!0,body:{entries:c,nextAfter:this.logIndex}}},this.createSession=s=>this.startSession(s),this.followUp=(s,a)=>this.writableSessionIds.has(s)?this.startSession(a,s):Promise.resolve({status:409,ok:!1,body:{error:"session_not_writable"}}),this.stopSession=()=>co(),this.sessionCost=()=>co(),this.resolveApproval=()=>co(),this.resolveAuth=()=>co(),this.artifacts=()=>co(),this.artifactContent=()=>Promise.resolve({status:501,ok:!1,bytes:new Uint8Array(0),truncated:!1}),this.dispatchSchedule=()=>co(),this.evalsList=()=>this.evalRequest("/evals",tW),this.evalsListRuns=()=>this.evalRequest("/evals/runs",nW),this.evalsStartRun=(s={})=>this.evalRequest("/evals/runs",yv,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({teamId:this.teamId,...s})}),this.evalsRunStatus=s=>this.evalRequest(`/evals/runs/${encodeURIComponent(s)}`,yv),this.evalsCancelRun=()=>co(),this.channelRequest=()=>co(),this.url=s=>s,this.basePath=`/api/v2/agentsdk/deployments/${encodeURIComponent(n)}`,this.capabilities=r.evals===!0?CG:oM,this.waitForRetry=r.waitForRetry??MG}async fetchJson(t,n){const r=t.includes("?")?"&":"?",s=await fetch(`${this.basePath}${t}${r}teamId=${this.teamId}`,n);return{response:s,value:await s.json().catch(()=>null)}}async request(t,n,r={}){const{response:s,value:a}=await this.fetchJson(t,r),l=n(a);return{status:l===null&&s.ok?502:s.status,ok:s.ok&&l!==null,body:l}}async evalRequest(t,n,r={}){const{response:s,value:a}=await this.fetchJson(t,r);if(!s.ok)return{status:s.status,ok:!1,body:a};const l=n(a);return{status:l===null?502:s.status,ok:l!==null,body:l}}async bootstrap(){this.bootstrapRequest??=this.request("",DG);const t=this.bootstrapRequest;try{const n=await t;return!n.ok&&this.bootstrapRequest===t&&(this.bootstrapRequest=null),n}catch(n){throw this.bootstrapRequest===t&&(this.bootstrapRequest=null),n}}async readTurnCounts(t){if(this.turnCountsReading)return;const n=new Set(t.map(a=>a.sessionId));for(const a of this.turnCounts.keys())n.has(a)||this.turnCounts.delete(a);const r=Date.now(),s=t.filter(a=>!a.customer&&this.turnCountStale(a,r));if(s.length!==0){this.turnCountsReading=!0;try{const a=new URLSearchParams({sessionIds:s.map(c=>c.sessionId).join(",")}),l=await this.request(`/session-turn-counts?${a.toString()}`,ZG).catch(()=>null);if(!l?.ok||l.body===null)return;for(const c of s){const f=this.turnCounts.get(c.sessionId)?.count,d=l.body.get(c.sessionId);this.turnCounts.set(c.sessionId,{activity:gR(c),count:d===void 0?f:Math.max(d,f??0),readAt:r})}}finally{this.turnCountsReading=!1}}}turnCountStale(t,n){const r=this.turnCounts.get(t.sessionId);return r===void 0||r.activity!==gR(t)?!0:lM.has(t.phase)&&n-r.readAt>=XG}async startSession(t,n){const r=await this.request("/sessions",jG,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({teamId:this.teamId,message:t,sessionId:n})});if(!r.ok||r.body===null)return{status:r.status,ok:!1,body:null};const s=r.body.sessionId??await this.waitForDeliveryBinding(r.body.deliveryId);return typeof s!="string"?s:(this.composedSessionIds.add(s),this.writableSessionIds.add(s),{status:r.status,ok:!0,body:{sessionId:s}})}async waitForDeliveryBinding(t){const n=Date.now();for(let r=0;r<mR;r++){const s=await this.request(`/session-deliveries/${encodeURIComponent(t)}`,zG);if(s.ok&&s.body?.status==="allocated")return s.body.sessionId;if(s.ok&&(s.body?.status==="skipped"||s.body?.status==="failed"))return{status:409,ok:!1,body:null};if(!(s.ok&&s.body?.status==="pending")&&s.status!==404)return{status:s.status,ok:!1,body:null};const a=Date.now()-n;if(a>=hR||r+1>=mR)break;await this.waitForRetry(Math.min(AG(r),hR-a))}return{status:504,ok:!1,body:null}}}function iW(e,t){const n=RG(document);switch(n.kind){case"local":return new wG(new kG(e,()=>t().authToken,()=>t().aliasToken));case"hosted":return new rW(n.teamId,n.deploymentSlug,{evals:n.evals})}}function al(e,t,n){return e.has(t)?n.some(r=>e.has(r))?"enabled":"read-only":"disabled"}function uM(e){const t=n=>al(e,yt.eventRead,[n]);return{composer:al(e,yt.sessionRead,[yt.sessionStart,yt.sessionFollowUp]),stop:t(yt.sessionStop),approvals:t(yt.approvalResolve),auth:t(yt.authResolve),logs:e.has(yt.logRead)?"enabled":"disabled",evals:al(e,yt.evalRead,[yt.evalRun]),artifacts:al(e,yt.artifactRead,[yt.artifactContent]),schedules:al(e,yt.infoRead,[yt.scheduleDispatch]),channelRoutes:al(e,yt.infoRead,[yt.channelInvoke])}}const sW=new Set(["actions.requested","actions.completed","action.result","action.approval_requested","action.approval_resolved","action.auth_requested","action.auth_resolved","subagent.called","subagent.completed","artifact.tagged"]),oW=new Set(["message.received","turn.started","message.completed","reasoning.appended","reasoning.completed","actions.requested","actions.completed","action.approval_requested","action.approval_resolved","action.auth_requested","action.auth_resolved","action.result","subagent.called","subagent.completed","artifact.tagged","turn.completed","turn.failed","agent.bound","session.failed"]),aW=12e4,bR=1e3;function lW(e){return e===404||e>=500&&e<600}function cM(){const e=window.location.pathname,t=e.replace(/\/playground\/?$/,"");return t===e?"":t}function uW(){const e=N7()!==null,t=e?NI():"";return{meta:{name:"agent",dev:!1,basePath:cM()},capabilities:uM(new Set),info:null,health:"unknown",sessions:[],current:null,localTrace:!1,view:"overview",running:!1,turnStartedAt:null,queued:[],composerDraft:null,authToken:"",aliasToken:t,aliasHosted:e,embedded:e&&O7(),transcript:[],traceEvents:[],historyLoading:!1,sessionCostUsd:null,barTitle:"No session",barId:"",externalUrl:null,drawerOpen:!1,overviewSection:"home",overviewRunId:null,surfaceFocusNonce:0,chatPanelOpen:!0,toast:null,evalCases:[],evalConfig:null,evalRun:null,evalRuns:[],evalNavReturn:!1}}class cW{constructor(t,n){this.api=t,this.stateStore=n,this.items=[],this.itemIndex=new Map,this.toolIds=new Set,this.assistantId=null,this.reasoningId=null,this.nestedAssistantIds=new Map,this.nestedReasoningIds=new Map,this.idSeq=0,this.streamAbort=null,this.streamRetry=null,this.snapshotOpen=!1,this.snapshotToken=0,this.lastIndex=-1,this.toastTimer=null,this.evalPollTimer=null,this.evalRestoreGeneration=0,this.evalPollGeneration=0,this.evalRestoreInFlight=null,this.booted=!1,this.pendingSessionDeepLink=null,this.aliasStreamInterrupted=!1,this.discardTurnBody=!1,this.activeTurnId=null,this.activeTurnStartedAt=null,this.pendingUserEchoes=[],this.pendingCreate=null,this.flushingQueue=!1,this.queueHeld=!1,this.knownSessionIds=new Set,this.sessionsSeeded=!1,this.subscribe=this.stateStore.subscribe,this.getState=()=>this.stateStore.getState(),this.getInitialState=()=>this.stateStore.getInitialState()}get historyOnly(){return this.state.meta.readonly===!0}get state(){return this.stateStore.getState()}hasCapability(t){return this.api.capabilities.has(t)}set(t){this.stateStore.setState(t)}commitTranscript(){this.set({transcript:this.items.slice()})}toast(t){this.set({toast:t}),this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>this.set({toast:null}),4e3)}setAuthToken(t){this.set({authToken:t})}async signInWithAliasToken(t){const n=t.trim();if(n==="")return{ok:!1,error:"Enter the deployment's alias token."};this.set({aliasToken:n});const r=await this.api.health();return!r.ok&&r.status===404?(this.set({aliasToken:""}),{ok:!1,error:"That token was not accepted. Check it and try again."}):(this.aliasStreamInterrupted=!1,this.booted=!1,await this.boot(),{ok:!0})}acceptAliasTokenHandoff(t){if(this.set({aliasToken:t}),!this.booted){this.boot();return}if(!this.aliasStreamInterrupted)return;this.aliasStreamInterrupted=!1;const n=this.state.current;n!==null&&this.streamAbort===null&&this.startStream(n.sessionId,this.lastIndex+1)}noteAliasAuthLoss(t){return!this.state.aliasHosted||t!==401&&t!==404||this.state.aliasToken.trim()===""?!1:(this.aliasStreamInterrupted=this.streamAbort!==null,this.stopStream(),this.set({aliasToken:""}),!0)}setDrawerOpen(t){this.set({drawerOpen:t})}setOverviewSection(t,n=null){this.set({overviewSection:t,overviewRunId:n}),this.setView("overview")}focusAgentSurface(){this.setOverviewSection("home"),this.set({drawerOpen:!1,surfaceFocusNonce:this.state.surfaceFocusNonce+1})}setChatPanelOpen(t){this.set({chatPanelOpen:t})}nextId(t){return this.idSeq+=1,`${t}-${this.idSeq}`}push(t){this.itemIndex.set(t.id,this.items.length),this.items.push(t)}update(t,n){const r=this.itemIndex.get(t);r!==void 0&&(this.items[r]={...this.items[r],...n})}appendItemText(t,n){const r=this.itemIndex.get(t),s=r===void 0?void 0:this.items[r],a=s!==void 0&&"text"in s?s.text:"";this.update(t,{text:pR(a,n)})}appendNestedText(t,n,r){this.updateSubagentChildren(t,s=>{const a=s.findIndex(f=>f.id===n),l=a<0?void 0:s[a];if(l===void 0||!("text"in l))return s;const c=s.slice();return c[a]={...l,text:pR(l.text,r)},c})}resetTranscript(){this.items=[],this.itemIndex.clear(),this.toolIds.clear(),this.assistantId=null,this.reasoningId=null,this.nestedAssistantIds.clear(),this.nestedReasoningIds.clear(),this.discardTurnBody=!1,this.activeTurnId=null,this.activeTurnStartedAt=null,this.queueHeld=!1,this.pendingUserEchoes=[],this.pendingCreate=null}subagentToolCallId(t){return`sub:${t}`}ensureSubagentTool(t,n){const r=this.subagentToolCallId(t),s=this.itemIndex.has(this.toolItemId(r));return this.upsertTool(r,s?"":"subagent:task",null,n)}getToolItem(t){const n=this.itemIndex.get(t);if(n===void 0)return null;const r=this.items[n];return r?.kind==="tool"?r:null}updateSubagentChildren(t,n,r=null){const s=this.ensureSubagentTool(t,r),a=this.getToolItem(s);if(a===null)return;const l=n([...a.children??[]]);this.update(s,{children:l})}upsertNestedTool(t,n,r,s,a){this.updateSubagentChildren(t,l=>{const c=l.findIndex(f=>f.kind==="tool"&&f.callId===n);if(c>=0){const f=l[c];if(f?.kind!=="tool")return l;const d=l.slice();return d[c]={...f,name:r||f.name,args:s??f.args},d}return l.push({kind:"tool",id:this.nextId("nested-tool"),callId:n,name:r,args:s??null,status:"running",output:null,startedAt:a??Date.now(),endedAt:null}),l},a)}finishNestedTool(t,n,r,s,a,l){this.updateSubagentChildren(t,c=>{const f=c.findIndex(b=>b.kind==="tool"&&b.callId===n),d=s==null?"(no output)":zn(s,4e3);if(f<0)return c.push({kind:"tool",id:this.nextId("nested-tool"),callId:n,name:r,args:null,status:a?"error":"done",output:d,outputRaw:s,startedAt:l??Date.now(),endedAt:l??Date.now()}),c;const h=c[f];if(h?.kind!=="tool")return c;const m=c.slice();return m[f]={...h,name:r||h.name,status:a?"error":"done",output:d,outputRaw:s,endedAt:l??Date.now()},m},l)}ensureNestedAssistant(t){const n=this.nestedAssistantIds.get(t);if(n)return n;const r=this.nextId("nested-asst");return this.nestedAssistantIds.set(t,r),this.updateSubagentChildren(t,s=>(s.push({kind:"assistant",id:r,text:"",streaming:!0}),s)),r}ensureNestedReasoning(t){const n=this.nestedReasoningIds.get(t);if(n)return n;const r=this.nextId("nested-think");return this.nestedReasoningIds.set(t,r),this.updateSubagentChildren(t,s=>(s.push({kind:"reasoning",id:r,text:"",open:!0}),s)),r}updateNestedChild(t,n,r){this.updateSubagentChildren(t,s=>{const a=s.findIndex(f=>f.id===n);if(a<0)return s;const l=s[a];if(l===void 0)return s;const c=s.slice();return c[a]={...l,...r},c})}pushUser(t){this.assistantId=null,this.reasoningId=null;const n=this.nextId("user");return this.push(t===null?{kind:"user",id:n,text:"",hidden:!0}:{kind:"user",id:n,text:t}),n}pushUserEcho(t){const n=this.pushUser(t);return this.pendingUserEchoes.push({id:n,text:t}),this.commitTranscript(),n}consumeUserEcho(t){const n=this.pendingUserEchoes[0];return n===void 0||t!==null&&n.text!==t?!1:(this.pendingUserEchoes.shift(),this.assistantId=null,this.reasoningId=null,!0)}rollbackUserEcho(t){const n=this.pendingUserEchoes.some(s=>s.id===t);if(this.pendingUserEchoes=this.pendingUserEchoes.filter(s=>s.id!==t),!n)return;const r=this.itemIndex.get(t);r!==void 0&&(this.items.splice(r,1),this.itemIndex.clear(),this.items.forEach((s,a)=>this.itemIndex.set(s.id,a))),this.commitTranscript()}pushDivider(t,n=!1,r){this.push({kind:"divider",id:this.nextId("div"),text:t,fail:n,url:r})}ensureAssistant(){if(this.assistantId)return this.assistantId;const t=this.nextId("asst");return this.push({kind:"assistant",id:t,text:"",streaming:!0}),this.assistantId=t,t}ensureReasoning(){if(this.reasoningId)return this.reasoningId;const t=this.nextId("think");return this.push({kind:"reasoning",id:t,text:"",open:!0}),this.reasoningId=t,t}toolItemId(t){return`tool:${t}`}upsertTool(t,n,r,s){const a=this.toolItemId(t);if(this.itemIndex.has(a)){const l={};if(n&&(l.name=n),r!=null&&(l.args=r),s!==null){const c=this.getToolItem(a);c!==null&&c.startedAt===null&&(l.startedAt=s)}return Object.keys(l).length>0&&this.update(a,l),a}return this.push({kind:"tool",id:a,callId:t,name:n,args:r??null,status:"running",output:null,startedAt:s??Date.now(),endedAt:null}),this.toolIds.add(a),a}markAwaiting(t,n,r){const s=this.upsertTool(t,n,r,Date.now());this.update(s,{status:"awaiting",gate:"approval",output:"Parked for human approval. Approve or deny to continue the turn."})}markAwaitingAuth(t,n,r,s){const a=this.upsertTool(t,n,null,Date.now());this.update(a,{status:"awaiting",gate:"auth",connection:r,authUrl:s,output:`Waiting for ${r} authorization.`})}clearAwaiting(t,n){const r=this.toolItemId(t);if(!this.itemIndex.has(r))return;const s=this.getToolItem(r)?.gate==="auth",a=n==="deny";this.update(r,{status:"running",output:a?s?"Canceled — tool will not execute.":"Denied — tool will not execute.":s?"Connected — retrying…":"Approved — executing…"})}finishTool(t,n,r,s,a){const l=this.upsertTool(t,n,null,a),c=r==null?"(no output)":zn(r,4e3);this.update(l,{status:s?"error":"done",output:c,outputRaw:r,endedAt:a??Date.now()}),this.activeTurnId===null&&!this.hasOpenTools()&&this.setRunning(!1)}hasOpenTools(){for(const t of this.toolIds){const n=this.itemIndex.get(t);if(n===void 0)continue;const r=this.items[n];if(r.kind==="tool"&&(r.status==="running"||r.status==="awaiting"))return!0}return!1}finalizeOpenTools(t,n){const r=t??Date.now();for(const s of this.toolIds){const a=this.itemIndex.get(s);if(a===void 0)continue;const l=this.items[a];l.kind==="tool"&&(l.status==="done"||l.status==="error"||l.status!=="awaiting"&&this.update(s,{status:"orphan",endedAt:r,output:n}))}}beginDiscardStaleTurnBody(){this.discardTurnBody=!0,this.activeTurnId=null}applyChat(t){if(this.discardTurnBody){if(t.type==="turn.started")this.discardTurnBody=!1;else if(t.type!=="message.received"&&t.type!=="agent.bound")return}else if(this.activeTurnId!==null&&t.turnId!==void 0&&t.turnId!==this.activeTurnId&&!sW.has(t.type)&&t.type!=="message.received"&&t.type!=="agent.bound")return;const n=t.data||{},r=Sl(t.at)||Date.now();switch(t.type){case"message.received":{const s=eM(n);this.consumeUserEcho(s)||this.pushUser(s);break}case"agent.bound":this.pushDivider(n.url?`cloud agent ${n.sdkAgentId}`:`agent ${n.sdkAgentId}`,!1,typeof n.url=="string"?n.url:void 0);break;case"turn.started":this.activeTurnId=t.turnId??null,this.activeTurnStartedAt=Sl(t.at),this.setRunning(!0);break;case"reasoning.appended":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.appendNestedText(n.parentCallId,this.ensureNestedReasoning(n.parentCallId),n):this.appendItemText(this.ensureReasoning(),n);break;case"reasoning.completed":if(typeof n.parentCallId=="string"&&n.parentCallId!==""){const s=this.nestedReasoningIds.get(n.parentCallId);s&&(this.updateNestedChild(n.parentCallId,s,{open:!1}),this.nestedReasoningIds.delete(n.parentCallId))}else this.reasoningId&&(this.update(this.reasoningId,{open:!1}),this.reasoningId=null);break;case"message.appended":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.appendNestedText(n.parentCallId,this.ensureNestedAssistant(n.parentCallId),n):this.appendItemText(this.ensureAssistant(),n);break;case"message.completed":{if(typeof n.parentCallId=="string"&&n.parentCallId!==""){const s=this.ensureNestedAssistant(n.parentCallId);this.updateNestedChild(n.parentCallId,s,{text:String(n.text??""),streaming:!1}),this.nestedAssistantIds.delete(n.parentCallId)}else{const s=this.ensureAssistant();this.update(s,{text:String(n.text??""),streaming:!1}),this.assistantId=null}break}case"actions.requested":this.setRunning(!0);for(const s of n.calls||[]){const a=typeof s.parentCallId=="string"&&s.parentCallId!==""?s.parentCallId:typeof n.parentCallId=="string"&&n.parentCallId!==""?n.parentCallId:void 0;a!==void 0?this.upsertNestedTool(a,s.callId,s.toolName,s.args,r):s.toolName==="task"||this.upsertTool(s.callId,s.toolName,s.args,r)}break;case"action.approval_requested":this.markAwaiting(n.callId,n.toolName,n.args);break;case"action.approval_resolved":this.clearAwaiting(n.callId,n.decision);break;case"action.auth_requested":this.markAwaitingAuth(n.callId,n.toolName,n.connection,n.authUrl);break;case"action.auth_resolved":this.clearAwaiting(n.callId,n.decision);break;case"action.result":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.finishNestedTool(n.parentCallId,n.callId,n.toolName,n.output,!!n.isError,r):n.toolName==="task"||this.finishTool(n.callId,n.toolName,n.output,!!n.isError,r);break;case"subagent.called":this.setRunning(!0),this.upsertTool(this.subagentToolCallId(n.callId),`subagent:${n.name||"task"}`,n.description,r);break;case"artifact.tagged":{const s=II(n);this.push({kind:"artifact",id:this.nextId("artifact"),artifactKind:s.kind,title:s.title,url:s.url,artifactId:s.artifactId,data:s.data});break}case"subagent.completed":this.nestedAssistantIds.delete(n.callId),this.nestedReasoningIds.delete(n.callId),this.finishTool(this.subagentToolCallId(n.callId),"","completed",!1,r);break;case"turn.completed":{this.activeTurnId=null,this.finalizeOpenTools(r,"(no result — turn completed before the tool reported back)");const s=this.activeTurnStartedAt;this.activeTurnStartedAt=null,this.push({kind:"turn-end",id:this.nextId("turn"),ms:s!==null&&Sl(t.at)!==null?Math.max(0,r-s):null,inTokens:typeof n.usage?.inputTokens=="number"?n.usage.inputTokens:void 0,outTokens:typeof n.usage?.outputTokens=="number"?n.usage.outputTokens:void 0,costUsd:typeof n.cost?.totalUsd=="number"?n.cost.totalUsd:void 0});const a=this.state.current?.sessionId;a&&this.refreshSessionCost(a),this.setRunning(this.hasOpenTools());break}case"turn.failed":this.activeTurnId=null,this.activeTurnStartedAt=null,this.finalizeOpenTools(r,`(no result — turn failed: ${n.message||"unknown"})`),this.pushDivider(`turn failed: ${n.message}`,!0),this.setRunning(this.hasOpenTools());break;case"session.waiting":this.setRunning(this.hasOpenTools()),this.refreshSessions();break;case"session.completed":this.finalizeOpenTools(r,"(no result — session completed)"),this.pushDivider("task session completed"),this.setRunning(!1),this.refreshSessions();break;case"session.failed":this.finalizeOpenTools(r,`(no result — session failed: ${n.message||"unknown"})`),this.pushDivider(`session failed: ${n.message}`,!0),this.setRunning(!1),this.refreshSessions();break}}ingestStreamEvent(t){if(t.index!==void 0){if(t.index<=this.lastIndex)return;this.lastIndex=t.index}this.state.traceEvents.push(t),this.applyChat(t)}flushStreamPaint(){this.set({transcript:this.items.slice(),traceEvents:this.state.traceEvents.slice()})}beginLocalTurn(){this.activeTurnStartedAt=Date.now(),this.setRunning(!0)}setRunning(t){this.set({running:t,turnStartedAt:t?this.activeTurnStartedAt:null}),t||queueMicrotask(()=>this.maybeFlushQueue())}setView(t){if(t==="logs"){this.set({view:"overview",overviewSection:"logs",evalNavReturn:!1});try{const s=new URL(window.location.href);s.searchParams.delete("view"),history.replaceState(null,"",s.toString())}catch{}DI("logs");return}const n=t==="overview"||t==="chat"||t==="trace"||t==="raw"||t==="evals"||t==="artifacts"?t:"overview",r=this.state.view==="evals"&&(n==="chat"||n==="trace"||n==="raw"||n==="artifacts");this.set({view:n,...n==="evals"||n==="overview"?{evalNavReturn:!1}:r?{evalNavReturn:!0}:{}}),r&&this.state.current===null&&this.attachEvalCaseSessionForView(n);try{const s=new URL(window.location.href);n==="overview"?s.searchParams.delete("view"):s.searchParams.set("view",n),history.replaceState(null,"",s.toString())}catch{}n==="evals"&&(this.refreshEvalRuns(),this.restoreEvalRun())}backToEvals(){this.set({evalNavReturn:!1}),this.setView("evals")}backToOverview(){this.set({evalNavReturn:!1}),this.setView("overview")}newChat(){this.historyOnly||!this.hasCapability(yt.sessionStart)||(this.deselectSession(),this.setView("chat"))}async refreshSessions(){if(!this.hasCapability(yt.sessionRead))return;let t;try{t=await this.api.sessions()}catch{return}if(!t.ok||!t.body){this.noteAliasAuthLoss(t.status);return}const n=t.body.sessions||[],r=sG({knownIds:this.knownSessionIds,sessions:n,currentSessionId:this.state.current?.sessionId??null,embedded:this.state.embedded,view:this.state.view,seeded:this.sessionsSeeded});this.knownSessionIds=new Set(n.map(l=>l.sessionId)),this.sessionsSeeded=!0;const s={sessions:n};let a=!1;if(this.state.current){const l=n.find(c=>c.sessionId===this.state.current?.sessionId);l?.continuationToken&&(s.current={...this.state.current,continuationToken:l.continuationToken}),l?.running===!0&&!this.state.running&&this.streamAbort===null&&!this.snapshotOpen&&!this.historyOnly?(s.running=!0,a=!0):l?.running===!1&&this.state.running&&!this.hasOpenTools()&&(s.running=!1)}if(this.set(s),s.running===!1&&queueMicrotask(()=>this.maybeFlushQueue()),a&&this.state.current!==null&&this.startStream(this.state.current.sessionId,this.lastIndex+1),r.action==="select"){const l=n.find(c=>c.sessionId===r.sessionId);l!==void 0&&this.selectSession(l);return}r.action==="reveal"&&this.revealEmbeddedTriggeredRun(r.sessionId,n)}revealEmbeddedTriggeredRun(t,n){if(this.state.view==="overview"){this.set({overviewSection:"runs"});return}const r=n.find(l=>l.sessionId===t),s=r?.channelId??"triggered",a=r?.title?.trim();this.toast(a===void 0||a===""?`New ${s} run started`:`New ${s} run: ${a}`)}isCurrent(t){return this.state.current!==null&&this.state.current.sessionId===t}stopStream(){this.streamAbort&&(this.streamAbort.abort(),this.streamAbort=null)}startStream(t,n){if(this.historyOnly||!this.hasCapability(yt.sessionStream))return;this.stopStream();const r=new AbortController;this.streamAbort=r;const s=Date.now(),a=this.lastIndex;this.api.subscribeEvents(t,n,r.signal).then(async l=>{if(!l.ok||!l.body){this.handleStreamPollFailure(t,r,l.status);return}this.streamRetry=null;const c=l.body.getReader(),f=new TextDecoder;let d="";for(;;){const h=await c.read();if(h.done){const y=this.lastIndex>a,k=Date.now()-s;this.scheduleReconnect(t,r,y?0:Math.max(0,bR-k));return}d+=f.decode(h.value,{stream:!0});const m=d.split(`
21
+ `,{status:c.status,headers:{"content-type":"application/x-ndjson"}})},this.logs=async(s=-1)=>{const a=this.logsFailure===void 0?{status:200,ok:!0,body:{entries:[],nextAfter:this.logIndex}}:{status:this.logsFailure,ok:!1,body:null};if(this.logsReading)return a;if(s<this.logIndex)this.logTails.clear(),this.logSessionId=void 0,this.logIndex=s;else if(Date.now()-this.logsReadAt<OG)return a;this.logsReadAt=Date.now(),this.logsReading=!0;const l=await this.request("/logs",qG).finally(()=>{this.logsReading=!1});if(!l.ok||l.body===null)return this.logsFailure=l.status===404?501:l.status,{status:this.logsFailure,ok:!1,body:null};this.logsFailure=void 0;const c=[];for(const f of l.body){if(f.lines.length===0)continue;const d=HG(this.logTails.get(f.sessionId)??[],f.lines);if(VG(this.logTails,f.sessionId,f.lines),d.length!==0){if(this.logSessionId!==f.sessionId){this.logSessionId=f.sessionId;const h=f.channelId===void 0?"":` (${f.channelId})`;c.push({index:++this.logIndex,at:"",line:`==> ${f.sessionId}${h} <==`})}for(const h of d)c.push({index:++this.logIndex,at:"",line:h})}}return{status:200,ok:!0,body:{entries:c,nextAfter:this.logIndex}}},this.createSession=s=>this.startSession(s),this.followUp=(s,a)=>this.writableSessionIds.has(s)?this.startSession(a,s):Promise.resolve({status:409,ok:!1,body:{error:"session_not_writable"}}),this.stopSession=()=>co(),this.sessionCost=()=>co(),this.resolveApproval=()=>co(),this.resolveAuth=()=>co(),this.artifacts=()=>co(),this.artifactContent=()=>Promise.resolve({status:501,ok:!1,bytes:new Uint8Array(0),truncated:!1}),this.dispatchSchedule=()=>co(),this.evalsList=()=>this.evalRequest("/evals",tW),this.evalsListRuns=()=>this.evalRequest("/evals/runs",nW),this.evalsStartRun=(s={})=>this.evalRequest("/evals/runs",yv,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({teamId:this.teamId,...s})}),this.evalsRunStatus=s=>this.evalRequest(`/evals/runs/${encodeURIComponent(s)}`,yv),this.evalsCancelRun=()=>co(),this.channelRequest=()=>co(),this.url=s=>s,this.basePath=`/api/v2/agentsdk/deployments/${encodeURIComponent(n)}`,this.capabilities=r.evals===!0?CG:oM,this.waitForRetry=r.waitForRetry??MG}async fetchJson(t,n){const r=t.includes("?")?"&":"?",s=await fetch(`${this.basePath}${t}${r}teamId=${this.teamId}`,n);return{response:s,value:await s.json().catch(()=>null)}}async request(t,n,r={}){const{response:s,value:a}=await this.fetchJson(t,r),l=n(a);return{status:l===null&&s.ok?502:s.status,ok:s.ok&&l!==null,body:l}}async evalRequest(t,n,r={}){const{response:s,value:a}=await this.fetchJson(t,r);if(!s.ok)return{status:s.status,ok:!1,body:a};const l=n(a);return{status:l===null?502:s.status,ok:l!==null,body:l}}async bootstrap(){this.bootstrapRequest??=this.request("",DG);const t=this.bootstrapRequest;try{const n=await t;return!n.ok&&this.bootstrapRequest===t&&(this.bootstrapRequest=null),n}catch(n){throw this.bootstrapRequest===t&&(this.bootstrapRequest=null),n}}async readTurnCounts(t){if(this.turnCountsReading)return;const n=new Set(t.map(a=>a.sessionId));for(const a of this.turnCounts.keys())n.has(a)||this.turnCounts.delete(a);const r=Date.now(),s=t.filter(a=>!a.customer&&this.turnCountStale(a,r));if(s.length!==0){this.turnCountsReading=!0;try{const a=new URLSearchParams({sessionIds:s.map(c=>c.sessionId).join(",")}),l=await this.request(`/session-turn-counts?${a.toString()}`,ZG).catch(()=>null);if(!l?.ok||l.body===null)return;for(const c of s){const f=this.turnCounts.get(c.sessionId)?.count,d=l.body.get(c.sessionId);this.turnCounts.set(c.sessionId,{activity:gR(c),count:d===void 0?f:Math.max(d,f??0),readAt:r})}}finally{this.turnCountsReading=!1}}}turnCountStale(t,n){const r=this.turnCounts.get(t.sessionId);return r===void 0||r.activity!==gR(t)?!0:lM.has(t.phase)&&n-r.readAt>=XG}async startSession(t,n){const r=await this.request("/sessions",jG,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({teamId:this.teamId,message:t,sessionId:n})});if(!r.ok||r.body===null)return{status:r.status,ok:!1,body:null};const s=r.body.sessionId??await this.waitForDeliveryBinding(r.body.deliveryId);return typeof s!="string"?s:(this.composedSessionIds.add(s),this.writableSessionIds.add(s),{status:r.status,ok:!0,body:{sessionId:s}})}async waitForDeliveryBinding(t){const n=Date.now();for(let r=0;r<mR;r++){const s=await this.request(`/session-deliveries/${encodeURIComponent(t)}`,zG);if(s.ok&&s.body?.status==="allocated")return s.body.sessionId;if(s.ok&&(s.body?.status==="skipped"||s.body?.status==="failed"))return{status:409,ok:!1,body:null};if(!(s.ok&&s.body?.status==="pending")&&s.status!==404)return{status:s.status,ok:!1,body:null};const a=Date.now()-n;if(a>=hR||r+1>=mR)break;await this.waitForRetry(Math.min(AG(r),hR-a))}return{status:504,ok:!1,body:null}}}function iW(e,t){const n=RG(document);switch(n.kind){case"local":return new wG(new kG(e,()=>t().authToken,()=>t().aliasToken));case"hosted":return new rW(n.teamId,n.deploymentSlug,{evals:n.evals})}}function al(e,t,n){return e.has(t)?n.some(r=>e.has(r))?"enabled":"read-only":"disabled"}function uM(e){const t=n=>al(e,yt.eventRead,[n]);return{composer:al(e,yt.sessionRead,[yt.sessionStart,yt.sessionFollowUp]),stop:t(yt.sessionStop),approvals:t(yt.approvalResolve),auth:t(yt.authResolve),logs:e.has(yt.logRead)?"enabled":"disabled",evals:al(e,yt.evalRead,[yt.evalRun]),artifacts:al(e,yt.artifactRead,[yt.artifactContent]),schedules:al(e,yt.infoRead,[yt.scheduleDispatch]),channelRoutes:al(e,yt.infoRead,[yt.channelInvoke])}}const sW=new Set(["actions.requested","actions.completed","action.result","action.approval_requested","action.approval_resolved","action.auth_requested","action.auth_resolved","subagent.called","subagent.completed","artifact.tagged"]),oW=new Set(["message.received","turn.started","message.completed","reasoning.appended","reasoning.completed","actions.requested","actions.completed","action.approval_requested","action.approval_resolved","action.auth_requested","action.auth_resolved","action.result","subagent.called","subagent.completed","artifact.tagged","turn.completed","turn.failed","agent.bound","session.failed"]),aW=12e4,bR=1e3;function lW(e){return e===404||e>=500&&e<600}function cM(){const e=window.location.pathname,t=e.replace(/\/playground\/?$/,"");return t===e?"":t}function uW(){const e=N7()!==null,t=e?NI():"";return{meta:{name:"agent",dev:!1,basePath:cM()},capabilities:uM(new Set),info:null,health:"unknown",sessions:[],current:null,localTrace:!1,view:"overview",running:!1,turnStartedAt:null,queued:[],composerDraft:null,authToken:"",aliasToken:t,aliasHosted:e,embedded:e&&O7(),transcript:[],traceEvents:[],historyLoading:!1,sessionCostUsd:null,barTitle:"No session",barId:"",externalUrl:null,drawerOpen:!1,overviewSection:"home",overviewRunId:null,surfaceFocusNonce:0,chatPanelOpen:!0,toast:null,evalCases:[],evalConfig:null,evalRun:null,evalRuns:[],evalNavReturn:!1}}class cW{constructor(t,n){this.api=t,this.stateStore=n,this.items=[],this.itemIndex=new Map,this.toolIds=new Set,this.assistantId=null,this.reasoningId=null,this.nestedAssistantIds=new Map,this.nestedReasoningIds=new Map,this.idSeq=0,this.streamAbort=null,this.streamRetry=null,this.snapshotOpen=!1,this.snapshotToken=0,this.lastIndex=-1,this.toastTimer=null,this.evalPollTimer=null,this.evalRestoreGeneration=0,this.evalPollGeneration=0,this.evalRestoreInFlight=null,this.booted=!1,this.pendingSessionDeepLink=null,this.aliasStreamInterrupted=!1,this.discardTurnBody=!1,this.activeTurnId=null,this.activeTurnStartedAt=null,this.pendingUserEchoes=[],this.pendingCreate=null,this.flushingQueue=!1,this.queueHeld=!1,this.knownSessionIds=new Set,this.sessionsSeeded=!1,this.subscribe=this.stateStore.subscribe,this.getState=()=>this.stateStore.getState(),this.getInitialState=()=>this.stateStore.getInitialState()}get historyOnly(){return this.state.meta.readonly===!0}get state(){return this.stateStore.getState()}hasCapability(t){return this.api.capabilities.has(t)}set(t){this.stateStore.setState(t)}commitTranscript(){this.set({transcript:this.items.slice()})}toast(t){this.set({toast:t}),this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>this.set({toast:null}),4e3)}setAuthToken(t){this.set({authToken:t})}async signInWithAliasToken(t){const n=t.trim();if(n==="")return{ok:!1,error:"Enter the deployment's alias token."};this.set({aliasToken:n});const r=await this.api.health();return!r.ok&&r.status===404?(this.set({aliasToken:""}),{ok:!1,error:"That token was not accepted. Check it and try again."}):(this.aliasStreamInterrupted=!1,this.booted=!1,await this.boot(),{ok:!0})}acceptAliasTokenHandoff(t){if(this.set({aliasToken:t}),!this.booted){this.boot();return}if(!this.aliasStreamInterrupted)return;this.aliasStreamInterrupted=!1;const n=this.state.current;n!==null&&this.streamAbort===null&&this.startStream(n.sessionId,this.lastIndex+1)}noteAliasAuthLoss(t){return!this.state.aliasHosted||t!==401&&t!==404||this.state.aliasToken.trim()===""?!1:(this.aliasStreamInterrupted=this.streamAbort!==null,this.stopStream(),this.set({aliasToken:""}),!0)}setDrawerOpen(t){this.set({drawerOpen:t})}setOverviewSection(t,n=null){this.set({overviewSection:t,overviewRunId:n}),this.setView("overview")}focusAgentSurface(){this.setOverviewSection("home"),this.set({drawerOpen:!1,surfaceFocusNonce:this.state.surfaceFocusNonce+1})}setChatPanelOpen(t){this.set({chatPanelOpen:t})}nextId(t){return this.idSeq+=1,`${t}-${this.idSeq}`}push(t){this.itemIndex.set(t.id,this.items.length),this.items.push(t)}update(t,n){const r=this.itemIndex.get(t);r!==void 0&&(this.items[r]={...this.items[r],...n})}itemText(t){const n=this.itemIndex.get(t),r=n===void 0?void 0:this.items[n];return r!==void 0&&"text"in r?r.text:""}appendItemText(t,n){this.update(t,{text:pR(this.itemText(t),n)})}appendNestedText(t,n,r){this.updateSubagentChildren(t,s=>{const a=s.findIndex(f=>f.id===n),l=a<0?void 0:s[a];if(l===void 0||!("text"in l))return s;const c=s.slice();return c[a]={...l,text:pR(l.text,r)},c})}resetTranscript(){this.items=[],this.itemIndex.clear(),this.toolIds.clear(),this.assistantId=null,this.reasoningId=null,this.nestedAssistantIds.clear(),this.nestedReasoningIds.clear(),this.discardTurnBody=!1,this.activeTurnId=null,this.activeTurnStartedAt=null,this.queueHeld=!1,this.pendingUserEchoes=[],this.pendingCreate=null}subagentToolCallId(t){return`sub:${t}`}ensureSubagentTool(t,n){const r=this.subagentToolCallId(t),s=this.itemIndex.has(this.toolItemId(r));return this.upsertTool(r,s?"":"subagent:task",null,n)}getToolItem(t){const n=this.itemIndex.get(t);if(n===void 0)return null;const r=this.items[n];return r?.kind==="tool"?r:null}updateSubagentChildren(t,n,r=null){const s=this.ensureSubagentTool(t,r),a=this.getToolItem(s);if(a===null)return;const l=n([...a.children??[]]);this.update(s,{children:l})}upsertNestedTool(t,n,r,s,a){this.updateSubagentChildren(t,l=>{const c=l.findIndex(f=>f.kind==="tool"&&f.callId===n);if(c>=0){const f=l[c];if(f?.kind!=="tool")return l;const d=l.slice();return d[c]={...f,name:r||f.name,args:s??f.args},d}return l.push({kind:"tool",id:this.nextId("nested-tool"),callId:n,name:r,args:s??null,status:"running",output:null,startedAt:a??Date.now(),endedAt:null}),l},a)}finishNestedTool(t,n,r,s,a,l){this.updateSubagentChildren(t,c=>{const f=c.findIndex(b=>b.kind==="tool"&&b.callId===n),d=s==null?"(no output)":zn(s,4e3);if(f<0)return c.push({kind:"tool",id:this.nextId("nested-tool"),callId:n,name:r,args:null,status:a?"error":"done",output:d,outputRaw:s,startedAt:l??Date.now(),endedAt:l??Date.now()}),c;const h=c[f];if(h?.kind!=="tool")return c;const m=c.slice();return m[f]={...h,name:r||h.name,status:a?"error":"done",output:d,outputRaw:s,endedAt:l??Date.now()},m},l)}ensureNestedAssistant(t){const n=this.nestedAssistantIds.get(t);if(n)return n;const r=this.nextId("nested-asst");return this.nestedAssistantIds.set(t,r),this.updateSubagentChildren(t,s=>(s.push({kind:"assistant",id:r,text:"",streaming:!0}),s)),r}ensureNestedReasoning(t){const n=this.nestedReasoningIds.get(t);if(n)return n;const r=this.nextId("nested-think");return this.nestedReasoningIds.set(t,r),this.updateSubagentChildren(t,s=>(s.push({kind:"reasoning",id:r,text:"",open:!0}),s)),r}updateNestedChild(t,n,r){this.updateSubagentChildren(t,s=>{const a=s.findIndex(f=>f.id===n);if(a<0)return s;const l=s[a];if(l===void 0)return s;const c=s.slice();return c[a]={...l,...r},c})}pushUser(t){this.assistantId=null,this.reasoningId=null;const n=this.nextId("user");return this.push(t===null?{kind:"user",id:n,text:"",hidden:!0}:{kind:"user",id:n,text:t}),n}pushUserEcho(t){const n=this.pushUser(t);return this.pendingUserEchoes.push({id:n,text:t}),this.commitTranscript(),n}consumeUserEcho(t){const n=this.pendingUserEchoes[0];return n===void 0||t!==null&&n.text!==t?!1:(this.pendingUserEchoes.shift(),this.assistantId=null,this.reasoningId=null,!0)}rollbackUserEcho(t){const n=this.pendingUserEchoes.some(s=>s.id===t);if(this.pendingUserEchoes=this.pendingUserEchoes.filter(s=>s.id!==t),!n)return;const r=this.itemIndex.get(t);r!==void 0&&(this.items.splice(r,1),this.itemIndex.clear(),this.items.forEach((s,a)=>this.itemIndex.set(s.id,a))),this.commitTranscript()}pushDivider(t,n=!1,r){this.push({kind:"divider",id:this.nextId("div"),text:t,fail:n,url:r})}ensureAssistant(){if(this.assistantId)return this.assistantId;const t=this.nextId("asst");return this.push({kind:"assistant",id:t,text:"",streaming:!0}),this.assistantId=t,t}ensureReasoning(){if(this.reasoningId)return this.reasoningId;const t=this.nextId("think");return this.push({kind:"reasoning",id:t,text:"",open:!0}),this.reasoningId=t,t}toolItemId(t){return`tool:${t}`}upsertTool(t,n,r,s){const a=this.toolItemId(t);if(this.itemIndex.has(a)){const l={};if(n&&(l.name=n),r!=null&&(l.args=r),s!==null){const c=this.getToolItem(a);c!==null&&c.startedAt===null&&(l.startedAt=s)}return Object.keys(l).length>0&&this.update(a,l),a}return this.push({kind:"tool",id:a,callId:t,name:n,args:r??null,status:"running",output:null,startedAt:s??Date.now(),endedAt:null}),this.toolIds.add(a),a}markAwaiting(t,n,r){const s=this.upsertTool(t,n,r,Date.now());this.update(s,{status:"awaiting",gate:"approval",output:"Parked for human approval. Approve or deny to continue the turn."})}markAwaitingAuth(t,n,r,s){const a=this.upsertTool(t,n,null,Date.now());this.update(a,{status:"awaiting",gate:"auth",connection:r,authUrl:s,output:`Waiting for ${r} authorization.`})}clearAwaiting(t,n){const r=this.toolItemId(t);if(!this.itemIndex.has(r))return;const s=this.getToolItem(r)?.gate==="auth",a=n==="deny";this.update(r,{status:"running",output:a?s?"Canceled — tool will not execute.":"Denied — tool will not execute.":s?"Connected — retrying…":"Approved — executing…"})}finishTool(t,n,r,s,a){const l=this.upsertTool(t,n,null,a),c=r==null?"(no output)":zn(r,4e3);this.update(l,{status:s?"error":"done",output:c,outputRaw:r,endedAt:a??Date.now()}),this.activeTurnId===null&&!this.hasOpenTools()&&this.setRunning(!1)}hasOpenTools(){for(const t of this.toolIds){const n=this.itemIndex.get(t);if(n===void 0)continue;const r=this.items[n];if(r.kind==="tool"&&(r.status==="running"||r.status==="awaiting"))return!0}return!1}finalizeOpenTools(t,n){const r=t??Date.now();for(const s of this.toolIds){const a=this.itemIndex.get(s);if(a===void 0)continue;const l=this.items[a];l.kind==="tool"&&(l.status==="done"||l.status==="error"||l.status!=="awaiting"&&this.update(s,{status:"orphan",endedAt:r,output:n}))}}beginDiscardStaleTurnBody(){this.discardTurnBody=!0,this.activeTurnId=null}applyChat(t){if(this.discardTurnBody){if(t.type==="turn.started")this.discardTurnBody=!1;else if(t.type!=="message.received"&&t.type!=="agent.bound")return}else if(this.activeTurnId!==null&&t.turnId!==void 0&&t.turnId!==this.activeTurnId&&!sW.has(t.type)&&t.type!=="message.received"&&t.type!=="agent.bound")return;const n=t.data||{},r=Sl(t.at)||Date.now();switch(t.type){case"message.received":{const s=eM(n);this.consumeUserEcho(s)||this.pushUser(s);break}case"agent.bound":this.pushDivider(n.url?`cloud agent ${n.sdkAgentId}`:`agent ${n.sdkAgentId}`,!1,typeof n.url=="string"?n.url:void 0);break;case"turn.started":this.activeTurnId=t.turnId??null,this.activeTurnStartedAt=Sl(t.at),this.setRunning(!0);break;case"reasoning.appended":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.appendNestedText(n.parentCallId,this.ensureNestedReasoning(n.parentCallId),n):this.appendItemText(this.ensureReasoning(),n);break;case"reasoning.completed":if(typeof n.parentCallId=="string"&&n.parentCallId!==""){const s=this.nestedReasoningIds.get(n.parentCallId);s&&(this.updateNestedChild(n.parentCallId,s,{open:!1}),this.nestedReasoningIds.delete(n.parentCallId))}else this.reasoningId&&(this.update(this.reasoningId,{open:!1}),this.reasoningId=null);break;case"message.appended":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.appendNestedText(n.parentCallId,this.ensureNestedAssistant(n.parentCallId),n):this.appendItemText(this.ensureAssistant(),n);break;case"message.completed":{const s=t.liveTruncated===!0,a=l=>s&&l!==""?l:String(n.text??"");if(typeof n.parentCallId=="string"&&n.parentCallId!==""){const l=n.parentCallId,c=this.ensureNestedAssistant(l);this.updateSubagentChildren(l,f=>{const d=f.findIndex(b=>b.id===c),h=d<0?void 0:f[d];if(h===void 0||!("text"in h))return f;const m=f.slice();return m[d]={...h,text:a(h.text),streaming:!1},m}),this.nestedAssistantIds.delete(l)}else{const l=this.ensureAssistant();this.update(l,{text:a(this.itemText(l)),streaming:!1}),this.assistantId=null}break}case"actions.requested":this.setRunning(!0);for(const s of n.calls||[]){const a=typeof s.parentCallId=="string"&&s.parentCallId!==""?s.parentCallId:typeof n.parentCallId=="string"&&n.parentCallId!==""?n.parentCallId:void 0;a!==void 0?this.upsertNestedTool(a,s.callId,s.toolName,s.args,r):s.toolName==="task"||this.upsertTool(s.callId,s.toolName,s.args,r)}break;case"action.approval_requested":this.markAwaiting(n.callId,n.toolName,n.args);break;case"action.approval_resolved":this.clearAwaiting(n.callId,n.decision);break;case"action.auth_requested":this.markAwaitingAuth(n.callId,n.toolName,n.connection,n.authUrl);break;case"action.auth_resolved":this.clearAwaiting(n.callId,n.decision);break;case"action.result":typeof n.parentCallId=="string"&&n.parentCallId!==""?this.finishNestedTool(n.parentCallId,n.callId,n.toolName,n.output,!!n.isError,r):n.toolName==="task"||this.finishTool(n.callId,n.toolName,n.output,!!n.isError,r);break;case"subagent.called":this.setRunning(!0),this.upsertTool(this.subagentToolCallId(n.callId),`subagent:${n.name||"task"}`,n.description,r);break;case"artifact.tagged":{const s=II(n);this.push({kind:"artifact",id:this.nextId("artifact"),artifactKind:s.kind,title:s.title,url:s.url,artifactId:s.artifactId,data:s.data});break}case"subagent.completed":this.nestedAssistantIds.delete(n.callId),this.nestedReasoningIds.delete(n.callId),this.finishTool(this.subagentToolCallId(n.callId),"","completed",!1,r);break;case"turn.completed":{this.activeTurnId=null,this.finalizeOpenTools(r,"(no result — turn completed before the tool reported back)");const s=this.activeTurnStartedAt;this.activeTurnStartedAt=null,this.push({kind:"turn-end",id:this.nextId("turn"),ms:s!==null&&Sl(t.at)!==null?Math.max(0,r-s):null,inTokens:typeof n.usage?.inputTokens=="number"?n.usage.inputTokens:void 0,outTokens:typeof n.usage?.outputTokens=="number"?n.usage.outputTokens:void 0,costUsd:typeof n.cost?.totalUsd=="number"?n.cost.totalUsd:void 0});const a=this.state.current?.sessionId;a&&this.refreshSessionCost(a),this.setRunning(this.hasOpenTools());break}case"turn.failed":this.activeTurnId=null,this.activeTurnStartedAt=null,this.finalizeOpenTools(r,`(no result — turn failed: ${n.message||"unknown"})`),this.pushDivider(`turn failed: ${n.message}`,!0),this.setRunning(this.hasOpenTools());break;case"session.waiting":this.setRunning(this.hasOpenTools()),this.refreshSessions();break;case"session.completed":this.finalizeOpenTools(r,"(no result — session completed)"),this.pushDivider("task session completed"),this.setRunning(!1),this.refreshSessions();break;case"session.failed":this.finalizeOpenTools(r,`(no result — session failed: ${n.message||"unknown"})`),this.pushDivider(`session failed: ${n.message}`,!0),this.setRunning(!1),this.refreshSessions();break}}ingestStreamEvent(t){if(t.index!==void 0){if(t.index<=this.lastIndex)return;this.lastIndex=t.index}this.state.traceEvents.push(t),this.applyChat(t)}flushStreamPaint(){this.set({transcript:this.items.slice(),traceEvents:this.state.traceEvents.slice()})}beginLocalTurn(){this.activeTurnStartedAt=Date.now(),this.setRunning(!0)}setRunning(t){this.set({running:t,turnStartedAt:t?this.activeTurnStartedAt:null}),t||queueMicrotask(()=>this.maybeFlushQueue())}setView(t){if(t==="logs"){this.set({view:"overview",overviewSection:"logs",evalNavReturn:!1});try{const s=new URL(window.location.href);s.searchParams.delete("view"),history.replaceState(null,"",s.toString())}catch{}DI("logs");return}const n=t==="overview"||t==="chat"||t==="trace"||t==="raw"||t==="evals"||t==="artifacts"?t:"overview",r=this.state.view==="evals"&&(n==="chat"||n==="trace"||n==="raw"||n==="artifacts");this.set({view:n,...n==="evals"||n==="overview"?{evalNavReturn:!1}:r?{evalNavReturn:!0}:{}}),r&&this.state.current===null&&this.attachEvalCaseSessionForView(n);try{const s=new URL(window.location.href);n==="overview"?s.searchParams.delete("view"):s.searchParams.set("view",n),history.replaceState(null,"",s.toString())}catch{}n==="evals"&&(this.refreshEvalRuns(),this.restoreEvalRun())}backToEvals(){this.set({evalNavReturn:!1}),this.setView("evals")}backToOverview(){this.set({evalNavReturn:!1}),this.setView("overview")}newChat(){this.historyOnly||!this.hasCapability(yt.sessionStart)||(this.deselectSession(),this.setView("chat"))}async refreshSessions(){if(!this.hasCapability(yt.sessionRead))return;let t;try{t=await this.api.sessions()}catch{return}if(!t.ok||!t.body){this.noteAliasAuthLoss(t.status);return}const n=t.body.sessions||[],r=sG({knownIds:this.knownSessionIds,sessions:n,currentSessionId:this.state.current?.sessionId??null,embedded:this.state.embedded,view:this.state.view,seeded:this.sessionsSeeded});this.knownSessionIds=new Set(n.map(l=>l.sessionId)),this.sessionsSeeded=!0;const s={sessions:n};let a=!1;if(this.state.current){const l=n.find(c=>c.sessionId===this.state.current?.sessionId);l?.continuationToken&&(s.current={...this.state.current,continuationToken:l.continuationToken}),l?.running===!0&&!this.state.running&&this.streamAbort===null&&!this.snapshotOpen&&!this.historyOnly?(s.running=!0,a=!0):l?.running===!1&&this.state.running&&!this.hasOpenTools()&&(s.running=!1)}if(this.set(s),s.running===!1&&queueMicrotask(()=>this.maybeFlushQueue()),a&&this.state.current!==null&&this.startStream(this.state.current.sessionId,this.lastIndex+1),r.action==="select"){const l=n.find(c=>c.sessionId===r.sessionId);l!==void 0&&this.selectSession(l);return}r.action==="reveal"&&this.revealEmbeddedTriggeredRun(r.sessionId,n)}revealEmbeddedTriggeredRun(t,n){if(this.state.view==="overview"){this.set({overviewSection:"runs"});return}const r=n.find(l=>l.sessionId===t),s=r?.channelId??"triggered",a=r?.title?.trim();this.toast(a===void 0||a===""?`New ${s} run started`:`New ${s} run: ${a}`)}isCurrent(t){return this.state.current!==null&&this.state.current.sessionId===t}stopStream(){this.streamAbort&&(this.streamAbort.abort(),this.streamAbort=null)}startStream(t,n){if(this.historyOnly||!this.hasCapability(yt.sessionStream))return;this.stopStream();const r=new AbortController;this.streamAbort=r;const s=Date.now(),a=this.lastIndex;this.api.subscribeEvents(t,n,r.signal).then(async l=>{if(!l.ok||!l.body){this.handleStreamPollFailure(t,r,l.status);return}this.streamRetry=null;const c=l.body.getReader(),f=new TextDecoder;let d="";for(;;){const h=await c.read();if(h.done){const y=this.lastIndex>a,k=Date.now()-s;this.scheduleReconnect(t,r,y?0:Math.max(0,bR-k));return}d+=f.decode(h.value,{stream:!0});const m=d.split(`
22
22
  `);d=m.pop()||"";const b=[];for(const y of m){if(r.signal.aborted)return;if(!y||!y.trim())continue;let k=null;try{k=JSON.parse(y)}catch{continue}k!==null&&b.push(k)}if(r.signal.aborted)return;for(const y of b)this.ingestStreamEvent(y);b.length>0&&this.flushStreamPaint()}}).catch(()=>{r.signal.aborted||this.scheduleReconnect(t,r)})}handleStreamPollFailure(t,n,r){if(lW(r)&&this.claimStreamRetryBudget(t)){this.scheduleReconnect(t,n);return}this.streamRetry=null,this.streamAbort===n&&(this.streamAbort=null),this.toast(`Stream failed (${r})`)}claimStreamRetryBudget(t){const n=Date.now();return this.streamRetry===null||this.streamRetry.sessionId!==t||this.listedRunning(t)?(this.streamRetry={sessionId:t,startedAt:n},!0):n-this.streamRetry.startedAt<aW}listedRunning(t){return this.state.sessions.some(n=>n.sessionId===t&&n.running===!0)}scheduleReconnect(t,n,r=bR){n.signal.aborted||this.historyOnly||this.isCurrent(t)&&setTimeout(()=>{!this.isCurrent(t)||this.streamAbort!==n||this.startStream(t,this.lastIndex+1)},r)}async refreshSessionCost(t){if(this.hasCapability(yt.sessionCost))try{const n=await this.api.sessionCost(t);if(!n.ok||n.body===null||this.state.current?.sessionId!==t)return;this.set({sessionCostUsd:n.body.source==="unavailable"?null:n.body.costUsd})}catch{}}selectSession(t){if(this.isCurrent(t.sessionId)&&(this.streamAbort!==null||this.snapshotOpen)){this.set({chatPanelOpen:!0,evalNavReturn:!1}),this.showSelectedSession(t.sessionId);return}this.stopStream(),this.streamRetry=null,this.resetTranscript(),this.lastIndex=-1,this.state.traceEvents=[],this.set({localTrace:!1,current:{sessionId:t.sessionId,channelId:t.channelId,mode:t.mode,followUpAllowed:t.followUpAllowed,continuationToken:t.continuationToken,externalUrl:t.externalUrl||null,prUrl:t.prUrl||null},running:!!t.running,turnStartedAt:null,queued:[],composerDraft:null,barTitle:t.title||"Session",barId:t.sessionId,externalUrl:t.externalUrl||null,transcript:[],traceEvents:[],sessionCostUsd:null,chatPanelOpen:!0,evalNavReturn:!1}),this.showSelectedSession(t.sessionId),this.refreshSessions(),this.refreshSessionCost(t.sessionId),this.loadEventsSnapshot(t.sessionId,!!t.running)}showSelectedSession(t){this.syncSessionUrl(t),(this.state.view==="evals"||this.state.view==="overview")&&(this.setView("chat"),this.set({evalNavReturn:!1}))}syncSessionUrl(t){try{const n=new URL(window.location.href);t?n.searchParams.set("sessionId",t):n.searchParams.delete("sessionId"),history.replaceState(null,"",n.toString())}catch{}}async loadEventsSnapshot(t,n){if(!this.hasCapability(yt.eventRead))return;const r=++this.snapshotToken;this.snapshotOpen=!0,this.set({historyLoading:!0}),this.stopStream();try{const s=await this.api.eventsText(t);if(r!==this.snapshotToken||!this.isCurrent(t))return;if(!s.ok){this.historyOnly?this.toast(`Could not load trace (${s.status})`):(this.toast(`Could not load trace (${s.status}) — falling back to stream`),this.startStream(t,0));return}const a=await s.text();if(r!==this.snapshotToken||!this.isCurrent(t)||(await this.refreshSessions(),r!==this.snapshotToken||!this.isCurrent(t)))return;const l=this.state.sessions.find(d=>d.sessionId===t),c=l!==void 0?l.running===!0:n;this.ingestEventsCompact(bv(a),c);const f=this.hasOpenTools()||c;this.setRunning(f),f&&!this.historyOnly&&this.startStream(t,this.lastIndex+1)}catch(s){if(r!==this.snapshotToken||!this.isCurrent(t))return;this.toast(`Trace load failed: ${ty(s)}`),this.historyOnly||this.startStream(t,0)}finally{r===this.snapshotToken&&(this.snapshotOpen=!1,this.set({historyLoading:!1}))}}ingestEventsCompact(t,n=!1){this.resetTranscript(),this.lastIndex=-1;for(const r of t){const s=oW.has(r.type)||n&&r.type==="message.appended";s&&this.applyChat(r),!(!s&&r.type==="message.appended")&&typeof r.index=="number"&&r.index>this.lastIndex&&(this.lastIndex=r.index)}this.setRunning(this.hasOpenTools()||n),this.set({traceEvents:t.slice(),transcript:this.items.slice()})}deselectSession(){this.stopStream(),this.streamRetry=null,this.resetTranscript(),this.lastIndex=-1,this.set({current:null,localTrace:!1,running:!1,turnStartedAt:null,queued:[],composerDraft:null,transcript:[],traceEvents:[],sessionCostUsd:null,barTitle:"No session",barId:"",externalUrl:null,chatPanelOpen:!0,evalNavReturn:!1}),this.syncSessionUrl(null),this.state.embedded||this.setView("overview"),this.refreshSessions()}loadLocalTrace(t,n){this.stopStream(),this.resetTranscript(),this.lastIndex=-1;const r=bv(t);if(r.length===0){this.toast("No session events found in that file."),this.deselectSession();return}const s=r[0].sessionId||"local-trace";this.set({current:null,localTrace:!0,running:!1,turnStartedAt:null,queued:[],composerDraft:null,barTitle:"Trace",barId:`${n||s} · ${r.length} events`,externalUrl:null,chatPanelOpen:!0}),this.setView("trace"),this.syncSessionUrl(null),this.ingestEventsCompact(r),this.toast(`Loaded ${r.length} events — Trace timeline ready`)}slashCommands(){return Jh(this.state.info?.channels)}async sendMessage(t,n={}){const r=t.trim();if(!r||this.state.localTrace||this.historyOnly)return!1;const s=this.state.current;if(lG(r))return this.hasCapability(yt.channelInvoke)?this.invokeSlashCommand(r):(this.toast("Channel commands are not available in this playground"),!1);if(s!==null&&(!this.hasCapability(yt.sessionFollowUp)||s.followUpAllowed===!1||s.channelId!=="http"||s.mode==="task"))return this.toast("This session is read-only in this playground"),!1;if(this.queueHeld=!1,s!==null&&this.state.running&&!n.force)return this.queueMessage(r),!0;if(s===null&&this.pendingCreate!==null)return this.queueMessage(r),!0;if(s===null){if(!this.hasCapability(yt.sessionStart))return this.toast("Starting new chats is not available in this playground"),!1;this.resetTranscript(),this.lastIndex=-1,this.beginLocalTurn();const l=this.pushUserEcho(r);this.set({localTrace:!1,barTitle:"Session",barId:"starting…",externalUrl:null,traceEvents:[]});const c={};this.pendingCreate=c;let f=!1,d=null,h=null;try{d=await this.api.createSession(r)}catch(m){h=m}finally{f=this.pendingCreate!==c,f||(this.pendingCreate=null)}return d===null?(f||(this.setRunning(!1),this.rollbackUserEcho(l),this.set({barTitle:"No session",barId:""})),this.toast(`Create failed: ${ty(h)}`),f):f?(d.ok?this.refreshSessions():this.toast(`Create failed: ${zn(d.body,160)}`),!0):!d.ok||!d.body?(this.setRunning(!1),this.rollbackUserEcho(l),this.set({barTitle:"No session",barId:""}),this.toast(`Create failed: ${zn(d.body,160)}`),!1):(this.set({current:{sessionId:d.body.sessionId,channelId:"http",mode:"chat",followUpAllowed:!0,continuationToken:d.body.continuationToken},barId:d.body.sessionId}),this.syncSessionUrl(d.body.sessionId),this.startStream(d.body.sessionId,0),this.refreshSessions(),!0)}this.beginLocalTurn();const a=this.pushUserEcho(r);return this.beginDiscardStaleTurnBody(),this.streamAbort===null&&this.startStream(s.sessionId,this.lastIndex+1),this.postFollowUp(s,r,!0,a)}async postFollowUp(t,n,r,s){let a;try{a=await this.api.followUp(t.sessionId,n,t.continuationToken)}catch(l){return this.setRunning(!1),this.rollbackUserEcho(s),this.toast(`Send failed: ${ty(l)}`),!1}if(a.ok&&a.body)return this.set({current:{...t,continuationToken:a.body.continuationToken}}),!0;if(a.body?.error==="stale_continuation_token"&&r){await this.refreshSessions();const l=this.state.current??t;return this.postFollowUp(l,n,!1,s)}return this.setRunning(!1),this.rollbackUserEcho(s),this.toast(`Send failed: ${zn(a.body,160)}`),!1}queueMessage(t){this.set({queued:[...this.state.queued,{id:this.nextId("queued"),text:t}]})}removeQueued(t){this.set({queued:this.state.queued.filter(n=>n.id!==t)})}clearQueue(){this.set({queued:[]})}editQueued(t){const n=this.state.queued.find(r=>r.id===t);n!==void 0&&(this.removeQueued(t),this.set({composerDraft:n.text}))}consumeComposerDraft(){this.set({composerDraft:null})}setComposerDraft(t){this.set({composerDraft:t})}async sendQueuedNow(t){const n=this.state.queued.find(s=>s.id===t);if(n===void 0)return;if(this.pendingCreate!==null){this.toast("The session is still starting. Queued messages send once it is ready.");return}this.removeQueued(t),this.queueHeld=!1,await this.sendMessage(n.text,{force:!0})||this.requeueFront(n)}requeueFront(t){this.set({queued:[t,...this.state.queued]}),this.queueHeld=!0}maybeFlushQueue(){if(this.flushingQueue||this.queueHeld)return;const{running:t,queued:n,localTrace:r,current:s}=this.state;if(t||r||this.historyOnly||s===null||n.length===0)return;const[a,...l]=n;if(a===void 0)return;this.flushingQueue=!0,this.set({queued:l}),this.beginLocalTurn();const c=this.pushUserEcho(a.text);this.streamAbort===null&&this.startStream(s.sessionId,this.lastIndex+1),this.postFollowUp(s,a.text,!0,c).then(f=>{f||this.requeueFront(a)}).finally(()=>{this.flushingQueue=!1})}async stopTurn(){const t=this.state.current?.sessionId;if(!t||this.state.localTrace||this.historyOnly||!this.hasCapability(yt.sessionStop)||!this.state.running)return;this.state.queued.length>0&&(this.queueHeld=!0),this.beginDiscardStaleTurnBody(),this.stopStream(),this.setRunning(!1),this.assistantId&&(this.update(this.assistantId,{streaming:!1}),this.assistantId=null),this.reasoningId&&(this.update(this.reasoningId,{open:!1}),this.reasoningId=null),this.finalizeOpenTools(Date.now(),"(no result — turn interrupted)"),this.pushDivider("turn interrupted"),this.commitTranscript();const n=await this.api.stopSession(t);if(!n.ok){this.toast(`Stop failed: ${zn(n.body,160)}`);return}this.refreshSessions()}async submitApproval(t,n){const r=this.state.current?.sessionId;if(!r||this.historyOnly||!this.hasCapability(yt.approvalResolve))return;const s=await this.api.resolveApproval(r,t,n);s.ok||this.toast(`Approval failed: ${zn(s.body,160)}`)}async submitAuth(t,n){const r=this.state.current?.sessionId;if(!r||this.historyOnly||!this.hasCapability(yt.authResolve))return;const s=await this.api.resolveAuth(r,t,n);s.ok||this.toast(`Connect failed: ${zn(s.body,160)}`)}async dispatchSchedule(t){if(this.historyOnly||!this.hasCapability(yt.scheduleDispatch))return;const n=await this.api.dispatchSchedule(t);if(!n.ok||!n.body){this.toast(`Dispatch failed: ${zn(n.body,120)}`);return}await this.refreshSessions();const r=n.body.sessionIds?.[0],s=this.state.sessions.find(a=>a.sessionId===r);s&&this.selectSession(s)}async refreshEvalCases(){if(!this.hasCapability(yt.evalRead))return;const t=await this.api.evalsList();if(!t.ok||!t.body){t.status!==0&&this.toast(`Could not list evals (${t.status}): ${zn(t.body,120)}`);return}this.set({evalCases:t.body.evals??[],evalConfig:t.body.config??null})}async refreshEvalRuns(){if(!this.hasCapability(yt.evalRead))return;const t=await this.api.evalsListRuns();if(!t.ok||t.body===null)return;const n=Array.isArray(t.body.runs)?t.body.runs:null;n!==null&&this.set({evalRuns:n})}async selectEvalRun(t){const n=t.trim();if(n==="")return;this.set({chatPanelOpen:!0});const r=this.state.evalRuns.find(a=>a.runId===n);if(r!==void 0&&r.status!=="running"){this.applyRestoredEvalRun(r),this.setView("evals");return}const s=await this.api.evalsRunStatus(n);if(!s.ok||s.body===null){this.toast(`Eval run not found: ${n}`);return}this.applyRestoredEvalRun(s.body),this.setView("evals"),this.refreshEvalRuns()}async openEvalRunInOverview(t){const n=t.trim();n!==""&&(this.setOverviewSection("runs",n),await this.selectEvalRun(n))}async restoreEvalRun(){if(this.hasCapability(yt.evalRead))return this.evalRestoreInFlight!==null?this.evalRestoreInFlight:(this.evalRestoreInFlight=this.doRestoreEvalRun().finally(()=>{this.evalRestoreInFlight=null}),this.evalRestoreInFlight)}async doRestoreEvalRun(){const t=++this.evalRestoreGeneration,n=pW();if(n!==null){const d=await this.api.evalsRunStatus(n);if(t!==this.evalRestoreGeneration)return;if(d.ok&&d.body){this.applyRestoredEvalRun(d.body),this.refreshEvalRuns();return}}const r=await this.api.evalsListRuns();if(t!==this.evalRestoreGeneration)return;const s=r.ok?r.body:null,a=Array.isArray(s?.runs)?s.runs:null;if(a!==null&&this.set({evalRuns:a}),s?.activeRunId!==void 0&&a!==null){const d=s.activeRunId,h=a.find(m=>m.runId===d)??await this.fetchEvalRunIfCurrent(t,d);if(t!==this.evalRestoreGeneration)return;if(h!==void 0){this.state.evalRun?.runId===h.runId?(this.set({evalRun:h}),h.status==="running"&&this.evalPollTimer===null&&this.startEvalRunPoll(h.runId)):this.applyRestoredEvalRun(h);return}}const l=this.state.evalRun;if(l!==null){l.status==="running"&&this.evalPollTimer===null&&this.startEvalRunPoll(l.runId);return}const c=dW(this.state.meta.basePath);if(c!==null){const d=await this.api.evalsRunStatus(c);if(t!==this.evalRestoreGeneration||this.state.evalRun!==null)return;if(d.ok&&d.body){this.applyRestoredEvalRun(d.body);return}}if(a===null)return;const f=a[0];f!==void 0&&this.state.evalRun===null&&this.applyRestoredEvalRun(f)}async fetchEvalRunIfCurrent(t,n){const r=await this.api.evalsRunStatus(n);if(t===this.evalRestoreGeneration)return r.ok&&r.body?r.body:void 0}applyRestoredEvalRun(t){this.set({evalRun:t}),this.mergeEvalRunIntoList(t),ep(this.state.meta.basePath,t.runId),hW(t.runId),t.status==="running"&&this.startEvalRunPoll(t.runId)}mergeEvalRunIntoList(t){const n=this.state.evalRuns.filter(r=>r.runId!==t.runId);this.set({evalRuns:[t,...n]})}async startEvalRun(t){if(this.historyOnly||!this.hasCapability(yt.evalRun))return;if(this.state.evalRun?.status==="running"){this.toast("An eval run is already in progress");return}this.evalRestoreGeneration+=1;const n=await this.api.evalsStartRun(t===void 0||t.length===0?{}:{filterIds:t});if(!n.ok||!n.body){this.toast(`Eval start failed: ${zn(n.body,160)}`);return}this.set({evalRun:n.body}),ep(this.state.meta.basePath,n.body.runId),(this.state.view==="overview"||this.state.view==="chat")&&(this.set({overviewSection:"runs",overviewRunId:n.body.runId,chatPanelOpen:!0}),this.mergeEvalRunIntoList(n.body)),this.setView("evals"),this.toast(`Eval ID: ${n.body.runId}`),this.startEvalRunPoll(n.body.runId),this.refreshEvalRuns()}async cancelEvalRun(t){if(this.historyOnly||!this.hasCapability(yt.evalCancel))return;const n=t??this.state.evalRun?.runId;if(n===void 0||n===""){this.toast("No eval run to cancel");return}const r=await this.api.evalsCancelRun(n);if(!r.ok||!r.body){this.toast(`Eval cancel failed: ${zn(r.body,160)}`);return}this.set({evalRun:r.body}),ep(this.state.meta.basePath,r.body.runId),this.toast(`Cancelled Eval ID ${r.body.runId}`),r.body.status==="running"?this.startEvalRunPoll(r.body.runId):this.stopEvalRunPoll(),this.refreshEvalRuns()}stopEvalRunPoll(){this.evalPollTimer!==null&&(clearInterval(this.evalPollTimer),this.evalPollTimer=null)}startEvalRunPoll(t){this.stopEvalRunPoll();const n=++this.evalPollGeneration;let r=!1,s=!1;const a=async()=>{if(!(n!==this.evalPollGeneration||r)){r=!0;try{const l=await this.api.evalsRunStatus(t);if(n!==this.evalPollGeneration||!l.ok||!l.body)return;if(this.set({evalRun:l.body}),ep(this.state.meta.basePath,l.body.runId),this.mergeEvalRunIntoList(l.body),l.body.status!=="running"){if(this.stopEvalRunPoll(),this.refreshSessions(),this.refreshEvalRuns(),s||n!==this.evalPollGeneration)return;s=!0;const{passed:c,failed:f,total:d}=l.body.summary;this.toast(l.body.status==="failed"?`Eval run failed: ${l.body.error??"unknown error"}`:`Evals done — ${c} passed, ${f} failed, ${d} total`)}}finally{r=!1}}};a(),this.evalPollTimer=setInterval(()=>{a()},1500)}async attachEvalCaseSessionForView(t){const r=(this.state.evalRun??this.state.evalRuns[0]??null)?.cases.find(a=>a.sessionId!==void 0)?.sessionId;if(r===void 0||(await this.refreshSessions(),this.state.current!==null||this.state.view!==t))return;const s=this.state.sessions.find(a=>a.sessionId===r);s!==void 0?this.selectSession({...s,running:s.running===!0}):this.selectSession({sessionId:r,channelId:"http",mode:"conversation",title:"Eval session",turnCount:0,running:!1}),this.set({evalNavReturn:!0}),this.setView(t)}async openEvalCaseSession(t){await this.refreshSessions();const n=this.state.sessions.find(r=>r.sessionId===t);n!==void 0?this.selectSession({...n,running:n.running===!0}):this.selectSession({sessionId:t,channelId:"http",mode:"conversation",title:"Eval session",turnCount:0,running:!1}),this.set({evalNavReturn:!0}),this.setView("chat")}async openEvalCaseTrace(t){await this.refreshSessions();const n=this.state.sessions.find(r=>r.sessionId===t);n!==void 0?this.selectSession({...n,running:n.running===!0}):this.selectSession({sessionId:t,channelId:"http",mode:"conversation",title:"Eval session",turnCount:0,running:!1}),this.set({evalNavReturn:!0}),this.setView("trace")}async openSessionFromChannelResponse(t,n){const r=typeof n?.sessionId=="string"&&n.sessionId.trim()!==""?n.sessionId:null;if(r===null)return!1;await this.refreshSessions();const s=this.state.sessions.find(c=>c.sessionId===r),a=typeof n.status=="string"?n.status:void 0,l=a===void 0||a==="started"||a==="running";if(s!==void 0)this.selectSession({...s,running:l?!0:!!s.running});else{const c=typeof n.continuationToken=="string"?n.continuationToken:typeof n.key=="string"?n.key:void 0,f=typeof n.pr=="string"?n.pr:typeof n.title=="string"?n.title:"Session";this.selectSession({sessionId:r,channelId:t,mode:typeof n.mode=="string"?n.mode:"task",title:f,turnCount:0,running:l,continuationToken:c,externalUrl:typeof n.agentUrl=="string"?n.agentUrl:null})}return this.setView("chat"),this.setDrawerOpen(!1),!0}async openSessionById(t){const n=t.trim();if(n==="")return;await this.refreshSessions();const r=this.state.sessions.find(s=>s.sessionId===n);r!==void 0?this.selectSession(r):this.selectSession({sessionId:n,channelId:"http",mode:"conversation",title:"Session",turnCount:0,running:!1}),this.setView("chat")}async invokeSlashCommand(t){if(!this.hasCapability(yt.channelInvoke))return!1;const n=t.trim(),r=this.slashCommands();if(/^\/help(?:\s|$)/i.test(n)){this.resetTranscript(),this.pushUser(n);const l=this.ensureAssistant();return this.update(l,{text:cG(r),streaming:!1}),this.assistantId=null,this.set({localTrace:!1,current:null,barTitle:"Help",barId:"",externalUrl:null,running:!1,turnStartedAt:null}),this.syncSessionUrl(null),this.commitTranscript(),!0}const s=fG(n,r);if(!s.ok)return this.toast(s.error),!1;this.setRunning(!0),this.resetTranscript(),this.pushUser(n);const a=this.ensureAssistant();this.update(a,{text:`Running \`${s.command.name}\` (${s.command.method} ${s.command.url})…`}),this.set({localTrace:!1,current:null,barTitle:s.command.name,barId:s.command.method,externalUrl:null,transcript:this.items.slice()}),this.syncSessionUrl(null);try{const l=await this.api.channelRequest(s.command.method,s.command.url,{body:s.body,query:s.query});return l.ok?await this.openSessionFromChannelResponse(s.command.channelId,l.body)?(this.assistantId=null,!0):(this.setRunning(!1),this.update(a,{text:"```json\n"+fW(l.body)+"\n```",streaming:!1}),this.assistantId=null,this.commitTranscript(),!0):(this.setRunning(!1),this.update(a,{text:`Command failed (${l.status}): ${zn(l.body,400)}`,streaming:!1}),this.assistantId=null,this.commitTranscript(),!0)}catch(l){return this.setRunning(!1),this.update(a,{text:`Command failed: ${l instanceof Error?l.message:String(l)}`,streaming:!1}),this.assistantId=null,this.commitTranscript(),!0}}async loadEngineMeta(){let t;try{t=await this.api.meta()}catch{return!1}return!t.ok||!t.body?!1:(this.set({meta:{name:t.body.name??"agent",dev:!!t.body.dev,basePath:this.api.url(""),indexPath:t.body.indexPath,version:t.body.version,readonly:t.body.readonly===!0}}),console.info(`[playground] engine version ${t.body.version??"pre-0.1.14"}`),!0)}refreshEngineStatus(){this.api.health().then(t=>{this.set({health:t.ok?"ok":"bad"})}),this.api.info().then(t=>{t.ok&&t.body?this.set({info:t.body}):t.status===401&&(this.noteAliasAuthLoss(t.status)||this.toast("Unauthorized: set a bearer token (⋯ menu) that matches the channel auth."))})}async pollEngineMetaUntilReady(){const t=Date.now()+18e4;let n=1e3;for(;Date.now()<t;){if(await new Promise(r=>setTimeout(r,n)),n=Math.min(n*2,1e4),this.aliasAuthPending)return;if(await this.loadEngineMeta()){this.refreshEngineStatus(),this.refreshEvalCases(),this.restoreEvalRun();const r=this.pendingSessionDeepLink;if(this.pendingSessionDeepLink=null,r!==null){await this.refreshSessions(),this.selectDeepLinkedSession(r);try{new URL(window.location.href).searchParams.get("view")==="overview"&&this.setView("overview")}catch{}}return}}this.pendingSessionDeepLink=null}selectDeepLinkedSession(t){const n=this.state.sessions.find(r=>r.sessionId===t);if(n){this.selectSession(n);return}this.selectSessionOutsideList(t)}async selectSessionOutsideList(t){if(this.api.sessionById!==void 0)try{const n=await this.api.sessionById(t);if(n.ok&&n.body?.session){this.state.current===null&&this.selectSession(n.body.session);return}}catch{}this.state.sessions.length>0&&this.toast(`Session not found: ${t}`)}get aliasAuthPending(){return this.state.aliasHosted&&this.state.aliasToken.trim()===""}async boot(){if(this.booted||this.aliasAuthPending)return;this.booted=!0;let t=null,n=null,r=null;try{const a=V7(window.location.href);t=a.sessionId,n=a.view,r=a.section}catch{}const s=await this.loadEngineMeta();s?this.refreshEngineStatus():(this.pendingSessionDeepLink=t,this.set({health:"bad"}),this.pollEngineMetaUntilReady()),n?this.setView(n):this.setView("overview"),r!==null&&this.set({overviewSection:r}),await this.refreshSessions(),this.refreshEvalCases(),this.refreshEvalRuns(),this.restoreEvalRun(),t&&s&&(this.selectDeepLinkedSession(t),n==="overview"&&this.setView("overview")),this.historyOnly||setInterval(()=>{this.refreshSessions()},this.state.meta.dev?2e3:5e3)}modelLabel(){return rG(this.state.info?.model)}}function ty(e){return e instanceof Error?e.message:String(e)}function fW(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function fM(e){return`agent-serve:evalRunId:${e||"/"}`}function dW(e){try{const t=sessionStorage.getItem(fM(e));return t!==null&&t!==""?t:null}catch{return null}}function pW(){try{const e=new URL(window.location.href).searchParams.get("evalRunId");if(e===null)return null;const t=e.trim();return t===""?null:t}catch{return null}}function hW(e){try{const t=new URL(window.location.href);if(t.searchParams.get("evalRunId")===e)return;t.searchParams.set("evalRunId",e),history.replaceState(null,"",t.toString())}catch{}}function ep(e,t){try{sessionStorage.setItem(fM(e),t)}catch{}}function mW(e){const t=T7(()=>uW()),n=e(t.getState);return t.setState({capabilities:uM(n.capabilities)}),new cW(n,t)}const Qe=mW(e=>iW(cM(),e));Qe.getState().aliasHosted&&I7(e=>Qe.acceptAliasTokenHandoff(e));let yR=Qe.getState().overviewSection;Qe.subscribe(e=>{e.overviewSection!==yR&&(yR=e.overviewSection,DI(e.overviewSection))});if(Qe.getState().embedded){let e=Qe.getState().view,t=Qe.getState().current?.sessionId??null,n=Qe.getState().overviewSection,r=t!==null;Qe.subscribe(s=>{const a=s.current?.sessionId??null;a!==null&&(r=!0),!(s.view===e&&a===t&&s.overviewSection===n)&&(e=s.view,t=a,n=s.overviewSection,Y7(s.view,r?a:void 0,void 0,s.overviewSection))})}function Ue(e){return C7(Qe,e)}function gW(){const[e,t]=v.useState(""),[n,r]=v.useState(null),[s,a]=v.useState(!1);async function l(c){c.preventDefault(),a(!0),r(null);const f=await Qe.signInWithAliasToken(e);a(!1),f.ok||r(f.error)}return g.jsx("div",{className:"pg-alias-signin",children:g.jsxs("div",{className:"pg-alias-signin-box",children:[g.jsx("h1",{children:"agent-serve playground"}),g.jsx("p",{children:"This deployment requires its alias token."}),n!==null?g.jsx("div",{className:"pg-alias-signin-error",children:n}):null,g.jsxs("form",{onSubmit:c=>{l(c)},children:[g.jsx(rf,{type:"password",size:"md","aria-label":"Alias token",placeholder:"adt_…",autoComplete:"off",autoFocus:!0,value:e,onChange:c=>t(c.target.value),disabled:s}),g.jsx(vn,{type:"submit",variant:"primary",disabled:s||e.trim()==="",children:s?"Checking…":"Open playground"})]}),g.jsxs("div",{className:"pg-alias-signin-hint",children:["The alias token was shown once when the agent was deployed. Lost it?",g.jsx("code",{children:"bdk rotate-token <slug>"})," mints a replacement. The token stays in this tab only — refresh to sign in again."]})]})})}function bW(){return g.jsx("div",{className:"pg-alias-signin",children:g.jsxs("div",{className:"pg-alias-signin-box",children:[g.jsx("h1",{children:"Playground disconnected"}),g.jsx("p",{children:"This playground connects through your Cursor dashboard. Use Reconnect on the dashboard, or reload the page."})]})})}const yW=["noopener","noreferrer"];function p0(e){return e.trim()===""}function dM(e){const t=e.trim();if(p0(t)||t.startsWith("#"))return!1;try{const n=new URL(t,"https://playground.invalid").protocol.toLowerCase();return n!=="javascript:"&&n!=="data:"&&n!=="vbscript:"&&n!=="file:"}catch{return!0}}function vW(e){if(e.hasAttribute("download"))return;const t=e.getAttribute("href");if(t===null||!dM(t))return;e.target="_blank";const n=new Set(e.rel.split(/\s+/).map(r=>r.toLowerCase()).filter(r=>r!==""));for(const r of yW)n.add(r);e.rel=[...n].join(" ")}function vR(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest("a");if(!(n instanceof HTMLAnchorElement))return;vW(n);const r=n.getAttribute("href");r!==null&&p0(r)&&!n.hasAttribute("download")&&e.preventDefault()}function xW(e=document){return e.addEventListener("click",vR,!0),()=>e.removeEventListener("click",vR,!0)}function pa({href:e,onClick:t,...n}){const s=e!==void 0&&p0(e)?a=>{a.preventDefault(),t?.(a)}:t;return e===void 0||!dM(e)?g.jsx("a",{href:e,...n,onClick:s}):g.jsx("a",{href:e,...n,onClick:s,target:"_blank",rel:"noopener noreferrer"})}const pM=512*1024,kW=64*1024*1024,SW=240;async function hM(e){if(!Qe.hasCapability(yt.artifactContent))return{phase:"absent"};try{const t=await Qe.api.artifactContent(e,pM);if(!t.ok)return t.status===404?{phase:"absent"}:{phase:"error",message:`HTTP ${t.status}`};let n=null;if(M7(t.contentType)){const r=new TextDecoder("utf-8",{fatal:!1}).decode(t.bytes);n=D7(r)?null:r}return{phase:"loaded",text:n,isDiff:n!==null&&L7(t.contentType,n),contentType:t.contentType,size:t.bytes.length,truncated:t.truncated}}catch(t){return{phase:"error",message:t instanceof Error?t.message:String(t)}}}async function mM(e,t){if(Qe.hasCapability(yt.artifactContent))try{const n=await Qe.api.artifactContent(e,kW);if(!n.ok)return;const r=new Blob([n.bytes.buffer],{type:n.contentType??"application/octet-stream"}),s=URL.createObjectURL(r),a=document.createElement("a");a.href=s,a.download=EW(t,e,n.contentType),a.click(),URL.revokeObjectURL(s)}catch{}}const wW={"text/x-diff":".diff","text/x-patch":".patch","application/json":".json","text/markdown":".md","text/plain":".txt","text/html":".html","text/csv":".csv"};function EW(e,t,n){const r=(e??t).trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),s=n?.split(";")[0]?.trim().toLowerCase()??"",a=wW[s]??"",l=r===""?t:r;return l.includes(".")?l:`${l}${a}`}function TW({text:e,isDiff:t}){const n=v.useMemo(()=>t?e.split(`
23
23
  `):null,[e,t]);return n===null?g.jsx("pre",{className:"pg-artifact-file-text",children:e}):g.jsx("pre",{className:"pg-artifact-file-text pg-artifact-diff",children:n.map((r,s)=>g.jsx("span",{className:`diff-line diff-${j7(r)}`,children:r},s))})}function gM({artifactId:e,title:t,state:n}){if(n.phase==="idle"||n.phase==="loading")return g.jsx("div",{className:"pg-artifact-file-note",children:"Loading contents…"});if(n.phase==="absent")return null;if(n.phase==="error")return g.jsxs("div",{className:"pg-artifact-file-note",children:["Failed to load contents: ",n.message]});const r=tv(n.size),s=[n.contentType?.split(";")[0],r].filter(a=>a!==void 0&&a!=="").join(" · ");return g.jsxs("div",{className:"pg-artifact-file",children:[g.jsxs("div",{className:"pg-artifact-file-head",children:[g.jsx(qt,{name:"file",size:"sm",color:"tertiary"}),g.jsx("span",{className:"pg-artifact-file-meta",children:s||"file payload"}),g.jsx(vn,{variant:"ghost",size:"sm",onClick:()=>{mM(e,t)},children:"Download"})]}),n.text!==null?g.jsx(TW,{text:n.text,isDiff:n.isDiff}):g.jsx("div",{className:"pg-artifact-file-note",children:"Binary payload — use Download to save it."}),n.truncated?g.jsxs("div",{className:"pg-artifact-file-note",children:["Preview truncated to ",tv(pM)," — Download has the full payload."]}):null]})}function RW({data:e}){const[t,n]=v.useState(!1),r=v.useMemo(()=>Eo(e),[e]);if(r===""||r==="null")return null;const s=r.length>SW;return g.jsxs("div",{className:"pg-artifact-data",children:[g.jsx("pre",{className:s&&!t?"pg-artifact-json clamped":"pg-artifact-json",children:r}),s?g.jsx("button",{type:"button",className:"link-btn",onClick:()=>n(a=>!a),children:t?"Collapse":"Show all"}):null]})}const CW=v.memo(function({artifactKind:t,title:n,url:r,artifactId:s,data:a}){const[l,c]=v.useState(!1),[f,d]=v.useState({phase:"idle"}),h=Ue(b=>b.capabilities.artifacts==="enabled"),m=b=>{c(b),!(!b||!h||s===void 0||f.phase!=="idle")&&(d({phase:"loading"}),hM(s).then(d))};return g.jsx("div",{className:"pg-artifact-card",children:g.jsx(yi,{action:"Artifact",details:g.jsxs("span",{className:"pg-artifact-head",children:[g.jsx(vo,{variant:"accent",size:"sm",pill:!0,children:t}),n!==void 0?g.jsx("span",{className:"pg-artifact-head-title",children:n}):null]}),leadingIcon:g.jsx(qt,{name:"bookmark",size:"sm",color:"secondary"}),open:l,onOpenChange:m,tone:"tertiary",children:g.jsxs("div",{className:"pg-artifact-body",children:[r!==void 0?g.jsx(pa,{className:"pg-artifact-link",href:r,children:r}):null,a!==void 0?g.jsx(RW,{data:a}):null,s!==void 0?h?g.jsx(gM,{artifactId:s,title:n,state:f}):g.jsx("div",{className:"pg-artifact-file-note",children:"File contents are not available in this playground"}):null]})})})}),xR=280,_W=8,ny=1e3;function AW({record:e}){const[t,n]=v.useState(!1),r=v.useMemo(()=>{const a=OI(e.data);return a!==null?{url:a,json:"",short:""}:{url:null,json:Eo(e.data),short:zn(e.data,xR)}},[e.data]);if(r.url!==null)return g.jsx(pa,{className:"artifact-link",href:r.url,children:r.url});if(r.json==="")return null;const s=r.json.length>xR||r.json.split(`
24
24
  `).length>_W;return g.jsxs("div",{className:"artifact-data",children:[g.jsx("pre",{className:"artifact-json",children:s&&!t?r.short:r.json}),s?g.jsx("button",{type:"button",className:"link-btn",onClick:()=>n(!t),children:t?"Collapse":"Expand"}):null]})}function NW({record:e,contentAvailable:t}){const[n,r]=v.useState({phase:"idle"}),s=e.content;if(s===void 0)return null;if(!t)return g.jsxs("div",{className:"pg-artifact-file-head",children:[g.jsx(qt,{name:"file",size:"sm",color:"tertiary"}),g.jsx("span",{className:"pg-artifact-file-meta",children:"File contents are not available in this playground"})]});if(n.phase==="idle"){const a=[s.contentType,tv(s.size)].filter(l=>l!==void 0&&l!=="").join(" · ");return g.jsxs("div",{className:"pg-artifact-file-head",children:[g.jsx(qt,{name:"file",size:"sm",color:"tertiary"}),g.jsx("span",{className:"pg-artifact-file-meta",children:a||"file payload"}),g.jsx(vn,{variant:"ghost",size:"sm",onClick:()=>{r({phase:"loading"}),hM(e.id).then(r)},children:"View"}),g.jsx(vn,{variant:"ghost",size:"sm",onClick:()=>{mM(e.id,e.title)},children:"Download"})]})}return g.jsx(gM,{artifactId:e.id,title:e.title,state:n})}const kR=v.memo(function({record:t,contentAvailable:n}){return g.jsxs("div",{className:"artifact-row",children:[g.jsxs("div",{className:"artifact-row-head",children:[g.jsx("span",{className:"artifact-title",children:z7(t)}),g.jsx(vo,{variant:"accent",size:"sm",pill:!0,children:t.kind}),g.jsx(vo,{variant:t.source==="model"?"success":"neutral",size:"sm",pill:!0,children:t.source}),g.jsx("span",{className:"artifact-updated",title:`updated ${t.updatedAt}`,children:gv(t.updatedAt)??t.updatedAt})]}),g.jsx(AW,{record:t}),g.jsx(NW,{record:t,contentAvailable:n})]})});function OW({sessionId:e,count:t,title:n}){const r=`${t} artifact${t===1?"":"s"}`;return e===null?g.jsxs("div",{className:"artifact-group-head",children:[g.jsx("span",{className:"artifact-group-id",children:"No session"}),g.jsx("span",{className:"artifact-group-n",children:r})]}):g.jsxs("button",{type:"button",className:"artifact-group-head",onClick:()=>{Qe.openSessionById(e)},title:"Open this session's replay",children:[g.jsx("span",{className:"artifact-group-id",children:n||e}),n?g.jsx("span",{className:"artifact-group-sub",children:e}):null,g.jsxs("span",{className:"artifact-group-n",children:[r," →"]})]})}function bM(){const e=Ue($=>$.current),t=Ue($=>$.sessions),n=Ue($=>$.capabilities.artifacts),r=n!=="disabled",s=n==="enabled",[a,l]=v.useState(null),[c,f]=v.useState(null),[d,h]=v.useState(null),[m,b]=v.useState("all"),[y,k]=v.useState(0);e===null&&m==="session"&&b("all");const S=m==="session"&&e!==null?e.sessionId:null,R=a!==null&&a.scope===S?a.rows:null;v.useEffect(()=>{if(!r)return;let $=!1,O=!1;f(null);const Y=async()=>{if(!O){O=!0;try{const B=await Qe.api.artifacts({sessionId:S??void 0,limit:ny});if($)return;if(!B.ok||B.body===null){f(`Failed to load artifacts (${B.status})`);return}f(null),l({scope:S,rows:B.body.artifacts??[]})}catch(B){$||f(B instanceof Error?B.message:String(B))}finally{O=!1}}};Y();const U=setInterval(()=>{Y()},4e3);return()=>{$=!0,clearInterval(U)}},[r,S,y]);const E=()=>k($=>$+1),T=S!==null;if(!r)return g.jsx("div",{className:"pg-artifacts is-empty",children:g.jsx(Ri,{body:"Artifacts are not available in this playground."})});if(R===null)return g.jsx("div",{className:"pg-artifacts is-empty",children:c!==null?g.jsx(Ri,{body:c,cta:{label:"Retry",onClick:E}}):g.jsx(Ri,{body:"Loading artifacts…"})});const C=MI(R);if(C.length===0)return g.jsx("div",{className:"pg-artifacts is-empty",children:g.jsx(Ri,{body:T?"No artifacts tagged for this session.":"No artifacts tagged yet."})});const _=P7(C),D=d!==null&&_.includes(d)?d:null,A=$7(C,D),I=T?[]:B7(A),P=new Map(t.map($=>[$.sessionId,$.title]));return g.jsxs("div",{className:"pg-artifacts",children:[g.jsxs("div",{className:"pg-artifacts-toolbar",children:[g.jsx("span",{className:"pg-artifacts-toolbar-title",children:"Artifacts"}),g.jsxs("span",{className:"pg-artifacts-toolbar-meta",children:[A.length," of ",C.length,C.length>=ny?` (newest ${ny})`:""]}),c!==null?g.jsx("span",{className:"pg-artifacts-toolbar-error",children:c}):null,g.jsx("span",{className:"grow"}),e!==null?g.jsxs(vc,{size:"sm",variant:"compact",value:m,onValueChange:$=>b($==="session"?"session":"all"),"aria-label":"Artifact scope",children:[g.jsx(vc.Item,{value:"all",children:"All sessions"}),g.jsx(vc.Item,{value:"session",children:"This session"})]}):null,g.jsx(vn,{variant:"secondary",size:"sm",onClick:E,children:"Refresh"})]}),_.length>1?g.jsxs("div",{className:"artifact-kinds",role:"group","aria-label":"Filter by kind",children:[g.jsx("button",{type:"button",className:`artifact-kind-chip${D===null?" active":""}`,onClick:()=>h(null),children:"All"}),_.map($=>g.jsx("button",{type:"button",className:`artifact-kind-chip${D===$?" active":""}`,onClick:()=>h(D===$?null:$),children:$},$))]}):null,A.length===0?g.jsx(Ri,{body:"No artifacts match this kind filter."}):T?g.jsx("div",{className:"artifact-list",children:A.map($=>g.jsx(kR,{record:$,contentAvailable:s},$.id))}):g.jsx("div",{className:"artifact-group-list",children:I.map($=>g.jsxs("section",{className:"artifact-group",children:[g.jsx(OW,{sessionId:$.sessionId,count:$.artifacts.length,title:$.sessionId===null?void 0:P.get($.sessionId)}),g.jsx("div",{className:"artifact-list",children:$.artifacts.map(O=>g.jsx(kR,{record:O,contentAvailable:s},O.id))})]},$.sessionId??"(none)"))})]})}function IW(e){const{localTrace:t,historyOnly:n,canStart:r,canFollowUp:s,current:a,running:l,slashNames:c}=e;if(n)return{disabled:!0,hint:"This agent is stopped. Open a session from Runs to inspect its chat and trace."};if(t)return{disabled:!0,hint:"Local trace (view only). Click New or pick a live session to chat."};if(a===null)return r?{disabled:!1,hint:c.length>0?`Slash commands: ${c.slice(0,4).join(", ")}${c.length>4?", …":""}, /help.`:""}:{disabled:!0,hint:"Starting new chats is not available in this playground."};if(!s)return{disabled:!0,hint:"This session is read-only in this playground."};if(a.followUpAllowed===!1||a.mode==="task"||a.channelId!=="http")return a.followUpAllowed===!1&&a.channelId==="http"?{disabled:!0,hint:"Customer sessions are read-only in this playground."}:a.mode==="task"?{disabled:!0,hint:"Task sessions (schedules) are fire-and-forget; watch only."}:a.channelId==="slack"?{disabled:!0,hint:`Slack thread — watch here, reply in Slack${a.externalUrl?" (Open in Slack above).":"."}`}:{disabled:!0,hint:`Sessions owned by the “${a.channelId}” channel take follow-ups through that channel; watch only here.`};if(!a.continuationToken&&a.followUpAllowed!==!0)return{disabled:!0,hint:"This session has no continuation token; watch only."};const d=c.length>0?` Channel commands (${c.slice(0,3).join(", ")}${c.length>3?", …":""}) also work from here.`:"";return{disabled:!1,hint:l?"Turn running — Enter queues the follow-up; ⌘Enter sends now and interrupts.":`Follow-ups reuse this session’s rotating continuation token.${d}`}}function MW(){const e=Ue(t=>t.queued);return e.length===0?null:g.jsx("div",{className:"pg-queue",role:"list","aria-label":"Queued messages",children:e.map(t=>g.jsxs("div",{className:"pg-queue-item",role:"listitem",children:[g.jsx("button",{type:"button",className:"pg-queue-label",title:"Edit queued message",onClick:()=>Qe.editQueued(t.id),children:t.text}),g.jsxs("span",{className:"pg-queue-actions",children:[g.jsx(br,{icon:"arrow-up",size:"sm",variant:"ghost","aria-label":"Send now (interrupts the running turn)",onClick:()=>{Qe.sendQueuedNow(t.id)}}),g.jsx(br,{icon:"x",size:"sm",variant:"ghost","aria-label":"Remove queued message",onClick:()=>Qe.removeQueued(t.id)})]})]},t.id))})}function yM(){const[e,t]=v.useState(""),[n,r]=v.useState(0),s=v.useRef(null),a=Ue(U=>U.localTrace),l=Ue(U=>U.meta.readonly===!0),c=Ue(U=>U.current),f=Ue(U=>U.running),d=Ue(U=>U.composerDraft),h=Ue(U=>U.info),m=Ue(U=>U.capabilities.composer),b=Ue(U=>U.capabilities.stop),y=m==="enabled"&&Qe.hasCapability(yt.sessionStart),k=m==="enabled"&&Qe.hasCapability(yt.sessionFollowUp),S=b==="enabled",R=Qe.hasCapability(yt.channelInvoke);v.useEffect(()=>{d!==null&&(t(U=>U.trim()?`${U} ${d}`:d),Qe.consumeComposerDraft(),s.current?.focus())},[d]);const E=v.useMemo(()=>R?Jh(h?.channels):[],[h,R]),T=v.useMemo(()=>rM(E),[E]),C=v.useMemo(()=>{if(a||l)return null;const U=e.replace(/^\s+/,"");return!U.startsWith("/")||/\s/.test(U)?null:U},[e,a,l]),_=v.useMemo(()=>C===null?[]:uG(C,E),[C,E]),D=C!==null&&_.length>0,{disabled:A,hint:I}=IW({localTrace:a,historyOnly:l,canStart:y,canFollowUp:k,current:c,running:f,slashNames:T}),P=S&&f&&c!==null&&!a&&!l,$=async(U=e,B=!1)=>{if(!U.trim())return;t(""),r(0),await Qe.sendMessage(U,{force:B})||t(q=>q.trim()?q:U)},O=U=>{t(`${U} `),r(0)},Y=U=>{if(D){if(U.key==="ArrowDown"){U.preventDefault(),r(B=>(B+1)%_.length);return}if(U.key==="ArrowUp"){U.preventDefault(),r(B=>(B-1+_.length)%_.length);return}if(U.key==="Tab"||U.key==="Enter"&&!U.shiftKey){const B=_[n]??_[0];if(B!==void 0&&C!==B.name){U.preventDefault(),O(B.name);return}}if(U.key==="Escape"){U.preventDefault(),t(""),r(0);return}}U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),$(e,U.metaKey||U.ctrlKey))};return g.jsxs("div",{className:"pg-composer",children:[D?g.jsxs("ul",{className:"pg-slash-menu",role:"listbox","aria-label":"Slash commands",children:[_.map((U,B)=>g.jsx("li",{children:g.jsxs("button",{type:"button",role:"option","aria-selected":B===n,className:B===n?"pg-slash-item is-active":"pg-slash-item",onMouseDown:j=>{j.preventDefault(),O(U.name)},onMouseEnter:()=>r(B),children:[g.jsx("code",{className:"pg-slash-name",children:U.name}),g.jsx("span",{className:"pg-slash-method",children:U.method}),U.description?g.jsx("span",{className:"pg-slash-desc",children:U.description}):null]})},`${U.name}:${U.method}`)),g.jsxs("li",{className:"pg-slash-footer",children:[g.jsx("code",{children:"/help"})," lists all channel commands"]})]}):null,g.jsxs("div",{className:"inner",children:[g.jsx(MW,{}),g.jsxs("div",{className:A&&!P?"pg-prompt disabled":"pg-prompt",children:[g.jsx("textarea",{ref:s,className:"pg-prompt-input",rows:1,placeholder:T.length>0?`Message the agent, or ${T[0]} …`:"Message the agent...","aria-label":"Message the agent","aria-autocomplete":D?"list":void 0,"aria-expanded":D,value:e,onChange:U=>{t(U.target.value),r(0)},onKeyDown:Y,disabled:A,autoFocus:!0}),g.jsxs("div",{className:"pg-prompt-toolbar",children:[g.jsx("span",{className:"pg-prompt-hint",title:I,children:I}),P&&!e.trim()?g.jsx(br,{icon:"square",iconVariant:"filled",variant:"primary",tone:"monochrome",rounded:!0,size:"lg",className:"pg-prompt-stop","aria-label":"Stop the running turn",onClick:()=>{Qe.stopTurn()}}):g.jsx(br,{icon:"arrow-up",variant:"primary",tone:"monochrome",rounded:!0,size:"lg","aria-label":f?"Queue message (⌘Enter sends now)":"Send message",disabled:A,onClick:()=>{$()}})]})]})]})]})}function DW(e){return{filename:`${e.runId}.eval-results.json`,text:`${JSON.stringify(e,null,2)}
@@ -8,8 +8,8 @@
8
8
  />
9
9
  <meta name="viewport" content="width=device-width, initial-scale=1" />
10
10
  <title>agent-serve playground</title>
11
- <script type="module" crossorigin src="./assets/index-HN5lOuAX.js"></script>
12
- <link rel="stylesheet" crossorigin href="./assets/index-JY1wKCMg.css">
11
+ <script type="module" crossorigin src="./assets/index-DIiKbZ25.js"></script>
12
+ <link rel="stylesheet" crossorigin href="./assets/index-CzttDc-d.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
package/dist/types.d.ts CHANGED
@@ -103,8 +103,9 @@ export interface AgentConfig {
103
103
  model?: ModelSetting;
104
104
  /**
105
105
  * Models to try, in order, when {@link model} is rejected before the
106
- * turn produces any output: catalog refusal ("Cannot use this model")
107
- * or a capacity error (`resource_exhausted` / `[unavailable]`). The
106
+ * turn produces any output: catalog refusal ("Cannot use this model"),
107
+ * a team admin block ("Model Blocked"), or a capacity error
108
+ * (`resource_exhausted` / `[unavailable]`). The
108
109
  * rejection is usually inside agent creation, before authored tools
109
110
  * run, so a fallback list on the agent is the only retry that can save
110
111
  * the turn. Each entry is the same shape as {@link model}.
@@ -2989,7 +2990,7 @@ export interface ResolvedAgent {
2989
2990
  /**
2990
2991
  * Remaining models from {@link AgentConfig.fallbacks}, in order. The
2991
2992
  * runner steps down this list when the primary model is rejected before
2992
- * the turn produces output (catalog refusal or capacity).
2993
+ * the turn produces output (catalog refusal, team admin block, or capacity).
2993
2994
  */
2994
2995
  modelFallbacks?: readonly ModelSetting[];
2995
2996
  /**
@@ -3269,7 +3270,8 @@ export interface RunnerTurnRequest {
3269
3270
  model?: ModelSetting;
3270
3271
  /**
3271
3272
  * Models to open the turn on, in order, after {@link model} is rejected
3272
- * (catalog refusal or `resource_exhausted` / `[unavailable]`) and before
3273
+ * (catalog refusal, team admin block, or `resource_exhausted` /
3274
+ * `[unavailable]`) and before
3273
3275
  * any output was streamed.
3274
3276
  */
3275
3277
  modelFallbacks?: readonly ModelSetting[];