@pikku/core 0.9.11 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/errors/errors.d.ts +2 -0
  3. package/dist/errors/errors.js +6 -0
  4. package/dist/function/function-runner.d.ts +15 -9
  5. package/dist/function/function-runner.js +55 -37
  6. package/dist/function/functions.types.d.ts +67 -1
  7. package/dist/function/functions.types.js +43 -1
  8. package/dist/index.d.ts +2 -6
  9. package/dist/index.js +2 -6
  10. package/dist/middleware/auth-apikey.d.ts +19 -11
  11. package/dist/middleware/auth-apikey.js +33 -33
  12. package/dist/middleware/auth-bearer.d.ts +34 -7
  13. package/dist/middleware/auth-bearer.js +53 -36
  14. package/dist/middleware/auth-cookie.d.ts +30 -12
  15. package/dist/middleware/auth-cookie.js +51 -43
  16. package/dist/middleware/timeout.d.ts +6 -2
  17. package/dist/middleware/timeout.js +7 -9
  18. package/dist/middleware-runner.d.ts +46 -43
  19. package/dist/middleware-runner.js +100 -69
  20. package/dist/permissions.d.ts +82 -20
  21. package/dist/permissions.js +176 -62
  22. package/dist/pikku-state.d.ts +46 -1
  23. package/dist/pikku-state.js +16 -1
  24. package/dist/services/content-service.d.ts +2 -3
  25. package/dist/services/index.d.ts +0 -1
  26. package/dist/services/index.js +0 -1
  27. package/dist/services/local-content.d.ts +2 -4
  28. package/dist/types/core.types.d.ts +110 -4
  29. package/dist/types/core.types.js +44 -1
  30. package/dist/utils.d.ts +1 -1
  31. package/dist/wirings/channel/channel-handler.d.ts +2 -2
  32. package/dist/wirings/channel/channel-handler.js +16 -12
  33. package/dist/wirings/channel/channel-runner.d.ts +2 -2
  34. package/dist/wirings/channel/channel-runner.js +6 -24
  35. package/dist/wirings/channel/channel.types.d.ts +15 -14
  36. package/dist/wirings/channel/local/local-channel-runner.js +12 -12
  37. package/dist/wirings/channel/serverless/serverless-channel-runner.js +7 -8
  38. package/dist/wirings/cli/channel/cli-channel-runner.d.ts +12 -0
  39. package/dist/wirings/cli/channel/cli-channel-runner.js +83 -0
  40. package/dist/wirings/cli/channel/index.d.ts +1 -0
  41. package/dist/wirings/cli/channel/index.js +1 -0
  42. package/dist/wirings/cli/cli-runner.d.ts +42 -0
  43. package/dist/wirings/cli/cli-runner.js +352 -0
  44. package/dist/wirings/cli/cli.types.d.ts +204 -0
  45. package/dist/wirings/cli/cli.types.js +1 -0
  46. package/dist/wirings/cli/command-parser.d.ts +19 -0
  47. package/dist/wirings/cli/command-parser.js +403 -0
  48. package/dist/wirings/cli/index.d.ts +5 -0
  49. package/dist/wirings/cli/index.js +5 -0
  50. package/dist/wirings/http/http-runner.d.ts +59 -10
  51. package/dist/wirings/http/http-runner.js +138 -131
  52. package/dist/wirings/http/http.types.d.ts +11 -10
  53. package/dist/wirings/http/index.d.ts +1 -1
  54. package/dist/wirings/http/index.js +1 -1
  55. package/dist/wirings/http/pikku-fetch-http-response.js +3 -1
  56. package/dist/wirings/http/routers/http-router.d.ts +0 -2
  57. package/dist/wirings/http/routers/path-to-regex.d.ts +1 -1
  58. package/dist/wirings/http/routers/path-to-regex.js +5 -34
  59. package/dist/wirings/mcp/mcp-endpoint-registry.d.ts +1 -1
  60. package/dist/wirings/mcp/mcp-runner.d.ts +4 -5
  61. package/dist/wirings/mcp/mcp-runner.js +32 -34
  62. package/dist/wirings/mcp/mcp.types.d.ts +38 -14
  63. package/dist/wirings/queue/queue-runner.d.ts +2 -2
  64. package/dist/wirings/queue/queue-runner.js +25 -27
  65. package/dist/wirings/queue/queue.types.d.ts +6 -5
  66. package/dist/wirings/rpc/index.d.ts +1 -1
  67. package/dist/wirings/rpc/index.js +1 -1
  68. package/dist/wirings/rpc/rpc-runner.d.ts +6 -18
  69. package/dist/wirings/rpc/rpc-runner.js +13 -8
  70. package/dist/wirings/scheduler/scheduler-runner.d.ts +2 -2
  71. package/dist/wirings/scheduler/scheduler-runner.js +38 -35
  72. package/dist/wirings/scheduler/scheduler.types.d.ts +5 -4
  73. package/package.json +9 -7
  74. package/src/errors/errors.ts +6 -0
  75. package/src/factory-functions.test.ts +60 -1
  76. package/src/function/function-runner.test.ts +81 -26
  77. package/src/function/function-runner.ts +89 -57
  78. package/src/function/functions.types.ts +85 -2
  79. package/src/index.ts +6 -19
  80. package/src/middleware/auth-apikey.ts +42 -57
  81. package/src/middleware/auth-bearer.ts +66 -49
  82. package/src/middleware/auth-cookie.ts +63 -82
  83. package/src/middleware/timeout.ts +10 -14
  84. package/src/middleware-runner.test.ts +24 -16
  85. package/src/middleware-runner.ts +115 -87
  86. package/src/permissions.test.ts +26 -27
  87. package/src/permissions.ts +216 -104
  88. package/src/pikku-state.ts +79 -2
  89. package/src/services/content-service.ts +5 -4
  90. package/src/services/index.ts +0 -1
  91. package/src/services/local-content.ts +9 -4
  92. package/src/types/core.types.ts +143 -5
  93. package/src/utils.ts +1 -1
  94. package/src/wirings/channel/channel-handler.ts +18 -21
  95. package/src/wirings/channel/channel-runner.ts +19 -32
  96. package/src/wirings/channel/channel.types.ts +29 -16
  97. package/src/wirings/channel/local/local-channel-runner.ts +25 -15
  98. package/src/wirings/channel/serverless/serverless-channel-runner.ts +15 -17
  99. package/src/wirings/cli/channel/cli-channel-runner.ts +123 -0
  100. package/src/wirings/cli/channel/index.ts +1 -0
  101. package/src/wirings/cli/cli-runner.test.ts +403 -0
  102. package/src/wirings/cli/cli-runner.ts +539 -0
  103. package/src/wirings/cli/cli.types.ts +350 -0
  104. package/src/wirings/cli/command-parser.test.ts +445 -0
  105. package/src/wirings/cli/command-parser.ts +504 -0
  106. package/src/wirings/cli/index.ts +13 -0
  107. package/src/wirings/http/http-runner.test.ts +8 -7
  108. package/src/wirings/http/http-runner.ts +165 -158
  109. package/src/wirings/http/http.types.ts +58 -11
  110. package/src/wirings/http/index.ts +7 -1
  111. package/src/wirings/http/pikku-fetch-http-response.ts +3 -1
  112. package/src/wirings/http/routers/http-router.ts +0 -2
  113. package/src/wirings/http/routers/path-to-regex.test.ts +4 -5
  114. package/src/wirings/http/routers/path-to-regex.ts +6 -43
  115. package/src/wirings/mcp/mcp-endpoint-registry.ts +1 -1
  116. package/src/wirings/mcp/mcp-runner.ts +58 -55
  117. package/src/wirings/mcp/mcp.types.ts +65 -14
  118. package/src/wirings/queue/queue-runner.ts +44 -47
  119. package/src/wirings/queue/queue.types.ts +10 -6
  120. package/src/wirings/rpc/index.ts +1 -1
  121. package/src/wirings/rpc/rpc-runner.ts +27 -9
  122. package/src/wirings/scheduler/scheduler-runner.ts +58 -56
  123. package/src/wirings/scheduler/scheduler.types.ts +10 -3
  124. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,539 @@
1
+ import { NotFoundError } from '../../errors/errors.js'
2
+ import { addFunction, runPikkuFunc } from '../../function/function-runner.js'
3
+ import { pikkuState } from '../../pikku-state.js'
4
+ import {
5
+ CorePikkuMiddleware,
6
+ CoreUserSession,
7
+ SessionServices,
8
+ PikkuWiringTypes,
9
+ } from '../../types/core.types.js'
10
+ import { closeSessionServices } from '../../utils.js'
11
+ import {
12
+ CoreCLI,
13
+ CLICommandMeta,
14
+ CLIOption,
15
+ CLIProgramState,
16
+ CorePikkuCLIRender,
17
+ CoreCLICommandConfig,
18
+ CLIMeta,
19
+ } from './cli.types.js'
20
+ import type {
21
+ CoreSingletonServices,
22
+ CoreServices,
23
+ CreateSessionServices,
24
+ PikkuInteraction,
25
+ CreateConfig,
26
+ CreateSingletonServices,
27
+ } from '../../types/core.types.js'
28
+ import { PikkuChannel } from '../channel/channel.types.js'
29
+ import { rpcService } from '../rpc/rpc-runner.js'
30
+ import { PikkuUserSessionService } from '../../services/user-session-service.js'
31
+ import { LocalVariablesService } from '../../services/local-variables.js'
32
+ import { generateCommandHelp, parseCLIArguments } from './command-parser.js'
33
+
34
+ /**
35
+ * CLI command execution error - thrown when CLI execution fails
36
+ * Should be caught by the wrapper to call process.exit()
37
+ */
38
+ export class CLIError extends Error {
39
+ constructor(
40
+ message: string,
41
+ public exitCode: number = 1
42
+ ) {
43
+ super(message)
44
+ this.name = 'CLIError'
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Default JSON renderer for CLI output
50
+ */
51
+ const defaultJSONRenderer: CorePikkuCLIRender<any> = (_services, data) => {
52
+ console.log(JSON.stringify(data, null, 2))
53
+ }
54
+
55
+ /**
56
+ * Registers a CLI command tree and all its functions
57
+ */
58
+ export const wireCLI = <
59
+ Commands extends Record<string, CoreCLICommandConfig<any, any, any>>,
60
+ GlobalOptions,
61
+ PikkuMiddleware extends CorePikkuMiddleware,
62
+ GlobalOutput,
63
+ >(
64
+ cli: CoreCLI<Commands, GlobalOptions, PikkuMiddleware, GlobalOutput>
65
+ ) => {
66
+ // Get the existing metadata that was generated during inspection
67
+ const cliMeta = pikkuState('cli', 'meta') || {}
68
+
69
+ if (!cliMeta.programs?.[cli.program]) {
70
+ throw new Error(
71
+ `CLI metadata not found for program '${cli.program}'. Did you run 'pikku all'?`
72
+ )
73
+ }
74
+
75
+ // Get existing programs state and add this program
76
+ const programs: Record<string, CLIProgramState> =
77
+ pikkuState('cli', 'programs') || {}
78
+ programs[cli.program] = {
79
+ defaultRenderer: (cli.render ||
80
+ defaultJSONRenderer) as CorePikkuCLIRender<any>,
81
+ middleware: cli.middleware || [],
82
+ renderers: {},
83
+ tags: cli.tags,
84
+ }
85
+ pikkuState('cli', 'programs', programs)
86
+
87
+ // Register all command functions recursively
88
+ registerCLICommands(
89
+ cli.commands as Record<string, any>,
90
+ [],
91
+ cli.options || {},
92
+ cli.program
93
+ )
94
+ }
95
+
96
+ /**
97
+ * Unwraps a function from pikku wrappers (pikkuFunc, pikkuSessionlessFunc, etc.)
98
+ * These wrappers return { func, middleware, ... } but we need the actual function
99
+ */
100
+ function unwrapFunc(command: any): {
101
+ func: Function
102
+ middleware?: any[]
103
+ auth?: boolean
104
+ permissions?: any
105
+ tags?: string[]
106
+ } {
107
+ if (typeof command === 'function') {
108
+ return { func: command }
109
+ }
110
+
111
+ // If command has a func property that's an object with func, unwrap it
112
+ if (
113
+ command.func &&
114
+ typeof command.func === 'object' &&
115
+ 'func' in command.func
116
+ ) {
117
+ return {
118
+ func: command.func.func,
119
+ middleware: command.func.middleware,
120
+ auth: command.func.auth,
121
+ permissions: command.func.permissions,
122
+ tags: command.func.tags,
123
+ }
124
+ }
125
+
126
+ // Otherwise return as-is
127
+ return command
128
+ }
129
+
130
+ /**
131
+ * Registers CLI commands and their functions recursively
132
+ */
133
+ function registerCLICommands(
134
+ commands: Record<string, any>,
135
+ path: string[] = [],
136
+ inheritedOptions: Record<string, CLIOption> = {},
137
+ program: string
138
+ ) {
139
+ // Get the CLI metadata to find actual function names
140
+ const cliMeta = pikkuState('cli', 'meta').programs[program]
141
+
142
+ for (const [name, command] of Object.entries(commands)) {
143
+ const fullPath = [...path, name]
144
+ const commandId = fullPath.join('.')
145
+
146
+ // Navigate metadata to find the actual function name
147
+ let currentMeta: CLICommandMeta | undefined = cliMeta?.commands[fullPath[0]]
148
+ for (let i = 1; i < fullPath.length; i++) {
149
+ currentMeta = currentMeta?.subcommands?.[fullPath[i]]
150
+ }
151
+ const funcName = currentMeta?.pikkuFuncName
152
+
153
+ // Skip if no function name (could be a command group)
154
+ if (!funcName) {
155
+ // Recursively register subcommands if they exist
156
+ if (typeof command === 'object' && command.subcommands) {
157
+ const commandOptions = command.options || {}
158
+ const mergedOptions = { ...inheritedOptions, ...commandOptions }
159
+ registerCLICommands(
160
+ command.subcommands,
161
+ fullPath,
162
+ mergedOptions,
163
+ program
164
+ )
165
+ }
166
+ continue
167
+ }
168
+
169
+ // Merge options (inherited + local)
170
+ const commandOptions =
171
+ typeof command === 'object' ? command.options || {} : {}
172
+ const mergedOptions = { ...inheritedOptions, ...commandOptions }
173
+
174
+ // Store the options and middleware in program state for use during execution
175
+ const programs: Record<string, CLIProgramState> = pikkuState(
176
+ 'cli',
177
+ 'programs'
178
+ )
179
+ if (programs[program]) {
180
+ if (!programs[program].commandOptions) {
181
+ programs[program].commandOptions = {}
182
+ }
183
+ programs[program].commandOptions![commandId] = mergedOptions
184
+
185
+ // Store command middleware from the wire config
186
+ if (typeof command === 'object' && command.middleware) {
187
+ if (!programs[program].commandMiddleware) {
188
+ programs[program].commandMiddleware = {}
189
+ }
190
+ programs[program].commandMiddleware![commandId] = command.middleware
191
+ }
192
+ }
193
+
194
+ addFunction(funcName, unwrapFunc(command))
195
+
196
+ // Register renderer if provided
197
+ if (typeof command === 'object' && command.render) {
198
+ if (programs[program]) {
199
+ programs[program].renderers[commandId] = command.render
200
+ }
201
+ }
202
+
203
+ // Recursively register subcommands
204
+ if (typeof command === 'object' && command.subcommands) {
205
+ registerCLICommands(command.subcommands, fullPath, mergedOptions, program)
206
+ }
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Plucks only the data that the function expects based on its schema
212
+ */
213
+ function pluckCLIData(
214
+ mergedData: Record<string, any>,
215
+ funcName: string,
216
+ availableOptions: Record<string, CLIOption>
217
+ ): Record<string, any> {
218
+ const funcMeta = pikkuState('function', 'meta')[funcName]
219
+ const schemaName = funcMeta?.inputSchemaName
220
+ const schema = schemaName
221
+ ? pikkuState('misc', 'schemas').get(schemaName)
222
+ : null
223
+
224
+ if (schema && schema.properties) {
225
+ // If we have a schema, only include fields that are in the schema
226
+ const result: Record<string, any> = {}
227
+ for (const key of Object.keys(schema.properties)) {
228
+ if (key in mergedData) {
229
+ result[key] = mergedData[key]
230
+ } else if (availableOptions[key]?.default !== undefined) {
231
+ // Apply default if not provided
232
+ result[key] = availableOptions[key].default
233
+ }
234
+ }
235
+ return result
236
+ } else {
237
+ // No schema, include all data
238
+ return { ...mergedData }
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Executes a CLI command for a specific program
244
+ */
245
+ export async function runCLICommand({
246
+ program,
247
+ commandPath,
248
+ data,
249
+ singletonServices,
250
+ createSessionServices,
251
+ }: {
252
+ program: string
253
+ commandPath: string[]
254
+ data: Record<string, any>
255
+ singletonServices: CoreSingletonServices
256
+ createSessionServices?: CreateSessionServices
257
+ }): Promise<any> {
258
+ // Get the command metadata to find the function name
259
+ const cliMeta = pikkuState('cli', 'meta')
260
+ const programMeta = cliMeta.programs?.[program]
261
+ if (!programMeta) {
262
+ throw new NotFoundError(`Program not found: ${program}`)
263
+ }
264
+
265
+ // Navigate command tree to find the function name
266
+ let currentCommand = programMeta.commands[commandPath[0]]
267
+ if (!currentCommand) {
268
+ throw new NotFoundError(`Command not found: ${commandPath.join(' ')}`)
269
+ }
270
+
271
+ for (let i = 1; i < commandPath.length; i++) {
272
+ if (
273
+ !currentCommand.subcommands ||
274
+ !currentCommand.subcommands[commandPath[i]]
275
+ ) {
276
+ throw new NotFoundError(`Command not found: ${commandPath.join(' ')}`)
277
+ }
278
+ currentCommand = currentCommand.subcommands[commandPath[i]]
279
+ }
280
+
281
+ const funcName = currentCommand.pikkuFuncName
282
+
283
+ // Get program-specific data
284
+ const programs: Record<string, CLIProgramState> =
285
+ pikkuState('cli', 'programs') || {}
286
+ const programData = programs[program]
287
+
288
+ // Combine program middleware + command middleware from the hierarchy
289
+ const allWireMiddleware: CorePikkuMiddleware[] = [
290
+ ...(programData?.middleware || []),
291
+ ]
292
+
293
+ // Walk through the command path and collect middleware from the runtime config
294
+ const commandParts: string[] = []
295
+ for (const part of commandPath) {
296
+ commandParts.push(part)
297
+ const commandId = commandParts.join('.')
298
+ const middleware = programData?.commandMiddleware?.[commandId]
299
+ if (middleware) {
300
+ allWireMiddleware.push(...middleware)
301
+ }
302
+ }
303
+
304
+ // Get command ID and options
305
+ const commandId = commandPath.join('.')
306
+ const availableOptions = programData?.commandOptions?.[commandId] || {}
307
+
308
+ // Pluck only the fields the function expects
309
+ const pluckedData = () => pluckCLIData(data, funcName, availableOptions)
310
+
311
+ // Get the renderer
312
+ const renderer =
313
+ programData?.renderers[commandId] || programData?.defaultRenderer
314
+
315
+ // Create a CLI channel for progressive output
316
+ const channel: PikkuChannel<unknown, unknown> = {
317
+ channelId: `cli:${program}:${commandId}`,
318
+ openingData: pluckedData,
319
+ send: async (data: any) => {
320
+ if (renderer) {
321
+ await Promise.resolve(renderer(singletonServices, data, undefined))
322
+ }
323
+ },
324
+ close: () => {
325
+ if (channel) {
326
+ channel.state = 'closed'
327
+ }
328
+ },
329
+ state: 'open',
330
+ }
331
+
332
+ const userSession = new PikkuUserSessionService<CoreUserSession>()
333
+ let sessionServices: SessionServices | undefined
334
+
335
+ const interaction: PikkuInteraction = {
336
+ cli: {
337
+ program,
338
+ command: commandPath,
339
+ data: pluckedData,
340
+ channel,
341
+ },
342
+ }
343
+
344
+ const getAllServices = async (session?: CoreUserSession) => {
345
+ // Create session-specific services for handling the command
346
+ sessionServices = await createSessionServices?.(
347
+ singletonServices,
348
+ interaction,
349
+ session
350
+ )
351
+
352
+ return rpcService.injectRPCService(
353
+ {
354
+ ...singletonServices,
355
+ ...sessionServices,
356
+ userSession,
357
+ channel,
358
+ },
359
+ interaction,
360
+ false
361
+ )
362
+ }
363
+
364
+ try {
365
+ const result = await runPikkuFunc(
366
+ PikkuWiringTypes.cli,
367
+ commandId,
368
+ funcName,
369
+ {
370
+ singletonServices,
371
+ getAllServices,
372
+ data: pluckedData,
373
+ auth: false,
374
+ userSession,
375
+ inheritedMiddleware: currentCommand.middleware,
376
+ wireMiddleware: allWireMiddleware,
377
+ inheritedPermissions: currentCommand.permissions,
378
+ wirePermissions: undefined,
379
+ tags: programData?.tags,
380
+ interaction,
381
+ }
382
+ )
383
+
384
+ // Apply renderer one final time with the final output (if renderer exists)
385
+ if (renderer) {
386
+ await Promise.resolve(
387
+ renderer(singletonServices, result, userSession.get())
388
+ )
389
+ }
390
+
391
+ return result
392
+ } finally {
393
+ // Close the channel
394
+ channel.close()
395
+
396
+ // Clean up session services
397
+ if (sessionServices) {
398
+ await closeSessionServices(singletonServices.logger, sessionServices)
399
+ }
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Factory function for CLI-specific renderers
405
+ */
406
+ export const pikkuCLIRender = <
407
+ Data,
408
+ Services extends CoreSingletonServices = CoreServices,
409
+ Session extends CoreUserSession = CoreUserSession,
410
+ >(
411
+ renderer: (
412
+ services: Services,
413
+ data: Data,
414
+ session?: Session
415
+ ) => void | Promise<void>
416
+ ): CorePikkuCLIRender<Data, Services, Session> => {
417
+ return renderer
418
+ }
419
+
420
+ /**
421
+ * Execute a CLI program with the given arguments
422
+ * This is the main entry point for CLI programs
423
+ *
424
+ * @throws {CLIError} When CLI execution fails - should be caught by wrapper to call process.exit()
425
+ */
426
+ export async function executeCLI({
427
+ programName,
428
+ args,
429
+ createConfig,
430
+ createSingletonServices,
431
+ createSessionServices,
432
+ }: {
433
+ programName: string
434
+ args?: string[]
435
+ createConfig: CreateConfig<any, any>
436
+ createSingletonServices: CreateSingletonServices<any, any>
437
+ createSessionServices?: CreateSessionServices<any, any>
438
+ }): Promise<void> {
439
+ if (!args) {
440
+ throw new Error(
441
+ 'CLI arguments are required, this is to satisfy release diffs'
442
+ )
443
+ }
444
+
445
+ try {
446
+ // Get CLI metadata from state
447
+ const allCLIMeta = pikkuState('cli', 'meta') as unknown as
448
+ | CLIMeta
449
+ | undefined
450
+ if (!allCLIMeta) {
451
+ throw new Error(
452
+ '[PKU342] CLI metadata not found. No CLI wirings were registered. See https://pikku.dev/errors/pku342 for more information.'
453
+ )
454
+ }
455
+ const programMeta = allCLIMeta.programs[programName]
456
+
457
+ if (!programMeta) {
458
+ throw new CLIError(`CLI program "${programName}" not found`, 1)
459
+ }
460
+
461
+ // Parse arguments for this specific program
462
+ const parsed = parseCLIArguments(args, programName, allCLIMeta)
463
+
464
+ // Handle help (check after parsing to support subcommand help)
465
+ // Show help if --help/-h is present, or if no args AND no default command
466
+ const shouldShowHelp =
467
+ args.includes('--help') ||
468
+ args.includes('-h') ||
469
+ (args.length === 0 && parsed.commandPath.length === 0)
470
+
471
+ if (shouldShowHelp) {
472
+ const helpText = generateCommandHelp(
473
+ programName,
474
+ allCLIMeta,
475
+ parsed.commandPath
476
+ )
477
+ console.log(helpText)
478
+ return
479
+ }
480
+
481
+ if (parsed.errors.length > 0) {
482
+ // Check if any error is about an unknown command
483
+ const hasUnknownCommand = parsed.errors.some(
484
+ (error) =>
485
+ error.startsWith('Unknown command:') ||
486
+ error.startsWith('Command not found:')
487
+ )
488
+
489
+ if (hasUnknownCommand) {
490
+ // Show help instead of error for unknown commands
491
+ const helpText = generateCommandHelp(
492
+ programName,
493
+ allCLIMeta,
494
+ parsed.commandPath
495
+ )
496
+ console.log(helpText)
497
+ throw new CLIError('Unknown command', 1)
498
+ } else {
499
+ // Show errors for other types of errors
500
+ console.error('Errors:')
501
+ parsed.errors.forEach((error) => console.error(` ${error}`))
502
+ throw new CLIError(parsed.errors.join('\n'), 1)
503
+ }
504
+ }
505
+
506
+ // Merge positionals and options into single data object
507
+ const data = { ...parsed.positionals, ...parsed.options }
508
+
509
+ // Create config (pass data in case it needs to use any parsed options)
510
+ const config = await createConfig(new LocalVariablesService(), data)
511
+
512
+ // Create services with config
513
+ const singletonServices = await createSingletonServices(config)
514
+
515
+ // Execute the command
516
+ await runCLICommand({
517
+ program: programName,
518
+ commandPath: parsed.commandPath,
519
+ data,
520
+ singletonServices,
521
+ createSessionServices,
522
+ })
523
+ } catch (error: any) {
524
+ // Re-throw CLIError as-is
525
+ if (error instanceof CLIError) {
526
+ throw error
527
+ }
528
+
529
+ // Wrap other errors in CLIError
530
+ console.error('Error:', error)
531
+
532
+ // Show stack trace in verbose mode
533
+ if (args.includes('--verbose') || args.includes('-v')) {
534
+ console.error('Stack trace:', error.stack)
535
+ }
536
+
537
+ throw new CLIError(error.message || String(error), 1)
538
+ }
539
+ }