@kapybara/zerosub 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/store.ts +86 -59
- package/index.client.tsx +2 -2
- package/package.json +2 -1
- package/server/adapter.ts +17 -4
- package/server/claude.ts +15 -5
- package/server/codex.ts +77 -15
- package/server/handoff.ts +1 -1
- package/server/limits.ts +11 -10
- package/server/process.ts +34 -5
- package/server/reopen.ts +15 -8
- package/server/service.ts +12 -1
package/client/store.ts
CHANGED
|
@@ -19,111 +19,138 @@ export interface StoreSnapshot {
|
|
|
19
19
|
* One poller per installation feeds the surface, composer pills and commands.
|
|
20
20
|
* Polling is cheap: the daemon answers from memory and refreshes usage on its own schedule.
|
|
21
21
|
*/
|
|
22
|
-
export
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
22
|
+
export interface ZeroSubStore {
|
|
23
|
+
readonly current: StoreSnapshot;
|
|
24
|
+
start(): void;
|
|
25
|
+
stop(): void;
|
|
26
|
+
rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
|
27
|
+
contract: PluginRpcContract<InputSchema, OutputSchema>,
|
|
28
|
+
input: ZodInput<InputSchema>,
|
|
29
|
+
): Promise<ZodOutput<OutputSchema>>;
|
|
30
|
+
subscribe(listener: () => void): () => void;
|
|
31
|
+
getSnapshot(): StoreSnapshot;
|
|
32
|
+
watch(intervalMs: number): () => void;
|
|
33
|
+
watchClosely(): () => void;
|
|
34
|
+
refresh(options?: { refreshUsage?: boolean; fresh?: boolean }): Promise<void>;
|
|
35
|
+
}
|
|
32
36
|
|
|
33
|
-
|
|
37
|
+
/**
|
|
38
|
+
* A closure, not a class: Hermes in React Native 0.81 has no class support in eval'd code. This bundle is
|
|
39
|
+
* large enough to be compiled lazily, so a class silently becomes undefined and `new` throws reading `.prototype`.
|
|
40
|
+
*/
|
|
41
|
+
export function createZeroSubStore(client: PluginClientContext): ZeroSubStore {
|
|
42
|
+
let snapshot: StoreSnapshot = { state: null, error: null };
|
|
43
|
+
const listeners = new Set<() => void>();
|
|
44
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
45
|
+
let inFlight: Promise<void> | null = null;
|
|
46
|
+
let issued = 0;
|
|
47
|
+
let published = 0;
|
|
48
|
+
let stopped = false;
|
|
49
|
+
/** Poll intervals wanted by open views; the shortest wins. */
|
|
50
|
+
const watchers: number[] = [];
|
|
34
51
|
|
|
35
|
-
start(): void {
|
|
36
|
-
void
|
|
52
|
+
function start(): void {
|
|
53
|
+
void refresh();
|
|
37
54
|
}
|
|
38
55
|
|
|
39
|
-
stop(): void {
|
|
40
|
-
|
|
41
|
-
if (
|
|
42
|
-
|
|
56
|
+
function stop(): void {
|
|
57
|
+
stopped = true;
|
|
58
|
+
if (timer) clearTimeout(timer);
|
|
59
|
+
listeners.clear();
|
|
43
60
|
}
|
|
44
61
|
|
|
45
62
|
/** Calls a daemon handler, then refreshes state so every view sees the result. */
|
|
46
|
-
async rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
|
63
|
+
async function rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
|
47
64
|
contract: PluginRpcContract<InputSchema, OutputSchema>,
|
|
48
65
|
input: ZodInput<InputSchema>,
|
|
49
66
|
): Promise<ZodOutput<OutputSchema>> {
|
|
50
67
|
try {
|
|
51
|
-
return await
|
|
68
|
+
return await client.rpc(contract, input);
|
|
52
69
|
} finally {
|
|
53
70
|
// A poll already in flight started before this action, so ask again once it lands.
|
|
54
|
-
void
|
|
71
|
+
void refresh({ fresh: true });
|
|
55
72
|
}
|
|
56
73
|
}
|
|
57
74
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
subscribe = (listener: () => void): (() => void) => {
|
|
63
|
-
this.listeners.add(listener);
|
|
64
|
-
return () => this.listeners.delete(listener);
|
|
75
|
+
const subscribe = (listener: () => void): (() => void) => {
|
|
76
|
+
listeners.add(listener);
|
|
77
|
+
return () => listeners.delete(listener);
|
|
65
78
|
};
|
|
66
79
|
|
|
67
|
-
getSnapshot = (): StoreSnapshot =>
|
|
80
|
+
const getSnapshot = (): StoreSnapshot => snapshot;
|
|
68
81
|
|
|
69
82
|
/** Poll at least this often until the returned function is called. */
|
|
70
|
-
watch(intervalMs: number): () => void {
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
function watch(intervalMs: number): () => void {
|
|
84
|
+
watchers.push(intervalMs);
|
|
85
|
+
schedule();
|
|
73
86
|
let watching = true;
|
|
74
87
|
return () => {
|
|
75
88
|
if (!watching) return;
|
|
76
89
|
watching = false;
|
|
77
|
-
const index =
|
|
78
|
-
if (index >= 0)
|
|
79
|
-
|
|
90
|
+
const index = watchers.indexOf(intervalMs);
|
|
91
|
+
if (index >= 0) watchers.splice(index, 1);
|
|
92
|
+
schedule();
|
|
80
93
|
};
|
|
81
94
|
}
|
|
82
95
|
|
|
83
96
|
/** Poll quickly while something (a sign-in flow) is waiting on the daemon. */
|
|
84
|
-
watchClosely(): () => void {
|
|
85
|
-
return
|
|
97
|
+
function watchClosely(): () => void {
|
|
98
|
+
return watch(ACTIVE_POLL_MS);
|
|
86
99
|
}
|
|
87
100
|
|
|
88
|
-
refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
|
|
89
|
-
if (
|
|
90
|
-
if (!options.fresh) return
|
|
91
|
-
return
|
|
101
|
+
function refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
|
|
102
|
+
if (inFlight && !options.refreshUsage) {
|
|
103
|
+
if (!options.fresh) return inFlight;
|
|
104
|
+
return inFlight.then(() => refresh({ refreshUsage: options.refreshUsage }));
|
|
92
105
|
}
|
|
93
|
-
const sequence = ++
|
|
94
|
-
const run =
|
|
106
|
+
const sequence = ++issued;
|
|
107
|
+
const run = client
|
|
95
108
|
.rpc(getState, { refreshUsage: options.refreshUsage })
|
|
96
109
|
.then((state) => {
|
|
97
110
|
// An older, slower answer must not overwrite a newer one.
|
|
98
|
-
if (sequence >=
|
|
99
|
-
|
|
100
|
-
|
|
111
|
+
if (sequence >= published) {
|
|
112
|
+
published = sequence;
|
|
113
|
+
publish({ state, error: null });
|
|
101
114
|
}
|
|
102
115
|
})
|
|
103
116
|
.catch((error: unknown) => {
|
|
104
|
-
if (sequence >=
|
|
117
|
+
if (sequence >= published) publish({ state: snapshot.state, error: describe(error) });
|
|
105
118
|
})
|
|
106
119
|
.finally(() => {
|
|
107
|
-
if (
|
|
108
|
-
|
|
120
|
+
if (inFlight === run) inFlight = null;
|
|
121
|
+
schedule();
|
|
109
122
|
});
|
|
110
|
-
|
|
123
|
+
inFlight = run;
|
|
111
124
|
return run;
|
|
112
125
|
}
|
|
113
126
|
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
for (const listener of [...
|
|
127
|
+
function publish(next: StoreSnapshot): void {
|
|
128
|
+
if (stopped) return;
|
|
129
|
+
snapshot = next;
|
|
130
|
+
for (const listener of [...listeners]) listener();
|
|
118
131
|
}
|
|
119
132
|
|
|
120
|
-
|
|
121
|
-
if (
|
|
122
|
-
if (
|
|
123
|
-
const loginActive =
|
|
124
|
-
const delay = Math.min(IDLE_POLL_MS, loginActive ? ACTIVE_POLL_MS : IDLE_POLL_MS, ...
|
|
125
|
-
|
|
133
|
+
function schedule(): void {
|
|
134
|
+
if (stopped) return;
|
|
135
|
+
if (timer) clearTimeout(timer);
|
|
136
|
+
const loginActive = snapshot.state?.logins.some((login) => isOpen(login.step)) ?? false;
|
|
137
|
+
const delay = Math.min(IDLE_POLL_MS, loginActive ? ACTIVE_POLL_MS : IDLE_POLL_MS, ...watchers);
|
|
138
|
+
timer = setTimeout(() => void refresh(), delay);
|
|
126
139
|
}
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
get current() {
|
|
143
|
+
return snapshot;
|
|
144
|
+
},
|
|
145
|
+
start,
|
|
146
|
+
stop,
|
|
147
|
+
rpc,
|
|
148
|
+
subscribe,
|
|
149
|
+
getSnapshot,
|
|
150
|
+
watch,
|
|
151
|
+
watchClosely,
|
|
152
|
+
refresh,
|
|
153
|
+
};
|
|
127
154
|
}
|
|
128
155
|
|
|
129
156
|
function isOpen(step: string): boolean {
|
package/index.client.tsx
CHANGED
|
@@ -3,12 +3,12 @@ import { AccountsSurface } from "./client/accounts-surface";
|
|
|
3
3
|
import { contributeCommands } from "./client/commands";
|
|
4
4
|
import { contributePills } from "./client/pills";
|
|
5
5
|
import { PreferencesScreen } from "./client/settings-screen";
|
|
6
|
-
import {
|
|
6
|
+
import { createZeroSubStore } from "./client/store";
|
|
7
7
|
import { SwitchRowView } from "./client/switch-row";
|
|
8
8
|
import { SWITCH_ROW_KIND, SWITCH_ROW_VERSION, SwitchRowSchema } from "./shared/timeline";
|
|
9
9
|
|
|
10
10
|
export default function contribute(client: PluginClientContext) {
|
|
11
|
-
const store =
|
|
11
|
+
const store = createZeroSubStore(client);
|
|
12
12
|
store.start();
|
|
13
13
|
|
|
14
14
|
client.addSurface("accounts", (props) => <AccountsSurface {...props} store={store} />);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kapybara/zerosub",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"paseo",
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
"@tanstack/react-query": "^5.90.11",
|
|
47
47
|
"@types/node": "^22.20.4",
|
|
48
48
|
"@types/react": "~19.2.0",
|
|
49
|
+
"esbuild": "^0.28.2",
|
|
49
50
|
"react": "19.1.0",
|
|
50
51
|
"react-native": "0.81.5",
|
|
51
52
|
"typescript": "^5.9.3",
|
package/server/adapter.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { PluginTurnOutcome } from "@getpaseo/plugin/server";
|
|
1
|
+
import type { PluginLifecycleEvents, PluginTurnOutcome } from "@getpaseo/plugin/server";
|
|
3
2
|
import type { Family, LoginMethod, LoginStep, Usage } from "../shared/model";
|
|
4
3
|
import type { RedeemOutcome } from "../shared/rpc";
|
|
5
4
|
|
|
5
|
+
/**
|
|
6
|
+
* One timeline entry. Taken from the SDK rather than `@getpaseo/protocol`: Paseo only supplies
|
|
7
|
+
* `@getpaseo/plugin` to plugins, and an npm install has no devDependencies to resolve it from.
|
|
8
|
+
*/
|
|
9
|
+
export type AgentTimelineItem = PluginLifecycleEvents["agent.turn_ended"]["timeline"][number];
|
|
10
|
+
|
|
6
11
|
/** A provider's answer to a redeem request. */
|
|
7
12
|
export interface RedeemReply {
|
|
8
13
|
outcome: RedeemOutcome;
|
|
@@ -35,6 +40,14 @@ export interface LimitHit {
|
|
|
35
40
|
message: string;
|
|
36
41
|
}
|
|
37
42
|
|
|
43
|
+
/** A finished turn, as Paseo reports it. */
|
|
44
|
+
export interface TurnEvent {
|
|
45
|
+
outcome: PluginTurnOutcome;
|
|
46
|
+
timeline: readonly AgentTimelineItem[];
|
|
47
|
+
/** Paseo's id for the turn; `null` when the turn failed before it started. */
|
|
48
|
+
turnId?: string | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
38
51
|
export interface LoginProgress {
|
|
39
52
|
step: LoginStep;
|
|
40
53
|
/** Link that finishes by itself when opened on the daemon machine (localhost callback), or the device-code page. */
|
|
@@ -88,9 +101,9 @@ export interface FamilyAdapter {
|
|
|
88
101
|
login(home: string | null, method: LoginMethod): Promise<LoginHandle>;
|
|
89
102
|
logout(home: string): Promise<void>;
|
|
90
103
|
/** Looks for a subscription usage-limit failure in a finished turn. */
|
|
91
|
-
detectLimit(event:
|
|
104
|
+
detectLimit(event: TurnEvent): LimitHit | null;
|
|
92
105
|
/** Looks for a turn that failed because the account's login is no longer valid. */
|
|
93
|
-
detectSignOut(event:
|
|
106
|
+
detectSignOut(event: TurnEvent): string | null;
|
|
94
107
|
}
|
|
95
108
|
|
|
96
109
|
/** The environment for a process ZeroSub spawns against `patch`. */
|
package/server/claude.ts
CHANGED
|
@@ -271,6 +271,7 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
|
|
|
271
271
|
private poll: ReturnType<typeof setInterval> | null = null;
|
|
272
272
|
private canceled = false;
|
|
273
273
|
private exited = false;
|
|
274
|
+
private killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
274
275
|
|
|
275
276
|
constructor(command: string, args: string[], env: NodeJS.ProcessEnv, private readonly capture: string | null) {
|
|
276
277
|
super();
|
|
@@ -295,14 +296,17 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
|
|
|
295
296
|
resolve({ ok: false, message: friendlyFailure(failure ?? this.stderr.trim()) });
|
|
296
297
|
});
|
|
297
298
|
});
|
|
298
|
-
|
|
299
|
-
|
|
299
|
+
// Decoding the stream, not each chunk, keeps a character split across two chunks whole.
|
|
300
|
+
this.child.stdout.setEncoding("utf8");
|
|
301
|
+
this.child.stderr.setEncoding("utf8");
|
|
302
|
+
this.child.stdout.on("data", (chunk: string) => {
|
|
303
|
+
this.stdout = (this.stdout + stripAnsi(chunk)).slice(-16_384);
|
|
300
304
|
const manual = firstUrl(this.stdout, /\/oauth\/authorize/);
|
|
301
305
|
if (manual && manual !== this.progress.codeUrl) this.update({ codeUrl: manual, step: "waiting" });
|
|
302
306
|
});
|
|
303
|
-
this.child.stderr.on("data", (chunk:
|
|
304
|
-
const text = stripAnsi(chunk
|
|
305
|
-
this.stderr
|
|
307
|
+
this.child.stderr.on("data", (chunk: string) => {
|
|
308
|
+
const text = stripAnsi(chunk);
|
|
309
|
+
this.stderr = (this.stderr + text).slice(-16_384);
|
|
306
310
|
if (/invalid code/i.test(text)) {
|
|
307
311
|
this.update({ message: "That code didn't work. Copy the whole code from the page and paste it again." });
|
|
308
312
|
}
|
|
@@ -332,11 +336,17 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
|
|
|
332
336
|
}
|
|
333
337
|
|
|
334
338
|
cancel(): void {
|
|
339
|
+
if (this.exited || this.canceled) return;
|
|
335
340
|
this.canceled = true;
|
|
336
341
|
this.child.kill("SIGTERM");
|
|
342
|
+
this.killTimer = setTimeout(() => {
|
|
343
|
+
if (!this.exited) this.child.kill("SIGKILL");
|
|
344
|
+
}, 3_000);
|
|
345
|
+
this.killTimer.unref();
|
|
337
346
|
}
|
|
338
347
|
|
|
339
348
|
private stop(): void {
|
|
349
|
+
clearTimeout(this.killTimer);
|
|
340
350
|
if (this.poll) clearInterval(this.poll);
|
|
341
351
|
if (this.capture) void rm(this.capture, { force: true });
|
|
342
352
|
}
|
package/server/codex.ts
CHANGED
|
@@ -20,10 +20,17 @@ const CLIENT_NAME = "codex_cli_rs";
|
|
|
20
20
|
|
|
21
21
|
type Json = Record<string, unknown>;
|
|
22
22
|
|
|
23
|
+
const MAX_FRAME_BYTES = 1024 * 1024;
|
|
24
|
+
/** Its steps time out one by one, so without this a stuck read could keep its callers waiting ~150 s. */
|
|
25
|
+
const READ_DEADLINE_MS = 60_000;
|
|
26
|
+
|
|
23
27
|
/** Newline-delimited JSON-RPC with `codex app-server` (no `jsonrpc` field on the wire). */
|
|
24
28
|
class AppServer {
|
|
25
29
|
private nextId = 1;
|
|
26
30
|
private buffer = "";
|
|
31
|
+
/** Dropping the rest of a message over the limit, up to its newline. */
|
|
32
|
+
private skipping = false;
|
|
33
|
+
private warnedOversized = false;
|
|
27
34
|
private stderr = "";
|
|
28
35
|
private closed = false;
|
|
29
36
|
private ending = false;
|
|
@@ -33,9 +40,12 @@ class AppServer {
|
|
|
33
40
|
|
|
34
41
|
private constructor(private readonly child: ChildProcessWithoutNullStreams) {
|
|
35
42
|
child.stdin.on("error", () => undefined);
|
|
36
|
-
|
|
37
|
-
child.
|
|
38
|
-
|
|
43
|
+
// Decoding the stream, not each chunk, keeps a character split across two chunks whole.
|
|
44
|
+
child.stdout.setEncoding("utf8");
|
|
45
|
+
child.stderr.setEncoding("utf8");
|
|
46
|
+
child.stdout.on("data", (text: string) => this.receive(text));
|
|
47
|
+
child.stderr.on("data", (text: string) => {
|
|
48
|
+
this.stderr = (this.stderr + text).slice(-4_000);
|
|
39
49
|
});
|
|
40
50
|
this.exited = new Promise((resolve) => {
|
|
41
51
|
const finish = (error?: Error) => {
|
|
@@ -50,14 +60,17 @@ class AppServer {
|
|
|
50
60
|
});
|
|
51
61
|
}
|
|
52
62
|
|
|
53
|
-
static async open(env: NodeJS.ProcessEnv): Promise<AppServer> {
|
|
63
|
+
static async open(env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<AppServer> {
|
|
54
64
|
const { command, prefix } = await providerCommand("codex");
|
|
65
|
+
signal?.throwIfAborted();
|
|
55
66
|
const child = spawn(command, [...prefix, "app-server"], { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
56
67
|
const server = new AppServer(child);
|
|
68
|
+
// Stops the session wherever it is, even while it is still starting.
|
|
69
|
+
signal?.addEventListener("abort", () => server.close(), { once: true });
|
|
57
70
|
try {
|
|
58
71
|
await server.request(
|
|
59
72
|
"initialize",
|
|
60
|
-
{ clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.2.
|
|
73
|
+
{ clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.2.2" }, capabilities: { experimentalApi: false } },
|
|
61
74
|
60_000,
|
|
62
75
|
);
|
|
63
76
|
server.send({ method: "initialized" });
|
|
@@ -113,13 +126,25 @@ class AppServer {
|
|
|
113
126
|
}
|
|
114
127
|
|
|
115
128
|
private receive(text: string): void {
|
|
116
|
-
this.
|
|
129
|
+
if (this.closed || this.ending) return;
|
|
130
|
+
let rest = text;
|
|
131
|
+
if (this.skipping) {
|
|
132
|
+
const end = rest.indexOf("\n");
|
|
133
|
+
if (end < 0) return;
|
|
134
|
+
this.skipping = false;
|
|
135
|
+
rest = rest.slice(end + 1);
|
|
136
|
+
}
|
|
137
|
+
this.buffer += rest;
|
|
117
138
|
let newline = this.buffer.indexOf("\n");
|
|
118
139
|
while (newline >= 0) {
|
|
119
|
-
const line = this.buffer.slice(0, newline)
|
|
140
|
+
const line = this.buffer.slice(0, newline);
|
|
120
141
|
this.buffer = this.buffer.slice(newline + 1);
|
|
121
142
|
newline = this.buffer.indexOf("\n");
|
|
122
|
-
if (
|
|
143
|
+
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
|
|
144
|
+
this.skipOversized();
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (!line.trim()) continue;
|
|
123
148
|
let message: Json;
|
|
124
149
|
try {
|
|
125
150
|
message = JSON.parse(line) as Json;
|
|
@@ -128,6 +153,19 @@ class AppServer {
|
|
|
128
153
|
}
|
|
129
154
|
this.dispatch(message);
|
|
130
155
|
}
|
|
156
|
+
// A message still arriving can't be kept past the limit either: drop it and skip to its newline.
|
|
157
|
+
if (Buffer.byteLength(this.buffer, "utf8") > MAX_FRAME_BYTES) {
|
|
158
|
+
this.buffer = "";
|
|
159
|
+
this.skipping = true;
|
|
160
|
+
this.skipOversized();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Only that message is lost; the session and every other request carry on. */
|
|
165
|
+
private skipOversized(): void {
|
|
166
|
+
if (this.warnedOversized) return;
|
|
167
|
+
this.warnedOversized = true;
|
|
168
|
+
console.warn("[ZeroSub] skipped a Codex message over the 1 MiB limit");
|
|
131
169
|
}
|
|
132
170
|
|
|
133
171
|
private dispatch(message: Json): void {
|
|
@@ -162,7 +200,7 @@ export class CodexAdapter implements FamilyAdapter {
|
|
|
162
200
|
/** ChatGPT accounts can't decrypt each other's reasoning, so threads stay on their account. */
|
|
163
201
|
readonly portable = false;
|
|
164
202
|
readonly usageSpacingMs = 20_000;
|
|
165
|
-
private readonly snapshots = new Map<string, { at: number; value: Promise<Snapshot> }>();
|
|
203
|
+
private readonly snapshots = new Map<string, { at: number; pending: boolean; value: Promise<Snapshot> }>();
|
|
166
204
|
|
|
167
205
|
async env(home: string | null): Promise<EnvPatch> {
|
|
168
206
|
if (!home) return { CODEX_HOME: null, CODEX_SQLITE_HOME: null };
|
|
@@ -197,15 +235,39 @@ export class CodexAdapter implements FamilyAdapter {
|
|
|
197
235
|
private snapshot(home: string | null, fresh = false): Promise<Snapshot> {
|
|
198
236
|
const key = home ?? "";
|
|
199
237
|
const cached = this.snapshots.get(key);
|
|
200
|
-
if (cached && Date.now() - cached.at < (fresh ? 5_000 : 15_000)) return cached.value;
|
|
201
|
-
const value = this.
|
|
202
|
-
|
|
203
|
-
|
|
238
|
+
if (cached && (cached.pending || Date.now() - cached.at < (fresh ? 5_000 : 15_000))) return cached.value;
|
|
239
|
+
const value = this.readWithDeadline(home).finally(() => {
|
|
240
|
+
const current = this.snapshots.get(key);
|
|
241
|
+
if (current?.value === value) {
|
|
242
|
+
current.pending = false;
|
|
243
|
+
current.at = Date.now();
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
this.snapshots.set(key, { at: Date.now(), pending: true, value });
|
|
247
|
+
value.catch(() => {
|
|
248
|
+
if (this.snapshots.get(key)?.value === value) this.snapshots.delete(key);
|
|
249
|
+
});
|
|
204
250
|
return value;
|
|
205
251
|
}
|
|
206
252
|
|
|
207
|
-
|
|
208
|
-
|
|
253
|
+
/** Everyone waiting shares this read, so when it runs out of time they all get the error and the app server stops. */
|
|
254
|
+
private readWithDeadline(home: string | null): Promise<Snapshot> {
|
|
255
|
+
const deadline = new AbortController();
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
const timer = setTimeout(() => {
|
|
258
|
+
const error = new Error(`Codex did not answer within ${READ_DEADLINE_MS / 1000} s`);
|
|
259
|
+
deadline.abort(error);
|
|
260
|
+
reject(error);
|
|
261
|
+
}, READ_DEADLINE_MS);
|
|
262
|
+
timer.unref();
|
|
263
|
+
this.readSnapshot(home, deadline.signal)
|
|
264
|
+
.then(resolve, reject)
|
|
265
|
+
.finally(() => clearTimeout(timer));
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private async readSnapshot(home: string | null, signal: AbortSignal): Promise<Snapshot> {
|
|
270
|
+
const server = await AppServer.open(spawnEnv(await this.env(home)), signal);
|
|
209
271
|
try {
|
|
210
272
|
const account = ((await server.request("account/read", {})) ?? {}) as Json;
|
|
211
273
|
const details = account.account as { type?: unknown; email?: unknown; planType?: unknown } | null;
|
package/server/handoff.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
|
3
2
|
import type { PluginHookContext } from "@getpaseo/plugin/server";
|
|
3
|
+
import type { AgentTimelineItem } from "./adapter";
|
|
4
4
|
|
|
5
5
|
type PaseoApi = PluginHookContext["paseo"];
|
|
6
6
|
|
package/server/limits.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { PluginTurnOutcome } from "@getpaseo/plugin/server";
|
|
3
|
-
import type { LimitHit, LimitKind } from "./adapter";
|
|
4
|
-
|
|
5
|
-
type TurnEvent = { outcome: PluginTurnOutcome; timeline: readonly AgentTimelineItem[] };
|
|
1
|
+
import type { LimitHit, LimitKind, TurnEvent } from "./adapter";
|
|
6
2
|
|
|
7
3
|
/**
|
|
8
4
|
* Claude Code's exact wording for hard limits (2.1.x templates: `You've hit your ${limit}${suffix}`),
|
|
@@ -56,14 +52,17 @@ function clean(text: string): string {
|
|
|
56
52
|
/**
|
|
57
53
|
* Where a CLI-generated notice can appear in a finished turn: the failure message, error items,
|
|
58
54
|
* Paseo's `[System Error]` rows, and — for Claude, which reports limits as a synthetic reply — the
|
|
59
|
-
* final assistant messages. Ordinary replies earlier in the turn are never inspected.
|
|
55
|
+
* final assistant messages. Ordinary replies earlier in the turn are never inspected. A turn that
|
|
56
|
+
* failed before it started has only its failure: Paseo never recorded its message, so the timeline
|
|
57
|
+
* still ends with the previous turn.
|
|
60
58
|
*/
|
|
61
59
|
function notices(event: TurnEvent, includeFinalReplies: boolean): string[] {
|
|
62
60
|
const found: string[] = [];
|
|
63
61
|
if (event.outcome.kind === "failed") found.push(event.outcome.error.message);
|
|
62
|
+
const timeline = event.turnId === null ? [] : event.timeline;
|
|
64
63
|
let replies = 0;
|
|
65
|
-
for (let index =
|
|
66
|
-
const item =
|
|
64
|
+
for (let index = timeline.length - 1; index >= 0; index -= 1) {
|
|
65
|
+
const item = timeline[index];
|
|
67
66
|
if (!item) continue;
|
|
68
67
|
if (item.type === "user_message") break;
|
|
69
68
|
if (item.type === "error") found.push(item.message);
|
|
@@ -115,13 +114,15 @@ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "
|
|
|
115
114
|
|
|
116
115
|
/**
|
|
117
116
|
* "· resets 3pm (Asia/Kolkata)", "· resets 3:30pm (America/New_York)",
|
|
118
|
-
* "· resets Sep 25, 3pm (Europe/Berlin)"
|
|
117
|
+
* "· resets Sep 25, 3pm (Europe/Berlin)" ("Sep 25 at 3pm" where the CLI's ICU is newer), or the
|
|
118
|
+
* legacy "|1790150000" epoch. A reset in the next calendar year also carries the year
|
|
119
|
+
* ("Jan 2, 2027"), which rolling the date forward already gives.
|
|
119
120
|
*/
|
|
120
121
|
export function parseClaudeReset(text: string, now: Date): string | null {
|
|
121
122
|
const epoch = text.match(/usage limit reached\|(\d{9,})/i);
|
|
122
123
|
if (epoch?.[1]) return new Date(Number(epoch[1]) * 1000).toISOString();
|
|
123
124
|
const match = text.match(
|
|
124
|
-
/resets\s+(?:([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2})
|
|
125
|
+
/resets\s+(?:([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2})(?:,?\s+\d{4})?,?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?(?:\s*\(([^)]+)\))?/i,
|
|
125
126
|
);
|
|
126
127
|
if (!match) return null;
|
|
127
128
|
const [, monthName, dayText, hourText, minuteText, meridiem, zone] = match;
|
package/server/process.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
3
|
|
|
3
4
|
export interface RunResult {
|
|
4
5
|
code: number | null;
|
|
@@ -7,6 +8,8 @@ export interface RunResult {
|
|
|
7
8
|
timedOut: boolean;
|
|
8
9
|
}
|
|
9
10
|
|
|
11
|
+
const MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
12
|
+
|
|
10
13
|
/** Runs a command to completion with a timeout. Never throws for a non-zero exit. */
|
|
11
14
|
export function run(
|
|
12
15
|
command: string,
|
|
@@ -17,6 +20,10 @@ export function run(
|
|
|
17
20
|
let stdout = "";
|
|
18
21
|
let stderr = "";
|
|
19
22
|
let timedOut = false;
|
|
23
|
+
let outputBytes = 0;
|
|
24
|
+
let outputExceeded = false;
|
|
25
|
+
const decoders = { stdout: new StringDecoder("utf8"), stderr: new StringDecoder("utf8") };
|
|
26
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
20
27
|
let child: ChildProcess;
|
|
21
28
|
try {
|
|
22
29
|
child = spawn(command, [...args], {
|
|
@@ -28,21 +35,43 @@ export function run(
|
|
|
28
35
|
resolve({ code: null, stdout, stderr: error instanceof Error ? error.message : String(error), timedOut });
|
|
29
36
|
return;
|
|
30
37
|
}
|
|
38
|
+
const terminate = () => {
|
|
39
|
+
if (killTimer) return;
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
child.kill("SIGTERM");
|
|
42
|
+
killTimer = setTimeout(() => child.kill("SIGKILL"), 2_000);
|
|
43
|
+
killTimer.unref();
|
|
44
|
+
};
|
|
31
45
|
const timer = setTimeout(() => {
|
|
32
46
|
timedOut = true;
|
|
33
|
-
|
|
34
|
-
setTimeout(() => child.kill("SIGKILL"), 2_000).unref();
|
|
47
|
+
terminate();
|
|
35
48
|
}, options.timeoutMs ?? 30_000);
|
|
49
|
+
const collect = (chunk: Buffer, stream: "stdout" | "stderr") => {
|
|
50
|
+
if (outputExceeded) return;
|
|
51
|
+
const remaining = MAX_OUTPUT_BYTES - outputBytes;
|
|
52
|
+
const text = decoders[stream].write(chunk.subarray(0, remaining));
|
|
53
|
+
if (stream === "stdout") stdout += text;
|
|
54
|
+
else stderr += text;
|
|
55
|
+
outputBytes += chunk.length;
|
|
56
|
+
if (outputBytes > MAX_OUTPUT_BYTES) {
|
|
57
|
+
outputExceeded = true;
|
|
58
|
+
terminate();
|
|
59
|
+
}
|
|
60
|
+
};
|
|
36
61
|
// A child that exits early turns our stdin write into EPIPE; without a listener that kills the plugin.
|
|
37
62
|
child.stdin?.on("error", () => undefined);
|
|
38
|
-
child.stdout?.on("data", (chunk: Buffer) => (
|
|
39
|
-
child.stderr?.on("data", (chunk: Buffer) => (
|
|
63
|
+
child.stdout?.on("data", (chunk: Buffer) => collect(chunk, "stdout"));
|
|
64
|
+
child.stderr?.on("data", (chunk: Buffer) => collect(chunk, "stderr"));
|
|
40
65
|
child.on("error", (error) => {
|
|
41
66
|
stderr += error.message;
|
|
42
67
|
});
|
|
43
68
|
child.on("close", (code) => {
|
|
44
69
|
clearTimeout(timer);
|
|
45
|
-
|
|
70
|
+
clearTimeout(killTimer);
|
|
71
|
+
stdout += decoders.stdout.end();
|
|
72
|
+
stderr += decoders.stderr.end();
|
|
73
|
+
if (outputExceeded) stderr = `Command output exceeded the 1 MiB limit.${stderr ? `\n${stderr}` : ""}`;
|
|
74
|
+
resolve({ code: outputExceeded ? null : code, stdout, stderr, timedOut });
|
|
46
75
|
});
|
|
47
76
|
if (options.input !== undefined) child.stdin?.end(options.input);
|
|
48
77
|
else child.stdin?.end();
|
package/server/reopen.ts
CHANGED
|
@@ -22,18 +22,24 @@ export class Reopener {
|
|
|
22
22
|
return this.cli.path;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/** `timedOut`: the command was stopped before the daemon answered, so the reload may still finish. */
|
|
26
|
+
async reopen(agentId: string): Promise<{ ok: true } | { ok: false; error: string; timedOut: boolean }> {
|
|
26
27
|
const cli = await this.locate();
|
|
27
|
-
if (!cli) return { ok: false, error: "The paseo command-line tool was not found on the daemon machine." };
|
|
28
|
+
if (!cli) return { ok: false, error: "The paseo command-line tool was not found on the daemon machine.", timedOut: false };
|
|
29
|
+
const args = ["agent", "reload", agentId, "--json", "--home", paseoHome()];
|
|
30
|
+
// Node refuses to execFile a .cmd/.bat without a shell (spawn EINVAL), so run it through cmd.exe.
|
|
31
|
+
const viaCmd = process.platform === "win32" && /\.(cmd|bat)$/i.test(cli);
|
|
32
|
+
const file = viaCmd ? (process.env.ComSpec ?? "cmd.exe") : cli;
|
|
33
|
+
const argv = viaCmd ? ["/d", "/s", "/c", `"${[cli, ...args].map((part) => `"${part}"`).join(" ")}"`] : args;
|
|
28
34
|
return new Promise((resolve) => {
|
|
29
35
|
execFile(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
{ timeout: 90_000, maxBuffer: 1024 * 1024, env: process.env },
|
|
36
|
+
file,
|
|
37
|
+
argv,
|
|
38
|
+
{ timeout: 90_000, maxBuffer: 1024 * 1024, env: process.env, windowsVerbatimArguments: viaCmd },
|
|
33
39
|
(error, _stdout, stderr) => {
|
|
34
40
|
if (!error) return resolve({ ok: true });
|
|
35
41
|
const detail = `${stderr || error.message}`.trim().split("\n").slice(-3).join(" ");
|
|
36
|
-
resolve({ ok: false, error: explainFailure(detail) });
|
|
42
|
+
resolve({ ok: false, error: explainFailure(detail), timedOut: error.killed === true });
|
|
37
43
|
},
|
|
38
44
|
);
|
|
39
45
|
});
|
|
@@ -56,16 +62,17 @@ async function isExecutable(path: string): Promise<boolean> {
|
|
|
56
62
|
}
|
|
57
63
|
}
|
|
58
64
|
|
|
59
|
-
async function findCli(): Promise<string | null> {
|
|
65
|
+
export async function findCli(exec: string = process.execPath): Promise<string | null> {
|
|
60
66
|
const candidates: string[] = [];
|
|
61
67
|
const executable = process.platform === "win32" ? "paseo.cmd" : "paseo";
|
|
62
68
|
|
|
63
69
|
// The daemon (and this subprocess) usually run inside the desktop app bundle, which ships the CLI.
|
|
64
|
-
const exec = process.execPath;
|
|
65
70
|
const appContents = exec.match(/^(.*?\.app\/Contents)\//)?.[1];
|
|
66
71
|
if (appContents) candidates.push(join(appContents, "Resources", "bin", "paseo"));
|
|
67
72
|
const resources = findAncestor(exec, "resources");
|
|
68
73
|
if (resources) candidates.push(join(resources, "bin", executable));
|
|
74
|
+
// The Windows desktop app keeps `resources/` beside Paseo.exe, not above it.
|
|
75
|
+
candidates.push(join(dirname(exec), "resources", "bin", executable));
|
|
69
76
|
|
|
70
77
|
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
|
|
71
78
|
if (directory) candidates.push(join(directory, executable));
|
package/server/service.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { readdir } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
|
5
4
|
import type {
|
|
6
5
|
PluginHookContext,
|
|
7
6
|
PluginLifecycleEvents,
|
|
@@ -22,6 +21,7 @@ import type { RedeemResult, ReopenSummary } from "../shared/rpc";
|
|
|
22
21
|
import { SWITCH_ROW_KIND, SWITCH_ROW_VERSION, type SwitchRow } from "../shared/timeline";
|
|
23
22
|
import {
|
|
24
23
|
applyEnv,
|
|
24
|
+
type AgentTimelineItem,
|
|
25
25
|
type FamilyAdapter,
|
|
26
26
|
type Identity,
|
|
27
27
|
type LimitHit,
|
|
@@ -1049,9 +1049,20 @@ export class Service {
|
|
|
1049
1049
|
}
|
|
1050
1050
|
return "closed";
|
|
1051
1051
|
}
|
|
1052
|
+
const before = (await this.store.read()).sessions[agentId];
|
|
1052
1053
|
const result = await this.reopener.reopen(agentId);
|
|
1053
1054
|
if (!result.ok) {
|
|
1054
1055
|
console.warn(`[ZeroSub] could not reopen ${agentId}: ${result.error}`);
|
|
1056
|
+
// Paseo asks for the new session's environment before it closes the old one, so a failed reload
|
|
1057
|
+
// has still recorded a session that never opened. One that ran out of time may yet open.
|
|
1058
|
+
if (!result.timedOut) {
|
|
1059
|
+
await this.store.update((draft) => {
|
|
1060
|
+
const recorded = draft.sessions[agentId];
|
|
1061
|
+
if (!recorded || recorded.openedAt === before?.openedAt) return;
|
|
1062
|
+
if (before) draft.sessions[agentId] = before;
|
|
1063
|
+
else delete draft.sessions[agentId];
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1055
1066
|
return "failed";
|
|
1056
1067
|
}
|
|
1057
1068
|
return "reopened";
|