From 9d8b952ef8fd0116379b8fb9cf30e3658f2efb01 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Mon, 19 Oct 2026 11:57:45 +0200 Subject: [PATCH 1/9] feat(nightshift): add `elastic nightshift ask` on top of the generated chat message command `nightshift ask` is the generated `kb agent-builder post-chat-message` command (POST /api/chat/message) with `agent_id` pinned to `nightshift.investigation`. A new `buildKbPresetCommand` helper re-exposes any generated Kibana command under a new name with some input fields fixed. Fixed fields are removed from the flags and schema, and supplying one via JSON input is a validation error rather than a silent override. Co-authored-by: Cursor --- README.md | 11 +++ docs/cli/schema.json | 55 +++++++++++++ src/completion/complete.ts | 8 ++ src/kb/register.ts | 55 ++++++++++++- src/namespaces.ts | 16 ++++ test/completion/complete.test.ts | 8 ++ test/kb/preset.test.ts | 128 +++++++++++++++++++++++++++++++ test/namespaces.test.ts | 22 ++++++ 8 files changed, 300 insertions(+), 3 deletions(-) create mode 100644 test/kb/preset.test.ts create mode 100644 test/namespaces.test.ts diff --git a/README.md b/README.md index fdcd9ae1..955feb76 100644 --- a/README.md +++ b/README.md @@ -409,6 +409,17 @@ elastic kb alerting list-rule-types Run `elastic kb --help` for all available commands in a namespace. +### `nightshift` - Nightshift investigation agent + +Ask the Nightshift investigation agent a question and get its answer back in a single response. +This is `elastic kb agent-builder post-chat-message` with the agent fixed to `nightshift.investigation`. +Requires Kibana 9.6+ with the `agentBuilder:experimentalFeatures` advanced setting enabled. + +```bash +elastic nightshift ask --message "Why did checkout latency spike at 14:00?" +elastic nightshift ask --conversation-id --message "Which service should I look at first?" +``` + ### `cloud` - Elastic Cloud Manage Elastic Cloud: Hosted deployments and Serverless projects. diff --git a/docs/cli/schema.json b/docs/cli/schema.json index cd594e37..9c66deb1 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -120794,6 +120794,61 @@ } ] }, + { + "segment": "nightshift", + "commands": [ + { + "path": [ + "nightshift" + ], + "name": "ask", + "parameters": [], + "summary": "Ask the Nightshift investigation agent a question and get its answer", + "intent": { + "requiresAuth": true + } + } + ], + "namespaces": [], + "summary": "Ask the Nightshift investigation agent", + "options": [ + { + "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/completion/complete.ts b/src/completion/complete.ts index 67612a3e..b3eee3db 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 investigation agent' })) + } + // `config` — deep-load on exact match, stub otherwise. if (firstWord === 'config') { const { registerConfigCommands } = await import('../config/commands.ts') diff --git a/src/kb/register.ts b/src/kb/register.ts index 36514f0f..80e3d1a9 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -5,13 +5,14 @@ import { Command } from 'commander' import { defineCommand, defineGroup } from '../factory.ts' -import type { OpaqueCommandHandle } from '../factory.ts' +import type { HandlerResult, JsonValue, OpaqueCommandHandle, ParsedResult } 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' @@ -24,14 +25,18 @@ import { getResolvedConfig } from '../config/store.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, + handler: (parsed: ParsedResult) => Promise = createKbHandler(def) +): OpaqueCommandHandle { validateKbApiDefinition(def) return defineCommand({ name: def.name, description: def.description, ...(def.input !== undefined ? { input: def.input } : {}), readOnly: def.method === 'GET' || def.method === 'HEAD', - handler: createKbHandler(def), + handler, ...(def.intent != null || inferIntentFromHttp(def.method) != null ? { intent: def.intent ?? inferIntentFromHttp(def.method)! } : {}), @@ -63,6 +68,50 @@ function buildStubLeaf (meta: KbApiMeta, target?: AvailabilityTarget): OpaqueCom return cmd } +/** 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 +} + +/** + * 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 + * @throws {Error} if `apiId` is not in the manifest or a fixed field is not in its input schema + */ +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)}`) + 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 required = Array.isArray(def.input?.['required']) + ? (def.input['required'] as string[]).filter(key => !(key in opts.fixed)) + : [] + const handler = createKbHandler(def, deps) + 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 }, + }, + undefined, + async (parsed) => await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }) + ) +} + /** * Sniffs `process.argv` to identify which KB leaf command the user * intends to invoke. Returns `null` on ambiguity or help requests. diff --git a/src/namespaces.ts b/src/namespaces.ts index 113d0d26..5984c25b 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -122,6 +122,22 @@ export const NAMESPACES: NamespaceEntry[] = [ return registerDocsCommands() }, }, + { + name: 'nightshift', + description: 'Ask the Nightshift investigation agent', + load: async () => { + const { buildKbPresetCommand } = await import('./kb/register.ts') + return defineGroup( + { name: 'nightshift', description: 'Ask the Nightshift investigation agent' }, + await buildKbPresetCommand({ + apiId: 'agent-builder.post-chat-message', + name: 'ask', + description: 'Ask the Nightshift investigation agent a question and get its answer', + fixed: { agent_id: 'nightshift.investigation' }, + }), + ) + }, + }, { name: 'config', description: 'Author and maintain the elastic config file', diff --git a/test/completion/complete.test.ts b/test/completion/complete.test.ts index 426f4118..532fcd5f 100644 --- a/test/completion/complete.test.ts +++ b/test/completion/complete.test.ts @@ -396,6 +396,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/kb/preset.test.ts b/test/kb/preset.test.ts new file mode 100644 index 00000000..ed5c812a --- /dev/null +++ b/test/kb/preset.test.ts @@ -0,0 +1,128 @@ +/* + * 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 { 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.investigation' }, + }) + 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.investigation' }, + }, 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.investigation', + }) + assert.match(stdout, /hi/) + }) + + 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.investigation' }, + }, 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/ + ) + }) + + 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/namespaces.test.ts b/test/namespaces.test.ts new file mode 100644 index 00000000..b728bed8 --- /dev/null +++ b/test/namespaces.test.ts @@ -0,0 +1,22 @@ +/* + * 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 { NAMESPACES } from '../src/namespaces.ts' + +describe('nightshift namespace', () => { + it('exposes the generated chat message command as `ask`, pinned to the investigation agent', async () => { + const ns = NAMESPACES.find(n => n.name === 'nightshift') + 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) + }) +}) From 158f2d79cd4d772259fd91ad608e491c77553b07 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Mon, 19 Oct 2026 12:10:10 +0200 Subject: [PATCH 2/9] feat(nightshift): accept the question as a positional argument `elastic nightshift ask "..."` now works alongside `--message`. `positionalArg.inputKey` lets a command fill an input schema field from its positional argument before validation; passing both the argument and the flag is an error. `buildKbPresetCommand` exposes this as a `positional` option. Also fixes cli-schema option hoisting, which dropped a positional parameter whenever a hoisted flag had the same name. Co-authored-by: Cursor --- README.md | 4 ++-- docs/cli/schema.json | 10 +++++++++- src/cli-schema.ts | 4 ++-- src/factory-core.ts | 6 +++++- src/factory.ts | 10 ++++++++++ src/kb/register.ts | 29 ++++++++++++++++++++++++----- src/namespaces.ts | 1 + test/cli-schema.test.ts | 20 ++++++++++++++++++++ test/factory.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ test/kb/preset.test.ts | 21 +++++++++++++++++++++ test/namespaces.test.ts | 1 + 11 files changed, 136 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 955feb76..912bc890 100644 --- a/README.md +++ b/README.md @@ -416,8 +416,8 @@ This is `elastic kb agent-builder post-chat-message` with the agent fixed to `ni Requires Kibana 9.6+ with the `agentBuilder:experimentalFeatures` advanced setting enabled. ```bash -elastic nightshift ask --message "Why did checkout latency spike at 14:00?" -elastic nightshift ask --conversation-id --message "Which service should I look at first?" +elastic nightshift ask "Why did checkout latency spike at 14:00?" +elastic nightshift ask --conversation-id "Which service should I look at first?" ``` ### `cloud` - Elastic Cloud diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 9c66deb1..aeb93954 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -120802,7 +120802,15 @@ "nightshift" ], "name": "ask", - "parameters": [], + "parameters": [ + { + "role": "positional", + "name": "message", + "type": "string", + "required": false, + "summary": "The user message to send to the agent." + } + ], "summary": "Ask the Nightshift investigation agent a question and get its answer", "intent": { "requiresAuth": true diff --git a/src/cli-schema.ts b/src/cli-schema.ts index b8ba1bf0..239dc217 100644 --- a/src/cli-schema.ts +++ b/src/cli-schema.ts @@ -424,7 +424,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) } @@ -464,7 +464,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/factory-core.ts b/src/factory-core.ts index 5a6f42ae..b97cb0cb 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 diff --git a/src/factory.ts b/src/factory.ts index 0387c172..4a6ef359 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -667,6 +667,16 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { } } + const positionalKey = config.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 ${config.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 } } diff --git a/src/kb/register.ts b/src/kb/register.ts index 80e3d1a9..d4332f4e 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -5,7 +5,7 @@ import { Command } from 'commander' import { defineCommand, defineGroup } from '../factory.ts' -import type { HandlerResult, JsonValue, OpaqueCommandHandle, ParsedResult } 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' @@ -28,7 +28,7 @@ import { getResolvedConfig } from '../config/store.ts' function buildLeafHandle ( def: KbApiDefinition, target?: AvailabilityTarget, - handler: (parsed: ParsedResult) => Promise = createKbHandler(def) + overrides: Pick & { handler?: CommandConfig['handler'] } = {} ): OpaqueCommandHandle { validateKbApiDefinition(def) return defineCommand({ @@ -36,7 +36,8 @@ function buildLeafHandle ( description: def.description, ...(def.input !== undefined ? { input: def.input } : {}), readOnly: def.method === 'GET' || def.method === 'HEAD', - handler, + handler: overrides.handler ?? createKbHandler(def), + ...(overrides.positionalArg !== undefined ? { positionalArg: overrides.positionalArg } : {}), ...(def.intent != null || inferIntentFromHttp(def.method) != null ? { intent: def.intent ?? inferIntentFromHttp(def.method)! } : {}), @@ -76,6 +77,8 @@ export interface KbPresetOptions { 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 } /** @@ -84,7 +87,7 @@ export interface KbPresetOptions { * schema, request builder, or handler. * * @param deps - test seam forwarded to `createKbHandler`; production callers omit it - * @throws {Error} if `apiId` is not in the manifest or a fixed field is not in its input schema + * @throws {Error} if `apiId` is not in the manifest, or a fixed or positional field is not in its input schema */ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHandlerDeps): Promise { const meta = kbApiManifest.find(m => m.id === opts.apiId) @@ -95,6 +98,10 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand 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)) : [] @@ -108,7 +115,19 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand input: { ...def.input, properties, required, additionalProperties: false }, }, undefined, - async (parsed) => await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }) + { + handler: async (parsed) => await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }), + ...(positional != null + ? { + positionalArg: { + name: positional, + description: String((properties[positional] as Record)['description'] ?? positional), + required: false, + inputKey: positional, + }, + } + : {}), + } ) } diff --git a/src/namespaces.ts b/src/namespaces.ts index 5984c25b..3f76f633 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -134,6 +134,7 @@ export const NAMESPACES: NamespaceEntry[] = [ name: 'ask', description: 'Ask the Nightshift investigation agent a question and get its answer', fixed: { agent_id: 'nightshift.investigation' }, + positional: 'message', }), ) }, diff --git a/test/cli-schema.test.ts b/test/cli-schema.test.ts index 66aefea0..f4e0b038 100644 --- a/test/cli-schema.test.ts +++ b/test/cli-schema.test.ts @@ -53,6 +53,26 @@ function findCommand (namespaces: CliNamespace[], path: string[], name: string): return undefined } +describe('buildCliSchema option hoisting', () => { + it('keeps a positional that shares its name with a hoisted flag', async () => { + const { Command } = await import('commander') + const { defineCommand, defineGroup } = await import('../src/factory.ts') + const { buildCliSchema } = await import('../src/cli-schema.ts') + const ask = defineCommand({ + name: 'ask', + description: 'Ask', + input: { type: 'object', properties: { message: { type: 'string' } } }, + positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, + handler: () => ({}), + }) + const root = new Command('elastic') + root.addCommand(defineGroup({ name: 'nightshift', description: 'Nightshift' }, ask)) + const schema = buildCliSchema(root, [], '0.0.0') + const params = schema.namespaces[0]?.commands[0]?.parameters ?? [] + assert.deepEqual(params.filter(p => p.role === 'positional').map(p => p.name), ['message']) + }) +}) + describe('cli schema', () => { it('does not emit runtime shortcuts into the docs-builder schema', async () => { const { code, stdout, stderr } = await runCliSchema() diff --git a/test/factory.test.ts b/test/factory.test.ts index 7df4f4eb..47c57c35 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -247,6 +247,47 @@ describe('defineCommand', () => { assert.equal(received[0].arg, 'ingest pipelines') }) + 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('sets parsed.arg to undefined when no positionalArg is declared', async () => { const received: ParsedResult[] = [] const cmd = defineCommand({ diff --git a/test/kb/preset.test.ts b/test/kb/preset.test.ts index ed5c812a..3c303f9e 100644 --- a/test/kb/preset.test.ts +++ b/test/kb/preset.test.ts @@ -97,6 +97,27 @@ describe('buildKbPresetCommand', () => { 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.investigation' }, + 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.investigation' }) + }) + + 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' })) diff --git a/test/namespaces.test.ts b/test/namespaces.test.ts index b728bed8..86f9260c 100644 --- a/test/namespaces.test.ts +++ b/test/namespaces.test.ts @@ -18,5 +18,6 @@ describe('nightshift namespace', () => { const flags = ask.options.map(o => o.long) assert.ok(flags.includes('--message')) assert.equal(flags.includes('--agent-id'), false) + assert.deepEqual(ask.registeredArguments.map(a => a.name()), ['message']) }) }) From b29e7774830b5951455189b48de122a303199d6c Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Mon, 19 Oct 2026 12:19:18 +0200 Subject: [PATCH 3/9] test(cli): check positional hoisting through the real cli-schema output Running the emitter in a subprocess, like the other cli-schema tests, checks the real nightshift ask entry and keeps cli-schema.ts out of in-process coverage, which pulled branch coverage below the 90% threshold in CI. Co-authored-by: Cursor --- test/cli-schema.test.ts | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/test/cli-schema.test.ts b/test/cli-schema.test.ts index f4e0b038..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 } @@ -53,27 +54,19 @@ function findCommand (namespaces: CliNamespace[], path: string[], name: string): return undefined } -describe('buildCliSchema option hoisting', () => { +describe('cli schema', () => { it('keeps a positional that shares its name with a hoisted flag', async () => { - const { Command } = await import('commander') - const { defineCommand, defineGroup } = await import('../src/factory.ts') - const { buildCliSchema } = await import('../src/cli-schema.ts') - const ask = defineCommand({ - name: 'ask', - description: 'Ask', - input: { type: 'object', properties: { message: { type: 'string' } } }, - positionalArg: { name: 'message', description: 'Message', required: false, inputKey: 'message' }, - handler: () => ({}), - }) - const root = new Command('elastic') - root.addCommand(defineGroup({ name: 'nightshift', description: 'Nightshift' }, ask)) - const schema = buildCliSchema(root, [], '0.0.0') - const params = schema.namespaces[0]?.commands[0]?.parameters ?? [] - assert.deepEqual(params.filter(p => p.role === 'positional').map(p => p.name), ['message']) + 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']) }) -}) -describe('cli schema', () => { it('does not emit runtime shortcuts into the docs-builder schema', async () => { const { code, stdout, stderr } = await runCliSchema() assert.equal(code, 0, stderr) From 61dc9be25cb9b3633b324c8f95d05069b0c264f0 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Mon, 19 Oct 2026 12:47:07 +0200 Subject: [PATCH 4/9] feat(config): scope nightshift to the serverless command profiles `nightshift` only applies to Serverless Observability projects. The `serverless` and `default` profiles now allow `nightshift.*` (they previously blocked it, since their allow-list only covered `stack.*`), and the `stack` profile blocks it, which also hides it from namespace help and completion. Without a profile nothing changes. Co-authored-by: Cursor --- README.md | 2 +- docs/cli/configuration_reference.md | 4 ++-- src/config/profiles.ts | 17 +++++++++++------ src/factory-core.ts | 6 ++---- test/completion/complete.test.ts | 19 +++++++++++++++++++ test/factory.test.ts | 17 ++++++++++++++++- 6 files changed, 51 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 912bc890..e08e0917 100644 --- a/README.md +++ b/README.md @@ -413,7 +413,7 @@ Run `elastic kb --help` for all available commands in a namespace. Ask the Nightshift investigation agent a question and get its answer back in a single response. This is `elastic kb agent-builder post-chat-message` with the agent fixed to `nightshift.investigation`. -Requires Kibana 9.6+ with the `agentBuilder:experimentalFeatures` advanced setting enabled. +Intended for Serverless Observability projects: requires Kibana 9.6+ with the `agentBuilder:experimentalFeatures` advanced setting enabled, and the `stack` command profile hides and blocks it. ```bash elastic nightshift ask "Why did checkout latency spike at 14:00?" diff --git a/docs/cli/configuration_reference.md b/docs/cli/configuration_reference.md index 1f22bb0b..00abfa8c 100644 --- a/docs/cli/configuration_reference.md +++ b/docs/cli/configuration_reference.md @@ -79,6 +79,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/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/factory-core.ts b/src/factory-core.ts index b97cb0cb..4711b95f 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -198,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/test/completion/complete.test.ts b/test/completion/complete.test.ts index 532fcd5f..91627ae5 100644 --- a/test/completion/complete.test.ts +++ b/test/completion/complete.test.ts @@ -148,6 +148,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 () => { + await withConfig([ + `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 () => { await withConfig([ 'current_context: local', diff --git a/test/factory.test.ts b/test/factory.test.ts index 47c57c35..6d7d1cf4 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -3112,12 +3112,27 @@ 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) }) + 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: blocks nightshift commands, which only apply to observability serverless', () => { + assert.equal(isCommandAllowed('nightshift.ask', { profile: 'stack' }), false) + }) + + 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', () => { const policy = { profile: 'serverless' as const, blocked: ['stack.es.ml.*'] } assert.equal(isCommandAllowed('stack.es.search', policy), true) From bf452bdfcb1be137a4ee33087bd962931a6943a3 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Mon, 19 Oct 2026 13:02:01 +0200 Subject: [PATCH 5/9] test(cli): keep positional inputKey tests from reading stdin The factory reads JSON input from stdin when it is not a TTY. On Windows CI that read never ends, so test/factory.test.ts hit the 60s timeout. Mark stdin as a TTY like the file's other input tests. Co-authored-by: Cursor --- test/factory.test.ts | 80 +++++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 34 deletions(-) diff --git a/test/factory.test.ts b/test/factory.test.ts index 6d7d1cf4..c4e807fd 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -247,45 +247,57 @@ describe('defineCommand', () => { assert.equal(received[0].arg, 'ingest pipelines') }) - 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 {} }, + 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 }) }) - 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 {} }, + 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' }) }) - 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 {} }, + 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/) }) - const err = await captureErrAsync(cmd, ['one', '--message', 'two']) - assert.equal(received.length, 0) - assert.match(err, /--message/) }) it('sets parsed.arg to undefined when no positionalArg is declared', async () => { From 6d1737ac99bcfbf5b23f08bb8954a26544ce793a Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Tue, 3 Nov 2026 10:58:26 +0100 Subject: [PATCH 6/9] fix(nightshift): gate ask to serverless targets and pin the assistant agent - Resolve the Kibana availability target for the preset and restrict it to serverless, so nightshift ask is hidden for stack version hints. - Pin agent_id to nightshift.assistant, the single-question agent, instead of the investigation agent. - Reword docs to Serverless Observability only. - Add regression tests for the --json positional conflict error and fold the nightshift assertion into the stack profile test. Co-authored-by: Cursor --- docs/cli/nightshift/index.md | 8 ++++-- docs/cli/schema.json | 4 +-- src/completion/complete.ts | 2 +- src/kb/register.ts | 34 ++++++++++++++++------ src/namespaces.ts | 27 ++++++++++-------- test/factory.test.ts | 23 ++++++++++++--- test/kb/preset.test.ts | 45 +++++++++++++++++++++++++---- test/namespaces.test.ts | 55 ++++++++++++++++++++++++++++++++++-- 8 files changed, 160 insertions(+), 38 deletions(-) diff --git a/docs/cli/nightshift/index.md b/docs/cli/nightshift/index.md index 7aa0d239..e4eeabee 100644 --- a/docs/cli/nightshift/index.md +++ b/docs/cli/nightshift/index.md @@ -1,8 +1,10 @@ ## Description -Ask the Nightshift investigation agent a question and get its answer back in a single response. -This is `elastic kb agent-builder post-chat-message` with the agent fixed to `nightshift.investigation`. -Intended for Serverless Observability projects: requires {{kib}} 9.6+ with the `agentBuilder:experimentalFeatures` advanced setting enabled, and the `stack` command profile hides and blocks it. +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?" diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 79bbf600..62979ca5 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -120811,14 +120811,14 @@ "summary": "The user message to send to the agent." } ], - "summary": "Ask the Nightshift investigation agent a question and get its answer", + "summary": "Ask the Nightshift assistant a question and get its answer", "intent": { "requiresAuth": true } } ], "namespaces": [], - "summary": "Ask the Nightshift investigation agent", + "summary": "Ask the Nightshift assistant", "options": [ { "role": "flag", diff --git a/src/completion/complete.ts b/src/completion/complete.ts index b3eee3db..69e091d4 100644 --- a/src/completion/complete.ts +++ b/src/completion/complete.ts @@ -202,7 +202,7 @@ export async function buildCompletionTree (rewrittenWords: readonly string[]): P 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 investigation agent' })) + root.addCommand(defineGroup({ name: 'nightshift', description: 'Ask the Nightshift assistant' })) } // `config` — deep-load on exact match, stub otherwise. diff --git a/src/kb/register.ts b/src/kb/register.ts index 2e440817..0f9fd939 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -55,6 +55,10 @@ export interface KbPresetOptions { 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'> } /** @@ -63,11 +67,23 @@ export interface KbPresetOptions { * schema, request builder, or handler. * * @param deps - test seam forwarded to `createKbHandler`; production callers omit it - * @throws {Error} if `apiId` is not in the manifest, or a fixed or positional field is not in its input schema + * @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 { +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)) { @@ -90,7 +106,7 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand // Generated schemas allow unknown keys; a pinned field supplied via JSON must error, not be overridden. input: { ...def.input, properties, required, additionalProperties: false }, }, - undefined, + opts.target, { handler: async (parsed) => await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }), ...(positional != null @@ -126,6 +142,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. */ @@ -143,11 +165,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/namespaces.ts b/src/namespaces.ts index f60636b7..659e0ca0 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -124,18 +124,23 @@ export const NAMESPACES: NamespaceEntry[] = [ }, { name: 'nightshift', - description: 'Ask the Nightshift investigation agent', - load: async () => { - const { buildKbPresetCommand } = await import('./kb/register.ts') + 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'], + ...(target !== undefined ? { target } : {}), + }) return defineGroup( - { name: 'nightshift', description: 'Ask the Nightshift investigation agent' }, - await buildKbPresetCommand({ - apiId: 'agent-builder.post-chat-message', - name: 'ask', - description: 'Ask the Nightshift investigation agent a question and get its answer', - fixed: { agent_id: 'nightshift.investigation' }, - positional: 'message', - }), + { name: 'nightshift', description: 'Ask the Nightshift assistant' }, + ...(ask != null ? [ask] : []), ) }, }, diff --git a/test/factory.test.ts b/test/factory.test.ts index 9951df70..a8921cea 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -299,6 +299,24 @@ describe('defineCommand', () => { 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 () => { @@ -3115,6 +3133,7 @@ describe('isCommandAllowed', () => { 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', () => { @@ -3122,10 +3141,6 @@ describe('isCommandAllowed', () => { assert.equal(isCommandAllowed('nightshift.ask', { profile: 'default' }), true) }) - it('profile stack: blocks nightshift commands, which only apply to observability serverless', () => { - assert.equal(isCommandAllowed('nightshift.ask', { profile: 'stack' }), false) - }) - 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) diff --git a/test/kb/preset.test.ts b/test/kb/preset.test.ts index 3c303f9e..e1742621 100644 --- a/test/kb/preset.test.ts +++ b/test/kb/preset.test.ts @@ -66,7 +66,7 @@ describe('buildKbPresetCommand', () => { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', - fixed: { agent_id: 'nightshift.investigation' }, + fixed: { agent_id: 'nightshift.assistant' }, }) assert.equal(cmd.name(), 'ask') assert.equal(cmd.description(), 'Ask the agent') @@ -83,7 +83,7 @@ describe('buildKbPresetCommand', () => { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', - fixed: { agent_id: 'nightshift.investigation' }, + 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) @@ -92,7 +92,7 @@ describe('buildKbPresetCommand', () => { assert.deepEqual(sent[0]!.body, { message: 'why is checkout slow?', conversation_id: 'c1', - agent_id: 'nightshift.investigation', + agent_id: 'nightshift.assistant', }) assert.match(stdout, /hi/) }) @@ -103,12 +103,12 @@ describe('buildKbPresetCommand', () => { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', - fixed: { agent_id: 'nightshift.investigation' }, + 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.investigation' }) + 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 () => { @@ -126,7 +126,7 @@ describe('buildKbPresetCommand', () => { apiId: CHAT_MESSAGE, name: 'ask', description: 'Ask the agent', - fixed: { agent_id: 'nightshift.investigation' }, + fixed: { agent_id: 'nightshift.assistant' }, }, recordingDeps(sent)) const { stderr } = await run(cmd, ['--input-file', filePath]) assert.equal(sent.length, 0) @@ -140,6 +140,39 @@ describe('buildKbPresetCommand', () => { ) }) + 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' } }), diff --git a/test/namespaces.test.ts b/test/namespaces.test.ts index 86f9260c..558e9b12 100644 --- a/test/namespaces.test.ts +++ b/test/namespaces.test.ts @@ -3,13 +3,42 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it } from 'node:test' +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', () => { - it('exposes the generated chat message command as `ask`, pinned to the investigation agent', async () => { - const ns = NAMESPACES.find(n => n.name === 'nightshift') + 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') @@ -20,4 +49,24 @@ describe('nightshift namespace', () => { assert.equal(flags.includes('--agent-id'), false) 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')) + }) }) From 04dc9c048abb7f6e95199a222ac6dbb5e64acfd8 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Tue, 3 Nov 2026 11:24:48 +0100 Subject: [PATCH 7/9] test: restore an unset exit code as 0 in captureStreams Bun ignores `process.exitCode = undefined`, so the new --json positional conflict test leaked exit code 1 into later tests under Bun. Co-authored-by: Cursor --- test/factory.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/factory.test.ts b/test/factory.test.ts index a8921cea..2eac077f 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -4375,7 +4375,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 } From 0e55b443df183ff57b1c6c88eea4becd3dfddd1c Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Wed, 4 Nov 2026 10:29:39 +0100 Subject: [PATCH 8/9] feat(nightshift): warn that nightshift ask is experimental Print a stderr warning before each nightshift ask request, suppressed by --accept-experimental or --json, following the elastic docs commands. Add a matching warning callout to the Nightshift docs page. Co-authored-by: Cursor --- docs/cli/nightshift/index.md | 4 +++ docs/cli/schema.json | 7 ++++ src/kb/register.ts | 32 +++++++++++++++-- src/namespaces.ts | 1 + test/kb/preset.test.ts | 68 ++++++++++++++++++++++++++++++++++++ test/namespaces.test.ts | 1 + 6 files changed, 111 insertions(+), 2 deletions(-) diff --git a/docs/cli/nightshift/index.md b/docs/cli/nightshift/index.md index e4eeabee..584ba286 100644 --- a/docs/cli/nightshift/index.md +++ b/docs/cli/nightshift/index.md @@ -1,5 +1,9 @@ ## 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`. diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 62979ca5..07552e31 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -120820,6 +120820,13 @@ "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 significantly; suppresses the warning" + }, { "role": "flag", "name": "conversation-id", diff --git a/src/kb/register.ts b/src/kb/register.ts index 0f9fd939..194e4f8a 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -28,7 +28,7 @@ import { buildStubLeaf } from '../lib/lazy-leaf.ts' function buildLeafHandle ( def: KbApiDefinition, target?: AvailabilityTarget, - overrides: Pick & { handler?: CommandConfig['handler'] } = {} + overrides: Pick & { handler?: CommandConfig['handler'] } = {} ): OpaqueCommandHandle { validateKbApiDefinition(def) const intent = def.intent ?? inferIntentFromHttp(def.method) @@ -39,6 +39,7 @@ function buildLeafHandle ( readOnly: def.method === 'GET' || def.method === 'HEAD', 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 } : {}), @@ -59,6 +60,18 @@ export interface KbPresetOptions { 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. `label` names the command in the warning. + */ + experimental?: { label: string } +} + +function experimentalBanner (label: string, isTTY: boolean): string { + const text = + `Warning: "${label}" is experimental and subject to significant changes before it reaches a stable state.\n` + + ' Pass --accept-experimental to suppress this warning.\n\n' + return isTTY ? `\x1b[33m${text}\x1b[0m` : text } /** @@ -98,6 +111,7 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand ? (def.input['required'] as string[]).filter(key => !(key in opts.fixed)) : [] const handler = createKbHandler(def, deps) + const experimental = opts.experimental return buildLeafHandle( { ...def, @@ -108,7 +122,21 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand }, opts.target, { - handler: async (parsed) => await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }), + handler: async (parsed) => { + if (experimental != null && parsed.options['accept-experimental'] !== true && parsed.options['json'] !== true) { + process.stderr.write(experimentalBanner(experimental.label, process.stderr.isTTY === true)) + } + return await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }) + }, + ...(experimental != null + ? { + options: [{ + long: 'accept-experimental', + type: 'boolean' as const, + description: 'Acknowledge that this command is experimental and may change significantly; suppresses the warning', + }], + } + : {}), ...(positional != null ? { positionalArg: { diff --git a/src/namespaces.ts b/src/namespaces.ts index 659e0ca0..e407bdd8 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -136,6 +136,7 @@ export const NAMESPACES: NamespaceEntry[] = [ positional: 'message', // Nightshift agents only exist on Serverless Observability projects. flavors: ['serverless'], + experimental: { label: 'nightshift ask' }, ...(target !== undefined ? { target } : {}), }) return defineGroup( diff --git a/test/kb/preset.test.ts b/test/kb/preset.test.ts index e1742621..499098b3 100644 --- a/test/kb/preset.test.ts +++ b/test/kb/preset.test.ts @@ -8,6 +8,7 @@ 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' @@ -140,6 +141,73 @@ describe('buildKbPresetCommand', () => { ) }) + 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' } }, 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: {} } diff --git a/test/namespaces.test.ts b/test/namespaces.test.ts index 558e9b12..8cbde071 100644 --- a/test/namespaces.test.ts +++ b/test/namespaces.test.ts @@ -47,6 +47,7 @@ describe('nightshift namespace', () => { 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']) }) From 1c99454c8d50b94323cdfb18828f9721dd691899 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Wed, 4 Nov 2026 11:31:39 +0100 Subject: [PATCH 9/9] refactor: share the experimental warning between docs and nightshift commands Move the --accept-experimental option and the stderr warning into src/lib/experimental.ts and use it from docs ask, docs search and the Kibana preset. Warning text is unchanged; the three commands now share one --accept-experimental description. Co-authored-by: Cursor --- docs/cli/schema.json | 6 +-- src/docs/ask.ts | 24 ++++-------- src/docs/search.ts | 24 ++++-------- src/kb/register.ts | 27 +++---------- src/lib/experimental.ts | 43 +++++++++++++++++++++ src/namespaces.ts | 5 ++- test/kb/preset.test.ts | 2 +- test/lib/experimental.test.ts | 72 +++++++++++++++++++++++++++++++++++ 8 files changed, 143 insertions(+), 60 deletions(-) create mode 100644 src/lib/experimental.ts create mode 100644 test/lib/experimental.test.ts diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 07552e31..d624a331 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -120670,7 +120670,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", @@ -120719,7 +120719,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", @@ -120825,7 +120825,7 @@ "name": "accept-experimental", "type": "boolean", "required": false, - "summary": "Acknowledge that this command is experimental and may change significantly; suppresses the warning" + "summary": "Acknowledge that this command is experimental and may change or be removed; suppresses the warning" }, { "role": "flag", 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/kb/register.ts b/src/kb/register.ts index 194e4f8a..8b1dedd8 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -17,6 +17,8 @@ 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. @@ -62,16 +64,9 @@ export interface KbPresetOptions { flavors?: ReadonlyArray<'stack' | 'serverless'> /** * Marks the command experimental: it warns on stderr before sending the request unless - * `--accept-experimental` or `--json` is passed. `label` names the command in the warning. + * `--accept-experimental` or `--json` is passed. */ - experimental?: { label: string } -} - -function experimentalBanner (label: string, isTTY: boolean): string { - const text = - `Warning: "${label}" is experimental and subject to significant changes before it reaches a stable state.\n` + - ' Pass --accept-experimental to suppress this warning.\n\n' - return isTTY ? `\x1b[33m${text}\x1b[0m` : text + experimental?: ExperimentalNotice } /** @@ -123,20 +118,10 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand opts.target, { handler: async (parsed) => { - if (experimental != null && parsed.options['accept-experimental'] !== true && parsed.options['json'] !== true) { - process.stderr.write(experimentalBanner(experimental.label, process.stderr.isTTY === true)) - } + if (experimental != null) warnIfExperimental(parsed, experimental) return await handler({ ...parsed, input: { ...(parsed.input as Record | undefined), ...opts.fixed } }) }, - ...(experimental != null - ? { - options: [{ - long: 'accept-experimental', - type: 'boolean' as const, - description: 'Acknowledge that this command is experimental and may change significantly; suppresses the warning', - }], - } - : {}), + ...(experimental != null ? { options: [ACCEPT_EXPERIMENTAL_OPTION] } : {}), ...(positional != null ? { positionalArg: { 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 e407bdd8..52b98723 100644 --- a/src/namespaces.ts +++ b/src/namespaces.ts @@ -136,7 +136,10 @@ export const NAMESPACES: NamespaceEntry[] = [ positional: 'message', // Nightshift agents only exist on Serverless Observability projects. flavors: ['serverless'], - experimental: { label: 'nightshift ask' }, + experimental: { + label: 'nightshift ask', + status: 'subject to significant changes before it reaches a stable state', + }, ...(target !== undefined ? { target } : {}), }) return defineGroup( diff --git a/test/kb/preset.test.ts b/test/kb/preset.test.ts index 499098b3..c4c81b9d 100644 --- a/test/kb/preset.test.ts +++ b/test/kb/preset.test.ts @@ -146,7 +146,7 @@ describe('buildKbPresetCommand', () => { 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' } }, recordingDeps(sent)) + 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 } 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(), '') + }) +})