Repository navigation
Expand file tree
/
Copy pathcommand-explain.ts
More file actions
353 lines (324 loc) · 12.6 KB
/
Copy pathcommand-explain.ts
File metadata and controls
353 lines (324 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { listCliCommandNames } from '@agent-device/command-registry/catalog';
import {
cliAliasesForCommand,
normalizeCliCommandAlias,
} from '@agent-device/command-registry/cli-command-aliases';
import { buildCommandUsage } from '../commands/schema/usage.ts';
import type { DaemonCommandRoute } from '@agent-device/command-registry/daemon-command-descriptor';
import { commandDescriptors, type Command } from '@agent-device/command-registry/registry';
import { ownerFilesForCommand } from '@agent-device/command-registry/owner-files';
import type { CommandTimeoutPolicy } from '@agent-device/command-registry/types';
import {
getCliCommandSchema,
getFlagDefinitions,
GLOBAL_FLAG_KEYS,
type CommandSchema,
type FlagDefinition,
type FlagKey,
} from '../commands/schema/command-schema.ts';
import { commandFamilies, type CommandFamilyMetadata } from '../commands/family/registry.ts';
export type CommandFlagExplanation = {
key: FlagKey;
syntax: string;
description?: string;
};
export type CommandAliasExplanation = {
/** User-typed CLI token the parser rewrites to this command. */
alias: string;
/** Flags the alias implicitly sets (e.g. `relaunch` => `open --relaunch`). */
impliedFlags?: FlagKey[];
};
export type CommandExplanation = {
command: Command;
aliases: CommandAliasExplanation[];
description: string;
catalog: { group: string; key: string };
family?: string;
daemon?: { route: string; traits: string[] };
exposure: {
batchable: boolean;
mcp: boolean;
postActionObservation?: string;
};
timeout: {
envelopeMs: number | 'unbounded';
onTimeout: 'preserve-daemon' | 'reset-daemon';
budget: string;
};
cli?: {
usage: string;
positionalArgs: readonly string[];
commandFlags: CommandFlagExplanation[];
supportedFlags: CommandFlagExplanation[];
globalFlags: CommandFlagExplanation[];
};
files: string[];
};
export type CommandExplanationResult =
| { found: true; explanation: CommandExplanation }
| { found: false; query: string; suggestions: string[] };
export type CommandExplanationFormatOptions = {
detail?: 'compact' | 'full';
};
type FileExists = (repoRelativePath: string) => boolean;
type CommandDescriptor = (typeof commandDescriptors)[number];
type CommandExplanationOptions = {
fileExists?: FileExists;
daemonRouteOwnerFiles: Readonly<Record<DaemonCommandRoute, string>>;
};
const descriptorByName: ReadonlyMap<string, CommandDescriptor> = new Map(
commandDescriptors.map((descriptor) => [descriptor.name, descriptor]),
);
const cliCommandNames = new Set<string>(listCliCommandNames());
const flagDefinitionsByKey = groupFlagDefinitions();
export function explainCommand(
query: string,
options: CommandExplanationOptions,
): CommandExplanationResult {
const descriptor = resolveDescriptor(query);
if (!descriptor) {
return { found: false, query, suggestions: suggestCommands(query) };
}
return {
found: true,
explanation: buildCommandExplanation(
descriptor,
options.fileExists,
options.daemonRouteOwnerFiles,
),
};
}
function buildCommandExplanation(
descriptor: CommandDescriptor,
fileExists: FileExists | undefined,
daemonRouteOwnerFiles: Readonly<Record<DaemonCommandRoute, string>>,
): CommandExplanation {
const family = commandFamilies.find((candidate) =>
candidate.metadata.some((metadata) => metadata.name === descriptor.name),
);
const cliSchema = cliCommandNames.has(descriptor.name)
? getCliCommandSchema(descriptor.name as Parameters<typeof getCliCommandSchema>[0])
: undefined;
const catalogKey = readCatalogKey(descriptor);
return {
command: descriptor.name,
aliases: describeCliAliases(descriptor.name),
description: describeCommandText(descriptor, family, cliSchema),
catalog: { group: descriptor.catalog.group, key: catalogKey },
...(family ? { family: family.name } : {}),
...describeCommandDaemon(descriptor),
exposure: describeCommandExposure(descriptor),
timeout: describeTimeoutPolicy(descriptor.timeoutPolicy),
...(cliSchema ? { cli: describeCliSurface(descriptor.name, cliSchema) } : {}),
files: commandFiles(
descriptor.name,
ownerFilesForCommand(descriptor.name),
family?.name,
'daemon' in descriptor ? descriptor.daemon?.route : undefined,
fileExists,
daemonRouteOwnerFiles,
),
};
}
export function formatCommandExplanation(
explanation: CommandExplanation,
options: CommandExplanationFormatOptions = {},
): string {
const full = options.detail === 'full';
const lines = [
`${explanation.command} [${explanation.catalog.group}]`,
explanation.description,
`catalog: ${explanation.catalog.key}${formatAliasSuffix(explanation.aliases)}`,
`family: ${explanation.family ?? 'none'}`,
explanation.daemon
? `daemon: ${explanation.daemon.route}${explanation.daemon.traits.length ? ` (${explanation.daemon.traits.join(', ')})` : ''}`
: 'daemon: none',
`exposure: batch=${yesNo(explanation.exposure.batchable)}, mcp=${yesNo(explanation.exposure.mcp)}${explanation.exposure.postActionObservation ? `, observe=${explanation.exposure.postActionObservation}` : ''}`,
`timeout: envelope=${formatEnvelope(explanation.timeout.envelopeMs)}, on-timeout=${explanation.timeout.onTimeout}, budget=${explanation.timeout.budget}`,
];
if (explanation.cli) {
lines.push(`usage: ${explanation.cli.usage}`);
lines.push(`flags: ${formatFlagList(explanation.cli.commandFlags)}`);
if (full) {
lines.push(`supported: ${formatFlagList(explanation.cli.supportedFlags)}`);
lines.push(`global: ${formatFlagList(explanation.cli.globalFlags)}`);
}
}
lines.push('files:', ...explanation.files.map((file) => ` ${file}`));
return lines.join('\n');
}
function resolveDescriptor(query: string): CommandDescriptor | undefined {
const direct = descriptorByName.get(normalizeCliCommandAlias(query));
if (direct) return direct;
return commandDescriptors.find((descriptor) => readCatalogKey(descriptor) === query);
}
function describeCliAliases(command: string): CommandAliasExplanation[] {
return cliAliasesForCommand(command).map((entry) => ({
alias: entry.alias,
...(entry.impliedFlags && entry.impliedFlags.length > 0
? { impliedFlags: [...entry.impliedFlags] }
: {}),
}));
}
function formatAliasSuffix(aliases: readonly CommandAliasExplanation[]): string {
if (aliases.length === 0) return '';
const rendered = aliases.map((entry) =>
entry.impliedFlags && entry.impliedFlags.length > 0
? `${entry.alias} (implies ${entry.impliedFlags.map((flag) => `--${flag}`).join(' ')})`
: entry.alias,
);
return ` (alias: ${rendered.join(', ')})`;
}
function readCatalogKey(descriptor: CommandDescriptor): string {
return 'key' in descriptor.catalog && descriptor.catalog.key
? descriptor.catalog.key
: descriptor.name;
}
function describeCommandText(
descriptor: CommandDescriptor,
family: (typeof commandFamilies)[number] | undefined,
cliSchema: CommandSchema | undefined,
): string {
const metadata = family?.metadata.find(
(candidate): candidate is CommandFamilyMetadata => candidate.name === descriptor.name,
);
return (
metadata?.description ?? cliSchema?.text.description ?? `Internal command ${descriptor.name}`
);
}
function describeCommandDaemon(descriptor: CommandDescriptor): Pick<CommandExplanation, 'daemon'> {
if (!('daemon' in descriptor) || !descriptor.daemon) return {};
return {
daemon: {
route: descriptor.daemon.route,
traits: describeDaemonTraits(descriptor.daemon),
},
};
}
function describeCommandExposure(descriptor: CommandDescriptor): CommandExplanation['exposure'] {
return {
batchable: descriptor.batchable,
mcp: descriptor.mcpExposed,
...('postActionObservation' in descriptor && descriptor.postActionObservation
? { postActionObservation: descriptor.postActionObservation }
: {}),
};
}
function suggestCommands(query: string): string[] {
const candidates = commandDescriptors.flatMap((descriptor) => [
descriptor.name,
readCatalogKey(descriptor),
...cliAliasesForCommand(descriptor.name).map((alias) => alias.alias),
]);
return [...new Set(candidates)]
.map((candidate) => ({ candidate, distance: levenshtein(query, candidate) }))
.sort(
(left, right) =>
left.distance - right.distance || left.candidate.localeCompare(right.candidate),
)
.slice(0, 3)
.map(({ candidate }) => candidate);
}
function describeDaemonTraits(daemon: { route: string } & Record<string, unknown>): string[] {
return Object.entries(daemon)
.filter(([key]) => key !== 'route')
.map(([key, value]) => `${key}=${describeTraitValue(value)}`)
.sort();
}
function describeTraitValue(value: unknown): string {
if (typeof value === 'function') return 'derived-policy';
if (value === undefined) return 'undefined';
if (value === null || typeof value !== 'object') return String(value);
return JSON.stringify(value);
}
function describeTimeoutPolicy(policy: CommandTimeoutPolicy): CommandExplanation['timeout'] {
const budget =
policy.budget.source === 'none'
? 'none'
: policy.budget.source === 'positional-parser'
? 'positional'
: `flag:${policy.budget.envelope ?? 'bound'}${policy.budget.defaultBudgetMs === undefined ? '' : `:default=${policy.budget.defaultBudgetMs}ms`}`;
return { envelopeMs: policy.envelopeMs, onTimeout: policy.onTimeout, budget };
}
function describeCliSurface(command: string, schema: CommandSchema): CommandExplanation['cli'] {
return {
usage: buildCommandUsage(command, schema),
positionalArgs: schema.positionalArgs ?? [],
commandFlags: describeFlags(schema.allowedFlags ?? [], schema.flagDescriptionOverrides),
supportedFlags: describeFlags(schema.supportedFlags ?? [], schema.flagDescriptionOverrides),
globalFlags: describeFlags([...GLOBAL_FLAG_KEYS]),
};
}
function describeFlags(
keys: readonly FlagKey[],
overrides?: Partial<Record<FlagKey, string>>,
): CommandFlagExplanation[] {
return [...new Set(keys)].sort().map((key) => {
const definitions = flagDefinitionsByKey.get(key) ?? [];
const preferred = definitions.find((definition) => definition.usageLabel) ?? definitions[0];
const description = overrides?.[key] ?? preferred?.usageDescription;
return {
key,
syntax:
preferred?.usageLabel ??
[...new Set(definitions.flatMap((definition) => definition.names))].join('/'),
...(description ? { description } : {}),
};
});
}
function groupFlagDefinitions(): Map<FlagKey, FlagDefinition[]> {
const result = new Map<FlagKey, FlagDefinition[]>();
for (const definition of getFlagDefinitions()) {
const existing = result.get(definition.key);
if (existing) existing.push(definition);
else result.set(definition.key, [definition]);
}
return result;
}
function commandFiles(
command: string,
ownerFiles: readonly string[],
family: string | undefined,
daemonRoute: DaemonCommandRoute | undefined,
fileExists: FileExists | undefined,
daemonRouteOwnerFiles: Readonly<Record<DaemonCommandRoute, string>>,
): string[] {
const derived = ['packages/command-registry/src/registry.ts'];
const opportunistic: string[] = [];
if (family) {
derived.push(`src/commands/${family}/index.ts`);
opportunistic.push(
`src/commands/${family}/${command}.test.ts`,
`src/commands/${family}/index.test.ts`,
);
} else if (cliCommandNames.has(command)) {
derived.push('src/commands/schema/command-overrides.ts');
}
if (daemonRoute) derived.push(daemonRouteOwnerFiles[daemonRoute]);
const present = fileExists ? opportunistic.filter(fileExists) : opportunistic;
return [...new Set([...derived, ...ownerFiles, ...present])];
}
function formatFlagList(flags: readonly CommandFlagExplanation[]): string {
return flags.length === 0 ? 'none' : flags.map((flag) => flag.syntax || flag.key).join(', ');
}
function formatEnvelope(envelope: number | 'unbounded'): string {
return envelope === 'unbounded' ? envelope : `${envelope}ms`;
}
function yesNo(value: boolean): string {
return value ? 'yes' : 'no';
}
function levenshtein(left: string, right: string): number {
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
const current = [leftIndex];
for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
current[rightIndex] = Math.min(
current[rightIndex - 1]! + 1,
previous[rightIndex]! + 1,
previous[rightIndex - 1]! + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
);
}
previous.splice(0, previous.length, ...current);
}
return previous[right.length]!;
}