@kapybara/zerosub 1.0.0
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/LICENSE +21 -0
- package/README.md +152 -0
- package/client/accounts-surface.tsx +592 -0
- package/client/add-account.tsx +351 -0
- package/client/commands.ts +112 -0
- package/client/fork-confirm.tsx +57 -0
- package/client/pills.ts +251 -0
- package/client/reset-confirm.tsx +138 -0
- package/client/settings-screen.tsx +120 -0
- package/client/store.ts +139 -0
- package/client/switch-row.tsx +103 -0
- package/client/ui.tsx +231 -0
- package/index.client.tsx +39 -0
- package/index.server.ts +91 -0
- package/package.json +58 -0
- package/paseo-plugin.json +7 -0
- package/server/adapter.ts +126 -0
- package/server/binaries.ts +63 -0
- package/server/claude-resets.ts +192 -0
- package/server/claude.ts +478 -0
- package/server/codex.ts +459 -0
- package/server/families.ts +78 -0
- package/server/handoff.ts +175 -0
- package/server/homes.ts +352 -0
- package/server/json-file.ts +39 -0
- package/server/limits.ts +213 -0
- package/server/machine.ts +17 -0
- package/server/modes.ts +34 -0
- package/server/paths.ts +37 -0
- package/server/process.ts +66 -0
- package/server/reopen.ts +95 -0
- package/server/routing.ts +131 -0
- package/server/service.ts +1692 -0
- package/server/state.ts +177 -0
- package/server/switch-guard.ts +28 -0
- package/server/usage.ts +68 -0
- package/shared/format.ts +99 -0
- package/shared/model.ts +150 -0
- package/shared/preferences.ts +32 -0
- package/shared/rpc.ts +120 -0
- package/shared/timeline.ts +42 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
|
3
|
+
import type { PluginHookContext } from "@getpaseo/plugin/server";
|
|
4
|
+
|
|
5
|
+
type PaseoApi = PluginHookContext["paseo"];
|
|
6
|
+
|
|
7
|
+
/** Label on a continuation agent naming the agent it carries on from. */
|
|
8
|
+
export const CONTINUED_FROM_LABEL = "zerosub.continued-from";
|
|
9
|
+
|
|
10
|
+
const MAX_TRANSCRIPT = 40_000;
|
|
11
|
+
const MAX_FIRST_MESSAGE = 6_000;
|
|
12
|
+
|
|
13
|
+
function clip(text: string, max: number): string {
|
|
14
|
+
const trimmed = text.trim();
|
|
15
|
+
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}…`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function describeTool(item: Extract<AgentTimelineItem, { type: "tool_call" }>): string {
|
|
19
|
+
const detail = item.detail;
|
|
20
|
+
const failed = item.status === "failed" ? " (failed)" : "";
|
|
21
|
+
switch (detail.type) {
|
|
22
|
+
case "shell": {
|
|
23
|
+
const exit = detail.exitCode === undefined || detail.exitCode === null ? "" : ` → exit ${detail.exitCode}`;
|
|
24
|
+
return `[ran \`${clip(detail.command, 200)}\`${exit}]`;
|
|
25
|
+
}
|
|
26
|
+
case "read":
|
|
27
|
+
return `[read ${detail.filePath}]`;
|
|
28
|
+
case "edit":
|
|
29
|
+
return `[edited ${detail.filePath}${failed}]`;
|
|
30
|
+
case "write":
|
|
31
|
+
return `[wrote ${detail.filePath}${failed}]`;
|
|
32
|
+
case "search":
|
|
33
|
+
return `[searched: ${clip(detail.query, 120)}]`;
|
|
34
|
+
case "plan":
|
|
35
|
+
return `[plan]\n${clip(detail.text, 2_000)}`;
|
|
36
|
+
default:
|
|
37
|
+
return `[${item.name}${failed}]`;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A readable account of what happened in a conversation, for a fresh agent to pick up from.
|
|
43
|
+
* Keeps the opening request and the most recent history; drops reasoning and tool output.
|
|
44
|
+
*/
|
|
45
|
+
export function buildTranscript(timeline: readonly AgentTimelineItem[], max = MAX_TRANSCRIPT): string {
|
|
46
|
+
const lines: string[] = [];
|
|
47
|
+
let firstUser: string | null = null;
|
|
48
|
+
let todos: string | null = null;
|
|
49
|
+
for (const item of timeline) {
|
|
50
|
+
switch (item.type) {
|
|
51
|
+
case "user_message":
|
|
52
|
+
if (firstUser === null) firstUser = clip(item.text, MAX_FIRST_MESSAGE);
|
|
53
|
+
lines.push(`User: ${item.text.trim()}`);
|
|
54
|
+
break;
|
|
55
|
+
case "assistant_message":
|
|
56
|
+
if (item.text.trim()) lines.push(`Assistant: ${item.text.trim()}`);
|
|
57
|
+
break;
|
|
58
|
+
case "tool_call":
|
|
59
|
+
lines.push(describeTool(item));
|
|
60
|
+
break;
|
|
61
|
+
case "todo":
|
|
62
|
+
todos = item.items.map((task) => `- [${task.completed ? "x" : " "}] ${task.text}`).join("\n");
|
|
63
|
+
break;
|
|
64
|
+
default:
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
let body = lines.join("\n\n");
|
|
69
|
+
if (body.length > max) {
|
|
70
|
+
const tail = body.slice(body.length - max);
|
|
71
|
+
const start = tail.indexOf("\n\n");
|
|
72
|
+
body = `${firstUser ? `User (original request): ${firstUser}\n\n` : ""}[… earlier conversation omitted …]\n\n${
|
|
73
|
+
start >= 0 ? tail.slice(start + 2) : tail
|
|
74
|
+
}`;
|
|
75
|
+
}
|
|
76
|
+
return todos ? `${body}\n\nTask list at the time it stopped:\n${todos}` : body;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function continuationPrompt(transcript: string, why: string, previous = "Codex"): string {
|
|
80
|
+
return [
|
|
81
|
+
`This task is continuing from an earlier ${previous} session that stopped because ${why}.`,
|
|
82
|
+
"The working directory already contains every change that session made. Here is its conversation, oldest first:",
|
|
83
|
+
"",
|
|
84
|
+
"<previous-session>",
|
|
85
|
+
transcript,
|
|
86
|
+
"</previous-session>",
|
|
87
|
+
"",
|
|
88
|
+
"Pick up exactly where it left off. Check the current state of the files before changing anything, and don't redo finished work.",
|
|
89
|
+
].join("\n");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function defaultModel(paseo: PaseoApi, provider: string): Promise<string | null> {
|
|
93
|
+
try {
|
|
94
|
+
const { models } = await paseo.providers.listModels(provider);
|
|
95
|
+
return (models?.find((entry) => entry.isDefault) ?? models?.[0])?.id ?? null;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface Continuation {
|
|
102
|
+
agentId: string;
|
|
103
|
+
title: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Another provider to continue on, instead of the source agent's own. */
|
|
107
|
+
export interface ContinuationTarget {
|
|
108
|
+
/** Paseo provider ID, e.g. `codex`. */
|
|
109
|
+
provider: string;
|
|
110
|
+
/** Its name for people, used in the new agent's title, e.g. `ChatGPT`. */
|
|
111
|
+
label: string;
|
|
112
|
+
/** A mode no more permissive than the source agent's. */
|
|
113
|
+
modeId: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Starts a new agent in the same workspace, pre-bound to another account, and hands it the
|
|
118
|
+
* conversation so far. Used where a thread cannot move between accounts (Codex encrypts its
|
|
119
|
+
* reasoning per ChatGPT account, so the old thread would be rejected by the new one), and to carry
|
|
120
|
+
* work over to the other provider when every account of one is out.
|
|
121
|
+
*/
|
|
122
|
+
export async function continueInNewAgent(options: {
|
|
123
|
+
paseo: PaseoApi;
|
|
124
|
+
sourceAgentId: string;
|
|
125
|
+
timeline?: readonly AgentTimelineItem[];
|
|
126
|
+
why: string;
|
|
127
|
+
bind(agentId: string): Promise<void>;
|
|
128
|
+
target?: ContinuationTarget;
|
|
129
|
+
/** What to call the session that stopped, e.g. `Claude Code`. */
|
|
130
|
+
previous?: string;
|
|
131
|
+
}): Promise<Continuation> {
|
|
132
|
+
const { paseo, sourceAgentId } = options;
|
|
133
|
+
const refreshed = await paseo.agents.ref(sourceAgentId).refresh();
|
|
134
|
+
const source = refreshed?.agent;
|
|
135
|
+
if (!source) throw new Error("The original agent is no longer available.");
|
|
136
|
+
|
|
137
|
+
let timeline = options.timeline;
|
|
138
|
+
if (!timeline) {
|
|
139
|
+
const page = await paseo.agents.ref(sourceAgentId).timeline.refetch({ direction: "tail", limit: 500 });
|
|
140
|
+
timeline = page.entries.map((entry) => entry.item);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The SDK needs "provider/model"; an agent created with the provider default may not record one.
|
|
144
|
+
// Another provider's agent starts on that provider's default model.
|
|
145
|
+
const { target } = options;
|
|
146
|
+
const provider = target?.provider ?? source.provider;
|
|
147
|
+
const model = target
|
|
148
|
+
? await defaultModel(paseo, provider)
|
|
149
|
+
: (source.model ?? source.runtimeInfo?.model ?? (await defaultModel(paseo, provider)));
|
|
150
|
+
if (!model) throw new Error(`Couldn't tell which ${provider} model to use for the new agent.`);
|
|
151
|
+
|
|
152
|
+
const agentId = randomUUID();
|
|
153
|
+
await options.bind(agentId);
|
|
154
|
+
const title = target
|
|
155
|
+
? `${source.title?.trim() || "Task"} (continued on ${target.label})`
|
|
156
|
+
: `${source.title?.trim() || "Codex task"} (continued)`;
|
|
157
|
+
// Modes and thinking options are provider-specific: only carry them over within one provider.
|
|
158
|
+
const config = target
|
|
159
|
+
? { provider: `${provider}/${model}`, modeId: target.modeId }
|
|
160
|
+
: {
|
|
161
|
+
provider: `${provider}/${model}`,
|
|
162
|
+
...(source.currentModeId ? { modeId: source.currentModeId } : {}),
|
|
163
|
+
...(source.thinkingOptionId ? { thinkingOptionId: source.thinkingOptionId } : {}),
|
|
164
|
+
};
|
|
165
|
+
const request = {
|
|
166
|
+
agentId,
|
|
167
|
+
config,
|
|
168
|
+
title,
|
|
169
|
+
prompt: continuationPrompt(buildTranscript(timeline), options.why, options.previous),
|
|
170
|
+
labels: { [CONTINUED_FROM_LABEL]: sourceAgentId },
|
|
171
|
+
};
|
|
172
|
+
if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
|
|
173
|
+
else await paseo.agents.create({ ...request, cwd: source.cwd });
|
|
174
|
+
return { agentId, title };
|
|
175
|
+
}
|
package/server/homes.ts
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
import { homesDir, mainClaudeDir, mainClaudeGlobalConfig, mainCodexHome } from "./paths";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A managed account home is a real directory holding that account's own credentials and account
|
|
8
|
+
* caches, with every other entry symlinked to the CLI's main home. Settings, skills, plugins, MCP
|
|
9
|
+
* config and — crucially — conversation history stay shared, so an agent can move between accounts
|
|
10
|
+
* and Paseo still finds its transcript.
|
|
11
|
+
*/
|
|
12
|
+
interface OverlaySpec {
|
|
13
|
+
main: string;
|
|
14
|
+
/** Directories created in main up front so they are shared rather than created per account. */
|
|
15
|
+
shareDirs: readonly string[];
|
|
16
|
+
isPrivate(name: string): boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const SYNC_TTL_MS = 30_000;
|
|
20
|
+
const lastSync = new Map<string, number>();
|
|
21
|
+
|
|
22
|
+
async function exists(path: string): Promise<boolean> {
|
|
23
|
+
try {
|
|
24
|
+
await stat(path);
|
|
25
|
+
return true;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function syncOverlay(home: string, spec: OverlaySpec): Promise<void> {
|
|
32
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
33
|
+
await mkdir(spec.main, { recursive: true, mode: 0o700 });
|
|
34
|
+
for (const directory of spec.shareDirs) await mkdir(join(spec.main, directory), { recursive: true });
|
|
35
|
+
|
|
36
|
+
for (const name of await readdir(spec.main)) {
|
|
37
|
+
if (name === ".DS_Store" || spec.isPrivate(name)) continue;
|
|
38
|
+
const link = join(home, name);
|
|
39
|
+
// Point at the real file: Claude Code's atomic writer follows exactly one symlink, so linking to
|
|
40
|
+
// a dotfiles symlink in main would make it replace the user's symlink with a plain file.
|
|
41
|
+
const target = await realpath(join(spec.main, name)).catch(() => null);
|
|
42
|
+
if (!target) continue;
|
|
43
|
+
const current = await lstat(link).catch(() => null);
|
|
44
|
+
if (current) {
|
|
45
|
+
if (!current.isSymbolicLink()) continue; // Created here by the CLI; leave it alone.
|
|
46
|
+
if ((await readlink(link)) === target) continue;
|
|
47
|
+
await unlink(link);
|
|
48
|
+
}
|
|
49
|
+
const targetStat = await stat(target).catch(() => null);
|
|
50
|
+
if (!targetStat) continue;
|
|
51
|
+
try {
|
|
52
|
+
await symlink(target, link, process.platform === "win32" && targetStat.isDirectory() ? "junction" : undefined);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.warn(`[ZeroSub] could not share ${name} with ${home}`, error instanceof Error ? error.message : error);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Drop links whose target disappeared from main.
|
|
59
|
+
for (const name of await readdir(home)) {
|
|
60
|
+
const link = join(home, name);
|
|
61
|
+
const current = await lstat(link).catch(() => null);
|
|
62
|
+
if (current?.isSymbolicLink() && !(await exists(link))) await unlink(link).catch(() => undefined);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Deletes a managed home. Its top level holds symlinks into the user's real CLI home, so those are
|
|
68
|
+
* unlinked first; nothing outside ZeroSub's own directory is ever followed or removed.
|
|
69
|
+
*/
|
|
70
|
+
export async function removeHome(home: string): Promise<void> {
|
|
71
|
+
if (!home.startsWith(homesDir() + sep)) return;
|
|
72
|
+
for (const name of await readdir(home).catch(() => [] as string[])) {
|
|
73
|
+
const path = join(home, name);
|
|
74
|
+
const entry = await lstat(path).catch(() => null);
|
|
75
|
+
if (entry?.isSymbolicLink()) await unlink(path).catch(() => undefined);
|
|
76
|
+
}
|
|
77
|
+
await rm(home, { recursive: true, force: true });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Atomic-write leftovers and scratch files: never worth sharing. */
|
|
81
|
+
function isTemporary(name: string): boolean {
|
|
82
|
+
return name.startsWith("..") || name.startsWith(".tmp") || /\.tmp(?:$|[-.])/.test(name);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// --------------------------------------------------------------------------- Claude
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Per-account entries, from Claude Code's own split between configuration and state: credentials,
|
|
89
|
+
* the global config (it holds `oauthAccount`), account caches, org policy, telemetry and locks.
|
|
90
|
+
*/
|
|
91
|
+
const CLAUDE_PRIVATE = new Set([
|
|
92
|
+
".credentials.json",
|
|
93
|
+
".config.json",
|
|
94
|
+
".oauth_refresh.lock",
|
|
95
|
+
".storage-write",
|
|
96
|
+
".session_ingress_token",
|
|
97
|
+
".update.lock",
|
|
98
|
+
".cc-writes",
|
|
99
|
+
"backups",
|
|
100
|
+
"statsig",
|
|
101
|
+
"telemetry",
|
|
102
|
+
"cache",
|
|
103
|
+
"usage-data",
|
|
104
|
+
"stats-cache.json",
|
|
105
|
+
"logs",
|
|
106
|
+
"debug",
|
|
107
|
+
"traces",
|
|
108
|
+
"startup-perf",
|
|
109
|
+
"hfi-auth.json",
|
|
110
|
+
"mcp-needs-auth-cache.json",
|
|
111
|
+
"mcp-discovery-cache",
|
|
112
|
+
"gh-pr-status-cache.json",
|
|
113
|
+
"jobs",
|
|
114
|
+
"sessions",
|
|
115
|
+
"teams",
|
|
116
|
+
"ide",
|
|
117
|
+
"local",
|
|
118
|
+
"ccr",
|
|
119
|
+
"bridge-spawn",
|
|
120
|
+
"active-time.json",
|
|
121
|
+
"server-sessions.json",
|
|
122
|
+
"server.lock",
|
|
123
|
+
"computer-use.lock",
|
|
124
|
+
"api-dumps",
|
|
125
|
+
"dump-prompts",
|
|
126
|
+
"feedback",
|
|
127
|
+
"feedback-bundles",
|
|
128
|
+
"antproto.json",
|
|
129
|
+
"uploads",
|
|
130
|
+
"shares",
|
|
131
|
+
"state",
|
|
132
|
+
"chrome",
|
|
133
|
+
"downloads",
|
|
134
|
+
"storage-v2",
|
|
135
|
+
"systemd",
|
|
136
|
+
"seed-admin",
|
|
137
|
+
"scratch",
|
|
138
|
+
"remote",
|
|
139
|
+
"local-settings",
|
|
140
|
+
"project-settings",
|
|
141
|
+
"file-transfers",
|
|
142
|
+
"mcp-skill-archives",
|
|
143
|
+
"loop.md",
|
|
144
|
+
]);
|
|
145
|
+
|
|
146
|
+
function claudePrivate(name: string): boolean {
|
|
147
|
+
return (
|
|
148
|
+
CLAUDE_PRIVATE.has(name) ||
|
|
149
|
+
isTemporary(name) ||
|
|
150
|
+
name.startsWith(".claude.json") ||
|
|
151
|
+
name.startsWith("remote-settings") ||
|
|
152
|
+
name.startsWith("policy-limits") ||
|
|
153
|
+
name.startsWith("daemon") ||
|
|
154
|
+
name.endsWith(".lock")
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Account identity and account-scoped caches in `.claude.json`; never copied between accounts. */
|
|
159
|
+
function isAccountKey(key: string): boolean {
|
|
160
|
+
return (
|
|
161
|
+
key === "oauthAccount" ||
|
|
162
|
+
key === "primaryApiKey" ||
|
|
163
|
+
key === "customApiKeyResponses" ||
|
|
164
|
+
key === "userID" ||
|
|
165
|
+
key === "anonymousId" ||
|
|
166
|
+
/cache/i.test(key) ||
|
|
167
|
+
/subscription/i.test(key)
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Per-project MCP and trust settings kept in step with the main login. */
|
|
172
|
+
const SHARED_PROJECT_KEYS = [
|
|
173
|
+
"mcpServers",
|
|
174
|
+
"enabledMcpjsonServers",
|
|
175
|
+
"disabledMcpjsonServers",
|
|
176
|
+
"enableAllProjectMcpServers",
|
|
177
|
+
"mcpContextUris",
|
|
178
|
+
"allowedTools",
|
|
179
|
+
"hasTrustDialogAccepted",
|
|
180
|
+
] as const;
|
|
181
|
+
|
|
182
|
+
type Json = Record<string, unknown>;
|
|
183
|
+
|
|
184
|
+
function isObject(value: unknown): value is Json {
|
|
185
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Brings main's value into an account's copy without discarding what the account added itself:
|
|
190
|
+
* objects merge (main wins; entries main removed since the last sync are dropped), lists union,
|
|
191
|
+
* and a `true` from main is adopted.
|
|
192
|
+
*/
|
|
193
|
+
export function mergeShared(current: unknown, main: unknown, removedKeys: ReadonlySet<string> = new Set()): unknown {
|
|
194
|
+
if (isObject(main)) {
|
|
195
|
+
const merged: Json = isObject(current) ? { ...current } : {};
|
|
196
|
+
for (const key of removedKeys) if (!(key in main)) delete merged[key];
|
|
197
|
+
return Object.assign(merged, main);
|
|
198
|
+
}
|
|
199
|
+
if (Array.isArray(main)) {
|
|
200
|
+
const union = Array.isArray(current) ? [...current] : [];
|
|
201
|
+
for (const entry of main) if (!union.some((existing) => JSON.stringify(existing) === JSON.stringify(entry))) union.push(entry);
|
|
202
|
+
return union;
|
|
203
|
+
}
|
|
204
|
+
if (typeof main === "boolean") return main || current === true;
|
|
205
|
+
return main === undefined ? current : main;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function readJsonObject(path: string): Promise<Record<string, unknown> | null> {
|
|
209
|
+
try {
|
|
210
|
+
const value = JSON.parse(await readFile(path, "utf8")) as unknown;
|
|
211
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function writeJsonAtomically(path: string, value: unknown): Promise<void> {
|
|
218
|
+
const temporary = `${path}.zerosub.${randomBytes(4).toString("hex")}.tmp`;
|
|
219
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
220
|
+
await rename(temporary, path);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Claude Code guards `.claude.json` writes with a `<file>.lock` directory; take it too. */
|
|
224
|
+
async function withClaudeConfigLock(file: string, action: () => Promise<void>): Promise<boolean> {
|
|
225
|
+
const lock = `${file}.lock`;
|
|
226
|
+
try {
|
|
227
|
+
await mkdir(lock);
|
|
228
|
+
} catch {
|
|
229
|
+
const held = await stat(lock).catch(() => null);
|
|
230
|
+
if (held && Date.now() - held.mtimeMs < 10_000) return false;
|
|
231
|
+
await rmdir(lock).catch(() => undefined);
|
|
232
|
+
try {
|
|
233
|
+
await mkdir(lock);
|
|
234
|
+
} catch {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
await action();
|
|
240
|
+
return true;
|
|
241
|
+
} finally {
|
|
242
|
+
await rmdir(lock).catch(() => undefined);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const lastMcpSync = new Map<string, number>();
|
|
247
|
+
/** MCP server names each home last received from main, so removals in main propagate. */
|
|
248
|
+
const lastMcpKeys = new Map<string, Set<string>>();
|
|
249
|
+
|
|
250
|
+
async function syncClaudeGlobalConfig(home: string): Promise<void> {
|
|
251
|
+
const source = mainClaudeGlobalConfig();
|
|
252
|
+
const target = join(home, ".claude.json");
|
|
253
|
+
const sourceStat = await stat(source).catch(() => null);
|
|
254
|
+
const main = sourceStat ? await readJsonObject(source) : null;
|
|
255
|
+
const targetExists = await exists(target);
|
|
256
|
+
|
|
257
|
+
if (!targetExists) {
|
|
258
|
+
// Seed a new account with the user's preferences, MCP servers and project trust — not identity.
|
|
259
|
+
const seed: Record<string, unknown> = {};
|
|
260
|
+
for (const [key, value] of Object.entries(main ?? {})) if (!isAccountKey(key)) seed[key] = value;
|
|
261
|
+
seed.hasCompletedOnboarding = true;
|
|
262
|
+
await writeJsonAtomically(target, seed);
|
|
263
|
+
lastMcpSync.set(home, sourceStat?.mtimeMs ?? 0);
|
|
264
|
+
lastMcpKeys.set(home, new Set(isObject(main?.mcpServers) ? Object.keys(main.mcpServers) : []));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (!main || !sourceStat || lastMcpSync.get(home) === sourceStat.mtimeMs) return;
|
|
268
|
+
|
|
269
|
+
const mainServers = isObject(main.mcpServers) ? main.mcpServers : {};
|
|
270
|
+
const synced = await withClaudeConfigLock(target, async () => {
|
|
271
|
+
const current = (await readJsonObject(target)) ?? {};
|
|
272
|
+
const next: Json = { ...current };
|
|
273
|
+
next.mcpServers = mergeShared(current.mcpServers, mainServers, lastMcpKeys.get(home));
|
|
274
|
+
const projects: Json = isObject(current.projects) ? { ...current.projects } : {};
|
|
275
|
+
for (const [path, settings] of Object.entries(isObject(main.projects) ? main.projects : {})) {
|
|
276
|
+
if (!isObject(settings)) continue;
|
|
277
|
+
const merged: Json = isObject(projects[path]) ? { ...(projects[path] as Json) } : {};
|
|
278
|
+
for (const key of SHARED_PROJECT_KEYS) if (key in settings) merged[key] = mergeShared(merged[key], settings[key]);
|
|
279
|
+
projects[path] = merged;
|
|
280
|
+
}
|
|
281
|
+
next.projects = projects;
|
|
282
|
+
await writeJsonAtomically(target, next);
|
|
283
|
+
});
|
|
284
|
+
if (synced) {
|
|
285
|
+
lastMcpSync.set(home, sourceStat.mtimeMs);
|
|
286
|
+
lastMcpKeys.set(home, new Set(Object.keys(mainServers)));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export async function prepareClaudeHome(home: string, force = false): Promise<void> {
|
|
291
|
+
const last = lastSync.get(home);
|
|
292
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
293
|
+
await syncOverlay(home, {
|
|
294
|
+
main: mainClaudeDir(),
|
|
295
|
+
shareDirs: ["projects", "file-history", "todos", "plans", "tasks", "session-env", "shell-snapshots"],
|
|
296
|
+
isPrivate: claudePrivate,
|
|
297
|
+
});
|
|
298
|
+
await syncClaudeGlobalConfig(home);
|
|
299
|
+
lastSync.set(home, Date.now());
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// --------------------------------------------------------------------------- Codex
|
|
303
|
+
|
|
304
|
+
/** Per-account entries in a Codex home: credentials and caches keyed to the ChatGPT account. */
|
|
305
|
+
const CODEX_PRIVATE = new Set([
|
|
306
|
+
"auth.json",
|
|
307
|
+
"secrets",
|
|
308
|
+
"models_cache.json",
|
|
309
|
+
"cloud-config-bundle-cache.json",
|
|
310
|
+
"cache",
|
|
311
|
+
"plugins",
|
|
312
|
+
".tmp",
|
|
313
|
+
"tmp",
|
|
314
|
+
"log",
|
|
315
|
+
"thread-writer-locks",
|
|
316
|
+
"mcp-oauth-locks",
|
|
317
|
+
"sqlite",
|
|
318
|
+
"ipc",
|
|
319
|
+
".codex-global-state.json",
|
|
320
|
+
"computer-use",
|
|
321
|
+
"browser",
|
|
322
|
+
]);
|
|
323
|
+
|
|
324
|
+
function codexPrivate(name: string): boolean {
|
|
325
|
+
return (
|
|
326
|
+
CODEX_PRIVATE.has(name) ||
|
|
327
|
+
isTemporary(name) ||
|
|
328
|
+
name.includes("codex-global-state") ||
|
|
329
|
+
/\.sqlite(?:-wal|-shm|-journal)?$/.test(name) ||
|
|
330
|
+
name.endsWith(".lock")
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export async function prepareCodexHome(home: string, force = false): Promise<void> {
|
|
335
|
+
const last = lastSync.get(home);
|
|
336
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
337
|
+
await syncOverlay(home, {
|
|
338
|
+
main: mainCodexHome(),
|
|
339
|
+
shareDirs: ["sessions", "archived_sessions"],
|
|
340
|
+
isPrivate: codexPrivate,
|
|
341
|
+
});
|
|
342
|
+
lastSync.set(home, Date.now());
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Where the main Codex home keeps its SQLite state; managed homes point there so thread metadata is shared. */
|
|
346
|
+
export async function codexSqliteHome(): Promise<string | null> {
|
|
347
|
+
if (process.env.CODEX_SQLITE_HOME) return process.env.CODEX_SQLITE_HOME;
|
|
348
|
+
const config = await readFile(join(mainCodexHome(), "config.toml"), "utf8").catch(() => "");
|
|
349
|
+
// A `sqlite_home` in the (shared) config.toml already applies to every account.
|
|
350
|
+
if (/^\s*sqlite_home\s*=/m.test(config)) return null;
|
|
351
|
+
return mainCodexHome();
|
|
352
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export async function readJson(path: string): Promise<unknown | undefined> {
|
|
6
|
+
let raw: string;
|
|
7
|
+
try {
|
|
8
|
+
raw = await readFile(path, "utf8");
|
|
9
|
+
} catch (error) {
|
|
10
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
11
|
+
throw error;
|
|
12
|
+
}
|
|
13
|
+
return JSON.parse(raw) as unknown;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Writes through a sibling temp file and rename, so readers never see a partial file. */
|
|
17
|
+
export async function writeJsonAtomic(path: string, value: unknown, mode = 0o600): Promise<void> {
|
|
18
|
+
const directory = dirname(path);
|
|
19
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
20
|
+
const temporary = join(directory, `.${randomBytes(6).toString("hex")}.tmp`);
|
|
21
|
+
try {
|
|
22
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
23
|
+
await rename(temporary, path);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
await rm(temporary, { force: true });
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Runs async sections one at a time, in call order. */
|
|
31
|
+
export class Mutex {
|
|
32
|
+
private tail: Promise<unknown> = Promise.resolve();
|
|
33
|
+
|
|
34
|
+
run<T>(section: () => Promise<T>): Promise<T> {
|
|
35
|
+
const result = this.tail.then(section, section);
|
|
36
|
+
this.tail = result.catch(() => undefined);
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
}
|