@chroxy/server 0.11.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 +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- 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 +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- 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 +69 -5
- 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 +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- 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 +53 -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 +211 -88
- 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 +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- 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 +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- 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 +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- 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 +23 -19
- 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/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 +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- 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 +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- 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 +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- 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 +330 -42
- 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/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -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 +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- 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 +12 -4
- 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 +64 -23
- 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 +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- 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 +207 -4
- 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/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- 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 +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- 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 +3491 -312
- package/src/session-message-history.js +722 -16
- 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-token-store.js +17 -8
- 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 +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- 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/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- 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 +133 -37
- 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/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 +360 -16
- 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 +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- 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 +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- 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
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session → unresolved review-thread count (#7430, on-demand follow-on to #7344).
|
|
3
|
+
*
|
|
4
|
+
* #7423's prefill line wants "0 unresolved threads" beside the check rollup,
|
|
5
|
+
* because that number is what explains a `BLOCKED` merge state when CI is
|
|
6
|
+
* 21/21 green. `session_pr_status` cannot carry it: `gh pr list --json` has no
|
|
7
|
+
* thread count, and reading one needs a GraphQL `reviewThreads` query.
|
|
8
|
+
*
|
|
9
|
+
* ## Why this is a separate survey and not two more fields on that one
|
|
10
|
+
*
|
|
11
|
+
* Since #7426 `surveySessionPrStatus` runs on a daemon-side SWEEP across every
|
|
12
|
+
* session (`SessionCiWatcher`, on `tickIntervalMs`/`discoveryIntervalMs`), not
|
|
13
|
+
* only when a dashboard asks. Adding a second `gh` invocation there doubles the
|
|
14
|
+
* subprocess and network cost of a background poll — on every session, on every
|
|
15
|
+
* tick — to enrich a string that is only ever built when a user clicks. So the
|
|
16
|
+
* count is paid for at CLICK time, through its own request/reply pair that the
|
|
17
|
+
* sweep never sends. #7422's one-`gh`-call-per-head consistency rule is
|
|
18
|
+
* untouched: the sweep's survey still makes exactly the calls it made before.
|
|
19
|
+
*
|
|
20
|
+
* ## Resolution is DELEGATED, never re-derived
|
|
21
|
+
*
|
|
22
|
+
* Which repo, which branch, which PR number — that is `session-pr-status.js`'s
|
|
23
|
+
* question, and it has a lot of hard-won behaviour in it (a reaped worktree, a
|
|
24
|
+
* detached HEAD, a branch name that would be option-parsed, and the fork path
|
|
25
|
+
* where a cross-repository PR is listed on the BASE repo and must be
|
|
26
|
+
* disambiguated by head owner). A second implementation of that would drift, so
|
|
27
|
+
* this module CALLS it and inherits its degradation table wholesale: every
|
|
28
|
+
* reason `surveySessionPrStatus` can produce passes through here verbatim.
|
|
29
|
+
*
|
|
30
|
+
* The cost is one extra `gh pr list` per counted click. That is the deliberate
|
|
31
|
+
* trade against duplicating resolution logic, and the per-session throttle on
|
|
32
|
+
* the handler bounds how often it can be paid.
|
|
33
|
+
*
|
|
34
|
+
* ## Never a fabricated zero
|
|
35
|
+
*
|
|
36
|
+
* The one contract worth stating twice. A count that was not taken is
|
|
37
|
+
* `unresolvedCount: null` with a `reason` — never `0`. The two are not
|
|
38
|
+
* interchangeable and a consumer must render them differently: "0 unresolved
|
|
39
|
+
* threads" printed for a reading that never happened says "nothing is blocking
|
|
40
|
+
* this PR", which is the exact false green #7344 exists to prevent. The same
|
|
41
|
+
* applies to a TRUNCATED page: 100 resolved threads on page one with every
|
|
42
|
+
* unresolved one past it must not report a flat 0, so `truncated` rides along
|
|
43
|
+
* and a truncated count is a LOWER BOUND.
|
|
44
|
+
*
|
|
45
|
+
* Every external interaction is injectable so tests never touch real git/gh:
|
|
46
|
+
* - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`.
|
|
47
|
+
* - `_now()` — returns a `Date` (defaults to `new Date()`).
|
|
48
|
+
* - `_survey(opts)` — the PR resolution, defaults to `surveySessionPrStatus`.
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
import { execFile } from 'child_process'
|
|
52
|
+
import { promisify } from 'util'
|
|
53
|
+
import {
|
|
54
|
+
surveySessionPrStatus,
|
|
55
|
+
probeGh,
|
|
56
|
+
redactAbsolutePaths,
|
|
57
|
+
EXEC_OPTS,
|
|
58
|
+
GH_MISSING_REASON,
|
|
59
|
+
} from './session-pr-status.js'
|
|
60
|
+
import { execFailureReason } from './utils/exec-failure-reason.js'
|
|
61
|
+
import { isSafeArgvValue } from './utils/argv-safety.js'
|
|
62
|
+
|
|
63
|
+
const execFileAsync = promisify(execFile)
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* How many review threads one page reads.
|
|
67
|
+
*
|
|
68
|
+
* 100 is GitHub's per-connection maximum for a single `first:` argument, so
|
|
69
|
+
* this is the most one call can see. Beyond it the reading is a lower bound and
|
|
70
|
+
* says so (`truncated`) rather than paginating: a PR with >100 review threads
|
|
71
|
+
* is far outside the case this line serves, and a paging loop would put an
|
|
72
|
+
* unbounded number of `gh` calls behind one click.
|
|
73
|
+
*/
|
|
74
|
+
export const REVIEW_THREAD_PAGE_SIZE = 100
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The GraphQL document. Written with variables (never string-interpolated), so
|
|
78
|
+
* the owner/name/number data cannot alter the query's shape.
|
|
79
|
+
*
|
|
80
|
+
* `totalCount` and `pageInfo.hasNextPage` are both requested deliberately —
|
|
81
|
+
* either one alone establishes whether the page is complete, and a reading that
|
|
82
|
+
* has NEITHER is treated as unusable rather than as complete.
|
|
83
|
+
*/
|
|
84
|
+
export const REVIEW_THREADS_QUERY = [
|
|
85
|
+
'query($owner: String!, $name: String!, $number: Int!, $first: Int!) {',
|
|
86
|
+
' repository(owner: $owner, name: $name) {',
|
|
87
|
+
' pullRequest(number: $number) {',
|
|
88
|
+
' reviewThreads(first: $first) {',
|
|
89
|
+
' totalCount',
|
|
90
|
+
' pageInfo { hasNextPage }',
|
|
91
|
+
' nodes { isResolved }',
|
|
92
|
+
' }',
|
|
93
|
+
' }',
|
|
94
|
+
' }',
|
|
95
|
+
'}',
|
|
96
|
+
].join('\n')
|
|
97
|
+
|
|
98
|
+
/** Reason when the branch definitively has no open PR to count threads on. */
|
|
99
|
+
export const NO_OPEN_PR_REASON = 'no open pull request for this branch — no review threads to count'
|
|
100
|
+
|
|
101
|
+
/** Reason when the resolved repo owner/name is not safe for an option-parsed argv slot. */
|
|
102
|
+
export const UNSAFE_REPO_REASON = 'repository owner or name cannot be passed safely to gh'
|
|
103
|
+
|
|
104
|
+
/** Reason when `gh api graphql` answered with something that is not JSON. */
|
|
105
|
+
export const UNPARSEABLE_REASON = 'gh api graphql produced unparseable output'
|
|
106
|
+
|
|
107
|
+
/** Reason when the response parsed but carried no usable review-thread data. */
|
|
108
|
+
export const NO_THREAD_DATA_REASON = 'gh api graphql returned no usable review-thread data'
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Reduce a `gh api graphql` response to `{ unresolvedCount, totalCount, truncated }`,
|
|
112
|
+
* or `null` when the response cannot be trusted to answer the question.
|
|
113
|
+
*
|
|
114
|
+
* Returning `null` is not a formality — it is the only alternative to guessing,
|
|
115
|
+
* and every guess available here is a guess in the dangerous direction (an
|
|
116
|
+
* unreadable node absorbed as "resolved", a partial response counted as whole,
|
|
117
|
+
* an unknown page state read as complete). Each of those under-reports
|
|
118
|
+
* unresolved threads, i.e. manufactures the green.
|
|
119
|
+
*
|
|
120
|
+
* @param {unknown} payload - the parsed `gh api graphql` JSON.
|
|
121
|
+
* @returns {{ unresolvedCount: number, totalCount: number|null, truncated: boolean }|null}
|
|
122
|
+
*/
|
|
123
|
+
export function summariseReviewThreads(payload) {
|
|
124
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null
|
|
125
|
+
// GitHub can answer with data AND errors; the data is then partial, and
|
|
126
|
+
// counting what survived under-reports. Refuse the whole reading.
|
|
127
|
+
if (Array.isArray(payload.errors) && payload.errors.length > 0) return null
|
|
128
|
+
|
|
129
|
+
const threads = payload?.data?.repository?.pullRequest?.reviewThreads
|
|
130
|
+
if (!threads || typeof threads !== 'object' || Array.isArray(threads)) return null
|
|
131
|
+
const nodes = threads.nodes
|
|
132
|
+
if (!Array.isArray(nodes)) return null
|
|
133
|
+
|
|
134
|
+
let unresolvedCount = 0
|
|
135
|
+
for (const node of nodes) {
|
|
136
|
+
// `isResolved` is `Boolean!` in GitHub's schema, so anything else means the
|
|
137
|
+
// response is not what was asked for. Treating it as resolved would hide a
|
|
138
|
+
// thread; treating it as unresolved would invent one.
|
|
139
|
+
if (!node || typeof node !== 'object' || typeof node.isResolved !== 'boolean') return null
|
|
140
|
+
if (!node.isResolved) unresolvedCount += 1
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const rawTotal = threads.totalCount
|
|
144
|
+
const totalCount = Number.isInteger(rawTotal) && rawTotal >= 0 ? rawTotal : null
|
|
145
|
+
const hasNextPage = threads?.pageInfo?.hasNextPage
|
|
146
|
+
|
|
147
|
+
let truncated
|
|
148
|
+
if (hasNextPage === true) truncated = true
|
|
149
|
+
else if (hasNextPage === false) truncated = totalCount !== null && totalCount > nodes.length
|
|
150
|
+
else if (totalCount !== null) truncated = totalCount > nodes.length
|
|
151
|
+
// Neither signal is readable: completeness was never established, so it must
|
|
152
|
+
// not be assumed. "Cannot check" is not "nothing to check".
|
|
153
|
+
else return null
|
|
154
|
+
|
|
155
|
+
return { unresolvedCount, totalCount, truncated }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The skeleton every return path shares — a count-shaped nothing. */
|
|
159
|
+
function baseSnapshot(sessionId, countedAt) {
|
|
160
|
+
return {
|
|
161
|
+
sessionId,
|
|
162
|
+
countedAt,
|
|
163
|
+
prNumber: null,
|
|
164
|
+
unresolvedCount: null,
|
|
165
|
+
totalCount: null,
|
|
166
|
+
truncated: false,
|
|
167
|
+
reason: null,
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Count the session PR's unresolved review threads.
|
|
173
|
+
*
|
|
174
|
+
* Never throws for an environmental cause: an unresolvable PR, a missing `gh`,
|
|
175
|
+
* a failed or unparseable call all resolve to a snapshot carrying a `reason`
|
|
176
|
+
* and a null count.
|
|
177
|
+
*
|
|
178
|
+
* @param {object} opts
|
|
179
|
+
* @param {string} opts.sessionId - the session this reading describes.
|
|
180
|
+
* @param {string|null|undefined} opts.cwd - the session's working directory.
|
|
181
|
+
* @param {Function} [opts._execFile] - promisified execFile seam.
|
|
182
|
+
* @param {Function} [opts._now] - Date factory seam.
|
|
183
|
+
* @param {Function} [opts._survey] - PR resolution seam.
|
|
184
|
+
* @returns {Promise<object>} the reading (minus the wire `type`/`requestId`,
|
|
185
|
+
* which the handler adds).
|
|
186
|
+
*/
|
|
187
|
+
export async function surveySessionPrThreads({
|
|
188
|
+
sessionId,
|
|
189
|
+
cwd,
|
|
190
|
+
_execFile = execFileAsync,
|
|
191
|
+
_now = () => new Date(),
|
|
192
|
+
_survey = surveySessionPrStatus,
|
|
193
|
+
} = {}) {
|
|
194
|
+
// Stamped when the reading STARTS, matching `generatedAt`'s convention on the
|
|
195
|
+
// status snapshot — but a field of its own, because the two go stale on
|
|
196
|
+
// different schedules and one timestamp over both would claim a consistency
|
|
197
|
+
// neither message has.
|
|
198
|
+
const snapshot = baseSnapshot(sessionId ?? null, _now().toISOString())
|
|
199
|
+
|
|
200
|
+
const status = await _survey({ sessionId, cwd, _execFile, _now })
|
|
201
|
+
|
|
202
|
+
// Resolution failed and already said why, in the vocabulary the status chip
|
|
203
|
+
// uses. Repeating it in different words here would make the same condition
|
|
204
|
+
// read as two different problems.
|
|
205
|
+
if (status?.reason) {
|
|
206
|
+
snapshot.reason = status.reason
|
|
207
|
+
return snapshot
|
|
208
|
+
}
|
|
209
|
+
if (!status?.pr || !status?.repo) {
|
|
210
|
+
snapshot.reason = NO_OPEN_PR_REASON
|
|
211
|
+
return snapshot
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const { owner, name } = status.repo
|
|
215
|
+
const number = status.pr.number
|
|
216
|
+
// Named even when the count fails, so a consumer can tell WHICH PR it has no
|
|
217
|
+
// count for — and refuse to print a count next to a different PR's number.
|
|
218
|
+
snapshot.prNumber = number
|
|
219
|
+
|
|
220
|
+
// These come from the git remote via parseGithubOwnerRepo rather than from a
|
|
221
|
+
// client, but they go into option-parsed argv slots, so they are checked like
|
|
222
|
+
// any other argv datum (argv-safety.js, fix shape 1).
|
|
223
|
+
if (!isSafeArgvValue(owner) || !isSafeArgvValue(name)) {
|
|
224
|
+
snapshot.reason = UNSAFE_REPO_REASON
|
|
225
|
+
return snapshot
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const ghPath = await probeGh(_execFile)
|
|
229
|
+
if (!ghPath) {
|
|
230
|
+
snapshot.reason = GH_MISSING_REASON
|
|
231
|
+
return snapshot
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Every datum rides in a `key=value` token, so none of them can begin with a
|
|
235
|
+
// `-` even in principle, and the query itself is a constant.
|
|
236
|
+
const args = [
|
|
237
|
+
'api', 'graphql',
|
|
238
|
+
'-f', `query=${REVIEW_THREADS_QUERY}`,
|
|
239
|
+
'-f', `owner=${owner}`,
|
|
240
|
+
'-f', `name=${name}`,
|
|
241
|
+
'-F', `number=${number}`,
|
|
242
|
+
'-F', `first=${REVIEW_THREAD_PAGE_SIZE}`,
|
|
243
|
+
]
|
|
244
|
+
|
|
245
|
+
let stdout
|
|
246
|
+
try {
|
|
247
|
+
;({ stdout } = await _execFile(ghPath, args, { ...EXEC_OPTS, cwd }))
|
|
248
|
+
} catch (err) {
|
|
249
|
+
// This reply reaches a pairing-bound (share-a-session) client, which has no
|
|
250
|
+
// business learning host filesystem layout — and execFile's own message is
|
|
251
|
+
// `Command failed: <absolute gh path> …`.
|
|
252
|
+
snapshot.reason = redactAbsolutePaths(execFailureReason(err, 'gh api graphql'))
|
|
253
|
+
return snapshot
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
let parsed
|
|
257
|
+
try {
|
|
258
|
+
parsed = JSON.parse(String(stdout == null ? '' : stdout))
|
|
259
|
+
} catch {
|
|
260
|
+
snapshot.reason = UNPARSEABLE_REASON
|
|
261
|
+
return snapshot
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const summary = summariseReviewThreads(parsed)
|
|
265
|
+
if (!summary) {
|
|
266
|
+
snapshot.reason = NO_THREAD_DATA_REASON
|
|
267
|
+
return snapshot
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return { ...snapshot, ...summary }
|
|
271
|
+
}
|
|
@@ -38,11 +38,11 @@
|
|
|
38
38
|
import { existsSync } from 'fs'
|
|
39
39
|
import { createLogger } from './logger.js'
|
|
40
40
|
import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
|
|
41
|
-
import {
|
|
41
|
+
import { defaultPresetTrustFile, _normalizePathKey } from './session-preset.js'
|
|
42
42
|
|
|
43
43
|
const log = createLogger('session-preset-trust')
|
|
44
44
|
|
|
45
|
-
export {
|
|
45
|
+
export { defaultPresetTrustFile }
|
|
46
46
|
|
|
47
47
|
/**
|
|
48
48
|
* In-memory + on-disk trust ledger for repo-local session presets. One
|
|
@@ -55,7 +55,7 @@ export class SessionPresetTrustStore extends PathHashTrustLedger {
|
|
|
55
55
|
*/
|
|
56
56
|
constructor({ filePath } = {}) {
|
|
57
57
|
super({
|
|
58
|
-
filePath: filePath ||
|
|
58
|
+
filePath: filePath || defaultPresetTrustFile(),
|
|
59
59
|
log,
|
|
60
60
|
normalizeKey: _normalizePathKey,
|
|
61
61
|
approvalField: 'approvedAt',
|
package/src/session-preset.js
CHANGED
|
@@ -39,6 +39,7 @@ import { dirname, join, resolve, basename } from 'path'
|
|
|
39
39
|
import { homedir } from 'os'
|
|
40
40
|
import { createHash } from 'crypto'
|
|
41
41
|
import { createLogger } from './logger.js'
|
|
42
|
+
import { configPath } from './config-dir.js'
|
|
42
43
|
|
|
43
44
|
const log = createLogger('session-preset')
|
|
44
45
|
|
|
@@ -63,8 +64,12 @@ const MAX_PRESET_FILE_BYTES = 64 * 1024
|
|
|
63
64
|
// Cap walk-up iterations — a safety belt; real repos are nowhere near this deep.
|
|
64
65
|
const REPO_DISCOVERY_MAX_DEPTH = 100
|
|
65
66
|
|
|
66
|
-
export
|
|
67
|
-
|
|
67
|
+
export function defaultConfigPath() {
|
|
68
|
+
return configPath('config.json')
|
|
69
|
+
}
|
|
70
|
+
export function defaultPresetTrustFile() {
|
|
71
|
+
return configPath('session-preset-trust.json')
|
|
72
|
+
}
|
|
68
73
|
|
|
69
74
|
const _PATH_COMPARE_CASE_INSENSITIVE =
|
|
70
75
|
process.platform === 'darwin' || process.platform === 'win32'
|
|
@@ -321,7 +326,7 @@ export function readRepoPresetFile(absPath) {
|
|
|
321
326
|
* @param {string} [configPath]
|
|
322
327
|
* @returns {object|null}
|
|
323
328
|
*/
|
|
324
|
-
export function _findRepoConfigEntry(repoPath, configPath =
|
|
329
|
+
export function _findRepoConfigEntry(repoPath, configPath = defaultConfigPath()) {
|
|
325
330
|
if (!repoPath || typeof repoPath !== 'string') return null
|
|
326
331
|
let raw
|
|
327
332
|
try {
|
|
@@ -351,7 +356,7 @@ function _resolveSafe(p) {
|
|
|
351
356
|
* @param {string} [configPath]
|
|
352
357
|
* @returns {null | ReturnType<typeof validatePreset>}
|
|
353
358
|
*/
|
|
354
|
-
export function readDaemonOverride(repoPath, configPath =
|
|
359
|
+
export function readDaemonOverride(repoPath, configPath = defaultConfigPath()) {
|
|
355
360
|
const entry = _findRepoConfigEntry(repoPath, configPath)
|
|
356
361
|
if (!entry || !entry.sessionPreset) return null
|
|
357
362
|
return validatePreset(entry.sessionPreset)
|
|
@@ -393,7 +398,7 @@ export function readDaemonOverride(repoPath, configPath = DEFAULT_CONFIG_PATH) {
|
|
|
393
398
|
*/
|
|
394
399
|
export function resolveSessionPreset(cwd, opts = {}) {
|
|
395
400
|
const trustStore = opts.trustStore || null
|
|
396
|
-
const configPath = opts.configPath ||
|
|
401
|
+
const configPath = opts.configPath || defaultConfigPath()
|
|
397
402
|
|
|
398
403
|
// 1. Locate the repo root (the dir holding `.chroxy/session.json`) via the
|
|
399
404
|
// walk-up. We need it for BOTH the repo-file read and the daemon override
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import fs from 'fs'
|
|
2
|
+
import { performance } from 'perf_hooks'
|
|
2
3
|
import { dirname } from 'path'
|
|
3
4
|
import { isWindows, writeFileRestricted } from './platform.js'
|
|
4
5
|
import { createLogger } from './logger.js'
|
|
6
|
+
import { savedHasHistory } from './session-archive-limits.js'
|
|
5
7
|
|
|
6
8
|
const log = createLogger('session-state-persistence')
|
|
7
9
|
|
|
@@ -21,14 +23,24 @@ export class SessionStatePersistence {
|
|
|
21
23
|
* @param {string} options.stateFilePath - Path to session state JSON file
|
|
22
24
|
* @param {number} [options.stateTtlMs=86400000] - Max age of persisted state before discard (default: 24 hours)
|
|
23
25
|
* @param {number} [options.persistDebounceMs=2000] - Debounce interval for state file writes
|
|
26
|
+
* @param {number} [options.persistMaxWaitMs=10000] - Upper bound on how long a pending write may be postponed by a continuous stream of schedulePersist calls
|
|
27
|
+
* @param {() => number} [options.now] - Monotonic millisecond clock for the max-wait window (default: performance.now). Must not be wall-clock time: setTimeout is monotonic, so a wall-clock rollback would otherwise stretch the window
|
|
24
28
|
* @param {boolean} [options.isWindowsOverride] - Test-only: force Windows-specific branches regardless of host platform
|
|
25
29
|
*/
|
|
26
|
-
constructor({ stateFilePath, stateTtlMs, persistDebounceMs = 2000, isWindowsOverride } = {}) {
|
|
30
|
+
constructor({ stateFilePath, stateTtlMs, persistDebounceMs = 2000, persistMaxWaitMs = 10_000, now = () => performance.now(), isWindowsOverride } = {}) {
|
|
27
31
|
this._stateFilePath = stateFilePath
|
|
28
32
|
this._stateTtlMs = stateTtlMs ?? 24 * 60 * 60 * 1000
|
|
29
33
|
this._persistDebounceMs = persistDebounceMs
|
|
34
|
+
this._persistMaxWaitMs = persistMaxWaitMs
|
|
35
|
+
this._now = now
|
|
30
36
|
this._persistTimer = null
|
|
37
|
+
/** @type {number|null} monotonic time at which the armed timer is due */
|
|
38
|
+
this._persistDueAt = null
|
|
39
|
+
/** @type {number|null} when the oldest unwritten schedulePersist call arrived (max-wait anchor) */
|
|
40
|
+
this._persistPendingSince = null
|
|
31
41
|
this._isWindows = isWindowsOverride ?? isWindows
|
|
42
|
+
/** @type {string|null} the last write's unconfirmed-durability verdict (see serializeState) */
|
|
43
|
+
this.lastDurabilityUnconfirmed = null
|
|
32
44
|
}
|
|
33
45
|
|
|
34
46
|
/**
|
|
@@ -66,9 +78,13 @@ export class SessionStatePersistence {
|
|
|
66
78
|
* `.bak` (rotate failed). `writeFileSync` on Windows overwrites either way.
|
|
67
79
|
*
|
|
68
80
|
* @param {object} state - The complete state object to write (version, timestamp, sessions, costs, etc.)
|
|
81
|
+
* @param {{ durable?: boolean }} [opts] - `durable` fsyncs the temp file before the rename, for
|
|
82
|
+
* a caller about to drop its only other copy of the data (#8866)
|
|
69
83
|
* @returns {object} The state that was written
|
|
70
84
|
*/
|
|
71
|
-
serializeState(state) {
|
|
85
|
+
serializeState(state, { durable = false } = {}) {
|
|
86
|
+
// Reset first: a throw before the write must not leave a previous verdict.
|
|
87
|
+
this.lastDurabilityUnconfirmed = null
|
|
72
88
|
const dir = dirname(this._stateFilePath)
|
|
73
89
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
|
|
74
90
|
const bakPath = this._stateFilePath + '.bak'
|
|
@@ -91,7 +107,11 @@ export class SessionStatePersistence {
|
|
|
91
107
|
// hard-kill mid-write (between writeFileSync and renameSync) is never
|
|
92
108
|
// reused by a later process and no sweeper reclaims it. Accepted: such
|
|
93
109
|
// mid-write hard-kills are rare and the sidecar is tiny (matches models.js).
|
|
94
|
-
writeFileRestricted(this._stateFilePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}
|
|
110
|
+
const written = writeFileRestricted(this._stateFilePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}`, durable })
|
|
111
|
+
// A post-rename directory-fsync failure does NOT throw: the file is live but
|
|
112
|
+
// its durability is unproven. Keep the verdict for callers that drop another
|
|
113
|
+
// copy on the strength of this write (`SessionManager._flushPersistConfirmedDurable`).
|
|
114
|
+
this.lastDurabilityUnconfirmed = written?.durabilityUnconfirmed ?? null
|
|
95
115
|
log.info(`Serialized ${state.sessions?.length ?? 0} session(s) to ${this._stateFilePath}`)
|
|
96
116
|
return state
|
|
97
117
|
}
|
|
@@ -207,12 +227,28 @@ export class SessionStatePersistence {
|
|
|
207
227
|
const now = Date.now()
|
|
208
228
|
const fresh = []
|
|
209
229
|
const dropped = []
|
|
230
|
+
// #7627 — the stale ENTRIES, not just their names. They are SET ASIDE, not
|
|
231
|
+
// deleted: the log below says so, because "Dropped" described the old
|
|
232
|
+
// behaviour and reading it as deletion is what made this defect invisible. A stale session is still
|
|
233
|
+
// not restored (that is the policy this filter exists for), but this layer
|
|
234
|
+
// cannot tell a session that would restore fine from one whose restore will
|
|
235
|
+
// REFUSE and whose history the #2954 contract promises to preserve. Only
|
|
236
|
+
// SessionManager knows that, so hand the entries over instead of deleting
|
|
237
|
+
// them here and let it decide. Deleting them here made the failed-restore
|
|
238
|
+
// TTL (30 days) unreachable for anything last active more than 24h ago.
|
|
239
|
+
const stale = []
|
|
210
240
|
for (const saved of state.sessions) {
|
|
211
241
|
const activityAt = (typeof saved.lastActivityAt === 'number' && saved.lastActivityAt > 0)
|
|
212
242
|
? saved.lastActivityAt
|
|
213
243
|
: state.timestamp
|
|
214
|
-
|
|
244
|
+
// #8870 — a session with no history is restored at any age. Setting it
|
|
245
|
+
// aside would end in the archive skipping it (nothing to read), so it
|
|
246
|
+
// left the list with no record: the startup "Default" vanished after a
|
|
247
|
+
// restart. It holds only its name, cwd, provider and settings, so it is
|
|
248
|
+
// restored like a recent session and leaves the way any live one does.
|
|
249
|
+
if (activityAt && now - activityAt > this._stateTtlMs && savedHasHistory(saved)) {
|
|
215
250
|
dropped.push(saved.name || saved.id || '<unknown>')
|
|
251
|
+
stale.push(saved)
|
|
216
252
|
} else {
|
|
217
253
|
fresh.push(saved)
|
|
218
254
|
}
|
|
@@ -225,18 +261,29 @@ export class SessionStatePersistence {
|
|
|
225
261
|
const MAX_NAMES = 10
|
|
226
262
|
const sample = dropped.slice(0, MAX_NAMES).map((n) => JSON.stringify(String(n)))
|
|
227
263
|
const more = dropped.length > MAX_NAMES ? `, …+${dropped.length - MAX_NAMES} more` : ''
|
|
228
|
-
log.warn(`
|
|
229
|
-
}
|
|
230
|
-
if (fresh.length === 0) {
|
|
231
|
-
log.info('All restored sessions are stale, starting fresh')
|
|
232
|
-
return null
|
|
264
|
+
log.warn(`Set aside ${dropped.length} stale session(s), not restored (>${Math.round(this._stateTtlMs / 60000)}min since last activity): ${sample.join(', ')}${more}`)
|
|
233
265
|
}
|
|
266
|
+
// NOTE: there is deliberately no `fresh.length === 0` early return here.
|
|
267
|
+
// #7627 made one unreachable — the guard above returns for an empty
|
|
268
|
+
// `state.sessions`, and the loop partitions a non-empty one into
|
|
269
|
+
// `fresh ∪ stale` — so it would have been dead code, and the all-stale case
|
|
270
|
+
// is now a legitimate result carrying entries for SessionManager to
|
|
271
|
+
// adjudicate. The warn above already reports it.
|
|
234
272
|
state.sessions = fresh
|
|
273
|
+
// #7627: carried separately so the normal restore path sees EXACTLY what it
|
|
274
|
+
// saw before — `state.sessions` is still the fresh set and nothing downstream
|
|
275
|
+
// has to learn about staleness to keep working.
|
|
276
|
+
state.staleSessions = stale
|
|
235
277
|
return state
|
|
236
278
|
}
|
|
237
279
|
|
|
238
280
|
/**
|
|
239
|
-
* Schedule a debounced persist
|
|
281
|
+
* Schedule a debounced persist with a max-wait. Calls arriving within
|
|
282
|
+
* persistDebounceMs of each other coalesce into one trailing write, but the
|
|
283
|
+
* write is never postponed past persistMaxWaitMs after the FIRST unwritten
|
|
284
|
+
* call (#8954). Without the max-wait a pure trailing debounce was reset by
|
|
285
|
+
* every append, so a long continuously-streaming turn wrote nothing until it
|
|
286
|
+
* ended.
|
|
240
287
|
*
|
|
241
288
|
* #5309 (WP-0.3) — durability boundary, by design: this debounce backs
|
|
242
289
|
* high-frequency message-history appends only. Session-LIST mutations
|
|
@@ -244,25 +291,53 @@ export class SessionStatePersistence {
|
|
|
244
291
|
* every CLEAN exit path serializes immediately — SIGINT/SIGTERM (server-cli.js)
|
|
245
292
|
* and the supervised IPC shutdown + crash handlers (server-cli-child.js, #5308)
|
|
246
293
|
* all call serializeState() directly (followed by destroyAll(), which cancels
|
|
247
|
-
* this timer and no-ops any stray fire). So the only way to lose
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
294
|
+
* this timer and no-ops any stray fire). So the only way to lose message
|
|
295
|
+
* history is an abrupt kill that runs NO handler at all — SIGKILL, OOM-kill,
|
|
296
|
+
* or power loss. The real bound on that loss is persistMaxWaitMs (default 10s)
|
|
297
|
+
* of history, NOT persistDebounceMs: during a continuous stream the debounce
|
|
298
|
+
* alone never fires, and the max-wait is what forces a write. That window is
|
|
299
|
+
* accepted as best-effort: shrinking it further trades constant write
|
|
300
|
+
* amplification on every token for protection against a kill we can't flush
|
|
301
|
+
* before anyway.
|
|
302
|
+
*
|
|
303
|
+
* Implemented with a single timer (delay = min(debounce, time left until the
|
|
304
|
+
* max-wait deadline), clamped at 0), so clearing `_persistTimer` cancels
|
|
305
|
+
* everything.
|
|
306
|
+
* Elapsed time comes from a MONOTONIC clock (`now`), the same time base as
|
|
307
|
+
* setTimeout, so a wall-clock rollback cannot stretch the window. A timer
|
|
308
|
+
* that is already due is never cancelled and re-armed: a call that runs
|
|
309
|
+
* before the overdue callback would otherwise keep pushing it back by Node's
|
|
310
|
+
* minimum delay and starve the write.
|
|
311
|
+
*
|
|
312
|
+
* The max-wait bounds postponement BY SCHEDULING CALLS only. It is not an
|
|
313
|
+
* absolute data-loss bound: the write still depends on the event loop running
|
|
314
|
+
* the callback and on serializeFn succeeding.
|
|
253
315
|
*
|
|
254
316
|
* @param {() => void} serializeFn - Function to call when the debounce fires
|
|
255
317
|
*/
|
|
256
318
|
schedulePersist(serializeFn) {
|
|
319
|
+
const now = this._now()
|
|
320
|
+
if (this._persistTimer === null || this._persistPendingSince === null) {
|
|
321
|
+
this._persistPendingSince = now
|
|
322
|
+
this._persistDueAt = null
|
|
323
|
+
}
|
|
324
|
+
// Already due (or due at/after the deadline): leave it alone.
|
|
325
|
+
if (this._persistTimer !== null && this._persistDueAt !== null && this._persistDueAt <= now) return
|
|
326
|
+
const deadline = this._persistPendingSince + this._persistMaxWaitMs
|
|
327
|
+
if (this._persistTimer !== null && now >= deadline) return
|
|
257
328
|
clearTimeout(this._persistTimer)
|
|
329
|
+
const delay = Math.max(0, Math.min(this._persistDebounceMs, deadline - now))
|
|
330
|
+
this._persistDueAt = now + delay
|
|
258
331
|
this._persistTimer = setTimeout(() => {
|
|
259
332
|
this._persistTimer = null
|
|
333
|
+
this._persistPendingSince = null
|
|
334
|
+
this._persistDueAt = null
|
|
260
335
|
try {
|
|
261
336
|
serializeFn()
|
|
262
337
|
} catch (err) {
|
|
263
338
|
log.error(`Failed to persist session state: ${err?.stack || err}`)
|
|
264
339
|
}
|
|
265
|
-
},
|
|
340
|
+
}, delay)
|
|
266
341
|
}
|
|
267
342
|
|
|
268
343
|
/**
|
|
@@ -271,6 +346,8 @@ export class SessionStatePersistence {
|
|
|
271
346
|
cancelPersist() {
|
|
272
347
|
clearTimeout(this._persistTimer)
|
|
273
348
|
this._persistTimer = null
|
|
349
|
+
this._persistPendingSince = null
|
|
350
|
+
this._persistDueAt = null
|
|
274
351
|
}
|
|
275
352
|
|
|
276
353
|
/**
|
|
@@ -18,6 +18,26 @@ export function formatIdleDuration(ms) {
|
|
|
18
18
|
return minutes > 0 ? `${hPart} ${minutes} minute${minutes !== 1 ? 's' : ''}` : hPart
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* #8223: like `formatIdleDuration`, but for a duration a message states as a FACT
|
|
23
|
+
* ("no response within …") rather than a rough idle window. `formatIdleDuration`
|
|
24
|
+
* rounds to the nearest minute, so the 90s first-output watchdog read "2 minutes"
|
|
25
|
+
* — a 33% overstatement. Here a value between a minute and an hour that is not a
|
|
26
|
+
* whole number of minutes keeps its seconds ("90 seconds"); whole minutes ("5
|
|
27
|
+
* minutes"), sub-minute values and hours format exactly as `formatIdleDuration`
|
|
28
|
+
* does, so the two only disagree where the rounding was wrong.
|
|
29
|
+
*
|
|
30
|
+
* `formatIdleDuration` itself is left alone: it has ~20 call sites and
|
|
31
|
+
* session-manager.test.js pins 90000 -> "2 minutes" for the idle-timeout copy.
|
|
32
|
+
*/
|
|
33
|
+
export function formatWatchdogDuration(ms) {
|
|
34
|
+
const totalSeconds = Math.round(ms / 1000)
|
|
35
|
+
if (totalSeconds > 60 && totalSeconds < 3600 && totalSeconds % 60 !== 0) {
|
|
36
|
+
return `${totalSeconds} seconds`
|
|
37
|
+
}
|
|
38
|
+
return formatIdleDuration(ms)
|
|
39
|
+
}
|
|
40
|
+
|
|
21
41
|
/**
|
|
22
42
|
* Manages session idle timeouts independently of session lifecycle.
|
|
23
43
|
*
|
|
@@ -10,9 +10,10 @@
|
|
|
10
10
|
//
|
|
11
11
|
// PairingManager stays filesystem-agnostic: it takes this as an injected
|
|
12
12
|
// { load, save } adapter, so tests can drive it with an in-memory fake.
|
|
13
|
-
import {
|
|
13
|
+
import { existsSync, mkdirSync } from 'fs'
|
|
14
14
|
import { join } from 'path'
|
|
15
15
|
import { writeFileRestricted } from './platform.js'
|
|
16
|
+
import { readTrustedSecretFile } from './trusted-file-read.js'
|
|
16
17
|
import { getOrCreateMasterKey, encryptJson, decryptEnvelope, isEncryptedEnvelope } from './credential-cipher.js'
|
|
17
18
|
import * as realKeychain from './keychain.js'
|
|
18
19
|
import { createLogger } from './logger.js'
|
|
@@ -43,19 +44,27 @@ export function createSessionTokenStore({ dir, keychain = realKeychain } = {}) {
|
|
|
43
44
|
// The daemon's `load()` fail-softs all of these to `[]` (a re-pair is harmless);
|
|
44
45
|
// the tokens CLI uses `loadResult()` so it never overwrites a store it couldn't
|
|
45
46
|
// read, nor reports "0 tokens" for one it simply failed to decrypt.
|
|
47
|
+
//
|
|
48
|
+
// #7893: the mode check and the read go through `readTrustedSecretFile` — ONE
|
|
49
|
+
// `open(O_NOFOLLOW)` + `fstat(fd)` + read from that same fd, so a rename or
|
|
50
|
+
// symlink-swap of `session-tokens.json` between the mode check and the read
|
|
51
|
+
// (the old `statSync(path)` then `readFileSync(path)` shape) is refused
|
|
52
|
+
// outright rather than followed.
|
|
46
53
|
function read() {
|
|
47
54
|
try {
|
|
48
|
-
if (!existsSync(file)) return { status: 'absent', entries: [] }
|
|
49
55
|
// Enforce owner-only 0600 (POSIX) — same boundary as the credential store.
|
|
50
56
|
// A world/group-readable token file is refused rather than trusted.
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
57
|
+
const result = readTrustedSecretFile(file, { mode: 0o600 })
|
|
58
|
+
if (result.status === 'absent') return { status: 'absent', entries: [] }
|
|
59
|
+
if (result.status === 'refused') {
|
|
60
|
+
if (result.code === 'EMODE') {
|
|
61
|
+
log.warn(`${file} has mode ${result.mode.toString(8).padStart(3, '0')}; refusing to read (must be 0600) — devices will re-pair`)
|
|
62
|
+
} else {
|
|
63
|
+
log.warn(`could not load persisted session tokens (${result.cause ? result.cause.message : result.code}) — devices will re-pair`)
|
|
56
64
|
}
|
|
65
|
+
return { status: 'unreadable', entries: [] }
|
|
57
66
|
}
|
|
58
|
-
const parsed = JSON.parse(
|
|
67
|
+
const parsed = JSON.parse(result.content)
|
|
59
68
|
if (isEncryptedEnvelope(parsed)) {
|
|
60
69
|
const key = getOrCreateMasterKey(keychain)
|
|
61
70
|
if (!key) {
|