@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
package/src/logger.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured logger with optional file output and rotation.
|
|
3
|
+
*
|
|
4
|
+
* Console-only by default (foreground mode). Call initFileLogging()
|
|
5
|
+
* on daemon startup to enable file output with automatic rotation.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { createLogger, initFileLogging, closeFileLogging } from './logger.js'
|
|
9
|
+
*
|
|
10
|
+
* // Optional — enable file logging for daemon mode
|
|
11
|
+
* initFileLogging({ level: 'debug', logDir: '/custom/path' })
|
|
12
|
+
*
|
|
13
|
+
* const log = createLogger('supervisor')
|
|
14
|
+
* log.info('Server ready')
|
|
15
|
+
* // => 2026-02-22T12:34:56.789Z [INFO] [supervisor] Server ready
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { appendFileSync, statSync, renameSync, mkdirSync, chmodSync } from 'fs'
|
|
19
|
+
import { join } from 'path'
|
|
20
|
+
import { homedir } from 'os'
|
|
21
|
+
import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue } from './redaction.js'
|
|
22
|
+
|
|
23
|
+
const DEFAULT_LOG_DIR = join(homedir(), '.chroxy', 'logs')
|
|
24
|
+
const MAX_LOG_SIZE = 5 * 1024 * 1024 // 5MB
|
|
25
|
+
const MAX_LOG_FILES = 3
|
|
26
|
+
const ROTATION_CHECK_INTERVAL = 100 // check every N writes
|
|
27
|
+
|
|
28
|
+
const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }
|
|
29
|
+
|
|
30
|
+
// #6029: the value-SHAPE patterns (SENSITIVE_PATTERNS / API_KEY_PATTERNS) and
|
|
31
|
+
// the contiguous redaction logic now live in redaction.js as the single source
|
|
32
|
+
// of truth, shared with the tool-broadcast sanitizer (ws-permissions.js). The
|
|
33
|
+
// constants are imported here for redactSensitivePreservingEscapes (the
|
|
34
|
+
// escape-aware PTY-dump pass that still needs the raw pattern list).
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Redact sensitive data from a log message. Delegates to the shared
|
|
38
|
+
* `redactValue` (redaction.js) so the logger and the tool-broadcast path apply
|
|
39
|
+
* identical patterns and replacement rules.
|
|
40
|
+
* @param {string} msg
|
|
41
|
+
* @returns {string}
|
|
42
|
+
*/
|
|
43
|
+
export function redactSensitive(msg) {
|
|
44
|
+
return redactValue(msg)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// #5358: escape/control sequences a TUI can interleave INTO a token while
|
|
48
|
+
// styling it (e.g. `sk-ant-oat01-AAAA\x1b[1mBBBB`), splitting the run so the
|
|
49
|
+
// contiguous patterns above miss it. Mirrors the claude-tui ANSI_STRIP set,
|
|
50
|
+
// kept local so logger.js stays dependency-free.
|
|
51
|
+
const TOKEN_SPLITTING_ESCAPE = new RegExp(
|
|
52
|
+
[
|
|
53
|
+
'\\x1b\\[[0-9;?]*[\\x40-\\x7E]', // CSI
|
|
54
|
+
'\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)', // OSC ... BEL/ST
|
|
55
|
+
'\\x1bO.', // SS3
|
|
56
|
+
'\\x1b[=>cN]', // single-char terminal-mode codes
|
|
57
|
+
'[\\x00-\\x08\\x0b-\\x1f\\x7f]', // stray C0 controls (except \t and \n)
|
|
58
|
+
].join('|'),
|
|
59
|
+
'g',
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* #5358: redact tokens from a string that may have escape sequences interleaved
|
|
64
|
+
* MID-TOKEN — the PTY hex-dump source. The contiguous `redactSensitive` misses
|
|
65
|
+
* a token split by an escape; this detects tokens in an escape-STRIPPED copy,
|
|
66
|
+
* then redacts the corresponding characters in the ORIGINAL while LEAVING the
|
|
67
|
+
* escape bytes in place. So a hex dump keeps the escape structure it exists to
|
|
68
|
+
* show, but the token leaks in neither the hex nor the ASCII column.
|
|
69
|
+
*
|
|
70
|
+
* Length-preserving (each token char → 'X'), so escape-byte offsets in the dump
|
|
71
|
+
* stay meaningful. Intended to be layered AFTER redactSensitive (which handles
|
|
72
|
+
* the contiguous case + key-name preservation); this pass only changes a string
|
|
73
|
+
* when a split token survived.
|
|
74
|
+
*
|
|
75
|
+
* NOTE: a generic high-entropy "any token-shaped string" heuristic is
|
|
76
|
+
* deliberately NOT added — on a diagnostic dump it would redact UUIDs, git
|
|
77
|
+
* SHAs, and base64 payloads (the very content the dump exists to show). The
|
|
78
|
+
* marker-prefixed patterns (sk-/AIza/Bearer/JWT/key=value) are the safe set.
|
|
79
|
+
*
|
|
80
|
+
* @param {string} s latin1/utf8 string (one char per byte for the dump path)
|
|
81
|
+
* @returns {string}
|
|
82
|
+
*/
|
|
83
|
+
export function redactSensitivePreservingEscapes(s) {
|
|
84
|
+
// Walk s, skipping escape runs, building a stripped copy + index map back to s.
|
|
85
|
+
let stripped = ''
|
|
86
|
+
const map = []
|
|
87
|
+
let i = 0
|
|
88
|
+
while (i < s.length) {
|
|
89
|
+
TOKEN_SPLITTING_ESCAPE.lastIndex = i
|
|
90
|
+
const m = TOKEN_SPLITTING_ESCAPE.exec(s)
|
|
91
|
+
if (m && m.index === i) { i += m[0].length || 1; continue }
|
|
92
|
+
stripped += s[i]
|
|
93
|
+
map.push(i)
|
|
94
|
+
i++
|
|
95
|
+
}
|
|
96
|
+
const chars = s.split('')
|
|
97
|
+
let changed = false
|
|
98
|
+
for (const pattern of [...SENSITIVE_PATTERNS, ...API_KEY_PATTERNS]) {
|
|
99
|
+
pattern.lastIndex = 0
|
|
100
|
+
let match
|
|
101
|
+
while ((match = pattern.exec(stripped)) !== null) {
|
|
102
|
+
for (let k = match.index; k < match.index + match[0].length; k++) chars[map[k]] = 'X'
|
|
103
|
+
changed = true
|
|
104
|
+
if (match[0].length === 0) pattern.lastIndex++ // guard against a zero-width match
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return changed ? chars.join('') : s
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let _logLevel = LOG_LEVELS[process.env.LOG_LEVEL] ?? LOG_LEVELS.info
|
|
111
|
+
let _jsonMode = false
|
|
112
|
+
let _logToFile = false
|
|
113
|
+
let _logDir = DEFAULT_LOG_DIR
|
|
114
|
+
let _logPath = null
|
|
115
|
+
let _writeCount = 0
|
|
116
|
+
|
|
117
|
+
/** Set of callbacks for broadcasting log entries (supports multiple WsServer instances) */
|
|
118
|
+
const _logListeners = new Set()
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Enable or disable JSON log output format.
|
|
122
|
+
* When enabled, log lines are emitted as JSON objects instead of human-readable strings.
|
|
123
|
+
* @param {boolean} enabled
|
|
124
|
+
*/
|
|
125
|
+
export function setJsonMode(enabled) {
|
|
126
|
+
_jsonMode = !!enabled
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Set a listener that receives every log entry as a structured object.
|
|
131
|
+
* @deprecated Use addLogListener/removeLogListener instead
|
|
132
|
+
* @param {((entry: {component: string, level: string, message: string, timestamp: number}) => void) | null} listener
|
|
133
|
+
*/
|
|
134
|
+
export function setLogListener(listener) {
|
|
135
|
+
_logListeners.clear()
|
|
136
|
+
if (listener) _logListeners.add(listener)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Add a log listener. Each WsServer instance registers its own.
|
|
141
|
+
* @param {(entry: {component: string, level: string, message: string, timestamp: number}) => void} listener
|
|
142
|
+
*/
|
|
143
|
+
export function addLogListener(listener) {
|
|
144
|
+
_logListeners.add(listener)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Remove a previously added log listener.
|
|
149
|
+
* @param {(entry: {component: string, level: string, message: string, timestamp: number}) => void} listener
|
|
150
|
+
*/
|
|
151
|
+
export function removeLogListener(listener) {
|
|
152
|
+
_logListeners.delete(listener)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Initialize file logging. Called once on daemon startup.
|
|
157
|
+
* @param {object} options
|
|
158
|
+
* @param {string} [options.level='info'] - Minimum log level
|
|
159
|
+
* @param {string} [options.logDir] - Log directory (default ~/.chroxy/logs)
|
|
160
|
+
*/
|
|
161
|
+
export function initFileLogging({ level = 'info', logDir } = {}) {
|
|
162
|
+
_logLevel = LOG_LEVELS[level] ?? LOG_LEVELS.info
|
|
163
|
+
_logToFile = true
|
|
164
|
+
_writeCount = 0
|
|
165
|
+
if (logDir) _logDir = logDir
|
|
166
|
+
// #3734 review (Copilot): create the log directory at mode 0700, and
|
|
167
|
+
// chmod existing dirs the same way. Logs may contain sensitive data
|
|
168
|
+
// (tool inputs, tokens that slip past the redactor), so they must not
|
|
169
|
+
// be readable by group/world. mkdirSync's `mode` is subject to umask,
|
|
170
|
+
// but the explicit chmodSync afterward defeats umask AND tightens any
|
|
171
|
+
// pre-existing dir created at a looser mode by an earlier code path.
|
|
172
|
+
// Failures (read-only home, missing perms) propagate up — initFileLogging
|
|
173
|
+
// is wrapped in a try/catch at the boot site (server-cli.js).
|
|
174
|
+
mkdirSync(_logDir, { recursive: true, mode: 0o700 })
|
|
175
|
+
try {
|
|
176
|
+
chmodSync(_logDir, 0o700)
|
|
177
|
+
} catch {
|
|
178
|
+
// Best-effort — if we can't chmod (e.g. dir owned by another user),
|
|
179
|
+
// we keep going. The mkdir mode bit covers fresh-create.
|
|
180
|
+
}
|
|
181
|
+
_logPath = join(_logDir, 'chroxy.log')
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Return the current on-disk log path, or `null` if file logging is disabled.
|
|
186
|
+
* Used by /diagnostics (#3732) to point operators at the log file.
|
|
187
|
+
*
|
|
188
|
+
* @returns {string|null}
|
|
189
|
+
*/
|
|
190
|
+
export function getLogPath() {
|
|
191
|
+
return _logToFile ? _logPath : null
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Close file logging. Used in tests for cleanup.
|
|
196
|
+
*/
|
|
197
|
+
export function closeFileLogging() {
|
|
198
|
+
_logToFile = false
|
|
199
|
+
_jsonMode = false
|
|
200
|
+
_logLevel = LOG_LEVELS.info
|
|
201
|
+
_logDir = DEFAULT_LOG_DIR
|
|
202
|
+
_logPath = null
|
|
203
|
+
_writeCount = 0
|
|
204
|
+
_logListeners.clear()
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function _maybeRotate() {
|
|
208
|
+
if (!_logPath) return
|
|
209
|
+
try {
|
|
210
|
+
const stats = statSync(_logPath)
|
|
211
|
+
if (stats.size < MAX_LOG_SIZE) return
|
|
212
|
+
} catch (err) {
|
|
213
|
+
if (err?.code !== 'ENOENT') console.error('[logger] stat failed:', err?.message)
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Rotate: chroxy.3.log (overwritten) <- chroxy.2.log <- chroxy.1.log <- chroxy.log
|
|
218
|
+
for (let i = MAX_LOG_FILES; i >= 1; i--) {
|
|
219
|
+
const from = i === 1 ? _logPath : _logPath.replace('.log', `.${i - 1}.log`)
|
|
220
|
+
const to = _logPath.replace('.log', `.${i}.log`)
|
|
221
|
+
try {
|
|
222
|
+
renameSync(from, to)
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (err?.code !== 'ENOENT') console.error('[logger] rename failed:', err?.message)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Change the minimum log level at runtime.
|
|
231
|
+
* Useful for --verbose CLI flags to enable debug output. (#747)
|
|
232
|
+
* @param {string} level - One of 'debug', 'info', 'warn', 'error'
|
|
233
|
+
*/
|
|
234
|
+
export function setLogLevel(level) {
|
|
235
|
+
if (level in LOG_LEVELS) {
|
|
236
|
+
_logLevel = LOG_LEVELS[level]
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Get the current minimum log level as a string.
|
|
242
|
+
* Useful for tests that need to round-trip the level across
|
|
243
|
+
* `beforeEach`/`afterEach` without clobbering a non-default
|
|
244
|
+
* `LOG_LEVEL` env configuration. (#2889)
|
|
245
|
+
* @returns {'debug' | 'info' | 'warn' | 'error'}
|
|
246
|
+
*/
|
|
247
|
+
export function getLogLevel() {
|
|
248
|
+
for (const [name, value] of Object.entries(LOG_LEVELS)) {
|
|
249
|
+
if (value === _logLevel) return name
|
|
250
|
+
}
|
|
251
|
+
return 'info'
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Create a component logger. Backward-compatible with existing API.
|
|
256
|
+
* @param {string} component - Component name for log prefix
|
|
257
|
+
* @param {object} [context] - Optional context (e.g. { sessionId })
|
|
258
|
+
* @returns {{ debug: Function, info: Function, warn: Function, error: Function, audit: Function, log: Function, withSession: Function }}
|
|
259
|
+
*/
|
|
260
|
+
export function createLogger(component, context = {}) {
|
|
261
|
+
const write = (level, msg, { always = false, toConsole = true } = {}) => {
|
|
262
|
+
// `always` bypasses the configured level gate (#6001) so an audit trail is
|
|
263
|
+
// never dropped by LOG_LEVEL. Everything else (redaction, console routing,
|
|
264
|
+
// listener broadcast, file write) is identical to a normal line.
|
|
265
|
+
if (!always && LOG_LEVELS[level] < _logLevel) return
|
|
266
|
+
|
|
267
|
+
const safeMsg = redactSensitive(msg)
|
|
268
|
+
const timestamp = new Date().toISOString()
|
|
269
|
+
const line = _jsonMode
|
|
270
|
+
? JSON.stringify({ ts: timestamp, level, component, msg: safeMsg })
|
|
271
|
+
: `${timestamp} [${level.toUpperCase()}] [${component}] ${safeMsg}`
|
|
272
|
+
|
|
273
|
+
// Write to console (for foreground mode). #6566: `toConsole:false` suppresses
|
|
274
|
+
// the console write while keeping the file + listener paths — used by the
|
|
275
|
+
// supervisor to log a REDACTED connect-block line to disk while printing the
|
|
276
|
+
// un-redacted line to the operator's terminal separately under --show-token.
|
|
277
|
+
if (toConsole) {
|
|
278
|
+
if (level === 'error') console.error(line)
|
|
279
|
+
else if (level === 'warn') console.warn(line)
|
|
280
|
+
else console.log(line)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Notify listeners (for WS broadcast to dashboard)
|
|
284
|
+
if (_logListeners.size > 0) {
|
|
285
|
+
const entry = { component, level, message: safeMsg, timestamp: Date.now() }
|
|
286
|
+
if (context.sessionId) entry.sessionId = context.sessionId
|
|
287
|
+
for (const listener of _logListeners) {
|
|
288
|
+
try {
|
|
289
|
+
listener(entry)
|
|
290
|
+
} catch {
|
|
291
|
+
// Never let listener errors break logging
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Write to file in daemon mode
|
|
297
|
+
if (_logToFile && _logPath) {
|
|
298
|
+
try {
|
|
299
|
+
appendFileSync(_logPath, line + '\n')
|
|
300
|
+
_writeCount++
|
|
301
|
+
if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
|
|
302
|
+
_maybeRotate()
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
305
|
+
// Silently ignore write failures (disk full, permission denied, etc.)
|
|
306
|
+
// to prevent logging errors from crashing the server (#746)
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
debug(msg) { write('debug', msg) },
|
|
313
|
+
info(msg, opts) { write('info', msg, opts) },
|
|
314
|
+
warn(msg, opts) { write('warn', msg, opts) },
|
|
315
|
+
error(msg, opts) { write('error', msg, opts) },
|
|
316
|
+
/**
|
|
317
|
+
* Always-on audit line (#6001) — bypasses the configured LOG_LEVEL so a
|
|
318
|
+
* security audit trail (e.g. shell-audit) is never suppressed by a quiet
|
|
319
|
+
* production log level. Tagged `[AUDIT]`; still redacted, broadcast to log
|
|
320
|
+
* listeners, and written to the daemon log file like any other line.
|
|
321
|
+
*/
|
|
322
|
+
audit(msg) { write('audit', msg, { always: true }) },
|
|
323
|
+
// Backward compat alias
|
|
324
|
+
log(msg) { write('info', msg) },
|
|
325
|
+
/** Create a child logger tagged with a session ID. */
|
|
326
|
+
withSession(sessionId) { return createLogger(component, { ...context, sessionId }) },
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Create a session-scoped component logger.
|
|
332
|
+
*
|
|
333
|
+
* This is the preferred factory for any code that operates within session
|
|
334
|
+
* context (`ClaudeTuiSession`, `SdkSession`, `CliSession`, per-session
|
|
335
|
+
* handlers in `handlers/*`, etc.). It guarantees that every log entry
|
|
336
|
+
* the returned logger emits is tagged with `sessionId`, which the
|
|
337
|
+
* WsServer `_logListener` (#4787) uses to route log entries to the
|
|
338
|
+
* correct bound client. An unscoped `createLogger(component)` in a
|
|
339
|
+
* session-aware module silently drops to "global only" fan-out, leaking
|
|
340
|
+
* PTY hex dumps and prompt sizes to operators on other sessions.
|
|
341
|
+
*
|
|
342
|
+
* Equivalent to `createLogger(component).withSession(sessionId)` but
|
|
343
|
+
* explicit at the call site. Throws if either argument is missing — the
|
|
344
|
+
* whole point of the helper is to prevent unscoped session logs, so a
|
|
345
|
+
* silent fallback would defeat its purpose.
|
|
346
|
+
*
|
|
347
|
+
* @example
|
|
348
|
+
* // In a per-session class constructor:
|
|
349
|
+
* this._log = loggerForSession('claude-tui-session', this._sessionId)
|
|
350
|
+
* this._log.info('sendMessage start') // entry.sessionId is set
|
|
351
|
+
*
|
|
352
|
+
* @param {string} component - Component tag (same as createLogger).
|
|
353
|
+
* @param {string} sessionId - Session id to bind. Required.
|
|
354
|
+
* @returns {ReturnType<typeof createLogger>}
|
|
355
|
+
*/
|
|
356
|
+
export function loggerForSession(component, sessionId) {
|
|
357
|
+
if (typeof component !== 'string' || component.length === 0) {
|
|
358
|
+
throw new TypeError('loggerForSession: component must be a non-empty string')
|
|
359
|
+
}
|
|
360
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
361
|
+
throw new TypeError('loggerForSession: sessionId must be a non-empty string')
|
|
362
|
+
}
|
|
363
|
+
return createLogger(component, { sessionId })
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* #5378 — pick a session-scoped logger when `sessionId` is present, else the
|
|
368
|
+
* unscoped component logger. Centralizes the
|
|
369
|
+
* `sessionId ? loggerForSession('ws', sessionId) : log` ternary that was
|
|
370
|
+
* hand-written across the WS handlers (#4828), where inlining it everywhere
|
|
371
|
+
* invited picking the wrong sessionId variable or inverting the condition — and
|
|
372
|
+
* emitting an operator log to the wrong scope is silent.
|
|
373
|
+
*
|
|
374
|
+
* Semantics match that ternary EXACTLY: a falsy `sessionId` (null / undefined /
|
|
375
|
+
* empty string — the legitimate single-session fallback) uses the unscoped
|
|
376
|
+
* logger, while a truthy value is passed to `loggerForSession`, which THROWS on
|
|
377
|
+
* a non-string. That deliberate throw is preserved (not swallowed) so a
|
|
378
|
+
* programming error — e.g. passing an object/number — fails loudly instead of
|
|
379
|
+
* silently reintroducing the wrong-scope logging this helper exists to prevent
|
|
380
|
+
* (#5390 review).
|
|
381
|
+
*
|
|
382
|
+
* @param {string|null|undefined} sessionId
|
|
383
|
+
* @param {string} [component='ws']
|
|
384
|
+
* @returns {ReturnType<typeof createLogger>}
|
|
385
|
+
*/
|
|
386
|
+
export function sessionLogger(sessionId, component = 'ws') {
|
|
387
|
+
return sessionId ? loggerForSession(component, sessionId) : createLogger(component)
|
|
388
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mailbox live-interrupt routes (agent-comm-system delivery layer).
|
|
3
|
+
*
|
|
4
|
+
* The `agent-comm-system` MCP fires a best-effort webhook on every send
|
|
5
|
+
* (AGENT_COMM_EMIT_WEBHOOK -> POST { to, from, id, subject, unread_count }).
|
|
6
|
+
* Point that at this daemon's `/api/mailbox` and chroxy will:
|
|
7
|
+
* 1. notify (rides the existing PushManager pipeline), and
|
|
8
|
+
* 2. wake the recipient NOW when it is a live, idle claude-tui session —
|
|
9
|
+
* by injecting a "process your mailbox" prompt into its PTY. When the
|
|
10
|
+
* recipient is mid-turn, not a TUI session, or unknown, chroxy notifies
|
|
11
|
+
* only and the portable idle Stop hook delivers at the next turn boundary.
|
|
12
|
+
*
|
|
13
|
+
* Routing needs an agent-id -> session map, populated via `/api/mailbox/register`.
|
|
14
|
+
*
|
|
15
|
+
* Both routes accept ONLY the daemon-level ingest secret (never the primary
|
|
16
|
+
* token — see docs/security/bearer-token-authority.md §6), reusing the exact
|
|
17
|
+
* auth used by POST /api/events, behind a pre-auth per-IP rate limit.
|
|
18
|
+
*/
|
|
19
|
+
import { createLogger } from './logger.js'
|
|
20
|
+
import { safeTokenCompare } from './token-compare.js'
|
|
21
|
+
import { resolveIngestSecret } from './event-ingest.js'
|
|
22
|
+
import { sendOversizeResponse } from './http-oversize.js'
|
|
23
|
+
import { settlePush } from './push.js'
|
|
24
|
+
import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
|
|
25
|
+
|
|
26
|
+
const log = createLogger('mailbox-route')
|
|
27
|
+
|
|
28
|
+
// Mailbox payloads are tiny ({ to, from, id, subject, unread_count }).
|
|
29
|
+
export const MAX_MAILBOX_BODY_BYTES = 8192
|
|
30
|
+
// Cap on log-visible / routing-key fields so a secret-holder can neither bloat
|
|
31
|
+
// the routing map nor inject control chars into logs + notifications.
|
|
32
|
+
const MAX_FIELD_LENGTH = 200
|
|
33
|
+
const CONTROL_CHARS = /[\u0000-\u001f\u007f]/
|
|
34
|
+
// Pre-auth per-IP rate limit (mirrors event-ingest.js): bound online
|
|
35
|
+
// brute-force of the secret AND invalid-token warn-log spam, BEFORE the
|
|
36
|
+
// constant-time secret check.
|
|
37
|
+
const MAILBOX_WINDOW_MS = 60_000
|
|
38
|
+
const MAILBOX_IP_MAX = 240
|
|
39
|
+
const MAILBOX_IP_BURST = 30
|
|
40
|
+
|
|
41
|
+
function sendJson(res, status, body) {
|
|
42
|
+
const payload = JSON.stringify(body)
|
|
43
|
+
res.writeHead(status, { 'Content-Type': 'application/json' })
|
|
44
|
+
res.end(payload)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 401, fail closed: no body detail about WHY auth failed. */
|
|
48
|
+
function sendUnauthorized(res) {
|
|
49
|
+
res.writeHead(401)
|
|
50
|
+
res.end()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Normalize a log-visible / routing-key field: trim, reject empty, reject
|
|
55
|
+
* control characters (log/notification injection), and cap the length (keeps
|
|
56
|
+
* the routing map bounded). Returns the cleaned value, or null when invalid.
|
|
57
|
+
*/
|
|
58
|
+
function cleanField(raw) {
|
|
59
|
+
if (typeof raw !== 'string') return null
|
|
60
|
+
const v = raw.trim()
|
|
61
|
+
if (!v || v.length > MAX_FIELD_LENGTH || CONTROL_CHARS.test(v)) return null
|
|
62
|
+
return v
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Pre-auth per-IP rate limit, lazily created on the server object (mirrors
|
|
67
|
+
* event-ingest.js). Returns true when the request may proceed; otherwise
|
|
68
|
+
* responds 429 + Retry-After and returns false.
|
|
69
|
+
*/
|
|
70
|
+
function checkIpRateLimit(server, req, res, routeName) {
|
|
71
|
+
if (!server._mailboxIpRateLimiter) {
|
|
72
|
+
server._mailboxIpRateLimiter = new RateLimiter({
|
|
73
|
+
windowMs: MAILBOX_WINDOW_MS,
|
|
74
|
+
maxMessages: MAILBOX_IP_MAX,
|
|
75
|
+
burst: MAILBOX_IP_BURST,
|
|
76
|
+
name: 'mailbox-ip',
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
const clientIp = getRateLimitKey(req.socket?.remoteAddress || '', req)
|
|
80
|
+
const { allowed, retryAfterMs } = server._mailboxIpRateLimiter.check(clientIp)
|
|
81
|
+
if (!allowed) {
|
|
82
|
+
log.warn(`Rate limited ${routeName} from ${clientIp}`)
|
|
83
|
+
sendJson(res, 429, { error: 'rate limited', retryAfterMs })
|
|
84
|
+
return false
|
|
85
|
+
}
|
|
86
|
+
return true
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Bearer auth against the daemon ingest secret (constant-time; same token
|
|
91
|
+
* class as POST /api/events). Returns true when authorized; otherwise responds
|
|
92
|
+
* 401 and returns false.
|
|
93
|
+
*/
|
|
94
|
+
function checkIngestAuth(server, req, res) {
|
|
95
|
+
const secret = resolveIngestSecret(server)
|
|
96
|
+
const authHeader = req.headers['authorization'] || ''
|
|
97
|
+
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''
|
|
98
|
+
// safeTokenCompare on every request (even when the secret failed to load, via
|
|
99
|
+
// the null check) — no early-exit timing oracle, no raw token logged.
|
|
100
|
+
if (!secret || !safeTokenCompare(token, secret)) {
|
|
101
|
+
log.warn('Rejected mailbox request: invalid or missing ingest auth')
|
|
102
|
+
sendUnauthorized(res)
|
|
103
|
+
return false
|
|
104
|
+
}
|
|
105
|
+
return true
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Capped utf8 body read + defensive JSON parse. Invokes `onParsed(obj)` with a
|
|
110
|
+
* plain object, or responds (413/400) and does not call back. Mirrors the
|
|
111
|
+
* event-ingest.js streaming pattern (counts BYTES, reassembles multi-byte).
|
|
112
|
+
*/
|
|
113
|
+
function readCappedJson(req, res, maxBytes, onParsed) {
|
|
114
|
+
req.setEncoding('utf8')
|
|
115
|
+
let body = ''
|
|
116
|
+
let bytes = 0
|
|
117
|
+
let oversized = false
|
|
118
|
+
req.on('data', (chunk) => {
|
|
119
|
+
if (oversized) return
|
|
120
|
+
bytes += Buffer.byteLength(chunk, 'utf8')
|
|
121
|
+
if (bytes > maxBytes) {
|
|
122
|
+
oversized = true
|
|
123
|
+
sendOversizeResponse(req, res, { error: 'body too large' })
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
body += chunk
|
|
127
|
+
})
|
|
128
|
+
req.on('end', () => {
|
|
129
|
+
if (oversized) return
|
|
130
|
+
let parsed
|
|
131
|
+
try {
|
|
132
|
+
parsed = JSON.parse(body || '{}')
|
|
133
|
+
} catch {
|
|
134
|
+
sendJson(res, 400, { error: 'invalid JSON' })
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
138
|
+
sendJson(res, 400, { error: 'invalid body' })
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
onParsed(parsed)
|
|
142
|
+
})
|
|
143
|
+
req.on('error', () => {
|
|
144
|
+
if (!oversized) sendJson(res, 400, { error: 'read error' })
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* POST /api/mailbox/register — map a mailbox id (AGENT_COMM_ID) to a live
|
|
150
|
+
* sessionId so POST /api/mailbox can wake the right session.
|
|
151
|
+
* Body: { agentCommId, sessionId }
|
|
152
|
+
*/
|
|
153
|
+
export function handleMailboxRegister(server, req, res) {
|
|
154
|
+
if (!checkIpRateLimit(server, req, res, 'POST /api/mailbox/register')) return
|
|
155
|
+
if (!checkIngestAuth(server, req, res)) return
|
|
156
|
+
readCappedJson(req, res, MAX_MAILBOX_BODY_BYTES, (body) => {
|
|
157
|
+
const agentCommId = cleanField(body.agentCommId)
|
|
158
|
+
const sessionId = cleanField(body.sessionId)
|
|
159
|
+
if (!agentCommId || !sessionId) {
|
|
160
|
+
sendJson(res, 400, { error: 'agentCommId and sessionId are required' })
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const ok = server.sessionManager?.registerAgentCommId?.(sessionId, agentCommId) === true
|
|
164
|
+
if (!ok) {
|
|
165
|
+
sendJson(res, 404, { error: 'unknown session' })
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
log.info(`Registered mailbox id "${agentCommId}" -> session ${sessionId}`)
|
|
169
|
+
sendJson(res, 200, { ok: true })
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* POST /api/mailbox — "new mail" ping from agent-comm-system's emit hook.
|
|
175
|
+
* Body: { to, from, id, subject?, unread_count }
|
|
176
|
+
* Notifies and, when `to` is a live idle claude-tui session, injects a wakeup.
|
|
177
|
+
*/
|
|
178
|
+
export function handleMailboxPing(server, req, res) {
|
|
179
|
+
if (!checkIpRateLimit(server, req, res, 'POST /api/mailbox')) return
|
|
180
|
+
if (!checkIngestAuth(server, req, res)) return
|
|
181
|
+
readCappedJson(req, res, MAX_MAILBOX_BODY_BYTES, (body) => {
|
|
182
|
+
const to = cleanField(body.to)
|
|
183
|
+
if (!to) {
|
|
184
|
+
sendJson(res, 400, { error: 'to is required' })
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
const from = cleanField(body.from) || 'unknown'
|
|
188
|
+
// Non-negative integer only — a negative / fractional count would render
|
|
189
|
+
// odd notification text and wakeup prompts.
|
|
190
|
+
const unreadCount =
|
|
191
|
+
typeof body.unread_count === 'number' &&
|
|
192
|
+
Number.isInteger(body.unread_count) &&
|
|
193
|
+
body.unread_count >= 0
|
|
194
|
+
? body.unread_count
|
|
195
|
+
: null
|
|
196
|
+
|
|
197
|
+
// Notify (fire-and-forget; settlePush logs a failed delivery/rejection
|
|
198
|
+
// instead of leaving the async send's rejection unhandled).
|
|
199
|
+
const notified = Boolean(server.pushManager)
|
|
200
|
+
if (notified) {
|
|
201
|
+
const countText = unreadCount != null ? `${unreadCount} unread` : 'new message'
|
|
202
|
+
settlePush(
|
|
203
|
+
server.pushManager.send('mailbox', 'New mail', `${to}: ${countText} from ${from}`, {
|
|
204
|
+
to,
|
|
205
|
+
from,
|
|
206
|
+
id: cleanField(body.id),
|
|
207
|
+
unread_count: unreadCount,
|
|
208
|
+
external: true,
|
|
209
|
+
}),
|
|
210
|
+
'mailbox',
|
|
211
|
+
log,
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const reason = injectWakeup(server, to, unreadCount)
|
|
216
|
+
// Record the delivery for the Control Room "Mailbox" tab (observability;
|
|
217
|
+
// recordMailboxEvent never throws into the delivery path).
|
|
218
|
+
server.sessionManager?.recordMailboxEvent?.({ to, from, unreadCount, outcome: reason })
|
|
219
|
+
sendJson(res, 200, { ok: true, notified, injected: reason === 'injected', reason })
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Inject a wakeup prompt into the recipient's live session when it is safe —
|
|
225
|
+
* a claude-tui session at a quiet prompt. Uses only public session surface
|
|
226
|
+
* (`writeTerminalInput` + the `isRunning` getter). Returns the outcome reason.
|
|
227
|
+
* @returns {'injected'|'busy'|'not-tui'|'no-session'|'pty-dead'}
|
|
228
|
+
*/
|
|
229
|
+
function injectWakeup(server, to, unreadCount) {
|
|
230
|
+
const session = server.sessionManager?.resolveSessionByAgentCommId?.(to) ?? null
|
|
231
|
+
if (!session) return 'no-session'
|
|
232
|
+
// #5984 (epic #5982): gate on the positive claude-tui discriminator, NOT
|
|
233
|
+
// `typeof session.writeTerminalInput` — a user-shell session (#5983) will
|
|
234
|
+
// also expose writeTerminalInput, and duck-typing here would let the weaker
|
|
235
|
+
// ingest-secret holder inject an executed line into a root shell (swarm-audit
|
|
236
|
+
// finding C2). Only the claude-tui PTY mirror is a legitimate wakeup target.
|
|
237
|
+
// Strict `!== true` (not truthiness): this gate is security-load-bearing, so a
|
|
238
|
+
// buggy override returning a truthy non-boolean must NOT be treated as tui.
|
|
239
|
+
if (session.constructor?.isClaudeTui !== true) return 'not-tui'
|
|
240
|
+
// Defense-in-depth: isClaudeTui===true implies writeTerminalInput exists today
|
|
241
|
+
// (only ClaudeTuiSession sets the marker AND defines the method), so this is
|
|
242
|
+
// unreachable in practice — but it guards against a future class that sets the
|
|
243
|
+
// marker without the method rather than throwing on the write below.
|
|
244
|
+
if (typeof session.writeTerminalInput !== 'function') return 'not-tui'
|
|
245
|
+
// `isRunning` is true mid-turn or with background shells — inject only at a
|
|
246
|
+
// quiet prompt so we never corrupt an in-flight turn's input.
|
|
247
|
+
if (session.isRunning) return 'busy'
|
|
248
|
+
const countText = unreadCount != null ? `${unreadCount} unread mailbox message(s)` : 'unread mailbox messages'
|
|
249
|
+
const text = `You have ${countText} — run receive_next to process them.\r`
|
|
250
|
+
const ok = session.writeTerminalInput(text)
|
|
251
|
+
return ok ? 'injected' : 'pty-dead'
|
|
252
|
+
}
|
package/src/mcp-tools.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP tool name parsing utilities.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code names MCP-provided tools using the convention:
|
|
5
|
+
* mcp__<server_name>__<tool_name>
|
|
6
|
+
*
|
|
7
|
+
* Built-in tools use simple names like "Bash", "Read", "Edit".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const MCP_PREFIX = 'mcp__'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Parse an MCP tool name into its server and tool components.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} toolName - The tool name from a content_block_start event
|
|
16
|
+
* @returns {{ serverName: string, toolName: string } | null} - Parsed parts, or null for built-in tools
|
|
17
|
+
*/
|
|
18
|
+
export function parseMcpToolName(toolName) {
|
|
19
|
+
if (!toolName || !toolName.startsWith(MCP_PREFIX)) return null
|
|
20
|
+
|
|
21
|
+
const rest = toolName.slice(MCP_PREFIX.length)
|
|
22
|
+
const sep = rest.indexOf('__')
|
|
23
|
+
if (sep === -1 || sep === 0) return null
|
|
24
|
+
|
|
25
|
+
const parsedTool = rest.slice(sep + 2)
|
|
26
|
+
if (!parsedTool) return null
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
serverName: rest.slice(0, sep),
|
|
30
|
+
toolName: parsedTool,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Get a display-friendly tool label.
|
|
36
|
+
* For MCP tools: "server:tool_name"
|
|
37
|
+
* For built-in tools: the name as-is
|
|
38
|
+
*
|
|
39
|
+
* @param {string} toolName - The raw tool name
|
|
40
|
+
* @returns {string|null|undefined} The input as-is for non-MCP/falsy values, or "server:tool" for MCP
|
|
41
|
+
*/
|
|
42
|
+
export function formatToolDisplay(toolName) {
|
|
43
|
+
const parsed = parseMcpToolName(toolName)
|
|
44
|
+
if (parsed) return `${parsed.serverName}:${parsed.toolName}`
|
|
45
|
+
return toolName
|
|
46
|
+
}
|