@ptkl/toolkit 1.4.4 → 1.6.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 (46) hide show
  1. package/README.md +34 -1
  2. package/dist/commands/__tests__/capabilities.test.js +83 -0
  3. package/dist/commands/__tests__/componentRunAs.test.js +65 -0
  4. package/dist/commands/__tests__/forge-bundle-layout.test.js +58 -0
  5. package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
  6. package/dist/commands/__tests__/forge-tools.test.js +64 -0
  7. package/dist/commands/__tests__/forge-variables.test.js +16 -0
  8. package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
  9. package/dist/commands/__tests__/role.test.js +83 -0
  10. package/dist/commands/__tests__/runAs.test.js +63 -0
  11. package/dist/commands/__tests__/thunder.test.js +46 -0
  12. package/dist/commands/component.js +9 -3
  13. package/dist/commands/forge.js +262 -202
  14. package/dist/commands/functions.js +11 -5
  15. package/dist/commands/integrations/payments.js +11 -7
  16. package/dist/commands/kortex.js +8 -6
  17. package/dist/commands/kortexPlaybook.js +396 -0
  18. package/dist/commands/role.js +45 -54
  19. package/dist/commands/satellite.js +0 -5
  20. package/dist/commands/thunder.js +19 -12
  21. package/dist/commands/workflow.js +10 -4
  22. package/dist/lib/__tests__/apiError.test.js +18 -0
  23. package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
  24. package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
  25. package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
  26. package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
  27. package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
  28. package/dist/lib/__tests__/runIdentity.test.js +101 -0
  29. package/dist/lib/__tests__/thunder.test.js +101 -0
  30. package/dist/lib/apiError.js +94 -1
  31. package/dist/lib/forgeDevKernelPlugin.js +90 -4
  32. package/dist/lib/forgeDevServiceExec.js +49 -0
  33. package/dist/lib/forgeDevServiceServer.js +163 -0
  34. package/dist/lib/forgeDevToken.js +126 -0
  35. package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +1 -1
  36. package/dist/lib/kortex/__tests__/playbookRules.test.js +120 -0
  37. package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
  38. package/dist/lib/kortex/playbookValidator.js +297 -0
  39. package/dist/lib/kortex/providers/protokol.js +1 -1
  40. package/dist/lib/kortex/resultSchemaChecker.js +188 -0
  41. package/dist/lib/kortex/session.js +1 -3
  42. package/dist/lib/oauth/ScopePreset.js +4 -3
  43. package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
  44. package/dist/lib/runIdentity.js +51 -0
  45. package/dist/lib/thunder.js +98 -0
  46. package/package.json +2 -2
@@ -2,6 +2,7 @@ import { Command } from "commander";
2
2
  import { readFileSync } from "fs";
3
3
  import { resolve } from "path";
4
4
  import * as sdk from "../lib/sdk.js";
5
+ import RunIdentityService from "../lib/runIdentity.js";
5
6
  import { registerCommand, withProfile } from "../lib/scaffold.js";
6
7
  /** `ptkl functions` — platform function CRUD + invocation (RFC §6, "Functions").
7
8
  * Maps onto the SDK `Functions` client (@ptkl/sdk/beta) for `list`/`get`/`update`/`run`/
@@ -44,7 +45,7 @@ class FunctionsCommand {
44
45
  })));
45
46
  cmd.addCommand(registerCommand(new Command("get")
46
47
  .description("Get function")
47
- .argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, reference) => {
48
+ .argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, reference, opts) => {
48
49
  const res = await sdk.platform(profile).function().get(reference);
49
50
  return res.data;
50
51
  })));
@@ -61,21 +62,26 @@ class FunctionsCommand {
61
62
  cmd.addCommand(registerCommand(new Command("create")
62
63
  .description("Create a new function")
63
64
  .option("-d, --data <data>", "Full create payload as JSON string (overrides --file)")
64
- .option("-i, --file <file>", "Path to a JSON file containing the full create payload")).action(withProfile(async (profile, opts) => {
65
+ .option("-i, --file <file>", "Path to a JSON file containing the full create payload")
66
+ .option("--run-as <prn>", "Identity the function runs as (prompted for when interactive)")).action(withProfile(async (profile, opts) => {
65
67
  const { data: dataStr, file } = opts;
66
68
  const payload = readPayload("--data", dataStr, file);
67
69
  const client = sdk.platform(profile).function();
68
- const res = await client.client.post("/v1/system/function", payload);
70
+ const identity = new RunIdentityService(client.client);
71
+ const runAs = await identity.forCreate(opts.runAs);
72
+ const res = await client.client.post("/v1/system/function", identity.withRunAs(payload, runAs));
69
73
  return res.data;
70
74
  })));
71
75
  cmd.addCommand(registerCommand(new Command("update")
72
76
  .description("Update an existing function")
73
77
  .argument("<uuid>", "UUID of the function to update")
74
78
  .option("-d, --data <data>", "Fields to update, as a JSON object string (overrides --file)")
75
- .option("-i, --file <file>", "Path to a JSON file containing the fields to update")).action(withProfile(async (profile, uuid, opts) => {
79
+ .option("-i, --file <file>", "Path to a JSON file containing the fields to update")
80
+ .option("--run-as <prn>", "Change the identity the function runs as")).action(withProfile(async (profile, uuid, opts) => {
76
81
  const { data: dataStr, file } = opts;
77
82
  const payload = readPayload("--data", dataStr, file);
78
- const res = await sdk.platform(profile).function().update(uuid, payload);
83
+ const identity = new RunIdentityService();
84
+ const res = await sdk.platform(profile).function().update(uuid, identity.withRunAs(payload, opts.runAs));
79
85
  return res.data;
80
86
  })));
81
87
  cmd.addCommand(registerCommand(new Command("signature")
@@ -71,7 +71,7 @@ class PaymentsCommand {
71
71
  registerList() {
72
72
  return registerCommand(new Command("list")
73
73
  .description("List payment transactions for a user")
74
- .requiredOption("-u, --user <userId>", "User id")
74
+ .option("-u, --user <userId>", "Deprecated, no longer used")
75
75
  .option("-s, --status <status>", "Filter by transaction status")
76
76
  .option("--sort-by <field>", "Field to sort by")
77
77
  .option("--sort-direction <direction>", "Sort direction: asc | desc")
@@ -88,7 +88,7 @@ class PaymentsCommand {
88
88
  page: opts.page !== undefined ? Number(opts.page) : undefined,
89
89
  }
90
90
  : undefined;
91
- const res = await sdk.payments(profile).getTransactions(opts.user, params);
91
+ const res = await sdk.payments(profile).getTransactions(params);
92
92
  return res?.data ?? res;
93
93
  }));
94
94
  }
@@ -99,7 +99,7 @@ class PaymentsCommand {
99
99
  .option("-u, --user <userId>", "Deprecated, no longer used")
100
100
  .requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
101
101
  await isActive(profile, "protokol-payments");
102
- const res = await sdk.payments(profile).getTransaction(opts.provider, opts.tx);
102
+ const res = await sdk.payments(profile).getTransaction(opts.tx);
103
103
  return res?.data ?? res;
104
104
  }));
105
105
  }
@@ -109,6 +109,7 @@ class PaymentsCommand {
109
109
  .addOption(providerOption())
110
110
  .option("-u, --user <userId>", "Deprecated, no longer used")
111
111
  .requiredOption("-d, --description <description>", "Payment description")
112
+ .requiredOption("--currency <code>", "3-letter currency code (e.g. EUR)")
112
113
  .option("--token <token>", "Pre-existing tokenized card to charge, if any")
113
114
  .option("--is-token-request", "Request tokenization of the card during payment")
114
115
  .option("--redirect-url <url>", "URL to redirect to after payment")
@@ -117,6 +118,7 @@ class PaymentsCommand {
117
118
  const res = await sdk.payments(profile).getPaymentLink(opts.provider, {
118
119
  ...parseAmount(opts),
119
120
  description: opts.description,
121
+ currency: opts.currency,
120
122
  ...(opts.token ? { token: opts.token } : {}),
121
123
  ...(opts.isTokenRequest ? { isTokenRequest: true } : {}),
122
124
  ...(opts.redirectUrl ? { redirectUrl: opts.redirectUrl } : {}),
@@ -148,12 +150,14 @@ class PaymentsCommand {
148
150
  .addOption(providerOption())
149
151
  .option("-u, --user <userId>", "Deprecated, no longer used")
150
152
  .requiredOption("--token <token>", "Tokenized card to charge")
151
- .requiredOption("-d, --description <description>", "Payment description"))).action(withProfile(async (profile, opts) => {
153
+ .requiredOption("-d, --description <description>", "Payment description")
154
+ .option("--currency <code>", "3-letter currency code (e.g. EUR)"))).action(withProfile(async (profile, opts) => {
152
155
  await isActive(profile, "protokol-payments");
153
156
  const res = await sdk.payments(profile).directPayUsingToken(opts.provider, {
154
157
  ...parseAmount(opts),
155
158
  token: opts.token,
156
159
  description: opts.description,
160
+ ...(opts.currency ? { currency: opts.currency } : {}),
157
161
  });
158
162
  return res?.data ?? res;
159
163
  }));
@@ -165,7 +169,7 @@ class PaymentsCommand {
165
169
  .option("-u, --user <userId>", "Deprecated, no longer used")
166
170
  .requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
167
171
  await isActive(profile, "protokol-payments");
168
- const res = await sdk.payments(profile).refund(opts.provider, opts.tx);
172
+ const res = await sdk.payments(profile).refund(opts.tx);
169
173
  return res?.data ?? res;
170
174
  }));
171
175
  }
@@ -176,7 +180,7 @@ class PaymentsCommand {
176
180
  .option("-u, --user <userId>", "Deprecated, no longer used")
177
181
  .requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
178
182
  await isActive(profile, "protokol-payments");
179
- const res = await sdk.payments(profile).voidTransaction(opts.provider, opts.tx);
183
+ const res = await sdk.payments(profile).voidTransaction(opts.tx);
180
184
  return res?.data ?? res;
181
185
  }));
182
186
  }
@@ -187,7 +191,7 @@ class PaymentsCommand {
187
191
  .option("-u, --user <userId>", "Deprecated, no longer used")
188
192
  .requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
189
193
  await isActive(profile, "protokol-payments");
190
- const res = await sdk.payments(profile).deactivatePaymentLink(opts.provider, opts.tx);
194
+ const res = await sdk.payments(profile).deactivatePaymentLink(opts.tx);
191
195
  return res?.data ?? res;
192
196
  }));
193
197
  }
@@ -7,9 +7,8 @@ import { registerCommand, withProfile } from "../lib/scaffold.js";
7
7
  import { UIBridge } from "../lib/kortex/bridge.js";
8
8
  import Session from "../lib/kortex/session.js";
9
9
  import { loadKortexConfig } from "../lib/kortex/config.js";
10
+ import KortexPlaybookCommand from "./kortexPlaybook.js";
10
11
  const PLATFORM_AGENT_NAMES = {
11
- 'protokol-bot': 'ProtokolBot',
12
- 'proka': 'Proka',
13
12
  'prota': 'Prota',
14
13
  };
15
14
  function parseJSON(label, raw) {
@@ -44,6 +43,7 @@ class KortexCommand {
44
43
  cmd.addCommand(this.registerKB());
45
44
  cmd.addCommand(this.registerDoc());
46
45
  cmd.addCommand(this.registerConversation());
46
+ cmd.addCommand(new KortexPlaybookCommand().register());
47
47
  cmd.addCommand(registerCommand(new Command('usage')
48
48
  .description('Get aggregated Kortex usage for the current project (admin), or a single user with --user')
49
49
  .option('-u, --user <uuid>', 'User-access UUID to scope usage to')
@@ -240,9 +240,11 @@ class KortexCommand {
240
240
  console.error(`\nRun \`ptkl profile use <name>\` or use \`ptkl --profile <name> kortex\``);
241
241
  process.exit(1);
242
242
  }
243
- // Resolve agent: CLI flag → persisted last used → ProtokolBot
243
+ // Resolve agent: CLI flag → persisted last used → Prota
244
244
  const config = loadKortexConfig();
245
- const agentUUID = opts.agent ?? config.lastAgentUUID ?? 'protokol-bot';
245
+ // A saved choice of a removed assistant becomes Prota.
246
+ const saved = config.lastAgentUUID === 'proka' || config.lastAgentUUID === 'protokol-bot' ? 'prota' : config.lastAgentUUID;
247
+ const agentUUID = opts.agent ?? saved ?? 'prota';
246
248
  let agentName = PLATFORM_AGENT_NAMES[agentUUID] ?? 'Kortex';
247
249
  if (!PLATFORM_AGENT_NAMES[agentUUID]) {
248
250
  try {
@@ -250,8 +252,8 @@ class KortexCommand {
250
252
  agentName = resp.data?.name ?? agentName;
251
253
  }
252
254
  catch {
253
- // Unknown agent, fall back to ProtokolBot
254
- agentName = 'ProtokolBot';
255
+ // Unknown agent, fall back to Prota
256
+ agentName = 'Prota';
255
257
  }
256
258
  }
257
259
  const isLocal = !opts.cloud;
@@ -0,0 +1,396 @@
1
+ import { Command } from "commander";
2
+ import { readFileSync, writeFileSync } from "fs";
3
+ import { kortex as kortexClient } from "../lib/sdk.js";
4
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
5
+ import PlaybookValidator, { MAX_RULE_LENGTH } from "../lib/kortex/playbookValidator.js";
6
+ // The first @ptkl/sdk release with the Workforce methods.
7
+ export const MIN_SDK_VERSION = '1.23.0';
8
+ const DONE_STATUSES = ['completed', 'failed', 'killed', 'timeout', 'expired'];
9
+ const NEEDS_PERSON_STATUSES = ['awaiting_approval', 'awaiting_answer', 'paused'];
10
+ // `ptkl kortex playbook`: playbooks as files. Pull to JSON, edit, validate, push a version,
11
+ // deploy, run. Exit codes for `run --wait`: 0 completed, 1 failed/killed/timeout/expired (including result_invalid), 2 needs a person, 3 still waiting after --timeout.
12
+ export default class KortexPlaybookCommand {
13
+ validator = new PlaybookValidator();
14
+ // The Workforce methods come with @ptkl/sdk MIN_SDK_VERSION. An older install would fail with
15
+ // "x is not a function", so say what to do instead.
16
+ client(profile) {
17
+ const client = kortexClient(profile);
18
+ if (typeof client.listPlaybooks !== 'function' || typeof client.checkWorkforceRule !== 'function') {
19
+ throw new Error(`This version of ptkl was installed with an older @ptkl/sdk that cannot manage playbooks. Update ptkl (it needs @ptkl/sdk ${MIN_SDK_VERSION} or newer).`);
20
+ }
21
+ return client;
22
+ }
23
+ register() {
24
+ const playbook = new Command('playbook')
25
+ .description('Manage Workforce playbooks as files: pull, edit, validate, push, deploy, run');
26
+ playbook.addCommand(this.list());
27
+ playbook.addCommand(this.get());
28
+ playbook.addCommand(this.versions());
29
+ playbook.addCommand(this.pull());
30
+ playbook.addCommand(this.validate());
31
+ playbook.addCommand(this.ruleCheck());
32
+ playbook.addCommand(this.push());
33
+ playbook.addCommand(this.deploy());
34
+ playbook.addCommand(this.rollback());
35
+ playbook.addCommand(this.deployments());
36
+ playbook.addCommand(this.run());
37
+ playbook.addCommand(this.runs());
38
+ playbook.addCommand(this.runGet());
39
+ return playbook;
40
+ }
41
+ list() {
42
+ return registerCommand(new Command('list')
43
+ .description('List playbooks')
44
+ .option('-p, --page <page>', 'Page number')
45
+ .option('-l, --limit <limit>', 'Page size')).action(withProfile(async (profile, opts) => {
46
+ return (await this.client(profile).listPlaybooks(this.paging(opts))).data;
47
+ }));
48
+ }
49
+ get() {
50
+ return registerCommand(new Command('get')
51
+ .description('Show a playbook and which version runs in dev and live')
52
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')).action(withProfile(async (profile, opts) => {
53
+ return (await this.client(profile).getPlaybook(opts.uuid)).data;
54
+ }));
55
+ }
56
+ versions() {
57
+ return registerCommand(new Command('versions')
58
+ .description('List the saved versions of a playbook')
59
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')).action(withProfile(async (profile, opts) => {
60
+ return (await this.client(profile).listPlaybookVersions(opts.uuid)).data;
61
+ }));
62
+ }
63
+ // Plain Command (not registerCommand): `-o` here is the playbook file, not the output flag.
64
+ pull() {
65
+ return new Command('pull')
66
+ .description('Write a playbook to a JSON file ({uuid, name, description, version, graph}); uses the live, else dev, else newest version')
67
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
68
+ .option('--version <version>', 'Version to pull (default: deployed in live, else dev, else the newest)')
69
+ .option('-o, --output <file>', 'File to write (default: print to stdout)')
70
+ .action(withProfile(async (profile, opts) => {
71
+ const client = this.client(profile);
72
+ const pb = (await client.getPlaybook(opts.uuid)).data;
73
+ let version = opts.version || pb.live_version || pb.dev_version;
74
+ if (!version) {
75
+ const all = (await client.listPlaybookVersions(opts.uuid)).data.data ?? [];
76
+ if (all.length === 0)
77
+ throw new Error('This playbook has no versions.');
78
+ version = [...all].sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))[0].version;
79
+ }
80
+ const v = (await client.getPlaybookVersion(opts.uuid, version)).data;
81
+ const file = {
82
+ uuid: pb.uuid,
83
+ name: pb.name,
84
+ description: pb.description ?? '',
85
+ version: v.version,
86
+ graph: v.graph,
87
+ };
88
+ const text = JSON.stringify(file, null, 2) + '\n';
89
+ if (opts.output) {
90
+ writeFileSync(opts.output, text);
91
+ console.log(`Wrote ${opts.output} (${pb.name}, version ${v.version}).`);
92
+ }
93
+ else {
94
+ process.stdout.write(text);
95
+ }
96
+ }));
97
+ }
98
+ // Local checks only (rule syntax is the server's to check: use rule-check): the server validates a saved version, so checking a draft there would
99
+ // mean pushing it first. With -u and --version it also asks the server about that saved version.
100
+ validate() {
101
+ return new Command('validate')
102
+ .description('Check a playbook file for problems (offline; the syntax of rules is only checked by the server, see rule-check). Exits 1 when there are problems')
103
+ .option('-f, --file <file>', 'Playbook file')
104
+ .option('-u, --uuid <uuid>', 'With --version, also ask the server to check that saved version (it also checks agents)')
105
+ .option('--version <version>', 'Saved version to check on the server')
106
+ .action(withProfile(async (profile, opts) => {
107
+ if (!opts.file && !(opts.uuid && opts.version)) {
108
+ throw new Error('Pass -f <file>, or -u <uuid> with --version.');
109
+ }
110
+ let problems = [];
111
+ let summary = '';
112
+ if (opts.file) {
113
+ const file = this.readFile(opts.file);
114
+ problems = this.validator.validate(file.graph);
115
+ summary = `${file.graph?.nodes?.length ?? 0} steps, ${file.graph?.edges?.length ?? 0} lines`;
116
+ }
117
+ if (opts.uuid && opts.version) {
118
+ const res = (await this.client(profile).validatePlaybook(opts.uuid, opts.version)).data;
119
+ problems = [...problems, ...(res.problems ?? [])];
120
+ }
121
+ if (problems.length === 0) {
122
+ console.log(`No problems found${summary ? ` (${summary})` : ''}.`);
123
+ return;
124
+ }
125
+ console.error(`${problems.length} problem${problems.length === 1 ? '' : 's'} found:`);
126
+ for (const p of problems)
127
+ console.error(` - ${p.message}${p.field ? ` (field: ${p.field})` : ''}`);
128
+ process.exitCode = 1;
129
+ }));
130
+ }
131
+ // Plain Command: `--input` is a file. Only the server can read a rule's syntax, so this asks it.
132
+ ruleCheck() {
133
+ return new Command('rule-check')
134
+ .description('Check one rule of a condition that decides by rules, and optionally try it on a sample input. The server checks the rule syntax; `playbook validate` does not. Exits 1 when the rule is not valid or cannot give an answer')
135
+ .requiredOption('--when <expression>', `The rule, in CEL syntax over input, at most ${MAX_RULE_LENGTH} characters, e.g. 'input.amount > 500 && input.currency == "RSD"'`)
136
+ .option('--input <file>', 'JSON file with a sample input to try the rule on (at most 64 KB)')
137
+ .action(withProfile(async (profile, opts) => {
138
+ const client = this.client(profile);
139
+ const body = { when: opts.when };
140
+ if (opts.input)
141
+ body.input = this.readJSON(opts.input);
142
+ const res = await client.checkWorkforceRule(body);
143
+ const out = res.data;
144
+ if (!out.valid) {
145
+ console.error(`The rule is not valid: ${out.message}`);
146
+ process.exitCode = 1;
147
+ }
148
+ else if (out.error) {
149
+ console.error(`The rule is valid, but it gives no answer for this input: ${out.error}`);
150
+ process.exitCode = 1;
151
+ }
152
+ else if (typeof out.result === 'boolean') {
153
+ console.log(`The rule is valid. For this input it is ${out.result}.`);
154
+ }
155
+ else {
156
+ console.log('The rule is valid.');
157
+ }
158
+ }));
159
+ }
160
+ push() {
161
+ return new Command('push')
162
+ .description('Create the playbook (no uuid) or save the file as a new version of it')
163
+ .requiredOption('-f, --file <file>', 'Playbook file')
164
+ .option('-u, --uuid <uuid>', 'Playbook to add a version to (default: "uuid" in the file)')
165
+ .option('--version <version>', 'Name for the new version (default: the newest version with its patch number plus one, e.g. 0.1.0 -> 0.1.1)')
166
+ .option('--note <note>', 'Note saved with the version')
167
+ .action(withProfile(async (profile, opts) => {
168
+ const file = this.readFile(opts.file);
169
+ const problems = this.validator.validate(file.graph);
170
+ if (problems.length > 0) {
171
+ console.error(`Not pushed. ${problems.length} problem${problems.length === 1 ? '' : 's'} found:`);
172
+ for (const p of problems)
173
+ console.error(` - ${p.message}${p.field ? ` (field: ${p.field})` : ''}`);
174
+ process.exitCode = 1;
175
+ return;
176
+ }
177
+ const client = this.client(profile);
178
+ const uuid = opts.uuid || file.uuid;
179
+ let playbookUUID;
180
+ let versionName;
181
+ if (!uuid) {
182
+ if (!file.name)
183
+ throw new Error('The file needs a "name" to create a playbook.');
184
+ const created = (await client.createPlaybook({
185
+ name: file.name,
186
+ description: file.description,
187
+ version: opts.version || file.version || undefined,
188
+ })).data;
189
+ playbookUUID = created.uuid;
190
+ versionName = opts.version || file.version || created.dev_version || '0.1.0';
191
+ console.log(`Created playbook ${playbookUUID}`);
192
+ }
193
+ else {
194
+ playbookUUID = uuid;
195
+ const name = opts.version || await this.nextVersionName(client, uuid);
196
+ const created = (await client.createPlaybookVersion(uuid, {
197
+ version: name,
198
+ note: opts.note || undefined,
199
+ })).data;
200
+ versionName = created?.version ?? name;
201
+ }
202
+ let saved;
203
+ try {
204
+ saved = (await client.savePlaybookVersion(playbookUUID, versionName, {
205
+ graph: file.graph,
206
+ note: opts.note || undefined,
207
+ })).data;
208
+ }
209
+ catch (e) {
210
+ // The playbook or version already exists; say so, so a retry adds to it instead of duplicating it.
211
+ console.error(`The drawing was not saved. Playbook ${playbookUUID}, version ${versionName} exists and is empty. Fix the file and run push again with -u ${playbookUUID}.`);
212
+ throw e;
213
+ }
214
+ console.log(`Saved version ${saved?.version ?? versionName} of ${playbookUUID}`);
215
+ }));
216
+ }
217
+ deploy() {
218
+ return registerCommand(new Command('deploy')
219
+ .description('Put a version to work in dev or live')
220
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
221
+ .requiredOption('--version <version>', 'Version to deploy')).action(withProfile(async (profile, opts) => {
222
+ this.checkEnv(opts.env);
223
+ return (await this.client(profile).deployPlaybook(opts.uuid, { version: opts.version, env: opts.env })).data;
224
+ }));
225
+ }
226
+ rollback() {
227
+ return registerCommand(new Command('rollback')
228
+ .description('Go back to the previous version in dev or live')
229
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')).action(withProfile(async (profile, opts) => {
230
+ this.checkEnv(opts.env);
231
+ return (await this.client(profile).rollbackPlaybook(opts.uuid, { env: opts.env })).data;
232
+ }));
233
+ }
234
+ deployments() {
235
+ return registerCommand(new Command('deployments')
236
+ .description('List the deploys and rollbacks of a playbook')
237
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
238
+ .option('-p, --page <page>', 'Page number')
239
+ .option('-l, --limit <limit>', 'Page size')).action(withProfile(async (profile, opts) => {
240
+ return (await this.client(profile).listPlaybookDeployments(opts.uuid, this.paging(opts))).data;
241
+ }));
242
+ }
243
+ // Plain Command: `-f`/`-o` are not needed here and `--input` is a file.
244
+ run() {
245
+ return new Command('run')
246
+ .description('Start a run of the version deployed to --env (default dev). Exit: 0 done, 1 failed, 2 needs a person, 3 still waiting after --timeout (with --wait)')
247
+ .requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
248
+ .option('--env <env>', 'dev | live', 'dev')
249
+ .option('--instructions <text>', 'Instructions for this run')
250
+ .option('--input <file>', 'JSON file passed to the run as input')
251
+ .option('--wait', 'Wait until the run ends or needs a person, then print the outcome')
252
+ .option('--interval <seconds>', 'Seconds between checks with --wait', '3')
253
+ .option('--timeout <seconds>', 'Stop waiting after this long (0 = no limit)', '0')
254
+ .action(withProfile(async (profile, opts) => {
255
+ this.checkEnv(opts.env);
256
+ const client = this.client(profile);
257
+ const body = { env: opts.env };
258
+ if (opts.instructions)
259
+ body.instructions = opts.instructions;
260
+ if (opts.input)
261
+ body.input = this.readJSON(opts.input);
262
+ const started = (await client.startPlaybookRun(opts.uuid, body)).data;
263
+ console.log(`Run ${started.uuid} ${started.status}`);
264
+ if (!opts.wait)
265
+ return;
266
+ const seconds = Number(opts.interval);
267
+ if (!Number.isFinite(seconds))
268
+ throw new Error('--interval must be a number of seconds.');
269
+ const interval = Math.max(1, seconds) * 1000;
270
+ const limit = Number(opts.timeout) * 1000;
271
+ if (!Number.isFinite(limit) || limit < 0)
272
+ throw new Error('--timeout must be a number of seconds (0 = no limit).');
273
+ const t0 = Date.now();
274
+ let detail = await this.pollRun(client, started.uuid, interval);
275
+ while (!DONE_STATUSES.includes(detail.run.status) && !NEEDS_PERSON_STATUSES.includes(detail.run.status)) {
276
+ if (limit > 0 && Date.now() - t0 > limit) {
277
+ console.error(`Still ${detail.run.status} after ${opts.timeout}s. Check with: ptkl kortex playbook run-get -u ${started.uuid}`);
278
+ process.exitCode = 3;
279
+ return;
280
+ }
281
+ await new Promise((r) => setTimeout(r, interval));
282
+ detail = await this.pollRun(client, started.uuid, interval);
283
+ }
284
+ this.printOutcome(detail);
285
+ }));
286
+ }
287
+ // A network error or a 5xx while waiting is retried a few times: the run itself is still going.
288
+ async pollRun(client, uuid, interval) {
289
+ for (let attempt = 1;; attempt++) {
290
+ try {
291
+ return (await client.getRun(uuid)).data;
292
+ }
293
+ catch (e) {
294
+ const status = e?.response?.status;
295
+ const transient = !e?.response || status >= 500;
296
+ if (!transient || attempt >= 5)
297
+ throw e;
298
+ await new Promise((r) => setTimeout(r, interval));
299
+ }
300
+ }
301
+ }
302
+ runs() {
303
+ return registerCommand(new Command('runs')
304
+ .description('List runs, newest first')
305
+ .option('--playbook <uuid>', 'Only runs of this playbook')
306
+ .option('--status <status>', 'Only runs in this status (queued, running, awaiting_approval, awaiting_answer, paused, completed, failed, killed, timeout, expired)')
307
+ .option('-p, --page <page>', 'Page number')
308
+ .option('-l, --limit <limit>', 'Page size')).action(withProfile(async (profile, opts) => {
309
+ const params = { ...this.paging(opts), playbook: opts.playbook, status: opts.status };
310
+ return (await this.client(profile).listRuns(params)).data;
311
+ }));
312
+ }
313
+ runGet() {
314
+ return registerCommand(new Command('run-get')
315
+ .description('Show a run with its steps')
316
+ .requiredOption('-u, --uuid <uuid>', 'Run UUID')).action(withProfile(async (profile, opts) => {
317
+ const detail = (await this.client(profile).getRun(opts.uuid)).data;
318
+ const run = detail?.run;
319
+ // The default print cuts nested objects short, so show the result in full.
320
+ if (!opts.format && !opts.output && run?.result && Object.keys(run.result).length > 0) {
321
+ console.log('Result:');
322
+ console.log(JSON.stringify(run.result, null, 2));
323
+ }
324
+ if (run?.stop_reason === 'result_invalid')
325
+ process.exitCode = 1;
326
+ return detail;
327
+ }));
328
+ }
329
+ printOutcome(detail) {
330
+ const run = detail.run;
331
+ console.log(`Run ${run.uuid} ${run.status}`);
332
+ if (run.summary)
333
+ console.log(run.summary);
334
+ if (run.error_message)
335
+ console.error(run.error_message);
336
+ if (run.result && Object.keys(run.result).length > 0) {
337
+ console.log('Result:');
338
+ console.log(JSON.stringify(run.result, null, 2));
339
+ }
340
+ if (NEEDS_PERSON_STATUSES.includes(run.status)) {
341
+ const waiting = [...detail.steps].reverse().find((s) => (s.kind === 'approval' || s.kind === 'question' || s.approval?.decision === 'pending') &&
342
+ s.status !== 'completed' && s.status !== 'denied');
343
+ if (waiting) {
344
+ console.log(`Waiting on you at step ${waiting.index}: ${waiting.label || waiting.name || waiting.kind}`);
345
+ }
346
+ else if (run.status === 'paused') {
347
+ console.log('The run is paused.');
348
+ }
349
+ process.exitCode = 2;
350
+ }
351
+ else if (run.status !== 'completed') {
352
+ process.exitCode = 1;
353
+ }
354
+ }
355
+ // Newest version by created_at, patch bumped; keeps bumping while the name is taken.
356
+ async nextVersionName(client, uuid) {
357
+ const all = (await client.listPlaybookVersions(uuid)).data.data ?? [];
358
+ if (all.length === 0)
359
+ throw new Error('This playbook has no versions to count from. Pass --version <name>.');
360
+ const newest = [...all].sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))[0];
361
+ const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(newest.version);
362
+ if (!m)
363
+ throw new Error(`The newest version "${newest.version}" is not MAJOR.MINOR.PATCH, so the next name cannot be worked out. Pass --version <name>.`);
364
+ const taken = new Set(all.map((v) => v.version));
365
+ let patch = Number(m[3]) + 1;
366
+ while (taken.has(`${m[1]}.${m[2]}.${patch}`))
367
+ patch++;
368
+ const name = `${m[1]}.${m[2]}.${patch}`;
369
+ console.log(`New version name: ${name}`);
370
+ return name;
371
+ }
372
+ checkEnv(env) {
373
+ if (env !== 'dev' && env !== 'live')
374
+ throw new Error('--env must be dev or live.');
375
+ }
376
+ paging(opts) {
377
+ return {
378
+ page: opts.page ? Number(opts.page) : undefined,
379
+ limit: opts.limit ? Number(opts.limit) : undefined,
380
+ };
381
+ }
382
+ readJSON(path) {
383
+ try {
384
+ return JSON.parse(readFileSync(path, 'utf8'));
385
+ }
386
+ catch (err) {
387
+ throw new Error(`Cannot read ${path} as JSON: ${err.message}`);
388
+ }
389
+ }
390
+ readFile(path) {
391
+ const file = this.readJSON(path);
392
+ if (!file || typeof file !== 'object' || !file.graph)
393
+ throw new Error(`${path} is not a playbook file (no "graph").`);
394
+ return file;
395
+ }
396
+ }