@countinghouse/ch-local 0.0.0-stage → 1.0.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 (262) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +361 -2
  3. package/bin/ch-local.js +472 -0
  4. package/clients/claude-code/.claude-plugin/plugin.json +6 -0
  5. package/clients/claude-code/.mcp.json +11 -0
  6. package/clients/claude-code/bin/launch.js +235 -0
  7. package/clients/claude-code/bin/win-acl.js +420 -0
  8. package/clients/claude-code/skills/ci-failure-triage/SKILL.md +21 -0
  9. package/clients/claude-code/skills/countinghouse-module/SKILL.md +177 -0
  10. package/clients/claude-code/skills/countinghouse-setup/SKILL.md +74 -0
  11. package/lib/allowlist.js +65 -0
  12. package/lib/aside.js +16 -0
  13. package/lib/atomic.js +45 -0
  14. package/lib/auto-apply.js +245 -0
  15. package/lib/auto-upgrade.js +98 -0
  16. package/lib/availability.js +307 -0
  17. package/lib/ceiling.js +280 -0
  18. package/lib/clean-text.js +20 -0
  19. package/lib/cli-change.js +38 -0
  20. package/lib/client-conditions-fixtures.js +143 -0
  21. package/lib/client-conditions.js +656 -0
  22. package/lib/clients.js +179 -0
  23. package/lib/command-line.js +202 -0
  24. package/lib/conditions-command.js +116 -0
  25. package/lib/control.js +134 -0
  26. package/lib/credential-store.js +414 -0
  27. package/lib/credentials-command.js +344 -0
  28. package/lib/daemon-requests.js +137 -0
  29. package/lib/daemon.js +888 -0
  30. package/lib/describe-module.js +137 -0
  31. package/lib/description-check.js +175 -0
  32. package/lib/failed-json.js +43 -0
  33. package/lib/gc.js +274 -0
  34. package/lib/github-token.js +57 -0
  35. package/lib/handoff-io.js +73 -0
  36. package/lib/held-back.js +116 -0
  37. package/lib/hidden-input.js +64 -0
  38. package/lib/history.js +49 -0
  39. package/lib/home.js +372 -0
  40. package/lib/in-place.js +1036 -0
  41. package/lib/install-plan.js +142 -0
  42. package/lib/install.js +846 -0
  43. package/lib/installed-description.js +153 -0
  44. package/lib/integrity.js +7 -0
  45. package/lib/lock.js +456 -0
  46. package/lib/lockfile-rules.js +98 -0
  47. package/lib/machine.js +20 -0
  48. package/lib/module-credentials.js +403 -0
  49. package/lib/module-record.js +298 -0
  50. package/lib/module-roles.js +44 -0
  51. package/lib/module-seams.js +26 -0
  52. package/lib/module-store.js +202 -0
  53. package/lib/module-values.js +334 -0
  54. package/lib/names.js +31 -0
  55. package/lib/next-steps.js +8 -0
  56. package/lib/node-check.js +56 -0
  57. package/lib/npm-fetch.js +123 -0
  58. package/lib/npm-release.js +99 -0
  59. package/lib/npm-upgrade.js +146 -0
  60. package/lib/npm.js +41 -0
  61. package/lib/outside-edits.js +162 -0
  62. package/lib/own-applied.js +175 -0
  63. package/lib/own-command.js +380 -0
  64. package/lib/own-file.js +120 -0
  65. package/lib/own-record.js +96 -0
  66. package/lib/own-tree.js +336 -0
  67. package/lib/pack-table.js +290 -0
  68. package/lib/packs-command.js +570 -0
  69. package/lib/packs.js +219 -0
  70. package/lib/pins.js +64 -0
  71. package/lib/pipe-probe.js +82 -0
  72. package/lib/plain-read.js +63 -0
  73. package/lib/private-file.js +90 -0
  74. package/lib/private-write.js +33 -0
  75. package/lib/provenance.js +234 -0
  76. package/lib/record.js +82 -0
  77. package/lib/registry.js +22 -0
  78. package/lib/release-pins.js +350 -0
  79. package/lib/release-pins.json +4225 -0
  80. package/lib/release-tags.js +12 -0
  81. package/lib/release.js +36 -0
  82. package/lib/restart-command.js +161 -0
  83. package/lib/rollback.js +227 -0
  84. package/lib/run-liveness.js +15 -0
  85. package/lib/runtime-log.js +287 -0
  86. package/lib/sandbox-support.js +17 -0
  87. package/lib/semver-order.js +40 -0
  88. package/lib/session-socket.js +69 -0
  89. package/lib/session-table.js +238 -0
  90. package/lib/session.js +281 -0
  91. package/lib/settings-command.js +82 -0
  92. package/lib/settings.js +564 -0
  93. package/lib/shim-binary.js +152 -0
  94. package/lib/shim-config.js +159 -0
  95. package/lib/shim-install.js +365 -0
  96. package/lib/sigstore/README.md +44 -0
  97. package/lib/sigstore/npm-keys.json +18 -0
  98. package/lib/sigstore/trusted-root.json +126 -0
  99. package/lib/snippets.js +76 -0
  100. package/lib/start.js +721 -0
  101. package/lib/store-files.js +48 -0
  102. package/lib/store-paths.js +33 -0
  103. package/lib/swap-preload.js +38 -0
  104. package/lib/tar.js +220 -0
  105. package/lib/uninstall.js +314 -0
  106. package/lib/unpack.js +41 -0
  107. package/lib/upgrade-stamp.js +63 -0
  108. package/lib/upgrade.js +281 -0
  109. package/lib/watch.js +40 -0
  110. package/lib/win-acl.js +420 -0
  111. package/node_modules/@sigstore/bundle/LICENSE +202 -0
  112. package/node_modules/@sigstore/bundle/README.md +19 -0
  113. package/node_modules/@sigstore/bundle/dist/build.d.ts +18 -0
  114. package/node_modules/@sigstore/bundle/dist/build.js +100 -0
  115. package/node_modules/@sigstore/bundle/dist/bundle.d.ts +74 -0
  116. package/node_modules/@sigstore/bundle/dist/bundle.js +24 -0
  117. package/node_modules/@sigstore/bundle/dist/error.d.ts +4 -0
  118. package/node_modules/@sigstore/bundle/dist/error.js +25 -0
  119. package/node_modules/@sigstore/bundle/dist/index.d.ts +8 -0
  120. package/node_modules/@sigstore/bundle/dist/index.js +43 -0
  121. package/node_modules/@sigstore/bundle/dist/serialized.d.ts +74 -0
  122. package/node_modules/@sigstore/bundle/dist/serialized.js +49 -0
  123. package/node_modules/@sigstore/bundle/dist/utility.d.ts +14 -0
  124. package/node_modules/@sigstore/bundle/dist/utility.js +2 -0
  125. package/node_modules/@sigstore/bundle/dist/validate.d.ts +7 -0
  126. package/node_modules/@sigstore/bundle/dist/validate.js +199 -0
  127. package/node_modules/@sigstore/bundle/package.json +35 -0
  128. package/node_modules/@sigstore/core/LICENSE +202 -0
  129. package/node_modules/@sigstore/core/README.md +10 -0
  130. package/node_modules/@sigstore/core/dist/asn1/error.d.ts +4 -0
  131. package/node_modules/@sigstore/core/dist/asn1/error.js +24 -0
  132. package/node_modules/@sigstore/core/dist/asn1/index.d.ts +1 -0
  133. package/node_modules/@sigstore/core/dist/asn1/index.js +20 -0
  134. package/node_modules/@sigstore/core/dist/asn1/length.d.ts +3 -0
  135. package/node_modules/@sigstore/core/dist/asn1/length.js +62 -0
  136. package/node_modules/@sigstore/core/dist/asn1/obj.d.ts +14 -0
  137. package/node_modules/@sigstore/core/dist/asn1/obj.js +155 -0
  138. package/node_modules/@sigstore/core/dist/asn1/parse.d.ts +6 -0
  139. package/node_modules/@sigstore/core/dist/asn1/parse.js +124 -0
  140. package/node_modules/@sigstore/core/dist/asn1/tag.d.ts +16 -0
  141. package/node_modules/@sigstore/core/dist/asn1/tag.js +89 -0
  142. package/node_modules/@sigstore/core/dist/crypto.d.ts +6 -0
  143. package/node_modules/@sigstore/core/dist/crypto.js +69 -0
  144. package/node_modules/@sigstore/core/dist/dsse.d.ts +1 -0
  145. package/node_modules/@sigstore/core/dist/dsse.js +29 -0
  146. package/node_modules/@sigstore/core/dist/encoding.d.ts +2 -0
  147. package/node_modules/@sigstore/core/dist/encoding.js +27 -0
  148. package/node_modules/@sigstore/core/dist/index.d.ts +9 -0
  149. package/node_modules/@sigstore/core/dist/index.js +66 -0
  150. package/node_modules/@sigstore/core/dist/json.d.ts +1 -0
  151. package/node_modules/@sigstore/core/dist/json.js +60 -0
  152. package/node_modules/@sigstore/core/dist/oid.d.ts +3 -0
  153. package/node_modules/@sigstore/core/dist/oid.js +20 -0
  154. package/node_modules/@sigstore/core/dist/pem.d.ts +2 -0
  155. package/node_modules/@sigstore/core/dist/pem.js +43 -0
  156. package/node_modules/@sigstore/core/dist/rfc3161/error.d.ts +2 -0
  157. package/node_modules/@sigstore/core/dist/rfc3161/error.js +21 -0
  158. package/node_modules/@sigstore/core/dist/rfc3161/index.d.ts +1 -0
  159. package/node_modules/@sigstore/core/dist/rfc3161/index.js +20 -0
  160. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.d.ts +36 -0
  161. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +212 -0
  162. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.d.ts +12 -0
  163. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +72 -0
  164. package/node_modules/@sigstore/core/dist/stream.d.ts +21 -0
  165. package/node_modules/@sigstore/core/dist/stream.js +117 -0
  166. package/node_modules/@sigstore/core/dist/x509/cert.d.ts +43 -0
  167. package/node_modules/@sigstore/core/dist/x509/cert.js +245 -0
  168. package/node_modules/@sigstore/core/dist/x509/ext.d.ts +41 -0
  169. package/node_modules/@sigstore/core/dist/x509/ext.js +146 -0
  170. package/node_modules/@sigstore/core/dist/x509/index.d.ts +2 -0
  171. package/node_modules/@sigstore/core/dist/x509/index.js +23 -0
  172. package/node_modules/@sigstore/core/dist/x509/sct.d.ts +25 -0
  173. package/node_modules/@sigstore/core/dist/x509/sct.js +158 -0
  174. package/node_modules/@sigstore/core/package.json +31 -0
  175. package/node_modules/@sigstore/protobuf-specs/LICENSE +202 -0
  176. package/node_modules/@sigstore/protobuf-specs/README.md +5 -0
  177. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.d.ts +44 -0
  178. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +59 -0
  179. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.d.ts +64 -0
  180. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +174 -0
  181. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.d.ts +74 -0
  182. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +141 -0
  183. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.d.ts +74 -0
  184. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +35 -0
  185. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.d.ts +1309 -0
  186. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +2191 -0
  187. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.d.ts +113 -0
  188. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +29 -0
  189. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.d.ts +23 -0
  190. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js +55 -0
  191. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.d.ts +43 -0
  192. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js +81 -0
  193. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.d.ts +22 -0
  194. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js +56 -0
  195. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.d.ts +35 -0
  196. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js +74 -0
  197. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.d.ts +146 -0
  198. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +103 -0
  199. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.d.ts +304 -0
  200. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +612 -0
  201. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.d.ts +33 -0
  202. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.js +55 -0
  203. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.d.ts +144 -0
  204. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +137 -0
  205. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.d.ts +386 -0
  206. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +284 -0
  207. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.d.ts +191 -0
  208. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +281 -0
  209. package/node_modules/@sigstore/protobuf-specs/dist/index.d.ts +6 -0
  210. package/node_modules/@sigstore/protobuf-specs/dist/index.js +37 -0
  211. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.d.ts +4 -0
  212. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js +35 -0
  213. package/node_modules/@sigstore/protobuf-specs/package.json +35 -0
  214. package/node_modules/@sigstore/verify/README.md +9 -0
  215. package/node_modules/@sigstore/verify/dist/bundle/dsse.d.ts +12 -0
  216. package/node_modules/@sigstore/verify/dist/bundle/dsse.js +44 -0
  217. package/node_modules/@sigstore/verify/dist/bundle/index.d.ts +4 -0
  218. package/node_modules/@sigstore/verify/dist/bundle/index.js +59 -0
  219. package/node_modules/@sigstore/verify/dist/bundle/message.d.ts +13 -0
  220. package/node_modules/@sigstore/verify/dist/bundle/message.js +54 -0
  221. package/node_modules/@sigstore/verify/dist/error.d.ts +16 -0
  222. package/node_modules/@sigstore/verify/dist/error.js +34 -0
  223. package/node_modules/@sigstore/verify/dist/index.d.ts +6 -0
  224. package/node_modules/@sigstore/verify/dist/index.js +28 -0
  225. package/node_modules/@sigstore/verify/dist/key/certificate.d.ts +21 -0
  226. package/node_modules/@sigstore/verify/dist/key/certificate.js +216 -0
  227. package/node_modules/@sigstore/verify/dist/key/index.d.ts +10 -0
  228. package/node_modules/@sigstore/verify/dist/key/index.js +75 -0
  229. package/node_modules/@sigstore/verify/dist/key/sct.d.ts +4 -0
  230. package/node_modules/@sigstore/verify/dist/key/sct.js +78 -0
  231. package/node_modules/@sigstore/verify/dist/policy.d.ts +5 -0
  232. package/node_modules/@sigstore/verify/dist/policy.js +50 -0
  233. package/node_modules/@sigstore/verify/dist/shared.types.d.ts +50 -0
  234. package/node_modules/@sigstore/verify/dist/shared.types.js +2 -0
  235. package/node_modules/@sigstore/verify/dist/timestamp/index.d.ts +11 -0
  236. package/node_modules/@sigstore/verify/dist/timestamp/index.js +24 -0
  237. package/node_modules/@sigstore/verify/dist/timestamp/tsa.d.ts +3 -0
  238. package/node_modules/@sigstore/verify/dist/timestamp/tsa.js +63 -0
  239. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.d.ts +11 -0
  240. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.js +154 -0
  241. package/node_modules/@sigstore/verify/dist/tlog/dsse.d.ts +6 -0
  242. package/node_modules/@sigstore/verify/dist/tlog/dsse.js +106 -0
  243. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.d.ts +6 -0
  244. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +94 -0
  245. package/node_modules/@sigstore/verify/dist/tlog/index.d.ts +5 -0
  246. package/node_modules/@sigstore/verify/dist/tlog/index.js +92 -0
  247. package/node_modules/@sigstore/verify/dist/tlog/intoto.d.ts +3 -0
  248. package/node_modules/@sigstore/verify/dist/tlog/intoto.js +62 -0
  249. package/node_modules/@sigstore/verify/dist/tlog/merkle.d.ts +3 -0
  250. package/node_modules/@sigstore/verify/dist/tlog/merkle.js +104 -0
  251. package/node_modules/@sigstore/verify/dist/tlog/set.d.ts +3 -0
  252. package/node_modules/@sigstore/verify/dist/tlog/set.js +60 -0
  253. package/node_modules/@sigstore/verify/dist/trust/filter.d.ts +8 -0
  254. package/node_modules/@sigstore/verify/dist/trust/filter.js +23 -0
  255. package/node_modules/@sigstore/verify/dist/trust/index.d.ts +5 -0
  256. package/node_modules/@sigstore/verify/dist/trust/index.js +90 -0
  257. package/node_modules/@sigstore/verify/dist/trust/trust.types.d.ts +29 -0
  258. package/node_modules/@sigstore/verify/dist/trust/trust.types.js +2 -0
  259. package/node_modules/@sigstore/verify/dist/verifier.d.ts +31 -0
  260. package/node_modules/@sigstore/verify/dist/verifier.js +160 -0
  261. package/node_modules/@sigstore/verify/package.json +36 -0
  262. package/package.json +37 -4
package/lib/clients.js ADDED
@@ -0,0 +1,179 @@
1
+ 'use strict';
2
+ // ch-local add <client>: writes the client's entry for the installed launcher
3
+ // and records exactly what it wrote in <home>/installed-clients.json, so that
4
+ // uninstall can take back exactly that and nothing else.
5
+ const fs = require('node:fs');
6
+ const {isDeepStrictEqual: same} = require('node:util');
7
+ const path = require('node:path');
8
+ const {snippet, SERVER} = require('./snippets');
9
+ const {layout} = require('./home');
10
+ const {writeAtomic} = require('./atomic');
11
+ const {chLocal, hintCommand} = require('./command-line');
12
+
13
+ const absolute = (v) => (typeof v === 'string' && path.isAbsolute(v) ? v : null);
14
+ // The file each client reads, under the user's home directory.
15
+ const FILES = {
16
+ cursor: (home) => path.join(home, '.cursor', 'mcp.json'),
17
+ // (Copilot reads $COPILOT_HOME/mcp-config.json when that is set)
18
+ // (a client's home variable only when absolute: a relative one would name
19
+ // a file under whatever directory add runs in)
20
+ vscode: (home, env) => path.join(absolute(env.COPILOT_HOME) || path.join(home, '.copilot'), 'mcp-config.json'),
21
+ codex: (home, env) => path.join(absolute(env.CODEX_HOME) || path.join(home, '.codex'), 'config.toml')
22
+ };
23
+ // (where: the home's layout, for the command's launcher form:
24
+ // lib/command-line.js)
25
+ const elsewhere = (where) => ({
26
+ 'claude-code': `Claude Code: use the plugin (claude plugin marketplace add mchen6/ch-local, then claude plugin install ch-packs@ch-packs), or run the line \`${chLocal(where, 'snippet claude-code')}\` prints`,
27
+ 'claude-desktop': `Claude Desktop: its route is the .mcpb bundle, which is not built yet (\`${chLocal(where, 'snippet claude-desktop')}\` says why)`
28
+ });
29
+
30
+ const isObject = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
31
+ // Any TOML spelling of the table's header: bare, double- or single-quoted key, spaces.
32
+ const TABLE = new RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*(?:"${SERVER}"|'${SERVER}'|${SERVER})[ \\t]*\\][ \\t]*(?:#.*)?$`, 'm');
33
+ const readText = (file) => (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null);
34
+
35
+ function readRecord(where) {
36
+ const text = readText(where.clients);
37
+ return text == null ? {entries: []} : JSON.parse(text);
38
+ }
39
+ function writeRecord(where, record) {
40
+ writeAtomic(where.clients, JSON.stringify(record, null, 2) + '\n');
41
+ }
42
+
43
+ // The outcome of an add: {ok: true, record} when ch-local wrote (or rewrote its
44
+ // own) entry, {ok: true, record: null} when an identical entry was written by
45
+ // hand (never adopted, so uninstall leaves it), {ok: false, why} otherwise.
46
+ const BY_HAND = {ok: true, record: null};
47
+
48
+ // `recorded`: what ch-local wrote to this file last time, or undefined.
49
+ function addJson(file, entry, recorded, where, client) {
50
+ const text = readText(file);
51
+ let config = {};
52
+ if (text != null && text.trim() !== '') {
53
+ try { config = JSON.parse(text); } catch { return {ok: false, why: `${file} is not plain JSON; add the entry by hand (${chLocal(where, `snippet ${client}`)} prints it)`}; }
54
+ }
55
+ if (!isObject(config) || (config.mcpServers !== undefined && !isObject(config.mcpServers))) {
56
+ return {ok: false, why: `${file} does not hold an object of servers ("mcpServers"); add the entry by hand (${chLocal(where, `snippet ${client}`)} prints it)`};
57
+ }
58
+ if (config.mcpServers === undefined) config.mcpServers = {};
59
+ const existing = config.mcpServers[SERVER];
60
+ const ours = recorded !== undefined && recorded.kind === 'json' && same(existing, recorded.entry);
61
+ if (existing !== undefined && !ours) {
62
+ return same(existing, entry) ? BY_HAND : {ok: false, why: `${file} already has a "${SERVER}" entry; ch-local leaves it alone`};
63
+ }
64
+ config.mcpServers[SERVER] = entry;
65
+ writeAtomic(file, JSON.stringify(config, null, 2) + '\n');
66
+ return {ok: true, record: {kind: 'json', entry}};
67
+ }
68
+
69
+ // Codex's table is ch-local's to rewrite or take back only while the whole
70
+ // of it, from its header to the next table, is still what ch-local wrote (its
71
+ // line endings and the blank lines after it aside). Any change of the user's
72
+ // (a wait set another way, a line added, a table of its own under it) leaves
73
+ // it to them, whole: nothing of theirs is merged with ch-local's lines, so no
74
+ // key is ever written twice (Codex refuses such a file) and no line of theirs
75
+ // is left to join another table.
76
+ // (a header: a line that is only [name] or [[name]], and a comment; a quoted
77
+ // part of a name may hold any character, a bracket too)
78
+ const HEADER = /^[ \t]*\[\[?(?:"[^"\n]*"|'[^'\n]*'|[^[\]\n"'])+\]\]?[ \t]*(?:#.*)?\r?$/m;
79
+ // (a table under this server's own, anywhere in the file: [mcp_servers.countinghouse.<name>])
80
+ const UNDER = new RegExp(`^[ \\t]*\\[\\[?[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*(?:"${SERVER}"|'${SERVER}'|${SERVER})[ \\t]*\\.`, 'm');
81
+ // -> {at, body, end, under} for the table in text: body is its text with the
82
+ // blank and comment lines after it left out, end where the next table begins;
83
+ // under: the file holds a table under this server's; or null
84
+ function codexTable(text) {
85
+ const m = TABLE.exec(text);
86
+ if (m == null) return null;
87
+ const nl = text.indexOf('\n', m.index);
88
+ const from = nl < 0 ? text.length : nl + 1;
89
+ const next = HEADER.exec(text.slice(from));
90
+ const end = next == null ? text.length : from + next.index;
91
+ const own = text.slice(m.index, end);
92
+ const lines = own.split('\n');
93
+ while (lines.length > 1 && /^[ \t]*(?:#.*)?\r?$/.test(lines[lines.length - 1])) lines.pop();
94
+ return {at: m.index, body: lines.join('\n').replace(/\r$/, ''), end, under: UNDER.test(text)};
95
+ }
96
+ const sameTable = (t, block) => typeof block === 'string' && !t.under && t.body.replace(/\r\n/g, '\n') === block.replace(/\n+$/, '');
97
+
98
+ // Appends the TOML table, or rewrites the one it wrote; records the separator it added.
99
+ function addToml(file, block, recorded) {
100
+ const text = readText(file) || '';
101
+ const t = codexTable(text);
102
+ if (t != null) {
103
+ if (recorded !== undefined && recorded.kind === 'toml' && sameTable(t, recorded.block)) {
104
+ // (sliced, not String.replace, whose $& and $' a path may hold; the
105
+ // blank lines after the table kept as they were)
106
+ const after = text.slice(t.at + t.body.length);
107
+ const crlf = t.body.includes('\r\n');
108
+ const lines = block.replace(/\n+$/, '');
109
+ writeAtomic(file, text.slice(0, t.at) + (crlf ? lines.replace(/\n/g, '\r\n') : lines) + (after === '' ? (crlf ? '\r\n' : '\n') : after));
110
+ return {ok: true, record: {kind: 'toml', block, separator: recorded.separator}};
111
+ }
112
+ // (an identical table written by hand, from this ch-local's snippet or an
113
+ // earlier one's: its three lines alone)
114
+ return sameTable(t, block) || sameTable(t, block.split('\n').slice(0, 3).join('\n')) ? BY_HAND
115
+ : {ok: false, why: `${file} already has a [mcp_servers.${SERVER}] table; ch-local leaves it alone`};
116
+ }
117
+ const separator = text === '' ? '' : text.endsWith('\n') ? '\n' : '\n\n';
118
+ writeAtomic(file, text + separator + block);
119
+ return {ok: true, record: {kind: 'toml', block, separator}};
120
+ }
121
+
122
+ async function add(client, io) {
123
+ const where = layout(io.env, io.homedir);
124
+ const other = elsewhere(where);
125
+ if (other[client] != null) { io.stderr.write(`ch-local: ${other[client]}\n`); return 2; }
126
+ if (FILES[client] == null) { io.stderr.write(`ch-local: unknown client "${client}"; one of: ${Object.keys(FILES).join(', ')}\n`); return 2; }
127
+ // (the npx form before an install: the home in words on Windows, as
128
+ // every pre-install hint -- the closing pass on release 1, L3)
129
+ if (!fs.existsSync(where.launcher)) { io.stderr.write(`ch-local: not installed yet: run ${hintCommand(where, 'install --pack ci-failure-triage', io.platform)} first\n`); return 1; }
130
+ const file = FILES[client](io.homedir(), io.env);
131
+ // the native shim where this platform has one (and its shim.json, kept
132
+ // current), else the per-session runtime, said
133
+ const {shim, note} = require('./shim-binary').shimFor({home: where.home, locate: io.locateShim ?? undefined});
134
+ if (shim != null) require('./shim-config').writeShimJson(where.home, {node: io.node, env: io.env, platform: io.platform});
135
+ if (note != null) io.stderr.write(note);
136
+ const {text} = snippet(client, {node: io.node, launcher: where.launcher, home: where.home});
137
+ const record = readRecord(where);
138
+ const recorded = record.entries.find((e) => e.client === client && e.file === file);
139
+ const r = client === 'codex' ? addToml(file, text, recorded) : addJson(file, JSON.parse(text).mcpServers[SERVER], recorded, where, client);
140
+ if (!r.ok) { io.stderr.write(`ch-local: ${r.why}\n`); return 1; }
141
+ if (r.record == null) { io.stdout.write(`"${SERVER}" is already there in ${file}; written by hand, so ch-local does not record it\n`); return 0; }
142
+ record.entries = record.entries.filter((e) => e !== recorded);
143
+ record.entries.push({client, file, key: SERVER, ...r.record, at: new Date().toISOString()});
144
+ writeRecord(where, record);
145
+ io.stdout.write(`added "${SERVER}" to ${file}\n`);
146
+ return 0;
147
+ }
148
+
149
+ // Takes back one recorded entry -> a line saying what happened.
150
+ function removeEntry(e) {
151
+ const text = readText(e.file);
152
+ if (text == null) return `${e.file}: gone already`;
153
+ if (e.kind === 'json') {
154
+ let config;
155
+ try { config = JSON.parse(text); } catch { return `${e.file}: no longer plain JSON; left in place`; }
156
+ const servers = config.mcpServers || {};
157
+ if (servers[e.key] === undefined) return `${e.file}: no "${e.key}" entry any more`;
158
+ if (!same(servers[e.key], e.entry)) return `${e.file}: the "${e.key}" entry was changed since ch-local wrote it; left in place`;
159
+ delete servers[e.key];
160
+ writeAtomic(e.file, JSON.stringify(config, null, 2) + '\n');
161
+ return `${e.file}: removed "${e.key}"`;
162
+ }
163
+ const t = codexTable(text);
164
+ if (t == null || !sameTable(t, e.block)) return `${e.file}: the [mcp_servers.${e.key}] table was changed since ch-local wrote it; left in place`;
165
+ // (its last line's own line end goes with it; the separator ch-local added
166
+ // before it too, unless taking it would join two lines)
167
+ let to = t.at + t.body.length;
168
+ if (text.startsWith('\r\n', to)) to += 2; else if (text.startsWith('\n', to)) to += 1;
169
+ // (the separator as it stands, its line ends turned to CRLF by an editor or not)
170
+ const recordedSep = typeof e.separator === 'string' ? e.separator : '';
171
+ const sep = [recordedSep.replace(/\n/g, '\r\n'), recordedSep].find((x) => x !== '' && text.slice(t.at - x.length, t.at) === x) || '';
172
+ const before = text.slice(0, t.at - sep.length);
173
+ // (a file that had no last line end gets none back; else the line before keeps its own)
174
+ const drop = sep !== '' && (before === '' || before.endsWith('\n') || (to === text.length && recordedSep === '\n\n'));
175
+ writeAtomic(e.file, (drop ? before : text.slice(0, t.at)) + text.slice(to));
176
+ return `${e.file}: removed [mcp_servers.${e.key}]`;
177
+ }
178
+
179
+ module.exports = {add, removeEntry, readRecord, FILES};
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+ // A ch-local command as a printed hint names it (A-chhints; the reviewer's
3
+ // plan approval, 11-20): the home's own launcher, `node "<real path>" <args>`,
4
+ // which runs as printed (nothing puts ch-local on PATH after an npx or a
5
+ // folder install), by the rule the credential line already used (A-firstrun
6
+ // d1: lib/home.js safeLauncher, the runtime's own character check); with
7
+ // no safe launcher -- none installed yet, or a path a shell would read --
8
+ // the bare `ch-local <args>`, which still names the command.
9
+ //
10
+ // Every printed hint that names a ch-local command is made here; a lexical
11
+ // pin (test/command-line.test.js) fails on a bare one written anywhere else.
12
+ const {safeLauncher} = require('./home');
13
+
14
+ // where: the home's layout (lib/home.js layout), or null (none known: the
15
+ // bare form); args: the command after `ch-local`, e.g. 'install' or
16
+ // `credentials add ${m}`
17
+ // (a launcher found is kept per home layout and platform, not resolved per
18
+ // message; none found is asked again, since an install may write it while
19
+ // the same command goes on printing)
20
+ const resolved = new WeakMap();
21
+ function launcherOf(where, platform) {
22
+ let byPlatform = resolved.get(where);
23
+ if (byPlatform == null) { byPlatform = new Map(); resolved.set(where, byPlatform); }
24
+ if (byPlatform.has(platform)) return byPlatform.get(platform);
25
+ const found = safeLauncher(where, platform);
26
+ if (found != null) byPlatform.set(platform, found);
27
+ return found;
28
+ }
29
+ // COUNTINGHOUSE_HOME before an npx command, for a home that isn't the
30
+ // default (POSIX): the home, quoted, or the placeholder where a shell would
31
+ // not read it plainly -- never left out, which would act on ~/.countinghouse
32
+ // (the medium on the follow-up to #129, 3). Windows: '' (A-chlocal-func).
33
+ // -> '' | 'COUNTINGHOUSE_HOME="<home>" '
34
+ function homePrefix(where, platform = process.platform) {
35
+ if (where == null || typeof where !== 'object' || where.home == null || platform === 'win32' || isDefaultHome(where)) return '';
36
+ return `COUNTINGHOUSE_HOME=${folderArg(String(where.home), platform)} `;
37
+ }
38
+
39
+ // (with no launcher yet, before any install, nothing puts ch-local on PATH:
40
+ // the npx form, which runs as printed: the final pass's ch-local part, A11)
41
+ const NPX = `npx ${require('../package.json').name}`;
42
+ function chLocal(where, args, platform = process.platform) {
43
+ const launcher = where != null && typeof where === 'object' && where.launcher != null ? launcherOf(where, platform) : null;
44
+ if (launcher != null) return `node "${launcher}" ${args}`;
45
+ // (a home that isn't the default is named, or the command acts on
46
+ // ~/.countinghouse when pasted into a new terminal: the reviewer on #129,
47
+ // 5. POSIX: before the command. Windows: not yet, which needs words beside
48
+ // each caller's command: A-chlocal-func)
49
+ return `${homePrefix(where, platform)}${NPX} ${args}`;
50
+ }
51
+
52
+ // a folder as a command's argument for the user to copy: quoted, or the
53
+ // placeholder where a shell would not read it plainly
54
+ // (and the characters a terminal shows as nothing: fillers, variation
55
+ // selectors, tag characters -- the reviewer's high on #113)
56
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f"`$\\%!^\u2018-\u201f\u200b-\u200f\u2028\u2029\u202a-\u202e\u2060-\u2069\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff0-\ufffb\u{e0000}-\u{e007f}]/u;
57
+ const folderArg = (p, platform = process.platform) => (typeof p === 'string' && p !== '' && !UNSAFE_ANY.test(platform === 'win32' ? p.replace(/\\/g, '/') : p) ? `"${p}"` : '"<its folder>"');
58
+
59
+ // text a module supplies, as a terminal shows it: every character UNSAFE
60
+ // names as "?" (a control, bidi or invisible one can move the cursor or hide
61
+ // a line), runs of white space as one space, cut at max characters
62
+ // (every control, format and line or paragraph separator character, by
63
+ // its Unicode category, beside the list above: the medium on #113's round 1)
64
+ const UNSAFE_ANY = new RegExp(`${UNSAFE.source}|[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]`, 'u');
65
+ const UNSAFE_ALL = new RegExp(`${UNSAFE.source}|[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]`, 'gu');
66
+ const terminalText = (s, max = 80) => {
67
+ const t = [...String(s).replace(UNSAFE_ALL, '?').replace(/\s+/g, ' ')];
68
+ // (cut by code points: a pair is never split)
69
+ return t.length > max ? `${t.slice(0, max - 1).join('')}…` : t.join('');
70
+ };
71
+
72
+ // The ch-local that is running, as a command to print, for a hint that only
73
+ // this release can carry out (the reviewer on #124: "bring the home to
74
+ // <ours>" run by the home's own, older launcher would reinstall the older
75
+ // release): `node "<this ch-local's bin/ch-local.js>" <args>`, with the home
76
+ // it acts on named when it is not the default one (POSIX: as the variable
77
+ // before the command; Windows: in words, by homeNote). A path a shell would
78
+ // read otherwise gives the bare form.
79
+ function chLocalSelf(where, args, platform = process.platform) {
80
+ const fs = require('node:fs');
81
+ const path = require('node:path');
82
+ let self;
83
+ // (no plain path to this ch-local: the npx form of THIS release, on this
84
+ // home: the medium on A11, 4)
85
+ const pinned = () => `${homePrefix(where, platform)}${NPX}@${require('../package.json').version} ${args}`;
86
+ try { self = fs.realpathSync.native(path.join(__dirname, '..', 'bin', 'ch-local.js')); } catch (err) { return pinned(); }
87
+ const plain = (p) => !UNSAFE_ANY.test(platform === 'win32' ? p.replace(/\\/g, '/') : p);
88
+ if (!plain(self)) return pinned();
89
+ return `${homePrefix(where, platform)}node "${self}" ${args}`;
90
+ }
91
+ // (Windows: the home, when it is not the default, said beside the command)
92
+ const homeNote = (where, platform = process.platform) => (where != null && !isDefaultHome(where, process.env, platform) && platform === 'win32' ? ` (with COUNTINGHOUSE_HOME set to ${folderArg(where.home, platform)})` : '');
93
+ // whether where.home is the default home (lib/home.js defaultHome: on Windows %LOCALAPPDATA%\countinghouse); none known (no
94
+ // LOCALAPPDATA): not the default
95
+ function isDefaultHome(where, env = process.env, platform = process.platform, homedir = require('node:os').homedir) {
96
+ const p = platform === 'win32' ? require('node:path').win32 : require('node:path');
97
+ let def;
98
+ try { def = require('./home').defaultHome(env, homedir, platform); } catch (err) { return false; }
99
+ return platform === 'win32' ? p.resolve(where.home).toLowerCase() === p.resolve(def).toLowerCase() : p.resolve(where.home) === p.resolve(def);
100
+ }
101
+
102
+ // The npx form of the latest release, for a release this ch-local can't read
103
+ // (a later pins format): `npx <package>@latest <args>`, on this home (POSIX:
104
+ // COUNTINGHOUSE_HOME before it when the home isn't the default; Windows: in
105
+ // words, homeNote). -> the command line
106
+ function npxLatest(where, args, platform = process.platform) {
107
+ return `${homePrefix(where, platform)}npx ${require('../package.json').name}@latest ${args}`;
108
+ }
109
+
110
+ // The way to make a running runtime take a change, said where the mode
111
+ // isn't known (status, credentials, settings): a client's own runtime
112
+ // restarts with the client; the shared one, which a client's restart only
113
+ // attaches to again, with `ch-local restart` (A5)
114
+ const restartEither = (where, platform = process.platform) => `restart your client, or with the shared runtime run \`${chLocal(where, 'restart', platform)}\``;
115
+ // The way, one only where the mode is known (inside start: a notice is cut
116
+ // at 200 characters, so both don't fit -- the reviewer's high on #147, M3).
117
+ // shared: true (the shared runtime), false (the client's own), or unknown.
118
+ const restartOne = (where, shared, platform = process.platform) => (shared === true ? `run \`${chLocal(where, 'restart', platform)}\`` : shared === false ? 'restart your client' : restartEither(where, platform));
119
+
120
+ // A command for the user's own terminal as a hint prints it: in backticks,
121
+ // and when it is the npx form (no launcher yet: before any install) on
122
+ // Windows for a home that isn't the default, the home in words after them
123
+ // (homeNote), which POSIX puts before the command (homePrefix). The
124
+ // launcher's form names its home already. -> '`<command>`' + the words
125
+ const hintCommand = (where, args, platform = process.platform) => {
126
+ const c = chLocal(where, args, platform);
127
+ return `\`${c}\`${c.includes(NPX) ? homeNote(where, platform) : ''}`;
128
+ };
129
+
130
+ // A notice within the runtime's 200-character notice cut (code points, as
131
+ // the cut): head, cut before tail where both don't fit, so a command at the
132
+ // end of tail always arrives whole; a tail that leaves no room for a head
133
+ // goes alone (the final pass on #134; #147's M3)
134
+ const NOTICE_MAX = 200;
135
+ // about: the module the line is about, whose name is the last of the
136
+ // explanation to go: the command is never what is dropped.
137
+ function fitNotice(head, tail, max = NOTICE_MAX, about = null) {
138
+ const n = (x) => [...x].length;
139
+ if (n(head) + n(tail) <= max) return `${head}${tail}`;
140
+ const room = max - n(tail);
141
+ const alone = tail.replace(/^(?:[;:,]\s*|\s+)/, '');
142
+ const cut = room < 20 ? null : `${terminalText(head, room)}${tail}`;
143
+ if (about != null && (cut == null || !cut.slice(0, cut.length - tail.length).includes(about))) {
144
+ const left = max - n(about) - 2 - n(tail);
145
+ const named = left >= 20 ? `${about}: ${terminalText(head, left)}${tail}` : `${about}: ${alone}`;
146
+ if (n(named) <= max) return named;
147
+ }
148
+ if (cut == null) return alone;
149
+ // (terminalText makes every backtick in a cut explanation "?": no half
150
+ // command survives there; the tail's command is the one to run)
151
+ return cut;
152
+ }
153
+
154
+ // Any notice within the cut: one whose last command (in backticks) would be
155
+ // cut is fitted around it, the explanation cut before it; one with none is
156
+ // cut at the end (the closing pass's pin on load and unload notices)
157
+ function fitAny(text, max = NOTICE_MAX, about = null, alone = true) {
158
+ if ([...text].length <= max) return text;
159
+ const within = (t) => [...t].length <= max;
160
+ const m = text.match(LAST_COMMAND);
161
+ if (m == null) return terminalText(text, max);
162
+ // (the words that join it go before the name does, the words after it too)
163
+ const [bare, command] = text.match(/(`[^`]*`)[^`]*$/);
164
+ const ways = [fitNotice(text.slice(0, m.index), text.slice(m.index), max, about),
165
+ fitNotice(text.slice(0, text.length - bare.length), bare, max, about),
166
+ ...(alone && about != null ? [`${about}: ${command}`] : []), ...(alone ? [command] : [])].filter(within);
167
+ const named = about != null ? ways.find((t) => t.slice(0, t.indexOf('`')).includes(about)) : null;
168
+ return named || ways[0] || fitNotice(text.slice(0, m.index), text.slice(m.index), max, about);
169
+ }
170
+
171
+ // The last command of a line (in backticks) and what is after it, with the few
172
+ // words that join it to what is before (": run ", "; stopped until ", " (").
173
+ const LAST_COMMAND = /(?:[:;,] ?[^`:;,(]{0,20}| \()?`[^`]*`[^`]*$/;
174
+ const closed = (t) => `${t}${')'.repeat(Math.max(0, t.split('(').length - t.split(')').length))}`;
175
+ // A line without its last command, what it opened closed.
176
+ const beforeCommand = (text) => { const m = text.match(LAST_COMMAND); return m != null && m.index > 0 ? closed(text.slice(0, m.index)) : text; };
177
+
178
+ // The line of a module held back ("not loading m: <reason>"), within the cut:
179
+ // its command whole (fitAny); one that its own folder takes past the cut names
180
+ // the folder in words instead. (A launcher path that leaves no room even so:
181
+ // the reason alone, to its last whole clause, with no command in part.)
182
+ function fitHeld(line, about = null, max = NOTICE_MAX) {
183
+ const within = (t) => [...t].length <= max;
184
+ const words = line.replace(/ add-module "[^"`]*"/, ' add-module "<its folder>"');
185
+ // (an add-module command past the cut with what follows it: in words before it goes alone)
186
+ const fitted = fitAny(line, max, about, words === line);
187
+ if (within(fitted)) return fitted;
188
+ const inWords = fitAny(words, max, about);
189
+ if (within(inWords)) return inWords;
190
+ const m = line.match(/`[^`]*`[^`]*$/);
191
+ if (m == null) return inWords;
192
+ const count = (t, c) => t.split(c).length - 1;
193
+ for (let reason = line.slice(0, m.index); ;) {
194
+ const shorter = reason.replace(/\s*[:;,(][^:;,(]*$/, '');
195
+ // (never nothing: the runtime drops an empty notice and answers ok)
196
+ if (shorter === reason) return terminalText(reason, max) || about || '';
197
+ reason = shorter;
198
+ if (within(closed(reason)) && count(reason, '`') % 2 === 0) return closed(reason);
199
+ }
200
+ }
201
+
202
+ module.exports = {fitAny, fitHeld, beforeCommand, fitNotice, NOTICE_MAX, chLocal, chLocalSelf, npxLatest, homePrefix, homeNote, isDefaultHome, folderArg, terminalText, UNSAFE_ANY, NPX, hintCommand, restartEither, restartOne};
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+ // ch-local conditions --for <client pid> --home <absolute home>
3
+ // (countinghouse's shared-runtime design, #236, section 5): the client's own
4
+ // inputs, for the native shim, which runs this once per connection and
5
+ // before each form, and carries the line as its `client` frame. It runs with
6
+ // the client's environment (less NODE_* and npm_config_*) in the client's
7
+ // working directory. It prints one JSON line and exits 0:
8
+ //
9
+ // {"status": "ok", "conditions": "yes" | "no", "repo": "owner/name" | null,
10
+ // "token": null}
11
+ //
12
+ // - conditions: the existing scan of the client (lib/client-conditions.js),
13
+ // the process <pid> and its ancestors, its configuration and its project;
14
+ // - repo: cwd's GitHub origin (start's own reading);
15
+ // - token: always null, and no `credentials`: a credential is a module's
16
+ // own, in the store, and a client's environment never gives one (#413
17
+ // section 6.9; L5a), so no session chooses one the shared runtime lacks.
18
+ // The field stays for the shim, which reads null as the daemon's.
19
+ // - why, when conditions is "no": {reason, at?}, the scan's closed reason and
20
+ // where it saw it, under the home only ("~/..."), for the runtime's latch.
21
+ //
22
+ // Anything that keeps the answer from being known (a bad argument) exits
23
+ // non-zero with no line: the shim counts it as failed.
24
+ const fs = require('node:fs');
25
+ const path = require('node:path');
26
+ const {clientConditions, readClientContext, clientLines, CLAUDE_CODE, REASONS} = require('./client-conditions');
27
+ const {cleanText} = require('./clean-text');
28
+ const {repoFromRemote, readOrigin} = require('./start');
29
+
30
+ // the most the shim reads of the line (shim/src/child.rs)
31
+ const MAX_LINE_BYTES = 4096;
32
+
33
+ class Unknown extends Error {}
34
+
35
+ // Why the client was judged able to answer forms by itself, or not
36
+ // interactive (the runtime's latch says so in its refusal, B2): the reason,
37
+ // one of client-conditions.js's closed REASONS, and where it was seen as a
38
+ // path under the user's home directory, "~/..." (cut and cleaned). A path
39
+ // outside the home is never sent: it may carry another name, and this text
40
+ // reaches the agent. -> {reason, at?} or null.
41
+ //
42
+ // Both are compared by real path (a home through a link, as cwd and the
43
+ // project usually are, keeps its project hits' place). A home that is a
44
+ // filesystem root or one level below it (HOME=/ or /home: a service, a
45
+ // container) is no boundary: every path would read as under it, others'
46
+ // homes too, so no place is sent.
47
+ // a path by its real path: its deepest part that exists resolved (a link,
48
+ // macOS's /var, a Windows short name), the rest re-appended
49
+ const real = (p) => {
50
+ let at = path.resolve(p);
51
+ const rest = [];
52
+ for (;;) {
53
+ try { return path.join(fs.realpathSync.native(at), ...rest); } catch (e) { /* not there: one up */ }
54
+ const up = path.dirname(at);
55
+ if (up === at) return path.resolve(p);
56
+ rest.unshift(path.basename(at));
57
+ at = up;
58
+ }
59
+ };
60
+ function whyOf(verdict, homeDir) {
61
+ if (verdict == null || !REASONS.includes(verdict.why)) return null;
62
+ const out = {reason: verdict.why};
63
+ if (typeof verdict.at !== 'string' || typeof homeDir !== 'string' || !path.isAbsolute(verdict.at) || !path.isAbsolute(homeDir)) return out;
64
+ const home = real(homeDir);
65
+ // a home at most one level below a root is no boundary (/home holds every
66
+ // user's): judged on the path as given AND on its real path, since a link
67
+ // can deepen it (macOS's /home is /System/Volumes/Data/home)
68
+ const depth = (p) => p.slice(path.parse(p).root.length).split(path.sep).filter(Boolean).length;
69
+ if (depth(path.resolve(homeDir)) < 2 || depth(home) < 2) return out;
70
+ const rel = path.relative(home, real(verdict.at));
71
+ const parts = rel.split(path.sep);
72
+ // no "..", no empty segment, and no backslash in a name (a separator on
73
+ // Windows, where the runtime reads this): the runtime refuses each, as
74
+ // the shared vectors do (conditionsWhy)
75
+ if (rel === '' || path.isAbsolute(rel) || parts.some((p) => p === '' || p === '..' || p.includes('\\'))) return out;
76
+ out.at = cleanText(`~/${parts.join('/')}`, 200);
77
+ return out;
78
+ }
79
+
80
+ // {pid, home} -> exit code
81
+ async function conditions({pid, home}, io) {
82
+ try {
83
+ const n = Number(pid);
84
+ if (!Number.isInteger(n) || n <= 0) throw new Unknown('--for needs a process id');
85
+ const context = await (io.clientAncestry !== undefined ? io.clientAncestry : readClientContext(n, 8, io.platform, io.env));
86
+ const lines = Array.isArray(context) ? context : clientLines(context != null ? context.lines : null);
87
+ const policyPresent = context != null && !Array.isArray(context) && context.policyPresent === true;
88
+ // the home, read once: the scan's and the why's
89
+ const homeDir = typeof io.homedir === 'function' ? io.homedir() : io.homedir;
90
+ const verdict = clientConditions({client: {name: CLAUDE_CODE, version: '0.0.0'}, home: homeDir,
91
+ cwd: io.cwd, env: io.env, platform: io.platform, managedPresent: policyPresent, parentCommandLines: () => lines, withAt: true,
92
+ // tests only: their world's root bounds the walk up (never set in use)
93
+ ...(io.conditionsStopAt != null ? {stopAt: io.conditionsStopAt} : {})});
94
+ const repo = repoFromRemote(readOrigin(io.cwd));
95
+ const why = verdict.mayElicit === true ? null : whyOf(verdict, homeDir);
96
+ const lineWith = (w) => JSON.stringify({status: 'ok', conditions: verdict.mayElicit === true ? 'yes' : 'no', repo, token: null,
97
+ ...(w != null ? {why: w} : {})});
98
+ const fits = (l) => Buffer.byteLength(l, 'utf8') + 1 <= MAX_LINE_BYTES;
99
+ // the why is an extra: a line too long with it goes without it, and only
100
+ // a line too long without it fails (the shim takes at most this much)
101
+ let line = lineWith(why);
102
+ if (!fits(line)) line = lineWith(null);
103
+ if (!fits(line)) throw new Unknown(`the line would be over ${MAX_LINE_BYTES} bytes`);
104
+ io.stdout.write(`${line}\n`);
105
+ return 0;
106
+ } catch (e) {
107
+ if (e instanceof Unknown) {
108
+ io.stderr.write(`ch-local conditions: ${e.message}\n`);
109
+ return 1;
110
+ }
111
+ io.stderr.write('ch-local conditions: the client checks could not run\n');
112
+ return 1;
113
+ }
114
+ }
115
+
116
+ module.exports = {conditions, whyOf, MAX_LINE_BYTES};
package/lib/control.js ADDED
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+ // start's side of the runtime's control channel (packs in place, part 2, plan
3
+ // Task B3; countinghouse's lib/control-channel.js): requests sent one at a
4
+ // time over the child's IPC fd, each answered by its id. A runtime that does
5
+ // not take control requests (one older than the channel) never answers: each
6
+ // request then fails at its timeout, and start says a restart is needed.
7
+ const TIMEOUT_MS = 30000;
8
+ // The runtime says {type: 'ready'} once it listens (countinghouse #210): a
9
+ // request sent before that was lost. Requests wait for it, and at most this
10
+ // long for an older runtime that never says it.
11
+ const READY_MS = 10000;
12
+
13
+ // child: {send(msg), onMessage(fn)}. -> {request(msg) -> Promise<reply>,
14
+ // onRequest(type, async (msg) -> fields)}
15
+ //
16
+ // The runtime asks start too (countinghouse part 3 P2, Task 4: may-elicit):
17
+ // {id: 'r<n>', type, ...}, answered {id, ok: true, ...fields} or {id, ok:
18
+ // false, code}, with no type (the runtime routes a reply by that).
19
+ function controlClient(child, {timeoutMs, readyMs} = {}) {
20
+ if (!(Number.isFinite(timeoutMs) && timeoutMs > 0)) timeoutMs = TIMEOUT_MS;
21
+ if (!(Number.isFinite(readyMs) && readyMs >= 0)) readyMs = READY_MS;
22
+ let next = 1;
23
+ let isReady = null;
24
+ const ready = new Promise((resolve) => { isReady = resolve; });
25
+ const readyTimer = setTimeout(() => isReady(), readyMs);
26
+ if (typeof readyTimer.unref === 'function') readyTimer.unref();
27
+ let chain = ready;
28
+ const waiting = new Map();
29
+ const handlers = new Map();
30
+ const tellers = new Map();
31
+ const answer = (m) => { try { child.send(m); } catch (err) { /* the runtime has gone */ } };
32
+ child.onMessage((m) => {
33
+ if (m != null && m.type === 'ready' && m.id === undefined) { clearTimeout(readyTimer); isReady(); return; }
34
+ // an unasked message, {type, ...} with no id (a session runtime's
35
+ // 'listening', countinghouse C3): to its teller, if one is set
36
+ if (m != null && m.id === undefined && typeof m.type === 'string') {
37
+ const fn = tellers.get(m.type);
38
+ if (fn != null) { try { fn(m); } catch (err) { /* the teller's own */ } }
39
+ return;
40
+ }
41
+ if (m != null && typeof m.id === 'string' && /^r\d+$/.test(m.id) && typeof m.type === 'string') {
42
+ const handler = handlers.get(m.type);
43
+ if (handler == null) { answer({id: m.id, ok: false, code: 'CONTROL_UNKNOWN'}); return; }
44
+ Promise.resolve().then(() => handler(m)).then(
45
+ (fields) => answer({...fields, id: m.id, ok: true}),
46
+ (err) => answer({id: m.id, ok: false, code: (err != null && typeof err.code === 'string') ? err.code : 'CONTROL_FAILED'}));
47
+ return;
48
+ }
49
+ const w = (m != null) ? waiting.get(m.id) : null;
50
+ if (w == null) return;
51
+ waiting.delete(m.id);
52
+ clearTimeout(w.timer);
53
+ w.resolve(m);
54
+ });
55
+ let closed = false;
56
+ const once = (msg) => new Promise((resolve) => {
57
+ if (closed) return resolve({ok: false, code: 'CONTROL_GONE', message: 'the runtime has ended'});
58
+ const id = next++;
59
+ const timer = setTimeout(() => {
60
+ waiting.delete(id);
61
+ resolve({id, ok: false, code: 'CONTROL_NO_ANSWER', message: `the runtime did not answer within ${timeoutMs} ms`});
62
+ }, timeoutMs);
63
+ if (typeof timer.unref === 'function') timer.unref();
64
+ waiting.set(id, {resolve, timer});
65
+ try {
66
+ child.send({...msg, id});
67
+ } catch (err) {
68
+ waiting.delete(id);
69
+ clearTimeout(timer);
70
+ resolve({id, ok: false, code: 'CONTROL_SEND_FAILED', message: err.message});
71
+ }
72
+ });
73
+ return {
74
+ onRequest: (type, fn) => { handlers.set(type, fn); },
75
+ onTold: (type, fn) => { tellers.set(type, fn); },
76
+ // the runtime has ended: every pending request is settled now,
77
+ // CONTROL_GONE, never left to its timeout, and later ones answer the same
78
+ close: () => {
79
+ closed = true;
80
+ clearTimeout(readyTimer);
81
+ isReady();
82
+ for (const [id, w] of waiting) { clearTimeout(w.timer); w.resolve({id, ok: false, code: 'CONTROL_GONE', message: 'the runtime has ended'}); }
83
+ waiting.clear();
84
+ },
85
+ request: (msg) => {
86
+ const p = chain.then(() => once(msg));
87
+ chain = p.catch(() => {});
88
+ return p;
89
+ }
90
+ };
91
+ }
92
+
93
+ // Never silent (countinghouse part 3, section 5): a text said on stderr and
94
+ // told to the client as a notice (the next result of any tool, and
95
+ // notifications/message). Buffered until the control channel is attached,
96
+ // then sent; one the runtime did not take is said on stderr, so nothing is
97
+ // lost unsaid. told: every text so far, so the applier repeats none of
98
+ // start's. A notice goes to every open session (countinghouse M5a: no
99
+ // session has a view of its own); it names the module it is about, or null
100
+ // (the module form's notice: {type: 'notice', module, text}).
101
+ // -> {tell(text, {module, fit, about}?), attach(control), told}
102
+ function teller(say) {
103
+ const buffered = [];
104
+ const told = new Set();
105
+ let control = null;
106
+ // never a rejection left unhandled (that ends start on Node 15 and later):
107
+ // a request that rejects is said, like one the runtime did not take
108
+ const notTold = (text, code) => say(`the client was not told: ${text} (${code || 'failed'})`);
109
+ const send = ({text, module}) => {
110
+ let p;
111
+ try { p = Promise.resolve(control.request({type: 'notice', module, text})); } catch (e) { p = Promise.reject(e); }
112
+ p.then((r) => { if (r == null || r.ok !== true) notTold(text, r && r.code); }, (e) => notTold(text, e && e.code));
113
+ };
114
+ return {
115
+ told,
116
+ // (said whole; told fitted to the runtime's notice cut, its command whole.
117
+ // A line with no command is told as it is, and so is one whose writer says
118
+ // so, as where it quotes a stored value or puts its commands first: the
119
+ // runtime cuts it at the end. about: the module it is about, named as long
120
+ // as its name fits beside the command)
121
+ tell(text, {module = null, fit = true, about = null} = {}) {
122
+ say(text);
123
+ told.add(text);
124
+ const notice = fit && /`[^`]*`/.test(text) ? require('./command-line').fitHeld(text, about) : text;
125
+ if (control != null) send({text: notice, module}); else buffered.push({text: notice, module});
126
+ },
127
+ attach(c) {
128
+ control = c;
129
+ buffered.splice(0).forEach(send);
130
+ }
131
+ };
132
+ }
133
+
134
+ module.exports = {controlClient, teller, TIMEOUT_MS, READY_MS};