@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// TranscriptTaskScanner (#5431) — incremental session-transcript scanner that
|
|
2
|
+
// derives OUTSTANDING background work (run_in_background Bash/Agent calls,
|
|
3
|
+
// Monitor streams) and a pending ScheduleWakeup from a Claude Code session
|
|
4
|
+
// transcript (`~/.claude/projects/<slug>/<sessionId>.jsonl`).
|
|
5
|
+
//
|
|
6
|
+
// Why a transcript scan: the per-PID session file (`~/.claude/sessions/
|
|
7
|
+
// <pid>.json`) that drives the readiness probe carries only `status` — no
|
|
8
|
+
// task info — but it DOES carry `sessionId` + `cwd`, which is enough to
|
|
9
|
+
// derive the transcript path. The transcript contains both halves of the
|
|
10
|
+
// signal, pairable by tool-use ID:
|
|
11
|
+
//
|
|
12
|
+
// Launch (assistant entry, verified shape):
|
|
13
|
+
// { "type": "assistant", "timestamp": "2026-06-10T02:39:05.423Z",
|
|
14
|
+
// "message": { "role": "assistant", "content": [
|
|
15
|
+
// { "type": "tool_use", "id": "toolu_015ydMyyDW7NE7Jbrqu6Eoxe",
|
|
16
|
+
// "name": "Bash",
|
|
17
|
+
// "input": { "description": "Install dependencies in merge worktree",
|
|
18
|
+
// "run_in_background": true, ... } } ] } }
|
|
19
|
+
//
|
|
20
|
+
// Completion (queue-operation entry; the same XML is also re-delivered as
|
|
21
|
+
// a `user` entry with string content when the notification is dequeued):
|
|
22
|
+
// { "type": "queue-operation", "operation": "enqueue",
|
|
23
|
+
// "timestamp": "2026-06-10T02:39:40.819Z",
|
|
24
|
+
// "content": "<task-notification>\n<task-id>bnclpiaj0</task-id>\n
|
|
25
|
+
// <tool-use-id>toolu_015ydMyyDW7NE7Jbrqu6Eoxe</tool-use-id>\n…
|
|
26
|
+
// <status>completed</status>…</task-notification>" }
|
|
27
|
+
//
|
|
28
|
+
// ScheduleWakeup (assistant tool_use, verified shape):
|
|
29
|
+
// { "type": "tool_use", "id": "toolu_016KpP2dT7mFhk4HDgUU2ype",
|
|
30
|
+
// "name": "ScheduleWakeup",
|
|
31
|
+
// "input": { "delaySeconds": 90, "reason": "Waiting for …",
|
|
32
|
+
// "prompt": "Check PR #149 required checks; …" } }
|
|
33
|
+
//
|
|
34
|
+
// Outstanding work = launches without a matching completion. A wakeup is
|
|
35
|
+
// pending until a later user/assistant entry lands AFTER its scheduled time
|
|
36
|
+
// (the harness re-invoked the agent), a later user entry carries its prompt,
|
|
37
|
+
// or a newer ScheduleWakeup supersedes it.
|
|
38
|
+
//
|
|
39
|
+
// Robustness contract (#5431 success criterion — degrade silently):
|
|
40
|
+
// - The transcript format is the harness's INTERNAL representation, not a
|
|
41
|
+
// stable API. Every parse is defensive; an unparseable line is skipped.
|
|
42
|
+
// - Any I/O or structural failure makes `scan()` return the EMPTY result
|
|
43
|
+
// (plus a debug log) — it never throws into the readiness path.
|
|
44
|
+
// - Transcripts grow large (5MB+); a byte offset is tracked per scanner so
|
|
45
|
+
// each scan reads only the new tail. A shrunken file (rotation /
|
|
46
|
+
// truncation) resets the scanner and re-reads from byte 0.
|
|
47
|
+
|
|
48
|
+
import { closeSync, fstatSync, openSync, readFileSync, readSync } from 'fs'
|
|
49
|
+
import { homedir } from 'os'
|
|
50
|
+
import { join } from 'path'
|
|
51
|
+
import { createLogger } from './logger.js'
|
|
52
|
+
|
|
53
|
+
const log = createLogger('transcript-tasks')
|
|
54
|
+
|
|
55
|
+
/** Empty scan result — the "no outstanding work / degraded" shape. */
|
|
56
|
+
export const EMPTY_TASK_SNAPSHOT = Object.freeze({
|
|
57
|
+
backgroundTasks: Object.freeze([]),
|
|
58
|
+
scheduledWakeup: null,
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
// Cap a single incremental read so a pathological transcript (or a first
|
|
62
|
+
// scan against an existing multi-MB file) can't balloon memory. 16 MiB is
|
|
63
|
+
// >3x the largest transcript observed in the wild (~5 MB); when the unread
|
|
64
|
+
// tail exceeds the cap we skip ahead and only parse the final window —
|
|
65
|
+
// stale-launch detail may be lost but the scanner stays bounded and the
|
|
66
|
+
// readiness path stays fast.
|
|
67
|
+
export const MAX_SCAN_BYTES = 16 * 1024 * 1024
|
|
68
|
+
|
|
69
|
+
// Truncate `description` fallbacks derived from an Agent `prompt` — prompts
|
|
70
|
+
// are unbounded; 80 chars matches the issue's payload sketch.
|
|
71
|
+
const PROMPT_DESCRIPTION_MAX = 80
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Slugify a cwd into the directory name Claude Code uses under
|
|
75
|
+
* `~/.claude/projects/`. Verified against real project dirs on disk:
|
|
76
|
+
* every non-alphanumeric character (slashes, dots, spaces, …) becomes `-`,
|
|
77
|
+
* e.g. `/Users/blamechris/Projects/repo-relay` →
|
|
78
|
+
* `-Users-blamechris-Projects-repo-relay` and
|
|
79
|
+
* `/Users/x/Downloads/Mom Hospitalization Files` →
|
|
80
|
+
* `-Users-x-Downloads-Mom-Hospitalization-Files`.
|
|
81
|
+
* @param {string} cwd
|
|
82
|
+
* @returns {string}
|
|
83
|
+
*/
|
|
84
|
+
export function slugifyCwd(cwd) {
|
|
85
|
+
return String(cwd).replace(/[^a-zA-Z0-9]/g, '-')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Derive the transcript path for a per-PID session file
|
|
90
|
+
* (`~/.claude/sessions/<pid>.json`, which carries `sessionId` + `cwd`).
|
|
91
|
+
* Returns null on any failure (missing file, bad JSON, missing fields) —
|
|
92
|
+
* callers treat null as "no transcript available, degrade to plain ready".
|
|
93
|
+
* @param {string} sessionFilePath
|
|
94
|
+
* @returns {string|null}
|
|
95
|
+
*/
|
|
96
|
+
export function transcriptPathForSessionFile(sessionFilePath) {
|
|
97
|
+
try {
|
|
98
|
+
const data = JSON.parse(readFileSync(sessionFilePath, 'utf8'))
|
|
99
|
+
const sessionId = typeof data?.sessionId === 'string' ? data.sessionId : null
|
|
100
|
+
const cwd = typeof data?.cwd === 'string' ? data.cwd : null
|
|
101
|
+
if (!sessionId || !cwd) return null
|
|
102
|
+
// Defence-in-depth: the sessionId becomes a path segment. Real ids are
|
|
103
|
+
// UUIDs; reject anything that could traverse out of the projects dir.
|
|
104
|
+
if (!/^[A-Za-z0-9-]+$/.test(sessionId)) return null
|
|
105
|
+
return join(homedir(), '.claude', 'projects', slugifyCwd(cwd), `${sessionId}.jsonl`)
|
|
106
|
+
} catch (err) {
|
|
107
|
+
log.debug?.(`transcriptPathForSessionFile failed for ${sessionFilePath}: ${err.message}`)
|
|
108
|
+
return null
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Extract every `<tool-use-id>…</tool-use-id>` from a task-notification blob. */
|
|
113
|
+
const TOOL_USE_ID_TAG = /<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/g
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Incremental scanner for one transcript file.
|
|
117
|
+
*
|
|
118
|
+
* Usage: construct once per (session, transcript path); call `scan()` on
|
|
119
|
+
* each readiness edge. Each call reads only bytes appended since the last
|
|
120
|
+
* call and returns the current outstanding-work snapshot:
|
|
121
|
+
*
|
|
122
|
+
* { backgroundTasks: [{ toolUseId, kind, description, startedAt }],
|
|
123
|
+
* scheduledWakeup: { at, reason } | null }
|
|
124
|
+
*
|
|
125
|
+
* `scan()` NEVER throws. A missing transcript yields the empty snapshot
|
|
126
|
+
* (the file may simply not exist yet); any other failure logs at debug and
|
|
127
|
+
* yields the empty snapshot too.
|
|
128
|
+
*/
|
|
129
|
+
export class TranscriptTaskScanner {
|
|
130
|
+
/**
|
|
131
|
+
* @param {string} transcriptPath - absolute path to the session .jsonl
|
|
132
|
+
* @param {object} [logger] - logger with debug/warn (defaults to module log)
|
|
133
|
+
*/
|
|
134
|
+
constructor(transcriptPath, logger = log) {
|
|
135
|
+
this.path = transcriptPath
|
|
136
|
+
this._log = logger
|
|
137
|
+
this._reset()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
_reset() {
|
|
141
|
+
this._offset = 0
|
|
142
|
+
this._remainder = ''
|
|
143
|
+
// Set when a capped read skipped ahead — the first "line" of the new
|
|
144
|
+
// window is almost certainly a tail fragment and must not be parsed.
|
|
145
|
+
this._discardFirstPartialLine = false
|
|
146
|
+
/** @type {Map<string, {toolUseId:string,kind:string,description:string,startedAt:number}>} */
|
|
147
|
+
this._tasks = new Map()
|
|
148
|
+
/** @type {{at:number,reason:string,prompt:string}|null} */
|
|
149
|
+
this._wakeup = null
|
|
150
|
+
// Latest user/assistant entry timestamp seen (epoch ms) — used to decide
|
|
151
|
+
// whether a scheduled wakeup has already fired (activity after its time).
|
|
152
|
+
this._lastActivityTs = 0
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Read any new transcript bytes, fold them into the tracked state, and
|
|
157
|
+
* return the outstanding-work snapshot. Never throws.
|
|
158
|
+
* @returns {{backgroundTasks: Array<{toolUseId:string,kind:string,description:string,startedAt:number}>, scheduledWakeup: {at:number,reason:string}|null}}
|
|
159
|
+
*/
|
|
160
|
+
scan() {
|
|
161
|
+
try {
|
|
162
|
+
this._readNewBytes()
|
|
163
|
+
return this._snapshot()
|
|
164
|
+
} catch (err) {
|
|
165
|
+
// ENOENT is the common benign case (transcript not written yet) —
|
|
166
|
+
// still debug-logged, but state is preserved so a later scan picks
|
|
167
|
+
// up where it left off if the file appears.
|
|
168
|
+
this._log.debug?.(`transcript scan failed for ${this.path}: ${err.message} — degrading to empty snapshot`)
|
|
169
|
+
return { backgroundTasks: [], scheduledWakeup: null }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
_readNewBytes() {
|
|
174
|
+
const fd = openSync(this.path, 'r')
|
|
175
|
+
try {
|
|
176
|
+
const size = fstatSync(fd).size
|
|
177
|
+
if (size < this._offset) {
|
|
178
|
+
// Truncated / rotated — drop everything and re-read from the start.
|
|
179
|
+
this._log.debug?.(`transcript ${this.path} shrank (${size} < ${this._offset}) — resetting scanner`)
|
|
180
|
+
this._reset()
|
|
181
|
+
}
|
|
182
|
+
if (size === this._offset) return
|
|
183
|
+
let start = this._offset
|
|
184
|
+
if (size - start > MAX_SCAN_BYTES) {
|
|
185
|
+
// Bounded read: skip ahead and parse only the final window. The
|
|
186
|
+
// skipped prefix may contain launches we'll never pair — acceptable
|
|
187
|
+
// degradation for a pathological file; note it at debug level.
|
|
188
|
+
this._log.debug?.(`transcript ${this.path} unread tail ${size - start}B exceeds cap — scanning final ${MAX_SCAN_BYTES}B only`)
|
|
189
|
+
this._reset()
|
|
190
|
+
start = size - MAX_SCAN_BYTES
|
|
191
|
+
// Discard the (almost certainly partial) first line of the window.
|
|
192
|
+
this._discardFirstPartialLine = true
|
|
193
|
+
}
|
|
194
|
+
const buf = Buffer.alloc(size - start)
|
|
195
|
+
const bytesRead = readSync(fd, buf, 0, buf.length, start)
|
|
196
|
+
this._offset = start + bytesRead
|
|
197
|
+
let text = this._remainder + buf.toString('utf8', 0, bytesRead)
|
|
198
|
+
this._remainder = ''
|
|
199
|
+
const lines = text.split('\n')
|
|
200
|
+
// The final element is either '' (text ended with \n) or a partial
|
|
201
|
+
// line still being written — keep it for the next scan either way.
|
|
202
|
+
this._remainder = lines.pop() ?? ''
|
|
203
|
+
for (let line of lines) {
|
|
204
|
+
if (this._discardFirstPartialLine) {
|
|
205
|
+
this._discardFirstPartialLine = false
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
line = line.trim()
|
|
209
|
+
if (line) this._ingestLine(line)
|
|
210
|
+
}
|
|
211
|
+
} finally {
|
|
212
|
+
closeSync(fd)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Fold one JSONL line into the tracked state. Skips (never throws on)
|
|
218
|
+
* unparseable or unexpected shapes.
|
|
219
|
+
* @param {string} line
|
|
220
|
+
*/
|
|
221
|
+
_ingestLine(line) {
|
|
222
|
+
// Completion check works on the RAW line: the task-notification XML
|
|
223
|
+
// appears in several entry shapes (queue-operation `content` string,
|
|
224
|
+
// dequeued `user` message string content, attachment entries) and a
|
|
225
|
+
// raw-text match covers all of them without depending on any one shape.
|
|
226
|
+
if (line.includes('<task-notification>')) {
|
|
227
|
+
for (const m of line.matchAll(TOOL_USE_ID_TAG)) {
|
|
228
|
+
// JSONL string escaping never alters the id (alphanumeric), so the
|
|
229
|
+
// raw match is exact. Any status (completed/failed/…) means the
|
|
230
|
+
// task is no longer running.
|
|
231
|
+
this._tasks.delete(m[1])
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let entry
|
|
236
|
+
try {
|
|
237
|
+
entry = JSON.parse(line)
|
|
238
|
+
} catch {
|
|
239
|
+
return // mid-write torn line or non-JSON — skip silently
|
|
240
|
+
}
|
|
241
|
+
if (!entry || typeof entry !== 'object') return
|
|
242
|
+
|
|
243
|
+
const ts = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN
|
|
244
|
+
const entryTs = Number.isFinite(ts) ? ts : null
|
|
245
|
+
|
|
246
|
+
if (entry.type === 'user' || entry.type === 'assistant') {
|
|
247
|
+
if (entryTs !== null && entryTs > this._lastActivityTs) this._lastActivityTs = entryTs
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (entry.type === 'assistant') {
|
|
251
|
+
const blocks = entry?.message?.content
|
|
252
|
+
if (Array.isArray(blocks)) {
|
|
253
|
+
for (const block of blocks) {
|
|
254
|
+
if (!block || block.type !== 'tool_use' || typeof block.id !== 'string') continue
|
|
255
|
+
this._ingestToolUse(block, entryTs ?? Date.now())
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (entry.type === 'user' && this._wakeup) {
|
|
262
|
+
// Wakeup consumption path 1: the fired wakeup is delivered back to the
|
|
263
|
+
// agent as a user message carrying the scheduled prompt.
|
|
264
|
+
const content = entry?.message?.content
|
|
265
|
+
const text = typeof content === 'string'
|
|
266
|
+
? content
|
|
267
|
+
: Array.isArray(content)
|
|
268
|
+
? content.map((b) => (typeof b?.text === 'string' ? b.text : typeof b?.content === 'string' ? b.content : '')).join('\n')
|
|
269
|
+
: ''
|
|
270
|
+
// Match on a bounded prefix — prompts are long and an exact full-string
|
|
271
|
+
// match is brittle against harness-side trimming/wrapping.
|
|
272
|
+
const probe = this._wakeup.prompt.slice(0, 200)
|
|
273
|
+
if (probe && text.includes(probe)) this._wakeup = null
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* @param {{id:string,name?:string,input?:object}} block
|
|
279
|
+
* @param {number} startedAt epoch ms
|
|
280
|
+
*/
|
|
281
|
+
_ingestToolUse(block, startedAt) {
|
|
282
|
+
const name = typeof block.name === 'string' ? block.name : ''
|
|
283
|
+
const input = (block.input && typeof block.input === 'object') ? block.input : {}
|
|
284
|
+
|
|
285
|
+
if (name === 'ScheduleWakeup') {
|
|
286
|
+
const delaySeconds = Number(input.delaySeconds)
|
|
287
|
+
if (Number.isFinite(delaySeconds) && delaySeconds >= 0) {
|
|
288
|
+
// A newer ScheduleWakeup supersedes any earlier pending one — the
|
|
289
|
+
// harness keeps at most one timer armed.
|
|
290
|
+
this._wakeup = {
|
|
291
|
+
at: startedAt + delaySeconds * 1000,
|
|
292
|
+
reason: typeof input.reason === 'string' ? input.reason : '',
|
|
293
|
+
prompt: typeof input.prompt === 'string' ? input.prompt : '',
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
let kind = null
|
|
300
|
+
if (name === 'Monitor') {
|
|
301
|
+
kind = 'monitor'
|
|
302
|
+
} else if (input.run_in_background === true) {
|
|
303
|
+
if (name === 'Bash') kind = 'bash'
|
|
304
|
+
else if (name === 'Agent') kind = 'agent'
|
|
305
|
+
}
|
|
306
|
+
if (!kind) return
|
|
307
|
+
|
|
308
|
+
const description = typeof input.description === 'string' && input.description
|
|
309
|
+
? input.description
|
|
310
|
+
: typeof input.prompt === 'string'
|
|
311
|
+
? input.prompt.slice(0, PROMPT_DESCRIPTION_MAX)
|
|
312
|
+
: ''
|
|
313
|
+
this._tasks.set(block.id, { toolUseId: block.id, kind, description, startedAt })
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
_snapshot() {
|
|
317
|
+
let scheduledWakeup = null
|
|
318
|
+
if (this._wakeup) {
|
|
319
|
+
// Wakeup consumption path 2: ANY user/assistant activity after the
|
|
320
|
+
// scheduled time means the harness already re-invoked the agent (or
|
|
321
|
+
// the user did) — the wakeup is spent even if its prompt text never
|
|
322
|
+
// re-appears verbatim.
|
|
323
|
+
if (this._lastActivityTs > this._wakeup.at) {
|
|
324
|
+
this._wakeup = null
|
|
325
|
+
} else {
|
|
326
|
+
scheduledWakeup = { at: this._wakeup.at, reason: this._wakeup.reason }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
backgroundTasks: [...this._tasks.values()].map((t) => ({ ...t })),
|
|
331
|
+
scheduledWakeup,
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { EventEmitter } from 'events'
|
|
2
|
+
import { createLogger } from '../logger.js'
|
|
3
|
+
import { metrics } from '../metrics.js'
|
|
4
|
+
import { sleep } from '../utils/sleep.js'
|
|
5
|
+
|
|
6
|
+
const log = createLogger('tunnel')
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Base class for tunnel adapters.
|
|
10
|
+
*
|
|
11
|
+
* Provides shared recovery logic (backoff loop, event emission, URL change
|
|
12
|
+
* detection). Subclasses implement provider-specific tunnel spawning.
|
|
13
|
+
*
|
|
14
|
+
* Events: tunnel_lost, tunnel_recovering, tunnel_recovered,
|
|
15
|
+
* tunnel_url_changed, tunnel_failed
|
|
16
|
+
*/
|
|
17
|
+
export class BaseTunnelAdapter extends EventEmitter {
|
|
18
|
+
constructor({ port, mode = 'default', config = {} }) {
|
|
19
|
+
super()
|
|
20
|
+
this.port = port
|
|
21
|
+
this.mode = mode
|
|
22
|
+
this.config = config
|
|
23
|
+
this.process = null
|
|
24
|
+
this.url = null
|
|
25
|
+
this.intentionalShutdown = false
|
|
26
|
+
this.recoveryAttempt = 0
|
|
27
|
+
// Initial "fast" recovery schedule. After this many attempts we
|
|
28
|
+
// emit `tunnel_recovery_exhausted_round` so the consumer can surface
|
|
29
|
+
// a "having trouble" notification to the user — but we keep
|
|
30
|
+
// retrying indefinitely, never give up. Pre-audit the loop bailed
|
|
31
|
+
// out after maxRecoveryAttempts and the process sat port-bound
|
|
32
|
+
// but unreachable forever (Skeptic, 2026-04-11 audit). The
|
|
33
|
+
// supervisor restarts the child, not the tunnel.
|
|
34
|
+
this.maxRecoveryAttempts = 3
|
|
35
|
+
this.recoveryBackoffs = [3000, 6000, 12000]
|
|
36
|
+
// Cold-start retry budget. Distinct from recoveryBackoffs which
|
|
37
|
+
// governs mid-session recovery. Reuses recoveryBackoffs for the
|
|
38
|
+
// delay between attempts so a single knob tunes both phases.
|
|
39
|
+
this.maxStartAttempts = 3
|
|
40
|
+
// Unbounded long-tail retry: after the initial round, keep trying
|
|
41
|
+
// with exponential backoff capped at 60s. A tunnel outage is often
|
|
42
|
+
// transient (Cloudflare rollover, flaky wifi on the user's dev
|
|
43
|
+
// machine); giving up permanently is almost always worse than
|
|
44
|
+
// waiting one more minute.
|
|
45
|
+
this.maxRetryBackoffMs = 60_000
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Provider name — subclass must override */
|
|
49
|
+
static get name() {
|
|
50
|
+
throw new Error('Subclass must implement static get name()')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Provider capabilities — subclass must override.
|
|
55
|
+
* @returns {{ modes: string[], stableUrl: boolean, binaryName: string, setupRequired: boolean, installHint: string }}
|
|
56
|
+
*/
|
|
57
|
+
static get capabilities() {
|
|
58
|
+
throw new Error('Subclass must implement static get capabilities()')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Check if the tunnel binary is available.
|
|
63
|
+
* @returns {{ available: boolean, version: string|null, hint: string|null }}
|
|
64
|
+
*/
|
|
65
|
+
static checkBinary() {
|
|
66
|
+
return { available: false, version: null, hint: null }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Interactive setup for this tunnel provider (no-op by default).
|
|
71
|
+
* @param {object} _config
|
|
72
|
+
*/
|
|
73
|
+
static async setup(_config) {
|
|
74
|
+
// No-op — subclass can override for interactive setup
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Whether this adapter's URLs survive restarts */
|
|
78
|
+
get hasStableUrl() {
|
|
79
|
+
return false
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Start the tunnel and return { httpUrl, wsUrl } */
|
|
83
|
+
async start() {
|
|
84
|
+
this.intentionalShutdown = false
|
|
85
|
+
this.recoveryAttempt = 0
|
|
86
|
+
|
|
87
|
+
// Bounded retry on initial start to absorb transient provider hiccups
|
|
88
|
+
// (e.g. Cloudflare quick-tunnel API briefly returning 5xx). The
|
|
89
|
+
// post-success recovery loop in _handleUnexpectedExit() handles
|
|
90
|
+
// outages mid-session; this loop handles cold-start failures so a
|
|
91
|
+
// momentary upstream blip doesn't crash the server with an
|
|
92
|
+
// unhandled rejection.
|
|
93
|
+
let lastErr = null
|
|
94
|
+
for (let attempt = 1; attempt <= this.maxStartAttempts; attempt++) {
|
|
95
|
+
if (this.intentionalShutdown) throw lastErr ?? new Error('Tunnel start aborted')
|
|
96
|
+
try {
|
|
97
|
+
return await this._startTunnel()
|
|
98
|
+
} catch (err) {
|
|
99
|
+
lastErr = err
|
|
100
|
+
if (attempt < this.maxStartAttempts) {
|
|
101
|
+
const backoffMs = this.recoveryBackoffs[attempt - 1] ?? this.recoveryBackoffs[this.recoveryBackoffs.length - 1]
|
|
102
|
+
log.warn(
|
|
103
|
+
`Tunnel start attempt ${attempt}/${this.maxStartAttempts} failed: ${err.message}. Retrying in ${backoffMs}ms...`
|
|
104
|
+
)
|
|
105
|
+
// Cancellable sleep — stop() aborts this so a startup retry
|
|
106
|
+
// doesn't block shutdown for up to 12s. Mirrors the recovery
|
|
107
|
+
// loop pattern in _handleUnexpectedExit().
|
|
108
|
+
this._startAbort = new AbortController()
|
|
109
|
+
try {
|
|
110
|
+
await sleep(backoffMs, this._startAbort.signal)
|
|
111
|
+
} catch {
|
|
112
|
+
// Aborted by stop() — bail with the last real error so the
|
|
113
|
+
// caller still sees the underlying provider failure.
|
|
114
|
+
throw lastErr
|
|
115
|
+
} finally {
|
|
116
|
+
this._startAbort = null
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
throw lastErr
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Provider-specific tunnel start — subclass must implement.
|
|
126
|
+
* Must set this.process and this.url, and wire up the 'close' handler
|
|
127
|
+
* to call this._handleUnexpectedExit().
|
|
128
|
+
* @returns {Promise<{ httpUrl: string, wsUrl: string }>}
|
|
129
|
+
*/
|
|
130
|
+
async _startTunnel() {
|
|
131
|
+
throw new Error('Subclass must implement _startTunnel()')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Stop the tunnel */
|
|
135
|
+
async stop() {
|
|
136
|
+
this.intentionalShutdown = true
|
|
137
|
+
// Cancel any in-flight recovery sleep so the loop exits immediately
|
|
138
|
+
// instead of waiting up to 60s for the backoff timer to fire.
|
|
139
|
+
if (this._recoveryAbort) {
|
|
140
|
+
this._recoveryAbort.abort()
|
|
141
|
+
this._recoveryAbort = null
|
|
142
|
+
}
|
|
143
|
+
// Same for cold-start retry sleep so a stop() during startup
|
|
144
|
+
// doesn't block on the 3s/6s cold-start backoff.
|
|
145
|
+
if (this._startAbort) {
|
|
146
|
+
this._startAbort.abort()
|
|
147
|
+
this._startAbort = null
|
|
148
|
+
}
|
|
149
|
+
if (this.process) {
|
|
150
|
+
this.process.kill()
|
|
151
|
+
this.process = null
|
|
152
|
+
this.url = null
|
|
153
|
+
log.info('Tunnel closed')
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Compute the backoff delay for a given recovery attempt number.
|
|
159
|
+
* First `recoveryBackoffs.length` attempts use the fast schedule
|
|
160
|
+
* (3s/6s/12s). After that, exponential backoff from the last fast
|
|
161
|
+
* value, capped at `maxRetryBackoffMs`.
|
|
162
|
+
*
|
|
163
|
+
* Exported for tests.
|
|
164
|
+
*/
|
|
165
|
+
_backoffForAttempt(attempt1Indexed) {
|
|
166
|
+
if (attempt1Indexed <= this.recoveryBackoffs.length) {
|
|
167
|
+
return this.recoveryBackoffs[attempt1Indexed - 1]
|
|
168
|
+
}
|
|
169
|
+
// After the fast round, double each additional attempt starting
|
|
170
|
+
// from the last fast value, capped at maxRetryBackoffMs.
|
|
171
|
+
const extra = attempt1Indexed - this.recoveryBackoffs.length
|
|
172
|
+
const lastFast = this.recoveryBackoffs[this.recoveryBackoffs.length - 1]
|
|
173
|
+
const computed = lastFast * Math.pow(2, extra)
|
|
174
|
+
return Math.min(computed, this.maxRetryBackoffMs)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Handle unexpected process exit with unbounded recovery loop.
|
|
179
|
+
*
|
|
180
|
+
* Keeps retrying until either the tunnel comes back OR the consumer
|
|
181
|
+
* explicitly calls stop(). After the initial fast round
|
|
182
|
+
* (recoveryBackoffs.length attempts) we emit
|
|
183
|
+
* `tunnel_recovery_exhausted_round` so the consumer can surface a
|
|
184
|
+
* "having trouble" notification, but the loop continues with
|
|
185
|
+
* capped exponential backoff.
|
|
186
|
+
*
|
|
187
|
+
* The `tunnel_failed` event is retained for backward compatibility
|
|
188
|
+
* but is only emitted at the round boundary alongside
|
|
189
|
+
* `tunnel_recovery_exhausted_round`. Consumers that previously
|
|
190
|
+
* listened for it and did nothing (server-cli.js, supervisor.js)
|
|
191
|
+
* now see a round-exhausted signal instead of a hard giveup.
|
|
192
|
+
*
|
|
193
|
+
* 2026-04-11 audit (Skeptic, Task #2): pre-fix gave up after
|
|
194
|
+
* maxRecoveryAttempts and left the process port-bound but
|
|
195
|
+
* unreachable forever. Directly contradicted the "supervisor
|
|
196
|
+
* auto-restart on crash" claim in MEMORY.md — the supervisor
|
|
197
|
+
* restarts the child, not the tunnel.
|
|
198
|
+
*/
|
|
199
|
+
async _handleUnexpectedExit(code, signal) {
|
|
200
|
+
if (this.intentionalShutdown) {
|
|
201
|
+
log.info(`Process exited cleanly (code ${code})`)
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const exitReason = signal ? `signal ${signal}` : `code ${code}`
|
|
206
|
+
log.warn(`Process exited unexpectedly (${exitReason})`)
|
|
207
|
+
metrics.inc('tunnel.flaps')
|
|
208
|
+
this.emit('tunnel_lost', { code, signal })
|
|
209
|
+
|
|
210
|
+
const oldUrl = this.url
|
|
211
|
+
let roundExhaustedEmitted = false
|
|
212
|
+
|
|
213
|
+
while (!this.intentionalShutdown) {
|
|
214
|
+
this.recoveryAttempt++
|
|
215
|
+
const backoff = this._backoffForAttempt(this.recoveryAttempt)
|
|
216
|
+
|
|
217
|
+
log.info(
|
|
218
|
+
`Attempting recovery ${this.recoveryAttempt}${this.recoveryAttempt <= this.maxRecoveryAttempts ? `/${this.maxRecoveryAttempts}` : ' (long-tail)'} in ${backoff}ms...`
|
|
219
|
+
)
|
|
220
|
+
this.emit('tunnel_recovering', {
|
|
221
|
+
attempt: this.recoveryAttempt,
|
|
222
|
+
delayMs: backoff,
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
// Cancellable sleep — stop() aborts this so we don't hold the
|
|
226
|
+
// event loop alive for up to 60s during shutdown.
|
|
227
|
+
this._recoveryAbort = new AbortController()
|
|
228
|
+
try {
|
|
229
|
+
await sleep(backoff, this._recoveryAbort.signal)
|
|
230
|
+
} catch {
|
|
231
|
+
// Aborted by stop() — exit the loop
|
|
232
|
+
return
|
|
233
|
+
} finally {
|
|
234
|
+
this._recoveryAbort = null
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (this.intentionalShutdown) return
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
const { httpUrl, wsUrl } = await this._startTunnel()
|
|
241
|
+
log.info(`Recovery successful after ${this.recoveryAttempt} attempts`)
|
|
242
|
+
this.emit('tunnel_recovered', {
|
|
243
|
+
httpUrl,
|
|
244
|
+
wsUrl,
|
|
245
|
+
attempt: this.recoveryAttempt,
|
|
246
|
+
})
|
|
247
|
+
this.recoveryAttempt = 0
|
|
248
|
+
|
|
249
|
+
if (oldUrl && httpUrl !== oldUrl) {
|
|
250
|
+
log.info(`URL changed from ${oldUrl} to ${httpUrl}`)
|
|
251
|
+
this.emit('tunnel_url_changed', {
|
|
252
|
+
oldUrl,
|
|
253
|
+
newUrl: httpUrl,
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return
|
|
258
|
+
} catch (err) {
|
|
259
|
+
log.error(
|
|
260
|
+
`Recovery attempt ${this.recoveryAttempt} failed: ${err.message}`
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Once we've blown through the initial fast round, tell any
|
|
265
|
+
// consumer (server-cli, supervisor, push notifications) that
|
|
266
|
+
// we're now in the long-tail retry state. Emit ONCE per round
|
|
267
|
+
// so we don't spam notifications.
|
|
268
|
+
if (!roundExhaustedEmitted && this.recoveryAttempt >= this.maxRecoveryAttempts) {
|
|
269
|
+
roundExhaustedEmitted = true
|
|
270
|
+
log.warn(
|
|
271
|
+
`Tunnel recovery still failing after ${this.maxRecoveryAttempts} fast attempts; continuing with long-tail retries (capped at ${this.maxRetryBackoffMs}ms)`
|
|
272
|
+
)
|
|
273
|
+
this.emit('tunnel_recovery_exhausted_round', {
|
|
274
|
+
attempts: this.recoveryAttempt,
|
|
275
|
+
nextBackoffMs: this._backoffForAttempt(this.recoveryAttempt + 1),
|
|
276
|
+
lastExitCode: code,
|
|
277
|
+
lastSignal: signal,
|
|
278
|
+
})
|
|
279
|
+
// Back-compat shim: the pre-audit code emitted `tunnel_failed`
|
|
280
|
+
// here and stopped retrying. Consumers that registered a
|
|
281
|
+
// tunnel_failed listener got a single "giveup" signal. We
|
|
282
|
+
// keep the event name for backward compat (server-cli.js
|
|
283
|
+
// surfaces a broadcastError from it) but the loop no longer
|
|
284
|
+
// gives up — it just continues in the long-tail state.
|
|
285
|
+
this.emit('tunnel_failed', {
|
|
286
|
+
message: `Tunnel recovery still failing after ${this.maxRecoveryAttempts} attempts (retrying with long-tail backoff)`,
|
|
287
|
+
lastExitCode: code,
|
|
288
|
+
lastSignal: signal,
|
|
289
|
+
recoveryOngoing: true,
|
|
290
|
+
})
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|