diff --git a/docs/cli/configuration_reference.md b/docs/cli/configuration_reference.md index bcc40e3b..ba63aef1 100644 --- a/docs/cli/configuration_reference.md +++ b/docs/cli/configuration_reference.md @@ -80,6 +80,6 @@ Built-in profiles (`profile` / `default_profile`): | Profile | Description | | - | - | -| `serverless` | Only commands that work on {{serverless-full}}. Hides `cloud hosted` and exposes `cloud serverless` plus the majority of stack commands. | -| `stack` | Full command surface, including self-managed / hosted-only APIs. Equivalent to having no policy (allow everything). | +| `serverless` | Only commands that work on {{serverless-full}}. Hides `cloud hosted` and exposes `cloud serverless`, `nightshift`, plus the majority of stack commands. | +| `stack` | Full command surface, including self-managed / hosted-only APIs, except `nightshift`, which only applies to {{serverless-short}} Observability projects. | | `default` | Alias for `serverless`; the most conservative baseline, recommended for agents and LLM-based tooling. | diff --git a/docs/cli/nightshift/index.md b/docs/cli/nightshift/index.md new file mode 100644 index 00000000..584ba286 --- /dev/null +++ b/docs/cli/nightshift/index.md @@ -0,0 +1,16 @@ +## Description + +:::{warning} +Nightshift commands are experimental and subject to significant changes before they reach a stable state. Each run prints a warning to stderr; pass `--accept-experimental` to suppress it. The warning is not printed with `--json`. +::: + +Ask the Nightshift assistant a question and get its answer back in a single response, without starting an investigation. +This is `elastic kb agent-builder post-chat-message` with the agent fixed to `nightshift.assistant`. + +Nightshift is only available on {{serverless-short}} Observability projects, with the `agentBuilder:experimentalFeatures` advanced setting enabled. +The command is hidden when the context's `kibana.version` [hint](../configuration.md#versions) is a {{stack}} version, and the `stack` command profile blocks it. + +```bash +elastic nightshift ask "Why did checkout latency spike at 14:00?" +elastic nightshift ask --conversation-id "Which service should I look at first?" +``` diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 85deddfd..223af572 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -123119,7 +123119,7 @@ "name": "accept-experimental", "type": "boolean", "required": false, - "summary": "Acknowledge that this command is experimental and may be removed; suppresses the warning" + "summary": "Acknowledge that this command is experimental and may change or be removed; suppresses the warning" }, { "role": "flag", @@ -123168,7 +123168,7 @@ "name": "accept-experimental", "type": "boolean", "required": false, - "summary": "Acknowledge that this command is experimental and may be removed; suppresses the warning" + "summary": "Acknowledge that this command is experimental and may change or be removed; suppresses the warning" }, { "role": "flag", @@ -123243,6 +123243,76 @@ } ] }, + { + "segment": "nightshift", + "commands": [ + { + "path": [ + "nightshift" + ], + "name": "ask", + "parameters": [ + { + "role": "positional", + "name": "message", + "type": "string", + "required": false, + "summary": "The user message to send to the agent." + } + ], + "summary": "Ask the Nightshift assistant a question and get its answer", + "intent": { + "requiresAuth": true + } + } + ], + "namespaces": [], + "summary": "Ask the Nightshift assistant", + "options": [ + { + "role": "flag", + "name": "accept-experimental", + "type": "boolean", + "required": false, + "summary": "Acknowledge that this command is experimental and may change or be removed; suppresses the warning" + }, + { + "role": "flag", + "name": "conversation-id", + "type": "string", + "required": false, + "summary": "The ID of an existing conversation to continue. Omit it to start a new conversation; the response carries the ID to reuse on the next call." + }, + { + "role": "flag", + "name": "message", + "type": "string", + "required": true, + "summary": "The user message to send to the agent." + }, + { + "role": "flag", + "name": "input-file", + "type": "string", + "required": false, + "summary": "path to a JSON file to use as command input" + }, + { + "role": "dryRun", + "name": "dry-run", + "type": "boolean", + "required": false, + "summary": "validate all inputs and exit without performing any action" + }, + { + "role": "flag", + "name": "no-validate", + "type": "boolean", + "required": false, + "summary": "skip input validation and send the request as-is" + } + ] + }, { "segment": "config", "commands": [], diff --git a/src/cli-schema.ts b/src/cli-schema.ts index e9cae066..41c8a4e9 100644 --- a/src/cli-schema.ts +++ b/src/cli-schema.ts @@ -434,7 +434,7 @@ function hoistNamespaceOptions (ns: CliNamespace): void { function stripFrom (n: CliNamespace): void { for (const cmd of n.commands) { - cmd.parameters = cmd.parameters.filter(p => !commonNames.has(p.name)) + cmd.parameters = cmd.parameters.filter(p => p.role === 'positional' || !commonNames.has(p.name)) } for (const sub of n.namespaces) stripFrom(sub) } @@ -474,7 +474,7 @@ function promoteToGlobalOptions ( } for (const cmd of rootCommands) { - cmd.parameters = cmd.parameters.filter(p => !commonNames.has(p.name)) + cmd.parameters = cmd.parameters.filter(p => p.role === 'positional' || !commonNames.has(p.name)) } return promoted diff --git a/src/completion/complete.ts b/src/completion/complete.ts index 67612a3e..69e091d4 100644 --- a/src/completion/complete.ts +++ b/src/completion/complete.ts @@ -197,6 +197,14 @@ export async function buildCompletionTree (rewrittenWords: readonly string[]): P root.addCommand(defineGroup({ name: 'docs', description: 'Search, read, and ask questions about Elastic documentation' })) } + // `nightshift` — deep-load on exact match, stub otherwise. + if (firstWord === 'nightshift') { + const { NAMESPACES } = await import('../namespaces.ts') + root.addCommand(await NAMESPACES.find(ns => ns.name === 'nightshift')!.load()) + } else { + root.addCommand(defineGroup({ name: 'nightshift', description: 'Ask the Nightshift assistant' })) + } + // `config` — deep-load on exact match, stub otherwise. if (firstWord === 'config') { const { registerConfigCommands } = await import('../config/commands.ts') diff --git a/src/config/profiles.ts b/src/config/profiles.ts index 76f11d6d..1d47d95f 100644 --- a/src/config/profiles.ts +++ b/src/config/profiles.ts @@ -13,8 +13,8 @@ * Built-in profiles: * - `serverless` — only commands that work on Elastic Serverless. Hides * `cloud hosted` and exposes `cloud serverless` + all stack commands. - * - `stack` — full surface including self-managed / hosted-only APIs. - * Equivalent to having no policy (allow everything). + * - `stack` — full surface including self-managed / hosted-only APIs, + * minus commands that only apply to Serverless projects. * - `default` — alias for `serverless`; the most conservative baseline, * recommended for agents and LLM-based tooling. */ @@ -40,14 +40,17 @@ const STACK_ONLY_ES_NAMESPACES = [ 'watcher', ] as const +/** Namespaces that only apply to Serverless projects (Nightshift: observability projects). */ +const SERVERLESS_ONLY_NAMESPACES = ['nightshift'] as const + /** * Resolves a built-in profile to an effective allow/block policy. * - * Returns `null` for `stack`, which means "no restriction" (allow everything). - * Returns an object with `allowed` and `blocked` patterns for all other profiles. + * `allowed`, when present, is the complete allow-list; without it every command + * not matched by `blocked` is allowed. */ -export function resolveBuiltinProfile (name: BuiltInProfile): { allowed: readonly string[]; blocked?: readonly string[] } | null { - if (name === 'stack') return null +export function resolveBuiltinProfile (name: BuiltInProfile): { allowed?: readonly string[]; blocked?: readonly string[] } { + if (name === 'stack') return { blocked: SERVERLESS_ONLY_NAMESPACES.map(ns => `${ns}.*`) } // `default` is an alias for `serverless` return { @@ -65,6 +68,8 @@ export function resolveBuiltinProfile (name: BuiltInProfile): { allowed: readonl // All stack commands (Elasticsearch + Kibana) 'stack.*', + ...SERVERLESS_ONLY_NAMESPACES.map(ns => `${ns}.*`), + // Cloud cross-cutting namespaces (apply to both Hosted and Serverless) 'cloud.trust.*', 'cloud.auth.*', diff --git a/src/docs/ask.ts b/src/docs/ask.ts index d4ec6924..e7e3ae60 100644 --- a/src/docs/ask.ts +++ b/src/docs/ask.ts @@ -7,6 +7,7 @@ import { defineCommand } from '../factory.ts' import type { OpaqueCommandHandle, JsonValue } from '../factory.ts' import { docsAskStream, newUuid, type AskStreamEvent } from './client.ts' import { startSpinner, streamAnswer } from './stream.ts' +import { ACCEPT_EXPERIMENTAL_OPTION, warnIfExperimental } from '../lib/experimental.ts' export interface AskDeps { docsAskStream: (message: string, conversationId: string) => AsyncGenerator @@ -27,34 +28,23 @@ const inputSchema: Record = { }, } -function experimentalBanner (isTTY: boolean): string { - const text = - 'Warning: "docs ask" is experimental and in active development.\n' + - ' Not yet suited for scripts or automation. Pass --accept-experimental to suppress this warning.\n\n' - return isTTY ? `\x1b[33m${text}\x1b[0m` : text -} - export function createAskCommand (deps: AskDeps = defaultDeps): OpaqueCommandHandle { return defineCommand({ name: 'ask', description: 'Ask a question about Elastic documentation using AI (single answer)', input: inputSchema, positionalArg: { name: 'question', description: 'Question to ask', required: false }, - options: [ - { - long: 'accept-experimental', - type: 'boolean', - description: 'Acknowledge that this command is experimental and may be removed; suppresses the warning', - }, - ], + options: [ACCEPT_EXPERIMENTAL_OPTION], handler: async (parsed): Promise => { const inp = parsed.input as { question?: string } | undefined const question = (parsed.arg ?? inp?.question ?? '').trim() if (question === '') return { error: { code: 'missing_input', message: 'Pass --question (or a positional question).' } } - if (parsed.options['accept-experimental'] !== true && parsed.options['json'] !== true) { - deps.stderr.write(experimentalBanner(process.stderr.isTTY === true)) - } + warnIfExperimental(parsed, { + label: 'docs ask', + status: 'in active development', + advice: 'Not yet suited for scripts or automation.', + }, deps.stderr) const conversationId = newUuid() const interactive = process.stderr.isTTY === true && parsed.options['json'] !== true diff --git a/src/docs/search.ts b/src/docs/search.ts index 0f540adb..53dd41e8 100644 --- a/src/docs/search.ts +++ b/src/docs/search.ts @@ -6,6 +6,7 @@ import { defineCommand } from '../factory.ts' import type { OpaqueCommandHandle, JsonValue } from '../factory.ts' import { docsSearch, stripHtmlTags } from './client.ts' +import { ACCEPT_EXPERIMENTAL_OPTION, warnIfExperimental } from '../lib/experimental.ts' function resultSummary (aiShortSummary: string | undefined, description: string): string { return (aiShortSummary != null && aiShortSummary !== '') ? aiShortSummary : stripHtmlTags(description) @@ -27,30 +28,19 @@ const inputSchema: Record = { }, } -function experimentalBanner (command: string, isTTY: boolean): string { - const text = - `Warning: "${command}" is experimental and in active development.\n` + - ` Not yet suited for scripts or automation. Pass --accept-experimental to suppress this warning.\n\n` - return isTTY ? `\x1b[33m${text}\x1b[0m` : text -} - export function createSearchCommand (deps: SearchDeps = defaultDeps): OpaqueCommandHandle { return defineCommand({ name: 'search', description: 'Search Elastic documentation', input: inputSchema, positionalArg: { name: 'query', description: 'Search terms', required: false }, - options: [ - { - long: 'accept-experimental', - type: 'boolean', - description: 'Acknowledge that this command is experimental and may be removed; suppresses the warning', - }, - ], + options: [ACCEPT_EXPERIMENTAL_OPTION], handler: async (parsed): Promise => { - if (parsed.options['accept-experimental'] !== true && parsed.options['json'] !== true) { - deps.stderr.write(experimentalBanner('docs search', process.stderr.isTTY === true)) - } + warnIfExperimental(parsed, { + label: 'docs search', + status: 'in active development', + advice: 'Not yet suited for scripts or automation.', + }, deps.stderr) const inp = parsed.input as { query?: string; page?: number; size?: number } | undefined const query = (parsed.arg ?? inp?.query ?? '').trim() if (query === '') return { error: { code: 'missing_input', message: 'query is required' } } diff --git a/src/factory-core.ts b/src/factory-core.ts index ecc5203e..40975929 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -78,7 +78,11 @@ export interface CommandConfig { name: string description: string options?: OptionDefinition[] - positionalArg?: { name: string; description: string; required?: boolean } + /** + * Optional positional argument. With `inputKey`, its value fills that input schema + * field before validation, as an alternative to the field's flag. + */ + positionalArg?: { name: string; description: string; required?: boolean; inputKey?: string } handler: (parsed: ParsedResult) => HandlerResult | Promise /** JSON Schema object for structured input (properties carry `x-found-in` routing). */ input?: Record @@ -194,10 +198,8 @@ export function isCommandAllowed (commandDotPath: string, policy: CommandPolicy if (policy.profile != null) { const profilePolicy = resolveBuiltinProfile(policy.profile) - if (profilePolicy != null) { - if (!profilePolicy.allowed.some(matches)) return false - if (profilePolicy.blocked?.some(matches)) return false - } + if (profilePolicy.allowed != null && !profilePolicy.allowed.some(matches)) return false + if (profilePolicy.blocked?.some(matches)) return false if (policy.blocked != null) return !policy.blocked.some(matches) return true } diff --git a/src/factory.ts b/src/factory.ts index b7b56348..834f04fe 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -455,7 +455,10 @@ interface MergedInput { } /** Merges schema-derived CLI flag values over the JSON input; flags win. */ -function mergeFlagsIntoInput (cmd: Command, jsonInput: unknown, schemaArgs: SchemaArgDefinition[], allRaw: OptionValues): MergedInput { +function mergeFlagsIntoInput ( + cmd: Command, jsonInput: unknown, schemaArgs: SchemaArgDefinition[], allRaw: OptionValues, + positionalArg?: CommandConfig['positionalArg'], +): MergedInput { let inputValue = jsonInput const rawBodyValues: Record = {} const sortParsedKeys = new Set() @@ -539,6 +542,16 @@ function mergeFlagsIntoInput (cmd: Command, jsonInput: unknown, schemaArgs: Sche } } + const positionalKey = positionalArg?.inputKey + const positionalInput = cmd.processedArgs[0] as string | undefined + if (positionalKey != null && positionalInput !== undefined) { + if (positionalKey in cliInput) { + const flag = schemaArgs.find((a) => a.schemaKey === positionalKey)?.cliFlag ?? positionalKey + return cmd.error(`pass ${positionalArg!.name} either as an argument or as --${flag}, not both`) + } + cliInput[positionalKey] = positionalInput + } + if (Object.keys(cliInput).length > 0) { inputValue = { ...(inputValue as Record ?? {}), ...cliInput } } @@ -864,7 +877,7 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { const jsonFormat = allRaw.json const options = collectOptions(optDefs, allRaw) const merged = isJsonSchemaInput(config.input) - ? mergeFlagsIntoInput(cmd, readInput(cmd, config), schemaArgs, allRaw) + ? mergeFlagsIntoInput(cmd, readInput(cmd, config), schemaArgs, allRaw, config.positionalArg) : undefined const positionalValue = config.positionalArg != null diff --git a/src/kb/register.ts b/src/kb/register.ts index 8564456f..8b1dedd8 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -4,18 +4,21 @@ */ import { defineCommand, defineGroup } from '../factory.ts' -import type { OpaqueCommandHandle } from '../factory.ts' +import type { CommandConfig, JsonValue, OpaqueCommandHandle } from '../factory.ts' import { inferIntentFromHttp } from '@cli-schema/spec' import type { KbApiDefinition } from './types.ts' import { validateKbApiDefinition } from './types.ts' import { kbApiManifest, loadKbApi } from './apis.ts' import type { KbApiMeta } from './apis.ts' import { createKbHandler } from './handler.ts' +import type { KbHandlerDeps } from './handler.ts' import { formatTextResponse } from '../output.ts' import type { AvailabilityTarget } from '../lib/availability.ts' import { isAvailable, parseVersionHint } from '../lib/availability.ts' import { getResolvedConfig } from '../config/store.ts' import { buildStubLeaf } from '../lib/lazy-leaf.ts' +import { ACCEPT_EXPERIMENTAL_OPTION, warnIfExperimental } from '../lib/experimental.ts' +import type { ExperimentalNotice } from '../lib/experimental.ts' // Every Kibana definition passes `validateKbApiDefinition` as of @elastic/schemas 0.5.1; // the five upstream path-param defects that used to need an allowlist here are fixed. @@ -24,7 +27,11 @@ import { buildStubLeaf } from '../lib/lazy-leaf.ts' // calls it), so an upstream regression fails here rather than at request time. /** Builds a leaf command handle from a definition. */ -function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): OpaqueCommandHandle { +function buildLeafHandle ( + def: KbApiDefinition, + target?: AvailabilityTarget, + overrides: Pick & { handler?: CommandConfig['handler'] } = {} +): OpaqueCommandHandle { validateKbApiDefinition(def) const intent = def.intent ?? inferIntentFromHttp(def.method) return defineCommand({ @@ -32,13 +39,103 @@ function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): Op description: def.description, ...(def.input !== undefined ? { input: def.input } : {}), readOnly: def.method === 'GET' || def.method === 'HEAD', - handler: createKbHandler(def), + handler: overrides.handler ?? createKbHandler(def), + ...(overrides.positionalArg !== undefined ? { positionalArg: overrides.positionalArg } : {}), + ...(overrides.options !== undefined ? { options: overrides.options } : {}), ...(intent != null ? { intent } : {}), ...(def.responseType === 'text' ? { formatOutput: formatTextResponse } : {}), ...(target !== undefined ? { target } : {}), }) } +/** A generated Kibana command re-exposed under another name with some input fields pinned. */ +export interface KbPresetOptions { + /** Manifest id of the generated command, e.g. `agent-builder.post-chat-message`. */ + apiId: string + name: string + description: string + /** Input fields sent with a fixed value; they are removed from the command's flags and schema. */ + fixed: Record + /** Input field that may also be passed as the command's positional argument. */ + positional?: string + /** Availability target; when set, no command is built if the endpoint is unavailable for it. */ + target?: AvailabilityTarget + /** Narrows the endpoint's availability to these deployment flavors. */ + flavors?: ReadonlyArray<'stack' | 'serverless'> + /** + * Marks the command experimental: it warns on stderr before sending the request unless + * `--accept-experimental` or `--json` is passed. + */ + experimental?: ExperimentalNotice +} + +/** + * Builds a command from a generated Kibana API definition with some input fields + * pinned, so a purpose-built command (e.g. `nightshift ask`) needs no hand-written + * schema, request builder, or handler. + * + * @param deps - test seam forwarded to `createKbHandler`; production callers omit it + * @returns the command, or `null` when the endpoint is unavailable for `opts.target` + * @throws {Error} if `apiId` is not in the manifest, a fixed or positional field is not in its + * input schema, or a flavor is not in its availability + */ +export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHandlerDeps): Promise { + const meta = kbApiManifest.find(m => m.id === opts.apiId) + if (meta == null) throw new Error(`unknown Kibana API ${JSON.stringify(opts.apiId)}`) + let availability = (meta as unknown as Record)['availability'] as Record | undefined + if (opts.flavors != null) { + for (const flavor of opts.flavors) { + if (availability == null || !(flavor in availability)) { + throw new Error(`flavor ${JSON.stringify(flavor)} is not in the availability of ${opts.apiId}`) + } + } + availability = Object.fromEntries(opts.flavors.map(flavor => [flavor, availability![flavor]])) + } + if (!isAvailable(availability, opts.target)) return null + const def = await loadKbApi(meta) + const properties = { ...(def.input?.['properties'] as Record | undefined) } + for (const key of Object.keys(opts.fixed)) { + if (!(key in properties)) throw new Error(`fixed field ${JSON.stringify(key)} is not an input of ${opts.apiId}`) + delete properties[key] + } + const positional = opts.positional + if (positional != null && !(positional in properties)) { + throw new Error(`positional field ${JSON.stringify(positional)} is not an input of ${opts.apiId}`) + } + const required = Array.isArray(def.input?.['required']) + ? (def.input['required'] as string[]).filter(key => !(key in opts.fixed)) + : [] + const handler = createKbHandler(def, deps) + const experimental = opts.experimental + return buildLeafHandle( + { + ...def, + name: opts.name, + description: opts.description, + // Generated schemas allow unknown keys; a pinned field supplied via JSON must error, not be overridden. + input: { ...def.input, properties, required, additionalProperties: false }, + }, + opts.target, + { + handler: async (parsed) => { + if (experimental != null) warnIfExperimental(parsed, experimental) + return await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }) + }, + ...(experimental != null ? { options: [ACCEPT_EXPERIMENTAL_OPTION] } : {}), + ...(positional != null + ? { + positionalArg: { + name: positional, + description: String((properties[positional] as Record)['description'] ?? positional), + required: false, + inputKey: positional, + }, + } + : {}), + } + ) +} + /** * Sniffs `process.argv` to identify which KB leaf command the user * intends to invoke. Returns `null` on ambiguity or help requests. @@ -58,6 +155,12 @@ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta return null } +/** Resolves the availability target from the active context's `kibana.version` hint, if any. */ +export function resolveKbTarget (): AvailabilityTarget | undefined { + const version = getResolvedConfig()?.context.kibana?.version + return version != null ? parseVersionHint(version) ?? undefined : undefined +} + export interface RegisterLazyOptions { argv?: readonly string[] /** Availability target; when present, commands and flags not matching the target are excluded. */ @@ -75,11 +178,7 @@ export async function registerKbCommandsLazy ( opts: RegisterLazyOptions = {} ): Promise { const argv = opts.argv ?? process.argv - let target = opts.target - if (target === undefined) { - const version = getResolvedConfig()?.context.kibana?.version - if (version != null) target = parseVersionHint(version) ?? undefined - } + const target = opts.target ?? resolveKbTarget() const manifest = kbApiManifest.filter(m => isAvailable((m as unknown as Record)['availability'], target) ) diff --git a/src/lib/experimental.ts b/src/lib/experimental.ts new file mode 100644 index 00000000..841ed431 --- /dev/null +++ b/src/lib/experimental.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { OptionDefinition, ParsedResult } from '../factory-core.ts' + +/** The `--accept-experimental` flag that experimental commands declare to suppress their warning. */ +export const ACCEPT_EXPERIMENTAL_OPTION: OptionDefinition = { + long: 'accept-experimental', + type: 'boolean', + description: 'Acknowledge that this command is experimental and may change or be removed; suppresses the warning', +} + +/** What an experimental command's warning says about it. */ +export interface ExperimentalNotice { + /** Command named in the warning, e.g. `docs search`. */ + label: string + /** Completes "is experimental and …", e.g. `in active development`. */ + status: string + /** Optional sentence shown before the suppression instructions. */ + advice?: string +} + +/** + * Writes the experimental warning to `stderr`, yellow when stderr is a TTY, unless the + * invocation passed `--accept-experimental` or `--json`. + * + * @param parsed - the command's parsed result; only `options` is read + * @param stderr - where the warning goes; commands with an injectable stderr pass theirs + */ +export function warnIfExperimental ( + parsed: Pick, + notice: ExperimentalNotice, + stderr: { write: (s: string) => boolean } = process.stderr, +): void { + if (parsed.options['accept-experimental'] === true || parsed.options['json'] === true) return + const suppress = 'Pass --accept-experimental to suppress this warning.' + const text = + `Warning: "${notice.label}" is experimental and ${notice.status}.\n` + + ` ${notice.advice != null ? `${notice.advice} ${suppress}` : suppress}\n\n` + stderr.write(process.stderr.isTTY === true ? `\x1b[33m${text}\x1b[0m` : text) +} diff --git a/src/namespaces.ts b/src/namespaces.ts index 1d48ef13..52b98723 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -122,6 +122,32 @@ export const NAMESPACES: NamespaceEntry[] = [ return registerDocsCommands() }, }, + { + name: 'nightshift', + description: 'Ask the Nightshift assistant', + load: async (opts) => { + const { buildKbPresetCommand, resolveKbTarget } = await import('./kb/register.ts') + const target = opts?.eager === true ? undefined : resolveKbTarget() + const ask = await buildKbPresetCommand({ + apiId: 'agent-builder.post-chat-message', + name: 'ask', + description: 'Ask the Nightshift assistant a question and get its answer', + fixed: { agent_id: 'nightshift.assistant' }, + positional: 'message', + // Nightshift agents only exist on Serverless Observability projects. + flavors: ['serverless'], + experimental: { + label: 'nightshift ask', + status: 'subject to significant changes before it reaches a stable state', + }, + ...(target !== undefined ? { target } : {}), + }) + return defineGroup( + { name: 'nightshift', description: 'Ask the Nightshift assistant' }, + ...(ask != null ? [ask] : []), + ) + }, + }, { name: 'config', description: 'Author and maintain the elastic config file', diff --git a/test/cli-schema.test.ts b/test/cli-schema.test.ts index 66aefea0..f754f07f 100644 --- a/test/cli-schema.test.ts +++ b/test/cli-schema.test.ts @@ -25,6 +25,7 @@ function runCliSchema (): Promise<{ code: number | null, stdout: string, stderr: interface CliParameter { name: string + role?: string repeatable?: boolean separator?: string } @@ -54,6 +55,18 @@ function findCommand (namespaces: CliNamespace[], path: string[], name: string): } describe('cli schema', () => { + it('keeps a positional that shares its name with a hoisted flag', async () => { + const { code, stdout, stderr } = await runCliSchema() + assert.equal(code, 0, stderr) + + // `nightshift` has a single command, so all of its flags (including `--message`) are + // hoisted to the namespace; the same-named positional must stay on the command. + const schema = JSON.parse(stdout) as { namespaces: CliNamespace[] } + const ask = findCommand(schema.namespaces, ['nightshift'], 'ask') + const positionals = ask?.parameters.filter((p) => p.role === 'positional').map((p) => p.name) + assert.deepEqual(positionals, ['message']) + }) + it('does not emit runtime shortcuts into the docs-builder schema', async () => { const { code, stdout, stderr } = await runCliSchema() assert.equal(code, 0, stderr) diff --git a/test/completion/complete.test.ts b/test/completion/complete.test.ts index 65483c1b..59ecd325 100644 --- a/test/completion/complete.test.ts +++ b/test/completion/complete.test.ts @@ -139,6 +139,25 @@ describe('handleComplete -- policy enforcement', () => { }) }) + for (const [profile, offered] of [['serverless', true], ['default', true], ['stack', false]] as const) { + it(`${offered ? 'offers' : 'hides'} nightshift ask under the ${profile} profile`, async (t) => { + await withConfig(t, [ + `default_profile: ${profile}`, + 'current_context: local', + 'contexts:', + ' local:', + ' kibana:', + ' url: http://localhost:5601', + '', + ], async () => { + const buf = bufferedWriter() + await handleComplete(['nightshift', ''], buf.write) + const out = parseOutput(buf.chunks.join('')) + assert.equal(out.candidates.includes('ask'), offered, `got: ${out.candidates.join(',')}`) + }) + }) + } + it('applies blocked commands without resolving active-context expressions', async (t) => { await withConfig(t, [ 'current_context: local', @@ -372,6 +391,14 @@ describe('buildCompletionTree -- docs and config subtrees', () => { assert.ok(docs.commands.length > 0, 'docs should have children when deep-loaded') }) + it('registers nightshift as a stub by default and deep-loads it on exact match', async () => { + const stub = (await buildCompletionTree(['stack'])).commands.find((c) => c.name() === 'nightshift') + assert.ok(stub != null, 'nightshift group should be present') + assert.equal(stub.commands.length, 0) + const loaded = (await buildCompletionTree(['nightshift'])).commands.find((c) => c.name() === 'nightshift') + assert.ok(loaded?.commands.some((c) => c.name() === 'ask'), 'nightshift should expose ask when deep-loaded') + }) + it('deep-loads config when first word is "config"', async () => { const root = await buildCompletionTree(['config']) const config = root.commands.find((c) => c.name() === 'config') diff --git a/test/factory.test.ts b/test/factory.test.ts index 1d014a46..65b1cb77 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -248,6 +248,77 @@ describe('defineCommand', () => { assert.equal(received[0].arg, 'ingest pipelines') }) + describe('with inputKey', () => { + // Commands with an input schema read stdin when it is not a TTY; on Windows CI that read never ends. + let origIsTTY: boolean | undefined + beforeEach(() => { + origIsTTY = process.stdin.isTTY + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true, writable: true }) + }) + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true, writable: true }) + }) + + it('fills the named input field from the positional value before validation', async () => { + const received: ParsedResult[] = [] + const cmd = defineCommand({ + name: 'ask', + description: 'Ask', + input: jsonSchema({ message: { type: 'string' }, topic: { type: 'string' } }, ['message']), + positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + await invokeAsync(cmd, ['why is it slow?', '--topic', 'checkout']) + assert.equal(received.length, 1) + assert.deepEqual(received[0].input, { message: 'why is it slow?', topic: 'checkout' }) + }) + + it('still accepts the input field as a flag when the positional is omitted', async () => { + const received: ParsedResult[] = [] + const cmd = defineCommand({ + name: 'ask', + description: 'Ask', + input: jsonSchema({ message: { type: 'string' } }, ['message']), + positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + await invokeAsync(cmd, ['--message', 'hi']) + assert.deepEqual(received[0].input, { message: 'hi' }) + }) + + it('errors when the positional and its flag are both given', async () => { + const received: ParsedResult[] = [] + const cmd = defineCommand({ + name: 'ask', + description: 'Ask', + input: jsonSchema({ message: { type: 'string' } }, ['message']), + positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + const err = await captureErrAsync(cmd, ['one', '--message', 'two']) + assert.equal(received.length, 0) + assert.match(err, /--message/) + }) + + it('emits input_validation_failed JSON when the positional and its flag are both given with --json', async () => { + const received: ParsedResult[] = [] + const cmd = defineCommand({ + name: 'ask', + description: 'Ask', + input: jsonSchema({ message: { type: 'string' } }, ['message']), + positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + const { stdout, stderr, exitCode } = await invokeCapturingStreams(cmd, ['--json'], ['one', '--message', 'two']) + assert.equal(received.length, 0) + assert.equal(stdout, '') + assert.deepEqual(JSON.parse(stderr), { + error: { code: 'input_validation_failed', message: 'pass message either as an argument or as --message, not both' }, + }) + assert.equal(exitCode, 1) + }) + }) + it('sets parsed.arg to undefined when no positionalArg is declared', async () => { const received: ParsedResult[] = [] const cmd = defineCommand({ @@ -3058,10 +3129,22 @@ describe('isCommandAllowed', () => { assert.equal(isCommandAllowed('stack.es.search', { profile: 'default' }), true) }) - it('profile stack: allows all commands (no restriction)', () => { + it('profile stack: allows all commands except serverless-only ones', () => { assert.equal(isCommandAllowed('cloud.hosted.deployments.list', { profile: 'stack' }), true) assert.equal(isCommandAllowed('cloud.serverless.projects.search.list', { profile: 'stack' }), true) assert.equal(isCommandAllowed('anything.at.all', { profile: 'stack' }), true) + assert.equal(isCommandAllowed('nightshift.ask', { profile: 'stack' }), false) + }) + + it('profile serverless and default: allow nightshift commands', () => { + assert.equal(isCommandAllowed('nightshift.ask', { profile: 'serverless' }), true) + assert.equal(isCommandAllowed('nightshift.ask', { profile: 'default' }), true) + }) + + it('profile stack: an extra blocked entry still applies', () => { + const policy = { profile: 'stack' as const, blocked: ['stack.es.ml.*'] } + assert.equal(isCommandAllowed('stack.es.ml.get-records', policy), false) + assert.equal(isCommandAllowed('stack.es.search', policy), true) }) it('profile + blocked: profile allows but blocked further restricts', () => { @@ -4329,7 +4412,8 @@ async function captureStreams(fn: () => Promise): Promise<{ stdout: string /* swallow -- caller inspects captured output */ } finally { exitCode = process.exitCode ?? 0 - process.exitCode = origExitCode as typeof process.exitCode + // Bun ignores `process.exitCode = undefined`, which would leak this command's exit code. + process.exitCode = origExitCode ?? 0 } }) return { stdout: stdout.join(''), stderr: stderr.join(''), exitCode } diff --git a/test/kb/preset.test.ts b/test/kb/preset.test.ts new file mode 100644 index 00000000..c4c81b9d --- /dev/null +++ b/test/kb/preset.test.ts @@ -0,0 +1,250 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, before, after, beforeEach, afterEach } from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Command } from 'commander' +import { buildKbPresetCommand } from '../../src/kb/register.ts' +import { buildKibanaRequestParams } from '../../src/kb/request-builder.ts' +import type { KibanaClient, KibanaRequestParams } from '../../src/lib/kibana-client.ts' +import type { OpaqueCommandHandle } from '../../src/factory.ts' + +const CHAT_MESSAGE = 'agent-builder.post-chat-message' + +function recordingDeps (sent: KibanaRequestParams[], response: unknown = { conversation_id: 'c1', answer: 'hi' }) { + const client = { request: async (params: KibanaRequestParams) => { sent.push(params); return response } } + return { buildKibanaRequestParams, getKibanaClient: () => client as unknown as KibanaClient } +} + +function longFlags (cmd: OpaqueCommandHandle): string[] { + return cmd.options.map((o) => o.long ?? '') +} + +/** Runs the command and captures string writes to stdout/stderr. */ +async function run (cmd: OpaqueCommandHandle, argv: string[]): Promise<{ stdout: string, stderr: string }> { + let stdout = '' + let stderr = '' + const origOut = process.stdout.write.bind(process.stdout) + const origErr = process.stderr.write.bind(process.stderr) + const patch = (orig: typeof origOut, sink: (s: string) => void) => (chunk: unknown, ...rest: unknown[]): boolean => { + if (typeof chunk === 'string') { sink(chunk); return true } + return Reflect.apply(orig, process.stdout, [chunk, ...rest]) as boolean + } + process.stdout.write = patch(origOut, (s) => { stdout += s }) as typeof process.stdout.write + process.stderr.write = patch(origErr, (s) => { stderr += s }) as typeof process.stderr.write + const exitCode = process.exitCode + cmd.exitOverride() + try { + await cmd.parseAsync(argv, { from: 'user' }) + } catch { /* CommanderError from exitOverride */ } finally { + process.stdout.write = origOut + process.stderr.write = origErr + process.exitCode = exitCode + } + return { stdout, stderr } +} + +describe('buildKbPresetCommand', () => { + let tmpDir: string + let origIsTTY: boolean | undefined + before(() => { tmpDir = mkdtempSync(join(tmpdir(), 'elastic-cli-preset-')) }) + after(() => { rmSync(tmpDir, { recursive: true }) }) + beforeEach(() => { + origIsTTY = process.stdin.isTTY + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true, writable: true }) + }) + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true, writable: true }) + }) + + it('exposes the generated flags under the new name, minus the fixed fields', async () => { + const cmd = await buildKbPresetCommand({ + apiId: CHAT_MESSAGE, + name: 'ask', + description: 'Ask the agent', + fixed: { agent_id: 'nightshift.assistant' }, + }) + assert.equal(cmd.name(), 'ask') + assert.equal(cmd.description(), 'Ask the agent') + const flags = longFlags(cmd) + assert.ok(flags.includes('--message')) + assert.ok(flags.includes('--conversation-id')) + assert.ok(flags.includes('--dry-run')) + assert.equal(flags.includes('--agent-id'), false) + }) + + it('sends the fixed values with the generated request', async () => { + const sent: KibanaRequestParams[] = [] + const cmd = await buildKbPresetCommand({ + apiId: CHAT_MESSAGE, + name: 'ask', + description: 'Ask the agent', + fixed: { agent_id: 'nightshift.assistant' }, + }, recordingDeps(sent)) + const { stdout } = await run(cmd, ['--message', 'why is checkout slow?', '--conversation-id', 'c1']) + assert.equal(sent.length, 1) + assert.equal(sent[0]!.method, 'POST') + assert.equal(sent[0]!.path, '/api/chat/message') + assert.deepEqual(sent[0]!.body, { + message: 'why is checkout slow?', + conversation_id: 'c1', + agent_id: 'nightshift.assistant', + }) + assert.match(stdout, /hi/) + }) + + it('accepts the positional field as a positional argument', async () => { + const sent: KibanaRequestParams[] = [] + const cmd = await buildKbPresetCommand({ + apiId: CHAT_MESSAGE, + name: 'ask', + description: 'Ask the agent', + fixed: { agent_id: 'nightshift.assistant' }, + positional: 'message', + }, recordingDeps(sent)) + await run(cmd, ['why is checkout slow?']) + assert.equal(sent.length, 1) + assert.deepEqual(sent[0]!.body, { message: 'why is checkout slow?', agent_id: 'nightshift.assistant' }) + }) + + it('throws when the positional field is not part of the generated input schema', async () => { + await assert.rejects( + buildKbPresetCommand({ apiId: CHAT_MESSAGE, name: 'ask', description: 'x', fixed: {}, positional: 'msg' }), + /msg/ + ) + }) + + it('rejects a fixed field supplied via JSON input instead of overriding it silently', async () => { + const filePath = join(tmpDir, 'override.json') + writeFileSync(filePath, JSON.stringify({ message: 'hi', agent_id: 'elastic-ai-agent' })) + const sent: KibanaRequestParams[] = [] + const cmd = await buildKbPresetCommand({ + apiId: CHAT_MESSAGE, + name: 'ask', + description: 'Ask the agent', + fixed: { agent_id: 'nightshift.assistant' }, + }, recordingDeps(sent)) + const { stderr } = await run(cmd, ['--input-file', filePath]) + assert.equal(sent.length, 0) + assert.match(stderr, /agent_id/) + }) + + it('throws for an unknown API id', async () => { + await assert.rejects( + buildKbPresetCommand({ apiId: 'agent-builder.does-not-exist', name: 'ask', description: 'x', fixed: {} }), + /agent-builder\.does-not-exist/ + ) + }) + + describe('experimental', () => { + const base = { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', fixed: { agent_id: 'nightshift.assistant' } } + const BANNER = /Warning: "nightshift ask" is experimental and subject to significant changes before it reaches a stable state\.[\s\S]*--accept-experimental/ + + async function build (sent: KibanaRequestParams[]) { + const cmd = await buildKbPresetCommand({ ...base, experimental: { label: 'nightshift ask', status: 'subject to significant changes before it reaches a stable state' } }, recordingDeps(sent)) + assert.ok(cmd != null) + return cmd + } + + it('warns on stderr and still sends the request', async () => { + const sent: KibanaRequestParams[] = [] + const { stdout, stderr } = await run(await build(sent), ['--message', 'hi']) + assert.match(stderr, BANNER) + assert.doesNotMatch(stdout, /experimental/) + assert.equal(sent.length, 1) + assert.deepEqual(sent[0]!.body, { message: 'hi', agent_id: 'nightshift.assistant' }) + }) + + it('colors the warning only when stderr is a TTY', async () => { + const origIsTTY = process.stderr.isTTY + const setTTY = (value: boolean | undefined) => Object.defineProperty(process.stderr, 'isTTY', { value, configurable: true, writable: true }) + try { + setTTY(true) + const tty = await run(await build([]), ['--message', 'hi']) + assert.ok(tty.stderr.startsWith('\x1b[33mWarning: "nightshift ask" is experimental'), 'Expected ANSI yellow color code') + assert.ok(tty.stderr.includes('\x1b[0m'), 'Expected ANSI reset code') + setTTY(false) + const plain = await run(await build([]), ['--message', 'hi']) + assert.match(plain.stderr, BANNER) + assert.ok(!plain.stderr.includes('\x1b['), 'Expected no ANSI codes') + } finally { + setTTY(origIsTTY) + } + }) + + it('--accept-experimental suppresses the warning and is not sent to Kibana', async () => { + const sent: KibanaRequestParams[] = [] + const { stderr } = await run(await build(sent), ['--message', 'hi', '--accept-experimental']) + assert.doesNotMatch(stderr, /experimental/) + assert.deepEqual(sent[0]!.body, { message: 'hi', agent_id: 'nightshift.assistant' }) + }) + + it('--json suppresses the warning', async () => { + const sent: KibanaRequestParams[] = [] + const root = new Command('elastic').option('--json', 'output as JSON').addCommand(await build(sent)) + const { stderr } = await run(root, ['--json', 'ask', '--message', 'hi']) + assert.doesNotMatch(stderr, /experimental/) + assert.equal(sent.length, 1) + }) + + it('does not warn when validation fails before the request', async () => { + const sent: KibanaRequestParams[] = [] + const { stderr } = await run(await build(sent), []) + assert.doesNotMatch(stderr, /is experimental/) + assert.equal(sent.length, 0) + }) + + it('non-experimental presets have no flag and no warning', async () => { + const cmd = await buildKbPresetCommand(base, recordingDeps([])) + assert.ok(cmd != null) + assert.equal(longFlags(cmd).includes('--accept-experimental'), false) + const { stderr } = await run(cmd, ['--message', 'hi']) + assert.doesNotMatch(stderr, /experimental/) + }) + }) + + describe('availability', () => { + const base = { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', fixed: {} } + + it('returns null when the target stack version predates the endpoint', async () => { + assert.equal(await buildKbPresetCommand({ ...base, target: [9, 5] }), null) + }) + + it('builds the command when the target stack version has the endpoint', async () => { + assert.ok(await buildKbPresetCommand({ ...base, target: [9, 6] }) != null) + }) + + it('builds the command without a target', async () => { + assert.ok(await buildKbPresetCommand(base) != null) + }) + + it('with flavors: [serverless], returns null for any stack target', async () => { + assert.equal(await buildKbPresetCommand({ ...base, flavors: ['serverless'], target: [9, 6] }), null) + assert.equal(await buildKbPresetCommand({ ...base, flavors: ['serverless'], target: [10, 0] }), null) + }) + + it('with flavors: [serverless], builds the command for a serverless target or no target', async () => { + assert.ok(await buildKbPresetCommand({ ...base, flavors: ['serverless'], target: 'serverless' }) != null) + assert.ok(await buildKbPresetCommand({ ...base, flavors: ['serverless'] }) != null) + }) + + it('throws when a flavor is not in the endpoint availability', async () => { + await assert.rejects( + buildKbPresetCommand({ ...base, flavors: ['serverless', 'cloud' as 'serverless'] }), + /cloud/ + ) + }) + }) + + it('throws when a fixed field is not part of the generated input schema', async () => { + await assert.rejects( + buildKbPresetCommand({ apiId: CHAT_MESSAGE, name: 'ask', description: 'x', fixed: { agentid: 'typo' } }), + /agentid/ + ) + }) +}) diff --git a/test/lib/experimental.test.ts b/test/lib/experimental.test.ts new file mode 100644 index 00000000..d357ae3c --- /dev/null +++ b/test/lib/experimental.test.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import { ACCEPT_EXPERIMENTAL_OPTION, warnIfExperimental } from '../../src/lib/experimental.ts' +import type { ParsedResult } from '../../src/factory.ts' + +function capture (): { write: (s: string) => boolean, text: () => string } { + const chunks: string[] = [] + return { write: (s) => { chunks.push(s); return true }, text: () => chunks.join('') } +} + +function withStderrTTY (value: boolean, fn: () => void): void { + const orig = process.stderr.isTTY + Object.defineProperty(process.stderr, 'isTTY', { value, configurable: true, writable: true }) + try { fn() } finally { + Object.defineProperty(process.stderr, 'isTTY', { value: orig, configurable: true, writable: true }) + } +} + +const parsed = (options: ParsedResult['options'] = {}): ParsedResult => ({ options }) + +describe('ACCEPT_EXPERIMENTAL_OPTION', () => { + it('is a boolean --accept-experimental flag', () => { + assert.equal(ACCEPT_EXPERIMENTAL_OPTION.long, 'accept-experimental') + assert.equal(ACCEPT_EXPERIMENTAL_OPTION.type, 'boolean') + assert.match(ACCEPT_EXPERIMENTAL_OPTION.description, /experimental/) + }) +}) + +describe('warnIfExperimental', () => { + const docs = { label: 'docs search', status: 'in active development', advice: 'Not yet suited for scripts or automation.' } + const nightshift = { label: 'nightshift ask', status: 'subject to significant changes before it reaches a stable state' } + + it('writes the banner with an advice line', () => { + const err = capture() + withStderrTTY(false, () => { warnIfExperimental(parsed(), docs, err) }) + assert.equal(err.text(), + 'Warning: "docs search" is experimental and in active development.\n' + + ' Not yet suited for scripts or automation. Pass --accept-experimental to suppress this warning.\n\n') + }) + + it('writes the banner without an advice line', () => { + const err = capture() + withStderrTTY(false, () => { warnIfExperimental(parsed(), nightshift, err) }) + assert.equal(err.text(), + 'Warning: "nightshift ask" is experimental and subject to significant changes before it reaches a stable state.\n' + + ' Pass --accept-experimental to suppress this warning.\n\n') + }) + + it('colors the banner yellow only when stderr is a TTY', () => { + const tty = capture() + withStderrTTY(true, () => { warnIfExperimental(parsed(), nightshift, tty) }) + assert.ok(tty.text().startsWith('\x1b[33mWarning: "nightshift ask"')) + assert.ok(tty.text().endsWith('\x1b[0m')) + }) + + it('is suppressed by --accept-experimental', () => { + const err = capture() + warnIfExperimental(parsed({ 'accept-experimental': true }), nightshift, err) + assert.equal(err.text(), '') + }) + + it('is suppressed by --json', () => { + const err = capture() + warnIfExperimental(parsed({ json: true }), nightshift, err) + assert.equal(err.text(), '') + }) +}) diff --git a/test/namespaces.test.ts b/test/namespaces.test.ts new file mode 100644 index 00000000..8cbde071 --- /dev/null +++ b/test/namespaces.test.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, afterEach } from 'node:test' +import assert from 'node:assert/strict' +import { NAMESPACES } from '../src/namespaces.ts' +import { setResolvedConfig, _testResetConfig } from '../src/config/store.ts' +import type { ResolvedConfig } from '../src/config/types.ts' +import { getKibanaClient, _testResetKibanaClient } from '../src/lib/kibana-client.ts' + +function withKibanaVersion (version: string): void { + setResolvedConfig({ context: { kibana: { version } } } as unknown as ResolvedConfig) +} + +describe('nightshift namespace', () => { + const ns = NAMESPACES.find(n => n.name === 'nightshift')! + afterEach(() => { _testResetConfig() }) + + it('sends `ask` to the Nightshift assistant agent', async (t) => { + setResolvedConfig({ context: { kibana: { url: 'http://localhost:5601' } } } as unknown as ResolvedConfig) + t.after(() => { _testResetKibanaClient() }) + const bodies: unknown[] = [] + getKibanaClient()._testSetFetch(async (_url, init) => { + bodies.push(JSON.parse(String(init?.body))) + return new Response('{"conversation_id":"c1"}', { status: 200, headers: { 'content-type': 'application/json' } }) + }) + const origIsTTY = process.stdin.isTTY + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true, writable: true }) + t.after(() => { Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true, writable: true }) }) + t.mock.method(process.stdout, 'write', () => true) + + const group = await ns.load() + group.exitOverride() + await group.parseAsync(['ask', 'why is checkout slow?'], { from: 'user' }) + + assert.deepEqual(bodies, [{ agent_id: 'nightshift.assistant', message: 'why is checkout slow?' }]) + }) + + it('exposes the generated chat message command as `ask` without an agent flag', async () => { + assert.ok(ns != null) + const group = await ns.load() + assert.equal(group.name(), 'nightshift') + const ask = group.commands.find(c => c.name() === 'ask') + assert.ok(ask != null) + const flags = ask.options.map(o => o.long) + assert.ok(flags.includes('--message')) + assert.equal(flags.includes('--agent-id'), false) + assert.ok(flags.includes('--accept-experimental'), 'nightshift ask is experimental') + assert.deepEqual(ask.registeredArguments.map(a => a.name()), ['message']) + }) + + it('offers `ask` when the Kibana version hint is serverless', async () => { + withKibanaVersion('serverless') + const group = await ns.load() + assert.ok(group.commands.some(c => c.name() === 'ask')) + }) + + for (const version of ['9.5', '9.6', '9.7']) { + it(`hides \`ask\` when the Kibana version hint is stack ${version}`, async () => { + withKibanaVersion(version) + const group = await ns.load() + assert.equal(group.commands.some(c => c.name() === 'ask'), false) + }) + } + + it('keeps `ask` in the eager tree regardless of the version hint', async () => { + withKibanaVersion('9.5') + const group = await ns.load({ eager: true }) + assert.ok(group.commands.some(c => c.name() === 'ask')) + }) +})