@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
package/README.md
CHANGED
|
@@ -117,7 +117,7 @@ If OAuth is not enabled on the host the command fails with a pointer to `--legac
|
|
|
117
117
|
|
|
118
118
|
**Legacy and CI.** `--legacy` (implied by `-u`, `-p` or `-t`) logs in as an API user (`/v1/user/api/auth`) or takes a token directly, e.g. `ptkl profile auth -t $TOKEN`. For CI use API-user tokens with `--legacy -t`.
|
|
119
119
|
|
|
120
|
-
Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts`), further limited by your own permissions in the project: apps, functions, components, templates, thunder, ratchet (read/inspect), users and roles (list), API users (`edit base_users` for list/get/edit/revoke-secret, `
|
|
120
|
+
Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts`), further limited by your own permissions in the project: apps, functions, components, templates, thunder, ratchet (read/inspect), users and roles (list), API users (`edit base_users` for list/get/edit/revoke-secret, `credentials::manage base_users` for new/new-secret), and `dev env_access` (non-live environments need `<env> env_access`; `dev` is the default — add others with `--add-scope "<env> env_access"`). Scope never grows by itself: re-run `ptkl profile auth` after creating resources whose per-resource permissions you need.
|
|
121
121
|
|
|
122
122
|
Access tokens (15 min) refresh transparently when a command starts, serialized across processes by a per-profile lock in `~/.ptkl` (the rotated refresh token is saved); long-running commands such as watch modes refresh only at start. If the session expired or was revoked you are asked to log in again. `profile inspect` masks tokens.
|
|
123
123
|
|
|
@@ -131,6 +131,39 @@ 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
|
+
|
|
154
|
+
## Run identity and code capabilities
|
|
155
|
+
|
|
156
|
+
Functions, components and workflows run as a run identity. `--run-as <prn>` sets it on create and changes it on update.
|
|
157
|
+
|
|
158
|
+
Capabilities are declared per unit, inside the JSON you already send, not with flags:
|
|
159
|
+
|
|
160
|
+
- a component function: `capabilities` on the function object in `settings.functions[]` (`component update-settings`);
|
|
161
|
+
- an expression node: `data.capabilities` on the node in a workflow graph or a component's `settings.events` (`workflow create|update|install`, `component update-settings`).
|
|
162
|
+
|
|
163
|
+
Absent or `null` means none declared; an array declares exactly those permissions (`[]` = none at all). Writes are whole, so leaving the field out clears it. `get` output returns the API data unchanged.
|
|
164
|
+
|
|
165
|
+
If the API refuses a write, the message names the unit (`function:<name>` or `node:<id>`) and capability: `capability_invalid` (unit, capability), `capability_not_held` (unit, capability) and `capability_not_held_by_identity` (unit, capability, run as).
|
|
166
|
+
|
|
134
167
|
## Forge
|
|
135
168
|
|
|
136
169
|
Commands for building and running Protokol Forge apps locally.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const fnUpdate = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
4
|
+
const fnGet = vi.fn();
|
|
5
|
+
const wfCreate = vi.fn(async (_body) => ({ data: { ok: true } }));
|
|
6
|
+
const wfUpdate = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
7
|
+
const wfInstall = vi.fn(async (_body) => ({ data: { ok: true } }));
|
|
8
|
+
const wfGet = vi.fn();
|
|
9
|
+
vi.mock('../../lib/sdk.js', () => ({
|
|
10
|
+
platform: () => ({
|
|
11
|
+
function: () => ({ client: { post, get: vi.fn() }, update: fnUpdate, get: fnGet }),
|
|
12
|
+
getPlatformClient: () => ({ post, get: vi.fn() }),
|
|
13
|
+
}),
|
|
14
|
+
workflow: () => ({ create: wfCreate, update: wfUpdate, install: wfInstall, get: wfGet }),
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('../../lib/util.js', () => ({
|
|
17
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
18
|
+
}));
|
|
19
|
+
import functions from '../functions.js';
|
|
20
|
+
import workflow from '../workflow.js';
|
|
21
|
+
const fn = (...a) => functions.register().parseAsync(['node', 'functions', ...a]);
|
|
22
|
+
const wf = (...a) => workflow.register().parseAsync(['node', 'workflow', ...a]);
|
|
23
|
+
let errors;
|
|
24
|
+
let logs;
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
vi.clearAllMocks();
|
|
27
|
+
errors = [];
|
|
28
|
+
logs = [];
|
|
29
|
+
vi.spyOn(console, 'error').mockImplementation((m) => { errors.push(String(m)); });
|
|
30
|
+
vi.spyOn(console, 'log').mockImplementation((m) => { logs.push(m); });
|
|
31
|
+
vi.spyOn(process, 'exit').mockImplementation(((c) => { throw new Error(`exit ${c}`); }));
|
|
32
|
+
});
|
|
33
|
+
describe('capabilities flags are gone', () => {
|
|
34
|
+
it('function create/update reject --capabilities and --clear-capabilities', async () => {
|
|
35
|
+
for (const flag of ['--capabilities', '--clear-capabilities']) {
|
|
36
|
+
await expect(fn('update', 'u1', '-d', '{}', flag, ...(flag === '--capabilities' ? ['a'] : []))).rejects.toThrow();
|
|
37
|
+
}
|
|
38
|
+
expect(fnUpdate).not.toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
it('workflow create/update/install reject the flags', async () => {
|
|
41
|
+
for (const sub of [['create'], ['update', 'w1'], ['install']]) {
|
|
42
|
+
await expect(wf(...sub, '-d', '{}', '--capabilities', 'a')).rejects.toThrow();
|
|
43
|
+
await expect(wf(...sub, '-d', '{}', '--clear-capabilities')).rejects.toThrow();
|
|
44
|
+
}
|
|
45
|
+
expect(wfCreate).not.toHaveBeenCalled();
|
|
46
|
+
expect(wfUpdate).not.toHaveBeenCalled();
|
|
47
|
+
expect(wfInstall).not.toHaveBeenCalled();
|
|
48
|
+
});
|
|
49
|
+
it('payloads are sent unchanged, capabilities inside settings and graph included', async () => {
|
|
50
|
+
const body = { name: 'f', settings: { functions: [{ name: 'a', expr: '1', capabilities: ['read x y'] }] } };
|
|
51
|
+
await fn('update', 'u1', '-d', JSON.stringify(body));
|
|
52
|
+
expect(fnUpdate).toHaveBeenLastCalledWith('u1', body);
|
|
53
|
+
const graph = { name: 'w', nodes: [{ id: 'n1', data: { capabilities: [] } }] };
|
|
54
|
+
await wf('update', 'w1', '-d', JSON.stringify(graph));
|
|
55
|
+
expect(wfUpdate).toHaveBeenLastCalledWith('w1', graph);
|
|
56
|
+
});
|
|
57
|
+
it('get output is the API data, with no capabilities label', async () => {
|
|
58
|
+
fnGet.mockResolvedValueOnce({ data: { name: 'f' } });
|
|
59
|
+
await fn('get', 'f');
|
|
60
|
+
expect(logs[0]).toEqual({ name: 'f' });
|
|
61
|
+
wfGet.mockResolvedValueOnce({ data: { name: 'w' } });
|
|
62
|
+
await wf('get', '-r', 'w');
|
|
63
|
+
expect(logs[1]).toEqual({ name: 'w' });
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe('refusals print unit and capability', () => {
|
|
67
|
+
it('capability_not_held', async () => {
|
|
68
|
+
fnUpdate.mockRejectedValueOnce({ response: { status: 403, data: { error: 'capability_not_held', unit: 'function:f', capability: 'secrets::read global_env', message: 'you do not hold it' } } });
|
|
69
|
+
await expect(fn('update', 'u1', '-d', '{}')).rejects.toThrow('exit 1');
|
|
70
|
+
const out = errors.join('\n');
|
|
71
|
+
expect(out).toContain('you do not hold it');
|
|
72
|
+
expect(out).toContain('unit: function:f');
|
|
73
|
+
expect(out).toContain('capability: secrets::read global_env');
|
|
74
|
+
});
|
|
75
|
+
it('capability_not_held_by_identity', async () => {
|
|
76
|
+
wfInstall.mockRejectedValueOnce({ response: { status: 403, data: { error: 'capability_not_held_by_identity', unit: 'node:n1', capability: 'x::y z', run_as: 'prn:role:1', message: 'identity lacks it' } } });
|
|
77
|
+
await expect(wf('install', '-d', '{}')).rejects.toThrow('exit 1');
|
|
78
|
+
const out = errors.join('\n');
|
|
79
|
+
expect(out).toContain('unit: node:n1');
|
|
80
|
+
expect(out).toContain('capability: x::y z');
|
|
81
|
+
expect(out).toContain('run as: prn:role:1');
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const get = vi.fn();
|
|
4
|
+
const ask = vi.fn();
|
|
5
|
+
vi.mock('@ptkl/sdk', () => ({
|
|
6
|
+
Platform: class {
|
|
7
|
+
getPlatformClient() { return { post, get }; }
|
|
8
|
+
},
|
|
9
|
+
}));
|
|
10
|
+
vi.mock('../../lib/util.js', () => ({
|
|
11
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('../../lib/runIdentity.js', async (orig) => {
|
|
14
|
+
const mod = await orig();
|
|
15
|
+
const Real = mod.default;
|
|
16
|
+
return { ...mod, default: class extends Real {
|
|
17
|
+
constructor(http, interactive) { super(http, interactive, ask); }
|
|
18
|
+
} };
|
|
19
|
+
});
|
|
20
|
+
import component from '../component.js';
|
|
21
|
+
const run = (...args) => component.register().parseAsync(['node', 'component', ...args]);
|
|
22
|
+
const URL = '/v3/system/component/create';
|
|
23
|
+
describe('component create --run-as', () => {
|
|
24
|
+
const saved = [process.stdin.isTTY, process.stdout.isTTY];
|
|
25
|
+
const setTty = (v) => {
|
|
26
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: v, configurable: true });
|
|
27
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: v, configurable: true });
|
|
28
|
+
};
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: saved[0], configurable: true });
|
|
31
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: saved[1], configurable: true });
|
|
32
|
+
});
|
|
33
|
+
beforeEach(() => {
|
|
34
|
+
setTty(false);
|
|
35
|
+
ask.mockReset();
|
|
36
|
+
post.mockClear();
|
|
37
|
+
get.mockReset();
|
|
38
|
+
});
|
|
39
|
+
it('sends --run-as with flag-built payload', async () => {
|
|
40
|
+
await run('create', '-n', 'N', '-t', 'tag', '--run-as', 'prn:role:1');
|
|
41
|
+
expect(post).toHaveBeenCalledWith(URL, expect.objectContaining({ name: 'N', tag: 'tag', run_as: 'prn:role:1' }));
|
|
42
|
+
});
|
|
43
|
+
it('sends --run-as with a --data payload', async () => {
|
|
44
|
+
await run('create', '-n', 'N', '-t', 'tag', '-d', '{"name":"c","tag":"t"}', '--run-as', 'prn:role:1');
|
|
45
|
+
expect(post).toHaveBeenCalledWith(URL, { name: 'c', tag: 't', run_as: 'prn:role:1' });
|
|
46
|
+
});
|
|
47
|
+
it('keeps run_as from a --data payload when no flag and no tty', async () => {
|
|
48
|
+
await run('create', '-n', 'N', '-t', 'tag', '-d', '{"name":"c","run_as":"prn:role:9"}');
|
|
49
|
+
expect(post).toHaveBeenCalledWith(URL, { name: 'c', run_as: 'prn:role:9' });
|
|
50
|
+
});
|
|
51
|
+
it('without flag or tty sends no run_as and does not fetch choices', async () => {
|
|
52
|
+
await run('create', '-n', 'N', '-t', 'tag');
|
|
53
|
+
const body = post.mock.calls[0][1];
|
|
54
|
+
expect(body).not.toHaveProperty('run_as');
|
|
55
|
+
expect(get).not.toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
it('with a tty sends the picked identity', async () => {
|
|
58
|
+
setTty(true);
|
|
59
|
+
get.mockResolvedValue({ data: { identities: [{ prn: 'prn:role:1', kind: 'role', name: 'Editors' }] } });
|
|
60
|
+
ask.mockResolvedValue('prn:role:1');
|
|
61
|
+
await run('create', '-n', 'N', '-t', 'tag');
|
|
62
|
+
expect(get).toHaveBeenCalledWith('/v1/system/run-identity/choices');
|
|
63
|
+
expect(post).toHaveBeenCalledWith(URL, expect.objectContaining({ run_as: 'prn:role:1' }));
|
|
64
|
+
});
|
|
65
|
+
});
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdtempSync, readFileSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
import { beforeAll, describe, expect, it } from 'vitest';
|
|
6
|
+
import forgeCommand, { bundleFilePath } from '../forge.js';
|
|
7
|
+
// A real `forge bundle` of a fixture app, because what a bundle writes and what its manifest
|
|
8
|
+
// declares have to agree and only a build can show that. Both halves broke once: the manifest
|
|
9
|
+
// named a script the build did not emit, and `forge install` read a folder the build no longer
|
|
10
|
+
// wrote to.
|
|
11
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
let app;
|
|
13
|
+
let manifest;
|
|
14
|
+
describe('forge bundle', () => {
|
|
15
|
+
beforeAll(async () => {
|
|
16
|
+
app = join(mkdtempSync(join(tmpdir(), 'ptkl-bundle-')), 'app');
|
|
17
|
+
cpSync(join(here, '__fixtures__', 'bundleApp'), app, { recursive: true });
|
|
18
|
+
const cwd = process.cwd();
|
|
19
|
+
try {
|
|
20
|
+
await forgeCommand.bundle({ path: app, upload: false });
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
process.chdir(cwd);
|
|
24
|
+
}
|
|
25
|
+
manifest = JSON.parse(readFileSync(join(app, 'dist', 'manifest.json'), 'utf-8'));
|
|
26
|
+
}, 120_000);
|
|
27
|
+
it('splits browser files from server files, and says so in the manifest', () => {
|
|
28
|
+
expect(manifest.layout).toBe(2);
|
|
29
|
+
expect(existsSync(join(app, 'dist', 'browser', 'main.bundle.js'))).toBe(true);
|
|
30
|
+
expect(existsSync(join(app, 'dist', 'server', 'services', 'svc.js'))).toBe(true);
|
|
31
|
+
expect(existsSync(join(app, 'dist', 'server', 'install.script.js'))).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
it('names a lifecycle script after its manifest key, not its entry file', () => {
|
|
34
|
+
// The fixture's install entry is src/setup.js. Naming the output after the entry emitted
|
|
35
|
+
// setup.script.js under a manifest declaring install.script.js: appservice refused the
|
|
36
|
+
// upload and `forge install` could not find it.
|
|
37
|
+
expect(manifest.scripts).toEqual({ install: 'install.script.js' });
|
|
38
|
+
expect(existsSync(join(app, 'dist', 'server', 'setup.script.js'))).toBe(false);
|
|
39
|
+
});
|
|
40
|
+
it('declares every file where the reader looks for it', () => {
|
|
41
|
+
const at = (kind, p) => bundleFilePath(join(app, 'dist'), kind, p);
|
|
42
|
+
expect(existsSync(at('server', manifest.scripts.install))).toBe(true);
|
|
43
|
+
expect(existsSync(at('server', manifest.services[0].script))).toBe(true);
|
|
44
|
+
expect(existsSync(at('browser', manifest.views.main))).toBe(true);
|
|
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
|
+
});
|
|
58
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { bundleFilePath } from '../forge.js';
|
|
6
|
+
const dist = (manifest) => {
|
|
7
|
+
const dir = mkdtempSync(join(tmpdir(), 'ptkl-dist-'));
|
|
8
|
+
mkdirSync(join(dir, 'server'), { recursive: true });
|
|
9
|
+
if (manifest !== undefined)
|
|
10
|
+
writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifest));
|
|
11
|
+
return dir;
|
|
12
|
+
};
|
|
13
|
+
describe('bundleFilePath', () => {
|
|
14
|
+
it('reads a layout 2 bundle out of its kind folder, where bundle writes it', () => {
|
|
15
|
+
const dir = dist({ layout: 2 });
|
|
16
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'server', 'install.script.js'));
|
|
17
|
+
expect(bundleFilePath(dir, 'browser', 'index.js')).toBe(join(dir, 'browser', 'index.js'));
|
|
18
|
+
});
|
|
19
|
+
it('reads an older flat bundle from the root', () => {
|
|
20
|
+
const dir = dist({ name: 'app' });
|
|
21
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
22
|
+
});
|
|
23
|
+
it('falls back to flat when nothing is built, so the caller reports the missing file', () => {
|
|
24
|
+
const dir = dist();
|
|
25
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
26
|
+
writeFileSync(join(dir, 'manifest.json'), 'not json');
|
|
27
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -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,16 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { assertVariablesAreDefaults } from '../forge.js';
|
|
3
|
+
describe('assertVariablesAreDefaults', () => {
|
|
4
|
+
it('accepts an absent block, plain values and secretgen::', () => {
|
|
5
|
+
expect(() => assertVariablesAreDefaults(undefined)).not.toThrow();
|
|
6
|
+
expect(() => assertVariablesAreDefaults({ dev: { A: '1', N: { G: 'secretgen::random(32)' } }, live: {} })).not.toThrow();
|
|
7
|
+
});
|
|
8
|
+
it('refuses a secret:: value naming the key', () => {
|
|
9
|
+
expect(() => assertVariablesAreDefaults({ dev: { N: { K: 'secret::abcdefgh12' } } })).toThrow(/variables\.dev\.N\.K/);
|
|
10
|
+
expect(() => assertVariablesAreDefaults({ live: { K: 'secretref::' } })).toThrow(/variables\.live\.K/);
|
|
11
|
+
});
|
|
12
|
+
it('refuses an unknown environment or a non-object', () => {
|
|
13
|
+
expect(() => assertVariablesAreDefaults({ prod: {} })).toThrow(/unknown environment/);
|
|
14
|
+
expect(() => assertVariablesAreDefaults('x')).toThrow(/must be an object/);
|
|
15
|
+
});
|
|
16
|
+
});
|