plazbot-cli 0.3.7 → 0.4.1

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 (117) hide show
  1. package/README.md +38 -2
  2. package/dist/commands/auth/browser-login.js +121 -0
  3. package/dist/commands/auth/index.js +5 -1
  4. package/dist/commands/auth/login.js +1 -3
  5. package/dist/commands/auth/logout.js +4 -3
  6. package/dist/commands/auth/status.js +8 -5
  7. package/dist/commands/auth/workspace.js +73 -0
  8. package/dist/commands/whatsapp/connect-flow.js +137 -0
  9. package/dist/commands/whatsapp/connect.js +26 -160
  10. package/dist/commands/whatsapp/index.js +4 -0
  11. package/dist/commands/whatsapp/setup.js +242 -0
  12. package/dist/schemas/agent.config.schema.json +24 -0
  13. package/dist/studio/components/App.js +1 -1
  14. package/dist/studio/runOneShot.js +2 -2
  15. package/dist/studio/runRepl.js +1 -1
  16. package/dist/utils/agent-errors.js +2 -2
  17. package/dist/utils/banner.js +10 -9
  18. package/dist/utils/credentials.js +31 -3
  19. package/dist/utils/open-browser.js +17 -0
  20. package/package.json +14 -6
  21. package/.claude/settings.local.json +0 -19
  22. package/CLAUDE.md +0 -121
  23. package/agent.config.json +0 -21
  24. package/dist/studio/components/AgentPanel.js +0 -35
  25. package/dist/studio/render/json.js +0 -16
  26. package/dist/studio/whatsapp/api.js +0 -63
  27. package/dist/studio/whatsapp/polling.js +0 -77
  28. package/dist/studio/whatsapp/types.js +0 -31
  29. package/src/cli.ts +0 -57
  30. package/src/commands/agent/ai-config.ts +0 -164
  31. package/src/commands/agent/chat.ts +0 -225
  32. package/src/commands/agent/copy.ts +0 -46
  33. package/src/commands/agent/create.ts +0 -103
  34. package/src/commands/agent/delete.ts +0 -71
  35. package/src/commands/agent/enable-widget.ts +0 -67
  36. package/src/commands/agent/export.ts +0 -430
  37. package/src/commands/agent/files.ts +0 -171
  38. package/src/commands/agent/get.ts +0 -233
  39. package/src/commands/agent/index.ts +0 -55
  40. package/src/commands/agent/list.ts +0 -58
  41. package/src/commands/agent/monitor.ts +0 -375
  42. package/src/commands/agent/on-message.ts +0 -82
  43. package/src/commands/agent/set.ts +0 -149
  44. package/src/commands/agent/templates.ts +0 -892
  45. package/src/commands/agent/tools.ts +0 -168
  46. package/src/commands/agent/update.ts +0 -61
  47. package/src/commands/agent/validate.ts +0 -135
  48. package/src/commands/agent/wizard.ts +0 -756
  49. package/src/commands/auth/index.ts +0 -10
  50. package/src/commands/auth/login.ts +0 -72
  51. package/src/commands/auth/logout.ts +0 -28
  52. package/src/commands/auth/status.ts +0 -28
  53. package/src/commands/portal/add-agent.ts +0 -66
  54. package/src/commands/portal/add-link.ts +0 -47
  55. package/src/commands/portal/clear-links.ts +0 -33
  56. package/src/commands/portal/create.ts +0 -58
  57. package/src/commands/portal/delete.ts +0 -70
  58. package/src/commands/portal/get.ts +0 -77
  59. package/src/commands/portal/index.ts +0 -32
  60. package/src/commands/portal/list.ts +0 -79
  61. package/src/commands/portal/update.ts +0 -93
  62. package/src/commands/whatsapp/broadcast.ts +0 -110
  63. package/src/commands/whatsapp/channels.ts +0 -109
  64. package/src/commands/whatsapp/chat.ts +0 -85
  65. package/src/commands/whatsapp/connect.ts +0 -220
  66. package/src/commands/whatsapp/delete-webhook.ts +0 -43
  67. package/src/commands/whatsapp/index.ts +0 -37
  68. package/src/commands/whatsapp/register-webhook.ts +0 -47
  69. package/src/commands/whatsapp/send-template.ts +0 -94
  70. package/src/commands/whatsapp/send.ts +0 -55
  71. package/src/commands/whatsapp/widget.ts +0 -75
  72. package/src/commands/workers/deploy.ts +0 -156
  73. package/src/commands/workers/index.ts +0 -30
  74. package/src/commands/workers/list.ts +0 -105
  75. package/src/commands/workers/logs.ts +0 -99
  76. package/src/commands/workers/remove.ts +0 -103
  77. package/src/commands/workers/secret.ts +0 -191
  78. package/src/commands/workers/test.ts +0 -145
  79. package/src/schemas/agent.config.schema.json +0 -569
  80. package/src/studio/api/sseClient.ts +0 -91
  81. package/src/studio/api/studioApi.ts +0 -27
  82. package/src/studio/api/types.ts +0 -96
  83. package/src/studio/components/App.tsx +0 -274
  84. package/src/studio/components/ChatLog.tsx +0 -121
  85. package/src/studio/components/ConnectCard.tsx +0 -171
  86. package/src/studio/components/Footer.tsx +0 -38
  87. package/src/studio/components/Header.tsx +0 -39
  88. package/src/studio/components/Input.tsx +0 -176
  89. package/src/studio/components/Message.tsx +0 -87
  90. package/src/studio/components/Suggestions.tsx +0 -26
  91. package/src/studio/components/ToolCall.tsx +0 -58
  92. package/src/studio/connect/api.ts +0 -98
  93. package/src/studio/connect/polling.ts +0 -94
  94. package/src/studio/connect/types.ts +0 -141
  95. package/src/studio/index.ts +0 -58
  96. package/src/studio/render/markdown.ts +0 -93
  97. package/src/studio/render/steps.ts +0 -57
  98. package/src/studio/runOneShot.ts +0 -114
  99. package/src/studio/runRepl.tsx +0 -82
  100. package/src/studio/slash/handlers.ts +0 -226
  101. package/src/studio/slash/parser.ts +0 -41
  102. package/src/studio/slash/registry.ts +0 -54
  103. package/src/studio/state/store.ts +0 -279
  104. package/src/types/agent.ts +0 -63
  105. package/src/types/auth.ts +0 -9
  106. package/src/types/common.ts +0 -10
  107. package/src/types/message.ts +0 -34
  108. package/src/types/portal.ts +0 -56
  109. package/src/types/workers.ts +0 -86
  110. package/src/utils/agent-errors.ts +0 -67
  111. package/src/utils/api.ts +0 -35
  112. package/src/utils/banner.ts +0 -99
  113. package/src/utils/credentials.ts +0 -38
  114. package/src/utils/help.ts +0 -51
  115. package/src/utils/logger.ts +0 -40
  116. package/src/utils/ui.ts +0 -109
  117. package/tsconfig.json +0 -18
@@ -1,226 +0,0 @@
1
- import { writeFile } from 'node:fs/promises';
2
- import { resolve } from 'node:path';
3
- import { homedir } from 'node:os';
4
- import { slashRegistry } from './registry.js';
5
- import type { SlashResult } from './registry.js';
6
- import { useStudioStore } from '../state/store.js';
7
-
8
- function expandTilde(p: string): string {
9
- if (p === '~') return homedir();
10
- if (p.startsWith('~/')) return resolve(homedir(), p.slice(2));
11
- return p;
12
- }
13
-
14
- function slugify(s: string): string {
15
- return s
16
- .normalize('NFKD')
17
- .replace(/[\u0300-\u036f]/g, '')
18
- .replace(/[^a-zA-Z0-9-_]+/g, '-')
19
- .replace(/^-+|-+$/g, '')
20
- .toLowerCase() || 'agent';
21
- }
22
-
23
- const CATEGORY_LABELS: Record<NonNullable<import('./registry.js').SlashCategory>, string> = {
24
- general: 'General',
25
- agent: 'Agent',
26
- session: 'Session',
27
- };
28
- const CATEGORY_ORDER: Array<NonNullable<import('./registry.js').SlashCategory>> = [
29
- 'general',
30
- 'agent',
31
- 'session',
32
- ];
33
-
34
- slashRegistry.register({
35
- name: 'help',
36
- aliases: ['?'],
37
- description: 'Show this help with every available command',
38
- category: 'general',
39
- handler(): SlashResult {
40
- const all = slashRegistry.list();
41
- const grouped = new Map<string, typeof all>();
42
- for (const cmd of all) {
43
- const cat = cmd.category ?? 'general';
44
- const arr = grouped.get(cat) ?? [];
45
- arr.push(cmd);
46
- grouped.set(cat, arr);
47
- }
48
-
49
- const lines: string[] = ['**Plazbot Studio — slash commands**', ''];
50
- lines.push('Type plain text to chat with the assistant.');
51
- lines.push('Slash commands run locally or send a templated prompt to the model.');
52
- lines.push('');
53
-
54
- for (const cat of CATEGORY_ORDER) {
55
- const items = grouped.get(cat);
56
- if (!items || items.length === 0) continue;
57
- lines.push(`**${CATEGORY_LABELS[cat]}**`);
58
- for (const cmd of items) {
59
- const usage = cmd.usage ?? `/${cmd.name}`;
60
- const aliasPart = cmd.aliases?.length
61
- ? ` _(alias: ${cmd.aliases.map((a) => '/' + a).join(', ')})_`
62
- : '';
63
- lines.push(`- \`${usage}\`${aliasPart} — ${cmd.description}`);
64
- }
65
- lines.push('');
66
- }
67
-
68
- lines.push('**Keyboard shortcuts**');
69
- lines.push('- `Esc` — cancel the current stream');
70
- lines.push('- `Ctrl+C` — exit Studio');
71
- lines.push('');
72
- lines.push('**Tip:** you can also speak naturally — e.g. _"list my agents"_, _"create a sales agent for WhatsApp"_ or _"connect this agent to WhatsApp Business"_.');
73
-
74
- useStudioStore.getState().pushSyntheticAssistant(lines.join('\n'));
75
- return { kind: 'noop' };
76
- },
77
- });
78
-
79
- slashRegistry.register({
80
- name: 'clear',
81
- aliases: ['cls'],
82
- description: 'Clear the conversation (keeps the loaded agent and token usage)',
83
- category: 'session',
84
- handler(): SlashResult {
85
- useStudioStore.getState().clearMessages();
86
- return { kind: 'noop' };
87
- },
88
- });
89
-
90
- slashRegistry.register({
91
- name: 'reset',
92
- description: 'Full reset: clears messages, loaded agent and token usage',
93
- category: 'session',
94
- handler(): SlashResult {
95
- useStudioStore.getState().reset();
96
- return { kind: 'noop' };
97
- },
98
- });
99
-
100
- const COMPACT_PROMPT = [
101
- 'You are about to compact this conversation.',
102
- '',
103
- 'Produce a concise but complete summary of everything we have discussed so far, in Markdown:',
104
- '- Goal / task the user is working on.',
105
- '- Key decisions and constraints.',
106
- '- Current agent configuration state (if any) and its `id`.',
107
- '- Pending items or next steps.',
108
- '',
109
- 'Reply with ONLY the summary content (no preamble, no farewell).',
110
- 'After this message, the previous history will be replaced by your summary so we can keep working with less context.',
111
- ].join('\n');
112
-
113
- slashRegistry.register({
114
- name: 'compact',
115
- description: 'Summarize the conversation and replace history with that summary',
116
- category: 'session',
117
- handler(): SlashResult {
118
- const store = useStudioStore.getState();
119
- if (store.messages.length === 0) {
120
- store.pushSyntheticAssistant('Nothing to compact yet.', { error: true });
121
- return { kind: 'noop' };
122
- }
123
- store.setPendingCompact(true);
124
- return { kind: 'message', content: COMPACT_PROMPT };
125
- },
126
- });
127
-
128
- slashRegistry.register({
129
- name: 'quit',
130
- aliases: ['exit', 'q'],
131
- description: 'Exit Studio',
132
- category: 'general',
133
- handler(_parsed, ctx): SlashResult {
134
- ctx.exit();
135
- return { kind: 'exit' };
136
- },
137
- });
138
-
139
- slashRegistry.register({
140
- name: 'agents',
141
- description: 'List the agents in the current workspace',
142
- category: 'agent',
143
- handler(): SlashResult {
144
- return { kind: 'message', content: 'List all agents in my workspace.' };
145
- },
146
- });
147
-
148
- slashRegistry.register({
149
- name: 'load',
150
- description: 'Load an agent by id and show its current configuration',
151
- category: 'agent',
152
- usage: '/load <agentId>',
153
- handler(parsed): SlashResult {
154
- const id = parsed.args[0];
155
- if (!id) {
156
- useStudioStore.getState().pushSyntheticAssistant('Usage: `/load <agentId>`', { error: true });
157
- return { kind: 'noop' };
158
- }
159
- useStudioStore.getState().setAgentId(id);
160
- return { kind: 'message', content: `Load the agent with id "${id}" and show me its current configuration.` };
161
- },
162
- });
163
-
164
- slashRegistry.register({
165
- name: 'save',
166
- description: 'Save the currently loaded agent configuration to the backend',
167
- category: 'agent',
168
- handler(): SlashResult {
169
- const { agentConfig } = useStudioStore.getState();
170
- if (!agentConfig) {
171
- useStudioStore.getState().pushSyntheticAssistant(
172
- 'No agent configuration loaded. Create one first or use `/load <id>`.',
173
- { error: true },
174
- );
175
- return { kind: 'noop' };
176
- }
177
- return { kind: 'message', content: 'Save this agent with its current configuration.' };
178
- },
179
- });
180
-
181
- slashRegistry.register({
182
- name: 'diagnose',
183
- description: 'Run diagnostics on the current agent and report any issues found',
184
- category: 'agent',
185
- handler(): SlashResult {
186
- return { kind: 'message', content: 'Diagnose this agent and report any issues you find.' };
187
- },
188
- });
189
-
190
- slashRegistry.register({
191
- name: 'export',
192
- aliases: ['download'],
193
- description: 'Export the current agent configuration to a JSON file on disk',
194
- category: 'agent',
195
- usage: '/export [path]',
196
- async handler(parsed): Promise<SlashResult> {
197
- const store = useStudioStore.getState();
198
- const { agentConfig } = store;
199
-
200
- if (!agentConfig) {
201
- store.pushSyntheticAssistant(
202
- 'No hay agente cargado. Crea o carga uno antes con `/load <id>`.',
203
- { error: true },
204
- );
205
- return { kind: 'noop' };
206
- }
207
-
208
- const cfg = agentConfig as any;
209
- const baseName = slugify(cfg?.name ?? store.agentId ?? 'agent');
210
- const defaultPath = `./${baseName}.json`;
211
- const targetArg = parsed.args[0] ?? defaultPath;
212
- const targetPath = resolve(process.cwd(), expandTilde(targetArg));
213
-
214
- try {
215
- await writeFile(targetPath, JSON.stringify(agentConfig, null, 2), 'utf-8');
216
- store.pushSyntheticAssistant(
217
- `Agente exportado a \`${targetPath}\`.\n\nValídalo con: \`plazbot agent validate ${targetPath}\``,
218
- );
219
- } catch (err) {
220
- const message = err instanceof Error ? err.message : String(err);
221
- store.pushSyntheticAssistant(`No pude escribir el archivo: ${message}`, { error: true });
222
- }
223
- return { kind: 'noop' };
224
- },
225
- });
226
-
@@ -1,41 +0,0 @@
1
- export interface ParsedSlash {
2
- name: string;
3
- args: string[];
4
- raw: string;
5
- }
6
-
7
- /**
8
- * Parsea un input crudo del usuario.
9
- * - Si empieza con `/`, retorna { name, args, raw } para ejecutar como slash command.
10
- * - Si no, retorna null (mensaje normal al backend).
11
- */
12
- export function parseSlash(input: string): ParsedSlash | null {
13
- const trimmed = input.trim();
14
- if (!trimmed.startsWith('/')) return null;
15
- const without = trimmed.slice(1);
16
- if (!without) return { name: '', args: [], raw: trimmed };
17
- // Split por espacios respetando comillas básicas.
18
- const tokens = tokenize(without);
19
- const [name, ...args] = tokens;
20
- return { name: (name ?? '').toLowerCase(), args, raw: trimmed };
21
- }
22
-
23
- function tokenize(s: string): string[] {
24
- const out: string[] = [];
25
- let cur = '';
26
- let quote: '"' | "'" | null = null;
27
- for (const ch of s) {
28
- if (quote) {
29
- if (ch === quote) { quote = null; continue; }
30
- cur += ch;
31
- } else if (ch === '"' || ch === "'") {
32
- quote = ch;
33
- } else if (/\s/.test(ch)) {
34
- if (cur) { out.push(cur); cur = ''; }
35
- } else {
36
- cur += ch;
37
- }
38
- }
39
- if (cur) out.push(cur);
40
- return out;
41
- }
@@ -1,54 +0,0 @@
1
- import type { ParsedSlash } from './parser.js';
2
-
3
- /**
4
- * Resultado de un slash handler:
5
- * - { kind: 'message', content } -> enviar `content` como mensaje normal al backend.
6
- * - { kind: 'noop' } -> ya consumido por el handler (sin tráfico).
7
- * - { kind: 'exit' } -> el REPL debe cerrarse.
8
- * - { kind: 'error', content } -> mostrar mensaje de error sintético.
9
- */
10
- export type SlashResult =
11
- | { kind: 'message'; content: string }
12
- | { kind: 'noop' }
13
- | { kind: 'exit' }
14
- | { kind: 'error'; content: string };
15
-
16
- export interface SlashHandlerContext {
17
- exit: () => void;
18
- }
19
-
20
- export type SlashHandler = (parsed: ParsedSlash, ctx: SlashHandlerContext) => SlashResult | Promise<SlashResult>;
21
-
22
- export type SlashCategory = 'general' | 'agent' | 'session';
23
-
24
- export interface SlashSpec {
25
- name: string;
26
- aliases?: string[];
27
- description: string;
28
- /** Group used by `/help` to render commands by section. Defaults to 'general'. */
29
- category?: SlashCategory;
30
- /** Optional usage line (e.g. `/load <agentId>`). Falls back to `/<name>`. */
31
- usage?: string;
32
- handler: SlashHandler;
33
- }
34
-
35
- class SlashRegistry {
36
- private map = new Map<string, SlashSpec>();
37
- private order: SlashSpec[] = [];
38
-
39
- register(spec: SlashSpec): void {
40
- this.order.push(spec);
41
- this.map.set(spec.name, spec);
42
- spec.aliases?.forEach((a) => this.map.set(a, spec));
43
- }
44
-
45
- get(name: string): SlashSpec | undefined {
46
- return this.map.get(name);
47
- }
48
-
49
- list(): SlashSpec[] {
50
- return this.order.slice();
51
- }
52
- }
53
-
54
- export const slashRegistry = new SlashRegistry();
@@ -1,279 +0,0 @@
1
- import { create } from 'zustand';
2
- import { randomUUID } from 'node:crypto';
3
- import type {
4
- ChannelLinkData,
5
- ConnectChannel,
6
- ConnectState,
7
- ConnectStatus,
8
- } from '../connect/types.js';
9
-
10
- export type Role = 'user' | 'assistant' | 'system';
11
-
12
- export interface ChatMessage {
13
- id: string;
14
- role: Role;
15
- content: string;
16
- /** Mensaje aún siendo recibido por streaming. */
17
- streaming?: boolean;
18
- /** Mensaje sintético generado por slash commands (no enviado al backend). */
19
- synthetic?: boolean;
20
- /** Marca de error visual. */
21
- error?: boolean;
22
- }
23
-
24
- export type StepStatus = 'running' | 'success' | 'error';
25
-
26
- export interface ToolStep {
27
- id: string;
28
- toolName: string;
29
- status: StepStatus;
30
- /** Anclamos el step debajo del mensaje del assistant que lo originó. */
31
- afterMessageId: string;
32
- result?: unknown;
33
- errorMessage?: string;
34
- }
35
-
36
- export interface StudioState {
37
- messages: ChatMessage[];
38
- steps: ToolStep[];
39
- agentConfig: unknown | null;
40
- agentId: string | null;
41
- usage: { inputTokens: number; outputTokens: number };
42
- streaming: boolean;
43
- abortController: AbortController | null;
44
- /** True mientras se está corriendo el flujo de /compact (el próximo assistant
45
- * reemplazará todo el historial cuando termine). */
46
- pendingCompact: boolean;
47
-
48
- pushUserMessage(content: string): string;
49
- pushSyntheticAssistant(content: string, opts?: { error?: boolean }): string;
50
- startAssistantMessage(): string;
51
- appendAssistantText(id: string, delta: string): void;
52
- finishAssistantMessage(id: string): void;
53
-
54
- startStep(toolName: string, afterMessageId: string): string;
55
- resolveLastStep(toolName: string, status: StepStatus, result?: unknown, errorMessage?: string): void;
56
- failAllRunningSteps(message?: string): void;
57
-
58
- setAgentConfig(cfg: unknown): void;
59
- setAgentId(id: string | null): void;
60
- addUsage(inT: number, outT: number): void;
61
-
62
- setStreaming(s: boolean): void;
63
- setAbortController(ctrl: AbortController | null): void;
64
- abortStream(): void;
65
-
66
- /** Channel connection card state (whatsapp/instagram/messenger; one active at a time). */
67
- connectCard: ConnectState | null;
68
- startConnectCard(channel: ConnectChannel, linkData: ChannelLinkData, anchorMessageId: string): string;
69
- updateConnectCard(patch: Partial<ConnectState>): void;
70
- setConnectStatus(status: ConnectStatus, extra?: Partial<ConnectState>): void;
71
- clearConnectCard(): void;
72
-
73
- /** Borra mensajes/steps/connectCard pero MANTIENE agente cargado, usage y config. */
74
- clearMessages(): void;
75
- /** Marca que el próximo stream completo debe reemplazar el historial. */
76
- setPendingCompact(v: boolean): void;
77
- /** Reemplaza todo el historial por el contenido del mensaje `id` (el resumen). */
78
- compactInto(id: string): void;
79
- /** Reset total (mensajes + agente + usage). */
80
- reset(): void;
81
- }
82
-
83
- function uid(): string {
84
- // randomUUID está disponible en Node >=14.17 con crypto. Fallback simple.
85
- try { return randomUUID(); } catch { return Math.random().toString(36).slice(2); }
86
- }
87
-
88
- export const useStudioStore = create<StudioState>((set, get) => ({
89
- messages: [],
90
- steps: [],
91
- agentConfig: null,
92
- agentId: null,
93
- usage: { inputTokens: 0, outputTokens: 0 },
94
- streaming: false,
95
- abortController: null,
96
- connectCard: null,
97
- pendingCompact: false,
98
-
99
- pushUserMessage(content) {
100
- const id = uid();
101
- set((s) => ({ messages: [...s.messages, { id, role: 'user', content }] }));
102
- return id;
103
- },
104
-
105
- pushSyntheticAssistant(content, opts) {
106
- const id = uid();
107
- set((s) => ({
108
- messages: [...s.messages, { id, role: 'assistant', content, synthetic: true, error: opts?.error }],
109
- }));
110
- return id;
111
- },
112
-
113
- startAssistantMessage() {
114
- const id = uid();
115
- set((s) => ({ messages: [...s.messages, { id, role: 'assistant', content: '', streaming: true }] }));
116
- return id;
117
- },
118
-
119
- appendAssistantText(id, delta) {
120
- set((s) => ({
121
- messages: s.messages.map((m) => (m.id === id ? { ...m, content: m.content + delta } : m)),
122
- }));
123
- },
124
-
125
- finishAssistantMessage(id) {
126
- set((s) => ({
127
- messages: s.messages.map((m) => (m.id === id ? { ...m, streaming: false } : m)),
128
- }));
129
- },
130
-
131
- startStep(toolName, afterMessageId) {
132
- const id = uid();
133
- set((s) => ({ steps: [...s.steps, { id, toolName, status: 'running', afterMessageId }] }));
134
- return id;
135
- },
136
-
137
- resolveLastStep(toolName, status, result, errorMessage) {
138
- set((s) => {
139
- const idx = [...s.steps].reverse().findIndex((x) => x.toolName === toolName && x.status === 'running');
140
- if (idx === -1) return {};
141
- const real = s.steps.length - 1 - idx;
142
- const updated = [...s.steps];
143
- updated[real] = { ...updated[real], status, result, errorMessage };
144
- return { steps: updated };
145
- });
146
- },
147
-
148
- failAllRunningSteps(message) {
149
- set((s) => ({
150
- steps: s.steps.map((x) =>
151
- x.status === 'running' ? { ...x, status: 'error', errorMessage: message ?? 'Cancelado' } : x,
152
- ),
153
- }));
154
- },
155
-
156
- setAgentConfig(cfg) {
157
- set({ agentConfig: cfg });
158
- },
159
-
160
- setAgentId(id) {
161
- set({ agentId: id });
162
- },
163
-
164
- addUsage(inT, outT) {
165
- set((s) => ({
166
- usage: {
167
- inputTokens: s.usage.inputTokens + (inT || 0),
168
- outputTokens: s.usage.outputTokens + (outT || 0),
169
- },
170
- }));
171
- },
172
-
173
- setStreaming(streaming) {
174
- set({ streaming });
175
- },
176
-
177
- setAbortController(abortController) {
178
- set({ abortController });
179
- },
180
-
181
- abortStream() {
182
- const ctrl = get().abortController;
183
- if (ctrl && !ctrl.signal.aborted) ctrl.abort();
184
- },
185
-
186
- startConnectCard(channel, linkData, anchorMessageId) {
187
- const id = uid();
188
- set({
189
- connectCard: {
190
- id,
191
- channel,
192
- linkData,
193
- status: 'waiting',
194
- anchorMessageId,
195
- attempt: 0,
196
- },
197
- });
198
- return id;
199
- },
200
-
201
- updateConnectCard(patch) {
202
- set((s) => (s.connectCard ? { connectCard: { ...s.connectCard, ...patch } } : {}));
203
- },
204
-
205
- setConnectStatus(status, extra) {
206
- set((s) => (s.connectCard ? { connectCard: { ...s.connectCard, status, ...(extra ?? {}) } } : {}));
207
- },
208
-
209
- clearConnectCard() {
210
- set({ connectCard: null });
211
- },
212
-
213
- clearMessages() {
214
- const ctrl = get().abortController;
215
- if (ctrl && !ctrl.signal.aborted) ctrl.abort();
216
- set({
217
- messages: [],
218
- steps: [],
219
- streaming: false,
220
- abortController: null,
221
- connectCard: null,
222
- pendingCompact: false,
223
- // agentConfig, agentId, usage se mantienen para seguir trabajando.
224
- });
225
- },
226
-
227
- setPendingCompact(v) {
228
- set({ pendingCompact: v });
229
- },
230
-
231
- compactInto(id) {
232
- set((s) => {
233
- const summary = s.messages.find((m) => m.id === id);
234
- if (!summary || !summary.content.trim()) {
235
- return { pendingCompact: false };
236
- }
237
- const newId = uid();
238
- return {
239
- messages: [
240
- {
241
- id: newId,
242
- role: 'assistant',
243
- content: summary.content,
244
- },
245
- ],
246
- steps: [],
247
- connectCard: null,
248
- pendingCompact: false,
249
- };
250
- });
251
- },
252
-
253
- reset() {
254
- const ctrl = get().abortController;
255
- if (ctrl && !ctrl.signal.aborted) ctrl.abort();
256
- set({
257
- messages: [],
258
- steps: [],
259
- agentConfig: null,
260
- agentId: null,
261
- usage: { inputTokens: 0, outputTokens: 0 },
262
- streaming: false,
263
- abortController: null,
264
- connectCard: null,
265
- pendingCompact: false,
266
- });
267
- },
268
- }));
269
-
270
- /**
271
- * Construye el array `messages` que se envía al backend a partir del estado.
272
- * Filtra mensajes sintéticos (synthetic === true) y los aún en streaming vacíos.
273
- */
274
- export function selectBackendMessages(): { role: 'user' | 'assistant'; content: string }[] {
275
- const { messages } = useStudioStore.getState();
276
- return messages
277
- .filter((m) => !m.synthetic && (m.role === 'user' || m.role === 'assistant') && m.content.trim().length > 0)
278
- .map((m) => ({ role: m.role as 'user' | 'assistant', content: m.content }));
279
- }
@@ -1,63 +0,0 @@
1
- import { BaseCommandOptions } from './common.js';
2
-
3
- export interface AgentCommandOptions {
4
- dev?: boolean;
5
- }
6
-
7
- export interface ChatOptions extends BaseCommandOptions {
8
- agentId: string;
9
- sessionId?: string;
10
- multipleAnswers?: boolean;
11
- }
12
-
13
- export interface OnMessageOptions extends BaseCommandOptions {
14
- agentId: string;
15
- question: string;
16
- sessionId?: string;
17
- multipleAnswers?: boolean;
18
- }
19
-
20
- export interface EnableWidgetOptions extends AgentCommandOptions {
21
- disable?: boolean;
22
- }
23
-
24
- export interface ListAgentsOptions extends BaseCommandOptions {
25
- }
26
-
27
- export interface AgentListItem {
28
- id: string;
29
- name: string;
30
- enable: boolean;
31
- description: string;
32
- createdAt: string;
33
- }
34
-
35
- export interface ChatMessage {
36
- timestamp: string;
37
- role: string;
38
- content: string;
39
- metadata?: Record<string, any>;
40
- source?: string;
41
- }
42
-
43
- export interface ChatHistoryParams {
44
- id: string;
45
- limit: number;
46
- from?: string;
47
- to?: string;
48
- }
49
-
50
- export interface ChatHistoryResponse {
51
- messages: ChatMessage[];
52
- success: boolean;
53
- }
54
-
55
- export interface AgentSource {
56
- title?: string;
57
- url?: string;
58
- }
59
-
60
- export interface AgentResponse {
61
- answer: string;
62
- sources?: AgentSource[];
63
- }
package/src/types/auth.ts DELETED
@@ -1,9 +0,0 @@
1
- import { BaseCommandOptions } from './common.js';
2
-
3
- export interface LoginOptions extends BaseCommandOptions {
4
- email?: string;
5
- apiKey: string;
6
- workspace: string;
7
- zone: "LA" | "EU";
8
- userId?: string;
9
- }
@@ -1,10 +0,0 @@
1
- export interface BaseCommandOptions {
2
- dev?: boolean;
3
- }
4
-
5
- export interface SDKOptions {
6
- workspaceId: string;
7
- apiKey: string;
8
- zone: "LA" | "EU";
9
- customUrl?: string;
10
- }