@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.
- package/README.md +34 -1
- package/dist/commands/__tests__/capabilities.test.js +83 -0
- package/dist/commands/__tests__/componentRunAs.test.js +65 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +58 -0
- package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
- package/dist/commands/__tests__/forge-tools.test.js +64 -0
- package/dist/commands/__tests__/forge-variables.test.js +16 -0
- package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
- package/dist/commands/__tests__/role.test.js +83 -0
- package/dist/commands/__tests__/runAs.test.js +63 -0
- package/dist/commands/__tests__/thunder.test.js +46 -0
- package/dist/commands/component.js +9 -3
- package/dist/commands/forge.js +262 -202
- package/dist/commands/functions.js +11 -5
- package/dist/commands/integrations/payments.js +11 -7
- package/dist/commands/kortex.js +8 -6
- package/dist/commands/kortexPlaybook.js +396 -0
- package/dist/commands/role.js +45 -54
- package/dist/commands/satellite.js +0 -5
- package/dist/commands/thunder.js +19 -12
- package/dist/commands/workflow.js +10 -4
- package/dist/lib/__tests__/apiError.test.js +18 -0
- package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
- package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
- package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
- package/dist/lib/__tests__/runIdentity.test.js +101 -0
- package/dist/lib/__tests__/thunder.test.js +101 -0
- package/dist/lib/apiError.js +94 -1
- package/dist/lib/forgeDevKernelPlugin.js +90 -4
- package/dist/lib/forgeDevServiceExec.js +49 -0
- package/dist/lib/forgeDevServiceServer.js +163 -0
- package/dist/lib/forgeDevToken.js +126 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +1 -1
- package/dist/lib/kortex/__tests__/playbookRules.test.js +120 -0
- package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
- package/dist/lib/kortex/playbookValidator.js +297 -0
- package/dist/lib/kortex/providers/protokol.js +1 -1
- package/dist/lib/kortex/resultSchemaChecker.js +188 -0
- package/dist/lib/kortex/session.js +1 -3
- package/dist/lib/oauth/ScopePreset.js +4 -3
- package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
- package/dist/lib/runIdentity.js +51 -0
- package/dist/lib/thunder.js +98 -0
- package/package.json +2 -2
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import { mkdtempSync, readFileSync, writeFileSync } from "fs";
|
|
4
|
+
import { tmpdir } from "os";
|
|
5
|
+
import { join } from "path";
|
|
6
|
+
const mocks = vi.hoisted(() => {
|
|
7
|
+
const calls = [];
|
|
8
|
+
const results = {};
|
|
9
|
+
const reply = (method, fallback) => async (...args) => {
|
|
10
|
+
calls.push({ method, args });
|
|
11
|
+
const queue = results[method];
|
|
12
|
+
const data = queue && queue.length > 1 ? queue.shift() : queue?.[0] ?? fallback;
|
|
13
|
+
return { data };
|
|
14
|
+
};
|
|
15
|
+
const client = {};
|
|
16
|
+
const defaults = {
|
|
17
|
+
listPlaybooks: { data: [] },
|
|
18
|
+
getPlaybook: { uuid: "pb1", name: "Pb", description: "d", live_version: "1.0.0", dev_version: "1.1.0" },
|
|
19
|
+
listPlaybookVersions: { data: [] },
|
|
20
|
+
getPlaybookVersion: { version: "1.0.0", graph: { nodes: [], edges: [] } },
|
|
21
|
+
createPlaybook: { uuid: "new1", dev_version: "0.1.0" },
|
|
22
|
+
createPlaybookVersion: { version: "0.2.0" },
|
|
23
|
+
savePlaybookVersion: { version: "0.2.0" },
|
|
24
|
+
validatePlaybook: { problems: [] },
|
|
25
|
+
deployPlaybook: { uuid: "pb1" },
|
|
26
|
+
rollbackPlaybook: { uuid: "pb1" },
|
|
27
|
+
listPlaybookDeployments: { data: [] },
|
|
28
|
+
startPlaybookRun: { uuid: "run1", status: "queued" },
|
|
29
|
+
listRuns: { data: [] },
|
|
30
|
+
checkWorkforceRule: { valid: true },
|
|
31
|
+
getRun: { run: { uuid: "run1", status: "completed", summary: "ok" }, steps: [] },
|
|
32
|
+
};
|
|
33
|
+
for (const [m, d] of Object.entries(defaults))
|
|
34
|
+
client[m] = reply(m, d);
|
|
35
|
+
return { calls, results, client };
|
|
36
|
+
});
|
|
37
|
+
vi.mock("../../lib/sdk.js", () => ({ kortex: () => mocks.client }));
|
|
38
|
+
vi.mock("../../lib/util.js", () => ({
|
|
39
|
+
default: { getCurrentProfile: () => ({ name: "test", host: "http://platform.test", token: "t", project: "p" }) },
|
|
40
|
+
}));
|
|
41
|
+
import KortexPlaybookCommand from "../kortexPlaybook.js";
|
|
42
|
+
const graph = {
|
|
43
|
+
nodes: [
|
|
44
|
+
{ id: "a", kind: "instruction", title: "Start", text: "Do it", agent_uuid: "ag1", x: 1, y: 2 },
|
|
45
|
+
{ id: "b", kind: "instruction", text: "Finish", agent_uuid: "ag1" },
|
|
46
|
+
],
|
|
47
|
+
edges: [{ from: "a", to: "b" }],
|
|
48
|
+
};
|
|
49
|
+
let dir;
|
|
50
|
+
let out;
|
|
51
|
+
let err;
|
|
52
|
+
const run = async (args) => {
|
|
53
|
+
const program = new Command().name("ptkl").exitOverride();
|
|
54
|
+
program.addCommand(new KortexPlaybookCommand().register());
|
|
55
|
+
await program.parseAsync(["playbook", ...args], { from: "user" });
|
|
56
|
+
};
|
|
57
|
+
const called = (m) => mocks.calls.filter((c) => c.method === m);
|
|
58
|
+
const writeJSON = (name, v) => { const p = join(dir, name); writeFileSync(p, JSON.stringify(v)); return p; };
|
|
59
|
+
describe("kortex playbook", () => {
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
dir = mkdtempSync(join(tmpdir(), "pb-"));
|
|
62
|
+
mocks.calls.length = 0;
|
|
63
|
+
for (const k of Object.keys(mocks.results))
|
|
64
|
+
delete mocks.results[k];
|
|
65
|
+
process.exitCode = undefined;
|
|
66
|
+
out = [];
|
|
67
|
+
err = [];
|
|
68
|
+
vi.spyOn(console, "log").mockImplementation((...a) => { out.push(a.join(" ")); });
|
|
69
|
+
vi.spyOn(console, "error").mockImplementation((...a) => { err.push(a.join(" ")); });
|
|
70
|
+
});
|
|
71
|
+
afterEach(() => { vi.restoreAllMocks(); process.exitCode = undefined; });
|
|
72
|
+
it("pull writes a file that push accepts unchanged (round trip)", async () => {
|
|
73
|
+
mocks.results.getPlaybookVersion = [{ version: "1.0.0", graph }];
|
|
74
|
+
mocks.results.listPlaybookVersions = [{ data: [{ version: "1.0.0", created_at: "2026-01-01" }] }];
|
|
75
|
+
const file = join(dir, "pb.json");
|
|
76
|
+
await run(["pull", "-u", "pb1", "-o", file]);
|
|
77
|
+
expect(called("getPlaybookVersion")[0].args).toEqual(["pb1", "1.0.0"]); // live wins over dev
|
|
78
|
+
const text = readFileSync(file, "utf8");
|
|
79
|
+
expect(text.endsWith("\n")).toBe(true);
|
|
80
|
+
expect(JSON.parse(text)).toEqual({ uuid: "pb1", name: "Pb", description: "d", version: "1.0.0", graph });
|
|
81
|
+
await run(["push", "-f", file]);
|
|
82
|
+
expect(called("createPlaybook")).toHaveLength(0);
|
|
83
|
+
expect(called("savePlaybookVersion")[0].args[2].graph).toEqual(graph);
|
|
84
|
+
});
|
|
85
|
+
it("pull --version asks for that version; falls back to the newest when nothing is deployed", async () => {
|
|
86
|
+
await run(["pull", "-u", "pb1", "--version", "0.9.0", "-o", join(dir, "a.json")]);
|
|
87
|
+
expect(called("getPlaybookVersion")[0].args[1]).toBe("0.9.0");
|
|
88
|
+
mocks.calls.length = 0;
|
|
89
|
+
mocks.results.getPlaybook = [{ uuid: "pb1", name: "Pb", live_version: "", dev_version: "" }];
|
|
90
|
+
mocks.results.listPlaybookVersions = [{ data: [
|
|
91
|
+
{ version: "0.1.0", created_at: "2026-01-01T00:00:00Z" },
|
|
92
|
+
{ version: "0.3.0", created_at: "2026-03-01T00:00:00Z" },
|
|
93
|
+
] }];
|
|
94
|
+
await run(["pull", "-u", "pb1", "-o", join(dir, "b.json")]);
|
|
95
|
+
expect(called("getPlaybookVersion")[0].args[1]).toBe("0.3.0");
|
|
96
|
+
});
|
|
97
|
+
it("validate exits 0 for a good file and 1 with plain-word problems for a bad one", async () => {
|
|
98
|
+
await run(["validate", "-f", writeJSON("ok.json", { name: "x", graph })]);
|
|
99
|
+
expect(process.exitCode).toBeUndefined();
|
|
100
|
+
expect(out.join("\n")).toContain("No problems found");
|
|
101
|
+
const bad = { ...graph, edges: [{ from: "a", to: "b" }, { from: "b", to: "a" }] };
|
|
102
|
+
await run(["validate", "-f", writeJSON("bad.json", { name: "x", graph: bad })]);
|
|
103
|
+
expect(process.exitCode).toBe(1);
|
|
104
|
+
expect(err.join("\n")).toMatch(/no starting step/);
|
|
105
|
+
});
|
|
106
|
+
it("validate reports a missing agent and an unreachable step", async () => {
|
|
107
|
+
const g = { nodes: [...graph.nodes, { id: "c", kind: "instruction", text: "x", agent_uuid: "" }], edges: graph.edges };
|
|
108
|
+
await run(["validate", "-f", writeJSON("g.json", { graph: g })]);
|
|
109
|
+
expect(process.exitCode).toBe(1);
|
|
110
|
+
expect(err.join("\n")).toMatch(/has no agent/);
|
|
111
|
+
expect(err.join("\n")).toMatch(/more than one starting step/);
|
|
112
|
+
});
|
|
113
|
+
it("validate with -u and --version also reports the server's problems", async () => {
|
|
114
|
+
mocks.results.validatePlaybook = [{ problems: [{ code: "agent_disabled", message: "Agent is disabled." }] }];
|
|
115
|
+
await run(["validate", "-u", "pb1", "--version", "1.0.0"]);
|
|
116
|
+
expect(called("validatePlaybook")[0].args).toEqual(["pb1", "1.0.0"]);
|
|
117
|
+
expect(process.exitCode).toBe(1);
|
|
118
|
+
expect(err.join("\n")).toContain("Agent is disabled.");
|
|
119
|
+
});
|
|
120
|
+
it("push without a uuid creates the playbook and saves the graph into its first version", async () => {
|
|
121
|
+
await run(["push", "-f", writeJSON("n.json", { name: "New", description: "d", version: "0.1.0", graph }), "--note", "first"]);
|
|
122
|
+
expect(called("createPlaybook")[0].args[0]).toEqual({ name: "New", description: "d", version: "0.1.0" });
|
|
123
|
+
expect(called("createPlaybookVersion")).toHaveLength(0);
|
|
124
|
+
expect(called("savePlaybookVersion")[0].args).toEqual(["new1", "0.1.0", { graph, note: "first" }]);
|
|
125
|
+
});
|
|
126
|
+
const versions = (...v) => ({ data: v.map(([version, created_at]) => ({ version, created_at })) });
|
|
127
|
+
const pushWith = async (extra = []) => run(["push", "-f", writeJSON("v.json", { name: "Pb", graph }), "-u", "pb1", ...extra]);
|
|
128
|
+
it("push bumps the patch of the newest version (0.1.0 -> 0.1.1) and prints it", async () => {
|
|
129
|
+
mocks.results.listPlaybookVersions = [versions(["0.1.0", "2026-01-01"])];
|
|
130
|
+
mocks.results.createPlaybookVersion = [{ version: "0.1.1" }];
|
|
131
|
+
await pushWith();
|
|
132
|
+
expect(called("createPlaybookVersion")[0].args[1].version).toBe("0.1.1");
|
|
133
|
+
expect(out.join("\n")).toContain("0.1.1");
|
|
134
|
+
});
|
|
135
|
+
it("push keeps bumping past a name that already exists", async () => {
|
|
136
|
+
mocks.results.listPlaybookVersions = [versions(["0.1.0", "2026-03-01"], ["0.1.1", "2026-01-01"], ["0.1.2", "2026-02-01"])];
|
|
137
|
+
await pushWith();
|
|
138
|
+
expect(called("createPlaybookVersion")[0].args[1].version).toBe("0.1.3");
|
|
139
|
+
});
|
|
140
|
+
it("push needs --version when the newest version is not MAJOR.MINOR.PATCH", async () => {
|
|
141
|
+
mocks.results.listPlaybookVersions = [versions(["draft", "2026-03-01"], ["0.1.0", "2026-01-01"])];
|
|
142
|
+
await expect(pushWith()).rejects.toThrow();
|
|
143
|
+
expect(called("createPlaybookVersion")).toHaveLength(0);
|
|
144
|
+
});
|
|
145
|
+
it("an explicit --version wins and the versions are not listed", async () => {
|
|
146
|
+
mocks.results.listPlaybookVersions = [versions(["draft", "2026-03-01"])];
|
|
147
|
+
await pushWith(["--version", "2.0.0"]);
|
|
148
|
+
expect(called("listPlaybookVersions")).toHaveLength(0);
|
|
149
|
+
expect(called("createPlaybookVersion")[0].args[1].version).toBe("2.0.0");
|
|
150
|
+
});
|
|
151
|
+
it("push with a uuid adds a version instead of creating a playbook", async () => {
|
|
152
|
+
mocks.results.listPlaybookVersions = [versions(["0.1.0", "2026-01-01"])];
|
|
153
|
+
await run(["push", "-f", writeJSON("u.json", { name: "Pb", graph }), "-u", "pb1", "--note", "tweak"]);
|
|
154
|
+
expect(called("createPlaybook")).toHaveLength(0);
|
|
155
|
+
expect(called("createPlaybookVersion")[0].args).toEqual(["pb1", { version: "0.1.1", note: "tweak" }]);
|
|
156
|
+
expect(called("savePlaybookVersion")[0].args).toEqual(["pb1", "0.2.0", { graph, note: "tweak" }]);
|
|
157
|
+
expect(out.join("\n")).toContain("Saved version 0.2.0");
|
|
158
|
+
});
|
|
159
|
+
it("push refuses a file with problems and sends nothing", async () => {
|
|
160
|
+
await run(["push", "-f", writeJSON("p.json", { name: "x", graph: { nodes: [], edges: [] } })]);
|
|
161
|
+
expect(process.exitCode).toBe(1);
|
|
162
|
+
expect(mocks.calls).toHaveLength(0);
|
|
163
|
+
});
|
|
164
|
+
it("deploy and rollback send version and env", async () => {
|
|
165
|
+
await run(["deploy", "-u", "pb1", "--version", "1.2.0", "--env", "live"]);
|
|
166
|
+
expect(called("deployPlaybook")[0].args).toEqual(["pb1", { version: "1.2.0", env: "live" }]);
|
|
167
|
+
await run(["rollback", "-u", "pb1", "--env", "dev"]);
|
|
168
|
+
expect(called("rollbackPlaybook")[0].args).toEqual(["pb1", { env: "dev" }]);
|
|
169
|
+
});
|
|
170
|
+
it("run sends env, instructions and input, prints the run, and does not poll without --wait", async () => {
|
|
171
|
+
await run(["run", "-u", "pb1", "--env", "live", "--instructions", "go", "--input", writeJSON("in.json", { a: 1 })]);
|
|
172
|
+
expect(called("startPlaybookRun")[0].args).toEqual(["pb1", { env: "live", instructions: "go", input: { a: 1 } }]);
|
|
173
|
+
expect(out.join("\n")).toContain("Run run1 queued");
|
|
174
|
+
expect(called("getRun")).toHaveLength(0);
|
|
175
|
+
});
|
|
176
|
+
it("--wait polls until the run is done", async () => {
|
|
177
|
+
mocks.results.getRun = [
|
|
178
|
+
{ run: { uuid: "run1", status: "running" }, steps: [] },
|
|
179
|
+
{ run: { uuid: "run1", status: "completed", summary: "All done" }, steps: [] },
|
|
180
|
+
];
|
|
181
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
182
|
+
expect(called("getRun")).toHaveLength(2);
|
|
183
|
+
expect(out.join("\n")).toContain("Run run1 completed");
|
|
184
|
+
expect(out.join("\n")).toContain("All done");
|
|
185
|
+
expect(process.exitCode).toBeUndefined();
|
|
186
|
+
});
|
|
187
|
+
it("--wait stops on needs-you and names the waiting step (exit 2)", async () => {
|
|
188
|
+
mocks.results.getRun = [
|
|
189
|
+
{ run: { uuid: "run1", status: "running" }, steps: [] },
|
|
190
|
+
{ run: { uuid: "run1", status: "awaiting_approval" }, steps: [
|
|
191
|
+
{ index: 1, kind: "think", status: "completed", label: "Plan" },
|
|
192
|
+
{ index: 2, kind: "approval", status: "running", label: "Send the email", approval: { decision: "pending" } },
|
|
193
|
+
] },
|
|
194
|
+
];
|
|
195
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
196
|
+
expect(called("getRun")).toHaveLength(2);
|
|
197
|
+
expect(out.join("\n")).toContain("Waiting on you at step 2: Send the email");
|
|
198
|
+
expect(process.exitCode).toBe(2);
|
|
199
|
+
});
|
|
200
|
+
it("--wait exits 1 when the run fails", async () => {
|
|
201
|
+
mocks.results.getRun = [{ run: { uuid: "run1", status: "failed", error_message: "boom" }, steps: [] }];
|
|
202
|
+
await run(["run", "-u", "pb1", "--wait"]);
|
|
203
|
+
expect(process.exitCode).toBe(1);
|
|
204
|
+
expect(err.join("\n")).toContain("boom");
|
|
205
|
+
});
|
|
206
|
+
it("--wait stops when nobody answered in time and exits 1", async () => {
|
|
207
|
+
mocks.results.getRun = [
|
|
208
|
+
{ run: { uuid: "run1", status: "running" }, steps: [] },
|
|
209
|
+
{ run: { uuid: "run1", status: "expired", stop_reason: "approval_expired", summary: "Stopped because nobody decided in time." }, steps: [] },
|
|
210
|
+
];
|
|
211
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
212
|
+
expect(out.join("\n")).toContain("Run run1 expired");
|
|
213
|
+
expect(process.exitCode).toBe(1);
|
|
214
|
+
});
|
|
215
|
+
it("runs passes the playbook and status filters; run-get fetches one run", async () => {
|
|
216
|
+
await run(["runs", "--playbook", "pb1", "--status", "failed", "-l", "5"]);
|
|
217
|
+
expect(called("listRuns")[0].args[0]).toEqual({ page: undefined, limit: 5, playbook: "pb1", status: "failed" });
|
|
218
|
+
await run(["run-get", "-u", "run1"]);
|
|
219
|
+
expect(called("getRun")[0].args[0]).toBe("run1");
|
|
220
|
+
});
|
|
221
|
+
const schema = { type: "object", properties: { priority: { type: "string", enum: ["low", "high"] }, text: { type: "string" } }, required: ["priority", "text"] };
|
|
222
|
+
const withSchema = (rs, extra = {}) => ({
|
|
223
|
+
graph: { nodes: [graph.nodes[0], { ...graph.nodes[1], result_schema: rs, ...extra }], edges: graph.edges },
|
|
224
|
+
});
|
|
225
|
+
const problemsFor = async (file) => {
|
|
226
|
+
err.length = 0;
|
|
227
|
+
process.exitCode = undefined;
|
|
228
|
+
await run(["validate", "-f", writeJSON("rs.json", file)]);
|
|
229
|
+
return err.join("\n");
|
|
230
|
+
};
|
|
231
|
+
it("result_schema survives pull and push, and a good schema validates", async () => {
|
|
232
|
+
const g = withSchema(schema).graph;
|
|
233
|
+
mocks.results.getPlaybookVersion = [{ version: "1.0.0", graph: g }];
|
|
234
|
+
mocks.results.listPlaybookVersions = [{ data: [{ version: "1.0.0", created_at: "2026-01-01" }] }];
|
|
235
|
+
const file = join(dir, "rs.json");
|
|
236
|
+
await run(["pull", "-u", "pb1", "-o", file]);
|
|
237
|
+
expect(JSON.parse(readFileSync(file, "utf8")).graph.nodes[1].result_schema).toEqual(schema);
|
|
238
|
+
await run(["push", "-f", file]);
|
|
239
|
+
expect(called("savePlaybookVersion")[0].args[2].graph.nodes[1].result_schema).toEqual(schema);
|
|
240
|
+
expect(await problemsFor(withSchema(schema))).toBe("");
|
|
241
|
+
expect(process.exitCode).toBeUndefined();
|
|
242
|
+
});
|
|
243
|
+
it("validate flags a schema that is not on an end step or is on a condition", async () => {
|
|
244
|
+
const notEnd = { graph: { nodes: [{ ...graph.nodes[0], result_schema: schema }, graph.nodes[1]], edges: graph.edges } };
|
|
245
|
+
expect(await problemsFor(notEnd)).toContain("Only a last step can return a result.");
|
|
246
|
+
expect(process.exitCode).toBe(1);
|
|
247
|
+
const cond = withSchema(schema, { kind: "condition", title: "Pick" });
|
|
248
|
+
expect(await problemsFor(cond)).toContain('Step "Pick" is a choice and cannot return a result.');
|
|
249
|
+
});
|
|
250
|
+
it("validate checks the schema's rules with the server's words", async () => {
|
|
251
|
+
expect(await problemsFor(withSchema({ type: "array" }))).toContain('the result: the top level must be an object, with "type": "object".');
|
|
252
|
+
expect(await problemsFor(withSchema({ type: "object", properties: { a: {} } }))).toContain('field \'a\': it needs a "type": object, array, string, number, integer or boolean.');
|
|
253
|
+
expect(await problemsFor(withSchema({ type: "object", properties: { a: { type: "string", minLength: 1 } } }))).toContain("field 'a': 'minLength' is not supported. Use only type, properties, required, items, enum, description and additionalProperties.");
|
|
254
|
+
expect(await problemsFor(withSchema({ type: "object", properties: { a: { type: "string" } }, required: ["b"] }))).toContain("the result: required lists 'b', which is not among its properties.");
|
|
255
|
+
expect(await problemsFor(withSchema({ type: "object", additionalProperties: {} }))).toContain("the result: additionalProperties must be true or false.");
|
|
256
|
+
const deep = { type: "object", properties: { a: { type: "object", properties: { b: { type: "object", properties: { c: { type: "object", properties: { d: { type: "object", properties: { e: { type: "string" } } } } } } } } } } };
|
|
257
|
+
expect(await problemsFor(withSchema(deep))).toContain("field 'a.b.c.d.e': nested too deeply (at most 5 levels).");
|
|
258
|
+
});
|
|
259
|
+
it("run --wait and run-get print the result; result_invalid exits 1", async () => {
|
|
260
|
+
const result = { reply: { priority: "high", text: "hello" } };
|
|
261
|
+
mocks.results.getRun = [{ run: { uuid: "run1", status: "completed", summary: "ok", result }, steps: [] }];
|
|
262
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
263
|
+
expect(out.join("\n")).toContain(JSON.stringify(result, null, 2));
|
|
264
|
+
expect(process.exitCode).toBeUndefined();
|
|
265
|
+
out.length = 0;
|
|
266
|
+
mocks.results.getRun = [{ run: { uuid: "run1", status: "failed", stop_reason: "result_invalid", result }, steps: [] }];
|
|
267
|
+
await run(["run-get", "-u", "run1"]);
|
|
268
|
+
expect(out.join("\n")).toContain(JSON.stringify(result, null, 2));
|
|
269
|
+
expect(process.exitCode).toBe(1);
|
|
270
|
+
process.exitCode = undefined;
|
|
271
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
272
|
+
expect(process.exitCode).toBe(1);
|
|
273
|
+
});
|
|
274
|
+
it("fails with a clear message when the installed SDK has no Workforce methods", async () => {
|
|
275
|
+
const saved = mocks.client.listPlaybooks;
|
|
276
|
+
delete mocks.client.listPlaybooks;
|
|
277
|
+
const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined));
|
|
278
|
+
try {
|
|
279
|
+
await run(["list"]);
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
mocks.client.listPlaybooks = saved;
|
|
283
|
+
}
|
|
284
|
+
expect(exit).toHaveBeenCalledWith(1);
|
|
285
|
+
expect(err.join("\n")).toContain("@ptkl/sdk 1.23.0 or newer");
|
|
286
|
+
});
|
|
287
|
+
it("--wait refuses an interval that is not a number", async () => {
|
|
288
|
+
const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined));
|
|
289
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "3s"]);
|
|
290
|
+
expect(exit).toHaveBeenCalledWith(1);
|
|
291
|
+
expect(err.join("\n")).toContain("--interval must be a number");
|
|
292
|
+
expect(called("getRun")).toHaveLength(0);
|
|
293
|
+
});
|
|
294
|
+
it("--wait keeps polling through a transient API error instead of exiting 1", async () => {
|
|
295
|
+
let n = 0;
|
|
296
|
+
const original = mocks.client.getRun;
|
|
297
|
+
mocks.client.getRun = async (...args) => {
|
|
298
|
+
if (++n === 2)
|
|
299
|
+
throw Object.assign(new Error("bad gateway"), { response: { status: 503, data: "" } });
|
|
300
|
+
return original(...args);
|
|
301
|
+
};
|
|
302
|
+
mocks.results.getRun = [
|
|
303
|
+
{ run: { uuid: "run1", status: "running" }, steps: [] },
|
|
304
|
+
{ run: { uuid: "run1", status: "completed" }, steps: [] },
|
|
305
|
+
];
|
|
306
|
+
try {
|
|
307
|
+
await run(["run", "-u", "pb1", "--wait", "--interval", "1"]);
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
mocks.client.getRun = original;
|
|
311
|
+
}
|
|
312
|
+
expect(out.join("\n")).toContain("Run run1 completed");
|
|
313
|
+
expect(process.exitCode).toBeUndefined();
|
|
314
|
+
});
|
|
315
|
+
it("push says which playbook exists when the save is refused", async () => {
|
|
316
|
+
const original = mocks.client.savePlaybookVersion;
|
|
317
|
+
mocks.client.savePlaybookVersion = async () => { throw new Error("step text is at most 8000 characters"); };
|
|
318
|
+
const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined));
|
|
319
|
+
try {
|
|
320
|
+
await run(["push", "-f", writeJSON("s.json", { name: "Pb", graph })]);
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
mocks.client.savePlaybookVersion = original;
|
|
324
|
+
}
|
|
325
|
+
expect(exit).toHaveBeenCalledWith(1);
|
|
326
|
+
expect(err.join("\n")).toContain("push again with -u new1");
|
|
327
|
+
});
|
|
328
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
// The role command is a thin wrapper over the SDK `Users` client; these tests pin the wiring that
|
|
4
|
+
// broke in core/toolkit#10 (`role()` does not exist on the Platform client) and keep
|
|
5
|
+
// `permissions-list` from calling the roles list endpoint.
|
|
6
|
+
const mocks = vi.hoisted(() => {
|
|
7
|
+
const calls = [];
|
|
8
|
+
const record = (method) => async (...args) => {
|
|
9
|
+
calls.push({ method, args });
|
|
10
|
+
return { data: { method, args } };
|
|
11
|
+
};
|
|
12
|
+
const users = {
|
|
13
|
+
createRole: record("createRole"),
|
|
14
|
+
listRoles: record("listRoles"),
|
|
15
|
+
listPermissions: record("listPermissions"),
|
|
16
|
+
editRole: record("editRole"),
|
|
17
|
+
deleteRole: record("deleteRole"),
|
|
18
|
+
};
|
|
19
|
+
return { calls, users, platform: { user: () => users } };
|
|
20
|
+
});
|
|
21
|
+
vi.mock("../../lib/sdk.js", () => ({ platform: () => mocks.platform }));
|
|
22
|
+
vi.mock("../../lib/util.js", () => ({
|
|
23
|
+
default: {
|
|
24
|
+
getCurrentProfile: () => ({ name: "test", host: "http://platform.test", token: "t", project: "p" }),
|
|
25
|
+
},
|
|
26
|
+
}));
|
|
27
|
+
import role from "../role.js";
|
|
28
|
+
const run = async (args) => {
|
|
29
|
+
const program = new Command().name("ptkl").exitOverride();
|
|
30
|
+
program.addCommand(role.register());
|
|
31
|
+
const printed = [];
|
|
32
|
+
const log = vi.spyOn(console, "log").mockImplementation((...a) => {
|
|
33
|
+
printed.push(a.map((x) => String(x)).join(" "));
|
|
34
|
+
});
|
|
35
|
+
try {
|
|
36
|
+
await program.parseAsync(["role", ...args], { from: "user" });
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
log.mockRestore();
|
|
40
|
+
}
|
|
41
|
+
return { output: () => JSON.parse(printed.join("\n").replace(/\u001b\[[0-9;]*m/g, "")) };
|
|
42
|
+
};
|
|
43
|
+
describe("role command", () => {
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
mocks.calls.length = 0;
|
|
46
|
+
});
|
|
47
|
+
it("list reads roles through the users client and prints its data", async () => {
|
|
48
|
+
const { output } = await run(["list", "-f", "json"]);
|
|
49
|
+
expect(mocks.calls).toEqual([{ method: "listRoles", args: [] }]);
|
|
50
|
+
expect(output()).toEqual({ method: "listRoles", args: [] });
|
|
51
|
+
});
|
|
52
|
+
it("permissions-list reads the permissions catalogue, not the roles list", async () => {
|
|
53
|
+
const { output } = await run(["permissions-list", "-f", "json"]);
|
|
54
|
+
expect(mocks.calls).toEqual([{ method: "listPermissions", args: [] }]);
|
|
55
|
+
expect(output()).toEqual({ method: "listPermissions", args: [] });
|
|
56
|
+
});
|
|
57
|
+
it("create sends the role payload with a numeric level", async () => {
|
|
58
|
+
const { output } = await run(["create", "-n", "support", "-p", "read base_users", "-w", "ws-1", "-l", "5", "-f", "json"]);
|
|
59
|
+
const role = { name: "support", permissions: ["read base_users"], workspaces: ["ws-1"], level: 5 };
|
|
60
|
+
expect(mocks.calls).toEqual([{ method: "createRole", args: [role] }]);
|
|
61
|
+
expect(output()).toEqual({ method: "createRole", args: [role] });
|
|
62
|
+
});
|
|
63
|
+
it("create defaults the level to 0", async () => {
|
|
64
|
+
await run(["create", "-n", "support", "-p", "read base_users", "edit base_users", "-w", "ws-1", "ws-2"]);
|
|
65
|
+
expect(mocks.calls[0].args[0]).toEqual({
|
|
66
|
+
name: "support",
|
|
67
|
+
permissions: ["read base_users", "edit base_users"],
|
|
68
|
+
workspaces: ["ws-1", "ws-2"],
|
|
69
|
+
level: 0,
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
it("edit sends the uuid separately from the editable fields", async () => {
|
|
73
|
+
const { output } = await run(["edit", "-u", "role-1", "-p", "read base_users", "edit base_users", "-w", "ws-1", "-l", "7", "-f", "json"]);
|
|
74
|
+
const fields = { permissions: ["read base_users", "edit base_users"], workspaces: ["ws-1"], level: 7 };
|
|
75
|
+
expect(mocks.calls).toEqual([{ method: "editRole", args: ["role-1", fields] }]);
|
|
76
|
+
expect(output()).toEqual({ method: "editRole", args: ["role-1", fields] });
|
|
77
|
+
});
|
|
78
|
+
it("delete removes the role by uuid", async () => {
|
|
79
|
+
const { output } = await run(["delete", "-u", "role-1", "-f", "json"]);
|
|
80
|
+
expect(mocks.calls).toEqual([{ method: "deleteRole", args: ["role-1"] }]);
|
|
81
|
+
expect(output()).toEqual({ method: "deleteRole", args: ["role-1"] });
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const update = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
4
|
+
const get = vi.fn();
|
|
5
|
+
const ask = vi.fn();
|
|
6
|
+
vi.mock('../../lib/sdk.js', () => ({
|
|
7
|
+
platform: () => ({ function: () => ({ client: { post, get }, update }) }),
|
|
8
|
+
}));
|
|
9
|
+
vi.mock('../../lib/util.js', () => ({
|
|
10
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
11
|
+
}));
|
|
12
|
+
vi.mock('../../lib/runIdentity.js', async (orig) => {
|
|
13
|
+
const mod = await orig();
|
|
14
|
+
const Real = mod.default;
|
|
15
|
+
return { ...mod, default: class extends Real {
|
|
16
|
+
constructor(http, interactive) { super(http, interactive, ask); }
|
|
17
|
+
} };
|
|
18
|
+
});
|
|
19
|
+
import functions from '../functions.js';
|
|
20
|
+
const run = (...args) => functions.register().parseAsync(['node', 'functions', ...args]);
|
|
21
|
+
describe('functions --run-as', () => {
|
|
22
|
+
const saved = [process.stdin.isTTY, process.stdout.isTTY];
|
|
23
|
+
const setTty = (v) => {
|
|
24
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: v, configurable: true });
|
|
25
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: v, configurable: true });
|
|
26
|
+
};
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: saved[0], configurable: true });
|
|
29
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: saved[1], configurable: true });
|
|
30
|
+
});
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
setTty(false);
|
|
33
|
+
ask.mockReset();
|
|
34
|
+
post.mockClear();
|
|
35
|
+
update.mockClear();
|
|
36
|
+
get.mockClear();
|
|
37
|
+
});
|
|
38
|
+
it('create sends --run-as as top-level run_as', async () => {
|
|
39
|
+
await run('create', '-d', '{"name":"f"}', '--run-as', 'prn:role:1');
|
|
40
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f', run_as: 'prn:role:1' });
|
|
41
|
+
});
|
|
42
|
+
it('create without a tty sends no run_as and does not fetch choices', async () => {
|
|
43
|
+
await run('create', '-d', '{"name":"f"}');
|
|
44
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f' });
|
|
45
|
+
expect(get).not.toHaveBeenCalled();
|
|
46
|
+
});
|
|
47
|
+
it('update without the flag sends no run_as', async () => {
|
|
48
|
+
await run('update', 'u1', '-d', '{"name":"g"}');
|
|
49
|
+
expect(update).toHaveBeenCalledWith('u1', { name: 'g' });
|
|
50
|
+
});
|
|
51
|
+
it('update with the flag sends run_as', async () => {
|
|
52
|
+
await run('update', 'u1', '-d', '{"name":"g"}', '--run-as', 'prn:role:1');
|
|
53
|
+
expect(update).toHaveBeenCalledWith('u1', { name: 'g', run_as: 'prn:role:1' });
|
|
54
|
+
});
|
|
55
|
+
it('create with a tty sends the picked identity', async () => {
|
|
56
|
+
setTty(true);
|
|
57
|
+
get.mockResolvedValue({ data: { identities: [{ prn: 'prn:role:1', kind: 'role', name: 'Editors' }] } });
|
|
58
|
+
ask.mockResolvedValue('prn:role:1');
|
|
59
|
+
await run('create', '-d', '{"name":"f"}');
|
|
60
|
+
expect(get).toHaveBeenCalledWith('/v1/system/run-identity/choices');
|
|
61
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f', run_as: 'prn:role:1' });
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
// The point of core/toolkit#17 is the request body, so these drive the real @ptkl/sdk Thunder client with
|
|
3
|
+
// only its HTTP layer stubbed: the options must survive Thunder.read()'s `const { only, ...options }` split.
|
|
4
|
+
const post = vi.fn(async (_path, _body) => ({ data: { total: 0, pages: 0, items: [] } }));
|
|
5
|
+
vi.mock('../../lib/sdk.js', async () => {
|
|
6
|
+
const { Thunder } = await import('@ptkl/sdk/beta');
|
|
7
|
+
const thunder = new Thunder({ host: 'http://h', token: 't', env: 'dev' });
|
|
8
|
+
thunder.client = { post };
|
|
9
|
+
return { thunder: () => thunder };
|
|
10
|
+
});
|
|
11
|
+
vi.mock('../../lib/util.js', () => ({
|
|
12
|
+
default: { getCurrentProfile: () => ({ name: 'p', host: 'http://h', project: 'proj', token: 't' }) },
|
|
13
|
+
}));
|
|
14
|
+
const { default: ThunderCommand } = await import('../thunder.js');
|
|
15
|
+
const { Command } = await import('commander');
|
|
16
|
+
vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
17
|
+
async function run(...args) {
|
|
18
|
+
const program = new Command().exitOverride();
|
|
19
|
+
program.addCommand(ThunderCommand.register());
|
|
20
|
+
await program.parseAsync(['node', 'ptkl', 'thunder', ...args, '-f', 'json']);
|
|
21
|
+
return post.mock.calls.at(-1);
|
|
22
|
+
}
|
|
23
|
+
describe('thunder paginate request body', () => {
|
|
24
|
+
it('sends a page size and offset when no page flags are given', async () => {
|
|
25
|
+
const [path, body] = await run('paginate', '-t', 'qa-th');
|
|
26
|
+
expect(path).toBe('/v3/system/thunder');
|
|
27
|
+
expect(body).toMatchObject({ type: 'qa-th', filters: {}, flag: 'Paginate', options: { limit: 20, skip: 0 } });
|
|
28
|
+
});
|
|
29
|
+
it('sends --limit, --skip, --sort and --only on the same read', async () => {
|
|
30
|
+
const [, body] = await run('paginate', '-t', 'qa-th', '--limit', '5', '--skip', '2', '--sort', '{"data.n":-1}', '--only', 'n');
|
|
31
|
+
expect(body).toMatchObject({
|
|
32
|
+
flag: 'Paginate',
|
|
33
|
+
options: { limit: 5, skip: 2, sort: [{ Key: 'data.n', Value: -1 }] },
|
|
34
|
+
only: ['n'],
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
it('paginates from the low-level read command too', async () => {
|
|
38
|
+
const [, body] = await run('read', '-t', 'qa-th', '--flag', 'Paginate', '-l', '1');
|
|
39
|
+
expect(body).toMatchObject({ flag: 'Paginate', options: { limit: 1, skip: 0 } });
|
|
40
|
+
});
|
|
41
|
+
it('leaves find without an options block', async () => {
|
|
42
|
+
const [, body] = await run('find', '-t', 'qa-th');
|
|
43
|
+
expect(body).toMatchObject({ flag: 'Find', filters: {} });
|
|
44
|
+
expect(body.options).toBeUndefined();
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -4,6 +4,7 @@ import { WebSocketServer } from "ws";
|
|
|
4
4
|
import { resolve, join, dirname } from "path";
|
|
5
5
|
import { rollup } from "rollup";
|
|
6
6
|
import util from "../lib/util.js";
|
|
7
|
+
import RunIdentityService from "../lib/runIdentity.js";
|
|
7
8
|
import { Platform as Api } from "@ptkl/sdk";
|
|
8
9
|
import OutputFormatCommand from "./outputCommand.js";
|
|
9
10
|
import { mkdirSync, writeFileSync, rmSync, readdirSync, existsSync, readFileSync } from "fs";
|
|
@@ -112,13 +113,15 @@ class ComponentCommand {
|
|
|
112
113
|
.option("--scope <scope>", "Component scope")
|
|
113
114
|
.option("--publish", "Publish the initial version immediately")
|
|
114
115
|
.option("-d, --data <data>", "Full create payload as JSON string (overrides other options)")
|
|
115
|
-
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
116
|
+
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
117
|
+
.option("--run-as <prn>", "Identity the component runs as (prompted for when interactive)")).action(this.createComponent))
|
|
116
118
|
.addCommand(new Command("update-settings")
|
|
117
119
|
.description("Save/update component settings for a version")
|
|
118
120
|
.requiredOption("-r, --ref <ref>", "Component ref")
|
|
119
121
|
.requiredOption("-v, --version <version>", "Component version")
|
|
120
122
|
.option("-d, --data <data>", "Settings as JSON string")
|
|
121
123
|
.option("-i, --file <file>", "Path to a JSON file containing the settings")
|
|
124
|
+
.option("--run-as <prn>", "Change the identity the component's code runs as")
|
|
122
125
|
.action(this.updateSettings))
|
|
123
126
|
.addCommand(new OutputFormatCommand(new Command("fork-version")
|
|
124
127
|
.description("Fork a component version to create a new one")
|
|
@@ -650,7 +653,9 @@ class ComponentCommand {
|
|
|
650
653
|
...(publish !== undefined && { publish }),
|
|
651
654
|
};
|
|
652
655
|
}
|
|
653
|
-
const
|
|
656
|
+
const identity = new RunIdentityService(httpClient);
|
|
657
|
+
const runAs = await identity.forCreate(opts.runAs);
|
|
658
|
+
const { data } = await httpClient.post("/v3/system/component/create", identity.withRunAs(payload, runAs));
|
|
654
659
|
return data;
|
|
655
660
|
}
|
|
656
661
|
async updateSettings(opts) {
|
|
@@ -664,7 +669,8 @@ class ComponentCommand {
|
|
|
664
669
|
const settings = file
|
|
665
670
|
? JSON.parse(readFileSync(resolve(file), "utf-8"))
|
|
666
671
|
: JSON.parse(dataStr);
|
|
667
|
-
const
|
|
672
|
+
const identity = new RunIdentityService();
|
|
673
|
+
const { data } = await client.saveSettings(identity.withRunAs(settings, opts.runAs), version);
|
|
668
674
|
return data;
|
|
669
675
|
}
|
|
670
676
|
async forkVersion(opts) {
|