@carrieros/cli-staging 0.0.0-stage → 0.4.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 +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +26 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +160 -0
- package/dist/commands/update.js +285 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +229 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +364 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +132 -0
- package/dist/services/api.js +441 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +384 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +416 -0
- package/dist/services/device-auth.js +288 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +42 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +115 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +730 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1622 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +414 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { ApiError } from "./api.js";
|
|
3
|
+
import { deviceLabel, localAuthorizeDefault, openBrowser, userCliAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
|
|
4
|
+
import { info, line } from "./output.js";
|
|
5
|
+
import { sleep, withSpinner } from "./spinner.js";
|
|
6
|
+
import { c } from "../ui/colors.js";
|
|
7
|
+
/**
|
|
8
|
+
* The single source of truth for browser-based login (OAuth 2.0 Device
|
|
9
|
+
* Authorization). This module owns only the *presentation* of the login — the
|
|
10
|
+
* flow, polling, token, and refresh logic are unchanged and live in
|
|
11
|
+
* device-auth.ts. Shared by the `login` command and the shell's first-run.
|
|
12
|
+
*
|
|
13
|
+
* Terminal choreography (Claude-Code style, minimal + fixed, no scroll flood):
|
|
14
|
+
* Opening your browser…
|
|
15
|
+
* ✓ Browser opened <verification url> Code XXXX-XXXX
|
|
16
|
+
* ⠋ Waiting for approval… (in-place spinner)
|
|
17
|
+
* ✓ Device authorized / Session synchronized / Logged in as <account>
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* The device-authorization flow without any terminal output: request a device
|
|
21
|
+
* code, compute where the browser should go, and — when `complete()` is called —
|
|
22
|
+
* poll for approval and persist the session exactly as the CLI does. Shared by
|
|
23
|
+
* `cos login` (which renders it in the terminal) and the IDE extension (which
|
|
24
|
+
* opens the URL with the editor's own browser API). One flow, one session store.
|
|
25
|
+
*/
|
|
26
|
+
export async function beginDeviceLogin(ctx, apiUrl, label = deviceLabel()) {
|
|
27
|
+
const authBase = userCliAuthBase(apiUrl);
|
|
28
|
+
const start = await startDeviceAuthorization(authBase, label);
|
|
29
|
+
const apiUri = start.verification_uri_complete || start.verification_uri;
|
|
30
|
+
const override = ctx.config.get("platformUrl") || process.env.CARRIEROS_PLATFORM_URL || localAuthorizeDefault(apiUrl, apiUri);
|
|
31
|
+
return {
|
|
32
|
+
openUrl: withPlatformOrigin(apiUri, override),
|
|
33
|
+
userCode: start.user_code,
|
|
34
|
+
// A cancelled sign-in stops polling, so a late approval never signs anyone in.
|
|
35
|
+
complete: async (signal) => persistSession(ctx, await pollForToken(authBase, start, undefined, signal), apiUrl)
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export async function deviceLogin(ctx, apiUrl) {
|
|
39
|
+
const authBase = userCliAuthBase(apiUrl);
|
|
40
|
+
// Branding + intro first (shown for both `cos` first-run and `cos login`).
|
|
41
|
+
line();
|
|
42
|
+
line(" " + c.brand("Welcome to Carrier OS"));
|
|
43
|
+
line(" " + c.dim("Sign in with your Carrier OS account."));
|
|
44
|
+
line();
|
|
45
|
+
info("Opening your browser…");
|
|
46
|
+
const start = await startDeviceAuthorization(authBase, deviceLabel());
|
|
47
|
+
// Where the browser goes to authorize this request.
|
|
48
|
+
//
|
|
49
|
+
// The API decides the PATH — /cli/authorize on the main Carrier OS site — and
|
|
50
|
+
// the overrides below only ever swap the origin, so a local override cannot
|
|
51
|
+
// send the browser to a page that does not exist. Precedence: explicit config
|
|
52
|
+
// `platformUrl` → env CARRIEROS_PLATFORM_URL → a localhost guess when the API
|
|
53
|
+
// is local but pointed at a production site → otherwise trust the API.
|
|
54
|
+
const apiUri = start.verification_uri_complete || start.verification_uri;
|
|
55
|
+
const override = ctx.config.get("platformUrl") ||
|
|
56
|
+
process.env.CARRIEROS_PLATFORM_URL ||
|
|
57
|
+
localAuthorizeDefault(apiUrl, apiUri);
|
|
58
|
+
const openUrl = withPlatformOrigin(apiUri, override);
|
|
59
|
+
const opened = openBrowser(openUrl);
|
|
60
|
+
line();
|
|
61
|
+
line(" " + (opened ? chalk.green("✓") + " Browser opened." : chalk.yellow("!") + " Couldn't open your browser."));
|
|
62
|
+
line();
|
|
63
|
+
// Persistent fallback (Claude-style): always offer the URL to sign in manually.
|
|
64
|
+
line(" " + c.dim("Browser didn't open? Use the URL below to sign in:"));
|
|
65
|
+
line(" " + c.brand(openUrl));
|
|
66
|
+
line();
|
|
67
|
+
// Waiting state — a single in-place spinner (never scrolls). Polling is
|
|
68
|
+
// unchanged; the spinner just animates until it resolves or throws.
|
|
69
|
+
const tokens = await withSpinner(chalk.dim("Waiting for approval…"), () => pollForToken(authBase, start));
|
|
70
|
+
return renderAuthorized(ctx, tokens, apiUrl);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The website's own "Not you? Use a different account" for this request: it signs
|
|
74
|
+
* that browser out of whoever is signed in there, shows the sign-in form, and
|
|
75
|
+
* returns to the same /cli/authorize request (code intact) for the account just
|
|
76
|
+
* signed in — which approves it there, as always.
|
|
77
|
+
*/
|
|
78
|
+
export function switchAccountUrl(openUrl) {
|
|
79
|
+
const u = new URL(openUrl);
|
|
80
|
+
return `${u.origin}/sign-in?switch=1&redirectTo=${encodeURIComponent(u.pathname + u.search)}`;
|
|
81
|
+
}
|
|
82
|
+
/** The success sequence — a short animated checklist, then persist + verify,
|
|
83
|
+
* ending on "Logged in as <email>" (the shell then pauses + shows the welcome). */
|
|
84
|
+
async function renderAuthorized(ctx, tokens, apiUrl) {
|
|
85
|
+
const ok = (msg) => line(" " + chalk.green("✓") + " " + msg);
|
|
86
|
+
line();
|
|
87
|
+
ok("Device authorized");
|
|
88
|
+
await sleep(150);
|
|
89
|
+
const scope = await persistSession(ctx, tokens, apiUrl);
|
|
90
|
+
ok("Session synchronized");
|
|
91
|
+
await sleep(130);
|
|
92
|
+
const email = scope.user?.email ?? tokens.account?.email;
|
|
93
|
+
if (email) {
|
|
94
|
+
line();
|
|
95
|
+
line(" Logged in as " + c.value(email));
|
|
96
|
+
}
|
|
97
|
+
return scope;
|
|
98
|
+
}
|
|
99
|
+
/** Save the issued tokens + a cached scope; land in Standard chat by default.
|
|
100
|
+
* (Unchanged behaviour — persistence + a verify to confirm the token works.) */
|
|
101
|
+
export async function persistSession(ctx, tokens, issuer) {
|
|
102
|
+
ctx.config.update({
|
|
103
|
+
auth: {
|
|
104
|
+
accessToken: tokens.access_token,
|
|
105
|
+
refreshToken: tokens.refresh_token,
|
|
106
|
+
// Which server issued this session. Only its refusal ends the session.
|
|
107
|
+
apiUrl: issuer,
|
|
108
|
+
account: tokens.account,
|
|
109
|
+
workspace: tokens.workspace ?? null,
|
|
110
|
+
project: tokens.project ?? null
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
// A conversation keeps its type forever. Reset the saved session too: a
|
|
114
|
+
// previous conversation must not resume under a different account.
|
|
115
|
+
ctx.setChatType("standard");
|
|
116
|
+
ctx.config.set("sessionTitle", undefined);
|
|
117
|
+
let scope;
|
|
118
|
+
try {
|
|
119
|
+
scope = await ctx.client().verify();
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
scope = scopeFromTokens(tokens);
|
|
123
|
+
}
|
|
124
|
+
ctx.config.set("scope", scope);
|
|
125
|
+
return scope;
|
|
126
|
+
}
|
|
127
|
+
function scopeFromTokens(tokens) {
|
|
128
|
+
return {
|
|
129
|
+
apiKey: null,
|
|
130
|
+
workspace: tokens.workspace ?? null,
|
|
131
|
+
project: tokens.project ?? null,
|
|
132
|
+
user: tokens.account ? { id: tokens.account.id, email: tokens.account.email } : null
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Render a single, minimal ✗ line for a failed login. Returns the category. */
|
|
136
|
+
export function renderLoginFailure(err, apiUrl) {
|
|
137
|
+
const code = err instanceof ApiError ? err.code : "other";
|
|
138
|
+
const fail = (msg) => line(" " + chalk.red("✗") + " " + msg);
|
|
139
|
+
line();
|
|
140
|
+
if (code === "ACCESS_DENIED") {
|
|
141
|
+
fail("Authorization cancelled in the browser.");
|
|
142
|
+
return "denied";
|
|
143
|
+
}
|
|
144
|
+
if (code === "EXPIRED_TOKEN" || code === "TIMEOUT") {
|
|
145
|
+
fail("Login timed out — the code expired before it was approved.");
|
|
146
|
+
return "expired";
|
|
147
|
+
}
|
|
148
|
+
if (code === "NETWORK_ERROR" || code.startsWith("HTTP_")) {
|
|
149
|
+
fail("Couldn't reach the server.");
|
|
150
|
+
if (apiUrl)
|
|
151
|
+
line(" " + c.dim(apiUrl));
|
|
152
|
+
return "network";
|
|
153
|
+
}
|
|
154
|
+
fail(err instanceof ApiError ? `${err.message} (${err.code})` : String(err?.message ?? err));
|
|
155
|
+
return "other";
|
|
156
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
/** The CLI's own version — from the baked constant when packaged, else package.json. */
|
|
4
|
+
export function cliVersion() {
|
|
5
|
+
if (typeof __CLI_VERSION__ === "string" && __CLI_VERSION__)
|
|
6
|
+
return __CLI_VERSION__;
|
|
7
|
+
try {
|
|
8
|
+
const pkgUrl = new URL("../../package.json", import.meta.url);
|
|
9
|
+
const pkg = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf8"));
|
|
10
|
+
return pkg.version ?? "0.0.0";
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return "0.0.0";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Which client is talking to the API, sent on every request:
|
|
18
|
+
*
|
|
19
|
+
* X-CarrierOS-Client: cli/0.4.1 | cli-exe/0.4.1 | vscode/0.2.1
|
|
20
|
+
* X-CarrierOS-Channel: latest | beta | next | staging (when known)
|
|
21
|
+
*
|
|
22
|
+
* Only the client kind, its version and its release channel — never a path,
|
|
23
|
+
* user name, token or anything else from the machine. Servers that do not read
|
|
24
|
+
* these headers ignore them, so older APIs are unaffected.
|
|
25
|
+
*/
|
|
26
|
+
let clientKind = "cli";
|
|
27
|
+
let clientVersionOverride = null;
|
|
28
|
+
let releaseChannel = null;
|
|
29
|
+
/** Set once at startup: "cli-exe" for the packaged build, "vscode" for the extension. */
|
|
30
|
+
export function setClientIdentity(kind, version) {
|
|
31
|
+
clientKind = kind;
|
|
32
|
+
clientVersionOverride = version && /^[0-9A-Za-z.+-]{1,64}$/.test(version) ? version : null;
|
|
33
|
+
}
|
|
34
|
+
export function setClientReleaseChannel(channel) {
|
|
35
|
+
releaseChannel = channel && /^(latest|beta|next|staging)$/.test(channel) ? channel : null;
|
|
36
|
+
}
|
|
37
|
+
export function clientHeaders() {
|
|
38
|
+
return {
|
|
39
|
+
"X-CarrierOS-Client": `${clientKind}/${clientVersionOverride ?? cliVersion()}`,
|
|
40
|
+
...(releaseChannel ? { "X-CarrierOS-Channel": releaseChannel } : {})
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createMutationGroup, startGroupMember, appliedGroupMember, failGroupMember, pruneSettledEvidence, reconcileMutationGroups } from "./mutation-groups.js";
|
|
3
|
+
import { MAX_FILES_PER_APPROVAL, APPROVAL_TIMEOUT_MS, MAX_MUTATIONS_PER_TURN, MAX_REVIEW_LINES, MutationError, appliedResult, applyPlan, assertPlanCurrent, planMutation, reviewLineCount, rollbackApplied } from "./mutations.js";
|
|
4
|
+
import { inWorkspaceMode } from "./workspace-registry.js";
|
|
5
|
+
const VERB = {
|
|
6
|
+
create_file: "Created",
|
|
7
|
+
write_file: "Overwrote",
|
|
8
|
+
edit_file: "Edited",
|
|
9
|
+
delete_file: "Deleted",
|
|
10
|
+
revert_change: "Reverted"
|
|
11
|
+
};
|
|
12
|
+
export function createMutationCoordinator(opts) {
|
|
13
|
+
const windowMs = opts.windowMs ?? 150;
|
|
14
|
+
const { ui } = opts;
|
|
15
|
+
const queue = [];
|
|
16
|
+
const applied = [];
|
|
17
|
+
let received = 0;
|
|
18
|
+
let timer = null;
|
|
19
|
+
let chain = Promise.resolve();
|
|
20
|
+
let stopped = false;
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
const submitOnce = (p, result) => {
|
|
23
|
+
// Transport owns retrying this exact result. A later batch error must never
|
|
24
|
+
// synthesize a contradictory second result for an already-finalized call.
|
|
25
|
+
if (p.result)
|
|
26
|
+
return Promise.resolve();
|
|
27
|
+
p.result = result;
|
|
28
|
+
// Recorded locally before the server can see it (see `record`). Bookkeeping
|
|
29
|
+
// never blocks delivery of a result that is already final.
|
|
30
|
+
try {
|
|
31
|
+
opts.record?.(result);
|
|
32
|
+
}
|
|
33
|
+
catch { /* the finalized result is still delivered */ }
|
|
34
|
+
return opts.submit(result);
|
|
35
|
+
};
|
|
36
|
+
const fail = (p, code, message) => submitOnce(p, {
|
|
37
|
+
tool_call_id: p.call.tool_call_id,
|
|
38
|
+
ok: false,
|
|
39
|
+
error: { code, message },
|
|
40
|
+
duration_ms: Date.now() - p.started
|
|
41
|
+
});
|
|
42
|
+
const succeed = (p, change) => submitOnce(p, {
|
|
43
|
+
tool_call_id: p.call.tool_call_id,
|
|
44
|
+
ok: true,
|
|
45
|
+
result: appliedResult(change),
|
|
46
|
+
duration_ms: Date.now() - p.started
|
|
47
|
+
});
|
|
48
|
+
async function review(batch) {
|
|
49
|
+
if (opts.signal?.aborted) {
|
|
50
|
+
stopped = true;
|
|
51
|
+
await Promise.all(batch.map(p => fail(p, "MUTATION_CANCELLED", "The turn was cancelled. Nothing was changed.")));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (stopped) {
|
|
55
|
+
// A "no" ends proposals for the turn. The model asks the user what they
|
|
56
|
+
// want instead of offering variations until one is accepted.
|
|
57
|
+
const message = "Further changes are stopped for this turn. Review the earlier rejection or unresolved failure with the user before proceeding.";
|
|
58
|
+
ui.refused?.({ files: batch.map((p) => p.call.arguments?.path).filter((x) => typeof x === "string"), code: "MUTATIONS_STOPPED", message });
|
|
59
|
+
await Promise.all(batch.map((p) => fail(p, "MUTATION_REJECTED", message)));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// Plan everything first. A proposal that cannot be planned is answered
|
|
63
|
+
// straight away — nothing touched disk, so there is nothing to approve.
|
|
64
|
+
const ready = [];
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
for (const p of batch) {
|
|
67
|
+
try {
|
|
68
|
+
const plan = planMutation(p.call);
|
|
69
|
+
// Two repositories can hold the same relative path, so identity here is
|
|
70
|
+
// the repository AND the path.
|
|
71
|
+
const key = `${plan.repositoryId}:${plan.rel.toLowerCase()}`;
|
|
72
|
+
if (seen.has(key)) {
|
|
73
|
+
const message = `${plan.rel} is already changed by another proposal in this step. Propose one change per file.`;
|
|
74
|
+
ui.refused?.({ files: [plan.rel], code: "CONFLICTING_CHANGE", message });
|
|
75
|
+
await fail(p, "CONFLICTING_CHANGE", message);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (reviewLineCount(plan) > MAX_REVIEW_LINES) {
|
|
79
|
+
const message = `The change to ${plan.rel} is too large to review. Split it into smaller edits.`;
|
|
80
|
+
ui.refused?.({ files: [plan.rel], code: "DIFF_TOO_LARGE", message });
|
|
81
|
+
await fail(p, "DIFF_TOO_LARGE", message);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
seen.add(key);
|
|
85
|
+
ready.push({ p, plan });
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
const e = err instanceof MutationError ? err : new MutationError("TOOL_FAILED", err.message);
|
|
89
|
+
const rel = p.call.arguments?.path;
|
|
90
|
+
ui.refused?.({ files: typeof rel === "string" ? [rel] : [], code: e.code, message: e.message });
|
|
91
|
+
await fail(p, e.code, e.message);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (ready.length === 0)
|
|
95
|
+
return;
|
|
96
|
+
// One approval, one repository.
|
|
97
|
+
//
|
|
98
|
+
// A group is approved as a unit, with verified rollback on failure. "All" has to
|
|
99
|
+
// mean something a person can hold in their head: these files, in this
|
|
100
|
+
// repository. A group spanning two repositories would ask for one yes
|
|
101
|
+
// covering two boundaries, and a rollback would have to reach across both.
|
|
102
|
+
// It is refused rather than split, because splitting it would decide on the
|
|
103
|
+
// user's behalf which half they meant.
|
|
104
|
+
const repositories = [...new Set(ready.map((r) => r.plan.repositoryId))];
|
|
105
|
+
if (repositories.length > 1) {
|
|
106
|
+
const names = [...new Set(ready.map((r) => r.plan.repositoryName))].join(", ");
|
|
107
|
+
ui.note([` ⊘ One change group cannot span ${names} — nothing was changed.`]);
|
|
108
|
+
ui.refused?.({ files: ready.map((r) => r.plan.rel), code: "MULTI_REPOSITORY_MUTATION_NOT_ALLOWED",
|
|
109
|
+
message: `A single change cannot span more than one repository (${names}). Nothing was changed.` });
|
|
110
|
+
await Promise.all(ready.map((r) => fail(r.p, "MULTI_REPOSITORY_MUTATION_NOT_ALLOWED", `A single change cannot span more than one repository (${names}). Nothing was changed. Propose the changes for each repository as a separate operation.`)));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const approvalScope = opts.recoveryScope?.();
|
|
114
|
+
const fingerprint = () => createHash("sha256").update(JSON.stringify({ plans: ready.map(r => ({ plan: r.plan, callId: r.p.call.tool_call_id })), workflow: opts.approvalContext?.() })).digest("hex");
|
|
115
|
+
const reviewedHash = fingerprint();
|
|
116
|
+
const approvalDeadline = Date.now() + APPROVAL_TIMEOUT_MS;
|
|
117
|
+
try {
|
|
118
|
+
opts.validatePlans?.(ready.map(r => r.plan));
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
ui.refused?.({ files: ready.map((r) => r.plan.rel), code: "CODING_WORKFLOW_BLOCKED", message: error.message });
|
|
122
|
+
await Promise.all(ready.map(r => fail(r.p, "CODING_WORKFLOW_BLOCKED", error.message)));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// The decision comes from the person, or from the session's Accept Edits
|
|
126
|
+
// policy — never from the model. Either way the checks after it (cancel,
|
|
127
|
+
// fingerprint, deadline, scope, freshness, checkpoint) still decide whether
|
|
128
|
+
// anything is written.
|
|
129
|
+
let decision;
|
|
130
|
+
if (opts.approveEditsByPolicy?.() === true) {
|
|
131
|
+
ui.approvedByPolicy?.(ready.map((r) => r.plan));
|
|
132
|
+
decision = "approve";
|
|
133
|
+
}
|
|
134
|
+
else
|
|
135
|
+
decision = await ui.review(ready.map((r) => r.plan));
|
|
136
|
+
if (opts.signal?.aborted) {
|
|
137
|
+
stopped = true;
|
|
138
|
+
await Promise.all(ready.map(r => fail(r.p, "MUTATION_CANCELLED", "The turn was cancelled during review. Nothing was changed.")));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (decision !== "approve") {
|
|
142
|
+
const code = decision === "timeout" ? "APPROVAL_TIMEOUT" : decision === "cancel" ? "MUTATION_CANCELLED" : "MUTATION_REJECTED";
|
|
143
|
+
const message = decision === "timeout"
|
|
144
|
+
? "No one approved the change in time. Nothing was changed."
|
|
145
|
+
: decision === "cancel"
|
|
146
|
+
? "The turn was cancelled during review. Nothing was changed."
|
|
147
|
+
: "The user rejected the change. Nothing was changed.";
|
|
148
|
+
if (decision === "reject" && ui.rejected)
|
|
149
|
+
ui.rejected(ready.map((r) => r.plan));
|
|
150
|
+
else
|
|
151
|
+
ui.note([decision === "timeout" ? " ⊘ Approval timed out — nothing changed." : decision === "cancel" ? " ⊘ Cancelled — nothing changed." : " ⊘ Rejected — nothing changed."]);
|
|
152
|
+
stopped = true;
|
|
153
|
+
await Promise.all(ready.map((r) => fail(r.p, code, message)));
|
|
154
|
+
if (decision === "cancel")
|
|
155
|
+
ui.cancelTurn();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (Date.now() >= approvalDeadline || fingerprint() !== reviewedHash || opts.recoveryScope?.() !== approvalScope) {
|
|
159
|
+
stopped = true;
|
|
160
|
+
const message = "The proposal, identity or approval deadline changed during review. Nothing was written. Request a fresh review.";
|
|
161
|
+
// The person said yes; tell them why nothing happened.
|
|
162
|
+
ui.applyFailed?.({ code: "APPROVAL_INVALIDATED", message, rolledBack: [], unresolved: [], notApplied: ready.map((r) => r.plan.rel) });
|
|
163
|
+
await Promise.all(ready.map(r => fail(r.p, "APPROVAL_INVALIDATED", message)));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// The approval was for diffs computed from specific bytes. Before the first
|
|
167
|
+
// write, every member must still be based on what is on disk — otherwise
|
|
168
|
+
// the whole group is refused (nothing written) and needs a fresh proposal
|
|
169
|
+
// and approval. applyPlan repeats the check per file immediately before its
|
|
170
|
+
// write, which still covers a change racing in between.
|
|
171
|
+
const stale = [];
|
|
172
|
+
for (const r of ready) {
|
|
173
|
+
try {
|
|
174
|
+
assertPlanCurrent(r.plan);
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
stale.push({ ...r, error: err instanceof MutationError ? err : new MutationError("STALE_FILE", err.message) });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (stale.length) {
|
|
181
|
+
const rels = stale.map((s) => s.plan.rel);
|
|
182
|
+
if (ui.noLongerValid)
|
|
183
|
+
ui.noLongerValid(rels);
|
|
184
|
+
else
|
|
185
|
+
ui.note([` ⊘ Change no longer valid: ${rels.join(", ")} changed after this review. Nothing was written.`]);
|
|
186
|
+
await Promise.all(ready.map((r) => {
|
|
187
|
+
const s = stale.find((x) => x.p === r.p);
|
|
188
|
+
return s
|
|
189
|
+
? fail(r.p, s.error.code, `${r.plan.rel} changed after this review. The proposed diff is no longer based on the current file. Nothing was written; propose the change again from a fresh read for a new review.`)
|
|
190
|
+
: fail(r.p, "NOT_APPLIED", `Not applied because ${rels.join(", ")} changed after this review. Nothing was written.`);
|
|
191
|
+
}));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
let group;
|
|
195
|
+
const root = ready[0].plan.repositoryRoot;
|
|
196
|
+
const scope = opts.recoveryScope?.();
|
|
197
|
+
// Settled history only; never fails the batch (see pruneSettledEvidence).
|
|
198
|
+
pruneSettledEvidence(root);
|
|
199
|
+
if (ready.length > 1) {
|
|
200
|
+
try {
|
|
201
|
+
group = createMutationGroup(ready.map(r => r.plan), scope);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
stopped = true;
|
|
205
|
+
ui.note([" ✗ Group intent could not be persisted. No target files were changed; available recovery evidence was preserved."]);
|
|
206
|
+
ui.applyFailed?.({ code: "GROUP_PERSISTENCE_FAILED", message: "Group intent could not be persisted. No target files were changed.",
|
|
207
|
+
rolledBack: [], unresolved: [], notApplied: ready.map(r => r.plan.rel) });
|
|
208
|
+
await Promise.all(ready.map(r => fail(r.p, "GROUP_PERSISTENCE_FAILED", "Group intent could not be persisted. No target files were changed.")));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const reconcileGroup = () => {
|
|
213
|
+
if (!group)
|
|
214
|
+
return;
|
|
215
|
+
try {
|
|
216
|
+
const report = reconcileMutationGroups(scope).groups.find(g => g.groupId === group.group_id);
|
|
217
|
+
if (report)
|
|
218
|
+
ui.note([report.message]);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
ui.note([`Group ${group.group_id}: recovery state is unresolved; evidence was preserved.`]);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
// Approved: apply in order; verify each rollback and report unresolved files.
|
|
225
|
+
const done = [];
|
|
226
|
+
for (let i = 0; i < ready.length; i += 1) {
|
|
227
|
+
const { p, plan } = ready[i];
|
|
228
|
+
try {
|
|
229
|
+
if (opts.signal?.aborted)
|
|
230
|
+
throw new MutationError("MUTATION_CANCELLED", "The turn was cancelled before mutation. Nothing further was applied.");
|
|
231
|
+
const prepared = group ? startGroupMember(root, group.group_id, plan.operationId) : undefined;
|
|
232
|
+
done.push({ p, change: applyPlan(plan, scope, prepared, opts.signal) });
|
|
233
|
+
if (group)
|
|
234
|
+
appliedGroupMember(root, group.group_id, plan.operationId);
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
const e = err instanceof MutationError ? err : new MutationError("WRITE_FAILED", err.message);
|
|
238
|
+
if (group) {
|
|
239
|
+
try {
|
|
240
|
+
failGroupMember(root, group.group_id, plan.operationId);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
ui.note([`Group ${group.group_id}: failure state could not be persisted; recovery evidence retained.`]);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const outcomes = [...done].reverse().map(d => ({ ...d, restored: rollbackApplied(d.change) }));
|
|
247
|
+
const unresolved = outcomes.filter(d => !d.restored);
|
|
248
|
+
if (unresolved.length || e.code === "MUTATION_UNRESOLVED" || e.code === "MUTATION_CANCELLED")
|
|
249
|
+
stopped = true;
|
|
250
|
+
ui.note([` ✗ ${plan.rel}: ${e.message}`,
|
|
251
|
+
...outcomes.map(d => d.restored
|
|
252
|
+
? ` ↺ ${d.change.repositoryName}/${d.change.rel}: rolled back.`
|
|
253
|
+
: ` ✗ ${d.change.repositoryName}/${d.change.rel}: rollback unresolved; file may remain modified. Recovery checkpoint ${d.change.checkpointId} preserved.`)]);
|
|
254
|
+
ui.applyFailed?.({
|
|
255
|
+
failed: plan.rel, code: e.code, message: e.message,
|
|
256
|
+
rolledBack: outcomes.filter(d => d.restored).map(d => d.change.rel),
|
|
257
|
+
// The failing file itself may also be left modified (its own recovery unresolved).
|
|
258
|
+
unresolved: [...unresolved.map(d => ({ rel: d.change.rel, checkpointId: d.change.checkpointId })),
|
|
259
|
+
...(e.recovery?.unresolved ? [{ rel: plan.rel, checkpointId: e.recovery.checkpointId }] : [])],
|
|
260
|
+
notApplied: ready.slice(i + 1).map(r => r.plan.rel)
|
|
261
|
+
});
|
|
262
|
+
reconcileGroup();
|
|
263
|
+
await Promise.all([
|
|
264
|
+
...outcomes.map((d) => fail(d.p, d.restored ? "ROLLED_BACK" : "ROLLBACK_UNRESOLVED", d.restored ? `Rolled back because the change to ${plan.rel} failed.`
|
|
265
|
+
: `${d.change.repositoryName}/${d.change.rel}: rollback unresolved; file may remain modified. Recovery checkpoint ${d.change.checkpointId} (operation ${d.change.operationId}) preserved.`)),
|
|
266
|
+
...(done.some(d => d.p === p) ? [] : [fail(p, e.code, e.message)]),
|
|
267
|
+
...ready.slice(i + 1).map((r) => fail(r.p, "NOT_APPLIED", `Not applied because the change to ${plan.rel} failed.`))
|
|
268
|
+
]);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
reconcileGroup();
|
|
273
|
+
applied.push(...done.map((d) => d.change));
|
|
274
|
+
ui.note(done.map((d) => {
|
|
275
|
+
// Say WHICH repository once the workspace has more than one; in a single
|
|
276
|
+
// repository the name would be noise on every line.
|
|
277
|
+
const where = inWorkspaceMode() ? `${d.change.repositoryName}/` : "";
|
|
278
|
+
return ` ✓ ${VERB[d.change.name] ?? "Changed"} ${where}${d.change.rel} (+${d.change.added} −${d.change.removed}) · Applied · ${d.change.operationId}`;
|
|
279
|
+
}));
|
|
280
|
+
await Promise.all(done.map((d) => succeed(d.p, d.change)));
|
|
281
|
+
}
|
|
282
|
+
function flush() {
|
|
283
|
+
timer = null;
|
|
284
|
+
const batch = queue.splice(0, MAX_FILES_PER_APPROVAL);
|
|
285
|
+
if (queue.length)
|
|
286
|
+
timer = setTimeout(flush, 0);
|
|
287
|
+
chain = chain
|
|
288
|
+
.then(() => review(batch))
|
|
289
|
+
.catch(async () => {
|
|
290
|
+
// Preserve finalized payloads; outbox retry must not become a second,
|
|
291
|
+
// contradictory submission after one member's transport failed.
|
|
292
|
+
if (batch.some(p => p.result))
|
|
293
|
+
ui.note(["Result delivery did not complete. Any saved results can be retried without rerunning file changes."]);
|
|
294
|
+
await Promise.all(batch.map((p) => fail(p, "TOOL_FAILED", "The change could not be processed.").catch(() => undefined)));
|
|
295
|
+
})
|
|
296
|
+
.finally(() => batch.forEach((p) => p.done()));
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
applied,
|
|
300
|
+
handle(call) {
|
|
301
|
+
// A repeated id is the same call: it is reviewed and answered at most once.
|
|
302
|
+
if (seen.has(call.tool_call_id))
|
|
303
|
+
return Promise.resolve();
|
|
304
|
+
seen.add(call.tool_call_id);
|
|
305
|
+
const started = Date.now();
|
|
306
|
+
received += 1;
|
|
307
|
+
if (received > MAX_MUTATIONS_PER_TURN) {
|
|
308
|
+
return opts
|
|
309
|
+
.submit({
|
|
310
|
+
tool_call_id: call.tool_call_id,
|
|
311
|
+
ok: false,
|
|
312
|
+
error: {
|
|
313
|
+
code: "MUTATION_LIMIT_REACHED",
|
|
314
|
+
message: `At most ${MAX_MUTATIONS_PER_TURN} file changes can be proposed in one turn.`
|
|
315
|
+
},
|
|
316
|
+
duration_ms: 0
|
|
317
|
+
})
|
|
318
|
+
.catch(() => undefined);
|
|
319
|
+
}
|
|
320
|
+
return new Promise((resolve) => {
|
|
321
|
+
queue.push({ call, started, done: resolve });
|
|
322
|
+
if (!timer)
|
|
323
|
+
timer = setTimeout(flush, windowMs);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
}
|