@kapybara/zerosub 1.2.1 → 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/claude.ts +15 -5
- package/server/codex.ts +77 -15
- package/server/process.ts +34 -5
- package/server/reopen.ts +11 -5
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/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/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
|
@@ -26,11 +26,16 @@ export class Reopener {
|
|
|
26
26
|
async reopen(agentId: string): Promise<{ ok: true } | { ok: false; error: string; timedOut: boolean }> {
|
|
27
27
|
const cli = await this.locate();
|
|
28
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;
|
|
29
34
|
return new Promise((resolve) => {
|
|
30
35
|
execFile(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
{ 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 },
|
|
34
39
|
(error, _stdout, stderr) => {
|
|
35
40
|
if (!error) return resolve({ ok: true });
|
|
36
41
|
const detail = `${stderr || error.message}`.trim().split("\n").slice(-3).join(" ");
|
|
@@ -57,16 +62,17 @@ async function isExecutable(path: string): Promise<boolean> {
|
|
|
57
62
|
}
|
|
58
63
|
}
|
|
59
64
|
|
|
60
|
-
async function findCli(): Promise<string | null> {
|
|
65
|
+
export async function findCli(exec: string = process.execPath): Promise<string | null> {
|
|
61
66
|
const candidates: string[] = [];
|
|
62
67
|
const executable = process.platform === "win32" ? "paseo.cmd" : "paseo";
|
|
63
68
|
|
|
64
69
|
// The daemon (and this subprocess) usually run inside the desktop app bundle, which ships the CLI.
|
|
65
|
-
const exec = process.execPath;
|
|
66
70
|
const appContents = exec.match(/^(.*?\.app\/Contents)\//)?.[1];
|
|
67
71
|
if (appContents) candidates.push(join(appContents, "Resources", "bin", "paseo"));
|
|
68
72
|
const resources = findAncestor(exec, "resources");
|
|
69
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));
|
|
70
76
|
|
|
71
77
|
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
|
|
72
78
|
if (directory) candidates.push(join(directory, executable));
|