@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,441 @@
|
|
|
1
|
+
import { spawn } from 'child_process'
|
|
2
|
+
import { createInterface } from 'readline'
|
|
3
|
+
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
4
|
+
import { createLogger } from './logger.js'
|
|
5
|
+
import { guardChildStreams } from './child-stream-guard.js'
|
|
6
|
+
import { getErrorMessage } from './utils/error-message.js'
|
|
7
|
+
import { prepareSpawn } from './utils/win-spawn.js'
|
|
8
|
+
|
|
9
|
+
const log = createLogger('jsonl-subprocess-session')
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* JsonlSubprocessSession — shared spawn/readline/event-handling for session
|
|
13
|
+
* providers that drive a CLI as a one-shot JSONL subprocess per message
|
|
14
|
+
* (Codex, Gemini; future: Aider, Ollama).
|
|
15
|
+
*
|
|
16
|
+
* Subclasses supply the binary, the argv builder, the event mapper, and a few
|
|
17
|
+
* descriptive constants; everything else (process lifecycle, readline loop,
|
|
18
|
+
* stderr capture, error propagation, busy-flag bookkeeping) lives here.
|
|
19
|
+
*
|
|
20
|
+
* Required subclass overrides (statics):
|
|
21
|
+
* - binaryCandidates — array of absolute binary paths tried in order
|
|
22
|
+
* - resolvedBinary — result of resolveBinary(name, candidates)
|
|
23
|
+
* - apiKeyEnv — env var name required for start() (e.g. 'OPENAI_API_KEY')
|
|
24
|
+
* - providerName — short name used for log prefixes / error text (e.g. 'codex')
|
|
25
|
+
*
|
|
26
|
+
* Optional subclass overrides (statics — defaults derived from providerName):
|
|
27
|
+
* - displayLabel — human label used in error text (defaults to providerName)
|
|
28
|
+
* - messageIdPrefix — prefix for generated message IDs (defaults to providerName)
|
|
29
|
+
*
|
|
30
|
+
* Note: the required statics above throw when accessed on an unconfigured subclass,
|
|
31
|
+
* but this happens at the time the getter is first read (e.g. during start() or
|
|
32
|
+
* sendMessage()), not at module-load time.
|
|
33
|
+
*
|
|
34
|
+
* Required instance overrides:
|
|
35
|
+
* - _buildArgs(text) — argv for spawn; inject model flag etc.
|
|
36
|
+
* - _buildChildEnv() — env map passed to spawn (buildSpawnEnv wrapper)
|
|
37
|
+
* - _processJsonlLine(event, ctx) — map one parsed JSONL event to emitter calls
|
|
38
|
+
*
|
|
39
|
+
* Optional hooks (default no-op):
|
|
40
|
+
* - _shouldSkipStderr(msg) — return true to drop a stderr line entirely
|
|
41
|
+
* - _emitFallbackResult(ctx) — fires on close; default emits minimal result
|
|
42
|
+
*
|
|
43
|
+
* The `ctx` passed to _processJsonlLine() / _emitFallbackResult() is mutable
|
|
44
|
+
* and shared across all callbacks for a single sendMessage() invocation:
|
|
45
|
+
* {
|
|
46
|
+
* messageId: string, // id shared by stream_start/delta/end for this turn
|
|
47
|
+
* didStreamStart: bool, // has a stream_start been emitted yet?
|
|
48
|
+
* didEmitResult: bool, // has the stream produced a `result` event?
|
|
49
|
+
* proc: ChildProcess, // the spawned child, exposed for rare edge cases
|
|
50
|
+
* }
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
const DEFAULT_STDERR_CAP = 1024
|
|
54
|
+
const STDERR_SLICE_FOR_ERROR = 500
|
|
55
|
+
|
|
56
|
+
export class JsonlSubprocessSession extends BaseSession {
|
|
57
|
+
|
|
58
|
+
// ------------------------------------------------------------------
|
|
59
|
+
// Static overrides — all throw by default so misconfigured subclasses
|
|
60
|
+
// fail loudly at module-load time rather than at first sendMessage().
|
|
61
|
+
// ------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
static get binaryCandidates() {
|
|
64
|
+
throw new Error(`${this.name}.binaryCandidates must be overridden`)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
static get resolvedBinary() {
|
|
68
|
+
throw new Error(`${this.name}.resolvedBinary must be overridden`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static get apiKeyEnv() {
|
|
72
|
+
throw new Error(`${this.name}.apiKeyEnv must be overridden`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* #6563 — whether this provider can authenticate WITHOUT `apiKeyEnv` set
|
|
77
|
+
* (e.g. Codex OAuth tokens in ~/.codex/auth.json from `codex login`). When
|
|
78
|
+
* true, start() does NOT throw on a missing env var. Base default: false
|
|
79
|
+
* (env-var-only). A subclass with a non-env credential source overrides this
|
|
80
|
+
* to reuse the SAME probe its resolveAuth()/preflight use, so display, runtime,
|
|
81
|
+
* and preflight share one definition of "authenticated".
|
|
82
|
+
*/
|
|
83
|
+
static hasAlternativeCredentials() {
|
|
84
|
+
return false
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
static get providerName() {
|
|
88
|
+
throw new Error(`${this.name}.providerName must be overridden`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
static get displayLabel() {
|
|
92
|
+
return this.providerName
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
static get messageIdPrefix() {
|
|
96
|
+
return this.providerName
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ------------------------------------------------------------------
|
|
100
|
+
// Lifecycle
|
|
101
|
+
// ------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
constructor(opts = {}) {
|
|
104
|
+
// #5367: forward every BaseSession opt via the canonical picker (preserves
|
|
105
|
+
// the #3805 / #4660 / #3899 / #4790 / #5288 plumbing that this middle layer
|
|
106
|
+
// historically had to re-declare by hand — the trap documented in
|
|
107
|
+
// [[feedback_jsonl_subprocess_middle_layer]]). The lone override is
|
|
108
|
+
// permissionMode, which defaults to 'auto' for subprocess providers.
|
|
109
|
+
super(buildBaseSessionOpts(opts, { permissionMode: opts.permissionMode || 'auto' }))
|
|
110
|
+
// JsonlSubprocessSession-local opt (not a BaseSession opt).
|
|
111
|
+
const { resumeSessionId } = opts
|
|
112
|
+
// #3865: accept resumeSessionId from constructor so SessionManager's
|
|
113
|
+
// serializeState/restoreState path carries a captured Codex thread_id
|
|
114
|
+
// across server restarts. Without this, persistence was wired up at
|
|
115
|
+
// every layer EXCEPT here, so restored Codex sessions silently lost
|
|
116
|
+
// their thread and the user experienced the same "context loss" the
|
|
117
|
+
// PR was supposed to fix.
|
|
118
|
+
this.resumeSessionId = resumeSessionId || null
|
|
119
|
+
this._process = null
|
|
120
|
+
// Skills MVP (#2957) — providers without a system-prompt flag (Codex,
|
|
121
|
+
// Gemini) prepend skills text to the first user message only.
|
|
122
|
+
this._skillsPrepended = false
|
|
123
|
+
// #4881: provider parity with CliSession's #4602 _intentionalStop flag.
|
|
124
|
+
// Set by `interrupt()` immediately before SIGINT-ing the child, then
|
|
125
|
+
// consumed inside `proc.on('close')` so a user-initiated Stop:
|
|
126
|
+
// - suppresses the loud "{provider} process exited with code N" error
|
|
127
|
+
// emit (SIGINT exits the JSONL subprocess with code 130 or null
|
|
128
|
+
// depending on the CLI), and
|
|
129
|
+
// - emits a single transient `stopped` event with the exit `code` so
|
|
130
|
+
// the dashboard/mobile UX can render the same quiet confirmation
|
|
131
|
+
// surface PR #4868 wired for CliSession.
|
|
132
|
+
// Single-use: cleared on every close path (close, destroy) so the flag
|
|
133
|
+
// never leaks past one sendMessage cycle. Matches CliSession's
|
|
134
|
+
// capture-and-clear discipline in `_handleChildClose`.
|
|
135
|
+
// The flag itself is declared+initialized on BaseSession (#5375).
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
start() {
|
|
139
|
+
const envVar = this.constructor.apiKeyEnv
|
|
140
|
+
// #6563: OAuth-only providers (Codex via `codex login`) have no env key — the
|
|
141
|
+
// child authenticates from its OAuth file (e.g. ~/.codex/auth.json; HOME is
|
|
142
|
+
// forwarded to the child). Only throw when there is NEITHER the env var NOR an
|
|
143
|
+
// alternative credential source, so a `codex login`-only user isn't rejected
|
|
144
|
+
// by the runtime despite resolveAuth() reporting ready.
|
|
145
|
+
if (!process.env[envVar] && !this.constructor.hasAlternativeCredentials()) {
|
|
146
|
+
throw new Error(`${envVar} environment variable is not set`)
|
|
147
|
+
}
|
|
148
|
+
this._processReady = true
|
|
149
|
+
process.nextTick(() => {
|
|
150
|
+
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
destroy() {
|
|
155
|
+
this._destroying = true
|
|
156
|
+
this._processReady = false
|
|
157
|
+
this._isBusy = false
|
|
158
|
+
// #4881: clear so a teardown after interrupt() never leaks the flag past
|
|
159
|
+
// this session instance. Mirrors CliSession.destroy() (#4602).
|
|
160
|
+
this._clearIntentionalStop()
|
|
161
|
+
if (this._process) {
|
|
162
|
+
try {
|
|
163
|
+
this._process.kill('SIGTERM')
|
|
164
|
+
} catch { /* already dead */ }
|
|
165
|
+
this._process = null
|
|
166
|
+
}
|
|
167
|
+
this.removeAllListeners()
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interrupt() {
|
|
171
|
+
if (!this._process) return
|
|
172
|
+
// #4881: mark the imminent child exit as user-initiated so the
|
|
173
|
+
// proc.on('close') handler suppresses the "exited with code N" error and
|
|
174
|
+
// instead emits a quiet `stopped` event with the exit code. Cleared in
|
|
175
|
+
// the close handler (single-use, mirrors CliSession #4602).
|
|
176
|
+
this.markIntentionalStop()
|
|
177
|
+
try {
|
|
178
|
+
this._process.kill('SIGINT')
|
|
179
|
+
} catch { /* already dead */ }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
setPermissionMode(_mode) {
|
|
183
|
+
// Subprocess providers don't support mode switching mid-flight. Subclasses
|
|
184
|
+
// may override if their CLI gains support.
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ------------------------------------------------------------------
|
|
188
|
+
// Required subclass methods
|
|
189
|
+
// ------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
/** @returns {string[]} argv passed to spawn() */
|
|
192
|
+
_buildArgs(_text) {
|
|
193
|
+
throw new Error(`${this.constructor.name}._buildArgs must be overridden`)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** @returns {object} env map passed to spawn() */
|
|
197
|
+
_buildChildEnv() {
|
|
198
|
+
throw new Error(`${this.constructor.name}._buildChildEnv must be overridden`)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Map a single parsed JSONL event to emitter calls. Mutate `ctx` to flip
|
|
203
|
+
* didStreamStart / didEmitResult as appropriate.
|
|
204
|
+
*
|
|
205
|
+
* @param {object} _event parsed JSON line
|
|
206
|
+
* @param {object} _ctx shared per-sendMessage mutable context
|
|
207
|
+
*/
|
|
208
|
+
_processJsonlLine(_event, _ctx) {
|
|
209
|
+
throw new Error(`${this.constructor.name}._processJsonlLine must be overridden`)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ------------------------------------------------------------------
|
|
213
|
+
// Optional subclass hooks
|
|
214
|
+
// ------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
/** Return true to silently drop a stderr line (e.g. node DeprecationWarning). */
|
|
217
|
+
_shouldSkipStderr(_msg) {
|
|
218
|
+
return false
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Emitted from close when the JSONL stream never produced a `result`.
|
|
223
|
+
* Default: emit a minimal result so clients transition from busy → idle.
|
|
224
|
+
* Codex overrides to only emit when turn.completed was missing.
|
|
225
|
+
*/
|
|
226
|
+
_emitFallbackResult(_ctx) {
|
|
227
|
+
this.emit('result', { cost: null, duration: null, usage: null, sessionId: null })
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ------------------------------------------------------------------
|
|
231
|
+
// sendMessage — the shared runtime
|
|
232
|
+
// ------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
async sendMessage(text, attachments, _options) {
|
|
235
|
+
if (!this._processReady) {
|
|
236
|
+
this.emit('error', { message: 'Session is not running' })
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
if (this._isBusy) {
|
|
240
|
+
this.emit('error', { message: 'Session is busy' })
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
if (attachments && attachments.length > 0) {
|
|
244
|
+
this.emit('error', {
|
|
245
|
+
message: `${this.constructor.displayLabel} provider does not support attachments`,
|
|
246
|
+
})
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const Klass = this.constructor
|
|
251
|
+
this._isBusy = true
|
|
252
|
+
// `{providerLabel}-msg-{bootPrefix}-{counter}` — the bootPrefix from
|
|
253
|
+
// BaseSession ensures messageIds from different server boots can never
|
|
254
|
+
// collide with the dashboard's localStorage cache (#3700). Without
|
|
255
|
+
// it, Codex/Gemini sessions would still hit the same collision class
|
|
256
|
+
// that CliSession/SdkSession were fixed for.
|
|
257
|
+
this._currentMessageId = `${Klass.messageIdPrefix}-msg-${this._messageIdPrefix}-${++this._messageCounter}`
|
|
258
|
+
|
|
259
|
+
// Skills MVP (#2957) — prepend skills text to the first user message when
|
|
260
|
+
// the provider has no system-prompt flag (Codex, Gemini). Only done once
|
|
261
|
+
// per session; subsequent messages flow through unmodified.
|
|
262
|
+
//
|
|
263
|
+
// Per-skill injection mode (#3200): subprocess providers have only one
|
|
264
|
+
// injection channel — the user message. Skills that asked for
|
|
265
|
+
// `injection: append` / `system` (the system-prompt channel) have
|
|
266
|
+
// nowhere else to land here, so we concatenate both buckets. The
|
|
267
|
+
// provider-default mode for Codex / Gemini is `prepend`, so in
|
|
268
|
+
// practice every loaded skill ends up in the prepend bucket and the
|
|
269
|
+
// system-prompt bucket is empty; the concat is defensive against
|
|
270
|
+
// user-authored frontmatter that pins `injection: append` explicitly.
|
|
271
|
+
//
|
|
272
|
+
// Header dedupe (#3228): build the combined payload via
|
|
273
|
+
// `_buildCombinedSkillsPrefix()` so the `# User skills` header is
|
|
274
|
+
// rendered exactly once at the top. The previous implementation
|
|
275
|
+
// concatenated the string outputs of `_buildPrependPrompt()` and
|
|
276
|
+
// `_buildSystemPrompt()` directly; each carries its own header and
|
|
277
|
+
// the join produced two headers in the user-message prefix.
|
|
278
|
+
//
|
|
279
|
+
// The `_skillsPrepended` flag is flipped AFTER the spawn succeeds (#3225).
|
|
280
|
+
// If spawn throws synchronously, leaving the flag false ensures the next
|
|
281
|
+
// sendMessage() retry still includes the skills text — otherwise a
|
|
282
|
+
// failed first turn would leak the skill bucket forever.
|
|
283
|
+
let effectiveText = text
|
|
284
|
+
let willPrependSkills = false
|
|
285
|
+
if (!this._skillsPrepended) {
|
|
286
|
+
const combined = typeof this._buildCombinedSkillsPrefix === 'function'
|
|
287
|
+
? this._buildCombinedSkillsPrefix()
|
|
288
|
+
: ''
|
|
289
|
+
if (combined) {
|
|
290
|
+
effectiveText = `${combined}\n\n---\n\n${text}`
|
|
291
|
+
}
|
|
292
|
+
willPrependSkills = true
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const args = this._buildArgs(effectiveText)
|
|
296
|
+
let proc
|
|
297
|
+
try {
|
|
298
|
+
// #6484 — the resolver can hand us a `.cmd` shim on Windows (npm-only host,
|
|
299
|
+
// no native `.exe`); spawning a `.cmd` via child_process throws EINVAL on
|
|
300
|
+
// Node 24, so route it through cmd.exe with proper escaping — the same
|
|
301
|
+
// prepareSpawn cli-session.js uses. No-op for a `.exe` and on POSIX.
|
|
302
|
+
const spawnSpec = prepareSpawn(Klass.resolvedBinary, args)
|
|
303
|
+
proc = spawn(spawnSpec.command, spawnSpec.args, {
|
|
304
|
+
cwd: this.cwd,
|
|
305
|
+
// We pass the prompt as argv, not stdin. Some CLIs, notably
|
|
306
|
+
// `codex exec`, treat an open stdin pipe as extra prompt input and
|
|
307
|
+
// wait for EOF forever, leaving the session stuck busy.
|
|
308
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
309
|
+
env: this._buildChildEnv(),
|
|
310
|
+
...spawnSpec.options,
|
|
311
|
+
})
|
|
312
|
+
} catch (err) {
|
|
313
|
+
// spawn() can throw synchronously (ENOENT for missing binary, EACCES,
|
|
314
|
+
// etc.) — leave _skillsPrepended false so a retry still injects the
|
|
315
|
+
// skills text. Reset busy state and surface the error to the caller.
|
|
316
|
+
this._isBusy = false
|
|
317
|
+
this.emit('error', {
|
|
318
|
+
message: getErrorMessage(err, `Failed to spawn ${Klass.providerName}`),
|
|
319
|
+
})
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Spawn succeeded: argv is committed to the wire, so flip the flag.
|
|
324
|
+
if (willPrependSkills) {
|
|
325
|
+
this._skillsPrepended = true
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
this._process = proc
|
|
329
|
+
|
|
330
|
+
const ctx = {
|
|
331
|
+
messageId: this._currentMessageId,
|
|
332
|
+
didStreamStart: false,
|
|
333
|
+
didEmitResult: false,
|
|
334
|
+
proc,
|
|
335
|
+
}
|
|
336
|
+
// Two buffers: `stderrBuf` collects high-signal lines (those the
|
|
337
|
+
// subclass did NOT skip via _shouldSkipStderr); `rawStderrBuf` collects
|
|
338
|
+
// every line as a fallback so non-zero exits never surface as a bare
|
|
339
|
+
// "exited with code N" with no detail (#3834). A subclass filter that's
|
|
340
|
+
// too aggressive — or a CLI that writes its real failure reason in a
|
|
341
|
+
// line that doesn't match the filter — would otherwise hide the cause.
|
|
342
|
+
let stderrBuf = ''
|
|
343
|
+
let rawStderrBuf = ''
|
|
344
|
+
|
|
345
|
+
const rl = createInterface({ input: proc.stdout })
|
|
346
|
+
|
|
347
|
+
rl.on('line', (line) => {
|
|
348
|
+
if (this._destroying) return
|
|
349
|
+
const event = this._parseJsonLine(line)
|
|
350
|
+
if (!event) return
|
|
351
|
+
this._processJsonlLine(event, ctx)
|
|
352
|
+
})
|
|
353
|
+
|
|
354
|
+
proc.stderr.on('data', (chunk) => {
|
|
355
|
+
if (this._destroying) return
|
|
356
|
+
// Split per-line so _shouldSkipStderr is applied to each line individually.
|
|
357
|
+
// A single data chunk may contain multiple lines; trimming the whole chunk
|
|
358
|
+
// would cause a skippable line (e.g. DeprecationWarning) to suppress real
|
|
359
|
+
// error lines that share the same chunk.
|
|
360
|
+
const lines = chunk.toString().split('\n')
|
|
361
|
+
for (const line of lines) {
|
|
362
|
+
const msg = line.trim()
|
|
363
|
+
if (!msg) continue
|
|
364
|
+
if (rawStderrBuf.length < DEFAULT_STDERR_CAP) {
|
|
365
|
+
rawStderrBuf += (rawStderrBuf ? '\n' : '') + msg
|
|
366
|
+
}
|
|
367
|
+
if (this._shouldSkipStderr(msg)) continue
|
|
368
|
+
if (stderrBuf.length < DEFAULT_STDERR_CAP) {
|
|
369
|
+
stderrBuf += (stderrBuf ? '\n' : '') + msg
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
})
|
|
373
|
+
|
|
374
|
+
// #5324 (WP-5.2) — guard the child's stdout/stderr streams against an
|
|
375
|
+
// unhandled 'error' event that would crash the daemon. Shared helper (P2-9);
|
|
376
|
+
// `_destroying` flips after attach so it is read lazily.
|
|
377
|
+
guardChildStreams(proc, { destroying: () => this._destroying, log, label: Klass.providerName })
|
|
378
|
+
|
|
379
|
+
proc.on('close', (code) => {
|
|
380
|
+
this._process = null
|
|
381
|
+
this._isBusy = false
|
|
382
|
+
// #4881: capture-and-clear BEFORE the _destroying short-circuit so the
|
|
383
|
+
// flag never leaks past a close even when destroy() fires first.
|
|
384
|
+
// Mirrors CliSession._handleChildClose (#4602).
|
|
385
|
+
const wasIntentionalStop = this._consumeIntentionalStop()
|
|
386
|
+
if (this._destroying) return
|
|
387
|
+
if (ctx.didStreamStart) {
|
|
388
|
+
this.emit('stream_end', { messageId: ctx.messageId })
|
|
389
|
+
ctx.didStreamStart = false
|
|
390
|
+
}
|
|
391
|
+
if (wasIntentionalStop) {
|
|
392
|
+
// #4881: user clicked Stop — interrupt() set the flag, SIGINT brought
|
|
393
|
+
// the child down. Skip the loud "{provider} process exited with code
|
|
394
|
+
// N" error surface and emit the quiet `stopped` event for parity
|
|
395
|
+
// with CliSession (#4868). SIGINT typically exits with 130 or null
|
|
396
|
+
// depending on the CLI; both are user-initiated and not crashes.
|
|
397
|
+
this.emit('stopped', { code })
|
|
398
|
+
} else if (code !== 0 && code !== null) {
|
|
399
|
+
// Prefer high-signal stderr; fall back to raw so the user always
|
|
400
|
+
// sees *some* explanation when the child died.
|
|
401
|
+
const sourceBuf = stderrBuf || rawStderrBuf
|
|
402
|
+
// #3841 — surface a one-shot warning when the raw fallback was the
|
|
403
|
+
// only signal. That means the subclass's _shouldSkipStderr filter
|
|
404
|
+
// swallowed every stderr line yet the child still died, so the
|
|
405
|
+
// filter is over-aggressive and worth tightening.
|
|
406
|
+
if (!stderrBuf && rawStderrBuf) {
|
|
407
|
+
log.warn(
|
|
408
|
+
`[${Klass.providerName}] _shouldSkipStderr filtered all stderr but child exited ${code} — using raw fallback`,
|
|
409
|
+
)
|
|
410
|
+
}
|
|
411
|
+
const detail = sourceBuf ? `: ${sourceBuf.slice(0, STDERR_SLICE_FOR_ERROR)}` : ''
|
|
412
|
+
this.emit('error', {
|
|
413
|
+
message: `${Klass.displayLabel} process exited with code ${code}${detail}`,
|
|
414
|
+
})
|
|
415
|
+
}
|
|
416
|
+
if (!ctx.didEmitResult) {
|
|
417
|
+
this._emitFallbackResult(ctx)
|
|
418
|
+
}
|
|
419
|
+
})
|
|
420
|
+
|
|
421
|
+
proc.on('error', (err) => {
|
|
422
|
+
this._process = null
|
|
423
|
+
this._isBusy = false
|
|
424
|
+
// Spawn-level error (ENOENT, EACCES, etc.) means the argv never
|
|
425
|
+
// reached a real process — revert `_skillsPrepended` so the next
|
|
426
|
+
// sendMessage retry still injects the prepend bucket (#3225). We
|
|
427
|
+
// can't distinguish a launch failure from a runtime crash via this
|
|
428
|
+
// event alone, but in practice 'error' on a ChildProcess fires for
|
|
429
|
+
// launch failures; runtime crashes flow through 'close' with a
|
|
430
|
+
// non-zero exit code (where the argv DID reach the process, so
|
|
431
|
+
// the flag rightly stays true).
|
|
432
|
+
if (willPrependSkills) {
|
|
433
|
+
this._skillsPrepended = false
|
|
434
|
+
}
|
|
435
|
+
if (this._destroying) return
|
|
436
|
+
this.emit('error', {
|
|
437
|
+
message: err.message || `Failed to spawn ${Klass.providerName}`,
|
|
438
|
+
})
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
}
|