@celestea/studio 2.7.1 → 2.7.2
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/store/session-id.d.ts +10 -0
- package/dist/store/session-id.js +14 -0
- package/dist/store/workspaces.d.ts +20 -1
- package/dist/store/workspaces.js +38 -22
- package/package.json +8 -8
- package/webdist/assets/{index-Bngs7gUm.js → index-CSJYbgdH.js} +9 -9
- package/webdist/build-meta.json +3 -3
- package/webdist/index.html +2 -2
|
@@ -18,6 +18,16 @@ export declare function baseName(path: string, input?: PathInputLike): string;
|
|
|
18
18
|
export declare function rootOf(path: string, input?: PathInputLike): string;
|
|
19
19
|
/** Absolute per the call's platform (Windows drive letters included). */
|
|
20
20
|
export declare function isAbsolutePath(path: string, input?: PathInputLike): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* `resolve` under the call's platform.
|
|
23
|
+
* W885 follow-up: "make this path absolute/canonical" is the same platform
|
|
24
|
+
* question as "is this path absolute" — `node:path`'s bare `resolve` answers
|
|
25
|
+
* it for the HOST, which is wrong the moment a win32 path is handled on Linux
|
|
26
|
+
* (tests) or the reverse.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolvePath(path: string, input?: PathInputLike): string;
|
|
29
|
+
/** `join` under the call's platform (public form of `under`; W883 E1/E2). */
|
|
30
|
+
export declare function joinPath(input: PathInputLike, base: string, ...segments: string[]): string;
|
|
21
31
|
/** Separators / control chars / whitespace -> '_'; CJK and letters survive. */
|
|
22
32
|
export declare function sanitizeComponent(s: string): string;
|
|
23
33
|
export interface ParsedSessionId {
|
package/dist/store/session-id.js
CHANGED
|
@@ -41,6 +41,20 @@ export function rootOf(path, input = undefined) {
|
|
|
41
41
|
export function isAbsolutePath(path, input = undefined) {
|
|
42
42
|
return apiOf(input).isAbsolute(path);
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* `resolve` under the call's platform.
|
|
46
|
+
* W885 follow-up: "make this path absolute/canonical" is the same platform
|
|
47
|
+
* question as "is this path absolute" — `node:path`'s bare `resolve` answers
|
|
48
|
+
* it for the HOST, which is wrong the moment a win32 path is handled on Linux
|
|
49
|
+
* (tests) or the reverse.
|
|
50
|
+
*/
|
|
51
|
+
export function resolvePath(path, input = undefined) {
|
|
52
|
+
return apiOf(input).resolve(path);
|
|
53
|
+
}
|
|
54
|
+
/** `join` under the call's platform (public form of `under`; W883 E1/E2). */
|
|
55
|
+
export function joinPath(input, base, ...segments) {
|
|
56
|
+
return under(input, base, ...segments);
|
|
57
|
+
}
|
|
44
58
|
/** Separators / control chars / whitespace -> '_'; CJK and letters survive. */
|
|
45
59
|
export function sanitizeComponent(s) {
|
|
46
60
|
let out = "";
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* - write = pretty JSON -> `<file>.json.tmp` -> rename (atomic, no fsync).
|
|
13
13
|
*/
|
|
14
14
|
import { type StoreResult } from "./result.js";
|
|
15
|
+
import { type PathInputLike } from "./session-id.js";
|
|
15
16
|
export declare const SESSION_FILE = "cli-main.jsonl";
|
|
16
17
|
export interface RegistryWorkspace {
|
|
17
18
|
path: string;
|
|
@@ -32,8 +33,26 @@ export interface WorkspacesView {
|
|
|
32
33
|
}
|
|
33
34
|
export declare class WorkspacesStore {
|
|
34
35
|
private readonly file;
|
|
36
|
+
/**
|
|
37
|
+
* The path rules of THIS call's platform. Defaults to the host's — production
|
|
38
|
+
* always wants the host — but it is injectable so the win32 branch is
|
|
39
|
+
* unit-tested on Linux (the W885 seam). `register()` used to test
|
|
40
|
+
* `startsWith("/")`, which rejected EVERY Windows absolute path, so a Windows
|
|
41
|
+
* install could never register a workspace and every "new session" ended in
|
|
42
|
+
* `404 unknown workspace ''`.
|
|
43
|
+
*/
|
|
44
|
+
private readonly platform;
|
|
35
45
|
private data;
|
|
36
|
-
constructor(file: string
|
|
46
|
+
constructor(file: string,
|
|
47
|
+
/**
|
|
48
|
+
* The path rules of THIS call's platform. Defaults to the host's — production
|
|
49
|
+
* always wants the host — but it is injectable so the win32 branch is
|
|
50
|
+
* unit-tested on Linux (the W885 seam). `register()` used to test
|
|
51
|
+
* `startsWith("/")`, which rejected EVERY Windows absolute path, so a Windows
|
|
52
|
+
* install could never register a workspace and every "new session" ended in
|
|
53
|
+
* `404 unknown workspace ''`.
|
|
54
|
+
*/
|
|
55
|
+
platform?: PathInputLike);
|
|
37
56
|
/** Snapshot of the registry (callers must not mutate it). */
|
|
38
57
|
registry(): RegistryData;
|
|
39
58
|
activeSession(): string | null;
|
package/dist/store/workspaces.js
CHANGED
|
@@ -12,10 +12,9 @@
|
|
|
12
12
|
* - write = pretty JSON -> `<file>.json.tmp` -> rename (atomic, no fsync).
|
|
13
13
|
*/
|
|
14
14
|
import { renameSync } from "node:fs";
|
|
15
|
-
import { resolve } from "node:path";
|
|
16
15
|
import { writeJsonAtomic, isDirectory, isFile, listEntries, readJsonIfExists } from "./fs-json.js";
|
|
17
16
|
import { badRequest, conflict, errText, fail, notFound, ok, serverError } from "./result.js";
|
|
18
|
-
import { sessionRoots, workspaceBasename } from "./session-id.js";
|
|
17
|
+
import { isAbsolutePath, joinPath, parentDir, resolvePath, sessionRoots, workspaceBasename, } from "./session-id.js";
|
|
19
18
|
export const SESSION_FILE = "cli-main.jsonl";
|
|
20
19
|
function parseEntry(row) {
|
|
21
20
|
if (typeof row !== "object" || row === null)
|
|
@@ -36,10 +35,10 @@ function parseRegistry(raw) {
|
|
|
36
35
|
return { workspaces, active_session: typeof active === "string" && active !== "" ? active : null };
|
|
37
36
|
}
|
|
38
37
|
/** Duplicate folder names make the workspace key ambiguous: hard error. */
|
|
39
|
-
function assertUniqueBasenames(workspaces) {
|
|
38
|
+
function assertUniqueBasenames(workspaces, input = undefined) {
|
|
40
39
|
const seen = new Map();
|
|
41
40
|
for (const w of workspaces) {
|
|
42
|
-
const base = workspaceBasename(w.path) ?? w.path;
|
|
41
|
+
const base = workspaceBasename(w.path, input) ?? w.path;
|
|
43
42
|
const other = seen.get(base);
|
|
44
43
|
if (other !== undefined && other !== w.path) {
|
|
45
44
|
throw new Error(`two workspaces resolve to the same folder name '${base}' (workspace keys must be unique basenames; rename one folder)`);
|
|
@@ -47,14 +46,14 @@ function assertUniqueBasenames(workspaces) {
|
|
|
47
46
|
seen.set(base, w.path);
|
|
48
47
|
}
|
|
49
48
|
}
|
|
50
|
-
function loadRegistry(file) {
|
|
49
|
+
function loadRegistry(file, input = undefined) {
|
|
51
50
|
const out = readJsonIfExists(file);
|
|
52
51
|
if (!out.exists)
|
|
53
52
|
return { workspaces: [], active_session: null };
|
|
54
53
|
if (out.error !== undefined)
|
|
55
54
|
throw new Error(`workspaces.json '${file}' is malformed: ${out.error}`);
|
|
56
55
|
const data = parseRegistry(out.value);
|
|
57
|
-
assertUniqueBasenames(data.workspaces);
|
|
56
|
+
assertUniqueBasenames(data.workspaces, input);
|
|
58
57
|
return data;
|
|
59
58
|
}
|
|
60
59
|
/**
|
|
@@ -62,15 +61,26 @@ function loadRegistry(file) {
|
|
|
62
61
|
* `register` used to keep whatever the client sent, so `/tmp/foo/` made the
|
|
63
62
|
* rename target `/tmp/foo/bar` — a child of the source folder (EINVAL).
|
|
64
63
|
*/
|
|
65
|
-
function normalizeWorkspacePath(path) {
|
|
66
|
-
return
|
|
64
|
+
function normalizeWorkspacePath(path, input = undefined) {
|
|
65
|
+
return resolvePath(path, input);
|
|
67
66
|
}
|
|
68
67
|
export class WorkspacesStore {
|
|
69
68
|
file;
|
|
69
|
+
platform;
|
|
70
70
|
data;
|
|
71
|
-
constructor(file
|
|
71
|
+
constructor(file,
|
|
72
|
+
/**
|
|
73
|
+
* The path rules of THIS call's platform. Defaults to the host's — production
|
|
74
|
+
* always wants the host — but it is injectable so the win32 branch is
|
|
75
|
+
* unit-tested on Linux (the W885 seam). `register()` used to test
|
|
76
|
+
* `startsWith("/")`, which rejected EVERY Windows absolute path, so a Windows
|
|
77
|
+
* install could never register a workspace and every "new session" ended in
|
|
78
|
+
* `404 unknown workspace ''`.
|
|
79
|
+
*/
|
|
80
|
+
platform = undefined) {
|
|
72
81
|
this.file = file;
|
|
73
|
-
this.
|
|
82
|
+
this.platform = platform;
|
|
83
|
+
this.data = loadRegistry(file, platform);
|
|
74
84
|
}
|
|
75
85
|
/** Snapshot of the registry (callers must not mutate it). */
|
|
76
86
|
registry() {
|
|
@@ -80,7 +90,7 @@ export class WorkspacesStore {
|
|
|
80
90
|
return this.data.active_session;
|
|
81
91
|
}
|
|
82
92
|
workspacePath(name) {
|
|
83
|
-
return this.data.workspaces.find((w) => workspaceBasename(w.path) === name)?.path;
|
|
93
|
+
return this.data.workspaces.find((w) => workspaceBasename(w.path, this.platform) === name)?.path;
|
|
84
94
|
}
|
|
85
95
|
persist() {
|
|
86
96
|
try {
|
|
@@ -119,7 +129,7 @@ export class WorkspacesStore {
|
|
|
119
129
|
view() {
|
|
120
130
|
return {
|
|
121
131
|
workspaces: this.data.workspaces.map((w) => {
|
|
122
|
-
const name = workspaceBasename(w.path) ?? w.path;
|
|
132
|
+
const name = workspaceBasename(w.path, this.platform) ?? w.path;
|
|
123
133
|
return { name, path: w.path, sessions: this.countSessions(w.path) };
|
|
124
134
|
}),
|
|
125
135
|
active_session: this.data.active_session,
|
|
@@ -130,19 +140,21 @@ export class WorkspacesStore {
|
|
|
130
140
|
const asked = rawPath.trim();
|
|
131
141
|
if (asked === "")
|
|
132
142
|
return badRequest("path must not be empty");
|
|
133
|
-
|
|
143
|
+
// W885 follow-up: "is this absolute" is a PLATFORM question, not `startsWith("/")`.
|
|
144
|
+
// On Windows every path is `C:\...`, so the old test rejected all of them.
|
|
145
|
+
if (!isAbsolutePath(asked, this.platform))
|
|
134
146
|
return badRequest(`path '${asked}' must be absolute`);
|
|
135
147
|
// W815-9: canonicalize before storing (see `normalizeWorkspacePath`).
|
|
136
|
-
const path = normalizeWorkspacePath(asked);
|
|
148
|
+
const path = normalizeWorkspacePath(asked, this.platform);
|
|
137
149
|
if (!isDirectory(path))
|
|
138
150
|
return badRequest(`path '${path}' is not an existing directory`);
|
|
139
|
-
const base = workspaceBasename(path);
|
|
151
|
+
const base = workspaceBasename(path, this.platform);
|
|
140
152
|
if (base === null)
|
|
141
153
|
return badRequest(`path '${path}' has no folder name`);
|
|
142
154
|
const existing = this.data.workspaces.find((w) => w.path === path);
|
|
143
155
|
if (existing !== undefined)
|
|
144
156
|
return conflict(`path '${path}' is already registered as workspace '${base}'`);
|
|
145
|
-
const clash = this.data.workspaces.find((w) => workspaceBasename(w.path) === base);
|
|
157
|
+
const clash = this.data.workspaces.find((w) => workspaceBasename(w.path, this.platform) === base);
|
|
146
158
|
if (clash !== undefined) {
|
|
147
159
|
return conflict(`workspace '${base}' already exists (folder '${path}' and '${clash.path}' share the same folder name; rename one folder first)`);
|
|
148
160
|
}
|
|
@@ -154,7 +166,7 @@ export class WorkspacesStore {
|
|
|
154
166
|
}
|
|
155
167
|
/** POST /api/workspaces/{name}/delete — deregister only. */
|
|
156
168
|
deregister(name) {
|
|
157
|
-
const idx = this.data.workspaces.findIndex((w) => workspaceBasename(w.path) === name);
|
|
169
|
+
const idx = this.data.workspaces.findIndex((w) => workspaceBasename(w.path, this.platform) === name);
|
|
158
170
|
if (idx < 0)
|
|
159
171
|
return notFound(`unknown workspace '${name}'`);
|
|
160
172
|
const [removed] = this.data.workspaces.splice(idx, 1);
|
|
@@ -178,20 +190,24 @@ export class WorkspacesStore {
|
|
|
178
190
|
}
|
|
179
191
|
/** POST /api/workspaces/{name}/rename — really renames the FOLDER. */
|
|
180
192
|
renameWorkspace(name, newName) {
|
|
181
|
-
const idx = this.data.workspaces.findIndex((w) => workspaceBasename(w.path) === name);
|
|
193
|
+
const idx = this.data.workspaces.findIndex((w) => workspaceBasename(w.path, this.platform) === name);
|
|
182
194
|
if (idx < 0)
|
|
183
195
|
return notFound(`unknown workspace '${name}'`);
|
|
184
196
|
const row = this.data.workspaces[idx];
|
|
185
197
|
if (row === undefined)
|
|
186
198
|
return notFound(`unknown workspace '${name}'`);
|
|
187
|
-
if (this.data.workspaces.some((w) => workspaceBasename(w.path) === newName)) {
|
|
199
|
+
if (this.data.workspaces.some((w) => workspaceBasename(w.path, this.platform) === newName)) {
|
|
188
200
|
return conflict(`workspace '${newName}' already exists`);
|
|
189
201
|
}
|
|
190
202
|
// W815-9: normalize a legacy row's path before deriving the sibling target.
|
|
191
|
-
const from = normalizeWorkspacePath(row.path);
|
|
203
|
+
const from = normalizeWorkspacePath(row.path, this.platform);
|
|
192
204
|
row.path = from;
|
|
193
|
-
|
|
194
|
-
|
|
205
|
+
// W885 follow-up: the sibling target is a PLATFORM question too. The old
|
|
206
|
+
// `lastIndexOf("/")` found no separator in `C:\Users\me\proj`, so the
|
|
207
|
+
// "parent" became `C:\Users\me\pro` and the rename moved the folder to a
|
|
208
|
+
// sibling of a NONEXISTENT directory.
|
|
209
|
+
const parent = parentDir(from, this.platform);
|
|
210
|
+
const target = joinPath(this.platform, parent, newName);
|
|
195
211
|
if (target !== row.path && isDirectory(target)) {
|
|
196
212
|
return conflict(`target '${target}' already exists; rename the folder first`);
|
|
197
213
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celestea/studio",
|
|
3
|
-
"version": "2.7.
|
|
3
|
+
"version": "2.7.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"@hono/node-server": "^2.1.1",
|
|
15
15
|
"hono": "^4.13.8",
|
|
16
|
-
"@celestea/agent-loop": "2.7.
|
|
17
|
-
"@celestea/
|
|
18
|
-
"@celestea/
|
|
19
|
-
"@celestea/
|
|
20
|
-
"@celestea/
|
|
21
|
-
"@celestea/tools": "2.7.
|
|
22
|
-
"@celestea/workers": "2.7.
|
|
16
|
+
"@celestea/agent-loop": "2.7.2",
|
|
17
|
+
"@celestea/llm": "2.7.2",
|
|
18
|
+
"@celestea/session": "2.7.2",
|
|
19
|
+
"@celestea/runtime": "2.7.2",
|
|
20
|
+
"@celestea/core": "2.7.2",
|
|
21
|
+
"@celestea/tools": "2.7.2",
|
|
22
|
+
"@celestea/workers": "2.7.2"
|
|
23
23
|
},
|
|
24
24
|
"files": [
|
|
25
25
|
"dist",
|
|
@@ -87,12 +87,12 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
|
|
|
87
87
|
`)}function Xf(e,t,n){let r=e.slice(1,-1).split(` · `),i=new Map;for(let e=1;e<r.length;e++){let t=r[e],n=t.indexOf(`=`);n>0&&i.set(t.slice(0,n),t.slice(n+1))}let a=r[1]??``,o=If.includes(a)?a:`user`,s=/^第 (\d+) 轮$/.exec(r[2]??``),c=r[3]??``,l=i.get(`fmt`),u=l!==void 0&&Lf.includes(l)?l:void 0,d=i.get(`file`),f=/^(\d+)-(\d+)$/.exec(i.get(`lines`)??``);return{id:`q`+String(n+1),source:{kind:o,session:``,turn:s?Number(s[1]):void 0,label:c},text:t,hash:``,bytes:Rf(t),truncated:i.get(`trunc`)===`1`,...u?{format:u}:{},...d===void 0?{}:{filePath:decodeURIComponent(d)},...f?{lineRange:{startLine:Number(f[1]),endLine:Number(f[2])}}:{}}}function Zf(e){let t=e.split(`
|
|
88
88
|
`),n=[],r=-1,i=0;for(;i<t.length;){if(t[i]!==`===== CELESTEA QUOTE =====`){i+=1;continue}let e=t[i+1];if(e===void 0||!/^\[引用 .*\]$/.test(e)){i+=1;continue}let a=i+2,o=[],s=!1;for(;a<t.length;){let e=t[a];if(e===`===== CELESTEA QUOTE =====`){s=!0;break}if(!e.startsWith(`> `))break;o.push(Kf(e.slice(2))),a+=1}if(!s){i+=1;continue}r<0&&(r=i),n.push(Xf(e,o.join(`
|
|
89
89
|
`),n.length)),i=a+1}return r<0?{quotes:[],rest:e}:{quotes:n,rest:t.slice(0,r).join(`
|
|
90
|
-
`).replace(/\s+$/,``)}}var Qf={selected:[],custom:``};function $f(e,t){return e[t]??Qf}function ep(e,t,n){return n?{selected:e.selected.includes(t)?e.selected.filter(e=>e!==t):[...e.selected,t],custom:e.custom}:{selected:[t],custom:e.custom}}function tp(e,t){return{selected:[...e.selected],custom:t}}function np(e,t){let n=[];for(let r of e){let e=$f(t,r.id);e.selected.length===0&&e.custom.trim()===``&&n.push(r.id)}return n}function rp(e,t){let n=[];for(let r of e){let e=$f(t,r.id),i=e.custom.trim();if(e.selected.length===0&&i===``)continue;let a={id:r.id,selected:[...e.selected]};i!==``&&(a.custom=i),n.push(a)}return n}function ip(e){let t=[];for(let n of e){let e=[...n.selected],r=(n.custom??``).trim();r!==``&&e.push(w(`chat.question.customQuote`,{text:r})),e.length>0&&t.push(e.join(w(`chat.question.answerSep`)))}return t.join(w(`chat.question.answerJoin`))}function ap(e,t){return typeof e.remaining_ms==`number`&&Number.isFinite(e.remaining_ms)?e.remaining_ms:typeof e.expires_at==`number`&&Number.isFinite(e.expires_at)?e.expires_at-t:null}function op(e,t){let n=ap(e,t);return n===null?null:t+n}function sp(e){if(e===null)return``;if(e<=0)return w(`chat.question.timedOut`);let t=Math.floor(e/1e3);if(t<60)return w(`chat.question.seconds`,{n:t});if(t<3600){let e=Math.floor(t/60),n=t%60;return w(`chat.question.clock`,{m:e,s:(n<10?`0`:``)+n})}return w(`chat.question.hoursMinutes`,{h:Math.floor(t/3600),m:Math.floor(t%3600/60)})}function cp(e){return e!==null&&e<=0}function lp(e){return typeof e==`string`?e:null}function up(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.label);if(n===null||n===``)return null;let r=lp(t.description);return r===null?{label:n}:{label:n,description:r}}function dp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.kind);return n===null||n===``?null:{...t,kind:n}}function fp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.id),r=lp(t.question);if(n===null||n===``||r===null||r===``)return null;let i={id:n,question:r},a=lp(t.header);a!==null&&(i.header=a);let o=lp(t.detail);o!==null&&(i.detail=o);let s=Array.isArray(t.options)?t.options.map(up).filter(e=>e!==null):[];s.length>0&&(i.options=s),t.multi_select===!0&&(i.multi_select=!0);let c=dp(t.intent);return c!==null&&(i.intent=c),i}function pp(e){return Array.isArray(e)?e.map(fp).filter(e=>e!==null):[]}function mp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.id);if(n===null||n===``)return null;let r=pp(t.questions);if(r.length===0)return null;let i={id:n,questions:r},a=lp(t.session);a!==null&&(i.session=a);for(let e of[`expires_at`,`timeout_ms`,`remaining_ms`]){let n=t[e];typeof n==`number`&&Number.isFinite(n)&&(i[e]=n)}return t.expired===!0&&(i.expired=!0),i}function hp(e){return e===404||e===409}function gp(e){return e.content}function _p(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=lp(e.id),i=e.selected;if(r===null||!Array.isArray(i))continue;let a=i.filter(e=>typeof e==`string`),o=lp(e.custom),s={id:r,selected:a};o!==null&&o!==``&&(s.custom=o),t.push(s)}return t}function vp(e){let t=new Map,n=[];for(let r of e){if(r.role!==`question`)continue;let e=typeof r.question_id==`string`?r.question_id:``;if(e!==``){if(r.kind===`question`){if(t.has(e))continue;let i=pp(gp(r));if(i.length===0)continue;let a={id:e,questions:i,settled:!1,timedOut:!1,answerText:``};typeof r.question_expires_at==`number`&&(a.expiresAt=r.question_expires_at),t.set(e,a),n.push(e);continue}if(r.kind===`answer`){let n=t.get(e);if(n===void 0)continue;n.settled=!0,n.timedOut=r.question_timed_out===!0,n.answerText=n.timedOut?``:ip(_p(gp(r)))}}}return n.map(e=>t.get(e))}function yp(e,t,n,r){let i=N(`label`,`q-opt`);r!==void 0&&r===n.label&&i.classList.add(`is-approve`);let a=N(`input`,`q-opt-input`);a.type=t.multi_select===!0?`checkbox`:`radio`,a.name=`q-`+e.id+`-`+t.id,a.value=n.label;let o=N(`span`,`q-opt-text`);return o.appendChild(N(`span`,`q-opt-label`,n.label)),n.description!==void 0&&n.description!==``&&o.appendChild(N(`span`,`q-opt-desc`,n.description)),i.appendChild(a),i.appendChild(o),a.addEventListener(`change`,()=>{e.picks[t.id]=ep($f(e.picks,t.id),n.label,t.multi_select===!0),e.onEdit()}),e.controls.push(a),i}function bp(e,t){let n=N(`div`,`q-item`);n.appendChild(N(`div`,`q-question`,t.question)),t.detail!==void 0&&t.detail!==``&&n.appendChild(N(`div`,`q-detail`,t.detail));let r=t.options??[];if(r.length>0){let i=N(`div`,`q-options`),a=t.intent?.approve;for(let n of r)i.appendChild(yp(e,t,n,a));n.appendChild(i)}let i=N(`input`,`q-custom-input`);i.type=`text`,i.autocomplete=`off`,i.placeholder=r.length>0?w(`chat.question.customPlaceholder`):w(`chat.question.customRequired`),i.addEventListener(`input`,()=>{e.picks[t.id]=tp($f(e.picks,t.id),i.value),e.onEdit()}),e.controls.push(i);let a=N(`div`,`q-custom`);return a.appendChild(i),n.appendChild(a),n}function xp(e){return e===`done`?w(`chat.question.answered`):e===`expired`?w(`chat.question.expired`):e===`closed`?w(`chat.question.closed`):``}var Sp=new WeakMap,Cp=new Set,wp=null;Vr((e,t)=>{!t&&Sr(e)===void 0&&Dp(e)});function Tp(e){let t=Sp.get(e.el);return t||(t=new Map,Sp.set(e.el,t)),t}function Ep(e){return e.root.isConnected?!0:e.root.parentElement!==null&&Sr(e.paneId)?.el===e.root.parentElement}function Dp(e){for(let t of Array.from(Cp))t.paneId===e&&Cp.delete(t);Op()}function Op(){Cp.size===0&&wp!==null&&(window.clearInterval(wp),wp=null)}function kp(e,t){let n=Tp(e),r=n.get(t);return r?Ep(r)?r:(n.delete(t),Cp.delete(r),null):null}function Ap(){let e=Date.now();for(let t of Array.from(Cp)){if(!Ep(t)){Cp.delete(t);continue}t.state===`pending`&&jp(t,e)}Op()}function jp(e,t){if(e.deadline===null){e.timer.textContent=``;return}let n=e.deadline-t;e.timer.textContent=sp(n),cp(n)&&e.state===`pending`&&Mp(e,`expired`)}function Mp(e,t,n){e.state=t,(t===`done`||t===`closed`)&&(e.settled=!0),e.card.dataset.state=t;let r=t!==`pending`;for(let t of e.controls)t.disabled=r;e.submit.disabled=r,e.submit.textContent=w(`chat.question.submit`),e.timer.textContent=r?``:e.timer.textContent,e.result.textContent=r?n??xp(t):``}function Np(e,t){if(t.state!==`pending`)return;if(t.deadline!==null&&Date.now()>=t.deadline){Mp(t,`expired`);return}let n=np(t.questions,t.picks);if(n.length>0){t.hint.textContent=w(`chat.question.missing`,{n:n.length});return}Pp(e,t)}async function Pp(e,t){let n=rp(t.questions,t.picks),r=e.id===``?void 0:e.id;Mp(t,`done`,w(`chat.question.answeredWith`,{answer:ip(n)})),t.hint.textContent=``;try{await j.answerQuestion(t.id,n,r)}catch(e){if(e instanceof D&&hp(e.status)){Mp(t,`closed`),t.hint.textContent=``;return}t.settled=!1,Mp(t,`pending`),t.hint.textContent=w(`chat.question.submitFailed`,{reason:O(e)}),jp(t,Date.now())}}function Fp(e,t){let n=N(`div`,`q-head`),r=N(`div`,`q-title`),i=t[0]?.header;r.textContent=i!==void 0&&i!==``?i:w(`chat.question.needDecision`);let a=t[0]?.intent?.kind;return a!==void 0&&a!==``&&r.appendChild(N(`span`,`q-intent`,a===`plan-review`?w(`chat.question.planReview`):a)),n.appendChild(r),n.appendChild(e.timer),n}function Ip(e,t){let n=N(`div`,`mcol q-col`),r=N(`div`,`msg question`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.question.title`))),i.appendChild(N(`span`,null,xe())),r.appendChild(i);let a=N(`div`,`bubble question-bubble`),o=N(`div`,`q-card`);o.dataset.state=`pending`;let s=N(`button`,`q-submit btn btn-accent`,w(`chat.question.submit`));s.type=`button`;let c={id:t.id,paneId:e.id,root:n,card:o,timer:N(`div`,`q-timer`),hint:N(`div`,`q-hint`),result:N(`div`,`q-result`),submit:s,controls:[],questions:t.questions,picks:{},deadline:null,state:`pending`,settled:!1,onEdit:()=>{c.hint.textContent=``}};o.appendChild(Fp(c,t.questions));let l=N(`div`,`q-items`);for(let e of t.questions)l.appendChild(bp(c,e));o.appendChild(l);let u=N(`div`,`q-actions`);return u.appendChild(c.submit),o.appendChild(u),o.appendChild(c.hint),o.appendChild(c.result),c.submit.addEventListener(`click`,()=>Np(e,c)),a.appendChild(o),r.appendChild(a),n.appendChild(r),c}function Lp(e,t){return co(e),e.el.appendChild(t.root),Tp(e).set(t.id,t),Cp.add(t),wp===null&&(wp=window.setInterval(Ap,1e3)),t}function Rp(e,t){t.questions.length>0&&(e.questions=t.questions),e.deadline=op(t,Date.now());let n=!cp(ap(t,Date.now()));return e.state===`expired`&&!e.settled&&n&&Mp(e,`pending`),e.state===`pending`&&(e.hint.textContent=``,jp(e,Date.now())),e}function zp(e){let t=mp(e),n=t?.questions;if(!t||n===void 0||n.length===0)return null;let r={id:t.id,questions:n};return t.expires_at!==void 0&&(r.expires_at=t.expires_at),t.timeout_ms!==void 0&&(r.timeout_ms=t.timeout_ms),t.remaining_ms!==void 0&&(r.remaining_ms=t.remaining_ms),r}function Bp(e,t){let n=zp(t);if(!n)return null;let r=kp(e,n.id);if(r)return Rp(r,n);let i=Rp(Ip(e,n),n);return Lp(e,i),W(e,!0),i}async function Vp(e){if(e.id===``)return;let t=e.id,n;try{n=await j.questions(t)}catch{return}let r=0;for(let t of n.questions??[]){let n=zp(t);if(!n)continue;let i=kp(e,n.id);if(i){Rp(i,n);continue}Lp(e,Rp(Ip(e,n),n)),r+=1}r>0&&W(e,!0)}function Hp(e,t,n){let r=Ip(e,{id:t.id,questions:t.questions});return n?(n.appendChild(r.root),Tp(e).set(r.id,r)):Lp(e,r),t.settled&&!t.timedOut?Mp(r,`done`,w(`chat.question.answeredWith`,{answer:t.answerText})):t.settled?(r.settled=!0,Mp(r,`expired`)):Mp(r,`expired`,w(`chat.question.interrupted`)),r.root}function Up(){for(let e of Cr())Vp(e)}function Wp(e,t){e.on(`question`,e=>{try{Bp(t(e),e)}catch(e){console.warn(`SSE question`,e)}}),e.onConn(e=>{e===`online`&&Up()})}var Gp=200;function Kp(e,t){let n=e.dedup;if(n.tail?.role!==`assistant`)return n.tail=null,t===``?null:t;n.guardActive||(n.guardActive=!0,n.guardBuf=``,n.guardAll=!1),n.guardBuf+=t;let r=n.tail.content??``;if(r.startsWith(n.guardBuf))return n.guardBuf===r&&(n.guardAll=!0),null;let i=n.guardBuf;return n.guardActive=!1,n.guardAll=!1,n.tail=null,i===``?null:i}function qp(e,t){let n=e.dedup;if(!n.guardActive)return!1;n.guardActive=!1;let r=n.guardAll||typeof t==`string`&&t!==``&&n.tail?.role===`assistant`&&t===(n.tail.content??``);return n.guardAll=!1,n.tail=null,r}function Jp(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Yp(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg tool`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.tool.title`))),r.appendChild(i);let a=N(`div`,`bubble`),o=N(`div`,`content restore-tool`);o.textContent=e,a.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n)}function Xp(e,t,n){if(t.kind===`call`){e.histToolStep+=1;let r=t.tool_call_id??`call_`+e.histToolStep,i=xh({step:e.histToolStep,name:t.tool_name??`tool`,argsText:Jp(t.tool_args),desc:_h(t.tool_args)});n.appendChild(i.col),e.restoreOps.set(r,i);return}let r=t.tool_call_id??``,i=e.restoreOps.get(r);if(i){let n=!!t.tool_error&&t.tool_error!==``;Sh(i,n?String(t.tool_error):Jp(t.tool_value),n,t.tool_value),e.restoreOps.delete(r);return}Yp(w(`shell.restore.orphanResult`)+(t.tool_error?String(t.tool_error):Jp(t.tool_value)),n)}function Zp(e){return e.kind===`steering`?`steering`:e.kind===`queued`?`queued`:`user`}function Qp(e,t,n,r){let i=String(t.content??``),a=typeof t.question_id==`string`?t.question_id:``;if(t.role===`question`){let i=a===``?void 0:r.get(a);i!==void 0&&t.kind===`question`&&Hp(e,i,n);return}if(t.role===`inbox`||t.kind===`inbox`){mf(e,i,{source:t.source,kind:t.kind,into:n});return}if(t.role===`user`){let r=Zf(i);ff(e,r.rest,{kind:Zp(t),attachments:of(t.attachments),quotes:r.quotes,into:n});return}if(t.role===`assistant`){if(i.trim()===``)return;let t=Ru(e,n);t.text=i,zu(e,t);return}if(t.role===`thinking`){$p(i,n);return}Xp(e,t,n)}function $p(e,t){t.appendChild(Df({text:e,collapsed:!0}).root)}function em(e,t){e.el.querySelector(`.restore-note`)||e.el.appendChild(N(`div`,`restore-note`,t))}async function tm(e,t){let n;try{n=await j.messages(e.id)}catch{e.streaming||em(e,w(`shell.restore.unavailable`));return}if(t&&!t())return;let r=n.messages??[];if(e.streaming)return;eo(e),e.restoreOps.clear(),e.histToolStep=0;let i=document.createElement(`div`);r.length>Gp&&i.appendChild(N(`div`,`restore-fold`,w(`shell.restore.folded`,{n:Gp})));let a=r.length>Gp?r.slice(r.length-Gp):r,o=new Map(vp(a).map(e=>[e.id,e]));for(let t of a)Qp(e,t,i,o);if(e.restoreOps.size){for(let t of e.restoreOps.values())Sh(t,w(`shell.restore.noResult`),!1);e.restoreOps.clear()}if(a.length){let e=N(`div`,`live-sep`);e.appendChild(N(`span`,null,w(`shell.restore.sessionStart`))),e.title=w(`shell.restore.earlier`),i.appendChild(e)}if(!t||t()){if(e.el.replaceChildren(...i.childNodes),!a.length){lo(e);let t=N(`div`,`live-sep`);t.appendChild(N(`span`,null,w(`shell.restore.sessionStart`))),e.el.appendChild(t)}e.dedup.tail=a.length?a[a.length-1]??null:null,e.dedup.guardActive=!1,e.dedup.guardBuf=``,e.dedup.guardAll=!1,e.restored=!0,to(e),W(e,!0),Vp(e)}}async function nm(){try{let e=((await j.sessions()).sessions??[]).find(e=>e.active===!0);if(e?.id)return e.id}catch{}try{let e=await j.workspaces();if(e.active_session)return e.active_session}catch{}try{if(((await j.sessions()).sessions??[]).some(e=>e.id===`cli-main`))return`cli-main`}catch{}return null}async function rm(){let e=await nm();if(e===null){let e=B();e&&!e.streaming&&em(e,w(`shell.restore.noActive`));return}let t=Nr(e);!t.restored&&!t.streaming?await tm(t):Vp(t)}var im=null;function am(){im||(im=document.createElement(`div`),im.className=`switch-progress`,document.body.appendChild(im))}function om(){im?.remove(),im=null}function sm(e,t){let n=wr(e,t?.kind,t?.title);if(Mr(e),!n.streaming&&!n.restored){let e=++n.restoreSeq;am(),tm(n,()=>e===n.restoreSeq).finally(()=>{e===n.restoreSeq&&om()})}else Vp(n);return n}var cm=null,lm=null,um=null,dm=null,fm=[],pm=[],mm=``;function hm(e){let t=(e.wid??``).trim();if(t!==``)return t;let n=(e.title??``).trim(),r=/^(W\d+)/.exec(n);if(r&&r[1])return r[1];let i=e.id??``,a=i.lastIndexOf(`-`);return a>=0?i.slice(a+1):i}function gm(e){return(e.title??``).trim().replace(/^W\d+\s*[·::-]\s*/,``)||hm(e)}function _m(e){return{id:e.id??``,wid:hm(e),title:gm(e),model:String(e.model??``),status:String(e.status??``)}}function vm(e){let t=e.parentSessionId??e.parent_session??e.parent;return typeof t==`string`&&t.trim()!==``?t.trim():null}function ym(e){return e.kind===`worker`||(e.id??``).startsWith(`worker:`)}function bm(e,t){let n=e.filter(ym);if(t===``)return n.map(_m);let r=n.filter(e=>{let n=vm(e);if(n!==null)return n===t;let r=e.id??``;return(r.startsWith(`worker:`)?r.slice(7):r).startsWith(t+`-`)});return(r.length>0?r:n).map(_m)}function xm(e){let t=Fr(e.id),n=e.status!==``&&e.status!==`RUNNING`,r=N(`button`,`ws-strip-row`+(t?` running`:``)+(n?` settled`:``));return r.type=`button`,r.dataset.id=e.id,r.appendChild(N(`span`,`sess-dot`+(t?` busy`:``))),r.appendChild(N(`span`,`ws-strip-wid`,e.wid)),r.appendChild(N(`span`,`ws-strip-title`,e.title)),r.appendChild(N(`span`,`ws-strip-meta`,e.status===``?w(t?`shell.tree.running`:`shell.tree.idle`):e.status)),r.title=e.wid+` · `+e.title+(e.model?` · `+e.model:``)+w(`shell.worker.stripHint`),r.addEventListener(`click`,()=>{sm(e.id,{kind:`worker`,title:e.title})}),r}function Sm(){if(lm===null||um===null||cm===null||!cm.isConnected)return;if(pm.length===0){cm.classList.add(`hidden`),lm.replaceChildren(),um.textContent=``;return}cm.classList.remove(`hidden`);let e=document.createDocumentFragment();for(let t of pm)e.appendChild(xm(t));lm.replaceChildren(...Array.from(e.childNodes)),um.textContent=String(pm.length);let t=pm.filter(e=>Fr(e.id)).length;dm!==null&&(dm.textContent=t>0?w(`shell.worker.stripTitle`,{n:t}):w(`shell.worker.stripTitlePlain`))}function Cm(e,t){e!=null&&(fm=e);let n=t===void 0?B():t;mm=n===null?``:n.id,pm=bm(fm,mm),Sm()}function wm(e){let t=e.id??``;if(t===``||cm===null)return;let n=_m(e),r=pm.findIndex(e=>e.id===t);r>=0?pm[r]={...pm[r],...n}:pm=[...pm,n],Sm()}function Tm(){if(cm!==null)return cm;let e=document.getElementById(`main`);if(!e)return null;let t=N(`div`,`ws-strip hidden`);t.id=`wsStrip`;let n=N(`div`,`ws-strip-head`);return dm=N(`span`,`ws-strip-lead`,w(`shell.worker.stripTitlePlain`)),um=N(`span`,`ws-strip-count`,``),lm=N(`div`,`ws-strip-list`),n.appendChild(dm),n.appendChild(um),t.appendChild(n),t.appendChild(lm),e.appendChild(t),cm=t,cm}var Em=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`svg`]),Dm=new Set([`md`,`markdown`,`mdx`]),Om=new Set([`diff`,`patch`]),km=new Set(`ts.tsx.js.jsx.mjs.cjs.py.rb.go.rs.java.c.h.cc.cpp.hpp.cs.php.sh.bash.zsh.sql.html.htm.css.scss.less.xml.json.jsonl.yaml.yml.toml.ini.cfg.conf.env.log.tex.rst.csv.tsv.txt.text`.split(`.`)),Am=new Set([...Em,...Dm,...Om,`json`,`jsonl`,`yaml`,`yml`,`toml`,`ini`,`cfg`,`conf`,`env`,`log`,`csv`,`tsv`,`txt`,`text`]),jm=new Set([`read_file`]),Mm=new Set([`read_file`,`write_file`,`list_dir`]);function Nm(e){let t=(e.split(/[?#]/)[0]??``).replace(/^.*[\\/]/,``),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function Pm(e){let t=Nm(e);return Em.has(t)?`image`:Dm.has(t)?`markdown`:Om.has(t)?`diff`:km.has(t)?`code`:`unknown`}function Fm(e){let t=e.trim();if(t===``||/\s/.test(t)||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith(`#`))return!1;let n=Nm(t);return Em.has(n)||Dm.has(n)||Om.has(n)||km.has(n)?t.includes(`/`)||t.includes(`\\`)||t.startsWith(`.`)?!0:Am.has(n):!1}function Im(e){if(typeof e==`string`){let t=e.trim();if(!t.startsWith(`{`))return null;try{return Im(JSON.parse(t))}catch{return null}}return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Lm(e,t){if(!Mm.has(e))return null;let n=Im(t),r=n&&typeof n.path==`string`?n.path.trim():``;return r===``||!Fm(r)?null:{path:r,kind:Pm(r),source:`tool`}}function Rm(){let e=`http://www.w3.org/2000/svg`,t=document.createElementNS(e,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.3`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`);let n=document.createElementNS(e,`path`);return n.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v7a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z`),t.appendChild(n),t}function zm(e){let t=N(`div`,`modal-scrim`),n=N(`div`,`modal-card ws-fs`);n.appendChild(N(`div`,`modal-card-title`,e.title)),e.note&&n.appendChild(N(`div`,`side-note`,e.note));let r=``,i=N(`div`,`ws-fs-crumbs`),a=N(`div`,`ws-fs-tree`),o=N(`div`,`ws-fs-addr`),s=N(`input`,`cfg-input`);s.placeholder=w(`chat.fsbrowse.pathPlaceholder`),s.value=``;let c=N(`button`,`btn btn-soft btn-mini`,w(`chat.fsbrowse.go`));c.type=`button`,o.appendChild(s),o.appendChild(c);let l=N(`div`,`ws-fs-status`);n.appendChild(i),n.appendChild(a),n.appendChild(o),n.appendChild(l);function u(e){let t=document.createElement(`div`),n=e.split(`/`).filter(Boolean),r=N(`button`,`ws-fs-crumb`+(n.length?``:` cur`),`/`);r.type=`button`,r.title=w(`chat.fsbrowse.root`),r.addEventListener(`click`,()=>void f(`/`)),t.appendChild(r);let a=``;for(let e=0;e<n.length;e++){let r=n[e];a+=`/`+r;let i=N(`button`,`ws-fs-crumb`+(e===n.length-1?` cur`:``),r);i.type=`button`;let o=a;i.addEventListener(`click`,()=>void f(o)),t.appendChild(i)}i.replaceChildren(...t.childNodes)}function d(e){i.replaceChildren(...e)}async function f(t){let n=Array.from(i.childNodes);l.className=`ws-fs-status`,l.textContent=``,u(t),s.value=t,r=t;let o;try{o=await j.fsBrowse(t)}catch{d(n),l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.unavailable`);let t=document.createElement(`div`);t.appendChild(N(`div`,`side-note`,e.fallbackNote??w(`chat.fsbrowse.fallback`))),a.replaceChildren(...t.childNodes);return}if(o.error){d(n),l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.failed`,{reason:O(o.error,w(`chat.fsbrowse.manualPath`))});return}l.textContent=w(`chat.fsbrowse.selected`,{path:o.path||`/`}),l.className=`ws-fs-status ok`,r=o.path??t,s.value=o.path??t,u(o.path??t);let c=document.createElement(`div`),p=o.dirs??[];p.length||c.appendChild(N(`div`,`side-note`,w(`chat.fsbrowse.noSubdirs`)));for(let e of p){let t=N(`div`,`ws-fs-dir`),n=N(`span`,`ws-fs-dir-icon`);n.appendChild(Rm()),t.appendChild(n),t.appendChild(N(`span`,`ws-fs-dir-name`,e)),t.addEventListener(`click`,()=>{f((r?r.replace(/\/+$/,``):``)+`/`+e)}),c.appendChild(t)}a.replaceChildren(...c.childNodes)}c.addEventListener(`click`,()=>{let e=s.value.trim();e&&f(e)}),s.addEventListener(`keydown`,e=>{e.key===`Enter`&&c.click()});let p=N(`div`,`modal-card-actions`),m=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));m.type=`button`;let h=N(`button`,`btn btn-accent`,e.confirmLabel);h.type=`button`;let g=null,_=!1,v=null,y=()=>{_||(_=!0,g&&(F(g),g=null),t.remove(),e.onClose?.(v))};g=P(y),m.addEventListener(`click`,y),h.addEventListener(`click`,()=>{let t=r||s.value.trim();if(!t){l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.needPath`),s.focus();return}v=t,e.onPick(t,{status:l,close:y,setBusy:t=>{h.disabled=t,h.textContent=t?e.busyLabel:e.confirmLabel}})}),p.appendChild(m),p.appendChild(h),n.appendChild(p),t.appendChild(n),document.body.appendChild(t),f(``)}function Bm(e,t){return new Promise(n=>{let r=null,i=!1,a=e=>{i||(i=!0,n(e))};zm({title:e,note:t,confirmLabel:w(`chat.preview.chooseDir`),busyLabel:w(`chat.preview.busy`),onPick:(e,t)=>{r=e,t.close()},onClose:()=>a(r)})})}var Vm={ts:`typescript`,tsx:`typescript`,js:`javascript`,jsx:`javascript`,mjs:`javascript`,cjs:`javascript`,json:`json`,jsonl:`json`,md:`markdown`,markdown:`markdown`,mdx:`markdown`,py:`python`,go:`go`,java:`java`,c:`cpp`,h:`cpp`,cc:`cpp`,cpp:`cpp`,hpp:`cpp`,sh:`bash`,bash:`bash`,zsh:`bash`,sql:`sql`,html:`xml`,htm:`xml`,xml:`xml`,css:`css`,scss:`css`,less:`css`,yaml:`yaml`,yml:`yaml`};function Hm(e,t){let n=N(`pre`,`preview-code`),r=N(`code`);r.textContent=e;let i=Vm[Nm(t)];return i&&(r.className=`language-`+i),n.appendChild(r),i&&pu(n),n}function Um(e){let t=N(`div`,`preview-md`);return fl(t,e),t}function Wm(e,t){let n=N(`div`,`preview-img`),r=N(`img`);return r.src=e,r.alt=t,n.appendChild(r),n}function Gm(e){return e.startsWith(`@@`)?` hunk`:e.startsWith(`+`)&&!e.startsWith(`+++`)?` add`:e.startsWith(`-`)&&!e.startsWith(`---`)?` del`:``}function Km(e){let t=e.split(`
|
|
91
|
-
`).map(e=>`<span class="preview-diff-line`+
|
|
92
|
-
`),n=N(`div`,`preview-diff`);return n.replaceChildren(...ul(t)),n}function
|
|
93
|
-
`+(n?.textContent??``);navigator.clipboard.writeText(r).catch(()=>{})}),s.appendChild(u);let d=N(`span`,`toolcard-fold`);d.setAttribute(`data-fold`,ph),d.innerHTML=hh,s.appendChild(d),o.appendChild(s),a.appendChild(o);let f=N(`div`,`toolcard-body`),p=N(`div`,`toolcard-args-preview`),m=bh(e.argsText);p.textContent=m?w(`chat.tool.args`,{text:m}):w(`chat.tool.argsNone`),f.appendChild(p),f.appendChild(N(`pre`,`tool-args`,e.argsText));let h=N(`div`,`toolcard-result-preview`);h.textContent=``,f.appendChild(h);let g=Lm(e.name,e.argsText);if(g!==null&&jm.has(e.name)){let e=g,t=N(`button`,`toolcard-preview`,w(`chat.tool.preview`));t.type=`button`,t.title=w(`chat.tool.previewHint`),t.addEventListener(`click`,t=>{t.preventDefault();let n=a.querySelector(`.tool-out`);uh({candidate:e,load:async()=>n?.textContent??null})}),f.appendChild(t)}return a.appendChild(f),a.addEventListener(`toggle`,()=>{o.setAttribute(`aria-expanded`,a.open?`true`:`false`),d.setAttribute(`data-fold`,a.open?mh:ph)}),i.appendChild(a),n.appendChild(i),t.appendChild(n),{toolName:e.name,col:t,card:a,label:l.querySelector(`.ts-label`)??l,resultPv:h,body:f}}function Sh(e,t,n,r){e.card.classList.remove(`running`),e.card.classList.add(n?`err`:`ok`),e.label.textContent=w(n?`chat.tool.failed`:`chat.tool.done`);let i=bh(t);e.resultPv.textContent=i?w(`chat.tool.result`,{text:i}):``,i&&e.resultPv.classList.add(`has`),e.body.querySelector(`.tool-out`)||e.body.appendChild(N(`pre`,`tool-out`+(n?` err-c`:``),t));let a=sf(r);a.length>0&&!e.body.querySelector(`.attach-grid`)&&e.body.appendChild(Bu(of(a)))}function Ch(e,t,n){e.step+=1;let r=xh({step:e.step,name:String(t.name||`tool`),argsText:yh(t.args),desc:_h(t.args)});return(n??e.el).appendChild(r.col),n||W(e),e.ops.set(String(t.id),r),r.col}function wh(e,t){if(e!==`spawn_worker`||t.ok===!1)return;let n=t.value;if(typeof n!=`object`||!n)return;let r=n,i=typeof r.sessionId==`string`?r.sessionId:``;if(i===``)return;let a=typeof r.wid==`string`?r.wid:``,o=typeof r.title==`string`?r.title:``;wm({id:`worker:`+i,kind:`worker`,...a===``?{}:{wid:a},...o===``?{}:{title:o},workspace:`engine`})}function Th(e,t){wh(e.ops.get(String(t.id))?.toolName??``,t);let n=e.ops.get(String(t.id));if(!n)return;let r=t.ok===!1||!!t.error,i=r?w(`chat.tool.failed`):t.decision===`deny`?w(`chat.tool.denied`):t.decision===`ask`?w(`chat.tool.ask`):w(`chat.tool.done`);Sh(n,t.error?String(t.error):yh(t.value),r||t.decision===`deny`),n.label.textContent=i,W(e)}var Eh=null;function Dh(){Eh&&Vu(Eh,Yd(),e=>{Zd(e),Dh()},()=>Dh())}function Oh(e,t){Eh=N(`div`,`attach-tray hidden`);let n=t??e;n===e?e.appendChild(Eh):n.parentElement?.insertBefore(Eh,n)??e.insertBefore(Eh,e.firstChild)}var kh=new Map,Ah=null,jh=null,Mh=0;function Nh(){return B()?.id??``}function Ph(e){return kh.get(e)??[]}function Fh(){if(!Ah||!jh)return;let e=jh.getBoundingClientRect().height;if(e<=0)return;let t=jh.querySelector(`.attach-tray`),n=t?t.offsetHeight:0;Ah.style.bottom=e+n+`px`}function Ih(e,t){let n=N(`div`,`quote-chip`);n.appendChild(N(`span`,`quote-chip-src`,e.source.label+(e.truncated?w(`chat.user.truncatedSuffix`):``)));let r=e.text.replace(/\s+/g,` `).trim();n.appendChild(N(`span`,`quote-chip-text`,r===``?w(`chat.quote.empty`):r.slice(0,40))),n.appendChild(N(`span`,`quote-chip-bytes`,String(e.bytes)+` B`));let i=N(`button`,`quote-chip-remove`,`×`);return i.type=`button`,i.title=w(`chat.quote.removeHint`),i.setAttribute(`aria-label`,w(`chat.quote.removeAria`,{label:e.source.label})),i.addEventListener(`click`,()=>t(e)),n.appendChild(i),n}function Lh(){if(!Ah)return;let e=Ph(Nh());if(e.length===0){Ah.classList.add(`hidden`),Ah.replaceChildren();return}Ah.classList.remove(`hidden`),Fh();let t=document.createElement(`div`);for(let n of e)t.appendChild(Ih(n,Rh));Ah.replaceChildren(...Array.from(t.childNodes)),Fh()}function Rh(e){let t=Nh(),n=Ph(t),r=n.indexOf(e);r>=0&&(n.splice(r,1),kh.set(t,n)),Lh()}function zh(e=Nh()){let t=Ph(e);return kh.set(e,[]),Nh()===e&&Lh(),t}function Bh(e,t){let n=Ph(e),r=new Set(n.map(e=>Uf(e))),i=t.filter(e=>!r.has(Uf(e)));kh.set(e,[...i,...n]),Nh()===e&&Lh()}async function Vh(e){let t=Nh(),n=Bf(e.text,Pf),r=await Hf(n.text),i=Ph(t),a=r===``?`x:`+n.text:r;if(i.some(e=>Uf(e)===a))return`duplicate`;if(i.length>=8)return`full`;let o=Ff-i.reduce((e,t)=>e+t.bytes,0);if(o<256)return`full`;let s=Bf(e.text,Math.min(Pf,o)),c=Wf({id:`q`+String(++Mh),source:e.source,text:s.text,hash:r,range:e.range,format:e.format,filePath:e.filePath,lineRange:e.lineRange});return c.truncated=s.truncated,i.push(c),kh.set(t,i),Nh()===t&&Lh(),`added`}function Hh(e,t){Ah||(jh=t??e,Ah=N(`div`,`quote-tray hidden`),Ah.id=`quoteTray`,jh.appendChild(Ah),Br(()=>Lh()))}var Uh=[];function Wh(e){let t=Uh.findIndex(t=>t.name===e.name);t>=0?Uh[t]=e:Uh.push(e)}function Gh(){return Uh}var Kh=3e4;function qh(e){return e.signal!==null&&e.signal!==``?w(`chat.run.signal`,{signal:e.signal}):e.exit_code===null?w(`chat.run.exitUnknown`):w(`chat.run.exit`,{code:e.exit_code,status:e.exit_code===0?w(`chat.run.success`):w(`chat.run.failure`)})}function Jh(e,t,n){if(t===``)return null;let r=N(`div`,`exec-stream `+n);return r.appendChild(N(`div`,`exec-stream-label`,e)),r.appendChild(N(`pre`,`exec-stream-body`,t)),r}function Yh(e){if(!e)return``;let t=[];return e.provider&&t.push(e.provider),t.push(e.net_isolated===!0?w(`chat.run.netIsolated`):w(`chat.run.netOnline`)),e.tmp_private===!0&&t.push(w(`chat.run.tmpPrivate`)),e.seccomp===!0&&t.push(w(`chat.run.seccomp`)),t.join(` · `)}function Xh(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.run.cmd`))),i.appendChild(N(`span`,null,xe())),r.appendChild(i);let a=N(`div`,`bubble exec-bubble`);return a.appendChild(N(`pre`,`exec-cmd`,t)),r.appendChild(a),n.appendChild(r),e.el.appendChild(n),to(e),n}function Zh(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec exec-note`),i=N(`div`,`bubble info-bubble`);i.appendChild(N(`div`,`content info-content`,t)),r.appendChild(i),n.appendChild(r),e.el.appendChild(n),to(e)}function Qh(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec`),i=N(`div`,`bubble exec-bubble`),a=N(`div`,`exec-block`);return i.appendChild(a),r.appendChild(i),n.appendChild(r),e.el.appendChild(n),to(e),{root:n,fill(n){let r=N(`div`,`exec-head`);r.appendChild(N(`span`,`exec-cmd`,t)),r.appendChild(N(`span`,`exec-code`+(n.failed?` err`:` ok`),n.codeLabel)),r.appendChild(N(`span`,`exec-dur`,String(n.durationMs)+` ms`)),a.appendChild(r);let i=Yh(n.sandbox);i!==``&&a.appendChild(N(`div`,`exec-sandbox`,i));let o=Jh(w(`chat.run.stdout`),n.stdout,`out`);o&&a.appendChild(o);let s=Jh(w(`chat.run.stderr`),n.stderr,`err`);s&&a.appendChild(s),!o&&!s&&a.appendChild(N(`div`,`exec-sandbox`,w(`chat.run.noOutput`))),W(e,!0)}}}async function $h(e,t){let n=t.trim();if(n===``)return;Xh(e,n);let r=Qh(e,n);W(e);try{let t=await j.exec({command:n,session:e.id===``?void 0:e.id,timeout_ms:Kh});r.fill({codeLabel:qh(t),durationMs:t.duration_ms,stdout:t.stdout??``,stderr:t.stderr??``,failed:t.exit_code!==0||t.signal!==null&&t.signal!==``,sandbox:t.sandbox})}catch(t){r.root.remove(),Zh(e,t instanceof D&&(t.status===404||t.status===405||t.status===501)?w(`chat.run.unsupported`):w(`chat.run.failed`,{reason:O(t,w(`settings.common.retryLater`))})),W(e,!0)}}function eg(e,t,n){gf(e,t,n)}var tg=!1;function ng(){tg||(tg=!0,Wh({name:`run`,desc:w(`chat.command.run.desc`),args:w(`chat.command.run.args`),async run(e){let t=e.args.trim();return t===``?(eg(e.ctx,w(`chat.command.run.usage`),`warn`),!0):(await $h(e.ctx,t),!0)}}),Wh({name:`goal`,desc:w(`chat.command.goal.desc`),args:w(`chat.command.goal.args`),async run(e){let t=e.args.trim();if(t===``){let t=Zr(e.ctx);return eg(e.ctx,t===``?w(`chat.command.goal.none`):w(`chat.command.goal.current`,{text:t})),!0}try{let n=await Xr(e.ctx,t===`done`?``:t);eg(e.ctx,n?w(`chat.command.goal.set`,{text:n.text}):w(`chat.command.goal.cleared`))}catch(t){eg(e.ctx,t instanceof Error?t.message:w(`chat.command.goal.saveFailed`),`err`)}return!0}}),Wh({name:`model`,desc:w(`chat.command.model.desc`),args:w(`chat.command.model.args`),async run(e){let t=e.args.trim();if(t===``)return eg(e.ctx,w(`chat.command.model.usage`),`warn`),!0;let n=await At(e.ctx.id,t);return n.kind===`ok`?eg(e.ctx,w(`chat.command.model.switched`)):n.kind===`busy`?eg(e.ctx,w(`chat.command.model.busy`),`warn`):eg(e.ctx,n.text,`err`),!0}}),Wh({name:`compact`,desc:w(`chat.command.compact.desc`),args:``,async run(e){return await fv(e.ctx),!0}}))}var J=null,rg=null,ig=null,ag=[],og=0,sg=null,cg=0,lg=null;function ug(){if(!J)return;let e=document.createElement(`div`);ag.forEach((t,n)=>{let r=N(`div`,`cmd-row`+(n===og?` active`:``)+(t.isDir?` dir`:``));r.appendChild(N(`span`,`cmd-name`,t.label)),r.appendChild(N(`span`,`cmd-desc`,t.desc)),t.meta!==void 0&&t.meta!==``&&r.appendChild(N(`span`,`cmd-args`,t.meta)),r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,n===og?`true`:`false`),r.addEventListener(`mousedown`,e=>{e.preventDefault(),dg(n)}),e.appendChild(r)}),J.replaceChildren(...Array.from(e.childNodes));let t=J.querySelector(`.cmd-row.active`);t&&typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`})}function dg(e){let t=ag[e];t&&lg&&lg(t)}function fg(){return J!==null&&!J.classList.contains(`hidden`)}function pg(e){sg=e}async function mg(e){if(!J||!sg)return;let t=++cg,n=[];try{n=await sg(e)}catch{n=[]}if(t===cg){if(ag=n,ag.length===0){hg();return}og>=ag.length&&(og=0),J.classList.remove(`hidden`),_g(),ug(),ig===null&&(ig=P(hg))}}function hg(){cg+=1,J&&(J.classList.add(`hidden`),ag=[],og=0,ig!==null&&(F(ig),ig=null))}function gg(e){return fg()?e.key===`Escape`?(e.preventDefault(),hg(),!0):e.key===`ArrowDown`?(e.preventDefault(),og=(og+1)%ag.length,ug(),!0):e.key===`ArrowUp`?(e.preventDefault(),og=(og-1+ag.length)%ag.length,ug(),!0):e.key===`Enter`||e.key===`Tab`?(e.preventDefault(),dg(og),!0):!1:!1}function _g(){if(!J||!rg)return;let e=rg.getBoundingClientRect();J.style.left=Math.max(8,e.left)+`px`,J.style.bottom=Math.max(8,window.innerHeight-e.top+6)+`px`}function vg(e,t){J||(rg=e,lg=t,J=N(`div`,`cmd-popup hidden`),J.id=`cmdPopup`,J.setAttribute(`role`,`listbox`),document.body.appendChild(J))}var yg=!1,bg=new Set,xg=[],Sg=[],Cg=null,wg=``,Tg=`active`,Eg=null,Dg=null,Og=``,kg=new Map,Ag=5e3;function jg(){return yg}function Mg(e){yg=e}function Ng(){return xg}function Pg(e){xg=e}function Fg(){return Sg}function Ig(e){Sg=e}function Lg(){return Cg}function Rg(e){Cg=e}function zg(){return wg}function Bg(e){wg=e}function Vg(){return Tg}function Hg(e){Tg=e}function Ug(){return Eg}function Wg(e){Eg=e}function Gg(){return Dg}function Kg(e){Dg=e}function qg(){return Og}function Jg(e){Og=e}function Yg(){return kg}function Xg(e){kg=e}function Zg(e){return e.replace(/\\/g,`/`)}function Qg(){let e=(B()?.workspace??``).trim();return e===``?``:e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)?e:Ng().find(t=>t.name===e)?.path??``}function $g(e){return e.type===`dir`?w(`chat.mention.dir`):e.size===null?w(`chat.mention.file`):e.size<1024?e.size+` B`:e.size<1048576?(e.size/1024).toFixed(1)+` KB`:(e.size/1048576).toFixed(1)+` MB`}async function e_(e){let t=Qg();if(t===``)return{path:``,items:[],notice:w(`chat.mention.noWorkspace`)};let n=Zg(e),r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r+1):``,a=r>=0?n.slice(r+1):n,o=Zg(t).replace(/\/+$/,``)+(i===``?``:`/`+i.replace(/^\/+/,``).replace(/\/+$/,``)),s;try{s=await j.fsList(o)}catch{return{path:o,items:[],notice:w(`chat.mention.unavailable`)}}if(s.error!==void 0&&s.error!==``)return{path:o,items:[],notice:w(`chat.mention.openFailed`,{reason:s.error})};let c=s.entries??[],l=a.toLowerCase();return{path:o,items:(l===``?c:c.filter(e=>e.name.toLowerCase().startsWith(l))).map(e=>{let t=i+e.name,n=e.type===`dir`?t+`/`:t;return{label:n,desc:$g(e),isDir:e.type===`dir`,value:n}}),notice:s.truncated===!0?w(`chat.mention.truncated`):``}}function t_(e){let t=e.trim();if(!t.startsWith(`!`))return e;let n=t.slice(1).trim();return n===``?`/`:`/run `+n}function n_(e){let t=t_(e).trim();return t.startsWith(`/`)&&t.length>1}function r_(e){let t=t_(e).trim().slice(1),n=t.search(/\s/);return n<0?{name:t,args:``}:{name:t.slice(0,n),args:t.slice(n+1)}}function i_(e,t){let n=Math.min(t,e.length)-1;for(;n>=0&&!/\s/.test(e[n]);){if(e[n]===`@`)return{start:n,after:e.slice(n+1,t)};--n}return null}async function a_(e,t){let n=t??B();if(!n||i_(e,e.length)!==null)return!1;let{name:r,args:i}=r_(e);if(r===``)return!1;let a=Gh().find(e=>e.name===r);return a?(hg(),await a.run({raw:e,args:i,ctx:n})):(gf(n,w(`chat.command.unknown`,{name:r}),`warn`),!0)}function o_(){return document.getElementById(`input`)}function s_(e){let t=o_();t&&(t.value=e.value+(e.value.endsWith(` `)?``:` `),t.dispatchEvent(new Event(`input`,{bubbles:!0})),hg(),t.focus())}function c_(e){let t=o_();if(!t)return;let n=t.selectionStart??t.value.length,r=i_(t.value,n);if(r===null)return;let i=t.value.slice(0,r.start),a=t.value.slice(n);t.value=i+`@`+e.value+a;let o=i.length+1+e.value.length;t.setSelectionRange(o,o),t.dispatchEvent(new Event(`input`,{bubbles:!0})),e.value.endsWith(`/`)?d_(t.value,o):hg(),t.focus()}async function l_(e){let t=await e_(e);if(t.notice!==``){let e=B();e&&gf(e,t.notice,`warn`)}return t.items}function u_(e){let t=e.toLowerCase();return Gh().filter(e=>e.name.toLowerCase().startsWith(t)).map(e=>({label:`/`+e.name,desc:e.desc,meta:e.args,value:`/`+e.name}))}async function d_(e,t){let n=i_(e,t??e.length);if(n!==null){pg(l_),await mg(n.after);return}if(e.startsWith(`/`)&&!/\s/.test(e.slice(1))){pg(u_),await mg(e.slice(1));return}pg(null),hg()}var f_=!1;function p_(){if(f_)return;f_=!0,ng();let e=o_();e&&(Br(()=>ei()),Kr(()=>ei()),pg(null),vg(e,e=>{e.label.startsWith(`/`)?s_(e):c_(e)}),e.addEventListener(`input`,()=>void d_(e.value,e.selectionStart??e.value.length)),e.addEventListener(`keydown`,e=>{gg(e)}),e.addEventListener(`blur`,()=>hg()))}function m_(e){return n_(e)}function h_(e){return gg(e)}var g_=240;function __(){return w(`chat.input.placeholderIdle`)}function v_(){return w(`chat.input.placeholderSteer`)}function y_(){return w(`chat.input.placeholderQueue`)}function b_(){return w(`chat.input.placeholderWorker`)}var x_=null,S_=null,C_=null,w_=null,T_=null,E_=`steer`,D_=`idle`;function O_(e){E_=e,A_()}function k_(){O_(E_===`steer`?`queue`:`steer`)}function A_(){if(T_){let e=T_.querySelector(`.sl-mode-label`);e?e.textContent=w(E_===`steer`?`chat.input.interject`:`chat.input.queue`):T_.textContent=w(E_===`steer`?`chat.input.interject`:`chat.input.queue`),T_.title=w(E_===`steer`?`chat.input.modeSteerTitle`:`chat.input.modeQueueTitle`),T_.classList.toggle(`queue`,E_===`queue`)}S_&&D_===`interject`&&(S_.placeholder=E_===`steer`?v_():y_()),C_&&(C_.disabled=!1,C_.textContent=w(D_===`worker`?`chat.input.send`:D_===`interject`?E_===`steer`?`chat.input.interject`:`chat.input.queue`:`chat.input.send`),C_.title=w(D_===`worker`?`chat.input.sendWorkerTitle`:D_===`interject`?E_===`steer`?`chat.input.steerTitle`:`chat.input.queueTitle`:`chat.input.sendTitle`))}function j_(e){let t=M(`#input`);S_=t,x_=M(`#inputbar`),C_=M(`#btnSend`);let n=M(`#slStop`);w_=n,T_=document.getElementById(`btnMode`);let r=()=>{t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,g_)+`px`};C_.addEventListener(`click`,()=>e.send(t.value,E_)),T_?.addEventListener(`click`,()=>k_()),n.addEventListener(`click`,()=>{n.disabled||(n.disabled=!0,e.cancel())}),t.addEventListener(`keydown`,n=>{if(h_(n)||n.key!==`Enter`||n.shiftKey)return;n.preventDefault();let r=n.ctrlKey||n.metaKey?E_===`steer`?`queue`:`steer`:E_;e.send(t.value,r)}),t.addEventListener(`input`,r),J_(t,x_),A_(),window.setTimeout(r,0)}function M_(){let e=S_??M(`#input`);e.value=``,e.style.height=`auto`,e.style.height=Math.min(e.scrollHeight,g_)+`px`}function N_(e){let t=S_??M(`#input`);t.value=e,t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,g_)+`px`}function P_(e){w_&&(w_.classList.toggle(`hidden`,!e),w_.disabled=!e)}function F_(e){D_=e;let t=S_;x_&&(x_.classList.toggle(`interject`,e===`interject`),x_.classList.toggle(`worker`,e===`worker`),x_.classList.remove(`readonly`)),T_&&T_.classList.toggle(`hidden`,e!==`interject`),t&&(t.placeholder=e===`worker`?b_():e===`interject`?E_===`steer`?v_():y_():__(),t.readOnly=!1),A_()}var I_=null,L_=null,R_=null,z_=`<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"></path></svg>`;function B_(){return x_??document.getElementById(`inputbar`)}function V_(){let e=Od(),t=jd();L_&&(L_.classList.toggle(`hidden`,!1),L_.disabled=!1,L_.title=t===``?w(`chat.input.attachTitle`):t),e||ef(),Dh()}window.addEventListener(`studio:config-saved`,()=>{Ed(),Dd().then(V_)});function H_(e){I_&&(I_.textContent=e,I_.classList.toggle(`hidden`,e===``))}function U_(e){let t=jd(),n=[],r=0;for(let i=0;i<e.length;i++){let a=e[i];a&&(t!==``&&a.type.indexOf(`image/`)===0?r+=1:n.push(a))}let i=Jd(n);Dh(),r>0?H_(t):i>0&&H_(w(`chat.input.rejectedCount`,{n:i}))}function W_(e){return td(e)?e.type.indexOf(`image/`)!==0||jd()===``:!1}function G_(e){let t=e.clipboardData;if(!t)return[];let n=[],r=t.items;if(r)for(let e=0;e<r.length;e++){let t=r[e];if(t&&t.kind===`file`&&W_({name:``,type:t.type})){let e=t.getAsFile();e&&n.push(e)}}if(n.length===0&&t.files)for(let e=0;e<t.files.length;e++){let r=t.files[e];r&&W_(r)&&n.push(r)}return n}function K_(e){let t=e.dataTransfer;return t?t.types&&Array.prototype.indexOf.call(t.types,`Files`)>=0?!0:!!t.files&&t.files.length>0:!1}function q_(){let e=jd();e!==``&&H_(e),R_?.click()}function J_(e,t){I_=N(`div`,`attach-note hidden`);let n=t.querySelector(`.input-box`),r=t.querySelector(`.input-side`);Oh(t,n),Hh(t,n),L_=document.createElement(`button`),L_.id=`btnAttach`,L_.type=`button`,L_.className=`btn btn-soft btn-icon attach-inline`,L_.innerHTML=z_,L_.title=w(`chat.input.attachTitle`),L_.setAttribute(`aria-label`,w(`chat.input.attachAria`)),L_.addEventListener(`click`,()=>q_()),n?n.appendChild(L_):r&&r.firstChild?r.insertBefore(L_,r.firstChild):(r??t).appendChild(L_),R_=document.createElement(`input`),R_.id=`attachInput`,R_.type=`file`,R_.accept=gd,R_.multiple=!0,R_.className=`attach-file hidden`,R_.addEventListener(`change`,()=>{if(R_&&R_.files){let e=[];for(let t=0;t<R_.files.length;t++){let n=R_.files[t];n&&td(n)&&e.push(n)}e.length>0&&U_(e)}R_&&(R_.value=``)}),t.insertBefore(I_,t.firstChild),t.appendChild(R_),e.addEventListener(`paste`,e=>{let t=G_(e);t.length>0&&U_(t)}),document.addEventListener(`dragover`,e=>{K_(e)&&(e.preventDefault(),B_()?.classList.add(`drop-active`))}),document.addEventListener(`dragleave`,e=>{K_(e)&&B_()?.classList.remove(`drop-active`)}),document.addEventListener(`drop`,e=>{B_()?.classList.remove(`drop-active`);let t=e.dataTransfer;t&&t.files&&t.files.length!==0&&(e.preventDefault(),U_(t.files))}),cd(Dh),V_(),Dd().then(V_)}var Y_=M(`#statusText`),X_=M(`#statusDot`),Z_=M(`#statusTurn`),Q_=M(`#statusTime`);function Y(e,t){Y_.textContent=e,X_.className=`dot`+(t?` `+t:``)}function $_(e){Z_.textContent=typeof e==`number`&&e>=1?w(`shell.status.turn`,{n:e}):w(`shell.status.turnNone`)}function ev(){R.streaming&&(Q_.textContent=be((Date.now()-R.t0)/1e3))}function tv(){R.t0=Date.now(),nv(),R.msgTimer=window.setInterval(ev,500),ev()}function nv(){R.msgTimer!==null&&(window.clearInterval(R.msgTimer),R.msgTimer=null)}function rv(){nv(),R.t0>0&&(Q_.textContent=be((Date.now()-R.t0)/1e3))}var iv=null;function av(){iv!==null&&(window.clearTimeout(iv),iv=null)}function X(e,t,n=6e3){av(),Y(e,t),iv=window.setTimeout(()=>{iv=null,!R.streaming&&(R.conn===`online`?Y(w(`shell.status.online`),`ok`):R.conn===`down`&&Y(w(`shell.status.reconnecting`),`err`))},n)}function ov(e){return e.id===``?void 0:e.id}function sv(e){return e instanceof Error?e.message:String(e)}var cv=!1,lv=new Map,uv=5e3;function dv(e){let t=typeof e.session==`string`&&e.session!==``?e.session:null,n=t?Sr(t)??null:B();n&&(Date.now()-(lv.get(n.id)??0)<uv||n.streaming||(async()=>{await tm(n),V(n)&&X(e.note||w(`shell.compact.done`),`ok`)})())}async function fv(e){if(!cv){cv=!0,M_(),e.draft=``;try{let t=ov(e);if(t===void 0){let e=await nm();if(e===null){X(w(`shell.compact.noSession`),`err`,8e3);return}t=e}Y(w(`shell.compact.busy`),`busy`);let n=await j.compactSession(t);if(n.compacted===!1){X(n.note||w(`shell.compact.notNeeded`),`ok`);return}lv.set(t,Date.now()),X(n.note||w(`shell.compact.historyDone`),`ok`),await tm(e)}catch(e){X(w(`shell.compact.failed`,{reason:sv(e)}),`err`,8e3)}finally{cv=!1}}}var pv=null;function mv(){return pv}function hv(e){pv=e}function gv(e){return e===`read_roots`||e===`write_roots`?`roots`:e===`net_hosts`?`hosts`:e===`tool_extra`?`tools`:null}function _v(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e!==``))).sort():[]}function vv(e,t){let n=gv(e),r={};return n!==null&&(r[n]=_v(n===`roots`?t.roots:n===`hosts`?t.hosts:t.tools)),JSON.stringify({cap:e,scope:r})}async function yv(e,t){let n=vv(e,t),r=new TextEncoder().encode(n),i=globalThis.crypto?.subtle;if(i)try{let e=await i.digest(`SHA-256`,r);return bv(new Uint8Array(e))}catch{}return xv(r)}function bv(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function xv(e){return bv(wv(e))}var Sv=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Cv(e,t){return(e>>>t|e<<32-t)>>>0}function wv(e){let t=e.length,n=Math.ceil((t+9)/64),r=new Uint8Array(n*64);r.set(e),r[t]=128;let i=new DataView(r.buffer);i.setUint32(n*64-8,Math.floor(t/536870912)),i.setUint32(n*64-4,t*8>>>0);let a=1779033703,o=3144134277,s=1013904242,c=2773480762,l=1359893119,u=2600822924,d=528734635,f=1541459225,p=new Uint32Array(64);for(let e=0;e<n;e++){for(let t=0;t<16;t++)p[t]=i.getUint32(e*64+t*4);for(let e=16;e<64;e++){let t=p[e-15],n=p[e-2],r=Cv(t,7)^Cv(t,18)^t>>>3,i=Cv(n,17)^Cv(n,19)^n>>>10;p[e]=p[e-16]+r+p[e-7]+i>>>0}let t=a,n=o,r=s,m=c,h=l,g=u,_=d,v=f;for(let e=0;e<64;e++){let i=Cv(h,6)^Cv(h,11)^Cv(h,25),a=h&g^~h&_,o=v+i+a+Sv[e]+p[e]>>>0,s=(Cv(t,2)^Cv(t,13)^Cv(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=h,h=m+o>>>0,m=r,r=n,n=t,t=o+s>>>0}a=a+t>>>0,o=o+n>>>0,s=s+r>>>0,c=c+m>>>0,l=l+h>>>0,u=u+g>>>0,d=d+_>>>0,f=f+v>>>0}let m=new Uint8Array(32),h=new DataView(m.buffer);return[a,o,s,c,l,u,d,f].forEach((e,t)=>h.setUint32(t*4,e)),m}var Tv=new Set([`network`,`write_roots`,`unsandboxed`]);function Ev(){return[{cap:`network`,label:w(`grants.cap.network.label`),impact:w(`grants.cap.network.impact`),extra:w(`grants.cap.network.extra`),kind:`bool`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:3600},{cap:`write_roots`,label:w(`grants.cap.writeRoots.label`),impact:w(`grants.cap.writeRoots.impact`),kind:`dirs`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`read_roots`,label:w(`grants.cap.readRoots.label`),impact:w(`grants.cap.readRoots.impact`),kind:`dirs`,danger:!1,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`net_hosts`,label:w(`grants.cap.netHosts.label`),impact:w(`grants.cap.netHosts.impact`),kind:`hosts`,danger:!1,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`tool_extra`,label:w(`grants.cap.toolExtra.label`),impact:w(`grants.cap.toolExtra.impact`),kind:`tools`,danger:!1,reserved:!0,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`unsandboxed`,label:w(`grants.cap.unsandboxed.label`),impact:w(`grants.cap.unsandboxed.impact`),kind:`bool`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:900}]}function Dv(){return new Map(Ev().map(e=>[e.cap,e]))}function Ov(){return[{sec:0,label:Mv()},{sec:900,label:w(`grants.ttl.min15`)},{sec:1800,label:w(`grants.ttl.min30`)},{sec:3600,label:w(`grants.ttl.hour1`)},{sec:86400,label:w(`grants.ttl.hour24`)}]}function kv(){return Ov().filter(e=>e.sec>0)}function Av(e){return e.label}var jv=1800;function Mv(){return w(`grants.permanent.label`)}function Nv(){return w(`grants.permanent.text`)}function Pv(){return w(`grants.permanent.paren`)}function Fv(){return Math.floor(Date.now()/1e3)}function Iv(e){let t=new Date(e*1e3),n=e=>(e<10?`0`:``)+e;return n(t.getHours())+`:`+n(t.getMinutes())}function Lv(e){return!(typeof e==`number`&&e>0)}function Rv(e){return Lv(e)?w(`grants.until.permanent`):w(`grants.until.at`,{time:Iv(e)})}function zv(e){return Lv(e)?Pv():w(`grants.until.paren`,{time:Iv(e)})}function Bv(e){return e.expired===!0||typeof e.expires_at==`number`&&e.expires_at>0&&e.expires_at<=Fv()}function Vv(e){return e&&e.scope&&typeof e.scope==`object`?e.scope:{}}function Z(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e!==``):[]}function Hv(e){let t=[];return e?(e.network===!0&&t.push(`network`),Z(e.read_roots).length&&t.push(`read_roots`),Z(e.write_roots).length&&t.push(`write_roots`),Z(e.net_hosts).length&&t.push(`net_hosts`),Z(e.tool_extra).length&&t.push(`tool_extra`),e.unsandboxed===!0&&t.push(`unsandboxed`),{count:t.length,danger:t.some(e=>Tv.has(e)),caps:t}):{count:0,danger:!1,caps:t}}function Uv(e){return new Promise(t=>{let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card confirm-card`);e.title&&r.appendChild(N(`div`,`modal-card-title`,e.title));let i=N(`div`,`confirm-message`);if(i.textContent=e.message,r.appendChild(i),e.note&&r.appendChild(N(`div`,`confirm-note`,e.note)),e.snapshot){r.appendChild(N(`div`,`confirm-snapshot-label`,e.snapshotLabel??w(`shell.confirm.result`)));let t=N(`pre`,`confirm-snapshot`);t.textContent=e.snapshot,r.appendChild(t)}let a=(e.requireText??``).trim(),o=null;if(a!==``){let t=N(`div`,`confirm-word-row`),n=document.createElement(`label`);n.textContent=e.requireHint??w(`shell.confirm.require`,{word:a});let i=N(`input`,`cfg-input`);i.type=`text`,i.autocomplete=`off`,i.spellcheck=!1,t.appendChild(n),t.appendChild(i),r.appendChild(t),r.appendChild(N(`div`,`confirm-word-hint`,w(`shell.confirm.requireHint`))),o=i}let s=N(`div`,`modal-card-actions`),c=N(`button`,`btn `+(e.danger?`btn-danger`:`btn-accent`),e.okLabel??w(`settings.action.confirm`));c.type=`button`;let l=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));l.type=`button`;let u=!1,d=null,f=e=>{u||(u=!0,d&&(F(d),d=null),n.remove(),t(e))};o&&(c.disabled=!0,o.addEventListener(`input`,()=>{c.disabled=o.value.trim()!==a}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&!c.disabled&&(e.preventDefault(),f(!0))})),c.addEventListener(`click`,()=>{o&&o.value.trim()!==a||f(!0)}),l.addEventListener(`click`,()=>f(!1)),n.addEventListener(`click`,e=>{e.target===n&&f(!1)}),s.appendChild(l),s.appendChild(c),r.appendChild(s),n.appendChild(r),document.body.appendChild(n),d=P(()=>f(!1)),o?o.focus():(e.focus===`ok`?c:l).focus()})}var Wv=`unknown`,Gv=0,Kv=null,qv=null,Jv=null,Yv=``,Xv=null,Zv=null,Qv=null,$v=new Map,ey=new Map,ty=new Map,ny=new Set,ry=null,iy=null;function ay(e){iy=e}function oy(){return iy}function sy(){return Wv}function cy(e){Wv=e}function ly(){return Gv}function uy(e){Gv=e}function dy(){return Kv}function fy(e){Kv=e}function py(){return qv}function my(e){qv=e}function hy(){return Jv}function gy(){return Yv}function _y(e,t){Jv=e,Yv=t}function vy(){return Xv}function yy(e){Xv=e}function by(){return Zv}function xy(e){Zv=e}function Sy(){return ry}function Cy(e){ry=e}var wy=new Map,Ty=new Map,Ey=null;function Dy(){return{granted:Array.from(wy.values(),e=>e.entry),revoked:new Set(Ty.keys()),revokeAll:Ey!==null}}function Oy(e,t){wy.set(e,{entry:t,settledAt:null}),Ty.delete(e)}function ky(e){let t=Date.now();if(e===null){Ey!==null&&(Ey.settledAt=t);return}let n=wy.get(e);n&&(n.settledAt=t);let r=Ty.get(e);r&&(r.settledAt=t)}function Ay(e){wy.delete(e)}function jy(e){if(e===null){wy.clear(),Ty.clear(),Ey={settledAt:null};return}wy.delete(e),Ty.set(e,{settledAt:null})}function My(e){if(e===null){Ey=null,Ty.clear();return}Ty.delete(e)}function Ny(e,t){let n=new Set;for(let t of e)typeof t.cap==`string`&&n.add(t.cap);for(let[e,r]of Array.from(wy))(n.has(e)||r.settledAt!==null&&r.settledAt<t)&&wy.delete(e);for(let[e,r]of Array.from(Ty))(!n.has(e)||r.settledAt!==null&&r.settledAt<t)&&Ty.delete(e);Ey!==null&&(n.size===0||Ey.settledAt!==null&&Ey.settledAt<t)&&(Ey=null)}function Py(){wy.clear(),Ty.clear(),Ey=null}function Fy(){return Qv}function Iy(e){Qv=e}function Ly(){let e=Dy();if(e.revokeAll)return[];let t=(hy()?.grants??[]).filter(t=>typeof t.cap==`string`&&!Bv(t)&&!e.revoked.has(t.cap));for(let n of e.granted)typeof n.cap==`string`&&!e.revoked.has(n.cap)&&t.push(n);return t}function Ry(e){let t=Ly().filter(t=>t.cap===e);return t.length?t[t.length-1]:null}function zy(e){return(hy()?.grants??[]).filter(t=>t.cap===e&&Bv(t))}function By(){if(!Ly().length)return w(`grants.phrase.default`);let e=[];for(let t of Ev()){let n=Ry(t.cap);n&&e.push(Vy(t,Vv(n)))}return e.length?w(`grants.phrase.canNow`)+e.join(w(`grants.copy.listSep`))+w(`grants.phrase.suffix`):w(`grants.phrase.default`)}function Vy(e,t){switch(e.cap){case`network`:return w(`grants.phrase.network`);case`write_roots`:return w(`grants.phrase.writeRoots`,{roots:Z(t.roots).join(w(`grants.copy.listSep`))});case`read_roots`:return w(`grants.phrase.readRoots`,{roots:Z(t.roots).join(w(`grants.copy.listSep`))});case`net_hosts`:return w(`grants.phrase.netHosts`,{hosts:Z(t.hosts).join(w(`grants.copy.listSep`))});case`tool_extra`:return w(`grants.phrase.toolExtra`,{tools:Z(t.tools).join(w(`grants.copy.listSep`))});case`unsandboxed`:return w(`grants.phrase.unsandboxed`)}}function Hy(){return w(`grants.copy.listSep`)}function Uy(e,t,n){let r=Rv(n);switch(e.cap){case`network`:return w(`grants.copy.network`,{until:r});case`write_roots`:return w(`grants.copy.writeRoots`,{roots:Z(t.roots).join(Hy()),until:r});case`unsandboxed`:return w(`grants.copy.unsandboxed`,{until:r});case`read_roots`:return w(`grants.copy.readRoots`,{roots:Z(t.roots).join(Hy()),until:r});case`net_hosts`:return w(`grants.copy.netHosts`,{hosts:Z(t.hosts).join(Hy()),until:r});case`tool_extra`:return w(`grants.copy.toolExtra`,{tools:Z(t.tools).join(Hy()),until:r})}}function Wy(e,t){let n=w(`grants.copy.presetHead`,{label:e,n:t.length}),r=t.map(e=>w(`grants.copy.presetBody`,{label:e.def.label,text:Uy(e.def,e.scope,e.expiresAt)})),i=t.every(e=>e.expiresAt===null)?w(`grants.copy.presetTailPermanent`,{permanent:Nv()}):w(`grants.copy.presetTailLimited`,{list:t.map(e=>e.def.label+` `+Rv(e.expiresAt)).join(Hy())});return[n,...r,i].join(`
|
|
94
|
-
`)}function Gy(e,t){return w(`grants.copy.previewPrefix`)+Vy(e,t)+w(`grants.copy.previewSuffix`)}function Ky(e,t){return w(`grants.copy.successPrefix`)+e.label+zv(t.grant?.expires_at)}var qy=`studio:grants-changed`,Jy=12e4,Yy=3,Xy=40,Zy=new Map,Qy=new Map,$y=!1;function eb(e){$y=e}function tb(e){Qy.set(e,Date.now())}function nb(e){let t=Zy.get(e);return t&&t.count>0?t:null}function rb(){window.dispatchEvent(new Event(qy))}function ib(e,t){if(e===``)return;let n=Zy.get(e),r=n!==void 0&&n.count===t.count&&n.danger===t.danger&&n.caps.join(`,`)===t.caps.join(`,`);t.count>0?Zy.set(e,t):Zy.delete(e),r||rb()}function ab(e){if(!$y||e.length===0)return;let t=Date.now(),n=[];for(let r of e){if(!r||n.includes(r))continue;let e=Qy.get(r);if(!(e!==void 0&&t-e<Jy)&&(n.push(r),n.length>=Xy))break}if(!n.length)return;let r=0,i=async()=>{for(;;){let e=r++;if(e>=n.length)return;await ob(n[e])}};for(let e=0;e<Math.min(Yy,n.length);e++)i()}async function ob(e){tb(e);try{let t=await j.grants(e);if(t.error)return;let n=(t.grants??[]).filter(e=>typeof e.cap==`string`&&!Bv(e)),r=n.map(e=>String(e.cap));ib(e,{count:n.length,danger:r.some(e=>Tv.has(e)),caps:r})}catch{}}function sb(){let e=dy();if(!e)return;let t=Ly(),n=t.length,r=t.some(e=>typeof e.expires_at==`number`&&e.expires_at>0&&e.expires_at-Fv()<120);e.classList.toggle(`granted`,n>0),e.classList.toggle(`has-expiring`,n>0&&r);let i=py();i&&(i.textContent=n>0?String(n):``),e.title=n===0?w(`grants.shield.default`):r?w(`grants.shield.expiring`):w(`grants.shield.granted`,{n}),e.setAttribute(`aria-label`,e.title)}var cb=null;function lb(){let e=vy();if(!e)return;let t=gn(dy());t&&_n(e,t)}function ub(){cb?.();let e=0,t=t=>{let n=t.target,r=vy();r&&n instanceof Node&&r.contains(n)||e===0&&(e=window.requestAnimationFrame(()=>{e=0,lb()}))};window.addEventListener(`resize`,t),document.addEventListener(`scroll`,t,!0),cb=()=>{e!==0&&(window.cancelAnimationFrame(e),e=0),window.removeEventListener(`resize`,t),document.removeEventListener(`scroll`,t,!0)}}function db(){cb?.(),cb=null}var fb=[`localhost`,`127.0.0.1`];function pb(){return[{id:`read-workspace`,label:w(`grants.preset.readWorkspace.label`),hint:w(`grants.preset.readWorkspace.hint`),ttlSec:0,steps:[{cap:`read_roots`,scopeKind:`dir`}]},{id:`write-output`,label:w(`grants.preset.writeOutput.label`),hint:w(`grants.preset.writeOutput.hint`),ttlSec:0,steps:[{cap:`write_roots`,scopeKind:`dir`}]},{id:`net`,label:w(`grants.preset.net.label`),hint:w(`grants.preset.net.hint`),ttlSec:0,steps:[{cap:`network`,scopeKind:`none`}]},{id:`localhost`,label:w(`grants.preset.localhost.label`),hint:w(`grants.preset.localhost.hint`),ttlSec:0,steps:[{cap:`network`,scopeKind:`none`},{cap:`net_hosts`,scopeKind:`hosts`,hosts:fb}]}]}function mb(e,t){return e.ttlSec<=0?0:!Number.isFinite(t)||t<=0?e.ttlSec:Math.min(e.ttlSec,t)}function hb(e,t){return e.steps.every(e=>{let n=t.find(t=>t.cap===e.cap);if(!n)return!1;if(e.scopeKind!==`hosts`)return!0;let r=n.hosts??[];return(e.hosts??[]).every(e=>r.includes(e))})}function gb(){let e=[];for(let t of Ev()){let n=Ry(t.cap);n&&e.push({cap:t.cap,hosts:t.kind===`hosts`?Z(Vv(n).hosts):[]})}return e}function _b(e){if(e.ttlSec<=0)return Mv();let t=Ov().find(t=>t.sec===e.ttlSec);return t?w(`grants.quick.ttlPrefix`,{label:Av(t)}):w(`grants.quick.ttlMinutes`,{n:Math.max(1,Math.round(e.ttlSec/60))})}function vb(e){let t=N(`div`,`grant-presets`),n=N(`div`,`grant-presets-head`);n.appendChild(N(`span`,`grant-presets-title`,w(`grants.quick.title`))),n.appendChild(N(`span`,`grant-presets-ttl-note`,w(`grants.quick.note`))),t.appendChild(n);let r=Sy(),i=gb();for(let n of pb()){let a=N(`button`,`grant-preset`);a.type=`button`;let o=hb(n,i);a.classList.toggle(`on`,o),a.disabled=r!==null,a.title=n.hint;let s=N(`span`,`grant-preset-top`);s.appendChild(N(`span`,`grant-preset-label`,n.label)),o&&s.appendChild(N(`span`,`grant-preset-tag`,w(`grants.quick.applied`))),s.appendChild(N(`span`,`grant-preset-ttl`,_b(n))),a.appendChild(s),a.appendChild(N(`span`,`grant-preset-hint`,n.hint)),a.addEventListener(`click`,()=>void yb(e,n)),t.appendChild(a)}return t}async function yb(e,t){let n=oy();if(!n){Iy({text:w(`grants.quick.unavailable`),cls:`err`}),e.renderPanel();return}await n(e,t)}function bb(e){let t=hy()?.max_ttl_sec?.[e.cap];return typeof t==`number`&&t>0?t:e.maxTtl}function xb(e){let t=ty.get(e.cap);return t===void 0?e.defaultTtl:t===0?0:Math.min(t,bb(e))}function Sb(e){return Math.min(jv,bb(e))}function Cb(e,t,n){let r={cap:e.cap,scope:t,ttl_sec:n};return e.cap===`unsandboxed`&&(r.uses_left=1),r}function wb(){let e=Z(hy()?.warnings);if(e.length===0)return null;let t=N(`div`,`grant-preview`);t.appendChild(N(`span`,`grant-preview-label`,w(`grants.warnings.label`)));for(let n of e)t.appendChild(N(`div`,`grant-impact`,n));return t}function Tb(){return hy()?.net_hosts_effective===!1}function Eb(e,t){let n=Ry(e.cap),r=zy(e.cap),i=N(`div`,`grant-row`+(n===null&&r.length?` expired`:``));i.dataset.cap=e.cap;let a=N(`div`,`grant-row-head`);if(a.appendChild(N(`span`,`grant-row-name`,e.label)),a.appendChild(Db(e,n,r)),e.cap===`net_hosts`&&Tb()){let e=N(`span`,`grant-badge`,w(`grants.rows.ineffective`));e.title=w(`grants.rows.ineffectiveTitle`),a.appendChild(e)}if(e.reserved===!0){let e=N(`span`,`grant-badge`,w(`grants.rows.reserved`));e.title=w(`grants.rows.reservedTitle`),a.appendChild(e)}i.appendChild(a),i.appendChild(N(`div`,`grant-impact`,e.impact)),e.extra&&i.appendChild(N(`div`,`grant-impact`,e.extra));let o=Vv(n),s=Z(o.roots).concat(Z(o.hosts),Z(o.tools));n&&s.length&&i.appendChild(N(`div`,`grant-detail`,kb(e,n,s)));for(let t of r){let n=Z(Vv(t).roots).concat(Z(Vv(t).hosts),Z(Vv(t).tools));i.appendChild(N(`div`,`grant-detail`,w(`grants.rows.expiredPrefix`,{what:n.length?n.join(w(`grants.copy.listSep`)):e.label})))}if((e.kind===`hosts`||e.kind===`tools`)&&!n&&e.reserved!==!0){let t=N(`div`,`grant-hosts-row`),n=N(`input`,`grant-input cfg-input`);n.type=`text`,n.spellcheck=!1,n.placeholder=e.kind===`hosts`?w(`grants.rows.hostPlaceholder`):w(`grants.rows.toolPlaceholder`),n.value=ey.get(e.cap)??``,n.addEventListener(`input`,()=>{ey.set(e.cap,n.value),$v.delete(e.cap);let t=i.querySelector(`.grant-err`);t&&t.remove()}),t.appendChild(n),i.appendChild(t)}let c=N(`div`,`grant-row-actions`);if(n){let n=N(`button`,`btn-mini`,w(`grants.rows.revoke`));n.type=`button`,n.addEventListener(`click`,()=>void t.revoke(e.cap)),c.appendChild(n)}else if(e.reserved!==!0){let n=N(`button`,`btn-mini`+(e.danger?` grant-danger-btn`:``),e.kind===`dirs`?w(`grants.rows.chooseDir`):w(`grants.rows.grant`));n.type=`button`,n.title=w(`grants.rows.grantTitle`,{permanent:Nv()}),n.addEventListener(`click`,()=>{ty.set(e.cap,0),t.startGrant(e)}),c.appendChild(n),c.appendChild(Ab(e,t)),e.cap===`unsandboxed`&&c.appendChild(N(`span`,`grant-impact`,w(`grants.rows.onceOnly`,{permanent:Nv()})))}i.appendChild(c),!n&&ny.has(e.cap)&&i.appendChild(jb(e,t));let l=$v.get(e.cap);return l&&i.appendChild(N(`div`,`grant-err`,l)),i}function Db(e,t,n){return t?N(`span`,`grant-badge on`,Ob(e,t)):n.length?N(`span`,`grant-badge expired`,w(`grants.rows.expired`)):N(`span`,`grant-badge`,w(`grants.rows.notGranted`))}function Ob(e,t){if(e.kind===`hosts`||e.kind===`tools`){let n=Z(Vv(t)[e.kind===`hosts`?`hosts`:`tools`]).length;return w(`grants.rows.grantedCount`,{n:n||1})}return Lv(t.expires_at)?w(`grants.rows.grantedPermanent`,{permanent:Mv()}):w(`grants.rows.grantedUntil`,{time:Iv(t.expires_at)})}function kb(e,t,n){let r=zv(t.expires_at);switch(e.cap){case`write_roots`:return w(`grants.rows.detailWrite`,{values:n.join(w(`grants.copy.listSep`)),exp:r});case`read_roots`:return w(`grants.rows.detailRead`,{values:n.join(w(`grants.copy.listSep`)),exp:r});case`net_hosts`:return n.join(`、`)+r;case`tool_extra`:return n.join(`、`)+r;default:return n.join(`、`)+r}}function Ab(e,t){let n=ny.has(e.cap),r=N(`button`,`btn-mini`,w(n?`grants.rows.tempCollapse`:`grants.rows.tempOpen`));return r.type=`button`,r.addEventListener(`click`,()=>{n?ny.delete(e.cap):ny.add(e.cap),t.renderPanel()}),r}function jb(e,t){let n=N(`div`,`grant-temp`);n.appendChild(N(`div`,`grant-impact`,w(`grants.rows.tempNote`)));let r=N(`div`,`grant-hosts-row`);r.appendChild(Mb(e));let i=N(`button`,`btn-mini`,w(`grants.rows.tempGrant`));return i.type=`button`,i.addEventListener(`click`,()=>void t.startGrant(e)),r.appendChild(i),n.appendChild(r),n}function Mb(e){let t=bb(e),n=document.createElement(`select`);n.className=`cfg-input grant-ttl`;let r=ty.get(e.cap),i=r!==void 0&&r>0?r:Sb(e),a=!1;for(let e of kv()){if(e.sec>t)continue;let r=document.createElement(`option`);r.value=String(e.sec),r.textContent=e.label,e.sec===i&&(a=!0),n.appendChild(r)}if(a)n.value=String(i);else{let e=Math.max(1,Math.min(i,t)),r=document.createElement(`option`);r.value=String(e),r.textContent=w(`grants.rows.minutes`,{n:Math.max(1,Math.round(e/60))}),n.appendChild(r),n.value=String(e)}return n.addEventListener(`change`,()=>ty.set(e.cap,Number(n.value))),n}function Nb(){db();let e=by();e&&(F(e),xy(null));let t=vy();t&&(t.remove(),yy(null))}function Pb(e){if(vy()){Nb();return}Fb(e)}async function Fb(e){Nb(),$v.clear(),Iy(null);let t=document.getElementById(`statusline`);if(!t)return;let n=N(`div`,`sl-popup grant-popup`);n.setAttribute(`role`,`dialog`),yy(n),t.appendChild(n),xy(P(()=>Nb())),n.appendChild(N(`div`,`sl-popup-title`,w(`grants.body.title`)));let r=N(`div`,`sl-popup-body`);if(n.appendChild(r),e.focusedSession()===``){r.replaceChildren(N(`div`,`sl-popup-note`,w(`grants.body.noSession`))),lb(),ub();return}let i=hy()!==null&&gy()===e.focusedSession();i||n.classList.add(`hidden`),i&&Ib(e),ub(),await e.refresh(!0),vy()===n&&(n.classList.remove(`hidden`),Ib(e))}function Ib(e){let t=vy();if(!t)return;let n=t.querySelector(`.sl-popup-body`);if(!n)return;let r=document.createElement(`div`);r.appendChild(vb(e)),r.appendChild(N(`div`,`grant-intro`,w(`grants.body.introDefault`))),r.appendChild(N(`div`,`grant-intro`,w(`grants.body.introScope`)));let i=wb();i&&r.appendChild(i);let a=N(`div`,`grant-preview`);if(a.appendChild(N(`span`,`grant-preview-label`,w(`grants.body.previewLabel`))),a.appendChild(N(`span`,null,By())),r.appendChild(a),hy()===null)r.appendChild(N(`div`,`sl-popup-note`,w(`grants.body.unreadable`)));else for(let t of Ev())(t.cap!==`unsandboxed`||hy()?.unsandboxed_available===!0)&&(t.reserved!==!0||Ry(t.cap)!==null||zy(t.cap).length!==0)&&r.appendChild(Eb(t,e));let o=N(`div`,`grant-foot`);o.appendChild(N(`div`,`grant-foot-note`,w(`grants.body.footNote`)));let s=N(`button`,`btn-mini grant-danger-btn`,w(`grants.body.revokeAll`));s.type=`button`,s.disabled=Ly().length===0,s.addEventListener(`click`,()=>void e.revoke(null)),o.appendChild(s),r.appendChild(o);let c=Fy();c&&r.appendChild(N(`div`,`sl-popup-status `+c.cls,c.text)),n.replaceChildren(...r.childNodes),lb()}function Lb(e){return/sk-/.test(e)||/Bearer\s/.test(e)||e.includes(`
|
|
95
|
-
`)||e.length>200}var
|
|
96
|
-
`+w(`grants.flow.effectiveNote`),snapshot:JSON.stringify(
|
|
97
|
-
`+w(`grants.flow.effectiveNote`),snapshot:JSON.stringify(hy()?.effective??{},null,2),snapshotLabel:w(`grants.flow.snapshotLabel`),okLabel:w(`grants.rows.grant`),danger:!0}))return;for(let e of r)Oy(e.def.cap,{cap:e.def.cap,scope:e.scope,expires_at:e.ttl===0?null:Fv()+e.ttl});Cy({id:t.id,index:0,total:r.length}),Kb(e);let o=[];for(let i=0;i<r.length;i++){let a=r[i];Cy({id:t.id,index:i,total:r.length});try{let e=await Xb(n,a.def,Cb(a.def,a.scope,a.ttl),a.scope);e?.effective&&ib(n,Hv(e.effective)),ky(a.def.cap),o.push(a.def.label)}catch(t){Ay(a.def.cap),Cy(null);let n=O(t,w(`settings.common.retryLater`)),r=w(`grants.flow.presetInterrupted`,{label:a.def.label,reason:n,done:o.length>0?w(`grants.flow.presetDone`,{list:o.join(w(`grants.copy.listSep`))}):w(`grants.flow.presetNoGrant`)});Iy({text:r,cls:`err`}),X(r,`err`,1e4),Kb(e),await e.refresh(!0);return}}Cy(null);let s=w(`grants.flow.presetComplete`,{list:o.join(w(`grants.copy.listSep`))});Iy({text:s,cls:`busy`}),X(s,`ok`,6e3),await e.refresh(!0)}async function Yb(e,t){let n=Dv().get(t.cap);if(!n)return Iy({text:w(`grants.flow.presetUnavailable`),cls:`err`}),null;let r={};if(t.scopeKind===`dir`){let t=await Bm(w(`grants.flow.chooseDirPreset`,{label:e.label}),w(`grants.flow.chooseDirPresetNote`,{permanent:Nv()}));if(t===null||t.trim()===``)return Iy({text:w(`grants.flow.presetNoDir`),cls:`err`}),null;r={roots:[t.trim()]}}else if(t.scopeKind===`hosts`){let e=ey.get(t.cap)??``,i=Ub(e.trim()===``?(t.hosts??[]).join(`, `):e);if(i.error!==``)return $v.set(t.cap,i.error),Iy({text:w(`grants.flow.presetBadHosts`,{label:n.label}),cls:`err`}),null;r={hosts:i.values}}return{def:n,scope:r,ttl:mb(e,bb(n))}}async function Xb(e,t,n,r){let i=await yv(t.cap,r);for(let r=0;r<2;r++){let a=await j.grantToken(e,t.cap,i);if(!a.token)throw new D(O(a.error,w(`grants.flow.cannotStart`)));try{let t=await j.grantCap(e,n,a.token);if(t.ok===!1)throw new D(O(t.error,w(`grants.flow.grantFailedRetry`)));return{effective:t.effective,grant:t.grant}}catch(e){if(e instanceof D&&(e.status===403||e.status===409)&&r===0)continue;throw e}}return null}ay((e,t)=>Jb(e,t));async function Zb(e,t){let n=e.focusedSession();if(n===``)return;let r=t?Dv().get(t):void 0;jy(t),Kb(e);try{let i=await j.revokeCap(n,t?{cap:t}:{});ky(t);let a=(i.revoked??[]).length,o=t&&r?w(`grants.flow.revokedOne`,{label:r.label}):a>1?w(`grants.flow.revokedMany`,{n:a}):w(`grants.flow.revoked`);Iy({text:o,cls:`busy`}),X(o,`ok`,6e3),i.effective&&ib(n,Hv(i.effective)),await e.refresh(!0)}catch(n){My(t);let r=w(`grants.flow.revokeFailed`,{reason:O(n,w(`settings.common.retryLater`))});Iy({text:r,cls:`err`}),X(r,`err`,8e3),Kb(e)}}var Qb=2e4,$b=null,ex=!1,tx={refresh:e=>ax(e),focusedSession:()=>ix(),renderPanel:()=>Ib(tx),startGrant:e=>qb(tx,e),revoke:e=>Zb(tx,e)};function nx(e){let t=e?`on`:`off`;if(sy()===t)return;cy(t),eb(e);let n=dy();n&&n.classList.toggle(`hidden`,!e),e?(ox(),ax(!0)):(Nb(),sx())}async function rx(e=!1){let t=Date.now();if(!(!e&&sy()!==`unknown`&&t-ly()<6e4)){uy(t);try{nx((await j.health()).capabilities?.grants===!0)}catch{nx(!1)}}}function ix(){let e=jr();return e===``?R.selSession??``:e}async function ax(e=!1){if(sy()!==`on`)return;let t=ix();if(t===``){_y(null,``),sb(),vy()&&Ib(tx);return}if(!e&&vy()===null&&t===gy()&&hy()!==null){sb();return}let n=t,r=Date.now();try{let e=await j.grants(n);if(n!==ix())return;_y(e,n),Ny(e.grants??[],r),tb(n);let t=(e.grants??[]).filter(e=>typeof e.cap==`string`&&!Bv(e)),i=t.map(e=>String(e.cap));ib(n,{count:t.length,danger:i.some(e=>Tv.has(e)),caps:i})}catch(e){if(n!==ix()||e instanceof D&&e.status===0)return;_y(null,n)}sb(),vy()&&Ib(tx)}function ox(){$b===null&&($b=window.setInterval(()=>{ax(!0)},Qb))}function sx(){$b!==null&&(window.clearInterval($b),$b=null)}function cx(){if(ex)return;ex=!0,fy(document.getElementById(`slGrant`)),my(document.getElementById(`slGrantBadge`));let e=dy();e&&e.addEventListener(`click`,e=>{e.stopPropagation(),Pb(tx)}),document.addEventListener(`click`,t=>{let n=vy();if(!n)return;let r=t.target;(typeof t.composedPath==`function`?t.composedPath():[]).some(e=>e===n)||n.contains(r)||e&&e.contains(r)||Nb()}),Br(()=>{$v.clear(),Iy(null),Py(),sy()===`on`&&ax(!0)}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&ax(!0)}),rx(!0),window.setInterval(()=>{sy()===`off`&&rx(!0)},6e4)}var lx=`hint-text-card`;function ux(e,t){let n=N(`div`,`hint-card-text`),r=(e.getAttribute(`data-hint-tag`)??``).trim();return r&&n.appendChild(N(`span`,`hint-card-tag`,r)),n.appendChild(N(`span`,`hint-card-body`,t)),n}function dx(){return{id:lx,priority:0,claim(e,t){return t?{build:()=>ux(e,t)}:null}}}function fx(){return[{id:lx,label:w(`plugins.desc.textCard.label`),hint:w(`plugins.desc.textCard.hint`),hot:!0,create:()=>dx()},{id:ha,label:w(`plugins.desc.railPreview.label`),hint:w(`plugins.desc.railPreview.hint`),hot:!0,create:()=>Ha()}]}function px(){return fx().map(e=>e.id)}function mx(e){return fx().find(t=>t.id===e)??null}function hx(){for(let e of fx())Wi(e.create())}function gx(e){return Ui(e)}function _x(e,t){let n=mx(e);if(n===null)return{ok:!1,text:w(`plugins.notFound`)};try{t?Gi(e):Ki(e)}catch(r){return vx(e,!t),console.warn(`[plugins] 切换失败:`+(r instanceof Error?r.message:String(r))),{ok:!1,text:w(`plugins.toggleFailed`,{label:n.label})}}return Ri(e,!t,px()),{ok:!0,text:w(`plugins.toggled`,{state:w(t?`plugins.on`:`plugins.off`),label:n.label})}}function vx(e,t){try{t?Gi(e):Ki(e)}catch(e){console.warn(`[plugins] 回滚失败:`+(e instanceof Error?e.message:String(e)))}}function yx(){Ai(),hx()}function bx(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`viewBox`,`0 0 16 16`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`1.3`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`);let r=document.createElementNS(t,`path`);switch(e){case`folder`:r.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v7a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z`);break;case`file`:r.setAttribute(`d`,`M3 1.5h6l4 4v9h-10zM9 1.5v4h4`);break;case`search`:r.setAttribute(`d`,`M6.5 11.5a5 5 0 1 1 0-10 5 5 0 0 1 0 10zM14.5 14.5l-3.8-3.8`);break;case`sort`:r.setAttribute(`d`,`M2 4h12M5 8h7M8 12h4`);break;case`folder-plus`:r.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v4M1.5 3.5v8a1 1 0 0 0 1 1h5.5M11 9v5M8.5 11.5h5`);break;case`plus`:r.setAttribute(`d`,`M8 3v10M3 8h10`)}return n.appendChild(r),n}function xx(){let e=`http://www.w3.org/2000/svg`,t=document.createElementNS(e,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`width`,`10`),t.setAttribute(`height`,`10`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(e,`path`);return n.setAttribute(`d`,`M8 1.6 13.2 3.4v4.2c0 3.1-2.1 5.6-5.2 6.8-3.1-1.2-5.2-3.7-5.2-6.8V3.4z`),t.appendChild(n),t}function Q(e){let t=document.getElementById(`sideFoot`);t&&(t.textContent=e)}function Sx(e){let t=jr()||Lg();for(let n of e.querySelectorAll(`.sess-leaf`))n.classList.toggle(`active`,n.dataset.id===t)}function Cx(e){for(let t of e.querySelectorAll(`.sess-dot[data-dot]`)){let e=Fr(t.dataset.dot??``);t.classList.toggle(`busy`,e),bi(t,w(e?`shell.tree.running`:`shell.tree.idle`))}for(let t of e.querySelectorAll(`.ws-worker-row`)){let e=Fr(t.dataset.id??``);t.classList.toggle(`running`,e);let n=t.querySelector(`.ws-worker-state`);n&&(n.textContent=w(e?`shell.tree.running`:`shell.tree.idle`),n.classList.toggle(`busy`,e))}}function wx(e,t){if(!t||t.count<=0){e.classList.add(`hidden`),e.replaceChildren(),e.title=``;return}e.classList.remove(`hidden`),e.classList.toggle(`danger`,t.danger),e.title=t.danger?w(`shell.tree.grantDanger`,{n:t.count}):w(`shell.tree.grantRelaxed`,{n:t.count}),e.firstChild||e.appendChild(xx())}function Tx(e){for(let t of e.querySelectorAll(`.sess-leaf-grant[data-grant-mark]`))wx(t,nb(t.dataset.grantMark??``))}var Ex=null,Dx=null,Ox=null,kx=null,Ax=`\0`;function jx(e){let t=(e.title??``).trim();if(t)return t;if(e.id===``)return w(`shell.sessbar.unresolved`);let n=e.id.lastIndexOf(`/`);return n>=0?e.id.slice(n+1):e.id}function Mx(){let e=M(`#sessionBar`);Ex=N(`span`,`sess-bar-name`,`—`),Dx=N(`span`,`sess-bar-kind hidden`,`WORKER`),Ox=N(`span`,`sess-bar-state`,w(`shell.sessbar.idle`)),kx=N(`span`,`sess-bar-others`);let t=N(`span`,`sess-bar-lead`,w(`shell.sessbar.session`));e.replaceChildren(t,Dx,Ex,Ox,kx)}function Nx(){let e=B();if(!Ex||!Ox||!Dx||!kx)return;if(!e){Ex.textContent=`—`,Ox.textContent=w(`shell.sessbar.idle`),Ox.className=`sess-bar-state`,Dx.classList.add(`hidden`),kx.replaceChildren(),Ax=`\0`;return}let t=e.streaming||Fr(e.id);Ex.textContent=jx(e),Ex.title=e.id||w(`shell.sessbar.unresolvedShort`),Dx.classList.toggle(`hidden`,e.kind!==`worker`),Ox.textContent=t?e.streaming?``:w(`shell.sessbar.background`):w(`shell.sessbar.idle`),Ox.className=`sess-bar-state`+(t?` busy`:``);let n=Cr().filter(t=>t!==e&&(t.streaming||Fr(t.id))),r=n.map(e=>e.id).join(`|`);if(r===Ax)return;if(Ax=r,!n.length){kx.replaceChildren();return}let i=document.createDocumentFragment();i.appendChild(N(`span`,`sess-bar-sep`,`·`)),i.appendChild(N(`span`,`sess-bar-note`,w(`shell.sessbar.others`,{n:n.length})));for(let e of n){let t=N(`button`,`sess-bar-chip`,jx(e));t.type=`button`,t.title=w(`shell.sessbar.switchTo`,{name:e.id||w(`shell.sessbar.thatSession`)}),t.addEventListener(`click`,()=>{sm(e.id,{kind:e.kind,title:e.title})}),i.appendChild(t)}kx.replaceChildren(...Array.from(i.childNodes))}function Px(e,t=`steer`){let n=e.trim(),r=B();if(!r)return;let i=Xd();if(n!==``||i!==0){if(m_(n)){M_(),r.draft=``,a_(n,r);return}if(r.kind===`worker`){Ix(r,n,t);return}if(r.streaming&&i>0){let e=w(`chat.send.busyWithAttachments`);X(e,`err`,6e3),Q(e);return}if(r.draft=``,r.streaming){Rx(r,n,t);return}Fx(r,n)}}function Fx(e,t){let n=e.id,r=Qd(n),i=zh(n),a=ff(e,t,{attachments:af(r),quotes:i});M_(),Dh(),hv(e),Rr(e,!0),e.turn=null,e.t0=Date.now(),e.phase=w(`chat.send.starting`),vh(e),V(e)&&(R.t0=e.t0,P_(!0),Y(w(`chat.send.starting`),`busy`),tv()),Nx(),ud(r).then(()=>nf(r)).then(n=>j.turn(dd(Yf(t,i),r),ov(e),void 0,n)).then(t=>{t.session&&Pr(t.session),e.turn===null&&t.turn!==void 0&&(e.turn=t.turn),e.phase=w(`chat.send.running`),V(e)&&($_(e.turn===null?t.turn??0:e.turn),Y(w(`chat.send.running`),`busy`))}).catch(o=>Lx({ctx:e,key:n,col:a,text:t,items:r,quotes:i,err:o}))}async function Ix(e,t,n){if(t===``)return;if(Xd()>0){let t=w(`chat.send.workerNoImages`);V(e)&&X(t,`err`,6e3),gf(e,t,`warn`);return}let r=zh(e.id),i=ff(e,t,{kind:n===`queue`?`queued`:`user`,quotes:r});M_(),e.draft=``;let a=vf(e,w(`chat.send.delivering`),void 0,i);hv(e);try{let n=await j.turn(Yf(t,r),ov(e)),i=n.status!==void 0&&n.status!==``&&n.status!==`RUNNING`;a.textContent=i?w(`chat.send.workerSettled`,{status:n.status??``}):w(`chat.send.workerDelivered`),a.className=`interject-note ok`,V(e)&&X(w(i?`chat.send.workerSettledShort`:`chat.send.workerDeliveredShort`),`ok`,4e3)}catch(n){i.remove(),a.parentElement?.remove(),e.interjectNote=null,r.length>0&&Bh(e.id,r),zx(e,t);let o=w(`chat.send.notDelivered`,{reason:sv(n)});V(e)&&(Y(o,`err`),window.setTimeout(()=>X(o,`err`,6e3),0)),gf(e,o,`warn`)}}function Lx(e){let{ctx:t,key:n,col:r,text:i,items:a,quotes:o,err:s}=e;Rr(t,!1),t.phase=w(`chat.send.failedPrefix`).replace(/[:: ]+$/,``),mv()===t&&hv(null);let c=a.length>0||o.length>0;c&&(r.remove(),a.length>0&&$d(n,a),o.length>0&&Bh(n,o),zx(t,i),Dh(),Lh());let l=w(`chat.send.failedPrefix`)+sv(s)+(c?w(`chat.send.failedRolledSuffix`):``);V(t)&&(P_(!1),nv(),Y(l,`err`),window.setTimeout(()=>X(l,`err`,6e3),0)),gf(t,l,c?`warn`:`err`),c&&Q(l),Nx()}async function Rx(e,t,n){let r=zh(e.id),i=Yf(t,r),a=ff(e,t,{kind:n===`queue`?`queued`:`steering`,quotes:r});M_(),Dh(),e.draft=``;let o=w(n===`queue`?`chat.send.queuedWaiting`:`chat.send.interjectedWaiting`),s=w(n===`queue`?`chat.send.queuedDone`:`chat.send.interjectedDone`),c=vf(e,o,void 0,a);hv(e),V(e)&&X(w(n===`queue`?`chat.send.queuedShort`:`chat.send.interjectedShort`),`busy`,4e3);let l=e=>{c.textContent=e,c.className=`interject-note ok`};try{let t=await j.turn(i,ov(e),n);if(t.placement===`queued`){l(s);return}if(t.placement===`steering`){l(w(`chat.send.interjectedDone`));return}if(t.placement===void 0){if(t.injected===!0){l(w(`chat.send.interjectedDone`));return}if(t.queued===!0||n===`queue`){l(s);return}}e.turn=t.turn??e.turn,Rr(e,!0),e.phase=w(`chat.send.running`),l(w(`chat.send.asNewTurn`)),Nx()}catch(o){if(n===`queue`)try{let t=await j.turn(i,ov(e),`steer`);if(t.injected!==!1){let e=hf(t.inbox_target??`next-step`);l(w(`chat.send.queueUnsupported`,{lane:e?w(`chat.send.laneSuffix`,{lane:e}):``}));return}}catch{}a.remove(),c.parentElement?.remove(),e.interjectNote=null,r.length>0&&Bh(e.id,r),zx(e,t);let s=w(n===`queue`?`chat.send.queueNotDelivered`:`chat.send.steerNotDelivered`,{reason:sv(o)});V(e)&&(Y(s,`err`),window.setTimeout(()=>X(s,`err`,6e3),0)),gf(e,s,`warn`)}}function zx(e,t){if(e.draft=t,!V(e))return;let n=document.querySelector(`#input`);n&&n.value.trim()===``&&N_(t)}var Bx=`.msg.info.downgrade`;function Vx(e){let t=e.cause;return[e.model??``,typeof t==`string`?t:``,e.message??``].join(`\0`)}function Hx(e){return e.el.querySelector(Bx)}function Ux(e,t){let n=Pd(t),r=n.split(`
|
|
98
|
-
`)[0]??n,i=Vx(t),a=Hx(e);if(a){if(_f(a,n),a.dataset.downgradeSig===i)return;a.dataset.downgradeSig=i}else{let t=gf(e,n,`err`,`downgrade`);if(t===null)return;t.dataset.downgradeSig=i}V(e)&&X(r,`err`,6e3)}function Wx(){return{cancelled:w(`chat.phase.cancelled`),error:w(`chat.phase.error`)}}function Gx(e){let t=typeof e.session==`string`&&e.session!==``?e.session:null;return t===null?mv()??B()??wr(``):Pr(t)||(Sr(t)??wr(t))}function Kx(e,t){let n=Qe({...t.statusline??{},...t});Object.keys(n).length>0&&(e.status={...e.status??{},...n})}function qx(e){F_(e.kind===`worker`?`worker`:e.streaming?`interject`:`idle`)}function Jx(e){R.t0=e.t0,R.turn=e.turn,R.assistant=e.assistant,$_(e.turn),P_(e.streaming),qx(e),ci.setSession(e.id),e.streaming?(tv(),Y(e.phase||w(`chat.phase.running`),`busy`)):(nv(),e.phase?Y(e.phase,e.phase===Wx().error||e.phase===Wx().cancelled?`err`:`ok`):R.conn===`online`?Y(w(`shell.status.online`),`ok`):R.conn===`down`&&Y(w(`shell.status.reconnecting`),`err`)),Nx()}function Yx(e,t){kf(e);let n=e.streaming;Rr(e,!1),e.turn=null,e.phase=Wx()[t]??``;let r=e.assistant;r&&(ku(r)?zu(e,r):Au(e,r)),e.assistant=null,mv()===e&&hv(null),V(e)&&(R.turn=null,R.assistant=null,P_(!1),rv(),e.phase===``?Y(R.conn===`down`?w(`shell.status.reconnecting`):w(`shell.status.online`),R.conn===`down`?`err`:`ok`):Y(e.phase,t===`error`||t===`cancelled`?`err`:`ok`)),n&&W(e,!0),Nx()}function Xx(e,t){if(Nd(t)){Ux(e,t);return}if(t.phase===`start`){V(e)&&av(),kf(e),e.streaming&&e.assistant&&(ku(e.assistant)?Yx(e,`completed`):Au(e,e.assistant)),e.turn=t.turn??null,e.t0=Date.now(),e.phase=w(`chat.phase.running`),Rr(e,!0),vh(e),V(e)&&(R.t0=e.t0,P_(!0),Y(w(`chat.phase.running`),`busy`),$_(e.turn),tv()),Nx();return}(t.turn===void 0||t.turn===null||e.turn===null||t.turn===e.turn)&&((t.phase===`completed`||t.phase===`cancelled`||t.phase===`error`)&&(Yx(e,t.phase||``),t.phase===`error`&&gf(e,w(`chat.status.turnError`,{reason:t.error||w(`chat.status.unknownError`)}),`err`)),t.phase===`lagged`&&gf(e,w(`chat.status.lagged`),`warn`),t.hint&&gf(e,String(t.hint),`warn`))}function Zx(e,t){if(e.turn===null&&(e.turn=t.turn??null),t.turn!==void 0&&t.turn!==e.turn)return;e.streaming===!1&&Rr(e,!0);let n=Kp(e,t.delta||``);n!==null&&(Fu(e,Ru(e),n),V(e)&&$_(e.turn))}function Qx(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||t.turn===e.turn)&&jf(e,t.delta||``)}function $x(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||e.turn===null||t.turn===e.turn)&&(Af(e),Lu(e),Ch(e,t),W(e))}function eS(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||e.turn===null||t.turn===e.turn)&&(Th(e,t),W(e))}function tS(e,t){if(e.turn===null&&(e.turn=t.turn??null),t.turn!==void 0&&e.turn!==null&&t.turn!==e.turn)return;if(Af(e),e.assistant===null&&typeof t.text==`string`&&t.text!==``){if(qp(e,t.text))return;Iu(e,Ru(e),t.text),W(e);return}let n=e.assistant;if(n){if(qp(e,t.text)){n.root.remove(),e.assistant=null;return}typeof t.text==`string`&&Iu(e,n,t.text),W(e)}}function nS(){let e=new he;return e.onConn(e=>{R.conn=e,e===`online`?Y(R.streaming?w(`chat.phase.running`):w(`shell.status.online`),R.streaming?`busy`:`ok`):e===`down`&&Y(w(`shell.status.reconnecting`),`err`)}),e.on(`status`,e=>{try{let t=Gx(e);V(t)?(ci.fromSse(e),e.session&&t.status&&(t.status={...t.status,...Qe(e)})):Kx(t,e),Xx(t,e)}catch(e){console.warn(`SSE status`,e)}}),e.on(`text`,e=>{try{Zx(Gx(e),e)}catch(e){console.warn(`SSE text`,e)}}),e.on(`thinking`,e=>{try{Qx(Gx(e),e)}catch(e){console.warn(`SSE thinking`,e)}}),e.on(`tool`,e=>{try{$x(Gx(e),e)}catch(e){console.warn(`SSE tool`,e)}}),e.on(`tool_result`,e=>{try{eS(Gx(e),e)}catch(e){console.warn(`SSE tool_result`,e)}}),e.on(`done`,e=>{try{ci.onSseDone(),tS(Gx(e),e)}catch(e){console.warn(`SSE done`,e)}}),e.on(`context`,e=>{try{gf(Gx(e),e.text||w(`chat.status.contextEvent`),e.cls===`err`?`err`:e.cls===`warn`?`warn`:void 0)}catch(e){console.warn(`SSE context`,e)}}),e.on(`compact`,e=>{try{dv(e)}catch(e){console.warn(`SSE compact`,e)}}),e.on(`inbox`,e=>{try{iS(Gx(e),e)}catch(e){console.warn(`SSE inbox`,e)}}),Wp(e,Gx),e.connect(),e}function rS(){let e=B();e&&e.streaming&&(Y(w(`chat.status.cancelling`),`busy`),j.cancel(ov(e)).catch(e=>{Y(w(`chat.status.cancelFailed`,{reason:sv(e)}),`err`)}))}function iS(e,t){let n=(t.text??t.note??t.hint??``).trim();n!==``&&mf(e,n,{source:t.source,target:t.target})}function aS(){j_({send(e,t){Px(e,t)},cancel:rS}),Br(e=>{no(e),so(e),Jx(e),Dh(),V_(),Cm(null,e)}),Vr(e=>{Nx();let t=B();t&&(t.id===e||t.id===``&&e===``)&&(qx(t),P_(t.streaming)),Cm(null,t)})}var oS=M(`#settingsTools`),sS=M(`#toolsCount`);function cS(e,t){let n=e??[];if(sS.textContent=String(n.length),t.replaceChildren(),!n.length){t.appendChild(N(`div`,`side-note`,w(`settings.tools.empty`)));return}let r=N(`table`,`tools-table`),i=N(`thead`),a=N(`tr`);a.appendChild(N(`th`,null,w(`settings.field.name`))),a.appendChild(N(`th`,null,w(`settings.field.description`))),i.appendChild(a),r.appendChild(i);let o=N(`tbody`);for(let e of n){let t=N(`tr`),n=N(`td`,`tools-name`);n.textContent=String(e.name),n.title=String(e.name),t.appendChild(n);let r=N(`td`,`tools-desc`);r.textContent=e.description?String(e.description):`—`,t.appendChild(r),o.appendChild(t)}r.appendChild(o),t.appendChild(r)}function lS(){let e=document.createElement(`div`);return j.tools().then(t=>{cS(t.tools,e),oS.replaceChildren(...e.childNodes)}).catch(t=>{sS.textContent=`—`,e.appendChild(N(`div`,`side-note err`,w(`settings.tools.unavailable`))),e.appendChild(N(`div`,`side-note`,t instanceof Error?t.message:String(t))),oS.replaceChildren(...e.childNodes)})}var uS=3;function dS(e){let t=typeof e==`string`?e.toLowerCase():``;return t===``?``:t.includes(`unknown workspace`)?w(`settings.batch.reasonUnknownWorkspace`):t.includes(`unknown session`)?w(`settings.batch.reasonUnknownSession`):``}function fS(e){let t=(e.id??``).trim();if(t===``)return w(`settings.batch.unknownTail`);let n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function pS(e,t){let n=Array.isArray(t?.failed)?t.failed:[];if(n.length===0)return``;for(let t of n)typeof t?.error==`string`&&t.error!==``&&console.warn(`[batch] `+e+`失败 `+(t.id??``)+`:`+t.error);let r=typeof t?.deleted==`number`?t.deleted:t?.archived,i=typeof r==`number`&&r>0?w(`settings.batch.rest`,{n:r}):``,a=dS(n[0]?.error);if(n.length===1)return w(`settings.batch.failedOne`,{verb:e,reason:a===``?fS(n[0]):a,rest:i});let o=n.map(fS),s=o.slice(0,uS).join(w(`settings.batch.listSep`)),c=o.length>uS?w(`settings.batch.more`,{n:o.length}):``,l=a===``?``:w(`settings.batch.headSep`,{reason:a});return w(`settings.batch.failedMany`,{verb:e,n:n.length,head:l,shown:s,more:c,rest:i})}function mS(e){return(Array.isArray(e?.failed)?e.failed:[]).map(e=>e?.id??``).filter(e=>e!==``)}var hS=[[`.ws-details`,`.ws-count`],[`.arc-ws`,`.arc-ws-count`]];function gS(e){return`[data-id="`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)+`"]`}function _S(e,t){if(!e)return;let n=Number.parseInt(e.textContent??``,10);Number.isFinite(n)&&(e.textContent=String(Math.max(0,n+t)))}function vS(e,t){for(let[n,r]of hS){let i=e.closest(n);i&&_S(i.querySelector(r),t)}}function yS(e){let t=e.container.querySelector(e.rowSel+gS(e.id));if(!t)return null;let n=t.parentElement;if(!n)return null;let r=t.nextElementSibling;vS(t,-1),_S(e.countEl??null,-1),t.remove();let i=!0;return{restore(){if(!i)return;i=!1;let a=r&&r.parentElement===n?r:null;n.insertBefore(t,a),vS(t,1),_S(e.countEl??null,1)}}}var bS=`.sess-leaf, .ws-worker-row`;function xS(e){if(e!==``){R.selSession===e&&(R.selSession=null),Lg()===e&&Rg(null),Dr(e);for(let t of _e(bS))t.dataset.id===e&&t.classList.remove(`active`,`sel`)}}function SS(e){for(let t of e)xS(t)}function CS(e){let t=(e??``).trim();if(t===``)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function wS(e){let t=(e.title??``).trim();return t===``?CS(e.id):t}function TS(e){let t=(e.workspace??``).trim();return t===``?`root`:t}function ES(e,t){let n=typeof e.modified==`number`?e.modified:-1,r=typeof t.modified==`number`?t.modified:-1;return r===n?wS(e).localeCompare(wS(t),`zh`):r-n}function DS(e){return(Array.isArray(e)?e:[]).filter(e=>e.archived===!0).sort(ES)}function OS(e){let t=new Map;for(let n of e){let e=TS(n),r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({workspace:e,rows:t})).sort((e,t)=>e.workspace.localeCompare(t.workspace,`zh`))}function kS(e){return e>0?String(e):`—`}function AS(e){return e.length===0}function jS(){return w(`settings.archive.empty`)}function MS(e){return w(`settings.archive.restoreConfirm`,{label:e})}function NS(e){return w(`settings.archive.deleteConfirm`,{label:e})}var PS=0,FS=!1;function IS(e,t=!1){let n=document.getElementById(`settingsArchiveHint`);n&&(n.className=t?`cfg-hintline err`:`cfg-hintline`,n.textContent=e)}function LS(e,t,n){let r=N(`button`,t,e);return r.type=`button`,r.addEventListener(`click`,n),r}function RS(e,t){let n=e.id??``,r=wS(e),i=N(`div`,`arc-row`);i.dataset.id=n;let a=N(`div`,`arc-main`);a.appendChild(N(`div`,`arc-title`,r));let o=CS(n);o!==``&&a.appendChild(N(`div`,`arc-id`,o)),i.appendChild(a);let s=N(`div`,`arc-actions`);return s.appendChild(LS(w(`settings.action.restore`),`btn-mini`,()=>void GS(n,r,t))),s.appendChild(LS(w(`settings.action.delete`),`btn-mini danger`,()=>void KS(n,r,t))),i.appendChild(s),i}function zS(e,t,n){let r=N(`details`,`arc-ws`);r.open=!0;let i=N(`summary`,`arc-ws-head`);i.appendChild(N(`span`,`arc-ws-name`,e)),i.appendChild(N(`span`,`arc-ws-count`,String(t.length))),r.appendChild(i);for(let e of t)r.appendChild(RS(e,n));return r}function BS(e,t){let n=N(`div`,`arc-wrap`);if(AS(e))return n.appendChild(N(`div`,`side-note`,jS())),n;for(let r of OS(e))n.appendChild(zS(r.workspace,r.rows,t));return n}function VS(e){let t=N(`div`,`arc-wrap`);return t.appendChild(N(`div`,`side-note err`,w(`settings.archive.unavailable`))),t.appendChild(N(`div`,`side-note`,O(e))),t}function HS(e,t,n){let r=++PS,i={container:e,countEl:t};return t&&n?.quiet!==!0&&(t.textContent=`…`),j.sessions({archived:!0}).then(n=>{if(r!==PS)return;let a=DS(n.sessions);t&&(t.textContent=kS(a.length)),e.replaceChildren(...BS(a,i).childNodes)}).catch(n=>{r===PS&&(t&&(t.textContent=`—`),e.replaceChildren(...VS(n).childNodes))})}async function US(e,t,n,r,i,a){FS=!0;let o=yS({container:a.container,id:n,rowSel:`.arc-row`,countEl:a.countEl});try{let s=pS(e,await r());s===``?(t&&xS(n),IS(i),await HS(a.container,a.countEl,{quiet:!0})):(o?.restore(),IS(s,!0))}catch(t){o?.restore(),IS(w(`settings.archive.failed`,{verb:e,reason:O(t)}),!0)}finally{FS=!1}}function WS(){let e=document.getElementById(`settingsArchive`);e&&HS(e,document.getElementById(`settingsArchiveCount`),{quiet:!0})}async function GS(e,t,n){FS||e===``||await Uv({title:w(`settings.archive.restoreTitle`),message:MS(t),okLabel:w(`settings.action.restore`)})&&await US(w(`settings.action.restore`),!1,e,()=>j.unarchiveSession(e),w(`settings.archive.restored`,{name:t}),n)}async function KS(e,t,n){FS||e===``||await Uv({title:w(`settings.archive.deleteTitle`),message:NS(t),okLabel:w(`settings.action.delete`),danger:!0})&&await US(w(`settings.action.delete`),!0,e,()=>j.batchDeleteSessions([e]),w(`settings.archive.deleted`,{name:t}),n)}var qS=[`low`,`high`,`max`];function JS(e,t=``,n=``){let r=N(`div`,`prov-model-row`),i=N(`input`,`cfg-input`);i.placeholder=w(`settings.providers.modelId`),i.value=t;let a=N(`input`,`cfg-input`);a.placeholder=w(`settings.providers.modelDisplayName`),a.value=n;let o=document.createElement(`details`);o.className=`prov-model-adv`;let s=document.createElement(`summary`);s.textContent=w(`settings.providers.advanced`),o.appendChild(s);let c=N(`div`,`prov-model-adv-body`),l=new Set,u=e=>e.replace(/\s+/g,``).toLowerCase(),d=new Map,f=N(`div`,`prov-effort-chips`),p=N(`button`,`btn-mini`,`+`);p.type=`button`,p.title=w(`settings.providers.addEffortTier`);let m=N(`input`,`cfg-input`);m.placeholder=w(`settings.providers.customTierPlaceholder`),m.hidden=!0,m.style.width=`170px`,m.style.flex=`0 0 auto`;let h=N(`span`,`cfg-hint`);h.hidden=!0,f.appendChild(p),f.appendChild(m),f.appendChild(h);let g=(e,t)=>{let n=e.dataset.effort??``;t?l.add(n):l.delete(n),e.classList.toggle(`on`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)},_=(t,n=!1)=>{let r=u(t);if(r===``||d.has(r))return;let i=N(`button`,`prov-effort-chip`,t);i.type=`button`,i.dataset.effort=t,i.addEventListener(`click`,()=>{g(i,!l.has(i.dataset.effort??``)),e.onLayout?.()}),d.set(r,i),f.insertBefore(i,p),g(i,n)},v=e=>{h.textContent=e,h.hidden=e===``},y=t=>{if(m.hidden)return;let n=m.value;if(m.value=``,m.hidden=!0,p.hidden=!1,t){let e=n.trim();e!==``&&(d.has(u(e))?v(w(`settings.providers.tierExists`,{tier:e})):(v(``),_(e,!0)))}e.onLayout?.()};p.addEventListener(`click`,()=>{m.hidden&&(v(``),m.value=``,m.hidden=!1,p.hidden=!0,e.onLayout?.(),m.focus())}),m.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),y(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y(!1))}),m.addEventListener(`blur`,()=>y(!0));for(let e of qS)_(e);let b={root:f,set(e){let t=new Map;for(let n of e){let e=n.trim();if(e===``)continue;let r=u(e);t.has(r)||t.set(r,e)}for(let[e,n]of t)d.has(e)||_(n);l.clear();for(let[e,n]of d)g(n,t.has(e))},values(){let e=[];for(let t of qS){let n=d.get(u(t))?.dataset.effort;n!==void 0&&l.has(n)&&e.push(n)}for(let t of d.values()){let n=t.dataset.effort??``;n!==``&&!qS.includes(n)&&l.has(n)&&e.push(n)}return e}},x=N(`input`,`cfg-input`);x.type=`text`,x.min=`0`,x.placeholder=w(`settings.providers.contextPlaceholder`);let ee=N(`input`,`cfg-input`);ee.type=`text`,ee.min=`0`,ee.placeholder=w(`settings.providers.maxOutPlaceholder`),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.providers.reasoningEffort`))),c.appendChild(f),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.providers.modelContext`))),c.appendChild(x),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.field.maxOutputTokens`))),c.appendChild(ee),o.appendChild(c),o.addEventListener(`toggle`,()=>e.onLayout?.());let te=N(`button`,`btn-mini danger`,w(`settings.action.remove`));te.type=`button`,te.addEventListener(`click`,()=>{r.remove(),e.rows=e.rows.filter(e=>e.li!==r),e.onLayout?.()}),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(te),e.modelsBox.appendChild(r),e.rows.push({id:i,name:a,efforts:b,ctx:x,maxOut:ee,li:r}),e.onLayout?.()}var YS=null;function XS(e,t){YS?.();let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card prov-picker`);r.appendChild(N(`div`,`modal-card-title`,w(`settings.providers.pickTitle`))),r.appendChild(N(`div`,`side-note`,w(`settings.providers.pickNote`)));let i=N(`div`,`prov-picker-list`),a=[],o=N(`div`,`prov-picker-count`),s=()=>{let e=a.filter(e=>e.checked).length;o.textContent=w(`settings.providers.pickCount`,{n:e,total:a.length})},c=document.createElement(`div`);for(let t of e){let e=N(`label`,`prov-picker-row`+(t.existing?` existing`:``)),n=N(`input`,`prov-picker-cb`);n.type=`checkbox`,n.checked=!1,n.disabled=t.existing,n.dataset.modelId=t.id,n.addEventListener(`change`,s),e.appendChild(n),e.appendChild(N(`span`,`prov-picker-id`,t.id)),t.existing&&e.appendChild(N(`span`,`prov-picker-tag`,w(`settings.providers.pickExisting`))),c.appendChild(e),t.existing||a.push(n)}i.replaceChildren(...c.childNodes),s(),r.appendChild(i),r.appendChild(o);let l=N(`div`,`modal-card-actions`),u=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));u.type=`button`;let d=N(`button`,`btn btn-accent`,w(`settings.action.confirm`));d.type=`button`;let f=null,p=()=>{YS===p&&(YS=null),f&&(F(f),f=null),n.remove()};YS=p,u.addEventListener(`click`,p),d.addEventListener(`click`,()=>{let e=a.filter(e=>e.checked).map(e=>e.dataset.modelId??``).filter(Boolean);p(),t(e)}),n.addEventListener(`click`,e=>{e.target===n&&p()}),l.appendChild(u),l.appendChild(d),r.appendChild(l),n.appendChild(r),document.body.appendChild(n),f=P(p),u.focus()}var ZS=M(`#settingsProviders`),QS=[],$S=null,eC=new Set;function tC(){return QS}function nC(){return $S}function rC(e,t){QS=e,$S=t}function iC(e){$S=e}function aC(e){return e instanceof Error?e.message:String(e)}var oC=[{value:`chat_completions`,label:`Chat Completions`},{value:`responses`,label:`Responses`},{value:`anthropic_messages`,label:`Anthropic Messages`}];function sC(e){let t=e.rows.filter(e=>e.id.value.trim()!==``||e.name.value.trim()!==``).map(e=>({id:e.id.value.trim(),name:e.name.value.trim()||e.id.value.trim(),reasoning_efforts:e.efforts.values(),context_window:cC(e.ctx),max_output_tokens:cC(e.maxOut)})),n=e.key.value.trim();return{id:e.originalId??e.name.value.trim(),name:e.name.value.trim(),note:e.note.value.trim(),base_url:e.url.value.trim(),request_format:e.format.value,...n===``?{}:{api_key:n},models:t}}function cC(e){let t=e.value.trim().toLowerCase().replace(/\s+/g,``);if(t===``)return null;let n=/^(\d+(?:\.\d+)?)([km])?$/.exec(t);if(!n)return null;let r=Number(n[1]);if(!Number.isFinite(r)||r<0)return null;let i=n[2]===`k`?1e3:n[2]===`m`?1e6:1,a=Math.round(r*i);return Number.isFinite(a)&&a>=0?a:null}function lC(e,t){let n=N(`div`,`prov-form`),r=N(`div`,`prov-editor-status`);n.appendChild(r);let i=(e,t)=>{let n=N(`label`,`prov-field`);return n.appendChild(N(`span`,`prov-field-label`,e)),n.appendChild(t),n},a=N(`input`,`cfg-input`);a.placeholder=w(`settings.providers.idPlaceholder`),a.value=e?.name??``,n.appendChild(i(w(`settings.field.name`),a));let o=N(`input`,`cfg-input`);o.placeholder=w(`settings.providers.notePlaceholder`),o.value=e?.note??``,n.appendChild(i(w(`settings.providers.note`),o));let s=N(`input`,`cfg-input`);s.type=`password`,s.placeholder=e?w(`settings.providers.keyPlaceholderExisting`):`API Key`,s.value=``,n.appendChild(i(`API Key`,s));let c=N(`input`,`cfg-input`);c.placeholder=`https://…/v1`,c.value=e?.base_url??``;let l=N(`button`,`btn btn-soft btn-mini`,w(`settings.providers.requestTest`));l.type=`button`;let u=N(`div`,`prov-urlrow`);u.appendChild(c),u.appendChild(l),n.appendChild(i(w(`settings.providers.apiUrl`),u));let d=document.createElement(`select`);d.className=`cfg-input`;for(let e of oC){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,d.appendChild(t)}if(e?.request_format){if(!oC.some(t=>t.value===e.request_format)){let t=document.createElement(`option`);t.value=e.request_format,t.textContent=e.request_format,d.appendChild(t)}d.value=e.request_format}n.appendChild(i(w(`settings.providers.requestFormat`),d));let f=N(`div`,`prov-models-head`);f.appendChild(N(`span`,`prov-models-title`,w(`settings.field.model`)));let p=N(`button`,`btn btn-soft btn-mini`,w(`settings.providers.fetchModels`));p.type=`button`,p.title=w(`settings.providers.fetchModelsHint`),f.appendChild(p),n.appendChild(f);let m=N(`div`,`prov-models`);n.appendChild(m);let h={root:n,name:a,note:o,key:s,url:c,format:d,modelsBox:m,status:r,rows:[],onLayout:t.onLayout,originalId:e?.id};for(let t of e?.models??[]){JS(h,t.id,t.name);let e=h.rows[h.rows.length-1];e.efforts.set(t.reasoning_efforts??[]),t.context_window!=null&&(e.ctx.value=String(t.context_window))}let g=N(`button`,`btn-mini`,w(`settings.providers.addModel`));g.type=`button`,g.addEventListener(`click`,()=>JS(h)),n.appendChild(g);let _=N(`div`,`modal-card-actions`),v=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));v.type=`button`;let y=N(`button`,`btn btn-accent`,w(`settings.action.save`));y.type=`button`,l.addEventListener(`click`,()=>{r.className=`prov-editor-status`,r.textContent=w(`settings.providers.testing`),j.testProvider(sC(h)).then(e=>{if(e.ok===!1||e.ok===void 0&&e.error){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.testFailed`,{reason:O(e.error,w(`settings.common.checkUrlKey`))});return}r.className=`prov-editor-status ok`,r.textContent=w(`settings.providers.testOk`,{ms:e.latency_ms??`—`,n:e.model_count??`—`})}).catch(e=>{r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.testFailed`,{reason:aC(e)})})});let b=0;return p.addEventListener(`click`,()=>{let e=++b,t=a.value.trim();if(!t){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.needId`);return}r.className=`prov-editor-status`,r.textContent=w(`settings.providers.savingAndFetching`),j.saveProvider(sC(h)).then(()=>j.fetchProviderModels(t)).then(t=>{if(e!==b)return;if(t.ok===!1||t.ok===void 0&&t.error){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.fetchFailed`,{reason:O(t.error,w(`settings.common.checkUrlKey`))});return}let n=t.models??[];if(!n.length){r.className=`prov-editor-status`,r.textContent=w(`settings.providers.noModelsFetched`);return}let i=new Set(h.rows.map(e=>e.id.value.trim()).filter(Boolean));r.className=`prov-editor-status ok`,r.textContent=w(`settings.providers.fetched`,{n:n.length}),XS(n.map(e=>({id:e.id,existing:i.has(e.id)})),e=>{let t=e.filter(e=>!h.rows.some(t=>t.id.value.trim()===e));for(let e of t)JS(h,e,e);r.className=`prov-editor-status ok`,r.textContent=t.length?w(`settings.providers.added`,{n:t.length,total:n.length}):w(`settings.providers.noneSelected`,{n:n.length})})}).catch(t=>{e===b&&(r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.fetchFailed`,{reason:aC(t)}))})}),y.addEventListener(`click`,()=>{let e=sC(h);if(!e.id){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.idRequired`);return}r.className=`prov-editor-status`,r.textContent=w(`settings.config.saving`),y.disabled=!0,j.saveProvider(e).then(n=>{if(n.ok===!1){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.saveFailed`,{reason:O(n.error,w(`settings.common.checkInput`))}),y.disabled=!1;return}y.disabled=!1,r.className=`prov-editor-status ok`,r.textContent=w(`settings.config.saved`),t.onSaved(e)}).catch(e=>{r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.saveFailed`,{reason:aC(e)}),y.disabled=!1})}),v.addEventListener(`click`,()=>t.onCancel()),_.appendChild(v),_.appendChild(y),n.appendChild(_),h}function uC(e){return e.models?.length??0}function dC(e,t){let n=document.createElement(`div`);t.is_default&&n.appendChild(N(`span`,`prov-badge`,w(`settings.tag.default`))),t.has_key&&n.appendChild(N(`span`,`prov-badge key`,w(`settings.providers.keyConfigured`))),!t.is_default&&!t.has_key&&(n.textContent=`—`),e.replaceChildren(...n.childNodes)}function fC(e,t){let n=e.dataset.id??``;e.dataset.id=t.id,n!==t.id&&eC.delete(n)&&eC.add(t.id),e.classList.toggle(`is-default`,t.is_default===!0);let r=e.querySelector(`.prov-name`);r&&(r.textContent=t.name||t.id);let i=e.querySelector(`.prov-td-note`);i&&(i.textContent=t.note??`—`);let a=e.querySelector(`.prov-td-fmt`);a&&(a.textContent=t.request_format??`—`);let o=e.querySelector(`.prov-td-models`);o&&(o.textContent=String(uC(t)));let s=e.querySelector(`.prov-td-state`);s&&dC(s,t)}function pC(e,t=``){let n=ZS.querySelector(`.prov-list-msg`);n&&(n.textContent=e,n.className=`prov-list-msg`+(t?` `+t:``))}async function mC(e,t,n){try{let r=await j.providers();rC(r.providers??[],r.default_model??null);let i=tC().find(e=>e.id===n);if(!i){e.loadProviders();return}fC(t,i)}catch{e.loadProviders()}}var hC=new Set;function gC(){for(let e of hC)e.overlay&&(F(e.overlay),e.overlay=null);hC.clear()}function _C(e){if(!e.open)return;let t=e.inner.style.maxHeight;t!==`none`&&t!==``&&(e.inner.style.maxHeight=e.inner.scrollHeight+`px`)}function vC(e){if(e.open)return;e.open=!0;let t=e.tr.dataset.id??``;t&&eC.add(t),e.tr.classList.add(`expanded`),e.tr.setAttribute(`aria-expanded`,`true`),e.panelTr.classList.add(`open`),e.inner.style.maxHeight=e.inner.scrollHeight+`px`,e.overlay=P(()=>yC(e))}function yC(e){if(!e.open)return;e.open=!1;let t=e.tr.dataset.id??``;t&&eC.delete(t),e.overlay&&(F(e.overlay),e.overlay=null),e.inner.style.maxHeight===`none`&&(e.inner.style.maxHeight=e.inner.scrollHeight+`px`,e.inner.offsetHeight),e.panelTr.classList.remove(`open`),e.tr.classList.remove(`expanded`),e.tr.setAttribute(`aria-expanded`,`false`),e.inner.style.maxHeight=`0px`}function bC(e){e.open?yC(e):vC(e)}function xC(e,t){let n=N(`tr`,`prov-row`);n.dataset.id=t.id,n.title=w(`settings.providers.expandHint`),n.setAttribute(`aria-expanded`,`false`),t.is_default&&n.classList.add(`is-default`);let r=N(`td`,`prov-td-name`);r.appendChild(N(`span`,`prov-name`,t.name||t.id)),n.appendChild(r),n.appendChild(N(`td`,`prov-td-note`,t.note??`—`)),n.appendChild(N(`td`,`prov-td-fmt`,t.request_format??`—`)),n.appendChild(N(`td`,`prov-td-models`,String(uC(t))));let i=N(`td`,`prov-td-state`);dC(i,t),n.appendChild(i);let a=N(`td`,`prov-td-ops`),o=N(`button`,`btn-mini danger`,w(`settings.action.delete`));o.type=`button`,o.addEventListener(`click`,t=>{t.stopPropagation();let r=n.dataset.id??``,i=tC().find(e=>e.id===r);Uv({title:w(`settings.providers.deleteTitle`),message:w(`settings.providers.confirmDelete`,{name:i?.name||r}),okLabel:w(`settings.action.delete`),danger:!0}).then(t=>{t&&j.deleteProvider(r).then(()=>void e.loadProviders()).catch(e=>pC(w(`settings.providers.deleteFailed`,{reason:aC(e)})))})}),a.appendChild(o),n.appendChild(a);let s=N(`tr`,`prov-panel-row`),c=N(`td`,`prov-panel-td`);c.colSpan=6;let l=N(`div`,`prov-inline`);c.appendChild(l),s.appendChild(c);let u={tr:n,panelTr:s,inner:l,open:!1,overlay:null};hC.add(u);let d=lC(t,{onSaved:t=>{yC(u),mC(e,n,t.id)},onCancel:()=>yC(u),onLayout:()=>_C(u)});return l.appendChild(d.root),l.addEventListener(`transitionend`,e=>{e.target===l&&e.propertyName===`max-height`&&u.open&&(l.style.maxHeight=`none`)}),n.addEventListener(`click`,e=>{let t=e.target;t instanceof Element&&t.closest(`button, a, input, select, textarea, label`)||bC(u)}),eC.has(t.id)&&(u.open=!0,n.classList.add(`expanded`),n.setAttribute(`aria-expanded`,`true`),s.classList.add(`open`),l.style.maxHeight=`none`,u.overlay=P(()=>yC(u))),{tr:n,panelTr:s}}function SC(e,t){if(gC(),e.replaceChildren(),!tC().length){e.appendChild(N(`div`,`side-note`,w(`settings.providers.empty`)));return}let n=N(`table`,`prov-table`),r=N(`thead`),i=N(`tr`);for(let e of[w(`settings.field.name`),w(`settings.providers.note`),w(`settings.providers.requestFormat`),w(`settings.field.model`),w(`settings.field.status`),w(`settings.field.actions`)])i.appendChild(N(`th`,null,e));r.appendChild(i),n.appendChild(r);let a=N(`tbody`);for(let e of tC()){let n=xC(t,e);a.appendChild(n.tr),a.appendChild(n.panelTr)}n.appendChild(a),e.appendChild(n)}function CC(e,t){let n=N(`div`,`prov-default-card`),r=N(`div`,`prov-default-head`);r.appendChild(N(`span`,`prov-default-title`,w(`settings.providers.defaultModel`))),r.appendChild(N(`span`,`prov-default-note`,w(`settings.providers.defaultNote`))),n.appendChild(r);let i=N(`div`,`prov-default-body`);i.appendChild(N(`span`,`prov-default-label`,w(`settings.providers.currentDefault`)));let a=document.createElement(`select`);a.className=`cfg-input prov-default-sel`;let o=new Set;for(let e of tC())for(let t of e.models??[]){let n=document.createElement(`option`);n.value=t.id,n.textContent=(e.name||e.id)+` / `+t.id,o.add(t.id),a.appendChild(n)}if(nC()!==null&&!o.has(nC()??``)){let e=document.createElement(`option`);e.value=nC()??``,e.textContent=w(`settings.providers.defaultNotInList`,{model:nC()??``}),a.appendChild(e)}a.value=nC()??``;let s=N(`span`,`prov-default-msg`);a.addEventListener(`change`,()=>{let e=a.value;e&&(s.textContent=w(`settings.providers.applyingDefault`),s.className=`prov-default-msg`,j.setDefaultModel(e).then(()=>{iC(e),s.textContent=w(`settings.providers.defaultApplied`),s.className=`prov-default-msg ok`,t.loadProviders()}).catch(e=>{s.textContent=w(`settings.providers.switchFailed`,{reason:aC(e)}),s.className=`prov-default-msg err`,a.value=nC()??``}))}),i.appendChild(a),i.appendChild(s),n.appendChild(i),e.appendChild(n)}var wC={loadProviders:()=>TC()};async function TC(){let e=document.createElement(`div`);try{let e=await j.providers();rC(e.providers??[],e.default_model??null)}catch(t){e.appendChild(N(`div`,`side-note err`,w(`settings.providers.listUnavailable`))),e.appendChild(N(`div`,`side-note`,aC(t))),ZS.replaceChildren(...e.childNodes);return}SC(e,wC),CC(e,wC),ZS.replaceChildren(...e.childNodes)}var EC=null;function DC(){EC?.();let e=N(`div`,`modal-scrim`),t=N(`div`,`modal-card prov-modal`);t.appendChild(N(`div`,`modal-card-title`,w(`settings.providers.add`)));let n=null,r=()=>{EC===r&&(EC=null),n&&(F(n),n=null),e.remove()};EC=r;let i=lC(null,{onSaved:()=>{r(),TC()},onCancel:r});t.appendChild(i.root),e.appendChild(t),document.body.appendChild(e),n=P(r),i.name.focus()}function OC(){M(`#btnAddProvider`).addEventListener(`click`,()=>DC())}var kC=M(`#settingsPrompts`),AC=M(`#promptsWrap`);function jC(){return[[`{{model}}`,w(`settings.prompts.varCurrentModel`)],[`{{provider}}`,w(`settings.field.provider`)],[`{{base_url}}`,w(`settings.prompts.varApiUrl`)],[`{{workspace}}`,w(`settings.prompts.varWorkspaceName`)],[`{{session}}`,w(`settings.prompts.varSessionTitle`)],[`{{tools}}`,w(`settings.prompts.varToolList`)],[`{{context_window}}`,w(`settings.field.contextWindow`)],[`{{max_output_tokens}}`,w(`settings.field.maxOutputTokens`)],[`{{date}}`,w(`settings.prompts.varCurrentDate`)]]}var MC=`global`,NC=``,PC=[],FC=[],IC=null;function LC(e){return e instanceof Error?e.message:String(e)}function RC(e){return w(e===`global`?`settings.scope.global`:`settings.scope.workspace`)}function zC(){let e=document.createElement(`div`);if(!FC.length){e.appendChild(N(`div`,`side-note`,w(MC===`global`?`settings.prompts.emptyGlobal`:`settings.prompts.emptyWorkspace`))),kC.replaceChildren(...e.childNodes);return}let t=N(`table`,`prompts-table`),n=N(`thead`),r=N(`tr`);for(let e of[w(`settings.field.name`),w(`settings.prompts.scope`),w(`settings.field.status`),w(`settings.field.actions`)])r.appendChild(N(`th`,null,e));n.appendChild(r),t.appendChild(n);let i=N(`tbody`);for(let e of FC){let t=N(`tr`);e.id===IC&&t.classList.add(`is-active`);let n=N(`td`,`prompts-td-name`);n.appendChild(N(`span`,`prompt-name`,e.name||e.id)),e.id===IC&&n.appendChild(N(`span`,`prompt-badge active`,w(`settings.tag.active`))),t.appendChild(n),t.appendChild(N(`td`,`prompts-td-scope`,RC(e.scope)));let r=N(`td`,`prompts-td-state`);e.is_default&&r.appendChild(N(`span`,`prompt-badge def`,w(`settings.tag.default`))),!e.is_default&&e.id!==IC&&(r.textContent=`—`),t.appendChild(r);let a=N(`td`,`prompts-td-ops`),o=N(`button`,`btn-mini`,w(`settings.action.edit`));o.type=`button`,o.addEventListener(`click`,()=>VC(e));let s=N(`button`,`btn-mini`,w(`settings.prompts.setDefault`));s.type=`button`,s.disabled=!!e.is_default,s.addEventListener(`click`,()=>{j.setDefaultPrompt(e.id,MC===`global`?void 0:NC||void 0).then(()=>{BC(w(`settings.prompts.setDefaultDone`,{name:e.name||e.id})),UC()}).catch(e=>BC(w(`settings.prompts.setDefaultFailed`,{reason:LC(e)})))});let c=N(`button`,`btn-mini danger`,w(`settings.action.delete`));c.type=`button`,c.addEventListener(`click`,()=>{Uv({title:w(`settings.prompts.deleteTitle`),message:w(`settings.prompts.confirmDelete`,{name:e.name||e.id}),okLabel:w(`settings.action.delete`),danger:!0}).then(t=>{t&&j.deletePrompt(e.id,MC===`global`?void 0:NC||void 0).then(()=>{BC(w(`settings.prompts.deleted`,{name:e.name||e.id})),UC()}).catch(e=>BC(w(`settings.prompts.deleteFailed`,{reason:LC(e)})))})}),a.appendChild(o),a.appendChild(s),a.appendChild(c),t.appendChild(a),i.appendChild(t)}t.appendChild(i),e.appendChild(t),e.appendChild(N(`div`,`prompts-note`,w(`settings.prompts.legend`))),kC.replaceChildren(...e.childNodes)}function BC(e){let t=document.getElementById(`sideFoot`);t&&(t.textContent=e)}function VC(e){let t=N(`div`,`modal-scrim`),n=N(`div`,`modal-card prompt-modal`);n.appendChild(N(`div`,`modal-card-title`,e?w(`settings.prompts.editTitle`,{name:e.name||e.id}):w(`settings.prompts.newPrompt`)));let r=N(`details`,`prompt-vars`),i=document.createElement(`summary`);i.textContent=w(`settings.prompts.variables`),r.appendChild(i);let a=N(`table`,`prompt-vars-table`),o=N(`tbody`);for(let[e,t]of jC()){let n=N(`tr`);n.appendChild(N(`td`,`prompt-var-code`,e)),n.appendChild(N(`td`,`prompt-var-desc`,t)),o.appendChild(n)}a.appendChild(o),r.appendChild(a),n.appendChild(r);let s=N(`label`,`prov-field`);s.appendChild(N(`span`,`prov-field-label`,w(`settings.field.name`)));let c=N(`input`,`cfg-input`);c.placeholder=w(`settings.prompts.promptName`),c.value=e?.name??``,s.appendChild(c),n.appendChild(s);let l=N(`div`,`ws-fs-status`);n.appendChild(l);let u=N(`div`,`prompt-secs`);n.appendChild(u),PC.length||u.appendChild(N(`div`,`side-note`,w(`settings.prompts.noSegmentEdit`)));let d=[];for(let t of PC){let n=N(`div`,`prompt-sec-row`),r=N(`div`,`prompt-sec-head`);r.appendChild(N(`span`,`prompt-sec-name`,t.name||t.id)),r.appendChild(N(`span`,`prompt-sec-scope`,RC(t.scope)));let i=N(`input`,`prompt-inherit`);i.type=`checkbox`,i.checked=!0;let a=N(`label`,`prompt-inherit-label`);a.appendChild(i),a.appendChild(N(`span`,null,w(`settings.prompts.inherit`))),r.appendChild(a),n.appendChild(r);let o=N(`textarea`,`prompt-sec-ta cfg-input`);o.rows=3,o.disabled=!0,o.placeholder=w(`settings.prompts.inheritedFromBuiltin`);let s=e?.section_overrides?.[t.id];s!==void 0&&(i.checked=!1,o.value=s),n.appendChild(o),u.appendChild(n),d.push({sec:t,ta:o,inherit:i});let c=()=>{o.disabled=i.checked,o.placeholder=i.checked?w(`settings.prompts.inheritedFromBuiltin`):w(`settings.prompts.overridePlaceholder`),n.classList.toggle(`inherited`,i.checked)};i.addEventListener(`change`,c),c()}let f=N(`div`,`modal-card-actions`),p=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));p.type=`button`;let m=N(`button`,`btn btn-accent`,w(`settings.action.save`));m.type=`button`;let h=null,g=()=>{h&&(F(h),h=null),t.remove()};h=P(g),p.addEventListener(`click`,g),m.addEventListener(`click`,()=>{let t=c.value.trim();if(!t){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.nameRequired`),c.focus();return}let n={};!d.length&&e?.section_overrides&&Object.assign(n,e.section_overrides);for(let e of d)if(!e.inherit.checked){if(e.ta.value.trim()===``){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.segmentNoOverride`,{name:e.sec.name||e.sec.id}),e.ta.focus();return}n[e.sec.id]=e.ta.value}m.disabled=!0,m.textContent=w(`settings.config.saving`),j.savePrompt({id:e?.id??`p`+Date.now().toString(36),name:t,section_overrides:n,workspace:MC===`workspace`&&NC||void 0}).then(e=>{if(e.ok===!1){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.saveFailed`,{reason:O(e.error,w(`settings.common.checkInput`))}),m.disabled=!1,m.textContent=w(`settings.action.save`);return}g(),BC(w(`settings.prompts.saved`,{name:t})),UC()}).catch(e=>{l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.saveFailed`,{reason:LC(e)}),m.disabled=!1,m.textContent=w(`settings.action.save`)})}),f.appendChild(p),f.appendChild(m),n.appendChild(f),t.appendChild(n),document.body.appendChild(t),c.focus()}var HC=0;async function UC(){let e=++HC,t=document.createElement(`div`),n;try{n=await j.prompts(MC===`workspace`&&NC||void 0)}catch(n){if(e!==HC)return;t.appendChild(N(`div`,`side-note err`,w(`settings.prompts.unsupported`))),t.appendChild(N(`div`,`side-note`,LC(n))),kC.replaceChildren(...t.childNodes);return}e===HC&&(PC=n.sections??[],FC=n.prompts??[],IC=n.active_prompt??null,zC())}function WC(){let e=N(`div`,`prompts-scope`),t=N(`button`,`prompts-scope-btn`+(MC===`global`?` active`:``),w(`settings.scope.global`));t.type=`button`;let n=N(`button`,`prompts-scope-btn`+(MC===`workspace`?` active`:``),w(`settings.scope.workspace`));n.type=`button`;let r=document.createElement(`select`);r.className=`cfg-input prompts-ws-sel`,r.style.display=MC===`workspace`?``:`none`;let i=e=>{MC=e,t.classList.toggle(`active`,e===`global`),n.classList.toggle(`active`,e===`workspace`),r.style.display=e===`workspace`?``:`none`};t.addEventListener(`click`,()=>{i(`global`),UC()}),n.addEventListener(`click`,()=>{i(`workspace`),UC()}),e.appendChild(t),e.appendChild(n),e.appendChild(r),AC.appendChild(e),j.workspaces().then(e=>{let t=e.workspaces??[];r.replaceChildren();for(let e of t){let t=document.createElement(`option`);t.value=e.name,t.textContent=e.name,r.appendChild(t)}t.length?(NC=t[0].name,r.value=NC,r.disabled=!1):r.disabled=!0}).catch(()=>{r.disabled=!0}),r.addEventListener(`change`,()=>{NC=r.value,UC()}),M(`#btnNewPrompt`).addEventListener(`click`,()=>VC(null)),UC()}var GC=[404,409,422];function KC(e,t){return e instanceof D?GC.includes(e.status)&&e.technical.trim()!==``?e.technical:e.message:O(e,t)}function qC(e){return e.ok===!1||e.preset===void 0}async function JC(e){let t=An();Fn(e);try{let t=await j.createPermissionPreset(e);if(qC(t)||t.preset===void 0)throw new D(w(`settings.permissions.rejected`));return Fn(t.preset),{ok:!0,text:w(`settings.permissions.savedCustom`),preset:t.preset}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.saveFailed`,{reason:KC(e,w(`settings.common.checkInput`))})}}}async function YC(e){let t=An();Fn(e);try{let t=await j.updatePermissionPreset(e.id,e);if(qC(t)||t.preset===void 0)throw new D(w(`settings.permissions.rejected`));return Fn(t.preset),{ok:!0,text:w(`settings.permissions.savedCustom`),preset:t.preset}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.saveFailed`,{reason:KC(e,w(`settings.common.checkInput`))})}}}async function XC(e){let t=An(),n=Nn(e)?.label??e;In(e);try{if((await j.deletePermissionPreset(e)).ok===!1)throw new D(w(`settings.permissions.opRejected`));return{ok:!0,text:w(`settings.permissions.deleted`,{label:n})}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.deleteFailed`,{reason:KC(e,w(`settings.common.retryLater`))})}}}var ZC=32,QC=64;function $C(){return w(`settings.permissions.idHint`)}function ew(){return w(`settings.permissions.rootsHint`)}function tw(){return w(`settings.permissions.toolsHint`)}function nw(e,t){let n=N(`input`,`cfg-input`);return n.type=`text`,n.value=e,n.placeholder=t,n}function rw(e,t){let n=N(`button`,`btn-mini`,e);return n.type=`button`,n.addEventListener(`click`,t),n}function iw(e,t,n){let r=N(`label`,`cfg-field`);return r.appendChild(N(`span`,`cfg-label`,e)),r.appendChild(t),n!==void 0&&n!==``&&r.appendChild(N(`span`,`cfg-hint`,n)),r}function aw(e,t,n){let r=N(`div`,`cfg-field`);r.appendChild(N(`span`,`cfg-label`,e));let i=N(`div`,`perm-field-body`);return i.appendChild(t),n!==void 0&&n!==``&&i.appendChild(N(`span`,`cfg-hint`,n)),r.appendChild(i),r}function ow(e,t,n){let r=N(`input`,`perm-switch-input`);r.type=`checkbox`,r.checked=t;let i=N(`label`,`perm-switch`);return i.appendChild(r),i.appendChild(N(`span`,`perm-switch-label`,e)),n!==void 0&&n!==``&&i.appendChild(N(`span`,`cfg-hint`,n)),{input:r,row:i}}function sw(e){let t=N(`div`,`perm-roots-edit`),n=N(`div`,`perm-roots-list`),r=e.slice(0,ZC),i=()=>{let e=document.createElement(`div`);for(let t of r){let n=N(`div`,`perm-root-row`);n.appendChild(N(`code`,`perm-root`,t)),n.appendChild(rw(w(`settings.action.remove`),()=>{let e=r.indexOf(t);e>=0&&r.splice(e,1),i()})),e.appendChild(n)}r.length===0&&e.appendChild(N(`div`,`side-note`,w(`settings.permissions.noExtraRootsAdded`))),n.replaceChildren(...e.childNodes)},a=e=>{let t=e.trim();t===``||r.includes(t)||r.length>=ZC||(r.push(t),i())},o=nw(``,w(`settings.permissions.rootPlaceholder`)),s=N(`div`,`perm-addrow`);return s.append(o,rw(w(`settings.action.add`),()=>{a(o.value),o.value=``}),rw(w(`settings.permissions.chooseDir`),()=>{Bm(w(`settings.permissions.chooseExtraDir`),ew()).then(e=>{e!==null&&a(e)})})),t.append(n,s),i(),{el:t,value:()=>r.slice()}}function cw(e,t,n){let r=N(`input`,`perm-tool-input`);r.type=`checkbox`,r.checked=t,r.addEventListener(`change`,()=>{r.checked?n.add(e):n.delete(e)});let i=N(`label`,`perm-tool`);return i.append(r,N(`span`,`perm-tool-name`,e)),i}function lw(e){let t=N(`div`,`perm-tools`),n=new Set(e),r=(r,i)=>{let a=document.createElement(`div`),o=new Set;for(let e of r.slice(0,QC))a.appendChild(cw(e,n.has(e),n)),o.add(e);for(let t of e)o.has(t)||a.appendChild(cw(t,!0,n));i!==``&&a.appendChild(N(`div`,`side-note`,i)),t.replaceChildren(...a.childNodes)};return r(e,``),j.tools().then(e=>{let t=(e.tools??[]).map(e=>e.name).filter(e=>typeof e==`string`&&e!==``);r(t,t.length===0?w(`settings.permissions.toolsNotLoaded`):``)}).catch(()=>r(e,w(`settings.permissions.toolsUnavailableReload`))),{el:t,value:()=>Array.from(n).slice(0,QC)}}function uw(e){e.classList.add(`hidden`),e.replaceChildren()}function dw(e,t,n){let r=t===null,i=nw(t?.id??``,w(`settings.permissions.idPlaceholder`));i.disabled=!r;let a=nw(t?.label??``,w(`settings.permissions.labelPlaceholder`)),o=ow(w(`settings.permissions.networkOn`),t?.network===!0),s=ow(w(`settings.permissions.workspaceOn`),t?.workspaceWritable===!0),c=ow(w(`settings.permissions.toolRootOn`),t?.toolRootsWritable===!0),l=ow(w(`settings.permissions.allPathsOn`),t?.allPaths===!0,w(`settings.permissions.allPathsRisk`)),u=ow(w(`settings.permissions.unsandboxedDeclare`),t?.unsandboxed===!0,vn()),d=sw(t?.writeRoots??[]),f=lw(t?.toolDeny??[]),p=N(`div`,`perm-editor-status`),m=N(`button`,`btn btn-accent`,w(`settings.action.save`));m.type=`button`;let h=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));h.type=`button`;let g=(e,t)=>{p.className=`perm-editor-status`+(e===``?``:` `+e),p.textContent=t};m.addEventListener(`click`,()=>{let e=i.value.trim();if(e===``)return g(`err`,w(`settings.permissions.saveIdRequired`));if(!yn.test(e))return g(`err`,w(`settings.permissions.idInvalid`,{hint:$C()}));let t={id:e,label:a.value.trim()||e,network:o.input.checked,workspaceWritable:s.input.checked,toolRootsWritable:c.input.checked,writeRoots:d.value(),allPaths:l.input.checked,unsandboxed:u.input.checked,toolDeny:f.value()};m.disabled=!0,g(``,``),(r?JC(t):YC(t)).then(e=>{if(e.ok){n.onSettled(e);return}m.disabled=!1,g(`err`,e.text)})}),h.addEventListener(`click`,()=>n.onCancel());let _=N(`form`,`cfg-form perm-editor-form`);_.appendChild(N(`div`,`perm-editor-title`,r?w(`settings.permissions.newTitle`):w(`settings.permissions.editTitle`,{id:t?.id??``}))),_.appendChild(iw(w(`settings.permissions.idField`),i,r?$C():w(`settings.permissions.idLocked`))),_.appendChild(iw(w(`settings.permissions.labelField`),a,w(`settings.permissions.labelHint`)));let v=N(`div`,`perm-switches`);for(let e of[o,s,c,l,u])v.appendChild(e.row);_.appendChild(aw(w(`settings.permissions.switches`),v)),_.appendChild(aw(w(`settings.permissions.extraRootsLabel`),d.el,ew())),_.appendChild(aw(w(`settings.permissions.toolsField`),f.el,tw()));let y=N(`div`,`cfg-actions`);y.append(m,h),_.appendChild(y),_.appendChild(p);let b=document.createElement(`div`);b.appendChild(_),e.replaceChildren(...b.childNodes),e.classList.remove(`hidden`)}function fw(e,t,n){let r=N(`button`,t,e);return r.type=`button`,r.addEventListener(`click`,n),r}function pw(e,t,n){let r=N(`div`,`perm-card`);r.dataset.id=e.id,r.dataset.builtin=t?`1`:`0`;let i=N(`div`,`perm-card-head`);if(i.appendChild(N(`span`,`perm-card-title`,e.label||e.id)),i.appendChild(N(`code`,`perm-card-id`,e.id)),t)i.appendChild(N(`span`,`perm-badge`,w(`settings.permissions.builtin`)));else{let t=N(`div`,`perm-card-ops`);t.appendChild(fw(w(`settings.action.edit`),`btn-mini`,()=>n.onEdit(e))),t.appendChild(fw(w(`settings.action.delete`),`btn-mini danger`,()=>n.onDelete(e))),i.appendChild(t)}r.appendChild(i);let a=N(`div`,`perm-chips`);for(let t of xn(e))a.appendChild(N(`span`,`perm-chip `+t.tone,t.text));if(r.appendChild(a),e.writeRoots.length>0){let t=N(`div`,`perm-roots`);t.appendChild(N(`span`,`perm-roots-label`,w(`settings.permissions.extraRootsLabel`)));for(let n of e.writeRoots)t.appendChild(N(`code`,`perm-root`,n));r.appendChild(t)}let o=wn(e);return o!==``&&r.appendChild(N(`div`,`perm-card-note`,o)),r}function mw(e,t){let n=document.createElement(`div`),r=An();if(r===null)n.appendChild(N(`div`,`side-note`,w(`settings.permissions.unavailable`)));else{for(let e of r.builtin)n.appendChild(pw(e,!0,t));for(let e of r.custom)n.appendChild(pw(e,!1,t));r.custom.length===0&&n.appendChild(N(`div`,`side-note`,w(`settings.permissions.emptyCustom`)))}e.replaceChildren(...n.childNodes)}function hw(e){let t=An();e.textContent=t===null?``:Sn(t.max)}var gw=`#settingsPermissions`,_w=!1;function vw(e){return document.querySelector(e)}function yw(){return vw(gw+` .perm-list`)}function bw(){return vw(gw+` .perm-editor`)}function xw(e,t){let n=vw(gw+` .perm-status`);n!==null&&(n.className=`perm-status`+(e===``?``:t?` ok`:` err`),n.textContent=e)}function Sw(e){let t=bw();t!==null&&dw(t,e,{onSettled:e=>{uw(t),xw(e.text,e.ok)},onCancel:()=>uw(t)})}async function Cw(e){if(!await Uv({title:w(`settings.permissions.deleteTitle`),message:w(`settings.permissions.deleteConfirm`,{name:e.label||e.id}),okLabel:w(`settings.action.delete`),danger:!0}))return;let t=await XC(e.id);xw(t.text,t.ok)}function ww(){let e=yw();e!==null&&mw(e,{onEdit:e=>Sw(e),onDelete:e=>void Cw(e)})}function Tw(){let e=vw(gw+` .perm-max`);e!==null&&hw(e)}function Ew(e){let t=document.createElement(`div`),n=N(`div`,`perm-toolbar`);n.appendChild(N(`span`,`perm-max`,``));let r=N(`button`,`btn-mini`,w(`settings.permissions.newPreset`));r.type=`button`,r.id=`btnNewPreset`,r.addEventListener(`click`,()=>Sw(null)),n.appendChild(r),t.append(n,N(`div`,`perm-status`),N(`div`,`perm-list`),N(`div`,`perm-editor hidden`)),e.replaceChildren(...t.childNodes)}function Dw(){_w||(_w=!0,window.addEventListener(Tn,()=>{Tw(),ww()}))}async function Ow(){Ew(M(gw)),Dw(),Tw(),An()!==null&&ww();try{await Ln(!0),Tw(),ww()}catch(e){xw(w(`settings.permissions.unavailableReason`,{reason:O(e,w(`settings.common.retryLater`))}),!1)}}function kw(e){return typeof e==`string`?e.trim():``}function Aw(e){if(Array.isArray(e))return e;if(typeof e!=`object`||!e)return[];let t=e.plugins;return Array.isArray(t)?t:[]}function jw(e){let t=[];for(let n of Aw(e)){if(typeof n!=`object`||!n)continue;let e=n,r=kw(e.name)||kw(e.id);r!==``&&t.push({name:r,version:kw(e.version),note:kw(e.description)})}return t}async function Mw(){return jw(await j.plugins())}var Nw=`#settingsPlugins`;function Pw(e,t){let n=N(`section`,`plug-sec`),r=N(`header`,`plug-sec-head`);return r.appendChild(N(`h5`,`plug-sec-title`,e)),r.appendChild(N(`span`,`plug-sec-note`,t)),n.appendChild(r),n}function Fw(e,t){let n=N(`div`,`plug-row`);n.dataset.id=e.id;let r=N(`div`,`plug-row-main`);r.appendChild(N(`div`,`plug-row-label`,e.label)),r.appendChild(N(`div`,`plug-row-hint`,e.hint)),n.appendChild(r);let i=N(`label`,`plug-switch`),a=document.createElement(`input`);return a.type=`checkbox`,a.className=`plug-switch-input`,a.checked=gx(e.id),a.addEventListener(`change`,()=>{let n=a.checked,r=_x(e.id,n);r.ok||(a.checked=!n),t(r.text,r.ok)}),i.appendChild(a),i.appendChild(N(`span`,`plug-switch-track`)),n.appendChild(i),n}function Iw(e){let t=N(`div`,`plug-host`);t.dataset.name=e.name;let n=N(`div`,`plug-row-main`),r=N(`div`,`plug-row-label`,e.name);return e.version!==``&&r.appendChild(N(`span`,`plug-host-ver`,e.version)),n.appendChild(r),e.note!==``&&n.appendChild(N(`div`,`plug-row-hint`,e.note)),t.appendChild(n),t.appendChild(N(`span`,`plug-badge`,w(`settings.plugins.hostBadge`))),t}function Lw(e,t){let n=document.createElement(`div`);if(t.length===0)n.appendChild(N(`div`,`plug-empty`,w(`settings.plugins.hostEmpty`)));else for(let e of t)n.appendChild(Iw(e));e.replaceChildren(...n.childNodes)}async function Rw(){let e=M(Nw),t=N(`div`,`plug-status`),n=(e,n)=>{t.className=`plug-status`+(e===``?``:n?` ok`:` err`),t.textContent=e},r=Pw(w(`settings.plugins.clientTitle`),w(`settings.plugins.clientNote`)),i=N(`div`,`plug-list`);for(let e of fx())i.appendChild(Fw(e,n));r.appendChild(i),r.appendChild(t);let a=N(`div`,`plug-host-list`),o=Pw(w(`settings.plugins.hostTitle`),w(`settings.plugins.hostNote`));o.appendChild(a);let s=document.createElement(`div`);s.append(r,o),e.replaceChildren(...s.childNodes);try{Lw(a,await Mw())}catch(e){Lw(a,[]),console.warn(`[plugins] `+O(e,w(`settings.plugins.hostUnavailable`)))}}function zw(e){e.documentElement.lang=oe()===`zh`?`zh-CN`:`en`}function Bw(e){for(let t of e.querySelectorAll(`[data-i18n]`)){let e=t.getAttribute(`data-i18n`);e&&(t.textContent=w(e))}for(let t of e.querySelectorAll(`[data-i18n-title]`)){let e=t.getAttribute(`data-i18n-title`);e&&t.setAttribute(`title`,w(e))}for(let t of e.querySelectorAll(`[data-i18n-aria-label]`)){let e=t.getAttribute(`data-i18n-aria-label`);e&&t.setAttribute(`aria-label`,w(e))}}var Vw=()=>{try{location.reload()}catch{}};function Hw(){Vw()}var Uw=new Set,Ww=!1;function Gw(){let e=N(`div`,`cfg-field i18n-field`);e.appendChild(N(`span`,`cfg-label`,w(`common.language`)));let t=N(`select`,`cfg-input`);for(let e of[`zh`,`en`]){let n=N(`option`,null,ce(e));n.value=e,t.appendChild(n)}return t.value=oe(),t.addEventListener(`change`,()=>{let e=t.value;e!==oe()&&(C(e),Hw())}),e.appendChild(t),e.appendChild(N(`span`,`cfg-hint`,w(`common.language.hint`))),Uw.add(e),e}function Kw(e){let t=e.querySelector(`.cfg-label`),n=e.querySelector(`.cfg-hint`),r=e.querySelector(`select`);t&&(t.textContent=w(`common.language`)),n&&(n.textContent=w(`common.language.hint`)),r instanceof HTMLSelectElement&&(r.value=oe())}function qw(e){let t=document.createElement(`div`);t.appendChild(Gw()),e.replaceChildren(...Array.from(t.childNodes))}function Jw(){Ww||(Ww=!0,Yw(),se(()=>{Yw();for(let e of Uw)e.isConnected&&Kw(e)}))}function Yw(){Bw(document),zw(document)}var Xw=M(`#settingsPage`),Zw=M(`#settingsConfig`),Qw=M(`#settingsHint`),$w=[`low`,`high`,`max`],eT={select:(e,t)=>{let n=N(`select`,`cfg-input`);for(let t of e){let e=N(`option`,null,t.label);e.value=t.value,n.appendChild(e)}let r=t??``;if(r!==``&&!e.some(e=>e.value===r)){let e=N(`option`,null,r+w(`settings.suffix.current`));e.value=r,n.appendChild(e)}return n.value=r,n},text:(e,t,n=`text`)=>{let r=N(`input`,`cfg-input`);return r.type=n,r.value=e,t&&(r.placeholder=t),r},num:(e,t)=>{let n=N(`input`,`cfg-input`);return n.type=`number`,n.min=`0`,n.placeholder=t,e!=null&&(n.value=String(e)),n},field:(e,t,n)=>{let r=N(`label`,`cfg-field`);return r.appendChild(N(`span`,`cfg-label`,e)),r.appendChild(t),n&&r.appendChild(N(`span`,`cfg-hint`,n)),r}};function tT(e){let t=e.trim();if(t===``)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:NaN}function nT(e,t,n){n.replaceChildren();let r=N(`form`,`cfg-form`),i=Array.isArray(e.available?.models)?e.available.models:[],a=Array.isArray(e.available?.efforts)?e.available.efforts:[],o=i.length?eT.select(i.map(e=>({value:e.id,label:e.name})),e.model??null):eT.text(e.model??``,w(`settings.config.modelName`));r.appendChild(eT.field(w(`settings.field.model`),o,i.length?``:w(`settings.config.modelNameHint`)));let s=[{value:``,label:w(`settings.config.effortStandard`)}];for(let e of a.length?a:$w)s.push({value:e,label:e});let c=eT.select(s,e.reasoning_effort??null);r.appendChild(eT.field(w(`settings.config.effort`),c,a.length?w(`settings.config.effortHint`):w(`settings.config.effortManual`)));let l=eT.text(e.base_url??``,`https://…/v1`);r.appendChild(eT.field(`Base URL`,l));let u=eT.text(``,w(`settings.config.apiKeyPlaceholder`),`password`);r.appendChild(eT.field(`API Key`,u,w(`settings.config.apiKeyHint`)));let d=e.context_window??e.context_window_tokens??t,f=eT.num(d,w(`settings.config.contextWindowPlaceholder`));r.appendChild(eT.field(w(`settings.field.contextWindow`),f));let p=eT.num(e.max_output_tokens??null,w(`settings.config.noLimit`));r.appendChild(eT.field(w(`settings.field.maxOutputTokens`),p));let m=eT.num(e.max_steps??null,w(`settings.config.notSet`));r.appendChild(eT.field(w(`settings.field.maxSteps`),m));let h=N(`textarea`,`cfg-input cfg-sys`);h.rows=6,h.placeholder=w(`settings.config.systemPromptPlaceholder`),h.value=e.system_prompt??``,r.appendChild(eT.field(w(`settings.field.systemPrompt`),h,w(`settings.config.systemPromptHint`)));let g=N(`div`,`cfg-actions`),_=N(`button`,`btn btn-accent`,w(`settings.action.save`));_.type=`button`;let v=N(`button`,`btn btn-soft`,w(`settings.action.reload`));v.type=`button`,g.appendChild(_),g.appendChild(v),r.appendChild(g);let y=N(`div`,`cfg-status`);r.appendChild(y),n.appendChild(r);let b=(e,t)=>{let n=tT(e.value);if(Number.isNaN(n))throw y.className=`cfg-status err`,y.textContent=w(`settings.config.notAValidNumber`,{name:t}),Error(`bad number: `+t);return n};_.addEventListener(`click`,()=>{y.className=`cfg-status`,y.textContent=``;let t={},n=o.value.trim();n!==``&&n!==(e.model??``)&&(t.model=n);let r=l.value.trim();r!==``&&r!==(e.base_url??``)&&(t.base_url=r),u.value.trim()!==``&&(t.api_key=u.value.trim()),t.reasoning_effort=c.value===``?null:c.value,t.context_window=b(f,w(`settings.field.contextWindow`)),t.max_output_tokens=b(p,w(`settings.field.maxOutputTokens`)),t.max_steps=b(m,w(`settings.field.maxSteps`)),t.system_prompt=h.value,_.disabled=!0,_.textContent=w(`settings.config.saving`),j.saveConfig(t).then(e=>{y.className=`cfg-status ok`,y.textContent=e.ok===!1?w(`settings.config.saveFailedRetry`):w(`settings.config.saved`),e.ok!==!1&&window.dispatchEvent(new Event(`studio:config-saved`))}).catch(e=>{y.className=`cfg-status err`;let t=e;e instanceof D&&e.status===409?y.textContent=w(`settings.config.busySave`):e instanceof D&&(e.status===405||e.status===404)?y.textContent=w(`settings.config.unsupportedSave`):y.textContent=w(`settings.config.saveFailed`,{reason:t.message||String(e)})}).finally(()=>{_.disabled=!1,_.textContent=w(`settings.action.save`)})}),v.addEventListener(`click`,()=>{rT({refresh:!0})})}async function rT(e={}){let t=document.createElement(`div`),n;try{n=e.refresh===!0?await gt():await ht()}catch(e){t.appendChild(N(`div`,`side-note err`,w(`settings.config.unavailable`))),t.appendChild(N(`div`,`side-note`,e instanceof Error?e.message:String(e))),Zw.replaceChildren(...t.childNodes),Qw.textContent=``;return}let r=null;try{r=(await j.status())?.context_usage?.window??null}catch{}try{nT(n,r,t),Qw.textContent=``,Zw.replaceChildren(...t.childNodes)}catch(e){t.appendChild(N(`div`,`side-note err`,w(`settings.config.unavailable`))),t.appendChild(N(`div`,`side-note`,e instanceof Error?e.message:String(e))),Zw.replaceChildren(...t.childNodes),Qw.textContent=``}}var iT=[`general`,`config`,`tools`,`archive`,`providers`,`prompts`,`permissions`,`plugins`],aT=`config`;function oT(e){return M(`.settings-pane[data-pane="`+e+`"]`)}function sT(e){return M(`.settings-nav-item[data-page="`+e+`"]`)}var cT={};function lT(e){e===`general`?qw(M(`#settingsGeneral`)):e===`config`?rT():e===`tools`?lS():e===`archive`?HS(M(`#settingsArchive`),M(`#settingsArchiveCount`)):e===`providers`?TC():e===`prompts`?UC():e===`permissions`?Ow():Rw()}function uT(e){aT=e;for(let t of iT)oT(t).classList.toggle(`active`,t===e);for(let t of iT)sT(t).classList.toggle(`active`,t===e);cT[e]||(cT[e]=!0,lT(e))}function dT(e){lT(e)}function fT(){dT(aT)}var pT=null;function mT(){Xw.classList.remove(`hidden`),pT||(pT=P(hT)),dT(`config`),uT(`config`)}function hT(){if(pT){let e=pT;pT=null,je(e),F(e)}Xw.classList.add(`hidden`)}function gT(){M(`#btnConfig`).addEventListener(`click`,mT),M(`#btnSettingsClose`).addEventListener(`click`,hT),M(`#btnSettingsReload`).addEventListener(`click`,fT);for(let e of iT)sT(e).addEventListener(`click`,()=>uT(e));Jw(),OC(),WC()}function _T(e,t){Mg(!1),bg.clear(),e.renderTreeInto?e.renderTreeInto(t,null):e.loadTreeInto(t,null)}function vT(e){for(let t of e.querySelectorAll(`.sess-check`))t.checked=t.dataset.id!==void 0&&bg.has(t.dataset.id);let t=e.querySelector(`.sess-batchbar`);t&&(t.querySelector(`.sess-batchbar-count`).textContent=w(`shell.tree.selectedCount`,{n:bg.size}),t.classList.toggle(`active`,bg.size>0))}async function yT(e,t){let n=Array.from(bg);if(!n.length||!await Uv({title:w(`shell.tree.batchDeleteTitle`),message:w(`shell.tree.batchDeleteConfirm`,{n:n.length}),okLabel:w(`settings.action.delete`),danger:!0}))return;let r=new Map;for(let e of n){let n=yS({container:t,id:e,rowSel:`.sess-leaf`});n&&r.set(e,n)}let i=Fg();Ig(i.filter(e=>!n.includes(e.id??``)));try{let a=await j.batchDeleteSessions(n),o=pS(w(`settings.action.delete`),a);if(o===``)SS(n),_T(e,t),Q(w(`shell.tree.deletedCount`,{n:n.length}));else{let e=mS(a);SS(n.filter(t=>!e.includes(t)));for(let t of e)r.get(t)?.restore();Ig(i),bg.clear();for(let t of e)bg.add(t);vT(t),Q(o)}WS()}catch(e){for(let e of r.values())e.restore();Ig(i),vT(t),Q(w(`shell.tree.batchDeleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}function bT(e,t,n){xT();let r=e.getBoundingClientRect(),i=N(`div`,`sess-menu`);for(let e of n){let t=N(`button`,`sess-menu-item`+(e.danger?` danger`:``),e.label);t.type=`button`,e.disabled&&(t.disabled=!0,t.classList.add(`disabled`)),t.addEventListener(`click`,t=>{t.stopPropagation(),xT(),e.onPick()}),i.appendChild(t)}e.appendChild(i);let a=Math.max(0,Math.min(t.right-r.left-8,e.clientWidth-180)),o=Math.max(0,Math.min(t.bottom-r.top+2,e.clientHeight-60));i.style.left=a+`px`,i.style.top=o+`px`}function xT(){for(let e of document.querySelectorAll(`.sess-menu`))e.remove()}function ST(e,t,n){sm(t,n),Rg(t),R.selSession=t,Sx(e),Cx(e),Q(n?.title?w(`shell.tree.switchedTo`,{title:n.title}):w(`shell.tree.switched`)),j.activateSession(t).then(e=>{e.ok===!1&&Q(w(`shell.tree.viewOpenActivateFailed`))}).catch(e=>{e instanceof D&&e.status===409?Q(w(`shell.tree.runningViewOpen`)):Q(w(`shell.tree.viewOpenActivateFailed`))})}async function CT(e,t,n,r){if(!await Uv({title:w(`shell.tree.archiveTitle`),message:w(`shell.tree.archiveConfirm`,{label:r}),okLabel:w(`shell.tree.archiveOk`)}))return;let i=yS({container:t,id:n,rowSel:`.sess-leaf`}),a=Fg();Ig(a.filter(e=>e.id!==n));try{let e=await j.archiveSession(n),t=pS(w(`shell.tree.archiveOk`),e);t===``?(xS(n),Q(w(`shell.tree.archived`,{label:r}))):(i?.restore(),Ig(a),Q(t)),WS()}catch(e){i?.restore(),Ig(a),Q(w(`shell.tree.archiveFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function wT(e,t,n,r){if(!await Uv({title:w(`shell.tree.deleteTitle`,{label:r}),message:w(`shell.tree.deleteConfirm`),okLabel:w(`settings.action.delete`),danger:!0}))return;let i=yS({container:t,id:n,rowSel:`.sess-leaf`}),a=Fg();Ig(a.filter(e=>e.id!==n));try{let e=await j.batchDeleteSessions([n]),t=pS(w(`settings.action.delete`),e);t===``?(xS(n),Q(w(`shell.tree.deletedSession`,{label:r}))):(i?.restore(),Ig(a),Q(t)),WS()}catch(e){i?.restore(),Ig(a),Q(w(`shell.tree.deleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function TT(e,t,n,r){let i=window.prompt(w(`shell.tree.renamePrompt`),r);if(i===null)return;let a=i.trim();if(a!==``&&a!==r)try{await j.renameSession(n,a),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.renameFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function ET(e,t,n){let r=window.prompt(w(`shell.tree.branchPrompt`),``);if(r!==null)try{let i=await j.branchSession(n,r.trim()===``?void 0:r.trim());if(i.ok===!1){Q(w(`shell.tree.branchFailedRetry`));return}let a=i.id??i.branch;a&&(R.selSession=a),Q(w(`shell.tree.branched`)),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.branchFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function DT(e,t,n){if(await Uv({title:w(`shell.tree.deleteWsTitle`,{name:n}),message:w(`shell.tree.deleteConfirm`),okLabel:w(`settings.action.delete`),danger:!0}))try{await j.deleteWorkspace(n),Q(w(`shell.tree.wsDeleted`,{name:n})),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.deleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function OT(e,t,n){let r=window.prompt(w(`shell.tree.renameWsPrompt`),n);if(r===null)return;let i=r.trim();if(i!==``&&i!==n)try{await j.renameWorkspace(n,i),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.renameFailed`,{reason:e instanceof Error?e.message:String(e)}))}}function kT(e,t=!0){let n={workspace:e.workspace,title:e.title},r=e.prompt??``;if(r!==``&&(n.prompt=r),!t)return n;let i=e.model??``;return i!==``&&(n.model=i),e.mode===`execution`&&(n.mode=e.mode),n}var AT=new Set([`text`,`search`,`url`,`tel`,`email`,`password`,`number`]);function jT(e){if(e.key!==`Enter`||e.shiftKey)return!1;let t=e.target;if(!t||typeof t.tagName!=`string`||t.tagName.toUpperCase()!==`INPUT`)return!1;let n=typeof t.type==`string`?t.type.toLowerCase():`text`;return AT.has(n===``?`text`:n)}function MT(e,t){let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card`);r.appendChild(N(`div`,`modal-card-title`,w(`shell.new.title`)));let i=N(`input`,`cfg-input`);i.placeholder=w(`shell.new.titlePlaceholder`);let a=N(`label`,`prov-field`);a.appendChild(N(`span`,`prov-field-label`,w(`shell.field.title`))),a.appendChild(i),r.appendChild(a);let o=document.createElement(`select`);o.className=`cfg-input`;let s=document.createElement(`option`);s.value=``,s.textContent=w(`shell.new.rootWorkspace`),o.appendChild(s);for(let e of Ng()){let t=document.createElement(`option`);t.value=e.name,t.textContent=e.name,o.appendChild(t)}t&&(o.value=t);let c=N(`label`,`prov-field`);c.appendChild(N(`span`,`prov-field-label`,w(`settings.scope.workspace`))),c.appendChild(o),r.appendChild(c);let l=document.createElement(`select`);l.className=`cfg-input`;let u=document.createElement(`option`);u.value=``,u.textContent=w(`shell.new.followDefault`),l.appendChild(u);let d=N(`label`,`prov-field`);d.appendChild(N(`span`,`prov-field-label`,w(`settings.field.model`))),d.appendChild(l),r.appendChild(d),j.config().then(e=>{let t=e.available?.models??[];for(let e of t){let t=document.createElement(`option`);t.value=e.id;let n=e.name||e.id,r=(e.provider??``).trim();t.textContent=(r?r+` · `:``)+e.id+(n===e.id?``:`(`+n+`)`),l.appendChild(t)}if(!t.length){let e=document.createElement(`option`);e.value=``,e.textContent=w(`shell.new.noModels`),e.disabled=!0,l.appendChild(e)}}).catch(()=>{let e=document.createElement(`option`);e.value=``,e.textContent=w(`shell.new.modelsUnavailable`),e.disabled=!0,l.appendChild(e)});let f=document.createElement(`select`);f.className=`cfg-input`;for(let e of Kt()){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,f.appendChild(t)}f.value=`standard`;let p=N(`label`,`prov-field`);p.appendChild(N(`span`,`prov-field-label`,w(`shell.field.mode`))),p.appendChild(f),r.appendChild(p);let m=N(`label`,`prov-field`);m.appendChild(N(`span`,`prov-field-label`,w(`shell.field.prompt`)));let h=document.createElement(`select`);h.className=`cfg-input`;let g=document.createElement(`option`);g.value=``,g.textContent=w(`shell.new.followDefault`),h.appendChild(g),m.appendChild(h),m.style.display=`none`,r.appendChild(m),j.prompts().then(e=>{let t=e.prompts??[];if(t.length){for(let e of t){let t=document.createElement(`option`);t.value=e.id,t.textContent=e.name+` (`+(e.scope===`global`?w(`settings.scope.global`):w(`settings.scope.workspace`))+`)`+(e.is_default?` · `+w(`settings.tag.default`):``),h.appendChild(t)}m.style.display=``}}).catch(()=>{});let _=N(`div`,`ws-fs-status`);r.appendChild(_);let v=N(`div`,`modal-card-actions`),y=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));y.type=`button`;let b=N(`button`,`btn btn-accent`,w(`shell.action.create`));b.type=`button`;let x=null,ee=()=>{x&&(F(x),x=null),n.remove()};x=P(ee),y.addEventListener(`click`,ee),b.addEventListener(`click`,()=>{let t=i.value.trim();if(!t){_.className=`ws-fs-status err`,_.textContent=w(`shell.new.titleRequired`),i.focus();return}let n=o.value===``?null:o.value,r=l.value===``?void 0:l.value,a=h.value===``?void 0:h.value;b.disabled=!0,b.textContent=w(`shell.new.creating`);let s=f.value,c=e=>j.createSession(kT({workspace:n,title:t,model:r,prompt:a,mode:s},e));c(!0).catch(e=>{let t=e;if((r!==void 0||s!==`standard`)&&t&&typeof t.status==`number`&&t.status>=400&&t.status<500)return c(!1);throw e}).then(async n=>{if(n.ok===!1)throw Error(O(n.error,w(`shell.new.rejected`)));let r=n.id;if(!r)try{let e=((await j.sessions()).sessions??[]).filter(e=>e.title===t);e.sort((e,t)=>(t.modified??0)-(e.modified??0)),r=e[0]?.id}catch{r=void 0}if(!r){_.className=`ws-fs-status err`,_.textContent=w(`shell.new.createdRefresh`),ee(),e.loadSessions();return}sm(r,{kind:`session`,title:t}),Rg(r),R.selSession=r,Q(w(`shell.new.createdOpened`,{title:t})),j.activateSession(r).then(e=>{e.ok===!1&&Q(w(`shell.tree.viewOpenActivateFailed`))}).catch(e=>{Q(w(`shell.tree.viewOpenFailed`,{reason:O(e,w(`shell.new.activateFailed`))}))}),ee(),e.loadSessions()}).catch(e=>{_.className=`ws-fs-status err`,_.textContent=w(`shell.new.failed`,{reason:e instanceof Error?e.message:String(e)}),b.disabled=!1,b.textContent=w(`shell.action.create`)})}),r.addEventListener(`keydown`,e=>{jT(e)&&(e.preventDefault(),b.disabled||b.click())}),v.appendChild(y),v.appendChild(b),r.appendChild(v),n.appendChild(r),document.body.appendChild(n),i.focus()}function NT(e){zm({title:w(`shell.new.wsTitle`),note:w(`shell.new.wsNote`),confirmLabel:w(`shell.action.create`),busyLabel:w(`shell.new.wsBusy`),fallbackNote:w(`shell.new.wsFallback`),onPick:(t,n)=>{n.setBusy(!0),j.createWorkspaceByPath(t).then(r=>{if(r.ok===!1){n.status.className=`ws-fs-status err`,n.status.textContent=w(`shell.new.wsRegisterFailed`,{reason:O(r.error,w(`shell.new.wsCheckPath`))}),n.setBusy(!1);return}Q(w(`shell.new.wsRegistered`,{path:t})),n.close(),e.loadSessions()}).catch(e=>{n.status.className=`ws-fs-status err`,n.status.textContent=w(`shell.new.wsRegisterFailed`,{reason:O(e,w(`shell.new.wsCheckPath`))}),n.setBusy(!1)})}})}function PT(e){let t=e.parentSessionId??e.parent_session??e.parent;return typeof t==`string`&&t.trim()!==``?t.trim():null}function FT(e){return e.kind===`worker`||(e.id??``).startsWith(`worker:`)}function IT(e){let t=(e.workspace??``).trim();return t===``?`root`:t}function LT(e){let t=e.lastIndexOf(`/`);return t>=0?e.slice(t+1):e}function RT(e){let t=zg();return t===``||e.toLowerCase().includes(t)}function zT(e){let t=[...e];return Vg()===`name`?(t.sort((e,t)=>(e.title||``).localeCompare(t.title||``,`zh`)),t):(t.sort((e,t)=>{let n=typeof e.modified==`number`?e.modified:-1;return(typeof t.modified==`number`?t.modified:-1)-n}),t)}function BT(e){return e.filter(e=>e.kind===`worker`||(e.id??``).startsWith(`worker:`))}function VT(e){let t=(e.title??``).trim(),n=/^(W\d+)/.exec(t);if(n&&n[1])return n[1];let r=e.id??``,i=r.lastIndexOf(`/`);return i>=0?r.slice(i+1):r}function HT(e){return(e.title??``).trim().replace(/^W\d+\s*[·::-]\s*/,``)||LT(e.id??``)||(e.id??``)}function UT(e){return e.map(e=>[e.id??``,e.title??``,e.model??``,Fr(e.id??``)?`1`:`0`,String(e.events??``),PT(e)??``].join(``)).join(``)}function WT(e,t,n=t){let r=N(`button`,`btn btn-soft ws-newsess`);r.type=`button`,r.appendChild(bx(`plus`)),r.appendChild(N(`span`,null,w(`shell.tree.newSession`))),r.addEventListener(`click`,()=>e.newSession()),n.appendChild(r);let i=N(`div`,`ws-toolrow`),a=N(`div`,`ws-search`);a.appendChild(bx(`search`));let o=N(`input`,`ws-search-input`);o.placeholder=w(`shell.tree.searchPlaceholder`),o.value=zg(),o.addEventListener(`input`,()=>{Bg(o.value.trim().toLowerCase());let n=Gg();n!==null&&window.clearTimeout(n),Kg(window.setTimeout(()=>void e.loadTreeInto(t,null),180))}),a.appendChild(o),i.appendChild(a);let s=N(`button`,`ws-toolbtn`);s.type=`button`,s.appendChild(bx(`sort`)),s.appendChild(N(`span`,`ws-toolbtn-label`,Vg()===`active`?w(`settings.tag.active`):w(`settings.field.name`))),s.title=w(`shell.tree.sortTitle`,{label:Vg()===`active`?w(`shell.tree.sortRecent`):w(`settings.field.name`)}),s.addEventListener(`click`,()=>{Hg(Vg()===`active`?`name`:`active`),e.loadTreeInto(t,null)}),i.appendChild(s);let c=N(`button`,`ws-toolbtn`);c.type=`button`,c.title=w(`shell.tree.newWorkspace`),c.appendChild(bx(`folder-plus`)),c.addEventListener(`click`,()=>e.newWorkspace()),i.appendChild(c),n.appendChild(i),n.appendChild(N(`div`,`ws-divider`))}function GT(e,t,n){let r=n.id??``,i=jg(),a=r===Lg(),o=N(`div`,`sess-leaf`+(a?` active`:``)+(R.selSession===r?` sel`:``));if(o.dataset.id=r,!i){let e=N(`span`,`sess-dot`+(Fr(r)?` busy`:``));e.dataset.dot=r,bi(e,Fr(r)?w(`shell.tree.running`):w(`shell.tree.idle`)),o.appendChild(e)}let s=null;if(i){let e=N(`input`,`sess-check`);e.type=`checkbox`,e.dataset.id=r,e.checked=bg.has(r),e.addEventListener(`change`,()=>{e.checked?bg.add(r):bg.delete(r),vT(t)}),o.appendChild(e),s=e}o.appendChild(bx(`file`));let c=n.title||LT(r)||w(`shell.tree.unnamed`),l=N(`span`,`sess-leaf-name`,c);o.appendChild(l);let u=Yg().get(r)??0;if(u>0){let e=N(`span`,`sess-worker-count`,`W`+u);e.title=w(`shell.tree.workerBadgeTitle`,{n:u}),o.appendChild(e)}let d=[];n.events!==void 0&&d.push(w(`shell.tree.events`,{n:n.events})),d.length&&o.appendChild(N(`span`,`sess-leaf-meta`,d.join(` · `)));let f=N(`span`,`sess-leaf-grant hidden`);if(f.dataset.grantMark=r,o.appendChild(f),wx(f,nb(r)),bi(o,c+w(i?`shell.tree.clickCheck`:`shell.tree.clickOpen`)),!i){let i=N(`button`,`sess-kebab`,`⋯`);i.type=`button`,i.title=w(`shell.tree.sessionOps`),i.addEventListener(`click`,o=>{o.stopPropagation(),bT(t,i.getBoundingClientRect(),[{label:w(a?`shell.tree.currentSession`:`shell.tree.open`),disabled:a,onPick:()=>ST(t,r,{kind:n.kind===`worker`?`worker`:`session`,title:n.title})},{label:w(`shell.tree.rename`),onPick:()=>void TT(e,t,r,n.title||LT(r))},{label:w(`shell.tree.archiveOk`),onPick:()=>void CT(e,t,r,c)},{label:w(`shell.tree.branch`),onPick:()=>void ET(e,t,r)},{label:w(`settings.action.delete`),danger:!0,onPick:()=>void wT(e,t,r,c)}])}),o.appendChild(i)}return o.addEventListener(`click`,e=>{if(jg()){if(s===null||e.target===s)return;s.checked=!s.checked,s.checked?bg.add(r):bg.delete(r),vT(t);return}ST(t,r,{kind:n.kind===`worker`?`worker`:`session`,title:n.title})}),o}function KT(e,t,n,r){let i=N(`div`,`ws-node`),a=document.createElement(`details`);a.className=`ws-details`,a.dataset.ws=n,a.open=!0;let o=document.createElement(`summary`);o.className=`ws-head`,o.appendChild(bx(`folder`)),o.appendChild(N(`span`,`ws-name`,n)),o.appendChild(N(`span`,`ws-count`,String(r.length)));let s=N(`button`,`sess-kebab`,`⋯`);s.type=`button`,s.title=w(`shell.tree.workspaceOps`),s.addEventListener(`click`,r=>{r.stopPropagation(),bT(t,s.getBoundingClientRect(),[{label:w(`shell.tree.newSession`),onPick:()=>e.newSession(n)},{label:w(`shell.tree.rename`),onPick:()=>void OT(e,t,n)},{label:w(`shell.tree.batchDeleteSessions`),onPick:()=>{Mg(!0),bg.clear(),e.loadTreeInto(t,null)}},{label:w(`shell.tree.deleteWorkspace`),danger:!0,onPick:()=>void DT(e,t,n)}])}),o.appendChild(s),a.appendChild(o);let c=N(`div`,`ws-body`);for(let n of zT(r))c.appendChild(GT(e,t,n));return a.appendChild(c),i.appendChild(a),i}function qT(e,t,n=t){let r=N(`div`,`sess-batchbar`);r.appendChild(N(`span`,`sess-batchbar-count`,w(`shell.tree.selectedZero`)));let i=N(`button`,`btn btn-danger btn-mini`,w(`shell.tree.deleteSelected`));i.type=`button`,i.addEventListener(`click`,()=>void yT(e,t));let a=N(`button`,`btn-mini`,w(`settings.action.cancel`));a.type=`button`,a.addEventListener(`click`,()=>_T(e,t)),r.appendChild(i),r.appendChild(a),n.appendChild(r)}function JT(e,t,n){let r=t.id??``,i=Fr(r),a=N(`div`,`ws-worker-row`+(n?` child`:``)+(jr()===r?` active`:``));a.dataset.id=r,a.appendChild(N(`span`,`sess-dot`+(i?` busy`:``))),a.appendChild(N(`span`,`ws-worker-wid`,VT(t))),a.appendChild(N(`span`,`ws-worker-title`,HT(t)));let o=N(`span`,`ws-worker-state`+(i?` busy`:``),w(i?`shell.tree.running`:`shell.tree.idle`));a.appendChild(o);let s=[];return t.model&&s.push(String(t.model)),t.events!==void 0&&s.push(w(`shell.tree.events`,{n:t.events})),s.length&&a.appendChild(N(`span`,`ws-worker-meta`,s.join(` · `))),a.title=HT(t)+(t.model?` · `+t.model:``)+w(`shell.worker.openHint`),a.addEventListener(`click`,()=>{ST(document.getElementById(`sessionTree`)??e,r,{kind:`worker`,title:t.title||r})}),a}function YT(e,t,n){let r=document.createElement(`details`);r.className=`ws-worker-details`,r.open=n;let i=document.createElement(`summary`);i.className=`ws-worker-summary`,i.appendChild(N(`span`,null,w(`shell.worker.title`))),i.appendChild(N(`span`,`ws-worker-count`,String(t.length))),r.appendChild(i);let a=new Map,o=[];for(let e of t){let t=PT(e);if(!t){o.push(e);continue}let n=a.get(t);n?n.push(e):a.set(t,[e])}let s=new Set;for(let e of Fg()){let t=e.id??``;t&&a.has(t)&&s.add(t)}for(let e of a.keys())s.add(e);if(s.size===0)for(let t of o)r.appendChild(JT(e,t,!1));else{for(let t of s){let n=a.get(t)??[],i=Fg().find(e=>e.id===t),o=N(`div`,`ws-worker-parent`);o.appendChild(N(`span`,`ws-lineage-mark`,`└`));let s=N(`span`,`ws-worker-parent-name`,i?.title||LT(t));o.appendChild(s),o.appendChild(N(`span`,`ws-worker-count`,String(n.length))),o.title=w(`shell.worker.parentHint`),o.addEventListener(`click`,()=>{ST(document.getElementById(`sessionTree`)??e,t,{kind:`session`,title:i?.title})}),r.appendChild(o);for(let t of n)r.appendChild(JT(e,t,!0))}if(o.length){let t=N(`div`,`ws-worker-parent`);t.appendChild(N(`span`,`ws-lineage-mark`,`·`)),t.appendChild(N(`span`,`ws-worker-parent-name`,w(`shell.worker.unlinked`))),r.appendChild(t);for(let t of o)r.appendChild(JT(e,t,!0))}}e.replaceChildren(r)}async function XT(e){if(!e.isConnected)return;let t;try{t=(await j.sessions()).sessions??[]}catch{return}let n=BT(t),r=e.querySelector(`.ws-worker-host`);if(!r)return;let i=UT(n);if(i===qg()){Cx(e);return}let a=r.querySelector(`.ws-worker-details`)?.open??!0;Jg(i),n.length?YT(r,n,a):r.replaceChildren()}function ZT(e){Ug()===null&&Wg(window.setInterval(()=>{XT(e)},Ag))}function QT(){let e=Ug();e!==null&&(window.clearInterval(e),Wg(null))}async function $T(e,t){xT(),t&&(t.textContent=`…`);try{let e=await j.workspaces();Pg(e.workspaces??[]),e.active_session&&Rg(e.active_session)}catch{Pg([])}try{let e=await j.sessions();Ig(e.sessions??[]);for(let e of Fg()){let t=e.id??``;t&&(Tr(t,{kind:e.kind===`worker`?`worker`:e.kind===`session`?`session`:void 0,title:e.title,model:e.model,workspace:e.workspace??void 0}),typeof e.busy==`boolean`&&zr(t,e.busy))}let t=(e.sessions??[]).find(e=>e.active===!0),n=jr();n?Rg(n):t?.id&&Rg(t.id)}catch(n){QT();let r=document.createElement(`div`);r.appendChild(N(`div`,`side-note err`,w(`shell.sessions.unavailable`))),r.appendChild(N(`div`,`side-note`,n instanceof Error?n.message:String(n))),e.replaceChildren(...r.childNodes),t&&(t.textContent=`—`);return}tE(e,t)}function eE(e,t){tE(e,t)}function tE(e,t){xT();let n=new Map;for(let t of e.querySelectorAll(`.ws-details`))n.set(t.dataset.ws??``,t.open);let r=document.activeElement?.classList.contains(`ws-search-input`)??!1,i=document.createElement(`div`),a=Fg().filter(e=>!FT(e)),o=new Set;for(let e of a)e.archived||o.add(IT(e));for(let e of o)Ng().some(t=>t.name===e)||Ng().push({name:e});Ng().sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),t&&(t.textContent=String(a.filter(e=>e.archived!==!0).length));let s=BT(Fg());Xg(new Map);for(let e of s){let t=PT(e);if(!t)continue;let n=Yg();n.set(t,(n.get(t)??0)+1)}WT(aE,e,i);let c=N(`div`,`ws-tree`),l=Ng().filter(e=>RT(e.name)||a.some(t=>!t.archived&&IT(t)===e.name&&RT(t.title??t.id??``))),u=0;for(let t of l){let n=a.filter(e=>!e.archived&&IT(e)===t.name&&RT(e.title??e.id??``));(RT(t.name)||n.length)&&(c.appendChild(KT(aE,e,t.name,n)),u+=n.length)}u||c.appendChild(N(`div`,`side-note`,zg()?w(`shell.sessions.noMatch`):w(`shell.sessions.empty`))),i.appendChild(c),jg()&&qT(aE,e,i);let d=N(`div`,`ws-worker-host`);i.appendChild(d),Jg(UT(s)),s.length?(YT(d,s,!0),ZT(e)):QT(),e.replaceChildren(...i.childNodes);for(let t of e.querySelectorAll(`.ws-details`)){let e=t.dataset.ws??``;n.has(e)&&(t.open=n.get(e)??!0)}if(r){let t=e.querySelector(`.ws-search-input`);t&&t.focus()}Cx(e),Nx(),Cm(Fg()),Tx(e),ab(a.filter(e=>!e.archived).map(e=>e.id??``))}function nE(){return $T(M(`#sessionTree`),M(`#sessionCount`))}function rE(e){MT(aE,e)}function iE(){NT(aE)}var aE={newSession:e=>rE(e),newWorkspace:()=>iE(),loadTreeInto:(e,t)=>$T(e,t),renderTreeInto:(e,t)=>eE(e,t),loadSessions:()=>nE()};function oE(){document.addEventListener(`click`,e=>{(!(e.target instanceof Element)||!e.target.closest(`.sess-menu`))&&xT()}),window.addEventListener(qy,()=>{let e=document.getElementById(`sessionTree`);e&&Tx(e)}),Vr(()=>{let e=document.getElementById(`sessionTree`);e&&(Cx(e),e.querySelector(`.ws-worker-host`)&&XT(e))}),nE()}var sE=[],cE=new Set,lE=0,uE=null;function dE(){for(let e of cE)e()}function fE(e){return cE.add(e),()=>cE.delete(e)}function pE(){return sE}function mE(e){return sE.find(t=>t.id===e)}function hE(){return uE}function gE(e){uE!==e&&(uE=e,dE())}function _E(e,t){return w(e===`files`?`chat.wb.menu.files`:e===`terminal`?`chat.wb.menu.terminal`:`chat.wb.menu.browser`)+` `+String(t)}function vE(e){return e===`right`?420:260}function yE(e,t=`right`){lE+=1;let n=sE.filter(t=>t.kind===e).length+1,r={id:`wb`+String(lE),kind:e,title:_E(e,n),dock:t,size:vE(t),seq:0};return sE.push(r),uE=r.id,dE(),r}function bE(e){let t=sE.findIndex(t=>t.id===e);t<0||(sE.splice(t,1),uE===e&&(uE=sE.length>0?sE[sE.length-1].id:null),dE())}function xE(e,t){let n=mE(e);n&&n.dock!==t&&(n.dock=t,n.size=vE(t),dE())}function SE(e,t){let n=mE(e);if(!n)return;let r=Math.max(160,Math.min(Math.round(t),1200));n.size!==r&&(n.size=r,dE())}function CE(e){let t=mE(e);return t?(t.seq+=1,t.seq):-1}function wE(e,t){return mE(e)?.seq===t}function TE(e){return e===null?`—`:e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`}function EE(e){if(e===null)return`—`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`—`;let n=e=>(e<10?`0`:``)+String(e);return t.getFullYear()+`-`+n(t.getMonth()+1)+`-`+n(t.getDate())+` `+n(t.getHours())+`:`+n(t.getMinutes())}function DE(e){let t=e.replace(/\\/g,`/`).replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n<=0?`/`:t.slice(0,n)}function OE(e){let t=Pm(e);return t===`markdown`||t===`diff`||t===`code`?t:`code`}function kE(e,t){let n=e.replace(/\/+$/,``)+`/`+t;uh({candidate:{path:n,kind:OE(n),source:`label`},loadFull:async()=>{try{let e=await j.fsRead(n);return e.error!==void 0&&e.error!==``?{degraded:e.error}:e.kind===`binary`?{degraded:w(`chat.preview.degradeBinary`),badge:w(`chat.preview.badgeBinary`)}:{text:e.text,truncated:e.truncated===!0}}catch(e){return{degraded:O(e,w(`chat.preview.degradeReadFailed`))}}}})}function AE(e){let t=e.data;if(t&&typeof t.path==`string`)return t;let n={path:Qg(),selected:null};return e.data=n,n}async function jE(e,t,n,r){let i=AE(t);if(i.path===``){e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.noWorkspace`)));return}let a=i.path,o;try{o=await j.fsList(a)}catch{if(!r(t.id,n))return;e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.listUnavailable`)));return}if(!r(t.id,n))return;if(o.error!==void 0&&o.error!==``){e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.dirOpenFailed`,{reason:o.error})));return}let s=o.entries??[],c=document.createElement(`div`),l=N(`div`,`wb-crumbs`),u=N(`button`,`wb-crumb`,w(`chat.wb.up`));u.type=`button`,u.addEventListener(`click`,()=>{i.path=DE(a),i.selected=null,jE(e,t,CE(t.id),r)}),l.appendChild(u);let d=N(`span`,`wb-crumb wb-crumb-cur`,a);d.title=a,l.appendChild(d),c.appendChild(l),o.truncated===!0&&c.appendChild(N(`div`,`wb-notice`,w(`chat.wb.dirTruncated`)));let f=N(`div`,`wb-list`);s.length===0&&f.appendChild(N(`div`,`wb-notice`,w(`chat.wb.dirEmpty`)));for(let n of s)f.appendChild(ME(n,i,a,e,t,r));c.appendChild(f),e.replaceChildren(...Array.from(c.childNodes))}function ME(e,t,n,r,i,a){let o=N(`div`,`wb-row`+(e.type===`dir`?` dir`:``)+(t.selected===e.name?` sel`:``));return o.appendChild(N(`span`,`wb-icon`,e.type===`dir`?`📁`:`📄`)),o.appendChild(N(`span`,`wb-name`,e.name)),o.appendChild(N(`span`,`wb-size`,TE(e.size))),o.appendChild(N(`span`,`wb-time`,EE(e.mtime))),o.addEventListener(`click`,()=>{e.type===`dir`?(t.path=n.replace(/\/+$/,``)+`/`+e.name,t.selected=null,jE(r,i,CE(i.id),a)):(t.selected=e.name,r.querySelectorAll(`.wb-row`).forEach(e=>e.classList.remove(`sel`)),o.classList.add(`sel`),kE(n,e.name))}),o}function NE(e){let t=e.data;if(t&&Array.isArray(t.lines))return t;let n={lines:[]};return e.data=n,n}function PE(e){let t=N(`div`,`wb-term-line`),n=N(`div`,`wb-term-cmd`);return n.appendChild(N(`span`,`wb-term-prompt`,`$`)),n.appendChild(N(`span`,`wb-term-cmdtext`,e.cmd)),t.appendChild(n),e.out!==``&&t.appendChild(N(`pre`,`wb-term-out`,e.out)),e.err!==``&&t.appendChild(N(`pre`,`wb-term-out err`,e.err)),t.appendChild(N(`div`,`wb-term-meta`+(e.failed?` err`:``),e.code+` · `+String(e.ms)+` ms`)),t}function FE(e,t,n){let r=NE(t),i=document.createElement(`div`);i.appendChild(N(`div`,`wb-term-note`,w(`chat.wb.term.note`)));let a=N(`div`,`wb-term-row`),o=N(`input`,`wb-term-input`);o.type=`text`,o.placeholder=w(`chat.wb.term.placeholder`);let s=N(`button`,`wb-btn wb-term-run`,w(`chat.wb.term.run`));s.type=`button`,a.appendChild(o),a.appendChild(s),i.appendChild(a);let c=N(`div`,`wb-term-outwrap`);for(let e of r.lines)c.appendChild(PE(e));i.appendChild(c),e.replaceChildren(...Array.from(i.childNodes));let l=()=>{let e=o.value.trim();e!==``&&(o.value=``,IE(t,e,CE(t.id),n,c))};s.addEventListener(`click`,l),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),l())})}async function IE(e,t,n,r,i){let a=N(`div`,`wb-term-line`);a.appendChild(N(`div`,`wb-term-meta`,w(`chat.wb.term.running`))),i.appendChild(a);let o;try{let e=await j.exec({command:t,timeout_ms:3e4});o={cmd:t,out:e.stdout??``,err:e.stderr??``,code:e.signal!==null&&e.signal!==``?w(`chat.wb.term.signal`,{signal:e.signal}):w(`chat.wb.term.exitCode`,{code:String(e.exit_code)}),ms:e.duration_ms,failed:e.exit_code!==0||e.signal!==null&&e.signal!==``}}catch(e){o={cmd:t,out:``,err:e instanceof D&&(e.status===404||e.status===405||e.status===501)?w(`chat.wb.term.unsupported`):O(e,w(`chat.wb.term.notStarted`)),code:w(`chat.tool.failed`),ms:0,failed:!0}}r(e.id,n)&&(NE(e).lines.push(o),a.replaceWith(PE(o)))}var LE=4e3;function RE(e){let t=e.trim();return t===``?``:/^https?:\/\//i.test(t)?t:`https://`+t}function zE(e,t,n){let r=t.data,i=r&&typeof r.url==`string`?r.url:``,a=document.createElement(`div`),o=N(`div`,`wb-url-row`),s=N(`input`,`wb-url-input`);s.type=`text`,s.placeholder=w(`chat.wb.urlPlaceholder`),s.value=i;let c=N(`button`,`wb-btn wb-url-open`,w(`chat.wb.open`));c.type=`button`,o.appendChild(s),o.appendChild(c),a.appendChild(o);let l=N(`div`,`wb-notice hidden`);a.appendChild(l);let u=N(`iframe`,`wb-frame`);u.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-popups`),a.appendChild(u);let d=N(`button`,`wb-btn wb-url-external hidden`,w(`chat.wb.openExternal`));d.type=`button`,a.appendChild(d),e.replaceChildren(...Array.from(a.childNodes));let f=(e,t)=>{l.textContent=e,l.classList.remove(`hidden`),d.classList.remove(`hidden`),d.addEventListener(`click`,()=>window.open(t,`_blank`,`noopener`))},p=e=>{let r=RE(e);if(r===``)return;t.data={url:r};let i=CE(t.id);l.classList.add(`hidden`),d.classList.add(`hidden`);let a=!1;u.addEventListener(`load`,()=>{n(t.id,i)&&(a=!0)}),u.src=r,window.setTimeout(()=>{n(t.id,i)&&!a&&f(w(`chat.wb.frameBlocked`),r)},LE)};c.addEventListener(`click`,()=>p(s.value)),s.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),p(s.value))}),i!==``&&p(i)}var BE=null,VE=null,HE=!1,UE=!1,WE=null;function GE(e){let t=N(`div`,`wb-head`);t.appendChild(N(`span`,`wb-title`,e.title));let n=N(`button`,`wb-btn wb-dock`,e.dock===`right`?`⇩`:`⇨`);n.type=`button`,n.title=e.dock===`right`?w(`chat.wb.dockBottom`):w(`chat.wb.dockRight`),n.setAttribute(`aria-label`,n.title),n.addEventListener(`click`,()=>xE(e.id,e.dock===`right`?`bottom`:`right`)),t.appendChild(n);let r=N(`button`,`wb-btn wb-close`,`×`);return r.type=`button`,r.title=w(`chat.wb.close`),r.setAttribute(`aria-label`,w(`chat.wb.close`)),r.addEventListener(`click`,()=>bE(e.id)),t.appendChild(r),t.addEventListener(`mousedown`,t=>{t.target.closest(`.wb-btn`)||YE(e,t)}),t}var KE=null,qE=!1,JE=null;function YE(e,t){KE={id:e.id,startDock:e.dock},window.addEventListener(`mousemove`,XE),window.addEventListener(`mouseup`,ZE),t.preventDefault()}function XE(e){if(!KE||qE)return;qE=!0;let t=e.clientY;requestAnimationFrame(()=>{if(qE=!1,!KE||!BE)return;let e=BE.getBoundingClientRect(),n=t>e.top+e.height*.66?`bottom`:`right`;JE||(JE=N(`div`,`wb-drop-hint`),BE.appendChild(JE)),JE.className=`wb-drop-hint `+n,JE.textContent=w(n===`bottom`?`chat.wb.dockBottom`:`chat.wb.dockRight`)})}function ZE(e){let t=KE;if(KE=null,window.removeEventListener(`mousemove`,XE),window.removeEventListener(`mouseup`,ZE),JE&&(JE.remove(),JE=null),!t||!BE)return;let n=BE.getBoundingClientRect(),r=e.clientY>n.top+n.height*.66?`bottom`:`right`;xE(t.id,r)}function QE(e){let t=N(`div`,`wb-resizer `+e.dock);return t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,e.dock===`right`?`vertical`:`horizontal`),t.addEventListener(`mousedown`,t=>{WE={id:e.id,startX:t.clientX,startY:t.clientY,startSize:e.size,dock:e.dock},window.addEventListener(`mousemove`,$E),window.addEventListener(`mouseup`,eD),t.preventDefault()}),t}function $E(e){if(!WE)return;let t=WE;UE||(UE=!0,requestAnimationFrame(()=>{if(UE=!1,!WE)return;let n=t.dock===`right`?t.startX-e.clientX:t.startY-e.clientY;SE(t.id,t.startSize+n)}))}function eD(){WE=null,window.removeEventListener(`mousemove`,$E),window.removeEventListener(`mouseup`,eD)}function tD(e){let t=N(`div`,`wb-panel`+(hE()===e.id?` focused`:``));t.dataset.panelId=e.id,t.appendChild(GE(e));let n=N(`div`,`wb-body`);return e.kind===`files`?jE(n,e,CE(e.id),wE):e.kind===`terminal`?FE(n,e,wE):e.kind===`browser`&&zE(n,e,wE),t.appendChild(n),t.addEventListener(`mousedown`,()=>gE(e.id)),t}function nD(){if(!BE||!VE)return;let e=pE(),t=e.filter(e=>e.dock===`bottom`),n=e.filter(e=>e.dock===`right`),r=document.createElement(`div`),i=t.reduce((e,t)=>Math.max(e,t.size),0);if(VE.style.setProperty(`--wb-bottom-h`,i+`px`),t.length>0){let e=N(`div`,`wb-zone bottom`);for(let n of t){e.appendChild(QE(n));let t=tD(n);t.style.height=n.size+`px`,t.style.flex=`1 1 0`,e.appendChild(t)}r.appendChild(e)}if(n.length>0){let e=N(`div`,`wb-zone right`);for(let t of n){let n=tD(t);n.style.width=t.size+`px`,e.appendChild(n),e.appendChild(QE(t))}r.appendChild(e)}VE.replaceChildren(...Array.from(r.childNodes)),VE.classList.toggle(`hidden`,e.length===0),BE.classList.toggle(`hidden`,e.length===0)}function rD(){if(HE)return;HE=!0;let e=document.getElementById(`main`);e&&(BE=N(`div`,`wb-host hidden`),VE=N(`div`,`wb-dock`),BE.appendChild(VE),e.appendChild(BE),fE(()=>nD()),nD())}var iD=null,aD=null;function oD(){iD&&iD.classList.add(`hidden`),aD!==null&&(F(aD),aD=null)}function sD(e){oD(),yE(e,`right`)}function cD(e,t,n){let r=N(`button`,`wb-menu-item`);return r.type=`button`,r.appendChild(N(`span`,`wb-menu-label`,t)),r.appendChild(N(`span`,`wb-menu-desc`,n)),r.addEventListener(`click`,()=>sD(e)),r}function lD(){if(iD===null&&(iD=N(`div`,`wb-menu hidden`),iD.id=`wbMenu`,iD.appendChild(cD(`files`,w(`chat.wb.menu.files`),w(`chat.wb.menu.filesDesc`))),iD.appendChild(cD(`terminal`,w(`chat.wb.menu.terminal`),w(`chat.wb.menu.terminalDesc`))),iD.appendChild(cD(`browser`,w(`chat.wb.menu.browser`),w(`chat.wb.menu.browserDesc`))),document.body.appendChild(iD)),!iD.classList.contains(`hidden`)){oD();return}iD.classList.remove(`hidden`),dD(),aD=P(oD),document.addEventListener(`pointerdown`,uD,!0)}function uD(e){let t=e.target;iD&&t instanceof Node&&(iD.contains(t)||t instanceof Element&&t.closest(`#btnWorkbench`))||(document.removeEventListener(`pointerdown`,uD,!0),oD())}function dD(){if(!iD)return;let e=document.getElementById(`btnWorkbench`),t=e?e.getBoundingClientRect():null;iD.style.top=(t?t.bottom+6:56)+`px`,iD.style.right=(t?Math.max(8,window.innerWidth-t.right):12)+`px`}function fD(){let e=document.getElementById(`btnWorkbench`);e&&e.addEventListener(`click`,()=>lD())}var pD=!1;function mD(){pD||(pD=!0,rD(),fD())}var hD=!1,$=null,gD=null,_D=null,vD=!1;function yD(e,t){if(e===null)return null;let n=e.nodeType===1?e:e.parentElement;return n?n.closest(t):null}function bD(e){return yD(e,`#inputbar`)!==null||yD(e,`textarea, input`)!==null}function xD(e){let t=e.querySelector(`.msg`),n=t?t.className:``;return n.includes(`user`)?`user`:n.includes(`tool`)?`tool`:n.includes(`inbox`)?`inbox`:`assistant`}function SD(e,t){if(t===`assistant`)return`Studio`;if(t===`inbox`)return w(`chat.msg.system`);if(t===`tool`){let t=e.querySelector(`.toolcard-name`)?.textContent??``;return t===``?w(`chat.quote.tool`):w(`chat.quote.toolNamed`,{name:t})}return e.querySelector(`.msg-caption .who`)?.textContent??w(`chat.user.you`)}function CD(e,t){let n=0;for(let r of Array.from(e.querySelectorAll(`.mcol`)))if(r.querySelector(`.msg.user`)&&(n+=1),r===t)break;return n>0?n:void 0}function wD(e,t){let n=xD(t);return{kind:n,session:e.id,turn:CD(e.el,t),label:SD(t,n)}}function TD(){$&&$.classList.add(`hidden`),_D=null,vD=!1,gD!==null&&(F(gD),gD=null)}function ED(e){if(!$)return;$.classList.remove(`hidden`);let t=fn({anchor:e,panel:{width:$.offsetWidth||48,height:$.offsetHeight||24},viewport:{width:window.innerWidth,height:window.innerHeight},gap:6,minHeight:0});$.style.top=t.top+`px`,$.style.left=t.left+`px`,gD===null&&(gD=P(TD))}function DD(e){if($&&e.target instanceof Node&&$.contains(e.target))return;let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0){TD();return}let n=t.getRangeAt(0),r=t.toString(),i=B(),a=n.commonAncestorContainer;if(r.trim()===``||!i||!i.el.contains(a)||bD(a)){TD();return}let o=yD(n.startContainer,`.mcol`),s=yD(n.endContainer,`.mcol`);if(!o||o!==s){TD();return}if(!yD(a,`.content, .tool-out, .think-seg-body`)){TD();return}_D={text:r,source:wD(i,o),format:yD(a,`pre, code`)?`code`:`text`},ED(n.getBoundingClientRect())}function OD(){if(vD)return;let e=window.getSelection();(!e||e.isCollapsed||e.rangeCount===0)&&TD()}function kD(e){if($&&e.target instanceof Node&&$.contains(e.target)){vD=!0;return}TD()}function AD(){let e=_D;TD(),e&&Vh(e).then(e=>{e===`full`?X(w(`chat.quote.max`),`err`,4e3):e===`duplicate`&&X(w(`chat.quote.duplicate`),`ok`,3e3)})}function jD(){hD||(hD=!0,$=document.createElement(`button`),$.type=`button`,$.className=`quote-float hidden`,$.textContent=w(`chat.quote.add`),$.title=w(`chat.quote.addHint`),$.setAttribute(`aria-label`,w(`chat.quote.addAria`)),$.addEventListener(`click`,AD),document.body.appendChild($),document.addEventListener(`mouseup`,DD),document.addEventListener(`selectionchange`,OD),document.addEventListener(`pointerdown`,kD,!0),document.addEventListener(`scroll`,TD,!0),window.addEventListener(`resize`,TD))}var MD=globalThis.__CELESTEA_BUILD__??{},ND=MD.version??`dev`,PD=MD.commits??0,FD=MD.sha??``,ID=MD.dirty??!1,LD=MD.buildTime??`dev`;function RD(){let e=PD>0?`-`+PD+`-g`+FD:``;return`v`+ND+e}function zD(){let e=PD>0?`+`+PD:``;return`Studio v`+ND+e+(ID?`*`:``)}var BD=`celestea-studio.sidebar-collapsed`,VD=`celestea-studio.sidebar-width`;function HD(e){return Math.min(560,Math.max(200,Math.round(e)))}function UD(){try{let e=localStorage.getItem(BD);return e===null?window.innerWidth<880:e===`1`}catch{return!1}}function WD(){try{let e=Number(localStorage.getItem(VD));return Number.isFinite(e)&&e>0?e:316}catch{return 316}}function GD(){let e=M(`#app`),t=M(`#sidebar`),n=M(`#sidebarResizer`),r=M(`#btnSidebar`),i=UD(),a=()=>{e.classList.toggle(`sidebar-collapsed`,i),e.style.setProperty(`--sidebar-w`,i?`0px`:t.style.width||`316px`),r.textContent=w(i?`shell.sidebar.expand`:`shell.sidebar.collapse`),r.title=w(i?`shell.sidebar.expandTitle`:`shell.sidebar.collapseTitle`)},o=n=>{let r=HD(n)+`px`;t.style.width=r,i||e.style.setProperty(`--sidebar-w`,r)};a(),o(WD()),r.addEventListener(`click`,()=>{if(!qD()){i=!i;try{localStorage.setItem(BD,i?`1`:`0`)}catch{}a()}});let s=!1,c=0,l=0,u=()=>{try{localStorage.setItem(VD,String(Math.round(t.getBoundingClientRect().width)))}catch{}};n.addEventListener(`pointerdown`,e=>{s=!0,c=e.clientX,l=t.getBoundingClientRect().width,n.setPointerCapture(e.pointerId),document.body.classList.add(`resizing`),e.preventDefault()}),n.addEventListener(`pointermove`,e=>{s&&o(l+(e.clientX-c))});let d=()=>{s&&(s=!1,document.body.classList.remove(`resizing`),u())};n.addEventListener(`pointerup`,d),n.addEventListener(`pointercancel`,d),n.addEventListener(`dblclick`,()=>{o(316),u()}),JD(r)}var KD=`(max-width: 640px)`;function qD(){try{return window.matchMedia(KD).matches}catch{return window.innerWidth<=640}}function JD(e){let t=M(`#app`),n=document.getElementById(`sidebarScrim`),r=!1,i=()=>{t.classList.toggle(`drawer-open`,r),n&&n.classList.toggle(`hidden`,!r),e.setAttribute(`aria-expanded`,r?`true`:`false`)},a=e=>{r!==e&&(r=e,i())};i(),e.addEventListener(`click`,()=>{qD()&&a(!r)}),n?.addEventListener(`click`,()=>a(!1)),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&r&&a(!1)}),document.getElementById(`sessionTree`)?.addEventListener(`click`,e=>{if(!r)return;let t=e.target;t&&t.closest(`.sess-leaf`)&&a(!1)});try{window.matchMedia(KD).addEventListener(`change`,e=>{e.matches||a(!1)})}catch{}}var YD=`celestea-studio.chat-col-width`,XD=1400,ZD=2,QD=16,$D=null;function eO(e){return Math.min(XD,Math.max(560,Math.round(e)))}function tO(){try{let e=localStorage.getItem(YD);if(e===null)return null;let t=Number(e);return Number.isFinite(t)&&t>0?eO(t):null}catch{return null}}function nO(e){try{e===null?localStorage.removeItem(YD):localStorage.setItem(YD,String(e))}catch{}}function rO(e){let t=document.documentElement.style;e===null?t.removeProperty(`--chat-col-user`):t.setProperty(`--chat-col-user`,eO(e)+`px`)}function iO(){let e=document.querySelector(`.sess-pane:not([hidden]) .mcol`)??document.querySelector(`.mcol`),t=e?e.getBoundingClientRect().width:0;return t>0?eO(t):560}function aO(e,t){$D=e===null?null:eO(e),rO($D),t&&nO($D)}function oO(e){let t=!1,n=0,r=0;e.addEventListener(`pointerdown`,i=>{t=!0,n=i.clientX,r=$D??iO();try{e.setPointerCapture(i.pointerId)}catch{}document.body.classList.add(`resizing-col`),i.preventDefault()}),e.addEventListener(`pointermove`,e=>{t&&aO(r+ZD*(e.clientX-n),!1)});let i=()=>{t&&(t=!1,document.body.classList.remove(`resizing-col`),nO($D))};e.addEventListener(`pointerup`,i),e.addEventListener(`pointercancel`,i),e.addEventListener(`dblclick`,()=>aO(null,!0))}function sO(e){e.addEventListener(`keydown`,e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`)return;e.preventDefault();let t=e.key===`ArrowRight`?QD:-16;aO(($D??iO())+t,!0)})}function cO(){let e=document.getElementById(`messages`);if(!e||e.querySelector(`.chatcol-resizer`)){aO(tO(),!1);return}let t=N(`div`,`chatcol-resizer`);t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,w(`shell.chatcol.label`)),t.title=w(`shell.chatcol.hint`),e.appendChild(t),oO(t),sO(t),aO(tO(),!1)}function lO(){return[{id:`mono`,label:w(`theme.mono.label`),hint:w(`theme.mono.hint`)},{id:`dark`,label:w(`theme.dark.label`),hint:w(`theme.dark.hint`)}]}var uO=`celestea-studio.theme`;function dO(){return document.documentElement.dataset.theme||`mono`}function fO(e){document.documentElement.dataset.theme=e;try{localStorage.setItem(uO,e)}catch{}}function pO(e=`mono`){let t=e;try{let e=localStorage.getItem(uO);e&&lO().some(t=>t.id===e)&&(t=e)}catch{}return fO(t),t}function mO(e){let t=()=>{let t=dO(),n=lO().find(e=>e.id===t)??lO()[0];e.textContent=n.label,e.title=w(`theme.title`,{hint:n.hint,suffix:lO().length>1?w(`theme.clickToSwitch`):w(`theme.onlyTheme`)})};if(t(),lO().length<2){e.setAttribute(`aria-disabled`,`true`);return}e.addEventListener(`click`,()=>{let e=lO().findIndex(e=>e.id===dO()),n=lO()[(e+1)%lO().length];fO(n.id),t()})}function hO(){j.health().then(e=>{e.model&&ci.merge({model:e.model}),R.streaming||Y(w(`shell.status.online`),`ok`)}).catch(()=>{R.streaming||Y(w(`chat.status.disconnected`),`err`)})}function gO(){pO(`mono`),mO(M(`#btnTheme`)),GD(),cO(),Hr(),Mx(),yx(),ci.start(),Tm(),oE(),gT(),cx();let e=document.getElementById(`brandVersion`);e&&(e.textContent=zD(),e.title=w(`chat.version.title`,{time:LD,version:RD(),dirty:ID?w(`chat.version.dirty`):``})),ro(),aS(),jD(),p_(),mD(),ei(),hO(),rm(),nS(),window.addEventListener(`studio:config-saved`,()=>hO()),M(`#input`).focus()}gO();
|
|
90
|
+
`).replace(/\s+$/,``)}}var Qf={selected:[],custom:``};function $f(e,t){return e[t]??Qf}function ep(e,t,n){return n?{selected:e.selected.includes(t)?e.selected.filter(e=>e!==t):[...e.selected,t],custom:e.custom}:{selected:[t],custom:e.custom}}function tp(e,t){return{selected:[...e.selected],custom:t}}function np(e,t){let n=[];for(let r of e){let e=$f(t,r.id);e.selected.length===0&&e.custom.trim()===``&&n.push(r.id)}return n}function rp(e,t){let n=[];for(let r of e){let e=$f(t,r.id),i=e.custom.trim();if(e.selected.length===0&&i===``)continue;let a={id:r.id,selected:[...e.selected]};i!==``&&(a.custom=i),n.push(a)}return n}function ip(e){let t=[];for(let n of e){let e=[...n.selected],r=(n.custom??``).trim();r!==``&&e.push(w(`chat.question.customQuote`,{text:r})),e.length>0&&t.push(e.join(w(`chat.question.answerSep`)))}return t.join(w(`chat.question.answerJoin`))}function ap(e,t){return typeof e.remaining_ms==`number`&&Number.isFinite(e.remaining_ms)?e.remaining_ms:typeof e.expires_at==`number`&&Number.isFinite(e.expires_at)?e.expires_at-t:null}function op(e,t){let n=ap(e,t);return n===null?null:t+n}function sp(e){if(e===null)return``;if(e<=0)return w(`chat.question.timedOut`);let t=Math.floor(e/1e3);if(t<60)return w(`chat.question.seconds`,{n:t});if(t<3600){let e=Math.floor(t/60),n=t%60;return w(`chat.question.clock`,{m:e,s:(n<10?`0`:``)+n})}return w(`chat.question.hoursMinutes`,{h:Math.floor(t/3600),m:Math.floor(t%3600/60)})}function cp(e){return e!==null&&e<=0}function lp(e){return typeof e==`string`?e:null}function up(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.label);if(n===null||n===``)return null;let r=lp(t.description);return r===null?{label:n}:{label:n,description:r}}function dp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.kind);return n===null||n===``?null:{...t,kind:n}}function fp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.id),r=lp(t.question);if(n===null||n===``||r===null||r===``)return null;let i={id:n,question:r},a=lp(t.header);a!==null&&(i.header=a);let o=lp(t.detail);o!==null&&(i.detail=o);let s=Array.isArray(t.options)?t.options.map(up).filter(e=>e!==null):[];s.length>0&&(i.options=s),t.multi_select===!0&&(i.multi_select=!0);let c=dp(t.intent);return c!==null&&(i.intent=c),i}function pp(e){return Array.isArray(e)?e.map(fp).filter(e=>e!==null):[]}function mp(e){if(typeof e!=`object`||!e)return null;let t=e,n=lp(t.id);if(n===null||n===``)return null;let r=pp(t.questions);if(r.length===0)return null;let i={id:n,questions:r},a=lp(t.session);a!==null&&(i.session=a);for(let e of[`expires_at`,`timeout_ms`,`remaining_ms`]){let n=t[e];typeof n==`number`&&Number.isFinite(n)&&(i[e]=n)}return t.expired===!0&&(i.expired=!0),i}function hp(e){return e===404||e===409}function gp(e){return e.content}function _p(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=lp(e.id),i=e.selected;if(r===null||!Array.isArray(i))continue;let a=i.filter(e=>typeof e==`string`),o=lp(e.custom),s={id:r,selected:a};o!==null&&o!==``&&(s.custom=o),t.push(s)}return t}function vp(e){let t=new Map,n=[];for(let r of e){if(r.role!==`question`)continue;let e=typeof r.question_id==`string`?r.question_id:``;if(e!==``){if(r.kind===`question`){if(t.has(e))continue;let i=pp(gp(r));if(i.length===0)continue;let a={id:e,questions:i,settled:!1,timedOut:!1,answerText:``};typeof r.question_expires_at==`number`&&(a.expiresAt=r.question_expires_at),t.set(e,a),n.push(e);continue}if(r.kind===`answer`){let n=t.get(e);if(n===void 0)continue;n.settled=!0,n.timedOut=r.question_timed_out===!0,n.answerText=n.timedOut?``:ip(_p(gp(r)))}}}return n.map(e=>t.get(e))}function yp(e,t,n,r){let i=N(`label`,`q-opt`);r!==void 0&&r===n.label&&i.classList.add(`is-approve`);let a=N(`input`,`q-opt-input`);a.type=t.multi_select===!0?`checkbox`:`radio`,a.name=`q-`+e.id+`-`+t.id,a.value=n.label;let o=N(`span`,`q-opt-text`);return o.appendChild(N(`span`,`q-opt-label`,n.label)),n.description!==void 0&&n.description!==``&&o.appendChild(N(`span`,`q-opt-desc`,n.description)),i.appendChild(a),i.appendChild(o),a.addEventListener(`change`,()=>{e.picks[t.id]=ep($f(e.picks,t.id),n.label,t.multi_select===!0),e.onEdit()}),e.controls.push(a),i}function bp(e,t){let n=N(`div`,`q-item`);n.appendChild(N(`div`,`q-question`,t.question)),t.detail!==void 0&&t.detail!==``&&n.appendChild(N(`div`,`q-detail`,t.detail));let r=t.options??[];if(r.length>0){let i=N(`div`,`q-options`),a=t.intent?.approve;for(let n of r)i.appendChild(yp(e,t,n,a));n.appendChild(i)}let i=N(`input`,`q-custom-input`);i.type=`text`,i.autocomplete=`off`,i.placeholder=r.length>0?w(`chat.question.customPlaceholder`):w(`chat.question.customRequired`),i.addEventListener(`input`,()=>{e.picks[t.id]=tp($f(e.picks,t.id),i.value),e.onEdit()}),e.controls.push(i);let a=N(`div`,`q-custom`);return a.appendChild(i),n.appendChild(a),n}function xp(e){return e===`done`?w(`chat.question.answered`):e===`expired`?w(`chat.question.expired`):e===`closed`?w(`chat.question.closed`):``}var Sp=new WeakMap,Cp=new Set,wp=null;Vr((e,t)=>{!t&&Sr(e)===void 0&&Dp(e)});function Tp(e){let t=Sp.get(e.el);return t||(t=new Map,Sp.set(e.el,t)),t}function Ep(e){return e.root.isConnected?!0:e.root.parentElement!==null&&Sr(e.paneId)?.el===e.root.parentElement}function Dp(e){for(let t of Array.from(Cp))t.paneId===e&&Cp.delete(t);Op()}function Op(){Cp.size===0&&wp!==null&&(window.clearInterval(wp),wp=null)}function kp(e,t){let n=Tp(e),r=n.get(t);return r?Ep(r)?r:(n.delete(t),Cp.delete(r),null):null}function Ap(){let e=Date.now();for(let t of Array.from(Cp)){if(!Ep(t)){Cp.delete(t);continue}t.state===`pending`&&jp(t,e)}Op()}function jp(e,t){if(e.deadline===null){e.timer.textContent=``;return}let n=e.deadline-t;e.timer.textContent=sp(n),cp(n)&&e.state===`pending`&&Mp(e,`expired`)}function Mp(e,t,n){e.state=t,(t===`done`||t===`closed`)&&(e.settled=!0),e.card.dataset.state=t;let r=t!==`pending`;for(let t of e.controls)t.disabled=r;e.submit.disabled=r,e.submit.textContent=w(`chat.question.submit`),e.timer.textContent=r?``:e.timer.textContent,e.result.textContent=r?n??xp(t):``}function Np(e,t){if(t.state!==`pending`)return;if(t.deadline!==null&&Date.now()>=t.deadline){Mp(t,`expired`);return}let n=np(t.questions,t.picks);if(n.length>0){t.hint.textContent=w(`chat.question.missing`,{n:n.length});return}Pp(e,t)}async function Pp(e,t){let n=rp(t.questions,t.picks),r=e.id===``?void 0:e.id;Mp(t,`done`,w(`chat.question.answeredWith`,{answer:ip(n)})),t.hint.textContent=``;try{await j.answerQuestion(t.id,n,r)}catch(e){if(e instanceof D&&hp(e.status)){Mp(t,`closed`),t.hint.textContent=``;return}t.settled=!1,Mp(t,`pending`),t.hint.textContent=w(`chat.question.submitFailed`,{reason:O(e)}),jp(t,Date.now())}}function Fp(e,t){let n=N(`div`,`q-head`),r=N(`div`,`q-title`),i=t[0]?.header;r.textContent=i!==void 0&&i!==``?i:w(`chat.question.needDecision`);let a=t[0]?.intent?.kind;return a!==void 0&&a!==``&&r.appendChild(N(`span`,`q-intent`,a===`plan-review`?w(`chat.question.planReview`):a)),n.appendChild(r),n.appendChild(e.timer),n}function Ip(e,t){let n=N(`div`,`mcol q-col`),r=N(`div`,`msg question`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.question.title`))),i.appendChild(N(`span`,null,xe())),r.appendChild(i);let a=N(`div`,`bubble question-bubble`),o=N(`div`,`q-card`);o.dataset.state=`pending`;let s=N(`button`,`q-submit btn btn-accent`,w(`chat.question.submit`));s.type=`button`;let c={id:t.id,paneId:e.id,root:n,card:o,timer:N(`div`,`q-timer`),hint:N(`div`,`q-hint`),result:N(`div`,`q-result`),submit:s,controls:[],questions:t.questions,picks:{},deadline:null,state:`pending`,settled:!1,onEdit:()=>{c.hint.textContent=``}};o.appendChild(Fp(c,t.questions));let l=N(`div`,`q-items`);for(let e of t.questions)l.appendChild(bp(c,e));o.appendChild(l);let u=N(`div`,`q-actions`);return u.appendChild(c.submit),o.appendChild(u),o.appendChild(c.hint),o.appendChild(c.result),c.submit.addEventListener(`click`,()=>Np(e,c)),a.appendChild(o),r.appendChild(a),n.appendChild(r),c}function Lp(e,t){return co(e),e.el.appendChild(t.root),Tp(e).set(t.id,t),Cp.add(t),wp===null&&(wp=window.setInterval(Ap,1e3)),t}function Rp(e,t){t.questions.length>0&&(e.questions=t.questions),e.deadline=op(t,Date.now());let n=!cp(ap(t,Date.now()));return e.state===`expired`&&!e.settled&&n&&Mp(e,`pending`),e.state===`pending`&&(e.hint.textContent=``,jp(e,Date.now())),e}function zp(e){let t=mp(e),n=t?.questions;if(!t||n===void 0||n.length===0)return null;let r={id:t.id,questions:n};return t.expires_at!==void 0&&(r.expires_at=t.expires_at),t.timeout_ms!==void 0&&(r.timeout_ms=t.timeout_ms),t.remaining_ms!==void 0&&(r.remaining_ms=t.remaining_ms),r}function Bp(e,t){let n=zp(t);if(!n)return null;let r=kp(e,n.id);if(r)return Rp(r,n);let i=Rp(Ip(e,n),n);return Lp(e,i),W(e,!0),i}async function Vp(e){if(e.id===``)return;let t=e.id,n;try{n=await j.questions(t)}catch{return}let r=0;for(let t of n.questions??[]){let n=zp(t);if(!n)continue;let i=kp(e,n.id);if(i){Rp(i,n);continue}Lp(e,Rp(Ip(e,n),n)),r+=1}r>0&&W(e,!0)}function Hp(e,t,n){let r=Ip(e,{id:t.id,questions:t.questions});return n?(n.appendChild(r.root),Tp(e).set(r.id,r)):Lp(e,r),t.settled&&!t.timedOut?Mp(r,`done`,w(`chat.question.answeredWith`,{answer:t.answerText})):t.settled?(r.settled=!0,Mp(r,`expired`)):Mp(r,`expired`,w(`chat.question.interrupted`)),r.root}function Up(){for(let e of Cr())Vp(e)}function Wp(e,t){e.on(`question`,e=>{try{Bp(t(e),e)}catch(e){console.warn(`SSE question`,e)}}),e.onConn(e=>{e===`online`&&Up()})}var Gp=200;function Kp(e,t){let n=e.dedup;if(n.tail?.role!==`assistant`)return n.tail=null,t===``?null:t;n.guardActive||(n.guardActive=!0,n.guardBuf=``,n.guardAll=!1),n.guardBuf+=t;let r=n.tail.content??``;if(r.startsWith(n.guardBuf))return n.guardBuf===r&&(n.guardAll=!0),null;let i=n.guardBuf;return n.guardActive=!1,n.guardAll=!1,n.tail=null,i===``?null:i}function qp(e,t){let n=e.dedup;if(!n.guardActive)return!1;n.guardActive=!1;let r=n.guardAll||typeof t==`string`&&t!==``&&n.tail?.role===`assistant`&&t===(n.tail.content??``);return n.guardAll=!1,n.tail=null,r}function Jp(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Yp(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg tool`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.tool.title`))),r.appendChild(i);let a=N(`div`,`bubble`),o=N(`div`,`content restore-tool`);o.textContent=e,a.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n)}function Xp(e,t,n){if(t.kind===`call`){e.histToolStep+=1;let r=t.tool_call_id??`call_`+e.histToolStep,i=Dh({step:e.histToolStep,name:t.tool_name??`tool`,argsText:Jp(t.tool_args),desc:Ch(t.tool_args)});n.appendChild(i.col),e.restoreOps.set(r,i);return}let r=t.tool_call_id??``,i=e.restoreOps.get(r);if(i){let n=!!t.tool_error&&t.tool_error!==``;Oh(i,n?String(t.tool_error):Jp(t.tool_value),n,t.tool_value),e.restoreOps.delete(r);return}Yp(w(`shell.restore.orphanResult`)+(t.tool_error?String(t.tool_error):Jp(t.tool_value)),n)}function Zp(e){return e.kind===`steering`?`steering`:e.kind===`queued`?`queued`:`user`}function Qp(e,t,n,r){let i=String(t.content??``),a=typeof t.question_id==`string`?t.question_id:``;if(t.role===`question`){let i=a===``?void 0:r.get(a);i!==void 0&&t.kind===`question`&&Hp(e,i,n);return}if(t.role===`inbox`||t.kind===`inbox`){mf(e,i,{source:t.source,kind:t.kind,into:n});return}if(t.role===`user`){let r=Zf(i);ff(e,r.rest,{kind:Zp(t),attachments:of(t.attachments),quotes:r.quotes,into:n});return}if(t.role===`assistant`){if(i.trim()===``)return;let t=Ru(e,n);t.text=i,zu(e,t);return}if(t.role===`thinking`){$p(i,n);return}Xp(e,t,n)}function $p(e,t){t.appendChild(Df({text:e,collapsed:!0}).root)}function em(e,t){e.el.querySelector(`.restore-note`)||e.el.appendChild(N(`div`,`restore-note`,t))}async function tm(e,t){let n;try{n=await j.messages(e.id)}catch{e.streaming||em(e,w(`shell.restore.unavailable`));return}if(t&&!t())return;let r=n.messages??[];if(e.streaming)return;eo(e),e.restoreOps.clear(),e.histToolStep=0;let i=document.createElement(`div`);r.length>Gp&&i.appendChild(N(`div`,`restore-fold`,w(`shell.restore.folded`,{n:Gp})));let a=r.length>Gp?r.slice(r.length-Gp):r,o=new Map(vp(a).map(e=>[e.id,e]));for(let t of a)Qp(e,t,i,o);if(e.restoreOps.size){for(let t of e.restoreOps.values())Oh(t,w(`shell.restore.noResult`),!1);e.restoreOps.clear()}if(a.length){let e=N(`div`,`live-sep`);e.appendChild(N(`span`,null,w(`shell.restore.sessionStart`))),e.title=w(`shell.restore.earlier`),i.appendChild(e)}if(!t||t()){if(e.el.replaceChildren(...i.childNodes),!a.length){lo(e);let t=N(`div`,`live-sep`);t.appendChild(N(`span`,null,w(`shell.restore.sessionStart`))),e.el.appendChild(t)}e.dedup.tail=a.length?a[a.length-1]??null:null,e.dedup.guardActive=!1,e.dedup.guardBuf=``,e.dedup.guardAll=!1,e.restored=!0,to(e),W(e,!0),Vp(e)}}async function nm(){try{let e=((await j.sessions()).sessions??[]).find(e=>e.active===!0);if(e?.id)return e.id}catch{}try{let e=await j.workspaces();if(e.active_session)return e.active_session}catch{}try{if(((await j.sessions()).sessions??[]).some(e=>e.id===`cli-main`))return`cli-main`}catch{}return null}async function rm(){let e=await nm();if(e===null){let e=B();e&&!e.streaming&&em(e,w(`shell.restore.noActive`));return}let t=Nr(e);!t.restored&&!t.streaming?await tm(t):Vp(t)}var im=null;function am(){im||(im=document.createElement(`div`),im.className=`switch-progress`,document.body.appendChild(im))}function om(){im?.remove(),im=null}function sm(e,t){let n=wr(e,t?.kind,t?.title);if(Mr(e),!n.streaming&&!n.restored){let e=++n.restoreSeq;am(),tm(n,()=>e===n.restoreSeq).finally(()=>{e===n.restoreSeq&&om()})}else Vp(n);return n}var cm=null,lm=null,um=null,dm=null,fm=[],pm=[],mm=``;function hm(e){let t=(e.wid??``).trim();if(t!==``)return t;let n=(e.title??``).trim(),r=/^(W\d+)/.exec(n);if(r&&r[1])return r[1];let i=e.id??``,a=i.lastIndexOf(`-`);return a>=0?i.slice(a+1):i}function gm(e){return(e.title??``).trim().replace(/^W\d+\s*[·::-]\s*/,``)||hm(e)}function _m(e){return{id:e.id??``,wid:hm(e),title:gm(e),model:String(e.model??``),status:String(e.status??``)}}function vm(e){let t=e.parentSessionId??e.parent_session??e.parent;return typeof t==`string`&&t.trim()!==``?t.trim():null}function ym(e){return e.kind===`worker`||(e.id??``).startsWith(`worker:`)}function bm(e,t){let n=e.filter(ym);if(t===``)return n.map(_m);let r=n.filter(e=>{let n=vm(e);if(n!==null)return n===t;let r=e.id??``;return(r.startsWith(`worker:`)?r.slice(7):r).startsWith(t+`-`)});return(r.length>0?r:n).map(_m)}function xm(e){let t=Fr(e.id),n=e.status!==``&&e.status!==`RUNNING`,r=N(`button`,`ws-strip-row`+(t?` running`:``)+(n?` settled`:``));return r.type=`button`,r.dataset.id=e.id,r.appendChild(N(`span`,`sess-dot`+(t?` busy`:``))),r.appendChild(N(`span`,`ws-strip-wid`,e.wid)),r.appendChild(N(`span`,`ws-strip-title`,e.title)),r.appendChild(N(`span`,`ws-strip-meta`,e.status===``?w(t?`shell.tree.running`:`shell.tree.idle`):e.status)),r.title=e.wid+` · `+e.title+(e.model?` · `+e.model:``)+w(`shell.worker.stripHint`),r.addEventListener(`click`,()=>{sm(e.id,{kind:`worker`,title:e.title})}),r}function Sm(){if(lm===null||um===null||cm===null||!cm.isConnected)return;if(pm.length===0){cm.classList.add(`hidden`),lm.replaceChildren(),um.textContent=``;return}cm.classList.remove(`hidden`);let e=document.createDocumentFragment();for(let t of pm)e.appendChild(xm(t));lm.replaceChildren(...Array.from(e.childNodes)),um.textContent=String(pm.length);let t=pm.filter(e=>Fr(e.id)).length;dm!==null&&(dm.textContent=t>0?w(`shell.worker.stripTitle`,{n:t}):w(`shell.worker.stripTitlePlain`))}function Cm(e,t){e!=null&&(fm=e);let n=t===void 0?B():t;mm=n===null?``:n.id,pm=bm(fm,mm),Sm()}function wm(e){let t=e.id??``;if(t===``||cm===null)return;let n=_m(e),r=pm.findIndex(e=>e.id===t);r>=0?pm[r]={...pm[r],...n}:pm=[...pm,n],Sm()}function Tm(){if(cm!==null)return cm;let e=document.getElementById(`main`);if(!e)return null;let t=N(`div`,`ws-strip hidden`);t.id=`wsStrip`;let n=N(`div`,`ws-strip-head`);return dm=N(`span`,`ws-strip-lead`,w(`shell.worker.stripTitlePlain`)),um=N(`span`,`ws-strip-count`,``),lm=N(`div`,`ws-strip-list`),n.appendChild(dm),n.appendChild(um),t.appendChild(n),t.appendChild(lm),e.appendChild(t),cm=t,cm}var Em=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`svg`]),Dm=new Set([`md`,`markdown`,`mdx`]),Om=new Set([`diff`,`patch`]),km=new Set(`ts.tsx.js.jsx.mjs.cjs.py.rb.go.rs.java.c.h.cc.cpp.hpp.cs.php.sh.bash.zsh.sql.html.htm.css.scss.less.xml.json.jsonl.yaml.yml.toml.ini.cfg.conf.env.log.tex.rst.csv.tsv.txt.text`.split(`.`)),Am=new Set([...Em,...Dm,...Om,`json`,`jsonl`,`yaml`,`yml`,`toml`,`ini`,`cfg`,`conf`,`env`,`log`,`csv`,`tsv`,`txt`,`text`]),jm=new Set([`read_file`]),Mm=new Set([`read_file`,`write_file`,`list_dir`]);function Nm(e){let t=(e.split(/[?#]/)[0]??``).replace(/^.*[\\/]/,``),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function Pm(e){let t=Nm(e);return Em.has(t)?`image`:Dm.has(t)?`markdown`:Om.has(t)?`diff`:km.has(t)?`code`:`unknown`}function Fm(e){let t=e.trim();if(t===``||/\s/.test(t)||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith(`#`))return!1;let n=Nm(t);return Em.has(n)||Dm.has(n)||Om.has(n)||km.has(n)?t.includes(`/`)||t.includes(`\\`)||t.startsWith(`.`)?!0:Am.has(n):!1}function Im(e){if(typeof e==`string`){let t=e.trim();if(!t.startsWith(`{`))return null;try{return Im(JSON.parse(t))}catch{return null}}return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Lm(e,t){if(!Mm.has(e))return null;let n=Im(t),r=n&&typeof n.path==`string`?n.path.trim():``;return r===``||!Fm(r)?null:{path:r,kind:Pm(r),source:`tool`}}function Rm(e){return/^[A-Za-z]:([\\/]|$)/.test(e)||/^\\\\/.test(e)}function zm(e){return Rm(e)?`\\`:`/`}function Bm(e){let t=/^([A-Za-z]:)[\\/]?/.exec(e);if(t)return t[1]+`\\`;let n=/^(\\\\[^\\/]+[\\/][^\\/]+)[\\/]?/.exec(e);return n?n[1]+`\\`:`/`}function Vm(e){let t=Bm(e),n=e;return n=t===`/`?e.replace(/^\/+/,``):e.toLowerCase().startsWith(t.toLowerCase())?e.slice(t.length):e,n.split(/[\\/]+/).filter(e=>e!==``)}function Hm(e,t){if(e===``)return t;let n=zm(e);return e.replace(/[\\/]+$/,``)+n+t}function Um(e){let t=Bm(e),n=Vm(e);if(n.length===0)return t;let r=t;for(let e=0;e<n.length-1;e++)r=Hm(r,n[e]);return r}function Wm(){let e=`http://www.w3.org/2000/svg`,t=document.createElementNS(e,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.3`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`);let n=document.createElementNS(e,`path`);return n.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v7a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z`),t.appendChild(n),t}function Gm(e){let t=N(`div`,`modal-scrim`),n=N(`div`,`modal-card ws-fs`);n.appendChild(N(`div`,`modal-card-title`,e.title)),e.note&&n.appendChild(N(`div`,`side-note`,e.note));let r=``,i=N(`div`,`ws-fs-crumbs`),a=N(`div`,`ws-fs-tree`),o=N(`div`,`ws-fs-addr`),s=N(`input`,`cfg-input`);s.placeholder=w(`chat.fsbrowse.pathPlaceholder`),s.value=``;let c=N(`button`,`btn btn-soft btn-mini`,w(`chat.fsbrowse.go`));c.type=`button`,o.appendChild(s),o.appendChild(c);let l=N(`div`,`ws-fs-status`);n.appendChild(i),n.appendChild(a),n.appendChild(o),n.appendChild(l);function u(e){let t=document.createElement(`div`),n=Bm(e),r=Vm(e),a=N(`button`,`ws-fs-crumb`+(r.length?``:` cur`),n);a.type=`button`,a.title=w(`chat.fsbrowse.root`),a.addEventListener(`click`,()=>void f(n)),t.appendChild(a);let o=n;for(let e=0;e<r.length;e++){let n=r[e];o=Hm(o,n);let i=N(`button`,`ws-fs-crumb`+(e===r.length-1?` cur`:``),n);i.type=`button`;let a=o;i.addEventListener(`click`,()=>void f(a)),t.appendChild(i)}i.replaceChildren(...t.childNodes)}function d(e){i.replaceChildren(...e)}async function f(t){let n=Array.from(i.childNodes);l.className=`ws-fs-status`,l.textContent=``,u(t),s.value=t,r=t;let o;try{o=await j.fsBrowse(t)}catch{d(n),l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.unavailable`);let t=document.createElement(`div`);t.appendChild(N(`div`,`side-note`,e.fallbackNote??w(`chat.fsbrowse.fallback`))),a.replaceChildren(...t.childNodes);return}if(o.error){d(n),l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.failed`,{reason:O(o.error,w(`chat.fsbrowse.manualPath`))});return}l.textContent=w(`chat.fsbrowse.selected`,{path:o.path||Bm(t)}),l.className=`ws-fs-status ok`,r=o.path??t,s.value=o.path??t,u(o.path??t);let c=document.createElement(`div`),p=o.dirs??[];p.length||c.appendChild(N(`div`,`side-note`,w(`chat.fsbrowse.noSubdirs`)));for(let e of p){let t=N(`div`,`ws-fs-dir`),n=N(`span`,`ws-fs-dir-icon`);n.appendChild(Wm()),t.appendChild(n),t.appendChild(N(`span`,`ws-fs-dir-name`,e)),t.addEventListener(`click`,()=>{f(Hm(r,e))}),c.appendChild(t)}a.replaceChildren(...c.childNodes)}c.addEventListener(`click`,()=>{let e=s.value.trim();e&&f(e)}),s.addEventListener(`keydown`,e=>{e.key===`Enter`&&c.click()});let p=N(`div`,`modal-card-actions`),m=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));m.type=`button`;let h=N(`button`,`btn btn-accent`,e.confirmLabel);h.type=`button`;let g=null,_=!1,v=null,y=()=>{_||(_=!0,g&&(F(g),g=null),t.remove(),e.onClose?.(v))};g=P(y),m.addEventListener(`click`,y),h.addEventListener(`click`,()=>{let t=r||s.value.trim();if(!t){l.className=`ws-fs-status err`,l.textContent=w(`chat.fsbrowse.needPath`),s.focus();return}v=t,e.onPick(t,{status:l,close:y,setBusy:t=>{h.disabled=t,h.textContent=t?e.busyLabel:e.confirmLabel}})}),p.appendChild(m),p.appendChild(h),n.appendChild(p),t.appendChild(n),document.body.appendChild(t),f(``)}function Km(e,t){return new Promise(n=>{let r=null,i=!1,a=e=>{i||(i=!0,n(e))};Gm({title:e,note:t,confirmLabel:w(`chat.preview.chooseDir`),busyLabel:w(`chat.preview.busy`),onPick:(e,t)=>{r=e,t.close()},onClose:()=>a(r)})})}var qm={ts:`typescript`,tsx:`typescript`,js:`javascript`,jsx:`javascript`,mjs:`javascript`,cjs:`javascript`,json:`json`,jsonl:`json`,md:`markdown`,markdown:`markdown`,mdx:`markdown`,py:`python`,go:`go`,java:`java`,c:`cpp`,h:`cpp`,cc:`cpp`,cpp:`cpp`,hpp:`cpp`,sh:`bash`,bash:`bash`,zsh:`bash`,sql:`sql`,html:`xml`,htm:`xml`,xml:`xml`,css:`css`,scss:`css`,less:`css`,yaml:`yaml`,yml:`yaml`};function Jm(e,t){let n=N(`pre`,`preview-code`),r=N(`code`);r.textContent=e;let i=qm[Nm(t)];return i&&(r.className=`language-`+i),n.appendChild(r),i&&pu(n),n}function Ym(e){let t=N(`div`,`preview-md`);return fl(t,e),t}function Xm(e,t){let n=N(`div`,`preview-img`),r=N(`img`);return r.src=e,r.alt=t,n.appendChild(r),n}function Zm(e){return e.startsWith(`@@`)?` hunk`:e.startsWith(`+`)&&!e.startsWith(`+++`)?` add`:e.startsWith(`-`)&&!e.startsWith(`---`)?` del`:``}function Qm(e){let t=e.split(`
|
|
91
|
+
`).map(e=>`<span class="preview-diff-line`+Zm(e)+`">`+ye(e)+`</span>`).join(`
|
|
92
|
+
`),n=N(`div`,`preview-diff`);return n.replaceChildren(...ul(t)),n}function $m(e){let t=N(`div`,`preview-degrade`);return t.replaceChildren(...ul(`<div class="preview-degrade-reason">`+ye(e)+`</div>`)),t}function eh(e){return/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(e)}function th(e){if(e.degraded!==void 0)return{node:$m(e.degraded),degraded:e.badge??e.degraded};if(e.kind===`image`)return e.url?{node:Xm(e.url,e.path),degraded:null}:{node:$m(w(`chat.preview.degradeImage`)),degraded:w(`chat.preview.badgeImage`)};let t=e.text??null;return t===null?{node:$m(w(`chat.preview.degradeNotInSession`)),degraded:w(`chat.preview.badgeNotInSession`)}:eh(t)?{node:$m(w(`chat.preview.degradeBinary`)),degraded:w(`chat.preview.badgeBinary`)}:t.length>262144?{node:$m(w(`chat.preview.degradeTooLarge`)),degraded:w(`chat.preview.badgeTooLarge`)}:e.kind===`markdown`?{node:Ym(t),degraded:null}:e.kind===`diff`?{node:Qm(t),degraded:null}:e.kind===`code`?{node:Jm(t,e.path),degraded:null}:{node:$m(w(`chat.preview.degradeUnsupported`)),degraded:w(`chat.preview.badgeUnsupported`)}}var nh=null,rh=null,ih=null,ah=null,oh=null,sh=null,ch=0,lh=``;function uh(e){return e.replace(/^.*[\\/]/,``)||e}function dh(e){let t=navigator.clipboard;t&&typeof t.writeText==`function`&&t.writeText(e).catch(()=>{})}function fh(e){Gm({title:w(`chat.preview.manager`),note:w(`chat.preview.target`,{path:e}),confirmLabel:w(`chat.preview.chooseDir`),busyLabel:w(`chat.preview.busy`),onPick:(e,t)=>t.close()})}function ph(){let e=N(`div`,`preview-host hidden`),t=N(`div`,`preview-panel`),n=N(`div`,`preview-head`);ih=N(`span`,`preview-title`),ah=N(`span`,`preview-path`),n.appendChild(ih),n.appendChild(ah),oh=N(`span`,`preview-note hidden`),n.appendChild(oh);let r=N(`button`,`preview-close`,`×`);r.type=`button`,r.title=w(`chat.preview.close`),r.setAttribute(`aria-label`,w(`chat.preview.close`)),r.addEventListener(`click`,_h),n.appendChild(r),t.appendChild(n),rh=N(`div`,`preview-body`),t.appendChild(rh);let i=N(`div`,`preview-actions`),a=N(`button`,`preview-action`,w(`chat.preview.copyPath`));a.type=`button`,a.addEventListener(`click`,()=>dh(lh)),i.appendChild(a);let o=N(`button`,`preview-action`,w(`chat.preview.openInManager`));o.type=`button`,o.addEventListener(`click`,()=>fh(lh)),i.appendChild(o),t.appendChild(i),e.appendChild(t),document.body.appendChild(e),nh=e}function mh(){(!nh||!nh.isConnected||!rh)&&ph()}async function hh(e,t,n){let r=null,i,a,o=!1;if(!e.url&&e.loadFull)try{let t=await e.loadFull();`degraded`in t?(i=t.degraded,a=t.badge):(r=t.text,o=t.truncated===!0)}catch{i=w(`chat.preview.degradeReadFailed`)}else if(!e.url&&e.load)try{r=await e.load()}catch{r=null}if(t!==ch)return;let s=th({path:e.candidate.path,kind:e.candidate.kind,text:r,url:e.url??null,degraded:i,badge:a});t===ch&&(n.replaceChildren(s.node),n.classList.toggle(`is-degraded`,s.degraded!==null),oh&&(oh.textContent=o?w(`chat.preview.truncated`):``,oh.classList.toggle(`hidden`,!o)))}function gh(e){let t=++ch;mh(),nh&&rh&&ih&&ah&&(lh=e.candidate.path,ih.textContent=uh(e.candidate.path),ah.textContent=e.candidate.path,ah.title=e.candidate.path,nh.classList.remove(`hidden`),oh&&(oh.textContent=``,oh.classList.add(`hidden`)),sh===null&&(sh=P(_h)),hh(e,t,rh))}function _h(){ch+=1,nh&&(nh.classList.add(`hidden`),rh&&rh.replaceChildren()),sh!==null&&(F(sh),sh=null)}var vh=60,yh=`collapsed`,bh=`expanded`,xh=`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false"><path d="M6 3.5 10.5 8 6 12.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path></svg>`;function Sh(e,t){let n=typeof e==`string`?e.replace(/\s+/g,` `).trim():``;return n===``?t:n.length<=60?n:n.slice(0,60)+`…`}function Ch(e){if(typeof e==`string`){let t=e.trim();if(!t.startsWith(`{`))return``;try{return Ch(JSON.parse(t))}catch{return``}}if(typeof e==`object`&&e){let t=e.desc;return typeof t==`string`?t:``}return``}function wh(e){e.step=0}function Th(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function Eh(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=vh?t:t.slice(0,vh)+`…`}function Dh(e){let t=N(`div`,`mcol`),n=N(`div`,`msg tool`),r=N(`div`,`msg-caption`);r.appendChild(N(`span`,`who`,w(`chat.tool.title`))),r.appendChild(N(`span`,null,e.name)),n.appendChild(r);let i=N(`div`,`bubble`),a=document.createElement(`details`);a.className=`toolcard running`,a.open=!1;let o=document.createElement(`summary`);o.className=`toolcard-head`,o.setAttribute(`aria-expanded`,`false`);let s=N(`div`,`toolcard-row1`);s.appendChild(N(`span`,`step-tag`,w(`chat.tool.step`,{n:e.step})));let c=N(`span`,`toolcard-name`,Sh(e.desc,e.name));c.title=e.name,s.appendChild(c);let l=N(`span`,`toolcard-state`);l.appendChild(N(`span`,`ts-dot`)),l.appendChild(N(`span`,`ts-label`,w(`chat.tool.running`))),s.appendChild(l);let u=N(`button`,`toolcard-copy`,w(`chat.tool.copy`));u.type=`button`,u.title=w(`chat.tool.copyHint`),u.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation();let n=a.querySelector(`.tool-out`),r=e.argsText+`
|
|
93
|
+
`+(n?.textContent??``);navigator.clipboard.writeText(r).catch(()=>{})}),s.appendChild(u);let d=N(`span`,`toolcard-fold`);d.setAttribute(`data-fold`,yh),d.innerHTML=xh,s.appendChild(d),o.appendChild(s),a.appendChild(o);let f=N(`div`,`toolcard-body`),p=N(`div`,`toolcard-args-preview`),m=Eh(e.argsText);p.textContent=m?w(`chat.tool.args`,{text:m}):w(`chat.tool.argsNone`),f.appendChild(p),f.appendChild(N(`pre`,`tool-args`,e.argsText));let h=N(`div`,`toolcard-result-preview`);h.textContent=``,f.appendChild(h);let g=Lm(e.name,e.argsText);if(g!==null&&jm.has(e.name)){let e=g,t=N(`button`,`toolcard-preview`,w(`chat.tool.preview`));t.type=`button`,t.title=w(`chat.tool.previewHint`),t.addEventListener(`click`,t=>{t.preventDefault();let n=a.querySelector(`.tool-out`);gh({candidate:e,load:async()=>n?.textContent??null})}),f.appendChild(t)}return a.appendChild(f),a.addEventListener(`toggle`,()=>{o.setAttribute(`aria-expanded`,a.open?`true`:`false`),d.setAttribute(`data-fold`,a.open?bh:yh)}),i.appendChild(a),n.appendChild(i),t.appendChild(n),{toolName:e.name,col:t,card:a,label:l.querySelector(`.ts-label`)??l,resultPv:h,body:f}}function Oh(e,t,n,r){e.card.classList.remove(`running`),e.card.classList.add(n?`err`:`ok`),e.label.textContent=w(n?`chat.tool.failed`:`chat.tool.done`);let i=Eh(t);e.resultPv.textContent=i?w(`chat.tool.result`,{text:i}):``,i&&e.resultPv.classList.add(`has`),e.body.querySelector(`.tool-out`)||e.body.appendChild(N(`pre`,`tool-out`+(n?` err-c`:``),t));let a=sf(r);a.length>0&&!e.body.querySelector(`.attach-grid`)&&e.body.appendChild(Bu(of(a)))}function kh(e,t,n){e.step+=1;let r=Dh({step:e.step,name:String(t.name||`tool`),argsText:Th(t.args),desc:Ch(t.args)});return(n??e.el).appendChild(r.col),n||W(e),e.ops.set(String(t.id),r),r.col}function Ah(e,t){if(e!==`spawn_worker`||t.ok===!1)return;let n=t.value;if(typeof n!=`object`||!n)return;let r=n,i=typeof r.sessionId==`string`?r.sessionId:``;if(i===``)return;let a=typeof r.wid==`string`?r.wid:``,o=typeof r.title==`string`?r.title:``;wm({id:`worker:`+i,kind:`worker`,...a===``?{}:{wid:a},...o===``?{}:{title:o},workspace:`engine`})}function jh(e,t){Ah(e.ops.get(String(t.id))?.toolName??``,t);let n=e.ops.get(String(t.id));if(!n)return;let r=t.ok===!1||!!t.error,i=r?w(`chat.tool.failed`):t.decision===`deny`?w(`chat.tool.denied`):t.decision===`ask`?w(`chat.tool.ask`):w(`chat.tool.done`);Oh(n,t.error?String(t.error):Th(t.value),r||t.decision===`deny`),n.label.textContent=i,W(e)}var Mh=null;function Nh(){Mh&&Vu(Mh,Yd(),e=>{Zd(e),Nh()},()=>Nh())}function Ph(e,t){Mh=N(`div`,`attach-tray hidden`);let n=t??e;n===e?e.appendChild(Mh):n.parentElement?.insertBefore(Mh,n)??e.insertBefore(Mh,e.firstChild)}var Fh=new Map,Ih=null,Lh=null,Rh=0;function zh(){return B()?.id??``}function Bh(e){return Fh.get(e)??[]}function Vh(){if(!Ih||!Lh)return;let e=Lh.getBoundingClientRect().height;if(e<=0)return;let t=Lh.querySelector(`.attach-tray`),n=t?t.offsetHeight:0;Ih.style.bottom=e+n+`px`}function Hh(e,t){let n=N(`div`,`quote-chip`);n.appendChild(N(`span`,`quote-chip-src`,e.source.label+(e.truncated?w(`chat.user.truncatedSuffix`):``)));let r=e.text.replace(/\s+/g,` `).trim();n.appendChild(N(`span`,`quote-chip-text`,r===``?w(`chat.quote.empty`):r.slice(0,40))),n.appendChild(N(`span`,`quote-chip-bytes`,String(e.bytes)+` B`));let i=N(`button`,`quote-chip-remove`,`×`);return i.type=`button`,i.title=w(`chat.quote.removeHint`),i.setAttribute(`aria-label`,w(`chat.quote.removeAria`,{label:e.source.label})),i.addEventListener(`click`,()=>t(e)),n.appendChild(i),n}function Uh(){if(!Ih)return;let e=Bh(zh());if(e.length===0){Ih.classList.add(`hidden`),Ih.replaceChildren();return}Ih.classList.remove(`hidden`),Vh();let t=document.createElement(`div`);for(let n of e)t.appendChild(Hh(n,Wh));Ih.replaceChildren(...Array.from(t.childNodes)),Vh()}function Wh(e){let t=zh(),n=Bh(t),r=n.indexOf(e);r>=0&&(n.splice(r,1),Fh.set(t,n)),Uh()}function Gh(e=zh()){let t=Bh(e);return Fh.set(e,[]),zh()===e&&Uh(),t}function Kh(e,t){let n=Bh(e),r=new Set(n.map(e=>Uf(e))),i=t.filter(e=>!r.has(Uf(e)));Fh.set(e,[...i,...n]),zh()===e&&Uh()}async function qh(e){let t=zh(),n=Bf(e.text,Pf),r=await Hf(n.text),i=Bh(t),a=r===``?`x:`+n.text:r;if(i.some(e=>Uf(e)===a))return`duplicate`;if(i.length>=8)return`full`;let o=Ff-i.reduce((e,t)=>e+t.bytes,0);if(o<256)return`full`;let s=Bf(e.text,Math.min(Pf,o)),c=Wf({id:`q`+String(++Rh),source:e.source,text:s.text,hash:r,range:e.range,format:e.format,filePath:e.filePath,lineRange:e.lineRange});return c.truncated=s.truncated,i.push(c),Fh.set(t,i),zh()===t&&Uh(),`added`}function Jh(e,t){Ih||(Lh=t??e,Ih=N(`div`,`quote-tray hidden`),Ih.id=`quoteTray`,Lh.appendChild(Ih),Br(()=>Uh()))}var Yh=[];function Xh(e){let t=Yh.findIndex(t=>t.name===e.name);t>=0?Yh[t]=e:Yh.push(e)}function Zh(){return Yh}var Qh=3e4;function $h(e){return e.signal!==null&&e.signal!==``?w(`chat.run.signal`,{signal:e.signal}):e.exit_code===null?w(`chat.run.exitUnknown`):w(`chat.run.exit`,{code:e.exit_code,status:e.exit_code===0?w(`chat.run.success`):w(`chat.run.failure`)})}function eg(e,t,n){if(t===``)return null;let r=N(`div`,`exec-stream `+n);return r.appendChild(N(`div`,`exec-stream-label`,e)),r.appendChild(N(`pre`,`exec-stream-body`,t)),r}function tg(e){if(!e)return``;let t=[];return e.provider&&t.push(e.provider),t.push(e.net_isolated===!0?w(`chat.run.netIsolated`):w(`chat.run.netOnline`)),e.tmp_private===!0&&t.push(w(`chat.run.tmpPrivate`)),e.seccomp===!0&&t.push(w(`chat.run.seccomp`)),t.join(` · `)}function ng(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec`),i=N(`div`,`msg-caption`);i.appendChild(N(`span`,`who`,w(`chat.run.cmd`))),i.appendChild(N(`span`,null,xe())),r.appendChild(i);let a=N(`div`,`bubble exec-bubble`);return a.appendChild(N(`pre`,`exec-cmd`,t)),r.appendChild(a),n.appendChild(r),e.el.appendChild(n),to(e),n}function rg(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec exec-note`),i=N(`div`,`bubble info-bubble`);i.appendChild(N(`div`,`content info-content`,t)),r.appendChild(i),n.appendChild(r),e.el.appendChild(n),to(e)}function ig(e,t){let n=N(`div`,`mcol`),r=N(`div`,`msg exec`),i=N(`div`,`bubble exec-bubble`),a=N(`div`,`exec-block`);return i.appendChild(a),r.appendChild(i),n.appendChild(r),e.el.appendChild(n),to(e),{root:n,fill(n){let r=N(`div`,`exec-head`);r.appendChild(N(`span`,`exec-cmd`,t)),r.appendChild(N(`span`,`exec-code`+(n.failed?` err`:` ok`),n.codeLabel)),r.appendChild(N(`span`,`exec-dur`,String(n.durationMs)+` ms`)),a.appendChild(r);let i=tg(n.sandbox);i!==``&&a.appendChild(N(`div`,`exec-sandbox`,i));let o=eg(w(`chat.run.stdout`),n.stdout,`out`);o&&a.appendChild(o);let s=eg(w(`chat.run.stderr`),n.stderr,`err`);s&&a.appendChild(s),!o&&!s&&a.appendChild(N(`div`,`exec-sandbox`,w(`chat.run.noOutput`))),W(e,!0)}}}async function ag(e,t){let n=t.trim();if(n===``)return;ng(e,n);let r=ig(e,n);W(e);try{let t=await j.exec({command:n,session:e.id===``?void 0:e.id,timeout_ms:Qh});r.fill({codeLabel:$h(t),durationMs:t.duration_ms,stdout:t.stdout??``,stderr:t.stderr??``,failed:t.exit_code!==0||t.signal!==null&&t.signal!==``,sandbox:t.sandbox})}catch(t){r.root.remove(),rg(e,t instanceof D&&(t.status===404||t.status===405||t.status===501)?w(`chat.run.unsupported`):w(`chat.run.failed`,{reason:O(t,w(`settings.common.retryLater`))})),W(e,!0)}}function og(e,t,n){gf(e,t,n)}var sg=!1;function cg(){sg||(sg=!0,Xh({name:`run`,desc:w(`chat.command.run.desc`),args:w(`chat.command.run.args`),async run(e){let t=e.args.trim();return t===``?(og(e.ctx,w(`chat.command.run.usage`),`warn`),!0):(await ag(e.ctx,t),!0)}}),Xh({name:`goal`,desc:w(`chat.command.goal.desc`),args:w(`chat.command.goal.args`),async run(e){let t=e.args.trim();if(t===``){let t=Zr(e.ctx);return og(e.ctx,t===``?w(`chat.command.goal.none`):w(`chat.command.goal.current`,{text:t})),!0}try{let n=await Xr(e.ctx,t===`done`?``:t);og(e.ctx,n?w(`chat.command.goal.set`,{text:n.text}):w(`chat.command.goal.cleared`))}catch(t){og(e.ctx,t instanceof Error?t.message:w(`chat.command.goal.saveFailed`),`err`)}return!0}}),Xh({name:`model`,desc:w(`chat.command.model.desc`),args:w(`chat.command.model.args`),async run(e){let t=e.args.trim();if(t===``)return og(e.ctx,w(`chat.command.model.usage`),`warn`),!0;let n=await At(e.ctx.id,t);return n.kind===`ok`?og(e.ctx,w(`chat.command.model.switched`)):n.kind===`busy`?og(e.ctx,w(`chat.command.model.busy`),`warn`):og(e.ctx,n.text,`err`),!0}}),Xh({name:`compact`,desc:w(`chat.command.compact.desc`),args:``,async run(e){return await vv(e.ctx),!0}}))}var J=null,lg=null,ug=null,dg=[],fg=0,pg=null,mg=0,hg=null;function gg(){if(!J)return;let e=document.createElement(`div`);dg.forEach((t,n)=>{let r=N(`div`,`cmd-row`+(n===fg?` active`:``)+(t.isDir?` dir`:``));r.appendChild(N(`span`,`cmd-name`,t.label)),r.appendChild(N(`span`,`cmd-desc`,t.desc)),t.meta!==void 0&&t.meta!==``&&r.appendChild(N(`span`,`cmd-args`,t.meta)),r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,n===fg?`true`:`false`),r.addEventListener(`mousedown`,e=>{e.preventDefault(),_g(n)}),e.appendChild(r)}),J.replaceChildren(...Array.from(e.childNodes));let t=J.querySelector(`.cmd-row.active`);t&&typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`})}function _g(e){let t=dg[e];t&&hg&&hg(t)}function vg(){return J!==null&&!J.classList.contains(`hidden`)}function yg(e){pg=e}async function bg(e){if(!J||!pg)return;let t=++mg,n=[];try{n=await pg(e)}catch{n=[]}if(t===mg){if(dg=n,dg.length===0){xg();return}fg>=dg.length&&(fg=0),J.classList.remove(`hidden`),Cg(),gg(),ug===null&&(ug=P(xg))}}function xg(){mg+=1,J&&(J.classList.add(`hidden`),dg=[],fg=0,ug!==null&&(F(ug),ug=null))}function Sg(e){return vg()?e.key===`Escape`?(e.preventDefault(),xg(),!0):e.key===`ArrowDown`?(e.preventDefault(),fg=(fg+1)%dg.length,gg(),!0):e.key===`ArrowUp`?(e.preventDefault(),fg=(fg-1+dg.length)%dg.length,gg(),!0):e.key===`Enter`||e.key===`Tab`?(e.preventDefault(),_g(fg),!0):!1:!1}function Cg(){if(!J||!lg)return;let e=lg.getBoundingClientRect();J.style.left=Math.max(8,e.left)+`px`,J.style.bottom=Math.max(8,window.innerHeight-e.top+6)+`px`}function wg(e,t){J||(lg=e,hg=t,J=N(`div`,`cmd-popup hidden`),J.id=`cmdPopup`,J.setAttribute(`role`,`listbox`),document.body.appendChild(J))}var Tg=!1,Eg=new Set,Dg=[],Og=[],kg=null,Ag=``,jg=`active`,Mg=null,Ng=null,Pg=``,Fg=new Map,Ig=5e3;function Lg(){return Tg}function Rg(e){Tg=e}function zg(){return Dg}function Bg(e){Dg=e}function Vg(){return Og}function Hg(e){Og=e}function Ug(){return kg}function Wg(e){kg=e}function Gg(){return Ag}function Kg(e){Ag=e}function qg(){return jg}function Jg(e){jg=e}function Yg(){return Mg}function Xg(e){Mg=e}function Zg(){return Ng}function Qg(e){Ng=e}function $g(){return Pg}function e_(e){Pg=e}function t_(){return Fg}function n_(e){Fg=e}function r_(e){return e.replace(/\\/g,`/`)}function i_(){let e=(B()?.workspace??``).trim();return e===``?``:e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)?e:zg().find(t=>t.name===e)?.path??``}function a_(e){return e.type===`dir`?w(`chat.mention.dir`):e.size===null?w(`chat.mention.file`):e.size<1024?e.size+` B`:e.size<1048576?(e.size/1024).toFixed(1)+` KB`:(e.size/1048576).toFixed(1)+` MB`}async function o_(e){let t=i_();if(t===``)return{path:``,items:[],notice:w(`chat.mention.noWorkspace`)};let n=r_(e),r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r+1):``,a=r>=0?n.slice(r+1):n,o=t;for(let e of i.split(`/`).filter(Boolean))o=Hm(o,e);let s;try{s=await j.fsList(o)}catch{return{path:o,items:[],notice:w(`chat.mention.unavailable`)}}if(s.error!==void 0&&s.error!==``)return{path:o,items:[],notice:w(`chat.mention.openFailed`,{reason:s.error})};let c=s.entries??[],l=a.toLowerCase(),u=(l===``?c:c.filter(e=>e.name.toLowerCase().startsWith(l))).map(e=>{let t=i+e.name,n=e.type===`dir`?t+`/`:t;return{label:n,desc:a_(e),isDir:e.type===`dir`,value:n}}),d=s.truncated===!0?w(`chat.mention.truncated`):``;return{path:o,items:u,notice:d}}function s_(e){let t=e.trim();if(!t.startsWith(`!`))return e;let n=t.slice(1).trim();return n===``?`/`:`/run `+n}function c_(e){let t=s_(e).trim();return t.startsWith(`/`)&&t.length>1}function l_(e){let t=s_(e).trim().slice(1),n=t.search(/\s/);return n<0?{name:t,args:``}:{name:t.slice(0,n),args:t.slice(n+1)}}function u_(e,t){let n=Math.min(t,e.length)-1;for(;n>=0&&!/\s/.test(e[n]);){if(e[n]===`@`)return{start:n,after:e.slice(n+1,t)};--n}return null}async function d_(e,t){let n=t??B();if(!n||u_(e,e.length)!==null)return!1;let{name:r,args:i}=l_(e);if(r===``)return!1;let a=Zh().find(e=>e.name===r);return a?(xg(),await a.run({raw:e,args:i,ctx:n})):(gf(n,w(`chat.command.unknown`,{name:r}),`warn`),!0)}function f_(){return document.getElementById(`input`)}function p_(e){let t=f_();t&&(t.value=e.value+(e.value.endsWith(` `)?``:` `),t.dispatchEvent(new Event(`input`,{bubbles:!0})),xg(),t.focus())}function m_(e){let t=f_();if(!t)return;let n=t.selectionStart??t.value.length,r=u_(t.value,n);if(r===null)return;let i=t.value.slice(0,r.start),a=t.value.slice(n);t.value=i+`@`+e.value+a;let o=i.length+1+e.value.length;t.setSelectionRange(o,o),t.dispatchEvent(new Event(`input`,{bubbles:!0})),e.value.endsWith(`/`)?__(t.value,o):xg(),t.focus()}async function h_(e){let t=await o_(e);if(t.notice!==``){let e=B();e&&gf(e,t.notice,`warn`)}return t.items}function g_(e){let t=e.toLowerCase();return Zh().filter(e=>e.name.toLowerCase().startsWith(t)).map(e=>({label:`/`+e.name,desc:e.desc,meta:e.args,value:`/`+e.name}))}async function __(e,t){let n=u_(e,t??e.length);if(n!==null){yg(h_),await bg(n.after);return}if(e.startsWith(`/`)&&!/\s/.test(e.slice(1))){yg(g_),await bg(e.slice(1));return}yg(null),xg()}var v_=!1;function y_(){if(v_)return;v_=!0,cg();let e=f_();e&&(Br(()=>ei()),Kr(()=>ei()),yg(null),wg(e,e=>{e.label.startsWith(`/`)?p_(e):m_(e)}),e.addEventListener(`input`,()=>void __(e.value,e.selectionStart??e.value.length)),e.addEventListener(`keydown`,e=>{Sg(e)}),e.addEventListener(`blur`,()=>xg()))}function b_(e){return c_(e)}function x_(e){return Sg(e)}var S_=240;function C_(){return w(`chat.input.placeholderIdle`)}function w_(){return w(`chat.input.placeholderSteer`)}function T_(){return w(`chat.input.placeholderQueue`)}function E_(){return w(`chat.input.placeholderWorker`)}var D_=null,O_=null,k_=null,A_=null,j_=null,M_=`steer`,N_=`idle`;function P_(e){M_=e,I_()}function F_(){P_(M_===`steer`?`queue`:`steer`)}function I_(){if(j_){let e=j_.querySelector(`.sl-mode-label`);e?e.textContent=w(M_===`steer`?`chat.input.interject`:`chat.input.queue`):j_.textContent=w(M_===`steer`?`chat.input.interject`:`chat.input.queue`),j_.title=w(M_===`steer`?`chat.input.modeSteerTitle`:`chat.input.modeQueueTitle`),j_.classList.toggle(`queue`,M_===`queue`)}O_&&N_===`interject`&&(O_.placeholder=M_===`steer`?w_():T_()),k_&&(k_.disabled=!1,k_.textContent=w(N_===`worker`?`chat.input.send`:N_===`interject`?M_===`steer`?`chat.input.interject`:`chat.input.queue`:`chat.input.send`),k_.title=w(N_===`worker`?`chat.input.sendWorkerTitle`:N_===`interject`?M_===`steer`?`chat.input.steerTitle`:`chat.input.queueTitle`:`chat.input.sendTitle`))}function L_(e){let t=M(`#input`);O_=t,D_=M(`#inputbar`),k_=M(`#btnSend`);let n=M(`#slStop`);A_=n,j_=document.getElementById(`btnMode`);let r=()=>{t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,S_)+`px`};k_.addEventListener(`click`,()=>e.send(t.value,M_)),j_?.addEventListener(`click`,()=>F_()),n.addEventListener(`click`,()=>{n.disabled||(n.disabled=!0,e.cancel())}),t.addEventListener(`keydown`,n=>{if(x_(n)||n.key!==`Enter`||n.shiftKey)return;n.preventDefault();let r=n.ctrlKey||n.metaKey?M_===`steer`?`queue`:`steer`:M_;e.send(t.value,r)}),t.addEventListener(`input`,r),ev(t,D_),I_(),window.setTimeout(r,0)}function R_(){let e=O_??M(`#input`);e.value=``,e.style.height=`auto`,e.style.height=Math.min(e.scrollHeight,S_)+`px`}function z_(e){let t=O_??M(`#input`);t.value=e,t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,S_)+`px`}function B_(e){A_&&(A_.classList.toggle(`hidden`,!e),A_.disabled=!e)}function V_(e){N_=e;let t=O_;D_&&(D_.classList.toggle(`interject`,e===`interject`),D_.classList.toggle(`worker`,e===`worker`),D_.classList.remove(`readonly`)),j_&&j_.classList.toggle(`hidden`,e!==`interject`),t&&(t.placeholder=e===`worker`?E_():e===`interject`?M_===`steer`?w_():T_():C_(),t.readOnly=!1),I_()}var H_=null,U_=null,W_=null,G_=`<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"></path></svg>`;function K_(){return D_??document.getElementById(`inputbar`)}function q_(){let e=Od(),t=jd();U_&&(U_.classList.toggle(`hidden`,!1),U_.disabled=!1,U_.title=t===``?w(`chat.input.attachTitle`):t),e||ef(),Nh()}window.addEventListener(`studio:config-saved`,()=>{Ed(),Dd().then(q_)});function J_(e){H_&&(H_.textContent=e,H_.classList.toggle(`hidden`,e===``))}function Y_(e){let t=jd(),n=[],r=0;for(let i=0;i<e.length;i++){let a=e[i];a&&(t!==``&&a.type.indexOf(`image/`)===0?r+=1:n.push(a))}let i=Jd(n);Nh(),r>0?J_(t):i>0&&J_(w(`chat.input.rejectedCount`,{n:i}))}function X_(e){return td(e)?e.type.indexOf(`image/`)!==0||jd()===``:!1}function Z_(e){let t=e.clipboardData;if(!t)return[];let n=[],r=t.items;if(r)for(let e=0;e<r.length;e++){let t=r[e];if(t&&t.kind===`file`&&X_({name:``,type:t.type})){let e=t.getAsFile();e&&n.push(e)}}if(n.length===0&&t.files)for(let e=0;e<t.files.length;e++){let r=t.files[e];r&&X_(r)&&n.push(r)}return n}function Q_(e){let t=e.dataTransfer;return t?t.types&&Array.prototype.indexOf.call(t.types,`Files`)>=0?!0:!!t.files&&t.files.length>0:!1}function $_(){let e=jd();e!==``&&J_(e),W_?.click()}function ev(e,t){H_=N(`div`,`attach-note hidden`);let n=t.querySelector(`.input-box`),r=t.querySelector(`.input-side`);Ph(t,n),Jh(t,n),U_=document.createElement(`button`),U_.id=`btnAttach`,U_.type=`button`,U_.className=`btn btn-soft btn-icon attach-inline`,U_.innerHTML=G_,U_.title=w(`chat.input.attachTitle`),U_.setAttribute(`aria-label`,w(`chat.input.attachAria`)),U_.addEventListener(`click`,()=>$_()),n?n.appendChild(U_):r&&r.firstChild?r.insertBefore(U_,r.firstChild):(r??t).appendChild(U_),W_=document.createElement(`input`),W_.id=`attachInput`,W_.type=`file`,W_.accept=gd,W_.multiple=!0,W_.className=`attach-file hidden`,W_.addEventListener(`change`,()=>{if(W_&&W_.files){let e=[];for(let t=0;t<W_.files.length;t++){let n=W_.files[t];n&&td(n)&&e.push(n)}e.length>0&&Y_(e)}W_&&(W_.value=``)}),t.insertBefore(H_,t.firstChild),t.appendChild(W_),e.addEventListener(`paste`,e=>{let t=Z_(e);t.length>0&&Y_(t)}),document.addEventListener(`dragover`,e=>{Q_(e)&&(e.preventDefault(),K_()?.classList.add(`drop-active`))}),document.addEventListener(`dragleave`,e=>{Q_(e)&&K_()?.classList.remove(`drop-active`)}),document.addEventListener(`drop`,e=>{K_()?.classList.remove(`drop-active`);let t=e.dataTransfer;t&&t.files&&t.files.length!==0&&(e.preventDefault(),Y_(t.files))}),cd(Nh),q_(),Dd().then(q_)}var tv=M(`#statusText`),nv=M(`#statusDot`),rv=M(`#statusTurn`),iv=M(`#statusTime`);function Y(e,t){tv.textContent=e,nv.className=`dot`+(t?` `+t:``)}function av(e){rv.textContent=typeof e==`number`&&e>=1?w(`shell.status.turn`,{n:e}):w(`shell.status.turnNone`)}function ov(){R.streaming&&(iv.textContent=be((Date.now()-R.t0)/1e3))}function sv(){R.t0=Date.now(),cv(),R.msgTimer=window.setInterval(ov,500),ov()}function cv(){R.msgTimer!==null&&(window.clearInterval(R.msgTimer),R.msgTimer=null)}function lv(){cv(),R.t0>0&&(iv.textContent=be((Date.now()-R.t0)/1e3))}var uv=null;function dv(){uv!==null&&(window.clearTimeout(uv),uv=null)}function X(e,t,n=6e3){dv(),Y(e,t),uv=window.setTimeout(()=>{uv=null,!R.streaming&&(R.conn===`online`?Y(w(`shell.status.online`),`ok`):R.conn===`down`&&Y(w(`shell.status.reconnecting`),`err`))},n)}function fv(e){return e.id===``?void 0:e.id}function pv(e){return e instanceof Error?e.message:String(e)}var mv=!1,hv=new Map,gv=5e3;function _v(e){let t=typeof e.session==`string`&&e.session!==``?e.session:null,n=t?Sr(t)??null:B();n&&(Date.now()-(hv.get(n.id)??0)<gv||n.streaming||(async()=>{await tm(n),V(n)&&X(e.note||w(`shell.compact.done`),`ok`)})())}async function vv(e){if(!mv){mv=!0,R_(),e.draft=``;try{let t=fv(e);if(t===void 0){let e=await nm();if(e===null){X(w(`shell.compact.noSession`),`err`,8e3);return}t=e}Y(w(`shell.compact.busy`),`busy`);let n=await j.compactSession(t);if(n.compacted===!1){X(n.note||w(`shell.compact.notNeeded`),`ok`);return}hv.set(t,Date.now()),X(n.note||w(`shell.compact.historyDone`),`ok`),await tm(e)}catch(e){X(w(`shell.compact.failed`,{reason:pv(e)}),`err`,8e3)}finally{mv=!1}}}var yv=null;function bv(){return yv}function xv(e){yv=e}function Sv(e){return e===`read_roots`||e===`write_roots`?`roots`:e===`net_hosts`?`hosts`:e===`tool_extra`?`tools`:null}function Cv(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e!==``))).sort():[]}function wv(e,t){let n=Sv(e),r={};return n!==null&&(r[n]=Cv(n===`roots`?t.roots:n===`hosts`?t.hosts:t.tools)),JSON.stringify({cap:e,scope:r})}async function Tv(e,t){let n=wv(e,t),r=new TextEncoder().encode(n),i=globalThis.crypto?.subtle;if(i)try{let e=await i.digest(`SHA-256`,r);return Ev(new Uint8Array(e))}catch{}return Dv(r)}function Ev(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function Dv(e){return Ev(Av(e))}var Ov=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function kv(e,t){return(e>>>t|e<<32-t)>>>0}function Av(e){let t=e.length,n=Math.ceil((t+9)/64),r=new Uint8Array(n*64);r.set(e),r[t]=128;let i=new DataView(r.buffer);i.setUint32(n*64-8,Math.floor(t/536870912)),i.setUint32(n*64-4,t*8>>>0);let a=1779033703,o=3144134277,s=1013904242,c=2773480762,l=1359893119,u=2600822924,d=528734635,f=1541459225,p=new Uint32Array(64);for(let e=0;e<n;e++){for(let t=0;t<16;t++)p[t]=i.getUint32(e*64+t*4);for(let e=16;e<64;e++){let t=p[e-15],n=p[e-2],r=kv(t,7)^kv(t,18)^t>>>3,i=kv(n,17)^kv(n,19)^n>>>10;p[e]=p[e-16]+r+p[e-7]+i>>>0}let t=a,n=o,r=s,m=c,h=l,g=u,_=d,v=f;for(let e=0;e<64;e++){let i=kv(h,6)^kv(h,11)^kv(h,25),a=h&g^~h&_,o=v+i+a+Ov[e]+p[e]>>>0,s=(kv(t,2)^kv(t,13)^kv(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=h,h=m+o>>>0,m=r,r=n,n=t,t=o+s>>>0}a=a+t>>>0,o=o+n>>>0,s=s+r>>>0,c=c+m>>>0,l=l+h>>>0,u=u+g>>>0,d=d+_>>>0,f=f+v>>>0}let m=new Uint8Array(32),h=new DataView(m.buffer);return[a,o,s,c,l,u,d,f].forEach((e,t)=>h.setUint32(t*4,e)),m}var jv=new Set([`network`,`write_roots`,`unsandboxed`]);function Mv(){return[{cap:`network`,label:w(`grants.cap.network.label`),impact:w(`grants.cap.network.impact`),extra:w(`grants.cap.network.extra`),kind:`bool`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:3600},{cap:`write_roots`,label:w(`grants.cap.writeRoots.label`),impact:w(`grants.cap.writeRoots.impact`),kind:`dirs`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`read_roots`,label:w(`grants.cap.readRoots.label`),impact:w(`grants.cap.readRoots.impact`),kind:`dirs`,danger:!1,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`net_hosts`,label:w(`grants.cap.netHosts.label`),impact:w(`grants.cap.netHosts.impact`),kind:`hosts`,danger:!1,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`tool_extra`,label:w(`grants.cap.toolExtra.label`),impact:w(`grants.cap.toolExtra.impact`),kind:`tools`,danger:!1,reserved:!0,confirmWord:``,defaultTtl:0,maxTtl:86400},{cap:`unsandboxed`,label:w(`grants.cap.unsandboxed.label`),impact:w(`grants.cap.unsandboxed.impact`),kind:`bool`,danger:!0,confirmWord:``,defaultTtl:0,maxTtl:900}]}function Nv(){return new Map(Mv().map(e=>[e.cap,e]))}function Pv(){return[{sec:0,label:Rv()},{sec:900,label:w(`grants.ttl.min15`)},{sec:1800,label:w(`grants.ttl.min30`)},{sec:3600,label:w(`grants.ttl.hour1`)},{sec:86400,label:w(`grants.ttl.hour24`)}]}function Fv(){return Pv().filter(e=>e.sec>0)}function Iv(e){return e.label}var Lv=1800;function Rv(){return w(`grants.permanent.label`)}function zv(){return w(`grants.permanent.text`)}function Bv(){return w(`grants.permanent.paren`)}function Vv(){return Math.floor(Date.now()/1e3)}function Hv(e){let t=new Date(e*1e3),n=e=>(e<10?`0`:``)+e;return n(t.getHours())+`:`+n(t.getMinutes())}function Uv(e){return!(typeof e==`number`&&e>0)}function Wv(e){return Uv(e)?w(`grants.until.permanent`):w(`grants.until.at`,{time:Hv(e)})}function Gv(e){return Uv(e)?Bv():w(`grants.until.paren`,{time:Hv(e)})}function Kv(e){return e.expired===!0||typeof e.expires_at==`number`&&e.expires_at>0&&e.expires_at<=Vv()}function qv(e){return e&&e.scope&&typeof e.scope==`object`?e.scope:{}}function Z(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e!==``):[]}function Jv(e){let t=[];return e?(e.network===!0&&t.push(`network`),Z(e.read_roots).length&&t.push(`read_roots`),Z(e.write_roots).length&&t.push(`write_roots`),Z(e.net_hosts).length&&t.push(`net_hosts`),Z(e.tool_extra).length&&t.push(`tool_extra`),e.unsandboxed===!0&&t.push(`unsandboxed`),{count:t.length,danger:t.some(e=>jv.has(e)),caps:t}):{count:0,danger:!1,caps:t}}function Yv(e){return new Promise(t=>{let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card confirm-card`);e.title&&r.appendChild(N(`div`,`modal-card-title`,e.title));let i=N(`div`,`confirm-message`);if(i.textContent=e.message,r.appendChild(i),e.note&&r.appendChild(N(`div`,`confirm-note`,e.note)),e.snapshot){r.appendChild(N(`div`,`confirm-snapshot-label`,e.snapshotLabel??w(`shell.confirm.result`)));let t=N(`pre`,`confirm-snapshot`);t.textContent=e.snapshot,r.appendChild(t)}let a=(e.requireText??``).trim(),o=null;if(a!==``){let t=N(`div`,`confirm-word-row`),n=document.createElement(`label`);n.textContent=e.requireHint??w(`shell.confirm.require`,{word:a});let i=N(`input`,`cfg-input`);i.type=`text`,i.autocomplete=`off`,i.spellcheck=!1,t.appendChild(n),t.appendChild(i),r.appendChild(t),r.appendChild(N(`div`,`confirm-word-hint`,w(`shell.confirm.requireHint`))),o=i}let s=N(`div`,`modal-card-actions`),c=N(`button`,`btn `+(e.danger?`btn-danger`:`btn-accent`),e.okLabel??w(`settings.action.confirm`));c.type=`button`;let l=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));l.type=`button`;let u=!1,d=null,f=e=>{u||(u=!0,d&&(F(d),d=null),n.remove(),t(e))};o&&(c.disabled=!0,o.addEventListener(`input`,()=>{c.disabled=o.value.trim()!==a}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&!c.disabled&&(e.preventDefault(),f(!0))})),c.addEventListener(`click`,()=>{o&&o.value.trim()!==a||f(!0)}),l.addEventListener(`click`,()=>f(!1)),n.addEventListener(`click`,e=>{e.target===n&&f(!1)}),s.appendChild(l),s.appendChild(c),r.appendChild(s),n.appendChild(r),document.body.appendChild(n),d=P(()=>f(!1)),o?o.focus():(e.focus===`ok`?c:l).focus()})}var Xv=`unknown`,Zv=0,Qv=null,$v=null,ey=null,ty=``,ny=null,ry=null,iy=null,ay=new Map,oy=new Map,sy=new Map,cy=new Set,ly=null,uy=null;function dy(e){uy=e}function fy(){return uy}function py(){return Xv}function my(e){Xv=e}function hy(){return Zv}function gy(e){Zv=e}function _y(){return Qv}function vy(e){Qv=e}function yy(){return $v}function by(e){$v=e}function xy(){return ey}function Sy(){return ty}function Cy(e,t){ey=e,ty=t}function wy(){return ny}function Ty(e){ny=e}function Ey(){return ry}function Dy(e){ry=e}function Oy(){return ly}function ky(e){ly=e}var Ay=new Map,jy=new Map,My=null;function Ny(){return{granted:Array.from(Ay.values(),e=>e.entry),revoked:new Set(jy.keys()),revokeAll:My!==null}}function Py(e,t){Ay.set(e,{entry:t,settledAt:null}),jy.delete(e)}function Fy(e){let t=Date.now();if(e===null){My!==null&&(My.settledAt=t);return}let n=Ay.get(e);n&&(n.settledAt=t);let r=jy.get(e);r&&(r.settledAt=t)}function Iy(e){Ay.delete(e)}function Ly(e){if(e===null){Ay.clear(),jy.clear(),My={settledAt:null};return}Ay.delete(e),jy.set(e,{settledAt:null})}function Ry(e){if(e===null){My=null,jy.clear();return}jy.delete(e)}function zy(e,t){let n=new Set;for(let t of e)typeof t.cap==`string`&&n.add(t.cap);for(let[e,r]of Array.from(Ay))(n.has(e)||r.settledAt!==null&&r.settledAt<t)&&Ay.delete(e);for(let[e,r]of Array.from(jy))(!n.has(e)||r.settledAt!==null&&r.settledAt<t)&&jy.delete(e);My!==null&&(n.size===0||My.settledAt!==null&&My.settledAt<t)&&(My=null)}function By(){Ay.clear(),jy.clear(),My=null}function Vy(){return iy}function Hy(e){iy=e}function Uy(){let e=Ny();if(e.revokeAll)return[];let t=(xy()?.grants??[]).filter(t=>typeof t.cap==`string`&&!Kv(t)&&!e.revoked.has(t.cap));for(let n of e.granted)typeof n.cap==`string`&&!e.revoked.has(n.cap)&&t.push(n);return t}function Wy(e){let t=Uy().filter(t=>t.cap===e);return t.length?t[t.length-1]:null}function Gy(e){return(xy()?.grants??[]).filter(t=>t.cap===e&&Kv(t))}function Ky(){if(!Uy().length)return w(`grants.phrase.default`);let e=[];for(let t of Mv()){let n=Wy(t.cap);n&&e.push(qy(t,qv(n)))}return e.length?w(`grants.phrase.canNow`)+e.join(w(`grants.copy.listSep`))+w(`grants.phrase.suffix`):w(`grants.phrase.default`)}function qy(e,t){switch(e.cap){case`network`:return w(`grants.phrase.network`);case`write_roots`:return w(`grants.phrase.writeRoots`,{roots:Z(t.roots).join(w(`grants.copy.listSep`))});case`read_roots`:return w(`grants.phrase.readRoots`,{roots:Z(t.roots).join(w(`grants.copy.listSep`))});case`net_hosts`:return w(`grants.phrase.netHosts`,{hosts:Z(t.hosts).join(w(`grants.copy.listSep`))});case`tool_extra`:return w(`grants.phrase.toolExtra`,{tools:Z(t.tools).join(w(`grants.copy.listSep`))});case`unsandboxed`:return w(`grants.phrase.unsandboxed`)}}function Jy(){return w(`grants.copy.listSep`)}function Yy(e,t,n){let r=Wv(n);switch(e.cap){case`network`:return w(`grants.copy.network`,{until:r});case`write_roots`:return w(`grants.copy.writeRoots`,{roots:Z(t.roots).join(Jy()),until:r});case`unsandboxed`:return w(`grants.copy.unsandboxed`,{until:r});case`read_roots`:return w(`grants.copy.readRoots`,{roots:Z(t.roots).join(Jy()),until:r});case`net_hosts`:return w(`grants.copy.netHosts`,{hosts:Z(t.hosts).join(Jy()),until:r});case`tool_extra`:return w(`grants.copy.toolExtra`,{tools:Z(t.tools).join(Jy()),until:r})}}function Xy(e,t){let n=w(`grants.copy.presetHead`,{label:e,n:t.length}),r=t.map(e=>w(`grants.copy.presetBody`,{label:e.def.label,text:Yy(e.def,e.scope,e.expiresAt)})),i=t.every(e=>e.expiresAt===null)?w(`grants.copy.presetTailPermanent`,{permanent:zv()}):w(`grants.copy.presetTailLimited`,{list:t.map(e=>e.def.label+` `+Wv(e.expiresAt)).join(Jy())});return[n,...r,i].join(`
|
|
94
|
+
`)}function Zy(e,t){return w(`grants.copy.previewPrefix`)+qy(e,t)+w(`grants.copy.previewSuffix`)}function Qy(e,t){return w(`grants.copy.successPrefix`)+e.label+Gv(t.grant?.expires_at)}var $y=`studio:grants-changed`,eb=12e4,tb=3,nb=40,rb=new Map,ib=new Map,ab=!1;function ob(e){ab=e}function sb(e){ib.set(e,Date.now())}function cb(e){let t=rb.get(e);return t&&t.count>0?t:null}function lb(){window.dispatchEvent(new Event($y))}function ub(e,t){if(e===``)return;let n=rb.get(e),r=n!==void 0&&n.count===t.count&&n.danger===t.danger&&n.caps.join(`,`)===t.caps.join(`,`);t.count>0?rb.set(e,t):rb.delete(e),r||lb()}function db(e){if(!ab||e.length===0)return;let t=Date.now(),n=[];for(let r of e){if(!r||n.includes(r))continue;let e=ib.get(r);if(!(e!==void 0&&t-e<eb)&&(n.push(r),n.length>=nb))break}if(!n.length)return;let r=0,i=async()=>{for(;;){let e=r++;if(e>=n.length)return;await fb(n[e])}};for(let e=0;e<Math.min(tb,n.length);e++)i()}async function fb(e){sb(e);try{let t=await j.grants(e);if(t.error)return;let n=(t.grants??[]).filter(e=>typeof e.cap==`string`&&!Kv(e)),r=n.map(e=>String(e.cap));ub(e,{count:n.length,danger:r.some(e=>jv.has(e)),caps:r})}catch{}}function pb(){let e=_y();if(!e)return;let t=Uy(),n=t.length,r=t.some(e=>typeof e.expires_at==`number`&&e.expires_at>0&&e.expires_at-Vv()<120);e.classList.toggle(`granted`,n>0),e.classList.toggle(`has-expiring`,n>0&&r);let i=yy();i&&(i.textContent=n>0?String(n):``),e.title=n===0?w(`grants.shield.default`):r?w(`grants.shield.expiring`):w(`grants.shield.granted`,{n}),e.setAttribute(`aria-label`,e.title)}var mb=null;function hb(){let e=wy();if(!e)return;let t=gn(_y());t&&_n(e,t)}function gb(){mb?.();let e=0,t=t=>{let n=t.target,r=wy();r&&n instanceof Node&&r.contains(n)||e===0&&(e=window.requestAnimationFrame(()=>{e=0,hb()}))};window.addEventListener(`resize`,t),document.addEventListener(`scroll`,t,!0),mb=()=>{e!==0&&(window.cancelAnimationFrame(e),e=0),window.removeEventListener(`resize`,t),document.removeEventListener(`scroll`,t,!0)}}function _b(){mb?.(),mb=null}var vb=[`localhost`,`127.0.0.1`];function yb(){return[{id:`read-workspace`,label:w(`grants.preset.readWorkspace.label`),hint:w(`grants.preset.readWorkspace.hint`),ttlSec:0,steps:[{cap:`read_roots`,scopeKind:`dir`}]},{id:`write-output`,label:w(`grants.preset.writeOutput.label`),hint:w(`grants.preset.writeOutput.hint`),ttlSec:0,steps:[{cap:`write_roots`,scopeKind:`dir`}]},{id:`net`,label:w(`grants.preset.net.label`),hint:w(`grants.preset.net.hint`),ttlSec:0,steps:[{cap:`network`,scopeKind:`none`}]},{id:`localhost`,label:w(`grants.preset.localhost.label`),hint:w(`grants.preset.localhost.hint`),ttlSec:0,steps:[{cap:`network`,scopeKind:`none`},{cap:`net_hosts`,scopeKind:`hosts`,hosts:vb}]}]}function bb(e,t){return e.ttlSec<=0?0:!Number.isFinite(t)||t<=0?e.ttlSec:Math.min(e.ttlSec,t)}function xb(e,t){return e.steps.every(e=>{let n=t.find(t=>t.cap===e.cap);if(!n)return!1;if(e.scopeKind!==`hosts`)return!0;let r=n.hosts??[];return(e.hosts??[]).every(e=>r.includes(e))})}function Sb(){let e=[];for(let t of Mv()){let n=Wy(t.cap);n&&e.push({cap:t.cap,hosts:t.kind===`hosts`?Z(qv(n).hosts):[]})}return e}function Cb(e){if(e.ttlSec<=0)return Rv();let t=Pv().find(t=>t.sec===e.ttlSec);return t?w(`grants.quick.ttlPrefix`,{label:Iv(t)}):w(`grants.quick.ttlMinutes`,{n:Math.max(1,Math.round(e.ttlSec/60))})}function wb(e){let t=N(`div`,`grant-presets`),n=N(`div`,`grant-presets-head`);n.appendChild(N(`span`,`grant-presets-title`,w(`grants.quick.title`))),n.appendChild(N(`span`,`grant-presets-ttl-note`,w(`grants.quick.note`))),t.appendChild(n);let r=Oy(),i=Sb();for(let n of yb()){let a=N(`button`,`grant-preset`);a.type=`button`;let o=xb(n,i);a.classList.toggle(`on`,o),a.disabled=r!==null,a.title=n.hint;let s=N(`span`,`grant-preset-top`);s.appendChild(N(`span`,`grant-preset-label`,n.label)),o&&s.appendChild(N(`span`,`grant-preset-tag`,w(`grants.quick.applied`))),s.appendChild(N(`span`,`grant-preset-ttl`,Cb(n))),a.appendChild(s),a.appendChild(N(`span`,`grant-preset-hint`,n.hint)),a.addEventListener(`click`,()=>void Tb(e,n)),t.appendChild(a)}return t}async function Tb(e,t){let n=fy();if(!n){Hy({text:w(`grants.quick.unavailable`),cls:`err`}),e.renderPanel();return}await n(e,t)}function Eb(e){let t=xy()?.max_ttl_sec?.[e.cap];return typeof t==`number`&&t>0?t:e.maxTtl}function Db(e){let t=sy.get(e.cap);return t===void 0?e.defaultTtl:t===0?0:Math.min(t,Eb(e))}function Ob(e){return Math.min(Lv,Eb(e))}function kb(e,t,n){let r={cap:e.cap,scope:t,ttl_sec:n};return e.cap===`unsandboxed`&&(r.uses_left=1),r}function Ab(){let e=Z(xy()?.warnings);if(e.length===0)return null;let t=N(`div`,`grant-preview`);t.appendChild(N(`span`,`grant-preview-label`,w(`grants.warnings.label`)));for(let n of e)t.appendChild(N(`div`,`grant-impact`,n));return t}function jb(){return xy()?.net_hosts_effective===!1}function Mb(e,t){let n=Wy(e.cap),r=Gy(e.cap),i=N(`div`,`grant-row`+(n===null&&r.length?` expired`:``));i.dataset.cap=e.cap;let a=N(`div`,`grant-row-head`);if(a.appendChild(N(`span`,`grant-row-name`,e.label)),a.appendChild(Nb(e,n,r)),e.cap===`net_hosts`&&jb()){let e=N(`span`,`grant-badge`,w(`grants.rows.ineffective`));e.title=w(`grants.rows.ineffectiveTitle`),a.appendChild(e)}if(e.reserved===!0){let e=N(`span`,`grant-badge`,w(`grants.rows.reserved`));e.title=w(`grants.rows.reservedTitle`),a.appendChild(e)}i.appendChild(a),i.appendChild(N(`div`,`grant-impact`,e.impact)),e.extra&&i.appendChild(N(`div`,`grant-impact`,e.extra));let o=qv(n),s=Z(o.roots).concat(Z(o.hosts),Z(o.tools));n&&s.length&&i.appendChild(N(`div`,`grant-detail`,Fb(e,n,s)));for(let t of r){let n=Z(qv(t).roots).concat(Z(qv(t).hosts),Z(qv(t).tools));i.appendChild(N(`div`,`grant-detail`,w(`grants.rows.expiredPrefix`,{what:n.length?n.join(w(`grants.copy.listSep`)):e.label})))}if((e.kind===`hosts`||e.kind===`tools`)&&!n&&e.reserved!==!0){let t=N(`div`,`grant-hosts-row`),n=N(`input`,`grant-input cfg-input`);n.type=`text`,n.spellcheck=!1,n.placeholder=e.kind===`hosts`?w(`grants.rows.hostPlaceholder`):w(`grants.rows.toolPlaceholder`),n.value=oy.get(e.cap)??``,n.addEventListener(`input`,()=>{oy.set(e.cap,n.value),ay.delete(e.cap);let t=i.querySelector(`.grant-err`);t&&t.remove()}),t.appendChild(n),i.appendChild(t)}let c=N(`div`,`grant-row-actions`);if(n){let n=N(`button`,`btn-mini`,w(`grants.rows.revoke`));n.type=`button`,n.addEventListener(`click`,()=>void t.revoke(e.cap)),c.appendChild(n)}else if(e.reserved!==!0){let n=N(`button`,`btn-mini`+(e.danger?` grant-danger-btn`:``),e.kind===`dirs`?w(`grants.rows.chooseDir`):w(`grants.rows.grant`));n.type=`button`,n.title=w(`grants.rows.grantTitle`,{permanent:zv()}),n.addEventListener(`click`,()=>{sy.set(e.cap,0),t.startGrant(e)}),c.appendChild(n),c.appendChild(Ib(e,t)),e.cap===`unsandboxed`&&c.appendChild(N(`span`,`grant-impact`,w(`grants.rows.onceOnly`,{permanent:zv()})))}i.appendChild(c),!n&&cy.has(e.cap)&&i.appendChild(Lb(e,t));let l=ay.get(e.cap);return l&&i.appendChild(N(`div`,`grant-err`,l)),i}function Nb(e,t,n){return t?N(`span`,`grant-badge on`,Pb(e,t)):n.length?N(`span`,`grant-badge expired`,w(`grants.rows.expired`)):N(`span`,`grant-badge`,w(`grants.rows.notGranted`))}function Pb(e,t){if(e.kind===`hosts`||e.kind===`tools`){let n=Z(qv(t)[e.kind===`hosts`?`hosts`:`tools`]).length;return w(`grants.rows.grantedCount`,{n:n||1})}return Uv(t.expires_at)?w(`grants.rows.grantedPermanent`,{permanent:Rv()}):w(`grants.rows.grantedUntil`,{time:Hv(t.expires_at)})}function Fb(e,t,n){let r=Gv(t.expires_at);switch(e.cap){case`write_roots`:return w(`grants.rows.detailWrite`,{values:n.join(w(`grants.copy.listSep`)),exp:r});case`read_roots`:return w(`grants.rows.detailRead`,{values:n.join(w(`grants.copy.listSep`)),exp:r});case`net_hosts`:return n.join(`、`)+r;case`tool_extra`:return n.join(`、`)+r;default:return n.join(`、`)+r}}function Ib(e,t){let n=cy.has(e.cap),r=N(`button`,`btn-mini`,w(n?`grants.rows.tempCollapse`:`grants.rows.tempOpen`));return r.type=`button`,r.addEventListener(`click`,()=>{n?cy.delete(e.cap):cy.add(e.cap),t.renderPanel()}),r}function Lb(e,t){let n=N(`div`,`grant-temp`);n.appendChild(N(`div`,`grant-impact`,w(`grants.rows.tempNote`)));let r=N(`div`,`grant-hosts-row`);r.appendChild(Rb(e));let i=N(`button`,`btn-mini`,w(`grants.rows.tempGrant`));return i.type=`button`,i.addEventListener(`click`,()=>void t.startGrant(e)),r.appendChild(i),n.appendChild(r),n}function Rb(e){let t=Eb(e),n=document.createElement(`select`);n.className=`cfg-input grant-ttl`;let r=sy.get(e.cap),i=r!==void 0&&r>0?r:Ob(e),a=!1;for(let e of Fv()){if(e.sec>t)continue;let r=document.createElement(`option`);r.value=String(e.sec),r.textContent=e.label,e.sec===i&&(a=!0),n.appendChild(r)}if(a)n.value=String(i);else{let e=Math.max(1,Math.min(i,t)),r=document.createElement(`option`);r.value=String(e),r.textContent=w(`grants.rows.minutes`,{n:Math.max(1,Math.round(e/60))}),n.appendChild(r),n.value=String(e)}return n.addEventListener(`change`,()=>sy.set(e.cap,Number(n.value))),n}function zb(){_b();let e=Ey();e&&(F(e),Dy(null));let t=wy();t&&(t.remove(),Ty(null))}function Bb(e){if(wy()){zb();return}Vb(e)}async function Vb(e){zb(),ay.clear(),Hy(null);let t=document.getElementById(`statusline`);if(!t)return;let n=N(`div`,`sl-popup grant-popup`);n.setAttribute(`role`,`dialog`),Ty(n),t.appendChild(n),Dy(P(()=>zb())),n.appendChild(N(`div`,`sl-popup-title`,w(`grants.body.title`)));let r=N(`div`,`sl-popup-body`);if(n.appendChild(r),e.focusedSession()===``){r.replaceChildren(N(`div`,`sl-popup-note`,w(`grants.body.noSession`))),hb(),gb();return}let i=xy()!==null&&Sy()===e.focusedSession();i||n.classList.add(`hidden`),i&&Hb(e),gb(),await e.refresh(!0),wy()===n&&(n.classList.remove(`hidden`),Hb(e))}function Hb(e){let t=wy();if(!t)return;let n=t.querySelector(`.sl-popup-body`);if(!n)return;let r=document.createElement(`div`);r.appendChild(wb(e)),r.appendChild(N(`div`,`grant-intro`,w(`grants.body.introDefault`))),r.appendChild(N(`div`,`grant-intro`,w(`grants.body.introScope`)));let i=Ab();i&&r.appendChild(i);let a=N(`div`,`grant-preview`);if(a.appendChild(N(`span`,`grant-preview-label`,w(`grants.body.previewLabel`))),a.appendChild(N(`span`,null,Ky())),r.appendChild(a),xy()===null)r.appendChild(N(`div`,`sl-popup-note`,w(`grants.body.unreadable`)));else for(let t of Mv())(t.cap!==`unsandboxed`||xy()?.unsandboxed_available===!0)&&(t.reserved!==!0||Wy(t.cap)!==null||Gy(t.cap).length!==0)&&r.appendChild(Mb(t,e));let o=N(`div`,`grant-foot`);o.appendChild(N(`div`,`grant-foot-note`,w(`grants.body.footNote`)));let s=N(`button`,`btn-mini grant-danger-btn`,w(`grants.body.revokeAll`));s.type=`button`,s.disabled=Uy().length===0,s.addEventListener(`click`,()=>void e.revoke(null)),o.appendChild(s),r.appendChild(o);let c=Vy();c&&r.appendChild(N(`div`,`sl-popup-status `+c.cls,c.text)),n.replaceChildren(...r.childNodes),hb()}function Ub(e){return/sk-/.test(e)||/Bearer\s/.test(e)||e.includes(`
|
|
95
|
+
`)||e.length>200}var Wb=/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;function Gb(e){let[t,n]=e.split(`/`);if(n!==void 0&&!/^\d{1,2}$/.test(n)||n!==void 0&&Number(n)>32)return!1;let r=(t??``).split(`.`);return r.length===4&&r.every(e=>/^\d{1,3}$/.test(e)&&Number(e)<=255)}function Kb(e){let[t,n]=e.split(`/`);return n!==void 0&&(!/^\d{1,3}$/.test(n)||Number(n)>128)||!t||!t.includes(`:`)?!1:/^[0-9a-fA-F:.]+$/.test(t)}function qb(e){return e.length>253?!1:Gb(e)||Kb(e)?!0:Wb.test(e)}function Jb(e){return e.split(/[\s,,;;]+/).map(e=>e.trim()).filter(e=>e!==``)}function Yb(e){let t=Jb(e);if(!t.length)return{values:[],error:w(`grants.scope.needHost`)};let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(Ub(r))return{values:[],error:w(`grants.scope.hostCred`,{n:e+1})};if(!qb(r))return{values:[],error:w(`grants.scope.hostInvalid`,{n:e+1})};n.push(r)}return{values:Array.from(new Set(n)),error:``}}var Xb=/^[a-zA-Z0-9_.:-]{1,64}$/;function Zb(e){let t=Jb(e);if(!t.length)return{values:[],error:w(`grants.scope.needTool`)};let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(Ub(r))return{values:[],error:w(`grants.scope.toolCred`,{n:e+1})};if(!Xb.test(r))return{values:[],error:w(`grants.scope.toolInvalid`,{n:e+1})};n.push(r)}return{values:Array.from(new Set(n)),error:``}}function Qb(e){pb(),e.renderPanel()}async function $b(e,t){let n=e.focusedSession();if(n===``)return;ay.delete(t.cap);let r={};if(t.kind===`dirs`){let e=await Km(w(`grants.flow.chooseDir`),w(`grants.flow.chooseDirNote`,{permanent:zv()}));if(e===null||e.trim()===``)return;r={roots:[e.trim()]}}else if(t.kind===`hosts`){let n=Yb(oy.get(t.cap)??``);if(n.error!==``){ay.set(t.cap,n.error),e.renderPanel();return}r={hosts:n.values}}else if(t.kind===`tools`){let n=Zb(oy.get(t.cap)??``);if(n.error!==``){ay.set(t.cap,n.error),e.renderPanel();return}r={tools:n.values}}let i=Db(t),a=i===0?null:Vv()+i;if(await Yv({title:w(`grants.flow.confirmTitle`,{label:t.label}),message:Yy(t,r,a),note:Zy(t,r)+`
|
|
96
|
+
`+w(`grants.flow.effectiveNote`),snapshot:JSON.stringify(xy()?.effective??{},null,2),snapshotLabel:w(`grants.flow.snapshotLabel`),okLabel:w(`grants.rows.grant`),danger:!0})){Py(t.cap,{cap:t.cap,scope:r,expires_at:a}),Qb(e);try{let a=await nx(n,t,kb(t,r,i),r);if(a===null){Iy(t.cap),Hy({text:w(`grants.flow.grantFailed`,{reason:O(void 0,w(`settings.common.retryLater`))}),cls:`err`}),Qb(e);return}oy.delete(t.cap),Fy(t.cap),Hy({text:Qy(t,a),cls:`busy`}),X(Qy(t,a),`ok`,6e3),a.effective&&ub(n,Jv(a.effective)),await e.refresh(!0)}catch(n){Iy(t.cap);let r=w(`grants.flow.grantFailed`,{reason:O(n,w(`settings.common.retryLater`))});Hy({text:r,cls:`err`}),X(r,`err`,8e3),Qb(e)}}}async function ex(e,t){let n=e.focusedSession();if(n===``||Oy()!==null)return;ay.clear();let r=[];for(let n of t.steps){let i=await tx(t,n);if(i===null){e.renderPanel();return}r.push(i)}if(r.length===0)return;let i=Vv(),a=r.map(e=>({def:e.def,scope:e.scope,expiresAt:e.ttl===0?null:i+e.ttl}));if(!await Yv({title:w(`grants.flow.confirmPresetTitle`,{label:t.label}),message:Xy(t.label,a),note:w(`grants.flow.presetNote`,{list:r.map(e=>qy(e.def,e.scope)).join(w(`grants.copy.listSep`))})+`
|
|
97
|
+
`+w(`grants.flow.effectiveNote`),snapshot:JSON.stringify(xy()?.effective??{},null,2),snapshotLabel:w(`grants.flow.snapshotLabel`),okLabel:w(`grants.rows.grant`),danger:!0}))return;for(let e of r)Py(e.def.cap,{cap:e.def.cap,scope:e.scope,expires_at:e.ttl===0?null:Vv()+e.ttl});ky({id:t.id,index:0,total:r.length}),Qb(e);let o=[];for(let i=0;i<r.length;i++){let a=r[i];ky({id:t.id,index:i,total:r.length});try{let e=await nx(n,a.def,kb(a.def,a.scope,a.ttl),a.scope);e?.effective&&ub(n,Jv(e.effective)),Fy(a.def.cap),o.push(a.def.label)}catch(t){Iy(a.def.cap),ky(null);let n=O(t,w(`settings.common.retryLater`)),r=w(`grants.flow.presetInterrupted`,{label:a.def.label,reason:n,done:o.length>0?w(`grants.flow.presetDone`,{list:o.join(w(`grants.copy.listSep`))}):w(`grants.flow.presetNoGrant`)});Hy({text:r,cls:`err`}),X(r,`err`,1e4),Qb(e),await e.refresh(!0);return}}ky(null);let s=w(`grants.flow.presetComplete`,{list:o.join(w(`grants.copy.listSep`))});Hy({text:s,cls:`busy`}),X(s,`ok`,6e3),await e.refresh(!0)}async function tx(e,t){let n=Nv().get(t.cap);if(!n)return Hy({text:w(`grants.flow.presetUnavailable`),cls:`err`}),null;let r={};if(t.scopeKind===`dir`){let t=await Km(w(`grants.flow.chooseDirPreset`,{label:e.label}),w(`grants.flow.chooseDirPresetNote`,{permanent:zv()}));if(t===null||t.trim()===``)return Hy({text:w(`grants.flow.presetNoDir`),cls:`err`}),null;r={roots:[t.trim()]}}else if(t.scopeKind===`hosts`){let e=oy.get(t.cap)??``,i=Yb(e.trim()===``?(t.hosts??[]).join(`, `):e);if(i.error!==``)return ay.set(t.cap,i.error),Hy({text:w(`grants.flow.presetBadHosts`,{label:n.label}),cls:`err`}),null;r={hosts:i.values}}return{def:n,scope:r,ttl:bb(e,Eb(n))}}async function nx(e,t,n,r){let i=await Tv(t.cap,r);for(let r=0;r<2;r++){let a=await j.grantToken(e,t.cap,i);if(!a.token)throw new D(O(a.error,w(`grants.flow.cannotStart`)));try{let t=await j.grantCap(e,n,a.token);if(t.ok===!1)throw new D(O(t.error,w(`grants.flow.grantFailedRetry`)));return{effective:t.effective,grant:t.grant}}catch(e){if(e instanceof D&&(e.status===403||e.status===409)&&r===0)continue;throw e}}return null}dy((e,t)=>ex(e,t));async function rx(e,t){let n=e.focusedSession();if(n===``)return;let r=t?Nv().get(t):void 0;Ly(t),Qb(e);try{let i=await j.revokeCap(n,t?{cap:t}:{});Fy(t);let a=(i.revoked??[]).length,o=t&&r?w(`grants.flow.revokedOne`,{label:r.label}):a>1?w(`grants.flow.revokedMany`,{n:a}):w(`grants.flow.revoked`);Hy({text:o,cls:`busy`}),X(o,`ok`,6e3),i.effective&&ub(n,Jv(i.effective)),await e.refresh(!0)}catch(n){Ry(t);let r=w(`grants.flow.revokeFailed`,{reason:O(n,w(`settings.common.retryLater`))});Hy({text:r,cls:`err`}),X(r,`err`,8e3),Qb(e)}}var ix=2e4,ax=null,ox=!1,sx={refresh:e=>dx(e),focusedSession:()=>ux(),renderPanel:()=>Hb(sx),startGrant:e=>$b(sx,e),revoke:e=>rx(sx,e)};function cx(e){let t=e?`on`:`off`;if(py()===t)return;my(t),ob(e);let n=_y();n&&n.classList.toggle(`hidden`,!e),e?(fx(),dx(!0)):(zb(),px())}async function lx(e=!1){let t=Date.now();if(!(!e&&py()!==`unknown`&&t-hy()<6e4)){gy(t);try{cx((await j.health()).capabilities?.grants===!0)}catch{cx(!1)}}}function ux(){let e=jr();return e===``?R.selSession??``:e}async function dx(e=!1){if(py()!==`on`)return;let t=ux();if(t===``){Cy(null,``),pb(),wy()&&Hb(sx);return}if(!e&&wy()===null&&t===Sy()&&xy()!==null){pb();return}let n=t,r=Date.now();try{let e=await j.grants(n);if(n!==ux())return;Cy(e,n),zy(e.grants??[],r),sb(n);let t=(e.grants??[]).filter(e=>typeof e.cap==`string`&&!Kv(e)),i=t.map(e=>String(e.cap));ub(n,{count:t.length,danger:i.some(e=>jv.has(e)),caps:i})}catch(e){if(n!==ux()||e instanceof D&&e.status===0)return;Cy(null,n)}pb(),wy()&&Hb(sx)}function fx(){ax===null&&(ax=window.setInterval(()=>{dx(!0)},ix))}function px(){ax!==null&&(window.clearInterval(ax),ax=null)}function mx(){if(ox)return;ox=!0,vy(document.getElementById(`slGrant`)),by(document.getElementById(`slGrantBadge`));let e=_y();e&&e.addEventListener(`click`,e=>{e.stopPropagation(),Bb(sx)}),document.addEventListener(`click`,t=>{let n=wy();if(!n)return;let r=t.target;(typeof t.composedPath==`function`?t.composedPath():[]).some(e=>e===n)||n.contains(r)||e&&e.contains(r)||zb()}),Br(()=>{ay.clear(),Hy(null),By(),py()===`on`&&dx(!0)}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&dx(!0)}),lx(!0),window.setInterval(()=>{py()===`off`&&lx(!0)},6e4)}var hx=`hint-text-card`;function gx(e,t){let n=N(`div`,`hint-card-text`),r=(e.getAttribute(`data-hint-tag`)??``).trim();return r&&n.appendChild(N(`span`,`hint-card-tag`,r)),n.appendChild(N(`span`,`hint-card-body`,t)),n}function _x(){return{id:hx,priority:0,claim(e,t){return t?{build:()=>gx(e,t)}:null}}}function vx(){return[{id:hx,label:w(`plugins.desc.textCard.label`),hint:w(`plugins.desc.textCard.hint`),hot:!0,create:()=>_x()},{id:ha,label:w(`plugins.desc.railPreview.label`),hint:w(`plugins.desc.railPreview.hint`),hot:!0,create:()=>Ha()}]}function yx(){return vx().map(e=>e.id)}function bx(e){return vx().find(t=>t.id===e)??null}function xx(){for(let e of vx())Wi(e.create())}function Sx(e){return Ui(e)}function Cx(e,t){let n=bx(e);if(n===null)return{ok:!1,text:w(`plugins.notFound`)};try{t?Gi(e):Ki(e)}catch(r){return wx(e,!t),console.warn(`[plugins] 切换失败:`+(r instanceof Error?r.message:String(r))),{ok:!1,text:w(`plugins.toggleFailed`,{label:n.label})}}return Ri(e,!t,yx()),{ok:!0,text:w(`plugins.toggled`,{state:w(t?`plugins.on`:`plugins.off`),label:n.label})}}function wx(e,t){try{t?Gi(e):Ki(e)}catch(e){console.warn(`[plugins] 回滚失败:`+(e instanceof Error?e.message:String(e)))}}function Tx(){Ai(),xx()}function Ex(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`viewBox`,`0 0 16 16`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`1.3`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`);let r=document.createElementNS(t,`path`);switch(e){case`folder`:r.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v7a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z`);break;case`file`:r.setAttribute(`d`,`M3 1.5h6l4 4v9h-10zM9 1.5v4h4`);break;case`search`:r.setAttribute(`d`,`M6.5 11.5a5 5 0 1 1 0-10 5 5 0 0 1 0 10zM14.5 14.5l-3.8-3.8`);break;case`sort`:r.setAttribute(`d`,`M2 4h12M5 8h7M8 12h4`);break;case`folder-plus`:r.setAttribute(`d`,`M1.5 3.5h4l1.5 2h7.5v4M1.5 3.5v8a1 1 0 0 0 1 1h5.5M11 9v5M8.5 11.5h5`);break;case`plus`:r.setAttribute(`d`,`M8 3v10M3 8h10`)}return n.appendChild(r),n}function Dx(){let e=`http://www.w3.org/2000/svg`,t=document.createElementNS(e,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`width`,`10`),t.setAttribute(`height`,`10`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(e,`path`);return n.setAttribute(`d`,`M8 1.6 13.2 3.4v4.2c0 3.1-2.1 5.6-5.2 6.8-3.1-1.2-5.2-3.7-5.2-6.8V3.4z`),t.appendChild(n),t}function Q(e){let t=document.getElementById(`sideFoot`);t&&(t.textContent=e)}function Ox(e){let t=jr()||Ug();for(let n of e.querySelectorAll(`.sess-leaf`))n.classList.toggle(`active`,n.dataset.id===t)}function kx(e){for(let t of e.querySelectorAll(`.sess-dot[data-dot]`)){let e=Fr(t.dataset.dot??``);t.classList.toggle(`busy`,e),bi(t,w(e?`shell.tree.running`:`shell.tree.idle`))}for(let t of e.querySelectorAll(`.ws-worker-row`)){let e=Fr(t.dataset.id??``);t.classList.toggle(`running`,e);let n=t.querySelector(`.ws-worker-state`);n&&(n.textContent=w(e?`shell.tree.running`:`shell.tree.idle`),n.classList.toggle(`busy`,e))}}function Ax(e,t){if(!t||t.count<=0){e.classList.add(`hidden`),e.replaceChildren(),e.title=``;return}e.classList.remove(`hidden`),e.classList.toggle(`danger`,t.danger),e.title=t.danger?w(`shell.tree.grantDanger`,{n:t.count}):w(`shell.tree.grantRelaxed`,{n:t.count}),e.firstChild||e.appendChild(Dx())}function jx(e){for(let t of e.querySelectorAll(`.sess-leaf-grant[data-grant-mark]`))Ax(t,cb(t.dataset.grantMark??``))}var Mx=null,Nx=null,Px=null,Fx=null,Ix=`\0`;function Lx(e){let t=(e.title??``).trim();if(t)return t;if(e.id===``)return w(`shell.sessbar.unresolved`);let n=e.id.lastIndexOf(`/`);return n>=0?e.id.slice(n+1):e.id}function Rx(){let e=M(`#sessionBar`);Mx=N(`span`,`sess-bar-name`,`—`),Nx=N(`span`,`sess-bar-kind hidden`,`WORKER`),Px=N(`span`,`sess-bar-state`,w(`shell.sessbar.idle`)),Fx=N(`span`,`sess-bar-others`);let t=N(`span`,`sess-bar-lead`,w(`shell.sessbar.session`));e.replaceChildren(t,Nx,Mx,Px,Fx)}function zx(){let e=B();if(!Mx||!Px||!Nx||!Fx)return;if(!e){Mx.textContent=`—`,Px.textContent=w(`shell.sessbar.idle`),Px.className=`sess-bar-state`,Nx.classList.add(`hidden`),Fx.replaceChildren(),Ix=`\0`;return}let t=e.streaming||Fr(e.id);Mx.textContent=Lx(e),Mx.title=e.id||w(`shell.sessbar.unresolvedShort`),Nx.classList.toggle(`hidden`,e.kind!==`worker`),Px.textContent=t?e.streaming?``:w(`shell.sessbar.background`):w(`shell.sessbar.idle`),Px.className=`sess-bar-state`+(t?` busy`:``);let n=Cr().filter(t=>t!==e&&(t.streaming||Fr(t.id))),r=n.map(e=>e.id).join(`|`);if(r===Ix)return;if(Ix=r,!n.length){Fx.replaceChildren();return}let i=document.createDocumentFragment();i.appendChild(N(`span`,`sess-bar-sep`,`·`)),i.appendChild(N(`span`,`sess-bar-note`,w(`shell.sessbar.others`,{n:n.length})));for(let e of n){let t=N(`button`,`sess-bar-chip`,Lx(e));t.type=`button`,t.title=w(`shell.sessbar.switchTo`,{name:e.id||w(`shell.sessbar.thatSession`)}),t.addEventListener(`click`,()=>{sm(e.id,{kind:e.kind,title:e.title})}),i.appendChild(t)}Fx.replaceChildren(...Array.from(i.childNodes))}function Bx(e,t=`steer`){let n=e.trim(),r=B();if(!r)return;let i=Xd();if(n!==``||i!==0){if(b_(n)){R_(),r.draft=``,d_(n,r);return}if(r.kind===`worker`){Hx(r,n,t);return}if(r.streaming&&i>0){let e=w(`chat.send.busyWithAttachments`);X(e,`err`,6e3),Q(e);return}if(r.draft=``,r.streaming){Wx(r,n,t);return}Vx(r,n)}}function Vx(e,t){let n=e.id,r=Qd(n),i=Gh(n),a=ff(e,t,{attachments:af(r),quotes:i});R_(),Nh(),xv(e),Rr(e,!0),e.turn=null,e.t0=Date.now(),e.phase=w(`chat.send.starting`),wh(e),V(e)&&(R.t0=e.t0,B_(!0),Y(w(`chat.send.starting`),`busy`),sv()),zx(),ud(r).then(()=>nf(r)).then(n=>j.turn(dd(Yf(t,i),r),fv(e),void 0,n)).then(t=>{t.session&&Pr(t.session),e.turn===null&&t.turn!==void 0&&(e.turn=t.turn),e.phase=w(`chat.send.running`),V(e)&&(av(e.turn===null?t.turn??0:e.turn),Y(w(`chat.send.running`),`busy`))}).catch(o=>Ux({ctx:e,key:n,col:a,text:t,items:r,quotes:i,err:o}))}async function Hx(e,t,n){if(t===``)return;if(Xd()>0){let t=w(`chat.send.workerNoImages`);V(e)&&X(t,`err`,6e3),gf(e,t,`warn`);return}let r=Gh(e.id),i=ff(e,t,{kind:n===`queue`?`queued`:`user`,quotes:r});R_(),e.draft=``;let a=vf(e,w(`chat.send.delivering`),void 0,i);xv(e);try{let n=await j.turn(Yf(t,r),fv(e)),i=n.status!==void 0&&n.status!==``&&n.status!==`RUNNING`;a.textContent=i?w(`chat.send.workerSettled`,{status:n.status??``}):w(`chat.send.workerDelivered`),a.className=`interject-note ok`,V(e)&&X(w(i?`chat.send.workerSettledShort`:`chat.send.workerDeliveredShort`),`ok`,4e3)}catch(n){i.remove(),a.parentElement?.remove(),e.interjectNote=null,r.length>0&&Kh(e.id,r),Gx(e,t);let o=w(`chat.send.notDelivered`,{reason:pv(n)});V(e)&&(Y(o,`err`),window.setTimeout(()=>X(o,`err`,6e3),0)),gf(e,o,`warn`)}}function Ux(e){let{ctx:t,key:n,col:r,text:i,items:a,quotes:o,err:s}=e;Rr(t,!1),t.phase=w(`chat.send.failedPrefix`).replace(/[:: ]+$/,``),bv()===t&&xv(null);let c=a.length>0||o.length>0;c&&(r.remove(),a.length>0&&$d(n,a),o.length>0&&Kh(n,o),Gx(t,i),Nh(),Uh());let l=w(`chat.send.failedPrefix`)+pv(s)+(c?w(`chat.send.failedRolledSuffix`):``);V(t)&&(B_(!1),cv(),Y(l,`err`),window.setTimeout(()=>X(l,`err`,6e3),0)),gf(t,l,c?`warn`:`err`),c&&Q(l),zx()}async function Wx(e,t,n){let r=Gh(e.id),i=Yf(t,r),a=ff(e,t,{kind:n===`queue`?`queued`:`steering`,quotes:r});R_(),Nh(),e.draft=``;let o=w(n===`queue`?`chat.send.queuedWaiting`:`chat.send.interjectedWaiting`),s=w(n===`queue`?`chat.send.queuedDone`:`chat.send.interjectedDone`),c=vf(e,o,void 0,a);xv(e),V(e)&&X(w(n===`queue`?`chat.send.queuedShort`:`chat.send.interjectedShort`),`busy`,4e3);let l=e=>{c.textContent=e,c.className=`interject-note ok`};try{let t=await j.turn(i,fv(e),n);if(t.placement===`queued`){l(s);return}if(t.placement===`steering`){l(w(`chat.send.interjectedDone`));return}if(t.placement===void 0){if(t.injected===!0){l(w(`chat.send.interjectedDone`));return}if(t.queued===!0||n===`queue`){l(s);return}}e.turn=t.turn??e.turn,Rr(e,!0),e.phase=w(`chat.send.running`),l(w(`chat.send.asNewTurn`)),zx()}catch(o){if(n===`queue`)try{let t=await j.turn(i,fv(e),`steer`);if(t.injected!==!1){let e=hf(t.inbox_target??`next-step`);l(w(`chat.send.queueUnsupported`,{lane:e?w(`chat.send.laneSuffix`,{lane:e}):``}));return}}catch{}a.remove(),c.parentElement?.remove(),e.interjectNote=null,r.length>0&&Kh(e.id,r),Gx(e,t);let s=w(n===`queue`?`chat.send.queueNotDelivered`:`chat.send.steerNotDelivered`,{reason:pv(o)});V(e)&&(Y(s,`err`),window.setTimeout(()=>X(s,`err`,6e3),0)),gf(e,s,`warn`)}}function Gx(e,t){if(e.draft=t,!V(e))return;let n=document.querySelector(`#input`);n&&n.value.trim()===``&&z_(t)}var Kx=`.msg.info.downgrade`;function qx(e){let t=e.cause;return[e.model??``,typeof t==`string`?t:``,e.message??``].join(`\0`)}function Jx(e){return e.el.querySelector(Kx)}function Yx(e,t){let n=Pd(t),r=n.split(`
|
|
98
|
+
`)[0]??n,i=qx(t),a=Jx(e);if(a){if(_f(a,n),a.dataset.downgradeSig===i)return;a.dataset.downgradeSig=i}else{let t=gf(e,n,`err`,`downgrade`);if(t===null)return;t.dataset.downgradeSig=i}V(e)&&X(r,`err`,6e3)}function Xx(){return{cancelled:w(`chat.phase.cancelled`),error:w(`chat.phase.error`)}}function Zx(e){let t=typeof e.session==`string`&&e.session!==``?e.session:null;return t===null?bv()??B()??wr(``):Pr(t)||(Sr(t)??wr(t))}function Qx(e,t){let n=Qe({...t.statusline??{},...t});Object.keys(n).length>0&&(e.status={...e.status??{},...n})}function $x(e){V_(e.kind===`worker`?`worker`:e.streaming?`interject`:`idle`)}function eS(e){R.t0=e.t0,R.turn=e.turn,R.assistant=e.assistant,av(e.turn),B_(e.streaming),$x(e),ci.setSession(e.id),e.streaming?(sv(),Y(e.phase||w(`chat.phase.running`),`busy`)):(cv(),e.phase?Y(e.phase,e.phase===Xx().error||e.phase===Xx().cancelled?`err`:`ok`):R.conn===`online`?Y(w(`shell.status.online`),`ok`):R.conn===`down`&&Y(w(`shell.status.reconnecting`),`err`)),zx()}function tS(e,t){kf(e);let n=e.streaming;Rr(e,!1),e.turn=null,e.phase=Xx()[t]??``;let r=e.assistant;r&&(ku(r)?zu(e,r):Au(e,r)),e.assistant=null,bv()===e&&xv(null),V(e)&&(R.turn=null,R.assistant=null,B_(!1),lv(),e.phase===``?Y(R.conn===`down`?w(`shell.status.reconnecting`):w(`shell.status.online`),R.conn===`down`?`err`:`ok`):Y(e.phase,t===`error`||t===`cancelled`?`err`:`ok`)),n&&W(e,!0),zx()}function nS(e,t){if(Nd(t)){Yx(e,t);return}if(t.phase===`start`){V(e)&&dv(),kf(e),e.streaming&&e.assistant&&(ku(e.assistant)?tS(e,`completed`):Au(e,e.assistant)),e.turn=t.turn??null,e.t0=Date.now(),e.phase=w(`chat.phase.running`),Rr(e,!0),wh(e),V(e)&&(R.t0=e.t0,B_(!0),Y(w(`chat.phase.running`),`busy`),av(e.turn),sv()),zx();return}(t.turn===void 0||t.turn===null||e.turn===null||t.turn===e.turn)&&((t.phase===`completed`||t.phase===`cancelled`||t.phase===`error`)&&(tS(e,t.phase||``),t.phase===`error`&&gf(e,w(`chat.status.turnError`,{reason:t.error||w(`chat.status.unknownError`)}),`err`)),t.phase===`lagged`&&gf(e,w(`chat.status.lagged`),`warn`),t.hint&&gf(e,String(t.hint),`warn`))}function rS(e,t){if(e.turn===null&&(e.turn=t.turn??null),t.turn!==void 0&&t.turn!==e.turn)return;e.streaming===!1&&Rr(e,!0);let n=Kp(e,t.delta||``);n!==null&&(Fu(e,Ru(e),n),V(e)&&av(e.turn))}function iS(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||t.turn===e.turn)&&jf(e,t.delta||``)}function aS(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||e.turn===null||t.turn===e.turn)&&(Af(e),Lu(e),kh(e,t),W(e))}function oS(e,t){e.turn===null&&(e.turn=t.turn??null),(t.turn===void 0||e.turn===null||t.turn===e.turn)&&(jh(e,t),W(e))}function sS(e,t){if(e.turn===null&&(e.turn=t.turn??null),t.turn!==void 0&&e.turn!==null&&t.turn!==e.turn)return;if(Af(e),e.assistant===null&&typeof t.text==`string`&&t.text!==``){if(qp(e,t.text))return;Iu(e,Ru(e),t.text),W(e);return}let n=e.assistant;if(n){if(qp(e,t.text)){n.root.remove(),e.assistant=null;return}typeof t.text==`string`&&Iu(e,n,t.text),W(e)}}function cS(){let e=new he;return e.onConn(e=>{R.conn=e,e===`online`?Y(R.streaming?w(`chat.phase.running`):w(`shell.status.online`),R.streaming?`busy`:`ok`):e===`down`&&Y(w(`shell.status.reconnecting`),`err`)}),e.on(`status`,e=>{try{let t=Zx(e);V(t)?(ci.fromSse(e),e.session&&t.status&&(t.status={...t.status,...Qe(e)})):Qx(t,e),nS(t,e)}catch(e){console.warn(`SSE status`,e)}}),e.on(`text`,e=>{try{rS(Zx(e),e)}catch(e){console.warn(`SSE text`,e)}}),e.on(`thinking`,e=>{try{iS(Zx(e),e)}catch(e){console.warn(`SSE thinking`,e)}}),e.on(`tool`,e=>{try{aS(Zx(e),e)}catch(e){console.warn(`SSE tool`,e)}}),e.on(`tool_result`,e=>{try{oS(Zx(e),e)}catch(e){console.warn(`SSE tool_result`,e)}}),e.on(`done`,e=>{try{ci.onSseDone(),sS(Zx(e),e)}catch(e){console.warn(`SSE done`,e)}}),e.on(`context`,e=>{try{gf(Zx(e),e.text||w(`chat.status.contextEvent`),e.cls===`err`?`err`:e.cls===`warn`?`warn`:void 0)}catch(e){console.warn(`SSE context`,e)}}),e.on(`compact`,e=>{try{_v(e)}catch(e){console.warn(`SSE compact`,e)}}),e.on(`inbox`,e=>{try{uS(Zx(e),e)}catch(e){console.warn(`SSE inbox`,e)}}),Wp(e,Zx),e.connect(),e}function lS(){let e=B();e&&e.streaming&&(Y(w(`chat.status.cancelling`),`busy`),j.cancel(fv(e)).catch(e=>{Y(w(`chat.status.cancelFailed`,{reason:pv(e)}),`err`)}))}function uS(e,t){let n=(t.text??t.note??t.hint??``).trim();n!==``&&mf(e,n,{source:t.source,target:t.target})}function dS(){L_({send(e,t){Bx(e,t)},cancel:lS}),Br(e=>{no(e),so(e),eS(e),Nh(),q_(),Cm(null,e)}),Vr(e=>{zx();let t=B();t&&(t.id===e||t.id===``&&e===``)&&($x(t),B_(t.streaming)),Cm(null,t)})}var fS=M(`#settingsTools`),pS=M(`#toolsCount`);function mS(e,t){let n=e??[];if(pS.textContent=String(n.length),t.replaceChildren(),!n.length){t.appendChild(N(`div`,`side-note`,w(`settings.tools.empty`)));return}let r=N(`table`,`tools-table`),i=N(`thead`),a=N(`tr`);a.appendChild(N(`th`,null,w(`settings.field.name`))),a.appendChild(N(`th`,null,w(`settings.field.description`))),i.appendChild(a),r.appendChild(i);let o=N(`tbody`);for(let e of n){let t=N(`tr`),n=N(`td`,`tools-name`);n.textContent=String(e.name),n.title=String(e.name),t.appendChild(n);let r=N(`td`,`tools-desc`);r.textContent=e.description?String(e.description):`—`,t.appendChild(r),o.appendChild(t)}r.appendChild(o),t.appendChild(r)}function hS(){let e=document.createElement(`div`);return j.tools().then(t=>{mS(t.tools,e),fS.replaceChildren(...e.childNodes)}).catch(t=>{pS.textContent=`—`,e.appendChild(N(`div`,`side-note err`,w(`settings.tools.unavailable`))),e.appendChild(N(`div`,`side-note`,t instanceof Error?t.message:String(t))),fS.replaceChildren(...e.childNodes)})}var gS=3;function _S(e){let t=typeof e==`string`?e.toLowerCase():``;return t===``?``:t.includes(`unknown workspace`)?w(`settings.batch.reasonUnknownWorkspace`):t.includes(`unknown session`)?w(`settings.batch.reasonUnknownSession`):``}function vS(e){let t=(e.id??``).trim();if(t===``)return w(`settings.batch.unknownTail`);let n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function yS(e,t){let n=Array.isArray(t?.failed)?t.failed:[];if(n.length===0)return``;for(let t of n)typeof t?.error==`string`&&t.error!==``&&console.warn(`[batch] `+e+`失败 `+(t.id??``)+`:`+t.error);let r=typeof t?.deleted==`number`?t.deleted:t?.archived,i=typeof r==`number`&&r>0?w(`settings.batch.rest`,{n:r}):``,a=_S(n[0]?.error);if(n.length===1)return w(`settings.batch.failedOne`,{verb:e,reason:a===``?vS(n[0]):a,rest:i});let o=n.map(vS),s=o.slice(0,gS).join(w(`settings.batch.listSep`)),c=o.length>gS?w(`settings.batch.more`,{n:o.length}):``,l=a===``?``:w(`settings.batch.headSep`,{reason:a});return w(`settings.batch.failedMany`,{verb:e,n:n.length,head:l,shown:s,more:c,rest:i})}function bS(e){return(Array.isArray(e?.failed)?e.failed:[]).map(e=>e?.id??``).filter(e=>e!==``)}var xS=[[`.ws-details`,`.ws-count`],[`.arc-ws`,`.arc-ws-count`]];function SS(e){return`[data-id="`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)+`"]`}function CS(e,t){if(!e)return;let n=Number.parseInt(e.textContent??``,10);Number.isFinite(n)&&(e.textContent=String(Math.max(0,n+t)))}function wS(e,t){for(let[n,r]of xS){let i=e.closest(n);i&&CS(i.querySelector(r),t)}}function TS(e){let t=e.container.querySelector(e.rowSel+SS(e.id));if(!t)return null;let n=t.parentElement;if(!n)return null;let r=t.nextElementSibling;wS(t,-1),CS(e.countEl??null,-1),t.remove();let i=!0;return{restore(){if(!i)return;i=!1;let a=r&&r.parentElement===n?r:null;n.insertBefore(t,a),wS(t,1),CS(e.countEl??null,1)}}}var ES=`.sess-leaf, .ws-worker-row`;function DS(e){if(e!==``){R.selSession===e&&(R.selSession=null),Ug()===e&&Wg(null),Dr(e);for(let t of _e(ES))t.dataset.id===e&&t.classList.remove(`active`,`sel`)}}function OS(e){for(let t of e)DS(t)}function kS(e){let t=(e??``).trim();if(t===``)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function AS(e){let t=(e.title??``).trim();return t===``?kS(e.id):t}function jS(e){let t=(e.workspace??``).trim();return t===``?`root`:t}function MS(e,t){let n=typeof e.modified==`number`?e.modified:-1,r=typeof t.modified==`number`?t.modified:-1;return r===n?AS(e).localeCompare(AS(t),`zh`):r-n}function NS(e){return(Array.isArray(e)?e:[]).filter(e=>e.archived===!0).sort(MS)}function PS(e){let t=new Map;for(let n of e){let e=jS(n),r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({workspace:e,rows:t})).sort((e,t)=>e.workspace.localeCompare(t.workspace,`zh`))}function FS(e){return e>0?String(e):`—`}function IS(e){return e.length===0}function LS(){return w(`settings.archive.empty`)}function RS(e){return w(`settings.archive.restoreConfirm`,{label:e})}function zS(e){return w(`settings.archive.deleteConfirm`,{label:e})}var BS=0,VS=!1;function HS(e,t=!1){let n=document.getElementById(`settingsArchiveHint`);n&&(n.className=t?`cfg-hintline err`:`cfg-hintline`,n.textContent=e)}function US(e,t,n){let r=N(`button`,t,e);return r.type=`button`,r.addEventListener(`click`,n),r}function WS(e,t){let n=e.id??``,r=AS(e),i=N(`div`,`arc-row`);i.dataset.id=n;let a=N(`div`,`arc-main`);a.appendChild(N(`div`,`arc-title`,r));let o=kS(n);o!==``&&a.appendChild(N(`div`,`arc-id`,o)),i.appendChild(a);let s=N(`div`,`arc-actions`);return s.appendChild(US(w(`settings.action.restore`),`btn-mini`,()=>void ZS(n,r,t))),s.appendChild(US(w(`settings.action.delete`),`btn-mini danger`,()=>void QS(n,r,t))),i.appendChild(s),i}function GS(e,t,n){let r=N(`details`,`arc-ws`);r.open=!0;let i=N(`summary`,`arc-ws-head`);i.appendChild(N(`span`,`arc-ws-name`,e)),i.appendChild(N(`span`,`arc-ws-count`,String(t.length))),r.appendChild(i);for(let e of t)r.appendChild(WS(e,n));return r}function KS(e,t){let n=N(`div`,`arc-wrap`);if(IS(e))return n.appendChild(N(`div`,`side-note`,LS())),n;for(let r of PS(e))n.appendChild(GS(r.workspace,r.rows,t));return n}function qS(e){let t=N(`div`,`arc-wrap`);return t.appendChild(N(`div`,`side-note err`,w(`settings.archive.unavailable`))),t.appendChild(N(`div`,`side-note`,O(e))),t}function JS(e,t,n){let r=++BS,i={container:e,countEl:t};return t&&n?.quiet!==!0&&(t.textContent=`…`),j.sessions({archived:!0}).then(n=>{if(r!==BS)return;let a=NS(n.sessions);t&&(t.textContent=FS(a.length)),e.replaceChildren(...KS(a,i).childNodes)}).catch(n=>{r===BS&&(t&&(t.textContent=`—`),e.replaceChildren(...qS(n).childNodes))})}async function YS(e,t,n,r,i,a){VS=!0;let o=TS({container:a.container,id:n,rowSel:`.arc-row`,countEl:a.countEl});try{let s=yS(e,await r());s===``?(t&&DS(n),HS(i),await JS(a.container,a.countEl,{quiet:!0})):(o?.restore(),HS(s,!0))}catch(t){o?.restore(),HS(w(`settings.archive.failed`,{verb:e,reason:O(t)}),!0)}finally{VS=!1}}function XS(){let e=document.getElementById(`settingsArchive`);e&&JS(e,document.getElementById(`settingsArchiveCount`),{quiet:!0})}async function ZS(e,t,n){VS||e===``||await Yv({title:w(`settings.archive.restoreTitle`),message:RS(t),okLabel:w(`settings.action.restore`)})&&await YS(w(`settings.action.restore`),!1,e,()=>j.unarchiveSession(e),w(`settings.archive.restored`,{name:t}),n)}async function QS(e,t,n){VS||e===``||await Yv({title:w(`settings.archive.deleteTitle`),message:zS(t),okLabel:w(`settings.action.delete`),danger:!0})&&await YS(w(`settings.action.delete`),!0,e,()=>j.batchDeleteSessions([e]),w(`settings.archive.deleted`,{name:t}),n)}var $S=[`low`,`high`,`max`];function eC(e,t=``,n=``){let r=N(`div`,`prov-model-row`),i=N(`input`,`cfg-input`);i.placeholder=w(`settings.providers.modelId`),i.value=t;let a=N(`input`,`cfg-input`);a.placeholder=w(`settings.providers.modelDisplayName`),a.value=n;let o=document.createElement(`details`);o.className=`prov-model-adv`;let s=document.createElement(`summary`);s.textContent=w(`settings.providers.advanced`),o.appendChild(s);let c=N(`div`,`prov-model-adv-body`),l=new Set,u=e=>e.replace(/\s+/g,``).toLowerCase(),d=new Map,f=N(`div`,`prov-effort-chips`),p=N(`button`,`btn-mini`,`+`);p.type=`button`,p.title=w(`settings.providers.addEffortTier`);let m=N(`input`,`cfg-input`);m.placeholder=w(`settings.providers.customTierPlaceholder`),m.hidden=!0,m.style.width=`170px`,m.style.flex=`0 0 auto`;let h=N(`span`,`cfg-hint`);h.hidden=!0,f.appendChild(p),f.appendChild(m),f.appendChild(h);let g=(e,t)=>{let n=e.dataset.effort??``;t?l.add(n):l.delete(n),e.classList.toggle(`on`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)},_=(t,n=!1)=>{let r=u(t);if(r===``||d.has(r))return;let i=N(`button`,`prov-effort-chip`,t);i.type=`button`,i.dataset.effort=t,i.addEventListener(`click`,()=>{g(i,!l.has(i.dataset.effort??``)),e.onLayout?.()}),d.set(r,i),f.insertBefore(i,p),g(i,n)},v=e=>{h.textContent=e,h.hidden=e===``},y=t=>{if(m.hidden)return;let n=m.value;if(m.value=``,m.hidden=!0,p.hidden=!1,t){let e=n.trim();e!==``&&(d.has(u(e))?v(w(`settings.providers.tierExists`,{tier:e})):(v(``),_(e,!0)))}e.onLayout?.()};p.addEventListener(`click`,()=>{m.hidden&&(v(``),m.value=``,m.hidden=!1,p.hidden=!0,e.onLayout?.(),m.focus())}),m.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),y(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y(!1))}),m.addEventListener(`blur`,()=>y(!0));for(let e of $S)_(e);let b={root:f,set(e){let t=new Map;for(let n of e){let e=n.trim();if(e===``)continue;let r=u(e);t.has(r)||t.set(r,e)}for(let[e,n]of t)d.has(e)||_(n);l.clear();for(let[e,n]of d)g(n,t.has(e))},values(){let e=[];for(let t of $S){let n=d.get(u(t))?.dataset.effort;n!==void 0&&l.has(n)&&e.push(n)}for(let t of d.values()){let n=t.dataset.effort??``;n!==``&&!$S.includes(n)&&l.has(n)&&e.push(n)}return e}},x=N(`input`,`cfg-input`);x.type=`text`,x.min=`0`,x.placeholder=w(`settings.providers.contextPlaceholder`);let ee=N(`input`,`cfg-input`);ee.type=`text`,ee.min=`0`,ee.placeholder=w(`settings.providers.maxOutPlaceholder`),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.providers.reasoningEffort`))),c.appendChild(f),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.providers.modelContext`))),c.appendChild(x),c.appendChild(N(`label`,`prov-adv-label`,w(`settings.field.maxOutputTokens`))),c.appendChild(ee),o.appendChild(c),o.addEventListener(`toggle`,()=>e.onLayout?.());let te=N(`button`,`btn-mini danger`,w(`settings.action.remove`));te.type=`button`,te.addEventListener(`click`,()=>{r.remove(),e.rows=e.rows.filter(e=>e.li!==r),e.onLayout?.()}),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(te),e.modelsBox.appendChild(r),e.rows.push({id:i,name:a,efforts:b,ctx:x,maxOut:ee,li:r}),e.onLayout?.()}var tC=null;function nC(e,t){tC?.();let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card prov-picker`);r.appendChild(N(`div`,`modal-card-title`,w(`settings.providers.pickTitle`))),r.appendChild(N(`div`,`side-note`,w(`settings.providers.pickNote`)));let i=N(`div`,`prov-picker-list`),a=[],o=N(`div`,`prov-picker-count`),s=()=>{let e=a.filter(e=>e.checked).length;o.textContent=w(`settings.providers.pickCount`,{n:e,total:a.length})},c=document.createElement(`div`);for(let t of e){let e=N(`label`,`prov-picker-row`+(t.existing?` existing`:``)),n=N(`input`,`prov-picker-cb`);n.type=`checkbox`,n.checked=!1,n.disabled=t.existing,n.dataset.modelId=t.id,n.addEventListener(`change`,s),e.appendChild(n),e.appendChild(N(`span`,`prov-picker-id`,t.id)),t.existing&&e.appendChild(N(`span`,`prov-picker-tag`,w(`settings.providers.pickExisting`))),c.appendChild(e),t.existing||a.push(n)}i.replaceChildren(...c.childNodes),s(),r.appendChild(i),r.appendChild(o);let l=N(`div`,`modal-card-actions`),u=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));u.type=`button`;let d=N(`button`,`btn btn-accent`,w(`settings.action.confirm`));d.type=`button`;let f=null,p=()=>{tC===p&&(tC=null),f&&(F(f),f=null),n.remove()};tC=p,u.addEventListener(`click`,p),d.addEventListener(`click`,()=>{let e=a.filter(e=>e.checked).map(e=>e.dataset.modelId??``).filter(Boolean);p(),t(e)}),n.addEventListener(`click`,e=>{e.target===n&&p()}),l.appendChild(u),l.appendChild(d),r.appendChild(l),n.appendChild(r),document.body.appendChild(n),f=P(p),u.focus()}var rC=M(`#settingsProviders`),iC=[],aC=null,oC=new Set;function sC(){return iC}function cC(){return aC}function lC(e,t){iC=e,aC=t}function uC(e){aC=e}function dC(e){return e instanceof Error?e.message:String(e)}var fC=[{value:`chat_completions`,label:`Chat Completions`},{value:`responses`,label:`Responses`},{value:`anthropic_messages`,label:`Anthropic Messages`}];function pC(e){let t=e.rows.filter(e=>e.id.value.trim()!==``||e.name.value.trim()!==``).map(e=>({id:e.id.value.trim(),name:e.name.value.trim()||e.id.value.trim(),reasoning_efforts:e.efforts.values(),context_window:mC(e.ctx),max_output_tokens:mC(e.maxOut)})),n=e.key.value.trim();return{id:e.originalId??e.name.value.trim(),name:e.name.value.trim(),note:e.note.value.trim(),base_url:e.url.value.trim(),request_format:e.format.value,...n===``?{}:{api_key:n},models:t}}function mC(e){let t=e.value.trim().toLowerCase().replace(/\s+/g,``);if(t===``)return null;let n=/^(\d+(?:\.\d+)?)([km])?$/.exec(t);if(!n)return null;let r=Number(n[1]);if(!Number.isFinite(r)||r<0)return null;let i=n[2]===`k`?1e3:n[2]===`m`?1e6:1,a=Math.round(r*i);return Number.isFinite(a)&&a>=0?a:null}function hC(e,t){let n=N(`div`,`prov-form`),r=N(`div`,`prov-editor-status`);n.appendChild(r);let i=(e,t)=>{let n=N(`label`,`prov-field`);return n.appendChild(N(`span`,`prov-field-label`,e)),n.appendChild(t),n},a=N(`input`,`cfg-input`);a.placeholder=w(`settings.providers.idPlaceholder`),a.value=e?.name??``,n.appendChild(i(w(`settings.field.name`),a));let o=N(`input`,`cfg-input`);o.placeholder=w(`settings.providers.notePlaceholder`),o.value=e?.note??``,n.appendChild(i(w(`settings.providers.note`),o));let s=N(`input`,`cfg-input`);s.type=`password`,s.placeholder=e?w(`settings.providers.keyPlaceholderExisting`):`API Key`,s.value=``,n.appendChild(i(`API Key`,s));let c=N(`input`,`cfg-input`);c.placeholder=`https://…/v1`,c.value=e?.base_url??``;let l=N(`button`,`btn btn-soft btn-mini`,w(`settings.providers.requestTest`));l.type=`button`;let u=N(`div`,`prov-urlrow`);u.appendChild(c),u.appendChild(l),n.appendChild(i(w(`settings.providers.apiUrl`),u));let d=document.createElement(`select`);d.className=`cfg-input`;for(let e of fC){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,d.appendChild(t)}if(e?.request_format){if(!fC.some(t=>t.value===e.request_format)){let t=document.createElement(`option`);t.value=e.request_format,t.textContent=e.request_format,d.appendChild(t)}d.value=e.request_format}n.appendChild(i(w(`settings.providers.requestFormat`),d));let f=N(`div`,`prov-models-head`);f.appendChild(N(`span`,`prov-models-title`,w(`settings.field.model`)));let p=N(`button`,`btn btn-soft btn-mini`,w(`settings.providers.fetchModels`));p.type=`button`,p.title=w(`settings.providers.fetchModelsHint`),f.appendChild(p),n.appendChild(f);let m=N(`div`,`prov-models`);n.appendChild(m);let h={root:n,name:a,note:o,key:s,url:c,format:d,modelsBox:m,status:r,rows:[],onLayout:t.onLayout,originalId:e?.id};for(let t of e?.models??[]){eC(h,t.id,t.name);let e=h.rows[h.rows.length-1];e.efforts.set(t.reasoning_efforts??[]),t.context_window!=null&&(e.ctx.value=String(t.context_window))}let g=N(`button`,`btn-mini`,w(`settings.providers.addModel`));g.type=`button`,g.addEventListener(`click`,()=>eC(h)),n.appendChild(g);let _=N(`div`,`modal-card-actions`),v=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));v.type=`button`;let y=N(`button`,`btn btn-accent`,w(`settings.action.save`));y.type=`button`,l.addEventListener(`click`,()=>{r.className=`prov-editor-status`,r.textContent=w(`settings.providers.testing`),j.testProvider(pC(h)).then(e=>{if(e.ok===!1||e.ok===void 0&&e.error){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.testFailed`,{reason:O(e.error,w(`settings.common.checkUrlKey`))});return}r.className=`prov-editor-status ok`,r.textContent=w(`settings.providers.testOk`,{ms:e.latency_ms??`—`,n:e.model_count??`—`})}).catch(e=>{r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.testFailed`,{reason:dC(e)})})});let b=0;return p.addEventListener(`click`,()=>{let e=++b,t=a.value.trim();if(!t){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.needId`);return}r.className=`prov-editor-status`,r.textContent=w(`settings.providers.savingAndFetching`),j.saveProvider(pC(h)).then(()=>j.fetchProviderModels(t)).then(t=>{if(e!==b)return;if(t.ok===!1||t.ok===void 0&&t.error){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.fetchFailed`,{reason:O(t.error,w(`settings.common.checkUrlKey`))});return}let n=t.models??[];if(!n.length){r.className=`prov-editor-status`,r.textContent=w(`settings.providers.noModelsFetched`);return}let i=new Set(h.rows.map(e=>e.id.value.trim()).filter(Boolean));r.className=`prov-editor-status ok`,r.textContent=w(`settings.providers.fetched`,{n:n.length}),nC(n.map(e=>({id:e.id,existing:i.has(e.id)})),e=>{let t=e.filter(e=>!h.rows.some(t=>t.id.value.trim()===e));for(let e of t)eC(h,e,e);r.className=`prov-editor-status ok`,r.textContent=t.length?w(`settings.providers.added`,{n:t.length,total:n.length}):w(`settings.providers.noneSelected`,{n:n.length})})}).catch(t=>{e===b&&(r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.fetchFailed`,{reason:dC(t)}))})}),y.addEventListener(`click`,()=>{let e=pC(h);if(!e.id){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.idRequired`);return}r.className=`prov-editor-status`,r.textContent=w(`settings.config.saving`),y.disabled=!0,j.saveProvider(e).then(n=>{if(n.ok===!1){r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.saveFailed`,{reason:O(n.error,w(`settings.common.checkInput`))}),y.disabled=!1;return}y.disabled=!1,r.className=`prov-editor-status ok`,r.textContent=w(`settings.config.saved`),t.onSaved(e)}).catch(e=>{r.className=`prov-editor-status err`,r.textContent=w(`settings.providers.saveFailed`,{reason:dC(e)}),y.disabled=!1})}),v.addEventListener(`click`,()=>t.onCancel()),_.appendChild(v),_.appendChild(y),n.appendChild(_),h}function gC(e){return e.models?.length??0}function _C(e,t){let n=document.createElement(`div`);t.is_default&&n.appendChild(N(`span`,`prov-badge`,w(`settings.tag.default`))),t.has_key&&n.appendChild(N(`span`,`prov-badge key`,w(`settings.providers.keyConfigured`))),!t.is_default&&!t.has_key&&(n.textContent=`—`),e.replaceChildren(...n.childNodes)}function vC(e,t){let n=e.dataset.id??``;e.dataset.id=t.id,n!==t.id&&oC.delete(n)&&oC.add(t.id),e.classList.toggle(`is-default`,t.is_default===!0);let r=e.querySelector(`.prov-name`);r&&(r.textContent=t.name||t.id);let i=e.querySelector(`.prov-td-note`);i&&(i.textContent=t.note??`—`);let a=e.querySelector(`.prov-td-fmt`);a&&(a.textContent=t.request_format??`—`);let o=e.querySelector(`.prov-td-models`);o&&(o.textContent=String(gC(t)));let s=e.querySelector(`.prov-td-state`);s&&_C(s,t)}function yC(e,t=``){let n=rC.querySelector(`.prov-list-msg`);n&&(n.textContent=e,n.className=`prov-list-msg`+(t?` `+t:``))}async function bC(e,t,n){try{let r=await j.providers();lC(r.providers??[],r.default_model??null);let i=sC().find(e=>e.id===n);if(!i){e.loadProviders();return}vC(t,i)}catch{e.loadProviders()}}var xC=new Set;function SC(){for(let e of xC)e.overlay&&(F(e.overlay),e.overlay=null);xC.clear()}function CC(e){if(!e.open)return;let t=e.inner.style.maxHeight;t!==`none`&&t!==``&&(e.inner.style.maxHeight=e.inner.scrollHeight+`px`)}function wC(e){if(e.open)return;e.open=!0;let t=e.tr.dataset.id??``;t&&oC.add(t),e.tr.classList.add(`expanded`),e.tr.setAttribute(`aria-expanded`,`true`),e.panelTr.classList.add(`open`),e.inner.style.maxHeight=e.inner.scrollHeight+`px`,e.overlay=P(()=>TC(e))}function TC(e){if(!e.open)return;e.open=!1;let t=e.tr.dataset.id??``;t&&oC.delete(t),e.overlay&&(F(e.overlay),e.overlay=null),e.inner.style.maxHeight===`none`&&(e.inner.style.maxHeight=e.inner.scrollHeight+`px`,e.inner.offsetHeight),e.panelTr.classList.remove(`open`),e.tr.classList.remove(`expanded`),e.tr.setAttribute(`aria-expanded`,`false`),e.inner.style.maxHeight=`0px`}function EC(e){e.open?TC(e):wC(e)}function DC(e,t){let n=N(`tr`,`prov-row`);n.dataset.id=t.id,n.title=w(`settings.providers.expandHint`),n.setAttribute(`aria-expanded`,`false`),t.is_default&&n.classList.add(`is-default`);let r=N(`td`,`prov-td-name`);r.appendChild(N(`span`,`prov-name`,t.name||t.id)),n.appendChild(r),n.appendChild(N(`td`,`prov-td-note`,t.note??`—`)),n.appendChild(N(`td`,`prov-td-fmt`,t.request_format??`—`)),n.appendChild(N(`td`,`prov-td-models`,String(gC(t))));let i=N(`td`,`prov-td-state`);_C(i,t),n.appendChild(i);let a=N(`td`,`prov-td-ops`),o=N(`button`,`btn-mini danger`,w(`settings.action.delete`));o.type=`button`,o.addEventListener(`click`,t=>{t.stopPropagation();let r=n.dataset.id??``,i=sC().find(e=>e.id===r);Yv({title:w(`settings.providers.deleteTitle`),message:w(`settings.providers.confirmDelete`,{name:i?.name||r}),okLabel:w(`settings.action.delete`),danger:!0}).then(t=>{t&&j.deleteProvider(r).then(()=>void e.loadProviders()).catch(e=>yC(w(`settings.providers.deleteFailed`,{reason:dC(e)})))})}),a.appendChild(o),n.appendChild(a);let s=N(`tr`,`prov-panel-row`),c=N(`td`,`prov-panel-td`);c.colSpan=6;let l=N(`div`,`prov-inline`);c.appendChild(l),s.appendChild(c);let u={tr:n,panelTr:s,inner:l,open:!1,overlay:null};xC.add(u);let d=hC(t,{onSaved:t=>{TC(u),bC(e,n,t.id)},onCancel:()=>TC(u),onLayout:()=>CC(u)});return l.appendChild(d.root),l.addEventListener(`transitionend`,e=>{e.target===l&&e.propertyName===`max-height`&&u.open&&(l.style.maxHeight=`none`)}),n.addEventListener(`click`,e=>{let t=e.target;t instanceof Element&&t.closest(`button, a, input, select, textarea, label`)||EC(u)}),oC.has(t.id)&&(u.open=!0,n.classList.add(`expanded`),n.setAttribute(`aria-expanded`,`true`),s.classList.add(`open`),l.style.maxHeight=`none`,u.overlay=P(()=>TC(u))),{tr:n,panelTr:s}}function OC(e,t){if(SC(),e.replaceChildren(),!sC().length){e.appendChild(N(`div`,`side-note`,w(`settings.providers.empty`)));return}let n=N(`table`,`prov-table`),r=N(`thead`),i=N(`tr`);for(let e of[w(`settings.field.name`),w(`settings.providers.note`),w(`settings.providers.requestFormat`),w(`settings.field.model`),w(`settings.field.status`),w(`settings.field.actions`)])i.appendChild(N(`th`,null,e));r.appendChild(i),n.appendChild(r);let a=N(`tbody`);for(let e of sC()){let n=DC(t,e);a.appendChild(n.tr),a.appendChild(n.panelTr)}n.appendChild(a),e.appendChild(n)}function kC(e,t){let n=N(`div`,`prov-default-card`),r=N(`div`,`prov-default-head`);r.appendChild(N(`span`,`prov-default-title`,w(`settings.providers.defaultModel`))),r.appendChild(N(`span`,`prov-default-note`,w(`settings.providers.defaultNote`))),n.appendChild(r);let i=N(`div`,`prov-default-body`);i.appendChild(N(`span`,`prov-default-label`,w(`settings.providers.currentDefault`)));let a=document.createElement(`select`);a.className=`cfg-input prov-default-sel`;let o=new Set;for(let e of sC())for(let t of e.models??[]){let n=document.createElement(`option`);n.value=t.id,n.textContent=(e.name||e.id)+` / `+t.id,o.add(t.id),a.appendChild(n)}if(cC()!==null&&!o.has(cC()??``)){let e=document.createElement(`option`);e.value=cC()??``,e.textContent=w(`settings.providers.defaultNotInList`,{model:cC()??``}),a.appendChild(e)}a.value=cC()??``;let s=N(`span`,`prov-default-msg`);a.addEventListener(`change`,()=>{let e=a.value;e&&(s.textContent=w(`settings.providers.applyingDefault`),s.className=`prov-default-msg`,j.setDefaultModel(e).then(()=>{uC(e),s.textContent=w(`settings.providers.defaultApplied`),s.className=`prov-default-msg ok`,t.loadProviders()}).catch(e=>{s.textContent=w(`settings.providers.switchFailed`,{reason:dC(e)}),s.className=`prov-default-msg err`,a.value=cC()??``}))}),i.appendChild(a),i.appendChild(s),n.appendChild(i),e.appendChild(n)}var AC={loadProviders:()=>jC()};async function jC(){let e=document.createElement(`div`);try{let e=await j.providers();lC(e.providers??[],e.default_model??null)}catch(t){e.appendChild(N(`div`,`side-note err`,w(`settings.providers.listUnavailable`))),e.appendChild(N(`div`,`side-note`,dC(t))),rC.replaceChildren(...e.childNodes);return}OC(e,AC),kC(e,AC),rC.replaceChildren(...e.childNodes)}var MC=null;function NC(){MC?.();let e=N(`div`,`modal-scrim`),t=N(`div`,`modal-card prov-modal`);t.appendChild(N(`div`,`modal-card-title`,w(`settings.providers.add`)));let n=null,r=()=>{MC===r&&(MC=null),n&&(F(n),n=null),e.remove()};MC=r;let i=hC(null,{onSaved:()=>{r(),jC()},onCancel:r});t.appendChild(i.root),e.appendChild(t),document.body.appendChild(e),n=P(r),i.name.focus()}function PC(){M(`#btnAddProvider`).addEventListener(`click`,()=>NC())}var FC=M(`#settingsPrompts`),IC=M(`#promptsWrap`);function LC(){return[[`{{model}}`,w(`settings.prompts.varCurrentModel`)],[`{{provider}}`,w(`settings.field.provider`)],[`{{base_url}}`,w(`settings.prompts.varApiUrl`)],[`{{workspace}}`,w(`settings.prompts.varWorkspaceName`)],[`{{session}}`,w(`settings.prompts.varSessionTitle`)],[`{{tools}}`,w(`settings.prompts.varToolList`)],[`{{context_window}}`,w(`settings.field.contextWindow`)],[`{{max_output_tokens}}`,w(`settings.field.maxOutputTokens`)],[`{{date}}`,w(`settings.prompts.varCurrentDate`)]]}var RC=`global`,zC=``,BC=[],VC=[],HC=null;function UC(e){return e instanceof Error?e.message:String(e)}function WC(e){return w(e===`global`?`settings.scope.global`:`settings.scope.workspace`)}function GC(){let e=document.createElement(`div`);if(!VC.length){e.appendChild(N(`div`,`side-note`,w(RC===`global`?`settings.prompts.emptyGlobal`:`settings.prompts.emptyWorkspace`))),FC.replaceChildren(...e.childNodes);return}let t=N(`table`,`prompts-table`),n=N(`thead`),r=N(`tr`);for(let e of[w(`settings.field.name`),w(`settings.prompts.scope`),w(`settings.field.status`),w(`settings.field.actions`)])r.appendChild(N(`th`,null,e));n.appendChild(r),t.appendChild(n);let i=N(`tbody`);for(let e of VC){let t=N(`tr`);e.id===HC&&t.classList.add(`is-active`);let n=N(`td`,`prompts-td-name`);n.appendChild(N(`span`,`prompt-name`,e.name||e.id)),e.id===HC&&n.appendChild(N(`span`,`prompt-badge active`,w(`settings.tag.active`))),t.appendChild(n),t.appendChild(N(`td`,`prompts-td-scope`,WC(e.scope)));let r=N(`td`,`prompts-td-state`);e.is_default&&r.appendChild(N(`span`,`prompt-badge def`,w(`settings.tag.default`))),!e.is_default&&e.id!==HC&&(r.textContent=`—`),t.appendChild(r);let a=N(`td`,`prompts-td-ops`),o=N(`button`,`btn-mini`,w(`settings.action.edit`));o.type=`button`,o.addEventListener(`click`,()=>qC(e));let s=N(`button`,`btn-mini`,w(`settings.prompts.setDefault`));s.type=`button`,s.disabled=!!e.is_default,s.addEventListener(`click`,()=>{j.setDefaultPrompt(e.id,RC===`global`?void 0:zC||void 0).then(()=>{KC(w(`settings.prompts.setDefaultDone`,{name:e.name||e.id})),YC()}).catch(e=>KC(w(`settings.prompts.setDefaultFailed`,{reason:UC(e)})))});let c=N(`button`,`btn-mini danger`,w(`settings.action.delete`));c.type=`button`,c.addEventListener(`click`,()=>{Yv({title:w(`settings.prompts.deleteTitle`),message:w(`settings.prompts.confirmDelete`,{name:e.name||e.id}),okLabel:w(`settings.action.delete`),danger:!0}).then(t=>{t&&j.deletePrompt(e.id,RC===`global`?void 0:zC||void 0).then(()=>{KC(w(`settings.prompts.deleted`,{name:e.name||e.id})),YC()}).catch(e=>KC(w(`settings.prompts.deleteFailed`,{reason:UC(e)})))})}),a.appendChild(o),a.appendChild(s),a.appendChild(c),t.appendChild(a),i.appendChild(t)}t.appendChild(i),e.appendChild(t),e.appendChild(N(`div`,`prompts-note`,w(`settings.prompts.legend`))),FC.replaceChildren(...e.childNodes)}function KC(e){let t=document.getElementById(`sideFoot`);t&&(t.textContent=e)}function qC(e){let t=N(`div`,`modal-scrim`),n=N(`div`,`modal-card prompt-modal`);n.appendChild(N(`div`,`modal-card-title`,e?w(`settings.prompts.editTitle`,{name:e.name||e.id}):w(`settings.prompts.newPrompt`)));let r=N(`details`,`prompt-vars`),i=document.createElement(`summary`);i.textContent=w(`settings.prompts.variables`),r.appendChild(i);let a=N(`table`,`prompt-vars-table`),o=N(`tbody`);for(let[e,t]of LC()){let n=N(`tr`);n.appendChild(N(`td`,`prompt-var-code`,e)),n.appendChild(N(`td`,`prompt-var-desc`,t)),o.appendChild(n)}a.appendChild(o),r.appendChild(a),n.appendChild(r);let s=N(`label`,`prov-field`);s.appendChild(N(`span`,`prov-field-label`,w(`settings.field.name`)));let c=N(`input`,`cfg-input`);c.placeholder=w(`settings.prompts.promptName`),c.value=e?.name??``,s.appendChild(c),n.appendChild(s);let l=N(`div`,`ws-fs-status`);n.appendChild(l);let u=N(`div`,`prompt-secs`);n.appendChild(u),BC.length||u.appendChild(N(`div`,`side-note`,w(`settings.prompts.noSegmentEdit`)));let d=[];for(let t of BC){let n=N(`div`,`prompt-sec-row`),r=N(`div`,`prompt-sec-head`);r.appendChild(N(`span`,`prompt-sec-name`,t.name||t.id)),r.appendChild(N(`span`,`prompt-sec-scope`,WC(t.scope)));let i=N(`input`,`prompt-inherit`);i.type=`checkbox`,i.checked=!0;let a=N(`label`,`prompt-inherit-label`);a.appendChild(i),a.appendChild(N(`span`,null,w(`settings.prompts.inherit`))),r.appendChild(a),n.appendChild(r);let o=N(`textarea`,`prompt-sec-ta cfg-input`);o.rows=3,o.disabled=!0,o.placeholder=w(`settings.prompts.inheritedFromBuiltin`);let s=e?.section_overrides?.[t.id];s!==void 0&&(i.checked=!1,o.value=s),n.appendChild(o),u.appendChild(n),d.push({sec:t,ta:o,inherit:i});let c=()=>{o.disabled=i.checked,o.placeholder=i.checked?w(`settings.prompts.inheritedFromBuiltin`):w(`settings.prompts.overridePlaceholder`),n.classList.toggle(`inherited`,i.checked)};i.addEventListener(`change`,c),c()}let f=N(`div`,`modal-card-actions`),p=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));p.type=`button`;let m=N(`button`,`btn btn-accent`,w(`settings.action.save`));m.type=`button`;let h=null,g=()=>{h&&(F(h),h=null),t.remove()};h=P(g),p.addEventListener(`click`,g),m.addEventListener(`click`,()=>{let t=c.value.trim();if(!t){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.nameRequired`),c.focus();return}let n={};!d.length&&e?.section_overrides&&Object.assign(n,e.section_overrides);for(let e of d)if(!e.inherit.checked){if(e.ta.value.trim()===``){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.segmentNoOverride`,{name:e.sec.name||e.sec.id}),e.ta.focus();return}n[e.sec.id]=e.ta.value}m.disabled=!0,m.textContent=w(`settings.config.saving`),j.savePrompt({id:e?.id??`p`+Date.now().toString(36),name:t,section_overrides:n,workspace:RC===`workspace`&&zC||void 0}).then(e=>{if(e.ok===!1){l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.saveFailed`,{reason:O(e.error,w(`settings.common.checkInput`))}),m.disabled=!1,m.textContent=w(`settings.action.save`);return}g(),KC(w(`settings.prompts.saved`,{name:t})),YC()}).catch(e=>{l.className=`ws-fs-status err`,l.textContent=w(`settings.prompts.saveFailed`,{reason:UC(e)}),m.disabled=!1,m.textContent=w(`settings.action.save`)})}),f.appendChild(p),f.appendChild(m),n.appendChild(f),t.appendChild(n),document.body.appendChild(t),c.focus()}var JC=0;async function YC(){let e=++JC,t=document.createElement(`div`),n;try{n=await j.prompts(RC===`workspace`&&zC||void 0)}catch(n){if(e!==JC)return;t.appendChild(N(`div`,`side-note err`,w(`settings.prompts.unsupported`))),t.appendChild(N(`div`,`side-note`,UC(n))),FC.replaceChildren(...t.childNodes);return}e===JC&&(BC=n.sections??[],VC=n.prompts??[],HC=n.active_prompt??null,GC())}function XC(){let e=N(`div`,`prompts-scope`),t=N(`button`,`prompts-scope-btn`+(RC===`global`?` active`:``),w(`settings.scope.global`));t.type=`button`;let n=N(`button`,`prompts-scope-btn`+(RC===`workspace`?` active`:``),w(`settings.scope.workspace`));n.type=`button`;let r=document.createElement(`select`);r.className=`cfg-input prompts-ws-sel`,r.style.display=RC===`workspace`?``:`none`;let i=e=>{RC=e,t.classList.toggle(`active`,e===`global`),n.classList.toggle(`active`,e===`workspace`),r.style.display=e===`workspace`?``:`none`};t.addEventListener(`click`,()=>{i(`global`),YC()}),n.addEventListener(`click`,()=>{i(`workspace`),YC()}),e.appendChild(t),e.appendChild(n),e.appendChild(r),IC.appendChild(e),j.workspaces().then(e=>{let t=e.workspaces??[];r.replaceChildren();for(let e of t){let t=document.createElement(`option`);t.value=e.name,t.textContent=e.name,r.appendChild(t)}t.length?(zC=t[0].name,r.value=zC,r.disabled=!1):r.disabled=!0}).catch(()=>{r.disabled=!0}),r.addEventListener(`change`,()=>{zC=r.value,YC()}),M(`#btnNewPrompt`).addEventListener(`click`,()=>qC(null)),YC()}var ZC=[404,409,422];function QC(e,t){return e instanceof D?ZC.includes(e.status)&&e.technical.trim()!==``?e.technical:e.message:O(e,t)}function $C(e){return e.ok===!1||e.preset===void 0}async function ew(e){let t=An();Fn(e);try{let t=await j.createPermissionPreset(e);if($C(t)||t.preset===void 0)throw new D(w(`settings.permissions.rejected`));return Fn(t.preset),{ok:!0,text:w(`settings.permissions.savedCustom`),preset:t.preset}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.saveFailed`,{reason:QC(e,w(`settings.common.checkInput`))})}}}async function tw(e){let t=An();Fn(e);try{let t=await j.updatePermissionPreset(e.id,e);if($C(t)||t.preset===void 0)throw new D(w(`settings.permissions.rejected`));return Fn(t.preset),{ok:!0,text:w(`settings.permissions.savedCustom`),preset:t.preset}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.saveFailed`,{reason:QC(e,w(`settings.common.checkInput`))})}}}async function nw(e){let t=An(),n=Nn(e)?.label??e;In(e);try{if((await j.deletePermissionPreset(e)).ok===!1)throw new D(w(`settings.permissions.opRejected`));return{ok:!0,text:w(`settings.permissions.deleted`,{label:n})}}catch(e){return jn(t),{ok:!1,text:w(`settings.permissions.deleteFailed`,{reason:QC(e,w(`settings.common.retryLater`))})}}}var rw=32,iw=64;function aw(){return w(`settings.permissions.idHint`)}function ow(){return w(`settings.permissions.rootsHint`)}function sw(){return w(`settings.permissions.toolsHint`)}function cw(e,t){let n=N(`input`,`cfg-input`);return n.type=`text`,n.value=e,n.placeholder=t,n}function lw(e,t){let n=N(`button`,`btn-mini`,e);return n.type=`button`,n.addEventListener(`click`,t),n}function uw(e,t,n){let r=N(`label`,`cfg-field`);return r.appendChild(N(`span`,`cfg-label`,e)),r.appendChild(t),n!==void 0&&n!==``&&r.appendChild(N(`span`,`cfg-hint`,n)),r}function dw(e,t,n){let r=N(`div`,`cfg-field`);r.appendChild(N(`span`,`cfg-label`,e));let i=N(`div`,`perm-field-body`);return i.appendChild(t),n!==void 0&&n!==``&&i.appendChild(N(`span`,`cfg-hint`,n)),r.appendChild(i),r}function fw(e,t,n){let r=N(`input`,`perm-switch-input`);r.type=`checkbox`,r.checked=t;let i=N(`label`,`perm-switch`);return i.appendChild(r),i.appendChild(N(`span`,`perm-switch-label`,e)),n!==void 0&&n!==``&&i.appendChild(N(`span`,`cfg-hint`,n)),{input:r,row:i}}function pw(e){let t=N(`div`,`perm-roots-edit`),n=N(`div`,`perm-roots-list`),r=e.slice(0,rw),i=()=>{let e=document.createElement(`div`);for(let t of r){let n=N(`div`,`perm-root-row`);n.appendChild(N(`code`,`perm-root`,t)),n.appendChild(lw(w(`settings.action.remove`),()=>{let e=r.indexOf(t);e>=0&&r.splice(e,1),i()})),e.appendChild(n)}r.length===0&&e.appendChild(N(`div`,`side-note`,w(`settings.permissions.noExtraRootsAdded`))),n.replaceChildren(...e.childNodes)},a=e=>{let t=e.trim();t===``||r.includes(t)||r.length>=rw||(r.push(t),i())},o=cw(``,w(`settings.permissions.rootPlaceholder`)),s=N(`div`,`perm-addrow`);return s.append(o,lw(w(`settings.action.add`),()=>{a(o.value),o.value=``}),lw(w(`settings.permissions.chooseDir`),()=>{Km(w(`settings.permissions.chooseExtraDir`),ow()).then(e=>{e!==null&&a(e)})})),t.append(n,s),i(),{el:t,value:()=>r.slice()}}function mw(e,t,n){let r=N(`input`,`perm-tool-input`);r.type=`checkbox`,r.checked=t,r.addEventListener(`change`,()=>{r.checked?n.add(e):n.delete(e)});let i=N(`label`,`perm-tool`);return i.append(r,N(`span`,`perm-tool-name`,e)),i}function hw(e){let t=N(`div`,`perm-tools`),n=new Set(e),r=(r,i)=>{let a=document.createElement(`div`),o=new Set;for(let e of r.slice(0,iw))a.appendChild(mw(e,n.has(e),n)),o.add(e);for(let t of e)o.has(t)||a.appendChild(mw(t,!0,n));i!==``&&a.appendChild(N(`div`,`side-note`,i)),t.replaceChildren(...a.childNodes)};return r(e,``),j.tools().then(e=>{let t=(e.tools??[]).map(e=>e.name).filter(e=>typeof e==`string`&&e!==``);r(t,t.length===0?w(`settings.permissions.toolsNotLoaded`):``)}).catch(()=>r(e,w(`settings.permissions.toolsUnavailableReload`))),{el:t,value:()=>Array.from(n).slice(0,iw)}}function gw(e){e.classList.add(`hidden`),e.replaceChildren()}function _w(e,t,n){let r=t===null,i=cw(t?.id??``,w(`settings.permissions.idPlaceholder`));i.disabled=!r;let a=cw(t?.label??``,w(`settings.permissions.labelPlaceholder`)),o=fw(w(`settings.permissions.networkOn`),t?.network===!0),s=fw(w(`settings.permissions.workspaceOn`),t?.workspaceWritable===!0),c=fw(w(`settings.permissions.toolRootOn`),t?.toolRootsWritable===!0),l=fw(w(`settings.permissions.allPathsOn`),t?.allPaths===!0,w(`settings.permissions.allPathsRisk`)),u=fw(w(`settings.permissions.unsandboxedDeclare`),t?.unsandboxed===!0,vn()),d=pw(t?.writeRoots??[]),f=hw(t?.toolDeny??[]),p=N(`div`,`perm-editor-status`),m=N(`button`,`btn btn-accent`,w(`settings.action.save`));m.type=`button`;let h=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));h.type=`button`;let g=(e,t)=>{p.className=`perm-editor-status`+(e===``?``:` `+e),p.textContent=t};m.addEventListener(`click`,()=>{let e=i.value.trim();if(e===``)return g(`err`,w(`settings.permissions.saveIdRequired`));if(!yn.test(e))return g(`err`,w(`settings.permissions.idInvalid`,{hint:aw()}));let t={id:e,label:a.value.trim()||e,network:o.input.checked,workspaceWritable:s.input.checked,toolRootsWritable:c.input.checked,writeRoots:d.value(),allPaths:l.input.checked,unsandboxed:u.input.checked,toolDeny:f.value()};m.disabled=!0,g(``,``),(r?ew(t):tw(t)).then(e=>{if(e.ok){n.onSettled(e);return}m.disabled=!1,g(`err`,e.text)})}),h.addEventListener(`click`,()=>n.onCancel());let _=N(`form`,`cfg-form perm-editor-form`);_.appendChild(N(`div`,`perm-editor-title`,r?w(`settings.permissions.newTitle`):w(`settings.permissions.editTitle`,{id:t?.id??``}))),_.appendChild(uw(w(`settings.permissions.idField`),i,r?aw():w(`settings.permissions.idLocked`))),_.appendChild(uw(w(`settings.permissions.labelField`),a,w(`settings.permissions.labelHint`)));let v=N(`div`,`perm-switches`);for(let e of[o,s,c,l,u])v.appendChild(e.row);_.appendChild(dw(w(`settings.permissions.switches`),v)),_.appendChild(dw(w(`settings.permissions.extraRootsLabel`),d.el,ow())),_.appendChild(dw(w(`settings.permissions.toolsField`),f.el,sw()));let y=N(`div`,`cfg-actions`);y.append(m,h),_.appendChild(y),_.appendChild(p);let b=document.createElement(`div`);b.appendChild(_),e.replaceChildren(...b.childNodes),e.classList.remove(`hidden`)}function vw(e,t,n){let r=N(`button`,t,e);return r.type=`button`,r.addEventListener(`click`,n),r}function yw(e,t,n){let r=N(`div`,`perm-card`);r.dataset.id=e.id,r.dataset.builtin=t?`1`:`0`;let i=N(`div`,`perm-card-head`);if(i.appendChild(N(`span`,`perm-card-title`,e.label||e.id)),i.appendChild(N(`code`,`perm-card-id`,e.id)),t)i.appendChild(N(`span`,`perm-badge`,w(`settings.permissions.builtin`)));else{let t=N(`div`,`perm-card-ops`);t.appendChild(vw(w(`settings.action.edit`),`btn-mini`,()=>n.onEdit(e))),t.appendChild(vw(w(`settings.action.delete`),`btn-mini danger`,()=>n.onDelete(e))),i.appendChild(t)}r.appendChild(i);let a=N(`div`,`perm-chips`);for(let t of xn(e))a.appendChild(N(`span`,`perm-chip `+t.tone,t.text));if(r.appendChild(a),e.writeRoots.length>0){let t=N(`div`,`perm-roots`);t.appendChild(N(`span`,`perm-roots-label`,w(`settings.permissions.extraRootsLabel`)));for(let n of e.writeRoots)t.appendChild(N(`code`,`perm-root`,n));r.appendChild(t)}let o=wn(e);return o!==``&&r.appendChild(N(`div`,`perm-card-note`,o)),r}function bw(e,t){let n=document.createElement(`div`),r=An();if(r===null)n.appendChild(N(`div`,`side-note`,w(`settings.permissions.unavailable`)));else{for(let e of r.builtin)n.appendChild(yw(e,!0,t));for(let e of r.custom)n.appendChild(yw(e,!1,t));r.custom.length===0&&n.appendChild(N(`div`,`side-note`,w(`settings.permissions.emptyCustom`)))}e.replaceChildren(...n.childNodes)}function xw(e){let t=An();e.textContent=t===null?``:Sn(t.max)}var Sw=`#settingsPermissions`,Cw=!1;function ww(e){return document.querySelector(e)}function Tw(){return ww(Sw+` .perm-list`)}function Ew(){return ww(Sw+` .perm-editor`)}function Dw(e,t){let n=ww(Sw+` .perm-status`);n!==null&&(n.className=`perm-status`+(e===``?``:t?` ok`:` err`),n.textContent=e)}function Ow(e){let t=Ew();t!==null&&_w(t,e,{onSettled:e=>{gw(t),Dw(e.text,e.ok)},onCancel:()=>gw(t)})}async function kw(e){if(!await Yv({title:w(`settings.permissions.deleteTitle`),message:w(`settings.permissions.deleteConfirm`,{name:e.label||e.id}),okLabel:w(`settings.action.delete`),danger:!0}))return;let t=await nw(e.id);Dw(t.text,t.ok)}function Aw(){let e=Tw();e!==null&&bw(e,{onEdit:e=>Ow(e),onDelete:e=>void kw(e)})}function jw(){let e=ww(Sw+` .perm-max`);e!==null&&xw(e)}function Mw(e){let t=document.createElement(`div`),n=N(`div`,`perm-toolbar`);n.appendChild(N(`span`,`perm-max`,``));let r=N(`button`,`btn-mini`,w(`settings.permissions.newPreset`));r.type=`button`,r.id=`btnNewPreset`,r.addEventListener(`click`,()=>Ow(null)),n.appendChild(r),t.append(n,N(`div`,`perm-status`),N(`div`,`perm-list`),N(`div`,`perm-editor hidden`)),e.replaceChildren(...t.childNodes)}function Nw(){Cw||(Cw=!0,window.addEventListener(Tn,()=>{jw(),Aw()}))}async function Pw(){Mw(M(Sw)),Nw(),jw(),An()!==null&&Aw();try{await Ln(!0),jw(),Aw()}catch(e){Dw(w(`settings.permissions.unavailableReason`,{reason:O(e,w(`settings.common.retryLater`))}),!1)}}function Fw(e){return typeof e==`string`?e.trim():``}function Iw(e){if(Array.isArray(e))return e;if(typeof e!=`object`||!e)return[];let t=e.plugins;return Array.isArray(t)?t:[]}function Lw(e){let t=[];for(let n of Iw(e)){if(typeof n!=`object`||!n)continue;let e=n,r=Fw(e.name)||Fw(e.id);r!==``&&t.push({name:r,version:Fw(e.version),note:Fw(e.description)})}return t}async function Rw(){return Lw(await j.plugins())}var zw=`#settingsPlugins`;function Bw(e,t){let n=N(`section`,`plug-sec`),r=N(`header`,`plug-sec-head`);return r.appendChild(N(`h5`,`plug-sec-title`,e)),r.appendChild(N(`span`,`plug-sec-note`,t)),n.appendChild(r),n}function Vw(e,t){let n=N(`div`,`plug-row`);n.dataset.id=e.id;let r=N(`div`,`plug-row-main`);r.appendChild(N(`div`,`plug-row-label`,e.label)),r.appendChild(N(`div`,`plug-row-hint`,e.hint)),n.appendChild(r);let i=N(`label`,`plug-switch`),a=document.createElement(`input`);return a.type=`checkbox`,a.className=`plug-switch-input`,a.checked=Sx(e.id),a.addEventListener(`change`,()=>{let n=a.checked,r=Cx(e.id,n);r.ok||(a.checked=!n),t(r.text,r.ok)}),i.appendChild(a),i.appendChild(N(`span`,`plug-switch-track`)),n.appendChild(i),n}function Hw(e){let t=N(`div`,`plug-host`);t.dataset.name=e.name;let n=N(`div`,`plug-row-main`),r=N(`div`,`plug-row-label`,e.name);return e.version!==``&&r.appendChild(N(`span`,`plug-host-ver`,e.version)),n.appendChild(r),e.note!==``&&n.appendChild(N(`div`,`plug-row-hint`,e.note)),t.appendChild(n),t.appendChild(N(`span`,`plug-badge`,w(`settings.plugins.hostBadge`))),t}function Uw(e,t){let n=document.createElement(`div`);if(t.length===0)n.appendChild(N(`div`,`plug-empty`,w(`settings.plugins.hostEmpty`)));else for(let e of t)n.appendChild(Hw(e));e.replaceChildren(...n.childNodes)}async function Ww(){let e=M(zw),t=N(`div`,`plug-status`),n=(e,n)=>{t.className=`plug-status`+(e===``?``:n?` ok`:` err`),t.textContent=e},r=Bw(w(`settings.plugins.clientTitle`),w(`settings.plugins.clientNote`)),i=N(`div`,`plug-list`);for(let e of vx())i.appendChild(Vw(e,n));r.appendChild(i),r.appendChild(t);let a=N(`div`,`plug-host-list`),o=Bw(w(`settings.plugins.hostTitle`),w(`settings.plugins.hostNote`));o.appendChild(a);let s=document.createElement(`div`);s.append(r,o),e.replaceChildren(...s.childNodes);try{Uw(a,await Rw())}catch(e){Uw(a,[]),console.warn(`[plugins] `+O(e,w(`settings.plugins.hostUnavailable`)))}}function Gw(e){e.documentElement.lang=oe()===`zh`?`zh-CN`:`en`}function Kw(e){for(let t of e.querySelectorAll(`[data-i18n]`)){let e=t.getAttribute(`data-i18n`);e&&(t.textContent=w(e))}for(let t of e.querySelectorAll(`[data-i18n-title]`)){let e=t.getAttribute(`data-i18n-title`);e&&t.setAttribute(`title`,w(e))}for(let t of e.querySelectorAll(`[data-i18n-aria-label]`)){let e=t.getAttribute(`data-i18n-aria-label`);e&&t.setAttribute(`aria-label`,w(e))}}var qw=()=>{try{location.reload()}catch{}};function Jw(){qw()}var Yw=new Set,Xw=!1;function Zw(){let e=N(`div`,`cfg-field i18n-field`);e.appendChild(N(`span`,`cfg-label`,w(`common.language`)));let t=N(`select`,`cfg-input`);for(let e of[`zh`,`en`]){let n=N(`option`,null,ce(e));n.value=e,t.appendChild(n)}return t.value=oe(),t.addEventListener(`change`,()=>{let e=t.value;e!==oe()&&(C(e),Jw())}),e.appendChild(t),e.appendChild(N(`span`,`cfg-hint`,w(`common.language.hint`))),Yw.add(e),e}function Qw(e){let t=e.querySelector(`.cfg-label`),n=e.querySelector(`.cfg-hint`),r=e.querySelector(`select`);t&&(t.textContent=w(`common.language`)),n&&(n.textContent=w(`common.language.hint`)),r instanceof HTMLSelectElement&&(r.value=oe())}function $w(e){let t=document.createElement(`div`);t.appendChild(Zw()),e.replaceChildren(...Array.from(t.childNodes))}function eT(){Xw||(Xw=!0,tT(),se(()=>{tT();for(let e of Yw)e.isConnected&&Qw(e)}))}function tT(){Kw(document),Gw(document)}var nT=M(`#settingsPage`),rT=M(`#settingsConfig`),iT=M(`#settingsHint`),aT=[`low`,`high`,`max`],oT={select:(e,t)=>{let n=N(`select`,`cfg-input`);for(let t of e){let e=N(`option`,null,t.label);e.value=t.value,n.appendChild(e)}let r=t??``;if(r!==``&&!e.some(e=>e.value===r)){let e=N(`option`,null,r+w(`settings.suffix.current`));e.value=r,n.appendChild(e)}return n.value=r,n},text:(e,t,n=`text`)=>{let r=N(`input`,`cfg-input`);return r.type=n,r.value=e,t&&(r.placeholder=t),r},num:(e,t)=>{let n=N(`input`,`cfg-input`);return n.type=`number`,n.min=`0`,n.placeholder=t,e!=null&&(n.value=String(e)),n},field:(e,t,n)=>{let r=N(`label`,`cfg-field`);return r.appendChild(N(`span`,`cfg-label`,e)),r.appendChild(t),n&&r.appendChild(N(`span`,`cfg-hint`,n)),r}};function sT(e){let t=e.trim();if(t===``)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:NaN}function cT(e,t,n){n.replaceChildren();let r=N(`form`,`cfg-form`),i=Array.isArray(e.available?.models)?e.available.models:[],a=Array.isArray(e.available?.efforts)?e.available.efforts:[],o=i.length?oT.select(i.map(e=>({value:e.id,label:e.name})),e.model??null):oT.text(e.model??``,w(`settings.config.modelName`));r.appendChild(oT.field(w(`settings.field.model`),o,i.length?``:w(`settings.config.modelNameHint`)));let s=[{value:``,label:w(`settings.config.effortStandard`)}];for(let e of a.length?a:aT)s.push({value:e,label:e});let c=oT.select(s,e.reasoning_effort??null);r.appendChild(oT.field(w(`settings.config.effort`),c,a.length?w(`settings.config.effortHint`):w(`settings.config.effortManual`)));let l=oT.text(e.base_url??``,`https://…/v1`);r.appendChild(oT.field(`Base URL`,l));let u=oT.text(``,w(`settings.config.apiKeyPlaceholder`),`password`);r.appendChild(oT.field(`API Key`,u,w(`settings.config.apiKeyHint`)));let d=e.context_window??e.context_window_tokens??t,f=oT.num(d,w(`settings.config.contextWindowPlaceholder`));r.appendChild(oT.field(w(`settings.field.contextWindow`),f));let p=oT.num(e.max_output_tokens??null,w(`settings.config.noLimit`));r.appendChild(oT.field(w(`settings.field.maxOutputTokens`),p));let m=oT.num(e.max_steps??null,w(`settings.config.notSet`));r.appendChild(oT.field(w(`settings.field.maxSteps`),m));let h=N(`textarea`,`cfg-input cfg-sys`);h.rows=6,h.placeholder=w(`settings.config.systemPromptPlaceholder`),h.value=e.system_prompt??``,r.appendChild(oT.field(w(`settings.field.systemPrompt`),h,w(`settings.config.systemPromptHint`)));let g=N(`div`,`cfg-actions`),_=N(`button`,`btn btn-accent`,w(`settings.action.save`));_.type=`button`;let v=N(`button`,`btn btn-soft`,w(`settings.action.reload`));v.type=`button`,g.appendChild(_),g.appendChild(v),r.appendChild(g);let y=N(`div`,`cfg-status`);r.appendChild(y),n.appendChild(r);let b=(e,t)=>{let n=sT(e.value);if(Number.isNaN(n))throw y.className=`cfg-status err`,y.textContent=w(`settings.config.notAValidNumber`,{name:t}),Error(`bad number: `+t);return n};_.addEventListener(`click`,()=>{y.className=`cfg-status`,y.textContent=``;let t={},n=o.value.trim();n!==``&&n!==(e.model??``)&&(t.model=n);let r=l.value.trim();r!==``&&r!==(e.base_url??``)&&(t.base_url=r),u.value.trim()!==``&&(t.api_key=u.value.trim()),t.reasoning_effort=c.value===``?null:c.value,t.context_window=b(f,w(`settings.field.contextWindow`)),t.max_output_tokens=b(p,w(`settings.field.maxOutputTokens`)),t.max_steps=b(m,w(`settings.field.maxSteps`)),t.system_prompt=h.value,_.disabled=!0,_.textContent=w(`settings.config.saving`),j.saveConfig(t).then(e=>{y.className=`cfg-status ok`,y.textContent=e.ok===!1?w(`settings.config.saveFailedRetry`):w(`settings.config.saved`),e.ok!==!1&&window.dispatchEvent(new Event(`studio:config-saved`))}).catch(e=>{y.className=`cfg-status err`;let t=e;e instanceof D&&e.status===409?y.textContent=w(`settings.config.busySave`):e instanceof D&&(e.status===405||e.status===404)?y.textContent=w(`settings.config.unsupportedSave`):y.textContent=w(`settings.config.saveFailed`,{reason:t.message||String(e)})}).finally(()=>{_.disabled=!1,_.textContent=w(`settings.action.save`)})}),v.addEventListener(`click`,()=>{lT({refresh:!0})})}async function lT(e={}){let t=document.createElement(`div`),n;try{n=e.refresh===!0?await gt():await ht()}catch(e){t.appendChild(N(`div`,`side-note err`,w(`settings.config.unavailable`))),t.appendChild(N(`div`,`side-note`,e instanceof Error?e.message:String(e))),rT.replaceChildren(...t.childNodes),iT.textContent=``;return}let r=null;try{r=(await j.status())?.context_usage?.window??null}catch{}try{cT(n,r,t),iT.textContent=``,rT.replaceChildren(...t.childNodes)}catch(e){t.appendChild(N(`div`,`side-note err`,w(`settings.config.unavailable`))),t.appendChild(N(`div`,`side-note`,e instanceof Error?e.message:String(e))),rT.replaceChildren(...t.childNodes),iT.textContent=``}}var uT=[`general`,`config`,`tools`,`archive`,`providers`,`prompts`,`permissions`,`plugins`],dT=`config`;function fT(e){return M(`.settings-pane[data-pane="`+e+`"]`)}function pT(e){return M(`.settings-nav-item[data-page="`+e+`"]`)}var mT={};function hT(e){e===`general`?$w(M(`#settingsGeneral`)):e===`config`?lT():e===`tools`?hS():e===`archive`?JS(M(`#settingsArchive`),M(`#settingsArchiveCount`)):e===`providers`?jC():e===`prompts`?YC():e===`permissions`?Pw():Ww()}function gT(e){dT=e;for(let t of uT)fT(t).classList.toggle(`active`,t===e);for(let t of uT)pT(t).classList.toggle(`active`,t===e);mT[e]||(mT[e]=!0,hT(e))}function _T(e){hT(e)}function vT(){_T(dT)}var yT=null;function bT(){nT.classList.remove(`hidden`),yT||(yT=P(xT)),_T(`config`),gT(`config`)}function xT(){if(yT){let e=yT;yT=null,je(e),F(e)}nT.classList.add(`hidden`)}function ST(){M(`#btnConfig`).addEventListener(`click`,bT),M(`#btnSettingsClose`).addEventListener(`click`,xT),M(`#btnSettingsReload`).addEventListener(`click`,vT);for(let e of uT)pT(e).addEventListener(`click`,()=>gT(e));eT(),PC(),XC()}function CT(e,t){Rg(!1),Eg.clear(),e.renderTreeInto?e.renderTreeInto(t,null):e.loadTreeInto(t,null)}function wT(e){for(let t of e.querySelectorAll(`.sess-check`))t.checked=t.dataset.id!==void 0&&Eg.has(t.dataset.id);let t=e.querySelector(`.sess-batchbar`);t&&(t.querySelector(`.sess-batchbar-count`).textContent=w(`shell.tree.selectedCount`,{n:Eg.size}),t.classList.toggle(`active`,Eg.size>0))}async function TT(e,t){let n=Array.from(Eg);if(!n.length||!await Yv({title:w(`shell.tree.batchDeleteTitle`),message:w(`shell.tree.batchDeleteConfirm`,{n:n.length}),okLabel:w(`settings.action.delete`),danger:!0}))return;let r=new Map;for(let e of n){let n=TS({container:t,id:e,rowSel:`.sess-leaf`});n&&r.set(e,n)}let i=Vg();Hg(i.filter(e=>!n.includes(e.id??``)));try{let a=await j.batchDeleteSessions(n),o=yS(w(`settings.action.delete`),a);if(o===``)OS(n),CT(e,t),Q(w(`shell.tree.deletedCount`,{n:n.length}));else{let e=bS(a);OS(n.filter(t=>!e.includes(t)));for(let t of e)r.get(t)?.restore();Hg(i),Eg.clear();for(let t of e)Eg.add(t);wT(t),Q(o)}XS()}catch(e){for(let e of r.values())e.restore();Hg(i),wT(t),Q(w(`shell.tree.batchDeleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}function ET(e,t,n){DT();let r=e.getBoundingClientRect(),i=N(`div`,`sess-menu`);for(let e of n){let t=N(`button`,`sess-menu-item`+(e.danger?` danger`:``),e.label);t.type=`button`,e.disabled&&(t.disabled=!0,t.classList.add(`disabled`)),t.addEventListener(`click`,t=>{t.stopPropagation(),DT(),e.onPick()}),i.appendChild(t)}e.appendChild(i);let a=Math.max(0,Math.min(t.right-r.left-8,e.clientWidth-180)),o=Math.max(0,Math.min(t.bottom-r.top+2,e.clientHeight-60));i.style.left=a+`px`,i.style.top=o+`px`}function DT(){for(let e of document.querySelectorAll(`.sess-menu`))e.remove()}function OT(e,t,n){sm(t,n),Wg(t),R.selSession=t,Ox(e),kx(e),Q(n?.title?w(`shell.tree.switchedTo`,{title:n.title}):w(`shell.tree.switched`)),j.activateSession(t).then(e=>{e.ok===!1&&Q(w(`shell.tree.viewOpenActivateFailed`))}).catch(e=>{e instanceof D&&e.status===409?Q(w(`shell.tree.runningViewOpen`)):Q(w(`shell.tree.viewOpenActivateFailed`))})}async function kT(e,t,n,r){if(!await Yv({title:w(`shell.tree.archiveTitle`),message:w(`shell.tree.archiveConfirm`,{label:r}),okLabel:w(`shell.tree.archiveOk`)}))return;let i=TS({container:t,id:n,rowSel:`.sess-leaf`}),a=Vg();Hg(a.filter(e=>e.id!==n));try{let e=await j.archiveSession(n),t=yS(w(`shell.tree.archiveOk`),e);t===``?(DS(n),Q(w(`shell.tree.archived`,{label:r}))):(i?.restore(),Hg(a),Q(t)),XS()}catch(e){i?.restore(),Hg(a),Q(w(`shell.tree.archiveFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function AT(e,t,n,r){if(!await Yv({title:w(`shell.tree.deleteTitle`,{label:r}),message:w(`shell.tree.deleteConfirm`),okLabel:w(`settings.action.delete`),danger:!0}))return;let i=TS({container:t,id:n,rowSel:`.sess-leaf`}),a=Vg();Hg(a.filter(e=>e.id!==n));try{let e=await j.batchDeleteSessions([n]),t=yS(w(`settings.action.delete`),e);t===``?(DS(n),Q(w(`shell.tree.deletedSession`,{label:r}))):(i?.restore(),Hg(a),Q(t)),XS()}catch(e){i?.restore(),Hg(a),Q(w(`shell.tree.deleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function jT(e,t,n,r){let i=window.prompt(w(`shell.tree.renamePrompt`),r);if(i===null)return;let a=i.trim();if(a!==``&&a!==r)try{await j.renameSession(n,a),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.renameFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function MT(e,t,n){let r=window.prompt(w(`shell.tree.branchPrompt`),``);if(r!==null)try{let i=await j.branchSession(n,r.trim()===``?void 0:r.trim());if(i.ok===!1){Q(w(`shell.tree.branchFailedRetry`));return}let a=i.id??i.branch;a&&(R.selSession=a),Q(w(`shell.tree.branched`)),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.branchFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function NT(e,t,n){if(await Yv({title:w(`shell.tree.deleteWsTitle`,{name:n}),message:w(`shell.tree.deleteConfirm`),okLabel:w(`settings.action.delete`),danger:!0}))try{await j.deleteWorkspace(n),Q(w(`shell.tree.wsDeleted`,{name:n})),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.deleteFailed`,{reason:e instanceof Error?e.message:String(e)}))}}async function PT(e,t,n){let r=window.prompt(w(`shell.tree.renameWsPrompt`),n);if(r===null)return;let i=r.trim();if(i!==``&&i!==n)try{await j.renameWorkspace(n,i),e.loadTreeInto(t,null)}catch(e){Q(w(`shell.tree.renameFailed`,{reason:e instanceof Error?e.message:String(e)}))}}function FT(e,t=!0){let n={workspace:e.workspace,title:e.title},r=e.prompt??``;if(r!==``&&(n.prompt=r),!t)return n;let i=e.model??``;return i!==``&&(n.model=i),e.mode===`execution`&&(n.mode=e.mode),n}var IT=new Set([`text`,`search`,`url`,`tel`,`email`,`password`,`number`]);function LT(e){if(e.key!==`Enter`||e.shiftKey)return!1;let t=e.target;if(!t||typeof t.tagName!=`string`||t.tagName.toUpperCase()!==`INPUT`)return!1;let n=typeof t.type==`string`?t.type.toLowerCase():`text`;return IT.has(n===``?`text`:n)}function RT(e,t){let n=N(`div`,`modal-scrim`),r=N(`div`,`modal-card`);r.appendChild(N(`div`,`modal-card-title`,w(`shell.new.title`)));let i=N(`input`,`cfg-input`);i.placeholder=w(`shell.new.titlePlaceholder`);let a=N(`label`,`prov-field`);a.appendChild(N(`span`,`prov-field-label`,w(`shell.field.title`))),a.appendChild(i),r.appendChild(a);let o=document.createElement(`select`);o.className=`cfg-input`;let s=document.createElement(`option`);s.value=``,s.textContent=w(`shell.new.rootWorkspace`),o.appendChild(s);for(let e of zg()){let t=document.createElement(`option`);t.value=e.name,t.textContent=e.name,o.appendChild(t)}t&&(o.value=t);let c=N(`label`,`prov-field`);c.appendChild(N(`span`,`prov-field-label`,w(`settings.scope.workspace`))),c.appendChild(o),r.appendChild(c);let l=document.createElement(`select`);l.className=`cfg-input`;let u=document.createElement(`option`);u.value=``,u.textContent=w(`shell.new.followDefault`),l.appendChild(u);let d=N(`label`,`prov-field`);d.appendChild(N(`span`,`prov-field-label`,w(`settings.field.model`))),d.appendChild(l),r.appendChild(d),j.config().then(e=>{let t=e.available?.models??[];for(let e of t){let t=document.createElement(`option`);t.value=e.id;let n=e.name||e.id,r=(e.provider??``).trim();t.textContent=(r?r+` · `:``)+e.id+(n===e.id?``:`(`+n+`)`),l.appendChild(t)}if(!t.length){let e=document.createElement(`option`);e.value=``,e.textContent=w(`shell.new.noModels`),e.disabled=!0,l.appendChild(e)}}).catch(()=>{let e=document.createElement(`option`);e.value=``,e.textContent=w(`shell.new.modelsUnavailable`),e.disabled=!0,l.appendChild(e)});let f=document.createElement(`select`);f.className=`cfg-input`;for(let e of Kt()){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,f.appendChild(t)}f.value=`standard`;let p=N(`label`,`prov-field`);p.appendChild(N(`span`,`prov-field-label`,w(`shell.field.mode`))),p.appendChild(f),r.appendChild(p);let m=N(`label`,`prov-field`);m.appendChild(N(`span`,`prov-field-label`,w(`shell.field.prompt`)));let h=document.createElement(`select`);h.className=`cfg-input`;let g=document.createElement(`option`);g.value=``,g.textContent=w(`shell.new.followDefault`),h.appendChild(g),m.appendChild(h),m.style.display=`none`,r.appendChild(m),j.prompts().then(e=>{let t=e.prompts??[];if(t.length){for(let e of t){let t=document.createElement(`option`);t.value=e.id,t.textContent=e.name+` (`+(e.scope===`global`?w(`settings.scope.global`):w(`settings.scope.workspace`))+`)`+(e.is_default?` · `+w(`settings.tag.default`):``),h.appendChild(t)}m.style.display=``}}).catch(()=>{});let _=N(`div`,`ws-fs-status`);r.appendChild(_);let v=N(`div`,`modal-card-actions`),y=N(`button`,`btn btn-soft`,w(`settings.action.cancel`));y.type=`button`;let b=N(`button`,`btn btn-accent`,w(`shell.action.create`));b.type=`button`;let x=null,ee=()=>{x&&(F(x),x=null),n.remove()};x=P(ee),y.addEventListener(`click`,ee),b.addEventListener(`click`,()=>{let t=i.value.trim();if(!t){_.className=`ws-fs-status err`,_.textContent=w(`shell.new.titleRequired`),i.focus();return}let n=o.value===``?null:o.value,r=l.value===``?void 0:l.value,a=h.value===``?void 0:h.value;b.disabled=!0,b.textContent=w(`shell.new.creating`);let s=f.value,c=e=>j.createSession(FT({workspace:n,title:t,model:r,prompt:a,mode:s},e));c(!0).catch(e=>{let t=e;if((r!==void 0||s!==`standard`)&&t&&typeof t.status==`number`&&t.status>=400&&t.status<500)return c(!1);throw e}).then(async n=>{if(n.ok===!1)throw Error(O(n.error,w(`shell.new.rejected`)));let r=n.id;if(!r)try{let e=((await j.sessions()).sessions??[]).filter(e=>e.title===t);e.sort((e,t)=>(t.modified??0)-(e.modified??0)),r=e[0]?.id}catch{r=void 0}if(!r){_.className=`ws-fs-status err`,_.textContent=w(`shell.new.createdRefresh`),ee(),e.loadSessions();return}sm(r,{kind:`session`,title:t}),Wg(r),R.selSession=r,Q(w(`shell.new.createdOpened`,{title:t})),j.activateSession(r).then(e=>{e.ok===!1&&Q(w(`shell.tree.viewOpenActivateFailed`))}).catch(e=>{Q(w(`shell.tree.viewOpenFailed`,{reason:O(e,w(`shell.new.activateFailed`))}))}),ee(),e.loadSessions()}).catch(e=>{_.className=`ws-fs-status err`,_.textContent=w(`shell.new.failed`,{reason:e instanceof Error?e.message:String(e)}),b.disabled=!1,b.textContent=w(`shell.action.create`)})}),r.addEventListener(`keydown`,e=>{LT(e)&&(e.preventDefault(),b.disabled||b.click())}),v.appendChild(y),v.appendChild(b),r.appendChild(v),n.appendChild(r),document.body.appendChild(n),i.focus()}function zT(e){Gm({title:w(`shell.new.wsTitle`),note:w(`shell.new.wsNote`),confirmLabel:w(`shell.action.create`),busyLabel:w(`shell.new.wsBusy`),fallbackNote:w(`shell.new.wsFallback`),onPick:(t,n)=>{n.setBusy(!0),j.createWorkspaceByPath(t).then(r=>{if(r.ok===!1){n.status.className=`ws-fs-status err`,n.status.textContent=w(`shell.new.wsRegisterFailed`,{reason:O(r.error,w(`shell.new.wsCheckPath`))}),n.setBusy(!1);return}Q(w(`shell.new.wsRegistered`,{path:t})),n.close(),e.loadSessions()}).catch(e=>{n.status.className=`ws-fs-status err`,n.status.textContent=w(`shell.new.wsRegisterFailed`,{reason:O(e,w(`shell.new.wsCheckPath`))}),n.setBusy(!1)})}})}function BT(e){let t=e.parentSessionId??e.parent_session??e.parent;return typeof t==`string`&&t.trim()!==``?t.trim():null}function VT(e){return e.kind===`worker`||(e.id??``).startsWith(`worker:`)}function HT(e){let t=(e.workspace??``).trim();return t===``?`root`:t}function UT(e){let t=e.lastIndexOf(`/`);return t>=0?e.slice(t+1):e}function WT(e){let t=Gg();return t===``||e.toLowerCase().includes(t)}function GT(e){let t=[...e];return qg()===`name`?(t.sort((e,t)=>(e.title||``).localeCompare(t.title||``,`zh`)),t):(t.sort((e,t)=>{let n=typeof e.modified==`number`?e.modified:-1;return(typeof t.modified==`number`?t.modified:-1)-n}),t)}function KT(e){return e.filter(e=>e.kind===`worker`||(e.id??``).startsWith(`worker:`))}function qT(e){let t=(e.title??``).trim(),n=/^(W\d+)/.exec(t);if(n&&n[1])return n[1];let r=e.id??``,i=r.lastIndexOf(`/`);return i>=0?r.slice(i+1):r}function JT(e){return(e.title??``).trim().replace(/^W\d+\s*[·::-]\s*/,``)||UT(e.id??``)||(e.id??``)}function YT(e){return e.map(e=>[e.id??``,e.title??``,e.model??``,Fr(e.id??``)?`1`:`0`,String(e.events??``),BT(e)??``].join(``)).join(``)}function XT(e,t,n=t){let r=N(`button`,`btn btn-soft ws-newsess`);r.type=`button`,r.appendChild(Ex(`plus`)),r.appendChild(N(`span`,null,w(`shell.tree.newSession`))),r.addEventListener(`click`,()=>e.newSession()),n.appendChild(r);let i=N(`div`,`ws-toolrow`),a=N(`div`,`ws-search`);a.appendChild(Ex(`search`));let o=N(`input`,`ws-search-input`);o.placeholder=w(`shell.tree.searchPlaceholder`),o.value=Gg(),o.addEventListener(`input`,()=>{Kg(o.value.trim().toLowerCase());let n=Zg();n!==null&&window.clearTimeout(n),Qg(window.setTimeout(()=>void e.loadTreeInto(t,null),180))}),a.appendChild(o),i.appendChild(a);let s=N(`button`,`ws-toolbtn`);s.type=`button`,s.appendChild(Ex(`sort`)),s.appendChild(N(`span`,`ws-toolbtn-label`,qg()===`active`?w(`settings.tag.active`):w(`settings.field.name`))),s.title=w(`shell.tree.sortTitle`,{label:qg()===`active`?w(`shell.tree.sortRecent`):w(`settings.field.name`)}),s.addEventListener(`click`,()=>{Jg(qg()===`active`?`name`:`active`),e.loadTreeInto(t,null)}),i.appendChild(s);let c=N(`button`,`ws-toolbtn`);c.type=`button`,c.title=w(`shell.tree.newWorkspace`),c.appendChild(Ex(`folder-plus`)),c.addEventListener(`click`,()=>e.newWorkspace()),i.appendChild(c),n.appendChild(i),n.appendChild(N(`div`,`ws-divider`))}function ZT(e,t,n){let r=n.id??``,i=Lg(),a=r===Ug(),o=N(`div`,`sess-leaf`+(a?` active`:``)+(R.selSession===r?` sel`:``));if(o.dataset.id=r,!i){let e=N(`span`,`sess-dot`+(Fr(r)?` busy`:``));e.dataset.dot=r,bi(e,Fr(r)?w(`shell.tree.running`):w(`shell.tree.idle`)),o.appendChild(e)}let s=null;if(i){let e=N(`input`,`sess-check`);e.type=`checkbox`,e.dataset.id=r,e.checked=Eg.has(r),e.addEventListener(`change`,()=>{e.checked?Eg.add(r):Eg.delete(r),wT(t)}),o.appendChild(e),s=e}o.appendChild(Ex(`file`));let c=n.title||UT(r)||w(`shell.tree.unnamed`),l=N(`span`,`sess-leaf-name`,c);o.appendChild(l);let u=t_().get(r)??0;if(u>0){let e=N(`span`,`sess-worker-count`,`W`+u);e.title=w(`shell.tree.workerBadgeTitle`,{n:u}),o.appendChild(e)}let d=[];n.events!==void 0&&d.push(w(`shell.tree.events`,{n:n.events})),d.length&&o.appendChild(N(`span`,`sess-leaf-meta`,d.join(` · `)));let f=N(`span`,`sess-leaf-grant hidden`);if(f.dataset.grantMark=r,o.appendChild(f),Ax(f,cb(r)),bi(o,c+w(i?`shell.tree.clickCheck`:`shell.tree.clickOpen`)),!i){let i=N(`button`,`sess-kebab`,`⋯`);i.type=`button`,i.title=w(`shell.tree.sessionOps`),i.addEventListener(`click`,o=>{o.stopPropagation(),ET(t,i.getBoundingClientRect(),[{label:w(a?`shell.tree.currentSession`:`shell.tree.open`),disabled:a,onPick:()=>OT(t,r,{kind:n.kind===`worker`?`worker`:`session`,title:n.title})},{label:w(`shell.tree.rename`),onPick:()=>void jT(e,t,r,n.title||UT(r))},{label:w(`shell.tree.archiveOk`),onPick:()=>void kT(e,t,r,c)},{label:w(`shell.tree.branch`),onPick:()=>void MT(e,t,r)},{label:w(`settings.action.delete`),danger:!0,onPick:()=>void AT(e,t,r,c)}])}),o.appendChild(i)}return o.addEventListener(`click`,e=>{if(Lg()){if(s===null||e.target===s)return;s.checked=!s.checked,s.checked?Eg.add(r):Eg.delete(r),wT(t);return}OT(t,r,{kind:n.kind===`worker`?`worker`:`session`,title:n.title})}),o}function QT(e,t,n,r){let i=N(`div`,`ws-node`),a=document.createElement(`details`);a.className=`ws-details`,a.dataset.ws=n,a.open=!0;let o=document.createElement(`summary`);o.className=`ws-head`,o.appendChild(Ex(`folder`)),o.appendChild(N(`span`,`ws-name`,n)),o.appendChild(N(`span`,`ws-count`,String(r.length)));let s=N(`button`,`sess-kebab`,`⋯`);s.type=`button`,s.title=w(`shell.tree.workspaceOps`),s.addEventListener(`click`,r=>{r.stopPropagation(),ET(t,s.getBoundingClientRect(),[{label:w(`shell.tree.newSession`),onPick:()=>e.newSession(n)},{label:w(`shell.tree.rename`),onPick:()=>void PT(e,t,n)},{label:w(`shell.tree.batchDeleteSessions`),onPick:()=>{Rg(!0),Eg.clear(),e.loadTreeInto(t,null)}},{label:w(`shell.tree.deleteWorkspace`),danger:!0,onPick:()=>void NT(e,t,n)}])}),o.appendChild(s),a.appendChild(o);let c=N(`div`,`ws-body`);for(let n of GT(r))c.appendChild(ZT(e,t,n));return a.appendChild(c),i.appendChild(a),i}function $T(e,t,n=t){let r=N(`div`,`sess-batchbar`);r.appendChild(N(`span`,`sess-batchbar-count`,w(`shell.tree.selectedZero`)));let i=N(`button`,`btn btn-danger btn-mini`,w(`shell.tree.deleteSelected`));i.type=`button`,i.addEventListener(`click`,()=>void TT(e,t));let a=N(`button`,`btn-mini`,w(`settings.action.cancel`));a.type=`button`,a.addEventListener(`click`,()=>CT(e,t)),r.appendChild(i),r.appendChild(a),n.appendChild(r)}function eE(e,t,n){let r=t.id??``,i=Fr(r),a=N(`div`,`ws-worker-row`+(n?` child`:``)+(jr()===r?` active`:``));a.dataset.id=r,a.appendChild(N(`span`,`sess-dot`+(i?` busy`:``))),a.appendChild(N(`span`,`ws-worker-wid`,qT(t))),a.appendChild(N(`span`,`ws-worker-title`,JT(t)));let o=N(`span`,`ws-worker-state`+(i?` busy`:``),w(i?`shell.tree.running`:`shell.tree.idle`));a.appendChild(o);let s=[];return t.model&&s.push(String(t.model)),t.events!==void 0&&s.push(w(`shell.tree.events`,{n:t.events})),s.length&&a.appendChild(N(`span`,`ws-worker-meta`,s.join(` · `))),a.title=JT(t)+(t.model?` · `+t.model:``)+w(`shell.worker.openHint`),a.addEventListener(`click`,()=>{OT(document.getElementById(`sessionTree`)??e,r,{kind:`worker`,title:t.title||r})}),a}function tE(e,t,n){let r=document.createElement(`details`);r.className=`ws-worker-details`,r.open=n;let i=document.createElement(`summary`);i.className=`ws-worker-summary`,i.appendChild(N(`span`,null,w(`shell.worker.title`))),i.appendChild(N(`span`,`ws-worker-count`,String(t.length))),r.appendChild(i);let a=new Map,o=[];for(let e of t){let t=BT(e);if(!t){o.push(e);continue}let n=a.get(t);n?n.push(e):a.set(t,[e])}let s=new Set;for(let e of Vg()){let t=e.id??``;t&&a.has(t)&&s.add(t)}for(let e of a.keys())s.add(e);if(s.size===0)for(let t of o)r.appendChild(eE(e,t,!1));else{for(let t of s){let n=a.get(t)??[],i=Vg().find(e=>e.id===t),o=N(`div`,`ws-worker-parent`);o.appendChild(N(`span`,`ws-lineage-mark`,`└`));let s=N(`span`,`ws-worker-parent-name`,i?.title||UT(t));o.appendChild(s),o.appendChild(N(`span`,`ws-worker-count`,String(n.length))),o.title=w(`shell.worker.parentHint`),o.addEventListener(`click`,()=>{OT(document.getElementById(`sessionTree`)??e,t,{kind:`session`,title:i?.title})}),r.appendChild(o);for(let t of n)r.appendChild(eE(e,t,!0))}if(o.length){let t=N(`div`,`ws-worker-parent`);t.appendChild(N(`span`,`ws-lineage-mark`,`·`)),t.appendChild(N(`span`,`ws-worker-parent-name`,w(`shell.worker.unlinked`))),r.appendChild(t);for(let t of o)r.appendChild(eE(e,t,!0))}}e.replaceChildren(r)}async function nE(e){if(!e.isConnected)return;let t;try{t=(await j.sessions()).sessions??[]}catch{return}let n=KT(t),r=e.querySelector(`.ws-worker-host`);if(!r)return;let i=YT(n);if(i===$g()){kx(e);return}let a=r.querySelector(`.ws-worker-details`)?.open??!0;e_(i),n.length?tE(r,n,a):r.replaceChildren()}function rE(e){Yg()===null&&Xg(window.setInterval(()=>{nE(e)},Ig))}function iE(){let e=Yg();e!==null&&(window.clearInterval(e),Xg(null))}async function aE(e,t){DT(),t&&(t.textContent=`…`);try{let e=await j.workspaces();Bg(e.workspaces??[]),e.active_session&&Wg(e.active_session)}catch{Bg([])}try{let e=await j.sessions();Hg(e.sessions??[]);for(let e of Vg()){let t=e.id??``;t&&(Tr(t,{kind:e.kind===`worker`?`worker`:e.kind===`session`?`session`:void 0,title:e.title,model:e.model,workspace:e.workspace??void 0}),typeof e.busy==`boolean`&&zr(t,e.busy))}let t=(e.sessions??[]).find(e=>e.active===!0),n=jr();n?Wg(n):t?.id&&Wg(t.id)}catch(n){iE();let r=document.createElement(`div`);r.appendChild(N(`div`,`side-note err`,w(`shell.sessions.unavailable`))),r.appendChild(N(`div`,`side-note`,n instanceof Error?n.message:String(n))),e.replaceChildren(...r.childNodes),t&&(t.textContent=`—`);return}sE(e,t)}function oE(e,t){sE(e,t)}function sE(e,t){DT();let n=new Map;for(let t of e.querySelectorAll(`.ws-details`))n.set(t.dataset.ws??``,t.open);let r=document.activeElement?.classList.contains(`ws-search-input`)??!1,i=document.createElement(`div`),a=Vg().filter(e=>!VT(e)),o=new Set;for(let e of a)e.archived||o.add(HT(e));for(let e of o)zg().some(t=>t.name===e)||zg().push({name:e});zg().sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),t&&(t.textContent=String(a.filter(e=>e.archived!==!0).length));let s=KT(Vg());n_(new Map);for(let e of s){let t=BT(e);if(!t)continue;let n=t_();n.set(t,(n.get(t)??0)+1)}XT(dE,e,i);let c=N(`div`,`ws-tree`),l=zg().filter(e=>WT(e.name)||a.some(t=>!t.archived&&HT(t)===e.name&&WT(t.title??t.id??``))),u=0;for(let t of l){let n=a.filter(e=>!e.archived&&HT(e)===t.name&&WT(e.title??e.id??``));(WT(t.name)||n.length)&&(c.appendChild(QT(dE,e,t.name,n)),u+=n.length)}u||c.appendChild(N(`div`,`side-note`,Gg()?w(`shell.sessions.noMatch`):w(`shell.sessions.empty`))),i.appendChild(c),Lg()&&$T(dE,e,i);let d=N(`div`,`ws-worker-host`);i.appendChild(d),e_(YT(s)),s.length?(tE(d,s,!0),rE(e)):iE(),e.replaceChildren(...i.childNodes);for(let t of e.querySelectorAll(`.ws-details`)){let e=t.dataset.ws??``;n.has(e)&&(t.open=n.get(e)??!0)}if(r){let t=e.querySelector(`.ws-search-input`);t&&t.focus()}kx(e),zx(),Cm(Vg()),jx(e),db(a.filter(e=>!e.archived).map(e=>e.id??``))}function cE(){return aE(M(`#sessionTree`),M(`#sessionCount`))}function lE(e){RT(dE,e)}function uE(){zT(dE)}var dE={newSession:e=>lE(e),newWorkspace:()=>uE(),loadTreeInto:(e,t)=>aE(e,t),renderTreeInto:(e,t)=>oE(e,t),loadSessions:()=>cE()};function fE(){document.addEventListener(`click`,e=>{(!(e.target instanceof Element)||!e.target.closest(`.sess-menu`))&&DT()}),window.addEventListener($y,()=>{let e=document.getElementById(`sessionTree`);e&&jx(e)}),Vr(()=>{let e=document.getElementById(`sessionTree`);e&&(kx(e),e.querySelector(`.ws-worker-host`)&&nE(e))}),cE()}var pE=[],mE=new Set,hE=0,gE=null;function _E(){for(let e of mE)e()}function vE(e){return mE.add(e),()=>mE.delete(e)}function yE(){return pE}function bE(e){return pE.find(t=>t.id===e)}function xE(){return gE}function SE(e){gE!==e&&(gE=e,_E())}function CE(e,t){return w(e===`files`?`chat.wb.menu.files`:e===`terminal`?`chat.wb.menu.terminal`:`chat.wb.menu.browser`)+` `+String(t)}function wE(e){return e===`right`?420:260}function TE(e,t=`right`){hE+=1;let n=pE.filter(t=>t.kind===e).length+1,r={id:`wb`+String(hE),kind:e,title:CE(e,n),dock:t,size:wE(t),seq:0};return pE.push(r),gE=r.id,_E(),r}function EE(e){let t=pE.findIndex(t=>t.id===e);t<0||(pE.splice(t,1),gE===e&&(gE=pE.length>0?pE[pE.length-1].id:null),_E())}function DE(e,t){let n=bE(e);n&&n.dock!==t&&(n.dock=t,n.size=wE(t),_E())}function OE(e,t){let n=bE(e);if(!n)return;let r=Math.max(160,Math.min(Math.round(t),1200));n.size!==r&&(n.size=r,_E())}function kE(e){let t=bE(e);return t?(t.seq+=1,t.seq):-1}function AE(e,t){return bE(e)?.seq===t}function jE(e){return e===null?`—`:e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`}function ME(e){if(e===null)return`—`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`—`;let n=e=>(e<10?`0`:``)+String(e);return t.getFullYear()+`-`+n(t.getMonth()+1)+`-`+n(t.getDate())+` `+n(t.getHours())+`:`+n(t.getMinutes())}function NE(e){let t=Pm(e);return t===`markdown`||t===`diff`||t===`code`?t:`code`}function PE(e,t){let n=Hm(e,t);gh({candidate:{path:n,kind:NE(n),source:`label`},loadFull:async()=>{try{let e=await j.fsRead(n);return e.error!==void 0&&e.error!==``?{degraded:e.error}:e.kind===`binary`?{degraded:w(`chat.preview.degradeBinary`),badge:w(`chat.preview.badgeBinary`)}:{text:e.text,truncated:e.truncated===!0}}catch(e){return{degraded:O(e,w(`chat.preview.degradeReadFailed`))}}}})}function FE(e){let t=e.data;if(t&&typeof t.path==`string`)return t;let n={path:i_(),selected:null};return e.data=n,n}async function IE(e,t,n,r){let i=FE(t);if(i.path===``){e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.noWorkspace`)));return}let a=i.path,o;try{o=await j.fsList(a)}catch{if(!r(t.id,n))return;e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.listUnavailable`)));return}if(!r(t.id,n))return;if(o.error!==void 0&&o.error!==``){e.replaceChildren(N(`div`,`wb-notice`,w(`chat.wb.dirOpenFailed`,{reason:o.error})));return}let s=o.entries??[],c=document.createElement(`div`),l=N(`div`,`wb-crumbs`),u=N(`button`,`wb-crumb`,w(`chat.wb.up`));u.type=`button`,u.addEventListener(`click`,()=>{i.path=Um(a),i.selected=null,IE(e,t,kE(t.id),r)}),l.appendChild(u);let d=N(`span`,`wb-crumb wb-crumb-cur`,a);d.title=a,l.appendChild(d),c.appendChild(l),o.truncated===!0&&c.appendChild(N(`div`,`wb-notice`,w(`chat.wb.dirTruncated`)));let f=N(`div`,`wb-list`);s.length===0&&f.appendChild(N(`div`,`wb-notice`,w(`chat.wb.dirEmpty`)));for(let n of s)f.appendChild(LE(n,i,a,e,t,r));c.appendChild(f),e.replaceChildren(...Array.from(c.childNodes))}function LE(e,t,n,r,i,a){let o=N(`div`,`wb-row`+(e.type===`dir`?` dir`:``)+(t.selected===e.name?` sel`:``));return o.appendChild(N(`span`,`wb-icon`,e.type===`dir`?`📁`:`📄`)),o.appendChild(N(`span`,`wb-name`,e.name)),o.appendChild(N(`span`,`wb-size`,jE(e.size))),o.appendChild(N(`span`,`wb-time`,ME(e.mtime))),o.addEventListener(`click`,()=>{e.type===`dir`?(t.path=Hm(n,e.name),t.selected=null,IE(r,i,kE(i.id),a)):(t.selected=e.name,r.querySelectorAll(`.wb-row`).forEach(e=>e.classList.remove(`sel`)),o.classList.add(`sel`),PE(n,e.name))}),o}function RE(e){let t=e.data;if(t&&Array.isArray(t.lines))return t;let n={lines:[]};return e.data=n,n}function zE(e){let t=N(`div`,`wb-term-line`),n=N(`div`,`wb-term-cmd`);return n.appendChild(N(`span`,`wb-term-prompt`,`$`)),n.appendChild(N(`span`,`wb-term-cmdtext`,e.cmd)),t.appendChild(n),e.out!==``&&t.appendChild(N(`pre`,`wb-term-out`,e.out)),e.err!==``&&t.appendChild(N(`pre`,`wb-term-out err`,e.err)),t.appendChild(N(`div`,`wb-term-meta`+(e.failed?` err`:``),e.code+` · `+String(e.ms)+` ms`)),t}function BE(e,t,n){let r=RE(t),i=document.createElement(`div`);i.appendChild(N(`div`,`wb-term-note`,w(`chat.wb.term.note`)));let a=N(`div`,`wb-term-row`),o=N(`input`,`wb-term-input`);o.type=`text`,o.placeholder=w(`chat.wb.term.placeholder`);let s=N(`button`,`wb-btn wb-term-run`,w(`chat.wb.term.run`));s.type=`button`,a.appendChild(o),a.appendChild(s),i.appendChild(a);let c=N(`div`,`wb-term-outwrap`);for(let e of r.lines)c.appendChild(zE(e));i.appendChild(c),e.replaceChildren(...Array.from(i.childNodes));let l=()=>{let e=o.value.trim();e!==``&&(o.value=``,VE(t,e,kE(t.id),n,c))};s.addEventListener(`click`,l),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),l())})}async function VE(e,t,n,r,i){let a=N(`div`,`wb-term-line`);a.appendChild(N(`div`,`wb-term-meta`,w(`chat.wb.term.running`))),i.appendChild(a);let o;try{let e=await j.exec({command:t,timeout_ms:3e4});o={cmd:t,out:e.stdout??``,err:e.stderr??``,code:e.signal!==null&&e.signal!==``?w(`chat.wb.term.signal`,{signal:e.signal}):w(`chat.wb.term.exitCode`,{code:String(e.exit_code)}),ms:e.duration_ms,failed:e.exit_code!==0||e.signal!==null&&e.signal!==``}}catch(e){o={cmd:t,out:``,err:e instanceof D&&(e.status===404||e.status===405||e.status===501)?w(`chat.wb.term.unsupported`):O(e,w(`chat.wb.term.notStarted`)),code:w(`chat.tool.failed`),ms:0,failed:!0}}r(e.id,n)&&(RE(e).lines.push(o),a.replaceWith(zE(o)))}var HE=4e3;function UE(e){let t=e.trim();return t===``?``:/^https?:\/\//i.test(t)?t:`https://`+t}function WE(e,t,n){let r=t.data,i=r&&typeof r.url==`string`?r.url:``,a=document.createElement(`div`),o=N(`div`,`wb-url-row`),s=N(`input`,`wb-url-input`);s.type=`text`,s.placeholder=w(`chat.wb.urlPlaceholder`),s.value=i;let c=N(`button`,`wb-btn wb-url-open`,w(`chat.wb.open`));c.type=`button`,o.appendChild(s),o.appendChild(c),a.appendChild(o);let l=N(`div`,`wb-notice hidden`);a.appendChild(l);let u=N(`iframe`,`wb-frame`);u.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-popups`),a.appendChild(u);let d=N(`button`,`wb-btn wb-url-external hidden`,w(`chat.wb.openExternal`));d.type=`button`,a.appendChild(d),e.replaceChildren(...Array.from(a.childNodes));let f=(e,t)=>{l.textContent=e,l.classList.remove(`hidden`),d.classList.remove(`hidden`),d.addEventListener(`click`,()=>window.open(t,`_blank`,`noopener`))},p=e=>{let r=UE(e);if(r===``)return;t.data={url:r};let i=kE(t.id);l.classList.add(`hidden`),d.classList.add(`hidden`);let a=!1;u.addEventListener(`load`,()=>{n(t.id,i)&&(a=!0)}),u.src=r,window.setTimeout(()=>{n(t.id,i)&&!a&&f(w(`chat.wb.frameBlocked`),r)},HE)};c.addEventListener(`click`,()=>p(s.value)),s.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),p(s.value))}),i!==``&&p(i)}var GE=null,KE=null,qE=!1,JE=!1,YE=null;function XE(e){let t=N(`div`,`wb-head`);t.appendChild(N(`span`,`wb-title`,e.title));let n=N(`button`,`wb-btn wb-dock`,e.dock===`right`?`⇩`:`⇨`);n.type=`button`,n.title=e.dock===`right`?w(`chat.wb.dockBottom`):w(`chat.wb.dockRight`),n.setAttribute(`aria-label`,n.title),n.addEventListener(`click`,()=>DE(e.id,e.dock===`right`?`bottom`:`right`)),t.appendChild(n);let r=N(`button`,`wb-btn wb-close`,`×`);return r.type=`button`,r.title=w(`chat.wb.close`),r.setAttribute(`aria-label`,w(`chat.wb.close`)),r.addEventListener(`click`,()=>EE(e.id)),t.appendChild(r),t.addEventListener(`mousedown`,t=>{t.target.closest(`.wb-btn`)||eD(e,t)}),t}var ZE=null,QE=!1,$E=null;function eD(e,t){ZE={id:e.id,startDock:e.dock},window.addEventListener(`mousemove`,tD),window.addEventListener(`mouseup`,nD),t.preventDefault()}function tD(e){if(!ZE||QE)return;QE=!0;let t=e.clientY;requestAnimationFrame(()=>{if(QE=!1,!ZE||!GE)return;let e=GE.getBoundingClientRect(),n=t>e.top+e.height*.66?`bottom`:`right`;$E||($E=N(`div`,`wb-drop-hint`),GE.appendChild($E)),$E.className=`wb-drop-hint `+n,$E.textContent=w(n===`bottom`?`chat.wb.dockBottom`:`chat.wb.dockRight`)})}function nD(e){let t=ZE;if(ZE=null,window.removeEventListener(`mousemove`,tD),window.removeEventListener(`mouseup`,nD),$E&&($E.remove(),$E=null),!t||!GE)return;let n=GE.getBoundingClientRect(),r=e.clientY>n.top+n.height*.66?`bottom`:`right`;DE(t.id,r)}function rD(e){let t=N(`div`,`wb-resizer `+e.dock);return t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,e.dock===`right`?`vertical`:`horizontal`),t.addEventListener(`mousedown`,t=>{YE={id:e.id,startX:t.clientX,startY:t.clientY,startSize:e.size,dock:e.dock},window.addEventListener(`mousemove`,iD),window.addEventListener(`mouseup`,aD),t.preventDefault()}),t}function iD(e){if(!YE)return;let t=YE;JE||(JE=!0,requestAnimationFrame(()=>{if(JE=!1,!YE)return;let n=t.dock===`right`?t.startX-e.clientX:t.startY-e.clientY;OE(t.id,t.startSize+n)}))}function aD(){YE=null,window.removeEventListener(`mousemove`,iD),window.removeEventListener(`mouseup`,aD)}function oD(e){let t=N(`div`,`wb-panel`+(xE()===e.id?` focused`:``));t.dataset.panelId=e.id,t.appendChild(XE(e));let n=N(`div`,`wb-body`);return e.kind===`files`?IE(n,e,kE(e.id),AE):e.kind===`terminal`?BE(n,e,AE):e.kind===`browser`&&WE(n,e,AE),t.appendChild(n),t.addEventListener(`mousedown`,()=>SE(e.id)),t}function sD(){if(!GE||!KE)return;let e=yE(),t=e.filter(e=>e.dock===`bottom`),n=e.filter(e=>e.dock===`right`),r=document.createElement(`div`),i=t.reduce((e,t)=>Math.max(e,t.size),0);if(KE.style.setProperty(`--wb-bottom-h`,i+`px`),t.length>0){let e=N(`div`,`wb-zone bottom`);for(let n of t){e.appendChild(rD(n));let t=oD(n);t.style.height=n.size+`px`,t.style.flex=`1 1 0`,e.appendChild(t)}r.appendChild(e)}if(n.length>0){let e=N(`div`,`wb-zone right`);for(let t of n){let n=oD(t);n.style.width=t.size+`px`,e.appendChild(n),e.appendChild(rD(t))}r.appendChild(e)}KE.replaceChildren(...Array.from(r.childNodes)),KE.classList.toggle(`hidden`,e.length===0),GE.classList.toggle(`hidden`,e.length===0)}function cD(){if(qE)return;qE=!0;let e=document.getElementById(`main`);e&&(GE=N(`div`,`wb-host hidden`),KE=N(`div`,`wb-dock`),GE.appendChild(KE),e.appendChild(GE),vE(()=>sD()),sD())}var lD=null,uD=null;function dD(){lD&&lD.classList.add(`hidden`),uD!==null&&(F(uD),uD=null)}function fD(e){dD(),TE(e,`right`)}function pD(e,t,n){let r=N(`button`,`wb-menu-item`);return r.type=`button`,r.appendChild(N(`span`,`wb-menu-label`,t)),r.appendChild(N(`span`,`wb-menu-desc`,n)),r.addEventListener(`click`,()=>fD(e)),r}function mD(){if(lD===null&&(lD=N(`div`,`wb-menu hidden`),lD.id=`wbMenu`,lD.appendChild(pD(`files`,w(`chat.wb.menu.files`),w(`chat.wb.menu.filesDesc`))),lD.appendChild(pD(`terminal`,w(`chat.wb.menu.terminal`),w(`chat.wb.menu.terminalDesc`))),lD.appendChild(pD(`browser`,w(`chat.wb.menu.browser`),w(`chat.wb.menu.browserDesc`))),document.body.appendChild(lD)),!lD.classList.contains(`hidden`)){dD();return}lD.classList.remove(`hidden`),gD(),uD=P(dD),document.addEventListener(`pointerdown`,hD,!0)}function hD(e){let t=e.target;lD&&t instanceof Node&&(lD.contains(t)||t instanceof Element&&t.closest(`#btnWorkbench`))||(document.removeEventListener(`pointerdown`,hD,!0),dD())}function gD(){if(!lD)return;let e=document.getElementById(`btnWorkbench`),t=e?e.getBoundingClientRect():null;lD.style.top=(t?t.bottom+6:56)+`px`,lD.style.right=(t?Math.max(8,window.innerWidth-t.right):12)+`px`}function _D(){let e=document.getElementById(`btnWorkbench`);e&&e.addEventListener(`click`,()=>mD())}var vD=!1;function yD(){vD||(vD=!0,cD(),_D())}var bD=!1,$=null,xD=null,SD=null,CD=!1;function wD(e,t){if(e===null)return null;let n=e.nodeType===1?e:e.parentElement;return n?n.closest(t):null}function TD(e){return wD(e,`#inputbar`)!==null||wD(e,`textarea, input`)!==null}function ED(e){let t=e.querySelector(`.msg`),n=t?t.className:``;return n.includes(`user`)?`user`:n.includes(`tool`)?`tool`:n.includes(`inbox`)?`inbox`:`assistant`}function DD(e,t){if(t===`assistant`)return`Studio`;if(t===`inbox`)return w(`chat.msg.system`);if(t===`tool`){let t=e.querySelector(`.toolcard-name`)?.textContent??``;return t===``?w(`chat.quote.tool`):w(`chat.quote.toolNamed`,{name:t})}return e.querySelector(`.msg-caption .who`)?.textContent??w(`chat.user.you`)}function OD(e,t){let n=0;for(let r of Array.from(e.querySelectorAll(`.mcol`)))if(r.querySelector(`.msg.user`)&&(n+=1),r===t)break;return n>0?n:void 0}function kD(e,t){let n=ED(t);return{kind:n,session:e.id,turn:OD(e.el,t),label:DD(t,n)}}function AD(){$&&$.classList.add(`hidden`),SD=null,CD=!1,xD!==null&&(F(xD),xD=null)}function jD(e){if(!$)return;$.classList.remove(`hidden`);let t=fn({anchor:e,panel:{width:$.offsetWidth||48,height:$.offsetHeight||24},viewport:{width:window.innerWidth,height:window.innerHeight},gap:6,minHeight:0});$.style.top=t.top+`px`,$.style.left=t.left+`px`,xD===null&&(xD=P(AD))}function MD(e){if($&&e.target instanceof Node&&$.contains(e.target))return;let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0){AD();return}let n=t.getRangeAt(0),r=t.toString(),i=B(),a=n.commonAncestorContainer;if(r.trim()===``||!i||!i.el.contains(a)||TD(a)){AD();return}let o=wD(n.startContainer,`.mcol`),s=wD(n.endContainer,`.mcol`);if(!o||o!==s){AD();return}if(!wD(a,`.content, .tool-out, .think-seg-body`)){AD();return}SD={text:r,source:kD(i,o),format:wD(a,`pre, code`)?`code`:`text`},jD(n.getBoundingClientRect())}function ND(){if(CD)return;let e=window.getSelection();(!e||e.isCollapsed||e.rangeCount===0)&&AD()}function PD(e){if($&&e.target instanceof Node&&$.contains(e.target)){CD=!0;return}AD()}function FD(){let e=SD;AD(),e&&qh(e).then(e=>{e===`full`?X(w(`chat.quote.max`),`err`,4e3):e===`duplicate`&&X(w(`chat.quote.duplicate`),`ok`,3e3)})}function ID(){bD||(bD=!0,$=document.createElement(`button`),$.type=`button`,$.className=`quote-float hidden`,$.textContent=w(`chat.quote.add`),$.title=w(`chat.quote.addHint`),$.setAttribute(`aria-label`,w(`chat.quote.addAria`)),$.addEventListener(`click`,FD),document.body.appendChild($),document.addEventListener(`mouseup`,MD),document.addEventListener(`selectionchange`,ND),document.addEventListener(`pointerdown`,PD,!0),document.addEventListener(`scroll`,AD,!0),window.addEventListener(`resize`,AD))}var LD=globalThis.__CELESTEA_BUILD__??{},RD=LD.version??`dev`,zD=LD.commits??0,BD=LD.sha??``,VD=LD.dirty??!1,HD=LD.buildTime??`dev`;function UD(){let e=zD>0?`-`+zD+`-g`+BD:``;return`v`+RD+e}function WD(){let e=zD>0?`+`+zD:``;return`Studio v`+RD+e+(VD?`*`:``)}var GD=`celestea-studio.sidebar-collapsed`,KD=`celestea-studio.sidebar-width`;function qD(e){return Math.min(560,Math.max(200,Math.round(e)))}function JD(){try{let e=localStorage.getItem(GD);return e===null?window.innerWidth<880:e===`1`}catch{return!1}}function YD(){try{let e=Number(localStorage.getItem(KD));return Number.isFinite(e)&&e>0?e:316}catch{return 316}}function XD(){let e=M(`#app`),t=M(`#sidebar`),n=M(`#sidebarResizer`),r=M(`#btnSidebar`),i=JD(),a=()=>{e.classList.toggle(`sidebar-collapsed`,i),e.style.setProperty(`--sidebar-w`,i?`0px`:t.style.width||`316px`),r.textContent=w(i?`shell.sidebar.expand`:`shell.sidebar.collapse`),r.title=w(i?`shell.sidebar.expandTitle`:`shell.sidebar.collapseTitle`)},o=n=>{let r=qD(n)+`px`;t.style.width=r,i||e.style.setProperty(`--sidebar-w`,r)};a(),o(YD()),r.addEventListener(`click`,()=>{if(!QD()){i=!i;try{localStorage.setItem(GD,i?`1`:`0`)}catch{}a()}});let s=!1,c=0,l=0,u=()=>{try{localStorage.setItem(KD,String(Math.round(t.getBoundingClientRect().width)))}catch{}};n.addEventListener(`pointerdown`,e=>{s=!0,c=e.clientX,l=t.getBoundingClientRect().width,n.setPointerCapture(e.pointerId),document.body.classList.add(`resizing`),e.preventDefault()}),n.addEventListener(`pointermove`,e=>{s&&o(l+(e.clientX-c))});let d=()=>{s&&(s=!1,document.body.classList.remove(`resizing`),u())};n.addEventListener(`pointerup`,d),n.addEventListener(`pointercancel`,d),n.addEventListener(`dblclick`,()=>{o(316),u()}),$D(r)}var ZD=`(max-width: 640px)`;function QD(){try{return window.matchMedia(ZD).matches}catch{return window.innerWidth<=640}}function $D(e){let t=M(`#app`),n=document.getElementById(`sidebarScrim`),r=!1,i=()=>{t.classList.toggle(`drawer-open`,r),n&&n.classList.toggle(`hidden`,!r),e.setAttribute(`aria-expanded`,r?`true`:`false`)},a=e=>{r!==e&&(r=e,i())};i(),e.addEventListener(`click`,()=>{QD()&&a(!r)}),n?.addEventListener(`click`,()=>a(!1)),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&r&&a(!1)}),document.getElementById(`sessionTree`)?.addEventListener(`click`,e=>{if(!r)return;let t=e.target;t&&t.closest(`.sess-leaf`)&&a(!1)});try{window.matchMedia(ZD).addEventListener(`change`,e=>{e.matches||a(!1)})}catch{}}var eO=`celestea-studio.chat-col-width`,tO=1400,nO=2,rO=16,iO=null;function aO(e){return Math.min(tO,Math.max(560,Math.round(e)))}function oO(){try{let e=localStorage.getItem(eO);if(e===null)return null;let t=Number(e);return Number.isFinite(t)&&t>0?aO(t):null}catch{return null}}function sO(e){try{e===null?localStorage.removeItem(eO):localStorage.setItem(eO,String(e))}catch{}}function cO(e){let t=document.documentElement.style;e===null?t.removeProperty(`--chat-col-user`):t.setProperty(`--chat-col-user`,aO(e)+`px`)}function lO(){let e=document.querySelector(`.sess-pane:not([hidden]) .mcol`)??document.querySelector(`.mcol`),t=e?e.getBoundingClientRect().width:0;return t>0?aO(t):560}function uO(e,t){iO=e===null?null:aO(e),cO(iO),t&&sO(iO)}function dO(e){let t=!1,n=0,r=0;e.addEventListener(`pointerdown`,i=>{t=!0,n=i.clientX,r=iO??lO();try{e.setPointerCapture(i.pointerId)}catch{}document.body.classList.add(`resizing-col`),i.preventDefault()}),e.addEventListener(`pointermove`,e=>{t&&uO(r+nO*(e.clientX-n),!1)});let i=()=>{t&&(t=!1,document.body.classList.remove(`resizing-col`),sO(iO))};e.addEventListener(`pointerup`,i),e.addEventListener(`pointercancel`,i),e.addEventListener(`dblclick`,()=>uO(null,!0))}function fO(e){e.addEventListener(`keydown`,e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`)return;e.preventDefault();let t=e.key===`ArrowRight`?rO:-16;uO((iO??lO())+t,!0)})}function pO(){let e=document.getElementById(`messages`);if(!e||e.querySelector(`.chatcol-resizer`)){uO(oO(),!1);return}let t=N(`div`,`chatcol-resizer`);t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,w(`shell.chatcol.label`)),t.title=w(`shell.chatcol.hint`),e.appendChild(t),dO(t),fO(t),uO(oO(),!1)}function mO(){return[{id:`mono`,label:w(`theme.mono.label`),hint:w(`theme.mono.hint`)},{id:`dark`,label:w(`theme.dark.label`),hint:w(`theme.dark.hint`)}]}var hO=`celestea-studio.theme`;function gO(){return document.documentElement.dataset.theme||`mono`}function _O(e){document.documentElement.dataset.theme=e;try{localStorage.setItem(hO,e)}catch{}}function vO(e=`mono`){let t=e;try{let e=localStorage.getItem(hO);e&&mO().some(t=>t.id===e)&&(t=e)}catch{}return _O(t),t}function yO(e){let t=()=>{let t=gO(),n=mO().find(e=>e.id===t)??mO()[0];e.textContent=n.label,e.title=w(`theme.title`,{hint:n.hint,suffix:mO().length>1?w(`theme.clickToSwitch`):w(`theme.onlyTheme`)})};if(t(),mO().length<2){e.setAttribute(`aria-disabled`,`true`);return}e.addEventListener(`click`,()=>{let e=mO().findIndex(e=>e.id===gO()),n=mO()[(e+1)%mO().length];_O(n.id),t()})}function bO(){j.health().then(e=>{e.model&&ci.merge({model:e.model}),R.streaming||Y(w(`shell.status.online`),`ok`)}).catch(()=>{R.streaming||Y(w(`chat.status.disconnected`),`err`)})}function xO(){vO(`mono`),yO(M(`#btnTheme`)),XD(),pO(),Hr(),Rx(),Tx(),ci.start(),Tm(),fE(),ST(),mx();let e=document.getElementById(`brandVersion`);e&&(e.textContent=WD(),e.title=w(`chat.version.title`,{time:HD,version:UD(),dirty:VD?w(`chat.version.dirty`):``})),ro(),dS(),ID(),y_(),yD(),ei(),bO(),rm(),cS(),window.addEventListener(`studio:config-saved`,()=>bO()),M(`#input`).focus()}xO();
|
package/webdist/build-meta.json
CHANGED
package/webdist/index.html
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
<!doctype html>
|
|
2
2
|
<html lang="zh-CN" data-theme="mono">
|
|
3
3
|
<head>
|
|
4
|
-
<script>window.__CELESTEA_BUILD__ = {"version":"2.7.
|
|
4
|
+
<script>window.__CELESTEA_BUILD__ = {"version":"2.7.2","commits":0,"sha":"9e23258","dirty":false,"buildTime":"2026-09-19T07:00:37.312Z"};</script>
|
|
5
5
|
|
|
6
6
|
<meta charset="utf-8" />
|
|
7
7
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
|
8
8
|
<title>Celestea Studio</title>
|
|
9
9
|
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%230d0f12'/%3E%3Crect x='5' y='5' width='6' height='6' rx='1.2' fill='none' stroke='%237f93b0' stroke-width='1.4'/%3E%3C/svg%3E" />
|
|
10
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-CSJYbgdH.js"></script>
|
|
11
11
|
<link rel="stylesheet" crossorigin href="/assets/index-Bu6ci_rN.css">
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|