@ai-workbench/connect 0.7.46 → 0.7.48-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ 0.7.47:登录检查的外层 SSH 拒连、中断按既有连接类错误提示;真实认证读取失败仍保留原错误。传输原因只进脱敏技术详情,不新增设置或重试。随总包0.3.10分发。
2
+
1
3
  员工一次安装:在官方 DSH「插件 → 添加插件」输入 `@ai-workbench/workbench`。已分装 network、connect、remote-agent 的,先移除三者,再装总包。
2
4
 
3
5
  本轮总包0.1.6精确锁定 network 0.4.11 / connect 0.7.39 / remote-agent 0.8.31;管理员按[总包发版说明](packages/workbench/README.md)重新生成并核验固定 tgz 与 SHA。工人不 publish。
package/client/index.cjs CHANGED
@@ -447,7 +447,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
447
447
  const locationCall=async(path,body)=>{if(state.reconfirming)return {ok:false,error:{code:'CONNECTION_UNKNOWN',message:'正在重新确认,请先重新检查当前连接。'}};const before=state.value?.workspaceLocations,at=eventVersion;let result;try{result=await call('/workspace-locations/'+path,'POST',body);}catch(error){if(!disposed&&at===eventVersion)failure();throw error;}if(disposed)return result;if(result?.ok&&path!=='browse'&&!validLocations(result.value)){if(at===eventVersion)failure();return {ok:false,error:{code:'CONNECTION_UNKNOWN',message:'工作区位置快照无法核实,请重新检查当前连接。'}};}if(result?.ok&&path!=='browse'&&state.value&&before?.instanceId===state.value.workspaceLocations?.instanceId&&before?.epoch===state.value.workspaceLocations?.epoch&&(path!=='select'||sameLocationContext(state.value.workspaceLocations,body))){const next=acceptLocations(result.value,'http');publish({...state,value:{...state.value,workspaceLocations:next}});}return result;};
448
448
  const accept=(value,source='event')=>{if(disposed)return;const next=value?.startup?.revision,id=value?.startup?.instanceId;if(typeof id!=='string'||!id||!Number.isSafeInteger(next)||next<0||!validSnapshot(value)){failure();return;}if(id!==instance){if(instance&&(source==='http'||retired.has(id)))return;if(instance)retired.add(instance);instance=id;revision=-1;}if(next<revision)return;revision=next;if(value.workspaceLocations)value={...value,workspaceLocations:acceptLocations(value.workspaceLocations,source)};publish({...state,value,error:value.actionErrorCode||value.enrollment?.need?.code||(value.actionError?'ACTION_FAILED':''),reconfirming:false});};
449
449
  const failure=()=>{if(!disposed)publish({...state,error:'CONNECTION_UNKNOWN',reconfirming:true});};
450
- return {getWorkspaceDirectoryPickerSettings:()=>call('/directory-picker/config','GET'),browseWorkspaceDirectories:body=>call('/directory-picker/browse','POST',body),createWorkspaceDirectory:body=>call('/directory-picker/create','POST',body),selectWorkspaceDirectory:body=>call('/directory-picker/select','POST',body),refreshWorkspaceLocations:()=>locationCall('refresh',{}),browseWorkspaceHostDirectories:body=>locationCall('browse',body),selectWorkspaceLocation:body=>locationCall('select',body),readConversationLog:()=>call('/conversation-log','GET'),quota:(path,body)=>call('/quota/'+path,body===undefined?'GET':'POST',body),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){if(state.reconfirming&&path!=='/check'||state.importing||state.acting)return;const account=/^\/(forget|logout)\//.test(path);if(account)publish({...state,acting:true});const importing=path==='/enrollment/import';if(importing)publish({...state,importing:true,error:''});const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}finally{if(!disposed&&(account||importing))publish({...state,...(account?{acting:false}:{}),...(importing?{importing:false}:{})});}},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();}};
450
+ return {readNetworkQuality:refresh=>call('/network-quality'+(refresh?'?refresh=1':''),'GET'),getWorkspaceDirectoryPickerSettings:()=>call('/directory-picker/config','GET'),browseWorkspaceDirectories:body=>call('/directory-picker/browse','POST',body),createWorkspaceDirectory:body=>call('/directory-picker/create','POST',body),selectWorkspaceDirectory:body=>call('/directory-picker/select','POST',body),refreshWorkspaceLocations:()=>locationCall('refresh',{}),browseWorkspaceHostDirectories:body=>locationCall('browse',body),selectWorkspaceLocation:body=>locationCall('select',body),readConversationLog:()=>call('/conversation-log','GET'),quota:(path,body)=>call('/quota/'+path,body===undefined?'GET':'POST',body),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){if(state.reconfirming&&path!=='/check'||state.importing||state.acting)return;const account=/^\/(forget|logout)\//.test(path);if(account)publish({...state,acting:true});const importing=path==='/enrollment/import';if(importing)publish({...state,importing:true,error:''});const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}finally{if(!disposed&&(account||importing))publish({...state,...(account?{acting:false}:{}),...(importing?{importing:false}:{})});}},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();}};
451
451
  }
452
452
  function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,reconfirming:snapshot.reconfirming,importing:snapshot.importing,acting:snapshot.acting,action:workbench.action};}
453
453
  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];}
@@ -589,6 +589,30 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
589
589
  function SettingsDisclosure({title,description,action,error,children,onOpen}){const [open,setOpen]=React.useState(false);return h('div',{'data-settings-disclosure':title,style:{borderBottom:'.5px solid var(--dsw-alias-border-l2)',padding:'16px 0',minWidth:0}},h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',gap:24,flexWrap:'wrap'}},h('div',{style:{flex:1,minWidth:0}},h(UI.DisclosureRow,{title:h('span',{style:{fontSize:14,lineHeight:'20px',fontWeight:400,color:'var(--dsw-alias-label-primary)'}},title),icon:h(UI.IconChevronRightOutlineRegular,{'aria-hidden':true}),open,expandable:true,expandOnRowClick:true,onToggle:()=>{const next=!open;setOpen(next);if(next)void onOpen?.();}}),description?h('div',{style:{...(error?errorStyle:descriptionStyle),marginTop:4,paddingLeft:22}},description):null),action?h('div',{style:{flexShrink:0}},action):null),open?h('div',{style:{paddingLeft:22,minWidth:0}},children):null);}
590
590
 
591
591
 
592
+ const NETWORK_GOOD_MS=150,NETWORK_FAIR_MS=500,NETWORK_REFRESH_MS=60_000;
593
+ function networkGrade(ms){return ms===null?'断开':ms<NETWORK_GOOD_MS?'好':ms<NETWORK_FAIR_MS?'一般':'差';}
594
+ function NetworkSignal({workbench,context,available=true}){
595
+ const [quality,setQuality]=React.useState(null),[phase,setPhase]=React.useState('checking');
596
+ React.useEffect(()=>{
597
+ let alive=true,busy=false;
598
+ setQuality(null);setPhase(available?'checking':'unavailable');
599
+ if(!available||!workbench.readNetworkQuality)return()=>{alive=false;};
600
+ const read=async(refresh=false)=>{if(busy)return;busy=true;try{const value=await workbench.readNetworkQuality(refresh);if(alive){const q=value?.quality;setQuality(q?.apiVersion===1&&Array.isArray(q.samples)?q:null);setPhase(q?'ready':'unavailable');}}catch{if(alive){setQuality(null);setPhase('unavailable');}}finally{busy=false;}};
601
+ void read(true);const timer=setInterval(()=>void read(),NETWORK_REFRESH_MS);
602
+ return()=>{alive=false;clearInterval(timer);};
603
+ },[workbench,context,available]);
604
+ const samples=quality?.samples??[],latest=samples.at(-1),grade=latest?networkGrade(latest.latencyMs):null,bars=grade==='好'?3:grade==='一般'?2:grade==='差'?1:0;
605
+ const latency=ms=>ms===null?'无回应':Math.round(ms)+' ms';
606
+ const time=at=>new Date(at).toLocaleString('zh-CN',{hour12:false});
607
+ const route=latest?.path==='direct'?'直连':latest?.path==='derp'?'中转'+(latest.relayCity?' · '+latest.relayCity:'')+(latest.relayRegion?'('+latest.relayRegion+')':''):latest?.path==='peer-relay'?'对端中转':'未知';
608
+ return h('div',{'data-network-signal':true,style:{paddingTop:12}},
609
+ h('div',{'aria-live':'polite','data-network-grade':grade??phase,style:{display:'flex',alignItems:'center',gap:8,fontSize:13}},
610
+ h('span',{'aria-hidden':true,style:{display:'inline-flex',gap:3,height:16,alignItems:'flex-end'}},...[7,11,16].map((height,i)=>h('span',{key:i,style:{display:'block',width:4,height,background:'currentColor',borderRadius:1,opacity:i<bars?1:.2}}))),
611
+ latest?h('span',null,'网络信号:'+grade+' · '+latency(latest.latencyMs)):h('span',null,phase==='checking'?'正在检测网络…':phase==='unavailable'?'网络检测暂不可用':'尚无网络检测记录')),
612
+ latest?h(React.Fragment,null,h('p',{style:descriptionStyle},'检测路径:'+route+' · 检测于 '+time(latest.observedAt)),
613
+ h('p',{style:{...descriptionStyle,overflowWrap:'anywhere'}},'最近 '+samples.length+' 次(旧→新):'+samples.map(s=>new Date(s.observedAt).toLocaleTimeString('zh-CN',{hour12:false})+' '+(s.latencyMs===null?'×':Math.round(s.latencyMs)+' ms')).join('、'))):null,
614
+ h('p',{style:descriptionStyle},'约每分钟检测一次;好 <150 ms,一般 <500 ms,差 ≥500 ms,断开为无回应。检测结果仅供参考。'));
615
+ }
592
616
  function SettingsRow({title,status,action,children,error}){return h('div',{style:{borderBottom:'.5px solid var(--dsw-alias-border-l2)',padding:'16px 0'}},h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',gap:24,flexWrap:'wrap'}},h('div',{style:{flex:1,minWidth:0}},h('div',{style:{fontSize:14,lineHeight:'20px',fontWeight:400}},title),h('div',{style:{...descriptionStyle,marginTop:4,...error?{color:'var(--dsw-alias-state-error-primary)'}:{}}},status)),action?h('div',{style:{flexShrink:0}},action):null),children);}
593
617
  function Advanced({t,children}){const [open,setOpen]=React.useState(false);return h('div',{style:{marginTop:24}},h(UI.DisclosureRow,{title:t('advanced'),icon:h(UI.IconChevronRightOutlineRegular,{'aria-hidden':true}),open,expandable:true,expandOnRowClick:true,onToggle:()=>setOpen(value=>!value)},children));}
594
618
 
@@ -682,7 +706,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
682
706
  reconfirming?h('p',{role:'status'},t('reconfirming')):null,
683
707
  h('fieldset',{disabled:!!reconfirming||!!acting,style:{border:0,padding:0,margin:0,minWidth:0}},
684
708
  h(SettingsRow,{title:t('connectionFiles'),error:!!enrollmentError,status:imported&&!connecting?t('imported',{employee:enrollment.username?t('parenthetical',{value:enrollment.username}):''}):enrollmentError?t(enrollmentError==='ENROLLMENT_REQUIRED'?'enrollmentKeyMissing':needKey(enrollmentError)):t(connecting?'networkChecking':'importHelp'),action:forgetPath?h(Button,{type:'button',variant:'toolbar',size:'md',disabled:!!acting||connecting,onClick:()=>setConfirmForget({employee:enrollment.username,path:forgetPath})},t('forgetConnection')):h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting||['ENROLLMENT_KEY_REJECTED','ENROLLMENT_REJECTED'].includes(enrollmentError),onClick:()=>void action('/enrollment/import')},t('import'))}),
685
- h(SettingsRow,{title:t('networkLabel'),error:!!networkError,status:connecting?t('networkChecking'):connected?t('networkConnected'):state?.connection?.recovery?.phase==='reconnecting'?h(ConnectionInterruption,{recovery:state.connection.recovery}):networkError?h(NeedMessage,{need:state.connection.need}):t(!imported?'networkWaiting':'unknown'),action:h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting,onClick:()=>void action()},t('recheck'))}),
709
+ h(SettingsRow,{title:t('networkLabel'),error:!!networkError,status:connecting?t('networkChecking'):connected?t('networkConnected'):state?.connection?.recovery?.phase==='reconnecting'?h(ConnectionInterruption,{recovery:state.connection.recovery}):networkError?h(NeedMessage,{need:state.connection.need}):t(!imported?'networkWaiting':'unknown'),action:h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting,onClick:()=>void action()},t('recheck'))},h(NetworkSignal,{workbench,context:JSON.stringify([enrollment?.instanceId,enrollment?.revision,enrollment?.phase,state?.network?.phase,reconfirming]),available:!reconfirming&&imported&&state?.network?.phase==='online'})),
686
710
  ...['codex','claude'].map(provider=>{
687
711
  const brand=provider==='claude'?'Claude':'Codex',{checking,unknown,ready}=providerStatus(connecting?undefined:s,provider),active=state?.browserLogin?.provider===provider&&s?.phase==='authorizing',question=isLoginQuestion(state)&&s.provider===provider;
688
712
  const allowed=!connecting&&!checking&&(s?.logins?.[provider]===false&&!unknown||provider==='claude'&&unknown&&!['checking','disposed'].includes(s?.phase));
@@ -697,7 +721,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
697
721
  confirmForget?h(UI.Modal,{open:true,title:t('forgetConnection'),onClose:()=>setConfirmForget(null)},h('p',null,t('forgetConfirm',{employee:confirmForget.employee})),h(Button,{type:'button',variant:'toolbar',size:'md',onClick:()=>setConfirmForget(null)},t('cancel')),h(Button,{type:'button',variant:'toolbar',size:'md',onClick:()=>{const path=confirmForget.path;setConfirmForget(null);if(path===forgetPath)void action(path);}},t('confirmForget'))):null,
698
722
  h(Advanced,{t},!state?.workspaceLocations?h('p',{style:descriptionStyle},t('workspaceLimit')):null,workbench.directoryPickerRegistration?h(WorkspacePickerSettings,{registration:workbench.directoryPickerRegistration}):null,h(WorkspaceLocations,{state,workbench}),h(Details,{state,error,t}),h(ConversationLog,{workbench})));
699
723
  }
700
- return {name:'ai-workbench-connect-client',inject:['slots','locale','uiWorkspace'],createWorkbenchController,WorkspaceDirectoryFlow,RemoteWorkspaceBrowser,createWorkspaceDirectoryPickerRegistration,Panel,dictionaries,apply(ctx){
724
+ return {name:'ai-workbench-connect-client',inject:['slots','locale','uiWorkspace'],createWorkbenchController,WorkspaceDirectoryFlow,RemoteWorkspaceBrowser,createWorkspaceDirectoryPickerRegistration,Panel,NetworkSignal,networkGrade,dictionaries,apply(ctx){
701
725
  ctx.effect(()=>ctx.locale.register(NS,dictionaries));const t=ctx.locale.bind(NS);
702
726
  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();});
703
727
  const registration=createWorkspaceDirectoryPickerRegistration(ctx,workbench);workbench.directoryPickerRegistration=registration;
@@ -1,8 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
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'];
3
+ const markers = ['AW_REMOTE_COMMAND_KILL_FAILED', 'AUTH_STATUS_JSON_INVALID:SyntaxError', 'Permission denied', 'Host key verification failed', 'Connection refused', 'Connection closed', 'Broken pipe', 'Connection reset by peer', 'Connection timed out', 'command not found', 'No such file or directory'];
4
4
  const names = ['Error', 'TypeError', 'SyntaxError', 'RangeError', 'AbortError', 'DOMException', 'UnknownError'];
5
5
  const codes = ['ENOENT', 'ENOTDIR', 'EIO', 'EPERM', 'ESRCH', 'EACCES', 'EINVAL', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ABORT_ERR', 'UNKNOWN'];
6
+ const transportReasons = ['CONNECTION_REFUSED', 'CONNECTION_RESET', 'PIPE_CLOSED', 'CONNECTION_CLOSED', 'CONNECTION_TIMEOUT', 'CANCELLED', 'SSH_EXIT_NONZERO', 'SSH_STDERR_NONEMPTY', 'SSH_PROCESS_FAILED'];
6
7
  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
8
  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
9
  const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -20,7 +21,7 @@ export function validAuthDiagnosticReason(value) {
20
21
  }
21
22
  if (!object(v) || JSON.stringify(v) !== value || v.version !== 1 || !stages.includes(v.stage) || !reasons.includes(v.reason))
22
23
  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
+ const fields = { transportReason: x => transportReasons.includes(x), 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
25
  return Object.entries(v).every(([key, item]) => Object.hasOwn(fields, key) && fields[key](item));
25
26
  }
26
27
  // Raw command output and exception messages can contain authentication material.
@@ -38,8 +39,30 @@ export class AuthDiagnosticError extends Error {
38
39
  diagnostic;
39
40
  constructor(diagnostic, message = 'REMOTE_RESULT_INVALID') { super(message); this.name = 'AuthDiagnosticError'; this.diagnostic = diagnostic; }
40
41
  }
42
+ // 仅外层 SSH/进程及固定系统错误参与传输归类;已解帧的认证结果不走此分支。
43
+ function transportReason(error) {
44
+ const d = error instanceof AuthDiagnosticError ? error.diagnostic : undefined;
45
+ const code = (d?.errorCode ?? error?.code);
46
+ const systems = { ECONNREFUSED: 'CONNECTION_REFUSED', ECONNRESET: 'CONNECTION_RESET', EPIPE: 'PIPE_CLOSED', ETIMEDOUT: 'CONNECTION_TIMEOUT', ABORT_ERR: 'CANCELLED' };
47
+ if (typeof code === 'string' && Object.hasOwn(systems, code))
48
+ return systems[code];
49
+ if (!d)
50
+ return;
51
+ if (['ssh-result', 'process-runner'].includes(String(d.stage)) && d.reason === 'CANCELLED')
52
+ return 'CANCELLED';
53
+ if (d.stage === 'ssh-result' && ['SSH_EXIT_NONZERO', 'SSH_STDERR_NONEMPTY'].includes(String(d.reason))) {
54
+ const found = d.stderr?.markers ?? [];
55
+ for (const [marker, reason] of [['Connection refused', 'CONNECTION_REFUSED'], ['Connection reset by peer', 'CONNECTION_RESET'], ['Broken pipe', 'PIPE_CLOSED'], ['Connection closed', 'CONNECTION_CLOSED'], ['Connection timed out', 'CONNECTION_TIMEOUT']])
56
+ if (found.includes(marker))
57
+ return reason;
58
+ return String(d.reason);
59
+ }
60
+ if (['process-spawn', 'process-stdin', 'process-runner'].includes(String(d.stage)) && ['SPAWN_FAILED', 'STDIN_FAILED', 'PROCESS_SIGNAL'].includes(String(d.reason)))
61
+ return 'SSH_PROCESS_FAILED';
62
+ }
41
63
  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)) }) });
64
+ const transport = transportReason(error);
65
+ const value = need(transport ? ['CONNECTION_RESET', 'PIPE_CLOSED', 'CONNECTION_CLOSED', 'CANCELLED'].includes(transport) ? 'CONNECTION_LOST' : 'SSH_FAILED' : code);
66
+ value.officialReason = JSON.stringify({ version: 1, ...(error instanceof AuthDiagnosticError ? error.diagnostic : { stage, reason, ...details, ...(error === undefined ? {} : exceptionSummary(error)) }), ...(transport ? { transportReason: transport } : {}) });
44
67
  return { ok: false, error: value };
45
68
  }
package/lib/components.js CHANGED
@@ -49,6 +49,29 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
49
49
  return;
50
50
  }
51
51
  const path = new URL(req.url ?? '/', 'http://dsh').pathname, service = api();
52
+ if (req.method === 'GET' && path === '/ai-workbench-connect/network-quality') {
53
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
54
+ const network = ctx.get('aiWorkbenchNetwork');
55
+ const current = service?.getEnrollmentState?.(), cancel = new AbortController();
56
+ const closed = () => cancel.abort();
57
+ res.once('close', closed);
58
+ let quality = null;
59
+ try {
60
+ quality = await network?.readNetworkQuality?.(cancel.signal, new URL(req.url, 'http://dsh').searchParams.get('refresh') === '1') ?? null;
61
+ }
62
+ catch {
63
+ quality = null;
64
+ }
65
+ res.removeListener('close', closed);
66
+ const next = api()?.getEnrollmentState?.();
67
+ if (network !== ctx.get('aiWorkbenchNetwork') || current?.instanceId !== next?.instanceId || current?.revision !== next?.revision)
68
+ quality = null;
69
+ if (!res.destroyed) {
70
+ res.statusCode = 200;
71
+ res.end(JSON.stringify({ quality }));
72
+ }
73
+ return;
74
+ }
52
75
  if (req.method === 'GET' && path === '/ai-workbench-connect/events' && service) {
53
76
  res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
54
77
  res.statusCode = 200;
package/lib/connect.js CHANGED
@@ -201,7 +201,7 @@ export function createConnect(ports, emit, options = {}) {
201
201
  const failure = authFailure('connect-check-login', 'STATUS_EXCEPTION', {}, error);
202
202
  if (!startup.finishCheck(ticket, failure))
203
203
  return authFailure('connect-check-login', 'STATUS_SUPERSEDED');
204
- return block(failure);
204
+ return ['network', 'ssh', 'enrollment'].includes(failure.error.layer) ? transportBlock(failure) : block(failure);
205
205
  }
206
206
  };
207
207
  const login = (provider) => {
package/lib/ssh.js CHANGED
@@ -107,8 +107,8 @@ export function createSsh(runner, maxOutputBytes) {
107
107
  const r = await runRemote(runner, t, 'id -un', signal);
108
108
  return r.exitCode === 0 && r.stdout.trim() === t.username ? ok(undefined) : fail('SSH_FAILED');
109
109
  }
110
- catch {
111
- return fail('SSH_FAILED');
110
+ catch (error) {
111
+ return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error, 'SSH_FAILED');
112
112
  } },
113
113
  status: async (t, p, signal) => {
114
114
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.46",
3
+ "version": "0.7.48-rc.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",
@@ -1,216 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
-
9
- ## [2.0.1] - 2020-08-29
10
- ### Fixed
11
- - Fix issue with `process.argv` when used with interpreters (`coffee`, `ts-node`, etc.), #150.
12
-
13
-
14
- ## [2.0.0] - 2020-08-14
15
- ### Changed
16
- - Full rewrite. Now port from python 3.9.0 & more precise following.
17
- See [doc](./doc) for difference and migration info.
18
- - node.js 10+ required
19
- - Removed most of local docs in favour of original ones.
20
-
21
-
22
- ## [1.0.10] - 2018-02-15
23
- ### Fixed
24
- - Use .concat instead of + for arrays, #122.
25
-
26
-
27
- ## [1.0.9] - 2016-09-29
28
- ### Changed
29
- - Rerelease after 1.0.8 - deps cleanup.
30
-
31
-
32
- ## [1.0.8] - 2016-09-29
33
- ### Changed
34
- - Maintenance (deps bump, fix node 6.5+ tests, coverage report).
35
-
36
-
37
- ## [1.0.7] - 2016-03-17
38
- ### Changed
39
- - Teach `addArgument` to accept string arg names. #97, @tomxtobin.
40
-
41
-
42
- ## [1.0.6] - 2016-02-06
43
- ### Changed
44
- - Maintenance: moved to eslint & updated CS.
45
-
46
-
47
- ## [1.0.5] - 2016-02-05
48
- ### Changed
49
- - Removed lodash dependency to significantly reduce install size.
50
- Thanks to @mourner.
51
-
52
-
53
- ## [1.0.4] - 2016-01-17
54
- ### Changed
55
- - Maintenance: lodash update to 4.0.0.
56
-
57
-
58
- ## [1.0.3] - 2015-10-27
59
- ### Fixed
60
- - Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple.
61
-
62
-
63
- ## [1.0.2] - 2015-03-22
64
- ### Changed
65
- - Relaxed lodash version dependency.
66
-
67
-
68
- ## [1.0.1] - 2015-02-20
69
- ### Changed
70
- - Changed dependencies to be compatible with ancient nodejs.
71
-
72
-
73
- ## [1.0.0] - 2015-02-19
74
- ### Changed
75
- - Maintenance release.
76
- - Replaced `underscore` with `lodash`.
77
- - Bumped version to 1.0.0 to better reflect semver meaning.
78
- - HISTORY.md -> CHANGELOG.md
79
-
80
-
81
- ## [0.1.16] - 2013-12-01
82
- ### Changed
83
- - Maintenance release. Updated dependencies and docs.
84
-
85
-
86
- ## [0.1.15] - 2013-05-13
87
- ### Fixed
88
- - Fixed #55, @trebor89
89
-
90
-
91
- ## [0.1.14] - 2013-05-12
92
- ### Fixed
93
- - Fixed #62, @maxtaco
94
-
95
-
96
- ## [0.1.13] - 2013-04-08
97
- ### Changed
98
- - Added `.npmignore` to reduce package size
99
-
100
-
101
- ## [0.1.12] - 2013-02-10
102
- ### Fixed
103
- - Fixed conflictHandler (#46), @hpaulj
104
-
105
-
106
- ## [0.1.11] - 2013-02-07
107
- ### Added
108
- - Added 70+ tests (ported from python), @hpaulj
109
- - Added conflictHandler, @applepicke
110
- - Added fromfilePrefixChar, @hpaulj
111
-
112
- ### Fixed
113
- - Multiple bugfixes, @hpaulj
114
-
115
-
116
- ## [0.1.10] - 2012-12-30
117
- ### Added
118
- - Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion)
119
- support, thanks to @hpaulj
120
-
121
- ### Fixed
122
- - Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj
123
-
124
-
125
- ## [0.1.9] - 2012-12-27
126
- ### Fixed
127
- - Fixed option dest interferens with other options (issue #23), thanks to @hpaulj
128
- - Fixed default value behavior with `*` positionals, thanks to @hpaulj
129
- - Improve `getDefault()` behavior, thanks to @hpaulj
130
- - Improve negative argument parsing, thanks to @hpaulj
131
-
132
-
133
- ## [0.1.8] - 2012-12-01
134
- ### Fixed
135
- - Fixed parser parents (issue #19), thanks to @hpaulj
136
- - Fixed negative argument parse (issue #20), thanks to @hpaulj
137
-
138
-
139
- ## [0.1.7] - 2012-10-14
140
- ### Fixed
141
- - Fixed 'choices' argument parse (issue #16)
142
- - Fixed stderr output (issue #15)
143
-
144
-
145
- ## [0.1.6] - 2012-09-09
146
- ### Fixed
147
- - Fixed check for conflict of options (thanks to @tomxtobin)
148
-
149
-
150
- ## [0.1.5] - 2012-09-03
151
- ### Fixed
152
- - Fix parser #setDefaults method (thanks to @tomxtobin)
153
-
154
-
155
- ## [0.1.4] - 2012-07-30
156
- ### Fixed
157
- - Fixed pseudo-argument support (thanks to @CGamesPlay)
158
- - Fixed addHelp default (should be true), if not set (thanks to @benblank)
159
-
160
-
161
- ## [0.1.3] - 2012-06-27
162
- ### Fixed
163
- - Fixed formatter api name: Formatter -> HelpFormatter
164
-
165
-
166
- ## [0.1.2] - 2012-05-29
167
- ### Fixed
168
- - Removed excess whitespace in help
169
- - Fixed error reporting, when parcer with subcommands
170
- called with empty arguments
171
-
172
- ### Added
173
- - Added basic tests
174
-
175
-
176
- ## [0.1.1] - 2012-05-23
177
- ### Fixed
178
- - Fixed line wrapping in help formatter
179
- - Added better error reporting on invalid arguments
180
-
181
-
182
- ## [0.1.0] - 2012-05-16
183
- ### Added
184
- - First release.
185
-
186
-
187
- [2.0.1]: https://github.com/nodeca/argparse/compare/2.0.0...2.0.1
188
- [2.0.0]: https://github.com/nodeca/argparse/compare/1.0.10...2.0.0
189
- [1.0.10]: https://github.com/nodeca/argparse/compare/1.0.9...1.0.10
190
- [1.0.9]: https://github.com/nodeca/argparse/compare/1.0.8...1.0.9
191
- [1.0.8]: https://github.com/nodeca/argparse/compare/1.0.7...1.0.8
192
- [1.0.7]: https://github.com/nodeca/argparse/compare/1.0.6...1.0.7
193
- [1.0.6]: https://github.com/nodeca/argparse/compare/1.0.5...1.0.6
194
- [1.0.5]: https://github.com/nodeca/argparse/compare/1.0.4...1.0.5
195
- [1.0.4]: https://github.com/nodeca/argparse/compare/1.0.3...1.0.4
196
- [1.0.3]: https://github.com/nodeca/argparse/compare/1.0.2...1.0.3
197
- [1.0.2]: https://github.com/nodeca/argparse/compare/1.0.1...1.0.2
198
- [1.0.1]: https://github.com/nodeca/argparse/compare/1.0.0...1.0.1
199
- [1.0.0]: https://github.com/nodeca/argparse/compare/0.1.16...1.0.0
200
- [0.1.16]: https://github.com/nodeca/argparse/compare/0.1.15...0.1.16
201
- [0.1.15]: https://github.com/nodeca/argparse/compare/0.1.14...0.1.15
202
- [0.1.14]: https://github.com/nodeca/argparse/compare/0.1.13...0.1.14
203
- [0.1.13]: https://github.com/nodeca/argparse/compare/0.1.12...0.1.13
204
- [0.1.12]: https://github.com/nodeca/argparse/compare/0.1.11...0.1.12
205
- [0.1.11]: https://github.com/nodeca/argparse/compare/0.1.10...0.1.11
206
- [0.1.10]: https://github.com/nodeca/argparse/compare/0.1.9...0.1.10
207
- [0.1.9]: https://github.com/nodeca/argparse/compare/0.1.8...0.1.9
208
- [0.1.8]: https://github.com/nodeca/argparse/compare/0.1.7...0.1.8
209
- [0.1.7]: https://github.com/nodeca/argparse/compare/0.1.6...0.1.7
210
- [0.1.6]: https://github.com/nodeca/argparse/compare/0.1.5...0.1.6
211
- [0.1.5]: https://github.com/nodeca/argparse/compare/0.1.4...0.1.5
212
- [0.1.4]: https://github.com/nodeca/argparse/compare/0.1.3...0.1.4
213
- [0.1.3]: https://github.com/nodeca/argparse/compare/0.1.2...0.1.3
214
- [0.1.2]: https://github.com/nodeca/argparse/compare/0.1.1...0.1.2
215
- [0.1.1]: https://github.com/nodeca/argparse/compare/0.1.0...0.1.1
216
- [0.1.0]: https://github.com/nodeca/argparse/releases/tag/0.1.0