@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,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSRF block-list — pure IP-classification logic extracted from
|
|
3
|
+
* byok-tool-executor.js (#4186).
|
|
4
|
+
*
|
|
5
|
+
* Defense-in-depth check that refuses targets in private / loopback /
|
|
6
|
+
* link-local / reserved / CGNAT / TEST-NET / benchmark / multicast ranges
|
|
7
|
+
* so a model induced into fetching `http://169.254.169.254/`,
|
|
8
|
+
* `http://127.0.0.1:<port>`, an RFC1918 address, or any IPv4-mapped
|
|
9
|
+
* IPv6 form of the same can't hit the user's local / cloud-instance
|
|
10
|
+
* environment.
|
|
11
|
+
*
|
|
12
|
+
* Pure module — no fs, no network I/O, no DNS, no `process.env` reads.
|
|
13
|
+
* The `node:net` import is only used for `isIP()` (a synchronous string
|
|
14
|
+
* classifier that does not open sockets). Caller (WebFetch /
|
|
15
|
+
* isHostAllowed in byok-tool-executor) does the DNS resolution and the
|
|
16
|
+
* `CHROXY_WEBFETCH_ALLOW_PRIVATE` opt-out check. Keeping this file side-
|
|
17
|
+
* effect free lets the test suite walk a large (ip, expected) table
|
|
18
|
+
* without any HTTP server spin-up.
|
|
19
|
+
*
|
|
20
|
+
* Background: #4132 introduced the original v4 blocklist; #4165 added the
|
|
21
|
+
* v6 path and IPv4-mapped IPv6 recursion; #4167 / #4184 expanded the v4
|
|
22
|
+
* ranges with CGNAT / TEST-NET / benchmark; #4186 extracted to this
|
|
23
|
+
* standalone module so the boundary-test table (#4185) and IPv4-mapped
|
|
24
|
+
* coverage (#4187) could grow without bloating the WebFetch integration
|
|
25
|
+
* suite. Behaviour is identical to the pre-extraction `isPrivateOrSpecialIp`
|
|
26
|
+
* — this is a pure refactor.
|
|
27
|
+
*/
|
|
28
|
+
import { isIP } from 'node:net'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Returns true if `ipStr` is an IP literal in any of the blocked ranges
|
|
32
|
+
* (or an IPv4-mapped IPv6 of one). Returns false for public-routable
|
|
33
|
+
* IPs and for non-IP input (caller should resolve hostnames via DNS
|
|
34
|
+
* first and pass each resolved address through this check).
|
|
35
|
+
*/
|
|
36
|
+
export function isPrivateOrSpecialIp(ipStr) {
|
|
37
|
+
const v = isIP(ipStr)
|
|
38
|
+
if (v === 4) {
|
|
39
|
+
const [a, b, c] = ipStr.split('.').map((p) => parseInt(p, 10))
|
|
40
|
+
if (a === 127) return true // loopback 127.0.0.0/8
|
|
41
|
+
if (a === 10) return true // RFC1918 10.0.0.0/8
|
|
42
|
+
if (a === 172 && b >= 16 && b <= 31) return true // RFC1918 172.16.0.0/12
|
|
43
|
+
if (a === 192 && b === 168) return true // RFC1918 192.168.0.0/16
|
|
44
|
+
if (a === 169 && b === 254) return true // link-local 169.254.0.0/16
|
|
45
|
+
if (a === 0) return true // 0.0.0.0/8 (this network)
|
|
46
|
+
if (a >= 224) return true // multicast + reserved
|
|
47
|
+
// #4167: defense-in-depth — ranges that aren't routable on the public
|
|
48
|
+
// internet and have a history of colliding with internal infra.
|
|
49
|
+
if (a === 100 && b >= 64 && b <= 127) return true // CGNAT 100.64.0.0/10 (RFC 6598)
|
|
50
|
+
if (a === 192 && b === 0 && c === 2) return true // TEST-NET-1 192.0.2.0/24 (RFC 5737)
|
|
51
|
+
if (a === 198 && b === 51 && c === 100) return true // TEST-NET-2 198.51.100.0/24
|
|
52
|
+
if (a === 203 && b === 0 && c === 113) return true // TEST-NET-3 203.0.113.0/24
|
|
53
|
+
if (a === 198 && (b === 18 || b === 19)) return true // benchmark 198.18.0.0/15 (RFC 2544)
|
|
54
|
+
return false
|
|
55
|
+
}
|
|
56
|
+
if (v === 6) {
|
|
57
|
+
const lower = ipStr.toLowerCase()
|
|
58
|
+
if (lower === '::1' || lower === '::') return true // loopback / unspecified
|
|
59
|
+
if (lower.startsWith('fe8') || lower.startsWith('fe9') ||
|
|
60
|
+
lower.startsWith('fea') || lower.startsWith('feb')) return true // link-local fe80::/10
|
|
61
|
+
if (lower.startsWith('fc') || lower.startsWith('fd')) return true // ULA fc00::/7
|
|
62
|
+
if (lower.startsWith('ff')) return true // multicast
|
|
63
|
+
// IPv4-mapped IPv6: ::ffff:0:0/96 — last 32 bits are the IPv4 address.
|
|
64
|
+
// Two textual forms exist:
|
|
65
|
+
// ::ffff:1.2.3.4 (dotted-quad tail)
|
|
66
|
+
// ::ffff:0102:0304 (hex tail — same address)
|
|
67
|
+
// Pre-#4165 only the dotted form was caught; ::ffff:7f00:1
|
|
68
|
+
// (= 127.0.0.1) would have bypassed the SSRF guard. Now we expand
|
|
69
|
+
// the address into 8 hex groups and if it's IPv4-mapped we
|
|
70
|
+
// materialise the v4 dotted form and recurse.
|
|
71
|
+
const v4 = mappedV6ToV4(lower)
|
|
72
|
+
if (v4) return isPrivateOrSpecialIp(v4)
|
|
73
|
+
return false
|
|
74
|
+
}
|
|
75
|
+
// Not an IP literal; caller should resolve first.
|
|
76
|
+
return false
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* If `lower` is an IPv4-mapped IPv6 address (::ffff:0:0/96), return the
|
|
81
|
+
* embedded IPv4 in dotted-quad form. Returns null for any other v6 or
|
|
82
|
+
* for malformed input.
|
|
83
|
+
*
|
|
84
|
+
* Handles BOTH textual forms — caller may pass either dotted-tail
|
|
85
|
+
* (::ffff:1.2.3.4) or hex-tail (::ffff:0102:0304). The two forms map
|
|
86
|
+
* to the same v4 and must produce the same answer.
|
|
87
|
+
*/
|
|
88
|
+
export function mappedV6ToV4(lower) {
|
|
89
|
+
if (typeof lower !== 'string') return null
|
|
90
|
+
// Expand `::` so we have exactly 8 hex groups (or 6 hex + 1 dotted v4).
|
|
91
|
+
let groups
|
|
92
|
+
if (lower.includes('.')) {
|
|
93
|
+
// Dotted-quad tail. Replace the trailing v4 with two hex groups.
|
|
94
|
+
const lastColon = lower.lastIndexOf(':')
|
|
95
|
+
if (lastColon < 0) return null
|
|
96
|
+
const head = lower.slice(0, lastColon)
|
|
97
|
+
const v4 = lower.slice(lastColon + 1)
|
|
98
|
+
if (isIP(v4) !== 4) return null
|
|
99
|
+
const [a, b, c, d] = v4.split('.').map((p) => parseInt(p, 10))
|
|
100
|
+
const hex = `${((a << 8) | b).toString(16).padStart(4, '0')}:${((c << 8) | d).toString(16).padStart(4, '0')}`
|
|
101
|
+
groups = expandV6Groups(`${head}:${hex}`)
|
|
102
|
+
} else {
|
|
103
|
+
groups = expandV6Groups(lower)
|
|
104
|
+
}
|
|
105
|
+
if (!groups || groups.length !== 8) return null
|
|
106
|
+
// IPv4-mapped means groups[0..4] are 0 and groups[5] is ffff.
|
|
107
|
+
for (let i = 0; i < 5; i++) if (groups[i] !== 0) return null
|
|
108
|
+
if (groups[5] !== 0xffff) return null
|
|
109
|
+
const g6 = groups[6]
|
|
110
|
+
const g7 = groups[7]
|
|
111
|
+
return `${(g6 >> 8) & 0xff}.${g6 & 0xff}.${(g7 >> 8) & 0xff}.${g7 & 0xff}`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function expandV6Groups(addr) {
|
|
115
|
+
const parts = addr.split('::')
|
|
116
|
+
if (parts.length > 2) return null
|
|
117
|
+
const left = parts[0] ? parts[0].split(':') : []
|
|
118
|
+
const right = parts.length === 2 && parts[1] ? parts[1].split(':') : []
|
|
119
|
+
const missing = 8 - (left.length + right.length)
|
|
120
|
+
if (missing < 0) return null
|
|
121
|
+
const middle = parts.length === 2 ? new Array(missing).fill('0') : []
|
|
122
|
+
const all = [...left, ...middle, ...right]
|
|
123
|
+
if (all.length !== 8) return null
|
|
124
|
+
const out = []
|
|
125
|
+
for (const g of all) {
|
|
126
|
+
if (!/^[0-9a-f]{1,4}$/.test(g)) return null
|
|
127
|
+
out.push(parseInt(g, 16))
|
|
128
|
+
}
|
|
129
|
+
return out
|
|
130
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side subagent counting (#5413 Phase 4).
|
|
3
|
+
*
|
|
4
|
+
* claude-code-notify tracked subagent counts in bash state files under
|
|
5
|
+
* /tmp — the root cause of the reliability pain this epic exists to fix.
|
|
6
|
+
* Here the count is DERIVED from the ingested event stream instead: the
|
|
7
|
+
* hook emitters are stateless, and this small in-memory aggregate keyed on
|
|
8
|
+
* (source, sessionId) is the only state.
|
|
9
|
+
*
|
|
10
|
+
* Semantics:
|
|
11
|
+
* - subagent_start → +1, subagent_stop → -1 (floored at 0 — stops can
|
|
12
|
+
* outnumber starts after a daemon restart; never go negative)
|
|
13
|
+
* - session_end → entry cleared (parity with the bash reset-at-end)
|
|
14
|
+
* - stale-entry expiry: entries untouched for ttlMs are swept lazily on
|
|
15
|
+
* access, so abandoned sessions (crashed CLI, never sent session_end)
|
|
16
|
+
* can't pin memory
|
|
17
|
+
* - hard cap on tracked entries: oldest-touched evicted first (the key
|
|
18
|
+
* space is attacker-influenced via sessionId, so it must be bounded
|
|
19
|
+
* even though the route is bearer-gated and rate-limited)
|
|
20
|
+
*
|
|
21
|
+
* Events without a sessionId are not counted — there is nothing to key on.
|
|
22
|
+
*
|
|
23
|
+
* Project dimension (#5463): the Discord status embed is keyed per PROJECT,
|
|
24
|
+
* and several sessions can emit into one project (main session + worktree
|
|
25
|
+
* agents remapped to the parent by the hooks' GAP B filter). Each entry
|
|
26
|
+
* therefore remembers the project its events carried, and
|
|
27
|
+
* `getProjectTotal(project)` sums the live entries of that project — the
|
|
28
|
+
* per-session entries stay the single source of truth (they carry the
|
|
29
|
+
* TTL/LRU lifecycle), so session_end and TTL/LRU eviction subtract a
|
|
30
|
+
* session's contribution automatically; there is no maintained per-project
|
|
31
|
+
* counter to drift. The total deliberately spans sources: the embed's
|
|
32
|
+
* project key has no source dimension either.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** Default time-to-live for an untouched entry. */
|
|
36
|
+
export const SUBAGENT_ENTRY_TTL_MS = 2 * 60 * 60 * 1000 // 2h
|
|
37
|
+
|
|
38
|
+
/** Hard ceiling on tracked (source, sessionId) entries. */
|
|
39
|
+
export const SUBAGENT_MAX_ENTRIES = 1000
|
|
40
|
+
|
|
41
|
+
/** Minimum interval between lazy sweeps (avoids a full scan per event). */
|
|
42
|
+
const SWEEP_INTERVAL_MS = 60 * 1000
|
|
43
|
+
|
|
44
|
+
export class SubagentCounter {
|
|
45
|
+
constructor({ ttlMs = SUBAGENT_ENTRY_TTL_MS, maxEntries = SUBAGENT_MAX_ENTRIES, now = Date.now } = {}) {
|
|
46
|
+
this._ttlMs = ttlMs
|
|
47
|
+
this._maxEntries = maxEntries
|
|
48
|
+
this._now = now
|
|
49
|
+
/** @type {Map<string, { count: number, touchedAt: number, project: string|null }>} */
|
|
50
|
+
this._entries = new Map()
|
|
51
|
+
this._lastSweepAt = 0
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
_key(source, sessionId) {
|
|
55
|
+
return `${source}\u0000${sessionId}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
_sweep(force = false) {
|
|
59
|
+
const now = this._now()
|
|
60
|
+
if (!force && now - this._lastSweepAt < SWEEP_INTERVAL_MS) return
|
|
61
|
+
this._lastSweepAt = now
|
|
62
|
+
for (const [key, entry] of this._entries) {
|
|
63
|
+
if (now - entry.touchedAt > this._ttlMs) this._entries.delete(key)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
_evictIfFull() {
|
|
68
|
+
if (this._entries.size < this._maxEntries) return
|
|
69
|
+
this._sweep(true)
|
|
70
|
+
while (this._entries.size >= this._maxEntries) {
|
|
71
|
+
// Map iteration is insertion-ordered; entries are re-inserted on
|
|
72
|
+
// touch, so the first key is the least recently touched.
|
|
73
|
+
const oldest = this._entries.keys().next().value
|
|
74
|
+
this._entries.delete(oldest)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Fold one ingested event into the counter. Returns the active count for
|
|
80
|
+
* the event's (source, sessionId) after the update, or null when the
|
|
81
|
+
* event doesn't participate (no sessionId, or an uncounted type).
|
|
82
|
+
*
|
|
83
|
+
* `project` (#5463) is the post-remap project the event was attributed to
|
|
84
|
+
* (the same key the Discord embed uses) — stored on the entry so
|
|
85
|
+
* getProjectTotal can aggregate across the sessions of one project.
|
|
86
|
+
* Latest event wins if a session's project ever changes.
|
|
87
|
+
*/
|
|
88
|
+
record(type, source, sessionId, project = null) {
|
|
89
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return null
|
|
90
|
+
this._sweep()
|
|
91
|
+
const key = this._key(source, sessionId)
|
|
92
|
+
if (type === 'session_end') {
|
|
93
|
+
this._entries.delete(key)
|
|
94
|
+
return 0
|
|
95
|
+
}
|
|
96
|
+
if (type !== 'subagent_start' && type !== 'subagent_stop') return null
|
|
97
|
+
const prev = this._entries.get(key)
|
|
98
|
+
const count = Math.max(0, (prev?.count ?? 0) + (type === 'subagent_start' ? 1 : -1))
|
|
99
|
+
// Delete-then-set keeps Map order = least-recently-touched first.
|
|
100
|
+
this._entries.delete(key)
|
|
101
|
+
if (count > 0 || type === 'subagent_stop') {
|
|
102
|
+
this._evictIfFull()
|
|
103
|
+
const normalizedProject =
|
|
104
|
+
typeof project === 'string' && project.length > 0 ? project : (prev?.project ?? null)
|
|
105
|
+
this._entries.set(key, { count, touchedAt: this._now(), project: normalizedProject })
|
|
106
|
+
}
|
|
107
|
+
return count
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Current active count for (source, sessionId); 0 when untracked/expired. */
|
|
111
|
+
getCount(source, sessionId) {
|
|
112
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return 0
|
|
113
|
+
const key = this._key(source, sessionId)
|
|
114
|
+
const entry = this._entries.get(key)
|
|
115
|
+
if (!entry) return 0
|
|
116
|
+
if (this._now() - entry.touchedAt > this._ttlMs) {
|
|
117
|
+
this._entries.delete(key)
|
|
118
|
+
return 0
|
|
119
|
+
}
|
|
120
|
+
return entry.count
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Per-project active-subagent total (#5463): the sum over all LIVE
|
|
125
|
+
* session entries attributed to `project`, across sources (the embed's
|
|
126
|
+
* project key has no source dimension). Computed lazily at read time —
|
|
127
|
+
* expired entries are dropped as they're encountered, so TTL expiry (and
|
|
128
|
+
* session_end / LRU eviction, which delete entries outright) subtracts a
|
|
129
|
+
* session's contribution with no maintained counter to drift.
|
|
130
|
+
*/
|
|
131
|
+
getProjectTotal(project) {
|
|
132
|
+
if (typeof project !== 'string' || project.length === 0) return 0
|
|
133
|
+
const now = this._now()
|
|
134
|
+
let total = 0
|
|
135
|
+
for (const [key, entry] of this._entries) {
|
|
136
|
+
if (now - entry.touchedAt > this._ttlMs) {
|
|
137
|
+
this._entries.delete(key)
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
if (entry.project === project) total += entry.count
|
|
141
|
+
}
|
|
142
|
+
return total
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Number of tracked entries (tests + observability). */
|
|
146
|
+
get size() {
|
|
147
|
+
return this._entries.size
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #5547 — server-side one-shot session summarizer.
|
|
3
|
+
*
|
|
4
|
+
* Produces a CONTINUATION BRIEF from a session's persisted message history so
|
|
5
|
+
* the operator can right-click a session in the dashboard sidebar, summarize
|
|
6
|
+
* it, and seed a fresh session with the result (cross-session `/compact`).
|
|
7
|
+
*
|
|
8
|
+
* Design:
|
|
9
|
+
* - History source is the session's `SessionMessageHistory` ring buffer
|
|
10
|
+
* (the universal, restart-surviving source — works even when the provider
|
|
11
|
+
* subprocess is gone). Entries are flattened with `extractSearchableText`
|
|
12
|
+
* from conversation-search.js — NOT re-derived here.
|
|
13
|
+
* - Long histories are WINDOWED before the model call: a small head sample
|
|
14
|
+
* plus the most-recent tail, capped at MAX_SUMMARIZE_CHARS. When truncated,
|
|
15
|
+
* the brief's header says so (and the result carries `truncated: true`).
|
|
16
|
+
* - Summarization is a ONE-SHOT model call (the SDK `query()` path), NOT a
|
|
17
|
+
* chat session — a short-lived invocation with no tools. Defaults to the
|
|
18
|
+
* target session's own model; `summarize.{provider,model}` config overrides.
|
|
19
|
+
*
|
|
20
|
+
* The model invocation is injectable (`runOneShot`) so the windowing/prompt
|
|
21
|
+
* logic is unit-testable without a live provider.
|
|
22
|
+
*/
|
|
23
|
+
import { query } from '@anthropic-ai/claude-agent-sdk'
|
|
24
|
+
import { extractSearchableText } from './conversation-search.js'
|
|
25
|
+
import { createLogger } from './logger.js'
|
|
26
|
+
|
|
27
|
+
const log = createLogger('summarize')
|
|
28
|
+
|
|
29
|
+
// Cap the summarizer input. The tail (most-recent) gets the lion's share; a
|
|
30
|
+
// small head sample preserves the opening goals/context. Chosen to stay well
|
|
31
|
+
// inside a cheap model's context while covering the bulk of a long session.
|
|
32
|
+
export const MAX_SUMMARIZE_CHARS = 100_000
|
|
33
|
+
// Head sample size when the history overflows the cap — enough to capture the
|
|
34
|
+
// initial task framing without eating into the recent-tail budget.
|
|
35
|
+
export const HEAD_SAMPLE_CHARS = 8_000
|
|
36
|
+
// Marker inserted between the head sample and the recent tail when truncated.
|
|
37
|
+
const TRUNCATION_MARKER = '\n\n[... earlier conversation omitted (history windowed for summarization) ...]\n\n'
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Flatten a session's history entries to a single transcript string, reusing
|
|
41
|
+
* `extractSearchableText` per entry. Each entry is prefixed with a coarse role
|
|
42
|
+
* label derived from its chroxy history `type` so the model can tell user turns
|
|
43
|
+
* from assistant/tool output. Entries that flatten to empty text are skipped.
|
|
44
|
+
*
|
|
45
|
+
* @param {Array<object>} history - SessionMessageHistory entries.
|
|
46
|
+
* @returns {string} newline-joined transcript.
|
|
47
|
+
*/
|
|
48
|
+
export function flattenHistory(history) {
|
|
49
|
+
if (!Array.isArray(history)) return ''
|
|
50
|
+
const lines = []
|
|
51
|
+
for (const entry of history) {
|
|
52
|
+
if (!entry || typeof entry !== 'object') continue
|
|
53
|
+
// extractSearchableText reads entry.message.content; chroxy history entries
|
|
54
|
+
// store their text on `content`. Normalize so the shared flattener sees a
|
|
55
|
+
// message-shaped object regardless of which source produced the entry.
|
|
56
|
+
const text = entryToText(entry)
|
|
57
|
+
if (!text) continue
|
|
58
|
+
lines.push(`${roleLabel(entry.type)}: ${text}`)
|
|
59
|
+
}
|
|
60
|
+
return lines.join('\n')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Pull readable text out of one history entry. Tries the shared
|
|
65
|
+
* `extractSearchableText` (JSONL message-shaped entries) first, then falls back
|
|
66
|
+
* to chroxy's ring-buffer shape (`content` string, optional `tool` label).
|
|
67
|
+
*
|
|
68
|
+
* @param {object} entry
|
|
69
|
+
* @returns {string}
|
|
70
|
+
*/
|
|
71
|
+
function entryToText(entry) {
|
|
72
|
+
// JSONL / message-shaped entry: let the shared flattener handle it.
|
|
73
|
+
const viaShared = extractSearchableText(entry).trim()
|
|
74
|
+
if (viaShared) return viaShared
|
|
75
|
+
|
|
76
|
+
// chroxy ring-buffer shape: { type, content, tool?, timestamp }
|
|
77
|
+
const parts = []
|
|
78
|
+
if (typeof entry.tool === 'string' && entry.tool) parts.push(`[${entry.tool}]`)
|
|
79
|
+
if (typeof entry.content === 'string' && entry.content) {
|
|
80
|
+
parts.push(entry.content)
|
|
81
|
+
} else if (Array.isArray(entry.content)) {
|
|
82
|
+
for (const block of entry.content) {
|
|
83
|
+
if (block && block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return parts.join(' ').trim()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Coarse role label for a chroxy history entry `type`.
|
|
91
|
+
* @param {string} type
|
|
92
|
+
* @returns {string}
|
|
93
|
+
*/
|
|
94
|
+
function roleLabel(type) {
|
|
95
|
+
switch (type) {
|
|
96
|
+
case 'user_input': return 'User'
|
|
97
|
+
case 'response': return 'Assistant'
|
|
98
|
+
case 'tool_use': return 'Tool'
|
|
99
|
+
default: return type === undefined || type === null ? 'Entry' : String(type)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Window a flattened transcript to fit MAX_SUMMARIZE_CHARS. Under the cap the
|
|
105
|
+
* transcript passes through untouched. Over the cap, keep a head sample +
|
|
106
|
+
* the most-recent tail joined by a truncation marker.
|
|
107
|
+
*
|
|
108
|
+
* @param {string} transcript
|
|
109
|
+
* @param {object} [opts]
|
|
110
|
+
* @param {number} [opts.maxChars]
|
|
111
|
+
* @param {number} [opts.headChars]
|
|
112
|
+
* @returns {{ text: string, truncated: boolean }}
|
|
113
|
+
*/
|
|
114
|
+
export function windowTranscript(transcript, opts = {}) {
|
|
115
|
+
const text = typeof transcript === 'string' ? transcript : ''
|
|
116
|
+
const maxChars = Number.isFinite(opts.maxChars) && opts.maxChars > 0 ? opts.maxChars : MAX_SUMMARIZE_CHARS
|
|
117
|
+
const headChars = Number.isFinite(opts.headChars) && opts.headChars >= 0 ? opts.headChars : HEAD_SAMPLE_CHARS
|
|
118
|
+
|
|
119
|
+
if (text.length <= maxChars) {
|
|
120
|
+
return { text, truncated: false }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Reserve the head sample + marker; the rest is the most-recent tail.
|
|
124
|
+
const effectiveHead = Math.min(headChars, Math.floor(maxChars / 2))
|
|
125
|
+
const tailBudget = maxChars - effectiveHead - TRUNCATION_MARKER.length
|
|
126
|
+
const head = effectiveHead > 0 ? text.slice(0, effectiveHead) : ''
|
|
127
|
+
const tail = tailBudget > 0 ? text.slice(text.length - tailBudget) : text.slice(text.length - maxChars)
|
|
128
|
+
const windowed = `${head}${TRUNCATION_MARKER}${tail}`
|
|
129
|
+
// Honour the contract for ANY maxChars > 0: when the cap is so small that the
|
|
130
|
+
// head + marker already exceed it (tailBudget <= 0), the assembled string can
|
|
131
|
+
// overshoot. Clamp to the most-recent maxChars so the return is always
|
|
132
|
+
// <= maxChars. (Unreachable at the production 100k cap; guards custom opts.)
|
|
133
|
+
return {
|
|
134
|
+
text: windowed.length <= maxChars ? windowed : windowed.slice(windowed.length - maxChars),
|
|
135
|
+
truncated: true,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Build the one-shot prompt asking the model for a continuation brief written
|
|
141
|
+
* for the NEXT session to consume (not prose for a human).
|
|
142
|
+
*
|
|
143
|
+
* @param {object} args
|
|
144
|
+
* @param {string} args.transcript - the (windowed) flattened transcript.
|
|
145
|
+
* @param {boolean} args.truncated - whether the transcript was windowed.
|
|
146
|
+
* @param {string} [args.sessionName] - human label for the source session.
|
|
147
|
+
* @returns {string}
|
|
148
|
+
*/
|
|
149
|
+
export function buildSummaryPrompt({ transcript, truncated, sessionName }) {
|
|
150
|
+
const truncationNote = truncated
|
|
151
|
+
? 'NOTE: the transcript below was WINDOWED (a head sample plus the most-recent tail) because the full history exceeded the size cap. State this caveat in your brief\'s header so the next session knows earlier detail may be missing.\n\n'
|
|
152
|
+
: ''
|
|
153
|
+
const label = typeof sessionName === 'string' && sessionName.trim()
|
|
154
|
+
? ` (source session: "${sessionName.trim()}")`
|
|
155
|
+
: ''
|
|
156
|
+
return [
|
|
157
|
+
`You are writing a CONTINUATION BRIEF${label} so a fresh agent session can pick up this work with no other context.`,
|
|
158
|
+
'Write for the NEXT session to consume — terse, structured, machine-actionable — NOT prose for a human reader.',
|
|
159
|
+
'',
|
|
160
|
+
'Cover, as headed sections, only what the transcript supports:',
|
|
161
|
+
'- Goal / task: what the session set out to do.',
|
|
162
|
+
'- Current state: what is done, in progress, or verified.',
|
|
163
|
+
'- Key decisions: choices made and the reasoning, so they are not relitigated.',
|
|
164
|
+
'- Open threads: unfinished work, known issues, next steps.',
|
|
165
|
+
'- Key file paths: files touched or central to the work (absolute paths where given).',
|
|
166
|
+
'',
|
|
167
|
+
'Be faithful to the transcript; do not invent facts. If a section has nothing, omit it.',
|
|
168
|
+
'',
|
|
169
|
+
truncationNote,
|
|
170
|
+
'--- TRANSCRIPT START ---',
|
|
171
|
+
transcript,
|
|
172
|
+
'--- TRANSCRIPT END ---',
|
|
173
|
+
].join('\n')
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Default one-shot model runner: the SDK `query()` path with NO tools, a single
|
|
178
|
+
* user prompt, and the result text collected from assistant content blocks.
|
|
179
|
+
* Used when the caller doesn't inject a `runOneShot` seam.
|
|
180
|
+
*
|
|
181
|
+
* @param {object} args
|
|
182
|
+
* @param {string} args.prompt
|
|
183
|
+
* @param {string} [args.model] - model id; omitted lets the SDK pick its default.
|
|
184
|
+
* @param {string} [args.cwd]
|
|
185
|
+
* @param {AbortSignal} [args.signal]
|
|
186
|
+
* @returns {Promise<string>} the model's text reply.
|
|
187
|
+
*/
|
|
188
|
+
export async function defaultRunOneShot({ prompt, model, cwd, signal }) {
|
|
189
|
+
const options = {
|
|
190
|
+
// No tools — a pure text summarization turn. The session must not be able
|
|
191
|
+
// to read/write files or run commands during summarization.
|
|
192
|
+
tools: { type: 'preset', preset: 'empty' },
|
|
193
|
+
permissionMode: 'bypassPermissions',
|
|
194
|
+
allowDangerouslySkipPermissions: true,
|
|
195
|
+
includePartialMessages: false,
|
|
196
|
+
maxTurns: 1,
|
|
197
|
+
}
|
|
198
|
+
if (typeof cwd === 'string' && cwd) options.cwd = cwd
|
|
199
|
+
if (typeof model === 'string' && model) options.model = model
|
|
200
|
+
if (signal) options.abortController = abortControllerFromSignal(signal)
|
|
201
|
+
|
|
202
|
+
const parts = []
|
|
203
|
+
const stream = query({ prompt, options })
|
|
204
|
+
for await (const msg of stream) {
|
|
205
|
+
if (msg?.type === 'assistant' && Array.isArray(msg.message?.content)) {
|
|
206
|
+
for (const block of msg.message.content) {
|
|
207
|
+
if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
208
|
+
}
|
|
209
|
+
} else if (msg?.type === 'result' && typeof msg.result === 'string' && parts.length === 0) {
|
|
210
|
+
// Fallback: some SDK builds carry the final text on the result message
|
|
211
|
+
// rather than (or in addition to) assistant blocks.
|
|
212
|
+
parts.push(msg.result)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return parts.join('').trim()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Bridge a plain AbortSignal to the SDK's `abortController` option (the SDK
|
|
220
|
+
* wants a controller, not a bare signal). When the upstream signal aborts, we
|
|
221
|
+
* abort the derived controller.
|
|
222
|
+
*/
|
|
223
|
+
function abortControllerFromSignal(signal) {
|
|
224
|
+
const controller = new AbortController()
|
|
225
|
+
if (signal.aborted) controller.abort()
|
|
226
|
+
else signal.addEventListener('abort', () => controller.abort(), { once: true })
|
|
227
|
+
return controller
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Summarize a session's history into a continuation brief. Orchestrates
|
|
232
|
+
* flatten → window → prompt → one-shot model call. The model call is injected
|
|
233
|
+
* (`runOneShot`) so this is testable without a provider; production uses
|
|
234
|
+
* `defaultRunOneShot`.
|
|
235
|
+
*
|
|
236
|
+
* @param {object} args
|
|
237
|
+
* @param {Array<object>} args.history - SessionMessageHistory entries.
|
|
238
|
+
* @param {string} [args.model] - model id to summarize with (default: session's).
|
|
239
|
+
* @param {string} [args.cwd] - working dir for the one-shot.
|
|
240
|
+
* @param {string} [args.sessionName] - human label for the brief header.
|
|
241
|
+
* @param {Function} [args.runOneShot] - injected model runner.
|
|
242
|
+
* @param {AbortSignal} [args.signal]
|
|
243
|
+
* @returns {Promise<{ summary: string, truncated: boolean }>}
|
|
244
|
+
* @throws {Error} when there is no history to summarize or the model returns empty.
|
|
245
|
+
*/
|
|
246
|
+
export async function summarizeSession({ history, model, cwd, sessionName, runOneShot, signal } = {}) {
|
|
247
|
+
const transcript = flattenHistory(history)
|
|
248
|
+
if (!transcript.trim()) {
|
|
249
|
+
const err = new Error('Session has no readable history to summarize')
|
|
250
|
+
err.reason = 'empty-history'
|
|
251
|
+
throw err
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const { text, truncated } = windowTranscript(transcript)
|
|
255
|
+
const prompt = buildSummaryPrompt({ transcript: text, truncated, sessionName })
|
|
256
|
+
|
|
257
|
+
const runner = typeof runOneShot === 'function' ? runOneShot : defaultRunOneShot
|
|
258
|
+
const summary = await runner({ prompt, model, cwd, signal })
|
|
259
|
+
|
|
260
|
+
if (typeof summary !== 'string' || !summary.trim()) {
|
|
261
|
+
const err = new Error('The summarizer returned no text')
|
|
262
|
+
err.reason = 'empty-summary'
|
|
263
|
+
throw err
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
log.info(`Summarized session${sessionName ? ` "${sessionName}"` : ''}: ${history.length} entries → ${summary.length} chars${truncated ? ' (windowed)' : ''}`)
|
|
267
|
+
return { summary: summary.trim(), truncated }
|
|
268
|
+
}
|