@di-framework/cli-plugin-ai 0.0.1 → 6.0.3
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.
- package/README.md +21 -0
- package/package.json +36 -9
- package/src/agent/audit.ts +169 -0
- package/src/agent/init.ts +168 -0
- package/src/agent/inspect.ts +252 -0
- package/src/agent/migrate.ts +215 -0
- package/src/command.ts +164 -0
- package/src/index.ts +23 -2
- package/src/skills/index.ts +276 -0
- package/src/skills/validate.ts +145 -0
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @di-framework/cli-plugin-ai
|
|
2
|
+
|
|
3
|
+
Agent configuration and Agent Skills commands for the `di-framework` CLI.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
di-framework extensions install ai
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
That installs `@di-framework/cli-plugin-ai` and mounts `di-framework ai`. The commands resolve `@di-framework/ai-utils` from the current project.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
di-framework ai agent audit
|
|
13
|
+
di-framework ai agent init --asset AGENTS.md --apply
|
|
14
|
+
di-framework ai agent inspect
|
|
15
|
+
di-framework ai agent migrate --plan
|
|
16
|
+
di-framework ai skills validate
|
|
17
|
+
di-framework ai skills index build --skills-dir ./.agents/skills --output ./.di-framework/skills-index.json
|
|
18
|
+
di-framework ai skills index query --input ./.di-framework/skills-index.json --query 'review authorization'
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`agent audit`, `agent inspect`, and the default `agent migrate` / `agent init` modes do not write files. `--apply` writes the plan from that same invocation. Skills index validation drift and query abstention exit `1`. Invalid options exit `2`. A missing `@di-framework/ai-utils` install, or an unexpected operation failure, exits `3`.
|
package/package.json
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@di-framework/cli-plugin-ai",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "6.0.3",
|
|
4
|
+
"description": "di-framework CLI extension for agent configuration and Agent Skills.",
|
|
5
|
+
"main": "./src/index.ts",
|
|
6
|
+
"types": "./src/index.ts",
|
|
7
|
+
"module": "./src/index.ts",
|
|
5
8
|
"type": "module",
|
|
6
9
|
"license": "(MIT OR Apache-2.0)",
|
|
7
10
|
"author": "@di-framework Contributors",
|
|
@@ -10,13 +13,37 @@
|
|
|
10
13
|
"url": "https://github.com/di-framework/cli-extensions",
|
|
11
14
|
"directory": "packages/cli-plugin-ai"
|
|
12
15
|
},
|
|
13
|
-
"
|
|
14
|
-
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/di-framework/cli-extensions/issues"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/di-framework/cli-extensions",
|
|
20
|
+
"keywords": [
|
|
21
|
+
"cli-plugin-ai",
|
|
22
|
+
"agent-skills",
|
|
23
|
+
"cli-extension",
|
|
24
|
+
"di-framework"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"test": "bun test",
|
|
28
|
+
"build": "bun -e \"console.log('@di-framework/cli-plugin-ai: source package')\""
|
|
29
|
+
},
|
|
15
30
|
"exports": {
|
|
16
|
-
".":
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./src/index.ts",
|
|
33
|
+
"bun": "./src/index.ts",
|
|
34
|
+
"import": "./src/index.ts",
|
|
35
|
+
"default": "./src/index.ts"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@di-framework/ai-utils": "^6",
|
|
40
|
+
"@di-framework/cli-extension": "^6"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@di-framework/cli": "^6"
|
|
17
44
|
},
|
|
18
|
-
"files": [
|
|
19
|
-
|
|
20
|
-
"
|
|
21
|
-
|
|
45
|
+
"files": [
|
|
46
|
+
"src",
|
|
47
|
+
"README.md"
|
|
48
|
+
]
|
|
22
49
|
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import type {
|
|
5
|
+
AgentConfigurationAuditFinding,
|
|
6
|
+
AgentConfigurationAuditReport,
|
|
7
|
+
AgentConfigurationAuditSeverity,
|
|
8
|
+
AuditAgentConfigurationOptions,
|
|
9
|
+
auditAgentConfiguration,
|
|
10
|
+
} from '@di-framework/ai-utils';
|
|
11
|
+
import { CommandFailure, type CommandResult, type JsonValue } from '@di-framework/cli-extension';
|
|
12
|
+
|
|
13
|
+
export type AgentAuditOperations = {
|
|
14
|
+
readonly auditAgentConfiguration: typeof auditAgentConfiguration;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const REPEATABLE_OPTIONS = new Set([
|
|
18
|
+
'--skills-dir',
|
|
19
|
+
'--skills-package',
|
|
20
|
+
'--instructions-fallback',
|
|
21
|
+
'--allowed-directory',
|
|
22
|
+
]);
|
|
23
|
+
const VALUE_OPTIONS = new Set([
|
|
24
|
+
'--workspace',
|
|
25
|
+
'--working-directory',
|
|
26
|
+
'--user-directory',
|
|
27
|
+
'--source-mode',
|
|
28
|
+
'--max-instruction-bytes',
|
|
29
|
+
]);
|
|
30
|
+
const SEVERITIES: readonly AgentConfigurationAuditSeverity[] = ['error', 'warning', 'info'];
|
|
31
|
+
const SEVERITY_LABELS: Readonly<Record<AgentConfigurationAuditSeverity, string>> = {
|
|
32
|
+
error: 'Errors',
|
|
33
|
+
warning: 'Warnings',
|
|
34
|
+
info: 'Info',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export function parseAgentAuditArgs(
|
|
38
|
+
args: readonly string[],
|
|
39
|
+
cwd = process.cwd(),
|
|
40
|
+
): AuditAgentConfigurationOptions {
|
|
41
|
+
const values = new Map<string, string>();
|
|
42
|
+
const repeated = new Map<string, string[]>();
|
|
43
|
+
for (let position = 0; position < args.length; position++) {
|
|
44
|
+
const option = args[position] ?? '';
|
|
45
|
+
if (!VALUE_OPTIONS.has(option) && !REPEATABLE_OPTIONS.has(option)) {
|
|
46
|
+
invalidUsage(`Unknown option or argument: ${option}`, option);
|
|
47
|
+
}
|
|
48
|
+
const value = args[++position];
|
|
49
|
+
if (value == null || value.startsWith('--')) {
|
|
50
|
+
invalidUsage(`Missing value for ${option}`, option);
|
|
51
|
+
}
|
|
52
|
+
if (REPEATABLE_OPTIONS.has(option)) {
|
|
53
|
+
repeated.set(option, [...(repeated.get(option) ?? []), value]);
|
|
54
|
+
} else {
|
|
55
|
+
if (values.has(option)) invalidUsage(`Option may be provided only once: ${option}`, option);
|
|
56
|
+
values.set(option, value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const workspace = resolve(cwd, values.get('--workspace') ?? '.');
|
|
61
|
+
const sourceMode = values.get('--source-mode');
|
|
62
|
+
if (sourceMode != null && sourceMode !== 'merge' && sourceMode !== 'replace') {
|
|
63
|
+
invalidUsage('--source-mode must be merge or replace', '--source-mode');
|
|
64
|
+
}
|
|
65
|
+
const maxBytesValue = values.get('--max-instruction-bytes');
|
|
66
|
+
const maxBytes = maxBytesValue == null ? undefined : Number(maxBytesValue);
|
|
67
|
+
if (maxBytes != null && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
|
|
68
|
+
invalidUsage(
|
|
69
|
+
'--max-instruction-bytes must be a non-negative safe integer',
|
|
70
|
+
'--max-instruction-bytes',
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
workspace,
|
|
76
|
+
workingDirectory: resolve(workspace, values.get('--working-directory') ?? cwd),
|
|
77
|
+
userDirectory: optionalResolved(workspace, values.get('--user-directory')),
|
|
78
|
+
directories: repeatedValues(repeated, '--skills-dir'),
|
|
79
|
+
packages: repeatedValues(repeated, '--skills-package'),
|
|
80
|
+
sourceMode,
|
|
81
|
+
fallbackFilenames: repeatedValues(repeated, '--instructions-fallback'),
|
|
82
|
+
maxBytes,
|
|
83
|
+
allowedDirectories: repeatedValues(repeated, '--allowed-directory')?.map((path) =>
|
|
84
|
+
resolve(workspace, path),
|
|
85
|
+
),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function runAgentAudit(
|
|
90
|
+
args: readonly string[],
|
|
91
|
+
operations?: AgentAuditOperations,
|
|
92
|
+
cwd = process.cwd(),
|
|
93
|
+
): Promise<CommandResult> {
|
|
94
|
+
const options = parseAgentAuditArgs(args, cwd);
|
|
95
|
+
const api = operations ?? (await loadAgentAuditOperations(cwd));
|
|
96
|
+
const report = api.auditAgentConfiguration(options);
|
|
97
|
+
return {
|
|
98
|
+
data: report as unknown as JsonValue,
|
|
99
|
+
text: formatAgentAuditText(report),
|
|
100
|
+
exitCode: report.valid ? 0 : 1,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function formatAgentAuditText(report: AgentConfigurationAuditReport): string {
|
|
105
|
+
const counts = new Map(
|
|
106
|
+
SEVERITIES.map((severity) => [
|
|
107
|
+
severity,
|
|
108
|
+
report.findings.filter((finding) => finding.severity === severity).length,
|
|
109
|
+
]),
|
|
110
|
+
);
|
|
111
|
+
const lines = [
|
|
112
|
+
`Agent configuration audit is ${report.valid ? 'valid' : 'invalid'}: ${counts.get('error')} error(s), ${counts.get('warning')} warning(s), ${counts.get('info')} info finding(s)`,
|
|
113
|
+
`Workspace: ${report.workspace}`,
|
|
114
|
+
`Working directory: ${report.workingDirectory}`,
|
|
115
|
+
];
|
|
116
|
+
for (const severity of SEVERITIES) {
|
|
117
|
+
const findings = report.findings.filter((finding) => finding.severity === severity);
|
|
118
|
+
lines.push(`${severityLabel(severity)} (${findings.length}):`);
|
|
119
|
+
if (findings.length === 0) lines.push(' (none)');
|
|
120
|
+
else for (const finding of findings) lines.push(...formatFinding(finding));
|
|
121
|
+
}
|
|
122
|
+
return lines.join('\n');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function formatFinding(finding: AgentConfigurationAuditFinding): string[] {
|
|
126
|
+
const metadata = [`provenance=${finding.provenance}`];
|
|
127
|
+
if (finding.precedence != null) metadata.push(`precedence=${finding.precedence}`);
|
|
128
|
+
if (finding.relatedPath != null) metadata.push(`related=${finding.relatedPath}`);
|
|
129
|
+
return [
|
|
130
|
+
` [${finding.code}] ${finding.path}: ${finding.message}`,
|
|
131
|
+
` ${metadata.join(', ')}`,
|
|
132
|
+
...(finding.action == null ? [] : [` Action: ${finding.action}`]),
|
|
133
|
+
];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function severityLabel(severity: AgentConfigurationAuditSeverity): string {
|
|
137
|
+
return SEVERITY_LABELS[severity];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function optionalResolved(base: string, value: string | undefined): string | undefined {
|
|
141
|
+
return value == null ? undefined : resolve(base, value);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function repeatedValues(
|
|
145
|
+
values: ReadonlyMap<string, readonly string[]>,
|
|
146
|
+
option: string,
|
|
147
|
+
): readonly string[] | undefined {
|
|
148
|
+
const entries = values.get(option);
|
|
149
|
+
return entries?.length ? entries : undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function loadAgentAuditOperations(cwd: string): Promise<AgentAuditOperations> {
|
|
153
|
+
try {
|
|
154
|
+
const projectRequire = createRequire(resolve(cwd, 'package.json'));
|
|
155
|
+
const modulePath = projectRequire.resolve('@di-framework/ai-utils');
|
|
156
|
+
return import(pathToFileURL(modulePath).href);
|
|
157
|
+
} catch (cause) {
|
|
158
|
+
throw new CommandFailure(
|
|
159
|
+
'AGENT_AUDIT_PACKAGE_UNAVAILABLE',
|
|
160
|
+
'Unable to load @di-framework/ai-utils from the current project',
|
|
161
|
+
3,
|
|
162
|
+
{ cause: cause instanceof Error ? cause.message : String(cause) },
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function invalidUsage(message: string, token: string): never {
|
|
168
|
+
throw new CommandFailure('INVALID_USAGE', message, 2, { token });
|
|
169
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import type {
|
|
5
|
+
AgentConfigurationMigrationExecutionResult,
|
|
6
|
+
AgentConfigurationMigrationPlan,
|
|
7
|
+
AgentConfigurationMigrationRequest,
|
|
8
|
+
auditAgentConfiguration,
|
|
9
|
+
executeAgentConfigurationMigration,
|
|
10
|
+
NeutralAgentAssetPath,
|
|
11
|
+
planAgentConfigurationMigration,
|
|
12
|
+
} from '@di-framework/ai-utils';
|
|
13
|
+
import { CommandFailure, type CommandResult, type JsonValue } from '@di-framework/cli-extension';
|
|
14
|
+
|
|
15
|
+
export type AgentInitOperations = {
|
|
16
|
+
readonly auditAgentConfiguration: typeof auditAgentConfiguration;
|
|
17
|
+
readonly planAgentConfigurationMigration: typeof planAgentConfigurationMigration;
|
|
18
|
+
readonly executeAgentConfigurationMigration: typeof executeAgentConfigurationMigration;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
interface ParsedAgentInitOptions {
|
|
22
|
+
readonly workspace: string;
|
|
23
|
+
readonly assets: readonly NeutralAgentAssetPath[];
|
|
24
|
+
readonly dryRun: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const NEUTRAL_ASSETS = [
|
|
28
|
+
'AGENTS.md',
|
|
29
|
+
'.agents/AGENTS.md',
|
|
30
|
+
'.agents/skills',
|
|
31
|
+
'.aiignore',
|
|
32
|
+
] as const satisfies readonly NeutralAgentAssetPath[];
|
|
33
|
+
|
|
34
|
+
const ASSET_CONTENT: Readonly<Record<Exclude<NeutralAgentAssetPath, '.agents/skills'>, string>> = {
|
|
35
|
+
'AGENTS.md': '# Repository instructions\n',
|
|
36
|
+
'.agents/AGENTS.md': '# Agent configuration instructions\n',
|
|
37
|
+
'.aiignore': '# Add paths that AI tools must ignore.\n',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export async function runAgentInit(
|
|
41
|
+
args: readonly string[],
|
|
42
|
+
operations?: AgentInitOperations,
|
|
43
|
+
cwd = process.cwd(),
|
|
44
|
+
): Promise<CommandResult> {
|
|
45
|
+
const options = parseAgentInitArgs(args, cwd);
|
|
46
|
+
const api = operations ?? (await loadAgentInitOperations(cwd));
|
|
47
|
+
const report = api.auditAgentConfiguration({
|
|
48
|
+
workspace: options.workspace,
|
|
49
|
+
workingDirectory: options.workspace,
|
|
50
|
+
sourceMode: 'replace',
|
|
51
|
+
});
|
|
52
|
+
const plan = api.planAgentConfigurationMigration(report, {
|
|
53
|
+
includeAuditOpportunities: false,
|
|
54
|
+
requests: options.assets.map(requestForAsset),
|
|
55
|
+
});
|
|
56
|
+
const execution = api.executeAgentConfigurationMigration(plan, { dryRun: options.dryRun });
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
data: { plan, execution } as unknown as JsonValue,
|
|
60
|
+
text: formatAgentInitText(plan, execution),
|
|
61
|
+
exitCode: plan.valid && execution.success ? 0 : 1,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function parseAgentInitArgs(args: readonly string[], cwd: string): ParsedAgentInitOptions {
|
|
66
|
+
let workspace = cwd;
|
|
67
|
+
let hasWorkspace = false;
|
|
68
|
+
let apply = false;
|
|
69
|
+
let explicitDryRun = false;
|
|
70
|
+
const assets: NeutralAgentAssetPath[] = [];
|
|
71
|
+
|
|
72
|
+
for (let position = 0; position < args.length; position++) {
|
|
73
|
+
const option = args[position] ?? '';
|
|
74
|
+
if (option === '--apply' || option === '--dry-run') {
|
|
75
|
+
if (option === '--apply') {
|
|
76
|
+
if (apply) invalidUsage('Option may be provided only once: --apply', option);
|
|
77
|
+
apply = true;
|
|
78
|
+
} else {
|
|
79
|
+
if (explicitDryRun) invalidUsage('Option may be provided only once: --dry-run', option);
|
|
80
|
+
explicitDryRun = true;
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (option !== '--workspace' && option !== '--asset') {
|
|
85
|
+
invalidUsage(`Unknown option or argument: ${option}`, option);
|
|
86
|
+
}
|
|
87
|
+
const value = args[++position];
|
|
88
|
+
if (value == null || value.startsWith('--')) {
|
|
89
|
+
invalidUsage(`Missing value for ${option}`, option);
|
|
90
|
+
}
|
|
91
|
+
if (option === '--workspace') {
|
|
92
|
+
if (hasWorkspace) invalidUsage('Option may be provided only once: --workspace', option);
|
|
93
|
+
workspace = resolve(cwd, value);
|
|
94
|
+
hasWorkspace = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (!isNeutralAsset(value)) {
|
|
98
|
+
invalidUsage(`--asset must be one of: ${NEUTRAL_ASSETS.join(', ')}`, option);
|
|
99
|
+
}
|
|
100
|
+
assets.push(value);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (apply && explicitDryRun) {
|
|
104
|
+
invalidUsage('--apply and --dry-run cannot be used together', '--apply');
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
workspace,
|
|
108
|
+
assets: assets.length === 0 ? NEUTRAL_ASSETS : assets,
|
|
109
|
+
dryRun: !apply,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isNeutralAsset(value: string): value is NeutralAgentAssetPath {
|
|
114
|
+
return (NEUTRAL_ASSETS as readonly string[]).includes(value);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function requestForAsset(asset: NeutralAgentAssetPath): AgentConfigurationMigrationRequest {
|
|
118
|
+
return asset === '.agents/skills'
|
|
119
|
+
? { target: asset }
|
|
120
|
+
: { target: asset, content: ASSET_CONTENT[asset] };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function formatAgentInitText(
|
|
124
|
+
plan: AgentConfigurationMigrationPlan,
|
|
125
|
+
execution: AgentConfigurationMigrationExecutionResult,
|
|
126
|
+
): string {
|
|
127
|
+
const actionPaths = new Map(plan.actions.map((action) => [action.id, action.relativeTargetPath]));
|
|
128
|
+
const lines = [
|
|
129
|
+
`Agent initialization plan for ${plan.workspace}`,
|
|
130
|
+
`Plan: ${plan.valid ? 'valid' : 'invalid'} (${plan.actions.length} actions)`,
|
|
131
|
+
...listOrNone(
|
|
132
|
+
plan.actions.map(
|
|
133
|
+
(action) =>
|
|
134
|
+
` [${action.status}:${action.code}] ${action.operation} ${action.relativeTargetPath} — ${action.message}`,
|
|
135
|
+
),
|
|
136
|
+
),
|
|
137
|
+
`Execution: ${execution.dryRun ? 'dry-run' : 'apply'} (${execution.success ? 'succeeded' : 'failed'})`,
|
|
138
|
+
` Applied: ${execution.applied.length}; skipped: ${execution.skipped.length}; failed: ${execution.failed.length}`,
|
|
139
|
+
...[...execution.applied, ...execution.skipped, ...execution.failed].map(
|
|
140
|
+
(result) =>
|
|
141
|
+
` [${result.status}:${result.code}] ${result.operation} ${actionPaths.get(result.actionId) ?? result.targetPath} — ${result.message}`,
|
|
142
|
+
),
|
|
143
|
+
];
|
|
144
|
+
return lines.join('\n');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function listOrNone(lines: readonly string[]): readonly string[] {
|
|
148
|
+
return lines.length === 0 ? [' (none)'] : lines;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function loadAgentInitOperations(cwd: string): Promise<AgentInitOperations> {
|
|
152
|
+
try {
|
|
153
|
+
const projectRequire = createRequire(resolve(cwd, 'package.json'));
|
|
154
|
+
const modulePath = projectRequire.resolve('@di-framework/ai-utils');
|
|
155
|
+
return import(pathToFileURL(modulePath).href);
|
|
156
|
+
} catch (cause) {
|
|
157
|
+
throw new CommandFailure(
|
|
158
|
+
'AGENT_INIT_PACKAGE_UNAVAILABLE',
|
|
159
|
+
'Unable to load @di-framework/ai-utils from the current project',
|
|
160
|
+
3,
|
|
161
|
+
{ cause: cause instanceof Error ? cause.message : String(cause) },
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function invalidUsage(message: string, token: string): never {
|
|
167
|
+
throw new CommandFailure('INVALID_USAGE', message, 2, { token });
|
|
168
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import type {
|
|
5
|
+
AiIgnorePolicyError,
|
|
6
|
+
discoverAgentInstructions,
|
|
7
|
+
loadAiIgnorePolicy,
|
|
8
|
+
resolveSkillSources,
|
|
9
|
+
validateResolvedSkillCatalog,
|
|
10
|
+
} from '@di-framework/ai-utils';
|
|
11
|
+
import { CommandFailure, type CommandResult, type JsonValue } from '@di-framework/cli-extension';
|
|
12
|
+
|
|
13
|
+
export type AgentInspectOperations = {
|
|
14
|
+
readonly resolveSkillSources: typeof resolveSkillSources;
|
|
15
|
+
readonly discoverAgentInstructions: typeof discoverAgentInstructions;
|
|
16
|
+
readonly loadAiIgnorePolicy: typeof loadAiIgnorePolicy;
|
|
17
|
+
readonly validateResolvedSkillCatalog: typeof validateResolvedSkillCatalog;
|
|
18
|
+
readonly AiIgnorePolicyError: typeof AiIgnorePolicyError;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
interface ParsedAgentInspectOptions {
|
|
22
|
+
readonly workspace: string;
|
|
23
|
+
readonly workingDirectory: string;
|
|
24
|
+
readonly userDirectory?: string;
|
|
25
|
+
readonly directories?: readonly string[];
|
|
26
|
+
readonly packages?: readonly string[];
|
|
27
|
+
readonly sourceMode?: 'merge' | 'replace';
|
|
28
|
+
readonly fallbackFilenames?: readonly string[];
|
|
29
|
+
readonly maxBytes?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const REPEATABLE_OPTIONS = new Set(['--skills-dir', '--skills-package', '--instructions-fallback']);
|
|
33
|
+
const VALUE_OPTIONS = new Set([
|
|
34
|
+
'--workspace',
|
|
35
|
+
'--working-directory',
|
|
36
|
+
'--user-directory',
|
|
37
|
+
'--source-mode',
|
|
38
|
+
'--max-instruction-bytes',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
export async function runAgentInspect(
|
|
42
|
+
args: readonly string[],
|
|
43
|
+
operations?: AgentInspectOperations,
|
|
44
|
+
cwd = process.cwd(),
|
|
45
|
+
): Promise<CommandResult> {
|
|
46
|
+
const options = parseAgentInspectArgs(args, cwd);
|
|
47
|
+
const api = operations ?? (await loadAgentInspectOperations(cwd));
|
|
48
|
+
try {
|
|
49
|
+
const skills = api.resolveSkillSources({
|
|
50
|
+
workspace: options.workspace,
|
|
51
|
+
userDirectory: options.userDirectory,
|
|
52
|
+
directories: options.directories,
|
|
53
|
+
packages: options.packages,
|
|
54
|
+
sourceMode: options.sourceMode,
|
|
55
|
+
});
|
|
56
|
+
const catalog = api.validateResolvedSkillCatalog(skills);
|
|
57
|
+
const instructions = api.discoverAgentInstructions({
|
|
58
|
+
workspace: options.workspace,
|
|
59
|
+
workingDirectory: options.workingDirectory,
|
|
60
|
+
fallbackFilenames: options.fallbackFilenames,
|
|
61
|
+
maxBytes: options.maxBytes,
|
|
62
|
+
});
|
|
63
|
+
const aiignore = api.loadAiIgnorePolicy({ workspace: options.workspace });
|
|
64
|
+
const result = {
|
|
65
|
+
workspace: options.workspace,
|
|
66
|
+
workingDirectory: options.workingDirectory,
|
|
67
|
+
skillRoots: skills.sources.map(({ path, realPath, origin, precedence }) => ({
|
|
68
|
+
path,
|
|
69
|
+
realPath,
|
|
70
|
+
origin,
|
|
71
|
+
precedence,
|
|
72
|
+
})),
|
|
73
|
+
instructionFiles: instructions.sources.map(
|
|
74
|
+
({ path, realPath, directory, filename, origin, precedence, bytes }) => ({
|
|
75
|
+
path,
|
|
76
|
+
realPath,
|
|
77
|
+
directory,
|
|
78
|
+
filename,
|
|
79
|
+
origin,
|
|
80
|
+
precedence,
|
|
81
|
+
bytes,
|
|
82
|
+
}),
|
|
83
|
+
),
|
|
84
|
+
aiignore: {
|
|
85
|
+
source: aiignore.source,
|
|
86
|
+
rules: aiignore.rules.map(
|
|
87
|
+
({ line, original, pattern, negated, directoryOnly, rootRelative }) => ({
|
|
88
|
+
line,
|
|
89
|
+
original,
|
|
90
|
+
pattern,
|
|
91
|
+
negated,
|
|
92
|
+
directoryOnly,
|
|
93
|
+
rootRelative,
|
|
94
|
+
}),
|
|
95
|
+
),
|
|
96
|
+
},
|
|
97
|
+
suppressedSources: [
|
|
98
|
+
...skills.diagnostics.map((diagnostic) => ({ scope: 'skills' as const, ...diagnostic })),
|
|
99
|
+
...instructions.diagnostics.map((diagnostic) => ({
|
|
100
|
+
scope: 'instructions' as const,
|
|
101
|
+
...diagnostic,
|
|
102
|
+
})),
|
|
103
|
+
],
|
|
104
|
+
shadowedSkills: catalog.diagnostics.filter(
|
|
105
|
+
(diagnostic) => diagnostic.code === 'skill-shadowed',
|
|
106
|
+
),
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
data: result as unknown as JsonValue,
|
|
110
|
+
text: formatAgentInspectText(result),
|
|
111
|
+
};
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (!(error instanceof api.AiIgnorePolicyError)) throw error;
|
|
114
|
+
throw new CommandFailure(`AGENT_INSPECT_${error.code}`, error.message, 2, {
|
|
115
|
+
policyCode: error.code,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function parseAgentInspectArgs(args: readonly string[], cwd: string): ParsedAgentInspectOptions {
|
|
121
|
+
const values = new Map<string, string>();
|
|
122
|
+
const repeated = new Map<string, string[]>();
|
|
123
|
+
for (let position = 0; position < args.length; position++) {
|
|
124
|
+
const option = args[position] ?? '';
|
|
125
|
+
if (!VALUE_OPTIONS.has(option) && !REPEATABLE_OPTIONS.has(option)) {
|
|
126
|
+
invalidUsage(`Unknown option or argument: ${option}`, option);
|
|
127
|
+
}
|
|
128
|
+
const value = args[++position];
|
|
129
|
+
if (value == null || value.startsWith('--')) {
|
|
130
|
+
invalidUsage(`Missing value for ${option}`, option);
|
|
131
|
+
}
|
|
132
|
+
if (REPEATABLE_OPTIONS.has(option)) {
|
|
133
|
+
repeated.set(option, [...(repeated.get(option) ?? []), value]);
|
|
134
|
+
} else {
|
|
135
|
+
if (values.has(option)) invalidUsage(`Option may be provided only once: ${option}`, option);
|
|
136
|
+
values.set(option, value);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const workspace = resolve(cwd, values.get('--workspace') ?? '.');
|
|
141
|
+
const sourceMode = values.get('--source-mode');
|
|
142
|
+
if (sourceMode != null && sourceMode !== 'merge' && sourceMode !== 'replace') {
|
|
143
|
+
invalidUsage('--source-mode must be merge or replace', '--source-mode');
|
|
144
|
+
}
|
|
145
|
+
const maxBytesValue = values.get('--max-instruction-bytes');
|
|
146
|
+
const maxBytes = maxBytesValue == null ? undefined : Number(maxBytesValue);
|
|
147
|
+
if (maxBytes != null && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
|
|
148
|
+
invalidUsage(
|
|
149
|
+
'--max-instruction-bytes must be a non-negative safe integer',
|
|
150
|
+
'--max-instruction-bytes',
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
workspace,
|
|
156
|
+
workingDirectory: resolve(workspace, values.get('--working-directory') ?? cwd),
|
|
157
|
+
userDirectory: optionalResolved(workspace, values.get('--user-directory')),
|
|
158
|
+
directories: repeatedValues(repeated, '--skills-dir'),
|
|
159
|
+
packages: repeatedValues(repeated, '--skills-package'),
|
|
160
|
+
sourceMode,
|
|
161
|
+
fallbackFilenames: repeatedValues(repeated, '--instructions-fallback'),
|
|
162
|
+
maxBytes,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function optionalResolved(base: string, value: string | undefined): string | undefined {
|
|
167
|
+
return value == null ? undefined : resolve(base, value);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function repeatedValues(
|
|
171
|
+
values: ReadonlyMap<string, readonly string[]>,
|
|
172
|
+
option: string,
|
|
173
|
+
): readonly string[] | undefined {
|
|
174
|
+
const entries = values.get(option);
|
|
175
|
+
return entries?.length ? entries : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function formatAgentInspectText(result: {
|
|
179
|
+
readonly workspace: string;
|
|
180
|
+
readonly workingDirectory: string;
|
|
181
|
+
readonly skillRoots: readonly {
|
|
182
|
+
readonly precedence: number;
|
|
183
|
+
readonly origin: string;
|
|
184
|
+
readonly path: string;
|
|
185
|
+
}[];
|
|
186
|
+
readonly instructionFiles: readonly { readonly precedence: number; readonly path: string }[];
|
|
187
|
+
readonly aiignore: {
|
|
188
|
+
readonly source: { readonly exists: boolean; readonly path: string };
|
|
189
|
+
readonly rules: readonly unknown[];
|
|
190
|
+
};
|
|
191
|
+
readonly suppressedSources: readonly {
|
|
192
|
+
readonly scope: string;
|
|
193
|
+
readonly code: string;
|
|
194
|
+
readonly path: string;
|
|
195
|
+
}[];
|
|
196
|
+
readonly shadowedSkills: readonly {
|
|
197
|
+
readonly skillName?: string;
|
|
198
|
+
readonly path: string;
|
|
199
|
+
readonly relatedPath?: string;
|
|
200
|
+
}[];
|
|
201
|
+
}): string {
|
|
202
|
+
const lines = [
|
|
203
|
+
`Agent configuration for ${result.workingDirectory}`,
|
|
204
|
+
`Workspace: ${result.workspace}`,
|
|
205
|
+
'Skill roots (highest precedence first):',
|
|
206
|
+
...listOrNone(
|
|
207
|
+
result.skillRoots.map(
|
|
208
|
+
(source) => ` ${source.precedence}. [${source.origin}] ${source.path}`,
|
|
209
|
+
),
|
|
210
|
+
),
|
|
211
|
+
'Instruction files (broad to specific):',
|
|
212
|
+
...listOrNone(
|
|
213
|
+
result.instructionFiles.map((source) => ` ${source.precedence}. ${source.path}`),
|
|
214
|
+
),
|
|
215
|
+
`.aiignore: ${result.aiignore.source.exists ? result.aiignore.source.path : 'not present'} (${result.aiignore.rules.length} rules)`,
|
|
216
|
+
'Suppressed sources:',
|
|
217
|
+
...listOrNone(
|
|
218
|
+
result.suppressedSources.map((source) => ` [${source.scope}:${source.code}] ${source.path}`),
|
|
219
|
+
),
|
|
220
|
+
'Shadowed skills:',
|
|
221
|
+
...listOrNone(
|
|
222
|
+
result.shadowedSkills.map(
|
|
223
|
+
(diagnostic) =>
|
|
224
|
+
` ${diagnostic.skillName ?? diagnostic.path} -> ${diagnostic.relatedPath ?? 'higher-precedence definition'}`,
|
|
225
|
+
),
|
|
226
|
+
),
|
|
227
|
+
];
|
|
228
|
+
return lines.join('\n');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function listOrNone(lines: readonly string[]): readonly string[] {
|
|
232
|
+
return lines.length === 0 ? [' (none)'] : lines;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function loadAgentInspectOperations(cwd: string): Promise<AgentInspectOperations> {
|
|
236
|
+
try {
|
|
237
|
+
const projectRequire = createRequire(resolve(cwd, 'package.json'));
|
|
238
|
+
const modulePath = projectRequire.resolve('@di-framework/ai-utils');
|
|
239
|
+
return import(pathToFileURL(modulePath).href);
|
|
240
|
+
} catch (cause) {
|
|
241
|
+
throw new CommandFailure(
|
|
242
|
+
'AGENT_INSPECT_PACKAGE_UNAVAILABLE',
|
|
243
|
+
'Unable to load @di-framework/ai-utils from the current project',
|
|
244
|
+
3,
|
|
245
|
+
{ cause: cause instanceof Error ? cause.message : String(cause) },
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function invalidUsage(message: string, token: string): never {
|
|
251
|
+
throw new CommandFailure('INVALID_USAGE', message, 2, { token });
|
|
252
|
+
}
|