@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,221 @@
|
|
|
1
|
+
import { cliVersion } from "./meta.js";
|
|
2
|
+
import { acquireUpdateLock, checkChannel, compareVersions, defaultUpdateChannel, detectInstallation, installedGlobalVersion, isUpdateChannel, manualUpdateCommand, otherLiveInstances, packageName, registerInstance, releaseUpdateLock, startDetachedInstall, updateInProgress } from "./update.js";
|
|
3
|
+
/**
|
|
4
|
+
* Automatic updates for the npm-installed CLI (Claude Code-style).
|
|
5
|
+
*
|
|
6
|
+
* • Checks the configured channel at startup (when the last check is older
|
|
7
|
+
* than the interval) and then every interval while the CLI runs. Checks are
|
|
8
|
+
* async, one at a time, and never block the composer.
|
|
9
|
+
* • A newer release on a writable global npm install is installed in the
|
|
10
|
+
* BACKGROUND WHEN YOU EXIT, by a detached `npm install -g <pkg>@<exact>`,
|
|
11
|
+
* and only if no other CLI window is still open — a running CLI never has
|
|
12
|
+
* its package replaced underneath it. The next launch verifies the result
|
|
13
|
+
* (it is running the new version, or it is not) and says so once.
|
|
14
|
+
* • Local, development, npx and unwritable installs are never modified; they
|
|
15
|
+
* get the right manual instruction, once per version.
|
|
16
|
+
* • Nothing here prints directly: notices go to `notify`, which the shell
|
|
17
|
+
* shows between turns, never in the middle of one.
|
|
18
|
+
*
|
|
19
|
+
* The Windows installer build has its own verified updater (packaged-update.ts)
|
|
20
|
+
* and is not handled here.
|
|
21
|
+
*/
|
|
22
|
+
export const DEFAULT_CHECK_INTERVAL_HOURS = 6;
|
|
23
|
+
const MIN_INTERVAL_HOURS = 1;
|
|
24
|
+
const MAX_INTERVAL_HOURS = 168;
|
|
25
|
+
export function updateSettings(config) {
|
|
26
|
+
const hours = Number(config.get("updateCheckIntervalHours"));
|
|
27
|
+
const channel = config.get("updateChannel");
|
|
28
|
+
return {
|
|
29
|
+
autoUpdates: config.get("autoUpdates") !== false && process.env.CARRIEROS_DISABLE_AUTOUPDATE !== "1",
|
|
30
|
+
// A staging package always follows the staging tag. This prevents a stale
|
|
31
|
+
// or manually copied production preference from making it query the wrong
|
|
32
|
+
// channel or recommend the production package.
|
|
33
|
+
channel: packageName() === "@carrieros/cli-staging"
|
|
34
|
+
? "staging"
|
|
35
|
+
: isUpdateChannel(channel) ? channel : defaultUpdateChannel(),
|
|
36
|
+
intervalHours: Number.isFinite(hours) && hours > 0
|
|
37
|
+
? Math.min(MAX_INTERVAL_HOURS, Math.max(MIN_INTERVAL_HOURS, Math.round(hours)))
|
|
38
|
+
: DEFAULT_CHECK_INTERVAL_HOURS
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export class AutoUpdater {
|
|
42
|
+
opts;
|
|
43
|
+
checking = null;
|
|
44
|
+
timer = null;
|
|
45
|
+
pending = null;
|
|
46
|
+
install = null;
|
|
47
|
+
unregister = null;
|
|
48
|
+
current;
|
|
49
|
+
installation;
|
|
50
|
+
now;
|
|
51
|
+
constructor(opts) {
|
|
52
|
+
this.opts = opts;
|
|
53
|
+
this.current = opts.current ?? cliVersion;
|
|
54
|
+
this.installation = opts.installation ?? (() => detectInstallation());
|
|
55
|
+
this.now = opts.now ?? Date.now;
|
|
56
|
+
}
|
|
57
|
+
/** The version that will be installed on exit, if any. */
|
|
58
|
+
get pendingVersion() {
|
|
59
|
+
return this.pending;
|
|
60
|
+
}
|
|
61
|
+
/** Begin: report the last background install, register this window, check. */
|
|
62
|
+
start() {
|
|
63
|
+
// Never run inside an update's own child process.
|
|
64
|
+
if (process.env.CARRIEROS_UPDATING === "1")
|
|
65
|
+
return;
|
|
66
|
+
this.unregister = registerInstance(this.opts.dir);
|
|
67
|
+
this.reportPreviousInstall();
|
|
68
|
+
const { intervalHours } = updateSettings(this.opts.config);
|
|
69
|
+
if (this.due(intervalHours))
|
|
70
|
+
setImmediate(() => void this.check());
|
|
71
|
+
// Not due for a fresh check: still act on the last result we know about, so
|
|
72
|
+
// an update skipped in an earlier session (another window was open, the
|
|
73
|
+
// folder was read-only…) is not forgotten until the next network check.
|
|
74
|
+
else
|
|
75
|
+
setImmediate(() => void this.actOnCached());
|
|
76
|
+
this.timer = setInterval(() => void this.check(), intervalHours * 3600_000);
|
|
77
|
+
this.timer.unref?.();
|
|
78
|
+
}
|
|
79
|
+
stop() {
|
|
80
|
+
if (this.timer)
|
|
81
|
+
clearInterval(this.timer);
|
|
82
|
+
this.timer = null;
|
|
83
|
+
this.unregister?.();
|
|
84
|
+
this.unregister = null;
|
|
85
|
+
}
|
|
86
|
+
due(intervalHours) {
|
|
87
|
+
const last = Math.max(this.opts.config.get("updateCheckAt") ?? 0, this.opts.config.get("updateCheckErrorAt") ?? 0);
|
|
88
|
+
return this.now() - last >= intervalHours * 3600_000;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The outcome of an install started when an earlier session exited. Verified
|
|
92
|
+
* by what is actually running now — never assumed from npm's exit code.
|
|
93
|
+
*/
|
|
94
|
+
reportPreviousInstall() {
|
|
95
|
+
const pending = this.opts.config.get("pendingUpdate");
|
|
96
|
+
if (!pending)
|
|
97
|
+
return;
|
|
98
|
+
if (this.current() === pending.version) {
|
|
99
|
+
this.opts.notify(`CarrierOS CLI ${pending.version} has been installed successfully.`);
|
|
100
|
+
this.opts.config.set("pendingUpdate", undefined);
|
|
101
|
+
this.opts.config.set("updateFailedVersion", undefined);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// Still running in the background: say nothing yet.
|
|
105
|
+
if (updateInProgress(this.opts.dir, this.now()))
|
|
106
|
+
return;
|
|
107
|
+
const channel = packageName() === "@carrieros/cli-staging"
|
|
108
|
+
? "staging"
|
|
109
|
+
: isUpdateChannel(pending.channel) ? pending.channel : defaultUpdateChannel();
|
|
110
|
+
this.opts.notify(`CarrierOS CLI could not be updated automatically. You can update manually using: ${manualUpdateCommand(channel)}`);
|
|
111
|
+
// Not retried automatically: a failing install would otherwise repeat on every exit.
|
|
112
|
+
this.opts.config.set("updateFailedVersion", pending.version);
|
|
113
|
+
this.opts.config.set("pendingUpdate", undefined);
|
|
114
|
+
}
|
|
115
|
+
/** One check at a time; a call while one runs waits for that one. */
|
|
116
|
+
check() {
|
|
117
|
+
if (!this.checking) {
|
|
118
|
+
this.checking = this.runCheck().finally(() => {
|
|
119
|
+
this.checking = null;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return this.checking;
|
|
123
|
+
}
|
|
124
|
+
/** Act on the cached latest version, without contacting the registry. */
|
|
125
|
+
async actOnCached() {
|
|
126
|
+
const latest = this.opts.config.get("latestCliVersion");
|
|
127
|
+
const current = this.current();
|
|
128
|
+
if (!latest)
|
|
129
|
+
return;
|
|
130
|
+
try {
|
|
131
|
+
if (compareVersions(latest, current) <= 0)
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
await this.act(latest, current);
|
|
138
|
+
}
|
|
139
|
+
async runCheck() {
|
|
140
|
+
const { channel } = updateSettings(this.opts.config);
|
|
141
|
+
let state;
|
|
142
|
+
try {
|
|
143
|
+
state = await checkChannel(channel, this.current());
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
this.opts.config.set("updateCheckErrorAt", this.now());
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (state.kind === "unreachable" || state.kind === "no-npm" || state.kind === "no-channel") {
|
|
150
|
+
// Recorded, never shown: an offline registry is not the user's problem.
|
|
151
|
+
this.opts.config.set("updateCheckErrorAt", this.now());
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
this.opts.config.set("latestCliVersion", state.latest);
|
|
155
|
+
this.opts.config.set("updateCheckAt", this.now());
|
|
156
|
+
if (state.kind !== "available")
|
|
157
|
+
return;
|
|
158
|
+
await this.act(state.latest, state.current);
|
|
159
|
+
}
|
|
160
|
+
/** A newer version is known: arrange the background install or tell the user how to update. */
|
|
161
|
+
async act(version, current) {
|
|
162
|
+
const { autoUpdates, channel } = updateSettings(this.opts.config);
|
|
163
|
+
const install = await this.installation().catch(() => ({ kind: "unknown" }));
|
|
164
|
+
this.install = install;
|
|
165
|
+
const name = packageName();
|
|
166
|
+
const failedBefore = this.opts.config.get("updateFailedVersion") === version;
|
|
167
|
+
if (autoUpdates && install.kind === "global" && install.writable && !failedBefore) {
|
|
168
|
+
this.pending = version;
|
|
169
|
+
this.notifyOnce(version, "auto", `CarrierOS CLI ${version} is available. You are currently using ${current}. It will be installed in the background when you exit.`);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (install.kind === "global" && !install.writable) {
|
|
173
|
+
this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Your global npm folder is not writable, so update manually: ${manualUpdateCommand(channel, name)}`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (install.kind === "local") {
|
|
177
|
+
this.notifyOnce(version, "local", `CarrierOS CLI ${version} is available. This copy is a project dependency — update it with your package manager, e.g. npm install ${name}@${version}`);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (install.kind === "npx") {
|
|
181
|
+
this.notifyOnce(version, "npx", `CarrierOS CLI ${version} is available. Run npx ${name}@${channel} to use it.`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (install.kind === "development")
|
|
185
|
+
return; // a checkout follows its own branch
|
|
186
|
+
this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Run /update to install it.`);
|
|
187
|
+
}
|
|
188
|
+
/** Each notice once per version and kind — across sessions. */
|
|
189
|
+
notifyOnce(version, kind, message) {
|
|
190
|
+
const key = `${version}:${kind}`;
|
|
191
|
+
if (this.opts.config.get("updateNoticeShown") === key)
|
|
192
|
+
return;
|
|
193
|
+
this.opts.config.set("updateNoticeShown", key);
|
|
194
|
+
this.opts.notify(message);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Leaving the CLI: start the pending background install. Skipped while
|
|
198
|
+
* another CLI window is open (it would have files replaced under it) or
|
|
199
|
+
* another update holds the lock; the next exit tries again.
|
|
200
|
+
*/
|
|
201
|
+
onExit() {
|
|
202
|
+
this.stop();
|
|
203
|
+
const version = this.pending;
|
|
204
|
+
if (!version)
|
|
205
|
+
return false;
|
|
206
|
+
// Already on disk (e.g. /update ran during the session): nothing to do.
|
|
207
|
+
if (this.install?.globalRoot && installedGlobalVersion(this.install.globalRoot) === version)
|
|
208
|
+
return false;
|
|
209
|
+
if (otherLiveInstances(this.opts.dir) > 0)
|
|
210
|
+
return false;
|
|
211
|
+
if (!acquireUpdateLock(this.opts.dir, process.pid, this.now()))
|
|
212
|
+
return false;
|
|
213
|
+
const { channel } = updateSettings(this.opts.config);
|
|
214
|
+
if (!startDetachedInstall(this.opts.dir, version)) {
|
|
215
|
+
releaseUpdateLock(this.opts.dir);
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
this.opts.config.set("pendingUpdate", { version, channel, startedAt: this.now() });
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/** Thrown for every way a stream can end other than `complete`. */
|
|
2
|
+
/**
|
|
3
|
+
* The server's structured provider-failure reasons (`reason` on a stream
|
|
4
|
+
* `error`), so a surface can tell them apart without reading the message.
|
|
5
|
+
* Anything else the server sends is dropped, never shown.
|
|
6
|
+
*/
|
|
7
|
+
export const PROVIDER_ERROR_REASONS = {
|
|
8
|
+
rate_limited: "Rate limited",
|
|
9
|
+
quota_daily: "Quota exhausted",
|
|
10
|
+
provider_credits: "Credits exhausted",
|
|
11
|
+
provider_request_failed: "Provider error",
|
|
12
|
+
provider_config: "Configuration error",
|
|
13
|
+
provider_auth: "Authentication error"
|
|
14
|
+
};
|
|
15
|
+
export function providerErrorReason(value) {
|
|
16
|
+
return typeof value === "string" && Object.hasOwn(PROVIDER_ERROR_REASONS, value) ? value : undefined;
|
|
17
|
+
}
|
|
18
|
+
export class StreamError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
status;
|
|
21
|
+
reason;
|
|
22
|
+
constructor(code, message, status = 0, reason) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.reason = reason;
|
|
27
|
+
this.name = "StreamError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Map the server's `complete` payload onto the synchronous endpoint's shape. */
|
|
31
|
+
export function completeToResult(d) {
|
|
32
|
+
return {
|
|
33
|
+
id: d.message_id ?? null,
|
|
34
|
+
response: typeof d.content === "string" ? d.content : "",
|
|
35
|
+
session_id: d.session_id,
|
|
36
|
+
tokens_used: Number(d.tokens_used ?? 0) || 0,
|
|
37
|
+
cost_usd: typeof d.cost_usd === "number" ? d.cost_usd : undefined,
|
|
38
|
+
credits_remaining: typeof d.credits_remaining === "number" ? d.credits_remaining : null,
|
|
39
|
+
credits_unlimited: typeof d.credits_unlimited === "boolean" ? d.credits_unlimited : null,
|
|
40
|
+
credits_spent: typeof d.credits_spent === "number" ? d.credits_spent : null,
|
|
41
|
+
sources: Array.isArray(d.sources) ? d.sources : [],
|
|
42
|
+
web_search_used: d.web_search_used === true,
|
|
43
|
+
high_power_used: d.high_power_used === true,
|
|
44
|
+
speed: d.speed === "fast" ? "fast" : d.speed === "standard" ? "standard" : undefined,
|
|
45
|
+
model: typeof d.model === "string" ? d.model : undefined
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Consume an SSE body until `complete`, `error`, `interrupted` or the socket
|
|
50
|
+
* ends. Frames are `data: {"type":…,"data":…}` separated by a blank line;
|
|
51
|
+
* `: ping` comments and the `[DONE]` sentinel carry nothing.
|
|
52
|
+
*/
|
|
53
|
+
export function consumeChatStream(body, handlers = {}, signal) {
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
let buffer = "";
|
|
56
|
+
let settled = false;
|
|
57
|
+
const finish = (fn) => {
|
|
58
|
+
if (settled)
|
|
59
|
+
return;
|
|
60
|
+
settled = true;
|
|
61
|
+
signal?.removeEventListener?.("abort", onAbort);
|
|
62
|
+
fn();
|
|
63
|
+
};
|
|
64
|
+
function onAbort() {
|
|
65
|
+
finish(() => reject(new StreamError("ABORTED", "Interrupted.")));
|
|
66
|
+
try {
|
|
67
|
+
body.destroy?.();
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
/* already closed */
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (signal?.aborted) {
|
|
74
|
+
onAbort();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
signal?.addEventListener?.("abort", onAbort, { once: true });
|
|
78
|
+
const dispatch = (type, data) => {
|
|
79
|
+
switch (type) {
|
|
80
|
+
case "message_created":
|
|
81
|
+
handlers.onMessageCreated?.(data);
|
|
82
|
+
return;
|
|
83
|
+
case "chunk":
|
|
84
|
+
if (typeof data.delta === "string" && data.delta)
|
|
85
|
+
handlers.onDelta?.(data.delta);
|
|
86
|
+
return;
|
|
87
|
+
case "status":
|
|
88
|
+
case "tool_status":
|
|
89
|
+
if (typeof data.message === "string")
|
|
90
|
+
handlers.onStatus?.(type, data.message);
|
|
91
|
+
return;
|
|
92
|
+
case "client_tool_call": {
|
|
93
|
+
if (!handlers.onClientToolCall)
|
|
94
|
+
return;
|
|
95
|
+
// Never let a tool handler's failure — or its duration — stall the
|
|
96
|
+
// parser: the server keeps streaming while it waits for the result.
|
|
97
|
+
void Promise.resolve()
|
|
98
|
+
.then(() => handlers.onClientToolCall(data))
|
|
99
|
+
.catch((error) => {
|
|
100
|
+
if (error?.code === "TOOL_RESULT_DELIVERY_FAILED") {
|
|
101
|
+
finish(() => reject(new StreamError("TOOL_RESULT_DELIVERY_FAILED", "Tool result delivery failed. Saved results will be retried before the next chat; tools are not rerun.")));
|
|
102
|
+
body.destroy?.();
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
case "complete":
|
|
108
|
+
finish(() => resolve(completeToResult(data)));
|
|
109
|
+
return;
|
|
110
|
+
case "interrupted":
|
|
111
|
+
finish(() => reject(signal?.aborted
|
|
112
|
+
? new StreamError("ABORTED", "Interrupted.")
|
|
113
|
+
: new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
|
|
114
|
+
return;
|
|
115
|
+
case "error":
|
|
116
|
+
finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.", 0, providerErrorReason(data.reason))));
|
|
117
|
+
return;
|
|
118
|
+
default:
|
|
119
|
+
return; // generation_type and anything newer: nothing to do
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const drain = () => {
|
|
123
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
124
|
+
let sep = buffer.indexOf("\n\n");
|
|
125
|
+
while (sep !== -1) {
|
|
126
|
+
const block = buffer.slice(0, sep);
|
|
127
|
+
buffer = buffer.slice(sep + 2);
|
|
128
|
+
const payload = block
|
|
129
|
+
.split("\n")
|
|
130
|
+
.filter((l) => l.startsWith("data:"))
|
|
131
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
132
|
+
.join("\n");
|
|
133
|
+
if (payload && payload !== "[DONE]") {
|
|
134
|
+
try {
|
|
135
|
+
const frame = JSON.parse(payload);
|
|
136
|
+
if (frame?.type)
|
|
137
|
+
dispatch(frame.type, frame.data ?? {});
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
/* a malformed frame is skipped, never fatal */
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (settled)
|
|
144
|
+
return;
|
|
145
|
+
sep = buffer.indexOf("\n\n");
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
body.setEncoding?.("utf8");
|
|
149
|
+
body.on("data", (chunk) => {
|
|
150
|
+
if (settled)
|
|
151
|
+
return;
|
|
152
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
153
|
+
drain();
|
|
154
|
+
});
|
|
155
|
+
body.on("end", () => {
|
|
156
|
+
if (settled)
|
|
157
|
+
return;
|
|
158
|
+
buffer += "\n\n";
|
|
159
|
+
drain();
|
|
160
|
+
finish(() => reject(new StreamError("STREAM_ENDED", "The connection closed before the response finished.")));
|
|
161
|
+
});
|
|
162
|
+
body.on("error", () => {
|
|
163
|
+
finish(() => reject(signal?.aborted
|
|
164
|
+
? new StreamError("ABORTED", "Interrupted.")
|
|
165
|
+
: new StreamError("NETWORK_ERROR", "The connection to the API dropped mid-response.")));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { folderKey } from "./folder-key.js";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ConfigStore } from "./config.js";
|
|
6
|
+
/**
|
|
7
|
+
* Checkpoints and the change journal for supervised file edits.
|
|
8
|
+
*
|
|
9
|
+
* Kept in the CLI's own app-data folder, per workspace — never inside the
|
|
10
|
+
* repository. A change can be undone whether or not the file was ever committed,
|
|
11
|
+
* nothing ends up in `git status`, and Git is not a dependency of the safety
|
|
12
|
+
* net. This is not a version-control system: it keeps enough to restore the
|
|
13
|
+
* last few approved changes, and prunes the rest.
|
|
14
|
+
*
|
|
15
|
+
* What a checkpoint holds is the ORIGINAL bytes of one file, plus whether it
|
|
16
|
+
* existed and its mode. That is the only file content the CLI ever retains, it
|
|
17
|
+
* stays on the machine, and credential files never get one because they are
|
|
18
|
+
* refused before a change is planned.
|
|
19
|
+
*/
|
|
20
|
+
/** Changes remembered per workspace; older checkpoints are deleted. */
|
|
21
|
+
const MAX_ENTRIES = 50;
|
|
22
|
+
export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
|
|
23
|
+
/**
|
|
24
|
+
* The identity of a repository's checkpoint store: a hash of its normalized
|
|
25
|
+
* root. Exported so a journal entry can record which store it was written to,
|
|
26
|
+
* and an undo can prove it is reading the right one.
|
|
27
|
+
*/
|
|
28
|
+
export function repositoryKey(root) {
|
|
29
|
+
// Canonical (real path, case-folded on Windows): a repository opened through a
|
|
30
|
+
// symlink must find the same evidence its changes wrote. Unchanged for any
|
|
31
|
+
// root whose resolved path is already its real path.
|
|
32
|
+
return sha256(folderKey(root)).slice(0, 16);
|
|
33
|
+
}
|
|
34
|
+
/** One directory per repository root, keyed by a hash of its normalized path. */
|
|
35
|
+
export function workspaceDir(root) {
|
|
36
|
+
const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
|
|
37
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
40
|
+
const journalFile = (root) => path.join(workspaceDir(root), "journal.json");
|
|
41
|
+
export class RecoveryStateError extends Error {
|
|
42
|
+
constructor(message = "Recovery state is unreadable or inconsistent. Existing evidence was preserved.") {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "RecoveryStateError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Waits between rename attempts while a Windows scanner or editor holds the target. */
|
|
48
|
+
export const RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80];
|
|
49
|
+
const LOCKED = new Set(["EPERM", "EBUSY", "EACCES"]);
|
|
50
|
+
/**
|
|
51
|
+
* renameSync that tolerates a transient Windows sharing lock (antivirus, the
|
|
52
|
+
* search indexer, an editor): EPERM/EBUSY/EACCES are retried a bounded number
|
|
53
|
+
* of times with a short backoff — on Windows only, where those codes mean a
|
|
54
|
+
* lock rather than a permission. Cancellation stops the retries. When they run
|
|
55
|
+
* out, the ORIGINAL error is thrown, so callers fail exactly as before.
|
|
56
|
+
*/
|
|
57
|
+
export function renameWithRetry(from, to, opts = {}) {
|
|
58
|
+
const rename = opts.rename ?? fs.renameSync;
|
|
59
|
+
const wait = opts.wait ?? ((ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms));
|
|
60
|
+
const retries = (opts.platform ?? process.platform) === "win32" ? RENAME_RETRY_DELAYS_MS : [];
|
|
61
|
+
for (let attempt = 0;; attempt++) {
|
|
62
|
+
try {
|
|
63
|
+
rename(from, to);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
const code = err.code ?? "";
|
|
68
|
+
if (!LOCKED.has(code) || attempt >= retries.length || opts.signal?.aborted)
|
|
69
|
+
throw err;
|
|
70
|
+
wait(retries[attempt]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Atomic publication with file fsync; directory fsync where supported. */
|
|
75
|
+
export function durableWrite(file, data) {
|
|
76
|
+
const tmp = `${file}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
77
|
+
try {
|
|
78
|
+
const fd = fs.openSync(tmp, "wx", 0o600);
|
|
79
|
+
try {
|
|
80
|
+
fs.writeFileSync(fd, data);
|
|
81
|
+
fs.fsyncSync(fd);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
renameWithRetry(tmp, file);
|
|
87
|
+
if (process.platform !== "win32") {
|
|
88
|
+
const dir = fs.openSync(path.dirname(file), "r");
|
|
89
|
+
try {
|
|
90
|
+
fs.fsyncSync(dir);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
fs.closeSync(dir);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
try {
|
|
99
|
+
fs.unlinkSync(tmp);
|
|
100
|
+
}
|
|
101
|
+
catch { /* absent after publication */ }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export function readJournal(root) {
|
|
105
|
+
try {
|
|
106
|
+
const file = journalFile(root);
|
|
107
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 2 * 1024 * 1024)
|
|
108
|
+
throw new RecoveryStateError();
|
|
109
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
110
|
+
if (!Array.isArray(parsed) || parsed.some(e => !e || typeof e.operation_id !== "string" ||
|
|
111
|
+
typeof e.path !== "string" || typeof e.checkpoint_id !== "string" ||
|
|
112
|
+
!["EXECUTED", "ROLLED_BACK", "FAILED"].includes(e.status)) ||
|
|
113
|
+
new Set(parsed.map(e => e.operation_id)).size !== parsed.length)
|
|
114
|
+
throw new RecoveryStateError();
|
|
115
|
+
return parsed;
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
if (err.code === "ENOENT")
|
|
119
|
+
return [];
|
|
120
|
+
throw new RecoveryStateError("Mutation journal is unreadable. It was preserved; history cannot be replaced or assumed empty.");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function writeJournal(root, entries) {
|
|
124
|
+
durableWrite(journalFile(root), JSON.stringify(entries, null, 2));
|
|
125
|
+
}
|
|
126
|
+
export function newCheckpointId() {
|
|
127
|
+
return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
|
|
128
|
+
}
|
|
129
|
+
/** Save a file's original bytes before it is changed. */
|
|
130
|
+
export function saveCheckpoint(root, checkpointId, original) {
|
|
131
|
+
if (original === null)
|
|
132
|
+
return; // nothing existed — undo means delete
|
|
133
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.before`);
|
|
134
|
+
durableWrite(file, original);
|
|
135
|
+
}
|
|
136
|
+
export function loadCheckpoint(root, checkpointId) {
|
|
137
|
+
try {
|
|
138
|
+
if (!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(checkpointId))
|
|
139
|
+
return null;
|
|
140
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.before`);
|
|
141
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 1024 * 1024)
|
|
142
|
+
return null;
|
|
143
|
+
return fs.readFileSync(file);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export function saveRecoveryReceipt(root, checkpointId, metadata) {
|
|
150
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.recovery.json`);
|
|
151
|
+
if (fs.existsSync(file))
|
|
152
|
+
throw new RecoveryStateError();
|
|
153
|
+
durableWrite(file, JSON.stringify({ ...metadata, checkpoint_id: checkpointId, repository_key: repositoryKey(root) }));
|
|
154
|
+
}
|
|
155
|
+
export const MAX_RECOVERY_SCAN = 100;
|
|
156
|
+
export function recoveryReceipts(root) {
|
|
157
|
+
const receipts = [];
|
|
158
|
+
let problems = 0;
|
|
159
|
+
const dir = workspaceDir(root);
|
|
160
|
+
const names = [];
|
|
161
|
+
// Bound directory traversal, not only the number of parsed JSON records.
|
|
162
|
+
let visited = 0, bounded = false;
|
|
163
|
+
const directory = fs.opendirSync(dir);
|
|
164
|
+
try {
|
|
165
|
+
let entry;
|
|
166
|
+
while ((entry = directory.readSync()) !== null) {
|
|
167
|
+
if (++visited > MAX_RECOVERY_SCAN * 4) {
|
|
168
|
+
bounded = true;
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
if (entry.name.endsWith(".recovery.json"))
|
|
172
|
+
names.push(entry.name);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
directory.closeSync();
|
|
177
|
+
}
|
|
178
|
+
if (names.length > MAX_RECOVERY_SCAN)
|
|
179
|
+
bounded = true;
|
|
180
|
+
for (const name of names.slice(0, MAX_RECOVERY_SCAN)) {
|
|
181
|
+
try {
|
|
182
|
+
const file = path.join(dir, name);
|
|
183
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 64 * 1024)
|
|
184
|
+
throw new RecoveryStateError();
|
|
185
|
+
const r = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
186
|
+
const hashValid = (exists, hash) => typeof exists === "boolean" &&
|
|
187
|
+
(exists ? typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash) : hash === null);
|
|
188
|
+
if ((r.group_id !== undefined && !/^grp_[a-f0-9]{32}$/.test(r.group_id)) ||
|
|
189
|
+
r.version !== 2 || r.approved !== true || r.repository_key !== repositoryKey(root) ||
|
|
190
|
+
typeof r.operation_id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(r.operation_id) || typeof r.repository_id !== "string" ||
|
|
191
|
+
typeof r.repository_name !== "string" || typeof r.path !== "string" ||
|
|
192
|
+
!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(r.checkpoint_id) || name !== `${r.checkpoint_id}.recovery.json` ||
|
|
193
|
+
!["create_file", "write_file", "edit_file", "delete_file", "revert_change"].includes(r.action) ||
|
|
194
|
+
!["prepared", "applied", "verified", "rolled_back", "unresolved"].includes(r.phase) ||
|
|
195
|
+
!["none", "ready", "queued", "acknowledged", "rejected"].includes(r.delivery) ||
|
|
196
|
+
typeof r.journal_persisted !== "boolean" || !Number.isFinite(Date.parse(r.created_at)) ||
|
|
197
|
+
!hashValid(r.before_exists, r.before_sha) || !hashValid(r.after_exists, r.after_sha) ||
|
|
198
|
+
(r.scope !== undefined && !/^[a-f0-9]{64}$/.test(r.scope)) ||
|
|
199
|
+
(r.result && (r.result.tool_call_id !== r.operation_id || typeof r.result.ok !== "boolean")) ||
|
|
200
|
+
(r.delivery !== "none" && !r.result))
|
|
201
|
+
throw new RecoveryStateError();
|
|
202
|
+
receipts.push(r);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
problems++;
|
|
206
|
+
} // No content, malformed paths or credentials in diagnostics.
|
|
207
|
+
}
|
|
208
|
+
const counts = new Map();
|
|
209
|
+
for (const r of receipts)
|
|
210
|
+
counts.set(r.operation_id, (counts.get(r.operation_id) ?? 0) + 1);
|
|
211
|
+
return { receipts: receipts.filter(r => {
|
|
212
|
+
if (counts.get(r.operation_id) > 1) {
|
|
213
|
+
problems++;
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
return true;
|
|
217
|
+
}), problems, bounded };
|
|
218
|
+
}
|
|
219
|
+
export function updateRecoveryReceipt(root, checkpointId, patch) {
|
|
220
|
+
const scan = recoveryReceipts(root);
|
|
221
|
+
const r = scan.receipts.find(e => e.checkpoint_id === checkpointId);
|
|
222
|
+
if (!r)
|
|
223
|
+
throw new RecoveryStateError();
|
|
224
|
+
if (r.result && patch.result && JSON.stringify(r.result) !== JSON.stringify(patch.result))
|
|
225
|
+
throw new RecoveryStateError();
|
|
226
|
+
durableWrite(path.join(workspaceDir(root), `${checkpointId}.recovery.json`), JSON.stringify({ ...r, ...patch }));
|
|
227
|
+
}
|
|
228
|
+
/** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
|
|
229
|
+
export function appendEntry(root, entry) {
|
|
230
|
+
const entries = [...readJournal(root), entry];
|
|
231
|
+
const dropped = entries.length > MAX_ENTRIES ? entries.splice(0, entries.length - MAX_ENTRIES) : [];
|
|
232
|
+
writeJournal(root, entries);
|
|
233
|
+
for (const d of dropped) {
|
|
234
|
+
try {
|
|
235
|
+
const receipt = recoveryReceipts(root).receipts.find(r => r.checkpoint_id === d.checkpoint_id);
|
|
236
|
+
if (!receipt || receipt.group_id || !receipt.journal_persisted || !["verified", "rolled_back"].includes(receipt.phase) ||
|
|
237
|
+
(receipt.scope && !["acknowledged", "rejected"].includes(receipt.delivery)))
|
|
238
|
+
continue;
|
|
239
|
+
fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`), { force: true });
|
|
240
|
+
fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.recovery.json`), { force: true });
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
/* already gone */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
export function updateEntry(root, operationId, patch) {
|
|
248
|
+
const entries = readJournal(root);
|
|
249
|
+
const i = entries.findIndex((e) => e.operation_id === operationId);
|
|
250
|
+
if (i === -1)
|
|
251
|
+
return;
|
|
252
|
+
entries[i] = { ...entries[i], ...patch };
|
|
253
|
+
writeJournal(root, entries);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The change `/undo` (or `revert_change` without an id) should undo: the most
|
|
257
|
+
* recent applied change that has not already been undone. Reverts are skipped,
|
|
258
|
+
* so undoing twice walks back two changes rather than toggling one.
|
|
259
|
+
*/
|
|
260
|
+
export function latestRevertible(root, operationId, repositoryId) {
|
|
261
|
+
const key = repositoryKey(root);
|
|
262
|
+
// An entry has to belong to THIS repository's store. Entries written before
|
|
263
|
+
// repository identity existed carry neither field and are accepted on the
|
|
264
|
+
// strength of the directory they were found in; anything that names a
|
|
265
|
+
// different repository is refused rather than restored.
|
|
266
|
+
const mine = (e) => (e.repository_key === undefined || e.repository_key === key) &&
|
|
267
|
+
(repositoryId === undefined || e.repository_id === undefined || e.repository_id === repositoryId);
|
|
268
|
+
const entries = readJournal(root).filter(mine);
|
|
269
|
+
if (operationId) {
|
|
270
|
+
return entries.find((e) => e.operation_id === operationId && e.status === "EXECUTED" && !e.reverts) ?? null;
|
|
271
|
+
}
|
|
272
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
273
|
+
const e = entries[i];
|
|
274
|
+
if (e.status === "EXECUTED" && !e.reverts)
|
|
275
|
+
return e;
|
|
276
|
+
}
|
|
277
|
+
return null;
|
|
278
|
+
}
|