@ptkl/toolkit 1.1.0 → 1.3.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/dist/commands/forge.js
CHANGED
|
@@ -8,6 +8,7 @@ import axios from 'axios';
|
|
|
8
8
|
import Util from "../lib/util.js";
|
|
9
9
|
import { dirname, extname, isAbsolute, join } from 'path';
|
|
10
10
|
import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
|
|
11
|
+
import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
|
|
11
12
|
import * as sdk from "../lib/sdk.js";
|
|
12
13
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
13
14
|
function parseJSON(label, raw) {
|
|
@@ -774,6 +775,11 @@ class ForgeCommand {
|
|
|
774
775
|
},
|
|
775
776
|
plugins: [
|
|
776
777
|
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
|
|
778
|
+
kortexDevPlugin({
|
|
779
|
+
host,
|
|
780
|
+
token: Util.getCurrentProfile().token,
|
|
781
|
+
projectEnv: env ?? 'dev',
|
|
782
|
+
}),
|
|
777
783
|
{
|
|
778
784
|
// Console bridge (dev only): when the app runs EMBEDDED (e.g. the
|
|
779
785
|
// Studio's Preview iframe), forward console output + uncaught errors
|
|
@@ -3,11 +3,16 @@ import * as sdk from "../../lib/sdk.js";
|
|
|
3
3
|
import { registerCommand, withProfile } from "../../lib/scaffold.js";
|
|
4
4
|
import { integrationSub, isActive } from "../integration.js";
|
|
5
5
|
/** `ptkl integration payments` — typed interface onto the `protokol-payments` integration (RFC
|
|
6
|
-
* §4.3 / §6.1, layer 2). `ptkl integration payments refund --provider monri --
|
|
7
|
-
* is literally `new Integrations({profile}).getPayments().refund('monri',
|
|
8
|
-
* `/karadjordje/v1/payment/monri/
|
|
6
|
+
* §4.3 / §6.1, layer 2). `ptkl integration payments refund --provider monri --tx <T>`
|
|
7
|
+
* is literally `new Integrations({profile}).getPayments().refund('monri', T)` ->
|
|
8
|
+
* `/karadjordje/v1/payment/monri/refund/{T}` — reached here via `sdk.payments(profile)`
|
|
9
9
|
* (src/lib/sdk.ts), which builds the same `Payments` client against the integrations gateway.
|
|
10
10
|
*
|
|
11
|
+
* `--user`/`-u` is deprecated and ignored: the backend never accepted a userId in the URL
|
|
12
|
+
* (it resolves the caller from the request's project identity), so the SDK dropped the
|
|
13
|
+
* parameter. The flag is kept optional here purely so existing scripts passing `-u` don't
|
|
14
|
+
* break with an "unknown option" error; the value is accepted and discarded.
|
|
15
|
+
*
|
|
11
16
|
* Every subcommand pre-checks `isActive('protokol-payments')` (see ../integration.ts) so an
|
|
12
17
|
* installed-but-inactive integration fails with a friendly hint instead of a raw 403. */
|
|
13
18
|
// The SDK's `PaymentProvider` type (@ptkl/sdk/beta, types/integrations/payments.ts) currently only
|
|
@@ -91,10 +96,10 @@ class PaymentsCommand {
|
|
|
91
96
|
return registerCommand(new Command("get")
|
|
92
97
|
.description("Get a single payment transaction")
|
|
93
98
|
.addOption(providerOption())
|
|
94
|
-
.
|
|
99
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
95
100
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
96
101
|
await isActive(profile, "protokol-payments");
|
|
97
|
-
const res = await sdk.payments(profile).getTransaction(opts.provider, opts.
|
|
102
|
+
const res = await sdk.payments(profile).getTransaction(opts.provider, opts.tx);
|
|
98
103
|
return res?.data ?? res;
|
|
99
104
|
}));
|
|
100
105
|
}
|
|
@@ -102,14 +107,14 @@ class PaymentsCommand {
|
|
|
102
107
|
return registerCommand(amountOptions(new Command("link")
|
|
103
108
|
.description("Create a payment link")
|
|
104
109
|
.addOption(providerOption())
|
|
105
|
-
.
|
|
110
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
106
111
|
.requiredOption("-d, --description <description>", "Payment description")
|
|
107
112
|
.option("--token <token>", "Pre-existing tokenized card to charge, if any")
|
|
108
113
|
.option("--is-token-request", "Request tokenization of the card during payment")
|
|
109
114
|
.option("--redirect-url <url>", "URL to redirect to after payment")
|
|
110
115
|
.option("--lang <lang>", "Payment page language: en | es | ba | hr"))).action(withProfile(async (profile, opts) => {
|
|
111
116
|
await isActive(profile, "protokol-payments");
|
|
112
|
-
const res = await sdk.payments(profile).getPaymentLink(opts.provider,
|
|
117
|
+
const res = await sdk.payments(profile).getPaymentLink(opts.provider, {
|
|
113
118
|
...parseAmount(opts),
|
|
114
119
|
description: opts.description,
|
|
115
120
|
...(opts.token ? { token: opts.token } : {}),
|
|
@@ -124,12 +129,12 @@ class PaymentsCommand {
|
|
|
124
129
|
return registerCommand(new Command("token-request")
|
|
125
130
|
.description("Create a token-request link (tokenize a card without charging it)")
|
|
126
131
|
.addOption(providerOption())
|
|
127
|
-
.
|
|
132
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
128
133
|
.requiredOption("-d, --description <description>", "Description shown on the payment page")
|
|
129
134
|
.option("--redirect-url <url>", "URL to redirect to after tokenization")
|
|
130
135
|
.option("--lang <lang>", "Payment page language: en | es | ba | hr")).action(withProfile(async (profile, opts) => {
|
|
131
136
|
await isActive(profile, "protokol-payments");
|
|
132
|
-
const res = await sdk.payments(profile).getTokenRequestLink(opts.provider,
|
|
137
|
+
const res = await sdk.payments(profile).getTokenRequestLink(opts.provider, {
|
|
133
138
|
description: opts.description,
|
|
134
139
|
...(opts.redirectUrl ? { redirectUrl: opts.redirectUrl } : {}),
|
|
135
140
|
...(opts.lang ? { lang: opts.lang } : {}),
|
|
@@ -141,11 +146,11 @@ class PaymentsCommand {
|
|
|
141
146
|
return registerCommand(amountOptions(new Command("direct-pay")
|
|
142
147
|
.description("Charge a previously tokenized card directly (no redirect)")
|
|
143
148
|
.addOption(providerOption())
|
|
144
|
-
.
|
|
149
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
145
150
|
.requiredOption("--token <token>", "Tokenized card to charge")
|
|
146
151
|
.requiredOption("-d, --description <description>", "Payment description"))).action(withProfile(async (profile, opts) => {
|
|
147
152
|
await isActive(profile, "protokol-payments");
|
|
148
|
-
const res = await sdk.payments(profile).directPayUsingToken(opts.provider,
|
|
153
|
+
const res = await sdk.payments(profile).directPayUsingToken(opts.provider, {
|
|
149
154
|
...parseAmount(opts),
|
|
150
155
|
token: opts.token,
|
|
151
156
|
description: opts.description,
|
|
@@ -157,10 +162,10 @@ class PaymentsCommand {
|
|
|
157
162
|
return registerCommand(new Command("refund")
|
|
158
163
|
.description("Refund a payment transaction")
|
|
159
164
|
.addOption(providerOption())
|
|
160
|
-
.
|
|
165
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
161
166
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
162
167
|
await isActive(profile, "protokol-payments");
|
|
163
|
-
const res = await sdk.payments(profile).refund(opts.provider, opts.
|
|
168
|
+
const res = await sdk.payments(profile).refund(opts.provider, opts.tx);
|
|
164
169
|
return res?.data ?? res;
|
|
165
170
|
}));
|
|
166
171
|
}
|
|
@@ -168,10 +173,10 @@ class PaymentsCommand {
|
|
|
168
173
|
return registerCommand(new Command("void")
|
|
169
174
|
.description("Void a payment transaction")
|
|
170
175
|
.addOption(providerOption())
|
|
171
|
-
.
|
|
176
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
172
177
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
173
178
|
await isActive(profile, "protokol-payments");
|
|
174
|
-
const res = await sdk.payments(profile).voidTransaction(opts.provider, opts.
|
|
179
|
+
const res = await sdk.payments(profile).voidTransaction(opts.provider, opts.tx);
|
|
175
180
|
return res?.data ?? res;
|
|
176
181
|
}));
|
|
177
182
|
}
|
|
@@ -179,10 +184,10 @@ class PaymentsCommand {
|
|
|
179
184
|
return registerCommand(new Command("cancel")
|
|
180
185
|
.description("Cancel (deactivate) a payment link")
|
|
181
186
|
.addOption(providerOption())
|
|
182
|
-
.
|
|
187
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
183
188
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
184
189
|
await isActive(profile, "protokol-payments");
|
|
185
|
-
const res = await sdk.payments(profile).deactivatePaymentLink(opts.provider, opts.
|
|
190
|
+
const res = await sdk.payments(profile).deactivatePaymentLink(opts.provider, opts.tx);
|
|
186
191
|
return res?.data ?? res;
|
|
187
192
|
}));
|
|
188
193
|
}
|
|
@@ -0,0 +1,894 @@
|
|
|
1
|
+
export function kortexDevPlugin(options = {}) {
|
|
2
|
+
const cfg = JSON.stringify({
|
|
3
|
+
host: options.host || '',
|
|
4
|
+
token: options.token || '',
|
|
5
|
+
projectEnv: options.projectEnv || 'dev',
|
|
6
|
+
});
|
|
7
|
+
// ── Polyfill script (runs BEFORE the app) ──────────────────────────
|
|
8
|
+
const polyfillScript = `(function(){
|
|
9
|
+
var __KTX_CFG = ${cfg};
|
|
10
|
+
if (window.kortex) return; // already provided (e.g. by the real platform runtime)
|
|
11
|
+
|
|
12
|
+
var _tools = [];
|
|
13
|
+
var _context = null;
|
|
14
|
+
var _helperActive = false;
|
|
15
|
+
var _listeners = [];
|
|
16
|
+
|
|
17
|
+
function notify(eventName) {
|
|
18
|
+
for (var i = 0; i < _listeners.length; i++) _listeners[i]();
|
|
19
|
+
// Production dispatches these; apps listening for them must work in dev too.
|
|
20
|
+
try {
|
|
21
|
+
window.dispatchEvent(new CustomEvent(eventName || 'kortex:capabilities-changed'));
|
|
22
|
+
} catch (e) { /* older browsers */ }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
var _trace = [];
|
|
26
|
+
|
|
27
|
+
// ── Parity helpers ────────────────────────────────────────────────
|
|
28
|
+
//
|
|
29
|
+
// These mirror platform-forge/src/kortex/{toolPolicy,kortexTools,kortexRun}.ts.
|
|
30
|
+
// They are duplicated, not shared, because platform-forge is not a published
|
|
31
|
+
// package — so they MUST be updated together. A dev tool that reports
|
|
32
|
+
// different approval behaviour than production is worse than no dev tool.
|
|
33
|
+
|
|
34
|
+
var __KTX_POLICY_TABLE = {
|
|
35
|
+
get_current_page: { category: 'read', risk: 'low', requiresConfirmation: false, fullAccessAuto: true },
|
|
36
|
+
get_project_context: { category: 'read', risk: 'low', requiresConfirmation: false, fullAccessAuto: true }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function __ktxInferPolicy(name) {
|
|
40
|
+
if (/^(get_|list_|find_|search_|format_)/.test(name) || /(_info|_status)$/.test(name)) {
|
|
41
|
+
return { category: 'read', risk: 'low', requiresConfirmation: false, fullAccessAuto: true };
|
|
42
|
+
}
|
|
43
|
+
if (/^(delete_|remove_|clear_|archive_)/.test(name)) {
|
|
44
|
+
return { category: 'destructive', risk: 'high', requiresConfirmation: true, fullAccessAuto: false };
|
|
45
|
+
}
|
|
46
|
+
if (/^(run_|test_|execute_)/.test(name)) {
|
|
47
|
+
return { category: 'execute', risk: 'high', requiresConfirmation: true, fullAccessAuto: false };
|
|
48
|
+
}
|
|
49
|
+
if (/^(create_|publish_|top_up_)/.test(name) || /payment/.test(name)) {
|
|
50
|
+
return { category: 'high_risk', risk: 'high', requiresConfirmation: true, fullAccessAuto: false };
|
|
51
|
+
}
|
|
52
|
+
if (/^(save_|refresh_|add_|connect_)/.test(name)) {
|
|
53
|
+
return { category: 'persist', risk: 'medium', requiresConfirmation: true, fullAccessAuto: false };
|
|
54
|
+
}
|
|
55
|
+
return { category: 'write', risk: 'medium', requiresConfirmation: true, fullAccessAuto: false };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function __ktxPolicyFromSchema(schema) {
|
|
59
|
+
if (!schema) return null;
|
|
60
|
+
var fn = schema.function || {};
|
|
61
|
+
return schema.kortex || schema.x_kortex || schema['x-kortex'] ||
|
|
62
|
+
fn.kortex || fn.x_kortex || fn['x-kortex'] || null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function __ktxResolvePolicy(name, schema, explicit) {
|
|
66
|
+
var base = __KTX_POLICY_TABLE[name] || __ktxInferPolicy(name || '');
|
|
67
|
+
var fromSchema = __ktxPolicyFromSchema(schema) || {};
|
|
68
|
+
var merged = { name: name, label: name };
|
|
69
|
+
for (var k in base) merged[k] = base[k];
|
|
70
|
+
for (var k2 in fromSchema) merged[k2] = fromSchema[k2];
|
|
71
|
+
if (explicit) for (var k3 in explicit) merged[k3] = explicit[k3];
|
|
72
|
+
return merged;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Production strips policy hints before the schema reaches the model.
|
|
76
|
+
function __ktxCleanSchema(schema) {
|
|
77
|
+
if (!schema) return schema;
|
|
78
|
+
var clean = {};
|
|
79
|
+
for (var k in schema) if (k !== 'kortex' && k !== 'x_kortex' && k !== 'x-kortex') clean[k] = schema[k];
|
|
80
|
+
if (clean.function && typeof clean.function === 'object') {
|
|
81
|
+
var fn = {};
|
|
82
|
+
for (var f in clean.function) if (f !== 'kortex' && f !== 'x_kortex' && f !== 'x-kortex') fn[f] = clean.function[f];
|
|
83
|
+
clean.function = fn;
|
|
84
|
+
}
|
|
85
|
+
return clean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function __ktxShouldAutoExecute(policy) {
|
|
89
|
+
if (!policy) return false;
|
|
90
|
+
return policy.requiresConfirmation === false;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ── Minimal schema validation (mirrors schemaValidate.ts) ─────────
|
|
94
|
+
function __ktxValidate(value, schema, path, errors) {
|
|
95
|
+
if (!schema || typeof schema !== 'object') return;
|
|
96
|
+
var t = schema.type;
|
|
97
|
+
var actual = value === null ? 'null' : (Array.isArray(value) ? 'array' : typeof value);
|
|
98
|
+
if (typeof t === 'string') {
|
|
99
|
+
var ok = t === 'integer'
|
|
100
|
+
? (typeof value === 'number' && value % 1 === 0)
|
|
101
|
+
: (t === 'number' ? typeof value === 'number' : actual === t);
|
|
102
|
+
if (!ok) { errors.push((path || '(root)') + ': expected ' + t + ', got ' + actual); return; }
|
|
103
|
+
}
|
|
104
|
+
if (Array.isArray(schema.enum) && schema.enum.indexOf(value) === -1) {
|
|
105
|
+
errors.push((path || '(root)') + ': must be one of ' + JSON.stringify(schema.enum));
|
|
106
|
+
}
|
|
107
|
+
if (typeof value === 'number') {
|
|
108
|
+
if (typeof schema.minimum === 'number' && value < schema.minimum) errors.push(path + ': must be >= ' + schema.minimum);
|
|
109
|
+
if (typeof schema.maximum === 'number' && value > schema.maximum) errors.push(path + ': must be <= ' + schema.maximum);
|
|
110
|
+
}
|
|
111
|
+
if (Array.isArray(value) && schema.items) {
|
|
112
|
+
for (var i = 0; i < value.length; i++) __ktxValidate(value[i], schema.items, path + '[' + i + ']', errors);
|
|
113
|
+
}
|
|
114
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
115
|
+
if (Array.isArray(schema.required)) {
|
|
116
|
+
for (var r = 0; r < schema.required.length; r++) {
|
|
117
|
+
if (!(schema.required[r] in value)) errors.push((path ? path + '.' : '') + schema.required[r] + ': is required but missing');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (schema.properties) {
|
|
121
|
+
for (var key in schema.properties) {
|
|
122
|
+
if (key in value) __ktxValidate(value[key], schema.properties[key], (path ? path + '.' : '') + key, errors);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function __ktxExtractJSON(text) {
|
|
129
|
+
var trimmed = String(text || '').trim();
|
|
130
|
+
var fence = trimmed.match(/\`\`\`(?:json)?\\s*([\\s\\S]*?)\`\`\`/);
|
|
131
|
+
var candidate = fence ? fence[1].trim() : trimmed;
|
|
132
|
+
try { return JSON.parse(candidate); } catch (e) {}
|
|
133
|
+
var start = candidate.search(/[\\[{]/);
|
|
134
|
+
var end = Math.max(candidate.lastIndexOf('}'), candidate.lastIndexOf(']'));
|
|
135
|
+
if (start >= 0 && end > start) {
|
|
136
|
+
try { return JSON.parse(candidate.slice(start, end + 1)); } catch (e2) {}
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function __ktxErr(code, message) {
|
|
142
|
+
var e = new Error(message);
|
|
143
|
+
e.name = 'KortexRunError';
|
|
144
|
+
e.code = code;
|
|
145
|
+
return e;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function __ktxTrace(entry) {
|
|
149
|
+
entry.at = new Date().toISOString();
|
|
150
|
+
_trace.unshift(entry);
|
|
151
|
+
if (_trace.length > 50) _trace.pop();
|
|
152
|
+
notify('kortex:dev-trace');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
var __KTX_RESERVED = ['bash', 'read_file'];
|
|
156
|
+
var __KTX_MAX_ROUNDS = 5;
|
|
157
|
+
|
|
158
|
+
function __ktxRun(request) {
|
|
159
|
+
if (!request || !request.agent) return Promise.reject(__ktxErr('agent_not_found', 'run() requires an agent uuid'));
|
|
160
|
+
if (!request.instructions) return Promise.reject(__ktxErr('upstream', 'run() requires instructions'));
|
|
161
|
+
if (!__KTX_CFG.token || !__KTX_CFG.host) {
|
|
162
|
+
return Promise.reject(__ktxErr('no_access', 'ptkl forge dev has no Kortex session. Run \`ptkl login\` and restart the dev server.'));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
var selected = [];
|
|
166
|
+
if (request.tools) {
|
|
167
|
+
var all = _tools.filter(function (t) {
|
|
168
|
+
var n = t.schema && t.schema.function && t.schema.function.name;
|
|
169
|
+
return n !== 'get_current_page' && n !== 'get_project_context';
|
|
170
|
+
});
|
|
171
|
+
selected = request.tools === true ? all : all.filter(function (t) {
|
|
172
|
+
return request.tools.indexOf(t.schema.function.name) !== -1;
|
|
173
|
+
});
|
|
174
|
+
for (var i = 0; i < selected.length; i++) {
|
|
175
|
+
if (__KTX_RESERVED.indexOf(selected[i].schema.function.name) !== -1) {
|
|
176
|
+
return Promise.reject(__ktxErr('upstream',
|
|
177
|
+
'Tool "' + selected[i].schema.function.name + '" is reserved — it switches Kortex into CLI mode. Rename it.'));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
var instructions = request.instructions;
|
|
183
|
+
if (request.schema) {
|
|
184
|
+
instructions += '\\n\\nRespond with a single JSON object matching this JSON Schema exactly. ' +
|
|
185
|
+
'Output only the JSON — no prose, no markdown, no code fences.\\n\\n' +
|
|
186
|
+
JSON.stringify(request.schema, null, 2);
|
|
187
|
+
}
|
|
188
|
+
var inputText = request.input === undefined ? '' : JSON.stringify(request.input, null, 2);
|
|
189
|
+
var messages = inputText
|
|
190
|
+
? [{ role: 'context', content: instructions }, { role: 'user', content: inputText }]
|
|
191
|
+
: [{ role: 'user', content: instructions }];
|
|
192
|
+
|
|
193
|
+
var toolCalls = [];
|
|
194
|
+
var usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
|
|
195
|
+
var rounds = 0;
|
|
196
|
+
var repaired = false;
|
|
197
|
+
var traceSteps = [];
|
|
198
|
+
|
|
199
|
+
function post() {
|
|
200
|
+
var body = { agent_uuid: request.agent, messages: messages };
|
|
201
|
+
if (selected.length) body.tools = selected.map(function (t) { return t.schema; });
|
|
202
|
+
|
|
203
|
+
return fetch(__KTX_CFG.host + '/luma/kortex/v1/chat', {
|
|
204
|
+
method: 'POST',
|
|
205
|
+
headers: {
|
|
206
|
+
'Content-Type': 'application/json',
|
|
207
|
+
'Accept': 'text/event-stream',
|
|
208
|
+
'Authorization': 'Bearer ' + __KTX_CFG.token,
|
|
209
|
+
'X-Project-Env': __KTX_CFG.projectEnv
|
|
210
|
+
},
|
|
211
|
+
body: JSON.stringify(body),
|
|
212
|
+
signal: request.signal
|
|
213
|
+
}).then(function (res) {
|
|
214
|
+
if (!res.ok) {
|
|
215
|
+
return res.text().then(function (t) {
|
|
216
|
+
var msg = t;
|
|
217
|
+
try { var j = JSON.parse(t); msg = j.error || j.message || t; } catch (e) {}
|
|
218
|
+
var code = res.status === 403 ? 'no_access'
|
|
219
|
+
: res.status === 404 ? 'agent_not_found'
|
|
220
|
+
: (res.status === 429 || res.status === 402) ? 'quota_exceeded' : 'upstream';
|
|
221
|
+
throw __ktxErr(code, msg || ('Request failed with status ' + res.status));
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return res.text();
|
|
225
|
+
}).then(function (raw) {
|
|
226
|
+
var text = '', calls = [];
|
|
227
|
+
raw.split('\\n').forEach(function (line) {
|
|
228
|
+
if (line.indexOf('data: ') !== 0) return;
|
|
229
|
+
var payload = line.slice(6);
|
|
230
|
+
if (payload === '[DONE]') return;
|
|
231
|
+
try {
|
|
232
|
+
var d = JSON.parse(payload);
|
|
233
|
+
if (typeof d.delta === 'string') text += d.delta;
|
|
234
|
+
if (typeof d.content === 'string' && d.content) text = d.content;
|
|
235
|
+
if (Array.isArray(d.tool_calls)) calls = d.tool_calls;
|
|
236
|
+
if (d.token_usage) {
|
|
237
|
+
usage.prompt_tokens = d.token_usage.prompt_tokens || usage.prompt_tokens;
|
|
238
|
+
usage.completion_tokens = d.token_usage.completion_tokens || usage.completion_tokens;
|
|
239
|
+
usage.total_tokens = d.token_usage.total_tokens || usage.total_tokens;
|
|
240
|
+
}
|
|
241
|
+
} catch (e) {}
|
|
242
|
+
});
|
|
243
|
+
return { text: text, calls: calls };
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function loop() {
|
|
248
|
+
return post().then(function (turn) {
|
|
249
|
+
if (turn.calls.length) {
|
|
250
|
+
rounds++;
|
|
251
|
+
if (rounds > __KTX_MAX_ROUNDS) throw __ktxErr('upstream', 'Exceeded ' + __KTX_MAX_ROUNDS + ' tool rounds.');
|
|
252
|
+
messages.push({ role: 'assistant', content: turn.text, tool_calls: turn.calls });
|
|
253
|
+
|
|
254
|
+
return turn.calls.reduce(function (chain, tc) {
|
|
255
|
+
return chain.then(function () {
|
|
256
|
+
var name = tc.function && tc.function.name;
|
|
257
|
+
var args = {};
|
|
258
|
+
try { args = JSON.parse((tc.function && tc.function.arguments) || '{}'); } catch (e) {}
|
|
259
|
+
var entry = _tools.filter(function (t) { return t.schema.function.name === name; })[0];
|
|
260
|
+
if (!entry) {
|
|
261
|
+
messages.push({ role: 'tool', content: JSON.stringify({ error: 'Unknown tool: ' + name }), tool_call_id: tc.id });
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (!__ktxShouldAutoExecute(entry.policy)) {
|
|
265
|
+
console.warn('[kortex dev] "' + name + '" requires confirmation in production (' +
|
|
266
|
+
entry.policy.category + '/' + entry.policy.risk + '). Auto-running in dev — verify approval behaviour in platform-forge.');
|
|
267
|
+
}
|
|
268
|
+
return Promise.resolve(entry.execute(args)).then(function (result) {
|
|
269
|
+
toolCalls.push({ name: name, arguments: args, result: result });
|
|
270
|
+
traceSteps.push({ tool: name, arguments: args, result: result, policy: entry.policy });
|
|
271
|
+
messages.push({ role: 'tool', content: JSON.stringify(result === undefined ? null : result), tool_call_id: tc.id });
|
|
272
|
+
}, function (err) {
|
|
273
|
+
var e = { error: String((err && err.message) || err) };
|
|
274
|
+
toolCalls.push({ name: name, arguments: args, result: e });
|
|
275
|
+
traceSteps.push({ tool: name, arguments: args, result: e, policy: entry.policy });
|
|
276
|
+
messages.push({ role: 'tool', content: JSON.stringify(e), tool_call_id: tc.id });
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}, Promise.resolve()).then(loop);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (!request.schema) {
|
|
283
|
+
return { data: null, text: turn.text, usage: usage, toolCalls: toolCalls };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
var parsed = __ktxExtractJSON(turn.text);
|
|
287
|
+
var errors = [];
|
|
288
|
+
if (parsed === undefined) errors.push('response was not valid JSON');
|
|
289
|
+
else __ktxValidate(parsed, request.schema, '', errors);
|
|
290
|
+
|
|
291
|
+
if (!errors.length) return { data: parsed, text: turn.text, usage: usage, toolCalls: toolCalls };
|
|
292
|
+
if (repaired) {
|
|
293
|
+
var e = __ktxErr('schema_invalid', 'Model output did not match the schema after one repair attempt.');
|
|
294
|
+
e.details = errors.join('\\n');
|
|
295
|
+
throw e;
|
|
296
|
+
}
|
|
297
|
+
repaired = true;
|
|
298
|
+
messages.push({ role: 'assistant', content: turn.text });
|
|
299
|
+
messages.push({ role: 'user', content: 'That response did not satisfy the schema:\\n' + errors.join('\\n') +
|
|
300
|
+
'\\n\\nReturn corrected JSON only — no prose, no code fences.' });
|
|
301
|
+
return loop();
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return loop().then(function (result) {
|
|
306
|
+
__ktxTrace({ name: request.name, request: request, steps: traceSteps, result: result });
|
|
307
|
+
return result;
|
|
308
|
+
}, function (err) {
|
|
309
|
+
__ktxTrace({ name: request.name, request: request, steps: traceSteps, error: { code: err.code, message: err.message, details: err.details } });
|
|
310
|
+
throw err;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
window.kortex = {
|
|
315
|
+
// Must track platform-forge's KORTEX_BRIDGE_VERSION. v2 adds run().
|
|
316
|
+
version: 2,
|
|
317
|
+
capabilities: ['tools', 'context', 'helper', 'run'],
|
|
318
|
+
|
|
319
|
+
get tools() { return _tools; },
|
|
320
|
+
|
|
321
|
+
_context: null,
|
|
322
|
+
_helperActive: false,
|
|
323
|
+
|
|
324
|
+
_trace: _trace,
|
|
325
|
+
|
|
326
|
+
run: function (request) { return __ktxRun(request); },
|
|
327
|
+
|
|
328
|
+
registerTool: function (schema, executeFn, policy) {
|
|
329
|
+
// Remove any existing tool with the same name
|
|
330
|
+
var name = schema && schema.function && schema.function.name;
|
|
331
|
+
if (name) {
|
|
332
|
+
for (var i = _tools.length - 1; i >= 0; i--) {
|
|
333
|
+
if (_tools[i].schema.function.name === name) _tools.splice(i, 1);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
_tools.push({
|
|
337
|
+
schema: __ktxCleanSchema(schema),
|
|
338
|
+
execute: executeFn,
|
|
339
|
+
policy: __ktxResolvePolicy(name, schema, policy)
|
|
340
|
+
});
|
|
341
|
+
_context = window.kortex._context;
|
|
342
|
+
_helperActive = window.kortex._helperActive;
|
|
343
|
+
notify();
|
|
344
|
+
console.log('[kortex dev] tool registered:', (name || '(unnamed)'),
|
|
345
|
+
'(total:', _tools.length + ')');
|
|
346
|
+
},
|
|
347
|
+
|
|
348
|
+
unregisterTool: function (name) {
|
|
349
|
+
for (var i = _tools.length - 1; i >= 0; i--) {
|
|
350
|
+
if (_tools[i].schema.function.name === name) {
|
|
351
|
+
_tools.splice(i, 1);
|
|
352
|
+
notify();
|
|
353
|
+
console.log('[kortex dev] tool unregistered:', name,
|
|
354
|
+
'(total:', _tools.length + ')');
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
},
|
|
359
|
+
|
|
360
|
+
registerContext: function (label, description, icon) {
|
|
361
|
+
window.kortex._context = { label: label, description: description || '', icon: icon || null };
|
|
362
|
+
_context = window.kortex._context;
|
|
363
|
+
notify();
|
|
364
|
+
},
|
|
365
|
+
|
|
366
|
+
unregisterContext: function () {
|
|
367
|
+
window.kortex._context = null;
|
|
368
|
+
_context = null;
|
|
369
|
+
notify();
|
|
370
|
+
},
|
|
371
|
+
|
|
372
|
+
showHelper: function () {
|
|
373
|
+
window.kortex._helperActive = true;
|
|
374
|
+
_helperActive = true;
|
|
375
|
+
notify('kortex:helper-changed');
|
|
376
|
+
},
|
|
377
|
+
|
|
378
|
+
hideHelper: function () {
|
|
379
|
+
window.kortex._helperActive = false;
|
|
380
|
+
_helperActive = false;
|
|
381
|
+
notify('kortex:helper-changed');
|
|
382
|
+
},
|
|
383
|
+
|
|
384
|
+
// Internal: subscribe to changes (used by the devtools panel)
|
|
385
|
+
_subscribe: function (fn) {
|
|
386
|
+
_listeners.push(fn);
|
|
387
|
+
return function () {
|
|
388
|
+
var idx = _listeners.indexOf(fn);
|
|
389
|
+
if (idx >= 0) _listeners.splice(idx, 1);
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
// Keep _context and _helperActive getters in sync
|
|
395
|
+
Object.defineProperty(window.kortex, '_context', {
|
|
396
|
+
get: function () { return _context; },
|
|
397
|
+
set: function (v) { _context = v; },
|
|
398
|
+
enumerable: true, configurable: true
|
|
399
|
+
});
|
|
400
|
+
Object.defineProperty(window.kortex, '_helperActive', {
|
|
401
|
+
get: function () { return _helperActive; },
|
|
402
|
+
set: function (v) { _helperActive = v; },
|
|
403
|
+
enumerable: true, configurable: true
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
console.log('[ptkl forge dev] kortex polyfill ready');
|
|
407
|
+
})();`;
|
|
408
|
+
// ── DevTools panel script (runs AFTER the polyfill) ────────────────
|
|
409
|
+
const devtoolsScript = `(function(){
|
|
410
|
+
if (window.__KORTEX_DEVTOOLS_LOADED) return;
|
|
411
|
+
window.__KORTEX_DEVTOOLS_LOADED = true;
|
|
412
|
+
|
|
413
|
+
// Wait for kortex polyfill
|
|
414
|
+
function waitForKortex(cb) {
|
|
415
|
+
if (window.kortex) { cb(); return; }
|
|
416
|
+
var tries = 0;
|
|
417
|
+
var iv = setInterval(function () {
|
|
418
|
+
if (window.kortex || ++tries > 50) { clearInterval(iv); if (window.kortex) cb(); }
|
|
419
|
+
}, 100);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
waitForKortex(function () {
|
|
423
|
+
|
|
424
|
+
// ── Styles ──────────────────────────────────────────────
|
|
425
|
+
var style = document.createElement('style');
|
|
426
|
+
style.textContent = [
|
|
427
|
+
'@keyframes ktx-slide-up { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }',
|
|
428
|
+
'@keyframes ktx-fade-in { from { opacity: 0; } to { opacity: 1; } }',
|
|
429
|
+
'@keyframes ktx-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.12); } }',
|
|
430
|
+
'.ktx-btn {',
|
|
431
|
+
' position: fixed; bottom: 16px; right: 16px; z-index: 99990;',
|
|
432
|
+
' display: flex; align-items: center; gap: 6px;',
|
|
433
|
+
' padding: 8px 14px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.12);',
|
|
434
|
+
' background: #1e1e2e; color: #cdd6f4; cursor: pointer;',
|
|
435
|
+
' font-family: system-ui, -apple-system, sans-serif; font-size: 13px; font-weight: 500;',
|
|
436
|
+
' box-shadow: 0 4px 24px rgba(0,0,0,0.4); transition: box-shadow 0.2s, background 0.2s;',
|
|
437
|
+
' user-select: none;',
|
|
438
|
+
'}',
|
|
439
|
+
'.ktx-btn:hover { background: #313244; box-shadow: 0 6px 32px rgba(0,0,0,0.5); }',
|
|
440
|
+
'.ktx-badge {',
|
|
441
|
+
' display: inline-flex; align-items: center; justify-content: center;',
|
|
442
|
+
' min-width: 20px; height: 20px; border-radius: 10px;',
|
|
443
|
+
' background: #cba6f7; color: #1e1e2e; font-size: 11px; font-weight: 700;',
|
|
444
|
+
' padding: 0 6px;',
|
|
445
|
+
'}',
|
|
446
|
+
'.ktx-badge:empty { display: none; }',
|
|
447
|
+
'.ktx-panel {',
|
|
448
|
+
' position: fixed; bottom: 60px; right: 16px; z-index: 99989;',
|
|
449
|
+
' width: 520px; max-height: 480px;',
|
|
450
|
+
' border-radius: 12px; border: 1px solid rgba(255,255,255,0.1);',
|
|
451
|
+
' background: #1e1e2e; color: #cdd6f4;',
|
|
452
|
+
' box-shadow: 0 8px 40px rgba(0,0,0,0.5);',
|
|
453
|
+
' font-family: system-ui, -apple-system, sans-serif; font-size: 13px;',
|
|
454
|
+
' display: none; flex-direction: column; overflow: hidden;',
|
|
455
|
+
' animation: ktx-slide-up 0.2s ease-out;',
|
|
456
|
+
'}',
|
|
457
|
+
'.ktx-panel.open { display: flex; }',
|
|
458
|
+
'.ktx-panel-header {',
|
|
459
|
+
' display: flex; align-items: center; justify-content: space-between;',
|
|
460
|
+
' padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.08);',
|
|
461
|
+
' background: #181825; flex-shrink: 0;',
|
|
462
|
+
'}',
|
|
463
|
+
'.ktx-panel-title { font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; }',
|
|
464
|
+
'.ktx-tabs { display: flex; gap: 2px; }',
|
|
465
|
+
'.ktx-tab {',
|
|
466
|
+
' padding: 5px 12px; border-radius: 6px; border: none; cursor: pointer;',
|
|
467
|
+
' background: transparent; color: #a6adc8; font-size: 12px; font-family: inherit;',
|
|
468
|
+
' transition: background 0.15s, color 0.15s;',
|
|
469
|
+
'}',
|
|
470
|
+
'.ktx-tab:hover { background: #313244; color: #cdd6f4; }',
|
|
471
|
+
'.ktx-tab.active { background: #45475a; color: #cdd6f4; }',
|
|
472
|
+
'.ktx-panel-body {',
|
|
473
|
+
' flex: 1; overflow-y: auto; padding: 8px 14px;',
|
|
474
|
+
' scrollbar-width: thin; scrollbar-color: #45475a transparent;',
|
|
475
|
+
'}',
|
|
476
|
+
'.ktx-panel-body::-webkit-scrollbar { width: 6px; }',
|
|
477
|
+
'.ktx-panel-body::-webkit-scrollbar-thumb { background: #45475a; border-radius: 3px; }',
|
|
478
|
+
'.ktx-run-box { padding: 10px; border-bottom: 1px solid rgba(255,255,255,0.08); display: flex; flex-direction: column; gap: 6px; }',
|
|
479
|
+
'.ktx-run-input { width: 100%; box-sizing: border-box; background: rgba(255,255,255,0.06); color: inherit; border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; padding: 6px 8px; font: inherit; font-size: 12px; }',
|
|
480
|
+
'.ktx-run-check { font-size: 11px; opacity: 0.75; display: flex; align-items: center; gap: 6px; }',
|
|
481
|
+
'.ktx-run-go { align-self: flex-start; cursor: pointer; border: 0; border-radius: 6px; padding: 5px 12px; font-size: 12px; background: #4f7cff; color: #fff; }',
|
|
482
|
+
'.ktx-run-status { font-size: 11px; color: #ff8888; min-height: 14px; }',
|
|
483
|
+
'.ktx-step { font-size: 11px; margin-top: 6px; padding-left: 8px; border-left: 2px solid rgba(255,255,255,0.12); }',
|
|
484
|
+
'.ktx-step pre { margin: 4px 0 0; white-space: pre-wrap; word-break: break-word; font-size: 10px; opacity: 0.85; }',
|
|
485
|
+
'.ktx-err { border-left-color: #ff5c5c; color: #ff9c9c; }',
|
|
486
|
+
'.ktx-empty {',
|
|
487
|
+
' text-align: center; padding: 32px 16px; color: #585b70;',
|
|
488
|
+
'}',
|
|
489
|
+
'.ktx-tool-card {',
|
|
490
|
+
' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
|
|
491
|
+
' margin-bottom: 8px; background: #181825; overflow: hidden;',
|
|
492
|
+
'}',
|
|
493
|
+
'.ktx-tool-card-header {',
|
|
494
|
+
' display: flex; align-items: center; justify-content: space-between;',
|
|
495
|
+
' padding: 8px 12px; cursor: pointer; user-select: none;',
|
|
496
|
+
' transition: background 0.15s;',
|
|
497
|
+
'}',
|
|
498
|
+
'.ktx-tool-card-header:hover { background: #313244; }',
|
|
499
|
+
'.ktx-tool-name { font-weight: 600; font-size: 13px; color: #cba6f7; }',
|
|
500
|
+
'.ktx-tool-desc { font-size: 12px; color: #a6adc8; margin-top: 2px; }',
|
|
501
|
+
'.ktx-tool-meta { display: flex; gap: 6px; align-items: center; flex-shrink: 0; }',
|
|
502
|
+
'.ktx-tag {',
|
|
503
|
+
' display: inline-block; padding: 2px 7px; border-radius: 4px;',
|
|
504
|
+
' font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;',
|
|
505
|
+
'}',
|
|
506
|
+
'.ktx-tag-risk-low { background: rgba(166,227,161,0.15); color: #a6e3a1; }',
|
|
507
|
+
'.ktx-tag-risk-medium { background: rgba(249,226,175,0.15); color: #f9e2af; }',
|
|
508
|
+
'.ktx-tag-risk-high { background: rgba(243,139,168,0.15); color: #f38ba8; }',
|
|
509
|
+
'.ktx-tag-confirm { background: rgba(203,166,247,0.15); color: #cba6f7; }',
|
|
510
|
+
'.ktx-tool-card-body {',
|
|
511
|
+
' display: none; padding: 10px 12px; border-top: 1px solid rgba(255,255,255,0.06);',
|
|
512
|
+
' background: #11111b;',
|
|
513
|
+
'}',
|
|
514
|
+
'.ktx-tool-card.expanded .ktx-tool-card-body { display: block; }',
|
|
515
|
+
'.ktx-params {',
|
|
516
|
+
' font-family: "SF Mono", "Cascadia Code", "Fira Code", monospace;',
|
|
517
|
+
' font-size: 11px; background: #181825; padding: 10px; border-radius: 6px;',
|
|
518
|
+
' overflow-x: auto; white-space: pre; color: #a6adc8;',
|
|
519
|
+
' max-height: 160px; overflow-y: auto;',
|
|
520
|
+
'}',
|
|
521
|
+
'.ktx-section-label {',
|
|
522
|
+
' font-size: 11px; font-weight: 600; color: #585b70;',
|
|
523
|
+
' text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; margin-top: 10px;',
|
|
524
|
+
'}',
|
|
525
|
+
'.ktx-section-label:first-child { margin-top: 0; }',
|
|
526
|
+
'.ktx-test-btn {',
|
|
527
|
+
' display: inline-flex; align-items: center; gap: 4px;',
|
|
528
|
+
' padding: 4px 10px; border-radius: 5px; border: 1px solid rgba(255,255,255,0.1);',
|
|
529
|
+
' background: #313244; color: #cdd6f4; cursor: pointer;',
|
|
530
|
+
' font-size: 11px; font-family: inherit; margin-top: 8px; transition: background 0.15s;',
|
|
531
|
+
'}',
|
|
532
|
+
'.ktx-test-btn:hover { background: #45475a; }',
|
|
533
|
+
'.ktx-test-area {',
|
|
534
|
+
' margin-top: 8px; border-top: 1px solid rgba(255,255,255,0.06); padding-top: 8px;',
|
|
535
|
+
'}',
|
|
536
|
+
'.ktx-test-input {',
|
|
537
|
+
' width: 100%; box-sizing: border-box; min-height: 60px;',
|
|
538
|
+
' background: #181825; border: 1px solid rgba(255,255,255,0.1); border-radius: 6px;',
|
|
539
|
+
' color: #cdd6f4; padding: 8px; font-size: 12px; font-family: monospace;',
|
|
540
|
+
' resize: vertical;',
|
|
541
|
+
'}',
|
|
542
|
+
'.ktx-test-input:focus { outline: none; border-color: #cba6f7; }',
|
|
543
|
+
'.ktx-test-result {',
|
|
544
|
+
' margin-top: 6px; padding: 8px; border-radius: 6px;',
|
|
545
|
+
' font-size: 11px; font-family: monospace; max-height: 120px; overflow-y: auto;',
|
|
546
|
+
' white-space: pre-wrap; word-break: break-all;',
|
|
547
|
+
'}',
|
|
548
|
+
'.ktx-test-result.success { background: rgba(166,227,161,0.08); color: #a6e3a1; border: 1px solid rgba(166,227,161,0.15); }',
|
|
549
|
+
'.ktx-test-result.error { background: rgba(243,139,168,0.08); color: #f38ba8; border: 1px solid rgba(243,139,168,0.15); }',
|
|
550
|
+
'.ktx-close-btn {',
|
|
551
|
+
' border: none; background: none; color: #585b70; cursor: pointer;',
|
|
552
|
+
' font-size: 18px; line-height: 1; padding: 0 4px; transition: color 0.15s;',
|
|
553
|
+
'}',
|
|
554
|
+
'.ktx-close-btn:hover { color: #cdd6f4; }',
|
|
555
|
+
'.ktx-chevron { font-size: 12px; color: #585b70; transition: transform 0.2s; }',
|
|
556
|
+
'.ktx-tool-card.expanded .ktx-chevron { transform: rotate(180deg); }',
|
|
557
|
+
'.ktx-context-card {',
|
|
558
|
+
' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
|
|
559
|
+
' padding: 12px; background: #181825;',
|
|
560
|
+
'}',
|
|
561
|
+
'.ktx-context-label { font-weight: 600; color: #cba6f7; }',
|
|
562
|
+
'.ktx-context-desc { color: #a6adc8; font-size: 12px; margin-top: 4px; }',
|
|
563
|
+
].join('\\n');
|
|
564
|
+
document.head.appendChild(style);
|
|
565
|
+
|
|
566
|
+
// ── DOM ──────────────────────────────────────────────────
|
|
567
|
+
var open = false;
|
|
568
|
+
var activeTab = 'tools';
|
|
569
|
+
|
|
570
|
+
// Toggle button
|
|
571
|
+
var btn = document.createElement('button');
|
|
572
|
+
btn.className = 'ktx-btn';
|
|
573
|
+
btn.innerHTML = '\\uD83D\\uDEE0 Kortex <span class="ktx-badge" id="ktx-badge"></span>';
|
|
574
|
+
btn.onclick = function () {
|
|
575
|
+
open = !open;
|
|
576
|
+
panel.className = 'ktx-panel' + (open ? ' open' : '');
|
|
577
|
+
render();
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
// Panel
|
|
581
|
+
var panel = document.createElement('div');
|
|
582
|
+
panel.className = 'ktx-panel';
|
|
583
|
+
panel.innerHTML = [
|
|
584
|
+
'<div class="ktx-panel-header">',
|
|
585
|
+
' <div class="ktx-panel-title">\\uD83D\\uDEE0 Kortex DevTools</div>',
|
|
586
|
+
' <div class="ktx-tabs">',
|
|
587
|
+
' <button class="ktx-tab active" data-tab="tools">Tools (<span id="ktx-tool-count">0</span>)</button>',
|
|
588
|
+
' <button class="ktx-tab" data-tab="context">Context</button>',
|
|
589
|
+
' <button class="ktx-tab" data-tab="runs">Runs (<span id="ktx-run-count">0</span>)</button>',
|
|
590
|
+
' </div>',
|
|
591
|
+
' <button class="ktx-close-btn" id="ktx-close">×</button>',
|
|
592
|
+
'</div>',
|
|
593
|
+
'<div class="ktx-panel-body" id="ktx-body"></div>',
|
|
594
|
+
].join('');
|
|
595
|
+
|
|
596
|
+
// Close button
|
|
597
|
+
panel.querySelector('#ktx-close').onclick = function (e) {
|
|
598
|
+
e.stopPropagation();
|
|
599
|
+
open = false;
|
|
600
|
+
panel.className = 'ktx-panel';
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
// Tab switching
|
|
604
|
+
panel.querySelectorAll('.ktx-tab').forEach(function (tab) {
|
|
605
|
+
tab.onclick = function (e) {
|
|
606
|
+
e.stopPropagation();
|
|
607
|
+
activeTab = tab.dataset.tab;
|
|
608
|
+
render();
|
|
609
|
+
};
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
document.body.appendChild(btn);
|
|
613
|
+
document.body.appendChild(panel);
|
|
614
|
+
|
|
615
|
+
// ── Render ───────────────────────────────────────────────
|
|
616
|
+
function getTools() {
|
|
617
|
+
return (window.kortex && window.kortex.tools) ? window.kortex.tools : [];
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function getContext() {
|
|
621
|
+
return (window.kortex && window.kortex._context) ? window.kortex._context : null;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function render() {
|
|
625
|
+
var tools = getTools();
|
|
626
|
+
var ctx = getContext();
|
|
627
|
+
|
|
628
|
+
// Badge
|
|
629
|
+
var badge = document.getElementById('ktx-badge');
|
|
630
|
+
if (badge) badge.textContent = tools.length || '';
|
|
631
|
+
|
|
632
|
+
// Tab counts
|
|
633
|
+
var toolCountEl = document.getElementById('ktx-tool-count');
|
|
634
|
+
if (toolCountEl) toolCountEl.textContent = tools.length;
|
|
635
|
+
|
|
636
|
+
// Tabs
|
|
637
|
+
panel.querySelectorAll('.ktx-tab').forEach(function (t) {
|
|
638
|
+
t.className = 'ktx-tab' + (t.dataset.tab === activeTab ? ' active' : '');
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
// Body
|
|
642
|
+
var body = document.getElementById('ktx-body');
|
|
643
|
+
if (!body) return;
|
|
644
|
+
|
|
645
|
+
var runCountEl = document.getElementById('ktx-run-count');
|
|
646
|
+
var trace = (window.kortex && window.kortex._trace) ? window.kortex._trace : [];
|
|
647
|
+
if (runCountEl) runCountEl.textContent = trace.length;
|
|
648
|
+
|
|
649
|
+
if (activeTab === 'tools') {
|
|
650
|
+
renderTools(body, tools);
|
|
651
|
+
} else if (activeTab === 'runs') {
|
|
652
|
+
renderRuns(body, trace);
|
|
653
|
+
} else {
|
|
654
|
+
renderContext(body, ctx);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function esc(v) {
|
|
659
|
+
return String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// The point of this panel: a developer needs to see whether the model chose
|
|
663
|
+
// their tool and what arguments it invented — a chat transcript does not
|
|
664
|
+
// show that. Prompt box drives a real /chat round-trip through the same
|
|
665
|
+
// run() the app uses.
|
|
666
|
+
function renderRuns(body, trace) {
|
|
667
|
+
var html = '<div class="ktx-run-box">' +
|
|
668
|
+
'<input id="ktx-run-agent" class="ktx-run-input" placeholder="agent uuid (required)" />' +
|
|
669
|
+
'<textarea id="ktx-run-prompt" class="ktx-run-input" rows="2" placeholder="Ask something — does the model call your tool?"></textarea>' +
|
|
670
|
+
'<label class="ktx-run-check"><input type="checkbox" id="ktx-run-tools" checked /> expose registered tools</label>' +
|
|
671
|
+
'<button id="ktx-run-go" class="ktx-run-go">Run</button>' +
|
|
672
|
+
'<div id="ktx-run-status" class="ktx-run-status"></div>' +
|
|
673
|
+
'</div>';
|
|
674
|
+
|
|
675
|
+
if (!trace.length) {
|
|
676
|
+
html += '<div class="ktx-empty">No runs yet.<br><span style="font-size:11px">Trigger an action from your app, or use the box above.</span></div>';
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
for (var i = 0; i < trace.length; i++) {
|
|
680
|
+
var t = trace[i];
|
|
681
|
+
html += '<div class="ktx-tool">';
|
|
682
|
+
html += '<div class="ktx-tool-name">' + esc(t.name || '(unnamed)') + '</div>';
|
|
683
|
+
html += '<div class="ktx-tool-desc">' + esc(t.at) + '</div>';
|
|
684
|
+
if (t.steps && t.steps.length) {
|
|
685
|
+
for (var j = 0; j < t.steps.length; j++) {
|
|
686
|
+
var st = t.steps[j];
|
|
687
|
+
html += '<div class="ktx-step"><b>tool</b> ' + esc(st.tool) +
|
|
688
|
+
' <span class="ktx-badge">' + esc(st.policy && st.policy.category) + '/' + esc(st.policy && st.policy.risk) + '</span>' +
|
|
689
|
+
'<pre>args: ' + esc(JSON.stringify(st.arguments)) + '\\nresult: ' + esc(JSON.stringify(st.result)) + '</pre></div>';
|
|
690
|
+
}
|
|
691
|
+
} else {
|
|
692
|
+
html += '<div class="ktx-step"><i>no tool calls</i></div>';
|
|
693
|
+
}
|
|
694
|
+
if (t.error) {
|
|
695
|
+
html += '<div class="ktx-step ktx-err"><b>' + esc(t.error.code) + '</b> ' + esc(t.error.message) +
|
|
696
|
+
(t.error.details ? '<pre>' + esc(t.error.details) + '</pre>' : '') + '</div>';
|
|
697
|
+
} else if (t.result) {
|
|
698
|
+
html += '<div class="ktx-step"><b>result</b><pre>' +
|
|
699
|
+
esc(t.result.data !== null && t.result.data !== undefined ? JSON.stringify(t.result.data, null, 2) : t.result.text) +
|
|
700
|
+
'</pre></div>';
|
|
701
|
+
}
|
|
702
|
+
html += '</div>';
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
body.innerHTML = html;
|
|
706
|
+
|
|
707
|
+
var go = document.getElementById('ktx-run-go');
|
|
708
|
+
if (go) go.onclick = function (e) {
|
|
709
|
+
e.stopPropagation();
|
|
710
|
+
var agent = (document.getElementById('ktx-run-agent') || {}).value || '';
|
|
711
|
+
var prompt = (document.getElementById('ktx-run-prompt') || {}).value || '';
|
|
712
|
+
var useTools = (document.getElementById('ktx-run-tools') || {}).checked;
|
|
713
|
+
var status = document.getElementById('ktx-run-status');
|
|
714
|
+
if (!agent || !prompt) { if (status) status.textContent = 'agent uuid and prompt are both required'; return; }
|
|
715
|
+
if (status) status.textContent = 'running…';
|
|
716
|
+
window.kortex.run({ name: 'devtools-prompt', agent: agent, instructions: prompt, tools: !!useTools })
|
|
717
|
+
.then(function () { if (status) status.textContent = ''; })
|
|
718
|
+
.catch(function (err) { if (status) status.textContent = (err.code || 'error') + ': ' + err.message; });
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function renderTools(body, tools) {
|
|
723
|
+
if (tools.length === 0) {
|
|
724
|
+
body.innerHTML = '<div class="ktx-empty">No tools registered yet.<br><span style="font-size:11px">Call <code>registerTool()</code> or <code>useKortexTool()</code> from your app.</span></div>';
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
var html = '';
|
|
729
|
+
for (var i = 0; i < tools.length; i++) {
|
|
730
|
+
var t = tools[i];
|
|
731
|
+
var name = t.schema && t.schema.function ? t.schema.function.name : '(unnamed)';
|
|
732
|
+
var desc = (t.schema && t.schema.function && t.schema.function.description) || '';
|
|
733
|
+
var params = (t.schema && t.schema.function && t.schema.function.parameters) || null;
|
|
734
|
+
var policy = t.policy || {};
|
|
735
|
+
var risk = policy.risk || '';
|
|
736
|
+
var needsConfirm = policy.requiresConfirmation;
|
|
737
|
+
var category = policy.category || '';
|
|
738
|
+
|
|
739
|
+
var tags = '';
|
|
740
|
+
if (risk) {
|
|
741
|
+
var riskClass = 'ktx-tag-risk-' + risk;
|
|
742
|
+
tags += '<span class="ktx-tag ' + riskClass + '">' + risk + '</span>';
|
|
743
|
+
}
|
|
744
|
+
if (needsConfirm) {
|
|
745
|
+
tags += '<span class="ktx-tag ktx-tag-confirm">confirm</span>';
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
html += '<div class="ktx-tool-card" data-idx="' + i + '">';
|
|
749
|
+
html += '<div class="ktx-tool-card-header" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); card.classList.toggle(\\'expanded\\'); })(this)">';
|
|
750
|
+
html += '<div><div class="ktx-tool-name">' + esc(name) + '</div>';
|
|
751
|
+
if (desc) html += '<div class="ktx-tool-desc">' + esc(desc.slice(0, 80)) + (desc.length > 80 ? '...' : '') + '</div>';
|
|
752
|
+
html += '</div>';
|
|
753
|
+
html += '<div class="ktx-tool-meta">' + tags + '<span class="ktx-chevron">\\u25BC</span></div>';
|
|
754
|
+
html += '</div>';
|
|
755
|
+
|
|
756
|
+
// Expanded body
|
|
757
|
+
html += '<div class="ktx-tool-card-body">';
|
|
758
|
+
if (desc) html += '<div class="ktx-section-label">Description</div><div style="font-size:12px;color:#a6adc8">' + esc(desc) + '</div>';
|
|
759
|
+
if (category) html += '<div class="ktx-section-label">Category</div><div style="font-size:12px;color:#a6adc8">' + esc(category) + '</div>';
|
|
760
|
+
if (params) {
|
|
761
|
+
html += '<div class="ktx-section-label">Parameters Schema</div>';
|
|
762
|
+
html += '<div class="ktx-params">' + esc(JSON.stringify(params, null, 2)) + '</div>';
|
|
763
|
+
}
|
|
764
|
+
html += '<button class="ktx-test-btn" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); var idx=parseInt(card.dataset.idx); window.__ktx_testTool(idx, card); })(this)">\\u25B6 Test</button>';
|
|
765
|
+
html += '<div class="ktx-test-area" style="display:none">';
|
|
766
|
+
html += '<textarea class="ktx-test-input" placeholder=\\'{\"key\": \"value\"}\\' rows="3"></textarea>';
|
|
767
|
+
html += '<div style="display:flex;gap:6px;margin-top:6px">';
|
|
768
|
+
html += '<button class="ktx-test-btn" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); var idx=parseInt(card.dataset.idx); window.__ktx_runTest(idx, card); })(this)">Run</button>';
|
|
769
|
+
html += '<button class="ktx-test-btn" style="background:transparent" onclick="(function(el){ var area=el.closest(\\'.ktx-test-area\\'); area.style.display=\\'none\\'; var res=area.querySelector(\\'.ktx-test-result\\'); if(res)res.remove(); })(this)">Cancel</button>';
|
|
770
|
+
html += '</div>';
|
|
771
|
+
html += '</div>';
|
|
772
|
+
html += '</div>'; // ktx-tool-card-body
|
|
773
|
+
|
|
774
|
+
html += '</div>'; // ktx-tool-card
|
|
775
|
+
}
|
|
776
|
+
body.innerHTML = html;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function renderContext(body, ctx) {
|
|
780
|
+
if (!ctx) {
|
|
781
|
+
body.innerHTML = '<div class="ktx-empty">No page context registered.<br><span style="font-size:11px">Call <code>registerContext()</code> or <code>useKortexContext()</code> from your app.</span></div>';
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
var html = '<div class="ktx-context-card">';
|
|
785
|
+
html += '<div class="ktx-context-label">' + esc(ctx.label) + '</div>';
|
|
786
|
+
if (ctx.description) html += '<div class="ktx-context-desc">' + esc(ctx.description) + '</div>';
|
|
787
|
+
if (ctx.icon) html += '<div style="margin-top:8px;font-size:11px;color:#585b70">Icon: ' + esc(ctx.icon) + '</div>';
|
|
788
|
+
html += '</div>';
|
|
789
|
+
body.innerHTML = html;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function esc(s) {
|
|
793
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// ── Tool testing ─────────────────────────────────────────
|
|
797
|
+
window.__ktx_testTool = function (idx, card) {
|
|
798
|
+
var area = card.querySelector('.ktx-test-area');
|
|
799
|
+
if (!area) return;
|
|
800
|
+
var showing = area.style.display !== 'none';
|
|
801
|
+
area.style.display = showing ? 'none' : 'block';
|
|
802
|
+
// Clear previous result
|
|
803
|
+
var prevResult = area.querySelector('.ktx-test-result');
|
|
804
|
+
if (prevResult) prevResult.remove();
|
|
805
|
+
// Focus the input
|
|
806
|
+
if (!showing) {
|
|
807
|
+
var input = area.querySelector('.ktx-test-input');
|
|
808
|
+
if (input) setTimeout(function () { input.focus(); }, 50);
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
|
|
812
|
+
window.__ktx_runTest = function (idx, card) {
|
|
813
|
+
var tools = getTools();
|
|
814
|
+
var tool = tools[idx];
|
|
815
|
+
if (!tool) return;
|
|
816
|
+
|
|
817
|
+
var area = card.querySelector('.ktx-test-area');
|
|
818
|
+
var input = area.querySelector('.ktx-test-input');
|
|
819
|
+
var prevResult = area.querySelector('.ktx-test-result');
|
|
820
|
+
if (prevResult) prevResult.remove();
|
|
821
|
+
|
|
822
|
+
var args;
|
|
823
|
+
try {
|
|
824
|
+
args = input.value.trim() ? JSON.parse(input.value) : {};
|
|
825
|
+
} catch (e) {
|
|
826
|
+
showResult(area, 'Invalid JSON: ' + e.message, false);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
try {
|
|
831
|
+
var result = tool.execute(args);
|
|
832
|
+
if (result && typeof result.then === 'function') {
|
|
833
|
+
result.then(
|
|
834
|
+
function (v) { showResult(area, JSON.stringify(v, null, 2), true); },
|
|
835
|
+
function (e) { showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false); }
|
|
836
|
+
);
|
|
837
|
+
} else {
|
|
838
|
+
showResult(area, JSON.stringify(result, null, 2), true);
|
|
839
|
+
}
|
|
840
|
+
} catch (e) {
|
|
841
|
+
showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false);
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
function showResult(area, text, success) {
|
|
846
|
+
var div = document.createElement('div');
|
|
847
|
+
div.className = 'ktx-test-result ' + (success ? 'success' : 'error');
|
|
848
|
+
div.textContent = text;
|
|
849
|
+
area.appendChild(div);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// ── Subscribe to changes ─────────────────────────────────
|
|
853
|
+
if (window.kortex._subscribe) {
|
|
854
|
+
window.kortex._subscribe(function () {
|
|
855
|
+
if (open) render();
|
|
856
|
+
// Always update the badge
|
|
857
|
+
var badge = document.getElementById('ktx-badge');
|
|
858
|
+
if (badge) {
|
|
859
|
+
var tools = getTools();
|
|
860
|
+
badge.textContent = tools.length || '';
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// Initial render for badge
|
|
866
|
+
var badge = document.getElementById('ktx-badge');
|
|
867
|
+
if (badge) {
|
|
868
|
+
var tools = getTools();
|
|
869
|
+
badge.textContent = tools.length || '';
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
console.log('[ptkl forge dev] Kortex DevTools ready \\u2014 click the \\uD83D\\uDEE0 button to inspect registered tools');
|
|
873
|
+
});
|
|
874
|
+
})();`;
|
|
875
|
+
return {
|
|
876
|
+
name: 'ptkl-kortex-dev',
|
|
877
|
+
transformIndexHtml() {
|
|
878
|
+
return [
|
|
879
|
+
{
|
|
880
|
+
tag: 'script',
|
|
881
|
+
attrs: { type: 'text/javascript' },
|
|
882
|
+
children: polyfillScript,
|
|
883
|
+
injectTo: 'head-prepend',
|
|
884
|
+
},
|
|
885
|
+
{
|
|
886
|
+
tag: 'script',
|
|
887
|
+
attrs: { type: 'text/javascript' },
|
|
888
|
+
children: devtoolsScript,
|
|
889
|
+
injectTo: 'body',
|
|
890
|
+
},
|
|
891
|
+
];
|
|
892
|
+
},
|
|
893
|
+
};
|
|
894
|
+
}
|