@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,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UserShellSession (#5983, epic #5982) — a PTY-only session that spawns the
|
|
3
|
+
* operator's `$SHELL` for a general-purpose terminal inside Chroxy, independent
|
|
4
|
+
* of any Claude session.
|
|
5
|
+
*
|
|
6
|
+
* This is the provider that ACTIVATES the security foundation built behind it:
|
|
7
|
+
* - `userShell.enabled` config gate (default OFF) — SessionManager.createSession (#5985a)
|
|
8
|
+
* - WS primary-token gate on create + every terminal_* op (#5985b)
|
|
9
|
+
* - excluded from the mailbox / isTui PTY-injection path (#5984)
|
|
10
|
+
*
|
|
11
|
+
* It deliberately does NOT inherit ClaudeTuiSession's machinery (resume,
|
|
12
|
+
* auto-respawn, conversation recovery, permission hook). A user shell has no
|
|
13
|
+
* "turns" and MUST NOT auto-respawn — per the #5985 swarm-audit (Guardian),
|
|
14
|
+
* typing `exit` resurrecting a fresh root shell is a footgun. Exit means gone.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { realpathSync, existsSync } from 'fs'
|
|
18
|
+
import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
|
|
19
|
+
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
20
|
+
import { createLogger } from './logger.js'
|
|
21
|
+
import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
|
|
22
|
+
|
|
23
|
+
const log = createLogger('user-shell-session')
|
|
24
|
+
|
|
25
|
+
// Match the claude-tui mirror grid so the dashboard renders shells at the same
|
|
26
|
+
// default size; a client resize overrides it via resizeTerminal.
|
|
27
|
+
const DEFAULT_COLS = 120
|
|
28
|
+
const DEFAULT_ROWS = 30
|
|
29
|
+
// Coalesce PTY bytes into one terminal_output per tick (bounds broadcast churn).
|
|
30
|
+
const MIRROR_FLUSH_MS = 50
|
|
31
|
+
// SIGTERM → grace → SIGKILL the process group on destroy.
|
|
32
|
+
const DESTROY_GRACE_MS = 3000
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Resolve the shell to spawn: `$SHELL` if it exists, then common fallbacks.
|
|
36
|
+
* Returns the first path that exists; if none do (a truly unusual host), falls
|
|
37
|
+
* back to `/bin/sh` as a last resort — start() then surfaces a clean spawn error
|
|
38
|
+
* if that path is also missing.
|
|
39
|
+
*/
|
|
40
|
+
function resolveShell() {
|
|
41
|
+
const shell = process.env.SHELL
|
|
42
|
+
if (typeof shell === 'string' && shell && existsSync(shell)) return shell
|
|
43
|
+
for (const cand of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
|
|
44
|
+
if (existsSync(cand)) return cand
|
|
45
|
+
}
|
|
46
|
+
return '/bin/sh'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class UserShellSession extends BaseSession {
|
|
50
|
+
static get displayLabel() {
|
|
51
|
+
return 'Shell'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// #5985b: this IS the general-purpose user shell — activates the WS
|
|
55
|
+
// primary-token terminal_* gates (create / subscribe / resize / input).
|
|
56
|
+
static get isUserShell() {
|
|
57
|
+
return true
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// #5984: NOT the claude-tui PTY mirror — stays false (inherited), so the
|
|
61
|
+
// mailbox wakeup / Control Room isTui path never targets a shell.
|
|
62
|
+
|
|
63
|
+
static get capabilities() {
|
|
64
|
+
return {
|
|
65
|
+
// No Claude semantics: no permission engine, model switch, plan mode,
|
|
66
|
+
// resume, thinking budget, streaming, or tool events. It is purely a PTY.
|
|
67
|
+
permissions: false,
|
|
68
|
+
inProcessPermissions: false,
|
|
69
|
+
modelSwitch: false,
|
|
70
|
+
permissionModeSwitch: false,
|
|
71
|
+
planMode: false,
|
|
72
|
+
resume: false,
|
|
73
|
+
terminal: true,
|
|
74
|
+
thinkingLevel: false,
|
|
75
|
+
streaming: false,
|
|
76
|
+
tools: false,
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
constructor(opts = {}) {
|
|
81
|
+
// Picker forwards every BaseSession opt; `provider` is fixed to user-shell.
|
|
82
|
+
super(buildBaseSessionOpts(opts, { provider: USER_SHELL_PROVIDER }))
|
|
83
|
+
this._term = null
|
|
84
|
+
this._ptyExited = false
|
|
85
|
+
this._destroying = false
|
|
86
|
+
this._shellAlive = false
|
|
87
|
+
// #5985 audit — the resolved shell path and the last exit code/reason (set
|
|
88
|
+
// when the PTY exits), surfaced to the shell-audit trail. resolveShell() is
|
|
89
|
+
// synchronous, so resolve it HERE (not in async start()) — the create-audit
|
|
90
|
+
// in the WS handler reads this right after createSession returns, before the
|
|
91
|
+
// fire-and-forget start() microtask has run, so a start()-set value would
|
|
92
|
+
// always be null on the audit line (agent review).
|
|
93
|
+
this._shellPath = resolveShell()
|
|
94
|
+
this._exitCode = null
|
|
95
|
+
this._exitReason = null
|
|
96
|
+
this._ptyCols = DEFAULT_COLS
|
|
97
|
+
this._ptyRows = DEFAULT_ROWS
|
|
98
|
+
this._mirrorBuffer = ''
|
|
99
|
+
this._mirrorTimer = null
|
|
100
|
+
this._terminalMirrorActive = false
|
|
101
|
+
this._killTimer = null
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A shell with a live PTY is "running" — keeps SessionTimeoutManager from
|
|
106
|
+
* reaping an open shell as idle and lets the UI show the tab as live. Turn-
|
|
107
|
+
* based `_isBusy` never flips for a shell, so the base getter would always be
|
|
108
|
+
* false; this reflects PTY liveness instead.
|
|
109
|
+
*/
|
|
110
|
+
get isRunning() {
|
|
111
|
+
return this._shellAlive
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Build the env for the spawned interactive shell PTY. Inherits the operator's
|
|
116
|
+
* full process env (it IS their shell) with TERM forced, then strips the
|
|
117
|
+
* chroxy-owned daemon secrets (#6311) — defence in depth so a command, script,
|
|
118
|
+
* or tool the user runs in the shell can't read the daemon's full-authority
|
|
119
|
+
* primary bearer token from the environment. Extracted so the strip is
|
|
120
|
+
* unit-testable without a real PTY spawn.
|
|
121
|
+
*
|
|
122
|
+
* @returns {Record<string, string>}
|
|
123
|
+
*/
|
|
124
|
+
_buildShellEnv() {
|
|
125
|
+
const env = { ...process.env, TERM: 'xterm-256color' }
|
|
126
|
+
for (const key of CHROXY_SECRET_DENYLIST) {
|
|
127
|
+
delete env[key]
|
|
128
|
+
}
|
|
129
|
+
return env
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Spawn the shell under node-pty and wire its I/O. Async + rejects on failure
|
|
134
|
+
* so SessionManager's _handleAsyncStartFailure tears down the phantom session
|
|
135
|
+
* (same contract claude-tui relies on).
|
|
136
|
+
*/
|
|
137
|
+
async start() {
|
|
138
|
+
let ptyMod
|
|
139
|
+
try {
|
|
140
|
+
ptyMod = await import('node-pty')
|
|
141
|
+
} catch (err) {
|
|
142
|
+
throw new Error(`node-pty unavailable: ${err.message}`)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Resolved in the constructor (see _shellPath) so the create-audit can read
|
|
146
|
+
// it synchronously; reuse it here for the actual spawn.
|
|
147
|
+
const shell = this._shellPath
|
|
148
|
+
let cwdReal
|
|
149
|
+
try {
|
|
150
|
+
cwdReal = realpathSync(this.cwd)
|
|
151
|
+
} catch {
|
|
152
|
+
// Fall back to the raw cwd; the spawn below surfaces a clean error if it's
|
|
153
|
+
// truly unusable. Never default to '/' silently (Tauri/launchd cwd trap).
|
|
154
|
+
cwdReal = this.cwd
|
|
155
|
+
}
|
|
156
|
+
const env = this._buildShellEnv()
|
|
157
|
+
|
|
158
|
+
try {
|
|
159
|
+
this._term = ptyMod.spawn(shell, [], {
|
|
160
|
+
name: 'xterm-256color',
|
|
161
|
+
cols: this._ptyCols,
|
|
162
|
+
rows: this._ptyRows,
|
|
163
|
+
cwd: cwdReal,
|
|
164
|
+
env,
|
|
165
|
+
})
|
|
166
|
+
} catch (err) {
|
|
167
|
+
throw new Error(`Failed to spawn user shell (${shell}): ${err.message}`)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// destroy() can race the spawn (it set _destroying while we awaited the
|
|
171
|
+
// import): kill the fresh PTY so it isn't orphaned, then bail.
|
|
172
|
+
if (this._destroying) {
|
|
173
|
+
try { this._term.kill('SIGTERM') } catch { /* already gone */ }
|
|
174
|
+
this._term = null
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
this._shellAlive = true
|
|
179
|
+
log.info(`user-shell spawned (${shell} pid=${this._term.pid} ${this._ptyCols}x${this._ptyRows} cwd=${cwdReal})`)
|
|
180
|
+
// #6276: announce the live PTY pid so SessionManager can record it to the
|
|
181
|
+
// orphan-reaper sidecar. Emitted synchronously here (the listener is wired in
|
|
182
|
+
// _wireSessionEvents before start()) so the pid is durably tracked the moment
|
|
183
|
+
// the shell exists — the only window where a SIGKILL could orphan it.
|
|
184
|
+
this.emit('shell_spawned', { pid: this._term.pid })
|
|
185
|
+
|
|
186
|
+
this._term.onData((data) => this._feedTerminalMirror(data))
|
|
187
|
+
this._term.onExit((info) => this._onShellExit(info, 'exit'))
|
|
188
|
+
// #5311 parity: keep a per-session PTY fault from crashing the whole daemon.
|
|
189
|
+
// node-pty rethrows a socket error unless the Terminal has >= 2 'error'
|
|
190
|
+
// listeners; drive teardown off 'close'/'error' and register a second no-op
|
|
191
|
+
// 'error' listener to clear the rethrow threshold. _onShellExit is
|
|
192
|
+
// idempotent (guards on _ptyExited) so any firing order tears down once.
|
|
193
|
+
this._term.on('error', (err) => this._onShellExit(null, `error: ${err?.message || 'unknown'}`))
|
|
194
|
+
this._term.on('error', () => {})
|
|
195
|
+
this._term.on('close', () => this._onShellExit(null, 'close'))
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The shell process ended (clean `exit`, close, or socket error). Idempotent.
|
|
200
|
+
* Tears the PTY down WITHOUT respawning — exit means gone (#5985 Guardian) —
|
|
201
|
+
* surfaces a final frame so the viewer sees it ended, and flips isRunning off.
|
|
202
|
+
*/
|
|
203
|
+
_onShellExit(info, reason) {
|
|
204
|
+
if (this._ptyExited) return
|
|
205
|
+
this._ptyExited = true
|
|
206
|
+
this._shellAlive = false
|
|
207
|
+
const code = info && typeof info.exitCode === 'number' ? info.exitCode : null
|
|
208
|
+
// #5985 audit — preserve the natural exit code/reason so the destroy audit
|
|
209
|
+
// entry can report how the shell ended (vs. a SIGTERM-killed null).
|
|
210
|
+
this._exitCode = code
|
|
211
|
+
this._exitReason = reason
|
|
212
|
+
log.info(`user-shell exited (reason=${reason}${code != null ? ` code=${code}` : ''})`)
|
|
213
|
+
// Flush any buffered bytes, then a terminal marker so a live viewer sees the
|
|
214
|
+
// shell ended rather than a frozen prompt. Kept out of history (it's a
|
|
215
|
+
// terminal_output, transient by wiring).
|
|
216
|
+
this._flushTerminalMirror()
|
|
217
|
+
// Only surface the marker when a viewer is actually subscribed — consistent
|
|
218
|
+
// with the coalescer's mirror-active gate (an unwatched shell does no work).
|
|
219
|
+
if (this._terminalMirrorActive) {
|
|
220
|
+
const marker = `\r\n[chroxy] shell exited${code != null ? ` (code ${code})` : ''}\r\n`
|
|
221
|
+
this.emit('terminal_output', { data: marker })
|
|
222
|
+
}
|
|
223
|
+
this._clearKillTimer()
|
|
224
|
+
// #5982 — signal a NATURAL exit so SessionManager can auto-remove the dead
|
|
225
|
+
// session (no lingering zombie shells). Emitted only here, so an explicit
|
|
226
|
+
// destroy() — which detaches listeners first — never triggers auto-remove.
|
|
227
|
+
this.emit('shell_exited', { code })
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Append a raw PTY chunk to the coalescing buffer and arm a single flush
|
|
232
|
+
* timer. Gated on an active mirror (a subscriber present) so an unwatched
|
|
233
|
+
* shell does no per-byte work. Bytes are NOT transformed — faithful render.
|
|
234
|
+
*/
|
|
235
|
+
_feedTerminalMirror(data) {
|
|
236
|
+
if (!this._terminalMirrorActive) return
|
|
237
|
+
this._mirrorBuffer += String(data)
|
|
238
|
+
if (this._mirrorTimer) return
|
|
239
|
+
this._mirrorTimer = setTimeout(() => this._flushTerminalMirror(), MIRROR_FLUSH_MS)
|
|
240
|
+
if (typeof this._mirrorTimer.unref === 'function') this._mirrorTimer.unref()
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Emit the coalesced buffer as one terminal_output and reset. No-op if empty. */
|
|
244
|
+
_flushTerminalMirror() {
|
|
245
|
+
if (this._mirrorTimer) {
|
|
246
|
+
clearTimeout(this._mirrorTimer)
|
|
247
|
+
this._mirrorTimer = null
|
|
248
|
+
}
|
|
249
|
+
const data = this._mirrorBuffer
|
|
250
|
+
if (!data) return
|
|
251
|
+
this._mirrorBuffer = ''
|
|
252
|
+
this.emit('terminal_output', { data })
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* WsServer toggles the coalescer when the terminal-subscriber count crosses
|
|
257
|
+
* 0↔1 (#5837). When turning OFF, drop the pending buffer/timer (nobody's
|
|
258
|
+
* watching, so a trailing flush is waste).
|
|
259
|
+
*/
|
|
260
|
+
setTerminalMirrorActive(active) {
|
|
261
|
+
const next = !!active
|
|
262
|
+
if (next === this._terminalMirrorActive) return
|
|
263
|
+
this._terminalMirrorActive = next
|
|
264
|
+
if (!next) {
|
|
265
|
+
if (this._mirrorTimer) {
|
|
266
|
+
clearTimeout(this._mirrorTimer)
|
|
267
|
+
this._mirrorTimer = null
|
|
268
|
+
}
|
|
269
|
+
this._mirrorBuffer = ''
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The live PTY's current grid, for a newly-subscribing viewer to letterbox to. */
|
|
274
|
+
getTerminalSize() {
|
|
275
|
+
return { cols: this._ptyCols, rows: this._ptyRows }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Resize the live PTY. Clamps to the protocol bounds (so a bad caller can't
|
|
280
|
+
* throw inside node-pty), records the size, applies it when a PTY is alive,
|
|
281
|
+
* and emits terminal_resize (broadcast back as terminal_size). Returns the
|
|
282
|
+
* applied size or null on a no-op.
|
|
283
|
+
*/
|
|
284
|
+
resizeTerminal(cols, rows) {
|
|
285
|
+
const c = Math.max(1, Math.min(1000, Math.floor(Number(cols))))
|
|
286
|
+
const r = Math.max(1, Math.min(1000, Math.floor(Number(rows))))
|
|
287
|
+
if (!Number.isFinite(c) || !Number.isFinite(r)) return null
|
|
288
|
+
if (c === this._ptyCols && r === this._ptyRows) return null
|
|
289
|
+
this._ptyCols = c
|
|
290
|
+
this._ptyRows = r
|
|
291
|
+
if (this._term && !this._ptyExited) {
|
|
292
|
+
try {
|
|
293
|
+
this._term.resize(c, r)
|
|
294
|
+
} catch (err) {
|
|
295
|
+
log.warn(`user-shell resize failed (${c}x${r}): ${err?.message || err}`)
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
this.emit('terminal_resize', { cols: c, rows: r })
|
|
299
|
+
return { cols: c, rows: r }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* #6313: force the live shell to repaint by toggling the grid width one column
|
|
304
|
+
* and back — each resize sends SIGWINCH, so the shell prompt (and any TUI the
|
|
305
|
+
* user is running) redraws. Recovery for the stateless raw-byte mirror after a
|
|
306
|
+
* WS-backpressure-dropped frame desyncs the xterm grid. Width is restored, so
|
|
307
|
+
* the authoritative size is unchanged. No-op (false) without a live PTY. Caveat:
|
|
308
|
+
* a plain shell redraws its current prompt line, not desynced scrollback.
|
|
309
|
+
* @returns {boolean} whether a repaint was driven against a live PTY.
|
|
310
|
+
*/
|
|
311
|
+
forceTerminalRepaint() {
|
|
312
|
+
if (!this._term || this._ptyExited) return false
|
|
313
|
+
const { cols, rows } = this.getTerminalSize()
|
|
314
|
+
const toggleCols = cols > 1 ? cols - 1 : 2
|
|
315
|
+
this.resizeTerminal(toggleCols, rows)
|
|
316
|
+
this.resizeTerminal(cols, rows)
|
|
317
|
+
return true
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Write raw client keystrokes to the live PTY. The WS handler enforces
|
|
322
|
+
* authority (PRIMARY token + viewer); this just writes. No-op (false) when
|
|
323
|
+
* there is no live PTY.
|
|
324
|
+
* @returns {boolean}
|
|
325
|
+
*/
|
|
326
|
+
writeTerminalInput(data) {
|
|
327
|
+
if (typeof data !== 'string' || data.length === 0) return false
|
|
328
|
+
if (!this._term || this._ptyExited || this._destroying) return false
|
|
329
|
+
try {
|
|
330
|
+
this._term.write(data)
|
|
331
|
+
return true
|
|
332
|
+
} catch (err) {
|
|
333
|
+
log.warn(`user-shell terminal input write failed: ${err?.message || err}`)
|
|
334
|
+
return false
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ── ProviderSession contract stubs ────────────────────────────────────────
|
|
339
|
+
// A user shell has no chat/turn semantics. These exist only to satisfy the
|
|
340
|
+
// REQUIRED_METHODS interface check; setModel/setPermissionMode are inherited
|
|
341
|
+
// from BaseSession (harmless no-ops here).
|
|
342
|
+
|
|
343
|
+
/** No-op: a shell takes raw keystrokes via writeTerminalInput, not messages. */
|
|
344
|
+
sendMessage() {
|
|
345
|
+
return false
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** No-op: there is no turn to interrupt; Ctrl-C is a keystroke (terminal_input). */
|
|
349
|
+
interrupt() {
|
|
350
|
+
return false
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Kill the PTY (no respawn) and clear all timers. SIGTERM, then after a grace
|
|
355
|
+
* window SIGKILL the whole process group so backgrounded jobs die too. The
|
|
356
|
+
* liveness probe + _ptyExited latch narrow escalation to a genuinely-hung
|
|
357
|
+
* shell (never a recycled pid).
|
|
358
|
+
*/
|
|
359
|
+
destroy() {
|
|
360
|
+
// Idempotent: a second destroy() (or a destroy racing the exit path) is a
|
|
361
|
+
// no-op — the first call already armed teardown (SIGTERM + the escalation
|
|
362
|
+
// timer), and re-running would do nothing useful and risks cancelling a
|
|
363
|
+
// still-pending SIGKILL escalation.
|
|
364
|
+
if (this._destroying) return
|
|
365
|
+
this._destroying = true
|
|
366
|
+
|
|
367
|
+
if (this._mirrorTimer) {
|
|
368
|
+
clearTimeout(this._mirrorTimer)
|
|
369
|
+
this._mirrorTimer = null
|
|
370
|
+
}
|
|
371
|
+
this._mirrorBuffer = ''
|
|
372
|
+
|
|
373
|
+
const term = this._term
|
|
374
|
+
const pid = term?.pid
|
|
375
|
+
if (term && !this._ptyExited) {
|
|
376
|
+
try { term.kill('SIGTERM') } catch { /* already gone */ }
|
|
377
|
+
if (Number.isInteger(pid) && pid > 0) {
|
|
378
|
+
this._killTimer = setTimeout(() => {
|
|
379
|
+
this._killTimer = null
|
|
380
|
+
if (this._ptyExited) return
|
|
381
|
+
try { process.kill(pid, 0) } catch { return /* already exited */ }
|
|
382
|
+
log.warn(`user-shell PTY (pid=${pid}) did not exit ${DESTROY_GRACE_MS}ms after SIGTERM — escalating to SIGKILL`)
|
|
383
|
+
let killed = false
|
|
384
|
+
if (process.platform !== 'win32') {
|
|
385
|
+
try { process.kill(-pid, 'SIGKILL'); killed = true } catch { /* group gone */ }
|
|
386
|
+
}
|
|
387
|
+
if (!killed) {
|
|
388
|
+
try { term.kill('SIGKILL') } catch {
|
|
389
|
+
try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}, DESTROY_GRACE_MS)
|
|
393
|
+
if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
this._term = null
|
|
397
|
+
this._shellAlive = false
|
|
398
|
+
|
|
399
|
+
// BaseSession teardown (background-shell tracker, activity registry, pending
|
|
400
|
+
// maps). Mirrors the other providers' destroy() tail.
|
|
401
|
+
this._destroyPendingBackgroundShells()
|
|
402
|
+
this.removeAllListeners()
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
_clearKillTimer() {
|
|
406
|
+
if (this._killTimer) {
|
|
407
|
+
clearTimeout(this._killTimer)
|
|
408
|
+
this._killTimer = null
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync } from 'fs'
|
|
2
|
+
import { dirname, join } from 'path'
|
|
3
|
+
import { createRequire } from 'module'
|
|
4
|
+
import { pathToFileURL } from 'url'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Check whether dependency resolution will succeed from a given package
|
|
8
|
+
* directory, across both package-local and hoisted (workspace) layouts.
|
|
9
|
+
*
|
|
10
|
+
* npm workspaces may place deps in any parent node_modules/ up the tree,
|
|
11
|
+
* not just the package's own node_modules/. This helper mirrors what Node
|
|
12
|
+
* will actually do at import time:
|
|
13
|
+
*
|
|
14
|
+
* 1. Try createRequire(startDir).resolve(probe) — the authoritative check.
|
|
15
|
+
* Matches Node's real module resolution, including symlinks, custom
|
|
16
|
+
* exports, and nested workspace layouts.
|
|
17
|
+
* 2. Fall back to walking up from startDir looking for
|
|
18
|
+
* node_modules/<probe>/ — useful when createRequire throws for an
|
|
19
|
+
* unrelated reason (malformed package.json, ENOENT races, etc.).
|
|
20
|
+
*
|
|
21
|
+
* @param {Object} options
|
|
22
|
+
* @param {string} options.startDir - Absolute path to begin resolution from
|
|
23
|
+
* (typically the server package root).
|
|
24
|
+
* @param {string[]} options.probes - Dependency names to probe. Succeeds if
|
|
25
|
+
* ANY probe resolves. Pass multiple to be robust against a single dep
|
|
26
|
+
* being removed from package.json in the future.
|
|
27
|
+
* @returns {{ ok: boolean, foundAt?: string, message?: string }}
|
|
28
|
+
*/
|
|
29
|
+
export function checkDependencies({ startDir, probes }) {
|
|
30
|
+
if (!startDir || !Array.isArray(probes) || probes.length === 0) {
|
|
31
|
+
return { ok: false, message: 'invalid arguments: startDir and non-empty probes required' }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 1. createRequire probe — closest to what Node does at import time.
|
|
35
|
+
// createRequire needs a file URL (or a filename); use a synthetic
|
|
36
|
+
// file path inside startDir so Node walks up from there.
|
|
37
|
+
const requireFromStart = createRequire(pathToFileURL(join(startDir, 'package.json')))
|
|
38
|
+
for (const probe of probes) {
|
|
39
|
+
try {
|
|
40
|
+
const resolved = requireFromStart.resolve(probe)
|
|
41
|
+
if (resolved) return { ok: true, foundAt: resolved }
|
|
42
|
+
} catch {
|
|
43
|
+
// fall through
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 2. Walk-up fallback: look for node_modules/<probe>/package.json in each
|
|
48
|
+
// ancestor. Checking package.json (not just the directory) avoids false
|
|
49
|
+
// positives from empty dirs, partially extracted installs, or stray folders
|
|
50
|
+
// that Node would still fail to resolve at import time.
|
|
51
|
+
// Stops at the filesystem root (when dirname returns the same path).
|
|
52
|
+
let dir = startDir
|
|
53
|
+
// Safety cap — real trees never exceed a few dozen levels.
|
|
54
|
+
for (let i = 0; i < 64; i++) {
|
|
55
|
+
for (const probe of probes) {
|
|
56
|
+
const candidate = join(dir, 'node_modules', probe)
|
|
57
|
+
if (existsSync(join(candidate, 'package.json'))) {
|
|
58
|
+
return { ok: true, foundAt: candidate }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const parent = dirname(dir)
|
|
62
|
+
if (parent === dir) break
|
|
63
|
+
dir = parent
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
ok: false,
|
|
68
|
+
message: `no node_modules containing ${probes.join(' or ')} found walking up from ${startDir}`,
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run async tasks with a concurrency limit.
|
|
3
|
+
* @param {Array<() => Promise>} tasks - Array of thunks returning promises
|
|
4
|
+
* @param {number} limit - Max concurrent tasks
|
|
5
|
+
* @returns {Promise<Array>} Results in order
|
|
6
|
+
*/
|
|
7
|
+
export async function runWithConcurrency(tasks, limit) {
|
|
8
|
+
if (!Number.isFinite(limit) || limit < 1) {
|
|
9
|
+
throw new RangeError('runWithConcurrency: limit must be >= 1')
|
|
10
|
+
}
|
|
11
|
+
const results = new Array(tasks.length)
|
|
12
|
+
let nextIndex = 0
|
|
13
|
+
|
|
14
|
+
async function worker() {
|
|
15
|
+
while (nextIndex < tasks.length) {
|
|
16
|
+
const idx = nextIndex++
|
|
17
|
+
results[idx] = await tasks[idx]()
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker())
|
|
22
|
+
await Promise.all(workers)
|
|
23
|
+
return results
|
|
24
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { getRegistryForProvider } from '../models.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shared context-window learn-loop helper (#3857, #4414).
|
|
5
|
+
*
|
|
6
|
+
* Providers ship static `contextWindow` values in their per-model metadata
|
|
7
|
+
* (see `*-session.js` `*_MODEL_METADATA` tables). Those values drift — the
|
|
8
|
+
* original 272k → 400k drift on `gpt-5` / `gpt-5-codex` is the canonical
|
|
9
|
+
* example, but the same exposure exists for every provider that publishes a
|
|
10
|
+
* fixed window: Gemini 2.5 Pro can grow past its current 2M cap, etc.
|
|
11
|
+
*
|
|
12
|
+
* This helper watches the per-turn `input_tokens` reported by the provider's
|
|
13
|
+
* end-of-turn JSONL event. When the observed value exceeds the registered
|
|
14
|
+
* window for the active model, it ratchets the registry entry upward to
|
|
15
|
+
* `inputTokens * HEADROOM` (rounded up to the nearest 1k for a clean meter
|
|
16
|
+
* reading) and emits `models_updated` so connected dashboards refresh.
|
|
17
|
+
*
|
|
18
|
+
* Only ratchets *up* — a single small turn must never shrink the registered
|
|
19
|
+
* window (the model didn't change, only the prompt size for this one turn).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Headroom multiplier applied to the observed input_tokens before writing
|
|
24
|
+
* it back to the registry. Gives the next turn a bit of slack before it
|
|
25
|
+
* pegs the meter again. Exported so tests can verify the exact ratchet
|
|
26
|
+
* target without recomputing the magic number.
|
|
27
|
+
*/
|
|
28
|
+
export const CONTEXT_WINDOW_HEADROOM = 1.1
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Per-provider sanity cap on the ratchet target. A single `input_tokens`
|
|
32
|
+
* value with a corrupt or malicious payload (overflow, JSONL parse glitch,
|
|
33
|
+
* future CLI bug) must not be able to balloon the registered window to an
|
|
34
|
+
* absurd number. Each cap is set well above the largest currently published
|
|
35
|
+
* window for that provider — any legit future model that exceeds it should
|
|
36
|
+
* bump the cap, not silently leak through.
|
|
37
|
+
*
|
|
38
|
+
* codex → 2,000,000 (today's max is 1M for gpt-4.1 / certain 1M GPT-5
|
|
39
|
+
* variants on plan tiers)
|
|
40
|
+
* gemini → 4,000,000 (today's max is 2M for gemini-2.5-pro / gemini-2.0-pro
|
|
41
|
+
* / gemini-1.5-pro; doubling leaves room for the next-gen bump
|
|
42
|
+
* without needing another source change)
|
|
43
|
+
*/
|
|
44
|
+
export const CONTEXT_WINDOW_RATCHET_CAPS = Object.freeze({
|
|
45
|
+
codex: 2_000_000,
|
|
46
|
+
gemini: 4_000_000,
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Default cap used when a provider isn't listed in CONTEXT_WINDOW_RATCHET_CAPS.
|
|
51
|
+
* Picked to match Codex's original 2M ceiling so existing callers see no
|
|
52
|
+
* behaviour change if they happen to pass an unknown providerName.
|
|
53
|
+
*/
|
|
54
|
+
export const DEFAULT_CONTEXT_WINDOW_RATCHET_CAP = 2_000_000
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Look up the configured cap for a given provider, falling back to the
|
|
58
|
+
* default if the provider isn't in the table.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} providerName
|
|
61
|
+
* @returns {number}
|
|
62
|
+
*/
|
|
63
|
+
export function getRatchetCap(providerName) {
|
|
64
|
+
// `Object.hasOwn` so a prototype-key lookup (`'constructor'`, `'toString'`,
|
|
65
|
+
// etc.) doesn't return the inherited member and NaN-poison the ratchet math
|
|
66
|
+
// downstream (`Math.min(n * 1.1, Object)` → NaN). In practice providerName
|
|
67
|
+
// only ever comes from registered names, but this closes the theoretical
|
|
68
|
+
// hole for ~one extra line.
|
|
69
|
+
if (Object.hasOwn(CONTEXT_WINDOW_RATCHET_CAPS, providerName)) {
|
|
70
|
+
return CONTEXT_WINDOW_RATCHET_CAPS[providerName]
|
|
71
|
+
}
|
|
72
|
+
return DEFAULT_CONTEXT_WINDOW_RATCHET_CAP
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Shared learn-loop helper. Ratchets the registered context window for
|
|
77
|
+
* `modelId` upward when `inputTokens` exceeds the current entry. No-ops on:
|
|
78
|
+
*
|
|
79
|
+
* - unknown model id (an unknown providerName falls through to the default
|
|
80
|
+
* Claude registry via `getRegistryForProvider`, so the no-op fires at the
|
|
81
|
+
* entry lookup — not at the registry lookup)
|
|
82
|
+
* - inputTokens not a finite positive number (corrupt JSONL — NaN * 1.1 =
|
|
83
|
+
* NaN; Infinity * 1.1 = Infinity → unbounded growth)
|
|
84
|
+
* - inputTokens at or below the registered window (no drift signal)
|
|
85
|
+
*
|
|
86
|
+
* Emits `models_updated` on the provided `emit` callback when the registry
|
|
87
|
+
* was updated, so connected dashboards pick up the corrected window without
|
|
88
|
+
* waiting for the next refresh. Mirrors the Claude SDK path in sdk-session.js
|
|
89
|
+
* which has an explicit `contextWindow` field — here we infer it from the
|
|
90
|
+
* observed token count.
|
|
91
|
+
*
|
|
92
|
+
* @param {string} providerName Provider key (e.g. 'codex', 'gemini')
|
|
93
|
+
* @param {string} modelId Short id or fullId of the active model
|
|
94
|
+
* @param {number} inputTokens `usage.input_tokens` from the end-of-turn event
|
|
95
|
+
* @param {(eventName: string, payload: object) => void} emit Callback used to
|
|
96
|
+
* broadcast `models_updated` when the registry was updated. Typically
|
|
97
|
+
* `session.emit.bind(session)`.
|
|
98
|
+
* @returns {boolean} true when the registry was updated, false when no-op
|
|
99
|
+
*/
|
|
100
|
+
export function maybeRatchetContextWindow(providerName, modelId, inputTokens, emit) {
|
|
101
|
+
// Defensive guard against corrupt/malicious JSONL — a non-finite or
|
|
102
|
+
// negative `input_tokens` must not feed the ratchet math.
|
|
103
|
+
if (!Number.isFinite(inputTokens) || inputTokens <= 0) return false
|
|
104
|
+
|
|
105
|
+
const registry = getRegistryForProvider(providerName)
|
|
106
|
+
if (!registry) return false
|
|
107
|
+
|
|
108
|
+
// Look up the active model in the registry to read its current window.
|
|
109
|
+
// Match on either short id or fullId — the registry stores both.
|
|
110
|
+
const models = registry.getModels()
|
|
111
|
+
const entry = models.find(m => m.id === modelId || m.fullId === modelId)
|
|
112
|
+
if (!entry) return false
|
|
113
|
+
if (typeof entry.contextWindow !== 'number' || entry.contextWindow <= 0) return false
|
|
114
|
+
|
|
115
|
+
if (inputTokens <= entry.contextWindow) return false
|
|
116
|
+
|
|
117
|
+
const cap = getRatchetCap(providerName)
|
|
118
|
+
|
|
119
|
+
// Round the bumped value up to the nearest 1k so the meter shows a clean
|
|
120
|
+
// number ("440k" not "440231") and we don't write a fresh cache entry on
|
|
121
|
+
// every single turn for sub-1k variation. Capped at the per-provider
|
|
122
|
+
// ratchet cap so a single corrupt turn can't balloon the registry.
|
|
123
|
+
const raw = Math.min(inputTokens * CONTEXT_WINDOW_HEADROOM, cap)
|
|
124
|
+
const bumped = Math.ceil(raw / 1000) * 1000
|
|
125
|
+
|
|
126
|
+
const changed = registry.updateContextWindow(modelId, bumped)
|
|
127
|
+
if (!changed) return false
|
|
128
|
+
|
|
129
|
+
// #4413 — persist the bumped registry to the provider-scoped cache file
|
|
130
|
+
// (e.g. `~/.chroxy/models-cache.codex.json`) so a server restart doesn't
|
|
131
|
+
// lose the learned window. `saveCache()` is idempotent (snapshot-deduped)
|
|
132
|
+
// and logs a warn on disk failure rather than throwing, so the in-memory
|
|
133
|
+
// ratchet always succeeds even when the disk path is unwritable. Each
|
|
134
|
+
// provider's registry routes to its own cache path via
|
|
135
|
+
// `getRegistryForProvider`'s `cachePath` hook — the default Claude cache
|
|
136
|
+
// is unaffected by non-Claude ratchets.
|
|
137
|
+
if (typeof registry.saveCache === 'function') {
|
|
138
|
+
registry.saveCache()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Broadcast the corrected registry so the dashboard's `availableModels`
|
|
142
|
+
// (and therefore the footer meter) picks up the new window without
|
|
143
|
+
// waiting for the next refresh.
|
|
144
|
+
if (typeof emit === 'function') {
|
|
145
|
+
emit('models_updated', { models: registry.getModels() })
|
|
146
|
+
}
|
|
147
|
+
return true
|
|
148
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extract a human-readable message from an unknown thrown value.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the `err && err.message ? err.message : 'fallback'` idiom that was
|
|
5
|
+
* copy-pasted ~60× across the server (catch blocks, log lines, degraded survey
|
|
6
|
+
* replies). Behaviour is identical to that idiom: a truthy `err` with a truthy
|
|
7
|
+
* `.message` yields the message; anything else (null/undefined `err`, a thrown
|
|
8
|
+
* non-Error, or an empty-string `.message`) yields the fallback.
|
|
9
|
+
*
|
|
10
|
+
* The fallback is returned **as-is, by reference** — it is NOT coerced to a
|
|
11
|
+
* string. Most callers pass a string, but some pass a non-string (e.g.
|
|
12
|
+
* `getErrorMessage(err, err)` to forward the raw value into a template), exactly
|
|
13
|
+
* as the original idiom did. So with a non-string fallback the return type is
|
|
14
|
+
* that fallback's type, not `string`. Do not "fix" this by stringifying — it
|
|
15
|
+
* would silently change those call sites.
|
|
16
|
+
*
|
|
17
|
+
* @param {unknown} err - the caught value (Error, string, anything).
|
|
18
|
+
* @param {T} [fallback='unknown error'] - returned by reference when there is no
|
|
19
|
+
* usable message; any type, defaulting to the string 'unknown error'.
|
|
20
|
+
* @returns {string|T} the message string, or the fallback unchanged.
|
|
21
|
+
* @template T
|
|
22
|
+
*/
|
|
23
|
+
export function getErrorMessage(err, fallback = 'unknown error') {
|
|
24
|
+
return err && err.message ? err.message : fallback
|
|
25
|
+
}
|