@limina_ai/plugin-sdk 0.0.0-stage → 1.0.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/README.md +21 -2
- package/THIRD_PARTY_LICENSES.txt +29 -0
- package/archive.js +58 -0
- package/bridge.js +188 -0
- package/cli.js +42 -0
- package/contract.js +75 -0
- package/execution.d.ts +12 -0
- package/execution.js +34 -0
- package/hsm-analysis.mjs +99 -0
- package/hsm-codec.mjs +39 -0
- package/index.d.ts +168 -0
- package/index.js +17 -0
- package/localization.js +31 -0
- package/package.json +49 -4
- package/schema/manifest.schema.json +207 -0
- package/supported-locales.json +32 -0
- package/ui-control-contract.mjs +21 -0
- package/ui-controller.js +146 -0
- package/validate.js +24 -0
- package/validation.js +5 -0
package/ui-controller.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// 中文:宿主注入的标准 DOM 控件适配器;不执行模型提供的脚本、选择器或 URL。
|
|
2
|
+
// English: The standard DOM control adapter injected by the host; it never executes scripts, selectors, or URLs supplied by the model.
|
|
3
|
+
(function createUIController({settle}) {
|
|
4
|
+
const view=crypto.randomUUID(),ids=new WeakMap(),nodes=new Map(),fileButtons=new Map(),adapters=new Map(),calls=new Map()
|
|
5
|
+
let next=0,revision=0,fingerprint='',running=false,humanRevision=0,dispatching=0
|
|
6
|
+
for(const type of ['click','input','change','keydown'])document.addEventListener(type,event=>{if(event.isTrusted&&!dispatching)humanRevision++},true)
|
|
7
|
+
const selector='input,textarea,select,button,summary,a[href],[role="button"],[role="tab"],[contenteditable="true"],[tabindex],canvas,[role="slider"],[role="checkbox"],[role="switch"],[role="treeitem"],[role="menuitem"],[draggable="true"]'
|
|
8
|
+
const elements=()=>[...new Set([...document.querySelectorAll(selector),...[...document.querySelectorAll('*')].filter(node=>['onclick','oninput','onchange','onkeydown'].some(key=>typeof node[key]==='function')),...[...adapters.keys()].filter(node=>node.isConnected)])]
|
|
9
|
+
const supported=node=>adapters.has(node)||node.matches('input,textarea,select,button,summary,[role="button"],[role="tab"],[contenteditable="true"]')&&!node.matches('input[type=hidden],input[type=image],input[type=submit],input[type=reset]')
|
|
10
|
+
const clean=text=>String(text||'').replace(/\s+/g,' ').trim().slice(0,240)
|
|
11
|
+
function id(node){if(!ids.has(node)){const key='c'+(++next);ids.set(node,key);nodes.set(key,node)}return ids.get(node)}
|
|
12
|
+
function visible(node){
|
|
13
|
+
if(!node.isConnected||node.closest('[hidden],[inert]')||!node.getClientRects().length||getComputedStyle(node).visibility==='hidden')return false
|
|
14
|
+
for(let parent=node.parentElement;parent;parent=parent.parentElement)if(parent.tagName==='DETAILS'&&!parent.open&&!parent.querySelector(':scope > summary')?.contains(node))return false
|
|
15
|
+
const modal=document.querySelector('dialog:modal');return !modal||modal.contains(node)
|
|
16
|
+
}
|
|
17
|
+
function label(node){
|
|
18
|
+
const wrapper=node.labels?.[0]?.cloneNode(true)
|
|
19
|
+
if(wrapper)for(const child of wrapper.querySelectorAll('input,textarea,select,button,small'))child.remove()
|
|
20
|
+
return clean(node.getAttribute('aria-label')||wrapper?.textContent||(/^(BUTTON|SUMMARY|A)$/.test(node.tagName)?node.textContent:'')||(node.type==='button'?node.value:'')||node.getAttribute('title')||node.getAttribute('placeholder')||node.id||node.name||node.getAttribute('data-check')||node.getAttribute('data-hsm')||node.type)
|
|
21
|
+
}
|
|
22
|
+
function secret(node){return node.type==='password'||node.hasAttribute('data-ui-sensitive')||/(?:^|[-_\s])(key|password|secret|seed|pin|pan)(?:$|[-_\s])|密钥|密码|私钥|秘密|口令/i.test([node.id,node.name,node.getAttribute('aria-label'),node.getAttribute('data-hsm')].join(' '))}
|
|
23
|
+
function kind(node){if(node.tagName==='INPUT'&&['button','submit','reset','image'].includes(node.type))return 'action';if(adapters.has(node))return adapters.get(node).kind;if(fileButtons.has(node)||node.type==='file')return 'file';if(node.tagName==='SELECT')return 'select';if(['checkbox','radio'].includes(node.type))return 'toggle';if(node.matches('input,textarea,[contenteditable="true"]'))return 'field';if(node.tagName==='SUMMARY')return 'disclosure';return 'action'}
|
|
24
|
+
function pageText(){const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),parts=[];while(walker.nextNode()){const node=walker.currentNode,parent=node.parentElement;if(parent&&!parent.closest('script,style,input,textarea,select,[data-ui-sensitive]')&&visible(parent)&&node.textContent.trim())parts.push(node.textContent.trim())}return parts.join('\n')}
|
|
25
|
+
function snapshot({offset=0,limit=20,include_hidden=false}={}){
|
|
26
|
+
const controls=elements().map(node=>{
|
|
27
|
+
const type=kind(node),shown=visible(node),disabled=node.matches(':disabled')||node.getAttribute('aria-disabled')==='true',sensitive=['field','select','file'].includes(type)&&secret(node)
|
|
28
|
+
const row={id:id(node),kind:type,label:label(node),visible:shown,disabled,readonly:!!node.readOnly,sensitive,supported:supported(node)}
|
|
29
|
+
if(type==='file'){row.accept=fileButtons.get(node)?.input.accept||node.accept||'';row.multiple=!!(fileButtons.get(node)?.input.multiple||node.multiple)}
|
|
30
|
+
else if(type==='toggle')row.checked=!!node.checked
|
|
31
|
+
else if(type==='disclosure')row.expanded=!!node.parentElement?.open
|
|
32
|
+
else if(type==='field'||type==='select'){
|
|
33
|
+
const value=node.isContentEditable?node.textContent:node.value
|
|
34
|
+
if(sensitive)row.filled=!!value;else if(shown){row.value=String(value??'').slice(0,256);row.length=String(value??'').length;row.truncated=row.length>256}
|
|
35
|
+
if(type==='select'){row.option_count=node.options.length;row.options=[...node.options].slice(0,20).map(option=>({value:option.value,label:clean(option.textContent),disabled:option.disabled||!!option.closest('optgroup:disabled')}))}
|
|
36
|
+
}
|
|
37
|
+
row.actions=type==='file'?['upload']:type==='field'||type==='select'?['set','read']:type==='toggle'?['set','activate']:['activate']
|
|
38
|
+
if(row.readonly)row.actions=row.actions.filter(action=>action!=='set')
|
|
39
|
+
if(!row.supported)row.actions=[]
|
|
40
|
+
if(typeof node.onkeydown==='function')row.actions.push('key')
|
|
41
|
+
const adapter=adapters.get(node)
|
|
42
|
+
if(adapter){const state=adapter.read?.()||{};if(state?.then)throw Error('UI adapter read must be synchronous');row.label=adapter.label;row.sensitive=!!adapter.sensitive;row.disabled=disabled||!!state.disabled;row.readonly=!!state.readonly;row.actions=['set','activate','upload','key'].filter(action=>typeof adapter[action]==='function');if(adapter.read)row.actions.push('read');if(row.sensitive){delete row.value;row.filled=!!state.value}else if(shown){row.value=String(state.value??'').slice(0,256);row.length=String(state.value??'').length;row.truncated=row.length>256}if(row.readonly)row.actions=row.actions.filter(action=>action!=='set')}
|
|
43
|
+
if(row.sensitive)row.actions=row.actions.filter(action=>action!=='read')
|
|
44
|
+
if(node.getAttribute('role')==='tab')row.selected=node.getAttribute('aria-selected')==='true'
|
|
45
|
+
return row
|
|
46
|
+
})
|
|
47
|
+
const feedback=[...document.querySelectorAll('[role="alert"],[role="status"],[data-ui-feedback],.feedback')].filter(visible).map(node=>clean(node.textContent)).filter(Boolean)
|
|
48
|
+
const errors=[...document.querySelectorAll('[role=alert],[data-tone=error],[data-error=true]')].filter(visible).map(node=>clean(node.textContent)).filter(Boolean)
|
|
49
|
+
const text=pageText(),body={controls,feedback,errors,text},encoded=JSON.stringify([body,[...adapters].map(([node,adapter])=>[id(node),adapter.read?.()]),[...document.querySelectorAll('input,textarea,select,[contenteditable="true"]')].map(node=>node.isContentEditable?node.textContent:node.value)])
|
|
50
|
+
if(encoded!==fingerprint){fingerprint=encoded;revision++}
|
|
51
|
+
const filtered=controls.filter(row=>include_hidden||row.visible),page=filtered.slice(offset,offset+limit)
|
|
52
|
+
return {view,revision,controls:page,feedback,errors,text:text.slice(0,1024),text_length:text.length,offset,next:offset+limit<filtered.length?offset+limit:null,matched:filtered.length,coverage:{total:controls.length,supported:controls.filter(row=>row.supported).length,unsupported:controls.filter(row=>!row.supported).map(row=>({id:row.id,label:row.label})),visible:controls.filter(row=>row.visible).length}}
|
|
53
|
+
}
|
|
54
|
+
// 中文:同一处理器同时用于人工事件和 AI 操作;返回 Promise 的业务处理器必须等待其完成。
|
|
55
|
+
// English: One handler serves both human events and AI actions, and a business handler returning a Promise must be awaited.
|
|
56
|
+
async function fire(node,type,options={}){
|
|
57
|
+
const handler=node['on'+type],waiting=[]
|
|
58
|
+
if(typeof handler==='function')node['on'+type]=function(event){try{const result=handler.call(this,event);if(result?.then)waiting.push(result);return result?.then?undefined:result}catch(error){waiting.push(Promise.reject(error));event.preventDefault();return false}}
|
|
59
|
+
try{
|
|
60
|
+
dispatching++
|
|
61
|
+
try{if(type==='click')node.click();else node.dispatchEvent(type==='keydown'?new KeyboardEvent(type,{...options,bubbles:true,cancelable:true}):new Event(type,{bubbles:true,cancelable:true}))}finally{dispatching--}
|
|
62
|
+
await Promise.all(waiting)
|
|
63
|
+
}finally{if(typeof handler==='function')node['on'+type]=handler}
|
|
64
|
+
}
|
|
65
|
+
async function run(command){
|
|
66
|
+
const humanBefore=humanRevision,before=snapshot(command)
|
|
67
|
+
if(command.action==='inspect')return {status:'inspected',snapshot:before}
|
|
68
|
+
if(command.view!==view||command.revision!==revision)return {status:'conflict',code:'STALE_VIEW',snapshot:before}
|
|
69
|
+
if(command.action==='read'&&command.target==='page'){const value=pageText(),start=command.start||0,end=Math.min(value.length,start+(command.length||4096));return {status:'read',view,revision,target:'page',value:value.slice(start,end),length:value.length,next:end<value.length?end:null}}
|
|
70
|
+
const node=nodes.get(command.target)
|
|
71
|
+
if(!node||!visible(node))throw Error('控件不在当前可见界面,请重新 inspect')
|
|
72
|
+
if(node.matches(':disabled')||node.getAttribute('aria-disabled')==='true')throw Error('控件当前不可用')
|
|
73
|
+
if(!supported(node))throw Error('该控件未提供可执行适配器')
|
|
74
|
+
if(command.action!=='read'){node.scrollIntoView({block:'nearest',inline:'nearest'});node.focus?.({preventScroll:true})}
|
|
75
|
+
const type=kind(node),adapter=adapters.get(node)
|
|
76
|
+
if(adapter){
|
|
77
|
+
const state=adapter.read?.()||{}
|
|
78
|
+
if(state.disabled)throw Error('控件当前不可用')
|
|
79
|
+
if(command.action==='read'){if(adapter.sensitive)throw Error('敏感控件不提供明文读取');const value=String(state.value??''),start=command.start||0,end=Math.min(value.length,start+(command.length||4096));return {status:'read',view,revision,target:command.target,value:value.slice(start,end),length:value.length,next:end<value.length?end:null}}
|
|
80
|
+
if(typeof adapter[command.action]!=='function'||command.action==='set'&&state.readonly)throw Error('控件不支持该操作')
|
|
81
|
+
await adapter[command.action](command.action==='set'?command.value:command.action==='upload'?command.files:command.action==='key'?{key:command.key,alt:!!command.alt}:undefined)
|
|
82
|
+
const effects=await settle();return {status:effects.some(effect=>effect.error)?'failed':'applied',effects,snapshot:snapshot()}
|
|
83
|
+
}
|
|
84
|
+
if(command.action==='read'){
|
|
85
|
+
if(secret(node))throw Error('敏感控件不提供明文读取')
|
|
86
|
+
if(!['field','select'].includes(type))throw Error('该控件不是文本字段')
|
|
87
|
+
if(type==='select'){const start=command.start||0;return {status:'read',view,revision,target:command.target,options:[...node.options].slice(start,start+20).map(option=>({value:option.value,label:clean(option.textContent),disabled:option.disabled||!!option.closest('optgroup:disabled')})),length:node.options.length,next:start+20<node.options.length?start+20:null}}
|
|
88
|
+
const value=String(node.isContentEditable?node.textContent:node.value)
|
|
89
|
+
const start=command.start||0,end=Math.min(value.length,start+(command.length||4096))
|
|
90
|
+
return {status:'read',view,revision,target:command.target,value:value.slice(start,end),length:value.length,next:end<value.length?end:null}
|
|
91
|
+
}
|
|
92
|
+
if(command.action==='set'){
|
|
93
|
+
if(!['field','select','toggle'].includes(type)||node.readOnly)throw Error('该控件不可修改')
|
|
94
|
+
if(type==='toggle'){if(typeof command.value!=='boolean')throw Error('开关值必须为布尔值');node.checked=command.value}
|
|
95
|
+
else if(type==='select'){
|
|
96
|
+
const option=[...node.options].find(option=>option.value===String(command.value)&&!option.disabled&&!option.closest('optgroup:disabled'))
|
|
97
|
+
if(!option)throw Error('选项不存在或已禁用');node.value=option.value
|
|
98
|
+
}else if(node.isContentEditable)node.textContent=String(command.value)
|
|
99
|
+
else node.value=String(command.value)
|
|
100
|
+
await fire(node,'input');await fire(node,'change')
|
|
101
|
+
}else if(command.action==='upload'){
|
|
102
|
+
const input=fileButtons.get(node)?.input||node
|
|
103
|
+
if(input.type!=='file')throw Error('目标不是文件导入控件')
|
|
104
|
+
if(!input.multiple&&command.files.length!==1)throw Error('该控件只接收一个文件')
|
|
105
|
+
const transfer=new DataTransfer()
|
|
106
|
+
for(const file of command.files){
|
|
107
|
+
if(!file.name||/[\/\\\x00]/.test(file.name))throw Error('文件名不能含路径')
|
|
108
|
+
const bytes=file.encoding==='base64'?Uint8Array.from(atob(file.content),c=>c.charCodeAt(0)):new TextEncoder().encode(file.content)
|
|
109
|
+
transfer.items.add(new File([bytes],file.name,{type:file.type||'application/octet-stream'}))
|
|
110
|
+
}
|
|
111
|
+
input.files=transfer.files;await fire(input,'change')
|
|
112
|
+
}else if(command.action==='key'){
|
|
113
|
+
if(typeof node.onkeydown!=='function')throw Error('该控件未声明键盘处理器')
|
|
114
|
+
await fire(node,'keydown',{key:command.key,altKey:!!command.alt})
|
|
115
|
+
}else if(command.action==='activate'){
|
|
116
|
+
if(type==='file')return {status:'needs_file',snapshot:before,target:command.target}
|
|
117
|
+
if(['disclosure','toggle','action'].includes(type)){
|
|
118
|
+
await fire(node,'click')
|
|
119
|
+
}else throw Error('该控件需要 set 操作')
|
|
120
|
+
}else throw Error('未知界面操作')
|
|
121
|
+
const effects=await settle(),after=snapshot()
|
|
122
|
+
return {status:effects.some(effect=>effect.error)?'failed':after.errors.length?'needs_attention':'applied',interleaved:humanBefore!==humanRevision,effects,snapshot:after}
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
snapshot,
|
|
126
|
+
register(node,adapter){
|
|
127
|
+
if(!(node instanceof Element)||!adapter||typeof adapter.label!=='string'||!['field','action','select','toggle','file'].includes(adapter.kind))throw Error('Invalid UI adapter')
|
|
128
|
+
const marked=node.hasAttribute('data-ui-sensitive');if(adapter.sensitive)node.setAttribute('data-ui-sensitive','');adapters.set(node,Object.freeze({...adapter}));return ()=>{adapters.delete(node);if(adapter.sensitive&&!marked)node.removeAttribute('data-ui-sensitive')}
|
|
129
|
+
},
|
|
130
|
+
bindFile(button,{accept='',multiple=false}={},handler){
|
|
131
|
+
const input=document.createElement('input');input.type='file';input.accept=accept;input.multiple=multiple
|
|
132
|
+
input.onchange=async event=>{try{await handler([...event.target.files])}finally{input.value=''}}
|
|
133
|
+
fileButtons.set(button,{input});button.onclick=()=>input.click()
|
|
134
|
+
},
|
|
135
|
+
async dispatch(requestId,command){
|
|
136
|
+
if(calls.has(requestId))return calls.get(requestId)
|
|
137
|
+
if(running)throw Error('工作台正在执行操作,请等待完成后重新检查')
|
|
138
|
+
running=true
|
|
139
|
+
const pending=run(command).finally(()=>{running=false})
|
|
140
|
+
calls.set(requestId,pending)
|
|
141
|
+
// 中文:不淘汰已执行的请求,防止重连后把同一个按钮再执行一次;随页面销毁时释放。
|
|
142
|
+
// English: Executed requests are never evicted so a reconnect cannot press the same button again; everything is released when the page is destroyed.
|
|
143
|
+
return pending
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
})
|
package/validate.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// 中文:SDK 构建与客户端预检共用的包契约校验器;后端安装时以同一份 JSON Schema 再次校验,后端是最终边界。
|
|
2
|
+
// English: Package validator shared by the SDK build and client pre-check. The backend re-validates with the same JSON Schema and is the final boundary.
|
|
3
|
+
import manifestSchema from './schema/manifest.schema.json' with { type: 'json' }
|
|
4
|
+
import { PACKAGE_FORMAT, limits, checkManifestRules } from './contract.js'
|
|
5
|
+
|
|
6
|
+
// 中文:用宿主提供的 Ajv 创建包校验器:格式、大小、清单 Schema 与跨字段规则。
|
|
7
|
+
// English: Build the package validator from the host Ajv: format, size, manifest schema and cross-field rules.
|
|
8
|
+
export function createPackageValidator(ajv) {
|
|
9
|
+
// 中文:宿主的 Ajv 可能是 draft-07 实例;清单 Schema 只使用两代通用的关键字,去掉 $schema 声明即可编译。
|
|
10
|
+
// English: Host Ajv instances may be draft-07; the manifest schema only uses keywords common to both drafts, so drop the $schema declaration.
|
|
11
|
+
const { $schema: _draft, $id: _id, ...schema } = manifestSchema
|
|
12
|
+
const validateManifest = ajv.compile(schema)
|
|
13
|
+
return function validatePackage(value) {
|
|
14
|
+
if (!value || value.format !== PACKAGE_FORMAT) throw new Error('请选择 LIMINA 插件安装包(契约 v3)')
|
|
15
|
+
if (JSON.stringify(value).length > limits.packageBytes) throw new Error('插件包不能超过 2 MB')
|
|
16
|
+
if (!validateManifest(value.manifest)) {
|
|
17
|
+
const issue = validateManifest.errors?.[0]
|
|
18
|
+
throw new Error(`插件清单无效:${issue?.instancePath || '/'} ${issue?.message || ''}`.trim())
|
|
19
|
+
}
|
|
20
|
+
for (const operation of Object.values(value.manifest.operations || {})) ajv.compile(operation.input_schema)
|
|
21
|
+
checkManifestRules(value.manifest, value)
|
|
22
|
+
return structuredClone(value)
|
|
23
|
+
}
|
|
24
|
+
}
|
package/validation.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// 中文:使用 SDK 的 AJV 依赖加载共用契约规则。
|
|
2
|
+
// English: Shared contract rules with the SDK AJV dependency.
|
|
3
|
+
import Ajv from "ajv"
|
|
4
|
+
import { createPackageValidator } from "./validate.js"
|
|
5
|
+
export const validatePackage = createPackageValidator(new Ajv({ allErrors: false, strict: false }))
|