@limina_ai/plugin-sdk 0.0.0-stage → 1.0.1

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/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @limina_ai/plugin-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ LIMINA 插件开发 SDK:类型定义、界面桥接、安装包校验器和 `limina-plugin` 构建命令。插件契约 v3,需要 Node.js 22 或以上版本。
4
+
5
+ ## 安装
6
+
7
+ ```sh
8
+ npm install --save-dev @limina_ai/plugin-sdk
9
+ ```
10
+
11
+ ## 构建插件
12
+
13
+ 插件项目用 `plugin.json` 声明清单、界面、执行代码与语言包,然后构建并校验:
14
+
15
+ ```sh
16
+ npx limina-plugin build
17
+ npx limina-plugin check <plugin.limina-plugin.zip>
18
+ ```
19
+
20
+ 把生成的 `.limina-plugin.zip` 在任意 LIMINA 客户端的「插件」页导入。
21
+
22
+ 完整教程、起步模板和示例见[插件开发教程](https://www.limina.cc/plugin-guide)。
@@ -0,0 +1,29 @@
1
+ zip.js 2.7.57 — BSD-3-Clause
2
+ BSD 3-Clause License
3
+
4
+ Copyright (c) 2023, Gildas Lormeau
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/archive.js ADDED
@@ -0,0 +1,58 @@
1
+ // 中文:客户端与 CLI 共用 ZIP 解析;只在内存读取,不向磁盘解压或执行代码。
2
+ // English: Shared ZIP reader for the client and CLI; never extracts to disk or executes package code.
3
+ import { ZipReader, ZipWriter, Uint8ArrayReader, Uint8ArrayWriter, TextReader } from '@zip.js/zip.js'
4
+ import { PACKAGE_FORMAT, ARCHIVE_FORMAT, limits } from './contract.js'
5
+ export const PACKAGE_LIMIT = limits.packageBytes
6
+ const decoder = new TextDecoder('utf-8', { fatal: true })
7
+ // 中文:拒绝绝对路径、路径穿越、隐藏文件及跨平台路径歧义。
8
+ // English: Reject absolute paths, traversal, hidden files and ambiguous cross-platform paths.
9
+ function safePath(name) {
10
+ if (typeof name !== 'string' || name.length > 200 || !/^[a-zA-Z0-9_/-]+(?:\.[a-zA-Z0-9_-]+)*$/.test(name) || name.split('/').some(x => !x || x.startsWith('.'))) throw Error('插件包包含不安全的文件路径')
11
+ return name
12
+ }
13
+ // 中文:解析 JSON 或 ZIP 插件包,限制压缩包路径、条目和解压总量;清单契约仍由调用方验证。
14
+ // English: Read JSON or ZIP packages with path, entry-count and expanded-size limits; callers must still validate the manifest contract.
15
+ export async function readPackage(bytes) {
16
+ if (!(bytes instanceof Uint8Array) || bytes.length > PACKAGE_LIMIT) throw Error('插件包不能超过 2 MB')
17
+ if (bytes[0] !== 0x50 || bytes[1] !== 0x4b) return JSON.parse(decoder.decode(bytes))
18
+ const reader = new ZipReader(new Uint8ArrayReader(bytes), { useWebWorkers: false, checkSignature: true, checkOverlappingEntry: true })
19
+ const files = new Map(), seen = new Set(); let size = 0, count = 0
20
+ try {
21
+ for await (const entry of reader.getEntriesGenerator()) {
22
+ if (++count > 64) throw Error('插件 ZIP 最多包含 64 个文件和目录')
23
+ const name = safePath(entry.directory ? entry.filename.slice(0, -1) : entry.filename)
24
+ if (seen.has(name.toLowerCase())) throw Error('插件 ZIP 包含重复文件')
25
+ seen.add(name.toLowerCase())
26
+ if (entry.encrypted || ((entry.externalFileAttributes >>> 16) & 0xf000) === 0xa000) throw Error('插件 ZIP 不允许加密文件或符号链接')
27
+ if (entry.directory) continue
28
+ if (size + entry.uncompressedSize > PACKAGE_LIMIT) throw Error('插件解压后不能超过 2 MB')
29
+ const chunks = []
30
+ // 中文:实际流量也执行总量限制,不能只信任 ZIP 声明的解压大小。
31
+ // English: Limit actual streamed bytes as well as the archive's declared size.
32
+ await entry.getData(new WritableStream({ write(chunk) { size += chunk.length; if (size > PACKAGE_LIMIT) throw Error('插件解压后不能超过 2 MB'); chunks.push(chunk) } }))
33
+ const body = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0)); let offset = 0
34
+ for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.length }
35
+ files.set(name, decoder.decode(body))
36
+ }
37
+ const read = name => { safePath(name); if (!files.has(name)) throw Error(`插件包缺少文件:${name}`); return files.get(name) }
38
+ const config = JSON.parse(read('plugin.json')), views = Object.create(null)
39
+ if (config.format !== ARCHIVE_FORMAT) throw Error('无效的 ZIP 插件格式(需要契约 v3 安装包)')
40
+ for (const [name, path] of Object.entries(config.views || {})) { if (!/^(?=.{1,40}$)[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(name)) throw Error('界面入口名称无效'); views[name] = read(path) }
41
+ return { format: PACKAGE_FORMAT, manifest: JSON.parse(read(config.manifest)), views, code: config.code ? read(config.code) : '', ...(config.licenses ? { licenses: read(config.licenses) } : {}) }
42
+ } finally { await reader.close() }
43
+ }
44
+ // 中文:构建可解压查看的目录化安装包,保持运行时契约不变。
45
+ // English: Build an inspectable directory-based package without changing the runtime contract.
46
+ export async function writePackage(pkg) {
47
+ const files = { 'manifest.json': JSON.stringify(pkg.manifest, null, 2) }, views = {}
48
+ for (const [name, html] of Object.entries(pkg.views || {})) { safePath(name); const path = `views/${name}.html`; views[name] = path; files[path] = html }
49
+ if (pkg.code) files['runtime/main.js'] = pkg.code
50
+ if (pkg.licenses) files['LICENSES.txt'] = pkg.licenses
51
+ files['plugin.json'] = JSON.stringify({ format: ARCHIVE_FORMAT, manifest: 'manifest.json', views, ...(pkg.code ? { code: 'runtime/main.js' } : {}), ...(pkg.licenses ? { licenses: 'LICENSES.txt' } : {}) }, null, 2)
52
+ if (Object.values(files).reduce((n, value) => n + new TextEncoder().encode(value).length, 0) > PACKAGE_LIMIT) throw Error('插件解压后不能超过 2 MB')
53
+ const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false })
54
+ for (const [name, value] of Object.entries(files)) await writer.add(name, new TextReader(value))
55
+ const bytes = await writer.close()
56
+ if (bytes.length > PACKAGE_LIMIT) throw Error('插件包不能超过 2 MB')
57
+ return bytes
58
+ }
package/bridge.js ADDED
@@ -0,0 +1,188 @@
1
+ // 中文:客户端注入的唯一 UI SDK 实现,含超时、订阅取消与页面退出清理。
2
+ // English: The host-injected UI SDK handles timeouts, subscriptions and page-exit cleanup.
3
+ (function createUIBridge(executionPolicy, operationTimeouts, createUIController, hostContext) {
4
+ // 中文:宿主在业务 HTML 执行前注入清单预算,插件调用参数不能改变执行时限。
5
+ // English: The host injects manifest budgets before plugin HTML; call arguments cannot override execution limits.
6
+ const budgets = Object.freeze({...operationTimeouts})
7
+ const defaultExecuteWait = executionPolicy.defaultTimeoutMs + executionPolicy.transportGraceMs + executionPolicy.uiGraceMs
8
+ const pending = new Map(), events = new Map(), viewListeners = new Set(), windowListeners = new Set(), localeListeners = new Set(); let latestView, windowContext, localeContext
9
+ let controlId=null,controlAccepting=false, effects=[], controlRequests=new Set()
10
+ const ui=createUIController({async settle(){
11
+ controlAccepting=false
12
+ while(controlRequests.size)await Promise.allSettled([...controlRequests])
13
+ await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))
14
+ while(controlRequests.size)await Promise.allSettled([...controlRequests])
15
+ return effects
16
+ }})
17
+ const notify = (fn, value) => { try { fn(value) } catch (error) { console.error(error) } }
18
+ // 中文:订阅界面语言;已知语言立即回放,返回取消订阅函数。
19
+ // English: Subscribe to the locale; the known locale is replayed at once. Returns an unsubscribe function.
20
+ function onLocale(fn) {
21
+ if (typeof fn !== 'function') throw new TypeError('Locale listener must be a function')
22
+ localeListeners.add(fn)
23
+ if (localeContext) notify(fn, localeContext)
24
+ else parent.postMessage({kind: 'ready'}, '*')
25
+ return () => localeListeners.delete(fn)
26
+ }
27
+ // 中文:用插件自带语言包创建翻译器,随宿主语言热切换。
28
+ // English: Create a translator from plugin-owned language packs that follows host locale changes.
29
+ function createI18n({messages, fallbackLocale = 'en'}) {
30
+ const canonical = code => Intl.getCanonicalLocales(code)[0]
31
+ const packs = new Map(Object.entries(messages).map(([code, pack]) => [canonical(code), {...pack}]))
32
+ const fallback = canonical(fallbackLocale)
33
+ if (!packs.has(fallback)) throw new TypeError('Missing fallback language pack')
34
+ const callbacks = new Set()
35
+ let current = localeContext?.locale || fallback, disposed = false
36
+ // 中文:按 BCP 47 依次回退:完整标签、逐级更短的标签、回退语言。
37
+ // English: BCP 47 fallback order: the exact tag, progressively shorter tags, then the fallback locale.
38
+ function candidates() {
39
+ // 中文:按 BCP 47 的查找顺序:先精确标签,再逐步放宽到更通用的标签,最后兜底。
40
+ // English: Follow BCP 47 lookup: exact tag, progressively less specific tags, then fallback.
41
+ const codes = [], parts = canonical(current).split('-')
42
+ while (parts.length) { codes.push(parts.join('-')); parts.pop() }
43
+ return [...new Set([...codes, fallback])]
44
+ }
45
+ const api = Object.freeze({
46
+ get locale() { return current },
47
+ get resolvedLocale() { return candidates().find(code => packs.has(code)) },
48
+ get direction() { return localeContext?.direction || (/^(ar|he|fa|ur)(-|$)/.test(current) ? 'rtl' : 'ltr') },
49
+ t(key, params = {}) {
50
+ let text = key
51
+ for (const code of candidates()) {
52
+ const pack = packs.get(code)
53
+ if (pack && Object.hasOwn(pack, key) && typeof pack[key] === 'string') { text = pack[key]; break }
54
+ }
55
+ return text.replace(/\{([a-zA-Z_][\w]*)\}/g, (token, name) => Object.hasOwn(params, name) ? String(params[name]) : token)
56
+ },
57
+ number(value, options) { return new Intl.NumberFormat(current, options).format(value) },
58
+ date(value, options) { return new Intl.DateTimeFormat(current, options).format(value) },
59
+ subscribe(fn) {
60
+ if (disposed) throw new Error('Translator is disposed')
61
+ if (typeof fn !== 'function') throw new TypeError('Translation listener must be a function')
62
+ callbacks.add(fn); notify(fn, api)
63
+ return () => callbacks.delete(fn)
64
+ },
65
+ dispose() { disposed = true; stop(); callbacks.clear() },
66
+ })
67
+ const stop = onLocale(value => { current = value.locale; for (const fn of callbacks) notify(fn, api) })
68
+ return api
69
+ }
70
+ // 中文:宿主返回的错误保留稳定的 code,便于插件按错误类型处理。
71
+ // English: Host errors keep a stable code so plugins can branch on failure kinds.
72
+ class LiminaError extends Error { constructor(message, code) { super(message); this.name = 'LiminaError'; this.code = code || 'ERROR' } }
73
+ // 中文:向宿主发起一次请求并按类型设置等待时限;界面控制期间的请求计入本次动作的效果。
74
+ // English: Send one request to the host with a per-kind wait limit; requests made during a UI-control action count as its effects.
75
+ function request(kind, data = {}) {
76
+ const promise=new Promise((resolve, reject) => {
77
+ const id = crypto.randomUUID()
78
+ // 中文:操作按清单预算等待;文件传输与人工选择文件给予更长时限。
79
+ // English: Operations wait by their manifest budget; file transfers and user file picking get longer limits.
80
+ const timeout = kind === 'invoke' ? (Object.hasOwn(budgets, data.operation) ? budgets[data.operation] : defaultExecuteWait) : kind.startsWith('files.') ? 3600000 : ['files.export','window.open','call'].includes(kind) ? 65000 : 15000
81
+ const timer = setTimeout(() => { pending.delete(id); reject(new LiminaError('宿主响应超时,请重新打开插件', 'TIMEOUT')) }, timeout)
82
+ pending.set(id, { resolve, reject, timer })
83
+ parent.postMessage({ kind, id, ...data, ...(controlId&&controlAccepting?{control_id:controlId}:{}) }, '*')
84
+ })
85
+ if(controlId&&controlAccepting){
86
+ const effect={kind,operation:data.operation||data.service};effects.push(effect)
87
+ const tracked=promise.then(()=>{effect.status='succeeded'},error=>{effect.status='failed';effect.error=error.message}).finally(()=>controlRequests.delete(tracked))
88
+ controlRequests.add(tracked)
89
+ }
90
+ return promise
91
+ }
92
+ // 中文:宿主服务调用;界面与节点上的执行代码使用同一组服务名和参数。
93
+ // English: Host service call; views and node-side operation code share the same service names and arguments.
94
+ const call = (service, args = {}) => request('call', { service, args })
95
+ const asBytes = data => data instanceof Uint8Array ? data : data instanceof ArrayBuffer ? new Uint8Array(data) : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null
96
+ const writeOptions = options => options?.ifMatch === undefined ? {} : { if_match: options.ifMatch }
97
+ // 中文:插件空间文件接口;路径相对本插件的文件夹,任何客户端读到的都是同一份数据。
98
+ // English: Plugin-space file API; paths are relative to this plugin's folder and every client sees the same data.
99
+ const files = Object.freeze({
100
+ list: (dir = '', options = {}) => call('files.list', { path: dir, recursive: options.recursive === true }).then(value => value.entries),
101
+ stat: path => call('files.stat', { path }).then(value => value.entry),
102
+ exists: path => call('files.stat', { path }).then(value => Boolean(value.entry)),
103
+ readText: path => request('files.blob', { path }).then(blob => blob.text()),
104
+ readBytes: path => request('files.blob', { path }).then(async blob => new Uint8Array(await blob.arrayBuffer())),
105
+ async readJSON(path, fallback) {
106
+ try { return JSON.parse(await files.readText(path)) }
107
+ catch (error) { if (error.code === 'NOT_FOUND' && arguments.length > 1) return fallback; throw error }
108
+ },
109
+ read: (path, options = {}) => call('files.read', { path, encoding: options.encoding === 'base64' ? 'base64' : 'utf8' }),
110
+ writeText: (path, text, options) => request('files.put', { path, blob: new Blob([String(text)]), ...writeOptions(options) }),
111
+ writeBytes(path, data, options) {
112
+ const bytes = asBytes(data)
113
+ if (!bytes) return Promise.reject(new TypeError('writeBytes 需要 Uint8Array 或 ArrayBuffer'))
114
+ return request('files.put', { path, blob: new Blob([bytes]), ...writeOptions(options) })
115
+ },
116
+ writeJSON: (path, value, options) => files.writeText(path, JSON.stringify(value), options),
117
+ remove: (path, options = {}) => call('files.remove', { path, recursive: options.recursive === true }).then(value => value.removed),
118
+ move: (from, to, options = {}) => call('files.move', { from, to, overwrite: options.overwrite === true }).then(value => value.entry),
119
+ // 中文:人工点击后,从用户设备选择文件并保存到插件空间。 English: After a user click, pick files from the user's device and save them into the plugin space.
120
+ import: (options = {}) => request('files.import', { options: { dir: options.dir || '', accept: options.accept || '', multiple: options.multiple === true } }).then(value => value.entries),
121
+ // 中文:人工点击后,把插件空间里的文件下载到用户设备。 English: After a user click, download a plugin-space file to the user's device.
122
+ export: (path, options = {}) => request('files.export', { path, name: options.name || '' }),
123
+ })
124
+ // 中文:订阅宿主事件,返回取消订阅函数。
125
+ // English: Subscribe to a host event; returns an unsubscribe function.
126
+ function on(name, fn) {
127
+ if (typeof fn !== 'function') throw new TypeError('事件监听器必须是函数')
128
+ if (!events.has(name)) events.set(name, new Set())
129
+ events.get(name).add(fn)
130
+ parent.postMessage({ kind: 'ready' }, '*')
131
+ return () => events.get(name)?.delete(fn)
132
+ }
133
+ window.limina = Object.freeze({
134
+ sdkVersion: hostContext.sdkVersion,
135
+ // 中文:宿主固定的运行上下文,插件不能修改。 English: Host-fixed context; plugins cannot change it.
136
+ context: Object.freeze({ plugin: Object.freeze({ ...hostContext.plugin }), surface: hostContext.surface, view: hostContext.view, taskId: hostContext.taskId || '' }),
137
+ LiminaError,
138
+ ui:Object.freeze({bindFile:ui.bindFile,register:ui.register,snapshot:ui.snapshot}),
139
+ getLocale: () => localeContext || null,
140
+ onLocale,
141
+ createI18n,
142
+ // 中文:调用清单声明的操作;后端校验后调度到执行节点,返回操作结果。
143
+ // English: Invoke a manifest operation; the backend validates it, schedules it to a runtime node and returns the result.
144
+ invoke: (operation, args = {}, options = {}) => request('invoke', { operation, args, options: { ...(options.node !== undefined ? { node: options.node } : {}) } }),
145
+ files,
146
+ // 中文:可选的执行节点(target 为 device 的操作使用)。 English: Selectable runtime nodes for device-targeted operations.
147
+ nodes: Object.freeze({ list: () => call('nodes.list').then(value => value.nodes) }),
148
+ // 中文:本插件的调用记录(含 AI 调用),用于在界面回放结果。 English: This plugin's invocation records, including AI calls, for replaying results in views.
149
+ invocations: Object.freeze({
150
+ list: (options = {}) => call('invocations.list', { limit: options.limit, before: options.before, operation: options.operation }),
151
+ read: id => call('invocations.read', { id }).then(value => value.invocation),
152
+ }),
153
+ // 中文:订阅宿主事件:invocation(操作完成,含 AI 与其他客户端)、files(插件空间变更)。
154
+ // English: Subscribe to host events: invocation (an operation finished, including AI and other clients) and files (plugin space changed).
155
+ on,
156
+ openWindow: viewState => request('window.open', {viewState}),
157
+ onWindowContext(fn) { windowListeners.add(fn); if(windowContext)fn(windowContext); return ()=>windowListeners.delete(fn) },
158
+ setViewState: value => parent.postMessage({kind:'view.state',value}, '*'),
159
+ onViewState(fn) { viewListeners.add(fn); if(latestView!==undefined)fn(latestView); return ()=>viewListeners.delete(fn) },
160
+ copy: text => request('copy', { text }),
161
+ })
162
+ addEventListener('message', event => {
163
+ if (event.source !== parent || !event.data || typeof event.data !== 'object') return
164
+ const d = event.data
165
+ if(d.kind==='ui.control'){
166
+ if(controlId===d.id)return
167
+ if(controlId&&controlId!==d.id){parent.postMessage({kind:'ui.control.result',id:d.id,error:'工作台正在执行操作'},'*');return}
168
+ controlId=d.id;controlAccepting=true;effects=[];controlRequests=new Set()
169
+ ui.dispatch(d.id,d.command).then(result=>parent.postMessage({kind:'ui.control.result',id:d.id,result},'*'),error=>parent.postMessage({kind:'ui.control.result',id:d.id,error:error.message},'*')).finally(()=>{controlId=null;controlAccepting=false})
170
+ return
171
+ }
172
+ if (d.kind === 'locale' && d.value && typeof d.value.locale === 'string') {
173
+ try {
174
+ const locale = Intl.getCanonicalLocales(d.value.locale)[0]
175
+ if (!locale) return
176
+ localeContext = Object.freeze({...d.value, locale, direction:d.value.direction==='rtl'?'rtl':'ltr'})
177
+ document.documentElement.lang=locale; document.documentElement.dir=localeContext.direction
178
+ for (const fn of localeListeners) notify(fn, localeContext)
179
+ } catch { /* 中文:忽略格式有误的宿主语言消息。 English: Ignore malformed host locale messages. */ }
180
+ }
181
+ if (d.kind === 'window.context') {windowContext=d.value;for(const fn of windowListeners)fn(windowContext)}
182
+ if (d.kind === 'view.state') { latestView=d.value; for(const fn of viewListeners)fn(latestView) }
183
+ if (d.kind === 'theme') { document.documentElement.style.colorScheme = d.dark ? 'dark' : 'light'; document.documentElement.dataset.theme = d.dark ? 'dark' : 'light' }
184
+ if (d.kind === 'event' && typeof d.name === 'string') { for (const fn of events.get(d.name) || []) notify(fn, d.data) }
185
+ if (d.kind === 'result') { const p = pending.get(d.id); if (p) { clearTimeout(p.timer); pending.delete(d.id); d.error ? p.reject(new LiminaError(d.error, d.code)) : p.resolve(d.value) } }
186
+ })
187
+ addEventListener('pagehide', () => { for (const p of pending.values()) { clearTimeout(p.timer); p.reject(new LiminaError('插件界面已关闭', 'CLOSED')) }; pending.clear(); events.clear(); viewListeners.clear(); windowListeners.clear(); localeListeners.clear() })
188
+ })
package/cli.js ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // 中文:本地插件构建命令,共享宿主校验;只读取项目内文件,不执行项目代码。
3
+ // English: Build local packages using shared validation; read project files without executing project code.
4
+ import { readFile, writeFile, realpath } from 'node:fs/promises'
5
+ import { resolve, dirname, relative, isAbsolute } from 'node:path'
6
+ import { readPackage, writePackage } from './archive.js'
7
+ import { validatePackage } from './validation.js'
8
+ import { validateLocales } from './localization.js'
9
+ import { PACKAGE_FORMAT } from './contract.js'
10
+ try {
11
+ const [command = 'build', target = 'plugin.json'] = process.argv.slice(2)
12
+ if (command === 'check') {
13
+ validatePackage(await readPackage(new Uint8Array(await readFile(resolve(target)))))
14
+ console.log('PASS plugin contract')
15
+ } else if (command === 'build') {
16
+ const configPath = await realpath(resolve(target)), root = dirname(configPath)
17
+ const config = JSON.parse(await readFile(configPath, 'utf8'))
18
+ // 中文:读取项目内构建输入并限制路径范围。
19
+ // English: Read build inputs within the project path boundary.
20
+ async function read(name) {
21
+ if (typeof name !== 'string') throw new Error('Missing source path')
22
+ const path = await realpath(resolve(root, name)), rel = relative(root, path)
23
+ if (rel.startsWith('..') || isAbsolute(rel)) throw new Error('Source must be inside project')
24
+ return readFile(path, 'utf8')
25
+ }
26
+ const manifest = JSON.parse(await read(config.manifest)), views = {}
27
+ const localization = config.locales ? validateLocales(JSON.parse(await read(config.locales))) : null
28
+ // 中文:转义 '<',避免某条翻译提前闭合内联的 script 元素。
29
+ // English: Escape '<' so a translation cannot close the inline script element.
30
+ const localeScript = localization ? `<script>window.liminaLocalization=${JSON.stringify(localization).replace(/</g, '\\u003c')};</script>` : ''
31
+ for (const [name, file] of Object.entries(config.views || {})) views[name] = localeScript + await read(file)
32
+ if (Object.keys(views).length && !localization) throw new Error('UI plugins must declare locales in plugin.json and provide all supported LIMINA languages')
33
+ const pkg = validatePackage({ format: PACKAGE_FORMAT, manifest, views, code: config.code ? await read(config.code) : '', ...(config.licenses ? { licenses: await read(config.licenses) } : {}) })
34
+ const output = resolve(root, config.output || `${manifest.id}.limina-plugin.zip`)
35
+ const rel = relative(root, output)
36
+ if (rel.startsWith('..') || isAbsolute(rel)) throw new Error('Output must be inside project')
37
+ const body = JSON.stringify(pkg, null, 2) + '\n'
38
+ if (Buffer.byteLength(body) > 2 * 1024 * 1024) throw new Error('Package exceeds 2 MB')
39
+ await writeFile(output, output.endsWith('.json') ? body : await writePackage(pkg))
40
+ console.log(`Built ${output}`)
41
+ } else throw new Error('Usage: limina-plugin build [plugin.json] | check <package.zip|package.json>')
42
+ } catch (error) { console.error(error.message); process.exitCode = 1 }
package/contract.js ADDED
@@ -0,0 +1,75 @@
1
+ // 中文:插件契约 v3 的唯一常量与跨字段规则;SDK 构建、客户端与后端校验保持同一语义。
2
+ // English: Single source of contract v3 constants and cross-field rules shared by the SDK build, clients and the backend.
3
+ import { isOperationTimeout } from './execution.js'
4
+
5
+ export const PACKAGE_FORMAT = 'limina.plugin.v3'
6
+ export const ARCHIVE_FORMAT = 'limina.plugin.archive.v2'
7
+ export const MANIFEST_SCHEMA = 3
8
+ export const SDK_VERSION = '1.0.0'
9
+
10
+ export const limits = Object.freeze({
11
+ packageBytes: 2 * 1024 * 1024,
12
+ inputSchemaChars: 24000,
13
+ resultBytes: 256 * 1024,
14
+ toolNameChars: 64,
15
+ // 中文:插件空间内单个插件文件夹的限制。 English: Limits of one plugin folder inside the plugin space.
16
+ folderBytes: 1024 ** 3,
17
+ pathChars: 512,
18
+ })
19
+
20
+ export const callers = Object.freeze(['ui', 'ai'])
21
+ export const surfaces = Object.freeze(['page', 'session'])
22
+ export const targets = Object.freeze(['auto', 'session', 'device', 'platform'])
23
+ // 中文:操作名 ui 保留给界面控制工具。 English: The operation name "ui" is reserved for the UI control tool.
24
+ export const reservedOperations = Object.freeze(['ui'])
25
+
26
+ // 中文:模型看到的工具名;长度受模型接口限制。 English: Model-facing tool name, bounded by model API limits.
27
+ export const toolName = (pluginId, operation) => `plugin_${pluginId}_${operation}`
28
+
29
+ // 中文:归一化插件空间内的相对路径;拒绝绝对路径、穿越和歧义字符。
30
+ // English: Normalize a path relative to the plugin folder; reject absolute paths, traversal and ambiguous characters.
31
+ export function normalizePath(value, { allowRoot = false } = {}) {
32
+ if (typeof value !== 'string') throw new TypeError('文件路径必须是字符串')
33
+ const path = value.replace(/^\/+|\/+$/g, '')
34
+ if (!path) { if (allowRoot) return ''; throw new Error('文件路径不能为空') }
35
+ if (path.length > limits.pathChars) throw new Error('文件路径过长')
36
+ for (const part of path.split('/')) {
37
+ if (!part || part === '.' || part === '..' || part.length > 255 || /[\\\u0000-\u001f\u007f]/.test(part)) throw new Error('文件路径无效')
38
+ }
39
+ return path
40
+ }
41
+
42
+ // 中文:JSON Schema 之外的跨字段规则。 English: Cross-field rules beyond the JSON Schema.
43
+ export function checkManifestRules(manifest, pkg) {
44
+ const operations = manifest.operations || {}, views = manifest.ui?.views || {}
45
+ const permissions = manifest.permissions || []
46
+ let ai = 0, code = false
47
+ for (const [name, operation] of Object.entries(operations)) {
48
+ if (reservedOperations.includes(name)) throw new Error(`操作名 ${name} 为保留名称`)
49
+ if (JSON.stringify(operation.input_schema).length > limits.inputSchemaChars) throw new Error(`操作 ${name} 的参数声明过大`)
50
+ if (operation.timeout_ms !== undefined && !isOperationTimeout(operation.timeout_ms)) throw new Error(`操作 ${name} 的 timeout_ms 无效`)
51
+ if (operation.callers.includes('ai')) {
52
+ ai++
53
+ if (!operation.description?.trim()) throw new Error(`AI 可调用的操作 ${name} 必须提供 description`)
54
+ if (toolName(manifest.id, name).length > limits.toolNameChars) throw new Error(`操作 ${name} 的工具名超过 ${limits.toolNameChars} 个字符,请缩短插件或操作标识`)
55
+ }
56
+ if ((operation.executor || 'code') === 'hsm') {
57
+ if (!permissions.includes('hsm')) throw new Error(`操作 ${name} 使用加密机通信,必须声明 hsm 权限`)
58
+ } else code = true
59
+ }
60
+ if (permissions.includes('background')) code = true
61
+ if (!Object.keys(views).length && !ai && !permissions.includes('background')) throw new Error('插件必须提供界面、AI 可调用的操作或后台生命周期')
62
+ if (manifest.ui?.control !== undefined && !Object.values(views).some(view => view.surfaces.includes('session'))) throw new Error('ui.control 需要提供 session 界面')
63
+ if (pkg) {
64
+ for (const name of Object.keys(views)) if (typeof pkg.views?.[name] !== 'string' || !pkg.views[name]) throw new Error(`插件包缺少界面文件:${name}`)
65
+ for (const name of Object.keys(pkg.views || {})) if (!views[name]) throw new Error(`插件包包含未声明的界面:${name}`)
66
+ if (code && (Object.keys(operations).length || permissions.includes('background')) && (typeof pkg.code !== 'string' || !pkg.code.trim())) throw new Error('插件声明了代码操作,但缺少执行代码')
67
+ }
68
+ return manifest
69
+ }
70
+
71
+ // 中文:按界面位置选择视图。 English: Pick the view for a surface.
72
+ export function viewFor(manifest, surface) {
73
+ const entry = Object.entries(manifest?.ui?.views || {}).find(([, view]) => view.surfaces.includes(surface))
74
+ return entry ? { name: entry[0], ...entry[1] } : null
75
+ }
package/execution.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { OperationDefinition } from './index.js';
2
+ export const executionPolicy: Readonly<{
3
+ defaultTimeoutMs: number;
4
+ minTimeoutMs: number;
5
+ maxTimeoutMs: number;
6
+ transportGraceMs: number;
7
+ uiGraceMs: number;
8
+ }>;
9
+ export function isOperationTimeout(value: unknown): value is number;
10
+ export function operationTimeout(definition?: Pick<OperationDefinition, 'timeout_ms'>): number;
11
+ export function operationTransportTimeout(definition?: Pick<OperationDefinition, 'timeout_ms'>): number;
12
+ export function operationUITimeout(definition?: Pick<OperationDefinition, 'timeout_ms'>): number;
package/execution.js ADDED
@@ -0,0 +1,34 @@
1
+ // 中文:所有插件共用的执行预算契约;清单只能在宿主允许范围内声明时限。
2
+ // 中文:时间线:后端对一次调用的总时长上限是 timeout_ms + 15 秒(运行时限 + 宿主调用余量,见 backend runner.HOST_ALLOWANCE_SECONDS),
3
+ // 中文:另有最多 5 秒的通信余量;AI 等待 timeout_ms + 30 秒,界面等待 timeout_ms + 30 秒,都晚于后端给出结果。
4
+ // English: Shared execution budgets for every plugin; manifests can declare only host-bounded limits.
5
+ // English: Timeline: the backend caps one invocation at timeout_ms + 15 s (the time limit plus an allowance for host
6
+ // English: calls, see backend runner.HOST_ALLOWANCE_SECONDS) with up to 5 s of transport slack; AI waits timeout_ms + 30 s
7
+ // and views wait timeout_ms + 30 s, both later than the backend produces a result.
8
+ export const executionPolicy = Object.freeze({
9
+ defaultTimeoutMs: 10000,
10
+ minTimeoutMs: 1000,
11
+ maxTimeoutMs: 110000,
12
+ transportGraceMs: 10000,
13
+ uiGraceMs: 20000,
14
+ })
15
+ // 中文:清单里的 timeout_ms 是否在允许范围内(整数,1000–110000 毫秒)。
16
+ // English: Whether a manifest timeout_ms is within the allowed range (an integer of 1000–110000 ms).
17
+ export function isOperationTimeout(value) {
18
+ return Number.isInteger(value) && value >= executionPolicy.minTimeoutMs && value <= executionPolicy.maxTimeoutMs
19
+ }
20
+ // 中文:操作的运行时限,未声明或无效时取默认值。
21
+ // English: An operation time limit, defaulting when absent or invalid.
22
+ export function operationTimeout(definition) {
23
+ return isOperationTimeout(definition?.timeout_ms) ? definition.timeout_ms : executionPolicy.defaultTimeoutMs
24
+ }
25
+ // 中文:运行时限加通信余量。
26
+ // English: The time limit plus transport slack.
27
+ export function operationTransportTimeout(definition) {
28
+ return operationTimeout(definition) + executionPolicy.transportGraceMs
29
+ }
30
+ // 中文:界面等待一次操作的最长时间,晚于后端给出结果的时间。
31
+ // English: How long a view waits for one operation, later than the backend produces a result.
32
+ export function operationUITimeout(definition) {
33
+ return operationTransportTimeout(definition) + executionPolicy.uiGraceMs
34
+ }
@@ -0,0 +1,99 @@
1
+ // 中文:声明式的响应校验与注解;不含脚本、表达式或厂商设备专属假设。
2
+ // English: Declarative response checks and annotations, with no scripts, expressions, or device-specific assumptions.
3
+ const bytes = value => {
4
+ if(typeof value!=='string' || !/^(?:[\da-f]{2})*$/i.test(value) || value.length>524296)throw Error('报文必须为完整 Hex 字节')
5
+ return Uint8Array.from(value.match(/../g)||[],x=>parseInt(x,16))
6
+ }
7
+ const integer=(n,min,max,label)=>{if(!Number.isSafeInteger(n)||n<min||n>max)throw Error(label+'超出范围');return n}
8
+ const hex=b=>Array.from(b,x=>x.toString(16).padStart(2,'0')).join('').toUpperCase()
9
+ export function validateAnalysis(config={}) {
10
+ if(!config||typeof config!=='object'||Array.isArray(config))throw Error('响应规则必须为对象')
11
+ const rules=config.rules===undefined?[]:config.rules,commands=config.commands===undefined?[]:config.commands
12
+ if(!Array.isArray(rules)||!Array.isArray(commands))throw Error('规则和指令必须为数组')
13
+ for(const rule of rules){
14
+ if(!rule||!['hex_equals','hex_not_equals','length','elapsed','field_equals','field_not_equals','field_range'].includes(rule.type))throw Error('未知响应规则')
15
+ if(rule.scope!==undefined&&!['frame','payload'].includes(rule.scope))throw Error('规则范围无效')
16
+ if(rule.type.startsWith('field_')){
17
+ if(typeof rule.field!=='string'||!rule.field||rule.field.length>200)throw Error('请选择规则字段')
18
+ if(rule.command!==undefined&&(typeof rule.command!=='string'||rule.command.length>200))throw Error('规则指令无效')
19
+ if(rule.type==='field_range'){for(const value of [rule.min,rule.max])if(typeof value!=='string'||!/^\d{1,20}$/.test(value))throw Error('范围必须为非负十进制整数');if(BigInt(rule.min)>BigInt(rule.max))throw Error('范围上下界颠倒')}
20
+ else if(typeof rule.expected!=='string'||rule.expected.length>524288)throw Error('期望字段值无效')
21
+ }else if(rule.type.startsWith('hex_')){integer(rule.offset,0,262144,'偏移');if(!bytes(rule.expected).length)throw Error('预期字节不能为空')}
22
+ else {integer(rule.min??0,0,100000000,'最小值');integer(rule.max,0,100000000,'最大值');if((rule.min??0)>rule.max)throw Error('范围上下界颠倒')}
23
+ }
24
+ const commandNames=new Set()
25
+ for(const command of commands){
26
+ if(!command||typeof command.name!=='string'||!command.name.trim()||command.name.length>200||!bytes(command.request_prefix).length)throw Error('指令名称或请求前缀无效')
27
+ if(commandNames.has(command.name))throw Error('指令名称重复:'+command.name)
28
+ commandNames.add(command.name)
29
+ if(command.response_prefix!==undefined)bytes(command.response_prefix)
30
+ if(!Array.isArray(command.fields))throw Error('指令字段必须为数组')
31
+ const seen=new Map()
32
+ for(const f of command.fields){
33
+ if(!f||typeof f.name!=='string'||f.name.length>200||!['hex','uint_be','uint_le','utf8'].includes(f.type))throw Error('解析字段无效')
34
+ if(!f.name.trim()||seen.has(f.name))throw Error('字段名称不能为空或重复')
35
+ if(f.role!==undefined&&!['length','status','data'].includes(f.role))throw Error('字段用途无效')
36
+ if(f.role==='length'&&!f.type.startsWith('uint_'))throw Error('长度字段必须使用整数类型')
37
+ if(f.offset==='next'){
38
+ if(!seen.size)throw Error('首个字段需要固定偏移')
39
+ }else integer(f.offset,0,262144,'字段偏移')
40
+ if(f.length_from!==undefined){if(f.length!==undefined||!seen.get(f.length_from)?.type.startsWith('uint_')||f.type.startsWith('uint_'))throw Error('数据长度需引用前面已定义的整数长度字段')}
41
+ else if(f.length!=='rest')integer(f.length,1,262144,'字段长度')
42
+ seen.set(f.name,f)
43
+ if(f.type.startsWith('uint_')&&(f.length==='rest'||f.length>8))throw Error('整数长度必须为 1–8 字节')
44
+ if(f.note!==undefined&&(typeof f.note!=='string'||f.note.length>1000))throw Error('字段注解过长')
45
+ if(f.values!==undefined&&(!f.values||typeof f.values!=='object'||Array.isArray(f.values)||Object.entries(f.values).some(([k,v])=>k.length>100||typeof v!=='string'||v.length>1000)))throw Error('字段值注解无效')
46
+ }
47
+ }
48
+ return config
49
+ }
50
+ export function analyzeResponse({sent,received,elapsed_ms,config={}}) {
51
+ validateAnalysis(config)
52
+ const payload=bytes(received.payload_hex),frame=bytes(received.hex)
53
+ const request=(sent?.payload_hex||'').toUpperCase()
54
+ const matches=(config.commands||[]).filter(c=>request?request.startsWith(c.request_prefix.toUpperCase()):!!c.response_prefix&&received.payload_hex.toUpperCase().startsWith(c.response_prefix.toUpperCase()))
55
+ const annotations=[],warnings=[]
56
+ let command=null
57
+ if(matches.length>1)warnings.push('多条指令前缀匹配,未自动选择解析模板')
58
+ else if(matches.length===1){
59
+ const c=matches[0];command=c.name
60
+ let previousEnd
61
+ if(c.response_prefix&&!received.payload_hex.toUpperCase().startsWith(c.response_prefix.toUpperCase()))warnings.push('响应指令与模板不匹配,未解析字段')
62
+ else for(const f of c.fields){
63
+ const offset=f.offset==='next'?previousEnd:f.offset
64
+ previousEnd=undefined
65
+ if(offset===undefined){warnings.push(f.name+':上一字段未成功解析');continue}
66
+ const source=f.length_from?annotations.find(a=>a.name===f.length_from):null
67
+ const length=f.length_from?Number(source?.value):f.length==='rest'?payload.length-offset:f.length
68
+ if(!Number.isSafeInteger(length)||length<0||length>262144){warnings.push(f.name+':长度字段缺失或超限');continue}
69
+ if(offset+length>payload.length){warnings.push(f.name+':报文过短');continue}
70
+ const part=payload.slice(offset,offset+length),raw=hex(part)
71
+ let value=raw
72
+ if(f.type==='utf8')value=new TextDecoder().decode(part)
73
+ if(f.type.startsWith('uint_')){let n=0n;for(const b of f.type==='uint_le'?[...part].reverse():part)n=n*256n+BigInt(b);value=n.toString()}
74
+ previousEnd=offset+length
75
+ annotations.push({name:f.name,type:f.type,role:f.role||'data',offset,length,hex:raw,value,note:f.values?.[raw]??f.values?.[value]??f.note??''})
76
+ }
77
+ }else if(config.commands?.length)warnings.push(request?'请求未匹配到指令模板':'响应未匹配到指令模板,请检查模板的响应指令前缀')
78
+ const checks=(config.rules||[]).map((r,index)=>{
79
+ const data=r.scope==='frame'?frame:payload
80
+ let actual,passed
81
+ if(r.type.startsWith('field_')){
82
+ const field=annotations.find(a=>a.name===r.field)
83
+ actual=field?.value??null;passed=false
84
+ if(field&&(!r.command||r.command===command)){
85
+ if(r.type==='field_range')passed=field.type.startsWith('uint_')&&BigInt(field.value)>=BigInt(r.min)&&BigInt(field.value)<=BigInt(r.max)
86
+ else {let expected=r.expected;if(field.type==='hex')expected=expected.replace(/\s/g,'').toUpperCase();if(field.type.startsWith('uint_')&&/^\d+$/.test(expected))expected=BigInt(expected).toString();passed=r.type==='field_equals'?field.value===expected:field.value!==expected}
87
+ }
88
+ }else if(r.type.startsWith('hex_')){
89
+ const expected=bytes(r.expected),part=data.slice(r.offset,r.offset+expected.length);actual=hex(part)
90
+ passed=part.length===expected.length&&(r.type==='hex_equals'?actual===hex(expected):actual!==hex(expected))
91
+ }else{actual=r.type==='length'?data.length:elapsed_ms;passed=Number.isFinite(actual)&&actual>=(r.min??0)&&actual<=r.max}
92
+ return {rule:index+1,name:r.name||r.type,passed,actual,expected:r.expected??{min:r.min??0,max:r.max}}
93
+ })
94
+ return {passed:checks.length?checks.every(r=>r.passed):null,checks,command,annotations,warnings}
95
+ }
96
+ export const randomResponseExample={
97
+ rules:[{name:'随机数响应码及成功状态',type:'hex_equals',scope:'payload',offset:0,expected:'01030000'}],
98
+ commands:[{name:'0x0102 获取随机数',request_prefix:'0102',response_prefix:'0103',source:'服务器密码机内部指令文档 V5.12,随机数指令;请核对设备版本',fields:[{name:'响应指令',offset:0,length:2,type:'hex',values:{'0103':'获取随机数响应'}},{name:'状态码',offset:2,length:2,type:'hex',values:{'0000':'执行成功'}},{name:'随机数',offset:4,length:'rest',type:'hex',note:'这里只验证格式和长度,不证明随机性质量'}]}]
99
+ }
package/hsm-codec.mjs ADDED
@@ -0,0 +1,39 @@
1
+ // 中文:字节预览与节点传输共用同一套线格式;不隐式添加换行或 BOM。
2
+ // English: Shared by the byte preview and node transport: one wire format, with no implicit newline or BOM.
3
+ export const MAX_FRAME = 256 * 1024
4
+ export function integer(value, fallback, min, max, name) {
5
+ const n=value===undefined?fallback:value
6
+ if(!Number.isInteger(n)||n<min||n>max)throw Error(name+' 必须为 '+min+'–'+max+' 的整数')
7
+ return n
8
+ }
9
+ export const hex=bytes=>Array.from(bytes,x=>x.toString(16).padStart(2,'0')).join('').toUpperCase()
10
+ export const concat=chunks=>{const bytes=new Uint8Array(chunks.reduce((n,b)=>n+b.length,0));let offset=0;for(const b of chunks){bytes.set(b,offset);offset+=b.length}return bytes}
11
+ export function decodeInput(input='',encoding='hex',encodeText) {
12
+ if(typeof input!=='string'||input.length>MAX_FRAME*2)throw Error('输入过长或格式错误')
13
+ if(encoding==='hex'){
14
+ const text=input.split(/\r?\n/).map(line=>{
15
+ if(line.startsWith('#'))return ''
16
+ const format={'@':'utf8','$':'gb18030','*':'utf16be'}[line[0]]
17
+ return format?hex(encodeText(line.slice(1),format)):line
18
+ }).join('').replace(/\s/g,'')
19
+ if(!/^(?:[a-f\d]{2})*$/i.test(text))throw Error('Hex 必须为完整字节;支持 # 注释、@ UTF-8、$ GB18030、* UTF-16BE 行')
20
+ return Uint8Array.from(text.match(/../g)||[],b=>parseInt(b,16))
21
+ }
22
+ if(!['base64','utf8','gb18030','utf16be'].includes(encoding))throw Error('不支持的编码')
23
+ if(encoding==='base64'&&!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.replace(/\s/g,'')))throw Error('Base64 格式无效')
24
+ return new Uint8Array(encodeText(input,encoding))
25
+ }
26
+ export function framing(args) {
27
+ return {lengthBytes:integer(args.length_bytes,2,0,4,'报文长度头'),messageBytes:integer(args.message_header_length,0,0,127,'消息头长度')}
28
+ }
29
+ export function encodeFrame(args,config,encodeText) {
30
+ const data=decodeInput(args.input,args.encoding,encodeText)
31
+ const header=args.message_header?decodeInput(args.message_header,'hex',encodeText):new Uint8Array(config.messageBytes)
32
+ if(header.length!==config.messageBytes)throw Error('消息头字节数与配置不一致')
33
+ const body=concat([header,data])
34
+ if(!body.length||body.length>MAX_FRAME||config.lengthBytes&&body.length>=2**(8*config.lengthBytes))throw Error('报文为空或超出长度头可表示范围')
35
+ const prefix=new Uint8Array(config.lengthBytes)
36
+ let length=body.length
37
+ for(let i=prefix.length-1;i>=0;i--){prefix[i]=length%256;length=Math.floor(length/256)}
38
+ return concat([prefix,body])
39
+ }