@ptkl/toolkit 1.5.0 → 1.7.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 +20 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +12 -0
- package/dist/commands/__tests__/forge-tools.test.js +64 -0
- package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
- package/dist/commands/forge.js +159 -70
- package/dist/commands/kortex.js +8 -6
- package/dist/commands/kortexPlaybook.js +396 -0
- package/dist/lib/__tests__/apiError.test.js +4 -0
- package/dist/lib/apiError.js +12 -1
- 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__/playbookToolStep.test.js +31 -0
- package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
- package/dist/lib/kortex/playbookValidator.js +322 -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/package.json +2 -2
package/README.md
CHANGED
|
@@ -131,6 +131,26 @@ You can override the active profile for any command using the global `--profile`
|
|
|
131
131
|
ptkl --profile production apps upload -a app -d ./my-app
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
+
## Workforce playbooks as files
|
|
135
|
+
|
|
136
|
+
`ptkl kortex playbook` manages Workforce playbooks as JSON files, so a developer (or an agent in a repo) can pull one, edit it, check it, push a version, deploy it and run it. Needs a `--legacy` profile (see above).
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
ptkl kortex playbook list
|
|
140
|
+
ptkl kortex playbook pull -u <playbook-uuid> -o refund.json # {uuid, name, description, version, graph}
|
|
141
|
+
ptkl kortex playbook validate -f refund.json # offline; exit 1 when there are problems
|
|
142
|
+
ptkl kortex playbook rule-check --when 'input.amount > 500' --input sample.json # the server checks a rule's syntax and tries it
|
|
143
|
+
ptkl kortex playbook push -f refund.json --note "tighter step 2" # creates the playbook if the file has no uuid
|
|
144
|
+
ptkl kortex playbook deploy -u <uuid> --version 0.2.0 --env dev
|
|
145
|
+
ptkl kortex playbook run -u <uuid> --env dev --instructions "Refund order 42" --wait
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
- A condition can decide by rules (`"decide_by": "rules"`): no agent, and each line out carries a `when` rule over `input` or `"otherwise": true`. `validate` checks that offline (a rule on every line, one otherwise, no agent, at most 20 lines) but cannot read a rule's CEL syntax; only the server can, so use `rule-check` or validate the saved version with `-u`/`--version`.
|
|
149
|
+
- `pull` writes the version deployed in live, else dev, else the newest (`--version` picks one). The file keeps its `uuid`, so `push -f` adds a new version to the same playbook; `-u` overrides it. The new version is named by bumping the patch of the newest one (`0.1.0` becomes `0.1.1`, skipping names already taken); if the newest name is not `MAJOR.MINOR.PATCH`, pass `--version <name>`.
|
|
150
|
+
- `validate` checks the drawing locally (steps, lines, one start, no loops). Agents that are missing or disabled are only known to the server: `validate -u <uuid> --version <v>` asks it about a saved version.
|
|
151
|
+
- `run --wait` polls until the run ends or needs a person. Exit code: 0 done, 1 failed/killed/timed out, 2 waiting on a person (the step is printed), 3 `--timeout` reached.
|
|
152
|
+
- Also: `get`, `versions`, `rollback -u <uuid> --env`, `deployments`, `runs [--playbook] [--status]`, `run-get -u <run uuid>`.
|
|
153
|
+
|
|
134
154
|
## Run identity and code capabilities
|
|
135
155
|
|
|
136
156
|
Functions, components and workflows run as a run identity. `--run-as <prn>` sets it on create and changes it on update.
|
|
@@ -43,4 +43,16 @@ describe('forge bundle', () => {
|
|
|
43
43
|
expect(existsSync(at('server', manifest.services[0].script))).toBe(true);
|
|
44
44
|
expect(existsSync(at('browser', manifest.views.main))).toBe(true);
|
|
45
45
|
});
|
|
46
|
+
it('builds each tool like a service and lists it in the manifest', () => {
|
|
47
|
+
expect(manifest.tools).toEqual([{
|
|
48
|
+
name: 'echo_tool',
|
|
49
|
+
description: 'Echoes its input.',
|
|
50
|
+
input_schema: { type: 'object', properties: { text: { type: 'string' } } },
|
|
51
|
+
read_only: true,
|
|
52
|
+
destructive: false,
|
|
53
|
+
permissions: [],
|
|
54
|
+
script: 'tools/echo_tool.js',
|
|
55
|
+
}]);
|
|
56
|
+
expect(existsSync(bundleFilePath(join(app, 'dist'), 'server', manifest.tools[0].script))).toBe(true);
|
|
57
|
+
});
|
|
46
58
|
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { assertToolsAreValid, toolsManifest } from '../forge.js';
|
|
3
|
+
const tool = (over = {}) => ({
|
|
4
|
+
name: 'create_order',
|
|
5
|
+
description: 'Creates an order.',
|
|
6
|
+
input_schema: { type: 'object', properties: {} },
|
|
7
|
+
script: 'src/tools/create_order.ts',
|
|
8
|
+
...over,
|
|
9
|
+
});
|
|
10
|
+
const bad = (t, re, perms = []) => expect(() => assertToolsAreValid([t], perms)).toThrow(re);
|
|
11
|
+
describe('assertToolsAreValid', () => {
|
|
12
|
+
it('accepts no tools and a full declaration', () => {
|
|
13
|
+
expect(() => assertToolsAreValid(undefined)).not.toThrow();
|
|
14
|
+
expect(() => assertToolsAreValid([])).not.toThrow();
|
|
15
|
+
expect(() => assertToolsAreValid([tool({ read_only: false, destructive: true, permissions: ['a::b'] })], ['a::b', 'c::d'])).not.toThrow();
|
|
16
|
+
});
|
|
17
|
+
it('rejects bad names and duplicates', () => {
|
|
18
|
+
for (const name of ['', 'Create', '1abc', 'a-b', 'a'.repeat(65), undefined])
|
|
19
|
+
bad(tool({ name }), /name must match/);
|
|
20
|
+
expect(() => assertToolsAreValid([tool(), tool()])).toThrow(/declared twice/);
|
|
21
|
+
expect(() => assertToolsAreValid([tool({ name: 'a'.repeat(64) })])).not.toThrow();
|
|
22
|
+
});
|
|
23
|
+
it('requires a description of 1..1024 chars', () => {
|
|
24
|
+
bad(tool({ description: undefined }), /description is required/);
|
|
25
|
+
bad(tool({ description: 'x'.repeat(1025) }), /description is required/);
|
|
26
|
+
});
|
|
27
|
+
it('refuses properties that are not an object and required that is not a list of strings', () => {
|
|
28
|
+
bad(tool({ input_schema: { type: 'object', properties: [] } }), /properties must be an object/);
|
|
29
|
+
bad(tool({ input_schema: { type: 'object', required: 'email' } }), /required must be an array of strings/);
|
|
30
|
+
bad(tool({ input_schema: { type: 'object', required: [1] } }), /required must be an array of strings/);
|
|
31
|
+
});
|
|
32
|
+
it('requires an object input_schema within 16 KB', () => {
|
|
33
|
+
bad(tool({ input_schema: undefined }), /input_schema must be/);
|
|
34
|
+
bad(tool({ input_schema: { type: 'string' } }), /input_schema must be/);
|
|
35
|
+
bad(tool({ input_schema: { type: 'object', description: 'x'.repeat(16 * 1024) } }), /larger than 16 KB/);
|
|
36
|
+
});
|
|
37
|
+
it('rejects read_only with destructive and non-boolean flags', () => {
|
|
38
|
+
bad(tool({ read_only: true, destructive: true }), /both read_only and destructive/);
|
|
39
|
+
bad(tool({ read_only: 'yes' }), /read_only must be a boolean/);
|
|
40
|
+
});
|
|
41
|
+
it('keeps permissions inside runtime_permissions', () => {
|
|
42
|
+
bad(tool({ permissions: ['x::y'] }), /not in runtime_permissions: x::y/, ['a::b']);
|
|
43
|
+
bad(tool({ permissions: 'x' }), /array of strings/);
|
|
44
|
+
});
|
|
45
|
+
it('requires a script and at most 50 tools', () => {
|
|
46
|
+
bad(tool({ script: undefined }), /script is required/);
|
|
47
|
+
const many = Array.from({ length: 51 }, (_, i) => tool({ name: `t${i}` }));
|
|
48
|
+
expect(() => assertToolsAreValid(many)).toThrow(/at most 50/);
|
|
49
|
+
expect(() => assertToolsAreValid('x')).toThrow(/must be an array/);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
describe('toolsManifest', () => {
|
|
53
|
+
it('fills defaults and points the script at the built file', () => {
|
|
54
|
+
expect(toolsManifest([tool()])).toEqual([{
|
|
55
|
+
name: 'create_order',
|
|
56
|
+
description: 'Creates an order.',
|
|
57
|
+
input_schema: { type: 'object', properties: {} },
|
|
58
|
+
read_only: false,
|
|
59
|
+
destructive: false,
|
|
60
|
+
permissions: [],
|
|
61
|
+
script: 'tools/create_order.js',
|
|
62
|
+
}]);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -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
|
+
});
|