@agentsdock/server 1.0.10 → 1.0.11-beta.12

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 (39) hide show
  1. package/NOTICE +7 -0
  2. package/package.json +1 -1
  3. package/server/NOTICE +7 -0
  4. package/server/VERSION +1 -1
  5. package/server/agent_server.py +1658 -498
  6. package/server/agentsdock_jobs.py +2 -2
  7. package/server/claude_history_repair.py +46 -61
  8. package/server/codex_auth.py +76 -7
  9. package/server/codex_history_repair.py +203 -38
  10. package/server/cursor_process_guard.py +67 -4
  11. package/server/cursor_provider_mcp.py +2 -0
  12. package/server/execution_durability.py +87 -11
  13. package/server/execution_install.py +5 -1
  14. package/server/gemini_acp_client.py +432 -0
  15. package/server/gemini_api.py +128 -0
  16. package/server/gemini_content.py +102 -0
  17. package/server/gemini_history.py +293 -0
  18. package/server/gemini_import.py +126 -0
  19. package/server/gemini_permissions.py +47 -0
  20. package/server/gemini_runner.py +493 -0
  21. package/server/gemini_runtime.py +322 -0
  22. package/server/install.sh +26 -2
  23. package/server/interactive_chat_controls.py +9 -3
  24. package/server/interactive_chat_native.py +1 -1
  25. package/server/interactive_chat_share_routes.py +2 -2
  26. package/server/interactive_chat_share_web.py +2 -2
  27. package/server/local_session_ownership.py +1 -0
  28. package/server/npm/agentsdock/QR-NOTICES.txt +56 -0
  29. package/server/npm/agentsdock/pair.cjs +123 -0
  30. package/server/npm/agentsdock/qr-renderer.cjs +15 -0
  31. package/server/provider_commands.py +65 -0
  32. package/server/provider_connections.py +39 -10
  33. package/server/public_chat_share_routes.py +8 -6
  34. package/server/public_chat_shares.py +17 -7
  35. package/server/server_instances.py +217 -15
  36. package/server/shared_chat_analytics_web.py +5 -0
  37. package/server/title_generation.py +60 -1
  38. package/server/transcript_reader.py +334 -0
  39. package/server/update_runner.py +4 -2
@@ -157,6 +157,7 @@ def exclusive_lock(path: Path):
157
157
  PROVIDER_ID_FIELDS = {
158
158
  "claude": "claude_session_id", "codex": "codex_thread_id",
159
159
  "cursor": "cursor_session_id", "opencode": "opencode_session_id",
160
+ "gemini": "gemini_session_id",
160
161
  }
161
162
  MAX_IMPORT_INDEX_BYTES = 64 * 1024 * 1024
162
163
  MAX_IMPORT_INDEX_TOTAL_BYTES = 128 * 1024 * 1024
@@ -0,0 +1,56 @@
1
+ qrcode
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2012 Ryan Day
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
+
12
+
13
+
14
+ pngjs
15
+ pngjs2 original work Copyright (c) 2015 Luke Page & Original Contributors
16
+ pngjs derived work Copyright (c) 2012 Kuba Niegowski
17
+
18
+ Permission is hereby granted, free of charge, to any person obtaining a copy
19
+ of this software and associated documentation files (the "Software"), to deal
20
+ in the Software without restriction, including without limitation the rights
21
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
+ copies of the Software, and to permit persons to whom the Software is
23
+ furnished to do so, subject to the following conditions:
24
+
25
+ The above copyright notice and this permission notice shall be included in
26
+ all copies or substantial portions of the Software.
27
+
28
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34
+ THE SOFTWARE.
35
+
36
+
37
+ dijkstrajs
38
+ ```
39
+ Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
40
+
41
+ Copyright (C) 2008
42
+ Wyatt Baldwin <self@wyattbaldwin.com>
43
+ All rights reserved
44
+
45
+ Licensed under the MIT license.
46
+
47
+ http://www.opensource.org/licenses/mit-license.php
48
+
49
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
55
+ THE SOFTWARE.
56
+ ```
@@ -0,0 +1,123 @@
1
+ 'use strict'
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+
5
+ function parsePair(args) {
6
+ const result = { kind: 'pair', name: 'default', network: 'auto', url: null, output: null, link: false }
7
+ if (args[0] && !args[0].startsWith('-')) result.name = args.shift()
8
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(result.name)) throw new Error('Invalid instance name.')
9
+ const seen = new Set()
10
+ while (args.length) {
11
+ const key = args.shift()
12
+ if (seen.has(key)) throw new Error('Specify each pairing option once.')
13
+ seen.add(key)
14
+ if (key === '--link') result.link = true
15
+ else if (key === '--network' && ['auto', 'tailscale', 'lan', 'local'].includes(args[0])) result.network = args.shift()
16
+ else if (key === '--url' && args[0] && !args[0].startsWith('-')) result.url = args.shift().replace(/\/$/, '')
17
+ else if (key === '--output' && args[0] && !args[0].startsWith('-')) result.output = args.shift()
18
+ else throw new Error('Use pair [NAME] [--network auto|tailscale|lan|local] [--url URL] [--output FILE.png] [--link].')
19
+ }
20
+ if (result.link && result.output) throw new Error('Choose --link or --output, not both.')
21
+ return result
22
+ }
23
+
24
+ function connectionLink({ serverUrl, serverUrls, accessToken, name, serverIdentity }) {
25
+ const values = serverUrls ?? [serverUrl]
26
+ if (!Array.isArray(values) || !values.length || values.length > 6) throw new Error('Invalid server addresses.')
27
+ const urls = [...new Set(values.map(value => {
28
+ if (typeof value !== 'string' || /[\x00-\x20\x7f]/.test(value)) throw new Error('Invalid server address.')
29
+ let url
30
+ try { url = new URL(value) } catch { throw new Error('Invalid server address.') }
31
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error('Invalid server address.')
32
+ return url.toString().replace(/\/$/, '')
33
+ }))]
34
+ if (!accessToken || (serverUrls && !serverIdentity?.trim()) ||
35
+ [accessToken, name, serverIdentity ?? ''].some(value => /[\x00-\x1f\x7f]/.test(value))) throw new Error('Invalid pairing details.')
36
+ const fields = new URLSearchParams(serverUrls
37
+ ? { v: '2', urls: JSON.stringify(urls), token: accessToken, name }
38
+ : { v: '1', url: urls[0], token: accessToken, name })
39
+ if (serverIdentity) fields.set('identity', serverIdentity)
40
+ const link = `agentsdock://connect#${fields}`
41
+ if (Buffer.byteLength(link) > 1800) throw new Error('Connection details are too long for a QR code.')
42
+ return link
43
+ }
44
+
45
+ function selectAddresses(choices, network, selectedUrl = null) {
46
+ const eligible = network === 'auto' ? [choices.tailscale, ...(choices.lan ?? [])].filter(Boolean)
47
+ : network === 'tailscale' ? [choices.tailscale].filter(Boolean) : choices[network] ?? []
48
+ if (selectedUrl) {
49
+ if (!eligible.includes(selectedUrl)) throw new Error('The requested URL is not a verified address for this instance/network. Run agentsdock status to check its addresses.')
50
+ return [selectedUrl]
51
+ }
52
+ const candidates = [...new Set(eligible)]
53
+ if (!candidates.length) throw new Error('No reachable address for this network. Run agentsdock status to check the binding. A localhost-only server cannot pair with a phone; use a reachable LAN or Tailscale binding. --network local is for this computer or an iOS simulator only.')
54
+ if (candidates.length > 6) throw new Error('Too many server addresses. Select a network or use --url URL.')
55
+ return candidates
56
+ }
57
+
58
+ async function pair(request, runtime, context, env) {
59
+ const helper = path.join(runtime.payload, 'instances.sh')
60
+ if (!fs.lstatSync(helper).isFile()) throw new Error('The instance helper is missing.')
61
+ const result = context.spawn('/bin/bash', [helper, '_pair-info', request.name], {
62
+ env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 20000, maxBuffer: 64000,
63
+ })
64
+ // Child output contains a credential. Never relay raw output/errors.
65
+ if (result.error || result.status !== 0) throw new Error('Could not read that server. Run agentsdock list and select an installed instance owned by this user.')
66
+ let details
67
+ try { details = JSON.parse(result.stdout) } catch { throw new Error('Invalid instance pairing metadata.') }
68
+ const candidates = selectAddresses(details.choices, request.network, request.url)
69
+ const checks = await Promise.all(candidates.map(async serverUrl => {
70
+ try {
71
+ const response = await (context.fetch ?? fetch)(`${serverUrl}/api/health`, {
72
+ headers: { 'X-AgentsDock-Token': details.accessToken }, redirect: 'error', signal: AbortSignal.timeout(8000),
73
+ })
74
+ if (!response.ok) return null
75
+ const health = await response.json()
76
+ if (health.ok !== true || typeof health.server_identity !== 'string' || !health.server_identity.trim()) return null
77
+ return { serverUrl, identity: health.server_identity }
78
+ } catch { return null }
79
+ }))
80
+ const first = checks.find(Boolean)
81
+ if (!first) throw new Error('No address passed authenticated health. Check that this server is running and reachable, then try again.')
82
+ if (checks.some(check => check && check.identity !== first.identity)) throw new Error('Server addresses reported different identities. Check the instance binding before sharing.')
83
+ const serverUrls = checks.filter(Boolean).map(check => check.serverUrl)
84
+ const serverUrl = serverUrls[0]
85
+ const link = connectionLink({ ...details, serverUrl, ...(serverUrls.length > 1 ? { serverUrls } : {}), serverIdentity: first.identity })
86
+ if (request.link) { context.print(link); return 0 }
87
+ const qr = context.qr ?? require('./qr-renderer.cjs')
88
+ if (request.output) {
89
+ const png = await qr.toBuffer(link, { type: 'png', errorCorrectionLevel: 'M', margin: 4, scale: 6 })
90
+ fs.writeFileSync(request.output, png, { flag: 'wx', mode: 0o600 })
91
+ }
92
+ context.print(`Pair ${request.name}\nServer addresses:\n${serverUrls.join('\n')}\nOpen AgentsDock mobile > Servers > Add server > Scan QR code.\nThe QR contains your access token. Keep it private. Mobile automatically tries the included addresses over Wi-Fi or Tailscale.`)
93
+ if (request.network === 'local') context.print('Local-only: works on this computer/iOS simulator, not a physical phone.')
94
+ if (request.output) context.print('QR image saved. Keep this file private.')
95
+ else context.print(await qr.toString(link, { type: 'terminal', small: true, errorCorrectionLevel: 'M', margin: 4 }))
96
+ return 0
97
+ }
98
+
99
+ async function showSetupQr(name, runtime, context, env) {
100
+ try {
101
+ await pair(parsePair([name]), runtime, context, env)
102
+ return true
103
+ } catch {
104
+ // Setup/token retrieval has already succeeded. Never expose private child errors
105
+ // or fail the installation merely because this network cannot pair yet.
106
+ context.print(`Connection QR unavailable. Once the server is reachable from your phone, run: agentsdock pair ${name}\nFor a specific network, add --network lan or --network tailscale.`)
107
+ return false
108
+ }
109
+ }
110
+
111
+ if (require.main === module) {
112
+ const name = process.argv[2]
113
+ if (!process.stdin.isTTY || !process.stdout.isTTY || process.argv.length !== 3 || !/^[a-z][a-z0-9-]{0,31}$/.test(name ?? '')) {
114
+ process.exitCode = 1
115
+ } else {
116
+ void showSetupQr(name, { payload: path.resolve(__dirname, '../..') }, {
117
+ spawn: require('node:child_process').spawnSync,
118
+ print: text => process.stdout.write(`${text}\n`),
119
+ }, process.env)
120
+ }
121
+ }
122
+
123
+ module.exports = { parsePair, connectionLink, selectAddresses, pair, showSetupQr }
@@ -0,0 +1,15 @@
1
+ // Generated from qrcode 1.5.4; see QR-NOTICES.txt. Regenerate: node scripts/build_cli_qr.mjs
2
+ var d=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var Me=d((Vo,Tt)=>{Tt.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var q=d(H=>{var Oe,Rn=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];H.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};H.getSymbolTotalCodewords=function(e){return Rn[e]};H.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};H.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Oe=e};H.isKanjiModeEnabled=function(){return typeof Oe<"u"};H.toSJIS=function(e){return Oe(e)}});var pe=d(R=>{R.L={bit:1};R.M={bit:0};R.Q={bit:3};R.H={bit:2};function Sn(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return R.L;case"m":case"medium":return R.M;case"q":case"quartile":return R.Q;case"h":case"high":return R.H;default:throw new Error("Unknown EC Level: "+t)}}R.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};R.from=function(e,r){if(R.isValid(e))return e;try{return Sn(e)}catch{return r}}});var Bt=d((Wo,bt)=>{function Ct(){this.buffer=[],this.length=0}Ct.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};bt.exports=Ct});var It=d((Jo,At)=>{function ne(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}ne.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};ne.prototype.get=function(t,e){return this.data[t*this.size+e]};ne.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};ne.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};At.exports=ne});var Lt=d(_e=>{var Pn=q().getSymbolSize;_e.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Pn(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,o=[n-7];for(let s=1;s<r-1;s++)o[s]=o[s-1]-i;return o.push(6),o.reverse()};_e.getPositions=function(e){let r=[],n=_e.getRowColCoords(e),i=n.length;for(let o=0;o<i;o++)for(let s=0;s<i;s++)o===0&&s===0||o===0&&s===i-1||o===i-1&&s===0||r.push([n[o],n[s]]);return r}});var Pt=d(St=>{var Mn=q().getSymbolSize,Rt=7;St.getPositions=function(e){let r=Mn(e);return[[0,0],[r-Rt,0],[0,r-Rt]]}});var Mt=d(E=>{E.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var z={N1:3,N2:3,N3:40,N4:10};E.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};E.from=function(e){return E.isValid(e)?parseInt(e,10):void 0};E.getPenaltyN1=function(e){let r=e.size,n=0,i=0,o=0,s=null,l=null;for(let u=0;u<r;u++){i=o=0,s=l=null;for(let f=0;f<r;f++){let a=e.get(u,f);a===s?i++:(i>=5&&(n+=z.N1+(i-5)),s=a,i=1),a=e.get(f,u),a===l?o++:(o>=5&&(n+=z.N1+(o-5)),l=a,o=1)}i>=5&&(n+=z.N1+(i-5)),o>=5&&(n+=z.N1+(o-5))}return n};E.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i<r-1;i++)for(let o=0;o<r-1;o++){let s=e.get(i,o)+e.get(i,o+1)+e.get(i+1,o)+e.get(i+1,o+1);(s===4||s===0)&&n++}return n*z.N2};E.getPenaltyN3=function(e){let r=e.size,n=0,i=0,o=0;for(let s=0;s<r;s++){i=o=0;for(let l=0;l<r;l++)i=i<<1&2047|e.get(s,l),l>=10&&(i===1488||i===93)&&n++,o=o<<1&2047|e.get(l,s),l>=10&&(o===1488||o===93)&&n++}return n*z.N3};E.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let o=0;o<n;o++)r+=e.data[o];return Math.abs(Math.ceil(r*100/n/5)-10)*z.N4};function On(t,e,r){switch(t){case E.Patterns.PATTERN000:return(e+r)%2===0;case E.Patterns.PATTERN001:return e%2===0;case E.Patterns.PATTERN010:return r%3===0;case E.Patterns.PATTERN011:return(e+r)%3===0;case E.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case E.Patterns.PATTERN101:return e*r%2+e*r%3===0;case E.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case E.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}E.applyMask=function(e,r){let n=r.size;for(let i=0;i<n;i++)for(let o=0;o<n;o++)r.isReserved(o,i)||r.xor(o,i,On(e,o,i))};E.getBestMask=function(e,r){let n=Object.keys(E.Patterns).length,i=0,o=1/0;for(let s=0;s<n;s++){r(s),E.applyMask(s,e);let l=E.getPenaltyN1(e)+E.getPenaltyN2(e)+E.getPenaltyN3(e)+E.getPenaltyN4(e);E.applyMask(s,e),l<o&&(o=l,i=s)}return i}});var Ne=d(ke=>{var x=pe(),me=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],ye=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];ke.getBlocksCount=function(e,r){switch(r){case x.L:return me[(e-1)*4+0];case x.M:return me[(e-1)*4+1];case x.Q:return me[(e-1)*4+2];case x.H:return me[(e-1)*4+3];default:return}};ke.getTotalCodewordsCount=function(e,r){switch(r){case x.L:return ye[(e-1)*4+0];case x.M:return ye[(e-1)*4+1];case x.Q:return ye[(e-1)*4+2];case x.H:return ye[(e-1)*4+3];default:return}}});var Ot=d(Ee=>{var ie=new Uint8Array(512),we=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)ie[r]=e,we[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)ie[r]=ie[r-255]})();Ee.log=function(e){if(e<1)throw new Error("log("+e+")");return we[e]};Ee.exp=function(e){return ie[e]};Ee.mul=function(e,r){return e===0||r===0?0:ie[we[e]+we[r]]}});var kt=d(oe=>{var qe=Ot();oe.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let o=0;o<r.length;o++)n[i+o]^=qe.mul(e[i],r[o]);return n};oe.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let i=n[0];for(let s=0;s<r.length;s++)n[s]^=qe.mul(r[s],i);let o=0;for(;o<n.length&&n[o]===0;)o++;n=n.slice(o)}return n};oe.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=oe.mul(r,new Uint8Array([1,qe.exp(n)]));return r}});var xt=d((rs,qt)=>{var Nt=kt();function xe(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}xe.prototype.initialize=function(e){this.degree=e,this.genPoly=Nt.generateECPolynomial(this.degree)};xe.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=Nt.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(n,i),o}return n};qt.exports=xe});var Ue=d(Ut=>{Ut.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Fe=d(N=>{var Ft="[0-9]+",kn="[A-Z $%*+\\-./:]+",se="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";se=se.replace(/u/g,"\\u");var Nn="(?:(?![A-Z0-9 $%*+\\-./:]|"+se+`)(?:.|[\r
3
+ ]))+`;N.KANJI=new RegExp(se,"g");N.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");N.BYTE=new RegExp(Nn,"g");N.NUMERIC=new RegExp(Ft,"g");N.ALPHANUMERIC=new RegExp(kn,"g");var qn=new RegExp("^"+se+"$"),xn=new RegExp("^"+Ft+"$"),Un=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");N.testKanji=function(e){return qn.test(e)};N.testNumeric=function(e){return xn.test(e)};N.testAlphanumeric=function(e){return Un.test(e)}});var U=d(T=>{var Fn=Ue(),De=Fe();T.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};T.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};T.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};T.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};T.MIXED={bit:-1};T.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Fn.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};T.getBestModeForData=function(e){return De.testNumeric(e)?T.NUMERIC:De.testAlphanumeric(e)?T.ALPHANUMERIC:De.testKanji(e)?T.KANJI:T.BYTE};T.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};T.isValid=function(e){return e&&e.bit&&e.ccBits};function Dn(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return T.NUMERIC;case"alphanumeric":return T.ALPHANUMERIC;case"kanji":return T.KANJI;case"byte":return T.BYTE;default:throw new Error("Unknown mode: "+t)}}T.from=function(e,r){if(T.isValid(e))return e;try{return Dn(e)}catch{return r}}});var Gt=d(G=>{var Te=q(),Yn=Ne(),Dt=pe(),F=U(),Ye=Ue(),Ht=7973,Yt=Te.getBCHDigit(Ht);function Hn(t,e,r){for(let n=1;n<=40;n++)if(e<=G.getCapacity(n,r,t))return n}function zt(t,e){return F.getCharCountIndicator(t,e)+4}function zn(t,e){let r=0;return t.forEach(function(n){let i=zt(n.mode,e);r+=i+n.getBitsLength()}),r}function Gn(t,e){for(let r=1;r<=40;r++)if(zn(t,r)<=G.getCapacity(r,e,F.MIXED))return r}G.from=function(e,r){return Ye.isValid(e)?parseInt(e,10):r};G.getCapacity=function(e,r,n){if(!Ye.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=F.BYTE);let i=Te.getSymbolTotalCodewords(e),o=Yn.getTotalCodewordsCount(e,r),s=(i-o)*8;if(n===F.MIXED)return s;let l=s-zt(n,e);switch(n){case F.NUMERIC:return Math.floor(l/10*3);case F.ALPHANUMERIC:return Math.floor(l/11*2);case F.KANJI:return Math.floor(l/13);case F.BYTE:default:return Math.floor(l/8)}};G.getBestVersionForData=function(e,r){let n,i=Dt.from(r,Dt.M);if(Array.isArray(e)){if(e.length>1)return Gn(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Hn(n.mode,n.getLength(),i)};G.getEncodedBits=function(e){if(!Ye.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Te.getBCHDigit(r)-Yt>=0;)r^=Ht<<Te.getBCHDigit(r)-Yt;return e<<12|r}});var jt=d(Kt=>{var He=q(),Vt=1335,vn=21522,vt=He.getBCHDigit(Vt);Kt.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;He.getBCHDigit(i)-vt>=0;)i^=Vt<<He.getBCHDigit(i)-vt;return(n<<10|i)^vn}});var Jt=d((us,Wt)=>{var Vn=U();function W(t){this.mode=Vn.NUMERIC,this.data=t.toString()}W.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};W.prototype.getLength=function(){return this.data.length};W.prototype.getBitsLength=function(){return W.getBitsLength(this.data.length)};W.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let o=this.data.length-r;o>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,o*3+1))};Wt.exports=W});var Zt=d((fs,Qt)=>{var Kn=U(),ze=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function J(t){this.mode=Kn.ALPHANUMERIC,this.data=t}J.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};J.prototype.getLength=function(){return this.data.length};J.prototype.getBitsLength=function(){return J.getBitsLength(this.data.length)};J.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=ze.indexOf(this.data[r])*45;n+=ze.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(ze.indexOf(this.data[r]),6)};Qt.exports=J});var Xt=d((as,$t)=>{var jn=U();function Q(t){this.mode=jn.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Q.getBitsLength=function(e){return e*8};Q.prototype.getLength=function(){return this.data.length};Q.prototype.getBitsLength=function(){return Q.getBitsLength(this.data.length)};Q.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};$t.exports=Q});var tr=d((hs,er)=>{var Wn=U(),Jn=q();function Z(t){this.mode=Wn.KANJI,this.data=t}Z.getBitsLength=function(e){return e*13};Z.prototype.getLength=function(){return this.data.length};Z.prototype.getBitsLength=function(){return Z.getBitsLength(this.data.length)};Z.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Jn.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
4
+ Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};er.exports=Z});var rr=d((cs,Ge)=>{"use strict";var le={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var o=le.PriorityQueue.make();o.push(e,0);for(var s,l,u,f,a,h,c,g,p;!o.empty();){s=o.pop(),l=s.value,f=s.cost,a=t[l]||{};for(u in a)a.hasOwnProperty(u)&&(h=a[u],c=f+h,g=i[u],p=typeof i[u]>"u",(p||g>c)&&(i[u]=c,o.push(u,c),n[u]=l))}if(typeof r<"u"&&typeof i[r]>"u"){var m=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(m)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=le.single_source_shortest_paths(t,e,r);return le.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=le.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Ge<"u"&&(Ge.exports=le)});var ar=d($=>{var y=U(),or=Jt(),sr=Zt(),lr=Xt(),ur=tr(),ue=Fe(),Ce=q(),Qn=rr();function nr(t){return unescape(encodeURIComponent(t)).length}function fe(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function fr(t){let e=fe(ue.NUMERIC,y.NUMERIC,t),r=fe(ue.ALPHANUMERIC,y.ALPHANUMERIC,t),n,i;return Ce.isKanjiModeEnabled()?(n=fe(ue.BYTE,y.BYTE,t),i=fe(ue.KANJI,y.KANJI,t)):(n=fe(ue.BYTE_KANJI,y.BYTE,t),i=[]),e.concat(r,n,i).sort(function(s,l){return s.index-l.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function ve(t,e){switch(e){case y.NUMERIC:return or.getBitsLength(t);case y.ALPHANUMERIC:return sr.getBitsLength(t);case y.KANJI:return ur.getBitsLength(t);case y.BYTE:return lr.getBitsLength(t)}}function Zn(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function $n(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case y.NUMERIC:e.push([n,{data:n.data,mode:y.ALPHANUMERIC,length:n.length},{data:n.data,mode:y.BYTE,length:n.length}]);break;case y.ALPHANUMERIC:e.push([n,{data:n.data,mode:y.BYTE,length:n.length}]);break;case y.KANJI:e.push([n,{data:n.data,mode:y.BYTE,length:nr(n.data)}]);break;case y.BYTE:e.push([{data:n.data,mode:y.BYTE,length:nr(n.data)}])}}return e}function Xn(t,e){let r={},n={start:{}},i=["start"];for(let o=0;o<t.length;o++){let s=t[o],l=[];for(let u=0;u<s.length;u++){let f=s[u],a=""+o+u;l.push(a),r[a]={node:f,lastCount:0},n[a]={};for(let h=0;h<i.length;h++){let c=i[h];r[c]&&r[c].node.mode===f.mode?(n[c][a]=ve(r[c].lastCount+f.length,f.mode)-ve(r[c].lastCount,f.mode),r[c].lastCount+=f.length):(r[c]&&(r[c].lastCount=f.length),n[c][a]=ve(f.length,f.mode)+4+y.getCharCountIndicator(f.mode,e))}}i=l}for(let o=0;o<i.length;o++)n[i[o]].end=0;return{map:n,table:r}}function ir(t,e){let r,n=y.getBestModeForData(t);if(r=y.from(e,n),r!==y.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+y.toString(r)+`.
5
+ Suggested mode is: `+y.toString(n));switch(r===y.KANJI&&!Ce.isKanjiModeEnabled()&&(r=y.BYTE),r){case y.NUMERIC:return new or(t);case y.ALPHANUMERIC:return new sr(t);case y.KANJI:return new ur(t);case y.BYTE:return new lr(t)}}$.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(ir(n,null)):n.data&&r.push(ir(n.data,n.mode)),r},[])};$.fromString=function(e,r){let n=fr(e,Ce.isKanjiModeEnabled()),i=$n(n),o=Xn(i,r),s=Qn.find_path(o.map,"start","end"),l=[];for(let u=1;u<s.length-1;u++)l.push(o.table[s[u]].node);return $.fromArray(Zn(l))};$.rawSplit=function(e){return $.fromArray(fr(e,Ce.isKanjiModeEnabled()))}});var Qe=d(hr=>{var Be=q(),Ve=pe(),ei=Bt(),ti=It(),ri=Lt(),ni=Pt(),We=Mt(),Je=Ne(),ii=xt(),be=Gt(),oi=jt(),si=U(),Ke=ar();function li(t,e){let r=t.size,n=ni.getPositions(e);for(let i=0;i<n.length;i++){let o=n[i][0],s=n[i][1];for(let l=-1;l<=7;l++)if(!(o+l<=-1||r<=o+l))for(let u=-1;u<=7;u++)s+u<=-1||r<=s+u||(l>=0&&l<=6&&(u===0||u===6)||u>=0&&u<=6&&(l===0||l===6)||l>=2&&l<=4&&u>=2&&u<=4?t.set(o+l,s+u,!0,!0):t.set(o+l,s+u,!1,!0))}}function ui(t){let e=t.size;for(let r=8;r<e-8;r++){let n=r%2===0;t.set(r,6,n,!0),t.set(6,r,n,!0)}}function fi(t,e){let r=ri.getPositions(e);for(let n=0;n<r.length;n++){let i=r[n][0],o=r[n][1];for(let s=-2;s<=2;s++)for(let l=-2;l<=2;l++)s===-2||s===2||l===-2||l===2||s===0&&l===0?t.set(i+s,o+l,!0,!0):t.set(i+s,o+l,!1,!0)}}function ai(t,e){let r=t.size,n=be.getEncodedBits(e),i,o,s;for(let l=0;l<18;l++)i=Math.floor(l/3),o=l%3+r-8-3,s=(n>>l&1)===1,t.set(i,o,s,!0),t.set(o,i,s,!0)}function je(t,e,r){let n=t.size,i=oi.getEncodedBits(e,r),o,s;for(o=0;o<15;o++)s=(i>>o&1)===1,o<6?t.set(o,8,s,!0):o<8?t.set(o+1,8,s,!0):t.set(n-15+o,8,s,!0),o<8?t.set(8,n-o-1,s,!0):o<9?t.set(8,15-o-1+1,s,!0):t.set(8,15-o-1,s,!0);t.set(n-8,8,1,!0)}function hi(t,e){let r=t.size,n=-1,i=r-1,o=7,s=0;for(let l=r-1;l>0;l-=2)for(l===6&&l--;;){for(let u=0;u<2;u++)if(!t.isReserved(i,l-u)){let f=!1;s<e.length&&(f=(e[s]>>>o&1)===1),t.set(i,l-u,f),o--,o===-1&&(s++,o=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function ci(t,e,r){let n=new ei;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),si.getCharCountIndicator(u.mode,t)),u.write(n)});let i=Be.getSymbolTotalCodewords(t),o=Je.getTotalCodewordsCount(t,e),s=(i-o)*8;for(n.getLengthInBits()+4<=s&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let l=(s-n.getLengthInBits())/8;for(let u=0;u<l;u++)n.put(u%2?17:236,8);return di(n,t,e)}function di(t,e,r){let n=Be.getSymbolTotalCodewords(e),i=Je.getTotalCodewordsCount(e,r),o=n-i,s=Je.getBlocksCount(e,r),l=n%s,u=s-l,f=Math.floor(n/s),a=Math.floor(o/s),h=a+1,c=f-a,g=new ii(c),p=0,m=new Array(s),_=new Array(s),w=0,Se=new Uint8Array(t.buffer);for(let j=0;j<s;j++){let Pe=j<u?a:h;m[j]=Se.slice(p,p+Pe),_[j]=g.encode(m[j]),p+=Pe,w=Math.max(w,Pe)}let re=new Uint8Array(n),A=0,L,k;for(L=0;L<w;L++)for(k=0;k<s;k++)L<m[k].length&&(re[A++]=m[k][L]);for(L=0;L<c;L++)for(k=0;k<s;k++)re[A++]=_[k][L];return re}function gi(t,e,r,n){let i;if(Array.isArray(t))i=Ke.fromArray(t);else if(typeof t=="string"){let f=e;if(!f){let a=Ke.rawSplit(t);f=be.getBestVersionForData(a,r)}i=Ke.fromString(t,f||40)}else throw new Error("Invalid data");let o=be.getBestVersionForData(i,r);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
6
+ The chosen QR Code version cannot contain this amount of data.
7
+ Minimum version required to store current data is: `+o+`.
8
+ `);let s=ci(e,r,i),l=Be.getSymbolSize(e),u=new ti(l);return li(u,e),ui(u),fi(u,e),je(u,r,0),e>=7&&ai(u,e),hi(u,s),isNaN(n)&&(n=We.getBestMask(u,je.bind(null,u,r))),We.applyMask(n,u),je(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}hr.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Ve.M,i,o;return typeof r<"u"&&(n=Ve.from(r.errorCorrectionLevel,Ve.M),i=be.from(r.version),o=We.from(r.maskPattern),r.toSJISFunc&&Be.setToSJISFunction(r.toSJISFunc)),gi(e,i,n,o)}});var Ze=d((ps,dr)=>{"use strict";var pi=require("util"),cr=require("stream"),P=dr.exports=function(){cr.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};pi.inherits(P,cr);P.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};P.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};P.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};P.prototype.destroySoon=P.prototype.end;P.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};P.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};P.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};P.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],o=Math.min(i.length,t.length-e);i.copy(n,e,0,o),e+=o,o!==i.length&&(this._buffers[--r]=i.slice(o))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};P.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Xe=d($e=>{"use strict";var D=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];$e.getImagePasses=function(t,e){let r=[],n=t%8,i=e%8,o=(t-n)/8,s=(e-i)/8;for(let l=0;l<D.length;l++){let u=D[l],f=o*u.x.length,a=s*u.y.length;for(let h=0;h<u.x.length&&u.x[h]<n;h++)f++;for(let h=0;h<u.y.length&&u.y[h]<i;h++)a++;f>0&&a>0&&r.push({width:f,height:a,index:l})}return r};$e.getInterlaceIterator=function(t){return function(e,r,n){let i=e%D[n].x.length,o=(e-i)/D[n].x.length*8+D[n].x[i],s=r%D[n].y.length,l=(r-s)/D[n].y.length*8+D[n].y[s];return o*4+l*t*4}}});var et=d((ms,gr)=>{"use strict";gr.exports=function(e,r,n){let i=e+r-n,o=Math.abs(i-e),s=Math.abs(i-r),l=Math.abs(i-n);return o<=s&&o<=l?e:s<=l?r:n}});var tt=d((ys,_r)=>{"use strict";var _i=Xe(),mi=et();function pr(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var X=_r.exports=function(t,e){let r=t.width,n=t.height,i=t.interlace,o=t.bpp,s=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let l=_i.getImagePasses(r,n);for(let u=0;u<l.length;u++)this._images.push({byteWidth:pr(l[u].width,o,s),height:l[u].height,lineIndex:0})}else this._images.push({byteWidth:pr(r,o,s),height:n,lineIndex:0});s===8?this._xComparison=o:s===16?this._xComparison=o*2:this._xComparison=1};X.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};X.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,i=n-1;for(let o=0;o<r;o++){let s=t[1+o],l=o>i?e[o-n]:0;e[o]=s+l}};X.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let i=0;i<r;i++){let o=t[1+i],s=n?n[i]:0;e[i]=o+s}};X.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,i=n-1,o=this._lastLine;for(let s=0;s<r;s++){let l=t[1+s],u=o?o[s]:0,f=s>i?e[s-n]:0,a=Math.floor((f+u)/2);e[s]=l+a}};X.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,i=n-1,o=this._lastLine;for(let s=0;s<r;s++){let l=t[1+s],u=o?o[s]:0,f=s>i?e[s-n]:0,a=s>i&&o?o[s-n]:0,h=mi(f,u,a);e[s]=l+h}};X.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],i=n.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var wr=d((ws,yr)=>{"use strict";var yi=require("util"),mr=Ze(),wi=tt(),Ei=yr.exports=function(t){mr.call(this);let e=[],r=this;this._filter=new wi(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};yi.inherits(Ei,mr)});var ee=d((Es,Er)=>{"use strict";Er.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var it=d((Ts,Tr)=>{"use strict";var rt=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;rt[t]=e}})();var nt=Tr.exports=function(){this._crc=-1};nt.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=rt[(this._crc^t[e])&255]^this._crc>>>8;return!0};nt.prototype.crc32=function(){return this._crc^-1};nt.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=rt[(e^t[r])&255]^e>>>8;return e^-1}});var ot=d((Cs,Cr)=>{"use strict";var C=ee(),Ti=it(),b=Cr.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[C.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[C.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[C.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[C.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[C.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[C.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};b.prototype.start=function(){this.read(C.PNG_SIGNATURE.length,this._parseSignature.bind(this))};b.prototype._parseSignature=function(t){let e=C.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};b.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let o=4;o<8;o++)n+=String.fromCharCode(t[o]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==C.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Ti,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};b.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};b.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};b.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};b.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};b.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],i=t[9],o=t[10],s=t[11],l=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(i in C.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(o!==0){this.error(new Error("Unsupported compression method"));return}if(s!==0){this.error(new Error("Unsupported filter method"));return}if(l!==0&&l!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let u=C.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!l,palette:!!(i&C.COLORTYPE_PALETTE),color:!!(i&C.COLORTYPE_COLOR),alpha:!!(i&C.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};b.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};b.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};b.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};b.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===C.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===C.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===C.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};b.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};b.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/C.GAMMA_DIVISION),this._handleChunkEnd()};b.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};b.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===C.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};b.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};b.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var st=d(Br=>{"use strict";var br=Xe(),Ci=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],bi=[function(){},function(t,e,r,n){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function Bi(t,e){let r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");let o=t[n];n++;let s,l,u,f,a,h,c,g;switch(e){default:throw new Error("unrecognised depth");case 16:c=t[n],n++,r.push((o<<8)+c);break;case 4:c=o&15,g=o>>4,r.push(g,c);break;case 2:a=o&3,h=o>>2&3,c=o>>4&3,g=o>>6&3,r.push(g,c,h,a);break;case 1:s=o&1,l=o>>1&1,u=o>>2&1,f=o>>3&1,a=o>>4&1,h=o>>5&1,c=o>>6&1,g=o>>7&1,r.push(g,c,h,a,f,u,l,s);break}}return{get:function(o){for(;r.length<o;)i();let s=r.slice(0,o);return r=r.slice(o),s},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Ai(t,e,r,n,i,o){let s=t.width,l=t.height,u=t.index;for(let f=0;f<l;f++)for(let a=0;a<s;a++){let h=r(a,f,u);Ci[n](e,i,h,o),o+=n}return o}function Ii(t,e,r,n,i,o){let s=t.width,l=t.height,u=t.index;for(let f=0;f<l;f++){for(let a=0;a<s;a++){let h=i.get(n),c=r(a,f,u);bi[n](e,h,c,o)}i.resetAfterLine()}}Br.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,o=e.bpp,s=e.interlace,l;i!==8&&(l=Bi(t,i));let u;i<=8?u=Buffer.alloc(r*n*4):u=new Uint16Array(r*n*4);let f=Math.pow(2,i)-1,a=0,h,c;if(s)h=br.getImagePasses(r,n),c=br.getInterlaceIterator(r,n);else{let g=0;c=function(){let p=g;return g+=4,p},h=[{width:r,height:n}]}for(let g=0;g<h.length;g++)i===8?a=Ai(h[g],u,c,o,t,a):Ii(h[g],u,c,o,l,f);if(i===8){if(a!==t.length)throw new Error("extra data found")}else l.end();return u}});var lt=d((Bs,Ar)=>{"use strict";function Li(t,e,r,n,i){let o=0;for(let s=0;s<n;s++)for(let l=0;l<r;l++){let u=i[t[o]];if(!u)throw new Error("index "+t[o]+" not in palette");for(let f=0;f<4;f++)e[o+f]=u[f];o+=4}}function Ri(t,e,r,n,i){let o=0;for(let s=0;s<n;s++)for(let l=0;l<r;l++){let u=!1;if(i.length===1?i[0]===t[o]&&(u=!0):i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2]&&(u=!0),u)for(let f=0;f<4;f++)e[o+f]=0;o+=4}}function Si(t,e,r,n,i){let o=255,s=Math.pow(2,i)-1,l=0;for(let u=0;u<n;u++)for(let f=0;f<r;f++){for(let a=0;a<4;a++)e[l+a]=Math.floor(t[l+a]*o/s+.5);l+=4}}Ar.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,o=e.colorType,s=e.transColor,l=e.palette,u=t;return o===3?Li(t,u,n,i,l):(s&&Ri(t,u,n,i,s),r!==8&&(r===16&&(u=Buffer.alloc(n*i*4)),Si(t,u,n,i,r))),u}});var Rr=d((As,Lr)=>{"use strict";var Pi=require("util"),ut=require("zlib"),Ir=Ze(),Mi=wr(),Oi=ot(),ki=st(),Ni=lt(),M=Lr.exports=function(t){Ir.call(this),this._parser=new Oi(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Pi.inherits(M,Ir);M.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};M.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ut.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,ut.Z_MIN_CHUNK);this._inflate=ut.createInflate({chunkSize:n});let i=r,o=this.emit.bind(this,"error");this._inflate.on("error",function(l){i&&o(l)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(l){i&&(l.length>i&&(l=l.slice(0,i)),i-=l.length,s(l))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};M.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Mi(this._bitmapInfo)};M.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};M.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};M.prototype._simpleTransparency=function(){this._metaData.alpha=!0};M.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};M.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};M.prototype._complete=function(t){if(this.errord)return;let e;try{let r=ki.dataToBitMap(t,this._bitmapInfo);e=Ni(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Pr=d((Is,Sr)=>{"use strict";var S=ee();Sr.exports=function(t,e,r,n){let i=[S.COLORTYPE_COLOR_ALPHA,S.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let p=(function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&p)return t}let o=n.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,l=S.COLORTYPE_TO_BPP_MAP[n.inputColorType];l===4&&!n.inputHasAlpha&&(l=3);let u=S.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(s=65535,u*=2);let f=Buffer.alloc(e*r*u),a=0,h=0,c=n.bgColor||{};c.red===void 0&&(c.red=s),c.green===void 0&&(c.green=s),c.blue===void 0&&(c.blue=s);function g(){let p,m,_,w=s;switch(n.inputColorType){case S.COLORTYPE_COLOR_ALPHA:w=o[a+3],p=o[a],m=o[a+1],_=o[a+2];break;case S.COLORTYPE_COLOR:p=o[a],m=o[a+1],_=o[a+2];break;case S.COLORTYPE_ALPHA:w=o[a+1],p=o[a],m=p,_=p;break;case S.COLORTYPE_GRAYSCALE:p=o[a],m=p,_=p;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(w/=s,p=Math.min(Math.max(Math.round((1-w)*c.red+w*p),0),s),m=Math.min(Math.max(Math.round((1-w)*c.green+w*m),0),s),_=Math.min(Math.max(Math.round((1-w)*c.blue+w*_),0),s))),{red:p,green:m,blue:_,alpha:w}}for(let p=0;p<r;p++)for(let m=0;m<e;m++){let _=g(o,a);switch(n.colorType){case S.COLORTYPE_COLOR_ALPHA:case S.COLORTYPE_COLOR:n.bitDepth===8?(f[h]=_.red,f[h+1]=_.green,f[h+2]=_.blue,i&&(f[h+3]=_.alpha)):(f.writeUInt16BE(_.red,h),f.writeUInt16BE(_.green,h+2),f.writeUInt16BE(_.blue,h+4),i&&f.writeUInt16BE(_.alpha,h+6));break;case S.COLORTYPE_ALPHA:case S.COLORTYPE_GRAYSCALE:{let w=(_.red+_.green+_.blue)/3;n.bitDepth===8?(f[h]=w,i&&(f[h+1]=_.alpha)):(f.writeUInt16BE(w,h),i&&f.writeUInt16BE(_.alpha,h+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}a+=l,h+=u}return f}});var kr=d((Ls,Or)=>{"use strict";var Mr=et();function qi(t,e,r,n,i){for(let o=0;o<r;o++)n[i+o]=t[e+o]}function xi(t,e,r){let n=0,i=e+r;for(let o=e;o<i;o++)n+=Math.abs(t[o]);return n}function Ui(t,e,r,n,i,o){for(let s=0;s<r;s++){let l=s>=o?t[e+s-o]:0,u=t[e+s]-l;n[i+s]=u}}function Fi(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,l=t[e+o]-s;i+=Math.abs(l)}return i}function Di(t,e,r,n,i){for(let o=0;o<r;o++){let s=e>0?t[e+o-r]:0,l=t[e+o]-s;n[i+o]=l}}function Yi(t,e,r){let n=0,i=e+r;for(let o=e;o<i;o++){let s=e>0?t[o-r]:0,l=t[o]-s;n+=Math.abs(l)}return n}function Hi(t,e,r,n,i,o){for(let s=0;s<r;s++){let l=s>=o?t[e+s-o]:0,u=e>0?t[e+s-r]:0,f=t[e+s]-(l+u>>1);n[i+s]=f}}function zi(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,l=e>0?t[e+o-r]:0,u=t[e+o]-(s+l>>1);i+=Math.abs(u)}return i}function Gi(t,e,r,n,i,o){for(let s=0;s<r;s++){let l=s>=o?t[e+s-o]:0,u=e>0?t[e+s-r]:0,f=e>0&&s>=o?t[e+s-(r+o)]:0,a=t[e+s]-Mr(l,u,f);n[i+s]=a}}function vi(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,l=e>0?t[e+o-r]:0,u=e>0&&o>=n?t[e+o-(r+n)]:0,f=t[e+o]-Mr(s,l,u);i+=Math.abs(f)}return i}var Vi={0:qi,1:Ui,2:Di,3:Hi,4:Gi},Ki={0:xi,1:Fi,2:Yi,3:zi,4:vi};Or.exports=function(t,e,r,n,i){let o;if(!("filterType"in n)||n.filterType===-1)o=[0,1,2,3,4];else if(typeof n.filterType=="number")o=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(i*=2);let s=e*i,l=0,u=0,f=Buffer.alloc((s+1)*r),a=o[0];for(let h=0;h<r;h++){if(o.length>1){let c=1/0;for(let g=0;g<o.length;g++){let p=Ki[o[g]](t,u,s,i);p<c&&(a=o[g],c=p)}}f[l]=a,l++,Vi[a](t,u,s,f,l,i),l+=s,u+=s}return f}});var ft=d((Rs,Nr)=>{"use strict";var B=ee(),ji=it(),Wi=Pr(),Ji=kr(),Qi=require("zlib"),Y=Nr.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Qi.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:B.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:B.COLORTYPE_COLOR_ALPHA,[B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Y.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Y.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Y.prototype.filterData=function(t,e,r){let n=Wi(t,e,r,this._options),i=B.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Ji(n,e,r,this._options,i)};Y.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(ji.crc32(n.slice(4,n.length-4)),n.length-4),n};Y.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*B.GAMMA_DIVISION),0),this._packChunk(B.TYPE_gAMA,e)};Y.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(B.TYPE_IHDR,r)};Y.prototype.packIDAT=function(t){return this._packChunk(B.TYPE_IDAT,t)};Y.prototype.packIEND=function(){return this._packChunk(B.TYPE_IEND,null)}});var Fr=d((Ss,Ur)=>{"use strict";var Zi=require("util"),qr=require("stream"),$i=ee(),Xi=ft(),xr=Ur.exports=function(t){qr.call(this);let e=t||{};this._packer=new Xi(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Zi.inherits(xr,qr);xr.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from($i.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var vr=d((ae,Gr)=>{"use strict";var Dr=require("assert").ok,te=require("zlib"),eo=require("util"),Yr=require("buffer").kMaxLength;function v(t){if(!(this instanceof v))return new v(t);t&&t.chunkSize<te.Z_MIN_CHUNK&&(t.chunkSize=te.Z_MIN_CHUNK),te.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function to(t){return new v(t)}function Hr(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}v.prototype._processChunk=function(t,e,r){if(typeof r=="function")return te.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,l=0,u=[],f=0,a;this.on("error",function(p){a=p});function h(p,m){if(n._hadError)return;let _=o-m;if(Dr(_>=0,"have should not go down"),_>0){let w=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,w.length>s&&(w=w.slice(0,s)),u.push(w),f+=w.length,s-=w.length,s===0)return!1}return(m===0||n._offset>=n._chunkSize)&&(o=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),m===0?(l+=i-p,i=p,!0):!1}Dr(this._handle,"zlib binding closed");let c;do c=this._handle.writeSync(e,t,l,i,this._buffer,this._offset,o),c=c||this._writeState;while(!this._hadError&&h(c[0],c[1]));if(this._hadError)throw a;if(f>=Yr)throw Hr(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Yr.toString(16)+" bytes");let g=Buffer.concat(u,f);return Hr(this),g};eo.inherits(v,te.Inflate);function ro(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=te.Z_FINISH),t._processChunk(e,r)}function zr(t,e){return ro(new v(e),t)}Gr.exports=ae=zr;ae.Inflate=v;ae.createInflate=to;ae.inflateSync=zr});var at=d((Ps,Kr)=>{"use strict";var Vr=Kr.exports=function(t){this._buffer=t,this._reads=[]};Vr.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Vr.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Wr=d(jr=>{"use strict";var no=at(),io=tt();jr.process=function(t,e){let r=[],n=new no(t);return new io(e,{read:n.read.bind(n),write:function(o){r.push(o)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var $r=d((Os,Zr)=>{"use strict";var Jr=!0,Qr=require("zlib"),oo=vr();Qr.deflateSync||(Jr=!1);var so=at(),lo=Wr(),uo=ot(),fo=st(),ao=lt();Zr.exports=function(t,e){if(!Jr)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(A){r=A}let i;function o(A){i=A}function s(A){i.transColor=A}function l(A){i.palette=A}function u(){i.alpha=!0}let f;function a(A){f=A}let h=[];function c(A){h.push(A)}let g=new so(t);if(new uo(e,{read:g.read.bind(g),error:n,metadata:o,gamma:a,palette:l,transColor:s,inflateData:c,simpleTransparency:u}).start(),g.process(),r)throw r;let m=Buffer.concat(h);h.length=0;let _;if(i.interlace)_=Qr.inflateSync(m);else{let L=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;_=oo(m,{chunkSize:L,maxLength:L})}if(m=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let w=lo.process(_,i);m=null;let Se=fo.dataToBitMap(w,i);w=null;let re=ao(Se,i);return i.data=re,i.gamma=f||0,i}});var rn=d((ks,tn)=>{"use strict";var Xr=!0,en=require("zlib");en.deflateSync||(Xr=!1);var ho=ee(),co=ft();tn.exports=function(t,e){if(!Xr)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new co(r),i=[];i.push(Buffer.from(ho.PNG_SIGNATURE)),i.push(n.packIHDR(t.width,t.height)),t.gamma&&i.push(n.packGAMA(t.gamma));let o=n.filterData(t.data,t.width,t.height),s=en.deflateSync(o,n.getDeflateOptions());if(o=null,!s||!s.length)throw new Error("bad png - invalid compressed data response");return i.push(n.packIDAT(s)),i.push(n.packIEND()),Buffer.concat(i)}});var nn=d(ht=>{"use strict";var go=$r(),po=rn();ht.read=function(t,e){return go(t,e||{})};ht.write=function(t,e){return po(t,e)}});var ln=d(sn=>{"use strict";var _o=require("util"),on=require("stream"),mo=Rr(),yo=Fr(),wo=nn(),I=sn.PNG=function(t){on.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new mo(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new yo(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};_o.inherits(I,on);I.sync=wo;I.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};I.prototype.parse=function(t,e){if(e){let r,n;r=function(i){this.removeListener("error",n),this.data=i,e(null,this)}.bind(this),n=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};I.prototype.write=function(t){return this._parser.write(t),!0};I.prototype.end=function(t){this._parser.end(t)};I.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};I.prototype._gamma=function(t){this.gamma=t};I.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};I.bitblt=function(t,e,r,n,i,o,s,l){if(r|=0,n|=0,i|=0,o|=0,s|=0,l|=0,r>t.width||n>t.height||r+i>t.width||n+o>t.height)throw new Error("bitblt reading outside image");if(s>e.width||l>e.height||s+i>e.width||l+o>e.height)throw new Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(l+u)*e.width+s<<2,(n+u)*t.width+r<<2,(n+u)*t.width+r+i<<2)};I.prototype.bitblt=function(t,e,r,n,i,o,s){return I.bitblt(this,t,e,r,n,i,o,s),this};I.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let i=0;i<3;i++){let o=t.data[n+i]/255;o=Math.pow(o,1/2.2/t.gamma),t.data[n+i]=Math.round(o*255)}}t.gamma=0}};I.prototype.adjustGamma=function(){I.adjustGamma(this)}});var he=d(V=>{function un(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}V.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:un(e.color.dark||"#000000ff"),light:un(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};V.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};V.getImageWidth=function(e,r){let n=V.getScale(e,r);return Math.floor((e+r.margin*2)*n)};V.qrToImageData=function(e,r,n){let i=r.modules.size,o=r.modules.data,s=V.getScale(i,n),l=Math.floor((i+n.margin*2)*s),u=n.margin*s,f=[n.color.light,n.color.dark];for(let a=0;a<l;a++)for(let h=0;h<l;h++){let c=(a*l+h)*4,g=n.color.light;if(a>=u&&h>=u&&a<l-u&&h<l-u){let p=Math.floor((a-u)/s),m=Math.floor((h-u)/s);g=f[o[p*i+m]?1:0]}e[c++]=g.r,e[c++]=g.g,e[c++]=g.b,e[c]=g.a}}});var fn=d(O=>{var Eo=require("fs"),To=ln().PNG,ct=he();O.render=function(e,r){let n=ct.getOptions(r),i=n.rendererOpts,o=ct.getImageWidth(e.modules.size,n);i.width=o,i.height=o;let s=new To(i);return ct.qrToImageData(s.data,e,n),s};O.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),O.renderToBuffer(e,r,function(i,o){i&&n(i);let s="data:image/png;base64,";s+=o.toString("base64"),n(null,s)})};O.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=O.render(e,r),o=[];i.on("error",n),i.on("data",function(s){o.push(s)}),i.on("end",function(){n(null,Buffer.concat(o))}),i.pack()};O.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=!1,s=(...u)=>{o||(o=!0,i.apply(null,u))},l=Eo.createWriteStream(e);l.on("error",s),l.on("close",s),O.renderToFileStream(l,r,n)};O.renderToFileStream=function(e,r,n){O.render(r,n).pack().pipe(e)}});var an=d(Ae=>{var Co=he(),bo={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Bo={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Ao(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}Ae.render=function(t,e,r){let n=Co.getOptions(e),i=bo;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=Bo);let o=t.modules.size,s=t.modules.data,l="",u=Array(o+n.margin*2+1).join(i.WW);u=Array(n.margin/2+1).join(u+`
9
+ `);let f=Array(n.margin+1).join(i.WW);l+=u;for(let a=0;a<o;a+=2){l+=f;for(let h=0;h<o;h++){let c=s[a*o+h],g=s[(a+1)*o+h];l+=Ao(c,g,i)}l+=f+`
10
+ `}return l+=u.slice(0,-1),typeof r=="function"&&r(null,l),l};Ae.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=require("fs"),s=Ae.render(r,n);o.writeFile(e,s,i)}});var cn=d(hn=>{hn.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,o="\x1B[40m \x1B[0m",s="\x1B[47m \x1B[0m",l="",u=Array(n+3).join(s),f=Array(2).join(s);l+=u+`
11
+ `;for(let a=0;a<n;++a){l+=s;for(let h=0;h<n;h++)l+=i[a*n+h]?o:s;l+=f+`
12
+ `}return l+=u+`
13
+ `,typeof r=="function"&&r(null,l),l}});var _n=d(pn=>{var Io="\x1B[47m",Lo="\x1B[40m",dt="\x1B[37m",gt="\x1B[30m",K="\x1B[0m",Ro=Io+gt,So=Lo+dt,Po=function(t,e,r){return{"00":K+" "+t,"01":K+e+"\u2584"+t,"02":K+r+"\u2584"+t,10:K+e+"\u2580"+t,11:" ",12:"\u2584",20:K+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},dn=function(t,e,r,n){let i=e+1;if(r>=i||n>=i||n<-1||r<-1)return"0";if(r>=e||n>=e||n<0||r<0)return"1";let o=n*e+r;return t[o]?"2":"1"},gn=function(t,e,r,n){return dn(t,e,r,n)+dn(t,e,r,n+1)};pn.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,o=!!(e&&e.inverse),s=e&&e.inverse?So:Ro,f=Po(s,o?gt:dt,o?dt:gt),a=K+`
14
+ `+s,h=s;for(let c=-1;c<n+1;c+=2){for(let g=-1;g<n;g++)h+=f[gn(i,n,g,c)];h+=f[gn(i,n,n,c)]+a}return h+=K,typeof r=="function"&&r(null,h),h}});var yn=d(mn=>{var Mo=cn(),Oo=_n();mn.render=function(t,e,r){return e&&e.small?Oo.render(t,e,r):Mo.render(t,e,r)}});var _t=d(En=>{var ko=he();function wn(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function pt(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function No(t,e,r){let n="",i=0,o=!1,s=0;for(let l=0;l<t.length;l++){let u=Math.floor(l%e),f=Math.floor(l/e);!u&&!o&&(o=!0),t[l]?(s++,l>0&&u>0&&t[l-1]||(n+=o?pt("M",u+r,.5+f+r):pt("m",i,0),i=0,o=!1),u+1<e&&t[l+1]||(n+=pt("h",s),s=0)):i++}return n}En.render=function(e,r,n){let i=ko.getOptions(r),o=e.modules.size,s=e.modules.data,l=o+i.margin*2,u=i.color.light.a?"<path "+wn(i.color.light,"fill")+' d="M0 0h'+l+"v"+l+'H0z"/>':"",f="<path "+wn(i.color.dark,"stroke")+' d="'+No(s,o,i.margin)+'"/>',a='viewBox="0 0 '+l+" "+l+'"',c='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+a+' shape-rendering="crispEdges">'+u+f+`</svg>
15
+ `;return typeof n=="function"&&n(null,c),c}});var Tn=d(Ie=>{var qo=_t();Ie.render=qo.render;Ie.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=require("fs"),l='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+Ie.render(r,n);o.writeFile(e,l,i)}});var Cn=d(Le=>{var mt=he();function xo(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function Uo(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Le.render=function(e,r,n){let i=n,o=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(o=Uo()),i=mt.getOptions(i);let s=mt.getImageWidth(e.modules.size,i),l=o.getContext("2d"),u=l.createImageData(s,s);return mt.qrToImageData(u.data,e,i),xo(l,o,s),l.putImageData(u,0,0),o};Le.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let o=Le.render(e,r,i),s=i.type||"image/png",l=i.rendererOpts||{};return o.toDataURL(s,l.quality)}});var Bn=d(ce=>{var Fo=Me(),yt=Qe(),bn=Cn(),Do=_t();function wt(t,e,r,n,i){let o=[].slice.call(arguments,1),s=o.length,l=typeof o[s-1]=="function";if(!l&&!Fo())throw new Error("Callback required as last argument");if(l){if(s<2)throw new Error("Too few arguments provided");s===2?(i=r,r=e,e=n=void 0):s===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(r=e,e=n=void 0):s===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,f){try{let a=yt.create(r,n);u(t(a,e,n))}catch(a){f(a)}})}try{let u=yt.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}ce.create=yt.create;ce.toCanvas=wt.bind(null,bn.render);ce.toDataURL=wt.bind(null,bn.renderToDataURL);ce.toString=wt.bind(null,function(t,e,r){return Do.render(t,r)})});var An=Me(),Et=Qe(),Yo=fn(),In=an(),Ho=yn(),Ln=Tn();function de(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(An())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function zo(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Re(t){switch(t){case"svg":return Ln;case"txt":case"utf8":return In;default:return Yo}}function Go(t){switch(t){case"svg":return Ln;case"terminal":return Ho;default:return In}}function ge(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let o=Et.create(e,r.opts);return t(o,r.opts,function(s,l){return s?i(s):n(l)})}catch(o){i(o)}});try{let n=Et.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}exports.create=Et.create;exports.toCanvas=Bn().toCanvas;exports.toString=function(e,r,n){let i=de(e,r,n),o=i.opts?i.opts.type:void 0,s=Go(o);return ge(s.render,e,i)};exports.toDataURL=function(e,r,n){let i=de(e,r,n),o=Re(i.opts.type);return ge(o.renderToDataURL,e,i)};exports.toBuffer=function(e,r,n){let i=de(e,r,n),o=Re(i.opts.type);return ge(o.renderToBuffer,e,i)};exports.toFile=function(e,r,n,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!An())throw new Error("Too few arguments provided");let o=de(r,n,i),s=o.opts.type||zo(e),u=Re(s).renderToFile.bind(null,e);return ge(u,r,o)};exports.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=de(r,n,e.emit.bind(e,"error")),s=Re("png").renderToFileStream.bind(null,e);ge(s,r,i)};
@@ -987,6 +987,71 @@ def claude_provider_command_inventory(
987
987
  )
988
988
 
989
989
 
990
+ def gemini_provider_skill_inventory(raw: str, *, cwd: str, selector_secret: str,
991
+ binding_context: str) -> ProviderCommandInventory:
992
+ """Project the pinned CLI's own resolved inventory, not a guessed scanner.
993
+
994
+ CLI 0.64 has no JSON skills command. Parse its exact bounded list format and
995
+ fail closed on ambiguous output. Paths/content stay server-side; invocation
996
+ asks Gemini's native activate_skill tool and never grants a tool permission.
997
+ """
998
+ records = []
999
+ text = raw.replace("\r\n", "\n")
1000
+ if text.strip() == "No skills discovered.":
1001
+ return _inventory(selector_secret, binding_context, "gemini", cwd, [], truncated=False)
1002
+ header = "Discovered Agent Skills:\n\n"
1003
+ if not text.startswith(header) or len(text.encode()) > 1024 * 1024:
1004
+ raise ProviderCommandDiscoveryError("Gemini skill inventory format is unsupported")
1005
+ blocks = text[len(header):].rstrip("\n").split("\n\n")
1006
+ if len(blocks) > MAX_PROVIDER_COMMANDS:
1007
+ raise ProviderCommandDiscoveryError("Gemini skill inventory exceeded its limit")
1008
+ seen = set()
1009
+ total = 0
1010
+ for block in blocks:
1011
+ match = re.fullmatch(r"([^\n]+) \[(Enabled|Disabled)\]( \[Built-in\])?\n Description: ([\s\S]*?)\n Location: ([^\n]+)", block)
1012
+ if not match:
1013
+ raise ProviderCommandDiscoveryError("Gemini skill inventory format is unsupported")
1014
+ name, enabled, builtin, description, location = match.groups()
1015
+ if enabled == "Disabled":
1016
+ continue
1017
+ # Native names can be more permissive than our slash-token grammar.
1018
+ # Such skills remain usable by the agent but are not offered as tokens.
1019
+ if canonical_provider_command_name(name) is None:
1020
+ continue
1021
+ if name.casefold() in seen:
1022
+ raise ProviderCommandDiscoveryError("Gemini skill names are ambiguous")
1023
+ seen.add(name.casefold())
1024
+ path = Path(location)
1025
+ if not path.is_absolute() or path.name != "SKILL.md" or len(location) > MAX_PROVIDER_COMMAND_PATH_CHARS:
1026
+ raise ProviderCommandDiscoveryError("Gemini returned an invalid skill location")
1027
+ # Resolve native installed links, then open only a regular, bounded file.
1028
+ # Discovery/revalidation is read-only; never use this path as a command.
1029
+ path = path.resolve(strict=True)
1030
+ descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1031
+ try:
1032
+ info = os.fstat(descriptor)
1033
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
1034
+ raise ProviderCommandDiscoveryError("Gemini skill file is unsupported")
1035
+ data = os.read(descriptor, 1024 * 1024 + 1)
1036
+ after = os.fstat(descriptor)
1037
+ if len(data) > 1024 * 1024 or (info.st_size, info.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
1038
+ raise ProviderCommandDiscoveryError("Gemini skill changed during discovery")
1039
+ finally:
1040
+ os.close(descriptor)
1041
+ total += len(data)
1042
+ if total > 16 * 1024 * 1024:
1043
+ raise ProviderCommandDiscoveryError("Gemini skills exceeded the aggregate limit")
1044
+ digest = hashlib.sha256(data).hexdigest()
1045
+ command_id = _opaque_command_id(selector_secret, binding_context, "gemini", cwd,
1046
+ name, json.dumps([str(path), digest]))
1047
+ records.append(ProviderCommandRecord(public={
1048
+ "id": command_id, "name": name, "label": name,
1049
+ "description": sanitize_provider_command_text(description, MAX_PROVIDER_COMMAND_DESCRIPTION_CHARS),
1050
+ "scope": "built-in" if builtin else "native", "source": "gemini", "kind": "skill", "invocation": f"/{name}",
1051
+ }, native={"name": name, "path": str(path), "content_sha256": digest}))
1052
+ return _inventory(selector_secret, binding_context, "gemini", cwd, records, truncated=False)
1053
+
1054
+
990
1055
  def empty_provider_command_inventory(
991
1056
  backend: str,
992
1057
  *,
@@ -28,7 +28,7 @@ MAX_BODY_BYTES = 16 * 1024
28
28
  # Reasoning can consume output tokens before the short visible check answer.
29
29
  # Keep this explicit probe bounded and single-shot, including for such models.
30
30
  MODEL_CHECK_MAX_OUTPUT_TOKENS = 256
31
- PROTOCOLS = {"claude": {"anthropic"}, "opencode": {"anthropic", "chat_completions", "responses"}, "cursor": {"cursor"}}
31
+ PROTOCOLS = {"claude": {"anthropic"}, "opencode": {"anthropic", "chat_completions", "responses"}, "cursor": {"cursor"}, "gemini": {"gemini"}}
32
32
  RESULTS = {"verified", "authentication_failed", "rate_limited", "unsupported", "connection_failed", "invalid_response", "model_required", "cli_update_required"}
33
33
 
34
34
 
@@ -52,9 +52,11 @@ def selection(backend: str, value: object) -> dict:
52
52
  from cursor_api_key import ENDPOINT
53
53
  if value["base_url"] != ENDPOINT or value["protocol"] != "cursor" or value["auth_header"] != "bearer":
54
54
  raise HTTPException(400, "Cursor API keys use Cursor's official service only.")
55
- if not isinstance(value["protocol"], str) or not isinstance(value["auth_header"], str) or value["protocol"] not in PROTOCOLS[backend] or value["auth_header"] not in {"bearer", "x-api-key"}:
55
+ if not isinstance(value["protocol"], str) or not isinstance(value["auth_header"], str) or value["protocol"] not in PROTOCOLS[backend] or value["auth_header"] not in {"bearer", "x-api-key", "x-goog-api-key"}:
56
56
  raise HTTPException(400, "Unsupported API protocol or authentication header.")
57
- if value["protocol"] != "anthropic" and value["auth_header"] != "bearer":
57
+ if (value["protocol"] == "gemini") != (value["auth_header"] == "x-goog-api-key"):
58
+ raise HTTPException(400, "Gemini API requires x-goog-api-key authentication.")
59
+ if value["protocol"] not in {"anthropic", "gemini"} and value["auth_header"] != "bearer":
58
60
  raise HTTPException(400, "This API protocol requires bearer authentication.")
59
61
  selected = validate_selection({"base_url": value["base_url"], "api_key": value["api_key"],
60
62
  "model": None if value["model"] == "" else value["model"]})
@@ -207,11 +209,15 @@ class ConnectionStore:
207
209
  try:
208
210
  value = self.for_session(session) if session else self.read(backend)
209
211
  configured = value.get("configured") is True and value.get("last_result") == "verified"
212
+ model = value.get("model")
213
+ if configured and backend == "gemini":
214
+ from gemini_api import default_model
215
+ model = default_model(value)
210
216
  if summary:
211
217
  # Large endpoint inventories belong to detail/settings reads,
212
218
  # not repeated once for every row of a session-list response.
213
219
  return {"configured": configured, "available": configured and installed,
214
- "model": value.get("model"), "base_url": value.get("base_url")}
220
+ "model": model, "base_url": value.get("base_url")}
215
221
  models = []
216
222
  if configured:
217
223
  cache_key = (backend, value["revision"])
@@ -225,12 +231,14 @@ class ConnectionStore:
225
231
  self.catalog_cache.pop(next(iter(self.catalog_cache)))
226
232
  if backend == "cursor" and not models:
227
233
  models = [{"value": "auto", "label": "Auto"}]
228
- model = value.get("model")
234
+ if backend == "gemini":
235
+ from gemini_api import model_options
236
+ models = model_options(value, models)
229
237
  if model and not any(item["value"] == model for item in models):
230
238
  models = [{"value": model, "label": model}, *models]
231
239
  return {"configured": configured, "available": configured and installed,
232
- "models": models, "efforts": [], "default_model": value.get("model"),
233
- "model": value.get("model"), "default_effort": None, "base_url": value.get("base_url")}
240
+ "models": models, "efforts": [], "default_model": model,
241
+ "model": model, "default_effort": None, "base_url": value.get("base_url")}
234
242
  except HTTPException:
235
243
  return {"configured": False, "available": False, "models": [], "efforts": [], "model": None, "base_url": None}
236
244
 
@@ -317,6 +325,9 @@ def require_model(value: dict) -> str:
317
325
 
318
326
 
319
327
  def discover_models(value: dict) -> list[dict]:
328
+ if value["protocol"] == "gemini":
329
+ from gemini_api import catalog
330
+ return catalog(value)["models"]
320
331
  return endpoint_model_catalog(value, protocol=value["protocol"])["models"]
321
332
 
322
333
 
@@ -355,6 +366,9 @@ def native_credentials_present(backend: str, diagnostic: dict) -> bool:
355
366
 
356
367
  async def probe_credentials(selected: dict) -> str:
357
368
  """Read-only key check. Public model lists alone never verify a credential."""
369
+ if selected.get("protocol") == "gemini":
370
+ from gemini_api import probe as gemini_probe
371
+ return await gemini_probe({**selected, "model": None})
358
372
  base = selected["base_url"]
359
373
  protocol = selected.get("protocol", "responses")
360
374
  headers = {"Accept": "application/json", "anthropic-version": "2023-06-01"}
@@ -397,6 +411,9 @@ async def probe_credentials(selected: dict) -> str:
397
411
 
398
412
  async def probe(selected: dict) -> str:
399
413
  """One small, explicit model request; no tools/history, redirects or retries."""
414
+ if selected.get("protocol") == "gemini":
415
+ from gemini_api import probe as gemini_probe
416
+ return await gemini_probe(selected)
400
417
  if not selected.get("model"):
401
418
  return await probe_credentials(selected)
402
419
  protocol = selected["protocol"]
@@ -546,7 +563,7 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
546
563
  return JSONResponse(value, headers={"Cache-Control": "no-store"})
547
564
 
548
565
  async def model_selection(backend, session_id=None):
549
- if backend not in {"codex", "claude", "opencode", "cursor"}:
566
+ if backend not in {"codex", "claude", "opencode", "cursor", "gemini"}:
550
567
  raise HTTPException(400, "Unsupported custom endpoint.")
551
568
  session = session_lookup(session_id) if session_id and session_lookup else None
552
569
  if session_id and (not session or session.get("backend") != backend):
@@ -567,6 +584,10 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
567
584
  if backend == "cursor":
568
585
  if cursor_catalog is None: raise HTTPException(501, "Cursor API keys are unavailable.")
569
586
  result = await cursor_catalog(selected)
587
+ elif backend == "gemini":
588
+ from gemini_api import catalog, model_options
589
+ result = await asyncio.to_thread(catalog, selected)
590
+ result["models"] = model_options(selected, result["models"])
570
591
  else:
571
592
  result = await asyncio.to_thread(endpoint_model_catalog, selected, protocol=selected.get("protocol", "responses"))
572
593
  # Fence a settings read that raced replacement/forget. Session bindings
@@ -581,8 +602,12 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
581
602
  with store.lock:
582
603
  store.catalog_cache[(backend, selected["revision"])] = (time.monotonic(), result["models"])
583
604
  if len(store.catalog_cache) > 32: store.catalog_cache.pop(next(iter(store.catalog_cache)))
605
+ model = selected.get("model")
606
+ if backend == "gemini":
607
+ from gemini_api import default_model
608
+ model = default_model(selected)
584
609
  return reply({"backend": backend, "revision": selected.get("credential_id") if backend == "codex" else selected["revision"],
585
- "models": result["models"], "default_model": selected.get("model"), "discovery_status": result["discovery_status"]})
610
+ "models": result["models"], "default_model": model, "discovery_status": result["discovery_status"]})
586
611
 
587
612
  @router.put("/api/admin/provider-models/{backend}")
588
613
  async def default_model(backend: str, request: Request):
@@ -611,7 +636,11 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
611
636
  saved = store.write(backend, current["revision"], {**value, "model": model, "expected_revision": current["revision"]}, current["last_result"], checked_at=current["checked_at"])
612
637
  cached = store.catalog_cache.get((backend, current["revision"]))
613
638
  if cached: store.catalog_cache[(backend, saved["revision"])] = cached
614
- return {"backend": backend, "revision": saved["revision"], "default_model": saved["model"]}
639
+ effective_model = saved["model"]
640
+ if backend == "gemini":
641
+ from gemini_api import default_model as gemini_default_model
642
+ effective_model = gemini_default_model(saved)
643
+ return {"backend": backend, "revision": saved["revision"], "default_model": effective_model}
615
644
  return reply(await asyncio.to_thread(save_model))
616
645
 
617
646
  @router.get("/api/admin/provider-accounts/{backend}")
@@ -256,9 +256,9 @@ def create_public_chat_share_router(
256
256
  raise ValueError("Invalid page")
257
257
  return page
258
258
 
259
- def render_page(value, path):
259
+ def render_page(value, path, *, analytics=False):
260
260
  return render_public_chat_html(value["snapshot"], page=value["page"], page_count=value["page_count"],
261
- message_count=value["message_count"], navigation_base=path)
261
+ message_count=value["message_count"], navigation_base=path, analytics=analytics)
262
262
 
263
263
  def last_page_redirect(path, page):
264
264
  return Response(status_code=303, headers={**public_chat_share_headers(),
@@ -292,10 +292,11 @@ def create_public_chat_share_router(
292
292
  if page is None:
293
293
  return last_page_redirect(request.url.path, value["page"])
294
294
  try:
295
- content = await worker(lambda: render_page(value, request.url.path), public=True)
295
+ content = await worker(lambda: render_page(value, request.url.path, analytics=request.method == "GET"), public=True)
296
296
  except Exception:
297
297
  return Response("Shared conversation temporarily unavailable.", status_code=503, headers=headers)
298
- return Response(content if request.method == "GET" else b"", headers=headers)
298
+ return Response(content if request.method == "GET" else b"",
299
+ headers=public_chat_share_headers(analytics=request.method == "GET"))
299
300
 
300
301
  @router.post("/shared-chat/{share_id}/unlock", include_in_schema=False)
301
302
  async def unlock(share_id: str, request: Request):
@@ -348,7 +349,7 @@ def create_public_chat_share_router(
348
349
  value = await worker(lambda: store().get_snapshot_page(token, page=page), public=True)
349
350
  if page is None:
350
351
  return last_page_redirect(request.url.path, value["page"])
351
- content = await worker(lambda: render_page(value, request.url.path), public=True)
352
+ content = await worker(lambda: render_page(value, request.url.path, analytics=request.method == "GET"), public=True)
352
353
  except PublicChatShareUnavailable:
353
354
  return Response("Shared conversation unavailable.", status_code=404, headers=headers)
354
355
  except HTTPException as exc:
@@ -360,7 +361,8 @@ def create_public_chat_share_router(
360
361
  # Never expose filesystem, database, or implementation details on
361
362
  # the unauthenticated viewer, including an unexpected failure.
362
363
  return Response("Shared conversation temporarily unavailable.", status_code=503, headers=headers)
363
- return Response(content if request.method == "GET" else b"", media_type="text/html", headers=headers)
364
+ return Response(content if request.method == "GET" else b"", media_type="text/html",
365
+ headers=public_chat_share_headers(analytics=request.method == "GET"))
364
366
 
365
367
  async def video_response(request, token, page, message_index, video_index, *, share_id=None):
366
368
  headers = {**public_chat_share_headers(), "Cross-Origin-Resource-Policy": "same-origin"}