@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
import { EventEmitter } from 'events'
|
|
2
|
+
import { randomUUID } from 'crypto'
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'fs'
|
|
4
|
+
import { join } from 'path'
|
|
5
|
+
import { homedir } from 'os'
|
|
6
|
+
import { execFile as execFileCb } from 'child_process'
|
|
7
|
+
import { promisify } from 'util'
|
|
8
|
+
import { writeFileRestricted } from './platform.js'
|
|
9
|
+
import { GIT } from './git.js'
|
|
10
|
+
import { createLogger } from './logger.js'
|
|
11
|
+
|
|
12
|
+
const log = createLogger('checkpoint')
|
|
13
|
+
|
|
14
|
+
const execFileAsync = promisify(execFileCb)
|
|
15
|
+
|
|
16
|
+
// Resolve at call time, not module-load time, so tests that set
|
|
17
|
+
// CHROXY_CONFIG_DIR in beforeEach are respected. Mirrors models.js and
|
|
18
|
+
// connection-info.js (#4633).
|
|
19
|
+
function defaultCheckpointsDir() {
|
|
20
|
+
const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
|
|
21
|
+
return join(configDir, 'checkpoints')
|
|
22
|
+
}
|
|
23
|
+
const MAX_CHECKPOINTS_PER_SESSION = 50
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Per-cwd async mutex map.
|
|
27
|
+
* Prevents concurrent checkpoint operations (create/restore) on the same
|
|
28
|
+
* working directory from interleaving git index/commit operations.
|
|
29
|
+
*/
|
|
30
|
+
const _cwdMutexes = new Map()
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Acquire an exclusive lock for the given cwd.
|
|
34
|
+
* Returns a release function — caller MUST call it in a finally block.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} cwd
|
|
37
|
+
* @returns {Promise<() => void>}
|
|
38
|
+
*/
|
|
39
|
+
async function acquireCwdLock(cwd) {
|
|
40
|
+
if (!_cwdMutexes.has(cwd)) {
|
|
41
|
+
_cwdMutexes.set(cwd, Promise.resolve())
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let release
|
|
45
|
+
const next = new Promise((resolve) => { release = resolve })
|
|
46
|
+
const current = _cwdMutexes.get(cwd)
|
|
47
|
+
_cwdMutexes.set(cwd, next)
|
|
48
|
+
|
|
49
|
+
await current
|
|
50
|
+
return () => release()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Manages checkpoint creation and restoration for session rewind.
|
|
55
|
+
*
|
|
56
|
+
* Each checkpoint captures:
|
|
57
|
+
* - The SDK session (conversation) ID at that point in time
|
|
58
|
+
* - A git snapshot ref for the file state (if in a git repo)
|
|
59
|
+
* - Metadata: timestamp, name, description, message count
|
|
60
|
+
*
|
|
61
|
+
* Git snapshots are stored as plain commit objects (not stash entries).
|
|
62
|
+
* This avoids touching the shared stash stack, making concurrent sessions
|
|
63
|
+
* in the same repository safe.
|
|
64
|
+
*
|
|
65
|
+
* Rewind creates a new session that resumes from the checkpoint's
|
|
66
|
+
* conversation ID, effectively branching the conversation.
|
|
67
|
+
*/
|
|
68
|
+
export class CheckpointManager extends EventEmitter {
|
|
69
|
+
/**
|
|
70
|
+
* @param {object} [options]
|
|
71
|
+
* @param {string} [options.checkpointsDir] - Override the on-disk directory
|
|
72
|
+
* for checkpoint state files. Defaults to `$CHROXY_CONFIG_DIR/checkpoints`
|
|
73
|
+
* (or `~/.chroxy/checkpoints` when unset). Tests should pass a tmp
|
|
74
|
+
* directory (or set `CHROXY_CONFIG_DIR`) to avoid contaminating the
|
|
75
|
+
* developer's real state (#4633).
|
|
76
|
+
*/
|
|
77
|
+
constructor(options = {}) {
|
|
78
|
+
super()
|
|
79
|
+
this._checkpoints = new Map() // sessionId -> Checkpoint[]
|
|
80
|
+
this._counters = new Map() // sessionId -> monotonic counter for default names
|
|
81
|
+
this._checkpointsDir = options.checkpointsDir || defaultCheckpointsDir()
|
|
82
|
+
// #5335: refs whose `git tag -d` failed (cwd -> Set<gitRef>). These are
|
|
83
|
+
// KNOWN orphans — the checkpoint they backed was already removed — so they
|
|
84
|
+
// can be retried later without any speculative "is this tag still live?"
|
|
85
|
+
// guess (which would race in-flight tag creation and, since tags are
|
|
86
|
+
// repo-global, delete a sibling worktree's live ref).
|
|
87
|
+
this._failedRefDeletes = new Map()
|
|
88
|
+
this._ensureDir()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
_ensureDir() {
|
|
92
|
+
if (!existsSync(this._checkpointsDir)) {
|
|
93
|
+
mkdirSync(this._checkpointsDir, { recursive: true })
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Create a checkpoint for a session.
|
|
99
|
+
* @param {object} params
|
|
100
|
+
* @param {string} params.sessionId - The Chroxy session ID
|
|
101
|
+
* @param {string} params.resumeSessionId - The SDK conversation ID at this point
|
|
102
|
+
* @param {string} params.cwd - Working directory for git operations
|
|
103
|
+
* @param {string} [params.name] - User-provided checkpoint name
|
|
104
|
+
* @param {string} [params.description] - Auto-generated description (e.g., last message)
|
|
105
|
+
* @param {number} [params.messageCount] - Number of messages at checkpoint time
|
|
106
|
+
* @returns {Promise<object>} The created checkpoint
|
|
107
|
+
*/
|
|
108
|
+
async createCheckpoint({ sessionId, resumeSessionId, cwd, name, description, messageCount }) {
|
|
109
|
+
const checkpoints = this._getCheckpoints(sessionId)
|
|
110
|
+
|
|
111
|
+
// Enforce max checkpoints — remove oldest if at limit
|
|
112
|
+
let evictedCwd = null
|
|
113
|
+
if (checkpoints.length >= MAX_CHECKPOINTS_PER_SESSION) {
|
|
114
|
+
const evicted = checkpoints.shift()
|
|
115
|
+
if (evicted?.gitRef) {
|
|
116
|
+
evictedCwd = evicted.cwd
|
|
117
|
+
this._deleteGitRefTracked(evicted.cwd, evicted.gitRef)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const checkpoint = {
|
|
122
|
+
id: randomUUID(),
|
|
123
|
+
sessionId,
|
|
124
|
+
resumeSessionId,
|
|
125
|
+
cwd,
|
|
126
|
+
name: name || `Checkpoint ${(this._counters.get(sessionId) || 0) + 1}`,
|
|
127
|
+
description: description || '',
|
|
128
|
+
messageCount: messageCount || 0,
|
|
129
|
+
createdAt: Date.now(),
|
|
130
|
+
gitRef: null,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Capture git state if in a git repo
|
|
134
|
+
const isGit = await this._isGitRepo(cwd)
|
|
135
|
+
if (isGit) {
|
|
136
|
+
const release = await acquireCwdLock(cwd)
|
|
137
|
+
try {
|
|
138
|
+
checkpoint.gitRef = await this._createGitSnapshot(cwd, checkpoint.id)
|
|
139
|
+
} finally {
|
|
140
|
+
release()
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
checkpoints.push(checkpoint)
|
|
145
|
+
this._counters.set(sessionId, (this._counters.get(sessionId) || 0) + 1)
|
|
146
|
+
this._checkpoints.set(sessionId, checkpoints)
|
|
147
|
+
// #5731 (T3): the checkpoint exists in memory and is returned to the client,
|
|
148
|
+
// but if the disk write failed it'll be gone on restart — surface that so the
|
|
149
|
+
// user isn't told their rewind point is saved when it isn't.
|
|
150
|
+
if (!this._persist(sessionId)) {
|
|
151
|
+
this.emit('checkpoint_persist_failed', { sessionId, checkpointId: checkpoint.id, operation: 'create' })
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// #5335: opportunistically retry any refs whose delete previously failed
|
|
155
|
+
// for this cwd, so transient `git tag -d` failures don't accrue. Race-free
|
|
156
|
+
// (only known orphans are retried) and fire-and-forget — never blocks or
|
|
157
|
+
// fails checkpoint creation.
|
|
158
|
+
if (evictedCwd) {
|
|
159
|
+
this.retryFailedRefDeletes(evictedCwd).catch((err) => {
|
|
160
|
+
log.warn(`retryFailedRefDeletes failed for ${evictedCwd}: ${err.message}`)
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
this.emit('checkpoint_created', checkpoint)
|
|
165
|
+
return checkpoint
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* List checkpoints for a session.
|
|
170
|
+
* @param {string} sessionId
|
|
171
|
+
* @returns {object[]} Array of checkpoints (newest last)
|
|
172
|
+
*/
|
|
173
|
+
listCheckpoints(sessionId) {
|
|
174
|
+
return this._getCheckpoints(sessionId).map((cp) => ({
|
|
175
|
+
id: cp.id,
|
|
176
|
+
name: cp.name,
|
|
177
|
+
description: cp.description,
|
|
178
|
+
messageCount: cp.messageCount,
|
|
179
|
+
createdAt: cp.createdAt,
|
|
180
|
+
hasGitSnapshot: !!cp.gitRef,
|
|
181
|
+
}))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Get a checkpoint by ID.
|
|
186
|
+
* @param {string} sessionId
|
|
187
|
+
* @param {string} checkpointId
|
|
188
|
+
* @returns {object|null}
|
|
189
|
+
*/
|
|
190
|
+
getCheckpoint(sessionId, checkpointId) {
|
|
191
|
+
return this._getCheckpoints(sessionId).find((cp) => cp.id === checkpointId) || null
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Restore file state from a checkpoint's git snapshot.
|
|
196
|
+
* Does NOT restore conversation state — that requires creating a new session
|
|
197
|
+
* with the checkpoint's resumeSessionId (handled by session-manager).
|
|
198
|
+
* @param {string} sessionId
|
|
199
|
+
* @param {string} checkpointId
|
|
200
|
+
* @returns {Promise<object>} The checkpoint data (including resumeSessionId)
|
|
201
|
+
*/
|
|
202
|
+
async restoreCheckpoint(sessionId, checkpointId) {
|
|
203
|
+
const checkpoint = this.getCheckpoint(sessionId, checkpointId)
|
|
204
|
+
if (!checkpoint) {
|
|
205
|
+
throw new Error(`Checkpoint not found: ${checkpointId}`)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Restore git state if snapshot exists
|
|
209
|
+
if (checkpoint.gitRef) {
|
|
210
|
+
const release = await acquireCwdLock(checkpoint.cwd)
|
|
211
|
+
try {
|
|
212
|
+
await this._restoreGitSnapshot(checkpoint.cwd, checkpoint.gitRef)
|
|
213
|
+
} finally {
|
|
214
|
+
release()
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
this.emit('checkpoint_restored', checkpoint)
|
|
219
|
+
return checkpoint
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Delete a checkpoint.
|
|
224
|
+
* @param {string} sessionId
|
|
225
|
+
* @param {string} checkpointId
|
|
226
|
+
*/
|
|
227
|
+
deleteCheckpoint(sessionId, checkpointId) {
|
|
228
|
+
const checkpoints = this._getCheckpoints(sessionId)
|
|
229
|
+
const idx = checkpoints.findIndex((cp) => cp.id === checkpointId)
|
|
230
|
+
if (idx === -1) return
|
|
231
|
+
|
|
232
|
+
const checkpoint = checkpoints[idx]
|
|
233
|
+
|
|
234
|
+
// Clean up git ref if present
|
|
235
|
+
if (checkpoint.gitRef) {
|
|
236
|
+
this._deleteGitRefTracked(checkpoint.cwd, checkpoint.gitRef)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
checkpoints.splice(idx, 1)
|
|
240
|
+
this._checkpoints.set(sessionId, checkpoints)
|
|
241
|
+
// #5731 (T3): a failed write here means the deleted checkpoint reappears on
|
|
242
|
+
// restart — surface it rather than silently "deleting" something that comes back.
|
|
243
|
+
if (!this._persist(sessionId)) {
|
|
244
|
+
this.emit('checkpoint_persist_failed', { sessionId, checkpointId, operation: 'delete' })
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Remove all checkpoints for a session.
|
|
250
|
+
* @param {string} sessionId
|
|
251
|
+
*/
|
|
252
|
+
clearCheckpoints(sessionId) {
|
|
253
|
+
const checkpoints = this._getCheckpoints(sessionId)
|
|
254
|
+
for (const cp of checkpoints) {
|
|
255
|
+
if (cp.gitRef) {
|
|
256
|
+
this._deleteGitRefTracked(cp.cwd, cp.gitRef)
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
this._checkpoints.delete(sessionId)
|
|
260
|
+
|
|
261
|
+
const file = join(this._checkpointsDir, `${sessionId}.json`)
|
|
262
|
+
if (existsSync(file)) {
|
|
263
|
+
try { unlinkSync(file) } catch { /* ignore */ }
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// -- Git operations --
|
|
268
|
+
|
|
269
|
+
async _isGitRepo(cwd) {
|
|
270
|
+
try {
|
|
271
|
+
await execFileAsync(GIT, ['rev-parse', '--is-inside-work-tree'], { cwd })
|
|
272
|
+
return true
|
|
273
|
+
} catch {
|
|
274
|
+
return false
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Create a snapshot of the current working tree state using a plain commit
|
|
280
|
+
* object, without touching the shared git stash stack.
|
|
281
|
+
*
|
|
282
|
+
* Strategy:
|
|
283
|
+
* 1. If the working tree is clean, tag HEAD directly.
|
|
284
|
+
* 2. Otherwise:
|
|
285
|
+
* a. Capture the current index state via `git write-tree`.
|
|
286
|
+
* b. Stage everything (tracked + untracked) with `git add -A`.
|
|
287
|
+
* c. Create a snapshot commit object via `git commit-tree` (no branch
|
|
288
|
+
* or ref is updated — the commit is dangling until we tag it).
|
|
289
|
+
* d. Tag the snapshot commit SHA.
|
|
290
|
+
* e. Restore the pre-snapshot index with `git read-tree` so the
|
|
291
|
+
* working tree is left exactly as it was.
|
|
292
|
+
*
|
|
293
|
+
* This never modifies refs/stash, so concurrent sessions operating on the
|
|
294
|
+
* same repository cannot corrupt each other. The per-cwd mutex in the
|
|
295
|
+
* caller serialises the git index operations within this process.
|
|
296
|
+
*/
|
|
297
|
+
async _createGitSnapshot(cwd, checkpointId) {
|
|
298
|
+
const tagName = `chroxy-checkpoint/${checkpointId}`
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
const { stdout: status } = await execFileAsync(
|
|
302
|
+
GIT, ['status', '--porcelain'],
|
|
303
|
+
{ cwd }
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
if (!status.trim()) {
|
|
307
|
+
// Working tree is clean — tag HEAD directly
|
|
308
|
+
await execFileAsync(GIT, ['tag', tagName, 'HEAD'], { cwd })
|
|
309
|
+
return tagName
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Capture the current index so we can restore it afterwards
|
|
313
|
+
const { stdout: savedIndexTree } = await execFileAsync(
|
|
314
|
+
GIT, ['write-tree'],
|
|
315
|
+
{ cwd }
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
// Stage everything including untracked files
|
|
319
|
+
await execFileAsync(GIT, ['add', '-A'], { cwd })
|
|
320
|
+
|
|
321
|
+
// Write the full working tree as a tree object
|
|
322
|
+
const { stdout: snapshotTree } = await execFileAsync(
|
|
323
|
+
GIT, ['write-tree'],
|
|
324
|
+
{ cwd }
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
// Create a dangling commit from the snapshot tree
|
|
328
|
+
const { stdout: snapshotSha } = await execFileAsync(
|
|
329
|
+
GIT, ['commit-tree', snapshotTree.trim(), '-p', 'HEAD', '-m', `chroxy-snapshot/${checkpointId}`],
|
|
330
|
+
{ cwd }
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
// Tag the snapshot commit for stable retrieval
|
|
334
|
+
await execFileAsync(GIT, ['tag', tagName, snapshotSha.trim()], { cwd })
|
|
335
|
+
|
|
336
|
+
// Restore the pre-snapshot index (leaves working tree untouched)
|
|
337
|
+
await execFileAsync(GIT, ['read-tree', savedIndexTree.trim()], { cwd })
|
|
338
|
+
|
|
339
|
+
return tagName
|
|
340
|
+
} catch (err) {
|
|
341
|
+
// Best-effort: restore the index if something went wrong mid-way
|
|
342
|
+
try { await execFileAsync(GIT, ['reset', 'HEAD'], { cwd }) } catch { /* ignore */ }
|
|
343
|
+
log.warn(`Failed to create git snapshot: ${err.message}`)
|
|
344
|
+
return null
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Restore file state from a git snapshot tag.
|
|
350
|
+
*
|
|
351
|
+
* The snapshot is a plain commit whose tree captures the full working-tree
|
|
352
|
+
* state at checkpoint time (tracked + untracked files). Restoring it is a
|
|
353
|
+
* two-step process:
|
|
354
|
+
*
|
|
355
|
+
* 1. Stash any current uncommitted changes so they are not lost (using
|
|
356
|
+
* `git stash push` here is intentional and safe because this is a
|
|
357
|
+
* user-initiated rewind operation where only one restore runs at a
|
|
358
|
+
* time under the per-cwd mutex).
|
|
359
|
+
* 2. Resolve the tag to its commit SHA and use `git checkout <sha> -- .`
|
|
360
|
+
* to overwrite all files in the working tree with the snapshot state.
|
|
361
|
+
*/
|
|
362
|
+
async _restoreGitSnapshot(cwd, gitRef) {
|
|
363
|
+
// #5335: we auto-stash the user's pending changes BEFORE resolving the tag.
|
|
364
|
+
// If anything after the stash fails (e.g. a corrupt/missing ref), the work
|
|
365
|
+
// would be silently orphaned in a stash. Track whether we stashed so the
|
|
366
|
+
// catch can put it back instead of leaving the user wedged.
|
|
367
|
+
let stashed = false
|
|
368
|
+
try {
|
|
369
|
+
// Stash any pending changes before restoring
|
|
370
|
+
const { stdout: status } = await execFileAsync(
|
|
371
|
+
GIT, ['status', '--porcelain'],
|
|
372
|
+
{ cwd }
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
if (status.trim()) {
|
|
376
|
+
await execFileAsync(GIT, ['stash', 'push', '-u', '-m', 'chroxy: auto-stash before rewind'], { cwd })
|
|
377
|
+
stashed = true
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Resolve the tag to the snapshot commit SHA
|
|
381
|
+
const { stdout: snapshotSha } = await execFileAsync(
|
|
382
|
+
GIT, ['rev-parse', gitRef],
|
|
383
|
+
{ cwd }
|
|
384
|
+
)
|
|
385
|
+
const { stdout: headCommit } = await execFileAsync(
|
|
386
|
+
GIT, ['rev-parse', 'HEAD'],
|
|
387
|
+
{ cwd }
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
const resolvedSha = snapshotSha.trim()
|
|
391
|
+
if (resolvedSha === headCommit.trim()) {
|
|
392
|
+
// Tag points to HEAD — working tree is already at the correct state.
|
|
393
|
+
// Leave the auto-stash parked, exactly like the checkout success path
|
|
394
|
+
// below: "restore to checkpoint" sets the user's pending changes aside
|
|
395
|
+
// (recoverable via the stash) rather than re-applying them over the
|
|
396
|
+
// restored state.
|
|
397
|
+
return
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// Checkout all files from the snapshot commit tree into the working tree.
|
|
401
|
+
// This handles both tracked modifications and files that were untracked
|
|
402
|
+
// at checkpoint time (they were staged and committed into the snapshot).
|
|
403
|
+
await execFileAsync(GIT, ['checkout', resolvedSha, '--', '.'], { cwd })
|
|
404
|
+
} catch (err) {
|
|
405
|
+
log.warn(`Failed to restore git snapshot: ${err.message}`)
|
|
406
|
+
// #5335: don't strand the auto-stashed changes. The common failure mode
|
|
407
|
+
// is a corrupt/missing ref, which throws at rev-parse BEFORE any checkout
|
|
408
|
+
// ran — so the tree is clean and the stash pops back cleanly.
|
|
409
|
+
if (stashed) {
|
|
410
|
+
try {
|
|
411
|
+
await execFileAsync(GIT, ['stash', 'pop'], { cwd })
|
|
412
|
+
} catch (popErr) {
|
|
413
|
+
// Pop failed (rare: a conflicting checkout ran before the failure).
|
|
414
|
+
// Point the user at the stash so the work isn't lost.
|
|
415
|
+
throw new Error(
|
|
416
|
+
`Git restore failed: ${err.message}. Your pending changes were auto-stashed but could not be re-applied (${popErr.message}) — recover them with \`git stash list\` / \`git stash pop\` (message: "chroxy: auto-stash before rewind")`
|
|
417
|
+
)
|
|
418
|
+
}
|
|
419
|
+
// Pop succeeded — the user's working state is intact.
|
|
420
|
+
throw new Error(`Git restore failed: ${err.message} (your pending changes were preserved)`)
|
|
421
|
+
}
|
|
422
|
+
throw new Error(`Git restore failed: ${err.message}`)
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Delete a checkpoint's git tag. Returns true if the tag is gone afterwards
|
|
427
|
+
// (deleted now, or already absent), false if the delete genuinely failed
|
|
428
|
+
// (e.g. a transient lock) so the caller can record it for retry.
|
|
429
|
+
async _deleteGitRef(cwd, gitRef) {
|
|
430
|
+
try {
|
|
431
|
+
await execFileAsync(GIT, ['tag', '-d', gitRef], { cwd })
|
|
432
|
+
return true
|
|
433
|
+
} catch (err) {
|
|
434
|
+
// "tag '...' not found" → already gone; treat as success.
|
|
435
|
+
if (/not found|No such|unknown tag/i.test(err.message || '')) return true
|
|
436
|
+
return false
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// #5335: best-effort delete of a checkpoint's ref that records the ref for a
|
|
441
|
+
// later retry if the delete fails, so a transient `git tag -d` failure does
|
|
442
|
+
// not leak a `chroxy-checkpoint/*` tag forever.
|
|
443
|
+
_deleteGitRefTracked(cwd, gitRef) {
|
|
444
|
+
this._deleteGitRef(cwd, gitRef).then((ok) => {
|
|
445
|
+
if (!ok) {
|
|
446
|
+
this._recordFailedRefDelete(cwd, gitRef)
|
|
447
|
+
log.warn(`Failed to delete git ref ${gitRef} (recorded for retry)`)
|
|
448
|
+
}
|
|
449
|
+
})
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
_recordFailedRefDelete(cwd, gitRef) {
|
|
453
|
+
if (!this._failedRefDeletes.has(cwd)) this._failedRefDeletes.set(cwd, new Set())
|
|
454
|
+
this._failedRefDeletes.get(cwd).add(gitRef)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Retry deleting refs whose previous delete failed for `cwd`. Race-free: only
|
|
459
|
+
* KNOWN orphans (a checkpoint we already removed) are retried — never a
|
|
460
|
+
* speculative classification of a repo-global tag — so this can never delete
|
|
461
|
+
* an in-flight or sibling-worktree checkpoint's ref.
|
|
462
|
+
* @param {string} cwd
|
|
463
|
+
* @returns {Promise<number>} number of orphaned refs successfully cleared
|
|
464
|
+
*/
|
|
465
|
+
async retryFailedRefDeletes(cwd) {
|
|
466
|
+
const set = this._failedRefDeletes.get(cwd)
|
|
467
|
+
if (!set || set.size === 0) return 0
|
|
468
|
+
let cleared = 0
|
|
469
|
+
for (const ref of [...set]) {
|
|
470
|
+
if (await this._deleteGitRef(cwd, ref)) { set.delete(ref); cleared++ }
|
|
471
|
+
}
|
|
472
|
+
if (set.size === 0) this._failedRefDeletes.delete(cwd)
|
|
473
|
+
if (cleared > 0) log.info(`Cleared ${cleared} previously-orphaned checkpoint ref(s) in ${cwd}`)
|
|
474
|
+
return cleared
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// -- Persistence --
|
|
478
|
+
|
|
479
|
+
_getCheckpoints(sessionId) {
|
|
480
|
+
if (!this._checkpoints.has(sessionId)) {
|
|
481
|
+
this._load(sessionId)
|
|
482
|
+
}
|
|
483
|
+
return this._checkpoints.get(sessionId) || []
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
_load(sessionId) {
|
|
487
|
+
const file = join(this._checkpointsDir, `${sessionId}.json`)
|
|
488
|
+
try {
|
|
489
|
+
if (existsSync(file)) {
|
|
490
|
+
const data = JSON.parse(readFileSync(file, 'utf8'))
|
|
491
|
+
this._checkpoints.set(sessionId, data.checkpoints || [])
|
|
492
|
+
} else {
|
|
493
|
+
this._checkpoints.set(sessionId, [])
|
|
494
|
+
}
|
|
495
|
+
} catch {
|
|
496
|
+
this._checkpoints.set(sessionId, [])
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// #5731 (T3): returns true on success, false if the write failed (disk full,
|
|
501
|
+
// locked file, read-only home). Callers emit `checkpoint_persist_failed` on
|
|
502
|
+
// false so the user is told their checkpoint wasn't durable instead of believing
|
|
503
|
+
// it was — the same silent-loss class fixed for session state in #5714.
|
|
504
|
+
_persist(sessionId) {
|
|
505
|
+
const file = join(this._checkpointsDir, `${sessionId}.json`)
|
|
506
|
+
const data = { version: 1, checkpoints: this._getCheckpoints(sessionId) }
|
|
507
|
+
try {
|
|
508
|
+
writeFileRestricted(file, JSON.stringify(data, null, 2))
|
|
509
|
+
return true
|
|
510
|
+
} catch (err) {
|
|
511
|
+
log.warn(`Failed to persist checkpoint for ${sessionId}: ${err.message}`)
|
|
512
|
+
return false
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createLogger } from './logger.js'
|
|
2
|
+
|
|
3
|
+
// Defensive fallback so the guard can NEVER throw a TypeError inside its own
|
|
4
|
+
// error handler if a future caller omits `log` — that would defeat the whole
|
|
5
|
+
// point of a crash-prevention guard (Copilot review). Both current callers
|
|
6
|
+
// pass their own session/provider logger.
|
|
7
|
+
const _fallbackLog = createLogger('child-stream-guard')
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Shared EPIPE guard for a spawned child's stdout/stderr (#5324/#5361).
|
|
11
|
+
*
|
|
12
|
+
* A stream-level 'error' (EPIPE on a dying child, a read fault) emitted on
|
|
13
|
+
* child.stdout/child.stderr with NO listener throws and crashes the WHOLE
|
|
14
|
+
* daemon — readline does not attach an error handler to its input, so each
|
|
15
|
+
* stream needs its own. We log + swallow: the matching process death already
|
|
16
|
+
* surfaces via 'close' (exit code) or 'error' (spawn failure), which drive
|
|
17
|
+
* teardown/respawn; the stream error itself carries no extra recoverable
|
|
18
|
+
* signal beyond "the pipe broke".
|
|
19
|
+
*
|
|
20
|
+
* Extracted from the byte-divergent copies in cli-session.js and
|
|
21
|
+
* jsonl-subprocess-session.js (audit P2-9). `destroying` is a GETTER, not a
|
|
22
|
+
* boolean: both call sites attach this before the `_destroying` flag can flip,
|
|
23
|
+
* so the guard must read it lazily on each error.
|
|
24
|
+
*
|
|
25
|
+
* @param {import('child_process').ChildProcess} child
|
|
26
|
+
* @param {{ destroying: () => boolean, log?: { warn: (m: string) => void }, label?: string }} opts
|
|
27
|
+
*/
|
|
28
|
+
export function guardChildStreams(child, { destroying, log = _fallbackLog, label } = {}) {
|
|
29
|
+
const prefix = label ? `[${label}] ` : ''
|
|
30
|
+
for (const name of ['stdout', 'stderr']) {
|
|
31
|
+
const stream = child?.[name]
|
|
32
|
+
if (!stream) continue
|
|
33
|
+
stream.on('error', (err) => {
|
|
34
|
+
if (destroying && destroying()) return
|
|
35
|
+
log.warn(`${prefix}${name} stream error (ignored): ${err?.message || err}`)
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
}
|