@ai-workbench/connect 0.7.28 → 0.7.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/index.cjs CHANGED
@@ -85,7 +85,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
85
85
  const record=value=>!!value&&typeof value==='object'&&!Array.isArray(value);
86
86
  const safeText=value=>typeof value==='string'&&value.length>0&&!/[\x00-\x1f\x7f]/.test(value);
87
87
  const validHost=value=>record(value)&&safeText(value.host)&&safeText(value.username)&&Number.isInteger(value.port)&&value.port>=1&&value.port<=65535&&Object.keys(value).every(key=>['host','username','port'].includes(key));
88
- const validLocationItem=item=>record(item)&&safeText(item.workspaceId)&&safeText(item.workspaceName)&&safeText(item.localPath)&&(item.bindingId===null||safeText(item.bindingId))&&[null,'local','host'].includes(item.source)&&['unselected','selected','invalid'].includes(item.status)&&['not-selected','local-pending','host-pending'].includes(item.execution);
88
+ const validLocationItem=item=>record(item)&&safeText(item.workspaceId)&&safeText(item.workspaceName)&&safeText(item.localPath)&&(item.bindingId===null||safeText(item.bindingId))&&[null,'local','host'].includes(item.source)&&(item.source==='host'?safeText(item.host?.host)&&safeText(item.remote?.path)&&item.remote.path.startsWith('/'):['unselected','selected','invalid'].includes(item.status)&&['not-selected','local-pending'].includes(item.execution));
89
89
  const validLocations=value=>record(value)&&safeText(value.instanceId)&&Number.isSafeInteger(value.epoch)&&value.epoch>=0&&Number.isSafeInteger(value.revision)&&value.revision>=0&&['loading','ready','failed','disposed'].includes(value.phase)&&Number.isSafeInteger(value.pageSize)&&value.pageSize>=1&&(value.host===undefined||value.host===null||validHost(value.host))&&Array.isArray(value.items)&&value.items.every(validLocationItem);
90
90
  const validSnapshot=value=>{const s=value?.startup,l=value?.workspaceLocations;return record(s)&&['checking','blocked','login-required','authorizing','idle','disposed'].includes(s.phase)&&record(s.logins)&&Object.values(s.logins).every(v=>typeof v==='boolean')&&(s.checkingProviders===undefined||Array.isArray(s.checkingProviders))&&(s.providerNeeds===undefined||record(s.providerNeeds))&&(l===undefined||l===null||validLocations(l));};
91
91
  const acceptLocations=(incoming,source)=>{if(!incoming)return incoming;const valid=typeof incoming.instanceId==='string'&&Number.isSafeInteger(incoming.epoch)&&incoming.epoch>=0&&Number.isSafeInteger(incoming.revision)&&incoming.revision>=0;if(!valid||retiredLocations.has(incoming.instanceId)||(workspaceLocations&&incoming.instanceId===workspaceLocations.instanceId&&(incoming.epoch<workspaceLocations.epoch||incoming.revision<workspaceLocations.revision))||(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId&&source==='http'))return workspaceLocations;if(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId)retiredLocations.add(workspaceLocations.instanceId);workspaceLocations=incoming;return incoming;};
@@ -108,7 +108,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
108
108
  const current=()=>live.current&&sameLocationContext(workbench.getSnapshot().value?.workspaceLocations,context);
109
109
  const browse=async(query={})=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const size=Number(pageSize);if(!/^\d+$/.test(pageSize)||!Number.isSafeInteger(size)||size<1){setError('每页条数需要正安全整数。');return;}const result=await workbench.browseWorkspaceHostDirectories({...context,pageSize:size,...query});if(at!==sequence.current||!current())return;if(!result?.ok){setError(result?.error?.message||'主机目录读取失败,未自动重试。');return;}const value=result.value;if(value.instanceId!==context.instanceId||value.epoch!==context.epoch||value.workspaceId!==context.workspaceId||value.bindingId!==context.expectedBindingId){setError('工作区或连接已变化,请刷新位置。');return;}setPage(value);}catch{if(at===sequence.current&&current())setError('主机目录读取失败,未自动重试。');}finally{if(at===sequence.current&&current())setLoading(false);}};
110
110
  const select=async(choice)=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const result=await workbench.selectWorkspaceLocation({...context,...choice});if(at!==sequence.current||!current())return;if(!result?.ok)setError(result?.error?.message||'位置未保存,请刷新位置。');}catch{if(at===sequence.current&&current())setError('位置保存结果无法确认,请刷新后核实;未自动重试。');}finally{if(at===sequence.current&&current())setLoading(false);}};
111
- const execution=item.status==='invalid'?'工作区位置当前不可用,请查看具体原因。':item.execution==='local-pending'?'已选择本机文件夹;运行前会核验本机执行条件。':item.execution==='host-pending'?'已选择主机文件夹;运行前会重新核对目录与权限。':'尚未选择文件来源。';
111
+ const execution=item.source==='host'?'已选择主机文件夹;每轮开始只确认该路径在主机上存在且为文件夹。':item.status==='invalid'?'工作区位置当前不可用,请查看具体原因。':item.execution==='local-pending'?'已选择本机文件夹;运行前会核验本机执行条件。':'尚未选择文件来源。';
112
112
  const identity=locations.host,host=identity?identity.username+'@'+identity.host+':'+identity.port:'主机标识尚未核实';
113
113
  return h('fieldset',null,h('legend',null,item.workspaceName),h('p',null,'原生本地工作区:'+item.localPath),h('p',null,'远程主机:'+host),h('p',{role:'status'},execution),item.need?h('p',{role:'alert'},item.need.message):null,h('button',{type:'button',disabled:loading,onClick:()=>select({source:'local'})},'使用本地文件夹'),h('button',{type:'button',disabled:loading,onClick:()=>browse()},'浏览主机文件夹'),h('label',null,'主机绝对目录',h('input',{type:'text',value:path,disabled:loading,onChange:event=>setPath(event.target.value)})),h('button',{type:'button',disabled:loading||!path.startsWith('/'),onClick:()=>browse({path})},'打开主机目录'),h('label',null,'主机目录每页条数',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:pageSize,disabled:loading,onChange:event=>setPageSize(event.target.value)})),h('p',null,'默认每页 '+locations.pageSize+' 条;可填写1至9007199254740991整数。只浏览和选择已有目录,不创建目录;本地文件不会自动上传。'),loading?h('p',{role:'status'},'正在核实工作区位置…'):null,error?h('p',{role:'alert'},error):null,page?h(React.Fragment,null,h('p',null,'请求目录:'+page.requestedPath),h('p',null,'规范路径:'+page.path),h('p',null,'父级:'+(page.parentPath??'无')),h('p',null,'符号链接:'+(page.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:page.permissions}),page.parentPath?h('button',{type:'button',disabled:loading,onClick:()=>browse({path:page.parentPath})},'打开父级目录'):null,h('button',{type:'button',disabled:loading||!page.selectionToken,onClick:()=>select({source:'host',selectionToken:page.selectionToken})},'选择当前主机文件夹'),...page.entries.map(entry=>h('div',{key:entry.requestedPath},h('p',null,entry.name+' · '+(entry.path??entry.requestedPath)+';符号链接:'+(entry.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:entry.permissions}),entry.errorCode?h('p',{role:'alert'},'目录无法使用:'+entry.errorCode):null,h('button',{type:'button',disabled:loading||!!entry.errorCode,onClick:()=>browse({path:entry.requestedPath})},'打开 '+entry.name),h('button',{type:'button',disabled:loading||!entry.selectionToken,onClick:()=>select({source:'host',selectionToken:entry.selectionToken})},'选择 '+entry.name))),page.nextCursor?h('button',{type:'button',disabled:loading,onClick:()=>browse({cursor:page.nextCursor})},'继续加载目录'):null):null);
114
114
  }
@@ -173,7 +173,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
173
173
  };
174
174
  return {getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},start(){if(started||!alive)return;started=true;return reload();},reload,dispose(){alive=false;epoch++;clear();listeners.clear();}};
175
175
  }
176
- function WorkspacePickerSettings({registration}){const value=React.useSyncExternalStore(registration.subscribe,registration.getSnapshot),settings=value.settings;return h('details',null,h('summary',null,'统一目录选择器'),h('p',{role:value.phase==='failed'?'alert':'status'},value.message),settings?h(React.Fragment,null,h('p',null,'远程映射目录:'+settings.mappingRoot+';子目录名为主机信任身份与远程规范路径的完整64位 SHA256。仅作原生工作区身份锚,不同步、不存员工文件;成功映射保留,移除工作区或卸载后不自动清理。添加失败只影响本次;若列表有残留条目,可在 DSH 原生工作区管理中删除,再重新选择。选择器不会因旧失败持续锁住。'),h('p',null,'workspaceLocations.pickerSlotPriority 当前为 '+settings.slotPriority+'(默认-10,小于0的安全整数;数值越低优先级越高)。可在官方插件 Config 修改,保留官方原生入口。'),h('p',null,'workspaceLocations.pageSize 当前为 '+settings.pageSize+'(默认100);enrollmentMetadataMaxBytes 当前为 '+settings.metadataMaxBytes+' 字节(默认1048576)。目录输出同时受 commandOutputMaxBytes 约束;请到官方插件 Config 查看和修改。没有隐藏目录数量或寿命上限。')):null,h('button',{type:'button',disabled:value.phase==='loading',onClick:()=>registration.reload()},'重新加载目录选择器设置'));}
176
+ function WorkspacePickerSettings({registration}){const value=React.useSyncExternalStore(registration.subscribe,registration.getSnapshot),settings=value.settings;return h('details',null,h('summary',null,'统一目录选择器'),h('p',{role:value.phase==='failed'?'alert':'status'},value.message),settings?h(React.Fragment,null,h('p',null,'远程映射目录:'+settings.mappingRoot+';子目录名由主机名与绝对路径生成,仅用于原生工作区占位,不作主机执行身份检查。仅作原生工作区身份锚,不同步、不存员工文件;成功映射保留,移除工作区或卸载后不自动清理。添加失败只影响本次;若列表有残留条目,可在 DSH 原生工作区管理中删除,再重新选择。选择器不会因旧失败持续锁住。'),h('p',null,'workspaceLocations.pickerSlotPriority 当前为 '+settings.slotPriority+'(默认-10,小于0的安全整数;数值越低优先级越高)。可在官方插件 Config 修改,保留官方原生入口。'),h('p',null,'workspaceLocations.pageSize 当前为 '+settings.pageSize+'(默认100);enrollmentMetadataMaxBytes 当前为 '+settings.metadataMaxBytes+' 字节(默认1048576)。目录输出同时受 commandOutputMaxBytes 约束;请到官方插件 Config 查看和修改。没有隐藏目录数量或寿命上限。')):null,h('button',{type:'button',disabled:value.phase==='loading',onClick:()=>registration.reload()},'重新加载目录选择器设置'));}
177
177
 
178
178
  function WorkspaceLocations({state,workbench}){
179
179
  const locations=state?.workspaceLocations,[error,setError]=React.useState(''),[refreshing,setRefreshing]=React.useState(false);if(!locations)return null;
@@ -2,15 +2,13 @@ const fs=require('node:fs/promises');
2
2
  const {constants}=require('node:fs');
3
3
  const path=require('node:path');
4
4
  const os=require('node:os');
5
- const error=code=>({protocolVersion:1,ok:false,error:{code}});
6
- const validIdentity=value=>value&&typeof value==='object'&&['device','inode','mtimeNs','ctimeNs'].every(key=>typeof value[key]==='string'&&/^-?\d+$/.test(value[key]));
5
+ const error=(code,exception)=>({protocolVersion:1,ok:false,error:{code,...(['ENOENT','ENOTDIR','EACCES','EPERM','EIO','ELOOP'].includes(exception?.code)?{systemCode:exception.code}:{})}});
7
6
  const identity=stat=>({device:String(stat.dev),inode:String(stat.ino),mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
8
7
  const entryIdentity=stat=>({device:String(stat.dev),inode:String(stat.ino)});
9
- const equal=(a,b)=>['device','inode','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
10
8
  const binaryCompare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
11
9
  const validPath=value=>typeof value==='string'&&path.isAbsolute(value)&&!value.includes('\0');
12
10
  const invalid=()=>Object.assign(new Error('HOST_DIRECTORY_INVALID'),{directoryCode:'HOST_DIRECTORY_INVALID'});
13
- const classify=exception=>exception?.directoryCode??(['EACCES','EPERM'].includes(exception?.code)?'HOST_DIRECTORY_UNREADABLE':'HOST_DIRECTORY_INVALID');
11
+ const classify=exception=>exception?.directoryCode??(['ENOENT','ENOTDIR','ELOOP'].includes(exception?.code)?'HOST_DIRECTORY_INVALID':'HOST_DIRECTORY_UNREADABLE');
14
12
  const unknownPermissions=()=>({read:null,write:null,execute:null,reason:'HOST_PERMISSION_UNKNOWN'});
15
13
  async function permissions(target){
16
14
  const result={};let unknown=false;
@@ -24,14 +22,13 @@ async function observe(requestedPath){
24
22
  const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())throw invalid();
25
23
  return {requestedPath,path:resolved,parentPath:path.dirname(resolved)===resolved?null:path.dirname(resolved),identity:identity(stat),entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink(),permissions:await permissions(resolved)};
26
24
  }
27
- function unchanged(before,after){return before.path===after.path&&equal(before.identity,after.identity)&&before.entryIdentity.device===after.entryIdentity.device&&before.entryIdentity.inode===after.entryIdentity.inode;}
28
25
  async function directoryEntry(requestedPath,name){
29
26
  const entry=await fs.lstat(requestedPath,{bigint:true});if(!entry.isDirectory()&&!entry.isSymbolicLink())return null;
30
27
  const base={name,requestedPath,entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink()};
31
28
  try{
32
29
  const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())return null;
33
30
  const access=await permissions(resolved);
34
- return {...base,path:resolved,identity:identity(stat),permissions:access,...access.read!==true||access.execute!==true?{errorCode:'HOST_DIRECTORY_UNREADABLE'}:{}};
31
+ return {...base,path:resolved,identity:identity(stat),permissions:access};
35
32
  }catch(exception){return {...base,permissions:unknownPermissions(),errorCode:classify(exception)};}
36
33
  }
37
34
  async function execute(request){
@@ -39,12 +36,12 @@ async function execute(request){
39
36
  if(!Number.isSafeInteger(request.maxOutputBytes)||request.maxOutputBytes<1)return error('HOST_DIRECTORY_INVALID');
40
37
  if(request.path!==undefined&&!validPath(request.path))return error('HOST_DIRECTORY_INVALID');
41
38
  if(request.operation==='inspect'&&request.path===undefined)return error('HOST_DIRECTORY_INVALID');
42
- if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.expected!==undefined&&!validIdentity(request.expected)||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0')||!validIdentity(request.expected))))return error('HOST_DIRECTORY_INVALID');
43
- if(request.operation==='create'&&(!validPath(request.path)||!validIdentity(request.expected)||typeof request.name!=='string'||['','.','..'].includes(request.name)||/[\\/\x00-\x1f\x7f]/.test(request.name)))return error('HOST_DIRECTORY_INVALID');
39
+ if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0'))))return error('HOST_DIRECTORY_INVALID');
40
+ if(request.operation==='create'&&(!validPath(request.path)||typeof request.name!=='string'||['','.','..'].includes(request.name)||/[\\/\x00-\x1f\x7f]/.test(request.name)))return error('HOST_DIRECTORY_INVALID');
44
41
  const requestedPath=request.path??os.homedir();
45
42
  try{
43
+ if(request.operation==='inspect'){const stat=await fs.stat(requestedPath);if(!stat.isDirectory())throw invalid();const result={protocolVersion:1,ok:true,value:{path:requestedPath}};return Buffer.byteLength(JSON.stringify(result)+'\n')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;}
46
44
  const before=await observe(requestedPath);
47
- if(request.expected!==undefined&&!equal(before.identity,request.expected))return error('HOST_DIRECTORY_CHANGED');
48
45
  if(request.operation==='create'){
49
46
  const child=path.join(before.path,request.name);
50
47
  try{await fs.mkdir(child);}catch(exception){return error(exception?.code==='EEXIST'?'HOST_DIRECTORY_EXISTS':classify(exception));}
@@ -64,11 +61,9 @@ async function execute(request){
64
61
  }
65
62
  const hasMore=window.length>request.pageSize;if(hasMore)window.pop();value={...before,entries:window,...hasMore?{nextAfter:window[window.length-1].name}:{}};
66
63
  }
67
- let after;try{after=await observe(requestedPath);}catch{return error('HOST_DIRECTORY_CHANGED');}
68
- if(!unchanged(before,after))return error('HOST_DIRECTORY_CHANGED');
69
64
  const result={protocolVersion:1,ok:true,value};
70
65
  return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
71
- }catch(exception){return error(classify(exception));}
66
+ }catch(exception){return error(classify(exception),exception);}
72
67
  }
73
68
  async function main(){
74
69
  let input='';for await(const chunk of process.stdin)input+=chunk;
package/lib/api.d.ts CHANGED
@@ -94,21 +94,16 @@ export interface ContractInfo {
94
94
  connectionMessages?: 1;
95
95
  localWorkspaceContext?: 1;
96
96
  modelCatalogTarget?: 1;
97
- hostWorkspaceResolution?: 1;
97
+ hostWorkspaceResolution?: 2;
98
98
  }
99
99
  export interface WorkspaceUse {
100
100
  provider: Provider;
101
101
  purpose: 'user-turn';
102
102
  }
103
103
  export interface HostSessionProjectTarget {
104
- instanceId: string;
105
- epoch: number;
106
- bindingRevision: number;
107
- bindingId: string;
108
104
  sessionId: string;
109
- workspaceId: string;
110
105
  source: 'host';
111
- directory: import('./host-directories.ts').HostDirectoryInfo;
106
+ host: string;
112
107
  project: {
113
108
  name: string;
114
109
  path: string;
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { need } from "./needs.js";
3
3
  const markers = ['AW_REMOTE_COMMAND_KILL_FAILED', 'AUTH_STATUS_JSON_INVALID:SyntaxError', 'Permission denied', 'Host key verification failed', 'Connection refused', 'Connection closed', 'command not found', 'No such file or directory'];
4
4
  const names = ['Error', 'TypeError', 'SyntaxError', 'RangeError', 'AbortError', 'DOMException', 'UnknownError'];
5
- const codes = ['ENOENT', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
5
+ const codes = ['ENOENT', 'ENOTDIR', 'EIO', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
6
6
  const stages = ['ssh-status', 'ssh-result', 'remote-frame', 'auth-status', 'connect-check-login', 'integration-pre-login', 'process-spawn', 'process-stdin', 'process-output', 'process-runner'];
7
7
  const reasons = ['CANCELLED', 'SSH_EXIT_NONZERO', 'SSH_STDERR_NONEMPTY', 'FRAME_TRUNCATED', 'FRAME_JSON_INVALID', 'FRAME_OBJECT_INVALID', 'FRAME_VERSION_INVALID', 'FRAME_NONCE_INVALID', 'FRAME_AFTER_END', 'FRAME_KEYS_INVALID', 'FRAME_START_MISSING', 'FRAME_BASE64_INVALID', 'REMOTE_COMMAND_SIGNAL', 'FRAME_END_EXIT_INVALID', 'FRAME_SEQUENCE_OR_VALUE_INVALID', 'FRAME_END_MISSING', 'STATUS_ARGUMENT_INVALID', 'STATUS_EXECUTION_FAILED', 'STATUS_JSON_INVALID', 'STATUS_OBJECT_INVALID', 'STATUS_KEYS_INVALID', 'STATUS_VERSION_INVALID', 'STATUS_PROVIDER_INVALID', 'STATUS_EXIT_MISMATCH', 'STATUS_LOGGED_IN_INVALID', 'STATUS_STDERR_NONEMPTY', 'STATUS_EXIT_INVALID', 'STATUS_EXCEPTION', 'STATUS_SUPERSEDED', 'SSH_PORT_MISSING', 'STDIN_FAILED', 'SPAWN_FAILED', 'OUTPUT_LIMIT_EXCEEDED', 'PROCESS_SIGNAL'];
8
8
  const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -45,11 +45,10 @@ export interface HostDirectoryRequest {
45
45
  path?: string;
46
46
  after?: string;
47
47
  pageSize: number;
48
- expected?: HostDirectoryIdentity;
49
48
  }
50
49
  export interface HostDirectories {
51
50
  browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
52
- inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
53
- create?(target: SshTarget, path: string, name: string, expected: HostDirectoryIdentity, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
51
+ inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
52
+ create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
54
53
  }
55
54
  export declare function createHostDirectories(runner: Runner, maxOutputBytes: number): HostDirectories;
@@ -1,7 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { runRemote } from "./ssh.js";
3
3
  import { fail, ok } from "./needs.js";
4
- import { AuthDiagnosticError } from "./auth-diagnostics.js";
4
+ import { AuthDiagnosticError, authFailure } from "./auth-diagnostics.js";
5
5
  const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID', 'HOST_DIRECTORY_EXISTS'];
6
6
  const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
7
7
  const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
@@ -18,14 +18,14 @@ function validEntry(value, parent) {
18
18
  return false;
19
19
  if (value.path === undefined || value.identity === undefined)
20
20
  return value.path === undefined && value.identity === undefined && value.errorCode !== undefined;
21
- return validPath(value.path) && validIdentity(value.identity) && (value.errorCode !== undefined || value.permissions.read === true && value.permissions.execute === true);
21
+ return validPath(value.path) && validIdentity(value.identity);
22
22
  }
23
23
  const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
24
24
  export function createHostDirectories(runner, maxOutputBytes) {
25
25
  async function request(target, operation, data, signal) {
26
26
  if (signal.aborted)
27
27
  return fail('CONNECTION_LOST');
28
- if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name) || !validIdentity(data.expected)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.expected !== undefined && !validIdentity(data.expected) || data.after !== undefined && (!validName(data.after) || !validIdentity(data.expected))))
28
+ if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.after !== undefined && (!validName(data.after))))
29
29
  return fail('HOST_DIRECTORY_INVALID');
30
30
  try {
31
31
  const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
@@ -34,7 +34,7 @@ export function createHostDirectories(runner, maxOutputBytes) {
34
34
  if (signal.aborted)
35
35
  return fail('CONNECTION_LOST');
36
36
  if (raw.exitCode !== 0 || raw.stderr !== '')
37
- return fail('CONNECTION_LOST');
37
+ return authFailure('ssh-result', raw.exitCode !== 0 ? 'SSH_EXIT_NONZERO' : 'SSH_STDERR_NONEMPTY', { exitCode: raw.exitCode }, undefined, 'CONNECTION_LOST');
38
38
  if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
39
39
  return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
40
40
  let result;
@@ -49,13 +49,15 @@ export function createHostDirectories(runner, maxOutputBytes) {
49
49
  if (!result.ok) {
50
50
  const error = result.error;
51
51
  const code = object(error) ? codes.find(code => code === error.code) : undefined;
52
- return fail(code ?? 'PROJECT_PROTOCOL_INVALID');
52
+ return authFailure('host-directory', 'REMOTE_DIRECTORY_ERROR', { ...(object(error) && ['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM', 'EIO', 'ELOOP'].includes(String(error.systemCode)) ? { errorCode: error.systemCode } : {}) }, undefined, code ?? 'PROJECT_PROTOCOL_INVALID');
53
53
  }
54
+ if (operation === 'inspect')
55
+ return object(result.value) && result.value.path === data.path ? ok({ path: data.path }) : fail('PROJECT_PROTOCOL_INVALID');
54
56
  if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== (operation === 'create' ? (data.path.endsWith('/') ? data.path : data.path + '/') + data.name : data.path))
55
57
  return fail('PROJECT_PROTOCOL_INVALID');
56
58
  if (operation === 'browse') {
57
59
  const value = result.value;
58
- if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name) || data.expected !== undefined && ['device', 'inode', 'mtimeNs', 'ctimeNs'].some(key => value.identity[key] !== data.expected[key]))
60
+ if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name))
59
61
  return fail('PROJECT_PROTOCOL_INVALID');
60
62
  }
61
63
  return ok(result.value);
@@ -69,8 +71,8 @@ export function createHostDirectories(runner, maxOutputBytes) {
69
71
  if (error.diagnostic.stage === 'remote-frame')
70
72
  return fail('PROJECT_PROTOCOL_INVALID');
71
73
  }
72
- return fail('CONNECTION_LOST');
74
+ return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
73
75
  }
74
76
  }
75
- return { create: (target, path, name, expected, signal) => request(target, 'create', { path, name, expected }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
77
+ return { create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
76
78
  }
@@ -1,19 +1,8 @@
1
1
  import type { ConnectApi, HostSessionProjectTarget, Result, WorkspaceUse } from './api.ts';
2
2
  import type { HostWorkspaceResolveContext } from './workspace-location-types.ts';
3
- import type { createWorkspaceLocations } from './workspace-locations.ts';
4
- import type { NativeWorkspaceRegistry } from './native-workspace.ts';
5
- interface Session {
6
- header: Record<string, any>;
7
- }
8
3
  interface Options {
9
- api: ConnectApi;
10
- registry: NativeWorkspaceRegistry;
11
- services: () => {
12
- sessions: {
13
- get(id: string): Session | undefined;
14
- };
15
- };
16
- withHostBinding: ReturnType<typeof createWorkspaceLocations>['withHostBinding'];
4
+ api: Pick<ConnectApi, 'ensureReady' | 'appendRemoteConversationDetail'> & Partial<Pick<ConnectApi, 'getConnectionState'>>;
5
+ hostDirectories?: import('./host-directories.ts').HostDirectories;
17
6
  }
18
7
  export declare function createHostSessionProjects(o: Options): {
19
8
  resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
@@ -1,62 +1,77 @@
1
1
  import { basename, isAbsolute } from 'node:path';
2
- import { realpath } from 'node:fs/promises';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { fail, ok, need, NeedError } from "./needs.js";
2
+ import { randomUUID } from 'node:crypto';
3
+ import { exceptionSummary, outputSummary } from "./auth-diagnostics.js";
4
+ import { ok, need, NeedError } from "./needs.js";
5
5
  const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
- function reject(code) { throw new NeedError(need(code)); }
7
- function changedSessionBinding() {
8
- const n = need('PROJECT_BINDING_INVALID');
9
- n.message = '文件来源已改,请新建会话继续';
10
- n.actor = 'employee';
11
- n.requires = '新会话与当前文件来源';
12
- n.action = { id: 'new-session', label: '新建会话继续', available: false };
13
- throw new NeedError(n);
14
- }
6
+ function reject(code, reason) { throw new NeedError({ ...need(code), officialReason: reason }); }
15
7
  export function createHostSessionProjects(o) {
16
- // 同一运行期的重连保留来源选择;不迁移旧测试会话。
17
- const sources = new Map();
8
+ const controllers = new Set();
18
9
  let disposed = false;
19
10
  async function resolve(id, use, input) {
11
+ let stage = 'request';
12
+ const failure = (error) => {
13
+ let n = error instanceof NeedError ? error.need : need('PROJECT_BINDING_INVALID');
14
+ if (n.code === 'HOST_DIRECTORY_UNREADABLE')
15
+ n = { ...n, message: '暂时无法读取会话记录的主机目录,请查看技术详情,确认主机存储或权限恢复后再试。' };
16
+ if (n.code === 'HOST_DIRECTORY_INVALID')
17
+ n = { ...n, message: '会话记录的主机路径不存在或不是文件夹,请恢复该目录后再试。' };
18
+ if (n.officialReason === 'SESSION_HOST_UNAVAILABLE')
19
+ n = { ...n, message: '此会话使用的主机当前未连接,请连接原主机后再试;会话文件来源保持不变。' };
20
+ const exception = exceptionSummary(error);
21
+ const payload = { stage, reason: n.officialReason ?? (error instanceof NeedError ? 'DECLARED_NEED' : 'UNEXPECTED_EXCEPTION'), ...exception, ...(!(error instanceof NeedError) && error instanceof Error ? { exception: outputSummary(error.message) } : {}) };
22
+ // 沿已有本机日志留一行;不记录异常原文/路径/凭据,也不让日志失败改写原失败。
23
+ const line = { event: 'HOST_WORKSPACE_RESOLVE_FAILED', code: n.code, ...payload };
24
+ try {
25
+ if (!text(id) || !use || !['claude', 'codex'].includes(use.provider) || typeof o.api.appendRemoteConversationDetail !== 'function')
26
+ throw Error('DIAGNOSTIC_CONTEXT_UNAVAILABLE');
27
+ const connection = o.api.getConnectionState?.();
28
+ o.api.appendRemoteConversationDetail({ version: 1, eventId: randomUUID(), instanceId: connection?.instanceId ?? 'unknown', epoch: connection?.epoch ?? 0, sessionId: id, provider: use.provider, turn: null, step: null, sequence: 0, kind: 'diagnostic', severity: 'action-required', code: n.code, summary: n.message, payload });
29
+ }
30
+ catch {
31
+ try {
32
+ console.warn(JSON.stringify(line));
33
+ }
34
+ catch { /* 日志不可用不改变本轮结果。 */ }
35
+ }
36
+ return { ok: false, error: n };
37
+ };
20
38
  try {
21
39
  if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
22
- reject('PROJECT_BINDING_REQUIRED');
23
- const provider = use.provider, c = structuredClone(input);
24
- if (!c || Object.keys(c).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !text(c.instanceId) || !Number.isSafeInteger(c.epoch) || c.epoch < 0 || !text(c.workspaceId) || !text(c.expectedBindingId))
25
- reject('WORKSPACE_LOCATION_INVALID');
26
- const session = o.services().sessions.get(id);
27
- if (!session || session.header.id !== id || !text(session.header.cwd) || !isAbsolute(session.header.cwd))
28
- reject('PROJECT_BINDING_REQUIRED');
29
- const header = structuredClone(session.header), source = { workspaceId: c.workspaceId, bindingId: c.expectedBindingId, source: 'host' };
30
- const guard = () => {
31
- const now = o.api.getConnectionState();
32
- if (disposed || now.phase === 'disposed')
33
- reject('DISPOSED');
34
- if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
35
- reject('CONNECTION_LOST');
36
- const matches = o.registry.list().filter(w => w.sessionIds.includes(id)), registered = o.registry.get(c.workspaceId);
37
- if (matches.length !== 1 || matches[0].id !== c.workspaceId || !registered || registered.path !== matches[0].path || !registered.sessionIds.includes(id))
38
- changedSessionBinding();
39
- if (o.services().sessions.get(id) !== session || !isDeepStrictEqual(session.header, header))
40
- reject('PROJECT_BINDING_INVALID');
41
- const previous = sources.get(id);
42
- if (previous && !isDeepStrictEqual(previous, source))
43
- changedSessionBinding();
44
- };
45
- guard();
46
- return await o.withHostBinding(c, async (value) => {
47
- if (await realpath(header.cwd) !== value.local.path)
48
- reject('WORKSPACE_LOCATION_INVALID');
49
- const ready = await o.api.ensureReady(provider);
50
- if (!ready.ok)
51
- return ready;
52
- if (!isDeepStrictEqual(ready.value, value.target))
53
- reject('CONNECTION_LOST');
54
- return ok({ instanceId: c.instanceId, epoch: c.epoch, sessionId: id, workspaceId: c.workspaceId, bindingId: c.expectedBindingId, bindingRevision: value.revision, source: 'host', directory: structuredClone(value.directory), project: { name: basename(value.directory.path) || '/', path: value.directory.path }, target: structuredClone(value.target) });
55
- }, () => { guard(); sources.set(id, source); });
40
+ reject('PROJECT_BINDING_REQUIRED', 'SESSION_OR_REQUEST_UNAVAILABLE');
41
+ const source = structuredClone(input);
42
+ if (!source || source.source !== 'host' || !text(source.host) || !text(source.path) || !isAbsolute(source.path))
43
+ reject('PROJECT_BINDING_REQUIRED', 'SESSION_HOST_PATH_REQUIRED');
44
+ if (disposed)
45
+ reject('DISPOSED', 'RUNTIME_DISPOSED');
46
+ stage = 'login-ready';
47
+ const ready = await o.api.ensureReady(use.provider);
48
+ if (!ready.ok)
49
+ return failure(new NeedError(ready.error));
50
+ if (disposed)
51
+ reject('DISPOSED', 'RUNTIME_DISPOSED');
52
+ if (ready.value.host !== source.host)
53
+ reject('WORKSPACE_LOCATION_INVALID', 'SESSION_HOST_UNAVAILABLE');
54
+ if (!o.hostDirectories)
55
+ reject('DEPENDENCY_REQUIRED', 'HOST_DIRECTORY_SERVICE_REQUIRED');
56
+ const controller = new AbortController();
57
+ controllers.add(controller);
58
+ try {
59
+ stage = 'host-directory';
60
+ const checked = await o.hostDirectories.inspect(ready.value, source.path, controller.signal);
61
+ if (!checked.ok)
62
+ return failure(new NeedError(checked.error));
63
+ if (disposed)
64
+ reject('DISPOSED', 'RUNTIME_DISPOSED');
65
+ return ok({ sessionId: id, source: 'host', host: source.host, project: { name: basename(source.path) || '/', path: source.path }, target: structuredClone(ready.value) });
66
+ }
67
+ finally {
68
+ controllers.delete(controller);
69
+ }
56
70
  }
57
71
  catch (e) {
58
- return e instanceof NeedError ? { ok: false, error: e.need } : fail('PROJECT_BINDING_INVALID');
72
+ return failure(e);
59
73
  }
60
74
  }
61
- return { resolve, dispose() { disposed = true; } };
75
+ return { resolve, dispose() { disposed = true; for (const controller of controllers)
76
+ controller.abort(); } };
62
77
  }
package/lib/needs.js CHANGED
@@ -47,7 +47,7 @@ const entries = {
47
47
  HOST_TRUST_REQUIRED: { layer: 'ssh', message: '远程主机连接还缺少可信的连接信息,请联系管理员。', requires: 'host.knownHosts', actor: 'administrator', action: { id: 'supply-host-trust', label: '提供主机信任材料', available: false } },
48
48
  HOST_KEY_MISMATCH: { layer: 'ssh', message: '主机身份与已开通的信任材料不符,需要管理员检查。', requires: '匹配的主机公钥', actor: 'administrator', action: { id: 'verify-host-trust', label: '检查主机身份', available: false } },
49
49
  PROJECT_PROTOCOL_INVALID: { layer: 'projects', message: '本次未能读取工作区位置,可重新打开目录选择器再选。', requires: '匹配版本的工作区服务', actor: 'administrator', action: { id: 'inspect-project-protocol', label: '检查工作区接口', available: false } },
50
- PROJECT_BINDING_INVALID: { layer: 'projects', message: '会话的文件来源已变化,请新建会话继续。', requires: '新会话与当前文件来源', actor: 'employee', action: { id: 'new-session', label: '新建会话', available: true } },
50
+ PROJECT_BINDING_INVALID: { layer: 'projects', message: '本轮工作区准备失败,原会话历史仍可查看。请查看技术详情后再试。', requires: '可核对的会话与工作区关系', actor: 'employee', action: { id: 'inspect-remote-details', label: '查看技术详情', available: true } },
51
51
  PROJECT_BINDING_REQUIRED: { layer: 'projects', message: '请在会话中选择已关联的远程工作区。', requires: '当前会话的可信远程工作区关联', actor: 'employee', action: { id: 'select-workspace', label: '选择工作区', available: true } },
52
52
  DISPOSED: { layer: 'integration', message: '连接插件已卸载,需要重新启用插件。', requires: '已启用的连接插件', actor: 'employee', action: { id: 'enable-plugin', label: '启用插件', available: false } },
53
53
  };
@@ -54,14 +54,16 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
54
54
  };
55
55
  api.readConversationLog = readLogs;
56
56
  const beforeContract = api.getContractInfo;
57
- const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution: 1 } : {}) });
57
+ const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution: 2 } : {}) });
58
58
  api.getContractInfo = currentContract;
59
59
  ctx.effect(() => () => { if (api.getContractInfo === currentContract)
60
60
  api.getContractInfo = beforeContract; if (api.appendRemoteConversationDetail === log.append)
61
61
  api.appendRemoteConversationDetail = beforeAppend; if (api.readConversationLog === readLogs)
62
62
  api.readConversationLog = beforeRead; });
63
63
  const unavailableHost = async () => fail('DEPENDENCY_REQUIRED');
64
- api.resolveSessionProject = unavailableHost;
64
+ const host = createHostSessionProjects({ api, hostDirectories: ports.hostDirectories });
65
+ api.resolveSessionProject = host.resolve;
66
+ ctx.effect(() => () => { api.resolveSessionProject = unavailableHost; host.dispose(); });
65
67
  let locationRevision = 0;
66
68
  ctx.inject(['profileContext', 'workspaceRegistry', 'sessions'], native => {
67
69
  const registry = native.get('workspaceRegistry');
@@ -82,10 +84,8 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
82
84
  api.refreshWorkspaceLocations = locations.refreshWorkspaceLocations;
83
85
  api.browseWorkspaceHostDirectories = locations.browseWorkspaceHostDirectories;
84
86
  api.selectWorkspaceLocation = locations.selectWorkspaceLocation;
85
- const host = createHostSessionProjects({ api, registry, services: () => ({ sessions: native.get('sessions') }), withHostBinding: locations.withHostBinding });
86
- api.resolveSessionProject = host.resolve;
87
87
  native.effect(() => { void locations.refreshWorkspaceLocations(); return api.onConnectionState(() => locations.observeConnection()); });
88
- native.effect(() => () => { api.resolveSessionProject = unavailableHost; delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; delete api.getWorkspaceDirectoryPickerSettings; delete api.browseWorkspaceDirectories; delete api.createWorkspaceDirectory; delete api.selectWorkspaceDirectory; host.dispose(); return Promise.all([locations.dispose(), picker?.dispose()]); });
88
+ native.effect(() => () => { delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; delete api.getWorkspaceDirectoryPickerSettings; delete api.browseWorkspaceDirectories; delete api.createWorkspaceDirectory; delete api.selectWorkspaceDirectory; return Promise.all([locations.dispose(), picker?.dispose()]); });
89
89
  });
90
90
  if (autoStart)
91
91
  void api.refreshLoginPrompts();
@@ -1,8 +1,8 @@
1
- import { access, lstat, stat, realpath, readdir, mkdir, open, rename, rm } from 'node:fs/promises';
1
+ import { access, lstat, stat, realpath, mkdir, open, rename, rm } from 'node:fs/promises';
2
2
  import { constants, lstatSync, realpathSync } from 'node:fs';
3
3
  import { join, dirname, basename, isAbsolute } from 'node:path';
4
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
5
- import { privateDirectory, readPrivate, readPrivateSync } from "./private-files.js";
5
+ import { privateDirectory, readPrivate } from "./private-files.js";
6
6
  import { fail, ok, need, NeedError } from "./needs.js";
7
7
  const queues = new Map();
8
8
  const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
@@ -10,7 +10,6 @@ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
10
  const string = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
11
11
  const path = (v) => string(v) && isAbsolute(v);
12
12
  const digest = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
13
- const decimal = (v) => typeof v === 'string' && /^\d+$/.test(v);
14
13
  const strict = (v, keys) => Object.keys(v).every(k => keys.includes(k));
15
14
  const sameInfo = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && a.identity.device === b.identity.device && a.identity.inode === b.identity.inode && a.entryIdentity.device === b.entryIdentity.device && a.entryIdentity.inode === b.entryIdentity.inode && ['read', 'write', 'execute'].every(k => a.permissions[k] === b.permissions[k]);
16
15
  const sameSnapshot = (a, b) => sameInfo(a, b) && a.identity.mtimeNs === b.identity.mtimeNs && a.identity.ctimeNs === b.identity.ctimeNs;
@@ -39,11 +38,11 @@ export function createWorkspaceDirectoryPicker(o) {
39
38
  if (!object(doc) || !strict(doc, ['data', 'checksum']) || !object(doc.data) || doc.checksum !== hash(doc.data))
40
39
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
41
40
  const d = doc.data;
42
- if (!strict(d, ['schemaVersion', 'lastTarget', 'local', 'host', 'mappings', 'journal']) || d.schemaVersion !== 1 || d.lastTarget !== undefined && !['local', 'host'].includes(d.lastTarget) || d.local !== undefined && !path(d.local) || d.host !== undefined && (!object(d.host) || !strict(d.host, ['identity', 'path']) || !digest(d.host.identity) || !path(d.host.path)) || !Array.isArray(d.mappings))
41
+ if (!strict(d, ['schemaVersion', 'lastTarget', 'local', 'host', 'mappings', 'journal']) || d.schemaVersion !== 1 || d.lastTarget !== undefined && !['local', 'host'].includes(d.lastTarget) || d.local !== undefined && !path(d.local) || d.host !== undefined && (!object(d.host) || !path(d.host.path)) || !Array.isArray(d.mappings))
43
42
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
44
43
  const names = new Set();
45
44
  for (const m of d.mappings) {
46
- if (!object(m) || !strict(m, ['name', 'identity', 'remotePath', 'device', 'inode']) || !digest(m.name) || !digest(m.identity) || !path(m.remotePath) || m.name !== hash([m.identity, m.remotePath]) || !decimal(m.device) || !decimal(m.inode) || names.has(m.name))
45
+ if (!object(m) || !digest(m.name) || !path(m.remotePath) || names.has(m.name))
47
46
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
48
47
  names.add(m.name);
49
48
  }
@@ -83,12 +82,8 @@ export function createWorkspaceDirectoryPicker(o) {
83
82
  finally {
84
83
  await rm(temp, { force: true });
85
84
  } }
86
- async function trust(c) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
87
- throw new NeedError(current.need ?? need('CONNECTION_LOST')); const t = take(o.api.getModelCatalogTarget('codex')); if (t.instanceId !== c.instanceId || t.epoch !== c.epoch)
88
- reject('WORKSPACE_LOCATION_CONFLICT'); const bytes = await readPrivate(t.target.knownHostsFile, o.metadataMaxBytes); check(c); return { target: t.target, identity: hash([t.target.host, t.target.username, t.target.port, bytes]) }; }
89
- function guardTrust(c, identity) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
90
- throw new NeedError(current.need ?? need('CONNECTION_LOST')); const t = take(o.api.getModelCatalogTarget('codex')); if (t.instanceId !== c.instanceId || t.epoch !== c.epoch || hash([t.target.host, t.target.username, t.target.port, readPrivateSync(t.target.knownHostsFile, o.metadataMaxBytes)]) !== identity)
91
- reject('WORKSPACE_LOCATION_CONFLICT'); }
85
+ function hostTarget() { if (disposed)
86
+ reject('DISPOSED'); const t = take(o.api.getModelCatalogTarget('codex')); return { target: t.target, host: t.target.host }; }
92
87
  async function remote(run) { const controller = new AbortController(); controllers.add(controller); try {
93
88
  return take(await run(controller.signal));
94
89
  }
@@ -125,24 +120,15 @@ export function createWorkspaceDirectoryPicker(o) {
125
120
  catch {
126
121
  return reject('WORKSPACE_PICKER_INVALID');
127
122
  } }
128
- async function inspect(s) { check(s.context); let current; if (s.target === 'host') {
129
- const t = await trust(s.context);
130
- if (t.identity !== s.identity)
131
- reject('WORKSPACE_LOCATION_CONFLICT');
132
- if (!o.hostDirectories)
133
- reject('DEPENDENCY_REQUIRED');
134
- current = await remote(signal => o.hostDirectories.inspect(t.target, s.info.requestedPath, signal));
135
- guardTrust(s.context, t.identity);
136
- }
137
- else
138
- current = await localInfo(s.info.requestedPath); check(s.context); if (!sameInfo(s.info, current))
123
+ async function inspect(s) { if (s.target === 'host') {
124
+ if (disposed)
125
+ reject('DISPOSED');
126
+ return s.info;
127
+ } check(s.context); const current = await localInfo(s.info.requestedPath); check(s.context); if (!sameInfo(s.info, current))
139
128
  reject('HOST_DIRECTORY_CHANGED'); if (current.permissions.read !== true || current.permissions.execute !== true)
140
129
  reject('HOST_DIRECTORY_UNREADABLE'); return current; }
141
130
  async function nativePath(p) { const s = await lstat(p, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || await realpath(p) !== p)
142
131
  reject('WORKSPACE_LOCATION_INVALID'); return { device: String(s.dev), inode: String(s.ino) }; }
143
- async function mappingPath(j) { const s = await lstat(j.path, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== BigInt(process.getuid()) || (s.mode & 63n) !== 0n || await realpath(j.path) !== j.path)
144
- reject('WORKSPACE_PICKER_STORAGE_FAILED'); if (j.device !== undefined && (String(s.dev) !== j.device || String(s.ino) !== j.inode))
145
- reject('WORKSPACE_PICKER_STORAGE_FAILED'); return { device: String(s.dev), inode: String(s.ino) }; }
146
132
  const unsubscribe = o.api.onConnectionState?.(() => { for (const controller of controllers)
147
133
  controller.abort(); });
148
134
  function serial(run) { const before = queues.get(file) ?? Promise.resolve(); const task = before.then(async () => { if (disposed)
@@ -166,20 +152,18 @@ export function createWorkspaceDirectoryPicker(o) {
166
152
  const target = (r.target ?? previous?.target ?? state.lastTarget ?? 'local');
167
153
  if (previous && target !== previous.target)
168
154
  reject('WORKSPACE_PICKER_INVALID');
169
- if (previous)
155
+ if (previous?.target === 'local')
170
156
  check(previous.context);
171
157
  if (target === 'local' && r.path === undefined)
172
158
  return ok({ target, path: '', parentPath: null, entries: [], selectionToken: '' });
173
- const trusted = target === 'host' ? await trust(c) : undefined;
174
- if (previous && (previous.context.instanceId !== c.instanceId || previous.context.epoch !== c.epoch || previous.identity !== trusted?.identity))
175
- reject('WORKSPACE_LOCATION_CONFLICT');
176
- let requested = r.path ?? previous?.info.requestedPath ?? (target === 'host' && state.host?.identity === trusted?.identity ? state.host?.path : undefined), notice;
159
+ const trusted = target === 'host' ? hostTarget() : undefined;
160
+ let requested = r.path ?? previous?.info.requestedPath ?? (target === 'host' && (!state.host?.host || state.host.host === trusted?.host) ? state.host?.path : undefined), notice;
177
161
  let info, entries, after = cursor?.kind === 'cursor' ? cursor.after : undefined, nextAfter;
178
162
  async function read() {
179
163
  if (target === 'host') {
180
164
  if (!o.hostDirectories)
181
165
  reject('DEPENDENCY_REQUIRED');
182
- return remote(signal => o.hostDirectories.browse(trusted.target, { ...(requested !== undefined ? { path: requested } : {}), pageSize: o.pageSize, ...(after ? { after, expected: previous.info.identity } : {}) }, signal));
166
+ return remote(signal => o.hostDirectories.browse(trusted.target, { ...(requested !== undefined ? { path: requested } : {}), pageSize: o.pageSize, ...(after ? { after } : {}) }, signal));
183
167
  }
184
168
  return { ...await localInfo(requested), entries: [] };
185
169
  }
@@ -197,13 +181,13 @@ export function createWorkspaceDirectoryPicker(o) {
197
181
  const { entries: rawEntries, nextAfter: more, ...directory } = page;
198
182
  info = directory;
199
183
  nextAfter = more;
200
- entries = rawEntries.map(e => ({ name: e.name, path: e.requestedPath, available: !e.errorCode && e.path !== undefined && e.permissions.read === true && e.permissions.execute === true, isSymlink: e.isSymlink }));
201
- if (previous && !sameSnapshot(previous.info, info))
202
- reject('HOST_DIRECTORY_CHANGED');
203
- check(c);
204
- if (trusted)
205
- guardTrust(c, trusted.identity);
206
- const selected = { kind: 'selection', target, context: c, ...(trusted ? { identity: trusted.identity } : {}), info };
184
+ entries = rawEntries.map(e => ({ name: e.name, path: e.requestedPath, available: !e.errorCode && e.path !== undefined, isSymlink: e.isSymlink }));
185
+ if (target === 'local') {
186
+ if (previous && !sameSnapshot(previous.info, info))
187
+ reject('HOST_DIRECTORY_CHANGED');
188
+ check(c);
189
+ }
190
+ const selected = { kind: 'selection', target, context: c, ...(trusted ? { host: trusted.host } : {}), info };
207
191
  const result = { target, path: info.path, parentPath: info.parentPath, entries, selectionToken: seal(selected), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', selection: selected, after: nextAfter }) } : {}), ...(notice ? { notice } : {}) };
208
192
  if (Buffer.byteLength(JSON.stringify(result)) > o.metadataMaxBytes)
209
193
  reject('HOST_DIRECTORY_PAGE_TOO_LARGE');
@@ -215,67 +199,48 @@ export function createWorkspaceDirectoryPicker(o) {
215
199
  const s = unseal(r.selectionToken);
216
200
  if (s.kind !== 'selection' || s.target !== 'host')
217
201
  reject('WORKSPACE_PICKER_INVALID');
218
- const info = await inspect(s), t = await trust(s.context);
219
- if (t.identity !== s.identity)
220
- reject('WORKSPACE_LOCATION_CONFLICT');
202
+ const info = s.info, t = hostTarget();
203
+ if (t.host !== s.host)
204
+ throw new NeedError({ ...need('WORKSPACE_PICKER_INVALID'), message: '当前已连接另一台主机,请返回并重新浏览要操作的主机目录。', officialReason: 'SELECTED_HOST_UNAVAILABLE' });
221
205
  if (!o.hostDirectories?.create)
222
206
  reject('DEPENDENCY_REQUIRED');
223
- const child = await remote(signal => o.hostDirectories.create(t.target, info.path, r.name, info.identity, signal));
224
- guardTrust(s.context, t.identity);
207
+ const child = await remote(signal => o.hostDirectories.create(t.target, info.path, r.name, signal));
225
208
  return browse({ target: 'host', path: child.path });
226
209
  }
227
- function sameSource(item, s) {
228
- if (item?.status !== 'selected' || item.source !== s.target)
229
- return false;
230
- if (s.target === 'local')
231
- return true;
232
- // refresh revalidates the old binding's requested path and entry. A newly
233
- // browsed alias may share its canonical directory without rewriting that binding.
234
- const a = item.remote, b = s.info;
235
- if (!a || a.path !== b.path || a.identity.device !== b.identity.device || a.identity.inode !== b.identity.inode || !['read', 'write', 'execute'].every(k => a.permissions[k] === b.permissions[k]))
236
- return false;
237
- const current = take(o.api.getModelCatalogTarget('codex')).target;
238
- return item.host?.host === current.host && item.host.username === current.username && item.host.port === current.port;
239
- }
210
+ function sameSource(item, s) { return s.target === 'local' ? item?.status === 'selected' && item.source === 'local' : item?.source === 'host' && item.host?.host === s.host && item.remote?.path === s.info.path; }
240
211
  function registrationTitle(j) { return (basename(j.selectedPath) || j.selectedPath) + ' · 正在添加 · ' + j.id; }
212
+ async function selectHost(s) {
213
+ if (disposed)
214
+ reject('DISPOSED');
215
+ if (!s.host || !path(s.info.path))
216
+ reject('WORKSPACE_PICKER_INVALID');
217
+ const existing = o.locations.getWorkspaceLocationState().items.find(i => i.source === 'host' && i.host?.host === s.host && i.remote?.path === s.info.path);
218
+ const name = hash([s.host, s.info.path]), localPath = existing?.localPath ?? join(mappingRoot, name);
219
+ await privateDirectory(mappingRoot);
220
+ await mkdir(localPath, { recursive: true, mode: 0o700 });
221
+ const workspace = o.registry.list().find(w => w.path === localPath) ?? await o.registry.create(localPath, (basename(s.info.path) || s.info.path) + '(远程主机)');
222
+ const saved = take(await o.locations.selectWorkspaceLocation({ ...context(), workspaceId: workspace.id, expectedBindingId: null, source: 'host', host: s.host, path: s.info.path }));
223
+ if (!sameSource(saved.items.find(i => i.workspaceId === workspace.id), s))
224
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
225
+ await save({ ...state, lastTarget: 'host', host: { host: s.host, path: s.info.path }, mappings: [...state.mappings.filter(m => m.name !== name), { name, host: s.host, remotePath: s.info.path }] });
226
+ return ok({ path: localPath, workspaceId: workspace.id, source: 'host' });
227
+ }
241
228
  async function select(r) {
242
229
  if (!object(r) || !strict(r, ['selectionToken']))
243
230
  reject('WORKSPACE_PICKER_INVALID');
244
231
  const selected = unseal(r.selectionToken);
245
232
  if (selected.kind !== 'selection')
246
233
  reject('WORKSPACE_PICKER_INVALID');
247
- const s = selected, info = await inspect(s), guard = () => { check(s.context); if (s.identity)
248
- guardTrust(s.context, s.identity); };
249
- const mapped = s.target === 'host' ? hash([s.identity, info.path]) : undefined, localPath = mapped ? join(mappingRoot, mapped) : info.path;
234
+ if (selected.target === 'host')
235
+ return selectHost(selected);
236
+ const s = selected, info = await inspect(s), guard = () => check(s.context);
237
+ const localPath = info.path;
250
238
  const previous = { ...(state.lastTarget ? { lastTarget: state.lastTarget } : {}), ...(state.local ? { local: state.local } : {}), ...(state.host ? { host: structuredClone(state.host) } : {}) };
251
- const j = { id: randomUUID(), source: s.target, path: localPath, selectedPath: info.path, ...(s.identity ? { identity: s.identity, mappingName: mapped } : {}), originalIds: o.registry.list().map(w => w.id) };
239
+ const j = { id: randomUUID(), source: s.target, path: localPath, selectedPath: info.path, originalIds: o.registry.list().map(w => w.id) };
252
240
  if (!o.registry.list().some(w => w.path === localPath))
253
241
  activePath = localPath;
254
242
  try {
255
- if (mapped) {
256
- await privateDirectory(mappingRoot);
257
- if (await realpath(mappingRoot) !== mappingRoot)
258
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
259
- const known = state.mappings.find(m => m.name === mapped);
260
- try {
261
- const observed = await mappingPath(j);
262
- if (known && (known.device !== observed.device || known.inode !== observed.inode) && o.registry.list().some(w => w.path === localPath))
263
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
264
- if (!known && (await readdir(localPath)).length !== 0)
265
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
266
- Object.assign(j, observed);
267
- }
268
- catch (e) {
269
- if (e.code !== 'ENOENT')
270
- throw e;
271
- await mkdir(localPath, { mode: 0o700 });
272
- Object.assign(j, await mappingPath(j));
273
- }
274
- const current = { name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode };
275
- await save({ ...state, mappings: [...state.mappings.filter(m => m.name !== mapped), current] }, guard);
276
- }
277
- else
278
- Object.assign(j, await nativePath(localPath));
243
+ Object.assign(j, await nativePath(localPath));
279
244
  guard();
280
245
  const matches = o.registry.list().filter(w => w.path === localPath);
281
246
  if (matches.length > 1)
@@ -305,13 +270,6 @@ export function createWorkspaceDirectoryPicker(o) {
305
270
  reject('WORKSPACE_LOCATION_CONFLICT');
306
271
  const c = { ...s.context, workspaceId: workspace.id, expectedBindingId: null };
307
272
  let request = { ...c, source: 'local' };
308
- if (s.target === 'host') {
309
- const page = take(await o.locations.browseWorkspaceHostDirectories({ ...c, path: info.requestedPath }));
310
- guard();
311
- if (!sameInfo(info, page))
312
- reject('HOST_DIRECTORY_CHANGED');
313
- request = { ...c, source: 'host', selectionToken: page.selectionToken };
314
- }
315
273
  await inspect(s);
316
274
  guard();
317
275
  const saved = take(await o.locations.selectWorkspaceLocation(request));
@@ -320,7 +278,7 @@ export function createWorkspaceDirectoryPicker(o) {
320
278
  reject('WORKSPACE_LOCATION_CONFLICT');
321
279
  j.bindingId = itemAfter.bindingId;
322
280
  }
323
- const n = mapped ? await mappingPath(j) : await nativePath(localPath);
281
+ const n = await nativePath(localPath);
324
282
  if (n.device !== j.device || n.inode !== j.inode)
325
283
  reject('WORKSPACE_LOCATION_CONFLICT');
326
284
  await inspect(s);
@@ -335,9 +293,7 @@ export function createWorkspaceDirectoryPicker(o) {
335
293
  reject('WORKSPACE_LOCATION_CONFLICT'); bindingGuard(); };
336
294
  finalGuard();
337
295
  // The registration path is blocked only while this call is in flight.
338
- const next = { ...state, lastTarget: s.target, ...(s.target === 'local' ? { local: info.path } : { host: { identity: s.identity, path: info.path } }), mappings: state.mappings.filter(m => m.name !== mapped) };
339
- if (mapped)
340
- next.mappings.push({ name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode });
296
+ const next = { ...state, lastTarget: s.target, local: info.path, mappings: state.mappings };
341
297
  await save(next, finalGuard);
342
298
  finalGuard();
343
299
  return ok({ path: localPath, workspaceId: workspace.id, source: s.target });
@@ -6,18 +6,21 @@ export interface WorkspaceLocationItem {
6
6
  localPath: string;
7
7
  bindingId: string | null;
8
8
  source: 'local' | 'host' | null;
9
- status: 'unselected' | 'selected' | 'invalid';
10
- execution: 'not-selected' | 'local-pending' | 'host-pending';
11
- remote?: HostDirectoryInfo;
9
+ status?: 'unselected' | 'selected' | 'invalid';
10
+ execution?: 'not-selected' | 'local-pending';
11
+ remote?: Pick<HostDirectoryInfo, 'path'>;
12
12
  host?: {
13
13
  host: string;
14
- username: string;
15
- port: number;
14
+ username?: string;
15
+ port?: number;
16
16
  };
17
17
  need?: ConnectNeed;
18
18
  }
19
- export interface HostWorkspaceResolveContext extends WorkspaceLocationContext {
20
- expectedBindingId: string;
19
+ /** 会话创建时记录;由 X 持久化,后续轮次只读同一来源。 */
20
+ export interface HostWorkspaceResolveContext {
21
+ source: 'host';
22
+ host: string;
23
+ path: string;
21
24
  }
22
25
  export interface WorkspaceLocationState {
23
26
  host: {
@@ -51,8 +54,8 @@ export interface WorkspaceBrowsePage extends HostDirectoryInfo {
51
54
  bindingId: string | null;
52
55
  host: {
53
56
  host: string;
54
- username: string;
55
- port: number;
57
+ username?: string;
58
+ port?: number;
56
59
  };
57
60
  selectionToken: string;
58
61
  entries: (HostDirectoryEntry & {
@@ -63,7 +66,11 @@ export interface WorkspaceBrowsePage extends HostDirectoryInfo {
63
66
  }
64
67
  export type WorkspaceSelectRequest = WorkspaceLocationContext & ({
65
68
  source: 'local';
66
- } | {
69
+ } | ({
67
70
  source: 'host';
71
+ } & ({
68
72
  selectionToken: string;
69
- });
73
+ } | {
74
+ host: string;
75
+ path: string;
76
+ })));
@@ -1,7 +1,7 @@
1
- import type { ConnectApi, Result, SshTarget } from './api.ts';
1
+ import type { ConnectApi, Result } from './api.ts';
2
2
  import type { NativeWorkspaceRegistry } from './native-workspace.ts';
3
3
  import type { WorkspaceLocationItem, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
- import type { HostDirectoryInfo, createHostDirectories } from './host-directories.ts';
4
+ import type { createHostDirectories } from './host-directories.ts';
5
5
  import { type LocalWorkspaceContext, type LocalWorkspaceContextRequest } from './local-workspace-context.ts';
6
6
  interface Options {
7
7
  isWorkspacePending?: (workspaceId: string) => boolean;
@@ -16,16 +16,6 @@ interface Options {
16
16
  }
17
17
  export declare function createWorkspaceLocations(o: Options): {
18
18
  captureWorkspacePickerGuard: (workspaceId: string, expectedBindingId: string) => () => void;
19
- withHostBinding: <T>(input: import("./workspace-location-types.ts").HostWorkspaceResolveContext, run: (value: {
20
- directory: HostDirectoryInfo;
21
- target: SshTarget;
22
- local: {
23
- path: string;
24
- device: number;
25
- inode: number;
26
- };
27
- revision: number;
28
- }, guard: () => void) => Promise<Result<T>>, finalize?: () => void) => Promise<Result<T>>;
29
19
  getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
30
20
  getWorkspaceLocationState: () => {
31
21
  host: {
@@ -1,4 +1,4 @@
1
- import { renameSync, realpathSync, lstatSync } from 'node:fs';
1
+ import { renameSync } 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';
@@ -10,9 +10,8 @@ const queues = new Map();
10
10
  const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
11
11
  const token = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
12
12
  const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
13
- const checksum = (r, historicalRevoked) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined, ...(historicalRevoked === undefined ? [] : [historicalRevoked])]);
13
+ const checksum = (r) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined]);
14
14
  const sameNative = (a, b) => a.workspaceId === b.workspaceId && a.localPath === b.localPath && a.localDev === b.localDev && a.localIno === b.localIno;
15
- const sameDirectory = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && JSON.stringify(a.identity) === JSON.stringify(b.identity) && JSON.stringify(a.entryIdentity) === JSON.stringify(b.entryIdentity);
16
15
  export function createWorkspaceLocations(o) {
17
16
  const controllers = new Set();
18
17
  const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'locations.json'), secret = randomBytes(32), listeners = new Set();
@@ -93,17 +92,28 @@ export function createWorkspaceLocations(o) {
93
92
  const data = JSON.parse(raw);
94
93
  if (!obj(data) || data.schemaVersion !== 1 || !Array.isArray(data.items))
95
94
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
96
- const items = data.items.filter(r => !obj(r) || r.source !== 'legacy-host');
97
- const ids = new Set(), active = new Set();
98
- for (const r of items) {
99
- if (!obj(r) || !token(r.bindingId) || !token(r.workspaceId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || !['local', 'host'].includes(r.source) || typeof r.active !== 'boolean' || r.legacyBindingId !== undefined || r.revoked !== undefined && (r.source !== 'host' || !['HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE'].includes(r.revoked)) || r.key !== checksum(r, r.revoked) || ids.has(r.bindingId) || r.active && active.has(r.workspaceId) || r.source !== 'local' && (!obj(r.remote) || !isAbsolute(r.remote.path) || !isAbsolute(r.remote.requestedPath) || !obj(r.remote.identity) || !obj(r.remote.entryIdentity) || !obj(r.remote.permissions) || !obj(r.host) || !token(r.host.host) || !token(r.host.username) || !Number.isSafeInteger(r.host.port) || !(/^[a-f0-9]{64}$/.test(r.identity))))
95
+ const result = [], ids = new Set(), active = new Set();
96
+ for (const r of data.items) {
97
+ if (r?.source === 'legacy-host' || r?.source === 'host' && r.active === false)
98
+ continue;
99
+ if (!obj(r) || !token(r.workspaceId) || typeof r.active !== 'boolean' || r.active && active.has(r.workspaceId))
100
100
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
101
- ids.add(r.bindingId);
101
+ if (r.source === 'host') {
102
+ // 旧记录仅取主机与路径;旧 identity/key/dev/ino 不再属于主机来源合同。
103
+ if (!obj(r.host) || !token(r.host.host) || !obj(r.remote) || !token(r.remote.path) || !isAbsolute(r.remote.path))
104
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
105
+ result.push({ workspaceId: r.workspaceId, source: 'host', active: r.active, host: { host: r.host.host }, remote: { path: r.remote.path } });
106
+ }
107
+ else {
108
+ if (r.source !== 'local' || !token(r.bindingId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || r.key !== checksum(r) || r.legacyBindingId !== undefined || r.revoked !== undefined || ids.has(r.bindingId))
109
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
110
+ ids.add(r.bindingId);
111
+ result.push(r);
112
+ }
102
113
  if (r.active)
103
114
  active.add(r.workspaceId);
104
- delete r.revoked;
105
115
  }
106
- return items;
116
+ return result;
107
117
  }
108
118
  function guardStoredBinding(expected) {
109
119
  const current = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === expected.workspaceId);
@@ -114,7 +124,8 @@ export function createWorkspaceLocations(o) {
114
124
  }
115
125
  async function save(items, beforeCommit, context) {
116
126
  for (const r of items)
117
- r.key = checksum(r);
127
+ if (r.source === 'local')
128
+ r.key = checksum(r);
118
129
  const bytes = JSON.stringify({ schemaVersion: 1, items }) + '\n';
119
130
  if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || Buffer.byteLength(bytes) > o.metadataMaxBytes)
120
131
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
@@ -129,7 +140,8 @@ export function createWorkspaceLocations(o) {
129
140
  await h.close();
130
141
  }
131
142
  await beforeCommit();
132
- check(context);
143
+ if (context)
144
+ check(context);
133
145
  renameSync(temp, file);
134
146
  const d = await open(root, 'r');
135
147
  try {
@@ -170,7 +182,7 @@ export function createWorkspaceLocations(o) {
170
182
  const current = stored.find(r => r.active && r.workspaceId === c.workspaceId);
171
183
  if ((current?.bindingId ?? null) !== c.expectedBindingId)
172
184
  reject('WORKSPACE_LOCATION_CONFLICT');
173
- if (current && !sameNative(current, n))
185
+ if (current?.source === 'local' && !sameNative(current, n))
174
186
  reject('WORKSPACE_LOCATION_INVALID');
175
187
  return { stored, n, current };
176
188
  }
@@ -185,15 +197,8 @@ export function createWorkspaceLocations(o) {
185
197
  controllers.delete(controller);
186
198
  }
187
199
  }
188
- async function target(c) {
189
- const t = o.api.getModelCatalogTarget('codex');
190
- if (!t.ok)
191
- throw new NeedError(t.error);
192
- const trust = await readPrivate(t.value.target.knownHostsFile, o.metadataMaxBytes);
193
- check(c);
194
- const value = t.value.target;
195
- return { value, identity: hash([value.host, value.username, value.port, value.projectRoot, value.session, trust]) };
196
- }
200
+ function target() { const t = o.api.getModelCatalogTarget('codex'); if (!t.ok)
201
+ throw new NeedError(t.error); return t.value.target; }
197
202
  const seal = (data) => { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); return body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); };
198
203
  function unseal(value) {
199
204
  if (!token(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
@@ -211,17 +216,17 @@ export function createWorkspaceLocations(o) {
211
216
  reject('WORKSPACE_LOCATION_CONFLICT');
212
217
  }
213
218
  }
214
- function directoryChange(a, b) {
215
- 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)
216
- return 'HOST_DIRECTORY_CHANGED';
217
- if (b.permissions.read === false || b.permissions.execute === false)
218
- return 'HOST_DIRECTORY_UNREADABLE';
219
- if (['read', 'write', 'execute'].some(k => typeof a.permissions[k] === 'boolean' && typeof b.permissions[k] === 'boolean' && a.permissions[k] !== b.permissions[k]))
220
- return 'HOST_DIRECTORY_CHANGED';
221
- }
222
- async function items(stored, inspectHost = false, c = connection()) {
219
+ async function items(stored) {
223
220
  const result = [];
224
221
  for (const w of o.registry.list()) {
222
+ const r = stored.find(r => r.active && r.workspaceId === w.id);
223
+ if (r?.source === 'host') {
224
+ const title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(远程主机)';
225
+ if (w.setTitle && w.title !== title)
226
+ await w.setTitle(title);
227
+ result.push({ workspaceId: w.id, workspaceName: title, localPath: w.path, bindingId: null, source: 'host', host: r.host, remote: r.remote });
228
+ continue;
229
+ }
225
230
  let n;
226
231
  try {
227
232
  n = await native(w.id);
@@ -230,140 +235,72 @@ export function createWorkspaceLocations(o) {
230
235
  result.push({ workspaceId: w.id, workspaceName: w.title, localPath: w.path, bindingId: null, source: null, status: 'invalid', execution: 'not-selected', need: need('WORKSPACE_LOCATION_INVALID') });
231
236
  continue;
232
237
  }
233
- const r = stored.find(r => r.active && r.workspaceId === w.id);
234
- const base = { workspaceId: w.id, workspaceName: w.title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null };
235
- if (r) {
236
- let valid = sameNative(r, n), error;
237
- // 来源来自本插件的原生路径绑定,离线仍可显示;不改目录或员工自取名称。
238
- if (valid && w.setTitle) {
239
- const title = w.title.replace(/(本机)$|(远程主机)$/u, '') + (r.source === 'local' ? '(本机)' : '(远程主机)');
240
- if (title !== w.title) {
241
- await w.setTitle(title);
242
- check(c);
243
- }
244
- base.workspaceName = title;
245
- }
246
- if (valid && r.source !== 'local') {
247
- try {
248
- valid = (await target(c)).identity === r.identity;
249
- if (valid && inspectHost && r.source === 'host') {
250
- const t = await target(c);
251
- check(c);
252
- const inspected = o.hostDirectories ? await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal)) : fail('DEPENDENCY_REQUIRED');
253
- check(c);
254
- if (!inspected.ok)
255
- error = inspected.error.code;
256
- else {
257
- const changed = directoryChange(r.remote, inspected.value);
258
- if (changed) {
259
- error = changed;
260
- }
261
- else if (Object.values(inspected.value.permissions).includes(null))
262
- error = 'HOST_DIRECTORY_UNREADABLE';
263
- }
264
- }
265
- }
266
- catch (e) {
267
- check(c);
268
- valid = false;
269
- error = e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED';
270
- }
271
- }
272
- result.push({ ...base, source: r.source, status: valid && !error ? 'selected' : 'invalid', execution: r.source === 'local' ? 'local-pending' : 'host-pending', ...(r.remote ? { remote: r.remote, host: r.host } : {}), ...(!valid || error ? { need: need(error ?? 'WORKSPACE_LOCATION_INVALID') } : {}) });
238
+ let title = w.title;
239
+ if (r && w.setTitle) {
240
+ title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(本机)';
241
+ if (title !== w.title)
242
+ await w.setTitle(title);
273
243
  }
274
- else
275
- result.push({ ...base, source: null, status: 'unselected', execution: 'not-selected' });
244
+ const valid = !r || sameNative(r, n);
245
+ result.push({ workspaceId: w.id, workspaceName: title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null, source: r ? 'local' : null, status: r ? (valid ? 'selected' : 'invalid') : 'unselected', execution: r ? 'local-pending' : 'not-selected', ...(!valid ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
276
246
  }
277
247
  return result;
278
248
  }
279
- async function refresh(c = connection()) {
280
- try {
281
- check(c);
282
- await prepare();
283
- const stored = await records();
284
- const next = await items(stored, true, c);
285
- check(c);
286
- publish(next);
287
- return ok(structuredClone(snapshot));
288
- }
289
- catch (e) {
290
- if (exact(c))
291
- publish(snapshot.items, e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED');
292
- throw e;
293
- }
249
+ async function refresh() { try {
250
+ await prepare();
251
+ publish(await items(await records()));
252
+ return ok(structuredClone(snapshot));
294
253
  }
254
+ catch (e) {
255
+ publish(snapshot.items, e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED');
256
+ throw e;
257
+ } }
295
258
  function strict(value, keys) {
296
259
  if (Object.keys(value).some(k => !keys.includes(k)))
297
260
  reject('WORKSPACE_LOCATION_INVALID');
298
261
  }
299
262
  async function browse(c) {
300
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'path', 'cursor', 'pageSize']);
301
- if (c.path !== undefined && (!isAbsolute(c.path) || c.path.includes('\0')) || c.path !== undefined && c.cursor !== undefined || c.pageSize !== undefined && (!Number.isSafeInteger(c.pageSize) || c.pageSize < 1))
263
+ await prepare();
264
+ if (!token(c.workspaceId) || c.path !== undefined && (!token(c.path) || !isAbsolute(c.path)))
302
265
  reject('HOST_DIRECTORY_INVALID');
303
- const x = await context(c), t = await target(c);
266
+ const t = target();
304
267
  if (!o.hostDirectories)
305
268
  reject('DEPENDENCY_REQUIRED');
306
- let request = { pageSize: c.pageSize ?? o.pageSize, ...(c.path !== undefined ? { path: c.path } : {}) };
307
- if (c.cursor) {
308
- const saved = unseal(c.cursor);
309
- if (saved.kind !== 'cursor' || JSON.stringify(saved.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }) || !sameNative(saved.native, x.n) || saved.identity !== t.identity || c.pageSize !== undefined && c.pageSize !== saved.request.pageSize)
310
- reject('WORKSPACE_LOCATION_CONFLICT');
311
- request = saved.request;
312
- }
313
- const page = await remote(c, signal => o.hostDirectories.browse(t.value, request, signal));
314
- check(c);
269
+ const previous = c.cursor ? unseal(c.cursor) : undefined;
270
+ const page = await remote(connection(), signal => o.hostDirectories.browse(t, { ...(c.path ? { path: c.path } : previous ? { path: previous.path } : {}), pageSize: c.pageSize ?? o.pageSize, ...(previous ? { after: previous.after } : {}) }, signal));
315
271
  if (!page.ok)
316
272
  return page;
317
- if (!sameNative(await native(c.workspaceId), x.n))
318
- reject('WORKSPACE_LOCATION_CONFLICT');
319
- check(c);
320
- const base = { context: { instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }, native: x.n, identity: t.identity };
321
- const choose = (info) => seal({ kind: 'selection', ...base, info });
322
- const { entries, nextAfter, ...info } = page.value;
323
- return ok({ ...info, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host: { host: t.value.host, username: t.value.username, port: t.value.port }, selectionToken: choose(info), pageSize: request.pageSize, entries: entries.map(e => ({ ...e, ...(e.path && e.identity && !e.errorCode ? { selectionToken: choose({ requestedPath: e.requestedPath, path: e.path, parentPath: info.path, identity: e.identity, entryIdentity: e.entryIdentity, isSymlink: e.isSymlink, permissions: e.permissions }) } : {}) })), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', ...base, request: { path: info.requestedPath, pageSize: request.pageSize, after: nextAfter, expected: info.identity } }) } : {}) });
273
+ const host = { host: t.host, username: t.username, port: t.port };
274
+ return ok({ ...page.value, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host, pageSize: c.pageSize ?? o.pageSize, selectionToken: seal({ host: t.host, path: page.value.path }), entries: page.value.entries.map(e => ({ ...e, selectionToken: seal({ host: t.host, path: e.path ?? e.requestedPath }) })), ...(page.value.nextAfter ? { nextCursor: seal({ path: page.value.path, after: page.value.nextAfter }) } : {}) });
324
275
  }
325
276
  async function select(c) {
326
- if (!obj(c))
327
- reject('WORKSPACE_LOCATION_INVALID');
328
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source', ...(c.source === 'host' ? ['selectionToken'] : [])]);
329
- if (!['local', 'host'].includes(c.source))
277
+ if (!obj(c) || !['local', 'host'].includes(c.source))
330
278
  reject('WORKSPACE_LOCATION_INVALID');
331
- const x = await context(c);
332
- let r = { ...x.n, bindingId: randomUUID(), source: c.source, active: true, key: '' };
333
- if (c.source !== 'local') {
334
- const t = await target(c);
335
- if (!o.hostDirectories)
336
- reject('DEPENDENCY_REQUIRED');
337
- const selected = unseal(c.selectionToken);
338
- if (selected.kind !== 'selection' || !sameNative(selected.native, x.n) || selected.identity !== t.identity || JSON.stringify(selected.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }))
339
- reject('WORKSPACE_LOCATION_CONFLICT');
340
- const selectedInfo = selected.info;
341
- const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, selectedInfo.requestedPath, signal));
342
- check(c);
343
- if (!inspected.ok)
344
- return inspected;
345
- if (!sameDirectory(selectedInfo, inspected.value))
346
- reject('HOST_DIRECTORY_CHANGED');
347
- if (inspected.value.permissions.read !== true || inspected.value.permissions.execute !== true)
348
- reject('HOST_DIRECTORY_UNREADABLE');
349
- r = { ...r, remote: inspected.value, identity: t.identity, host: { host: t.value.host, username: t.value.username, port: t.value.port } };
279
+ if (c.source === 'host') {
280
+ await prepare();
281
+ const selected = 'selectionToken' in c ? unseal(c.selectionToken) : c;
282
+ if (!token(c.workspaceId) || !token(selected.host) || !token(selected.path) || !isAbsolute(selected.path))
283
+ reject('HOST_DIRECTORY_INVALID');
284
+ const stored = await records();
285
+ for (const old of stored)
286
+ if (old.workspaceId === c.workspaceId)
287
+ old.active = false;
288
+ stored.push({ workspaceId: c.workspaceId, source: 'host', active: true, host: { host: selected.host }, remote: { path: selected.path } });
289
+ await save(stored, async () => { });
290
+ publish(await items(stored));
291
+ return ok(structuredClone(snapshot));
350
292
  }
351
- if (!sameNative(await native(c.workspaceId), x.n))
352
- reject('WORKSPACE_LOCATION_CONFLICT');
353
- check(c);
354
- if (x.current && x.current.source === r.source && JSON.stringify(x.current.remote) === JSON.stringify(r.remote) && x.current.identity === r.identity)
293
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source']);
294
+ const x = await context(c);
295
+ if (x.current?.source === 'local')
355
296
  return ok(structuredClone(snapshot));
297
+ const r = { ...x.n, bindingId: randomUUID(), source: 'local', active: true, key: '' };
356
298
  for (const old of x.stored)
357
299
  if (old.active && old.workspaceId === c.workspaceId)
358
300
  old.active = false;
359
- if (x.stored.some(old => old.bindingId === r.bindingId))
360
- reject('WORKSPACE_LOCATION_CONFLICT');
361
301
  x.stored.push(r);
362
- await save(x.stored, async () => {
363
- if (!sameNative(await native(c.workspaceId), x.n))
364
- reject('WORKSPACE_LOCATION_CONFLICT');
365
- check(c);
366
- }, c);
302
+ await save(x.stored, async () => { if (!sameNative(await native(c.workspaceId), x.n))
303
+ reject('WORKSPACE_LOCATION_CONFLICT'); check(c); }, c);
367
304
  publish(await items(x.stored));
368
305
  check(c);
369
306
  return ok(structuredClone(snapshot));
@@ -424,93 +361,20 @@ export function createWorkspaceLocations(o) {
424
361
  const c = { instanceId: request.instanceId, epoch: request.epoch, workspaceId: request.workspaceId, expectedBindingId: request.expectedBindingId };
425
362
  return serial(() => localContext(c));
426
363
  }
427
- function withHostBinding(input, run, finalize = () => { }) {
428
- const c = structuredClone(input);
429
- return serial(async () => {
430
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId']);
431
- if (!token(c.expectedBindingId))
432
- reject('WORKSPACE_LOCATION_INVALID');
433
- checkPending(c.workspaceId);
434
- const x = await context(c), r = x.current;
435
- if (!r || r.source !== 'host' || !r.remote)
436
- reject('WORKSPACE_LOCATION_CONFLICT');
437
- const t = await target(c);
438
- check(c);
439
- if (t.identity !== r.identity)
440
- reject('WORKSPACE_LOCATION_INVALID');
441
- const bytes = await readPrivate(file, o.metadataMaxBytes), registeredPath = registeredLocalPath(c.workspaceId);
442
- const guard = () => {
443
- checkPending(c.workspaceId);
444
- check(c);
445
- const now = o.api.getConnectionState();
446
- if (now.phase !== 'connected')
447
- reject('CONNECTION_LOST');
448
- const latest = o.api.getModelCatalogTarget('codex');
449
- if (!latest.ok)
450
- throw new NeedError(latest.error);
451
- const v = latest.value.target;
452
- if (hash([v.host, v.username, v.port, v.projectRoot, v.session, readPrivateSync(v.knownHostsFile, o.metadataMaxBytes)]) !== t.identity)
453
- reject('WORKSPACE_LOCATION_INVALID');
454
- if (readPrivateSync(file, o.metadataMaxBytes) !== bytes)
455
- reject('WORKSPACE_LOCATION_CONFLICT');
456
- if (registeredLocalPath(c.workspaceId) !== registeredPath)
457
- reject('WORKSPACE_LOCATION_INVALID');
458
- try {
459
- const path = realpathSync(registeredPath), st = lstatSync(path);
460
- if (path !== x.n.localPath || !st.isDirectory() || st.dev !== x.n.localDev || st.ino !== x.n.localIno)
461
- reject('WORKSPACE_LOCATION_INVALID');
462
- }
463
- catch (e) {
464
- if (e instanceof NeedError)
465
- throw e;
466
- reject('WORKSPACE_LOCATION_INVALID');
467
- }
468
- };
469
- guard();
470
- if (!o.hostDirectories)
471
- reject('DEPENDENCY_REQUIRED');
472
- const current = await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal));
473
- if (!current.ok)
474
- throw new NeedError(current.error);
475
- const changed = directoryChange(r.remote, current.value);
476
- if (changed)
477
- reject(changed);
478
- if (Object.values(current.value.permissions).includes(null))
479
- reject('HOST_DIRECTORY_UNREADABLE');
480
- const value = { directory: current.value, target: structuredClone(t.value), local: { path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, revision: snapshot.revision };
481
- const result = await run(value, guard);
482
- if (!result.ok)
483
- return result;
484
- guard();
485
- finalize();
486
- return result;
487
- });
488
- }
489
364
  function captureWorkspacePickerGuard(workspaceId, expectedBindingId) {
490
365
  const original = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === workspaceId);
491
- if (!original || original.bindingId !== expectedBindingId)
366
+ if (!original || original.source !== 'local' || original.bindingId !== expectedBindingId)
492
367
  reject('WORKSPACE_LOCATION_CONFLICT');
493
368
  const registeredPath = registeredLocalPath(workspaceId);
494
369
  return () => { guardStoredBinding(original); if (registeredLocalPath(workspaceId) !== registeredPath)
495
370
  reject('WORKSPACE_LOCATION_INVALID'); };
496
371
  }
497
- return { captureWorkspacePickerGuard, withHostBinding, 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)), observeConnection() {
372
+ return { captureWorkspacePickerGuard, 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)), observeConnection() {
498
373
  if (disposed)
499
374
  return;
500
375
  for (const controller of controllers)
501
376
  controller.abort();
502
- const connected = o.api.getConnectionState().phase === 'connected';
503
- publish(snapshot.items.map(item => {
504
- if (item.source !== 'host')
505
- return item;
506
- if (!connected)
507
- return { ...item, need: need('CONNECTION_LOST') };
508
- if (item.need?.code === 'CONNECTION_LOST' || item.need?.code === 'WORKSPACE_LOCATION_CONFLICT') {
509
- const { need: _, ...selected } = item;
510
- return selected;
511
- }
512
- return item;
513
- }));
377
+ publish(snapshot.items);
514
378
  }, dispose() {
515
379
  disposed = true;
516
380
  for (const controller of controllers)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.28",
3
+ "version": "0.7.29",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1"