castle-web-cli 0.4.173 → 0.4.174
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-prompts.d.ts +8 -2
- package/dist/agent-prompts.js +19 -11
- package/dist/agent.js +37 -13
- package/dist/native/loop.js +9 -0
- package/dist/native/openrouter.d.ts +2 -0
- package/dist/native/openrouter.js +10 -1
- package/dist/native/types.d.ts +1 -0
- package/dist/shell/assets/{index-Ws0WrCbi.js → index-DF1yMXPS.js} +4 -4
- package/dist/shell/index.html +1 -1
- package/kits/base/castle.json +1 -1
- package/package.json +1 -1
package/dist/agent-prompts.d.ts
CHANGED
|
@@ -75,7 +75,11 @@ export declare function renderPlanDigest(plan: RouterPlanOpts, tasks: PromptTask
|
|
|
75
75
|
export declare function planOpenQuestionLines(fileText: string): string[];
|
|
76
76
|
export declare function renderTaskPlanSlice(fileText: string, item: string | undefined, finishedWork?: PlanFinishedWork[]): string;
|
|
77
77
|
export declare const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
|
|
78
|
-
export
|
|
78
|
+
export interface RouterPromptParts {
|
|
79
|
+
system: string;
|
|
80
|
+
user: string;
|
|
81
|
+
}
|
|
82
|
+
export interface RouterPromptOpts {
|
|
79
83
|
deckLabel: string;
|
|
80
84
|
quickReference?: string;
|
|
81
85
|
deckTree?: string;
|
|
@@ -85,7 +89,9 @@ export declare function buildRouterPrompt(opts: {
|
|
|
85
89
|
plan?: RouterPlanOpts;
|
|
86
90
|
playtest?: boolean;
|
|
87
91
|
instruction: string;
|
|
88
|
-
}
|
|
92
|
+
}
|
|
93
|
+
export declare function buildRouterPromptParts(opts: RouterPromptOpts): RouterPromptParts;
|
|
94
|
+
export declare function buildRouterPrompt(opts: RouterPromptOpts): string;
|
|
89
95
|
export declare function userTurnInstruction(opts: {
|
|
90
96
|
messages: string[];
|
|
91
97
|
interruptedDraft?: string;
|
package/dist/agent-prompts.js
CHANGED
|
@@ -820,7 +820,7 @@ function renderTasks(tasks, showItems) {
|
|
|
820
820
|
// not included" and burns its first turns hunting for CLAUDE.md. Exported so
|
|
821
821
|
// the platform block (platformDoc.ts) can keep the sentence after itself.
|
|
822
822
|
export const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
|
|
823
|
-
export function
|
|
823
|
+
export function buildRouterPromptParts(opts) {
|
|
824
824
|
// Making the ABSENCE explicit, not just omitting the section, matters: a
|
|
825
825
|
// router on a bare/greenfield deck otherwise has no way to tell "no docs
|
|
826
826
|
// exist" from "the docs section just wasn't included in this prompt", and
|
|
@@ -842,17 +842,19 @@ export function buildRouterPrompt(opts) {
|
|
|
842
842
|
const plan = opts.plan
|
|
843
843
|
? `\n\n== plan ==\n${renderPlanDigest(opts.plan, opts.tasks)}`
|
|
844
844
|
: "";
|
|
845
|
-
//
|
|
846
|
-
//
|
|
847
|
-
//
|
|
848
|
-
//
|
|
849
|
-
|
|
845
|
+
// Two parts, split for prompt caching. `system` holds what is the same from
|
|
846
|
+
// one turn to the next within a serve -- the rules, the deck identity, the
|
|
847
|
+
// file tree and (smith) the deck source -- and each backend sends it as
|
|
848
|
+
// system text, which is the prefix the provider caches turn after turn. A
|
|
849
|
+
// file edit invalidates it; a chat turn does not. `user` holds what changes
|
|
850
|
+
// every turn: the transcript, the plan, the board and this instruction.
|
|
851
|
+
return {
|
|
852
|
+
system: `${routerRules(opts.plan !== undefined, opts.playtest === true)}
|
|
850
853
|
|
|
851
854
|
== deck ==
|
|
852
|
-
${opts.deckLabel}${quickReference}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
${renderTranscript(opts.messages)}${deckFiles}${deckSource}${plan}
|
|
855
|
+
${opts.deckLabel}${quickReference}${deckFiles}${deckSource}`,
|
|
856
|
+
user: `== conversation so far ==
|
|
857
|
+
${renderTranscript(opts.messages)}${plan}
|
|
856
858
|
|
|
857
859
|
== background tasks ==
|
|
858
860
|
${renderTasks(opts.tasks, opts.plan !== undefined)}
|
|
@@ -860,7 +862,13 @@ ${renderTasks(opts.tasks, opts.plan !== undefined)}
|
|
|
860
862
|
== now ==
|
|
861
863
|
${opts.instruction}
|
|
862
864
|
|
|
863
|
-
Reply now, as "you" in the conversation. Plain reply text only -- no role prefix
|
|
865
|
+
Reply now, as "you" in the conversation. Plain reply text only -- no role prefix.`,
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
// The router prompt as one string, system part first. What the goldens pin.
|
|
869
|
+
export function buildRouterPrompt(opts) {
|
|
870
|
+
const parts = buildRouterPromptParts(opts);
|
|
871
|
+
return `${parts.system}\n\n${parts.user}`;
|
|
864
872
|
}
|
|
865
873
|
export function userTurnInstruction(opts) {
|
|
866
874
|
const parts = [];
|
package/dist/agent.js
CHANGED
|
@@ -27,7 +27,7 @@ import { WebSocketServer } from 'ws';
|
|
|
27
27
|
import { rawDataToString } from './rawData.js';
|
|
28
28
|
import { atomicWriteFileSync } from './atomicFile.js';
|
|
29
29
|
import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
|
|
30
|
-
import { applyPlanOps,
|
|
30
|
+
import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, planOpenQuestionLines, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, } from './agent-prompts.js';
|
|
31
31
|
import { readCastleJson } from './castleJson.js';
|
|
32
32
|
import { checkOpenrouterKey, checkOpenrouterModel, openrouterCatalogEntry, primeOpenrouterCatalog, } from './openrouter-catalog.js';
|
|
33
33
|
import { classifyProviderError, failureCopy, setReaderTimeZone, } from './agent-failures.js';
|
|
@@ -501,6 +501,17 @@ function claudeSettingsArg(auth) {
|
|
|
501
501
|
...(auth?.mode === 'user-key' ? { apiKeyHelper: anthropicKeyHelperCommand() } : {}),
|
|
502
502
|
});
|
|
503
503
|
}
|
|
504
|
+
// The claude CLI puts every CLAUDE.md it finds, and a git-status note, into the
|
|
505
|
+
// first user message of each process, ahead of the prompt. A router turn is a
|
|
506
|
+
// new process, so that text (the kit guide: ~23k tokens on a kit deck) is sent
|
|
507
|
+
// uncached on every call of every turn. The router already carries the deck's
|
|
508
|
+
// quick reference and file tree in its cached system part, and can read a
|
|
509
|
+
// guide on demand; tasks keep the CLI's own loading. Measured on a 30k-token
|
|
510
|
+
// router prompt: a second turn goes from 40k tokens written to 4.6k.
|
|
511
|
+
const ROUTER_CLAUDE_ENV = {
|
|
512
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1',
|
|
513
|
+
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS: '1',
|
|
514
|
+
};
|
|
504
515
|
function buildAgentInvocation(backend, role, prompt, claudeModel,
|
|
505
516
|
// Already resolved for this role by the caller (router turns pass
|
|
506
517
|
// settings.routerOpenrouterModel, task spawns settings.tasksOpenrouterModel).
|
|
@@ -512,7 +523,14 @@ metering,
|
|
|
512
523
|
// The task this spawn belongs to, so its playtest frames land under
|
|
513
524
|
// tasks/<id>/playtest/ and count against that task's call budget. Absent for
|
|
514
525
|
// router turns, which get no playtest tool at all.
|
|
515
|
-
taskId
|
|
526
|
+
taskId,
|
|
527
|
+
// The stable part of a router prompt. claude takes it as appended system
|
|
528
|
+
// text, which its own cache breakpoints cover; cursor has no such flag and
|
|
529
|
+
// gets it ahead of the prompt.
|
|
530
|
+
systemPrompt) {
|
|
531
|
+
const systemText = [systemPrompt, role === 'task' ? CLAUDE_TASK_SYSTEM_REMINDER : undefined]
|
|
532
|
+
.filter((text) => Boolean(text))
|
|
533
|
+
.join('\n\n');
|
|
516
534
|
if (backend === 'claude') {
|
|
517
535
|
const viaOpenrouter = claudeModel === 'openrouter';
|
|
518
536
|
const orAuth = viaOpenrouter ? resolveOpenrouterAuth() : null;
|
|
@@ -547,15 +565,18 @@ taskId) {
|
|
|
547
565
|
claudeSettingsArg(anAuth),
|
|
548
566
|
'--strict-mcp-config',
|
|
549
567
|
...(role === 'task' ? [mcpConfigArg(metering.deckDir, taskId)] : []),
|
|
550
|
-
...(
|
|
568
|
+
...(systemText ? ['--append-system-prompt', systemText] : []),
|
|
551
569
|
prompt,
|
|
552
570
|
],
|
|
553
|
-
env:
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
571
|
+
env: {
|
|
572
|
+
...withCustomHeaders(viaOpenrouter ? envForOpenrouterSpawn(orAuth) : envForClaudeSpawn(anAuth), meteringHeaders({
|
|
573
|
+
deckDir: metering.deckDir,
|
|
574
|
+
sessionId: metering.sessionId,
|
|
575
|
+
route: viaOpenrouter ? 'openrouter' : 'anthropic',
|
|
576
|
+
direct,
|
|
577
|
+
})),
|
|
578
|
+
...(role === 'router' ? ROUTER_CLAUDE_ENV : {}),
|
|
579
|
+
},
|
|
559
580
|
};
|
|
560
581
|
}
|
|
561
582
|
return {
|
|
@@ -569,7 +590,7 @@ taskId) {
|
|
|
569
590
|
'--model',
|
|
570
591
|
CURSOR_MODEL,
|
|
571
592
|
...(role === 'router' ? ['--mode', 'ask'] : ['--force']),
|
|
572
|
-
prompt,
|
|
593
|
+
systemPrompt ? `${systemPrompt}\n\n${prompt}` : prompt,
|
|
573
594
|
],
|
|
574
595
|
env: envForAgentSpawn(backend),
|
|
575
596
|
};
|
|
@@ -1852,6 +1873,7 @@ async function runAgentSmith(opts) {
|
|
|
1852
1873
|
// "" (auto) becomes undefined so no provider.order is sent.
|
|
1853
1874
|
providerTier: opts.openrouterTuning?.providerTier || undefined,
|
|
1854
1875
|
prompt: opts.prompt,
|
|
1876
|
+
system: opts.system,
|
|
1855
1877
|
systemReminder: opts.systemReminder,
|
|
1856
1878
|
attachments: opts.attachments,
|
|
1857
1879
|
timeoutMs: opts.timeoutMs,
|
|
@@ -2169,6 +2191,7 @@ async function runAgentTurn(opts) {
|
|
|
2169
2191
|
}),
|
|
2170
2192
|
model: opts.openrouterModel,
|
|
2171
2193
|
prompt: opts.prompt,
|
|
2194
|
+
system: opts.systemPrompt,
|
|
2172
2195
|
// Mirrors claude's --append-system-prompt for tasks (the native loop
|
|
2173
2196
|
// appends it to its own system framing).
|
|
2174
2197
|
systemReminder: opts.role === 'task' ? CLAUDE_TASK_SYSTEM_REMINDER : undefined,
|
|
@@ -2185,7 +2208,7 @@ async function runAgentTurn(opts) {
|
|
|
2185
2208
|
onSpawn: opts.onSpawn,
|
|
2186
2209
|
}));
|
|
2187
2210
|
}
|
|
2188
|
-
const invocation = buildAgentInvocation(opts.backend, opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, { sessionId, deckDir: opts.cwd }, opts.taskId);
|
|
2211
|
+
const invocation = buildAgentInvocation(opts.backend, opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, { sessionId, deckDir: opts.cwd }, opts.taskId, opts.systemPrompt);
|
|
2189
2212
|
const startedMs = Date.now();
|
|
2190
2213
|
const run = runAgentCli({
|
|
2191
2214
|
cwd: opts.cwd,
|
|
@@ -3273,7 +3296,7 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
|
|
|
3273
3296
|
// ROUTER_DECK_CONTENTS_BUDGET's comment (the router prompt is already the
|
|
3274
3297
|
// largest one this serve builds).
|
|
3275
3298
|
const isSmith = ctx.backend() === 'smith';
|
|
3276
|
-
return
|
|
3299
|
+
return buildRouterPromptParts({
|
|
3277
3300
|
deckLabel: ctx.deckLabel,
|
|
3278
3301
|
quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, ctx.backend()),
|
|
3279
3302
|
deckTree: buildDeckTree(ctx.deckDir, isSmith
|
|
@@ -3409,7 +3432,8 @@ function runRouterTurnIn(ctx, instruction, attachments = []) {
|
|
|
3409
3432
|
void runAgentTurn({
|
|
3410
3433
|
backend,
|
|
3411
3434
|
role: 'router',
|
|
3412
|
-
prompt,
|
|
3435
|
+
prompt: prompt.user,
|
|
3436
|
+
systemPrompt: prompt.system,
|
|
3413
3437
|
claudeModel: ctx.claudeModel(),
|
|
3414
3438
|
openrouterModel: ctx.openrouterModel(),
|
|
3415
3439
|
openrouterTuning: ctx.openrouterTuning(),
|
package/dist/native/loop.js
CHANGED
|
@@ -319,6 +319,8 @@ const ROLE_FRAMING = {
|
|
|
319
319
|
};
|
|
320
320
|
function buildSystemMessage(opts) {
|
|
321
321
|
const parts = [ROLE_FRAMING[opts.role]];
|
|
322
|
+
if (opts.system)
|
|
323
|
+
parts.push(opts.system);
|
|
322
324
|
if (opts.systemReminder)
|
|
323
325
|
parts.push(opts.systemReminder);
|
|
324
326
|
return parts.join("\n\n");
|
|
@@ -700,10 +702,17 @@ async function runLoop(opts, toolSchemas, log) {
|
|
|
700
702
|
};
|
|
701
703
|
}
|
|
702
704
|
usedAnyTool = true;
|
|
705
|
+
// The reasoning goes back with the turn it belongs to. Anthropic treats an
|
|
706
|
+
// assistant turn returned without its thinking as a changed prefix and
|
|
707
|
+
// recomputes every message after it, so without this no call in the loop
|
|
708
|
+
// reads the cache (measured: 0 cached tokens per call, 30k written each).
|
|
703
709
|
messages.push({
|
|
704
710
|
role: "assistant",
|
|
705
711
|
content: streamResult.message.content || null,
|
|
706
712
|
tool_calls: toolCalls,
|
|
713
|
+
...(streamResult.message.reasoning_details
|
|
714
|
+
? { reasoning_details: streamResult.message.reasoning_details }
|
|
715
|
+
: {}),
|
|
707
716
|
});
|
|
708
717
|
const toolResults = await runToolCalls(toolCalls, opts.role, toolCtx, playtestFrames, toolLabels, imageLabels, log, opts.onActivity);
|
|
709
718
|
messages.push(...toolResults);
|
|
@@ -25,11 +25,13 @@ export interface ORMessage {
|
|
|
25
25
|
content?: string | null | ORContentPart[];
|
|
26
26
|
tool_calls?: ORToolCall[];
|
|
27
27
|
tool_call_id?: string;
|
|
28
|
+
reasoning_details?: unknown[];
|
|
28
29
|
}
|
|
29
30
|
export interface ORAssistantMessage {
|
|
30
31
|
role: "assistant";
|
|
31
32
|
content: string;
|
|
32
33
|
tool_calls?: ORToolCall[];
|
|
34
|
+
reasoning_details?: unknown[];
|
|
33
35
|
}
|
|
34
36
|
export type ORReasoningEffort = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
35
37
|
export type ORRoutingMode = "balanced" | "nitro" | "exacto" | "floor";
|
|
@@ -344,6 +344,7 @@ export async function streamChatCompletion(opts) {
|
|
|
344
344
|
return { message: null, crashed: false, error: "could not run openrouter: empty response body" };
|
|
345
345
|
}
|
|
346
346
|
let content = "";
|
|
347
|
+
const reasoningDetails = [];
|
|
347
348
|
// Observed live (2026-07): some providers' MID-stream usage passthrough is
|
|
348
349
|
// junk (constant cache_read=128 / cache_created=0 on every event) while the
|
|
349
350
|
// FINAL usage chunk -- the one OpenRouter emits at/after finish_reason --
|
|
@@ -398,6 +399,9 @@ export async function streamChatCompletion(opts) {
|
|
|
398
399
|
if (typeof delta.reasoning === "string" && delta.reasoning) {
|
|
399
400
|
opts.onThinking?.(delta.reasoning);
|
|
400
401
|
}
|
|
402
|
+
if (Array.isArray(delta.reasoning_details)) {
|
|
403
|
+
reasoningDetails.push(...delta.reasoning_details);
|
|
404
|
+
}
|
|
401
405
|
const toolCallDeltas = delta.tool_calls;
|
|
402
406
|
if (Array.isArray(toolCallDeltas)) {
|
|
403
407
|
for (const tc of toolCallDeltas) {
|
|
@@ -461,7 +465,12 @@ export async function streamChatCompletion(opts) {
|
|
|
461
465
|
};
|
|
462
466
|
}
|
|
463
467
|
return {
|
|
464
|
-
message: {
|
|
468
|
+
message: {
|
|
469
|
+
role: "assistant",
|
|
470
|
+
content,
|
|
471
|
+
tool_calls: finalizeToolCalls(pendingToolCalls),
|
|
472
|
+
...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
|
|
473
|
+
},
|
|
465
474
|
usage: finalUsage ?? usage,
|
|
466
475
|
reasoningTokens: finalReasoningTokens ?? reasoningTokens,
|
|
467
476
|
crashed: false,
|
package/dist/native/types.d.ts
CHANGED
|
@@ -438,8 +438,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
438
438
|
${e}</tr>
|
|
439
439
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
440
440
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${wW(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=TW(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+wW(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=TW(e);if(i===null)return wW(n);e=i;let a=`<img src="${e}" alt="${wW(n)}"`;return t&&(a+=` title="${wW(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:wW(e.text)}},IW=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},LW=class e{options;renderer;textRenderer;constructor(e){this.options=e||uU,this.options.renderer=this.options.renderer||new FW,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new IW}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},RW=class{options;block;constructor(e){this.options=e||uU}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?PW.lex:PW.lexInline}provideParser(e=this.block){return e?LW.parse:LW.parseInline}},zW=new class{defaults=lU();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=LW;Renderer=FW;TextRenderer=IW;Lexer=PW;Tokenizer=NW;Hooks=RW;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new FW(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new NW(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new RW;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];RW.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&RW.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return PW.lex(e,t??this.defaults)}parser(e,t){return LW.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?PW.lex:PW.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?LW.parse:LW.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?PW.lex:PW.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?LW.parse:LW.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
441
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+wW(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function BW(e,t){return zW.parse(e,t)}BW.options=BW.setOptions=function(e){return zW.setOptions(e),BW.defaults=zW.defaults,dU(BW.defaults),BW},BW.getDefaults=lU,BW.defaults=uU,BW.use=function(...e){return zW.use(...e),BW.defaults=zW.defaults,dU(BW.defaults),BW},BW.walkTokens=function(e,t){return zW.walkTokens(e,t)},BW.parseInline=zW.parseInline,BW.Parser=LW,BW.parser=LW.parse,BW.Renderer=FW,BW.TextRenderer=IW,BW.Lexer=PW,BW.lexer=PW.lex,BW.Tokenizer=NW,BW.Hooks=RW,BW.parse=BW,BW.options,BW.setOptions,BW.use,BW.walkTokens,BW.parseInline,LW.parse,PW.lex;var VW
|
|
441
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+wW(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function BW(e,t){return zW.parse(e,t)}BW.options=BW.setOptions=function(e){return zW.setOptions(e),BW.defaults=zW.defaults,dU(BW.defaults),BW},BW.getDefaults=lU,BW.defaults=uU,BW.use=function(...e){return zW.use(...e),BW.defaults=zW.defaults,dU(BW.defaults),BW},BW.walkTokens=function(e,t){return zW.walkTokens(e,t)},BW.parseInline=zW.parseInline,BW.Parser=LW,BW.parser=LW.parse,BW.Renderer=FW,BW.TextRenderer=IW,BW.Lexer=PW,BW.lexer=PW.lex,BW.Tokenizer=NW,BW.Hooks=RW,BW.parse=BW,BW.options,BW.setOptions,BW.use,BW.walkTokens,BW.parseInline,LW.parse,PW.lex;var VW=20;function HW(e,t){let n=e.lastIndexOf(`@`,t-1);if(n<0||n>0&&!/\s/.test(e[n-1]))return null;let r=e.slice(n+1,t);return/\s/.test(r)?null:{start:n,end:t,query:r}}function UW(e){let{inputRef:t,anchorRef:n,setValue:r}=e,[i,a]=g.useState(null),[o,s]=g.useState([]),[c,l]=g.useState([]),[u,d]=g.useState(0),f=g.useRef(null),p=g.useCallback(()=>{let e=t.current;if(!e)return;let n=HW(e.value,e.selectionStart??0);if(!n){f.current=null,a(null);return}f.current!==null&&f.current!==n.start&&(f.current=null),a(f.current===n.start?null:n)},[t]),m=i!==null;g.useEffect(()=>{m&&ln(!0).then(s,()=>s([]))},[m]);let h=g.useMemo(()=>i?Tn(o,i.query).slice(0,VW):[],[o,i]),_=i!==null&&h.length>0;g.useEffect(()=>d(0),[i?.query,i?.start]);let v=g.useCallback(()=>{i&&(f.current=i.start),a(null)},[i]),y=g.useCallback(e=>{if(!i)return;let n=t.current?.value??``,o=`${n.slice(0,i.start)}@${e} ${n.slice(i.end)}`;l(t=>t.includes(e)?t:[...t,e]),r(o),a(null),f.current=null;let s=i.start+e.length+2;requestAnimationFrame(()=>{let e=t.current;e&&(e.focus(),e.setSelectionRange(s,s))})},[i,t,r]),b=g.useCallback(e=>{if(!_)return!1;if(e.key===`Escape`)v();else if(e.key===`ArrowDown`)d(e=>Math.min(h.length-1,e+1));else if(e.key===`ArrowUp`)d(e=>Math.max(0,e-1));else if(e.key===`Enter`||e.key===`Tab`)y(h[Math.min(u,h.length-1)]);else return!1;return e.preventDefault(),!0},[_,h,u,y,v]),x=g.useCallback(e=>c.filter(t=>e.includes(`@${t}`)),[c]);return{overlay:_?(0,j.jsx)(WW,{anchorRef:n,results:h,index:u,onHover:d,onPick:y,onDismiss:v}):null,handleKeyDown:b,sync:p,attachedIn:x,clear:g.useCallback(()=>{l([]),a(null),f.current=null},[])}}function WW(e){let t=g.useRef(null),n=Rr(t,e.anchorRef,[e.results]),{anchorRef:r,onDismiss:i}=e;return g.useEffect(()=>{let e=e=>{let n=e.target;t.current?.contains(n)||r.current?.contains(n)||i()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[r,i]),g.useEffect(()=>{t.current?.querySelector(`.mention-item.active`)?.scrollIntoView({block:`nearest`})},[e.index]),(0,It.createPortal)((0,j.jsx)(`div`,{className:`mention-picker`,ref:t,style:n,onMouseDown:e=>e.preventDefault(),children:e.results.map((t,n)=>(0,j.jsxs)(`button`,{type:`button`,className:`mention-item${n===e.index?` active`:``}`,onMouseEnter:()=>e.onHover(n),onClick:()=>e.onPick(t),children:[(0,j.jsx)(`span`,{className:`mention-name`,children:se(t)}),(0,j.jsx)(`span`,{className:`mention-dir`,children:ce(t)})]},t))}),document.body)}var GW=/```ask[ \t]*\n([\s\S]*?)```/g,KW=/\[\[([^[\]\n]+)\]\]/g;function qW(e,t){let n=[],r=e.replace(KW,(e,t)=>{let r=t.trim();return r&&!n.includes(r)&&n.push(r),``});return t&&(r=r.replace(/\[\[[\s\S]*$/,``).replace(/\[$/,``)),{prose:r.replace(/[ \t]+$/gm,``).replace(/\n{3,}/g,`
|
|
442
442
|
|
|
443
|
-
`),chips:n}}function
|
|
444
|
-
`),a=(i===-1?r:r.slice(0,i)).trim();i===-1?a===``?e=e.slice(0,t):`ask`.startsWith(a)&&(e=e.slice(0,t),n=!0):a===`ask`&&(e=e.slice(0,t),n=!0)}let r=[],i=0,a;for(
|
|
445
|
-
`)}`:``}var vG={thinking:(0,j.jsx)(M,{name:`lightbulb`}),reading:(0,j.jsx)(M,{name:`book`}),building:(0,j.jsx)(M,{name:`hammer`}),painting:(0,j.jsx)(M,{name:`pencil`}),playing:(0,j.jsx)(M,{name:`gamepad`})},yG={thinking:`Thinking`,reading:`Reading files`,building:`Editing logic`,painting:`Editing art`,playing:`Playtesting`},bG={thinking:`#FFC826`,reading:`#FFC826`,building:`#FFEB57`,painting:`#FFEB57`,playing:`#D3FC7E`};function xG(e){if(e.status===`done`)return{icon:(0,j.jsx)(M,{name:`check`}),color:`#5AC54F`};if(e.status===`failed`)return{icon:(0,j.jsx)(M,{name:`times`}),color:`#F5545D`};if(e.status===`interrupted`)return{icon:(0,j.jsx)(M,{name:`stop`}),color:`#B4B4B4`};if(e.status===`blocked`)return{icon:(0,j.jsx)(M,{name:`stop`}),color:`#F5A623`};let t=e.avatar&&vG[e.avatar]?e.avatar:`thinking`;return{icon:vG[t],color:bG[t]}}function SG(e){let t=Math.max(1,Math.round((e??0)/1e3));if(t<60)return`Thought for ${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`Thought for ${n}m`:`Thought for ${n}m ${r}s`}var CG=`plan.md`;function wG(){let e=hi();return(0,j.jsxs)(`button`,{type:`button`,className:`msg-plan`,title:`Open ${CG}`,onClick:()=>e.openFile(CG),children:[CG,` updated`]})}function TG(e){let t=hi();return(0,j.jsxs)(`button`,{type:`button`,className:`msg-file`,title:`Open ${e.path}`,onClick:()=>t.openFile(e.path),children:[`@`,e.path]})}function EG(e,t){if(t.length===0)return[e];let n=[...t].sort((e,t)=>t.length-e.length).map(e=>({path:e,token:`@${e}`})),r=[],i=``;for(let t=0;t<e.length;){let a=n.find(n=>e.startsWith(n.token,t));if(!a){i+=e[t],t+=1;continue}i&&r.push(i),i=``,r.push({path:a.path}),t+=a.token.length}return i&&r.push(i),r}function DG(e){return(0,j.jsx)(`span`,{children:EG(e.text,e.files??[]).map((e,t)=>typeof e==`string`?e:(0,j.jsx)(TG,{path:e.path},`${e.path}-${t}`))})}function OG(e){try{return{__html:BW.parse(e,{breaks:!0,async:!1})}}catch{return{__html:``}}}var kG=(0,j.jsx)(M,{name:`send`}),AG=(0,j.jsx)(M,{name:`stop`}),jG=(0,j.jsx)(M,{name:`chevron-down`,className:`mode-caret`}),MG=[{value:`claude`,label:`Claude`},{value:`cursor`,label:`Cursor`},{value:`smith`,label:`Smith`}],NG=[{value:`opus`,label:`Opus`},{value:`sonnet`,label:`Sonnet`},{value:`fable`,label:`Fable`},{value:`openrouter`,label:`OpenRouter`}];function PG(e,t){return e===`smith`||e===`claude`&&t===`openrouter`}function FG(e){if(!e||!e.trim())return null;let t=e.trim(),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function IG(e,t,n){let r=MG.find(t=>t.value===e)?.label??e??`?`;if(e===`claude`){if(t===`openrouter`){let e=FG(n);return e?`${r} (${e})`:`${r} (OpenRouter)`}let e=NG.find(e=>e.value===t)?.label??t;return e?`${r} (${e})`:r}if(e===`smith`){let e=FG(n);return e?`${r} (${e})`:r}return r}function LG(e){return`${IG(e.router,e.routerClaudeModel,e.routerOpenrouterModel)} → ${IG(e.tasks,e.tasksClaudeModel,e.tasksOpenrouterModel)}`}var RG=`/__castle/agent/model-caps`,zG=[{value:`balanced`,label:`Balanced`},{value:`nitro`,label:`Nitro`},{value:`exacto`,label:`Exacto`},{value:`floor`,label:`Floor`}],BG=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],VG={none:`None`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`XHigh`,max:`Max`};function HG(e){let t=e?.reasoningEfforts;if(!t||t.length===0)return null;let n=new Set(t);return BG.filter(e=>n.has(e)).map(e=>({value:e,label:VG[e]??e}))}var UG={openai:`OpenAI`,azure:`Azure`,anthropic:`Anthropic`,google:`Google`,"google-vertex":`Vertex`,deepinfra:`DeepInfra`,fireworks:`Fireworks`,together:`Together`,groq:`Groq`,cerebras:`Cerebras`,baseten:`Baseten`},WG={flex:`Flex`,priority:`Priority`,standard:`Standard`,eu:`EU`};function GG(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}function KG(e){let[t,n]=e.split(`/`),r=UG[t]??GG(t);return n?`${r} ${WG[n]??GG(n)}`:r}function qG(e){let t=e?.providerTiers;return!t||t.length<2?null:[{value:``,label:`Auto`},...t.map(e=>({value:e,label:KG(e)}))]}function JG(e,t,n,r,i){let a=e===`router`,o=a?`routerClaudeModel`:`tasksClaudeModel`,s=a?`routerOpenrouterModel`:`tasksOpenrouterModel`,c=[{type:`enum`,key:e,label:a?`Operator`:`Tasks`,options:MG},{type:`enum`,key:o,label:`Model`,options:NG.filter(e=>!r.includes(e.value)),showWhen:t=>t[e]===`claude`,note:i&&t[o]===`openrouter`?`Pick Opus, Sonnet, or Fable to use your Anthropic credentials`:void 0},{type:`text`,key:s,label:`OpenRouter model`,placeholder:a?`openai/gpt-5.6-sol`:`openai/gpt-5.6-terra`,showWhen:t=>PG(t[e],t[o])}];if(t[e]===`smith`){let e=HG(n);e&&c.push({type:`select`,key:a?`routerReasoningEffort`:`tasksReasoningEffort`,label:`Reasoning`,options:e}),c.push({type:`select`,key:a?`routerRouting`:`tasksRouting`,label:`Routing`,options:zG});let t=qG(n);t&&c.push({type:`select`,key:a?`routerProviderTier`:`tasksProviderTier`,label:`Provider`,options:t})}return c}function YG(e){let{label:t,placeholder:n,value:r,warning:i,onCommit:a}=e,[o,s]=g.useState(r);g.useEffect(()=>s(r),[r]);let c=g.useRef(o),l=g.useRef(r),u=g.useRef(a);c.current=o,l.current=r,u.current=a;let d=()=>{let e=c.current.trim();return e&&e!==l.current?(u.current(e),!0):!1},f=()=>{d()||s(l.current)};g.useEffect(()=>()=>{d()},[]);let p=e=>{s(e),a(e)};return(0,j.jsxs)(`div`,{className:`settings-row settings-row-stack`,children:[(0,j.jsxs)(`div`,{className:`settings-row-main`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:t}),(0,j.jsx)(`input`,{type:`text`,className:`settings-text${i?` settings-text-warn`:``}`,value:o,placeholder:n,onChange:e=>s(e.target.value),onBlur:f,onKeyDown:e=>{e.key===`Enter`&&(f(),e.target.blur())}})]}),i?(0,j.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,i.message,i.suggestion?(0,j.jsxs)(j.Fragment,{children:[` `,`Did you mean`,` `,(0,j.jsx)(`button`,{type:`button`,className:`settings-warning-suggest`,onMouseDown:e=>{e.preventDefault(),p(i.suggestion)},children:i.suggestion}),`?`]}):null]}):null]})}function XG(e,t,n){let r=e?.[t];if(!(!r||!n||r.model!==n))return{message:r.message,suggestion:r.suggestion}}function ZG(e){if(!e||e.limitMicros===null||e.limitMicros<=0)return null;if(e.blocked)return 1;if(e.credits?.plan===`daily`&&e.credits.dailyFreeRemainingCredits!==null){let t=e.credits.dailyFreeRemainingCredits*1e4;return t<=0?1:Math.min(1,Math.max(0,e.usedMicros/(e.usedMicros+t)))}return Math.min(1,e.usedMicros/e.limitMicros)}function QG(e){let t=e?.autoReload;return!t?.enabled||t.disabledReason||t.thresholdCredits===null||t.amountCredits===null?null:{thresholdCredits:t.thresholdCredits,amountCredits:t.amountCredits}}function $G(e){if(e?.blocked)return` usage-blocked`;if(e?.credits?.plan===`credits`)return e.credits.lowBalance&&!QG(e.credits)?` usage-warn`:``;let t=ZG(e);return t===null?``:t>=.8?` usage-warn`:``}var eK=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`});function tK(e){return eK.format(e/100)}function nK(e){return tK(e/1e4)}function rK(e,t,n=!1){if(!t||t.displayUnit===`usd`||t.usdPerCredit<=0)return nK(e);let r=Math.round(e/1e6/t.usdPerCredit),i=r.toLocaleString();return n?`${i} ${r===1?`credit`:`credits`}`:`${i} AI ${r===1?`credit`:`credits`}`}function iK(e){return e.resetAtMs?new Date(e.resetAtMs).toLocaleTimeString([],{hour:`numeric`,minute:`2-digit`}):``}function aK(e){let{usage:t}=e,n=ZG(t);if(n===null)return null;let r=iK(t),i=t.credits?.plan===`daily`?t.credits.purchasedCredits+t.credits.grantedCredits:0,a=i>0?` + ${tK(i)} credits`:``;return(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:`Daily AI usage`}),(0,j.jsx)(`span`,{className:`settings-usage-text`,children:(t.blocked?`Limit reached`:`${Math.round(n*100)}%${r?` \u00b7 resets ${r}`:``}`)+a})]}),(0,j.jsx)(`div`,{className:`settings-usage-bar`,children:(0,j.jsx)(`div`,{className:`settings-usage-fill`+(t.blocked?` blocked`:``),style:{width:`${n*100}%`}})})]})}function oK(e){let{usage:t}=e;if(t.spendableMicros===null)return null;let n=iK(t),r=t.credits?.nextGrantAt?new Date(t.credits.nextGrantAt).toLocaleDateString():null,i=t.credits?.autoReload,a=QG(t.credits),o=t.creditsExhausted&&i?.disabledReason?`Auto-reload is paused`:t.credits?.lowBalance&&!t.creditsExhausted&&!t.blocked?a?`Auto-reload adds ${rK(a.amountCredits*1e4,t.credits.rates,!0)} when you drop below ${rK(a.thresholdCredits*1e4,t.credits.rates,!0)}`:i?.enabled&&i.disabledReason?`Auto-reload is paused`:`Running low on credits`:null,s=`${rK(t.spendableMicros,t.credits?.rates,!0)} left`;return t.blocked&&(s=`Daily limit reached${n?` · resets ${n}`:``}`),t.creditsExhausted&&(s=`${rK(0,t.credits?.rates,!0)} left`),(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:`AI credits`}),(0,j.jsx)(`span`,{className:`settings-usage-text`,children:s})]}),o?(0,j.jsx)(`div`,{className:`settings-usage-subtext`,children:o}):null,r?(0,j.jsxs)(`div`,{className:`settings-usage-subtext`,children:[`refreshes `,r]}):null]})}function sK(e){return e.usage.credits?.plan===`credits`?(0,j.jsx)(oK,{usage:e.usage}):(0,j.jsx)(aK,{usage:e.usage})}function cK(e){if(window.ReactNativeWebView){window.ReactNativeWebView.postMessage(JSON.stringify({type:`castle-open-credits`}));return}if(!window.open(`https://castle.xyz/credits`,`_blank`))return;lK?.();let t=()=>{document.visibilityState===`visible`&&(lK?.(),e())};lK=()=>{document.removeEventListener(`visibilitychange`,t),lK=null},document.addEventListener(`visibilitychange`,t)}var lK=null;function uK(e){let{label:t=`Get more credits`,onReturn:n}=e;return(0,j.jsx)(`button`,{type:`button`,className:`settings-account-open`,onClick:()=>cK(n),children:t})}function dK(e){return(0,j.jsx)(`button`,{type:`button`,className:`settings-account-open`,onClick:e.onOpen,children:e.anyStored?`Manage your account`:`Use your own account`})}function fK(e){let{login:t}=e,[n,r]=g.useState(``),i=()=>{n.trim()&&e.onSubmitCode(n.trim())};return(0,j.jsxs)(j.Fragment,{children:[t.url?(0,j.jsxs)(`div`,{className:`castle-key-login`,children:[(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Open this link to sign in, then come back here.`}),(0,j.jsx)(`a`,{className:`castle-key-url`,href:t.url,target:`_blank`,rel:`noreferrer noopener`,children:t.url})]}):(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Starting sign-in…`}),t.phase===`awaiting-code`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Paste the code the browser shows you:`}),(0,j.jsx)(`input`,{className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,value:n,placeholder:`code`,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i()}}),t.message?(0,j.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null]}):null,t.phase===`verifying`?(0,j.jsx)(`div`,{className:`castle-key-stored`,children:`Finishing sign-in…`}):null,t.phase===`error`?(0,j.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null,(0,j.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,j.jsx)(`button`,{type:`button`,onClick:e.onCancel,children:t.phase===`error`?`Close`:`Cancel`}),t.phase===`awaiting-code`?(0,j.jsx)(`button`,{type:`button`,onClick:i,disabled:!n.trim(),children:`Submit`}):null]})]})}function pK(e){let t=e.accounts.providers,n=e.accounts.login,[r,i]=g.useState(()=>(t.find(e=>e.key?.present||e.login?.loggedIn)??t[0])?.id??``),[a,o]=g.useState(``),[s,c]=g.useState(null),l=(n?t.find(e=>e.login?.provider===n.provider):null)??t.find(e=>e.id===r)??t[0]??null,u=g.useRef(e.onClose);u.current=e.onClose;let d=n!==null;g.useEffect(()=>{let e=e=>{e.key===`Escape`&&!d&&u.current()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[d]);let f=g.useRef(null);if(g.useEffect(()=>{if(n){f.current=n.provider;return}let e=f.current;e!==null&&(f.current=null,t.find(t=>t.login?.provider===e)?.login?.loggedIn&&u.current())}),!l)return null;let p=!!l.login?.loggedIn,m=!!l.key?.present,h=p||m,_=()=>{let t=a.trim();if(t){if(t.length>500){c(`That key is too long.`);return}if([...t].some(e=>{let t=e.codePointAt(0)??0;return t<32||t===127})){c(`That key contains invalid characters.`);return}e.onSave(l.id,t),e.onClose()}};return(0,It.createPortal)((0,j.jsx)(`div`,{className:`castle-modal-scrim`,onMouseDown:n?void 0:e.onClose,children:(0,j.jsxs)(`div`,{className:`castle-modal`,onMouseDown:e=>e.stopPropagation(),children:[(0,j.jsx)(`div`,{className:`castle-key-heading`,children:n?`Sign in to ${l.label}`:`Your account`}),n?null:(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Run the operator on your own account and bypass Castle's daily limit.`}),t.length>1&&!n?(0,j.jsx)(`div`,{className:`castle-key-tabs`,children:t.map(e=>(0,j.jsx)(`button`,{type:`button`,className:`castle-key-tab`+(e.id===l.id?` active`:``),onClick:()=>{i(e.id),o(``),c(null)},children:e.label},e.id))}):null,n?(0,j.jsx)(fK,{login:n,onSubmitCode:e.onSubmitCode,onCancel:e.onCancelLogin}):(0,j.jsxs)(j.Fragment,{children:[h?(0,j.jsxs)(j.Fragment,{children:[p?(0,j.jsxs)(`div`,{className:`castle-key-row`,children:[(0,j.jsxs)(`span`,{children:[`Signed in with your `,l.label,` account.`]}),(0,j.jsx)(`button`,{type:`button`,onClick:()=>{e.onLogout(l.id),e.onClose()},children:`Sign out`})]}):null,m?(0,j.jsxs)(`div`,{className:`castle-key-row`,children:[(0,j.jsxs)(`span`,{children:[`API key saved (`,l.key?.hint,`).`]}),(0,j.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemove(l.id),e.onClose()},children:`Remove`})]}):null]}):(0,j.jsxs)(j.Fragment,{children:[l.login?(0,j.jsxs)(`button`,{type:`button`,className:`castle-key-signin`,onClick:()=>e.onStartLogin(l.id),children:[`Sign in with your `,l.label,` account`]}):null,l.login&&l.key?(0,j.jsx)(`div`,{className:`castle-key-or`,children:`or`}):null,l.key?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`castle-key-field-label`,children:`Add API key`}),(0,j.jsx)(`input`,{type:`password`,className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,"data-1p-ignore":!0,"data-lpignore":`true`,value:a,placeholder:l.key.placeholder,onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&_()}}),s?(0,j.jsx)(`div`,{className:`castle-key-error`,children:s}):null]}):null]}),(0,j.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,j.jsx)(`button`,{type:`button`,onClick:e.onClose,children:`Cancel`}),!h&&l.key?(0,j.jsx)(`button`,{type:`button`,onClick:_,disabled:!a.trim(),children:`Save`}):null]})]})]})}),document.body)}function mK(e){let{settings:t,onSetSetting:n,onClose:r}=e,i=e.usage?.credits?.plan===`credits`?e.usage.spendableMicros!==null:ZG(e.usage)!==null,a=e.accounts.providers.some(e=>e.key?.present||e.login?.loggedIn),o=e.accounts.providers.some(e=>e.id===`anthropic`&&(e.key?.present||e.login?.loggedIn)),s=e.accounts.providers.length>0&&(i||a),c=e.usage?.credits?.plan===`credits`?e.usage.credits:null,l=c?e.usage?.creditsExhausted?`Get more credits`:e.usage?.blocked||!c.lowBalance?null:c.autoReload.disabledReason?`Update your card`:QG(c)?null:`Set up auto-reload`:null,u=g.useRef(null),[d,f]=g.useState({}),p=t.routerOpenrouterModel?.trim()??``,m=t.tasksOpenrouterModel?.trim()??``,h=t.router===`smith`,_=t.tasks===`smith`;g.useEffect(()=>{let e=new Set;h&&p&&e.add(p),_&&m&&e.add(m);let t=!1;for(let n of e)fetch(`${RG}?model=${encodeURIComponent(n)}`).then(e=>e.ok?e.json():null).then(e=>{!t&&e&&f(t=>({...t,[n]:e}))}).catch(()=>{});return()=>{t=!0}},[h,p,_,m]);let v=e.usage?.blockedClaudeModels??[],y=[JG(`router`,t,d[p],v,o),JG(`tasks`,t,d[m],v,o)];return Pr(u,r,e.triggerRef),(0,It.createPortal)((0,j.jsxs)(`div`,{className:`settings-popover`,ref:u,style:Rr(u,e.triggerRef,[t,d,i,s,l,e.usage,o]),onMouseDown:e=>e.stopPropagation(),children:[i||s||l?(0,j.jsxs)(`div`,{className:`settings-group`,children:[i&&e.usage?(0,j.jsx)(sK,{usage:e.usage}):null,l?(0,j.jsxs)(`div`,{className:`settings-usage-actions`,children:[s?(0,j.jsx)(dK,{anyStored:a,onOpen:e.onOpenKeys}):null,(0,j.jsx)(uK,{label:l,onReturn:e.onRefreshUsage})]}):s?(0,j.jsx)(dK,{anyStored:a,onOpen:e.onOpenKeys}):null]}):null,y.map((r,i)=>(0,j.jsx)(`div`,{className:`settings-group`,children:r.filter(e=>!e.showWhen||e.showWhen(t)).map(r=>{if(r.type===`text`)return(0,j.jsx)(YG,{label:r.label,placeholder:r.placeholder,value:t[r.key]??``,warning:XG(e.warnings,r.key,t[r.key]),onCommit:e=>n(r.key,e)},r.key);if(r.type===`select`)return(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:r.label}),(0,j.jsx)(`select`,{className:`settings-select`,value:t[r.key]??``,onChange:e=>n(r.key,e.target.value),children:r.options.map(e=>(0,j.jsx)(`option`,{value:e.value,children:e.label},e.value))})]},r.key);let i=t[r.key];return(0,j.jsxs)(`div`,{className:`settings-row settings-row-stack`,children:[(0,j.jsxs)(`div`,{className:`settings-row-main`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:r.label}),(0,j.jsx)(`div`,{className:`settings-seg`,children:r.options.map(e=>(0,j.jsx)(`button`,{type:`button`,tabIndex:-1,className:`settings-opt`+(i===e.value?` active`:``),onClick:()=>n(r.key,e.value),children:e.label},e.value))})]}),r.note?(0,j.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,r.note]}):null]},r.key)})},i))]}),document.body)}function hK(e){let{spec:t,interactive:n,answers:r,onSubmit:i}=e,[a,o]=g.useState({}),s=n?a:r??{},c=(e,t,r)=>{n&&o(n=>{let i=n[e]??[];if(r){let r=i.includes(t)?i.filter(e=>e!==t):[...i,t];return{...n,[e]:r}}return{...n,[e]:i[0]===t?[]:[t]}})};return(0,j.jsxs)(`div`,{className:`picker${n?``:` picker-locked`}`,children:[t.questions.map(e=>(0,j.jsxs)(`fieldset`,{className:`picker-q`,disabled:!n,children:[(0,j.jsx)(`legend`,{className:`picker-q-label`,children:e.q}),(0,j.jsx)(`div`,{className:`picker-options`,children:e.options.map(t=>{let r=(s[e.id]??[]).includes(t);return(0,j.jsxs)(`label`,{className:`picker-option${r?` is-checked`:``}`,children:[(0,j.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:r,disabled:!n,onChange:()=>c(e.id,t,e.multi)}),(0,j.jsx)(`span`,{children:t})]},t)})})]},e.id)),n?(0,j.jsx)(`div`,{className:`picker-actions`,children:(0,j.jsx)(`button`,{className:`picker-submit`,type:`button`,onClick:()=>{let e=_G(t,a);e&&i(a,e)},children:`Submit`})}):null]})}function gK(e){let{chips:t,interactive:n,onPick:r}=e,[i,a]=g.useState(null),o=n&&i===null;return(0,j.jsx)(`div`,{className:`chips`+(o?``:` chips-inert`),children:t.map(e=>(0,j.jsx)(`button`,{type:`button`,className:`chip`+(i===e?` is-picked`:``),disabled:!o,onClick:()=>{a(e),r(e)},children:e},e))})}function _K(){return(0,j.jsxs)(`div`,{className:`picker picker-skeleton`,"aria-hidden":`true`,children:[(0,j.jsx)(`span`,{className:`picker-skeleton-hint`,children:`preparing options…`}),(0,j.jsxs)(`div`,{className:`picker-q`,children:[(0,j.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-label`}),(0,j.jsxs)(`div`,{className:`picker-options`,children:[(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:84}}),(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:116}}),(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:72}})]})]})]})}function vK(e){let t=/^\[Editing (.+)\]$/,n=/^\[Reading (.+)\]$/,r=new Set;for(let n of e){let e=t.exec(n.trim());if(e)for(let t of e[1].split(`, `))r.add(t)}let i=[];for(let t of e){let e=n.exec(t.trim());if(e){let t=e[1].split(`, `).filter(e=>!r.has(e));if(t.length===0)continue;i.push(`[Reading ${t.join(`, `)}]`);continue}i.push(t)}return i}function yK(e){let t=/^\[([A-Za-z]+)\s+(.+)\]$/,n=[];for(let r of e){let e=t.exec(r.trim());if(e){let r=n.length?t.exec(n[n.length-1].trim()):null;if(r&&r[1]===e[1]){r[2].split(`, `).includes(e[2])||(n[n.length-1]=`[${e[1]} ${r[2]}, ${e[2]}]`);continue}}n.push(r)}return n}function bK(e){return e.detail?(0,j.jsxs)(`details`,{className:`msg-error-detail`,children:[(0,j.jsx)(`summary`,{children:`Details (full text in the browser console)`}),(0,j.jsx)(`pre`,{children:e.detail})]}):null}function xK(e){let t=g.useRef(null),n=g.useRef(!0);return g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.lines]),(0,j.jsx)(`div`,{className:`task-feed`,ref:t,onScroll:()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},onClick:e=>e.stopPropagation(),children:yK(vK(e.lines)).map((e,t)=>{let n=/^\[(.+)\]$/.exec(e.trim());return n?(0,j.jsx)(`div`,{className:`task-feed-tool`,children:n[1]},t):(0,j.jsx)(`div`,{className:`task-feed-msg`,dangerouslySetInnerHTML:OG(e)},t)})})}function SK(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function CK(e){let{task:t,onAck:n}=e,[r,i]=g.useState(!1),a=()=>{i(e=>!e)},[o,s]=g.useState(()=>Date.now());g.useEffect(()=>{if(t.status!==`running`)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[t.status]);let c=t.startedAt?Date.parse(t.startedAt):null,l=t.finishedAt?Date.parse(t.finishedAt):null,u=C.includes(t.status),d=t.status===`done`?100:u?t.progress:Math.min(t.progress,95),f=t.notes.trim()||(t.status===`failed`?t.errorCopy?.trim():void 0)||t.resultSummary?.trim()||``,p=xG(t),m=t.status===`running`?t.phase?.trim()||yG[t.avatar??``]||`Working`:t.status===`waiting`?`Queued`:t.status===`blocked`?`Blocked`:t.status===`done`?`Done`:t.status===`failed`?`Failed`:t.status===`interrupted`?`Interrupted`:t.status;return(0,j.jsx)(`div`,{className:`task${r?` open`:``}`,onClick:a,children:(0,j.jsxs)(`div`,{className:`task-row`,children:[(0,j.jsx)(`div`,{className:`pie`,style:{background:`conic-gradient(#fff ${d*3.6}deg, #333 0deg)`},children:(0,j.jsx)(`div`,{className:`avatar`,style:{background:p.color},children:(0,j.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:p.icon})})}),(0,j.jsxs)(`div`,{className:`task-meta`,children:[(0,j.jsxs)(`div`,{className:`task-head`,children:[(0,j.jsxs)(`div`,{className:`task-text`,children:[(0,j.jsxs)(`div`,{className:`task-name`,children:[(0,j.jsx)(`span`,{className:`tn`,children:t.title}),`: `,m]}),(0,j.jsx)(`div`,{className:`task-sub`,children:t.status===`running`&&c!=null?SK(o-c):u&&c!=null&&l!=null?(0,j.jsxs)(j.Fragment,{children:[`Worked for `,SK(l-c)]}):null})]}),u?(0,j.jsx)(`button`,{className:`task-dismiss`,type:`button`,onClick:e=>{e.stopPropagation(),n(t.id,!1)},children:`Dismiss`}):null]}),(0,j.jsxs)(`div`,{className:`task-body`,children:[r&&t.status===`running`&&e.feed&&e.feed.length>0?(0,j.jsx)(xK,{lines:e.feed}):null,r&&t.status!==`running`&&f?(0,j.jsx)(`div`,{className:`task-notes`,dangerouslySetInnerHTML:OG(f)}):null,r&&t.status===`failed`?(0,j.jsx)(bK,{detail:t.errorDetail}):null,r?(0,j.jsx)(wK,{frames:t.playtestFrames}):null]})]})]})})}function wK(e){let t=e.frames??[];return t.length===0?null:(0,j.jsxs)(`div`,{className:`task-playtest-frames`,children:[(0,j.jsxs)(`div`,{className:`task-playtest-frames-label`,children:[`Playtest frames (`,t.length,`)`]}),(0,j.jsx)(`div`,{className:`task-playtest-frames-row`,children:t.map(e=>(0,j.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:(0,j.jsx)(`img`,{className:`task-playtest-frame`,src:e,alt:`playtest frame`})},e))})]})}function TK(e){return e.filter(e=>!(e.acknowledged&&C.includes(e.status)))}function EK(e){let t=g.useRef(null),n=g.useRef(!0),r=g.useRef(0),[i,a]=g.useState(!1),o=TK(e.tasks);g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.tasks]),g.useEffect(()=>()=>window.clearTimeout(r.current),[]);let s=()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24,a(!0),window.clearTimeout(r.current),r.current=window.setTimeout(()=>a(!1),900))};if(o.length===0)return null;let c=o.filter(e=>C.includes(e.status));return(0,j.jsxs)(`div`,{id:`task-board`,className:`task-stack${i?` scrolling`:``}`,ref:t,onScroll:s,children:[(0,j.jsxs)(`div`,{className:`task-board-header`,children:[(0,j.jsxs)(`div`,{className:`task-board-heading`,children:[(0,j.jsx)(`span`,{className:`task-board-title`,children:`Tasks`}),(0,j.jsxs)(`span`,{className:`task-board-status`,children:[c.length,`/`,o.length,` completed`]})]}),c.length>0?(0,j.jsx)(`button`,{type:`button`,className:`task-clear-completed`,onClick:()=>{for(let t of c)e.onAck(t.id,!1)},children:`Clear completed`}):null]}),o.map(t=>(0,j.jsx)(CK,{task:t,feed:e.feeds[t.id],onAck:e.onAck},t.id))]})}function DK(e){let{msg:t,onPickerSubmit:n,onChip:r,chipsLive:i=!1,interactive:a=!1}=e;if(t.role===`log`)return(0,j.jsx)(`div`,{className:`msg toolline`,children:t.text});if(t.role===`user`)return(0,j.jsxs)(`div`,{className:`msg user`,children:[(t.attachments??[]).map(e=>(0,j.jsx)(`img`,{className:`msg-image`,src:e,alt:``},e)),t.text?(0,j.jsx)(DG,{text:t.text,files:t.files}):null]});let o=t.status===`streaming`,s=hG(t.text,o),c=gG(s)||t.planUpdated===!0;if(!o&&!c)return null;let l=!o&&!t.pickerAnswers&&a,u=-1;s.forEach((e,t)=>{e.kind===`md`&&e.text.trim()!==``&&(u=t)});let d=s.some(e=>e.kind===`ask`||e.kind===`ask-pending`),f=o&&u===-1&&!d,p=!!(t.thinking&&t.thinking.trim());return(0,j.jsxs)(`div`,{className:`assistant-turn`,children:[s.map((e,a)=>{if(e.kind===`ask-pending`)return(0,j.jsx)(_K,{},a);if(e.kind===`chips`)return(0,j.jsx)(gK,{chips:e.chips,interactive:!o&&i,onPick:r},a);if(e.kind===`ask`)return(0,j.jsx)(hK,{spec:e.spec,interactive:l,answers:t.pickerAnswers,onSubmit:(e,r)=>n(t,e,r)},a);if(!e.text.trim())return null;let s=[`msg`,`assistant`,`md`];return o&&a===u&&s.push(`streaming`),t.status===`error`&&s.push(`errbubble`),(0,j.jsx)(`div`,{className:s.join(` `),dangerouslySetInnerHTML:OG(e.text)},a)}),p?(0,j.jsxs)(`details`,{className:`msg-thinking`,children:[(0,j.jsxs)(`summary`,{"aria-label":t.activity??`Thinking`,children:[(0,j.jsx)(`span`,{className:`thinking-caret`,"aria-hidden":`true`}),f?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`span`,{className:`thinking-dots`,"aria-hidden":`true`,children:[(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{})]}),(0,j.jsx)(`span`,{className:`thinking-label`,children:t.activity??`Thinking`})]}):(0,j.jsx)(`span`,{className:`thinking-label`,children:SG(t.thinkingMs)})]}),(0,j.jsx)(`div`,{className:`msg-thinking-body`,dangerouslySetInnerHTML:OG(t.thinking??``)})]}):f?(0,j.jsxs)(`div`,{className:`msg-thinking`,"aria-label":t.activity??`thinking`,children:[(0,j.jsxs)(`span`,{className:`thinking-dots`,"aria-hidden":`true`,children:[(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{})]}),t.activity?(0,j.jsx)(`span`,{className:`thinking-label`,children:t.activity}):null]}):o&&t.activity?(0,j.jsxs)(`div`,{className:`msg-activity`,children:[t.activity,`...`]}):null,o?null:(0,j.jsx)(bK,{detail:t.errorDetail}),t.planUpdated?(0,j.jsx)(wG,{}):null,t.interrupted?(0,j.jsx)(`div`,{className:`msg-interrupted`,children:`interrupted by your next message`}):null]})}function OK(e){let t=g.useRef(null),n=g.useRef(null),r=g.useRef(0),i=g.useRef(!0),a=g.useRef(0);g.useEffect(()=>(GW(i.current),()=>GW(!1)),[]);let[o,s]=g.useState(!1),c=g.useCallback(()=>{let e=t.current;e&&(e.scrollHeight-e.clientHeight-e.scrollTop<=1||(a.current=typeof performance<`u`?performance.now():Date.now(),e.scrollTop=e.scrollHeight))},[]),l=g.useCallback(()=>{c();let e=t.current;e&&e.clientHeight>0&&s(!0)},[c]);g.useLayoutEffect(()=>{if(!i.current)return;l();let e=requestAnimationFrame(l),t=window.setTimeout(l,250),n=window.setTimeout(()=>s(!0),500);return()=>{cancelAnimationFrame(e),clearTimeout(t),clearTimeout(n)}},[e.messages,l]),g.useEffect(()=>{let e=t.current;if(!e)return;let a=new ResizeObserver(()=>{i.current?l():e.scrollTop=e.scrollHeight-e.clientHeight-r.current});return a.observe(e),n.current&&a.observe(n.current,{box:`border-box`}),()=>a.disconnect()},[l]);let u=()=>{let e=t.current;if(!e||(typeof performance<`u`?performance.now():Date.now())-a.current<200)return;r.current=e.scrollHeight-e.scrollTop-e.clientHeight;let n=r.current<48;i.current=n,GW(n)},d=AK(e.messages),f=jK(e.messages);return(0,j.jsx)(`div`,{id:`chat-messages`,className:`chat-scroll`,"data-castle-allow-select":``,ref:t,onScroll:u,children:(0,j.jsxs)(`div`,{className:`chat-thread`+(o?` ready`:``),ref:n,children:[e.messages.length===0?(0,j.jsx)(`div`,{id:`chat-empty`,children:`Tell the agent what you want to make.`}):null,e.messages.map(t=>(0,j.jsx)(DK,{msg:t,interactive:t.id===d,chipsLive:t.id===f,onPickerSubmit:e.onPickerSubmit,onChip:e.onChip},t.id))]})})}function kK(e){return e.role!==`assistant`||e.pickerAnswers?!1:hG(e.text).some(e=>e.kind===`ask`)}function AK(e){for(let t=e.length-1;t>=0;t--)if(kK(e[t]))return e[t].id;return null}function jK(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(n.role===`assistant`){if(n.status===`streaming`)return null;if(hG(n.text).some(e=>e.kind===`chips`))return n.id}}return null}function MK(e,t){for(let n of Array.from(e)){if(!n.type.startsWith(`image/`))continue;let e=new FileReader;e.onload=()=>{typeof e.result==`string`&&t({name:n.name,dataUrl:e.result})},e.readAsDataURL(n)}}function NK(e){return e.pending.length===0?null:(0,j.jsx)(`div`,{id:`chat-pending`,children:e.pending.map((t,n)=>(0,j.jsx)(`img`,{src:t.dataUrl,alt:t.name,title:`remove`,onClick:()=>e.onRemove(n)},`${t.name}-${n}`))})}function PK(e){return e.queued.length===0?null:(0,j.jsx)(`div`,{className:`chat-queue`,onMouseDown:e=>e.preventDefault(),children:e.queued.map((t,n)=>(0,j.jsxs)(`div`,{className:`queue-row`,children:[(0,j.jsx)(`span`,{className:`queue-snippet`,children:t.length>60?`${t.slice(0,60)}\u2026`:t}),(0,j.jsx)(`button`,{className:`queue-send-now`,type:`button`,tabIndex:-1,title:`Send now — interrupts the turn`,onClick:e.onInterrupt,children:`send now`}),(0,j.jsx)(`button`,{className:`queue-remove`,type:`button`,tabIndex:-1,title:`Remove from queue`,onClick:()=>e.onCancelQueued(n),children:`✕`})]},n))})}function FK(e){let{running:t,queued:n}=e,[r,i]=g.useState(``),[a,o]=g.useState(!1),[s,c]=g.useState(!1),l=g.useRef(null),[u,d]=g.useState([]),[f,p]=g.useState(!1);g.useEffect(()=>{t||p(!1)},[t]);let m=g.useRef(null),h=g.useRef(null),_=cG({inputRef:m,anchorRef:h,setValue:i}),v=g.useCallback(()=>{let e=m.current;if(!e)return;e.style.height=`auto`;let t=Number.parseFloat(window.getComputedStyle(e).lineHeight),n=Number.isFinite(t)?Math.ceil(t):21,i=r.length===0?n:Math.min(e.scrollHeight,120);e.style.height=i>0?`${i}px`:``},[r]);g.useLayoutEffect(v,[v]),g.useLayoutEffect(()=>{let e=h.current,t=e?.closest(`.shell-root`)??null;if(!e||!t)return;let n=()=>{t.style.setProperty(`--composer-reserve`,`${e.offsetHeight+7}px`)};n();let r=new ResizeObserver(n);return r.observe(e),()=>{r.disconnect(),t.style.removeProperty(`--composer-reserve`)}},[]);let y=e=>{d(t=>t.length>=6?t:[...t,e])},b=()=>{let t=r.trim();!t&&u.length===0||(e.onSend(t,u,_.attachedIn(t)),i(``),d([]),_.clear())},x=r.trim().length>0||u.length>0,S=e=>{let t=e.target;h.current?.contains(t)&&(t instanceof Element&&t.closest(`.composer-pill, #chat-send`)||m.current?.focus())},C=t&&!x;return(0,j.jsxs)(g.Fragment,{children:[(0,j.jsx)(NK,{pending:u,onRemove:e=>d(t=>t.filter((t,n)=>n!==e))}),_.overlay,(0,j.jsxs)(`div`,{className:`chat-input`,ref:h,children:[(0,j.jsx)(PK,{queued:n,onInterrupt:e.onInterrupt,onCancelQueued:e.onCancelQueued}),(0,j.jsxs)(`div`,{className:`ta`,onClick:S,children:[(0,j.jsx)(`textarea`,{id:`chat-input`,className:`ta-text`,ref:m,rows:1,placeholder:t?`Queue a message…`:`Message the operator`,value:r,onChange:e=>{i(e.target.value),_.sync()},onSelect:_.sync,onPaste:e=>{let t=e.clipboardData?.files;t&&t.length>0&&(e.preventDefault(),MK(t,y))},onKeyDown:e=>{_.handleKeyDown(e)||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),b())}}),(0,j.jsxs)(`div`,{className:`ta-bottom`,onMouseDown:e=>e.preventDefault(),children:[(0,j.jsxs)(`div`,{className:`composer-settings`,children:[(0,j.jsxs)(`button`,{ref:l,className:`composer-pill`+(a?` active`:``)+$G(e.usage),type:`button`,tabIndex:-1,title:`Agent & model settings`,"aria-label":`Agent & model settings`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:()=>{a||e.onRefreshUsage(),o(e=>!e)},children:[(0,j.jsx)(`span`,{className:`composer-pill-label`,children:LG(e.settings)}),jG]}),a?(0,j.jsx)(mK,{settings:e.settings,warnings:e.settingsWarnings,usage:e.usage,accounts:e.accounts,triggerRef:l,onSetSetting:e.onSetSetting,onOpenKeys:()=>c(!0),onRefreshUsage:e.onRefreshUsage,onClose:()=>o(!1)}):null,s?(0,j.jsx)(pK,{accounts:e.accounts,onSave:e.onSetCredential,onRemove:e.onClearCredential,onStartLogin:e.onStartLogin,onSubmitCode:e.onSubmitLoginCode,onCancelLogin:e.onCancelLogin,onLogout:e.onLogout,onClose:()=>c(!1)}):null]}),(0,j.jsx)(`button`,{id:`chat-send`,type:`button`,tabIndex:-1,title:C?f?`Stopping…`:`Stop`:`Send`,disabled:!C&&!x||C&&f,onClick:()=>{C?(p(!0),e.onInterrupt()):b()},children:C?AG:kG})]})]})]})]})}function IK(e){let{agent:t}=e,{messages:n,tasks:r,feeds:i,settings:a,running:o,queued:s}=t,c=(e,n,r)=>{t.submitPicker(e.id,n,r)},l=e=>{t.sendUserMessage(e,[],[])};return(0,j.jsxs)(`div`,{id:`chat-host`,children:[(0,j.jsxs)(`div`,{className:`operator-inset`,children:[(0,j.jsx)(EK,{tasks:r,feeds:i,onAck:t.ackTask}),TK(r).length>0?(0,j.jsx)(`div`,{className:`chat-divider`,"aria-hidden":`true`}):null,(0,j.jsx)(OK,{messages:n,onPickerSubmit:c,onChip:l})]}),(0,j.jsx)(FK,{running:o,queued:s,onSend:t.sendUserMessage,onInterrupt:t.interrupt,onCancelQueued:t.cancelQueued,settings:a,settingsWarnings:t.settingsWarnings,usage:t.usage,accounts:t.accounts,onSetSetting:t.setSetting,onRefreshUsage:t.refreshUsage,onSetCredential:t.setCredential,onClearCredential:t.clearCredential,onStartLogin:t.startLogin,onSubmitLoginCode:t.submitLoginCode,onCancelLogin:t.cancelLogin,onLogout:t.logout})]})}var LK=`castle-flow-layout:`,RK=1;function zK(e,t){if(e)try{let n={version:RK,state:t};localStorage.setItem(LK+e,JSON.stringify(n))}catch{}}function BK(e,t,n){if(!e)return null;try{let r=localStorage.getItem(LK+e);if(!r)return null;let i=JSON.parse(r);if(i.version!==RK||!i.state||!Array.isArray(i.state.groups))return null;let a=rt(UK(i.state,t),n);return a.groups.length===0?null:Ee(a)}catch{return null}}var VK=new Set([`operator`,`files`]);function HK(e){let t=e.codeView;if(t===void 0)return e;let n={...e};return delete n.codeView,t&&(n.view=Ut),n}function UK(e,t){let n=new Set,r=[];for(let i of e.groups){let e=i.tabs.filter(e=>!(e.kind===`editor`&&e.path!==void 0&&!t.has(e.path))).map(HK);if(e.length===0)continue;let a=e.find(e=>e.kind!==`editor`);if(a&&VK.has(a.kind)){if(n.has(a.kind))continue;n.add(a.kind)}let o=i.activeTabId;e.some(e=>e.id===o)||(o=e[0].id),r.push({...i,tabs:e,activeTabId:o})}return{groups:r,activeGroupId:r.some(t=>t.id===e.activeGroupId)?e.activeGroupId:r[0]?.id??null,pinnedGroupId:r.some(t=>t.id===e.pinnedGroupId)?e.pinnedGroupId:null,maximizedGroupId:null}}var WK=g.createContext(null),GK={groups:[],activeGroupId:null,pinnedGroupId:null,maximizedGroupId:null};function KK(e,t){let n=[];if(e.forEach((e,r)=>{let i=t.get(r);if(!i)return;let a=i.getBoundingClientRect(),o=e.left-a.left,s=e.top-a.top;Math.abs(o)<1&&Math.abs(s)<1||(i.style.transition=`none`,i.style.transform=`translate(${o}px, ${s}px)`,n.push(i))}),n.length!==0){n[0].getBoundingClientRect();for(let e of n){e.style.transition=`transform 180ms ease`,e.style.transform=`translate(0px, 0px)`;let t=()=>{e.style.transition=``,e.style.transform=``,e.removeEventListener(`transitionend`,t)};e.addEventListener(`transitionend`,t)}}}function qK(e){return Array.isArray(e.column)}function JK(e){return Array.isArray(e.tabs)}function YK(e){let t=[],n=e=>{JK(e)?t.push(...e.tabs??[]):t.push(e)};for(let t of e)qK(t)?(t.column??[]).forEach(n):n(t);return t}function XK(e){return e===`files`?`files`:e===`playtest`?`play`:e===`terminal`?`terminal`:e===`editor`?`editor`:null}var ZK=[{type:`files`},{type:`playtest`},{type:`editor`,file:`scenes/main.scene`}];function QK(e,t){let n=e&&e.length>0?YK(e):ZK,r=v?null:Ce(`operator`),i=r?[Te([r],_e(r))]:[],a=new Map,o=null;for(let e of n){let n=XK(e.type);if(!n||n===`editor`&&!e.file)continue;if(n===`editor`&&e.file){let n=t(e.file),r=a.get(n);if(r){r.tabs.push(Ce(`editor`,e.file));continue}let s=Ce(`editor`,e.file),c=Te([s],_e(s));a.set(n,c),i.push(c),o||=c.id;continue}let r=Ce(n,e.file);i.push(Te([r],_e(r)))}return{groups:i,activeGroupId:o??i[0]?.id??null,pinnedGroupId:null,maximizedGroupId:null}}function $K(){let e=Oi(),[t,n]=g.useState(()=>ji());return g.useEffect(()=>{if(e)return;let t=window.matchMedia(`(max-width: 768px)`),r=()=>n(t.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}function eq(e){let t=e.target;if(!(t instanceof HTMLIFrameElement)||!t.classList.contains(`deck-frame`))return t;try{let n=t.contentDocument;if(!n)return t;let r=t.getBoundingClientRect();return n.elementFromPoint(e.clientX-r.left,e.clientY-r.top)??t}catch{return t}}function tq(e,t){let n=e,r=!!(n?.ownerDocument&&n.ownerDocument!==t.ownerDocument),i=r?null:t.parentElement;for(;n&&n!==i;){if(n.nodeType===1){let e=getComputedStyle(n).overflowY;if((e===`auto`||e===`scroll`)&&n.scrollHeight>n.clientHeight+1)return!0}if(!r&&n===t)break;n=n.parentElement}return!1}function nq(e,t,n){let r=e,i=t.parentElement;for(;r&&r!==i;){if(r.nodeType===1){let e=getComputedStyle(r),t=e.touchAction;if(t.includes(`pan-y`)&&!t.includes(`pan-x`))return!0;let i=e.overflowX;if(i===`auto`||i===`scroll`){let e=r.scrollWidth-r.clientWidth;if(e>1&&(n>0?r.scrollLeft>1:r.scrollLeft<e-1))return!0}}if(r===t)break;r=r.parentElement}return!1}function rq(e){g.useEffect(()=>{let t=e.current;if(!t)return;let n=e=>{e.deltaY!==0&&(t.scrollWidth<=t.clientWidth||!e.shiftKey&&tq(eq(e),t)||(t.scrollLeft+=e.deltaX-e.deltaY,e.preventDefault()))};return t.addEventListener(`wheel`,n,{passive:!1}),()=>t.removeEventListener(`wheel`,n)},[e])}function iq(e,t,n){g.useLayoutEffect(()=>{let n=e.current,r=n?.querySelector(`.flow-row`);if(!n||!r)return;let i=()=>{let e=r.lastElementChild,i=e?e.offsetLeft+e.offsetWidth:0,a=t&&i>n.clientWidth?n.clientWidth/2:0;r.style.setProperty(`--flow-overscroll`,`${Math.round(a)}px`)};i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e,t,n])}function aq(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(r.left>=n.left-1&&r.right<=n.right+1)return;let i=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;e.scrollTo({left:e.scrollLeft+(r.left+r.width/2-(n.left+n.width/2)),behavior:i?`auto`:`smooth`})}function oq(e,t){let n=g.useRef(new Map),r=g.useCallback(e=>{let t=n.current.get(e);if(t)return t.obj;let r={visible:!1,active:!1,activeCbs:new Set,visibleCbs:new Set,obj:{id:e,isVisible:()=>r.visible,isActive:()=>r.active,onDidActiveChange:e=>(r.activeCbs.add(e),()=>r.activeCbs.delete(e)),onDidVisibilityChange:e=>(r.visibleCbs.add(e),()=>r.visibleCbs.delete(e))}};return n.current.set(e,r),r.obj},[]);return g.useEffect(()=>{let r=new Set;for(let i of e.groups){let a=t?i.id===e.activeGroupId:!0;for(let t of i.tabs){r.add(t.id);let o=n.current.get(t.id);if(!o)continue;let s=i.activeTabId===t.id,c=a&&s,l=i.id===e.activeGroupId&&s;c!==o.visible&&(o.visible=c,o.visibleCbs.forEach(e=>e(c))),l!==o.active&&(o.active=l,o.activeCbs.forEach(e=>e(l)))}}for(let e of n.current.keys())r.has(e)||n.current.delete(e)}),r}function sq({agent:e}){let[t,n]=g.useState(GK),[r,i]=g.useState(null),[a,o]=g.useState(null),s=g.useRef(null),c=g.useRef(!1),l=$K(),u=g.useRef(l);u.current=l;let d=g.useRef(GK),f=g.useRef(null),[p,m]=g.useState(null);d.current=t;let h=g.useRef(new Map),_=t.groups.find(e=>e.tabs.some(e=>e.kind===`operator`))?.id??null,v=g.useRef(_);v.current=_;let[y,b]=g.useState(null),x=g.useRef(null),S=g.useRef(null),C=g.useRef(null),w=g.useRef({page:0,count:0,ids:[]});rq(S),iq(S,!l&&!t.maximizedGroupId,t.groups);let T=oq(t,l);g.useEffect(()=>{let e=!0;Promise.all([en(),ln().catch(()=>[])]).then(([t,r])=>{e&&(s.current=t.deckId,Bt(t),i(t.kitEditorExtensions),o(r),n(BK(t.deckId,new Set(r),Jt)??QK(t.initialPanels,Jt)),c.current=!0)},()=>{e&&(i([]),o([]),n(QK(null,Jt)),c.current=!0)});let t=gA(t=>{t.changes.some(e=>e.event!==`change`)&&ln().then(t=>{e&&o(t)}).catch(()=>{}),t.changes.some(e=>e.path===`castle.json`||e.path.startsWith(`imports/`))&&en().then(t=>{e&&(Bt(t),i(t.kitEditorExtensions))},()=>{})});return()=>{e=!1,t()}},[]),g.useEffect(()=>{if(!c.current)return;let e=window.setTimeout(()=>zK(s.current,t),400);return()=>window.clearTimeout(e)},[t]);let ee=g.useMemo(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId),n=e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0];return n&&n.kind===`editor`?n.path??null:null},[t.groups,t.activeGroupId]),E=g.useRef(null),te=g.useCallback(e=>{if(u.current||d.current.maximizedGroupId)return;let t=S.current,n=h.current.get(e);t&&n&&aq(t,n)},[]),D=g.useCallback((e,t)=>{e&&(E.current=e,t||requestAnimationFrame(()=>{E.current===e&&(E.current=null,te(e))}))},[te]);g.useLayoutEffect(()=>{let e=E.current;e&&(E.current=null,te(e))},[t.groups,t.activeGroupId,t.maximizedGroupId,te]);let ne=g.useCallback(e=>{let t=d.current,r=e(t);r!==t&&n(()=>r),D(r.activeGroupId,r!==t)},[D]),re=g.useCallback((e,t,r)=>{let i=d.current,a=u.current?1:1/0,o=t?Qe(i,t,e,Jt,a,r):Ze(i,e,Jt,a,r);if(o===i)return;let c=ge(o);for(let e of ge(i))c.has(e)||ft(e);nr(s.current,e),n(()=>o),D(o.activeGroupId,!0)},[D]),O=g.useMemo(()=>({openFile:(e,t)=>re(e,void 0,t),openPlaytest:()=>ne(e=>tt(e,`play`)),closeEditor:e=>n(t=>{let n=ke(t,e);return n?Ke(t,n.group.id,n.tab.id):t}),activeEditorPath:ee,kitEditorExts:r,terminalTheme:`dark`}),[r,ee,re,ne]);gi(O);let k=g.useCallback((e,t)=>{let r=d.current,i=r.maximizedGroupId?st({...r,maximizedGroupId:null},e):He(r,e);i!==r&&n(()=>i),t?.reveal&&D(e,i!==r)},[D]),ie=g.useCallback(e=>{let t=Oe(d.current,e);if(t)for(let e of t.tabs)e.kind===`editor`&&e.path&&ft(e.path);n(t=>nt(t,e))},[]),ae=g.useCallback((e,t)=>{let r=Oe(d.current,e)?.tabs.find(e=>e.id===t);r?.kind===`editor`&&r.path&&ft(r.path),n(n=>Ke(n,e,t))},[]),oe=g.useCallback((e,t)=>n(n=>Ue(n,e,t)),[]),se=g.useCallback((e,t,r)=>{n(n=>at(n,e,t,r))},[]),[ce,A]=g.useState(null),le=g.useCallback(e=>A(e),[]),ue=g.useCallback(()=>A(null),[]),de=g.useCallback((e,t)=>re(t,e),[re]),fe=g.useCallback((e,t,r)=>{n(n=>Ye(n,e,t,r))},[]),pe=g.useCallback(e=>n(t=>ot(t,e)),[]),me=g.useCallback(e=>{let t=d.current.maximizedGroupId===e;n(t=>st(t,e)),t&&D(e,!0)},[D]),_e=g.useCallback((e,t,r)=>{n(n=>lt(ct(n,e,t),e,r))},[]);g.useEffect(()=>{if(!l)return;let e=S.current,t=C.current;if(!e||!t)return;let r=0,i=0,a=0,o=1,s=!1,c=!1,u=null,d=e=>t.style.setProperty(`--flow-drag`,`${e}px`),f=t=>{t.touches.length===1&&(r=t.touches[0].clientX,i=t.touches[0].clientY,a=t.timeStamp,u=t.target,o=e.clientWidth||1,s=!1,c=!1)},p=n=>{if(n.touches.length!==1)return;let a=n.touches[0].clientX-r,o=n.touches[0].clientY-i;if(!s){if(Math.abs(a)<8&&Math.abs(o)<8)return;s=!0,c=Math.abs(a)>Math.abs(o)&&!nq(u,e,a),c&&t.classList.add(`flow-dragging`)}if(!c)return;n.preventDefault();let{page:l,count:f}=w.current;d(l===0&&a>0||l===f-1&&a<0?a*.3:a)},m=e=>{if(!c){t.classList.remove(`flow-dragging`);return}c=!1,t.classList.remove(`flow-dragging`);let i=e.changedTouches[0],s=i?i.clientX-r:0,l=e.timeStamp-a,{page:u,count:f,ids:p}=w.current,m=Math.abs(s)>50&&l<250,h=Math.abs(s)>o*.25,g=u;s<0&&(m||h)?g=Math.min(f-1,u+1):s>0&&(m||h)&&(g=Math.max(0,u-1));let _=p[g];g!==u&&_?n(e=>He(e,_)):d(0)};return e.addEventListener(`touchstart`,f,{passive:!0}),e.addEventListener(`touchmove`,p,{passive:!1}),e.addEventListener(`touchend`,m,{passive:!0}),e.addEventListener(`touchcancel`,m,{passive:!0}),()=>{e.removeEventListener(`touchstart`,f),e.removeEventListener(`touchmove`,p),e.removeEventListener(`touchend`,m),e.removeEventListener(`touchcancel`,m)}},[l]);let ve=g.useCallback((e,t)=>{t?h.current.set(e,t):h.current.delete(e),e===v.current&&b(t)},[]);g.useLayoutEffect(()=>{b(_?h.current.get(_)??null:null)},[_]);let ye=aG(e,y),[be,xe]=g.useState(null),Se=g.useRef(null),Ce=g.useRef(!1);g.useLayoutEffect(()=>{let e=Se.current;e&&(Se.current=null,KK(e,h.current))});let we=g.useCallback((e,t)=>{let r=d.current;if(u.current){let n=it(r,e,t),i=r.groups.findIndex(e=>e.id===r.activeGroupId);n.groups.findIndex(e=>e.id===n.activeGroupId)!==i&&(Ce.current=!0)}else{let e=new Map;for(let t of r.groups){let n=h.current.get(t.id)?.getBoundingClientRect();n&&e.set(t.id,n)}Se.current=e}n(n=>it(n,e,t))},[]);g.useEffect(()=>()=>{x.current?.()},[]);let Te=g.useCallback((e,r)=>{if(l||e.button!==0||e.target.closest(`.panel-tab, button`)||!h.current.get(r))return;let i=e.currentTarget,a=e.pointerId;try{i.setPointerCapture(a)}catch{}let o=e.clientX,s=t.groups.findIndex(e=>e.id===r),c=e=>{let n=t.groups.filter(e=>e.id!==r).map(e=>{let t=h.current.get(e.id)?.getBoundingClientRect();return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),i=0;for(;i<n.length&&n[i].center<e;)i+=1;if(i===s)return{target:i,x:null};let a=i<n.length?n[i].left-6:n.length?n[n.length-1].right+6:e;return{target:i,x:a}},u=!1,d=e.clientX,f=0,p=()=>{let e=S.current;if(e&&e.scrollWidth>e.clientWidth+1){let t=e.getBoundingClientRect(),n=0;d<t.left+64?n=-(1-Math.max(0,d-t.left)/64):d>t.right-64&&(n=1-Math.max(0,t.right-d)/64),n!==0&&(e.scrollLeft+=n*24,xe({id:r,x:c(d).x}))}f=requestAnimationFrame(p)},m=e=>{!u&&Math.abs(e.clientX-o)<5||(u||(document.body.classList.add(`flow-reordering`),u=!0,f=requestAnimationFrame(p)),d=e.clientX,xe({id:r,x:c(e.clientX).x}))},g=!1,_=()=>{if(!g){g=!0,i.removeEventListener(`pointermove`,m),i.removeEventListener(`pointerup`,v),i.removeEventListener(`pointercancel`,y),i.removeEventListener(`lostpointercapture`,y);try{i.hasPointerCapture(a)&&i.releasePointerCapture(a)}catch{}f&&cancelAnimationFrame(f),document.body.classList.remove(`flow-reordering`),x.current=null}},v=e=>{let i=u;if(_(),i){let{target:i}=c(e.clientX);if(i!==s){let e=new Map;for(let n of t.groups){let t=h.current.get(n.id)?.getBoundingClientRect();t&&e.set(n.id,t)}Se.current=e,n(e=>it(e,r,i))}}xe(null)},y=()=>{_(),xe(null)};x.current=y,i.addEventListener(`pointermove`,m),i.addEventListener(`pointerup`,v),i.addEventListener(`pointercancel`,y),i.addEventListener(`lostpointercapture`,y)},[l,t.groups]),[Ee,De]=g.useState(null),Ae=g.useCallback(e=>De(t=>t?null:{anchor:e}),[]),je=g.useCallback(()=>{let e=C.current?.querySelector(`.flow-tabs-add`);De({anchor:e?.getBoundingClientRect()??new DOMRect(window.innerWidth/2,48)})},[]);g.useEffect(()=>{let e=(e,t)=>(t&&t!==window?[...document.querySelectorAll(`iframe.deck-frame`)].find(e=>e.contentWindow===t):e)?.closest?.(`.flow-group`)?.getAttribute(`data-group-id`)??null;return jt(`pointermove`,t=>{let n=e(t.target,t.view);f.current=n,!u.current&&m(e=>e===n?e:n)},{passive:!0})},[]);let Me=g.useMemo(()=>yt({getState:()=>d.current,setState:n,spawn:ne,focusGroup:e=>k(e,{reveal:!0}),closeGroup:ie,closeTab:ae,openPath:e=>re(e),openNewGroupPicker:je,getHoveredGroupId:()=>f.current,toggleMaximize:me}),[ne,k,ie,ae,re,je,me]),Ne=Pt(Me),Pe=t.groups.some(e=>e.id===t.activeGroupId)?t.activeGroupId:t.groups[0]?.id??null,Fe=l?null:t.maximizedGroupId,Ie=Math.max(0,t.groups.findIndex(e=>e.id===Pe));w.current={page:Ie,count:t.groups.length,ids:t.groups.map(e=>e.id)},g.useLayoutEffect(()=>{let e=C.current;if(!e)return;let t=Ce.current;t&&e.classList.add(`flow-dragging`),e.style.setProperty(`--flow-page`,String(Ie)),e.style.setProperty(`--flow-drag`,`0px`),t&&(Ce.current=!1,e.offsetHeight,requestAnimationFrame(()=>e.classList.remove(`flow-dragging`)))},[Ie,l]),Wn(C),Kn(()=>ce?(A(null),!0):Ee?(De(null),!0):!1);let Le=ce?Oe(t,ce):null,Re=Le?.tabs.find(e=>e.id===Le.activeTabId)??Le?.tabs[0],ze=Re&&Re.kind===`editor`?Re.path??``:``;return(0,j.jsx)(mi,{value:O,children:(0,j.jsx)(WK.Provider,{value:e,children:(0,j.jsxs)(`div`,{ref:C,className:`flow-root${l?` is-mobile`:``}${Fe?` is-maximized`:``}`,children:[(0,j.jsx)(cq,{state:t,activeId:Pe,operatorBadge:ye,onFocusGroup:k,onReorderGroup:we,onNewGroup:Ae}),(0,j.jsx)(`div`,{className:`flow-scroller`,ref:S,children:(0,j.jsx)(`div`,{className:`flow-field`,children:(0,j.jsx)(`div`,{className:`flow-row`,children:t.groups.map(e=>(0,j.jsx)(uq,{group:e,active:e.id===Pe,mobile:l,pinned:e.id===t.pinnedGroupId&&!Fe,maximized:e.id===Fe,hidden:Fe!==null&&e.id!==Fe,dragging:be?.id===e.id,hovered:e.id===p,getLifecycle:T,registerEl:ve,onFocusGroup:k,onClose:ie,onActivateTab:oe,onCloseTab:ae,onReorderTab:se,onOpenMobileSwitch:le,onOpenInGroup:de,onSetTabView:fe,onTogglePin:pe,onToggleMaximize:me,onStartDrag:Te,onResize:_e},e.id))})})}),be&&be.x!==null&&(()=>{let e=S.current?.getBoundingClientRect(),t=h.current.get(be.id)?.getBoundingClientRect();if(!e||!t)return null;let n=Math.max(t.top,e.top+12+36),r=Math.min(t.bottom,e.bottom)-n;return r<=0?null:(0,j.jsx)(`div`,{className:`flow-drop-indicator`,style:{left:be.x,top:n,height:r}})})(),Ee&&(0,j.jsx)(bq,{anchor:Ee.anchor,files:a??[],onOpenFile:e=>re(e),onSpawnPanel:e=>ne(t=>tt(t,e)),onSpawnClass:e=>ne(t=>$e(t,e,Jt)),onClose:()=>De(null)}),ce&&(0,j.jsx)(wi,{groupId:ce,groupClass:he(Le,Jt),currentFile:ze,files:a,recent:ir(s.current),view:Re?.view,onSetView:e=>{ce&&Re&&fe(ce,Re.id,e)},onOpen:(e,t)=>re(e,t),onClose:ue}),(0,j.jsx)(Zn,{openFile:e=>re(e),openPanel:e=>ne(t=>tt(t,e===`playtest`?`play`:e)),panels:vq,getCommands:Me}),Ne?(0,j.jsxs)(`div`,{className:`chord-hint`,role:`status`,children:[(0,j.jsx)(`kbd`,{children:Ne}),(0,j.jsx)(`span`,{children:`waiting for the next key…`})]}):null]})})})}function cq(e){let{state:t,activeId:n,operatorBadge:r,onFocusGroup:i,onReorderGroup:a,onNewGroup:o}=e,s=Jn(),[c,l]=g.useState(!1),u=s?.title?.trim()||`Untitled deck`;Vn(u,r),Hn(r);let d=s?.visibility===`public`?yr:s?.visibility===`unlisted`?_r:vr,f=s?.saving??`idle`,p=s?.saveError??null,m=s?.draftAutosaveState??null,h=m===`starting`||m===`saving`?`Saving draft…`:m===`dirty`?`Unsaved changes`:m===`error`?`Draft save failed`:m===`saved`?`Draft saved`:null,[_,v]=g.useState(null),y=g.useRef(!1);g.useEffect(()=>{_!==null&&(f===`working`&&(y.current=!0),f===`done`&&y.current&&v(`done`),p&&y.current&&v(`failed`))},[f,p,_]);let b=g.useCallback(()=>{y.current=!1,v(`pushing`),zn(`push`)},[]);return(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`flow-topbar`,children:[(0,j.jsxs)(`div`,{className:`flow-topbar-leading`,children:[Oi()?null:(0,j.jsxs)(`div`,{className:`flow-castle-wrap`,children:[(0,j.jsx)(`button`,{type:`button`,className:`dock-control dock-control-icon dock-control-mark`,title:`Menu`,"aria-haspopup":`menu`,"aria-expanded":c,onClick:()=>l(e=>!e),children:Tr}),c&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-menu-backdrop`,onClick:()=>l(!1)}),(0,j.jsxs)(`div`,{className:`menu flow-castle-menu`,role:`menu`,children:[(0,j.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{l(!1),zn(`back-to-decks`)},children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:xr}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:`Back to decks`})]}),(0,j.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{l(!1),zn(`new-deck`)},children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:pr}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:`New deck`})]}),(0,j.jsx)(`div`,{className:`menu-separator flow-menu-narrow`}),(0,j.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,onClick:()=>{l(!1),zn(`open-settings`)},children:(0,j.jsx)(`span`,{className:`menu-item-label`,children:`Deck settings`})}),(0,j.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,disabled:f===`working`,onClick:()=>{l(!1),b()},children:(0,j.jsx)(`span`,{className:`menu-item-label`,children:f===`working`?`Pushing…`:p?`Push failed — retry`:f===`done`?`Pushed ✓`:`Push to Castle`})})]})]})]}),(0,j.jsxs)(`button`,{type:`button`,className:`dock-control dock-control-quiet flow-deck-identity`,title:`Deck settings`,onClick:()=>zn(`open-settings`),children:[(0,j.jsx)(`span`,{className:`flow-deck-vis`,children:d}),(0,j.jsx)(`span`,{className:`flow-deck-name`,children:u}),(0,j.jsx)(`span`,{className:`flow-deck-caret`,children:Sr})]}),h?(0,j.jsx)(`span`,{className:`flow-draft-status${m===`error`?` is-error`:``}`,role:`status`,children:h}):null]}),(0,j.jsxs)(`div`,{className:`flow-tabs-wrap`,children:[(0,j.jsx)(Xr,{groups:t.groups,activeId:n,operatorBadge:r,onFocusGroup:i,onReorderGroup:a}),(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet flow-tabs-add flow-picker-trigger`,title:`New group`,"aria-label":`New group`,onClick:e=>o(e.currentTarget.getBoundingClientRect()),children:pr})]}),(0,j.jsx)(`div`,{className:`flow-topbar-trailing`,children:(0,j.jsxs)(`button`,{type:`button`,className:`dock-control flow-preview-btn${p?` flow-preview-btn-failed`:``}`,title:p??`Publish this deck to your Castle account (sandbox edits stay local until pushed)`,disabled:f===`working`,onClick:()=>zn(`push`),children:[br,(0,j.jsxs)(`span`,{className:`flow-preview-label`,children:[(0,j.jsx)(`span`,{className:`flow-preview-label-sizer`,"aria-hidden":`true`,children:`Push to Castle`}),(0,j.jsx)(`span`,{children:f===`working`?`Pushing…`:p?`Push failed`:f===`done`?`Pushed ✓`:`Push to Castle`})]})]})})]}),_!==null&&(0,j.jsx)(`div`,{className:`flow-push-modal-backdrop`,children:(0,j.jsx)(`div`,{className:`flow-push-modal`,role:`dialog`,"aria-modal":`true`,children:_===`failed`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-check flow-push-check-failed`,children:`!`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Push failed`}),(0,j.jsx)(`div`,{className:`flow-push-sub`,children:p}),(0,j.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>v(null),children:`Dismiss`})]}):_===`done`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-check`,children:`✓`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Pushed to Castle`}),s?.shareUrl?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Your deck is live at`}),(0,j.jsx)(`a`,{className:`flow-push-url`,href:s.shareUrl,target:`_blank`,rel:`noreferrer`,children:s.shareUrl.replace(/^https?:\/\//,``)})]}):(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Saved to your Castle account.`}),(0,j.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>v(null),children:`Done`})]}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-spinner`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Pushing to Castle…`}),(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Publishing your latest changes.`})]})})})]})}function lq(e,t){e.currentTarget.blur(),t()}var uq=g.memo(function(e){let{group:t,active:n,mobile:r,pinned:i,maximized:a,hidden:o,dragging:s,hovered:c,getLifecycle:l,registerEl:u}=e,{onFocusGroup:d,onClose:f}=e,p=me(t),m=xq(t,e.onResize),[h,_]=g.useState(()=>p&&t.tabs.every(pe)),v=g.useCallback(()=>_(e=>!e),[]),y=r?void 0:a?{flex:`1 1 auto`}:{flex:`0 0 auto`,width:t.w,height:t.h},b=p?null:t.tabs[0],x=(0,j.jsx)(`button`,{type:`button`,className:r?`button button-icon button-icon-large button-quiet`:`button button-icon button-quiet`,title:`Close`,"aria-label":`Close`,onClick:e=>lq(e,()=>f(t.id)),children:mr}),S=n=>{n.target.closest(`button`)||a||e.onStartDrag(n,t.id)},C=n&&!r&&!a;return(0,j.jsxs)(`div`,{ref:e=>u(t.id,e),"data-group-id":t.id,className:`panel flow-group${C?` is-active`:``}${i?` pinned`:``}${a?` maximized`:``}${o?` hidden`:``}${s?` is-dragging`:``}${c?` is-hover`:``}${p?` is-editor`:``}`,style:y,onMouseDown:()=>d(t.id),children:[p?(0,j.jsx)(Gr,{group:t,mobile:r,pinned:i,maximized:a,onStartDrag:e.onStartDrag,onActivateTab:e.onActivateTab,onCloseTab:e.onCloseTab,onCloseGroup:f,onReorderTab:e.onReorderTab,onTogglePin:e.onTogglePin,onToggleMaximize:e.onToggleMaximize,onOpenMobileSwitch:e.onOpenMobileSwitch,onSetTabView:e.onSetTabView,drawerOpen:h,onToggleDrawer:v}):r?(0,j.jsxs)(`div`,{className:`panel-header flow-tabstrip flow-tabstrip-mobile`,onPointerDown:S,children:[(0,j.jsx)(`div`,{className:`flow-mobile-strip-left`}),(0,j.jsxs)(`div`,{className:`panel-mobile-current`,children:[(0,j.jsx)(`span`,{className:`flow-tab-icon`,children:b&&fr(b.kind,b.path)}),(0,j.jsx)(`span`,{className:`panel-mobile-current-label`,children:b?.label})]}),(0,j.jsx)(`div`,{className:`panel-header-actions flow-mobile-strip-right`,children:x})]}):(0,j.jsxs)(`div`,{className:`panel-header flow-tabstrip`,onPointerDown:S,children:[(0,j.jsxs)(`div`,{className:`panel-title`,children:[(0,j.jsx)(`span`,{className:`flow-tab-icon`,children:b&&fr(b.kind,b.path)}),(0,j.jsx)(`span`,{children:b?.label})]}),(0,j.jsxs)(`div`,{className:`panel-header-actions`,children:[!a&&(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:i?`Unpin`:`Pin to left`,"aria-label":i?`Unpin`:`Pin to left`,"aria-pressed":i,onClick:n=>lq(n,()=>e.onTogglePin(t.id)),children:gr}),(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:a?`Restore`:`Maximize`,"aria-label":a?`Restore`:`Maximize`,"aria-pressed":a,onClick:n=>lq(n,()=>e.onToggleMaximize(t.id)),children:a?wr:Cr}),x]})]}),(0,j.jsx)(`div`,{className:`flow-panel-body`,children:t.tabs.map(n=>(0,j.jsx)(`div`,{className:`flow-tab-body${n.id===t.activeTabId?``:` inactive`}`,children:(0,j.jsx)(dq,{tab:n,groupId:t.id,lifecycle:l(n.id),onOpenInGroup:e.onOpenInGroup,onSetTabView:e.onSetTabView,drawerOpen:h&&!r})},n.id))}),!r&&!a&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-resize-e`,onPointerDown:m(`x`),title:`Drag to resize width`}),(0,j.jsx)(`div`,{className:`flow-resize-s`,onPointerDown:m(`y`),title:`Drag to resize height`}),(0,j.jsx)(`div`,{className:`flow-resize-se`,onPointerDown:m(`xy`),title:`Drag to resize`})]})]})}),dq=g.memo(function(e){let{tab:t,groupId:n,lifecycle:r,onOpenInGroup:i,onSetTabView:a,drawerOpen:o}=e;if(t.kind===`editor`&&pe(t))return(0,j.jsxs)(`div`,{className:`flow-empty-editor`,children:[o?(0,j.jsx)(eH,{currentFile:``,filterClass:t.classHint,onOpen:e=>i(n,e)}):null,(0,j.jsx)(`div`,{className:`flow-empty-editor-msg`,children:`Open a file`})]});switch(t.kind){case`editor`:return(0,j.jsx)(WV,{file:t.path,editorClass:t.view,lifecycle:r,hideContextBar:!0,drawerOpen:o,drawer:(0,j.jsx)(eH,{currentFile:t.path??``,filterClass:t.path?Jt(t.path):void 0,onOpen:e=>i(n,e),view:t.view,onSetView:e=>a(n,t.id,e)})});case`play`:return(0,j.jsx)(QV,{lifecycle:r});case`terminal`:return(0,j.jsx)($V,{lifecycle:r});case`files`:return(0,j.jsx)(nU,{lifecycle:r});case`operator`:return(0,j.jsx)(fq,{});default:return(0,j.jsx)(pq,{tab:t})}});function fq(){let e=g.useContext(WK);return e?(0,j.jsx)(`div`,{className:`shell-root docked flow-operator-host`,style:{"--operator-col":`100%`},children:(0,j.jsx)(IK,{agent:e})}):(0,j.jsx)(`div`,{className:`flow-placeholder`,children:`operator unavailable`})}function pq(e){let{tab:t}=e;return(0,j.jsxs)(`div`,{className:`flow-placeholder kind-${t.kind}`,children:[(0,j.jsx)(`div`,{className:`flow-placeholder-icon`,children:fr(t.kind,t.path)}),(0,j.jsx)(`div`,{className:`flow-placeholder-label`,children:t.label}),(0,j.jsx)(`div`,{className:`flow-placeholder-kind`,children:t.path??t.kind})]})}function mq(e,t){g.useEffect(()=>{let n=n=>{n.target.closest(e)||t()},r=window.setTimeout(()=>document.addEventListener(`mousedown`,n),0);return()=>{window.clearTimeout(r),document.removeEventListener(`mousedown`,n)}},[e,t])}function hq(e,t){return Math.max(8,Math.min(e,window.innerWidth-t-8))}var gq=300,_q=[...v?[]:[{kind:`operator`,label:`Operator`}],{kind:`play`,label:`Play`},...v?[]:[{kind:`terminal`,label:`Terminal`}],{kind:`files`,label:`Files`}],vq=_q.map(({kind:e,label:t})=>({kind:e===`play`?`playtest`:e,label:t}));function yq(e,t){let n=t.trim().toLowerCase(),r=_q.filter(e=>e.label.toLowerCase().includes(n)).map(e=>({kind:`panel`,panel:e.kind,label:e.label})),i=new Set;for(let t of e)i.add(Jt(t));let a=[...i].map(e=>{let t=Yt(e);return{kind:`class`,classId:e,label:t.label,icon:t.icon}}).filter(e=>e.label.toLowerCase().includes(n)).sort((e,t)=>e.label.localeCompare(t.label)),o=e.filter(e=>e.toLowerCase().includes(n)).slice(0,40).map(e=>({kind:`file`,path:e}));return[...r,...a,...o]}function bq(e){let{anchor:t,files:n,onOpenFile:r,onSpawnPanel:i,onSpawnClass:a,onClose:o}=e,[s,c]=g.useState(``),[l,u]=g.useState(0);mq(`.flow-picker, .flow-picker-trigger`,o);let d=yq(n,s),f=Math.min(l,Math.max(0,d.length-1)),p=e=>{e.kind===`panel`?i(e.panel):e.kind===`class`?a(e.classId):r(e.path),o()};return(0,It.createPortal)((0,j.jsxs)(`div`,{className:`menu flow-picker`,style:{top:t.bottom+4,left:hq(t.left,gq),width:gq},onMouseDown:e=>e.stopPropagation(),children:[(0,j.jsx)(`input`,{className:`flow-picker-input`,autoFocus:!0,placeholder:`Open a file or panel…`,value:s,onChange:e=>{c(e.target.value),u(0)},onKeyDown:e=>{e.key===`Escape`?o():e.key===`ArrowDown`?(e.preventDefault(),u(e=>Math.min(e+1,d.length-1))):e.key===`ArrowUp`?(e.preventDefault(),u(e=>Math.max(e-1,0))):e.key===`Enter`&&d[f]&&p(d[f])}}),(0,j.jsxs)(`div`,{className:`flow-picker-list`,children:[d.length===0&&(0,j.jsx)(`div`,{className:`flow-picker-empty`,children:`No matches`}),d.map((e,t)=>(0,j.jsxs)(`button`,{type:`button`,className:`menu-item${t===f?` is-hover`:``}`,onMouseEnter:()=>u(t),onClick:()=>p(e),children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:e.kind===`panel`?fr(e.panel):e.kind===`class`?lr(e.icon):fr(`editor`,e.path)}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:e.kind===`panel`||e.kind===`class`?e.label:e.path})]},e.kind===`panel`?`p:${e.panel}`:e.kind===`class`?`c:${e.classId}`:`f:${e.path}`))]})]}),document.body)}function xq(e,t){return g.useCallback(n=>r=>{r.preventDefault(),r.stopPropagation();let i=r.clientX,a=r.clientY,o=e.w,s=e.h,c=r.currentTarget;c.setPointerCapture(r.pointerId);let l=!1,u=r=>{let c=r.clientX-i,u=r.clientY-a;if(!l&&Math.abs(c)<5&&Math.abs(u)<5)return;l=!0;let d=n===`y`?o:Math.max(200,o+c),f=n===`x`?s:Math.max(160,s+u);t(e.id,d,f)},d=()=>{c.removeEventListener(`pointermove`,u),c.removeEventListener(`pointerup`,d)};c.addEventListener(`pointermove`,u),c.addEventListener(`pointerup`,d)},[e.id,e.w,e.h,t])}function Sq(){let e=oe(),t=g.useRef(0);return qn(()=>{let n=Date.now();n-t.current<1e3||(t.current=n,e.refreshUsage())}),(0,j.jsx)(sq,{agent:e})}var Cq=document.getElementById(`root`);if(!Cq)throw Error(`Missing #root`);dH(),dj(),(0,_.createRoot)(Cq).render((0,j.jsx)(Sq,{}));
|
|
443
|
+
`),chips:n}}function JW(e,t){let n=[],r=e.map((r,i)=>{if(r.kind!==`md`)return r;let a=qW(r.text,t&&i===e.length-1);for(let e of a.chips)n.includes(e)||n.push(e);return{kind:`md`,text:a.prose}});return n.length>0&&r.push({kind:`chips`,chips:n}),r}function YW(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||!Array.isArray(t.questions))return null;let n=[];return t.questions.forEach((e,t)=>{let r=e;if(!r||typeof r.q!=`string`||!Array.isArray(r.options))return;let i=r.options.filter(e=>typeof e==`string`&&e.trim()!==``);if(i.length===0)return;let a=typeof r.id==`string`&&r.id.trim()?r.id.trim():`q${t}`;n.push({id:a,q:r.q,options:i,multi:r.multi===!0})}),n.length===0?null:{questions:n}}function XW(e,t=!1){let n=!1;if((e.split("```").length-1)%2==1){let t=e.lastIndexOf("```"),r=e.slice(t+3),i=r.indexOf(`
|
|
444
|
+
`),a=(i===-1?r:r.slice(0,i)).trim();i===-1?a===``?e=e.slice(0,t):`ask`.startsWith(a)&&(e=e.slice(0,t),n=!0):a===`ask`&&(e=e.slice(0,t),n=!0)}let r=[],i=0,a;for(GW.lastIndex=0;(a=GW.exec(e))!==null;){let t=YW(a[1]);t&&(a.index>i&&r.push({kind:`md`,text:e.slice(i,a.index)}),r.push({kind:`ask`,spec:t}),i=a.index+a[0].length)}return i<e.length&&r.push({kind:`md`,text:e.slice(i)}),r.length===0&&!n&&r.push({kind:`md`,text:e}),n&&r.push({kind:`ask-pending`}),JW(r,t)}function ZW(e){return e.some(e=>e.kind===`ask`||e.kind===`ask-pending`||e.kind===`chips`||e.kind===`md`&&e.text.trim()!==``)}function QW(e,t){let n=[];for(let r of e.questions){let e=(t[r.id]??[]).filter(e=>r.options.includes(e));e.length!==0&&n.push(`- ${r.q} \u2192 ${e.join(`, `)}`)}return n.length?`Here's what I picked:\n${n.join(`
|
|
445
|
+
`)}`:``}var $W={thinking:(0,j.jsx)(M,{name:`lightbulb`}),reading:(0,j.jsx)(M,{name:`book`}),building:(0,j.jsx)(M,{name:`hammer`}),painting:(0,j.jsx)(M,{name:`pencil`}),playing:(0,j.jsx)(M,{name:`gamepad`})},eG={thinking:`Thinking`,reading:`Reading files`,building:`Editing logic`,painting:`Editing art`,playing:`Playtesting`},tG={thinking:`#FFC826`,reading:`#FFC826`,building:`#FFEB57`,painting:`#FFEB57`,playing:`#D3FC7E`};function nG(e){if(e.status===`done`)return{icon:(0,j.jsx)(M,{name:`check`}),color:`#5AC54F`};if(e.status===`failed`)return{icon:(0,j.jsx)(M,{name:`times`}),color:`#F5545D`};if(e.status===`interrupted`)return{icon:(0,j.jsx)(M,{name:`stop`}),color:`#B4B4B4`};if(e.status===`blocked`)return{icon:(0,j.jsx)(M,{name:`stop`}),color:`#F5A623`};let t=e.avatar&&$W[e.avatar]?e.avatar:`thinking`;return{icon:$W[t],color:tG[t]}}function rG(e){let t=Math.max(1,Math.round((e??0)/1e3));if(t<60)return`Thought for ${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`Thought for ${n}m`:`Thought for ${n}m ${r}s`}var iG=`plan.md`;function aG(){let e=hi();return(0,j.jsxs)(`button`,{type:`button`,className:`msg-plan`,title:`Open ${iG}`,onClick:()=>e.openFile(iG),children:[iG,` updated`]})}function oG(e){let t=hi();return(0,j.jsxs)(`button`,{type:`button`,className:`msg-file`,title:`Open ${e.path}`,onClick:()=>t.openFile(e.path),children:[`@`,e.path]})}function sG(e,t){if(t.length===0)return[e];let n=[...t].sort((e,t)=>t.length-e.length).map(e=>({path:e,token:`@${e}`})),r=[],i=``;for(let t=0;t<e.length;){let a=n.find(n=>e.startsWith(n.token,t));if(!a){i+=e[t],t+=1;continue}i&&r.push(i),i=``,r.push({path:a.path}),t+=a.token.length}return i&&r.push(i),r}function cG(e){return(0,j.jsx)(`span`,{children:sG(e.text,e.files??[]).map((e,t)=>typeof e==`string`?e:(0,j.jsx)(oG,{path:e.path},`${e.path}-${t}`))})}function lG(e){try{return{__html:BW.parse(e,{breaks:!0,async:!1})}}catch{return{__html:``}}}var uG=(0,j.jsx)(M,{name:`send`}),dG=(0,j.jsx)(M,{name:`stop`}),fG=(0,j.jsx)(M,{name:`chevron-down`,className:`mode-caret`}),pG=[{value:`claude`,label:`Claude`},{value:`cursor`,label:`Cursor`},{value:`smith`,label:`Smith`}],mG=[{value:`opus`,label:`Opus`},{value:`sonnet`,label:`Sonnet`},{value:`fable`,label:`Fable`},{value:`openrouter`,label:`OpenRouter`}];function hG(e,t){return e===`smith`||e===`claude`&&t===`openrouter`}function gG(e){if(!e||!e.trim())return null;let t=e.trim(),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function _G(e,t,n){let r=pG.find(t=>t.value===e)?.label??e??`?`;if(e===`claude`){if(t===`openrouter`){let e=gG(n);return e?`${r} (${e})`:`${r} (OpenRouter)`}let e=mG.find(e=>e.value===t)?.label??t;return e?`${r} (${e})`:r}if(e===`smith`){let e=gG(n);return e?`${r} (${e})`:r}return r}function vG(e){return`${_G(e.router,e.routerClaudeModel,e.routerOpenrouterModel)} → ${_G(e.tasks,e.tasksClaudeModel,e.tasksOpenrouterModel)}`}var yG=`/__castle/agent/model-caps`,bG=[{value:`balanced`,label:`Balanced`},{value:`nitro`,label:`Nitro`},{value:`exacto`,label:`Exacto`},{value:`floor`,label:`Floor`}],xG=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],SG={none:`None`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`XHigh`,max:`Max`};function CG(e){let t=e?.reasoningEfforts;if(!t||t.length===0)return null;let n=new Set(t);return xG.filter(e=>n.has(e)).map(e=>({value:e,label:SG[e]??e}))}var wG={openai:`OpenAI`,azure:`Azure`,anthropic:`Anthropic`,google:`Google`,"google-vertex":`Vertex`,deepinfra:`DeepInfra`,fireworks:`Fireworks`,together:`Together`,groq:`Groq`,cerebras:`Cerebras`,baseten:`Baseten`},TG={flex:`Flex`,priority:`Priority`,standard:`Standard`,eu:`EU`};function EG(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}function DG(e){let[t,n]=e.split(`/`),r=wG[t]??EG(t);return n?`${r} ${TG[n]??EG(n)}`:r}function OG(e){let t=e?.providerTiers;return!t||t.length<2?null:[{value:``,label:`Auto`},...t.map(e=>({value:e,label:DG(e)}))]}function kG(e,t,n,r,i){let a=e===`router`,o=a?`routerClaudeModel`:`tasksClaudeModel`,s=a?`routerOpenrouterModel`:`tasksOpenrouterModel`,c=[{type:`enum`,key:e,label:a?`Operator`:`Tasks`,options:pG},{type:`enum`,key:o,label:`Model`,options:mG.filter(e=>!r.includes(e.value)),showWhen:t=>t[e]===`claude`,note:i&&t[o]===`openrouter`?`Pick Opus, Sonnet, or Fable to use your Anthropic credentials`:void 0},{type:`text`,key:s,label:`OpenRouter model`,placeholder:a?`openai/gpt-5.6-sol`:`openai/gpt-5.6-terra`,showWhen:t=>hG(t[e],t[o])}];if(t[e]===`smith`){let e=CG(n);e&&c.push({type:`select`,key:a?`routerReasoningEffort`:`tasksReasoningEffort`,label:`Reasoning`,options:e}),c.push({type:`select`,key:a?`routerRouting`:`tasksRouting`,label:`Routing`,options:bG});let t=OG(n);t&&c.push({type:`select`,key:a?`routerProviderTier`:`tasksProviderTier`,label:`Provider`,options:t})}return c}function AG(e){let{label:t,placeholder:n,value:r,warning:i,onCommit:a}=e,[o,s]=g.useState(r);g.useEffect(()=>s(r),[r]);let c=g.useRef(o),l=g.useRef(r),u=g.useRef(a);c.current=o,l.current=r,u.current=a;let d=()=>{let e=c.current.trim();return e&&e!==l.current?(u.current(e),!0):!1},f=()=>{d()||s(l.current)};g.useEffect(()=>()=>{d()},[]);let p=e=>{s(e),a(e)};return(0,j.jsxs)(`div`,{className:`settings-row settings-row-stack`,children:[(0,j.jsxs)(`div`,{className:`settings-row-main`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:t}),(0,j.jsx)(`input`,{type:`text`,className:`settings-text${i?` settings-text-warn`:``}`,value:o,placeholder:n,onChange:e=>s(e.target.value),onBlur:f,onKeyDown:e=>{e.key===`Enter`&&(f(),e.target.blur())}})]}),i?(0,j.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,i.message,i.suggestion?(0,j.jsxs)(j.Fragment,{children:[` `,`Did you mean`,` `,(0,j.jsx)(`button`,{type:`button`,className:`settings-warning-suggest`,onMouseDown:e=>{e.preventDefault(),p(i.suggestion)},children:i.suggestion}),`?`]}):null]}):null]})}function jG(e,t,n){let r=e?.[t];if(!(!r||!n||r.model!==n))return{message:r.message,suggestion:r.suggestion}}function MG(e){if(!e||e.limitMicros===null||e.limitMicros<=0)return null;if(e.blocked)return 1;if(e.credits?.plan===`daily`&&e.credits.dailyFreeRemainingCredits!==null){let t=e.credits.dailyFreeRemainingCredits*1e4;return t<=0?1:Math.min(1,Math.max(0,e.usedMicros/(e.usedMicros+t)))}return Math.min(1,e.usedMicros/e.limitMicros)}function NG(e){let t=e?.autoReload;return!t?.enabled||t.disabledReason||t.thresholdCredits===null||t.amountCredits===null?null:{thresholdCredits:t.thresholdCredits,amountCredits:t.amountCredits}}function PG(e){if(e?.blocked)return` usage-blocked`;if(e?.credits?.plan===`credits`)return e.credits.lowBalance&&!NG(e.credits)?` usage-warn`:``;let t=MG(e);return t===null?``:t>=.8?` usage-warn`:``}var FG=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`});function IG(e){return FG.format(e/100)}function LG(e){return IG(e/1e4)}function RG(e,t,n=!1){if(!t||t.displayUnit===`usd`||t.usdPerCredit<=0)return LG(e);let r=Math.round(e/1e6/t.usdPerCredit),i=r.toLocaleString();return n?`${i} ${r===1?`credit`:`credits`}`:`${i} AI ${r===1?`credit`:`credits`}`}function zG(e){return e.resetAtMs?new Date(e.resetAtMs).toLocaleTimeString([],{hour:`numeric`,minute:`2-digit`}):``}function BG(e){let{usage:t}=e,n=MG(t);if(n===null)return null;let r=zG(t),i=t.credits?.plan===`daily`?t.credits.purchasedCredits+t.credits.grantedCredits:0,a=i>0?` + ${IG(i)} credits`:``;return(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:`Daily AI usage`}),(0,j.jsx)(`span`,{className:`settings-usage-text`,children:(t.blocked?`Limit reached`:`${Math.round(n*100)}%${r?` \u00b7 resets ${r}`:``}`)+a})]}),(0,j.jsx)(`div`,{className:`settings-usage-bar`,children:(0,j.jsx)(`div`,{className:`settings-usage-fill`+(t.blocked?` blocked`:``),style:{width:`${n*100}%`}})})]})}function VG(e){let{usage:t}=e;if(t.spendableMicros===null)return null;let n=zG(t),r=t.credits?.nextGrantAt?new Date(t.credits.nextGrantAt).toLocaleDateString():null,i=t.credits?.autoReload,a=NG(t.credits),o=t.creditsExhausted&&i?.disabledReason?`Auto-reload is paused`:t.credits?.lowBalance&&!t.creditsExhausted&&!t.blocked?a?`Auto-reload adds ${RG(a.amountCredits*1e4,t.credits.rates,!0)} when you drop below ${RG(a.thresholdCredits*1e4,t.credits.rates,!0)}`:i?.enabled&&i.disabledReason?`Auto-reload is paused`:`Running low on credits`:null,s=`${RG(t.spendableMicros,t.credits?.rates,!0)} left`;return t.blocked&&(s=`Daily limit reached${n?` · resets ${n}`:``}`),t.creditsExhausted&&(s=`${RG(0,t.credits?.rates,!0)} left`),(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:`AI credits`}),(0,j.jsx)(`span`,{className:`settings-usage-text`,children:s})]}),o?(0,j.jsx)(`div`,{className:`settings-usage-subtext`,children:o}):null,r?(0,j.jsxs)(`div`,{className:`settings-usage-subtext`,children:[`refreshes `,r]}):null]})}function HG(e){return e.usage.credits?.plan===`credits`?(0,j.jsx)(VG,{usage:e.usage}):(0,j.jsx)(BG,{usage:e.usage})}function UG(e){if(window.ReactNativeWebView){window.ReactNativeWebView.postMessage(JSON.stringify({type:`castle-open-credits`}));return}if(!window.open(`https://castle.xyz/credits`,`_blank`))return;WG?.();let t=()=>{document.visibilityState===`visible`&&(WG?.(),e())};WG=()=>{document.removeEventListener(`visibilitychange`,t),WG=null},document.addEventListener(`visibilitychange`,t)}var WG=null;function GG(e){let{label:t=`Get more credits`,onReturn:n}=e;return(0,j.jsx)(`button`,{type:`button`,className:`settings-account-open`,onClick:()=>UG(n),children:t})}function KG(e){return(0,j.jsx)(`button`,{type:`button`,className:`settings-account-open`,onClick:e.onOpen,children:e.anyStored?`Manage your account`:`Use your own account`})}function qG(e){let{login:t}=e,[n,r]=g.useState(``),i=()=>{n.trim()&&e.onSubmitCode(n.trim())};return(0,j.jsxs)(j.Fragment,{children:[t.url?(0,j.jsxs)(`div`,{className:`castle-key-login`,children:[(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Open this link to sign in, then come back here.`}),(0,j.jsx)(`a`,{className:`castle-key-url`,href:t.url,target:`_blank`,rel:`noreferrer noopener`,children:t.url})]}):(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Starting sign-in…`}),t.phase===`awaiting-code`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Paste the code the browser shows you:`}),(0,j.jsx)(`input`,{className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,value:n,placeholder:`code`,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i()}}),t.message?(0,j.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null]}):null,t.phase===`verifying`?(0,j.jsx)(`div`,{className:`castle-key-stored`,children:`Finishing sign-in…`}):null,t.phase===`error`?(0,j.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null,(0,j.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,j.jsx)(`button`,{type:`button`,onClick:e.onCancel,children:t.phase===`error`?`Close`:`Cancel`}),t.phase===`awaiting-code`?(0,j.jsx)(`button`,{type:`button`,onClick:i,disabled:!n.trim(),children:`Submit`}):null]})]})}function JG(e){let t=e.accounts.providers,n=e.accounts.login,[r,i]=g.useState(()=>(t.find(e=>e.key?.present||e.login?.loggedIn)??t[0])?.id??``),[a,o]=g.useState(``),[s,c]=g.useState(null),l=(n?t.find(e=>e.login?.provider===n.provider):null)??t.find(e=>e.id===r)??t[0]??null,u=g.useRef(e.onClose);u.current=e.onClose;let d=n!==null;g.useEffect(()=>{let e=e=>{e.key===`Escape`&&!d&&u.current()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[d]);let f=g.useRef(null);if(g.useEffect(()=>{if(n){f.current=n.provider;return}let e=f.current;e!==null&&(f.current=null,t.find(t=>t.login?.provider===e)?.login?.loggedIn&&u.current())}),!l)return null;let p=!!l.login?.loggedIn,m=!!l.key?.present,h=p||m,_=()=>{let t=a.trim();if(t){if(t.length>500){c(`That key is too long.`);return}if([...t].some(e=>{let t=e.codePointAt(0)??0;return t<32||t===127})){c(`That key contains invalid characters.`);return}e.onSave(l.id,t),e.onClose()}};return(0,It.createPortal)((0,j.jsx)(`div`,{className:`castle-modal-scrim`,onMouseDown:n?void 0:e.onClose,children:(0,j.jsxs)(`div`,{className:`castle-modal`,onMouseDown:e=>e.stopPropagation(),children:[(0,j.jsx)(`div`,{className:`castle-key-heading`,children:n?`Sign in to ${l.label}`:`Your account`}),n?null:(0,j.jsx)(`div`,{className:`castle-key-subtitle`,children:`Run the operator on your own account and bypass Castle's daily limit.`}),t.length>1&&!n?(0,j.jsx)(`div`,{className:`castle-key-tabs`,children:t.map(e=>(0,j.jsx)(`button`,{type:`button`,className:`castle-key-tab`+(e.id===l.id?` active`:``),onClick:()=>{i(e.id),o(``),c(null)},children:e.label},e.id))}):null,n?(0,j.jsx)(qG,{login:n,onSubmitCode:e.onSubmitCode,onCancel:e.onCancelLogin}):(0,j.jsxs)(j.Fragment,{children:[h?(0,j.jsxs)(j.Fragment,{children:[p?(0,j.jsxs)(`div`,{className:`castle-key-row`,children:[(0,j.jsxs)(`span`,{children:[`Signed in with your `,l.label,` account.`]}),(0,j.jsx)(`button`,{type:`button`,onClick:()=>{e.onLogout(l.id),e.onClose()},children:`Sign out`})]}):null,m?(0,j.jsxs)(`div`,{className:`castle-key-row`,children:[(0,j.jsxs)(`span`,{children:[`API key saved (`,l.key?.hint,`).`]}),(0,j.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemove(l.id),e.onClose()},children:`Remove`})]}):null]}):(0,j.jsxs)(j.Fragment,{children:[l.login?(0,j.jsxs)(`button`,{type:`button`,className:`castle-key-signin`,onClick:()=>e.onStartLogin(l.id),children:[`Sign in with your `,l.label,` account`]}):null,l.login&&l.key?(0,j.jsx)(`div`,{className:`castle-key-or`,children:`or`}):null,l.key?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`castle-key-field-label`,children:`Add API key`}),(0,j.jsx)(`input`,{type:`password`,className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,"data-1p-ignore":!0,"data-lpignore":`true`,value:a,placeholder:l.key.placeholder,onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&_()}}),s?(0,j.jsx)(`div`,{className:`castle-key-error`,children:s}):null]}):null]}),(0,j.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,j.jsx)(`button`,{type:`button`,onClick:e.onClose,children:`Cancel`}),!h&&l.key?(0,j.jsx)(`button`,{type:`button`,onClick:_,disabled:!a.trim(),children:`Save`}):null]})]})]})}),document.body)}function YG(e){let{settings:t,onSetSetting:n,onClose:r}=e,i=e.usage?.credits?.plan===`credits`?e.usage.spendableMicros!==null:MG(e.usage)!==null,a=e.accounts.providers.some(e=>e.key?.present||e.login?.loggedIn),o=e.accounts.providers.some(e=>e.id===`anthropic`&&(e.key?.present||e.login?.loggedIn)),s=e.accounts.providers.length>0&&(i||a),c=e.usage?.credits?.plan===`credits`?e.usage.credits:null,l=c?e.usage?.creditsExhausted?`Get more credits`:e.usage?.blocked||!c.lowBalance?null:c.autoReload.disabledReason?`Update your card`:NG(c)?null:`Set up auto-reload`:null,u=g.useRef(null),[d,f]=g.useState({}),p=t.routerOpenrouterModel?.trim()??``,m=t.tasksOpenrouterModel?.trim()??``,h=t.router===`smith`,_=t.tasks===`smith`;g.useEffect(()=>{let e=new Set;h&&p&&e.add(p),_&&m&&e.add(m);let t=!1;for(let n of e)fetch(`${yG}?model=${encodeURIComponent(n)}`).then(e=>e.ok?e.json():null).then(e=>{!t&&e&&f(t=>({...t,[n]:e}))}).catch(()=>{});return()=>{t=!0}},[h,p,_,m]);let v=e.usage?.blockedClaudeModels??[],y=[kG(`router`,t,d[p],v,o),kG(`tasks`,t,d[m],v,o)];return Pr(u,r,e.triggerRef),(0,It.createPortal)((0,j.jsxs)(`div`,{className:`settings-popover`,ref:u,style:Rr(u,e.triggerRef,[t,d,i,s,l,e.usage,o]),onMouseDown:e=>e.stopPropagation(),children:[i||s||l?(0,j.jsxs)(`div`,{className:`settings-group`,children:[i&&e.usage?(0,j.jsx)(HG,{usage:e.usage}):null,l?(0,j.jsxs)(`div`,{className:`settings-usage-actions`,children:[s?(0,j.jsx)(KG,{anyStored:a,onOpen:e.onOpenKeys}):null,(0,j.jsx)(GG,{label:l,onReturn:e.onRefreshUsage})]}):s?(0,j.jsx)(KG,{anyStored:a,onOpen:e.onOpenKeys}):null]}):null,y.map((r,i)=>(0,j.jsx)(`div`,{className:`settings-group`,children:r.filter(e=>!e.showWhen||e.showWhen(t)).map(r=>{if(r.type===`text`)return(0,j.jsx)(AG,{label:r.label,placeholder:r.placeholder,value:t[r.key]??``,warning:jG(e.warnings,r.key,t[r.key]),onCommit:e=>n(r.key,e)},r.key);if(r.type===`select`)return(0,j.jsxs)(`div`,{className:`settings-row`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:r.label}),(0,j.jsx)(`select`,{className:`settings-select`,value:t[r.key]??``,onChange:e=>n(r.key,e.target.value),children:r.options.map(e=>(0,j.jsx)(`option`,{value:e.value,children:e.label},e.value))})]},r.key);let i=t[r.key];return(0,j.jsxs)(`div`,{className:`settings-row settings-row-stack`,children:[(0,j.jsxs)(`div`,{className:`settings-row-main`,children:[(0,j.jsx)(`span`,{className:`settings-label`,children:r.label}),(0,j.jsx)(`div`,{className:`settings-seg`,children:r.options.map(e=>(0,j.jsx)(`button`,{type:`button`,tabIndex:-1,className:`settings-opt`+(i===e.value?` active`:``),onClick:()=>n(r.key,e.value),children:e.label},e.value))})]}),r.note?(0,j.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,r.note]}):null]},r.key)})},i))]}),document.body)}function XG(e){let{spec:t,interactive:n,answers:r,onSubmit:i}=e,[a,o]=g.useState({}),s=n?a:r??{},c=(e,t,r)=>{n&&o(n=>{let i=n[e]??[];if(r){let r=i.includes(t)?i.filter(e=>e!==t):[...i,t];return{...n,[e]:r}}return{...n,[e]:i[0]===t?[]:[t]}})};return(0,j.jsxs)(`div`,{className:`picker${n?``:` picker-locked`}`,children:[t.questions.map(e=>(0,j.jsxs)(`fieldset`,{className:`picker-q`,disabled:!n,children:[(0,j.jsx)(`legend`,{className:`picker-q-label`,children:e.q}),(0,j.jsx)(`div`,{className:`picker-options`,children:e.options.map(t=>{let r=(s[e.id]??[]).includes(t);return(0,j.jsxs)(`label`,{className:`picker-option${r?` is-checked`:``}`,children:[(0,j.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:r,disabled:!n,onChange:()=>c(e.id,t,e.multi)}),(0,j.jsx)(`span`,{children:t})]},t)})})]},e.id)),n?(0,j.jsx)(`div`,{className:`picker-actions`,children:(0,j.jsx)(`button`,{className:`picker-submit`,type:`button`,onClick:()=>{let e=QW(t,a);e&&i(a,e)},children:`Submit`})}):null]})}function ZG(e){let{chips:t,interactive:n,onPick:r}=e,[i,a]=g.useState(null),o=n&&i===null;return(0,j.jsx)(`div`,{className:`chips`+(o?``:` chips-inert`),children:t.map(e=>(0,j.jsx)(`button`,{type:`button`,className:`chip`+(i===e?` is-picked`:``),disabled:!o,onClick:()=>{a(e),r(e)},children:e},e))})}function QG(){return(0,j.jsxs)(`div`,{className:`picker picker-skeleton`,"aria-hidden":`true`,children:[(0,j.jsx)(`span`,{className:`picker-skeleton-hint`,children:`preparing options…`}),(0,j.jsxs)(`div`,{className:`picker-q`,children:[(0,j.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-label`}),(0,j.jsxs)(`div`,{className:`picker-options`,children:[(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:84}}),(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:116}}),(0,j.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:72}})]})]})]})}function $G(e){let t=/^\[Editing (.+)\]$/,n=/^\[Reading (.+)\]$/,r=new Set;for(let n of e){let e=t.exec(n.trim());if(e)for(let t of e[1].split(`, `))r.add(t)}let i=[];for(let t of e){let e=n.exec(t.trim());if(e){let t=e[1].split(`, `).filter(e=>!r.has(e));if(t.length===0)continue;i.push(`[Reading ${t.join(`, `)}]`);continue}i.push(t)}return i}function eK(e){let t=/^\[([A-Za-z]+)\s+(.+)\]$/,n=[];for(let r of e){let e=t.exec(r.trim());if(e){let r=n.length?t.exec(n[n.length-1].trim()):null;if(r&&r[1]===e[1]){r[2].split(`, `).includes(e[2])||(n[n.length-1]=`[${e[1]} ${r[2]}, ${e[2]}]`);continue}}n.push(r)}return n}function tK(e){return e.detail?(0,j.jsxs)(`details`,{className:`msg-error-detail`,children:[(0,j.jsx)(`summary`,{children:`Details (full text in the browser console)`}),(0,j.jsx)(`pre`,{children:e.detail})]}):null}function nK(e){let t=g.useRef(null),n=g.useRef(!0);return g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.lines]),(0,j.jsx)(`div`,{className:`task-feed`,ref:t,onScroll:()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},onClick:e=>e.stopPropagation(),children:eK($G(e.lines)).map((e,t)=>{let n=/^\[(.+)\]$/.exec(e.trim());return n?(0,j.jsx)(`div`,{className:`task-feed-tool`,children:n[1]},t):(0,j.jsx)(`div`,{className:`task-feed-msg`,dangerouslySetInnerHTML:lG(e)},t)})})}function rK(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function iK(e){let{task:t,onAck:n}=e,[r,i]=g.useState(!1),a=()=>{i(e=>!e)},[o,s]=g.useState(()=>Date.now());g.useEffect(()=>{if(t.status!==`running`)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[t.status]);let c=t.startedAt?Date.parse(t.startedAt):null,l=t.finishedAt?Date.parse(t.finishedAt):null,u=C.includes(t.status),d=t.status===`done`?100:u?t.progress:Math.min(t.progress,95),f=t.notes.trim()||(t.status===`failed`?t.errorCopy?.trim():void 0)||t.resultSummary?.trim()||``,p=nG(t),m=t.status===`running`?t.phase?.trim()||eG[t.avatar??``]||`Working`:t.status===`waiting`?`Queued`:t.status===`blocked`?`Blocked`:t.status===`done`?`Done`:t.status===`failed`?`Failed`:t.status===`interrupted`?`Interrupted`:t.status;return(0,j.jsx)(`div`,{className:`task${r?` open`:``}`,onClick:a,children:(0,j.jsxs)(`div`,{className:`task-row`,children:[(0,j.jsx)(`div`,{className:`pie`,style:{background:`conic-gradient(#fff ${d*3.6}deg, #333 0deg)`},children:(0,j.jsx)(`div`,{className:`avatar`,style:{background:p.color},children:(0,j.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:p.icon})})}),(0,j.jsxs)(`div`,{className:`task-meta`,children:[(0,j.jsxs)(`div`,{className:`task-head`,children:[(0,j.jsxs)(`div`,{className:`task-text`,children:[(0,j.jsxs)(`div`,{className:`task-name`,children:[(0,j.jsx)(`span`,{className:`tn`,children:t.title}),`: `,m]}),(0,j.jsx)(`div`,{className:`task-sub`,children:t.status===`running`&&c!=null?rK(o-c):u&&c!=null&&l!=null?(0,j.jsxs)(j.Fragment,{children:[`Worked for `,rK(l-c)]}):null})]}),u?(0,j.jsx)(`button`,{className:`task-dismiss`,type:`button`,onClick:e=>{e.stopPropagation(),n(t.id,!1)},children:`Dismiss`}):null]}),(0,j.jsxs)(`div`,{className:`task-body`,children:[r&&t.status===`running`&&e.feed&&e.feed.length>0?(0,j.jsx)(nK,{lines:e.feed}):null,r&&t.status!==`running`&&f?(0,j.jsx)(`div`,{className:`task-notes`,dangerouslySetInnerHTML:lG(f)}):null,r&&t.status===`failed`?(0,j.jsx)(tK,{detail:t.errorDetail}):null,r?(0,j.jsx)(aK,{frames:t.playtestFrames}):null]})]})]})})}function aK(e){let t=e.frames??[];return t.length===0?null:(0,j.jsxs)(`div`,{className:`task-playtest-frames`,children:[(0,j.jsxs)(`div`,{className:`task-playtest-frames-label`,children:[`Playtest frames (`,t.length,`)`]}),(0,j.jsx)(`div`,{className:`task-playtest-frames-row`,children:t.map(e=>(0,j.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:(0,j.jsx)(`img`,{className:`task-playtest-frame`,src:e,alt:`playtest frame`})},e))})]})}function oK(e){return e.filter(e=>!(e.acknowledged&&C.includes(e.status)))}function sK(e){let t=g.useRef(null),n=g.useRef(!0),r=g.useRef(0),[i,a]=g.useState(!1),o=oK(e.tasks);g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.tasks]),g.useEffect(()=>()=>window.clearTimeout(r.current),[]);let s=()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24,a(!0),window.clearTimeout(r.current),r.current=window.setTimeout(()=>a(!1),900))};if(o.length===0)return null;let c=o.filter(e=>C.includes(e.status));return(0,j.jsxs)(`div`,{id:`task-board`,className:`task-stack${i?` scrolling`:``}`,ref:t,onScroll:s,children:[(0,j.jsxs)(`div`,{className:`task-board-header`,children:[(0,j.jsxs)(`div`,{className:`task-board-heading`,children:[(0,j.jsx)(`span`,{className:`task-board-title`,children:`Tasks`}),(0,j.jsxs)(`span`,{className:`task-board-status`,children:[c.length,`/`,o.length,` completed`]})]}),c.length>0?(0,j.jsx)(`button`,{type:`button`,className:`task-clear-completed`,onClick:()=>{for(let t of c)e.onAck(t.id,!1)},children:`Clear completed`}):null]}),o.map(t=>(0,j.jsx)(iK,{task:t,feed:e.feeds[t.id],onAck:e.onAck},t.id))]})}function cK(e){let{msg:t,onPickerSubmit:n,onChip:r,chipsLive:i=!1,interactive:a=!1}=e;if(t.role===`log`)return(0,j.jsx)(`div`,{className:`msg toolline`,children:t.text});if(t.role===`user`)return(0,j.jsxs)(`div`,{className:`msg user`,children:[(t.attachments??[]).map(e=>(0,j.jsx)(`img`,{className:`msg-image`,src:e,alt:``},e)),t.text?(0,j.jsx)(cG,{text:t.text,files:t.files}):null]});let o=t.status===`streaming`,s=XW(t.text,o),c=ZW(s)||t.planUpdated===!0;if(!o&&!c)return null;let l=!o&&!t.pickerAnswers&&a,u=-1;s.forEach((e,t)=>{e.kind===`md`&&e.text.trim()!==``&&(u=t)});let d=s.some(e=>e.kind===`ask`||e.kind===`ask-pending`),f=o&&u===-1&&!d,p=!!(t.thinking&&t.thinking.trim());return(0,j.jsxs)(`div`,{className:`assistant-turn`,children:[s.map((e,a)=>{if(e.kind===`ask-pending`)return(0,j.jsx)(QG,{},a);if(e.kind===`chips`)return(0,j.jsx)(ZG,{chips:e.chips,interactive:!o&&i,onPick:r},a);if(e.kind===`ask`)return(0,j.jsx)(XG,{spec:e.spec,interactive:l,answers:t.pickerAnswers,onSubmit:(e,r)=>n(t,e,r)},a);if(!e.text.trim())return null;let s=[`msg`,`assistant`,`md`];return o&&a===u&&s.push(`streaming`),t.status===`error`&&s.push(`errbubble`),(0,j.jsx)(`div`,{className:s.join(` `),dangerouslySetInnerHTML:lG(e.text)},a)}),p?(0,j.jsxs)(`details`,{className:`msg-thinking`,children:[(0,j.jsxs)(`summary`,{"aria-label":t.activity??`Thinking`,children:[(0,j.jsx)(`span`,{className:`thinking-caret`,"aria-hidden":`true`}),f?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`span`,{className:`thinking-dots`,"aria-hidden":`true`,children:[(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{})]}),(0,j.jsx)(`span`,{className:`thinking-label`,children:t.activity??`Thinking`})]}):(0,j.jsx)(`span`,{className:`thinking-label`,children:rG(t.thinkingMs)})]}),(0,j.jsx)(`div`,{className:`msg-thinking-body`,dangerouslySetInnerHTML:lG(t.thinking??``)})]}):f?(0,j.jsxs)(`div`,{className:`msg-thinking`,"aria-label":t.activity??`thinking`,children:[(0,j.jsxs)(`span`,{className:`thinking-dots`,"aria-hidden":`true`,children:[(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{}),(0,j.jsx)(`i`,{})]}),t.activity?(0,j.jsx)(`span`,{className:`thinking-label`,children:t.activity}):null]}):o&&t.activity?(0,j.jsxs)(`div`,{className:`msg-activity`,children:[t.activity,`...`]}):null,o?null:(0,j.jsx)(tK,{detail:t.errorDetail}),t.planUpdated?(0,j.jsx)(aG,{}):null,t.interrupted?(0,j.jsx)(`div`,{className:`msg-interrupted`,children:`interrupted by your next message`}):null]})}function lK(e){let t=g.useRef(null),n=g.useRef(null),r=g.useRef(0),i=g.useRef(!0),a=g.useRef(0),[o,s]=g.useState(!1),c=g.useCallback(()=>{let e=t.current;e&&(e.scrollHeight-e.clientHeight-e.scrollTop<=1||(a.current=typeof performance<`u`?performance.now():Date.now(),e.scrollTop=e.scrollHeight))},[]),l=g.useCallback(()=>{c();let e=t.current;e&&e.clientHeight>0&&s(!0)},[c]);g.useLayoutEffect(()=>{if(!i.current)return;l();let e=requestAnimationFrame(l),t=window.setTimeout(l,250),n=window.setTimeout(()=>s(!0),500);return()=>{cancelAnimationFrame(e),clearTimeout(t),clearTimeout(n)}},[e.messages,l]),g.useEffect(()=>{let e=t.current;if(!e)return;let a=new ResizeObserver(()=>{i.current?l():e.scrollTop=e.scrollHeight-e.clientHeight-r.current});return a.observe(e),n.current&&a.observe(n.current,{box:`border-box`}),()=>a.disconnect()},[l]);let u=()=>{let e=t.current;e&&((typeof performance<`u`?performance.now():Date.now())-a.current<200||(r.current=e.scrollHeight-e.scrollTop-e.clientHeight,i.current=r.current<48))},d=dK(e.messages),f=fK(e.messages);return(0,j.jsx)(`div`,{id:`chat-messages`,className:`chat-scroll`,"data-castle-allow-select":``,ref:t,onScroll:u,children:(0,j.jsxs)(`div`,{className:`chat-thread`+(o?` ready`:``),ref:n,children:[e.messages.length===0?(0,j.jsx)(`div`,{id:`chat-empty`,children:`Tell the agent what you want to make.`}):null,e.messages.map(t=>(0,j.jsx)(cK,{msg:t,interactive:t.id===d,chipsLive:t.id===f,onPickerSubmit:e.onPickerSubmit,onChip:e.onChip},t.id))]})})}function uK(e){return e.role!==`assistant`||e.pickerAnswers?!1:XW(e.text).some(e=>e.kind===`ask`)}function dK(e){for(let t=e.length-1;t>=0;t--)if(uK(e[t]))return e[t].id;return null}function fK(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(n.role===`assistant`){if(n.status===`streaming`)return null;if(XW(n.text).some(e=>e.kind===`chips`))return n.id}}return null}function pK(e,t){for(let n of Array.from(e)){if(!n.type.startsWith(`image/`))continue;let e=new FileReader;e.onload=()=>{typeof e.result==`string`&&t({name:n.name,dataUrl:e.result})},e.readAsDataURL(n)}}function mK(e){return e.pending.length===0?null:(0,j.jsx)(`div`,{id:`chat-pending`,children:e.pending.map((t,n)=>(0,j.jsx)(`img`,{src:t.dataUrl,alt:t.name,title:`remove`,onClick:()=>e.onRemove(n)},`${t.name}-${n}`))})}function hK(e){return e.queued.length===0?null:(0,j.jsx)(`div`,{className:`chat-queue`,onMouseDown:e=>e.preventDefault(),children:e.queued.map((t,n)=>(0,j.jsxs)(`div`,{className:`queue-row`,children:[(0,j.jsx)(`span`,{className:`queue-snippet`,children:t.length>60?`${t.slice(0,60)}\u2026`:t}),(0,j.jsx)(`button`,{className:`queue-send-now`,type:`button`,tabIndex:-1,title:`Send now — interrupts the turn`,onClick:e.onInterrupt,children:`send now`}),(0,j.jsx)(`button`,{className:`queue-remove`,type:`button`,tabIndex:-1,title:`Remove from queue`,onClick:()=>e.onCancelQueued(n),children:`✕`})]},n))})}function gK(e){let{running:t,queued:n}=e,[r,i]=g.useState(``),[a,o]=g.useState(!1),[s,c]=g.useState(!1),l=g.useRef(null),[u,d]=g.useState([]),[f,p]=g.useState(!1);g.useEffect(()=>{t||p(!1)},[t]);let m=g.useRef(null),h=g.useRef(null),_=UW({inputRef:m,anchorRef:h,setValue:i}),v=g.useCallback(()=>{let e=m.current;if(!e)return;e.style.height=`auto`;let t=Number.parseFloat(window.getComputedStyle(e).lineHeight),n=Number.isFinite(t)?Math.ceil(t):21,i=r.length===0?n:Math.min(e.scrollHeight,120);e.style.height=i>0?`${i}px`:``},[r]);g.useLayoutEffect(v,[v]),g.useLayoutEffect(()=>{let e=h.current,t=e?.closest(`.shell-root`)??null;if(!e||!t)return;let n=()=>{t.style.setProperty(`--composer-reserve`,`${e.offsetHeight+7}px`)};n();let r=new ResizeObserver(n);return r.observe(e),()=>{r.disconnect(),t.style.removeProperty(`--composer-reserve`)}},[]);let y=e=>{d(t=>t.length>=6?t:[...t,e])},b=()=>{let t=r.trim();!t&&u.length===0||(e.onSend(t,u,_.attachedIn(t)),i(``),d([]),_.clear())},x=r.trim().length>0||u.length>0,S=e=>{let t=e.target;h.current?.contains(t)&&(t instanceof Element&&t.closest(`.composer-pill, #chat-send`)||m.current?.focus())},C=t&&!x;return(0,j.jsxs)(g.Fragment,{children:[(0,j.jsx)(mK,{pending:u,onRemove:e=>d(t=>t.filter((t,n)=>n!==e))}),_.overlay,(0,j.jsxs)(`div`,{className:`chat-input`,ref:h,children:[(0,j.jsx)(hK,{queued:n,onInterrupt:e.onInterrupt,onCancelQueued:e.onCancelQueued}),(0,j.jsxs)(`div`,{className:`ta`,onClick:S,children:[(0,j.jsx)(`textarea`,{id:`chat-input`,className:`ta-text`,ref:m,rows:1,placeholder:t?`Queue a message…`:`Message the operator`,value:r,onChange:e=>{i(e.target.value),_.sync()},onSelect:_.sync,onPaste:e=>{let t=e.clipboardData?.files;t&&t.length>0&&(e.preventDefault(),pK(t,y))},onKeyDown:e=>{_.handleKeyDown(e)||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),b())}}),(0,j.jsxs)(`div`,{className:`ta-bottom`,onMouseDown:e=>e.preventDefault(),children:[(0,j.jsxs)(`div`,{className:`composer-settings`,children:[(0,j.jsxs)(`button`,{ref:l,className:`composer-pill`+(a?` active`:``)+PG(e.usage),type:`button`,tabIndex:-1,title:`Agent & model settings`,"aria-label":`Agent & model settings`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:()=>{a||e.onRefreshUsage(),o(e=>!e)},children:[(0,j.jsx)(`span`,{className:`composer-pill-label`,children:vG(e.settings)}),fG]}),a?(0,j.jsx)(YG,{settings:e.settings,warnings:e.settingsWarnings,usage:e.usage,accounts:e.accounts,triggerRef:l,onSetSetting:e.onSetSetting,onOpenKeys:()=>c(!0),onRefreshUsage:e.onRefreshUsage,onClose:()=>o(!1)}):null,s?(0,j.jsx)(JG,{accounts:e.accounts,onSave:e.onSetCredential,onRemove:e.onClearCredential,onStartLogin:e.onStartLogin,onSubmitCode:e.onSubmitLoginCode,onCancelLogin:e.onCancelLogin,onLogout:e.onLogout,onClose:()=>c(!1)}):null]}),(0,j.jsx)(`button`,{id:`chat-send`,type:`button`,tabIndex:-1,title:C?f?`Stopping…`:`Stop`:`Send`,disabled:!C&&!x||C&&f,onClick:()=>{C?(p(!0),e.onInterrupt()):b()},children:C?dG:uG})]})]})]})]})}function _K(e){let{agent:t}=e,{messages:n,tasks:r,feeds:i,settings:a,running:o,queued:s}=t,c=(e,n,r)=>{t.submitPicker(e.id,n,r)},l=e=>{t.sendUserMessage(e,[],[])};return(0,j.jsxs)(`div`,{id:`chat-host`,children:[(0,j.jsxs)(`div`,{className:`operator-inset`,children:[(0,j.jsx)(sK,{tasks:r,feeds:i,onAck:t.ackTask}),oK(r).length>0?(0,j.jsx)(`div`,{className:`chat-divider`,"aria-hidden":`true`}):null,(0,j.jsx)(lK,{messages:n,onPickerSubmit:c,onChip:l})]}),(0,j.jsx)(gK,{running:o,queued:s,onSend:t.sendUserMessage,onInterrupt:t.interrupt,onCancelQueued:t.cancelQueued,settings:a,settingsWarnings:t.settingsWarnings,usage:t.usage,accounts:t.accounts,onSetSetting:t.setSetting,onRefreshUsage:t.refreshUsage,onSetCredential:t.setCredential,onClearCredential:t.clearCredential,onStartLogin:t.startLogin,onSubmitLoginCode:t.submitLoginCode,onCancelLogin:t.cancelLogin,onLogout:t.logout})]})}var vK=`castle-operator-seen-v1`,yK=`castle-operator-seen-v2`;function bK(){try{let e=localStorage.getItem(yK);if(e!==null){let t=JSON.parse(e);if(t&&typeof t==`object`){let e=t,n=e.taskIds;return{messageId:typeof e.messageId==`string`?e.messageId:void 0,taskIds:Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:void 0}}}let t=localStorage.getItem(vK);if(t!==null)return{messageId:t,taskIds:void 0}}catch{}return{messageId:void 0,taskIds:void 0}}function xK(e,t){try{localStorage.setItem(yK,JSON.stringify({messageId:e,taskIds:t}))}catch{}}function SK(e){let t=[];for(let n of e)n.role===`assistant`&&n.status!==`streaming`&&t.push(n.id);return t}function CK(e){let t=SK(e);return t[t.length-1]??``}function wK(e){let t=[];for(let n of e)C.includes(n.status)&&!n.acknowledged&&t.push(n.id);return t}function TK(e,t){if(t===void 0)return 0;let n=SK(e);if(t===``)return n.length;let r=n.indexOf(t);return r<0?0:n.length-r-1}function EK(e,t){if(t===void 0)return 0;let n=new Set(t),r=0;for(let t of e)n.has(t)||(r+=1);return r}function DK(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function OK(e,t,n,r){let i=CK(t),a=wK(n);if(e)return{messageId:i,taskIds:a};let o=SK(t);return r.messageId===void 0?t.length===0?r:{messageId:i,taskIds:a}:r.messageId!==``&&o.length>0&&!o.includes(r.messageId)?{messageId:i,taskIds:r.taskIds}:r.taskIds===void 0?{messageId:r.messageId,taskIds:a}:r}function kK(){let[e,t]=g.useState(()=>document.visibilityState===`visible`);return g.useEffect(()=>{let e=()=>t(document.visibilityState===`visible`);return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),e}function AK(e){let t=e.boundingClientRect;if(t.width<=0||t.height<=0)return!1;let n=e.intersectionRect;return n.width>=t.width-1&&n.height>=t.height-1}var jK=Array.from({length:21},(e,t)=>t/20);function MK(e){let[t,n]=g.useState(!1);return g.useEffect(()=>{if(!e){n(!1);return}let t=new IntersectionObserver(([e])=>n(e?AK(e):!1),{threshold:jK});return t.observe(e),()=>t.disconnect()},[e]),t}function NK(e,t,n){let r=kK(),i=MK(n),a=r&&(t||i),[o,s]=g.useState(bK);g.useEffect(()=>{let t=OK(a,e.messages,e.tasks,o);t.messageId===o.messageId&&DK(t.taskIds,o.taskIds)||(t.messageId!==void 0&&t.taskIds!==void 0&&xK(t.messageId,t.taskIds),s(t))},[a,e.messages,e.tasks,o]);let c=wK(e.tasks),l=a?{messageId:CK(e.messages),taskIds:c}:o;return TK(e.messages,l.messageId)+EK(c,l.taskIds)}var PK=`castle-flow-layout:`,FK=1;function IK(e,t){if(e)try{let n={version:FK,state:t};localStorage.setItem(PK+e,JSON.stringify(n))}catch{}}function LK(e,t,n){if(!e)return null;try{let r=localStorage.getItem(PK+e);if(!r)return null;let i=JSON.parse(r);if(i.version!==FK||!i.state||!Array.isArray(i.state.groups))return null;let a=rt(BK(i.state,t),n);return a.groups.length===0?null:Ee(a)}catch{return null}}var RK=new Set([`operator`,`files`]);function zK(e){let t=e.codeView;if(t===void 0)return e;let n={...e};return delete n.codeView,t&&(n.view=Ut),n}function BK(e,t){let n=new Set,r=[];for(let i of e.groups){let e=i.tabs.filter(e=>!(e.kind===`editor`&&e.path!==void 0&&!t.has(e.path))).map(zK);if(e.length===0)continue;let a=e.find(e=>e.kind!==`editor`);if(a&&RK.has(a.kind)){if(n.has(a.kind))continue;n.add(a.kind)}let o=i.activeTabId;e.some(e=>e.id===o)||(o=e[0].id),r.push({...i,tabs:e,activeTabId:o})}return{groups:r,activeGroupId:r.some(t=>t.id===e.activeGroupId)?e.activeGroupId:r[0]?.id??null,pinnedGroupId:r.some(t=>t.id===e.pinnedGroupId)?e.pinnedGroupId:null,maximizedGroupId:null}}var VK=g.createContext(null),HK={groups:[],activeGroupId:null,pinnedGroupId:null,maximizedGroupId:null};function UK(e,t){let n=[];if(e.forEach((e,r)=>{let i=t.get(r);if(!i)return;let a=i.getBoundingClientRect(),o=e.left-a.left,s=e.top-a.top;Math.abs(o)<1&&Math.abs(s)<1||(i.style.transition=`none`,i.style.transform=`translate(${o}px, ${s}px)`,n.push(i))}),n.length!==0){n[0].getBoundingClientRect();for(let e of n){e.style.transition=`transform 180ms ease`,e.style.transform=`translate(0px, 0px)`;let t=()=>{e.style.transition=``,e.style.transform=``,e.removeEventListener(`transitionend`,t)};e.addEventListener(`transitionend`,t)}}}function WK(e){return Array.isArray(e.column)}function GK(e){return Array.isArray(e.tabs)}function KK(e){let t=[],n=e=>{GK(e)?t.push(...e.tabs??[]):t.push(e)};for(let t of e)WK(t)?(t.column??[]).forEach(n):n(t);return t}function qK(e){return e===`files`?`files`:e===`playtest`?`play`:e===`terminal`?`terminal`:e===`editor`?`editor`:null}var JK=[{type:`files`},{type:`playtest`},{type:`editor`,file:`scenes/main.scene`}];function YK(e,t){let n=e&&e.length>0?KK(e):JK,r=v?null:Ce(`operator`),i=r?[Te([r],_e(r))]:[],a=new Map,o=null;for(let e of n){let n=qK(e.type);if(!n||n===`editor`&&!e.file)continue;if(n===`editor`&&e.file){let n=t(e.file),r=a.get(n);if(r){r.tabs.push(Ce(`editor`,e.file));continue}let s=Ce(`editor`,e.file),c=Te([s],_e(s));a.set(n,c),i.push(c),o||=c.id;continue}let r=Ce(n,e.file);i.push(Te([r],_e(r)))}return{groups:i,activeGroupId:o??i[0]?.id??null,pinnedGroupId:null,maximizedGroupId:null}}function XK(){let e=Oi(),[t,n]=g.useState(()=>ji());return g.useEffect(()=>{if(e)return;let t=window.matchMedia(`(max-width: 768px)`),r=()=>n(t.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}function ZK(e){let t=e.target;if(!(t instanceof HTMLIFrameElement)||!t.classList.contains(`deck-frame`))return t;try{let n=t.contentDocument;if(!n)return t;let r=t.getBoundingClientRect();return n.elementFromPoint(e.clientX-r.left,e.clientY-r.top)??t}catch{return t}}function QK(e,t){let n=e,r=!!(n?.ownerDocument&&n.ownerDocument!==t.ownerDocument),i=r?null:t.parentElement;for(;n&&n!==i;){if(n.nodeType===1){let e=getComputedStyle(n).overflowY;if((e===`auto`||e===`scroll`)&&n.scrollHeight>n.clientHeight+1)return!0}if(!r&&n===t)break;n=n.parentElement}return!1}function $K(e,t,n){let r=e,i=t.parentElement;for(;r&&r!==i;){if(r.nodeType===1){let e=getComputedStyle(r),t=e.touchAction;if(t.includes(`pan-y`)&&!t.includes(`pan-x`))return!0;let i=e.overflowX;if(i===`auto`||i===`scroll`){let e=r.scrollWidth-r.clientWidth;if(e>1&&(n>0?r.scrollLeft>1:r.scrollLeft<e-1))return!0}}if(r===t)break;r=r.parentElement}return!1}function eq(e){g.useEffect(()=>{let t=e.current;if(!t)return;let n=e=>{e.deltaY!==0&&(t.scrollWidth<=t.clientWidth||!e.shiftKey&&QK(ZK(e),t)||(t.scrollLeft+=e.deltaX-e.deltaY,e.preventDefault()))};return t.addEventListener(`wheel`,n,{passive:!1}),()=>t.removeEventListener(`wheel`,n)},[e])}function tq(e,t,n){g.useLayoutEffect(()=>{let n=e.current,r=n?.querySelector(`.flow-row`);if(!n||!r)return;let i=()=>{let e=r.lastElementChild,i=e?e.offsetLeft+e.offsetWidth:0,a=t&&i>n.clientWidth?n.clientWidth/2:0;r.style.setProperty(`--flow-overscroll`,`${Math.round(a)}px`)};i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e,t,n])}function nq(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(r.left>=n.left-1&&r.right<=n.right+1)return;let i=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;e.scrollTo({left:e.scrollLeft+(r.left+r.width/2-(n.left+n.width/2)),behavior:i?`auto`:`smooth`})}function rq(e,t){let n=g.useRef(new Map),r=g.useCallback(e=>{let t=n.current.get(e);if(t)return t.obj;let r={visible:!1,active:!1,activeCbs:new Set,visibleCbs:new Set,obj:{id:e,isVisible:()=>r.visible,isActive:()=>r.active,onDidActiveChange:e=>(r.activeCbs.add(e),()=>r.activeCbs.delete(e)),onDidVisibilityChange:e=>(r.visibleCbs.add(e),()=>r.visibleCbs.delete(e))}};return n.current.set(e,r),r.obj},[]);return g.useEffect(()=>{let r=new Set;for(let i of e.groups){let a=t?i.id===e.activeGroupId:!0;for(let t of i.tabs){r.add(t.id);let o=n.current.get(t.id);if(!o)continue;let s=i.activeTabId===t.id,c=a&&s,l=i.id===e.activeGroupId&&s;c!==o.visible&&(o.visible=c,o.visibleCbs.forEach(e=>e(c))),l!==o.active&&(o.active=l,o.activeCbs.forEach(e=>e(l)))}}for(let e of n.current.keys())r.has(e)||n.current.delete(e)}),r}function iq({agent:e}){let[t,n]=g.useState(HK),[r,i]=g.useState(null),[a,o]=g.useState(null),s=g.useRef(null),c=g.useRef(!1),l=XK(),u=g.useRef(l);u.current=l;let d=g.useRef(HK),f=g.useRef(null),[p,m]=g.useState(null);d.current=t;let h=g.useRef(new Map),_=t.groups.find(e=>e.tabs.some(e=>e.kind===`operator`))?.id??null,v=g.useRef(_);v.current=_;let[y,b]=g.useState(null),x=g.useRef(null),S=g.useRef(null),C=g.useRef(null),w=g.useRef({page:0,count:0,ids:[]});eq(S),tq(S,!l&&!t.maximizedGroupId,t.groups);let T=rq(t,l);g.useEffect(()=>{let e=!0;Promise.all([en(),ln().catch(()=>[])]).then(([t,r])=>{e&&(s.current=t.deckId,Bt(t),i(t.kitEditorExtensions),o(r),n(LK(t.deckId,new Set(r),Jt)??YK(t.initialPanels,Jt)),c.current=!0)},()=>{e&&(i([]),o([]),n(YK(null,Jt)),c.current=!0)});let t=gA(t=>{t.changes.some(e=>e.event!==`change`)&&ln().then(t=>{e&&o(t)}).catch(()=>{}),t.changes.some(e=>e.path===`castle.json`||e.path.startsWith(`imports/`))&&en().then(t=>{e&&(Bt(t),i(t.kitEditorExtensions))},()=>{})});return()=>{e=!1,t()}},[]),g.useEffect(()=>{if(!c.current)return;let e=window.setTimeout(()=>IK(s.current,t),400);return()=>window.clearTimeout(e)},[t]);let ee=g.useMemo(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId),n=e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0];return n&&n.kind===`editor`?n.path??null:null},[t.groups,t.activeGroupId]),E=g.useRef(null),te=g.useCallback(e=>{if(u.current||d.current.maximizedGroupId)return;let t=S.current,n=h.current.get(e);t&&n&&nq(t,n)},[]),D=g.useCallback((e,t)=>{e&&(E.current=e,t||requestAnimationFrame(()=>{E.current===e&&(E.current=null,te(e))}))},[te]);g.useLayoutEffect(()=>{let e=E.current;e&&(E.current=null,te(e))},[t.groups,t.activeGroupId,t.maximizedGroupId,te]);let ne=g.useCallback(e=>{let t=d.current,r=e(t);r!==t&&n(()=>r),D(r.activeGroupId,r!==t)},[D]),re=g.useCallback((e,t,r)=>{let i=d.current,a=u.current?1:1/0,o=t?Qe(i,t,e,Jt,a,r):Ze(i,e,Jt,a,r);if(o===i)return;let c=ge(o);for(let e of ge(i))c.has(e)||ft(e);nr(s.current,e),n(()=>o),D(o.activeGroupId,!0)},[D]),O=g.useMemo(()=>({openFile:(e,t)=>re(e,void 0,t),openPlaytest:()=>ne(e=>tt(e,`play`)),closeEditor:e=>n(t=>{let n=ke(t,e);return n?Ke(t,n.group.id,n.tab.id):t}),activeEditorPath:ee,kitEditorExts:r,terminalTheme:`dark`}),[r,ee,re,ne]);gi(O);let k=g.useCallback((e,t)=>{let r=d.current,i=r.maximizedGroupId?st({...r,maximizedGroupId:null},e):He(r,e);i!==r&&n(()=>i),t?.reveal&&D(e,i!==r)},[D]),ie=g.useCallback(e=>{let t=Oe(d.current,e);if(t)for(let e of t.tabs)e.kind===`editor`&&e.path&&ft(e.path);n(t=>nt(t,e))},[]),ae=g.useCallback((e,t)=>{let r=Oe(d.current,e)?.tabs.find(e=>e.id===t);r?.kind===`editor`&&r.path&&ft(r.path),n(n=>Ke(n,e,t))},[]),oe=g.useCallback((e,t)=>n(n=>Ue(n,e,t)),[]),se=g.useCallback((e,t,r)=>{n(n=>at(n,e,t,r))},[]),[ce,A]=g.useState(null),le=g.useCallback(e=>A(e),[]),ue=g.useCallback(()=>A(null),[]),de=g.useCallback((e,t)=>re(t,e),[re]),fe=g.useCallback((e,t,r)=>{n(n=>Ye(n,e,t,r))},[]),pe=g.useCallback(e=>n(t=>ot(t,e)),[]),me=g.useCallback(e=>{let t=d.current.maximizedGroupId===e;n(t=>st(t,e)),t&&D(e,!0)},[D]),_e=g.useCallback((e,t,r)=>{n(n=>lt(ct(n,e,t),e,r))},[]);g.useEffect(()=>{if(!l)return;let e=S.current,t=C.current;if(!e||!t)return;let r=0,i=0,a=0,o=1,s=!1,c=!1,u=null,d=e=>t.style.setProperty(`--flow-drag`,`${e}px`),f=t=>{t.touches.length===1&&(r=t.touches[0].clientX,i=t.touches[0].clientY,a=t.timeStamp,u=t.target,o=e.clientWidth||1,s=!1,c=!1)},p=n=>{if(n.touches.length!==1)return;let a=n.touches[0].clientX-r,o=n.touches[0].clientY-i;if(!s){if(Math.abs(a)<8&&Math.abs(o)<8)return;s=!0,c=Math.abs(a)>Math.abs(o)&&!$K(u,e,a),c&&t.classList.add(`flow-dragging`)}if(!c)return;n.preventDefault();let{page:l,count:f}=w.current;d(l===0&&a>0||l===f-1&&a<0?a*.3:a)},m=e=>{if(!c){t.classList.remove(`flow-dragging`);return}c=!1,t.classList.remove(`flow-dragging`);let i=e.changedTouches[0],s=i?i.clientX-r:0,l=e.timeStamp-a,{page:u,count:f,ids:p}=w.current,m=Math.abs(s)>50&&l<250,h=Math.abs(s)>o*.25,g=u;s<0&&(m||h)?g=Math.min(f-1,u+1):s>0&&(m||h)&&(g=Math.max(0,u-1));let _=p[g];g!==u&&_?n(e=>He(e,_)):d(0)};return e.addEventListener(`touchstart`,f,{passive:!0}),e.addEventListener(`touchmove`,p,{passive:!1}),e.addEventListener(`touchend`,m,{passive:!0}),e.addEventListener(`touchcancel`,m,{passive:!0}),()=>{e.removeEventListener(`touchstart`,f),e.removeEventListener(`touchmove`,p),e.removeEventListener(`touchend`,m),e.removeEventListener(`touchcancel`,m)}},[l]);let ve=g.useCallback((e,t)=>{t?h.current.set(e,t):h.current.delete(e),e===v.current&&b(t)},[]);g.useLayoutEffect(()=>{b(_?h.current.get(_)??null:null)},[_]);let ye=NK(e,(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId);return(e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0])?.kind===`operator`})(),y),[be,xe]=g.useState(null),Se=g.useRef(null),Ce=g.useRef(!1);g.useLayoutEffect(()=>{let e=Se.current;e&&(Se.current=null,UK(e,h.current))});let we=g.useCallback((e,t)=>{let r=d.current;if(u.current){let n=it(r,e,t),i=r.groups.findIndex(e=>e.id===r.activeGroupId);n.groups.findIndex(e=>e.id===n.activeGroupId)!==i&&(Ce.current=!0)}else{let e=new Map;for(let t of r.groups){let n=h.current.get(t.id)?.getBoundingClientRect();n&&e.set(t.id,n)}Se.current=e}n(n=>it(n,e,t))},[]);g.useEffect(()=>()=>{x.current?.()},[]);let Te=g.useCallback((e,r)=>{if(l||e.button!==0||e.target.closest(`.panel-tab, button`)||!h.current.get(r))return;let i=e.currentTarget,a=e.pointerId;try{i.setPointerCapture(a)}catch{}let o=e.clientX,s=t.groups.findIndex(e=>e.id===r),c=e=>{let n=t.groups.filter(e=>e.id!==r).map(e=>{let t=h.current.get(e.id)?.getBoundingClientRect();return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),i=0;for(;i<n.length&&n[i].center<e;)i+=1;if(i===s)return{target:i,x:null};let a=i<n.length?n[i].left-6:n.length?n[n.length-1].right+6:e;return{target:i,x:a}},u=!1,d=e.clientX,f=0,p=()=>{let e=S.current;if(e&&e.scrollWidth>e.clientWidth+1){let t=e.getBoundingClientRect(),n=0;d<t.left+64?n=-(1-Math.max(0,d-t.left)/64):d>t.right-64&&(n=1-Math.max(0,t.right-d)/64),n!==0&&(e.scrollLeft+=n*24,xe({id:r,x:c(d).x}))}f=requestAnimationFrame(p)},m=e=>{!u&&Math.abs(e.clientX-o)<5||(u||(document.body.classList.add(`flow-reordering`),u=!0,f=requestAnimationFrame(p)),d=e.clientX,xe({id:r,x:c(e.clientX).x}))},g=!1,_=()=>{if(!g){g=!0,i.removeEventListener(`pointermove`,m),i.removeEventListener(`pointerup`,v),i.removeEventListener(`pointercancel`,y),i.removeEventListener(`lostpointercapture`,y);try{i.hasPointerCapture(a)&&i.releasePointerCapture(a)}catch{}f&&cancelAnimationFrame(f),document.body.classList.remove(`flow-reordering`),x.current=null}},v=e=>{let i=u;if(_(),i){let{target:i}=c(e.clientX);if(i!==s){let e=new Map;for(let n of t.groups){let t=h.current.get(n.id)?.getBoundingClientRect();t&&e.set(n.id,t)}Se.current=e,n(e=>it(e,r,i))}}xe(null)},y=()=>{_(),xe(null)};x.current=y,i.addEventListener(`pointermove`,m),i.addEventListener(`pointerup`,v),i.addEventListener(`pointercancel`,y),i.addEventListener(`lostpointercapture`,y)},[l,t.groups]),[Ee,De]=g.useState(null),Ae=g.useCallback(e=>De(t=>t?null:{anchor:e}),[]),je=g.useCallback(()=>{let e=C.current?.querySelector(`.flow-tabs-add`);De({anchor:e?.getBoundingClientRect()??new DOMRect(window.innerWidth/2,48)})},[]);g.useEffect(()=>{let e=(e,t)=>(t&&t!==window?[...document.querySelectorAll(`iframe.deck-frame`)].find(e=>e.contentWindow===t):e)?.closest?.(`.flow-group`)?.getAttribute(`data-group-id`)??null;return jt(`pointermove`,t=>{let n=e(t.target,t.view);f.current=n,!u.current&&m(e=>e===n?e:n)},{passive:!0})},[]);let Me=g.useMemo(()=>yt({getState:()=>d.current,setState:n,spawn:ne,focusGroup:e=>k(e,{reveal:!0}),closeGroup:ie,closeTab:ae,openPath:e=>re(e),openNewGroupPicker:je,getHoveredGroupId:()=>f.current,toggleMaximize:me}),[ne,k,ie,ae,re,je,me]),Ne=Pt(Me),Pe=t.groups.some(e=>e.id===t.activeGroupId)?t.activeGroupId:t.groups[0]?.id??null,Fe=l?null:t.maximizedGroupId,Ie=Math.max(0,t.groups.findIndex(e=>e.id===Pe));w.current={page:Ie,count:t.groups.length,ids:t.groups.map(e=>e.id)},g.useLayoutEffect(()=>{let e=C.current;if(!e)return;let t=Ce.current;t&&e.classList.add(`flow-dragging`),e.style.setProperty(`--flow-page`,String(Ie)),e.style.setProperty(`--flow-drag`,`0px`),t&&(Ce.current=!1,e.offsetHeight,requestAnimationFrame(()=>e.classList.remove(`flow-dragging`)))},[Ie,l]),Wn(C),Kn(()=>ce?(A(null),!0):Ee?(De(null),!0):!1);let Le=ce?Oe(t,ce):null,Re=Le?.tabs.find(e=>e.id===Le.activeTabId)??Le?.tabs[0],ze=Re&&Re.kind===`editor`?Re.path??``:``;return(0,j.jsx)(mi,{value:O,children:(0,j.jsx)(VK.Provider,{value:e,children:(0,j.jsxs)(`div`,{ref:C,className:`flow-root${l?` is-mobile`:``}${Fe?` is-maximized`:``}`,children:[(0,j.jsx)(aq,{state:t,activeId:Pe,operatorBadge:ye,onFocusGroup:k,onReorderGroup:we,onNewGroup:Ae}),(0,j.jsx)(`div`,{className:`flow-scroller`,ref:S,children:(0,j.jsx)(`div`,{className:`flow-field`,children:(0,j.jsx)(`div`,{className:`flow-row`,children:t.groups.map(e=>(0,j.jsx)(sq,{group:e,active:e.id===Pe,mobile:l,pinned:e.id===t.pinnedGroupId&&!Fe,maximized:e.id===Fe,hidden:Fe!==null&&e.id!==Fe,dragging:be?.id===e.id,hovered:e.id===p,getLifecycle:T,registerEl:ve,onFocusGroup:k,onClose:ie,onActivateTab:oe,onCloseTab:ae,onReorderTab:se,onOpenMobileSwitch:le,onOpenInGroup:de,onSetTabView:fe,onTogglePin:pe,onToggleMaximize:me,onStartDrag:Te,onResize:_e},e.id))})})}),be&&be.x!==null&&(()=>{let e=S.current?.getBoundingClientRect(),t=h.current.get(be.id)?.getBoundingClientRect();if(!e||!t)return null;let n=Math.max(t.top,e.top+12+36),r=Math.min(t.bottom,e.bottom)-n;return r<=0?null:(0,j.jsx)(`div`,{className:`flow-drop-indicator`,style:{left:be.x,top:n,height:r}})})(),Ee&&(0,j.jsx)(_q,{anchor:Ee.anchor,files:a??[],onOpenFile:e=>re(e),onSpawnPanel:e=>ne(t=>tt(t,e)),onSpawnClass:e=>ne(t=>$e(t,e,Jt)),onClose:()=>De(null)}),ce&&(0,j.jsx)(wi,{groupId:ce,groupClass:he(Le,Jt),currentFile:ze,files:a,recent:ir(s.current),view:Re?.view,onSetView:e=>{ce&&Re&&fe(ce,Re.id,e)},onOpen:(e,t)=>re(e,t),onClose:ue}),(0,j.jsx)(Zn,{openFile:e=>re(e),openPanel:e=>ne(t=>tt(t,e===`playtest`?`play`:e)),panels:hq,getCommands:Me}),Ne?(0,j.jsxs)(`div`,{className:`chord-hint`,role:`status`,children:[(0,j.jsx)(`kbd`,{children:Ne}),(0,j.jsx)(`span`,{children:`waiting for the next key…`})]}):null]})})})}function aq(e){let{state:t,activeId:n,operatorBadge:r,onFocusGroup:i,onReorderGroup:a,onNewGroup:o}=e,s=Jn(),[c,l]=g.useState(!1),u=s?.title?.trim()||`Untitled deck`;Vn(u,r),Hn(r);let d=s?.visibility===`public`?yr:s?.visibility===`unlisted`?_r:vr,f=s?.saving??`idle`,p=s?.saveError??null,m=s?.draftAutosaveState??null,h=m===`starting`||m===`saving`?`Saving draft…`:m===`dirty`?`Unsaved changes`:m===`error`?`Draft save failed`:m===`saved`?`Draft saved`:null,[_,v]=g.useState(null),y=g.useRef(!1);g.useEffect(()=>{_!==null&&(f===`working`&&(y.current=!0),f===`done`&&y.current&&v(`done`),p&&y.current&&v(`failed`))},[f,p,_]);let b=g.useCallback(()=>{y.current=!1,v(`pushing`),zn(`push`)},[]);return(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{className:`flow-topbar`,children:[(0,j.jsxs)(`div`,{className:`flow-topbar-leading`,children:[Oi()?null:(0,j.jsxs)(`div`,{className:`flow-castle-wrap`,children:[(0,j.jsx)(`button`,{type:`button`,className:`dock-control dock-control-icon dock-control-mark`,title:`Menu`,"aria-haspopup":`menu`,"aria-expanded":c,onClick:()=>l(e=>!e),children:Tr}),c&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-menu-backdrop`,onClick:()=>l(!1)}),(0,j.jsxs)(`div`,{className:`menu flow-castle-menu`,role:`menu`,children:[(0,j.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{l(!1),zn(`back-to-decks`)},children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:xr}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:`Back to decks`})]}),(0,j.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{l(!1),zn(`new-deck`)},children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:pr}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:`New deck`})]}),(0,j.jsx)(`div`,{className:`menu-separator flow-menu-narrow`}),(0,j.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,onClick:()=>{l(!1),zn(`open-settings`)},children:(0,j.jsx)(`span`,{className:`menu-item-label`,children:`Deck settings`})}),(0,j.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,disabled:f===`working`,onClick:()=>{l(!1),b()},children:(0,j.jsx)(`span`,{className:`menu-item-label`,children:f===`working`?`Pushing…`:p?`Push failed — retry`:f===`done`?`Pushed ✓`:`Push to Castle`})})]})]})]}),(0,j.jsxs)(`button`,{type:`button`,className:`dock-control dock-control-quiet flow-deck-identity`,title:`Deck settings`,onClick:()=>zn(`open-settings`),children:[(0,j.jsx)(`span`,{className:`flow-deck-vis`,children:d}),(0,j.jsx)(`span`,{className:`flow-deck-name`,children:u}),(0,j.jsx)(`span`,{className:`flow-deck-caret`,children:Sr})]}),h?(0,j.jsx)(`span`,{className:`flow-draft-status${m===`error`?` is-error`:``}`,role:`status`,children:h}):null]}),(0,j.jsxs)(`div`,{className:`flow-tabs-wrap`,children:[(0,j.jsx)(Xr,{groups:t.groups,activeId:n,operatorBadge:r,onFocusGroup:i,onReorderGroup:a}),(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet flow-tabs-add flow-picker-trigger`,title:`New group`,"aria-label":`New group`,onClick:e=>o(e.currentTarget.getBoundingClientRect()),children:pr})]}),(0,j.jsx)(`div`,{className:`flow-topbar-trailing`,children:(0,j.jsxs)(`button`,{type:`button`,className:`dock-control flow-preview-btn${p?` flow-preview-btn-failed`:``}`,title:p??`Publish this deck to your Castle account (sandbox edits stay local until pushed)`,disabled:f===`working`,onClick:()=>zn(`push`),children:[br,(0,j.jsxs)(`span`,{className:`flow-preview-label`,children:[(0,j.jsx)(`span`,{className:`flow-preview-label-sizer`,"aria-hidden":`true`,children:`Push to Castle`}),(0,j.jsx)(`span`,{children:f===`working`?`Pushing…`:p?`Push failed`:f===`done`?`Pushed ✓`:`Push to Castle`})]})]})})]}),_!==null&&(0,j.jsx)(`div`,{className:`flow-push-modal-backdrop`,children:(0,j.jsx)(`div`,{className:`flow-push-modal`,role:`dialog`,"aria-modal":`true`,children:_===`failed`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-check flow-push-check-failed`,children:`!`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Push failed`}),(0,j.jsx)(`div`,{className:`flow-push-sub`,children:p}),(0,j.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>v(null),children:`Dismiss`})]}):_===`done`?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-check`,children:`✓`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Pushed to Castle`}),s?.shareUrl?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Your deck is live at`}),(0,j.jsx)(`a`,{className:`flow-push-url`,href:s.shareUrl,target:`_blank`,rel:`noreferrer`,children:s.shareUrl.replace(/^https?:\/\//,``)})]}):(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Saved to your Castle account.`}),(0,j.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>v(null),children:`Done`})]}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-push-spinner`}),(0,j.jsx)(`div`,{className:`flow-push-title`,children:`Pushing to Castle…`}),(0,j.jsx)(`div`,{className:`flow-push-sub`,children:`Publishing your latest changes.`})]})})})]})}function oq(e,t){e.currentTarget.blur(),t()}var sq=g.memo(function(e){let{group:t,active:n,mobile:r,pinned:i,maximized:a,hidden:o,dragging:s,hovered:c,getLifecycle:l,registerEl:u}=e,{onFocusGroup:d,onClose:f}=e,p=me(t),m=vq(t,e.onResize),[h,_]=g.useState(()=>p&&t.tabs.every(pe)),v=g.useCallback(()=>_(e=>!e),[]),y=r?void 0:a?{flex:`1 1 auto`}:{flex:`0 0 auto`,width:t.w,height:t.h},b=p?null:t.tabs[0],x=(0,j.jsx)(`button`,{type:`button`,className:r?`button button-icon button-icon-large button-quiet`:`button button-icon button-quiet`,title:`Close`,"aria-label":`Close`,onClick:e=>oq(e,()=>f(t.id)),children:mr}),S=n=>{n.target.closest(`button`)||a||e.onStartDrag(n,t.id)},C=n&&!r&&!a;return(0,j.jsxs)(`div`,{ref:e=>u(t.id,e),"data-group-id":t.id,className:`panel flow-group${C?` is-active`:``}${i?` pinned`:``}${a?` maximized`:``}${o?` hidden`:``}${s?` is-dragging`:``}${c?` is-hover`:``}${p?` is-editor`:``}`,style:y,onMouseDown:()=>d(t.id),children:[p?(0,j.jsx)(Gr,{group:t,mobile:r,pinned:i,maximized:a,onStartDrag:e.onStartDrag,onActivateTab:e.onActivateTab,onCloseTab:e.onCloseTab,onCloseGroup:f,onReorderTab:e.onReorderTab,onTogglePin:e.onTogglePin,onToggleMaximize:e.onToggleMaximize,onOpenMobileSwitch:e.onOpenMobileSwitch,onSetTabView:e.onSetTabView,drawerOpen:h,onToggleDrawer:v}):r?(0,j.jsxs)(`div`,{className:`panel-header flow-tabstrip flow-tabstrip-mobile`,onPointerDown:S,children:[(0,j.jsx)(`div`,{className:`flow-mobile-strip-left`}),(0,j.jsxs)(`div`,{className:`panel-mobile-current`,children:[(0,j.jsx)(`span`,{className:`flow-tab-icon`,children:b&&fr(b.kind,b.path)}),(0,j.jsx)(`span`,{className:`panel-mobile-current-label`,children:b?.label})]}),(0,j.jsx)(`div`,{className:`panel-header-actions flow-mobile-strip-right`,children:x})]}):(0,j.jsxs)(`div`,{className:`panel-header flow-tabstrip`,onPointerDown:S,children:[(0,j.jsxs)(`div`,{className:`panel-title`,children:[(0,j.jsx)(`span`,{className:`flow-tab-icon`,children:b&&fr(b.kind,b.path)}),(0,j.jsx)(`span`,{children:b?.label})]}),(0,j.jsxs)(`div`,{className:`panel-header-actions`,children:[!a&&(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:i?`Unpin`:`Pin to left`,"aria-label":i?`Unpin`:`Pin to left`,"aria-pressed":i,onClick:n=>oq(n,()=>e.onTogglePin(t.id)),children:gr}),(0,j.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:a?`Restore`:`Maximize`,"aria-label":a?`Restore`:`Maximize`,"aria-pressed":a,onClick:n=>oq(n,()=>e.onToggleMaximize(t.id)),children:a?wr:Cr}),x]})]}),(0,j.jsx)(`div`,{className:`flow-panel-body`,children:t.tabs.map(n=>(0,j.jsx)(`div`,{className:`flow-tab-body${n.id===t.activeTabId?``:` inactive`}`,children:(0,j.jsx)(cq,{tab:n,groupId:t.id,lifecycle:l(n.id),onOpenInGroup:e.onOpenInGroup,onSetTabView:e.onSetTabView,drawerOpen:h&&!r})},n.id))}),!r&&!a&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(`div`,{className:`flow-resize-e`,onPointerDown:m(`x`),title:`Drag to resize width`}),(0,j.jsx)(`div`,{className:`flow-resize-s`,onPointerDown:m(`y`),title:`Drag to resize height`}),(0,j.jsx)(`div`,{className:`flow-resize-se`,onPointerDown:m(`xy`),title:`Drag to resize`})]})]})}),cq=g.memo(function(e){let{tab:t,groupId:n,lifecycle:r,onOpenInGroup:i,onSetTabView:a,drawerOpen:o}=e;if(t.kind===`editor`&&pe(t))return(0,j.jsxs)(`div`,{className:`flow-empty-editor`,children:[o?(0,j.jsx)(eH,{currentFile:``,filterClass:t.classHint,onOpen:e=>i(n,e)}):null,(0,j.jsx)(`div`,{className:`flow-empty-editor-msg`,children:`Open a file`})]});switch(t.kind){case`editor`:return(0,j.jsx)(WV,{file:t.path,editorClass:t.view,lifecycle:r,hideContextBar:!0,drawerOpen:o,drawer:(0,j.jsx)(eH,{currentFile:t.path??``,filterClass:t.path?Jt(t.path):void 0,onOpen:e=>i(n,e),view:t.view,onSetView:e=>a(n,t.id,e)})});case`play`:return(0,j.jsx)(QV,{lifecycle:r});case`terminal`:return(0,j.jsx)($V,{lifecycle:r});case`files`:return(0,j.jsx)(nU,{lifecycle:r});case`operator`:return(0,j.jsx)(lq,{});default:return(0,j.jsx)(uq,{tab:t})}});function lq(){let e=g.useContext(VK);return e?(0,j.jsx)(`div`,{className:`shell-root docked flow-operator-host`,style:{"--operator-col":`100%`},children:(0,j.jsx)(_K,{agent:e})}):(0,j.jsx)(`div`,{className:`flow-placeholder`,children:`operator unavailable`})}function uq(e){let{tab:t}=e;return(0,j.jsxs)(`div`,{className:`flow-placeholder kind-${t.kind}`,children:[(0,j.jsx)(`div`,{className:`flow-placeholder-icon`,children:fr(t.kind,t.path)}),(0,j.jsx)(`div`,{className:`flow-placeholder-label`,children:t.label}),(0,j.jsx)(`div`,{className:`flow-placeholder-kind`,children:t.path??t.kind})]})}function dq(e,t){g.useEffect(()=>{let n=n=>{n.target.closest(e)||t()},r=window.setTimeout(()=>document.addEventListener(`mousedown`,n),0);return()=>{window.clearTimeout(r),document.removeEventListener(`mousedown`,n)}},[e,t])}function fq(e,t){return Math.max(8,Math.min(e,window.innerWidth-t-8))}var pq=300,mq=[...v?[]:[{kind:`operator`,label:`Operator`}],{kind:`play`,label:`Play`},...v?[]:[{kind:`terminal`,label:`Terminal`}],{kind:`files`,label:`Files`}],hq=mq.map(({kind:e,label:t})=>({kind:e===`play`?`playtest`:e,label:t}));function gq(e,t){let n=t.trim().toLowerCase(),r=mq.filter(e=>e.label.toLowerCase().includes(n)).map(e=>({kind:`panel`,panel:e.kind,label:e.label})),i=new Set;for(let t of e)i.add(Jt(t));let a=[...i].map(e=>{let t=Yt(e);return{kind:`class`,classId:e,label:t.label,icon:t.icon}}).filter(e=>e.label.toLowerCase().includes(n)).sort((e,t)=>e.label.localeCompare(t.label)),o=e.filter(e=>e.toLowerCase().includes(n)).slice(0,40).map(e=>({kind:`file`,path:e}));return[...r,...a,...o]}function _q(e){let{anchor:t,files:n,onOpenFile:r,onSpawnPanel:i,onSpawnClass:a,onClose:o}=e,[s,c]=g.useState(``),[l,u]=g.useState(0);dq(`.flow-picker, .flow-picker-trigger`,o);let d=gq(n,s),f=Math.min(l,Math.max(0,d.length-1)),p=e=>{e.kind===`panel`?i(e.panel):e.kind===`class`?a(e.classId):r(e.path),o()};return(0,It.createPortal)((0,j.jsxs)(`div`,{className:`menu flow-picker`,style:{top:t.bottom+4,left:fq(t.left,pq),width:pq},onMouseDown:e=>e.stopPropagation(),children:[(0,j.jsx)(`input`,{className:`flow-picker-input`,autoFocus:!0,placeholder:`Open a file or panel…`,value:s,onChange:e=>{c(e.target.value),u(0)},onKeyDown:e=>{e.key===`Escape`?o():e.key===`ArrowDown`?(e.preventDefault(),u(e=>Math.min(e+1,d.length-1))):e.key===`ArrowUp`?(e.preventDefault(),u(e=>Math.max(e-1,0))):e.key===`Enter`&&d[f]&&p(d[f])}}),(0,j.jsxs)(`div`,{className:`flow-picker-list`,children:[d.length===0&&(0,j.jsx)(`div`,{className:`flow-picker-empty`,children:`No matches`}),d.map((e,t)=>(0,j.jsxs)(`button`,{type:`button`,className:`menu-item${t===f?` is-hover`:``}`,onMouseEnter:()=>u(t),onClick:()=>p(e),children:[(0,j.jsx)(`span`,{className:`menu-icon`,children:e.kind===`panel`?fr(e.panel):e.kind===`class`?lr(e.icon):fr(`editor`,e.path)}),(0,j.jsx)(`span`,{className:`menu-item-label`,children:e.kind===`panel`||e.kind===`class`?e.label:e.path})]},e.kind===`panel`?`p:${e.panel}`:e.kind===`class`?`c:${e.classId}`:`f:${e.path}`))]})]}),document.body)}function vq(e,t){return g.useCallback(n=>r=>{r.preventDefault(),r.stopPropagation();let i=r.clientX,a=r.clientY,o=e.w,s=e.h,c=r.currentTarget;c.setPointerCapture(r.pointerId);let l=!1,u=r=>{let c=r.clientX-i,u=r.clientY-a;if(!l&&Math.abs(c)<5&&Math.abs(u)<5)return;l=!0;let d=n===`y`?o:Math.max(200,o+c),f=n===`x`?s:Math.max(160,s+u);t(e.id,d,f)},d=()=>{c.removeEventListener(`pointermove`,u),c.removeEventListener(`pointerup`,d)};c.addEventListener(`pointermove`,u),c.addEventListener(`pointerup`,d)},[e.id,e.w,e.h,t])}function yq(){let e=oe(),t=g.useRef(0);return qn(()=>{let n=Date.now();n-t.current<1e3||(t.current=n,e.refreshUsage())}),(0,j.jsx)(iq,{agent:e})}var bq=document.getElementById(`root`);if(!bq)throw Error(`Missing #root`);dH(),dj(),(0,_.createRoot)(bq).render((0,j.jsx)(yq,{}));
|
package/dist/shell/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<link rel="icon" type="image/png" sizes="32x32" href="/__castle/ide/favicon-32x32.png" />
|
|
11
11
|
<link rel="icon" type="image/png" sizes="16x16" href="/__castle/ide/favicon-16x16.png" />
|
|
12
12
|
<link rel="icon" href="/__castle/ide/favicon.ico" sizes="any" />
|
|
13
|
-
<script type="module" crossorigin src="/__castle/ide/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/__castle/ide/assets/index-DF1yMXPS.js"></script>
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-6odVZQSZ.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
package/kits/base/castle.json
CHANGED