@ai-workbench/connect 0.7.19 → 0.7.20

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 CHANGED
@@ -81,15 +81,21 @@ 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,workspaceLocations;const retiredLocations=new Set();const retiredSources=new Set(),retiredDownloads=new Set(),retired=new Set(),listeners=new Set();
84
+ let state={value:undefined,error:'',reconfirming:false},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 record=value=>!!value&&typeof value==='object'&&!Array.isArray(value);
87
+ const safeText=value=>typeof value==='string'&&value.length>0&&!/[\x00-\x1f\x7f]/.test(value);
88
+ 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));
89
+ const validLocationItem=item=>record(item)&&safeText(item.workspaceId)&&safeText(item.workspaceName)&&safeText(item.localPath)&&(item.bindingId===null||safeText(item.bindingId))&&[null,'local','host','legacy-host'].includes(item.source)&&['unselected','selected','legacy-confirmation-required','invalid'].includes(item.status)&&['not-selected','local-pending','host-pending','legacy-confirmed'].includes(item.execution);
90
+ 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);
91
+ 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));};
86
92
  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':'')});};
89
- const failure=()=>{if(!disposed)publish({value:undefined,error:'CONNECTION_UNKNOWN'});};
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();}};
93
+ const locationCall=async(path,body)=>{if(state.reconfirming)return {ok:false,error:{code:'CONNECTION_UNKNOWN',message:'正在重新确认,请先重新检查当前连接。'}};const before=state.value?.workspaceLocations,at=eventVersion;let result;try{result=await call('/workspace-locations/'+path,'POST',body);}catch(error){if(!disposed&&at===eventVersion)failure();throw error;}if(disposed)return result;if(result?.ok&&path!=='browse'&&!validLocations(result.value)){if(at===eventVersion)failure();return {ok:false,error:{code:'CONNECTION_UNKNOWN',message:'工作区位置快照无法核实,请重新检查当前连接。'}};}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;};
94
+ 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||!validSnapshot(value)){failure();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':''),reconfirming:false});};
95
+ const failure=()=>{if(!disposed)publish({...state,error:'CONNECTION_UNKNOWN',reconfirming:true});};
96
+ 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){if(state.reconfirming&&path!=='/check')return;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();}};
91
97
  }
92
- function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,action:workbench.action};}
98
+ function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,reconfirming:snapshot.reconfirming,action:workbench.action};}
93
99
  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];}
94
100
  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)));}
95
101
  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')));}
@@ -124,14 +130,14 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
124
130
  const current=()=>live.current&&sameLocationContext(workbench.getSnapshot().value?.workspaceLocations,context);
125
131
  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&&current())setError('主机目录读取失败,未自动重试。');}finally{if(at===sequence.current&&current())setLoading(false);}};
126
132
  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&&current())setError('位置保存结果无法确认,请刷新后核实;未自动重试。');}finally{if(at===sequence.current&&current())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:'主机标识尚未核实';
133
+ const execution=item.execution==='local-pending'?'已选择本机文件夹;运行前会核验本机执行条件。':item.execution==='host-pending'?'已选择主机文件夹;运行前会重新核对目录与权限。':item.execution==='legacy-confirmed'?'已明确确认原有主机关联;继续使用原有执行入口。':'尚未选择文件来源。';
134
+ const identity=locations.host,host=identity?identity.username+'@'+identity.host+':'+identity.port:'主机标识尚未核实';
129
135
  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
136
  }
131
137
  function WorkspaceLocations({state,workbench}){
132
138
  const locations=state?.workspaceLocations,[error,setError]=React.useState(''),[refreshing,setRefreshing]=React.useState(false);if(!locations)return null;
133
139
  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,'当前没有原生工作区,请先通过默认添加工作区选择文件夹。'));
140
+ return h('details',null,h('summary',null,'工作区文件来源'),h('p',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,'当前没有原生工作区,请先通过默认添加工作区选择文件夹。'));
135
141
  }
136
142
  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,不会因下载失败自动换源。'));}
137
143
  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'?(typeof d.errorCode==='string'&&d.errorCode.startsWith('COMPONENT_DOWNLOAD_TLS_')?'当前网络的安全证书验证失败,组件无法下载;请换个网络或联系网管。':'登录组件准备失败,请查看技术详情;未重试或换源。'):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;}
@@ -162,7 +168,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
162
168
  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);}};
163
169
  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},'保存诊断设置'));
164
170
  }
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,download=state?.loginComponent?.download,tlsFailure=download?.phase==='failed'&&typeof download.errorCode==='string'&&download.errorCode.startsWith('COMPONENT_DOWNLOAD_TLS_'),loginFailures=Object.values(state?.startup?.providerNeeds??{}).filter(need=>need?.code==='LOGIN_FAILED'),matchingTlsNeed=tlsFailure&&loginFailures.length>0&&loginFailures.every(need=>need.officialReason===download.errorCode),errorKey=matchingTlsNeed&&error==='LOGIN_FAILED'?undefined:connectionMessage&&['CONNECTION_LOST','HOST_OFFLINE','SSH_FAILED'].includes(error)?undefined:error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!(matchingTlsNeed&&message==='loginFailed')&&!['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')));}
171
+ function Panel({workbench,t}){const {state,error,reconfirming,action}=useWorkbench(workbench),message=messageKey(state?.startup),connectionMessage=state?.connection?.phase==='unavailable'&&state.connection.need?.message?state.connection.need.message:state?.connection?.recovery?.version===1?state.connection.recovery.message:undefined,download=state?.loginComponent?.download,tlsFailure=download?.phase==='failed'&&typeof download.errorCode==='string'&&download.errorCode.startsWith('COMPONENT_DOWNLOAD_TLS_'),loginFailures=Object.values(state?.startup?.providerNeeds??{}).filter(need=>need?.code==='LOGIN_FAILED'),matchingTlsNeed=tlsFailure&&loginFailures.length>0&&loginFailures.every(need=>need.officialReason===download.errorCode),errorKey=reconfirming?undefined:matchingTlsNeed&&error==='LOGIN_FAILED'?undefined:connectionMessage&&['CONNECTION_LOST','HOST_OFFLINE','SSH_FAILED'].includes(error)?undefined:error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!(matchingTlsNeed&&message==='loginFailed')&&!['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')),reconfirming?h('p',{role:'status'},'正在重新确认'):null,h('fieldset',{disabled:!!reconfirming,style:{border:0,padding:0,margin:0}},h('p',null,t('loginNetworkBoundary')),h(ComponentSource,{state,action}),h(DownloadProgress,{state,action}),h(Enrollment,{state,action,t}),bodyVisible&&(!reconfirming||!!state)?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')));}
166
172
  return {name:'ai-workbench-connect-client',inject:['slots','locale'],createWorkbenchController,Panel,dictionaries,observeNotice,apply(ctx){
167
173
  ctx.effect(()=>ctx.locale.register(NS,dictionaries));const t=ctx.locale.bind(NS);
168
174
  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();});
package/lib/api.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { LocalUserTurnAcceptanceRequest, LocalUserTurnAcceptance } from './local-user-turn-types.ts';
2
2
  export type { LocalUserTurnAcceptanceRequest, LocalUserTurnAcceptance } from './local-user-turn-types.ts';
3
3
  export { CONNECTION_MESSAGES, connectionEmployeeMessage } from './connection-messages.ts';
4
- import type { WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
+ import type { HostWorkspaceResolveContext, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
5
5
  export type * from './workspace-location-types.ts';
6
6
  import type { LocalWorkspaceContextRequest, LocalWorkspaceContext } from './local-workspace-context.ts';
7
7
  export type { LocalWorkspaceContextRequest, LocalWorkspaceContext, LocalWorkspaceProcess } from './local-workspace-context.ts';
@@ -126,6 +126,7 @@ export interface ContractInfo {
126
126
  localWorkspaceContext?: 1;
127
127
  modelCatalogTarget?: 1;
128
128
  localUserTurnAcceptance?: 1;
129
+ hostWorkspaceResolution?: 1;
129
130
  }
130
131
  export interface WorkspaceUse {
131
132
  provider: Provider;
@@ -147,6 +148,19 @@ export interface SessionProjectTarget {
147
148
  project: Project;
148
149
  target: SshTarget;
149
150
  notice?: WorkspaceNotice;
151
+ source?: 'legacy-host';
152
+ }
153
+ export interface HostSessionProjectTarget {
154
+ instanceId: string;
155
+ epoch: number;
156
+ bindingRevision: number;
157
+ bindingId: string;
158
+ sessionId: string;
159
+ workspaceId: string;
160
+ source: 'host';
161
+ directory: import('./host-directories.ts').HostDirectoryInfo;
162
+ project: Project;
163
+ target: SshTarget;
150
164
  }
151
165
  export interface WorkspaceBindingState {
152
166
  instanceId: string;
@@ -303,7 +317,7 @@ export interface ConnectApi {
303
317
  getWorkspaceBindingState(): WorkspaceBindingState;
304
318
  onWorkspaceBindingState(listener: (state: WorkspaceBindingState) => void): () => void;
305
319
  acknowledgeWorkspaceNotice(receipt: WorkspaceNoticeReceipt): Promise<Result<void>>;
306
- resolveSessionProject(sessionId: string, use: WorkspaceUse): Promise<Result<SessionProjectTarget>>;
320
+ resolveSessionProject(sessionId: string, use: WorkspaceUse, location?: HostWorkspaceResolveContext): Promise<Result<SessionProjectTarget | HostSessionProjectTarget>>;
307
321
  getConnectionState(): ConnectionState;
308
322
  onConnectionState(listener: (state: ConnectionState) => void): () => void;
309
323
  getLoginPromptState(): LoginPromptState;
@@ -1,3 +1,4 @@
1
+ import type { HostDetailsAdmission } from './host-session-projects.ts';
1
2
  import type { LocalDetailsAdmission } from './local-user-turn-acceptance.ts';
2
3
  import type { ConnectApi, ConnectionState, Provider, RemoteConversationDetail, RemoteConversationDetailState, Result } from './api.ts';
3
4
  export interface ConversationDetailOptions {
@@ -5,6 +6,7 @@ export interface ConversationDetailOptions {
5
6
  maxEventBytes: number;
6
7
  pageSize: number;
7
8
  localAcceptance?: LocalDetailsAdmission;
9
+ hostAcceptance?: HostDetailsAdmission;
8
10
  storageName?: 'conversation-details' | 'login-diagnostics';
9
11
  validate?: (detail: RemoteConversationDetail) => boolean;
10
12
  knownKinds?: readonly string[];
@@ -53,7 +53,8 @@ export function createConversationDetails(options) {
53
53
  const parent = join(options.profileDir, 'ai-workbench-connect'), root = join(parent, options.storageName ?? 'conversation-details');
54
54
  const valid = (detail) => validRemoteConversationDetail(detail) && (!options.validate || options.validate(detail));
55
55
  let disposed = false, uncertain = false, revision = 0, tail = Promise.resolve();
56
- const localRefs = new WeakMap();
56
+ const localRefs = new WeakMap(), hostRefs = new WeakMap();
57
+ const reference = (d) => hostRefs.has(d) ? ['host', hostRefs.get(d)] : localRefs.get(d) ?? null;
57
58
  let writeGuard, finalReadGuard;
58
59
  const recordGuards = new WeakMap();
59
60
  let snapshotGuards = [];
@@ -182,7 +183,7 @@ export function createConversationDetails(options) {
182
183
  if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || (st.mode & 0o777) !== 0o600)
183
184
  throw Error('DETAIL_RECORD_INVALID');
184
185
  const record = JSON.parse(await checked(h.readFile('utf8'), before));
185
- if (!validStored(record) || canonical(record.detail) !== canonical(detail) || (record.localAcceptanceId ?? undefined) !== localRefs.get(detail))
186
+ if (!validStored(record) || canonical(record.detail) !== canonical(detail) || (record.localAcceptanceId ?? undefined) !== localRefs.get(detail) || (record.hostBindingRef ?? undefined) !== hostRefs.get(detail))
186
187
  throw Error('DETAIL_RECORD_INVALID');
187
188
  await checked(h.sync(), before);
188
189
  }
@@ -219,6 +220,8 @@ export function createConversationDetails(options) {
219
220
  return false;
220
221
  if (raw.version === 1)
221
222
  return Object.keys(raw).sort().join(',') === 'detail,digest,version';
223
+ if (raw.version === 3)
224
+ return Object.keys(raw).sort().join(',') === 'detail,digest,hostBindingRef,scopeDigest,version' && text(raw.hostBindingRef) && raw.scopeDigest === digest(canonical(['host', raw.hostBindingRef, raw.detail]));
222
225
  return raw.version === 2 && Object.keys(raw).sort().join(',') === 'detail,digest,localAcceptanceId,scopeDigest,version' && text(raw.localAcceptanceId) && raw.scopeDigest === digest(canonical([raw.localAcceptanceId, raw.detail]));
223
226
  }
224
227
  async function rows(domain, before) {
@@ -237,6 +240,14 @@ export function createConversationDetails(options) {
237
240
  if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
238
241
  throw new NeedError(r.error);
239
242
  }
243
+ if (raw.version === 3) {
244
+ if (!options.hostAcceptance)
245
+ throw Error('DETAIL_HOST_CONTEXT_REQUIRED');
246
+ hostRefs.set(d, raw.hostBindingRef);
247
+ const r = await checked(options.hostAcceptance.readScope(d.sessionId, d.provider, raw.hostBindingRef, d, basename(domain)), before);
248
+ if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
249
+ throw new NeedError(r.error);
250
+ }
240
251
  ids.add(d.eventId);
241
252
  sequences.add(canonical([d.sessionId, d.provider, d.sequence]));
242
253
  items.push(d);
@@ -254,6 +265,13 @@ export function createConversationDetails(options) {
254
265
  async function readScope(sessionId, provider, before) {
255
266
  if (!text(sessionId) || !brand(provider))
256
267
  throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
268
+ if (options.hostAcceptance?.hasSession(sessionId)) {
269
+ const host = await checked(options.hostAcceptance.readScope(sessionId, provider), before);
270
+ if (!host.ok)
271
+ throw new NeedError(host.error);
272
+ finalReadGuard = host.value.guard;
273
+ return host.value.identity;
274
+ }
257
275
  const legacy = await checked(options.scope(sessionId, provider), before);
258
276
  const local = options.localAcceptance ? await checked(options.localAcceptance.readScope(sessionId, provider), before) : undefined;
259
277
  if (local && !local.ok && local.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
@@ -269,8 +287,19 @@ export function createConversationDetails(options) {
269
287
  }
270
288
  async function authorized(items, identity, sessionId, provider, before) {
271
289
  const selected = items.filter(d => d.sessionId === sessionId && d.provider === provider), result = [];
272
- const legacy = selected.some(d => !localRefs.has(d)) ? await checked(options.scope(sessionId, provider), before) : undefined;
290
+ const legacy = selected.some(d => !localRefs.has(d) && !hostRefs.has(d)) ? await checked(options.scope(sessionId, provider), before) : undefined;
273
291
  for (const d of selected) {
292
+ const hostRef = hostRefs.get(d);
293
+ if (hostRef) {
294
+ const r = await checked(options.hostAcceptance.readScope(sessionId, provider, hostRef, d, identity), before);
295
+ if (r.ok && r.value.identity === identity) {
296
+ recordGuards.set(d, { guard: r.value.guard, cacheGuard: r.value.cacheGuard });
297
+ result.push(d);
298
+ }
299
+ else if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
300
+ throw new NeedError(r.error);
301
+ continue;
302
+ }
274
303
  const ref = localRefs.get(d);
275
304
  if (ref) {
276
305
  const r = await checked(options.localAcceptance.readScope(sessionId, provider, ref, d, identity), before);
@@ -352,14 +381,16 @@ export function createConversationDetails(options) {
352
381
  const before = start();
353
382
  if (detail.instanceId !== before.instanceId || detail.epoch !== before.epoch)
354
383
  return fail('REMOTE_DETAIL_SCOPE_INVALID');
384
+ let admissionGuard;
355
385
  const write = async (proof) => {
386
+ admissionGuard = proof?.guard;
356
387
  writeGuard = proof?.guard;
357
388
  try {
358
389
  check(before);
359
390
  if (!Number.isSafeInteger(options.maxEventBytes) || options.maxEventBytes < 1)
360
391
  return fail('SETTINGS_REQUIRED');
361
392
  const identity = proof?.identity ?? await scope(detail.sessionId, detail.provider, before), domain = (await prepare(identity, before, true)), items = await rows(domain, before), existing = items.find(d => d.eventId === detail.eventId);
362
- if (existing && (canonical(existing) !== canonical(detail) || localRefs.get(existing) !== localId))
393
+ if (existing && (canonical(existing) !== canonical(detail) || localRefs.get(existing) !== localId || hostRefs.get(existing) !== proof?.hostBindingRef))
363
394
  return fail('REMOTE_DETAIL_CONFLICT');
364
395
  if (!existing && Buffer.byteLength(JSON.stringify(detail), 'utf8') > options.maxEventBytes)
365
396
  return fail('REMOTE_DETAIL_TOO_LARGE');
@@ -371,10 +402,12 @@ export function createConversationDetails(options) {
371
402
  const file = join(domain, digest(detail.eventId) + '.json');
372
403
  await key(before, true);
373
404
  if (!existing) {
374
- const envelope = localId ? { version: 2, localAcceptanceId: localId, scopeDigest: digest(canonical([localId, detail])) } : { version: 1 };
405
+ const envelope = proof?.hostBindingRef ? { version: 3, hostBindingRef: proof.hostBindingRef, scopeDigest: digest(canonical(['host', proof.hostBindingRef, detail])) } : localId ? { version: 2, localAcceptanceId: localId, scopeDigest: digest(canonical([localId, detail])) } : { version: 1 };
375
406
  await durable(file, JSON.stringify({ ...envelope, digest: digest(canonical(detail)), detail }) + '\n', before);
376
407
  if (localId)
377
408
  localRefs.set(detail, localId);
409
+ if (proof?.hostBindingRef)
410
+ hostRefs.set(detail, proof.hostBindingRef);
378
411
  items.push(detail);
379
412
  }
380
413
  else {
@@ -399,6 +432,16 @@ export function createConversationDetails(options) {
399
432
  writeGuard = undefined;
400
433
  }
401
434
  };
435
+ if (options.hostAcceptance?.hasSession(detail.sessionId)) {
436
+ if (localId)
437
+ return fail('REMOTE_DETAIL_SCOPE_INVALID');
438
+ const result = await options.hostAcceptance.withWrite(detail, write);
439
+ if (result.ok) {
440
+ admissionGuard?.();
441
+ check(before);
442
+ }
443
+ return !result.ok && result.error.code === 'REMOTE_DETAIL_STORAGE_FAILED' ? error(new NeedError(result.error)) : result;
444
+ }
402
445
  if (localId) {
403
446
  if (!options.localAcceptance)
404
447
  return fail('REMOTE_DETAIL_SCOPE_INVALID');
@@ -463,7 +506,7 @@ export function createConversationDetails(options) {
463
506
  const c = readCursor(q.cursor, secret);
464
507
  if (!c || typeof c !== 'object' || Array.isArray(c) || !['after,authorization,identity,provider,sessionId,upper,version', 'after,identity,provider,sessionId,upper,version'].includes(Object.keys(c).sort().join(',')) || c.version !== 1 || c.identity !== identity || c.sessionId !== q.sessionId || c.provider !== q.provider || !integer(c.upper) || !integer(c.after) || c.after > c.upper || !all.some(d => d.sequence === c.upper) || !all.some(d => d.sequence === c.after))
465
508
  return fail('REMOTE_DETAIL_CURSOR_INVALID');
466
- if (c.authorization === undefined ? all.some(d => d.sequence <= c.upper && localRefs.has(d)) : c.authorization !== digest(canonical(all.filter(d => d.sequence <= c.upper).map(d => [d.eventId, localRefs.get(d) ?? null]))))
509
+ if (c.authorization === undefined ? all.some(d => d.sequence <= c.upper && (localRefs.has(d) || hostRefs.has(d))) : c.authorization !== digest(canonical(all.filter(d => d.sequence <= c.upper).map(d => [d.eventId, reference(d)]))))
467
510
  return fail('REMOTE_DETAIL_CURSOR_INVALID');
468
511
  upper = c.upper;
469
512
  after = c.after;
@@ -474,7 +517,7 @@ export function createConversationDetails(options) {
474
517
  await stateRows(items, identity, before);
475
518
  if (await readScope(q.sessionId, q.provider, before) !== identity)
476
519
  return fail('REMOTE_DETAIL_SCOPE_INVALID');
477
- const value = { items: structuredClone(page), ...counts(bounded, options.knownKinds), ...(page.length < remaining.length ? { nextCursor: cursor({ version: 1, identity, sessionId: q.sessionId, provider: q.provider, upper, after: page.at(-1).sequence, authorization: digest(canonical(bounded.map(d => [d.eventId, localRefs.get(d) ?? null]))) }, secret) } : {}) };
520
+ const value = { items: structuredClone(page), ...counts(bounded, options.knownKinds), ...(page.length < remaining.length ? { nextCursor: cursor({ version: 1, identity, sessionId: q.sessionId, provider: q.provider, upper, after: page.at(-1).sequence, authorization: digest(canonical(bounded.map(d => [d.eventId, reference(d)]))) }, secret) } : {}) };
478
521
  finalReadGuard?.();
479
522
  check(before);
480
523
  return ok(value);
@@ -0,0 +1,71 @@
1
+ import type { ConnectApi, HostSessionProjectTarget, Provider, RemoteConversationDetail, Result, WorkspaceUse } from './api.ts';
2
+ import type { HostWorkspaceResolveContext, WorkspaceLocationState } from './workspace-location-types.ts';
3
+ import type { createWorkspaceLocations } from './workspace-locations.ts';
4
+ import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
5
+ interface Session {
6
+ header: Record<string, any>;
7
+ seq: number;
8
+ }
9
+ interface Event {
10
+ seq: number;
11
+ type: string;
12
+ data: any;
13
+ }
14
+ interface Services {
15
+ sessions: {
16
+ get(id: string): Session | undefined;
17
+ flush(session: Session): Promise<boolean>;
18
+ };
19
+ persistence: {
20
+ identity?: symbol;
21
+ open(id: string, access: 'read'): Promise<{
22
+ id: string;
23
+ access: string;
24
+ header: Record<string, any>;
25
+ inheritedEventCount: number;
26
+ read(): Promise<{
27
+ events: readonly Event[];
28
+ }>;
29
+ close(): Promise<void>;
30
+ }>;
31
+ };
32
+ }
33
+ interface Options {
34
+ profileDir: string;
35
+ metadataMaxBytes: number;
36
+ api: ConnectApi;
37
+ registry: NativeWorkspaceRegistry;
38
+ services: () => Services;
39
+ readHeader: (id: string) => Promise<any>;
40
+ readLegacy: () => Promise<{
41
+ sessionIds: string[];
42
+ }[]>;
43
+ context: () => Promise<Result<{
44
+ identity: string;
45
+ guard?: () => void;
46
+ }>>;
47
+ withHostBinding: ReturnType<typeof createWorkspaceLocations>['withHostBinding'];
48
+ }
49
+ export declare function changedSessionBinding(): never;
50
+ export declare function createHostSessionProjects(o: Options): {
51
+ active: () => boolean;
52
+ observe: (session: Session, event: Event) => void;
53
+ observeLocations: (state: WorkspaceLocationState) => void;
54
+ observeSessionDisposed: (session: Session) => void;
55
+ resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
56
+ readScope: (sessionId: string, provider: Provider, ref?: string, detail?: RemoteConversationDetail, expectedIdentity?: string) => Promise<Result<{
57
+ identity: string;
58
+ guard: () => void;
59
+ cacheGuard: () => void;
60
+ }>>;
61
+ withWrite: <T>(detail: RemoteConversationDetail, run: (proof: {
62
+ identity: string;
63
+ hostBindingRef: string;
64
+ guard: () => void;
65
+ }) => Promise<Result<T>>) => Promise<Result<T>>;
66
+ compatible: (id: string, header: any, source: "host" | "local" | "legacy-host", bindingId?: string) => void;
67
+ hasSession: (id: string) => boolean;
68
+ dispose(): void;
69
+ };
70
+ export type HostDetailsAdmission = ReturnType<typeof createHostSessionProjects>;
71
+ export {};
@@ -0,0 +1,291 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { basename } from 'node:path';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { acceptanceStore, canonical, sameSessionHeader, validHeader } from "./local-acceptance-store.js";
5
+ import { hostProjectStore } from "./host-session-store.js";
6
+ import { fail, ok, need, NeedError } from "./needs.js";
7
+ const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
8
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
9
+ function reject(code) { throw new NeedError(need(code)); }
10
+ export function changedSessionBinding() { const n = need('PROJECT_BINDING_INVALID'); n.message = '文件来源已改,请新建会话继续'; n.actor = 'employee'; n.requires = '新会话与当前文件来源'; n.action = { id: 'new-session', label: '新建会话继续', available: false }; throw new NeedError(n); }
11
+ const resultError = (e) => e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
12
+ export function createHostSessionProjects(o) {
13
+ const store = hostProjectStore(o.profileDir, o.metadataMaxBytes), local = acceptanceStore(o.profileDir, o.metadataMaxBytes), runtimeId = randomUUID(), observed = new WeakMap(), revisions = new Map(), blocked = new Set(), persistenceIdentity = o.services().persistence.identity;
14
+ let disposed = false, uncertain = false, uncertainRecordId;
15
+ function active() { if (o.services().persistence.identity !== persistenceIdentity)
16
+ disposed = true; return !disposed; }
17
+ function life(c) { const now = o.api.getConnectionState(); if (!active() || now.phase === 'disposed')
18
+ reject('DISPOSED'); if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
19
+ reject('CONNECTION_LOST'); }
20
+ function mapping(id, workspaceId) { const list = o.registry.list().filter(w => w.sessionIds.includes(id)), registered = o.registry.get(workspaceId); if (list.length !== 1 || list[0].id !== workspaceId || !registered || registered.path !== list[0].path || !registered.sessionIds.includes(id)) {
21
+ for (const r of store.read())
22
+ if (r.sessionId === id)
23
+ blocked.add(r.id);
24
+ changedSessionBinding();
25
+ } }
26
+ function compatible(id, header, source, bindingId) {
27
+ const existing = store.read().filter(r => r.sessionId === id && sameSessionHeader(r.header, header));
28
+ if (existing.some(r => source !== 'host' || r.bindingId !== bindingId))
29
+ changedSessionBinding();
30
+ }
31
+ function observe(session, event) {
32
+ if (!active() || o.services().sessions.get(session.header.id) !== session)
33
+ return;
34
+ if (event.type === 'turn/start')
35
+ observed.set(session, new Map([[event.seq, { seq: event.seq, type: event.type, data: { turn: event.data.turn } }]]));
36
+ else if (event.type === 'turn/end')
37
+ observed.delete(session);
38
+ else if (event.type === 'user/message' && event.data?.source?.kind === 'user')
39
+ observed.get(session)?.set(event.seq, { seq: event.seq, type: event.type, data: { id: event.data.id } });
40
+ }
41
+ function capture(id, use, c) {
42
+ if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
43
+ reject('PROJECT_BINDING_REQUIRED');
44
+ if (!c || Object.keys(c).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !text(c.instanceId) || !int(c.epoch) || !text(c.workspaceId) || !text(c.expectedBindingId))
45
+ reject('WORKSPACE_LOCATION_INVALID');
46
+ life(c);
47
+ const services = o.services(), session = services.sessions.get(id);
48
+ if (!session || !int(session.seq) || !validHeader(session.header) || session.header.id !== id)
49
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
50
+ const header = structuredClone(session.header), watermark = session.seq, proof = observed.get(session);
51
+ if (!proof || ![...proof.values()].some(e => e.type === 'user/message'))
52
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
53
+ const guard = () => { life(c); mapping(id, c.workspaceId); if (o.services().sessions.get(id) !== session || canonical(session.header) !== canonical(header) || session.seq !== watermark)
54
+ reject('LOCAL_USER_TURN_CHANGED'); };
55
+ guard();
56
+ return { services, session, header, watermark, proof, guard };
57
+ }
58
+ async function verify(c, provider, path, guard) {
59
+ if (typeof c.header.cwd !== 'string' || await realpath(c.header.cwd) !== path)
60
+ reject('WORKSPACE_LOCATION_INVALID');
61
+ guard();
62
+ if (!await c.services.sessions.flush(c.session))
63
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
64
+ guard();
65
+ const handle = await c.services.persistence.open(c.header.id, 'read');
66
+ let events = [], inherited = 0;
67
+ try {
68
+ guard();
69
+ if (handle.id !== c.header.id || handle.access !== 'read' || !sameSessionHeader(handle.header, c.header) || !int(handle.inheritedEventCount))
70
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
71
+ inherited = handle.inheritedEventCount;
72
+ events = (await handle.read()).events;
73
+ guard();
74
+ }
75
+ finally {
76
+ await handle.close();
77
+ }
78
+ guard();
79
+ if (!Array.isArray(events) || events.length < c.watermark || events.some((e, i) => e.seq !== i))
80
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
81
+ let start, step, input, route, routeContext;
82
+ for (const e of events.slice(0, c.watermark)) {
83
+ if (e.type === 'turn/start') {
84
+ start = e;
85
+ step = undefined;
86
+ input = undefined;
87
+ route = undefined;
88
+ routeContext = undefined;
89
+ }
90
+ else if (e.type === 'turn/end') {
91
+ start = undefined;
92
+ step = undefined;
93
+ input = undefined;
94
+ route = undefined;
95
+ routeContext = undefined;
96
+ }
97
+ else if (e.type === 'step/start')
98
+ step = e;
99
+ else if (e.type === 'step/end')
100
+ step = undefined;
101
+ else if (e.type === 'user/message' && start && e.data?.source?.kind === 'user' && c.proof.has(e.seq))
102
+ input = e;
103
+ else if (e.type === 'request/header')
104
+ route = e.data?.header?.config?.provider;
105
+ else if (e.type === 'request/context')
106
+ routeContext = e.data?.provider;
107
+ }
108
+ const expected = provider === 'claude' ? 'claude-code-workbench' : 'codex-remote';
109
+ if (!start || !step || !input || !int(start.data.turn) || step.data.turn !== start.data.turn || [start.seq, step.seq, input.seq].some(n => n < inherited) || !c.proof.has(start.seq) || c.proof.get(start.seq)?.data.turn !== start.data.turn || !text(input.data.id) || !c.proof.has(input.seq) || c.proof.get(input.seq)?.data.id !== input.data.id || route !== expected || routeContext !== undefined && routeContext !== expected)
110
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
111
+ }
112
+ function revoke(bindingId) { const items = store.read(); let changed = false; for (const r of items)
113
+ if (r.bindingId === bindingId && !r.revoked) {
114
+ r.revoked = true;
115
+ changed = true;
116
+ } if (changed) {
117
+ try {
118
+ store.save(items, () => { });
119
+ }
120
+ catch (e) {
121
+ uncertain = true;
122
+ throw e;
123
+ }
124
+ } }
125
+ async function resolve(id, use, input) {
126
+ let c, location, provider;
127
+ try {
128
+ location = structuredClone(input);
129
+ provider = use?.provider;
130
+ c = capture(id, structuredClone(use), location);
131
+ }
132
+ catch (e) {
133
+ return resultError(e);
134
+ }
135
+ try {
136
+ let commit = () => { c.guard(); };
137
+ const result = await o.withHostBinding(location, async (value, bindingGuard) => {
138
+ const context = await o.context();
139
+ c.guard();
140
+ bindingGuard();
141
+ if (!context.ok)
142
+ return context;
143
+ const guard = () => { c.guard(); context.value.guard?.(); bindingGuard(); };
144
+ guard();
145
+ compatible(id, c.header, 'host', location.expectedBindingId);
146
+ if (local.read().some(r => r.acceptance.sessionId === id && sameSessionHeader(r.header, c.header)) || (await o.readLegacy()).some(r => r.sessionIds.includes(id)))
147
+ changedSessionBinding();
148
+ guard();
149
+ const ready = await o.api.ensureReady(provider);
150
+ guard();
151
+ if (!ready.ok)
152
+ return ready;
153
+ if (canonical(ready.value) !== canonical(value.target))
154
+ reject('CONNECTION_LOST');
155
+ await verify(c, provider, value.local.path, guard);
156
+ guard();
157
+ commit = () => {
158
+ guard();
159
+ const items = store.read();
160
+ if (items.some(r => r.bindingId === location.expectedBindingId && r.revoked))
161
+ reject('HOST_DIRECTORY_CHANGED');
162
+ const existing = items.find(r => r.sessionId === id && r.provider === provider && sameSessionHeader(r.header, c.header) && r.bindingId === location.expectedBindingId && r.instanceId === location.instanceId && r.epoch === location.epoch && r.runtimeId === runtimeId);
163
+ if (uncertain && (!existing || existing.id !== uncertainRecordId))
164
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
165
+ if (existing) {
166
+ if (blocked.has(existing.id))
167
+ changedSessionBinding();
168
+ if (canonical(existing.header) !== canonical(c.header) || existing.identity !== context.value.identity || canonical(existing.local) !== canonical(value.local))
169
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
170
+ store.verify(existing, guard);
171
+ uncertain = false;
172
+ uncertainRecordId = undefined;
173
+ }
174
+ else {
175
+ const record = { id: randomUUID(), sessionId: id, provider, header: c.header, identity: context.value.identity, workspaceId: location.workspaceId, bindingId: location.expectedBindingId, instanceId: location.instanceId, epoch: location.epoch, runtimeId, local: value.local, directory: value.directory, revoked: false, key: '' };
176
+ items.push(record);
177
+ try {
178
+ store.save(items, guard);
179
+ }
180
+ catch (e) {
181
+ if (e instanceof NeedError)
182
+ throw e;
183
+ uncertain = true;
184
+ uncertainRecordId = record.id;
185
+ throw new NeedError(need('REMOTE_DETAIL_STORAGE_FAILED'));
186
+ }
187
+ }
188
+ guard();
189
+ };
190
+ guard();
191
+ return ok({ instanceId: location.instanceId, epoch: location.epoch, sessionId: id, workspaceId: location.workspaceId, bindingId: location.expectedBindingId, bindingRevision: value.revision, source: 'host', directory: structuredClone(value.directory), project: { name: basename(value.directory.path) || '/', path: value.directory.path }, target: structuredClone(value.target) });
192
+ }, () => commit());
193
+ if (result.ok)
194
+ c.guard();
195
+ if (!result.ok && ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE', 'WORKSPACE_LOCATION_INVALID'].includes(result.error.code))
196
+ revoke(location.expectedBindingId);
197
+ return result;
198
+ }
199
+ catch (e) {
200
+ return resultError(e);
201
+ }
202
+ }
203
+ async function readScope(sessionId, provider, ref, detail, expectedIdentity) {
204
+ try {
205
+ const before = o.api.getConnectionState();
206
+ life(before);
207
+ const items = store.read(), context = await o.context();
208
+ life(before);
209
+ if (!context.ok)
210
+ return context;
211
+ const live = o.services().sessions.get(sessionId), revision = revisions.get(sessionId) ?? 0, rawHeader = await o.readHeader(sessionId), header = rawHeader && structuredClone(rawHeader);
212
+ life(before);
213
+ context.value.guard?.();
214
+ const record = ref ? items.find(r => r.id === ref) : undefined;
215
+ if (ref && !record)
216
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
217
+ if (record && detail && (record.sessionId !== detail.sessionId || record.provider !== detail.provider || record.instanceId !== detail.instanceId || record.epoch !== detail.epoch || expectedIdentity !== undefined && record.identity !== expectedIdentity))
218
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
219
+ const admitted = (record ? [record] : items).filter(r => r.identity === context.value.identity && r.sessionId === sessionId && r.provider === provider && sameSessionHeader(r.header, header));
220
+ if (!admitted.length)
221
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
222
+ const guard = () => { life(before); context.value.guard?.(); const current = o.services().sessions.get(sessionId); if (revision !== (revisions.get(sessionId) ?? 0) || live && current !== live || current && canonical(current.header) !== canonical(header))
223
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); const now = store.read(); for (const r of admitted) {
224
+ const same = now.find(n => n.id === r.id);
225
+ if (!same || canonical({ ...same, revoked: false, key: '' }) !== canonical({ ...r, revoked: false, key: '' }))
226
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
227
+ } };
228
+ guard();
229
+ return ok({ identity: context.value.identity, guard, cacheGuard: () => { guard(); if (!live || o.services().sessions.get(sessionId) !== live)
230
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); } });
231
+ }
232
+ catch (e) {
233
+ return resultError(e);
234
+ }
235
+ }
236
+ async function withWrite(detail, run) {
237
+ try {
238
+ const before = o.api.getConnectionState();
239
+ life(before);
240
+ if (uncertain)
241
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
242
+ const r = store.read().find(r => r.sessionId === detail.sessionId && r.provider === detail.provider && r.instanceId === before.instanceId && r.epoch === before.epoch && r.runtimeId === runtimeId && !r.revoked && !blocked.has(r.id));
243
+ if (!r)
244
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
245
+ if (detail.instanceId !== r.instanceId || detail.epoch !== r.epoch)
246
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
247
+ const header = await o.readHeader(r.sessionId);
248
+ life(before);
249
+ if (canonical(header) !== canonical(r.header))
250
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
251
+ let finalGuard = () => life(before);
252
+ const result = await o.withHostBinding({ instanceId: r.instanceId, epoch: r.epoch, workspaceId: r.workspaceId, expectedBindingId: r.bindingId }, async (value, bindingGuard) => {
253
+ const context = await o.context();
254
+ life(before);
255
+ if (!context.ok)
256
+ return context;
257
+ if (context.value.identity !== r.identity)
258
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
259
+ const guard = () => { life(before); context.value.guard?.(); bindingGuard(); mapping(r.sessionId, r.workspaceId); const current = o.services().sessions.get(r.sessionId); if (!current || canonical(current.header) !== canonical(r.header))
260
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); if (canonical(value.local) !== canonical(r.local))
261
+ reject('WORKSPACE_LOCATION_INVALID'); const same = store.read().find(n => n.id === r.id); if (!same || canonical(same) !== canonical(r) || same.revoked)
262
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); };
263
+ guard();
264
+ finalGuard = guard;
265
+ return run({ identity: r.identity, hostBindingRef: r.id, guard });
266
+ }, () => finalGuard());
267
+ if (result.ok)
268
+ finalGuard();
269
+ if (!result.ok && ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE', 'WORKSPACE_LOCATION_INVALID'].includes(result.error.code))
270
+ revoke(r.bindingId);
271
+ return result;
272
+ }
273
+ catch (e) {
274
+ return resultError(e);
275
+ }
276
+ }
277
+ function observeLocations(state) { if (!active() || state.phase !== 'ready')
278
+ return; const items = store.read(), bindings = new Set(items.map(r => r.bindingId)); for (const binding of bindings) {
279
+ const r = items.find(r => r.bindingId === binding), item = state.items.find(i => i.workspaceId === r.workspaceId);
280
+ if (!item) {
281
+ if (!o.registry.get(r.workspaceId))
282
+ revoke(binding);
283
+ }
284
+ else if (item.bindingId !== binding || item.source !== 'host')
285
+ revoke(binding);
286
+ } }
287
+ function observeSessionDisposed(session) { for (const r of store.read())
288
+ if (r.sessionId === session.header.id && sameSessionHeader(r.header, session.header))
289
+ blocked.add(r.id); observed.delete(session); revisions.set(session.header.id, (revisions.get(session.header.id) ?? 0) + 1); }
290
+ return { active, observe, observeLocations, observeSessionDisposed, resolve, readScope, withWrite, compatible, hasSession: (id) => store.read().some(r => r.sessionId === id), dispose() { disposed = true; } };
291
+ }
@@ -0,0 +1,27 @@
1
+ import type { HostDirectoryInfo } from './host-directories.ts';
2
+ import type { Provider } from './api.ts';
3
+ export interface HostProjectRecord {
4
+ id: string;
5
+ sessionId: string;
6
+ provider: Provider;
7
+ header: Record<string, any>;
8
+ identity: string;
9
+ workspaceId: string;
10
+ bindingId: string;
11
+ instanceId: string;
12
+ epoch: number;
13
+ runtimeId: string;
14
+ local: {
15
+ path: string;
16
+ device: number;
17
+ inode: number;
18
+ };
19
+ directory: HostDirectoryInfo;
20
+ revoked: boolean;
21
+ key: string;
22
+ }
23
+ export declare function hostProjectStore(profile: string, maxBytes: number): {
24
+ read: () => HostProjectRecord[];
25
+ save: (items: HostProjectRecord[], guard: () => void) => void;
26
+ verify: (expected: HostProjectRecord, guard: () => void) => void;
27
+ };
@@ -0,0 +1,130 @@
1
+ import { constants, openSync, closeSync, fstatSync, lstatSync, readFileSync, writeFileSync, fsyncSync, renameSync, unlinkSync, realpathSync } from 'node:fs';
2
+ import { join, isAbsolute } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { canonical, hash, validHeader } from "./local-acceptance-store.js";
5
+ const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
7
+ function validRecord(r) {
8
+ if (!r || Object.keys(r).sort().join(',') !== 'bindingId,directory,epoch,header,id,identity,instanceId,key,local,provider,revoked,runtimeId,sessionId,workspaceId' || !['id', 'sessionId', 'workspaceId', 'bindingId', 'instanceId', 'runtimeId'].every(k => text(r[k])) || !['claude', 'codex'].includes(r.provider) || !int(r.epoch) || !validHeader(r.header) || r.header.id !== r.sessionId || !/^[a-f0-9]{64}$/.test(r.identity) || typeof r.revoked !== 'boolean' || r.key !== hash({ ...r, key: '' }))
9
+ return false;
10
+ const d = r.directory, l = r.local;
11
+ return l && Object.keys(l).sort().join(',') === 'device,inode,path' && typeof l.path === 'string' && isAbsolute(l.path) && int(l.device) && int(l.inode) && d && Object.keys(d).sort().join(',') === 'entryIdentity,identity,isSymlink,parentPath,path,permissions,requestedPath' && (d.parentPath === null || typeof d.parentPath === 'string' && isAbsolute(d.parentPath)) && typeof d.path === 'string' && isAbsolute(d.path) && typeof d.requestedPath === 'string' && isAbsolute(d.requestedPath) && d.identity && Object.keys(d.identity).sort().join(',') === 'ctimeNs,device,inode,mtimeNs' && ['device', 'inode'].every(k => typeof d.identity[k] === 'string' && /^\d+$/.test(d.identity[k])) && ['mtimeNs', 'ctimeNs'].every(k => typeof d.identity[k] === 'string' && /^-?\d+$/.test(d.identity[k])) && d.entryIdentity && Object.keys(d.entryIdentity).sort().join(',') === 'device,inode' && ['device', 'inode'].every(k => typeof d.entryIdentity[k] === 'string' && /^\d+$/.test(d.entryIdentity[k])) && typeof d.isSymlink === 'boolean' && d.permissions && Object.keys(d.permissions).every(k => ['read', 'write', 'execute', 'reason'].includes(k)) && ([d.permissions.read, d.permissions.write, d.permissions.execute].includes(null) ? d.permissions.reason === 'HOST_PERMISSION_UNKNOWN' : d.permissions.reason === undefined) && ['read', 'write', 'execute'].every(k => [true, false, null].includes(d.permissions[k]));
12
+ }
13
+ export function hostProjectStore(profile, maxBytes) {
14
+ const root = join(profile, 'ai-workbench-connect'), file = join(root, 'host-session-projects.json');
15
+ const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
16
+ throw Error('HOST_SESSION_DIRECTORY_INVALID'); };
17
+ function read() {
18
+ if (realpathSync(profile) !== profile)
19
+ throw Error('HOST_SESSION_PROFILE_INVALID');
20
+ try {
21
+ directory(root);
22
+ }
23
+ catch (e) {
24
+ if (e.code === 'ENOENT')
25
+ return [];
26
+ throw e;
27
+ }
28
+ let fd;
29
+ try {
30
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
31
+ }
32
+ catch (e) {
33
+ if (e.code === 'ENOENT')
34
+ return [];
35
+ throw e;
36
+ }
37
+ try {
38
+ const st = fstatSync(fd);
39
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
40
+ throw Error('HOST_SESSION_FILE_INVALID');
41
+ const bytes = readFileSync(fd);
42
+ if (bytes.length > maxBytes)
43
+ throw Error('HOST_SESSION_LIMIT');
44
+ const data = JSON.parse(bytes.toString('utf8'));
45
+ if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
46
+ throw Error('HOST_SESSION_FORMAT_INVALID');
47
+ const ids = new Set();
48
+ for (const r of data.items) {
49
+ if (!validRecord(r) || ids.has(r.id))
50
+ throw Error('HOST_SESSION_RECORD_INVALID');
51
+ ids.add(r.id);
52
+ }
53
+ return data.items;
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ }
59
+ function save(items, guard) {
60
+ directory(root);
61
+ for (const r of items)
62
+ r.key = hash({ ...r, key: '' });
63
+ const bytes = JSON.stringify({ version: 1, items }) + '\n';
64
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
65
+ throw Error('HOST_SESSION_LIMIT');
66
+ const temp = join(root, '.host-session-' + randomUUID());
67
+ let created = false;
68
+ try {
69
+ const fd = openSync(temp, 'wx', 0o600);
70
+ created = true;
71
+ try {
72
+ writeFileSync(fd, bytes);
73
+ fsyncSync(fd);
74
+ }
75
+ finally {
76
+ closeSync(fd);
77
+ }
78
+ guard();
79
+ renameSync(temp, file);
80
+ created = false;
81
+ for (const path of [root, profile]) {
82
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
83
+ try {
84
+ fsyncSync(d);
85
+ }
86
+ finally {
87
+ closeSync(d);
88
+ }
89
+ }
90
+ }
91
+ finally {
92
+ if (created)
93
+ unlinkSync(temp);
94
+ }
95
+ }
96
+ function verify(expected, guard) {
97
+ directory(root);
98
+ if (realpathSync(profile) !== profile)
99
+ throw Error('HOST_SESSION_PROFILE_INVALID');
100
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
101
+ try {
102
+ const st = fstatSync(fd);
103
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
104
+ throw Error('HOST_SESSION_FILE_INVALID');
105
+ const bytes = readFileSync(fd);
106
+ if (bytes.length > maxBytes)
107
+ throw Error('HOST_SESSION_LIMIT');
108
+ const data = JSON.parse(bytes.toString('utf8'));
109
+ if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
110
+ throw Error('HOST_SESSION_CHANGED');
111
+ guard();
112
+ fsyncSync(fd);
113
+ }
114
+ finally {
115
+ closeSync(fd);
116
+ }
117
+ for (const path of [root, profile]) {
118
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
119
+ try {
120
+ guard();
121
+ fsyncSync(d);
122
+ }
123
+ finally {
124
+ closeSync(d);
125
+ }
126
+ }
127
+ guard();
128
+ }
129
+ return { read, save, verify };
130
+ }
@@ -31,6 +31,8 @@ interface Services {
31
31
  };
32
32
  }
33
33
  interface Options {
34
+ assertPriorBinding?: (sessionId: string, header: Record<string, any>, bindingId: string) => Promise<void>;
35
+ assertSessionBinding?: (sessionId: string, header: Record<string, any>, source: 'local', bindingId: string) => void;
34
36
  profileDir: string;
35
37
  metadataMaxBytes: number;
36
38
  registry: NativeWorkspaceRegistry;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { acceptanceStore, canonical, validHeader, sameSessionHeader } from "./local-acceptance-store.js";
3
+ import { changedSessionBinding } from "./host-session-projects.js";
3
4
  import { fail, ok, need, NeedError } from "./needs.js";
4
5
  const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
5
6
  const int = (v) => Number.isSafeInteger(v) && v >= 0;
@@ -65,9 +66,14 @@ export function createLocalUserTurnAcceptance(o) {
65
66
  let items = [];
66
67
  try {
67
68
  c.guard();
69
+ await o.assertPriorBinding?.(r.sessionId, c.header, r.expectedBindingId);
70
+ c.guard();
71
+ o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId);
68
72
  if (uncertain)
69
73
  reject('REMOTE_DETAIL_STORAGE_FAILED');
70
74
  items = store.read();
75
+ if (items.some(v => v.acceptance.sessionId === r.sessionId && sameSessionHeader(v.header, c.header) && v.acceptance.bindingId !== r.expectedBindingId))
76
+ changedSessionBinding();
71
77
  const context = await o.context();
72
78
  c.guard();
73
79
  if (!context.ok)
@@ -75,7 +81,7 @@ export function createLocalUserTurnAcceptance(o) {
75
81
  const identity = context.value.identity;
76
82
  const result = await o.withLocalBinding(r, async (directory, bindingGuard) => {
77
83
  try {
78
- const guard = () => { c.guard(); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
84
+ const guard = () => { c.guard(); o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
79
85
  reject('REMOTE_DETAIL_SCOPE_INVALID'); };
80
86
  guard();
81
87
  // Canonical session cwd must be the selected official directory; no basename/host mapping.
@@ -7,6 +7,9 @@ import { NeedError, need, fail } from "./needs.js";
7
7
  import { createNativeImportPicker } from "./native-import-picker.js";
8
8
  import { createHash } from 'node:crypto';
9
9
  import { readPrivate, readPrivateSync } from "./private-files.js";
10
+ import { hostProjectStore } from "./host-session-store.js";
11
+ import { acceptanceStore, sameSessionHeader } from "./local-acceptance-store.js";
12
+ import { createHostSessionProjects, changedSessionBinding } from "./host-session-projects.js";
10
13
  import { createLocalUserTurnAcceptance } from "./local-user-turn-acceptance.js";
11
14
  import { createConversationDetails } from "./conversation-details.js";
12
15
  import { createLoginDiagnostics } from "./login-diagnostics.js";
@@ -92,7 +95,19 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
92
95
  }
93
96
  };
94
97
  const nativeSessions = native.get('sessions'), nativePersistence = native.get('sessionPersistence');
95
- const localAcceptance = process.platform === 'darwin' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createLocalUserTurnAcceptance({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, registry, getConnectionState: api.getConnectionState, readHeader, context, withLocalBinding: locations.withLocalBinding,
98
+ const hostLedger = hostProjectStore(profile.dir, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes), localLedger = acceptanceStore(profile.dir, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
99
+ const assertHostBinding = (id, header) => { if (hostLedger.read().some(r => r.sessionId === id && sameSessionHeader(r.header, header)))
100
+ changedSessionBinding(); };
101
+ const officialServices = () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') });
102
+ const hostAcceptance = typeof ports.hostDirectories?.inspect === 'function' && typeof ports.hostDirectories?.browse === 'function' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createHostSessionProjects({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, api, registry, services: officialServices, readHeader, readLegacy: bindings.readLegacyLocations, context, withHostBinding: locations.withHostBinding }) : undefined;
103
+ if (hostAcceptance) {
104
+ native.on('session/event', (session, event) => hostAcceptance.observe(session, event));
105
+ native.on('session/disposed', (session) => hostAcceptance.observeSessionDisposed(session));
106
+ native.effect(() => locations.onWorkspaceLocationState(hostAcceptance.observeLocations));
107
+ native.effect(() => () => hostAcceptance.dispose());
108
+ }
109
+ const localAcceptance = process.platform === 'darwin' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createLocalUserTurnAcceptance({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, registry, getConnectionState: api.getConnectionState, readHeader, context, assertSessionBinding: assertHostBinding, assertPriorBinding: async (id) => { if ((await bindings.readLegacyLocations()).some(r => r.sessionIds.includes(id)))
110
+ changedSessionBinding(); }, withLocalBinding: locations.withLocalBinding,
96
111
  // SessionStore proxies are not instance IDs. Check the exact live Session and
97
112
  // SessionPersistence's public stable identity, plus the injected lifetime.
98
113
  services: () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') }) }) : undefined;
@@ -105,7 +120,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
105
120
  delete api.acceptLocalWorkspaceUserTurn; });
106
121
  }
107
122
  const details = createConversationDetails({ profileDir: profile.dir, get maxEventBytes() { return settings ? settings.values()?.maxEventBytes ?? 0 : config.conversationDetails?.maxEventBytes ?? CONVERSATION_DETAIL_DEFAULTS.maxEventBytes; }, get pageSize() { return settings ? settings.values()?.pageSize ?? 0 : config.conversationDetails?.pageSize ?? CONVERSATION_DETAIL_DEFAULTS.pageSize; }, getConnectionState: api.getConnectionState,
108
- context, localAcceptance,
123
+ context, localAcceptance, hostAcceptance,
109
124
  scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
110
125
  return current; return bindings.verifyRemoteConversationScope(sessionId, provider, current.value.target); },
111
126
  onState: state => ctx.emit('ai-workbench/remote-conversation-detail-state', state) });
@@ -140,7 +155,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
140
155
  api.listLoginDiagnostics = loginDiagnostics.listLoginDiagnostics;
141
156
  api.getLoginDiagnosticState = loginDiagnostics.getLoginDiagnosticState;
142
157
  api.onLoginDiagnosticState = loginDiagnostics.onLoginDiagnosticState;
143
- const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(api.getConnectionState().phase !== 'disposed' ? { preflightDiagnostics: 1 } : {}), ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1, ...(localAcceptance?.active() ? { localUserTurnAcceptance: 1 } : {}) } : {}) });
158
+ const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(hostAcceptance?.active() && api.getConnectionState().phase !== 'disposed' ? { hostWorkspaceResolution: 1 } : {}), ...(api.getConnectionState().phase !== 'disposed' ? { preflightDiagnostics: 1 } : {}), ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1, ...(localAcceptance?.active() ? { localUserTurnAcceptance: 1 } : {}) } : {}) });
144
159
  api.getContractInfo = detailContractInfo;
145
160
  native.effect(() => { details.observeConnection(api.getConnectionState()); return api.onConnectionState(details.observeConnection); });
146
161
  native.effect(() => { loginDiagnostics.observeConnection(api.getConnectionState()); return api.onConnectionState(loginDiagnostics.observeConnection); });
@@ -150,7 +165,17 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
150
165
  api.getWorkspaceBindingState = bindings.getWorkspaceBindingState;
151
166
  api.onWorkspaceBindingState = bindings.onWorkspaceBindingState;
152
167
  api.acknowledgeWorkspaceNotice = bindings.acknowledgeWorkspaceNotice;
153
- api.resolveSessionProject = (sessionId, use) => locations.resolveLegacySession(sessionId, () => bindings.resolveSessionProject(sessionId, use));
168
+ api.resolveSessionProject = (sessionId, use, location) => { if (location !== undefined)
169
+ return hostAcceptance ? hostAcceptance.resolve(sessionId, use, location) : Promise.resolve(fail('DEPENDENCY_REQUIRED')); return locations.resolveLegacySession(sessionId, async () => { try {
170
+ const header = await readHeader(sessionId);
171
+ assertHostBinding(sessionId, header);
172
+ if (localLedger.read().some(r => r.acceptance.sessionId === sessionId && sameSessionHeader(r.header, header)))
173
+ changedSessionBinding();
174
+ return bindings.resolveSessionProject(sessionId, use);
175
+ }
176
+ catch (e) {
177
+ return e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
178
+ } }); };
154
179
  native.effect(() => () => { api.resolveSessionProject = async () => fail('DEPENDENCY_REQUIRED'); api.acknowledgeWorkspaceNotice = async () => fail('DEPENDENCY_REQUIRED'); return bindings.dispose(); });
155
180
  });
156
181
  }
@@ -17,7 +17,15 @@ export interface WorkspaceLocationItem {
17
17
  };
18
18
  need?: ConnectNeed;
19
19
  }
20
+ export interface HostWorkspaceResolveContext extends WorkspaceLocationContext {
21
+ expectedBindingId: string;
22
+ }
20
23
  export interface WorkspaceLocationState {
24
+ host: {
25
+ host: string;
26
+ username: string;
27
+ port: number;
28
+ } | null;
21
29
  instanceId: string;
22
30
  epoch: number;
23
31
  revision: number;
@@ -1,7 +1,7 @@
1
- import type { ConnectApi, Result } from './api.ts';
1
+ import type { ConnectApi, Result, SshTarget } from './api.ts';
2
2
  import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
3
- import type { WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
- import type { createHostDirectories } from './host-directories.ts';
3
+ import type { WorkspaceLocationItem, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
+ import type { HostDirectoryInfo, createHostDirectories } from './host-directories.ts';
5
5
  import { type LocalWorkspaceContext, type LocalWorkspaceContextRequest } from './local-workspace-context.ts';
6
6
  interface Native {
7
7
  workspaceId: string;
@@ -31,13 +31,36 @@ interface Options {
31
31
  nextRevision?: () => number;
32
32
  }
33
33
  export declare function createWorkspaceLocations(o: Options): {
34
+ withHostBinding: <T>(input: import("./workspace-location-types.ts").HostWorkspaceResolveContext, run: (value: {
35
+ directory: HostDirectoryInfo;
36
+ target: SshTarget;
37
+ local: {
38
+ path: string;
39
+ device: number;
40
+ inode: number;
41
+ };
42
+ revision: number;
43
+ }, guard: () => void) => Promise<Result<T>>, finalize?: () => void) => Promise<Result<T>>;
34
44
  withLocalBinding: <T>(c: LocalWorkspaceContextRequest, run: (directory: {
35
45
  path: string;
36
46
  device: number;
37
47
  inode: number;
38
48
  }, guard: () => void) => Promise<Result<T>>) => Promise<Result<T>>;
39
49
  getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
40
- getWorkspaceLocationState: () => WorkspaceLocationState;
50
+ getWorkspaceLocationState: () => {
51
+ host: {
52
+ host: string;
53
+ username: string;
54
+ port: number;
55
+ } | null;
56
+ instanceId: string;
57
+ epoch: number;
58
+ revision: number;
59
+ phase: "loading" | "ready" | "failed" | "disposed";
60
+ pageSize: number;
61
+ items: WorkspaceLocationItem[];
62
+ need?: import("./api.ts").ConnectNeed;
63
+ };
41
64
  onWorkspaceLocationState(listener: (s: WorkspaceLocationState) => void): () => void;
42
65
  refreshWorkspaceLocations: () => Promise<Result<WorkspaceLocationState>>;
43
66
  browseWorkspaceHostDirectories: (c: WorkspaceBrowseRequest) => Promise<Result<WorkspaceBrowsePage>>;
@@ -2,7 +2,7 @@ import { renameSync, realpathSync, lstatSync } from 'node:fs';
2
2
  import { lstat, realpath, open, rm } from 'node:fs/promises';
3
3
  import { join, isAbsolute } from 'node:path';
4
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
5
- import { privateDirectory, readPrivate } from "./private-files.js";
5
+ import { privateDirectory, readPrivate, readPrivateSync } from "./private-files.js";
6
6
  import { fail, ok, need, NeedError } from "./needs.js";
7
7
  import { readLocalWorkspaceProcess } from "./local-workspace-context.js";
8
8
  const queues = new Map();
@@ -16,8 +16,11 @@ export function createWorkspaceLocations(o) {
16
16
  const controllers = new Set();
17
17
  const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'locations.json'), secret = randomBytes(32), listeners = new Set();
18
18
  let disposed = false, revision = 0, tail = Promise.resolve();
19
- let snapshot = { ...connection(), revision: 0, phase: 'loading', pageSize: o.pageSize, items: [] };
19
+ let snapshot = { ...connection(), host: currentHost(), revision: 0, phase: 'loading', pageSize: o.pageSize, items: [] };
20
20
  function connection() { const c = o.api.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; }
21
+ function currentHost() { const c = o.api.getConnectionState(); if (c.phase !== 'connected')
22
+ return null; const r = o.api.getModelCatalogTarget('codex'); if (!r.ok || r.value.instanceId !== c.instanceId || r.value.epoch !== c.epoch)
23
+ return null; const { host, username, port } = r.value.target; return { host, username, port }; }
21
24
  function exact(c) { const now = connection(); return !disposed && now.instanceId === c.instanceId && now.epoch === c.epoch; }
22
25
  function reject(code) { throw new NeedError(need(code)); }
23
26
  function check(c) {
@@ -25,7 +28,7 @@ export function createWorkspaceLocations(o) {
25
28
  reject(disposed ? 'DISPOSED' : 'WORKSPACE_LOCATION_CONFLICT');
26
29
  }
27
30
  function publish(items, error) {
28
- snapshot = { ...connection(), revision: (revision = o.nextRevision?.() ?? revision + 1), phase: disposed ? 'disposed' : error ? 'failed' : 'ready', pageSize: o.pageSize, items, ...(error ? { need: need(error) } : {}) };
31
+ snapshot = { ...connection(), host: currentHost(), revision: (revision = o.nextRevision?.() ?? revision + 1), phase: disposed ? 'disposed' : error ? 'failed' : 'ready', pageSize: o.pageSize, items, ...(error ? { need: need(error) } : {}) };
29
32
  for (const listener of listeners)
30
33
  listener(structuredClone(snapshot));
31
34
  o.onState?.(structuredClone(snapshot));
@@ -401,6 +404,77 @@ export function createWorkspaceLocations(o) {
401
404
  return fail('WORKSPACE_LOCATION_INVALID');
402
405
  return ok(undefined);
403
406
  }
407
+ // Same queue as selection: a successful callback cannot race a new source UUID.
408
+ function withHostBinding(input, run, finalize = () => { }) {
409
+ const c = structuredClone(input);
410
+ return serial(async () => {
411
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId']);
412
+ if (!token(c.expectedBindingId))
413
+ reject('WORKSPACE_LOCATION_INVALID');
414
+ const x = await context(c), r = x.current;
415
+ if (!r || r.source !== 'host' || !r.remote)
416
+ reject('WORKSPACE_LOCATION_CONFLICT');
417
+ const t = await target(c);
418
+ check(c);
419
+ if (t.identity !== r.identity)
420
+ reject('WORKSPACE_LOCATION_INVALID');
421
+ const bytes = await readPrivate(file, o.metadataMaxBytes), registeredPath = registeredLocalPath(c.workspaceId);
422
+ const guard = () => {
423
+ check(c);
424
+ const now = o.api.getConnectionState();
425
+ if (now.phase !== 'connected')
426
+ reject('CONNECTION_LOST');
427
+ const latest = o.api.getModelCatalogTarget('codex');
428
+ if (!latest.ok)
429
+ throw new NeedError(latest.error);
430
+ const v = latest.value.target;
431
+ if (hash([v.host, v.username, v.port, v.projectRoot, v.session, readPrivateSync(v.knownHostsFile, o.metadataMaxBytes)]) !== t.identity)
432
+ reject('WORKSPACE_LOCATION_INVALID');
433
+ if (readPrivateSync(file, o.metadataMaxBytes) !== bytes)
434
+ reject('WORKSPACE_LOCATION_CONFLICT');
435
+ if (registeredLocalPath(c.workspaceId) !== registeredPath)
436
+ reject('WORKSPACE_LOCATION_INVALID');
437
+ try {
438
+ const path = realpathSync(registeredPath), st = lstatSync(path);
439
+ if (path !== x.n.localPath || !st.isDirectory() || st.dev !== x.n.localDev || st.ino !== x.n.localIno)
440
+ reject('WORKSPACE_LOCATION_INVALID');
441
+ }
442
+ catch (e) {
443
+ if (e instanceof NeedError)
444
+ throw e;
445
+ reject('WORKSPACE_LOCATION_INVALID');
446
+ }
447
+ };
448
+ const inspect = async () => {
449
+ guard();
450
+ if (!o.hostDirectories)
451
+ reject('DEPENDENCY_REQUIRED');
452
+ const current = await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal));
453
+ guard();
454
+ if (!current.ok)
455
+ throw new NeedError(current.error);
456
+ const a = r.remote, b = current.value;
457
+ if (a.path !== b.path || a.requestedPath !== b.requestedPath || a.identity.device !== b.identity.device || a.identity.inode !== b.identity.inode || a.entryIdentity.device !== b.entryIdentity.device || a.entryIdentity.inode !== b.entryIdentity.inode || a.isSymlink !== b.isSymlink)
458
+ reject('HOST_DIRECTORY_CHANGED');
459
+ if (b.permissions.read !== true || b.permissions.execute !== true)
460
+ reject('HOST_DIRECTORY_UNREADABLE');
461
+ if (['read', 'write', 'execute'].some(k => a.permissions[k] !== b.permissions[k]))
462
+ reject('HOST_DIRECTORY_CHANGED');
463
+ return b;
464
+ };
465
+ const directory = await inspect(), value = { directory, target: structuredClone(t.value), local: { path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, revision: snapshot.revision };
466
+ const result = await run(value, guard);
467
+ guard();
468
+ if (!result.ok)
469
+ return result;
470
+ // Do not treat directory content timestamps as identity changes.
471
+ value.directory = await inspect();
472
+ guard();
473
+ finalize();
474
+ guard();
475
+ return result;
476
+ });
477
+ }
404
478
  // Internal transaction only: same queue as source selection, never a public execution API.
405
479
  function withLocalBinding(c, run) {
406
480
  return serial(async () => {
@@ -429,7 +503,7 @@ export function createWorkspaceLocations(o) {
429
503
  return run({ path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, guard);
430
504
  });
431
505
  }
432
- return { withLocalBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => structuredClone(snapshot), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), guardLegacySession: (id) => serial(() => guard(id)), resolveLegacySession: (id, resolve) => serial(async () => {
506
+ return { withHostBinding, withLocalBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), guardLegacySession: (id) => serial(() => guard(id)), resolveLegacySession: (id, resolve) => serial(async () => {
433
507
  const c = connection(), before = await guard(id);
434
508
  if (!before.ok)
435
509
  return before;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.19",
3
+ "version": "0.7.20",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1"