@ai-workbench/connect 0.7.45 → 0.7.47
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 +12 -0
- package/client/index.cjs +77 -1
- package/helper/quota.cjs +81 -0
- package/lib/api.d.ts +1 -0
- package/lib/auth-diagnostics.js +27 -4
- package/lib/components.js +58 -0
- package/lib/connect.js +1 -1
- package/lib/defaults.d.ts +8 -0
- package/lib/defaults.js +3 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +14 -2
- package/lib/ports.d.ts +1 -0
- package/lib/quota.d.ts +81 -0
- package/lib/quota.js +131 -0
- package/lib/ssh.js +14 -2
- package/package.json +1 -1
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。
|
|
@@ -138,3 +140,13 @@ DSH workflow/subagent 并行派出的多个子会话(以及同一员工同时
|
|
|
138
140
|
### 登出时结束该品牌仍在运行的主机会话(0.7.45)
|
|
139
141
|
|
|
140
142
|
在“远程主机连接”里登出主机 Claude 或 Codex 后,L 在同一次主机命令里经主机会话控制(`aw-session status` 识别品牌,`kill --if-instance` 结束)结束该员工在主机上仍活着的这一品牌的会话进程;另一品牌不动,已无回应的残留目录不动。这些进程沿用登出前的登录,不应在登出后继续运行。正在进行的那一轮会结束,员工在原对话发下一条消息即按原会话续接(主机未登录时提示需要登录)。结束未获确认时登出报 `LOGOUT_FAILED`,可再次登出。CLI 登出本身失败时不动任何会话。不新增设置、限制或错误码。
|
|
143
|
+
|
|
144
|
+
### 订阅额度(0.7.46)
|
|
145
|
+
|
|
146
|
+
“远程主机连接”里 Codex、Claude 两个登录行下面各有一张“订阅额度”卡,显示方式和“使用重置”交互照抄 DSH 的 Codex 订阅插件(dsh-codex-subscription 3.2.16)。数据由 L 经员工自己的 ssh 通道在主机上运行 `helper/quota.cjs` 取得,用的是员工本人的主机登录,只走官方 CLI:Codex 走 `codex app-server` 的 `account/rateLimits/read` 和 `account/rateLimitResetCredit/consume`,Claude 走 `claude -p --input-format stream-json` 的 `get_usage` 控制请求(`/usage` 背后的数据,不发模型请求,不留会话)。凭据、账号 id、原始响应不出主机,只回传显示要用的字段;重置卡 id 和幂等键只留在 L 后台内存里,页面只拿不透明 ref。
|
|
147
|
+
|
|
148
|
+
- Codex:各额度窗口的剩余百分比、窗口(5 小时/每周…)、重置时间;额外 Credits 余额;Credits 月度消费上限;可用重置次数、每张重置卡的有效期,以及“使用重置”。
|
|
149
|
+
- “使用重置”:先点“使用重置”出现确认区,显示警告“执行后会消耗 1 次,且无法撤销”(额度未用尽时提示服务可能不执行)。须勾选“我知道…”,并等倒计时结束,“确认使用”才可点。结果“已完成/没有可重置的额度/没有可用的重置/已处理”。结果不确定时保留同一确认,再确认复用同一幂等键,不会另发一次重置。
|
|
150
|
+
- Claude:5 小时、每周、按模型的每周窗口,以及额外用量(本月已用/月上限,单位美分)。Claude 没有重置次数、“使用重置”和 Credits 余额,这几项不显示。
|
|
151
|
+
- 刷新:卡片显示时读一次;“刷新”按钮;页面重新可见时;使用重置后;页面可见期间按最高已用百分比定时重读。
|
|
152
|
+
- 新增 3 个具名设置,默认值照抄 DSH 插件,待 owner 追认:`quota.resetConfirmDelayMs`(5000)、`quota.resetChallengeTtlMs`(60000)、`quota.refreshSchedule`(<75% 60000、≥75% 30000、≥90% 15000、≥99% 5000 毫秒)。不新增错误码;不加请求时限(DSH 有 15 秒,我们其它主机调用都不设时限)。
|
package/client/index.cjs
CHANGED
|
@@ -431,6 +431,9 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
431
431
|
};
|
|
432
432
|
const needKey=code=>dictionaries.en['need.'+code]?'need.'+code:code==='ENROLLMENT_KEY_REJECTED'?'enrollmentKeyRejected':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_REQUIRED'?'loginRequired':code==='LOGIN_FAILED'?'loginFailed':code==='POLICY_DENIED'?'denied':code==='LOGIN_PROMPT_INVALID'?'stale':code==='ACTION_FAILED'?'actionFailed':'unavailable';
|
|
433
433
|
for(const dictionary of Object.values(dictionaries))Object.assign(dictionary,accountCopy);
|
|
434
|
+
// Quota card copy follows dsh-codex-subscription 3.2.16 (lib/client.js:2707-2804), with the brand named instead of ChatGPT.
|
|
435
|
+
const quotaCopy={"usage":"订阅额度","refresh":"刷新","refreshing":"刷新中…","noUsage":"登录后可读取主机上 {brand} 返回的额度窗口。","usageLoading":"正在读取额度…","usageEmpty":"当前账户没有返回可显示的额度窗口。请稍后刷新;这不代表额度为零。","usageRefreshFailed":"暂时无法更新额度,请稍后重试。","usageLastKnown":"上次获取的额度 · {value}","usageUpdated":"更新于 {value}","remaining":"剩余 {value}%","windowFiveHours":"5 小时额度","windowDaily":"每日额度","windowWeekly":"每周额度","windowMonthly":"每月额度","windowAnnual":"年度额度","windowHours":"{value} 小时额度","windowDays":"{value} 天额度","resets":"重置于 {value}","resetUnknown":"重置时间未提供","creditsFoldTitle":"额外 Credits 与额度重置","creditsBalance":"额外 Credits 余额","creditsUnit":"credits","unlimited":"不限额","unavailable":"暂无数据","creditsNote":"下方的额外 Credits 和额度重置与套餐额度分开计算。","creditsAfterAllowance":"Credits 要等套餐额度用完后才会开始消耗,官方没有“先用 Credits”的开关。","monthlyCreditLimit":"Credits 月度消费上限","creditsUsed":"已用 {used} / {limit} credits","spendReached":"Credits 月度消费上限已用尽。","resetCredits":"额度重置","resetCreditsHint":"使用重置可恢复短周期额度、每周额度,或两者同时恢复。","resetAvailableTab":"可用","resetFull":"完全重置","resetCreditDefaultName":"额度重置","resetUse":"使用重置","resetPreparing":"准备中…","resetConfirmTitle":"确认使用额度重置","resetWarning":"执行后会消耗 1 次,且无法撤销。","resetEarlyWarning":"当前额度未用尽,服务可能不执行重置。","resetAcknowledge":"我知道这次操作可能立即消耗 1 次重置","resetCreditExpires":"有效期至:{value}","resetCreditExpiryUnknown":"到期时间未提供","resetWait":"请等待 {count} 秒","resetFinal":"确认使用","resetUsing":"使用中…","resetSuccess":"额度重置已完成。","resetNothing":"当前没有可重置的额度,未消耗新的重置次数。","resetNoCredit":"没有可用的额度重置。","resetAlready":"这次重置请求已处理。","resetFailed":"无法使用额度重置。","resetRenewLogin":"登录状态已失效,请重新登录。","resetExpired":"本次确认已失效,请重新开始。","resetInProgress":"额度重置正在处理中。","resetTooEarly":"请等待冷静期结束后再确认。","resetAcknowledgeRequired":"请先确认已了解这次操作可能消耗重置次数。","resetUncertain":"服务端返回结果不确定。请再次确认,插件会复用同一个请求,不会另外发起一次重置。","extraUsage":"额外用量(本月)","extraUsageUsed":"已用 {used} / {limit}","extraUsageOff":"未开启"};
|
|
436
|
+
for(const dictionary of Object.values(dictionaries))Object.assign(dictionary,quotaCopy);
|
|
434
437
|
function createWorkbenchController(call,subscribe){
|
|
435
438
|
let state={value:undefined,error:'',reconfirming:false,importing:false,acting:false},disposed=false,started=false,off,revision=-1,instance,eventVersion=0;let workspaceLocations;const retiredLocations=new Set();const retired=new Set(),listeners=new Set();
|
|
436
439
|
const publish=next=>{state=next;for(const fn of listeners)fn();};
|
|
@@ -444,7 +447,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
444
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;};
|
|
445
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});};
|
|
446
449
|
const failure=()=>{if(!disposed)publish({...state,error:'CONNECTION_UNKNOWN',reconfirming:true});};
|
|
447
|
-
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'),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 {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();}};
|
|
448
451
|
}
|
|
449
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};}
|
|
450
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 +592,78 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
589
592
|
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);}
|
|
590
593
|
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));}
|
|
591
594
|
|
|
595
|
+
|
|
596
|
+
// Quota card: display, refresh timing and reset confirmation copied from dsh-codex-subscription 3.2.16 (lib/client.js:11804-11880, 19925-20400).
|
|
597
|
+
const later=(fn,ms)=>typeof setTimeout==='function'?setTimeout(fn,ms):undefined,cancelLater=id=>{if(id!==undefined&&typeof clearTimeout==='function')clearTimeout(id);};
|
|
598
|
+
const uiLocale=()=>typeof document==='undefined'?undefined:document.documentElement?.lang||undefined;
|
|
599
|
+
const pct=value=>Number(value).toLocaleString(uiLocale(),{maximumFractionDigits:1});
|
|
600
|
+
const amount=value=>Number.isFinite(Number(value))&&String(value).trim()!==''?Number(value).toLocaleString(uiLocale(),{maximumFractionDigits:2}):value;
|
|
601
|
+
const near=(seconds,expected)=>seconds>=expected*.95&&seconds<=expected*1.05;
|
|
602
|
+
function windowLabel(minutes,t){const seconds=minutes*60;if(!Number.isFinite(seconds)||seconds<=0)return '';if(near(seconds,18e3))return t('windowFiveHours');if(near(seconds,86400))return t('windowDaily');if(near(seconds,604800))return t('windowWeekly');if(near(seconds,2592e3))return t('windowMonthly');if(near(seconds,31536e3))return t('windowAnnual');return seconds>=86400&&seconds%86400===0?t('windowDays',{value:(seconds/86400).toLocaleString(uiLocale())}):t('windowHours',{value:(Math.round(seconds/3600*10)/10).toLocaleString(uiLocale())});}
|
|
603
|
+
function dateOf(ms){const date=new Date(ms);return Number.isFinite(date.getTime())?date:undefined;}
|
|
604
|
+
function ResetTime({resetsAt,t}){const date=Number.isSafeInteger(resetsAt)?dateOf(resetsAt*1000):undefined;if(!date)return h('span',null,t('resetUnknown'));return h('time',{dateTime:date.toISOString(),title:date.toLocaleString(uiLocale())},t('resets',{value:date.toLocaleString(uiLocale(),{month:'numeric',day:'numeric',hour:'2-digit',minute:'2-digit'})}));}
|
|
605
|
+
function ResetExpiry({expiresAt,t}){const date=Number.isSafeInteger(expiresAt)?dateOf(expiresAt>1e12?expiresAt:expiresAt*1000):undefined;return h('span',{style:descriptionStyle},date?h('time',{dateTime:date.toISOString()},t('resetCreditExpires',{value:date.toLocaleDateString(uiLocale(),{month:'long',day:'numeric'})})):t('resetCreditExpiryUnknown'));}
|
|
606
|
+
const resetErrorKey={'not-signed-in':'resetRenewLogin',expired:'resetExpired','in-progress':'resetInProgress','too-early':'resetTooEarly','acknowledge-required':'resetAcknowledgeRequired','no-credit':'resetNoCredit',uncertain:'resetUncertain'};
|
|
607
|
+
function ResetControl({workbench,t,credit,exhausted,onConsumed}){
|
|
608
|
+
const lock=React.useRef(false),[challenge,setChallenge]=React.useState(),[busy,setBusy]=React.useState(false),[acknowledged,setAcknowledged]=React.useState(false),[countdown,setCountdown]=React.useState(0),[error,setError]=React.useState(),[result,setResult]=React.useState();
|
|
609
|
+
React.useEffect(()=>{if(!challenge){setCountdown(0);return;}const update=()=>setCountdown(Math.max(0,Math.ceil((challenge.readyAt-Date.now())/1000)));update();const timer=typeof setInterval==='function'?setInterval(update,250):undefined;return()=>{if(timer!==undefined)clearInterval(timer);};},[challenge]);
|
|
610
|
+
const fail=reply=>setError(t(resetErrorKey[reply?.reason]??'resetFailed'));
|
|
611
|
+
const prepare=()=>{if(busy||lock.current)return;lock.current=true;setBusy(true);setError();setResult();workbench.quota('codex/reset/prepare',{ref:credit.ref}).then(reply=>{if(reply?.ok){setChallenge(reply.value);setAcknowledged(false);}else fail(reply);},()=>fail()).finally(()=>{lock.current=false;setBusy(false);});};
|
|
612
|
+
const cancel=()=>{if(busy)return;setChallenge();setAcknowledged(false);setError();};
|
|
613
|
+
const ready=!!challenge&&acknowledged&&countdown===0;
|
|
614
|
+
const consume=()=>{if(busy||!ready||lock.current)return;lock.current=true;setBusy(true);setError();setResult();workbench.quota('codex/reset/consume',{challengeId:challenge.challengeId,acknowledged}).then(reply=>{if(reply?.ok){setChallenge();setAcknowledged(false);const outcome=reply.value?.outcome;setResult(t(outcome==='reset'?'resetSuccess':outcome==='nothingToReset'?'resetNothing':outcome==='noCredit'?'resetNoCredit':'resetAlready'));onConsumed();}else fail(reply);},()=>fail({reason:'uncertain'})).finally(()=>{lock.current=false;setBusy(false);});};
|
|
615
|
+
const name=credit.name===undefined?t('resetCreditDefaultName'):/^full reset$/i.test(credit.name)?t('resetFull'):credit.name;
|
|
616
|
+
return h('div',{'data-quota-reset':credit.ref,style:{padding:'8px 0'}},
|
|
617
|
+
!challenge?h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',gap:12,flexWrap:'wrap'}},h('div',null,h('strong',null,name),' ',h(ResetExpiry,{expiresAt:credit.expiresAt,t})),h(Button,{type:'button',variant:'outline',size:'sm',disabled:busy,'aria-busy':busy,onClick:prepare},busy?t('resetPreparing'):t('resetUse'))):
|
|
618
|
+
h('div',{role:'group'},h('h4',{style:{margin:'4px 0'}},challenge.title&&!/^full reset$/i.test(challenge.title)?challenge.title:t('resetConfirmTitle')),challenge.description?h('p',{style:descriptionStyle},challenge.description):null,h(ResetExpiry,{expiresAt:challenge.creditExpiresAt,t}),
|
|
619
|
+
h('p',{style:errorStyle},t(exhausted?'resetWarning':'resetEarlyWarning')),
|
|
620
|
+
h('label',{style:{display:'flex',gap:8,alignItems:'center',fontSize:12}},h('input',{type:'checkbox',checked:acknowledged,disabled:busy,onChange:event=>setAcknowledged(event.target.checked)}),h('span',null,t('resetAcknowledge'))),
|
|
621
|
+
countdown>0?h('p',{role:'status',style:descriptionStyle},t('resetWait',{count:countdown})):null,
|
|
622
|
+
h('div',{style:{display:'flex',gap:8,marginTop:8}},h(Button,{type:'button',variant:'outline',size:'sm',disabled:busy,onClick:cancel},t('cancel')),h(Button,{type:'button',variant:'outline',size:'sm',disabled:!ready||busy,'aria-busy':busy,onClick:consume},busy?t('resetUsing'):t('resetFinal')))),
|
|
623
|
+
result?h('p',{role:'status',style:descriptionStyle},result):null,
|
|
624
|
+
error?h('p',{role:'alert',style:errorStyle},error):null);
|
|
625
|
+
}
|
|
626
|
+
function QuotaCard({workbench,provider,brand,signedIn,t}){
|
|
627
|
+
const [usage,setUsage]=React.useState(),[busy,setBusy]=React.useState(false),[error,setError]=React.useState();
|
|
628
|
+
const live=React.useRef({timer:undefined,flight:undefined,generation:0,next:undefined});
|
|
629
|
+
const load=React.useCallback((force=false)=>{
|
|
630
|
+
const state=live.current;if(state.flight&&!force)return state.flight;cancelLater(state.timer);state.timer=undefined;const generation=state.generation;setBusy(true);
|
|
631
|
+
const visible=()=>typeof document==='undefined'||document.visibilityState!=='hidden';
|
|
632
|
+
const flight=Promise.resolve().then(()=>workbench.quota(provider)).then(reply=>{if(generation!==state.generation)return;if(reply?.ok){setUsage(reply.value);setError();state.next=reply.value.nextRefreshMs;}else{setError(reply?.reason==='connection'&&reply.message?{message:reply.message}:{reason:reply?.reason??'read-failed'});if(Number.isSafeInteger(reply?.nextRefreshMs))state.next=reply.nextRefreshMs;}},()=>{if(generation===state.generation)setError({reason:'read-failed'});}).finally(()=>{if(generation!==state.generation||state.flight!==flight)return;setBusy(false);state.flight=undefined;if(Number.isSafeInteger(state.next)&&state.next>0&&visible())state.timer=later(()=>{state.timer=undefined;load();},state.next);});
|
|
633
|
+
state.flight=flight;return flight;
|
|
634
|
+
},[workbench,provider]);
|
|
635
|
+
React.useEffect(()=>{const state=live.current;if(!signedIn){state.generation++;cancelLater(state.timer);state.timer=undefined;state.flight=undefined;setUsage();setError();setBusy(false);return;}
|
|
636
|
+
load(true);const wake=()=>{if(typeof document==='undefined'||document.visibilityState!=='hidden')load();else{cancelLater(state.timer);state.timer=undefined;}};
|
|
637
|
+
if(typeof document!=='undefined')document.addEventListener('visibilitychange',wake);
|
|
638
|
+
return()=>{state.generation++;cancelLater(state.timer);state.timer=undefined;state.flight=undefined;if(typeof document!=='undefined')document.removeEventListener('visibilitychange',wake);};},[signedIn,load]);
|
|
639
|
+
const limits=signedIn?usage?.limits??[]:[],visibleUsage=signedIn?usage:undefined;
|
|
640
|
+
const exhausted=limits.some(limit=>limit.id!=='code_review'&&limit.windows.some(window=>window.usedPercent>=100));
|
|
641
|
+
const resetCredits=visibleUsage?.resetCredits,credits=visibleUsage?.credits,individual=visibleUsage?.individualLimit,extra=visibleUsage?.extraUsage;
|
|
642
|
+
const hasDetails=limits.length>0||!!credits||!!individual||resetCredits?.availableCount>0||!!extra;
|
|
643
|
+
const fetchedAt=visibleUsage?dateOf(visibleUsage.fetchedAt):undefined;
|
|
644
|
+
const stale=!!error||limits.some(limit=>limit.windows.some(window=>Number.isSafeInteger(window.resetsAt)&&window.resetsAt*1000<=Date.now()));
|
|
645
|
+
const balance=credits?credits.unlimited?t('unlimited'):credits.balance==null?t('unavailable'):amount(credits.balance)+' '+t('creditsUnit'):'';
|
|
646
|
+
const money=cents=>extra?.currency?(cents/100).toLocaleString(uiLocale(),{style:'currency',currency:extra.currency}):(cents/100).toLocaleString(uiLocale(),{minimumFractionDigits:2,maximumFractionDigits:2});
|
|
647
|
+
const row=(label,value,key,children)=>h('div',{key,style:{padding:'8px 0'}},h('div',{style:{display:'flex',justifyContent:'space-between',gap:12}},h('span',{style:{fontSize:13}},label),h('strong',{style:{fontSize:13}},value)),children);
|
|
648
|
+
return h('div',{'data-quota':provider,style:{marginTop:12,padding:'12px',border:'.5px solid var(--dsw-alias-border-l2)',borderRadius:8}},
|
|
649
|
+
h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',gap:12,flexWrap:'wrap'}},h('div',null,h('strong',{style:{fontSize:13}},t('usage')),fetchedAt?h('time',{dateTime:fetchedAt.toISOString(),style:{...descriptionStyle,marginLeft:8}},t(stale?'usageLastKnown':'usageUpdated',{value:fetchedAt.toLocaleString(uiLocale())})):null),
|
|
650
|
+
h(Button,{type:'button',variant:'outline',size:'sm',disabled:!signedIn||busy,'aria-busy':busy,onClick:()=>load(true)},busy?t('refreshing'):t('refresh'))),
|
|
651
|
+
h('div',{'aria-live':'polite'},!signedIn?h('p',{style:descriptionStyle},t('noUsage',{brand})):null,signedIn&&busy&&!usage?h('p',{role:'status',style:descriptionStyle},t('usageLoading')):null,signedIn&&!busy&&!error&&usage&&!hasDetails?h('p',{role:'status',style:descriptionStyle},t('usageEmpty')):null),
|
|
652
|
+
signedIn&&error?h('p',{role:'alert',style:errorStyle},error.message??t(error.reason==='not-signed-in'?'resetRenewLogin':'usageRefreshFailed')):null,
|
|
653
|
+
visibleUsage?.spendControlReached===true?h('p',{role:'alert',style:errorStyle},t('spendReached')):null,
|
|
654
|
+
...limits.flatMap(limit=>limit.windows.map((window,index)=>h('div',{key:limit.id+'-'+window.windowMinutes+'-'+index,style:{padding:'8px 0'}},
|
|
655
|
+
h('div',{style:{display:'flex',justifyContent:'space-between',gap:12}},h('span',{style:{fontSize:13}},limit.name??limit.id),h('strong',{style:{fontSize:13}},pct(window.remainingPercent)+'%')),
|
|
656
|
+
h('progress',{max:'100',value:window.remainingPercent,style:{width:'100%'},'aria-label':(limit.name??limit.id)+' '+t('remaining',{value:pct(window.remainingPercent)})}),
|
|
657
|
+
h('div',{style:{...descriptionStyle,display:'flex',justifyContent:'space-between',gap:12}},h('span',null,windowLabel(window.windowMinutes,t)),h(ResetTime,{resetsAt:window.resetsAt,t}))))),
|
|
658
|
+
credits||individual||resetCredits?.availableCount>0?h('details',{style:{marginTop:8}},h('summary',{style:{fontSize:13}},t('creditsFoldTitle'),' ',h('span',{style:descriptionStyle},balance)),
|
|
659
|
+
h('p',{style:descriptionStyle},t('creditsNote')),
|
|
660
|
+
credits?row(t('creditsBalance'),balance,'balance'):null,
|
|
661
|
+
credits&&!credits.unlimited?h('p',{style:descriptionStyle},t('creditsAfterAllowance')):null,
|
|
662
|
+
resetCredits?.availableCount>0?h('section',{'aria-label':t('resetCredits'),style:{marginTop:8}},h('div',null,h('strong',{style:{fontSize:13}},t('resetCredits')),' ',h('span',{style:descriptionStyle},t('resetCreditsHint'))),h('div',{style:descriptionStyle},t('resetAvailableTab'),' ',h('b',null,resetCredits.availableCount)),
|
|
663
|
+
...resetCredits.credits.map(credit=>h(ResetControl,{key:credit.ref,workbench,t,credit,exhausted,onConsumed:()=>load(true)}))):null,
|
|
664
|
+
individual?row(t('monthlyCreditLimit'),t('remaining',{value:pct(individual.remainingPercent)}),'individual',h(React.Fragment,null,h('progress',{max:'100',value:individual.remainingPercent,style:{width:'100%'}}),individual.used!==undefined&&individual.limit!==undefined?h('div',{style:descriptionStyle},t('creditsUsed',{used:amount(individual.used),limit:amount(individual.limit)})):null,Number.isSafeInteger(individual.resetsAt)?h('div',{style:descriptionStyle},h(ResetTime,{resetsAt:individual.resetsAt,t})):null)):null):null,
|
|
665
|
+
extra?row(t('extraUsage'),extra.enabled?(Number.isFinite(extra.usedCents)&&Number.isFinite(extra.monthlyLimitCents)?t('extraUsageUsed',{used:money(extra.usedCents),limit:money(extra.monthlyLimitCents)}):t('unavailable')):t('extraUsageOff'),'extra'):null);
|
|
666
|
+
}
|
|
592
667
|
function providerStatus(s,provider){const checking=!s||s.phase==='checking'||s.checkingProviders?.includes(provider),unknown=!!s?.providerNeeds?.[provider]||s?.logins?.[provider]===undefined;return {checking,unknown,ready:!checking&&!unknown&&s?.logins?.[provider]===true,needsLogin:!checking&&!unknown&&s?.logins?.[provider]===false};}
|
|
593
668
|
function Panel(props){return h(Translation.Provider,{value:{t:props.t}},h(PanelBody,props));}
|
|
594
669
|
function PanelBody({workbench,t}){
|
|
@@ -613,6 +688,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
613
688
|
const allowed=!connecting&&!checking&&(s?.logins?.[provider]===false&&!unknown||provider==='claude'&&unknown&&!['checking','disposed'].includes(s?.phase));
|
|
614
689
|
return h(SettingsRow,{key:provider,title:t('provider',{brand}),status:t(active?'statusAuthorizing':checking?'statusChecking':unknown?'statusUnknown':ready?'statusSignedIn':'statusSignIn'),action:accountContext&&connected&&!active&&!checking&&ready?h(Button,{type:'button',variant:'toolbar',size:'md',disabled:!!acting||s?.phase==='authorizing',onClick:()=>void action(accountPath('logout/'+provider))},t('logoutHost',{brand})):!active&&allowed?h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting||s?.phase==='authorizing',onClick:()=>void action(question?'/respond/'+s.requestId+'/authorize':'/start-login/'+provider+'/'+s.instanceId+'/'+s.revision)},t('signIn',{brand})):!active&&!checking&&unknown?h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting||s?.phase==='authorizing',onClick:()=>void action()},t('recheck')):null},
|
|
615
690
|
active?h(BrowserLogin,{key:state.browserLogin.id,value:state.browserLogin,action}):null,
|
|
691
|
+
accountContext&&connected&&!unknown&&workbench.quota?h(QuotaCard,{workbench,provider,brand,signedIn:s?.logins?.[provider]===true,t}):null,
|
|
616
692
|
!connecting&&s?.providerNeeds?.[provider]&&!(provider==='claude'&&loginFailure)?h('div',{role:'alert',style:{...descriptionStyle,color:'var(--dsw-alias-state-error-primary)',marginTop:4}},h(NeedMessage,{need:s.providerNeeds[provider]})):null,
|
|
617
693
|
provider==='claude'&&loginFailure?h('p',{role:'alert',style:{...descriptionStyle,color:'var(--dsw-alias-state-error-primary)',marginTop:4}},t(ready?'claudeLoginReportedFailure':failure?.includes('不属于本次登录')?'invalidCode':failure?.includes('主机未确认成功')?'hostLoginFailed':'claudeLoginFailed')):null);
|
|
618
694
|
}),
|
package/helper/quota.cjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Host-side quota read for the employee's own Claude/Codex sign-in, through the official CLIs only.
|
|
2
|
+
// Credentials stay with the CLI; only the projected quota fields below leave this process.
|
|
3
|
+
// codex: official app-server account/rateLimits/read and account/rateLimitResetCredit/consume.
|
|
4
|
+
// claude: official CLI stream-json control request get_usage (the data behind /usage).
|
|
5
|
+
const {spawn}=require('node:child_process');
|
|
6
|
+
const [provider,budgetText,action='read',...extra]=process.argv.slice(1),budget=Number(budgetText);
|
|
7
|
+
if(!['codex','claude'].includes(provider)||!Number.isSafeInteger(budget)||budget<1||!['read','consume'].includes(action)||extra.length||action==='consume'&&provider!=='codex')process.exit(2);
|
|
8
|
+
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
9
|
+
const int=value=>Number.isSafeInteger(value)?value:undefined;
|
|
10
|
+
const text=(value,max=240)=>typeof value==='string'&&value.trim()?value.trim().slice(0,max):undefined;
|
|
11
|
+
let done=false;
|
|
12
|
+
function reply(body){if(done)return;done=true;process.stdout.write(JSON.stringify({protocolVersion:1,provider,...body})+'\n',()=>{stopChild();process.exit(0);});}
|
|
13
|
+
let child;
|
|
14
|
+
function stopChild(){if(child?.pid)try{process.kill(-child.pid,'SIGKILL');}catch{}}
|
|
15
|
+
process.on('SIGHUP',()=>{stopChild();process.exit(1);});process.on('SIGTERM',()=>{stopChild();process.exit(1);});
|
|
16
|
+
// Once a consume request may have reached the CLI, a crash, exit or overflow leaves its outcome unknown.
|
|
17
|
+
const failed=()=>reply({ok:false,reason:action==='consume'?'uncertain':'read-failed'});
|
|
18
|
+
function run(command,args,lines,onLine){
|
|
19
|
+
child=spawn(command,args,{detached:true,stdio:['pipe','pipe','ignore']});
|
|
20
|
+
let size=0,buffer='';
|
|
21
|
+
child.once('error',failed);
|
|
22
|
+
child.stdin.on('error',()=>{});
|
|
23
|
+
child.stdout.setEncoding('utf8');
|
|
24
|
+
child.stdout.on('data',chunk=>{size+=Buffer.byteLength(chunk);if(size>budget){failed();return;}buffer+=chunk;let index;while((index=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,index);buffer=buffer.slice(index+1);let value;try{value=JSON.parse(line);}catch{continue;}onLine(value);if(done)return;}});
|
|
25
|
+
child.once('close',failed);
|
|
26
|
+
for(const line of lines)child.stdin.write(JSON.stringify(line)+'\n');
|
|
27
|
+
}
|
|
28
|
+
const authRequired=error=>/authentication required/i.test(String(error?.message??''));
|
|
29
|
+
function codexWindow(value){
|
|
30
|
+
if(!object(value)||!Number.isFinite(value.usedPercent))return undefined;
|
|
31
|
+
const minutes=int(value.windowDurationMins),resetsAt=int(value.resetsAt);
|
|
32
|
+
return {usedPercent:value.usedPercent,remainingPercent:Math.max(0,100-value.usedPercent),...minutes&&minutes>0?{windowMinutes:minutes}:{},...resetsAt&&resetsAt>0?{resetsAt}:{}};
|
|
33
|
+
}
|
|
34
|
+
function codexQuota(result){
|
|
35
|
+
if(!object(result)||!object(result.rateLimits))return undefined;
|
|
36
|
+
const snapshots=object(result.rateLimitsByLimitId)&&Object.keys(result.rateLimitsByLimitId).length?Object.values(result.rateLimitsByLimitId):[result.rateLimits];
|
|
37
|
+
const limits=[];
|
|
38
|
+
for(const snapshot of snapshots){if(!object(snapshot))continue;const windows=[codexWindow(snapshot.primary),codexWindow(snapshot.secondary)].filter(Boolean);const id=text(snapshot.limitId,64)??'codex';if(windows.length)limits.push({id,name:text(snapshot.limitName,120)??(id==='codex'?'Codex':id),windows});}
|
|
39
|
+
const base=result.rateLimits,c=base.credits,individual=base.individualLimit,resets=result.rateLimitResetCredits;
|
|
40
|
+
const credits=object(c)&&c.hasCredits===true?{unlimited:c.unlimited===true,...typeof c.balance==='string'&&/^-?\d+(?:\.\d+)?$/.test(c.balance)?{balance:c.balance}:{}}:undefined;
|
|
41
|
+
const individualLimit=object(individual)&&Number.isFinite(individual.remainingPercent)?{remainingPercent:individual.remainingPercent,...typeof individual.used==='string'?{used:individual.used}:{},...typeof individual.limit==='string'?{limit:individual.limit}:{},...int(individual.resetsAt)?{resetsAt:individual.resetsAt}:{}}:undefined;
|
|
42
|
+
const resetCredits=object(resets)&&int(resets.availableCount)!==undefined&&resets.availableCount>=0?{availableCount:resets.availableCount,credits:(Array.isArray(resets.credits)?resets.credits:[]).filter(credit=>object(credit)&&credit.status==='available'&&text(credit.id,256)).map(credit=>({id:credit.id,...text(credit.title,120)?{name:text(credit.title,120)}:{},...text(credit.description)?{description:text(credit.description)}:{},...int(credit.expiresAt)&&credit.expiresAt>0?{expiresAt:credit.expiresAt}:{}}))}:undefined;
|
|
43
|
+
return {limits,...credits?{credits}:{},...individualLimit?{individualLimit}:{},...typeof base.spendControlReached==='boolean'?{spendControlReached:base.spendControlReached}:{},...resetCredits?{resetCredits}:{}};
|
|
44
|
+
}
|
|
45
|
+
function claudeWindow(value,name,windowMinutes){
|
|
46
|
+
if(!object(value)||!Number.isFinite(value.utilization))return undefined;
|
|
47
|
+
const parsed=typeof value.resets_at==='string'?Date.parse(value.resets_at):NaN,resetsAt=Number.isFinite(parsed)&&parsed>0?Math.floor(parsed/1000):undefined;
|
|
48
|
+
return {id:name,name,windows:[{usedPercent:value.utilization,remainingPercent:Math.max(0,100-value.utilization),windowMinutes,...resetsAt?{resetsAt}:{}}]};
|
|
49
|
+
}
|
|
50
|
+
function claudeQuota(response){
|
|
51
|
+
if(!object(response)||response.rate_limits_available!==true||!object(response.rate_limits))return undefined;
|
|
52
|
+
const r=response.rate_limits,limits=[claudeWindow(r.five_hour,'Claude',300),claudeWindow(r.seven_day,'Claude',10080),claudeWindow(r.seven_day_opus,'Opus',10080),claudeWindow(r.seven_day_sonnet,'Sonnet',10080),...(Array.isArray(r.model_scoped)?r.model_scoped.map(row=>object(row)&&text(row.display_name,120)?claudeWindow(row,text(row.display_name,120),10080):undefined):[])].filter(Boolean);
|
|
53
|
+
const e=r.extra_usage,extraUsage=object(e)&&typeof e.is_enabled==='boolean'?{enabled:e.is_enabled,...Number.isFinite(e.monthly_limit)?{monthlyLimitCents:e.monthly_limit}:{},...Number.isFinite(e.used_credits)?{usedCents:e.used_credits}:{},...Number.isFinite(e.utilization)?{utilization:e.utilization}:{},...text(e.currency,8)?{currency:text(e.currency,8)}:{}}:undefined;
|
|
54
|
+
return {limits,...extraUsage?{extraUsage}:{}};
|
|
55
|
+
}
|
|
56
|
+
function main(input){
|
|
57
|
+
if(provider==='claude'){
|
|
58
|
+
run('claude',['-p','--input-format','stream-json','--output-format','stream-json','--verbose','--no-session-persistence'],[{type:'control_request',request_id:'aw-init',request:{subtype:'initialize'}},{type:'control_request',request_id:'aw-usage',request:{subtype:'get_usage',skip_behaviors:true}}],value=>{
|
|
59
|
+
if(value?.type!=='control_response'||value.response?.request_id!=='aw-usage')return;
|
|
60
|
+
if(value.response.subtype!=='success'){reply({ok:false,reason:'read-failed'});return;}
|
|
61
|
+
const response=value.response.response;
|
|
62
|
+
if(object(response)&&response.rate_limits_available===false&&response.subscription_type===null){reply({ok:false,reason:'not-signed-in'});return;}
|
|
63
|
+
const quota=claudeQuota(response);reply(quota?{ok:true,value:quota}:{ok:false,reason:'read-failed'});
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
let request;
|
|
68
|
+
if(action==='consume'){
|
|
69
|
+
let body;try{body=JSON.parse(input);}catch{body=undefined;}
|
|
70
|
+
if(!object(body)||!text(body.creditId,256)||!/^[a-f0-9-]{36}$/.test(String(body.idempotencyKey))||Object.keys(body).length!==2)process.exit(2);
|
|
71
|
+
request={jsonrpc:'2.0',id:2,method:'account/rateLimitResetCredit/consume',params:{creditId:body.creditId,idempotencyKey:body.idempotencyKey}};
|
|
72
|
+
}else request={jsonrpc:'2.0',id:2,method:'account/rateLimits/read',params:null};
|
|
73
|
+
run('codex',['app-server'],[{jsonrpc:'2.0',id:1,method:'initialize',params:{clientInfo:{name:'ai-workbench-connect',version:'1'}}},{jsonrpc:'2.0',method:'initialized'},request],value=>{
|
|
74
|
+
if(value?.id!==2)return;
|
|
75
|
+
if(value.error){reply({ok:false,reason:authRequired(value.error)?'not-signed-in':action==='consume'?'uncertain':'read-failed'});return;}
|
|
76
|
+
if(action==='consume'){const outcome=value.result?.outcome;reply(['reset','nothingToReset','noCredit','alreadyRedeemed'].includes(outcome)?{ok:true,value:{outcome}}:{ok:false,reason:'uncertain'});return;}
|
|
77
|
+
const quota=codexQuota(value.result);reply(quota?{ok:true,value:quota}:{ok:false,reason:'read-failed'});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if(action==='consume'){let input='';process.stdin.setEncoding('utf8');process.stdin.on('data',chunk=>{input+=chunk;if(input.length>budget)process.exit(2);});process.stdin.on('end',()=>main(input));}
|
|
81
|
+
else main('');
|
package/lib/api.d.ts
CHANGED
|
@@ -179,6 +179,7 @@ export interface ConnectApi {
|
|
|
179
179
|
refreshWorkspaceLocations?(): Promise<Result<WorkspaceLocationState>>;
|
|
180
180
|
browseWorkspaceHostDirectories?(request: WorkspaceBrowseRequest): Promise<Result<WorkspaceBrowsePage>>;
|
|
181
181
|
selectWorkspaceLocation?(request: WorkspaceSelectRequest): Promise<Result<WorkspaceLocationState>>;
|
|
182
|
+
quota?: import('./quota.ts').QuotaService;
|
|
182
183
|
getModelCatalogTarget(provider: Provider): Result<ModelCatalogTarget>;
|
|
183
184
|
appendRemoteConversationDetail(detail: RemoteConversationDetail): void;
|
|
184
185
|
readConversationLog(): Promise<Result<string>>;
|
package/lib/auth-diagnostics.js
CHANGED
|
@@ -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
|
|
43
|
-
value
|
|
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
|
@@ -194,6 +194,64 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
194
194
|
}
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
|
+
const quotaRoute = /^\/ai-workbench-connect\/quota\/(codex|claude)(?:\/reset\/(prepare|consume))?$/.exec(path);
|
|
198
|
+
if (quotaRoute) {
|
|
199
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
200
|
+
const [, provider, step] = quotaRoute;
|
|
201
|
+
const respond = (status, value) => { res.statusCode = status; res.end(JSON.stringify(value)); };
|
|
202
|
+
if (!service?.quota) {
|
|
203
|
+
respond(503, fail('DEPENDENCY_REQUIRED'));
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const quota = service.quota, serve = async (work) => { try {
|
|
207
|
+
respond(200, await work());
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
respond(503, fail('DEPENDENCY_REQUIRED'));
|
|
211
|
+
} };
|
|
212
|
+
if (!step) {
|
|
213
|
+
if (req.method !== 'GET') {
|
|
214
|
+
respond(404, { error: 'not-found' });
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
await serve(() => quota.read(provider));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (req.method !== 'POST' || provider !== 'codex') {
|
|
221
|
+
respond(404, { error: 'not-found' });
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// A malformed reset request reuses the existing "confirmation no longer valid" result; no new error code.
|
|
225
|
+
let body;
|
|
226
|
+
try {
|
|
227
|
+
const chunks = [];
|
|
228
|
+
let bytes = 0;
|
|
229
|
+
if (!Number.isSafeInteger(metadataMaxBytes) || metadataMaxBytes < 1)
|
|
230
|
+
throw Error();
|
|
231
|
+
for await (const chunk of req) {
|
|
232
|
+
const part = Buffer.from(chunk);
|
|
233
|
+
bytes += part.length;
|
|
234
|
+
if (bytes > metadataMaxBytes)
|
|
235
|
+
throw Error();
|
|
236
|
+
chunks.push(part);
|
|
237
|
+
}
|
|
238
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
239
|
+
if (!record(parsed))
|
|
240
|
+
throw Error();
|
|
241
|
+
body = parsed;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
respond(400, { ok: false, reason: 'expired' });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const keys = Object.keys(body).sort().join(',');
|
|
248
|
+
if (step === 'prepare' ? keys !== 'ref' : keys !== 'acknowledged,challengeId') {
|
|
249
|
+
respond(400, { ok: false, reason: 'expired' });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
await serve(() => step === 'prepare' ? quota.prepareReset(body.ref) : quota.consumeReset(body.challengeId, body.acknowledged));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
197
255
|
if (req.method === 'GET' && path === '/ai-workbench-connect/conversation-log') {
|
|
198
256
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
199
257
|
if (!service || typeof service.readConversationLog !== 'function') {
|
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/defaults.d.ts
CHANGED
|
@@ -18,3 +18,11 @@ export declare const NETWORK_DEFAULTS: Readonly<{
|
|
|
18
18
|
export declare const WORKSPACE_LOCATION_DEFAULTS: {
|
|
19
19
|
readonly pageSize: 100;
|
|
20
20
|
};
|
|
21
|
+
export declare const QUOTA_DEFAULTS: Readonly<{
|
|
22
|
+
resetConfirmDelayMs: 5000;
|
|
23
|
+
resetChallengeTtlMs: 60000;
|
|
24
|
+
refreshSchedule: readonly {
|
|
25
|
+
usedPercentAtLeast: number;
|
|
26
|
+
intervalMs: number;
|
|
27
|
+
}[];
|
|
28
|
+
}>;
|
package/lib/defaults.js
CHANGED
|
@@ -2,3 +2,6 @@
|
|
|
2
2
|
export const L_DEFAULTS = Object.freeze({ enrollmentMetadataMaxBytes: 1048576, commandOutputMaxBytes: 1048576, remoteKillGraceMs: 1000, loginOutputMaxBytes: 1048576 });
|
|
3
3
|
export const NETWORK_DEFAULTS = Object.freeze({ logUpload: false, statusRefreshIntervalSeconds: 2, dialTimeoutSeconds: 20, headerTimeoutSeconds: 10, enrollmentObservationSeconds: 30, httpMaxHeaderBytes: 1048576, startupObservationSeconds: 35, shutdownObservationSeconds: 10, controlResponseMaxBytes: 65536 });
|
|
4
4
|
export const WORKSPACE_LOCATION_DEFAULTS = { pageSize: 100 };
|
|
5
|
+
// Quota card timings copied from dsh-codex-subscription 3.2.16 (lib/index.js:16156-16157 reset confirmation;
|
|
6
|
+
// lib/client.js:11789-11795 refresh cadence by highest used percent). Named settings pending owner confirmation.
|
|
7
|
+
export const QUOTA_DEFAULTS = Object.freeze({ resetConfirmDelayMs: 5000, resetChallengeTtlMs: 60000, refreshSchedule: Object.freeze([{ usedPercentAtLeast: 0, intervalMs: 60000 }, { usedPercentAtLeast: 75, intervalMs: 30000 }, { usedPercentAtLeast: 90, intervalMs: 15000 }, { usedPercentAtLeast: 99, intervalMs: 5000 }]) });
|
package/lib/index.d.ts
CHANGED
|
@@ -27,6 +27,14 @@ export interface Config {
|
|
|
27
27
|
remoteKillGraceMs?: number;
|
|
28
28
|
loginOutputMaxBytes?: number;
|
|
29
29
|
};
|
|
30
|
+
quota?: {
|
|
31
|
+
resetConfirmDelayMs?: number;
|
|
32
|
+
resetChallengeTtlMs?: number;
|
|
33
|
+
refreshSchedule?: {
|
|
34
|
+
usedPercentAtLeast: number;
|
|
35
|
+
intervalMs: number;
|
|
36
|
+
}[];
|
|
37
|
+
};
|
|
30
38
|
}
|
|
31
39
|
export declare const Config: z<Config>;
|
|
32
40
|
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void, autoStart?: boolean): void;
|
package/lib/index.js
CHANGED
|
@@ -5,7 +5,8 @@ import { createConnect } from "./connect.js";
|
|
|
5
5
|
import { configuredPorts } from "./integration.js";
|
|
6
6
|
import { attachProfileRuntime } from "./profile-runtime.js";
|
|
7
7
|
import { profileSettings } from "./profile-settings.js";
|
|
8
|
-
import { L_DEFAULTS, NETWORK_DEFAULTS } from "./defaults.js";
|
|
8
|
+
import { L_DEFAULTS, NETWORK_DEFAULTS, QUOTA_DEFAULTS } from "./defaults.js";
|
|
9
|
+
import { createQuota, clearOnSignOut } from "./quota.js";
|
|
9
10
|
import { registerComponents } from "./components.js";
|
|
10
11
|
export { writeNetworkConfig } from "./network.js";
|
|
11
12
|
export { createConnect } from "./connect.js";
|
|
@@ -25,6 +26,11 @@ export const Config = z.object({
|
|
|
25
26
|
trustDir: z.string().description('主机信任缓存目录:由管理员安装时配置'),
|
|
26
27
|
commandOutputMaxBytes: positive().default(L_DEFAULTS.commandOutputMaxBytes).description('远程命令输出内存上限(字节),默认1048576,管理员可修改'),
|
|
27
28
|
network: z.object({ executable: z.string(), runtimeDir: z.string(), stateDir: z.string(), configFile: z.string(), helperLogFile: z.string(), nodeName: z.string(), startupObservationSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.startupObservationSeconds), shutdownObservationSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.shutdownObservationSeconds), controlResponseMaxBytes: positive().default(NETWORK_DEFAULTS.controlResponseMaxBytes), logUpload: z.boolean().default(NETWORK_DEFAULTS.logUpload), statusRefreshIntervalSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.statusRefreshIntervalSeconds), dialTimeoutSeconds: z.number().min(1e-9).default(NETWORK_DEFAULTS.dialTimeoutSeconds), headerTimeoutSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.headerTimeoutSeconds), enrollmentObservationSeconds: z.number().min(1e-9).default(NETWORK_DEFAULTS.enrollmentObservationSeconds), httpMaxHeaderBytes: positive().default(NETWORK_DEFAULTS.httpMaxHeaderBytes), controlMaxBytes: positive() }).description('远程网络连接设置:使用默认技术参数,管理员可修改;路径根据当前用户和应用配置目录生成,员工无需填写'),
|
|
29
|
+
quota: z.object({
|
|
30
|
+
resetConfirmDelayMs: z.number().step(1).min(0).max(2147483647).default(QUOTA_DEFAULTS.resetConfirmDelayMs).description('quota.resetConfirmDelayMs:额度卡“使用重置”出现确认后,要等多少毫秒才能点“确认使用”;默认5000,照抄DSH Codex订阅插件,管理员可改'),
|
|
31
|
+
resetChallengeTtlMs: positive().max(2147483647).default(QUOTA_DEFAULTS.resetChallengeTtlMs).description('quota.resetChallengeTtlMs:一次“使用重置”确认的有效毫秒数,过期须重新点“使用重置”;默认60000,照抄DSH Codex订阅插件,管理员可改'),
|
|
32
|
+
refreshSchedule: z.array(z.object({ usedPercentAtLeast: z.number().min(0).max(100), intervalMs: positive().max(2147483647) })).min(1).default(QUOTA_DEFAULTS.refreshSchedule.map(step => ({ ...step }))).description('quota.refreshSchedule:设置页可见时额度卡自动重读的间隔,按最高已用百分比取最高一档;默认<75%每60000、≥75%每30000、≥90%每15000、≥99%每5000毫秒,照抄DSH Codex订阅插件,管理员可改'),
|
|
33
|
+
}),
|
|
28
34
|
helper: z.object({
|
|
29
35
|
remoteKillGraceMs: z.number().step(1).min(0).max(2147483647).default(L_DEFAULTS.remoteKillGraceMs).description('远端本轮登录进程组结束宽限毫秒;默认1000,0立即KILL,管理员可改'),
|
|
30
36
|
loginOutputMaxBytes: positive().default(L_DEFAULTS.loginOutputMaxBytes).description('登录进程输出字节上限;默认1048576,管理员可改'),
|
|
@@ -42,7 +48,13 @@ export function apply(ctx, config = {}) {
|
|
|
42
48
|
config = profileSettings(config, ctx.get('profileContext')?.dir);
|
|
43
49
|
const network = ctx.get('aiWorkbenchNetwork');
|
|
44
50
|
const ports = configuredPorts(config, network, ctx.get('profileContext')?.dir);
|
|
45
|
-
register(ctx, ports, config.inventory, api =>
|
|
51
|
+
register(ctx, ports, config.inventory, api => {
|
|
52
|
+
attachProfileRuntime(ctx, api, ports, config, network, true);
|
|
53
|
+
const quota = createQuota(api, ports.ssh, { resetConfirmDelayMs: config.quota?.resetConfirmDelayMs ?? QUOTA_DEFAULTS.resetConfirmDelayMs, resetChallengeTtlMs: config.quota?.resetChallengeTtlMs ?? QUOTA_DEFAULTS.resetChallengeTtlMs, refreshSchedule: config.quota?.refreshSchedule ?? QUOTA_DEFAULTS.refreshSchedule.map(step => ({ ...step })) });
|
|
54
|
+
// A sign-in change may be another account: forget its reset refs and confirmations (as the DSH plugin does on account change).
|
|
55
|
+
ctx.effect(() => clearOnSignOut(api, quota));
|
|
56
|
+
api.quota = quota;
|
|
57
|
+
}, false);
|
|
46
58
|
registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
47
59
|
}
|
|
48
60
|
export { createProfileEnrollment } from "./profile-enrollment.js";
|
package/lib/ports.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ export interface Ports {
|
|
|
35
35
|
};
|
|
36
36
|
ssh?: {
|
|
37
37
|
logout?(target: SshTarget, provider: Provider, signal: AbortSignal): Promise<Result<void>>;
|
|
38
|
+
quota?(target: SshTarget, provider: Provider, action: 'read' | 'consume', signal: AbortSignal, input?: string): Promise<Result<CommandResult>>;
|
|
38
39
|
verify(target: SshTarget, signal: AbortSignal): Promise<Result<void>>;
|
|
39
40
|
status(target: SshTarget, provider: Provider, signal: AbortSignal): Promise<Result<CommandResult>>;
|
|
40
41
|
};
|
package/lib/quota.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ConnectApi, Provider } from './api.ts';
|
|
2
|
+
import type { Ports } from './ports.ts';
|
|
3
|
+
export interface QuotaSettings {
|
|
4
|
+
resetConfirmDelayMs: number;
|
|
5
|
+
resetChallengeTtlMs: number;
|
|
6
|
+
refreshSchedule: {
|
|
7
|
+
usedPercentAtLeast: number;
|
|
8
|
+
intervalMs: number;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
export interface QuotaWindow {
|
|
12
|
+
usedPercent: number;
|
|
13
|
+
remainingPercent: number;
|
|
14
|
+
windowMinutes?: number;
|
|
15
|
+
resetsAt?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface QuotaView {
|
|
18
|
+
fetchedAt: number;
|
|
19
|
+
nextRefreshMs: number;
|
|
20
|
+
limits: {
|
|
21
|
+
id: string;
|
|
22
|
+
name?: string;
|
|
23
|
+
windows: QuotaWindow[];
|
|
24
|
+
}[];
|
|
25
|
+
credits?: {
|
|
26
|
+
unlimited: boolean;
|
|
27
|
+
balance?: string;
|
|
28
|
+
};
|
|
29
|
+
individualLimit?: {
|
|
30
|
+
remainingPercent: number;
|
|
31
|
+
used?: string;
|
|
32
|
+
limit?: string;
|
|
33
|
+
resetsAt?: number;
|
|
34
|
+
};
|
|
35
|
+
spendControlReached?: boolean;
|
|
36
|
+
resetCredits?: {
|
|
37
|
+
availableCount: number;
|
|
38
|
+
credits: {
|
|
39
|
+
ref: string;
|
|
40
|
+
name?: string;
|
|
41
|
+
expiresAt?: number;
|
|
42
|
+
}[];
|
|
43
|
+
};
|
|
44
|
+
extraUsage?: {
|
|
45
|
+
enabled: boolean;
|
|
46
|
+
monthlyLimitCents?: number;
|
|
47
|
+
usedCents?: number;
|
|
48
|
+
utilization?: number;
|
|
49
|
+
currency?: string;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export type QuotaReason = 'not-signed-in' | 'read-failed' | 'connection' | 'expired' | 'in-progress' | 'too-early' | 'acknowledge-required' | 'uncertain' | 'no-credit';
|
|
53
|
+
export type QuotaResult<T> = {
|
|
54
|
+
ok: true;
|
|
55
|
+
value: T;
|
|
56
|
+
} | {
|
|
57
|
+
ok: false;
|
|
58
|
+
reason: QuotaReason;
|
|
59
|
+
message?: string;
|
|
60
|
+
nextRefreshMs?: number;
|
|
61
|
+
};
|
|
62
|
+
export interface QuotaChallenge {
|
|
63
|
+
challengeId: string;
|
|
64
|
+
readyAt: number;
|
|
65
|
+
expiresAt: number;
|
|
66
|
+
availableCount: number;
|
|
67
|
+
title?: string;
|
|
68
|
+
description?: string;
|
|
69
|
+
creditExpiresAt?: number;
|
|
70
|
+
}
|
|
71
|
+
export interface QuotaService {
|
|
72
|
+
read(provider: Provider): Promise<QuotaResult<QuotaView>>;
|
|
73
|
+
prepareReset(ref: unknown): Promise<QuotaResult<QuotaChallenge>>;
|
|
74
|
+
consumeReset(challengeId: unknown, acknowledged: unknown): Promise<QuotaResult<{
|
|
75
|
+
outcome: 'reset' | 'nothingToReset' | 'noCredit' | 'alreadyRedeemed';
|
|
76
|
+
}>>;
|
|
77
|
+
clear(): void;
|
|
78
|
+
}
|
|
79
|
+
export declare function refreshInterval(schedule: QuotaSettings['refreshSchedule'], limits: QuotaView['limits']): number;
|
|
80
|
+
export declare function clearOnSignOut(api: Pick<ConnectApi, 'onLoginPromptState'>, quota: Pick<QuotaService, 'clear'>): () => void;
|
|
81
|
+
export declare function createQuota(api: Pick<ConnectApi, 'getSshTarget'>, ssh: Ports['ssh'], settings: QuotaSettings, now?: () => number): QuotaService;
|
package/lib/quota.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Plan quota shown under each host sign-in row, modelled on dsh-codex-subscription 3.2.16 (settings → 订阅额度).
|
|
2
|
+
// Data comes from the employee's own host sign-in through helper/quota.cjs; credit ids and idempotency keys stay in this
|
|
3
|
+
// process, the settings page only sees opaque refs and challenge ids (as in that plugin's src/reset-credits.js).
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
export function refreshInterval(schedule, limits) {
|
|
6
|
+
const used = limits.flatMap(limit => limit.windows.map(window => window.usedPercent)), highest = used.length ? Math.max(...used) : -Infinity;
|
|
7
|
+
return [...schedule].sort((a, b) => b.usedPercentAtLeast - a.usedPercentAtLeast).find(step => highest >= step.usedPercentAtLeast)?.intervalMs ?? Math.max(...schedule.map(step => step.intervalMs));
|
|
8
|
+
}
|
|
9
|
+
// A connection check briefly reports the login as unknown; only an explicit signed-in → signed-out change may be another account.
|
|
10
|
+
export function clearOnSignOut(api, quota) {
|
|
11
|
+
let codex;
|
|
12
|
+
return api.onLoginPromptState(state => { const next = state.logins.codex; if (codex === true && next === false)
|
|
13
|
+
quota.clear(); if (next !== undefined)
|
|
14
|
+
codex = next; });
|
|
15
|
+
}
|
|
16
|
+
export function createQuota(api, ssh, settings, now = Date.now) {
|
|
17
|
+
let availableCount = 0, epoch = 0;
|
|
18
|
+
const lastLimits = new Map();
|
|
19
|
+
const flights = new Map(), refs = new Map(), challenges = new Map();
|
|
20
|
+
const refOf = (credit) => { for (const [ref, known] of refs)
|
|
21
|
+
if (known.id === credit.id) {
|
|
22
|
+
refs.set(ref, credit);
|
|
23
|
+
return ref;
|
|
24
|
+
} const ref = randomUUID(); refs.set(ref, credit); return ref; };
|
|
25
|
+
const call = async (provider, action, input) => {
|
|
26
|
+
const target = await api.getSshTarget();
|
|
27
|
+
if (!target.ok)
|
|
28
|
+
return { ok: false, reason: 'connection', message: target.error.message };
|
|
29
|
+
if (!ssh?.quota)
|
|
30
|
+
return { ok: false, reason: 'read-failed' };
|
|
31
|
+
const raw = await ssh.quota(target.value, provider, action, new AbortController().signal, input);
|
|
32
|
+
if (!raw.ok)
|
|
33
|
+
return { ok: false, reason: action === 'consume' ? 'uncertain' : 'read-failed' };
|
|
34
|
+
let reply;
|
|
35
|
+
try {
|
|
36
|
+
reply = raw.value.exitCode === 0 ? JSON.parse(raw.value.stdout.trim()) : undefined;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
reply = undefined;
|
|
40
|
+
}
|
|
41
|
+
if (reply?.protocolVersion !== 1 || reply.provider !== provider)
|
|
42
|
+
return { ok: false, reason: action === 'consume' ? 'uncertain' : 'read-failed' };
|
|
43
|
+
return reply.ok === true ? { ok: true, value: reply.value } : { ok: false, reason: reply.reason };
|
|
44
|
+
};
|
|
45
|
+
const read = (provider) => {
|
|
46
|
+
const running = flights.get(provider);
|
|
47
|
+
if (running)
|
|
48
|
+
return running;
|
|
49
|
+
const promise = (async () => {
|
|
50
|
+
const result = await call(provider, 'read');
|
|
51
|
+
if (!result.ok)
|
|
52
|
+
return { ...result, nextRefreshMs: refreshInterval(settings.refreshSchedule, lastLimits.get(provider) ?? []) };
|
|
53
|
+
const value = result.value, limits = Array.isArray(value?.limits) ? value.limits : [];
|
|
54
|
+
lastLimits.set(provider, limits);
|
|
55
|
+
const view = { fetchedAt: now(), nextRefreshMs: refreshInterval(settings.refreshSchedule, limits), limits };
|
|
56
|
+
for (const key of ['credits', 'individualLimit', 'spendControlReached', 'extraUsage'])
|
|
57
|
+
if (value[key] !== undefined)
|
|
58
|
+
view[key] = value[key];
|
|
59
|
+
if (value.resetCredits)
|
|
60
|
+
availableCount = value.resetCredits.availableCount;
|
|
61
|
+
if (value.resetCredits)
|
|
62
|
+
view.resetCredits = { availableCount: value.resetCredits.availableCount, credits: value.resetCredits.credits.map(credit => ({ ref: refOf(credit), ...credit.name ? { name: credit.name } : {}, ...credit.expiresAt ? { expiresAt: credit.expiresAt } : {} })) };
|
|
63
|
+
return { ok: true, value: view };
|
|
64
|
+
})();
|
|
65
|
+
flights.set(provider, promise);
|
|
66
|
+
void promise.finally(() => { if (flights.get(provider) === promise)
|
|
67
|
+
flights.delete(provider); });
|
|
68
|
+
return promise;
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
read,
|
|
72
|
+
async prepareReset(ref) {
|
|
73
|
+
const credit = typeof ref === 'string' ? refs.get(ref) : undefined;
|
|
74
|
+
if (!credit)
|
|
75
|
+
return { ok: false, reason: 'expired' };
|
|
76
|
+
for (const [challengeId, challenge] of challenges) {
|
|
77
|
+
if (challenge.ref !== ref)
|
|
78
|
+
continue;
|
|
79
|
+
if (challenge.pending)
|
|
80
|
+
return { ok: false, reason: 'in-progress' };
|
|
81
|
+
if (now() > challenge.expiresAt) {
|
|
82
|
+
challenges.delete(challengeId);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
return { ok: true, value: { challengeId, readyAt: challenge.readyAt, expiresAt: challenge.expiresAt, availableCount: challenge.availableCount, ...challenge.title ? { title: challenge.title } : {}, ...challenge.description ? { description: challenge.description } : {}, ...challenge.creditExpiresAt ? { creditExpiresAt: challenge.creditExpiresAt } : {} } };
|
|
86
|
+
}
|
|
87
|
+
const preparedAt = now(), creditExpiresAt = credit.expiresAt ? credit.expiresAt * 1000 : undefined;
|
|
88
|
+
if (creditExpiresAt !== undefined && creditExpiresAt <= preparedAt)
|
|
89
|
+
return { ok: false, reason: 'no-credit' };
|
|
90
|
+
const readyAt = preparedAt + settings.resetConfirmDelayMs, expiresAt = Math.min(preparedAt + settings.resetChallengeTtlMs, creditExpiresAt ?? Number.MAX_SAFE_INTEGER);
|
|
91
|
+
if (expiresAt <= readyAt)
|
|
92
|
+
return { ok: false, reason: 'expired' };
|
|
93
|
+
const challengeId = randomUUID();
|
|
94
|
+
challenges.set(challengeId, { creditId: credit.id, idempotencyKey: randomUUID(), readyAt, expiresAt, availableCount, ref: ref, pending: false, ...credit.name ? { title: credit.name } : {}, ...credit.description ? { description: credit.description } : {}, ...creditExpiresAt ? { creditExpiresAt } : {} });
|
|
95
|
+
return { ok: true, value: { challengeId, readyAt, expiresAt, availableCount, ...credit.name ? { title: credit.name } : {}, ...credit.description ? { description: credit.description } : {}, ...creditExpiresAt ? { creditExpiresAt } : {} } };
|
|
96
|
+
},
|
|
97
|
+
async consumeReset(challengeId, acknowledged) {
|
|
98
|
+
const challenge = typeof challengeId === 'string' ? challenges.get(challengeId) : undefined;
|
|
99
|
+
if (!challenge)
|
|
100
|
+
return { ok: false, reason: 'expired' };
|
|
101
|
+
if (challenge.pending)
|
|
102
|
+
return { ok: false, reason: 'in-progress' };
|
|
103
|
+
if (now() < challenge.readyAt)
|
|
104
|
+
return { ok: false, reason: 'too-early' };
|
|
105
|
+
if (now() > challenge.expiresAt) {
|
|
106
|
+
challenges.delete(challengeId);
|
|
107
|
+
return { ok: false, reason: 'expired' };
|
|
108
|
+
}
|
|
109
|
+
if (acknowledged !== true)
|
|
110
|
+
return { ok: false, reason: 'acknowledge-required' };
|
|
111
|
+
challenge.pending = true;
|
|
112
|
+
const at = epoch;
|
|
113
|
+
let result;
|
|
114
|
+
try {
|
|
115
|
+
result = await call('codex', 'consume', JSON.stringify({ creditId: challenge.creditId, idempotencyKey: challenge.idempotencyKey }));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
result = { ok: false, reason: 'uncertain' };
|
|
119
|
+
}
|
|
120
|
+
challenge.pending = false;
|
|
121
|
+
// Uncertain results keep the same confirmation so a retry reuses the same idempotency key, never a second reset.
|
|
122
|
+
if (!(!result.ok && result.reason === 'uncertain' && now() <= challenge.expiresAt)) {
|
|
123
|
+
challenges.delete(challengeId);
|
|
124
|
+
if (result.ok && at === epoch)
|
|
125
|
+
refs.clear();
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
},
|
|
129
|
+
clear() { epoch++; refs.clear(); challenges.clear(); },
|
|
130
|
+
};
|
|
131
|
+
}
|
package/lib/ssh.js
CHANGED
|
@@ -91,12 +91,24 @@ export function createSsh(runner, maxOutputBytes) {
|
|
|
91
91
|
return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error, 'LOGOUT_FAILED');
|
|
92
92
|
}
|
|
93
93
|
},
|
|
94
|
+
// Quota read/consume runs the official CLI as the employee on the host; only the helper's projected JSON line comes back.
|
|
95
|
+
quota: async (t, p, action, signal, input) => {
|
|
96
|
+
try {
|
|
97
|
+
if (!['codex', 'claude'].includes(p) || !['read', 'consume'].includes(action) || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1)
|
|
98
|
+
return authFailure('ssh-status', 'STATUS_ARGUMENT_INVALID');
|
|
99
|
+
const source = await readFile(new URL('../helper/quota.cjs', import.meta.url), 'utf8');
|
|
100
|
+
return ok(await runRemote(runner, t, 'node -e ' + "'" + source.replaceAll("'", "'\\''") + "' -- " + p + ' ' + maxOutputBytes + ' ' + action, signal, input));
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error);
|
|
104
|
+
}
|
|
105
|
+
},
|
|
94
106
|
verify: async (t, signal) => { try {
|
|
95
107
|
const r = await runRemote(runner, t, 'id -un', signal);
|
|
96
108
|
return r.exitCode === 0 && r.stdout.trim() === t.username ? ok(undefined) : fail('SSH_FAILED');
|
|
97
109
|
}
|
|
98
|
-
catch {
|
|
99
|
-
return
|
|
110
|
+
catch (error) {
|
|
111
|
+
return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error, 'SSH_FAILED');
|
|
100
112
|
} },
|
|
101
113
|
status: async (t, p, signal) => {
|
|
102
114
|
try {
|