sliccy 2.50.0 → 2.50.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/node-server/chrome-launch.d.ts +57 -0
  2. package/dist/node-server/chrome-launch.js +74 -1
  3. package/dist/node-server/index.js +26 -5
  4. package/dist/ui/assets/{adobe-VlJOhvPz.js → adobe-DUtaWS08.js} +1 -1
  5. package/dist/ui/assets/{adobe-DVwtzHxI.js → adobe-DyivPKeZ.js} +1 -1
  6. package/dist/ui/assets/{agent-bridge-DsHLDU8V.js → agent-bridge-CwcUwWSd.js} +1 -1
  7. package/dist/ui/assets/{agent-message-to-chat-C6dml3OW.js → agent-message-to-chat-CImm2vOT.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-CAsn2pUF.js → azure-openai-CWUoVLgB.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-B8qTt0Fr.js → azure-openai-iR8v3vNp.js} +1 -1
  10. package/dist/ui/assets/{cdp-DKSAtFO4.js → cdp-BqE7lRro.js} +3 -3
  11. package/dist/ui/assets/cost-command-DbyN_w4x.js +1 -0
  12. package/dist/ui/assets/{es-BraVol3C.js → es-Dn0gWvf2.js} +1 -1
  13. package/dist/ui/assets/{fs-s0F9YT_h.js → fs-BHjUDaPI.js} +1 -1
  14. package/dist/ui/assets/{fs-CT7Y5NS0.js → fs-DR9Kg_gg.js} +2 -2
  15. package/dist/ui/assets/{github-CBcAkmch.js → github-C4yRzqy8.js} +1 -1
  16. package/dist/ui/assets/{github-C1HESy2C.js → github-_05uBVE2.js} +2 -2
  17. package/dist/ui/assets/{index-Cv13fIWN.js → index-BbIDJNZM.js} +5 -5
  18. package/dist/ui/assets/{kernel-worker-CqyRKXBm.js → kernel-worker-iLIRf2UW.js} +9 -9
  19. package/dist/ui/assets/{local-llm-DTDLm5Sb.js → local-llm-DDeUXsOw.js} +1 -1
  20. package/dist/ui/assets/{local-llm-Cy8fUfwX.js → local-llm-DQTKwWew.js} +1 -1
  21. package/dist/ui/assets/{magick-wasm-BbaIA46K.js → magick-wasm-Bxy887fy.js} +1 -1
  22. package/dist/ui/assets/{mount-D8M77aD2.js → mount-BlPJ6Tdt.js} +1 -1
  23. package/dist/ui/assets/{mount-DqdX0aJz.js → mount-XZ9QStv8.js} +2 -2
  24. package/dist/ui/assets/{nuke-command-BmCQQFws.js → nuke-command-DRPb3203.js} +1 -1
  25. package/dist/ui/assets/{oauth-bootstrap-rwNGPidZ.js → oauth-bootstrap-BcPvzxBK.js} +1 -1
  26. package/dist/ui/assets/{oauth-service-Jx8rqyjf.js → oauth-service-CfvA2rAX.js} +1 -1
  27. package/dist/ui/assets/{offscreen-client-NKbRDPeW.js → offscreen-client-D-QLFw1K.js} +1 -1
  28. package/dist/ui/assets/{onboarding-orchestrator-DoO86elX.js → onboarding-orchestrator-C9pDcsCa.js} +1 -1
  29. package/dist/ui/assets/{provider-settings-Fm4AIIxK.js → provider-settings-B_lSRZ0U.js} +1 -1
  30. package/dist/ui/assets/{provider-settings-CWTeejO7.js → provider-settings-DGXqU1Yt.js} +3 -3
  31. package/dist/ui/assets/{providers-FGQY_gVN.js → providers-B3LV-JEw.js} +1 -1
  32. package/dist/ui/assets/{spawn-DYz9wTw2.js → spawn-CGCJ3d87.js} +1 -1
  33. package/dist/ui/assets/{upgrade-detection-CFxvnEBe.js → upgrade-detection-BWEeiTSq.js} +1 -1
  34. package/dist/ui/index.html +4 -4
  35. package/dist/ui/packages/webapp/index.html +4 -4
  36. package/package.json +1 -1
  37. package/dist/ui/assets/cost-command-CZfmQkvX.js +0 -1
@@ -37,6 +37,46 @@ export declare function buildChromeLaunchArgs(options: {
37
37
  launchUrl: string;
38
38
  profile: ChromeLaunchProfile;
39
39
  }): string[];
40
+ /**
41
+ * Walk up from a Chrome executable path
42
+ * (`…/Foo.app/Contents/MacOS/Foo`) to its enclosing `.app` bundle so we
43
+ * can hand it to `/usr/bin/open -a`. Returns `null` on non-darwin
44
+ * platforms or bare-binary paths so the caller falls back to a direct
45
+ * exec (Linux/Windows have no LaunchServices equivalent).
46
+ */
47
+ export declare function resolveChromeAppBundle(executablePath: string, platform?: NodeJS.Platform): string | null;
48
+ export interface ChromeSpawnPlan {
49
+ command: string;
50
+ args: string[];
51
+ /**
52
+ * `true` when the spawn is routed through `/usr/bin/open` so
53
+ * LaunchServices owns the new Chrome process. The caller should rely
54
+ * on `DevToolsActivePort` for CDP port discovery in this mode because
55
+ * `open`'s stderr never carries Chrome's `DevTools listening on …`
56
+ * banner.
57
+ */
58
+ usesLaunchServices: boolean;
59
+ }
60
+ /**
61
+ * Decide how to spawn Chrome so macOS TCC attributes camera/microphone
62
+ * requests to Chrome itself rather than to whatever terminal launched
63
+ * `node`. On darwin, when we can resolve an enclosing `.app` bundle for
64
+ * the Chrome executable, route the spawn through
65
+ * `/usr/bin/open -n -a <bundle> -W --args …` so LaunchServices becomes
66
+ * Chrome's parent and TCC responsible process. Without this hop,
67
+ * `getUserMedia()` calls in Google Meet, Zoom, etc. hang forever on
68
+ * machines where the terminal app has never been granted camera/mic
69
+ * access (or has no `NS{Camera,Microphone}UsageDescription`).
70
+ *
71
+ * On Linux / Windows, fall back to a direct exec — neither platform has
72
+ * a LaunchServices equivalent, and they don't suffer the same TCC
73
+ * inheritance problem.
74
+ */
75
+ export declare function planChromeSpawn(options: {
76
+ executablePath: string;
77
+ chromeArgs: string[];
78
+ platform?: NodeJS.Platform;
79
+ }): ChromeSpawnPlan;
40
80
  export declare function findChromeExecutable(options?: FindChromeExecutableOptions): string | null;
41
81
  export declare function ensureQaProfileScaffold(projectRoot: string): Promise<ChromeLaunchProfile[]>;
42
82
  /**
@@ -59,6 +99,23 @@ export declare function parseCdpPortFromStderr(line: string): number | null;
59
99
  * partial line is carried forward to the next chunk.
60
100
  */
61
101
  export declare function waitForCdpPortFromStderr(child: ChildProcess, timeoutMs?: number): Promise<number>;
102
+ /**
103
+ * Delete a stale `<userDataDir>/DevToolsActivePort` left behind by a
104
+ * previous Chrome run before we spawn a new one. Otherwise
105
+ * `waitForCdpPortFromActivePortFile` can win the race instantly with the
106
+ * old port from a crashed / SIGKILL'd previous launch — Chrome only
107
+ * writes the file when its listener comes up, and never proactively
108
+ * clears it on shutdown. The file lives inside a profile directory that
109
+ * is reused across runs (both the dev `/tmp/browser-coding-agent-chrome`
110
+ * profile and the persistent `.qa/chrome/<profile>` QA profiles), so the
111
+ * stale-port window is real.
112
+ *
113
+ * ENOENT is fine (no previous run); other errors are swallowed too
114
+ * because a failure to unlink shouldn't block a launch — the worst case
115
+ * is the pre-existing stale-port behavior, which is what we want to
116
+ * avoid but is not worth crashing over.
117
+ */
118
+ export declare function clearStaleDevToolsActivePort(userDataDir: string): Promise<void>;
62
119
  /**
63
120
  * Poll `<userDataDir>/DevToolsActivePort` for the CDP port. Chrome writes
64
121
  * this file as soon as the DevTools listener is up — its first line is
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readdirSync } from 'fs';
2
- import { mkdir, readFile, writeFile } from 'fs/promises';
2
+ import { mkdir, readFile, unlink, writeFile } from 'fs/promises';
3
3
  import { homedir } from 'os';
4
4
  import { dirname, join } from 'path';
5
5
  /**
@@ -113,6 +113,55 @@ export function buildChromeLaunchArgs(options) {
113
113
  args.push(options.launchUrl);
114
114
  return args;
115
115
  }
116
+ /**
117
+ * Walk up from a Chrome executable path
118
+ * (`…/Foo.app/Contents/MacOS/Foo`) to its enclosing `.app` bundle so we
119
+ * can hand it to `/usr/bin/open -a`. Returns `null` on non-darwin
120
+ * platforms or bare-binary paths so the caller falls back to a direct
121
+ * exec (Linux/Windows have no LaunchServices equivalent).
122
+ */
123
+ export function resolveChromeAppBundle(executablePath, platform = process.platform) {
124
+ if (platform !== 'darwin')
125
+ return null;
126
+ const parts = executablePath.split('/');
127
+ for (let i = parts.length - 1; i >= 0; i--) {
128
+ if (parts[i]?.toLowerCase().endsWith('.app')) {
129
+ return parts.slice(0, i + 1).join('/');
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+ /**
135
+ * Decide how to spawn Chrome so macOS TCC attributes camera/microphone
136
+ * requests to Chrome itself rather than to whatever terminal launched
137
+ * `node`. On darwin, when we can resolve an enclosing `.app` bundle for
138
+ * the Chrome executable, route the spawn through
139
+ * `/usr/bin/open -n -a <bundle> -W --args …` so LaunchServices becomes
140
+ * Chrome's parent and TCC responsible process. Without this hop,
141
+ * `getUserMedia()` calls in Google Meet, Zoom, etc. hang forever on
142
+ * machines where the terminal app has never been granted camera/mic
143
+ * access (or has no `NS{Camera,Microphone}UsageDescription`).
144
+ *
145
+ * On Linux / Windows, fall back to a direct exec — neither platform has
146
+ * a LaunchServices equivalent, and they don't suffer the same TCC
147
+ * inheritance problem.
148
+ */
149
+ export function planChromeSpawn(options) {
150
+ const platform = options.platform ?? process.platform;
151
+ const bundle = resolveChromeAppBundle(options.executablePath, platform);
152
+ if (bundle) {
153
+ return {
154
+ command: '/usr/bin/open',
155
+ args: ['-n', '-a', bundle, '-W', '--args', ...options.chromeArgs],
156
+ usesLaunchServices: true,
157
+ };
158
+ }
159
+ return {
160
+ command: options.executablePath,
161
+ args: options.chromeArgs,
162
+ usesLaunchServices: false,
163
+ };
164
+ }
116
165
  function findPuppeteerChromeForTesting(options) {
117
166
  const cacheRoot = join(options.homeDir, '.cache', 'puppeteer', 'chrome');
118
167
  let entries;
@@ -369,6 +418,30 @@ export function waitForCdpPortFromStderr(child, timeoutMs = getDefaultCdpLaunchT
369
418
  });
370
419
  });
371
420
  }
421
+ /**
422
+ * Delete a stale `<userDataDir>/DevToolsActivePort` left behind by a
423
+ * previous Chrome run before we spawn a new one. Otherwise
424
+ * `waitForCdpPortFromActivePortFile` can win the race instantly with the
425
+ * old port from a crashed / SIGKILL'd previous launch — Chrome only
426
+ * writes the file when its listener comes up, and never proactively
427
+ * clears it on shutdown. The file lives inside a profile directory that
428
+ * is reused across runs (both the dev `/tmp/browser-coding-agent-chrome`
429
+ * profile and the persistent `.qa/chrome/<profile>` QA profiles), so the
430
+ * stale-port window is real.
431
+ *
432
+ * ENOENT is fine (no previous run); other errors are swallowed too
433
+ * because a failure to unlink shouldn't block a launch — the worst case
434
+ * is the pre-existing stale-port behavior, which is what we want to
435
+ * avoid but is not worth crashing over.
436
+ */
437
+ export async function clearStaleDevToolsActivePort(userDataDir) {
438
+ try {
439
+ await unlink(join(userDataDir, 'DevToolsActivePort'));
440
+ }
441
+ catch {
442
+ // Intentionally ignored — see docstring.
443
+ }
444
+ }
372
445
  /**
373
446
  * Poll `<userDataDir>/DevToolsActivePort` for the CDP port. Chrome writes
374
447
  * this file as soon as the DevTools listener is up — its first line is
@@ -12,7 +12,7 @@ import express from 'express';
12
12
  import { WebSocketServer, WebSocket } from 'ws';
13
13
  import { ElectronAppAlreadyRunningError, ElectronOverlayInjector, launchElectronApp, } from './electron-controller.js';
14
14
  import { getElectronAppPorts } from './electron-runtime.js';
15
- import { buildChromeLaunchArgs, ensureQaProfileScaffold, findChromeExecutable, resolveChromeLaunchProfile, waitForCdpPortFromStderr, } from './chrome-launch.js';
15
+ import { buildChromeLaunchArgs, clearStaleDevToolsActivePort, ensureQaProfileScaffold, findChromeExecutable, planChromeSpawn, resolveChromeLaunchProfile, waitForCdpPort, } from './chrome-launch.js';
16
16
  import { resolveCliBrowserLaunchUrl } from './launch-url.js';
17
17
  import { parseCliRuntimeFlags } from './runtime-flags.js';
18
18
  import { FileLogger } from './file-logger.js';
@@ -471,15 +471,36 @@ async function main() {
471
471
  launchUrl: browserLaunchUrl,
472
472
  profile: chromeProfile,
473
473
  });
474
- launchedBrowserProcess = spawn(chromePath, chromeArgs, {
474
+ // Profile directories are reused across runs (both the dev
475
+ // `/tmp/browser-coding-agent-chrome` profile and the persistent
476
+ // `.qa/chrome/<profile>` QA profiles). Chrome never proactively
477
+ // clears `DevToolsActivePort` on shutdown, so a stale file from a
478
+ // previous crash/SIGKILL would let our active-port-file poller win
479
+ // the race instantly with the wrong port. Clear it before spawn.
480
+ await clearStaleDevToolsActivePort(chromeProfile.userDataDir);
481
+ // On macOS, route through `/usr/bin/open` so LaunchServices owns the
482
+ // new Chrome process. Without this hop the terminal that started
483
+ // `node` stays in Chrome's TCC responsibility chain, which silently
484
+ // breaks `getUserMedia()` (camera/mic in Google Meet, Zoom, etc.)
485
+ // whenever the terminal hasn't already been granted camera/microphone
486
+ // access. With LaunchServices in the loop, Chrome becomes its own
487
+ // TCC responsible process and the user's
488
+ // `/Applications/Google Chrome.app` privacy grant applies as expected.
489
+ const spawnPlan = planChromeSpawn({ executablePath: chromePath, chromeArgs });
490
+ launchedBrowserProcess = spawn(spawnPlan.command, spawnPlan.args, {
475
491
  stdio: ['ignore', 'pipe', 'pipe'],
476
492
  detached: false,
477
493
  env: { ...process.env, GOOGLE_CRASHPAD_DISABLE: '1' },
478
494
  });
479
495
  launchedBrowserLabel = chromeProfile.displayName;
480
- // Parse the actual CDP port from Chrome's stderr before piping output.
481
- // Chrome prints "DevTools listening on ws://HOST:PORT/..." to stderr.
482
- const actualCdpPort = await waitForCdpPortFromStderr(launchedBrowserProcess);
496
+ // Use the stderr-vs-DevToolsActivePort race so we work in both
497
+ // direct-exec mode (Linux/Windows, or bare-binary fallbacks where
498
+ // stderr carries Chrome's banner) and LaunchServices mode (macOS,
499
+ // where stderr belongs to `open` and only the active-port file
500
+ // surfaces the real CDP port).
501
+ const actualCdpPort = await waitForCdpPort(launchedBrowserProcess, {
502
+ userDataDir: chromeProfile.userDataDir,
503
+ });
483
504
  CDP_PORT = actualCdpPort;
484
505
  console.log(`Chrome CDP listening on port ${CDP_PORT}`);
485
506
  pipeChildOutput(launchedBrowserProcess, 'chrome');
@@ -1 +1 @@
1
- import{a as e,f as t,t as n}from"./provider-settings-Fm4AIIxK.js";import{d as r,f as i,l as a,p as o,u as s}from"./bedrock-camp-9aDiXDk5.js";import{d as c,o as l,u}from"./transform-messages-uhk4b6os.js";import{getOAuthPageOrigin as d}from"./oauth-service-Jx8rqyjf.js";const f=Object.assign({"/packages/webapp/providers/adobe-config.json":{proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`}})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function p(){let t=e(`adobe`);if(t)return t.replace(/\/$/,``);if(f.proxyEndpoint)return f.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const m=new Map,h=new Map;async function g(e){let t=m.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[j]:`2.50.0`}});if(t.ok){let n=await t.json();return m.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}let n={};return m.set(e,n),n}function _(e){let t=e.clientId||f.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 v(e){return e.scopes||f.scopes}function y(e){return e.imsEnvironment||f.imsEnvironment||`prod`}const b={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function x(e){return b[e??f.imsEnvironment??`prod`]??b.prod}const S=typeof chrome<`u`&&!!chrome?.runtime?.id;function C(){return n().find(e=>e.providerId===`adobe`)}async function w(e,t){try{let n=await fetch(`${x(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function T(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)}:null}const E={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!f.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`],getModelIds:()=>{let e=e=>{let t={id:e.id,name:e.name??e.id},n=h.get(e.id);return n?.api&&(t.api=n.api),n?.context_window!==void 0&&(t.context_window=n.context_window),n?.max_tokens!==void 0&&(t.max_tokens=n.max_tokens),n?.reasoning!==void 0&&(t.reasoning=n.reasoning),n?.input&&(t.input=n.input),/haiku/i.test(e.id)&&(t.compat={supportsEagerToolInputStreaming:!1}),t};for(let t of L.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id}));try{localStorage.setItem(`slicc-adobe-models`,JSON.stringify(n))}catch{}return n}for(let t of m.values())if(t.models?.length)return t.models.map(e);try{let e=localStorage.getItem(`slicc-adobe-models`);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,n)=>{let r=p(),i=await g(r),a=_(i),o=v(i),s=y(i),c=S?null:await d(),l=S?f.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:f.redirectUri??`${c.origin}/auth/callback`,u=S?void 0:btoa(JSON.stringify({port:parseInt(new URL(c.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),m=u?JSON.parse(atob(u)).nonce:null,h=new URLSearchParams({client_id:a,scope:o,response_type:`token`,redirect_uri:l});u&&h.set(`state`,u);let b=await e(`${x(s)}/ims/authorize/v2?${h}`);if(!b)return;if(m&&b)try{if(new URL(b).searchParams.get(`nonce`)!==m){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 C=T(b);if(!C){console.error(`[adobe] Could not extract token from redirect URL`);return}let E=await w(C.accessToken,s);await t({providerId:`adobe`,accessToken:C.accessToken,tokenExpiresAt:Date.now()+C.expiresIn*1e3,userName:E.name,userAvatar:E.avatar,baseUrl:f.proxyEndpoint?void 0:r}),await R().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),n()},onOAuthLogout:async()=>{let e=C();if(e?.accessToken)try{let t=m.values().next().value??{},n=t.clientId||f.clientId,r=y(t);if(n){let t=await fetch(`${x(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 t({providerId:`adobe`,accessToken:``})},onSilentRenew:async()=>C()?.accessToken?A():null};let D=null;async function O(){let e=C();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...`);try{let e=await A();if(e)return e}catch(e){console.warn(`[adobe] Silent renewal failed:`,e instanceof Error?e.message:String(e))}let t=C();if((t?.tokenExpiresAt??0)-Date.now()>0&&t?.accessToken)return t.accessToken;throw Error(`Adobe session expired — please log in again`)}function k(){let e=C();return e?.tokenExpiresAt?Date.now()>e.tokenExpiresAt-6e4:!0}async function A(){return typeof window>`u`?null:D||(D=(async()=>{try{let e=p(),n=await g(e),r=_(n),i=v(n),a=y(n),o=S?f.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:f.redirectUri??`${window.location.origin}/auth/callback`,s=S?void 0:btoa(JSON.stringify({port:parseInt(new URL(window.location.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),c=s?JSON.parse(atob(s)).nonce:null,l=new URLSearchParams({client_id:r,scope:i,response_type:`token`,redirect_uri:o,prompt:`none`});s&&l.set(`state`,s);let u=`${x(a)}/ims/authorize/v2?${l}`,{createOAuthLauncher:d}=await import(`./oauth-service-Jx8rqyjf.js`),m=await d()(u);if(!m)return null;if(c&&m)try{if(new URL(m).searchParams.get(`nonce`)!==c)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),null}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let h=T(m);if(!h)return null;let b=C();return await t({providerId:`adobe`,accessToken:h.accessToken,tokenExpiresAt:Date.now()+h.expiresIn*1e3,userName:b?.userName,userAvatar:b?.userAvatar,baseUrl:f.proxyEndpoint?void 0:e}),console.log(`[adobe] Token renewed silently`),await R().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),h.accessToken}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}finally{D=null}})(),D)}const j=`X-Slicc-Version`;function M(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[j]=`2.50.0`,{...e,headers:t}}function N(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()}}}const P=(e,t,n={})=>{let r=l();return(async()=>{try{let i=await O();if(String(e.api).includes(`openai`)){let a=s({...e,baseUrl:`${p()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,M({...n,apiKey:i}));for await(let e of a)r.push(e)}else{let o=a({...e,baseUrl:p(),api:`anthropic-messages`},t,M({...n,apiKey:i}));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(N(e,t)),r.end()}})(),r},F=(e,t,n)=>{let a=l();return(async()=>{try{let o=await O();if(String(e.api).includes(`openai`)){let r=i({...e,baseUrl:`${p()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,M({...n,apiKey:o}));for await(let e of r)a.push(e)}else{let i=r({...e,baseUrl:p(),api:`anthropic-messages`},t,M({...n,apiKey:o}));for await(let e of i)a.push(e)}a.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),a.push(N(e,t)),a.end()}})(),a};async function I(){try{let e=await O(),t=p(),n=await fetch(`${t}/v1/models`,{headers:{Authorization:`Bearer ${e}`,[j]:`2.50.0`}});if(n.ok){let e=await n.json();if(e.data?.length){for(let t of e.data){let e={id:t.id,name:t.name};t.api!==void 0&&(e.api=t.api),t.context_window!==void 0&&(e.context_window=t.context_window),t.max_tokens!==void 0&&(e.max_tokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),h.set(t.id,e)}let n=new Map;for(let e of c())try{for(let t of u(e))n.set(t.id,t)}catch{}return e.data.map(e=>{let r=n.get(e.id),i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`;return r?{...r,provider:`adobe`,api:i}:{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:t,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},inputCost:0,outputCost:0,cacheReadCost:0,cacheWriteCost:0,reasoning:!0}})}}else console.warn(`[adobe] Proxy /v1/models returned ${n.status}, falling back to Anthropic models`)}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return u(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}const L=new Map;async function R(){let e=p(),t=L.get(e);if(t)return t;let n=await I();return L.set(e,n),n}function z(){o({api:`adobe-anthropic`,stream:P,streamSimple:F}),o({api:`adobe-openai`,stream:P,streamSimple:F})}export{E as config,R as getAdobeModels,O as getValidAccessToken,k as isTokenExpired,z as register};
1
+ import{a as e,f as t,t as n}from"./provider-settings-B_lSRZ0U.js";import{d as r,f as i,l as a,p as o,u as s}from"./bedrock-camp-9aDiXDk5.js";import{d as c,o as l,u}from"./transform-messages-uhk4b6os.js";import{getOAuthPageOrigin as d}from"./oauth-service-CfvA2rAX.js";const f=Object.assign({"/packages/webapp/providers/adobe-config.json":{proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`}})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function p(){let t=e(`adobe`);if(t)return t.replace(/\/$/,``);if(f.proxyEndpoint)return f.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const m=new Map,h=new Map;async function g(e){let t=m.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[j]:`2.50.2`}});if(t.ok){let n=await t.json();return m.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}let n={};return m.set(e,n),n}function _(e){let t=e.clientId||f.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 v(e){return e.scopes||f.scopes}function y(e){return e.imsEnvironment||f.imsEnvironment||`prod`}const b={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function x(e){return b[e??f.imsEnvironment??`prod`]??b.prod}const S=typeof chrome<`u`&&!!chrome?.runtime?.id;function C(){return n().find(e=>e.providerId===`adobe`)}async function w(e,t){try{let n=await fetch(`${x(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function T(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)}:null}const E={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!f.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`],getModelIds:()=>{let e=e=>{let t={id:e.id,name:e.name??e.id},n=h.get(e.id);return n?.api&&(t.api=n.api),n?.context_window!==void 0&&(t.context_window=n.context_window),n?.max_tokens!==void 0&&(t.max_tokens=n.max_tokens),n?.reasoning!==void 0&&(t.reasoning=n.reasoning),n?.input&&(t.input=n.input),/haiku/i.test(e.id)&&(t.compat={supportsEagerToolInputStreaming:!1}),t};for(let t of L.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id}));try{localStorage.setItem(`slicc-adobe-models`,JSON.stringify(n))}catch{}return n}for(let t of m.values())if(t.models?.length)return t.models.map(e);try{let e=localStorage.getItem(`slicc-adobe-models`);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,n)=>{let r=p(),i=await g(r),a=_(i),o=v(i),s=y(i),c=S?null:await d(),l=S?f.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:f.redirectUri??`${c.origin}/auth/callback`,u=S?void 0:btoa(JSON.stringify({port:parseInt(new URL(c.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),m=u?JSON.parse(atob(u)).nonce:null,h=new URLSearchParams({client_id:a,scope:o,response_type:`token`,redirect_uri:l});u&&h.set(`state`,u);let b=await e(`${x(s)}/ims/authorize/v2?${h}`);if(!b)return;if(m&&b)try{if(new URL(b).searchParams.get(`nonce`)!==m){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 C=T(b);if(!C){console.error(`[adobe] Could not extract token from redirect URL`);return}let E=await w(C.accessToken,s);await t({providerId:`adobe`,accessToken:C.accessToken,tokenExpiresAt:Date.now()+C.expiresIn*1e3,userName:E.name,userAvatar:E.avatar,baseUrl:f.proxyEndpoint?void 0:r}),await R().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),n()},onOAuthLogout:async()=>{let e=C();if(e?.accessToken)try{let t=m.values().next().value??{},n=t.clientId||f.clientId,r=y(t);if(n){let t=await fetch(`${x(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 t({providerId:`adobe`,accessToken:``})},onSilentRenew:async()=>C()?.accessToken?A():null};let D=null;async function O(){let e=C();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...`);try{let e=await A();if(e)return e}catch(e){console.warn(`[adobe] Silent renewal failed:`,e instanceof Error?e.message:String(e))}let t=C();if((t?.tokenExpiresAt??0)-Date.now()>0&&t?.accessToken)return t.accessToken;throw Error(`Adobe session expired — please log in again`)}function k(){let e=C();return e?.tokenExpiresAt?Date.now()>e.tokenExpiresAt-6e4:!0}async function A(){return typeof window>`u`?null:D||(D=(async()=>{try{let e=p(),n=await g(e),r=_(n),i=v(n),a=y(n),o=S?f.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:f.redirectUri??`${window.location.origin}/auth/callback`,s=S?void 0:btoa(JSON.stringify({port:parseInt(new URL(window.location.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),c=s?JSON.parse(atob(s)).nonce:null,l=new URLSearchParams({client_id:r,scope:i,response_type:`token`,redirect_uri:o,prompt:`none`});s&&l.set(`state`,s);let u=`${x(a)}/ims/authorize/v2?${l}`,{createOAuthLauncher:d}=await import(`./oauth-service-CfvA2rAX.js`),m=await d()(u);if(!m)return null;if(c&&m)try{if(new URL(m).searchParams.get(`nonce`)!==c)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),null}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let h=T(m);if(!h)return null;let b=C();return await t({providerId:`adobe`,accessToken:h.accessToken,tokenExpiresAt:Date.now()+h.expiresIn*1e3,userName:b?.userName,userAvatar:b?.userAvatar,baseUrl:f.proxyEndpoint?void 0:e}),console.log(`[adobe] Token renewed silently`),await R().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),h.accessToken}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}finally{D=null}})(),D)}const j=`X-Slicc-Version`;function M(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[j]=`2.50.2`,{...e,headers:t}}function N(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()}}}const P=(e,t,n={})=>{let r=l();return(async()=>{try{let i=await O();if(String(e.api).includes(`openai`)){let a=s({...e,baseUrl:`${p()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,M({...n,apiKey:i}));for await(let e of a)r.push(e)}else{let o=a({...e,baseUrl:p(),api:`anthropic-messages`},t,M({...n,apiKey:i}));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(N(e,t)),r.end()}})(),r},F=(e,t,n)=>{let a=l();return(async()=>{try{let o=await O();if(String(e.api).includes(`openai`)){let r=i({...e,baseUrl:`${p()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,M({...n,apiKey:o}));for await(let e of r)a.push(e)}else{let i=r({...e,baseUrl:p(),api:`anthropic-messages`},t,M({...n,apiKey:o}));for await(let e of i)a.push(e)}a.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),a.push(N(e,t)),a.end()}})(),a};async function I(){try{let e=await O(),t=p(),n=await fetch(`${t}/v1/models`,{headers:{Authorization:`Bearer ${e}`,[j]:`2.50.2`}});if(n.ok){let e=await n.json();if(e.data?.length){for(let t of e.data){let e={id:t.id,name:t.name};t.api!==void 0&&(e.api=t.api),t.context_window!==void 0&&(e.context_window=t.context_window),t.max_tokens!==void 0&&(e.max_tokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),h.set(t.id,e)}let n=new Map;for(let e of c())try{for(let t of u(e))n.set(t.id,t)}catch{}return e.data.map(e=>{let r=n.get(e.id),i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`;return r?{...r,provider:`adobe`,api:i}:{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:t,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},inputCost:0,outputCost:0,cacheReadCost:0,cacheWriteCost:0,reasoning:!0}})}}else console.warn(`[adobe] Proxy /v1/models returned ${n.status}, falling back to Anthropic models`)}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return u(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}const L=new Map;async function R(){let e=p(),t=L.get(e);if(t)return t;let n=await I();return L.set(e,n),n}function z(){o({api:`adobe-anthropic`,stream:P,streamSimple:F}),o({api:`adobe-openai`,stream:P,streamSimple:F})}export{E as config,R as getAdobeModels,O as getValidAccessToken,k as isTokenExpired,z as register};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/oauth-service-B7as8KRE.js","assets/panel-rpc-f0zFUOaZ.js","assets/chunk-jRWAZmH_.js"])))=>i.map(i=>d[i]);
2
- import{r as e,s as t,v as n}from"./provider-settings-CWTeejO7.js";import{t as r}from"./preload-helper-ca-nBW7U.js";import{c as i,l as a,o,s,u as c}from"./bedrock-camp-CqXHYC67.js";import{d as l,o as u,u as d}from"./simple-options-imi_RHvn.js";import{getOAuthPageOrigin as f}from"./oauth-service-B7as8KRE.js";var p=Object.assign({"/packages/webapp/providers/adobe-config.json":{proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`}})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function m(){let e=t(`adobe`);if(e)return e.replace(/\/$/,``);if(p.proxyEndpoint)return p.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}var h=new Map,g=new Map;async function _(e){let t=h.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[M]:`2.50.0`}});if(t.ok){let n=await t.json();return h.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}let n={};return h.set(e,n),n}function v(e){let t=e.clientId||p.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 y(e){return e.scopes||p.scopes}function b(e){return e.imsEnvironment||p.imsEnvironment||`prod`}var x={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function S(e){return x[e??p.imsEnvironment??`prod`]??x.prod}var C=typeof chrome<`u`&&!!chrome?.runtime?.id;function w(){return e().find(e=>e.providerId===`adobe`)}async function T(e,t){try{let n=await fetch(`${S(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function E(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)}:null}var D={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!p.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`],getModelIds:()=>{let e=e=>{let t={id:e.id,name:e.name??e.id},n=g.get(e.id);return n?.api&&(t.api=n.api),n?.context_window!==void 0&&(t.context_window=n.context_window),n?.max_tokens!==void 0&&(t.max_tokens=n.max_tokens),n?.reasoning!==void 0&&(t.reasoning=n.reasoning),n?.input&&(t.input=n.input),/haiku/i.test(e.id)&&(t.compat={supportsEagerToolInputStreaming:!1}),t};for(let t of R.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id}));try{localStorage.setItem(`slicc-adobe-models`,JSON.stringify(n))}catch{}return n}for(let t of h.values())if(t.models?.length)return t.models.map(e);try{let e=localStorage.getItem(`slicc-adobe-models`);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)=>{let r=m(),i=await _(r),a=v(i),o=y(i),s=b(i),c=C?null:await f(),l=C?p.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:p.redirectUri??`${c.origin}/auth/callback`,u=C?void 0:btoa(JSON.stringify({port:parseInt(new URL(c.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),d=u?JSON.parse(atob(u)).nonce:null,h=new URLSearchParams({client_id:a,scope:o,response_type:`token`,redirect_uri:l});u&&h.set(`state`,u);let g=await e(`${S(s)}/ims/authorize/v2?${h}`);if(!g)return;if(d&&g)try{if(new URL(g).searchParams.get(`nonce`)!==d){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 x=E(g);if(!x){console.error(`[adobe] Could not extract token from redirect URL`);return}let w=await T(x.accessToken,s);await n({providerId:`adobe`,accessToken:x.accessToken,tokenExpiresAt:Date.now()+x.expiresIn*1e3,userName:w.name,userAvatar:w.avatar,baseUrl:p.proxyEndpoint?void 0:r}),await z().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=w();if(e?.accessToken)try{let t=h.values().next().value??{},n=t.clientId||p.clientId,r=b(t);if(n){let t=await fetch(`${S(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:``})},onSilentRenew:async()=>w()?.accessToken?j():null},O=null;async function k(){let e=w();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...`);try{let e=await j();if(e)return e}catch(e){console.warn(`[adobe] Silent renewal failed:`,e instanceof Error?e.message:String(e))}let t=w();if((t?.tokenExpiresAt??0)-Date.now()>0&&t?.accessToken)return t.accessToken;throw Error(`Adobe session expired — please log in again`)}function A(){let e=w();return e?.tokenExpiresAt?Date.now()>e.tokenExpiresAt-6e4:!0}async function j(){return typeof window>`u`?null:O||(O=(async()=>{try{let e=m(),t=await _(e),i=v(t),a=y(t),o=b(t),s=C?p.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:p.redirectUri??`${window.location.origin}/auth/callback`,c=C?void 0:btoa(JSON.stringify({port:parseInt(new URL(window.location.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),l=c?JSON.parse(atob(c)).nonce:null,u=new URLSearchParams({client_id:i,scope:a,response_type:`token`,redirect_uri:s,prompt:`none`});c&&u.set(`state`,c);let d=`${S(o)}/ims/authorize/v2?${u}`,{createOAuthLauncher:f}=await r(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-B7as8KRE.js`);return{createOAuthLauncher:e}},__vite__mapDeps([0,1,2])),h=await f()(d);if(!h)return null;if(l&&h)try{if(new URL(h).searchParams.get(`nonce`)!==l)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),null}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=E(h);if(!g)return null;let x=w();return await n({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:x?.userName,userAvatar:x?.userAvatar,baseUrl:p.proxyEndpoint?void 0:e}),console.log(`[adobe] Token renewed silently`),await z().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),g.accessToken}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}finally{O=null}})(),O)}var M=`X-Slicc-Version`;function N(e){let t={},n=M.toLowerCase();if(e.headers)for(let[r,i]of Object.entries(e.headers))r.toLowerCase()!==n&&(t[r]=i);return t[M]=`2.50.0`,{...e,headers:t}}function P(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()}}}var F=(e,t,n={})=>{let r=u();return(async()=>{try{let i=await k();if(String(e.api).includes(`openai`)){let a=s({...e,baseUrl:`${m()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,N({...n,apiKey:i}));for await(let e of a)r.push(e)}else{let a=o({...e,baseUrl:m(),api:`anthropic-messages`},t,N({...n,apiKey:i}));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(P(e,t)),r.end()}})(),r},I=(e,t,n)=>{let r=u();return(async()=>{try{let o=await k();if(String(e.api).includes(`openai`)){let i=a({...e,baseUrl:`${m()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,N({...n,apiKey:o}));for await(let e of i)r.push(e)}else{let a=i({...e,baseUrl:m(),api:`anthropic-messages`},t,N({...n,apiKey:o}));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(P(e,t)),r.end()}})(),r};async function L(){try{let e=await k(),t=m(),n=await fetch(`${t}/v1/models`,{headers:{Authorization:`Bearer ${e}`,[M]:`2.50.0`}});if(n.ok){let e=await n.json();if(e.data?.length){for(let t of e.data){let e={id:t.id,name:t.name};t.api!==void 0&&(e.api=t.api),t.context_window!==void 0&&(e.context_window=t.context_window),t.max_tokens!==void 0&&(e.max_tokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),g.set(t.id,e)}let n=new Map;for(let e of l())try{for(let t of d(e))n.set(t.id,t)}catch{}return e.data.map(e=>{let r=n.get(e.id),i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`;return r?{...r,provider:`adobe`,api:i}:{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:t,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},inputCost:0,outputCost:0,cacheReadCost:0,cacheWriteCost:0,reasoning:!0}})}}else console.warn(`[adobe] Proxy /v1/models returned ${n.status}, falling back to Anthropic models`)}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return d(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}var R=new Map;async function z(){let e=m(),t=R.get(e);if(t)return t;let n=await L();return R.set(e,n),n}function B(){c({api:`adobe-anthropic`,stream:F,streamSimple:I}),c({api:`adobe-openai`,stream:F,streamSimple:I})}export{D as config,z as getAdobeModels,k as getValidAccessToken,A as isTokenExpired,B as register};
2
+ import{r as e,s as t,v as n}from"./provider-settings-DGXqU1Yt.js";import{t as r}from"./preload-helper-ca-nBW7U.js";import{c as i,l as a,o,s,u as c}from"./bedrock-camp-CqXHYC67.js";import{d as l,o as u,u as d}from"./simple-options-imi_RHvn.js";import{getOAuthPageOrigin as f}from"./oauth-service-B7as8KRE.js";var p=Object.assign({"/packages/webapp/providers/adobe-config.json":{proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`}})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function m(){let e=t(`adobe`);if(e)return e.replace(/\/$/,``);if(p.proxyEndpoint)return p.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}var h=new Map,g=new Map;async function _(e){let t=h.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[M]:`2.50.2`}});if(t.ok){let n=await t.json();return h.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}let n={};return h.set(e,n),n}function v(e){let t=e.clientId||p.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 y(e){return e.scopes||p.scopes}function b(e){return e.imsEnvironment||p.imsEnvironment||`prod`}var x={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function S(e){return x[e??p.imsEnvironment??`prod`]??x.prod}var C=typeof chrome<`u`&&!!chrome?.runtime?.id;function w(){return e().find(e=>e.providerId===`adobe`)}async function T(e,t){try{let n=await fetch(`${S(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function E(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)}:null}var D={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!p.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`],getModelIds:()=>{let e=e=>{let t={id:e.id,name:e.name??e.id},n=g.get(e.id);return n?.api&&(t.api=n.api),n?.context_window!==void 0&&(t.context_window=n.context_window),n?.max_tokens!==void 0&&(t.max_tokens=n.max_tokens),n?.reasoning!==void 0&&(t.reasoning=n.reasoning),n?.input&&(t.input=n.input),/haiku/i.test(e.id)&&(t.compat={supportsEagerToolInputStreaming:!1}),t};for(let t of R.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id}));try{localStorage.setItem(`slicc-adobe-models`,JSON.stringify(n))}catch{}return n}for(let t of h.values())if(t.models?.length)return t.models.map(e);try{let e=localStorage.getItem(`slicc-adobe-models`);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)=>{let r=m(),i=await _(r),a=v(i),o=y(i),s=b(i),c=C?null:await f(),l=C?p.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:p.redirectUri??`${c.origin}/auth/callback`,u=C?void 0:btoa(JSON.stringify({port:parseInt(new URL(c.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),d=u?JSON.parse(atob(u)).nonce:null,h=new URLSearchParams({client_id:a,scope:o,response_type:`token`,redirect_uri:l});u&&h.set(`state`,u);let g=await e(`${S(s)}/ims/authorize/v2?${h}`);if(!g)return;if(d&&g)try{if(new URL(g).searchParams.get(`nonce`)!==d){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 x=E(g);if(!x){console.error(`[adobe] Could not extract token from redirect URL`);return}let w=await T(x.accessToken,s);await n({providerId:`adobe`,accessToken:x.accessToken,tokenExpiresAt:Date.now()+x.expiresIn*1e3,userName:w.name,userAvatar:w.avatar,baseUrl:p.proxyEndpoint?void 0:r}),await z().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=w();if(e?.accessToken)try{let t=h.values().next().value??{},n=t.clientId||p.clientId,r=b(t);if(n){let t=await fetch(`${S(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:``})},onSilentRenew:async()=>w()?.accessToken?j():null},O=null;async function k(){let e=w();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...`);try{let e=await j();if(e)return e}catch(e){console.warn(`[adobe] Silent renewal failed:`,e instanceof Error?e.message:String(e))}let t=w();if((t?.tokenExpiresAt??0)-Date.now()>0&&t?.accessToken)return t.accessToken;throw Error(`Adobe session expired — please log in again`)}function A(){let e=w();return e?.tokenExpiresAt?Date.now()>e.tokenExpiresAt-6e4:!0}async function j(){return typeof window>`u`?null:O||(O=(async()=>{try{let e=m(),t=await _(e),i=v(t),a=y(t),o=b(t),s=C?p.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:p.redirectUri??`${window.location.origin}/auth/callback`,c=C?void 0:btoa(JSON.stringify({port:parseInt(new URL(window.location.href).port||`5710`,10),path:`/auth/callback`,nonce:crypto.randomUUID()})),l=c?JSON.parse(atob(c)).nonce:null,u=new URLSearchParams({client_id:i,scope:a,response_type:`token`,redirect_uri:s,prompt:`none`});c&&u.set(`state`,c);let d=`${S(o)}/ims/authorize/v2?${u}`,{createOAuthLauncher:f}=await r(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-B7as8KRE.js`);return{createOAuthLauncher:e}},__vite__mapDeps([0,1,2])),h=await f()(d);if(!h)return null;if(l&&h)try{if(new URL(h).searchParams.get(`nonce`)!==l)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),null}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=E(h);if(!g)return null;let x=w();return await n({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:x?.userName,userAvatar:x?.userAvatar,baseUrl:p.proxyEndpoint?void 0:e}),console.log(`[adobe] Token renewed silently`),await z().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),g.accessToken}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}finally{O=null}})(),O)}var M=`X-Slicc-Version`;function N(e){let t={},n=M.toLowerCase();if(e.headers)for(let[r,i]of Object.entries(e.headers))r.toLowerCase()!==n&&(t[r]=i);return t[M]=`2.50.2`,{...e,headers:t}}function P(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()}}}var F=(e,t,n={})=>{let r=u();return(async()=>{try{let i=await k();if(String(e.api).includes(`openai`)){let a=s({...e,baseUrl:`${m()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,N({...n,apiKey:i}));for await(let e of a)r.push(e)}else{let a=o({...e,baseUrl:m(),api:`anthropic-messages`},t,N({...n,apiKey:i}));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(P(e,t)),r.end()}})(),r},I=(e,t,n)=>{let r=u();return(async()=>{try{let o=await k();if(String(e.api).includes(`openai`)){let i=a({...e,baseUrl:`${m()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,N({...n,apiKey:o}));for await(let e of i)r.push(e)}else{let a=i({...e,baseUrl:m(),api:`anthropic-messages`},t,N({...n,apiKey:o}));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(P(e,t)),r.end()}})(),r};async function L(){try{let e=await k(),t=m(),n=await fetch(`${t}/v1/models`,{headers:{Authorization:`Bearer ${e}`,[M]:`2.50.2`}});if(n.ok){let e=await n.json();if(e.data?.length){for(let t of e.data){let e={id:t.id,name:t.name};t.api!==void 0&&(e.api=t.api),t.context_window!==void 0&&(e.context_window=t.context_window),t.max_tokens!==void 0&&(e.max_tokens=t.max_tokens),t.reasoning!==void 0&&(e.reasoning=t.reasoning),t.input!==void 0&&(e.input=t.input),g.set(t.id,e)}let n=new Map;for(let e of l())try{for(let t of d(e))n.set(t.id,t)}catch{}return e.data.map(e=>{let r=n.get(e.id),i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`;return r?{...r,provider:`adobe`,api:i}:{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:t,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},inputCost:0,outputCost:0,cacheReadCost:0,cacheWriteCost:0,reasoning:!0}})}}else console.warn(`[adobe] Proxy /v1/models returned ${n.status}, falling back to Anthropic models`)}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return d(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}var R=new Map;async function z(){let e=m(),t=R.get(e);if(t)return t;let n=await L();return R.set(e,n),n}function B(){c({api:`adobe-anthropic`,stream:F,streamSimple:I}),c({api:`adobe-openai`,stream:F,streamSimple:I})}export{D as config,z as getAdobeModels,k as getValidAccessToken,A as isTokenExpired,B as register};
@@ -1 +1 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import"./provider-settings-CWTeejO7.js";var t=e(`agent-bridge`),n=`__slicc_agent`,r=`agent-spawn-request`;function i(){let e={spawn(e){return new Promise((t,n)=>{let i=globalThis.chrome?.runtime;if(!i||typeof i.sendMessage!=`function`){n(Error(`agent: chrome.runtime.sendMessage not available`));return}let a=e=>{let r=i.lastError;if(r){n(Error(r.message??`chrome.runtime error`));return}if(e==null){n(Error(`agent: empty response from offscreen bridge`));return}let a=e;if(!a.ok){n(Error(a.error??`agent: offscreen bridge error`));return}if(!a.result){n(Error(`agent: offscreen bridge returned no result`));return}t(a.result)};try{i.sendMessage({source:`panel`,payload:{type:r,options:e}},a)}catch(e){n(e instanceof Error?e:Error(String(e)))}})}};return globalThis[n]=e,t.info(`agent bridge proxy published on globalThis.__slicc_agent`),e}export{i as publishAgentBridgeProxy};
1
+ import{t as e}from"./logger-B-No_qN_.js";import"./provider-settings-DGXqU1Yt.js";var t=e(`agent-bridge`),n=`__slicc_agent`,r=`agent-spawn-request`;function i(){let e={spawn(e){return new Promise((t,n)=>{let i=globalThis.chrome?.runtime;if(!i||typeof i.sendMessage!=`function`){n(Error(`agent: chrome.runtime.sendMessage not available`));return}let a=e=>{let r=i.lastError;if(r){n(Error(r.message??`chrome.runtime error`));return}if(e==null){n(Error(`agent: empty response from offscreen bridge`));return}let a=e;if(!a.ok){n(Error(a.error??`agent: offscreen bridge error`));return}if(!a.result){n(Error(`agent: offscreen bridge returned no result`));return}t(a.result)};try{i.sendMessage({source:`panel`,payload:{type:r,options:e}},a)}catch(e){n(e instanceof Error?e:Error(String(e)))}})}};return globalThis[n]=e,t.info(`agent bridge proxy published on globalThis.__slicc_agent`),e}export{i as publishAgentBridgeProxy};
@@ -1,4 +1,4 @@
1
- import{i as e}from"./kernel-worker-CqyRKXBm.js";const t=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`scoop-notify`,`scoop-idle`,`scoop-wait`]);function n(e){return e!=null&&t.has(e)}function r(t,n={}){let{source:r=`cone`,idSeed:c=d,hiddenToolNames:l=e}=n,f=[],h=null,g=new Set;for(let e of t){if(i(e)){let t=s(e.content);if(t.length===0)continue;let n=p(t);for(let t of n){if(t.body.length===0&&t.sender==null)continue;let n=t.sender?m(t.sender):null,r={id:c(),role:`user`,content:t.body,timestamp:e.timestamp};n&&(r.source=`lick`,r.channel=n),f.push(r)}h=null;continue}if(a(e)){let t=s(e.content),n=u(e),i=[];for(let e of n)l.has(e.name)?g.add(e.id):i.push(e);let a={id:c(),role:`assistant`,content:t,timestamp:e.timestamp,source:r};i.length>0&&(a.toolCalls=i),f.push(a),h=a;continue}if(o(e)){if(g.has(e.toolCallId))continue;let t=h?.toolCalls?.find(t=>t.id===e.toolCallId);if(!t)continue;t.result=s(e.content),t.isError=e.isError;continue}}return f}function i(e){return e.role===`user`}function a(e){return e.role===`assistant`}function o(e){return e.role===`toolResult`}function s(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)c(n)&&t.push(n.text);return t.join(``)}function c(e){return e.type===`text`}function l(e){return e.type===`toolCall`}function u(e){if(!Array.isArray(e.content))return[];let t=[];for(let n of e.content)l(n)&&t.push({id:n.id,name:n.name,input:n.arguments});return t}function d(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function f(e){if(!e.startsWith(`[`))return null;let n=e.indexOf(`] `);if(n<=0||e.lastIndexOf(`
1
+ import{i as e}from"./kernel-worker-iLIRf2UW.js";const t=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`scoop-notify`,`scoop-idle`,`scoop-wait`]);function n(e){return e!=null&&t.has(e)}function r(t,n={}){let{source:r=`cone`,idSeed:c=d,hiddenToolNames:l=e}=n,f=[],h=null,g=new Set;for(let e of t){if(i(e)){let t=s(e.content);if(t.length===0)continue;let n=p(t);for(let t of n){if(t.body.length===0&&t.sender==null)continue;let n=t.sender?m(t.sender):null,r={id:c(),role:`user`,content:t.body,timestamp:e.timestamp};n&&(r.source=`lick`,r.channel=n),f.push(r)}h=null;continue}if(a(e)){let t=s(e.content),n=u(e),i=[];for(let e of n)l.has(e.name)?g.add(e.id):i.push(e);let a={id:c(),role:`assistant`,content:t,timestamp:e.timestamp,source:r};i.length>0&&(a.toolCalls=i),f.push(a),h=a;continue}if(o(e)){if(g.has(e.toolCallId))continue;let t=h?.toolCalls?.find(t=>t.id===e.toolCallId);if(!t)continue;t.result=s(e.content),t.isError=e.isError;continue}}return f}function i(e){return e.role===`user`}function a(e){return e.role===`assistant`}function o(e){return e.role===`toolResult`}function s(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)c(n)&&t.push(n.text);return t.join(``)}function c(e){return e.type===`text`}function l(e){return e.type===`toolCall`}function u(e){if(!Array.isArray(e.content))return[];let t=[];for(let n of e.content)l(n)&&t.push({id:n.id,name:n.name,input:n.arguments});return t}function d(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function f(e){if(!e.startsWith(`[`))return null;let n=e.indexOf(`] `);if(n<=0||e.lastIndexOf(`
2
2
  `,n)!==-1)return null;let r=e.slice(n+2);if(r.startsWith(`User: `))return{sender:`User`,body:r.slice(6)};for(let e of t){let t=`${e}:`;if(!r.startsWith(t))continue;let n=r.indexOf(`
3
3
  `),i=n===-1?r.length:n,a=r.slice(0,i),o=-1,s=a.indexOf(`[`,t.length);if(s>t.length&&(o=a.lastIndexOf(`: `,s)),o<t.length&&(o=r.indexOf(`: `,t.length)),!(o<0||o>=i))return{sender:r.slice(0,o),body:r.slice(o+2)}}let i=r.indexOf(`
4
4
  `),a=i===-1?r.length:i,o=r.indexOf(`: `);if(o<=0||o>=a)return null;let s=r.slice(0,o);return s.includes(`
@@ -1 +1 @@
1
- import{i as e,o as t}from"./provider-settings-Fm4AIIxK.js";import{p as n}from"./bedrock-camp-9aDiXDk5.js";import{o as r,r as i,s as a,t as o}from"./transform-messages-uhk4b6os.js";import{t as s}from"./openai-D6Fs9zDM.js";const c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let e=t(c);if(!e)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=o(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}const g=(t,n,i={})=>{let o=r();return(async()=>{let r={role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let u=i.apiKey;if(!u)throw Error(`Azure API key is required`);let d=t.baseUrl;if(!d)throw Error(`Azure endpoint is required`);let g=t.id,_={};t.headers&&Object.assign(_,t.headers),i.headers&&Object.assign(_,i.headers);let v=e(c)||l,y=new s({endpoint:d.replace(/\/+$/,``),apiKey:u,deployment:g,apiVersion:v,dangerouslyAllowBrowser:!0,defaultHeaders:_}),b=[...n.systemPrompt?[{role:`system`,content:n.systemPrompt}]:[],...f(n,t)],x=p(n.tools),S=await y.chat.completions.create({model:g,messages:b,stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...x?{tools:x}:{}});o.push({type:`start`,partial:r});for await(let e of S){e.usage&&(r.usage.input=e.usage.prompt_tokens??0,r.usage.output=e.usage.completion_tokens??0,r.usage.totalTokens=e.usage.total_tokens??0,a(t,r.usage));for(let t of e.choices??[]){let e=t.delta;if(e){if(e.content){let{block:t,index:n}=m(r);t.text===``&&o.push({type:`text_start`,contentIndex:n,partial:r}),t.text+=e.content,o.push({type:`text_delta`,contentIndex:n,delta:e.content,partial:r})}if(e.tool_calls)for(let t of e.tool_calls){let e=t.id?h(r,t.id):void 0;if(!e&&t.id&&(e={type:`toolCall`,id:t.id,name:t.function?.name??``,arguments:{},_partialJson:``},r.content.push(e),o.push({type:`toolcall_start`,contentIndex:r.content.length-1,partial:r})),e&&t.function?.arguments){e._partialJson+=t.function.arguments;try{e.arguments=JSON.parse(e._partialJson)}catch{}o.push({type:`toolcall_delta`,contentIndex:r.content.indexOf(e),delta:t.function.arguments,partial:r})}}t.finish_reason&&(r.stopReason=t.finish_reason===`tool_calls`?`toolUse`:t.finish_reason===`length`?`length`:`stop`)}}}for(let e of r.content){let t=r.content.indexOf(e);if(e.type===`toolCall`){let n=e;try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,o.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:r})}else e.type===`text`&&o.push({type:`text_end`,contentIndex:t,content:e.text,partial:r})}o.push({type:`done`,reason:r.stopReason,message:r}),o.end()}catch(e){r.stopReason=i.signal?.aborted?`aborted`:`error`,r.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:r.stopReason,error:r}),o.end()}})(),o},_=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return g(e,t,{...i(e,n,r)})};function v(){n({api:`azure-openai-anthropic`,stream:g,streamSimple:_})}export{u as config,v as register};
1
+ import{i as e,o as t}from"./provider-settings-B_lSRZ0U.js";import{p as n}from"./bedrock-camp-9aDiXDk5.js";import{o as r,r as i,s as a,t as o}from"./transform-messages-uhk4b6os.js";import{t as s}from"./openai-D6Fs9zDM.js";const c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let e=t(c);if(!e)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=o(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}const g=(t,n,i={})=>{let o=r();return(async()=>{let r={role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let u=i.apiKey;if(!u)throw Error(`Azure API key is required`);let d=t.baseUrl;if(!d)throw Error(`Azure endpoint is required`);let g=t.id,_={};t.headers&&Object.assign(_,t.headers),i.headers&&Object.assign(_,i.headers);let v=e(c)||l,y=new s({endpoint:d.replace(/\/+$/,``),apiKey:u,deployment:g,apiVersion:v,dangerouslyAllowBrowser:!0,defaultHeaders:_}),b=[...n.systemPrompt?[{role:`system`,content:n.systemPrompt}]:[],...f(n,t)],x=p(n.tools),S=await y.chat.completions.create({model:g,messages:b,stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...x?{tools:x}:{}});o.push({type:`start`,partial:r});for await(let e of S){e.usage&&(r.usage.input=e.usage.prompt_tokens??0,r.usage.output=e.usage.completion_tokens??0,r.usage.totalTokens=e.usage.total_tokens??0,a(t,r.usage));for(let t of e.choices??[]){let e=t.delta;if(e){if(e.content){let{block:t,index:n}=m(r);t.text===``&&o.push({type:`text_start`,contentIndex:n,partial:r}),t.text+=e.content,o.push({type:`text_delta`,contentIndex:n,delta:e.content,partial:r})}if(e.tool_calls)for(let t of e.tool_calls){let e=t.id?h(r,t.id):void 0;if(!e&&t.id&&(e={type:`toolCall`,id:t.id,name:t.function?.name??``,arguments:{},_partialJson:``},r.content.push(e),o.push({type:`toolcall_start`,contentIndex:r.content.length-1,partial:r})),e&&t.function?.arguments){e._partialJson+=t.function.arguments;try{e.arguments=JSON.parse(e._partialJson)}catch{}o.push({type:`toolcall_delta`,contentIndex:r.content.indexOf(e),delta:t.function.arguments,partial:r})}}t.finish_reason&&(r.stopReason=t.finish_reason===`tool_calls`?`toolUse`:t.finish_reason===`length`?`length`:`stop`)}}}for(let e of r.content){let t=r.content.indexOf(e);if(e.type===`toolCall`){let n=e;try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,o.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:r})}else e.type===`text`&&o.push({type:`text_end`,contentIndex:t,content:e.text,partial:r})}o.push({type:`done`,reason:r.stopReason,message:r}),o.end()}catch(e){r.stopReason=i.signal?.aborted?`aborted`:`error`,r.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:r.stopReason,error:r}),o.end()}})(),o},_=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return g(e,t,{...i(e,n,r)})};function v(){n({api:`azure-openai-anthropic`,stream:g,streamSimple:_})}export{u as config,v as register};
@@ -1 +1 @@
1
- import{c as e,o as t}from"./provider-settings-CWTeejO7.js";import{u as n}from"./bedrock-camp-CqXHYC67.js";import{i as r,n as i,o as a,s as o}from"./simple-options-imi_RHvn.js";import{t as s}from"./openai-CRGaNv9i.js";var c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=r(e.messages,t,d),i=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)i.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});i.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));r.length?i.push({role:`assistant`,content:n||null,tool_calls:r}):i.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;i.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return i}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}var g=(e,n,r={})=>{let i=a();return(async()=>{let a={role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()};try{let u=r.apiKey;if(!u)throw Error(`Azure API key is required`);let d=e.baseUrl;if(!d)throw Error(`Azure endpoint is required`);let g=e.id,_={};e.headers&&Object.assign(_,e.headers),r.headers&&Object.assign(_,r.headers);let v=t(c)||l,y=new s({endpoint:d.replace(/\/+$/,``),apiKey:u,deployment:g,apiVersion:v,dangerouslyAllowBrowser:!0,defaultHeaders:_}),b=[...n.systemPrompt?[{role:`system`,content:n.systemPrompt}]:[],...f(n,e)],x=p(n.tools),S=await y.chat.completions.create({model:g,messages:b,stream:!0,stream_options:{include_usage:!0},...r.maxTokens?{max_completion_tokens:r.maxTokens}:{},...r.temperature===void 0?{}:{temperature:r.temperature},...x?{tools:x}:{}});i.push({type:`start`,partial:a});for await(let t of S){t.usage&&(a.usage.input=t.usage.prompt_tokens??0,a.usage.output=t.usage.completion_tokens??0,a.usage.totalTokens=t.usage.total_tokens??0,o(e,a.usage));for(let e of t.choices??[]){let t=e.delta;if(t){if(t.content){let{block:e,index:n}=m(a);e.text===``&&i.push({type:`text_start`,contentIndex:n,partial:a}),e.text+=t.content,i.push({type:`text_delta`,contentIndex:n,delta:t.content,partial:a})}if(t.tool_calls)for(let e of t.tool_calls){let t=e.id?h(a,e.id):void 0;if(!t&&e.id&&(t={type:`toolCall`,id:e.id,name:e.function?.name??``,arguments:{},_partialJson:``},a.content.push(t),i.push({type:`toolcall_start`,contentIndex:a.content.length-1,partial:a})),t&&e.function?.arguments){t._partialJson+=e.function.arguments;try{t.arguments=JSON.parse(t._partialJson)}catch{}i.push({type:`toolcall_delta`,contentIndex:a.content.indexOf(t),delta:e.function.arguments,partial:a})}}e.finish_reason&&(a.stopReason=e.finish_reason===`tool_calls`?`toolUse`:e.finish_reason===`length`?`length`:`stop`)}}}for(let e of a.content){let t=a.content.indexOf(e);if(e.type===`toolCall`){let n=e;try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,i.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:a})}else e.type===`text`&&i.push({type:`text_end`,contentIndex:t,content:e.text,partial:a})}i.push({type:`done`,reason:a.stopReason,message:a}),i.end()}catch(e){a.stopReason=r.signal?.aborted?`aborted`:`error`,a.errorMessage=e instanceof Error?e.message:JSON.stringify(e),i.push({type:`error`,reason:a.stopReason,error:a}),i.end()}})(),i},_=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return g(e,t,{...i(e,n,r)})};function v(){n({api:`azure-openai-anthropic`,stream:g,streamSimple:_})}export{u as config,v as register};
1
+ import{c as e,o as t}from"./provider-settings-DGXqU1Yt.js";import{u as n}from"./bedrock-camp-CqXHYC67.js";import{i as r,n as i,o as a,s as o}from"./simple-options-imi_RHvn.js";import{t as s}from"./openai-CRGaNv9i.js";var c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=r(e.messages,t,d),i=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)i.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});i.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));r.length?i.push({role:`assistant`,content:n||null,tool_calls:r}):i.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;i.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return i}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}var g=(e,n,r={})=>{let i=a();return(async()=>{let a={role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()};try{let u=r.apiKey;if(!u)throw Error(`Azure API key is required`);let d=e.baseUrl;if(!d)throw Error(`Azure endpoint is required`);let g=e.id,_={};e.headers&&Object.assign(_,e.headers),r.headers&&Object.assign(_,r.headers);let v=t(c)||l,y=new s({endpoint:d.replace(/\/+$/,``),apiKey:u,deployment:g,apiVersion:v,dangerouslyAllowBrowser:!0,defaultHeaders:_}),b=[...n.systemPrompt?[{role:`system`,content:n.systemPrompt}]:[],...f(n,e)],x=p(n.tools),S=await y.chat.completions.create({model:g,messages:b,stream:!0,stream_options:{include_usage:!0},...r.maxTokens?{max_completion_tokens:r.maxTokens}:{},...r.temperature===void 0?{}:{temperature:r.temperature},...x?{tools:x}:{}});i.push({type:`start`,partial:a});for await(let t of S){t.usage&&(a.usage.input=t.usage.prompt_tokens??0,a.usage.output=t.usage.completion_tokens??0,a.usage.totalTokens=t.usage.total_tokens??0,o(e,a.usage));for(let e of t.choices??[]){let t=e.delta;if(t){if(t.content){let{block:e,index:n}=m(a);e.text===``&&i.push({type:`text_start`,contentIndex:n,partial:a}),e.text+=t.content,i.push({type:`text_delta`,contentIndex:n,delta:t.content,partial:a})}if(t.tool_calls)for(let e of t.tool_calls){let t=e.id?h(a,e.id):void 0;if(!t&&e.id&&(t={type:`toolCall`,id:e.id,name:e.function?.name??``,arguments:{},_partialJson:``},a.content.push(t),i.push({type:`toolcall_start`,contentIndex:a.content.length-1,partial:a})),t&&e.function?.arguments){t._partialJson+=e.function.arguments;try{t.arguments=JSON.parse(t._partialJson)}catch{}i.push({type:`toolcall_delta`,contentIndex:a.content.indexOf(t),delta:e.function.arguments,partial:a})}}e.finish_reason&&(a.stopReason=e.finish_reason===`tool_calls`?`toolUse`:e.finish_reason===`length`?`length`:`stop`)}}}for(let e of a.content){let t=a.content.indexOf(e);if(e.type===`toolCall`){let n=e;try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,i.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:a})}else e.type===`text`&&i.push({type:`text_end`,contentIndex:t,content:e.text,partial:a})}i.push({type:`done`,reason:a.stopReason,message:a}),i.end()}catch(e){a.stopReason=r.signal?.aborted?`aborted`:`error`,a.errorMessage=e instanceof Error?e.message:JSON.stringify(e),i.push({type:`error`,reason:a.stopReason,error:a}),i.end()}})(),i},_=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return g(e,t,{...i(e,n,r)})};function v(){n({api:`azure-openai-anthropic`,stream:g,streamSimple:_})}export{u as config,v as register};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/magick-wasm-BbaIA46K.js","assets/index-Cv13fIWN.js","assets/chunk-jRWAZmH_.js","assets/preload-helper-ca-nBW7U.js","assets/provider-settings-CWTeejO7.js","assets/bedrock-camp-CqXHYC67.js","assets/env-api-keys-DxKb6C4Q.js","assets/simple-options-imi_RHvn.js","assets/json-parse-C5jSA6JB.js","assets/tray-follower-status-DKq8RTLd.js","assets/logger-B-No_qN_.js","assets/tool-ui-B3Bihlxa.js","assets/telemetry-B7l3TtVP.js","assets/fs-CT7Y5NS0.js","assets/backend-local-mju0Ps5U.js","assets/mount-picker-popup-DJJfRF_c.js","assets/path-utils-d3qOVZOu.js","assets/mime-types-DL940yDZ.js","assets/mount-DqdX0aJz.js","assets/index-eWuuouO-.css"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./logger-B-No_qN_.js";import{t}from"./preload-helper-ca-nBW7U.js";import"./index-Cv13fIWN.js";var n=e(`cdp`),r=class{ws=null;nextId=1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:r=5e3}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${r}ms`))},r);try{this.ws=new WebSocket(t)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,n.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(n.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=()=>{this.handleClose()}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this.cleanup(),n.info(`Disconnected`)}async send(e,t,r,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};return t&&(o.params=t),r&&(o.sessionId=r),n.debug(`Send`,{method:e,id:a,sessionId:r}),new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(a),n(Error(`CDP command timed out after ${i}ms: ${e}`))},i);this.pending.set(a,{resolve:e=>{clearTimeout(r),t(e)},reject:e=>{clearTimeout(r),n(e)}}),this.ws.send(JSON.stringify(o))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;n.debug(`Response`,{id:e.id,hasError:!!e.error});let r=this.pending.get(e.id);r&&(this.pending.delete(e.id),e.error?(n.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),r.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):r.resolve(e.result??{}));return}if(`method`in t){let e=t;n.debug(`Event`,{method:e.method,sessionId:e.sessionId});let r=this.listeners.get(e.method);if(r){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of r)try{e(t)}catch{}}}}handleClose(){n.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});for(let[,e]of this.pending)e.reject(Error(`CDP connection closed`));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};function i(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}var a=`(function() {
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/magick-wasm-Bxy887fy.js","assets/index-BbIDJNZM.js","assets/chunk-jRWAZmH_.js","assets/preload-helper-ca-nBW7U.js","assets/provider-settings-DGXqU1Yt.js","assets/bedrock-camp-CqXHYC67.js","assets/env-api-keys-DxKb6C4Q.js","assets/simple-options-imi_RHvn.js","assets/json-parse-C5jSA6JB.js","assets/tray-follower-status-DKq8RTLd.js","assets/logger-B-No_qN_.js","assets/tool-ui-B3Bihlxa.js","assets/telemetry-B7l3TtVP.js","assets/fs-DR9Kg_gg.js","assets/backend-local-mju0Ps5U.js","assets/mount-picker-popup-DJJfRF_c.js","assets/path-utils-d3qOVZOu.js","assets/mime-types-DL940yDZ.js","assets/mount-XZ9QStv8.js","assets/index-eWuuouO-.css"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./logger-B-No_qN_.js";import{t}from"./preload-helper-ca-nBW7U.js";import"./index-BbIDJNZM.js";var n=e(`cdp`),r=class{ws=null;nextId=1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:r=5e3}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${r}ms`))},r);try{this.ws=new WebSocket(t)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,n.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(n.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=()=>{this.handleClose()}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this.cleanup(),n.info(`Disconnected`)}async send(e,t,r,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};return t&&(o.params=t),r&&(o.sessionId=r),n.debug(`Send`,{method:e,id:a,sessionId:r}),new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(a),n(Error(`CDP command timed out after ${i}ms: ${e}`))},i);this.pending.set(a,{resolve:e=>{clearTimeout(r),t(e)},reject:e=>{clearTimeout(r),n(e)}}),this.ws.send(JSON.stringify(o))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;n.debug(`Response`,{id:e.id,hasError:!!e.error});let r=this.pending.get(e.id);r&&(this.pending.delete(e.id),e.error?(n.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),r.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):r.resolve(e.result??{}));return}if(`method`in t){let e=t;n.debug(`Event`,{method:e.method,sessionId:e.sessionId});let r=this.listeners.get(e.method);if(r){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of r)try{e(t)}catch{}}}}handleClose(){n.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});for(let[,e]of this.pending)e.reject(Error(`CDP connection closed`));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};function i(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}var a=`(function() {
3
3
  'use strict';
4
4
 
5
5
  // ===== DOM Utilities =====
@@ -869,7 +869,7 @@ import{t as e}from"./logger-B-No_qN_.js";import{t}from"./preload-helper-ca-nBW7U
869
869
  } catch(e) {
870
870
  return { role: 'RootWebArea', name: '', description: 'Error: ' + (e.message || String(e)) };
871
871
  }
872
- })()`,o=`ws://localhost:5710/cdp`,s=e(`browser-api`);function c(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:o}var l=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;handleJavaScriptDialogOpening=async e=>{let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),s.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){s.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}};constructor(e){this.client=e??new r,this.localClient=this.client,this.addDialogListener(this.client)}getTransport(){return this.client}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url}));return[...e,...r]}async connect(e){await this.client.connect({url:e?.url??c(),timeout:e?.timeout})}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let n={format:e?.format??`png`,captureBeyondViewport:!0};if(e?.quality!==void 0&&(n.quality=e.quality),e?.clip||e?.fullPage){let t=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),n=JSON.parse(e.result?.value??`{}`);t=n.w??0,r=n.h??0}catch{}e?.clip?n.clip={...e.clip,scale:e.clip.scale??1}:n.clip={x:0,y:0,width:t||1280,height:r||800,scale:1}}let r;try{r=await this.client.send(`Page.captureScreenshot`,n,this.sessionId)}catch{await this.client.send(`Page.bringToFront`,{},this.sessionId),r=await this.client.send(`Page.captureScreenshot`,n,this.sessionId)}let i=r.data;if(e?.maxWidth)try{let{getMagick:n}=await t(async()=>{let{getMagick:e}=await import(`./magick-wasm-BbaIA46K.js`);return{getMagick:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),r=await n(),a=atob(i),o=new Uint8Array(a.length);for(let e=0;e<a.length;e++)o[e]=a.charCodeAt(e);let s=8e3,c=!1;await r.ImageMagick.read(o,async t=>{let n=Math.min(e.maxWidth,s),r=Math.max(t.width,t.height);if(t.width>n||r>s){let e=Math.min(n/t.width,s/r);t.resize(Math.round(t.width*e),Math.round(t.height*e)),c=!0}c&&t.write(`PNG`,e=>{let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);i=btoa(t)})})}catch(e){console.warn(`[browser-api] Screenshot maxWidth resize failed, returning original`,e)}return i}finally{}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e){await this.ensureConnected(),this.ensureAttached();let t=await this.boundingBox(e);if(!t)throw Error(`Element not found: ${e}`);let n=t.x+t.width/2,r=t.y+t.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n,y:r,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:n,y:r,button:`left`,clickCount:1},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(a,{awaitPromise:!1,returnByValue:!0});return!e||typeof e!=`object`?{role:`RootWebArea`,name:``}:u(e)}async clickByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let n=(await this.client.send(`Runtime.callFunctionOn`,{objectId:t.objectId,functionDeclaration:`function() {
872
+ })()`,o=`ws://localhost:5710/cdp`,s=e(`browser-api`);function c(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:o}var l=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;handleJavaScriptDialogOpening=async e=>{let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),s.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){s.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}};constructor(e){this.client=e??new r,this.localClient=this.client,this.addDialogListener(this.client)}getTransport(){return this.client}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url}));return[...e,...r]}async connect(e){await this.client.connect({url:e?.url??c(),timeout:e?.timeout})}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let n={format:e?.format??`png`,captureBeyondViewport:!0};if(e?.quality!==void 0&&(n.quality=e.quality),e?.clip||e?.fullPage){let t=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),n=JSON.parse(e.result?.value??`{}`);t=n.w??0,r=n.h??0}catch{}e?.clip?n.clip={...e.clip,scale:e.clip.scale??1}:n.clip={x:0,y:0,width:t||1280,height:r||800,scale:1}}let r;try{r=await this.client.send(`Page.captureScreenshot`,n,this.sessionId)}catch{await this.client.send(`Page.bringToFront`,{},this.sessionId),r=await this.client.send(`Page.captureScreenshot`,n,this.sessionId)}let i=r.data;if(e?.maxWidth)try{let{getMagick:n}=await t(async()=>{let{getMagick:e}=await import(`./magick-wasm-Bxy887fy.js`);return{getMagick:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),r=await n(),a=atob(i),o=new Uint8Array(a.length);for(let e=0;e<a.length;e++)o[e]=a.charCodeAt(e);let s=8e3,c=!1;await r.ImageMagick.read(o,async t=>{let n=Math.min(e.maxWidth,s),r=Math.max(t.width,t.height);if(t.width>n||r>s){let e=Math.min(n/t.width,s/r);t.resize(Math.round(t.width*e),Math.round(t.height*e)),c=!0}c&&t.write(`PNG`,e=>{let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);i=btoa(t)})})}catch(e){console.warn(`[browser-api] Screenshot maxWidth resize failed, returning original`,e)}return i}finally{}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e){await this.ensureConnected(),this.ensureAttached();let t=await this.boundingBox(e);if(!t)throw Error(`Element not found: ${e}`);let n=t.x+t.width/2,r=t.y+t.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n,y:r,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:n,y:r,button:`left`,clickCount:1},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(a,{awaitPromise:!1,returnByValue:!0});return!e||typeof e!=`object`?{role:`RootWebArea`,name:``}:u(e)}async clickByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let n=(await this.client.send(`Runtime.callFunctionOn`,{objectId:t.objectId,functionDeclaration:`function() {
873
873
  this.scrollIntoView({ block: 'center', inline: 'center' });
874
874
  const r = this.getBoundingClientRect();
875
875
  return { x: r.x, y: r.y, width: r.width, height: r.height };
@@ -0,0 +1 @@
1
+ import"./index-BbIDJNZM.js";function e(e){}export{e as registerSessionCostsProvider};