@kubb/cli 5.0.0-beta.4 → 5.0.0-beta.40

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 (155) hide show
  1. package/README.md +198 -36
  2. package/dist/agent-DQerNyd8.cjs +70 -0
  3. package/dist/agent-DQerNyd8.cjs.map +1 -0
  4. package/dist/agent-ZKJkTTGN.js +68 -0
  5. package/dist/agent-ZKJkTTGN.js.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-CRm0XQPb.js} +1 -0
  7. package/dist/constants-84a47qA-.js +35 -0
  8. package/dist/constants-84a47qA-.js.map +1 -0
  9. package/dist/constants-AHhyFH15.cjs +139 -0
  10. package/dist/constants-AHhyFH15.cjs.map +1 -0
  11. package/dist/constants-BtmponZ3.cjs +58 -0
  12. package/dist/constants-BtmponZ3.cjs.map +1 -0
  13. package/dist/constants-C94RKp3A.js +116 -0
  14. package/dist/constants-C94RKp3A.js.map +1 -0
  15. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  16. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  17. package/dist/{define-Ctii4bel.js → define-DNG1U8ha.js} +2 -2
  18. package/dist/{define-Ctii4bel.js.map → define-DNG1U8ha.js.map} +1 -1
  19. package/dist/{errors-CjPmyZHy.js → errors-CoxrNXaA.js} +2 -2
  20. package/dist/{errors-CjPmyZHy.js.map → errors-CoxrNXaA.js.map} +1 -1
  21. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  22. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  23. package/dist/generate-40x9PP4o.js +77 -0
  24. package/dist/generate-40x9PP4o.js.map +1 -0
  25. package/dist/generate-DQLvFw4z.cjs +76 -0
  26. package/dist/generate-DQLvFw4z.cjs.map +1 -0
  27. package/dist/index.cjs +23 -14
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +23 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/init-CT9RChdK.js +53 -0
  33. package/dist/init-CT9RChdK.js.map +1 -0
  34. package/dist/init-sEaUN7Dj.cjs +53 -0
  35. package/dist/init-sEaUN7Dj.cjs.map +1 -0
  36. package/dist/mcp-Siyb6fTT.cjs +39 -0
  37. package/dist/mcp-Siyb6fTT.cjs.map +1 -0
  38. package/dist/mcp-cjPrOeot.js +39 -0
  39. package/dist/mcp-cjPrOeot.js.map +1 -0
  40. package/dist/{package-BapVyQ-w.cjs → package-BJ6qam2Y.cjs} +2 -2
  41. package/dist/package-BJ6qam2Y.cjs.map +1 -0
  42. package/dist/package-CR5vEK4K.js +6 -0
  43. package/dist/package-CR5vEK4K.js.map +1 -0
  44. package/dist/{agent-sdYBBgrd.js → run-BQ3Qj0xB.js} +46 -43
  45. package/dist/run-BQ3Qj0xB.js.map +1 -0
  46. package/dist/run-BQzoaxjR.js +32 -0
  47. package/dist/run-BQzoaxjR.js.map +1 -0
  48. package/dist/run-CGf0KEts.js +51 -0
  49. package/dist/run-CGf0KEts.js.map +1 -0
  50. package/dist/{generate-CNrRLY4n.js → run-CHZKHTv0.js} +832 -828
  51. package/dist/run-CHZKHTv0.js.map +1 -0
  52. package/dist/{init-CZ5Xq2Hd.cjs → run-C_NMctua.cjs} +107 -149
  53. package/dist/run-C_NMctua.cjs.map +1 -0
  54. package/dist/{generate-B1Pa2ho-.cjs → run-CcQawFNK.cjs} +784 -780
  55. package/dist/run-CcQawFNK.cjs.map +1 -0
  56. package/dist/run-CkTpemme.cjs +52 -0
  57. package/dist/run-CkTpemme.cjs.map +1 -0
  58. package/dist/run-Cl4SrSob.cjs +33 -0
  59. package/dist/run-Cl4SrSob.cjs.map +1 -0
  60. package/dist/{agent-B4cAAab2.cjs → run-D-s2LdlW.cjs} +46 -43
  61. package/dist/run-D-s2LdlW.cjs.map +1 -0
  62. package/dist/{init-eNRlotJK.js → run-D8dCWepS.js} +107 -149
  63. package/dist/run-D8dCWepS.js.map +1 -0
  64. package/dist/{shell-DLzN4fRo.js → shell-BrqyJdB7.js} +2 -2
  65. package/dist/{shell-DLzN4fRo.js.map → shell-BrqyJdB7.js.map} +1 -1
  66. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  67. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  68. package/dist/validate-8pgfxUTy.js +26 -0
  69. package/dist/validate-8pgfxUTy.js.map +1 -0
  70. package/dist/validate-CstV7Pc2.cjs +26 -0
  71. package/dist/validate-CstV7Pc2.cjs.map +1 -0
  72. package/package.json +16 -15
  73. package/src/commands/agent/start.ts +10 -7
  74. package/src/commands/agent.ts +3 -1
  75. package/src/commands/generate.ts +21 -13
  76. package/src/commands/init.ts +34 -3
  77. package/src/commands/mcp.ts +28 -4
  78. package/src/commands/validate.ts +6 -4
  79. package/src/constants.ts +3 -74
  80. package/src/index.ts +6 -4
  81. package/src/loggers/clackLogger.ts +143 -181
  82. package/src/loggers/githubActionsLogger.ts +119 -121
  83. package/src/loggers/plainLogger.ts +50 -100
  84. package/src/loggers/types.ts +6 -0
  85. package/src/loggers/utils.ts +190 -18
  86. package/src/runners/agent/run.ts +113 -0
  87. package/src/runners/agent/utils.ts +98 -0
  88. package/src/runners/generate/run.ts +411 -0
  89. package/src/runners/generate/utils.ts +222 -0
  90. package/src/runners/init/run.ts +212 -0
  91. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  92. package/src/runners/mcp/run.ts +37 -0
  93. package/src/runners/validate/run.ts +63 -0
  94. package/dist/agent-B4cAAab2.cjs.map +0 -1
  95. package/dist/agent-CR6Z96og.js +0 -56
  96. package/dist/agent-CR6Z96og.js.map +0 -1
  97. package/dist/agent-Dmxzqg4d.cjs +0 -58
  98. package/dist/agent-Dmxzqg4d.cjs.map +0 -1
  99. package/dist/agent-sdYBBgrd.js.map +0 -1
  100. package/dist/constants-CnDXa1R6.cjs +0 -148
  101. package/dist/constants-CnDXa1R6.cjs.map +0 -1
  102. package/dist/constants-aL3CP_Wq.js +0 -95
  103. package/dist/constants-aL3CP_Wq.js.map +0 -1
  104. package/dist/generate-B1Pa2ho-.cjs.map +0 -1
  105. package/dist/generate-BDGOOsBM.cjs +0 -65
  106. package/dist/generate-BDGOOsBM.cjs.map +0 -1
  107. package/dist/generate-CNrRLY4n.js.map +0 -1
  108. package/dist/generate-DuhxPLGr.js +0 -66
  109. package/dist/generate-DuhxPLGr.js.map +0 -1
  110. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  111. package/dist/init-CnZXHrbq.js +0 -25
  112. package/dist/init-CnZXHrbq.js.map +0 -1
  113. package/dist/init-NYJSZJSb.cjs +0 -25
  114. package/dist/init-NYJSZJSb.cjs.map +0 -1
  115. package/dist/init-eNRlotJK.js.map +0 -1
  116. package/dist/mcp-CYOgxB82.cjs +0 -47
  117. package/dist/mcp-CYOgxB82.cjs.map +0 -1
  118. package/dist/mcp-CdFWyrwi.cjs +0 -16
  119. package/dist/mcp-CdFWyrwi.cjs.map +0 -1
  120. package/dist/mcp-DhSxuDMD.js +0 -16
  121. package/dist/mcp-DhSxuDMD.js.map +0 -1
  122. package/dist/mcp-DmJm3TrU.js +0 -46
  123. package/dist/mcp-DmJm3TrU.js.map +0 -1
  124. package/dist/package-BapVyQ-w.cjs.map +0 -1
  125. package/dist/package-DyJE-qNq.js +0 -6
  126. package/dist/package-DyJE-qNq.js.map +0 -1
  127. package/dist/telemetry-DN95_2pF.cjs +0 -282
  128. package/dist/telemetry-DN95_2pF.cjs.map +0 -1
  129. package/dist/telemetry-LgT_sdPe.js +0 -245
  130. package/dist/telemetry-LgT_sdPe.js.map +0 -1
  131. package/dist/validate-C6npXzel.cjs +0 -25
  132. package/dist/validate-C6npXzel.cjs.map +0 -1
  133. package/dist/validate-kLJoT_hi.js +0 -33
  134. package/dist/validate-kLJoT_hi.js.map +0 -1
  135. package/dist/validate-n38Rh-Y7.js +0 -25
  136. package/dist/validate-n38Rh-Y7.js.map +0 -1
  137. package/dist/validate-yKKzqEZ5.cjs +0 -34
  138. package/dist/validate-yKKzqEZ5.cjs.map +0 -1
  139. package/src/loggers/fileSystemLogger.ts +0 -138
  140. package/src/runners/agent.ts +0 -155
  141. package/src/runners/generate.ts +0 -333
  142. package/src/runners/init.ts +0 -296
  143. package/src/runners/mcp.ts +0 -51
  144. package/src/runners/validate.ts +0 -39
  145. package/src/types.ts +0 -11
  146. package/src/utils/Writables.ts +0 -17
  147. package/src/utils/executeHooks.ts +0 -45
  148. package/src/utils/flags.ts +0 -9
  149. package/src/utils/getConfig.ts +0 -10
  150. package/src/utils/getCosmiConfig.ts +0 -80
  151. package/src/utils/getSummary.ts +0 -68
  152. package/src/utils/runHook.ts +0 -91
  153. package/src/utils/telemetry.ts +0 -273
  154. package/src/utils/watcher.ts +0 -19
  155. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
@@ -1,13 +1,58 @@
1
+ import process from 'node:process'
1
2
  import { styleText } from 'node:util'
2
- import { canUseTTY, formatHrtime, isGitHubActions } from '@internals/utils'
3
- import type { Logger, LoggerContext, LoggerOptions } from '@kubb/core'
3
+ import { canUseTTY, formatHrtime, getElapsedMs, isGitHubActions } from '@internals/utils'
4
+ import type { Logger, LoggerContext, LoggerOptions, Reporter, ReporterContext } from '@kubb/core'
4
5
  import { logLevel as logLevelMap } from '@kubb/core'
5
6
  import { clackLogger } from './clackLogger.ts'
6
- import { fileSystemLogger } from './fileSystemLogger.ts'
7
7
  import { githubActionsLogger } from './githubActionsLogger.ts'
8
8
  import { plainLogger } from './plainLogger.ts'
9
9
  import type { LoggerType } from './types.ts'
10
10
 
11
+ /**
12
+ * Output sink for a hook subprocess, controlling how streamed lines and exit output are forwarded.
13
+ */
14
+ type HookOutputSink = {
15
+ /**
16
+ * Called for each streamed stdout line while the hook runs.
17
+ */
18
+ onLine?: (line: string) => void
19
+ /**
20
+ * Called with stderr content after the hook exits with a non-zero code.
21
+ */
22
+ onStderr?: (text: string) => void
23
+ /**
24
+ * Called with stdout content after the hook exits with a non-zero code.
25
+ */
26
+ onStdout?: (text: string) => void
27
+ }
28
+
29
+ /**
30
+ * Output sink combined with stream control for a hook subprocess.
31
+ */
32
+ export type HookSinkOptions = HookOutputSink & {
33
+ /**
34
+ * When `true`, streams process output line-by-line via `onLine`.
35
+ *
36
+ * @default false
37
+ */
38
+ stream?: boolean
39
+ }
40
+
41
+ /**
42
+ * Factory called once per hook command to build the output sink and streaming flag.
43
+ * The function should set up any logger UI (e.g., spinner) and return callbacks that forward subprocess output to it.
44
+ *
45
+ * `hookId` is the same id passed to `kubb:hook:start` / `kubb:hook:end`, letting the logger
46
+ * correlate streamed output with the active UI element (e.g., a clack `taskLog`) it created in the start handler.
47
+ */
48
+ export type HookSinkFactory = (commandWithArgs: string, hookId: string) => HookSinkOptions | null
49
+
50
+ /**
51
+ * Logger variant that may return a {@link HookSinkFactory} from `install`.
52
+ * The factory is forwarded to hook execution so the logger controls subprocess output routing.
53
+ */
54
+ type CLILogger = Logger<LoggerOptions, HookSinkFactory | undefined | null>
55
+
11
56
  /**
12
57
  * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
13
58
  * Shared across all logger adapters to avoid duplication.
@@ -26,11 +71,29 @@ export function formatMessage(message: string, logLevel: number): string {
26
71
  }
27
72
 
28
73
  type ProgressState = {
74
+ /**
75
+ * Total number of plugins scheduled for this generation run.
76
+ */
29
77
  totalPlugins: number
78
+ /**
79
+ * Number of plugins that have finished without error.
80
+ */
30
81
  completedPlugins: number
82
+ /**
83
+ * Number of plugins that exited with an error.
84
+ */
31
85
  failedPlugins: number
86
+ /**
87
+ * Total number of files expected to be written.
88
+ */
32
89
  totalFiles: number
90
+ /**
91
+ * Number of files written so far.
92
+ */
33
93
  processedFiles: number
94
+ /**
95
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
96
+ */
34
97
  hrStart: [number, number]
35
98
  }
36
99
 
@@ -39,7 +102,7 @@ type ProgressState = {
39
102
  * Returns null when there is nothing to display.
40
103
  */
41
104
  export function buildProgressLine(state: ProgressState): string | null {
42
- const parts: string[] = []
105
+ const parts: Array<string> = []
43
106
  const duration = formatHrtime(state.hrStart)
44
107
 
45
108
  if (state.totalPlugins > 0) {
@@ -62,11 +125,85 @@ export function buildProgressLine(state: ProgressState): string | null {
62
125
  return parts.join(styleText('dim', ' | '))
63
126
  }
64
127
 
128
+ /**
129
+ * Creates the per-run progress counters shared by the clack and GitHub Actions loggers.
130
+ */
131
+ export function createProgressCounters(): ProgressState {
132
+ return {
133
+ totalPlugins: 0,
134
+ completedPlugins: 0,
135
+ failedPlugins: 0,
136
+ totalFiles: 0,
137
+ processedFiles: 0,
138
+ hrStart: process.hrtime(),
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Resets the progress counters in place at the start/end of a generation run.
144
+ */
145
+ export function resetProgressCounters(state: ProgressState): void {
146
+ state.totalPlugins = 0
147
+ state.completedPlugins = 0
148
+ state.failedPlugins = 0
149
+ state.totalFiles = 0
150
+ state.processedFiles = 0
151
+ state.hrStart = process.hrtime()
152
+ }
153
+
154
+ /**
155
+ * Records a finished plugin against the progress counters.
156
+ */
157
+ export function recordPluginResult(state: ProgressState, success: boolean): void {
158
+ if (success) {
159
+ state.completedPlugins++
160
+ } else {
161
+ state.failedPlugins++
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Tracks per-hook start times so a logger can report a hook's elapsed duration.
167
+ * Used by the loggers that key timing by hook `id` (GitHub Actions, plain).
168
+ */
169
+ export type HookTimer = {
170
+ start(id: string): void
171
+ /**
172
+ * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.
173
+ */
174
+ end(id: string): number | undefined
175
+ clear(): void
176
+ }
177
+
178
+ /**
179
+ * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
180
+ */
181
+ export function createHookTimer(): HookTimer {
182
+ const starts = new Map<string, [number, number]>()
183
+
184
+ return {
185
+ start(id: string): void {
186
+ starts.set(id, process.hrtime())
187
+ },
188
+ end(id: string): number | undefined {
189
+ const hrStart = starts.get(id)
190
+ if (!hrStart) {
191
+ return undefined
192
+ }
193
+ starts.delete(id)
194
+ return getElapsedMs(hrStart)
195
+ },
196
+ clear(): void {
197
+ starts.clear()
198
+ },
199
+ }
200
+ }
201
+
65
202
  /**
66
203
  * Join a command and its optional args into a single display string.
67
204
  * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
68
205
  */
69
- export function formatCommandWithArgs(command: string, args?: readonly string[]): string {
206
+ export function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {
70
207
  return args?.length ? `${command} ${args.join(' ')}` : command
71
208
  }
72
209
 
@@ -80,27 +217,62 @@ function detectLogger(): LoggerType {
80
217
  return 'plain'
81
218
  }
82
219
 
83
- const logMapper = {
220
+ const logMapper: Record<LoggerType, CLILogger> = {
84
221
  clack: clackLogger,
85
222
  plain: plainLogger,
86
223
  'github-actions': githubActionsLogger,
87
- } as const satisfies Record<LoggerType, Logger>
88
-
89
- export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<void> {
90
- const type = detectLogger()
224
+ }
91
225
 
92
- const logger = logMapper[type] as Logger
226
+ /**
227
+ * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
228
+ * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
229
+ */
230
+ export function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {
231
+ context.on('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {
232
+ await reporter.report({ config, diagnostics, filesCreated, status, hrStart }, ctx)
233
+ })
93
234
 
94
- if (!logger) {
95
- throw new Error(`Unknown adapter type: ${type}`)
235
+ if (reporter.drain) {
236
+ context.on('kubb:lifecycle:end', () => reporter.drain?.(ctx))
96
237
  }
238
+ }
239
+
240
+ /**
241
+ * Installs the live logger (the TUI view) and the given reporters (the output), returning the
242
+ * terminal logger's hook sink when one was installed. The reporters are already selected by the
243
+ * caller (the CLI maps `--reporter` to names via `selectReporters`); this only wires them.
244
+ *
245
+ * Loggers and reporters are independent: the `cli` reporter also activates the env logger summary.
246
+ * The `json` reporter owns stdout, so the live logger and the `cli` summary are suppressed whenever
247
+ * `json` is among the reporters, even if `cli` is also listed.
248
+ */
249
+ async function setupReporters(
250
+ context: LoggerContext,
251
+ { logLevel, reporters }: LoggerOptions & { reporters: ReadonlyArray<Reporter> },
252
+ ): Promise<HookSinkFactory | null> {
253
+ const hasJson = reporters.some((reporter) => reporter.name === 'json')
254
+ const ctx: ReporterContext = { logLevel }
255
+
256
+ let makeSink: HookSinkFactory | null = null
97
257
 
98
- // Install primary logger
99
- const cleanup = await logger.install(context, { logLevel })
258
+ for (const reporter of reporters) {
259
+ if (reporter.name === 'cli') {
260
+ if (hasJson) {
261
+ continue
262
+ }
263
+ const type = detectLogger()
264
+ const logger = logMapper[type]
265
+ if (!logger) {
266
+ throw new Error(`Unknown adapter type: ${type}`)
267
+ }
268
+ const sink = await logger.install(context, { logLevel })
269
+ makeSink = typeof sink === 'function' ? sink : null
270
+ }
100
271
 
101
- if (logLevel >= logLevelMap.debug) {
102
- await fileSystemLogger.install(context, { logLevel })
272
+ installReporter(context, reporter, ctx)
103
273
  }
104
274
 
105
- return cleanup
275
+ return makeSink
106
276
  }
277
+
278
+ export default setupReporters
@@ -0,0 +1,113 @@
1
+ import { createRequire } from 'node:module'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { styleText } from 'node:util'
5
+ import * as clack from '@clack/prompts'
6
+ import { spawnAsync, getErrorMessage } from '@internals/utils'
7
+ import { Telemetry } from '@kubb/core'
8
+ import { agentDefaults } from '../../constants.ts'
9
+ import { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'
10
+
11
+ type AgentStartOptions = {
12
+ /**
13
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
14
+ */
15
+ port: string | undefined
16
+ /**
17
+ * Hostname the HTTP server binds to.
18
+ *
19
+ * @default 'localhost'
20
+ */
21
+ host: string
22
+ /**
23
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
24
+ */
25
+ configPath: string | undefined
26
+ /**
27
+ * Grants the agent permission to write generated files to the filesystem.
28
+ */
29
+ allowWrite: boolean
30
+ /**
31
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
32
+ */
33
+ allowAll: boolean
34
+ /**
35
+ * Current `@kubb/cli` version string, used for the telemetry payload.
36
+ */
37
+ version: string
38
+ }
39
+
40
+ /**
41
+ * Spawns the Kubb Agent HTTP server as a Node.js subprocess.
42
+ * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.
43
+ */
44
+ export async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {
45
+ const hrStart = process.hrtime()
46
+ const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'agent', kubbVersion: version, hrStart, status }))
47
+
48
+ try {
49
+ // Load .env file into process.env using Node.js built-in (v20.12.0+)
50
+ try {
51
+ process.loadEnvFile()
52
+ } catch {
53
+ // .env file may not exist. Ignore
54
+ }
55
+
56
+ // Resolve the @kubb/agent package path, createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)
57
+ const require = createRequire(import.meta.url)
58
+ let agentPkgPath: string
59
+ try {
60
+ agentPkgPath = require.resolve('@kubb/agent/package.json')
61
+ } catch (_e) {
62
+ console.error(styleText('red', 'The @kubb/agent package is not installed.'))
63
+ console.error('')
64
+ console.error('Install it with:')
65
+ console.error(styleText('cyan', ' npm install @kubb/agent'))
66
+ console.error(styleText('cyan', ' # or'))
67
+ console.error(styleText('cyan', ' pnpm install @kubb/agent'))
68
+ console.error('')
69
+ process.exit(1)
70
+ }
71
+ const agentDir = path.dirname(agentPkgPath)
72
+ const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)
73
+
74
+ const resolvedEnv = resolveAgentStartEnvironment({
75
+ port,
76
+ host,
77
+ configPath,
78
+ allowWrite,
79
+ allowAll,
80
+ })
81
+ const numericPort = Number(resolvedEnv.port)
82
+
83
+ if (!Number.isInteger(numericPort) || numericPort <= 0) {
84
+ throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`)
85
+ }
86
+
87
+ clack.log.step(styleText('cyan', 'Starting agent server...'))
88
+ clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))
89
+ clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))
90
+ clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))
91
+ if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {
92
+ clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))
93
+ }
94
+
95
+ if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {
96
+ clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))
97
+ process.exit(1)
98
+ }
99
+
100
+ // Spawns the server as a detached background process so the CLI can exit independently.
101
+ await spawnAsync('node', [serverPath], {
102
+ env: resolvedEnv.env,
103
+ cwd: process.cwd(),
104
+ })
105
+
106
+ await report('success')
107
+ } catch (error) {
108
+ await report('failed')
109
+ clack.log.error(styleText('red', 'Failed to start agent server'))
110
+ clack.log.error(getErrorMessage(error))
111
+ process.exit(1)
112
+ }
113
+ }
@@ -0,0 +1,98 @@
1
+ import net from 'node:net'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { agentDefaults } from '../../constants.ts'
5
+
6
+ type AgentStartEnvironmentInput = {
7
+ /**
8
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
9
+ */
10
+ port: string | undefined
11
+ /**
12
+ * Hostname the HTTP server binds to.
13
+ */
14
+ host: string
15
+ /**
16
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
17
+ */
18
+ configPath: string | undefined
19
+ /**
20
+ * Grants the agent permission to write generated files to the filesystem.
21
+ */
22
+ allowWrite: boolean
23
+ /**
24
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
25
+ */
26
+ allowAll: boolean
27
+ }
28
+
29
+ type ResolvedAgentStartEnvironment = {
30
+ /**
31
+ * Final port string after merging CLI flag, `PORT` env var, and the default.
32
+ */
33
+ port: string
34
+ /**
35
+ * Final hostname after merging CLI flag, `HOST` env var, and the default.
36
+ */
37
+ host: string
38
+ /**
39
+ * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.
40
+ */
41
+ allowWrite: boolean
42
+ /**
43
+ * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.
44
+ */
45
+ allowAll: boolean
46
+ /**
47
+ * Absolute path to the Kubb config file passed to the agent subprocess.
48
+ */
49
+ agentConfigPath: string
50
+ /**
51
+ * Merged `process.env` object with all resolved agent environment variables applied.
52
+ */
53
+ env: NodeJS.ProcessEnv
54
+ }
55
+
56
+ /**
57
+ * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
58
+ */
59
+ export function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {
60
+ const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port
61
+ const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)
62
+ const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'
63
+ const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'
64
+ const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()
65
+ const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)
66
+
67
+ return {
68
+ port: resolvedPort,
69
+ host: resolvedHost,
70
+ allowWrite: resolvedAllowWrite,
71
+ allowAll: resolvedAllowAll,
72
+ agentConfigPath,
73
+ env: {
74
+ ...process.env,
75
+ PORT: resolvedPort,
76
+ HOST: resolvedHost,
77
+ KUBB_AGENT_ROOT: agentRoot,
78
+ KUBB_AGENT_CONFIG: agentConfigPath,
79
+ KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
80
+ KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
81
+ KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,
82
+ KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,
83
+ KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,
84
+ },
85
+ }
86
+ }
87
+
88
+ export function isPortAvailable(port: number, host: string): Promise<boolean> {
89
+ return new Promise((resolve) => {
90
+ const server = net.createServer()
91
+ server.once('error', () => resolve(false))
92
+ server.once('listening', () => {
93
+ server.close()
94
+ resolve(true)
95
+ })
96
+ server.listen(port, host)
97
+ })
98
+ }