@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
package/src/log.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  /**
2
2
  * Structured logger wrapping pino — applies kit's charmtone theme
3
- * colors to stderr output.
3
+ * colors to stderr output (or an injected `output` sink).
4
4
  *
5
5
  * API: `logger.info('msg', 'key', val, 'key2', val2)` (variadic key-value)
6
6
  * This matches Go's charm/log API, not pino's native object API.
7
7
  * Pino handles transports, serialization, and performance under the hood.
8
+ *
9
+ * The `-V` count → level mapping and the `--quiet` override both come from
10
+ * the parity contract (`parity.json` verbosity block), so the level
11
+ * vocabulary stays identical across the Go, TypeScript and Python ports.
8
12
  */
9
13
 
10
14
  import pino from 'pino';
11
15
 
16
+ import { parity, type ParityData } from './tui/parity.js';
17
+
12
18
  // ---------------------------------------------------------------------------
13
19
  // Types
14
20
  // ---------------------------------------------------------------------------
@@ -19,11 +25,64 @@ export interface Logger {
19
25
  error(msg: string, ...keyvals: any[]): void;
20
26
  debug(msg: string, ...keyvals: any[]): void;
21
27
  trace(msg: string, ...keyvals: any[]): void;
28
+ /**
29
+ * Info-level line marked as a success: label `SUCC` in the theme's
30
+ * success colour. Filtered exactly like `info` (not a new level).
31
+ */
32
+ success(msg: string, ...keyvals: any[]): void;
22
33
  }
23
34
 
35
+ /** Minimal sink the logger writes rendered lines to. */
36
+ export interface LogOutput {
37
+ write(chunk: string): unknown;
38
+ }
39
+
40
+ /** Kit level vocabulary (same spellings as Go/py and `parity.json`). */
41
+ export type LogLevelName = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
42
+
43
+ /** One log line, as handed to a custom `formatter`. */
44
+ export interface LogRecord {
45
+ level: LogLevelName;
46
+ msg: string;
47
+ /** Key-value pairs in call order (after pino serialization). */
48
+ fields: Record<string, unknown>;
49
+ /** Set on `success()` lines, whose `level` is `'info'`. */
50
+ kind?: 'success';
51
+ }
52
+
53
+ /** Renders a record to one line; a missing trailing newline is appended. */
54
+ export type LogFormatter = (rec: LogRecord) => string;
55
+
24
56
  export interface LoggerOptions {
25
57
  quiet?: boolean;
26
58
  noColor?: boolean;
59
+ /**
60
+ * Explicit threshold; wins over the factory default and the `-V` count.
61
+ * `'silent'` drops everything. `quiet` only raises it (to the contract's
62
+ * `quiet_override`), never lowers it — same as Go's `WithLevel`.
63
+ * TS-only option; not a parity verbosity entry.
64
+ */
65
+ level?: LogLevelName | 'silent';
66
+ /**
67
+ * Where rendered lines go. Defaults to `process.stderr`, resolved at
68
+ * write time. Mirrors Go's `(*log.Logger).SetOutput`; useful for
69
+ * capturing output in tests.
70
+ */
71
+ output?: LogOutput;
72
+ /**
73
+ * Line format. `'text'` (default) is `LEVEL msg k=v`; `'json'` is one
74
+ * object per line shaped like Go charm/log's JSONFormatter:
75
+ * `{"level":"info","msg":"...",...kv}` (no time/pid/hostname, no ANSI).
76
+ * `success` lines carry `"level":"info","kind":"success"`. Selected by
77
+ * this option only — no env var or flag.
78
+ */
79
+ format?: 'text' | 'json';
80
+ /**
81
+ * TS extension point: render each line yourself (glyph prefixes, house
82
+ * styles). The returned string is written as-is, plus `\n` if missing.
83
+ * Wins over `format` and `noColor`; level filtering still applies.
84
+ */
85
+ formatter?: LogFormatter;
27
86
  }
28
87
 
29
88
  // ---------------------------------------------------------------------------
@@ -34,6 +93,7 @@ const CHERRY = [0xed, 0x4a, 0x5e] as const;
34
93
  const YAM = [0xe5, 0xa1, 0x4e] as const;
35
94
  const SQUID = [0x85, 0x81, 0x83] as const;
36
95
  const SMOKE = [0xbf, 0xbc, 0xc8] as const;
96
+ const GUAC = [0x52, 0xcf, 0x84] as const; // theme.success
37
97
 
38
98
  type RGB = readonly [number, number, number];
39
99
 
@@ -49,35 +109,103 @@ function bold(text: string): string {
49
109
  // Kit-themed pino transport
50
110
  // ---------------------------------------------------------------------------
51
111
 
112
+ /**
113
+ * pino level number for `success`. One above info so it passes and drops
114
+ * at exactly the same thresholds as info (no kit level sits at 31).
115
+ */
116
+ const SUCCESS_LEVEL = 31;
117
+
52
118
  const LEVEL_STYLES: Record<number, { label: string; color: RGB; bold: boolean }> = {
53
119
  10: { label: 'TRAC', color: SMOKE, bold: false },
54
120
  20: { label: 'DEBU', color: SMOKE, bold: false },
55
121
  30: { label: 'INFO', color: SQUID, bold: false },
122
+ [SUCCESS_LEVEL]: { label: 'SUCC', color: GUAC, bold: false },
56
123
  40: { label: 'WARN', color: YAM, bold: true },
57
124
  50: { label: 'ERRO', color: CHERRY, bold: true },
58
125
  60: { label: 'ERRO', color: CHERRY, bold: true },
59
126
  };
60
127
 
61
- function kitTransport(noColor: boolean): pino.DestinationStream {
128
+ /** pino level number → kit level name (charm/log spellings). */
129
+ const LEVEL_NAMES: Record<number, LogLevelName> = {
130
+ 10: 'trace', 20: 'debug', 30: 'info', [SUCCESS_LEVEL]: 'info',
131
+ 40: 'warn', 50: 'error', 60: 'fatal',
132
+ };
133
+
134
+ /** pino bookkeeping keys that are never user fields. */
135
+ const RESERVED_KEYS = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'v']);
136
+
137
+ /** A parsed log line, before rendering. */
138
+ interface ParsedRecord extends LogRecord {
139
+ levelNum: number;
140
+ }
141
+
142
+ function parseRecord(chunk: string): ParsedRecord {
143
+ const obj = JSON.parse(chunk);
144
+ const fields: Record<string, unknown> = {};
145
+ for (const [k, v] of Object.entries(obj)) {
146
+ if (!RESERVED_KEYS.has(k)) fields[k] = v;
147
+ }
148
+ const levelNum = LEVEL_STYLES[obj.level] ? obj.level : 30;
149
+ return {
150
+ levelNum,
151
+ level: LEVEL_NAMES[levelNum],
152
+ msg: obj.msg ?? '',
153
+ fields,
154
+ ...(levelNum === SUCCESS_LEVEL ? { kind: 'success' as const } : {}),
155
+ };
156
+ }
157
+
158
+ function renderText(rec: ParsedRecord, noColor: boolean): string {
159
+ const style = LEVEL_STYLES[rec.levelNum];
160
+ let prefix = noColor ? style.label : fg(style.color, style.label);
161
+ if (style.bold && !noColor) prefix = bold(prefix);
162
+
163
+ const kvParts: string[] = [];
164
+ for (const [k, v] of Object.entries(rec.fields)) {
165
+ const sv = String(v);
166
+ kvParts.push(sv.includes(' ') ? `${k}="${sv}"` : `${k}=${sv}`);
167
+ }
168
+ const kv = kvParts.length ? ' ' + kvParts.join(' ') : '';
169
+ return `${prefix} ${rec.msg}${kv}\n`;
170
+ }
171
+
172
+ function renderJSON(rec: ParsedRecord): string {
173
+ const out: Record<string, unknown> = { level: rec.level, msg: rec.msg };
174
+ if (rec.kind) out.kind = rec.kind;
175
+ Object.assign(out, rec.fields);
176
+ if (rec.kind) out.kind = rec.kind; // a user `kind` field never masks it
177
+ return JSON.stringify(out) + '\n';
178
+ }
179
+
180
+ function renderCustom(rec: ParsedRecord, formatter: LogFormatter): string {
181
+ const { levelNum: _levelNum, ...pub } = rec;
182
+ const line = formatter(pub);
183
+ return line.endsWith('\n') ? line : line + '\n';
184
+ }
185
+
186
+ interface TransportOptions {
187
+ noColor: boolean;
188
+ format: 'text' | 'json';
189
+ formatter?: LogFormatter;
190
+ output?: LogOutput;
191
+ }
192
+
193
+ function render(rec: ParsedRecord, o: TransportOptions): string {
194
+ if (o.formatter) return renderCustom(rec, o.formatter);
195
+ return o.format === 'json' ? renderJSON(rec) : renderText(rec, o.noColor);
196
+ }
197
+
198
+ function kitTransport(o: TransportOptions): pino.DestinationStream {
199
+ // Resolve the default lazily so callers that swap process.stderr after
200
+ // construction keep seeing their writes.
201
+ const out = (): LogOutput => o.output ?? process.stderr;
62
202
  return {
63
203
  write(chunk: string): void {
64
204
  try {
65
- const obj = JSON.parse(chunk);
66
- const style = LEVEL_STYLES[obj.level] ?? LEVEL_STYLES[30];
67
- let prefix = noColor ? style.label : fg(style.color, style.label);
68
- if (style.bold && !noColor) prefix = bold(prefix);
69
-
70
- const msg = obj.msg ?? '';
71
- const kvParts: string[] = [];
72
- for (const [k, v] of Object.entries(obj)) {
73
- if (['level', 'time', 'pid', 'hostname', 'msg', 'v'].includes(k)) continue;
74
- const sv = String(v);
75
- kvParts.push(sv.includes(' ') ? `${k}="${sv}"` : `${k}=${sv}`);
76
- }
77
- const kv = kvParts.length ? ' ' + kvParts.join(' ') : '';
78
- process.stderr.write(`${prefix} ${msg}${kv}\n`);
205
+ const rec = parseRecord(chunk);
206
+ out().write(render(rec, o));
79
207
  } catch {
80
- process.stderr.write(chunk);
208
+ out().write(chunk);
81
209
  }
82
210
  },
83
211
  };
@@ -96,17 +224,81 @@ function kvToObj(keyvals: any[]): Record<string, any> {
96
224
  return obj;
97
225
  }
98
226
 
227
+ // ---------------------------------------------------------------------------
228
+ // Parity contract → pino level names
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /** Pino level names the contract's level vocabulary may resolve to. */
232
+ const PINO_LEVELS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
233
+
234
+ /**
235
+ * Resolve a contract level name to a pino level name.
236
+ *
237
+ * The names are the cross-language vocabulary declared in `parity.json`;
238
+ * pino happens to use the same spellings, so this is a membership check
239
+ * rather than a translation table (Go needs one because charm/log has no
240
+ * `trace`).
241
+ */
242
+ function levelByName(name: string): string | undefined {
243
+ return PINO_LEVELS.has(name) ? name : undefined;
244
+ }
245
+
246
+ /**
247
+ * Resolve a `-V` count against a parity contract's `verbosity.levels`
248
+ * table. Counts above the highest declared key clamp to that key's level;
249
+ * an empty or unresolvable table falls back to `info`.
250
+ *
251
+ * Taking the contract as a parameter (rather than reading the module-level
252
+ * `parity`) keeps the mapping testable against a constructed `ParityData`
253
+ * without mutating the shared `parity.json`.
254
+ */
255
+ export function verbosityLevel(d: ParityData, verbose: number): string {
256
+ const levels = d.verbosity?.levels ?? {};
257
+ // Highest declared count at or below `verbose` wins.
258
+ let best = -1;
259
+ for (const key of Object.keys(levels)) {
260
+ const n = Number(key);
261
+ if (!Number.isInteger(n)) continue;
262
+ if (n <= verbose && n > best) best = n;
263
+ }
264
+ if (best < 0) return 'info';
265
+ return levelByName(levels[String(best)]) ?? 'info';
266
+ }
267
+
268
+ /**
269
+ * Resolve a parity contract's `verbosity.quiet_override` to a pino level
270
+ * name. An unrecognized or absent override falls back to `warn`.
271
+ */
272
+ export function quietLevel(d: ParityData): string {
273
+ return levelByName(d.verbosity?.quiet_override ?? '') ?? 'warn';
274
+ }
275
+
99
276
  // ---------------------------------------------------------------------------
100
277
  // Factory
101
278
  // ---------------------------------------------------------------------------
102
279
 
103
- export function createLogger(opts?: LoggerOptions): Logger {
104
- const quiet = opts?.quiet ?? false;
105
- const noColor = opts?.noColor ?? false;
280
+ const LEVEL_RANK: Record<string, number> = {
281
+ trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60, silent: Infinity,
282
+ };
106
283
 
107
- const p = pino({
108
- level: quiet ? 'warn' : 'debug',
109
- }, kitTransport(noColor));
284
+ /** Apply `quiet` to a threshold: raise to the quiet override, never lower. */
285
+ function applyQuiet(level: string, quiet: boolean): string {
286
+ if (!quiet) return level;
287
+ const q = quietLevel(parity);
288
+ return LEVEL_RANK[level] < LEVEL_RANK[q] ? q : level;
289
+ }
290
+
291
+ function build(opts: LoggerOptions, defaultLevel: string): Logger {
292
+ const level = applyQuiet(opts.level ?? defaultLevel, opts.quiet ?? false);
293
+ const p = pino<'success'>(
294
+ { level, customLevels: { success: SUCCESS_LEVEL } },
295
+ kitTransport({
296
+ noColor: opts.noColor ?? false,
297
+ format: opts.format ?? 'text',
298
+ formatter: opts.formatter,
299
+ output: opts.output,
300
+ }),
301
+ );
110
302
 
111
303
  return {
112
304
  info: (msg, ...kv) => p.info(kvToObj(kv), msg),
@@ -114,42 +306,29 @@ export function createLogger(opts?: LoggerOptions): Logger {
114
306
  error: (msg, ...kv) => p.error(kvToObj(kv), msg),
115
307
  debug: (msg, ...kv) => p.debug(kvToObj(kv), msg),
116
308
  trace: (msg, ...kv) => p.trace(kvToObj(kv), msg),
309
+ success: (msg, ...kv) => p.success(kvToObj(kv), msg),
117
310
  };
118
311
  }
119
312
 
313
+ export function createLogger(opts?: LoggerOptions): Logger {
314
+ // Note: the default level here is `debug`, NOT the contract's
315
+ // zero-verbosity level. createLogger predates the verbosity contract and
316
+ // is deliberately chattier than `withVerbose({ verbose: 0 })`; only the
317
+ // quiet override is contract-declared, so only it is wired.
318
+ return build(opts ?? {}, 'debug');
319
+ }
320
+
120
321
  // ---------------------------------------------------------------------------
121
322
  // Verbose-aware factory
122
323
  // ---------------------------------------------------------------------------
123
324
 
124
325
  /**
125
- * Map verbose count to pino level: 0=info, 1=debug, 2+=trace.
126
- * Quiet overrides to warn regardless of verbose count.
326
+ * Map verbose count to a pino level through the parity contract's
327
+ * `verbosity.levels` table. An explicit `level` wins over the count.
328
+ * Quiet raises to the contract's `quiet_override` level.
127
329
  */
128
330
  export function withVerbose(
129
331
  opts: LoggerOptions & { verbose?: number },
130
332
  ): Logger {
131
- const quiet = opts.quiet ?? false;
132
- const noColor = opts.noColor ?? false;
133
- const v = opts.verbose ?? 0;
134
-
135
- let level: string;
136
- if (quiet) {
137
- level = 'warn';
138
- } else if (v >= 2) {
139
- level = 'trace';
140
- } else if (v >= 1) {
141
- level = 'debug';
142
- } else {
143
- level = 'info';
144
- }
145
-
146
- const p = pino({ level }, kitTransport(noColor));
147
-
148
- return {
149
- info: (msg, ...kv) => p.info(kvToObj(kv), msg),
150
- warn: (msg, ...kv) => p.warn(kvToObj(kv), msg),
151
- error: (msg, ...kv) => p.error(kvToObj(kv), msg),
152
- debug: (msg, ...kv) => p.debug(kvToObj(kv), msg),
153
- trace: (msg, ...kv) => p.trace(kvToObj(kv), msg),
154
- };
333
+ return build(opts, verbosityLevel(parity, opts.verbose ?? 0));
155
334
  }
@@ -0,0 +1,63 @@
1
+ # mcp
2
+
3
+ ## What it answers
4
+
5
+ How a Commander command tree is served over the Model Context Protocol from one mount that answers both the `2024-11-05` handshake era and the `2026-07-28` stateless era, choosing per request. Wrong module for REST or ConnectRPC surfaces (`@hop-top/kit/api`, `@hop-top/kit/rpc`) and for the service lifecycle that hosts the mount (`@hop-top/kit/serve`).
6
+
7
+ ## Use it when
8
+
9
+ - expose leaves as MCP tools: `commanderBridge(root, { run })` then `createMcpHandler(bridge, opts)`
10
+ - bind to your own HTTP stack: the handler is `(McpHttpRequest) => Promise<McpHttpResponse>`; node:http, hono, express, fastify or a Worker is your call
11
+ - serve a host that spawns the tool: `serveStdio(bridge)` (or `serveStdio(handler)`), newline-delimited JSON-RPC on stdin/stdout, `done` resolves when stdin ends
12
+ - gate destructive tools: `policy` option, `defaultPolicy()` blocks remote destructive calls
13
+ - require confirmation on the modern era: `headerConfirmationGate` or `ElicitationConfirmGate`
14
+ - name tools for a host that refuses dots (`widget_add`, not `widget.add`): `toolNameSeparator: '_'`
15
+ - record every refusal the mount makes (auth, confirmation, destructive ceiling): `audit: (record: McpAuditRecord) => void`
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { Command } from 'commander';
21
+ import { createMcpHandler, commanderBridge } from '@hop-top/kit/mcp';
22
+
23
+ const root = new Command('app');
24
+ root.command('ping').description('Ping the server');
25
+ const bridge = commanderBridge(root, {
26
+ run: async () => ({ stdout: 'pong\n', exitCode: 0 }),
27
+ });
28
+ const handler = createMcpHandler(bridge, {
29
+ serverInfo: { name: 'app', version: '0.1.0' },
30
+ });
31
+ const res = await handler({
32
+ method: 'POST',
33
+ headers: { 'content-type': 'application/json' },
34
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
35
+ });
36
+ console.log(res.status, res.body);
37
+ ```
38
+
39
+ ## Contract
40
+
41
+ - Wire bytes are pinned by [`sdk/tests/cross-lang/fixtures/mcp-wire.json`](../../../tests/cross-lang/fixtures/mcp-wire.json), compared as raw bytes; [`conformance.test.ts`](conformance.test.ts) replays both `cases` and `sequences`.
42
+ - Protocol layer is `@modelcontextprotocol/core` + `@modelcontextprotocol/server` (v2). The v1 `@modelcontextprotocol/sdk` cannot serve `2026-07-28` and is not a dependency.
43
+ - Era detection follows the marker set and precedence chain in [`dispatch.ts`](dispatch.ts), not the SDK's own classifier.
44
+ - stdio ([`stdio.ts`](stdio.ts)) drives the same era dispatch with no header layer: the `2026-07-28` header checks are skipped, notifications are never answered, batches are refused.
45
+ - `tools/list` re-reads the bridge's leaves per request; caching the leaf set fails the sequence fixture.
46
+ - `commanderBridge` requires `run`: kit does not capture a command's output for you.
47
+ - Tool names join the leaf path with `toolNameSeparator` (default `.`) and split back on it. The mount throws on an empty separator and, for any other than `.`, on a command name containing it (`data_sync` under `_`). Names are not otherwise rewritten or length-checked.
48
+ - Tasks extension: `TASKS_SUPPORTED` is `false`; `discoverCapabilities` reports it.
49
+ - `audit` ([`audit.ts`](audit.ts)) is the port of Go's bridge sinks for this surface: called after a refusal is decided and before the response is written, never changing the wire bytes; a throw is swallowed. `error` is Go's sentinel string (`MCP_AUDIT_*`).
50
+ - Parity: [`contracts/parity/README.md`](../../../../contracts/parity/README.md), section "MCP wire contract".
51
+
52
+ ## Neighbours
53
+
54
+ - `@hop-top/kit/serve`: service lifecycle hosting the mount
55
+ - `@hop-top/kit/api`, `@hop-top/kit/rpc`: REST and ConnectRPC clients
56
+ - `@hop-top/kit/safety`: `--force` delegation guard the policy builds on
57
+ - Go reference: [`go/transport/mcpsdk`](../../../../go/transport/mcpsdk/README.md); Python port: [`hop_top_kit/mcp`](../../../py/hop_top_kit/mcp/README.md)
58
+
59
+ ## See also
60
+
61
+ - [`sdk/ts/README.md`](../../README.md), section "MCP surface": options, safety, confirmation, scope
62
+ - [`docs/adopters/guides/serve-mcp-from-any-sdk.md`](../../../../docs/adopters/guides/serve-mcp-from-any-sdk.md)
63
+ - [`docs/adopters/guides/expose-cli-over-mcp.md`](../../../../docs/adopters/guides/expose-cli-over-mcp.md): the Go reference
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Positional arguments under a non-default toolNameSeparator, on both
3
+ * eras over HTTP and over serveStdio: the separator only renames the
4
+ * tool, the "args" array still reaches Invocation.args in order.
5
+ */
6
+
7
+ import { PassThrough } from 'node:stream';
8
+ import { Command } from 'commander';
9
+ import { describe, expect, it } from 'vitest';
10
+
11
+ import { commanderBridge } from './bridge.js';
12
+ import { createMcpHandler } from './dispatch.js';
13
+ import { serveStdio } from './stdio.js';
14
+ import type { Invocation, InvokeResult, McpBridge } from './types.js';
15
+
16
+ const MODERN_META = {
17
+ 'io.modelcontextprotocol/clientCapabilities': {},
18
+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
19
+ };
20
+
21
+ /** root -> item -> add <name> [note] --count <n> */
22
+ function bridge(): McpBridge {
23
+ const root = new Command('root');
24
+ root
25
+ .command('item')
26
+ .command('add')
27
+ .description('Add an item')
28
+ .argument('<name>')
29
+ .argument('[note]')
30
+ .option('--count <n>', 'how many');
31
+ const run = (inv: Invocation): InvokeResult => ({
32
+ stdout: `${inv.path.join(' ')} ${JSON.stringify(inv.args ?? [])} ${JSON.stringify(inv.flags ?? {})}\n`,
33
+ exitCode: 0,
34
+ });
35
+ return commanderBridge(root, { run });
36
+ }
37
+
38
+ function text(result: Record<string, unknown>): string {
39
+ return (result.content as Array<{ text: string }>).map((c) => c.text).join('');
40
+ }
41
+
42
+ describe('positional args with toolNameSeparator', () => {
43
+ const handler = createMcpHandler(bridge(), { toolNameSeparator: '_' });
44
+ const post = (body: unknown, headers: Record<string, string> = {}) =>
45
+ handler({ method: 'POST', headers, body: JSON.stringify(body) });
46
+
47
+ it('publishes the args property under the separated name', async () => {
48
+ const res = await post({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
49
+ const tools = JSON.parse(res.body).result.tools as Array<{
50
+ name: string;
51
+ inputSchema: { properties: Record<string, unknown>; required?: string[] };
52
+ }>;
53
+ const add = tools.find((t) => t.name === 'item_add');
54
+ expect(add).toBeDefined();
55
+ expect(add?.inputSchema.properties.args).toMatchObject({ type: 'array', minItems: 1 });
56
+ expect(add?.inputSchema.required).toContain('args');
57
+ });
58
+
59
+ it('splits args out on a legacy call', async () => {
60
+ const res = await post({
61
+ jsonrpc: '2.0',
62
+ id: 2,
63
+ method: 'tools/call',
64
+ params: { name: 'item_add', arguments: { args: ['bolt', '-x'], count: '2' } },
65
+ });
66
+ const body = JSON.parse(res.body);
67
+ expect(body.result.isError).toBe(false);
68
+ expect(text(body.result)).toBe('item add ["bolt","-x"] {"count":"2"}\n');
69
+ });
70
+
71
+ it('splits args out on a modern call', async () => {
72
+ const res = await post(
73
+ {
74
+ jsonrpc: '2.0',
75
+ id: 3,
76
+ method: 'tools/call',
77
+ params: { name: 'item_add', arguments: { args: ['bolt'] }, _meta: MODERN_META },
78
+ },
79
+ {
80
+ 'MCP-Protocol-Version': '2026-07-28',
81
+ 'Mcp-Method': 'tools/call',
82
+ 'Mcp-Name': 'item_add',
83
+ },
84
+ );
85
+ const body = JSON.parse(res.body);
86
+ expect(body.error).toBeUndefined();
87
+ expect(body.result.isError).toBe(false);
88
+ expect(text(body.result)).toBe('item add ["bolt"] {}\n');
89
+ });
90
+
91
+ it('refuses a missing required argument on both eras', async () => {
92
+ const legacy = JSON.parse(
93
+ (
94
+ await post({
95
+ jsonrpc: '2.0',
96
+ id: 4,
97
+ method: 'tools/call',
98
+ params: { name: 'item_add', arguments: {} },
99
+ })
100
+ ).body,
101
+ );
102
+ expect(legacy.result.isError).toBe(true);
103
+ expect(text(legacy.result)).toContain('missing required argument: name');
104
+
105
+ const modern = JSON.parse(
106
+ (
107
+ await post(
108
+ {
109
+ jsonrpc: '2.0',
110
+ id: 5,
111
+ method: 'tools/call',
112
+ params: { name: 'item_add', arguments: {}, _meta: MODERN_META },
113
+ },
114
+ {
115
+ 'MCP-Protocol-Version': '2026-07-28',
116
+ 'Mcp-Method': 'tools/call',
117
+ 'Mcp-Name': 'item_add',
118
+ },
119
+ )
120
+ ).body,
121
+ );
122
+ expect(modern.result.isError).toBe(true);
123
+ expect(text(modern.result)).toContain('missing required argument: name');
124
+ });
125
+
126
+ it('carries args over serveStdio on both eras', async () => {
127
+ const input = new PassThrough();
128
+ const output = new PassThrough();
129
+ let out = '';
130
+ output.on('data', (c: Buffer) => (out += c.toString('utf8')));
131
+ const server = serveStdio(bridge(), {
132
+ input,
133
+ output,
134
+ log: new PassThrough(),
135
+ mount: { toolNameSeparator: '_' },
136
+ });
137
+ input.write(
138
+ `${JSON.stringify({
139
+ jsonrpc: '2.0',
140
+ id: 1,
141
+ method: 'tools/call',
142
+ params: { name: 'item_add', arguments: { args: ['bolt', 'spare'] } },
143
+ })}\n`,
144
+ );
145
+ input.write(
146
+ `${JSON.stringify({
147
+ jsonrpc: '2.0',
148
+ id: 2,
149
+ method: 'tools/call',
150
+ params: { name: 'item_add', arguments: { args: ['nut'] }, _meta: MODERN_META },
151
+ })}\n`,
152
+ );
153
+ input.end();
154
+ await server.done;
155
+ const got = new Map<number, Record<string, unknown>>();
156
+ for (const line of out.split('\n').filter((l) => l !== '')) {
157
+ const m = JSON.parse(line) as { id: number; result: Record<string, unknown> };
158
+ got.set(m.id, m.result);
159
+ }
160
+ expect(text(got.get(1) ?? {})).toBe('item add ["bolt","spare"] {}\n');
161
+ expect(got.get(2)).toMatchObject({ resultType: 'complete', isError: false });
162
+ expect(text(got.get(2) ?? {})).toBe('item add ["nut"] {}\n');
163
+ });
164
+ });