sliccy 6.149.0 → 6.150.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.
Files changed (127) hide show
  1. package/dist/node-server/_shared/preview-url.d.ts.map +1 -1
  2. package/dist/node-server/_shared/preview-url.js +5 -3
  3. package/dist/node-server/_shared/preview-url.js.map +1 -1
  4. package/dist/ui/.vite/manifest.json +176 -176
  5. package/dist/ui/assets/SKILL-BXSAhY0E.js +133 -0
  6. package/dist/ui/assets/{SKILL-saWWhAfi.js → SKILL-DC91lupP.js} +1 -1
  7. package/dist/ui/assets/{account-store-CA1A4MNg.js → account-store-CLFiIEe9.js} +1 -1
  8. package/dist/ui/assets/{account-store-D5-EuwRH.js → account-store-FB6hD_og.js} +1 -1
  9. package/dist/ui/assets/{adobe-DV-vFrsP.js → adobe-C0SuhrNz.js} +1 -1
  10. package/dist/ui/assets/{adobe-DtbhCwKF.js → adobe-aiATKwYr.js} +1 -1
  11. package/dist/ui/assets/{agent-bridge-Bk8XJ8b8.js → agent-bridge-3cLsKfah.js} +1 -1
  12. package/dist/ui/assets/{agent-panels-DKzja1c3.js → agent-panels-riabOq_G.js} +1 -1
  13. package/dist/ui/assets/{apply-layout-y9wx9NT9.js → apply-layout-Bz6N8odC.js} +1 -1
  14. package/dist/ui/assets/{apps-yQbw27PS.js → apps-BxA4sLPb.js} +1 -1
  15. package/dist/ui/assets/{azure-openai-DHtO2E0K.js → azure-openai-DkH6LhzR.js} +1 -1
  16. package/dist/ui/assets/{azure-openai-yibXp_Bz.js → azure-openai-hlwpTQ2A.js} +1 -1
  17. package/dist/ui/assets/{budget-usage-source-CsYOdKgf.js → budget-usage-source-D6zuo6Hu.js} +1 -1
  18. package/dist/ui/assets/{cdp-DvBgKWeM.js → cdp-DJGttMQn.js} +1 -1
  19. package/dist/ui/assets/{cerebras-CS6Db07O.js → cerebras-CUNK2jZM.js} +1 -1
  20. package/dist/ui/assets/{cerebras-CaDy2asW.js → cerebras-DBQ1bv38.js} +1 -1
  21. package/dist/ui/assets/{composer-speech-DPiVvFU6.js → composer-speech-BFUPGTEu.js} +1 -1
  22. package/dist/ui/assets/{connect-surface-DZZV0bKb.js → connect-surface-D_kgCGp2.js} +1 -1
  23. package/dist/ui/assets/{directed-approval-zgdk1qJY.js → directed-approval-EWvnA53r.js} +1 -1
  24. package/dist/ui/assets/{fs-CeHAWOzG.js → fs-BExiqsiJ.js} +2 -2
  25. package/dist/ui/assets/{fs-ZsGKH6_S.js → fs-Cc9eDq3V.js} +1 -1
  26. package/dist/ui/assets/{github-EHGL5L1f.js → github-BY2Hef8-.js} +2 -2
  27. package/dist/ui/assets/{github-CaKl6IqQ.js → github-BsO9qBMX.js} +1 -1
  28. package/dist/ui/assets/{github-copilot-BHsKQLD0.js → github-copilot-BL5LC-w9.js} +1 -1
  29. package/dist/ui/assets/{github-copilot-Cjxeuomt.js → github-copilot-DYeNaU6e.js} +1 -1
  30. package/dist/ui/assets/{github-install-CZ0EukOV.js → github-install-BTMb6Eqq.js} +1 -1
  31. package/dist/ui/assets/{github-zip-CS4YNRru.js → github-zip-fcV1ZI6K.js} +1 -1
  32. package/dist/ui/assets/{hear-Cbevfmh3.js → hear-ZHJ-907t.js} +1 -1
  33. package/dist/ui/assets/{help-B7QDR4Te.js → help-DhWsyOhV.js} +1 -1
  34. package/dist/ui/assets/{js-realm-worker-8iSCqCPx.js → js-realm-worker-DZArxACB.js} +1 -1
  35. package/dist/ui/assets/{kernel-worker-C_WWxLV9.js → kernel-worker-2JqW5-by.js} +92 -85
  36. package/dist/ui/assets/lick-urls-HYeTtmbf.js +1 -0
  37. package/dist/ui/assets/{lick-ws-bridge-DlghqmSh.js → lick-ws-bridge-BlInST5r.js} +1 -1
  38. package/dist/ui/assets/{lick-ws-bridge-BbfNnO1f.js → lick-ws-bridge-DqmithfF.js} +1 -1
  39. package/dist/ui/assets/{local-llm-0LkBgtj2.js → local-llm-BB5WjVB9.js} +1 -1
  40. package/dist/ui/assets/{local-llm-Dr2UbIXv.js → local-llm-DcnAyJLX.js} +1 -1
  41. package/dist/ui/assets/{main-BAC0OCne.js → main-DbmhUBke.js} +3 -3
  42. package/dist/ui/assets/{main-cherry-CewPDwbT.js → main-cherry-CizWgCog.js} +1 -1
  43. package/dist/ui/assets/{memory-curation-seam-Dhr-Lh0Q.js → memory-curation-seam-DPw-uMRg.js} +1 -1
  44. package/dist/ui/assets/{mount-C-ANRQIp.js → mount-C4Dcf141.js} +1 -1
  45. package/dist/ui/assets/{mount-BLSZhkn-.js → mount-C4r5pcZ6.js} +3 -3
  46. package/dist/ui/assets/{mount-recovery-DUczfSWq.js → mount-recovery-BvMNCrP1.js} +1 -1
  47. package/dist/ui/assets/{new-session-BoS7dRsh.js → new-session-B8mQOTMk.js} +2 -2
  48. package/dist/ui/assets/{oauth-bootstrap-Bxgy2Cqv.js → oauth-bootstrap-Bssxvnj9.js} +2 -2
  49. package/dist/ui/assets/{onboarding-orchestrator-Dk1ohi_0.js → onboarding-orchestrator-BTy-2rjb.js} +1 -1
  50. package/dist/ui/assets/{openai-codex-BknfgoBF.js → openai-codex-C1PBtm8V.js} +1 -1
  51. package/dist/ui/assets/{openai-codex-DMzQdrNm.js → openai-codex-rd_p0one.js} +1 -1
  52. package/dist/ui/assets/{openrouter-CRaR6ORa.js → openrouter-BJIIR9g5.js} +1 -1
  53. package/dist/ui/assets/{openrouter-CQPRB3mI.js → openrouter-DVjN51Bu.js} +1 -1
  54. package/dist/ui/assets/{openrouter-free-CKjfWow9.js → openrouter-free-1EVH-oJw.js} +1 -1
  55. package/dist/ui/assets/{openrouter-free-BCZac4lk.js → openrouter-free-CU-iItiG.js} +1 -1
  56. package/dist/ui/assets/{openrouter-oauth-DZ-Abl0n.js → openrouter-oauth-CHusQ8ye.js} +1 -1
  57. package/dist/ui/assets/{openrouter-oauth-DQ6_4qbW.js → openrouter-oauth-Da-6Oq0D.js} +1 -1
  58. package/dist/ui/assets/panel-rpc-handlers-Ch4Behyn.js +2 -0
  59. package/dist/ui/assets/{panelize-shell-BExnoycZ.js → panelize-shell-C0m6TyBn.js} +1 -1
  60. package/dist/ui/assets/{provider-CHJuS3Eo.js → provider-BPE-djCs.js} +2 -2
  61. package/dist/ui/assets/{provider-Ccwke1Gk.js → provider-M-0eEmke.js} +1 -1
  62. package/dist/ui/assets/provider-settings-Vnae44M1.js +1 -0
  63. package/dist/ui/assets/provider-store-access-DD87rc3B.js +1 -0
  64. package/dist/ui/assets/provider-store-access-JCVbVn4R.js +1 -0
  65. package/dist/ui/assets/{providers-BYl2eNQm.js → providers-DDqVLz05.js} +1 -1
  66. package/dist/ui/assets/{providers-Dx2Bx5aE.js → providers-Dq0px1q5.js} +2 -2
  67. package/dist/ui/assets/{quick-llm-DT2lt16M.js → quick-llm-CPEd0yPp.js} +1 -1
  68. package/dist/ui/assets/{recovery-screen-BjiUo-AL.js → recovery-screen-DHlUCruV.js} +1 -1
  69. package/dist/ui/assets/{run-DLgsQ07W.js → run-C03Ay2Z7.js} +1 -1
  70. package/dist/ui/assets/{run-BtmtVfUW.js → run-Ct4a1SOJ.js} +1 -1
  71. package/dist/ui/assets/{run-BxzwgwS3.js → run-FWploF5d.js} +2 -2
  72. package/dist/ui/assets/{session-jsonl-BigzXvfg.js → session-jsonl-B6NACdIo.js} +1 -1
  73. package/dist/ui/assets/{setup-feature-flags-remote-Ca2-hqlo.js → setup-feature-flags-remote-CUAqKOVK.js} +1 -1
  74. package/dist/ui/assets/sidecar-repair-DFADpBRH.js +1 -0
  75. package/dist/ui/assets/{silent-renew-backoff-BHjNTQU2.js → silent-renew-backoff-CmODQQqt.js} +1 -1
  76. package/dist/ui/assets/{skills-CJ8qNnZs.js → skills-BUpWgkUH.js} +1 -1
  77. package/dist/ui/assets/slicc-version-BSblY8aE.js +1 -0
  78. package/dist/ui/assets/{snapshot-DGK3m0L_.js → snapshot-1vOpGcO0.js} +1 -1
  79. package/dist/ui/assets/{snapshot-features-DluhSLEH.js → snapshot-features-_N-rE3pl.js} +1 -1
  80. package/dist/ui/assets/{soundscape-BK9WmnUG.js → soundscape-0en207GO.js} +1 -1
  81. package/dist/ui/assets/{speak-DZISsPxk.js → speak-_rLrkLgU.js} +1 -1
  82. package/dist/ui/assets/{sprinkle-manager-BCrGJ7_g.js → sprinkle-manager-DcJJcpU8.js} +1 -1
  83. package/dist/ui/assets/{sprinkle-renderer-D-1PliuW.js → sprinkle-renderer-D3FHwzp3.js} +1 -1
  84. package/dist/ui/assets/{state-KlJITKEj.js → state-BURn7jMK.js} +1 -1
  85. package/dist/ui/assets/{store-Bfm_2de6.js → store-BR5AolDe.js} +1 -1
  86. package/dist/ui/assets/{store-C4pwV1r3.js → store-HMh9Lk9i.js} +1 -1
  87. package/dist/ui/assets/{sudo-ClTWT5F4.js → sudo-HC-PPt3W.js} +1 -1
  88. package/dist/ui/assets/{sync-dialog-Dlmp9or_.js → sync-dialog-CjOSIYTL.js} +1 -1
  89. package/dist/ui/assets/{transformers-env-CKztDfUT.js → transformers-env-Cp_6LEw_.js} +1 -1
  90. package/dist/ui/assets/tray-leader-BmmfZ-wo.js +1 -0
  91. package/dist/ui/assets/{tray-sidecar-izQ2ZF5D.js → tray-sidecar-C58V0O9z.js} +1 -1
  92. package/dist/ui/assets/{upgrade-detection-CNPzRkE7.js → upgrade-detection-D9YglioG.js} +1 -1
  93. package/dist/ui/assets/{voice-reply-JlXeQN7_.js → voice-reply-BZZxlsn0.js} +1 -1
  94. package/dist/ui/assets/{wc-attach-Cl4Hwieg.js → wc-attach-BlsSvdoI.js} +2 -2
  95. package/dist/ui/assets/{wc-extension-ChMc6MeX.js → wc-extension-h0B2v7jl.js} +2 -2
  96. package/dist/ui/assets/{wc-follower-CvdBVpCG.js → wc-follower-BrT0nSWH.js} +3 -3
  97. package/dist/ui/assets/{wc-follower-oauth-C83SZJty.js → wc-follower-oauth-ldrlDvsz.js} +1 -1
  98. package/dist/ui/assets/{wc-gelatiere-3y6MXjH6.js → wc-gelatiere-BuetYYQ6.js} +1 -1
  99. package/dist/ui/assets/{wc-live-xtrWHFoh.js → wc-live-BdztSz08.js} +5 -5
  100. package/dist/ui/assets/{wc-nav-CDS_UeWj.js → wc-nav-Cp_gz-jE.js} +2 -2
  101. package/dist/ui/assets/{wc-onboarding-DqB8019g.js → wc-onboarding-CL2TlWps.js} +2 -2
  102. package/dist/ui/assets/{wc-placeholder-CZw2rZaI.js → wc-placeholder-DMvwda2Y.js} +3 -3
  103. package/dist/ui/assets/{wc-secret-request-CP500uCX.js → wc-secret-request-BocSAQbJ.js} +1 -1
  104. package/dist/ui/assets/{wc-settings-yS0Tn1rR.js → wc-settings-c6zuyeIz.js} +3 -3
  105. package/dist/ui/assets/{wc-shell-CuK7bTlD.js → wc-shell-CNx2tU3J.js} +3 -3
  106. package/dist/ui/assets/{wc-shortcut-config-C-lIC8ic.js → wc-shortcut-config-CmsfFHRi.js} +1 -1
  107. package/dist/ui/assets/{wc-shortcuts-DsrVa-7o.js → wc-shortcuts-p6BtQ0R3.js} +1 -1
  108. package/dist/ui/assets/{wc-sprinkles-CWvQ1c_3.js → wc-sprinkles-CXRTNH8y.js} +2 -2
  109. package/dist/ui/assets/{wc-transcript-export-BIlHmS1O.js → wc-transcript-export-CbYm5pR2.js} +2 -2
  110. package/dist/ui/assets/{wc-tray-PhDRuhzo.js → wc-tray-j9M1XqGl.js} +4 -4
  111. package/dist/ui/assets/welcome-detection-Bu8Zf41r.js +1 -0
  112. package/dist/ui/assets/{whisper-session-B0UflXuX.js → whisper-session-DPNk8OqX.js} +2 -2
  113. package/dist/ui/assets/{xai-grok-C_IBpHs8.js → xai-grok-BEIq12AG.js} +1 -1
  114. package/dist/ui/assets/{xai-grok-k1KZairZ.js → xai-grok-BQrSjOw1.js} +1 -1
  115. package/dist/ui/index.html +3 -3
  116. package/dist/ui/packages/webapp/index.html +3 -3
  117. package/package.json +1 -1
  118. package/dist/ui/assets/SKILL-DA3Jh760.js +0 -1
  119. package/dist/ui/assets/lick-urls-CadwTNxP.js +0 -1
  120. package/dist/ui/assets/panel-rpc-handlers-l_wby7rY.js +0 -2
  121. package/dist/ui/assets/provider-settings-C9aYrpFT.js +0 -1
  122. package/dist/ui/assets/provider-store-access-Bvoy_8oD.js +0 -1
  123. package/dist/ui/assets/provider-store-access-C2g47uIb.js +0 -1
  124. package/dist/ui/assets/sidecar-repair-wcIxeWMP.js +0 -1
  125. package/dist/ui/assets/slicc-version-PYnMeU2R.js +0 -1
  126. package/dist/ui/assets/tray-leader-CDhsXeeJ.js +0 -1
  127. package/dist/ui/assets/welcome-detection-DocFcHWj.js +0 -1
@@ -0,0 +1,133 @@
1
+ var e=`---
2
+ name: automation
3
+ description: |
4
+ Use this when setting up event-driven automation in SLICC — webhooks, cron
5
+ tasks, or filesystem watchers that route events to a scoop or cone. Covers
6
+ \`webhook\`,
7
+ \`crontask\`, and \`fswatch\` shell commands. Read this BEFORE wiring up anything
8
+ that should fire on a schedule, an HTTP call, or a VFS change.
9
+ allowed-tools: bash
10
+ ---
11
+
12
+ # Automation: webhooks, cron, filesystem watchers
13
+
14
+ SLICC's automation primitives turn external or VFS-internal events into **licks** — messages routed to a work unit. Three shell commands set them up:
15
+
16
+ | Command | Trigger | Use case |
17
+ | ---------- | ---------------------------- | --------------------------------- |
18
+ | \`webhook\` | Inbound HTTP request | Callbacks from external services |
19
+ | \`crontask\` | Cron schedule | Recurring background work |
20
+ | \`fswatch\` | VFS create / modify / delete | React to authored content changes |
21
+
22
+ All three take \`--scoop <target>\`, which names **a unit, not a species**: a scoop name, a cone name, or a folder (\`cone-<slug>\`, \`<name>-scoop\`). Omit it and events come back to whichever unit you are — the cone you are in, or the scoop itself if you are one. A target naming no live unit is **refused at create time** (exit 1, listing the valid targets) — create the scoop first, then register the webhook / cron task / watcher against it. Events are never re-routed when a target disappears; stable-home webhook deliveries remain queued as described below.
23
+
24
+ **If you want your own events, omit \`--scoop\` — never hardcode \`cone\`.** All three commands behave identically here, so omitting the flag is always available, and it works the same whether you are a cone or a scoop. The literal folder \`cone\` is not a synonym for "me": it belongs to whichever cone currently holds it, and it is handed to the next new cone after the original one is dropped. A skill that hardcodes it delivers its callbacks into another cone's chat in exactly the multi-cone workspaces where the target matters.
25
+
26
+ A stable \`/wh/\` webhook's \`202\` means **durably accepted**, not that agent work finished.
27
+ The home queues before forwarding, including while no leader is connected. It preserves
28
+ FIFO within each webhook ID, removing an event after explicit delivery/filter acknowledgement,
29
+ registration revocation, or bounded explicit rejection. Delivery is at-least-once:
30
+ make downstream side effects safe to retry. An explicitly missing registration or unresolved
31
+ target gets three consecutive rejection attempts at least 30 seconds apart before becoming a
32
+ terminal dead letter. Other webhook IDs can proceed during that backoff. Repair the registration
33
+ during the grace period to deliver normally. Ambiguous/transient outcomes stay queued without a
34
+ terminal budget and reset the rejection streak. The operator-only archive retains the latest
35
+ 100 terminal receipts with original payloads and a lifetime outcome counter; older terminal
36
+ details are replaced, not pending events. There is no automatic replay of terminal outcomes.
37
+ \`202\` is acceptance, not guaranteed eventual delivery.
38
+ Accepted events are never evicted or aged out. Limits are 100 events, 120 KiB encoded
39
+ home storage, 64 KiB per body and eight pending home requests. \`429 WEBHOOK_QUEUE_FULL\`
40
+ or \`WEBHOOK_HOME_BUSY\` means retry after 30 seconds; \`413\` means reduce the body.
41
+ Blocked replay retries by durable alarm after 30 seconds; successful replay continues
42
+ backlog after one second. Home admission expires after 90 days without rebind, not an
43
+ event-retention TTL.
44
+
45
+ Stable URLs survive tray resets without redirects. Local-only/legacy delivery is not
46
+ this durable queue: it can report \`404 WEBHOOK_NOT_REGISTERED\`,
47
+ \`422 WEBHOOK_TARGET_UNRESOLVED\` or \`410 NO_LIVE_LEADER\` directly. Old tray-scoped
48
+ URLs may return \`308 TRAY_SUPERSEDED\` plus \`Location\`; configure senders to follow
49
+ POST redirects if still using them. Retry transient failures, not permanent revocation.
50
+
51
+ The stable URL's \`coneId\` is the **leader-session lineage**, shared by its WorkUnits,
52
+ not a per-agent cone security boundary. Tray reset preserves this identity and its
53
+ private management credentials across failed attempts and reloads. A reset that cannot
54
+ complete required transfer work fails rather than silently replacing a stable URL;
55
+ retry it to resume the same replacement. Management credentials are never available
56
+ through the agent filesystem, public tray status, or followers.
57
+ If the replacement expired while offline, recovery replaces it only when the hub proves
58
+ transfer never started. Otherwise it finishes the same frozen transfer, then moves from
59
+ that expired owner to a fresh tray. Do not erase private state to bypass a pending reset.
60
+
61
+ ## \`webhook\`
62
+
63
+ Receive HTTP callbacks. The lick carries the request method, path, headers, and body; \`create\` allocates a path and prints the URL.
64
+
65
+ \`\`\`bash
66
+ webhook create --scoop pr-watcher --name gh-prs
67
+ webhook create --scoop Research --name inbox # a cone, by name
68
+ webhook create --name inbox # your own cone
69
+ webhook list && webhook delete wh-1
70
+ \`\`\`
71
+
72
+ If a delivery URL leaks, run \`webhook rotate\` on the connected leader, then
73
+ \`webhook list\` and update every external sender. Rotation freshly randomizes both delivery
74
+ and private management secrets for **all** webhooks, not an individual ID; the cone identity,
75
+ webhook registrations, and queued events stay intact. Old URLs and old management secrets
76
+ stop authenticating new operations.
77
+ The command prints no capability. A lost response or transient failure preserves an
78
+ idempotent retry intent, replayed before reconnect. A definitive refusal (for example,
79
+ an old tab's \`403\` after another tab reset the tray) drops the rejected intent instead
80
+ of blocking every later start. Reconnect before requesting a new rotation; newer
81
+ identity state from another tab is never replaced with the refused operation's secret.
82
+ \`webhook rotate --help\` never rotates. This needs a stable tray home and the
83
+ leader panel RPC (standalone or hosted extension leader), not a local-only URL.
84
+
85
+ \`webhook delete <id>\` permanently revokes that stable-home registration before
86
+ removing its local definition. Valid-secret deliveries then return permanent
87
+ \`410 WEBHOOK_REVOKED\`; queued events for that ID are discarded, never replayed.
88
+ If revocation fails, the definition stays intact: reconnect the leader and retry
89
+ the same delete. Local-only and legacy registrations retain local deletion.
90
+ \`webhook delete <id> --help\` has no side effects.
91
+
92
+ Flags:
93
+
94
+ - \`--scoop <target>\` — scoop name, cone name, or folder. Omit for your own cone.
95
+ - \`--name <label>\` — label shown in \`webhook list\`.
96
+ - \`--filter <js>\` — JS expression per request; falsy drops the event before the agent sees it.
97
+
98
+ ## \`crontask\`
99
+
100
+ Run on a cron schedule. Standard 5-field cron (minute hour day month weekday).
101
+
102
+ \`\`\`bash
103
+ crontask create --cron "0 * * * *" --scoop hourly-summary --name hourly
104
+ crontask create --cron "0 9 * * *" --name digest # your own cone
105
+ crontask list && crontask delete ct-1 # \`kill\` is an alias for \`delete\`
106
+ \`\`\`
107
+
108
+ Flags:
109
+
110
+ - \`--cron <expr>\` — required; 5-field cron expression.
111
+ - \`--scoop <target>\` — scoop name, cone name, or folder. Omit for your own cone.
112
+ - \`--name <label>\` — label.
113
+ - \`--filter <js>\` — JS expression evaluated each tick; falsy skips that fire.
114
+
115
+ ## \`fswatch\`
116
+
117
+ Watch a VFS path; deliver a lick when a matching file is created, modified, or deleted.
118
+
119
+ \`\`\`bash
120
+ fswatch create --path /workspace --pattern "*.md" --scoop doc-watcher --name md-changes
121
+ fswatch create --path /workspace/src --pattern "*.ts" # your own cone
122
+ fswatch list && fswatch delete fsw-1
123
+ \`\`\`
124
+
125
+ Events carry the change type (\`create\`, \`modify\`, \`delete\`) and the path.
126
+
127
+ ## Don't
128
+
129
+ - Don't poll on a \`crontask\` for work the cone could do reactively. Cron is for genuinely recurring jobs (digests, refreshes); reactive work belongs on \`fswatch\`/\`webhook\`.
130
+ - Don't leave watchers/webhooks/crons orphaned. Stable-home webhooks with missing targets retry briefly, then dead-letter; repair them promptly or use \`... list\` and \`... delete\` to clean up. Other trigger licks are dropped, never re-routed.
131
+ - Don't register against a scoop you have not created yet. \`--scoop\` is resolved when you create the entry, so a forward reference exits 1; run \`scoop_scoop create <name>\` first.
132
+ - Don't fan one trigger out to N near-identical entries. Register once, let the receiver dispatch.
133
+ `;export{e as default};
@@ -1 +1 @@
1
- var e="---\nname: playwright-cli\ndescription: |\n Use this whenever the user asks to browse, navigate, click, fill a form,\n scrape, take a screenshot, or otherwise interact with a web page. SLICC drives\n the browser through the `playwright-cli` shell command (also aliased as\n `playwright` and `puppeteer`). Read this BEFORE running any browser\n automation: every tab-operating command requires a `--tab` target id, and\n multi-agent tab handling has rules you must follow.\nallowed-tools: bash\n---\n\n# Browser Automation via playwright-cli\n\nUse `playwright-cli` (also aliased as `playwright` and `puppeteer`) via the bash tool for all browser automation.\n\n**Every tab-operating command requires `--tab=<targetId>`.** There is no implicit \"current tab\". Always specify which tab you're operating on.\n\n`playwright-cli <command> --help` prints that command's usage and does nothing else — safe to run before any action.\n\n## Quick Start\n\n```bash\n# 1. Open a page — note the targetId in the output\nplaywright-cli open https://example.com\n# Output: Opened https://example.com in new tab [targetId: E9A3F...]\n\n# 2. Take a snapshot to see the page structure and get element refs\nplaywright-cli snapshot --tab=E9A3F\n\n# 3. Interact using refs from the snapshot (e.g. e5, e12)\nplaywright-cli click --tab=E9A3F e5\nplaywright-cli fill --tab=E9A3F e12 \"hello world\"\n\n# 4. Re-snapshot after interactions (refs change)\nplaywright-cli snapshot --tab=E9A3F\n```\n\n## Tab IDs\n\n- `tab-list` shows all tabs with their targetIds. The user's active tab is marked `(active)`.\n- `tab-new` / `open` return the new tab's targetId — capture it for subsequent commands.\n- Use `--tab=<targetId>` on ALL commands that operate on a tab.\n\n## Frame IDs\n\n- `frames --tab=<targetId>` lists frame IDs. A frame ID is not a tab target ID; never pass it to `--tab`.\n- Use `--tab=<targetId> --frame=<frameId>` with `eval`, `eval-file`, or `snapshot` to target a child frame, including cross-origin frames.\n- A frame-scoped `snapshot` prints only that frame's accessibility subtree. Its frame-prefixed refs work with `click`, `fill`, `dblclick`, `hover`, `select`, `check`, and `uncheck`; do not pass `--frame` to those commands. Other ref commands require refs from a top-level snapshot.\n\n## Common Failure Modes\n\n- `--tab <targetId> is required` — you forgot `--tab=<id>`. Run `tab-list` to get IDs.\n- `is a frame ID, not a tab target ID` — keep the owning tab's targetId in `--tab` and pass the frame ID with `--frame`.\n- `No snapshot available` — run `snapshot --tab=<id>` before using refs.\n- `unknown flag \"--x\"` / `unexpected argument \"y\"` — every subcommand rejects arguments it does not\n support, so an exit code of 0 means everything you passed was honoured. Check `<verb> --help`.\n- For free-text payloads that start with `-` (e.g. `fill`/`type`/`eval`), put `--` before the text:\n `fill --tab=<id> e1 -- --dash-looking`.\n- `is not an element ref` — a screenshot's positional is a main-frame element ref (`e5`); the output\n path is `--filename=<path>`. Frame-prefixed refs (`f1e5`) clip only with `click`-family commands.\n- Refs are tied to **one tab + one snapshot**. They do not carry across tabs, navigations, or reloads.\n\n## Element Refs\n\nSnapshots assign short ref IDs (`e1`, `e2`, ...) to interactive elements. Use these refs with `click`, `fill`, `dblclick`, `hover`, `select`, `check`, `uncheck`, `drag`, `upload`, `drop`, and `screenshot`.\n\nRefs are invalidated after any state-changing command. Always re-snapshot to get fresh refs.\n\n## Commands\n\nAll commands below that operate on a tab require `--tab=<targetId>`.\n\n### Core\n\n```bash\nplaywright-cli open [url] [--foreground] [--mobile] # Open tab (background by default), returns targetId\nplaywright-cli tab-new [url] [--foreground] [--mobile] # Same as open\nplaywright-cli tab-close --tab=<id> # Close tab (alias: close)\nplaywright-cli goto --tab=<id> <url> # Navigate tab\nplaywright-cli navigate --tab=<id> <url> # Alias for goto\nplaywright-cli snapshot --tab=<id> [--frame=<frameId>] [--no-iframes] [--filename=path] [--depth=<n>] [--boxes] # Tab tree or one frame subtree; --depth limits nesting, --boxes adds [box=x,y,w,h] rects\nplaywright-cli find --tab=<id> <text> # Search the snapshot for text (case-insensitive), returns matching lines + context\nplaywright-cli find --tab=<id> --regex=<re> # Same, with a regexp (use either text or --regex, not both)\nplaywright-cli eval --tab=<id> [--frame=<frameId>] <expression> [--filename=path|--output=path] # Evaluate JS in a tab/frame, incl. top-level await/return; use `--` before an expression that starts with `-`\nplaywright-cli eval-file --tab=<id> [--frame=<frameId>] <vfs-path> [--output=path|--filename=path] # Evaluate JS from a VFS file in a tab/frame (top-level await/return supported)\nplaywright-cli frames --tab=<id> # List frame IDs for --frame (not --tab)\nplaywright-cli resize --tab=<id> <width> <height> # Resize viewport\n```\n\n`--foreground` (or `--fg`) opens the new tab **in the foreground** — it brings the\nnew tab to the front and switches the user's visible/active tab to it, instead of\nopening in the background.\n\n**Bringing a tab to the foreground (activate / focus / raise / switch to a tab):**\n\n- **New tab** → `open <url> --foreground` (or `tab-new <url> --fg`).\n- **Existing tab** → `tab-select <index>` (1-based index from `tab-list`).\n\n`--mobile` opens the tab with generic mobile-device emulation (viewport,\ndevice pixel ratio, touch, Android Chrome UA), sticky for the tab's lifetime —\na later `resize` changes only the dimensions and keeps the mobile identity.\nMobile pages are usually lighter, which saves tokens.\n\nThese two are the ONLY ways to change which tab is in front. There is no\n`activate`, `bring-to-front`, or `focus` subcommand, and `eval`-ing\n`window.focus()` does NOT work (browsers block a page from stealing foreground).\nIf a tab didn't come to the front, re-run `tab-select` / `--foreground` — do not\nfall back to `window.focus()`.\n\n### Interaction\n\n```bash\nplaywright-cli click --tab=<id> <ref> [--modifiers=Shift,Control,Alt,Meta] # Click element\nplaywright-cli dblclick --tab=<id> <ref> [button] [--modifiers=...] # Double-click\nplaywright-cli fill --tab=<id> <ref> <text> [--submit] # Clear input + type text (--submit presses Enter); use `--` before text that starts with `-`\nplaywright-cli type --tab=<id> <text> [--submit] # Type into focused element (--submit presses Enter); use `--` before text that starts with `-`\nplaywright-cli hover --tab=<id> <ref> # Hover over element\nplaywright-cli select --tab=<id> <ref> <value> # Select dropdown value\nplaywright-cli check --tab=<id> <ref> # Check checkbox/radio\nplaywright-cli uncheck --tab=<id> <ref> # Uncheck checkbox/radio\nplaywright-cli drag --tab=<id> <startRef> <endRef> # Drag and drop\nplaywright-cli upload --tab=<id> [ref] <file> [file...] # Upload VFS files to file input as raw bytes (optional snapshot ref targets hidden inputs)\nplaywright-cli drop --tab=<id> <ref> [--path=<vfs-path>] [--data=<mime/type=value>] # Drop files/data onto element (--path drops raw bytes)\nplaywright-cli dialog-accept --tab=<id> [text] # Accept JS dialog\nplaywright-cli dialog-dismiss --tab=<id> # Dismiss JS dialog\n```\n\n### Keyboard\n\n```bash\nplaywright-cli press --tab=<id> <key> # Press key (keyDown + keyUp, e.g. Enter, Tab, Escape)\nplaywright-cli keydown --tab=<id> <key> # Hold key down (no paired keyUp)\nplaywright-cli keyup --tab=<id> <key> # Release held key (no paired keyDown)\n```\n\n### Mouse\n\n```bash\nplaywright-cli mousemove --tab=<id> <x> <y> # Move mouse to coordinates (negative coords ok, e.g. -10 20)\nplaywright-cli mousedown --tab=<id> [button] # Press mouse button (left/right/middle, default: left)\nplaywright-cli mouseup --tab=<id> [button] # Release mouse button\nplaywright-cli mousewheel --tab=<id> <dx> <dy> # Scroll mouse wheel (negative deltas ok, e.g. 0 -300)\n```\n\n### Navigation\n\n```bash\nplaywright-cli go-back --tab=<id> # history.back()\nplaywright-cli go-forward --tab=<id> # history.forward()\nplaywright-cli reload --tab=<id> # Reload page\n```\n\n### Teleport\n\n```bash\nplaywright-cli teleport --tab=<id> --start=<regex> --return=<regex> [--timeout=<s>]\nplaywright-cli teleport --list # List available follower runtimes\nplaywright-cli teleport --off --tab=<id> # Cancel a teleport on this tab\nplaywright-cli open <url> --teleport-start=<regex> --teleport-return=<regex>\nplaywright-cli goto --tab=<id> <url> --teleport-start=<regex> --teleport-return=<regex>\n```\n\nTeleport is for leader/follower tray auth handoffs. Scoped to a specific tab — only commands targeting the teleporting tab are blocked; other tabs remain operational.\n\n`--runtime` is optional: without it, teleport picks the most recently active eligible follower (preferring standalone floats). Only followers that can actually serve cookies are eligible — cherry hosts, exec-only CLI followers, and any target advertising `network: false` are excluded, so a teleport fails fast instead of \"succeeding\" with zero cookies.\n\n### Screenshots\n\n```bash\nplaywright-cli screenshot --tab=<id> # Save to $TMPDIR/screenshot-<ts>.png\nplaywright-cli screenshot --tab=<id> --filename=page.png # Save to custom path\nplaywright-cli screenshot --tab=<id> e5 # Clip to an element (positional = MAIN-FRAME ref, not a path)\nplaywright-cli screenshot --tab=<id> --fullPage # Full scrollable page (alias: --full-page)\nplaywright-cli screenshot --tab=<id> --max-width=800 # Downscale to a max width (png output only)\nplaywright-cli screenshot --tab=<id> --type=jpeg # png (default) / jpeg / webp; inferred from --filename extension\nplaywright-cli screenshot --tab=<id> --hires # Capture in device pixels (honors device pixel ratio)\n```\n\nAn element screenshot (`screenshot e5`) returns **that element's crop or fails**\n(exit 1) — typically because the snapshot went stale after a navigation or\nlayout change. Re-run `snapshot` and retry with a fresh ref; it never silently\nsubstitutes a full-viewport frame.\n\nA `resize` sticks to its tab: the viewport override is re-applied automatically\nwhenever the tab is re-attached, so another driver switching tabs cannot reset\nit.\n\nAll playwright-cli commands share one browser, and locking is **per tab**:\ncommands on different tabs run in parallel; commands on the same tab serialize.\nA slow or hung navigation stalls only its own tab. A few genuinely global\noperations (`tab-select`, `--foreground`, and the attach that points the bridge\nat a tab) still take a bridge-wide lock, but they are short and never wrap a\npage wait. When callers queue up, commands may emit a\n`note: browser bridge contended — ...` line on stderr with the total lock wait\nand queue depth; the note says whether the wait was on **this tab** or\n**bridge-wide**. Either way it is back-off guidance — stagger callers or give\neach one its own tab, never re-run the command; it already ran, it was just\nslow to get the lock.\n\n**Giving up cancels the command.** When your `bash` call stops waiting — the\nturn is cancelled, `timeout` fires, or someone runs `kill <pid>` — the\nplaywright-cli command is cancelled too instead of running on for a caller that\nis gone: a queued command drops out of the tab's queue without taking the lock,\na `goto` waiting on a load event and a `waitForSelector` poll stop at once, and\na multi-step command stops before its next CDP round trip. Such a command exits\n**130** with a stderr line naming the step it stopped at, never 0.\n\nTwo consequences for you:\n\n- A cancelled command may have **half-landed**. The CDP request already on the\n wire cannot be recalled, so keys may be typed or a click delivered before the\n stop. `snapshot` the tab and continue from what you see rather than blindly\n re-running — same rule as a mid-command session reset.\n- `background_after` alone does **not** cancel; it detaches, and the command\n keeps running as a background job (that is what makes a long `goto` usable).\n Use `timeout` or `kill <pid>` when you actually want it stopped.\n\n**Stale session.** The bridge re-attaches automatically after a Chrome reset;\nthere is no need to reload the tab or open a new one. Two error shapes:\n\n- `Session with given id not found` — the bridge already re-attached; re-run\n the command.\n- `… was reset mid-command … the outcome is unknown` — part of the command may\n have landed (keys typed, a click delivered) before the session died. Do NOT\n blindly re-run it: `snapshot` the tab first and continue from what you see.\n\n### Save As\n\n```bash\nplaywright-cli pdf --tab=<id> [--filename=path] # Save page as PDF (not available in extension mode)\n```\n\n### Viewing pages and screenshots yourself\n\nThe browser displays things to the human; `open --view` is what lets _you_ see them. **But viewing screenshots is a last resort for the cone — every image you load eats a large chunk of the context window** (a single 1280×800 PNG can run 1500+ tokens, full-page screenshots much more). Reach for cheaper signals first:\n\n1. **`playwright-cli snapshot --tab=<id>`** — text accessibility tree. Use this first; it answers \"what's on the page\" for almost all verification tasks at a tiny fraction of the token cost. On a big page, `find --tab=<id> <text>` greps the snapshot and returns just the matching lines with context, and `snapshot --depth=<n>` caps the tree — both much cheaper than the full tree.\n2. **`eval` against the DOM** — when you need a specific value (`document.title`, an attribute, computed style), `eval` it. Don't screenshot for facts you can extract.\n3. **Delegate visual inspection to a scoop.** If the cone genuinely needs vision (layout regression, render fidelity, \"does this look right\"), spawn a scoop to take and view the screenshot — the scoop's context absorbs the tokens, and you receive its summary back. The cone's window stays clean for orchestration.\n4. **`open --view` in the cone** — only when the cone itself must see pixels for its current decision and steps 1–3 won't do.\n\n**What you CAN see:**\n\n- `open --view <path>` — reads an image from the VFS and returns it. Works with PNG, JPEG, GIF, WebP, SVG.\n- `playwright-cli screenshot --tab=<id>` + `open --view <path>` — screenshot a tab, then view it.\n- `screencapture --view screenshot.png` — capture the user's screen via browser screen sharing.\n- `playwright-cli snapshot --tab=<id>` — accessibility tree (text). Use to verify content without vision.\n\n**What only the human sees:**\n\n- `serve <dir>` — opens an app directory in a browser tab (read-only preview).\n- `serve --ttl 30d <dir>` — uploads an immutable snapshot that works without the leader. TTL units are whole `m`, `h`, `d`, or `w`, capped at 30 days. It implies `--no-bridge`, conflicts with `--bridge`/`--max-tabs`, and is limited to 1,000 files, 25 MiB per file, and 50 MiB total. Use `serve --list` for mode/expiry and `serve --stop <token>` to revoke it early.\n- `serve --bridge <dir>` — opens a **driveable** preview whose visitors auto-connect as live synthetic-CDP targets you can navigate/click/evaluate/screenshot via playwright. **Security: opt-in only; cross-subdomain cookie risk accepted (host-only cookies isolated; `Domain=.sliccy.now` cookies readable across previews).** Flags: `--max-tabs <N>` (default 20), `--quiet` (suppress the first-visit announcement), `--no-bridge` (force read-only), `--stop <token>` (revoke + delete webhook). Use `serve --logs [<token>] [--lines <N>]` to inspect leader-memory-only connect/disconnect records without emitting a lick or waking the cone. `serve --truncate [<token>]` clears matching records **and re-arms the first-visit announcement**, so the next visit announces once. Visitor page API: `window.slicc.emit(name, detail?)` (fires webhook lick on cone), `window.slicc.on(name, cb)` (subscribes to CustomEvents you dispatch).\n- `open <path>` (no flags) — opens a file in a browser tab.\n- `imgcat <path>` — displays an image in the terminal preview.\n\n**Workflow to verify a page (when vision is actually required):**\n\n1. `serve /workspace/app` — open the app (the human sees it).\n2. `playwright-cli tab-list` — find the tab by URL, note the targetId.\n3. `playwright-cli snapshot --tab=<id>` — required before screenshot, and often answers your question on its own.\n4. `playwright-cli screenshot --tab=<id> --filename=\"$TMPDIR/shot.png\"` — consider `--max-width` to keep the file small.\n5. `open --view \"$TMPDIR/shot.png\"` — now you can see it. Strongly prefer doing this from a scoop, not the cone.\n\n**Don't:**\n\n- Default to screenshots when a snapshot would do.\n- `read_file` on a PNG or base64-encode to view images.\n- `imgcat` or `cat` on screenshots expecting to see them.\n- Open a screenshot then screenshot that tab.\n- Use `eval` to check the active tab — use `tab-list`.\n\n### Tab Management\n\n```bash\nplaywright-cli tab-list # List tabs with targetIds + (active) marker\nplaywright-cli tab-new [url] # New tab, returns targetId\nplaywright-cli tab-close --tab=<id> # Close specific tab\nplaywright-cli tab-select <index> # Select (bring to front) tab by 1-based index\n```\n\n### Cookies\n\n```bash\nplaywright-cli cookie-list --tab=<id> [--domain=<d>] [--path=<p>] # List cookies (filter by domain/path)\nplaywright-cli cookie-get --tab=<id> <name> # Get cookie\nplaywright-cli cookie-set --tab=<id> <name> <value> [--sameSite=Strict|Lax|None] [other flags] # Set cookie\nplaywright-cli cookie-delete --tab=<id> <name> [--domain= --path=] # Delete cookie\nplaywright-cli cookie-clear --tab=<id> # Clear all cookies\n```\n\n### Storage\n\n```bash\nplaywright-cli localstorage-list --tab=<id>\nplaywright-cli localstorage-get --tab=<id> <key>\nplaywright-cli localstorage-set --tab=<id> <key> <value>\nplaywright-cli localstorage-delete --tab=<id> <key>\nplaywright-cli localstorage-clear --tab=<id>\n# Same pattern for sessionstorage-*\nplaywright-cli state-save --tab=<id> [filename|--filename=path] # Save cookies + localStorage to JSON\nplaywright-cli state-load --tab=<id> <filename> # Restore from state file\n```\n\n### Network\n\n```bash\nplaywright-cli console --tab=<id> [min-level] [--clear] # List console messages (debug/log/info/warning/error)\nplaywright-cli requests --tab=<id> [--static] [--filter=<regex>] [--clear] # List network requests\nplaywright-cli request --tab=<id> <index> [--filename=path] # Full request details\nplaywright-cli request-headers --tab=<id> <index> # Request headers only\nplaywright-cli request-body --tab=<id> <index> # Request body only\nplaywright-cli response-headers --tab=<id> <index> # Response headers only\nplaywright-cli response-body --tab=<id> <index> [--filename=path] # Response body (--filename saves the exact bytes)\nplaywright-cli network-state-set --tab=<id> <online|offline> # Toggle network state\nplaywright-cli route --tab=<id> <pattern> [--status=N] [--body=text] [--content-type=type] [--header=name:value]\nplaywright-cli route-list --tab=<id> # List active routes\nplaywright-cli unroute --tab=<id> [pattern] # Remove routes (all if no pattern)\n```\n\n### DevTools\n\n```bash\nplaywright-cli generate-locator --tab=<id> <ref> # Generate Playwright locator string for element\nplaywright-cli highlight --tab=<id> <ref> [--style=<css>] # Highlight element with visual overlay\nplaywright-cli highlight --tab=<id> --hide [ref] # Remove highlight (all if no ref)\n```\n\n### HAR Recording\n\n```bash\nplaywright-cli record [url] [--filter=<js-expr>] # Open tab with network recording\nplaywright-cli stop-recording <recordingId> # Stop and save HAR\n```\n\n## Multi-Agent Tab Behavior\n\n**All agents (cone + scoops) share the same tab namespace.** There is no tab isolation.\n\n- `tab-list` shows **every** tab from every agent — yours, the cone's, other scoops'. The list can be noisy.\n- Any agent can `eval`, `snapshot`, or `close` any tab — there are no ownership checks.\n- Tab counts fluctuate as other agents open and close tabs concurrently.\n\n**Best practices for scoops:**\n\n1. **Track your own tab IDs.** When you open a tab, capture the targetId and store it. Don't rely on `tab-list` to find your tabs later — other agents' tabs will be mixed in.\n\n ```bash\n # Open and capture the ID\n playwright-cli tab-new https://example.com\n # Output: Opened https://example.com in new tab [targetId: ABC123...]\n # Use ABC123 for all subsequent commands on this tab\n ```\n\n2. **NEVER close tabs you didn't open.** Tabs you don't recognize belong to the **user** or other agents. User tabs are off-limits unless the user explicitly asks you to close them. Only close tabs whose targetId you captured from your own `tab-new` / `open` calls.\n\n3. **Handle \"tab not found\" gracefully.** Another agent might close a tab between your `tab-list` and your command. If you get `Error: No tab with id`, the tab is gone — move on.\n\n4. **Don't depend on tab count or ordering.** Other agents are opening/closing tabs concurrently. Use targetIds, not positional logic.\n\n5. **Clean up when done.** Close all tabs you opened before finishing. Include this in every scoop brief:\n _\"Close each tab with `playwright-cli tab-close --tab=<id>` when done.\"_\n\n## Tips\n\n- **Refs change after every interaction** — always re-snapshot before clicking or filling.\n- `open` and `tab-new` open tabs in the **background** by default. Capture the targetId from the output. To open in the **foreground** add `--foreground`/`--fg`; to raise an **already-open** tab use `tab-select <index>`.\n- After `click`, `fill`, `goto`, `go-back`, `go-forward`, `reload`, `select`, `check`, `uncheck`, `drag`, or `dialog-*`, take a fresh `snapshot --tab=<id>` before using refs again.\n- Unexpected JavaScript dialogs are auto-dismissed on attached pages.\n- Use `eval --tab=<id>` for DOM operations not covered by built-in commands; save results with `--filename=path`.\n- The SLICC app tab and Chrome internal UI tabs are automatically excluded from `tab-list`.\n- `fill` clears and types into regular inputs, textareas, and `contenteditable` elements. Use `--submit` to press Enter after. If the text or an `eval` expression starts with `-`, put `--` before it so it is not parsed as a flag.\n- Negative numbers for `mousewheel` / `mousemove` are positionals (no `--` needed): `mousewheel --tab=<id> 0 -300`.\n- `drop --path=<vfs-path>` injects the file as **raw bytes**; a UTF-8 text round-trip would replace every byte >= 0x80 with `EF BF BD`, so mp4/zip/jpg drops stay byte-exact.\n- Screenshots default to `$TMPDIR/screenshot-<timestamp>.png` — your own scratch directory, not the shared root. Use `--filename=path` to save elsewhere —\n `screenshot <path>` is an error, because that slot is the element ref.\n- Unsupported flags and extra positionals are rejected per subcommand, so a probe that exits 0 means\n the flag was honoured — nothing is silently dropped.\n- Use `keydown`/`keyup` for holding modifier keys (e.g. Shift+click: `keydown Shift`, `click`, `keyup Shift`).\n- Use `requests` + `response-body` to inspect XHR/fetch responses; `route` to mock or block them.\n- **Calling the app's own backend? Use `curlwright`, not `eval-file`.** It is curl's flags run by a `fetch()` inside the tab, so cookies, origin and session come along: `curlwright -s -X POST https://app.example.com/api/items -H 'X-CSRF-Token: abc' -d '{\"name\":\"x\"}' --tab=<id>`. `-o <file>` writes a **byte-exact** body, which `eval-file` cannot do at all — that is the only way to pull a binary response out of a page. Without `--tab` it uses the tab already on that origin. `curlwright --help` for the flag list. It cancels the same way playwright-cli does — giving up exits **130** and writes no `-o` file for a response nobody is reading — but the in-page `fetch` is bounded by `-m`, not by the cancellation, so a cancelled request may still have reached the server.\n- `state-save` / `state-load` persist auth state (cookies + localStorage) across sessions.\n- `pdf` saves a print-layout PDF; not available in extension mode.\n- `upload` injects VFS files as **raw bytes** (a UTF-8 text round-trip would replace every byte ≥ 0x80 with `EF BF BD`). A leading `eN` / `fNeN` token is a snapshot ref, never a filename — run `snapshot` first; without a ref, focus the file input first. To upload a file named `e2`, pass `./e2` or an absolute path.\n\n## Low-level CDP escape hatch\n\nFor raw Chrome DevTools Protocol calls that `playwright-cli` doesn't wrap, send JSON-RPC directly over WebSocket with `websocat`:\n\n```bash\n# Discover the page's debug socket URL via the CDP HTTP endpoint\ncurl -s http://127.0.0.1:9222/json | jq -r '.[0].webSocketDebuggerUrl'\n\n# Send a single CDP method, receive the response, exit\necho 'Page.navigate {\"url\":\"https://example.com\"}' \\\n | websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc ws://127.0.0.1:9222/devtools/page/<id>\n```\n\nRun `websocat --help` for the full flag list. Use this only when `playwright-cli` has no wrapper for the CDP method you need.\n";export{e as default};
1
+ var e="---\nname: playwright-cli\ndescription: |\n Use this whenever the user asks to browse, navigate, click, fill a form,\n scrape, take a screenshot, or otherwise interact with a web page. SLICC drives\n the browser through the `playwright-cli` shell command (also aliased as\n `playwright` and `puppeteer`). Read this BEFORE running any browser\n automation: every tab-operating command requires a `--tab` target id, and\n multi-agent tab handling has rules you must follow.\nallowed-tools: bash\n---\n\n# Browser Automation via playwright-cli\n\nUse `playwright-cli` (also aliased as `playwright` and `puppeteer`) via the bash tool for all browser automation.\n\n**Every tab-operating command requires `--tab=<targetId>`.** There is no implicit \"current tab\". Always specify which tab you're operating on.\n\n`playwright-cli <command> --help` prints that command's usage and does nothing else — safe to run before any action.\n\n## Quick Start\n\n```bash\n# 1. Open a page — note the targetId in the output\nplaywright-cli open https://example.com\n# Output: Opened https://example.com in new tab [targetId: E9A3F...]\n\n# 2. Take a snapshot to see the page structure and get element refs\nplaywright-cli snapshot --tab=E9A3F\n\n# 3. Interact using refs from the snapshot (e.g. e5, e12)\nplaywright-cli click --tab=E9A3F e5\nplaywright-cli fill --tab=E9A3F e12 \"hello world\"\n\n# 4. Re-snapshot after interactions (refs change)\nplaywright-cli snapshot --tab=E9A3F\n```\n\n## Tab IDs\n\n- `tab-list` shows all tabs with their targetIds. The user's active tab is marked `(active)`.\n- `tab-new` / `open` return the new tab's targetId — capture it for subsequent commands.\n- Use `--tab=<targetId>` on ALL commands that operate on a tab.\n\n## Frame IDs\n\n- `frames --tab=<targetId>` lists frame IDs. A frame ID is not a tab target ID; never pass it to `--tab`.\n- Use `--tab=<targetId> --frame=<frameId>` with `eval`, `eval-file`, or `snapshot` to target a child frame, including cross-origin frames.\n- A frame-scoped `snapshot` prints only that frame's accessibility subtree. Its frame-prefixed refs work with `click`, `fill`, `dblclick`, `hover`, `select`, `check`, and `uncheck`; do not pass `--frame` to those commands. Other ref commands require refs from a top-level snapshot.\n\n## Common Failure Modes\n\n- `--tab <targetId> is required` — you forgot `--tab=<id>`. Run `tab-list` to get IDs.\n- `is a frame ID, not a tab target ID` — keep the owning tab's targetId in `--tab` and pass the frame ID with `--frame`.\n- `No snapshot available` — run `snapshot --tab=<id>` before using refs.\n- `unknown flag \"--x\"` / `unexpected argument \"y\"` — every subcommand rejects arguments it does not\n support, so an exit code of 0 means everything you passed was honoured. Check `<verb> --help`.\n- For free-text payloads that start with `-` (e.g. `fill`/`type`/`eval`), put `--` before the text:\n `fill --tab=<id> e1 -- --dash-looking`.\n- `is not an element ref` — a screenshot's positional is a main-frame element ref (`e5`); the output\n path is `--filename=<path>`. Frame-prefixed refs (`f1e5`) clip only with `click`-family commands.\n- Refs are tied to **one tab + one snapshot**. They do not carry across tabs, navigations, or reloads.\n\n## Element Refs\n\nSnapshots assign short ref IDs (`e1`, `e2`, ...) to interactive elements. Use these refs with `click`, `fill`, `dblclick`, `hover`, `select`, `check`, `uncheck`, `drag`, `upload`, `drop`, and `screenshot`.\n\nRefs are invalidated after any state-changing command. Always re-snapshot to get fresh refs.\n\n## Commands\n\nAll commands below that operate on a tab require `--tab=<targetId>`.\n\n### Core\n\n```bash\nplaywright-cli open [url] [--foreground] [--mobile] # Open tab (background by default), returns targetId\nplaywright-cli tab-new [url] [--foreground] [--mobile] # Same as open\nplaywright-cli tab-close --tab=<id> # Close tab (alias: close)\nplaywright-cli goto --tab=<id> <url> # Navigate tab\nplaywright-cli navigate --tab=<id> <url> # Alias for goto\nplaywright-cli snapshot --tab=<id> [--frame=<frameId>] [--no-iframes] [--filename=path] [--depth=<n>] [--boxes] # Tab tree or one frame subtree; --depth limits nesting, --boxes adds [box=x,y,w,h] rects\nplaywright-cli find --tab=<id> <text> # Search the snapshot for text (case-insensitive), returns matching lines + context\nplaywright-cli find --tab=<id> --regex=<re> # Same, with a regexp (use either text or --regex, not both)\nplaywright-cli eval --tab=<id> [--frame=<frameId>] <expression> [--filename=path|--output=path] # Evaluate JS in a tab/frame, incl. top-level await/return; use `--` before an expression that starts with `-`\nplaywright-cli eval-file --tab=<id> [--frame=<frameId>] <vfs-path> [--output=path|--filename=path] # Evaluate JS from a VFS file in a tab/frame (top-level await/return supported)\nplaywright-cli frames --tab=<id> # List frame IDs for --frame (not --tab)\nplaywright-cli resize --tab=<id> <width> <height> # Resize viewport\n```\n\n`--foreground` (or `--fg`) opens the new tab **in the foreground** — it brings the\nnew tab to the front and switches the user's visible/active tab to it, instead of\nopening in the background.\n\n**Bringing a tab to the foreground (activate / focus / raise / switch to a tab):**\n\n- **New tab** → `open <url> --foreground` (or `tab-new <url> --fg`).\n- **Existing tab** → `tab-select <index>` (1-based index from `tab-list`).\n\n`--mobile` opens the tab with generic mobile-device emulation (viewport,\ndevice pixel ratio, touch, Android Chrome UA), sticky for the tab's lifetime —\na later `resize` changes only the dimensions and keeps the mobile identity.\nMobile pages are usually lighter, which saves tokens.\n\nThese two are the ONLY ways to change which tab is in front. There is no\n`activate`, `bring-to-front`, or `focus` subcommand, and `eval`-ing\n`window.focus()` does NOT work (browsers block a page from stealing foreground).\nIf a tab didn't come to the front, re-run `tab-select` / `--foreground` — do not\nfall back to `window.focus()`.\n\n### Interaction\n\n```bash\nplaywright-cli click --tab=<id> <ref> [--modifiers=Shift,Control,Alt,Meta] # Click element\nplaywright-cli dblclick --tab=<id> <ref> [button] [--modifiers=...] # Double-click\nplaywright-cli fill --tab=<id> <ref> <text> [--submit] # Clear input + type text (--submit presses Enter); use `--` before text that starts with `-`\nplaywright-cli type --tab=<id> <text> [--submit] # Type into focused element (--submit presses Enter); use `--` before text that starts with `-`\nplaywright-cli hover --tab=<id> <ref> # Hover over element\nplaywright-cli select --tab=<id> <ref> <value> # Select dropdown value\nplaywright-cli check --tab=<id> <ref> # Check checkbox/radio\nplaywright-cli uncheck --tab=<id> <ref> # Uncheck checkbox/radio\nplaywright-cli drag --tab=<id> <startRef> <endRef> # Drag and drop\nplaywright-cli upload --tab=<id> [ref] <file> [file...] # Upload VFS files to file input as raw bytes (optional snapshot ref targets hidden inputs)\nplaywright-cli drop --tab=<id> <ref> [--path=<vfs-path>] [--data=<mime/type=value>] # Drop files/data onto element (--path drops raw bytes)\nplaywright-cli dialog-accept --tab=<id> [text] # Accept JS dialog\nplaywright-cli dialog-dismiss --tab=<id> # Dismiss JS dialog\n```\n\n### Keyboard\n\n```bash\nplaywright-cli press --tab=<id> <key> # Press key (keyDown + keyUp, e.g. Enter, Tab, Escape)\nplaywright-cli keydown --tab=<id> <key> # Hold key down (no paired keyUp)\nplaywright-cli keyup --tab=<id> <key> # Release held key (no paired keyDown)\n```\n\n### Mouse\n\n```bash\nplaywright-cli mousemove --tab=<id> <x> <y> # Move mouse to coordinates (negative coords ok, e.g. -10 20)\nplaywright-cli mousedown --tab=<id> [button] # Press mouse button (left/right/middle, default: left)\nplaywright-cli mouseup --tab=<id> [button] # Release mouse button\nplaywright-cli mousewheel --tab=<id> <dx> <dy> # Scroll mouse wheel (negative deltas ok, e.g. 0 -300)\n```\n\n### Navigation\n\n```bash\nplaywright-cli go-back --tab=<id> # history.back()\nplaywright-cli go-forward --tab=<id> # history.forward()\nplaywright-cli reload --tab=<id> # Reload page\n```\n\n### Teleport\n\n```bash\nplaywright-cli teleport --tab=<id> --start=<regex> --return=<regex> [--timeout=<s>]\nplaywright-cli teleport --list # List available follower runtimes\nplaywright-cli teleport --off --tab=<id> # Cancel a teleport on this tab\nplaywright-cli open <url> --teleport-start=<regex> --teleport-return=<regex>\nplaywright-cli goto --tab=<id> <url> --teleport-start=<regex> --teleport-return=<regex>\n```\n\nTeleport is for leader/follower tray auth handoffs. Scoped to a specific tab — only commands targeting the teleporting tab are blocked; other tabs remain operational.\n\n`--runtime` is optional: without it, teleport picks the most recently active eligible follower (preferring standalone floats). Only followers that can actually serve cookies are eligible — cherry hosts, exec-only CLI followers, and any target advertising `network: false` are excluded, so a teleport fails fast instead of \"succeeding\" with zero cookies.\n\n### Screenshots\n\n```bash\nplaywright-cli screenshot --tab=<id> # Save to $TMPDIR/screenshot-<ts>.png\nplaywright-cli screenshot --tab=<id> --filename=page.png # Save to custom path\nplaywright-cli screenshot --tab=<id> e5 # Clip to an element (positional = MAIN-FRAME ref, not a path)\nplaywright-cli screenshot --tab=<id> --fullPage # Full scrollable page (alias: --full-page)\nplaywright-cli screenshot --tab=<id> --max-width=800 # Downscale to a max width (png output only)\nplaywright-cli screenshot --tab=<id> --type=jpeg # png (default) / jpeg / webp; inferred from --filename extension\nplaywright-cli screenshot --tab=<id> --hires # Capture in device pixels (honors device pixel ratio)\n```\n\nAn element screenshot (`screenshot e5`) returns **that element's crop or fails**\n(exit 1) — typically because the snapshot went stale after a navigation or\nlayout change. Re-run `snapshot` and retry with a fresh ref; it never silently\nsubstitutes a full-viewport frame.\n\nA `resize` sticks to its tab: the viewport override is re-applied automatically\nwhenever the tab is re-attached, so another driver switching tabs cannot reset\nit.\n\nAll playwright-cli commands share one browser, and locking is **per tab**:\ncommands on different tabs run in parallel; commands on the same tab serialize.\nA slow or hung navigation stalls only its own tab. A few genuinely global\noperations (`tab-select`, `--foreground`, and the attach that points the bridge\nat a tab) still take a bridge-wide lock, but they are short and never wrap a\npage wait. When callers queue up, commands may emit a\n`note: browser bridge contended — ...` line on stderr with the total lock wait\nand queue depth; the note says whether the wait was on **this tab** or\n**bridge-wide**. Either way it is back-off guidance — stagger callers or give\neach one its own tab, never re-run the command; it already ran, it was just\nslow to get the lock.\n\n**Giving up cancels the command.** When your `bash` call stops waiting — the\nturn is cancelled, `timeout` fires, or someone runs `kill <pid>` — the\nplaywright-cli command is cancelled too instead of running on for a caller that\nis gone: a queued command drops out of the tab's queue without taking the lock,\na `goto` waiting on a load event and a `waitForSelector` poll stop at once, and\na multi-step command stops before its next CDP round trip. Such a command exits\n**130** with a stderr line naming the step it stopped at, never 0.\n\nTwo consequences for you:\n\n- A cancelled command may have **half-landed**. The CDP request already on the\n wire cannot be recalled, so keys may be typed or a click delivered before the\n stop. `snapshot` the tab and continue from what you see rather than blindly\n re-running — same rule as a mid-command session reset.\n- `background_after` alone does **not** cancel; it detaches, and the command\n keeps running as a background job (that is what makes a long `goto` usable).\n Use `timeout` or `kill <pid>` when you actually want it stopped.\n\n**Stale session.** The bridge re-attaches automatically after a Chrome reset;\nthere is no need to reload the tab or open a new one. Two error shapes:\n\n- `Session with given id not found` — the bridge already re-attached; re-run\n the command.\n- `… was reset mid-command … the outcome is unknown` — part of the command may\n have landed (keys typed, a click delivered) before the session died. Do NOT\n blindly re-run it: `snapshot` the tab first and continue from what you see.\n\n### Save As\n\n```bash\nplaywright-cli pdf --tab=<id> [--filename=path] # Save page as PDF (not available in extension mode)\n```\n\n### Viewing pages and screenshots yourself\n\nThe browser displays things to the human; `open --view` is what lets _you_ see them. **But viewing screenshots is a last resort for the cone — every image you load eats a large chunk of the context window** (a single 1280×800 PNG can run 1500+ tokens, full-page screenshots much more). Reach for cheaper signals first:\n\n1. **`playwright-cli snapshot --tab=<id>`** — text accessibility tree. Use this first; it answers \"what's on the page\" for almost all verification tasks at a tiny fraction of the token cost. On a big page, `find --tab=<id> <text>` greps the snapshot and returns just the matching lines with context, and `snapshot --depth=<n>` caps the tree — both much cheaper than the full tree.\n2. **`eval` against the DOM** — when you need a specific value (`document.title`, an attribute, computed style), `eval` it. Don't screenshot for facts you can extract.\n3. **Delegate visual inspection to a scoop.** If the cone genuinely needs vision (layout regression, render fidelity, \"does this look right\"), spawn a scoop to take and view the screenshot — the scoop's context absorbs the tokens, and you receive its summary back. The cone's window stays clean for orchestration.\n4. **`open --view` in the cone** — only when the cone itself must see pixels for its current decision and steps 1–3 won't do.\n\n**What you CAN see:**\n\n- `open --view <path>` — reads an image from the VFS and returns it. Works with PNG, JPEG, GIF, WebP, SVG.\n- `playwright-cli screenshot --tab=<id>` + `open --view <path>` — screenshot a tab, then view it.\n- `screencapture --view screenshot.png` — capture the user's screen via browser screen sharing.\n- `playwright-cli snapshot --tab=<id>` — accessibility tree (text). Use to verify content without vision.\n\n**What only the human sees:**\n\n- `serve <dir>` — opens an app directory in a browser tab (read-only preview).\n- Preview URLs survive authenticated tray roves without changing their original directory, entry file, or bridge permissions. A handoff can briefly return `503`; retry the same pending rove rather than minting another target. Bridge tabs reconnect automatically (their connection IDs may change). Revoked previews stay revoked, and persistent snapshots keep their original expiry rather than receiving a fresh TTL.\n- Persistent uploads retry safely only with the same file bytes and MIME type. Body/R2-write waits time out after 30 seconds. Unknown writes retain bounded cleanup bookkeeping (up to eight unresolved uploads per preview); expiry/revoke never makes such a preview serve again, even if a delayed write finishes later.\n- `serve --ttl 30d <dir>` — uploads an immutable snapshot that works without the leader. TTL units are whole `m`, `h`, `d`, or `w`, capped at 30 days. It implies `--no-bridge`, conflicts with `--bridge`/`--max-tabs`, and is limited to 1,000 files, 25 MiB per file, and 50 MiB total. Use `serve --list` for mode/expiry and `serve --stop <token>` to revoke it early.\n- `serve --bridge <dir>` — opens a **driveable** preview whose visitors auto-connect as live synthetic-CDP targets you can navigate/click/evaluate/screenshot via playwright. **Security: opt-in only; cross-subdomain cookie risk accepted (host-only cookies isolated; `Domain=.sliccy.now` cookies readable across previews).** Flags: `--max-tabs <N>` (default 20), `--quiet` (suppress the first-visit announcement), `--no-bridge` (force read-only), `--stop <token>` (revoke + delete webhook). Use `serve --logs [<token>] [--lines <N>]` to inspect leader-memory-only connect/disconnect records without emitting a lick or waking the cone. `serve --truncate [<token>]` clears matching records **and re-arms the first-visit announcement**, so the next visit announces once. Visitor page API: `window.slicc.emit(name, detail?)` (fires webhook lick on cone), `window.slicc.on(name, cb)` (subscribes to CustomEvents you dispatch).\n- `open <path>` (no flags) — opens a file in a browser tab.\n- `imgcat <path>` — displays an image in the terminal preview.\n\n**Workflow to verify a page (when vision is actually required):**\n\n1. `serve /workspace/app` — open the app (the human sees it).\n2. `playwright-cli tab-list` — find the tab by URL, note the targetId.\n3. `playwright-cli snapshot --tab=<id>` — required before screenshot, and often answers your question on its own.\n4. `playwright-cli screenshot --tab=<id> --filename=\"$TMPDIR/shot.png\"` — consider `--max-width` to keep the file small.\n5. `open --view \"$TMPDIR/shot.png\"` — now you can see it. Strongly prefer doing this from a scoop, not the cone.\n\n**Don't:**\n\n- Default to screenshots when a snapshot would do.\n- `read_file` on a PNG or base64-encode to view images.\n- `imgcat` or `cat` on screenshots expecting to see them.\n- Open a screenshot then screenshot that tab.\n- Use `eval` to check the active tab — use `tab-list`.\n\n### Tab Management\n\n```bash\nplaywright-cli tab-list # List tabs with targetIds + (active) marker\nplaywright-cli tab-new [url] # New tab, returns targetId\nplaywright-cli tab-close --tab=<id> # Close specific tab\nplaywright-cli tab-select <index> # Select (bring to front) tab by 1-based index\n```\n\n### Cookies\n\n```bash\nplaywright-cli cookie-list --tab=<id> [--domain=<d>] [--path=<p>] # List cookies (filter by domain/path)\nplaywright-cli cookie-get --tab=<id> <name> # Get cookie\nplaywright-cli cookie-set --tab=<id> <name> <value> [--sameSite=Strict|Lax|None] [other flags] # Set cookie\nplaywright-cli cookie-delete --tab=<id> <name> [--domain= --path=] # Delete cookie\nplaywright-cli cookie-clear --tab=<id> # Clear all cookies\n```\n\n### Storage\n\n```bash\nplaywright-cli localstorage-list --tab=<id>\nplaywright-cli localstorage-get --tab=<id> <key>\nplaywright-cli localstorage-set --tab=<id> <key> <value>\nplaywright-cli localstorage-delete --tab=<id> <key>\nplaywright-cli localstorage-clear --tab=<id>\n# Same pattern for sessionstorage-*\nplaywright-cli state-save --tab=<id> [filename|--filename=path] # Save cookies + localStorage to JSON\nplaywright-cli state-load --tab=<id> <filename> # Restore from state file\n```\n\n### Network\n\n```bash\nplaywright-cli console --tab=<id> [min-level] [--clear] # List console messages (debug/log/info/warning/error)\nplaywright-cli requests --tab=<id> [--static] [--filter=<regex>] [--clear] # List network requests\nplaywright-cli request --tab=<id> <index> [--filename=path] # Full request details\nplaywright-cli request-headers --tab=<id> <index> # Request headers only\nplaywright-cli request-body --tab=<id> <index> # Request body only\nplaywright-cli response-headers --tab=<id> <index> # Response headers only\nplaywright-cli response-body --tab=<id> <index> [--filename=path] # Response body (--filename saves the exact bytes)\nplaywright-cli network-state-set --tab=<id> <online|offline> # Toggle network state\nplaywright-cli route --tab=<id> <pattern> [--status=N] [--body=text] [--content-type=type] [--header=name:value]\nplaywright-cli route-list --tab=<id> # List active routes\nplaywright-cli unroute --tab=<id> [pattern] # Remove routes (all if no pattern)\n```\n\n### DevTools\n\n```bash\nplaywright-cli generate-locator --tab=<id> <ref> # Generate Playwright locator string for element\nplaywright-cli highlight --tab=<id> <ref> [--style=<css>] # Highlight element with visual overlay\nplaywright-cli highlight --tab=<id> --hide [ref] # Remove highlight (all if no ref)\n```\n\n### HAR Recording\n\n```bash\nplaywright-cli record [url] [--filter=<js-expr>] # Open tab with network recording\nplaywright-cli stop-recording <recordingId> # Stop and save HAR\n```\n\n## Multi-Agent Tab Behavior\n\n**All agents (cone + scoops) share the same tab namespace.** There is no tab isolation.\n\n- `tab-list` shows **every** tab from every agent — yours, the cone's, other scoops'. The list can be noisy.\n- Any agent can `eval`, `snapshot`, or `close` any tab — there are no ownership checks.\n- Tab counts fluctuate as other agents open and close tabs concurrently.\n\n**Best practices for scoops:**\n\n1. **Track your own tab IDs.** When you open a tab, capture the targetId and store it. Don't rely on `tab-list` to find your tabs later — other agents' tabs will be mixed in.\n\n ```bash\n # Open and capture the ID\n playwright-cli tab-new https://example.com\n # Output: Opened https://example.com in new tab [targetId: ABC123...]\n # Use ABC123 for all subsequent commands on this tab\n ```\n\n2. **NEVER close tabs you didn't open.** Tabs you don't recognize belong to the **user** or other agents. User tabs are off-limits unless the user explicitly asks you to close them. Only close tabs whose targetId you captured from your own `tab-new` / `open` calls.\n\n3. **Handle \"tab not found\" gracefully.** Another agent might close a tab between your `tab-list` and your command. If you get `Error: No tab with id`, the tab is gone — move on.\n\n4. **Don't depend on tab count or ordering.** Other agents are opening/closing tabs concurrently. Use targetIds, not positional logic.\n\n5. **Clean up when done.** Close all tabs you opened before finishing. Include this in every scoop brief:\n _\"Close each tab with `playwright-cli tab-close --tab=<id>` when done.\"_\n\n## Tips\n\n- **Refs change after every interaction** — always re-snapshot before clicking or filling.\n- `open` and `tab-new` open tabs in the **background** by default. Capture the targetId from the output. To open in the **foreground** add `--foreground`/`--fg`; to raise an **already-open** tab use `tab-select <index>`.\n- After `click`, `fill`, `goto`, `go-back`, `go-forward`, `reload`, `select`, `check`, `uncheck`, `drag`, or `dialog-*`, take a fresh `snapshot --tab=<id>` before using refs again.\n- Unexpected JavaScript dialogs are auto-dismissed on attached pages.\n- Use `eval --tab=<id>` for DOM operations not covered by built-in commands; save results with `--filename=path`.\n- The SLICC app tab and Chrome internal UI tabs are automatically excluded from `tab-list`.\n- `fill` clears and types into regular inputs, textareas, and `contenteditable` elements. Use `--submit` to press Enter after. If the text or an `eval` expression starts with `-`, put `--` before it so it is not parsed as a flag.\n- Negative numbers for `mousewheel` / `mousemove` are positionals (no `--` needed): `mousewheel --tab=<id> 0 -300`.\n- `drop --path=<vfs-path>` injects the file as **raw bytes**; a UTF-8 text round-trip would replace every byte >= 0x80 with `EF BF BD`, so mp4/zip/jpg drops stay byte-exact.\n- Screenshots default to `$TMPDIR/screenshot-<timestamp>.png` — your own scratch directory, not the shared root. Use `--filename=path` to save elsewhere —\n `screenshot <path>` is an error, because that slot is the element ref.\n- Unsupported flags and extra positionals are rejected per subcommand, so a probe that exits 0 means\n the flag was honoured — nothing is silently dropped.\n- Use `keydown`/`keyup` for holding modifier keys (e.g. Shift+click: `keydown Shift`, `click`, `keyup Shift`).\n- Use `requests` + `response-body` to inspect XHR/fetch responses; `route` to mock or block them.\n- **Calling the app's own backend? Use `curlwright`, not `eval-file`.** It is curl's flags run by a `fetch()` inside the tab, so cookies, origin and session come along: `curlwright -s -X POST https://app.example.com/api/items -H 'X-CSRF-Token: abc' -d '{\"name\":\"x\"}' --tab=<id>`. `-o <file>` writes a **byte-exact** body, which `eval-file` cannot do at all — that is the only way to pull a binary response out of a page. Without `--tab` it uses the tab already on that origin. `curlwright --help` for the flag list. It cancels the same way playwright-cli does — giving up exits **130** and writes no `-o` file for a response nobody is reading — but the in-page `fetch` is bounded by `-m`, not by the cancellation, so a cancelled request may still have reached the server.\n- `state-save` / `state-load` persist auth state (cookies + localStorage) across sessions.\n- `pdf` saves a print-layout PDF; not available in extension mode.\n- `upload` injects VFS files as **raw bytes** (a UTF-8 text round-trip would replace every byte ≥ 0x80 with `EF BF BD`). A leading `eN` / `fNeN` token is a snapshot ref, never a filename — run `snapshot` first; without a ref, focus the file input first. To upload a file named `e2`, pass `./e2` or an absolute path.\n\n## Low-level CDP escape hatch\n\nFor raw Chrome DevTools Protocol calls that `playwright-cli` doesn't wrap, send JSON-RPC directly over WebSocket with `websocat`:\n\n```bash\n# Discover the page's debug socket URL via the CDP HTTP endpoint\ncurl -s http://127.0.0.1:9222/json | jq -r '.[0].webSocketDebuggerUrl'\n\n# Send a single CDP method, receive the response, exit\necho 'Page.navigate {\"url\":\"https://example.com\"}' \\\n | websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc ws://127.0.0.1:9222/devtools/page/<id>\n```\n\nRun `websocat --help` for the full flag list. Use this only when `playwright-cli` has no wrapper for the CDP method you need.\n";export{e as default};
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/oauth-service-BsW9nY_u.js","assets/preload-helper-Czpn1I53.js","assets/proxied-fetch-DyBveeCl.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/base64-DJRlyqZu.js","assets/fetch-body-1l9I58Vk.js","assets/api-endpoint-DGxXvrur.js","assets/runtime-env-Dlaokqg1.js","assets/panel-rpc-B3MSVImO.js","assets/permissions-surface-registry-CilCRwhh.js"])))=>i.map(i=>d[i]);
2
- import{n as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{t as n}from"./preload-helper-Czpn1I53.js";import{c as r,l as i,o as a,s as o,u as s}from"./claude-model-version-CSATLzrT.js";import"./libesm-BypnjKEL.js";import{t as c}from"./logger-DDBAeTLF.js";import{n as l}from"./base64-DJRlyqZu.js";import"./proxied-fetch-DyBveeCl.js";import{a as u,t as d}from"./api-endpoint-DGxXvrur.js";import{n as f}from"./float-topology-YtctpJaG.js";import"./secret-topology-DLJBhHOi.js";import{n as p}from"./secrets-bridge-client--VZ3E0yk.js";import"./tool-ui-eSQ1g2I1.js";import{n as m,o as h,t as g}from"./providers-Dx2Bx5aE.js";import{n as _,t as v}from"./panel-rpc-B3MSVImO.js";import{i as y,r as b,t as x}from"./bedrock-camp-compat-BeCSBUrZ.js";var S={assign:0,create:0,clone:0,discard:0,update:0};function ee(e){return Array.isArray(e)}function te(e){return C(e,null)}function ne(e){return C(typeof e,`object`)&&!te(e)}function C(e,t){return e===t}function re(e){if(!ne(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!te(t)&&C(typeof t.constructor,`function`)&&!(C(t.constructor,globalThis.Object)||C(t.constructor.name,`Object`))}function ie(e){return C(e,`__proto__`)||C(e,`constructor`)||C(e,`prototype`)}function ae(e,t){return ie(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function w(e){return Object.getOwnPropertyNames(e)}function oe(e){return Object.getOwnPropertySymbols(e)}function se(e){return globalThis.ArrayBuffer.isView(e)}function ce(e){return e instanceof globalThis.RegExp}function le(e){return e instanceof globalThis.Set}function ue(e){return e instanceof globalThis.Map}function de(e){return e}function fe(e){return ae(e,`~kind`)||ae(e,`~unsafe`)}function pe(e){let t={},n=Object.getOwnPropertyDescriptors(e);for(let e of Object.keys(n)){if(ie(e))continue;let r=n[e];ae(r,`value`)&&Object.defineProperty(t,e,{...r,value:T(r.value)})}return t}function me(e){let t={};for(let n of w(e))ie(n)||(t[n]=T(e[n]));for(let n of oe(e))t[n]=T(e[n]);return t}function he(e){return re(e)?de(e):fe(e)?pe(e):me(e)}function ge(e){return e.map(e=>T(e))}function _e(e){return e.slice()}function ve(e){return new RegExp(e.source,e.flags)}function ye(e){return new Map(T([...e.entries()]))}function be(e){return new Set(T([...e.values()]))}function T(e){return se(e)?_e(e):ce(e)?ve(e):ue(e)?ye(e):le(e)?be(e):ee(e)?ge(e):ne(e)?he(e):e}function xe(e){return S.clone+=1,T(e)}var Se={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Ce(){return Se}function we(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Te(e,t){return{...e,...t}}function Ee(e,t,n={}){S.create+=1;let r=Ce(),i=Te(t,n),a=r.enumerableKind?Te(i,e):we(i,e);return r.immutableTypes?Object.freeze(a):a}function De(e,t,n){S.update+=1;let r=Ce(),i=xe(e);for(let e of Object.keys(t))Object.defineProperty(i,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(i,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return i}function Oe(e){return ne(e)}function ke(e){return De(e,{"~optional":!0},{})}function Ae(e,t){return De(ke(e),{},t)}function je(e,t){return Ee({"~kind":`Array`},{type:`array`,items:e},t)}function Me(e,t={}){return Ae(e,t)}function Ne(e){return Me(e)}function Pe(e){return Oe(e)&&ae(e,`~optional`)}function Fe(e){return w(e).filter(t=>!Pe(e[t]))}function Ie(e,t={}){let n=Fe(e);return Ee({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var Le;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(Le||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var Re=new Float64Array(1);new DataView(Re.buffer),new Uint8Array(Re.buffer),new TextEncoder;var ze=`-?(?:0|[1-9][0-9]*)`,Be=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function Ve(e){return Ee({"~kind":`Number`},{type:`number`},e)}function E(e){return Ee({"~kind":`String`},{type:`string`},e)}var He=`^${ze}$`;`${Be}`;function Ue(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var We=[...Ue(97,122),...Ue(65,90)],Ge=[`0`,...Ue(49,57)];[...Ge],[...We,...Ge],[...Ge],new RegExp(He);function Ke(e,t){try{return Promise.resolve(t(qe))}catch(e){return Promise.reject(e)}}var qe={startSpan:Ke,addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(qe);var Je=Symbol.for(`yaml.alias`),Ye=Symbol.for(`yaml.document`),D=Symbol.for(`yaml.map`),Xe=Symbol.for(`yaml.pair`),Ze=Symbol.for(`yaml.scalar`),Qe=Symbol.for(`yaml.seq`),O=Symbol.for(`yaml.node.type`),k=e=>!!e&&typeof e==`object`&&e[O]===Je,$e=e=>!!e&&typeof e==`object`&&e[O]===Ye,et=e=>!!e&&typeof e==`object`&&e[O]===D,A=e=>!!e&&typeof e==`object`&&e[O]===Xe,j=e=>!!e&&typeof e==`object`&&e[O]===Ze,tt=e=>!!e&&typeof e==`object`&&e[O]===Qe;function M(e){if(e&&typeof e==`object`)switch(e[O]){case D:case Qe:return!0}return!1}function N(e){if(e&&typeof e==`object`)switch(e[O]){case Je:case D:case Ze:case Qe:return!0}return!1}var nt=e=>(j(e)||M(e))&&!!e.anchor,P=Symbol(`break visit`),rt=Symbol(`skip children`),it=Symbol(`remove node`);function at(e,t){let n=st(t);$e(e)?ot(null,e.contents,n,Object.freeze([e]))===it&&(e.contents=null):ot(null,e,n,Object.freeze([]))}at.BREAK=P,at.SKIP=rt,at.REMOVE=it;function ot(e,t,n,r){let i=ct(e,t,n,r);if(N(i)||A(i))return lt(e,r,i),ot(e,i,n,r);if(typeof i!=`symbol`){if(M(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ot(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===P)return P;else i===it&&(t.items.splice(e,1),--e)}}else if(A(t)){r=Object.freeze(r.concat(t));let e=ot(`key`,t.key,n,r);if(e===P)return P;e===it&&(t.key=null);let i=ot(`value`,t.value,n,r);if(i===P)return P;i===it&&(t.value=null)}}return i}function st(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function ct(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(et(t))return n.Map?.(e,t,r);if(tt(t))return n.Seq?.(e,t,r);if(A(t))return n.Pair?.(e,t,r);if(j(t))return n.Scalar?.(e,t,r);if(k(t))return n.Alias?.(e,t,r)}function lt(e,t,n){let r=t[t.length-1];if(M(r))r.items[e]=n;else if(A(r))e===`key`?r.key=n:r.value=n;else if($e(r))r.contents=n;else{let e=k(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}function ut(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function dt(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=dt(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=dt(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=dt(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=dt(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function F(e,t,n){if(Array.isArray(e))return e.map((e,t)=>F(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!nt(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var ft=class{constructor(e){Object.defineProperty(this,O,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!$e(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=F(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?dt(i,{"":o},``,o):o}},pt=class extends ft{constructor(e){super(Je),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],at(e,{Node:(e,t)=>{(k(t)||nt(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(F(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=mt(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(ut(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function mt(e,t,n){if(k(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(M(t)){let r=0;for(let i of t.items){let t=mt(e,i,n);t>r&&(r=t)}return r}if(A(t)){let r=mt(e,t.key,n),i=mt(e,t.value,n);return Math.max(r,i)}return 1}var ht=e=>!e||typeof e!=`function`&&typeof e!=`object`,I=class extends ft{constructor(e){super(Ze),this.value=e}toJSON(e,t){return t?.keep?this.value:F(this.value,e,t)}toString(){return String(this.value)}};I.BLOCK_FOLDED=`BLOCK_FOLDED`,I.BLOCK_LITERAL=`BLOCK_LITERAL`,I.PLAIN=`PLAIN`,I.QUOTE_DOUBLE=`QUOTE_DOUBLE`,I.QUOTE_SINGLE=`QUOTE_SINGLE`;var gt=`tag:yaml.org,2002:`;function _t(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function vt(e,t,n){if($e(e)&&(e=e.contents),N(e))return e;if(A(e)){let t=n.schema[D].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new pt(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=gt+t.slice(2));let l=_t(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new I(e);return c&&(c.node=t),t}l=e instanceof Map?o[D]:Symbol.iterator in Object(e)?o[Qe]:o[D]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new I(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function yt(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return vt(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var bt=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,xt=class extends ft{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>N(t)||A(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(bt(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(M(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,yt(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(M(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&j(i)?i.value:i:M(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!A(t))return!1;let n=t.value;return n==null||e&&j(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return M(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(M(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,yt(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},St=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function Ct(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var L=(e,t,n)=>e.endsWith(`
2
+ import{n as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{t as n}from"./preload-helper-Czpn1I53.js";import{c as r,l as i,o as a,s as o,u as s}from"./claude-model-version-CSATLzrT.js";import"./libesm-BypnjKEL.js";import{t as c}from"./logger-DDBAeTLF.js";import{n as l}from"./base64-DJRlyqZu.js";import"./proxied-fetch-DyBveeCl.js";import{a as u,t as d}from"./api-endpoint-DGxXvrur.js";import{n as f}from"./float-topology-YtctpJaG.js";import"./secret-topology-DLJBhHOi.js";import{n as p}from"./secrets-bridge-client--VZ3E0yk.js";import"./tool-ui-eSQ1g2I1.js";import{n as m,o as h,t as g}from"./providers-Dq0px1q5.js";import{n as _,t as v}from"./panel-rpc-B3MSVImO.js";import{i as y,r as b,t as x}from"./bedrock-camp-compat-BeCSBUrZ.js";var S={assign:0,create:0,clone:0,discard:0,update:0};function ee(e){return Array.isArray(e)}function te(e){return C(e,null)}function ne(e){return C(typeof e,`object`)&&!te(e)}function C(e,t){return e===t}function re(e){if(!ne(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!te(t)&&C(typeof t.constructor,`function`)&&!(C(t.constructor,globalThis.Object)||C(t.constructor.name,`Object`))}function ie(e){return C(e,`__proto__`)||C(e,`constructor`)||C(e,`prototype`)}function ae(e,t){return ie(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function w(e){return Object.getOwnPropertyNames(e)}function oe(e){return Object.getOwnPropertySymbols(e)}function se(e){return globalThis.ArrayBuffer.isView(e)}function ce(e){return e instanceof globalThis.RegExp}function le(e){return e instanceof globalThis.Set}function ue(e){return e instanceof globalThis.Map}function de(e){return e}function fe(e){return ae(e,`~kind`)||ae(e,`~unsafe`)}function pe(e){let t={},n=Object.getOwnPropertyDescriptors(e);for(let e of Object.keys(n)){if(ie(e))continue;let r=n[e];ae(r,`value`)&&Object.defineProperty(t,e,{...r,value:T(r.value)})}return t}function me(e){let t={};for(let n of w(e))ie(n)||(t[n]=T(e[n]));for(let n of oe(e))t[n]=T(e[n]);return t}function he(e){return re(e)?de(e):fe(e)?pe(e):me(e)}function ge(e){return e.map(e=>T(e))}function _e(e){return e.slice()}function ve(e){return new RegExp(e.source,e.flags)}function ye(e){return new Map(T([...e.entries()]))}function be(e){return new Set(T([...e.values()]))}function T(e){return se(e)?_e(e):ce(e)?ve(e):ue(e)?ye(e):le(e)?be(e):ee(e)?ge(e):ne(e)?he(e):e}function xe(e){return S.clone+=1,T(e)}var Se={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Ce(){return Se}function we(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Te(e,t){return{...e,...t}}function Ee(e,t,n={}){S.create+=1;let r=Ce(),i=Te(t,n),a=r.enumerableKind?Te(i,e):we(i,e);return r.immutableTypes?Object.freeze(a):a}function De(e,t,n){S.update+=1;let r=Ce(),i=xe(e);for(let e of Object.keys(t))Object.defineProperty(i,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(i,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return i}function Oe(e){return ne(e)}function ke(e){return De(e,{"~optional":!0},{})}function Ae(e,t){return De(ke(e),{},t)}function je(e,t){return Ee({"~kind":`Array`},{type:`array`,items:e},t)}function Me(e,t={}){return Ae(e,t)}function Ne(e){return Me(e)}function Pe(e){return Oe(e)&&ae(e,`~optional`)}function Fe(e){return w(e).filter(t=>!Pe(e[t]))}function Ie(e,t={}){let n=Fe(e);return Ee({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var Le;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(Le||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var Re=new Float64Array(1);new DataView(Re.buffer),new Uint8Array(Re.buffer),new TextEncoder;var ze=`-?(?:0|[1-9][0-9]*)`,Be=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function Ve(e){return Ee({"~kind":`Number`},{type:`number`},e)}function E(e){return Ee({"~kind":`String`},{type:`string`},e)}var He=`^${ze}$`;`${Be}`;function Ue(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var We=[...Ue(97,122),...Ue(65,90)],Ge=[`0`,...Ue(49,57)];[...Ge],[...We,...Ge],[...Ge],new RegExp(He);function Ke(e,t){try{return Promise.resolve(t(qe))}catch(e){return Promise.reject(e)}}var qe={startSpan:Ke,addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(qe);var Je=Symbol.for(`yaml.alias`),Ye=Symbol.for(`yaml.document`),D=Symbol.for(`yaml.map`),Xe=Symbol.for(`yaml.pair`),Ze=Symbol.for(`yaml.scalar`),Qe=Symbol.for(`yaml.seq`),O=Symbol.for(`yaml.node.type`),k=e=>!!e&&typeof e==`object`&&e[O]===Je,$e=e=>!!e&&typeof e==`object`&&e[O]===Ye,et=e=>!!e&&typeof e==`object`&&e[O]===D,A=e=>!!e&&typeof e==`object`&&e[O]===Xe,j=e=>!!e&&typeof e==`object`&&e[O]===Ze,tt=e=>!!e&&typeof e==`object`&&e[O]===Qe;function M(e){if(e&&typeof e==`object`)switch(e[O]){case D:case Qe:return!0}return!1}function N(e){if(e&&typeof e==`object`)switch(e[O]){case Je:case D:case Ze:case Qe:return!0}return!1}var nt=e=>(j(e)||M(e))&&!!e.anchor,P=Symbol(`break visit`),rt=Symbol(`skip children`),it=Symbol(`remove node`);function at(e,t){let n=st(t);$e(e)?ot(null,e.contents,n,Object.freeze([e]))===it&&(e.contents=null):ot(null,e,n,Object.freeze([]))}at.BREAK=P,at.SKIP=rt,at.REMOVE=it;function ot(e,t,n,r){let i=ct(e,t,n,r);if(N(i)||A(i))return lt(e,r,i),ot(e,i,n,r);if(typeof i!=`symbol`){if(M(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ot(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===P)return P;else i===it&&(t.items.splice(e,1),--e)}}else if(A(t)){r=Object.freeze(r.concat(t));let e=ot(`key`,t.key,n,r);if(e===P)return P;e===it&&(t.key=null);let i=ot(`value`,t.value,n,r);if(i===P)return P;i===it&&(t.value=null)}}return i}function st(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function ct(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(et(t))return n.Map?.(e,t,r);if(tt(t))return n.Seq?.(e,t,r);if(A(t))return n.Pair?.(e,t,r);if(j(t))return n.Scalar?.(e,t,r);if(k(t))return n.Alias?.(e,t,r)}function lt(e,t,n){let r=t[t.length-1];if(M(r))r.items[e]=n;else if(A(r))e===`key`?r.key=n:r.value=n;else if($e(r))r.contents=n;else{let e=k(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}function ut(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function dt(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=dt(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=dt(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=dt(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=dt(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function F(e,t,n){if(Array.isArray(e))return e.map((e,t)=>F(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!nt(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var ft=class{constructor(e){Object.defineProperty(this,O,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!$e(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=F(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?dt(i,{"":o},``,o):o}},pt=class extends ft{constructor(e){super(Je),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],at(e,{Node:(e,t)=>{(k(t)||nt(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(F(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=mt(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(ut(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function mt(e,t,n){if(k(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(M(t)){let r=0;for(let i of t.items){let t=mt(e,i,n);t>r&&(r=t)}return r}if(A(t)){let r=mt(e,t.key,n),i=mt(e,t.value,n);return Math.max(r,i)}return 1}var ht=e=>!e||typeof e!=`function`&&typeof e!=`object`,I=class extends ft{constructor(e){super(Ze),this.value=e}toJSON(e,t){return t?.keep?this.value:F(this.value,e,t)}toString(){return String(this.value)}};I.BLOCK_FOLDED=`BLOCK_FOLDED`,I.BLOCK_LITERAL=`BLOCK_LITERAL`,I.PLAIN=`PLAIN`,I.QUOTE_DOUBLE=`QUOTE_DOUBLE`,I.QUOTE_SINGLE=`QUOTE_SINGLE`;var gt=`tag:yaml.org,2002:`;function _t(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function vt(e,t,n){if($e(e)&&(e=e.contents),N(e))return e;if(A(e)){let t=n.schema[D].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new pt(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=gt+t.slice(2));let l=_t(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new I(e);return c&&(c.node=t),t}l=e instanceof Map?o[D]:Symbol.iterator in Object(e)?o[Qe]:o[D]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new I(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function yt(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return vt(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var bt=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,xt=class extends ft{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>N(t)||A(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(bt(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(M(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,yt(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(M(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&j(i)?i.value:i:M(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!A(t))return!1;let n=t.value;return n==null||e&&j(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return M(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(M(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,yt(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},St=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function Ct(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var L=(e,t,n)=>e.endsWith(`
3
3
  `)?Ct(n,t):n.includes(`
4
4
  `)?`
5
5
  `+Ct(n,t):(e.endsWith(` `)?``:` `)+n,wt=`flow`,Tt=`block`,Et=`quoted`;function Dt(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=Ot(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{n,r}from"./panel-rpc-BPwAqRch.js";import{n as i,o as a,t as o}from"./providers-BYl2eNQm.js";import"./proxied-fetch-B57RqgUb.js";import{a as s,t as c}from"./api-endpoint-Lx_FU5cP.js";import{u as l}from"./core-D59qaXEb.js";import{i as u,n as ee,r as d}from"./compat-uEPf6-XW.js";import{t as f}from"./secrets-bridge-client-DBeju3mP.js";import{i as te,r as ne,t as re}from"./bedrock-camp-compat-99DjWBHV.js";import{o as ie}from"./claude-model-version-m5AAX9Oe.js";const ae=`slicc_oauth_extra_domains`;function p(e){try{let t=e.getItem(ae);if(!t)return{};let n=JSON.parse(t);if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n)){if(typeof e!=`string`||!Array.isArray(t))continue;let n=t.filter(e=>typeof e==`string`&&e.length>0);n.length>0&&(r[e]=n)}return r}catch{return{}}}function oe(e,t){try{e.setItem(ae,JSON.stringify(t))}catch(e){throw Error(`Failed to persist OAuth extras (localStorage quota exceeded?): ${e instanceof Error?e.message:String(e)}`)}}function se(e,t){let n={input:0,output:0,cacheRead:0,cacheWrite:0},r=ie(e);if(!r)return n;let i;for(let e of t.values()){let t=ie(e.id);!t||t.family!==r.family||(!i||t.major>i.major||t.major===i.major&&t.minor>i.minor)&&(i={major:t.major,minor:t.minor,cost:e.cost})}return i?.cost??n}const ce=t(`model-policy`),m=`/etc/models`;function h(){return{sections:{}}}function le(e){let t=e.indexOf(`#`);return(t===-1?e:e.slice(0,t)).trim()}function ue(e){let t=h();if(typeof e!=`string`)return t;let n=null;for(let r of e.split(/\r?\n/)){let e=le(r);if(!e)continue;let i=/^\[([^\]]+)\]$/.exec(e);if(i){n=i[1].trim(),t.sections[n]??=[];continue}if(n===null){ce.warn(`model policy entry before any [provider] section — ignored`,{entry:e});continue}let a=e.startsWith(`-`),o=a?e.slice(1).trim():e,s=o.indexOf(`:`);if(s<=0||s===o.length-1){ce.warn(`model policy entry is not provider:model — ignored`,{entry:e});continue}t.sections[n].push({providerId:o.slice(0,s).trim(),modelId:o.slice(s+1).trim(),deny:a})}return t}function g(e,t,n){return e.providerId===t?e.modelId===`*`||e.modelId===n:!1}function de(e,t){return e.sections[t]??[]}function fe(e,t,n,r){return de(e,t).some(e=>e.deny&&g(e,n,r))}function pe(e,t,n,r){let i=de(e,t);return i.some(e=>e.deny&&g(e,n,r))?!1:n===t||i.some(e=>!e.deny&&g(e,n,r))}let me=h();function he(e){me=e}function _(){return me}function ge(e,t,n){return`add \`${t}:${n}\` (or \`${t}:*\`) under \`[${e}]\` in ${m}`}var _e=e({ACCOUNTS_KEY:()=>b,__test__:()=>Ce,addAccount:()=>P,applyProviderDefaults:()=>Ee,clearAllSettings:()=>ut,clearApiKey:()=>at,clearBaseUrl:()=>ct,clearSelectedProvider:()=>nt,ensureOAuthMaskReplica:()=>Je,exportProviders:()=>lt,getAccounts:()=>M,getAllAvailableModels:()=>Ae,getAllExtraOAuthDomains:()=>Fe,getAlternativeModelProviders:()=>je,getApiKey:()=>rt,getApiKeyForProvider:()=>z,getApiVersionForProvider:()=>Qe,getAvailableProviders:()=>w,getBaseUrl:()=>ot,getBaseUrlForProvider:()=>B,getDeploymentForProvider:()=>Ze,getExtraOAuthDomains:()=>Me,getOAuthAccountInfo:()=>k,getProviderConfig:()=>E,getProviderModels:()=>O,getRawApiKeyForProvider:()=>R,getSelectedModelId:()=>V,getSelectedProvider:()=>H,isModelHiddenFromPicker:()=>j,isUsableOAuthMaskReplica:()=>I,logoutOAuthAccount:()=>Re,maskOAuthTokenWithRetry:()=>ze,migrateLegacyAuthOnlySelection:()=>xe,modelRunsOnProvider:()=>ht,persistOAuthMaskViaServiceWorker:()=>L,policyVisible:()=>ke,providerOffersLlmModels:()=>T,removeAccount:()=>F,resolveCurrentModel:()=>K,resolveModelById:()=>G,resolveModelByShorthand:()=>gt,resolveModelIdForScoop:()=>St,resolveModelSelectionForScoop:()=>X,saveOAuthAccount:()=>Xe,setApiKey:()=>it,setBaseUrl:()=>st,setExtraOAuthDomains:()=>Ne,setExtraOAuthDomainsAsync:()=>Pe,setSelectedModelId:()=>$e,setSelectedProvider:()=>tt});const v=ee,y=d,b=`slicc_accounts`,x=`selected-model`,ve=[`slicc_provider`,`slicc_api_key`,`slicc_base_url`,`anthropic_api_key`,`api_provider`,`azure_resource`,`bedrock_region`],ye=new Set([`github`]);function S(e){let t;try{t=u()}catch{return!1}return t.includes(e)&&!a(e)}let C=!1;function be(){if(!C){C=!0;for(let e of ve)try{localStorage.removeItem(e)}catch{}xe()}}function xe(){try{let e=localStorage.getItem(x);if(e){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t);(ye.has(n)||S(n))&&localStorage.removeItem(x)}}}catch{}try{let e=localStorage.getItem(b);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let n=t.filter(e=>!(typeof e==`object`&&e&&typeof e.providerId==`string`&&S(e.providerId)));n.length!==t.length&&localStorage.setItem(b,JSON.stringify(n))}catch{}}function Se(){C=!1}const Ce={_resetLegacyCleanup:Se};function w(){let e=u().filter(a),t=i();return[...new Set([...e,...t])].filter(e=>!o(e)?.hidden)}function T(e){try{if(O(e).length>0)return!0}catch{}try{if(d(e).length>0)return!0}catch{}let t=o(e);return!!(t?.modelOverrides&&Object.keys(t.modelOverrides).length>0)}function we(e,t){try{if(O(e).some(e=>e.id===t))return!0}catch{}try{if(d(e).some(e=>e.id===t))return!0}catch{}let n=o(e);return!!(n?.modelOverrides&&Object.hasOwn(n.modelOverrides,t))}function E(e){return o(e)||{id:e,name:e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),description:`${e} provider`,requiresApiKey:!0,requiresBaseUrl:!1}}function D(e,t){t.context_window!==void 0&&(e.contextWindow=t.context_window),t.max_tokens!==void 0&&(e.maxTokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),t.cost!==void 0&&(e.cost=t.cost,e.inputCost=t.cost.input,e.outputCost=t.cost.output,e.cacheReadCost=t.cost.cacheRead,e.cacheWriteCost=t.cost.cacheWrite),t.compat!==void 0&&(e.compat={...e.compat??{},...t.compat}),t.thinkingLevelMap!==void 0&&(e.thinkingLevelMap={...e.thinkingLevelMap??{},...t.thinkingLevelMap})}function O(e){try{if(e===`bedrock-camp`){let e=re(B(`bedrock-camp`));return y(`amazon-bedrock`).filter(t=>te(t,e)).map(e=>({...e,api:`bedrock-camp-converse`,provider:`bedrock-camp`,reasoning:e.reasoning===!0&&ne(e)}))}let t=E(e);if(t.getModelIds){let n;try{n=t.getModelIds()}catch(t){return A.error(`Provider getModelIds callback failed`,{providerId:e,error:t instanceof Error?t.message:String(t)}),[]}let r=new Map;for(let e of u())try{for(let t of y(e))r.set(t.id,t)}catch{}return n.map(n=>{let i=n.api===`openai`?`openai`:`anthropic`,a=`${e}-${i}`,o=r.get(n.id),s;if(o)s={...o,api:a,provider:e};else if(s=U(e,n.id,``,a),n.name&&(s.name=n.name),i===`anthropic`){let e=se(n.id,r);s.cost=e,s.inputCost=e.input,s.outputCost=e.output,s.cacheReadCost=e.cacheRead,s.cacheWriteCost=e.cacheWrite}let c=t.modelOverrides?.[n.id];return c&&D(s,c),D(s,n),s})}if(t.isOAuth){let n=y(`anthropic`),r=`${e}-anthropic`;return n.map(n=>{let i={...n,api:r,provider:e},a=t.modelOverrides?.[n.id];return a&&D(i,a),i})}return y(e===`azure-ai-foundry`?`anthropic`:e)}catch(t){return A.error(`Failed to load models`,{providerId:e,error:t instanceof Error?t.message:String(t)}),[]}}function k(e){let t=M().find(t=>t.providerId===e);if(!t?.accessToken)return null;let n=!!t.tokenExpiresAt&&Date.now()>t.tokenExpiresAt-6e4;return{token:t.accessToken,maskedValue:t.maskedValue,expiresAt:t.tokenExpiresAt,userName:t.userName,userAvatar:t.userAvatar,scopes:t.scopes,expired:n}}const Te=Object.assign({})[`/packages/webapp/providers.json`]??[],A=t(`provider-settings`);function Ee(e=Te){if(e.length===0||M().length>0)return;let t=new Set(w());for(let n of e)if(!(!n.providerId||!n.apiKey)){if(!t.has(n.providerId)){A.warn(`Unknown provider "${n.providerId}" in providers.json — skipping`);continue}P(n.providerId,n.apiKey,n.baseUrl)}let n=e.find(e=>e.providerId&&e.apiKey&&t.has(e.providerId));n?.model&&!localStorage.getItem(x)&&localStorage.setItem(x,`${n.providerId}:${n.model}`)}const De=[/haiku/i];function j(e){return De.some(t=>t.test(e))}function Oe(e){return e.filter(e=>!j(e.id))}function ke(e,t){let n=Z();if(n===null)return e;let r=_();return e.filter(e=>!fe(r,n,t,e.id))}function Ae(){let e=M();if(e.length===0)return[];let t=new Map;for(let n of e){if(t.has(n.providerId))continue;let e=E(n.providerId);if(e.hidden||S(n.providerId))continue;let r=ke(Oe(O(n.providerId)),n.providerId);if(r.length===0)continue;let i={providerId:n.providerId,providerName:e.name,models:r};t.set(n.providerId,i)}return[...t.values()]}function je(e){return Ae().map(e=>e.providerId).filter(t=>t!==e)}function M(){be();let e=localStorage.getItem(b);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.providerId==`string`&&typeof e.apiKey==`string`):[]}catch{return[]}}function Me(e){return p(localStorage)[e]??[]}function Ne(e,t){let n=p(localStorage),r=t.map(e=>e.trim()).filter(e=>e.length>0);r.length===0?delete n[e]:n[e]=r,oe(localStorage,n)}async function Pe(e,t){if(r()){Ne(e,t);return}let i=n();if(!i)throw Error(`setExtraOAuthDomainsAsync: no DOM and no panel-rpc client — cannot persist to page localStorage`);let{storeAfter:a}=await i.call(`oauth-extras-set`,{providerId:e,domains:t});try{oe(localStorage,a)}catch(t){A.warn(`worker-shim mirror failed after successful page write — reload to refresh`,{providerId:e,error:t instanceof Error?t.message:String(t)})}}function Fe(){return p(localStorage)}function Ie(e){localStorage.setItem(b,JSON.stringify(e))}async function N(e){if(r()){Ie(e);return}let t=n();if(!t)throw Error(`saveAccountsAsync: no DOM and no panel-rpc client — cannot persist to page localStorage`);let i=JSON.stringify(e),{storedJson:a}=await t.call(`save-oauth-accounts`,{accountsJson:i});try{localStorage.setItem(b,a)}catch(e){A.warn(`worker-shim mirror failed after successful page write — reload to refresh`,{error:e instanceof Error?e.message:String(e)})}}function P(e,t,n,r,i){let a=M().filter(t=>t.providerId!==e),o={providerId:e,apiKey:t};n&&(o.baseUrl=n),r&&(o.deployment=r),i&&(o.apiVersion=i),a.push(o),Ie(a)}async function Le(e){let t=l();try{if(t===`extension-direct`){let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.delete`,name:`oauth.${e}.token`},n=>{chrome.runtime.lastError&&A.error(`SW secrets.delete transport failed`,{providerId:e,error:chrome.runtime.lastError.message}),t(n??{})})});t.error&&A.error(`SW secrets.delete returned error`,{providerId:e,error:t.error})}else if(t===`extension-delegate`){let t=await f(`secrets.delete`,{name:`oauth.${e}.token`});t?.error&&A.error(`Bridge secrets.delete returned error`,{providerId:e,error:t.error})}else if(t!==`connect`){let t=await fetch(s(`/api/secrets/oauth/${e}`),{method:`DELETE`,headers:c()});!t.ok&&t.status!==404&&A.warn(`OAuth replica DELETE non-ok`,{providerId:e,status:t.status})}}catch(n){A.error(`OAuth replica removal failed`,{providerId:e,topology:t,error:n instanceof Error?n.message:String(n)})}}async function F(e){let t=M().find(t=>t.providerId===e),n=E(e);t&&n?.isOAuth&&await Re(e),await Le(e),await N(M().filter(t=>t.providerId!==e));let r=localStorage.getItem(x)??``,i=r.indexOf(`:`);i>0&&r.slice(0,i)===e&&localStorage.removeItem(x)}async function Re(e){let t=M().find(t=>t.providerId===e);if(!t)return;let n=E(e);if(n?.isOAuth){if(n.onOAuthLogout)try{await n.onOAuthLogout()}catch(t){A.warn(`onOAuthLogout failed`,{providerId:e,error:t instanceof Error?t.message:String(t)})}if(n.getOAuthLogoutUrl){let r=n.getOAuthLogoutUrl(t);if(r){let{openIdpLogoutUrl:t}=await import(`./oauth-service-BZl-9EoE.js`);await t(r).catch(t=>{A.warn(`IdP logout popup failed`,{providerId:e,error:t instanceof Error?t.message:String(t)})})}}await N(M().map(t=>t.providerId===e?{providerId:t.providerId,apiKey:``,baseUrl:t.baseUrl,userName:t.userName,userAvatar:t.userAvatar,loggedOut:!0}:t)),await Le(e)}}async function ze(e,t={}){let n=Math.max(1,t.attempts??3),r=t.delayMs??150,i=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),a;for(let t=0;t<n;t++){let o=await e();if(o.maskedValue)return{maskedValue:o.maskedValue};o.error&&(a=o.error),t<n-1&&await i(r)}return{lastError:a}}const Be=`access token rotated during mask write`;function Ve(e,t,n,r){let i=r.find(t=>t.providerId===e);return i?.accessToken?i.accessToken===t?(i.maskedValue=n,{maskedValue:n}):(A.warn(`OAuth mask write raced with token rotation; discarding replica`,{providerId:e}),{error:Be}):{error:`account gone after mask write`}}function I(e,t){return!!e&&e!==t}async function L(e,t,n){let r={providerId:e.providerId,accessToken:e.accessToken,domains:e.domains.join(`,`)},{maskedValue:i,lastError:a}=await ze(()=>t.sendMaskRequest(r),n);if(!I(i,e.accessToken)){let t=i?`mask replica equals the access token`:a??`no error reported (cold SW or empty reply)`;return A.error(`OAuth mask give-up: no masked value after retries`,{providerId:e.providerId,reason:t}),{error:t}}let o=t.getAccounts(),s=Ve(e.providerId,e.accessToken,i,o);return s.maskedValue&&await t.saveAccounts(o),s}function He(e){let t=E(e).oauthTokenDomains??[],n=Me(e),r=new Set,i=[];for(let e of[...t,...n]){let t=e.toLowerCase();r.has(t)||(r.add(t),i.push(e))}return i}function Ue(e){return new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.mask-oauth-token`,...e},n=>{chrome.runtime.lastError&&A.error(`SW mask-oauth-token transport failed`,{providerId:e.providerId,error:chrome.runtime.lastError.message});let r=typeof n==`object`&&n?n:void 0;r?.error&&A.warn(`SW mask-oauth-token returned error`,{providerId:e.providerId,error:r.error}),t(r??{})})})}function We(e){return f(`secrets.mask-oauth-token`,e).then(t=>(t?.error&&A.warn(`Bridge mask-oauth-token returned error`,{providerId:e.providerId,error:t.error}),t??{})).catch(t=>(A.error(`Bridge mask-oauth-token transport failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)}),{}))}async function Ge(e,t,n){let r=s(`/api/secrets/oauth-update`),i=await fetch(r,{method:`POST`,headers:c({"Content-Type":`application/json`}),body:JSON.stringify({providerId:e,accessToken:t,domains:n})});if(!i.ok)return A.warn(`OAuth replica POST non-ok`,{providerId:e,status:i.status,url:r}),{error:`OAuth replica POST HTTP ${i.status}`};let a=await i.json();if(typeof a.maskedValue!=`string`)return A.warn(`OAuth replica POST ok but missing maskedValue`,{providerId:e,url:r}),{error:`OAuth replica POST ok but missing maskedValue`};if(!I(a.maskedValue,t))return A.error(`OAuth mask replica equals the access token; refusing to persist`,{providerId:e}),{error:`mask replica equals the access token`};let o=M(),l=Ve(e,t,a.maskedValue,o);return l.maskedValue&&await N(o),l}async function Ke(e,t){let n=await qe(e,t);if(n.error!==Be)return n;let r=M().find(t=>t.providerId===e)?.accessToken;return!r||r===t?n:qe(e,r)}async function qe(e,t){let n=He(e);if(n.length===0)return{error:`no oauth token domains configured`};let r=l();try{return r===`extension-direct`?L({providerId:e,accessToken:t,domains:n},{sendMaskRequest:Ue,getAccounts:M,saveAccounts:N}):r===`extension-delegate`?L({providerId:e,accessToken:t,domains:n},{sendMaskRequest:We,getAccounts:M,saveAccounts:N}):r===`connect`?{error:`no replica store in connect mode`}:await Ge(e,t,n)}catch(t){let n=t instanceof Error?t.message:String(t);return A.error(`OAuth replica sync failed`,{providerId:e,topology:r,error:n}),{error:n}}}async function Je(e){let t=M().find(t=>t.providerId===e);return t?.accessToken?I(t.maskedValue,t.accessToken)?{maskedValue:t.maskedValue}:Ke(e,t.accessToken):{error:`no access token held`}}function Ye(e,t){if(e.accessToken)return`scopes`in e?e.scopes:t?.scopes}async function Xe(e){let t=M().find(t=>t.providerId===e.providerId),n=M().filter(t=>t.providerId!==e.providerId);n.push({providerId:e.providerId,apiKey:``,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar,baseUrl:e.baseUrl??t?.baseUrl,scopes:Ye(e,t)}),await N(n),await Ke(e.providerId,e.accessToken)}function R(e){let t=M().find(t=>t.providerId===e);return t&&(t.accessToken||t.apiKey)||null}function z(e){let t=M().find(t=>t.providerId===e);return t?t.accessToken||t.apiKey||(E(e).optionalApiKey?`local`:null):null}function B(e){return M().find(t=>t.providerId===e)?.baseUrl??null}function Ze(e){return M().find(t=>t.providerId===e)?.deployment??null}function Qe(e){return M().find(t=>t.providerId===e)?.apiVersion??null}function V(){let e=localStorage.getItem(x)||``,t=e.indexOf(`:`);return t>=0?e.slice(t+1):e}function $e(e){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t),r=new Set([...i(),...w()]),a=n.includes(`.`);if(r.has(n)||!a){localStorage.setItem(x,e);return}}let n=H();localStorage.setItem(x,`${n}:${e}`)}function et(){return localStorage.getItem(x)||``}function H(){let e=et(),t=e.indexOf(`:`);if(t>0)return e.slice(0,t);let n=M(),r=V();if(r){let e=n.find(e=>T(e.providerId)&&we(e.providerId,r));if(e)return e.providerId}let i=n.find(e=>T(e.providerId));return i?i.providerId:n.length>0?n[0].providerId:`anthropic`}function tt(e){let t=V();localStorage.setItem(x,`${e}:${t}`)}function nt(){let e=V();localStorage.setItem(x,e)}function rt(){return z(H())}function it(e){let t=H();P(t,e,B(t)??void 0)}async function at(){await F(H())}function ot(){return B(H())}function st(e){let t=H(),n=R(t);n&&P(t,n,e||void 0)}function ct(){let e=H(),t=R(e);t&&P(e,t)}function lt(){let e=M(),t=H(),n=V();return e.map(e=>{let r={providerId:e.providerId,apiKey:e.apiKey};return e.baseUrl&&(r.baseUrl=e.baseUrl),e.providerId===t&&n&&(r.model=n),r})}async function ut(){let e=M();await Promise.allSettled(e.map(e=>F(e.providerId))),localStorage.removeItem(b),localStorage.removeItem(x);for(let e of ve)localStorage.removeItem(e)}function dt(e){return/^(?:gpt[-.]?|o[0-9]|chatgpt)/i.test(e)?`openai`:`anthropic`}function U(e,t,n,r){return{id:t,name:t,provider:e,api:r??`${e}-${dt(t)}`,baseUrl:n??``,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},reasoning:!0}}function W(e,t){return t.isOAuth||e===`azure-ai-foundry`?`anthropic`:e===`bedrock-camp`?`amazon-bedrock`:e}function ft(e,t,n){let r=O(e).find(e=>e.id===t);return r?n?{...r,baseUrl:n}:r:null}function pt(e,t,n,r){return n.isOAuth?O(t).find(e=>e.id===r)||{...e,api:`${t}-anthropic`,provider:t}:t===`bedrock-camp`?{...e,api:`bedrock-camp-converse`,provider:`bedrock-camp`}:e}function mt(e,t,n,r,i){if(t.isOAuth)return ft(e,n,r)??U(e,n,r);if(i)throw Error(`Model ${n} is not available from provider ${e}`);return K()}function G(e,t){if(!e)return K();let n=t??H(),r=B(n),i=E(n);if(t!==void 0){let t=ft(n,e,r);if(t)return t}try{let t=W(n,i),a=v(t,e);if(!a?.id)throw Error(`Model ${e} not found`);let o=pt(a,n,i,e);return r?{...o,baseUrl:r}:o}catch(a){return A.debug(`resolveModelById: pi-ai lookup miss, using provider fallback`,{providerId:n,modelId:e,error:a instanceof Error?a.message:String(a)}),mt(n,i,e,r,t!==void 0)}}function ht(e,t){return e.provider===t||e.provider===W(t,E(t))}function K(){let e=H(),t=V(),n=B(e),r=O(e),i=E(e),a=i.defaultModelId?r.find(e=>e.id.toLowerCase().includes(i.defaultModelId.toLowerCase()))?.id:void 0,o=t||a||r[0]?.id||`claude-sonnet-4-6`;try{let t=W(e,i),a=v(t,o);if(!a?.id)throw Error(`Model ${o} not found in ${t} registry`);let s=a;return i.isOAuth?s=r.find(e=>e.id===o)||{...s,api:`${e}-anthropic`,provider:e}:e===`bedrock-camp`&&(s={...s,api:`bedrock-camp-converse`,provider:`bedrock-camp`}),n&&(s={...s,baseUrl:n}),s}catch(t){A.debug(`resolveCurrentModel: pi-ai lookup miss, using provider fallback`,{providerId:e,effectiveModelId:o,error:t instanceof Error?t.message:String(t)});let a=r.find(e=>e.id===o);return a?n?{...a,baseUrl:n}:a:i.isOAuth?U(e,o,n):v(`anthropic`,`claude-sonnet-4-0`)}}function gt(e){let t=e.toLowerCase();if(!t)return null;let n=null;try{n=H()}catch{}if(n!==null){let e=q(t,[n]);if(e!==null)return e}return q(t,M().map(e=>e.providerId))}function q(e,t){let n=null,r=-1;for(let i of t)for(let t of O(i)){let i=t.id.toLowerCase(),a=(t.name??``).toLowerCase();if(!i.includes(e)&&!a.includes(e))continue;let o=t.contextWindow??0;(o>r||o===r&&Ct(t.id,n??``)>0)&&(r=o,n=t.id)}return n}function J(){let e=[];try{for(let t of M())e.includes(t.providerId)||e.push(t.providerId)}catch{}try{let t=H();e.includes(t)||e.push(t)}catch{}return e}function _t(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1)return null;let n=e.slice(0,t),r=e.slice(t+1),i=J().includes(n);if(i)return{providerId:n,modelId:r,configured:i};let a=!1;try{a=w().includes(n)}catch{}return a?{providerId:n,modelId:r,configured:!1}:null}function Y(e,t,n=!0){let r=[e],i=n?q(e.toLowerCase(),[t]):null;i!==null&&i!==e&&r.push(i);let a=[];try{a=O(t)}catch{}for(let n of r)if(!(a.length>0&&!a.some(e=>e.id===n)))try{if(G(n,t).id===n)return{modelId:n,providerId:t}}catch(r){A.debug(`selectModelFromProvider: candidate did not resolve`,{input:e,candidate:n,providerId:t,error:r instanceof Error?r.message:String(r)})}return null}function vt(e){return e.map(e=>`${e.providerId}:${e.modelId}`).join(`, `)}function X(e){if(!e)return{ok:!1,error:`unknown model: (empty)`};let t=_t(e);if(t)return bt(e,t);let n=null;try{n=H()}catch{}if(n!==null){let t=Y(e,n);if(t)return $(t)}return xt(e,n)}function Z(){try{return H()}catch{return null}}function Q(e){let t=Z();return t===null||pe(_(),t,e.providerId,e.modelId)}function yt(e){let t=Z()??`<none>`;return{ok:!1,error:`model not allowed: ${`${e.providerId}:${e.modelId}`} is blocked by ${m} while "${t}" is selected — ${ge(t,e.providerId,e.modelId)}`}}function $(e){return Q(e)?{ok:!0,selection:e}:yt(e)}function bt(e,t){if(!t.configured){let n=J();return{ok:!1,error:`unknown model: ${e} (provider "${t.providerId}" is not configured${n.length>0?`; configured: ${n.join(`, `)}`:``})`}}let n=Y(t.modelId,t.providerId);return n?$(n):{ok:!1,error:`unknown model: ${e} (provider "${t.providerId}" does not offer "${t.modelId}")`}}function xt(e,t){let n=J().filter(e=>e!==t);for(let t of[`exact`,`shorthand`]){let r=[];for(let i of n){let n=t===`exact`?e:q(e.toLowerCase(),[i]);if(n===null)continue;let a=Y(n,i,!1);a&&r.push(a)}let i=r.filter(Q);if(i.length===0&&r.length>0)return yt(r[0]);if(i.length===1)return{ok:!0,selection:i[0]};if(i.length>1)return{ok:!1,error:`ambiguous model: ${e} matches ${vt(i)} — qualify it as provider:model`}}return{ok:!1,error:`unknown model: ${e}`}}function St(e){let t=X(e);return t.ok?t.selection.modelId:null}function Ct(e,t){let n=e.match(/\d+/g)?.map(Number)??[],r=t.match(/\d+/g)?.map(Number)??[],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t}return 0}export{se as S,Xe as _,z as a,ue as b,Ze as c,V as d,H as f,X as g,G as h,rt as i,k as l,K as m,Je as n,Qe as o,ht as p,M as r,B as s,_e as t,O as u,m as v,he as x,h as y};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{n,r}from"./panel-rpc-BPwAqRch.js";import{n as i,o as a,t as o}from"./providers-DDqVLz05.js";import"./proxied-fetch-B57RqgUb.js";import{a as s,t as c}from"./api-endpoint-Lx_FU5cP.js";import{u as l}from"./core-D59qaXEb.js";import{i as u,n as ee,r as d}from"./compat-uEPf6-XW.js";import{t as f}from"./secrets-bridge-client-DBeju3mP.js";import{i as te,r as ne,t as re}from"./bedrock-camp-compat-99DjWBHV.js";import{o as ie}from"./claude-model-version-m5AAX9Oe.js";const ae=`slicc_oauth_extra_domains`;function p(e){try{let t=e.getItem(ae);if(!t)return{};let n=JSON.parse(t);if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n)){if(typeof e!=`string`||!Array.isArray(t))continue;let n=t.filter(e=>typeof e==`string`&&e.length>0);n.length>0&&(r[e]=n)}return r}catch{return{}}}function oe(e,t){try{e.setItem(ae,JSON.stringify(t))}catch(e){throw Error(`Failed to persist OAuth extras (localStorage quota exceeded?): ${e instanceof Error?e.message:String(e)}`)}}function se(e,t){let n={input:0,output:0,cacheRead:0,cacheWrite:0},r=ie(e);if(!r)return n;let i;for(let e of t.values()){let t=ie(e.id);!t||t.family!==r.family||(!i||t.major>i.major||t.major===i.major&&t.minor>i.minor)&&(i={major:t.major,minor:t.minor,cost:e.cost})}return i?.cost??n}const ce=t(`model-policy`),m=`/etc/models`;function h(){return{sections:{}}}function le(e){let t=e.indexOf(`#`);return(t===-1?e:e.slice(0,t)).trim()}function ue(e){let t=h();if(typeof e!=`string`)return t;let n=null;for(let r of e.split(/\r?\n/)){let e=le(r);if(!e)continue;let i=/^\[([^\]]+)\]$/.exec(e);if(i){n=i[1].trim(),t.sections[n]??=[];continue}if(n===null){ce.warn(`model policy entry before any [provider] section — ignored`,{entry:e});continue}let a=e.startsWith(`-`),o=a?e.slice(1).trim():e,s=o.indexOf(`:`);if(s<=0||s===o.length-1){ce.warn(`model policy entry is not provider:model — ignored`,{entry:e});continue}t.sections[n].push({providerId:o.slice(0,s).trim(),modelId:o.slice(s+1).trim(),deny:a})}return t}function g(e,t,n){return e.providerId===t?e.modelId===`*`||e.modelId===n:!1}function de(e,t){return e.sections[t]??[]}function fe(e,t,n,r){return de(e,t).some(e=>e.deny&&g(e,n,r))}function pe(e,t,n,r){let i=de(e,t);return i.some(e=>e.deny&&g(e,n,r))?!1:n===t||i.some(e=>!e.deny&&g(e,n,r))}let me=h();function he(e){me=e}function _(){return me}function ge(e,t,n){return`add \`${t}:${n}\` (or \`${t}:*\`) under \`[${e}]\` in ${m}`}var _e=e({ACCOUNTS_KEY:()=>b,__test__:()=>Ce,addAccount:()=>P,applyProviderDefaults:()=>Ee,clearAllSettings:()=>ut,clearApiKey:()=>at,clearBaseUrl:()=>ct,clearSelectedProvider:()=>nt,ensureOAuthMaskReplica:()=>Je,exportProviders:()=>lt,getAccounts:()=>M,getAllAvailableModels:()=>Ae,getAllExtraOAuthDomains:()=>Fe,getAlternativeModelProviders:()=>je,getApiKey:()=>rt,getApiKeyForProvider:()=>z,getApiVersionForProvider:()=>Qe,getAvailableProviders:()=>w,getBaseUrl:()=>ot,getBaseUrlForProvider:()=>B,getDeploymentForProvider:()=>Ze,getExtraOAuthDomains:()=>Me,getOAuthAccountInfo:()=>k,getProviderConfig:()=>E,getProviderModels:()=>O,getRawApiKeyForProvider:()=>R,getSelectedModelId:()=>V,getSelectedProvider:()=>H,isModelHiddenFromPicker:()=>j,isUsableOAuthMaskReplica:()=>I,logoutOAuthAccount:()=>Re,maskOAuthTokenWithRetry:()=>ze,migrateLegacyAuthOnlySelection:()=>xe,modelRunsOnProvider:()=>ht,persistOAuthMaskViaServiceWorker:()=>L,policyVisible:()=>ke,providerOffersLlmModels:()=>T,removeAccount:()=>F,resolveCurrentModel:()=>K,resolveModelById:()=>G,resolveModelByShorthand:()=>gt,resolveModelIdForScoop:()=>St,resolveModelSelectionForScoop:()=>X,saveOAuthAccount:()=>Xe,setApiKey:()=>it,setBaseUrl:()=>st,setExtraOAuthDomains:()=>Ne,setExtraOAuthDomainsAsync:()=>Pe,setSelectedModelId:()=>$e,setSelectedProvider:()=>tt});const v=ee,y=d,b=`slicc_accounts`,x=`selected-model`,ve=[`slicc_provider`,`slicc_api_key`,`slicc_base_url`,`anthropic_api_key`,`api_provider`,`azure_resource`,`bedrock_region`],ye=new Set([`github`]);function S(e){let t;try{t=u()}catch{return!1}return t.includes(e)&&!a(e)}let C=!1;function be(){if(!C){C=!0;for(let e of ve)try{localStorage.removeItem(e)}catch{}xe()}}function xe(){try{let e=localStorage.getItem(x);if(e){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t);(ye.has(n)||S(n))&&localStorage.removeItem(x)}}}catch{}try{let e=localStorage.getItem(b);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let n=t.filter(e=>!(typeof e==`object`&&e&&typeof e.providerId==`string`&&S(e.providerId)));n.length!==t.length&&localStorage.setItem(b,JSON.stringify(n))}catch{}}function Se(){C=!1}const Ce={_resetLegacyCleanup:Se};function w(){let e=u().filter(a),t=i();return[...new Set([...e,...t])].filter(e=>!o(e)?.hidden)}function T(e){try{if(O(e).length>0)return!0}catch{}try{if(d(e).length>0)return!0}catch{}let t=o(e);return!!(t?.modelOverrides&&Object.keys(t.modelOverrides).length>0)}function we(e,t){try{if(O(e).some(e=>e.id===t))return!0}catch{}try{if(d(e).some(e=>e.id===t))return!0}catch{}let n=o(e);return!!(n?.modelOverrides&&Object.hasOwn(n.modelOverrides,t))}function E(e){return o(e)||{id:e,name:e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),description:`${e} provider`,requiresApiKey:!0,requiresBaseUrl:!1}}function D(e,t){t.context_window!==void 0&&(e.contextWindow=t.context_window),t.max_tokens!==void 0&&(e.maxTokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),t.cost!==void 0&&(e.cost=t.cost,e.inputCost=t.cost.input,e.outputCost=t.cost.output,e.cacheReadCost=t.cost.cacheRead,e.cacheWriteCost=t.cost.cacheWrite),t.compat!==void 0&&(e.compat={...e.compat??{},...t.compat}),t.thinkingLevelMap!==void 0&&(e.thinkingLevelMap={...e.thinkingLevelMap??{},...t.thinkingLevelMap})}function O(e){try{if(e===`bedrock-camp`){let e=re(B(`bedrock-camp`));return y(`amazon-bedrock`).filter(t=>te(t,e)).map(e=>({...e,api:`bedrock-camp-converse`,provider:`bedrock-camp`,reasoning:e.reasoning===!0&&ne(e)}))}let t=E(e);if(t.getModelIds){let n;try{n=t.getModelIds()}catch(t){return A.error(`Provider getModelIds callback failed`,{providerId:e,error:t instanceof Error?t.message:String(t)}),[]}let r=new Map;for(let e of u())try{for(let t of y(e))r.set(t.id,t)}catch{}return n.map(n=>{let i=n.api===`openai`?`openai`:`anthropic`,a=`${e}-${i}`,o=r.get(n.id),s;if(o)s={...o,api:a,provider:e};else if(s=U(e,n.id,``,a),n.name&&(s.name=n.name),i===`anthropic`){let e=se(n.id,r);s.cost=e,s.inputCost=e.input,s.outputCost=e.output,s.cacheReadCost=e.cacheRead,s.cacheWriteCost=e.cacheWrite}let c=t.modelOverrides?.[n.id];return c&&D(s,c),D(s,n),s})}if(t.isOAuth){let n=y(`anthropic`),r=`${e}-anthropic`;return n.map(n=>{let i={...n,api:r,provider:e},a=t.modelOverrides?.[n.id];return a&&D(i,a),i})}return y(e===`azure-ai-foundry`?`anthropic`:e)}catch(t){return A.error(`Failed to load models`,{providerId:e,error:t instanceof Error?t.message:String(t)}),[]}}function k(e){let t=M().find(t=>t.providerId===e);if(!t?.accessToken)return null;let n=!!t.tokenExpiresAt&&Date.now()>t.tokenExpiresAt-6e4;return{token:t.accessToken,maskedValue:t.maskedValue,expiresAt:t.tokenExpiresAt,userName:t.userName,userAvatar:t.userAvatar,scopes:t.scopes,expired:n}}const Te=Object.assign({})[`/packages/webapp/providers.json`]??[],A=t(`provider-settings`);function Ee(e=Te){if(e.length===0||M().length>0)return;let t=new Set(w());for(let n of e)if(!(!n.providerId||!n.apiKey)){if(!t.has(n.providerId)){A.warn(`Unknown provider "${n.providerId}" in providers.json — skipping`);continue}P(n.providerId,n.apiKey,n.baseUrl)}let n=e.find(e=>e.providerId&&e.apiKey&&t.has(e.providerId));n?.model&&!localStorage.getItem(x)&&localStorage.setItem(x,`${n.providerId}:${n.model}`)}const De=[/haiku/i];function j(e){return De.some(t=>t.test(e))}function Oe(e){return e.filter(e=>!j(e.id))}function ke(e,t){let n=Z();if(n===null)return e;let r=_();return e.filter(e=>!fe(r,n,t,e.id))}function Ae(){let e=M();if(e.length===0)return[];let t=new Map;for(let n of e){if(t.has(n.providerId))continue;let e=E(n.providerId);if(e.hidden||S(n.providerId))continue;let r=ke(Oe(O(n.providerId)),n.providerId);if(r.length===0)continue;let i={providerId:n.providerId,providerName:e.name,models:r};t.set(n.providerId,i)}return[...t.values()]}function je(e){return Ae().map(e=>e.providerId).filter(t=>t!==e)}function M(){be();let e=localStorage.getItem(b);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.providerId==`string`&&typeof e.apiKey==`string`):[]}catch{return[]}}function Me(e){return p(localStorage)[e]??[]}function Ne(e,t){let n=p(localStorage),r=t.map(e=>e.trim()).filter(e=>e.length>0);r.length===0?delete n[e]:n[e]=r,oe(localStorage,n)}async function Pe(e,t){if(r()){Ne(e,t);return}let i=n();if(!i)throw Error(`setExtraOAuthDomainsAsync: no DOM and no panel-rpc client — cannot persist to page localStorage`);let{storeAfter:a}=await i.call(`oauth-extras-set`,{providerId:e,domains:t});try{oe(localStorage,a)}catch(t){A.warn(`worker-shim mirror failed after successful page write — reload to refresh`,{providerId:e,error:t instanceof Error?t.message:String(t)})}}function Fe(){return p(localStorage)}function Ie(e){localStorage.setItem(b,JSON.stringify(e))}async function N(e){if(r()){Ie(e);return}let t=n();if(!t)throw Error(`saveAccountsAsync: no DOM and no panel-rpc client — cannot persist to page localStorage`);let i=JSON.stringify(e),{storedJson:a}=await t.call(`save-oauth-accounts`,{accountsJson:i});try{localStorage.setItem(b,a)}catch(e){A.warn(`worker-shim mirror failed after successful page write — reload to refresh`,{error:e instanceof Error?e.message:String(e)})}}function P(e,t,n,r,i){let a=M().filter(t=>t.providerId!==e),o={providerId:e,apiKey:t};n&&(o.baseUrl=n),r&&(o.deployment=r),i&&(o.apiVersion=i),a.push(o),Ie(a)}async function Le(e){let t=l();try{if(t===`extension-direct`){let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.delete`,name:`oauth.${e}.token`},n=>{chrome.runtime.lastError&&A.error(`SW secrets.delete transport failed`,{providerId:e,error:chrome.runtime.lastError.message}),t(n??{})})});t.error&&A.error(`SW secrets.delete returned error`,{providerId:e,error:t.error})}else if(t===`extension-delegate`){let t=await f(`secrets.delete`,{name:`oauth.${e}.token`});t?.error&&A.error(`Bridge secrets.delete returned error`,{providerId:e,error:t.error})}else if(t!==`connect`){let t=await fetch(s(`/api/secrets/oauth/${e}`),{method:`DELETE`,headers:c()});!t.ok&&t.status!==404&&A.warn(`OAuth replica DELETE non-ok`,{providerId:e,status:t.status})}}catch(n){A.error(`OAuth replica removal failed`,{providerId:e,topology:t,error:n instanceof Error?n.message:String(n)})}}async function F(e){let t=M().find(t=>t.providerId===e),n=E(e);t&&n?.isOAuth&&await Re(e),await Le(e),await N(M().filter(t=>t.providerId!==e));let r=localStorage.getItem(x)??``,i=r.indexOf(`:`);i>0&&r.slice(0,i)===e&&localStorage.removeItem(x)}async function Re(e){let t=M().find(t=>t.providerId===e);if(!t)return;let n=E(e);if(n?.isOAuth){if(n.onOAuthLogout)try{await n.onOAuthLogout()}catch(t){A.warn(`onOAuthLogout failed`,{providerId:e,error:t instanceof Error?t.message:String(t)})}if(n.getOAuthLogoutUrl){let r=n.getOAuthLogoutUrl(t);if(r){let{openIdpLogoutUrl:t}=await import(`./oauth-service-BZl-9EoE.js`);await t(r).catch(t=>{A.warn(`IdP logout popup failed`,{providerId:e,error:t instanceof Error?t.message:String(t)})})}}await N(M().map(t=>t.providerId===e?{providerId:t.providerId,apiKey:``,baseUrl:t.baseUrl,userName:t.userName,userAvatar:t.userAvatar,loggedOut:!0}:t)),await Le(e)}}async function ze(e,t={}){let n=Math.max(1,t.attempts??3),r=t.delayMs??150,i=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),a;for(let t=0;t<n;t++){let o=await e();if(o.maskedValue)return{maskedValue:o.maskedValue};o.error&&(a=o.error),t<n-1&&await i(r)}return{lastError:a}}const Be=`access token rotated during mask write`;function Ve(e,t,n,r){let i=r.find(t=>t.providerId===e);return i?.accessToken?i.accessToken===t?(i.maskedValue=n,{maskedValue:n}):(A.warn(`OAuth mask write raced with token rotation; discarding replica`,{providerId:e}),{error:Be}):{error:`account gone after mask write`}}function I(e,t){return!!e&&e!==t}async function L(e,t,n){let r={providerId:e.providerId,accessToken:e.accessToken,domains:e.domains.join(`,`)},{maskedValue:i,lastError:a}=await ze(()=>t.sendMaskRequest(r),n);if(!I(i,e.accessToken)){let t=i?`mask replica equals the access token`:a??`no error reported (cold SW or empty reply)`;return A.error(`OAuth mask give-up: no masked value after retries`,{providerId:e.providerId,reason:t}),{error:t}}let o=t.getAccounts(),s=Ve(e.providerId,e.accessToken,i,o);return s.maskedValue&&await t.saveAccounts(o),s}function He(e){let t=E(e).oauthTokenDomains??[],n=Me(e),r=new Set,i=[];for(let e of[...t,...n]){let t=e.toLowerCase();r.has(t)||(r.add(t),i.push(e))}return i}function Ue(e){return new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.mask-oauth-token`,...e},n=>{chrome.runtime.lastError&&A.error(`SW mask-oauth-token transport failed`,{providerId:e.providerId,error:chrome.runtime.lastError.message});let r=typeof n==`object`&&n?n:void 0;r?.error&&A.warn(`SW mask-oauth-token returned error`,{providerId:e.providerId,error:r.error}),t(r??{})})})}function We(e){return f(`secrets.mask-oauth-token`,e).then(t=>(t?.error&&A.warn(`Bridge mask-oauth-token returned error`,{providerId:e.providerId,error:t.error}),t??{})).catch(t=>(A.error(`Bridge mask-oauth-token transport failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)}),{}))}async function Ge(e,t,n){let r=s(`/api/secrets/oauth-update`),i=await fetch(r,{method:`POST`,headers:c({"Content-Type":`application/json`}),body:JSON.stringify({providerId:e,accessToken:t,domains:n})});if(!i.ok)return A.warn(`OAuth replica POST non-ok`,{providerId:e,status:i.status,url:r}),{error:`OAuth replica POST HTTP ${i.status}`};let a=await i.json();if(typeof a.maskedValue!=`string`)return A.warn(`OAuth replica POST ok but missing maskedValue`,{providerId:e,url:r}),{error:`OAuth replica POST ok but missing maskedValue`};if(!I(a.maskedValue,t))return A.error(`OAuth mask replica equals the access token; refusing to persist`,{providerId:e}),{error:`mask replica equals the access token`};let o=M(),l=Ve(e,t,a.maskedValue,o);return l.maskedValue&&await N(o),l}async function Ke(e,t){let n=await qe(e,t);if(n.error!==Be)return n;let r=M().find(t=>t.providerId===e)?.accessToken;return!r||r===t?n:qe(e,r)}async function qe(e,t){let n=He(e);if(n.length===0)return{error:`no oauth token domains configured`};let r=l();try{return r===`extension-direct`?L({providerId:e,accessToken:t,domains:n},{sendMaskRequest:Ue,getAccounts:M,saveAccounts:N}):r===`extension-delegate`?L({providerId:e,accessToken:t,domains:n},{sendMaskRequest:We,getAccounts:M,saveAccounts:N}):r===`connect`?{error:`no replica store in connect mode`}:await Ge(e,t,n)}catch(t){let n=t instanceof Error?t.message:String(t);return A.error(`OAuth replica sync failed`,{providerId:e,topology:r,error:n}),{error:n}}}async function Je(e){let t=M().find(t=>t.providerId===e);return t?.accessToken?I(t.maskedValue,t.accessToken)?{maskedValue:t.maskedValue}:Ke(e,t.accessToken):{error:`no access token held`}}function Ye(e,t){if(e.accessToken)return`scopes`in e?e.scopes:t?.scopes}async function Xe(e){let t=M().find(t=>t.providerId===e.providerId),n=M().filter(t=>t.providerId!==e.providerId);n.push({providerId:e.providerId,apiKey:``,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar,baseUrl:e.baseUrl??t?.baseUrl,scopes:Ye(e,t)}),await N(n),await Ke(e.providerId,e.accessToken)}function R(e){let t=M().find(t=>t.providerId===e);return t&&(t.accessToken||t.apiKey)||null}function z(e){let t=M().find(t=>t.providerId===e);return t?t.accessToken||t.apiKey||(E(e).optionalApiKey?`local`:null):null}function B(e){return M().find(t=>t.providerId===e)?.baseUrl??null}function Ze(e){return M().find(t=>t.providerId===e)?.deployment??null}function Qe(e){return M().find(t=>t.providerId===e)?.apiVersion??null}function V(){let e=localStorage.getItem(x)||``,t=e.indexOf(`:`);return t>=0?e.slice(t+1):e}function $e(e){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t),r=new Set([...i(),...w()]),a=n.includes(`.`);if(r.has(n)||!a){localStorage.setItem(x,e);return}}let n=H();localStorage.setItem(x,`${n}:${e}`)}function et(){return localStorage.getItem(x)||``}function H(){let e=et(),t=e.indexOf(`:`);if(t>0)return e.slice(0,t);let n=M(),r=V();if(r){let e=n.find(e=>T(e.providerId)&&we(e.providerId,r));if(e)return e.providerId}let i=n.find(e=>T(e.providerId));return i?i.providerId:n.length>0?n[0].providerId:`anthropic`}function tt(e){let t=V();localStorage.setItem(x,`${e}:${t}`)}function nt(){let e=V();localStorage.setItem(x,e)}function rt(){return z(H())}function it(e){let t=H();P(t,e,B(t)??void 0)}async function at(){await F(H())}function ot(){return B(H())}function st(e){let t=H(),n=R(t);n&&P(t,n,e||void 0)}function ct(){let e=H(),t=R(e);t&&P(e,t)}function lt(){let e=M(),t=H(),n=V();return e.map(e=>{let r={providerId:e.providerId,apiKey:e.apiKey};return e.baseUrl&&(r.baseUrl=e.baseUrl),e.providerId===t&&n&&(r.model=n),r})}async function ut(){let e=M();await Promise.allSettled(e.map(e=>F(e.providerId))),localStorage.removeItem(b),localStorage.removeItem(x);for(let e of ve)localStorage.removeItem(e)}function dt(e){return/^(?:gpt[-.]?|o[0-9]|chatgpt)/i.test(e)?`openai`:`anthropic`}function U(e,t,n,r){return{id:t,name:t,provider:e,api:r??`${e}-${dt(t)}`,baseUrl:n??``,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},reasoning:!0}}function W(e,t){return t.isOAuth||e===`azure-ai-foundry`?`anthropic`:e===`bedrock-camp`?`amazon-bedrock`:e}function ft(e,t,n){let r=O(e).find(e=>e.id===t);return r?n?{...r,baseUrl:n}:r:null}function pt(e,t,n,r){return n.isOAuth?O(t).find(e=>e.id===r)||{...e,api:`${t}-anthropic`,provider:t}:t===`bedrock-camp`?{...e,api:`bedrock-camp-converse`,provider:`bedrock-camp`}:e}function mt(e,t,n,r,i){if(t.isOAuth)return ft(e,n,r)??U(e,n,r);if(i)throw Error(`Model ${n} is not available from provider ${e}`);return K()}function G(e,t){if(!e)return K();let n=t??H(),r=B(n),i=E(n);if(t!==void 0){let t=ft(n,e,r);if(t)return t}try{let t=W(n,i),a=v(t,e);if(!a?.id)throw Error(`Model ${e} not found`);let o=pt(a,n,i,e);return r?{...o,baseUrl:r}:o}catch(a){return A.debug(`resolveModelById: pi-ai lookup miss, using provider fallback`,{providerId:n,modelId:e,error:a instanceof Error?a.message:String(a)}),mt(n,i,e,r,t!==void 0)}}function ht(e,t){return e.provider===t||e.provider===W(t,E(t))}function K(){let e=H(),t=V(),n=B(e),r=O(e),i=E(e),a=i.defaultModelId?r.find(e=>e.id.toLowerCase().includes(i.defaultModelId.toLowerCase()))?.id:void 0,o=t||a||r[0]?.id||`claude-sonnet-4-6`;try{let t=W(e,i),a=v(t,o);if(!a?.id)throw Error(`Model ${o} not found in ${t} registry`);let s=a;return i.isOAuth?s=r.find(e=>e.id===o)||{...s,api:`${e}-anthropic`,provider:e}:e===`bedrock-camp`&&(s={...s,api:`bedrock-camp-converse`,provider:`bedrock-camp`}),n&&(s={...s,baseUrl:n}),s}catch(t){A.debug(`resolveCurrentModel: pi-ai lookup miss, using provider fallback`,{providerId:e,effectiveModelId:o,error:t instanceof Error?t.message:String(t)});let a=r.find(e=>e.id===o);return a?n?{...a,baseUrl:n}:a:i.isOAuth?U(e,o,n):v(`anthropic`,`claude-sonnet-4-0`)}}function gt(e){let t=e.toLowerCase();if(!t)return null;let n=null;try{n=H()}catch{}if(n!==null){let e=q(t,[n]);if(e!==null)return e}return q(t,M().map(e=>e.providerId))}function q(e,t){let n=null,r=-1;for(let i of t)for(let t of O(i)){let i=t.id.toLowerCase(),a=(t.name??``).toLowerCase();if(!i.includes(e)&&!a.includes(e))continue;let o=t.contextWindow??0;(o>r||o===r&&Ct(t.id,n??``)>0)&&(r=o,n=t.id)}return n}function J(){let e=[];try{for(let t of M())e.includes(t.providerId)||e.push(t.providerId)}catch{}try{let t=H();e.includes(t)||e.push(t)}catch{}return e}function _t(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1)return null;let n=e.slice(0,t),r=e.slice(t+1),i=J().includes(n);if(i)return{providerId:n,modelId:r,configured:i};let a=!1;try{a=w().includes(n)}catch{}return a?{providerId:n,modelId:r,configured:!1}:null}function Y(e,t,n=!0){let r=[e],i=n?q(e.toLowerCase(),[t]):null;i!==null&&i!==e&&r.push(i);let a=[];try{a=O(t)}catch{}for(let n of r)if(!(a.length>0&&!a.some(e=>e.id===n)))try{if(G(n,t).id===n)return{modelId:n,providerId:t}}catch(r){A.debug(`selectModelFromProvider: candidate did not resolve`,{input:e,candidate:n,providerId:t,error:r instanceof Error?r.message:String(r)})}return null}function vt(e){return e.map(e=>`${e.providerId}:${e.modelId}`).join(`, `)}function X(e){if(!e)return{ok:!1,error:`unknown model: (empty)`};let t=_t(e);if(t)return bt(e,t);let n=null;try{n=H()}catch{}if(n!==null){let t=Y(e,n);if(t)return $(t)}return xt(e,n)}function Z(){try{return H()}catch{return null}}function Q(e){let t=Z();return t===null||pe(_(),t,e.providerId,e.modelId)}function yt(e){let t=Z()??`<none>`;return{ok:!1,error:`model not allowed: ${`${e.providerId}:${e.modelId}`} is blocked by ${m} while "${t}" is selected — ${ge(t,e.providerId,e.modelId)}`}}function $(e){return Q(e)?{ok:!0,selection:e}:yt(e)}function bt(e,t){if(!t.configured){let n=J();return{ok:!1,error:`unknown model: ${e} (provider "${t.providerId}" is not configured${n.length>0?`; configured: ${n.join(`, `)}`:``})`}}let n=Y(t.modelId,t.providerId);return n?$(n):{ok:!1,error:`unknown model: ${e} (provider "${t.providerId}" does not offer "${t.modelId}")`}}function xt(e,t){let n=J().filter(e=>e!==t);for(let t of[`exact`,`shorthand`]){let r=[];for(let i of n){let n=t===`exact`?e:q(e.toLowerCase(),[i]);if(n===null)continue;let a=Y(n,i,!1);a&&r.push(a)}let i=r.filter(Q);if(i.length===0&&r.length>0)return yt(r[0]);if(i.length===1)return{ok:!0,selection:i[0]};if(i.length>1)return{ok:!1,error:`ambiguous model: ${e} matches ${vt(i)} — qualify it as provider:model`}}return{ok:!1,error:`unknown model: ${e}`}}function St(e){let t=X(e);return t.ok?t.selection.modelId:null}function Ct(e,t){let n=e.match(/\d+/g)?.map(Number)??[],r=t.match(/\d+/g)?.map(Number)??[],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t}return 0}export{se as S,Xe as _,z as a,ue as b,Ze as c,V as d,H as f,X as g,G as h,rt as i,k as l,K as m,Je as n,Qe as o,ht as p,M as r,B as s,_e as t,O as u,m as v,he as x,h as y};
@@ -1 +1 @@
1
- import{n as e}from"./panel-rpc-BPwAqRch.js";import{S as t,_ as n,r,s as i}from"./account-store-D5-EuwRH.js";import{a}from"./diagnostics-DN_idNHx.js";import{a as o,i as s,r as c}from"./compat-uEPf6-XW.js";import{a as l,r as u,s as d,t as f}from"./legacy-api-aliases-jKEvBgOL.js";import{i as p,n as m,r as h}from"./claude-model-version-m5AAX9Oe.js";import{n as g}from"./budget-usage-source-CsYOdKgf.js";import{r as _}from"./provider-budget-DbHWq3j6.js";import{n as v}from"./llm-session-id-BZyXP_j2.js";import{n as y,t as ee}from"./silent-renew-backoff-DIMz5UqB.js";import{getOAuthPageOrigin as te}from"./oauth-service-BZl-9EoE.js";import{n as b}from"./temperature-support-LHBt3FMX.js";import"./provider-settings-C9aYrpFT.js";var ne={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function re(e,t){return m(e,t)}function x(e,t,n){return e!==`xhigh`||!t?e:p(t,n)?`xhigh`:h(t,n)?`max`:`high`}function ie(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return x((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ae(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function S(e,t){if(!re(e.id,e.name))return t;let n=t,r=x(n.effort??ie(n.reasoning,e),e.id,e.name);return{...t,onPayload:ae(r,n.onPayload)}}function oe(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}async function se(e,t,n,r={}){let i=typeof AbortController==`function`?new AbortController:null,a=i?setTimeout(()=>i.abort(),r.timeoutMs??8e3):null;try{let a=await n(`${e.replace(/\/$/,``)}/v1/usage`,{headers:{...r.headers,Authorization:`Bearer ${t}`},...i?{signal:i.signal}:{}});if(a.status===404||a.status===501)return null;if(!a.ok)throw Error(`Adobe /v1/usage returned ${a.status}`);return _(await a.json())}finally{a&&clearTimeout(a)}}const C=Object.assign({"/packages/webapp/providers/adobe-config.json":ne})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function w(){let e=i(`adobe`);if(e)return e.replace(/\/$/,``);if(C.proxyEndpoint)return C.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const T=new Map,ce=new Map,le=`slicc-adobe-models`;function E(e){try{localStorage.setItem(le,JSON.stringify(e))}catch{}}async function D(e){try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`6.149.0`}});return t.ok?await t.json():(console.warn(`[adobe] Proxy /v1/config returned ${t.status}`),null)}catch(e){return console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e)),null}}async function O(e){let t=T.get(e);if(t)return t;let n=await D(e);return n||=(await new Promise(e=>setTimeout(e,600)),await D(e)),n?(T.set(e,n),n):{}}function k(e){let t=e.clientId||C.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function A(e){return e.scopes||C.scopes}function j(e){return e.imsEnvironment||C.imsEnvironment||`prod`}const M={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function N(e){return M[e??C.imsEnvironment??`prod`]??M.prod}async function P(){let e;try{e=w()}catch{return{}}return T.get(e)||new Promise(t=>{let n=setTimeout(()=>t({}),5e3),r=e=>{clearTimeout(n),t(e)};O(e).then(r,()=>r({}))})}function F(e){try{let t=e.split(`.`)[1];if(!t)return;let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n+`=`.repeat((4-n.length%4)%4)),i=JSON.parse(r);return typeof i.client_id==`string`?i.client_id:void 0}catch{return}}const I=typeof chrome<`u`&&!!chrome?.runtime?.id;function L(){return r().find(e=>e.providerId===`adobe`)}const ue=[`/ims/profile/v1`,`/ims/userinfo/v2`];async function de(e,t){try{let n=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){console.warn(`[adobe] Profile fetch ${e} returned ${n.status}`);return}let r=await n.json(),i=r.displayName||r.name||r.email;return i?{name:i,avatar:r.picture||r.avatar_url}:void 0}catch(t){console.warn(`[adobe] Profile fetch ${e} failed:`,t instanceof Error?t.message:String(t));return}}async function fe(e,t){for(let n of ue){let r=await de(`${N(t)}${n}`,e);if(r)return r}return console.warn(`[adobe] No IMS profile endpoint named the user; account will have no display name`),{}}async function pe(){let e=L(),t=e?.accessToken;if(!t)return{status:`unknown`,detail:`no stored token`};let n=await P(),r=F(t)||n.clientId||C.clientId||``;if(!r)return{status:`unknown`,detail:`no IMS client ID available`};let i=N(j(n));try{let n=await fetch(`${i}/ims/validate_token/v1`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:r,token:t,type:`access_token`}),signal:AbortSignal.timeout(1e4)});if(!n.ok)return{status:`unknown`,detail:`HTTP ${n.status}${n.statusText?` ${n.statusText}`:``}`};let a=await n.json();return a.valid===!0?{status:`accepted`,userName:e?.userName}:a.valid===!1?{status:`rejected`,detail:`IMS reported the token invalid (${typeof a.reason==`string`?a.reason:`no reason given`})`}:{status:`unknown`,detail:"IMS answered 200 without a boolean `valid` verdict"}}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10),scope:n.get(`scope`)??void 0}:null}const z={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!C.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`,`api.aem.live`],getBudgetUsage:he,getModelIds:()=>{let e=e=>oe(e,ce.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of T.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(le);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,t,r)=>{let i=w(),a=await O(i),o=k(a),s=A(a),c=j(a),l=I?null:await te(),u=I?null:y({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),d=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),r?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${N(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let _=R(h);if(!_){console.error(`[adobe] Could not extract token from redirect URL`);return}let v=await fe(_.accessToken,c);await n({providerId:`adobe`,accessToken:_.accessToken,tokenExpiresAt:Date.now()+_.expiresIn*1e3,userName:v.name,userAvatar:v.avatar,scopes:_.scope,baseUrl:C.proxyEndpoint?void 0:i}),g(),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=L();if(e?.accessToken)try{let t=await P(),n=F(e.accessToken)||t.clientId||C.clientId,r=j(t);if(n){let t=await fetch(`${N(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await n({providerId:`adobe`,accessToken:``}),g()},onSilentRenew:async()=>L()?.accessToken?U():null,onValidateToken:pe,refreshModels:async e=>{await $(e);let t=z.getModelIds?.();t?.length&&E(t)}};let B=null;const me=ee();async function V(){let e=L();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await me.run(()=>U());if(t)return t;let n=L();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}async function he(){let e;try{e=w()}catch{return null}let t=L();if(!t?.accessToken||H())throw Error(`Adobe budget: not signed in`);return se(e,t.accessToken,fetch,{headers:{"X-Session-Id":v(be)}})}function H(){let e=L();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function U(){if(typeof window>`u`){let t=e();if(!t)return null;try{let{accessToken:e}=await t.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return e}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return B===null&&(B=ye().finally(()=>{B=null})),B}function ge(e,t){let n=k(t),r=A(t),i=j(t),a=I?null:y({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),o=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${N(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function _e(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function ve(e,t){let r=L();await n({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:r?.userName,userAvatar:r?.userAvatar,scopes:e.scope,baseUrl:C.proxyEndpoint?void 0:t})}async function ye(){try{let e=w(),{authorizeUrl:t,expectedNonce:n}=ge(e,await O(e)),{createOAuthLauncher:r}=await import(`./oauth-service-BZl-9EoE.js`),i=await r()(t,{interactive:!1});if(!i||!_e(i,n))return null;let a=R(i);return a?(await ve(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`6.149.0`,{...e,headers:t}}const be=`adobe-usage-probe`,K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":v(`adobe-provider-fallback`)}}}function xe(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function Y(e){console.error(`[adobe] Stream error:`,e instanceof Error?e.message:String(e))}const X=(e,t,n={})=>{let r=a();return Se(r,e,t,n).catch(Y),r};async function Se(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=u(a,n,G(q({...r,apiKey:i},`streamAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=f(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}const Z=(e,t,n)=>{let r=a();return Ce(r,e,t,n).catch(Y),r};async function Ce(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=d(a,n,G(q({...r,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=l(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}function we(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function Te(){let e=new Map;for(let t of s())try{let n=c(t);for(let t of n)e.set(t.id,t)}catch{}return e}function Ee(e,n,r){let i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`,a=r.get(e.id);if(a)return{...a,provider:`adobe`,api:i};let o=t(e.id,r);return{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:n,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:o,inputCost:o.input,outputCost:o.output,cacheReadCost:o.cacheRead,cacheWriteCost:o.cacheWrite,reasoning:!0}}function De(e,t){for(let t of e)ce.set(t.id,we(t));let n=Te();return e.map(e=>Ee(e,t,n))}async function Oe(e){try{let t=e??await V(),n=w(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`6.149.0`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return De(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function ke(){return c(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=w(),n=Q.get(t);if(n)return n;let r=await Oe(e);return r?(Q.set(t,r),r):ke()}function Ae(){o({api:`adobe-anthropic`,stream:X,streamSimple:Z}),o({api:`adobe-openai`,stream:X,streamSimple:Z})}export{xe as __resetAdobeSessionIdWarningCacheForTests,z as config,R as extractTokenFromUrl,$ as getAdobeModels,V as getValidAccessToken,H as isTokenExpired,Ae as register};
1
+ import{n as e}from"./panel-rpc-BPwAqRch.js";import{S as t,_ as n,r,s as i}from"./account-store-FB6hD_og.js";import{a}from"./diagnostics-DN_idNHx.js";import{a as o,i as s,r as c}from"./compat-uEPf6-XW.js";import{a as l,r as u,s as d,t as f}from"./legacy-api-aliases-jKEvBgOL.js";import{i as p,n as m,r as h}from"./claude-model-version-m5AAX9Oe.js";import{n as g}from"./budget-usage-source-D6zuo6Hu.js";import{r as _}from"./provider-budget-DbHWq3j6.js";import{n as v}from"./llm-session-id-BZyXP_j2.js";import{n as y,t as ee}from"./silent-renew-backoff-DIMz5UqB.js";import{getOAuthPageOrigin as te}from"./oauth-service-BZl-9EoE.js";import{n as b}from"./temperature-support-LHBt3FMX.js";import"./provider-settings-Vnae44M1.js";var ne={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function re(e,t){return m(e,t)}function x(e,t,n){return e!==`xhigh`||!t?e:p(t,n)?`xhigh`:h(t,n)?`max`:`high`}function ie(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return x((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ae(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function S(e,t){if(!re(e.id,e.name))return t;let n=t,r=x(n.effort??ie(n.reasoning,e),e.id,e.name);return{...t,onPayload:ae(r,n.onPayload)}}function oe(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}async function se(e,t,n,r={}){let i=typeof AbortController==`function`?new AbortController:null,a=i?setTimeout(()=>i.abort(),r.timeoutMs??8e3):null;try{let a=await n(`${e.replace(/\/$/,``)}/v1/usage`,{headers:{...r.headers,Authorization:`Bearer ${t}`},...i?{signal:i.signal}:{}});if(a.status===404||a.status===501)return null;if(!a.ok)throw Error(`Adobe /v1/usage returned ${a.status}`);return _(await a.json())}finally{a&&clearTimeout(a)}}const C=Object.assign({"/packages/webapp/providers/adobe-config.json":ne})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function w(){let e=i(`adobe`);if(e)return e.replace(/\/$/,``);if(C.proxyEndpoint)return C.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const T=new Map,ce=new Map,le=`slicc-adobe-models`;function E(e){try{localStorage.setItem(le,JSON.stringify(e))}catch{}}async function D(e){try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`6.150.0`}});return t.ok?await t.json():(console.warn(`[adobe] Proxy /v1/config returned ${t.status}`),null)}catch(e){return console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e)),null}}async function O(e){let t=T.get(e);if(t)return t;let n=await D(e);return n||=(await new Promise(e=>setTimeout(e,600)),await D(e)),n?(T.set(e,n),n):{}}function k(e){let t=e.clientId||C.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function A(e){return e.scopes||C.scopes}function j(e){return e.imsEnvironment||C.imsEnvironment||`prod`}const M={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function N(e){return M[e??C.imsEnvironment??`prod`]??M.prod}async function P(){let e;try{e=w()}catch{return{}}return T.get(e)||new Promise(t=>{let n=setTimeout(()=>t({}),5e3),r=e=>{clearTimeout(n),t(e)};O(e).then(r,()=>r({}))})}function F(e){try{let t=e.split(`.`)[1];if(!t)return;let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n+`=`.repeat((4-n.length%4)%4)),i=JSON.parse(r);return typeof i.client_id==`string`?i.client_id:void 0}catch{return}}const I=typeof chrome<`u`&&!!chrome?.runtime?.id;function L(){return r().find(e=>e.providerId===`adobe`)}const ue=[`/ims/profile/v1`,`/ims/userinfo/v2`];async function de(e,t){try{let n=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){console.warn(`[adobe] Profile fetch ${e} returned ${n.status}`);return}let r=await n.json(),i=r.displayName||r.name||r.email;return i?{name:i,avatar:r.picture||r.avatar_url}:void 0}catch(t){console.warn(`[adobe] Profile fetch ${e} failed:`,t instanceof Error?t.message:String(t));return}}async function fe(e,t){for(let n of ue){let r=await de(`${N(t)}${n}`,e);if(r)return r}return console.warn(`[adobe] No IMS profile endpoint named the user; account will have no display name`),{}}async function pe(){let e=L(),t=e?.accessToken;if(!t)return{status:`unknown`,detail:`no stored token`};let n=await P(),r=F(t)||n.clientId||C.clientId||``;if(!r)return{status:`unknown`,detail:`no IMS client ID available`};let i=N(j(n));try{let n=await fetch(`${i}/ims/validate_token/v1`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:r,token:t,type:`access_token`}),signal:AbortSignal.timeout(1e4)});if(!n.ok)return{status:`unknown`,detail:`HTTP ${n.status}${n.statusText?` ${n.statusText}`:``}`};let a=await n.json();return a.valid===!0?{status:`accepted`,userName:e?.userName}:a.valid===!1?{status:`rejected`,detail:`IMS reported the token invalid (${typeof a.reason==`string`?a.reason:`no reason given`})`}:{status:`unknown`,detail:"IMS answered 200 without a boolean `valid` verdict"}}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10),scope:n.get(`scope`)??void 0}:null}const z={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!C.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`,`api.aem.live`],getBudgetUsage:he,getModelIds:()=>{let e=e=>oe(e,ce.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of T.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(le);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,t,r)=>{let i=w(),a=await O(i),o=k(a),s=A(a),c=j(a),l=I?null:await te(),u=I?null:y({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),d=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),r?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${N(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let _=R(h);if(!_){console.error(`[adobe] Could not extract token from redirect URL`);return}let v=await fe(_.accessToken,c);await n({providerId:`adobe`,accessToken:_.accessToken,tokenExpiresAt:Date.now()+_.expiresIn*1e3,userName:v.name,userAvatar:v.avatar,scopes:_.scope,baseUrl:C.proxyEndpoint?void 0:i}),g(),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=L();if(e?.accessToken)try{let t=await P(),n=F(e.accessToken)||t.clientId||C.clientId,r=j(t);if(n){let t=await fetch(`${N(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await n({providerId:`adobe`,accessToken:``}),g()},onSilentRenew:async()=>L()?.accessToken?U():null,onValidateToken:pe,refreshModels:async e=>{await $(e);let t=z.getModelIds?.();t?.length&&E(t)}};let B=null;const me=ee();async function V(){let e=L();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await me.run(()=>U());if(t)return t;let n=L();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}async function he(){let e;try{e=w()}catch{return null}let t=L();if(!t?.accessToken||H())throw Error(`Adobe budget: not signed in`);return se(e,t.accessToken,fetch,{headers:{"X-Session-Id":v(be)}})}function H(){let e=L();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function U(){if(typeof window>`u`){let t=e();if(!t)return null;try{let{accessToken:e}=await t.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return e}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return B===null&&(B=ye().finally(()=>{B=null})),B}function ge(e,t){let n=k(t),r=A(t),i=j(t),a=I?null:y({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),o=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${N(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function _e(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function ve(e,t){let r=L();await n({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:r?.userName,userAvatar:r?.userAvatar,scopes:e.scope,baseUrl:C.proxyEndpoint?void 0:t})}async function ye(){try{let e=w(),{authorizeUrl:t,expectedNonce:n}=ge(e,await O(e)),{createOAuthLauncher:r}=await import(`./oauth-service-BZl-9EoE.js`),i=await r()(t,{interactive:!1});if(!i||!_e(i,n))return null;let a=R(i);return a?(await ve(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`6.150.0`,{...e,headers:t}}const be=`adobe-usage-probe`,K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":v(`adobe-provider-fallback`)}}}function xe(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function Y(e){console.error(`[adobe] Stream error:`,e instanceof Error?e.message:String(e))}const X=(e,t,n={})=>{let r=a();return Se(r,e,t,n).catch(Y),r};async function Se(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=u(a,n,G(q({...r,apiKey:i},`streamAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=f(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}const Z=(e,t,n)=>{let r=a();return Ce(r,e,t,n).catch(Y),r};async function Ce(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=d(a,n,G(q({...r,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=l(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}function we(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function Te(){let e=new Map;for(let t of s())try{let n=c(t);for(let t of n)e.set(t.id,t)}catch{}return e}function Ee(e,n,r){let i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`,a=r.get(e.id);if(a)return{...a,provider:`adobe`,api:i};let o=t(e.id,r);return{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:n,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:o,inputCost:o.input,outputCost:o.output,cacheReadCost:o.cacheRead,cacheWriteCost:o.cacheWrite,reasoning:!0}}function De(e,t){for(let t of e)ce.set(t.id,we(t));let n=Te();return e.map(e=>Ee(e,t,n))}async function Oe(e){try{let t=e??await V(),n=w(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`6.150.0`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return De(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function ke(){return c(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=w(),n=Q.get(t);if(n)return n;let r=await Oe(e);return r?(Q.set(t,r),r):ke()}function Ae(){o({api:`adobe-anthropic`,stream:X,streamSimple:Z}),o({api:`adobe-openai`,stream:X,streamSimple:Z})}export{xe as __resetAdobeSessionIdWarningCacheForTests,z as config,R as extractTokenFromUrl,$ as getAdobeModels,V as getValidAccessToken,H as isTokenExpired,Ae as register};