@prestyj/cli 5.38.0 → 5.39.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/README.md +92 -42
- package/dist/app-sidecar/fleet-adapter.d.ts +138 -0
- package/dist/app-sidecar/fleet-adapter.js +356 -0
- package/dist/app-sidecar/fleet-adapter.js.map +1 -0
- package/dist/app-sidecar/fleet-routes.d.ts +4 -0
- package/dist/app-sidecar/fleet-routes.js +109 -0
- package/dist/app-sidecar/fleet-routes.js.map +1 -0
- package/dist/app-sidecar/goal-routes.d.ts +20 -0
- package/dist/app-sidecar/goal-routes.js +42 -1
- package/dist/app-sidecar/goal-routes.js.map +1 -1
- package/dist/app-sidecar.js +5 -0
- package/dist/app-sidecar.js.map +1 -1
- package/dist/cli/cloud.d.ts +45 -0
- package/dist/cli/cloud.js +241 -0
- package/dist/cli/cloud.js.map +1 -0
- package/dist/cli/command-routing.d.ts +3 -2
- package/dist/cli/command-routing.js +24 -3
- package/dist/cli/command-routing.js.map +1 -1
- package/dist/cli/fleet.d.ts +19 -3
- package/dist/cli/fleet.js +107 -33
- package/dist/cli/fleet.js.map +1 -1
- package/dist/cli/goals.d.ts +11 -0
- package/dist/cli/goals.js +115 -0
- package/dist/cli/goals.js.map +1 -0
- package/dist/cli/node.d.ts +18 -1
- package/dist/cli/node.js +303 -33
- package/dist/cli/node.js.map +1 -1
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.js +18 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/cloud/claude.d.ts +128 -0
- package/dist/core/cloud/claude.js +836 -0
- package/dist/core/cloud/claude.js.map +1 -0
- package/dist/core/cloud/cloud-agent.d.ts +136 -0
- package/dist/core/cloud/cloud-agent.js +783 -0
- package/dist/core/cloud/cloud-agent.js.map +1 -0
- package/dist/core/cloud/codex.d.ts +154 -0
- package/dist/core/cloud/codex.js +622 -0
- package/dist/core/cloud/codex.js.map +1 -0
- package/dist/core/cloud/config.d.ts +69 -0
- package/dist/core/cloud/config.js +86 -0
- package/dist/core/cloud/config.js.map +1 -0
- package/dist/core/cloud/git.d.ts +15 -0
- package/dist/core/cloud/git.js +33 -0
- package/dist/core/cloud/git.js.map +1 -0
- package/dist/core/cloud/registry.d.ts +13 -0
- package/dist/core/cloud/registry.js +64 -0
- package/dist/core/cloud/registry.js.map +1 -0
- package/dist/core/cloud/runner.d.ts +46 -0
- package/dist/core/cloud/runner.js +99 -0
- package/dist/core/cloud/runner.js.map +1 -0
- package/dist/core/cloud/snapshot.d.ts +23 -0
- package/dist/core/cloud/snapshot.js +98 -0
- package/dist/core/cloud/snapshot.js.map +1 -0
- package/dist/core/cloud/types.d.ts +139 -0
- package/dist/core/cloud/types.js +28 -0
- package/dist/core/cloud/types.js.map +1 -0
- package/dist/core/fleet/client.d.ts +106 -6
- package/dist/core/fleet/client.js +352 -20
- package/dist/core/fleet/client.js.map +1 -1
- package/dist/core/fleet/cloud-jobs.d.ts +59 -0
- package/dist/core/fleet/cloud-jobs.js +131 -0
- package/dist/core/fleet/cloud-jobs.js.map +1 -0
- package/dist/core/fleet/discovery.d.ts +2 -0
- package/dist/core/fleet/discovery.js +3 -1
- package/dist/core/fleet/discovery.js.map +1 -1
- package/dist/core/fleet/fleet-scheduler.d.ts +4 -0
- package/dist/core/fleet/fleet-scheduler.js +11 -1
- package/dist/core/fleet/fleet-scheduler.js.map +1 -1
- package/dist/core/fleet/git.d.ts +7 -0
- package/dist/core/fleet/git.js +22 -1
- package/dist/core/fleet/git.js.map +1 -1
- package/dist/core/fleet/machines.d.ts +112 -0
- package/dist/core/fleet/machines.js +219 -0
- package/dist/core/fleet/machines.js.map +1 -0
- package/dist/core/fleet/node/agents.d.ts +2 -0
- package/dist/core/fleet/node/agents.js +195 -9
- package/dist/core/fleet/node/agents.js.map +1 -1
- package/dist/core/fleet/node/config.d.ts +37 -3
- package/dist/core/fleet/node/config.js +201 -40
- package/dist/core/fleet/node/config.js.map +1 -1
- package/dist/core/fleet/node/context.d.ts +19 -1
- package/dist/core/fleet/node/docker.d.ts +13 -5
- package/dist/core/fleet/node/docker.js +132 -66
- package/dist/core/fleet/node/docker.js.map +1 -1
- package/dist/core/fleet/node/doctor.d.ts +29 -0
- package/dist/core/fleet/node/doctor.js +202 -0
- package/dist/core/fleet/node/doctor.js.map +1 -0
- package/dist/core/fleet/node/env.d.ts +7 -0
- package/dist/core/fleet/node/env.js +51 -0
- package/dist/core/fleet/node/env.js.map +1 -0
- package/dist/core/fleet/node/gc.d.ts +46 -0
- package/dist/core/fleet/node/gc.js +140 -0
- package/dist/core/fleet/node/gc.js.map +1 -0
- package/dist/core/fleet/node/goals.d.ts +43 -0
- package/dist/core/fleet/node/goals.js +418 -0
- package/dist/core/fleet/node/goals.js.map +1 -0
- package/dist/core/fleet/node/jobs.d.ts +37 -2
- package/dist/core/fleet/node/jobs.js +236 -15
- package/dist/core/fleet/node/jobs.js.map +1 -1
- package/dist/core/fleet/node/local-client.d.ts +9 -0
- package/dist/core/fleet/node/local-client.js +29 -0
- package/dist/core/fleet/node/local-client.js.map +1 -0
- package/dist/core/fleet/node/ops-routes.d.ts +15 -0
- package/dist/core/fleet/node/ops-routes.js +84 -0
- package/dist/core/fleet/node/ops-routes.js.map +1 -0
- package/dist/core/fleet/node/pair-code-route.d.ts +14 -0
- package/dist/core/fleet/node/pair-code-route.js +76 -0
- package/dist/core/fleet/node/pair-code-route.js.map +1 -0
- package/dist/core/fleet/node/secrets.d.ts +43 -0
- package/dist/core/fleet/node/secrets.js +184 -0
- package/dist/core/fleet/node/secrets.js.map +1 -0
- package/dist/core/fleet/node/server.d.ts +22 -1
- package/dist/core/fleet/node/server.js +210 -21
- package/dist/core/fleet/node/server.js.map +1 -1
- package/dist/core/fleet/node/state.d.ts +24 -1
- package/dist/core/fleet/node/state.js +12 -3
- package/dist/core/fleet/node/state.js.map +1 -1
- package/dist/core/fleet/node/tls.d.ts +17 -0
- package/dist/core/fleet/node/tls.js +49 -0
- package/dist/core/fleet/node/tls.js.map +1 -0
- package/dist/core/fleet/node/uninstall.d.ts +27 -0
- package/dist/core/fleet/node/uninstall.js +100 -0
- package/dist/core/fleet/node/uninstall.js.map +1 -0
- package/dist/core/fleet/node/update.d.ts +28 -0
- package/dist/core/fleet/node/update.js +62 -0
- package/dist/core/fleet/node/update.js.map +1 -0
- package/dist/core/fleet/node/workspace.d.ts +4 -0
- package/dist/core/fleet/node/workspace.js +38 -9
- package/dist/core/fleet/node/workspace.js.map +1 -1
- package/dist/core/fleet/node-load.d.ts +4 -0
- package/dist/core/fleet/node-load.js +62 -0
- package/dist/core/fleet/node-load.js.map +1 -0
- package/dist/core/fleet/project-config.d.ts +10 -0
- package/dist/core/fleet/project-config.js +39 -1
- package/dist/core/fleet/project-config.js.map +1 -1
- package/dist/core/fleet/prompt-hint.d.ts +11 -0
- package/dist/core/fleet/prompt-hint.js +47 -0
- package/dist/core/fleet/prompt-hint.js.map +1 -0
- package/dist/core/fleet/propose-config.d.ts +26 -0
- package/dist/core/fleet/propose-config.js +95 -0
- package/dist/core/fleet/propose-config.js.map +1 -0
- package/dist/core/fleet/protocol.d.ts +97 -1
- package/dist/core/fleet/protocol.js +10 -1
- package/dist/core/fleet/protocol.js.map +1 -1
- package/dist/core/fleet/registry.d.ts +12 -1
- package/dist/core/fleet/registry.js +39 -7
- package/dist/core/fleet/registry.js.map +1 -1
- package/dist/core/fleet/remote-agent-nodes.d.ts +56 -8
- package/dist/core/fleet/remote-agent-nodes.js +162 -22
- package/dist/core/fleet/remote-agent-nodes.js.map +1 -1
- package/dist/core/fleet/remote-agent.d.ts +52 -1
- package/dist/core/fleet/remote-agent.js +220 -40
- package/dist/core/fleet/remote-agent.js.map +1 -1
- package/dist/core/fleet/service.d.ts +95 -3
- package/dist/core/fleet/service.js +762 -35
- package/dist/core/fleet/service.js.map +1 -1
- package/dist/core/fleet/store.js +22 -5
- package/dist/core/fleet/store.js.map +1 -1
- package/dist/core/fleet/types.d.ts +36 -1
- package/dist/core/fleet/types.js +12 -2
- package/dist/core/fleet/types.js.map +1 -1
- package/dist/core/goal-controller.d.ts +1 -0
- package/dist/core/goal-controller.js +1 -1
- package/dist/core/goal-controller.js.map +1 -1
- package/dist/core/goal-fleet.d.ts +117 -0
- package/dist/core/goal-fleet.js +441 -0
- package/dist/core/goal-fleet.js.map +1 -0
- package/dist/core/goal-headless.d.ts +45 -0
- package/dist/core/goal-headless.js +177 -0
- package/dist/core/goal-headless.js.map +1 -0
- package/dist/core/goal-remote-worker.d.ts +45 -0
- package/dist/core/goal-remote-worker.js +157 -0
- package/dist/core/goal-remote-worker.js.map +1 -0
- package/dist/core/goal-store.d.ts +36 -0
- package/dist/core/goal-store.js +69 -1
- package/dist/core/goal-store.js.map +1 -1
- package/dist/core/goal-verifier.d.ts +5 -0
- package/dist/core/goal-verifier.js +10 -0
- package/dist/core/goal-verifier.js.map +1 -1
- package/dist/core/goal-worker.d.ts +12 -0
- package/dist/core/goal-worker.js +162 -8
- package/dist/core/goal-worker.js.map +1 -1
- package/dist/core/subagent-manager.d.ts +12 -5
- package/dist/core/subagent-manager.js +15 -10
- package/dist/core/subagent-manager.js.map +1 -1
- package/dist/core/validation/backends.d.ts +34 -5
- package/dist/core/validation/backends.js +45 -5
- package/dist/core/validation/backends.js.map +1 -1
- package/dist/core/validation/cloud-backend.d.ts +77 -0
- package/dist/core/validation/cloud-backend.js +343 -0
- package/dist/core/validation/cloud-backend.js.map +1 -0
- package/dist/core/validation/config.js +9 -2
- package/dist/core/validation/config.js.map +1 -1
- package/dist/core/validation/node-backend.d.ts +2 -0
- package/dist/core/validation/node-backend.js +5 -0
- package/dist/core/validation/node-backend.js.map +1 -1
- package/dist/core/validation/scheduler.d.ts +11 -0
- package/dist/core/validation/scheduler.js +34 -7
- package/dist/core/validation/scheduler.js.map +1 -1
- package/dist/core/validation/service.d.ts +6 -0
- package/dist/core/validation/service.js +51 -13
- package/dist/core/validation/service.js.map +1 -1
- package/dist/core/validation/types.d.ts +14 -0
- package/dist/modes/acp-mode.d.ts +3 -1
- package/dist/modes/acp-mode.js +2 -1
- package/dist/modes/acp-mode.js.map +1 -1
- package/dist/system-prompt.d.ts +5 -0
- package/dist/system-prompt.js +3 -0
- package/dist/system-prompt.js.map +1 -1
- package/dist/tools/fleet.d.ts +40 -4
- package/dist/tools/fleet.js +228 -17
- package/dist/tools/fleet.js.map +1 -1
- package/dist/tools/goals.d.ts +4 -1
- package/dist/tools/goals.js +45 -5
- package/dist/tools/goals.js.map +1 -1
- package/dist/tools/index.d.ts +7 -0
- package/dist/tools/index.js +6 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/steroids.d.ts +1 -1
- package/dist/tools/subagent-control.js +1 -1
- package/dist/tools/subagent-control.js.map +1 -1
- package/dist/tools/validate.js +1 -1
- package/dist/tools/validate.js.map +1 -1
- package/dist/ui/App.js +2 -0
- package/dist/ui/App.js.map +1 -1
- package/package.json +6 -4
|
@@ -0,0 +1,836 @@
|
|
|
1
|
+
// Claude Code cloud sessions (claude.ai/code) as a cloud provider, reached
|
|
2
|
+
// with the Claude subscription sign-in EZ Coder already holds. The code goes
|
|
3
|
+
// up as a one-commit seed bundle, a session runs the prompt in Anthropic's
|
|
4
|
+
// sandbox, and the harness's event log (Bash tool_use + tool_result) is the
|
|
5
|
+
// record of what really ran. API facts: goal notes cloud-api-notes.md.
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { gunzipSync } from "node:zlib";
|
|
8
|
+
import { AuthStorage, NotLoggedInError } from "../auth-storage.js";
|
|
9
|
+
import { benchProvider, providerSettings, readCloudSettings, recordUtilization, } from "./config.js";
|
|
10
|
+
import { bundleOf, commitSnapshot, workingTreeSnapshot } from "./snapshot.js";
|
|
11
|
+
import { CloudError, } from "./types.js";
|
|
12
|
+
export const CLAUDE_API = "https://api.anthropic.com";
|
|
13
|
+
export const CLAUDE_SESSION_URL = "https://claude.ai/code/";
|
|
14
|
+
/** Cheapest capable model: a runner only relays one command. */
|
|
15
|
+
export const DEFAULT_RUNNER_MODEL = "claude-haiku-5-5";
|
|
16
|
+
const CCR_BETA = "ccr-byoc-2025-07-29";
|
|
17
|
+
const OAUTH_BETA = "oauth-2025-04-20";
|
|
18
|
+
const FILES_BETA = "files-api-2025-04-14,oauth-2025-04-20";
|
|
19
|
+
const CONTEXT_TTL_MS = 10 * 60_000;
|
|
20
|
+
const EVENT_PAGES_PER_POLL = 50;
|
|
21
|
+
const ACTIVITY_KEEP = 20;
|
|
22
|
+
/** Bash timeouts when the caller gives none (Claude Code's own long-run settings). */
|
|
23
|
+
const DEFAULT_BASH_TIMEOUT_MS = 30 * 60_000;
|
|
24
|
+
const DEFAULT_BASH_MAX_TIMEOUT_MS = 2 * 3_600_000;
|
|
25
|
+
const NOT_SIGNED_IN_HINT = "Sign in to Claude in EZ Coder (/login)";
|
|
26
|
+
function asRecord(value) {
|
|
27
|
+
return value && typeof value === "object" ? value : {};
|
|
28
|
+
}
|
|
29
|
+
function unixToIso(value) {
|
|
30
|
+
return typeof value === "number" && Number.isFinite(value)
|
|
31
|
+
? new Date(value * 1000).toISOString()
|
|
32
|
+
: undefined;
|
|
33
|
+
}
|
|
34
|
+
function toolResultText(content) {
|
|
35
|
+
if (typeof content === "string")
|
|
36
|
+
return content;
|
|
37
|
+
if (!Array.isArray(content))
|
|
38
|
+
return "";
|
|
39
|
+
return content
|
|
40
|
+
.map((c) => {
|
|
41
|
+
const r = asRecord(c);
|
|
42
|
+
return r.type === "text" && typeof r.text === "string" ? r.text : "";
|
|
43
|
+
})
|
|
44
|
+
.join("");
|
|
45
|
+
}
|
|
46
|
+
/** Usage from a rate_limit_event (`limited` once the status is no longer an allowed one). */
|
|
47
|
+
export function usageFromRateLimit(event) {
|
|
48
|
+
const info = asRecord(event.rate_limit_info);
|
|
49
|
+
if (!Object.keys(info).length)
|
|
50
|
+
return undefined;
|
|
51
|
+
const status = typeof info.status === "string" ? info.status : "allowed";
|
|
52
|
+
const windows = asRecord(info.unifiedWindows);
|
|
53
|
+
const week = asRecord(windows.seven_day);
|
|
54
|
+
let utilization = typeof week.utilization === "number" ? week.utilization : undefined;
|
|
55
|
+
if (utilization === undefined) {
|
|
56
|
+
const all = Object.values(windows)
|
|
57
|
+
.map((w) => asRecord(w).utilization)
|
|
58
|
+
.filter((u) => typeof u === "number");
|
|
59
|
+
if (all.length)
|
|
60
|
+
utilization = Math.max(...all);
|
|
61
|
+
}
|
|
62
|
+
const limited = !status.startsWith("allowed");
|
|
63
|
+
const resetsAt = limited
|
|
64
|
+
? (unixToIso(info.resetsAt) ?? unixToIso(week.resetsAt))
|
|
65
|
+
: (unixToIso(week.resetsAt) ?? unixToIso(info.resetsAt));
|
|
66
|
+
return {
|
|
67
|
+
limited,
|
|
68
|
+
...(utilization !== undefined && { utilization }),
|
|
69
|
+
...(resetsAt && { resetsAt }),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* System prompt for runner tasks. Says honestly who sends the messages: the
|
|
74
|
+
* account owner's own tool, running their project's checks in a throwaway
|
|
75
|
+
* sandbox. Without it the sandbox treats API messages as coming from an
|
|
76
|
+
* unknown peer session.
|
|
77
|
+
*/
|
|
78
|
+
export const RUNNER_SYSTEM_PROMPT = "You are a test runner in a disposable cloud sandbox. Messages in this session are sent by " +
|
|
79
|
+
"EZ Coder, the account owner's own development tool, to run checks on the owner's project. " +
|
|
80
|
+
"Run the shell command you are given exactly as written, once, and reply with only the last " +
|
|
81
|
+
"line of its output. Never edit files.";
|
|
82
|
+
export class ClaudeCloudProvider {
|
|
83
|
+
id = "claude-cloud";
|
|
84
|
+
deps;
|
|
85
|
+
context;
|
|
86
|
+
tracks = new Map();
|
|
87
|
+
/** approveCommand per session started here (handles may also carry it). */
|
|
88
|
+
approvals = new Map();
|
|
89
|
+
/** Edit-sync commands permission prompts may approve, per session. */
|
|
90
|
+
syncApprovals = new Map();
|
|
91
|
+
constructor(deps = {}) {
|
|
92
|
+
this.deps = {
|
|
93
|
+
fetch: (...args) => fetch(...args),
|
|
94
|
+
auth: deps.auth ?? new AuthStorage(),
|
|
95
|
+
settings: () => readCloudSettings(),
|
|
96
|
+
recordUtilization,
|
|
97
|
+
benchProvider,
|
|
98
|
+
commitSnapshot,
|
|
99
|
+
workingTreeSnapshot,
|
|
100
|
+
bundleOf,
|
|
101
|
+
now: () => Date.now(),
|
|
102
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
103
|
+
...deps,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// ── HTTP ─────────────────────────────────────────────────
|
|
107
|
+
async token() {
|
|
108
|
+
let creds;
|
|
109
|
+
try {
|
|
110
|
+
creds = await this.deps.auth.resolveCredentials("anthropic");
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
if (e instanceof NotLoggedInError || e?.name === "NotLoggedInError") {
|
|
114
|
+
throw new CloudError("Not signed in to Claude in EZ Coder", "not_signed_in");
|
|
115
|
+
}
|
|
116
|
+
throw e;
|
|
117
|
+
}
|
|
118
|
+
// Signed in through Claude Code: Claude Code holds the token, we have none.
|
|
119
|
+
if (!creds.accessToken) {
|
|
120
|
+
throw new CloudError("Not signed in to Claude in EZ Coder", "not_signed_in");
|
|
121
|
+
}
|
|
122
|
+
return creds.accessToken;
|
|
123
|
+
}
|
|
124
|
+
/** One API call; a 401 refreshes the sign-in once. Never logs the token. */
|
|
125
|
+
async call(method, url, opts) {
|
|
126
|
+
let token = await this.token();
|
|
127
|
+
for (let attempt = 0;; attempt++) {
|
|
128
|
+
const headers = {
|
|
129
|
+
Authorization: `Bearer ${token}`,
|
|
130
|
+
"anthropic-version": "2023-06-01",
|
|
131
|
+
"anthropic-beta": opts.beta,
|
|
132
|
+
};
|
|
133
|
+
if (opts.org)
|
|
134
|
+
headers["x-organization-uuid"] = opts.org;
|
|
135
|
+
if (opts.body !== undefined)
|
|
136
|
+
headers["content-type"] = "application/json";
|
|
137
|
+
let res;
|
|
138
|
+
try {
|
|
139
|
+
res = await this.deps.fetch(CLAUDE_API + url, {
|
|
140
|
+
method,
|
|
141
|
+
headers,
|
|
142
|
+
...(opts.form
|
|
143
|
+
? { body: opts.form }
|
|
144
|
+
: opts.body !== undefined
|
|
145
|
+
? { body: JSON.stringify(opts.body) }
|
|
146
|
+
: {}),
|
|
147
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 60_000),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
catch (e) {
|
|
151
|
+
throw new CloudError(`Claude cloud unreachable: ${e instanceof Error ? e.message : String(e)}`, "unreachable");
|
|
152
|
+
}
|
|
153
|
+
if (res.status === 401 && attempt === 0) {
|
|
154
|
+
const fresh = await this.deps.auth
|
|
155
|
+
.resolveCredentials("anthropic", { forceRefresh: true, rejectedToken: token })
|
|
156
|
+
.catch(() => undefined);
|
|
157
|
+
if (fresh?.accessToken) {
|
|
158
|
+
token = fresh.accessToken;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const text = await res.text();
|
|
163
|
+
if (!res.ok)
|
|
164
|
+
throw this.httpError(method, url, res, text);
|
|
165
|
+
try {
|
|
166
|
+
return (text ? JSON.parse(text) : {});
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
throw new CloudError(`Claude cloud ${method} ${url}: bad JSON reply`, "http", res.status);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
httpError(method, url, res, text) {
|
|
174
|
+
const path = url.split("?")[0];
|
|
175
|
+
const brief = text.replace(/\s+/g, " ").slice(0, 300);
|
|
176
|
+
const msg = `Claude cloud ${method} ${path}: HTTP ${res.status}${brief ? ` ${brief}` : ""}`;
|
|
177
|
+
const limit = /usage limit|rate[_ ]?limit|quota|exceeded your/i.test(text);
|
|
178
|
+
if (res.status === 429 || (res.status >= 400 && res.status < 500 && limit)) {
|
|
179
|
+
const retry = Number(res.headers.get("retry-after"));
|
|
180
|
+
const until = Number.isFinite(retry) && retry > 0
|
|
181
|
+
? new Date(this.deps.now() + retry * 1000).toISOString()
|
|
182
|
+
: undefined;
|
|
183
|
+
return new CloudError(msg, "usage_limited", res.status, until);
|
|
184
|
+
}
|
|
185
|
+
if (res.status === 401)
|
|
186
|
+
return new CloudError(msg, "not_signed_in", 401);
|
|
187
|
+
if (res.status === 403)
|
|
188
|
+
return new CloudError(msg, "not_allowed", 403);
|
|
189
|
+
if (res.status === 404)
|
|
190
|
+
return new CloudError(msg, "not_found", 404);
|
|
191
|
+
return new CloudError(msg, "http", res.status);
|
|
192
|
+
}
|
|
193
|
+
// ── account and environment ──────────────────────────────
|
|
194
|
+
async loadContext(force = false) {
|
|
195
|
+
const now = this.deps.now();
|
|
196
|
+
if (!force && this.context && now - this.context.at < CONTEXT_TTL_MS)
|
|
197
|
+
return this.context;
|
|
198
|
+
const profile = await this.call("GET", "/api/oauth/profile", { beta: OAUTH_BETA });
|
|
199
|
+
const org = profile.organization?.uuid;
|
|
200
|
+
if (!org)
|
|
201
|
+
throw new CloudError("Claude profile has no organization", "not_allowed");
|
|
202
|
+
const a = profile.account ?? {};
|
|
203
|
+
const orgType = profile.organization?.organization_type ?? "";
|
|
204
|
+
const plan = a.has_claude_max
|
|
205
|
+
? "Max"
|
|
206
|
+
: a.has_claude_pro
|
|
207
|
+
? "Pro"
|
|
208
|
+
: /team/i.test(orgType)
|
|
209
|
+
? "Team"
|
|
210
|
+
: /enterprise/i.test(orgType)
|
|
211
|
+
? "Enterprise"
|
|
212
|
+
: undefined;
|
|
213
|
+
const ctx = {
|
|
214
|
+
at: now,
|
|
215
|
+
org,
|
|
216
|
+
account: a.email ?? "Claude account",
|
|
217
|
+
...(plan && { plan }),
|
|
218
|
+
};
|
|
219
|
+
if (plan) {
|
|
220
|
+
const list = await this.call("GET", "/v1/environment_providers", { beta: CCR_BETA, org });
|
|
221
|
+
const envs = list.environments ?? [];
|
|
222
|
+
const wanted = providerSettings(this.deps.settings(), this.id).environment;
|
|
223
|
+
const cloud = envs.filter((e) => e.kind === "anthropic_cloud" && e.state !== "archived");
|
|
224
|
+
const active = cloud.filter((e) => !e.state || e.state === "active");
|
|
225
|
+
const env = wanted
|
|
226
|
+
? envs.find((e) => e.environment_id === wanted || e.name === wanted)
|
|
227
|
+
: (active.find((e) => e.name === "Default") ?? active[0]);
|
|
228
|
+
if (env)
|
|
229
|
+
ctx.env = env;
|
|
230
|
+
else
|
|
231
|
+
ctx.envProblem = wanted
|
|
232
|
+
? `environment "${wanted}" (~/.ezcoder/cloud.json) not found in this Claude account`
|
|
233
|
+
: "no Claude Code cloud environment yet";
|
|
234
|
+
}
|
|
235
|
+
this.context = ctx;
|
|
236
|
+
return ctx;
|
|
237
|
+
}
|
|
238
|
+
async detect() {
|
|
239
|
+
let ctx;
|
|
240
|
+
try {
|
|
241
|
+
ctx = await this.loadContext();
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
if (e instanceof CloudError && e.code === "not_signed_in") {
|
|
245
|
+
return {
|
|
246
|
+
id: this.id,
|
|
247
|
+
available: false,
|
|
248
|
+
detail: "not signed in to Claude",
|
|
249
|
+
setupHint: NOT_SIGNED_IN_HINT,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
return { id: this.id, available: false, detail: e instanceof Error ? e.message : String(e) };
|
|
253
|
+
}
|
|
254
|
+
const account = ctx.plan ? `${ctx.account} (${ctx.plan})` : ctx.account;
|
|
255
|
+
if (!ctx.plan) {
|
|
256
|
+
return {
|
|
257
|
+
id: this.id,
|
|
258
|
+
available: false,
|
|
259
|
+
account,
|
|
260
|
+
detail: `${ctx.account} has no Claude Pro, Max or Team plan (needed for Claude Code cloud)`,
|
|
261
|
+
setupHint: "Sign in to Claude with a Pro, Max or Team account",
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
if (!ctx.env?.environment_id) {
|
|
265
|
+
return {
|
|
266
|
+
id: this.id,
|
|
267
|
+
available: false,
|
|
268
|
+
account,
|
|
269
|
+
detail: `${account}: ${ctx.envProblem ?? "no cloud environment"}`,
|
|
270
|
+
setupHint: "Run `ezcoder cloud setup` to create the Default Claude Code cloud environment " +
|
|
271
|
+
"(or open claude.ai/code once)",
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
const name = ctx.env.name ?? ctx.env.environment_id;
|
|
275
|
+
return {
|
|
276
|
+
id: this.id,
|
|
277
|
+
available: true,
|
|
278
|
+
account,
|
|
279
|
+
environmentId: ctx.env.environment_id,
|
|
280
|
+
environmentName: name,
|
|
281
|
+
detail: `${account}, environment ${name}`,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Create the "Default" cloud environment the way Claude Code's CLI does
|
|
286
|
+
* (trusted network access, Python + Node). Only on explicit user action.
|
|
287
|
+
*/
|
|
288
|
+
async createDefaultEnvironment() {
|
|
289
|
+
const ctx = await this.loadContext(true);
|
|
290
|
+
if (!ctx.plan)
|
|
291
|
+
throw new CloudError(`${ctx.account} has no Claude Pro/Max/Team plan`, "not_allowed");
|
|
292
|
+
if (ctx.env?.environment_id) {
|
|
293
|
+
return { environmentId: ctx.env.environment_id, name: ctx.env.name ?? "Default" };
|
|
294
|
+
}
|
|
295
|
+
const created = await this.call("POST", "/v1/environment_providers/cloud/create", {
|
|
296
|
+
beta: CCR_BETA,
|
|
297
|
+
org: ctx.org,
|
|
298
|
+
body: {
|
|
299
|
+
name: "Default",
|
|
300
|
+
kind: "anthropic_cloud",
|
|
301
|
+
description: "Default - trusted network access",
|
|
302
|
+
config: {
|
|
303
|
+
environment_type: "anthropic",
|
|
304
|
+
cwd: "/home/user",
|
|
305
|
+
init_script: null,
|
|
306
|
+
environment: {},
|
|
307
|
+
languages: [
|
|
308
|
+
{ name: "python", version: "3.11" },
|
|
309
|
+
{ name: "node", version: "20" },
|
|
310
|
+
],
|
|
311
|
+
network_config: { allowed_hosts: [], allow_default_hosts: true },
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
});
|
|
315
|
+
this.context = undefined;
|
|
316
|
+
const environmentId = created.environment_id ?? created.id;
|
|
317
|
+
if (!environmentId)
|
|
318
|
+
throw new CloudError("environment create returned no id", "http");
|
|
319
|
+
return { environmentId, name: created.name ?? "Default" };
|
|
320
|
+
}
|
|
321
|
+
/** Account, org and environment for a task, or a CloudError saying why not. */
|
|
322
|
+
async ready() {
|
|
323
|
+
const ctx = await this.loadContext();
|
|
324
|
+
if (!ctx.plan)
|
|
325
|
+
throw new CloudError(`${ctx.account} has no Claude Pro/Max/Team plan`, "not_allowed");
|
|
326
|
+
if (!ctx.env?.environment_id) {
|
|
327
|
+
throw new CloudError(ctx.envProblem ?? "no Claude Code cloud environment", "no_environment");
|
|
328
|
+
}
|
|
329
|
+
return ctx;
|
|
330
|
+
}
|
|
331
|
+
// ── tasks ────────────────────────────────────────────────
|
|
332
|
+
async start(request) {
|
|
333
|
+
const ctx = await this.ready();
|
|
334
|
+
const { repoRoot, sha } = request.source;
|
|
335
|
+
// Agents send their uncommitted work: snapshot it from the working tree.
|
|
336
|
+
const snap = request.source.patch
|
|
337
|
+
? await this.deps.workingTreeSnapshot(repoRoot)
|
|
338
|
+
: await this.deps.commitSnapshot(repoRoot, sha);
|
|
339
|
+
const bundle = await this.deps.bundleOf(repoRoot, snap.commit);
|
|
340
|
+
const form = new FormData();
|
|
341
|
+
form.append("file", new Blob([new Uint8Array(bundle)]), "repo.bundle");
|
|
342
|
+
form.append("purpose", "user_data");
|
|
343
|
+
const file = await this.call("POST", "/v1/files", {
|
|
344
|
+
beta: FILES_BETA,
|
|
345
|
+
org: ctx.org,
|
|
346
|
+
form,
|
|
347
|
+
timeoutMs: 15 * 60_000,
|
|
348
|
+
});
|
|
349
|
+
if (!file.id)
|
|
350
|
+
throw new CloudError("bundle upload returned no file id", "http");
|
|
351
|
+
const settings = providerSettings(this.deps.settings(), this.id);
|
|
352
|
+
const bashMs = request.commandTimeoutMinutes !== undefined
|
|
353
|
+
? Math.min((Math.ceil(request.commandTimeoutMinutes) + 5) * 60_000, 24 * 3_600_000)
|
|
354
|
+
: undefined;
|
|
355
|
+
const env = {
|
|
356
|
+
...request.env,
|
|
357
|
+
BASH_DEFAULT_TIMEOUT_MS: String(bashMs ?? DEFAULT_BASH_TIMEOUT_MS),
|
|
358
|
+
BASH_MAX_TIMEOUT_MS: String(bashMs ?? DEFAULT_BASH_MAX_TIMEOUT_MS),
|
|
359
|
+
};
|
|
360
|
+
const sessionContext = {
|
|
361
|
+
sources: [],
|
|
362
|
+
outcomes: [],
|
|
363
|
+
seed_bundle_file_id: file.id,
|
|
364
|
+
environment_variables: env,
|
|
365
|
+
model: request.model ?? settings.runnerModel ?? DEFAULT_RUNNER_MODEL,
|
|
366
|
+
...(request.maxTurns !== undefined && { max_turns: request.maxTurns }),
|
|
367
|
+
...(request.disallowedTools?.length && { disallowed_tools: request.disallowedTools }),
|
|
368
|
+
// Runner tasks: a one-line system prompt and the shell tool only. Half
|
|
369
|
+
// the tokens of the default prompt (measured: ~$0.008 vs ~$0.02 a stage).
|
|
370
|
+
...(request.runner && {
|
|
371
|
+
custom_system_prompt: RUNNER_SYSTEM_PROMPT,
|
|
372
|
+
builtin_tools: ["Bash"],
|
|
373
|
+
}),
|
|
374
|
+
};
|
|
375
|
+
const created = await this.call("POST", "/v1/sessions", {
|
|
376
|
+
beta: CCR_BETA,
|
|
377
|
+
org: ctx.org,
|
|
378
|
+
body: {
|
|
379
|
+
title: request.title.slice(0, 200),
|
|
380
|
+
environment_id: ctx.env.environment_id,
|
|
381
|
+
events: [{ type: "event", data: this.userEvent(request.prompt) }],
|
|
382
|
+
session_context: sessionContext,
|
|
383
|
+
},
|
|
384
|
+
});
|
|
385
|
+
if (!created.id)
|
|
386
|
+
throw new CloudError("session create returned no id", "http");
|
|
387
|
+
if (request.approveCommand)
|
|
388
|
+
this.approvals.set(created.id, request.approveCommand);
|
|
389
|
+
return {
|
|
390
|
+
provider: this.id,
|
|
391
|
+
id: created.id,
|
|
392
|
+
url: CLAUDE_SESSION_URL + created.id,
|
|
393
|
+
baseTree: snap.tree,
|
|
394
|
+
baseCommit: snap.commit,
|
|
395
|
+
repoRoot,
|
|
396
|
+
...(request.approveCommand && { approveCommand: request.approveCommand }),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
userEvent(content) {
|
|
400
|
+
return {
|
|
401
|
+
uuid: randomUUID(),
|
|
402
|
+
session_id: "",
|
|
403
|
+
type: "user",
|
|
404
|
+
parent_tool_use_id: null,
|
|
405
|
+
message: { role: "user", content },
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
track(id) {
|
|
409
|
+
let t = this.tracks.get(id);
|
|
410
|
+
if (!t) {
|
|
411
|
+
t = {
|
|
412
|
+
toolUses: new Map(),
|
|
413
|
+
commands: [],
|
|
414
|
+
turns: 0,
|
|
415
|
+
usageFresh: false,
|
|
416
|
+
activity: [],
|
|
417
|
+
tokens: { input: 0, output: 0 },
|
|
418
|
+
prompts: new Map(),
|
|
419
|
+
answered: new Set(),
|
|
420
|
+
};
|
|
421
|
+
this.tracks.set(id, t);
|
|
422
|
+
}
|
|
423
|
+
return t;
|
|
424
|
+
}
|
|
425
|
+
/** Read events after the cursor (paged) and fold them into the track. */
|
|
426
|
+
async pull(id, org, t) {
|
|
427
|
+
for (let page = 0; page < EVENT_PAGES_PER_POLL; page++) {
|
|
428
|
+
const q = `/v1/sessions/${encodeURIComponent(id)}/events?limit=500${t.cursor ? `&after_id=${encodeURIComponent(t.cursor)}` : ""}`;
|
|
429
|
+
const r = await this.call("GET", q, { beta: CCR_BETA, org });
|
|
430
|
+
const data = r.data ?? [];
|
|
431
|
+
for (const e of data)
|
|
432
|
+
this.fold(t, e);
|
|
433
|
+
const last = r.last_id ?? data.at(-1)?.id;
|
|
434
|
+
if (typeof last === "string" && last)
|
|
435
|
+
t.cursor = last;
|
|
436
|
+
if (!r.has_more || !data.length)
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
fold(t, e) {
|
|
441
|
+
switch (e.type) {
|
|
442
|
+
case "assistant": {
|
|
443
|
+
const content = asRecord(e.message).content;
|
|
444
|
+
if (!Array.isArray(content))
|
|
445
|
+
break;
|
|
446
|
+
for (const item of content) {
|
|
447
|
+
const c = asRecord(item);
|
|
448
|
+
if (c.type === "text" && typeof c.text === "string" && c.text.trim()) {
|
|
449
|
+
t.finalText = c.text;
|
|
450
|
+
}
|
|
451
|
+
else if (c.type === "tool_use" && typeof c.id === "string") {
|
|
452
|
+
const tool = typeof c.name === "string" ? c.name : "?";
|
|
453
|
+
const input = asRecord(c.input);
|
|
454
|
+
t.toolUses.set(c.id, { name: tool, input });
|
|
455
|
+
t.activity.push({ tool, input });
|
|
456
|
+
if (t.activity.length > ACTIVITY_KEEP)
|
|
457
|
+
t.activity.shift();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
break;
|
|
461
|
+
}
|
|
462
|
+
case "user": {
|
|
463
|
+
const content = asRecord(e.message).content;
|
|
464
|
+
if (!Array.isArray(content))
|
|
465
|
+
break;
|
|
466
|
+
for (const item of content) {
|
|
467
|
+
const c = asRecord(item);
|
|
468
|
+
if (c.type !== "tool_result" || typeof c.tool_use_id !== "string")
|
|
469
|
+
continue;
|
|
470
|
+
const use = t.toolUses.get(c.tool_use_id);
|
|
471
|
+
if (!use || use.name !== "Bash" || typeof use.input.command !== "string")
|
|
472
|
+
continue;
|
|
473
|
+
t.commands.push({
|
|
474
|
+
command: use.input.command,
|
|
475
|
+
output: toolResultText(c.content),
|
|
476
|
+
isError: c.is_error === true,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
case "result": {
|
|
482
|
+
t.turns++;
|
|
483
|
+
t.resultError =
|
|
484
|
+
e.is_error === true
|
|
485
|
+
? typeof e.result === "string" && e.result
|
|
486
|
+
? e.result
|
|
487
|
+
: `turn ended with an error${typeof e.subtype === "string" ? ` (${e.subtype})` : ""}`
|
|
488
|
+
: undefined;
|
|
489
|
+
for (const u of Object.values(asRecord(e.model_usage_since_last_result))) {
|
|
490
|
+
const m = asRecord(u);
|
|
491
|
+
const n = (k) => (typeof m[k] === "number" ? m[k] : 0);
|
|
492
|
+
t.tokens.input +=
|
|
493
|
+
n("inputTokens") + n("cacheCreationInputTokens") + n("cacheReadInputTokens");
|
|
494
|
+
t.tokens.output += n("outputTokens");
|
|
495
|
+
}
|
|
496
|
+
break;
|
|
497
|
+
}
|
|
498
|
+
case "rate_limit_event": {
|
|
499
|
+
const usage = usageFromRateLimit(e);
|
|
500
|
+
if (usage) {
|
|
501
|
+
t.usage = usage;
|
|
502
|
+
t.usageFresh = true;
|
|
503
|
+
}
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
case "control_request": {
|
|
507
|
+
const req = asRecord(e.request);
|
|
508
|
+
if (req.subtype !== "can_use_tool" || typeof e.request_id !== "string")
|
|
509
|
+
break;
|
|
510
|
+
const input = asRecord(req.input);
|
|
511
|
+
t.prompts.set(e.request_id, {
|
|
512
|
+
tool: typeof req.tool_name === "string" ? req.tool_name : "?",
|
|
513
|
+
toolUseId: typeof req.tool_use_id === "string" ? req.tool_use_id : "",
|
|
514
|
+
...(Object.keys(input).length && { input }),
|
|
515
|
+
});
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
case "control_response": {
|
|
519
|
+
const id = asRecord(e.response).request_id;
|
|
520
|
+
if (typeof id === "string")
|
|
521
|
+
t.answered.add(id);
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
case "env_manager_log": {
|
|
525
|
+
const content = asRecord(e.data).content;
|
|
526
|
+
if (typeof content === "string")
|
|
527
|
+
t.lastLog = content;
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
default:
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
async status(handle) {
|
|
535
|
+
const ctx = await this.loadContext();
|
|
536
|
+
// Status first, then events: an idle session's final events are already written.
|
|
537
|
+
const session = await this.call("GET", `/v1/sessions/${encodeURIComponent(handle.id)}`, { beta: CCR_BETA, org: ctx.org });
|
|
538
|
+
const t = this.track(handle.id);
|
|
539
|
+
await this.pull(handle.id, ctx.org, t);
|
|
540
|
+
const answeredNow = await this.answerPrompts(handle, ctx.org, t);
|
|
541
|
+
if (t.usageFresh && t.usage) {
|
|
542
|
+
t.usageFresh = false;
|
|
543
|
+
if (t.usage.utilization !== undefined) {
|
|
544
|
+
this.deps.recordUtilization(this.id, t.usage.utilization, t.usage.resetsAt);
|
|
545
|
+
}
|
|
546
|
+
if (t.usage.limited) {
|
|
547
|
+
const until = t.usage.resetsAt ?? new Date(this.deps.now() + 3_600_000).toISOString();
|
|
548
|
+
this.deps.benchProvider(this.id, until, "Claude plan usage limit reached");
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
let state;
|
|
552
|
+
switch (session.session_status) {
|
|
553
|
+
case "pending":
|
|
554
|
+
state = "starting";
|
|
555
|
+
break;
|
|
556
|
+
case "running":
|
|
557
|
+
state = "running";
|
|
558
|
+
break;
|
|
559
|
+
case "requires_action":
|
|
560
|
+
// A permission prompt: answered above (allow our command, deny the rest).
|
|
561
|
+
state = "running";
|
|
562
|
+
break;
|
|
563
|
+
case "idle":
|
|
564
|
+
// Idle before the first turn ends = still being set up.
|
|
565
|
+
state = t.turns > 0 ? "idle" : "starting";
|
|
566
|
+
break;
|
|
567
|
+
case "failed":
|
|
568
|
+
state = "failed";
|
|
569
|
+
break;
|
|
570
|
+
case "archived":
|
|
571
|
+
state = "cancelled";
|
|
572
|
+
break;
|
|
573
|
+
default:
|
|
574
|
+
state = "running";
|
|
575
|
+
}
|
|
576
|
+
const error = state === "failed"
|
|
577
|
+
? (t.resultError ?? `session failed${t.lastLog ? ` (last: ${t.lastLog})` : ""}`)
|
|
578
|
+
: t.resultError;
|
|
579
|
+
if (answeredNow && state === "idle")
|
|
580
|
+
state = "running";
|
|
581
|
+
return {
|
|
582
|
+
state,
|
|
583
|
+
...(t.finalText !== undefined && { finalText: t.finalText }),
|
|
584
|
+
commands: [...t.commands],
|
|
585
|
+
turns: t.turns,
|
|
586
|
+
...(t.usage && { usage: { ...t.usage } }),
|
|
587
|
+
...(error && { error }),
|
|
588
|
+
...(t.activity.length && { activity: [...t.activity] }),
|
|
589
|
+
usageTokens: { ...t.tokens },
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Answer pending permission prompts: allow a Bash call whose command is
|
|
594
|
+
* byte-identical to the task's approveCommand, deny everything else.
|
|
595
|
+
* (Verified live: control_response via POST /v1/sessions/<id>/events.)
|
|
596
|
+
*/
|
|
597
|
+
async answerPrompts(handle, org, t) {
|
|
598
|
+
const approve = handle.approveCommand ?? this.approvals.get(handle.id);
|
|
599
|
+
const sync = this.syncApprovals.get(handle.id);
|
|
600
|
+
let n = 0;
|
|
601
|
+
for (const [requestId, p] of t.prompts) {
|
|
602
|
+
if (t.answered.has(requestId))
|
|
603
|
+
continue;
|
|
604
|
+
const input = t.toolUses.get(p.toolUseId)?.input ?? p.input;
|
|
605
|
+
const command = input?.command;
|
|
606
|
+
const ok = p.tool === "Bash" &&
|
|
607
|
+
typeof command === "string" &&
|
|
608
|
+
(command === approve || (sync?.has(command) ?? false));
|
|
609
|
+
const response = ok
|
|
610
|
+
? { behavior: "allow", updatedInput: input, toolUseID: p.toolUseId }
|
|
611
|
+
: { behavior: "deny", message: "Only the given command may run." };
|
|
612
|
+
await this.call("POST", `/v1/sessions/${encodeURIComponent(handle.id)}/events`, {
|
|
613
|
+
beta: CCR_BETA,
|
|
614
|
+
org,
|
|
615
|
+
body: {
|
|
616
|
+
events: [
|
|
617
|
+
{
|
|
618
|
+
uuid: randomUUID(),
|
|
619
|
+
type: "control_response",
|
|
620
|
+
response: { subtype: "success", request_id: requestId, response },
|
|
621
|
+
},
|
|
622
|
+
],
|
|
623
|
+
},
|
|
624
|
+
});
|
|
625
|
+
t.answered.add(requestId);
|
|
626
|
+
n++;
|
|
627
|
+
}
|
|
628
|
+
return n;
|
|
629
|
+
}
|
|
630
|
+
async postEvents(handle, events) {
|
|
631
|
+
const ctx = await this.loadContext();
|
|
632
|
+
await this.call("POST", `/v1/sessions/${encodeURIComponent(handle.id)}/events`, {
|
|
633
|
+
beta: CCR_BETA,
|
|
634
|
+
org: ctx.org,
|
|
635
|
+
body: { events },
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
async send(handle, message) {
|
|
639
|
+
await this.postEvents(handle, [this.userEvent(message)]);
|
|
640
|
+
}
|
|
641
|
+
async interrupt(handle) {
|
|
642
|
+
await this.postEvents(handle, [
|
|
643
|
+
{
|
|
644
|
+
type: "control_request",
|
|
645
|
+
request_id: `interrupt-${randomUUID()}`,
|
|
646
|
+
request: { subtype: "interrupt" },
|
|
647
|
+
},
|
|
648
|
+
]);
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* The session's changes against `handle.baseCommit`, brought back through
|
|
652
|
+
* the harness's own command record (never assistant text): a follow-up turn
|
|
653
|
+
* asks the agent to run exact commands that print the sandbox's diff
|
|
654
|
+
* gzipped + base64 between markers with its sha256 and length. A Bash
|
|
655
|
+
* tool_result carries ~30 KB before Claude Code swaps it for a
|
|
656
|
+
* <persisted-output> preview (measured live), so larger diffs come back in
|
|
657
|
+
* numbered chunks in a second turn. Only when the session is idle.
|
|
658
|
+
*/
|
|
659
|
+
async diff(handle) {
|
|
660
|
+
const base = handle.baseCommit;
|
|
661
|
+
if (!base || !/^[0-9a-f]{40,64}$/.test(base)) {
|
|
662
|
+
throw new CloudError("This session has no snapshot commit to diff against", "not_allowed");
|
|
663
|
+
}
|
|
664
|
+
const status = await this.status(handle);
|
|
665
|
+
if (status.state !== "idle") {
|
|
666
|
+
throw new CloudError(`session is ${status.state}, not idle; edits not synced`, "not_allowed");
|
|
667
|
+
}
|
|
668
|
+
const prepare = claudeSyncPrepareCommand(base);
|
|
669
|
+
const first = await this.runSyncTurn(handle, [prepare], SYNC_PROMPT_ONE);
|
|
670
|
+
const header = parseSyncOutput(first[0]);
|
|
671
|
+
if (header.empty)
|
|
672
|
+
return Buffer.alloc(0);
|
|
673
|
+
if (header.length > MAX_SYNC_B64_BYTES) {
|
|
674
|
+
throw new CloudError(`the session's changes are ${Math.round(header.length / 1024)} KB packed, over the ` +
|
|
675
|
+
`${MAX_SYNC_B64_BYTES / 1024} KB sync limit; they stay in the session: ${handle.url}`, "too_large");
|
|
676
|
+
}
|
|
677
|
+
let data = header.data;
|
|
678
|
+
if (data.length < header.length) {
|
|
679
|
+
const chunks = claudeSyncChunkCommands(header.length).slice(1);
|
|
680
|
+
const outputs = await this.runSyncTurn(handle, chunks, SYNC_PROMPT_MANY);
|
|
681
|
+
for (const out of outputs)
|
|
682
|
+
data += parseSyncChunk(out);
|
|
683
|
+
}
|
|
684
|
+
return decodeSyncPayload(data, header.sha256, header.length);
|
|
685
|
+
}
|
|
686
|
+
/** One follow-up turn running exactly `commands`; their recorded outputs, in order. */
|
|
687
|
+
async runSyncTurn(handle, commands, prompt) {
|
|
688
|
+
const before = await this.status(handle);
|
|
689
|
+
const t = this.track(handle.id);
|
|
690
|
+
const seen = t.commands.length;
|
|
691
|
+
this.syncApprovals.set(handle.id, new Set(commands));
|
|
692
|
+
try {
|
|
693
|
+
const listed = commands.map((c) => "```\n" + c + "\n```").join("\n");
|
|
694
|
+
await this.send(handle, `${prompt}\n${listed}`);
|
|
695
|
+
const deadline = this.deps.now() + SYNC_TURN_TIMEOUT_MS;
|
|
696
|
+
for (;;) {
|
|
697
|
+
await this.deps.sleep(SYNC_POLL_MS);
|
|
698
|
+
const s = await this.status(handle);
|
|
699
|
+
if (s.state === "failed" || s.state === "cancelled") {
|
|
700
|
+
throw new CloudError(`sync turn ${s.state}: ${s.error ?? ""}`.trim(), "http");
|
|
701
|
+
}
|
|
702
|
+
if (s.state === "idle" && s.turns > before.turns)
|
|
703
|
+
break;
|
|
704
|
+
if (this.deps.now() > deadline) {
|
|
705
|
+
throw new CloudError("sync turn timed out", "unreachable");
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const fresh = t.commands.slice(seen);
|
|
709
|
+
// Models wrap commands (live: a `cd` into the cwd added in front), so
|
|
710
|
+
// the record must contain every step of ours unchanged; additions are
|
|
711
|
+
// tolerated, any dropped or altered step is refused.
|
|
712
|
+
return commands.map((command) => {
|
|
713
|
+
const steps = syncCommandSteps(command);
|
|
714
|
+
const record = fresh.filter((r) => r.command === command).at(-1) ??
|
|
715
|
+
fresh.filter((r) => steps.every((step) => r.command.includes(step))).at(-1);
|
|
716
|
+
if (!record) {
|
|
717
|
+
throw new CloudError("the agent did not run the sync command as given", "http");
|
|
718
|
+
}
|
|
719
|
+
return record.output;
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
finally {
|
|
723
|
+
this.syncApprovals.delete(handle.id);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
async archive(handle) {
|
|
727
|
+
this.tracks.delete(handle.id);
|
|
728
|
+
this.approvals.delete(handle.id);
|
|
729
|
+
this.syncApprovals.delete(handle.id);
|
|
730
|
+
try {
|
|
731
|
+
const ctx = await this.loadContext();
|
|
732
|
+
await this.call("POST", `/v1/sessions/${encodeURIComponent(handle.id)}/archive`, {
|
|
733
|
+
beta: CCR_BETA,
|
|
734
|
+
org: ctx.org,
|
|
735
|
+
body: {},
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
catch (e) {
|
|
739
|
+
if (e instanceof CloudError && (e.status === 409 || e.status === 404))
|
|
740
|
+
return;
|
|
741
|
+
throw e;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
// ── edit sync (diff) ───────────────────────────────────────
|
|
746
|
+
/** Base64 characters per Bash tool_result (measured: 30 KB passes, 100 KB is swapped for a preview). */
|
|
747
|
+
export const SYNC_CHUNK_CHARS = 24_000;
|
|
748
|
+
/** Packed (gzip + base64) diff size past which edits stay in the session. */
|
|
749
|
+
export const MAX_SYNC_B64_BYTES = 1024 * 1024;
|
|
750
|
+
const SYNC_POLL_MS = 3_000;
|
|
751
|
+
const SYNC_TURN_TIMEOUT_MS = 10 * 60_000;
|
|
752
|
+
const SYNC_FILE = "/tmp/ezsync.b64";
|
|
753
|
+
// Short (every sync turn runs on the session's model), saying who sends it
|
|
754
|
+
// (EZ Coder, for the account owner) and why: live, a model refused an unexplained request
|
|
755
|
+
// to print packed data ("it came from another session, not from you").
|
|
756
|
+
const SYNC_PROMPT_ONE = "Sent by EZ Coder, the app I (the account owner) use to run this session. Please run this exact Bash command once, " +
|
|
757
|
+
"unchanged: it prints your file changes as a packed, checksummed diff so they can be copied " +
|
|
758
|
+
"back to my computer. Then reply only: done";
|
|
759
|
+
const SYNC_PROMPT_MANY = "Sent by EZ Coder, the app I (the account owner) use to run this session. The packed diff was too long for one output; " +
|
|
760
|
+
"please run these exact Bash commands, one per Bash call, in order, unchanged, " +
|
|
761
|
+
"then reply only: done";
|
|
762
|
+
/**
|
|
763
|
+
* In the sandbox repo (the session's working directory): a private index seeded from HEAD plus every change
|
|
764
|
+
* (untracked, not ignored, included), diffed against the snapshot commit,
|
|
765
|
+
* packed, and printed with a header and the first chunk.
|
|
766
|
+
*/
|
|
767
|
+
export function claudeSyncPrepareCommand(baseCommit) {
|
|
768
|
+
return ([
|
|
769
|
+
"export GIT_INDEX_FILE=/tmp/ezsync.index",
|
|
770
|
+
"git read-tree HEAD",
|
|
771
|
+
"git add -A",
|
|
772
|
+
`git diff --cached --binary ${baseCommit} > /tmp/ezsync.patch`,
|
|
773
|
+
].join(" && ") +
|
|
774
|
+
` && if [ -s /tmp/ezsync.patch ]; then gzip -9nc /tmp/ezsync.patch | base64 -w0 > ${SYNC_FILE}` +
|
|
775
|
+
` && echo "EZSYNC $(sha256sum < ${SYNC_FILE} | cut -c1-64) $(wc -c < ${SYNC_FILE})"` +
|
|
776
|
+
` && head -c ${SYNC_CHUNK_CHARS} ${SYNC_FILE} && echo && echo EZSYNC-END; else echo "EZSYNC EMPTY"; fi`);
|
|
777
|
+
}
|
|
778
|
+
/** Commands printing chunk k (1-based) of the packed diff; [0] is part of the prepare command. */
|
|
779
|
+
export function claudeSyncChunkCommands(length) {
|
|
780
|
+
const out = [];
|
|
781
|
+
for (let k = 0; k * SYNC_CHUNK_CHARS < length; k++) {
|
|
782
|
+
out.push(`echo EZSYNC-PART ${k + 1}; tail -c +${k * SYNC_CHUNK_CHARS + 1} ${SYNC_FILE} | ` +
|
|
783
|
+
`head -c ${SYNC_CHUNK_CHARS}; echo; echo EZSYNC-END`);
|
|
784
|
+
}
|
|
785
|
+
return out;
|
|
786
|
+
}
|
|
787
|
+
export function parseSyncOutput(output) {
|
|
788
|
+
const lines = output.replace(/\r/g, "").split("\n");
|
|
789
|
+
const at = lines.findIndex((l) => l.startsWith("EZSYNC "));
|
|
790
|
+
if (at < 0) {
|
|
791
|
+
throw new CloudError(output.includes("persisted-output")
|
|
792
|
+
? "the sync output was cut off by the sandbox"
|
|
793
|
+
: `the sync command printed no result: ${output.trim().slice(-300)}`, "http");
|
|
794
|
+
}
|
|
795
|
+
const head = lines[at].trim();
|
|
796
|
+
if (head === "EZSYNC EMPTY")
|
|
797
|
+
return { empty: true };
|
|
798
|
+
const m = /^EZSYNC ([0-9a-f]{64}) (\d+)$/.exec(head);
|
|
799
|
+
const end = lines.indexOf("EZSYNC-END", at + 1);
|
|
800
|
+
if (!m || end < 0)
|
|
801
|
+
throw new CloudError("the sync output is malformed or cut off", "http");
|
|
802
|
+
return {
|
|
803
|
+
empty: false,
|
|
804
|
+
sha256: m[1],
|
|
805
|
+
length: Number(m[2]),
|
|
806
|
+
data: lines
|
|
807
|
+
.slice(at + 1, end)
|
|
808
|
+
.join("")
|
|
809
|
+
.trim(),
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
export function parseSyncChunk(output) {
|
|
813
|
+
const lines = output.replace(/\r/g, "").split("\n");
|
|
814
|
+
const at = lines.findIndex((l) => /^EZSYNC-PART \d+$/.test(l.trim()));
|
|
815
|
+
const end = lines.indexOf("EZSYNC-END", at + 1);
|
|
816
|
+
if (at < 0 || end < 0)
|
|
817
|
+
throw new CloudError("a sync chunk is missing or cut off", "http");
|
|
818
|
+
return lines
|
|
819
|
+
.slice(at + 1, end)
|
|
820
|
+
.join("")
|
|
821
|
+
.trim();
|
|
822
|
+
}
|
|
823
|
+
export function decodeSyncPayload(data, sha256, length) {
|
|
824
|
+
if (data.length !== length || createHash("sha256").update(data).digest("hex") !== sha256) {
|
|
825
|
+
throw new CloudError(`the synced changes don't match their checksum (${data.length}/${length} bytes)`, "http");
|
|
826
|
+
}
|
|
827
|
+
return gunzipSync(Buffer.from(data, "base64"));
|
|
828
|
+
}
|
|
829
|
+
/** The steps of a sync command (split on `&&` and `;`), each of which a recorded run must contain. */
|
|
830
|
+
export function syncCommandSteps(command) {
|
|
831
|
+
return command
|
|
832
|
+
.split(/\s*(?:&&|;)\s*/)
|
|
833
|
+
.map((step) => step.trim())
|
|
834
|
+
.filter(Boolean);
|
|
835
|
+
}
|
|
836
|
+
//# sourceMappingURL=claude.js.map
|