@chroxy/server 0.10.0 → 0.11.10
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 +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrowing an approved Write/Edit (#8446): how the content that reaches the
|
|
3
|
+
* agent's tool executor is built when the operator drops hunks in the pre-write
|
|
4
|
+
* review (#6543).
|
|
5
|
+
*
|
|
6
|
+
* The client reviews the REDACTED copy of the tool input (`get_permission_input`
|
|
7
|
+
* runs `sanitizeToolInput` over it). Content a client builds from that copy
|
|
8
|
+
* carries `[REDACTED]` wherever a secret-shaped span was, so trusting it writes the
|
|
9
|
+
* placeholder into the user's file in place of the original characters. Two rules
|
|
10
|
+
* keep that from happening, and both live here so the permission manager has one
|
|
11
|
+
* place to call:
|
|
12
|
+
*
|
|
13
|
+
* 1. HUNK DECISIONS, NOT CONTENT. The client says which hunks it dropped and
|
|
14
|
+
* which it kept (their line ranges, the `@@` header numbers of the diff it
|
|
15
|
+
* rendered). The server computes the diff itself over the same redacted copy,
|
|
16
|
+
* with the same differ (`computeHunks`, shared through @chroxy/protocol), and
|
|
17
|
+
* requires the client's ranges to be exactly that list of hunks. It then
|
|
18
|
+
* rebuilds the result from the RAW input it holds, so the written text is made
|
|
19
|
+
* only of lines the agent proposed, and only ever the proposal with whole real
|
|
20
|
+
* hunks reverted.
|
|
21
|
+
* 2. TEXT IS NEVER A BASE. Text a client sends (an older client, or the Bash
|
|
22
|
+
* command editor) was edited from the copy it was shown. Where redaction
|
|
23
|
+
* changed that copy the text cannot be trusted to be the original with an
|
|
24
|
+
* edit, whatever it contains: counting placeholders cannot say where one came
|
|
25
|
+
* from, so such text is refused outright and only `droppedHunks` may narrow
|
|
26
|
+
* the field. Where redaction changed nothing, the text is just text.
|
|
27
|
+
*
|
|
28
|
+
* A refusal throws {@link EditedInputRefusedError}; nothing is written.
|
|
29
|
+
*/
|
|
30
|
+
import { computeHunks, splitContentLines } from '@chroxy/protocol'
|
|
31
|
+
import { sanitizeToolInput, PULL_MAX_INPUT_CHARS } from './redaction.js'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The reserved key of `permission_response.editedInput` that carries the hunk
|
|
35
|
+
* decisions: an array of {@link HunkRange}, the hunks the operator dropped. Its
|
|
36
|
+
* presence puts the field in hunk mode. It is not a content field, so the content
|
|
37
|
+
* whitelist never reads it as one.
|
|
38
|
+
*/
|
|
39
|
+
export const DROPPED_HUNKS_KEY = 'droppedHunks'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The hunks the operator kept: with `droppedHunks`, every hunk of the diff it was shown.
|
|
43
|
+
* Required whenever `droppedHunks` is not empty, because the server needs the whole
|
|
44
|
+
* partition to compare with its own hunk list.
|
|
45
|
+
*/
|
|
46
|
+
export const KEPT_HUNKS_KEY = 'keptHunks'
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @typedef {object} HunkRange
|
|
50
|
+
* @property {number} oldStart `@@ -oldStart,oldCount` of the hunk
|
|
51
|
+
* @property {number} oldCount
|
|
52
|
+
* @property {number} newStart `@@ +newStart,newCount`
|
|
53
|
+
* @property {number} newCount
|
|
54
|
+
* Git's convention, as the differ emits it: a side with a non-zero count starts at a
|
|
55
|
+
* 1-based line, a side with a zero count starts AFTER the 0-based line.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Per tool: the content field a hunk review narrows and the text the diff was drawn
|
|
60
|
+
* against. Write is drawn against the empty file; Edit against the text it replaces.
|
|
61
|
+
* Must match the client's `TOOL_DIFF` (dashboard + app `PreWriteDiffReview`).
|
|
62
|
+
*/
|
|
63
|
+
const HUNK_REVIEW = {
|
|
64
|
+
Write: { field: 'content', base: () => '' },
|
|
65
|
+
Edit: { field: 'new_string', base: (input) => input.old_string },
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether a tool's content is narrowed by hunk decisions rather than sent as text. */
|
|
69
|
+
export function isHunkReviewedTool(toolName) {
|
|
70
|
+
return Object.prototype.hasOwnProperty.call(HUNK_REVIEW, toolName)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class EditedInputRefusedError extends Error {
|
|
74
|
+
constructor(message) {
|
|
75
|
+
super(message)
|
|
76
|
+
this.name = 'EditedInputRefusedError'
|
|
77
|
+
this.code = 'EDITED_INPUT_REFUSED'
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The 0-based first line of a side of a hunk, from its header number — the inverse
|
|
83
|
+
* of the differ's header math (a zero-count side's start is already 0-based).
|
|
84
|
+
*/
|
|
85
|
+
function lineIndex(start, count) {
|
|
86
|
+
return count === 0 ? start : start - 1
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `@@ -a,b +c,d @@` from a client range, refusing anything that is not four whole counts. */
|
|
90
|
+
function headerOf(h) {
|
|
91
|
+
if (!h || typeof h !== 'object') return null
|
|
92
|
+
const { oldStart, oldCount, newStart, newCount } = h
|
|
93
|
+
for (const n of [oldStart, oldCount, newStart, newCount]) {
|
|
94
|
+
if (!Number.isSafeInteger(n) || n < 0) return null
|
|
95
|
+
}
|
|
96
|
+
return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Append `lines[from, to)` to `out`. A loop, not a spread: a hunk may be 100K+ lines. */
|
|
100
|
+
function pushRange(out, lines, from, to) {
|
|
101
|
+
for (let i = from; i < to; i++) out.push(lines[i])
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const NOT_A_DIFF = 'The hunks you named are not the hunks of the change that was proposed, so the edit was not applied.'
|
|
105
|
+
const HIDDEN_DIFFERENCE = 'This change contains differences that redaction hid from the review, so it can only be approved or denied as a whole. The request was denied; the agent can propose it again, and it can be approved whole.'
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The server's own hunks over the shown copy, parsed into line positions in the
|
|
109
|
+
* texts, in order. Each entry carries the hunk's lines so a walk can tell its
|
|
110
|
+
* context from its changes.
|
|
111
|
+
*/
|
|
112
|
+
function ownHunks(shownBase, shownProposed) {
|
|
113
|
+
return computeHunks(shownBase, shownProposed).map((hunk) => {
|
|
114
|
+
const m = /^@@ -(\d+),(\d+) \+(\d+),(\d+) @@$/.exec(hunk.header)
|
|
115
|
+
if (!m) throw new EditedInputRefusedError(NOT_A_DIFF)
|
|
116
|
+
const oldCount = Number(m[2])
|
|
117
|
+
const newCount = Number(m[4])
|
|
118
|
+
return {
|
|
119
|
+
header: hunk.header,
|
|
120
|
+
lines: hunk.lines,
|
|
121
|
+
oldIdx: lineIndex(Number(m[1]), oldCount),
|
|
122
|
+
oldCount,
|
|
123
|
+
newIdx: lineIndex(Number(m[3]), newCount),
|
|
124
|
+
newCount,
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Whether the raw texts differ at a line the shown copy reads as unchanged: outside
|
|
131
|
+
* every hunk, or as a hunk's context line. That is a change redaction hid (two
|
|
132
|
+
* different keys both read `[REDACTED]`).
|
|
133
|
+
*/
|
|
134
|
+
function hasHiddenDifference(hunks, baseLines, proposedLines) {
|
|
135
|
+
let oldAt = 0
|
|
136
|
+
let newAt = 0
|
|
137
|
+
const sameAt = (o, n) => baseLines[o] !== proposedLines[n]
|
|
138
|
+
for (const h of hunks) {
|
|
139
|
+
for (; oldAt < h.oldIdx; oldAt++, newAt++) if (sameAt(oldAt, newAt)) return true
|
|
140
|
+
for (const line of h.lines) {
|
|
141
|
+
if (line.type === 'context') {
|
|
142
|
+
if (sameAt(oldAt, newAt)) return true
|
|
143
|
+
oldAt++
|
|
144
|
+
newAt++
|
|
145
|
+
} else if (line.type === 'deletion') {
|
|
146
|
+
oldAt++
|
|
147
|
+
} else {
|
|
148
|
+
newAt++
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (; oldAt < baseLines.length; oldAt++, newAt++) if (sameAt(oldAt, newAt)) return true
|
|
153
|
+
return false
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Build a Write/Edit's narrowed content from the RAW input and the client's hunk
|
|
158
|
+
* decisions: the proposed text with each dropped hunk's lines replaced by the original
|
|
159
|
+
* text's lines, every line taken from the raw input.
|
|
160
|
+
*
|
|
161
|
+
* The client lists EVERY hunk it was shown, dropped or kept. The server diffs the same
|
|
162
|
+
* redacted copy itself (same differ, same context) and requires the client's ranges to
|
|
163
|
+
* be exactly its hunks: the same headers, each once, none missing and none extra. A
|
|
164
|
+
* range that lands off its hunk, a zero-count side that invents an insertion or a
|
|
165
|
+
* deletion, or a partition that deletes a line both sides share, is not that list and is
|
|
166
|
+
* refused. The lines outside the hunks are then unchanged lines by construction.
|
|
167
|
+
*
|
|
168
|
+
* Two things are refused rather than guessed at. The client's line numbers only mean the
|
|
169
|
+
* same lines in the raw text when redaction kept the line count (it never adds a line
|
|
170
|
+
* break; a pattern that spanned one removes it). And when the raw texts differ at a line
|
|
171
|
+
* the shown copy reads as unchanged (a rotated key), dropping any hunk would write that
|
|
172
|
+
* hidden change unseen, so only a whole approve or deny is left.
|
|
173
|
+
*
|
|
174
|
+
* @param {object} rawInput the agent's proposed tool input, as held server-side
|
|
175
|
+
* @param {string} toolName 'Write' | 'Edit'
|
|
176
|
+
* @param {unknown} dropped the client's `editedInput.droppedHunks`
|
|
177
|
+
* @param {unknown} kept the client's `editedInput.keptHunks`
|
|
178
|
+
* @returns {string} the narrowed content for the tool's content field
|
|
179
|
+
*/
|
|
180
|
+
export function narrowByDroppedHunks(rawInput, toolName, dropped, kept) {
|
|
181
|
+
const review = HUNK_REVIEW[toolName]
|
|
182
|
+
const rawProposed = rawInput[review.field]
|
|
183
|
+
const rawBase = review.base(rawInput)
|
|
184
|
+
if (typeof rawProposed !== 'string' || typeof rawBase !== 'string') {
|
|
185
|
+
throw new EditedInputRefusedError(`This ${toolName} has no text content to narrow, so the edit was not applied.`)
|
|
186
|
+
}
|
|
187
|
+
if (!Array.isArray(dropped)) {
|
|
188
|
+
throw new EditedInputRefusedError('The dropped hunks were not a list the server can read, so the edit was not applied.')
|
|
189
|
+
}
|
|
190
|
+
// Nothing dropped: the proposal as it stands.
|
|
191
|
+
if (dropped.length === 0) return rawProposed
|
|
192
|
+
if (!Array.isArray(kept)) {
|
|
193
|
+
throw new EditedInputRefusedError('The kept hunks were not a list the server can read, so the edit was not applied.')
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The copy the client was shown: the same call `get_permission_input` makes.
|
|
197
|
+
const shown = sanitizeToolInput(rawInput, { maxChars: PULL_MAX_INPUT_CHARS })
|
|
198
|
+
const shownProposed = shown?.[review.field]
|
|
199
|
+
const shownBase = review.base(shown ?? {})
|
|
200
|
+
if (typeof shownProposed !== 'string' || typeof shownBase !== 'string') {
|
|
201
|
+
throw new EditedInputRefusedError('This change is too large to narrow hunk by hunk, so the edit was not applied.')
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const baseLines = splitContentLines(rawBase)
|
|
205
|
+
const proposedLines = splitContentLines(rawProposed)
|
|
206
|
+
if (baseLines.length !== splitContentLines(shownBase).length
|
|
207
|
+
|| proposedLines.length !== splitContentLines(shownProposed).length) {
|
|
208
|
+
throw new EditedInputRefusedError(
|
|
209
|
+
'Redacting this content changed its line structure, so the hunks you dropped cannot be mapped back to the original text and the edit was not applied.',
|
|
210
|
+
)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The client's partition must be exactly the server's own hunk list.
|
|
214
|
+
const hunks = ownHunks(shownBase, shownProposed)
|
|
215
|
+
if (dropped.length + kept.length !== hunks.length) throw new EditedInputRefusedError(NOT_A_DIFF)
|
|
216
|
+
const decision = new Map() // header -> true when dropped
|
|
217
|
+
for (const [list, isDropped] of [[dropped, true], [kept, false]]) {
|
|
218
|
+
for (const range of list) {
|
|
219
|
+
const header = headerOf(range)
|
|
220
|
+
if (header === null) throw new EditedInputRefusedError(NOT_A_DIFF)
|
|
221
|
+
decision.set(header, isDropped)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Same count, and every real hunk named: so nothing is repeated or extra either.
|
|
225
|
+
if (hunks.some((h) => !decision.has(h.header))) throw new EditedInputRefusedError(NOT_A_DIFF)
|
|
226
|
+
|
|
227
|
+
if (hasHiddenDifference(hunks, baseLines, proposedLines)) throw new EditedInputRefusedError(HIDDEN_DIFFERENCE)
|
|
228
|
+
|
|
229
|
+
const out = []
|
|
230
|
+
let newAt = 0
|
|
231
|
+
for (const h of hunks) {
|
|
232
|
+
pushRange(out, proposedLines, newAt, h.newIdx)
|
|
233
|
+
if (decision.get(h.header)) pushRange(out, baseLines, h.oldIdx, h.oldIdx + h.oldCount)
|
|
234
|
+
else pushRange(out, proposedLines, h.newIdx, h.newIdx + h.newCount)
|
|
235
|
+
newAt = h.newIdx + h.newCount
|
|
236
|
+
}
|
|
237
|
+
pushRange(out, proposedLines, newAt, proposedLines.length)
|
|
238
|
+
return out.join('\n')
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Refuse text a client sent for `field` when redaction changed any of the text it was
|
|
243
|
+
* drawn from. `field` is a whitelisted content field; for a hunk-reviewed tool the text
|
|
244
|
+
* an older client narrowed from is the field AND the text it replaces.
|
|
245
|
+
*
|
|
246
|
+
* Fails closed: an input too large to have been shown whole reads as changed.
|
|
247
|
+
*
|
|
248
|
+
* @param {object} rawInput
|
|
249
|
+
* @param {string} toolName
|
|
250
|
+
* @param {string} field
|
|
251
|
+
*/
|
|
252
|
+
export function assertClientTextAllowed(rawInput, toolName, field) {
|
|
253
|
+
const shown = sanitizeToolInput(rawInput, { maxChars: PULL_MAX_INPUT_CHARS })
|
|
254
|
+
const names = isHunkReviewedTool(toolName) ? [field, 'old_string'] : [field]
|
|
255
|
+
for (const name of names) {
|
|
256
|
+
const raw = rawInput?.[name]
|
|
257
|
+
if (typeof raw !== 'string') continue
|
|
258
|
+
if (shown?.[name] !== raw) {
|
|
259
|
+
throw new EditedInputRefusedError(
|
|
260
|
+
'Part of this request was redacted before you saw it, so text edited from that copy cannot be applied. The request was denied; the agent can propose it again, and it can be approved whole.',
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
import { EventEmitter } from 'events'
|
|
2
|
+
import { assertAuthorized } from './connection-authority.js'
|
|
2
3
|
import { randomBytes } from 'crypto'
|
|
3
4
|
import { execFile } from 'child_process'
|
|
4
5
|
import { existsSync, readFileSync, mkdirSync } from 'fs'
|
|
5
|
-
import { dirname
|
|
6
|
-
import { homedir } from 'os'
|
|
6
|
+
import { dirname } from 'path'
|
|
7
7
|
import { writeFileRestricted } from './platform.js'
|
|
8
8
|
import { createLogger } from './logger.js'
|
|
9
9
|
import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
|
|
10
10
|
import { DockerBackend } from './environments/backends/docker.js'
|
|
11
|
+
import { configPath } from './config-dir.js'
|
|
11
12
|
import {
|
|
12
13
|
parseDevContainer,
|
|
13
14
|
validateMounts,
|
|
14
15
|
sanitizeContainerEnv,
|
|
15
16
|
} from './devcontainer-config.js'
|
|
17
|
+
import { liveSessionsError } from './environments/destroy-with-sessions.js'
|
|
16
18
|
|
|
17
19
|
const log = createLogger('environment-manager')
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
function defaultStatePath() {
|
|
22
|
+
return configPath('environments.json')
|
|
23
|
+
}
|
|
20
24
|
const DEFAULT_IMAGE = 'node:22-slim'
|
|
21
25
|
const DEFAULT_MEMORY_LIMIT = '2g'
|
|
22
26
|
const DEFAULT_CPU_LIMIT = '2'
|
|
@@ -57,10 +61,19 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
57
61
|
*/
|
|
58
62
|
constructor({ statePath, _execFile, backend, workspacePVCDefault } = {}) {
|
|
59
63
|
super()
|
|
60
|
-
this._statePath = statePath ||
|
|
64
|
+
this._statePath = statePath || defaultStatePath()
|
|
61
65
|
this._environments = new Map()
|
|
62
66
|
// Per-environment mutex: Map<envId, Promise> — serializes operations
|
|
63
67
|
this._locks = new Map()
|
|
68
|
+
// #7575 — ids of environments currently mid-teardown. An INTERNAL, never-
|
|
69
|
+
// persisted marker (a Set, not an `env.status` value): `destroy()` adds an id
|
|
70
|
+
// before its first teardown `await` and clears it in a `finally`, and
|
|
71
|
+
// `getContainerInfo()` refuses a create while an id is present. It is NOT a
|
|
72
|
+
// fourth `status` — the wire enum (`EnvironmentStatusSchema`) is closed to
|
|
73
|
+
// running/stopped/error, and this marker is never serialized, so a client
|
|
74
|
+
// snapshot never carries it and a crash mid-teardown clears it for free
|
|
75
|
+
// (the Set is reconstructed empty on restart).
|
|
76
|
+
this._destroying = new Set()
|
|
64
77
|
// Injected for testing — falls back to real execFile.
|
|
65
78
|
// _execFile is forwarded to DockerBackend so existing tests that inject a
|
|
66
79
|
// mock execFile continue to work without modification.
|
|
@@ -381,41 +394,111 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
381
394
|
|
|
382
395
|
/**
|
|
383
396
|
* Destroy an environment and its container.
|
|
397
|
+
*
|
|
398
|
+
* #7562: REFUSES when sessions are still attached (`env.sessions` non-empty)
|
|
399
|
+
* unless `force` is set. This is the server-side half of a guard that lived
|
|
400
|
+
* only in the dashboard (`EnvironmentPanel`'s disabled Destroy button), so any
|
|
401
|
+
* OTHER sender of the message — a stale dashboard tab, the Control Room's
|
|
402
|
+
* `containers_action` (no UI guard at all), a script, any future client —
|
|
403
|
+
* could `docker rm -f` the container out from under running sessions. (The
|
|
404
|
+
* mobile app is not one of them today: it can put a session INTO an
|
|
405
|
+
* environment via `create_session`'s `environmentId`, but it has no
|
|
406
|
+
* environment-destroy surface. It is a potential victim of this, not a
|
|
407
|
+
* perpetrator.) The check sits HERE, at the one chokepoint every
|
|
408
|
+
* caller reaches, rather than in each handler: a per-caller check is the
|
|
409
|
+
* "guard wired to only some of its callers" shape in
|
|
410
|
+
* docs/false-safety-guards.md, which is precisely how `containers_action`
|
|
411
|
+
* came to have no guard at all.
|
|
412
|
+
*
|
|
413
|
+
* `force` does NOT clean the sessions up — this class has no handle on the
|
|
414
|
+
* SessionManager. The cascade (destroy the sessions cleanly, THEN the
|
|
415
|
+
* environment) is `environments/destroy-with-sessions.js`, which is what both
|
|
416
|
+
* handlers call. A direct `destroy(id, { force: true })` is the deliberate
|
|
417
|
+
* "I know, take it down anyway" escape.
|
|
418
|
+
*
|
|
384
419
|
* @param {string} envId - Environment ID
|
|
420
|
+
* @param {{force?: boolean}} [opts]
|
|
421
|
+
* @throws {Error & {code: 'ENVIRONMENT_HAS_LIVE_SESSIONS', sessions: string[]}}
|
|
422
|
+
* when sessions are attached and `force` is not set. Nothing is torn down.
|
|
385
423
|
*/
|
|
386
|
-
async destroy(envId) {
|
|
424
|
+
async destroy(envId, { force = false, isAuthorized } = {}) {
|
|
387
425
|
const release = await this._acquireLock(envId)
|
|
388
426
|
try {
|
|
427
|
+
assertAuthorized(isAuthorized)
|
|
389
428
|
const env = this._getEnvironmentOrThrow(envId)
|
|
429
|
+
// #7562 — refuse BEFORE any teardown, so a refused destroy leaves the
|
|
430
|
+
// container running and the environment registered.
|
|
431
|
+
if (!force && Array.isArray(env.sessions) && env.sessions.length > 0) {
|
|
432
|
+
log.warn(`Refusing to destroy environment "${env.name}" (${envId}): ${env.sessions.length} live session(s) attached`)
|
|
433
|
+
throw liveSessionsError(env)
|
|
434
|
+
}
|
|
390
435
|
log.info(`Destroying environment "${env.name}" (${envId})`)
|
|
391
436
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
437
|
+
// #7575 — mark the environment mid-teardown BEFORE the first `await`, while
|
|
438
|
+
// this method still holds the lock and no other task can run. `destroy` is
|
|
439
|
+
// async and YIELDS at the backend teardown below; a `create_session` that
|
|
440
|
+
// begins during that yield would otherwise attach a session to a container
|
|
441
|
+
// we are about to `docker rm -f` and an environment record we are about to
|
|
442
|
+
// delete — a TOCTOU on the #7562 live-sessions guard, which saw zero
|
|
443
|
+
// sessions and proceeded. Adding the id to `_destroying` here means such a
|
|
444
|
+
// create's `getContainerInfo` is refused with the existing NOT_RUNNING-style
|
|
445
|
+
// error — no new wire shape, and (unlike overloading `env.status`) no value
|
|
446
|
+
// that could leak into the closed `EnvironmentStatusSchema` enum or persist.
|
|
447
|
+
//
|
|
448
|
+
// Why marking synchronously here is SUFFICIENT (and `addSession` is not
|
|
449
|
+
// also gated): the create path reads the container info (the create
|
|
450
|
+
// handler's `getContainerInfo`) and tags the env (`addSession`, via the
|
|
451
|
+
// synchronous `SessionManager.createSession`) in ONE synchronous run — there
|
|
452
|
+
// is no `await` between them — so that whole read→tag sequence is atomic
|
|
453
|
+
// with respect to this method's yields. Every interleaving therefore
|
|
454
|
+
// resolves safely: a create that ran entirely BEFORE this mark tagged the
|
|
455
|
+
// env, so the #7562 check above saw the session and refused this destroy; a
|
|
456
|
+
// create that starts AT OR AFTER this mark sees the env in `_destroying` at
|
|
457
|
+
// `getContainerInfo` and is refused. There is no interleaving where
|
|
458
|
+
// `getContainerInfo` passes AND `addSession` lands during teardown.
|
|
459
|
+
//
|
|
460
|
+
// LOAD-BEARING INVARIANT: that atomicity. If a future change inserts an
|
|
461
|
+
// `await` between `getContainerInfo` and `addSession`, a create whose read
|
|
462
|
+
// already passed could still `addSession` during this teardown, reopening
|
|
463
|
+
// the window — close it then by re-checking `_destroying` inside
|
|
464
|
+
// `addSession` (which runs synchronously and would observe this mark).
|
|
465
|
+
this._destroying.add(envId)
|
|
466
|
+
try {
|
|
467
|
+
if (env.compose && env.composeProject) {
|
|
468
|
+
await this._backend.destroyComposeEnvironment({
|
|
469
|
+
composeFile: env.compose,
|
|
470
|
+
composeProject: env.composeProject,
|
|
471
|
+
cwd: env.cwd,
|
|
472
|
+
})
|
|
473
|
+
} else if (env.containerId) {
|
|
474
|
+
// #6134: remove the container whenever one exists — NOT only when
|
|
475
|
+
// status==='running'. Now that stop() makes 'stopped' a reachable state,
|
|
476
|
+
// gating on 'running' would orphan a stopped container (the manager
|
|
477
|
+
// entry is deleted but `docker rm -f` never runs). `docker rm -f` works
|
|
478
|
+
// on stopped/exited containers too, and _removeContainer swallows a
|
|
479
|
+
// "no such container" for one that never started.
|
|
480
|
+
await this._backend.destroyEnvironment(env.containerId)
|
|
481
|
+
}
|
|
407
482
|
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
483
|
+
// Clean up snapshot images
|
|
484
|
+
if (Array.isArray(env.snapshots)) {
|
|
485
|
+
for (const snap of env.snapshots) {
|
|
486
|
+
await this._backend.removeImage(snap.image)
|
|
487
|
+
}
|
|
412
488
|
}
|
|
413
|
-
}
|
|
414
489
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
490
|
+
this._environments.delete(envId)
|
|
491
|
+
this._persist()
|
|
492
|
+
this.emit('environment_destroyed', { id: envId, name: env.name })
|
|
493
|
+
log.info(`Environment "${env.name}" destroyed`)
|
|
494
|
+
} finally {
|
|
495
|
+
// Clear the marker on BOTH paths. On success the env is already gone, so
|
|
496
|
+
// this only matters on failure: a teardown that threw left the env
|
|
497
|
+
// registered and unchanged (nothing was deleted, `env.status` was never
|
|
498
|
+
// touched), and clearing the mark makes it immediately re-enterable —
|
|
499
|
+
// `getContainerInfo` stops refusing and a subsequent create succeeds.
|
|
500
|
+
this._destroying.delete(envId)
|
|
501
|
+
}
|
|
419
502
|
} finally {
|
|
420
503
|
release()
|
|
421
504
|
}
|
|
@@ -431,9 +514,10 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
431
514
|
* don't implement the lifecycle (k8s/rancher today) throw a clear error that
|
|
432
515
|
* the handler surfaces as CONTAINER_ACTION_FAILED.
|
|
433
516
|
*/
|
|
434
|
-
async stop(envId) {
|
|
517
|
+
async stop(envId, { isAuthorized } = {}) {
|
|
435
518
|
const release = await this._acquireLock(envId)
|
|
436
519
|
try {
|
|
520
|
+
assertAuthorized(isAuthorized)
|
|
437
521
|
const env = this._getEnvironmentOrThrow(envId)
|
|
438
522
|
if (env.compose) throw new Error(`Stop is not supported for compose environments yet`)
|
|
439
523
|
if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to stop`)
|
|
@@ -457,9 +541,10 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
457
541
|
* currently running or stopped; ends running). Returns the resulting status.
|
|
458
542
|
* Same compose / backend-support constraints as {@link stop}.
|
|
459
543
|
*/
|
|
460
|
-
async restart(envId) {
|
|
544
|
+
async restart(envId, { isAuthorized } = {}) {
|
|
461
545
|
const release = await this._acquireLock(envId)
|
|
462
546
|
try {
|
|
547
|
+
assertAuthorized(isAuthorized)
|
|
463
548
|
const env = this._getEnvironmentOrThrow(envId)
|
|
464
549
|
if (env.compose) throw new Error(`Restart is not supported for compose environments yet`)
|
|
465
550
|
if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to restart`)
|
|
@@ -501,6 +586,14 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
501
586
|
*/
|
|
502
587
|
getContainerInfo(envId) {
|
|
503
588
|
const env = this._getEnvironmentOrThrow(envId)
|
|
589
|
+
// #7575 — refuse a create against an environment whose teardown is already
|
|
590
|
+
// in flight. `destroy()` adds the id to `_destroying` before its first
|
|
591
|
+
// `await` (and clears it in a `finally`), so this closes the TOCTOU window
|
|
592
|
+
// where `destroy` had passed the #7562 sessions check and was mid-`docker
|
|
593
|
+
// rm -f`: without this, `getContainerInfo` returned live details and the
|
|
594
|
+
// session attached to a container about to vanish. Same NOT_RUNNING-style
|
|
595
|
+
// refusal — no new wire shape.
|
|
596
|
+
if (this._destroying.has(envId)) throw new Error(`Environment "${env.name}" is not running (status: destroying)`)
|
|
504
597
|
if (env.status !== 'running') throw new Error(`Environment "${env.name}" is not running (status: ${env.status})`)
|
|
505
598
|
return {
|
|
506
599
|
containerId: env.containerId,
|
|
@@ -511,6 +604,12 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
511
604
|
|
|
512
605
|
/**
|
|
513
606
|
* Track a session connecting to an environment.
|
|
607
|
+
*
|
|
608
|
+
* #7552: called from `SessionManager.createSession` for every session created
|
|
609
|
+
* with an `environmentId` — the production writer `env.sessions` spent its
|
|
610
|
+
* whole life without. Idempotent; a no-op for an unknown environment (which
|
|
611
|
+
* can be destroyed between the handler's `getContainerInfo` and the create).
|
|
612
|
+
*
|
|
514
613
|
* @param {string} envId
|
|
515
614
|
* @param {string} sessionId
|
|
516
615
|
*/
|
|
@@ -520,19 +619,48 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
520
619
|
if (!env.sessions.includes(sessionId)) {
|
|
521
620
|
env.sessions.push(sessionId)
|
|
522
621
|
this._persist()
|
|
622
|
+
this._emitSessionsChanged(env)
|
|
523
623
|
}
|
|
524
624
|
}
|
|
525
625
|
|
|
526
626
|
/**
|
|
527
627
|
* Track a session disconnecting from an environment.
|
|
628
|
+
*
|
|
629
|
+
* #7552: called from `SessionManager._cleanupSessionMaps` (the single funnel
|
|
630
|
+
* every session takes OUT of `_sessions`) and from `destroyAll()`. A MISSED
|
|
631
|
+
* detach is the inverse of the bug this wiring fixes — a stale id would make
|
|
632
|
+
* the environment permanently undestroyable — so the caller side is pinned
|
|
633
|
+
* path-by-path in `tests/environment-session-wiring.test.js`.
|
|
634
|
+
*
|
|
528
635
|
* @param {string} envId
|
|
529
636
|
* @param {string} sessionId
|
|
530
637
|
*/
|
|
531
638
|
removeSession(envId, sessionId) {
|
|
532
639
|
const env = this._environments.get(envId)
|
|
533
640
|
if (!env) return
|
|
641
|
+
if (!env.sessions.includes(sessionId)) return
|
|
534
642
|
env.sessions = env.sessions.filter(s => s !== sessionId)
|
|
535
643
|
this._persist()
|
|
644
|
+
this._emitSessionsChanged(env)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* #7552: announce that an environment's session tag CHANGED, so the WsServer
|
|
649
|
+
* can re-broadcast `environment_list` and the dashboard's copy stays true.
|
|
650
|
+
*
|
|
651
|
+
* Without this the dashboard refreshes only when the Environments panel
|
|
652
|
+
* mounts or an environment is created/destroyed — none of which is a session
|
|
653
|
+
* lifecycle event. A destroy guard reading a stale `sessions.length` is the
|
|
654
|
+
* same false safety by a different route, so the freshness is part of the fix
|
|
655
|
+
* rather than a follow-up. Emitted only on a REAL change (a duplicate add or
|
|
656
|
+
* an absent remove is silent) so a busy-but-unchanged daemon broadcasts
|
|
657
|
+
* nothing.
|
|
658
|
+
*
|
|
659
|
+
* @param {Object} env
|
|
660
|
+
* @private
|
|
661
|
+
*/
|
|
662
|
+
_emitSessionsChanged(env) {
|
|
663
|
+
this.emit('environment_sessions_changed', { id: env.id, sessions: [...env.sessions] })
|
|
536
664
|
}
|
|
537
665
|
|
|
538
666
|
/**
|
|
@@ -576,11 +704,22 @@ export class EnvironmentManager extends EventEmitter {
|
|
|
576
704
|
let allHealthy = true
|
|
577
705
|
|
|
578
706
|
for (const env of this._environments.values()) {
|
|
579
|
-
// Clear
|
|
580
|
-
//
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
//
|
|
707
|
+
// Clear the PREVIOUS process's session references unconditionally,
|
|
708
|
+
// regardless of whether the environment's container is reachable,
|
|
709
|
+
// stopped, or has no containerId at all. (#3494: this used to live at the
|
|
710
|
+
// bottom of the loop body and was skipped by the no-containerId
|
|
711
|
+
// `continue` below.)
|
|
712
|
+
//
|
|
713
|
+
// #7561: this is no longer the last word on the tag. Sessions now persist
|
|
714
|
+
// their environment binding and RE-ATTACH on restore, so the sequence at
|
|
715
|
+
// boot is: reconnect() wipes the stale ids written by the process that
|
|
716
|
+
// died, then SessionManager.restoreState() re-tags the ones that actually
|
|
717
|
+
// came back. The ordering is load-bearing and holds in server-cli.js —
|
|
718
|
+
// the manager is constructed and reconnect()ed before the SessionManager
|
|
719
|
+
// exists, let alone restores — and is pinned in
|
|
720
|
+
// tests/environment-restore-binding.test.js. A reconnect() AFTER a
|
|
721
|
+
// restore would silently un-tag every restored session and put the
|
|
722
|
+
// destroy guard (#7562) back to sleep.
|
|
584
723
|
env.sessions = []
|
|
585
724
|
|
|
586
725
|
if (!env.containerId) {
|