paseo-plugin-account-switcher 0.7.1 → 0.8.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/OVERVIEW.md +9 -3
- package/OVERVIEW.zh-CN.md +9 -3
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.md +5 -5
- package/client/accounts.tsx +18 -2
- package/client/failover-row.tsx +49 -0
- package/client/runtime.ts +2 -1
- package/client/screens.ts +30 -0
- package/index.client.tsx +13 -8
- package/index.server.ts +139 -7
- package/npm-shrinkwrap.json +2 -2
- package/package.json +8 -7
- package/server/controller.ts +53 -17
- package/server/failover.ts +67 -0
- package/server/launcher-artifact.ts +1 -1
- package/server/paseo-usage.ts +126 -0
- package/server/selection.ts +6 -3
- package/server/session-env.ts +21 -0
- package/server/store.ts +9 -1
- package/server/switching.ts +45 -21
- package/server/timeline.ts +10 -0
- package/shared/contracts.ts +5 -0
- package/shared/failover.ts +45 -0
- /package/licenses/{paseo-0.8.0.txt → paseo-0.11.4.txt} +0 -0
- /package/licenses/{zod-4.6.5.txt → zod-4.6.7.txt} +0 -0
package/index.server.ts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
2
|
import * as rpc from "./shared/contracts";
|
|
3
3
|
import { AccountController } from "./server/controller";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { AutoFailoverGuard, extraUsageLeft, failoverDecision, mayBeUsedUp } from "./server/failover";
|
|
5
|
+
import type { PaseoApi } from "./server/paseo-api";
|
|
6
|
+
import { registerPaseoUsage } from "./server/paseo-usage";
|
|
7
|
+
import { profileEnv } from "./server/session-env";
|
|
8
|
+
import { accountFrom, boundAccount, type Registry } from "./server/store";
|
|
9
|
+
import { SwitchRefusal } from "./server/switching";
|
|
10
|
+
import { appendAccountNote, appendFailoverRow } from "./server/timeline";
|
|
11
|
+
import { FAILOVER_KIND, type FailoverRow } from "./shared/failover";
|
|
6
12
|
import type { AccountNote } from "./shared/timeline";
|
|
7
13
|
|
|
8
14
|
// Paseo hands `agent.create`'s environment to the same agent's first `agent.session_open`, which alone knows the agent ID.
|
|
9
15
|
const MODEL_ENV="PASEO_ACCOUNT_SWITCHER_MODEL";
|
|
16
|
+
// The prompt that resumes an agent's work on the account it was switched to.
|
|
17
|
+
const CONTINUE="Continue.";
|
|
18
|
+
const reason=(error:unknown)=>error instanceof Error?error.message:String(error);
|
|
19
|
+
// What a failover row shows for a failure that is not one of the switch service's own refusals: their messages are
|
|
20
|
+
// written for the user, any other error's may carry paths or internals.
|
|
21
|
+
const SWITCH_FAILED="The switch failed; the plugin log has details.";
|
|
10
22
|
|
|
11
23
|
export default function contribute(server:PluginServerContext){
|
|
12
24
|
const controller=new AccountController();
|
|
@@ -31,15 +43,15 @@ export default function contribute(server:PluginServerContext){
|
|
|
31
43
|
server.handle(rpc.prepareSwitch,async({agentId,accountId},{paseo})=>{await controller.ensureRuntime(paseo);return controller.switcher(paseo).prepare(agentId,accountId);});
|
|
32
44
|
server.handle(rpc.applySwitch,async({agentId,accountId},{paseo})=>{
|
|
33
45
|
await controller.ensureRuntime(paseo);
|
|
46
|
+
// The registry as the agent left it: the note names the account from its binding.
|
|
34
47
|
const before=await controller.store.read().catch(()=>null);
|
|
35
48
|
const binding=await controller.switcher(paseo).apply(agentId,accountId);
|
|
36
49
|
if(binding.currentAccountId){
|
|
37
50
|
const to=binding.currentAccountId;
|
|
38
51
|
void controller.usage.refresh(to).catch(()=>{});
|
|
39
52
|
const switched=await note(agentId,async()=>{
|
|
40
|
-
const state=await controller.store.read()
|
|
41
|
-
|
|
42
|
-
const fromId=prior?prior.currentAccountId:state.accounts.find(a=>a.source==="system"&&a.provider===binding.provider)?.id;
|
|
53
|
+
const state=await controller.store.read();
|
|
54
|
+
const fromId=before?await controller.accountOf(paseo,agentId,binding.provider,before):null;
|
|
43
55
|
const label=labelOf(state,to);
|
|
44
56
|
return label?{kind:"switched",from:labelOf(state,fromId),to:label,reason:null}:null;
|
|
45
57
|
});
|
|
@@ -47,9 +59,75 @@ export default function contribute(server:PluginServerContext){
|
|
|
47
59
|
}
|
|
48
60
|
return binding;
|
|
49
61
|
});
|
|
62
|
+
const guard=new AutoFailoverGuard();
|
|
63
|
+
// Offers already in the chat, by agent, account and reset: one exhaustion gets one offered or "none" row, not one per
|
|
64
|
+
// turn. A later exhaustion, with another reset or account, is offered again. In memory, like the guard.
|
|
65
|
+
const offered=new Set<string>();
|
|
66
|
+
// Agents with a failover switch under way, from its "switching" row until the row tells the outcome.
|
|
67
|
+
const switching=new Set<string>();
|
|
68
|
+
// Applies a failover row's switch the way `/account` does: the same service checks the account, that the agent is idle
|
|
69
|
+
// and has no pending permission, and the launch receipt. The row, not a separate note, tells the outcome, and a failure
|
|
70
|
+
// is shown there before it is rethrown: a refusal by its message, anything else as SWITCH_FAILED, its detail logged.
|
|
71
|
+
// "Continue." follows unless the row says the switch does not resume the agent.
|
|
72
|
+
const switchOver=async(paseo:PaseoApi,agentId:string,row:FailoverRow,toId:string,done:"switched"|"auto")=>{
|
|
73
|
+
// Claimed before any await. A second switch would only be refused by the service, and its row would cover the first one's.
|
|
74
|
+
if(switching.has(agentId))throw new SwitchRefusal("An account switch is already in progress.");
|
|
75
|
+
switching.add(agentId);
|
|
76
|
+
try{
|
|
77
|
+
await appendFailoverRow(paseo,agentId,{...row,state:"switching",error:null});
|
|
78
|
+
try{
|
|
79
|
+
await controller.ensureRuntime(paseo);
|
|
80
|
+
// One step: a refusal before the switch starts leaves no selection the user never made.
|
|
81
|
+
await controller.switcher(paseo).switchTo(agentId,toId);
|
|
82
|
+
}catch(error){
|
|
83
|
+
const refused=error instanceof SwitchRefusal;
|
|
84
|
+
if(!refused)console.error(`Could not switch agent ${agentId} to account ${toId}: ${reason(error)}`);
|
|
85
|
+
await appendFailoverRow(paseo,agentId,{...row,state:"failed",error:refused?error.message:SWITCH_FAILED});
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
void controller.usage.refresh(toId).catch(()=>{});
|
|
89
|
+
await appendFailoverRow(paseo,agentId,{...row,state:done,error:null});
|
|
90
|
+
}finally{switching.delete(agentId);}
|
|
91
|
+
if(row.resumes===false)return;
|
|
92
|
+
// The switch stands even if the prompt is not delivered; the chat is idle on the new account either way.
|
|
93
|
+
await paseo.agents.ref(agentId).send(CONTINUE).catch(error=>console.error(`Could not ask agent ${agentId} to continue on the new account: ${reason(error)}`));
|
|
94
|
+
};
|
|
95
|
+
server.handle(rpc.setAutoFailover,async({provider,enabled})=>{await controller.ready;await controller.store.change(r=>{r.autoFailover[provider]=enabled;});return{};});
|
|
96
|
+
server.handle(rpc.applyFailover,async({agentId,accountId,rowId,fromId},{paseo})=>{
|
|
97
|
+
// Only refusals, written for the user, reach the client as they are; any other error may carry paths or internals.
|
|
98
|
+
// switchOver logs its own failures; one before it is logged here.
|
|
99
|
+
const shown=(error:unknown,logged:boolean)=>{
|
|
100
|
+
if(error instanceof SwitchRefusal)return error;
|
|
101
|
+
if(!logged)console.error(`Could not check the switch offer for agent ${agentId}: ${reason(error)}`);
|
|
102
|
+
return new Error(SWITCH_FAILED);
|
|
103
|
+
};
|
|
104
|
+
let row:FailoverRow,toId:string;
|
|
105
|
+
try{
|
|
106
|
+
// Only this agent's own failover row may be rewritten with the outcome.
|
|
107
|
+
if(!rowId.startsWith(`${FAILOVER_KIND}-${agentId}-`))throw new SwitchRefusal("The switch offer belongs to another agent.");
|
|
108
|
+
// A switch under way keeps its row; checking first also keeps the stale-offer check below from rewriting it.
|
|
109
|
+
if(switching.has(agentId))throw new SwitchRefusal("An account switch is already in progress.");
|
|
110
|
+
await controller.ready;
|
|
111
|
+
const state=await controller.store.read(),target=state.accounts.find(a=>a.id===accountId);
|
|
112
|
+
if(!target)throw new SwitchRefusal("Account not found.");
|
|
113
|
+
// Named at the click: the account the agent leaves now, with a launch not confirmed yet confirmed by its receipt.
|
|
114
|
+
const currentId=await controller.accountOf(paseo,agentId,target.provider,state),from=labelOf(state,currentId);
|
|
115
|
+
if(!currentId||!from)throw new SwitchRefusal("This agent's account is not confirmed yet. Choose an account in the account switcher instead.");
|
|
116
|
+
toId=target.id;
|
|
117
|
+
row={rowId,state:"offered",from,fromId:currentId,to:target.label,toId,resetsAt:null,error:null};
|
|
118
|
+
// An offer made before the agent moved: switching now would leave an account the row never named.
|
|
119
|
+
const stale=currentId===target.id?`The agent already runs on ${target.label}.`:fromId&&fromId!==currentId?`This offer is out of date: the agent now runs on ${from}.`:null;
|
|
120
|
+
if(stale){await appendFailoverRow(paseo,agentId,{...row,state:"failed",error:stale});throw new SwitchRefusal(stale);}
|
|
121
|
+
}catch(error){throw shown(error,false);}
|
|
122
|
+
try{await switchOver(paseo,agentId,row,toId,"switched");}
|
|
123
|
+
catch(error){throw shown(error,true);}
|
|
124
|
+
return{};
|
|
125
|
+
});
|
|
50
126
|
server.handle(rpc.setIntegration,({enabled},{paseo})=>controller.integration(paseo,enabled));
|
|
51
127
|
server.handle(rpc.listUsage,async({visible},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.list({visible})};});
|
|
52
128
|
server.handle(rpc.refreshUsage,async({accountId},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.refresh(accountId)};});
|
|
129
|
+
// Paseo's Usage view lists the managed accounts too; a daemon before 0.11 has no usage sources, and the Accounts screen still shows the same limits.
|
|
130
|
+
registerPaseoUsage(server,controller);
|
|
53
131
|
const removeCreate=server.before("agent.create",({request})=>{
|
|
54
132
|
const model=request.config.model;
|
|
55
133
|
if((request.config.provider!=="claude"&&request.config.provider!=="codex")||!model)return request;
|
|
@@ -67,13 +145,67 @@ export default function contribute(server:PluginServerContext){
|
|
|
67
145
|
if(started)startNotes.set(request.agentId,{note:started,at:now});
|
|
68
146
|
}
|
|
69
147
|
}
|
|
148
|
+
// Paseo resolves an agent's login, and so its usage, from this session's environment. The launcher applies the profile to the CLI itself; this only lets Paseo see the same one.
|
|
149
|
+
// The registry is read after any binding above, so a new agent already has its profile. A failed read costs only that hint.
|
|
150
|
+
const profile=await controller.store.read().then(state=>profileEnv(state,request.agentId,request.provider),error=>{console.error(`Could not name the account profile for agent ${request.agentId}: ${error instanceof Error?error.message:String(error)}`);return{};});
|
|
70
151
|
// The model hint must not reach the provider CLI.
|
|
71
|
-
return {...request,env};
|
|
152
|
+
return {...request,env:{...env,...profile}};
|
|
72
153
|
});
|
|
73
154
|
const removeCreated=server.on("agent.created",async({agent},{paseo})=>{
|
|
74
155
|
const pending=startNotes.get(agent.id);startNotes.delete(agent.id);
|
|
75
156
|
if(pending)void appendAccountNote(paseo,agent.id,pending.note);
|
|
76
157
|
await controller.observeAgentRegistration(agent.id);
|
|
77
158
|
});
|
|
78
|
-
|
|
159
|
+
// Paseo does not say why a turn failed. The evidence is the plugin's own reading of the agent's account, taken again now:
|
|
160
|
+
// a used-up account gets a row, once per exhaustion, and any other failure is left alone.
|
|
161
|
+
// Claude reports a turn its limit stopped as completed (the SDK's error result has subtype "success"), Codex as failed.
|
|
162
|
+
// A completed Claude turn is read again only when the last reading already shows the account used up, and not while
|
|
163
|
+
// its paid extra usage has room: Claude then keeps answering past a full 5-hour window.
|
|
164
|
+
const removeTurnEnded=server.on("agent.turn_ended",async({agent,turnId,outcome},{paseo})=>{
|
|
165
|
+
const provider=agent.provider;
|
|
166
|
+
if(provider!=="claude"&&provider!=="codex")return;
|
|
167
|
+
const completed=provider==="claude"&&outcome.kind==="completed";
|
|
168
|
+
if(outcome.kind!=="failed"&&!completed)return;
|
|
169
|
+
const rowId=`${FAILOVER_KIND}-${agent.id}-${turnId??Date.now()}`;
|
|
170
|
+
// A switch under way, or the automatic one this turn already had, owns the agent's row: a repeated or concurrent
|
|
171
|
+
// report of the turn adds nothing, so it can neither roll that row back nor start a second switch.
|
|
172
|
+
const settled=(state:Registry)=>switching.has(agent.id)||guard.hasTurn(agent.id,rowId,Date.now())||state.bindings.some(b=>b.agentId===agent.id&&b.status==="switching");
|
|
173
|
+
try{
|
|
174
|
+
await controller.ready;
|
|
175
|
+
const state=await controller.store.read();
|
|
176
|
+
// Without that provider's launcher the CLI runs on the system login, so a switch could not take effect.
|
|
177
|
+
if(!state.integration.enabled||!state.integration.providers.includes(provider)||settled(state))return;
|
|
178
|
+
// An agent started with no app open may have a launch nothing has confirmed yet; its receipt confirms it now.
|
|
179
|
+
const fromId=await controller.accountOf(paseo,agent.id,provider,state),from=labelOf(state,fromId);
|
|
180
|
+
if(!fromId||!from)return;
|
|
181
|
+
// The cache costs no provider request, so an ordinary completed turn ends here.
|
|
182
|
+
if(completed&&!mayBeUsedUp((await controller.usage.list()).find(item=>item.accountId===fromId),Date.now()))return;
|
|
183
|
+
// A full window read earlier still counts until its reset, so the account is read again before deciding.
|
|
184
|
+
const [usage,snapshot]=await Promise.all([controller.usage.refresh(fromId),paseo.agents.ref(agent.id).refresh().catch(()=>null)]);
|
|
185
|
+
if(completed&&extraUsageLeft(usage.find(item=>item.accountId===fromId)))return;
|
|
186
|
+
// A switch may have started or finished during those reads; from here to the row nothing awaits.
|
|
187
|
+
const latest=await controller.store.read();
|
|
188
|
+
if(settled(latest)||boundAccount(latest,agent.id,provider)!==fromId)return;
|
|
189
|
+
const model=snapshot?.agent.runtimeInfo?.model||snapshot?.agent.model||null,now=Date.now();
|
|
190
|
+
const decision=failoverDecision({currentId:fromId,accounts:latest.accounts.filter(a=>a.provider===provider),usage,model,now});
|
|
191
|
+
if(!decision)return;
|
|
192
|
+
const offer=decision.kind==="offer"?latest.accounts.find(a=>a.id===decision.toId):undefined;
|
|
193
|
+
const row:FailoverRow={rowId,state:offer?"offered":"none",from,fromId,to:offer?.label??null,toId:offer?.id??null,resetsAt:decision.resetsAt,error:null};
|
|
194
|
+
if(row.toId&&latest.autoFailover[provider]&&guard.allow(agent.id,rowId,fromId,row.toId,now)){
|
|
195
|
+
// Recorded before the first await of the switch: the guard's check and record must not be split.
|
|
196
|
+
guard.record(agent.id,rowId,fromId,row.toId,now);
|
|
197
|
+
// The switch reloads the agent and waits for its launch, longer than Paseo waits for a hook; the row reports it.
|
|
198
|
+
// A completed turn may have finished its work, so that switch does not ask the agent to continue.
|
|
199
|
+
// switchOver logged any failure but a refusal already.
|
|
200
|
+
void switchOver(paseo,agent.id,completed?{...row,resumes:false}:row,row.toId,"auto").catch(error=>{if(error instanceof SwitchRefusal)console.error(`Could not switch agent ${agent.id} automatically: ${error.message}`);});
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
// Recorded before the await, so a turn reported meanwhile finds it.
|
|
204
|
+
const key=JSON.stringify([agent.id,fromId,row.resetsAt]);
|
|
205
|
+
if(offered.has(key))return;
|
|
206
|
+
offered.add(key);
|
|
207
|
+
await appendFailoverRow(paseo,agent.id,row);
|
|
208
|
+
}catch(error){console.error(`Could not check whether agent ${agent.id} ran out of its account's limit: ${reason(error)}`);}
|
|
209
|
+
});
|
|
210
|
+
return async()=>{removeCreate();removeHook();removeCreated();removeTurnEnded();startNotes.clear();await controller.close();};
|
|
79
211
|
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-plugin-account-switcher",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "paseo-plugin-account-switcher",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.8.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@iarna/toml": "^2.2.5"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-plugin-account-switcher",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "dutchakdev",
|
|
@@ -37,18 +37,19 @@
|
|
|
37
37
|
"@iarna/toml": "^2.2.5"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@getpaseo/client": "0.
|
|
41
|
-
"@getpaseo/plugin": "0.
|
|
42
|
-
"@getpaseo/protocol": "0.
|
|
40
|
+
"@getpaseo/client": "0.11.4",
|
|
41
|
+
"@getpaseo/plugin": "0.11.4",
|
|
42
|
+
"@getpaseo/protocol": "0.11.4",
|
|
43
43
|
"@tanstack/react-query": "^5.90.11",
|
|
44
44
|
"@types/node": "^22.0.0",
|
|
45
45
|
"@types/react": "~19.2.0",
|
|
46
|
-
"esbuild": "^0.
|
|
46
|
+
"esbuild": "^0.28.2",
|
|
47
47
|
"react": "19.1.0",
|
|
48
48
|
"react-native": "0.81.5",
|
|
49
49
|
"semver": "^7.8.5",
|
|
50
|
-
"typescript": "^
|
|
51
|
-
"
|
|
50
|
+
"typescript": "^7.0.2",
|
|
51
|
+
"vite": "^8.3.5",
|
|
52
|
+
"vitest": "^5.0.5",
|
|
52
53
|
"zod": "^4.4.3"
|
|
53
54
|
},
|
|
54
55
|
"repository": {
|
package/server/controller.ts
CHANGED
|
@@ -1,23 +1,34 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { promisify } from "node:util";
|
|
2
|
+
import { promisify, stripVTControlCharacters } from "node:util";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join, dirname, resolve } from "node:path";
|
|
5
5
|
import { lstat, readFile, realpath, rm } from "node:fs/promises";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import type { PaseoApi } from "./paseo-api";
|
|
8
8
|
import { AccountSchema, missingCli, type LoginSession, type Provider } from "../shared/contracts";
|
|
9
|
-
import { AccountStore, accountFrom, type Registry, type StoredAccount } from "./store";
|
|
9
|
+
import { AccountStore, accountFrom, boundAccount, type Registry, type StoredAccount, type StoredBinding } from "./store";
|
|
10
10
|
import { prepareProfile } from "./profiles";
|
|
11
11
|
import { accountCommand, accountEnvironment, launchLogin, probeAccount, removeAccountCredentials } from "./auth";
|
|
12
12
|
import { installIntegration, restoreIntegration, writeLaunchers, prepareRuntime, reconcileIntegration } from "./integration";
|
|
13
|
-
import { SwitchService } from "./switching";
|
|
13
|
+
import { SwitchRefusal, SwitchService } from "./switching";
|
|
14
14
|
import { createUsageService, readCredentialVersion, type AccountReadOptions, type QuotaAccount } from "./usage";
|
|
15
15
|
import { renewExpiredClaudeToken } from "./usage/claude";
|
|
16
16
|
import { LoginSessions, type LoginDependencies } from "./login";
|
|
17
17
|
|
|
18
18
|
const execFileAsync=promisify(execFile);
|
|
19
|
+
// Paseo sets these for its own Node processes, this plugin's included, and removes them before it starts an outside
|
|
20
|
+
// command. Inherited, ELECTRON_RUN_AS_NODE makes an Electron executable, such as a `paseo` link to the desktop app's
|
|
21
|
+
// executable left by an older install, run as plain Node, which then fails to load "agent" as a script.
|
|
22
|
+
const RUNTIME_ENV=["PASEO_NODE_ENV","PASEO_DESKTOP_MANAGED","PASEO_SUPERVISED","ELECTRON_RUN_AS_NODE","ELECTRON_NO_ATTACH_CONSOLE","ESBUILD_BINARY_PATH"];
|
|
23
|
+
// PASEO_CLI names the desktop app's bundled CLI, for the daemon the app starts and for one started from the app's terminal,
|
|
24
|
+
// which inherits it and can outlive the app. A standalone daemon finds `paseo` on PATH.
|
|
25
|
+
function paseoCli(){const env={...process.env};for(const key of RUNTIME_ENV)delete env[key];return{command:process.env.PASEO_CLI?.trim()||"paseo",env};}
|
|
19
26
|
// A revoked sign-in fails every renewal; this bounds how often it starts the CLI.
|
|
20
27
|
const RENEWAL_INTERVAL=600000;
|
|
28
|
+
// Agent statuses that show a launch got under way, for the receipt check: the Accounts list waits for a session that is
|
|
29
|
+
// up. Failover also takes "error", which Paseo sets when a turn fails, before the plugin's turn_ended hook runs: the
|
|
30
|
+
// launcher wrote the receipt when it started the CLI, so the receipt still names the account the agent started on.
|
|
31
|
+
const STARTED=["idle","running"],STARTED_FOR_FAILOVER=[...STARTED,"error"];
|
|
21
32
|
export class AccountController {
|
|
22
33
|
readonly store:AccountStore;
|
|
23
34
|
readonly ready:Promise<void>;
|
|
@@ -56,17 +67,32 @@ export class AccountController {
|
|
|
56
67
|
await this.reconcileDeletedAgents(paseo);
|
|
57
68
|
await this.reconcileLogins();
|
|
58
69
|
const state=await this.store.read();
|
|
59
|
-
for(const binding of state.bindings.
|
|
60
|
-
try{
|
|
61
|
-
const receipt=JSON.parse(await readFile(join(this.store.root,"receipts",encodeURIComponent(binding.agentId)+".json"),"utf8"));
|
|
62
|
-
if(receipt.accountId!==binding.launchAccountId||receipt.launchToken!==binding.launchToken)continue;
|
|
63
|
-
const live=await paseo.agents.ref(binding.agentId).refresh();
|
|
64
|
-
if(!live||!["idle","running"].includes(live.agent.status))continue;
|
|
65
|
-
await this.store.change(r=>{const b=r.bindings.find(b=>b.agentId===binding.agentId);if(r.integration.enabled&&!this.integrationChanging&&b&&b.launchToken===binding.launchToken&&b.launchAccountId===binding.launchAccountId&&b.currentAccountId===null&&b.status==="ready"){b.currentAccountId=binding.launchAccountId;b.launchToken=null;b.registrationObserved=true;}});
|
|
66
|
-
}catch{/* The UI keeps the account unconfirmed until native startup succeeds. */}
|
|
67
|
-
}
|
|
70
|
+
for(const binding of state.bindings)await this.confirmLaunch(paseo,state,binding,STARTED);
|
|
68
71
|
return this.store.snapshot();
|
|
69
72
|
}
|
|
73
|
+
/** Confirms that an agent runs on the account it was launched on: the launcher's receipt names that account and launch,
|
|
74
|
+
* and the agent's status is one of `started`. True once the binding records it as the agent's account. */
|
|
75
|
+
private async confirmLaunch(paseo:PaseoApi,state:Registry,binding:StoredBinding,started:readonly string[]):Promise<boolean>{
|
|
76
|
+
if(!state.integration.enabled||this.integrationChanging||binding.currentAccountId!==null||binding.status!=="ready"||!binding.launchAccountId||!binding.launchToken)return false;
|
|
77
|
+
try{
|
|
78
|
+
const receipt=JSON.parse(await readFile(join(this.store.root,"receipts",encodeURIComponent(binding.agentId)+".json"),"utf8"));
|
|
79
|
+
if(receipt.accountId!==binding.launchAccountId||receipt.launchToken!==binding.launchToken)return false;
|
|
80
|
+
const live=await paseo.agents.ref(binding.agentId).refresh();
|
|
81
|
+
if(!live||!started.includes(live.agent.status))return false;
|
|
82
|
+
return await this.store.change(r=>{const b=r.bindings.find(b=>b.agentId===binding.agentId);if(r.integration.enabled&&!this.integrationChanging&&b&&b.launchToken===binding.launchToken&&b.launchAccountId===binding.launchAccountId&&b.currentAccountId===null&&b.status==="ready"){b.currentAccountId=binding.launchAccountId;b.launchToken=null;b.registrationObserved=true;return true;}return false;});
|
|
83
|
+
}catch{/* The UI keeps the account unconfirmed until native startup succeeds. */return false;}
|
|
84
|
+
}
|
|
85
|
+
/** The account an agent runs on, for failover. A launch not confirmed yet is confirmed now by its receipt, the check
|
|
86
|
+
* `snapshot` makes while the app polls: an agent started with no app open (a schedule, a heartbeat, `paseo run`) would
|
|
87
|
+
* otherwise wait for that. Unlike `snapshot` it also accepts an agent a failed turn left in "error". Null when nothing
|
|
88
|
+
* confirms one. `state` is the registry to take the binding from, the latest by default. */
|
|
89
|
+
async accountOf(paseo:PaseoApi,agentId:string,provider:Provider,state?:Registry):Promise<string|null>{
|
|
90
|
+
await this.ready;
|
|
91
|
+
const registry=state??await this.store.read(),known=boundAccount(registry,agentId,provider);
|
|
92
|
+
if(known)return known;
|
|
93
|
+
const binding=registry.bindings.find(b=>b.agentId===agentId);
|
|
94
|
+
return binding&&await this.confirmLaunch(paseo,registry,binding,STARTED_FOR_FAILOVER)?binding.launchAccountId:null;
|
|
95
|
+
}
|
|
70
96
|
async observeAgentRegistration(agentId:string){
|
|
71
97
|
await this.ready;
|
|
72
98
|
await this.store.change(r=>{const binding=r.bindings.find(b=>b.agentId===agentId);if(binding)binding.registrationObserved=true;});
|
|
@@ -307,19 +333,29 @@ export class AccountController {
|
|
|
307
333
|
}
|
|
308
334
|
switcher(paseo:PaseoApi):SwitchService {
|
|
309
335
|
let service=this.switches.get(paseo);if(service)return service;
|
|
310
|
-
const requireIntegration=async()=>{if(this.integrationChanging)throw new
|
|
336
|
+
const requireIntegration=async()=>{if(this.integrationChanging)throw new SwitchRefusal("An integration change is still in progress.");await reconcileIntegration(paseo,this.store);if(!(await this.store.read()).integration.enabled)throw new SwitchRefusal("Account integration is no longer active. Check its settings and enable it again.");};
|
|
311
337
|
service=new SwitchService({store:this.store,applying:this.applying,usage:()=>this.usage.list(),checkAccount:async id=>{await requireIntegration();return this.checkAccount(id);},inspect:async(id)=>{
|
|
312
|
-
const result=await paseo.agents.ref(id).refresh();if(!result)throw new
|
|
338
|
+
const result=await paseo.agents.ref(id).refresh();if(!result)throw new SwitchRefusal("Agent not found.");
|
|
313
339
|
const a=result.agent;
|
|
314
340
|
return{provider:a.provider,busy:a.status==="running"||a.status==="initializing"||!!a.activeTurn||a.pendingPermissions.length>0,archived:!!a.archivedAt};
|
|
315
341
|
},reload:async(id)=>{
|
|
316
342
|
await requireIntegration();
|
|
317
343
|
const config=JSON.parse(await readFile(join(dirname(this.store.root),"config.json"),"utf8"));
|
|
318
344
|
const listen=config.daemon?.listen;
|
|
319
|
-
if(typeof listen!=="string"||!listen)throw new
|
|
345
|
+
if(typeof listen!=="string"||!listen)throw new SwitchRefusal("Could not identify the daemon for reload.");
|
|
320
346
|
const host=listen.replace(/^0\.0\.0\.0:/,"127.0.0.1:");
|
|
321
|
-
|
|
322
|
-
|
|
347
|
+
const cli=paseoCli();let command=cli.command;
|
|
348
|
+
const reload=(file:string)=>execFileAsync(file,["agent","reload",id,"--json","--host",host],{timeout:120_000,maxBuffer:1024*1024,env:cli.env});
|
|
349
|
+
try{
|
|
350
|
+
// A CLI that could not start reloaded nothing, so `paseo` on PATH can still try. One that ran and failed is not repeated.
|
|
351
|
+
await reload(command).catch(error=>{const code=(error as {code?:unknown}).code;if(command==="paseo"||(code!=="ENOENT"&&code!=="EACCES"))throw error;command="paseo";return reload(command);});
|
|
352
|
+
}
|
|
353
|
+
catch(error){
|
|
354
|
+
// The chat gets the refusal; the cause, which can name local paths, goes only to the plugin log.
|
|
355
|
+
const {code,signal,stderr}=error as {code?:unknown;signal?:unknown;stderr?:unknown};
|
|
356
|
+
console.error(`Native reload of agent ${id} with ${command} failed (${signal?`signal ${signal}`:`code ${code}`}): ${stripVTControlCharacters(String(stderr??"")).replace(/\s+/g," ").trim().slice(0,500)||"no output"}`);
|
|
357
|
+
throw new SwitchRefusal("The native agent reload failed. Check the agent status and try again.");
|
|
358
|
+
}
|
|
323
359
|
// Paseo 0.11 reloads into an idle session and spawns the CLI on first use; listing
|
|
324
360
|
// commands starts it so the launcher can confirm the account. Older hosts already started it.
|
|
325
361
|
const agent=paseo.agents.ref(id) as {commands?:()=>Promise<unknown>};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { UsageSnapshot } from "../shared/contracts";
|
|
2
|
+
import { defaultBlocker, fullUntilReset, launchOrder, type SelectionAccount } from "./selection";
|
|
3
|
+
|
|
4
|
+
export type FailoverDecision =
|
|
5
|
+
| { kind: "offer"; fromId: string; toId: string; resetsAt: string | null }
|
|
6
|
+
| { kind: "none"; fromId: string; resetsAt: string | null };
|
|
7
|
+
|
|
8
|
+
/** What to do after an agent's turn failed on `currentId`. Paseo does not say why a turn failed, so the only evidence
|
|
9
|
+
* is the plugin's own readings: null unless they show the account is used up (a full account-wide window until a future
|
|
10
|
+
* reset, or the provider's own "not allowed"). A plan that lacks the model is not a limit and gives null as well.
|
|
11
|
+
* Readings are taken as given; the caller refreshes them first. `resetsAt` is the latest end of the full windows:
|
|
12
|
+
* the account stays blocked until the last of them resets; null when the evidence carries none.
|
|
13
|
+
* The replacement is the first account a new agent would try instead. */
|
|
14
|
+
export function failoverDecision(input: { currentId: string; accounts: readonly SelectionAccount[]; usage: readonly UsageSnapshot[]; model: string | null; now: number }): FailoverDecision | null {
|
|
15
|
+
const { currentId, usage, now } = input;
|
|
16
|
+
const evidence = { defaultId: currentId, accounts: input.accounts, usage, model: input.model, now };
|
|
17
|
+
if (defaultBlocker(evidence) !== "exhausted") return null;
|
|
18
|
+
const resets = (usage.find(item => item.accountId === currentId)?.windows ?? [])
|
|
19
|
+
.filter(window => fullUntilReset(window, now))
|
|
20
|
+
.map(window => window.resetsAt!)
|
|
21
|
+
.sort((a, b) => Date.parse(b) - Date.parse(a));
|
|
22
|
+
const resetsAt = resets[0] ?? null;
|
|
23
|
+
const toId = launchOrder(evidence).find(id => id !== currentId);
|
|
24
|
+
return toId ? { kind: "offer", fromId: currentId, toId, resetsAt } : { kind: "none", fromId: currentId, resetsAt };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Whether the account's paid extra usage still has room: a spend window under 100%. Claude then keeps answering past
|
|
28
|
+
* a full 5-hour window, so a completed turn on such an account did not run out. */
|
|
29
|
+
export function extraUsageLeft(snapshot: UsageSnapshot | undefined): boolean {
|
|
30
|
+
return !!snapshot?.windows.some(window => window.scope === "spend" && window.usedPercent !== null && window.usedPercent < 100);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Whether the last reading of an account, read from the cache, gives reason to read it again after a turn that completed:
|
|
34
|
+
* a full account-wide window until a later reset, or the provider's "not allowed" however old, unless paid extra usage
|
|
35
|
+
* still has room. Claude reports a turn its limit stopped as completed, so this keeps every ordinary completed turn from
|
|
36
|
+
* costing a provider request. */
|
|
37
|
+
export function mayBeUsedUp(cached: UsageSnapshot | undefined, now: number): boolean {
|
|
38
|
+
return !!cached && !extraUsageLeft(cached) && (cached.usageAllowed === false || cached.windows.some(window => fullUntilReset(window, now)));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const HOUR = 3_600_000, MAX_PER_HOUR = 3;
|
|
42
|
+
type Switch = { turnKey: string; fromId: string; toId: string; at: number };
|
|
43
|
+
|
|
44
|
+
/** Keeps automatic switching from looping, in memory: one switch per turn, three per agent in the last hour (rolling),
|
|
45
|
+
* and never to an account the agent left in that hour. `allow` only asks; `record` registers a switch that happened. */
|
|
46
|
+
export class AutoFailoverGuard {
|
|
47
|
+
private readonly switches = new Map<string, Switch[]>();
|
|
48
|
+
|
|
49
|
+
private recent(agentId: string, now: number): Switch[] {
|
|
50
|
+
return (this.switches.get(agentId) ?? []).filter(item => now - item.at < HOUR);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
allow(agentId: string, turnKey: string, fromId: string, toId: string, now: number): boolean {
|
|
54
|
+
if (fromId === toId) return false;
|
|
55
|
+
const recent = this.recent(agentId, now);
|
|
56
|
+
return recent.length < MAX_PER_HOUR && !recent.some(item => item.turnKey === turnKey || item.fromId === toId);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Whether this turn already had its automatic switch: a turn reported again must not be offered or switched twice. */
|
|
60
|
+
hasTurn(agentId: string, turnKey: string, now: number): boolean {
|
|
61
|
+
return this.recent(agentId, now).some(item => item.turnKey === turnKey);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
record(agentId: string, turnKey: string, fromId: string, toId: string, now: number): void {
|
|
65
|
+
this.switches.set(agentId, [...this.recent(agentId, now), { turnKey, fromId, toId, at: now }]);
|
|
66
|
+
}
|
|
67
|
+
}
|