sliccy 6.85.0 → 6.87.0
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/node-server/_shared/tray-sync-protocol.d.ts +5 -0
- package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
- package/dist/ui/.vite/manifest.json +117 -117
- package/dist/ui/assets/{account-store-CC9-shzK.js → account-store-DgIW0bp1.js} +1 -1
- package/dist/ui/assets/{account-store-Bm2VajTN.js → account-store-blR0Xytj.js} +1 -1
- package/dist/ui/assets/{adobe-C8PFeNMw.js → adobe-C17z0Y2h.js} +1 -1
- package/dist/ui/assets/{adobe-DV3pVuB2.js → adobe-CFR798vg.js} +1 -1
- package/dist/ui/assets/{apply-layout-BWYkpSzL.js → apply-layout-B5YqftfH.js} +1 -1
- package/dist/ui/assets/{apps-FU_mREPr.js → apps-15mQcCNI.js} +1 -1
- package/dist/ui/assets/{azure-openai-BB_RtcNo.js → azure-openai-DqSVy438.js} +1 -1
- package/dist/ui/assets/{azure-openai-Ddc3Amtb.js → azure-openai-DrVwGRsm.js} +1 -1
- package/dist/ui/assets/{cerebras-CaUDJipB.js → cerebras-DebqNIZb.js} +1 -1
- package/dist/ui/assets/{cerebras-CeCaF7ho.js → cerebras-Dm3uDOEA.js} +1 -1
- package/dist/ui/assets/{connect-surface-Cb-Tddoq.js → connect-surface-MD54fGyS.js} +1 -1
- package/dist/ui/assets/{fs-BoALHjOA.js → fs-Ck5oWGOP.js} +1 -1
- package/dist/ui/assets/{fs-C3sT_rdX.js → fs-D6il5fMD.js} +2 -2
- package/dist/ui/assets/{github-B2er6OPi.js → github-Bgw3umJ4.js} +1 -1
- package/dist/ui/assets/{github-BCeM1yTx.js → github-C-n1YRYP.js} +2 -2
- package/dist/ui/assets/{github-copilot-COAyRbqy.js → github-copilot-BjEfXLPk.js} +1 -1
- package/dist/ui/assets/{github-copilot-C3u4jyIt.js → github-copilot-vFlxvzX_.js} +1 -1
- package/dist/ui/assets/{github-install-CZo0KQdD.js → github-install-CQEJO19w.js} +1 -1
- package/dist/ui/assets/{github-zip-BWCMqOny.js → github-zip-D1UI8lqd.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-BM9iKQxx.js → js-realm-worker-Dp9q1rw2.js} +1 -1
- package/dist/ui/assets/{kernel-worker-C799qNgs.js → kernel-worker-CwS_G03U.js} +662 -661
- package/dist/ui/assets/{local-llm-DsctUmhm.js → local-llm-Dyqfr9rL.js} +1 -1
- package/dist/ui/assets/{local-llm-Xlw2sPon.js → local-llm-mKb5CRG9.js} +1 -1
- package/dist/ui/assets/{main-BGeWTLT3.js → main-fP6BNO3n.js} +3 -3
- package/dist/ui/assets/{mount-8URyt32_.js → mount-0XiB20zr.js} +2 -2
- package/dist/ui/assets/{mount-Bf0tLVvW.js → mount-4UhANN4M.js} +1 -1
- package/dist/ui/assets/{mount-recovery-CJPSdeEr.js → mount-recovery-C5L5QvtB.js} +1 -1
- package/dist/ui/assets/{new-session-bqvpUvUb.js → new-session-yPvAN6DW.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-B9xLY1WU.js → oauth-bootstrap-t5whfM5H.js} +2 -2
- package/dist/ui/assets/{openai-codex-CLkRugCd.js → openai-codex-DLmBzdVE.js} +1 -1
- package/dist/ui/assets/{openai-codex-DXZXMUyx.js → openai-codex-naKUFiqn.js} +1 -1
- package/dist/ui/assets/{openrouter-D10TY-Dp.js → openrouter-BWmtrNqE.js} +1 -1
- package/dist/ui/assets/{openrouter-D0rcNFGP.js → openrouter-DKndqlOm.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BZu7QjbB.js → openrouter-oauth-CzlXYsOz.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-_btBc4s4.js → openrouter-oauth-DzHbL_tB.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-DIavhh02.js → panel-rpc-handlers-Bk3xpS4a.js} +2 -2
- package/dist/ui/assets/{provider-CHcsfo-Y.js → provider-DlWapVk5.js} +2 -2
- package/dist/ui/assets/{provider-CQjaVYIp.js → provider-DmWLQiT_.js} +1 -1
- package/dist/ui/assets/{provider-settings-DDkeX-2T.js → provider-settings-DASqyNzx.js} +1 -1
- package/dist/ui/assets/{provider-settings-CEg8KcDf.js → provider-settings-eap0NvPq.js} +1 -1
- package/dist/ui/assets/{provider-store-access-Dql39T9w.js → provider-store-access-6vie58RV.js} +2 -2
- package/dist/ui/assets/provider-store-access-CM6uixPC.js +1 -0
- package/dist/ui/assets/{providers-Br4FC81W.js → providers-BoWSRjN8.js} +2 -2
- package/dist/ui/assets/{providers-BtP9WaiU.js → providers-DdmrS25V.js} +1 -1
- package/dist/ui/assets/{quick-llm--XIPLZbE.js → quick-llm-Dx7LMDJm.js} +1 -1
- package/dist/ui/assets/{recovery-screen-Dz6zrthP.js → recovery-screen-f0PWFjGs.js} +1 -1
- package/dist/ui/assets/{redirect-uri-DTtRAbQB.js → redirect-uri-GNDuxiLL.js} +1 -1
- package/dist/ui/assets/session-freezer-CjetY7-l.js +160 -0
- package/dist/ui/assets/{setup-feature-flags-remote-BmiHHKo-.js → setup-feature-flags-remote-B09TVbHZ.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-Du9_yqP6.js → setup-standalone-prelude-Bgk3IEZS.js} +1 -1
- package/dist/ui/assets/{setup-sudo-gOP6wC-U.js → setup-sudo-Bn6JILej.js} +2 -2
- package/dist/ui/assets/{skills-DLjB_DHd.js → skills-BLq1HPIs.js} +1 -1
- package/dist/ui/assets/slicc-version-DJCgixn2.js +1 -0
- package/dist/ui/assets/{store-CGwOTjvf.js → store-_4qNLs0p.js} +1 -1
- package/dist/ui/assets/{store-CsCK1o4K.js → store-mm3MbxdX.js} +1 -1
- package/dist/ui/assets/{sudo-D3lnFaTe.js → sudo-Cl0AxRzu.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-DmECLitF.js → upgrade-detection-CoyR0nu_.js} +1 -1
- package/dist/ui/assets/{wc-extension-BLEu9V64.js → wc-extension-BU1tl5FG.js} +2 -2
- package/dist/ui/assets/{wc-follower-DRBcybRO.js → wc-follower-Cy-j8Qfu.js} +3 -3
- package/dist/ui/assets/{wc-live-D5kc29Ya.js → wc-live-WKelF6Hq.js} +4 -4
- package/dist/ui/assets/{wc-nav-Sr7kMJL2.js → wc-nav-DQetahZz.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-v5-703FM.js → wc-onboarding-Tr6-eTzf.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-BP0AWV7J.js → wc-placeholder-D-Hr5Op2.js} +2 -2
- package/dist/ui/assets/{wc-settings-BGMPQFfE.js → wc-settings-01KgBEBL.js} +2 -2
- package/dist/ui/assets/{wc-shell-DoMz1z6V.js → wc-shell-ClNhTcYg.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-4A8-YDvD.js → wc-sprinkles-CHCZj4eg.js} +2 -2
- package/dist/ui/assets/wc-tray-BVjxbhtE.js +2 -0
- package/dist/ui/assets/{xai-grok-1WsE92-V.js → xai-grok-BuRdCv1G.js} +1 -1
- package/dist/ui/assets/{xai-grok-EfgbooQZ.js → xai-grok-CYQXcaOo.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +1 -1
- package/dist/ui/assets/provider-store-access-t5K7duLx.js +0 -1
- package/dist/ui/assets/session-freezer-C1uLti2Q.js +0 -160
- package/dist/ui/assets/slicc-version-DPf4lYVB.js +0 -1
- package/dist/ui/assets/wc-tray-B9YuHgK6.js +0 -2
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm--XIPLZbE.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/account-store-CC9-shzK.js","assets/preload-helper-Czpn1I53.js","assets/bedrock-camp-qpZqnqLa.js","assets/diagnostics-DN_idNHx.js","assets/transform-messages-N_eMsP2M.js","assets/provider-env-CTOcDKrQ.js","assets/__vite-browser-external-5eBdwsFd.js","assets/openrouter.models-gbjkpjE_.js","assets/libesm-BI4UHVqp.js","assets/logger-DDBAeTLF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-B4g-4VbQ.js","assets/base64-DpPqYZJF.js","assets/runtime-env-Dlaokqg1.js","assets/fetch-body-D2PwksUW.js","assets/float-topology-BgioAcOd.js","assets/runtime-env-E-i2SW1s.js","assets/secret-topology-xLmXoozo.js","assets/secrets-bridge-client-cWDAnFqs.js","assets/port-bridge-client-BbVs1yhx.js","assets/image-markers-BXtVm4og.js","assets/tool-ui-DfXu6quJ.js","assets/providers-Br4FC81W.js","assets/panel-rpc-B3MSVImO.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-ZLR7gmJ4.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{Q as t,X as n,Z as r}from"./account-store-CC9-shzK.js";import{t as i}from"./preload-helper-Czpn1I53.js";import{l as a}from"./bedrock-camp-qpZqnqLa.js";import{t as o}from"./logger-DDBAeTLF.js";import{t as s}from"./attachments-CByeG2Ru.js";import{t as c}from"./types-idfTVsM8.js";import{t as l}from"./icons-ZLR7gmJ4.js";import{c as u,l as d,n as f,r as ee,t as p,u as te}from"./record-Z5ZWTUPJ.js";import{a as ne}from"./dictation-priming-CNllGgNq.js";import"./agent-message-to-chat-_cvF5A5g.js";var re=`---
|
|
3
|
-
writablePaths:
|
|
4
|
-
- /workspace/CLAUDE.md
|
|
5
|
-
visiblePaths:
|
|
6
|
-
- /sessions/
|
|
7
|
-
- /shared/
|
|
8
|
-
- /workspace/
|
|
9
|
-
allowedCommands:
|
|
10
|
-
- awk
|
|
11
|
-
- cat
|
|
12
|
-
- cp
|
|
13
|
-
- cut
|
|
14
|
-
- echo
|
|
15
|
-
- file
|
|
16
|
-
- find
|
|
17
|
-
- grep
|
|
18
|
-
- head
|
|
19
|
-
- jq # structured reads of JSON stores such as /shared/loose-ends.json
|
|
20
|
-
- ls
|
|
21
|
-
- mkdir
|
|
22
|
-
- mv
|
|
23
|
-
- od # read-only byte inspection of corrupted stores
|
|
24
|
-
- printf
|
|
25
|
-
- rg # recursive, .gitignore-aware search; what the curator actually uses over find|xargs grep
|
|
26
|
-
- sed
|
|
27
|
-
- sort
|
|
28
|
-
- tail
|
|
29
|
-
- tr
|
|
30
|
-
- uniq
|
|
31
|
-
- upskill
|
|
32
|
-
- wc
|
|
33
|
-
timeoutSeconds: 1200
|
|
34
|
-
thinkingLevel: medium
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
# Memory curator
|
|
38
|
-
|
|
39
|
-
Curate the durable memory for session {{SESSION_COUNT}}. Today's date is {{TODAY}}.
|
|
40
|
-
|
|
41
|
-
**Work fast: a full pass should finish in well under 10 minutes.** The run is hard-stopped at 20 minutes, and a kill mid-write can corrupt the memory file or leave it over budget — so mine the three signals, rewrite the file, compact it in the same pass, and stop, rather than exploring the archive exhaustively.
|
|
42
|
-
|
|
43
|
-
Read the entire current memory at {{MEMORY_PATH}} if it exists. Then mine the archived session at {{SESSION_ARCHIVE_PATH}} using the reading recipes below. Rewrite the entire {{MEMORY_PATH}} file with the durable information worth carrying into future sessions. Every part of the file is editable and counts toward the budget.
|
|
44
|
-
|
|
45
|
-
## What to look for
|
|
46
|
-
|
|
47
|
-
Three things carry across sessions, and each has its own place in the archive:
|
|
48
|
-
|
|
49
|
-
| Look for | Where it lives |
|
|
50
|
-
| --------------- | ---------------------------------------------------------------------- |
|
|
51
|
-
| **Preferences** | the user's own messages — how they want things done, and what to avoid |
|
|
52
|
-
| **Projects** | tool-call arguments — the paths, repos and files actually worked on |
|
|
53
|
-
| **Pitfalls** | failed tool calls — what broke, and the error that proves it |
|
|
54
|
-
|
|
55
|
-
Pitfalls are the highest-value and most-often-lost category: a failure that cost half an hour is worth one line next time. Keep the error text that identifies it, not the stack trace.
|
|
56
|
-
|
|
57
|
-
## Reading the session archive
|
|
58
|
-
|
|
59
|
-
**Never \`cat\` the archive and never \`head\` it.** Archives reach several megabytes, and the machine-readable \`<!-- slicc:session-data ... -->\` block is a _single line_ holding the whole session as JSON — roughly half the file. Reading it costs a fortune and tells you nothing the prose below it does not. Whole \`### Tool\` result bodies are the other half and are equally not worth reading.
|
|
60
|
-
|
|
61
|
-
Check the size first, then pull the three signals separately. Together they run about 1% of the archive, so these work on a 2.5 MB file as happily as on a small one.
|
|
62
|
-
|
|
63
|
-
\`\`\`bash
|
|
64
|
-
wc -c {{SESSION_ARCHIVE_PATH}}
|
|
65
|
-
|
|
66
|
-
# Preferences — what the user asked for, in their words.
|
|
67
|
-
sed '/^<!-- slicc:session-data$/,/^-->$/d' {{SESSION_ARCHIVE_PATH}} \\
|
|
68
|
-
| awk '/^## User/{p=1;next} /^## (Assistant|Summary)/{p=0} /^### Tool/{p=0} p'
|
|
69
|
-
|
|
70
|
-
# Projects — the paths touched most, which name the work.
|
|
71
|
-
sed '/^<!-- slicc:session-data$/,/^-->$/d' {{SESSION_ARCHIVE_PATH}} \\
|
|
72
|
-
| grep -o '/[A-Za-z0-9_][A-Za-z0-9_./-]\\{3,\\}' \\
|
|
73
|
-
| sort | uniq -c | sort -rn | head -40
|
|
74
|
-
|
|
75
|
-
# Pitfalls — failed calls with the input that caused them.
|
|
76
|
-
sed '/^<!-- slicc:session-data$/,/^-->$/d' {{SESSION_ARCHIVE_PATH}} \\
|
|
77
|
-
| grep -B6 '^Result:.*\\(rror\\|not found\\|failed\\|denied\\|ENOENT\\|fatal\\)' \\
|
|
78
|
-
| cut -c1-200
|
|
79
|
-
\`\`\`
|
|
80
|
-
|
|
81
|
-
Only if something is still missing, reach into one specific block with \`grep -n\` plus a bounded \`sed -n 'START,ENDp'\`. Never widen these to the whole file.
|
|
82
|
-
|
|
83
|
-
## Suggesting a skill
|
|
84
|
-
|
|
85
|
-
A recurring pitfall is often a missing skill. Once you know what broke and what the work was, spend **one** lookup on it — no more, and skip it entirely when the session had no failures:
|
|
86
|
-
|
|
87
|
-
\`\`\`bash
|
|
88
|
-
upskill search <a few words from the pitfall>
|
|
89
|
-
upskill list # what is already installed — never suggest a duplicate
|
|
90
|
-
\`\`\`
|
|
91
|
-
|
|
92
|
-
\`upskill ai-ecoverse/skills\` and \`upskill adobe/skills\` list a repo's skills without installing anything. **Never install.** You have no write access to the skills tree, so an install attempt will fail or interrupt the user for approval; recommending is your job, deciding is theirs. Put any suggestion in your closing message, with the pitfall it addresses — that message is delivered to the main agent.
|
|
93
|
-
|
|
94
|
-
## Working within the budget
|
|
95
|
-
|
|
96
|
-
Measure, decide, then write once. Do not converge on the budget by trial and error — each attempt re-reads your whole context and is billed accordingly.
|
|
97
|
-
|
|
98
|
-
1. \`wc -c {{MEMORY_PATH}}\` to get the current size, and subtract {{BUDGET_CHARS}} to get the exact surplus.
|
|
99
|
-
2. Decide up front which sections absorb that surplus, oldest-dated first, and roughly what each one costs. Budget the whole cut before editing anything.
|
|
100
|
-
3. Write the complete file once, already inside the budget. Never write a version you know to be over budget «to fix in the next step»: the pass can be killed at any moment, and the file you leave behind is the one the next session inherits.
|
|
101
|
-
4. \`wc -c {{MEMORY_PATH}}\` to confirm. If you are still over, cut a whole section rather than shaving a few characters at a time.
|
|
102
|
-
|
|
103
|
-
Per-section costs come out of \`awk\`, not an interpreter: \`awk '/^## /{h=$0} {c[h]+=length($0)+1} END{for(k in c) printf "%7d %s\\n", c[k], k}' {{MEMORY_PATH}} | sort -rn\` tells you which sections pay for the surplus.
|
|
104
|
-
|
|
105
|
-
To draft before committing, draft in \`{{SCRATCH_DIR}}\`. That is your own scratch folder: writable without a grant and without an approval prompt, private to this pass, and deleted when the pass ends. Reuse one filename such as \`{{SCRATCH_DIR}}/draft.md\` rather than numbering drafts — you have no \`rm\`, so every extra draft survives until the folder goes.
|
|
106
|
-
|
|
107
|
-
If the pass is running long, drop the oldest-dated section wholesale and write. An under-budget file missing one stale section is a good outcome; an over-budget file is a broken one.
|
|
108
|
-
|
|
109
|
-
Rules:
|
|
110
|
-
|
|
111
|
-
- Keep durable preferences, stable project facts, validated approaches, named resources, and the pitfalls worth not repeating.
|
|
112
|
-
- Organize retained information into concise per-topic sections rather than one flat list. Let the topic lead the heading; preferences, projects and pitfalls are what to look for, not a required table of contents.
|
|
113
|
-
- Never write next to the memory file. It is versioned, so backups and scratch copies beside it are noise; drafts belong in \`{{SCRATCH_DIR}}\`. Do not draft in \`/tmp/\` either: it is shared with every other scoop, which can read and overwrite what you leave there.
|
|
114
|
-
- Shell tools only. Interpreters such as \`python3\` and \`node -e\` are not on your allow-list, so reaching for one costs an approval round-trip and may fail even when approved — \`awk\`, \`sed\`, \`wc\` and \`sort\` cover every measurement this pass needs.
|
|
115
|
-
- End every \`##\` and \`###\` section heading with its last-verified date in \`YYYY-MM-DD\` form, for example \`## Deployment pipeline (2026-08-06)\`. Dates are UTC, matching the session archive timestamps, so a late-evening freeze west of UTC stamps the next day.
|
|
116
|
-
- Stamp sections you write or confirm with today's date, {{TODAY}}.
|
|
117
|
-
- Prioritize re-verifying the oldest-dated sections. Treat undated headings as maximally stale and date them on this pass.
|
|
118
|
-
- Drop ephemera and duplicates. Delete or merge sections that are stale, superseded, or unverifiable.
|
|
119
|
-
- Preserve concrete identifiers such as file paths, URLs, IDs, and names verbatim.
|
|
120
|
-
- Keep the entire file at or below the hard budget of {{BUDGET_CHARS}} characters, with no exempt region. When over budget, compact or remove the oldest-dated sections first.
|
|
121
|
-
- Write the result to {{MEMORY_PATH}}; do not merely return it in your response.
|
|
122
|
-
|
|
123
|
-
<!-- How to customize
|
|
124
|
-
Add curator instructions here, for example: also update the knowledge base at /path following its WIKI.md. Extend visiblePaths or writablePaths above to grant access to extra stores, and adjust timeoutSeconds when needed.
|
|
125
|
-
|
|
126
|
-
writablePaths defaults to the memory file alone rather than /workspace/, because the curator can run upskill and a directory-wide grant would also let it install skills into /workspace/skills. Widen it only as far as a task genuinely needs; a single file is a valid entry, not just a directory.
|
|
127
|
-
|
|
128
|
-
Scratch space needs no entry here. The curator spawns under a fixed per-cone name (memory-curator for the primary cone), so the bridge grants it {{SCRATCH_DIR}} — private to the run, writable without a prompt, and removed when the pass ends — and that is where the prompt sends drafts. /tmp/ is writable too, but it is shared with every other scoop and visible to the cone, so a full rewrite of durable memory does not belong there.
|
|
129
|
-
|
|
130
|
-
thinkingLevel accepts off, minimal, low, medium, high, or xhigh. Curation is cheaper with reasoning than without: an unreasoned pass converges on the budget by trial and error, and because every turn re-reads the whole context, turn count is what the pass costs. Lower it to off only if you also shrink the prompt to a single mechanical instruction.
|
|
131
|
-
|
|
132
|
-
MEMORY.md is user-edited only: the curator intentionally has read-only access to /shared/ and cannot rewrite its own instructions. A bare / is rejected in writablePaths.
|
|
133
|
-
|
|
134
|
-
Frontmatter supports a strict YAML subset. Arrays may use the block form above (with optional # comment tails) or inline form such as [cat, grep]. \`allowedCommands\` is additive: listed commands extend the built-in base set without replacing it. Inline entries containing commas must be quoted, for example ["/knowledge/lars,rebecca/"].
|
|
135
|
-
-->
|
|
136
|
-
`,ie=`/cones`,m=`/workspace/skills`;function h(e){if(u(e)){if(ee(e))return{root:`/workspace`,memoryPath:`/workspace/CLAUDE.md`,scratch:`/tmp`};let t=`${ie}/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:`/tmp`}}let t=`/scoops/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:t}}var g=Object.freeze(h({parentJid:null,folder:p}));function ae(e,t){let n=[...e],r=d(n,t)??te(n)[0];return r?h(r):g}function oe(e){let t=`${e.root}/`,n=`${m}/`;return n.startsWith(t)?[t]:[t,n]}var se=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function ce(e){return typeof e==`string`&&se.includes(e)}o(`agent-bridge`);var le=`agent: name already in use`,_=o(`cone-memory-budget`),ue=4e3,de=2e3,fe=1.25,pe=g.memoryPath,me=`/sessions/index.json`,he=4096,ge=/^## Auto-extracted/m,_e=`Consolidate the auto-extracted memory bullets below into a single tighter set of durable memories.
|
|
137
|
-
|
|
138
|
-
Rules:
|
|
139
|
-
- Output ONLY a single \`## Auto-extracted (consolidated)\` heading followed by markdown bullets.
|
|
140
|
-
- One fact per bullet. Drop duplicates and superseded facts. Keep the most recent / specific phrasing.
|
|
141
|
-
- Preserve concrete identifiers (file paths, URLs, IDs, names) verbatim.
|
|
142
|
-
- Be terse. Aim well under the original size.
|
|
143
|
-
- Do NOT add preamble, commentary, or any heading other than the single consolidated one.`;function v(e){return Math.round(ue+de*Math.log2((Number.isFinite(e)&&e>=0?e:0)+2))}function ve(e){let t=ge.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function y(e){try{let t=await e.readFile(me,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r.length:0}catch{return 0}}async function ye(e){let{header:t,autoExtracted:n}=ve(e.currentContent);if(!n.trim())return e.currentContent;let r=`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
|
|
144
|
-
|
|
145
|
-
<auto-extracted>
|
|
146
|
-
${n}
|
|
147
|
-
</auto-extracted>`,i={role:`user`,content:[{type:`text`,text:_e}],timestamp:Date.now()},o=await a(e.model,{systemPrompt:r,messages:[i]},{apiKey:e.apiKey,maxTokens:he,headers:e.headers,signal:e.signal});if(o.stopReason===`error`)throw Error(`Restructure call failed: ${o.errorMessage||`Unknown error`}`);let s=o.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
148
|
-
`).trim();if(!s)throw Error(`Restructure call returned empty content`);return`${t}${t.length===0||t.endsWith(`
|
|
149
|
-
`)?``:`
|
|
150
|
-
`}${s}\n`}async function be(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??pe,n=``;try{let r=await e.vfs.readFile(t,{encoding:`utf-8`});n=typeof r==`string`?r:new TextDecoder().decode(r)}catch{return{restructured:!1,reason:`missing-file`}}let r=await y(e.vfs),i=v(r),a=i*fe;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};_.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await ye({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),_.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return _.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}var b=o(`agentic-memory`),xe=`/shared/MEMORY.md`,Se=1200,Ce=e=>[e.memoryPath],we=e=>[`/sessions/`,`/shared/`,...oe(e)],Te=`awk.cat.cp.cut.date.diff.du.echo.file.find.grep.head.jq.ls.mkdir.mount.mv.nl.od.printf.readlink.sed.sort.stat.tail.touch.tr.uniq.upskill.wc.xxd`.split(`.`),Ee=new Set([`writablePaths`,`visiblePaths`,`allowedCommands`]),De=new Set([`model`,`timeoutSeconds`,`thinkingLevel`]),Oe=`medium`,x=3e4;function S(e){return e===`cone`?`memory-curator`:`memory-curator-${e}`}function ke(e){let t=S(e);return Ae.test(t)?t:S(p)}var Ae=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function je(e){return`/scoops/agent-${ke(e)}`}var C=je(p);function Me(e){return h({parentJid:null,folder:e?.folder??`cone`})}function w(e,t){if(t.root===g.root)return e;if(e===g.memoryPath)return t.memoryPath;if(e===`/workspace/skills`||e.startsWith(`/workspace/skills/`))return e;let n=`${g.root}/`;return e===g.root?t.root:e.startsWith(n)?`${t.root}/${e.slice(n.length)}`:e}function Ne(e,t){let n=`${m}/`,r=e=>e.some(e=>n.startsWith(e.endsWith(`/`)?e:`${e}/`)),i=e.map(e=>w(e,t));return r(e)&&!r(i)&&i.push(n),i}async function Pe(e){try{if(e.signal?.aborted)return{ok:!1,reason:`aborted`,legacyFallbackSafe:!1};let t=Me(e.cone),n=je(e.cone?.folder??`cone`),r=await Fe(e.vfs,t),i=Ue(r,We(Ge(r.promptTemplate,{MEMORY_PATH:t.memoryPath,SESSION_ARCHIVE_PATH:e.sessionArchivePath,SESSION_COUNT:String(e.sessionCount),BUDGET_CHARS:String(v(e.sessionCount)),SCRATCH_DIR:n,TODAY:e.today??new Date().toISOString().slice(0,10)}),n),e.sessionArchivePath,t,e.cone);e.signal&&(i.signal=e.signal);let a=await Ke(Promise.resolve().then(()=>e.spawn(i)),r.timeoutSeconds*1e3+x,e.signal);if(a.type===`timeout`)return b.warn(`Agentic memory wait timed out past the in-run bound + grace`,{timeoutSeconds:r.timeoutSeconds,graceMs:x}),{ok:!1,reason:`timeout`,legacyFallbackSafe:!1};if(a.type===`aborted`)return{ok:!1,reason:`aborted`,legacyFallbackSafe:!1};if(a.type===`error`)return{ok:!1,reason:A(a.error),legacyFallbackSafe:!0};if(a.result.exitCode!==0){let e=(a.result.finalText??``).startsWith(le);return{ok:!1,reason:a.result.finalText||`exit-${a.result.exitCode}`,legacyFallbackSafe:!e}}return{ok:!0,report:a.result.finalText}}catch(e){return b.warn(`Agentic memory pass failed`,{error:A(e)}),{ok:!1,reason:A(e),legacyFallbackSafe:!1}}}async function Fe(e,t=g){try{let n=await e.readFile(xe,{encoding:`utf-8`});return T(typeof n==`string`?n:new TextDecoder().decode(n),t)}catch(e){return b.warn(`Could not load valid MEMORY.md; using built-in default`,{error:A(e)}),T(re,t)}}function T(e,t=g){let n=e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
|
|
151
|
-
`).match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!n?.[2].trim())throw Error(`MEMORY.md requires frontmatter and a prompt`);let r=Le(n[1]),i=D(r,`writablePaths`,Ce(t));if(i.length===0)throw Error(`writablePaths must not be empty`);O(i,`writablePaths`);let a=D(r,`visiblePaths`,we(t));O(a,`visiblePaths`);let o=He(r.timeoutSeconds),s=Ve(r.model,`model`);return{writablePaths:i.map(e=>w(e,t)),visiblePaths:Ne(a,t),allowedCommands:[...new Set([...Te,...D(r,`allowedCommands`,[])])],...s?{model:s}:{},thinkingLevel:Ie(r.thinkingLevel),timeoutSeconds:o,promptTemplate:n[2].trim()}}function Ie(e){if(e===void 0)return Oe;if(typeof e!=`string`||!ce(e))throw Error(`thinkingLevel must be one of ${se.join(`, `)}`);return e}function Le(e){let t={},n=e.split(`
|
|
152
|
-
`);for(let e=0;e<n.length;e+=1){let r=n[e];if(!r.trim()||r.trimStart().startsWith(`#`))continue;let i=r.match(/^([A-Za-z][A-Za-z0-9]*):\s*(.*)$/);if(!i)throw Error(`Invalid frontmatter line: ${r}`);let[,a,o]=i;if(Ee.has(a)){let r=Re(n,e,o);t[a]=r.value,e=r.lastIndex}else if(De.has(a)&&o.trim())t[a]=E(o);else throw Error(`Unsupported or empty frontmatter field: ${a}`)}return t}function Re(e,t,n){if(n.trim()){let e=n.trim();if(!e.startsWith(`[`)||!e.endsWith(`]`))throw Error(`Expected an array`);let r=e.slice(1,-1).trim();return{value:r?ze(r):[],lastIndex:t}}let r=[],i=t;for(let n=t+1;n<e.length;n+=1){let t=e[n].match(/^\s+-\s+(.+)$/);if(!t)break;r.push(E(Be(t[1]))),i=n}return{value:r,lastIndex:i}}function ze(e){let t=[],n=0,r;for(let i=0;i<e.length;i+=1){let a=e[i];a===`"`||a===`'`?r=r===a?void 0:r??a:a===`,`&&!r&&(t.push(E(e.slice(n,i))),n=i+1)}if(r)throw Error(`Unclosed quoted value`);return t.push(E(e.slice(n))),t}function Be(e){let t;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`"`||r===`'`)t=t===r?void 0:t??r;else if(r===`#`&&!t&&(n===0||/\s/.test(e[n-1])))return e.slice(0,n).trimEnd()}return e}function E(e){let t=e.trim();if(!t)throw Error(`Empty frontmatter value`);let n=t[0];if((n===`"`||n===`'`)&&t.at(-1)===n)return t.slice(1,-1);if(n===`"`||n===`'`)throw Error(`Unclosed quoted value`);return t}function D(e,t,n){let r=e[t];if(r===void 0)return[...n];if(!Array.isArray(r)||r.some(e=>!e))throw Error(`${t} is invalid`);return[...r]}function Ve(e,t){if(e!==void 0){if(typeof e!=`string`||!e)throw Error(`${t} is invalid`);return e}}function He(e){if(e===void 0)return 600;if(typeof e!=`string`)throw Error(`timeoutSeconds is invalid`);let t=Number(e);if(!Number.isFinite(t)||t<=0)throw Error(`timeoutSeconds must be positive`);return Math.min(t,Se)}function O(e,t){if(e.some(e=>!e.startsWith(`/`)||e.includes(`\0`)||t===`writablePaths`&&e===`/`))throw Error(`${t} must contain absolute VFS paths`)}function k(e){return`/sessions/.curated/${e.slice(e.lastIndexOf(`/`)+1)}`}function Ue(e,t,n,r,i){let a=e.model===`parent`||e.model===`cone`;return{cwd:r.root,writablePaths:e.writablePaths,visiblePaths:e.visiblePaths,allowedCommands:e.allowedCommands,prompt:t,thinkingLevel:e.thinkingLevel,persistSession:!0,name:ke(i?.folder??`cone`),...i?.jid?{parentJid:i.jid}:{},notifyOnComplete:!0,successReceiptPath:k(n),maxWallClockMs:e.timeoutSeconds*1e3,...!a&&e.model?{modelId:e.model}:{}}}function We(e,t){return t===C?e:e.replaceAll(C,t)}function Ge(e,t){let n=e;for(let[e,r]of Object.entries(t))n=n.replaceAll(`{{${e}}}`,r);return n}function Ke(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(s),n?.removeEventListener(`abort`,o),r(e))},o=()=>a({type:`aborted`}),s=setTimeout(()=>a({type:`timeout`}),t);n?.addEventListener(`abort`,o,{once:!0}),e.then(e=>a({type:`result`,result:e}),e=>a({type:`error`,error:e}))})}function A(e){return e instanceof Error?e.message:String(e)}var j=`/sessions`,M=`/sessions/index.json`;async function N(e){try{let t=await e.readFile(M,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function P(e){return`${j}/${e.filename}`}function F(e){let t=e,n=`Untitled`,r={},i=t.match(/^---\n([\s\S]*?)\n---\n+/);if(i){t=t.slice(i[0].length);let e=L(i[1],`cost`),a=L(i[1],`models`);e&&(r.cost=e),a&&(r.models=a);let o=i[1].match(/^cone:\s*(.+?)\s*$/m)?.[1];o&&(r.cone=o);let s=i[1].match(/^coneLabel:\s*(.+?)\s*$/m)?.[1];s&&(r.coneLabel=I(s)),/^memorySkipped:\s*true\s*$/m.test(i[1])&&(r.memorySkipped=!0);let c=i[1].match(/^title:\s*(.+?)\s*$/m);c&&(n=I(c[1]))}let a=t.match(/<!-- slicc:session-data\n([\s\S]*?)\n-->\n*/);if(a){try{let e=a[1].replace(/-- >/g,`-->`),t=JSON.parse(e);if(Array.isArray(t))return{title:n,messages:t,...r}}catch{}t=t.replace(/<!-- slicc:session-data\n[\s\S]*?\n-->\n*/,``)}return t=t.replace(/^#\s+[^\n]*\n+/,``),{title:n,messages:qe(t),...r}}function I(e){let t=e.trim();if(!t.startsWith(`"`))return t;try{let e=JSON.parse(t);if(typeof e==`string`)return e}catch{}return t.replace(/^"|"$/g,``)}function L(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function qe(e){let t=[],n=/^## (User|Assistant)\s*\n/gm,r=[],i;for(;(i=n.exec(e))!==null;)r.push({role:i[1]===`User`?`user`:`assistant`,start:i.index,bodyStart:i.index+i[0].length});for(let n=0;n<r.length;n++){let i=n+1<r.length?r[n+1].start:e.length,a=e.slice(r[n].bodyStart,i).trim();t.push({id:`frozen-${n}`,role:r[n].role,content:a,timestamp:0})}return t}function R(e){let t=``;for(let n of e){let e=n.role===`user`?`User`:`Assistant`,r=n.role===`user`?ne(n.content):n.content;if(t+=`## ${e}\n${r}\n\n`,n.attachments?.length&&(t+=`Attachments:\n${n.attachments.map(e=>`- ${s(e)}`).join(`
|
|
153
|
-
`)}\n\n`),n.toolCalls)for(let e of n.toolCalls)t+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}return t}var Je=e({PENDING_SESSION_ATTEMPT_LIMIT:()=>3,SESSIONS_INDEX_PATH:()=>M,curateFrozenSessionMemories:()=>U,enrichPendingSession:()=>Z,freezeConeSession:()=>H,listPendingEnrichments:()=>bt,markSnapshotUnavailable:()=>$,processPendingSessions:()=>xt,readSessionsIndex:()=>N}),z=o(`session-freezer`),Ye=4,B=2048,V=40,Xe=`${j}/attachments`;async function H(e){let t=await ct(e.sessionStore,J(e));if(!t||t.messages.length<Ye)return z.info(`Skipping freeze: session below threshold or missing`,{messageCount:t?.messages.length??0}),null;let n=Y(t.messages),r=e.mode??`full`,i=r===`full`&&!!(e.apiKey&&e.model);!e.agenticMemorySpawn&&e.memory!==`skip`&&await G(e,n,i);let a=await Qe(e,n,i)||mt(t.messages);return await $e(e,t,a,r,i?await Ze(e,a):void 0,!!e.agenticMemorySpawn&&e.memory!==`skip`)}async function U(e,t){let n=Y(t.archive.messages),r;try{r=await Pe({spawn:e.agenticMemorySpawn,vfs:e.vfs,sessionArchivePath:P(t),sessionCount:await y(e.vfs),...e.cone?{cone:e.cone}:{}})}catch(e){r={ok:!1,reason:e instanceof Error?e.message:String(e),legacyFallbackSafe:!1}}if(r.ok){let n=await Nt(e.vfs,t.filename);return await wt(e.vfs,t.filename),n?(delete t.memoryPending,z.info(`Agentic memory pass completed`,{filename:t.filename}),n):(z.info(`Agentic memory pass completed; index entry already gone`,{filename:t.filename}),null)}return r.legacyFallbackSafe?(z.warn(`Agentic memory pass failed after finishing — falling back to legacy extraction`,{filename:t.filename,reason:r.reason}),await G(e,n,!0),null):(z.warn(`Agentic memory pass unfinished — entry stays pending for boot catch-up`,{filename:t.filename,reason:r.reason,attemptLimit:3}),null)}async function Ze(e,t){try{return W(await(e.pickIcon??(await i(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm--XIPLZbE.js`).then(e=>e.n);return{pickLucideIcon:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]))).pickLucideIcon)({subject:`"${t}" — an archived chat session`})??void 0)}catch(e){z.warn(`Icon pick failed (freeze still proceeds)`,{error:e instanceof Error?e.message:String(e)});return}}function W(e){if(e)return l(e)?e:void 0}async function G(e,r,i){if(!i){z.info(`LLM unavailable — skipping memory extraction; freezing anyway`);return}let a=``;try{a=await t({messages:r,instruction:n,model:e.model,apiKey:e.apiKey,maxTokens:B,headers:e.headers})}catch(e){z.warn(`Memory extraction call failed (freeze still proceeds)`,{error:e instanceof Error?e.message:String(e)});return}if(!a.trim()||a.trim()===`NONE`){z.info(`Memory extraction returned no durable memories`);return}try{await vt(e.vfs,st(J(e)),a.trim(),`new-session`,{model:e.model,apiKey:e.apiKey,headers:e.headers}),z.info(`Memory extracted and appended on new-session`)}catch(e){z.warn(`Memory append failed`,{error:e instanceof Error?e.message:String(e)})}}async function Qe(e,n,i){if(!i)return``;try{return pt(await t({messages:n,instruction:r,model:e.model,apiKey:e.apiKey,maxTokens:V,headers:e.headers}))}catch(e){return z.warn(`Title generation call failed (using heuristic)`,{error:e instanceof Error?e.message:String(e)}),``}}async function $e(e,t,n,r,i,a=!1){let o=new Date().toISOString(),s=crypto.randomUUID(),c=r===`quick`?`pending-${gt()}.md`:`${o.replace(/[:.]/g,`-`)}-${ht(n)}.md`,l=et(t.messages),u=J(e),d={cone:u,...u!==`cone`&&e.cone?.label?{coneLabel:e.cone.label}:{}},f={filename:c,sessionId:s,title:n,frozenAt:o,messageCount:t.messages.length,...l??{},...d,...i?{icon:i}:{},...r===`quick`?{pendingEnrichment:!0}:{},...a?{memoryPending:!0}:{},...e.memory===`skip`?{memorySkipped:!0}:{}};try{await X(e.vfs,j);let r=await nt(e.vfs,t.messages,c.replace(/\.md$/,``)),i={id:t.id,title:n,frozenAt:o,createdAt:t.createdAt,updatedAt:t.updatedAt,messageCount:t.messages.length,messages:r,...l??{},...d,...e.memory===`skip`?{memorySkipped:!0}:{}},a=ft(i);return await e.vfs.writeFile(`${j}/${c}`,a),await yt(e.vfs,f),await e.vfs.flush(),z.info(`Cone session frozen`,{filename:c,title:n,cone:u,messageCount:t.messages.length}),{...f,archive:i}}catch(e){return z.warn(`Failed to write frozen session to VFS`,{error:e instanceof Error?e.message:String(e)}),null}}function et(e){let t={total:0,input:0,output:0,cacheRead:0,cacheWrite:0},n=new Map,r=!1;for(let i of e){if(i.role!==`assistant`)continue;let{model:e,usage:a}=i;if(!e||!a||!tt(a))return null;let o=a.cost;r=!0,t.total+=o.total,t.input+=o.input,t.output+=o.output,t.cacheRead+=o.cacheRead,t.cacheWrite+=o.cacheWrite;let s=n.get(e)??{model:e,cost:0,turns:0,tokens:0};s.cost+=o.total,s.turns+=1,s.tokens+=a.input+a.output+a.cacheRead+a.cacheWrite,n.set(e,s)}return r?{cost:t,models:[...n.values()].sort((e,t)=>t.cost-e.cost)}:null}function K(e){return typeof e==`number`&&Number.isFinite(e)}function tt(e){let{cost:t}=e;return[e.input,e.output,e.cacheRead,e.cacheWrite].every(K)&&[t.input,t.output,t.cacheRead,t.cacheWrite,t.total].every(K)}async function nt(e,t,n){let r={vfs:e,archiveDir:`${Xe}/${n}`,copiedPaths:new Map,fileIndex:0},i=[];for(let e of t){if(!e.attachments?.some(q)){i.push(e);continue}let t=[];for(let n of e.attachments)t.push(await rt(r,n));i.push({...e,attachments:t})}return i}async function rt(e,t){if(!q(t))return t;let n=e.copiedPaths.get(t.path);if(n)return{...t,path:n};let r=await it(e.vfs,t.path);if(!r)return ot(t);let i=t.name.replace(/[^A-Za-z0-9._-]+/g,`_`)||`attachment`,a=`${e.archiveDir}/${e.fileIndex++}-${i}`;return await X(e.vfs,e.archiveDir),await e.vfs.writeFile(a,r),e.copiedPaths.set(t.path,a),{...t,path:a}}async function it(e,t){try{if(!await at(e,t))return null;let n=await e.readFile(t,{encoding:`binary`});if(!(n instanceof Uint8Array))throw Error(`Expected binary attachment content at ${t}`);return n}catch{return null}}function q(e){return typeof e.path==`string`&&e.path.startsWith(`/tmp/`)&&e.data===void 0&&e.text===void 0}async function at(e,t){let n=t.split(`/`).slice(1);if(n.length<2||n[0]!==`tmp`||n.some(e=>!e||e===`.`||e===`..`))return!1;let r=`/`;for(let t=0;t<n.length;t+=1){let i=(await e.readDir(r)).find(e=>e.name===n[t]);if(!i)return!1;if(t===n.length-1)return i.type===`file`;if(i.type!==`directory`)return!1;r=r===`/`?`/${n[t]}`:`${r}/${n[t]}`}return!1}function ot(e){let{path:t,...n}=e;return{...n,error:e.error??`Archived attachment file is missing or unsafe to preserve.`}}function J(e){return e.cone?.folder||`cone`}function st(e){return h({parentJid:null,folder:e}).memoryPath}async function ct(e,t){let n=f({folder:t});try{return await e.load(n)}catch(e){return z.warn(`Failed to load cone chat session`,{sessionId:n,error:e instanceof Error?e.message:String(e)}),null}}function Y(e){return e.map(e=>({role:e.role,content:[{type:`text`,text:e.content}],timestamp:e.timestamp}))}var lt=`<!-- slicc:session-data
|
|
154
|
-
`,ut=`
|
|
155
|
-
-->`;function dt(e){return e.map(e=>{let t={id:e.id,role:e.role,content:e.content,timestamp:e.timestamp};return e.attachments?.length&&(t.attachments=e.attachments),e.toolCalls?.length&&(t.toolCalls=e.toolCalls.map(e=>({id:e.id,name:e.name,input:e.input,...e.result===void 0?{}:{result:e.result},...e.isError?{isError:e.isError}:{}}))),e.source&&(t.source=e.source),e.channel&&(t.channel=e.channel),t})}function ft(e){let t=(e.cost?`cost: ${JSON.stringify(e.cost)}\n`:``)+(e.models?`models: ${JSON.stringify(e.models)}\n`:``),n=(e.cone?`cone: ${e.cone}\n`:``)+(e.coneLabel?`coneLabel: ${JSON.stringify(e.coneLabel)}\n`:``)+(e.memorySkipped?`memorySkipped: true
|
|
156
|
-
`:``),r=`---\nid: ${e.id}\ntitle: ${JSON.stringify(e.title)}\nfrozenAt: ${e.frozenAt}\ncreatedAt: ${e.createdAt}\nupdatedAt: ${e.updatedAt}\nmessageCount: ${e.messageCount}\n`+t+n+`---
|
|
157
|
-
|
|
158
|
-
`,i=`${lt}${JSON.stringify(dt(e.messages)).replace(/-->/g,`-- >`)}${ut}\n\n`,a=`# ${e.title}\n\n`;return r+i+a+R(e.messages)}function pt(e){let t=e.trim();return t=t.replace(/^["'`]+|["'`]+$/g,``).trim(),t=t.replace(/\s+/g,` `),t.length>80&&(t=t.slice(0,80).trimEnd()),t}function mt(e){let t=e.find(e=>e.role===`user`);if(!t?.content)return`untitled-session`;let n=t.content.trim().replace(/\s+/g,` `);return n.length>60?`${n.slice(0,60)}…`:n||`untitled-session`}function ht(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48)||`session`}function gt(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`}function _t(e){return e.startsWith(`pending-`)}async function X(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function vt(e,t,n,r,i){let a=t,o=``;try{let t=await e.readFile(a,{encoding:`utf-8`});o=typeof t==`string`?t:new TextDecoder().decode(t)}catch(t){if(!(t instanceof c)||t.code!==`ENOENT`)throw t;await X(e,a.slice(0,a.lastIndexOf(`/`)))}let s=`## Auto-extracted (${new Date().toISOString().slice(0,10)}, ${r})`,l=`${o.length===0||o.endsWith(`
|
|
159
|
-
`)?``:`
|
|
160
|
-
`}\n${s}\n\n${n}\n`;await e.writeFile(a,o+l);try{await be({vfs:e,memoryPath:a,model:i?.model,apiKey:i?.apiKey,headers:i?.headers,signal:i?.signal})}catch(e){z.warn(`Cone memory budget step threw (append already committed)`,{error:e instanceof Error?e.message:String(e)})}}async function yt(e,t){let n=[];try{let t=await e.readFile(M,{encoding:`utf-8`}),r=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(r);Array.isArray(i)&&(n=i)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let r=[t,...n.filter(e=>e.filename!==t.filename)];await e.writeFile(M,JSON.stringify(r,null,2))}async function bt(e){return(await N(e)).filter(e=>(e.pendingEnrichment===!0||e.memoryPending===!0)&&St(e)<3)}async function xt(e){let t={attempted:0,completed:0};if(!e.model||!e.apiKey)return t;try{let n=await bt(e.vfs);for(let r of n)try{let n=await Pt(e.vfs,r.filename);if(!n)continue;t.attempted+=1,await Z(e.vfs,n,{model:e.model,apiKey:e.apiKey,headers:e.headers})&&(t.completed+=1)}catch(e){z.warn(`Pending session catch-up attempt failed`,{filename:r.filename,error:e instanceof Error?e.message:String(e)})}}catch(e){z.warn(`Pending session catch-up failed`,{error:e instanceof Error?e.message:String(e)})}return t}function St(e){let t=e.pendingAttemptCount;return typeof t==`number`&&Number.isInteger(t)&&t>0?t:0}async function Z(e,t,n){if(!t.pendingEnrichment&&!t.memoryPending)return null;let r=await Et(e,t);if(r===null)return null;let i=Dt(t,r);if(i===null)return null;let a=t.memoryPending===!0&&n.skipMemory!==!0&&await Ct(e,t),o=a||t.memorySkipped===!0?{...n,skipMemory:!0}:n,s=await Ot(t,i,o);if(s===null)return null;let c=await Tt(o,s.newTitle);await kt(e,t,s.bullets,o);let l=await jt(e,t,r,s.newTitle,c,n.skipMemory===!0);return l&&a&&await wt(e,t.filename),l}async function Ct(e,t){try{return await e.stat(k(`/sessions/${t.filename}`)),!0}catch{return!1}}async function wt(e,t){try{await e.rm(k(`/sessions/${t}`))}catch{}}async function Tt(e,t){if(e.pickIcon)try{return await W(await e.pickIcon({subject:`"${t}" — an archived chat session`})??void 0)}catch(e){z.warn(`Enrichment icon pick failed (continuing without icon)`,{error:e instanceof Error?e.message:String(e)});return}}async function Et(e,t){try{let n=await e.readFile(P(t),{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){return e?.code===`ENOENT`?z.info(`Pending archive missing — treating as already enriched`,{filename:t.filename}):z.warn(`Failed to read pending archive (entry stays pending)`,{filename:t.filename,error:e instanceof Error?e.message:String(e)}),null}}function Dt(e,t){let n;try{n=F(t).messages}catch(t){return z.warn(`Failed to parse pending archive — leaving entry intact`,{filename:e.filename,error:t instanceof Error?t.message:String(t)}),null}return n.length===0?(z.info(`Pending archive has no messages — skipping enrichment`,{filename:e.filename}),null):Y(n)}async function Ot(e,i,a){let o=``;if(!a.skipMemory)try{o=await t({messages:i,instruction:n,model:a.model,apiKey:a.apiKey,maxTokens:B,headers:a.headers})}catch(t){return z.warn(`Enrichment memory call failed (entry stays pending)`,{filename:e.filename,error:t instanceof Error?t.message:String(t)}),null}let s=``;try{s=pt(await t({messages:i,instruction:r,model:a.model,apiKey:a.apiKey,maxTokens:V,headers:a.headers}))}catch(t){return z.warn(`Enrichment title call failed (entry stays pending)`,{filename:e.filename,error:t instanceof Error?t.message:String(t)}),null}return s?{bullets:o,newTitle:s}:(z.info(`Enrichment title call returned empty — entry stays pending`,{filename:e.filename}),null)}async function kt(e,t,n,r){let i=n.trim();if(!(!i||i===`NONE`))try{await vt(e,st(t.cone||`cone`),i,`pending-enrichment`,{model:r.model,apiKey:r.apiKey,headers:r.headers})}catch(e){z.warn(`Enrichment memory append failed (continuing with title rewrite)`,{filename:t.filename,error:e instanceof Error?e.message:String(e)})}}function At(e,t,n,r,i){let a=r??e.icon;return{filename:t,title:n,frozenAt:e.frozenAt,messageCount:e.messageCount,...e.cost?{cost:e.cost}:{},...e.models?{models:e.models}:{},...e.cone?{cone:e.cone}:{},...e.coneLabel?{coneLabel:e.coneLabel}:{},...e.sessionId?{sessionId:e.sessionId}:{},...a?{icon:a}:{},...e.completeSnapshotUnavailable?{completeSnapshotUnavailable:!0}:{},...i&&e.memoryPending?{memoryPending:!0}:{},...e.memorySkipped?{memorySkipped:!0}:{}}}async function jt(e,t,n,r,i,a=!1){let o=P(t),s=_t(t.filename),c=s?r:t.title,l=s?`${t.frozenAt.replace(/[:.]/g,`-`)}-${ht(r)}.md`:t.filename,u=`${j}/${l}`;if(s)try{await X(e,j),await e.writeFile(u,Mt(n,c))}catch(e){return z.warn(`Enrichment write failed (entry stays pending)`,{filename:t.filename,error:e instanceof Error?e.message:String(e)}),null}let d=At(t,l,c,i,a);try{await Ft(e,t.filename,d)}catch(e){return z.warn(`Enrichment index update failed (entry may stay pending)`,{filename:t.filename,error:e instanceof Error?e.message:String(e)}),null}if(u!==o)try{await e.rm(o)}catch(e){z.info(`Stale pending archive cleanup failed (harmless)`,{oldPath:o,error:e instanceof Error?e.message:String(e)})}try{await e.flush()}catch{}return z.info(`Pending session enriched`,{oldFilename:t.filename,newFilename:l,title:c}),d}function Mt(e,t){let n=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!n)return e;let r=n[1].replace(/^title:\s*.+$/m,`title: ${JSON.stringify(t)}`),i=n[2];return i=i.replace(/^#\s+[^\n]*$/m,`# ${t}`),`---\n${r}\n---\n${i}`}var Q=Promise.resolve();async function Nt(e,t){let n=null,r=async()=>{let r=await N(e),i=r.findIndex(e=>e.filename===t);if(i===-1)return;let{memoryPending:a,pendingEnrichment:o,pendingAttemptCount:s,...c}=r[i],l=r.slice();l[i]=c,await e.writeFile(M,JSON.stringify(l,null,2)),await e.flush(),n=c},i=Q.then(r,r);Q=i.then(()=>void 0,()=>void 0);try{await i}catch(e){z.warn(`Failed to clear agentic memory pending marker`,{filename:t,error:e instanceof Error?e.message:String(e)})}return n}async function Pt(e,t){let n=null,r=async()=>{let r=await N(e),i=r.findIndex(e=>e.filename===t);if(i===-1)return;let a=r[i];if(!a.pendingEnrichment&&!a.memoryPending)return;let o=St(a);if(o>=3)return;n={...a,pendingAttemptCount:o+1};let s=r.slice();s[i]=n,await e.writeFile(M,JSON.stringify(s,null,2)),await e.flush()},i=Q.then(r,r);return Q=i.then(()=>void 0,()=>void 0),await i,n}async function Ft(e,t,n){let r=async()=>{let r=[];try{let t=await e.readFile(M,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(n);Array.isArray(i)&&(r=i)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let i=r.findIndex(e=>e.filename===t),a;i===-1?a=[n,...r.filter(e=>e.filename!==n.filename)]:(a=r.slice(),a[i]=n,a=a.filter((e,t)=>t===i||e.filename!==n.filename)),await e.writeFile(M,JSON.stringify(a,null,2))},i=Q.then(r,r);return Q=i.then(()=>void 0,()=>void 0),i}async function $(e,t){let n=async()=>{let n=[];try{let t=await e.readFile(M,{encoding:`utf-8`}),r=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(r);Array.isArray(i)&&(n=i)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e;return}if(!n.find(e=>e.filename===t))return;let r=n.map(e=>e.filename===t?{...e,completeSnapshotUnavailable:!0}:e);await e.writeFile(M,JSON.stringify(r,null,2))},r=Q.then(n,n);return Q=r.then(()=>void 0,()=>void 0),r}export{xt as a,M as c,N as d,g as f,$ as i,P as l,Z as n,Je as o,ae as p,H as r,R as s,U as t,F as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(){return{version:`6.85.0`,releasedAt:`2026-08-23T08:04:26Z`,buildId:`6.85.0-mt5iu64p`}}let t=null;function n(e){t=e}function r(){return t}export{e as n,n as r,r as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/panel-rpc-B3MSVImO.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/panel-rpc-handlers-DIavhh02.js","assets/account-store-CC9-shzK.js","assets/preload-helper-Czpn1I53.js","assets/bedrock-camp-qpZqnqLa.js","assets/diagnostics-DN_idNHx.js","assets/transform-messages-N_eMsP2M.js","assets/provider-env-CTOcDKrQ.js","assets/__vite-browser-external-5eBdwsFd.js","assets/openrouter.models-gbjkpjE_.js","assets/libesm-BI4UHVqp.js","assets/logger-DDBAeTLF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-B4g-4VbQ.js","assets/base64-DpPqYZJF.js","assets/runtime-env-Dlaokqg1.js","assets/fetch-body-D2PwksUW.js","assets/float-topology-BgioAcOd.js","assets/runtime-env-E-i2SW1s.js","assets/secret-topology-xLmXoozo.js","assets/secrets-bridge-client-cWDAnFqs.js","assets/port-bridge-client-BbVs1yhx.js","assets/image-markers-BXtVm4og.js","assets/tool-ui-DfXu6quJ.js","assets/providers-Br4FC81W.js","assets/provider-settings-DDkeX-2T.js","assets/telemetry-BVzuNdvW.js","assets/runtime-env-CgsZ7LTp.js","assets/tray-runtime-config-CRGwg9SK.js","assets/messages-BD4p8GuF.js","assets/tray-follower-status-BAjnN7Ar.js","assets/clipboard-eqmn97SP.js","assets/tray-join-url-BIvzbiFR.js","assets/hid-device-registry-B2R-0rNt.js","assets/serial-port-registry-B3LG5UIy.js","assets/usb-operations-Cgk-otz-.js","assets/usb-device-registry-CRsCisej.js","assets/wc-permissions-registry-BVc_OAkS.js","assets/permissions-surface-registry-CilCRwhh.js","assets/tray-leader-DcRtwWl-.js","assets/db-DIbBClfy.js","assets/tray-sync-protocol-DV_QG_Ey.js","assets/tray-sync-protocol-BZ5yhJH9.js","assets/hosted-config-apply-uAym2aS5.js","assets/tab-teleport-Dhh60nH7.js","assets/slicc-app-url-BsBryEhn.js","assets/teleport-storage-CwYntbOB.js","assets/logger-BoSvu4mW.js","assets/src-BWaKqLvQ.js","assets/wc-transcript-export-DKIleW7-.js","assets/export-spool-Eul4J1RP.js","assets/page-approval-service-Bbc3_KdK.js","assets/theme-engine-By4GU_Wc.js","assets/legacy-styles-DcRu2WCJ.js","assets/tray-leave-runtime-BGfdX5KF.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{C as e,H as t,I as n,L as r,d as i,f as a}from"./account-store-CC9-shzK.js";import{t as o}from"./preload-helper-Czpn1I53.js";import{t as s}from"./logger-DDBAeTLF.js";import{n as c}from"./attachments-CByeG2Ru.js";import{n as l,t as u}from"./base64-DpPqYZJF.js";import{r as d}from"./src-CAWTvdAa.js";import{o as f,r as p}from"./proxied-fetch-B4g-4VbQ.js";import{t as m}from"./slicc-app-url-BsBryEhn.js";import{d as h,f as g,l as _,p as v}from"./tray-sync-protocol-BZ5yhJH9.js";import{a as y,i as b,p as ee,r as x}from"./tray-runtime-config-CRGwg9SK.js";import{r as te}from"./panel-rpc-B3MSVImO.js";import{a as S,c as ne,d as re,f as C,i as ie,l as ae,n as oe,o as se,r as ce,s as le,t as ue,u as w}from"./wc-tray-scoops-B2RP8cgD.js";import{a as de,t as fe}from"./tray-follower-status-BAjnN7Ar.js";import"./provider-settings-DDkeX-2T.js";import{t as pe}from"./permissions-surface-registry-CilCRwhh.js";import{t as me}from"./pending-request-table-Dgn6qYdL.js";import"./logger-BoSvu4mW.js";import"./handoff-link-BM4ctkE8.js";import{t as he}from"./remote-cdp-transport-CgOXLjZ8.js";import{n as ge}from"./path-utils-DNJG-zQf.js";import{t as _e}from"./terminal-session-client-ADzaWGFd.js";import{i as ve,n as T,t as ye}from"./tray-leader-DcRtwWl-.js";import{i as be,s as xe}from"./record-Z5ZWTUPJ.js";import"./teleport-storage-CwYntbOB.js";import{i as Se,n as Ce}from"./tray-sync-protocol-DV_QG_Ey.js";import{t as we}from"./synthetic-cdp-transport-Ds83IPjw.js";import{n as E,r as D}from"./sprinkle-instances-B8n7h-oP.js";import{l as Te,t as Ee}from"./follower-presentation-DqBw0YiV.js";import{a as De,c as Oe,h as O,i as k,o as A,s as ke,t as Ae}from"./host-command-G_JIdBPR.js";import{n as je,r as Me,t as Ne}from"./leader-session-events-CC6poXIx.js";var j=s(`tab-persistence-guard`),Pe=`slicc-tray-leader-active`,Fe=class{options;active=!1;audioCtx=null;oscillator=null;lockController=null;beforeUnloadHandler=null;constructor(e={}){this.options=e}activate(){this.active||(this.active=!0,this.startSilentAudio(),this.acquireWebLock(),this.installBeforeUnload(),j.info(`Tab persistence guard activated`))}deactivate(){this.active&&(this.active=!1,this.stopSilentAudio(),this.releaseWebLock(),this.removeBeforeUnload(),j.info(`Tab persistence guard deactivated`))}isActive(){return this.active}startSilentAudio(){try{let e=(this.options.audioContextFactory??(()=>{let e=typeof globalThis<`u`?globalThis.AudioContext??globalThis.webkitAudioContext:void 0;return e?new e:null}))();if(!e){j.warn(`AudioContext unavailable — discard prevention via silent audio disabled`);return}e.resume?.().catch(()=>{});let t=e.createOscillator(),n=e.createGain();n.gain.value=0,t.connect(n),n.connect(e.destination),t.start(),this.audioCtx=e,this.oscillator=t}catch(e){j.warn(`Failed to start silent audio guard`,{error:e instanceof Error?e.message:String(e)})}}stopSilentAudio(){try{this.oscillator?.stop()}catch{}this.oscillator=null,this.audioCtx&&=(this.audioCtx.close?.().catch(()=>{}),null)}acquireWebLock(){try{let e=this.options.lockManager??(typeof navigator<`u`&&`locks`in navigator?navigator.locks:null);if(!e){j.warn(`navigator.locks unavailable — discard prevention via Web Lock disabled`);return}let t=new AbortController;this.lockController=t,e.request(Pe,{mode:`exclusive`,signal:t.signal},()=>new Promise(e=>{if(t.signal.aborted){e();return}let n=()=>{t.signal.removeEventListener(`abort`,n),e()};t.signal.addEventListener(`abort`,n,{once:!0})})).catch(e=>{e?.name!==`AbortError`&&j.warn(`Web Lock request rejected`,{error:e instanceof Error?e.message:String(e)})})}catch(e){j.warn(`Failed to acquire Web Lock`,{error:e instanceof Error?e.message:String(e)})}}releaseWebLock(){try{this.lockController?.abort()}catch{}this.lockController=null}installBeforeUnload(){try{let e=this.options.windowRef??(typeof window<`u`?window:null);if(!e)return;let t=()=>{};e.addEventListener(`beforeunload`,t),this.beforeUnloadHandler=t}catch{}}removeBeforeUnload(){try{let e=this.options.windowRef??(typeof window<`u`?window:null);e&&this.beforeUnloadHandler&&e.removeEventListener(`beforeunload`,this.beforeUnloadHandler)}catch{}this.beforeUnloadHandler=null}};s(`playwright-teleport`);function Ie(e){if(e.userName)return`${e.providerId}:${e.userName}`;if(e.accessToken)try{let t=JSON.parse(atob(e.accessToken.split(`.`)[1].replace(/-/g,`+`).replace(/_/g,`/`))),n=t.email??t.user_id??t.sub;if(n)return`${e.providerId}:${n}`}catch{}return null}async function Le(){try{let e=i().filter(e=>!e.loggedOut),t=[`adobe`,`github`].map(t=>e.find(e=>e.providerId===t)).find(Boolean)??e[0],n=t?Ie(t):null;if(!n)return`00000000`;let r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return Array.from(new Uint8Array(r,0,4),e=>e.toString(16).padStart(2,`0`)).join(``)}catch{return`00000000`}}function M(e,t){let n=e()?.currentLeaderSync;if(!n)throw Error(`serve ${t}: no active leader tray`);return n}function Re(e,t){return{lifecycleRecords:[...e.getPreviewLifecycleRecords(t)]}}function ze(e,t){return{cleared:e.clearPreviewLifecycleRecords(t),rearmed:e.rearmPreviewAnnouncements(t)}}async function Be(e){let{instanceId:t,browser:n,remoteCdpBridge:r,remoteCdpPushChannel:i,getLeader:a,performTrayLeaveLocally:s,window:c}=e,{installPanelRpcHandler:l,createPanelRpcEventEmitter:u}=await o(async()=>{let{installPanelRpcHandler:e,createPanelRpcEventEmitter:t}=await import(`./panel-rpc-B3MSVImO.js`).then(e=>e.i);return{installPanelRpcHandler:e,createPanelRpcEventEmitter:t}},__vite__mapDeps([0,1])),{createStandalonePanelRpcHandlers:d}=await o(async()=>{let{createStandalonePanelRpcHandlers:e}=await import(`./panel-rpc-handlers-DIavhh02.js`);return{createStandalonePanelRpcHandlers:e}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,26,27,28,29,30,31,32,33,34,35,36,37])),{getLeaderPermissionsSurface:f}=await o(async()=>{let{getLeaderPermissionsSurface:e}=await import(`./wc-permissions-registry-BVc_OAkS.js`).then(e=>e.t);return{getLeaderPermissionsSurface:e}},__vite__mapDeps([38,1,39])),p=u({instanceId:t}),m=new Map,h=l({instanceId:t,handlers:d({resetTray:async()=>{let e=a();if(!e)throw Error(`no active tray session to reset`);return await e.reset()},leaveTray:async({workerBaseUrl:e,requestId:t})=>await s({workerBaseUrl:e,requestId:t}),joinTray:({joinUrl:e})=>(ee(c.localStorage,e),c.dispatchEvent(new CustomEvent(`slicc:tray-join`,{detail:{joinUrl:e}})),{joinUrl:e}),emitEvent:(e,t)=>p.emit(e,t),emitCherrySliccEvent:(e,t,n)=>a()?.sync.emitCherrySliccEvent(e,t,n)??!1,execOnRemote:async({runtimeId:e,command:t,cwd:n,env:r,execToken:i,timeoutMs:o})=>{let s=a()?.currentLeaderSync;if(!s)throw Error(`ssh: no active leader tray`);let c=new AbortController;m.set(i,c);try{return await s.execOnRemote(e,t,{cwd:n,env:r,signal:c.signal,timeoutMs:o})}finally{m.delete(i)}},signalRemoteExec:({execToken:e})=>{m.get(e)?.abort()},mintPreview:async e=>{let t=a()?.currentLeaderSync;if(!t)throw Error(`serve: no active leader tray; cannot mint preview`);let{getLeaderTrayRuntimeStatus:n}=await o(async()=>{let{getLeaderTrayRuntimeStatus:e}=await import(`./tray-leader-DcRtwWl-.js`).then(e=>e.a);return{getLeaderTrayRuntimeStatus:e}},__vite__mapDeps([40,1,12,14,4,15,13,16,17,28,19,29,30,41])),r=n().session;if(!r)throw Error(`serve: leader tray has no active session`);let i=new URL(r.controllerUrl).pathname.split(`/`).pop()??``,{CHERRY_RUNTIME_TAG:s}=await o(async()=>{let{CHERRY_RUNTIME_TAG:e}=await import(`./tray-sync-protocol-DV_QG_Ey.js`).then(e=>e.a);return{CHERRY_RUNTIME_TAG:e}},__vite__mapDeps([42,1,12,13,43])),{mintPreviewViaWorker:c}=await o(async()=>{let{mintPreviewViaWorker:e}=await import(`./preview-mint-client-CF-bFBqv.js`);return{mintPreviewViaWorker:e}},[]),l=t.getConnectedFollowers().some(e=>e.runtime===s),u=!e.noBridge&&(e.bridge||l),d=!e.noBridge&&e.bridge,f=await Le(),{url:p,previewToken:m}=await c({workerBaseUrl:r.workerBaseUrl,trayId:r.trayId,controllerToken:i,servedRoot:e.servedRoot,entryPath:e.entryPath,allowLive:u,bridge:d,maxTabs:e.maxTabs,webhookId:e.webhookId,userHash:f,quiet:e.quiet??!1,ttlMs:e.ttlMs,snapshotFiles:e.snapshotFiles}),h=e.entryPath?e.entryPath.split(`/`).pop()??`Preview`:`Preview`;return t.registerMintedPreview(m,{url:p,title:h,quiet:e.quiet??!1}),t.broadcastPreviewOpen(p),{url:p,pushed:t.getConnectedFollowers().length,previewToken:m}},revokePreview:async({previewToken:e})=>{let t=a()?.currentLeaderSync;if(!t)throw Error(`serve --stop: no active leader tray; cannot revoke preview`);let{getLeaderTrayRuntimeStatus:n}=await o(async()=>{let{getLeaderTrayRuntimeStatus:e}=await import(`./tray-leader-DcRtwWl-.js`).then(e=>e.a);return{getLeaderTrayRuntimeStatus:e}},__vite__mapDeps([40,1,12,14,4,15,13,16,17,28,19,29,30,41])),r=n().session;if(!r)throw Error(`serve --stop: leader tray has no active session`);let i=new URL(r.controllerUrl).pathname.split(`/`).pop()??``,{revokePreviewViaWorker:s}=await o(async()=>{let{revokePreviewViaWorker:e}=await import(`./preview-mint-client-CF-bFBqv.js`);return{revokePreviewViaWorker:e}},[]),c=await s({workerBaseUrl:r.workerBaseUrl,trayId:r.trayId,controllerToken:i,previewToken:e});return t.dropMintedPreview(e),c},listPreviews:async()=>{let{getLeaderTrayRuntimeStatus:e}=await o(async()=>{let{getLeaderTrayRuntimeStatus:e}=await import(`./tray-leader-DcRtwWl-.js`).then(e=>e.a);return{getLeaderTrayRuntimeStatus:e}},__vite__mapDeps([40,1,12,14,4,15,13,16,17,28,19,29,30,41])),t=e().session;if(!t)throw Error(`serve: leader tray has no active session`);let n=new URL(t.controllerUrl).pathname.split(`/`).pop()??``,{listPreviewsViaWorker:r}=await o(async()=>{let{listPreviewsViaWorker:e}=await import(`./preview-mint-client-CF-bFBqv.js`);return{listPreviewsViaWorker:e}},[]);return await r({workerBaseUrl:t.workerBaseUrl,trayId:t.trayId,controllerToken:n})},getPreviewLifecycleRecords:e=>Re(M(a,`--logs`),e),truncatePreviewLifecycleRecords:e=>ze(M(a,`--truncate`),e),listRemoteTargets:()=>n.listAllTargets(),remoteCdp:r,getPermissionsSurface:()=>f(),shouldDelegateOAuth:()=>a()?.sync.shouldDelegateOAuthLogin()===!0,delegateOAuthLogin:async e=>{let t=a()?.sync;return t?.shouldDelegateOAuthLogin()?{delegated:!0,...await t.delegateOAuthLogin(e)}:{delegated:!1}}})});c.addEventListener(`beforeunload`,()=>{h(),p.dispose(),r.disposeAll(),i?.close()},{once:!0})}async function Ve(e){let{log:r}=e;await new Promise(e=>setTimeout(e,5e3));try{let e=await fetch(f(`/api/hosted-bootstrap`),{signal:AbortSignal.timeout(1e4),headers:p()});if(!e.ok)return;let i=await e.json(),a=i.accounts??(i.adobeImsToken?[{providerId:`adobe`,kind:`oauth`,accessToken:i.adobeImsToken}]:[]);i.model?localStorage.setItem(`selected-model`,i.model):localStorage.getItem(`selected-model`)||localStorage.setItem(`selected-model`,`adobe:claude-opus-4-6`),i.effortLevel?localStorage.setItem(`slicc_locked_effort_level`,i.effortLevel):localStorage.removeItem(`slicc_locked_effort_level`);let[{applyHostedAccounts:s,prewarmHostedModels:c},l]=await Promise.all([o(()=>import(`./hosted-config-apply-uAym2aS5.js`),__vite__mapDeps([44,12])),o(()=>import(`./provider-settings-DDkeX-2T.js`).then(e=>e.t),__vite__mapDeps([26,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,27,28,29,30,31,32,33]))]);await c(a,{getRefreshModels:e=>l.getProviderConfig(e).refreshModels});let u=JSON.parse(localStorage.getItem(`slicc_cloud_managed`)??`[]`);await s(a,{saveOAuthAccount:t,addAccount:l.addAccount,removeAccount:n,currentProviderIds:()=>l.getAccounts().map(e=>e.providerId),previouslyManaged:()=>u}),localStorage.setItem(`slicc_cloud_managed`,JSON.stringify(a.map(e=>e.providerId))),r.info(`hosted-leader: cone config applied`,{count:a.length})}catch(e){r.warn(`hosted-leader: bootstrap fetch failed; provider needs manual login`,{error:e instanceof Error?e.message:String(e)})}}var He=0,Ue=class{client;sessions=new Map;constructor(e){this.client=e}async run(e){let t=this.getOrCreate(e);if(t.running)return{exitCode:1,error:`another terminal command is already running`};t.running=!0,t.onChunk=e.onChunk;let n=()=>t.session.signal(`SIGINT`);try{return await t.opened,e.signal.addEventListener(`abort`,n,{once:!0}),e.signal.aborted?{exitCode:130}:{exitCode:(await t.session.exec(e.command,{cwd:e.cwd,env:e.env,discardCapturedOutput:!0})).exitCode}}catch(t){return this.close(e.sessionId),{exitCode:1,error:t instanceof Error?t.message:String(t)}}finally{e.signal.removeEventListener(`abort`,n),t.onChunk=void 0,t.running=!1}}close(e){let t=this.sessions.get(e);t&&(this.sessions.delete(e),t.session.close(),t.session.dispose())}getOrCreate(e){let t=this.sessions.get(e.sessionId);if(t)return t;let n=`follower-exec-${++He}-${Date.now()}`,r={};return r.session=new _e({client:this.client,sid:n,onEvent:e=>{e.type===`terminal-output`&&r.onChunk?.(e.stream,e.data)}}),r.opened=r.session.open({cwd:e.cwd,env:e.env}),r.running=!1,this.sessions.set(e.sessionId,r),r}};function N(e,t){if(!e||!t||!e.startsWith(`/`)||t===`/`||/%2[eE]/.test(e)||e.split(`/`).some(e=>e===`.`||e===`..`))return!1;let n=t.endsWith(`/`)?t.slice(0,-1):t;return e===n||e.startsWith(n+`/`)}var We=65536;async function Ge(e,t,n){let{reqId:r,servedRoot:i,asText:a}=e,o=e.vfsPath;if(!N(o,i)){t.send({type:`preview.response`,reqId:r,ok:!1,status:403});return}try{if((await n.stat(o)).type===`directory`&&(o=o.replace(/\/?$/,`/`)+`index.html`,!N(o,i))){t.send({type:`preview.response`,reqId:r,ok:!1,status:403});return}}catch{}let s,c;try{if(a)s=await n.readFile(o,{encoding:`utf-8`}),c=`utf-8`;else{let e=await n.readFile(o,{encoding:`binary`});s=l(e),c=`base64`}}catch(e){e?.code===`ENOENT`?t.send({type:`preview.response`,reqId:r,ok:!1,status:404}):t.send({type:`preview.response`,reqId:r,ok:!1,status:500,reason:String(e?.message??e)});return}let u=qe(o),d=Ke(s,We);for(let e=0;e<d.length;e++)t.send({type:`preview.response`,reqId:r,ok:!0,mime:u,chunkIndex:e,totalChunks:d.length,content:d[e],encoding:c})}function Ke(e,t){if(e.length<=t)return[e];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function qe(e){return/\.html?$/i.test(e)?`text/html`:/\.css$/i.test(e)?`text/css`:/\.m?js$/i.test(e)?`application/javascript`:/\.json$/i.test(e)?`application/json`:/\.svg$/i.test(e)?`image/svg+xml`:/\.png$/i.test(e)?`image/png`:/\.jpe?g$/i.test(e)?`image/jpeg`:/\.gif$/i.test(e)?`image/gif`:/\.webp$/i.test(e)?`image/webp`:/\.ico$/i.test(e)?`image/x-icon`:/\.woff2$/i.test(e)?`font/woff2`:/\.woff$/i.test(e)?`font/woff`:/\.ttf$/i.test(e)?`font/ttf`:/\.mp4$/i.test(e)?`video/mp4`:/\.webm$/i.test(e)?`video/webm`:/\.mp3$/i.test(e)?`audio/mpeg`:/\.pdf$/i.test(e)?`application/pdf`:/\.xml$/i.test(e)?`application/xml`:/\.wasm$/i.test(e)?`application/wasm`:`application/octet-stream`}var P=32768,F=`[content too large to sync — view on leader]`;function Je(e){switch(e.type){case`tool_result`:return{...e,result:F};case`tool_use_start`:return{...e,toolInput:{note:F}};case`tool_ui`:return{...e,html:`<p>${F}</p>`};case`content_delta`:return{...e,text:F};case`terminal_output`:return{...e,text:F};case`screenshot`:return{type:`error`,error:`Screenshot ${F}`};default:return null}}var Ye=class{context;constructor(e){this.context=e}broadcastEvent(e){if(this.context.followers.followers.size===0)return;let t=this.context.options.getScoopJid(),n=this.context.followers.broadcastToAllFollowers({type:`agent_event`,event:e,scoopJid:t});if(n.length===0)return;let r=Je(e);if(r)for(let e of n)this.context.followers.followers.get(e)?.sync.send({type:`agent_event`,event:r,scoopJid:t})}broadcastUserMessage(e,t,n){if(this.context.followers.followers.size===0)return;let r=n?.length?c(n):n;this.broadcast({type:`user_message_echo`,text:e,messageId:t,scoopJid:this.context.options.getScoopJid(),attachments:r})}broadcastStatus(e){this.context.followers.followers.size!==0&&this.broadcast({type:`status`,scoopStatus:e,scoopJid:this.context.options.getScoopJid()})}async sendSnapshotToFollower(e,t){let n=this.context.followers.followers.get(e);if(!n)return;let{options:r}=this.context,i=r.getScoopJid(),a=t??n.selectedScoopJid??i;try{let e=r.getScoops?.();e&&!e.some(e=>e.jid===a)&&(a=i)}catch(e){this.context.log.warn(`getScoops failed while validating snapshot target`,{targetJid:a,error:e instanceof Error?e.message:String(e)})}let o;if(r.getMessagesForScoop&&a!==i)try{o=await Promise.resolve(r.getMessagesForScoop(a))}catch(e){this.context.log.warn(`getMessagesForScoop failed, falling back to active scoop`,{targetJid:a,error:e instanceof Error?e.message:String(e)}),a=i,o=r.getMessages()}else o=r.getMessages();n.selectedScoopJid=a,Se(n.sync,o,a),this.context.log.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:o.length,scoopJid:a})}broadcastSnapshot(){if(this.context.followers.followers.size!==0)for(let e of this.context.followers.followers.keys())this.sendSnapshotToFollower(e)}sendModelCatalogToFollower(e){let t=this.context.followers.followers.get(e);if(!t)return;let n=this.buildModelCatalog();n&&(this.publishModelCatalog(t,n),this.sendModelStateToFollower(e))}broadcastModelCatalog(){if(this.context.followers.followers.size===0)return;let e=this.buildModelCatalog();if(e){for(let t of this.context.followers.followers.values())this.publishModelCatalog(t,e);this.broadcastModelState()}}publishModelCatalog(e,t){if(t.length===0&&!e.modelCatalogSent){this.context.log.debug(`Model catalog empty; deferring models.list`,{bootstrapId:e.bootstrapId});return}t.length>0&&(e.modelCatalogSent=!0),e.sync.send({type:`models.list`,models:t})}broadcastModelState(){if(this.context.followers.followers.size!==0)for(let e of this.context.followers.followers.keys())this.sendModelStateToFollower(e)}sendModelStateToFollower(e){let t=this.context.followers.followers.get(e),n=this.context.options.getModelSelectionState;if(!t)return;if(!t.modelCatalogSent){let e=this.buildModelCatalog();e&&e.length>0&&this.publishModelCatalog(t,e)}if(!n)return;let r=t.selectedScoopJid??this.context.options.getScoopJid();try{t.sync.send({type:`model.state`,state:n(r)})}catch(t){this.context.log.warn(`Failed to compute model selection state`,{bootstrapId:e,scoopJid:r,error:t instanceof Error?t.message:String(t)})}}buildModelCatalog(){let e=this.context.options.getModelCatalog;if(!e)return null;try{return e().map(e=>({providerName:e.providerName,modelId:e.modelId,modelName:e.modelName,reasoning:e.reasoning===!0}))}catch(e){return this.context.log.warn(`Failed to compute model catalog`,{error:e instanceof Error?e.message:String(e)}),null}}sendScoopsListToFollower(e){let t=this.context.followers.followers.get(e);if(!t)return;let n=this.context.options.getScoops;if(n)try{t.sync.send({type:`scoops.list`,scoops:n(),activeScoopJid:this.context.options.getScoopJid()})}catch(t){this.context.log.warn(`Failed to send scoops.list`,{bootstrapId:e,error:t instanceof Error?t.message:String(t)})}}sendSprinklesListToFollower(e){let t=this.context.followers.followers.get(e);if(!t)return;let n=this.context.options.getSprinkles;if(n)try{t.sync.send({type:`sprinkles.list`,sprinkles:n()})}catch(t){this.context.log.warn(`Failed to send sprinkles.list`,{bootstrapId:e,error:t instanceof Error?t.message:String(t)})}}broadcastScoopsList(){if(this.context.followers.followers.size===0)return;let e=this.context.options.getScoops;if(!e)return;let t;try{t=e()}catch(e){this.context.log.warn(`Failed to compute scoops list`,{error:e instanceof Error?e.message:String(e)});return}this.broadcast({type:`scoops.list`,scoops:t,activeScoopJid:this.context.options.getScoopJid()})}broadcastSprinklesList(){if(this.context.followers.followers.size===0)return;let e=this.context.options.getSprinkles;if(!e)return;let t;try{t=e()}catch(e){this.context.log.warn(`Failed to compute sprinkles list`,{error:e instanceof Error?e.message:String(e)});return}this.broadcast({type:`sprinkles.list`,sprinkles:t})}broadcastSprinkleUpdate(e,t,n){let r=this.context.followers,i={type:`sprinkle.update`,sprinkleName:e,data:t};if(n?.runtime){let e=r.resolveFollowerByRuntimeId(n.runtime);return e?{followers:e.follower.sync.send(i)?[n.runtime]:[]}:{followers:[],unknownRuntime:n.runtime}}if(r.followers.size===0)return{followers:[]};let a=new Set(r.broadcastToAllFollowers(i)),o=[];for(let e of r.followers.keys())a.has(e)||o.push(r.runtimeIdForBootstrap(e)??e);return{followers:o}}broadcastTheme(e){this.context.followers.followers.size!==0&&this.broadcast({type:`theme.apply`,themeJson:e})}broadcastSprinkleReloaded(e){this.context.followers.followers.size!==0&&this.broadcast({type:`sprinkle.reloaded`,sprinkleName:e})}broadcastPreviewOpen(e){this.context.followers.followers.size!==0&&this.broadcast({type:`preview.open`,requestId:`prv-${crypto.randomUUID()}`,url:e})}async handleSprinkleFetch(e,t,n){let r=this.context.followers.followers.get(e);if(!r)return;let i=this.context.options.readSprinkleContent;if(!i){r.sync.send({type:`sprinkle.content`,requestId:t,sprinkleName:n,content:``,error:`Leader has no sprinkle content reader`});return}let a=null;try{a=await Promise.resolve(i(n))}catch(e){r.sync.send({type:`sprinkle.content`,requestId:t,sprinkleName:n,content:``,error:e instanceof Error?e.message:String(e)});return}if(a==null){r.sync.send({type:`sprinkle.content`,requestId:t,sprinkleName:n,content:``,error:`Sprinkle not found: ${n}`});return}if(a.length<=65536){r.sync.send({type:`sprinkle.content`,requestId:t,sprinkleName:n,content:a});return}let o=Math.ceil(a.length/P);for(let e=0;e<o;e++)r.sync.send({type:`sprinkle.content`,requestId:t,sprinkleName:n,content:a.slice(e*P,(e+1)*P),chunkIndex:e,totalChunks:o})}broadcast(e){this.context.followers.broadcastToAllFollowers(e)}},Xe=150,Ze=class{context;options;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;previewOriginalTarget=null;previewLastTargetId=null;previewGeneration=0;previewSequence=0;previewLatestSuccessfulSequence=0;previewRequestsInFlight=0;previewRestoreTimer=null;constructor(e,t){this.context=e,this.options=t,e.followers.onFollowerRemoved({removeRuntime:(e,t)=>this.cleanupRemoteTransports(t)})}handleCDPRequest(e,t){let{requestId:n,targetRuntimeId:r,localTargetId:i,method:a,params:o,sessionId:s}=t;if(r===`leader`){this.executeLocalCDP(n,i,a,o,s,e);return}this.forwardCDPRequest(n,r,i,a,o,s,e)}async executeLocalCDP(e,t,n,r,i,a){let o=this.context.followers.followers.get(a);if(!o)return;let s=this.context.options.browserTransport;if(!s){o.sync.send({type:`cdp.response`,requestId:e,error:`Leader has no browser transport`});return}try{let a=n===`Page.bringToFront`?await this.executeFollowerBringToFront(s,t,r,i):await s.send(n,r,i);g(o.sync,e,a)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeFollowerBringToFront(e,t,n,r){let i=this.previewGeneration,a=++this.previewSequence;this.previewRequestsInFlight++,this.cancelPreviewRestore(),this.previewOriginalTarget??=this.findFocusedTargetId(e,t,r);try{await this.previewOriginalTarget;let o=await e.send(`Page.bringToFront`,n,r);return i===this.previewGeneration&&a>this.previewLatestSuccessfulSequence&&(this.previewLatestSuccessfulSequence=a,this.previewLastTargetId=t),o}finally{i===this.previewGeneration&&(this.previewRequestsInFlight--,this.previewRequestsInFlight===0&&this.previewLastTargetId===null?(this.previewOriginalTarget=null,this.previewLatestSuccessfulSequence=0):this.schedulePreviewRestore(e))}}resetPreviewFocus(){this.cancelPreviewRestore(),this.previewGeneration++,this.previewOriginalTarget=null,this.previewLastTargetId=null,this.previewLatestSuccessfulSequence=0,this.previewRequestsInFlight=0}cancelPreviewRestore(){this.previewRestoreTimer!==null&&(clearTimeout(this.previewRestoreTimer),this.previewRestoreTimer=null)}schedulePreviewRestore(e){this.previewRequestsInFlight===0&&this.previewLastTargetId!==null&&(this.cancelPreviewRestore(),this.previewRestoreTimer=setTimeout(()=>{this.previewRestoreTimer=null,this.restorePreviewFocus(e)},Xe))}async restorePreviewFocus(e){let t=this.previewLatestSuccessfulSequence,n=await this.previewOriginalTarget,r=this.previewLastTargetId;if(!n||!r||n===r){this.finishPreviewBurst(t);return}let i=await this.findFocusedTargetId(e);if(!this.previewRestoreIsCurrent(t)){this.schedulePreviewRestore(e);return}if(i!==r){this.finishPreviewBurst(t);return}try{await this.bringTargetToFront(e,n,t)}catch(e){this.context.log.debug(`Follower preview focus restore skipped`,{targetId:n,error:e instanceof Error?e.message:String(e)})}this.finishPreviewBurst(t)}previewRestoreIsCurrent(e){return e===this.previewLatestSuccessfulSequence&&this.previewRequestsInFlight===0}finishPreviewBurst(e){this.previewRestoreIsCurrent(e)&&(this.cancelPreviewRestore(),this.previewOriginalTarget=null,this.previewLastTargetId=null,this.previewLatestSuccessfulSequence=0)}async bringTargetToFront(e,t,n){let r=(await e.send(`Target.attachToTarget`,{targetId:t,flatten:!0})).sessionId;if(typeof r==`string`)try{if(!this.previewRestoreIsCurrent(n))return;await e.send(`Page.bringToFront`,{},r)}finally{try{await e.send(`Target.detachFromTarget`,{sessionId:r})}catch{}}}async findFocusedTargetId(e,t,n){let r;try{let t=await e.send(`Target.getTargets`);r=Array.isArray(t.targetInfos)?t.targetInfos:[]}catch{return null}let i=r.filter(e=>e.type===`page`&&typeof e.targetId==`string`),a=i.find(e=>e.active===!0);if(a)return a.targetId;for(let r of i){let i=r.targetId===t?n:void 0;if(await this.targetHasFocus(e,r.targetId,i))return r.targetId}return null}async targetHasFocus(e,t,n){let r=n,i=!1;try{if(!r){let n=await e.send(`Target.attachToTarget`,{targetId:t,flatten:!0});r=typeof n.sessionId==`string`?n.sessionId:void 0,i=!!r}return r?(await e.send(`Runtime.evaluate`,{expression:`document.hasFocus()`,returnByValue:!0},r)).result?.value===!0:!1}catch{return!1}finally{if(i&&r)try{await e.send(`Target.detachFromTarget`,{sessionId:r})}catch{}}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.context.followers.runtimeToBootstrap.get(t),c=s?this.context.followers.followers.get(s):void 0,l=this.context.followers.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t}=e,n=this.pendingCDPRoutes.get(t);if(!n)return;let r=h(this.cdpChunkBuffers,e);if(!r)return;if(this.pendingCDPRoutes.delete(t),n.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,r.result,r.error);return}let i=this.context.followers.followers.get(n.requesterBootstrapId);i&&g(i.sync,t,r.result,r.error)}handleCDPEvent(e,t,n,r){let i=this.context.followers.runtimeIdForBootstrap(e);if(!i)return;let a=`${i}:`,o=r?{...n,sessionId:r}:n;for(let[e,n]of this.remoteTransports)e.startsWith(a)&&n.handleEvent(t,o)}createRemoteTransport(e,t){if(e===`preview`){let e=t.indexOf(`:`);if(e===-1)throw Error(`Invalid preview localTargetId format: expected "<token>:<connId>", got "${t}"`);let n=t.slice(e+1),r=this.options.getBridgeTransport(n);if(!r)throw Error(`Preview bridge connection "${n}" not found`);return r}let n=`${e}:${t}`,r=new he({sendCDPRequest:(r,i,a,o)=>{let s=this.context.followers.runtimeToBootstrap.get(e),c=s?this.context.followers.followers.get(s):void 0;if(!c){this.remoteTransports.get(n)?.handleResponse(r,void 0,`Target runtime "${e}" not connected`);return}this.pendingCDPRoutes.set(r,{requesterBootstrapId:`__leader__`,requestId:r}),c.sync.send({type:`cdp.request`,requestId:r,localTargetId:t,method:i,params:a,sessionId:o})}});return this.remoteTransports.set(n,r),r}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}cleanupRemoteTransports(e){let t=`${e}:`;for(let e of[...this.remoteTransports.keys()])e.startsWith(t)&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),this.context.log.debug(`Cleaned up stale remote transport`,{key:e}));try{this.context.options.onRemoteTransportsCleaned?.(e)}catch(t){this.context.log.warn(`onRemoteTransportsCleaned handler threw`,{runtimeId:e,error:t instanceof Error?t.message:String(t)})}}cleanupOrphanedRemoteTransports(e){for(let t of[...this.remoteTransports.keys()]){let n=t.substring(0,t.indexOf(`:`));n!==`leader`&&!this.context.followers.runtimeToBootstrap.has(n)&&n!==e&&(this.remoteTransports.get(t)?.disconnect(),this.remoteTransports.delete(t),this.context.log.debug(`Cleaned up orphaned remote transport on advertise`,{key:t}))}}},Qe=class{context;constructor(e){this.context=e}routeCherryHostEvent(e,t){if(!_(t))return;let n=this.context.options.onCherryHostEvent;if(!n){this.context.log.debug(`cherry.host_event received but no onCherryHostEvent wired`,{bootstrapId:e,name:t.name});return}let r=this.context.followers.runtimeIdForBootstrap(e);try{n(r,t.name,t.detail)}catch(n){this.context.log.warn(`Failed to route cherry.host_event to cone`,{bootstrapId:e,name:t.name,error:n instanceof Error?n.message:String(n)})}}emitCherrySliccEvent(e,t,n){let r=e.indexOf(`:`),i=r>=0?e.slice(0,r):e,a=this.context.followers.runtimeToBootstrap.get(i),o=a?this.context.followers.followers.get(a):void 0;return o?o.sync.send({type:`cherry.slicc_event`,targetId:e,name:t,detail:n}):(this.context.log.warn(`emitCherrySliccEvent: owning follower not connected`,{targetId:e,name:t}),!1)}};s(`lick-manager`);var $e=new Set([`navigate`,`discovery`]);function I(e){return e?e.includes(`ios`)?`ios`:e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}function L(e,t){switch(e){case`extension`:return`extension follower`;case`standalone`:return`standalone follower`;case`electron`:return`Electron follower`;case`ios`:return`iOS follower`;default:return t?`follower (${t})`:`follower`}}var et=6e4,tt=class{options;followers=new Map;runtimeToBootstrap=new Map;removalHooks=new Set;followerBroadcastErrorLogAt=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=Ce(t),i=r.onMessage(t=>this.options.onMessage(e,t)),a=new re({sendPing:()=>r.send({type:`ping`}),isTransportOpen:()=>r.isOpen,onStalled:()=>{this.options.log.warn(`Follower stopped answering pings; channel still open, keeping it`,{bootstrapId:e})},onRecovered:()=>{this.options.log.info(`Follower is answering pings again`,{bootstrapId:e})},onDead:()=>{this.options.log.warn(`Follower keepalive dead, removing follower`,{bootstrapId:e}),this.removeFollower(e),this.options.onFollowerDead?.(e)}});a.start();let o={bootstrapId:e,sync:r,unsubscribe:i,keepalive:a,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:Date.now(),floatType:I(n?.runtime)};return this.followers.set(e,o),this.options.log.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.notifyFollowerCountChanged(),o}removeFollower(e){let t=this.followers.get(e);if(!t)return;t.keepalive.stop(),t.unsubscribe(),t.sync.close(),this.followers.delete(e);for(let t of this.removalHooks)t.beforeRegistryCleanup?.(e);this.followerBroadcastErrorLogAt.delete(e);let n=this.runtimeIdForBootstrap(e);if(n){for(let t of this.removalHooks)t.removeRuntime?.(e,n);this.runtimeToBootstrap.delete(n)}for(let t of this.removalHooks)t.afterRegistryCleanup?.(e,n);this.options.log.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size}),this.notifyFollowerCountChanged()}onFollowerRemoved(e){return this.removalHooks.add(e),()=>this.removalHooks.delete(e)}notifyFollowerCountChanged(){this.options.onFollowerCountChanged?.(this.followers.size)}setRuntimeId(e,t){this.runtimeToBootstrap.set(e,t)}resolveFollowerByRuntimeId(e){let t=this.runtimeToBootstrap.get(e);if(t){let e=this.followers.get(t);if(e)return{bootstrapId:t,follower:e}}let n=[e];e.startsWith(`follower-`)&&n.push(e.slice(9));for(let e of n){let t=this.followers.get(e);if(t)return{bootstrapId:e,follower:t}}return null}runtimeIdForBootstrap(e){for(let[t,n]of this.runtimeToBootstrap)if(n===e)return t}setSprinkleInstances(e,t){let n=this.followers.get(e);n&&(n.sprinkleInstances=[...t])}getSprinkleInstances(){let e=[];for(let[t,n]of this.followers){let r=this.runtimeIdForBootstrap(t)??t;for(let t of n.sprinkleInstances??[])e.push({name:t,runtimeId:r,runtime:n.runtime})}return e}getFollowerMotds(){let e=new Map;for(let[t,n]of this.followers)n.peerMotd&&e.set(t,n.peerMotd);return e}getExecCapableBootstrapIds(){let e=new Set;for(let[t,n]of this.followers)n.peerCapabilities?.exec&&e.add(t);return e}getBrowserCapableBootstrapIds(){return new Set(this.runtimeToBootstrap.values())}getFollowerDetails(){return[...this.followers.values()].map(e=>({bootstrapId:e.bootstrapId,runtime:e.runtime,connectedAt:e.connectedAt,lastActivity:e.lastActivity,floatType:e.floatType,hostOrigin:e.hostOrigin,selectedScoopJid:e.selectedScoopJid,health:e.keepalive.isStalled?`stalled`:`live`}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([e,t])=>{let n=this.followers.get(t);return{runtimeId:e,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:n?.lastActivity,floatType:n?.floatType}})}broadcastToAllFollowers(e){let t=performance.now(),n=[];for(let[r,i]of this.followers){let a=!1,o;try{a=i.sync.send(e)}catch(e){o=e}if(a){this.followerBroadcastErrorLogAt.delete(r);continue}n.push(r),t-(this.followerBroadcastErrorLogAt.get(r)??-1/0)>et&&(this.followerBroadcastErrorLogAt.set(r,t),this.options.log.error(`Broadcast send to follower failed`,{bootstrapId:r,messageType:e.type,...o?{error:o instanceof Error?o.message:String(o)}:{}}))}return n}},nt=class{context;collaborators;constructor(e,t){this.context=e,this.collaborators=t}dispatch(e,t){this.noteLegacyPeer(e,t);let{broadcast:n,cdpRouter:r,remoteExec:i,fsRouter:a,tabRouter:o}=this.collaborators,{teleportPool:s,transcriptExport:c,cherryRouter:l,tabTeleportRouter:u}=this.collaborators,{oauthPopupDelegation:d}=this.collaborators;switch(t.type){case`user_message`:this.handleFollowerUserMessage(e,t);break;case`abort`:this.context.log.info(`Follower abort received`,{bootstrapId:e}),this.context.options.onFollowerAbort();break;case`new_session`:this.handleFollowerNewSession(e,t.action);break;case`request_snapshot`:this.context.log.info(`Follower snapshot request received`,{bootstrapId:e,scoopJid:t.scoopJid}),n.sendSnapshotToFollower(e,t.scoopJid);break;case`scoops.select`:this.handleScoopSelection(e,t.scoopJid);break;case`models.request`:n.sendModelCatalogToFollower(e);break;case`model.select`:this.handleModelSelection(e,t.modelId,t.scoopJid);break;case`thinking.set`:this.handleThinkingSelection(e,t.scoopJid,t.thinkingLevel,t.effortOverride);break;case`sprinkles.refresh`:this.context.log.info(`Follower requested sprinkles refresh`,{bootstrapId:e}),n.sendSprinklesListToFollower(e);break;case`sprinkle.fetch`:n.handleSprinkleFetch(e,t.requestId,t.sprinkleName);break;case`sprinkle.lick`:this.handleFollowerSprinkleLick(e,t);break;case`sprinkle.instances`:this.context.followers.setSprinkleInstances(e,t.sprinkles),this.context.options.onSprinkleInstancesChanged?.();break;case`lick`:this.handleFollowerLick(e,t);break;case`targets.advertise`:s.handleFollowerTargetsAdvertise(e,t);break;case`cdp.request`:r.handleCDPRequest(e,t);break;case`cdp.response`:r.handleCDPResponse(t);break;case`cdp.event`:r.handleCDPEvent(e,t.method,t.params,t.sessionId);break;case`tab.open`:this.routeTabOpen(e,t);break;case`tab.opened`:o.handleTabOpenResponse(t.requestId,t.targetId);break;case`tab.open.error`:o.handleTabOpenError(t.requestId,t.error);break;case`tab.teleport.request`:u.handleTeleportRequest(e,t);break;case`oauth.popup.response`:d.handlePopupResponse(e,t.requestId,t.redirectUrl,t.error);break;case`fs.request`:this.routeFsRequest(e,t);break;case`fs.response`:a.handleFsResponse(t.requestId,t.response);break;case`exec.request`:case`exec.chunk`:case`exec.response`:case`exec.signal`:i.handleFollowerExecMessage(e,t);break;case`transcript.export.request`:c.handleTranscriptExportRequest(e,t.requestId,t.selector);break;case`transcript.export.cancel`:c.handleTranscriptExportCancel(e,t.requestId);break;case`transcript.export.ack`:c.handleTranscriptExportAck(e,t.requestId,t.index);break;case`sudo.approve.response`:this.collaborators.sudoDelegation.handleResponse(e,t.requestId,t.decision,t.pattern,t.attestation);break;case`push.register`:this.handlePushRegister(e,t);break;case`cherry.host_event`:l.routeCherryHostEvent(e,t);break;case`ping`:this.handlePing(e);break;case`pong`:this.handlePong(e);break;case`hello`:this.handleFollowerHello(e,t);break;default:{let n=v(t);this.context.log.warn(`Unknown follower message type — skewed follower?`,{bootstrapId:e,type:n.type})}}}noteLegacyPeer(e,t){if(t.type===`hello`)return;let n=this.context.followers.followers.get(e);!n||n.peerProtocolVersion!==void 0||n.legacyPeerLogged||(n.legacyPeerLogged=!0,this.context.log.info(`Follower sent no hello — legacy peer (pre-versioning build)`,{bootstrapId:e}))}handleFollowerUserMessage(e,t){this.context.log.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId});let n=this.context.followers.followers.get(e);n&&(n.lastActivity=Date.now()),this.collaborators.requesterTracker.noteFollowerUserMessage(e,this.context.followers.runtimeIdForBootstrap(e));let r=t.attachments?.length?c(t.attachments):t.attachments;t.steer?this.context.options.onFollowerMessage(t.text,t.messageId,r,{steer:!0}):this.context.options.onFollowerMessage(t.text,t.messageId,r)}handleFollowerNewSession(e,t){this.context.log.info(`Follower new-session received`,{bootstrapId:e,action:t});try{this.context.options.onFollowerNewSession?.(t,e)}catch(e){this.context.log.warn(`onFollowerNewSession handler threw`,{error:e instanceof Error?e.message:String(e)})}}handleScoopSelection(e,t){this.context.log.info(`Follower selected scoop`,{bootstrapId:e,scoopJid:t});let n=this.context.followers.followers.get(e);n&&(n.selectedScoopJid=t,this.collaborators.broadcast.sendSnapshotToFollower(e,t))}handleModelSelection(e,t,n){let r=n??this.context.followers.followers.get(e)?.selectedScoopJid;try{let n=this.context.options.onFollowerModelSelect?.(t,r??void 0);if(n===!0){this.collaborators.broadcast.broadcastModelState();return}if(typeof n==`object`&&typeof n?.then==`function`){n.then(n=>{if(n){this.collaborators.broadcast.broadcastModelState();return}this.context.log.warn(`Follower model selection was not applied`,{bootstrapId:e,modelId:t}),this.collaborators.broadcast.broadcastModelState()}).catch(n=>{this.context.log.warn(`Follower model selection failed to persist`,{bootstrapId:e,modelId:t,error:n instanceof Error?n.message:String(n)}),this.collaborators.broadcast.broadcastModelState()});return}this.context.log.warn(`Rejecting unknown or unresolvable follower model selection`,{bootstrapId:e,modelId:t})}catch(n){this.context.log.warn(`Rejecting follower model selection after apply failure`,{bootstrapId:e,modelId:t,error:n instanceof Error?n.message:String(n)})}}handleThinkingSelection(e,t,n,r){let i=this.context.followers.followers.get(e)?.selectedScoopJid;if(!i){this.context.log.warn(`Rejecting follower thinking selection without a selected scoop`,{bootstrapId:e,requestedScoopJid:t});return}t!==i&&this.context.log.warn(`Follower thinking selection targeted a stale scoop; using selected scoop`,{bootstrapId:e,requestedScoopJid:t,scoopJid:i});try{let t=this.context.options.onFollowerThinkingSet?.(i,n,r);t&&typeof t.then==`function`?t.then(t=>{if(t===!1){this.logThinkingApplyFailure(e,i,Error(`thinking update was not acknowledged`));return}this.collaborators.broadcast.broadcastModelState()}).catch(t=>this.logThinkingApplyFailure(e,i,t)):this.collaborators.broadcast.broadcastModelState()}catch(t){this.logThinkingApplyFailure(e,i,t)}}logThinkingApplyFailure(e,t,n){this.context.log.warn(`Follower thinking selection apply failed`,{bootstrapId:e,scoopJid:t,error:n instanceof Error?n.message:String(n)})}handleFollowerSprinkleLick(e,t){this.context.log.info(`Follower sprinkle lick received`,{bootstrapId:e,sprinkleName:t.sprinkleName});let n=this.context.followers.followers.get(e),r=L(n?.floatType??`unknown`,n?.runtime);try{this.context.options.onSprinkleLick?.(t.sprinkleName,t.body,t.targetScoop,r)}catch(e){this.context.log.warn(`onSprinkleLick handler threw`,{error:e instanceof Error?e.message:String(e)})}}handleFollowerLick(e,t){let n=t.event;if(!n||!$e.has(n.type)){this.context.log.warn(`Rejecting malformed or non-forwardable lick from follower`,{bootstrapId:e,type:n?.type});return}let r=this.context.followers.followers.get(e),{targetScoop:i,...a}=n,o={...a,originFollowerId:e,originLabel:L(r?.floatType??`unknown`,r?.runtime)};try{this.context.options.onForwardedLick?.(o,e)}catch(e){this.context.log.warn(`onForwardedLick handler threw`,{error:e instanceof Error?e.message:String(e)})}}routeTabOpen(e,t){let{requestId:n,targetRuntimeId:r,url:i}=t;r===`leader`?this.collaborators.tabRouter.executeLocalTabOpen(n,i,e):this.collaborators.tabRouter.forwardTabOpen(n,r,i,e)}routeFsRequest(e,t){let{requestId:n,targetRuntimeId:r,request:i}=t;r===`leader`?this.collaborators.fsRouter.executeLocalFs(n,i,e):this.collaborators.fsRouter.forwardFsRequest(n,r,i,e)}handlePing(e){let t=this.context.followers.followers.get(e);t&&(t.keepalive.receivePing(),t.lastActivity=Date.now(),t.sync.send({type:`pong`}))}handlePushRegister(e,t){let n=typeof t.token==`string`?t.token.trim():``,r=t.environment===`production`?`production`:`sandbox`;if(t.platform!==`ios`||!/^[0-9a-fA-F]{32,400}$/.test(n)){this.context.log.warn(`Ignoring malformed push.register`,{bootstrapId:e});return}this.collaborators.registerPushToken?.(e,{platform:`ios`,token:n,environment:r})}handlePong(e){let t=this.context.followers.followers.get(e);t&&(t.keepalive.receivePong(),t.lastActivity=Date.now())}handleFollowerHello(e,t){let n=this.context.followers.followers.get(e);n&&(n.peerProtocolVersion=t.protocolVersion,n.peerCapabilities=t.capabilities,n.peerMotd=t.motd,this.context.followers.notifyFollowerCountChanged(),this.collaborators.sudoDelegation.handleFollowerReady(e)),t.protocolVersion>7?this.context.log.warn(`Follower speaks a newer tray sync protocol — update this build`,{bootstrapId:e,followerVersion:t.protocolVersion,ourVersion:7}):this.context.log.info(`Follower hello`,{bootstrapId:e,protocolVersion:t.protocolVersion})}};function rt(e){if(typeof e.path!=`string`||!e.path.startsWith(`/`))return!1;let t=ge(e.path);return t!==`/proc`&&!t.startsWith(`/proc/`)}function it(){return{ok:!1,error:`Follower filesystem access denied`,code:`EACCES`}}var at=class{context;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.context=e,e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.rejectPendingForFollower(e)})}async executeLocalFs(e,t,n){let r=this.context.followers.followers.get(n);if(!r)return;let i=this.context.options.vfs;if(!i){r.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Leader has no VFS`}});return}if(!rt(t)){r.sync.send({type:`fs.response`,requestId:e,response:it()});return}let a=await w(i,t);for(let t of a)r.sync.send({type:`fs.response`,requestId:e,response:t})}forwardFsRequest(e,t,n,r){let i=this.context.followers.runtimeToBootstrap.get(t),a=i?this.context.followers.followers.get(i):void 0,o=this.context.followers.followers.get(r);if(!i||!a){o?.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Target runtime "${t}" not connected`}});return}this.pendingFsRoutes.set(e,{requesterBootstrapId:r,targetBootstrapId:i,requestId:e,chunks:[],totalChunks:1}),a.sync.send({type:`fs.request`,requestId:e,request:n})}handleFsResponse(e,t){let n=this.pendingFsRoutes.get(e);if(!n){this.resolveUnroutedLeaderResponse(e,t);return}n.requesterBootstrapId!==`__leader__`&&this.context.followers.followers.get(n.requesterBootstrapId)?.sync.send({type:`fs.response`,requestId:e,response:t});let r=this.addResponseChunk(n,t);if(r&&(this.pendingFsRoutes.delete(e),n.requesterBootstrapId===`__leader__`)){let t=this.fsResolvers.get(e);t&&(this.fsResolvers.delete(e),t.resolve(r))}}sendFsRequest(e,t){if(e===`leader`){let e=this.context.options.vfs;return e?w(e,t):Promise.resolve([{ok:!1,error:`Leader has no VFS`}])}let n=this.context.followers.runtimeToBootstrap.get(e),r=n?this.context.followers.followers.get(n):void 0;if(!n||!r)return Promise.resolve([{ok:!1,error:`Target runtime "${e}" not connected`}]);let i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,a)=>{this.fsResolvers.set(i,{resolve:e,reject:a,responses:[]}),this.pendingFsRoutes.set(i,{requesterBootstrapId:`__leader__`,targetBootstrapId:n,requestId:i,chunks:[],totalChunks:1}),r.sync.send({type:`fs.request`,requestId:i,request:t})})}addResponseChunk(e,t){return e.chunks.push(t),e.totalChunks=t.ok&&t.totalChunks||1,e.chunks.length<e.totalChunks?null:e.chunks}resolveUnroutedLeaderResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}rejectPendingForFollower(e){for(let[t,n]of this.pendingFsRoutes){if(n.targetBootstrapId!==e&&n.requesterBootstrapId!==e)continue;this.pendingFsRoutes.delete(t);let r=this.fsResolvers.get(t);r&&(this.fsResolvers.delete(t),r.reject(Error(`follower disconnected before the fs request completed`)))}}},R=s(`oauth-cdp-login`),ot=12e4,st=500;function ct(e){let t;try{t=new URL(e).searchParams.get(`redirect_uri`)}catch{return null}if(!t)return null;let n;try{let e=new URL(t);n=`${e.origin}${e.pathname}`}catch{return null}return e=>{try{let t=new URL(e);return`${t.origin}${t.pathname}`===n?t.searchParams.has(`code`)||t.searchParams.has(`error`)||t.hash.includes(`access_token`):!1}catch{return!1}}}function lt(e){try{let t=new URL(e);if(t.searchParams.has(`nonce`))return e;let n=t.searchParams.get(`state`);if(!n)return e;let r=JSON.parse(atob(n))?.nonce;return typeof r!=`string`||!r?e:(t.searchParams.delete(`state`),t.searchParams.set(`nonce`,r),t.toString())}catch{return e}}async function ut(e,t){try{let n=await e.withTab(t,()=>e.evaluate(`window.location.href`));return typeof n==`string`?n:null}catch{return null}}async function dt(e){let{browser:t,runtimeId:n,authorizeUrl:r,signal:i}=e,a=ct(r);if(!a)throw Error(`authorize URL has no redirect_uri to watch for`);let o=await t.createRemotePage(n,r),s=o.includes(`:`)?o:`${n}:${o}`;return R.info(`Opened delegated login tab on follower`,{runtimeId:n}),await new Promise(n=>{let r=[],o=!1,c=e=>{if(!o){o=!0;for(let e of r)e();t.closePage(s).catch(e=>{R.warn(`Could not close delegated login tab`,{error:String(e)})}),n(typeof e==`string`?lt(e):e)}};(async()=>{try{await t.withTab(s,async()=>{await t.sendCDP(`Page.enable`)});let e=t.getTransport(),n=e=>{let t=e.frame;!t?.url||t.parentId||a(t.url)&&(R.info(`Delegated login reached the callback`,{via:`frameNavigated`}),c(t.url))};e.on(`Page.frameNavigated`,n),r.push(()=>e.off(`Page.frameNavigated`,n));let i=async()=>{if(o)return;let e=await ut(t,s);o||!e||!a(e)||(R.info(`Delegated login reached the callback`,{via:`poll`}),c(e))},l=setInterval(()=>void i(),st);r.push(()=>clearInterval(l))}catch(e){R.warn(`Delegated CDP login could not start`,{error:String(e)}),c(null)}})();let l=setTimeout(()=>{R.warn(`Delegated CDP login timed out`),c(null)},e.timeoutMs??ot);r.push(()=>clearTimeout(l));let u=()=>c(null);i?.addEventListener(`abort`,u),r.push(()=>i?.removeEventListener(`abort`,u)),i?.aborted&&c(null)})}var ft=125e3,pt=class e{context;waiters=new Map;counter=0;constructor(e){this.context=e,e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.settleAllForFollower(e,{redirectUrl:null,error:`the follower handling this login disconnected`})})}static key(e,t){return`${e}:${t}`}requestPopup(t,n){let r=this.context.followers.followers.get(t);if(!r)return Promise.resolve({redirectUrl:null,error:`follower is no longer connected`});let i=`oauth-popup-${Date.now()}-${++this.counter}`,a=e.key(t,i);return new Promise(e=>{let o=setTimeout(()=>{this.context.log.warn(`Delegated OAuth popup timed out`,{bootstrapId:t,requestId:i}),this.settle(a,{redirectUrl:null,error:`the delegated login timed out`})},ft);this.waiters.set(a,t=>{clearTimeout(o),e(t)}),r.sync.send({type:`oauth.popup.request`,requestId:i,url:n})===!1&&(this.context.log.warn(`Could not deliver delegated OAuth popup request`,{bootstrapId:t,requestId:i}),this.settle(a,{redirectUrl:null,error:`could not reach the follower`}))})}handlePopupResponse(t,n,r,i){this.settle(e.key(t,n),{redirectUrl:r??null,error:i})}settle(e,t){let n=this.waiters.get(e);n&&(this.waiters.delete(e),n(t))}settleAllForFollower(e,t){for(let n of[...this.waiters.keys()])n.startsWith(`${e}:`)&&this.settle(n,t)}},mt=3e4,ht={target:`preview-target`,session:`preview-session`,frame:`preview-frame`,loader:`preview-loader`},gt=class extends we{connId;sendToWorker;nextId=1;pending=new me;constructor(e){super({targetUrl:e.targetUrl,targetOrigin:e.targetOrigin,title:e.title,ids:e.ids??ht}),this.connId=e.connId,this.sendToWorker=e.send}async connect(e){this._state=`connected`}onCloseTarget(){this.sendToWorker({type:`bridge.close`,connId:this.connId})}disconnect(){this.pending.rejectAll(`PreviewBridgeCdpTransport disconnected`),this._state=`disconnected`}async forward(e,t,n,r=mt){let i=this.nextId++,a=this.pending.issue(i,r,`PreviewBridge CDP timed out after ${r}ms: ${e}`);return this.sendToWorker({type:`bridge.cdp.request`,connId:this.connId,id:i,method:e,params:t,sessionId:n}),a}deliverResponse(e,t){t.error?this.pending.reject(e,Error(`PreviewBridge CDP error: ${t.error.message} (${t.error.code})`)):this.pending.resolve(e,t.result??{})}},_t=class{context;mintMap=new Map;bridgeConns=new Map;lifecycleRecords=[];lifecycleRecordStart=0;lifecycleRecordCount=0;constructor(e){this.context=e}registerMintedPreview(e,t){let n=this.mintMap.get(e)?.announced??!1;this.mintMap.set(e,{...t,announced:n})}restorePreviewState(e){let t=this.mintMap.get(e.previewToken);if(t){t.quiet=e.quiet,t.announced=e.announced;return}this.mintMap.set(e.previewToken,{url:``,title:`Preview`,quiet:e.quiet,announced:e.announced})}dropMintedPreview(e){this.mintMap.delete(e),this.clearPreviewLifecycleRecords(e)}onBridgeConnected(e){let{connId:t,previewToken:n,origin:r,userAgent:i,connectedAt:a}=e,o=e.replay===!0,s=o?this.restoreReplayedPreview(n,r):this.getOrCreatePreview(n,r);if(s.url||=r,this.bridgeConns.has(t)){if(o)return;this.recordLifecycle({timestamp:new Date().toISOString(),lifecycle:`connected`,connId:t,previewToken:n,origin:r,userAgent:i,connectedAt:a,announced:!1});return}let{url:c,title:l,quiet:u}=s,d=new gt({connId:t,targetUrl:c,targetOrigin:r,title:l,send:e=>this.context.sendControl(e)});if(d.connect(),this.bridgeConns.set(t,{previewToken:n,origin:r,userAgent:i,connectedAt:a,url:c,title:l,quiet:u,transport:d}),this.context.log.info(`Preview bridge connected`,{connId:t,previewToken:n,origin:r,userAgent:i}),o)return;let f=new Date().toISOString(),p=!s.announced,m=p&&!u&&!!this.context.options.onPreviewLick;p&&(s.announced=!0,this.context.sendControl({type:`preview.state.update`,previewToken:n,announced:!0})),this.recordLifecycle({timestamp:f,lifecycle:`connected`,connId:t,previewToken:n,origin:r,userAgent:i,connectedAt:a,announced:m}),m&&this.emitPreviewConnectedLick(e,f)}onBridgeDisconnected(e){let{connId:t,reason:n}=e,r=this.bridgeConns.get(t);if(!r){this.recordLifecycle({timestamp:new Date().toISOString(),lifecycle:`disconnected`,connId:t,reason:n,announced:!1});return}let{previewToken:i,origin:a,userAgent:o,connectedAt:s}=r;r.transport.disconnect(),this.bridgeConns.delete(t),this.context.log.info(`Preview bridge disconnected`,{connId:t,reason:n}),this.recordLifecycle({timestamp:new Date().toISOString(),lifecycle:`disconnected`,connId:t,previewToken:i,origin:a,userAgent:o,connectedAt:s,reason:n,announced:!1})}onBridgeCdpResponse(e){let{connId:t,id:n,result:r,error:i}=e,a=this.bridgeConns.get(t);if(!a){this.context.log.warn(`Received bridge.cdp.response for unknown connId`,{connId:t,id:n});return}a.transport.deliverResponse(n,{result:r,error:i})}getBridgeTransport(e){return this.bridgeConns.get(e)?.transport}getTargetEntries(){return[...this.bridgeConns].map(([e,t])=>({targetId:`preview:${t.previewToken}:${e}`,localTargetId:e,runtimeId:`preview`,title:t.title,url:t.url,isLocal:!1,kind:`preview`}))}stop(){for(let e of this.bridgeConns.values())e.transport.disconnect();this.bridgeConns.clear(),this.mintMap.clear(),this.resetLifecycleRecords()}getPreviewLifecycleRecords(e){return this.snapshotLifecycleRecords().filter(t=>e===void 0||t.previewToken===e).map(e=>({...e}))}clearPreviewLifecycleRecords(e){let t=this.snapshotLifecycleRecords(),n=t.filter(t=>e!==void 0&&t.previewToken!==e),r=t.length-n.length;this.resetLifecycleRecords();for(let e of n)this.recordLifecycle(e);return r}rearmPreviewAnnouncements(e){let t=0;for(let[n,r]of this.mintMap)(e===void 0||n===e)&&(r.announced=!1,this.context.sendControl({type:`preview.state.update`,previewToken:n,announced:!1}),t+=1);return t}getOrCreatePreview(e,t){let n=this.mintMap.get(e);if(n)return n;let r={url:t,title:`Preview`,quiet:!1,announced:!1};return this.mintMap.set(e,r),r}restoreReplayedPreview(e,t){let n=this.mintMap.get(e);if(n)return n.announced||=!0,n;let r={url:t,title:`Preview`,quiet:!0,announced:!0};return this.mintMap.set(e,r),r}emitPreviewConnectedLick(e,t){let n={type:`preview`,previewLifecycle:`connected`,previewConnId:e.connId,previewToken:e.previewToken,previewOrigin:e.origin,previewUserAgent:e.userAgent,previewConnectedAt:e.connectedAt,timestamp:t,body:{}};try{this.context.options.onPreviewLick?.(n)}catch(e){this.context.log.warn(`onPreviewLick handler threw`,{error:e instanceof Error?e.message:String(e)})}}recordLifecycle(e){if(this.lifecycleRecordCount<500){let t=(this.lifecycleRecordStart+this.lifecycleRecordCount)%500;this.lifecycleRecords[t]=e,this.lifecycleRecordCount+=1;return}this.lifecycleRecords[this.lifecycleRecordStart]=e,this.lifecycleRecordStart=(this.lifecycleRecordStart+1)%500}snapshotLifecycleRecords(){return Array.from({length:this.lifecycleRecordCount},(e,t)=>{let n=(this.lifecycleRecordStart+t)%500;return this.lifecycleRecords[n]})}resetLifecycleRecords(){this.lifecycleRecords=[],this.lifecycleRecordStart=0,this.lifecycleRecordCount=0}},vt=16777216,yt=class{context;pendingRemoteExecs=new Map;localExecAborters=new Map;constructor(e){this.context=e,e.followers.onFollowerRemoved({beforeRegistryCleanup:e=>this.handleFollowerRemoved(e)})}async execOnRemote(e,t,n={}){let r=this.context.followers.resolveFollowerByRuntimeId(e);if(!r)throw Error(`No connected follower for '${e}'`);let{bootstrapId:i,follower:a}=r;if(!a.peerCapabilities?.exec)throw Error(`Follower '${e}' is not an exec target — only a 'slicc … follow' CLI accepts commands`);let o=`lexec-${crypto.randomUUID()}`;return new Promise((r,s)=>{let c={bootstrapId:i,stdout:``,stderr:``,stdoutDecoder:new TextDecoder(`utf-8`),stderrDecoder:new TextDecoder(`utf-8`),bytes:0,truncated:!1,onChunk:n.onChunk,resolve:r,reject:s};if(n.timeoutMs&&n.timeoutMs>0&&(c.timer=setTimeout(()=>{this.pendingRemoteExecs.delete(o)&&(this.sendExecSignal(i,o,`SIGKILL`),s(Error(`exec on '${e}' timed out after ${n.timeoutMs}ms`)))},n.timeoutMs)),this.pendingRemoteExecs.set(o,c),n.signal){let e=()=>this.sendExecSignal(i,o,`SIGINT`);n.signal.aborted?e():n.signal.addEventListener(`abort`,e,{once:!0})}a.sync.send({type:`exec.request`,requestId:o,command:t,cwd:n.cwd,env:n.env})||(this.pendingRemoteExecs.delete(o),c.timer&&clearTimeout(c.timer),s(Error(`Failed to send exec.request to follower '${e}'`)))})}handleFollowerExecMessage(e,t){switch(t.type){case`exec.request`:this.handleFollowerExecRequest(e,t);break;case`exec.chunk`:this.handleRemoteExecChunk(e,t);break;case`exec.response`:this.handleRemoteExecResponse(e,t);break;case`exec.signal`:this.handleFollowerExecSignal(e,t)}}sendExecSignal(e,t,n){this.context.followers.followers.get(e)?.sync.send({type:`exec.signal`,requestId:t,signal:n})}handleRemoteExecChunk(e,t){let n=this.pendingRemoteExecs.get(t.requestId);if(!n||n.bootstrapId!==e)return;let r;try{r=u(t.data)}catch{return}if(n.truncated)return;n.bytes+=r.length,n.bytes>vt&&(n.truncated=!0);let i=(t.stream===`stdout`?n.stdoutDecoder:n.stderrDecoder).decode(r,{stream:!0});t.stream===`stdout`?n.stdout+=i:n.stderr+=i,n.onChunk?.(t.stream,i)}handleRemoteExecResponse(e,t){let n=this.pendingRemoteExecs.get(t.requestId);!n||n.bootstrapId!==e||(this.pendingRemoteExecs.delete(t.requestId),n.timer&&clearTimeout(n.timer),n.stdout+=n.stdoutDecoder.decode(),n.stderr+=n.stderrDecoder.decode(),n.resolve({stdout:n.truncated?`${n.stdout}\n[output truncated at cap]`:n.stdout,stderr:n.stderr,exitCode:t.exitCode,error:t.error}))}async handleFollowerExecRequest(e,t){let{requestId:n,command:r,cwd:i,env:a}=t,o=this.context.options.execInShell;if(!o){this.context.followers.followers.get(e)?.sync.send({type:`exec.response`,requestId:n,exitCode:127,error:`exec is not supported on this leader`});return}let s=new AbortController,c=`${e}:${n}`;this.localExecAborters.set(c,{bootstrapId:e,controller:s});try{let t=await o(r,{sessionId:e,cwd:i,env:a,signal:s.signal,onChunk:(t,r)=>{this.context.followers.followers.get(e)?.sync.send({type:`exec.chunk`,requestId:n,stream:t,data:l(new TextEncoder().encode(r))})}});this.context.followers.followers.get(e)?.sync.send({type:`exec.response`,requestId:n,exitCode:t.exitCode,error:t.error})}catch(t){this.context.followers.followers.get(e)?.sync.send({type:`exec.response`,requestId:n,exitCode:1,error:t instanceof Error?t.message:String(t)})}finally{this.localExecAborters.delete(c)}}handleFollowerExecSignal(e,t){this.localExecAborters.get(`${e}:${t.requestId}`)?.controller.abort()}handleFollowerRemoved(e){for(let[t,n]of this.pendingRemoteExecs)n.bootstrapId===e&&(this.pendingRemoteExecs.delete(t),n.timer&&clearTimeout(n.timer),n.reject(Error(`follower disconnected before the command completed`)));for(let[t,n]of this.localExecAborters)n.bootstrapId===e&&(n.controller.abort(),this.localExecAborters.delete(t));this.context.options.closeExecShell?.(e)}},bt=class{origin=null;noteFollowerUserMessage(e,t){this.origin={kind:`follower`,bootstrapId:e,runtimeId:t,at:Date.now()}}noteLeaderUserMessage(){this.origin={kind:`leader`,at:Date.now()}}get(){return this.origin}handleFollowerRemoved(e){this.origin?.kind===`follower`&&this.origin.bootstrapId===e&&(this.origin=null)}},xt=class{context;pending=new Map;counter=0;now;timeoutMs;newId;constructor(e,t={}){this.context=e,this.now=t.now??(()=>Date.now()),this.timeoutMs=t.timeoutMs??3e5,this.newId=t.newId??(()=>`sudo-${this.now()}-${++this.counter}`),e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.handleFollowerRemoved(e)})}capableFollowers(){let e=[];for(let[t,n]of this.context.followers.followers)n.peerCapabilities?.sudoApproval===!0&&e.push(t);return e}hasCapableFollower(){return this.capableFollowers().length>0}get pendingCount(){return this.pending.size}requestApproval(e,t={}){let n=this.newId(),r=this.now()+this.timeoutMs;return new Promise(i=>{let a={requestId:n,request:e,scoopName:t.scoopName,prompted:new Set,expiresAt:r,timer:setTimeout(()=>{this.context.log.warn(`Delegated sudo approval timed out — denying`,{requestId:n}),this.settle(n,{decision:`deny`})},this.timeoutMs),settle:i};this.pending.set(n,a);for(let e of this.capableFollowers())this.prompt(a,e);this.sendPush(e,n,a.scoopName),a.prompted.size===0&&this.context.options.headlessLeader!==!0&&(this.context.log.warn(`No capable follower for delegated sudo approval — denying`,{requestId:n}),this.settle(n,{decision:`deny`}))})}handleFollowerReady(e){if(this.context.followers.followers.get(e)?.peerCapabilities?.sudoApproval===!0)for(let t of this.pending.values())t.prompted.has(e)||this.prompt(t,e)}handleResponse(e,t,n,r,i){let a=this.pending.get(t);if(!a?.prompted.has(e)){this.context.log.warn(`Ignoring sudo verdict for an unknown or unprompted request`,{bootstrapId:e,requestId:t});return}let o=this.context.followers.followers.get(e)?.peerCapabilities?.biometric===!0,s=i===`biometric`||i===`passcode`||i===`none`?i:void 0,c;n===`allow`?c={decision:`allow`,...s?{attestation:s}:{}}:n===`always`?o?c={decision:`always`,pattern:typeof r==`string`&&r.trim().length>0?r.trim():a.request.suggestedPattern?.trim()||a.request.detail,...s?{attestation:s}:{}}:(this.context.log.info(`Downgrading "always" from a non-biometric follower to "allow"`,{bootstrapId:e,requestId:t}),c={decision:`allow`,...s?{attestation:s}:{}}):c={decision:`deny`},this.context.log.info(`Delegated sudo approval settled by follower`,{bootstrapId:e,requestId:t,decision:c.decision,attestation:s??`none`}),this.settle(t,c,e)}prompt(e,t){let n=this.context.followers.followers.get(t);if(!n)return;let r=e.scoopName;if(n.sync.send({type:`sudo.approve.request`,requestId:e.requestId,kind:e.request.kind,detail:e.request.detail,...e.request.suggestedPattern?{suggestedPattern:e.request.suggestedPattern}:{},...r?{scoopName:r}:{},expiresAt:e.expiresAt})===!1){this.context.log.warn(`Could not deliver delegated sudo prompt`,{bootstrapId:t,requestId:e.requestId});return}e.prompted.add(t)}sendPush(e,t,n){try{this.context.sendControl({type:`push.send`,category:`sudo_request`,label:n??e.kind,requestId:t})}catch{}}settle(e,t,n){let r=this.pending.get(e);if(r){this.pending.delete(e),clearTimeout(r.timer);for(let t of r.prompted)t!==n&&this.context.followers.followers.get(t)?.sync.send({type:`sudo.approve.cancel`,requestId:e});r.settle(t)}}handleFollowerRemoved(e){for(let t of this.pending.values())t.prompted.delete(e),t.prompted.size===0&&this.context.options.headlessLeader!==!0&&(this.context.log.warn(`Every prompted follower disconnected — denying sudo approval`,{requestId:t.requestId}),this.settle(t.requestId,{decision:`deny`}))}dispose(){for(let e of[...this.pending.keys()])this.settle(e,{decision:`deny`})}},St=class{context;options;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;constructor(e,t){this.context=e,this.options=t,e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.rejectPendingForFollower(e)})}canRuntimeOpenTab(e){let t=this.options.getTargetEntries().filter(t=>t.runtimeId===e);return t.length===0||t.some(e=>!this.options.isCherryTarget(e))}openRemoteTab(e,t){let n=this.context.followers.runtimeToBootstrap.get(e),r=n?this.context.followers.followers.get(n):void 0;if(!n||!r)return Promise.reject(Error(`Target runtime "${e}" not connected`));if(!this.canRuntimeOpenTab(e))return Promise.reject(Error(`Target runtime "${e}" is a cherry host that cannot open tabs`));let i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,a)=>{this.tabOpenResolvers.set(i,{resolve:e,reject:a}),this.pendingTabOpenRoutes.set(i,{requesterBootstrapId:`__leader__`,targetBootstrapId:n,requestId:i}),r.sync.send({type:`tab.open`,requestId:i,url:t})})}async executeLocalTabOpen(e,t,n){let r=this.context.followers.followers.get(n);if(!r)return;let i=this.context.options.browserTransport;if(!i){r.sync.send({type:`tab.open.error`,requestId:e,error:`Leader has no browser transport`});return}try{let n=(await i.send(`Target.createTarget`,{url:t,background:!0})).targetId;r.sync.send({type:`tab.opened`,requestId:e,targetId:`leader:${n}`})}catch(t){r.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardTabOpen(e,t,n,r){let i=this.context.followers.runtimeToBootstrap.get(t),a=i?this.context.followers.followers.get(i):void 0,o=this.context.followers.followers.get(r);if(!i||!a){o?.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" not connected`});return}if(!this.canRuntimeOpenTab(t)){o?.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" is a cherry host that cannot open tabs`});return}this.pendingTabOpenRoutes.set(e,{requesterBootstrapId:r,targetBootstrapId:i,requestId:e}),a.sync.send({type:`tab.open`,requestId:e,url:n})}handleTabOpenResponse(e,t){let n=this.pendingTabOpenRoutes.get(e);if(n){if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.resolve(t));return}this.context.followers.followers.get(n.requesterBootstrapId)?.sync.send({type:`tab.opened`,requestId:e,targetId:t})}}handleTabOpenError(e,t){let n=this.pendingTabOpenRoutes.get(e);if(n){if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.reject(Error(t)));return}this.context.followers.followers.get(n.requesterBootstrapId)?.sync.send({type:`tab.open.error`,requestId:e,error:t})}}rejectPendingForFollower(e){for(let[t,n]of this.pendingTabOpenRoutes){if(n.targetBootstrapId!==e&&n.requesterBootstrapId!==e)continue;this.pendingTabOpenRoutes.delete(t);let r=this.tabOpenResolvers.get(t);r&&(this.tabOpenResolvers.delete(t),r.reject(Error(`follower disconnected before the tab opened`)))}}},Ct=45e3,wt=`leader`,Tt=class{context;options;inFlight=new Map;constructor(e,t){this.context=e,this.options=t,e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.abandonForFollower(e)})}async handleTeleportRequest(e,t){let{requestId:n,targetId:r}=t;this.context.log.info(`Follower requested a tab teleport`,{bootstrapId:e,targetId:r}),this.inFlight.set(n,{bootstrapId:e,settled:!1});let i=setTimeout(()=>this.fail(n,`tab teleport timed out`),Ct);try{let t=this.context.followers.runtimeIdForBootstrap(e);if(!t){this.fail(n,`requesting follower has not advertised a runtime yet`);return}let i=this.options.getTargetEntries().find(e=>e.targetId===r);if(!i){this.fail(n,`source tab ${r} is not in the tray registry`);return}let a=this.context.options.browserAPI;if(!a){this.fail(n,`leader has no BrowserAPI to drive the teleport`);return}let o=i.runtimeId===wt?i.localTargetId:i.targetId,s=await(this.options.teleportTab??await Et())(a,{sourceTargetId:o,destination:{kind:`runtime`,runtimeId:t}});this.succeed(n,s.targetId,s.degraded)}catch(e){this.fail(n,e instanceof Error?e.message:String(e))}finally{clearTimeout(i)}}succeed(e,t,n){let r=this.inFlight.get(e);!r||r.settled||(r.settled=!0,this.inFlight.delete(e),this.context.log.info(`Tab teleport to follower completed`,{requestId:e,targetId:t,degraded:n}),this.context.followers.followers.get(r.bootstrapId)?.sync.send({type:`tab.opened`,requestId:e,targetId:t}))}fail(e,t){let n=this.inFlight.get(e);!n||n.settled||(n.settled=!0,this.inFlight.delete(e),this.context.log.warn(`Tab teleport to follower failed`,{requestId:e,error:t}),this.context.followers.followers.get(n.bootstrapId)?.sync.send({type:`tab.open.error`,requestId:e,error:t}))}abandonForFollower(e){for(let[t,n]of[...this.inFlight])n.bootstrapId===e&&(n.settled=!0,this.inFlight.delete(t),this.context.log.info(`Dropped in-flight tab teleport for departed follower`,{requestId:t,bootstrapId:e}))}};async function Et(){return(await o(()=>import(`./tab-teleport-Dhh60nH7.js`),__vite__mapDeps([45,12,13,46,47,48]))).teleportTabOneWay}var Dt=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1,kind:r.kind??`browser`,capabilities:r.capabilities});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}};function z(e){return e.kind===`cherry`}function Ot(e,t){return e.filter(e=>e.kind===`preview`?!1:t.requireNetwork&&e.capabilities?e.capabilities.network===!0:!z(e)||!t.requireNetwork)}var kt=class{context;options;registry=new Dt;constructor(e,t){this.context=e,this.options=t,e.followers.onFollowerRemoved({removeRuntime:(e,t)=>this.registry.removeRuntime(t),afterRegistryCleanup:()=>{this.registry.hasChanged()&&this.broadcastTargetRegistry()}})}setLocalTargets(e){this.registry.setTargets(`leader`,e),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){this.context.followers.followers.size!==0&&this.context.followers.broadcastToAllFollowers({type:`targets.registry`,targets:this.getFollowerBroadcastEntries()})}sendTargetRegistryToFollower(e){let t=this.getFollowerBroadcastEntries();t.length!==0&&this.context.followers.followers.get(e)?.sync.send({type:`targets.registry`,targets:t})}getTargets(){return this.getConnectedEntries()}getRegistryEntries(){return this.registry.getEntries()}getFollowerBroadcastEntries(){return this.getConnectedEntries().filter(e=>e.kind!==`preview`)}getConnectedEntries(){return[...this.registry.getEntries().filter(e=>{if(e.runtimeId===`leader`)return!0;let t=this.context.followers.runtimeToBootstrap.get(e.runtimeId);return t?this.context.followers.followers.has(t):!1}),...this.options.getPreviewTargetEntries()]}canRuntimeServeTeleport(e,t){if(t.runtime===`slicc-cherry`)return!1;if(t.floatType===`ios`)return this.registry.getEntries().filter(t=>t.runtimeId===e).some(e=>e.capabilities?.network===!0);let n=this.registry.getEntries().filter(t=>t.runtimeId===e);return n.length===0?t.peerCapabilities?.browser===!0:Ot(n,{requireNetwork:!0}).length>0}getTeleportEligibleBootstrapIds(){let e=new Set;for(let[t,n]of this.context.followers.runtimeToBootstrap){let r=this.context.followers.followers.get(n);r&&this.canRuntimeServeTeleport(t,r)&&e.add(n)}return e}getBestFollowerForTeleport(){let e=[];for(let[t,n]of this.context.followers.runtimeToBootstrap){let r=this.context.followers.followers.get(n);!r||!this.canRuntimeServeTeleport(t,r)||e.push({runtimeId:t,bootstrapId:n,floatType:r.floatType,lastActivity:r.lastActivity})}if(e.length===0)return null;let t=e.filter(e=>e.floatType===`standalone`),n=t.length>0?t:e;return n.sort((e,t)=>t.lastActivity-e.lastActivity),n[0]}handleFollowerTargetsAdvertise(e,t){this.context.log.info(`Follower targets advertised`,{bootstrapId:e,runtimeId:t.runtimeId,targetCount:t.targets.length}),this.options.cleanupOrphanedRemoteTransports(t.runtimeId),this.context.followers.setRuntimeId(t.runtimeId,e),this.registry.setTargets(t.runtimeId,t.targets);let n=this.context.followers.followers.get(e);if(n&&n.runtime===`slicc-cherry`){let e=t.targets.find(e=>e.kind===`cherry`);if(e)try{n.hostOrigin=new URL(e.url).origin}catch{}}this.broadcastTargetRegistry(),this.options.onTeleportEligibilityChanged?.()}},B=32768,At=1048576,jt=3e4,Mt=3;function V(e){return e.kind===`frozen`?`frozen:${e.sessionId}`:`active`}function Nt(e){let t=8192,n=``;for(let r=0;r<e.length;r+=t)n+=String.fromCharCode(...e.subarray(r,r+t));return btoa(n)}async function Pt(e,t,n){if(typeof e.bufferedAmount==`number`)for(;!n.aborted&&e.bufferedAmount>t;)await new Promise(e=>setTimeout(e,25))}var Ft=class e{context;activeExports=new Map;ackWaiters=new Map;constructor(e){this.context=e,e.followers.onFollowerRemoved({afterRegistryCleanup:e=>this.handleFollowerRemoved(e)})}static exportKey(e,t){return`${e}:${t}`}static ackKey(e,t,n){return`${e}:${t}:${n}`}clearAckWaiters(e,t){let n=`${e}:${t}:`;for(let[e,t]of this.ackWaiters)e.startsWith(n)&&(t.reject(Error(`export aborted`)),this.ackWaiters.delete(e))}handleFollowerRemoved(e){for(let[t,n]of this.activeExports){if(n.bootstrapId!==e)continue;n.abort.abort();let r=t.slice(e.length+1);this.clearAckWaiters(e,r),this.activeExports.delete(t)}}async handleTranscriptExportRequest(t,n,r){let i=e.exportKey(t,n);if(this.activeExports.has(i)){this.context.log.warn(`Duplicate transcript export request from same follower, ignoring`,{bootstrapId:t,requestId:n});return}let a=this.context.followers.followers.get(t);if(!a)return;let{requestSudoApproval:o,createTranscriptExport:s}=this.context.options;if(!o||!s){a.sync.send({type:`transcript.export.denied`,requestId:n});return}if([...this.activeExports.values()].some(e=>e.bootstrapId===t)){this.context.log.warn(`Follower already has an in-flight export; denying duplicate`,{bootstrapId:t,requestId:n}),a.sync.send({type:`transcript.export.denied`,requestId:n});return}let c=new AbortController;this.activeExports.set(i,{bootstrapId:t,abort:c});let l=L(a.floatType,a.runtime);a.sync.send({type:`transcript.export.pending`,requestId:n});let u=!1;try{let e=await o({kind:`export`,detail:V(r),suggestedPattern:V(r),followerLabel:l,hostOrigin:a.hostOrigin});u=e.decision===`allow`||e.decision===`always`}catch(e){this.context.log.warn(`transcript export approval threw`,{requestId:n,error:e instanceof Error?e.message:String(e)}),u=!1}let d=this.context.followers.followers.get(t);if(!this.activeExports.has(i)||!d){this.activeExports.delete(i);return}if(!u){d.sync.send({type:`transcript.export.denied`,requestId:n}),this.activeExports.delete(i);return}this.streamTranscriptExport(t,n,r,c)}handleTranscriptExportCancel(t,n){let r=e.exportKey(t,n),i=this.activeExports.get(r);i&&(this.context.log.info(`Transcript export cancelled by follower`,{requestId:n,bootstrapId:t}),i.abort.abort(),this.activeExports.delete(r),this.clearAckWaiters(t,n))}handleTranscriptExportAck(t,n,r){let i=e.ackKey(t,n,r),a=this.ackWaiters.get(i);a&&(this.ackWaiters.delete(i),a.resolve())}async streamTranscriptExport(t,n,r,i){let a=e.exportKey(t,n),{createTranscriptExport:s}=this.context.options;if(!this.context.followers.followers.get(t)||!s){this.activeExports.delete(a);return}let c=e=>{let r=this.context.followers.followers.get(t);r&&r.sync.send({type:`transcript.export.error`,requestId:n,code:e}),this.activeExports.delete(a)},l;try{l=await s(r,i.signal)}catch(e){if(i.signal.aborted){this.activeExports.delete(a);return}this.context.log.warn(`createTranscriptExport failed`,{requestId:n,error:e instanceof Error?e.message:String(e)}),c(e instanceof d?e.code:`session-not-found`);return}if(i.signal.aborted||!this.activeExports.has(a)){this.activeExports.delete(a);return}let u=this.context.followers.followers.get(t)?.sync;if(!u){this.activeExports.delete(a);return}u.send({type:`transcript.export.start`,requestId:n,filename:l.filename});let{sha256:f}=await o(async()=>{let{sha256:e}=await import(`./src-BWaKqLvQ.js`).then(e=>e.t);return{sha256:e}},__vite__mapDeps([49,1])),p=f.create(),m=(this.context.followers.followers.get(t)?.peerProtocolVersion??0)>=Mt,{streamError:h,chunkCount:g,byteLength:_}=await this.sendExportChunks({bootstrapId:t,requestId:n,chunks:l.chunks,hasher:p,abort:i,awaitAck:m,onSlice:(e,r)=>{let i=this.context.followers.followers.get(t);return i?(i.sync.send({type:`transcript.export.chunk`,requestId:n,index:e,data:r}),!0):!1}});if(h){c(`transfer-corrupt`);return}if(!this.activeExports.has(a))return;if(i.signal.aborted){c(`transfer-aborted`);return}let v;try{v=await l.completion}catch{if(i.signal.aborted){this.activeExports.delete(a);return}c(`transfer-aborted`);return}if(i.signal.aborted||!this.activeExports.has(a)){this.activeExports.delete(a);return}if(v.byteLength!==_){this.context.log.warn(`Transcript export byte count mismatch between service and leader stream`,{requestId:n,serviceByteLength:v.byteLength,leaderByteCount:_}),c(`transfer-corrupt`);return}let y=p.hex();if(v.sha256!==y){this.context.log.warn(`Transcript export SHA-256 mismatch between service and leader stream`,{requestId:n}),c(`transfer-corrupt`);return}let b=this.context.followers.followers.get(t);b&&b.sync.send({type:`transcript.export.complete`,requestId:n,chunks:g,byteLength:_,sha256:y}),this.activeExports.delete(a)}async sendExportChunks(t){let{bootstrapId:n,requestId:r,chunks:i,hasher:a,abort:o,onSlice:s,awaitAck:c}=t,l=e.exportKey(n,r),u=this.context.followers.followers.get(n)?.sync;if(!u)return{streamError:!0,chunkCount:0,byteLength:0};let d=0,f=0;try{for await(let e of i){if(o.signal.aborted||!this.activeExports.has(l))return{streamError:!1,chunkCount:d,byteLength:f};a.update(e),f+=e.byteLength;let t=await this.sendExportSlices({bootstrapId:n,requestId:r,b64:Nt(e),sync:u,key:l,abort:o,onSlice:s,awaitAck:c,startIdx:d});if(d=t.nextIdx,t.done!==`continue`)return{streamError:t.done===`error`,chunkCount:d,byteLength:f}}}catch(e){return o.signal.aborted?{streamError:!1,chunkCount:d,byteLength:f}:(this.context.log.warn(`Error streaming transcript export chunks`,{requestId:r,error:e instanceof Error?e.message:String(e)}),{streamError:!0,chunkCount:d,byteLength:f})}return{streamError:!1,chunkCount:d,byteLength:f}}async sendExportSlices(e){let{bootstrapId:t,requestId:n,b64:r,sync:i,key:a,abort:o,onSlice:s,awaitAck:c}=e,l=e.startIdx;for(let e=0;e<r.length;e+=B){if(o.signal.aborted||!this.activeExports.has(a)||(await Pt(i,At,o.signal),o.signal.aborted||!this.activeExports.has(a)))return{nextIdx:l,done:`abort`};let u=r.slice(e,e+B);if(!s(l,u))return{nextIdx:l,done:`error`};if(c&&(!await this.waitForAck(t,n,l,o)||o.signal.aborted||!this.activeExports.has(a)))return{nextIdx:l+1,done:`abort`};l++}return{nextIdx:l,done:`continue`}}waitForAck(t,n,r,i){let a=i.signal;return new Promise(o=>{if(a.aborted){o(!1);return}let s=e.ackKey(t,n,r),c,l=()=>{c!==void 0&&(clearTimeout(c),c=void 0)},u=()=>{this.ackWaiters.delete(s),l()},d=()=>{u(),o(!1)};a.addEventListener(`abort`,d,{once:!0}),c=setTimeout(()=>{c=void 0,i.abort(),this.clearAckWaiters(t,n)},jt),this.ackWaiters.set(s,{resolve:()=>{a.removeEventListener(`abort`,d),u(),o(!0)},reject:()=>{a.removeEventListener(`abort`,d),u(),o(!1)}})})}},H=s(`tray-leader-sync`),It=class{options;lastThemeJson=null;followerRegistry;broadcast;cdpRouter;remoteExec;fsRouter;tabRouter;previewBridge;cherryRouter;teleportPool;transcriptExport;followerDispatch;requesterTracker=new bt;tabTeleportRouter;oauthPopupDelegation;sudoDelegation;pushRegistered=new Set;get followers(){return this.followerRegistry.followers}constructor(e){this.options=e,this.followerRegistry=new tt({log:H,onMessage:(e,t)=>this.followerDispatch.dispatch(e,t),onFollowerDead:e=>this.options.onFollowerDead?.(e),onFollowerCountChanged:e=>this.options.onFollowerCountChanged?.(e)});let t={options:e,followers:this.followerRegistry,log:H,sendControl:e.sendControl};this.broadcast=new Ye(t),this.previewBridge=new _t(t),this.cdpRouter=new Ze(t,{getBridgeTransport:e=>this.previewBridge.getBridgeTransport(e)}),this.remoteExec=new yt(t),this.teleportPool=new kt(t,{cleanupOrphanedRemoteTransports:e=>this.cdpRouter.cleanupOrphanedRemoteTransports(e),getPreviewTargetEntries:()=>this.previewBridge.getTargetEntries(),onTeleportEligibilityChanged:()=>this.options.onFollowerTargetsChanged?.()}),this.transcriptExport=new Ft(t),this.fsRouter=new at(t),this.tabRouter=new St(t,{getTargetEntries:()=>this.teleportPool.getRegistryEntries(),isCherryTarget:z}),this.cherryRouter=new Qe(t),this.tabTeleportRouter=new Tt(t,{getTargetEntries:()=>this.teleportPool.getConnectedEntries()}),this.oauthPopupDelegation=new pt(t),this.sudoDelegation=new xt(t),this.followerDispatch=new nt(t,{broadcast:this.broadcast,cdpRouter:this.cdpRouter,remoteExec:this.remoteExec,fsRouter:this.fsRouter,tabRouter:this.tabRouter,teleportPool:this.teleportPool,transcriptExport:this.transcriptExport,cherryRouter:this.cherryRouter,requesterTracker:this.requesterTracker,tabTeleportRouter:this.tabTeleportRouter,oauthPopupDelegation:this.oauthPopupDelegation,sudoDelegation:this.sudoDelegation,registerPushToken:(e,t)=>{this.pushRegistered.add(e);try{this.options.sendControl({type:`push.register`,bootstrapId:e,...t})}catch(t){H.warn(`Could not forward push.register to the tray hub`,{bootstrapId:e,error:t instanceof Error?t.message:String(t)})}}}),this.followerRegistry.onFollowerRemoved({afterRegistryCleanup:e=>this.requesterTracker.handleFollowerRemoved(e)}),Object.defineProperties(this,{activeExports:{get:()=>this.transcriptExport.activeExports},bridgeConns:{get:()=>this.previewBridge.bridgeConns},mintMap:{get:()=>this.previewBridge.mintMap}})}addFollower(e,t,n){let{sync:r}=this.followerRegistry.addFollower(e,t,n);r.send({type:`hello`,protocolVersion:7,capabilities:{exec:this.options.execInShell!==void 0}}),this.broadcast.sendSnapshotToFollower(e),this.broadcast.sendScoopsListToFollower(e),this.broadcast.sendModelCatalogToFollower(e),this.broadcast.sendSprinklesListToFollower(e),this.lastThemeJson!==null&&r.send({type:`theme.apply`,themeJson:this.lastThemeJson}),this.teleportPool.sendTargetRegistryToFollower(e)}removeFollower(e){this.followerRegistry.removeFollower(e)}broadcastEvent(e){this.broadcast.broadcastEvent(e)}broadcastUserMessage(e,t,n){this.broadcast.broadcastUserMessage(e,t,n)}broadcastStatus(e){this.broadcast.broadcastStatus(e)}broadcastSnapshot(){this.broadcast.broadcastSnapshot()}broadcastScoopsList(){this.broadcast.broadcastScoopsList()}broadcastSprinklesList(){this.broadcast.broadcastSprinklesList()}broadcastModelCatalog(){this.broadcast.broadcastModelCatalog()}broadcastModelState(){this.broadcast.broadcastModelState()}getSprinkleInstances(){return this.followerRegistry.getSprinkleInstances()}broadcastSprinkleUpdate(e,t,n){return this.broadcast.broadcastSprinkleUpdate(e,t,n)}broadcastTheme(e){this.lastThemeJson=e,this.broadcast.broadcastTheme(e)}broadcastSprinkleReloaded(e){this.broadcast.broadcastSprinkleReloaded(e)}broadcastPreviewOpen(e){this.broadcast.broadcastPreviewOpen(e)}async execOnRemote(e,t,n={}){return this.remoteExec.execOnRemote(e,t,n)}getExecCapableBootstrapIds(){return this.followerRegistry.getExecCapableBootstrapIds()}getBrowserCapableBootstrapIds(){return this.followerRegistry.getBrowserCapableBootstrapIds()}getTeleportEligibleBootstrapIds(){return this.teleportPool.getTeleportEligibleBootstrapIds()}getFollowerMotds(){return this.followerRegistry.getFollowerMotds()}getFollowerDetails(){return this.followerRegistry.getFollowerDetails()}setLocalTargets(e){this.teleportPool.setLocalTargets(e)}broadcastTargetRegistry(){this.teleportPool.broadcastTargetRegistry()}getTargets(){return this.teleportPool.getTargets()}createRemoteTransport(e,t){return this.cdpRouter.createRemoteTransport(e,t)}removeRemoteTransport(e,t){this.cdpRouter.removeRemoteTransport(e,t)}getConnectedFollowers(){return this.followerRegistry.getConnectedFollowers()}getBestFollowerForTeleport(){return this.teleportPool.getBestFollowerForTeleport()}shouldDelegateSudo(){return this.options.headlessLeader===!0?!0:this.sudoDelegation.hasCapableFollower()?this.requesterTracker.get()?.kind===`follower`:!1}delegateSudoApproval(e,t){return this.sudoDelegation.requestApproval(e,t)}notifyTurnEnd(e){if(this.pushRegistered.size!==0)try{this.options.sendControl({type:`push.send`,category:`turn_end`,label:e})}catch(e){H.debug?.(`push.send(turn_end) not delivered`,{error:e instanceof Error?e.message:String(e)})}}noteLeaderUserMessage(){this.requesterTracker.noteLeaderUserMessage()}getLastUserMessageOrigin(){return this.requesterTracker.get()}hasDelegatableFollower(){return this.pickDriveableFollower()!==null||this.pickOAuthPopupFollower()!==null}shouldDelegateOAuthLogin(){return this.options.headlessLeader===!0?!0:this.hasDelegatableFollower()?this.requesterTracker.get()?.kind===`follower`:!1}async delegateOAuthLogin(e){let t=this.pickDriveableFollower();if(t&&this.options.browserAPI){H.info(`Delegating OAuth login by driving a follower browser`,{runtimeId:t.runtimeId});try{return{redirectUrl:await dt({browser:this.options.browserAPI,runtimeId:t.runtimeId,authorizeUrl:e})}}catch(e){H.warn(`Driven login failed; trying the popup path`,{error:String(e)})}}let n=this.pickOAuthPopupFollower();return n?(H.info(`Delegating OAuth popup to a follower`,{bootstrapId:n}),this.oauthPopupDelegation.requestPopup(n,e)):{redirectUrl:null,error:`no connected follower can show an interactive login`}}pickDriveableFollower(){let e=this.teleportPool.getTeleportEligibleBootstrapIds(),t=e=>this.followerRegistry.runtimeIdForBootstrap(e),n=this.requesterTracker.get();if(n?.kind===`follower`&&e.has(n.bootstrapId)){let e=t(n.bootstrapId);if(e)return{bootstrapId:n.bootstrapId,runtimeId:e}}let r=[...this.followerRegistry.followers.values()].filter(t=>e.has(t.bootstrapId)).sort((e,t)=>t.lastActivity-e.lastActivity);for(let e of r){let n=t(e.bootstrapId);if(n)return{bootstrapId:e.bootstrapId,runtimeId:n}}return null}pickOAuthPopupFollower(){let e=e=>this.followerRegistry.followers.get(e)?.peerCapabilities?.oauthPopup===!0,t=this.requesterTracker.get();return t?.kind===`follower`&&e(t.bootstrapId)?t.bootstrapId:[...this.followerRegistry.followers.values()].filter(t=>e(t.bootstrapId)).sort((e,t)=>t.lastActivity-e.lastActivity)[0]?.bootstrapId??null}get hasFollowers(){return this.followers.size>0}stop(){this.cdpRouter.resetPreviewFocus();for(let e of[...this.followers.keys()])this.removeFollower(e);this.previewBridge.stop()}emitCherrySliccEvent(e,t,n){return this.cherryRouter.emitCherrySliccEvent(e,t,n)}openRemoteTab(e,t){return this.tabRouter.openRemoteTab(e,t)}sendFsRequest(e,t){return this.fsRouter.sendFsRequest(e,t)}registerMintedPreview(e,t){this.previewBridge.registerMintedPreview(e,t)}dropMintedPreview(e){this.previewBridge.dropMintedPreview(e)}restorePreviewState(e){this.previewBridge.restorePreviewState(e)}getPreviewLifecycleRecords(e){return this.previewBridge.getPreviewLifecycleRecords(e)}clearPreviewLifecycleRecords(e){return this.previewBridge.clearPreviewLifecycleRecords(e)}rearmPreviewAnnouncements(e){return this.previewBridge.rearmPreviewAnnouncements(e)}onBridgeConnected(e){this.previewBridge.onBridgeConnected(e)}onBridgeDisconnected(e){this.previewBridge.onBridgeDisconnected(e)}onBridgeCdpResponse(e){this.previewBridge.onBridgeCdpResponse(e)}getBridgeTransport(e){return this.previewBridge.getBridgeTransport(e)}},U=s(`page-leader-tray`);function W(e,t){let n=new Map(t.getFollowerDetails().map(e=>[e.bootstrapId,e])),r=[];for(let t of e.getPeers()){let e=n.get(t.bootstrapId);t.state===`connected`&&!e||(r.push({bootstrapId:t.bootstrapId,runtime:e?.runtime??t.runtime,connectedAt:e?.connectedAt??t.connectedAt??void 0,lastActivity:e?.lastActivity,floatType:e?.floatType??I(t.runtime),hostOrigin:e?.hostOrigin,selectedScoopJid:e?.selectedScoopJid,health:e?.health,peerState:t.state}),n.delete(t.bootstrapId))}for(let e of n.values())r.push({...e,peerState:`connected`});return r}function Lt(e,t,n){return new It({sendControl:e=>t().sendControlMessage(e),getMessages:e.getMessages,getMessagesForScoop:e.getMessagesForScoop,getScoopJid:e.getScoopJid,getScoops:e.getScoops,getSprinkles:e.getSprinkles,getModelCatalog:e.getModelCatalog,getModelSelectionState:e.getModelSelectionState,onFollowerModelSelect:e.onFollowerModelSelect,onFollowerThinkingSet:e.onFollowerThinkingSet,readSprinkleContent:e.readSprinkleContent,onSprinkleLick:e.onSprinkleLick,onSprinkleInstancesChanged:e.onSprinkleInstancesChanged,onForwardedLick:e.onForwardedLick,onFollowerMessage:e.onFollowerMessage,onFollowerAbort:e.onFollowerAbort,onFollowerNewSession:e.onFollowerNewSession,onFollowerCountChanged:n,onRemoteTransportsCleaned:e.onRemoteTransportsCleaned,execInShell:e.execInShell,closeExecShell:e.closeExecShell,onCherryHostEvent:e.onCherryHostEvent,onPreviewLick:e.onPreviewLick,requestSudoApproval:e.requestSudoApproval,createTranscriptExport:e.createTranscriptExport,headlessLeader:e.kind===`hosted`,browserAPI:e.browserAPI,browserTransport:e.browserTransport,vfs:e.vfs})}function Rt(e,t,n,r){return new le({peerConnectionFactory:r,sendControlMessage:t=>e().sendControlMessage(t),onPeersChanged:n,onPeerConnected:(e,n)=>{U.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})},onPeerDisconnected:(e,t)=>{U.info(`Tray follower disconnected`,{bootstrapId:e,reason:t})},onPeerTransportClosed:e=>{t.removeFollower(e)}})}function zt(e,t,n,r,i,a){let o=t=>{e.browserTransport?.sendLeaderJoinUrl?.(t)};return new ye({workerBaseUrl:e.workerBaseUrl,runtime:e.runtime??`slicc-standalone`,...e.kind?{kind:e.kind}:{},onLeaderReady:t=>{e.onLeaderReady?.(t),o(t.joinUrl)},fetchImpl:r,...e._storeOverride?{store:e._storeOverride}:{},...e._webSocketFactory?{webSocketFactory:e._webSocketFactory}:{},onControlMessage:r=>{if(r.type===`webhook.event`){e.sendWebhookEvent(r.webhookId,r.headers,r.body);return}if(r.type===`preview.request`){let t=e.vfs;if(!t){a().sendControlMessage({type:`preview.response`,reqId:r.reqId,ok:!1,status:500,reason:`leader has no VFS bound`});return}Ge(r,{send:e=>a().sendControlMessage(e)},t).catch(e=>{U.error(`preview.request handling failed`,{error:e instanceof Error?e.message:String(e)})});return}if(r.type===`preview.revoked`){U.info(`Preview revoked by worker`,{previewToken:r.previewToken}),n.dropMintedPreview(r.previewToken);return}if(r.type===`preview.state`){n.restorePreviewState(r);return}if(r.type===`bridge.connected`){n.onBridgeConnected(r);return}if(r.type===`bridge.disconnected`){n.onBridgeDisconnected(r);return}if(r.type===`bridge.cdp.response`){n.onBridgeCdpResponse(r);return}t.handleControlMessage(r).catch(e=>{U.error(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})},onReconnecting:(e,t)=>{U.info(`Leader tray reconnecting`,{attempt:e,lastError:t})},onReconnected:e=>{U.info(`Leader tray reconnected`,{trayId:e.trayId}),i(e),o(e.joinUrl)},onReconnectGaveUp:(e,t)=>{U.error(`Leader tray reconnect gave up`,{lastError:e,attempts:t}),o(null)}})}function Bt(e,t){let n=new ne(U,{failureMessage:`Leader CDP target refresh failed (best-effort, throttled)`,recoveryMessage:`Leader CDP target refresh recovered (stable for debounce window)`});return async()=>{let r;try{r=await e.browserAPI.listPages()}catch(e){n.reportFailure(e);return}n.reportSuccess();try{let e=typeof location<`u`&&location.origin?[location.origin]:void 0,n=r.filter(t=>!m(t.url,{selfOrigins:e})).map(e=>({targetId:e.targetId,title:e.title,url:e.url}));t.setLocalTargets(n)}catch(e){U.error(`Leader target broadcast failed (sync.setLocalTargets threw)`,{error:e instanceof Error?e.message:String(e)})}}}function Vt(e,t){return setInterval(()=>{try{e.broadcastScoopsList(),e.broadcastSprinklesList()}catch(e){U.error(`Failed to broadcast follower lists`,{error:e instanceof Error?e.message:String(e)})}},t)}function Ht(e){return t=>{let n=e._historyOverride??Ut();if(n)try{let e=y(n.href,t.workerBaseUrl,t.trayId);e!==n.href&&n.replaceState(null,``,e)}catch(e){U.debug(`URL bar update skipped`,{error:e instanceof Error?e.message:String(e)})}}}function G(e){let t=e._refreshIntervalMs??5e3,n=e._scoopBroadcastCoalesceMs??50,r=e._fetchImpl??((e,t)=>fetch(e,t)),i,a,o,s=Ht(e),c=()=>{let t=W(a,o).filter(e=>e.peerState===`connected`).length;e.onFollowerCountChanged?.(t)};o=Lt(e,()=>i,c),e.browserAPI.setTrayTargetProvider(o),a=Rt(()=>i,o,c,e._peerConnectionFactory),i=zt(e,a,o,r,s,()=>i);let l=e.onAgentEvent(e=>o.broadcastEvent(e)),u=[],d=Bt(e,o);u.push(setInterval(d,t)),d(),u.push(Vt(o,t));let f=i.start();f.then(s).catch(e=>{U.error(`Leader tray start failed`,{error:e instanceof Error?e.message:String(e)})});let p=!1,m=null;return{ready:f,scheduleScoopsListBroadcast:()=>{p||m!==null||(m=setTimeout(()=>{m=null,p||o.broadcastScoopsList()},n))},stop(){p=!0,m!==null&&clearTimeout(m),m=null,l();for(let e of u)clearInterval(e);o.stop(),a.stop(),i.stop()},async reset(){o.stop(),a.stop(),i.stop(),await i.clearSession();let e=await i.start();return s(e),T()},leader:i,peers:a,sync:o,get currentLeaderSync(){return p?null:o}}}function Ut(){return typeof window>`u`||!window.history||!window.location?null:{get href(){return window.location.href},replaceState(e,t,n){window.history.replaceState(e,t,n)}}}function Wt(e){let t=new Map,n=(e,t)=>`${e}:${t}`,r=(r,i)=>{let a=n(r,i),o=t.get(a);if(!o){let n=e.getSync();if(!n)throw Error(`remote-cdp: leader tray not started`);o={runtimeId:r,localTargetId:i,transport:n.createRemoteTransport(r,i),forwarders:new Map},t.set(a,o)}return o},i=n=>{let r=t.get(n);if(!r)return;for(let[e,t]of r.forwarders)r.transport.off(e,t.listener);r.forwarders.clear();let i=e.getSync();i?.removeRemoteTransport?i.removeRemoteTransport(r.runtimeId,r.localTargetId):r.transport.disconnect(),t.delete(n)};return{async send({runtimeId:e,localTargetId:t,method:n,params:i,sessionId:a,timeout:o}){return r(e,t).transport.send(n,i,a,o)},async subscribe({runtimeId:t,localTargetId:n,event:i}){let a=r(t,n),o=a.forwarders.get(i);if(o)return o.count+=1,{ok:!0};let s=r=>e.postEvent({runtimeId:t,localTargetId:n,method:i,params:r});return a.transport.on(i,s),a.forwarders.set(i,{listener:s,count:1}),{ok:!0}},async unsubscribe({runtimeId:e,localTargetId:r,event:i}){let a=t.get(n(e,r)),o=a?.forwarders.get(i);return!a||!o?{ok:!0}:(--o.count,o.count<=0&&(a.transport.off(i,o.listener),a.forwarders.delete(i)),{ok:!0})},async detach({runtimeId:e,localTargetId:t}){return i(n(e,t)),{ok:!0}},async openTab({runtimeId:t,url:n}){let r=e.getSync();if(!r?.openRemoteTab)throw Error(`remote-cdp: openRemoteTab not available`);return{targetId:await r.openRemoteTab(t,n)}},cleanupRuntime(e){let n=`${e}:`;for(let e of[...t.keys()])e.startsWith(n)&&i(e)},disposeAll(){for(let e of[...t.keys()])i(e)}}}var K=s(`tray-leader-lock`);function Gt(e){return`slicc-tray-leader:${e}`}function q(){let e=!1,t=null;return{release:()=>{e||(e=!0,t?.())},heldPromise:new Promise(e=>{t=e})}}async function J(e,t){if(!t)return{status:`granted`,release:()=>{}};let n=Gt(e),r,i=new Promise(e=>{r=e}),a=q();return t.request(n,{mode:`exclusive`,ifAvailable:!0},e=>e===null?(r(!1),Promise.resolve()):(r(!0),a.heldPromise)),await i?{status:`granted`,release:a.release}:{status:`deferred`,waitForPromotion:()=>new Promise(e=>{let r=q();t.request(n,{mode:`exclusive`},()=>(e({release:r.release}),r.heldPromise))})}}async function Kt(e){let t=await J(e.workerBaseUrl,e.lockManager);if(t.status===`granted`){if(!e.shouldLead()){t.release();return}e.onGranted(t.release);return}K.error(`Another tab is already leading on this tray worker — deferring leader start until the other tab releases the lock.`);let{release:n}=await t.waitForPromotion();if(!e.shouldLead()){n();return}K.error(`Late promotion: this tab is now the tray leader.`),e.onGranted(n)}function qt(){return typeof navigator<`u`&&navigator.locks&&typeof navigator.locks.request==`function`?navigator.locks:null}function Y(e){let t=e.sync.getExecCapableBootstrapIds(),n=e.sync.getBrowserCapableBootstrapIds(),r=e.sync.getTeleportEligibleBootstrapIds(),i=e.sync.getFollowerMotds();return W(e.peers,e.sync).map(e=>({runtimeId:se(e.bootstrapId),bootstrapId:e.bootstrapId,runtime:e.runtime,connectedAt:e.connectedAt,lastActivity:e.lastActivity,floatType:e.floatType,hostOrigin:e.hostOrigin,selectedScoopJid:e.selectedScoopJid,health:e.health,peerState:e.peerState,exec:t.has(e.bootstrapId),cdp:n.has(e.bootstrapId),teleportEligible:r.has(e.bootstrapId),motd:i.get(e.bootstrapId)}))}function X(){return a().flatMap(e=>e.models.map(t=>({providerName:e.providerName,modelId:`${e.providerId}:${t.id}`,modelName:t.name??t.id,reasoning:t.reasoning===!0})))}function Jt(e,t){let n=t?be(t):void 0;if(!n)return Yt(e);let r=`${n.provider}:${n.id}`;return e.find(e=>e.modelId===r)?.modelId??e.find(e=>e.modelId.endsWith(`:${n.id}`))?.modelId??r}function Yt(e){let t=r();return e.find(e=>e.modelId===`${t.provider}:${t.id}`)?.modelId??e.find(e=>e.modelId.endsWith(`:${t.id}`))?.modelId??`${t.provider}:${t.id}`}async function Xt(t){let n=i().map(t=>e(t.providerId).refreshModels).filter(e=>e!==void 0);if(n.length===0)return!1;let r=await Promise.allSettled(n.map(e=>e()));for(let e of r)e.status===`rejected`&&t.warn(`dynamic model catalog refresh failed`,e.reason);return!0}function Zt(e){e.window.addEventListener(Oe,()=>{e.getSync()?.broadcastModelCatalog()}),e.window.addEventListener(`slicc:accounts-changed`,()=>{e.getSync()?.broadcastModelCatalog(),$t(e.refreshDynamicCatalogs(),e.refreshTimeoutMs??5e3).then(t=>{t&&e.getSync()?.broadcastModelCatalog()}).catch(t=>e.log.warn(`dynamic model catalog refresh failed`,t))})}function Qt(e){e.window.addEventListener(ke,()=>{e.getSync()?.broadcastModelState()}),e.window.addEventListener(`model-change`,t=>{t.detail?.source!==`follower`&&e.getSync()?.broadcastModelState()})}function $t(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`dynamic model catalog refresh timed out`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}function Z(e,t,n){let{browser:r,client:i,getController:a}=e,o=null,s=[],c=()=>{e.refs.switcher.scoops=ue(s,o)},l=Me({composerMeta:e.refs.composerMeta,getSync:n,getSelectedScoopJid:()=>o,interceptLocalHandlers:!0,getLockedEffortLevel:()=>e.window.localStorage.getItem(`slicc_locked_effort_level`)});return e.refs.switcher.connection=`disconnected`,e.refs.switcher.addEventListener(`slicc-scoop-select`,t=>{let r=n();if(!r)return;t.stopImmediatePropagation();let i=t.detail?.key;i&&(o=i,c(),e.refs.switcher.setAttribute(`active`,i),r.selectScoop(i))},{capture:!0}),{joinUrl:t,onSnapshot:(e,t)=>{o=t;let n=a();n?.loadMessages(e),n?.setProcessing(e.some(e=>e.isStreaming))},onUserMessage:(e,t,n,r)=>a()?.addUserMessage(e,r),onStatus:(e,t)=>{ae(t,o)&&a()?.setProcessing(e===`processing`)},setChatAgent:e=>a()?.setAgent(e),browserAPI:r,onForwardingToggle:e=>i.sendSetFollowerForwarding(e),getSelectedScoopJid:()=>o,onConnectionChange:t=>{e.refs.switcher.connection=t?`connected`:`disconnected`,t||l.reset()},addSprinkle:(t,n,r)=>e.addSprinkle(t,n,r),removeSprinkle:t=>e.removeSprinkle(t),onScoopsList:(t,n)=>{(!o||!t.some(e=>e.jid===o))&&(o=n),s=t,c(),e.refs.switcher.setAttribute(`active`,o)},onOAuthPopupRequest:(t,n)=>ce(t,n,{getPermissionsSurface:pe,window:e.window}),onModelsList:l.onModelsList,onModelState:l.onModelState}}function Q(e){D(e.leader?e.leader.sync.getSprinkleInstances():[])}function en(e,t,n){let r=t.leader?Y(t.leader):[],i=n;i>0?t.persistenceGuard.activate():t.persistenceGuard.deactivate(),e.refs.floatbar.setAttribute(`label`,i>0?`tray · live`:e.baseFloatLabel??`standalone · live`),e.refs.floatbar.followers=Te(r.filter(e=>e.peerState!==`connecting`)),A(r),Q(t),e.window.dispatchEvent(new CustomEvent(Ee,{detail:{followers:r}}))}function tn(e){let{client:t,refs:n}=e;return{getModelSelectionState:e=>{let n=X(),r=t.getScoop(e),i=O(t.getScoops(),r??null),a=r?xe(r):{};return{activeModelId:Jt(n,i),scoopJid:e,thinkingLevel:a.level===`max`?`xhigh`:a.level,effortOverride:a.level===`max`?a.effortOverride??`max`:a.effortOverride}},onFollowerModelSelect:(r,i)=>{let a=X().find(e=>e.modelId===r);if(!a)return!1;let o=i?t.getScoop(i):void 0,s=O(t.getScoops(),o??null);if(!s)return!1;let c=a.modelId.indexOf(`:`);return t.setScoopModel(s.jid,{provider:a.modelId.slice(0,c),id:a.modelId.slice(c+1)}).then(t=>(t&&s.jid===e.getSelectedJid()&&(n.composerMeta.dispatchEvent(new CustomEvent(`model-change`,{bubbles:!0,composed:!0,detail:{id:a.modelId,model:a.modelName,provider:a.providerName,source:`follower`}})),n.composerMeta.setAttribute(`model`,a.modelName)),t)).catch(()=>!1)}}}function nn(e,t,n){let{client:r,refs:i}=e,a=(n=0)=>{en(e,t,n)},s=new Ue(r);return c=>({workerBaseUrl:c,getMessages:()=>e.getController()?.getMessages()??[],getMessagesForScoop:e=>r.getMessagesForScoop(e),getScoopJid:()=>e.getSelectedJid(),getScoops:()=>oe(r.getScoops(),i.switcher.scoops),getModelCatalog:X,...tn(e),onFollowerThinkingSet:(e,t,n)=>r.setScoopThinkingLevel(e,t,n),getSprinkles:()=>{let t=new Set(e.sprinkleManager.opened());return e.sprinkleManager.available().map(e=>({name:e.name,title:e.title,path:e.path,open:t.has(e.name),autoOpen:e.autoOpen,icon:e.icon}))},readSprinkleContent:async t=>{let n=e.sprinkleManager.available().find(e=>e.name===t);if(!n)return null;try{let t=await(await e.openFs()).readFile(n.path,{encoding:`utf-8`});return typeof t==`string`?t:new TextDecoder(`utf-8`).decode(t)}catch{return null}},onSprinkleLick:(e,t,n,i)=>r.sendSprinkleLick(e,t,n,i),onSprinkleInstancesChanged:()=>Q(t),onFollowerMessage:(n,r,i,a)=>{e.getController()?.addUserMessage(n,i),e.agentHandle.sendMessage(n,r,i,a),t.leader?.sync.broadcastUserMessage(n,r,i),t.leader&&A(Y(t.leader))},onFollowerAbort:()=>e.agentHandle.stop(),onFollowerNewSession:t=>{e.window.dispatchEvent(new CustomEvent(je,{detail:{action:t}}))},onFollowerCountChanged:a,onFollowerTargetsChanged:()=>{t.leader&&A(Y(t.leader))},onRemoteTransportsCleaned:e=>n.cleanupRuntime(e),onForwardedLick:e=>r.sendForwardedLick(e),onCherryHostEvent:(e,t,n)=>r.sendCherryHostEvent(e,t,n),onPreviewLick:e=>r.sendPreviewLick(e),requestSudoApproval:e=>r.requestSudoApproval({kind:e.kind,detail:e.detail,...e.suggestedPattern?{suggestedPattern:e.suggestedPattern}:{}}),createTranscriptExport:async(e,t)=>{let{runTranscriptExportForFollower:n}=await o(async()=>{let{runTranscriptExportForFollower:e}=await import(`./wc-transcript-export-DKIleW7-.js`);return{runTranscriptExportForFollower:e}},__vite__mapDeps([50,4,51,13,49,1]));return n(e,t,r)},sendWebhookEvent:(e,t,n)=>r.sendWebhookEvent(e,t,n),onAgentEvent:t=>e.agentHandle.onEvent(t),execInShell:(e,t)=>s.run({command:e,...t}),closeExecShell:e=>s.close(e),browserAPI:e.browser,browserTransport:e.realCdpTransport,vfs:{async stat(t){return(await e.openFs()).stat(t)},async readFile(t,n){return(await e.openFs()).readFile(t,n)},async readDir(t){return(await e.openFs()).readDir(t)},async writeFile(t,n,r){return(await e.openWriter()).writeFile(t,n,r)},async mkdir(t,n){return(await e.openWriter()).mkdir(t,n)},async rm(t,n){return(await e.openWriter()).rm(t,n)}}})}var $=null;function rn(e,t){return{wireLeaderHooks:t=>{o(async()=>{let{setSudoTrayDelegate:e}=await import(`./page-approval-service-Bbc3_KdK.js`);return{setSudoTrayDelegate:e}},__vite__mapDeps([52,12,18,14,1,4,15,13,16,17,19])).then(({setSudoTrayDelegate:e})=>e({shouldDelegate:()=>t.sync.shouldDelegateSudo(),requestApproval:e=>t.sync.delegateSudoApproval(e)})),$=e.agentHandle.onEvent(n=>{if(n.type===`turn_end`){let n=e.getSelectedJid();t.sync.notifyTurnEnd(n===`cone`?`SLICC`:n)}}),k(()=>Y(t)),De(()=>t.reset()),E(()=>t.sync.getSprinkleInstances()),e.sprinkleManager.setSendToSprinkleHook((e,n,r)=>t.sync.broadcastSprinkleUpdate(e,n,r)),e.sprinkleManager.setReloadHook(e=>t.sync.broadcastSprinkleReloaded(e)),e.getController()?.setOnLocalUserMessage((e,n,r)=>{t.sync.noteLeaderUserMessage(),t.sync.broadcastUserMessage(e,n,r)}),e.getController()?.setOnLocalProcessingChange(e=>t.sync.broadcastStatus(e?`processing`:`ready`)),o(async()=>{let{setThemeChangeListener:e,getActiveThemeId:t,getActiveThemeJson:n}=await import(`./theme-engine-By4GU_Wc.js`).then(e=>e.p);return{setThemeChangeListener:e,getActiveThemeId:t,getActiveThemeJson:n}},__vite__mapDeps([53,1,12])).then(({setThemeChangeListener:e,getActiveThemeId:n,getActiveThemeJson:r})=>{let i;e(e=>{n()!==`__preview`&&(clearTimeout(i),i=setTimeout(()=>t.sync.broadcastTheme(e),150))}),t.sync.broadcastTheme(r())}).catch(t=>e.log.error(`failed to install tray theme sync`,t))},clearLeaderHooks:()=>{o(async()=>{let{setSudoTrayDelegate:e}=await import(`./page-approval-service-Bbc3_KdK.js`);return{setSudoTrayDelegate:e}},__vite__mapDeps([52,12,18,14,1,4,15,13,16,17,19])).then(({setSudoTrayDelegate:e})=>e(null)),$?.(),$=null,k(null),A([]),E(null),D([]),De(null),e.getController()?.setOnLocalUserMessage(void 0),e.getController()?.setOnLocalProcessingChange(void 0),e.sprinkleManager.setSendToSprinkleHook(void 0),e.sprinkleManager.setReloadHook(void 0),t.disposeAll(),o(async()=>{let{setThemeChangeListener:e}=await import(`./theme-engine-By4GU_Wc.js`).then(e=>e.p);return{setThemeChangeListener:e}},__vite__mapDeps([53,1,12])).then(({setThemeChangeListener:e})=>{e(null)}).catch(t=>e.log.error(`failed to clear tray theme sync`,t))}}}function an(e){return{runtime:`slicc-hosted-leader`,kind:`hosted`,onLeaderReady:t=>{fetch(f(`/api/cloud-status`),{method:`POST`,headers:p({"content-type":`application/json`}),body:JSON.stringify({joinUrl:t.joinUrl,trayId:t.trayId,controllerUrl:t.controllerUrl,webhookUrl:t.webhookUrl,runtime:t.runtime,sliccVersion:`6.85.0`}),signal:AbortSignal.timeout(1e4)}).catch(t=>{e.log.error(`failed to POST /api/cloud-status`,{error:String(t)})})}}}function on(e,t,n,r,i){let{window:a,log:o}=e;if(e.runtimeMode===`hosted-leader`){a.localStorage.removeItem(x);let i=a.localStorage.getItem(b);if(!i){o.error(`hosted-leader: tray worker base URL not seeded`);return}t.leader=G({...n(i),...an(e)}),r(t.leader),Ve({log:o});return}let s=a.localStorage.getItem(x),c=a.localStorage.getItem(b);s?t.follower=S(Z(e,s,()=>t.follower?.currentSync??null)):c&&sn(c,e,t,n,r,i)}function sn(e,t,n,r,i,a){Kt({workerBaseUrl:e,lockManager:a,shouldLead:()=>!n.leader&&!n.follower&&t.window.localStorage.getItem(`slicc.trayWorkerBaseUrl`)===e,onGranted:t=>{n.lockRelease=t,n.leader=G(r(e)),i(n.leader)}})}function cn(e,t,n,r){let{window:i,log:a}=e;i.addEventListener(`slicc:tray-join`,r=>{let i=r.detail?.joinUrl;if(!i)return;let o=t.leader,s=t.lockRelease;t.leader=null,t.lockRelease=null,t.persistenceGuard.deactivate(),n();let c=t.follower;t.follower=null;try{o?.stop()}catch(e){a.error(`leader stop threw during tray-join switch`,e)}s?.();try{c?.stop()}catch(e){a.error(`previous follower stop threw during tray-join switch`,e)}try{t.follower=S(Z(e,i,()=>t.follower?.currentSync??null))}catch(e){a.error(`tray-join failed`,e)}}),i.addEventListener(`slicc:tray-leave`,e=>{let t=e;r({workerBaseUrl:t.detail?.workerBaseUrl??null,requestId:t.detail?.requestId}).catch(e=>a.error(`tray-leave failed`,e))}),i.addEventListener(`beforeunload`,()=>{t.persistenceGuard.deactivate(),t.leader?.stop(),t.follower?.stop(),t.lockRelease?.(),t.lockRelease=null},{once:!0})}async function ln(e){let{loadSprinkleStyles:t}=await o(async()=>{let{loadSprinkleStyles:e}=await import(`./legacy-styles-DcRu2WCJ.js`);return{loadSprinkleStyles:e}},__vite__mapDeps([54,4]));await t();let{client:n,instanceId:r,window:i,log:a}=e,s={leader:null,follower:null,persistenceGuard:new Fe,lockRelease:null},c=qt();Zt({window:i,getSync:()=>s.leader?.sync??null,refreshDynamicCatalogs:()=>Xt(a),log:a}),Qt({window:i,getSync:()=>s.leader?.sync??null});let l=typeof BroadcastChannel==`function`?new BroadcastChannel(te(r)):null,u=Wt({getSync:()=>s.leader?.sync??null,postEvent:e=>{let t={type:`panel-rpc-push`,op:`remote-cdp-event`,payload:e};l?.postMessage(t)}});n.setForwardLickHandler(e=>{let t=s.follower?.currentSync;t?t.forwardLick(e):a.warn(`forward-lick dropped: no active follower sync`)});let d=nn(e,s,u),{wireLeaderHooks:f,clearLeaderHooks:p}=rn(e,u);i.addEventListener(Ne,()=>{s.leader?.sync.broadcastSnapshot()});let m=async t=>{let{performTrayLeave:n}=await o(async()=>{let{performTrayLeave:e}=await import(`./tray-leave-runtime-BGfdX5KF.js`);return{performTrayLeave:e}},__vite__mapDeps([55,29,13,14,1,4,15,16,17,30])),r=()=>{s.leader||(s.lockRelease?.(),s.lockRelease=null)},l=n({workerBaseUrl:t.workerBaseUrl,requestId:t.requestId},{getLeader:()=>s.leader,setLeader:e=>{s.leader=e,e||s.persistenceGuard.deactivate()},getFollower:()=>s.follower,setFollower:e=>{s.follower=e},startLeader:e=>(s.lockRelease?.(),s.lockRelease=null,J(e,c).then(e=>{if(e.status===`granted`){if(!s.leader){e.release();return}s.lockRelease=e.release}}),G(d(e))),clearLeaderHooks:p,wireLeaderHooks:f,storage:i.localStorage,log:a});try{let t=await l;return s.follower||(e.refs.switcher.connection=`connected`),r(),t}catch(e){throw r(),e}};return await Be({instanceId:r,browser:e.browser,remoteCdpBridge:u,remoteCdpPushChannel:l,getLeader:()=>s.leader,performTrayLeaveLocally:m,window:i}),on(e,s,d,f,c),ie(e.refs.floatbar),ve(e=>{i.localStorage.setItem(`slicc.leaderTrayStatus`,JSON.stringify(e))}),i.localStorage.setItem(`slicc.leaderTrayStatus`,JSON.stringify(T())),de(e=>{i.localStorage.setItem(C,JSON.stringify(e))}),i.localStorage.setItem(C,JSON.stringify(fe())),A(Ae(),i.localStorage),cn(e,s,p,m),{getLeader:()=>s.leader,getFollower:()=>s.follower,scheduleScoopsListBroadcast:()=>s.leader?.scheduleScoopsListBroadcast(),performTrayLeaveLocally:m}}export{ln as wireWcTray};
|