@ptkl/toolkit 0.11.0 → 1.0.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.
@@ -1,40 +1,235 @@
1
1
  import { Command } from "commander";
2
- import { Platform as Api } from "@ptkl/sdk";
3
- import util from "../lib/util.js";
4
- import OutputFormatCommand from "./outputCommand.js";
2
+ import * as sdk from "../lib/sdk.js";
3
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
4
+ /** `ptkl workflow` — Workflow engine (RFC §4.2 "Workflow", `workflow/…` gateway prefix).
5
+ * Maps onto the SDK `Workflow` client (@ptkl/sdk/beta):
6
+ * - CRUD -> create/update/get/list/delete
7
+ * - trigger/publish/install -> trigger/publish/install
8
+ * - history -> getHistory/getHistoryEntry (execution history)
9
+ * - running -> getRunning/getRunningEntry (in-flight executions)
10
+ * - execution control -> pause/resume/kill/restart
11
+ * - node control -> pauseNode/resumeNode/killNode
12
+ * - errors -> getErrors/removeError/removeAllErrors */
13
+ function parseJSON(label, raw) {
14
+ try {
15
+ return JSON.parse(raw);
16
+ }
17
+ catch {
18
+ console.error(`${label} must be valid JSON`);
19
+ process.exit(1);
20
+ }
21
+ }
22
+ function readNodeControlOptions(opts) {
23
+ const iterationIdx = opts.iterationIdx !== undefined ? Number(opts.iterationIdx) : undefined;
24
+ const parentNodeId = opts.parentNodeId !== undefined ? Number(opts.parentNodeId) : undefined;
25
+ if (iterationIdx === undefined && parentNodeId === undefined)
26
+ return undefined;
27
+ return { ...(iterationIdx !== undefined ? { iterationIdx } : {}), ...(parentNodeId !== undefined ? { parentNodeId } : {}) };
28
+ }
29
+ function withNodeControlOptions(cmd) {
30
+ return cmd
31
+ .option("--iteration-idx <n>", "Iteration index (for nodes inside a loop)")
32
+ .option("--parent-node-id <id>", "Parent node ID (for nodes inside a loop)");
33
+ }
5
34
  class WorkflowCommand {
6
35
  register() {
7
- return new Command("workflow")
8
- .description("Manage project workflows")
9
- .version("0.1.0")
10
- .addCommand(new OutputFormatCommand(new Command("settings")
11
- .description("Get settings for a workflow")
12
- .requiredOption("-r, --ref <ref>", "Workflow name or UUID")).action(this.getSettings))
13
- .addCommand(new OutputFormatCommand(new Command("list")
14
- .description("List all workflows for the current project")).action(this.list))
15
- .addCommand(new OutputFormatCommand(new Command("get")
36
+ const cmd = new Command("workflow").description("Manage project workflows");
37
+ cmd.addCommand(registerCommand(new Command("list").description("List all workflows for the current project")).action(withProfile(async (profile) => {
38
+ const res = await sdk.workflow(profile).list();
39
+ return res.data;
40
+ })));
41
+ cmd.addCommand(registerCommand(new Command("get")
16
42
  .description("Get a workflow by name or UUID")
17
- .requiredOption("-r, --ref <ref>", "Workflow name or UUID")).action(this.get));
43
+ .requiredOption("-r, --ref <ref>", "Workflow name or UUID")).action(withProfile(async (profile, opts) => {
44
+ const res = await sdk.workflow(profile).get(opts.ref);
45
+ return res.data;
46
+ })));
47
+ cmd.addCommand(registerCommand(new Command("settings")
48
+ .description("Get settings for a workflow")
49
+ .requiredOption("-r, --ref <ref>", "Workflow name or UUID")).action(withProfile(async (profile, opts) => {
50
+ const res = await sdk.workflow(profile).get(opts.ref);
51
+ return res.data.settings;
52
+ })));
53
+ cmd.addCommand(registerCommand(new Command("create")
54
+ .description("Create a new workflow")
55
+ .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")).action(withProfile(async (profile, opts) => {
56
+ const data = parseJSON("--data", opts.data);
57
+ const res = await sdk.workflow(profile).create(data);
58
+ return res.data;
59
+ })));
60
+ cmd.addCommand(registerCommand(new Command("update")
61
+ .description("Update an existing workflow")
62
+ .argument("<id>", "Workflow UUID")
63
+ .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")).action(withProfile(async (profile, id, opts) => {
64
+ const data = parseJSON("--data", opts.data);
65
+ const res = await sdk.workflow(profile).update(id, data);
66
+ return res.data;
67
+ })));
68
+ cmd.addCommand(registerCommand(new Command("delete")
69
+ .description("Delete a workflow")
70
+ .argument("<id>", "Workflow UUID")).action(withProfile(async (profile, id) => {
71
+ const res = await sdk.workflow(profile).delete(id);
72
+ return res.data;
73
+ })));
74
+ cmd.addCommand(registerCommand(new Command("trigger")
75
+ .description("Trigger a workflow's event handler by workflow ID")
76
+ .argument("<id>", "Workflow UUID")
77
+ .argument("<event>", "Event name")
78
+ .option("-d, --data <json>", "Event payload as a JSON string", "{}")).action(withProfile(async (profile, id, event, opts) => {
79
+ const data = parseJSON("--data", opts.data);
80
+ const res = await sdk.workflow(profile).trigger(id, event, data);
81
+ return res.data;
82
+ })));
83
+ cmd.addCommand(registerCommand(new Command("publish")
84
+ .description("Publish an event to every workflow subscribed to it")
85
+ .argument("<event>", "Event name")
86
+ .option("-d, --data <json>", "Event payload as a JSON string", "{}")).action(withProfile(async (profile, event, opts) => {
87
+ const data = parseJSON("--data", opts.data);
88
+ const res = await sdk.workflow(profile).publish(event, data);
89
+ return res.data;
90
+ })));
91
+ cmd.addCommand(registerCommand(new Command("install")
92
+ .description("Create and publish a workflow in one call (rejects if name+integrator already exists)")
93
+ .requiredOption("-d, --data <json>", "Install payload as a JSON string (name, settings, project_uuid, dev_version, public_version, integrator)")).action(withProfile(async (profile, opts) => {
94
+ const data = parseJSON("--data", opts.data);
95
+ const res = await sdk.workflow(profile).install(data);
96
+ return res.data;
97
+ })));
98
+ cmd.addCommand(this.registerHistory());
99
+ cmd.addCommand(this.registerRunning());
100
+ cmd.addCommand(registerCommand(new Command("pause")
101
+ .description("Pause a running workflow execution")
102
+ .argument("<exec>", "Execution UUID")).action(withProfile(async (profile, exec) => {
103
+ const res = await sdk.workflow(profile).pause(exec);
104
+ return res.data;
105
+ })));
106
+ cmd.addCommand(registerCommand(new Command("resume")
107
+ .description("Resume a paused workflow execution")
108
+ .argument("<exec>", "Execution UUID")).action(withProfile(async (profile, exec) => {
109
+ const res = await sdk.workflow(profile).resume(exec);
110
+ return res.data;
111
+ })));
112
+ cmd.addCommand(registerCommand(new Command("kill")
113
+ .description("Kill a running or paused workflow execution")
114
+ .argument("<exec>", "Execution UUID")).action(withProfile(async (profile, exec) => {
115
+ const res = await sdk.workflow(profile).kill(exec);
116
+ return res.data;
117
+ })));
118
+ cmd.addCommand(registerCommand(new Command("restart")
119
+ .description("Restart a failed/killed workflow execution from history")
120
+ .argument("<exec>", "Execution UUID")
121
+ .option("--clear-state", "Discard prior node state instead of a smart resume")).action(withProfile(async (profile, exec, opts) => {
122
+ const res = await sdk.workflow(profile).restart(exec, { clearState: !!opts.clearState });
123
+ return res.data;
124
+ })));
125
+ cmd.addCommand(this.registerNode());
126
+ cmd.addCommand(this.registerErrors());
127
+ return cmd;
128
+ }
129
+ registerHistory() {
130
+ const history = new Command("history").description("Inspect workflow execution history");
131
+ history.addCommand(registerCommand(new Command("list")
132
+ .description("List workflow execution history, grouped by context")
133
+ .option("--limit <n>", "Max results")
134
+ .option("--offset <n>", "Result offset")
135
+ .option("--status <status>", "Filter by execution status")
136
+ .option("--ref <ref>", "Filter by workflow ref (name or UUID)")
137
+ .option("--type <type>", "Filter by execution type")
138
+ .option("--workflow-name <name>", "Filter by workflow name")
139
+ .option("--context-uuid <uuid>", "Filter by context UUID")
140
+ .option("--date-from <date>", "Only include executions starting after this date")).action(withProfile(async (profile, opts) => {
141
+ const res = await sdk.workflow(profile).getHistory({
142
+ limit: opts.limit !== undefined ? Number(opts.limit) : undefined,
143
+ offset: opts.offset !== undefined ? Number(opts.offset) : undefined,
144
+ status: opts.status,
145
+ ref: opts.ref,
146
+ type: opts.type,
147
+ workflow_name: opts.workflowName,
148
+ context_uuid: opts.contextUuid,
149
+ date_from: opts.dateFrom,
150
+ });
151
+ return res.data;
152
+ })));
153
+ history.addCommand(registerCommand(new Command("get")
154
+ .description("Get a single workflow execution history entry")
155
+ .argument("<exec>", "Execution UUID")).action(withProfile(async (profile, exec) => {
156
+ const res = await sdk.workflow(profile).getHistoryEntry(exec);
157
+ return res.data;
158
+ })));
159
+ return history;
18
160
  }
19
- async getSettings(opts) {
20
- const { ref } = opts;
21
- const profile = util.getCurrentProfile();
22
- const client = new Api({ token: profile.token, host: profile.host }).workflow();
23
- const { data } = await client.get(ref);
24
- return data.settings;
161
+ registerRunning() {
162
+ const running = new Command("running").description("Inspect currently running workflow executions");
163
+ running.addCommand(registerCommand(new Command("list")
164
+ .description("List currently running workflow executions")
165
+ .option("--limit <n>", "Max results")
166
+ .option("--offset <n>", "Result offset")
167
+ .option("--status <status>", "Filter by execution status")
168
+ .option("--type <type>", "Filter by execution type")
169
+ .option("--ref <ref>", "Filter by workflow ref (name or UUID)")
170
+ .option("--workflow-name <name>", "Filter by workflow name")
171
+ .option("--context-uuid <uuid>", "Filter by context UUID")).action(withProfile(async (profile, opts) => {
172
+ const res = await sdk.workflow(profile).getRunning({
173
+ limit: opts.limit !== undefined ? Number(opts.limit) : undefined,
174
+ offset: opts.offset !== undefined ? Number(opts.offset) : undefined,
175
+ status: opts.status,
176
+ type: opts.type,
177
+ ref: opts.ref,
178
+ workflow_name: opts.workflowName,
179
+ context_uuid: opts.contextUuid,
180
+ });
181
+ return res.data;
182
+ })));
183
+ running.addCommand(registerCommand(new Command("get")
184
+ .description("Get a single running workflow execution")
185
+ .argument("<exec>", "Execution UUID")).action(withProfile(async (profile, exec) => {
186
+ const res = await sdk.workflow(profile).getRunningEntry(exec);
187
+ return res.data;
188
+ })));
189
+ return running;
25
190
  }
26
- async list(opts) {
27
- const profile = util.getCurrentProfile();
28
- const client = new Api({ token: profile.token, host: profile.host }).workflow();
29
- const { data } = await client.list();
30
- return data;
191
+ registerNode() {
192
+ const node = new Command("node").description("Node-level execution control within a running workflow");
193
+ node.addCommand(registerCommand(withNodeControlOptions(new Command("pause")
194
+ .description("Pause a single node within a running workflow execution")
195
+ .argument("<exec>", "Execution UUID")
196
+ .argument("<nodeId>", "Node ID"))).action(withProfile(async (profile, exec, nodeId, opts) => {
197
+ const res = await sdk.workflow(profile).pauseNode(exec, Number(nodeId), readNodeControlOptions(opts));
198
+ return res.data;
199
+ })));
200
+ node.addCommand(registerCommand(withNodeControlOptions(new Command("resume")
201
+ .description("Resume a single node within a running workflow execution")
202
+ .argument("<exec>", "Execution UUID")
203
+ .argument("<nodeId>", "Node ID"))).action(withProfile(async (profile, exec, nodeId, opts) => {
204
+ const res = await sdk.workflow(profile).resumeNode(exec, Number(nodeId), readNodeControlOptions(opts));
205
+ return res.data;
206
+ })));
207
+ node.addCommand(registerCommand(withNodeControlOptions(new Command("kill")
208
+ .description("Kill a single node within a running workflow execution")
209
+ .argument("<exec>", "Execution UUID")
210
+ .argument("<nodeId>", "Node ID"))).action(withProfile(async (profile, exec, nodeId, opts) => {
211
+ const res = await sdk.workflow(profile).killNode(exec, Number(nodeId), readNodeControlOptions(opts));
212
+ return res.data;
213
+ })));
214
+ return node;
31
215
  }
32
- async get(opts) {
33
- const { ref } = opts;
34
- const profile = util.getCurrentProfile();
35
- const client = new Api({ token: profile.token, host: profile.host }).workflow();
36
- const { data } = await client.get(ref);
37
- return data;
216
+ registerErrors() {
217
+ const errors = new Command("errors").description("Manage workflow execution errors");
218
+ errors.addCommand(registerCommand(new Command("list").description("List workflow execution errors")).action(withProfile(async (profile) => {
219
+ const res = await sdk.workflow(profile).getErrors();
220
+ return res.data;
221
+ })));
222
+ errors.addCommand(registerCommand(new Command("remove")
223
+ .description("Remove a single workflow execution error")
224
+ .argument("<id>", "Error ID")).action(withProfile(async (profile, id) => {
225
+ const res = await sdk.workflow(profile).removeError(id);
226
+ return res.data;
227
+ })));
228
+ errors.addCommand(registerCommand(new Command("clear").description("Remove all workflow execution errors")).action(withProfile(async (profile) => {
229
+ const res = await sdk.workflow(profile).removeAllErrors();
230
+ return res.data;
231
+ })));
232
+ return errors;
38
233
  }
39
234
  }
40
235
  export default new WorkflowCommand();
@@ -7,13 +7,14 @@
7
7
  * in platform-forge/src/lib/dynamicImport.ts — uses a DOM overlay with an iframe
8
8
  * instead of a popup window to avoid popup blockers.
9
9
  */
10
- export function forgeDevKernelPlugin(appName, platformUrl) {
10
+ export function forgeDevKernelPlugin(appName, platformUrl, devHubPort) {
11
11
  const appRef = appName ?? '';
12
12
  const platUrl = platformUrl ? platformUrl.replace(/\/$/, '') : '';
13
13
  const scriptContent = `(function(){
14
14
  var _appRef=${JSON.stringify(appRef)};
15
15
  var _platformUrl=${JSON.stringify(platUrl)};
16
16
  window.$forge=window.forge||{};
17
+ ${devHubPort ? ` window.__PTKL_DEV_HUB__="http://localhost:${devHubPort}";\n window.DEV_HUB_PORT=${devHubPort};` : ''}
17
18
  function openPlatformPopup(url){return window.open(url,'_blank');}
18
19
  function showWaitingOverlay(message){
19
20
  var overlay=document.createElement('div');
@@ -0,0 +1,113 @@
1
+ import { EventEmitter } from 'node:events';
2
+ export class UIBridge extends EventEmitter {
3
+ cwd;
4
+ isLocal;
5
+ profileName;
6
+ _inputResolve = null;
7
+ _consentResolve = null;
8
+ _agentPickerResolve = null;
9
+ _convPickerResolve = null;
10
+ _lastThinkingContent = '';
11
+ _thinkingStart = 0;
12
+ agentName;
13
+ agentUUID;
14
+ constructor(opts) {
15
+ super();
16
+ this.agentUUID = opts.agentUUID;
17
+ this.agentName = opts.agentName;
18
+ this.cwd = opts.cwd;
19
+ this.isLocal = opts.isLocal;
20
+ this.profileName = opts.profileName;
21
+ }
22
+ // --- Input (session awaits, Ink resolves) ---
23
+ getInput() {
24
+ this.emit('input_ready');
25
+ return new Promise((resolve) => {
26
+ this._inputResolve = resolve;
27
+ });
28
+ }
29
+ submitInput(value) {
30
+ const resolve = this._inputResolve;
31
+ this._inputResolve = null;
32
+ resolve?.(value);
33
+ }
34
+ // --- Consent (session awaits, Ink resolves) ---
35
+ requestConsent(name, summary) {
36
+ this.emit('consent_request', { name, summary });
37
+ return new Promise((resolve) => {
38
+ this._consentResolve = resolve;
39
+ });
40
+ }
41
+ resolveConsent(answer) {
42
+ const resolve = this._consentResolve;
43
+ this._consentResolve = null;
44
+ resolve?.(answer);
45
+ }
46
+ // --- Session → UI: stream ---
47
+ startStream() { this.emit('stream_start'); }
48
+ appendDelta(text) { this.emit('delta', text); }
49
+ finalizeStream(content) { this.emit('stream_end', content); }
50
+ setStreamAgentLabel(name) { this.emit('agent_label', name); }
51
+ // --- Session → UI: thinking ---
52
+ startThinking() {
53
+ this._thinkingStart = Date.now();
54
+ this._lastThinkingContent = '';
55
+ this.emit('thinking_start');
56
+ }
57
+ appendThinkingDelta(text) {
58
+ this._lastThinkingContent += text;
59
+ }
60
+ finalizeThinking() {
61
+ const elapsed = ((Date.now() - this._thinkingStart) / 1000).toFixed(1);
62
+ this.emit('thinking_end', elapsed);
63
+ }
64
+ getLastThinking() { return this._lastThinkingContent; }
65
+ // --- Session → UI: messages ---
66
+ addUserMessage(content) { this.emit('user_message', content); }
67
+ addToolCall(name, summary) { this.emit('tool_call', { name, summary }); }
68
+ addToolResult(name, success, error) {
69
+ this.emit('tool_result', { name, success, error });
70
+ }
71
+ setTokenUsage(prompt, completion) {
72
+ this.emit('token_usage', { prompt, completion });
73
+ }
74
+ showError(message) { this.emit('error', message); }
75
+ showSystem(content) { this.emit('system', content); }
76
+ showMCPStatus(servers) { this.emit('mcp_status', servers); }
77
+ setProcessing(active) { this.emit('processing', active); }
78
+ setContextUsage(used, limit) { this.emit('context_usage', { used, limit }); }
79
+ clearMessages() { this.emit('clear'); }
80
+ // --- Agent picker (session awaits, Ink resolves) ---
81
+ showAgentPicker(agents) {
82
+ this.emit('show_agent_picker', agents);
83
+ return new Promise((resolve) => {
84
+ this._agentPickerResolve = resolve;
85
+ });
86
+ }
87
+ resolveAgentPicker(agent) {
88
+ const resolve = this._agentPickerResolve;
89
+ this._agentPickerResolve = null;
90
+ resolve?.(agent);
91
+ }
92
+ setActiveAgent(uuid, name) {
93
+ this.agentUUID = uuid;
94
+ this.agentName = name;
95
+ this.emit('active_agent_changed', { uuid, name });
96
+ }
97
+ // --- Conversation picker (session awaits, Ink resolves) ---
98
+ showConversationPicker(conversations) {
99
+ this.emit('show_conv_picker', conversations);
100
+ return new Promise((resolve) => {
101
+ this._convPickerResolve = resolve;
102
+ });
103
+ }
104
+ resolveConversationPicker(conv) {
105
+ const resolve = this._convPickerResolve;
106
+ this._convPickerResolve = null;
107
+ resolve?.(conv);
108
+ }
109
+ replayMessages(messages) {
110
+ this.emit('replay_messages', messages);
111
+ }
112
+ quit() { this.emit('quit'); }
113
+ }
@@ -0,0 +1,21 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const CONFIG_DIR = join(process.env.HOME ?? '~', '.ptkl');
4
+ const CONFIG_FILE = join(CONFIG_DIR, 'kortex.json');
5
+ export function loadKortexConfig() {
6
+ try {
7
+ if (existsSync(CONFIG_FILE)) {
8
+ return JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
9
+ }
10
+ }
11
+ catch { /* ignore malformed file */ }
12
+ return {};
13
+ }
14
+ export function saveKortexConfig(config) {
15
+ try {
16
+ if (!existsSync(CONFIG_DIR))
17
+ mkdirSync(CONFIG_DIR, { recursive: true });
18
+ writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
19
+ }
20
+ catch { /* ignore write errors */ }
21
+ }
@@ -0,0 +1,84 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ const CONV_DIR = join(process.env.HOME ?? '~', '.ptkl', 'kortex', 'conversations');
5
+ function ensureDir() {
6
+ if (!existsSync(CONV_DIR))
7
+ mkdirSync(CONV_DIR, { recursive: true });
8
+ }
9
+ function filePath(uuid) {
10
+ return join(CONV_DIR, `${uuid}.json`);
11
+ }
12
+ function deriveTitle(messages) {
13
+ const first = messages.find(m => m.role === 'user');
14
+ if (!first)
15
+ return 'New conversation';
16
+ const text = first.content.trim();
17
+ return text.length > 60 ? text.slice(0, 57) + '...' : text;
18
+ }
19
+ export function createConversation(agentUUID, agentName, cwd) {
20
+ const now = new Date().toISOString();
21
+ return {
22
+ meta: {
23
+ uuid: randomUUID(),
24
+ title: 'New conversation',
25
+ agentUUID,
26
+ agentName,
27
+ cwd,
28
+ createdAt: now,
29
+ updatedAt: now,
30
+ messageCount: 0,
31
+ },
32
+ messages: [],
33
+ };
34
+ }
35
+ export function saveConversation(conv) {
36
+ try {
37
+ ensureDir();
38
+ conv.meta.updatedAt = new Date().toISOString();
39
+ conv.meta.messageCount = conv.messages.filter(m => m.role === 'user' || m.role === 'assistant').length;
40
+ conv.meta.title = deriveTitle(conv.messages);
41
+ writeFileSync(filePath(conv.meta.uuid), JSON.stringify(conv, null, 2));
42
+ }
43
+ catch { /* ignore write errors */ }
44
+ }
45
+ export function loadConversation(uuid) {
46
+ try {
47
+ const data = readFileSync(filePath(uuid), 'utf-8');
48
+ return JSON.parse(data);
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ export function listConversations() {
55
+ try {
56
+ ensureDir();
57
+ const files = readdirSync(CONV_DIR).filter(f => f.endsWith('.json'));
58
+ const metas = [];
59
+ for (const file of files) {
60
+ try {
61
+ const data = JSON.parse(readFileSync(join(CONV_DIR, file), 'utf-8'));
62
+ if (data.meta)
63
+ metas.push(data.meta);
64
+ }
65
+ catch { /* skip corrupt files */ }
66
+ }
67
+ metas.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
68
+ return metas;
69
+ }
70
+ catch {
71
+ return [];
72
+ }
73
+ }
74
+ export function deleteConversation(uuid) {
75
+ try {
76
+ const path = filePath(uuid);
77
+ if (existsSync(path)) {
78
+ unlinkSync(path);
79
+ return true;
80
+ }
81
+ }
82
+ catch { /* ignore */ }
83
+ return false;
84
+ }