@kosuke-ai/kosuke 1.0.58 → 1.0.60

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 (80) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +31 -2
  3. package/dist/commands/hand-written.js +15 -0
  4. package/dist/commands/help.js +52 -0
  5. package/dist/generated/commands/crons/create--personal.js +2 -1
  6. package/dist/generated/commands/crons/update--personal.js +2 -1
  7. package/dist/generated/commands/deploys/queue-update.js +2 -1
  8. package/dist/generated/commands/find/index.js +17 -0
  9. package/dist/generated/commands/index.js +279 -291
  10. package/dist/generated/commands/integrations/tools-call.js +2 -1
  11. package/dist/generated/commands/projects/batch-merging-get.js +1 -1
  12. package/dist/generated/commands/projects/batch-merging-picks-set.js +2 -1
  13. package/dist/generated/commands/projects/batch-merging-set.js +19 -1
  14. package/dist/generated/commands/projects/create.js +21 -9
  15. package/dist/generated/commands/projects/labels-delete.js +2 -1
  16. package/dist/generated/commands/projects/live-logs-list.js +1 -1
  17. package/dist/generated/commands/projects/live-queries-run.js +1 -1
  18. package/dist/generated/commands/projects/live-traffic-get.js +1 -1
  19. package/dist/generated/commands/projects/releases-list.js +1 -1
  20. package/dist/generated/commands/projects/services-create.js +6 -3
  21. package/dist/generated/commands/projects/services-update.js +6 -3
  22. package/dist/generated/commands/projects/settings-set.js +4 -2
  23. package/dist/generated/commands/projects/versions-list.js +1 -1
  24. package/dist/generated/commands/sensei/cards-mark-read.js +1 -1
  25. package/dist/generated/commands/sensei/cards-set.js +40 -10
  26. package/dist/generated/commands/sensei/connect-buttons-create.js +2 -1
  27. package/dist/generated/commands/sensei/describe-cards-create.js +1 -1
  28. package/dist/generated/commands/sensei/messages-send.js +2 -1
  29. package/dist/generated/commands/sensei/sessions-assessments-create.js +3 -1
  30. package/dist/generated/commands/sensei/sessions-facts-get.js +1 -1
  31. package/dist/generated/commands/sensei/suggestions-create.js +2 -1
  32. package/dist/generated/commands/sensei/threads-get.js +8 -1
  33. package/dist/generated/commands/sensei/threads-split.js +2 -1
  34. package/dist/generated/commands/sensei/tickets-merge.js +4 -2
  35. package/dist/generated/commands/sensei/watch-reads-finish.js +4 -2
  36. package/dist/generated/commands/sensei/writing-samples-create.js +2 -1
  37. package/dist/generated/commands/sessions/get.js +1 -1
  38. package/dist/generated/commands/sessions/labels-set.js +6 -3
  39. package/dist/generated/commands/sessions/labels-update.js +4 -2
  40. package/dist/generated/commands/sessions/list--all.js +2 -3
  41. package/dist/generated/commands/sessions/qa-runs-finish.js +2 -1
  42. package/dist/generated/commands/sessions/qa-runs-results-create.js +2 -1
  43. package/dist/generated/commands/sessions/qa-runs-start.js +2 -1
  44. package/dist/generated/commands/sessions/queue-update.js +2 -1
  45. package/dist/generated/commands/sessions/send.js +4 -2
  46. package/dist/generated/commands/sessions/update.js +2 -1
  47. package/dist/generated/commands/skills/create--personal.js +2 -1
  48. package/dist/generated/commands/skills/create.js +2 -1
  49. package/dist/generated/commands/skills/update--personal.js +2 -1
  50. package/dist/generated/commands/skills/update.js +2 -1
  51. package/dist/generated/commands/tasks/create--personal.js +235 -11
  52. package/dist/generated/commands/tasks/create.js +1 -1
  53. package/dist/generated/commands/tasks/delete--personal.js +6 -3
  54. package/dist/generated/commands/tasks/get--personal.js +6 -3
  55. package/dist/generated/commands/tasks/list--all.js +1 -1
  56. package/dist/generated/commands/tasks/list--personal.js +91 -9
  57. package/dist/generated/commands/tasks/move--personal.js +7 -4
  58. package/dist/generated/commands/tasks/start--personal.js +6 -3
  59. package/dist/generated/commands/tasks/update--personal.js +85 -10
  60. package/dist/generated/commands/tasks/update.js +3 -2
  61. package/dist/generated/commands/user/personal-space-get.js +19 -0
  62. package/dist/generated/commands/workspaces/sandboxes-stop.js +2 -1
  63. package/dist/program.js +13 -2
  64. package/dist/runtime/arguments.js +58 -0
  65. package/dist/runtime/attach.js +177 -18
  66. package/dist/runtime/help.js +398 -0
  67. package/dist/runtime/personal-space-id.js +26 -0
  68. package/dist/runtime/personal-space.js +10 -0
  69. package/dist/runtime/runtime.js +25 -5
  70. package/dist/runtime/thread-text.js +316 -0
  71. package/openapi.json +321 -599
  72. package/package.json +11 -4
  73. package/dist/generated/commands/projects/backlog-items-create.js +0 -35
  74. package/dist/generated/commands/projects/backlog-items-delete.js +0 -20
  75. package/dist/generated/commands/projects/backlog-items-list.js +0 -19
  76. package/dist/generated/commands/projects/backlog-items-send.js +0 -20
  77. package/dist/generated/commands/projects/backlog-items-update.js +0 -42
  78. package/dist/generated/commands/projects/live-writes-create.js +0 -38
  79. package/dist/generated/commands/projects/live-writes-get.js +0 -21
  80. package/dist/generated/commands/projects/workflow-set.js +0 -33
@@ -1,6 +1,11 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { Argument, Command, InvalidArgumentError, Option } from 'commander';
3
+ import { addsSessionIdFlag, CLI_ONLY_FLAGS, omitsProject, SESSION_ID_FLAG, sessionIdField, } from './arguments.js';
4
+ import { setAfterHelp, setOptionShape, shortSummary, usageError } from './help.js';
3
5
  import { buildRequest, execute, readWholeBody, UsageError } from './invoke.js';
6
+ import { PERSONAL_SPACE_PARAM } from './personal-space.js';
7
+ import { personalSpaceId } from './personal-space-id.js';
8
+ import { threadView, TOOLS_FLAG_HELP } from './thread-text.js';
4
9
  import { fieldsOf, formLabel, formUsage, leafShape, pathParamsFor, PERSONAL, scopeOf, selectForm, } from './variants.js';
5
10
  /**
6
11
  * One commander command per command name: positionals for path params, a flag per
@@ -22,43 +27,162 @@ function attachLeaf(root, path, operation, runtime, hidden) {
22
27
  const parent = groupFor(root, path.slice(0, -1));
23
28
  const leaf = parent.command(path[path.length - 1], { hidden });
24
29
  leaf.description(operation.summary);
30
+ // `projectId, sessionId, ...`: commander takes one fewer, the project looked up (sessionArgs).
31
+ const lookup = omitsProject(operation);
25
32
  for (const name of operation.pathParams) {
26
- leaf.addArgument(new Argument(`<${name}>`, humanize(name)));
33
+ leaf.addArgument(lookup
34
+ ? new Argument(`[${name}]`, name === 'projectId' ? 'Project id; left out, read from the session.' : humanize(name))
35
+ : new Argument(`<${name}>`, humanize(name)));
36
+ }
37
+ if (lookup) {
38
+ leaf.usage(['[options]', '[projectId]', ...operation.pathParams.slice(1).map((n) => `<${n}>`)].join(' '));
39
+ }
40
+ const sessionField = sessionIdField(operation);
41
+ if (sessionField) {
42
+ leaf.addArgument(new Argument('[sessionId]', `Session id, as --${SESSION_ID_FLAG}.`));
27
43
  }
28
44
  const fields = fieldsOf(operation);
29
45
  for (const field of fields)
30
46
  addFieldOptions(leaf, field, field.description ?? '');
47
+ if (addsSessionIdFlag(operation)) {
48
+ leaf.addOption(new Option(`--${SESSION_ID_FLAG} <id>`, 'Session id, in place of <sessionId>; the project is read from it.'));
49
+ }
50
+ const view = VIEWS[operation.command.join(' ')];
51
+ for (const flag of CLI_ONLY_FLAGS[operation.command.join(' ')] ?? []) {
52
+ leaf.addOption(new Option(flag, view?.flags[flag] ?? ''));
53
+ }
31
54
  addBodyOptions(leaf, operation);
32
55
  leaf.action(async (...args) => {
33
56
  const options = args[args.length - 2];
34
- const positionals = args.slice(0, operation.pathParams.length);
57
+ const operands = args.slice(0, args.length - 2);
58
+ const positionals = operands.slice(0, operation.pathParams.length);
59
+ let session = null;
35
60
  try {
36
61
  checkFileFlags(options, fields.filter((field) => field.file).map((field) => field.flag));
62
+ if (lookup)
63
+ session = sessionArgs(operation, operands, options);
37
64
  // Refuse `personal` where a workspace id goes on a command with no personal form.
38
- if (!operation.variant)
65
+ else if (!operation.variant) {
39
66
  selectForm([operation], { first: positionals[0], flags: {} });
67
+ }
40
68
  }
41
69
  catch (error) {
42
70
  if (error instanceof UsageError)
43
- leaf.error(error.message);
71
+ usageError(leaf, error.message);
44
72
  throw error;
45
73
  }
46
74
  const values = Object.fromEntries(fields.map((field) => [
47
75
  field.name,
48
76
  options[optionKey(field.flag)] ?? fileValue(field, options),
49
77
  ]));
78
+ if (sessionField) {
79
+ const positional = operands[operation.pathParams.length];
80
+ const flagged = values[sessionField.name];
81
+ if (positional !== undefined && flagged !== undefined && positional !== flagged) {
82
+ usageError(leaf, `the session id is given twice, as ${positional} and ${String(flagged)}.`);
83
+ }
84
+ values[sessionField.name] = flagged ?? positional;
85
+ }
86
+ let pathParams = Object.fromEntries(operation.pathParams.map((name, i) => [name, positionals[i]]));
87
+ if (session) {
88
+ const projectId = session.params.projectId ?? (await projectOf(runtime, session.sessionId));
89
+ if (projectId === null)
90
+ return;
91
+ pathParams = { ...session.params, projectId };
92
+ }
50
93
  await run(leaf, runtime, operation, {
51
- pathParams: Object.fromEntries(operation.pathParams.map((name, i) => [name, positionals[i]])),
94
+ pathParams,
52
95
  fields: values,
53
96
  wholeBody: readWholeBody({
54
97
  body: options.body,
55
98
  bodyFile: options.bodyFile,
56
99
  }),
57
100
  attachments: options.attach ?? [],
58
- });
101
+ }, options);
59
102
  });
60
103
  return leaf;
61
104
  }
105
+ /**
106
+ * A command's own view of its response and the CLI-only flags (`CLI_ONLY_FLAGS`) that shape
107
+ * it; an error passes through unchanged.
108
+ */
109
+ const VIEWS = {
110
+ 'sensei threads get': {
111
+ flags: { '--tools': TOOLS_FLAG_HELP },
112
+ view: (body, options) => threadView(body, { tools: options.tools === true }),
113
+ },
114
+ };
115
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
116
+ /**
117
+ * The path params of a `projectId, sessionId, ...` command: all of them, one fewer with the
118
+ * project left out, or `--session-id` in the session's place with or without the project.
119
+ */
120
+ function sessionArgs(operation, operands, options) {
121
+ const names = operation.pathParams;
122
+ const given = operands.slice(0, names.length).filter((value) => value !== undefined);
123
+ const flagged = addsSessionIdFlag(operation)
124
+ ? options[optionKey(SESSION_ID_FLAG)]
125
+ : undefined;
126
+ const rest = names.slice(2);
127
+ const expected = `<sessionId>${rest.map((name) => ` <${name}>`).join('')}`;
128
+ let projectId;
129
+ let sessionId;
130
+ let after;
131
+ if (flagged !== undefined) {
132
+ if (given.length === rest.length + 1)
133
+ [projectId, ...after] = given;
134
+ else if (given.length === rest.length)
135
+ after = given;
136
+ else {
137
+ throw new UsageError(`with --${SESSION_ID_FLAG}, give ${rest.length ? `[projectId] ${rest.map((n) => `<${n}>`).join(' ')}` : 'at most the project id'}; got ${given.length} argument${given.length === 1 ? '' : 's'}.`);
138
+ }
139
+ sessionId = flagged;
140
+ }
141
+ else if (given.length === names.length) {
142
+ [projectId, sessionId, ...after] = given;
143
+ // Both given: sent as typed, as before.
144
+ return { sessionId, params: Object.fromEntries(names.map((name, i) => [name, given[i]])) };
145
+ }
146
+ else if (given.length === names.length - 1) {
147
+ [sessionId, ...after] = given;
148
+ }
149
+ else {
150
+ throw new UsageError(`expected [projectId] ${expected}; got ${given.length} argument${given.length === 1 ? '' : 's'}.`);
151
+ }
152
+ if (!UUID.test(sessionId)) {
153
+ throw new UsageError(`${sessionId} is not a session id; expected [projectId] ${expected}.`);
154
+ }
155
+ return {
156
+ sessionId,
157
+ params: {
158
+ ...(projectId === undefined ? {} : { projectId }),
159
+ sessionId,
160
+ ...Object.fromEntries(rest.map((name, i) => [name, after[i]])),
161
+ },
162
+ };
163
+ }
164
+ /** The session's project, by the lookup `kosuke find` runs; null once the failure is printed. */
165
+ async function projectOf(runtime, sessionId) {
166
+ const outcome = await execute(runtime.client(), {
167
+ method: 'get',
168
+ path: '/api/find/{query}',
169
+ pathParams: { query: sessionId },
170
+ query: {},
171
+ body: null,
172
+ });
173
+ if (!outcome.ok) {
174
+ runtime.output(outcome);
175
+ return null;
176
+ }
177
+ const rows = outcome.body?.data;
178
+ const row = (Array.isArray(rows) ? rows : []).find((candidate) => candidate.match === 'session' &&
179
+ typeof candidate.sessionId === 'string' &&
180
+ candidate.sessionId.toLowerCase() === sessionId.toLowerCase());
181
+ if (typeof row?.projectId === 'string')
182
+ return row.projectId;
183
+ runtime.output({ ok: false, status: 404, body: `error: no session ${sessionId} in your reach.` });
184
+ return null;
185
+ }
62
186
  /** A leaf over several forms: the union of their flags, the form picked per call. */
63
187
  function attachForms(root, forms, runtime, reachable) {
64
188
  const path = forms[0].command;
@@ -111,8 +235,10 @@ function attachForms(root, forms, runtime, reachable) {
111
235
  multipart: forms.find((form) => form.multipart)?.multipart ?? null,
112
236
  attachments: forms.find((form) => form.attachments)?.attachments ?? false,
113
237
  });
114
- leaf.addHelpText('after', () => '\nForms:\n' +
115
- visible.map((form) => ` ${formUsage(form, shape)}\n ${form.summary}`).join('\n'));
238
+ setAfterHelp(leaf, (long) => '\nForms:\n' +
239
+ visible
240
+ .map((form) => ` ${formUsage(form, shape)}\n ${long ? form.summary : shortSummary(form.summary)}`)
241
+ .join('\n'));
116
242
  leaf.action(async (...args) => {
117
243
  const options = args[args.length - 2];
118
244
  const operands = args.slice(0, args.length - 2);
@@ -157,20 +283,28 @@ function attachForms(root, forms, runtime, reachable) {
157
283
  }
158
284
  throw error;
159
285
  }
286
+ const pathParams = pathParamsFor(form, shape, first, positionals, given);
287
+ const wholeBody = readWholeBody({
288
+ body: options.body,
289
+ bodyFile: options.bodyFile,
290
+ });
291
+ if (form.personalSpace) {
292
+ const id = await personalSpaceId(runtime);
293
+ if (id === null)
294
+ return;
295
+ pathParams[PERSONAL_SPACE_PARAM] = id;
296
+ }
160
297
  await run(leaf, runtime, form, {
161
- pathParams: pathParamsFor(form, shape, first, positionals, given),
298
+ pathParams,
162
299
  fields,
163
- wholeBody: readWholeBody({
164
- body: options.body,
165
- bodyFile: options.bodyFile,
166
- }),
300
+ wholeBody,
167
301
  attachments: options.attach ?? [],
168
302
  });
169
303
  });
170
304
  return leaf;
171
305
  }
172
306
  /** Build, send and print; a usage error is commander's, so it prints as one. */
173
- async function run(leaf, runtime, operation, input) {
307
+ async function run(leaf, runtime, operation, input, options = {}) {
174
308
  let request;
175
309
  try {
176
310
  request = buildRequest(operation, input);
@@ -194,7 +328,8 @@ async function run(leaf, runtime, operation, input) {
194
328
  }
195
329
  try {
196
330
  const outcome = await execute(client, request, controller.signal);
197
- runtime.output(outcome);
331
+ const view = VIEWS[operation.command.join(' ')]?.view;
332
+ runtime.output(view && outcome.ok ? { ...outcome, body: view(outcome.body, options) } : outcome);
198
333
  }
199
334
  finally {
200
335
  process.removeListener('SIGINT', cancel);
@@ -230,13 +365,18 @@ function parseForForm(field, raw) {
230
365
  if (field.kind === 'number' || field.kind === 'integer')
231
366
  return numberParser(field)(raw);
232
367
  if (field.kind === 'json')
233
- return jsonParser(raw);
368
+ return isOwnerRepo(field) ? ownerRepoParser(raw) : jsonParser(raw);
234
369
  if (field.kind === 'boolean')
235
370
  return raw === 'true';
236
371
  return field.repeated ? [raw] : raw;
237
372
  }
238
373
  function addFieldOptions(leaf, field, description) {
239
- leaf.addOption(optionFor({ ...field, description }));
374
+ const option = optionFor({
375
+ ...field,
376
+ description: isOwnerRepo(field) ? `owner/repo, or JSON. ${description}`.trim() : description,
377
+ });
378
+ setOptionShape(option, field.shape);
379
+ leaf.addOption(option);
240
380
  if (field.file) {
241
381
  leaf.addOption(new Option(`--${field.flag}-file <path>`, `Read ${field.name} from a file, or - for stdin.`));
242
382
  }
@@ -281,9 +421,28 @@ function optionFor(field) {
281
421
  if (field.kind === 'number' || field.kind === 'integer')
282
422
  option.argParser(numberParser(field));
283
423
  if (field.kind === 'json')
284
- option.argParser(jsonParser);
424
+ option.argParser(isOwnerRepo(field) ? ownerRepoParser : jsonParser);
285
425
  return option;
286
426
  }
427
+ /** A repository field: `{owner, name}` on the wire, `owner/repo` on the command line too. */
428
+ function isOwnerRepo(field) {
429
+ if (field.kind !== 'json' || field.repeated)
430
+ return false;
431
+ return (field.name === 'repository' ||
432
+ (typeof field.shape === 'string' && /^\{owner: string, name: string[,}]/.test(field.shape)));
433
+ }
434
+ const OWNER_REPO = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/;
435
+ function ownerRepoParser(raw) {
436
+ const match = OWNER_REPO.exec(raw);
437
+ if (match)
438
+ return { owner: match[1], name: match[2] };
439
+ try {
440
+ return JSON.parse(raw);
441
+ }
442
+ catch {
443
+ throw new InvalidArgumentError('Expected owner/repo or JSON.');
444
+ }
445
+ }
287
446
  /**
288
447
  * One value per flag, collected into the array the wire takes. `choices` is
289
448
  * set for the help text and then overridden, because its own parser keeps
@@ -0,0 +1,398 @@
1
+ import { Help } from 'commander';
2
+ /**
3
+ * The help an agent reads. Short by default: the usage line, the description's first sentence
4
+ * and one line per flag. `--help --long` prints the whole text. `kosuke help --compact` prints
5
+ * the tree in one screen, and a call that names no command or flag says which one it meant.
6
+ */
7
+ /** A line of the short help holds this many characters of a description. */
8
+ const SHORT_WIDTH = 60;
9
+ const LONG_HELP_FLAG = '--long';
10
+ const FULL_TEXT = 'Full text: --help --long';
11
+ const CARD_RULES = 'Card rules: kosuke sensei cards schema [field]';
12
+ /** Text a leaf prints after its flags (a `Forms:` list), by whether the help is long. */
13
+ const afterText = new WeakMap();
14
+ /** A `json` flag's shape, printed after its description in the long help. */
15
+ const optionShapes = new WeakMap();
16
+ /** The configurations `helpConfiguration` made, which print the after-text themselves. */
17
+ const configurations = new WeakSet();
18
+ export function setAfterHelp(leaf, text) {
19
+ afterText.set(leaf, text);
20
+ // A tree built without this help, as a test builds one, still prints it, in full.
21
+ leaf.addHelpText('after', () => (configurations.has(leaf.configureHelp()) ? '' : text(true)));
22
+ }
23
+ export function setOptionShape(option, shape) {
24
+ if (shape)
25
+ optionShapes.set(option, shape);
26
+ }
27
+ /**
28
+ * `run()` reads `--long` beside `--help`, `-h` or `kosuke help` before commander parses, and
29
+ * drops it.
30
+ */
31
+ export function takeLongHelp(argv) {
32
+ const args = argv.slice(2);
33
+ const asksHelp = args.includes('--help') || args.includes('-h') || args[0] === 'help';
34
+ if (!asksHelp || !args.includes(LONG_HELP_FLAG))
35
+ return { argv: [...argv], long: false };
36
+ return { argv: [...argv.slice(0, 2), ...args.filter((a) => a !== LONG_HELP_FLAG)], long: true };
37
+ }
38
+ /**
39
+ * The text up to its first sentence's end: a `.`, `!` or `?` followed by a space and a capital,
40
+ * a backtick or a parenthesis, or by the end.
41
+ */
42
+ function firstSentence(text) {
43
+ const flat = text.replace(/\s+/g, ' ').trim();
44
+ const end = /[.!?](?=\s+[A-Z`("]|$)/.exec(flat);
45
+ return end ? flat.slice(0, end.index + 1) : flat;
46
+ }
47
+ /**
48
+ * At most `SHORT_WIDTH` characters, ending `…` when cut: at the first clause break (`:`, `;`,
49
+ * `,`, ` (`) past 20 characters, or else at a word.
50
+ */
51
+ function oneLine(text) {
52
+ if (text.length <= SHORT_WIDTH)
53
+ return text;
54
+ const room = text.slice(0, SHORT_WIDTH - 1);
55
+ const clause = /[:;,]| \(/g;
56
+ clause.lastIndex = 20;
57
+ const brk = clause.exec(room)?.index ?? -1;
58
+ const space = room.lastIndexOf(' ');
59
+ const end = brk >= 20 ? brk : space > SHORT_WIDTH / 2 ? space : room.length;
60
+ return `${room.slice(0, end).replace(/[\s,;:]+$/, '')}…`;
61
+ }
62
+ function commandPath(command) {
63
+ const words = [];
64
+ for (let current = command; current?.parent; current = current.parent) {
65
+ words.unshift(current.name());
66
+ }
67
+ return words;
68
+ }
69
+ /** A shape on one line, for the long help, which wraps it under its flag. */
70
+ function shapeLine(shape) {
71
+ if (typeof shape === 'string')
72
+ return `Shape: ${shape}`;
73
+ const [head, ...members] = shape;
74
+ return `Shape: ${head} ${members.join(' | ')}`;
75
+ }
76
+ /** A subcommand as its usage line names it: `get [projectId] <sessionId>`. */
77
+ function subcommandTerm(helper, command, long) {
78
+ const custom = command._usage;
79
+ const term = custom
80
+ ? `${command.name()} ${custom}`
81
+ : Help.prototype.subcommandTerm.call(helper, command);
82
+ return long ? term : term.replace(' [options]', '');
83
+ }
84
+ function shapeLines(shape) {
85
+ if (typeof shape === 'string')
86
+ return `Shape: ${shape}`;
87
+ const [head, ...members] = shape;
88
+ return [`Shape: ${head}`, ...members.map((member) => ` ${member}`)].join('\n');
89
+ }
90
+ /** The help configuration of the whole tree, short or long. */
91
+ export function helpConfiguration(long) {
92
+ const configuration = build(long);
93
+ configurations.add(configuration);
94
+ return configuration;
95
+ }
96
+ function build(long) {
97
+ const base = Help.prototype;
98
+ if (long) {
99
+ return {
100
+ sortSubcommands: true,
101
+ subcommandTerm(command) {
102
+ return subcommandTerm(this, command, true);
103
+ },
104
+ optionDescription(option) {
105
+ const text = base.optionDescription.call(this, option);
106
+ const shape = optionShapes.get(option);
107
+ if (!shape)
108
+ return text;
109
+ return text ? `${text}\n${shapeLine(shape)}` : shapeLine(shape);
110
+ },
111
+ formatHelp(command, helper) {
112
+ const text = base.formatHelp.call(this, command, helper);
113
+ const after = afterText.get(command);
114
+ return after ? `${text}${after(true)}\n` : text;
115
+ },
116
+ };
117
+ }
118
+ // Whether this help cut anything, so it ends by saying where the rest is.
119
+ let cut = false;
120
+ const shorten = (text, width) => {
121
+ if (!text)
122
+ return text ?? '';
123
+ const sentence = firstSentence(text);
124
+ const short = width ? oneLine(sentence) : sentence;
125
+ if (short !== text.replace(/\s+/g, ' ').trim())
126
+ cut = true;
127
+ return short;
128
+ };
129
+ return {
130
+ sortSubcommands: true,
131
+ // Never wrapped: a flag is one line, however wide the terminal.
132
+ helpWidth: 100_000,
133
+ commandDescription(command) {
134
+ return shorten(command.description(), false);
135
+ },
136
+ subcommandTerm(command) {
137
+ return subcommandTerm(this, command, false);
138
+ },
139
+ subcommandDescription(command) {
140
+ return shorten(command.summary() || command.description(), true);
141
+ },
142
+ optionDescription(option) {
143
+ const short = Object.assign(Object.create(option), {
144
+ description: shorten(option.description, true),
145
+ });
146
+ return base.optionDescription.call(this, short);
147
+ },
148
+ argumentDescription(argument) {
149
+ const short = Object.assign(Object.create(argument), {
150
+ description: shorten(argument.description, true),
151
+ });
152
+ return base.argumentDescription.call(this, short);
153
+ },
154
+ formatHelp(command, helper) {
155
+ cut = false;
156
+ let text = base.formatHelp.call(this, command, helper);
157
+ const after = afterText.get(command);
158
+ if (after)
159
+ text += `${after(false)}\n`;
160
+ if (commandPath(command).join(' ') === 'sensei cards set')
161
+ return `${text}\n${CARD_RULES}\n`;
162
+ return cut ? `${text}\n${FULL_TEXT}\n` : text;
163
+ },
164
+ };
165
+ }
166
+ /** A form's summary as the short help lists it under `Forms:`. */
167
+ export function shortSummary(summary) {
168
+ return oneLine(firstSentence(summary));
169
+ }
170
+ const ABBREVIATIONS = new Map([
171
+ ['projectId', 'P'],
172
+ ['sessionId', 'S'],
173
+ ['workspaceId|personal', 'W'],
174
+ ['workspaceId', 'w'],
175
+ ]);
176
+ const LEGEND = 'P=projectId S=sessionId PS=[projectId] sessionId W=workspaceId|personal w=workspaceId; [x] optional';
177
+ /** A positional as the compact tree writes it: `P`, `[S]`, `job`, `name...`. */
178
+ function abbreviate(token) {
179
+ const optional = token.startsWith('[');
180
+ const variadic = token.endsWith('...]') || token.endsWith('...>');
181
+ const name = token.replace(/^[<[]|[>\]]$/g, '').replace(/\.\.\.$/, '');
182
+ const short = ABBREVIATIONS.get(name) ?? name.replace(/(?<=[a-z0-9])Id$/, '').replace(/Id\|/, '|');
183
+ const word = `${short}${variadic ? '...' : ''}`;
184
+ return optional ? `[${word}]` : word;
185
+ }
186
+ /** A leaf's positionals, read off its usage line. */
187
+ function argumentsOf(command) {
188
+ return command
189
+ .usage()
190
+ .split(' ')
191
+ .filter((token) => /^[<[]/.test(token) && token !== '[options]' && token !== '[command]')
192
+ .map(abbreviate)
193
+ .join(' ')
194
+ .replace(/^\[P\] S\b/, 'PS');
195
+ }
196
+ const visible = (command) => [...command.commands]
197
+ .filter((child) => !child._hidden)
198
+ .sort((a, b) => (a.name() < b.name() ? -1 : a.name() > b.name() ? 1 : 0));
199
+ const runs = (command) => command._actionHandler !== null;
200
+ /** A sub-group with one leaf and nothing under it, which its parent's line lists as two words. */
201
+ function folded(group) {
202
+ if (runs(group))
203
+ return null;
204
+ const children = visible(group);
205
+ const [only] = children;
206
+ return children.length === 1 && runs(only) && !only.commands.length ? only : null;
207
+ }
208
+ /**
209
+ * `create P; delete|get PS; env sync PS`: a group's own leaves, those with the same arguments
210
+ * merged, then its folded sub-groups.
211
+ */
212
+ function leafList(group, fold = true) {
213
+ const byArgs = new Map();
214
+ // Its own item, by its leaf and arguments: `branches|releases list P`. Merged with the
215
+ // group's leaves, `list|folders create` would read as one group.
216
+ const two = new Map();
217
+ for (const child of visible(group)) {
218
+ const leaf = fold && child.commands.length ? folded(child) : null;
219
+ if (leaf) {
220
+ const rest = [leaf.name(), argumentsOf(leaf)].filter(Boolean).join(' ');
221
+ two.set(rest, [...(two.get(rest) ?? []), child.name()]);
222
+ }
223
+ else if (runs(child)) {
224
+ const args = argumentsOf(child);
225
+ byArgs.set(args, [...(byArgs.get(args) ?? []), child.name()]);
226
+ }
227
+ }
228
+ return [
229
+ ...[...byArgs].map(([args, names]) => [names.join('|'), args].filter(Boolean).join(' ')),
230
+ ...[...two].map(([rest, names]) => `${names.join('|')} ${rest}`),
231
+ ].join('; ');
232
+ }
233
+ /**
234
+ * Every visible command of the tree, one line per group, sub-groups indented under theirs with
235
+ * their path from it. Sibling sub-groups with the same leaves share a line: `diff commits|files`.
236
+ */
237
+ export function compactHelp(program) {
238
+ const lines = ['Flags: kosuke <command> --help.', LEGEND];
239
+ const top = leafList(program, false);
240
+ if (top)
241
+ lines.push(`kosuke: ${top}`);
242
+ const walk = (command, path) => {
243
+ const groups = visible(command).filter((child) => child.commands.length && !folded(child));
244
+ // Leaf-only sub-groups merge by what they list; one with groups of its own stands alone.
245
+ const merged = new Map();
246
+ for (const child of groups) {
247
+ const leaves = leafList(child);
248
+ const nested = visible(child).some((grandchild) => grandchild.commands.length);
249
+ const key = nested || !leaves ? `\u0000${child.name()}` : leaves;
250
+ merged.set(key, [...(merged.get(key) ?? []), child.name()]);
251
+ }
252
+ for (const [leaves, names] of merged) {
253
+ const words = [...path, names.join('|')].join(' ');
254
+ if (!leaves.startsWith('\u0000')) {
255
+ lines.push(` ${words}: ${leaves}`);
256
+ continue;
257
+ }
258
+ const child = groups.find((group) => group.name() === names[0]);
259
+ const own = leafList(child);
260
+ if (own)
261
+ lines.push(` ${words}: ${own}`);
262
+ walk(child, [...path, child.name()]);
263
+ }
264
+ };
265
+ for (const group of visible(program)) {
266
+ if (!group.commands.length)
267
+ continue;
268
+ lines.push(`${group.name()}: ${leafList(group)}`.trimEnd());
269
+ walk(group, []);
270
+ }
271
+ return lines.join('\n');
272
+ }
273
+ // --- did you mean --------------------------------------------------------------------------
274
+ function editDistance(a, b) {
275
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
276
+ for (let i = 1; i <= a.length; i++) {
277
+ for (let j = 1; j <= b.length; j++) {
278
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
279
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
280
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
281
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
282
+ }
283
+ }
284
+ }
285
+ return d[a.length][b.length];
286
+ }
287
+ /** The candidates close to `word`: within two edits, or one holding the other. */
288
+ function closeTo(word, candidates) {
289
+ const bare = (text) => text.replace(/^-+/, '');
290
+ return candidates.filter((candidate) => {
291
+ const [a, b] = [bare(word), bare(candidate)];
292
+ return editDistance(a, b) <= 2 || (a.length > 1 && (b.includes(a) || a.includes(b)));
293
+ });
294
+ }
295
+ function usageLine(command) {
296
+ return `Usage: ${['kosuke', ...commandPath(command), command.usage()].join(' ')}`;
297
+ }
298
+ /** `error: unknown command 'lst' for 'kosuke sessions qa runs'.` and the command it meant. */
299
+ export function unknownCommand(group, word) {
300
+ const names = visible(group).map((child) => child.name());
301
+ const close = closeTo(word, names);
302
+ const hint = close.length === 1
303
+ ? `Did you mean ${close[0]}?`
304
+ : `Did you mean one of: ${(close.length ? close : names).join(', ')}?`;
305
+ const where = ['kosuke', ...commandPath(group)].join(' ');
306
+ return group.error(`error: unknown command '${word}' for '${where}'.\n${hint}`, { code: 'commander.unknownCommand' });
307
+ }
308
+ /**
309
+ * Every command of the tree says which command or flag it meant, and a call with the wrong
310
+ * count of arguments prints its usage line. Exit code 1 and stderr, as commander's own errors.
311
+ */
312
+ export function suggestOnError(root) {
313
+ const patch = (command) => {
314
+ const target = command;
315
+ const where = ['kosuke', ...commandPath(command)].join(' ');
316
+ target.unknownCommand = function () {
317
+ unknownCommand(command, this.args[0] ?? '');
318
+ };
319
+ target.unknownOption = function (flag) {
320
+ if (this._allowUnknownOption)
321
+ return;
322
+ const longs = [];
323
+ for (let at = command; at; at = at.parent) {
324
+ for (const option of at.options)
325
+ if (option.long)
326
+ longs.push(option.long);
327
+ }
328
+ const close = closeTo(flag, longs);
329
+ const hint = close.length === 1 ? `Did you mean ${close[0]}?` : usageLine(command);
330
+ this.error(`error: unknown option '${flag}' for '${where}'.\n${hint}`, {
331
+ code: 'commander.unknownOption',
332
+ });
333
+ };
334
+ const missing = target.missingArgument.bind(target);
335
+ target.missingArgument = function (name) {
336
+ withUsage(command, () => missing(name));
337
+ };
338
+ const excess = target._excessArguments.bind(target);
339
+ target._excessArguments = function (received) {
340
+ withUsage(command, () => excess(received));
341
+ };
342
+ command.commands.forEach(patch);
343
+ };
344
+ patch(root);
345
+ }
346
+ /** Runs one of commander's own argument errors with the usage line after its message. */
347
+ function withUsage(command, raise) {
348
+ const target = command;
349
+ const error = target.error;
350
+ target.error = (message, options) => error.call(target, `${message}\n${usageLine(command)}`, options);
351
+ try {
352
+ raise();
353
+ }
354
+ finally {
355
+ target.error = error;
356
+ }
357
+ }
358
+ /** A usage error with the leaf's usage line, through commander so it prints as one. */
359
+ export function usageError(leaf, message) {
360
+ return leaf.error(`error: ${message}\n${usageLine(leaf)}`);
361
+ }
362
+ // --- kosuke sensei cards schema --------------------------------------------------------------
363
+ function fieldsOf(operation) {
364
+ return [...operation.query, ...(operation.body?.fields ?? []), ...(operation.multipart ?? [])];
365
+ }
366
+ function fieldText(field) {
367
+ const head = [
368
+ `--${field.flag} ${field.kind}`,
369
+ field.required ? 'required' : 'optional',
370
+ ...(field.choices ? [`one of ${field.choices.join('|')}`] : []),
371
+ ...(field.repeated ? ['repeat for several'] : []),
372
+ ].join(', ');
373
+ const lines = [head];
374
+ if (field.description)
375
+ lines.push(` ${field.description}`);
376
+ if (field.shape)
377
+ lines.push(...shapeLines(field.shape)
378
+ .split('\n')
379
+ .map((line) => ` ${line}`));
380
+ return lines.join('\n');
381
+ }
382
+ /**
383
+ * `kosuke sensei cards schema [field]`: the rules `cards set --help --long` holds, read from
384
+ * its descriptor: the summary, then each field's flag, kind, whether it is required, its
385
+ * description and its shape. One field by wire name or by flag.
386
+ */
387
+ export function cardSchema(operation, wanted) {
388
+ const fields = fieldsOf(operation);
389
+ if (wanted === undefined) {
390
+ return [operation.summary, '', ...fields.map(fieldText)].join('\n');
391
+ }
392
+ const name = wanted.replace(/^--/, '');
393
+ const field = fields.find((candidate) => candidate.name === name || candidate.flag === name);
394
+ if (!field) {
395
+ throw new Error(`No field ${wanted}. Fields: ${fields.map((candidate) => candidate.flag).join(', ')}.`);
396
+ }
397
+ return fieldText(field);
398
+ }