@qodalis/mcp-cli 0.1.0 → 0.2.1

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 (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +137 -26
  3. package/dist/src/cli.js +21 -11
  4. package/dist/src/cli.js.map +1 -1
  5. package/dist/src/config.d.ts +10 -6
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +25 -6
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/dev/api.d.ts +94 -0
  10. package/dist/src/dev/api.d.ts.map +1 -0
  11. package/dist/src/dev/api.js +425 -0
  12. package/dist/src/dev/api.js.map +1 -0
  13. package/dist/src/dev/docs.d.ts +93 -0
  14. package/dist/src/dev/docs.d.ts.map +1 -0
  15. package/dist/src/dev/docs.js +275 -0
  16. package/dist/src/dev/docs.js.map +1 -0
  17. package/dist/src/dev/prompts.d.ts +11 -0
  18. package/dist/src/dev/prompts.d.ts.map +1 -0
  19. package/dist/src/dev/prompts.js +141 -0
  20. package/dist/src/dev/prompts.js.map +1 -0
  21. package/dist/src/dev/scaffold.d.ts +55 -0
  22. package/dist/src/dev/scaffold.d.ts.map +1 -0
  23. package/dist/src/dev/scaffold.js +213 -0
  24. package/dist/src/dev/scaffold.js.map +1 -0
  25. package/dist/src/dev/tools.d.ts +170 -0
  26. package/dist/src/dev/tools.d.ts.map +1 -0
  27. package/dist/src/dev/tools.js +258 -0
  28. package/dist/src/dev/tools.js.map +1 -0
  29. package/dist/src/index.d.ts +7 -2
  30. package/dist/src/index.d.ts.map +1 -1
  31. package/dist/src/index.js +6 -1
  32. package/dist/src/index.js.map +1 -1
  33. package/dist/src/remote.d.ts +3 -1
  34. package/dist/src/remote.d.ts.map +1 -1
  35. package/dist/src/remote.js +17 -10
  36. package/dist/src/remote.js.map +1 -1
  37. package/dist/src/server.d.ts +11 -2
  38. package/dist/src/server.d.ts.map +1 -1
  39. package/dist/src/server.js +85 -15
  40. package/dist/src/server.js.map +1 -1
  41. package/docs/llms-full.txt +1825 -0
  42. package/package.json +7 -4
@@ -0,0 +1,1825 @@
1
+ # Qodalis CLI plugin development
2
+
3
+ > Reference for writing Qodalis CLI plugins: browser (web) plugins that run in the terminal UI, and server plugins for the Node.js, .NET and Python CLI servers. Every topic is self-contained. Version 2.0. Source: https://github.com/qodalis-solutions/web-cli. Docs: https://cli.qodalis.com.
4
+
5
+ ## Overview
6
+
7
+ ### Web plugins vs server plugins
8
+
9
+ A Qodalis CLI command is either a web plugin running in the browser or a server plugin running in a CLI server; the user types both in the same terminal.
10
+
11
+ - **Web plugin**: a TypeScript package exporting an `ICliModule` (from `@qodalis/cli-core`) whose `processors` implement `ICliCommandProcessor`. It runs in the page, writes to the xterm.js terminal through `context.writer`, can prompt (`context.reader`), keep state, call HTTP APIs, go full screen, run background services. Use it for anything that can run in the browser: tools, formatters, games, UIs over a REST API, interactive prompts.
12
+ - **Server plugin**: a processor/module for a Qodalis CLI server (`@qodalis/cli-server-abstractions` for Node, `Qodalis.Cli.Abstractions` for .NET, `qodalis-cli-server-abstractions` for Python). It runs on the server, receives the parsed command over HTTP and returns text or structured output (`text`, `table`, `list`, `json`, `key-value`). Use it when the command needs server resources: the filesystem, databases, secrets, OS processes, private networks. Server commands are also exposed as MCP tools when the server enables MCP.
13
+ - The browser terminal discovers server commands at startup (`GET /api/v1/qcli/commands`) and registers a proxy for each one as `<server>:<command>` (e.g. `node:weather`) plus the bare name (`weather`) when no local command owns it.
14
+ - Rule of thumb: no secrets and no server-only resources -> web plugin; otherwise server plugin. Both can coexist (a web command can call a server through `context.http`).
15
+
16
+ ### Packages
17
+
18
+ The npm, NuGet and PyPI packages a plugin author uses, by role.
19
+
20
+ | Package | Role |
21
+ |---|---|
22
+ | `@qodalis/cli-core` | Web plugin API: `ICliModule`, `ICliCommandProcessor`, `ICliExecutionContext`, `CliProcessCommand`, `API_VERSION`, `DefaultLibraryAuthor`, `bootCliModule`, colors, tokens. The only runtime dependency of a web plugin. |
23
+ | `@qodalis/cli` | Framework-agnostic engine: `CliEngine`, `CliTestHarness` (for tests). |
24
+ | `@qodalis/angular-cli` | Angular wrapper: `CliModule`, `<cli>`, `<cli-panel>`, `resolveCliModuleProvider`. |
25
+ | `@qodalis/react-cli` | React wrapper: `Cli`, `CliPanel`, `CliProvider`, `CliConfigProvider`. |
26
+ | `@qodalis/vue-cli` | Vue 3 wrapper: `Cli`, `CliPanel`, `CliConfigProvider`. |
27
+ | `@qodalis/create-cli-plugin` | Scaffolder (`npx @qodalis/create-cli-plugin`). |
28
+ | `@qodalis/cli-<name>` | Published web plugins (`@qodalis/cli-guid`, `@qodalis/cli-todo`, ...). Each exports `<name>Module`. |
29
+ | `@qodalis/cli-server-abstractions` (npm) | Node server plugin API. Server: `@qodalis/cli-server-node`. |
30
+ | `Qodalis.Cli.Abstractions` (NuGet) | .NET server plugin API. Server: `Qodalis.Cli`. |
31
+ | `qodalis-cli-server-abstractions` (PyPI, import `qodalis_cli_server_abstractions`) | Python server plugin API. Server: `qodalis-cli-server` (import `qodalis_cli`). |
32
+ | `@qodalis/mcp-cli` | MCP server for AI assistants: docs search, API lookup, plugin scaffolding, and (with `QCLI_URL`) driving a CLI server. |
33
+
34
+ ### Shipping the CLI under your own name
35
+
36
+ `CliOptions.branding` sets the name and icon an application ships the CLI under. Anything left out keeps Qodalis CLI's.
37
+
38
+ ```tsx
39
+ <CliPanel options={{ branding: { name: 'RateBell CLI', icon: '/favicon.svg' }, servers: [...] }} />
40
+ ```
41
+
42
+ - `name` replaces "Web CLI" and the Qodalis CLI art in the welcome banner and the startup log, and "CLI" in the panel's header and hide tab (React, Vue, Angular).
43
+ - `icon` (an image URL: http(s), a path, or a `data:image` URL) replaces the panel's terminal glyph.
44
+ - The copyright line, the documentation link and `version` stay Qodalis CLI's; `version` adds the name as an `App` row.
45
+
46
+ ## Web plugins
47
+
48
+ ### Scaffolding a web plugin with create-cli-plugin
49
+
50
+ `@qodalis/create-cli-plugin` generates a ready-to-build web plugin, either standalone (its own npm project) or inside the web-cli monorepo.
51
+
52
+ ```bash
53
+ # Standalone, interactive
54
+ npx @qodalis/create-cli-plugin
55
+
56
+ # Standalone, non-interactive (all flags optional except --name)
57
+ npx @qodalis/create-cli-plugin --name weather --description "Weather forecasts" --processor-name Weather
58
+
59
+ # Inside the web-cli monorepo (builds the scaffolder first)
60
+ pnpm run create-plugin -- --name weather --description "Weather forecasts" --processor-name Weather
61
+ ```
62
+
63
+ - Flags: `-n, --name <name>` (lowercase; becomes the command and `@qodalis/cli-<name>`), `-d, --description <description>` (default `CLI extension for <name>`), `-p, --processor-name <name>` (PascalCase; default: PascalCase of the name; the class is `Cli<ProcessorName>CommandProcessor`). Without `--name` it prompts.
64
+ - Monorepo mode is detected by walking up to a directory with a `pnpm-workspace.yaml` mentioning `packages/plugins`; the plugin is created in `packages/plugins/<name>/` with `project.json`, `tsconfig.spec.json`, a `tsconfig.base.json` path alias `@qodalis/cli-<name>` -> `./dist/<name>` and an `angular.json` Karma test entry. Build with `pnpm nx build <name>`, test with `pnpm nx test <name>`.
65
+ - Standalone mode creates `./qodalis-cli-<name>/`, runs `pnpm install` (or `npm install`), and also writes `.gitignore`, `pnpm-workspace.yaml` and `AGENTS.md`. Build with `npx tsup` (or `npm run build`), publish with `npm publish --access public`.
66
+
67
+ Generated layout (both modes):
68
+
69
+ ```text
70
+ src/
71
+ public-api.ts # exports the processor, version and `<name>Module: ICliModule`
72
+ cli-entrypoint.ts # UMD entry: bootCliModule(module) for `pkg add`
73
+ lib/
74
+ index.ts # barrel
75
+ version.ts # LIBRARY_VERSION, API_VERSION = 2
76
+ processors/cli-<name>-command-processor.ts
77
+ tests/index.spec.ts # Jasmine-style describe/it/expect
78
+ tsup.config.ts # CJS + ESM + d.ts, plus IIFE bundle in dist/umd
79
+ package.json # name @qodalis/cli-<name>, dependency @qodalis/cli-core
80
+ ```
81
+
82
+ ### ICliModule
83
+
84
+ `ICliModule` (from `@qodalis/cli-core`) is the unit a web plugin exports: it bundles command processors, services, guards, permissions and translations, plus lifecycle hooks.
85
+
86
+ ```typescript
87
+ import { API_VERSION, ICliModule } from '@qodalis/cli-core';
88
+
89
+ export const weatherModule: ICliModule = {
90
+ apiVersion: API_VERSION, // required; modules below the runtime's API_VERSION (2) are rejected at boot
91
+ name: '@qodalis/cli-weather', // required; unique id
92
+ version: '1.0.0',
93
+ description: 'Weather forecasts',
94
+ dependencies: [], // module names booted before this one
95
+ priority: 0, // lower boots first (default 0)
96
+ processors: [new CliWeatherCommandProcessor()],
97
+ services: [], // CliProvider[] registered in the shared container
98
+ guards: [], // ICliCommandGuard[] run before every command
99
+ permissions: [], // CliPermissionDefinition[] ({ name: 'weather:read', description? })
100
+ translations: { es: { 'cli.weather.description': 'Previsión del tiempo' } },
101
+ async onInit(context) {}, // after services are registered, before processors initialize
102
+ async onSetup(context) { return true; }, // first-run setup; true marks it done (persisted)
103
+ async onAfterBoot(context) {}, // all modules booted, terminal interactive
104
+ async onDestroy(context) {}, // teardown
105
+ };
106
+ ```
107
+
108
+ - `config?: Record<string, any>` and `configure?(config): ICliModule` support configurable modules; implement `ICliConfigurableModule<TConfig>` and return a copy: `configure(config) { return { ...this, config }; }`. Hosts then pass `weatherModule.configure({ units: 'metric' })`.
109
+ - Only `apiVersion` and `name` are required. Use the `API_VERSION` constant (core exports `API_VERSION = 2`; scaffolded plugins keep their own copy in `src/lib/version.ts`).
110
+ - Removed in 2.0.0-rc.1: `ICliUmdModule`, `bootUmdModule`, `registerProcessor(s)`, `resolveCommandProcessorProvider`, `CliCommandProcessor_TOKEN` and the `processors` input/prop. Always wrap processors in a module.
111
+
112
+ ### ICliCommandProcessor
113
+
114
+ `ICliCommandProcessor` is the interface every web command implements; only `command` and `processCommand` are required.
115
+
116
+ ```typescript
117
+ import {
118
+ CliProcessCommand,
119
+ ICliCommandProcessor,
120
+ ICliExecutionContext,
121
+ } from '@qodalis/cli-core';
122
+
123
+ export class CliHelloCommandProcessor implements ICliCommandProcessor {
124
+ command = 'hello';
125
+ aliases = ['hi'];
126
+ description = 'Greets someone';
127
+ author = { name: 'Jane Doe', email: 'jane@example.com' };
128
+ version = '1.0.0';
129
+ acceptsRawInput = true; // text after the command -> command.value / command.positionals
130
+ metadata = { icon: '👋', module: '@acme/cli-hello' };
131
+ parameters = [
132
+ { name: 'shout', aliases: ['s'], description: 'Upper-case the greeting', required: false, type: 'boolean' },
133
+ ];
134
+
135
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
136
+ const name = command.positionals?.[0] ?? 'world';
137
+ const text = `Hello, ${name}!`;
138
+ context.writer.writeln(command.args['shout'] ? text.toUpperCase() : text);
139
+ }
140
+ }
141
+ ```
142
+
143
+ All members:
144
+
145
+ | Member | Type | Purpose |
146
+ |---|---|---|
147
+ | `command` | `string` | Command word (matched case-insensitively). |
148
+ | `aliases?` | `string[]` | Alternative names. |
149
+ | `description?` | `string` | Shown by `help`; translated via key `cli.<command>.description`. |
150
+ | `author?` | `ICliCommandAuthor` | `{ name, email }`. `DefaultLibraryAuthor` is the Qodalis author; use your own for third-party plugins. |
151
+ | `version?` | `string` | Default `'1.0.0'`. |
152
+ | `acceptsRawInput?` | `boolean` | Capture text after the command as `command.value` instead of treating it as sub-commands. |
153
+ | `valueRequired?` | `boolean` | Like `acceptsRawInput`, and the engine errors (`Value required`) unless a positional value, piped data or named args are given; required-parameter checks are skipped when positional input exists. |
154
+ | `metadata?` | `CliProcessorMetadata` | `sealed`, `hidden`, `requireServer`, `module`, `icon`, `requiredCoreVersion`, `requiredCliVersion`, `requireAuth`, `requiredGroups`, `requiredPermissions`, `literalInput` (see the metadata topic). |
155
+ | `processors?` | `ICliCommandChildProcessor[]` | Sub-commands (`parent` is set by the engine). |
156
+ | `parameters?` | `ICliCommandParameterDescriptor[]` | Flags (`--name value`, `--name=value`, `-n`). |
157
+ | `hooks?` | `ICliProcessorHook[]` | `{ when: 'before' \| 'after', execute(context): Promise<void> }`. |
158
+ | `stateConfiguration?` | `CliStateConfiguration` | Per-processor persisted state (root processors only). |
159
+ | `configurationOptions?` | `ICliConfigurationOption[]` | Settings shown by the `configure` command. |
160
+ | `extendsProcessor?` | `boolean` | Wrap an existing processor with the same `command` instead of replacing it. |
161
+ | `originalProcessor?` | `ICliCommandProcessor` | Set by the registry when `extendsProcessor` is true; delegate with `this.originalProcessor.processCommand(command, context)`. |
162
+ | `processCommand(command, context)` | `Promise<void>` | Runs the command. |
163
+ | `writeDescription?(context)` | `void` | Custom long help text. |
164
+ | `validateBeforeExecution?(command, context)` | `{ valid, message? }` | Reject a command before it runs; `message` is printed as an error. |
165
+ | `initialize?(context)` | `Promise<void>` | Called once at boot (with the processor's own state store). |
166
+ | `onData?(data, context)` | `Promise<void>` | Raw terminal input while this processor is the context processor (full-screen apps). |
167
+ | `onResize?(cols, rows, context)` | `void` | Terminal resized while in full-screen mode. |
168
+ | `onDispose?(context)` | `void` | Full-screen mode ended, terminal disconnected or component destroyed. |
169
+ | `controls?` | `ICliCommandControls` | Keys a full-screen command reads, so touch hosts can show them as buttons (see below). |
170
+
171
+ Execution order for one command: parse -> find processor -> global parameter handlers (`--help`, ...) -> extract `value`/`positionals` -> command guards -> `valueRequired` check -> required-parameter and `validator` checks -> `validateBeforeExecution` -> `before` hooks -> `processCommand` -> `after` hooks.
172
+
173
+ ### CliProcessCommand and argument parsing
174
+
175
+ `CliProcessCommand` is the parsed command passed to `processCommand`: words, flags, positional values and piped data.
176
+
177
+ ```typescript
178
+ type CliProcessCommand = {
179
+ command: string; // command text without flags, e.g. 'todo add'
180
+ chainCommands: string[]; // command words, e.g. ['todo', 'add']
181
+ rawCommand: string; // the line as typed
182
+ value?: string; // text after the command/sub-command words (flags removed, quotes kept); only with acceptsRawInput/valueRequired
183
+ positionals?: string[]; // shell-split arguments: quotes removed, escapes applied, flags excluded
184
+ args: Record<string, any>; // flags, keyed by parameter name AND each alias
185
+ data?: any; // piped input from the previous command (`a | b`)
186
+ };
187
+ ```
188
+
189
+ - Flag forms: `--name=value` (always works), `--name value` / `-n 5` (space form: only when the parameter is declared, its `type` is not `'boolean'`, **and** the processor accepts positional input via `acceptsRawInput` or `valueRequired`; otherwise the value word is taken as a sub-command and the command is not found), `-n5`, `-abc` (= `-a -b -c` when each letter is a declared boolean). A flag without value is `true`.
190
+ - Values that look numeric become numbers, `'true'`/`'false'` become booleans. For declared parameters: `type: 'boolean'` maps `true/'true'/'1'/'yes'/'y'/1` to `true`, anything else to `false`; `type: 'array'` collects repeated flags (`--tag a --tag b` -> `['a', 'b']`). Other types keep the parsed value; convert yourself (`Number(command.args['count'])`).
191
+ - Undeclared flags still land in `args` under their typed name.
192
+ - Read a flag that has aliases with `getParameterValue(descriptor, command.args)` (exported from `@qodalis/cli-core`), or just `command.args['name']` (aliases are mirrored for declared parameters).
193
+ - `defaultValue` is shown by `help` only; it is not injected into `args`. Apply it yourself: `const units = command.args['units'] ?? 'metric';`.
194
+ - Prefer `command.positionals` to `command.value` (quotes handled, `"my file.txt"` is one argument).
195
+
196
+ ### Parameters
197
+
198
+ `ICliCommandParameterDescriptor` declares a flag: name, aliases, type, required, default (help only) and an optional validator.
199
+
200
+ ```typescript
201
+ import { ICliCommandParameterDescriptor } from '@qodalis/cli-core';
202
+
203
+ const parameters: ICliCommandParameterDescriptor[] = [
204
+ {
205
+ name: 'count',
206
+ aliases: ['c'],
207
+ description: 'How many items to generate',
208
+ required: false,
209
+ type: 'number', // 'string' | 'number' | 'boolean' | 'array' | 'object' | string
210
+ defaultValue: 1, // shown in help; not applied automatically
211
+ validator: (value) =>
212
+ Number(value) > 0 && Number(value) <= 100
213
+ ? { valid: true }
214
+ : { valid: false, message: 'count must be between 1 and 100' },
215
+ },
216
+ { name: 'json', description: 'Print JSON', required: false, type: 'boolean' },
217
+ ];
218
+ ```
219
+
220
+ - Set `acceptsRawInput = true` on a processor whose parameters take values if users should be able to type `--count 5`; without it only `--count=5` works.
221
+ - `required: true` parameters are checked only in named-argument mode (no positional value and no piped data); the error is `Missing required parameters: --name`.
222
+ - `validator` runs when the flag is present; failures print `Invalid parameters:` with each message and the command does not run.
223
+ - Every command also gets the global `--help` handling; a processor declaring a parameter with the same name or alias takes it over.
224
+
225
+ ### Sub-commands
226
+
227
+ Sub-commands are nested processors in `processors`; the engine walks the command words down the tree and runs the deepest match.
228
+
229
+ ```typescript
230
+ import {
231
+ CliProcessCommand,
232
+ ICliCommandProcessor,
233
+ ICliExecutionContext,
234
+ } from '@qodalis/cli-core';
235
+
236
+ class NotesAddProcessor implements ICliCommandProcessor {
237
+ command = 'add';
238
+ description = 'Add a note';
239
+ valueRequired = true; // `notes add buy milk` -> value 'buy milk'
240
+
241
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext) {
242
+ const text = command.positionals!.join(' '); // quotes removed; command.value keeps them
243
+ const notes: string[] = context.state.getState()['notes'] ?? [];
244
+ context.state.updateState({ notes: [...notes, text] });
245
+ await context.state.persist();
246
+ context.writer.writeSuccess('Note added');
247
+ }
248
+ }
249
+
250
+ class NotesListProcessor implements ICliCommandProcessor {
251
+ command = 'list';
252
+ aliases = ['ls'];
253
+ description = 'List notes';
254
+
255
+ async processCommand(_: CliProcessCommand, context: ICliExecutionContext) {
256
+ const notes: string[] = context.state.getState()['notes'] ?? [];
257
+ context.writer.writeList(notes, { ordered: true });
258
+ }
259
+ }
260
+
261
+ export class CliNotesCommandProcessor implements ICliCommandProcessor {
262
+ command = 'notes';
263
+ description = 'Keep short notes';
264
+ processors = [new NotesAddProcessor(), new NotesListProcessor()];
265
+ stateConfiguration = { initialState: { notes: [] } }; // state is owned by the root processor
266
+
267
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext) {
268
+ await context.executor.showHelp(command, context); // `notes` alone prints help
269
+ }
270
+ }
271
+ ```
272
+
273
+ - Resolution: match the first word against root `command`/`aliases`, then each following word against the current processor's `processors`. If a word matches no child, the command is not found, unless the current processor has no children and `acceptsRawInput`/`valueRequired` is set (then the rest is its value).
274
+ - Children share the root processor's state store (`context.state`).
275
+ - Translation keys for sub-commands include the path: `cli.notes.add.description`.
276
+
277
+ ### Processor metadata, access control and permissions
278
+
279
+ `metadata` (`CliProcessorMetadata`) flags how the engine treats a processor: sealing, visibility, server requirement, version requirements and access control.
280
+
281
+ ```typescript
282
+ metadata = {
283
+ icon: '🌦', // string or CliIcon, shown in help
284
+ module: '@qodalis/cli-weather', // owning module name
285
+ hidden: false, // true: not listed by `help`, still runnable
286
+ sealed: false, // true: cannot be replaced/removed (can still be extended)
287
+ requireServer: false, // the command needs a connected server
288
+ requiredCoreVersion: '2.0.0', // skip the processor at boot if @qodalis/cli-core is older
289
+ requiredCliVersion: '2.0.0', // same for @qodalis/cli
290
+ literalInput: false, // true: pass the whole line verbatim (no pipes, ;, &&, $VAR expansion)
291
+ requireAuth: true, // a signed-in user is required
292
+ requiredGroups: ['admin'], // user must be in one of these groups (implies requireAuth)
293
+ requiredPermissions: ['weather:write'], // user must hold all (implies requireAuth)
294
+ };
295
+ ```
296
+
297
+ - `requireAuth`, `requiredGroups` and `requiredPermissions` are enforced by core guards only when an auth module registers an `ICliAuthorizationService` (e.g. `@qodalis/cli-users`); without one they are informational.
298
+ - Declare the permission names your module uses in `ICliModule.permissions` (`{ name: 'weather:write', description: 'Change weather settings' }`) so admins can list and grant them.
299
+ - Inside a command, check ad hoc with the authorization service: `context.services.get(ICliAuthorizationService_TOKEN)?.can('weather:write')`.
300
+
301
+ ### Command guards
302
+
303
+ An `ICliCommandGuard` runs before every command (across all modules) and can block it; contribute guards through `ICliModule.guards`.
304
+
305
+ ```typescript
306
+ import { ICliCommandGuard, ICliModule, API_VERSION } from '@qodalis/cli-core';
307
+
308
+ const businessHoursGuard: ICliCommandGuard = {
309
+ name: 'business-hours',
310
+ priority: 10, // lower runs first
311
+ appliesTo: (processor) => processor.command === 'deploy',
312
+ canActivate: (command, processor, context) => {
313
+ const hour = new Date().getHours();
314
+ return hour >= 9 && hour < 17 ? true : 'deploy is only allowed 09:00-17:00';
315
+ },
316
+ };
317
+
318
+ export const deployModule: ICliModule = {
319
+ apiVersion: API_VERSION,
320
+ name: '@acme/cli-deploy',
321
+ processors: [/* ... */],
322
+ guards: [businessHoursGuard],
323
+ };
324
+ ```
325
+
326
+ - `canActivate` returns `CliCommandGuardResult`: `true`/`undefined` allow; `false` blocks with a default message; a `string` blocks with that message; or `{ allowed: boolean, message?: string }`. May be async.
327
+ - A guard that throws blocks the command (fail closed). Blocked commands exit with code -1 and the message printed as an error.
328
+
329
+ ### ICliExecutionContext
330
+
331
+ `ICliExecutionContext` is the second argument of `processCommand`: the command's access to the terminal, input, state, services, HTTP and process control.
332
+
333
+ | Member | Use |
334
+ |---|---|
335
+ | `writer: ICliTerminalWriter` | Output (`writeln`, `writeSuccess`, `writeError`, tables, JSON, ...). |
336
+ | `reader: ICliInputReader` | Interactive prompts (`readLine`, `readConfirm`, `readSelect`, ...). |
337
+ | `progressBar: ICliPercentageProgressBar` | `show(text?)`, `update(percent, { type?: 'replace' \| 'increment' })`, `setText`, `complete()`, `hide()`. |
338
+ | `spinner?: ICliSpinner` | `show(text?)`, `setText(text)`, `hide()`. |
339
+ | `textAnimator?: ICliTextAnimator` | `showText(text, { speed?, removeAfterTyping? })` typewriter effect. |
340
+ | `notifier: ICliNotifier` | Status line in the panel header: `info`, `success`, `warn`, `error`, `clear`; cleared when the command ends. |
341
+ | `state: ICliStateStore` | The processor's state store (see state topic). |
342
+ | `clipboard: ICliClipboard` | `write(text)`, `read()`. |
343
+ | `http: ICliHttpClient` | HTTP client wired to the command's abort signal. |
344
+ | `services: ICliServiceProvider` | DI container (`get`, `getRequired`, `getAll`, `has`, `set`). |
345
+ | `translator: ICliTranslationService` | `t(key, defaultValue, params?)`, `getLocale()`. |
346
+ | `executor: ICliCommandExecutorService` | `showHelp(command, context)`, `executeCommand(line, context)`. |
347
+ | `process: ICliExecutionProcess` | `exit(code?, { silent? })` ends the command (it throws to unwind unless `silent`), `output(data)` sets pipe data. |
348
+ | `signal?: AbortSignal` / `onAbort: Subject<void>` | Ctrl+C / kill; check for cooperative cancellation. |
349
+ | `backgroundServices: ICliBackgroundServiceRegistry` | Register/start daemons and jobs. |
350
+ | `events?: ICliEventBus` | Terminal event bus. |
351
+ | `logger: ICliLogger` | `log`, `info`, `warn`, `error`, `debug`. |
352
+ | `options?: CliOptions` | Host options (servers, logLevel, ...). |
353
+ | `userSession?: ICliUserSession` | Current user session, when an auth module is present. |
354
+ | `terminal: Terminal` | The raw xterm.js terminal (`cols`, `rows`, `write`). |
355
+ | `enterFullScreenMode(processor, { showCursor? })` / `exitFullScreenMode()` | Alternate screen; input routed to `processor.onData`. |
356
+ | `createInterval(cb, ms)` / `createTimeout(cb, ms)` | Managed timers, cleared on full-screen exit and destroy. |
357
+ | `setContextProcessor(processor, silent?, fullScreen?)` | Route subsequent input to a processor. |
358
+ | `submitCommand(line)` | Run a line as if typed (history + prompt). |
359
+ | `promptPathProvider?` | Set to `() => string \| null` to change the path shown in the prompt. |
360
+ | `showPrompt`, `currentLine`, `setCurrentLine`, `cursorPosition`, `clearLine`, `clearCurrentLine`, `refreshCurrentLine`, `promptLength` | Low-level line editing. |
361
+ | `isBooted?` | `true` once boot finished. |
362
+
363
+ ```typescript
364
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
365
+ context.spinner?.show('Loading');
366
+ try {
367
+ const items = await context.http.get<{ name: string }[]>('https://api.example.com/items');
368
+ context.spinner?.hide();
369
+ context.writer.writeObjectsAsTable(items);
370
+ context.process.output(items); // available to the next command in a pipe
371
+ } catch (e) {
372
+ context.spinner?.hide();
373
+ context.writer.writeError(`Request failed: ${e}`);
374
+ context.process.exit(1);
375
+ }
376
+ }
377
+ ```
378
+
379
+ ### Writer API
380
+
381
+ `context.writer` (`ICliTerminalWriter`) writes text, colors, tables, lists, JSON, boxes and links to the terminal.
382
+
383
+ ```typescript
384
+ import { CliForegroundColor } from '@qodalis/cli-core';
385
+
386
+ const w = context.writer;
387
+ w.write('no newline');
388
+ w.writeln('line'); // writeln() alone prints an empty line
389
+ w.writeSuccess('Done');
390
+ w.writeInfo('FYI');
391
+ w.writeWarning('Careful');
392
+ w.writeError('Failed'); // stderr in tests
393
+ w.writeln(w.wrapInColor('cyan text', CliForegroundColor.Cyan));
394
+ w.wrapInBackgroundColor('text', CliBackgroundColor.Blue);
395
+ w.writeJson({ a: 1 }); // pretty, colorized
396
+ w.writeTable(['Name', 'Size'], [['a.txt', '1 KB']]);
397
+ w.writeObjectsAsTable([{ name: 'a', size: 1 }]);
398
+ w.writeList(['one', 'two'], { ordered: true, prefix: '-', color: CliForegroundColor.Green });
399
+ w.writeKeyValue({ Status: 'ok', Version: '1.0' }, { separator: ':', keyColor: CliForegroundColor.Yellow });
400
+ w.writeColumns(['a', 'b', 'c', 'd'], { columns: 2, padding: 2 });
401
+ w.writeDivider({ char: '-', length: 40, color: CliForegroundColor.White });
402
+ w.writeBox(['Line 1', 'Line 2'], { title: 'Notice', borderColor: CliForegroundColor.Cyan, padding: 1 });
403
+ w.writeLink('Docs', 'https://cli.qodalis.com');
404
+ w.writeIndented('indented', 2); // 2 spaces per level
405
+ w.writeToFile('report.txt', 'content'); // browser download
406
+ ```
407
+
408
+ - Colors: `CliForegroundColor` / `CliBackgroundColor` enums (`Black`, `Red`, `Green`, `Yellow`, `Blue`, `Magenta`, `Cyan`, `White`, `Reset`).
409
+ - Use `\r\n` or `writeln` for new lines; xterm needs carriage returns with raw `write`.
410
+
411
+ ### Input reader
412
+
413
+ `context.reader` (`ICliInputReader`) shows interactive prompts; every method resolves `null` when the user aborts (Ctrl+C or Escape).
414
+
415
+ ```typescript
416
+ const name = await context.reader.readLine('Name: ', {
417
+ default: 'guest',
418
+ placeholder: 'your name',
419
+ validate: (v) => (v.trim() ? null : 'Name is required'), // string = error, null = ok
420
+ });
421
+ if (name === null) return; // aborted
422
+
423
+ const password = await context.reader.readPassword('Password: ');
424
+ const ok = await context.reader.readConfirm('Continue?', true); // boolean | null
425
+ const env = await context.reader.readSelect('Environment:', [
426
+ { label: 'Production', value: 'prod', description: 'live', group: 'Remote' },
427
+ { label: 'Staging', value: 'stage', group: 'Remote' },
428
+ { label: 'Local', value: 'local', disabled: true },
429
+ ], { default: 'stage', searchable: true, onChange: (v) => {} });
430
+ const size = await context.reader.readSelectInline('Size:', [
431
+ { label: 'S', value: 's' }, { label: 'M', value: 'm' },
432
+ ]);
433
+ const tags = await context.reader.readMultiSelect('Tags:', [
434
+ { label: 'bug', value: 'bug', checked: true }, { label: 'feature', value: 'feature' },
435
+ ], { searchable: true }); // string[] | null
436
+ const count = await context.reader.readNumber('Count:', { min: 1, max: 10, default: 3 });
437
+ const date = await context.reader.readDate('Due date:', { format: 'YYYY-MM-DD', min: '2026-01-01' });
438
+ const files = await context.reader.readFile('Pick a file', { multiple: false }); // CliFileResult[] | null
439
+ ```
440
+
441
+ ### State store and persistence
442
+
443
+ Each root processor gets its own state store (`context.state`) configured by `stateConfiguration`; sub-commands share their root's store.
444
+
445
+ ```typescript
446
+ export class CliCounterCommandProcessor implements ICliCommandProcessor {
447
+ command = 'counter';
448
+ stateConfiguration = {
449
+ initialState: { count: 0 },
450
+ storeName: 'counter', // default: the command name
451
+ autoPersist: true, // save after every change (else call persist())
452
+ scope: 'global' as const, // 'global' (browser, all tabs) | 'user' (per signed-in user) | 'session' (this terminal, memory)
453
+ version: 1,
454
+ migrate: (state, fromVersion) => state,
455
+ syncAcrossTabs: true,
456
+ };
457
+
458
+ async processCommand(_: CliProcessCommand, context: ICliExecutionContext) {
459
+ const { count } = context.state.getState<{ count: number }>();
460
+ context.state.updateState({ count: count + 1 });
461
+ // or: await context.state.update((s) => ({ count: s['count'] + 1 }));
462
+ context.writer.writeln(`count = ${count + 1}`);
463
+ }
464
+ }
465
+ ```
466
+
467
+ - `ICliStateStore`: `getState<T>()`, `updateState(partial)`, `update(fn)`, `select(selector)` (Observable), `subscribe(cb)`, `reset()`, `persist()`, `initialize()`, `reload?()`.
468
+ - `configurationOptions` values (set with `configure`) are read with `getPluginConfigValue(context, '<command>', '<key>', defaultValue)` from `@qodalis/cli-core`.
469
+
470
+ ### Configuration options
471
+
472
+ `configurationOptions` exposes processor settings in the built-in `configure` command (interactive menu and `configure get/set`).
473
+
474
+ ```typescript
475
+ import { getPluginConfigValue, ICliConfigurationOption } from '@qodalis/cli-core';
476
+
477
+ configurationOptions: ICliConfigurationOption[] = [
478
+ { key: 'units', label: 'Units', description: 'Temperature units', type: 'select', defaultValue: 'metric',
479
+ options: [{ label: 'Metric', value: 'metric' }, { label: 'Imperial', value: 'imperial' }] },
480
+ { key: 'maxDays', label: 'Max days', description: 'Forecast length', type: 'number', defaultValue: 3,
481
+ validator: (v) => (v >= 1 && v <= 7 ? { valid: true } : { valid: false, message: '1-7' }) },
482
+ ];
483
+
484
+ // in processCommand
485
+ const units = getPluginConfigValue(context, 'weather', 'units', 'metric');
486
+ ```
487
+
488
+ - Option `type`: `'string' | 'number' | 'boolean' | 'select'`; `category` overrides the grouping (default: the processor's command name, which is also the category passed to `getPluginConfigValue`).
489
+
490
+ ### Services and dependency injection
491
+
492
+ Modules register services with `services: CliProvider[]`; commands resolve them from `context.services` by token.
493
+
494
+ ```typescript
495
+ import { API_VERSION, createCliToken, ICliModule } from '@qodalis/cli-core';
496
+
497
+ export interface IWeatherApi { current(city: string): Promise<string>; }
498
+ export const IWeatherApi_TOKEN = createCliToken<IWeatherApi>('weather-api'); // typed string token
499
+
500
+ class WeatherApi implements IWeatherApi {
501
+ constructor(private readonly baseUrl: string) {}
502
+ async current(city: string) { return `${city}: sunny`; }
503
+ }
504
+
505
+ export const weatherModule: ICliModule = {
506
+ apiVersion: API_VERSION,
507
+ name: '@acme/cli-weather',
508
+ services: [
509
+ { provide: 'weather-base-url', useValue: 'https://api.example.com' },
510
+ { provide: IWeatherApi_TOKEN, useClass: WeatherApi, deps: ['weather-base-url'] },
511
+ // { provide: TOKEN, useFactory: (url: string) => new WeatherApi(url), deps: ['weather-base-url'] },
512
+ // { provide: TOKEN, useValue: x, multi: true } // multi-provider: read with getAll
513
+ ],
514
+ processors: [/* ... */],
515
+ };
516
+
517
+ // in processCommand
518
+ const api = context.services.getRequired(IWeatherApi_TOKEN); // throws if missing; get() returns undefined
519
+ ```
520
+
521
+ - `CliProvider` = `{ provide, sealed?, transient?, multi? }` plus one of `useValue`, `useClass` (+ `deps`), `useFactory` (+ `deps`). `useClass`/`useFactory` are created lazily on first `get`, so `deps` may be registered later.
522
+ - `sealed: true` prevents overriding the token; `transient: true` creates a new instance per `get`.
523
+ - Well-known tokens are exported from `@qodalis/cli-core` (e.g. `ICliAuthorizationService_TOKEN`, `ICliCommandGuard_TOKEN`, `ICliServerAuthTokenProvider_TOKEN`, `ICliTranslationService_TOKEN`).
524
+
525
+ ### Translations (i18n)
526
+
527
+ Plugins ship translations in `ICliModule.translations` and translate at runtime with `context.translator.t(key, englishDefault, params?)`.
528
+
529
+ ```typescript
530
+ export const weatherModule: ICliModule = {
531
+ apiVersion: API_VERSION,
532
+ name: '@acme/cli-weather',
533
+ processors: [new CliWeatherCommandProcessor()],
534
+ translations: {
535
+ es: { 'cli.weather.description': 'Mostrar el tiempo', 'cli.weather.now': 'Ahora en {city}' },
536
+ fr: { 'cli.weather.description': 'Afficher la météo', 'cli.weather.now': 'Maintenant à {city}' },
537
+ },
538
+ };
539
+
540
+ // in processCommand: English default inline, {param} interpolation
541
+ context.writer.writeln(context.translator.t('cli.weather.now', 'Now in {city}', { city }));
542
+ ```
543
+
544
+ - `help` translates descriptions automatically with key `cli.<command path>.description` (e.g. `cli.weather.forecast.description`).
545
+ - Locale codes used by the official language packs: `de`, `es`, `fr`, `it`, `ja`, `ko`, `pt`, `ro`, `ru`, `zh`. Missing keys fall back to the default string.
546
+
547
+ ### HTTP client
548
+
549
+ `context.http` (`ICliHttpClient`) is a fetch wrapper that parses JSON, throws `CliHttpError` on non-2xx and aborts on Ctrl+C.
550
+
551
+ ```typescript
552
+ import { CliHttpError } from '@qodalis/cli-core';
553
+
554
+ try {
555
+ const user = await context.http.get<{ name: string }>('https://api.example.com/me', { timeout: 5000 });
556
+ await context.http.post('https://api.example.com/items', { name: 'x' }, { headers: { 'X-Key': 'k' } });
557
+ } catch (e) {
558
+ if (e instanceof CliHttpError) context.writer.writeError(`${e.status} ${e.statusText}`);
559
+ else throw e;
560
+ }
561
+ ```
562
+
563
+ - Methods: `fetch(url, init?)` (raw `Response`), `get`, `post(url, body?)`, `put`, `patch`, `delete`, `head` (returns `Response`), `options`. Options extend `RequestInit` (minus `method`/`body`) with `timeout` (ms).
564
+
565
+ ### Background services and jobs
566
+
567
+ `context.backgroundServices` runs daemons (long-lived) and jobs (one-shot) outside the command, on the main thread or in a Web Worker.
568
+
569
+ ```typescript
570
+ export const heartbeatModule: ICliModule = {
571
+ apiVersion: API_VERSION,
572
+ name: '@acme/cli-heartbeat',
573
+ async onAfterBoot(context) {
574
+ context.backgroundServices.register({
575
+ name: 'heartbeat',
576
+ description: 'Logs every 10s',
577
+ type: 'daemon', // 'daemon' | 'job'
578
+ async onStart(ctx) {
579
+ ctx.createInterval(() => ctx.log('beat'), 10000);
580
+ ctx.emit({ source: 'heartbeat', type: 'started' });
581
+ },
582
+ async onStop(ctx) { ctx.log('stopped'); },
583
+ onError(error, ctx) { ctx.log(error.message, 'error'); },
584
+ });
585
+ await context.backgroundServices.start('heartbeat');
586
+ },
587
+ };
588
+
589
+ // one-shot job from a command
590
+ await context.backgroundServices.startJob('export', async (ctx) => {
591
+ ctx.log('exporting...');
592
+ if (ctx.signal.aborted) return;
593
+ });
594
+ ```
595
+
596
+ - `ICliServiceContext` (`ctx`): `signal`, `emit(event)`, `log(message, level?)` (`'info' | 'warn' | 'error'`), `createInterval`, `createTimeout`, `state`, `services`.
597
+ - Registry: `register`, `start(name)`, `stop(name)`, `restart(name)`, `startJob(name, task, { workerCompatible? })`, `getStatus(name)`, `list()`, `getLogs(name, limit?)`, `on(handler, { source?, type? })` (returns unsubscribe), `destroyAll()`.
598
+ - Worker mode: set `workerCompatible: true` and `workerFactory: () => new Worker(...)`; `onStart` is the main-thread fallback. Users manage services with the built-in `services` command.
599
+
600
+ ### Full-screen mode and raw input
601
+
602
+ A processor can take over the terminal (games, editors, pagers) with `enterFullScreenMode`, receiving every keystroke in `onData`.
603
+
604
+ ```typescript
605
+ export class CliClockCommandProcessor implements ICliCommandProcessor {
606
+ command = 'clock';
607
+ description = 'Full-screen clock (q to quit)';
608
+ private context?: ICliExecutionContext;
609
+
610
+ async processCommand(_: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
611
+ this.context = context;
612
+ context.enterFullScreenMode(this); // alternate screen, cursor hidden
613
+ this.render();
614
+ context.createInterval(() => this.render(), 1000); // cleared automatically on exit
615
+ }
616
+
617
+ async onData(data: string, context: ICliExecutionContext): Promise<void> {
618
+ if (data === 'q' || data === '\x1b') context.exitFullScreenMode(); // also restores the prompt
619
+ }
620
+
621
+ onResize(cols: number, rows: number): void { this.render(); }
622
+
623
+ onDispose(): void { this.context = undefined; }
624
+
625
+ private render(): void {
626
+ const t = this.context?.terminal;
627
+ if (!t) return;
628
+ t.write('\x1b[H\x1b[2J'); // home + clear
629
+ t.write(new Date().toLocaleTimeString());
630
+ }
631
+ }
632
+ ```
633
+
634
+ - `onData` receives raw sequences: arrows `\x1b[A`/`\x1b[B`/`\x1b[C`/`\x1b[D`, Enter `\r`, Backspace `\x7f`, Escape `\x1b`, Ctrl+C `\x03` (passed through in full-screen mode).
635
+ - Pass `{ showCursor: true }` for REPL-style UIs.
636
+
637
+ ### Touch keys for full-screen commands (controls)
638
+
639
+ A full-screen command lists the keys it reads in `controls`, so phones (which have no Ctrl, Esc or arrow keys) can show them as buttons.
640
+
641
+ Hosts on touch screens (the Qodalis CLI phone app) show them as buttons while the command runs and send each key's `data` to `onData`; help screens can list them.
642
+
643
+ ```typescript
644
+ import { CliKeyData, ICliCommandControls } from '@qodalis/cli-core';
645
+
646
+ controls: ICliCommandControls = {
647
+ keys: [
648
+ { label: 'ESC', key: 'Esc', data: CliKeyData.escape, description: 'Quit' },
649
+ { label: 'PAUSE', key: 'Space', data: CliKeyData.space, description: 'Pause' },
650
+ { label: '←', key: 'Left', data: CliKeyData.left, description: 'Left', repeat: true },
651
+ { label: 'SAVE', key: 'Ctrl+S', data: CliKeyData.ctrl('s'), description: 'Save' },
652
+ ],
653
+ swipe: true, // swipes on the screen send arrows (games on a board)
654
+ tap: CliKeyData.space, // a tap sends this key's data
655
+ // textInput: true, // the command also reads typed text (editors): keep the keyboard open
656
+ };
657
+ ```
658
+
659
+ - `data` is what a terminal sends for the key (`CliKeyData` has the arrows, Home/End, PgUp/PgDn, Esc, Enter, Backspace and `ctrl(letter)`); a letter key is just the letter (`'f'`).
660
+ - List the most used keys first; `repeat: true` repeats a held key.
661
+ - Without `textInput`, touch hosts close the on-screen keyboard so the command gets the screen (a hardware keyboard keeps working).
662
+
663
+ ### Extending an existing command
664
+
665
+ Set `extendsProcessor = true` to wrap a processor registered with the same `command` and delegate to `originalProcessor`.
666
+
667
+ ```typescript
668
+ export class EchoTimestampProcessor implements ICliCommandProcessor {
669
+ command = 'echo';
670
+ extendsProcessor = true;
671
+ acceptsRawInput = true;
672
+ originalProcessor?: ICliCommandProcessor; // set by the registry
673
+
674
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext) {
675
+ context.writer.write(`[${new Date().toISOString()}] `);
676
+ await this.originalProcessor?.processCommand(command, context);
677
+ }
678
+ }
679
+ ```
680
+
681
+ - Without `extendsProcessor`, registering a processor with an existing command replaces it (unless the existing one has `metadata.sealed`).
682
+
683
+ ### Registering a module in a host app
684
+
685
+ Hosts pass plugin modules to the terminal: Angular DI or `[modules]`, React/Vue `modules` prop, or `CliEngine.registerModule` in plain TypeScript.
686
+
687
+ ```typescript
688
+ // Angular (NgModule)
689
+ import { CliModule, resolveCliModuleProvider } from '@qodalis/angular-cli';
690
+ import { guidModule } from '@qodalis/cli-guid';
691
+
692
+ @NgModule({
693
+ imports: [BrowserModule, CliModule],
694
+ providers: [resolveCliModuleProvider(guidModule), resolveCliModuleProvider(weatherModule)],
695
+ })
696
+ export class AppModule {}
697
+ // template: <cli></cli> or <cli-panel></cli-panel>; or pass [modules]="modules" on either
698
+ ```
699
+
700
+ ```tsx
701
+ // React
702
+ import { Cli, CliConfigProvider } from '@qodalis/react-cli';
703
+
704
+ <Cli modules={[guidModule, weatherModule]} />
705
+ // or share config: <CliConfigProvider modules={modules} options={options}><Cli /></CliConfigProvider>
706
+ ```
707
+
708
+ ```html
709
+ <!-- Vue 3 -->
710
+ <script setup lang="ts">
711
+ import { Cli } from '@qodalis/vue-cli';
712
+ const modules = [guidModule, weatherModule];
713
+ </script>
714
+ <template>
715
+ <Cli :modules="modules" />
716
+ </template>
717
+ ```
718
+
719
+ ```typescript
720
+ // Vanilla TypeScript
721
+ import '@xterm/xterm/css/xterm.css';
722
+ import { CliEngine } from '@qodalis/cli';
723
+ import { CliLogLevel } from '@qodalis/cli-core';
724
+
725
+ const engine = new CliEngine(document.getElementById('terminal')!, { logLevel: CliLogLevel.INFO });
726
+ engine.registerModule(weatherModule); // or registerModules([...]); before start()
727
+ await engine.start();
728
+ ```
729
+
730
+ - `<CliPanel>` (React/Vue) and `<cli-panel>` (Angular) accept the same `modules`.
731
+ - Configured modules: pass `weatherModule.configure({ ... })` instead of `weatherModule`.
732
+
733
+ ### Runtime installation with pkg add (UMD)
734
+
735
+ Published plugins can be installed in a running terminal with `pkg add @qodalis/cli-<name>`, which loads the plugin's IIFE bundle and boots its module.
736
+
737
+ ```bash
738
+ pkg add @qodalis/cli-weather # alias: packages add
739
+ pkg ls
740
+ pkg remove @qodalis/cli-weather
741
+ ```
742
+
743
+ ```typescript
744
+ // src/cli-entrypoint.ts (bundled to dist/umd/index.global.js by tsup, format 'iife')
745
+ import { bootCliModule, ICliModule } from '@qodalis/cli-core';
746
+ import { CliWeatherCommandProcessor } from './lib/processors/cli-weather-command-processor';
747
+ import { API_VERSION } from './lib/version';
748
+
749
+ const module: ICliModule = {
750
+ apiVersion: API_VERSION,
751
+ name: '@qodalis/cli-weather',
752
+ processors: [new CliWeatherCommandProcessor()],
753
+ };
754
+
755
+ bootCliModule(module);
756
+ ```
757
+
758
+ - `package.json` fields `umd` and `unpkg` point at the IIFE bundle; packages are fetched from unpkg/jsdelivr by default (`CliOptions.packageSources` adds sources).
759
+ - `bootCliModule(module)` registers the module with the running terminal's module registry; it does nothing outside a browser terminal.
760
+ - UMD bundles must not use Angular decorators; use plain classes.
761
+
762
+ ### Testing with CliTestHarness
763
+
764
+ `CliTestHarness` (from `@qodalis/cli`) runs commands through the real parser and executor without xterm or DOM, capturing output.
765
+
766
+ ```typescript
767
+ import { CliTestHarness } from '@qodalis/cli';
768
+ import { CliNotesCommandProcessor } from '../lib/processors/cli-notes-command-processor';
769
+ import { CliGreetCommandProcessor } from '../lib/processors/cli-greet-command-processor';
770
+
771
+ describe('notes', () => {
772
+ let harness: CliTestHarness;
773
+
774
+ beforeEach(() => {
775
+ harness = new CliTestHarness();
776
+ harness.registerProcessor(new CliNotesCommandProcessor());
777
+ });
778
+
779
+ it('adds and lists notes', async () => {
780
+ await harness.execute('notes add "buy milk"');
781
+ const result = await harness.execute('notes list');
782
+ expect(result.lists[0]).toEqual(['buy milk']);
783
+ expect(result.exitCode).toBe(0);
784
+ });
785
+
786
+ it('answers prompts', async () => {
787
+ harness.registerProcessor(new CliGreetCommandProcessor()); // calls readLine then readConfirm
788
+ harness.setReaderResponses('Ada', true); // consumed in order by readLine, readConfirm, ...
789
+ const result = await harness.execute('greet');
790
+ expect(result.output).toContain('Ada');
791
+ });
792
+ });
793
+ ```
794
+
795
+ - Result (`CliTestResult`): `stdout: string[]`, `stderr: string[]` (writeError/writeWarning), `output` (stdout joined by `\n`), `exitCode`, `data` (from `process.output`), `tables: { headers, rows }[]`, `lists: string[][]`.
796
+ - Harness API: `registerProcessor(p)`, `registerProcessors([...])`, `registerService(token, value)`, `initializeProcessors()`, `setReaderResponses(...values)`, `setUserSession(session)`, `setUserSessionProvider(fn)`, `execute(line)`, plus `registry`, `executor`, `services`, `translator`.
797
+ - Pipes work: `harness.execute('echo hello | grep hello')`. State is in memory per harness.
798
+ - In the monorepo, tests are Jasmine on Karma (`pnpm nx test <name>`, ChromeHeadless). Test files live in `src/tests/*.spec.ts`.
799
+
800
+ ### Building and publishing a web plugin
801
+
802
+ Web plugins build with tsup into CJS, ESM, type declarations and an IIFE bundle for runtime loading, then publish to npm.
803
+
804
+ ```bash
805
+ # standalone plugin
806
+ npx tsup # or npm run build -> dist/public-api.{js,mjs,d.ts}, dist/umd/index.global.js
807
+ npm publish --access public # files: ["dist"]
808
+
809
+ # monorepo plugin
810
+ pnpm nx build <name> # -> dist/<name>/
811
+ pnpm nx test <name>
812
+ pnpm nx lint <name>
813
+ ```
814
+
815
+ - Mark `@qodalis/cli-core` as external in the library build (the scaffolded `tsup.config.ts` does); the IIFE build bundles everything (`noExternal: [/.*/]`).
816
+ - `@qodalis/cli-core` is a dependency; standalone plugins pin `^<scaffolder version>` (all `@qodalis/*` web packages share one version).
817
+
818
+ ### Conventions for web plugins
819
+
820
+ Naming, structure and API-version rules that official and third-party web plugins follow.
821
+
822
+ - Package `@qodalis/cli-<name>` for official plugins (any scope for third-party); module export `<camelName>Module`; processor class `Cli<Name>CommandProcessor` in `src/lib/processors/cli-<name>-command-processor.ts`; module name = package name.
823
+ - Always set `apiVersion: API_VERSION` (2). Plugins depend only on `@qodalis/cli-core` (never on Angular/React/Vue).
824
+ - Translation keys: `cli.<command path>.<key>`; always pass the English default to `t()`.
825
+ - Use `context.writer` for output (never `console.log`), `context.http` for requests (abort on Ctrl+C), `context.reader` for prompts, `createInterval`/`createTimeout` for timers in full-screen apps.
826
+ - Check `null` from every reader method (user aborted). Exit with `context.process.exit(1)` on failure so pipes and `&&` stop (it throws to end the command; code after it does not run).
827
+ - TypeScript style in the monorepo: 4-space indent, single quotes, semicolons.
828
+
829
+ ## Server plugins
830
+
831
+ ### How server commands reach the browser terminal
832
+
833
+ A server plugin registers command processors in a Qodalis CLI server (Node, .NET or Python); the browser terminal discovers them and proxies execution over HTTP.
834
+
835
+ - The host app lists servers in `CliOptions.servers`: `{ name: 'node', url: 'http://localhost:8047' }` (optional `headers`, `timeout`, `enabled`).
836
+ - At startup the terminal calls `GET /api/qcli/versions` and `GET /api/v1/qcli/commands`, then registers each root command as `<server>:<command>` (e.g. `node:weather`) and as the bare name (`weather`) unless a local web command already owns it. If several servers have the command, the bare name uses the default server (`server default <name>`) or asks.
837
+ - Running a command sends `POST /api/v1/qcli/execute` with `{ command, chainCommands, rawCommand, value, positionals, args, data }`; the server resolves the processor and returns `{ exitCode, outputs: [...] }`. `POST /api/v1/qcli/execute/stream` returns Server-Sent Events (`output`, `done`, `error`).
838
+ - Output types rendered by the browser: `text` (optional `style`: `success | error | info | warning`), `table` (`headers`, `rows`), `list` (`items`, `ordered?`), `json` (`value`), `key-value` (`entries: { key, value }[]`).
839
+ - In the browser, a server command that has sub-commands accepts only its sub-command words; a leaf command accepts positional text (`weather current Paris`).
840
+ - Exceptions thrown by a processor become exit code 1 with `Error executing command: <message>` (style `error`). Unknown commands return `Unknown command: <name>`.
841
+ - Servers: Node `@qodalis/cli-server-node` (default port 8047 in the demos), .NET `Qodalis.Cli` (8046), Python `qodalis-cli-server` (8048).
842
+
843
+ ### Paging list output (all servers)
844
+
845
+ A command that can return many rows must page them: a terminal should never receive thousands of rows.
846
+
847
+ - Declare the parameters: `--skip` (default 0) and `--take` (default 50, at most 500). Node `CliPaging.parameters()`, .NET `CliPaging.Parameters()` (`Qodalis.Cli.Abstractions.Helpers`), Python `CliPaging.parameters()`.
848
+ - Read the request: Node `CliPaging.from(command)`, .NET `CliPaging.From(command)`, Python `CliPaging.from_command(command)`. It gives `skip` and `take` for the query; missing or invalid values fall back to the defaults.
849
+ - Query those rows (and the total when it is cheap) and write it with the paged table writer: Node `writePagedTable(headers, rows, page, { total, hasMore })`, .NET `WritePagedTable(headers, rows, page, total, hasMore)`, Python `write_paged_table(headers, rows, page, total=None, has_more=None)`. Without a total, pass `hasMore` (query `take + 1` rows to find out).
850
+ - On the wire the table carries `page: { skip, take, total?, hasMore }`. The web terminal prints `Rows 51–100 of 1987 · next: <command> --skip 100` under it; MCP text output adds `(rows 51-100 of 1987; next: skip=100)`.
851
+ - Safety net: a table without a page that has more than the server's `maxTableRows` / `MaxTableRows` / `max_table_rows` rows (default 200, 0 = no limit) is cut to that many and marked `page.truncated`; the terminal says the command does not page. Do not rely on it: page instead.
852
+
853
+ .NET example:
854
+
855
+ ```csharp
856
+ public override IEnumerable<ICliCommandParameterDescriptor>? Parameters { get; set; } = CliPaging.Parameters();
857
+
858
+ public async Task<ICliStructuredResponse?> HandleStructuredAsync(CliProcessCommand command, CancellationToken cancellationToken = default)
859
+ {
860
+ var page = CliPaging.From(command);
861
+ var total = await db.Orders.CountAsync(cancellationToken);
862
+ var rows = await db.Orders.OrderBy(o => o.Id).Skip(page.Skip).Take(page.Take)
863
+ .Select(o => new[] { o.Id.ToString(), o.Customer }).ToArrayAsync(cancellationToken);
864
+
865
+ var builder = new CliResponseBuilder();
866
+ builder.WritePagedTable(["Id", "Customer"], rows, page, total);
867
+ return builder.Build();
868
+ }
869
+ ```
870
+
871
+ ### Node: minimal server processor
872
+
873
+ A Node server command extends `CliCommandProcessor` from `@qodalis/cli-server-abstractions` and returns its output text from `handleAsync`.
874
+
875
+ ```typescript
876
+ import {
877
+ CliCommandProcessor,
878
+ CliProcessCommand,
879
+ getPositionalText,
880
+ } from '@qodalis/cli-server-abstractions';
881
+
882
+ export class CliGreetCommandProcessor extends CliCommandProcessor {
883
+ command = 'greet';
884
+ description = 'Greets someone';
885
+ acceptsValue = true; // optional positional value (valueRequired = true makes it mandatory)
886
+
887
+ async handleAsync(command: CliProcessCommand, signal?: AbortSignal): Promise<string> {
888
+ const name = getPositionalText(command) || 'world';
889
+ return `Hello, ${name}!`;
890
+ }
891
+ }
892
+ ```
893
+
894
+ ```typescript
895
+ import { createCliServer } from '@qodalis/cli-server-node';
896
+
897
+ const { app } = createCliServer({
898
+ configure: (builder) => builder.addProcessor(new CliGreetCommandProcessor()),
899
+ });
900
+ app.listen(8047);
901
+ ```
902
+
903
+ - `ICliCommandProcessor` members: `command`, `description`, `author` (default `DefaultLibraryAuthor`), `version` (default `'1.0.0'`), `allowUnlistedCommands?`, `valueRequired?`, `acceptsValue?`, `processors?`, `parameters?`, `requiredPermissions?`, `handleAsync(command, signal?) => Promise<string>`, `handleStructuredAsync?(command, signal?) => Promise<CliStructuredResponse>` (takes precedence when present).
904
+ - `CliProcessCommand`: `command`, `chainCommands: string[]`, `rawCommand`, `value?` (as typed), `positionals?: string[]` (shell-split; sent by current browsers), `args: Record<string, any>`, `data?`. Helpers: `getPositionals(command)` (falls back to splitting `value`), `getPositionalText(command)`, `splitShellWords`, `joinShellWords`, `quoteShellWord`.
905
+ - `signal` is aborted when the HTTP client disconnects.
906
+ - Packages: `npm install @qodalis/cli-server-abstractions` for plugins; `@qodalis/cli-server-node` for the host.
907
+
908
+ ### Node: parameters, sub-commands and modules
909
+
910
+ Node server commands declare flags with `CliCommandParameterDescriptor`, nest sub-commands in `processors`, and are grouped into a `CliModule` registered with `builder.addModule`.
911
+
912
+ ```typescript
913
+ import {
914
+ CliCommandParameterDescriptor,
915
+ CliCommandProcessor,
916
+ CliModule,
917
+ CliProcessCommand,
918
+ getPositionalText,
919
+ ICliCommandProcessor,
920
+ } from '@qodalis/cli-server-abstractions';
921
+
922
+ // constructor order: (name, description, required = false, type = 'string', aliases?, defaultValue?)
923
+ const locationParam = new CliCommandParameterDescriptor(
924
+ 'location', 'City name', false, 'string', ['-l'], 'London',
925
+ );
926
+
927
+ function location(command: CliProcessCommand): string {
928
+ return command.args?.location ? String(command.args.location) : getPositionalText(command) || 'London';
929
+ }
930
+
931
+ class WeatherCurrentProcessor extends CliCommandProcessor {
932
+ command = 'current';
933
+ description = 'Current conditions';
934
+ parameters = [locationParam];
935
+ acceptsValue = true;
936
+ async handleAsync(command: CliProcessCommand): Promise<string> {
937
+ return `Sunny in ${location(command)}`;
938
+ }
939
+ }
940
+
941
+ class CliWeatherCommandProcessor extends CliCommandProcessor {
942
+ command = 'weather';
943
+ description = 'Weather information';
944
+ parameters = [locationParam];
945
+ processors: ICliCommandProcessor[] = [new WeatherCurrentProcessor()];
946
+ async handleAsync(command: CliProcessCommand): Promise<string> {
947
+ return `Sunny in ${location(command)}`;
948
+ }
949
+ }
950
+
951
+ export class WeatherModule extends CliModule {
952
+ name = 'weather';
953
+ version = '1.0.0';
954
+ description = 'Weather commands';
955
+ processors: ICliCommandProcessor[] = [new CliWeatherCommandProcessor()];
956
+ }
957
+
958
+ // host: createCliServer({ configure: (builder) => builder.addModule(new WeatherModule()) });
959
+ ```
960
+
961
+ - Dispatch: root by `command` (case-insensitive), then each `chainCommands` word against `processors`. If a word matches no child, the current processor handles it only when `allowUnlistedCommands` is true; otherwise `Unknown command`. Only the resolved processor runs.
962
+ - Registering a second processor with the same command replaces the first.
963
+ - `CliBuilder` (all chainable): `addProcessor(p)`, `addModule(m)`, `addMcpToolProvider(provider)`, `setFileStorageProvider(...)`, `addDataExplorerProvider(...)`, `addFileSystem(options)`.
964
+ - `createCliServer(options)` options: `basePath` (default `'/api/qcli'`), `cors`, `allowedOrigins`, `enableShell`, `shell`, `trustProxy`, `auth`, `mcp` (`boolean | CliMcpOptions`), `configure(builder)`. Returns `{ app, registry, builder, executor, eventSocketManager, logSocketManager, mountPlugin, setAuth, mcp }`.
965
+
966
+ ### Node: structured and streaming output
967
+
968
+ Node processors return tables, lists, JSON and key-value output from `handleStructuredAsync`, or stream outputs over SSE with `handleStreamAsync`.
969
+
970
+ ```typescript
971
+ import {
972
+ CliCommandProcessor,
973
+ CliProcessCommand,
974
+ CliStructuredOutput,
975
+ CliStructuredResponse,
976
+ ICliStreamCommandProcessor,
977
+ } from '@qodalis/cli-server-abstractions';
978
+
979
+ export class CliUsersCommandProcessor extends CliCommandProcessor implements ICliStreamCommandProcessor {
980
+ command = 'users';
981
+ description = 'Lists users';
982
+
983
+ async handleAsync(): Promise<string> {
984
+ return 'use the structured output';
985
+ }
986
+
987
+ async handleStructuredAsync(command: CliProcessCommand): Promise<CliStructuredResponse> {
988
+ return {
989
+ exitCode: 0,
990
+ outputs: [
991
+ { type: 'text', value: '2 users', style: 'info' },
992
+ { type: 'table', headers: ['Name', 'Role'], rows: [['ada', 'admin'], ['bob', 'user']] },
993
+ { type: 'key-value', entries: [{ key: 'Total', value: '2' }] },
994
+ ],
995
+ };
996
+ }
997
+
998
+ async handleStreamAsync(
999
+ command: CliProcessCommand,
1000
+ emit: (output: CliStructuredOutput) => void,
1001
+ signal?: AbortSignal,
1002
+ ): Promise<number> {
1003
+ for (const name of ['ada', 'bob']) {
1004
+ if (signal?.aborted) return 1;
1005
+ emit({ type: 'text', value: name });
1006
+ }
1007
+ return 0; // exit code
1008
+ }
1009
+ }
1010
+ ```
1011
+
1012
+ - `CliStructuredOutput` = `text` (`value`, `style?`) | `table` (`headers`, `rows`, `page?`) | `list` (`items`, `ordered?`) | `json` (`value`) | `key-value` (`entries`). Import these types from `@qodalis/cli-server-abstractions` (the server package re-exports them as `CliServerOutput` / `CliServerResponse`).
1013
+ - `CliResponseBuilder` (from `@qodalis/cli-server-node`): `writeText(text, style?)`, `writeTable(headers, rows)`, `writePagedTable(headers, rows, page, { total?, hasMore? })`, `writeList(items, ordered?)`, `writeJson(value)`, `writeKeyValue(record)`, `setExitCode(code)`, `build()`.
1014
+ - `/execute/stream` prefers `handleStreamAsync`, then `handleStructuredAsync` (each output emitted), then `handleAsync`.
1015
+
1016
+ ### Node: permissions and MCP tools
1017
+
1018
+ Node processors declare `requiredPermissions`; every command automatically becomes an MCP tool when MCP is on, and plugins can add custom tools with an `McpToolProvider`.
1019
+
1020
+ ```typescript
1021
+ import { createCliServer, mcpError, mcpObjectSchema, McpToolProvider } from '@qodalis/cli-server-node';
1022
+
1023
+ class CliDeployCommandProcessor extends CliCommandProcessor {
1024
+ command = 'deploy';
1025
+ description = 'Deploys the app';
1026
+ requiredPermissions = ['deploy:run']; // plus commands:execute; enforced when the server is protected
1027
+ async handleAsync(): Promise<string> { return 'deployed'; }
1028
+ }
1029
+
1030
+ const statusTools: McpToolProvider = {
1031
+ name: 'status',
1032
+ getTools: () => [
1033
+ {
1034
+ name: 'status_ping', // ^[a-z0-9_-]{1,64}$
1035
+ description: 'Ping a host',
1036
+ inputSchema: mcpObjectSchema({ host: { type: 'string', description: 'Host name' } }, ['host']),
1037
+ requiredPermissions: [],
1038
+ annotations: { readOnlyHint: true },
1039
+ call: async (args, context) =>
1040
+ args.host ? { text: `pong ${args.host}`, isError: false } : mcpError('host required'),
1041
+ },
1042
+ ],
1043
+ };
1044
+
1045
+ createCliServer({
1046
+ mcp: { instructions: 'Deployment server tools' }, // or mcp: true; endpoint POST /api/qcli/mcp
1047
+ configure: (builder) => builder.addProcessor(new CliDeployCommandProcessor()).addMcpToolProvider(statusTools),
1048
+ });
1049
+ ```
1050
+
1051
+ - Permissions are enforced only when an auth provider protects the server (the users plugin): `/execute` requires `commands:execute` plus every `requiredPermissions` along the root-to-sub-command chain.
1052
+ - Command tools: a processor becomes a tool when it has no sub-processors, declares parameters or takes a value; name = command path joined with `_` (`weather_current`); input schema = parameters (+ `value`).
1053
+ - `CliMcpOptions`: `enabled?`, `tools?` (allow-list, trailing `*` = prefix), `exclude?`, `token?` (static bearer, only without an auth provider), `instructions?`.
1054
+ - `McpTool.call(args, context)` gets pre-validated args and `{ auth?, signal, request }`; return `McpToolResult` `{ text, structured?, isError }` (helpers `mcpError(message)`, `mcpJson(value, text?)`). Also `server.mcp.addProvider(provider)` after creation.
1055
+
1056
+ ### Node: testing server processors
1057
+
1058
+ Node server processors are tested with Vitest, by calling `handleAsync` directly or through the HTTP API with Supertest.
1059
+
1060
+ ```typescript
1061
+ import { describe, it, expect } from 'vitest';
1062
+ import request from 'supertest';
1063
+ import { createCliServer } from '@qodalis/cli-server-node';
1064
+ import { CliGreetCommandProcessor } from '../greet';
1065
+
1066
+ describe('greet', () => {
1067
+ it('greets directly', async () => {
1068
+ const result = await new CliGreetCommandProcessor().handleAsync({
1069
+ command: 'greet', chainCommands: [], rawCommand: 'greet Ada', value: 'Ada', args: {},
1070
+ });
1071
+ expect(result).toBe('Hello, Ada!');
1072
+ });
1073
+
1074
+ it('greets over HTTP', async () => {
1075
+ const { app } = createCliServer({ configure: (b) => b.addProcessor(new CliGreetCommandProcessor()) });
1076
+ const res = await request(app)
1077
+ .post('/api/v1/qcli/execute')
1078
+ .send({ command: 'greet', chainCommands: [], rawCommand: 'greet Ada', value: 'Ada', args: {} })
1079
+ .expect(200);
1080
+ expect(res.body.exitCode).toBe(0);
1081
+ expect(res.body.outputs[0]).toEqual({ type: 'text', value: 'Hello, Ada!' });
1082
+ });
1083
+ });
1084
+ ```
1085
+
1086
+ ### .NET: minimal server processor
1087
+
1088
+ A .NET server command derives from `Qodalis.Cli.CliCommandProcessor` (interface `ICliCommandProcessor` in `Qodalis.Cli.Abstractions`) and returns text from `HandleAsync`.
1089
+
1090
+ ```csharp
1091
+ using Qodalis.Cli;
1092
+ using Qodalis.Cli.Abstractions;
1093
+ using Qodalis.Cli.Abstractions.Helpers;
1094
+
1095
+ public class CliGreetCommandProcessor : CliCommandProcessor
1096
+ {
1097
+ public override string Command { get; set; } = "greet";
1098
+ public override string Description { get; set; } = "Greets someone";
1099
+ public override bool? AcceptsRawInput { get; set; } = true;
1100
+
1101
+ public override Task<string> HandleAsync(CliProcessCommand command, CancellationToken cancellationToken = default)
1102
+ {
1103
+ var name = CliValueHelpers.GetPositionalText(command);
1104
+ return Task.FromResult($"Hello, {(string.IsNullOrWhiteSpace(name) ? "world" : name)}!");
1105
+ }
1106
+ }
1107
+ ```
1108
+
1109
+ ```csharp
1110
+ // Program.cs
1111
+ builder.Services
1112
+ .AddControllers()
1113
+ .AddCli(cli =>
1114
+ {
1115
+ cli.AddProcessor<CliGreetCommandProcessor>(); // built by DI (constructor injection)
1116
+ });
1117
+
1118
+ var app = builder.Build();
1119
+ app.UseWebSockets();
1120
+ app.MapControllers();
1121
+ app.UseCli(); // after UseWebSockets()
1122
+ app.Run();
1123
+ ```
1124
+
1125
+ - `ICliCommandProcessor`: `Command`, `Description`, `Author` (default `DefaultLibraryAuthor.Instance`), `AllowUnlistedCommands`, `ValueRequired`, `AcceptsRawInput`, `Version` (default `"1.0.0"`), `Processors`, `Parameters`, `RequiredPermissions`, `HandleAsync(command, cancellationToken)`, default-implemented `HandleStructuredAsync(command, cancellationToken)` (return `null` to fall back to `HandleAsync`).
1126
+ - `CliProcessCommand`: `Command`, `Data`, `ChainCommands`, `RawCommand`, `Value`, `Positionals` (may be `null` from old clients), `Args: Dictionary<string, object>`. Helpers in `CliValueHelpers`: `GetPositionals`, `GetPositionalText`, `SplitShellWords`, `JoinShellWords`, `QuoteShellWord`.
1127
+ - The base classes `CliCommandProcessor` and `CliModule` live in the `Qodalis.Cli` package (namespace `Qodalis.Cli`); reference it, not only `Qodalis.Cli.Abstractions`.
1128
+ - The cancellation token is the HTTP request's `RequestAborted`.
1129
+
1130
+ ### .NET: parameters, sub-commands and modules
1131
+
1132
+ .NET server commands declare flags with `CliCommandParameterDescriptor` object initializers, nest sub-commands in `Processors`, and group them in a `CliModule` registered with `cli.AddModule`.
1133
+
1134
+ ```csharp
1135
+ using Qodalis.Cli;
1136
+ using Qodalis.Cli.Abstractions;
1137
+ using Qodalis.Cli.Abstractions.Helpers;
1138
+
1139
+ public class CliWeatherCommandProcessor : CliCommandProcessor
1140
+ {
1141
+ public override string Command { get; set; } = "weather";
1142
+ public override string Description { get; set; } = "Weather information";
1143
+ public override bool? AcceptsRawInput { get; set; } = true;
1144
+
1145
+ public override IEnumerable<ICliCommandParameterDescriptor>? Parameters { get; set; } =
1146
+ [
1147
+ new CliCommandParameterDescriptor
1148
+ {
1149
+ Name = "location", // required member
1150
+ Description = "City name", // required member
1151
+ Aliases = ["-l"],
1152
+ Type = CommandParameterType.String, // String | Number | Boolean | Array | Object
1153
+ DefaultValue = "London",
1154
+ },
1155
+ ];
1156
+
1157
+ public override IEnumerable<ICliCommandProcessor>? Processors { get; set; } = [new WeatherCurrentProcessor()];
1158
+
1159
+ public override Task<string> HandleAsync(CliProcessCommand command, CancellationToken cancellationToken = default)
1160
+ => Task.FromResult($"Sunny in {Location(command)}");
1161
+
1162
+ internal static string Location(CliProcessCommand command) =>
1163
+ command.Args.TryGetValue("location", out var loc) ? loc.ToString()!
1164
+ : CliValueHelpers.GetPositionalText(command) is { Length: > 0 } text ? text : "London";
1165
+ }
1166
+
1167
+ internal class WeatherCurrentProcessor : CliCommandProcessor
1168
+ {
1169
+ public override string Command { get; set; } = "current";
1170
+ public override string Description { get; set; } = "Current conditions";
1171
+ public override bool? AcceptsRawInput { get; set; } = true;
1172
+
1173
+ public override Task<string> HandleAsync(CliProcessCommand command, CancellationToken cancellationToken = default)
1174
+ => Task.FromResult($"Sunny in {CliWeatherCommandProcessor.Location(command)}");
1175
+ }
1176
+
1177
+ public class WeatherModule : CliModule
1178
+ {
1179
+ public override string Name => "weather";
1180
+ public override string Version => "1.0.0";
1181
+ public override string Description => "Weather commands";
1182
+ public override IEnumerable<ICliCommandProcessor> Processors { get; } = [new CliWeatherCommandProcessor()];
1183
+ }
1184
+
1185
+ // Program.cs: .AddCli(cli => cli.AddModule(new WeatherModule()));
1186
+ ```
1187
+
1188
+ - Dispatch: root by `Command` (case-insensitive), then each chain word against `Processors`; at the first word that matches no child the deepest matched processor handles the command (so `weather Paris` runs `weather`).
1189
+ - The last registration of a command name wins.
1190
+ - `CliBuilder` (in `AddCli(cli => ...)`): `AddProcessor<T>()` (DI-built), `AddProcessor(instance)`, `AddProcessorsFromAssembly(assembly)`, `AddModule(module)` (module-created instances, no DI), `AddMcp(o => ...)`, `EnableShell(...)`, `SetAllowedOrigins(...)`, `AddFileSystem(...)`, `AddDataExplorerProvider(...)`, `AddApplicationPart(assembly)`, `Services` (the `IServiceCollection`). Plugins add their own `CliBuilder` extension methods (e.g. `cli.AddJob<T>(...)`).
1191
+ - Packages: `dotnet add package Qodalis.Cli` (brings `Qodalis.Cli.Abstractions`); targets .NET 10.
1192
+
1193
+ ### .NET: structured and streaming output
1194
+
1195
+ .NET processors return structured output by explicitly implementing `ICliCommandProcessor.HandleStructuredAsync` with `CliResponseBuilder`, and stream with `ICliStreamCommandProcessor`.
1196
+
1197
+ ```csharp
1198
+ using Qodalis.Cli;
1199
+ using Qodalis.Cli.Abstractions;
1200
+ using Qodalis.Cli.Models;
1201
+ using Qodalis.Cli.Services;
1202
+
1203
+ public class CliUsersCommandProcessor : CliCommandProcessor, ICliStreamCommandProcessor
1204
+ {
1205
+ public override string Command { get; set; } = "users";
1206
+ public override string Description { get; set; } = "Lists users";
1207
+
1208
+ public override Task<string> HandleAsync(CliProcessCommand command, CancellationToken ct = default)
1209
+ => Task.FromResult(string.Empty);
1210
+
1211
+ // The base class does not declare HandleStructuredAsync: implement the interface member explicitly
1212
+ Task<ICliStructuredResponse?> ICliCommandProcessor.HandleStructuredAsync(CliProcessCommand command, CancellationToken ct)
1213
+ {
1214
+ var builder = new CliResponseBuilder();
1215
+ builder.WriteText("2 users", "info");
1216
+ builder.WriteTable(["Name", "Role"], [["ada", "admin"], ["bob", "user"]]);
1217
+ builder.WriteKeyValue(new Dictionary<string, string> { ["Total"] = "2" });
1218
+ return Task.FromResult<ICliStructuredResponse?>(builder.Build());
1219
+ }
1220
+
1221
+ public async Task<int> HandleStreamAsync(CliProcessCommand command, Func<object, Task> emit, CancellationToken ct = default)
1222
+ {
1223
+ foreach (var name in new[] { "ada", "bob" })
1224
+ {
1225
+ ct.ThrowIfCancellationRequested();
1226
+ await emit(new TextOutput { Value = name });
1227
+ }
1228
+ return 0; // exit code
1229
+ }
1230
+ }
1231
+ ```
1232
+
1233
+ - `ICliResponseBuilder`: `WriteText(text, style?)`, `WriteTable(headers, rows)`, `WritePagedTable(headers, rows, page, total?, hasMore?)`, `WriteList(items, ordered = false)`, `WriteJson(value)`, `WriteKeyValue(dictionary)`, `SetExitCode(code)`, `Build()` -> `CliServerResponse { ExitCode, Outputs }`.
1234
+ - Output classes (`Qodalis.Cli.Models`): `TextOutput { Value, Style }`, `TableOutput { Headers, Rows, Page? }`, `ListOutput { Items, Ordered }`, `JsonOutput { Value }`, `KeyValueOutput { Entries: KeyValueEntry[] }`.
1235
+ - The executor uses the structured result only if it is a `CliServerResponse`; an empty `HandleAsync` string produces no output.
1236
+
1237
+ ### .NET: permissions and MCP tools
1238
+
1239
+ .NET processors declare `RequiredPermissions`; with `cli.AddMcp()` every command is an MCP tool, and plugins add tools by registering an `IMcpToolProvider`.
1240
+
1241
+ ```csharp
1242
+ using System.Text.Json.Nodes;
1243
+ using Qodalis.Cli.Mcp;
1244
+
1245
+ public class CliDeployCommandProcessor : CliCommandProcessor
1246
+ {
1247
+ public override string Command { get; set; } = "deploy";
1248
+ public override string Description { get; set; } = "Deploys the app";
1249
+ public override IEnumerable<string>? RequiredPermissions { get; set; } = ["deploy:run"];
1250
+ public override Task<string> HandleAsync(CliProcessCommand command, CancellationToken ct = default)
1251
+ => Task.FromResult("deployed");
1252
+ }
1253
+
1254
+ internal sealed class StatusMcpToolProvider : IMcpToolProvider
1255
+ {
1256
+ public Task<IReadOnlyList<McpToolDefinition>> GetToolsAsync(McpToolContext context, CancellationToken cancellationToken) =>
1257
+ Task.FromResult<IReadOnlyList<McpToolDefinition>>(
1258
+ [
1259
+ new McpToolDefinition
1260
+ {
1261
+ Name = "status_ping",
1262
+ Description = "Ping a host",
1263
+ InputSchema = McpSchema.Object(new JsonObject { ["host"] = McpSchema.Property("string", "Host name") }, "host"),
1264
+ Annotations = McpToolAnnotations.ReadOnly,
1265
+ CallAsync = (args, ctx, ct) => Task.FromResult(McpToolResult.Ok($"pong {McpSchema.GetString(args, "host")}")),
1266
+ },
1267
+ ]);
1268
+ }
1269
+
1270
+ // Program.cs
1271
+ .AddCli(cli =>
1272
+ {
1273
+ cli.AddProcessor<CliDeployCommandProcessor>();
1274
+ cli.Services.AddMcpToolProvider<StatusMcpToolProvider>();
1275
+ cli.AddMcp(o => o.Instructions = "Deployment server tools"); // POST /api/qcli/mcp
1276
+ });
1277
+ ```
1278
+
1279
+ - Permissions are checked only when the server requires authentication (users plugin): `commands:execute` plus the `RequiredPermissions` of every processor from the root to the resolved sub-command (401 without a principal, 403 when missing).
1280
+ - `McpOptions`: `Enabled`, `Tools` (allow-list, trailing `*`), `Exclude`, `Token`, `Instructions`. Command tools: name = command path joined with `_`; schema from `Parameters` (+ `value`).
1281
+ - `McpToolResult.Ok(text, structured?)` / `McpToolResult.Error(text)`; `McpToolContext` has `Principal`, `Services`, `HttpContext`. Plugin tools win name collisions over command tools.
1282
+
1283
+ ### .NET: testing server processors
1284
+
1285
+ .NET server processors are tested with xUnit by building a `CliCommandRegistry` and `CliCommandExecutorService` directly.
1286
+
1287
+ ```csharp
1288
+ using Microsoft.Extensions.Logging.Abstractions;
1289
+ using Qodalis.Cli.Abstractions;
1290
+ using Qodalis.Cli.Models;
1291
+ using Qodalis.Cli.Services;
1292
+
1293
+ public class GreetTests
1294
+ {
1295
+ [Fact]
1296
+ public async Task Greets()
1297
+ {
1298
+ var registry = new CliCommandRegistry(NullLogger<CliCommandRegistry>.Instance);
1299
+ var executor = new CliCommandExecutorService(registry, NullLogger<CliCommandExecutorService>.Instance, Array.Empty<ICliProcessorFilter>());
1300
+ registry.Register(new CliGreetCommandProcessor());
1301
+
1302
+ var response = await executor.ExecuteAsync(new CliProcessCommand { Command = "greet", Value = "Ada" });
1303
+
1304
+ Assert.Equal(0, response.ExitCode);
1305
+ Assert.Equal("Hello, Ada!", Assert.IsType<TextOutput>(response.Outputs[0]).Value);
1306
+ }
1307
+ }
1308
+ ```
1309
+
1310
+ - Or call `processor.HandleAsync(new CliProcessCommand { ... })` directly. Integration tests use `Microsoft.AspNetCore.Mvc.Testing` / `TestServer`.
1311
+
1312
+ ### Python: minimal server processor
1313
+
1314
+ A Python server command subclasses `CliCommandProcessor` from `qodalis_cli_server_abstractions` and returns text from `async handle_async(command, cancellation_event=None)`.
1315
+
1316
+ ```python
1317
+ import asyncio
1318
+
1319
+ from qodalis_cli_server_abstractions import (
1320
+ CliCommandProcessor,
1321
+ CliProcessCommand,
1322
+ get_positional_text,
1323
+ )
1324
+
1325
+
1326
+ class CliGreetCommandProcessor(CliCommandProcessor):
1327
+ @property
1328
+ def command(self) -> str:
1329
+ return "greet"
1330
+
1331
+ @property
1332
+ def description(self) -> str:
1333
+ return "Greets someone"
1334
+
1335
+ @property
1336
+ def value_required(self) -> bool | None:
1337
+ return False # False = optional positional value, True = required, None = no value
1338
+
1339
+ async def handle_async(
1340
+ self,
1341
+ command: CliProcessCommand,
1342
+ cancellation_event: asyncio.Event | None = None,
1343
+ ) -> str:
1344
+ return f"Hello, {get_positional_text(command) or 'world'}!"
1345
+ ```
1346
+
1347
+ ```python
1348
+ import uvicorn
1349
+ from qodalis_cli import CliServerOptions, create_cli_server
1350
+
1351
+ result = create_cli_server(
1352
+ CliServerOptions(configure=lambda builder: builder.add_processor(CliGreetCommandProcessor()))
1353
+ )
1354
+ uvicorn.run(result.app, host="0.0.0.0", port=8048)
1355
+ ```
1356
+
1357
+ - `ICliCommandProcessor` properties: `command` and `description` (abstract), `author` (default `DEFAULT_LIBRARY_AUTHOR`), `version` (`"1.0.0"`), `allow_unlisted_commands`, `value_required`, `processors`, `parameters`, `required_permissions`; methods `handle_async(command, cancellation_event=None) -> str` (abstract) and `handle_structured_async(command, cancellation_event=None)`.
1358
+ - `CliProcessCommand` dataclass: `command`, `raw_command`, `value`, `args: dict`, `chain_commands: list[str]`, `data`, `positionals: list[str] | None`. Helpers: `get_positionals`, `get_positional_text`, `split_shell_words`, `join_shell_words`.
1359
+ - Packages: `pip install qodalis-cli-server-abstractions` (plugins), `qodalis-cli-server` (host, import `qodalis_cli`). Python >= 3.10.
1360
+ - Poll `cancellation_event.is_set()` in long loops when it is given; `/execute` passes `None`.
1361
+
1362
+ ### Python: parameters, sub-commands and modules
1363
+
1364
+ Python server commands declare flags with `CliCommandParameterDescriptor`, nest sub-commands in `processors`, and are grouped into a `CliModule` registered with `builder.add_module`.
1365
+
1366
+ ```python
1367
+ import asyncio
1368
+
1369
+ from qodalis_cli_server_abstractions import (
1370
+ CliCommandParameterDescriptor,
1371
+ CliCommandProcessor,
1372
+ CliModule,
1373
+ CliProcessCommand,
1374
+ ICliCommandParameterDescriptor,
1375
+ ICliCommandProcessor,
1376
+ get_positional_text,
1377
+ )
1378
+
1379
+ _location = CliCommandParameterDescriptor(
1380
+ name="location", description="City name", required=False,
1381
+ type="string", aliases=["-l"], default_value="London",
1382
+ )
1383
+
1384
+
1385
+ def _get_location(command: CliProcessCommand) -> str:
1386
+ return str(command.args.get("location") or get_positional_text(command) or "London")
1387
+
1388
+
1389
+ class _WeatherCurrentProcessor(CliCommandProcessor):
1390
+ @property
1391
+ def command(self) -> str:
1392
+ return "current"
1393
+
1394
+ @property
1395
+ def description(self) -> str:
1396
+ return "Current conditions"
1397
+
1398
+ @property
1399
+ def parameters(self) -> list[ICliCommandParameterDescriptor]:
1400
+ return [_location]
1401
+
1402
+ async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
1403
+ return f"Sunny in {_get_location(command)}"
1404
+
1405
+
1406
+ class _CliWeatherCommandProcessor(CliCommandProcessor):
1407
+ @property
1408
+ def command(self) -> str:
1409
+ return "weather"
1410
+
1411
+ @property
1412
+ def description(self) -> str:
1413
+ return "Weather information"
1414
+
1415
+ @property
1416
+ def parameters(self) -> list[ICliCommandParameterDescriptor]:
1417
+ return [_location]
1418
+
1419
+ @property
1420
+ def processors(self) -> list[ICliCommandProcessor]:
1421
+ return [_WeatherCurrentProcessor()]
1422
+
1423
+ async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
1424
+ return f"Sunny in {_get_location(command)}"
1425
+
1426
+
1427
+ class WeatherModule(CliModule):
1428
+ @property
1429
+ def name(self) -> str:
1430
+ return "weather"
1431
+
1432
+ @property
1433
+ def version(self) -> str:
1434
+ return "1.0.0"
1435
+
1436
+ @property
1437
+ def description(self) -> str:
1438
+ return "Weather commands"
1439
+
1440
+ @property
1441
+ def processors(self) -> list[ICliCommandProcessor]:
1442
+ return [_CliWeatherCommandProcessor()]
1443
+
1444
+
1445
+ # host: create_cli_server(CliServerOptions(configure=lambda b: b.add_module(WeatherModule())))
1446
+ ```
1447
+
1448
+ - `CliCommandParameterDescriptor(name, description, required=False, type="string", aliases=None, default_value=None)`.
1449
+ - Dispatch: root by `command.lower()`, then each `chain_commands` word against `processors`; if a word matches no child, the current processor handles it only when `allow_unlisted_commands` is truthy, else `Unknown command`. Only the resolved processor runs.
1450
+ - `CliBuilder` (chainable): `add_processor`, `add_module`, `set_file_storage_provider`, `add_data_explorer_provider`, `add_filesystem` (legacy). Registering the same command twice replaces the first.
1451
+ - `CliServerOptions`: `base_path` (`"/api/qcli"`), `cors`, `cors_origins`, `allowed_origins`, `enable_shell`, `shell`, `mcp` (`True`, dict or `CliMcpOptions`), `configure`. `create_cli_server` returns `CliServerResult` with `app`, `registry`, `builder`, `executor`, `mcp`, `mount_plugin(plugin)`, ...
1452
+
1453
+ ### Python: structured and streaming output
1454
+
1455
+ Python processors return structured output by overriding `handle_structured_async` with `CliResponseBuilder`, and stream by also implementing `ICliStreamCommandProcessor`.
1456
+
1457
+ ```python
1458
+ import asyncio
1459
+ from typing import Any, Callable
1460
+
1461
+ from qodalis_cli import CliResponseBuilder
1462
+ from qodalis_cli_server_abstractions import (
1463
+ CliCommandProcessor,
1464
+ CliProcessCommand,
1465
+ ICliStreamCommandProcessor,
1466
+ )
1467
+
1468
+
1469
+ class CliUsersCommandProcessor(CliCommandProcessor, ICliStreamCommandProcessor):
1470
+ @property
1471
+ def command(self) -> str:
1472
+ return "users"
1473
+
1474
+ @property
1475
+ def description(self) -> str:
1476
+ return "Lists users"
1477
+
1478
+ async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
1479
+ return "ada, bob"
1480
+
1481
+ async def handle_structured_async(
1482
+ self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None
1483
+ ) -> Any:
1484
+ builder = CliResponseBuilder()
1485
+ builder.write_text("2 users", "info")
1486
+ builder.write_table(["Name", "Role"], [["ada", "admin"], ["bob", "user"]])
1487
+ builder.write_key_value({"Total": "2"})
1488
+ return builder.build()
1489
+
1490
+ async def handle_stream_async(
1491
+ self,
1492
+ command: CliProcessCommand,
1493
+ emit: Callable[[dict[str, Any]], None],
1494
+ cancellation_event: asyncio.Event | None = None,
1495
+ ) -> int:
1496
+ for name in ("ada", "bob"):
1497
+ emit({"type": "text", "value": name})
1498
+ return 0 # exit code
1499
+ ```
1500
+
1501
+ - Keep the `cancellation_event` parameter in every override: the executor always passes two arguments.
1502
+ - Return `self._STRUCTURED_NOT_IMPLEMENTED` from `handle_structured_async` to fall back to `handle_async`.
1503
+ - `CliResponseBuilder`: `write_text(text, style=None)`, `write_table(headers, rows)`, `write_paged_table(headers, rows, page, total=None, has_more=None)`, `write_list(items, ordered=False)`, `write_json(value)`, `write_key_value(dict)`, `set_exit_code(code)`, `build()` -> `CliServerResponse`. Output models (`qodalis_cli.models`): `CliServerTextOutput`, `CliServerTableOutput`, `CliServerListOutput`, `CliServerJsonOutput`, `CliServerKeyValueOutput`.
1504
+
1505
+ ### Python: permissions and MCP tools
1506
+
1507
+ Python processors declare `required_permissions`; with `mcp=True` every command is an MCP tool, and plugins add tools by registering an `IMcpToolProvider` on `result.mcp`.
1508
+
1509
+ ```python
1510
+ from qodalis_cli import CliMcpOptions, CliServerOptions, McpTool, McpToolResult, create_cli_server
1511
+ from qodalis_cli.mcp import object_schema
1512
+
1513
+
1514
+ class StatusToolProvider:
1515
+ name = "status"
1516
+
1517
+ async def get_tools(self, context):
1518
+ async def ping(args, ctx):
1519
+ return McpToolResult(text=f"pong {args['host']}")
1520
+
1521
+ return [
1522
+ McpTool(
1523
+ name="status_ping",
1524
+ description="Ping a host",
1525
+ input_schema=object_schema({"host": {"type": "string"}}, ["host"]),
1526
+ call=ping,
1527
+ annotations={"readOnlyHint": True},
1528
+ )
1529
+ ]
1530
+
1531
+
1532
+ result = create_cli_server(
1533
+ CliServerOptions(configure=configure, mcp=CliMcpOptions(instructions="Deployment server tools"))
1534
+ )
1535
+ result.mcp.add_provider(StatusToolProvider()) # endpoint POST /api/qcli/mcp
1536
+ ```
1537
+
1538
+ - Declare permissions on a processor with `@property def required_permissions(self) -> list[str] | None: return ["deploy:run"]`; enforced (403) only when the users plugin protects the server, together with `commands:execute`, along the whole command chain.
1539
+ - `CliMcpOptions(enabled=True, tools=None, exclude=None, token=None, instructions=None)`. Command tools: name = command path joined with `_`; schema from `parameters` (+ `value` when `value_required` is not `None`).
1540
+ - `McpToolResult(text, structured=None, is_error=False)`, `McpToolResult.error(message)`; a plugin object with `on_mount(self, server)` can call `server.mcp.add_provider(...)` when mounted with `result.mount_plugin(plugin)`.
1541
+
1542
+ ### Python: testing server processors
1543
+
1544
+ Python server processors are tested with pytest (`asyncio_mode = "auto"`), calling `handle_async` directly or through `CliCommandExecutorService`.
1545
+
1546
+ ```python
1547
+ from qodalis_cli import CliCommandExecutorService, CliCommandRegistry
1548
+ from qodalis_cli_server_abstractions import CliProcessCommand
1549
+
1550
+
1551
+ async def test_greet_direct():
1552
+ command = CliProcessCommand(command="greet", raw_command="greet Ada", value="Ada")
1553
+ assert await CliGreetCommandProcessor().handle_async(command) == "Hello, Ada!"
1554
+
1555
+
1556
+ async def test_greet_executor():
1557
+ registry = CliCommandRegistry()
1558
+ registry.register(CliGreetCommandProcessor())
1559
+ result = await CliCommandExecutorService(registry).execute_async(CliProcessCommand(command="greet", value="Ada"))
1560
+ assert result.exit_code == 0
1561
+ assert result.outputs[0].value == "Hello, Ada!"
1562
+ ```
1563
+
1564
+ - HTTP tests: `from fastapi.testclient import TestClient`; `with TestClient(create_cli_server(CliServerOptions(configure=...)).app) as client: client.post("/api/v1/qcli/execute", json={...})`.
1565
+
1566
+ ### .NET: jobs that run elsewhere
1567
+
1568
+ The jobs API (`/api/v1/qcli/jobs`), the `jobs_*` MCP tools, `server jobs` and the dashboard's jobs page work on an `ICliJobManager` (`Qodalis.Cli.Abstractions.Jobs`). The default runs the jobs registered with `AddJob` in the server's process; a host whose jobs run elsewhere implements the interface and registers it with `cli.SetJobManager<T>()` (scoped).
1569
+
1570
+ - Implement `GetJobsAsync` (each `CliJobInfo` with `Id`, `Name`, `Status`, `LastRunAt`, `LastRunStatus` and `Actions`, such as `["trigger", "pause", "resume"]`), `TriggerAsync`, `PauseAsync`, `ResumeAsync`, `GetExecutionsAsync` and `GetExecutionAsync`.
1571
+ - `StopAsync`, `CancelAsync` and `UpdateAsync` default to `NotSupportedException` (HTTP `501`, `NOT_SUPPORTED`); the dashboard shows only the actions in `Actions`.
1572
+ - Throw `KeyNotFoundException` for an unknown job (`404`) and `InvalidOperationException` when the job's state refuses the action (`409`).
1573
+
1574
+ ### Admin dashboard: name and icon (all servers)
1575
+
1576
+ The dashboard is "Qodalis Cli Admin" with the Qodalis Solutions logo unless the admin plugin sets its branding: the name and icon (browser tab, sidebar, sign-in page) and the terminal's name in its welcome banner.
1577
+
1578
+ - .NET: `cli.AddAdmin(o => { o.Branding.Name = "RateBell"; o.Branding.IconUrl = "/favicon.svg"; o.Branding.CliName = "RateBell CLI"; })`
1579
+ - Node: `new CliAdminBuilder().setBranding({ name: 'RateBell', iconUrl: '/favicon.svg', cliName: 'RateBell CLI' })`
1580
+ - Python: `CliAdminBuilder().set_branding({"name": "RateBell", "icon_url": "/favicon.svg", "cli_name": "RateBell CLI"})`
1581
+ - The icon is an absolute http(s) URL, a root-relative path or a base64 `data:image` URL; invalid values fail at startup. The values are served as `branding` in `/qcli/admin/theme.json`.
1582
+ - The filesystem API (`/api/qcli/fs/*`) and the dashboard's Files page exist only when the server enables the filesystem (`AddFileSystem()` in .NET); otherwise the routes answer `404`.
1583
+
1584
+ ## Recipes
1585
+
1586
+ ### Recipe: a complete web plugin end to end
1587
+
1588
+ Build, test and register a `dice` web plugin (`dice roll --sides 20 --count 2`) from scaffold to host app.
1589
+
1590
+ ```bash
1591
+ npx @qodalis/create-cli-plugin --name dice --description "Roll dice" --processor-name Dice
1592
+ cd qodalis-cli-dice
1593
+ ```
1594
+
1595
+ ```typescript
1596
+ // src/lib/processors/cli-dice-command-processor.ts
1597
+ import {
1598
+ CliProcessCommand,
1599
+ ICliCommandProcessor,
1600
+ ICliExecutionContext,
1601
+ } from '@qodalis/cli-core';
1602
+ import { LIBRARY_VERSION } from '../version';
1603
+
1604
+ class DiceRollProcessor implements ICliCommandProcessor {
1605
+ command = 'roll';
1606
+ description = 'Roll one or more dice';
1607
+ acceptsRawInput = true; // lets users type `--sides 20` as well as `--sides=20`
1608
+ parameters = [
1609
+ { name: 'sides', aliases: ['s'], description: 'Sides per die', required: false, type: 'number', defaultValue: 6,
1610
+ validator: (v: any) => (Number(v) >= 2 ? { valid: true } : { valid: false, message: 'at least 2 sides' }) },
1611
+ { name: 'count', aliases: ['c'], description: 'Number of dice', required: false, type: 'number', defaultValue: 1 },
1612
+ ];
1613
+
1614
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
1615
+ const sides = Number(command.args['sides'] ?? 6); // defaultValue is not applied automatically
1616
+ const count = Number(command.args['count'] ?? 1);
1617
+ const rolls = Array.from({ length: count }, () => 1 + Math.floor(Math.random() * sides));
1618
+ context.writer.writeln(`${rolls.join(' ')} (total ${rolls.reduce((a, b) => a + b, 0)})`);
1619
+ context.process.output(rolls); // pipe-able
1620
+ }
1621
+ }
1622
+
1623
+ export class CliDiceCommandProcessor implements ICliCommandProcessor {
1624
+ command = 'dice';
1625
+ description = 'Roll dice';
1626
+ author = { name: 'Jane Doe', email: 'jane@example.com' };
1627
+ version = LIBRARY_VERSION;
1628
+ processors = [new DiceRollProcessor()];
1629
+ metadata = { icon: '🎲' };
1630
+
1631
+ async processCommand(command: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
1632
+ await context.executor.showHelp(command, context);
1633
+ }
1634
+ }
1635
+ ```
1636
+
1637
+ ```typescript
1638
+ // src/public-api.ts (generated; module export)
1639
+ import { ICliModule } from '@qodalis/cli-core';
1640
+ import { CliDiceCommandProcessor } from './lib/processors/cli-dice-command-processor';
1641
+ import { API_VERSION } from './lib/version';
1642
+
1643
+ export * from './lib/processors/cli-dice-command-processor';
1644
+ export * from './lib/version';
1645
+
1646
+ export const diceModule: ICliModule = {
1647
+ apiVersion: API_VERSION,
1648
+ name: '@qodalis/cli-dice',
1649
+ processors: [new CliDiceCommandProcessor()],
1650
+ translations: { es: { 'cli.dice.description': 'Tirar dados' } },
1651
+ };
1652
+ ```
1653
+
1654
+ ```typescript
1655
+ // src/tests/index.spec.ts
1656
+ import { CliTestHarness } from '@qodalis/cli';
1657
+ import { CliDiceCommandProcessor } from '../lib/processors/cli-dice-command-processor';
1658
+
1659
+ describe('dice', () => {
1660
+ it('rolls the requested number of dice', async () => {
1661
+ const harness = new CliTestHarness();
1662
+ harness.registerProcessor(new CliDiceCommandProcessor());
1663
+ const result = await harness.execute('dice roll --sides 6 --count 3');
1664
+ expect(result.data.length).toBe(3);
1665
+ expect(result.data.every((n: number) => n >= 1 && n <= 6)).toBe(true);
1666
+ });
1667
+
1668
+ it('rejects one-sided dice', async () => {
1669
+ const harness = new CliTestHarness();
1670
+ harness.registerProcessor(new CliDiceCommandProcessor());
1671
+ const result = await harness.execute('dice roll --sides 1');
1672
+ expect(result.output).toContain('at least 2 sides');
1673
+ });
1674
+ });
1675
+ ```
1676
+
1677
+ ```bash
1678
+ npx tsup # dist/public-api.{js,mjs,d.ts} + dist/umd/index.global.js
1679
+ npm publish --access public # then in any Qodalis terminal: pkg add @qodalis/cli-dice
1680
+ ```
1681
+
1682
+ ```tsx
1683
+ // Host app (React); Angular: providers: [resolveCliModuleProvider(diceModule)]
1684
+ import { Cli } from '@qodalis/react-cli';
1685
+ import { diceModule } from '@qodalis/cli-dice';
1686
+
1687
+ export const App = () => <Cli modules={[diceModule]} />;
1688
+ ```
1689
+
1690
+ - `CliTestHarness` comes from `@qodalis/cli` (add it as a dev dependency together with a test runner in a standalone project; the monorepo already runs Jasmine/Karma).
1691
+ - The validator error is printed by the engine (`Invalid parameters:` + message), so the command never runs with bad input.
1692
+
1693
+ ### Recipe: a server command used from the browser terminal
1694
+
1695
+ Add a `sysinfo` command to a Node CLI server and run it from a web terminal configured with that server.
1696
+
1697
+ ```typescript
1698
+ // server.ts (Node, Express): npm install @qodalis/cli-server-node @qodalis/cli-server-abstractions
1699
+ import os from 'node:os';
1700
+ import {
1701
+ CliCommandProcessor,
1702
+ CliProcessCommand,
1703
+ CliStructuredResponse,
1704
+ } from '@qodalis/cli-server-abstractions';
1705
+ import { createCliServer } from '@qodalis/cli-server-node';
1706
+
1707
+ class CliSysinfoCommandProcessor extends CliCommandProcessor {
1708
+ command = 'sysinfo';
1709
+ description = 'Server host information';
1710
+
1711
+ async handleAsync(): Promise<string> {
1712
+ return `${os.hostname()} (${os.platform()})`;
1713
+ }
1714
+
1715
+ async handleStructuredAsync(_: CliProcessCommand): Promise<CliStructuredResponse> {
1716
+ return {
1717
+ exitCode: 0,
1718
+ outputs: [
1719
+ {
1720
+ type: 'key-value',
1721
+ entries: [
1722
+ { key: 'Host', value: os.hostname() },
1723
+ { key: 'Platform', value: `${os.platform()} ${os.release()}` },
1724
+ { key: 'CPUs', value: String(os.cpus().length) },
1725
+ { key: 'Uptime', value: `${Math.round(os.uptime() / 60)} min` },
1726
+ ],
1727
+ },
1728
+ ],
1729
+ };
1730
+ }
1731
+ }
1732
+
1733
+ const { app } = createCliServer({
1734
+ allowedOrigins: ['http://localhost:4200'], // the web app's origin (CORS + WebSocket upgrades)
1735
+ configure: (builder) => builder.addProcessor(new CliSysinfoCommandProcessor()),
1736
+ });
1737
+ app.listen(8047, () => console.log('CLI server on http://localhost:8047'));
1738
+ ```
1739
+
1740
+ ```typescript
1741
+ // Web app: tell the terminal about the server (CliOptions.servers)
1742
+ import { CliOptions } from '@qodalis/cli-core';
1743
+
1744
+ export const options: CliOptions = {
1745
+ servers: [{ name: 'node', url: 'http://localhost:8047' }],
1746
+ };
1747
+ // Angular: <cli [options]="options"></cli> React: <Cli options={options} /> Vue: <Cli :options="options" />
1748
+ ```
1749
+
1750
+ ```bash
1751
+ # in the browser terminal
1752
+ sysinfo # bare name (no local command named sysinfo)
1753
+ node:sysinfo # explicit server
1754
+ server ls # connected servers
1755
+ ```
1756
+
1757
+ - The same command in .NET: `cli.AddProcessor<CliSysinfoCommandProcessor>()` with a `CliCommandProcessor` subclass; in Python: `builder.add_processor(...)` with a `CliCommandProcessor` subclass (see the server plugin topics).
1758
+ - Enable `mcp: true` in `createCliServer` to expose `sysinfo` as an MCP tool too.
1759
+
1760
+ ### Recipe: a web plugin with an interactive prompt
1761
+
1762
+ A `signup` web command that asks for a name, a plan, extra options and confirmation, handling Ctrl+C at every step.
1763
+
1764
+ ```typescript
1765
+ import {
1766
+ CliProcessCommand,
1767
+ ICliCommandProcessor,
1768
+ ICliExecutionContext,
1769
+ } from '@qodalis/cli-core';
1770
+
1771
+ export class CliSignupCommandProcessor implements ICliCommandProcessor {
1772
+ command = 'signup';
1773
+ description = 'Create an account interactively';
1774
+
1775
+ async processCommand(_: CliProcessCommand, context: ICliExecutionContext): Promise<void> {
1776
+ const { reader, writer } = context;
1777
+
1778
+ const email = await reader.readLine('Email: ', {
1779
+ placeholder: 'you@example.com',
1780
+ validate: (v) => (/^\S+@\S+\.\S+$/.test(v) ? null : 'Enter a valid email'),
1781
+ });
1782
+ if (email === null) return writer.writeWarning('Cancelled');
1783
+
1784
+ const plan = await reader.readSelect('Plan:', [
1785
+ { label: 'Free', value: 'free', description: '1 project' },
1786
+ { label: 'Pro', value: 'pro', description: 'unlimited projects' },
1787
+ ], { default: 'free' });
1788
+ if (plan === null) return writer.writeWarning('Cancelled');
1789
+
1790
+ const extras = await reader.readMultiSelect('Extras:', [
1791
+ { label: 'Newsletter', value: 'newsletter', checked: true },
1792
+ { label: 'Beta features', value: 'beta' },
1793
+ ]);
1794
+ if (extras === null) return writer.writeWarning('Cancelled');
1795
+
1796
+ writer.writeKeyValue({ Email: email, Plan: plan, Extras: extras.join(', ') || '-' });
1797
+ const confirmed = await reader.readConfirm('Create the account?', true);
1798
+ if (!confirmed) return writer.writeWarning('Not created');
1799
+
1800
+ context.spinner?.show('Creating account');
1801
+ try {
1802
+ await context.http.post('https://api.example.com/accounts', { email, plan, extras });
1803
+ context.spinner?.hide();
1804
+ writer.writeSuccess(`Account created for ${email}`);
1805
+ } catch (e) {
1806
+ context.spinner?.hide();
1807
+ writer.writeError(`Failed: ${e}`);
1808
+ context.process.exit(1);
1809
+ }
1810
+ }
1811
+ }
1812
+ ```
1813
+
1814
+ ```typescript
1815
+ // test: queue answers in prompt order
1816
+ const harness = new CliTestHarness();
1817
+ harness.registerProcessor(new CliSignupCommandProcessor());
1818
+ harness.setReaderResponses('ada@example.com', 'pro', ['beta'], false);
1819
+ const result = await harness.execute('signup');
1820
+ expect(result.output).toContain('ada@example.com');
1821
+ expect(result.stderr.join('\n')).toContain('Not created'); // writeWarning goes to stderr
1822
+ ```
1823
+
1824
+ - Every `reader` method resolves `null` on Ctrl+C/Escape: check it before using the value.
1825
+ - `readConfirm` resolves `boolean | null`; `!confirmed` treats abort as "no".