@ai-workbench/connect 0.7.18 → 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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- 安装:在官方 DSH「插件 → 添加插件」中选择编排已核验的 tgz 绝对路径。已由编排发布的版本也可按其提供的精确包版本安装;本轮0.7.18只提供固定tgz,本项目不自行 publish。
1
+ 安装:在官方 DSH「插件 → 添加插件」中选择编排已核验的 tgz 绝对路径。已由编排发布的版本也可按其提供的精确包版本安装;本轮0.7.19只提供固定tgz,本项目不自行 publish。
2
2
 
3
3
  # 远程主机连接插件(L)
4
4
 
@@ -43,7 +43,7 @@ openssl s_client -connect registry.npmjs.org:443 -servername registry.npmjs.org
43
43
 
44
44
  D13已通过[PR15](https://github.com/yzsnstotz/ai-workbench-connect/pull/15)合推main7915df5,移除前为909eabb;五项被拒产物及清单引用已撤除。不再生成新的聚合整包或验收ZIP,交付物为插件本身。
45
45
 
46
- **插件版本0.7.18,API保持0.7.0/native-local-v1。** 本轮沿用现有N/X公开API,真实组合由编排验证。L导入动作固定使用官方系统目录窗口:自动能力为native时直接消费其pick;SSH等启动上下文提供browse时,明确调用同一官方原生包的公开pickNativeDirectory,不修改全局选择器。失败原因与临时登录路径只在本节技术详情准确投影。js-yaml/yauzl及其传递运行依赖随tgz打包,官方宿主peer由已安装官方程序提供,员工不另装npm依赖。真实中文GUI/授权及leo E门分别留证。旧140测试/46图只属于前任draft.3;本轮证据独立记录于[第2轮证据](docs/evidence/2026-10-21-L-round2-draft4/)。不得拿旧0.6.3 tgz当native-local-v1的输入。
46
+ **插件版本0.7.19,API保持0.7.0/native-local-v1。** 本轮沿用现有N/X公开API,真实组合由编排验证。L导入动作固定使用官方系统目录窗口:自动能力为native时直接消费其pick;SSH等启动上下文提供browse时,明确调用同一官方原生包的公开pickNativeDirectory,不修改全局选择器。失败原因与临时登录路径只在本节技术详情准确投影。js-yaml/yauzl及其传递运行依赖随tgz打包,官方宿主peer由已安装官方程序提供,员工不另装npm依赖。真实中文GUI/授权及leo E门分别留证。旧140测试/46图只属于前任draft.3;本轮证据独立记录于[第2轮证据](docs/evidence/2026-10-21-L-round2-draft4/)。不得拿旧0.6.3 tgz当native-local-v1的输入。
47
47
 
48
48
  开发使用Node24.13.1,依赖/缓存/构建和临时HOME放自有外接APFS。工程检查为`npm test`、`npm run check`、`npm run build`;它们不替代真实产品路径。安装走官方插件管理,本包自身只声明一个官方bundle条目,不使用wrapper或员工启动器。工人GUI按[SELFTEST](docs/SELFTEST.md)的PID和三项获准偏离执行,不操作owner实例。
49
49
 
@@ -53,7 +53,7 @@ L0.7.4按owner最新纠正分开供给和授权:Electron组件从自身官方
53
53
 
54
54
  官方Electron内置Node会把.asar视作虚拟目录;组件缓存/解压专用physical-fs在Electron中使用original-fs核验物理归档,不修改全局process.noAsar。真实官方运行时新建及跨Node复用缓存均有回归。
55
55
 
56
- 0.7.5仅调整公开 npm 发布元数据和包内容:运行依赖继续随包,合同、源码、测试与证据不进包;无安装脚本。源码与合同见[项目仓库](https://github.com/yzsnstotz/ai-workbench-connect)。发布前可用官方插件页安装已核验的tgz绝对路径。0.7.18本轮提供固定tgz,由编排决定发布;L不执行publish。
56
+ 0.7.5仅调整公开 npm 发布元数据和包内容:运行依赖继续随包,合同、源码、测试与证据不进包;无安装脚本。源码与合同见[项目仓库](https://github.com/yzsnstotz/ai-workbench-connect)。发布前可用官方插件页安装已核验的tgz绝对路径。0.7.19本轮提供固定tgz,由编排决定发布;L不执行publish。
57
57
 
58
58
  0.7.6:L设置节可显式选择 GitHub 官方源或 npmmirror(Electron 官方文档列出的中国镜像),显示所选来源与理由。未保存选择/未显式配置时默认 npmmirror,依据为编排在leo的可达性实测,不代表自动测速。优先级:本profile设置节已保存选择 → helper.componentDownloadSource初值 → 旧helper.source显式URL → 默认npmmirror;坏设置/保存失败明确报错,不静默切源。预设仍校验原Electron44.0.0固定SHA256。helper.componentObservationIntervalMs默认1000毫秒,只刷新“已N秒无进展”,不触发超时/重试/换源。Claude网页登录的当前流向见下节;Codex本版保留原有N主机代理方式。
59
59
 
@@ -121,3 +121,7 @@ RFC8628的 `verification_uri_complete` 是可选字段;固定0.163.0 CLI只提
121
121
  payload 仅有七个必填字段:phase 固定 `workspace-source-admission`;stage 为 source-context/source-confirmation/input-acceptance/login-readiness/local-admission/input-prepare/model-catalog/runtime-resolve;workspaceId/bindingId 为已观测 ID 或 null;source 为 local/host/legacy-host 或 null;status 沿工作区来源的 unselected/selected/legacy-confirmation-required/invalid 或 null;outcome 为 confirmation-required/confirmed/declined/cancelled/failed。未知来源事实显式 null,不推测或补建关系,不接收额外字段/正文/凭据/环境。
122
122
 
123
123
  设置 → 远程主机连接 → **连接前技术详情(含登录与工作区确认)** 可按原生会话/品牌逐项展开完整记录并继续加载。写入只记诊断,不产生来源确认、品牌接纳或执行权限;同 eventId 同内容只核持久 ACK,异内容冲突,不重放选择或执行。新增 Config/默认/阈值为 0,沿既有 conversationDetails 字节预算/分页。真实 X2 消费、GUI/leo/owner 门另验;不 publish。
124
+
125
+ ## 0.7.19 本地首轮会话核验修复
126
+
127
+ 官方 rc.2 JSONL 会将新会话省略的 delegationDepth 写为 0。接纳与本地技术详情历史核验现在只将这两种官方表示视为同一身份,避免新建 Claude/Codex 会话误报 REMOTE_DETAIL_SCOPE_INVALID;其他完整 header 身份、实际员工输入、品牌、目录与连接代次检查保持严格。不会重写原始 header/旧关系摘要或恢复旧轮写权限,无新增 Config、权限或自动重试。X 的输入核验和错误文案须随统一 0.8.13 修复;leo 真实组合复验另行进行,本包不安装现场、不 publish。
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 {};