@ai-workbench/connect 0.7.11 → 0.7.14
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 +28 -8
- package/helper/host-directories.cjs +72 -0
- package/lib/api.d.ts +23 -1
- package/lib/api.js +1 -1
- package/lib/components.d.ts +1 -1
- package/lib/components.js +80 -5
- package/lib/connect.d.ts +3 -0
- package/lib/connect.js +53 -11
- package/lib/connection-messages.d.ts +7 -0
- package/lib/connection-messages.js +6 -0
- package/lib/cordis.d.ts +2 -1
- package/lib/defaults.d.ts +6 -0
- package/lib/defaults.js +2 -0
- package/lib/host-directories.d.ts +53 -0
- package/lib/host-directories.js +76 -0
- package/lib/index.d.ts +8 -1
- package/lib/index.js +9 -4
- package/lib/integration.js +2 -0
- package/lib/local-workspace-context.d.ts +46 -0
- package/lib/local-workspace-context.js +17 -0
- package/lib/needs.js +12 -0
- package/lib/ports.d.ts +2 -0
- package/lib/profile-runtime.js +20 -3
- package/lib/startup.d.ts +1 -1
- package/lib/startup.js +33 -13
- package/lib/workspace-bindings.d.ts +30 -1
- package/lib/workspace-bindings.js +1 -0
- package/lib/workspace-location-types.d.ts +65 -0
- package/lib/workspace-location-types.js +1 -0
- package/lib/workspace-locations.d.ts +45 -0
- package/lib/workspace-locations.js +427 -0
- package/node_modules/argparse/CHANGELOG.md +216 -0
- package/package.json +4 -3
package/client/index.cjs
CHANGED
|
@@ -52,7 +52,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
52
52
|
"importInvalid": "这份连接资料无法通过检查,请向管理员领取有效的文件夹。",
|
|
53
53
|
"workspaceBlocked": "远程工作区暂时无法载入,请联系管理员。",
|
|
54
54
|
"workspaceSyncing": "正在更新远程工作区…",
|
|
55
|
-
"workspaceLimit": "
|
|
55
|
+
"workspaceLimit": "通过默认添加工作区选择本地文件夹,然后在本节明确选择本地或主机文件来源。本地文件不会自动上传。",
|
|
56
56
|
"unknown": "远程主机连接状态无法确认,请联系管理员。",
|
|
57
57
|
"checking": "正在检查远程主机连接…",
|
|
58
58
|
"details": "技术详情",
|
|
@@ -81,15 +81,17 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
81
81
|
const needKey=code=>code==='ENROLLMENT_RESULT_UNKNOWN'?'enrollmentUnknown':code==='ENROLLMENT_REJECTED'?'enrollmentRejected':code==='CONNECTION_UNKNOWN'?'unknown':code==='ENROLLMENT_INVALID'?'importInvalid':code==='DEPENDENCY_REQUIRED'?'notReady':['ENROLLMENT_REQUIRED','NETWORK_KEY_INVALID'].includes(code)?'enrollment':code==='SETTINGS_REQUIRED'?'settings':code==='LOGIN_FAILED'?'loginFailed':code==='POLICY_DENIED'?'denied':code==='LOGIN_PROMPT_INVALID'?'stale':code==='ACTION_FAILED'?'actionFailed':'unavailable';
|
|
82
82
|
function messageKey(s){if(!s||s.phase==='checking')return 'checking';if(s.phase==='blocked'||s.phase==='disposed')return needKey(s.technicalDetails?.code);if(s.phase==='login-required')return 'loginRequired';if(s.phase==='authorizing')return 'authorizing';return Object.keys(s.providerNeeds??{}).length?'loginUnknown':'complete';}
|
|
83
83
|
function createWorkbenchController(call,subscribe){
|
|
84
|
-
let state={value:undefined,error:''},disposed=false,started=false,off,revision=-1,instance,eventVersion=0;let download,componentSource;const retiredSources=new Set(),retiredDownloads=new Set(),retired=new Set(),listeners=new Set();
|
|
84
|
+
let state={value:undefined,error:''},disposed=false,started=false,off,revision=-1,instance,eventVersion=0;let download,componentSource,workspaceLocations;const retiredLocations=new Set();const retiredSources=new Set(),retiredDownloads=new Set(),retired=new Set(),listeners=new Set();
|
|
85
85
|
const publish=next=>{state=next;for(const fn of listeners)fn();};
|
|
86
|
-
const
|
|
86
|
+
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;};
|
|
87
|
+
const locationCall=async(path,body)=>{const before=state.value?.workspaceLocations;const result=await call('/workspace-locations/'+path,'POST',body);if(disposed)return result;if(result?.ok&&path!=='browse'&&state.value&&before?.instanceId===state.value.workspaceLocations?.instanceId&&before?.epoch===state.value.workspaceLocations?.epoch&&(path!=='select'||sameLocationContext(state.value.workspaceLocations,body))){const next=acceptLocations(result.value,'http');publish({...state,value:{...state.value,workspaceLocations:next}});}return result;};
|
|
88
|
+
const accept=(value,source='event')=>{if(disposed)return;const next=value?.startup?.revision,id=value?.startup?.instanceId;if(typeof id!=='string'||!id||!Number.isSafeInteger(next)||next<0){publish({value:undefined,error:'CONNECTION_UNKNOWN'});return;}if(id!==instance){if(instance&&(source==='http'||retired.has(id)))return;if(instance)retired.add(instance);instance=id;revision=-1;}if(next<revision)return;revision=next;const incoming=value.loginComponent?.download;if(incoming){if(typeof incoming.instanceId!=='string'||!Number.isSafeInteger(incoming.revision)||incoming.revision<0||retiredDownloads.has(incoming.instanceId)||(download&&incoming.instanceId===download.instanceId&&incoming.revision<download.revision)||(download&&incoming.instanceId!==download.instanceId&&source==='http')){value={...value,loginComponent:{...value.loginComponent,download}};}else{if(download&&incoming.instanceId!==download.instanceId)retiredDownloads.add(download.instanceId);download=incoming;}}const choice=value.loginComponent?.source;if(choice){if(typeof choice.instanceId!=='string'||!Number.isSafeInteger(choice.revision)||choice.revision<0||retiredSources.has(choice.instanceId)||(componentSource&&choice.instanceId===componentSource.instanceId&&choice.revision<componentSource.revision)||(componentSource&&choice.instanceId!==componentSource.instanceId&&source==='http')){if(componentSource)value={...value,loginComponent:{...value.loginComponent,source:componentSource}};}else{if(componentSource&&choice.instanceId!==componentSource.instanceId)retiredSources.add(componentSource.instanceId);componentSource=choice;}}if(value.workspaceLocations)value={...value,workspaceLocations:acceptLocations(value.workspaceLocations,source)};publish({value,error:value.actionErrorCode||value.enrollment?.need?.code||(value.actionError?'ACTION_FAILED':'')});};
|
|
87
89
|
const failure=()=>{if(!disposed)publish({value:undefined,error:'CONNECTION_UNKNOWN'});};
|
|
88
|
-
return {readLoginDiagnostics:query=>call('/login-diagnostics?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),readDetails:query=>call('/conversation-details?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}},start(){if(disposed||started)return;started=true;off=subscribe(value=>{eventVersion++;accept(value);},()=>{eventVersion++;failure();});const at=eventVersion;void call('/status','GET').then(value=>{if(at===eventVersion)accept(value,'http');},()=>{if(at===eventVersion)failure();});},dispose(){disposed=true;off?.();listeners.clear();}};
|
|
90
|
+
return {refreshWorkspaceLocations:()=>locationCall('refresh',{}),browseWorkspaceHostDirectories:body=>locationCall('browse',body),selectWorkspaceLocation:body=>locationCall('select',body),readLoginDiagnostics:query=>call('/login-diagnostics?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),readDetails:query=>call('/conversation-details?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}},start(){if(disposed||started)return;started=true;off=subscribe(value=>{eventVersion++;accept(value);},()=>{eventVersion++;failure();});const at=eventVersion;void call('/status','GET').then(value=>{if(at===eventVersion)accept(value,'http');},()=>{if(at===eventVersion)failure();});},dispose(){disposed=true;off?.();listeners.clear();}};
|
|
89
91
|
}
|
|
90
92
|
function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,action:workbench.action};}
|
|
91
93
|
function isLoginQuestion(state){const s=state?.startup;return s?.phase==='login-required'&&s.requestId&&s.provider&&s.logins?.[s.provider]===false&&!s.checkingProviders?.includes(s.provider)&&!s.providerNeeds?.[s.provider];}
|
|
92
|
-
function Details({state,error,t}){return h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({actionErrorCode:error||state?.actionErrorCode,enrollment:state?.enrollment,actionError:state?.actionError,inventory:state?.inventory,network:state?.network,connect:state?.connect,workspaces:state?.workspaces,checks:state?.startup?.technicalDetails,providerNeeds:state?.startup?.providerNeeds,queuedProviders:state?.startup?.queuedProviders,checkingProviders:state?.startup?.checkingProviders,loginComponent:state?.loginComponent},null,2)));}
|
|
94
|
+
function Details({state,error,t}){return h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({actionErrorCode:error||state?.actionErrorCode,enrollment:state?.enrollment,actionError:state?.actionError,inventory:state?.inventory,network:state?.network,connection:state?.connection,connectionMessageSettings:state?.connectionMessageSettings,connect:state?.connect,workspaces:state?.workspaces,checks:state?.startup?.technicalDetails,providerNeeds:state?.startup?.providerNeeds,queuedProviders:state?.startup?.queuedProviders,checkingProviders:state?.startup?.checkingProviders,loginComponent:state?.loginComponent},null,2)));}
|
|
93
95
|
function Choices({state,action,t}){if(!isLoginQuestion(state))return null;const brand=state.startup.provider==='claude'?'Claude':'Codex';return h('div',null,h('button',{type:'button',onClick:()=>void action('/respond/'+state.startup.requestId+'/authorize')},t('signIn',{brand})),h('button',{type:'button',onClick:()=>void action('/respond/'+state.startup.requestId+'/defer')},t('later')));}
|
|
94
96
|
function Enrollment({state,action,t}){const value=state?.enrollment;if(!value)return null;return h('div',null,h('p',null,t('importHelp')),value.phase==='imported'?h('p',null,t('imported')):h('button',{type:'button',disabled:value.phase==='importing'||['ENROLLMENT_RESULT_UNKNOWN','ENROLLMENT_REJECTED'].includes(value.need?.code),onClick:()=>void action('/enrollment/import')},t(value.phase==='importing'?'importing':'import')));}
|
|
95
97
|
function observeNotice(node,notify){
|
|
@@ -106,12 +108,30 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
106
108
|
}
|
|
107
109
|
function WorkspaceNotices({state,action}){
|
|
108
110
|
const [retained,setRetained]=React.useState([]),sent=React.useRef(new Set());
|
|
109
|
-
const pending=(state?.workspaceBindings?.items??[]).filter(item=>item.notice.settings==='pending'&&['ready','unavailable'].includes(item.status));
|
|
111
|
+
const pending=(state?.workspaceBindings?.items??[]).filter(item=>(!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed'))&&item.notice.settings==='pending'&&['ready','unavailable'].includes(item.status));
|
|
110
112
|
const items=[...retained,...pending.filter(item=>!retained.some(old=>old.notice.noticeId===item.notice.noticeId))];
|
|
111
113
|
// Retain each sentence during this opening after its independent durable ACK.
|
|
112
114
|
React.useEffect(()=>{if(pending.length)setRetained(old=>[...old,...pending.filter(item=>!old.some(prior=>prior.notice.noticeId===item.notice.noticeId))]);},[pending.map(item=>item.notice.noticeId).join(',')]);
|
|
113
115
|
const visible=item=>{if(!sent.current.has(item.notice.noticeId)){sent.current.add(item.notice.noticeId);void action('/workspace-notice/'+item.notice.noticeId+'/displayed');}};
|
|
114
|
-
return h('div',null,...items.map(item=>h(WorkspaceNoticeRow,{key:item.notice.noticeId,item,onVisible:visible})));
|
|
116
|
+
return h('div',null,...items.filter(item=>!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed')).map(item=>h(WorkspaceNoticeRow,{key:item.notice.noticeId,item,onVisible:visible})));
|
|
117
|
+
}
|
|
118
|
+
const sameLocationContext=(state,context)=>state?.instanceId===context.instanceId&&state?.epoch===context.epoch&&state.items?.some(item=>item.workspaceId===context.workspaceId&&item.bindingId===context.expectedBindingId);
|
|
119
|
+
function DirectoryPermissions({permissions}){return h('p',null,...['read','write','execute'].map((key,index)=>(index?';':'')+({read:'读取',write:'写入',execute:'进入'}[key])+':'+(permissions?.[key]===true?'允许':permissions?.[key]===false?'不允许':'未知')),permissions?.reason?'('+permissions.reason+')':'');}
|
|
120
|
+
function WorkspaceLocationRow({item,locations,workbench}){
|
|
121
|
+
const [page,setPage]=React.useState(null),[path,setPath]=React.useState(''),[pageSize,setPageSize]=React.useState(String(locations.pageSize)),[loading,setLoading]=React.useState(false),[error,setError]=React.useState('');
|
|
122
|
+
const live=React.useRef(true),sequence=React.useRef(0),context={instanceId:locations.instanceId,epoch:locations.epoch,workspaceId:item.workspaceId,expectedBindingId:item.bindingId};
|
|
123
|
+
React.useEffect(()=>()=>{live.current=false;sequence.current++;},[]);
|
|
124
|
+
const current=()=>live.current&&sameLocationContext(workbench.getSnapshot().value?.workspaceLocations,context);
|
|
125
|
+
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);}};
|
|
126
|
+
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);}};
|
|
127
|
+
const execution=item.execution==='local-pending'?'仅记录本地文件夹选择;D 本地执行尚未接通。':item.execution==='host-pending'?'主机文件夹已记录,等待 X 远程提供方接入位置合同后才能执行。':item.execution==='legacy-confirmed'?'已明确确认原有主机关联;继续使用原有执行入口。':'尚未选择文件来源。';
|
|
128
|
+
const identity=page?.host??item.host,host=identity?identity.username+'@'+identity.host+':'+identity.port:'主机标识尚未核实';
|
|
129
|
+
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,item.status==='legacy-confirmation-required'?h(React.Fragment,null,h('p',null,'此工作区有旧主机映射,必须明确确认;不会自动沿用。'),item.remote||item.legacyPath?h('p',null,'原有主机目录:'+(item.remote?.path??item.legacyPath)):null,h('button',{type:'button',disabled:loading,onClick:()=>select({source:'legacy-host',confirmLegacy:true})},'确认沿用旧主机关联')):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);
|
|
130
|
+
}
|
|
131
|
+
function WorkspaceLocations({state,workbench}){
|
|
132
|
+
const locations=state?.workspaceLocations,[error,setError]=React.useState(''),[refreshing,setRefreshing]=React.useState(false);if(!locations)return null;
|
|
133
|
+
const refresh=async()=>{setRefreshing(true);setError('');try{const result=await workbench.refreshWorkspaceLocations();if(!result?.ok)setError(result?.error?.message||'原生工作区列表读取失败。');}catch{setError('原生工作区列表读取失败,未自动重试。');}finally{setRefreshing(false);}};
|
|
134
|
+
return h('details',null,h('summary',null,'工作区文件来源'),h('p',null,'先通过默认添加工作区选择真实本地文件夹,再逐个明确选择来源;本节不替换原生目录选择器。没有默认来源。'),h('button',{type:'button',disabled:refreshing,onClick:refresh},'刷新原生工作区列表'),error?h('p',{role:'alert'},error):null,locations.phase!=='ready'?h('p',{role:'status'},locations.need?.message||'工作区位置尚未核实。'):locations.items.length?locations.items.map(item=>h(WorkspaceLocationRow,{key:JSON.stringify([locations.instanceId,locations.epoch,item.workspaceId,item.bindingId,item.source,item.localPath]),item,locations,workbench})):h('p',null,'当前没有原生工作区,请先通过默认添加工作区选择文件夹。'));
|
|
115
135
|
}
|
|
116
136
|
function ComponentSource({state,action}){const c=state?.loginComponent?.source;if(!c)return null;const busy=c.changing||c.phase!=='ready'||['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)||state?.startup?.phase==='authorizing';return h('div',null,h('p',null,c.phase==='ready'?'登录组件下载源:'+c.selectedLabel:c.phase==='loading'?'正在读取登录组件下载源设置…':'登录组件下载源设置不可用;未切换到其他来源。'),h('p',null,c.reason),c.selectionErrorCode?h('p',{role:'alert'},c.selectionErrorCode==='COMPONENT_PIN_MISMATCH'?'下载源未更改:当前组件版本或 SHA256 与预设不符,请查看技术详情。':'下载源未更改,请查看技术详情。'):null,...(c.choices??[]).map(choice=>h('button',{key:choice.id,type:'button',disabled:busy||c.selectedId===choice.id,onClick:()=>void action('/component-source/'+choice.id)},'使用 '+choice.label)),h('p',null,'Electron '+c.version+';两项预设使用同一固定 SHA256,不会因下载失败自动换源。'));}
|
|
117
137
|
function DownloadProgress({state,action}){const d=state?.loginComponent?.download;const [,refresh]=React.useState(0),interval=state?.loginComponent?.observationIntervalMs,observing=d?.phase==='downloading'&&Number.isFinite(d.lastProgressAt);React.useEffect(()=>{if(!observing||!Number.isSafeInteger(interval)||interval<1||interval>2147483647)return;const timer=setInterval(()=>refresh(x=>x+1),interval);return()=>clearInterval(timer);},[observing,interval,d?.attemptId]);if(!d)return null;const seconds=Number.isFinite(d.lastProgressAt)?Math.max(0,Math.floor((Date.now()-d.lastProgressAt)/1000)):null;const text=d.phase==='downloading'?'正在从'+(d.sourceLabel||'所选地址')+'下载登录组件:已下载 '+d.receivedBytes+' 字节'+(d.totalBytes===null?'(总大小未知)':',共 '+d.totalBytes+' 字节')+'。'+(seconds===null?'':'已 '+seconds+' 秒无进展;仅观察,不会自动重试或换源。')+'Claude、Codex 登录网页都使用本机网络;Codex 设备码需复制后粘贴到官方页面。':d.phase==='verifying'?'正在校验登录组件…':d.phase==='unpacking'?'正在解压登录组件…':d.phase==='failed'?'登录组件准备失败,请查看技术详情;未重试或换源。':d.phase==='cancelled'?'登录组件下载已取消。':null;return text?h(React.Fragment,null,h('p',{role:'status'},text),['downloading','verifying','unpacking'].includes(d.phase)&&d.attemptId?h('button',{type:'button',onClick:()=>void action('/component-download/cancel/'+d.attemptId)},'取消组件下载'):null):null;}
|
|
@@ -142,7 +162,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
142
162
|
const save=async()=>{const maxEventBytes=Number(max),pageSize=Number(size);if(!/^\d+$/.test(max)||!/^\d+$/.test(size)||![maxEventBytes,pageSize].every(n=>Number.isSafeInteger(n)&&n>0)){setError('设置未保存:两项都需要1至9007199254740991之间的整数。');return;}setError('');setSaving(true);try{await action('/conversation-detail-settings',{maxEventBytes,pageSize});}finally{setSaving(false);}};
|
|
143
163
|
return h('details',null,h('summary',null,'管理员设置'),h('p',null,'仅调整诊断记录。保存后即时生效,重开继续沿用本节保存值;已保存值优先于官方插件 Config 初值。未保存时使用 Config 或以下默认值。'),h('label',null,'conversationDetails.maxEventBytes',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:max,disabled,onChange:event=>setMax(event.target.value)})),h('p',null,'完整 UTF-8 JSON 事件字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小拒收超过新值的新事件,不裁剪、不删除已保存记录,也不阻止原事件的幂等核实。'),h('label',null,'conversationDetails.pageSize',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:size,disabled,onChange:event=>setSize(event.target.value)})),h('p',null,'一次详情页条数;默认100,范围1至9007199254740991整数。改大增加一次读取和界面负担;改小增加继续加载次数,不减少完整快照总数。'),h('p',null,'enrollmentMetadataMaxBytes 当前为 '+settings.metadataMaxBytes+' 字节(默认1048576),同时限制诊断设置文件与保存提交JSON;调小可能拒绝设置读取或保存,可在官方插件 Config 修改。'),h('p',null,'诊断记录不自动过期、不按条数淘汰、没有隐藏总条数上限;本版没有清除入口。'),h('p',null,settings.phase==='ready'?(settings.source==='saved'?'当前使用本节已保存设置。':'当前使用官方插件 Config 初值或默认值。'):settings.phase==='saving'?'正在保存设置…':'设置无法核实,未自动使用其他值;请联系管理员。'),error?h('p',{role:'alert'},error):null,settings.errorCode?h('p',{role:'alert'},'设置保存或读取失败:'+settings.errorCode):null,h('button',{type:'button',disabled,onClick:save},'保存诊断设置'));
|
|
144
164
|
}
|
|
145
|
-
function Panel({workbench,t}){const {state,error,action}=useWorkbench(workbench),message=messageKey(state?.startup),errorKey=error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)&&(!error||!!state?.startup)&&!(state?.enrollment?.phase==='blocked'&&state.enrollment.need);return h('section',{'aria-label':t('title')},h('h2',null,t('title')),h('p',null,t('loginNetworkBoundary')),h(ComponentSource,{state,action}),h(DownloadProgress,{state,action}),h(Enrollment,{state,action,t}),bodyVisible?h('p',{role:errorKey===message?'alert':undefined},t(message)):null,errorKey&&(!bodyVisible||errorKey!==message)?h('p',{role:'alert'},t(errorKey)):null,state?h(React.Fragment,null,...['codex','claude'].map(provider=>{const brand=provider==='claude'?'Claude':'Codex',checking=state.startup?.checkingProviders?.includes(provider),unknown=state.startup?.providerNeeds?.[provider]||state.startup?.logins?.[provider]===undefined;return h('div',{key:provider},h('p',null,t('provider',{brand})+': '+t(checking?'statusChecking':unknown?'statusUnknown':state.startup.logins[provider]?'statusSignedIn':'statusSignIn')),state.startup?.logins?.[provider]===false&&!checking&&!unknown&&(!isLoginQuestion(state)||state.startup.provider!==provider)?h('button',{type:'button',disabled:state.startup.phase==='authorizing',onClick:()=>void action('/start-login/'+provider+'/'+state.startup.instanceId+'/'+state.startup.revision)},t('signIn',{brand})):null);}),h(Choices,{state,action,t}),h(WorkspaceNotices,{state,action})
|
|
165
|
+
function Panel({workbench,t}){const {state,error,action}=useWorkbench(workbench),message=messageKey(state?.startup),connectionMessage=state?.connection?.recovery?.version===1?state.connection.recovery.message:undefined,errorKey=connectionMessage&&['CONNECTION_LOST','HOST_OFFLINE','SSH_FAILED'].includes(error)?undefined:error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)&&(!error||!!state?.startup)&&!(state?.enrollment?.phase==='blocked'&&state.enrollment.need);return h('section',{'aria-label':t('title')},h('h2',null,t('title')),h('p',null,t('loginNetworkBoundary')),h(ComponentSource,{state,action}),h(DownloadProgress,{state,action}),h(Enrollment,{state,action,t}),bodyVisible?h('p',{role:errorKey===message?'alert':undefined},connectionMessage??t(message)):null,errorKey&&(!bodyVisible||errorKey!==message)?h('p',{role:'alert'},t(errorKey)):null,state?h(React.Fragment,null,...['codex','claude'].map(provider=>{const brand=provider==='claude'?'Claude':'Codex',checking=state.startup?.checkingProviders?.includes(provider),unknown=state.startup?.providerNeeds?.[provider]||state.startup?.logins?.[provider]===undefined;return h('div',{key:provider},h('p',null,t('provider',{brand})+': '+t(checking?'statusChecking':unknown?'statusUnknown':state.startup.logins[provider]?'statusSignedIn':'statusSignIn')),state.startup?.logins?.[provider]===false&&!checking&&!unknown&&(!isLoginQuestion(state)||state.startup.provider!==provider)?h('button',{type:'button',disabled:state.startup.phase==='authorizing',onClick:()=>void action('/start-login/'+provider+'/'+state.startup.instanceId+'/'+state.startup.revision)},t('signIn',{brand})):null);}),h(Choices,{state,action,t}),h(WorkspaceNotices,{state,action}),!state.workspaceLocations?h('p',null,t('workspaceLimit')):null,...(state.workspaceBindings?.items??[]).filter(item=>item.notice.provider==='delivered'&&(!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed'))).map(item=>h('p',{key:'delivery-'+item.notice.noticeId},item.workspaceName+':首次说明已记入可核对回复。'))):null,h(WorkspaceLocations,{state,workbench}),h(RemoteConversationDetails,{state,workbench}),h(RemoteConversationDetails,{state,workbench,loginDiagnostics:true}),h(ConversationDetailSettings,{state,action}),h(Details,{state,error,t}),h('button',{type:'button',onClick:()=>void action()},t('recheck')));}
|
|
146
166
|
return {name:'ai-workbench-connect-client',inject:['slots','locale'],createWorkbenchController,Panel,dictionaries,observeNotice,apply(ctx){
|
|
147
167
|
ctx.effect(()=>ctx.locale.register(NS,dictionaries));const t=ctx.locale.bind(NS);
|
|
148
168
|
const workbench=createWorkbenchController(async(path,method,body)=>{const response=await fetch('/ai-workbench-connect'+path,{method,...body===undefined?{}:{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}});const value=await response.json();if(!response.ok&&!value?.startup&&typeof value?.ok!=='boolean')throw Error('connection-unavailable');return value;},(accept,failure)=>{const source=new EventSource('/ai-workbench-connect/events');source.onmessage=event=>{try{accept(JSON.parse(event.data));}catch{failure();}};source.onerror=failure;return()=>source.close();});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const fs=require('node:fs/promises');
|
|
2
|
+
const {constants}=require('node:fs');
|
|
3
|
+
const path=require('node:path');
|
|
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]));
|
|
7
|
+
const identity=stat=>({device:String(stat.dev),inode:String(stat.ino),mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
|
|
8
|
+
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
|
+
const binaryCompare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
|
|
11
|
+
const validPath=value=>typeof value==='string'&&path.isAbsolute(value)&&!value.includes('\0');
|
|
12
|
+
const invalid=()=>Object.assign(new Error('HOST_DIRECTORY_INVALID'),{directoryCode:'HOST_DIRECTORY_INVALID'});
|
|
13
|
+
const classify=exception=>exception?.directoryCode??(['EACCES','EPERM'].includes(exception?.code)?'HOST_DIRECTORY_UNREADABLE':'HOST_DIRECTORY_INVALID');
|
|
14
|
+
const unknownPermissions=()=>({read:null,write:null,execute:null,reason:'HOST_PERMISSION_UNKNOWN'});
|
|
15
|
+
async function permissions(target){
|
|
16
|
+
const result={};let unknown=false;
|
|
17
|
+
for(const [key,mode] of [['read',constants.R_OK],['write',constants.W_OK],['execute',constants.X_OK]]){
|
|
18
|
+
try{await fs.access(target,mode);result[key]=true;}catch(exception){result[key]=['EACCES','EPERM'].includes(exception?.code)?false:null;if(result[key]===null)unknown=true;}
|
|
19
|
+
}
|
|
20
|
+
if(unknown)result.reason='HOST_PERMISSION_UNKNOWN';return result;
|
|
21
|
+
}
|
|
22
|
+
async function observe(requestedPath){
|
|
23
|
+
const entry=await fs.lstat(requestedPath,{bigint:true});
|
|
24
|
+
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())throw invalid();
|
|
25
|
+
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
|
+
}
|
|
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
|
+
async function directoryEntry(requestedPath,name){
|
|
29
|
+
const entry=await fs.lstat(requestedPath,{bigint:true});if(!entry.isDirectory()&&!entry.isSymbolicLink())return null;
|
|
30
|
+
const base={name,requestedPath,entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink()};
|
|
31
|
+
try{
|
|
32
|
+
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())return null;
|
|
33
|
+
const access=await permissions(resolved);
|
|
34
|
+
return {...base,path:resolved,identity:identity(stat),permissions:access,...access.read!==true||access.execute!==true?{errorCode:'HOST_DIRECTORY_UNREADABLE'}:{}};
|
|
35
|
+
}catch(exception){return {...base,permissions:unknownPermissions(),errorCode:classify(exception)};}
|
|
36
|
+
}
|
|
37
|
+
async function execute(request){
|
|
38
|
+
if(request?.protocolVersion!==1||!['browse','inspect'].includes(request.operation))return error('PROJECT_PROTOCOL_INVALID');
|
|
39
|
+
if(!Number.isSafeInteger(request.maxOutputBytes)||request.maxOutputBytes<1)return error('HOST_DIRECTORY_INVALID');
|
|
40
|
+
if(request.path!==undefined&&!validPath(request.path))return error('HOST_DIRECTORY_INVALID');
|
|
41
|
+
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.expected!==undefined&&!validIdentity(request.expected)||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0')||!validIdentity(request.expected))))return error('HOST_DIRECTORY_INVALID');
|
|
43
|
+
const requestedPath=request.path??os.homedir();
|
|
44
|
+
try{
|
|
45
|
+
const before=await observe(requestedPath);
|
|
46
|
+
if(request.expected!==undefined&&!equal(before.identity,request.expected))return error('HOST_DIRECTORY_CHANGED');
|
|
47
|
+
let value=before;
|
|
48
|
+
if(request.operation==='browse'){
|
|
49
|
+
// Keep only the smallest pageSize+1 eligible names, independent of readdir order.
|
|
50
|
+
const window=[];
|
|
51
|
+
for await(const dirent of await fs.opendir(requestedPath)){
|
|
52
|
+
const name=dirent.name;if(request.after!==undefined&&binaryCompare(name,request.after)<=0)continue;
|
|
53
|
+
if(!dirent.isDirectory()&&!dirent.isSymbolicLink()&&(dirent.isFile()||dirent.isBlockDevice()||dirent.isCharacterDevice()||dirent.isFIFO()||dirent.isSocket()))continue;
|
|
54
|
+
if(window.length>request.pageSize&&binaryCompare(name,window[window.length-1].name)>=0)continue;
|
|
55
|
+
const entry=await directoryEntry(path.join(requestedPath,name),name);if(entry===null)continue;
|
|
56
|
+
let index=window.findIndex(item=>binaryCompare(name,item.name)<0);if(index===-1)index=window.length;window.splice(index,0,entry);if(window.length>request.pageSize+1)window.pop();
|
|
57
|
+
}
|
|
58
|
+
const hasMore=window.length>request.pageSize;if(hasMore)window.pop();value={...before,entries:window,...hasMore?{nextAfter:window[window.length-1].name}:{}};
|
|
59
|
+
}
|
|
60
|
+
let after;try{after=await observe(requestedPath);}catch{return error('HOST_DIRECTORY_CHANGED');}
|
|
61
|
+
if(!unchanged(before,after))return error('HOST_DIRECTORY_CHANGED');
|
|
62
|
+
const result={protocolVersion:1,ok:true,value};
|
|
63
|
+
return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
|
|
64
|
+
}catch(exception){return error(classify(exception));}
|
|
65
|
+
}
|
|
66
|
+
async function main(){
|
|
67
|
+
let input='';for await(const chunk of process.stdin)input+=chunk;
|
|
68
|
+
let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
|
|
69
|
+
process.stdout.write(JSON.stringify(result)+'\n');
|
|
70
|
+
}
|
|
71
|
+
module.exports={execute};
|
|
72
|
+
if(require.main===module)void main();
|
package/lib/api.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from './connection-messages.ts';
|
|
2
|
+
import type { WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
|
|
3
|
+
export type * from './workspace-location-types.ts';
|
|
4
|
+
import type { LocalWorkspaceContextRequest, LocalWorkspaceContext } from './local-workspace-context.ts';
|
|
5
|
+
export type { LocalWorkspaceContextRequest, LocalWorkspaceContext, LocalWorkspaceProcess } from './local-workspace-context.ts';
|
|
1
6
|
export type Provider = 'claude' | 'codex';
|
|
2
|
-
export type NeedCode = 'REMOTE_DETAIL_INVALID' | 'REMOTE_DETAIL_SCOPE_INVALID' | 'REMOTE_DETAIL_STORAGE_FAILED' | 'REMOTE_DETAIL_TOO_LARGE' | 'REMOTE_DETAIL_SEQUENCE_INVALID' | 'REMOTE_DETAIL_CONFLICT' | 'REMOTE_DETAIL_CURSOR_INVALID' | 'MODEL_CATALOG_CONTEXT_INVALID' | 'ACTIVATION_CONFLICT' | 'ACTIVATION_CANCELLED' | 'ENROLLMENT_CLEANUP_UNBOUND' | 'ENROLLMENT_CLEANUP_FAILED' | 'ENROLLMENT_MISMATCH' | 'LOCAL_STATE_INVALID' | 'ALREADY_RUNNING' | 'ENROLLMENT_RECEIPT_REQUIRED' | 'CONTROL_PROTOCOL_INVALID' | 'HELPER_HANDOFF_FAILED' | 'HELPER_SHUTDOWN_FORCED' | 'ENROLLMENT_RESULT_UNKNOWN' | 'ENROLLMENT_REJECTED' | 'ENROLLMENT_REQUIRED' | 'ENROLLMENT_INVALID' | 'NETWORK_KEY_INVALID' | 'HOST_OFFLINE' | 'EMPLOYEE_MISSING' | 'SSH_FAILED' | 'LOGIN_REQUIRED' | 'POLICY_DENIED' | 'CONNECTION_LOST' | 'DEPENDENCY_REQUIRED' | 'SETTINGS_REQUIRED' | 'AUTH_STATUS_INVALID' | 'LOGIN_FAILED' | 'LOGIN_PROMPT_INVALID' | 'DISPOSED' | 'HOST_TRUST_REQUIRED' | 'HOST_KEY_MISMATCH' | 'PROJECT_NAME_INVALID' | 'PROJECT_ROOT_INVALID' | 'PROJECT_EXISTS' | 'PROJECT_INIT_FAILED' | 'PROJECT_CREATE_FAILED' | 'PROJECT_LIST_FAILED' | 'PROJECT_PROTOCOL_INVALID' | 'PROJECT_BINDING_REQUIRED' | 'PROJECT_BINDING_INVALID' | 'PROJECT_BINDING_BUSY' | 'PROJECT_CREATE_UNKNOWN' | 'PROJECT_NOTICE_DELIVERY_UNKNOWN';
|
|
7
|
+
export type NeedCode = 'LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED' | 'LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE' | 'HOST_DIRECTORY_INVALID' | 'HOST_DIRECTORY_UNREADABLE' | 'HOST_DIRECTORY_CHANGED' | 'HOST_DIRECTORY_PAGE_TOO_LARGE' | 'WORKSPACE_LOCATION_REQUIRED' | 'WORKSPACE_LOCATION_INVALID' | 'WORKSPACE_LOCATION_CONFLICT' | 'WORKSPACE_LOCATION_PROVIDER_REQUIRED' | 'WORKSPACE_EXECUTION_UNAVAILABLE' | 'WORKSPACE_LOCATION_STORAGE_FAILED' | 'REMOTE_DETAIL_INVALID' | 'REMOTE_DETAIL_SCOPE_INVALID' | 'REMOTE_DETAIL_STORAGE_FAILED' | 'REMOTE_DETAIL_TOO_LARGE' | 'REMOTE_DETAIL_SEQUENCE_INVALID' | 'REMOTE_DETAIL_CONFLICT' | 'REMOTE_DETAIL_CURSOR_INVALID' | 'MODEL_CATALOG_CONTEXT_INVALID' | 'ACTIVATION_CONFLICT' | 'ACTIVATION_CANCELLED' | 'ENROLLMENT_CLEANUP_UNBOUND' | 'ENROLLMENT_CLEANUP_FAILED' | 'ENROLLMENT_MISMATCH' | 'LOCAL_STATE_INVALID' | 'ALREADY_RUNNING' | 'ENROLLMENT_RECEIPT_REQUIRED' | 'CONTROL_PROTOCOL_INVALID' | 'HELPER_HANDOFF_FAILED' | 'HELPER_SHUTDOWN_FORCED' | 'ENROLLMENT_RESULT_UNKNOWN' | 'ENROLLMENT_REJECTED' | 'ENROLLMENT_REQUIRED' | 'ENROLLMENT_INVALID' | 'NETWORK_KEY_INVALID' | 'HOST_OFFLINE' | 'EMPLOYEE_MISSING' | 'SSH_FAILED' | 'LOGIN_REQUIRED' | 'POLICY_DENIED' | 'CONNECTION_LOST' | 'DEPENDENCY_REQUIRED' | 'SETTINGS_REQUIRED' | 'AUTH_STATUS_INVALID' | 'LOGIN_FAILED' | 'LOGIN_PROMPT_INVALID' | 'DISPOSED' | 'HOST_TRUST_REQUIRED' | 'HOST_KEY_MISMATCH' | 'PROJECT_NAME_INVALID' | 'PROJECT_ROOT_INVALID' | 'PROJECT_EXISTS' | 'PROJECT_INIT_FAILED' | 'PROJECT_CREATE_FAILED' | 'PROJECT_LIST_FAILED' | 'PROJECT_PROTOCOL_INVALID' | 'PROJECT_BINDING_REQUIRED' | 'PROJECT_BINDING_INVALID' | 'PROJECT_BINDING_BUSY' | 'PROJECT_CREATE_UNKNOWN' | 'PROJECT_NOTICE_DELIVERY_UNKNOWN';
|
|
3
8
|
export interface ConnectNeed {
|
|
4
9
|
code: NeedCode;
|
|
5
10
|
layer: 'enrollment' | 'network' | 'ssh' | 'auth' | 'integration' | 'settings' | 'projects';
|
|
@@ -71,7 +76,15 @@ export interface ProjectList {
|
|
|
71
76
|
reason: 'invalid-name' | 'symlink' | 'not-directory' | 'permissions' | 'not-git' | 'invalid-git' | 'outside-root';
|
|
72
77
|
}[];
|
|
73
78
|
}
|
|
79
|
+
export interface ConnectionRecovery {
|
|
80
|
+
version: 1;
|
|
81
|
+
phase: 'reconnecting' | 'administrator-required';
|
|
82
|
+
message: '正在自动重连' | '请联系管理员';
|
|
83
|
+
startedAt: number;
|
|
84
|
+
administratorAfterMs: number;
|
|
85
|
+
}
|
|
74
86
|
export interface ConnectionState {
|
|
87
|
+
recovery?: ConnectionRecovery;
|
|
75
88
|
instanceId: string;
|
|
76
89
|
phase: 'connecting' | 'connected' | 'unavailable' | 'disposed';
|
|
77
90
|
epoch: number;
|
|
@@ -105,6 +118,9 @@ export interface ContractInfo {
|
|
|
105
118
|
workspaceBinding: 'native-local-v1';
|
|
106
119
|
remoteConversationDetails?: 1;
|
|
107
120
|
loginDiagnostics?: 1;
|
|
121
|
+
workspaceLocations?: 1;
|
|
122
|
+
connectionMessages?: 1;
|
|
123
|
+
localWorkspaceContext?: 1;
|
|
108
124
|
}
|
|
109
125
|
export interface WorkspaceUse {
|
|
110
126
|
provider: Provider;
|
|
@@ -224,6 +240,12 @@ export interface ModelCatalogTarget {
|
|
|
224
240
|
target: SshTarget;
|
|
225
241
|
}
|
|
226
242
|
export interface ConnectApi {
|
|
243
|
+
getLocalWorkspaceContext?(request: LocalWorkspaceContextRequest): Promise<Result<LocalWorkspaceContext>>;
|
|
244
|
+
getWorkspaceLocationState?(): WorkspaceLocationState;
|
|
245
|
+
onWorkspaceLocationState?(listener: (state: WorkspaceLocationState) => void): () => void;
|
|
246
|
+
refreshWorkspaceLocations?(): Promise<Result<WorkspaceLocationState>>;
|
|
247
|
+
browseWorkspaceHostDirectories?(request: WorkspaceBrowseRequest): Promise<Result<WorkspaceBrowsePage>>;
|
|
248
|
+
selectWorkspaceLocation?(request: WorkspaceSelectRequest): Promise<Result<WorkspaceLocationState>>;
|
|
227
249
|
appendLoginDiagnostic(detail: RemoteConversationDetail): Promise<Result<{
|
|
228
250
|
eventId: string;
|
|
229
251
|
recorded: true;
|
package/lib/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from "./connection-messages.js";
|
package/lib/components.d.ts
CHANGED
|
@@ -7,4 +7,4 @@ export interface ComponentInventory {
|
|
|
7
7
|
claude: string;
|
|
8
8
|
codex?: string;
|
|
9
9
|
}
|
|
10
|
-
export declare function registerComponents(ctx: Context, inventory?: ComponentInventory, temporaryDataParent?: string, component?: ComponentProgressStore, sources?: ComponentSources, observationIntervalMs?: number, metadataMaxBytes?: number): void;
|
|
10
|
+
export declare function registerComponents(ctx: Context, inventory?: ComponentInventory, temporaryDataParent?: string, component?: ComponentProgressStore, sources?: ComponentSources, observationIntervalMs?: number, metadataMaxBytes?: number, administratorAfterMs?: number): void;
|
package/lib/components.js
CHANGED
|
@@ -1,13 +1,40 @@
|
|
|
1
|
+
import { connectionEmployeeMessage } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
1
3
|
import { ComponentDownloadError } from "./component-download.js";
|
|
2
4
|
import { L_DEFAULTS } from "./defaults.js";
|
|
3
5
|
import { fail } from "./needs.js";
|
|
4
6
|
import { employeeMessage } from "./startup.js";
|
|
5
|
-
|
|
7
|
+
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
8
|
+
const text = (value) => typeof value === 'string' && value.length > 0 && !value.includes('\0');
|
|
9
|
+
function validLocationInput(operation, value) {
|
|
10
|
+
if (!record(value))
|
|
11
|
+
return false;
|
|
12
|
+
if (operation === 'refresh')
|
|
13
|
+
return Object.keys(value).length === 0;
|
|
14
|
+
const context = ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId'];
|
|
15
|
+
if (!text(value.instanceId) || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !text(value.workspaceId) || !(value.expectedBindingId === null || text(value.expectedBindingId)))
|
|
16
|
+
return false;
|
|
17
|
+
let extra;
|
|
18
|
+
if (operation === 'browse') {
|
|
19
|
+
extra = ['path', 'cursor', 'pageSize'];
|
|
20
|
+
if (value.path !== undefined && (!text(value.path) || !value.path.startsWith('/')) || value.cursor !== undefined && !text(value.cursor) || value.path !== undefined && value.cursor !== undefined || value.pageSize !== undefined && (!Number.isSafeInteger(value.pageSize) || value.pageSize < 1))
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
else if (operation === 'select') {
|
|
24
|
+
extra = value.source === 'local' ? ['source'] : value.source === 'host' ? ['source', 'selectionToken'] : value.source === 'legacy-host' ? ['source', 'confirmLegacy'] : [];
|
|
25
|
+
if (!extra.length || value.source === 'host' && !text(value.selectionToken) || value.source === 'legacy-host' && value.confirmLegacy !== true)
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
return false;
|
|
30
|
+
return Object.keys(value).every(key => [...context, ...extra].includes(key));
|
|
31
|
+
}
|
|
32
|
+
export function registerComponents(ctx, inventory, temporaryDataParent, component, sources, observationIntervalMs = L_DEFAULTS.componentObservationIntervalMs, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes, administratorAfterMs = CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs) {
|
|
6
33
|
const detailSettings = () => ctx.get('aiWorkbenchConversationDetailSettings');
|
|
7
34
|
const api = () => ctx.get('aiWorkbenchConnect');
|
|
8
35
|
const getState = () => {
|
|
9
36
|
const network = ctx.get('aiWorkbenchNetwork'), connect = api(), state = connect?.getState(), networkState = network?.getState();
|
|
10
|
-
return { loginDiagnostics: connect?.getLoginDiagnosticState?.() ?? null, conversationDetails: connect?.getRemoteConversationDetailState?.() ?? null, conversationDetailSettings: detailSettings() ? { ...detailSettings().getState(), metadataMaxBytes } : null, workspaceBindings: connect?.getWorkspaceBindingState?.() ?? null, loginComponent: { temporaryDataParent: temporaryDataParent ?? null, download: component?.getState() ?? null, source: sources?.getState() ?? null, observationIntervalMs }, startup: connect?.getLoginPromptState?.() ?? null, inventory: inventory ?? null, network: { serviceProvided: !!network, phase: networkState?.phase ?? 'missing', needCode: networkState?.error?.code ?? networkState?.need?.code }, enrollment: connect?.getEnrollmentState?.() ?? null, connection: connect?.getConnectionState?.() ?? null, connect: { serviceProvided: !!connect, phase: state?.phase ?? 'missing', message: state?.need ? employeeMessage(state.need.code) : '连接服务等待就绪' }, codex: inventory?.codex ? { installed: true, message: 'Codex 组件已安装' } : { installed: null, message: '组件清单未装配' } };
|
|
37
|
+
return { connectionMessageSettings: { administratorAfterMs }, workspaceLocations: connect?.getWorkspaceLocationState?.() ?? null, loginDiagnostics: connect?.getLoginDiagnosticState?.() ?? null, conversationDetails: connect?.getRemoteConversationDetailState?.() ?? null, conversationDetailSettings: detailSettings() ? { ...detailSettings().getState(), metadataMaxBytes } : null, workspaceBindings: connect?.getWorkspaceBindingState?.() ?? null, loginComponent: { temporaryDataParent: temporaryDataParent ?? null, download: component?.getState() ?? null, source: sources?.getState() ?? null, observationIntervalMs }, startup: connect?.getLoginPromptState?.() ?? null, inventory: inventory ?? null, network: { serviceProvided: !!network, phase: networkState?.phase ?? 'missing', needCode: networkState?.error?.code ?? networkState?.need?.code }, enrollment: connect?.getEnrollmentState?.() ?? null, connection: connect?.getConnectionState?.() ?? null, connect: { serviceProvided: !!connect, phase: state?.phase ?? 'missing', message: connectionEmployeeMessage(connect?.getConnectionState?.()) ?? (state?.need ? employeeMessage(state.need.code) : '连接服务等待就绪') }, codex: inventory?.codex ? { installed: true, message: 'Codex 组件已安装' } : { installed: null, message: '组件清单未装配' } };
|
|
11
38
|
};
|
|
12
39
|
ctx.provide('aiWorkbenchComponents', { getState });
|
|
13
40
|
ctx.inject(['webServer', 'connection'], host => {
|
|
@@ -28,9 +55,9 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
28
55
|
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
29
56
|
res.statusCode = 200;
|
|
30
57
|
let closed = false;
|
|
31
|
-
let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unnative = () => { }, undownload = () => { }, unsource = () => { }, undetails = () => { }, unloginDetails = () => { }, undetailsettings = () => { };
|
|
58
|
+
let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unnative = () => { }, undownload = () => { }, unsource = () => { }, undetails = () => { }, unloginDetails = () => { }, undetailsettings = () => { }, unlocations = () => { };
|
|
32
59
|
const close = () => { if (closed)
|
|
33
|
-
return; closed = true; unprompt(); unconnection(); unenrollment(); unnative(); undownload(); unsource(); undetails(); unloginDetails(); undetailsettings(); streams.delete(close); res.end(); };
|
|
60
|
+
return; closed = true; unprompt(); unconnection(); unenrollment(); unnative(); undownload(); unsource(); undetails(); unloginDetails(); undetailsettings(); unlocations(); streams.delete(close); res.end(); };
|
|
34
61
|
const send = () => { if (closed)
|
|
35
62
|
return; try {
|
|
36
63
|
if (!res.write('data: ' + JSON.stringify(getState()) + '\n\n'))
|
|
@@ -48,11 +75,59 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
48
75
|
undetails = service.onRemoteConversationDetailState?.(send) ?? (() => { });
|
|
49
76
|
unloginDetails = service.onLoginDiagnosticState?.(send) ?? (() => { });
|
|
50
77
|
undetailsettings = detailSettings()?.onState(send) ?? (() => { });
|
|
78
|
+
unlocations = service.onWorkspaceLocationState?.(send) ?? (() => { });
|
|
51
79
|
streams.add(close);
|
|
52
80
|
res.once('close', close);
|
|
53
81
|
send();
|
|
54
82
|
return;
|
|
55
83
|
}
|
|
84
|
+
if (req.method === 'POST' && /^\/ai-workbench-connect\/workspace-locations\/(refresh|browse|select)$/.test(path)) {
|
|
85
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
86
|
+
const invalid = () => { res.statusCode = 400; res.end(JSON.stringify(fail('WORKSPACE_LOCATION_INVALID'))); };
|
|
87
|
+
const operation = path.split('/').at(-1);
|
|
88
|
+
let body;
|
|
89
|
+
try {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
let bytes = 0;
|
|
92
|
+
if (!Number.isSafeInteger(metadataMaxBytes) || metadataMaxBytes < 1) {
|
|
93
|
+
invalid();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
for await (const chunk of req) {
|
|
97
|
+
const data = Buffer.from(chunk);
|
|
98
|
+
bytes += data.length;
|
|
99
|
+
if (bytes > metadataMaxBytes) {
|
|
100
|
+
invalid();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
chunks.push(data);
|
|
104
|
+
}
|
|
105
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
invalid();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (!validLocationInput(operation, body)) {
|
|
112
|
+
invalid();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!service || service.getContractInfo?.().workspaceLocations !== 1 || typeof service.refreshWorkspaceLocations !== 'function' || typeof service.browseWorkspaceHostDirectories !== 'function' || typeof service.selectWorkspaceLocation !== 'function') {
|
|
116
|
+
res.statusCode = 503;
|
|
117
|
+
res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED')));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const result = operation === 'refresh' ? await service.refreshWorkspaceLocations() : operation === 'browse' ? await service.browseWorkspaceHostDirectories(body) : await service.selectWorkspaceLocation(body);
|
|
122
|
+
res.statusCode = result.ok ? 200 : 409;
|
|
123
|
+
res.end(JSON.stringify(result));
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
res.statusCode = 503;
|
|
127
|
+
res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED')));
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
56
131
|
if (req.method === 'GET' && ['/ai-workbench-connect/login-diagnostics', '/ai-workbench-connect/login-diagnostic-receipt'].includes(path)) {
|
|
57
132
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
58
133
|
const unavailable = () => { res.statusCode = 503; res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED'))); };
|
|
@@ -203,7 +278,7 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
203
278
|
if (!result.ok) {
|
|
204
279
|
res.statusCode = 409;
|
|
205
280
|
actionErrorCode = result.error.code;
|
|
206
|
-
actionError = result.error.code === 'LOGIN_PROMPT_INVALID' ? result.error.message : employeeMessage(result.error.code);
|
|
281
|
+
actionError = result.error.code === 'LOGIN_PROMPT_INVALID' ? result.error.message : employeeMessage(result.error.code, service.getConnectionState());
|
|
207
282
|
}
|
|
208
283
|
}
|
|
209
284
|
else if (req.method !== 'GET' || path !== '/ai-workbench-connect/status') {
|
package/lib/connect.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ import type { ConnectApi, ConnectState, Provider, ConnectionState, LoginPromptSt
|
|
|
2
2
|
import type { Enrollment, Ports } from './ports.ts';
|
|
3
3
|
export declare function validEnrollment(e: Enrollment): boolean;
|
|
4
4
|
export interface ConnectOptions {
|
|
5
|
+
connectionMessages?: {
|
|
6
|
+
administratorAfterMs?: number;
|
|
7
|
+
};
|
|
5
8
|
providers?: Provider[];
|
|
6
9
|
onConnectionState?: (s: ConnectionState) => void;
|
|
7
10
|
onPromptState?: (s: LoginPromptState) => void;
|
package/lib/connect.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { CONNECTION_MESSAGES, connectionEmployeeMessage, isConnectionInterruption } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
1
3
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { dependency, fail, ok, need } from "./needs.js";
|
|
4
|
+
import { dependency, fail as baseFail, ok, need } from "./needs.js";
|
|
3
5
|
import { isProjectName } from "./projects.js";
|
|
4
6
|
import { createStartup } from "./startup.js";
|
|
5
7
|
import { parseLoginStatus } from "./auth-status.js";
|
|
@@ -20,41 +22,81 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
20
22
|
let connection = { instanceId, phase: 'unavailable', epoch: 0 };
|
|
21
23
|
const connectionListeners = new Set();
|
|
22
24
|
let startup;
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
+
const fail = (code) => { const result = baseFail(code), message = connectionEmployeeMessage(connection); if (!result.ok && message && isConnectionInterruption(code))
|
|
26
|
+
result.error.message = message; return result; };
|
|
27
|
+
const configuredAfterMs = options.connectionMessages?.administratorAfterMs;
|
|
28
|
+
const administratorAfterMs = configuredAfterMs === undefined ? CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs : configuredAfterMs;
|
|
29
|
+
const validMessageSettings = Number.isSafeInteger(administratorAfterMs) && administratorAfterMs >= 1 && administratorAfterMs <= 2147483647;
|
|
30
|
+
let recovery, recoveryTimer, recoverySerial = 0;
|
|
31
|
+
const stopRecovery = () => { recoverySerial++; if (recoveryTimer !== undefined)
|
|
32
|
+
clearTimeout(recoveryTimer); recoveryTimer = undefined; recovery = undefined; };
|
|
33
|
+
const setConnection = (phase, sourceNeed) => {
|
|
34
|
+
if (phase === 'connected' || phase === 'disposed' || phase === 'unavailable' && sourceNeed && !isConnectionInterruption(sourceNeed.code))
|
|
35
|
+
stopRecovery();
|
|
36
|
+
else if (phase === 'unavailable' && sourceNeed && isConnectionInterruption(sourceNeed.code) && !recovery && validMessageSettings) {
|
|
37
|
+
const mine = ++recoverySerial;
|
|
38
|
+
recovery = { version: 1, phase: 'reconnecting', message: CONNECTION_MESSAGES.reconnecting, startedAt: Date.now(), administratorAfterMs };
|
|
39
|
+
recoveryTimer = setTimeout(() => {
|
|
40
|
+
if (disposed || mine !== recoverySerial || !recovery)
|
|
41
|
+
return;
|
|
42
|
+
recoveryTimer = undefined;
|
|
43
|
+
recovery = { ...recovery, phase: 'administrator-required', message: CONNECTION_MESSAGES.administratorRequired };
|
|
44
|
+
setConnection(connection.phase, connection.need);
|
|
45
|
+
if (state.need && isConnectionInterruption(state.need.code))
|
|
46
|
+
publish({ ...state, need: { ...state.need, message: CONNECTION_MESSAGES.administratorRequired } });
|
|
47
|
+
}, administratorAfterMs);
|
|
48
|
+
recoveryTimer.unref?.();
|
|
49
|
+
}
|
|
50
|
+
const message = connectionEmployeeMessage({ recovery });
|
|
51
|
+
const next = { instanceId, phase, epoch: generation, ...(sourceNeed ? { need: { ...sourceNeed, ...(message ? { message } : {}) } } : {}), ...(recovery ? { recovery: structuredClone(recovery) } : {}) };
|
|
25
52
|
if (JSON.stringify(next) === JSON.stringify(connection))
|
|
26
53
|
return;
|
|
27
54
|
if (phase !== 'connected')
|
|
28
55
|
trustedTarget = undefined;
|
|
29
56
|
connection = structuredClone(next);
|
|
57
|
+
const publication = connection;
|
|
58
|
+
// 同步读取者在事件回调里也必须看到同一份员工话。
|
|
59
|
+
if (phase === 'unavailable' && next.need)
|
|
60
|
+
state = { phase: 'blocked', need: structuredClone(next.need) };
|
|
61
|
+
else if (message && state.need && isConnectionInterruption(state.need.code))
|
|
62
|
+
state = { ...state, need: { ...state.need, message } };
|
|
30
63
|
startup?.connectionChanged(next);
|
|
64
|
+
if (connection !== publication)
|
|
65
|
+
return;
|
|
31
66
|
options.onConnectionState?.(structuredClone(next));
|
|
32
|
-
|
|
67
|
+
if (connection !== publication)
|
|
68
|
+
return;
|
|
69
|
+
for (const listener of connectionListeners) {
|
|
70
|
+
if (connection !== publication)
|
|
71
|
+
return;
|
|
33
72
|
listener(structuredClone(next));
|
|
73
|
+
}
|
|
34
74
|
};
|
|
35
75
|
let controller = new AbortController();
|
|
36
76
|
const loginFlights = new Map();
|
|
37
77
|
const pending = new Set();
|
|
38
78
|
let disposal;
|
|
39
79
|
const track = (promise) => { pending.add(promise); void promise.then(() => pending.delete(promise), () => pending.delete(promise)); return promise; };
|
|
40
|
-
const publish = (s) => { state = structuredClone(s); emit(structuredClone(state)); };
|
|
80
|
+
const publish = (s) => { const message = connectionEmployeeMessage(connection); state = structuredClone(s.need && isConnectionInterruption(s.need.code) && message ? { ...s, need: { ...s.need, message } } : s); emit(structuredClone(state)); };
|
|
41
81
|
const invalid = (g) => disposed ? fail('DISPOSED') : g !== generation ? fail('CONNECTION_LOST') : undefined;
|
|
42
82
|
const block = (r) => { if (!r.ok && !disposed) {
|
|
43
|
-
publish({ phase: 'blocked', need: r.error });
|
|
44
83
|
if (connection.phase !== 'connected')
|
|
45
84
|
setConnection('unavailable', r.error);
|
|
46
|
-
|
|
85
|
+
publish({ phase: 'blocked', need: r.error });
|
|
86
|
+
} const message = connectionEmployeeMessage(connection); return !r.ok && message && isConnectionInterruption(r.error.code) ? { ok: false, error: { ...r.error, message } } : r; };
|
|
47
87
|
const transportBlock = (r) => { if (!r.ok && !disposed && connection.phase === 'connected') {
|
|
48
88
|
generation++;
|
|
49
89
|
controller.abort();
|
|
50
90
|
controller = new AbortController();
|
|
51
91
|
flight = undefined;
|
|
52
92
|
loginFlights.clear();
|
|
53
|
-
}
|
|
54
|
-
setConnection('unavailable', r.error); return
|
|
93
|
+
} if (!r.ok && !disposed)
|
|
94
|
+
setConnection('unavailable', r.error); return block(r); };
|
|
55
95
|
const connect = (reuseTrusted = false) => {
|
|
56
96
|
if (disposed)
|
|
57
97
|
return Promise.resolve(fail('DISPOSED'));
|
|
98
|
+
if (!validMessageSettings)
|
|
99
|
+
return Promise.resolve(block(fail('SETTINGS_REQUIRED')));
|
|
58
100
|
if ((state.target || reuseTrusted) && connection.phase === 'connected' && trustedTarget)
|
|
59
101
|
return Promise.resolve(ok(structuredClone(trustedTarget)));
|
|
60
102
|
if (flight)
|
|
@@ -251,8 +293,8 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
251
293
|
controller = new AbortController();
|
|
252
294
|
flight = undefined;
|
|
253
295
|
loginFlights.clear();
|
|
254
|
-
block(fail('CONNECTION_LOST'));
|
|
255
296
|
setConnection('unavailable', need('CONNECTION_LOST'));
|
|
297
|
+
block(fail('CONNECTION_LOST'));
|
|
256
298
|
}
|
|
257
299
|
else {
|
|
258
300
|
void connect();
|
|
@@ -280,7 +322,7 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
280
322
|
getRemoteConversationDetailReceipt: async () => dependency('官方会话存储与持久诊断记录'),
|
|
281
323
|
getRemoteConversationDetailState: () => ({ instanceId, epoch: connection.epoch, revision: 0, phase: disposed ? 'disposed' : 'unavailable', sessions: [], need: need(disposed ? 'DISPOSED' : 'DEPENDENCY_REQUIRED') }),
|
|
282
324
|
onRemoteConversationDetailState: () => () => { }, listRemoteConversationDetails: async () => dependency('官方会话存储与持久诊断记录'),
|
|
283
|
-
getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', workspaceBinding: 'native-local-v1' }),
|
|
325
|
+
getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', workspaceBinding: 'native-local-v1', connectionMessages: 1 }),
|
|
284
326
|
getEnrollmentState: () => ({ instanceId, revision: 0, phase: 'blocked', need: need('DEPENDENCY_REQUIRED') }), onEnrollmentState: () => () => { },
|
|
285
327
|
importEnrollment: async () => dependency('官方profileContext与原生目录选择服务'),
|
|
286
328
|
getWorkspaceBindingState: () => ({ instanceId, revision: 0, items: [] }), onWorkspaceBindingState: () => () => { }, acknowledgeWorkspaceNotice: async () => dependency('官方工作区说明回执'), resolveSessionProject: async () => dependency('官方会话存储与L可信工作区关联'),
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ConnectionState, NeedCode } from './api.ts';
|
|
2
|
+
export declare const CONNECTION_MESSAGES: Readonly<{
|
|
3
|
+
readonly reconnecting: "正在自动重连";
|
|
4
|
+
readonly administratorRequired: "请联系管理员";
|
|
5
|
+
}>;
|
|
6
|
+
export declare function connectionEmployeeMessage(state: Pick<ConnectionState, 'recovery'> | undefined): string | undefined;
|
|
7
|
+
export declare const isConnectionInterruption: (code: NeedCode) => boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export const CONNECTION_MESSAGES = Object.freeze({ reconnecting: '正在自动重连', administratorRequired: '请联系管理员' });
|
|
2
|
+
// 状态由L计时;消费方不按自己的时钟/品牌推断阶段。
|
|
3
|
+
export function connectionEmployeeMessage(state) {
|
|
4
|
+
return state?.recovery?.phase === 'reconnecting' ? CONNECTION_MESSAGES.reconnecting : state?.recovery?.phase === 'administrator-required' ? CONNECTION_MESSAGES.administratorRequired : undefined;
|
|
5
|
+
}
|
|
6
|
+
export const isConnectionInterruption = (code) => ['CONNECTION_LOST', 'HOST_OFFLINE', 'SSH_FAILED'].includes(code);
|
package/lib/cordis.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, WorkspaceBindingState, RemoteConversationDetailState } from './api.ts';
|
|
1
|
+
import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, WorkspaceBindingState, RemoteConversationDetailState, WorkspaceLocationState } from './api.ts';
|
|
2
2
|
declare module '@deepseek-ai/cordis' {
|
|
3
3
|
interface Context {
|
|
4
4
|
aiWorkbenchConnect: ConnectApi;
|
|
5
5
|
}
|
|
6
6
|
interface Events {
|
|
7
|
+
'ai-workbench/workspace-location-state': (state: WorkspaceLocationState) => void;
|
|
7
8
|
'ai-workbench/login-diagnostic-state': (state: RemoteConversationDetailState) => void;
|
|
8
9
|
'ai-workbench/remote-conversation-detail-state': (state: RemoteConversationDetailState) => void;
|
|
9
10
|
'ai-workbench/enrollment-state': (state: EnrollmentState) => void;
|
package/lib/defaults.d.ts
CHANGED
|
@@ -32,3 +32,9 @@ export declare const CONVERSATION_DETAIL_DEFAULTS: Readonly<{
|
|
|
32
32
|
maxEventBytes: 1048576;
|
|
33
33
|
pageSize: 100;
|
|
34
34
|
}>;
|
|
35
|
+
export declare const WORKSPACE_LOCATION_DEFAULTS: {
|
|
36
|
+
readonly pageSize: 100;
|
|
37
|
+
};
|
|
38
|
+
export declare const CONNECTION_MESSAGE_DEFAULTS: Readonly<{
|
|
39
|
+
administratorAfterMs: 30000;
|
|
40
|
+
}>;
|
package/lib/defaults.js
CHANGED
|
@@ -3,3 +3,5 @@ export const L_DEFAULTS = Object.freeze({ enrollmentMetadataMaxBytes: 1048576, c
|
|
|
3
3
|
export const ELECTRON_PIN = Object.freeze({ source: 'https://github.com/electron/electron/releases/download/v44.0.0/electron-v44.0.0-darwin-arm64.zip', sha256: '076d79742986e1b100b69ebecc691cb07368045e54c9087cef631b8622b76a80', executable: 'Electron.app/Contents/MacOS/Electron' });
|
|
4
4
|
export const NETWORK_DEFAULTS = Object.freeze({ proxyListen: '127.0.0.1:0', logUpload: false, statusRefreshIntervalSeconds: 2, dialTimeoutSeconds: 20, headerTimeoutSeconds: 10, enrollmentObservationSeconds: 30, httpMaxHeaderBytes: 1048576, httpMaxResponseHeaderBytes: 1048576, startupObservationSeconds: 35, shutdownObservationSeconds: 10, controlResponseMaxBytes: 65536, downloadMaxRedirects: 3 });
|
|
5
5
|
export const CONVERSATION_DETAIL_DEFAULTS = Object.freeze({ maxEventBytes: 1048576, pageSize: 100 });
|
|
6
|
+
export const WORKSPACE_LOCATION_DEFAULTS = { pageSize: 100 };
|
|
7
|
+
export const CONNECTION_MESSAGE_DEFAULTS = Object.freeze({ administratorAfterMs: 30000 });
|