@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.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,682 @@
1
+ /**
2
+ * Skills settings handlers — split out of settings-handlers.js (audit P2-4,
3
+ * pure move). list_skills + skill activate/deactivate + skill-trust accept/
4
+ * grant. Skill trust whitelists host-executable code, so trust mutations
5
+ * require host-level authority (a pairing-bound token is rejected);
6
+ * activate/deactivate are not gated (no more capability than ordinary input).
7
+ */
8
+ import {
9
+ resolveSession,
10
+ resolveSessionOrError,
11
+ requireSessionMethod,
12
+ sendError,
13
+ sendSessionError,
14
+ } from '../handler-utils.js'
15
+ import {
16
+ loadActiveSkillsLayered,
17
+ findRepoSkillsDir,
18
+ findSkillForRetrust,
19
+ DEFAULT_SKILLS_DIR,
20
+ _isCommunityNamespace,
21
+ } from '../skills-loader.js'
22
+ import { realpathSync, readdirSync, statSync } from 'fs'
23
+ import { loggerForSession } from '../logger.js'
24
+
25
+ // #3250: strict ISO-8601 datetime gate matching the shape z.string().datetime()
26
+ // accepts. Used by handleListSkills to drop malformed timestamps from a
27
+ // hand-edited trust ledger before forwarding — see comment in handleListSkills
28
+ // for context. Date.parse is intentionally NOT used here: it accepts forms
29
+ // like "2026-03-18 10:00:00" (space separator) that the wire schema rejects.
30
+ const ISO_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/
31
+ function _isIsoDatetime(s) {
32
+ return typeof s === 'string' && ISO_DATETIME_RE.test(s)
33
+ }
34
+ /**
35
+ * Reject skill-trust mutations from a bound (pairing-issued) client. A skill is
36
+ * EXECUTABLE CODE that runs on the host; granting trust (`skill_trust_grant`) or
37
+ * re-accepting changed content (`skill_trust_accept`) whitelists that code to
38
+ * run, which is a host-level integrity decision — the same class of escalation
39
+ * as flipping auto permission mode or writing provider credentials. A bound
40
+ * (share-a-session) token is scoped to USE the session, not to extend what code
41
+ * the host will execute, so these require host-level authority (unbound client).
42
+ *
43
+ * Note: skill_activate / skill_deactivate are deliberately NOT gated here — they
44
+ * only toggle ALREADY-installed, already-trusted local skills into the session,
45
+ * which is no more capability than the input a bound client can already send.
46
+ *
47
+ * Returns true and sends the rejection if the client is bound (caller must
48
+ * early-return); false to proceed. See docs/security/bearer-token-authority.md.
49
+ */
50
+ function rejectSkillTrustIfBound(ws, client, msg, ctx) {
51
+ if (!client?.boundSessionId) return false
52
+ loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to modify skill trust (${msg?.type}) — rejected`)
53
+ sendError(ws, msg?.requestId, 'SKILL_TRUST_FORBIDDEN_BOUND_CLIENT',
54
+ 'Pairing-issued session tokens cannot grant or accept skill trust (a skill is host-executable code). Use the primary API token from a device with physical access to this machine.', undefined, ctx)
55
+ return true
56
+ }
57
+ /**
58
+ * Return the active skills the running session is using.
59
+ *
60
+ * v1 (#2957) sourced skills only from `~/.chroxy/skills/`. v2 (#3067) layers a
61
+ * repo-scoped overlay on top: walk up from the active session's cwd looking
62
+ * for `.chroxy/skills/`, and let any repo file override a global file with the
63
+ * same name. The payload includes a `source` ("global" or "repo") per skill so
64
+ * clients can show which tier each one came from.
65
+ *
66
+ * The session loaded skills at construction with whatever `globalDir`/`repoDir`
67
+ * it was given (including test overrides), so when an active session resolves
68
+ * we mirror its loaded set instead of re-scanning disk — that keeps the WS
69
+ * payload aligned with what's actually being injected and respects test-only
70
+ * skillsDir overrides. The disk scan is the fallback used only when no session
71
+ * is bound or it doesn't expose a skills accessor (e.g. mock sessions).
72
+ *
73
+ * Disabling a skill remains a filesystem rename (`*.disabled.md`); there's no
74
+ * enable/disable UI in v2 either.
75
+ */
76
+ function handleListSkills(ws, client, msg, ctx) {
77
+ const entry = resolveSession(ctx, msg, client)
78
+
79
+ // #3209: emit the full activation context so the dashboard can
80
+ // render manual-skill toggles. For a bound session, run a fresh
81
+ // layered scan with `includeInactive: true` against that session's
82
+ // active set — the session's cached `_skills` only contains active
83
+ // entries (manual ones are filtered at construction).
84
+ // #3252: prefer the public getter so future BaseSession internal
85
+ // refactors don't silently turn this into "no active skills" without
86
+ // a type error or test failure. Optional-chaining the getter keeps
87
+ // mock sessions (which don't define the method) compatible.
88
+ const activeSetCandidate = entry?.session?.getActiveManualSkillsRaw?.()
89
+ const activeSet = activeSetCandidate instanceof Set ? activeSetCandidate : new Set()
90
+ // #3205: prefer the session's resolved skill dirs when available so
91
+ // the response matches what the session is actually injecting. This
92
+ // matters when the session was constructed with `skillsDir` /
93
+ // `repoSkillsDir` overrides (tests pin temp dirs; future wiring may
94
+ // override per-session). Fall back to the defaults / cwd-walk only
95
+ // when the session doesn't expose these — typically because no
96
+ // session is bound (the no-session path scans the global tier).
97
+ const sessionSkillsDir = entry?.session?._skillsDir || DEFAULT_SKILLS_DIR
98
+ const sessionRepoDir = entry?.session
99
+ ? (entry.session._repoSkillsDir !== undefined
100
+ ? entry.session._repoSkillsDir
101
+ : (entry.session.cwd ? findRepoSkillsDir(entry.session.cwd) : null))
102
+ : null
103
+ const provider = entry?.provider || null
104
+ // #3205: trust store powers the hash + last-activated metadata in
105
+ // the response. When the session has no trust store wired (operator
106
+ // didn't opt into 'warn' / 'block' modes), those fields are simply
107
+ // omitted — the dashboard renders the panel without those columns
108
+ // rather than showing fake data.
109
+ // #3252: same getter pattern as activeSet — keeps mock sessions
110
+ // working without forcing every test to add the method.
111
+ const trustStore = entry?.session?.getTrustStore?.() ?? null
112
+
113
+ // #3226 (review): forward the bound session's `providerSkillAllowlist`
114
+ // (if any) so the per-session listing reflects what the prompt builder
115
+ // would actually inject. Without this, on Codex/Gemini sessions with
116
+ // an allowlist configured, the dashboard would still show toggles for
117
+ // skills the runtime drops at prompt-build time. Skipped entirely
118
+ // when `includeAllProviders` is true (#3226's no-session path).
119
+ const sessionAllowlist = entry?.session?._providerSkillAllowlist || null
120
+
121
+ const skills = loadActiveSkillsLayered({
122
+ globalDir: sessionSkillsDir,
123
+ repoDir: sessionRepoDir,
124
+ provider,
125
+ activeManualSkills: activeSet,
126
+ providerSkillAllowlist: sessionAllowlist,
127
+ includeInactive: true,
128
+ // #3226: when no provider is bound (no session, or a session
129
+ // that doesn't expose one), bypass the provider-scoping gate
130
+ // and the per-provider allowlist so the dashboard's "browse
131
+ // all installed skills" listing doesn't silently drop scoped
132
+ // entries. Per-session listings keep `provider` set, so the
133
+ // current session's filtered view is unchanged.
134
+ includeAllProviders: provider == null,
135
+ }).map((s) => {
136
+ // `metadata.activation` is the authoritative source — keep
137
+ // anything else as `auto` to match the loader's defaults.
138
+ const rawActivation = typeof s.metadata?.activation === 'string'
139
+ ? s.metadata.activation.trim().toLowerCase()
140
+ : null
141
+ const activation = rawActivation === 'manual' ? 'manual' : 'auto'
142
+
143
+ const out = {
144
+ name: s.name,
145
+ description: s.description,
146
+ source: s.source || 'global',
147
+ activation,
148
+ // For `auto` skills, `active` is always true (they always load).
149
+ // For `manual` skills, reflect the loader's per-skill flag —
150
+ // already set from the activeManualSkills membership.
151
+ active: activation === 'auto' ? true : !!s.active,
152
+ }
153
+
154
+ // #3205: optional metadata fields — `version` from the YAML
155
+ // frontmatter, `hashPrefix` + `lastVerified` from the trust store.
156
+ // All optional so older clients keep parsing this response, and a
157
+ // trust-disabled session still gets a useful panel (just without
158
+ // the audit columns).
159
+ const version = typeof s.metadata?.version === 'string' ? s.metadata.version.trim() : null
160
+ if (version) out.version = version
161
+
162
+ if (trustStore && typeof trustStore.getRecord === 'function' && typeof s.path === 'string') {
163
+ const record = trustStore.getRecord(s.path)
164
+ if (record) {
165
+ // 8-char hash prefix matches the sanitised log + skill_changed
166
+ // wire format from #3215 / #3234. The full SHA never leaves
167
+ // the server.
168
+ out.hashPrefix = record.sha256.slice(0, 8)
169
+ // #3250: producer-side ISO-8601 validation. The wire schema
170
+ // (ServerSkillsListSchema) tightened these to z.string().datetime();
171
+ // a hand-edited or corrupted ~/.chroxy/skills-trust.json could
172
+ // otherwise emit a non-ISO string that fails the WHOLE
173
+ // skills_list payload at the dashboard parser. Drop the
174
+ // offending field instead — the dashboard renders the panel
175
+ // without that column rather than rejecting the response.
176
+ //
177
+ // Date.parse is too permissive (accepts e.g. "2026-03-18 10:00:00"
178
+ // which z.string().datetime() rejects). Match Zod's strict
179
+ // ISO-8601 shape: T separator + Z or numeric offset.
180
+ if (typeof record.lastVerified === 'string'
181
+ && _isIsoDatetime(record.lastVerified)) {
182
+ out.lastVerified = record.lastVerified
183
+ }
184
+ if (typeof record.firstSeen === 'string'
185
+ && _isIsoDatetime(record.firstSeen)) {
186
+ out.firstSeen = record.firstSeen
187
+ }
188
+ }
189
+ }
190
+
191
+ return out
192
+ })
193
+
194
+ ctx.transport.send(ws, { type: 'skills_list', skills })
195
+ }
196
+
197
+ /**
198
+ * #3209: activate a manual skill at runtime. The dashboard sends this
199
+ * when a user checks a manual-skill toggle. The session's active set
200
+ * is mutated, the skills list is reloaded so the next prompt picks
201
+ * up the new skill, and a `skill_activated` broadcast lets other
202
+ * clients on the same session refresh their UI.
203
+ */
204
+ function handleSkillActivate(ws, client, msg, ctx) {
205
+ if (typeof msg.skillName !== 'string' || msg.skillName === '') {
206
+ sendSessionError(ws, ctx, 'skill_activate requires a non-empty `skillName`')
207
+ return
208
+ }
209
+ const sessionId = msg.sessionId || client.activeSessionId
210
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
211
+ if (!entry) return
212
+ if (!requireSessionMethod(ws, ctx, entry, 'activateSkill', 'This provider does not support skill activation')) {
213
+ return
214
+ }
215
+ // #3246: subprocess providers (CliSession, CodexSession,
216
+ // GeminiSession) snapshot the skills text at session start —
217
+ // mutating in-memory state mid-session does not propagate to the
218
+ // running model. Refuse the toggle with a distinct error code so
219
+ // the dashboard can surface "this provider doesn't support runtime
220
+ // toggle" UX instead of silently flipping a checkbox that does
221
+ // nothing on the wire.
222
+ if (typeof entry.session.supportsRuntimeSkillToggle === 'function'
223
+ && !entry.session.supportsRuntimeSkillToggle()) {
224
+ sendError(
225
+ ws,
226
+ msg?.requestId,
227
+ 'SKILL_TOGGLE_UNSUPPORTED',
228
+ `Provider '${entry.provider}' does not support runtime skill toggling. Restart the session with the skill in 'activeManualSkills' instead.`,
229
+ undefined,
230
+ ctx,
231
+ )
232
+ return
233
+ }
234
+
235
+ const changed = entry.session.activateSkill(msg.skillName)
236
+ if (!changed) return // already active or invalid name — no-op, no broadcast
237
+
238
+ ctx.transport.broadcastToSession(sessionId, {
239
+ type: 'skill_activated',
240
+ sessionId,
241
+ skillName: msg.skillName,
242
+ })
243
+ }
244
+
245
+ /**
246
+ * #3209: deactivate a manual skill at runtime. Mirror of
247
+ * `handleSkillActivate`.
248
+ */
249
+ function handleSkillDeactivate(ws, client, msg, ctx) {
250
+ if (typeof msg.skillName !== 'string' || msg.skillName === '') {
251
+ sendSessionError(ws, ctx, 'skill_deactivate requires a non-empty `skillName`')
252
+ return
253
+ }
254
+ const sessionId = msg.sessionId || client.activeSessionId
255
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
256
+ if (!entry) return
257
+ if (!requireSessionMethod(ws, ctx, entry, 'deactivateSkill', 'This provider does not support skill toggling')) {
258
+ return
259
+ }
260
+ // #3246: same capability gate as activate — subprocess providers
261
+ // can't honour a mid-session deactivate either.
262
+ if (typeof entry.session.supportsRuntimeSkillToggle === 'function'
263
+ && !entry.session.supportsRuntimeSkillToggle()) {
264
+ sendError(
265
+ ws,
266
+ msg?.requestId,
267
+ 'SKILL_TOGGLE_UNSUPPORTED',
268
+ `Provider '${entry.provider}' does not support runtime skill toggling. Restart the session without the skill in 'activeManualSkills' instead.`,
269
+ undefined,
270
+ ctx,
271
+ )
272
+ return
273
+ }
274
+
275
+ const changed = entry.session.deactivateSkill(msg.skillName)
276
+ if (!changed) return // wasn't active — no-op, no broadcast
277
+
278
+ ctx.transport.broadcastToSession(sessionId, {
279
+ type: 'skill_deactivated',
280
+ sessionId,
281
+ skillName: msg.skillName,
282
+ })
283
+ }
284
+
285
+ /**
286
+ * #3235: operator-facing accept-hash surface for SkillsTrustStore. After
287
+ * a content-hash mismatch fires (`skill_changed` event), the operator
288
+ * needs a way to re-trust the new content without manually editing
289
+ * `~/.chroxy/skills-trust.json`. This handler:
290
+ *
291
+ * 1. Validates the inbound `skillName`.
292
+ * 2. Looks up the skill on the bound session (via `_getSkills()`) so
293
+ * we use the exact post-frontmatter `body` and `path` the loader
294
+ * already validated.
295
+ * 3. Calls `trustStore.acceptHash(realPath, body)` to overwrite the
296
+ * stored hash with the current content's digest.
297
+ * 4. Flushes the ledger so the new hash survives a crash.
298
+ * 5. Broadcasts `skill_trust_accepted` so the dashboard can clear any
299
+ * mismatch badge — pairs with the `skill_changed` event from #3234.
300
+ *
301
+ * Error envelope:
302
+ * - `INVALID_SKILL_NAME` (session_error envelope) — missing/empty.
303
+ * - `No active session` (session_error envelope) — no bound session.
304
+ * - `TRUST_NOT_ENABLED` — bound session has no trust store wired.
305
+ * - `SKILL_NOT_FOUND` — name doesn't match any currently-loaded skill.
306
+ *
307
+ * The handler does NOT trigger a session reload — the new hash takes
308
+ * effect on the NEXT load. In `block` mode, that's exactly what the
309
+ * operator wants: re-trust now, the skill loads on next session start.
310
+ */
311
+ function handleSkillTrustAccept(ws, client, msg, ctx) {
312
+ if (rejectSkillTrustIfBound(ws, client, msg, ctx)) return
313
+ if (typeof msg.skillName !== 'string' || msg.skillName === '') {
314
+ sendSessionError(ws, ctx, 'skill_trust_accept requires a non-empty `skillName`')
315
+ return
316
+ }
317
+ const sessionId = msg.sessionId || client.activeSessionId
318
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
319
+ if (!entry) return
320
+
321
+ // #3252: getter-with-optional-chaining keeps mock sessions (which
322
+ // don't define the method) compatible while still surfacing TRUST_NOT_ENABLED
323
+ // for legitimate trust-disabled sessions.
324
+ const trustStore = entry?.session?.getTrustStore?.() ?? null
325
+ if (!trustStore || typeof trustStore.acceptHash !== 'function') {
326
+ sendError(
327
+ ws,
328
+ msg?.requestId,
329
+ 'TRUST_NOT_ENABLED',
330
+ 'This session has no skills trust store wired (operator did not opt into warn/block mode).',
331
+ undefined,
332
+ ctx,
333
+ )
334
+ return
335
+ }
336
+
337
+ // Find the skill. We CAN'T use `_getSkills()` here: in `block` mode,
338
+ // a hash-mismatched skill is filtered out at load time, which means
339
+ // the very skills the operator is trying to re-trust are absent from
340
+ // the loaded list. Fall back to a direct filesystem lookup that
341
+ // bypasses the trust gate (#3235 review).
342
+ let resolvedPath = null
343
+ let resolvedBody = null
344
+
345
+ // First try the session's already-loaded list — covers the warn-mode
346
+ // case where the skill stays in `_skills` even after a mismatch.
347
+ // Using the loaded entry's body+path is preferable when available
348
+ // because the body has already been validated by the same loader pass
349
+ // that recorded the trust hash.
350
+ const loadedSkills = typeof entry.session._getSkills === 'function'
351
+ ? entry.session._getSkills()
352
+ : []
353
+ const loaded = Array.isArray(loadedSkills)
354
+ ? loadedSkills.find((s) => s && s.name === msg.skillName)
355
+ : null
356
+ if (loaded && typeof loaded.path === 'string' && typeof loaded.body === 'string') {
357
+ resolvedPath = loaded.path
358
+ resolvedBody = loaded.body
359
+ } else {
360
+ // Block-mode recovery path: scan the session's skill dirs directly.
361
+ const sessionGlobalDir = entry?.session?._skillsDir || DEFAULT_SKILLS_DIR
362
+ const sessionRepoDir = entry?.session?._repoSkillsDir !== undefined
363
+ ? entry.session._repoSkillsDir
364
+ : (entry?.session?.cwd ? findRepoSkillsDir(entry.session.cwd) : null)
365
+ const found = findSkillForRetrust({
366
+ skillName: msg.skillName,
367
+ globalDir: sessionGlobalDir,
368
+ repoDir: sessionRepoDir,
369
+ })
370
+ if (found) {
371
+ resolvedPath = found.realPath
372
+ resolvedBody = found.body
373
+ }
374
+ }
375
+
376
+ if (resolvedPath === null || resolvedBody === null) {
377
+ sendError(
378
+ ws,
379
+ msg?.requestId,
380
+ 'SKILL_NOT_FOUND',
381
+ `No skill named '${msg.skillName}' found in the session's skill directories.`,
382
+ undefined,
383
+ ctx,
384
+ )
385
+ return
386
+ }
387
+
388
+ trustStore.acceptHash(resolvedPath, resolvedBody)
389
+
390
+ // #3235 review: persist BEFORE broadcasting. If flush fails, the
391
+ // dashboard mustn't clear the mismatch indicator on a hash that
392
+ // never reached disk — the next restart would re-flag the skill.
393
+ // Surface the error to the caller so they can retry.
394
+ if (typeof trustStore.flush === 'function') {
395
+ try {
396
+ trustStore.flush()
397
+ } catch (err) {
398
+ // #4828: session-scoped — `sessionId` is in scope here.
399
+ loggerForSession('ws', sessionId).warn(`skill_trust_accept: flush failed (${err && err.message ? err.message : err})`)
400
+ sendError(
401
+ ws,
402
+ msg?.requestId,
403
+ 'TRUST_FLUSH_FAILED',
404
+ 'Accepted in memory but the trust ledger could not be persisted. Retry; the next restart may re-flag this skill.',
405
+ undefined,
406
+ ctx,
407
+ )
408
+ return
409
+ }
410
+ }
411
+
412
+ ctx.transport.broadcastToSession(sessionId, {
413
+ type: 'skill_trust_accepted',
414
+ sessionId,
415
+ skillName: msg.skillName,
416
+ })
417
+ }
418
+
419
+ // #3500: shallow scan of community/*/<skillName>.{md,markdown} across the
420
+ // configured skills roots. Returns the first author (other than `claimedAuthor`)
421
+ // that actually owns the skill on disk, or null if no such author exists.
422
+ //
423
+ // Bounded cost: one readdirSync per skills root + one statSync per author dir
424
+ // per extension. Only invoked on the SKILL_NOT_FOUND error path after the
425
+ // per-author realpath lookup has already missed — never on the happy path.
426
+ //
427
+ // Each candidate is gated through `_isCommunityNamespace` against the root's
428
+ // realpath, mirroring the security check the per-author loop applies. That
429
+ // rejects hidden author dirs (.foo), symlinks that escape the root, and any
430
+ // segment shape that doesn't fit `community/<author>/<file>`.
431
+ function _scanCommunityForSkillName(skillsRoots, skillName, claimedAuthor) {
432
+ for (const root of skillsRoots) {
433
+ let rootReal
434
+ try {
435
+ rootReal = realpathSync(root)
436
+ } catch {
437
+ continue
438
+ }
439
+ let authorEntries
440
+ try {
441
+ authorEntries = readdirSync(`${rootReal}/community`, { withFileTypes: true })
442
+ } catch {
443
+ // No community/ dir under this root — skip.
444
+ continue
445
+ }
446
+ // #3549: readdir order is filesystem/platform-dependent. Sort by name so
447
+ // that when multiple community authors expose a skill with the same name,
448
+ // the suggested `actualAuthor` is deterministic (matches the alphabetical
449
+ // ordering used by the skills loader's community walk).
450
+ authorEntries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
451
+ for (const ent of authorEntries) {
452
+ const authorName = ent.name
453
+ // Mirror _isCommunityNamespace's hidden-author guard. We also need the
454
+ // entry to be a directory (or a symlink to one) — readdir's withFileTypes
455
+ // gives us .isDirectory() / .isSymbolicLink() checks without an extra stat
456
+ // for the common case.
457
+ if (!authorName || authorName === '.' || authorName === '..' || authorName.startsWith('.')) continue
458
+ if (!ent.isDirectory() && !ent.isSymbolicLink()) continue
459
+ if (authorName === claimedAuthor) continue
460
+ for (const ext of ['md', 'markdown']) {
461
+ const candidatePath = `${rootReal}/community/${authorName}/${skillName}.${ext}`
462
+ let candidateReal
463
+ try {
464
+ candidateReal = realpathSync(candidatePath)
465
+ } catch {
466
+ continue
467
+ }
468
+ // Confirm the resolved path is regular and under community/<author>/.
469
+ try {
470
+ const st = statSync(candidateReal)
471
+ if (!st.isFile()) continue
472
+ } catch {
473
+ continue
474
+ }
475
+ const { isCommunity, author: actualAuthor } = _isCommunityNamespace(candidateReal, rootReal)
476
+ if (!isCommunity) continue
477
+ if (!actualAuthor || actualAuthor === claimedAuthor) continue
478
+ return actualAuthor
479
+ }
480
+ }
481
+ }
482
+ return null
483
+ }
484
+
485
+ /**
486
+ * #3297: grant community trust for a given author/skill. Fired when the
487
+ * dashboard operator accepts the first-activation prompt for a community
488
+ * skill. Unlike `skill_trust_accept` (hash mismatch recovery), this
489
+ * handler:
490
+ *
491
+ * 1. Validates `skillName` and `author` from the payload.
492
+ * 2. Resolves the skill's realpath from the session's skills dirs
493
+ * (falling back to a direct community/<author>/<name>.md scan
494
+ * because community skills are absent from `_getSkills()` while
495
+ * pending trust).
496
+ * 3. Applies a security gate: verifies the resolved path is genuinely
497
+ * under `community/<author>/` via `_isCommunityNamespace`, and that
498
+ * the directory author matches the claimed `author`.
499
+ * 4. Calls `trustStore.grantCommunityTrust(author, { realPath })` to
500
+ * write both the byAuthor and byPath indexes and flush synchronously.
501
+ * 5. Calls `session._loadSkills()` so the just-trusted skill is active
502
+ * for the CURRENT session immediately (no restart required).
503
+ * 6. Broadcasts `skill_trust_granted` to all session clients and sends
504
+ * `skill_trust_grant_ok` ack to the requesting client.
505
+ *
506
+ * Error codes:
507
+ * - `INVALID_SKILL_NAME` — missing/empty skillName
508
+ * - `INVALID_AUTHOR` — missing/empty author, OR (#3307) the skill resolves
509
+ * on disk under a different `community/<author>/` namespace than the
510
+ * caller claims (e.g. via a symlink that crosses author dirs), OR (#3500)
511
+ * a shallow scan of `community/<author>/` finds the skillName under a different
512
+ * author when the per-author lookup misses (the common no-symlink case).
513
+ * For the cross-author cases the response carries `actualAuthor` as a
514
+ * structured field (#3538) — clients can branch on `code` and read
515
+ * `actualAuthor` directly to render "did you mean alice?" without
516
+ * regex-parsing the human-readable `message`. The empty-author
517
+ * validation case does NOT carry `actualAuthor` (no real author known).
518
+ * - `No active session` (session_error) — no bound session
519
+ * - `TRUST_NOT_ENABLED` — session has no trust store
520
+ * - `SKILL_NOT_FOUND` — can't find the skill on disk under any author
521
+ * - `TRUST_FLUSH_FAILED` — granted in memory but the trust ledger could not be persisted
522
+ */
523
+ function handleSkillTrustGrant(ws, client, msg, ctx) {
524
+ if (rejectSkillTrustIfBound(ws, client, msg, ctx)) return
525
+ if (typeof msg.skillName !== 'string' || msg.skillName === '') {
526
+ sendError(ws, msg?.requestId, 'INVALID_SKILL_NAME', 'skill_trust_grant requires a non-empty `skillName`', undefined, ctx)
527
+ return
528
+ }
529
+ if (typeof msg.author !== 'string' || msg.author === '') {
530
+ sendError(ws, msg?.requestId, 'INVALID_AUTHOR', 'skill_trust_grant requires a non-empty `author`', undefined, ctx)
531
+ return
532
+ }
533
+
534
+ const sessionId = msg.sessionId || client.activeSessionId
535
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
536
+ if (!entry) return
537
+
538
+ const trustStore = entry?.session?.getTrustStore?.() ?? null
539
+ if (!trustStore || typeof trustStore.grantCommunityTrust !== 'function') {
540
+ sendError(ws, msg?.requestId, 'TRUST_NOT_ENABLED', 'This session has no skills trust store wired.', undefined, ctx)
541
+ return
542
+ }
543
+
544
+ // Resolve the skill path. Community skills are absent from _getSkills()
545
+ // while pending trust, so we scan the community dirs directly.
546
+ const sessionGlobalDir = entry?.session?._skillsDir || DEFAULT_SKILLS_DIR
547
+ const sessionRepoDir = entry?.session?._repoSkillsDir !== undefined
548
+ ? entry.session._repoSkillsDir
549
+ : (entry?.session?.cwd ? findRepoSkillsDir(entry.session.cwd) : null)
550
+
551
+ // Collect all skills roots to search
552
+ const skillsRoots = [sessionGlobalDir]
553
+ if (sessionRepoDir) skillsRoots.push(sessionRepoDir)
554
+
555
+ let resolvedPath = null
556
+ // #3307: track when the lookup resolves to a real file but lands under a
557
+ // different community author than the caller claims. Distinguishes
558
+ // "skill missing entirely" (SKILL_NOT_FOUND) from "skill exists under
559
+ // a different namespace" (INVALID_AUTHOR) so clients can guide the
560
+ // operator toward the correct author.
561
+ let namespaceMismatchDetected = false
562
+ // #3538: capture the real author of the cross-namespace resolve so we can
563
+ // surface it as a structured field on INVALID_AUTHOR (no regex on message).
564
+ let mismatchActualAuthor = null
565
+
566
+ for (const root of skillsRoots) {
567
+ let rootReal
568
+ try {
569
+ rootReal = realpathSync(root)
570
+ } catch {
571
+ continue
572
+ }
573
+ // Try community/<author>/<skillName> with each allowed extension (.md, .markdown)
574
+ let candidateReal = null
575
+ for (const ext of ['md', 'markdown']) {
576
+ const candidatePath = `${root}/community/${msg.author}/${msg.skillName}.${ext}`
577
+ try {
578
+ candidateReal = realpathSync(candidatePath)
579
+ break
580
+ } catch {
581
+ // not found with this extension — try next
582
+ }
583
+ }
584
+ if (!candidateReal) continue
585
+ // Security gate: verify the resolved path is under community/<author>/
586
+ const { isCommunity, author: actualAuthor } = _isCommunityNamespace(candidateReal, rootReal)
587
+ if (!isCommunity) continue
588
+ if (actualAuthor !== msg.author) {
589
+ // Skill exists on disk but the realpath belongs to a different community
590
+ // author (e.g. via a symlink). Flag it so we can surface INVALID_AUTHOR
591
+ // after the loop instead of the misleading SKILL_NOT_FOUND.
592
+ namespaceMismatchDetected = true
593
+ // Remember the real author so the error response can carry it
594
+ // structurally (#3538). Keep the first hit — additional roots are
595
+ // unlikely to disagree but if they do, the first match is what the
596
+ // per-author lookup would have resolved to.
597
+ if (mismatchActualAuthor === null) mismatchActualAuthor = actualAuthor
598
+ continue
599
+ }
600
+ resolvedPath = candidateReal
601
+ break
602
+ }
603
+
604
+ if (!resolvedPath) {
605
+ if (namespaceMismatchDetected) {
606
+ sendError(
607
+ ws,
608
+ msg?.requestId,
609
+ 'INVALID_AUTHOR',
610
+ `Community skill '${msg.skillName}' resolves to a different author than '${msg.author}'.`,
611
+ // #3538: structured field for client suggestions ("did you mean X?").
612
+ { actualAuthor: mismatchActualAuthor },
613
+ ctx,
614
+ )
615
+ return
616
+ }
617
+ // #3500: per-author realpath lookup missed. Before declaring SKILL_NOT_FOUND,
618
+ // scan community/*/ for the skillName — the common operator path is
619
+ // `community/alice/foo.md` exists with NO symlink under `community/<msg.author>/`,
620
+ // and we want to surface "wrong author" rather than "missing".
621
+ const actualAuthor = _scanCommunityForSkillName(skillsRoots, msg.skillName, msg.author)
622
+ if (actualAuthor) {
623
+ sendError(
624
+ ws,
625
+ msg?.requestId,
626
+ 'INVALID_AUTHOR',
627
+ `Community skill '${msg.skillName}' is owned by '${actualAuthor}', not '${msg.author}'.`,
628
+ // #3538: structured field for client suggestions ("did you mean X?").
629
+ { actualAuthor },
630
+ ctx,
631
+ )
632
+ return
633
+ }
634
+ sendError(ws, msg?.requestId, 'SKILL_NOT_FOUND', `No community skill '${msg.skillName}' found for author '${msg.author}'.`, undefined, ctx)
635
+ return
636
+ }
637
+
638
+ try {
639
+ trustStore.grantCommunityTrust(msg.author, { realPath: resolvedPath })
640
+ } catch (err) {
641
+ // #4828: session-scoped — `sessionId` is in scope earlier in the handler.
642
+ loggerForSession('ws', sessionId).warn(`skill_trust_grant: flush failed (${err && err.message ? err.message : err})`)
643
+ sendError(
644
+ ws,
645
+ msg?.requestId,
646
+ 'TRUST_FLUSH_FAILED',
647
+ 'Granted in memory but the trust ledger could not be persisted. Retry; the next restart may re-prompt for trust.',
648
+ undefined,
649
+ ctx,
650
+ )
651
+ return
652
+ }
653
+
654
+ // Reload skills immediately so the just-trusted skill is active in this session.
655
+ if (typeof entry.session._loadSkills === 'function') {
656
+ entry.session._loadSkills()
657
+ }
658
+
659
+ ctx.transport.broadcastToSession(sessionId, {
660
+ type: 'skill_trust_granted',
661
+ sessionId,
662
+ skillName: msg.skillName,
663
+ author: msg.author,
664
+ })
665
+
666
+ ctx.transport.send(ws, {
667
+ type: 'skill_trust_grant_ok',
668
+ requestId: msg?.requestId ?? null,
669
+ sessionId,
670
+ skillName: msg.skillName,
671
+ author: msg.author,
672
+ })
673
+ }
674
+
675
+
676
+ export const skillsHandlers = {
677
+ list_skills: handleListSkills,
678
+ skill_activate: handleSkillActivate,
679
+ skill_deactivate: handleSkillDeactivate,
680
+ skill_trust_accept: handleSkillTrustAccept,
681
+ skill_trust_grant: handleSkillTrustGrant,
682
+ }