@habitat-ai/cli 0.5.15 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +100 -4
  2. package/dist/application-Idvdhc9h.js +80 -0
  3. package/dist/application.js +2 -18
  4. package/dist/cli-DxjKzwlV.js +4757 -0
  5. package/dist/cli.js +2 -0
  6. package/dist/command-DkmTpQvc.js +74 -0
  7. package/dist/command.d.ts +36 -35
  8. package/dist/command.js +2 -45
  9. package/dist/generators/cli-command.js +263 -0
  10. package/dist/generators/cli-extension.js +192 -0
  11. package/dist/generators/init.js +20 -20
  12. package/dist/generators/preset.js +8 -7
  13. package/dist/generators/remove-hook.js +7 -4
  14. package/dist/generators/service.js +130 -139
  15. package/dist/habitat.app-CgdXa2f2.js +16617 -0
  16. package/dist/habitat.app.js +2 -0
  17. package/dist/host-BcptPYDL.js +293 -0
  18. package/dist/host.d.ts +57 -0
  19. package/dist/host.js +3 -0
  20. package/dist/index.js +8 -5
  21. package/dist/initialization-BWDg3bks.js +249 -0
  22. package/dist/migrations/0-5-7-repository-foundation.js +42 -38
  23. package/dist/nx-generators-DQDXOkMX.js +44 -0
  24. package/dist/nx-generators.js +2 -51
  25. package/dist/nx-plugin.d.ts +4 -1
  26. package/dist/nx-plugin.js +247 -15
  27. package/dist/oclif-DBwcAyVK.js +11 -0
  28. package/dist/oclif.js +3 -0
  29. package/dist/product-version-Bqc0L8lq.js +18 -0
  30. package/dist/publish-generator-tree-CgFdcykY.js +14 -0
  31. package/dist/repository-preset-DYxxe7p3.js +543 -0
  32. package/dist/verified-writes-Cne-zTxS.js +60 -0
  33. package/generators/cli-command/schema.json +20 -0
  34. package/generators/cli-extension/schema.json +20 -0
  35. package/generators/service/files/AGENTS.md.template +5 -2
  36. package/generators/service/files/habitat.toml.template +1 -1
  37. package/generators.json +10 -0
  38. package/oclif.manifest.json +1094 -27
  39. package/package.json +72 -8
  40. package/dist/application.d.ts +0 -14
  41. package/dist/commands/check.d.ts +0 -15
  42. package/dist/commands/check.js +0 -32
  43. package/dist/commands/hook.d.ts +0 -12
  44. package/dist/commands/hook.js +0 -25
  45. package/dist/commands/resolve.d.ts +0 -9
  46. package/dist/commands/resolve.js +0 -15
  47. package/dist/generators/init.d.ts +0 -3
  48. package/dist/generators/preset.d.ts +0 -4
  49. package/dist/generators/remove-hook.d.ts +0 -3
  50. package/dist/generators/service.d.ts +0 -16
  51. package/dist/index.d.ts +0 -1
  52. package/dist/lib/binding.d.ts +0 -10
  53. package/dist/lib/binding.js +0 -16
  54. package/dist/lib/output.d.ts +0 -9
  55. package/dist/lib/output.js +0 -22
  56. package/dist/migrations/0-5-7-repository-foundation.d.ts +0 -3
  57. package/dist/nx/initialization.d.ts +0 -62
  58. package/dist/nx/initialization.js +0 -265
  59. package/dist/nx/projection.d.ts +0 -29
  60. package/dist/nx/projection.js +0 -308
  61. package/dist/nx/repository-preset.d.ts +0 -22
  62. package/dist/nx/repository-preset.js +0 -596
  63. package/dist/nx-generators.d.ts +0 -42
  64. package/dist/product-version.d.ts +0 -2
  65. package/dist/product-version.js +0 -15
package/dist/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ import { n as runHabitatProcess, t as entrypoint } from "./cli-DxjKzwlV.js";
2
+ export { entrypoint, runHabitatProcess };
@@ -0,0 +1,74 @@
1
+ import { Command, Flags } from "@oclif/core";
2
+ //#region src/lib/output.ts
3
+ /**
4
+ * Writes one complete Habitat command result as JSON before the command returns.
5
+ *
6
+ * Awaiting the stream callback prevents Bun from ending the process while a
7
+ * large stdout write is still buffered at the Oclif process boundary. EPIPE
8
+ * remains successful because it means the downstream pipe deliberately
9
+ * stopped reading, matching Oclif's stdout behavior.
10
+ */
11
+ function writeJsonResult(result) {
12
+ return new Promise((resolve, reject) => {
13
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`, (error) => {
14
+ if (error && !isBrokenPipe(error)) {
15
+ reject(error);
16
+ return;
17
+ }
18
+ resolve();
19
+ });
20
+ });
21
+ }
22
+ function isBrokenPipe(error) {
23
+ return "code" in error && error.code === "EPIPE";
24
+ }
25
+ //#endregion
26
+ //#region src/command.ts
27
+ /** Shared result and output contract for native Oclif command projections. */
28
+ var HabitatCommand = class extends Command {
29
+ static baseFlags = { json: Flags.boolean({ description: "Output machine-readable JSON" }) };
30
+ ok(data, meta, warnings) {
31
+ return {
32
+ ok: true,
33
+ data,
34
+ meta,
35
+ warnings
36
+ };
37
+ }
38
+ fail(message, options) {
39
+ return {
40
+ ok: false,
41
+ error: {
42
+ message,
43
+ code: options?.code,
44
+ details: options?.details
45
+ },
46
+ meta: options?.meta
47
+ };
48
+ }
49
+ /** Renders one result through the selected machine or human output channel. */
50
+ async outputResult(result, options) {
51
+ if ((options?.flags ?? {
52
+ json: false,
53
+ dryRun: false,
54
+ yes: false
55
+ }).json) {
56
+ await writeJsonResult(result);
57
+ return;
58
+ }
59
+ if (options?.human) {
60
+ options.human(result);
61
+ return;
62
+ }
63
+ this.log(result.ok ? "ok" : `error: ${result.error.message}`);
64
+ }
65
+ static extractBaseFlags(flags) {
66
+ return {
67
+ json: Boolean(flags.json),
68
+ dryRun: Boolean(flags["dry-run"] ?? flags.dryRun),
69
+ yes: Boolean(flags.yes)
70
+ };
71
+ }
72
+ };
73
+ //#endregion
74
+ export { writeJsonResult as n, HabitatCommand as t };
package/dist/command.d.ts CHANGED
@@ -1,44 +1,45 @@
1
1
  import { Command } from "@oclif/core";
2
- /** Normalized values for the shared machine-output and mutation-control flags. */
3
- export type HabitatBaseFlags = {
4
- json: boolean;
5
- dryRun: boolean;
6
- yes: boolean;
2
+ //#region src/command.d.ts
3
+ /** Normalized machine output and explicitly opted-in mutation controls. */
4
+ type HabitatBaseFlags = {
5
+ json: boolean;
6
+ dryRun: boolean;
7
+ yes: boolean;
7
8
  };
8
9
  /** Structured command failure rendered consistently for machine and human callers. */
9
- export type HabitatError = {
10
- message: string;
11
- code?: string;
12
- details?: unknown;
10
+ type HabitatError = {
11
+ message: string;
12
+ code?: string;
13
+ details?: unknown;
13
14
  };
14
15
  /** Stable success-or-failure envelope returned by Habitat command projections. */
15
- export type HabitatResult<TData = unknown> = {
16
- ok: true;
17
- data?: TData;
18
- warnings?: string[];
19
- meta?: Record<string, unknown>;
16
+ type HabitatResult<TData = unknown> = {
17
+ ok: true;
18
+ data?: TData;
19
+ warnings?: string[];
20
+ meta?: Record<string, unknown>;
20
21
  } | {
21
- ok: false;
22
- error: HabitatError;
23
- meta?: Record<string, unknown>;
22
+ ok: false;
23
+ error: HabitatError;
24
+ meta?: Record<string, unknown>;
24
25
  };
25
26
  /** Shared result and output contract for native Oclif command projections. */
26
- export declare abstract class HabitatCommand extends Command {
27
- static baseFlags: {
28
- readonly json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
29
- readonly "dry-run": import("@oclif/core/interfaces").BooleanFlag<boolean>;
30
- readonly yes: import("@oclif/core/interfaces").BooleanFlag<boolean>;
31
- };
32
- protected ok<TData>(data?: TData, meta?: Record<string, unknown>, warnings?: string[]): HabitatResult<TData>;
33
- protected fail(message: string, options?: {
34
- code?: string;
35
- details?: unknown;
36
- meta?: Record<string, unknown>;
37
- }): HabitatResult<never>;
38
- /** Renders one result through the selected machine or human output channel. */
39
- protected outputResult<TData>(result: HabitatResult<TData>, options?: {
40
- flags?: HabitatBaseFlags;
41
- human?: (result: HabitatResult<TData>) => void;
42
- }): Promise<void>;
43
- static extractBaseFlags(flags: Record<string, unknown>): HabitatBaseFlags;
27
+ declare abstract class HabitatCommand extends Command {
28
+ static baseFlags: {
29
+ readonly json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
30
+ };
31
+ protected ok<TData>(data?: TData, meta?: Record<string, unknown>, warnings?: string[]): HabitatResult<TData>;
32
+ protected fail(message: string, options?: {
33
+ code?: string;
34
+ details?: unknown;
35
+ meta?: Record<string, unknown>;
36
+ }): HabitatResult<never>;
37
+ /** Renders one result through the selected machine or human output channel. */
38
+ protected outputResult<TData>(result: HabitatResult<TData>, options?: {
39
+ flags?: HabitatBaseFlags;
40
+ human?: (result: HabitatResult<TData>) => void;
41
+ }): Promise<void>;
42
+ static extractBaseFlags(flags: Record<string, unknown>): HabitatBaseFlags;
44
43
  }
44
+ //#endregion
45
+ export { HabitatBaseFlags, HabitatCommand, HabitatError, HabitatResult };
package/dist/command.js CHANGED
@@ -1,45 +1,2 @@
1
- import { Command, Flags } from "@oclif/core";
2
- import { writeJsonResult } from "./lib/output.js";
3
- /** Shared result and output contract for native Oclif command projections. */
4
- export class HabitatCommand extends Command {
5
- static baseFlags = {
6
- json: Flags.boolean({ description: "Output machine-readable JSON" }),
7
- "dry-run": Flags.boolean({
8
- description: "Print actions without making any changes",
9
- }),
10
- yes: Flags.boolean({
11
- char: "y",
12
- description: "Assume yes for prompts/confirmation",
13
- }),
14
- };
15
- ok(data, meta, warnings) {
16
- return { ok: true, data, meta, warnings };
17
- }
18
- fail(message, options) {
19
- return {
20
- ok: false,
21
- error: { message, code: options?.code, details: options?.details },
22
- meta: options?.meta,
23
- };
24
- }
25
- /** Renders one result through the selected machine or human output channel. */
26
- async outputResult(result, options) {
27
- const flags = options?.flags ?? { json: false, dryRun: false, yes: false };
28
- if (flags.json) {
29
- await writeJsonResult(result);
30
- return;
31
- }
32
- if (options?.human) {
33
- options.human(result);
34
- return;
35
- }
36
- this.log(result.ok ? "ok" : `error: ${result.error.message}`);
37
- }
38
- static extractBaseFlags(flags) {
39
- return {
40
- json: Boolean(flags.json),
41
- dryRun: Boolean(flags["dry-run"] ?? flags.dryRun),
42
- yes: Boolean(flags.yes),
43
- };
44
- }
45
- }
1
+ import { t as HabitatCommand } from "./command-DkmTpQvc.js";
2
+ export { HabitatCommand };
@@ -0,0 +1,263 @@
1
+ import { t as stageVerifiedWrites } from "../verified-writes-Cne-zTxS.js";
2
+ import { Type } from "typebox";
3
+ import { Validator } from "typebox/schema";
4
+ import { parse } from "smol-toml";
5
+ import { getProjects, names, readJson } from "@nx/devkit";
6
+ import ts from "typescript";
7
+ //#region src/generators/cli-command.ts
8
+ const optionsValidator = new Validator({}, Type.Object({
9
+ topic: Type.String({ pattern: "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }),
10
+ name: Type.String({ pattern: "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" })
11
+ }, { additionalProperties: false }));
12
+ /** Adds one command to an existing Habitat topic without selecting or activating it. */
13
+ function createCliCommand(tree, options) {
14
+ if (!optionsValidator.Check(options)) throw new Error("Command options require safe topic and name identifiers.");
15
+ const rootPackage = readJson(tree, "package.json");
16
+ if (rootPackage.name !== "habitat-workspace" || rootPackage.private !== true) throw new Error("Official commands require the Habitat repository.");
17
+ const root = `plugins/cli/topics/${options.topic}`;
18
+ const projectName = `@habitat-ai/plugin-${options.topic}`;
19
+ const projects = getProjects(tree);
20
+ const appSelection = parse(requiredText(tree, "apps/habitat/habitat.toml"));
21
+ if (projects.get("@habitat-ai/cli")?.root !== "apps/habitat" || appSelection.ownerProject !== "@habitat-ai/cli" || appSelection.blueprint !== "app" || appSelection.blueprintVersion !== 2 || appSelection.roots?.project !== "apps/habitat") throw new Error("Official commands require the admitted Habitat CLI app owner.");
22
+ const owners = [...projects].filter(([, project]) => project.root === root);
23
+ const project = projects.get(projectName);
24
+ if (owners.length !== 1 || owners[0][0] !== projectName || project?.root !== root) throw new Error("Command destination requires the exact existing Habitat topic Nx owner.");
25
+ const manifest = readJson(tree, `${root}/package.json`);
26
+ const projectFile = readJson(tree, `${root}/project.json`);
27
+ const selection = parse(requiredText(tree, `${root}/habitat.toml`));
28
+ if (manifest.name !== projectName || projectFile.name !== projectName || selection.ownerProject !== projectName || selection.blueprint !== "plugin-cli-topic" || selection.blueprintVersion !== 1 || selection.roots?.project !== root) throw new Error("Topic package, project, and Habitat selection must agree.");
29
+ const before = requiredText(tree, `${root}/src/index.ts`);
30
+ const symbol = `${names(options.name).propertyName}Command`;
31
+ const id = `${options.topic}:${options.name}`;
32
+ const sourcePath = `src/commands/${options.name}.ts`;
33
+ const updated = registerCommand(before, symbol, `./commands/${options.name}.js`);
34
+ for (const file of commandFiles(tree, `${root}/src/commands`)) {
35
+ if (file === `${root}/${sourcePath}`) continue;
36
+ if (declaresCommandId(parseSource(file, requiredText(tree, file)), id)) throw new Error(`Command ID '${id}' already exists.`);
37
+ }
38
+ const packageBefore = requiredText(tree, `${root}/package.json`);
39
+ const packageAfter = packageWithTestContract(packageBefore);
40
+ const testRunner = usesVitest(JSON.parse(packageBefore)) ? "vitest" : "bun:test";
41
+ stageVerifiedWrites(tree, { root }, [
42
+ {
43
+ path: sourcePath,
44
+ contents: commandSource(symbol, id)
45
+ },
46
+ {
47
+ path: `test/commands/${options.name}.test.ts`,
48
+ contents: commandTest(symbol, options.name, id, testRunner)
49
+ },
50
+ {
51
+ path: "src/index.ts",
52
+ contents: updated,
53
+ before
54
+ },
55
+ {
56
+ path: "package.json",
57
+ contents: packageAfter,
58
+ before: packageBefore
59
+ }
60
+ ]);
61
+ }
62
+ function usesVitest(manifest) {
63
+ return manifest.devDependencies?.vitest !== void 0 || manifest.dependencies?.vitest !== void 0;
64
+ }
65
+ function packageWithTestContract(contents) {
66
+ const manifest = JSON.parse(contents);
67
+ for (const field of [
68
+ "scripts",
69
+ "dependencies",
70
+ "devDependencies"
71
+ ]) if (manifest[field] !== void 0 && (typeof manifest[field] !== "object" || manifest[field] === null || Array.isArray(manifest[field]))) throw new Error(`Topic package ${field} must be an object.`);
72
+ const command = usesVitest(manifest) ? "vitest run test/commands" : "bun test test/commands";
73
+ if (manifest.scripts?.["test:cli-commands"] !== void 0 && manifest.scripts["test:cli-commands"] !== command) throw new Error("The dedicated CLI command test script is already owned by another workflow.");
74
+ manifest.scripts = {
75
+ ...manifest.scripts,
76
+ "test:cli-commands": command
77
+ };
78
+ manifest.devDependencies = { ...manifest.devDependencies };
79
+ for (const [name, version] of Object.entries({
80
+ effect: "4.1.4",
81
+ "bun-types": "1.3.14"
82
+ })) if ((manifest.dependencies?.[name] ?? manifest.devDependencies[name]) === void 0) manifest.devDependencies[name] = version;
83
+ return `${JSON.stringify(manifest, null, 2)}\n`;
84
+ }
85
+ function requiredText(tree, path) {
86
+ const value = tree.read(path, "utf8");
87
+ if (value === null) throw new Error(`Required topic file is missing: ${path}`);
88
+ return value;
89
+ }
90
+ function parseSource(path, contents) {
91
+ const source = ts.createSourceFile(path, contents, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
92
+ if (source.parseDiagnostics?.length) throw new Error(`Cannot update malformed TypeScript: ${path}`);
93
+ return source;
94
+ }
95
+ function registerCommand(contents, symbol, modulePath) {
96
+ const source = parseSource("index.ts", contents);
97
+ const imports = source.statements.filter(ts.isImportDeclaration);
98
+ const factoryImports = imports.filter((node) => !node.importClause?.isTypeOnly && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === "@habitat-ai/sdk/plugins/cli").flatMap((node) => {
99
+ const bindings = node.importClause?.namedBindings;
100
+ return bindings && ts.isNamedImports(bindings) ? bindings.elements.filter((element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "defineCliTopicPlugin") : [];
101
+ });
102
+ if (factoryImports.length !== 1) throw new Error("Topic requires one explicit SDK topic factory import.");
103
+ const factoryName = factoryImports[0].name.text;
104
+ const arrays = [];
105
+ const visit = (node) => {
106
+ if (ts.isCallExpression(node) && ts.isCallExpression(node.expression)) {
107
+ const factory = node.expression.expression;
108
+ if (ts.isPropertyAccessExpression(factory) && ts.isIdentifier(factory.expression) && factory.expression.text === factoryName && factory.name.text === "factory") {
109
+ const declaration = node.parent;
110
+ const statement = declaration.parent?.parent;
111
+ if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name) || declaration.name.text !== "createPlugin" || !statement || !ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) throw new Error("Topic factory must directly initialize the exported createPlugin declaration.");
112
+ if (node.arguments.length !== 1 || !ts.isObjectLiteralExpression(node.arguments[0])) throw new Error("Topic factory requires one explicit membership object.");
113
+ const properties = node.arguments[0].properties;
114
+ const commands = properties.filter((property) => literalPropertyName(property.name) === "commands");
115
+ if (commands.length !== 1 || !ts.isPropertyAssignment(commands[0]) || !ts.isArrayLiteralExpression(commands[0].initializer)) throw new Error("Topic commands must be one explicit array.");
116
+ if (properties.slice(properties.indexOf(commands[0]) + 1).some((property) => ts.isSpreadAssignment(property) || property.name && ts.isComputedPropertyName(property.name) && literalPropertyName(property.name) === void 0)) throw new Error("Later topic properties must not overwrite command membership.");
117
+ arrays.push(commands[0].initializer);
118
+ }
119
+ }
120
+ ts.forEachChild(node, visit);
121
+ };
122
+ visit(source);
123
+ if (arrays.length !== 1 || arrays[0].elements.some((element) => !ts.isIdentifier(element))) throw new Error("Topic membership must have one unambiguous identifier-only array.");
124
+ const array = arrays[0];
125
+ const entries = array.elements.map((element) => element.getText(source));
126
+ if (new Set(entries).size !== entries.length) throw new Error("Topic membership contains duplicates.");
127
+ const matching = imports.filter((node) => ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === modulePath);
128
+ const bindings = topLevelBindings(source).get(symbol) ?? [];
129
+ if (matching.length > 0 || entries.includes(symbol)) {
130
+ const binding = matching[0]?.importClause?.namedBindings;
131
+ if (matching.length !== 1 || !binding || !ts.isNamedImports(binding) || matching[0].importClause?.isTypeOnly || binding.elements.length !== 1 || binding.elements[0].isTypeOnly || binding.elements[0].name.text !== symbol || binding.elements[0].propertyName !== void 0 || matching[0].importClause?.name !== void 0 || !entries.includes(symbol)) throw new Error("Existing command import and registration disagree.");
132
+ if (bindings.length !== 1 || bindings[0] !== binding.elements[0].name) throw new Error("Command name collides with an existing topic declaration.");
133
+ return contents;
134
+ }
135
+ if (bindings.length > 0) throw new Error("Command name collides with an existing topic declaration.");
136
+ const insertion = array.elements.end;
137
+ const addition = entries.length === 0 ? symbol : `${array.elements.hasTrailingComma ? "" : ","} ${symbol}`;
138
+ return `import { ${symbol} } from "${modulePath}";\n${contents.slice(0, insertion) + addition + contents.slice(insertion)}`;
139
+ }
140
+ function literalPropertyName(name) {
141
+ if (name === void 0) return void 0;
142
+ if (ts.isComputedPropertyName(name)) return ts.isStringLiteral(name.expression) || ts.isNoSubstitutionTemplateLiteral(name.expression) || ts.isNumericLiteral(name.expression) ? name.expression.text : void 0;
143
+ return ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : void 0;
144
+ }
145
+ function topLevelBindings(source) {
146
+ const bindings = /* @__PURE__ */ new Map();
147
+ const add = (name) => {
148
+ if (ts.isIdentifier(name)) {
149
+ const declarations = bindings.get(name.text) ?? [];
150
+ declarations.push(name);
151
+ bindings.set(name.text, declarations);
152
+ } else for (const element of name.elements) if (ts.isBindingElement(element)) add(element.name);
153
+ };
154
+ const visit = (node) => {
155
+ if (ts.isImportDeclaration(node)) {
156
+ if (node.importClause?.name) add(node.importClause.name);
157
+ const named = node.importClause?.namedBindings;
158
+ if (named) {
159
+ if (ts.isNamespaceImport(named)) add(named.name);
160
+ else for (const element of named.elements) add(element.name);
161
+ }
162
+ return;
163
+ }
164
+ if (ts.isImportEqualsDeclaration(node)) {
165
+ add(node.name);
166
+ return;
167
+ }
168
+ if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node) || ts.isModuleDeclaration(node)) {
169
+ if (node.parent === source && node.name && ts.isIdentifier(node.name)) add(node.name);
170
+ return;
171
+ }
172
+ if (ts.isFunctionLike(node) || ts.isClassExpression(node)) return;
173
+ if (ts.isVariableDeclarationList(node)) {
174
+ if (ts.isVariableStatement(node.parent) && node.parent.parent === source || !(node.flags & ts.NodeFlags.BlockScoped)) for (const declaration of node.declarations) add(declaration.name);
175
+ }
176
+ ts.forEachChild(node, visit);
177
+ };
178
+ ts.forEachChild(source, visit);
179
+ return bindings;
180
+ }
181
+ function declaresCommandId(source, id) {
182
+ const factories = /* @__PURE__ */ new Set();
183
+ const namespaces = /* @__PURE__ */ new Map();
184
+ for (const statement of source.statements) {
185
+ if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
186
+ const factory = statement.moduleSpecifier.text === "@habitat-ai/sdk/plugins/cli/oclif" ? "createOclifCommand" : statement.moduleSpecifier.text === "@habitat-ai/sdk/plugins/cli/effect" ? "defineCommand" : void 0;
187
+ const binding = statement.importClause?.namedBindings;
188
+ if (factory === void 0 || binding === void 0) continue;
189
+ if (ts.isNamespaceImport(binding)) namespaces.set(binding.name.text, factory);
190
+ else for (const element of binding.elements) if (!element.isTypeOnly && (element.propertyName ?? element.name).text === factory) factories.add(element.name.text);
191
+ }
192
+ for (const statement of source.statements) {
193
+ if (!ts.isVariableStatement(statement)) continue;
194
+ for (const declaration of statement.declarationList.declarations) {
195
+ const call = declaration.initializer;
196
+ if (call === void 0 || !ts.isCallExpression(call)) continue;
197
+ const callee = call.expression;
198
+ if (!(ts.isIdentifier(callee) && factories.has(callee.text)) && !(ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && namespaces.get(callee.expression.text) === callee.name.text)) continue;
199
+ const metadata = call.arguments[0];
200
+ if (metadata === void 0 || !ts.isObjectLiteralExpression(metadata)) throw new Error(`Cannot qualify an existing command ID in ${source.fileName}.`);
201
+ let declaredId;
202
+ for (const property of metadata.properties) {
203
+ const name = literalPropertyName(property.name);
204
+ if (ts.isSpreadAssignment(property) || name === void 0) declaredId = void 0;
205
+ else if (name === "id") declaredId = ts.isPropertyAssignment(property) && (ts.isStringLiteral(property.initializer) || ts.isNoSubstitutionTemplateLiteral(property.initializer)) ? property.initializer.text : void 0;
206
+ }
207
+ if (declaredId === void 0) throw new Error(`Cannot qualify an existing command ID in ${source.fileName}.`);
208
+ if (declaredId === id) return true;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+ function commandFiles(tree, root) {
214
+ return tree.children(root).flatMap((name) => {
215
+ const path = `${root}/${name}`;
216
+ return tree.isFile(path) ? path.endsWith(".ts") ? [path] : [] : commandFiles(tree, path);
217
+ });
218
+ }
219
+ function commandSource(symbol, id) {
220
+ return `import { createOclifCommand, type OclifCommandContext } from "@habitat-ai/sdk/plugins/cli/oclif";
221
+ import { Effect } from "@habitat-ai/sdk/effect";
222
+ import { Args, Flags } from "@oclif/core";
223
+
224
+ const args = { message: Args.string({ required: true }) };
225
+ const flags = { uppercase: Flags.boolean({ default: false }) };
226
+
227
+ /** Echoes one parsed message without acquiring or retaining capabilities. */
228
+ export const ${symbol} = createOclifCommand({
229
+ id: "${id}",
230
+ description: "Echo a message",
231
+ args,
232
+ flags,
233
+ effect(context: OclifCommandContext<typeof args, typeof flags>) {
234
+ return Effect.succeed({ message: context.flags.uppercase ? context.args.message.toUpperCase() : context.args.message });
235
+ },
236
+ present(result, command) { command.log(result.message); },
237
+ });
238
+ `;
239
+ }
240
+ function commandTest(symbol, name, id, testRunner) {
241
+ return `import assert from "node:assert/strict";
242
+ import { test } from "${testRunner}";
243
+ import { Effect } from "effect";
244
+ import { ${symbol} } from "../../src/commands/${name}.js";
245
+
246
+ test("${id} preserves input and applies uppercase only when selected", async () => {
247
+ for (const uppercase of [false, true]) {
248
+ const program = ${symbol}.effect({
249
+ input: { args: { message: "Hello" }, flags: { uppercase, json: false } },
250
+ clients: {},
251
+ resources: { has: () => false, get: () => { throw new Error("No resource is declared"); } },
252
+ telemetry: { span: (_name, effect) => effect, event: () => Effect.void },
253
+ execution: { appId: "test", processId: "test", entrypointId: "test", profileId: "test", role: "cli", ownerId: "test", executionId: "test", traceId: "test" },
254
+ });
255
+ if (!Effect.isEffect(program)) throw new Error("The authored echo returns a native Effect value");
256
+ const result = await Effect.runPromise(program);
257
+ assert.deepEqual(result, { message: uppercase ? "HELLO" : "Hello" });
258
+ }
259
+ });
260
+ `;
261
+ }
262
+ //#endregion
263
+ export { createCliCommand as default };
@@ -0,0 +1,192 @@
1
+ import { t as stageVerifiedWrites } from "../verified-writes-Cne-zTxS.js";
2
+ import { Type } from "typebox";
3
+ import { Validator } from "typebox/schema";
4
+ //#region src/generators/cli-extension.ts
5
+ const optionsValidator = new Validator({}, Type.Object({
6
+ id: Type.String({
7
+ pattern: "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
8
+ maxLength: 196
9
+ }),
10
+ destination: Type.String({ minLength: 1 })
11
+ }, { additionalProperties: false }));
12
+ /** Stages one standalone native Oclif extension; Nx owns publication, not activation. */
13
+ function createCliExtension(tree, options) {
14
+ if (!optionsValidator.Check(options)) throw new Error("Extension options require a safe kebab-case id and an explicit destination.");
15
+ const name = `habitat-extension-${options.id}`;
16
+ stageVerifiedWrites(tree, { root: options.destination }, [
17
+ {
18
+ path: ".gitignore",
19
+ contents: "node_modules/\ndist/\n"
20
+ },
21
+ {
22
+ path: "README.md",
23
+ contents: readme(name, options.id)
24
+ },
25
+ {
26
+ path: "package.json",
27
+ contents: json({
28
+ name,
29
+ version: "0.1.0",
30
+ description: "A standalone native Oclif extension",
31
+ license: "UNLICENSED",
32
+ type: "module",
33
+ files: ["dist", "README.md"],
34
+ engines: { node: "^24.18.1" },
35
+ scripts: {
36
+ build: "tsc -p tsconfig.json",
37
+ typecheck: "tsc -p tsconfig.json --noEmit",
38
+ test: "node --test test/commands.test.mjs"
39
+ },
40
+ dependencies: { "@oclif/core": "4.13.3" },
41
+ devDependencies: {
42
+ "@types/node": "24.13.3",
43
+ typescript: "5.9.3"
44
+ },
45
+ oclif: { commands: {
46
+ strategy: "explicit",
47
+ target: "./dist/commands.js",
48
+ identifier: "COMMANDS"
49
+ } }
50
+ })
51
+ },
52
+ {
53
+ path: "src/commands.ts",
54
+ contents: commandSource(options.id)
55
+ },
56
+ {
57
+ path: "test/commands.test.mjs",
58
+ contents: commandTests(options.id)
59
+ },
60
+ {
61
+ path: "tsconfig.json",
62
+ contents: json({
63
+ compilerOptions: {
64
+ target: "ES2022",
65
+ module: "NodeNext",
66
+ moduleResolution: "NodeNext",
67
+ rootDir: "src",
68
+ outDir: "dist",
69
+ declaration: true,
70
+ strict: true,
71
+ noEmitOnError: true,
72
+ skipLibCheck: true,
73
+ types: ["node"]
74
+ },
75
+ include: ["src/**/*.ts"]
76
+ })
77
+ }
78
+ ]);
79
+ }
80
+ function json(value) {
81
+ return `${JSON.stringify(value, null, 2)}\n`;
82
+ }
83
+ function commandSource(id) {
84
+ return `import { Args, Command, Flags } from "@oclif/core";
85
+
86
+ export class Hello extends Command {
87
+ static override description = "Greet someone";
88
+ static override args = {
89
+ name: Args.string({ description: "Who to greet", default: "world" }),
90
+ };
91
+ static override flags = {
92
+ uppercase: Flags.boolean({ char: "u", description: "Use uppercase", default: false }),
93
+ };
94
+
95
+ async run(): Promise<void> {
96
+ const { args, flags } = await this.parse(Hello);
97
+ const greeting = "Hello, " + args.name + "!";
98
+ this.log(flags.uppercase ? greeting.toUpperCase() : greeting);
99
+ }
100
+ }
101
+
102
+ export const COMMANDS = { "${id}:hello": Hello };
103
+ `;
104
+ }
105
+ function commandTests(id) {
106
+ return `import assert from "node:assert/strict";
107
+ import { spawnSync } from "node:child_process";
108
+ import { test } from "node:test";
109
+ import { fileURLToPath } from "node:url";
110
+
111
+ const root = fileURLToPath(new URL("..", import.meta.url));
112
+ const program = \`
113
+ import { Config, flush, handle, run } from "@oclif/core";
114
+ let failed = false;
115
+ let failure;
116
+ try {
117
+ const config = await Config.load({ root: process.cwd(), userPlugins: false, devPlugins: false });
118
+ await run(process.argv.slice(1), config);
119
+ } catch (error) {
120
+ failed = true;
121
+ failure = error;
122
+ }
123
+ try { await flush(); } catch (error) {
124
+ if (!failed) { failed = true; failure = error; }
125
+ }
126
+ if (failed) handle(failure);
127
+ \`;
128
+
129
+ function invoke(args) {
130
+ const result = spawnSync(process.execPath, ["--input-type=module", "--eval", program, "--", ...args], {
131
+ cwd: root,
132
+ encoding: "utf8",
133
+ env: { ...process.env, NODE_ENV: "production", NO_COLOR: "1" },
134
+ timeout: 10000,
135
+ });
136
+ assert.ifError(result.error);
137
+ assert.equal(result.signal, null);
138
+ return result;
139
+ }
140
+
141
+ test("native discovery and default argument", () => {
142
+ const result = invoke(["${id}:hello"]);
143
+ assert.equal(result.status, 0, result.stderr);
144
+ assert.equal(result.stdout, "Hello, world!\\n");
145
+ assert.equal(result.stderr, "");
146
+ });
147
+
148
+ test("native argument and uppercase flag", () => {
149
+ const result = invoke(["${id}:hello", "Ada", "--uppercase"]);
150
+ assert.equal(result.status, 0, result.stderr);
151
+ assert.equal(result.stdout, "HELLO, ADA!\\n");
152
+ assert.equal(result.stderr, "");
153
+ });
154
+
155
+ test("native parser refuses an unknown flag", () => {
156
+ const result = invoke(["${id}:hello", "--unknown"]);
157
+ assert.equal(result.status, 2);
158
+ assert.equal(result.stdout, "");
159
+ assert.match(result.stderr, /Nonexistent flag: --unknown/);
160
+ });
161
+ `;
162
+ }
163
+ function readme(name, id) {
164
+ return `# ${name}
165
+
166
+ A standalone Oclif extension with the \`${id}:hello\` command.
167
+
168
+ ## Development
169
+
170
+ Use Node.js 24.18.1 or a later compatible Node.js 24 release.
171
+
172
+ \`\`\`sh
173
+ npm install
174
+ npm run build
175
+ npm test
176
+ \`\`\`
177
+
178
+ The native command accepts an optional name (default: \`world\`) and an
179
+ \`--uppercase\` / \`-u\` flag. Tests use Oclif discovery and parsing in real
180
+ Node.js child processes.
181
+
182
+ Oclif reads the explicit \`COMMANDS\` export from \`dist/commands.js\`. No
183
+ Habitat SDK, CLI, workspace-relative import, or Nx installation is needed to
184
+ build and test this package. No Nx project registration is generated.
185
+
186
+ Generation creates source only. It does not install, link, or activate this
187
+ extension in an Oclif host. Choose publication metadata and a license before
188
+ publishing the package.
189
+ `;
190
+ }
191
+ //#endregion
192
+ export { createCliExtension as default };