@ai-workbench/connect 0.7.9 → 0.7.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/client/index.cjs +33 -13
- package/helper/host-directories.cjs +72 -0
- package/helper/remote-command.cjs +1 -1
- package/lib/api.d.ts +44 -1
- package/lib/api.js +1 -1
- package/lib/auth-diagnostics.d.ts +22 -0
- package/lib/auth-diagnostics.js +45 -0
- package/lib/auth-status.js +21 -8
- package/lib/components.d.ts +1 -1
- package/lib/components.js +106 -5
- package/lib/connect.d.ts +3 -0
- package/lib/connect.js +105 -23
- package/lib/connection-messages.d.ts +7 -0
- package/lib/connection-messages.js +6 -0
- package/lib/conversation-details.d.ts +3 -0
- package/lib/conversation-details.js +8 -7
- package/lib/cordis.d.ts +3 -1
- package/lib/defaults.d.ts +6 -0
- package/lib/defaults.js +2 -0
- package/lib/host-directories.d.ts +53 -0
- package/lib/host-directories.js +76 -0
- package/lib/index.d.ts +8 -1
- package/lib/index.js +9 -4
- package/lib/integration.js +6 -3
- package/lib/local-workspace-context.d.ts +46 -0
- package/lib/local-workspace-context.js +17 -0
- package/lib/login-diagnostics.d.ts +26 -0
- package/lib/login-diagnostics.js +42 -0
- package/lib/needs.js +12 -0
- package/lib/ports.d.ts +2 -0
- package/lib/processes.js +6 -5
- package/lib/profile-runtime.js +53 -22
- package/lib/ssh.js +37 -14
- package/lib/startup.d.ts +23 -2
- package/lib/startup.js +152 -41
- package/lib/workspace-bindings.d.ts +30 -1
- package/lib/workspace-bindings.js +1 -0
- package/lib/workspace-location-types.d.ts +65 -0
- package/lib/workspace-location-types.js +1 -0
- package/lib/workspace-locations.d.ts +45 -0
- package/lib/workspace-locations.js +427 -0
- package/node_modules/argparse/CHANGELOG.md +216 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
安装:在 DSH「插件 → 添加插件」填写 `@ai-workbench/connect@0.7.
|
|
1
|
+
安装:在 DSH「插件 → 添加插件」填写 `@ai-workbench/connect@0.7.11`,或运行 `dsh plugin --profile desktop add @ai-workbench/connect@0.7.11`。
|
|
2
2
|
|
|
3
3
|
# 远程主机连接插件(L)
|
|
4
4
|
|
|
@@ -23,7 +23,7 @@ minimumReleaseAgeExclude:
|
|
|
23
23
|
|
|
24
24
|
D13已通过[PR15](https://github.com/yzsnstotz/ai-workbench-connect/pull/15)合推main7915df5,移除前为909eabb;五项被拒产物及清单引用已撤除。不再生成新的聚合整包或验收ZIP,交付物为插件本身。
|
|
25
25
|
|
|
26
|
-
**插件版本0.7.
|
|
26
|
+
**插件版本0.7.11,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的输入。
|
|
27
27
|
|
|
28
28
|
开发使用Node24.13.1,依赖/缓存/构建和临时HOME放自有外接APFS。工程检查为`npm test`、`npm run check`、`npm run build`;它们不替代真实产品路径。安装走官方插件管理,本包自身只声明一个官方bundle条目,不使用wrapper或员工启动器。工人GUI按[SELFTEST](docs/SELFTEST.md)的PID和三项获准偏离执行,不操作owner实例。
|
|
29
29
|
|
|
@@ -33,7 +33,7 @@ L0.7.4按owner最新纠正分开供给和授权:Electron组件从自身官方
|
|
|
33
33
|
|
|
34
34
|
官方Electron内置Node会把.asar视作虚拟目录;组件缓存/解压专用physical-fs在Electron中使用original-fs核验物理归档,不修改全局process.noAsar。真实官方运行时新建及跨Node复用缓存均有回归。
|
|
35
35
|
|
|
36
|
-
0.7.5仅调整公开 npm 发布元数据和包内容:运行依赖继续随包,合同、源码、测试与证据不进包;无安装脚本。源码与合同见[项目仓库](https://github.com/yzsnstotz/ai-workbench-connect)。发布前可用官方插件页或上述命令安装已核验的tgz绝对路径。0.7.
|
|
36
|
+
0.7.5仅调整公开 npm 发布元数据和包内容:运行依赖继续随包,合同、源码、测试与证据不进包;无安装脚本。源码与合同见[项目仓库](https://github.com/yzsnstotz/ai-workbench-connect)。发布前可用官方插件页或上述命令安装已核验的tgz绝对路径。0.7.11本轮提供固定tgz,由编排决定发布;L不执行publish。
|
|
37
37
|
|
|
38
38
|
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主机代理方式。
|
|
39
39
|
|
|
@@ -72,3 +72,13 @@ RFC8628的 `verification_uri_complete` 是可选字段;固定0.163.0 CLI只提
|
|
|
72
72
|
诊断记录不自动过期、不按条数淘汰、没有隐藏总条数上限,本版没有清除入口。目录目标查询 `getModelCatalogTarget` 同步返回当前已核验且仍 connected 的内存深副本,不连接、不登录、不查凭据、不绑定项目;projectRoot 元数据不构成模型查询 cwd 授权。
|
|
73
73
|
|
|
74
74
|
本单工程证据见 [D19/D21](docs/evidence/2026-10-22-L-D19-D21/RESULT.md)。
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
### 0.7.10:登录检查失败的技术原因
|
|
78
|
+
|
|
79
|
+
员工正文和操作入口保持不变。管理员在远程主机连接的技术详情查看失败阶段:进程启动/输入/输出预算、SSH退出或信号、远端结果帧、官方登录状态JSON。保留固定错误类型、系统错误码、退出码、预期键缺失及stderr安全摘要;不显示原始命令输出、异常message或认证材料。消费方需保留已有ConnectNeed.officialReason进入会话技术详情。未知状态仍无法授权,不用等待/重试/放宽校验掩盖。沿用commandOutputMaxBytes,新增设置0;真实根因和产品验收以本轮回执为准。
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
0.7.10还修复实际登录检查结果与启动快照不一致:排队品牌queuedProviders与实际检查checkingProviders分开,成功/失败按品牌及当前代次发布;旧结果不能覆盖新结果。认证未知不自动触发反复重连检查。首次绑定前的失败可通过loginDiagnostics:1及五项登录诊断接口持久记录,在同一设置节“登录前技术详情”查看;与工作区绑定和普通会话详情隔离,不启动授权、不创建关联。详见提供方合同0.7.10 P1定稿。
|
|
83
|
+
|
|
84
|
+
0.7.11:登录前诊断可保留实例不一致时的实际双 ID;只有固定原因与观察字段一致时接纳,当前连接/事件作用域仍严格核验。详见提供方合同的“0.7.10 P1定稿”及“0.7.11:观察到的登录实例ID”两节。D16 旧安装迁移暂停,未包含迁移实现;等待 owner 决定更新前入口。
|
package/client/index.cjs
CHANGED
|
@@ -52,7 +52,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
52
52
|
"importInvalid": "这份连接资料无法通过检查,请向管理员领取有效的文件夹。",
|
|
53
53
|
"workspaceBlocked": "远程工作区暂时无法载入,请联系管理员。",
|
|
54
54
|
"workspaceSyncing": "正在更新远程工作区…",
|
|
55
|
-
"workspaceLimit": "
|
|
55
|
+
"workspaceLimit": "通过默认添加工作区选择本地文件夹,然后在本节明确选择本地或主机文件来源。本地文件不会自动上传。",
|
|
56
56
|
"unknown": "远程主机连接状态无法确认,请联系管理员。",
|
|
57
57
|
"checking": "正在检查远程主机连接…",
|
|
58
58
|
"details": "技术详情",
|
|
@@ -81,15 +81,17 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
81
81
|
const needKey=code=>code==='ENROLLMENT_RESULT_UNKNOWN'?'enrollmentUnknown':code==='ENROLLMENT_REJECTED'?'enrollmentRejected':code==='CONNECTION_UNKNOWN'?'unknown':code==='ENROLLMENT_INVALID'?'importInvalid':code==='DEPENDENCY_REQUIRED'?'notReady':['ENROLLMENT_REQUIRED','NETWORK_KEY_INVALID'].includes(code)?'enrollment':code==='SETTINGS_REQUIRED'?'settings':code==='LOGIN_FAILED'?'loginFailed':code==='POLICY_DENIED'?'denied':code==='LOGIN_PROMPT_INVALID'?'stale':code==='ACTION_FAILED'?'actionFailed':'unavailable';
|
|
82
82
|
function messageKey(s){if(!s||s.phase==='checking')return 'checking';if(s.phase==='blocked'||s.phase==='disposed')return needKey(s.technicalDetails?.code);if(s.phase==='login-required')return 'loginRequired';if(s.phase==='authorizing')return 'authorizing';return Object.keys(s.providerNeeds??{}).length?'loginUnknown':'complete';}
|
|
83
83
|
function createWorkbenchController(call,subscribe){
|
|
84
|
-
let state={value:undefined,error:''},disposed=false,started=false,off,revision=-1,instance,eventVersion=0;let download,componentSource;const retiredSources=new Set(),retiredDownloads=new Set(),retired=new Set(),listeners=new Set();
|
|
84
|
+
let state={value:undefined,error:''},disposed=false,started=false,off,revision=-1,instance,eventVersion=0;let download,componentSource,workspaceLocations;const retiredLocations=new Set();const retiredSources=new Set(),retiredDownloads=new Set(),retired=new Set(),listeners=new Set();
|
|
85
85
|
const publish=next=>{state=next;for(const fn of listeners)fn();};
|
|
86
|
-
const
|
|
86
|
+
const acceptLocations=(incoming,source)=>{if(!incoming)return incoming;const valid=typeof incoming.instanceId==='string'&&Number.isSafeInteger(incoming.epoch)&&incoming.epoch>=0&&Number.isSafeInteger(incoming.revision)&&incoming.revision>=0;if(!valid||retiredLocations.has(incoming.instanceId)||(workspaceLocations&&incoming.instanceId===workspaceLocations.instanceId&&(incoming.epoch<workspaceLocations.epoch||incoming.revision<workspaceLocations.revision))||(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId&&source==='http'))return workspaceLocations;if(workspaceLocations&&incoming.instanceId!==workspaceLocations.instanceId)retiredLocations.add(workspaceLocations.instanceId);workspaceLocations=incoming;return incoming;};
|
|
87
|
+
const locationCall=async(path,body)=>{const before=state.value?.workspaceLocations;const result=await call('/workspace-locations/'+path,'POST',body);if(disposed)return result;if(result?.ok&&path!=='browse'&&state.value&&before?.instanceId===state.value.workspaceLocations?.instanceId&&before?.epoch===state.value.workspaceLocations?.epoch&&(path!=='select'||sameLocationContext(state.value.workspaceLocations,body))){const next=acceptLocations(result.value,'http');publish({...state,value:{...state.value,workspaceLocations:next}});}return result;};
|
|
88
|
+
const accept=(value,source='event')=>{if(disposed)return;const next=value?.startup?.revision,id=value?.startup?.instanceId;if(typeof id!=='string'||!id||!Number.isSafeInteger(next)||next<0){publish({value:undefined,error:'CONNECTION_UNKNOWN'});return;}if(id!==instance){if(instance&&(source==='http'||retired.has(id)))return;if(instance)retired.add(instance);instance=id;revision=-1;}if(next<revision)return;revision=next;const incoming=value.loginComponent?.download;if(incoming){if(typeof incoming.instanceId!=='string'||!Number.isSafeInteger(incoming.revision)||incoming.revision<0||retiredDownloads.has(incoming.instanceId)||(download&&incoming.instanceId===download.instanceId&&incoming.revision<download.revision)||(download&&incoming.instanceId!==download.instanceId&&source==='http')){value={...value,loginComponent:{...value.loginComponent,download}};}else{if(download&&incoming.instanceId!==download.instanceId)retiredDownloads.add(download.instanceId);download=incoming;}}const choice=value.loginComponent?.source;if(choice){if(typeof choice.instanceId!=='string'||!Number.isSafeInteger(choice.revision)||choice.revision<0||retiredSources.has(choice.instanceId)||(componentSource&&choice.instanceId===componentSource.instanceId&&choice.revision<componentSource.revision)||(componentSource&&choice.instanceId!==componentSource.instanceId&&source==='http')){if(componentSource)value={...value,loginComponent:{...value.loginComponent,source:componentSource}};}else{if(componentSource&&choice.instanceId!==componentSource.instanceId)retiredSources.add(componentSource.instanceId);componentSource=choice;}}if(value.workspaceLocations)value={...value,workspaceLocations:acceptLocations(value.workspaceLocations,source)};publish({value,error:value.actionErrorCode||value.enrollment?.need?.code||(value.actionError?'ACTION_FAILED':'')});};
|
|
87
89
|
const failure=()=>{if(!disposed)publish({value:undefined,error:'CONNECTION_UNKNOWN'});};
|
|
88
|
-
return {readDetails:query=>call('/conversation-details?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}},start(){if(disposed||started)return;started=true;off=subscribe(value=>{eventVersion++;accept(value);},()=>{eventVersion++;failure();});const at=eventVersion;void call('/status','GET').then(value=>{if(at===eventVersion)accept(value,'http');},()=>{if(at===eventVersion)failure();});},dispose(){disposed=true;off?.();listeners.clear();}};
|
|
90
|
+
return {refreshWorkspaceLocations:()=>locationCall('refresh',{}),browseWorkspaceHostDirectories:body=>locationCall('browse',body),selectWorkspaceLocation:body=>locationCall('select',body),readLoginDiagnostics:query=>call('/login-diagnostics?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),readDetails:query=>call('/conversation-details?'+Object.entries(query).filter(([,v])=>v!==undefined).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'),'GET'),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}},start(){if(disposed||started)return;started=true;off=subscribe(value=>{eventVersion++;accept(value);},()=>{eventVersion++;failure();});const at=eventVersion;void call('/status','GET').then(value=>{if(at===eventVersion)accept(value,'http');},()=>{if(at===eventVersion)failure();});},dispose(){disposed=true;off?.();listeners.clear();}};
|
|
89
91
|
}
|
|
90
92
|
function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,action:workbench.action};}
|
|
91
93
|
function isLoginQuestion(state){const s=state?.startup;return s?.phase==='login-required'&&s.requestId&&s.provider&&s.logins?.[s.provider]===false&&!s.checkingProviders?.includes(s.provider)&&!s.providerNeeds?.[s.provider];}
|
|
92
|
-
function Details({state,error,t}){return h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({actionErrorCode:error||state?.actionErrorCode,enrollment:state?.enrollment,actionError:state?.actionError,inventory:state?.inventory,network:state?.network,connect:state?.connect,workspaces:state?.workspaces,checks:state?.startup?.technicalDetails,providerNeeds:state?.startup?.providerNeeds,checkingProviders:state?.startup?.checkingProviders,loginComponent:state?.loginComponent},null,2)));}
|
|
94
|
+
function Details({state,error,t}){return h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({actionErrorCode:error||state?.actionErrorCode,enrollment:state?.enrollment,actionError:state?.actionError,inventory:state?.inventory,network:state?.network,connection:state?.connection,connectionMessageSettings:state?.connectionMessageSettings,connect:state?.connect,workspaces:state?.workspaces,checks:state?.startup?.technicalDetails,providerNeeds:state?.startup?.providerNeeds,queuedProviders:state?.startup?.queuedProviders,checkingProviders:state?.startup?.checkingProviders,loginComponent:state?.loginComponent},null,2)));}
|
|
93
95
|
function Choices({state,action,t}){if(!isLoginQuestion(state))return null;const brand=state.startup.provider==='claude'?'Claude':'Codex';return h('div',null,h('button',{type:'button',onClick:()=>void action('/respond/'+state.startup.requestId+'/authorize')},t('signIn',{brand})),h('button',{type:'button',onClick:()=>void action('/respond/'+state.startup.requestId+'/defer')},t('later')));}
|
|
94
96
|
function Enrollment({state,action,t}){const value=state?.enrollment;if(!value)return null;return h('div',null,h('p',null,t('importHelp')),value.phase==='imported'?h('p',null,t('imported')):h('button',{type:'button',disabled:value.phase==='importing'||['ENROLLMENT_RESULT_UNKNOWN','ENROLLMENT_REJECTED'].includes(value.need?.code),onClick:()=>void action('/enrollment/import')},t(value.phase==='importing'?'importing':'import')));}
|
|
95
97
|
function observeNotice(node,notify){
|
|
@@ -106,12 +108,30 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
106
108
|
}
|
|
107
109
|
function WorkspaceNotices({state,action}){
|
|
108
110
|
const [retained,setRetained]=React.useState([]),sent=React.useRef(new Set());
|
|
109
|
-
const pending=(state?.workspaceBindings?.items??[]).filter(item=>item.notice.settings==='pending'&&['ready','unavailable'].includes(item.status));
|
|
111
|
+
const pending=(state?.workspaceBindings?.items??[]).filter(item=>(!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed'))&&item.notice.settings==='pending'&&['ready','unavailable'].includes(item.status));
|
|
110
112
|
const items=[...retained,...pending.filter(item=>!retained.some(old=>old.notice.noticeId===item.notice.noticeId))];
|
|
111
113
|
// Retain each sentence during this opening after its independent durable ACK.
|
|
112
114
|
React.useEffect(()=>{if(pending.length)setRetained(old=>[...old,...pending.filter(item=>!old.some(prior=>prior.notice.noticeId===item.notice.noticeId))]);},[pending.map(item=>item.notice.noticeId).join(',')]);
|
|
113
115
|
const visible=item=>{if(!sent.current.has(item.notice.noticeId)){sent.current.add(item.notice.noticeId);void action('/workspace-notice/'+item.notice.noticeId+'/displayed');}};
|
|
114
|
-
return h('div',null,...items.map(item=>h(WorkspaceNoticeRow,{key:item.notice.noticeId,item,onVisible:visible})));
|
|
116
|
+
return h('div',null,...items.filter(item=>!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed')).map(item=>h(WorkspaceNoticeRow,{key:item.notice.noticeId,item,onVisible:visible})));
|
|
117
|
+
}
|
|
118
|
+
const sameLocationContext=(state,context)=>state?.instanceId===context.instanceId&&state?.epoch===context.epoch&&state.items?.some(item=>item.workspaceId===context.workspaceId&&item.bindingId===context.expectedBindingId);
|
|
119
|
+
function DirectoryPermissions({permissions}){return h('p',null,...['read','write','execute'].map((key,index)=>(index?';':'')+({read:'读取',write:'写入',execute:'进入'}[key])+':'+(permissions?.[key]===true?'允许':permissions?.[key]===false?'不允许':'未知')),permissions?.reason?'('+permissions.reason+')':'');}
|
|
120
|
+
function WorkspaceLocationRow({item,locations,workbench}){
|
|
121
|
+
const [page,setPage]=React.useState(null),[path,setPath]=React.useState(''),[pageSize,setPageSize]=React.useState(String(locations.pageSize)),[loading,setLoading]=React.useState(false),[error,setError]=React.useState('');
|
|
122
|
+
const live=React.useRef(true),sequence=React.useRef(0),context={instanceId:locations.instanceId,epoch:locations.epoch,workspaceId:item.workspaceId,expectedBindingId:item.bindingId};
|
|
123
|
+
React.useEffect(()=>()=>{live.current=false;sequence.current++;},[]);
|
|
124
|
+
const current=()=>live.current&&sameLocationContext(workbench.getSnapshot().value?.workspaceLocations,context);
|
|
125
|
+
const browse=async(query={})=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const size=Number(pageSize);if(!/^\d+$/.test(pageSize)||!Number.isSafeInteger(size)||size<1){setError('每页条数需要正安全整数。');return;}const result=await workbench.browseWorkspaceHostDirectories({...context,pageSize:size,...query});if(at!==sequence.current||!current())return;if(!result?.ok){setError(result?.error?.message||'主机目录读取失败,未自动重试。');return;}const value=result.value;if(value.instanceId!==context.instanceId||value.epoch!==context.epoch||value.workspaceId!==context.workspaceId||value.bindingId!==context.expectedBindingId){setError('工作区或连接已变化,请刷新后重选。');return;}setPage(value);}catch{if(at===sequence.current&¤t())setError('主机目录读取失败,未自动重试。');}finally{if(at===sequence.current&¤t())setLoading(false);}};
|
|
126
|
+
const select=async(choice)=>{const at=++sequence.current;setLoading(true);setError('');setPage(null);try{const result=await workbench.selectWorkspaceLocation({...context,...choice});if(at!==sequence.current||!current())return;if(!result?.ok)setError(result?.error?.message||'位置未保存,请刷新后重选。');}catch{if(at===sequence.current&¤t())setError('位置保存结果无法确认,请刷新后核实;未自动重试。');}finally{if(at===sequence.current&¤t())setLoading(false);}};
|
|
127
|
+
const execution=item.execution==='local-pending'?'仅记录本地文件夹选择;D 本地执行尚未接通。':item.execution==='host-pending'?'主机文件夹已记录,等待 X 远程提供方接入位置合同后才能执行。':item.execution==='legacy-confirmed'?'已明确确认原有主机关联;继续使用原有执行入口。':'尚未选择文件来源。';
|
|
128
|
+
const identity=page?.host??item.host,host=identity?identity.username+'@'+identity.host+':'+identity.port:'主机标识尚未核实';
|
|
129
|
+
return h('fieldset',null,h('legend',null,item.workspaceName),h('p',null,'原生本地工作区:'+item.localPath),h('p',null,'远程主机:'+host),h('p',{role:'status'},execution),item.need?h('p',{role:'alert'},item.need.message):null,item.status==='legacy-confirmation-required'?h(React.Fragment,null,h('p',null,'此工作区有旧主机映射,必须明确确认;不会自动沿用。'),item.remote||item.legacyPath?h('p',null,'原有主机目录:'+(item.remote?.path??item.legacyPath)):null,h('button',{type:'button',disabled:loading,onClick:()=>select({source:'legacy-host',confirmLegacy:true})},'确认沿用旧主机关联')):null,h('button',{type:'button',disabled:loading,onClick:()=>select({source:'local'})},'使用本地文件夹'),h('button',{type:'button',disabled:loading,onClick:()=>browse()},'浏览主机文件夹'),h('label',null,'主机绝对目录',h('input',{type:'text',value:path,disabled:loading,onChange:event=>setPath(event.target.value)})),h('button',{type:'button',disabled:loading||!path.startsWith('/'),onClick:()=>browse({path})},'打开主机目录'),h('label',null,'主机目录每页条数',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:pageSize,disabled:loading,onChange:event=>setPageSize(event.target.value)})),h('p',null,'默认每页 '+locations.pageSize+' 条;可填写1至9007199254740991整数。只浏览和选择已有目录,不创建目录;本地文件不会自动上传。'),loading?h('p',{role:'status'},'正在核实工作区位置…'):null,error?h('p',{role:'alert'},error):null,page?h(React.Fragment,null,h('p',null,'请求目录:'+page.requestedPath),h('p',null,'规范路径:'+page.path),h('p',null,'父级:'+(page.parentPath??'无')),h('p',null,'符号链接:'+(page.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:page.permissions}),page.parentPath?h('button',{type:'button',disabled:loading,onClick:()=>browse({path:page.parentPath})},'打开父级目录'):null,h('button',{type:'button',disabled:loading||!page.selectionToken,onClick:()=>select({source:'host',selectionToken:page.selectionToken})},'选择当前主机文件夹'),...page.entries.map(entry=>h('div',{key:entry.requestedPath},h('p',null,entry.name+' · '+(entry.path??entry.requestedPath)+';符号链接:'+(entry.isSymlink?'是':'否')),h(DirectoryPermissions,{permissions:entry.permissions}),entry.errorCode?h('p',{role:'alert'},'目录无法使用:'+entry.errorCode):null,h('button',{type:'button',disabled:loading||!!entry.errorCode,onClick:()=>browse({path:entry.requestedPath})},'打开 '+entry.name),h('button',{type:'button',disabled:loading||!entry.selectionToken,onClick:()=>select({source:'host',selectionToken:entry.selectionToken})},'选择 '+entry.name))),page.nextCursor?h('button',{type:'button',disabled:loading,onClick:()=>browse({cursor:page.nextCursor})},'继续加载目录'):null):null);
|
|
130
|
+
}
|
|
131
|
+
function WorkspaceLocations({state,workbench}){
|
|
132
|
+
const locations=state?.workspaceLocations,[error,setError]=React.useState(''),[refreshing,setRefreshing]=React.useState(false);if(!locations)return null;
|
|
133
|
+
const refresh=async()=>{setRefreshing(true);setError('');try{const result=await workbench.refreshWorkspaceLocations();if(!result?.ok)setError(result?.error?.message||'原生工作区列表读取失败。');}catch{setError('原生工作区列表读取失败,未自动重试。');}finally{setRefreshing(false);}};
|
|
134
|
+
return h('details',null,h('summary',null,'工作区文件来源'),h('p',null,'先通过默认添加工作区选择真实本地文件夹,再逐个明确选择来源;本节不替换原生目录选择器。没有默认来源。'),h('button',{type:'button',disabled:refreshing,onClick:refresh},'刷新原生工作区列表'),error?h('p',{role:'alert'},error):null,locations.phase!=='ready'?h('p',{role:'status'},locations.need?.message||'工作区位置尚未核实。'):locations.items.length?locations.items.map(item=>h(WorkspaceLocationRow,{key:JSON.stringify([locations.instanceId,locations.epoch,item.workspaceId,item.bindingId,item.source,item.localPath]),item,locations,workbench})):h('p',null,'当前没有原生工作区,请先通过默认添加工作区选择文件夹。'));
|
|
115
135
|
}
|
|
116
136
|
function ComponentSource({state,action}){const c=state?.loginComponent?.source;if(!c)return null;const busy=c.changing||c.phase!=='ready'||['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)||state?.startup?.phase==='authorizing';return h('div',null,h('p',null,c.phase==='ready'?'登录组件下载源:'+c.selectedLabel:c.phase==='loading'?'正在读取登录组件下载源设置…':'登录组件下载源设置不可用;未切换到其他来源。'),h('p',null,c.reason),c.selectionErrorCode?h('p',{role:'alert'},c.selectionErrorCode==='COMPONENT_PIN_MISMATCH'?'下载源未更改:当前组件版本或 SHA256 与预设不符,请查看技术详情。':'下载源未更改,请查看技术详情。'):null,...(c.choices??[]).map(choice=>h('button',{key:choice.id,type:'button',disabled:busy||c.selectedId===choice.id,onClick:()=>void action('/component-source/'+choice.id)},'使用 '+choice.label)),h('p',null,'Electron '+c.version+';两项预设使用同一固定 SHA256,不会因下载失败自动换源。'));}
|
|
117
137
|
function DownloadProgress({state,action}){const d=state?.loginComponent?.download;const [,refresh]=React.useState(0),interval=state?.loginComponent?.observationIntervalMs,observing=d?.phase==='downloading'&&Number.isFinite(d.lastProgressAt);React.useEffect(()=>{if(!observing||!Number.isSafeInteger(interval)||interval<1||interval>2147483647)return;const timer=setInterval(()=>refresh(x=>x+1),interval);return()=>clearInterval(timer);},[observing,interval,d?.attemptId]);if(!d)return null;const seconds=Number.isFinite(d.lastProgressAt)?Math.max(0,Math.floor((Date.now()-d.lastProgressAt)/1000)):null;const text=d.phase==='downloading'?'正在从'+(d.sourceLabel||'所选地址')+'下载登录组件:已下载 '+d.receivedBytes+' 字节'+(d.totalBytes===null?'(总大小未知)':',共 '+d.totalBytes+' 字节')+'。'+(seconds===null?'':'已 '+seconds+' 秒无进展;仅观察,不会自动重试或换源。')+'Claude、Codex 登录网页都使用本机网络;Codex 设备码需复制后粘贴到官方页面。':d.phase==='verifying'?'正在校验登录组件…':d.phase==='unpacking'?'正在解压登录组件…':d.phase==='failed'?'登录组件准备失败,请查看技术详情;未重试或换源。':d.phase==='cancelled'?'登录组件下载已取消。':null;return text?h(React.Fragment,null,h('p',{role:'status'},text),['downloading','verifying','unpacking'].includes(d.phase)&&d.attemptId?h('button',{type:'button',onClick:()=>void action('/component-download/cancel/'+d.attemptId)},'取消组件下载'):null):null;}
|
|
@@ -120,20 +140,20 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
120
140
|
function ConversationDetailRecord({item}){
|
|
121
141
|
return h('details',null,h('summary',null,'序号 '+item.sequence+' · '+severityLabel(item.severity)+' · '+item.summary),h('dl',null,...Object.keys(detailFieldLabels).flatMap(key=>[h('dt',{key:key+'-label'},detailFieldLabels[key]+'('+key+')'),h('dd',{key:key+'-value'},key==='payload'?h('pre',null,JSON.stringify(item.payload,null,2)):item[key]===undefined?'未提供':item[key]===null?'null(官方未提供)':key==='severity'?severityLabel(item[key])+'('+item[key]+')':String(item[key]))])));
|
|
122
142
|
}
|
|
123
|
-
function ConversationDetailSession({session,workbench}){
|
|
143
|
+
function ConversationDetailSession({session,workbench,loginDiagnostics=false}){
|
|
124
144
|
const [page,setPage]=React.useState(null),[loading,setLoading]=React.useState(false),[error,setError]=React.useState(''),live=React.useRef(true),busy=React.useRef(false);
|
|
125
145
|
React.useEffect(()=>()=>{live.current=false;},[]);
|
|
126
146
|
const load=async more=>{if(busy.current)return;busy.current=true;setLoading(true);setError('');try{
|
|
127
|
-
const result=await workbench.readDetails({sessionId:session.sessionId,provider:session.provider,...(more&&page?.nextCursor?{cursor:page.nextCursor}:{})});if(!live.current)return;
|
|
147
|
+
const result=await (loginDiagnostics?workbench.readLoginDiagnostics:workbench.readDetails)({sessionId:session.sessionId,provider:session.provider,...(more&&page?.nextCursor?{cursor:page.nextCursor}:{})});if(!live.current)return;
|
|
128
148
|
if(!result?.ok){setPage(null);setError(result?.error?.message||'详情读取失败,请确认当前连接;未自动重试。');return;}
|
|
129
149
|
setPage(old=>({...result.value,items:more?[...(old?.items??[]),...result.value.items]:result.value.items}));
|
|
130
150
|
}catch{if(live.current){setPage(null);setError('详情读取失败,请确认当前连接;未自动重试。');}}finally{busy.current=false;if(live.current)setLoading(false);}};
|
|
131
151
|
return h('details',null,h('summary',null,session.sessionId+' · '+(session.provider==='claude'?'Claude':'Codex')+' · 共 '+session.total+' 条,未知 '+session.unknownCount+' 条,'+session.actionRequiredCount+' 项需处理'),h('button',{type:'button',disabled:loading,onClick:()=>load(false)},page?'刷新详情':'读取详情'),loading?h('p',{role:'status'},'正在读取详情…'):null,error?h('p',{role:'alert'},error):null,page?h(React.Fragment,null,h('p',null,'本轮详情快照:共 '+page.total+' 条,未知 '+page.unknownCount+' 条,'+page.actionRequiredCount+' 项需处理。'),...page.items.map(item=>h(ConversationDetailRecord,{key:item.eventId,item})),page.nextCursor?h('button',{type:'button',disabled:loading,onClick:()=>load(true)},'继续加载'):null):null);
|
|
132
152
|
}
|
|
133
|
-
function RemoteConversationDetails({state,workbench}){
|
|
134
|
-
const details=state?.conversationDetails;if(!details)return null;
|
|
153
|
+
function RemoteConversationDetails({state,workbench,loginDiagnostics=false}){
|
|
154
|
+
const details=loginDiagnostics?state?.loginDiagnostics:state?.conversationDetails;if(!details)return null;
|
|
135
155
|
const count=(details.sessions??[]).reduce((sum,s)=>sum+s.actionRequiredCount,0);
|
|
136
|
-
return h('div',null,count?h('p',{role:'status'},'诊断记录有 '+count+'
|
|
156
|
+
return h('div',null,count?h('p',{role:'status'},'诊断记录有 '+count+' 项需处理,请展开'+(loginDiagnostics?'登录前技术详情':'会话技术详情')+'查看。'):null,h('details',null,h('summary',null,loginDiagnostics?'登录前技术详情':'会话技术详情'),details.phase==='ready'&&details.need?h('p',{role:'status'},'部分历史记录的原生会话或品牌关联无法核实,当前不显示其计数与正文。'):null,details.phase==='ready'?(details.sessions.length?details.sessions.map(session=>h(ConversationDetailSession,{key:details.instanceId+':'+details.epoch+':'+session.provider+':'+session.sessionId,session,workbench,loginDiagnostics})):h('p',null,'当前可信连接没有可读取的诊断记录。')):h('p',{role:'status'},details.phase==='loading'?'正在核验诊断记录…':details.need?.message||'诊断记录暂时无法读取,请确认当前连接。')));
|
|
137
157
|
}
|
|
138
158
|
function ConversationDetailSettings({state,action}){
|
|
139
159
|
const settings=state?.conversationDetailSettings,[max,setMax]=React.useState(''),[size,setSize]=React.useState(''),[error,setError]=React.useState(''),[saving,setSaving]=React.useState(false);
|
|
@@ -142,7 +162,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
142
162
|
const save=async()=>{const maxEventBytes=Number(max),pageSize=Number(size);if(!/^\d+$/.test(max)||!/^\d+$/.test(size)||![maxEventBytes,pageSize].every(n=>Number.isSafeInteger(n)&&n>0)){setError('设置未保存:两项都需要1至9007199254740991之间的整数。');return;}setError('');setSaving(true);try{await action('/conversation-detail-settings',{maxEventBytes,pageSize});}finally{setSaving(false);}};
|
|
143
163
|
return h('details',null,h('summary',null,'管理员设置'),h('p',null,'仅调整诊断记录。保存后即时生效,重开继续沿用本节保存值;已保存值优先于官方插件 Config 初值。未保存时使用 Config 或以下默认值。'),h('label',null,'conversationDetails.maxEventBytes',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:max,disabled,onChange:event=>setMax(event.target.value)})),h('p',null,'完整 UTF-8 JSON 事件字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小拒收超过新值的新事件,不裁剪、不删除已保存记录,也不阻止原事件的幂等核实。'),h('label',null,'conversationDetails.pageSize',h('input',{type:'number',min:1,max:Number.MAX_SAFE_INTEGER,step:1,value:size,disabled,onChange:event=>setSize(event.target.value)})),h('p',null,'一次详情页条数;默认100,范围1至9007199254740991整数。改大增加一次读取和界面负担;改小增加继续加载次数,不减少完整快照总数。'),h('p',null,'enrollmentMetadataMaxBytes 当前为 '+settings.metadataMaxBytes+' 字节(默认1048576),同时限制诊断设置文件与保存提交JSON;调小可能拒绝设置读取或保存,可在官方插件 Config 修改。'),h('p',null,'诊断记录不自动过期、不按条数淘汰、没有隐藏总条数上限;本版没有清除入口。'),h('p',null,settings.phase==='ready'?(settings.source==='saved'?'当前使用本节已保存设置。':'当前使用官方插件 Config 初值或默认值。'):settings.phase==='saving'?'正在保存设置…':'设置无法核实,未自动使用其他值;请联系管理员。'),error?h('p',{role:'alert'},error):null,settings.errorCode?h('p',{role:'alert'},'设置保存或读取失败:'+settings.errorCode):null,h('button',{type:'button',disabled,onClick:save},'保存诊断设置'));
|
|
144
164
|
}
|
|
145
|
-
function Panel({workbench,t}){const {state,error,action}=useWorkbench(workbench),message=messageKey(state?.startup),errorKey=error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)&&(!error||!!state?.startup)&&!(state?.enrollment?.phase==='blocked'&&state.enrollment.need);return h('section',{'aria-label':t('title')},h('h2',null,t('title')),h('p',null,t('loginNetworkBoundary')),h(ComponentSource,{state,action}),h(DownloadProgress,{state,action}),h(Enrollment,{state,action,t}),bodyVisible?h('p',{role:errorKey===message?'alert':undefined},t(message)):null,errorKey&&(!bodyVisible||errorKey!==message)?h('p',{role:'alert'},t(errorKey)):null,state?h(React.Fragment,null,...['codex','claude'].map(provider=>{const brand=provider==='claude'?'Claude':'Codex',checking=state.startup?.checkingProviders?.includes(provider),unknown=state.startup?.providerNeeds?.[provider]||state.startup?.logins?.[provider]===undefined;return h('div',{key:provider},h('p',null,t('provider',{brand})+': '+t(checking?'statusChecking':unknown?'statusUnknown':state.startup.logins[provider]?'statusSignedIn':'statusSignIn')),state.startup?.logins?.[provider]===false&&!checking&&!unknown&&(!isLoginQuestion(state)||state.startup.provider!==provider)?h('button',{type:'button',disabled:state.startup.phase==='authorizing',onClick:()=>void action('/start-login/'+provider+'/'+state.startup.instanceId+'/'+state.startup.revision)},t('signIn',{brand})):null);}),h(Choices,{state,action,t}),h(WorkspaceNotices,{state,action})
|
|
165
|
+
function Panel({workbench,t}){const {state,error,action}=useWorkbench(workbench),message=messageKey(state?.startup),connectionMessage=state?.connection?.recovery?.version===1?state.connection.recovery.message:undefined,errorKey=connectionMessage&&['CONNECTION_LOST','HOST_OFFLINE','SSH_FAILED'].includes(error)?undefined:error==='ENROLLMENT_REQUIRED'&&state?.enrollment?.phase==='blocked'?'enrollmentKeyMissing':error?needKey(error):undefined,bodyVisible=!['downloading','verifying','unpacking'].includes(state?.loginComponent?.download?.phase)&&(!error||!!state?.startup)&&!(state?.enrollment?.phase==='blocked'&&state.enrollment.need);return h('section',{'aria-label':t('title')},h('h2',null,t('title')),h('p',null,t('loginNetworkBoundary')),h(ComponentSource,{state,action}),h(DownloadProgress,{state,action}),h(Enrollment,{state,action,t}),bodyVisible?h('p',{role:errorKey===message?'alert':undefined},connectionMessage??t(message)):null,errorKey&&(!bodyVisible||errorKey!==message)?h('p',{role:'alert'},t(errorKey)):null,state?h(React.Fragment,null,...['codex','claude'].map(provider=>{const brand=provider==='claude'?'Claude':'Codex',checking=state.startup?.checkingProviders?.includes(provider),unknown=state.startup?.providerNeeds?.[provider]||state.startup?.logins?.[provider]===undefined;return h('div',{key:provider},h('p',null,t('provider',{brand})+': '+t(checking?'statusChecking':unknown?'statusUnknown':state.startup.logins[provider]?'statusSignedIn':'statusSignIn')),state.startup?.logins?.[provider]===false&&!checking&&!unknown&&(!isLoginQuestion(state)||state.startup.provider!==provider)?h('button',{type:'button',disabled:state.startup.phase==='authorizing',onClick:()=>void action('/start-login/'+provider+'/'+state.startup.instanceId+'/'+state.startup.revision)},t('signIn',{brand})):null);}),h(Choices,{state,action,t}),h(WorkspaceNotices,{state,action}),!state.workspaceLocations?h('p',null,t('workspaceLimit')):null,...(state.workspaceBindings?.items??[]).filter(item=>item.notice.provider==='delivered'&&(!state.workspaceLocations||state.workspaceLocations.items?.some(location=>location.workspaceId===item.workspaceId&&location.execution==='legacy-confirmed'))).map(item=>h('p',{key:'delivery-'+item.notice.noticeId},item.workspaceName+':首次说明已记入可核对回复。'))):null,h(WorkspaceLocations,{state,workbench}),h(RemoteConversationDetails,{state,workbench}),h(RemoteConversationDetails,{state,workbench,loginDiagnostics:true}),h(ConversationDetailSettings,{state,action}),h(Details,{state,error,t}),h('button',{type:'button',onClick:()=>void action()},t('recheck')));}
|
|
146
166
|
return {name:'ai-workbench-connect-client',inject:['slots','locale'],createWorkbenchController,Panel,dictionaries,observeNotice,apply(ctx){
|
|
147
167
|
ctx.effect(()=>ctx.locale.register(NS,dictionaries));const t=ctx.locale.bind(NS);
|
|
148
168
|
const workbench=createWorkbenchController(async(path,method,body)=>{const response=await fetch('/ai-workbench-connect'+path,{method,...body===undefined?{}:{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}});const value=await response.json();if(!response.ok&&!value?.startup&&typeof value?.ok!=='boolean')throw Error('connection-unavailable');return value;},(accept,failure)=>{const source=new EventSource('/ai-workbench-connect/events');source.onmessage=event=>{try{accept(JSON.parse(event.data));}catch{failure();}};source.onerror=failure;return()=>source.close();});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const fs=require('node:fs/promises');
|
|
2
|
+
const {constants}=require('node:fs');
|
|
3
|
+
const path=require('node:path');
|
|
4
|
+
const os=require('node:os');
|
|
5
|
+
const error=code=>({protocolVersion:1,ok:false,error:{code}});
|
|
6
|
+
const validIdentity=value=>value&&typeof value==='object'&&['device','inode','mtimeNs','ctimeNs'].every(key=>typeof value[key]==='string'&&/^-?\d+$/.test(value[key]));
|
|
7
|
+
const identity=stat=>({device:String(stat.dev),inode:String(stat.ino),mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
|
|
8
|
+
const entryIdentity=stat=>({device:String(stat.dev),inode:String(stat.ino)});
|
|
9
|
+
const equal=(a,b)=>['device','inode','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
|
|
10
|
+
const binaryCompare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
|
|
11
|
+
const validPath=value=>typeof value==='string'&&path.isAbsolute(value)&&!value.includes('\0');
|
|
12
|
+
const invalid=()=>Object.assign(new Error('HOST_DIRECTORY_INVALID'),{directoryCode:'HOST_DIRECTORY_INVALID'});
|
|
13
|
+
const classify=exception=>exception?.directoryCode??(['EACCES','EPERM'].includes(exception?.code)?'HOST_DIRECTORY_UNREADABLE':'HOST_DIRECTORY_INVALID');
|
|
14
|
+
const unknownPermissions=()=>({read:null,write:null,execute:null,reason:'HOST_PERMISSION_UNKNOWN'});
|
|
15
|
+
async function permissions(target){
|
|
16
|
+
const result={};let unknown=false;
|
|
17
|
+
for(const [key,mode] of [['read',constants.R_OK],['write',constants.W_OK],['execute',constants.X_OK]]){
|
|
18
|
+
try{await fs.access(target,mode);result[key]=true;}catch(exception){result[key]=['EACCES','EPERM'].includes(exception?.code)?false:null;if(result[key]===null)unknown=true;}
|
|
19
|
+
}
|
|
20
|
+
if(unknown)result.reason='HOST_PERMISSION_UNKNOWN';return result;
|
|
21
|
+
}
|
|
22
|
+
async function observe(requestedPath){
|
|
23
|
+
const entry=await fs.lstat(requestedPath,{bigint:true});
|
|
24
|
+
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())throw invalid();
|
|
25
|
+
return {requestedPath,path:resolved,parentPath:path.dirname(resolved)===resolved?null:path.dirname(resolved),identity:identity(stat),entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink(),permissions:await permissions(resolved)};
|
|
26
|
+
}
|
|
27
|
+
function unchanged(before,after){return before.path===after.path&&equal(before.identity,after.identity)&&before.entryIdentity.device===after.entryIdentity.device&&before.entryIdentity.inode===after.entryIdentity.inode;}
|
|
28
|
+
async function directoryEntry(requestedPath,name){
|
|
29
|
+
const entry=await fs.lstat(requestedPath,{bigint:true});if(!entry.isDirectory()&&!entry.isSymbolicLink())return null;
|
|
30
|
+
const base={name,requestedPath,entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink()};
|
|
31
|
+
try{
|
|
32
|
+
const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())return null;
|
|
33
|
+
const access=await permissions(resolved);
|
|
34
|
+
return {...base,path:resolved,identity:identity(stat),permissions:access,...access.read!==true||access.execute!==true?{errorCode:'HOST_DIRECTORY_UNREADABLE'}:{}};
|
|
35
|
+
}catch(exception){return {...base,permissions:unknownPermissions(),errorCode:classify(exception)};}
|
|
36
|
+
}
|
|
37
|
+
async function execute(request){
|
|
38
|
+
if(request?.protocolVersion!==1||!['browse','inspect'].includes(request.operation))return error('PROJECT_PROTOCOL_INVALID');
|
|
39
|
+
if(!Number.isSafeInteger(request.maxOutputBytes)||request.maxOutputBytes<1)return error('HOST_DIRECTORY_INVALID');
|
|
40
|
+
if(request.path!==undefined&&!validPath(request.path))return error('HOST_DIRECTORY_INVALID');
|
|
41
|
+
if(request.operation==='inspect'&&request.path===undefined)return error('HOST_DIRECTORY_INVALID');
|
|
42
|
+
if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.expected!==undefined&&!validIdentity(request.expected)||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0')||!validIdentity(request.expected))))return error('HOST_DIRECTORY_INVALID');
|
|
43
|
+
const requestedPath=request.path??os.homedir();
|
|
44
|
+
try{
|
|
45
|
+
const before=await observe(requestedPath);
|
|
46
|
+
if(request.expected!==undefined&&!equal(before.identity,request.expected))return error('HOST_DIRECTORY_CHANGED');
|
|
47
|
+
let value=before;
|
|
48
|
+
if(request.operation==='browse'){
|
|
49
|
+
// Keep only the smallest pageSize+1 eligible names, independent of readdir order.
|
|
50
|
+
const window=[];
|
|
51
|
+
for await(const dirent of await fs.opendir(requestedPath)){
|
|
52
|
+
const name=dirent.name;if(request.after!==undefined&&binaryCompare(name,request.after)<=0)continue;
|
|
53
|
+
if(!dirent.isDirectory()&&!dirent.isSymbolicLink()&&(dirent.isFile()||dirent.isBlockDevice()||dirent.isCharacterDevice()||dirent.isFIFO()||dirent.isSocket()))continue;
|
|
54
|
+
if(window.length>request.pageSize&&binaryCompare(name,window[window.length-1].name)>=0)continue;
|
|
55
|
+
const entry=await directoryEntry(path.join(requestedPath,name),name);if(entry===null)continue;
|
|
56
|
+
let index=window.findIndex(item=>binaryCompare(name,item.name)<0);if(index===-1)index=window.length;window.splice(index,0,entry);if(window.length>request.pageSize+1)window.pop();
|
|
57
|
+
}
|
|
58
|
+
const hasMore=window.length>request.pageSize;if(hasMore)window.pop();value={...before,entries:window,...hasMore?{nextAfter:window[window.length-1].name}:{}};
|
|
59
|
+
}
|
|
60
|
+
let after;try{after=await observe(requestedPath);}catch{return error('HOST_DIRECTORY_CHANGED');}
|
|
61
|
+
if(!unchanged(before,after))return error('HOST_DIRECTORY_CHANGED');
|
|
62
|
+
const result={protocolVersion:1,ok:true,value};
|
|
63
|
+
return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
|
|
64
|
+
}catch(exception){return error(classify(exception));}
|
|
65
|
+
}
|
|
66
|
+
async function main(){
|
|
67
|
+
let input='';for await(const chunk of process.stdin)input+=chunk;
|
|
68
|
+
let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
|
|
69
|
+
process.stdout.write(JSON.stringify(result)+'\n');
|
|
70
|
+
}
|
|
71
|
+
module.exports={execute};
|
|
72
|
+
if(require.main===module)void main();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Public transport adapter. SSH status describes this protocol, not the child command.
|
|
2
2
|
const {spawn}=require('node:child_process');
|
|
3
3
|
let request='',child,broken=false;
|
|
4
|
-
const killChild=()=>{if(child?.pid)try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error?.code!=='ESRCH'){process.stderr.write('AW_REMOTE_COMMAND_KILL_FAILED\n');process.exitCode=2;}}};
|
|
4
|
+
const killChild=()=>{if(child?.pid)try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error?.code!=='ESRCH'){const name=['Error','TypeError','RangeError'].includes(error?.name)?error.name:'UnknownError',code=['EPERM','EACCES','EINVAL'].includes(error?.code)?error.code:'UNKNOWN';process.stderr.write('AW_REMOTE_COMMAND_KILL_FAILED:'+name+':'+code+'\n');process.exitCode=2;}}};
|
|
5
5
|
const stop=()=>{broken=true;killChild();};
|
|
6
6
|
process.stdout.on('error',stop);process.on('SIGHUP',stop);process.on('SIGTERM',stop);
|
|
7
7
|
process.stdin.setEncoding('utf8');process.stdin.on('data',b=>request+=b);
|
package/lib/api.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from './connection-messages.ts';
|
|
2
|
+
import type { WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
|
|
3
|
+
export type * from './workspace-location-types.ts';
|
|
4
|
+
import type { LocalWorkspaceContextRequest, LocalWorkspaceContext } from './local-workspace-context.ts';
|
|
5
|
+
export type { LocalWorkspaceContextRequest, LocalWorkspaceContext, LocalWorkspaceProcess } from './local-workspace-context.ts';
|
|
1
6
|
export type Provider = 'claude' | 'codex';
|
|
2
|
-
export type NeedCode = 'REMOTE_DETAIL_INVALID' | 'REMOTE_DETAIL_SCOPE_INVALID' | 'REMOTE_DETAIL_STORAGE_FAILED' | 'REMOTE_DETAIL_TOO_LARGE' | 'REMOTE_DETAIL_SEQUENCE_INVALID' | 'REMOTE_DETAIL_CONFLICT' | 'REMOTE_DETAIL_CURSOR_INVALID' | 'MODEL_CATALOG_CONTEXT_INVALID' | 'ACTIVATION_CONFLICT' | 'ACTIVATION_CANCELLED' | 'ENROLLMENT_CLEANUP_UNBOUND' | 'ENROLLMENT_CLEANUP_FAILED' | 'ENROLLMENT_MISMATCH' | 'LOCAL_STATE_INVALID' | 'ALREADY_RUNNING' | 'ENROLLMENT_RECEIPT_REQUIRED' | 'CONTROL_PROTOCOL_INVALID' | 'HELPER_HANDOFF_FAILED' | 'HELPER_SHUTDOWN_FORCED' | 'ENROLLMENT_RESULT_UNKNOWN' | 'ENROLLMENT_REJECTED' | 'ENROLLMENT_REQUIRED' | 'ENROLLMENT_INVALID' | 'NETWORK_KEY_INVALID' | 'HOST_OFFLINE' | 'EMPLOYEE_MISSING' | 'SSH_FAILED' | 'LOGIN_REQUIRED' | 'POLICY_DENIED' | 'CONNECTION_LOST' | 'DEPENDENCY_REQUIRED' | 'SETTINGS_REQUIRED' | 'AUTH_STATUS_INVALID' | 'LOGIN_FAILED' | 'LOGIN_PROMPT_INVALID' | 'DISPOSED' | 'HOST_TRUST_REQUIRED' | 'HOST_KEY_MISMATCH' | 'PROJECT_NAME_INVALID' | 'PROJECT_ROOT_INVALID' | 'PROJECT_EXISTS' | 'PROJECT_INIT_FAILED' | 'PROJECT_CREATE_FAILED' | 'PROJECT_LIST_FAILED' | 'PROJECT_PROTOCOL_INVALID' | 'PROJECT_BINDING_REQUIRED' | 'PROJECT_BINDING_INVALID' | 'PROJECT_BINDING_BUSY' | 'PROJECT_CREATE_UNKNOWN' | 'PROJECT_NOTICE_DELIVERY_UNKNOWN';
|
|
7
|
+
export type NeedCode = 'LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED' | 'LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE' | 'HOST_DIRECTORY_INVALID' | 'HOST_DIRECTORY_UNREADABLE' | 'HOST_DIRECTORY_CHANGED' | 'HOST_DIRECTORY_PAGE_TOO_LARGE' | 'WORKSPACE_LOCATION_REQUIRED' | 'WORKSPACE_LOCATION_INVALID' | 'WORKSPACE_LOCATION_CONFLICT' | 'WORKSPACE_LOCATION_PROVIDER_REQUIRED' | 'WORKSPACE_EXECUTION_UNAVAILABLE' | 'WORKSPACE_LOCATION_STORAGE_FAILED' | 'REMOTE_DETAIL_INVALID' | 'REMOTE_DETAIL_SCOPE_INVALID' | 'REMOTE_DETAIL_STORAGE_FAILED' | 'REMOTE_DETAIL_TOO_LARGE' | 'REMOTE_DETAIL_SEQUENCE_INVALID' | 'REMOTE_DETAIL_CONFLICT' | 'REMOTE_DETAIL_CURSOR_INVALID' | 'MODEL_CATALOG_CONTEXT_INVALID' | 'ACTIVATION_CONFLICT' | 'ACTIVATION_CANCELLED' | 'ENROLLMENT_CLEANUP_UNBOUND' | 'ENROLLMENT_CLEANUP_FAILED' | 'ENROLLMENT_MISMATCH' | 'LOCAL_STATE_INVALID' | 'ALREADY_RUNNING' | 'ENROLLMENT_RECEIPT_REQUIRED' | 'CONTROL_PROTOCOL_INVALID' | 'HELPER_HANDOFF_FAILED' | 'HELPER_SHUTDOWN_FORCED' | 'ENROLLMENT_RESULT_UNKNOWN' | 'ENROLLMENT_REJECTED' | 'ENROLLMENT_REQUIRED' | 'ENROLLMENT_INVALID' | 'NETWORK_KEY_INVALID' | 'HOST_OFFLINE' | 'EMPLOYEE_MISSING' | 'SSH_FAILED' | 'LOGIN_REQUIRED' | 'POLICY_DENIED' | 'CONNECTION_LOST' | 'DEPENDENCY_REQUIRED' | 'SETTINGS_REQUIRED' | 'AUTH_STATUS_INVALID' | 'LOGIN_FAILED' | 'LOGIN_PROMPT_INVALID' | 'DISPOSED' | 'HOST_TRUST_REQUIRED' | 'HOST_KEY_MISMATCH' | 'PROJECT_NAME_INVALID' | 'PROJECT_ROOT_INVALID' | 'PROJECT_EXISTS' | 'PROJECT_INIT_FAILED' | 'PROJECT_CREATE_FAILED' | 'PROJECT_LIST_FAILED' | 'PROJECT_PROTOCOL_INVALID' | 'PROJECT_BINDING_REQUIRED' | 'PROJECT_BINDING_INVALID' | 'PROJECT_BINDING_BUSY' | 'PROJECT_CREATE_UNKNOWN' | 'PROJECT_NOTICE_DELIVERY_UNKNOWN';
|
|
3
8
|
export interface ConnectNeed {
|
|
4
9
|
code: NeedCode;
|
|
5
10
|
layer: 'enrollment' | 'network' | 'ssh' | 'auth' | 'integration' | 'settings' | 'projects';
|
|
@@ -71,7 +76,15 @@ export interface ProjectList {
|
|
|
71
76
|
reason: 'invalid-name' | 'symlink' | 'not-directory' | 'permissions' | 'not-git' | 'invalid-git' | 'outside-root';
|
|
72
77
|
}[];
|
|
73
78
|
}
|
|
79
|
+
export interface ConnectionRecovery {
|
|
80
|
+
version: 1;
|
|
81
|
+
phase: 'reconnecting' | 'administrator-required';
|
|
82
|
+
message: '正在自动重连' | '请联系管理员';
|
|
83
|
+
startedAt: number;
|
|
84
|
+
administratorAfterMs: number;
|
|
85
|
+
}
|
|
74
86
|
export interface ConnectionState {
|
|
87
|
+
recovery?: ConnectionRecovery;
|
|
75
88
|
instanceId: string;
|
|
76
89
|
phase: 'connecting' | 'connected' | 'unavailable' | 'disposed';
|
|
77
90
|
epoch: number;
|
|
@@ -85,6 +98,7 @@ export interface LoginPromptState {
|
|
|
85
98
|
requestId?: string;
|
|
86
99
|
provider?: Provider;
|
|
87
100
|
logins: Partial<Record<Provider, boolean>>;
|
|
101
|
+
queuedProviders?: Provider[];
|
|
88
102
|
checkingProviders: Provider[];
|
|
89
103
|
providerNeeds: Partial<Record<Provider, ConnectNeed>>;
|
|
90
104
|
technicalDetails: {
|
|
@@ -103,6 +117,10 @@ export interface ContractInfo {
|
|
|
103
117
|
status: 'implemented';
|
|
104
118
|
workspaceBinding: 'native-local-v1';
|
|
105
119
|
remoteConversationDetails?: 1;
|
|
120
|
+
loginDiagnostics?: 1;
|
|
121
|
+
workspaceLocations?: 1;
|
|
122
|
+
connectionMessages?: 1;
|
|
123
|
+
localWorkspaceContext?: 1;
|
|
106
124
|
}
|
|
107
125
|
export interface WorkspaceUse {
|
|
108
126
|
provider: Provider;
|
|
@@ -222,6 +240,31 @@ export interface ModelCatalogTarget {
|
|
|
222
240
|
target: SshTarget;
|
|
223
241
|
}
|
|
224
242
|
export interface ConnectApi {
|
|
243
|
+
getLocalWorkspaceContext?(request: LocalWorkspaceContextRequest): Promise<Result<LocalWorkspaceContext>>;
|
|
244
|
+
getWorkspaceLocationState?(): WorkspaceLocationState;
|
|
245
|
+
onWorkspaceLocationState?(listener: (state: WorkspaceLocationState) => void): () => void;
|
|
246
|
+
refreshWorkspaceLocations?(): Promise<Result<WorkspaceLocationState>>;
|
|
247
|
+
browseWorkspaceHostDirectories?(request: WorkspaceBrowseRequest): Promise<Result<WorkspaceBrowsePage>>;
|
|
248
|
+
selectWorkspaceLocation?(request: WorkspaceSelectRequest): Promise<Result<WorkspaceLocationState>>;
|
|
249
|
+
appendLoginDiagnostic(detail: RemoteConversationDetail): Promise<Result<{
|
|
250
|
+
eventId: string;
|
|
251
|
+
recorded: true;
|
|
252
|
+
}>>;
|
|
253
|
+
getLoginDiagnosticReceipt(query: {
|
|
254
|
+
eventId: string;
|
|
255
|
+
sessionId: string;
|
|
256
|
+
provider: Provider;
|
|
257
|
+
}): Promise<Result<{
|
|
258
|
+
eventId: string;
|
|
259
|
+
recorded: false;
|
|
260
|
+
} | {
|
|
261
|
+
eventId: string;
|
|
262
|
+
recorded: true;
|
|
263
|
+
detail: RemoteConversationDetail;
|
|
264
|
+
}>>;
|
|
265
|
+
listLoginDiagnostics(query: RemoteDetailQuery): Promise<Result<RemoteDetailPage>>;
|
|
266
|
+
getLoginDiagnosticState(): RemoteConversationDetailState;
|
|
267
|
+
onLoginDiagnosticState(listener: (state: RemoteConversationDetailState) => void): () => void;
|
|
225
268
|
getModelCatalogTarget(provider: Provider): Result<ModelCatalogTarget>;
|
|
226
269
|
appendRemoteConversationDetail(detail: RemoteConversationDetail): Promise<Result<{
|
|
227
270
|
eventId: string;
|
package/lib/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from "./connection-messages.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { NeedCode, Result } from './api.ts';
|
|
2
|
+
export declare function validAuthDiagnosticReason(value: unknown): value is string;
|
|
3
|
+
export declare function outputSummary(value: string): {
|
|
4
|
+
cleanupErrors?: {
|
|
5
|
+
errorName: string;
|
|
6
|
+
errorCode: string;
|
|
7
|
+
}[] | undefined;
|
|
8
|
+
bytes: number;
|
|
9
|
+
sha256: string;
|
|
10
|
+
markers: string[];
|
|
11
|
+
};
|
|
12
|
+
export declare function exceptionSummary(error: unknown): {
|
|
13
|
+
errorCode?: string | undefined;
|
|
14
|
+
errorName: string;
|
|
15
|
+
};
|
|
16
|
+
export declare class AuthDiagnosticError extends Error {
|
|
17
|
+
readonly diagnostic: Record<string, unknown>;
|
|
18
|
+
constructor(diagnostic: Record<string, unknown>, message?: string);
|
|
19
|
+
}
|
|
20
|
+
export declare function authFailure(stage: string, reason: string, details?: Record<string, unknown>, error?: unknown, code?: NeedCode): Extract<Result<never>, {
|
|
21
|
+
ok: false;
|
|
22
|
+
}>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { need } from "./needs.js";
|
|
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
|
+
const names = ['Error', 'TypeError', 'SyntaxError', 'RangeError', 'AbortError', 'DOMException', 'UnknownError'];
|
|
5
|
+
const codes = ['ENOENT', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
|
|
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
|
+
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
|
+
const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
9
|
+
const integer = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
|
|
10
|
+
function summary(v) { return object(v) && Object.keys(v).every(k => ['bytes', 'sha256', 'markers', 'cleanupErrors'].includes(k)) && integer(v.bytes) && typeof v.sha256 === 'string' && /^[a-f0-9]{64}$/.test(v.sha256) && Array.isArray(v.markers) && v.markers.every((m) => typeof m === 'string' && markers.includes(m)) && (v.cleanupErrors === undefined || Array.isArray(v.cleanupErrors) && v.cleanupErrors.every((e) => object(e) && Object.keys(e).sort().join(',') === 'errorCode,errorName' && ['Error', 'TypeError', 'RangeError', 'UnknownError'].includes(e.errorName) && ['EPERM', 'EACCES', 'EINVAL', 'UNKNOWN'].includes(e.errorCode))); }
|
|
11
|
+
export function validAuthDiagnosticReason(value) {
|
|
12
|
+
if (typeof value !== 'string')
|
|
13
|
+
return false;
|
|
14
|
+
let v;
|
|
15
|
+
try {
|
|
16
|
+
v = JSON.parse(value);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
if (!object(v) || JSON.stringify(v) !== value || v.version !== 1 || !stages.includes(v.stage) || !reasons.includes(v.reason))
|
|
22
|
+
return false;
|
|
23
|
+
const fields = { version: x => x === 1, stage: x => stages.includes(x), reason: x => reasons.includes(x), errorName: x => names.includes(x), errorCode: x => codes.includes(x), exitCode: x => x === null || typeof x === 'number' && Number.isFinite(x) && Number.isInteger(x), signal: x => ['SIGTERM', 'SIGKILL', 'SIGABRT', 'SIGHUP', 'SIGINT', 'SIGSEGV', 'OTHER'].includes(x), index: integer, unexpectedCount: integer, maxOutputBytes: x => integer(x) && x > 0, observedBytes: integer, stderr: summary, output: summary, missing: x => Array.isArray(x) && x.every(k => ['nonce', 'protocolVersion', 'type', 'data', 'exitCode', 'signal', 'loggedIn', 'provider'].includes(k)), loggedInType: x => ['null', 'undefined', 'object', 'boolean', 'number', 'string', 'function', 'symbol', 'bigint'].includes(x), exitCodeType: x => ['undefined', 'object', 'boolean', 'number', 'string', 'function', 'symbol', 'bigint'].includes(x) };
|
|
24
|
+
return Object.entries(v).every(([key, item]) => Object.hasOwn(fields, key) && fields[key](item));
|
|
25
|
+
}
|
|
26
|
+
// Raw command output and exception messages can contain authentication material.
|
|
27
|
+
// Only fixed markers and content hashes cross the existing technical-detail field.
|
|
28
|
+
export function outputSummary(value) {
|
|
29
|
+
const found = markers.filter(marker => value.includes(marker));
|
|
30
|
+
const cleanupErrors = [...value.matchAll(/AW_REMOTE_COMMAND_KILL_FAILED:(Error|TypeError|RangeError|UnknownError):(EPERM|EACCES|EINVAL|UNKNOWN)(?=\r?\n|$)/g)].map(match => ({ errorName: match[1], errorCode: match[2] }));
|
|
31
|
+
return { bytes: Buffer.byteLength(value), sha256: createHash('sha256').update(value).digest('hex'), markers: found, ...(cleanupErrors.length ? { cleanupErrors } : {}) };
|
|
32
|
+
}
|
|
33
|
+
export function exceptionSummary(error) {
|
|
34
|
+
const value = error;
|
|
35
|
+
return { errorName: typeof value?.name === 'string' && names.includes(value.name) ? value.name : 'UnknownError', ...(typeof value?.code === 'string' && codes.includes(value.code) ? { errorCode: value.code } : {}) };
|
|
36
|
+
}
|
|
37
|
+
export class AuthDiagnosticError extends Error {
|
|
38
|
+
diagnostic;
|
|
39
|
+
constructor(diagnostic, message = 'REMOTE_RESULT_INVALID') { super(message); this.name = 'AuthDiagnosticError'; this.diagnostic = diagnostic; }
|
|
40
|
+
}
|
|
41
|
+
export function authFailure(stage, reason, details = {}, error, code = 'AUTH_STATUS_INVALID') {
|
|
42
|
+
const value = need(code);
|
|
43
|
+
value.officialReason = JSON.stringify({ version: 1, ...(error instanceof AuthDiagnosticError ? error.diagnostic : { stage, reason, ...details, ...(error === undefined ? {} : exceptionSummary(error)) }) });
|
|
44
|
+
return { ok: false, error: value };
|
|
45
|
+
}
|
package/lib/auth-status.js
CHANGED
|
@@ -1,18 +1,31 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ok } from "./needs.js";
|
|
2
|
+
import { authFailure, outputSummary } from "./auth-diagnostics.js";
|
|
2
3
|
export function parseLoginStatus(provider, result) {
|
|
4
|
+
const invalid = (reason, details = {}) => authFailure('auth-status', reason, { exitCode: result.exitCode, ...(result.stderr !== '' ? { stderr: outputSummary(result.stderr) } : {}), ...details });
|
|
3
5
|
let v;
|
|
4
6
|
try {
|
|
5
7
|
v = JSON.parse(result.stdout);
|
|
6
8
|
}
|
|
7
|
-
catch {
|
|
8
|
-
return
|
|
9
|
+
catch (error) {
|
|
10
|
+
return invalid('STATUS_JSON_INVALID', { output: outputSummary(result.stdout), errorName: error instanceof SyntaxError ? 'SyntaxError' : 'UnknownError' });
|
|
9
11
|
}
|
|
10
|
-
if (!v || typeof v !== 'object' || Array.isArray(v)
|
|
11
|
-
return
|
|
12
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
13
|
+
return invalid('STATUS_OBJECT_INVALID');
|
|
14
|
+
const expected = ['exitCode', 'loggedIn', 'protocolVersion', 'provider'];
|
|
15
|
+
if (Object.keys(v).sort().join(',') !== expected.join(','))
|
|
16
|
+
return invalid('STATUS_KEYS_INVALID', { missing: expected.filter(key => !Object.hasOwn(v, key)), unexpectedCount: Object.keys(v).filter(key => !expected.includes(key)).length });
|
|
12
17
|
const status = v;
|
|
13
|
-
if (status.protocolVersion !== 1
|
|
14
|
-
return
|
|
18
|
+
if (status.protocolVersion !== 1)
|
|
19
|
+
return invalid('STATUS_VERSION_INVALID');
|
|
20
|
+
if (status.provider !== provider)
|
|
21
|
+
return invalid('STATUS_PROVIDER_INVALID');
|
|
22
|
+
if (status.exitCode !== result.exitCode)
|
|
23
|
+
return invalid('STATUS_EXIT_MISMATCH');
|
|
24
|
+
if (typeof status.loggedIn !== 'boolean')
|
|
25
|
+
return invalid('STATUS_LOGGED_IN_INVALID', { loggedInType: status.loggedIn === null ? 'null' : typeof status.loggedIn });
|
|
26
|
+
if (result.stderr !== '')
|
|
27
|
+
return invalid('STATUS_STDERR_NONEMPTY', { stderr: outputSummary(result.stderr) });
|
|
15
28
|
if (status.loggedIn ? result.exitCode !== 0 : provider === 'codex' ? result.exitCode !== 1 : result.exitCode !== 0 && result.exitCode !== 1)
|
|
16
|
-
return
|
|
29
|
+
return invalid('STATUS_EXIT_INVALID');
|
|
17
30
|
return ok({ provider, loggedIn: status.loggedIn });
|
|
18
31
|
}
|
package/lib/components.d.ts
CHANGED
|
@@ -7,4 +7,4 @@ export interface ComponentInventory {
|
|
|
7
7
|
claude: string;
|
|
8
8
|
codex?: string;
|
|
9
9
|
}
|
|
10
|
-
export declare function registerComponents(ctx: Context, inventory?: ComponentInventory, temporaryDataParent?: string, component?: ComponentProgressStore, sources?: ComponentSources, observationIntervalMs?: number, metadataMaxBytes?: number): void;
|
|
10
|
+
export declare function registerComponents(ctx: Context, inventory?: ComponentInventory, temporaryDataParent?: string, component?: ComponentProgressStore, sources?: ComponentSources, observationIntervalMs?: number, metadataMaxBytes?: number, administratorAfterMs?: number): void;
|