@ptkl/toolkit 1.1.0 → 1.2.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.
@@ -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,7 @@ class ForgeCommand {
774
775
  },
775
776
  plugins: [
776
777
  forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
778
+ kortexDevPlugin(),
777
779
  {
778
780
  // Console bridge (dev only): when the app runs EMBEDDED (e.g. the
779
781
  // 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 --user <U> --tx <T>`
7
- * is literally `new Integrations({profile}).getPayments().refund('monri', U, T)` ->
8
- * `/karadjordje/v1/payment/monri/{U}/refund/{T}` — reached here via `sdk.payments(profile)`
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
- .requiredOption("-u, --user <userId>", "User id")
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.user, opts.tx);
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
- .requiredOption("-u, --user <userId>", "User id")
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, opts.user, {
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
- .requiredOption("-u, --user <userId>", "User id")
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, opts.user, {
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
- .requiredOption("-u, --user <userId>", "User id")
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, opts.user, {
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
- .requiredOption("-u, --user <userId>", "User id")
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.user, opts.tx);
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
- .requiredOption("-u, --user <userId>", "User id")
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.user, opts.tx);
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
- .requiredOption("-u, --user <userId>", "User id")
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.user, opts.tx);
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,523 @@
1
+ /**
2
+ * Vite plugin that polyfills `window.kortex` during `ptkl forge dev` and
3
+ * injects a developer tools panel for inspecting registered Kortex tools.
4
+ *
5
+ * In production the platform-forge runtime provides the real `window.kortex`,
6
+ * but during local development it's absent — so all `registerTool()` /
7
+ * `useKortexTool()` calls silently no-op. This plugin closes that gap:
8
+ *
9
+ * 1. Polyfills `window.kortex` with a fully functional KortexAPI that stores
10
+ * every registered tool, just like production.
11
+ * 2. Injects a floating DevTools overlay so developers can see every
12
+ * registered tool, its schema, policy, and page context in real time.
13
+ * 3. Includes a tool tester — invoke any tool with custom JSON arguments
14
+ * and inspect the return value or error.
15
+ */
16
+ export function kortexDevPlugin() {
17
+ // ── Polyfill script (runs BEFORE the app) ──────────────────────────
18
+ const polyfillScript = `(function(){
19
+ if (window.kortex) return; // already provided (e.g. by the real platform runtime)
20
+
21
+ var _tools = [];
22
+ var _context = null;
23
+ var _helperActive = false;
24
+ var _listeners = [];
25
+
26
+ function notify() {
27
+ for (var i = 0; i < _listeners.length; i++) _listeners[i]();
28
+ }
29
+
30
+ window.kortex = {
31
+ get tools() { return _tools; },
32
+
33
+ _context: null,
34
+ _helperActive: false,
35
+
36
+ registerTool: function (schema, executeFn, policy) {
37
+ // Remove any existing tool with the same name
38
+ var name = schema && schema.function && schema.function.name;
39
+ if (name) {
40
+ for (var i = _tools.length - 1; i >= 0; i--) {
41
+ if (_tools[i].schema.function.name === name) _tools.splice(i, 1);
42
+ }
43
+ }
44
+ _tools.push({
45
+ schema: schema,
46
+ execute: executeFn,
47
+ policy: policy || {}
48
+ });
49
+ _context = window.kortex._context;
50
+ _helperActive = window.kortex._helperActive;
51
+ notify();
52
+ console.log('[kortex dev] tool registered:', (name || '(unnamed)'),
53
+ '(total:', _tools.length + ')');
54
+ },
55
+
56
+ unregisterTool: function (name) {
57
+ for (var i = _tools.length - 1; i >= 0; i--) {
58
+ if (_tools[i].schema.function.name === name) {
59
+ _tools.splice(i, 1);
60
+ notify();
61
+ console.log('[kortex dev] tool unregistered:', name,
62
+ '(total:', _tools.length + ')');
63
+ return;
64
+ }
65
+ }
66
+ },
67
+
68
+ registerContext: function (label, description, icon) {
69
+ window.kortex._context = { label: label, description: description || '', icon: icon || null };
70
+ _context = window.kortex._context;
71
+ notify();
72
+ },
73
+
74
+ unregisterContext: function () {
75
+ window.kortex._context = null;
76
+ _context = null;
77
+ notify();
78
+ },
79
+
80
+ showHelper: function () {
81
+ window.kortex._helperActive = true;
82
+ _helperActive = true;
83
+ notify();
84
+ },
85
+
86
+ hideHelper: function () {
87
+ window.kortex._helperActive = false;
88
+ _helperActive = false;
89
+ notify();
90
+ },
91
+
92
+ // Internal: subscribe to changes (used by the devtools panel)
93
+ _subscribe: function (fn) {
94
+ _listeners.push(fn);
95
+ return function () {
96
+ var idx = _listeners.indexOf(fn);
97
+ if (idx >= 0) _listeners.splice(idx, 1);
98
+ };
99
+ }
100
+ };
101
+
102
+ // Keep _context and _helperActive getters in sync
103
+ Object.defineProperty(window.kortex, '_context', {
104
+ get: function () { return _context; },
105
+ set: function (v) { _context = v; },
106
+ enumerable: true, configurable: true
107
+ });
108
+ Object.defineProperty(window.kortex, '_helperActive', {
109
+ get: function () { return _helperActive; },
110
+ set: function (v) { _helperActive = v; },
111
+ enumerable: true, configurable: true
112
+ });
113
+
114
+ console.log('[ptkl forge dev] kortex polyfill ready');
115
+ })();`;
116
+ // ── DevTools panel script (runs AFTER the polyfill) ────────────────
117
+ const devtoolsScript = `(function(){
118
+ if (window.__KORTEX_DEVTOOLS_LOADED) return;
119
+ window.__KORTEX_DEVTOOLS_LOADED = true;
120
+
121
+ // Wait for kortex polyfill
122
+ function waitForKortex(cb) {
123
+ if (window.kortex) { cb(); return; }
124
+ var tries = 0;
125
+ var iv = setInterval(function () {
126
+ if (window.kortex || ++tries > 50) { clearInterval(iv); if (window.kortex) cb(); }
127
+ }, 100);
128
+ }
129
+
130
+ waitForKortex(function () {
131
+
132
+ // ── Styles ──────────────────────────────────────────────
133
+ var style = document.createElement('style');
134
+ style.textContent = [
135
+ '@keyframes ktx-slide-up { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }',
136
+ '@keyframes ktx-fade-in { from { opacity: 0; } to { opacity: 1; } }',
137
+ '@keyframes ktx-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.12); } }',
138
+ '.ktx-btn {',
139
+ ' position: fixed; bottom: 16px; right: 16px; z-index: 99990;',
140
+ ' display: flex; align-items: center; gap: 6px;',
141
+ ' padding: 8px 14px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.12);',
142
+ ' background: #1e1e2e; color: #cdd6f4; cursor: pointer;',
143
+ ' font-family: system-ui, -apple-system, sans-serif; font-size: 13px; font-weight: 500;',
144
+ ' box-shadow: 0 4px 24px rgba(0,0,0,0.4); transition: box-shadow 0.2s, background 0.2s;',
145
+ ' user-select: none;',
146
+ '}',
147
+ '.ktx-btn:hover { background: #313244; box-shadow: 0 6px 32px rgba(0,0,0,0.5); }',
148
+ '.ktx-badge {',
149
+ ' display: inline-flex; align-items: center; justify-content: center;',
150
+ ' min-width: 20px; height: 20px; border-radius: 10px;',
151
+ ' background: #cba6f7; color: #1e1e2e; font-size: 11px; font-weight: 700;',
152
+ ' padding: 0 6px;',
153
+ '}',
154
+ '.ktx-badge:empty { display: none; }',
155
+ '.ktx-panel {',
156
+ ' position: fixed; bottom: 60px; right: 16px; z-index: 99989;',
157
+ ' width: 520px; max-height: 480px;',
158
+ ' border-radius: 12px; border: 1px solid rgba(255,255,255,0.1);',
159
+ ' background: #1e1e2e; color: #cdd6f4;',
160
+ ' box-shadow: 0 8px 40px rgba(0,0,0,0.5);',
161
+ ' font-family: system-ui, -apple-system, sans-serif; font-size: 13px;',
162
+ ' display: none; flex-direction: column; overflow: hidden;',
163
+ ' animation: ktx-slide-up 0.2s ease-out;',
164
+ '}',
165
+ '.ktx-panel.open { display: flex; }',
166
+ '.ktx-panel-header {',
167
+ ' display: flex; align-items: center; justify-content: space-between;',
168
+ ' padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.08);',
169
+ ' background: #181825; flex-shrink: 0;',
170
+ '}',
171
+ '.ktx-panel-title { font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; }',
172
+ '.ktx-tabs { display: flex; gap: 2px; }',
173
+ '.ktx-tab {',
174
+ ' padding: 5px 12px; border-radius: 6px; border: none; cursor: pointer;',
175
+ ' background: transparent; color: #a6adc8; font-size: 12px; font-family: inherit;',
176
+ ' transition: background 0.15s, color 0.15s;',
177
+ '}',
178
+ '.ktx-tab:hover { background: #313244; color: #cdd6f4; }',
179
+ '.ktx-tab.active { background: #45475a; color: #cdd6f4; }',
180
+ '.ktx-panel-body {',
181
+ ' flex: 1; overflow-y: auto; padding: 8px 14px;',
182
+ ' scrollbar-width: thin; scrollbar-color: #45475a transparent;',
183
+ '}',
184
+ '.ktx-panel-body::-webkit-scrollbar { width: 6px; }',
185
+ '.ktx-panel-body::-webkit-scrollbar-thumb { background: #45475a; border-radius: 3px; }',
186
+ '.ktx-empty {',
187
+ ' text-align: center; padding: 32px 16px; color: #585b70;',
188
+ '}',
189
+ '.ktx-tool-card {',
190
+ ' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
191
+ ' margin-bottom: 8px; background: #181825; overflow: hidden;',
192
+ '}',
193
+ '.ktx-tool-card-header {',
194
+ ' display: flex; align-items: center; justify-content: space-between;',
195
+ ' padding: 8px 12px; cursor: pointer; user-select: none;',
196
+ ' transition: background 0.15s;',
197
+ '}',
198
+ '.ktx-tool-card-header:hover { background: #313244; }',
199
+ '.ktx-tool-name { font-weight: 600; font-size: 13px; color: #cba6f7; }',
200
+ '.ktx-tool-desc { font-size: 12px; color: #a6adc8; margin-top: 2px; }',
201
+ '.ktx-tool-meta { display: flex; gap: 6px; align-items: center; flex-shrink: 0; }',
202
+ '.ktx-tag {',
203
+ ' display: inline-block; padding: 2px 7px; border-radius: 4px;',
204
+ ' font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;',
205
+ '}',
206
+ '.ktx-tag-risk-low { background: rgba(166,227,161,0.15); color: #a6e3a1; }',
207
+ '.ktx-tag-risk-medium { background: rgba(249,226,175,0.15); color: #f9e2af; }',
208
+ '.ktx-tag-risk-high { background: rgba(243,139,168,0.15); color: #f38ba8; }',
209
+ '.ktx-tag-confirm { background: rgba(203,166,247,0.15); color: #cba6f7; }',
210
+ '.ktx-tool-card-body {',
211
+ ' display: none; padding: 10px 12px; border-top: 1px solid rgba(255,255,255,0.06);',
212
+ ' background: #11111b;',
213
+ '}',
214
+ '.ktx-tool-card.expanded .ktx-tool-card-body { display: block; }',
215
+ '.ktx-params {',
216
+ ' font-family: "SF Mono", "Cascadia Code", "Fira Code", monospace;',
217
+ ' font-size: 11px; background: #181825; padding: 10px; border-radius: 6px;',
218
+ ' overflow-x: auto; white-space: pre; color: #a6adc8;',
219
+ ' max-height: 160px; overflow-y: auto;',
220
+ '}',
221
+ '.ktx-section-label {',
222
+ ' font-size: 11px; font-weight: 600; color: #585b70;',
223
+ ' text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; margin-top: 10px;',
224
+ '}',
225
+ '.ktx-section-label:first-child { margin-top: 0; }',
226
+ '.ktx-test-btn {',
227
+ ' display: inline-flex; align-items: center; gap: 4px;',
228
+ ' padding: 4px 10px; border-radius: 5px; border: 1px solid rgba(255,255,255,0.1);',
229
+ ' background: #313244; color: #cdd6f4; cursor: pointer;',
230
+ ' font-size: 11px; font-family: inherit; margin-top: 8px; transition: background 0.15s;',
231
+ '}',
232
+ '.ktx-test-btn:hover { background: #45475a; }',
233
+ '.ktx-test-area {',
234
+ ' margin-top: 8px; border-top: 1px solid rgba(255,255,255,0.06); padding-top: 8px;',
235
+ '}',
236
+ '.ktx-test-input {',
237
+ ' width: 100%; box-sizing: border-box; min-height: 60px;',
238
+ ' background: #181825; border: 1px solid rgba(255,255,255,0.1); border-radius: 6px;',
239
+ ' color: #cdd6f4; padding: 8px; font-size: 12px; font-family: monospace;',
240
+ ' resize: vertical;',
241
+ '}',
242
+ '.ktx-test-input:focus { outline: none; border-color: #cba6f7; }',
243
+ '.ktx-test-result {',
244
+ ' margin-top: 6px; padding: 8px; border-radius: 6px;',
245
+ ' font-size: 11px; font-family: monospace; max-height: 120px; overflow-y: auto;',
246
+ ' white-space: pre-wrap; word-break: break-all;',
247
+ '}',
248
+ '.ktx-test-result.success { background: rgba(166,227,161,0.08); color: #a6e3a1; border: 1px solid rgba(166,227,161,0.15); }',
249
+ '.ktx-test-result.error { background: rgba(243,139,168,0.08); color: #f38ba8; border: 1px solid rgba(243,139,168,0.15); }',
250
+ '.ktx-close-btn {',
251
+ ' border: none; background: none; color: #585b70; cursor: pointer;',
252
+ ' font-size: 18px; line-height: 1; padding: 0 4px; transition: color 0.15s;',
253
+ '}',
254
+ '.ktx-close-btn:hover { color: #cdd6f4; }',
255
+ '.ktx-chevron { font-size: 12px; color: #585b70; transition: transform 0.2s; }',
256
+ '.ktx-tool-card.expanded .ktx-chevron { transform: rotate(180deg); }',
257
+ '.ktx-context-card {',
258
+ ' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
259
+ ' padding: 12px; background: #181825;',
260
+ '}',
261
+ '.ktx-context-label { font-weight: 600; color: #cba6f7; }',
262
+ '.ktx-context-desc { color: #a6adc8; font-size: 12px; margin-top: 4px; }',
263
+ ].join('\\n');
264
+ document.head.appendChild(style);
265
+
266
+ // ── DOM ──────────────────────────────────────────────────
267
+ var open = false;
268
+ var activeTab = 'tools';
269
+
270
+ // Toggle button
271
+ var btn = document.createElement('button');
272
+ btn.className = 'ktx-btn';
273
+ btn.innerHTML = '\\uD83D\\uDEE0 Kortex <span class="ktx-badge" id="ktx-badge"></span>';
274
+ btn.onclick = function () {
275
+ open = !open;
276
+ panel.className = 'ktx-panel' + (open ? ' open' : '');
277
+ render();
278
+ };
279
+
280
+ // Panel
281
+ var panel = document.createElement('div');
282
+ panel.className = 'ktx-panel';
283
+ panel.innerHTML = [
284
+ '<div class="ktx-panel-header">',
285
+ ' <div class="ktx-panel-title">\\uD83D\\uDEE0 Kortex DevTools</div>',
286
+ ' <div class="ktx-tabs">',
287
+ ' <button class="ktx-tab active" data-tab="tools">Tools (<span id="ktx-tool-count">0</span>)</button>',
288
+ ' <button class="ktx-tab" data-tab="context">Context</button>',
289
+ ' </div>',
290
+ ' <button class="ktx-close-btn" id="ktx-close">&times;</button>',
291
+ '</div>',
292
+ '<div class="ktx-panel-body" id="ktx-body"></div>',
293
+ ].join('');
294
+
295
+ // Close button
296
+ panel.querySelector('#ktx-close').onclick = function (e) {
297
+ e.stopPropagation();
298
+ open = false;
299
+ panel.className = 'ktx-panel';
300
+ };
301
+
302
+ // Tab switching
303
+ panel.querySelectorAll('.ktx-tab').forEach(function (tab) {
304
+ tab.onclick = function (e) {
305
+ e.stopPropagation();
306
+ activeTab = tab.dataset.tab;
307
+ render();
308
+ };
309
+ });
310
+
311
+ document.body.appendChild(btn);
312
+ document.body.appendChild(panel);
313
+
314
+ // ── Render ───────────────────────────────────────────────
315
+ function getTools() {
316
+ return (window.kortex && window.kortex.tools) ? window.kortex.tools : [];
317
+ }
318
+
319
+ function getContext() {
320
+ return (window.kortex && window.kortex._context) ? window.kortex._context : null;
321
+ }
322
+
323
+ function render() {
324
+ var tools = getTools();
325
+ var ctx = getContext();
326
+
327
+ // Badge
328
+ var badge = document.getElementById('ktx-badge');
329
+ if (badge) badge.textContent = tools.length || '';
330
+
331
+ // Tab counts
332
+ var toolCountEl = document.getElementById('ktx-tool-count');
333
+ if (toolCountEl) toolCountEl.textContent = tools.length;
334
+
335
+ // Tabs
336
+ panel.querySelectorAll('.ktx-tab').forEach(function (t) {
337
+ t.className = 'ktx-tab' + (t.dataset.tab === activeTab ? ' active' : '');
338
+ });
339
+
340
+ // Body
341
+ var body = document.getElementById('ktx-body');
342
+ if (!body) return;
343
+
344
+ if (activeTab === 'tools') {
345
+ renderTools(body, tools);
346
+ } else {
347
+ renderContext(body, ctx);
348
+ }
349
+ }
350
+
351
+ function renderTools(body, tools) {
352
+ if (tools.length === 0) {
353
+ 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>';
354
+ return;
355
+ }
356
+
357
+ var html = '';
358
+ for (var i = 0; i < tools.length; i++) {
359
+ var t = tools[i];
360
+ var name = t.schema && t.schema.function ? t.schema.function.name : '(unnamed)';
361
+ var desc = (t.schema && t.schema.function && t.schema.function.description) || '';
362
+ var params = (t.schema && t.schema.function && t.schema.function.parameters) || null;
363
+ var policy = t.policy || {};
364
+ var risk = policy.risk || '';
365
+ var needsConfirm = policy.requiresConfirmation;
366
+ var category = policy.category || '';
367
+
368
+ var tags = '';
369
+ if (risk) {
370
+ var riskClass = 'ktx-tag-risk-' + risk;
371
+ tags += '<span class="ktx-tag ' + riskClass + '">' + risk + '</span>';
372
+ }
373
+ if (needsConfirm) {
374
+ tags += '<span class="ktx-tag ktx-tag-confirm">confirm</span>';
375
+ }
376
+
377
+ html += '<div class="ktx-tool-card" data-idx="' + i + '">';
378
+ html += '<div class="ktx-tool-card-header" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); card.classList.toggle(\\'expanded\\'); })(this)">';
379
+ html += '<div><div class="ktx-tool-name">' + esc(name) + '</div>';
380
+ if (desc) html += '<div class="ktx-tool-desc">' + esc(desc.slice(0, 80)) + (desc.length > 80 ? '...' : '') + '</div>';
381
+ html += '</div>';
382
+ html += '<div class="ktx-tool-meta">' + tags + '<span class="ktx-chevron">\\u25BC</span></div>';
383
+ html += '</div>';
384
+
385
+ // Expanded body
386
+ html += '<div class="ktx-tool-card-body">';
387
+ if (desc) html += '<div class="ktx-section-label">Description</div><div style="font-size:12px;color:#a6adc8">' + esc(desc) + '</div>';
388
+ if (category) html += '<div class="ktx-section-label">Category</div><div style="font-size:12px;color:#a6adc8">' + esc(category) + '</div>';
389
+ if (params) {
390
+ html += '<div class="ktx-section-label">Parameters Schema</div>';
391
+ html += '<div class="ktx-params">' + esc(JSON.stringify(params, null, 2)) + '</div>';
392
+ }
393
+ 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>';
394
+ html += '<div class="ktx-test-area" style="display:none">';
395
+ html += '<textarea class="ktx-test-input" placeholder=\\'{\"key\": \"value\"}\\' rows="3"></textarea>';
396
+ html += '<div style="display:flex;gap:6px;margin-top:6px">';
397
+ 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>';
398
+ 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>';
399
+ html += '</div>';
400
+ html += '</div>';
401
+ html += '</div>'; // ktx-tool-card-body
402
+
403
+ html += '</div>'; // ktx-tool-card
404
+ }
405
+ body.innerHTML = html;
406
+ }
407
+
408
+ function renderContext(body, ctx) {
409
+ if (!ctx) {
410
+ 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>';
411
+ return;
412
+ }
413
+ var html = '<div class="ktx-context-card">';
414
+ html += '<div class="ktx-context-label">' + esc(ctx.label) + '</div>';
415
+ if (ctx.description) html += '<div class="ktx-context-desc">' + esc(ctx.description) + '</div>';
416
+ if (ctx.icon) html += '<div style="margin-top:8px;font-size:11px;color:#585b70">Icon: ' + esc(ctx.icon) + '</div>';
417
+ html += '</div>';
418
+ body.innerHTML = html;
419
+ }
420
+
421
+ function esc(s) {
422
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
423
+ }
424
+
425
+ // ── Tool testing ─────────────────────────────────────────
426
+ window.__ktx_testTool = function (idx, card) {
427
+ var area = card.querySelector('.ktx-test-area');
428
+ if (!area) return;
429
+ var showing = area.style.display !== 'none';
430
+ area.style.display = showing ? 'none' : 'block';
431
+ // Clear previous result
432
+ var prevResult = area.querySelector('.ktx-test-result');
433
+ if (prevResult) prevResult.remove();
434
+ // Focus the input
435
+ if (!showing) {
436
+ var input = area.querySelector('.ktx-test-input');
437
+ if (input) setTimeout(function () { input.focus(); }, 50);
438
+ }
439
+ };
440
+
441
+ window.__ktx_runTest = function (idx, card) {
442
+ var tools = getTools();
443
+ var tool = tools[idx];
444
+ if (!tool) return;
445
+
446
+ var area = card.querySelector('.ktx-test-area');
447
+ var input = area.querySelector('.ktx-test-input');
448
+ var prevResult = area.querySelector('.ktx-test-result');
449
+ if (prevResult) prevResult.remove();
450
+
451
+ var args;
452
+ try {
453
+ args = input.value.trim() ? JSON.parse(input.value) : {};
454
+ } catch (e) {
455
+ showResult(area, 'Invalid JSON: ' + e.message, false);
456
+ return;
457
+ }
458
+
459
+ try {
460
+ var result = tool.execute(args);
461
+ if (result && typeof result.then === 'function') {
462
+ result.then(
463
+ function (v) { showResult(area, JSON.stringify(v, null, 2), true); },
464
+ function (e) { showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false); }
465
+ );
466
+ } else {
467
+ showResult(area, JSON.stringify(result, null, 2), true);
468
+ }
469
+ } catch (e) {
470
+ showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false);
471
+ }
472
+ };
473
+
474
+ function showResult(area, text, success) {
475
+ var div = document.createElement('div');
476
+ div.className = 'ktx-test-result ' + (success ? 'success' : 'error');
477
+ div.textContent = text;
478
+ area.appendChild(div);
479
+ }
480
+
481
+ // ── Subscribe to changes ─────────────────────────────────
482
+ if (window.kortex._subscribe) {
483
+ window.kortex._subscribe(function () {
484
+ if (open) render();
485
+ // Always update the badge
486
+ var badge = document.getElementById('ktx-badge');
487
+ if (badge) {
488
+ var tools = getTools();
489
+ badge.textContent = tools.length || '';
490
+ }
491
+ });
492
+ }
493
+
494
+ // Initial render for badge
495
+ var badge = document.getElementById('ktx-badge');
496
+ if (badge) {
497
+ var tools = getTools();
498
+ badge.textContent = tools.length || '';
499
+ }
500
+
501
+ console.log('[ptkl forge dev] Kortex DevTools ready \\u2014 click the \\uD83D\\uDEE0 button to inspect registered tools');
502
+ });
503
+ })();`;
504
+ return {
505
+ name: 'ptkl-kortex-dev',
506
+ transformIndexHtml() {
507
+ return [
508
+ {
509
+ tag: 'script',
510
+ attrs: { type: 'text/javascript' },
511
+ children: polyfillScript,
512
+ injectTo: 'head-prepend',
513
+ },
514
+ {
515
+ tag: 'script',
516
+ attrs: { type: 'text/javascript' },
517
+ children: devtoolsScript,
518
+ injectTo: 'body',
519
+ },
520
+ ];
521
+ },
522
+ };
523
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",