@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/dist/commands/forge.js
CHANGED
|
@@ -75,6 +75,148 @@ export function assertVariablesAreDefaults(variables) {
|
|
|
75
75
|
walk(tree, `variables.${env}`);
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Builds the scripts of a services or tools section to outDir, one file per entry named after it.
|
|
80
|
+
* Runs in the sandbox: axios is replaced by the platform's axiosAdapter.
|
|
81
|
+
*/
|
|
82
|
+
async function buildServerScripts(path, mode, outDir, items, kind) {
|
|
83
|
+
if (!items || items.length === 0)
|
|
84
|
+
return;
|
|
85
|
+
if (!existsSync(outDir)) {
|
|
86
|
+
mkdirSync(outDir, { recursive: true });
|
|
87
|
+
}
|
|
88
|
+
const builds = items.map(async (item) => {
|
|
89
|
+
return await build({
|
|
90
|
+
root: path,
|
|
91
|
+
mode: mode ?? 'production',
|
|
92
|
+
base: '/',
|
|
93
|
+
build: {
|
|
94
|
+
outDir,
|
|
95
|
+
emptyOutDir: false,
|
|
96
|
+
target: 'esnext',
|
|
97
|
+
rollupOptions: {
|
|
98
|
+
input: item.script,
|
|
99
|
+
external: ['axios'],
|
|
100
|
+
output: {
|
|
101
|
+
format: 'esm',
|
|
102
|
+
entryFileNames: `${item.name}.js`,
|
|
103
|
+
assetFileNames: '[name].[ext]',
|
|
104
|
+
manualChunks: undefined,
|
|
105
|
+
inlineDynamicImports: true,
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
plugins: [
|
|
110
|
+
{
|
|
111
|
+
name: 'wrap-service-script',
|
|
112
|
+
generateBundle(options, bundle) {
|
|
113
|
+
for (const fileName in bundle) {
|
|
114
|
+
const chunk = bundle[fileName];
|
|
115
|
+
if (chunk.type === 'chunk' && chunk.code) {
|
|
116
|
+
let code = chunk.code;
|
|
117
|
+
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
118
|
+
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
119
|
+
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
120
|
+
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
121
|
+
}).join(''));
|
|
122
|
+
chunk.code = code;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
]
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
const results = await Promise.allSettled(builds);
|
|
131
|
+
const failed = results.flatMap((r, i) => (r.status === 'rejected' ? [{ item: items[i], reason: r.reason }] : []));
|
|
132
|
+
if (failed.length > 0) {
|
|
133
|
+
console.error(`\n❌ Failed to build ${kind.toLowerCase()}s:`);
|
|
134
|
+
failed.forEach(({ item, reason }) => {
|
|
135
|
+
console.error(`\n ${kind}: ${item.name}`);
|
|
136
|
+
console.error(` Input: ${item.script}`);
|
|
137
|
+
console.error(formatBuildError(reason));
|
|
138
|
+
});
|
|
139
|
+
throw new Error(`${kind} build failed. See errors above.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
143
|
+
const TOOLS_MAX = 50;
|
|
144
|
+
const TOOL_SCHEMA_MAX_BYTES = 16 * 1024;
|
|
145
|
+
/**
|
|
146
|
+
* Validates the `tools` section of ptkl.config.js (agent tools, separate from services).
|
|
147
|
+
* Mirrors the appservice rules so a build that passes here is not refused at upload.
|
|
148
|
+
*/
|
|
149
|
+
export function assertToolsAreValid(tools, runtimePermissions = []) {
|
|
150
|
+
if (tools === undefined || tools === null)
|
|
151
|
+
return;
|
|
152
|
+
if (!Array.isArray(tools))
|
|
153
|
+
throw new Error("tools must be an array");
|
|
154
|
+
if (tools.length > TOOLS_MAX)
|
|
155
|
+
throw new Error(`tools: at most ${TOOLS_MAX} tools per app (got ${tools.length})`);
|
|
156
|
+
const declared = new Set(Array.isArray(runtimePermissions) ? runtimePermissions.filter((p) => typeof p === "string") : []);
|
|
157
|
+
const seen = new Set();
|
|
158
|
+
tools.forEach((tool, i) => {
|
|
159
|
+
if (typeof tool !== "object" || tool === null || Array.isArray(tool)) {
|
|
160
|
+
throw new Error(`tools[${i}] must be an object`);
|
|
161
|
+
}
|
|
162
|
+
const at = `tools[${i}]`;
|
|
163
|
+
if (typeof tool.name !== "string" || !TOOL_NAME.test(tool.name)) {
|
|
164
|
+
throw new Error(`${at}.name must match ${TOOL_NAME} (lowercase letters, digits, underscores; starts with a letter; max 64)`);
|
|
165
|
+
}
|
|
166
|
+
if (seen.has(tool.name))
|
|
167
|
+
throw new Error(`${at}.name "${tool.name}" is declared twice`);
|
|
168
|
+
seen.add(tool.name);
|
|
169
|
+
const name = `tool "${tool.name}"`;
|
|
170
|
+
if (typeof tool.description !== "string" || tool.description.length < 1 || tool.description.length > 1024) {
|
|
171
|
+
throw new Error(`${name}: description is required, 1 to 1024 characters`);
|
|
172
|
+
}
|
|
173
|
+
const schema = tool.input_schema;
|
|
174
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema) || schema.type !== "object") {
|
|
175
|
+
throw new Error(`${name}: input_schema must be a JSON Schema object with type "object"`);
|
|
176
|
+
}
|
|
177
|
+
const plain = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
178
|
+
if (schema.properties !== undefined && !plain(schema.properties)) {
|
|
179
|
+
throw new Error(`${name}: input_schema.properties must be an object`);
|
|
180
|
+
}
|
|
181
|
+
if (schema.required !== undefined && (!Array.isArray(schema.required) || schema.required.some((r) => typeof r !== "string"))) {
|
|
182
|
+
throw new Error(`${name}: input_schema.required must be an array of strings`);
|
|
183
|
+
}
|
|
184
|
+
if (Buffer.byteLength(JSON.stringify(schema), "utf-8") > TOOL_SCHEMA_MAX_BYTES) {
|
|
185
|
+
throw new Error(`${name}: input_schema is larger than 16 KB`);
|
|
186
|
+
}
|
|
187
|
+
for (const flag of ["read_only", "destructive"]) {
|
|
188
|
+
if (tool[flag] !== undefined && typeof tool[flag] !== "boolean")
|
|
189
|
+
throw new Error(`${name}: ${flag} must be a boolean`);
|
|
190
|
+
}
|
|
191
|
+
if (tool.read_only === true && tool.destructive === true) {
|
|
192
|
+
throw new Error(`${name}: a tool cannot be both read_only and destructive`);
|
|
193
|
+
}
|
|
194
|
+
if (tool.permissions !== undefined) {
|
|
195
|
+
if (!Array.isArray(tool.permissions) || tool.permissions.some((p) => typeof p !== "string")) {
|
|
196
|
+
throw new Error(`${name}: permissions must be an array of strings`);
|
|
197
|
+
}
|
|
198
|
+
const extra = tool.permissions.filter((p) => !declared.has(p));
|
|
199
|
+
if (extra.length > 0) {
|
|
200
|
+
throw new Error(`${name}: permissions not in runtime_permissions: ${extra.join(", ")}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (typeof tool.script !== "string" || tool.script.trim() === "") {
|
|
204
|
+
throw new Error(`${name}: script is required`);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
/** The `manifest.tools` entries for a validated tools section. */
|
|
209
|
+
export function toolsManifest(tools) {
|
|
210
|
+
return tools.map((t) => ({
|
|
211
|
+
name: t.name,
|
|
212
|
+
description: t.description,
|
|
213
|
+
input_schema: t.input_schema,
|
|
214
|
+
read_only: t.read_only ?? false,
|
|
215
|
+
destructive: t.destructive ?? false,
|
|
216
|
+
permissions: t.permissions ?? [],
|
|
217
|
+
script: `tools/${t.name}.js`,
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
78
220
|
/**
|
|
79
221
|
* Where a built bundle keeps one of its files. Layout 2 (what `forge bundle` writes) splits the
|
|
80
222
|
* bundle into browser/ and server/; layout 1 was one flat folder and is still what an older build
|
|
@@ -339,6 +481,14 @@ class ForgeCommand {
|
|
|
339
481
|
.argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
|
|
340
482
|
const res = await sdk.platform(profile).forge().listServices(ref);
|
|
341
483
|
return res.data;
|
|
484
|
+
})))
|
|
485
|
+
.addCommand(registerCommand(new Command("tools")
|
|
486
|
+
.description("List agent tools declared by a Forge app")
|
|
487
|
+
.argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref, opts) => {
|
|
488
|
+
// No named SDK method yet: same stopgap as `domains`. --env (the shared option) picks the approved revision.
|
|
489
|
+
const client = sdk.platform(profile).forge();
|
|
490
|
+
const res = await client.client.get(`/luma/appservice/v1/forge/${ref}/tools`, { params: { env: opts.env } });
|
|
491
|
+
return res.data;
|
|
342
492
|
})))
|
|
343
493
|
.addCommand(this.registerVariables())
|
|
344
494
|
.addCommand(this.registerDomains())
|
|
@@ -439,7 +589,7 @@ class ForgeCommand {
|
|
|
439
589
|
// Change to the app directory
|
|
440
590
|
process.chdir(path);
|
|
441
591
|
const module = await import(`${path}/ptkl.config.js`);
|
|
442
|
-
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, variables, scripts, services, ssrRenderer, } = module.default ?? {};
|
|
592
|
+
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, variables, scripts, services, tools, ssrRenderer, } = module.default ?? {};
|
|
443
593
|
const iconBase64 = encodeIcon(icon, path);
|
|
444
594
|
// Clean dist folder before building to remove stale files
|
|
445
595
|
if (existsSync(distPath)) {
|
|
@@ -454,6 +604,7 @@ class ForgeCommand {
|
|
|
454
604
|
assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
|
|
455
605
|
assertRequiresIsValid(requires);
|
|
456
606
|
assertVariablesAreDefaults(variables);
|
|
607
|
+
assertToolsAreValid(tools, runtime_permissions);
|
|
457
608
|
// Normalize views: support both string entries and object entries with access/permissions
|
|
458
609
|
const normalizedViews = {};
|
|
459
610
|
if (views) {
|
|
@@ -495,6 +646,10 @@ class ForgeCommand {
|
|
|
495
646
|
...(svc.permissions && { permissions: svc.permissions }),
|
|
496
647
|
}));
|
|
497
648
|
}
|
|
649
|
+
// Tools are listed only when declared, so an app without tools keeps its manifest as before.
|
|
650
|
+
if (tools && tools.length > 0) {
|
|
651
|
+
manifest.tools = toolsManifest(tools);
|
|
652
|
+
}
|
|
498
653
|
// Different build approach for public vs platform apps
|
|
499
654
|
if (type === 'public') {
|
|
500
655
|
// Public apps: standard SPA build with index.html
|
|
@@ -728,75 +883,9 @@ class ForgeCommand {
|
|
|
728
883
|
throw new Error('Script build failed. See errors above.');
|
|
729
884
|
}
|
|
730
885
|
}
|
|
731
|
-
// Build service scripts
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
if (!existsSync(servicesDir)) {
|
|
735
|
-
mkdirSync(servicesDir, { recursive: true });
|
|
736
|
-
}
|
|
737
|
-
const buildServices = services.map(async (svc) => {
|
|
738
|
-
try {
|
|
739
|
-
const result = await build({
|
|
740
|
-
root: path,
|
|
741
|
-
mode: mode ?? 'production',
|
|
742
|
-
base: '/',
|
|
743
|
-
build: {
|
|
744
|
-
outDir: servicesDir,
|
|
745
|
-
emptyOutDir: false,
|
|
746
|
-
target: 'esnext',
|
|
747
|
-
rollupOptions: {
|
|
748
|
-
input: svc.script,
|
|
749
|
-
external: ['axios'],
|
|
750
|
-
output: {
|
|
751
|
-
format: 'esm',
|
|
752
|
-
entryFileNames: `${svc.name}.js`,
|
|
753
|
-
assetFileNames: '[name].[ext]',
|
|
754
|
-
manualChunks: undefined,
|
|
755
|
-
inlineDynamicImports: true,
|
|
756
|
-
}
|
|
757
|
-
},
|
|
758
|
-
},
|
|
759
|
-
plugins: [
|
|
760
|
-
{
|
|
761
|
-
name: 'wrap-service-script',
|
|
762
|
-
generateBundle(options, bundle) {
|
|
763
|
-
for (const fileName in bundle) {
|
|
764
|
-
const chunk = bundle[fileName];
|
|
765
|
-
if (chunk.type === 'chunk' && chunk.code) {
|
|
766
|
-
let code = chunk.code;
|
|
767
|
-
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
768
|
-
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
769
|
-
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
770
|
-
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
771
|
-
}).join(''));
|
|
772
|
-
chunk.code = code;
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
]
|
|
778
|
-
});
|
|
779
|
-
return result;
|
|
780
|
-
}
|
|
781
|
-
catch (error) {
|
|
782
|
-
throw error;
|
|
783
|
-
}
|
|
784
|
-
});
|
|
785
|
-
const serviceResults = await Promise.allSettled(buildServices);
|
|
786
|
-
const failedServices = serviceResults.filter(r => r.status === 'rejected');
|
|
787
|
-
if (failedServices.length > 0) {
|
|
788
|
-
console.error('\n❌ Failed to build services:');
|
|
789
|
-
failedServices.forEach((result, index) => {
|
|
790
|
-
const failedIndices = serviceResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
|
|
791
|
-
const svc = services[failedIndices[index]];
|
|
792
|
-
const reason = result.reason;
|
|
793
|
-
console.error(`\n Service: ${svc.name}`);
|
|
794
|
-
console.error(` Input: ${svc.script}`);
|
|
795
|
-
console.error(formatBuildError(reason));
|
|
796
|
-
});
|
|
797
|
-
throw new Error('Service build failed. See errors above.');
|
|
798
|
-
}
|
|
799
|
-
}
|
|
886
|
+
// Build service and tool scripts (same Vite config and axios wrapper)
|
|
887
|
+
await buildServerScripts(path, mode, join(serverDir, 'services'), services, 'Service');
|
|
888
|
+
await buildServerScripts(path, mode, join(serverDir, 'tools'), tools, 'Tool');
|
|
800
889
|
console.log("✅ All builds completed successfully");
|
|
801
890
|
}
|
|
802
891
|
console.log("Packaging app...");
|
package/dist/commands/kortex.js
CHANGED
|
@@ -7,9 +7,8 @@ import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
|
7
7
|
import { UIBridge } from "../lib/kortex/bridge.js";
|
|
8
8
|
import Session from "../lib/kortex/session.js";
|
|
9
9
|
import { loadKortexConfig } from "../lib/kortex/config.js";
|
|
10
|
+
import KortexPlaybookCommand from "./kortexPlaybook.js";
|
|
10
11
|
const PLATFORM_AGENT_NAMES = {
|
|
11
|
-
'protokol-bot': 'ProtokolBot',
|
|
12
|
-
'proka': 'Proka',
|
|
13
12
|
'prota': 'Prota',
|
|
14
13
|
};
|
|
15
14
|
function parseJSON(label, raw) {
|
|
@@ -44,6 +43,7 @@ class KortexCommand {
|
|
|
44
43
|
cmd.addCommand(this.registerKB());
|
|
45
44
|
cmd.addCommand(this.registerDoc());
|
|
46
45
|
cmd.addCommand(this.registerConversation());
|
|
46
|
+
cmd.addCommand(new KortexPlaybookCommand().register());
|
|
47
47
|
cmd.addCommand(registerCommand(new Command('usage')
|
|
48
48
|
.description('Get aggregated Kortex usage for the current project (admin), or a single user with --user')
|
|
49
49
|
.option('-u, --user <uuid>', 'User-access UUID to scope usage to')
|
|
@@ -240,9 +240,11 @@ class KortexCommand {
|
|
|
240
240
|
console.error(`\nRun \`ptkl profile use <name>\` or use \`ptkl --profile <name> kortex\``);
|
|
241
241
|
process.exit(1);
|
|
242
242
|
}
|
|
243
|
-
// Resolve agent: CLI flag → persisted last used →
|
|
243
|
+
// Resolve agent: CLI flag → persisted last used → Prota
|
|
244
244
|
const config = loadKortexConfig();
|
|
245
|
-
|
|
245
|
+
// A saved choice of a removed assistant becomes Prota.
|
|
246
|
+
const saved = config.lastAgentUUID === 'proka' || config.lastAgentUUID === 'protokol-bot' ? 'prota' : config.lastAgentUUID;
|
|
247
|
+
const agentUUID = opts.agent ?? saved ?? 'prota';
|
|
246
248
|
let agentName = PLATFORM_AGENT_NAMES[agentUUID] ?? 'Kortex';
|
|
247
249
|
if (!PLATFORM_AGENT_NAMES[agentUUID]) {
|
|
248
250
|
try {
|
|
@@ -250,8 +252,8 @@ class KortexCommand {
|
|
|
250
252
|
agentName = resp.data?.name ?? agentName;
|
|
251
253
|
}
|
|
252
254
|
catch {
|
|
253
|
-
// Unknown agent, fall back to
|
|
254
|
-
agentName = '
|
|
255
|
+
// Unknown agent, fall back to Prota
|
|
256
|
+
agentName = 'Prota';
|
|
255
257
|
}
|
|
256
258
|
}
|
|
257
259
|
const isLocal = !opts.cloud;
|