@fish-under-sea/magpie-dragonapi 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@fish-under-sea/magpie-dragonapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "DragonAPI for magpie: a provider plugin whose models, groups and prices come from the site's public /api/pricing, with balance and per-call usage from an sk- key, plus a local page that lists the market (read-only), shows usage and can mint new keys for a group.",
5
+ "type": "module",
6
+ "main": "index.mjs",
7
+ "exports": {
8
+ ".": "./index.mjs",
9
+ "./page": "./page/index.html"
10
+ },
11
+ "scripts": {
12
+ "test": "node --test --test-isolation=none \"tests/*.test.mjs\"",
13
+ "serve": "node serve.mjs"
14
+ },
15
+ "license": "MIT",
16
+ "files": [
17
+ "index.mjs",
18
+ "lib",
19
+ "page",
20
+ "ui",
21
+ "serve.mjs",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "keywords": [
26
+ "magpie",
27
+ "magpie-provider",
28
+ "magpie-page",
29
+ "opencode-plugin",
30
+ "dragonapi",
31
+ "new-api",
32
+ "relay"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/Fish-under-sea/magpie-dragonapi.git"
37
+ },
38
+ "homepage": "https://github.com/Fish-under-sea/magpie-dragonapi#readme",
39
+ "bugs": {
40
+ "url": "https://github.com/Fish-under-sea/magpie-dragonapi/issues"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "magpie": {
46
+ "icon": "page/icon.svg",
47
+ "page": {
48
+ "title": "DragonAPI",
49
+ "titles": {
50
+ "zh": "DragonAPI",
51
+ "zh-TW": "DragonAPI",
52
+ "ja": "DragonAPI",
53
+ "de": "DragonAPI"
54
+ },
55
+ "file": "page/index.html",
56
+ "icon": "page/icon.svg",
57
+ "service": {
58
+ "port": 3517,
59
+ "option": "port"
60
+ }
61
+ },
62
+ "options": {
63
+ "port": 3517,
64
+ "site": "https://newapi.dragon3api.com"
65
+ }
66
+ }
67
+ }
package/page/boot.js ADDED
@@ -0,0 +1,112 @@
1
+ // 带路页:把 magpie 页面那个沙箱框架导航到本插件的本地服务。
2
+ //
3
+ // 为什么必须「直接跳」,不能先探测:
4
+ //
5
+ // 页面的 CSP 是 `connect-src 'none'`,fetch / XHR / WebSocket 全被禁止,
6
+ // 连 no-cors 的请求都会被直接拒绝。所以「先看看服务在不在再决定跳不跳」
7
+ // 这条路走不通——探测永远失败,页面会永远停在等待页。唯一可行的是直接
8
+ // `location.replace`。这一点社区插件 page-chat 的 SERVE.md 也写过。
9
+ //
10
+ // 跳到哪里,分三种情况:
11
+ //
12
+ // 1. 桌面窗口:`magpie.service` 是空字符串,页面直接跳 127.0.0.1:<port>。
13
+ // 2. magpie web(在另一台机器上打开):127.0.0.1 是看页面那台电脑自己,
14
+ // 不是跑服务的那台。这时 bridge 会给出 `magpie.service`——magpie web
15
+ // 在自己的地址上替本服务转发的路径(package.json 的 magpie.page.service
16
+ // 声明了它)。有就跳那里。
17
+ // 3. 旧版 magpie 既没有 service、又不在本机:给出 SSH 端口转发的做法。
18
+ (async () => {
19
+ const DEFAULT_PORT = 3517
20
+ let port = DEFAULT_PORT
21
+ let theme = ''
22
+ let tokens = null
23
+ let service = ''
24
+
25
+ try {
26
+ const t = await window.magpie?.ready
27
+ if (t) {
28
+ if (typeof t.dark === 'boolean') theme = t.dark ? 'dark' : 'light'
29
+ if (t.tokens && typeof t.tokens === 'object') tokens = t.tokens
30
+ }
31
+ } catch { /* 没有 bridge 就退回默认主题 */ }
32
+
33
+ try {
34
+ const s = window.magpie?.service
35
+ if (typeof s === 'string' && /^https?:\/\//.test(s)) service = s
36
+ } catch { /* 旧版 magpie 没有 service */ }
37
+
38
+ try {
39
+ const o = await window.magpie?.options?.get?.()
40
+ if (o && Number.isFinite(Number(o.port)) && Number(o.port) > 0) port = Number(o.port)
41
+ } catch { /* 没有 options 就用默认端口 */ }
42
+
43
+ // 主题与设计令牌一起带过去:magpie 的 bridge 已经把它们算好了,
44
+ // 这样界面配色和字体跟窗口完全一致,连用户的自定义主题也算在内。
45
+ const q = new URLSearchParams()
46
+ if (theme) q.set('theme', theme)
47
+ const slim = {}
48
+ for (const [k, v] of Object.entries(tokens || {})) {
49
+ const s = String(v ?? '').trim()
50
+ if (s) slim[k] = s
51
+ }
52
+ if (Object.keys(slim).length) q.set('tokens', JSON.stringify(slim))
53
+
54
+ /** 5 秒后这份文档还活着,说明跳转没走成,换成能操作的提示。 */
55
+ function armTimeout(p) {
56
+ setTimeout(() => {
57
+ const said = document.getElementById('said')
58
+ if (!said) return
59
+ said.textContent = '本地服务没有在运行(127.0.0.1:' + p + ')'
60
+ if (document.getElementById('boot-retry')) return
61
+ const btn = document.createElement('button')
62
+ btn.id = 'boot-retry'
63
+ btn.type = 'button'
64
+ btn.textContent = '重试'
65
+ btn.addEventListener('click', () => location.reload())
66
+ said.parentNode.appendChild(btn)
67
+ }, 5000)
68
+ }
69
+
70
+ if (service) {
71
+ armTimeout(port)
72
+ location.replace(service + '?' + q.toString())
73
+ return
74
+ }
75
+
76
+ const target = 'http://127.0.0.1:' + port + '/?' + q.toString()
77
+
78
+ if (!isLoopback(location.hostname)) {
79
+ showRemote(port, target)
80
+ return
81
+ }
82
+ armTimeout(port)
83
+ location.replace(target)
84
+ })()
85
+
86
+ function isLoopback(host) {
87
+ const h = String(host || '').toLowerCase().replace(/^\[|\]$/g, '')
88
+ return h === '' || h === 'localhost' || h.endsWith('.localhost') || h === '::1' || /^127\./.test(h)
89
+ }
90
+
91
+ function showRemote(port, target) {
92
+ const said = document.getElementById('said')
93
+ if (!said) return
94
+ const host = location.hostname.replace(/^\[|\]$/g, '')
95
+ said.textContent = ''
96
+ const p = (text) => {
97
+ const el = document.createElement('p')
98
+ el.textContent = text
99
+ said.appendChild(el)
100
+ return el
101
+ }
102
+ p('界面服务只在运行 magpie 的那台机器上监听 127.0.0.1:' + port + ',从这台电脑的浏览器连不到它。')
103
+ p('在这台电脑上开一个 SSH 端口转发,然后点「继续」:')
104
+ const code = p('ssh -N -L ' + port + ':127.0.0.1:' + port + ' <用户名>@' + host)
105
+ code.style.fontFamily = 'ui-monospace, Menlo, Consolas, monospace'
106
+ code.style.userSelect = 'all'
107
+ const go = document.createElement('button')
108
+ go.type = 'button'
109
+ go.textContent = '继续'
110
+ go.addEventListener('click', () => location.replace(target))
111
+ said.parentNode.appendChild(go)
112
+ }
package/page/icon.svg ADDED
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" role="img" aria-label="DragonAPI">
2
+ <defs>
3
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#f0532d"/>
5
+ <stop offset="1" stop-color="#8b1f0a"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect width="128" height="128" rx="28" fill="url(#g)"/>
9
+ <path d="M30 84c14-4 20-14 22-26 3 12 8 20 20 24-8 3-13 7-15 14 9-2 16-1 22 3-6 2-11 6-14 12-6-9-16-14-30-13z" fill="#fff" opacity=".95"/>
10
+ <path d="M84 40c6 6 10 14 10 24 0 16-12 26-26 30 8-6 12-14 12-24 0-10-4-18-10-24 5-2 10-4 14-6z" fill="#fff" opacity=".7"/>
11
+ <circle cx="78" cy="52" r="3.4" fill="#8b1f0a"/>
12
+ </svg>
@@ -0,0 +1,32 @@
1
+ <!doctype html>
2
+ <html lang="zh">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>DragonAPI</title>
7
+ <style>
8
+ :root { color-scheme: light dark; }
9
+ html, body { margin: 0; height: 100%; }
10
+ body {
11
+ display: grid; place-items: center;
12
+ font: 13px/1.5 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif);
13
+ background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText);
14
+ }
15
+ .box { text-align: center; color: var(--magpie-muted, GrayText); max-width: 32em; padding: 0 16px; }
16
+ .box b { display: block; color: var(--magpie-fg, CanvasText); font-size: 14px; margin-bottom: 6px; }
17
+ .box button {
18
+ margin-top: 10px; padding: 4px 14px; font: inherit; cursor: pointer;
19
+ border-radius: 6px; border: 1px solid currentColor; background: transparent; color: inherit;
20
+ }
21
+ .box code { font-family: ui-monospace, Menlo, Consolas, monospace; user-select: all; }
22
+ </style>
23
+ </head>
24
+ <body>
25
+ <div class="box">
26
+ <b>DragonAPI</b>
27
+ <span id="said">正在连接到本地服务…</span>
28
+ </div>
29
+ <script src="_magpie/bridge.js"></script>
30
+ <script src="boot.js"></script>
31
+ </body>
32
+ </html>
package/serve.mjs ADDED
@@ -0,0 +1,110 @@
1
+ // 独立启动本地服务,不依赖 magpie 的插件宿主。
2
+ //
3
+ // 用法:node serve.mjs
4
+ //
5
+ // 存在的意义:插件宿主被别的插件拖慢、或者根本没起来时,界面就打不开。
6
+ // 这时可以用这个脚本单独把服务拉起来。它和插件起的是同一个服务,读同一份
7
+ // 状态文件,所以不会打架——但两个一起跑会抢端口,所以先探测一下。
8
+ //
9
+ // 注意:单独起的服务**没有 magpie 的账号钥匙**,余额与用量会显示为「—」,
10
+ // 模型广场、密钥管理、PAT 这些照常可用。钥匙只有插件进程才知道。
11
+
12
+ import { homedir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { existsSync } from 'node:fs'
15
+
16
+ import { startService } from './lib/service.mjs'
17
+ import { createCatalogSource } from './lib/catalog-source.mjs'
18
+ import { createStatusSource } from './lib/status-source.mjs'
19
+ import { loadState, saveState } from './lib/store.mjs'
20
+
21
+ const CANDIDATES = [3517, 3518, 3519, 3520]
22
+ const SITE = process.env.DRAGONAPI_SITE || 'https://newapi.dragon3api.com'
23
+
24
+ /** 探测是否已经有一个服务在跑。 */
25
+ async function alreadyRunning() {
26
+ for (const p of CANDIDATES) {
27
+ try {
28
+ const res = await fetch('http://127.0.0.1:' + p + '/api/ping', { signal: AbortSignal.timeout(800) })
29
+ if (res.ok) {
30
+ const j = await res.json().catch(() => null)
31
+ if (j && j.ok) return { port: p, version: j.version }
32
+ }
33
+ } catch { /* 这个端口没有 */ }
34
+ }
35
+ return null
36
+ }
37
+
38
+ /** 猜 magpie 的配置目录:插件宿主会把它作为 input.directory 交进来。 */
39
+ function guessDir() {
40
+ const candidates = []
41
+ if (process.env.DRAGONAPI_DIR) candidates.push(process.env.DRAGONAPI_DIR)
42
+ const xdg = String(process.env.XDG_CONFIG_HOME || '').trim()
43
+ if (xdg) candidates.push(join(xdg, 'magpie'))
44
+ candidates.push(join(homedir(), '.config', 'magpie'))
45
+ if (process.platform === 'win32') {
46
+ const appdata = String(process.env.APPDATA || '').trim()
47
+ if (appdata) candidates.push(join(appdata, 'magpie'))
48
+ }
49
+ for (const d of candidates) {
50
+ if (existsSync(join(d, 'plugins.json'))) return d
51
+ }
52
+ return candidates[candidates.length - 1]
53
+ }
54
+
55
+ const alive = await alreadyRunning()
56
+ if (alive) {
57
+ console.log('')
58
+ console.log(' 界面服务已经在运行了')
59
+ console.log(' 地址: http://127.0.0.1:' + alive.port + ' (版本 ' + (alive.version || '?') + ')')
60
+ console.log(' 不需要再起一个,直接去 magpie 里打开「DragonAPI」即可。')
61
+ console.log('')
62
+ process.exit(0)
63
+ }
64
+
65
+ const dir = guessDir()
66
+ const state = loadState(dir)
67
+
68
+ // 与插件同一套源,只是没有钥匙:余额会显示「—」。
69
+ const catalog = createCatalogSource({ site: SITE })
70
+ const status = createStatusSource({
71
+ site: SITE,
72
+ seed: state.status || null,
73
+ onRead: (v) => { state.status = v; saveState(dir, state) },
74
+ })
75
+
76
+ const info = await startService({
77
+ port: 3517,
78
+ dir,
79
+ site: SITE,
80
+ catalog,
81
+ status,
82
+ getState: async () => ({
83
+ accounts: state.accounts || {},
84
+ pat: state.pat || '',
85
+ patHint: state.patHint || '',
86
+ patScopes: state.patScopes || [],
87
+ enabledGroups: state.enabledGroups || [],
88
+ }),
89
+ setPat: async ({ pat, hint, scopes, user }) => {
90
+ state.pat = pat
91
+ state.patHint = hint
92
+ state.patScopes = scopes
93
+ if (user) state.user = { id: user.id, name: user.username }
94
+ saveState(dir, state)
95
+ },
96
+ // 单独跑时没有 magpie 的钥匙,余额会显示为 —。
97
+ keyOf: () => '',
98
+ }).catch((e) => {
99
+ console.error('启动失败:', e?.message || e)
100
+ process.exit(1)
101
+ })
102
+
103
+ console.log('')
104
+ console.log(' DragonAPI 界面服务已就绪')
105
+ console.log(' 地址: http://127.0.0.1:' + info.port)
106
+ console.log(' 配置目录: ' + dir)
107
+ console.log(' 这个窗口最小化即可,关掉服务就停了')
108
+ console.log('')
109
+
110
+ process.on('SIGINT', async () => { await info.close(); process.exit(0) })