@roarkanalytics/cli 0.67.1 → 0.68.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 (51) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +22 -0
  3. package/completions.js +3 -3
  4. package/npm-shrinkwrap.json +2 -2
  5. package/package.json +1 -1
  6. package/runtime/commands/config-as-code.js +5 -23
  7. package/runtime/commands/get-started.d.ts +34 -0
  8. package/runtime/commands/get-started.js +350 -0
  9. package/runtime/config-bundle.d.ts +10 -0
  10. package/runtime/config-bundle.js +14 -3
  11. package/runtime/config-changes.d.ts +15 -0
  12. package/runtime/config-changes.js +32 -0
  13. package/runtime/get-started/account.d.ts +18 -0
  14. package/runtime/get-started/account.js +35 -0
  15. package/runtime/get-started/agent.d.ts +17 -0
  16. package/runtime/get-started/agent.js +116 -0
  17. package/runtime/get-started/answers.d.ts +15 -0
  18. package/runtime/get-started/answers.js +42 -0
  19. package/runtime/get-started/apply.d.ts +35 -0
  20. package/runtime/get-started/apply.js +54 -0
  21. package/runtime/get-started/existing.d.ts +15 -0
  22. package/runtime/get-started/existing.js +47 -0
  23. package/runtime/get-started/ladder.d.ts +37 -0
  24. package/runtime/get-started/ladder.js +69 -0
  25. package/runtime/get-started/module.d.ts +20 -0
  26. package/runtime/get-started/module.js +159 -0
  27. package/runtime/get-started/placeholder.d.ts +9 -0
  28. package/runtime/get-started/placeholder.js +36 -0
  29. package/runtime/get-started/prompt.d.ts +32 -0
  30. package/runtime/get-started/prompt.js +132 -0
  31. package/runtime/get-started/resources.d.ts +106 -0
  32. package/runtime/get-started/resources.js +184 -0
  33. package/runtime/get-started/run.d.ts +42 -0
  34. package/runtime/get-started/run.js +101 -0
  35. package/runtime/get-started/scaffold-only.d.ts +19 -0
  36. package/runtime/get-started/scaffold-only.js +43 -0
  37. package/runtime/get-started/scaffold.d.ts +15 -0
  38. package/runtime/get-started/scaffold.js +35 -0
  39. package/runtime/get-started/starter-metrics.d.ts +33 -0
  40. package/runtime/get-started/starter-metrics.js +104 -0
  41. package/runtime/get-started/steps.d.ts +33 -0
  42. package/runtime/get-started/steps.js +112 -0
  43. package/runtime/get-started/target.d.ts +47 -0
  44. package/runtime/get-started/target.js +81 -0
  45. package/runtime/get-started/types.d.ts +18 -0
  46. package/runtime/get-started/types.js +8 -0
  47. package/runtime/get-started/watch.d.ts +57 -0
  48. package/runtime/get-started/watch.js +103 -0
  49. package/runtime/program.js +5 -0
  50. package/version.d.ts +1 -1
  51. package/version.js +1 -1
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ /**
3
+ * Step 2: which agent is under test, and how Roark reaches it.
4
+ *
5
+ * The longest step, because it has the most ways to be right: adopt one that already exists in
6
+ * Roark (and do not create a duplicate of it), declare a new one with a line to call, or declare
7
+ * one with nothing reachable yet and come back later.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.chooseAgent = void 0;
11
+ const ladder_1 = require("./ladder");
12
+ const answers_1 = require("./answers");
13
+ const resources_1 = require("./resources");
14
+ /** How many of the project's own agents to offer. A pick list has to stay readable. */
15
+ const AGENT_PAGE = 10;
16
+ /** One agent's lines. More than this is not a picker, and no agent under test has that many. */
17
+ const ENDPOINT_PAGE = 50;
18
+ /** The project's existing agents, or undefined when they could not be read. */
19
+ const listAgents = async (client) => {
20
+ try {
21
+ const response = await client.agent.list({ limit: AGENT_PAGE });
22
+ return {
23
+ agents: response.data.map((agent) => ({ id: agent.id, name: agent.name })),
24
+ // Not paged through. A picker with fifty entries is not a picker, so the honest move is
25
+ // to say the list is partial rather than to make it longer or to pretend it is complete.
26
+ truncated: response.pagination?.hasMore === true,
27
+ };
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ };
33
+ /** The agent's lines, or undefined when they could not be read: that is not the same as none. */
34
+ const listEndpoints = async (client, agentId) => {
35
+ try {
36
+ const response = await client.agentEndpoint.list({ agentId, limit: ENDPOINT_PAGE });
37
+ return response.data.map((endpoint) => ({ value: endpoint.value, direction: endpoint.direction }));
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ };
43
+ /**
44
+ * Step 2. Three ways in: adopt an agent that is already in Roark (the common case, and the one
45
+ * that stops the flow creating a duplicate), declare a new one with a number to call, or declare
46
+ * one with nothing reachable yet and come back to it.
47
+ */
48
+ const chooseAgent = async (client, prompter, say, binaryName, color) => {
49
+ const listed = await listAgents(client);
50
+ const CREATE = '\u0000create';
51
+ if (listed === undefined) {
52
+ // Said out loud rather than swallowed: without it, a project full of agents looks empty and
53
+ // the obvious next step is to create a duplicate of one that already exists.
54
+ say((0, ladder_1.note)("Could not read this project's agents, so this will declare a new one.", color, 'yellow'));
55
+ }
56
+ const existing = listed?.agents ?? [];
57
+ if (existing.length > 0) {
58
+ const choices = [
59
+ ...existing.map((agent) => ({ value: agent.id, label: agent.name, hint: 'already in Roark' })),
60
+ { value: CREATE, label: 'A new agent', hint: 'not in Roark yet' },
61
+ ];
62
+ if (listed?.truncated === true) {
63
+ say((0, ladder_1.note)(`Showing the first ${AGENT_PAGE} agents. If the one you want is not here, pick "A new agent" and give it the same name to adopt it.`, color));
64
+ }
65
+ const picked = await prompter.select('Which agent are we testing?', choices, existing[0].id);
66
+ if (picked !== CREATE) {
67
+ const agent = existing.find((candidate) => candidate.id === picked);
68
+ const slug = (0, resources_1.slugify)(agent.name) || 'agent';
69
+ const endpoints = await listEndpoints(client, agent.id);
70
+ // Endpoints are deliberately NOT declared for an adopted agent: an absent `endpoints` key
71
+ // leaves what Roark holds untouched, where an empty list would detach every one of them.
72
+ const base = {
73
+ name: slug,
74
+ ...(slug === agent.name ? {} : { displayName: agent.name }),
75
+ };
76
+ if (endpoints === undefined) {
77
+ // Distinct from "it has none": reporting a read failure as an agent with no line would
78
+ // skip the plan and the run over what may be a blip. Both say how to finish, because
79
+ // stopping early here is a pause, not a dead end.
80
+ say((0, ladder_1.note)(`Could not read ${agent.name}'s lines, so this stops before the plan. Run \`${binaryName} get-started\` again to finish it.`, color, 'yellow'));
81
+ return base;
82
+ }
83
+ if (endpoints.length === 0) {
84
+ say((0, ladder_1.note)(`That agent has no endpoint yet, so there is no line to call. Add one, then run \`${binaryName} get-started\` again to finish.`, color, 'yellow'));
85
+ return base;
86
+ }
87
+ if (endpoints.length === 1)
88
+ return { ...base, dial: endpoints[0] };
89
+ const line = await prompter.select('Which of its lines should the run call?', endpoints.map((endpoint) => ({
90
+ value: endpoint.value,
91
+ label: endpoint.value,
92
+ hint: endpoint.direction.toLowerCase().replace(/_/g, ' '),
93
+ })), endpoints[0].value);
94
+ return { ...base, dial: endpoints.find((endpoint) => endpoint.value === line) };
95
+ }
96
+ }
97
+ const name = await prompter.ask('What should we call the agent?', {
98
+ default: 'my-agent',
99
+ validate: (0, answers_1.nameRules)('name'),
100
+ });
101
+ const reachable = await prompter.select('Can Roark call it right now?', [
102
+ { value: 'phone', label: 'Yes, at a phone number I own', hint: 'Roark dials it and plays the caller' },
103
+ { value: 'later', label: 'Not yet', hint: 'write the files now, add the number later' },
104
+ ], 'phone');
105
+ if (reachable === 'later') {
106
+ say((0, ladder_1.echoCommand)(`${binaryName} agent create --name ${name}`, color));
107
+ return { name };
108
+ }
109
+ const value = await prompter.ask('Phone number for Roark to call', { validate: answers_1.phoneRules });
110
+ say((0, ladder_1.echoCommand)(`${binaryName} agent endpoint create --agent-id <id> --value ${value} --direction INCOMING`, color));
111
+ // INCOMING, so the run is inbound: Roark places the call and it runs the moment it is started.
112
+ // An outgoing-only line makes the run outbound, which needs your system to dial Roark.
113
+ return { name, endpoints: [{ value, direction: 'INCOMING' }], dial: { value, direction: 'INCOMING' } };
114
+ };
115
+ exports.chooseAgent = chooseAgent;
116
+ /** Placeholders for `--scaffold-only`: a complete, valid set of files with nothing invented about you. */
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What an answer is allowed to be, and the choices offered for the ones that are codes.
3
+ *
4
+ * The validators exist so a bad answer is caught at the prompt, where it can simply be asked
5
+ * again, rather than at apply time with the whole config already written.
6
+ */
7
+ import type { Choice, Prompter } from './prompt';
8
+ export declare const nameRules: (what: string) => (answer: string) => string | undefined;
9
+ export declare const phoneRules: (answer: string) => string | undefined;
10
+ export declare const enumRules: (answer: string) => string | undefined;
11
+ export declare const LANGUAGES: readonly Choice<string>[];
12
+ export declare const ACCENTS: readonly Choice<string>[];
13
+ export declare const GENDERS: readonly Choice<string>[];
14
+ /** `other` defers to a typed code rather than listing every value the DSL accepts. */
15
+ export declare const pickCode: (prompter: Prompter, question: string, choices: readonly Choice<string>[], fallback: string) => Promise<string>;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * What an answer is allowed to be, and the choices offered for the ones that are codes.
4
+ *
5
+ * The validators exist so a bad answer is caught at the prompt, where it can simply be asked
6
+ * again, rather than at apply time with the whole config already written.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.pickCode = exports.GENDERS = exports.ACCENTS = exports.LANGUAGES = exports.enumRules = exports.phoneRules = exports.nameRules = void 0;
10
+ const resources_1 = require("./resources");
11
+ const nameRules = (what) => (answer) => resources_1.NAME_PATTERN.test(answer) ? undefined : (`A ${what} is lowercase letters, numbers, - _ . (e.g. ${(0, resources_1.slugify)(`my ${what}`) || 'my-name'}).`);
12
+ exports.nameRules = nameRules;
13
+ const phoneRules = (answer) => resources_1.PHONE_PATTERN.test(answer) ? undefined : 'Use E.164: a + and the country code, e.g. +15551234567.';
14
+ exports.phoneRules = phoneRules;
15
+ const enumRules = (answer) => /^[A-Z][A-Z_]*$/.test(answer) ? undefined : 'Use the upper-case code, e.g. EN or US_X_SOUTH.';
16
+ exports.enumRules = enumRules;
17
+ exports.LANGUAGES = [
18
+ { value: 'EN', label: 'English' },
19
+ { value: 'ES', label: 'Spanish' },
20
+ { value: 'FR', label: 'French' },
21
+ { value: 'DE', label: 'German' },
22
+ { value: 'other', label: 'Something else', hint: 'type the code, e.g. HI, NL, PT' },
23
+ ];
24
+ exports.ACCENTS = [
25
+ { value: 'US', label: 'US' },
26
+ { value: 'GB', label: 'British' },
27
+ { value: 'IN', label: 'Indian' },
28
+ { value: 'AU', label: 'Australian' },
29
+ { value: 'other', label: 'Something else', hint: 'type the code, e.g. ES, DE, PH' },
30
+ ];
31
+ exports.GENDERS = [
32
+ { value: 'FEMALE', label: 'Female' },
33
+ { value: 'MALE', label: 'Male' },
34
+ ];
35
+ /** `other` defers to a typed code rather than listing every value the DSL accepts. */
36
+ const pickCode = async (prompter, question, choices, fallback) => {
37
+ const picked = await prompter.select(question, choices, fallback);
38
+ if (picked !== 'other')
39
+ return picked;
40
+ return (await prompter.ask('Which code?', { validate: exports.enumRules })).toUpperCase();
41
+ };
42
+ exports.pickCode = pickCode;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Preview the config, confirm it, apply it.
3
+ *
4
+ * Its own module for the same reason as the run phase: it is a self-contained step with one
5
+ * decision in it, where the question-asking steps thread one `Setup` through shared state.
6
+ */
7
+ import type Roark from '@roarkanalytics/sdk';
8
+ import { type Target } from './target';
9
+ import type { ConfigChange } from './types';
10
+ import type { Prompter } from './prompt';
11
+ interface ApplyPhase {
12
+ client: Roark;
13
+ prompter: Prompter;
14
+ say: (text: string) => void;
15
+ binaryName: string;
16
+ color: boolean;
17
+ quiet: boolean;
18
+ options: Record<string, unknown>;
19
+ target: Target;
20
+ }
21
+ /**
22
+ * Preview the config, confirm it, apply it.
23
+ *
24
+ * Its own function for the same reason as `startRun`: it is a self-contained phase with one
25
+ * decision in it, and the steps around it are not - they thread one `Setup` through shared
26
+ * local state. `stopped` carries the one case the caller cannot infer, a user who said no,
27
+ * where the files are written and the right thing is to stop without running anything.
28
+ */
29
+ export declare const applyConfig: (phase: ApplyPhase) => Promise<{
30
+ stopped: true;
31
+ } | {
32
+ stopped: false;
33
+ applied: ConfigChange[] | undefined;
34
+ }>;
35
+ export {};
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ /**
3
+ * Preview the config, confirm it, apply it.
4
+ *
5
+ * Its own module for the same reason as the run phase: it is a self-contained step with one
6
+ * decision in it, where the question-asking steps thread one `Setup` through shared state.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.applyConfig = void 0;
10
+ const node_path_1 = require("node:path");
11
+ const config_bundle_1 = require("../config-bundle");
12
+ const config_module_1 = require("../config-module");
13
+ const config_changes_1 = require("../config-changes");
14
+ const output_1 = require("../output");
15
+ const ladder_1 = require("./ladder");
16
+ const module_1 = require("./module");
17
+ const target_1 = require("./target");
18
+ /**
19
+ * Preview the config, confirm it, apply it.
20
+ *
21
+ * Its own function for the same reason as `startRun`: it is a self-contained phase with one
22
+ * decision in it, and the steps around it are not - they thread one `Setup` through shared
23
+ * local state. `stopped` carries the one case the caller cannot infer, a user who said no,
24
+ * where the files are written and the right thing is to stop without running anything.
25
+ */
26
+ const applyConfig = async (phase) => {
27
+ const { client, prompter, say, binaryName, color, quiet, options, target } = phase;
28
+ // `prune: false`, always. What this writes is a subset of a real config, and a quickstart
29
+ // that deleted a resource someone already managed would be indefensible.
30
+ const bundle = target.format === 'ts' ?
31
+ await (0, config_module_1.loadConfigModule)((0, node_path_1.join)(target.dir, module_1.CONFIG_MODULE_FILE), { prune: false })
32
+ : await (0, config_bundle_1.buildBundle)(target.dir, { prune: false });
33
+ const preview = await client.config.diff(bundle);
34
+ const count = (0, config_changes_1.changeCount)(preview.data.summary);
35
+ say('');
36
+ if (count === 0) {
37
+ say('Nothing to apply: the project already matches this config.');
38
+ return { stopped: false, applied: undefined };
39
+ }
40
+ say((0, config_changes_1.formatChanges)(preview.data));
41
+ say((0, ladder_1.note)('Nothing is deleted: this applies without pruning.', color));
42
+ const go = options['yes'] === true || (await prompter.confirm(`Apply ${count} change(s)?`, true));
43
+ if (!go) {
44
+ say('');
45
+ say(`Stopped before applying. The config is written; run \`${(0, target_1.applyCommand)(binaryName, target)}\` when ready.`);
46
+ if (!quiet)
47
+ (0, output_1.write)(target.label);
48
+ return { stopped: true };
49
+ }
50
+ const response = await client.config.apply(bundle);
51
+ say((0, config_changes_1.formatChanges)(response.data));
52
+ return { stopped: false, applied: response.data.changes };
53
+ };
54
+ exports.applyConfig = applyConfig;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What the config already declares.
3
+ *
4
+ * Every step consults this to decide whether to ask at all, which is what makes the command safe
5
+ * to re-run: a second pass fills the gaps and leaves the rest alone.
6
+ */
7
+ import type { Target } from './target';
8
+ /**
9
+ * Resources the config directory already declares, so a second run fills the gaps instead of
10
+ * asking everything again. An empty or absent directory is a fresh start; anything else wrong
11
+ * with it (unparseable YAML, a resource with no kind) is raised, because `apply` would hit it
12
+ * two steps later anyway and this is the better place to find out.
13
+ */
14
+ export declare const readExisting: (target: Target) => Promise<Record<string, unknown>[]>;
15
+ export declare const namesOfKind: (resources: readonly Record<string, unknown>[], kind: string) => string[];
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /**
3
+ * What the config already declares.
4
+ *
5
+ * Every step consults this to decide whether to ask at all, which is what makes the command safe
6
+ * to re-run: a second pass fills the gaps and leaves the rest alone.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.namesOfKind = exports.readExisting = void 0;
10
+ const node_fs_1 = require("node:fs");
11
+ const node_path_1 = require("node:path");
12
+ const config_bundle_1 = require("../config-bundle");
13
+ const config_module_1 = require("../config-module");
14
+ const module_1 = require("./module");
15
+ /**
16
+ * Resources the config directory already declares, so a second run fills the gaps instead of
17
+ * asking everything again. An empty or absent directory is a fresh start; anything else wrong
18
+ * with it (unparseable YAML, a resource with no kind) is raised, because `apply` would hit it
19
+ * two steps later anyway and this is the better place to find out.
20
+ */
21
+ const readExisting = async (target) => {
22
+ if (target.format === 'ts') {
23
+ const file = (0, node_path_1.join)(target.dir, module_1.CONFIG_MODULE_FILE);
24
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.resolve)(file)))
25
+ return [];
26
+ return (await (0, config_module_1.loadConfigModule)(file)).resources;
27
+ }
28
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.resolve)(target.dir)))
29
+ return [];
30
+ try {
31
+ return (await (0, config_bundle_1.buildBundle)(target.dir)).resources;
32
+ }
33
+ catch (error) {
34
+ // An empty directory is a fresh start, not a problem. Anything else (unparseable YAML, a
35
+ // resource with no kind) is a real error the user has to see: apply would hit it two steps
36
+ // later anyway, and this is the better place to find out.
37
+ if (error instanceof config_bundle_1.EmptyConfigDirectoryError)
38
+ return [];
39
+ throw error;
40
+ }
41
+ };
42
+ exports.readExisting = readExisting;
43
+ const namesOfKind = (resources, kind) => resources
44
+ .filter((resource) => resource['kind'] === kind)
45
+ .map((resource) => String(resource['name']))
46
+ .filter((name) => name.length > 0);
47
+ exports.namesOfKind = namesOfKind;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * How the flow narrates itself.
3
+ *
4
+ * Seven steps, each announced before it is asked about and summarised once it is done, so the
5
+ * terminal reads as a list someone is working down rather than a wall of questions. Printed, not
6
+ * redrawn: no cursor control means the scrollback is still readable afterwards, and a copied
7
+ * terminal still makes sense in a bug report.
8
+ *
9
+ * Pure string builders, so the wording is tested without a terminal.
10
+ */
11
+ import { type Style } from '../output';
12
+ export interface LadderStep {
13
+ title: string;
14
+ /** One line on why this step exists, which is the part a newcomer is missing. */
15
+ why: string;
16
+ }
17
+ /**
18
+ * The order is the dependency order the server applies in (metric, persona, agent, flow, plan),
19
+ * so what the flow teaches is also how config as code actually works.
20
+ */
21
+ export declare const STEPS: readonly LadderStep[];
22
+ export declare const intro: (binaryName: string, target: string, format: "yaml" | "ts", color: boolean) => string;
23
+ export declare const stepHeader: (index: number, color: boolean) => string;
24
+ export declare const stepDone: (index: number, summary: string, color: boolean) => string;
25
+ export declare const stepSkipped: (index: number, summary: string, color: boolean) => string;
26
+ /** The command a step is shorthand for, so the wizard teaches the CLI instead of hiding it. */
27
+ export declare const echoCommand: (command: string, color: boolean) => string;
28
+ export declare const note: (text: string, color: boolean, style?: Style) => string;
29
+ export interface NextSteps {
30
+ binaryName: string;
31
+ /** What to call the config when pointing at it: a directory, or a file. */
32
+ dir: string;
33
+ /** The apply command for this config, spelled the way a person would type it. */
34
+ apply: string;
35
+ lines: readonly string[];
36
+ }
37
+ export declare const nextSteps: ({ dir, apply, lines }: NextSteps, color: boolean) => string;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * How the flow narrates itself.
4
+ *
5
+ * Seven steps, each announced before it is asked about and summarised once it is done, so the
6
+ * terminal reads as a list someone is working down rather than a wall of questions. Printed, not
7
+ * redrawn: no cursor control means the scrollback is still readable afterwards, and a copied
8
+ * terminal still makes sense in a bug report.
9
+ *
10
+ * Pure string builders, so the wording is tested without a terminal.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.nextSteps = exports.note = exports.echoCommand = exports.stepSkipped = exports.stepDone = exports.stepHeader = exports.intro = exports.STEPS = void 0;
14
+ const output_1 = require("../output");
15
+ /**
16
+ * The order is the dependency order the server applies in (metric, persona, agent, flow, plan),
17
+ * so what the flow teaches is also how config as code actually works.
18
+ */
19
+ exports.STEPS = [
20
+ { title: 'Account', why: 'who you are, and the project this lands in' },
21
+ { title: 'Agent', why: 'the voice agent being tested, and how Roark reaches it' },
22
+ { title: 'Caller', why: 'the persona that calls it: language, accent, voice' },
23
+ { title: 'Scenario', why: 'what the caller is calling about' },
24
+ { title: 'Metrics', why: 'how the call gets graded' },
25
+ { title: 'Plan', why: 'the saved, repeatable run' },
26
+ { title: 'Run', why: 'place the call, then read the verdict' },
27
+ ];
28
+ const label = (index) => `${index + 1}/${exports.STEPS.length}`;
29
+ const intro = (binaryName, target, format, color) => [
30
+ '',
31
+ (0, output_1.paint)(`${binaryName}: let's get your first graded simulation running.`, 'bold', color),
32
+ (0, output_1.paint)(`${exports.STEPS.length} steps. Everything is written to ${target} as ${format === 'ts' ? 'TypeScript' : 'YAML'} you own and can commit.`, 'dim', color),
33
+ '',
34
+ ].join('\n');
35
+ exports.intro = intro;
36
+ const stepHeader = (index, color) => {
37
+ const step = exports.STEPS[index];
38
+ return [
39
+ '',
40
+ `${(0, output_1.paint)(label(index), 'cyan', color)} ${(0, output_1.paint)(step.title, 'bold', color)}`,
41
+ (0, output_1.paint)(` ${step.why}`, 'dim', color),
42
+ '',
43
+ ].join('\n');
44
+ };
45
+ exports.stepHeader = stepHeader;
46
+ const stepDone = (index, summary, color) => {
47
+ const step = exports.STEPS[index];
48
+ return `${(0, output_1.paint)('✓', 'green', color)} ${(0, output_1.paint)(label(index), 'dim', color)} ${step.title}: ${summary}`;
49
+ };
50
+ exports.stepDone = stepDone;
51
+ const stepSkipped = (index, summary, color) => {
52
+ const step = exports.STEPS[index];
53
+ return `${(0, output_1.paint)('·', 'yellow', color)} ${(0, output_1.paint)(label(index), 'dim', color)} ${step.title}: ${summary}`;
54
+ };
55
+ exports.stepSkipped = stepSkipped;
56
+ /** The command a step is shorthand for, so the wizard teaches the CLI instead of hiding it. */
57
+ const echoCommand = (command, color) => (0, output_1.paint)(` same as: ${command}`, 'dim', color);
58
+ exports.echoCommand = echoCommand;
59
+ const note = (text, color, style = 'dim') => (0, output_1.paint)(` ${text}`, style, color);
60
+ exports.note = note;
61
+ const nextSteps = ({ dir, apply, lines }, color) => [
62
+ '',
63
+ (0, output_1.paint)('What next:', 'bold', color),
64
+ ...lines.map((line) => ` ${line}`),
65
+ ` ${(0, output_1.paint)(`git add ${dir}`, 'cyan', color)} keep it in git; CI can run the same two commands`,
66
+ ` ${(0, output_1.paint)(apply, 'cyan', color)} redeploy after you edit the config`,
67
+ '',
68
+ ].join('\n');
69
+ exports.nextSteps = nextSteps;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The TypeScript form of the config `get-started` writes.
3
+ *
4
+ * Same resources as the YAML, serialized differently: `roark.config.ts` exporting
5
+ * `defineConfig({ resources })`, with one `define*` helper per kind. The DSL is a mirror of the
6
+ * YAML one (cross-references are names, not object references), so this takes the resource
7
+ * objects the YAML path already builds and only changes how they reach the page.
8
+ *
9
+ * Worth the second emitter because the two are not interchangeable in practice: YAML needs
10
+ * nothing installed and works for anyone who reached the CLI through a global install, while the
11
+ * TypeScript form gives types, editor completion and real code around the values - but only in a
12
+ * project that has `@roarkanalytics/sdk` to import from.
13
+ */
14
+ import { type ScaffoldFile, type Setup } from './resources';
15
+ /** The file `config apply` auto-detects when it is given no path, which is why this name. */
16
+ export declare const CONFIG_MODULE_FILE = "roark.config.ts";
17
+ /** The package the helpers come from. Absent from the project, the config cannot be loaded. */
18
+ export declare const CONFIG_MODULE_IMPORT = "@roarkanalytics/sdk/lib/config";
19
+ /** The whole `roark.config.ts`, or undefined when the setup has nothing to write. */
20
+ export declare const setupModule: (setup: Setup) => ScaffoldFile;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /**
3
+ * The TypeScript form of the config `get-started` writes.
4
+ *
5
+ * Same resources as the YAML, serialized differently: `roark.config.ts` exporting
6
+ * `defineConfig({ resources })`, with one `define*` helper per kind. The DSL is a mirror of the
7
+ * YAML one (cross-references are names, not object references), so this takes the resource
8
+ * objects the YAML path already builds and only changes how they reach the page.
9
+ *
10
+ * Worth the second emitter because the two are not interchangeable in practice: YAML needs
11
+ * nothing installed and works for anyone who reached the CLI through a global install, while the
12
+ * TypeScript form gives types, editor completion and real code around the values - but only in a
13
+ * project that has `@roarkanalytics/sdk` to import from.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.setupModule = exports.CONFIG_MODULE_IMPORT = exports.CONFIG_MODULE_FILE = void 0;
17
+ const resources_1 = require("./resources");
18
+ /** The file `config apply` auto-detects when it is given no path, which is why this name. */
19
+ exports.CONFIG_MODULE_FILE = 'roark.config.ts';
20
+ /** The package the helpers come from. Absent from the project, the config cannot be loaded. */
21
+ exports.CONFIG_MODULE_IMPORT = '@roarkanalytics/sdk/lib/config';
22
+ const HELPERS = {
23
+ metric: 'defineMetric',
24
+ persona: 'definePersona',
25
+ agent: 'defineAgent',
26
+ flow: 'defineImprovFlow',
27
+ simulationPlan: 'defineSimulationPlan',
28
+ };
29
+ const omit = (value, key) => Object.fromEntries(Object.entries(value).filter(([name]) => name !== key));
30
+ /** `my-agent` -> `myAgent`, for the const each resource is bound to. */
31
+ const camelize = (name) => {
32
+ const camel = name
33
+ .split(/[-_.]+/)
34
+ .filter((part) => part.length > 0)
35
+ .map((part, index) => (index === 0 ? part : `${part.charAt(0).toUpperCase()}${part.slice(1)}`))
36
+ .join('');
37
+ // A config name may start with a digit, which an identifier may not.
38
+ return /^[0-9]/.test(camel) ? `_${camel}` : camel;
39
+ };
40
+ /**
41
+ * A single-quoted TypeScript string.
42
+ *
43
+ * Newlines are escaped, not just quotes and backslashes. Nothing the prompts can produce today
44
+ * holds one - readline hands back a line at a time - but a value that gained one from anywhere
45
+ * else would emit a literal broken across two lines, which is not valid TypeScript, and the
46
+ * failure would land on the user as a syntax error in a file they did not write.
47
+ */
48
+ const quote = (value) => `'${value
49
+ .replace(/\\/g, '\\\\')
50
+ .replace(/'/g, "\\'")
51
+ .replace(/\n/g, '\\n')
52
+ .replace(/\r/g, '\\r')
53
+ .replace(/\t/g, '\\t')}'`;
54
+ /**
55
+ * How wide a line may get before the literal breaks across several.
56
+ *
57
+ * Roughly what a formatter would do, so running prettier over the generated file is close to a
58
+ * no-op rather than a rewrite of every line someone would then see in a diff.
59
+ */
60
+ const WIDTH = 88;
61
+ const key = (name) => (/^[a-zA-Z_$][\w$]*$/.test(name) ? name : quote(name));
62
+ const entriesOf = (value) => Object.entries(value).filter(([, entry]) => entry !== undefined);
63
+ /** The whole value on one line. Used when it fits; the multi-line form is the fallback. */
64
+ const compact = (value) => {
65
+ if (typeof value === 'string')
66
+ return quote(value);
67
+ if (typeof value === 'number' || typeof value === 'boolean')
68
+ return String(value);
69
+ if (value === null)
70
+ return 'null';
71
+ if (Array.isArray(value))
72
+ return `[${value.map(compact).join(', ')}]`;
73
+ if (typeof value === 'object') {
74
+ const entries = entriesOf(value);
75
+ if (entries.length === 0)
76
+ return '{}';
77
+ return `{ ${entries.map(([name, entry]) => `${key(name)}: ${compact(entry)}`).join(', ')} }`;
78
+ }
79
+ return 'undefined';
80
+ };
81
+ /**
82
+ * A TypeScript object literal.
83
+ *
84
+ * Hand-rolled rather than `JSON.stringify`: the output is code someone will read and edit, so it
85
+ * wants single quotes, unquoted keys, trailing commas and short values kept on one line, none of
86
+ * which JSON can produce.
87
+ */
88
+ const literal = (value, indent, used = 0) => {
89
+ const inline = compact(value);
90
+ // `used` is what the line already spent before this value: `const x = defineAgent(` and the
91
+ // closing `);`. Without it a one-line literal that fits on its own overflows once its
92
+ // declaration is in front of it.
93
+ if (indent.length + used + inline.length <= WIDTH)
94
+ return inline;
95
+ if (Array.isArray(value)) {
96
+ const inner = `${indent} `;
97
+ const entries = value.map((entry) => `${inner}${literal(entry, inner)},`).join('\n');
98
+ return `[\n${entries}\n${indent}]`;
99
+ }
100
+ if (value !== null && typeof value === 'object') {
101
+ const inner = `${indent} `;
102
+ const lines = entriesOf(value)
103
+ .map(([name, entry]) => `${inner}${key(name)}: ${literal(entry, inner)},`)
104
+ .join('\n');
105
+ return `{\n${lines}\n${indent}}`;
106
+ }
107
+ return inline;
108
+ };
109
+ /** The resources, as `const <name> = define<Kind>({ ... })` blocks, in apply order. */
110
+ const declarations = (setup) => {
111
+ const used = new Set();
112
+ const helpers = [];
113
+ const bindings = [];
114
+ const blocks = [];
115
+ for (const { kind, resource, notes } of (0, resources_1.resourcesFor)(setup, 'ts')) {
116
+ const helper = HELPERS[kind];
117
+ if (helper === undefined)
118
+ continue;
119
+ if (!helpers.includes(helper))
120
+ helpers.push(helper);
121
+ // `kind` is the helper's job. `type` is too, but ONLY for a flow, where the helper is chosen
122
+ // per type (`defineImprovFlow`): a metric's `type` is a required field of its own, and
123
+ // stripping that one produces a config that does not compile.
124
+ const { kind: _kind, name, ...fields } = resource;
125
+ const rest = kind === 'flow' ? omit(fields, 'type') : fields;
126
+ let binding = camelize(String(name));
127
+ // Two kinds may legitimately share a name, and two consts may not.
128
+ if (used.has(binding))
129
+ binding = `${binding}${kind.charAt(0).toUpperCase()}${kind.slice(1)}`;
130
+ used.add(binding);
131
+ bindings.push(binding);
132
+ const opening = `const ${binding} = ${helper}(`;
133
+ const body = literal({ name, ...rest }, '', opening.length + ');'.length);
134
+ blocks.push([...notes.map((note) => `// ${note}`), `${opening}${body});`].join('\n'));
135
+ }
136
+ return { source: blocks.join('\n\n'), helpers, bindings };
137
+ };
138
+ /** The whole `roark.config.ts`, or undefined when the setup has nothing to write. */
139
+ const setupModule = (setup) => {
140
+ const { source, helpers, bindings } = declarations(setup);
141
+ const imported = [...helpers, 'defineConfig'].sort();
142
+ return {
143
+ path: exports.CONFIG_MODULE_FILE,
144
+ contents: [
145
+ '// Roark config as code. Everything this project declares in Roark lives here.',
146
+ '//',
147
+ `// \`roark config apply\` finds this file by name, so it needs no argument. The YAML form is`,
148
+ '// equivalent: see https://roark.ai/documentation/config-as-code/overview',
149
+ '',
150
+ `import {\n${imported.map((helper) => ` ${helper},`).join('\n')}\n} from '${exports.CONFIG_MODULE_IMPORT}';`,
151
+ '',
152
+ source,
153
+ '',
154
+ `export default defineConfig({\n resources: [${bindings.join(', ')}],\n});`,
155
+ '',
156
+ ].join('\n'),
157
+ };
158
+ };
159
+ exports.setupModule = setupModule;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * What `--scaffold-only` writes: a complete, valid config with nothing invented about you.
3
+ *
4
+ * Every value here is a placeholder someone is expected to replace, which is why the command
5
+ * prints a TODO per file rather than pretending the result is ready to apply.
6
+ */
7
+ import { type ConfigFormat, type Setup } from './resources';
8
+ export declare const placeholderSetup: () => Setup;
9
+ export declare const placeholderTodos: (format: ConfigFormat) => string[];