@otto-code/server 0.8.4 → 0.8.5

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.
@@ -16,6 +16,7 @@ import { createPathEquivalenceMatcher } from "../../../utils/path.js";
16
16
  import { spawnProcess } from "../../../utils/spawn.js";
17
17
  import { extractCodexTerminalSessionId, nonEmptyString } from "./tool-call-mapper-utils.js";
18
18
  import { buildCodexFeatures, codexModelSupportsFastMode } from "./codex-feature-definitions.js";
19
+ import { priceCodexUsageUsd } from "./codex-pricing.js";
19
20
  import { CodexAppServerClient, parseCodexThreadForkResponse, parseCodexThreadRollbackResponse, } from "./codex/app-server-transport.js";
20
21
  import { revertCodexConversation } from "./codex/rewind.js";
21
22
  import { materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, } from "./provider-image-output.js";
@@ -676,6 +677,7 @@ export function accumulateCodexTurnUsage(prior, request) {
676
677
  const inputTokens = addUsageLeaf(prior?.inputTokens, request.inputTokens);
677
678
  const cachedInputTokens = addUsageLeaf(prior?.cachedInputTokens, request.cachedInputTokens);
678
679
  const outputTokens = addUsageLeaf(prior?.outputTokens, request.outputTokens);
680
+ const totalCostUsd = addUsageLeaf(prior?.totalCostUsd, request.totalCostUsd);
679
681
  if (inputTokens !== undefined) {
680
682
  merged.inputTokens = inputTokens;
681
683
  }
@@ -685,6 +687,9 @@ export function accumulateCodexTurnUsage(prior, request) {
685
687
  if (outputTokens !== undefined) {
686
688
  merged.outputTokens = outputTokens;
687
689
  }
690
+ if (totalCostUsd !== undefined) {
691
+ merged.totalCostUsd = totalCostUsd;
692
+ }
688
693
  return merged;
689
694
  }
690
695
  function extractUserText(content) {
@@ -4217,6 +4222,12 @@ export class CodexAppServerAgentSession {
4217
4222
  this.emitSubAgentActivityUpdate(subAgentCallId, "running");
4218
4223
  return;
4219
4224
  }
4225
+ // `turn/completed` can arrive before Codex's item-completed notification.
4226
+ // Do not end a visible action there: the item event carries its real result.
4227
+ // A new root turn is the first unambiguous point at which an old action can
4228
+ // no longer produce that terminal event, so it is the safe stale-action
4229
+ // fallback for older Codex app-server versions that omit one.
4230
+ this.settleActiveForegroundToolCalls("completed", null);
4220
4231
  this.currentTurnId = parsed.turnId;
4221
4232
  this.resetTurnTrackingState();
4222
4233
  this.emitEvent({ type: "turn_started", provider: CODEX_PROVIDER });
@@ -4234,8 +4245,14 @@ export class CodexAppServerAgentSession {
4234
4245
  this.emitSubAgentActivityUpdate(subAgentCallId, status);
4235
4246
  return;
4236
4247
  }
4237
- const terminalStatus = parsed.status === "failed" || parsed.status === "interrupted" ? parsed.status : "completed";
4238
- this.settleActiveForegroundToolCalls(terminalStatus, parsed.errorMessage);
4248
+ // Successful turns do not imply every action event has arrived yet. Codex
4249
+ // may report `turn/completed` before its action's terminal notification;
4250
+ // ending it here made the visualizer hide real in-flight work. Failed and
4251
+ // interrupted turns cannot produce a successful terminal result, so settle
4252
+ // their outstanding actions immediately.
4253
+ if (parsed.status === "failed" || parsed.status === "interrupted") {
4254
+ this.settleActiveForegroundToolCalls(parsed.status, parsed.errorMessage);
4255
+ }
4239
4256
  // A failed or interrupted turn already burned every request it made, and the
4240
4257
  // manager books `usage` on all three outcomes. Reporting it only on the
4241
4258
  // happy path made Esc-heavy and retrying sessions look free.
@@ -4268,9 +4285,13 @@ export class CodexAppServerAgentSession {
4268
4285
  this.activeForegroundTurnId = null;
4269
4286
  this.activeClientMessageId = null;
4270
4287
  this.pendingSubAgentNotificationsByThreadId.clear();
4271
- this.resetTurnTrackingState();
4288
+ this.resetTurnTrackingState({
4289
+ // Preserve successful-turn actions until their late item-completed event
4290
+ // arrives (or the next root turn proves the event was omitted).
4291
+ preserveActiveForegroundToolCalls: parsed.status === "completed",
4292
+ });
4272
4293
  }
4273
- resetTurnTrackingState() {
4294
+ resetTurnTrackingState(options) {
4274
4295
  this.turnUsage = undefined;
4275
4296
  this.latestPlanResult = null;
4276
4297
  this.emittedItemStartedIds.clear();
@@ -4278,7 +4299,9 @@ export class CodexAppServerAgentSession {
4278
4299
  this.emittedProviderSubagentUserMessageKeys.clear();
4279
4300
  this.emittedExecCommandStartedCallIds.clear();
4280
4301
  this.emittedExecCommandCompletedCallIds.clear();
4281
- this.activeForegroundToolCalls.clear();
4302
+ if (!options?.preserveActiveForegroundToolCalls) {
4303
+ this.activeForegroundToolCalls.clear();
4304
+ }
4282
4305
  this.pendingAgentMessages.clear();
4283
4306
  this.pendingReasoning.clear();
4284
4307
  this.pendingCommandOutputDeltas.clear();
@@ -4318,7 +4341,8 @@ export class CodexAppServerAgentSession {
4318
4341
  if (!requestUsage) {
4319
4342
  return;
4320
4343
  }
4321
- this.turnUsage = accumulateCodexTurnUsage(this.turnUsage, requestUsage);
4344
+ const totalCostUsd = priceCodexUsageUsd(requestUsage, this.config.model);
4345
+ this.turnUsage = accumulateCodexTurnUsage(this.turnUsage, totalCostUsd === undefined ? requestUsage : { ...requestUsage, totalCostUsd });
4322
4346
  this.notifySubscribers({
4323
4347
  type: "usage_updated",
4324
4348
  provider: CODEX_PROVIDER,
@@ -0,0 +1,16 @@
1
+ import type { AgentUsage } from "../agent-sdk-types.js";
2
+ /** USD per million tokens for the three billable Codex token classes. */
3
+ export interface CodexModelRates {
4
+ inputPerMTok: number;
5
+ cachedInputPerMTok: number;
6
+ outputPerMTok: number;
7
+ }
8
+ /** The published price card for a Codex model, if it is a priced model. */
9
+ export declare function codexModelRates(model: string | undefined): CodexModelRates | undefined;
10
+ /**
11
+ * Price one Codex request from its disjoint token split. Codex does not charge
12
+ * cache writes, and `toAgentUsage` has already removed cached input from fresh
13
+ * input, so these three leaves can be multiplied independently.
14
+ */
15
+ export declare function priceCodexUsageUsd(usage: Pick<AgentUsage, "inputTokens" | "cachedInputTokens" | "outputTokens">, model: string | undefined): number | undefined;
16
+ //# sourceMappingURL=codex-pricing.d.ts.map
@@ -0,0 +1,39 @@
1
+ // Published OpenAI Codex rate-card prices, used only by the Codex provider to
2
+ // attach a dollar cost to its own token usage. Keep this provider-bound: an
3
+ // OpenAI-compatible endpoint may serve a GPT-named model at different prices.
4
+ // Source: https://help.openai.com/en/articles/20001106 (2026-08-06).
5
+ function rates(input, output) {
6
+ return { inputPerMTok: input, cachedInputPerMTok: input * 0.1, outputPerMTok: output };
7
+ }
8
+ // Exact Codex model id (lowercased) to price card. An unknown or preview-only
9
+ // model deliberately remains unpriced.
10
+ const CODEX_MODEL_RATES = {
11
+ "gpt-5.6-sol": rates(5, 30),
12
+ "gpt-5.6-terra": rates(2, 12),
13
+ "gpt-5.6-luna": rates(0.2, 1.2),
14
+ "gpt-5.5": rates(5, 30),
15
+ "gpt-5.5-cyber": rates(12.5, 75),
16
+ "gpt-5.4": rates(2.5, 15),
17
+ "gpt-5.4-mini": rates(0.75, 4.5),
18
+ "gpt-5.3-codex": rates(1.75, 14),
19
+ "gpt-5.2": rates(1.75, 14),
20
+ };
21
+ /** The published price card for a Codex model, if it is a priced model. */
22
+ export function codexModelRates(model) {
23
+ return model ? CODEX_MODEL_RATES[model.trim().toLowerCase()] : undefined;
24
+ }
25
+ /**
26
+ * Price one Codex request from its disjoint token split. Codex does not charge
27
+ * cache writes, and `toAgentUsage` has already removed cached input from fresh
28
+ * input, so these three leaves can be multiplied independently.
29
+ */
30
+ export function priceCodexUsageUsd(usage, model) {
31
+ const card = codexModelRates(model);
32
+ if (!card)
33
+ return undefined;
34
+ return (((usage.inputTokens ?? 0) * card.inputPerMTok +
35
+ (usage.cachedInputTokens ?? 0) * card.cachedInputPerMTok +
36
+ (usage.outputTokens ?? 0) * card.outputPerMTok) /
37
+ 1000000);
38
+ }
39
+ //# sourceMappingURL=codex-pricing.js.map
@@ -207,6 +207,10 @@ declare class OpenCodeAgentSession implements AgentSession {
207
207
  private readonly subscribers;
208
208
  private nextTurnOrdinal;
209
209
  private turnState;
210
+ /** OpenCode can publish `session.status: idle` before the final tool part.
211
+ * Keep that terminal update attached to the completed turn, but never let it
212
+ * leak into a later foreground turn. */
213
+ private lateForegroundToolTurnId;
210
214
  private readonly runningToolCalls;
211
215
  private subAgentsByCallId;
212
216
  private subAgentCallIdByChildSessionId;
@@ -253,6 +257,8 @@ declare class OpenCodeAgentSession implements AgentSession {
253
257
  private consumeEventStream;
254
258
  private consumeOpenCodeStreamEvent;
255
259
  private emitBackgroundPermissionRequests;
260
+ private resolveForegroundTurnId;
261
+ private emitLateForegroundToolTerminals;
256
262
  private shouldStartAutonomousTurn;
257
263
  private startAutonomousTurn;
258
264
  private finishForegroundTurn;
@@ -2104,6 +2104,10 @@ class OpenCodeAgentSession {
2104
2104
  this.subscribers = new Set();
2105
2105
  this.nextTurnOrdinal = 0;
2106
2106
  this.turnState = { status: "idle" };
2107
+ /** OpenCode can publish `session.status: idle` before the final tool part.
2108
+ * Keep that terminal update attached to the completed turn, but never let it
2109
+ * leak into a later foreground turn. */
2110
+ this.lateForegroundToolTurnId = null;
2107
2111
  this.runningToolCalls = new Map();
2108
2112
  this.subAgentsByCallId = new Map();
2109
2113
  this.subAgentCallIdByChildSessionId = new Map();
@@ -2256,6 +2260,7 @@ class OpenCodeAgentSession {
2256
2260
  throw new Error("OpenCode is still stopping the previous turn");
2257
2261
  }
2258
2262
  this.runningToolCalls.clear();
2263
+ this.lateForegroundToolTurnId = null;
2259
2264
  this.subAgentsByCallId.clear();
2260
2265
  this.subAgentCallIdByChildSessionId.clear();
2261
2266
  const turnAbortController = new AbortController();
@@ -2655,16 +2660,8 @@ class OpenCodeAgentSession {
2655
2660
  foregroundEvents.push(translatedEvent);
2656
2661
  }
2657
2662
  }
2658
- if (!turnId && this.shouldStartAutonomousTurn(event, foregroundEvents)) {
2659
- turnId = this.startAutonomousTurn();
2660
- }
2663
+ turnId = this.resolveForegroundTurnId({ event, foregroundEvents, turnId, eventCount });
2661
2664
  if (!turnId) {
2662
- this.emitBackgroundPermissionRequests(foregroundEvents);
2663
- this.traceOpenCode("provider.opencode.event.skip", {
2664
- n: eventCount,
2665
- reason: "no_active_turn",
2666
- type: event.type,
2667
- });
2668
2665
  return;
2669
2666
  }
2670
2667
  this.traceOpenCode("provider.opencode.parsed_event", {
@@ -2701,6 +2698,40 @@ class OpenCodeAgentSession {
2701
2698
  }
2702
2699
  }
2703
2700
  }
2701
+ resolveForegroundTurnId(params) {
2702
+ if (params.turnId) {
2703
+ return params.turnId;
2704
+ }
2705
+ if (this.emitLateForegroundToolTerminals(params.foregroundEvents)) {
2706
+ return null;
2707
+ }
2708
+ if (this.shouldStartAutonomousTurn(params.event, params.foregroundEvents)) {
2709
+ return this.startAutonomousTurn();
2710
+ }
2711
+ this.emitBackgroundPermissionRequests(params.foregroundEvents);
2712
+ this.traceOpenCode("provider.opencode.event.skip", {
2713
+ n: params.eventCount,
2714
+ reason: "no_active_turn",
2715
+ type: params.event.type,
2716
+ });
2717
+ return null;
2718
+ }
2719
+ emitLateForegroundToolTerminals(events) {
2720
+ if (!this.lateForegroundToolTurnId) {
2721
+ return false;
2722
+ }
2723
+ let emitted = false;
2724
+ for (const event of events) {
2725
+ if (event.type !== "timeline" ||
2726
+ event.item.type !== "tool_call" ||
2727
+ event.item.status === "running") {
2728
+ continue;
2729
+ }
2730
+ this.notifySubscribers(event, this.lateForegroundToolTurnId);
2731
+ emitted = true;
2732
+ }
2733
+ return emitted;
2734
+ }
2704
2735
  shouldStartAutonomousTurn(event, foregroundEvents) {
2705
2736
  if (this.turnState.status !== "idle") {
2706
2737
  return false;
@@ -2729,6 +2760,7 @@ class OpenCodeAgentSession {
2729
2760
  const turnId = this.createTurnId();
2730
2761
  this.turnState = { status: "running", turnId };
2731
2762
  this.runningToolCalls.clear();
2763
+ this.lateForegroundToolTurnId = null;
2732
2764
  this.subAgentsByCallId.clear();
2733
2765
  this.subAgentCallIdByChildSessionId.clear();
2734
2766
  this.pendingUserMessageText = null;
@@ -2750,9 +2782,11 @@ class OpenCodeAgentSession {
2750
2782
  }
2751
2783
  if (event.type === "turn_canceled" || event.type === "turn_failed") {
2752
2784
  this.synthesizeInterruptedToolCalls(turnId);
2785
+ this.lateForegroundToolTurnId = null;
2753
2786
  }
2754
2787
  else {
2755
2788
  this.runningToolCalls.clear();
2789
+ this.lateForegroundToolTurnId = turnId;
2756
2790
  }
2757
2791
  this.pendingUserMessageText = null;
2758
2792
  this.pendingClientMessageId = null;
@@ -1857,7 +1857,7 @@ __d(function(g,_r,_i,_a,m,_e,d){"use strict";var e,t;Object.defineProperty(_e,'_
1857
1857
  __d(function(_g,_r,_i,_a,m,_e,d){"use strict";var t;Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"stateDiagram_default",{enumerable:!0,get:function(){return g}}),Object.defineProperty(_e,"stateRenderer_v3_unified_default",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"StateDB",{enumerable:!0,get:function(){return dt}}),Object.defineProperty(_e,"styles_default",{enumerable:!0,get:function(){return ut}});var e,s=_r(d[0]),i=_r(d[1]),n=_r(d[2]),r=_r(d[3]),o=_r(d[4]),a=_r(d[5]),l=_r(d[6]),c=_r(d[7]),h=_r(d[8]),u=_r(d[9]),p=(e=u)&&e.__esModule?e:{default:e},y=(function(){var t=(0,c.__name)(function(t,e,s,i){for(s=s||{},i=t.length;i--;s[t[i]]=e);return s},"o"),e=[1,2],s=[1,3],i=[1,4],n=[2,4],r=[1,9],o=[1,11],a=[1,16],l=[1,17],h=[1,18],u=[1,19],p=[1,33],y=[1,20],g=[1,21],f=[1,22],_=[1,23],S=[1,24],b=[1,26],k=[1,27],T=[1,28],E=[1,29],C=[1,30],x=[1,31],D=[1,32],$=[1,35],v=[1,36],I=[1,37],A=[1,38],L=[1,34],w=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],O=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],N=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],R={trace:(0,c.__name)(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"--\x3e":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",6:"SD",14:"DESCR",15:"--\x3e",16:"HIDE_EMPTY",17:"scale",18:"WIDTH",19:"COMPOSIT_STATE",20:"STRUCT_START",21:"STRUCT_STOP",22:"STATE_DESCR",23:"AS",24:"ID",25:"FORK",26:"JOIN",27:"CHOICE",28:"CONCURRENT",29:"note",31:"NOTE_TEXT",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",38:"CLICK",39:"STRING",40:"HREF",41:"classDef",42:"CLASSDEF_ID",43:"CLASSDEF_STYLEOPTS",44:"DEFAULT",45:"style",46:"STYLE_IDS",47:"STYLEDEF_STYLEOPTS",48:"class",49:"CLASSENTITY_IDS",50:"STYLECLASS",51:"direction_tb",52:"direction_bt",53:"direction_rl",54:"direction_lr",56:";",57:"EDGE_STATE",58:"STYLE_SEPARATOR",59:"left_of",60:"right_of"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:(0,c.__name)(function(t,e,s,i,n,r,o){var a=r.length-1;switch(n){case 3:return i.setRootDoc(r[a]),r[a];case 4:this.$=[];break;case 5:"nl"!=r[a]&&(r[a-1].push(r[a]),this.$=r[a-1]);break;case 6:case 7:case 12:this.$=r[a];break;case 8:this.$="nl";break;case 13:const t=r[a-1];t.description=i.trimColon(r[a]),this.$=t;break;case 14:this.$={stmt:"relation",state1:r[a-2],state2:r[a]};break;case 15:const e=i.trimColon(r[a]);this.$={stmt:"relation",state1:r[a-3],state2:r[a-1],description:e};break;case 19:this.$={stmt:"state",id:r[a-3],type:"default",description:"",doc:r[a-1]};break;case 20:var l=r[a],c=r[a-2].trim();if(r[a].match(":")){var h=r[a].split(":");l=h[0],c=[c,h[1]]}this.$={stmt:"state",id:l,type:"default",description:c};break;case 21:this.$={stmt:"state",id:r[a-3],type:"default",description:r[a-5],doc:r[a-1]};break;case 22:this.$={stmt:"state",id:r[a],type:"fork"};break;case 23:this.$={stmt:"state",id:r[a],type:"join"};break;case 24:this.$={stmt:"state",id:r[a],type:"choice"};break;case 25:this.$={stmt:"state",id:i.getDividerId(),type:"divider"};break;case 26:this.$={stmt:"state",id:r[a-1].trim(),note:{position:r[a-2].trim(),text:r[a].trim()}};break;case 29:this.$=r[a].trim(),i.setAccTitle(this.$);break;case 30:case 31:this.$=r[a].trim(),i.setAccDescription(this.$);break;case 32:this.$={stmt:"click",id:r[a-3],url:r[a-2],tooltip:r[a-1]};break;case 33:this.$={stmt:"click",id:r[a-3],url:r[a-1],tooltip:""};break;case 34:case 35:this.$={stmt:"classDef",id:r[a-1].trim(),classes:r[a].trim()};break;case 36:this.$={stmt:"style",id:r[a-1].trim(),styleClass:r[a].trim()};break;case 37:this.$={stmt:"applyClass",id:r[a-1].trim(),styleClass:r[a].trim()};break;case 38:i.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 39:i.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 40:i.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 41:i.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 44:case 45:this.$={stmt:"state",id:r[a].trim(),type:"default",description:""};break;case 46:case 47:this.$={stmt:"state",id:r[a-2].trim(),classes:[r[a].trim()],type:"default",description:""}}},"anonymous"),table:[{3:1,4:e,5:s,6:i},{1:[3]},{3:5,4:e,5:s,6:i},{3:6,4:e,5:s,6:i},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],n,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:r,5:o,8:8,9:10,10:12,11:13,12:14,13:15,16:a,17:l,19:h,22:u,24:p,25:y,26:g,27:f,28:_,29:S,32:25,33:b,35:k,37:T,38:E,41:C,45:x,48:D,51:$,52:v,53:I,54:A,57:L},t(w,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:a,17:l,19:h,22:u,24:p,25:y,26:g,27:f,28:_,29:S,32:25,33:b,35:k,37:T,38:E,41:C,45:x,48:D,51:$,52:v,53:I,54:A,57:L},t(w,[2,7]),t(w,[2,8]),t(w,[2,9]),t(w,[2,10]),t(w,[2,11]),t(w,[2,12],{14:[1,40],15:[1,41]}),t(w,[2,16]),{18:[1,42]},t(w,[2,18],{20:[1,43]}),{23:[1,44]},t(w,[2,22]),t(w,[2,23]),t(w,[2,24]),t(w,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(w,[2,28]),{34:[1,49]},{36:[1,50]},t(w,[2,31]),{13:51,24:p,57:L},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(O,[2,44],{58:[1,56]}),t(O,[2,45],{58:[1,57]}),t(w,[2,38]),t(w,[2,39]),t(w,[2,40]),t(w,[2,41]),t(w,[2,6]),t(w,[2,13]),{13:58,24:p,57:L},t(w,[2,17]),t(N,n,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(w,[2,29]),t(w,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(w,[2,14],{14:[1,71]}),{4:r,5:o,8:8,9:10,10:12,11:13,12:14,13:15,16:a,17:l,19:h,21:[1,72],22:u,24:p,25:y,26:g,27:f,28:_,29:S,32:25,33:b,35:k,37:T,38:E,41:C,45:x,48:D,51:$,52:v,53:I,54:A,57:L},t(w,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(w,[2,34]),t(w,[2,35]),t(w,[2,36]),t(w,[2,37]),t(O,[2,46]),t(O,[2,47]),t(w,[2,15]),t(w,[2,19]),t(N,n,{7:78}),t(w,[2,26]),t(w,[2,27]),{5:[1,79]},{5:[1,80]},{4:r,5:o,8:8,9:10,10:12,11:13,12:14,13:15,16:a,17:l,19:h,21:[1,81],22:u,24:p,25:y,26:g,27:f,28:_,29:S,32:25,33:b,35:k,37:T,38:E,41:C,45:x,48:D,51:$,52:v,53:I,54:A,57:L},t(w,[2,32]),t(w,[2,33]),t(w,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:(0,c.__name)(function(t,e){if(!e.recoverable){var s=new Error(t);throw s.hash=e,s}this.trace(t)},"parseError"),parse:(0,c.__name)(function(t){var e=this,s=[0],i=[],n=[null],r=[],o=this.table,a="",l=0,h=0,u=0,p=r.slice.call(arguments,1),y=Object.create(this.lexer),g={yy:{}};for(var f in this.yy)Object.prototype.hasOwnProperty.call(this.yy,f)&&(g.yy[f]=this.yy[f]);y.setInput(t,g.yy),g.yy.lexer=y,g.yy.parser=this,void 0===y.yylloc&&(y.yylloc={});var _=y.yylloc;r.push(_);var S=y.options&&y.options.ranges;function b(){var t;return"number"!=typeof(t=i.pop()||y.lex()||1)&&(t instanceof Array&&(t=(i=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError,(0,c.__name)(function(t){s.length=s.length-2*t,n.length=n.length-t,r.length=r.length-t},"popStack"),(0,c.__name)(b,"lex");for(var k,T,E,C,x,D,$,v,I,A={};;){if(E=s[s.length-1],this.defaultActions[E]?C=this.defaultActions[E]:(null==k&&(k=b()),C=o[E]&&o[E][k]),void 0===C||!C.length||!C[0]){var L="";for(D in I=[],o[E])this.terminals_[D]&&D>2&&I.push("'"+this.terminals_[D]+"'");L=y.showPosition?"Parse error on line "+(l+1)+":\n"+y.showPosition()+"\nExpecting "+I.join(", ")+", got '"+(this.terminals_[k]||k)+"'":"Parse error on line "+(l+1)+": Unexpected "+(1==k?"end of input":"'"+(this.terminals_[k]||k)+"'"),this.parseError(L,{text:y.match,token:this.terminals_[k]||k,line:y.yylineno,loc:_,expected:I})}if(C[0]instanceof Array&&C.length>1)throw new Error("Parse Error: multiple actions possible at state: "+E+", token: "+k);switch(C[0]){case 1:s.push(k),n.push(y.yytext),r.push(y.yylloc),s.push(C[1]),k=null,T?(k=T,T=null):(h=y.yyleng,a=y.yytext,l=y.yylineno,_=y.yylloc,u>0&&u--);break;case 2:if($=this.productions_[C[1]][1],A.$=n[n.length-$],A._$={first_line:r[r.length-($||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-($||1)].first_column,last_column:r[r.length-1].last_column},S&&(A._$.range=[r[r.length-($||1)].range[0],r[r.length-1].range[1]]),void 0!==(x=this.performAction.apply(A,[a,h,l,g.yy,C[1],n,r].concat(p))))return x;$&&(s=s.slice(0,-1*$*2),n=n.slice(0,-1*$),r=r.slice(0,-1*$)),s.push(this.productions_[C[1]][0]),n.push(A.$),r.push(A._$),v=o[s[s.length-2]][s[s.length-1]],s.push(v);break;case 3:return!0}}return!0},"parse")},B=(function(){return{EOF:1,parseError:(0,c.__name)(function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},"parseError"),setInput:(0,c.__name)(function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:(0,c.__name)(function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},"input"),unput:(0,c.__name)(function(t){var e=t.length,s=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var i=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),s.length-1&&(this.yylineno-=s.length-1);var n=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:s?(s.length===i.length?this.yylloc.first_column:0)+i[i.length-s.length].length-s[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[n[0],n[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},"unput"),more:(0,c.__name)(function(){return this._more=!0,this},"more"),reject:(0,c.__name)(function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},"reject"),less:(0,c.__name)(function(t){this.unput(this.match.slice(t))},"less"),pastInput:(0,c.__name)(function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:(0,c.__name)(function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:(0,c.__name)(function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},"showPosition"),test_match:(0,c.__name)(function(t,e){var s,i,n;if(this.options.backtrack_lexer&&(n={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(n.yylloc.range=this.yylloc.range.slice(0))),(i=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=i.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:i?i[i.length-1].length-i[i.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],s=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),s)return s;if(this._backtrack){for(var r in n)this[r]=n[r];return!1}return!1},"test_match"),next:(0,c.__name)(function(){if(this.done)return this.EOF;var t,e,s,i;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var n=this._currentRules(),r=0;r<n.length;r++)if((s=this._input.match(this.rules[n[r]]))&&(!e||s[0].length>e[0].length)){if(e=s,i=r,this.options.backtrack_lexer){if(!1!==(t=this.test_match(s,n[r])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,n[i]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:(0,c.__name)(function(){var t=this.next();return t||this.lex()},"lex"),begin:(0,c.__name)(function(t){this.conditionStack.push(t)},"begin"),popState:(0,c.__name)(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:(0,c.__name)(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:(0,c.__name)(function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},"topState"),pushState:(0,c.__name)(function(t){this.begin(t)},"pushState"),stateStackSize:(0,c.__name)(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:(0,c.__name)(function(t,e,s,i){function n(){const s=e.yytext.indexOf("%%");if(0===s)return!1;if(s>0){const i=e.yytext.slice(0,s),n=e.yytext.slice(s);n&&t.lexer.unput(n),e.yytext=i}return!0}(0,c.__name)(n,"processId");switch(s){case 0:return 38;case 1:return 40;case 2:return 39;case 3:return 44;case 4:case 43:return 51;case 5:case 44:return 52;case 6:case 45:return 53;case 7:case 46:return 54;case 8:case 78:return 5;case 9:case 10:case 11:case 12:case 57:case 63:break;case 13:case 33:return this.pushState("SCALE"),17;case 14:case 34:return 18;case 15:case 21:case 35:case 50:case 54:this.popState();break;case 16:return this.begin("acc_title"),33;case 17:return this.popState(),"acc_title_value";case 18:return this.begin("acc_descr"),35;case 19:return this.popState(),"acc_descr_value";case 20:this.begin("acc_descr_multiline");break;case 22:return"acc_descr_multiline_value";case 23:return this.pushState("CLASSDEF"),41;case 24:return this.popState(),this.pushState("CLASSDEFID"),"DEFAULT_CLASSDEF_ID";case 25:return this.popState(),this.pushState("CLASSDEFID"),42;case 26:return this.popState(),43;case 27:return this.pushState("CLASS"),48;case 28:return this.popState(),this.pushState("CLASS_STYLE"),49;case 29:return this.popState(),50;case 30:return this.pushState("STYLE"),45;case 31:return this.popState(),this.pushState("STYLEDEF_STYLES"),46;case 32:return this.popState(),47;case 36:this.pushState("STATE");break;case 37:case 40:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),25;case 38:case 41:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),26;case 39:case 42:return this.popState(),e.yytext=e.yytext.slice(0,-10).trim(),27;case 47:this.pushState("STATE_STRING");break;case 48:return this.pushState("STATE_ID"),"AS";case 49:case 65:if(!n())return;return this.popState(),"ID";case 51:return"STATE_DESCR";case 52:throw new Error('Error: State name must be a single word. Found: "'+e.yytext.trim()+'"');case 53:return 19;case 55:return this.popState(),this.pushState("struct"),20;case 56:return this.popState(),21;case 58:return this.begin("NOTE"),29;case 59:return this.popState(),this.pushState("NOTE_ID"),59;case 60:return this.popState(),this.pushState("NOTE_ID"),60;case 61:this.popState(),this.pushState("FLOATING_NOTE");break;case 62:return this.popState(),this.pushState("FLOATING_NOTE_ID"),"AS";case 64:return"NOTE_TEXT";case 66:if(!n())return;return this.popState(),this.pushState("NOTE_TEXT"),24;case 67:return this.popState(),e.yytext=e.yytext.substr(2).trim(),31;case 68:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),31;case 69:case 70:return 6;case 71:return 16;case 72:return 57;case 73:if(!n())return;return 24;case 74:return e.yytext=e.yytext.trim(),14;case 75:return 15;case 76:return 28;case 77:return 58;case 79:return"INVALID"}},"anonymous"),rules:[/^(?:click\b)/i,/^(?:href\b)/i,/^(?:"[^"]*")/i,/^(?:default\b)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:classDef\s+)/i,/^(?:DEFAULT\s+)/i,/^(?:\w+\s+)/i,/^(?:[^\n]*)/i,/^(?:class\s+)/i,/^(?:(\w+)+((,\s*\w+)*))/i,/^(?:[^\n]*)/i,/^(?:style\s+)/i,/^(?:[\w,]+\s+)/i,/^(?:[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:state\s+)/i,/^(?:.*<<fork>>)/i,/^(?:.*<<join>>)/i,/^(?:.*<<choice>>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:\w+\s+\w+.*?\{)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?\n\s*end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:(?:[^:\n;]|:[^:\n;])+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?::::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[10,11,12],inclusive:!1},struct:{rules:[10,11,12,23,27,30,36,43,44,45,46,56,57,58,72,73,74,75,76,77],inclusive:!1},FLOATING_NOTE_ID:{rules:[65],inclusive:!1},FLOATING_NOTE:{rules:[62,63,64],inclusive:!1},NOTE_TEXT:{rules:[67,68],inclusive:!1},NOTE_ID:{rules:[66],inclusive:!1},NOTE:{rules:[59,60,61],inclusive:!1},STYLEDEF_STYLEOPTS:{rules:[],inclusive:!1},STYLEDEF_STYLES:{rules:[32],inclusive:!1},STYLE_IDS:{rules:[],inclusive:!1},STYLE:{rules:[31],inclusive:!1},CLASS_STYLE:{rules:[29],inclusive:!1},CLASS:{rules:[28],inclusive:!1},CLASSDEFID:{rules:[26],inclusive:!1},CLASSDEF:{rules:[24,25],inclusive:!1},acc_descr_multiline:{rules:[21,22],inclusive:!1},acc_descr:{rules:[19],inclusive:!1},acc_title:{rules:[17],inclusive:!1},SCALE:{rules:[14,15,34,35],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[49],inclusive:!1},STATE_STRING:{rules:[50,51],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[10,11,12,37,38,39,40,41,42,47,48,52,53,54,55],inclusive:!1},ID:{rules:[10,11,12],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,11,12,13,16,18,20,23,27,30,33,36,55,58,69,70,71,72,73,74,75,77,78,79],inclusive:!0}}}})();function F(){this.yy={}}return R.lexer=B,(0,c.__name)(F,"Parser"),F.prototype=R,R.Parser=F,new F})();y.parser=y;var g=y,f="state",_="root",S="relation",b="default",k="divider",T="fill:none",E="fill: #333",C="markdown",x="normal",D="rect",$="rectWithTitle",v="divider",I="roundedWithTitle",A="statediagram",L=`${A}-state`,w="transition",O=`${w} note-edge`,N=`${A}-note`,R=`${A}-cluster`,B=`${A}-cluster-alt`,F="parent",P="note",Y="----",G=`${Y}${P}`,j=`${Y}${F}`,z=(0,c.__name)((t,e="TB")=>{if(!t.doc)return e;let s=e;for(const e of t.doc)"dir"===e.stmt&&(s=e.value);return s},"getDir"),M={getClasses:(0,c.__name)(function(t,e){return e.db.getClasses()},"getClasses"),draw:(0,c.__name)(async function(t,e,r,c){l.log.info("REF0:"),l.log.info("Drawing state diagram (v2)",e);const{securityLevel:h,state:u,layout:p}=(0,a.getConfig2)();c.db.extract(c.db.getRootDocV2());const y=c.db.getData(),g=(0,s.getDiagramElement)(e,h);y.type=c.type,y.layoutAlgorithm=p,y.nodeSpacing=u?.nodeSpacing||50,y.rankSpacing=u?.rankSpacing||50;"neo"===(0,a.getConfig2)().look?y.markers=["barbNeo"]:y.markers=["barb"],y.diagramId=e,await(0,n.render)(y,g);try{("function"==typeof c.db.getLinks?c.db.getLinks():new Map).forEach((t,e)=>{const s="string"==typeof e?e:"string"==typeof e?.id?e.id:"",i=y.nodes.find(t=>t.id===s);if(!s)return void l.log.warn("\u26a0\ufe0f Invalid or missing stateId from key:",JSON.stringify(e));const n=g.node()?.querySelectorAll("g.node, g.rough-node");let r;if(n?.forEach(t=>{const e=t.textContent?.trim();t.id!==i?.domId&&e!==s||(r=t)}),!r)return void l.log.warn("\u26a0\ufe0f Could not find node matching text:",s);const o=r.parentNode;if(!o)return void l.log.warn("\u26a0\ufe0f Node has no parent, cannot wrap:",s);const a=document.createElementNS("http://www.w3.org/2000/svg","a"),c=t.url.replace(/^"+|"+$/g,"");if(a.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",c),a.setAttribute("target","_blank"),t.tooltip){const e=t.tooltip.replace(/^"+|"+$/g,"");a.setAttribute("title",e),r.setAttribute("title",e)}o.replaceChild(a,r),a.appendChild(r),l.log.info("\ud83d\udd17 Wrapped node in <a> tag for:",s,t.url)})}catch(t){l.log.error("\u274c Error injecting clickable links:",t)}o.utils_default.insertTitle(g,"statediagramTitleText",u?.titleTopMargin??25,c.db.getDiagramTitle()),(0,i.setupViewPortForSVG)(g,8,A,u?.useMaxWidth??!0)},"draw"),getDir:z},W=new Map,U=0;function X(t="",e=0,s="",i=Y){return`state-${t}${null!==s&&s.length>0?`${i}${s}`:""}-${e}`}(0,c.__name)(X,"stateDomId");var H=(0,c.__name)((t,e,s,i,n,r,o,c)=>{l.log.trace("items",e),e.forEach(e=>{switch(e.stmt){case f:case b:Q(t,e,s,i,n,r,o,c);break;case S:{Q(t,e.state1,s,i,n,r,o,c),Q(t,e.state2,s,i,n,r,o,c);const l="neo"===o,h={id:"edge"+U,start:e.state1.id,end:e.state2.id,arrowhead:"normal",arrowTypeEnd:l?"arrow_barb_neo":"arrow_barb",style:T,labelStyle:"",label:a.common_default.sanitizeText(e.description??"",(0,a.getConfig2)()),arrowheadStyle:E,labelpos:"c",labelType:C,thickness:x,classes:w,look:o};n.push(h),U++}}})},"setupDoc"),V=(0,c.__name)((t,e="TB")=>{let s=e;if(t.doc)for(const e of t.doc)"dir"===e.stmt&&(s=e.value);return s},"getDir");function J(t,e,s){if(!e.id||"</join></fork>"===e.id||"</choice>"===e.id)return;e.cssClasses&&(Array.isArray(e.cssCompiledStyles)||(e.cssCompiledStyles=[]),e.cssClasses.split(" ").forEach(t=>{const i=s.get(t);i&&(e.cssCompiledStyles=[...e.cssCompiledStyles??[],...i.styles])}));const i=t.find(t=>t.id===e.id);i?Object.assign(i,e):t.push(e)}function K(t){return t?.classes?.join(" ")??""}function q(t){return t?.styles??[]}(0,c.__name)(J,"insertOrUpdateNode"),(0,c.__name)(K,"getClassesFromDbInfo"),(0,c.__name)(q,"getStylesFromDbInfo");var Q=(0,c.__name)((t,e,s,i,n,r,o,c)=>{const h=e.id,u=s.get(h),p=K(u),y=q(u),g=(0,a.getConfig2)();if(l.log.info("dataFetcher parsedItem",e,u,y),"root"!==h){let s=D;!0===e.start?s="stateStart":!1===e.start&&(s="stateEnd"),e.type!==b&&(s=e.type),W.get(h)||W.set(h,{id:h,shape:s,description:a.common_default.sanitizeText(h,g),cssClasses:`${p} ${L}`,cssStyles:y});const u=W.get(h);e.description&&(Array.isArray(u.description)?(u.shape=$,u.description.push(e.description)):u.description?.length&&u.description.length>0?(u.shape=$,u.description===h?u.description=[e.description]:u.description=[u.description,e.description]):(u.shape=D,u.description=e.description),u.description=a.common_default.sanitizeTextOrArray(u.description,g)),1===u.description?.length&&u.shape===$&&("group"===u.type?u.shape=I:u.shape=D),!u.type&&e.doc&&(l.log.info("Setting cluster for XCX",h,V(e)),u.type="group",u.isGroup=!0,u.dir=V(e),u.explicitDir=e.doc.some(t=>"dir"===t.stmt),u.shape=e.type===k?v:I,u.cssClasses=`${u.cssClasses} ${R} ${r?B:""}`);const f={labelStyle:"",shape:u.shape,label:u.description,cssClasses:u.cssClasses,cssCompiledStyles:[],cssStyles:u.cssStyles,id:h,dir:u.dir,domId:X(h,U),type:u.type,isGroup:"group"===u.type,padding:8,rx:10,ry:10,look:o,labelType:"markdown"};if(f.shape===v&&(f.label=""),t&&"root"!==t.id&&(l.log.trace("Setting node ",h," to be child of its parent ",t.id),f.parentId=t.id),f.centerLabel=!0,e.note){const t={labelStyle:"",shape:"note",label:e.note.text,labelType:"markdown",cssClasses:N,cssStyles:[],cssCompiledStyles:[],id:h+G+"-"+U,domId:X(h,U,P),type:u.type,isGroup:"group"===u.type,padding:g.flowchart?.padding,look:o,position:e.note.position},s=h+j,r={labelStyle:"",shape:"noteGroup",label:e.note.text,cssClasses:u.cssClasses,cssStyles:[],id:h+j,domId:X(h,U,F),type:"group",isGroup:!0,padding:16,look:o,position:e.note.position};U++,r.id=s,t.parentId=s,J(i,r,c),J(i,t,c),J(i,f,c);let a=h,l=t.id;"left of"===e.note.position&&(a=t.id,l=h),n.push({id:a+"-"+l,start:a,end:l,arrowhead:"none",arrowTypeEnd:"",style:T,labelStyle:"",classes:O,arrowheadStyle:E,labelpos:"c",labelType:C,thickness:x,look:o})}else J(i,f,c)}e.doc&&(l.log.trace("Adding nodes children "),H(e,e.doc,s,i,n,!r,o,c))},"dataFetcher"),Z=(0,c.__name)(()=>{W.clear(),U=0},"reset"),tt="[*]",et="start",st="[*]",it="end",nt="color",rt="fill",ot="bgFill",at=",",lt=(0,c.__name)(()=>new Map,"newClassesList"),ct=(0,c.__name)(()=>({relations:[],states:new Map,documents:{}}),"newDoc"),ht=(0,c.__name)(t=>JSON.parse(JSON.stringify(t)),"clone"),dt=(t=class{constructor(t){this.version=t,this.nodes=[],this.edges=[],this.rootDoc=[],this.classes=lt(),this.documents={root:ct()},this.currentDocument=this.documents.root,this.startEndCount=0,this.dividerCnt=0,this.links=new Map,this.funs=[],this.getAccTitle=a.getAccTitle,this.setAccTitle=a.setAccTitle,this.getAccDescription=a.getAccDescription,this.setAccDescription=a.setAccDescription,this.setDiagramTitle=a.setDiagramTitle,this.getDiagramTitle=a.getDiagramTitle,this.clear(),this.setRootDoc=this.setRootDoc.bind(this),this.getDividerId=this.getDividerId.bind(this),this.setDirection=this.setDirection.bind(this),this.trimColon=this.trimColon.bind(this),this.bindFunctions=this.bindFunctions.bind(this)}extract(t){this.clear(!0);for(const e of Array.isArray(t)?t:t.doc)switch(e.stmt){case f:this.addState(e.id.trim(),e.type,e.doc,e.description,e.note);break;case S:this.addRelation(e.state1,e.state2,e.description);break;case"classDef":this.addStyleClass(e.id.trim(),e.classes);break;case"style":this.handleStyleDef(e);break;case"applyClass":this.setCssClass(e.id.trim(),e.styleClass);break;case"click":this.addLink(e.id,e.url,e.tooltip)}const e=this.getStates(),s=(0,a.getConfig2)();Z(),Q(void 0,this.getRootDocV2(),e,this.nodes,this.edges,!0,s.look,this.classes);for(const t of this.nodes)if(Array.isArray(t.label)){if(t.description=t.label.slice(1),t.isGroup&&t.description.length>0)throw new Error(`Group nodes can only have label. Remove the additional description for node [${t.id}]`);t.label=t.label[0]}}handleStyleDef(t){const e=t.id.trim().split(","),s=t.styleClass.split(",");for(const t of e){let e=this.getState(t);if(!e){const s=t.trim();this.addState(s),e=this.getState(s)}e&&(e.styles=s.map(t=>t.replace(/;/g,"")?.trim()))}}setRootDoc(t){l.log.info("Setting root doc",t),this.rootDoc=t,1===this.version?this.extract(t):this.extract(this.getRootDocV2())}docTranslator(t,e,s){if(e.stmt===S)return this.docTranslator(t,e.state1,!0),void this.docTranslator(t,e.state2,!1);if(e.stmt===f&&(e.id===tt?(e.id=t.id+(s?"_start":"_end"),e.start=s):e.id=e.id.trim()),e.stmt!==_&&e.stmt!==f||!e.doc)return;const i=[];let n=[];for(const t of e.doc)if(t.type===k){const e=ht(t);e.doc=ht(n),i.push(e),n=[]}else n.push(t);if(i.length>0&&n.length>0){const t={stmt:f,id:(0,o.generateId)(),type:"divider",doc:ht(n)};i.push(ht(t)),e.doc=i}e.doc.forEach(t=>this.docTranslator(e,t,!0))}getRootDocV2(){return this.docTranslator({id:_,stmt:_},{id:_,stmt:_,doc:this.rootDoc},!0),{id:_,doc:this.rootDoc}}addState(t,e=b,s=void 0,i=void 0,n=void 0,r=void 0,o=void 0,c=void 0){const h=t?.trim();if(this.currentDocument.states.has(h)){const t=this.currentDocument.states.get(h);if(!t)throw new Error(`State not found: ${h}`);t.doc||(t.doc=s),t.type||(t.type=e)}else l.log.info("Adding state ",h,i),this.currentDocument.states.set(h,{stmt:f,id:h,descriptions:[],type:e,doc:s,note:n,classes:[],styles:[],textStyles:[]});if(i){l.log.info("Setting state description",h,i);(Array.isArray(i)?i:[i]).forEach(t=>this.addDescription(h,t.trim()))}if(n){const t=this.currentDocument.states.get(h);if(!t)throw new Error(`State not found: ${h}`);t.note=n,t.note.text=a.common_default.sanitizeText(t.note.text,(0,a.getConfig2)())}if(r){l.log.info("Setting state classes",h,r);(Array.isArray(r)?r:[r]).forEach(t=>this.setCssClass(h,t.trim()))}if(o){l.log.info("Setting state styles",h,o);(Array.isArray(o)?o:[o]).forEach(t=>this.setStyle(h,t.trim()))}if(c){l.log.info("Setting state styles",h,o);(Array.isArray(c)?c:[c]).forEach(t=>this.setTextStyle(h,t.trim()))}}clear(t){this.nodes=[],this.edges=[],this.funs=[this.setupToolTips.bind(this)],this.documents={root:ct()},this.currentDocument=this.documents.root,this.startEndCount=0,this.classes=lt(),t||(this.links=new Map,(0,a.clear)())}getState(t){return this.currentDocument.states.get(t)}getStates(){return this.currentDocument.states}logDocuments(){l.log.info("Documents = ",this.documents)}getRelations(){return this.currentDocument.relations}addLink(t,e,s){this.links.set(t,{url:e,tooltip:s}),l.log.warn("Adding link",t,e,s)}getLinks(){return this.links}startIdIfNeeded(t=""){return t===tt?(this.startEndCount++,`${et}${this.startEndCount}`):t}startTypeIfNeeded(t="",e=b){return t===tt?et:e}endIdIfNeeded(t=""){return t===st?(this.startEndCount++,`${it}${this.startEndCount}`):t}endTypeIfNeeded(t="",e=b){return t===st?it:e}addRelationObjs(t,e,s=""){const i=this.startIdIfNeeded(t.id.trim()),n=this.startTypeIfNeeded(t.id.trim(),t.type),r=this.startIdIfNeeded(e.id.trim()),o=this.startTypeIfNeeded(e.id.trim(),e.type);this.addState(i,n,t.doc,t.description,t.note,t.classes,t.styles,t.textStyles),this.addState(r,o,e.doc,e.description,e.note,e.classes,e.styles,e.textStyles),this.currentDocument.relations.push({id1:i,id2:r,relationTitle:a.common_default.sanitizeText(s,(0,a.getConfig2)())})}addRelation(t,e,s){if("object"==typeof t&&"object"==typeof e)this.addRelationObjs(t,e,s);else if("string"==typeof t&&"string"==typeof e){const i=this.startIdIfNeeded(t.trim()),n=this.startTypeIfNeeded(t),r=this.endIdIfNeeded(e.trim()),o=this.endTypeIfNeeded(e);this.addState(i,n),this.addState(r,o),this.currentDocument.relations.push({id1:i,id2:r,relationTitle:s?a.common_default.sanitizeText(s,(0,a.getConfig2)()):void 0})}}addDescription(t,e){const s=this.currentDocument.states.get(t),i=e.startsWith(":")?e.replace(":","").trim():e;s?.descriptions?.push(a.common_default.sanitizeText(i,(0,a.getConfig2)()))}cleanupLabel(t){return t.startsWith(":")?t.slice(2).trim():t.trim()}getDividerId(){return this.dividerCnt++,`divider-id-${this.dividerCnt}`}addStyleClass(t,e=""){this.classes.has(t)||this.classes.set(t,{id:t,styles:[],textStyles:[]});const s=this.classes.get(t);e&&s&&e.split(at).forEach(t=>{const e=t.replace(/([^;]*);/,"$1").trim();if(RegExp(nt).exec(t)){const t=e.replace(rt,ot).replace(nt,rt);s.textStyles.push(t)}s.styles.push(e)})}getClasses(){return this.classes}setupToolTips(t){const e=(0,r.createTooltip)();(0,h.select)(t).select("svg").selectAll("g.node, g.rough-node").on("mouseover",t=>{const s=(0,h.select)(t.currentTarget),i=s.attr("title");if(null===i)return;const n=t.currentTarget?.getBoundingClientRect();e.transition().duration(200).style("opacity",".9"),e.style("left",window.scrollX+n.left+(n.right-n.left)/2+"px").style("top",window.scrollY+n.bottom+"px"),e.html(p.default.sanitize(i)),s.classed("hover",!0)}).on("mouseout",t=>{e.transition().duration(500).style("opacity",0);(0,h.select)(t.currentTarget).classed("hover",!1)})}setCssClass(t,e){t.split(",").forEach(t=>{let s=this.getState(t);if(!s){const e=t.trim();this.addState(e),s=this.getState(e)}s?.classes?.push(e)})}setStyle(t,e){this.getState(t)?.styles?.push(e)}setTextStyle(t,e){this.getState(t)?.textStyles?.push(e)}bindFunctions(t){this.funs.forEach(e=>{e(t)})}getDirectionStatement(){return this.rootDoc.find(t=>"dir"===t.stmt)}getDirection(){return this.getDirectionStatement()?.value??"TB"}setDirection(t){const e=this.getDirectionStatement();e?e.value=t:this.rootDoc.unshift({stmt:"dir",value:t})}trimColon(t){return t.startsWith(":")?t.slice(1).trim():t.trim()}getData(){const t=(0,a.getConfig2)();return{nodes:this.nodes,edges:this.edges,other:{},config:t,direction:z(this.getRootDocV2())}}getConfig(){return(0,a.getConfig2)().state}},(0,c.__name)(t,"StateDB"),t.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3},t),ut=(0,c.__name)(t=>`\ndefs [id$="-barbEnd"] {\n fill: ${t.transitionColor};\n stroke: ${t.transitionColor};\n }\ng.stateGroup text {\n fill: ${t.nodeBorder};\n stroke: none;\n font-size: 10px;\n}\ng.stateGroup text {\n fill: ${t.textColor};\n stroke: none;\n font-size: 10px;\n\n}\ng.stateGroup .state-title {\n font-weight: bolder;\n fill: ${t.stateLabelColor};\n}\n\ng.stateGroup rect {\n fill: ${t.mainBkg};\n stroke: ${t.nodeBorder};\n}\n\ng.stateGroup line {\n stroke: ${t.lineColor};\n stroke-width: ${t.strokeWidth||1};\n}\n\n.transition {\n stroke: ${t.transitionColor};\n stroke-width: ${t.strokeWidth||1};\n fill: none;\n}\n\n.stateGroup .composit {\n fill: ${t.background};\n border-bottom: 1px\n}\n\n.stateGroup .alt-composit {\n fill: #e0e0e0;\n border-bottom: 1px\n}\n\n.state-note {\n stroke: ${t.noteBorderColor};\n fill: ${t.noteBkgColor};\n\n text {\n fill: ${t.noteTextColor};\n stroke: none;\n font-size: 10px;\n }\n}\n\n.stateLabel .box {\n stroke: none;\n stroke-width: 0;\n fill: ${t.mainBkg};\n opacity: 0.5;\n}\n\n.edgeLabel .label rect {\n fill: ${t.labelBackgroundColor};\n opacity: 0.5;\n}\n.edgeLabel {\n background-color: ${t.edgeLabelBackground};\n p {\n background-color: ${t.edgeLabelBackground};\n }\n rect {\n opacity: 0.5;\n background-color: ${t.edgeLabelBackground};\n fill: ${t.edgeLabelBackground};\n }\n text-align: center;\n}\n.edgeLabel .label text {\n fill: ${t.transitionLabelColor||t.tertiaryTextColor};\n}\n.label div .edgeLabel {\n color: ${t.transitionLabelColor||t.tertiaryTextColor};\n}\n\n.stateLabel text {\n fill: ${t.stateLabelColor};\n font-size: 10px;\n font-weight: bold;\n}\n\n.node circle.state-start {\n fill: ${t.specialStateColor};\n stroke: ${t.specialStateColor};\n}\n\n.node .fork-join {\n fill: ${t.specialStateColor};\n stroke: ${t.specialStateColor};\n}\n\n.node circle.state-end {\n fill: ${t.innerEndBackground};\n stroke: ${t.background};\n stroke-width: 1.5\n}\n.end-state-inner {\n fill: ${t.compositeBackground||t.background};\n // stroke: ${t.background};\n stroke-width: 1.5\n}\n\n.node rect {\n fill: ${t.stateBkg||t.mainBkg};\n stroke: ${t.stateBorder||t.nodeBorder};\n stroke-width: ${t.strokeWidth||1}px;\n}\n.node polygon {\n fill: ${t.mainBkg};\n stroke: ${t.stateBorder||t.nodeBorder};;\n stroke-width: ${t.strokeWidth||1}px;\n}\n[id$="-barbEnd"] {\n fill: ${t.lineColor};\n}\n\n.statediagram-cluster rect {\n fill: ${t.compositeTitleBackground};\n stroke: ${t.stateBorder||t.nodeBorder};\n stroke-width: ${t.strokeWidth||1}px;\n}\n\n.cluster-label, .nodeLabel {\n color: ${t.stateLabelColor};\n // line-height: 1;\n}\n\n.statediagram-cluster rect.outer {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state .divider {\n stroke: ${t.stateBorder||t.nodeBorder};\n}\n\n.statediagram-state .title-state {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-cluster.statediagram-cluster .inner {\n fill: ${t.compositeBackground||t.background};\n}\n.statediagram-cluster.statediagram-cluster-alt .inner {\n fill: ${t.altBackground?t.altBackground:"#efefef"};\n}\n\n.statediagram-cluster .inner {\n rx:0;\n ry:0;\n}\n\n.statediagram-state rect.basic {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state rect.divider {\n stroke-dasharray: 10,10;\n fill: ${t.altBackground?t.altBackground:"#efefef"};\n}\n\n.note-edge {\n stroke-dasharray: 5;\n}\n\n.statediagram-note rect {\n fill: ${t.noteBkgColor};\n stroke: ${t.noteBorderColor};\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n.statediagram-note rect {\n fill: ${t.noteBkgColor};\n stroke: ${t.noteBorderColor};\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n\n.statediagram-note text {\n fill: ${t.noteTextColor};\n}\n\n.statediagram-note .nodeLabel {\n color: ${t.noteTextColor};\n}\n.statediagram .edgeLabel {\n color: red; // ${t.noteTextColor};\n}\n\n[id$="-dependencyStart"], [id$="-dependencyEnd"] {\n fill: ${t.lineColor};\n stroke: ${t.lineColor};\n stroke-width: ${t.strokeWidth||1};\n}\n\n.statediagramTitleText {\n text-anchor: middle;\n font-size: 18px;\n fill: ${t.textColor};\n}\n\n[data-look="neo"].statediagram-cluster rect {\n fill: ${t.mainBkg};\n stroke: ${t.useGradient?"url("+t.svgId+"-gradient)":t.stateBorder||t.nodeBorder};\n stroke-width: ${t.strokeWidth??1};\n}\n[data-look="neo"].statediagram-cluster rect.outer {\n rx: ${t.radius}px;\n ry: ${t.radius}px;\n filter: ${t.dropShadow?t.dropShadow.replace("url(#drop-shadow)",`url(${t.svgId}-drop-shadow)`):"none"}\n}\n`,"getStyles")},6906,[6884,6885,5021,6881,5029,5030,5031,5032,5034,5035]);
1858
1858
  __d(function(g,_r,_i,_a,m,_e,d){"use strict";var e,t;const n=["railroad","svgId","theme","look"];Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"db",{enumerable:!0,get:function(){return S}}),Object.defineProperty(_e,"getStyles",{enumerable:!0,get:function(){return E}}),Object.defineProperty(_e,"renderer",{enumerable:!0,get:function(){return q}});var r,i=_r(d[0]),a=(r=i)&&r.__esModule?r:{default:r},o=_r(d[1]),l=_r(d[2]),s=_r(d[3]),c=_r(d[4]),h="",p="",u="",f=[],T=new Map,x=(0,c.__name)(e=>(0,l.sanitizeText)(e,(0,l.getConfig2)()),"sanitizeText"),w=(0,c.__name)(e=>{switch(e.type){case"terminal":return Object.assign({},e,{value:x(e.value)});case"nonterminal":return Object.assign({},e,{name:x(e.name)});case"sequence":return Object.assign({},e,{elements:e.elements.map(w)});case"choice":return Object.assign({},e,{alternatives:e.alternatives.map(w)});case"optional":return Object.assign({},e,{element:w(e.element)});case"repetition":return Object.assign({},e,{element:w(e.element),separator:e.separator?w(e.separator):void 0});case"special":return Object.assign({},e,{text:x(e.text)})}},"sanitizeAstNode"),k=(0,c.__name)(()=>{h="",p="",u="",f.length=0,T.clear(),(0,l.clear)(),s.log.debug("[Railroad] Database cleared")},"clear"),C=(0,c.__name)(e=>{h=x(e),s.log.debug("[Railroad] Title set:",e)},"setTitle"),b=(0,c.__name)(()=>h,"getTitle"),S={clear:k,setTitle:C,getTitle:b,addRule:(0,c.__name)(e=>{const t=Object.assign({},e,{name:x(e.name),definition:w(e.definition),comment:e.comment?x(e.comment):void 0});s.log.debug("[Railroad] Adding rule:",t.name),T.has(t.name)&&s.log.warn(`[Railroad] Rule '${t.name}' is already defined. Overwriting.`),f.push(t),T.set(t.name,t)},"addRule"),getRules:(0,c.__name)(()=>f,"getRules"),getRule:(0,c.__name)(e=>T.get(e),"getRule"),setAccTitle:(0,c.__name)(e=>{p=x(e).replace(/^\s+/g,""),s.log.debug("[Railroad] Accessibility title set:",e)},"setAccTitle"),getAccTitle:(0,c.__name)(()=>p,"getAccTitle"),setAccDescription:(0,c.__name)(e=>{u=x(e).replace(/\n\s+/g,"\n"),s.log.debug("[Railroad] Accessibility description set:",e)},"setAccDescription"),getAccDescription:(0,c.__name)(()=>u,"getAccDescription"),setDiagramTitle:C,getDiagramTitle:b},F={compactMode:!1,padding:10,verticalSeparation:8,horizontalSeparation:10,arcRadius:10,fontSize:14,fontFamily:"monospace",terminalFill:"#FFFFC0",terminalStroke:"#000000",terminalTextColor:"#000000",nonTerminalFill:"#FFFFFF",nonTerminalStroke:"#000000",nonTerminalTextColor:"#000000",lineColor:"#000000",strokeWidth:2,markerFill:"#000000",commentFill:"#E8E8E8",commentStroke:"#888888",commentTextColor:"#666666",specialFill:"#F0E0FF",specialStroke:"#8800CC",ruleNameColor:"#000066",showMarkers:!0,markerRadius:5},y=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$|^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch)\([\d\s%+,./-]+\)$|^[a-z]+$/i,$=/^[\w "',.-]+$/,_=new Set(["compactMode","padding","verticalSeparation","horizontalSeparation","arcRadius","fontSize","fontFamily","terminalFill","terminalStroke","terminalTextColor","nonTerminalFill","nonTerminalStroke","nonTerminalTextColor","lineColor","strokeWidth","markerFill","commentFill","commentStroke","commentTextColor","specialFill","specialStroke","ruleNameColor","showMarkers","markerRadius"]),R=(0,c.__name)(e=>!!e&&Object.keys(e).every(e=>"railroad"===e||_.has(e)),"isRailroadStyleOptions"),v=(0,c.__name)(e=>e?"railroad"in e&&e.railroad?e.railroad:R(e)?e:{}:{},"extractRailroadOverrides"),z=(0,c.__name)(e=>{if(!e||R(e))return{};return(0,a.default)(e,n)},"extractThemeOverrides"),N=(0,c.__name)((e,t)=>{if("string"!=typeof e)return t;const n=e.trim();return y.test(n)?n:t},"sanitizeColorValue"),O=(0,c.__name)((e,t)=>{if("string"!=typeof e)return t;const n=e.trim();return $.test(n)?n:t},"sanitizeFontFamilyValue"),M=(0,c.__name)((e,t)=>{const n="number"==typeof e?e:"string"==typeof e?Number.parseFloat(e):Number.NaN;return Number.isFinite(n)&&n>=0?n:t},"sanitizeNumberValue"),A=(0,c.__name)(e=>{const t="number"==typeof e?e:"string"==typeof e?Number.parseFloat(e):Number.NaN;return Number.isFinite(t)&&t>0?t:void 0},"parseThemeFontSize"),j=(0,c.__name)(e=>{const t=O(e.fontFamily,F.fontFamily),n=A(e.fontSize)??F.fontSize;return Object.assign({},F,{fontFamily:t,fontSize:n,terminalFill:N(e.secondBkg??e.secondaryColor,F.terminalFill),terminalStroke:N(e.secondaryBorderColor??e.lineColor,F.terminalStroke),terminalTextColor:N(e.secondaryTextColor??e.textColor,F.terminalTextColor),nonTerminalFill:N(e.mainBkg??e.background,F.nonTerminalFill),nonTerminalStroke:N(e.primaryBorderColor??e.lineColor,F.nonTerminalStroke),nonTerminalTextColor:N(e.primaryTextColor??e.textColor,F.nonTerminalTextColor),lineColor:N(e.lineColor,F.lineColor),markerFill:N(e.lineColor,F.markerFill),commentFill:N(e.labelBackground??e.tertiaryColor,F.commentFill),commentStroke:N(e.tertiaryBorderColor??e.lineColor,F.commentStroke),commentTextColor:N(e.tertiaryTextColor??e.textColor,F.commentTextColor),specialFill:N(e.tertiaryColor??e.secondaryColor,F.specialFill),specialStroke:N(e.tertiaryBorderColor??e.secondaryBorderColor,F.specialStroke),ruleNameColor:N(e.titleColor??e.textColor,F.ruleNameColor)})},"buildThemeDefaults"),B=(0,c.__name)(e=>{const t=(0,l.getConfig)(),n=Object.assign({},(0,l.getThemeVariables)(),t.themeVariables??{},z(e)),r=j(n),i=Object.assign({},t.railroad??{},v(e));return{compactMode:i.compactMode??r.compactMode,padding:M(i.padding,r.padding),verticalSeparation:M(i.verticalSeparation,r.verticalSeparation),horizontalSeparation:M(i.horizontalSeparation,r.horizontalSeparation),arcRadius:M(i.arcRadius,r.arcRadius),fontSize:M(i.fontSize,r.fontSize),fontFamily:O(i.fontFamily,r.fontFamily),terminalFill:N(i.terminalFill,r.terminalFill),terminalStroke:N(i.terminalStroke,r.terminalStroke),terminalTextColor:N(i.terminalTextColor,r.terminalTextColor),nonTerminalFill:N(i.nonTerminalFill,r.nonTerminalFill),nonTerminalStroke:N(i.nonTerminalStroke,r.nonTerminalStroke),nonTerminalTextColor:N(i.nonTerminalTextColor,r.nonTerminalTextColor),lineColor:N(i.lineColor,r.lineColor),strokeWidth:M(i.strokeWidth,r.strokeWidth),markerFill:N(i.markerFill,r.markerFill),commentFill:N(i.commentFill,r.commentFill),commentStroke:N(i.commentStroke,r.commentStroke),commentTextColor:N(i.commentTextColor,r.commentTextColor),specialFill:N(i.specialFill,r.specialFill),specialStroke:N(i.specialStroke,r.specialStroke),ruleNameColor:N(i.ruleNameColor,r.ruleNameColor),showMarkers:i.showMarkers??r.showMarkers,markerRadius:M(i.markerRadius,r.markerRadius)}},"buildRailroadStyleOptions"),E=(0,c.__name)(e=>{const{fontFamily:t,fontSize:n,terminalFill:r,terminalStroke:i,terminalTextColor:a,nonTerminalFill:o,nonTerminalStroke:l,nonTerminalTextColor:s,lineColor:c,strokeWidth:h,markerFill:p,commentFill:u,commentStroke:f,commentTextColor:T,specialFill:x,specialStroke:w,ruleNameColor:k}=B(e);return`\n .railroad-diagram {\n font-family: ${t};\n font-size: ${n}px;\n }\n\n .railroad-terminal rect {\n fill: ${r};\n stroke: ${i};\n stroke-width: ${h}px;\n }\n\n .railroad-terminal text {\n fill: ${a};\n font-family: ${t};\n font-size: ${n}px;\n text-anchor: middle;\n dominant-baseline: middle;\n }\n\n .railroad-nonterminal rect {\n fill: ${o};\n stroke: ${l};\n stroke-width: ${h}px;\n }\n\n .railroad-nonterminal text {\n fill: ${s};\n font-family: ${t};\n font-size: ${n}px;\n text-anchor: middle;\n dominant-baseline: middle;\n }\n\n .railroad-line {\n stroke: ${c};\n stroke-width: ${h}px;\n fill: none;\n }\n\n .railroad-start circle,\n .railroad-end circle {\n fill: ${p};\n }\n\n .railroad-comment ellipse {\n fill: ${u};\n stroke: ${f};\n stroke-width: ${h}px;\n }\n\n .railroad-comment text {\n fill: ${T};\n font-style: italic;\n font-family: ${t};\n font-size: ${n}px;\n text-anchor: middle;\n dominant-baseline: middle;\n }\n\n .railroad-special rect {\n fill: ${x};\n stroke: ${w};\n stroke-width: ${h}px;\n stroke-dasharray: 5,3;\n }\n\n .railroad-special text {\n fill: ${s};\n font-family: ${t};\n font-size: ${n}px;\n text-anchor: middle;\n dominant-baseline: middle;\n }\n\n .railroad-rule-name {\n font-weight: bold;\n fill: ${k};\n font-family: ${t};\n font-size: ${n}px;\n }\n\n .railroad-group {\n /* Grouping container, no specific styles */\n }\n`},"getStyles"),D=(e=class{constructor(){this.d=""}moveTo(e,t){return this.d+=`M ${e} ${t} `,this}lineTo(e,t){return this.d+=`L ${e} ${t} `,this}horizontalTo(e){return this.d+=`H ${e} `,this}verticalTo(e){return this.d+=`V ${e} `,this}arcTo(e,t,n,r,i,a,o){return this.d+=`A ${e} ${t} ${n} ${r?1:0} ${i?1:0} ${a} ${o} `,this}build(){return this.d.trim()}},(0,c.__name)(e,"PathBuilder"),e),W=(t=class{constructor(e,t=B()){this.textCache=new Map,this.svg=e,this.config=t}measureText(e){if(this.textCache.has(e))return this.textCache.get(e);const t=this.svg.append("text").attr("font-family",this.config.fontFamily).attr("font-size",this.config.fontSize).text(e),n=t.node().getBBox(),r={width:n.width,height:n.height};return t.remove(),this.textCache.set(e,r),r}renderTerminal(e,t){const n=this.measureText(t),r=n.width+2*this.config.padding,i=n.height+2*this.config.padding,a=e.append("g").attr("class","railroad-terminal");return a.append("rect").attr("x",0).attr("y",0).attr("width",r).attr("height",i).attr("rx",10).attr("ry",10),a.append("text").attr("x",r/2).attr("y",i/2).text(t),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderNonTerminal(e,t){const n=this.measureText(t),r=n.width+2*this.config.padding,i=n.height+2*this.config.padding,a=e.append("g").attr("class","railroad-nonterminal");return a.append("rect").attr("x",0).attr("y",0).attr("width",r).attr("height",i),a.append("text").attr("x",r/2).attr("y",i/2).text(t),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderSequence(e,t){const n=t.map(t=>this.renderExpression(e,t));let r=0,i=0,a=0;for(const e of n)r+=e.dimensions.width,i=Math.max(i,e.dimensions.up),a=Math.max(a,e.dimensions.down);r+=(n.length-1)*this.config.horizontalSeparation;const o=e.append("g").attr("class","railroad-sequence");let l=0;for(let e=0;e<n.length;e++){const t=n[e],r=i-t.dimensions.up;if(o.node().appendChild(t.element).setAttribute("transform",`translate(${l}, ${r})`),e<n.length-1){const e=l+t.dimensions.width,n=e+this.config.horizontalSeparation,r=i;o.append("path").attr("class","railroad-line").attr("d",(new D).moveTo(e,r).lineTo(n,r).build())}l+=t.dimensions.width+this.config.horizontalSeparation}return{element:o.node(),dimensions:{width:r,height:i+a,up:i,down:a}}}renderChoice(e,t){const n=t.map(t=>this.renderExpression(e,t));let r=0,i=0;for(const e of n)r=Math.max(r,e.dimensions.width),i+=e.dimensions.height;i+=(n.length-1)*this.config.verticalSeparation;const a=this.config.arcRadius,o=r+4*a,l=e.append("g").attr("class","railroad-choice");let s=0;const c=i/2;for(const e of n){const t=s,n=t+e.dimensions.up,i=2*a+(r-e.dimensions.width)/2;l.node().appendChild(e.element).setAttribute("transform",`translate(${i}, ${t})`);const h=new D,p=n>c;n===c?h.moveTo(0,c).lineTo(i,n):h.moveTo(0,c).arcTo(a,a,0,!1,p,a,c+(p?a:-a)).lineTo(a,n-(p?a:-a)).arcTo(a,a,0,!1,!p,2*a,n).lineTo(i,n),l.append("path").attr("class","railroad-line").attr("d",h.build());const u=new D,f=i+e.dimensions.width,T=o-2*a;n===c?u.moveTo(f,n).lineTo(o,c):u.moveTo(f,n).lineTo(T,n).arcTo(a,a,0,!1,!p,o-a,n+(p?-a:a)).lineTo(o-a,c+(p?a:-a)).arcTo(a,a,0,!1,p,o,c),l.append("path").attr("class","railroad-line").attr("d",u.build()),s+=e.dimensions.height+this.config.verticalSeparation}return{element:l.node(),dimensions:{width:o,height:i,up:c,down:i-c}}}renderOptional(e,t){const n=this.renderExpression(e,t),r=this.config.arcRadius,i=2*r,a=n.dimensions.width+4*r,o=n.dimensions.height+i,l=e.append("g").attr("class","railroad-optional"),s=2*r,c=i;l.node().appendChild(n.element).setAttribute("transform",`translate(${s}, ${c})`);const h=c+n.dimensions.up,p=(new D).moveTo(0,h).lineTo(2*r,h);l.append("path").attr("class","railroad-line").attr("d",p.build());const u=(new D).moveTo(s+n.dimensions.width,h).lineTo(a,h);l.append("path").attr("class","railroad-line").attr("d",u.build());const f=(new D).moveTo(0,h).arcTo(r,r,0,!1,!1,r,h-r).lineTo(r,r).arcTo(r,r,0,!1,!0,2*r,0).lineTo(a-2*r,0).arcTo(r,r,0,!1,!0,a-r,r).lineTo(a-r,h-r).arcTo(r,r,0,!1,!1,a,h);return l.append("path").attr("class","railroad-line").attr("d",f.build()),{element:l.node(),dimensions:{width:a,height:o,up:h,down:o-h}}}renderRepetition(e,t,n){const r=this.renderExpression(e,t),i=this.config.arcRadius,a=2*i,o=r.dimensions.width+4*i,l=0===n,s=r.dimensions.height+a+(l?a:0),c=e.append("g").attr("class","railroad-repetition"),h=2*i,p=l?a:0;c.node().appendChild(r.element).setAttribute("transform",`translate(${h}, ${p})`);const u=p+r.dimensions.up;c.append("path").attr("class","railroad-line").attr("d",(new D).moveTo(0,u).lineTo(2*i,u).build()),c.append("path").attr("class","railroad-line").attr("d",(new D).moveTo(h+r.dimensions.width,u).lineTo(o,u).build());const f=p+r.dimensions.height+i,T=(new D).moveTo(h+r.dimensions.width,u).arcTo(i,i,0,!1,!0,h+r.dimensions.width+i,u+i).lineTo(h+r.dimensions.width+i,f).arcTo(i,i,0,!1,!0,h+r.dimensions.width,f+i).lineTo(2*i,f+i).arcTo(i,i,0,!1,!0,i,f).lineTo(i,u+i).arcTo(i,i,0,!1,!0,2*i,u);if(c.append("path").attr("class","railroad-line").attr("d",T.build()),l){const e=(new D).moveTo(0,u).arcTo(i,i,0,!1,!1,i,u-i).lineTo(i,i).arcTo(i,i,0,!1,!0,2*i,0).lineTo(o-2*i,0).arcTo(i,i,0,!1,!0,o-i,i).lineTo(o-i,u-i).arcTo(i,i,0,!1,!1,o,u);c.append("path").attr("class","railroad-line").attr("d",e.build())}return{element:c.node(),dimensions:{width:o,height:s,up:u,down:s-u}}}renderSpecial(e,t){const n=this.measureText("? "+t+" ?"),r=n.width+2*this.config.padding,i=n.height+2*this.config.padding,a=e.append("g").attr("class","railroad-special");return a.append("rect").attr("x",0).attr("y",0).attr("width",r).attr("height",i),a.append("text").attr("x",r/2).attr("y",i/2).text("? "+t+" ?"),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderExpression(e,t){switch(t.type){case"terminal":return this.renderTerminal(e,t.value);case"nonterminal":return this.renderNonTerminal(e,t.name);case"sequence":return this.renderSequence(e,t.elements);case"choice":return this.renderChoice(e,t.alternatives);case"optional":return this.renderOptional(e,t.element);case"repetition":return this.renderRepetition(e,t.element,t.min);case"special":return this.renderSpecial(e,t.text);default:throw new Error(`Unknown node type: ${t.type}`)}}renderRule(e,t){const n=this.svg.append("g").attr("class","railroad-rule").attr("transform",`translate(0, ${t})`),r=e.name+" =",i=this.measureText(r).width+20,a=i+20,o=n.append("g"),l=this.renderExpression(o,e.definition),s=Math.max(20,l.dimensions.up),c=s-l.dimensions.up;o.attr("transform",`translate(${a}, ${c})`);n.append("g").attr("class","railroad-rule-name-group").append("text").attr("class","railroad-rule-name").attr("x",0).attr("y",s).text(r);n.append("g").attr("class","railroad-start").append("circle").attr("cx",i).attr("cy",s).attr("r",this.config.markerRadius);return n.append("g").attr("class","railroad-end").append("circle").attr("cx",a+l.dimensions.width+10).attr("cy",s).attr("r",this.config.markerRadius),n.append("path").attr("class","railroad-line").attr("d",(new D).moveTo(i+this.config.markerRadius,s).lineTo(a,s).build()),n.append("path").attr("class","railroad-line").attr("d",(new D).moveTo(a+l.dimensions.width,s).lineTo(a+l.dimensions.width+10-this.config.markerRadius,s).build()),{height:Math.max(40,c+l.dimensions.height+2*this.config.padding),width:a+l.dimensions.width+10+this.config.markerRadius}}renderDiagram(e){let t=this.config.padding,n=0;for(const r of e){const e=this.renderRule(r,t);t+=e.height+this.config.verticalSeparation,n=Math.max(n,e.width)}return{width:n+2*this.config.padding,height:t+this.config.padding}}},(0,c.__name)(t,"RailroadRenderer"),t),V=(0,c.__name)((e,t,n)=>{(0,l.configureSvgSize)(e,t.height,t.width,n),e.attr("viewBox",`0 0 ${t.width} ${t.height}`)},"configureRailroadSvgSize"),q={draw:(0,c.__name)((e,t,n)=>{s.log.debug("[Railroad] Rendering diagram\n"+e);try{const e=(0,o.selectSvgElement)(t);e.attr("class","railroad-diagram");const n=(0,l.getConfig)().railroad,r=n?.useMaxWidth??!0,i=S.getRules();if(s.log.debug(`[Railroad] Rendering ${i.length} rules`),0===i.length)return s.log.warn("[Railroad] No rules to render"),void V(e,{height:100,width:200},r);const a=new W(e,B()).renderDiagram(i);V(e,a,r),s.log.debug("[Railroad] Render complete")}catch(e){throw s.log.error("[Railroad] Render error:",e),e}},"draw")}},6907,[35,5019,5030,5031,5032]);
1859
1859
  __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.VisualizerToolbar=function(s){const n=(0,l.c)(87),{sessions:c,selectedSessionId:h,onSelectSession:F,followActive:C,onToggleFollow:H,timelineOpen:V,filesOpen:O,costOpen:R,statsOpen:N,soundMuted:L,hudHidden:X,onToggleTimeline:Z,onToggleFiles:q,onToggleCost:J,onToggleStats:K,onZoomToFit:Q,onRestart:Y,onToggleAudio:$,onToggleHud:ee,onCollapseToPip:te}=s,le=null===h,oe=X,se=(0,u.useIsCompactFormFactor)(),[ne,ie]=(0,o.useState)(null);let ae;n[0]===Symbol.for("react.memo_cache_sentinel")?(ae=t=>{const l=t.nativeEvent.layout.width;ie(t=>null!==t&&Math.abs(t-l)<1?t:l)},n[0]=ae):ae=n[0];const re=ae,ce=null!==te;let de;n[1]!==ne||n[2]!==se||n[3]!==ce?(de=M(ne,se,ce),n[1]=ne,n[2]=se,n[3]=ce,n[4]=de):de=n[4];const ue=de;let he;n[5]!==c?(he=c.map(W),n[5]=c,n[6]=he):he=n[6];const be=he;let ge;if(n[7]!==h||n[8]!==c){let t;n[10]!==h?(t=t=>t.id===h,n[10]=h,n[11]=t):t=n[11],ge=c.find(t),n[7]=h,n[8]=c,n[9]=ge}else ge=n[9];const me=ge;let pe;n[12]!==me?(pe=me?{label:me.label}:null,n[12]=me,n[13]=pe):pe=n[13];const fe=pe;let Ie;n[14]!==F?(Ie=t=>F(t),n[14]=F,n[15]=Ie):Ie=n[15];const Te=Ie;let ye;n[16]!==ue||n[17]!==Z||n[18]!==oe||n[19]!==V?(ye=ue.has("timeline")?null:(0,I.jsx)(p.ToolbarIconButton,{label:"Timeline",Icon:y,selected:!oe&&V,onPress:Z,disabled:oe,testID:"visualizer-toolbar-timeline"},"timeline"),n[16]=ue,n[17]=Z,n[18]=oe,n[19]=V,n[20]=ye):ye=n[20];const we=ye;let xe;n[21]!==O||n[22]!==ue||n[23]!==q||n[24]!==oe?(xe=ue.has("files")?null:(0,I.jsx)(p.ToolbarIconButton,{label:"Files",Icon:T,selected:!oe&&O,onPress:q,disabled:oe,testID:"visualizer-toolbar-files"},"files"),n[21]=O,n[22]=ue,n[23]=q,n[24]=oe,n[25]=xe):xe=n[25];const Se=xe;let ve;n[26]!==R||n[27]!==ue||n[28]!==J||n[29]!==oe?(ve=ue.has("cost")?null:(0,I.jsx)(p.ToolbarIconButton,{label:"Cost",Icon:w,selected:!oe&&R,onPress:J,disabled:oe,testID:"visualizer-toolbar-cost"},"cost"),n[26]=R,n[27]=ue,n[28]=J,n[29]=oe,n[30]=ve):ve=n[30];const je=ve,De=X?"Show HUD":"Hide HUD",Pe=X?j:v,ze=!X;let Ue;n[31]!==ee||n[32]!==De||n[33]!==Pe||n[34]!==ze?(Ue=(0,I.jsx)(p.ToolbarIconButton,{label:De,Icon:Pe,selected:ze,onPress:ee,testID:"visualizer-toolbar-hud"},"hud"),n[31]=ee,n[32]=De,n[33]=Pe,n[34]=ze,n[35]=Ue):Ue=n[35];const _e=Ue;let Be;n[36]!==te?(Be=null===te?null:(0,I.jsx)(p.ToolbarIconButton,{label:"Collapse to picture-in-picture",Icon:B,onPress:te,testID:"visualizer-toolbar-pip"},"pip"),n[36]=te,n[37]=Be):Be=n[37];const Fe=Be;let Ce;n[38]!==je||n[39]!==Se||n[40]!==_e||n[41]!==Fe||n[42]!==we?(Ce=[{id:"timeline",nodes:[we]},{id:"panels",nodes:[Se,je]},{id:"hud",nodes:[_e]},{id:"surface",nodes:[Fe]}].map(E).filter(k),n[38]=je,n[39]=Se,n[40]=_e,n[41]=Fe,n[42]=we,n[43]=Ce):Ce=n[43];const He=Ce,Ve=0===c.length?"No chats":"Select a chat",Me=0===c.length,Oe=c.length>8;let Ae,ke;n[44]!==Te||n[45]!==be||n[46]!==fe||n[47]!==h||n[48]!==Ve||n[49]!==Me||n[50]!==Oe?(Ae=(0,I.jsx)(t.View,{style:G.chats,children:(0,I.jsx)(b.SelectField,{label:"Chat",value:h,selectedDisplay:fe,options:be,onChange:Te,placeholder:Ve,emptyText:"No chats to visualize",disabled:Me,searchable:Oe,size:"sm",triggerStyle:G.chatsTrigger,field:!1,testID:"visualizer-toolbar-chats",triggerTestID:"visualizer-toolbar-chats-trigger"})}),n[44]=Te,n[45]=be,n[46]=fe,n[47]=h,n[48]=Ve,n[49]=Me,n[50]=Oe,n[51]=Ae):Ae=n[51];n[52]!==C||n[53]!==ue||n[54]!==H||n[55]!==c.length?(ke=ue.has("pin")?null:(0,I.jsx)(p.ToolbarIconButton,{label:C?"Pin this chat":"Unpin - follow the active chat",Icon:C?U:_,selected:!C,onPress:H,disabled:0===c.length,testID:"visualizer-toolbar-follow"}),n[52]=C,n[53]=ue,n[54]=H,n[55]=c.length,n[56]=ke):ke=n[56];const Ee=L?"Unmute":"Mute",Re=L?S:x,We=!L;let Ge,Ne,Le,Xe,Ze,qe,Je,Ke,Qe;n[57]!==$||n[58]!==Ee||n[59]!==Re||n[60]!==We?(Ge=(0,I.jsx)(p.ToolbarIconButton,{label:Ee,Icon:Re,selected:We,onPress:$,testID:"visualizer-toolbar-audio"}),n[57]=$,n[58]=Ee,n[59]=Re,n[60]=We,n[61]=Ge):Ge=n[61];n[62]===Symbol.for("react.memo_cache_sentinel")?(Ne=(0,I.jsx)(f.ToolbarSeparator,{}),n[62]=Ne):Ne=n[62];n[63]!==Q||n[64]!==le?(Le=(0,I.jsx)(p.ToolbarIconButton,{label:"Zoom to Fit",Icon:D,onPress:Q,disabled:le,testID:"visualizer-toolbar-zoom-to-fit"}),n[63]=Q,n[64]=le,n[65]=Le):Le=n[65];n[66]!==ue||n[67]!==K||n[68]!==oe||n[69]!==N?(Xe=ue.has("stats")?null:(0,I.jsx)(p.ToolbarIconButton,{label:"Toggle Stats",Icon:P,selected:!oe&&N,onPress:K,disabled:oe,testID:"visualizer-toolbar-stats"}),n[66]=ue,n[67]=K,n[68]=oe,n[69]=N,n[70]=Xe):Xe=n[70];n[71]===Symbol.for("react.memo_cache_sentinel")?(Ze=(0,I.jsx)(f.ToolbarSeparator,{}),n[71]=Ze):Ze=n[71];n[72]!==Y||n[73]!==le?(qe=(0,I.jsx)(p.ToolbarIconButton,{label:"Restart",Icon:z,onPress:Y,disabled:le,testID:"visualizer-toolbar-restart"}),n[72]=Y,n[73]=le,n[74]=qe):qe=n[74];n[75]!==Ae||n[76]!==ke||n[77]!==Ge||n[78]!==Le||n[79]!==Xe||n[80]!==qe?(Je=(0,I.jsxs)(t.View,{style:G.leftGroup,children:[Ae,ke,Ge,Ne,Le,Xe,Ze,qe]}),n[75]=Ae,n[76]=ke,n[77]=Ge,n[78]=Le,n[79]=Xe,n[80]=qe,n[81]=Je):Je=n[81];n[82]!==He?(Ke=(0,I.jsx)(t.View,{style:G.toggles,children:He.map(A)}),n[82]=He,n[83]=Ke):Ke=n[83];n[84]!==Je||n[85]!==Ke?(Qe=(0,I.jsxs)(t.View,{style:G.bar,onLayout:re,children:[Je,Ke]}),n[84]=Je,n[85]=Ke,n[86]=Qe):Qe=n[86];return Qe};var t=r(d[0]),l=r(d[1]),o=r(d[2]);r(d[3]);var s=r(d[4]),n=r(d[5]),c=r(d[6]),u=r(d[7]),h=r(d[8]),b=r(d[9]),p=r(d[10]),f=r(d[11]),I=r(d[12]);const T=(0,s.withUnistyles)(n.Files),y=(0,s.withUnistyles)(n.Timeline),w=(0,s.withUnistyles)(n.DollarSign),x=(0,s.withUnistyles)(n.Volume2),S=(0,s.withUnistyles)(n.VolumeX),v=(0,s.withUnistyles)(n.Eye),j=(0,s.withUnistyles)(n.EyeOff),D=(0,s.withUnistyles)(n.FitScreen),P=(0,s.withUnistyles)(n.BarChart),z=(0,s.withUnistyles)(n.Restart),U=(0,s.withUnistyles)(n.Pin),_=(0,s.withUnistyles)(n.PinFilled),B=(0,s.withUnistyles)(n.PictureInPicture),F=["timeline","files","cost","pin","stats"],C=45,H=29,V=4;function M(t,l,o){if(null===t)return O;const s=l?C:H,n=t-(112+(V+(o?1:0))*s+42),c=Math.max(0,Math.min(F.length,Math.floor(n/s)));return new Set(F.slice(0,F.length-c))}const O=new Set;function A(t,l){return(0,I.jsxs)(o.Fragment,{children:[l>0?(0,I.jsx)(f.ToolbarSeparator,{}):null,t.nodes]},t.id)}function k(t){return t.nodes.length>0}function E(t){return{id:t.id,nodes:t.nodes.filter(R)}}function R(t){return null!==t}function W(t){return{id:t.id,value:t.id,label:t.label}}const G=s.StyleSheet.create(t=>({bar:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:t.spacing[2],paddingHorizontal:t.spacing[2],paddingVertical:t.spacing[1],minHeight:c.PANE_TOOLBAR_HEIGHT,borderBottomWidth:t.borderWidth[1],borderBottomColor:t.colors.border,backgroundColor:t.colors.background,uni__dependencies:[0]},leftGroup:{flexDirection:"row",alignItems:"center",gap:5,flexShrink:1},chats:{flexShrink:1,maxWidth:h.TAB_MAX_WIDTH},chatsTrigger:{minHeight:{xs:40,md:26},paddingVertical:3},toggles:{flexDirection:"row",alignItems:"center",gap:5,flexShrink:0}}))},6908,[360,306,36,146,56,1120,3591,347,4749,4109,4586,4587,279]);
1860
- __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.sessionIdForRootAgent=function(t){return t},e.sessionIdForDraft=f,e.useVisualizerEventAdapter=function(o){const{serverId:l,workspaceId:c,active:p,agentIdFilter:v=null,draftSessions:h=q,postMessage:y}=o,I=(0,s.useHostRuntimeClient)(l),b=(0,t.useRef)(y);b.current=y;const w=(0,t.useRef)(new Map);(0,t.useEffect)(()=>{if(!p||!I)return;const t={nodes:new Map,sessionNames:new Map,pending:[],pendingSessionMessages:[],pendingBackfill:[],backfillDrain:null,epochMs:Date.now(),sessionEpochMs:new Map,hydrating:!0},o={disposed:!1};b.current({type:"reset"}),w.current.clear();const f=async()=>{for(;t.pendingBackfill.length>0&&!o.disposed;){const s=t.pendingBackfill.shift();s&&await D({state:t,client:I,agentId:s})}},h=()=>{if(t.backfillDrain)return t.backfillDrain;const s=f();return t.backfillDrain=s,s.finally(()=>{t.backfillDrain===s&&(t.backfillDrain=null)}),s},y=async()=>{await h(),o.disposed||B(t,b.current)};(async()=>{const n=(0,s.getHostRuntimeStore)().refreshAgentDirectory({serverId:l}).catch(()=>{});if(A(t,N(l,c,v)),await y(),await n,!o.disposed){for(A(t,N(l,c,v)),await y();!o.disposed&&(t.pendingBackfill.length>0||t.backfillDrain);)await y();t.hydrating=!1}})();const T=n.useSessionStore.subscribe((s,n)=>{o.disposed||s.sessions[l]?.agents!==n.sessions[l]?.agents&&(A(t,N(l,c,v)),t.pendingBackfill.length>0&&y())}),M=I.on("agent_stream",s=>{if(o.disposed||"agent_stream"!==s.type)return;const{agentId:n,event:a,timestamp:l,seq:c,epoch:p}=s.payload,f=t.nodes.get(n);if(!f)return;const v={event:a,time:u(t,Date.parse(l),f.sessionId),seq:c,epoch:p};null!==f.cursor?R(t,f,v):f.bufferedLive.push(v)}),S=setInterval(()=>{o.disposed||B(t,b.current)},a);return()=>{o.disposed=!0,clearInterval(S),T(),M()}},[p,I,l,c,v]),(0,t.useEffect)(()=>{if(!p||!I)return;const t=w.current,s=new Map(h.map(t=>[f(t.draftId),t.label]));for(const n of t.keys())s.has(n)||(b.current({type:"close-session",sessionId:n}),t.delete(n));for(const[n,o]of s){const s=t.get(n);void 0===s?(b.current({type:"session-started",session:{id:n,label:o,status:"active",startTime:0,lastActivityTime:0}}),t.set(n,o)):s!==o&&(b.current({type:"session-updated",sessionId:n,label:o}),t.set(n,o))}},[p,I,l,c,v,h])};var t=r(d[0]),s=r(d[1]),n=r(d[2]),o=r(d[3]);const a=200,l=8;function u(t,s,n){if(!Number.isFinite(s))return 0;const o=(null!=n?t.sessionEpochMs.get(n):void 0)??t.epochMs;return Math.max(0,(s-o)/1e3)}function c(t){return{name:t.name,sessionId:t.sessionId,workspaceRoot:t.workspaceRoot}}function p(t,s){let n=t;for(let t=0;t<l;t+=1){const t=s.get(n);if(!t?.parentAgentId||!s.has(t.parentAgentId))return n;n=t.parentAgentId}return n}function f(t){return`draft:${t}`}function v(t){const s=t.personalitySpinner;return s?.glowA&&s.glowB?{glowA:s.glowA,glowB:s.glowB}:null}function h(t){return t?`${t.glowA}|${t.glowB}`:null}function y(t,s,n,a,l){if(s.isRoot)return(0,o.buildRootAgentSpawnEvent)({ctx:c(s),model:n.model,provider:n.provider,personalityColors:a,time:l});const u=n.parentAgentId?t.nodes.get(n.parentAgentId):void 0;return(0,o.buildObservedSubagentSpawnEvent)({ctx:c(s),parentName:u?.name??n.parentAgentId??s.sessionId,task:n.title,personalityColors:a,time:l})}function I(t,s,n){const a=t.nodes.get(s);if(a)return a;const l=n.get(s);if(!l)return;const f=Boolean(l.parentAgentId&&n.has(l.parentAgentId));if(!f&&"observed"===l.attend&&l.parentAgentId)return;const y=!f,b=y?s:p(s,n),A=l.createdAt.getTime();y&&t.sessionEpochMs.set(b,A);const w=t.sessionNames.get(b)??new Set;t.sessionNames.set(b,w);const T=(0,o.resolveAgentNodeName)({agentId:s,title:l.title,usedNames:w});w.add(T);const M=v(l),S={sessionId:b,name:T,isRoot:y,workspaceRoot:l.cwd,lastModel:l.model,lastTitle:l.title,lastPersonaColorKey:h(M),lastStatus:l.status,terminalEmitted:!1,sessionRemoved:!1,cursor:null,bufferedLive:[],startedToolCallIds:new Set,subAgentDispatchLabels:new Map,lastContextTokens:null,lastCumulativeTokens:null,lastCostUsd:null,streamingMessage:null};if(t.nodes.set(s,S),t.pendingBackfill.push(s),y)t.pendingSessionMessages.push({type:"session-started",session:{id:b,label:(0,o.truncateSessionLabel)(l.title??T),status:"active",startTime:A,lastActivityTime:l.lastActivityAt.getTime()}}),t.pending.push((0,o.buildRootAgentSpawnEvent)({ctx:c(S),model:l.model,provider:l.provider,personalityColors:M,time:u(t,A,S.sessionId)}));else{const s=l.parentAgentId,a=I(t,s,n);t.pending.push((0,o.buildObservedSubagentSpawnEvent)({ctx:c(S),parentName:a?.name??s,task:l.title,personalityColors:M,time:u(t,A,S.sessionId)}))}return S}function b(t,s,n){n.isRoot?(n.sessionRemoved||t.pendingSessionMessages.push({type:"close-session",sessionId:n.sessionId}),t.sessionEpochMs.delete(n.sessionId)):n.terminalEmitted||t.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(n),time:u(t,Date.now(),n.sessionId)})),t.nodes.delete(s),t.sessionNames.get(n.sessionId)?.delete(n.name)}function A(t,s){if(0===s.length)return;const n=new Map(s.map(t=>[t.id,t])),a=[...s].sort((t,s)=>t.createdAt.getTime()-s.createdAt.getTime());for(const s of a){let a=t.nodes.get(s.id);if(a){const n=u(t,s.lastActivityAt.getTime(),a.sessionId);s.model&&s.model!==a.lastModel&&(a.lastModel=s.model,t.pending.push((0,o.buildModelDetectedEvent)({ctx:c(a),model:s.model,time:n}))),a.isRoot&&s.title&&s.title!==a.lastTitle&&(a.lastTitle=s.title,t.pendingSessionMessages.push({type:"session-updated",sessionId:a.sessionId,label:(0,o.truncateSessionLabel)(s.title)}),t.pending.push((0,o.buildAgentRenameEvent)({ctx:c(a),label:s.title.trim(),time:n})));const l=v(s),p=h(l);p!==a.lastPersonaColorKey&&(a.lastPersonaColorKey=p,a.terminalEmitted||a.sessionRemoved||t.pending.push(y(t,a,s,l,n)))}else if(a=I(t,s.id,n),!a)continue;w(t,a,s),T(t,a,s)}if(!t.hydrating){const s=[];for(const[o,a]of t.nodes)n.has(o)||s.push([o,a]);for(const[n,o]of s)b(t,n,o)}}function w(t,s,n){const a=n.lastUsage?.contextWindowUsedTokens??null,l=n.cumulativeTokens??null,p=n.cumulativeUsage?.costUsd??null,f=null!=a&&a!==s.lastContextTokens,v=null!=l&&l!==s.lastCumulativeTokens,h=null!=p&&p!==s.lastCostUsd;if(!f&&!v&&!h)return;s.lastContextTokens=a??s.lastContextTokens,s.lastCumulativeTokens=l??s.lastCumulativeTokens,s.lastCostUsd=p??s.lastCostUsd;const y=(0,o.buildContextUpdateEvent)(Object.assign({ctx:c(s)},n.lastUsage?{usage:n.lastUsage}:{},null!=l?{cumulativeTokens:l}:{},null!=p?{costUsd:p}:{},{time:u(t,n.lastActivityAt.getTime(),s.sessionId)}));y&&t.pending.push(y)}function T(t,s,n){s.lastStatus=n.status;const a=Boolean(n.archivedAt);if(s.isRoot){if(a&&!s.sessionRemoved)return s.sessionRemoved=!0,s.terminalEmitted=!0,void t.pendingSessionMessages.push({type:"close-session",sessionId:s.sessionId});!a&&s.sessionRemoved&&(s.sessionRemoved=!1,s.terminalEmitted=!1,t.pendingSessionMessages.push({type:"session-started",session:{id:s.sessionId,label:(0,o.truncateSessionLabel)(n.title??s.name),status:"active",startTime:n.createdAt.getTime(),lastActivityTime:n.lastActivityAt.getTime()}}),t.pending.push(y(t,s,n,v(n),u(t,n.lastActivityAt.getTime(),s.sessionId))))}const l=(0,o.isVisualizerAgentTerminal)({status:n.status,attend:n.attend,archived:Boolean(n.archivedAt),requiresAttention:Boolean(n.requiresAttention)}),p=u(t,n.lastActivityAt.getTime(),s.sessionId);if(l&&!s.terminalEmitted)return s.terminalEmitted=!0,t.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(s),time:p})),void(s.isRoot&&t.pendingSessionMessages.push({type:"session-ended",sessionId:s.sessionId}));!l&&s.terminalEmitted&&(s.terminalEmitted=!1,t.pending.push(y(t,s,n,v(n),p)))}function M(t){return"user_message"===t.type||"assistant_message"===t.type||"reasoning"===t.type}function S(t){return"user_message"===t.type?"user":"assistant_message"===t.type?"assistant":"thinking"}function k(t,s){return"messageId"in t&&t.messageId?t.messageId:s}function E(t){const s=t.streamingMessage;return s?(t.streamingMessage=null,0===s.text.length?[]:[{time:s.time,sessionId:t.sessionId,type:"message",payload:{agent:t.name,content:s.text,role:s.role}}]):[]}function C(t,s,n){const o=S(s),a=k(s,o),l=[],u=t.streamingMessage;u&&u.key!==a&&l.push(...E(t));const c=t.streamingMessage;return c&&c.key===a?(c.text+=s.text,c.time=n):t.streamingMessage={key:a,role:o,text:s.text,time:n},l}function x(t,s,n){if(M(s))return C(t,s,n);const a=E(t);let l=!1;if("tool_call"===s.type){const u=t.startedToolCallIds.has(s.callId),p="sub_agent"===s.detail.type;if("running"===s.status&&u){if(p&&"sub_agent"===s.detail.type){const l=(0,o.resolveSubAgentChildLabel)(s.detail);if(t.subAgentDispatchLabels.get(s.callId)!==l)return t.subAgentDispatchLabels.set(s.callId,l),[...a,(0,o.buildSubagentDispatchEvent)({ctx:c(t),detail:s.detail,time:n})]}return a}l="running"!==s.status&&!u,t.startedToolCallIds.add(s.callId),p&&"sub_agent"===s.detail.type&&("running"===s.status||l)&&t.subAgentDispatchLabels.set(s.callId,(0,o.resolveSubAgentChildLabel)(s.detail))}return[...a,...(0,o.timelineItemToSimulationEvents)({ctx:c(t),item:s,time:n,synthesizeToolCallStart:l})]}function R(t,s,n){if("timeline"!==n.event.type)t.pending.push(...E(s)),t.pending.push(...(0,o.streamEventToSimulationEvents)({ctx:c(s),event:n.event,time:n.time}));else{if(null!=n.seq&&null!=n.epoch){if(s.cursor&&n.epoch===s.cursor.epoch&&n.seq<=s.cursor.seq)return;s.cursor={epoch:n.epoch,seq:n.seq}}t.pending.push(...x(s,n.event.item,n.time))}}async function D(t){const{state:s,client:n,agentId:a}=t,l=s.nodes.get(a);if(!l)return;let p=0;try{const t=await n.fetchAgentTimeline(a,{direction:"tail",limit:0,projection:"projected"});for(const n of t.entries){const t=u(s,Date.parse(n.timestamp),l.sessionId);p=Math.max(p,t),s.pending.push(...x(l,n.item,t))}l.cursor={epoch:t.epoch,seq:t.endCursor?.seq??t.window.maxSeq}}catch{l.cursor={epoch:"",seq:0}}const f=l.bufferedLive;l.bufferedLive=[];for(const t of f)p=Math.max(p,t.time),R(s,l,t);s.pending.push(...E(l)),l.terminalEmitted&&!l.sessionRemoved?s.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(l),time:p})):l.terminalEmitted||"idle"!==l.lastStatus||s.pending.push((0,o.buildAgentIdleEvent)({ctx:c(l),time:p,resting:!0}))}function _(t){let s=0;for(const n of t)"session-started"===n.type&&s++;if(s<2)return t;const n=new Map;for(const s of t){let t="";"session-started"===s.type?t=s.session.id:"session-updated"!==s.type&&"session-ended"!==s.type&&"close-session"!==s.type||(t=s.sessionId);let o=n.get(t);o||(o={activity:Number.NEGATIVE_INFINITY,messages:[]},n.set(t,o)),o.messages.push(s),"session-started"===s.type&&(o.activity=s.session.lastActivityTime)}return[...n.values()].sort((t,s)=>t.activity-s.activity).flatMap(t=>t.messages)}function B(t,s){for(const n of _(t.pendingSessionMessages))s(n);if(t.pendingSessionMessages=[],t.pending.length>0){const n=t.pending;t.pending=[],s(Object.assign({type:"agent-event-batch",events:n},t.hydrating?{hydrate:!0}:{}))}}function N(t,s,o){const a=n.useSessionStore.getState().sessions[t]?.agents;if(!a)return[];const l=[];for(const t of a.values())t.workspaceId===s&&l.push(t);if(!o)return l;const u=new Map(l.map(t=>[t.id,t]));return l.filter(t=>o.has(t.id)||o.has(p(t.id,u)))}const q=[]},6909,[36,3448,3351,6910]);
1860
+ __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.sessionIdForRootAgent=function(t){return t},e.sessionIdForDraft=f,e.useVisualizerEventAdapter=function(o){const{serverId:l,workspaceId:c,active:p,agentIdFilter:v=null,draftSessions:h=q,postMessage:y}=o,I=(0,s.useHostRuntimeClient)(l),b=(0,t.useRef)(y);b.current=y;const w=(0,t.useRef)(new Map);(0,t.useEffect)(()=>{if(!p||!I)return;const t={nodes:new Map,sessionNames:new Map,pending:[],pendingSessionMessages:[],pendingBackfill:[],backfillDrain:null,epochMs:Date.now(),sessionEpochMs:new Map,hydrating:!0},o={disposed:!1};b.current({type:"reset"}),w.current.clear();const f=async()=>{for(;t.pendingBackfill.length>0&&!o.disposed;){const s=t.pendingBackfill.shift();s&&await D({state:t,client:I,agentId:s})}},h=()=>{if(t.backfillDrain)return t.backfillDrain;const s=f();return t.backfillDrain=s,s.finally(()=>{t.backfillDrain===s&&(t.backfillDrain=null)}),s},y=async()=>{await h(),o.disposed||B(t,b.current)};(async()=>{const n=(0,s.getHostRuntimeStore)().refreshAgentDirectory({serverId:l}).catch(()=>{});if(A(t,N(l,c,v)),await y(),await n,!o.disposed){for(A(t,N(l,c,v)),await y();!o.disposed&&(t.pendingBackfill.length>0||t.backfillDrain);)await y();t.hydrating=!1}})();const T=n.useSessionStore.subscribe((s,n)=>{o.disposed||s.sessions[l]?.agents!==n.sessions[l]?.agents&&(A(t,N(l,c,v)),t.pendingBackfill.length>0&&y())}),M=I.on("agent_stream",s=>{if(o.disposed||"agent_stream"!==s.type)return;const{agentId:n,event:a,timestamp:l,seq:c,epoch:p}=s.payload,f=t.nodes.get(n);if(!f)return;const v={event:a,time:u(t,Date.parse(l),f.sessionId),seq:c,epoch:p};null!==f.cursor?R(t,f,v):f.bufferedLive.push(v)}),S=setInterval(()=>{o.disposed||B(t,b.current)},a);return()=>{o.disposed=!0,clearInterval(S),T(),M()}},[p,I,l,c,v]),(0,t.useEffect)(()=>{if(!p||!I)return;const t=w.current,s=new Map(h.map(t=>[f(t.draftId),t.label]));for(const n of t.keys())s.has(n)||(b.current({type:"close-session",sessionId:n}),t.delete(n));for(const[n,o]of s){const s=t.get(n);void 0===s?(b.current({type:"session-started",session:{id:n,label:o,status:"active",startTime:0,lastActivityTime:0}}),t.set(n,o)):s!==o&&(b.current({type:"session-updated",sessionId:n,label:o}),t.set(n,o))}},[p,I,l,c,v,h])};var t=r(d[0]),s=r(d[1]),n=r(d[2]),o=r(d[3]);const a=200,l=8;function u(t,s,n){if(!Number.isFinite(s))return 0;const o=(null!=n?t.sessionEpochMs.get(n):void 0)??t.epochMs;return Math.max(0,(s-o)/1e3)}function c(t){return{name:t.name,sessionId:t.sessionId,workspaceRoot:t.workspaceRoot}}function p(t,s){let n=t;for(let t=0;t<l;t+=1){const t=s.get(n);if(!t?.parentAgentId||!s.has(t.parentAgentId))return n;n=t.parentAgentId}return n}function f(t){return`draft:${t}`}function v(t){const s=t.personalitySpinner;return s?.glowA&&s.glowB?{glowA:s.glowA,glowB:s.glowB}:null}function h(t){return t?`${t.glowA}|${t.glowB}`:null}function y(t,s,n,a,l){if(s.isRoot)return(0,o.buildRootAgentSpawnEvent)({ctx:c(s),model:n.model,provider:n.provider,personalityColors:a,time:l});const u=n.parentAgentId?t.nodes.get(n.parentAgentId):void 0;return(0,o.buildObservedSubagentSpawnEvent)({ctx:c(s),parentName:u?.name??n.parentAgentId??s.sessionId,task:n.title,personalityColors:a,time:l})}function I(t,s,n){const a=t.nodes.get(s);if(a)return a;const l=n.get(s);if(!l)return;const f=Boolean(l.parentAgentId&&n.has(l.parentAgentId));if(!f&&"observed"===l.attend&&l.parentAgentId)return;const y=!f,b=y?s:p(s,n),A=l.createdAt.getTime();y&&t.sessionEpochMs.set(b,A);const w=t.sessionNames.get(b)??new Set;t.sessionNames.set(b,w);const T=(0,o.resolveAgentNodeName)({agentId:s,title:l.title,usedNames:w});w.add(T);const M=v(l),S={sessionId:b,name:T,isRoot:y,workspaceRoot:l.cwd,lastModel:l.model,lastTitle:l.title,lastPersonaColorKey:h(M),lastStatus:l.status,terminalEmitted:!1,sessionRemoved:!1,cursor:null,bufferedLive:[],startedToolCallIds:new Set,subAgentDispatchLabels:new Map,lastContextTokens:null,lastCumulativeTokens:null,lastCostUsd:null,streamingMessage:null};if(t.nodes.set(s,S),t.pendingBackfill.push(s),y)t.pendingSessionMessages.push({type:"session-started",session:{id:b,label:(0,o.truncateSessionLabel)(l.title??T),status:"active",startTime:A,lastActivityTime:l.lastActivityAt.getTime()}}),t.pending.push((0,o.buildRootAgentSpawnEvent)({ctx:c(S),model:l.model,provider:l.provider,personalityColors:M,time:u(t,A,S.sessionId)}));else{const s=l.parentAgentId,a=I(t,s,n);t.pending.push((0,o.buildObservedSubagentSpawnEvent)({ctx:c(S),parentName:a?.name??s,task:l.title,personalityColors:M,time:u(t,A,S.sessionId)}))}return S}function b(t,s,n){n.isRoot?(n.sessionRemoved||t.pendingSessionMessages.push({type:"close-session",sessionId:n.sessionId}),t.sessionEpochMs.delete(n.sessionId)):n.terminalEmitted||t.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(n),time:u(t,Date.now(),n.sessionId)})),t.nodes.delete(s),t.sessionNames.get(n.sessionId)?.delete(n.name)}function A(t,s){if(0===s.length)return;const n=new Map(s.map(t=>[t.id,t])),a=[...s].sort((t,s)=>t.createdAt.getTime()-s.createdAt.getTime());for(const s of a){let a=t.nodes.get(s.id);if(a){const n=u(t,s.lastActivityAt.getTime(),a.sessionId);s.model&&s.model!==a.lastModel&&(a.lastModel=s.model,t.pending.push((0,o.buildModelDetectedEvent)({ctx:c(a),model:s.model,time:n}))),a.isRoot&&s.title&&s.title!==a.lastTitle&&(a.lastTitle=s.title,t.pendingSessionMessages.push({type:"session-updated",sessionId:a.sessionId,label:(0,o.truncateSessionLabel)(s.title)}),t.pending.push((0,o.buildAgentRenameEvent)({ctx:c(a),label:s.title.trim(),time:n})));const l=v(s),p=h(l);p!==a.lastPersonaColorKey&&(a.lastPersonaColorKey=p,a.terminalEmitted||a.sessionRemoved||t.pending.push(y(t,a,s,l,n)))}else if(a=I(t,s.id,n),!a)continue;w(t,a,s),T(t,a,s)}if(!t.hydrating){const s=[];for(const[o,a]of t.nodes)n.has(o)||s.push([o,a]);for(const[n,o]of s)b(t,n,o)}}function w(t,s,n){const a=n.lastUsage?.contextWindowUsedTokens??null,l=n.cumulativeTokens??null,p=n.cumulativeUsage?.costUsd??null,f=null!=a&&a!==s.lastContextTokens,v=null!=l&&l!==s.lastCumulativeTokens,h=null!=p&&p!==s.lastCostUsd;if(!f&&!v&&!h)return;s.lastContextTokens=a??s.lastContextTokens,s.lastCumulativeTokens=l??s.lastCumulativeTokens,s.lastCostUsd=p??s.lastCostUsd;const y=(0,o.buildContextUpdateEvent)(Object.assign({ctx:c(s)},n.lastUsage?{usage:n.lastUsage}:{},null!=l?{cumulativeTokens:l}:{},null!=p?{costUsd:p}:{},{time:u(t,n.lastActivityAt.getTime(),s.sessionId)}));y&&t.pending.push(y)}function T(t,s,n){s.lastStatus=n.status;const a=Boolean(n.archivedAt);if(s.isRoot){if(a&&!s.sessionRemoved)return s.sessionRemoved=!0,s.terminalEmitted=!0,void t.pendingSessionMessages.push({type:"close-session",sessionId:s.sessionId});!a&&s.sessionRemoved&&(s.sessionRemoved=!1,s.terminalEmitted=!1,t.pendingSessionMessages.push({type:"session-started",session:{id:s.sessionId,label:(0,o.truncateSessionLabel)(n.title??s.name),status:"active",startTime:n.createdAt.getTime(),lastActivityTime:n.lastActivityAt.getTime()}}),t.pending.push(y(t,s,n,v(n),u(t,n.lastActivityAt.getTime(),s.sessionId))))}const l=(0,o.isVisualizerAgentTerminal)({status:n.status,attend:n.attend,archived:Boolean(n.archivedAt),requiresAttention:Boolean(n.requiresAttention)}),p=u(t,n.lastActivityAt.getTime(),s.sessionId);if(l&&!s.terminalEmitted)return s.terminalEmitted=!0,void t.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(s),time:p}));!l&&s.terminalEmitted&&(s.terminalEmitted=!1,t.pending.push(y(t,s,n,v(n),p)))}function M(t){return"user_message"===t.type||"assistant_message"===t.type||"reasoning"===t.type}function S(t){return"user_message"===t.type?"user":"assistant_message"===t.type?"assistant":"thinking"}function k(t,s){return"messageId"in t&&t.messageId?t.messageId:s}function E(t){const s=t.streamingMessage;return s?(t.streamingMessage=null,0===s.text.length?[]:[{time:s.time,sessionId:t.sessionId,type:"message",payload:{agent:t.name,content:s.text,role:s.role}}]):[]}function C(t,s,n){const o=S(s),a=k(s,o),l=[],u=t.streamingMessage;u&&u.key!==a&&l.push(...E(t));const c=t.streamingMessage;return c&&c.key===a?(c.text+=s.text,c.time=n):t.streamingMessage={key:a,role:o,text:s.text,time:n},l}function x(t,s,n){if(M(s))return C(t,s,n);const a=E(t);let l=!1;if("tool_call"===s.type){const u=t.startedToolCallIds.has(s.callId),p="sub_agent"===s.detail.type;if("running"===s.status&&u){if(p&&"sub_agent"===s.detail.type){const l=(0,o.resolveSubAgentChildLabel)(s.detail);if(t.subAgentDispatchLabels.get(s.callId)!==l)return t.subAgentDispatchLabels.set(s.callId,l),[...a,(0,o.buildSubagentDispatchEvent)({ctx:c(t),detail:s.detail,time:n})]}return a}l="running"!==s.status&&!u,t.startedToolCallIds.add(s.callId),p&&"sub_agent"===s.detail.type&&("running"===s.status||l)&&t.subAgentDispatchLabels.set(s.callId,(0,o.resolveSubAgentChildLabel)(s.detail))}return[...a,...(0,o.timelineItemToSimulationEvents)({ctx:c(t),item:s,time:n,synthesizeToolCallStart:l})]}function R(t,s,n){if("timeline"!==n.event.type)t.pending.push(...E(s)),t.pending.push(...(0,o.streamEventToSimulationEvents)({ctx:c(s),event:n.event,time:n.time}));else{if(null!=n.seq&&null!=n.epoch){if(s.cursor&&n.epoch===s.cursor.epoch&&n.seq<=s.cursor.seq)return;s.cursor={epoch:n.epoch,seq:n.seq}}t.pending.push(...x(s,n.event.item,n.time))}}async function D(t){const{state:s,client:n,agentId:a}=t,l=s.nodes.get(a);if(!l)return;let p=0;try{const t=await n.fetchAgentTimeline(a,{direction:"tail",limit:0,projection:"projected"});for(const n of t.entries){const t=u(s,Date.parse(n.timestamp),l.sessionId);p=Math.max(p,t),s.pending.push(...x(l,n.item,t))}l.cursor={epoch:t.epoch,seq:t.endCursor?.seq??t.window.maxSeq}}catch{l.cursor={epoch:"",seq:0}}const f=l.bufferedLive;l.bufferedLive=[];for(const t of f)p=Math.max(p,t.time),R(s,l,t);s.pending.push(...E(l)),l.terminalEmitted&&!l.sessionRemoved?s.pending.push((0,o.buildAgentCompleteEvent)({ctx:c(l),time:p})):l.terminalEmitted||"idle"!==l.lastStatus||s.pending.push((0,o.buildAgentIdleEvent)({ctx:c(l),time:p,resting:!0}))}function _(t){let s=0;for(const n of t)"session-started"===n.type&&s++;if(s<2)return t;const n=new Map;for(const s of t){let t="";"session-started"===s.type?t=s.session.id:"session-updated"!==s.type&&"session-ended"!==s.type&&"close-session"!==s.type||(t=s.sessionId);let o=n.get(t);o||(o={activity:Number.NEGATIVE_INFINITY,messages:[]},n.set(t,o)),o.messages.push(s),"session-started"===s.type&&(o.activity=s.session.lastActivityTime)}return[...n.values()].sort((t,s)=>t.activity-s.activity).flatMap(t=>t.messages)}function B(t,s){for(const n of _(t.pendingSessionMessages))s(n);if(t.pendingSessionMessages=[],t.pending.length>0){const n=t.pending;t.pending=[],s(Object.assign({type:"agent-event-batch",events:n},t.hydrating?{hydrate:!0}:{}))}}function N(t,s,o){const a=n.useSessionStore.getState().sessions[t]?.agents;if(!a)return[];const l=[];for(const t of a.values())t.workspaceId===s&&l.push(t);if(!o)return l;const u=new Map(l.map(t=>[t.id,t]));return l.filter(t=>o.has(t.id)||o.has(p(t.id,u)))}const q=[]},6909,[36,3448,3351,6910]);
1861
1861
  __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.resolveVisualizerRuntime=s,e.truncateSessionLabel=function(t){const n=t.trim();return n.length>l?`${n.slice(0,l).trimEnd()}\u2026`:n},e.resolveAgentNodeName=function(t){const n=t.title?.trim(),s=n&&n.length>0?n:`Agent ${t.agentId.slice(0,6)}`;if(!t.usedNames.has(s))return s;return`${s} (${t.agentId.slice(0,6)})`},e.buildRootAgentSpawnEvent=function(t){const n=s(t.provider);return{time:t.time,sessionId:t.ctx.sessionId,type:"agent_spawn",payload:Object.assign({name:t.ctx.name,isMain:!0},t.model?{model:t.model}:{},n?{runtime:n}:{},p(t.personalityColors))}},e.buildObservedSubagentSpawnEvent=function(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"agent_spawn",payload:Object.assign({name:t.ctx.name,parent:t.parentName},t.task?{task:t.task}:{},p(t.personalityColors))}},e.buildAgentRenameEvent=function(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"agent_rename",payload:{agent:t.ctx.name,label:t.label}}},e.buildModelDetectedEvent=function(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"model_detected",payload:{agent:t.ctx.name,model:t.model}}},e.isVisualizerAgentTerminal=function(t){if("closed"===t.status||t.archived)return!0;if("observed"===t.attend&&!t.requiresAttention)return"idle"===t.status||"error"===t.status;return!1},e.buildAgentCompleteEvent=function(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"agent_complete",payload:{name:t.ctx.name}}},e.buildAgentIdleEvent=f,e.buildPermissionRequestedEvent=y,e.buildContextUpdateEvent=x,e.toolCallDetailFilePath=k,e.summarizeToolCallArgs=v,e.summarizeToolCallResult=w,e.deriveToolCallDiscovery=N,e.estimateToolCallTokenCost=W,e.resolveSubAgentChildLabel=z,e.buildSubagentDispatchEvent=function(t){const n=q(t.detail);return{time:t.time,sessionId:t.ctx.sessionId,type:"subagent_dispatch",payload:{parent:t.ctx.name,child:n,task:n}}},e.timelineItemToSimulationEvents=U,e.streamEventToSimulationEvents=function(t){const{ctx:n,event:s,time:o}=t;switch(s.type){case"timeline":return U({ctx:n,item:s.item,time:o});case"turn_completed":{const t=[],r=s.usage?x({ctx:n,usage:s.usage,time:o}):null;return r&&t.push(r),t.push(f({ctx:n,time:o,resting:!0})),t}case"turn_failed":case"turn_canceled":return[f({ctx:n,time:o,resting:!0})];case"permission_requested":return[y({ctx:n,time:o})];case"permission_resolved":return[f({ctx:n,time:o})];default:return[]}};var t=_r(d[0]),n=_r(d[1]);function s(t){return"claude"===t?"claude":t.startsWith("codex")?"codex":"copilot"===t||"opencode"===t||"pi"===t?t:"omp"===t?"openai-compat":void 0}const o=200;function r(t,n=o){return t.length>n?`${t.slice(0,n)}\u2026`:t}const l=24;function u(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function c(t,n){if(!n||!t)return t;const s=n.trim().replace(/[\\/]+$/,"");if(!s)return t;const o=/^[A-Za-z]:/.test(s),r=s.split(/[\\/]+/).map(u).join("[\\\\/]"),l=new RegExp(`${r}(?:([\\\\/])|(?=[^\\w.-]|$))`,o?"gi":"g");return t.replace(l,(t,n)=>n?"":".")}function p(t){return t?.glowA&&t.glowB?{colorA:t.glowA,colorB:t.glowB}:{}}function f(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"agent_idle",payload:Object.assign({name:t.ctx.name},t.resting?{resting:!0}:{})}}function y(t){return{time:t.time,sessionId:t.ctx.sessionId,type:"permission_requested",payload:{agent:t.ctx.name}}}const h=[{key:"systemPrompt",label:"System prompt"},{key:"userMessages",label:"Messages"},{key:"toolResults",label:"Tool results"},{key:"reasoning",label:"Reasoning"},{key:"subagentResults",label:"Subagent results"}];function b(t,n){const s=t.filter(t=>t.tokens>0);if(0===s.length)return null;const o=s.reduce((t,n)=>t+n.tokens,0);if(null==n||n<=0)return{segments:s};const r=n/o;return{segments:s.map(t=>({label:t.label,tokens:Math.round(t.tokens*r)}))}}function x(t){const n=t.usage?.contextWindowUsedTokens;if(null==n&&null==t.cumulativeTokens&&null==t.costUsd)return null;const s=(o=t.usage,r=n??void 0,o?.contextCategories&&o.contextCategories.length>0?b(o.contextCategories.filter(t=>!t.isDeferred).map(t=>({label:t.name,tokens:t.tokens})),r):o?.contextComposition?b((l=o.contextComposition,h.map(({key:t,label:n})=>({label:n,tokens:l[t]??0}))),r):null);var o,r,l;return{time:t.time,sessionId:t.ctx.sessionId,type:"context_update",payload:Object.assign({agent:t.ctx.name},null!=n?{tokens:n}:{},null!=t.usage?.contextWindowMaxTokens?{tokensMax:t.usage.contextWindowMaxTokens}:{},null!=t.cumulativeTokens?{cumulativeTokens:t.cumulativeTokens}:{},null!=t.costUsd?{costUsd:t.costUsd}:{},s?{breakdown:s}:{})}}function k(t){switch(t.type){case"read":case"edit":case"write":return t.filePath;default:return}}function v(t){switch(t.type){case"shell":return t.command;case"read":case"edit":case"write":return t.filePath;case"search":return t.query;case"fetch":return t.url;case"worktree_setup":return t.branchName;case"sub_agent":return t.description??t.subAgentType??"";case"plain_text":return t.label??t.text??"";case"plan":return r(t.text);default:return""}}function I(t){return t.output?r(t.output):null!=t.exitCode?`exit ${t.exitCode}`:""}function _(t){return null!=t.numMatches?`${t.numMatches} matches`:null!=t.numFiles?`${t.numFiles} files`:t.content?r(t.content):""}function w(t){switch(t.type){case"shell":return I(t);case"read":case"write":return t.content?r(t.content):"";case"edit":return t.unifiedDiff?r(t.unifiedDiff):"";case"search":return _(t);case"fetch":return t.result?r(t.result):t.codeText??"";case"worktree_setup":case"sub_agent":return r(t.log);case"plain_text":return t.text??t.label??"";case"plan":return r(t.text);default:return""}}const T=40,C=44;function $(t,n=C){const s=t.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n).trimEnd()}\u2026`:s}function E(t,n){return t.split("\n").map(t=>t.trim()).filter(t=>t.length>0).slice(0,n).map(t=>$(t))}function A(t){let n=0,s=0;for(const o of t.split("\n"))o.startsWith("+++")||o.startsWith("---")||(o.startsWith("+")?n++:o.startsWith("-")&&s++);return 0===n&&0===s?"edited":`+${n} \u2212${s} lines`}const R=/(\d+\s+(?:passed|failed|passing|failing))|(tests?:)|(\bpass(?:ed)?\b|\bfail(?:ed)?\b)|coverage|(\d+\s+of\s+\d+)/i;function S(t){const n=t.split("\n").map(t=>t.trim()).filter(Boolean).filter(t=>R.test(t)).slice(0,3);if(0===n.length)return null;const s=/fail/i.test(t)&&!/0\s+fail/i.test(t);return{label:s?"Tests failed":"Tests pass",content:n.map(t=>$(t)).join("\n"),failed:s}}function j(t,n){if(t.webResults&&t.webResults.length>0)return{type:"finding",label:$(t.query||"Web search",T),content:t.webResults.slice(0,3).map(t=>$(t.title)).join("\n")};if(null==t.numMatches&&null==t.numFiles)return null;const s=[];null!=t.numMatches&&s.push(`${t.numMatches} match${1===t.numMatches?"":"es"}`),null!=t.numFiles&&s.push(`${t.numFiles} file${1===t.numFiles?"":"s"}`);const o=(t.filePaths??[]).slice(0,3).map(t=>$(n(t)));return{type:"pattern",label:$(t.query||"Search",T),content:[s.join(" \xb7 "),...o].filter(Boolean).join("\n")}}function M(t,n){const s=t.content?t.content.split("\n").length:0,o=t.content?E(t.content,2):[];return{type:"code",label:`NEW: ${$(n(t.filePath),T)}`,content:[s>0?`${s} lines`:"created",...o].filter(Boolean).join("\n")}}function D(t,n){const s=t.output?S(t.output):null;return s?{type:s.failed?"error":"finding",label:s.label,content:s.content}:n||null!=t.exitCode&&0!==t.exitCode?{type:"error",label:"Command failed",content:[$(t.command,T),null!=t.exitCode?`exit ${t.exitCode}`:""].filter(Boolean).join("\n")}:null}function O(t){if(!t.result)return null;let n=t.url;try{n=new URL(t.url).host||t.url}catch{}return{type:"finding",label:$(n,T),content:E(t.result,2).join("\n")||"fetched"}}function N(t,n){const s=t=>c(t,n?.workspaceRoot);switch(t.type){case"search":return j(t,s);case"write":return M(t,s);case"edit":return{type:"code",label:$(s(t.filePath),T),content:t.unifiedDiff?A(t.unifiedDiff):"edited"};case"shell":return D(t,n?.isError);case"fetch":return O(t);default:return null}}function W(t){let n=0;try{n=JSON.stringify(t)?.length??0}catch{return}const s=Math.round(n/4);return s>0?s:void 0}function P(t){if("string"==typeof t)return t;if(t&&"object"==typeof t&&"message"in t){const n=t.message;if("string"==typeof n)return n}try{return JSON.stringify(t)}catch{return String(t)}}function z(n){return(0,t.deriveObservedSubagentTitle)(Object.assign({},n.subAgentType?{subAgentType:n.subAgentType}:{},n.description?{description:n.description}:{}))}function q(t){return z(t)}function B(t){const{ctx:s,item:o,time:r}=t,l=k(o.detail),u=l?c(l,s.workspaceRoot):void 0,p=u??c(v(o.detail),s.workspaceRoot),f=[{time:r,sessionId:s.sessionId,type:"tool_call_start",payload:Object.assign({agent:s.name,tool:(0,n.getToolDisplayName)(o.name),args:p},u?{inputData:{file_path:u}}:{})}];if("sub_agent"===o.detail.type){const t=q(o.detail);f.push({time:r,sessionId:s.sessionId,type:"subagent_dispatch",payload:{parent:s.name,child:t,task:t}})}return f}function F(t){const{ctx:s,item:o,time:r}=t,l="sub_agent"===o.detail.type?o.detail:null;if("running"===o.status)return B({ctx:s,item:o,time:r});const u=t.synthesizeStart?B({ctx:s,item:o,time:r}):[],c="failed"===o.status,p=W(o.detail),f=N(o.detail,{workspaceRoot:s.workspaceRoot,isError:c});if(u.push({time:r,sessionId:s.sessionId,type:"tool_call_end",payload:Object.assign({agent:s.name,tool:(0,n.getToolDisplayName)(o.name),result:w(o.detail),isError:c},null!=p?{tokenCost:p}:{},f?{discovery:f}:{},c?{errorMessage:P(o.error)}:{})}),l){const t=q(l);u.push({time:r,sessionId:s.sessionId,type:"subagent_return",payload:{parent:s.name,child:t,summary:w(o.detail)}})}return u}function U(t){const{ctx:n,item:s,time:o}=t;switch(s.type){case"user_message":return[{time:o,sessionId:n.sessionId,type:"message",payload:{agent:n.name,content:s.text,role:"user"}}];case"assistant_message":return[{time:o,sessionId:n.sessionId,type:"message",payload:{agent:n.name,content:s.text,role:"assistant"}}];case"reasoning":return[{time:o,sessionId:n.sessionId,type:"message",payload:{agent:n.name,content:s.text,role:"thinking"}}];case"tool_call":return F({ctx:n,item:s,time:o,synthesizeStart:t.synthesizeToolCallStart});default:return[]}}},6910,[6911,4395]);
1862
1862
  __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"OBSERVED_SUBAGENT_TITLE_MAX",{enumerable:!0,get:function(){return n}}),e.normalizeObservedTitleSource=u,e.normalizeObservedSubagentType=l,e.deriveObservedSubagentTitle=function(t){const o=l(t.subAgentType)??u(t.description)??"Subagent";if(o.length<=n)return o;return`${o.slice(0,59).trimEnd()}\u2026`},e.observedUpdateHasTitleSource=function(n){return null!==l(n.subAgentType)||null!==u(n.description)};const n=60,t=new Set(["general-purpose","general","task","agent","subagent"]);function u(n){if("string"!=typeof n)return null;const t=n.replace(/\s+/g," ").trim();return t.length>0?t:null}function l(n){const l=u(n);return null===l||t.has(l.toLowerCase())?null:l}},6911,[]);
1863
1863
  __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.resolveVisualizerAppearance=function(F){const n=F.isCompact?F.uiFontSize+t.COMPACT_UI_FONT_SIZE_BUMP:F.uiFontSize;return{uiFontFamily:F.uiFontFamily.trim()||o.DEFAULT_UI_FONT_STACK,codeFontFamily:F.monoFontFamily.trim()||o.DEFAULT_MONO_FONT_STACK,chatFontSize:Math.round(o.FONT_SIZE.sm*(n/o.FONT_SIZE.base))}};var t=r(d[0]),o=r(d[1])},6912,[4343,305]);