@kalphq/cli 0.0.0-dev-20260509010940 → 0.0.0-dev-20260510030416

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.
Files changed (40) hide show
  1. package/dist/{add-KRHLYYTO.js → add-XTXSSGC5.js} +3 -2
  2. package/dist/{add-KRHLYYTO.js.map → add-XTXSSGC5.js.map} +1 -1
  3. package/dist/chunk-5RODADXW.js +65 -0
  4. package/dist/chunk-5RODADXW.js.map +1 -0
  5. package/dist/chunk-E7V5UMX7.js +28 -0
  6. package/dist/chunk-E7V5UMX7.js.map +1 -0
  7. package/dist/chunk-FO24J6XL.js +23 -0
  8. package/dist/chunk-FO24J6XL.js.map +1 -0
  9. package/dist/chunk-NJ3OTDOX.js +93 -0
  10. package/dist/chunk-NJ3OTDOX.js.map +1 -0
  11. package/dist/{delete-47ZP6XRB.js → delete-N4OSUK3X.js} +3 -2
  12. package/dist/{delete-47ZP6XRB.js.map → delete-N4OSUK3X.js.map} +1 -1
  13. package/dist/deploy-HRUJDN2F.js +63 -0
  14. package/dist/deploy-HRUJDN2F.js.map +1 -0
  15. package/dist/dev-ZKXOQ2GQ.js +71 -0
  16. package/dist/dev-ZKXOQ2GQ.js.map +1 -0
  17. package/dist/index.js +12 -9
  18. package/dist/index.js.map +1 -1
  19. package/dist/{list-3ZQIFUOT.js → list-VMJPWHIH.js} +3 -2
  20. package/dist/{list-3ZQIFUOT.js.map → list-VMJPWHIH.js.map} +1 -1
  21. package/dist/login-M5Y57ZZU.js +73 -0
  22. package/dist/login-M5Y57ZZU.js.map +1 -0
  23. package/dist/{logout-V67DZZXO.js → logout-U5V5K775.js} +5 -4
  24. package/dist/logout-U5V5K775.js.map +1 -0
  25. package/dist/push-P2NWWXGL.js +287 -0
  26. package/dist/push-P2NWWXGL.js.map +1 -0
  27. package/dist/{secrets-KFMVBKJQ.js → secrets-P7ADVLOS.js} +5 -5
  28. package/dist/{sync-YFM5P3IS.js → sync-OTO44GQS.js} +3 -2
  29. package/dist/{sync-YFM5P3IS.js.map → sync-OTO44GQS.js.map} +1 -1
  30. package/package.json +5 -4
  31. package/dist/chunk-6LLXGS2P.js +0 -25
  32. package/dist/chunk-6LLXGS2P.js.map +0 -1
  33. package/dist/login-JYPWGL6P.js +0 -38
  34. package/dist/login-JYPWGL6P.js.map +0 -1
  35. package/dist/logout-V67DZZXO.js.map +0 -1
  36. package/dist/push-UZADV7TZ.js +0 -255
  37. package/dist/push-UZADV7TZ.js.map +0 -1
  38. package/dist/studio-7LGUD42G.js +0 -92
  39. package/dist/studio-7LGUD42G.js.map +0 -1
  40. /package/dist/{secrets-KFMVBKJQ.js.map → secrets-P7ADVLOS.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/login.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst LOGO = \"🦋\";\n\nexport default defineCommand({\n meta: { name: \"login\", description: \"Authenticate with Kalp\" },\n async run() {\n const home = homedir();\n\n p.intro(`${LOGO} ${pc.bold(\"kalp login\")}`);\n\n const s = p.spinner();\n s.start(\"Authenticating...\");\n\n // Create ~/.kalp directory (global user config)\n const kalpDir = join(home, \".kalp\");\n await mkdir(kalpDir, { recursive: true });\n\n // Create mock auth.json\n const authData = {\n token: \"mock-token-\" + Date.now(),\n email: \"user@example.com\",\n expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),\n };\n\n await writeFile(\n join(kalpDir, \"auth.json\"),\n JSON.stringify(authData, null, 2),\n \"utf-8\",\n );\n\n s.stop(\"Authenticated successfully\");\n p.log.success(`Logged in as ${pc.cyan(authData.email)}`);\n p.outro(pc.green(\"Ready to use Kalp Cloud\"));\n },\n});\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,YAAY,OAAO;AACnB,OAAO,QAAQ;AACf,SAAS,OAAO,iBAAiB;AACjC,SAAS,YAAY;AACrB,SAAS,eAAe;AAExB,IAAM,OAAO;AAEb,IAAO,gBAAQ,cAAc;AAAA,EAC3B,MAAM,EAAE,MAAM,SAAS,aAAa,yBAAyB;AAAA,EAC7D,MAAM,MAAM;AACV,UAAM,OAAO,QAAQ;AAErB,IAAE,QAAM,GAAG,IAAI,IAAI,GAAG,KAAK,YAAY,CAAC,EAAE;AAE1C,UAAM,IAAM,UAAQ;AACpB,MAAE,MAAM,mBAAmB;AAG3B,UAAM,UAAU,KAAK,MAAM,OAAO;AAClC,UAAM,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAGxC,UAAM,WAAW;AAAA,MACf,OAAO,gBAAgB,KAAK,IAAI;AAAA,MAChC,OAAO;AAAA,MACP,WAAW,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,KAAK,GAAI,EAAE,YAAY;AAAA,IACzE;AAEA,UAAM;AAAA,MACJ,KAAK,SAAS,WAAW;AAAA,MACzB,KAAK,UAAU,UAAU,MAAM,CAAC;AAAA,MAChC;AAAA,IACF;AAEA,MAAE,KAAK,4BAA4B;AACnC,IAAE,MAAI,QAAQ,gBAAgB,GAAG,KAAK,SAAS,KAAK,CAAC,EAAE;AACvD,IAAE,QAAM,GAAG,MAAM,yBAAyB,CAAC;AAAA,EAC7C;AACF,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/logout.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst LOGO = \"🦋\";\n\nexport default defineCommand({\n meta: { name: \"logout\", description: \"Sign out from Kalp\" },\n async run() {\n const home = homedir();\n\n p.intro(`${LOGO} ${pc.bold(\"kalp logout\")}`);\n\n const s = p.spinner();\n s.start(\"Signing out...\");\n\n try {\n await rm(join(home, \".kalp\", \"auth.json\"), { force: true });\n s.stop(\"Signed out successfully\");\n p.outro(pc.green(\"Logged out from Kalp\"));\n } catch {\n s.stop(\"Nothing to do\");\n p.outro(pc.dim(\"No active session found\"));\n }\n },\n});\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,YAAY,OAAO;AACnB,OAAO,QAAQ;AACf,SAAS,UAAU;AACnB,SAAS,YAAY;AACrB,SAAS,eAAe;AAExB,IAAM,OAAO;AAEb,IAAO,iBAAQ,cAAc;AAAA,EAC3B,MAAM,EAAE,MAAM,UAAU,aAAa,qBAAqB;AAAA,EAC1D,MAAM,MAAM;AACV,UAAM,OAAO,QAAQ;AAErB,IAAE,QAAM,GAAG,IAAI,IAAI,GAAG,KAAK,aAAa,CAAC,EAAE;AAE3C,UAAM,IAAM,UAAQ;AACpB,MAAE,MAAM,gBAAgB;AAExB,QAAI;AACF,YAAM,GAAG,KAAK,MAAM,SAAS,WAAW,GAAG,EAAE,OAAO,KAAK,CAAC;AAC1D,QAAE,KAAK,yBAAyB;AAChC,MAAE,QAAM,GAAG,MAAM,sBAAsB,CAAC;AAAA,IAC1C,QAAQ;AACN,QAAE,KAAK,eAAe;AACtB,MAAE,QAAM,GAAG,IAAI,yBAAyB,CAAC;AAAA,IAC3C;AAAA,EACF;AACF,CAAC;","names":[]}
@@ -1,255 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- ensureConfig
4
- } from "./chunk-INB3LG6O.js";
5
-
6
- // src/commands/push.ts
7
- import { access as access2, mkdir, writeFile, readFile as readFile2 } from "fs/promises";
8
- import { join as join2 } from "path";
9
- import { defineCommand } from "citty";
10
- import * as p2 from "@clack/prompts";
11
- import pc from "picocolors";
12
-
13
- // src/utils/manifest/index.ts
14
- import { access, readFile, rm, mkdtemp } from "fs/promises";
15
- import { join } from "path";
16
- import { tmpdir } from "os";
17
- import { buildAgent } from "@kalphq/compiler";
18
-
19
- // src/utils/ir/hashIR.ts
20
- import { calculateAgentHash } from "@kalphq/compiler";
21
- function computePushHash(ir) {
22
- const bundles = ir.bundles || {};
23
- const handlers = Object.keys(bundles).reduce(
24
- (acc, hash) => ({
25
- ...acc,
26
- [hash]: { hash }
27
- }),
28
- {}
29
- );
30
- return calculateAgentHash(ir, handlers);
31
- }
32
-
33
- // src/utils/manifest/index.ts
34
- async function readAgentManifest(params) {
35
- const { cwd, agentName } = params;
36
- const agentPath = join(cwd, "agents", agentName, "index.ts");
37
- await access(agentPath);
38
- const tempOutDir = await mkdtemp(join(tmpdir(), "kalp-build-"));
39
- try {
40
- await buildAgent(agentPath, tempOutDir, cwd);
41
- const irContent = await readFile(join(tempOutDir, "ir.json"), "utf-8");
42
- const ir = JSON.parse(irContent);
43
- return {
44
- format: "kalp-agent-manifest",
45
- schemaVersion: 3,
46
- ir,
47
- metadata: {
48
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
49
- }
50
- };
51
- } finally {
52
- await rm(tempOutDir, { recursive: true, force: true });
53
- }
54
- }
55
-
56
- // src/utils/issues.ts
57
- import p from "picocolors";
58
- var severityIcons = {
59
- error: p.red("\u2718"),
60
- warning: p.yellow("\u26A0"),
61
- info: p.blue("\u2139")
62
- };
63
- var severityLabels = {
64
- error: p.red("Error"),
65
- warning: p.yellow("Warning"),
66
- info: p.blue("Info")
67
- };
68
- function renderLegacyError(error, showDebug = true) {
69
- const lines = [];
70
- const debugMatch = error.match(/\(debug: (.+)\)$/);
71
- const debug = debugMatch ? debugMatch[1] : void 0;
72
- const mainError = debugMatch ? error.replace(/\(debug: .+\)$/, "").trim() : error;
73
- lines.push(p.red(p.bold(`\u2718 ${mainError.split("\n")[0]}`)));
74
- const fixMatch = mainError.match(/Fix:\n((?:- .+\n?)+)/);
75
- if (fixMatch) {
76
- lines.push("");
77
- lines.push(p.green(" Fix:"));
78
- const fixLines = fixMatch[1]?.split("\n").filter(Boolean) ?? [];
79
- for (const line of fixLines) {
80
- lines.push(` ${line.replace(/^- /, "")}`);
81
- }
82
- }
83
- if (showDebug && debug) {
84
- lines.push("");
85
- lines.push(p.dim(` (debug: ${debug})`));
86
- }
87
- return lines.join("\n");
88
- }
89
-
90
- // src/commands/push.ts
91
- var LOGO = "\u{1F98B}";
92
- function formatBytes(bytes) {
93
- if (bytes < 1024) return `${bytes} B`;
94
- return `${(bytes / 1024).toFixed(1)} KB`;
95
- }
96
- function printPushResult(agentName, hash, handlers) {
97
- const div = pc.dim("\u2500".repeat(48));
98
- const handlerCount = Object.keys(handlers).length;
99
- const totalSize = Object.values(handlers).reduce((sum, h) => sum + h.size, 0);
100
- console.log("\n" + div);
101
- console.log(pc.green("\u2714 Deployed"));
102
- console.log("");
103
- console.log(` ${pc.bold(agentName)} ${pc.dim(hash.slice(0, 7))}...`);
104
- console.log(
105
- ` ${pc.dim(String(handlerCount))} handlers \xB7 ${formatBytes(totalSize)}`
106
- );
107
- console.log(div + "\n");
108
- }
109
- function printPushError(phase, errors, blockers, verbose) {
110
- const div = pc.dim("\u2500".repeat(48));
111
- console.log("\n" + div);
112
- for (const e of errors) {
113
- console.log(renderLegacyError(e, verbose));
114
- console.log("");
115
- }
116
- if (phase === "analysis" && blockers) {
117
- for (const b of blockers) {
118
- console.log(pc.red(`\u2718 Blocker: ${b}`));
119
- }
120
- }
121
- if (!verbose) {
122
- console.log(pc.dim(`
123
- Run with --verbose for more details.
124
- `));
125
- }
126
- console.log(div + "\n");
127
- }
128
- var push_default = defineCommand({
129
- meta: { name: "push", description: "Push agent to Kalp cloud" },
130
- args: {
131
- agent: {
132
- type: "string",
133
- alias: "a",
134
- description: "Agent name to push",
135
- required: false
136
- },
137
- verbose: {
138
- type: "boolean",
139
- alias: "v",
140
- description: "Show debug information",
141
- default: false
142
- }
143
- },
144
- async run({ args }) {
145
- const cwd = process.cwd();
146
- const agentName = args.agent;
147
- p2.intro(`${LOGO} ${pc.bold("kalp push")}`);
148
- if (!agentName) {
149
- p2.log.error(`Missing required flag ${pc.cyan("-a <agent-name>")}`);
150
- process.exit(1);
151
- }
152
- try {
153
- await ensureConfig(cwd);
154
- } catch {
155
- p2.log.error(`${pc.cyan("kalp.config.ts")} not found`);
156
- process.exit(1);
157
- }
158
- const agentPath = join2(cwd, "agents", agentName, "index.ts");
159
- try {
160
- await access2(agentPath);
161
- } catch {
162
- p2.log.error(`Agent ${pc.cyan(agentName)} not found`);
163
- process.exit(1);
164
- }
165
- const s = p2.spinner();
166
- s.start(`Compiling ${pc.cyan(agentName)}`);
167
- const manifest = await readAgentManifest({ cwd, agentName });
168
- const bundles = manifest.ir.bundles || {};
169
- const handlerCount = Object.keys(bundles).length;
170
- const hash = computePushHash(manifest.ir);
171
- s.stop(`Compiled ${pc.cyan(agentName)} \u2014 ${handlerCount} handlers`);
172
- s.start(`Checking for changes`);
173
- const statusResponse = await fetch(
174
- `http://localhost:3000/api/agents/${agentName}/status`
175
- );
176
- const statusData = await statusResponse.json().catch(() => null);
177
- if (statusData?.exists && statusData.hash === hash) {
178
- s.stop(pc.green("No changes detected"));
179
- p2.note(
180
- `Agent ${pc.cyan(agentName)} is already deployed with the same logic.`,
181
- "Skipped"
182
- );
183
- p2.outro(`${LOGO} ${pc.green("No deployment needed")}`);
184
- return;
185
- }
186
- s.start(`Pushing to cloud`);
187
- let secretKey;
188
- try {
189
- const envPath = join2(cwd, ".env");
190
- const envContent = await readFile2(envPath, "utf-8");
191
- const match = envContent.match(/^KALP_SECRET_KEY=(.+)$/m);
192
- if (match && match[1]) {
193
- secretKey = match[1].trim();
194
- }
195
- } catch {
196
- }
197
- if (!secretKey) {
198
- p2.log.warning(
199
- "KALP_SECRET_KEY not found in .env. Studio authentication will not work."
200
- );
201
- p2.note("Run 'kalp studio' to generate a new secret.", "Action");
202
- }
203
- const response = await fetch(`http://localhost:3000/api/agents/push`, {
204
- method: "POST",
205
- headers: { "Content-Type": "application/json" },
206
- body: JSON.stringify({
207
- agentName,
208
- ir: manifest.ir,
209
- hash,
210
- secretKey
211
- // Send secret for injection into Cloudflare
212
- })
213
- });
214
- const body = await response.json().catch(() => null);
215
- if (!response.ok) {
216
- s.stop(pc.red("Push failed"));
217
- const phase = body?.phase ?? "unknown";
218
- const errors = body?.errors ?? [`HTTP ${response.status}`];
219
- const blockers = body?.blockers;
220
- printPushError(phase, errors, blockers);
221
- process.exit(1);
222
- }
223
- const displayHandlers = Object.entries(bundles).reduce(
224
- (acc, [hash2, bundle]) => ({
225
- ...acc,
226
- [hash2]: {
227
- size: Buffer.byteLength(bundle.code)
228
- }
229
- }),
230
- {}
231
- );
232
- s.stop(pc.green("Pushed successfully"));
233
- printPushResult(agentName, hash, displayHandlers);
234
- const kalpDir = join2(cwd, ".kalp");
235
- await mkdir(kalpDir, { recursive: true });
236
- const stateData = {
237
- agentName,
238
- workerUrl: `http://localhost:3000/a/${agentName}`,
239
- lastPush: (/* @__PURE__ */ new Date()).toISOString(),
240
- hash
241
- };
242
- await writeFile(
243
- join2(kalpDir, "state.json"),
244
- JSON.stringify(stateData, null, 2),
245
- "utf-8"
246
- );
247
- const dashboardUrl = `http://localhost:3000/a/${agentName}`;
248
- p2.outro(`${LOGO} ${pc.green("Agent live at")} ${pc.cyan(dashboardUrl)}`);
249
- process.exit(0);
250
- }
251
- });
252
- export {
253
- push_default as default
254
- };
255
- //# sourceMappingURL=push-UZADV7TZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/push.ts","../src/utils/manifest/index.ts","../src/utils/ir/hashIR.ts","../src/utils/issues.ts"],"sourcesContent":["import { access, mkdir, writeFile, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { defineCommand } from \"citty\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { ensureConfig } from \"@/utils/fs\";\nimport { readAgentManifest, computePushHash } from \"@/utils/manifest\";\nimport { renderLegacyError } from \"@/utils/issues\";\n\nconst LOGO = \"🦋\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n return `${(bytes / 1024).toFixed(1)} KB`;\n}\n\nfunction printPushResult(\n agentName: string,\n hash: string,\n handlers: Record<string, { size: number }>,\n) {\n const div = pc.dim(\"─\".repeat(48));\n const handlerCount = Object.keys(handlers).length;\n const totalSize = Object.values(handlers).reduce((sum, h) => sum + h.size, 0);\n\n console.log(\"\\n\" + div);\n console.log(pc.green(\"✔ Deployed\"));\n console.log(\"\");\n console.log(` ${pc.bold(agentName)} ${pc.dim(hash.slice(0, 7))}...`);\n console.log(\n ` ${pc.dim(String(handlerCount))} handlers · ${formatBytes(totalSize)}`,\n );\n console.log(div + \"\\n\");\n}\n\nfunction printPushError(\n phase: string,\n errors: string[],\n blockers?: string[],\n verbose?: boolean,\n) {\n const div = pc.dim(\"─\".repeat(48));\n console.log(\"\\n\" + div);\n\n for (const e of errors) {\n console.log(renderLegacyError(e, verbose));\n console.log(\"\");\n }\n\n if (phase === \"analysis\" && blockers) {\n for (const b of blockers) {\n console.log(pc.red(`✘ Blocker: ${b}`));\n }\n }\n\n if (!verbose) {\n console.log(pc.dim(`\\nRun with --verbose for more details.\\n`));\n }\n\n console.log(div + \"\\n\");\n}\n\nexport default defineCommand({\n meta: { name: \"push\", description: \"Push agent to Kalp cloud\" },\n args: {\n agent: {\n type: \"string\",\n alias: \"a\",\n description: \"Agent name to push\",\n required: false,\n },\n verbose: {\n type: \"boolean\",\n alias: \"v\",\n description: \"Show debug information\",\n default: false,\n },\n },\n async run({ args }) {\n const cwd = process.cwd();\n const agentName = args.agent;\n\n p.intro(`${LOGO} ${pc.bold(\"kalp push\")}`);\n\n if (!agentName) {\n p.log.error(`Missing required flag ${pc.cyan(\"-a <agent-name>\")}`);\n process.exit(1);\n }\n\n try {\n await ensureConfig(cwd);\n } catch {\n p.log.error(`${pc.cyan(\"kalp.config.ts\")} not found`);\n process.exit(1);\n }\n\n const agentPath = join(cwd, \"agents\", agentName, \"index.ts\");\n try {\n await access(agentPath);\n } catch {\n p.log.error(`Agent ${pc.cyan(agentName)} not found`);\n process.exit(1);\n }\n\n const s = p.spinner();\n s.start(`Compiling ${pc.cyan(agentName)}`);\n\n const manifest = await readAgentManifest({ cwd, agentName });\n\n const bundles = (manifest.ir.bundles || {}) as Record<\n string,\n { code: string }\n >;\n const handlerCount = Object.keys(bundles).length;\n\n const hash = computePushHash(manifest.ir);\n\n s.stop(`Compiled ${pc.cyan(agentName)} — ${handlerCount} handlers`);\n\n s.start(`Checking for changes`);\n\n const statusResponse = await fetch(\n `http://localhost:3000/api/agents/${agentName}/status`,\n );\n\n const statusData = (await statusResponse.json().catch(() => null)) as {\n agentName: string;\n hash?: string;\n exists: boolean;\n } | null;\n\n if (statusData?.exists && statusData.hash === hash) {\n s.stop(pc.green(\"No changes detected\"));\n p.note(\n `Agent ${pc.cyan(agentName)} is already deployed with the same logic.`,\n \"Skipped\",\n );\n p.outro(`${LOGO} ${pc.green(\"No deployment needed\")}`);\n return;\n }\n\n s.start(`Pushing to cloud`);\n\n // Read KALP_SECRET_KEY from .env local\n let secretKey: string | undefined;\n try {\n const envPath = join(cwd, \".env\");\n const envContent = await readFile(envPath, \"utf-8\");\n const match = envContent.match(/^KALP_SECRET_KEY=(.+)$/m);\n if (match && match[1]) {\n secretKey = match[1].trim();\n }\n } catch {\n // .env doesn't exist\n }\n\n if (!secretKey) {\n p.log.warning(\n \"KALP_SECRET_KEY not found in .env. Studio authentication will not work.\",\n );\n p.note(\"Run 'kalp studio' to generate a new secret.\", \"Action\");\n }\n\n const response = await fetch(`http://localhost:3000/api/agents/push`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n agentName,\n ir: manifest.ir,\n hash,\n secretKey, // Send secret for injection into Cloudflare\n }),\n });\n\n const body = (await response.json().catch(() => null)) as Record<\n string,\n unknown\n > | null;\n\n if (!response.ok) {\n s.stop(pc.red(\"Push failed\"));\n const phase = (body?.phase as string) ?? \"unknown\";\n const errors = (body?.errors as string[]) ?? [`HTTP ${response.status}`];\n const blockers = body?.blockers as string[] | undefined;\n printPushError(phase, errors, blockers);\n process.exit(1);\n }\n\n const displayHandlers = Object.entries(bundles).reduce(\n (acc, [hash, bundle]) => ({\n ...acc,\n [hash]: {\n size: Buffer.byteLength(bundle.code),\n },\n }),\n {} as Record<string, { size: number }>,\n );\n\n s.stop(pc.green(\"Pushed successfully\"));\n printPushResult(agentName, hash, displayHandlers);\n\n // Save worker URL to .kalp/state.json\n const kalpDir = join(cwd, \".kalp\");\n await mkdir(kalpDir, { recursive: true });\n\n const stateData = {\n agentName,\n workerUrl: `http://localhost:3000/a/${agentName}`,\n lastPush: new Date().toISOString(),\n hash,\n };\n\n await writeFile(\n join(kalpDir, \"state.json\"),\n JSON.stringify(stateData, null, 2),\n \"utf-8\",\n );\n\n const dashboardUrl = `http://localhost:3000/a/${agentName}`;\n p.outro(`${LOGO} ${pc.green(\"Agent live at\")} ${pc.cyan(dashboardUrl)}`);\n\n process.exit(0);\n },\n});\n","import { access, readFile, rm, mkdtemp } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport { buildAgent } from \"@kalphq/compiler\";\n\nimport type { AgentManifestV3 } from \"@/utils/manifest/types\";\nexport type { AgentManifestV3 } from \"@/utils/manifest/types\";\nexport { computePushHash } from \"@/utils/ir/hashIR\";\n\n/**\n * Reads and compiles an agent into a pushable manifest.\n */\nexport async function readAgentManifest(params: {\n cwd: string;\n agentName: string;\n}): Promise<AgentManifestV3> {\n const { cwd, agentName } = params;\n const agentPath = join(cwd, \"agents\", agentName, \"index.ts\");\n await access(agentPath);\n\n // Use a temporary directory for the compiler output\n const tempOutDir = await mkdtemp(join(tmpdir(), \"kalp-build-\"));\n\n try {\n // Build the agent - compiler produces ir.bundles with all handler code\n await buildAgent(agentPath, tempOutDir, cwd);\n\n // Load the IR generated by the compiler (includes bundles with code)\n const irContent = await readFile(join(tempOutDir, \"ir.json\"), \"utf-8\");\n const ir = JSON.parse(irContent);\n\n return {\n format: \"kalp-agent-manifest\",\n schemaVersion: 3,\n ir,\n metadata: {\n generatedAt: new Date().toISOString(),\n },\n };\n } finally {\n // Cleanup temp build directory\n await rm(tempOutDir, { recursive: true, force: true });\n }\n}\n","import type { IRGraph } from \"@kalphq/sdk\";\nimport { calculateAgentHash } from \"@kalphq/compiler\";\n\nexport function getIRHash(ir: IRGraph): string {\n const { calculateIRHash } = require(\"@kalphq/compiler\");\n return calculateIRHash(ir);\n}\n\nexport function computePushHash(\n ir: IRGraph & { bundles?: Record<string, { code: string }> },\n): string {\n const bundles = ir.bundles || {};\n const handlers = Object.keys(bundles).reduce(\n (acc, hash) => ({\n ...acc,\n [hash]: { hash },\n }),\n {} as Record<string, { hash: string }>,\n );\n\n return calculateAgentHash(ir, handlers);\n}\n","import p from \"picocolors\";\n\n/**\n * Severity level for a validation issue.\n */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A structured validation issue found during agent analysis or compilation.\n */\nexport interface ValidationIssue {\n severity: Severity;\n message: string;\n context?: string;\n location?: string;\n fix?: string;\n debug?: string;\n}\n\ninterface RenderOptions {\n format?: \"pretty\" | \"json\" | \"minimal\";\n showDebug?: boolean;\n}\n\nconst severityIcons: Record<Severity, string> = {\n error: p.red(\"✘\"),\n warning: p.yellow(\"⚠\"),\n info: p.blue(\"ℹ\"),\n};\n\nconst severityLabels: Record<Severity, string> = {\n error: p.red(\"Error\"),\n warning: p.yellow(\"Warning\"),\n info: p.blue(\"Info\"),\n};\n\nfunction groupByContext(\n issues: ValidationIssue[],\n): Map<string, ValidationIssue[]> {\n const groups = new Map<string, ValidationIssue[]>();\n\n for (const issue of issues) {\n const context = issue.context ?? \"General\";\n const existing = groups.get(context) ?? [];\n existing.push(issue);\n groups.set(context, existing);\n }\n\n return groups;\n}\n\nfunction renderPrettyIssue(issue: ValidationIssue, showDebug: boolean): string {\n const lines: string[] = [];\n\n // Header with icon, severity label, and message\n lines.push(\n `${severityIcons[issue.severity]} ${severityLabels[issue.severity]}: ${p.bold(issue.message)}`,\n );\n\n // Context (location in code)\n if (issue.context) {\n lines.push(p.dim(` Found in: ${issue.context}`));\n }\n if (issue.location) {\n lines.push(p.dim(` Location: ${issue.location}`));\n }\n\n // Empty line before fix\n lines.push(\"\");\n\n // Fix section\n if (issue.fix) {\n lines.push(p.green(\" Fix:\"));\n const fixLines = issue.fix.split(\"\\n\");\n for (const fixLine of fixLines) {\n lines.push(` ${fixLine}`);\n }\n }\n\n // Debug info (optional)\n if (showDebug && issue.debug) {\n lines.push(\"\");\n lines.push(p.dim(` (debug: ${issue.debug})`));\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction renderGroupedIssues(\n issues: ValidationIssue[],\n showDebug: boolean,\n): string {\n const groups = groupByContext(issues);\n const output: string[] = [];\n\n for (const [context, contextIssues] of groups) {\n // Context header\n output.push(p.cyan(p.bold(`→ ${context}`)));\n output.push(\"\");\n\n // Issues in this context\n for (const issue of contextIssues) {\n output.push(renderPrettyIssue(issue, showDebug));\n output.push(\"\"); // Empty line between issues\n }\n }\n\n return output.join(\"\\n\");\n}\n\nfunction renderMinimalIssue(issue: ValidationIssue): string {\n const icon =\n issue.severity === \"error\" ? \"✘\" : issue.severity === \"warning\" ? \"⚠\" : \"ℹ\";\n const context = issue.context ? ` [${issue.context}]` : \"\";\n return `${icon} ${issue.message}${context}`;\n}\n\nexport function renderIssues(\n issues: ValidationIssue[],\n options: RenderOptions = {},\n): string {\n const { format = \"pretty\", showDebug = false } = options;\n\n if (issues.length === 0) {\n return p.green(\"✓ No issues found\");\n }\n\n // Sort by severity: errors first, then warnings, then info\n const sorted = [...issues].sort((a, b) => {\n const severityOrder: Record<Severity, number> = {\n error: 0,\n warning: 1,\n info: 2,\n };\n return severityOrder[a.severity]! - severityOrder[b.severity]!;\n });\n\n switch (format) {\n case \"json\":\n return JSON.stringify(sorted, null, 2);\n\n case \"minimal\":\n return sorted.map(renderMinimalIssue).join(\"\\n\");\n\n case \"pretty\":\n default: {\n const output: string[] = [];\n\n // Summary header\n const errorCount = issues.filter((i) => i.severity === \"error\").length;\n const warningCount = issues.filter(\n (i) => i.severity === \"warning\",\n ).length;\n const infoCount = issues.filter((i) => i.severity === \"info\").length;\n\n if (errorCount > 0) {\n output.push(\n p.red(\n p.bold(`Found ${errorCount} error${errorCount > 1 ? \"s\" : \"\"}`),\n ),\n );\n }\n if (warningCount > 0) {\n output.push(\n p.yellow(`${warningCount} warning${warningCount > 1 ? \"s\" : \"\"}`),\n );\n }\n if (infoCount > 0) {\n output.push(p.blue(`${infoCount} info`));\n }\n output.push(\"\");\n\n // Grouped issues\n output.push(renderGroupedIssues(sorted, showDebug));\n\n return output.join(\"\\n\");\n }\n }\n}\n\n// Render legacy error strings in DX-first format\nexport function renderLegacyError(\n error: string,\n showDebug: boolean = true,\n): string {\n const lines: string[] = [];\n\n // Extract debug info if present\n const debugMatch = error.match(/\\(debug: (.+)\\)$/);\n const debug = debugMatch ? debugMatch[1] : undefined;\n const mainError = debugMatch\n ? error.replace(/\\(debug: .+\\)$/, \"\").trim()\n : error;\n\n lines.push(p.red(p.bold(`✘ ${mainError.split(\"\\n\")[0]}`)));\n\n // Show fix if present in the error\n const fixMatch = mainError.match(/Fix:\\n((?:- .+\\n?)+)/);\n if (fixMatch) {\n lines.push(\"\");\n lines.push(p.green(\" Fix:\"));\n const fixLines = fixMatch[1]?.split(\"\\n\").filter(Boolean) ?? [];\n for (const line of fixLines) {\n lines.push(` ${line.replace(/^- /, \"\")}`);\n }\n }\n\n if (showDebug && debug) {\n lines.push(\"\");\n lines.push(p.dim(` (debug: ${debug})`));\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;AAAA,SAAS,UAAAA,SAAQ,OAAO,WAAW,YAAAC,iBAAgB;AACnD,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AAC9B,YAAYC,QAAO;AACnB,OAAO,QAAQ;;;ACJf,SAAS,QAAQ,UAAU,IAAI,eAAe;AAC9C,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,kBAAkB;;;ACF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,EAAE,WAAW,KAAK,CAAC;AAExC,UAAM,YAAY;AAAA,MAChB;AAAA,MACA,WAAW,2BAA2B,SAAS;AAAA,MAC/C,WAAU,oBAAI,KAAK,GAAE,YAAY;AAAA,MACjC;AAAA,IACF;AAEA,UAAM;AAAA,MACJA,MAAK,SAAS,YAAY;AAAA,MAC1B,KAAK,UAAU,WAAW,MAAM,CAAC;AAAA,MACjC;AAAA,IACF;AAEA,UAAM,eAAe,2BAA2B,SAAS;AACzD,IAAE,SAAM,GAAG,IAAI,IAAI,GAAG,MAAM,eAAe,CAAC,IAAI,GAAG,KAAK,YAAY,CAAC,EAAE;AAEvE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;","names":["access","readFile","join","p","join","access","readFile","hash"]}
@@ -1,92 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/commands/studio.ts
4
- import { defineCommand } from "citty";
5
- import * as p from "@clack/prompts";
6
- import pc from "picocolors";
7
- import { readFile, writeFile } from "fs/promises";
8
- import { join } from "path";
9
- import { randomBytes } from "crypto";
10
- import { SignJWT } from "jose";
11
- import open from "open";
12
- var LOGO = "\u{1F98B}";
13
- async function ensureSecretKey(cwd) {
14
- const envPath = join(cwd, ".env");
15
- try {
16
- const envContent2 = await readFile(envPath, "utf-8");
17
- const match = envContent2.match(/^KALP_SECRET_KEY=(.+)$/m);
18
- if (match && match[1]) {
19
- return { key: match[1].trim(), isNew: false };
20
- }
21
- } catch {
22
- }
23
- const secretKey = randomBytes(32).toString("hex");
24
- const envContent = `# Kalp Studio Authentication Secret
25
- KALP_SECRET_KEY=${secretKey}
26
- `;
27
- await writeFile(envPath, envContent, "utf-8");
28
- return { key: secretKey, isNew: true };
29
- }
30
- async function readWorkerUrl(cwd) {
31
- try {
32
- const statePath = join(cwd, ".kalp", "state.json");
33
- const content = await readFile(statePath, "utf-8");
34
- const state = JSON.parse(content);
35
- return state.workerUrl || null;
36
- } catch {
37
- return null;
38
- }
39
- }
40
- var studio_default = defineCommand({
41
- meta: { name: "studio", description: "Open Kalp Studio in browser" },
42
- args: {
43
- url: {
44
- type: "string",
45
- alias: "u",
46
- description: "Worker URL (overrides saved state)",
47
- required: false
48
- }
49
- },
50
- async run({ args }) {
51
- const cwd = process.cwd();
52
- p.intro(`${LOGO} ${pc.bold("kalp studio")}`);
53
- const s = p.spinner();
54
- s.start("Checking authentication secret");
55
- const { key: secretKey, isNew: isNewSecret } = await ensureSecretKey(cwd);
56
- s.stop("Authentication secret ready");
57
- if (isNewSecret) {
58
- p.log.warning(
59
- "No KALP_SECRET_KEY found. Generated a new one in .env"
60
- );
61
- p.note(
62
- "Please run 'kalp push' to sync the new secret with Cloudflare",
63
- "Action Required"
64
- );
65
- }
66
- const workerUrl = args.url || await readWorkerUrl(cwd);
67
- if (!workerUrl) {
68
- p.log.error(
69
- "No worker URL found. Run 'kalp push' first or use --url flag"
70
- );
71
- process.exit(1);
72
- }
73
- s.start("Generating authentication token");
74
- const secret = new TextEncoder().encode(secretKey);
75
- const token = await new SignJWT({
76
- sub: "cli-user",
77
- aud: "kalp-studio",
78
- iat: Date.now(),
79
- exp: Math.floor(Date.now() / 1e3) + 3600
80
- // 1 hour
81
- }).setProtectedHeader({ alg: "HS256" }).sign(secret);
82
- s.stop("Token generated");
83
- const studioUrl = `${workerUrl}/studio?token=${token}`;
84
- p.log.info(`Opening Studio at ${pc.cyan(studioUrl)}`);
85
- await open(studioUrl);
86
- p.outro(`${LOGO} ${pc.green("Studio opened")}`);
87
- }
88
- });
89
- export {
90
- studio_default as default
91
- };
92
- //# sourceMappingURL=studio-7LGUD42G.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/studio.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { SignJWT } from \"jose\";\nimport open from \"open\";\n\nconst LOGO = \"🦋\";\n\n/**\n * Generate KALP_SECRET_KEY if not exists.\n * Returns the key and whether it was newly created.\n */\nasync function ensureSecretKey(cwd: string): Promise<{ key: string, isNew: boolean }> {\n const envPath = join(cwd, \".env\");\n \n try {\n const envContent = await readFile(envPath, \"utf-8\");\n const match = envContent.match(/^KALP_SECRET_KEY=(.+)$/m);\n if (match && match[1]) {\n return { key: match[1].trim(), isNew: false };\n }\n } catch {\n // .env doesn't exist, create it\n }\n\n // Generate new secret\n const secretKey = randomBytes(32).toString(\"hex\");\n const envContent = `# Kalp Studio Authentication Secret\nKALP_SECRET_KEY=${secretKey}\n`;\n \n await writeFile(envPath, envContent, \"utf-8\");\n return { key: secretKey, isNew: true };\n}\n\n/**\n * Read worker URL from .kalp/state.json.\n */\nasync function readWorkerUrl(cwd: string): Promise<string | null> {\n try {\n const statePath = join(cwd, \".kalp\", \"state.json\");\n const content = await readFile(statePath, \"utf-8\");\n const state = JSON.parse(content);\n return state.workerUrl || null;\n } catch {\n return null;\n }\n}\n\nexport default defineCommand({\n meta: { name: \"studio\", description: \"Open Kalp Studio in browser\" },\n args: {\n url: {\n type: \"string\",\n alias: \"u\",\n description: \"Worker URL (overrides saved state)\",\n required: false,\n },\n },\n async run({ args }) {\n const cwd = process.cwd();\n \n p.intro(`${LOGO} ${pc.bold(\"kalp studio\")}`);\n\n // 1. Ensure KALP_SECRET_KEY exists\n const s = p.spinner();\n s.start(\"Checking authentication secret\");\n \n const { key: secretKey, isNew: isNewSecret } = await ensureSecretKey(cwd);\n \n s.stop(\"Authentication secret ready\");\n\n if (isNewSecret) {\n p.log.warning(\n \"No KALP_SECRET_KEY found. Generated a new one in .env\"\n );\n p.note(\n \"Please run 'kalp push' to sync the new secret with Cloudflare\",\n \"Action Required\"\n );\n }\n\n // 2. Get worker URL\n const workerUrl = args.url || (await readWorkerUrl(cwd));\n \n if (!workerUrl) {\n p.log.error(\n \"No worker URL found. Run 'kalp push' first or use --url flag\"\n );\n process.exit(1);\n }\n\n // 3. Generate JWT (1 hour expiry)\n s.start(\"Generating authentication token\");\n \n const secret = new TextEncoder().encode(secretKey);\n const token = await new SignJWT({\n sub: \"cli-user\",\n aud: \"kalp-studio\",\n iat: Date.now(),\n exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .sign(secret);\n \n s.stop(\"Token generated\");\n\n // 4. Open browser\n const studioUrl = `${workerUrl}/studio?token=${token}`;\n p.log.info(`Opening Studio at ${pc.cyan(studioUrl)}`);\n \n await open(studioUrl);\n \n p.outro(`${LOGO} ${pc.green(\"Studio opened\")}`);\n },\n});\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,YAAY,OAAO;AACnB,OAAO,QAAQ;AACf,SAAS,UAAU,iBAAiB;AACpC,SAAS,YAAY;AACrB,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,OAAO,UAAU;AAEjB,IAAM,OAAO;AAMb,eAAe,gBAAgB,KAAuD;AACpF,QAAM,UAAU,KAAK,KAAK,MAAM;AAEhC,MAAI;AACF,UAAMA,cAAa,MAAM,SAAS,SAAS,OAAO;AAClD,UAAM,QAAQA,YAAW,MAAM,yBAAyB;AACxD,QAAI,SAAS,MAAM,CAAC,GAAG;AACrB,aAAO,EAAE,KAAK,MAAM,CAAC,EAAE,KAAK,GAAG,OAAO,MAAM;AAAA,IAC9C;AAAA,EACF,QAAQ;AAAA,EAER;AAGA,QAAM,YAAY,YAAY,EAAE,EAAE,SAAS,KAAK;AAChD,QAAM,aAAa;AAAA,kBACH,SAAS;AAAA;AAGzB,QAAM,UAAU,SAAS,YAAY,OAAO;AAC5C,SAAO,EAAE,KAAK,WAAW,OAAO,KAAK;AACvC;AAKA,eAAe,cAAc,KAAqC;AAChE,MAAI;AACF,UAAM,YAAY,KAAK,KAAK,SAAS,YAAY;AACjD,UAAM,UAAU,MAAM,SAAS,WAAW,OAAO;AACjD,UAAM,QAAQ,KAAK,MAAM,OAAO;AAChC,WAAO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