@ekanos/cli 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"validate.js","sourceRoot":"","sources":["../../src/commands/validate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAGlC,OAAO,EACL,cAAc,EACd,uBAAuB,EACvB,UAAU,GACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,UAAU,EACV,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAQ1D;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAe,EACf,IAAkB;;IAElB,MAAM,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAErC,MAAM,IAAI,GAAG,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IAE3D,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,EAAE,GAAG,QAAE,IAAI,CAAC,GAAG,mCAAI,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IACtE,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAE5B,MAAM,KAAK,GAA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U,CAAC,CAAC;QAC/C,OAAO,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACjD,CAAC,CAAC;SACD,MAAM,CACL,CAAC,KAAK,EAAgD,EAAE,CAAC,KAAK,KAAK,IAAI,CACxE,CAAC;IAEJ,MAAM,CAAC,cAAc,CAAC,GAAG,WAAW,CAAC;IACrC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,cAAc,EAAE,CAAC;QACvE,OAAO,CAAC,IAAI,GAAG,iBAAiB,cAAc,CAAC,UAAU,IAAI,CAAC;IAChE,CAAC;SAAM,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,OAAO,CAAC,IAAI;YACV,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;IAC9E,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC;IAC9B,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO;IAEtC,MAAM,QAAQ,GAAG,UAAU,CAAC,UAAU,CAAC;QACrC,CAAC,CAAC,WAAW;QACb,CAAC,CAAC,GAAG,UAAU,IAAI,WAAW,EAAE,CAAC;IACnC,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["import type { Finding } from '@ekanos/integration-schema';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { CliContext } from '../context';\nimport {\n acceptedKeysAt,\n extractUnrecognizedKeys,\n suggestKey,\n} from '../did-you-mean';\nimport { validationError } from '../errors';\nimport type { ExitCode } from '../exit-codes';\nimport { renderFindings } from '../findings-renderer';\nimport { loadProject } from '../project';\nimport { assertSchemaNotSkewed } from '../schema-skew';\nimport {\n ENCLOSING_NOTE,\n extractPathFromMessage,\n isRootPath,\n locateDotPath,\n} from '../source-locator';\nimport { pluralize } from '../ui';\nimport { announceUpdate, checkForUpdate } from '../update-notice';\nimport { collectAllFindings } from '../validate-findings';\n\nexport interface ValidateArgs {\n /** Project directory (contains ekanos.json). Defaults to cwd. */\n dir: string;\n env?: Record<string, string | undefined>;\n}\n\n/**\n * `validate` — parse the declaration with the REAL zod schemas from\n * `@ekanos/integration-schema` (never a reimplementation), gather structured\n * findings, and add project-level integrity checks (the vitest inline-SDK\n * check). Exit 0 with `findings: []` when clean; exit 3 when any error-severity\n * finding is present, with the findings carried in the envelope's `data`.\n *\n * The findings pass itself lives in `validate-findings.ts`, shared with\n * `publish` so the publish gate cannot drift from what validate checks.\n *\n * Runs the schema-skew gate FIRST, before anything else — see\n * `schema-skew.ts` for why a newer project schema than the CLI bundles makes\n * every finding below it unreliable.\n */\nexport async function runValidate(\n ctx: CliContext,\n args: ValidateArgs,\n): Promise<ExitCode> {\n const loaded = loadProject(args.dir);\n\n const skew = assertSchemaNotSkewed(ctx, loaded.projectDir);\n\n const notice = await checkForUpdate({ env: args.env ?? process.env });\n announceUpdate(ctx, notice);\n\n const slugs = loaded.integrations.map((i) => i.slug).join(', ');\n ctx.log(\n ctx.ui.dim(\n `Validating ${loaded.integrations.length} integration` +\n `${loaded.integrations.length === 1 ? '' : 's'} (${slugs})…`,\n ),\n );\n\n const findings = await collectAllFindings(loaded);\n enrichSchemaFindings(findings, loaded.projectDir);\n\n const errorCount = findings.filter((f) => f.severity === 'error').length;\n const data = {\n slug: loaded.primary.slug,\n integrations: loaded.integrations.map((i) => ({\n slug: i.slug,\n entry: i.entry,\n })),\n findings,\n ...(skew.status === 'project-older'\n ? {\n schemaSkew: {\n status: skew.status,\n cliSchemaVersion: skew.cliSchemaVersion,\n projectSchemaVersion: skew.projectSchemaVersion,\n },\n }\n : {}),\n ...(notice ? { toolchain: notice } : {}),\n };\n\n if (errorCount > 0) {\n // Render the shared findings block to stderr BEFORE the envelope\n // settles, human mode only — JSON mode already carries the exact same\n // findings in `data.findings` and must stay byte-identical. The closing\n // order is findings block -> short summary (via `ctx.fail`'s\n // `findingsSummary` option) -> next action: `log` doesn't care that the\n // context already settled, so it's safe to call after `fail`.\n if (!ctx.jsonMode) {\n renderFindings(ctx, findings, { cwd: loaded.projectDir });\n }\n\n const exitCode = ctx.fail(\n validationError(\n `${errorCount} validation finding${errorCount === 1 ? '' : 's'}.`,\n 'Resolve the error-severity findings in data.findings, then re-run ' +\n '\"ekanos validate\".',\n ),\n data,\n !ctx.jsonMode\n ? { findingsSummary: { command: 'ekanos validate', errorCount } }\n : undefined,\n );\n\n if (!ctx.jsonMode) {\n ctx.log(ctx.ui.nextAction('ekanos validate', 'after fixing, re-check'));\n }\n\n return exitCode;\n }\n\n const successLine = ctx.jsonMode\n ? `validate: OK — no findings for ${slugs}.`\n : ctx.ui.result({\n title: findings.length === 0 ? 'No findings' : 'Valid',\n tone: findings.length === 0 ? 'ok' : 'warn',\n rows: [\n ['Checked', loaded.integrations.map((i) => i.slug)],\n ...(findings.length > 0\n ? [\n [\n 'Findings',\n pluralize(findings.length, 'warning or note'),\n ] as const,\n ]\n : []),\n ],\n notes:\n findings.length > 0\n ? ['None are errors. Run with --json to read them.']\n : [],\n });\n\n return ctx.succeed(data, successLine);\n}\n\n/**\n * Best-effort dot-path → `file:line` + \"did you mean?\" enrichment for\n * `definition.schema` findings — the ones `collectDefinitionFindings` builds\n * directly from a zod issue (see its doc comment in\n * `@ekanos/integration-schema`). Mutates `line` (already part of `Finding`'s\n * shape, just usually absent) and, for an unrecognized key with a close\n * match, `hint`; for a resolved-but-missing key it appends a plain-text (no\n * ANSI — `findings-renderer.ts` styles it at render time) note to `message`.\n * These are additive changes to `data.findings` in `--json` mode too — the\n * envelope's existing fields never change shape or disappear across a minor\n * release, so a partner's own JSON parsing keeps working; only new optional\n * fields are ever added.\n *\n * Every other finding, and every locator miss, passes through unchanged:\n * `source-locator.ts`'s whole design is to never guess, so a miss here is\n * silent, not an error.\n */\nfunction enrichSchemaFindings(findings: Finding[], projectDir: string): void {\n const sourceCache = new Map<string, string | null>();\n\n const readSource = (file: string): string | null => {\n const cached = sourceCache.get(file);\n if (cached !== undefined) return cached;\n\n let text: string | null;\n try {\n text = fs.readFileSync(path.resolve(projectDir, file), 'utf8');\n } catch {\n // Best-effort — an unreadable file (deleted, permissions, a race with\n // a concurrent edit) just means no enrichment, never a validate\n // failure.\n text = null;\n }\n sourceCache.set(file, text);\n return text;\n };\n\n for (const finding of findings) {\n if (finding.check !== 'definition.schema') continue;\n if (finding.line !== undefined || finding.file === undefined) continue;\n\n const parsed = extractPathFromMessage(finding.message);\n if (!parsed) continue;\n\n const source = readSource(finding.file);\n if (source === null) continue;\n\n const unrecognizedKeys = extractUnrecognizedKeys(parsed.rest);\n if (unrecognizedKeys) {\n applyUnrecognizedKeyEnrichment(\n finding,\n source,\n parsed.path,\n unrecognizedKeys,\n );\n continue;\n }\n\n applyLocation(finding, locateDotPath(source, parsed.path));\n }\n}\n\n/** Sets `line`/`message` from a locate result — shared by the plain schema-path case and the unrecognized-key case below. A `'none'` result changes nothing. */\nfunction applyLocation(\n finding: Finding,\n result: ReturnType<typeof locateDotPath>,\n): void {\n if (result.confidence === 'none') return;\n\n finding.line = result.line;\n if (result.confidence === 'enclosing') {\n finding.message = `${finding.message} ${ENCLOSING_NOTE}`;\n }\n}\n\nfunction applyUnrecognizedKeyEnrichment(\n finding: Finding,\n source: string,\n parentPath: string,\n badKeys: string[],\n): void {\n const candidates = acceptedKeysAt(parentPath);\n const suggestions = badKeys\n .map((bad) => {\n const suggestion = suggestKey(bad, candidates);\n return suggestion ? { bad, suggestion } : null;\n })\n .filter(\n (entry): entry is { bad: string; suggestion: string } => entry !== null,\n );\n\n const [onlySuggestion] = suggestions;\n if (suggestions.length === 1 && badKeys.length === 1 && onlySuggestion) {\n finding.hint = `did you mean \"${onlySuggestion.suggestion}\"?`;\n } else if (suggestions.length > 0) {\n finding.hint =\n suggestions.map((s) => `\"${s.bad}\" → \"${s.suggestion}\"`).join(', ') + '?';\n }\n\n const [firstBadKey] = badKeys;\n if (firstBadKey === undefined) return;\n\n const fullPath = isRootPath(parentPath)\n ? firstBadKey\n : `${parentPath}.${firstBadKey}`;\n applyLocation(finding, locateDotPath(source, fullPath));\n}\n"]}
1
+ {"version":3,"file":"validate.js","sourceRoot":"","sources":["../../src/commands/validate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAGlC,OAAO,EACL,cAAc,EACd,uBAAuB,EACvB,UAAU,GACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,UAAU,EACV,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAQ1D;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAe,EACf,IAAkB;;IAElB,MAAM,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAErC,MAAM,IAAI,GAAG,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IAE3D,MAAM,MAAM,GAAG,MAAM,cAAc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D,CAAC","sourcesContent":["import type { Finding } from '@ekanos/integration-schema';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { CliContext } from '../context';\nimport {\n acceptedKeysAt,\n extractUnrecognizedKeys,\n suggestKey,\n} from '../did-you-mean';\nimport { validationError } from '../errors';\nimport type { ExitCode } from '../exit-codes';\nimport { renderFindings } from '../findings-renderer';\nimport { loadProject } from '../project';\nimport { assertSchemaNotSkewed } from '../schema-skew';\nimport {\n ENCLOSING_NOTE,\n extractPathFromMessage,\n isRootPath,\n locateDotPath,\n} from '../source-locator';\nimport { pluralize } from '../ui';\nimport { announceUpdate, checkForUpdate } from '../update-notice';\nimport { collectAllFindings } from '../validate-findings';\n\nexport interface ValidateArgs {\n /** Project directory (contains ekanos.json). Defaults to cwd. */\n dir: string;\n env?: Record<string, string | undefined>;\n}\n\n/**\n * `validate` — parse the declaration with the REAL zod schemas from\n * `@ekanos/integration-schema` (never a reimplementation), gather structured\n * findings, and add project-level integrity checks (the vitest inline-SDK\n * check). Exit 0 with `findings: []` when clean; exit 3 when any error-severity\n * finding is present, with the findings carried in the envelope's `data`.\n *\n * The findings pass itself lives in `validate-findings.ts`, shared with\n * `publish` so the publish gate cannot drift from what validate checks.\n *\n * Runs the schema-skew gate FIRST, before anything else — see\n * `schema-skew.ts` for why a newer project schema than the CLI bundles makes\n * every finding below it unreliable.\n */\nexport async function runValidate(\n ctx: CliContext,\n args: ValidateArgs,\n): Promise<ExitCode> {\n const loaded = loadProject(args.dir);\n\n const skew = assertSchemaNotSkewed(ctx, loaded.projectDir);\n\n const notice = await checkForUpdate({ env: args.env ?? process.env });\n announceUpdate(ctx, notice, { env: args.env ?? process.env });\n\n const slugs = loaded.integrations.map((i) => i.slug).join(', ');\n ctx.log(\n ctx.ui.dim(\n `Validating ${loaded.integrations.length} integration` +\n `${loaded.integrations.length === 1 ? '' : 's'} (${slugs})…`,\n ),\n );\n\n const findings = await collectAllFindings(loaded);\n enrichSchemaFindings(findings, loaded.projectDir);\n\n const errorCount = findings.filter((f) => f.severity === 'error').length;\n const data = {\n slug: loaded.primary.slug,\n integrations: loaded.integrations.map((i) => ({\n slug: i.slug,\n entry: i.entry,\n })),\n findings,\n ...(skew.status === 'project-older'\n ? {\n schemaSkew: {\n status: skew.status,\n cliSchemaVersion: skew.cliSchemaVersion,\n projectSchemaVersion: skew.projectSchemaVersion,\n },\n }\n : {}),\n ...(notice ? { toolchain: notice } : {}),\n };\n\n if (errorCount > 0) {\n // Render the shared findings block to stderr BEFORE the envelope\n // settles, human mode only — JSON mode already carries the exact same\n // findings in `data.findings` and must stay byte-identical. The closing\n // order is findings block -> short summary (via `ctx.fail`'s\n // `findingsSummary` option) -> next action: `log` doesn't care that the\n // context already settled, so it's safe to call after `fail`.\n if (!ctx.jsonMode) {\n renderFindings(ctx, findings, { cwd: loaded.projectDir });\n }\n\n const exitCode = ctx.fail(\n validationError(\n `${errorCount} validation finding${errorCount === 1 ? '' : 's'}.`,\n 'Resolve the error-severity findings in data.findings, then re-run ' +\n '\"ekanos validate\".',\n ),\n data,\n !ctx.jsonMode\n ? { findingsSummary: { command: 'ekanos validate', errorCount } }\n : undefined,\n );\n\n if (!ctx.jsonMode) {\n ctx.log(ctx.ui.nextAction('ekanos validate', 'after fixing, re-check'));\n }\n\n return exitCode;\n }\n\n const successLine = ctx.jsonMode\n ? `validate: OK — no findings for ${slugs}.`\n : ctx.ui.result({\n title: findings.length === 0 ? 'No findings' : 'Valid',\n tone: findings.length === 0 ? 'ok' : 'warn',\n rows: [\n ['Checked', loaded.integrations.map((i) => i.slug)],\n ...(findings.length > 0\n ? [\n [\n 'Findings',\n pluralize(findings.length, 'warning or note'),\n ] as const,\n ]\n : []),\n ],\n notes:\n findings.length > 0\n ? ['None are errors. Run with --json to read them.']\n : [],\n });\n\n return ctx.succeed(data, successLine);\n}\n\n/**\n * Best-effort dot-path → `file:line` + \"did you mean?\" enrichment for\n * `definition.schema` findings — the ones `collectDefinitionFindings` builds\n * directly from a zod issue (see its doc comment in\n * `@ekanos/integration-schema`). Mutates `line` (already part of `Finding`'s\n * shape, just usually absent) and, for an unrecognized key with a close\n * match, `hint`; for a resolved-but-missing key it appends a plain-text (no\n * ANSI — `findings-renderer.ts` styles it at render time) note to `message`.\n * These are additive changes to `data.findings` in `--json` mode too — the\n * envelope's existing fields never change shape or disappear across a minor\n * release, so a partner's own JSON parsing keeps working; only new optional\n * fields are ever added.\n *\n * Every other finding, and every locator miss, passes through unchanged:\n * `source-locator.ts`'s whole design is to never guess, so a miss here is\n * silent, not an error.\n */\nfunction enrichSchemaFindings(findings: Finding[], projectDir: string): void {\n const sourceCache = new Map<string, string | null>();\n\n const readSource = (file: string): string | null => {\n const cached = sourceCache.get(file);\n if (cached !== undefined) return cached;\n\n let text: string | null;\n try {\n text = fs.readFileSync(path.resolve(projectDir, file), 'utf8');\n } catch {\n // Best-effort — an unreadable file (deleted, permissions, a race with\n // a concurrent edit) just means no enrichment, never a validate\n // failure.\n text = null;\n }\n sourceCache.set(file, text);\n return text;\n };\n\n for (const finding of findings) {\n if (finding.check !== 'definition.schema') continue;\n if (finding.line !== undefined || finding.file === undefined) continue;\n\n const parsed = extractPathFromMessage(finding.message);\n if (!parsed) continue;\n\n const source = readSource(finding.file);\n if (source === null) continue;\n\n const unrecognizedKeys = extractUnrecognizedKeys(parsed.rest);\n if (unrecognizedKeys) {\n applyUnrecognizedKeyEnrichment(\n finding,\n source,\n parsed.path,\n unrecognizedKeys,\n );\n continue;\n }\n\n applyLocation(finding, locateDotPath(source, parsed.path));\n }\n}\n\n/** Sets `line`/`message` from a locate result — shared by the plain schema-path case and the unrecognized-key case below. A `'none'` result changes nothing. */\nfunction applyLocation(\n finding: Finding,\n result: ReturnType<typeof locateDotPath>,\n): void {\n if (result.confidence === 'none') return;\n\n finding.line = result.line;\n if (result.confidence === 'enclosing') {\n finding.message = `${finding.message} ${ENCLOSING_NOTE}`;\n }\n}\n\nfunction applyUnrecognizedKeyEnrichment(\n finding: Finding,\n source: string,\n parentPath: string,\n badKeys: string[],\n): void {\n const candidates = acceptedKeysAt(parentPath);\n const suggestions = badKeys\n .map((bad) => {\n const suggestion = suggestKey(bad, candidates);\n return suggestion ? { bad, suggestion } : null;\n })\n .filter(\n (entry): entry is { bad: string; suggestion: string } => entry !== null,\n );\n\n const [onlySuggestion] = suggestions;\n if (suggestions.length === 1 && badKeys.length === 1 && onlySuggestion) {\n finding.hint = `did you mean \"${onlySuggestion.suggestion}\"?`;\n } else if (suggestions.length > 0) {\n finding.hint =\n suggestions.map((s) => `\"${s.bad}\" → \"${s.suggestion}\"`).join(', ') + '?';\n }\n\n const [firstBadKey] = badKeys;\n if (firstBadKey === undefined) return;\n\n const fullPath = isRootPath(parentPath)\n ? firstBadKey\n : `${parentPath}.${firstBadKey}`;\n applyLocation(finding, locateDotPath(source, fullPath));\n}\n"]}
package/dist/context.d.ts CHANGED
@@ -102,7 +102,7 @@ export declare class CliContext {
102
102
  * an unknown command so an agent reading stderr is told what to do next
103
103
  * without the line ever touching stdout.
104
104
  */
105
- emitClaudeCodeHint(payload: Record<string, unknown>): void;
105
+ emitClaudeCodeHint(payload: Record<string, unknown>): boolean;
106
106
  /**
107
107
  * Terminal success. Writes the single stdout object (JSON mode) or a concise
108
108
  * human line (human mode). Returns the OK exit code so the caller can end the
package/dist/context.js CHANGED
@@ -85,8 +85,9 @@ export class CliContext {
85
85
  // at a terminal, or piping into `less` or `grep` — gets the readable
86
86
  // error or help text, never a line of JSON above it.
87
87
  if (!this.explicitJson && !this.agentDetected)
88
- return;
88
+ return false;
89
89
  this.stderr.write(`claude-code-hint: ${JSON.stringify(payload)}\n`);
90
+ return true;
90
91
  }
91
92
  /**
92
93
  * Terminal success. Writes the single stdout object (JSON mode) or a concise
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAiB,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE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,IAAI,IAAI,CAAC,CAAC;YAChE,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC,QAAQ,CAAC;IACzB,CAAC;IAEO,MAAM;QACZ,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CACb,8DAA8D;gBAC5D,mEAAmE;gBACnE,wCAAwC,CAC3C,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,GAAiD;IAEjD,OAAO,CACL,GAAG,CAAC,UAAU,KAAK,GAAG;QACtB,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;QAC1B,GAAG,CAAC,YAAY,KAAK,GAAG;QACxB,GAAG,CAAC,UAAU,KAAK,GAAG;QACtB,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CACtB,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,MAA0B;IAC/C,OAAO;QACL,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE;YACvB,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { CliError } from './errors';\nimport { EXIT_CODES, type ExitCode } from './exit-codes';\nimport { echoInvocation } from './invocation';\nimport { type Ui, createUi } from './ui';\n\n/**\n * A single writable sink. Real streams satisfy this; tests pass a capturing\n * buffer so the stdout-purity invariant can be asserted byte-for-byte.\n */\nexport interface WriteStream {\n write(chunk: string): void;\n isTTY?: boolean;\n}\n\nexport interface ContextInput {\n /**\n * The user's EXPLICIT preference, already parsed: `true` for `--json`,\n * `false` for `--no-json`, `undefined` when neither was passed. The\n * undefined case is what allows the mode to be inferred instead.\n */\n jsonFlag?: boolean;\n stdout?: WriteStream;\n stderr?: WriteStream;\n /** Overrides process.env for CLAUDECODE detection (tests). */\n env?: Record<string, string | undefined>;\n}\n\n/** The success envelope. */\ninterface OkEnvelope {\n ok: true;\n data: unknown;\n}\n\n/** The error envelope. `data` is optional — validate carries its findings here. */\ninterface ErrEnvelope {\n ok: false;\n data?: unknown;\n error: { code: string; message: string; hint: string; docs?: string };\n}\n\n/** See `fail`'s doc comment — the human-mode epilogue seam for a command that already rendered a findings block. */\ninterface FindingsSummary {\n /** The command name to name in the summary line, e.g. \"ekanos validate\". */\n command: string;\n errorCount: number;\n}\n\nexport interface FailOptions {\n findingsSummary?: FindingsSummary;\n}\n\n/**\n * `data` is deliberately `unknown` above — each verb owns its own shape — but\n * one convention spans several of them: `validate`, `dev`, `publish` and\n * `status` all add an OPTIONAL `toolchain` field to `data` (never to the\n * envelope's top level) when the proactive update check in `update-notice.ts`\n * finds this CLI is behind. See that file's `ToolchainNoticeData` for the\n * shape, and `README.md`'s \"Keeping the toolchain current\" section for the\n * full contract. It is absent, not `null`, when there is nothing to report.\n */\n\n/**\n * The agent-native output envelope, resolved ONCE at startup and threaded\n * through every command.\n *\n * The load-bearing invariant: in JSON mode, stdout receives EXACTLY ONE JSON\n * object for the whole process — nothing else, ever. Every progress line, warn,\n * and scrap of human prose goes to stderr. This is the single most common way\n * an agent's tool call breaks (a stray log line on stdout makes the JSON\n * unparseable), so the context enforces it structurally: `succeed`/`fail` are\n * the only writers of stdout, and a `settled` latch makes a second call throw\n * rather than emit a second object.\n */\nexport class CliContext {\n readonly jsonMode: boolean;\n /**\n * The environment the context resolved against — exposed so decoration\n * (the gradient banner) can honour `NO_COLOR` / `EKANOS_NO_BANNER` without\n * every call site threading `process.env` through by hand.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /**\n * The style layer (`ui.ts`), resolved once against stderr — the stream\n * every human-mode render target uses — so every command shares one color\n * decision instead of each re-deriving it. See `ui.ts` for the tokens and\n * components this carries.\n */\n readonly ui: Ui;\n /** A coding agent's marker is in the environment (`isAgentEnvironment`). */\n readonly agentDetected: boolean;\n /** `--json` was passed — not inferred from a pipe. */\n private readonly explicitJson: boolean;\n private readonly stdout: WriteStream;\n private readonly stderr: WriteStream;\n private settled = false;\n private failed: { code: string; exitCode: number } | null = null;\n\n constructor(input: ContextInput = {}) {\n const stdout = input.stdout ?? defaultStream(process.stdout);\n const stderr = input.stderr ?? defaultStream(process.stderr);\n const env = input.env ?? process.env;\n\n this.stdout = stdout;\n this.stderr = stderr;\n this.env = env;\n this.ui = createUi({ isTTY: stderr.isTTY === true, env });\n\n // Resolve JSON mode once. An EXPLICIT flag always wins: `--json` forces the\n // envelope on even at a terminal, `--no-json` forces the human form even\n // when piped. Only when the user expressed no preference is the mode\n // inferred — from a non-TTY stdout (piped into another program or an agent)\n // or the CLAUDECODE marker.\n const nonTty = stdout.isTTY !== true;\n this.jsonMode = input.jsonFlag ?? (nonTty || env.CLAUDECODE === '1');\n this.explicitJson = input.jsonFlag === true;\n this.agentDetected = isAgentEnvironment(env);\n }\n\n /**\n * The code and exit code this run failed with, once it has — what a\n * recorded failure (`last-error.ts`) and the report hint name. Null on\n * success or before the run settles.\n */\n get failure(): { code: string; exitCode: number } | null {\n return this.failed;\n }\n\n /** Whether stderr is a real terminal — decoration (the banner) gates on this. */\n get stderrIsTTY(): boolean {\n return this.stderr.isTTY === true;\n }\n\n /**\n * Whether stdout is a real terminal — `wizard.ts`'s `canWizard` gates on\n * this (clack renders to stdout, unlike the rest of this CLI's human\n * output). `ctx.jsonMode` being false does not by itself guarantee this:\n * `--no-json` forces human mode even against a piped stdout.\n */\n get stdoutIsTTY(): boolean {\n return this.stdout.isTTY === true;\n }\n\n /** Human/progress output — ALWAYS stderr, so stdout stays pure in JSON mode. */\n log(message: string): void {\n this.stderr.write(`${echoInvocation(message)}\\n`);\n }\n\n /** A warning — stderr, no ANSI. */\n warn(message: string): void {\n this.stderr.write(`${echoInvocation(message)}\\n`);\n }\n\n /**\n * Emit the `claude-code-hint` protocol line to STDERR. Used on --help and on\n * an unknown command so an agent reading stderr is told what to do next\n * without the line ever touching stdout.\n */\n emitClaudeCodeHint(payload: Record<string, unknown>): void {\n // The protocol line is machine-readable JSON for an agent reading\n // stderr. It is written only when an agent is known to be reading: one\n // was detected in the environment, or `--json` was asked for. A person —\n // at a terminal, or piping into `less` or `grep` — gets the readable\n // error or help text, never a line of JSON above it.\n if (!this.explicitJson && !this.agentDetected) return;\n\n this.stderr.write(`claude-code-hint: ${JSON.stringify(payload)}\\n`);\n }\n\n /**\n * Terminal success. Writes the single stdout object (JSON mode) or a concise\n * human line (human mode). Returns the OK exit code so the caller can end the\n * process with it. Idempotent-by-latch: a second settle throws.\n */\n succeed(data: unknown, humanSummary?: string): ExitCode {\n this.settle();\n if (this.jsonMode) {\n const envelope: OkEnvelope = { ok: true, data };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else if (humanSummary !== '') {\n // An explicit empty summary means \"already said it\" — a wizard flow's\n // outro is the result, and a trailing line would just repeat it.\n this.stdout.write(`${echoInvocation(humanSummary ?? 'OK')}\\n`);\n }\n return EXIT_CODES.OK;\n }\n\n /**\n * Terminal failure. Writes the single stdout error object (JSON mode) or the\n * message + hint to stderr (human mode). Returns the error's exit code.\n *\n * `error.hint` is guaranteed non-empty by CliError's constructor, so the\n * envelope's \"every error carries a hint\" invariant holds for every path\n * that reaches here.\n *\n * `options.findingsSummary` is the seam for a command that has ALREADY\n * rendered the shared findings block to stderr (human mode) before calling\n * this — `validate`'s and `publish`'s gate-refusal paths. Passing it swaps\n * the default two-line `Error: … / Hint: …` epilogue (whose hint always\n * points at the JSON-only `data.findings`) for one short summary line,\n * `✖ <command> failed: <n> error(s)`, so a partner never reads the same\n * finding jargon twice. JSON mode is completely unaffected either way —\n * `error.hint` always carries the original, JSON-only-appropriate text in\n * the envelope.\n */\n fail(error: CliError, data?: unknown, options?: FailOptions): ExitCode {\n this.failWith({\n code: error.code,\n message: error.message,\n hint: error.hint,\n docs: error.docs,\n exitCode: error.exitCode,\n data,\n findingsSummary: options?.findingsSummary,\n });\n return error.exitCode;\n }\n\n /**\n * The low-level failure emitter. Used directly by `test`, whose exit code is\n * a TRANSPARENT passthrough of the delegated runner's exit code (which is not\n * one of the CLI's own frozen numeric conditions) and whose error `code` is\n * an out-of-taxonomy string. Enforces the same non-empty-hint invariant as\n * CliError so no failure path can emit an empty hint.\n */\n failWith(params: {\n code: string;\n message: string;\n hint: string;\n /** A docs URL for this error; JSON gets a `docs` field, human mode a line. */\n docs?: string;\n exitCode: number;\n data?: unknown;\n findingsSummary?: FindingsSummary;\n }): number {\n this.settle();\n this.failed = { code: params.code, exitCode: params.exitCode };\n if (!params.hint || params.hint.trim().length === 0) {\n throw new Error(\n `failWith for \"${params.message}\" was given an empty hint. Every CLI ` +\n 'error must carry an imperative remediation.',\n );\n }\n // The commands a hint names, as this run was invoked (`invocation.ts`).\n const message = echoInvocation(params.message);\n const hint = echoInvocation(params.hint);\n if (this.jsonMode) {\n const envelope: ErrEnvelope = {\n ok: false,\n ...(params.data !== undefined ? { data: params.data } : {}),\n error: {\n code: params.code,\n message,\n hint,\n ...(params.docs ? { docs: params.docs } : {}),\n },\n };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else if (params.findingsSummary) {\n const { command, errorCount } = params.findingsSummary;\n this.stderr.write(\n `${this.ui.err(\n `${this.ui.glyphs.err} ${command} failed: ${errorCount} error${\n errorCount === 1 ? '' : 's'\n }`,\n )}\\n`,\n );\n } else {\n this.stderr.write(`${this.ui.err('Error:')} ${message}\\n`);\n this.stderr.write(`${this.ui.dim('Hint:')} ${hint}\\n`);\n if (params.docs) {\n this.stderr.write(`${this.ui.dim('Docs:')} ${params.docs}\\n`);\n }\n }\n return params.exitCode;\n }\n\n private settle(): void {\n if (this.settled) {\n throw new Error(\n 'CliContext settled twice — a command tried to emit a second ' +\n 'terminal result. In JSON mode this would corrupt stdout with two ' +\n 'objects. This is a bug in the command.',\n );\n }\n this.settled = true;\n }\n}\n\n/**\n * The environment markers coding agents set in the shells they run:\n * Claude Code (`CLAUDECODE=1`), Codex (`CODEX_SANDBOX`), Cursor's agent\n * (`CURSOR_AGENT=1`), Gemini CLI (`GEMINI_CLI=1`), and the generic\n * `AI_AGENT`. A pipe alone is not one — a person piping into `grep` is not\n * an agent.\n */\nexport function isAgentEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n): boolean {\n return (\n env.CLAUDECODE === '1' ||\n Boolean(env.CODEX_SANDBOX) ||\n env.CURSOR_AGENT === '1' ||\n env.GEMINI_CLI === '1' ||\n Boolean(env.AI_AGENT)\n );\n}\n\nfunction defaultStream(stream: NodeJS.WriteStream): WriteStream {\n return {\n write: (chunk: string) => {\n stream.write(chunk);\n },\n isTTY: stream.isTTY,\n };\n}\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAiB,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAW,QAAQ,EAAE,MAAM,MAAM,CAAC;AAgDzC;;;;;;;;GAQG;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,UAAU;IAwBrB,YAAY,KAAK,GAAiB,EAAE;;QAH5B,YAAO,GAAG,KAAK,CAAC;QAChB,WAAM,GAA8C,IAAI,CAAC;QAG/D,MAAM,MAAM,SAAG,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,MAAM,SAAG,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,GAAG,SAAG,KAAK,CAAC,GAAG,mCAAI,OAAO,CAAC,GAAG,CAAC;QAErC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,EAAE,GAAG,QAAQ,CAAC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AO;QACL,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE;YACvB,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { CliError } from './errors';\nimport { EXIT_CODES, type ExitCode } from './exit-codes';\nimport { echoInvocation } from './invocation';\nimport { type Ui, createUi } from './ui';\n\n/**\n * A single writable sink. Real streams satisfy this; tests pass a capturing\n * buffer so the stdout-purity invariant can be asserted byte-for-byte.\n */\nexport interface WriteStream {\n write(chunk: string): void;\n isTTY?: boolean;\n}\n\nexport interface ContextInput {\n /**\n * The user's EXPLICIT preference, already parsed: `true` for `--json`,\n * `false` for `--no-json`, `undefined` when neither was passed. The\n * undefined case is what allows the mode to be inferred instead.\n */\n jsonFlag?: boolean;\n stdout?: WriteStream;\n stderr?: WriteStream;\n /** Overrides process.env for CLAUDECODE detection (tests). */\n env?: Record<string, string | undefined>;\n}\n\n/** The success envelope. */\ninterface OkEnvelope {\n ok: true;\n data: unknown;\n}\n\n/** The error envelope. `data` is optional — validate carries its findings here. */\ninterface ErrEnvelope {\n ok: false;\n data?: unknown;\n error: { code: string; message: string; hint: string; docs?: string };\n}\n\n/** See `fail`'s doc comment — the human-mode epilogue seam for a command that already rendered a findings block. */\ninterface FindingsSummary {\n /** The command name to name in the summary line, e.g. \"ekanos validate\". */\n command: string;\n errorCount: number;\n}\n\nexport interface FailOptions {\n findingsSummary?: FindingsSummary;\n}\n\n/**\n * `data` is deliberately `unknown` above — each verb owns its own shape — but\n * one convention spans several of them: `validate`, `dev`, `publish` and\n * `status` all add an OPTIONAL `toolchain` field to `data` (never to the\n * envelope's top level) when the proactive update check in `update-notice.ts`\n * finds this CLI is behind. See that file's `ToolchainNoticeData` for the\n * shape, and `README.md`'s \"Keeping the toolchain current\" section for the\n * full contract. It is absent, not `null`, when there is nothing to report.\n */\n\n/**\n * The agent-native output envelope, resolved ONCE at startup and threaded\n * through every command.\n *\n * The load-bearing invariant: in JSON mode, stdout receives EXACTLY ONE JSON\n * object for the whole process — nothing else, ever. Every progress line, warn,\n * and scrap of human prose goes to stderr. This is the single most common way\n * an agent's tool call breaks (a stray log line on stdout makes the JSON\n * unparseable), so the context enforces it structurally: `succeed`/`fail` are\n * the only writers of stdout, and a `settled` latch makes a second call throw\n * rather than emit a second object.\n */\nexport class CliContext {\n readonly jsonMode: boolean;\n /**\n * The environment the context resolved against — exposed so decoration\n * (the gradient banner) can honour `NO_COLOR` / `EKANOS_NO_BANNER` without\n * every call site threading `process.env` through by hand.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /**\n * The style layer (`ui.ts`), resolved once against stderr — the stream\n * every human-mode render target uses — so every command shares one color\n * decision instead of each re-deriving it. See `ui.ts` for the tokens and\n * components this carries.\n */\n readonly ui: Ui;\n /** A coding agent's marker is in the environment (`isAgentEnvironment`). */\n readonly agentDetected: boolean;\n /** `--json` was passed — not inferred from a pipe. */\n private readonly explicitJson: boolean;\n private readonly stdout: WriteStream;\n private readonly stderr: WriteStream;\n private settled = false;\n private failed: { code: string; exitCode: number } | null = null;\n\n constructor(input: ContextInput = {}) {\n const stdout = input.stdout ?? defaultStream(process.stdout);\n const stderr = input.stderr ?? defaultStream(process.stderr);\n const env = input.env ?? process.env;\n\n this.stdout = stdout;\n this.stderr = stderr;\n this.env = env;\n this.ui = createUi({ isTTY: stderr.isTTY === true, env });\n\n // Resolve JSON mode once. An EXPLICIT flag always wins: `--json` forces the\n // envelope on even at a terminal, `--no-json` forces the human form even\n // when piped. Only when the user expressed no preference is the mode\n // inferred — from a non-TTY stdout (piped into another program or an agent)\n // or the CLAUDECODE marker.\n const nonTty = stdout.isTTY !== true;\n this.jsonMode = input.jsonFlag ?? (nonTty || env.CLAUDECODE === '1');\n this.explicitJson = input.jsonFlag === true;\n this.agentDetected = isAgentEnvironment(env);\n }\n\n /**\n * The code and exit code this run failed with, once it has — what a\n * recorded failure (`last-error.ts`) and the report hint name. Null on\n * success or before the run settles.\n */\n get failure(): { code: string; exitCode: number } | null {\n return this.failed;\n }\n\n /** Whether stderr is a real terminal — decoration (the banner) gates on this. */\n get stderrIsTTY(): boolean {\n return this.stderr.isTTY === true;\n }\n\n /**\n * Whether stdout is a real terminal — `wizard.ts`'s `canWizard` gates on\n * this (clack renders to stdout, unlike the rest of this CLI's human\n * output). `ctx.jsonMode` being false does not by itself guarantee this:\n * `--no-json` forces human mode even against a piped stdout.\n */\n get stdoutIsTTY(): boolean {\n return this.stdout.isTTY === true;\n }\n\n /** Human/progress output — ALWAYS stderr, so stdout stays pure in JSON mode. */\n log(message: string): void {\n this.stderr.write(`${echoInvocation(message)}\\n`);\n }\n\n /** A warning — stderr, no ANSI. */\n warn(message: string): void {\n this.stderr.write(`${echoInvocation(message)}\\n`);\n }\n\n /**\n * Emit the `claude-code-hint` protocol line to STDERR. Used on --help and on\n * an unknown command so an agent reading stderr is told what to do next\n * without the line ever touching stdout.\n */\n emitClaudeCodeHint(payload: Record<string, unknown>): boolean {\n // The protocol line is machine-readable JSON for an agent reading\n // stderr. It is written only when an agent is known to be reading: one\n // was detected in the environment, or `--json` was asked for. A person —\n // at a terminal, or piping into `less` or `grep` — gets the readable\n // error or help text, never a line of JSON above it.\n if (!this.explicitJson && !this.agentDetected) return false;\n\n this.stderr.write(`claude-code-hint: ${JSON.stringify(payload)}\\n`);\n return true;\n }\n\n /**\n * Terminal success. Writes the single stdout object (JSON mode) or a concise\n * human line (human mode). Returns the OK exit code so the caller can end the\n * process with it. Idempotent-by-latch: a second settle throws.\n */\n succeed(data: unknown, humanSummary?: string): ExitCode {\n this.settle();\n if (this.jsonMode) {\n const envelope: OkEnvelope = { ok: true, data };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else if (humanSummary !== '') {\n // An explicit empty summary means \"already said it\" — a wizard flow's\n // outro is the result, and a trailing line would just repeat it.\n this.stdout.write(`${echoInvocation(humanSummary ?? 'OK')}\\n`);\n }\n return EXIT_CODES.OK;\n }\n\n /**\n * Terminal failure. Writes the single stdout error object (JSON mode) or the\n * message + hint to stderr (human mode). Returns the error's exit code.\n *\n * `error.hint` is guaranteed non-empty by CliError's constructor, so the\n * envelope's \"every error carries a hint\" invariant holds for every path\n * that reaches here.\n *\n * `options.findingsSummary` is the seam for a command that has ALREADY\n * rendered the shared findings block to stderr (human mode) before calling\n * this — `validate`'s and `publish`'s gate-refusal paths. Passing it swaps\n * the default two-line `Error: … / Hint: …` epilogue (whose hint always\n * points at the JSON-only `data.findings`) for one short summary line,\n * `✖ <command> failed: <n> error(s)`, so a partner never reads the same\n * finding jargon twice. JSON mode is completely unaffected either way —\n * `error.hint` always carries the original, JSON-only-appropriate text in\n * the envelope.\n */\n fail(error: CliError, data?: unknown, options?: FailOptions): ExitCode {\n this.failWith({\n code: error.code,\n message: error.message,\n hint: error.hint,\n docs: error.docs,\n exitCode: error.exitCode,\n data,\n findingsSummary: options?.findingsSummary,\n });\n return error.exitCode;\n }\n\n /**\n * The low-level failure emitter. Used directly by `test`, whose exit code is\n * a TRANSPARENT passthrough of the delegated runner's exit code (which is not\n * one of the CLI's own frozen numeric conditions) and whose error `code` is\n * an out-of-taxonomy string. Enforces the same non-empty-hint invariant as\n * CliError so no failure path can emit an empty hint.\n */\n failWith(params: {\n code: string;\n message: string;\n hint: string;\n /** A docs URL for this error; JSON gets a `docs` field, human mode a line. */\n docs?: string;\n exitCode: number;\n data?: unknown;\n findingsSummary?: FindingsSummary;\n }): number {\n this.settle();\n this.failed = { code: params.code, exitCode: params.exitCode };\n if (!params.hint || params.hint.trim().length === 0) {\n throw new Error(\n `failWith for \"${params.message}\" was given an empty hint. Every CLI ` +\n 'error must carry an imperative remediation.',\n );\n }\n // The commands a hint names, as this run was invoked (`invocation.ts`).\n const message = echoInvocation(params.message);\n const hint = echoInvocation(params.hint);\n if (this.jsonMode) {\n const envelope: ErrEnvelope = {\n ok: false,\n ...(params.data !== undefined ? { data: params.data } : {}),\n error: {\n code: params.code,\n message,\n hint,\n ...(params.docs ? { docs: params.docs } : {}),\n },\n };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else if (params.findingsSummary) {\n const { command, errorCount } = params.findingsSummary;\n this.stderr.write(\n `${this.ui.err(\n `${this.ui.glyphs.err} ${command} failed: ${errorCount} error${\n errorCount === 1 ? '' : 's'\n }`,\n )}\\n`,\n );\n } else {\n this.stderr.write(`${this.ui.err('Error:')} ${message}\\n`);\n this.stderr.write(`${this.ui.dim('Hint:')} ${hint}\\n`);\n if (params.docs) {\n this.stderr.write(`${this.ui.dim('Docs:')} ${params.docs}\\n`);\n }\n }\n return params.exitCode;\n }\n\n private settle(): void {\n if (this.settled) {\n throw new Error(\n 'CliContext settled twice — a command tried to emit a second ' +\n 'terminal result. In JSON mode this would corrupt stdout with two ' +\n 'objects. This is a bug in the command.',\n );\n }\n this.settled = true;\n }\n}\n\n/**\n * The environment markers coding agents set in the shells they run:\n * Claude Code (`CLAUDECODE=1`), Codex (`CODEX_SANDBOX`), Cursor's agent\n * (`CURSOR_AGENT=1`), Gemini CLI (`GEMINI_CLI=1`), and the generic\n * `AI_AGENT`. A pipe alone is not one — a person piping into `grep` is not\n * an agent.\n */\nexport function isAgentEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n): boolean {\n return (\n env.CLAUDECODE === '1' ||\n Boolean(env.CODEX_SANDBOX) ||\n env.CURSOR_AGENT === '1' ||\n env.GEMINI_CLI === '1' ||\n Boolean(env.AI_AGENT)\n );\n}\n\nfunction defaultStream(stream: NodeJS.WriteStream): WriteStream {\n return {\n write: (chunk: string) => {\n stream.write(chunk);\n },\n isTTY: stream.isTTY,\n };\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -62,6 +62,12 @@ export interface RunOptions {
62
62
  * in, so no other test's stubbed fetch sees the extra call.
63
63
  */
64
64
  feedbackUpdates?: boolean;
65
+ /**
66
+ * Check, in the background, for a newer `@ekanos/cli` and announce it
67
+ * after the command (`update-notice.ts`). `bin.ts` turns it on; a test
68
+ * opts in, so no other test's stubbed fetch sees the extra calls.
69
+ */
70
+ updateCheck?: boolean;
65
71
  }
66
72
  /**
67
73
  * The single entry point. Resolves the agent-native envelope once, dispatches
package/dist/index.js CHANGED
@@ -51,6 +51,7 @@ import { cli, detectInvocation, setInvocation, } from './invocation.js';
51
51
  import { writeLastError } from './last-error.js';
52
52
  import { parseArgv } from './parse-argv.js';
53
53
  import { unknownCommand } from './unknown-command.js';
54
+ import { startUpdateCheck } from './update-notice.js';
54
55
  export { CliContext } from './context.js';
55
56
  export { EXIT_CODES, ERROR_CODES } from './exit-codes.js';
56
57
  const GLOBAL_SPECS = {
@@ -1172,9 +1173,10 @@ const USAGE = [
1172
1173
  ' the message is redacted first. Nothing is ever sent on its own.',
1173
1174
  '',
1174
1175
  'Keeping the toolchain current:',
1175
- ' validate, dev and publish all check for a newer @ekanos/cli in the',
1176
- ' background (never blocking, silenced by EKANOS_NO_UPDATE_CHECK) and warn',
1177
- ' on stderr when one exists. Run "ekanos upgrade --check" any time a',
1176
+ ' Every command except init, login, logout and upgrade checks for a newer',
1177
+ ' @ekanos/cli in the background (at most every 4 hours, never blocking,',
1178
+ ' silenced by EKANOS_NO_UPDATE_CHECK) and says so once on stderr when one',
1179
+ ' exists. Run "ekanos upgrade --check" any time a',
1178
1180
  ' validate finding smells like version skew (an unrecognized-key error you',
1179
1181
  ' are confident is correct) — it is read-only and safe to run freely. A',
1180
1182
  ' bare "ekanos upgrade" MUTATES the project (installs the target versions,',
@@ -1218,6 +1220,20 @@ const NO_UPDATE_CHECK_COMMANDS = new Set([
1218
1220
  'logout',
1219
1221
  'upgrade',
1220
1222
  ]);
1223
+ /**
1224
+ * The commands the toolchain check (`update-notice.ts`) skips; every other
1225
+ * command runs it. Not `NO_UPDATE_CHECK_COMMANDS`: that set also skips the
1226
+ * commands that never reach the host with a session (`validate`, `dev`,
1227
+ * `test`), which the fix check needs and this one does not. `init` writes
1228
+ * the versions it scaffolds with; `login` and `logout` change the session
1229
+ * this check would use; `upgrade` resolves the target itself and is the fix.
1230
+ */
1231
+ const NO_TOOLCHAIN_CHECK_COMMANDS = new Set([
1232
+ 'init',
1233
+ 'login',
1234
+ 'logout',
1235
+ 'upgrade',
1236
+ ]);
1221
1237
  const REPORT_HINT = () => `${cli()} feedback --last-error "<what you were trying to do>"`;
1222
1238
  /**
1223
1239
  * The single entry point. Resolves the agent-native envelope once, dispatches
@@ -1226,33 +1242,40 @@ const REPORT_HINT = () => `${cli()} feedback --last-error "<what you were trying
1226
1242
  * `process.exit`, so this stays fully testable.
1227
1243
  */
1228
1244
  export async function run(argv, options = {}) {
1229
- var _a;
1230
- var _b, _c, _d, _e;
1245
+ var _a, _b;
1246
+ var _c, _d, _e, _f;
1231
1247
  const jsonFlag = scanJsonFlag(argv);
1232
- setInvocation((_b = options.invocation) !== null && _b !== void 0 ? _b : detectInvocation((_c = options.env) !== null && _c !== void 0 ? _c : process.env), COMMANDS);
1248
+ setInvocation((_c = options.invocation) !== null && _c !== void 0 ? _c : detectInvocation((_d = options.env) !== null && _d !== void 0 ? _d : process.env), COMMANDS);
1233
1249
  const ctx = new CliContext({
1234
1250
  jsonFlag,
1235
1251
  stdout: options.stdout,
1236
1252
  stderr: options.stderr,
1237
1253
  env: options.env,
1238
1254
  });
1239
- const cwd = (_d = options.cwd) !== null && _d !== void 0 ? _d : process.cwd();
1240
- const env = (_e = options.env) !== null && _e !== void 0 ? _e : process.env;
1255
+ const cwd = (_e = options.cwd) !== null && _e !== void 0 ? _e : process.cwd();
1256
+ const env = (_f = options.env) !== null && _f !== void 0 ? _f : process.env;
1241
1257
  resetHttpTrace();
1242
1258
  const trace = {
1243
1259
  command: null,
1244
1260
  positionals: [],
1245
1261
  reportHinted: false,
1246
1262
  updates: null,
1263
+ toolchain: null,
1247
1264
  };
1248
1265
  const exitCode = await dispatch(argv, options, ctx, cwd, env, trace);
1249
1266
  if (exitCode !== 0 && trace.command !== 'feedback') {
1250
1267
  afterFailure(argv, options, ctx, env, trace, exitCode);
1251
1268
  }
1252
1269
  try {
1253
- (_a = trace.updates) === null || _a === void 0 ? void 0 : _a.finish(ctx);
1270
+ (_a = trace.toolchain) === null || _a === void 0 ? void 0 : _a.finish(ctx);
1254
1271
  }
1255
- catch (_f) {
1272
+ catch (_g) {
1273
+ // A courtesy: it never changes how a run ends.
1274
+ }
1275
+ try {
1276
+ (_b = trace.updates) === null || _b === void 0 ? void 0 : _b.finish(ctx);
1277
+ }
1278
+ catch (_h) {
1256
1279
  // A courtesy: it never changes how a run ends.
1257
1280
  }
1258
1281
  return exitCode;
@@ -1333,6 +1356,9 @@ async function dispatch(argv, options, ctx, cwd, env, trace) {
1333
1356
  if (parsed.flags.help === true) {
1334
1357
  return emitCommandHelp(ctx, command);
1335
1358
  }
1359
+ if (options.updateCheck && !NO_TOOLCHAIN_CHECK_COMMANDS.has(command)) {
1360
+ trace.toolchain = startUpdateCheck({ env });
1361
+ }
1336
1362
  if (options.feedbackUpdates && !NO_UPDATE_CHECK_COMMANDS.has(command)) {
1337
1363
  trace.updates = startFeedbackUpdatesCheck({ env });
1338
1364
  }