@ai-workbench/connect 0.7.27 → 0.7.29
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/client/index.cjs +5 -5
- package/helper/host-directories.cjs +7 -12
- package/lib/api.d.ts +2 -7
- package/lib/auth-diagnostics.js +1 -1
- package/lib/host-directories.d.ts +2 -3
- package/lib/host-directories.js +10 -8
- package/lib/host-session-projects.d.ts +2 -13
- package/lib/host-session-projects.js +65 -50
- package/lib/index.d.ts +1 -1
- package/lib/index.js +5 -4
- package/lib/native-workspace.d.ts +1 -0
- package/lib/needs.js +2 -2
- package/lib/profile-runtime.d.ts +1 -1
- package/lib/profile-runtime.js +11 -8
- package/lib/startup.js +2 -2
- package/lib/workspace-directory-picker.js +51 -95
- package/lib/workspace-location-types.d.ts +18 -11
- package/lib/workspace-locations.d.ts +2 -12
- package/lib/workspace-locations.js +81 -208
- package/package.json +1 -1
- package/node_modules/argparse/CHANGELOG.md +0 -216
package/client/index.cjs
CHANGED
|
@@ -85,7 +85,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
85
85
|
const record=value=>!!value&&typeof value==='object'&&!Array.isArray(value);
|
|
86
86
|
const safeText=value=>typeof value==='string'&&value.length>0&&!/[\x00-\x1f\x7f]/.test(value);
|
|
87
87
|
const validHost=value=>record(value)&&safeText(value.host)&&safeText(value.username)&&Number.isInteger(value.port)&&value.port>=1&&value.port<=65535&&Object.keys(value).every(key=>['host','username','port'].includes(key));
|
|
88
|
-
const validLocationItem=item=>record(item)&&safeText(item.workspaceId)&&safeText(item.workspaceName)&&safeText(item.localPath)&&(item.bindingId===null||safeText(item.bindingId))&&[null,'local','host'].includes(item.source)&&['unselected','selected','invalid'].includes(item.status)&&['not-selected','local-pending'
|
|
88
|
+
const validLocationItem=item=>record(item)&&safeText(item.workspaceId)&&safeText(item.workspaceName)&&safeText(item.localPath)&&(item.bindingId===null||safeText(item.bindingId))&&[null,'local','host'].includes(item.source)&&(item.source==='host'?safeText(item.host?.host)&&safeText(item.remote?.path)&&item.remote.path.startsWith('/'):['unselected','selected','invalid'].includes(item.status)&&['not-selected','local-pending'].includes(item.execution));
|
|
89
89
|
const validLocations=value=>record(value)&&safeText(value.instanceId)&&Number.isSafeInteger(value.epoch)&&value.epoch>=0&&Number.isSafeInteger(value.revision)&&value.revision>=0&&['loading','ready','failed','disposed'].includes(value.phase)&&Number.isSafeInteger(value.pageSize)&&value.pageSize>=1&&(value.host===undefined||value.host===null||validHost(value.host))&&Array.isArray(value.items)&&value.items.every(validLocationItem);
|
|
90
90
|
const validSnapshot=value=>{const s=value?.startup,l=value?.workspaceLocations;return record(s)&&['checking','blocked','login-required','authorizing','idle','disposed'].includes(s.phase)&&record(s.logins)&&Object.values(s.logins).every(v=>typeof v==='boolean')&&(s.checkingProviders===undefined||Array.isArray(s.checkingProviders))&&(s.providerNeeds===undefined||record(s.providerNeeds))&&(l===undefined||l===null||validLocations(l));};
|
|
91
91
|
const acceptLocations=(incoming,source)=>{if(!incoming)return incoming;const valid=typeof incoming.instanceId==='string'&&Number.isSafeInteger(incoming.epoch)&&incoming.epoch>=0&&Number.isSafeInteger(incoming.revision)&&incoming.revision>=0;if(!valid||retiredLocations.has(incoming.instanceId)||(workspaceLocations&&incoming.instanceId===workspaceLocations.instanceId&&(incoming.epoch<workspaceLocations.epoch||incoming.revision<workspaceLocations.revision))||(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId&&source==='http'))return workspaceLocations;if(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId)retiredLocations.add(workspaceLocations.instanceId);workspaceLocations=incoming;return incoming;};
|
|
@@ -108,7 +108,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
108
108
|
const current=()=>live.current&&sameLocationContext(workbench.getSnapshot().value?.workspaceLocations,context);
|
|
109
109
|
const browse=async(query={})=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const size=Number(pageSize);if(!/^\d+$/.test(pageSize)||!Number.isSafeInteger(size)||size<1){setError('每页条数需要正安全整数。');return;}const result=await workbench.browseWorkspaceHostDirectories({...context,pageSize:size,...query});if(at!==sequence.current||!current())return;if(!result?.ok){setError(result?.error?.message||'主机目录读取失败,未自动重试。');return;}const value=result.value;if(value.instanceId!==context.instanceId||value.epoch!==context.epoch||value.workspaceId!==context.workspaceId||value.bindingId!==context.expectedBindingId){setError('工作区或连接已变化,请刷新位置。');return;}setPage(value);}catch{if(at===sequence.current&¤t())setError('主机目录读取失败,未自动重试。');}finally{if(at===sequence.current&¤t())setLoading(false);}};
|
|
110
110
|
const select=async(choice)=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const result=await workbench.selectWorkspaceLocation({...context,...choice});if(at!==sequence.current||!current())return;if(!result?.ok)setError(result?.error?.message||'位置未保存,请刷新位置。');}catch{if(at===sequence.current&¤t())setError('位置保存结果无法确认,请刷新后核实;未自动重试。');}finally{if(at===sequence.current&¤t())setLoading(false);}};
|
|
111
|
-
const execution=item.
|
|
111
|
+
const execution=item.source==='host'?'已选择主机文件夹;每轮开始只确认该路径在主机上存在且为文件夹。':item.status==='invalid'?'工作区位置当前不可用,请查看具体原因。':item.execution==='local-pending'?'已选择本机文件夹;运行前会核验本机执行条件。':'尚未选择文件来源。';
|
|
112
112
|
const identity=locations.host,host=identity?identity.username+'@'+identity.host+':'+identity.port:'主机标识尚未核实';
|
|
113
113
|
return h('fieldset',null,h('legend',null,item.workspaceName),h('p',null,'原生本地工作区:'+item.localPath),h('p',null,'远程主机:'+host),h('p',{role:'status'},execution),item.need?h('p',{role:'alert'},item.need.message):null,h('button',{type:'button',disabled:loading,onClick:()=>select({source:'local'})},'使用本地文件夹'),h('button',{type:'button',disabled:loading,onClick:()=>browse()},'浏览主机文件夹'),h('label',null,'主机绝对目录',h('input',{type:'text',value:path,disabled:loading,onChange:event=>setPath(event.target.value)})),h('button',{type:'button',disabled:loading||!path.startsWith('/'),onClick:()=>browse({path})},'打开主机目录'),h('label',null,'主机目录每页条数',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:pageSize,disabled:loading,onChange:event=>setPageSize(event.target.value)})),h('p',null,'默认每页 '+locations.pageSize+' 条;可填写1至9007199254740991整数。只浏览和选择已有目录,不创建目录;本地文件不会自动上传。'),loading?h('p',{role:'status'},'正在核实工作区位置…'):null,error?h('p',{role:'alert'},error):null,page?h(React.Fragment,null,h('p',null,'请求目录:'+page.requestedPath),h('p',null,'规范路径:'+page.path),h('p',null,'父级:'+(page.parentPath??'无')),h('p',null,'符号链接:'+(page.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:page.permissions}),page.parentPath?h('button',{type:'button',disabled:loading,onClick:()=>browse({path:page.parentPath})},'打开父级目录'):null,h('button',{type:'button',disabled:loading||!page.selectionToken,onClick:()=>select({source:'host',selectionToken:page.selectionToken})},'选择当前主机文件夹'),...page.entries.map(entry=>h('div',{key:entry.requestedPath},h('p',null,entry.name+' · '+(entry.path??entry.requestedPath)+';符号链接:'+(entry.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:entry.permissions}),entry.errorCode?h('p',{role:'alert'},'目录无法使用:'+entry.errorCode):null,h('button',{type:'button',disabled:loading||!!entry.errorCode,onClick:()=>browse({path:entry.requestedPath})},'打开 '+entry.name),h('button',{type:'button',disabled:loading||!entry.selectionToken,onClick:()=>select({source:'host',selectionToken:entry.selectionToken})},'选择 '+entry.name))),page.nextCursor?h('button',{type:'button',disabled:loading,onClick:()=>browse({cursor:page.nextCursor})},'继续加载目录'):null):null);
|
|
114
114
|
}
|
|
@@ -152,13 +152,13 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
152
152
|
if(value.target==='local'){setPage(null);await pickLocal(at);}else setPage(append&&previous?.target==='host'&&previous.path===value.path?{...value,entries:[...previous.entries,...value.entries.filter(entry=>!previous.entries.some(old=>old.path===entry.path))]}:value);
|
|
153
153
|
}catch{if(current(at))setError(savingRef.current?'工作区添加结果无法确认,请查看工作区列表。':'目录无法读取,请检查连接。');}finally{if(current(at)){locked.current=false;savingRef.current=false;setSaving(false);setBusy(false);}}
|
|
154
154
|
};
|
|
155
|
-
React.useEffect(()=>{savingRef.current=false;setSaving(false);if(open){active.current=true;generation.current++;locked.current=false;setTarget(null);setPage(null);setError('');
|
|
155
|
+
React.useEffect(()=>{savingRef.current=false;setSaving(false);if(open){active.current=true;generation.current++;locked.current=false;setTarget(null);setPage(null);setError('');setBusy(false);}else{setPage(null);setError('');setBusy(false);}},[open]);
|
|
156
156
|
const cancel=()=>{if(!active.current||savingRef.current)return;active.current=false;generation.current++;locked.current=false;setPage(null);setBusy(false);outcome.current.onCancel();};
|
|
157
157
|
const select=async()=>{if(!active.current||locked.current||!page)return;locked.current=true;setBusy(true);setError('');const at=generation.current;try{await commit(page,at);}catch{if(current(at))setError('工作区添加结果无法确认,请查看工作区列表。');}finally{if(current(at)){locked.current=false;savingRef.current=false;setSaving(false);setBusy(false);}}};
|
|
158
158
|
const createFolder=async(name)=>{if(!active.current||locked.current||!page)return false;locked.current=true;savingRef.current=true;setBusy(true);setError('');const at=generation.current;try{const result=await workbench.createWorkspaceDirectory({selectionToken:page.selectionToken,name});if(!current(at))return false;if(!result?.ok){setError(pickerNeedText(result?.error,'文件夹未能创建,请查看当前目录。'));return false;}setPage(result.value);return true;}catch{if(current(at))setError('创建结果无法确认,请查看目录后再试。');return false;}finally{if(current(at)){locked.current=false;savingRef.current=false;setBusy(false);}}};
|
|
159
159
|
if(!open)return null;
|
|
160
160
|
return h('section',{role:'dialog','aria-modal':true,'aria-label':'选择工作区目录',style:{position:'fixed',inset:0,zIndex:100,background:'rgba(0,0,0,.25)',display:'flex',alignItems:'center',justifyContent:'center'}},h('div',{style:{background:'var(--background, Canvas)',color:'var(--foreground, CanvasText)',border:'1px solid var(--border, #ddd)',borderRadius:12,padding:24,width:'min(720px,90vw)',maxHeight:'85vh',overflow:'auto',boxShadow:'0 12px 40px rgba(0,0,0,.2)'}},h('h2',null,'选择工作区目录'),h('div',{'aria-label':'目录所在设备',style:{display:'flex',gap:8}},...['local','host'].map(value=>h('button',{key:value,type:'button',disabled:busy||creating,'aria-pressed':target===value,onClick:()=>browse({target:value})},value==='local'?'本机':'远程主机'))),
|
|
161
|
-
target==='host'?h(RemoteWorkspaceBrowser,{page,busy,error,browse,select,cancel,createFolder,saving,onCreateOpenChange:setCreating}):h(React.Fragment,null,h('p',{role:'status'},busy?saving?'正在添加工作区…':'请在系统窗口选择文件夹。':'本机文件夹使用系统目录选择框。'),error?h('p',{role:'alert'},error):null,h('button',{type:'button',disabled:busy,onClick:()=>browse({target:'local'})},'选择文件夹'),h('button',{type:'button',disabled:saving,onClick:cancel},'取消'))));
|
|
161
|
+
target===null?h(React.Fragment,null,h('p',null,'请选择目录所在设备。'),h('button',{type:'button',onClick:cancel},'取消')):target==='host'?h(RemoteWorkspaceBrowser,{page,busy,error,browse,select,cancel,createFolder,saving,onCreateOpenChange:setCreating}):h(React.Fragment,null,h('p',{role:'status'},busy?saving?'正在添加工作区…':'请在系统窗口选择文件夹。':'本机文件夹使用系统目录选择框。'),error?h('p',{role:'alert'},error):null,h('button',{type:'button',disabled:busy,onClick:()=>browse({target:'local'})},'选择文件夹'),h('button',{type:'button',disabled:saving,onClick:cancel},'取消'))));
|
|
162
162
|
}
|
|
163
163
|
function createWorkspaceDirectoryPickerRegistration(ctx,workbench){
|
|
164
164
|
const pickDirectory=()=>{const desktop=globalThis.__DSH_DIRECTORY_PICKER__;return desktop===undefined?ctx.uiWorkspace.pickDirectory():desktop.pick();};
|
|
@@ -173,7 +173,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
173
173
|
};
|
|
174
174
|
return {getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},start(){if(started||!alive)return;started=true;return reload();},reload,dispose(){alive=false;epoch++;clear();listeners.clear();}};
|
|
175
175
|
}
|
|
176
|
-
function WorkspacePickerSettings({registration}){const value=React.useSyncExternalStore(registration.subscribe,registration.getSnapshot),settings=value.settings;return h('details',null,h('summary',null,'统一目录选择器'),h('p',{role:value.phase==='failed'?'alert':'status'},value.message),settings?h(React.Fragment,null,h('p',null,'远程映射目录:'+settings.mappingRoot+'
|
|
176
|
+
function WorkspacePickerSettings({registration}){const value=React.useSyncExternalStore(registration.subscribe,registration.getSnapshot),settings=value.settings;return h('details',null,h('summary',null,'统一目录选择器'),h('p',{role:value.phase==='failed'?'alert':'status'},value.message),settings?h(React.Fragment,null,h('p',null,'远程映射目录:'+settings.mappingRoot+';子目录名由主机名与绝对路径生成,仅用于原生工作区占位,不作主机执行身份检查。仅作原生工作区身份锚,不同步、不存员工文件;成功映射保留,移除工作区或卸载后不自动清理。添加失败只影响本次;若列表有残留条目,可在 DSH 原生工作区管理中删除,再重新选择。选择器不会因旧失败持续锁住。'),h('p',null,'workspaceLocations.pickerSlotPriority 当前为 '+settings.slotPriority+'(默认-10,小于0的安全整数;数值越低优先级越高)。可在官方插件 Config 修改,保留官方原生入口。'),h('p',null,'workspaceLocations.pageSize 当前为 '+settings.pageSize+'(默认100);enrollmentMetadataMaxBytes 当前为 '+settings.metadataMaxBytes+' 字节(默认1048576)。目录输出同时受 commandOutputMaxBytes 约束;请到官方插件 Config 查看和修改。没有隐藏目录数量或寿命上限。')):null,h('button',{type:'button',disabled:value.phase==='loading',onClick:()=>registration.reload()},'重新加载目录选择器设置'));}
|
|
177
177
|
|
|
178
178
|
function WorkspaceLocations({state,workbench}){
|
|
179
179
|
const locations=state?.workspaceLocations,[error,setError]=React.useState(''),[refreshing,setRefreshing]=React.useState(false);if(!locations)return null;
|
|
@@ -2,15 +2,13 @@ const fs=require('node:fs/promises');
|
|
|
2
2
|
const {constants}=require('node:fs');
|
|
3
3
|
const path=require('node:path');
|
|
4
4
|
const os=require('node:os');
|
|
5
|
-
const error=code=>({protocolVersion:1,ok:false,error:{code}});
|
|
6
|
-
const validIdentity=value=>value&&typeof value==='object'&&['device','inode','mtimeNs','ctimeNs'].every(key=>typeof value[key]==='string'&&/^-?\d+$/.test(value[key]));
|
|
5
|
+
const error=(code,exception)=>({protocolVersion:1,ok:false,error:{code,...(['ENOENT','ENOTDIR','EACCES','EPERM','EIO','ELOOP'].includes(exception?.code)?{systemCode:exception.code}:{})}});
|
|
7
6
|
const identity=stat=>({device:String(stat.dev),inode:String(stat.ino),mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
|
|
8
7
|
const entryIdentity=stat=>({device:String(stat.dev),inode:String(stat.ino)});
|
|
9
|
-
const equal=(a,b)=>['device','inode','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
|
|
10
8
|
const binaryCompare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
|
|
11
9
|
const validPath=value=>typeof value==='string'&&path.isAbsolute(value)&&!value.includes('\0');
|
|
12
10
|
const invalid=()=>Object.assign(new Error('HOST_DIRECTORY_INVALID'),{directoryCode:'HOST_DIRECTORY_INVALID'});
|
|
13
|
-
const classify=exception=>exception?.directoryCode??(['
|
|
11
|
+
const classify=exception=>exception?.directoryCode??(['ENOENT','ENOTDIR','ELOOP'].includes(exception?.code)?'HOST_DIRECTORY_INVALID':'HOST_DIRECTORY_UNREADABLE');
|
|
14
12
|
const unknownPermissions=()=>({read:null,write:null,execute:null,reason:'HOST_PERMISSION_UNKNOWN'});
|
|
15
13
|
async function permissions(target){
|
|
16
14
|
const result={};let unknown=false;
|
|
@@ -24,14 +22,13 @@ async function observe(requestedPath){
|
|
|
24
22
|
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())throw invalid();
|
|
25
23
|
return {requestedPath,path:resolved,parentPath:path.dirname(resolved)===resolved?null:path.dirname(resolved),identity:identity(stat),entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink(),permissions:await permissions(resolved)};
|
|
26
24
|
}
|
|
27
|
-
function unchanged(before,after){return before.path===after.path&&equal(before.identity,after.identity)&&before.entryIdentity.device===after.entryIdentity.device&&before.entryIdentity.inode===after.entryIdentity.inode;}
|
|
28
25
|
async function directoryEntry(requestedPath,name){
|
|
29
26
|
const entry=await fs.lstat(requestedPath,{bigint:true});if(!entry.isDirectory()&&!entry.isSymbolicLink())return null;
|
|
30
27
|
const base={name,requestedPath,entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink()};
|
|
31
28
|
try{
|
|
32
29
|
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())return null;
|
|
33
30
|
const access=await permissions(resolved);
|
|
34
|
-
return {...base,path:resolved,identity:identity(stat),permissions:access
|
|
31
|
+
return {...base,path:resolved,identity:identity(stat),permissions:access};
|
|
35
32
|
}catch(exception){return {...base,permissions:unknownPermissions(),errorCode:classify(exception)};}
|
|
36
33
|
}
|
|
37
34
|
async function execute(request){
|
|
@@ -39,12 +36,12 @@ async function execute(request){
|
|
|
39
36
|
if(!Number.isSafeInteger(request.maxOutputBytes)||request.maxOutputBytes<1)return error('HOST_DIRECTORY_INVALID');
|
|
40
37
|
if(request.path!==undefined&&!validPath(request.path))return error('HOST_DIRECTORY_INVALID');
|
|
41
38
|
if(request.operation==='inspect'&&request.path===undefined)return error('HOST_DIRECTORY_INVALID');
|
|
42
|
-
if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.
|
|
43
|
-
if(request.operation==='create'&&(!validPath(request.path)
|
|
39
|
+
if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0'))))return error('HOST_DIRECTORY_INVALID');
|
|
40
|
+
if(request.operation==='create'&&(!validPath(request.path)||typeof request.name!=='string'||['','.','..'].includes(request.name)||/[\\/\x00-\x1f\x7f]/.test(request.name)))return error('HOST_DIRECTORY_INVALID');
|
|
44
41
|
const requestedPath=request.path??os.homedir();
|
|
45
42
|
try{
|
|
43
|
+
if(request.operation==='inspect'){const stat=await fs.stat(requestedPath);if(!stat.isDirectory())throw invalid();const result={protocolVersion:1,ok:true,value:{path:requestedPath}};return Buffer.byteLength(JSON.stringify(result)+'\n')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;}
|
|
46
44
|
const before=await observe(requestedPath);
|
|
47
|
-
if(request.expected!==undefined&&!equal(before.identity,request.expected))return error('HOST_DIRECTORY_CHANGED');
|
|
48
45
|
if(request.operation==='create'){
|
|
49
46
|
const child=path.join(before.path,request.name);
|
|
50
47
|
try{await fs.mkdir(child);}catch(exception){return error(exception?.code==='EEXIST'?'HOST_DIRECTORY_EXISTS':classify(exception));}
|
|
@@ -64,11 +61,9 @@ async function execute(request){
|
|
|
64
61
|
}
|
|
65
62
|
const hasMore=window.length>request.pageSize;if(hasMore)window.pop();value={...before,entries:window,...hasMore?{nextAfter:window[window.length-1].name}:{}};
|
|
66
63
|
}
|
|
67
|
-
let after;try{after=await observe(requestedPath);}catch{return error('HOST_DIRECTORY_CHANGED');}
|
|
68
|
-
if(!unchanged(before,after))return error('HOST_DIRECTORY_CHANGED');
|
|
69
64
|
const result={protocolVersion:1,ok:true,value};
|
|
70
65
|
return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
|
|
71
|
-
}catch(exception){return error(classify(exception));}
|
|
66
|
+
}catch(exception){return error(classify(exception),exception);}
|
|
72
67
|
}
|
|
73
68
|
async function main(){
|
|
74
69
|
let input='';for await(const chunk of process.stdin)input+=chunk;
|
package/lib/api.d.ts
CHANGED
|
@@ -94,21 +94,16 @@ export interface ContractInfo {
|
|
|
94
94
|
connectionMessages?: 1;
|
|
95
95
|
localWorkspaceContext?: 1;
|
|
96
96
|
modelCatalogTarget?: 1;
|
|
97
|
-
hostWorkspaceResolution?:
|
|
97
|
+
hostWorkspaceResolution?: 2;
|
|
98
98
|
}
|
|
99
99
|
export interface WorkspaceUse {
|
|
100
100
|
provider: Provider;
|
|
101
101
|
purpose: 'user-turn';
|
|
102
102
|
}
|
|
103
103
|
export interface HostSessionProjectTarget {
|
|
104
|
-
instanceId: string;
|
|
105
|
-
epoch: number;
|
|
106
|
-
bindingRevision: number;
|
|
107
|
-
bindingId: string;
|
|
108
104
|
sessionId: string;
|
|
109
|
-
workspaceId: string;
|
|
110
105
|
source: 'host';
|
|
111
|
-
|
|
106
|
+
host: string;
|
|
112
107
|
project: {
|
|
113
108
|
name: string;
|
|
114
109
|
path: string;
|
package/lib/auth-diagnostics.js
CHANGED
|
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { need } from "./needs.js";
|
|
3
3
|
const markers = ['AW_REMOTE_COMMAND_KILL_FAILED', 'AUTH_STATUS_JSON_INVALID:SyntaxError', 'Permission denied', 'Host key verification failed', 'Connection refused', 'Connection closed', 'command not found', 'No such file or directory'];
|
|
4
4
|
const names = ['Error', 'TypeError', 'SyntaxError', 'RangeError', 'AbortError', 'DOMException', 'UnknownError'];
|
|
5
|
-
const codes = ['ENOENT', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
|
|
5
|
+
const codes = ['ENOENT', 'ENOTDIR', 'EIO', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
|
|
6
6
|
const stages = ['ssh-status', 'ssh-result', 'remote-frame', 'auth-status', 'connect-check-login', 'integration-pre-login', 'process-spawn', 'process-stdin', 'process-output', 'process-runner'];
|
|
7
7
|
const reasons = ['CANCELLED', 'SSH_EXIT_NONZERO', 'SSH_STDERR_NONEMPTY', 'FRAME_TRUNCATED', 'FRAME_JSON_INVALID', 'FRAME_OBJECT_INVALID', 'FRAME_VERSION_INVALID', 'FRAME_NONCE_INVALID', 'FRAME_AFTER_END', 'FRAME_KEYS_INVALID', 'FRAME_START_MISSING', 'FRAME_BASE64_INVALID', 'REMOTE_COMMAND_SIGNAL', 'FRAME_END_EXIT_INVALID', 'FRAME_SEQUENCE_OR_VALUE_INVALID', 'FRAME_END_MISSING', 'STATUS_ARGUMENT_INVALID', 'STATUS_EXECUTION_FAILED', 'STATUS_JSON_INVALID', 'STATUS_OBJECT_INVALID', 'STATUS_KEYS_INVALID', 'STATUS_VERSION_INVALID', 'STATUS_PROVIDER_INVALID', 'STATUS_EXIT_MISMATCH', 'STATUS_LOGGED_IN_INVALID', 'STATUS_STDERR_NONEMPTY', 'STATUS_EXIT_INVALID', 'STATUS_EXCEPTION', 'STATUS_SUPERSEDED', 'SSH_PORT_MISSING', 'STDIN_FAILED', 'SPAWN_FAILED', 'OUTPUT_LIMIT_EXCEEDED', 'PROCESS_SIGNAL'];
|
|
8
8
|
const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
@@ -45,11 +45,10 @@ export interface HostDirectoryRequest {
|
|
|
45
45
|
path?: string;
|
|
46
46
|
after?: string;
|
|
47
47
|
pageSize: number;
|
|
48
|
-
expected?: HostDirectoryIdentity;
|
|
49
48
|
}
|
|
50
49
|
export interface HostDirectories {
|
|
51
50
|
browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
|
|
52
|
-
inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo
|
|
53
|
-
create?(target: SshTarget, path: string, name: string,
|
|
51
|
+
inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
|
|
52
|
+
create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
|
|
54
53
|
}
|
|
55
54
|
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number): HostDirectories;
|
package/lib/host-directories.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import { runRemote } from "./ssh.js";
|
|
3
3
|
import { fail, ok } from "./needs.js";
|
|
4
|
-
import { AuthDiagnosticError } from "./auth-diagnostics.js";
|
|
4
|
+
import { AuthDiagnosticError, authFailure } from "./auth-diagnostics.js";
|
|
5
5
|
const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID', 'HOST_DIRECTORY_EXISTS'];
|
|
6
6
|
const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
7
|
const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
|
|
@@ -18,14 +18,14 @@ function validEntry(value, parent) {
|
|
|
18
18
|
return false;
|
|
19
19
|
if (value.path === undefined || value.identity === undefined)
|
|
20
20
|
return value.path === undefined && value.identity === undefined && value.errorCode !== undefined;
|
|
21
|
-
return validPath(value.path) && validIdentity(value.identity)
|
|
21
|
+
return validPath(value.path) && validIdentity(value.identity);
|
|
22
22
|
}
|
|
23
23
|
const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
24
24
|
export function createHostDirectories(runner, maxOutputBytes) {
|
|
25
25
|
async function request(target, operation, data, signal) {
|
|
26
26
|
if (signal.aborted)
|
|
27
27
|
return fail('CONNECTION_LOST');
|
|
28
|
-
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)
|
|
28
|
+
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.after !== undefined && (!validName(data.after))))
|
|
29
29
|
return fail('HOST_DIRECTORY_INVALID');
|
|
30
30
|
try {
|
|
31
31
|
const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
@@ -34,7 +34,7 @@ export function createHostDirectories(runner, maxOutputBytes) {
|
|
|
34
34
|
if (signal.aborted)
|
|
35
35
|
return fail('CONNECTION_LOST');
|
|
36
36
|
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
37
|
-
return
|
|
37
|
+
return authFailure('ssh-result', raw.exitCode !== 0 ? 'SSH_EXIT_NONZERO' : 'SSH_STDERR_NONEMPTY', { exitCode: raw.exitCode }, undefined, 'CONNECTION_LOST');
|
|
38
38
|
if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
|
|
39
39
|
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
40
40
|
let result;
|
|
@@ -49,13 +49,15 @@ export function createHostDirectories(runner, maxOutputBytes) {
|
|
|
49
49
|
if (!result.ok) {
|
|
50
50
|
const error = result.error;
|
|
51
51
|
const code = object(error) ? codes.find(code => code === error.code) : undefined;
|
|
52
|
-
return
|
|
52
|
+
return authFailure('host-directory', 'REMOTE_DIRECTORY_ERROR', { ...(object(error) && ['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM', 'EIO', 'ELOOP'].includes(String(error.systemCode)) ? { errorCode: error.systemCode } : {}) }, undefined, code ?? 'PROJECT_PROTOCOL_INVALID');
|
|
53
53
|
}
|
|
54
|
+
if (operation === 'inspect')
|
|
55
|
+
return object(result.value) && result.value.path === data.path ? ok({ path: data.path }) : fail('PROJECT_PROTOCOL_INVALID');
|
|
54
56
|
if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== (operation === 'create' ? (data.path.endsWith('/') ? data.path : data.path + '/') + data.name : data.path))
|
|
55
57
|
return fail('PROJECT_PROTOCOL_INVALID');
|
|
56
58
|
if (operation === 'browse') {
|
|
57
59
|
const value = result.value;
|
|
58
|
-
if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name)
|
|
60
|
+
if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name))
|
|
59
61
|
return fail('PROJECT_PROTOCOL_INVALID');
|
|
60
62
|
}
|
|
61
63
|
return ok(result.value);
|
|
@@ -69,8 +71,8 @@ export function createHostDirectories(runner, maxOutputBytes) {
|
|
|
69
71
|
if (error.diagnostic.stage === 'remote-frame')
|
|
70
72
|
return fail('PROJECT_PROTOCOL_INVALID');
|
|
71
73
|
}
|
|
72
|
-
return
|
|
74
|
+
return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
|
|
73
75
|
}
|
|
74
76
|
}
|
|
75
|
-
return { create: (target, path, name,
|
|
77
|
+
return { create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
76
78
|
}
|
|
@@ -1,19 +1,8 @@
|
|
|
1
1
|
import type { ConnectApi, HostSessionProjectTarget, Result, WorkspaceUse } from './api.ts';
|
|
2
2
|
import type { HostWorkspaceResolveContext } from './workspace-location-types.ts';
|
|
3
|
-
import type { createWorkspaceLocations } from './workspace-locations.ts';
|
|
4
|
-
import type { NativeWorkspaceRegistry } from './native-workspace.ts';
|
|
5
|
-
interface Session {
|
|
6
|
-
header: Record<string, any>;
|
|
7
|
-
}
|
|
8
3
|
interface Options {
|
|
9
|
-
api: ConnectApi
|
|
10
|
-
|
|
11
|
-
services: () => {
|
|
12
|
-
sessions: {
|
|
13
|
-
get(id: string): Session | undefined;
|
|
14
|
-
};
|
|
15
|
-
};
|
|
16
|
-
withHostBinding: ReturnType<typeof createWorkspaceLocations>['withHostBinding'];
|
|
4
|
+
api: Pick<ConnectApi, 'ensureReady' | 'appendRemoteConversationDetail'> & Partial<Pick<ConnectApi, 'getConnectionState'>>;
|
|
5
|
+
hostDirectories?: import('./host-directories.ts').HostDirectories;
|
|
17
6
|
}
|
|
18
7
|
export declare function createHostSessionProjects(o: Options): {
|
|
19
8
|
resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
|
|
@@ -1,62 +1,77 @@
|
|
|
1
1
|
import { basename, isAbsolute } from 'node:path';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { exceptionSummary, outputSummary } from "./auth-diagnostics.js";
|
|
4
|
+
import { ok, need, NeedError } from "./needs.js";
|
|
5
5
|
const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
|
|
6
|
-
function reject(code) { throw new NeedError(need(code)); }
|
|
7
|
-
function changedSessionBinding() {
|
|
8
|
-
const n = need('PROJECT_BINDING_INVALID');
|
|
9
|
-
n.message = '文件来源已改,请新建会话继续';
|
|
10
|
-
n.actor = 'employee';
|
|
11
|
-
n.requires = '新会话与当前文件来源';
|
|
12
|
-
n.action = { id: 'new-session', label: '新建会话继续', available: false };
|
|
13
|
-
throw new NeedError(n);
|
|
14
|
-
}
|
|
6
|
+
function reject(code, reason) { throw new NeedError({ ...need(code), officialReason: reason }); }
|
|
15
7
|
export function createHostSessionProjects(o) {
|
|
16
|
-
|
|
17
|
-
const sources = new Map();
|
|
8
|
+
const controllers = new Set();
|
|
18
9
|
let disposed = false;
|
|
19
10
|
async function resolve(id, use, input) {
|
|
11
|
+
let stage = 'request';
|
|
12
|
+
const failure = (error) => {
|
|
13
|
+
let n = error instanceof NeedError ? error.need : need('PROJECT_BINDING_INVALID');
|
|
14
|
+
if (n.code === 'HOST_DIRECTORY_UNREADABLE')
|
|
15
|
+
n = { ...n, message: '暂时无法读取会话记录的主机目录,请查看技术详情,确认主机存储或权限恢复后再试。' };
|
|
16
|
+
if (n.code === 'HOST_DIRECTORY_INVALID')
|
|
17
|
+
n = { ...n, message: '会话记录的主机路径不存在或不是文件夹,请恢复该目录后再试。' };
|
|
18
|
+
if (n.officialReason === 'SESSION_HOST_UNAVAILABLE')
|
|
19
|
+
n = { ...n, message: '此会话使用的主机当前未连接,请连接原主机后再试;会话文件来源保持不变。' };
|
|
20
|
+
const exception = exceptionSummary(error);
|
|
21
|
+
const payload = { stage, reason: n.officialReason ?? (error instanceof NeedError ? 'DECLARED_NEED' : 'UNEXPECTED_EXCEPTION'), ...exception, ...(!(error instanceof NeedError) && error instanceof Error ? { exception: outputSummary(error.message) } : {}) };
|
|
22
|
+
// 沿已有本机日志留一行;不记录异常原文/路径/凭据,也不让日志失败改写原失败。
|
|
23
|
+
const line = { event: 'HOST_WORKSPACE_RESOLVE_FAILED', code: n.code, ...payload };
|
|
24
|
+
try {
|
|
25
|
+
if (!text(id) || !use || !['claude', 'codex'].includes(use.provider) || typeof o.api.appendRemoteConversationDetail !== 'function')
|
|
26
|
+
throw Error('DIAGNOSTIC_CONTEXT_UNAVAILABLE');
|
|
27
|
+
const connection = o.api.getConnectionState?.();
|
|
28
|
+
o.api.appendRemoteConversationDetail({ version: 1, eventId: randomUUID(), instanceId: connection?.instanceId ?? 'unknown', epoch: connection?.epoch ?? 0, sessionId: id, provider: use.provider, turn: null, step: null, sequence: 0, kind: 'diagnostic', severity: 'action-required', code: n.code, summary: n.message, payload });
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
try {
|
|
32
|
+
console.warn(JSON.stringify(line));
|
|
33
|
+
}
|
|
34
|
+
catch { /* 日志不可用不改变本轮结果。 */ }
|
|
35
|
+
}
|
|
36
|
+
return { ok: false, error: n };
|
|
37
|
+
};
|
|
20
38
|
try {
|
|
21
39
|
if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
|
|
22
|
-
reject('PROJECT_BINDING_REQUIRED');
|
|
23
|
-
const
|
|
24
|
-
if (!
|
|
25
|
-
reject('
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (!isDeepStrictEqual(ready.value, value.target))
|
|
53
|
-
reject('CONNECTION_LOST');
|
|
54
|
-
return ok({ instanceId: c.instanceId, epoch: c.epoch, sessionId: id, workspaceId: c.workspaceId, bindingId: c.expectedBindingId, bindingRevision: value.revision, source: 'host', directory: structuredClone(value.directory), project: { name: basename(value.directory.path) || '/', path: value.directory.path }, target: structuredClone(value.target) });
|
|
55
|
-
}, () => { guard(); sources.set(id, source); });
|
|
40
|
+
reject('PROJECT_BINDING_REQUIRED', 'SESSION_OR_REQUEST_UNAVAILABLE');
|
|
41
|
+
const source = structuredClone(input);
|
|
42
|
+
if (!source || source.source !== 'host' || !text(source.host) || !text(source.path) || !isAbsolute(source.path))
|
|
43
|
+
reject('PROJECT_BINDING_REQUIRED', 'SESSION_HOST_PATH_REQUIRED');
|
|
44
|
+
if (disposed)
|
|
45
|
+
reject('DISPOSED', 'RUNTIME_DISPOSED');
|
|
46
|
+
stage = 'login-ready';
|
|
47
|
+
const ready = await o.api.ensureReady(use.provider);
|
|
48
|
+
if (!ready.ok)
|
|
49
|
+
return failure(new NeedError(ready.error));
|
|
50
|
+
if (disposed)
|
|
51
|
+
reject('DISPOSED', 'RUNTIME_DISPOSED');
|
|
52
|
+
if (ready.value.host !== source.host)
|
|
53
|
+
reject('WORKSPACE_LOCATION_INVALID', 'SESSION_HOST_UNAVAILABLE');
|
|
54
|
+
if (!o.hostDirectories)
|
|
55
|
+
reject('DEPENDENCY_REQUIRED', 'HOST_DIRECTORY_SERVICE_REQUIRED');
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
controllers.add(controller);
|
|
58
|
+
try {
|
|
59
|
+
stage = 'host-directory';
|
|
60
|
+
const checked = await o.hostDirectories.inspect(ready.value, source.path, controller.signal);
|
|
61
|
+
if (!checked.ok)
|
|
62
|
+
return failure(new NeedError(checked.error));
|
|
63
|
+
if (disposed)
|
|
64
|
+
reject('DISPOSED', 'RUNTIME_DISPOSED');
|
|
65
|
+
return ok({ sessionId: id, source: 'host', host: source.host, project: { name: basename(source.path) || '/', path: source.path }, target: structuredClone(ready.value) });
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
controllers.delete(controller);
|
|
69
|
+
}
|
|
56
70
|
}
|
|
57
71
|
catch (e) {
|
|
58
|
-
return e
|
|
72
|
+
return failure(e);
|
|
59
73
|
}
|
|
60
74
|
}
|
|
61
|
-
return { resolve, dispose() { disposed = true;
|
|
75
|
+
return { resolve, dispose() { disposed = true; for (const controller of controllers)
|
|
76
|
+
controller.abort(); } };
|
|
62
77
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ export interface Config {
|
|
|
38
38
|
};
|
|
39
39
|
}
|
|
40
40
|
export declare const Config: z<Config>;
|
|
41
|
-
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void): void;
|
|
41
|
+
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void, autoStart?: boolean): void;
|
|
42
42
|
export declare function apply(ctx: Context, config?: Config): void;
|
|
43
43
|
export { createProfileEnrollment } from './profile-enrollment.ts';
|
|
44
44
|
export { profileSettings } from './profile-settings.ts';
|
package/lib/index.js
CHANGED
|
@@ -13,7 +13,7 @@ export { writeNetworkConfig } from "./network.js";
|
|
|
13
13
|
export { createConnect } from "./connect.js";
|
|
14
14
|
export { sshArgs } from "./ssh.js";
|
|
15
15
|
export const name = 'ai-workbench-connect';
|
|
16
|
-
export const inject = ['aiWorkbenchNetwork'];
|
|
16
|
+
export const inject = ['aiWorkbenchNetwork', 'profileContext'];
|
|
17
17
|
const positive = () => z.number().step(1).min(1);
|
|
18
18
|
// Administrator settings are optional in schema so the loaded service can explain missing prerequisites.
|
|
19
19
|
// aiWorkbenchNetwork itself is a required Cordis injection; missing N holds this module from loading.
|
|
@@ -37,12 +37,13 @@ export const Config = z.object({
|
|
|
37
37
|
executable: z.string().description('darwin-arm64默认Electron.app/Contents/MacOS/Electron;其他平台无默认,管理员可改'), loginOutputMaxBytes: positive().default(L_DEFAULTS.loginOutputMaxBytes).description('登录进程输出字节上限;默认1048576,管理员可改'), ipcMaxBytes: positive().default(L_DEFAULTS.ipcMaxBytes).description('私有IPC字节上限;默认1048576,管理员可改'),
|
|
38
38
|
}),
|
|
39
39
|
});
|
|
40
|
-
export function register(ctx, ports, _inventory, extend) {
|
|
40
|
+
export function register(ctx, ports, _inventory, extend, autoStart = true) {
|
|
41
41
|
// 当前独立插件始终检查两品牌;保留旧inventory参数兼容调用,但不以交付清单开关能力。
|
|
42
42
|
const api = createConnect(ports, state => ctx.emit('ai-workbench/connect-state', state), { onConnectionState: state => ctx.emit('ai-workbench/connection-state', state), onPromptState: state => ctx.emit('ai-workbench/login-prompt-state', state), onPromptResult: result => ctx.emit('ai-workbench/login-prompt-result', result) });
|
|
43
43
|
extend?.(api);
|
|
44
44
|
ctx.provide('aiWorkbenchConnect', api);
|
|
45
|
-
ctx.effect(() => {
|
|
45
|
+
ctx.effect(() => { if (autoStart)
|
|
46
|
+
void api.refreshLoginPrompts(); return () => api.dispose(); });
|
|
46
47
|
}
|
|
47
48
|
export function apply(ctx, config = {}) {
|
|
48
49
|
config = profileSettings(config, ctx.get('profileContext')?.dir);
|
|
@@ -50,7 +51,7 @@ export function apply(ctx, config = {}) {
|
|
|
50
51
|
const sources = createComponentSources({ sha256: config.helper?.sha256 });
|
|
51
52
|
ctx.effect(() => () => sources.dispose());
|
|
52
53
|
const ports = configuredPorts(config, network, component, sources);
|
|
53
|
-
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network));
|
|
54
|
+
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network, true), false);
|
|
54
55
|
registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
55
56
|
}
|
|
56
57
|
export { createProfileEnrollment } from "./profile-enrollment.js";
|
package/lib/needs.js
CHANGED
|
@@ -41,13 +41,13 @@ const entries = {
|
|
|
41
41
|
POLICY_DENIED: { layer: 'auth', message: '公司的 AI 席位设置不允许此操作,需要 AI 账号管理员开启。', requires: '允许此操作的 AI 席位设置', actor: 'ai-administrator', action: { id: 'contact-ai-administrator', label: '联系 AI 账号管理员', available: false } },
|
|
42
42
|
CONNECTION_LOST: { layer: 'network', message: '连接中断,正在等待网络恢复信号,恢复后将重新连接。', requires: '网络恢复', actor: 'plugin', action: { id: 'await-network', label: '等待网络恢复', available: false } },
|
|
43
43
|
DEPENDENCY_REQUIRED: { layer: 'integration', message: '远程主机连接的连接组件没有装好,请联系管理员。', requires: '提供方契约与适配器', actor: 'administrator', action: { id: 'supply-dependency', label: '提供集成前置条件', available: false } },
|
|
44
|
-
SETTINGS_REQUIRED: { layer: 'settings', message: '
|
|
44
|
+
SETTINGS_REQUIRED: { layer: 'settings', message: '远程主机连接设置暂不可用,请查看技术详情。', requires: '已确认的连接设置', actor: 'administrator', action: { id: 'configure-settings', label: '确认具名设置', available: false } },
|
|
45
45
|
AUTH_STATUS_INVALID: { layer: 'auth', message: '暂时无法确认登录状态,可检查本机网络后重新检查。', requires: '有效的官方 CLI 登录状态', actor: 'administrator', action: { id: 'inspect-auth-status', label: '检查官方 CLI', available: false } },
|
|
46
46
|
LOGIN_FAILED: { layer: 'auth', message: '登录未完成,窗口已关闭或助手失败,可以重新授权。', requires: '完成 AI 授权', actor: 'employee', action: { id: 'open-login', label: '重新授权', available: true } },
|
|
47
47
|
HOST_TRUST_REQUIRED: { layer: 'ssh', message: '远程主机连接还缺少可信的连接信息,请联系管理员。', requires: 'host.knownHosts', actor: 'administrator', action: { id: 'supply-host-trust', label: '提供主机信任材料', available: false } },
|
|
48
48
|
HOST_KEY_MISMATCH: { layer: 'ssh', message: '主机身份与已开通的信任材料不符,需要管理员检查。', requires: '匹配的主机公钥', actor: 'administrator', action: { id: 'verify-host-trust', label: '检查主机身份', available: false } },
|
|
49
49
|
PROJECT_PROTOCOL_INVALID: { layer: 'projects', message: '本次未能读取工作区位置,可重新打开目录选择器再选。', requires: '匹配版本的工作区服务', actor: 'administrator', action: { id: 'inspect-project-protocol', label: '检查工作区接口', available: false } },
|
|
50
|
-
PROJECT_BINDING_INVALID: { layer: 'projects', message: '
|
|
50
|
+
PROJECT_BINDING_INVALID: { layer: 'projects', message: '本轮工作区准备失败,原会话历史仍可查看。请查看技术详情后再试。', requires: '可核对的会话与工作区关系', actor: 'employee', action: { id: 'inspect-remote-details', label: '查看技术详情', available: true } },
|
|
51
51
|
PROJECT_BINDING_REQUIRED: { layer: 'projects', message: '请在会话中选择已关联的远程工作区。', requires: '当前会话的可信远程工作区关联', actor: 'employee', action: { id: 'select-workspace', label: '选择工作区', available: true } },
|
|
52
52
|
DISPOSED: { layer: 'integration', message: '连接插件已卸载,需要重新启用插件。', requires: '已启用的连接插件', actor: 'employee', action: { id: 'enable-plugin', label: '启用插件', available: false } },
|
|
53
53
|
};
|
package/lib/profile-runtime.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ import type { ConnectApi } from './api.ts';
|
|
|
3
3
|
import type { Ports } from './ports.ts';
|
|
4
4
|
import type { Config } from './index.ts';
|
|
5
5
|
import type { NetworkProvider } from './provider.ts';
|
|
6
|
-
export declare function attachProfileRuntime(ctx: Context, api: ConnectApi, ports: Ports, config: Config, network?: NetworkProvider): void;
|
|
6
|
+
export declare function attachProfileRuntime(ctx: Context, api: ConnectApi, ports: Ports, config: Config, network?: NetworkProvider, autoStart?: boolean): void;
|
package/lib/profile-runtime.js
CHANGED
|
@@ -8,10 +8,10 @@ import { createHostSessionProjects } from "./host-session-projects.js";
|
|
|
8
8
|
import { createConversationLog } from "./conversation-log.js";
|
|
9
9
|
import { L_DEFAULTS, WORKSPACE_LOCATION_DEFAULTS } from "./defaults.js";
|
|
10
10
|
import { fail } from "./needs.js";
|
|
11
|
-
export function attachProfileRuntime(ctx, api, ports, config, network) {
|
|
12
|
-
ctx.inject(['profileContext'], scope => attachScopedProfileRuntime(scope, api, ports, config, network));
|
|
11
|
+
export function attachProfileRuntime(ctx, api, ports, config, network, autoStart = false) {
|
|
12
|
+
ctx.inject(['profileContext'], scope => attachScopedProfileRuntime(scope, api, ports, config, network, autoStart));
|
|
13
13
|
}
|
|
14
|
-
function attachScopedProfileRuntime(ctx, api, ports, config, network) {
|
|
14
|
+
function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart = false) {
|
|
15
15
|
const profile = ctx.get('profileContext');
|
|
16
16
|
if (!profile || typeof profile.dir !== 'string')
|
|
17
17
|
return;
|
|
@@ -26,6 +26,7 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network) {
|
|
|
26
26
|
api.importEnrollment = async () => { const result = await manager.importEnrollment(); if (result.ok && result.value.outcome === 'imported')
|
|
27
27
|
await api.refreshLoginPrompts(); return result; };
|
|
28
28
|
ctx.effect(() => () => manager.dispose());
|
|
29
|
+
// 首次连接由真实资料读取器就绪触发;不读取 integration 的未配置占位端口。
|
|
29
30
|
const beforeAppend = api.appendRemoteConversationDetail, beforeRead = api.readConversationLog;
|
|
30
31
|
const log = createConversationLog({ profileDir: profile.dir });
|
|
31
32
|
api.appendRemoteConversationDetail = log.append;
|
|
@@ -53,14 +54,16 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network) {
|
|
|
53
54
|
};
|
|
54
55
|
api.readConversationLog = readLogs;
|
|
55
56
|
const beforeContract = api.getContractInfo;
|
|
56
|
-
const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution:
|
|
57
|
+
const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution: 2 } : {}) });
|
|
57
58
|
api.getContractInfo = currentContract;
|
|
58
59
|
ctx.effect(() => () => { if (api.getContractInfo === currentContract)
|
|
59
60
|
api.getContractInfo = beforeContract; if (api.appendRemoteConversationDetail === log.append)
|
|
60
61
|
api.appendRemoteConversationDetail = beforeAppend; if (api.readConversationLog === readLogs)
|
|
61
62
|
api.readConversationLog = beforeRead; });
|
|
62
63
|
const unavailableHost = async () => fail('DEPENDENCY_REQUIRED');
|
|
63
|
-
api.
|
|
64
|
+
const host = createHostSessionProjects({ api, hostDirectories: ports.hostDirectories });
|
|
65
|
+
api.resolveSessionProject = host.resolve;
|
|
66
|
+
ctx.effect(() => () => { api.resolveSessionProject = unavailableHost; host.dispose(); });
|
|
64
67
|
let locationRevision = 0;
|
|
65
68
|
ctx.inject(['profileContext', 'workspaceRegistry', 'sessions'], native => {
|
|
66
69
|
const registry = native.get('workspaceRegistry');
|
|
@@ -81,9 +84,9 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network) {
|
|
|
81
84
|
api.refreshWorkspaceLocations = locations.refreshWorkspaceLocations;
|
|
82
85
|
api.browseWorkspaceHostDirectories = locations.browseWorkspaceHostDirectories;
|
|
83
86
|
api.selectWorkspaceLocation = locations.selectWorkspaceLocation;
|
|
84
|
-
const host = createHostSessionProjects({ api, registry, services: () => ({ sessions: native.get('sessions') }), withHostBinding: locations.withHostBinding });
|
|
85
|
-
api.resolveSessionProject = host.resolve;
|
|
86
87
|
native.effect(() => { void locations.refreshWorkspaceLocations(); return api.onConnectionState(() => locations.observeConnection()); });
|
|
87
|
-
native.effect(() => () => {
|
|
88
|
+
native.effect(() => () => { delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; delete api.getWorkspaceDirectoryPickerSettings; delete api.browseWorkspaceDirectories; delete api.createWorkspaceDirectory; delete api.selectWorkspaceDirectory; return Promise.all([locations.dispose(), picker?.dispose()]); });
|
|
88
89
|
});
|
|
90
|
+
if (autoStart)
|
|
91
|
+
void api.refreshLoginPrompts();
|
|
89
92
|
}
|
package/lib/startup.js
CHANGED
|
@@ -13,12 +13,12 @@ export function employeeMessage(code, connection) {
|
|
|
13
13
|
if (code === 'ENROLLMENT_REQUIRED' || code === 'ENROLLMENT_INVALID' || code === 'NETWORK_KEY_INVALID')
|
|
14
14
|
return '我需要连接资料,请联系管理员发放。';
|
|
15
15
|
if (code === 'SETTINGS_REQUIRED')
|
|
16
|
-
return
|
|
16
|
+
return need(code).message;
|
|
17
17
|
if (code === 'LOGIN_FAILED')
|
|
18
18
|
return '登录没有完成。你可以再次请求登录,或稍后再试。';
|
|
19
19
|
if (code === 'POLICY_DENIED')
|
|
20
20
|
return '这个账号暂时不能使用,请联系公司账号管理员。';
|
|
21
|
-
return '
|
|
21
|
+
return '远程主机暂时连不上,请查看技术详情。';
|
|
22
22
|
}
|
|
23
23
|
export function createStartup(api, providers, emit = () => { }, result = () => { }, instanceId = randomUUID()) {
|
|
24
24
|
let disposed = false, revision = 0, serial = 0, generation = 0, checkSerial = 0, connectionPhase = 'unavailable', observedConnected = false, observedUnavailable = false;
|