@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,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #6764 — semantic session titles (pure logic).
|
|
3
|
+
*
|
|
4
|
+
* The sidebar's auto-generated session title has historically been the raw
|
|
5
|
+
* first user message truncated to ~40 chars at a word boundary. That is a
|
|
6
|
+
* copy of the prompt, not a summary — long or code-heavy first messages produce
|
|
7
|
+
* noisy, low-signal labels. This module produces a short, semantic title from a
|
|
8
|
+
* cheap one-shot model call instead, and ALWAYS falls back to the truncation
|
|
9
|
+
* behaviour when the feature is off, the call fails, or the model returns
|
|
10
|
+
* nothing usable.
|
|
11
|
+
*
|
|
12
|
+
* Everything here is PURE and dependency-free (no provider, no SDK import): the
|
|
13
|
+
* one-shot model runner is INJECTED (`runOneShot`) so the prompt/sanitise/gate
|
|
14
|
+
* logic is unit-testable without a live provider. Production wires
|
|
15
|
+
* `defaultRunOneShot` from summarize-session.js as the runner (reusing the same
|
|
16
|
+
* SDK one-shot + credential plumbing as the #5547 summarizer).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// Truncation-fallback cap — matches the historical `_autoLabelSession` length so
|
|
20
|
+
// the fallback label is byte-for-byte what the old behaviour produced.
|
|
21
|
+
export const TITLE_MAX_LEN = 40
|
|
22
|
+
// Cap for a model-generated title. A well-behaved Haiku reply is ~5-8 words; the
|
|
23
|
+
// cap only bites when the model ignores instructions and returns prose.
|
|
24
|
+
export const TITLE_MODEL_MAX_LEN = 60
|
|
25
|
+
// Default cheap model for the one-shot title call. The short alias resolves to
|
|
26
|
+
// the latest Haiku (see claude-model-catalog.js), so it survives model bumps.
|
|
27
|
+
export const DEFAULT_SEMANTIC_TITLE_MODEL = 'haiku'
|
|
28
|
+
// Default timeout (ms) for the one-shot title call. The call is fire-and-forget,
|
|
29
|
+
// so a stalled provider connection must never leave its promise pending forever:
|
|
30
|
+
// the closure retains the SessionManager, the first message, and the sessionId,
|
|
31
|
+
// so an un-timed-out call is an unbounded per-session leak for opted-in users, and
|
|
32
|
+
// the underlying one-shot subprocess is never torn down. The caller passes
|
|
33
|
+
// `AbortSignal.timeout(this)` as the `signal` so the call aborts (and the SDK
|
|
34
|
+
// tears the subprocess down) and `generateSessionTitle` fails open to the
|
|
35
|
+
// truncation label. Server-side only (Node's AbortSignal.timeout).
|
|
36
|
+
export const DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS = 15_000
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Word-boundary truncation used as the ALWAYS-available fallback label. Byte-for
|
|
40
|
+
* -byte compatible with the pre-#6764 `_autoLabelSession` truncation.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} text
|
|
43
|
+
* @param {number} [maxLen=TITLE_MAX_LEN]
|
|
44
|
+
* @returns {string} the label, or '' when the input has no usable text.
|
|
45
|
+
*/
|
|
46
|
+
export function truncateTitle(text, maxLen = TITLE_MAX_LEN) {
|
|
47
|
+
const trimmed = typeof text === 'string' ? text.trim() : ''
|
|
48
|
+
if (!trimmed) return ''
|
|
49
|
+
if (trimmed.length <= maxLen) return trimmed
|
|
50
|
+
const cut = trimmed.lastIndexOf(' ', maxLen)
|
|
51
|
+
return (cut > 10 ? trimmed.slice(0, cut) : trimmed.slice(0, maxLen)) + '...'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Clean a raw model reply into a usable one-line title. Models occasionally wrap
|
|
56
|
+
* the title in quotes, add a trailing period, prepend prose, or emit multiple
|
|
57
|
+
* lines — this strips all of that and returns '' when nothing usable remains
|
|
58
|
+
* (which the caller treats as "fall back to truncation").
|
|
59
|
+
*
|
|
60
|
+
* @param {string} raw
|
|
61
|
+
* @param {number} [maxLen=TITLE_MODEL_MAX_LEN]
|
|
62
|
+
* @returns {string} a cleaned title, or '' when unusable.
|
|
63
|
+
*/
|
|
64
|
+
export function sanitizeModelTitle(raw, maxLen = TITLE_MODEL_MAX_LEN) {
|
|
65
|
+
if (typeof raw !== 'string') return ''
|
|
66
|
+
// First non-empty line — models sometimes prepend a preamble or add newlines.
|
|
67
|
+
let line = ''
|
|
68
|
+
for (const l of raw.split('\n')) {
|
|
69
|
+
if (l.trim()) { line = l.trim(); break }
|
|
70
|
+
}
|
|
71
|
+
if (!line) return ''
|
|
72
|
+
// Strip surrounding quotes/backticks (straight or curly) the model wrapped it in.
|
|
73
|
+
line = line.replace(/^["'`“‘]+/, '').replace(/["'`”’]+$/, '').trim()
|
|
74
|
+
// Collapse internal whitespace runs to single spaces.
|
|
75
|
+
line = line.replace(/\s+/g, ' ')
|
|
76
|
+
// Drop a single trailing sentence period, but preserve a real ellipsis ('...').
|
|
77
|
+
line = line.replace(/(?<!\.)\.$/, '').trim()
|
|
78
|
+
if (!line) return ''
|
|
79
|
+
if (line.length <= maxLen) return line
|
|
80
|
+
const cut = line.lastIndexOf(' ', maxLen)
|
|
81
|
+
return (cut > 10 ? line.slice(0, cut) : line.slice(0, maxLen)) + '...'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Build the one-shot prompt asking for a short semantic title. The first user
|
|
86
|
+
* message is the primary signal; an optional first assistant response can be
|
|
87
|
+
* supplied for extra context. Both are length-capped so the call stays cheap
|
|
88
|
+
* even when the opening message is huge.
|
|
89
|
+
*
|
|
90
|
+
* @param {object} args
|
|
91
|
+
* @param {string} args.firstUserMessage
|
|
92
|
+
* @param {string} [args.firstAssistantResponse]
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
export function buildTitlePrompt({ firstUserMessage, firstAssistantResponse } = {}) {
|
|
96
|
+
const parts = [
|
|
97
|
+
'Generate a short, specific title (5 to 8 words maximum) that summarizes what this coding session is about, based on the first message below.',
|
|
98
|
+
'Rules:',
|
|
99
|
+
'- Output ONLY the title text: no surrounding quotes, no trailing punctuation, no preamble, no explanation.',
|
|
100
|
+
'- Be concrete — name the actual task, file, feature, or bug. Avoid generic titles like "Help request" or "Coding question".',
|
|
101
|
+
'- Never exceed 8 words.',
|
|
102
|
+
'',
|
|
103
|
+
'First user message:',
|
|
104
|
+
String(firstUserMessage == null ? '' : firstUserMessage).slice(0, 4000),
|
|
105
|
+
]
|
|
106
|
+
if (typeof firstAssistantResponse === 'string' && firstAssistantResponse.trim()) {
|
|
107
|
+
parts.push('', 'First assistant response (extra context):', firstAssistantResponse.slice(0, 2000))
|
|
108
|
+
}
|
|
109
|
+
parts.push('', 'Title:')
|
|
110
|
+
return parts.join('\n')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Produce a session title, gated + fail-open.
|
|
115
|
+
*
|
|
116
|
+
* Resolution order:
|
|
117
|
+
* 1. Feature off / no runner / no source text → truncation fallback.
|
|
118
|
+
* 2. Model call succeeds with usable text → the sanitised semantic title.
|
|
119
|
+
* 3. Model call errors, times out, or returns
|
|
120
|
+
* nothing usable → truncation fallback.
|
|
121
|
+
*
|
|
122
|
+
* The returned `source` lets the caller decide whether to broadcast an update
|
|
123
|
+
* (only a `'model'` title is worth replacing the already-applied truncation).
|
|
124
|
+
*
|
|
125
|
+
* @param {object} args
|
|
126
|
+
* @param {string} args.firstUserMessage
|
|
127
|
+
* @param {string} [args.firstAssistantResponse]
|
|
128
|
+
* @param {boolean} [args.enabled] - feature gate; false → truncation.
|
|
129
|
+
* @param {string} [args.model] - model id/alias for the one-shot.
|
|
130
|
+
* @param {string} [args.cwd] - working dir for the one-shot.
|
|
131
|
+
* @param {Function} [args.runOneShot] - injected model runner ({ prompt, model, cwd, signal }) => Promise<string>.
|
|
132
|
+
* @param {AbortSignal} [args.signal]
|
|
133
|
+
* @param {string} [args.fallback] - precomputed truncation label (else derived from firstUserMessage).
|
|
134
|
+
* @returns {Promise<{ title: string, source: 'model'|'truncation' }>}
|
|
135
|
+
*/
|
|
136
|
+
export async function generateSessionTitle({
|
|
137
|
+
firstUserMessage,
|
|
138
|
+
firstAssistantResponse,
|
|
139
|
+
enabled,
|
|
140
|
+
model,
|
|
141
|
+
cwd,
|
|
142
|
+
runOneShot,
|
|
143
|
+
signal,
|
|
144
|
+
fallback,
|
|
145
|
+
} = {}) {
|
|
146
|
+
const fallbackTitle = typeof fallback === 'string' && fallback
|
|
147
|
+
? fallback
|
|
148
|
+
: truncateTitle(firstUserMessage)
|
|
149
|
+
const truncated = { title: fallbackTitle, source: 'truncation' }
|
|
150
|
+
|
|
151
|
+
if (enabled !== true) return truncated
|
|
152
|
+
if (typeof runOneShot !== 'function') return truncated
|
|
153
|
+
|
|
154
|
+
const source = typeof firstUserMessage === 'string' ? firstUserMessage.trim() : ''
|
|
155
|
+
if (!source) return truncated
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
const prompt = buildTitlePrompt({ firstUserMessage: source, firstAssistantResponse })
|
|
159
|
+
const raw = await runOneShot({ prompt, model, cwd, signal })
|
|
160
|
+
const clean = sanitizeModelTitle(raw)
|
|
161
|
+
if (clean) return { title: clean, source: 'model' }
|
|
162
|
+
return truncated
|
|
163
|
+
} catch {
|
|
164
|
+
// Fail open — a failed/timed-out title call must never leave a session
|
|
165
|
+
// unnamed; the truncation label is always good enough.
|
|
166
|
+
return truncated
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -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'
|
|
@@ -26,57 +27,90 @@ const STORE_FILE = 'session-tokens.json'
|
|
|
26
27
|
* @param {object} opts
|
|
27
28
|
* @param {string} opts.dir - directory to hold the store (e.g. `~/.chroxy`).
|
|
28
29
|
* @param {object} [opts.keychain] - keychain module (injectable for tests).
|
|
29
|
-
* @returns {{
|
|
30
|
+
* @returns {{
|
|
31
|
+
* load: () => Array<[string, object]>,
|
|
32
|
+
* loadResult: () => { status: 'absent'|'ok'|'unreadable', entries: Array<[string, object]> },
|
|
33
|
+
* exists: () => boolean,
|
|
34
|
+
* save: (entries: Array<[string, object]>, opts?: { durable?: boolean }) => boolean,
|
|
35
|
+
* }}
|
|
30
36
|
* `entries` is the `[token, meta]` pair list from the PairingManager map.
|
|
31
37
|
*/
|
|
32
38
|
export function createSessionTokenStore({ dir, keychain = realKeychain } = {}) {
|
|
33
39
|
const file = join(dir, STORE_FILE)
|
|
34
40
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
41
|
+
// Read the store, distinguishing the THREE outcomes an interactive caller must
|
|
42
|
+
// not conflate (#6599): 'absent' (no file), 'ok' (read + decoded), 'unreadable'
|
|
43
|
+
// (file present but wrong perms / no keychain key / corrupt / undecryptable).
|
|
44
|
+
// The daemon's `load()` fail-softs all of these to `[]` (a re-pair is harmless);
|
|
45
|
+
// the tokens CLI uses `loadResult()` so it never overwrites a store it couldn't
|
|
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.
|
|
53
|
+
function read() {
|
|
54
|
+
try {
|
|
55
|
+
// Enforce owner-only 0600 (POSIX) — same boundary as the credential store.
|
|
56
|
+
// A world/group-readable token file is refused rather than trusted.
|
|
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`)
|
|
47
64
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return Array.isArray(data?.entries) ? data.entries : []
|
|
65
|
+
return { status: 'unreadable', entries: [] }
|
|
66
|
+
}
|
|
67
|
+
const parsed = JSON.parse(result.content)
|
|
68
|
+
if (isEncryptedEnvelope(parsed)) {
|
|
69
|
+
const key = getOrCreateMasterKey(keychain)
|
|
70
|
+
if (!key) {
|
|
71
|
+
log.warn('session-token store is encrypted but no keychain key is available — devices will re-pair')
|
|
72
|
+
return { status: 'unreadable', entries: [] }
|
|
57
73
|
}
|
|
58
|
-
|
|
59
|
-
return Array.isArray(
|
|
60
|
-
} catch (err) {
|
|
61
|
-
// A missing / corrupt / undecryptable store is not fatal: the worst case
|
|
62
|
-
// is that devices re-pair (the pre-#6598 behaviour). Never throw into the
|
|
63
|
-
// auth path.
|
|
64
|
-
log.warn(`could not load persisted session tokens (${err.message}) — devices will re-pair`)
|
|
65
|
-
return []
|
|
74
|
+
const data = decryptEnvelope(parsed, key)
|
|
75
|
+
return { status: 'ok', entries: Array.isArray(data?.entries) ? data.entries : [] }
|
|
66
76
|
}
|
|
67
|
-
|
|
77
|
+
// Plaintext fallback (no-keychain host).
|
|
78
|
+
return { status: 'ok', entries: Array.isArray(parsed?.entries) ? parsed.entries : [] }
|
|
79
|
+
} catch (err) {
|
|
80
|
+
// A missing / corrupt / undecryptable store is not fatal for the daemon: the
|
|
81
|
+
// worst case is that devices re-pair (the pre-#6598 behaviour). Never throw
|
|
82
|
+
// into the auth path. Report 'unreadable' so an interactive caller can tell
|
|
83
|
+
// this apart from a genuinely-empty store.
|
|
84
|
+
log.warn(`could not load persisted session tokens (${err.message}) — devices will re-pair`)
|
|
85
|
+
return { status: 'unreadable', entries: [] }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
load: () => read().entries,
|
|
91
|
+
loadResult: read,
|
|
92
|
+
exists: () => existsSync(file),
|
|
68
93
|
|
|
69
|
-
|
|
94
|
+
// `durable` (#6914): fsync the store to disk before returning success. The
|
|
95
|
+
// fail-CLOSED REVOKE path (`_persistSessionTokensSnapshot`) sets it so a
|
|
96
|
+
// power loss within the OS writeback window can't resurrect a revoked token
|
|
97
|
+
// after a reported-successful revoke. The fail-SAFE mint / slide / sweep
|
|
98
|
+
// path leaves it off (default) — a lost page-cache write there merely forces
|
|
99
|
+
// a harmless re-pair, and an fsync per token issuance is not worth the I/O.
|
|
100
|
+
save(entries, { durable = false } = {}) {
|
|
70
101
|
try {
|
|
71
102
|
mkdirSync(dir, { recursive: true })
|
|
72
103
|
const payload = { v: 1, entries }
|
|
73
104
|
const key = getOrCreateMasterKey(keychain)
|
|
74
105
|
const body = key ? JSON.stringify(encryptJson(payload, key)) : JSON.stringify(payload)
|
|
75
|
-
writeFileRestricted(file, body)
|
|
106
|
+
writeFileRestricted(file, body, { durable })
|
|
107
|
+
return true
|
|
76
108
|
} catch (err) {
|
|
77
|
-
// Persistence is best-effort
|
|
78
|
-
// require re-pairing
|
|
109
|
+
// Persistence is best-effort for the daemon (a failed write just means a
|
|
110
|
+
// restart may require re-pairing), so we don't throw; but RETURN false so
|
|
111
|
+
// an interactive caller can report the failure instead of a false success.
|
|
79
112
|
log.warn(`could not persist session tokens (${err.message})`)
|
|
113
|
+
return false
|
|
80
114
|
}
|
|
81
115
|
},
|
|
82
116
|
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live-session wakeup gate — the ONE place that decides whether a daemon-side
|
|
3
|
+
* event may type a line into a running session.
|
|
4
|
+
*
|
|
5
|
+
* Two callers want this today: the mailbox live-interrupt (`mailbox-route.js`,
|
|
6
|
+
* "you have unread mail") and the CI-completion watcher (`session-ci-watcher.js`,
|
|
7
|
+
* "CI finished on your PR"). They shared nothing but a copied four-line gate,
|
|
8
|
+
* and that gate is security-load-bearing — so it lives here once instead of
|
|
9
|
+
* twice. The rules it enforces, and why each one exists:
|
|
10
|
+
*
|
|
11
|
+
* 1. **claude-tui only, via the positive discriminator.** `#5984` (epic #5982):
|
|
12
|
+
* gate on `constructor.isClaudeTui === true`, NOT on
|
|
13
|
+
* `typeof session.writeTerminalInput` — a user-shell session (#5983) also
|
|
14
|
+
* exposes `writeTerminalInput`, and duck-typing here would let a weaker
|
|
15
|
+
* credential inject an EXECUTED line into a root shell (swarm-audit finding
|
|
16
|
+
* C2). Strict `!== true` rather than truthiness: a buggy override returning
|
|
17
|
+
* a truthy non-boolean must not read as "tui".
|
|
18
|
+
* 2. **Idle only.** `isRunning` is true mid-turn and while background shells are
|
|
19
|
+
* alive; typing then corrupts an in-flight turn's input.
|
|
20
|
+
* 3. **One line, no control characters but the trailing return.** The caller's
|
|
21
|
+
* text is scrubbed here rather than at each call site, because the interesting
|
|
22
|
+
* inputs (a GitHub PR title, a mailbox subject) are strings this daemon did
|
|
23
|
+
* not author.
|
|
24
|
+
*
|
|
25
|
+
* The session lookup deliberately stays with the caller: "which session" is a
|
|
26
|
+
* routing question (a mailbox id, a session id) and the two callers answer it
|
|
27
|
+
* differently. This module only answers "may I, and did it land".
|
|
28
|
+
*
|
|
29
|
+
* ## The second route: the provider-neutral turn-input seam (#8301)
|
|
30
|
+
*
|
|
31
|
+
* PTY typing reaches claude-tui only, so a claude-sdk session (the default
|
|
32
|
+
* provider) never learned that CI finished (`wake: not-tui`). A caller that
|
|
33
|
+
* opts in with `{ turnInput: true }` also reaches every provider whose
|
|
34
|
+
* `sendMessage` is a real turn-input seam: it dispatches when idle, QUEUES when
|
|
35
|
+
* busy (`enqueueOutgoingMessage`, flushed at turn end, cleared by `interrupt()`)
|
|
36
|
+
* and reports admission through `onInputAdmission`. Those providers declare it
|
|
37
|
+
* with the static capability `daemonTurnInput: true`.
|
|
38
|
+
*
|
|
39
|
+
* - **Positive discriminator, strict `=== true`** — the same reasoning as rule 1:
|
|
40
|
+
* a duck-typed `typeof session.sendMessage === 'function'` is true of EVERY
|
|
41
|
+
* session, the user shell included, and a user shell executes the lines it is
|
|
42
|
+
* given. `UserShellSession` must never declare the flag; `isUserShell` is
|
|
43
|
+
* refused here as well, so one wrong flag cannot reach it.
|
|
44
|
+
* - **Opt-in per caller.** The mailbox wake does NOT pass `turnInput` — #7437
|
|
45
|
+
* owns that caller and its PTY-only gate stays as it is. A claude-tui session
|
|
46
|
+
* keeps the PTY route whatever the caller passes.
|
|
47
|
+
* - **Busy is fine here.** The queue absorbs it; `isRunning` is not consulted
|
|
48
|
+
* (a background shell does not corrupt SDK input the way it corrupts PTY
|
|
49
|
+
* typing).
|
|
50
|
+
* - **The outcome is the provider's admission, not our hope.** `accepted` →
|
|
51
|
+
* `injected`, `queued` → `queued`, `rejected` → `rejected`. Admission may land
|
|
52
|
+
* after `sendMessage` returns, in which case the synchronous result is
|
|
53
|
+
* `pending` and `onAdmission` is the one place the final outcome is delivered.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
import { createLogger } from './logger.js'
|
|
57
|
+
|
|
58
|
+
const log = createLogger('session-wake')
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Outcome of a wake attempt.
|
|
62
|
+
* @typedef {'injected'|'busy'|'not-tui'|'no-session'|'pty-dead'|'empty-text'|'queued'|'rejected'|'pending'|'error'} WakeOutcome
|
|
63
|
+
* `queued`, `rejected`, `pending` and `error` belong to the turn-input route
|
|
64
|
+
* (#8301) only; the PTY route never returns them.
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/** Cap on injected text — one prompt line, not a payload. */
|
|
68
|
+
export const MAX_WAKE_TEXT_CHARS = 500
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Scrub a candidate wakeup line: collapse every control character (including
|
|
72
|
+
* the CR/LF that would submit early, or split one line into several) to a
|
|
73
|
+
* space, squeeze runs of whitespace, trim, and cap the length.
|
|
74
|
+
*
|
|
75
|
+
* Returns '' when nothing usable survives — the caller then gets `empty-text`
|
|
76
|
+
* rather than a bare carriage return typed into a live prompt.
|
|
77
|
+
*
|
|
78
|
+
* @param {unknown} text
|
|
79
|
+
* @returns {string}
|
|
80
|
+
*/
|
|
81
|
+
export function sanitizeWakeText(text) {
|
|
82
|
+
if (typeof text !== 'string') return ''
|
|
83
|
+
const flattened = text.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim()
|
|
84
|
+
return flattened.length > MAX_WAKE_TEXT_CHARS ? flattened.slice(0, MAX_WAKE_TEXT_CHARS) : flattened
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Does this session class declare the provider-neutral turn-input seam?
|
|
89
|
+
* Strict `=== true` on the CLASS, never the instance and never truthiness. A
|
|
90
|
+
* throwing `capabilities` getter reads as "no" — an unreadable declaration is
|
|
91
|
+
* not a declaration.
|
|
92
|
+
*
|
|
93
|
+
* @param {object} session
|
|
94
|
+
* @returns {boolean}
|
|
95
|
+
*/
|
|
96
|
+
export function supportsDaemonTurnInput(session) {
|
|
97
|
+
try {
|
|
98
|
+
const Klass = session?.constructor
|
|
99
|
+
if (Klass?.isUserShell === true) return false
|
|
100
|
+
return Klass?.capabilities?.daemonTurnInput === true
|
|
101
|
+
} catch {
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Map a provider admission report to a wake outcome, or null when the report is
|
|
108
|
+
* not final (an unrecognised shape must not be read as success).
|
|
109
|
+
*/
|
|
110
|
+
function outcomeForAdmission(admission) {
|
|
111
|
+
if (!admission || typeof admission !== 'object') return null
|
|
112
|
+
const { status, delivery } = admission
|
|
113
|
+
if (status === 'accepted' && delivery === 'dispatch_started') return 'injected'
|
|
114
|
+
if (status === 'queued' && delivery === 'queued') return 'queued'
|
|
115
|
+
if (status === 'rejected' && delivery === 'not_dispatched') return 'rejected'
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The turn-input route (#8301). See the module header.
|
|
121
|
+
*
|
|
122
|
+
* @param {object} session
|
|
123
|
+
* @param {string} text
|
|
124
|
+
* @param {{ clientMessageId?: string, admitAtFlush?: () => boolean, onAdmission?: (result: {outcome: 'injected'|'queued'|'rejected', line: string, clientMessageId: string|undefined, admission: object}) => void }} opts
|
|
125
|
+
* @returns {WakeOutcome}
|
|
126
|
+
*/
|
|
127
|
+
function wakeViaTurnInput(session, text, { clientMessageId, admitAtFlush, onAdmission } = {}) {
|
|
128
|
+
if (!supportsDaemonTurnInput(session)) return 'not-tui'
|
|
129
|
+
if (typeof session.sendMessage !== 'function') return 'not-tui'
|
|
130
|
+
const line = sanitizeWakeText(text)
|
|
131
|
+
if (line.length === 0) return 'empty-text'
|
|
132
|
+
|
|
133
|
+
let outcome = null
|
|
134
|
+
let dispatchNotified = false
|
|
135
|
+
const notify = (mapped, admission) => {
|
|
136
|
+
if (typeof onAdmission !== 'function') return
|
|
137
|
+
try {
|
|
138
|
+
onAdmission({ outcome: mapped, line, clientMessageId, admission })
|
|
139
|
+
} catch (err) {
|
|
140
|
+
log.warn(`wake onAdmission callback threw: ${err?.message || err}`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Two notifications at most, and the distinction is the point.
|
|
144
|
+
//
|
|
145
|
+
// The FIRST final report decides `outcome` (what `wakeSession` returns and what
|
|
146
|
+
// the caller logs): `queued` means "it landed in the provider's queue", and a
|
|
147
|
+
// later report never rewrites that.
|
|
148
|
+
//
|
|
149
|
+
// But `queued` is not DISPATCHED. A queued item is re-dispatched at turn end
|
|
150
|
+
// with the SAME sendOptions, so the provider reports admission a second time,
|
|
151
|
+
// `accepted`, if and only if the item actually went out — it may instead be
|
|
152
|
+
// cancelled at flush (`admitAtFlush` refused, an interrupt cleared the queue)
|
|
153
|
+
// and never report again. That second report is the moment the line became a
|
|
154
|
+
// turn, so it is delivered ONCE more, as `injected`, and a caller that records
|
|
155
|
+
// "this turn happened" (history, the `user_input` broadcast) should key off
|
|
156
|
+
// `injected`, never off `queued`.
|
|
157
|
+
const onInputAdmission = (admission) => {
|
|
158
|
+
const mapped = outcomeForAdmission(admission)
|
|
159
|
+
if (mapped === null) return
|
|
160
|
+
if (outcome === null) {
|
|
161
|
+
outcome = mapped
|
|
162
|
+
if (mapped === 'injected') dispatchNotified = true
|
|
163
|
+
notify(mapped, admission)
|
|
164
|
+
return
|
|
165
|
+
}
|
|
166
|
+
if (outcome === 'queued' && !dispatchNotified && mapped !== 'queued') {
|
|
167
|
+
dispatchNotified = true
|
|
168
|
+
notify(mapped, admission)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let result
|
|
173
|
+
try {
|
|
174
|
+
result = session.sendMessage(line, [], {
|
|
175
|
+
...(typeof clientMessageId === 'string' ? { clientMessageId } : {}),
|
|
176
|
+
// A wake that QUEUES behind a running turn is dispatched later, by the
|
|
177
|
+
// provider's queue, with no caller on the stack. The caller's flush-time
|
|
178
|
+
// admission check rides with the item so the queue can re-ask then.
|
|
179
|
+
...(typeof admitAtFlush === 'function' ? { admitAtFlush } : {}),
|
|
180
|
+
onInputAdmission,
|
|
181
|
+
})
|
|
182
|
+
} catch (err) {
|
|
183
|
+
log.warn(`wake sendMessage threw: ${err?.message || err}`)
|
|
184
|
+
return outcome ?? 'error'
|
|
185
|
+
}
|
|
186
|
+
// #5313: a rejecting promise must never escape to process-level
|
|
187
|
+
// unhandledRejection (which exits the daemon over one session's fault).
|
|
188
|
+
if (result && typeof result.catch === 'function') {
|
|
189
|
+
result.catch((err) => {
|
|
190
|
+
log.error(`wake sendMessage rejected: ${err?.message || err}`)
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
return outcome ?? 'pending'
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Type `text` into a live session's prompt when it is safe to do so.
|
|
198
|
+
*
|
|
199
|
+
* Never throws: a session whose `writeTerminalInput` throws reports `pty-dead`
|
|
200
|
+
* like a write that returns false, because both mean "the line did not land"
|
|
201
|
+
* and neither is the caller's problem to recover from.
|
|
202
|
+
*
|
|
203
|
+
* @param {object|null|undefined} session - the live provider session object.
|
|
204
|
+
* @param {string} text - the line to type. A trailing return is appended here;
|
|
205
|
+
* callers must NOT include one (it would be scrubbed anyway).
|
|
206
|
+
* @param {object} [opts]
|
|
207
|
+
* @param {boolean} [opts.turnInput] - also reach non-tui providers through the
|
|
208
|
+
* `sendMessage`/queue seam (#8301). Absent/false = the claude-tui-only gate,
|
|
209
|
+
* unchanged. Strict `=== true`.
|
|
210
|
+
* @param {string} [opts.clientMessageId] - turn-input route: the stable daemon
|
|
211
|
+
* id the provider's queue mirror and history carry.
|
|
212
|
+
* @param {() => boolean} [opts.admitAtFlush] - turn-input route: re-asked by the
|
|
213
|
+
* provider's queue (BaseSession `dequeueNextOutgoing`) when a QUEUED wake is
|
|
214
|
+
* about to be dispatched; anything but `true` (or a throw) drops it.
|
|
215
|
+
* @param {Function} [opts.onAdmission] - turn-input route: called once with the
|
|
216
|
+
* final admission outcome (see `wakeViaTurnInput`).
|
|
217
|
+
* @returns {WakeOutcome}
|
|
218
|
+
*/
|
|
219
|
+
export function wakeSession(session, text, opts = {}) {
|
|
220
|
+
if (!session) return 'no-session'
|
|
221
|
+
if (session.constructor?.isClaudeTui !== true) {
|
|
222
|
+
if (opts?.turnInput === true) return wakeViaTurnInput(session, text, opts)
|
|
223
|
+
return 'not-tui'
|
|
224
|
+
}
|
|
225
|
+
// Defence in depth: isClaudeTui === true implies writeTerminalInput exists
|
|
226
|
+
// today (only ClaudeTuiSession sets the marker AND defines the method), so
|
|
227
|
+
// this is unreachable in practice — but it guards a future class that sets
|
|
228
|
+
// the marker without the method rather than throwing on the write below.
|
|
229
|
+
if (typeof session.writeTerminalInput !== 'function') return 'not-tui'
|
|
230
|
+
if (session.isRunning) return 'busy'
|
|
231
|
+
const line = sanitizeWakeText(text)
|
|
232
|
+
if (line.length === 0) return 'empty-text'
|
|
233
|
+
let ok
|
|
234
|
+
try {
|
|
235
|
+
ok = session.writeTerminalInput(`${line}\r`)
|
|
236
|
+
} catch {
|
|
237
|
+
return 'pty-dead'
|
|
238
|
+
}
|
|
239
|
+
return ok ? 'injected' : 'pty-dead'
|
|
240
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { homedir } from 'os'
|
|
2
1
|
import { join } from 'path'
|
|
3
2
|
import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs'
|
|
4
3
|
import { writeFileRestricted } from './platform.js'
|
|
4
|
+
import { configDir } from './config-dir.js'
|
|
5
5
|
|
|
6
6
|
// #6277 — discovery for the host-local user-shell approval listener.
|
|
7
7
|
//
|
|
@@ -17,7 +17,7 @@ import { writeFileRestricted } from './platform.js'
|
|
|
17
17
|
// connection.json for the primary token.
|
|
18
18
|
|
|
19
19
|
function getConfigDir() {
|
|
20
|
-
return
|
|
20
|
+
return configDir()
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export function getShellApprovalInfoPath() {
|
|
@@ -69,9 +69,10 @@ export class ShellApprovalStore {
|
|
|
69
69
|
* @param {string} [req.tokenClass] - for the post-create audit record
|
|
70
70
|
* @param {string} [req.deviceName] - for the audit + `shell list`
|
|
71
71
|
* @param {string} [req.hint] - human-facing label surfaced to the client/log
|
|
72
|
+
* @param {string|null} [req.requestId] - the held `create_session`'s client correlation id (#7977), echoed on the post-approval `session_switched` and on a denial `session_error`
|
|
72
73
|
* @returns {{ approvalId: string, expiresAt: number }}
|
|
73
74
|
*/
|
|
74
|
-
createPendingApproval({ clientId, createSessionOptions, tokenClass = null, deviceName = null, hint = null } = {}) {
|
|
75
|
+
createPendingApproval({ clientId, createSessionOptions, tokenClass = null, deviceName = null, hint = null, requestId = null } = {}) {
|
|
75
76
|
this._sweepExpired()
|
|
76
77
|
// FIFO-evict the oldest while at/over the cap (a fresh request shouldn't be
|
|
77
78
|
// refused; the oldest held approval is the most likely to be abandoned).
|
|
@@ -96,6 +97,7 @@ export class ShellApprovalStore {
|
|
|
96
97
|
tokenClass,
|
|
97
98
|
deviceName,
|
|
98
99
|
hint,
|
|
100
|
+
requestId,
|
|
99
101
|
requestedAt,
|
|
100
102
|
expiresAt,
|
|
101
103
|
})
|
package/src/skills-loader.js
CHANGED
|
@@ -67,10 +67,13 @@ import { dirname, join, relative, resolve, sep } from 'path'
|
|
|
67
67
|
import { homedir } from 'os'
|
|
68
68
|
import { createLogger } from './logger.js'
|
|
69
69
|
import { getErrorMessage } from './utils/error-message.js'
|
|
70
|
+
import { configPath } from './config-dir.js'
|
|
70
71
|
|
|
71
72
|
const log = createLogger('skills-loader')
|
|
72
73
|
|
|
73
|
-
export
|
|
74
|
+
export function defaultSkillsDir() {
|
|
75
|
+
return configPath('skills')
|
|
76
|
+
}
|
|
74
77
|
|
|
75
78
|
// Cap walk-up iterations as a safety belt; real repos are nowhere near this deep.
|
|
76
79
|
const REPO_DISCOVERY_MAX_DEPTH = 100
|
|
@@ -1448,7 +1451,7 @@ export function findRepoSkillsDir(cwd) {
|
|
|
1448
1451
|
if (statSync(candidate).isDirectory()) {
|
|
1449
1452
|
// Defensive: the user's global skills dir is never a repo overlay.
|
|
1450
1453
|
// Even if we somehow walk up to it, refuse to claim it as repo-scoped.
|
|
1451
|
-
if (_sameAbsolutePath(candidate,
|
|
1454
|
+
if (_sameAbsolutePath(candidate, defaultSkillsDir())) return null
|
|
1452
1455
|
return candidate
|
|
1453
1456
|
}
|
|
1454
1457
|
} catch {
|
|
@@ -1772,7 +1775,7 @@ export const SKILLS_PROMPT_HEADER = [
|
|
|
1772
1775
|
*
|
|
1773
1776
|
* @param {object} args
|
|
1774
1777
|
* @param {string} args.skillName - The skill's display name (no extension).
|
|
1775
|
-
* @param {string} [args.globalDir] - Defaults to
|
|
1778
|
+
* @param {string} [args.globalDir] - Defaults to defaultSkillsDir().
|
|
1776
1779
|
* @param {string|null} [args.repoDir] - Optional repo overlay dir.
|
|
1777
1780
|
* @param {string[]} [args.allowedExtensions] - Defaults to DEFAULT_ALLOWED_EXTENSIONS.
|
|
1778
1781
|
* @returns {{ realPath: string, body: string } | null}
|
|
@@ -1793,7 +1796,7 @@ export function findSkillForRetrust({
|
|
|
1793
1796
|
if (repoDir) dirs.push({ dir: repoDir, source: 'repo' })
|
|
1794
1797
|
if (globalDir) dirs.push({ dir: globalDir, source: 'global' })
|
|
1795
1798
|
if (dirs.length === 0) {
|
|
1796
|
-
dirs.push({ dir:
|
|
1799
|
+
dirs.push({ dir: defaultSkillsDir(), source: 'global' })
|
|
1797
1800
|
}
|
|
1798
1801
|
|
|
1799
1802
|
for (const { dir } of dirs) {
|
package/src/skills-manager.js
CHANGED
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
formatSkillsForPrompt,
|
|
25
25
|
groupSkillsByInjectionMode,
|
|
26
26
|
findRepoSkillsDir,
|
|
27
|
-
|
|
27
|
+
defaultSkillsDir,
|
|
28
28
|
} from './skills-loader.js'
|
|
29
29
|
import { SkillsTrustStore } from './skills-trust.js'
|
|
30
30
|
|
|
@@ -90,7 +90,7 @@ export class SkillsManager {
|
|
|
90
90
|
|
|
91
91
|
// Cache the immutable load-time inputs so the runtime toggle path (#3209)
|
|
92
92
|
// can rebuild layerOpts without re-parsing constructor args.
|
|
93
|
-
this._skillsDir = skillsDir ||
|
|
93
|
+
this._skillsDir = skillsDir || defaultSkillsDir()
|
|
94
94
|
this._repoSkillsDir = repoSkillsDir !== undefined
|
|
95
95
|
? repoSkillsDir
|
|
96
96
|
: findRepoSkillsDir(cwd)
|