@laburen/delta-cli 0.2.0-canary.13 → 0.2.0-canary.20

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 (65) hide show
  1. package/dist/commands/agent-follow-ups/body.d.ts +20 -0
  2. package/dist/commands/agent-follow-ups/body.js +31 -0
  3. package/dist/commands/agent-follow-ups/body.js.map +1 -0
  4. package/dist/commands/agent-follow-ups.d.ts +10 -0
  5. package/dist/commands/agent-follow-ups.js +129 -0
  6. package/dist/commands/agent-follow-ups.js.map +1 -0
  7. package/dist/commands/agent-run/body.d.ts +2 -0
  8. package/dist/commands/agent-run/body.js +2 -0
  9. package/dist/commands/agent-run/body.js.map +1 -1
  10. package/dist/commands/agent-run/render.d.ts +26 -3
  11. package/dist/commands/agent-run/render.js +47 -6
  12. package/dist/commands/agent-run/render.js.map +1 -1
  13. package/dist/commands/agent-run.d.ts +3 -1
  14. package/dist/commands/agent-run.js +145 -31
  15. package/dist/commands/agent-run.js.map +1 -1
  16. package/dist/commands/agent-tools/shared.d.ts +176 -0
  17. package/dist/commands/agent-tools/shared.js +4 -1
  18. package/dist/commands/agent-tools/shared.js.map +1 -1
  19. package/dist/commands/config-sources.d.ts +3 -1
  20. package/dist/commands/config-sources.js +6 -0
  21. package/dist/commands/config-sources.js.map +1 -1
  22. package/dist/commands/config-wizard.js +21 -20
  23. package/dist/commands/config-wizard.js.map +1 -1
  24. package/dist/commands/wizards.d.ts +1 -1
  25. package/dist/commands/wizards.js +9 -1
  26. package/dist/commands/wizards.js.map +1 -1
  27. package/dist/errors.d.ts +4 -1
  28. package/dist/errors.js +517 -44
  29. package/dist/errors.js.map +1 -1
  30. package/dist/generated/commands.d.ts +9 -1
  31. package/dist/generated/commands.js +17 -11
  32. package/dist/generated/commands.js.map +1 -1
  33. package/dist/generated/schemas.js +15 -12
  34. package/dist/generated/schemas.js.map +1 -1
  35. package/dist/invocation.d.ts +30 -0
  36. package/dist/invocation.js +130 -33
  37. package/dist/invocation.js.map +1 -1
  38. package/dist/operations/file-input.d.ts +5 -0
  39. package/dist/operations/file-input.js +67 -0
  40. package/dist/operations/file-input.js.map +1 -0
  41. package/dist/operations/params.d.ts +3 -1
  42. package/dist/operations/params.js +35 -6
  43. package/dist/operations/params.js.map +1 -1
  44. package/dist/operations/register.d.ts +4 -0
  45. package/dist/operations/register.js +67 -7
  46. package/dist/operations/register.js.map +1 -1
  47. package/dist/operations/run-operation.js +4 -2
  48. package/dist/operations/run-operation.js.map +1 -1
  49. package/dist/operations/skeleton.js +13 -5
  50. package/dist/operations/skeleton.js.map +1 -1
  51. package/dist/operations/tables.js +11 -2
  52. package/dist/operations/tables.js.map +1 -1
  53. package/dist/output.d.ts +2 -0
  54. package/dist/output.js +30 -5
  55. package/dist/output.js.map +1 -1
  56. package/dist/pickers.d.ts +4 -2
  57. package/dist/pickers.js +29 -15
  58. package/dist/pickers.js.map +1 -1
  59. package/dist/program.js +13 -24
  60. package/dist/program.js.map +1 -1
  61. package/docs/SKILL.md +20 -13
  62. package/docs/references/auth-and-organizations.md +2 -0
  63. package/docs/references/commands.md +149 -22
  64. package/docs/references/output-and-errors.md +40 -16
  65. package/package.json +2 -2
package/dist/errors.js CHANGED
@@ -1,24 +1,46 @@
1
1
  import { isLaburenApiError, isLaburenConnectionError, isLaburenOAuthError, isLaburenTimeoutError, } from "@laburen/delta-sdk/platform";
2
2
  import { CommanderError } from "commander";
3
3
  import { OPERATION_COMMANDS } from "./generated/commands.js";
4
- import { commandText, redactSecrets, shellQuote, VALUE_PLACEHOLDER, withoutOption, } from "./invocation.js";
4
+ import { commandText, flagsEnd, redactSecrets, shellQuote, VALUE_PLACEHOLDER, withoutOption, } from "./invocation.js";
5
+ /**
6
+ * Junta los `next` que tienen el mismo comando literal en uno solo, en el lugar del primero: dos `next` iguales no dicen cuál
7
+ * elegir. Pasa cuando dos caminos distintos dan el mismo comando (un `--data` de un archivo, o escrito en la línea, que sale como
8
+ * `<value>`); el `when` lista cada opción.
9
+ */
10
+ function mergeSameCommand(steps) {
11
+ const merged = [];
12
+ for (const step of steps) {
13
+ const same = merged.findIndex((m) => m.command === step.command);
14
+ if (same === -1) {
15
+ merged.push(step);
16
+ continue;
17
+ }
18
+ const group = steps.filter((s) => s.command === step.command);
19
+ merged[same] = {
20
+ ...merged[same],
21
+ when: `the same command covers these options: ${group.map((s, i) => `(${i + 1}) ${s.when}`).join("; ")}`,
22
+ };
23
+ }
24
+ return merged;
25
+ }
5
26
  /** Error de la CLI con su `reason` estable, el código de salida (1 API/red, 2 mal uso) y los pasos para arreglarlo. */
6
27
  export class CliError extends Error {
7
28
  reason;
8
29
  exitCode;
9
- next;
10
30
  requestId;
11
31
  issues;
12
32
  details;
13
33
  userActionRequired;
14
34
  choices;
35
+ /** Los pasos para arreglarlo; nunca dos con el mismo comando (ver `mergeSameCommand`). */
36
+ next;
15
37
  constructor(reason, message, exitCode, next = [], requestId, extra = {}) {
16
38
  super(message);
17
39
  this.reason = reason;
18
40
  this.exitCode = exitCode;
19
- this.next = next;
20
41
  this.requestId = requestId;
21
42
  this.name = "CliError";
43
+ this.next = mergeSameCommand(next);
22
44
  this.issues = extra.issues ?? [];
23
45
  this.details = extra.details ?? {};
24
46
  this.userActionRequired = extra.userActionRequired ?? false;
@@ -40,6 +62,7 @@ const NOT_FOUND_LIST = {
40
62
  mcp_connection_version_not_found: ["mcp", "connections", "versions", "list", "<connection_id>"],
41
63
  token_not_found: ["tokens", "list"],
42
64
  widget_not_found: ["agents", "widgets", "list", "<agent_id>"],
65
+ decision_not_found: ["decisions", "list"],
43
66
  };
44
67
  /** Reemplaza cada `<nombre>` por el id que vino en el comando; si no vino, queda el marcador. */
45
68
  function fillIds(parts, ids = {}) {
@@ -54,10 +77,9 @@ function fillIds(parts, ids = {}) {
54
77
  }
55
78
  /** El valor de una opción (`--name x` o `--name=x`) en los argumentos que escribió la persona. */
56
79
  function optionValue(args = [], flag) {
57
- for (let i = 0; i < args.length; i++) {
80
+ const end = flagsEnd(args);
81
+ for (let i = 0; i < end; i++) {
58
82
  const arg = args[i];
59
- if (arg === "--")
60
- return undefined;
61
83
  if (arg === flag)
62
84
  return args[i + 1];
63
85
  if (arg.startsWith(`${flag}=`))
@@ -65,6 +87,11 @@ function optionValue(args = [], flag) {
65
87
  }
66
88
  return undefined;
67
89
  }
90
+ /** `details.reason` del choque entre la tool `thinking` y un modelo que razona. */
91
+ const THINKING_TOOL_CONFLICT = "thinking_tool_conflict";
92
+ /** Cómo pedir un modelo con una capacidad en `models list`: la tabla dice `yes`/`no` y el `--json` `true`/`false` (en `capabilities`). */
93
+ const EVALS_MODEL = "a model with EVALS yes in `models list` (`capabilities.evals` true with --json)";
94
+ const THINKING_TOOL_MODEL = "a model with THINKING TOOL yes in `models list` (`capabilities.thinking_tool` true with --json)";
68
95
  /** Los campos de `details.field` que se arreglan eligiendo otro modelo o nivel de reasoning de los que ofrece la API. */
69
96
  const MODEL_FIELDS = new Set([
70
97
  "model",
@@ -81,13 +108,152 @@ function agentVersionsOf(details) {
81
108
  typeof v.agent_id === "string" &&
82
109
  typeof v.version_id === "string");
83
110
  }
111
+ const ENVIRONMENT_FIELD = { flag: "--environment", path: ["environment"] };
112
+ const THREAD_FIELD = { flag: "--thread", path: ["memory", "thread"] };
113
+ /** En `agents follow-ups run` el thread va en la raíz del body, no en `memory`. */
114
+ const FOLLOW_UP_THREAD_FIELD = { flag: "--thread", path: ["thread"] };
115
+ const RESOURCE_FIELD = { flag: "--resource", path: ["memory", "resource"] };
116
+ const CHANNEL_FIELD = { flag: "--channel", path: ["channel"] };
117
+ const MODEL_FIELD = { flag: "--model", path: ["model"] };
118
+ const REASONING_FIELD = {
119
+ flag: "--reasoning",
120
+ path: ["model_settings", "reasoning"],
121
+ };
122
+ const WRITE_FIELDS = [
123
+ MODEL_FIELD,
124
+ { flag: "--instructions", path: ["instructions"] },
125
+ REASONING_FIELD,
126
+ { flag: "--max-steps", path: ["max_steps"] },
127
+ ];
128
+ /** El `--data` en línea como objeto; `undefined` si no hay `--data`, y `"opaque"` si es un archivo, stdin o no se lee (no se puede mirar adentro). */
129
+ function inlineData(args = []) {
130
+ const raw = optionValue(args, "--data");
131
+ if (raw === undefined)
132
+ return undefined;
133
+ try {
134
+ const parsed = JSON.parse(raw);
135
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
136
+ ? parsed
137
+ : "opaque";
138
+ }
139
+ catch {
140
+ return "opaque";
141
+ }
142
+ }
143
+ function valueAt(obj, path) {
144
+ let cur = obj;
145
+ for (const key of path) {
146
+ if (typeof cur !== "object" || cur === null)
147
+ return undefined;
148
+ cur = cur[key];
149
+ }
150
+ return cur;
151
+ }
152
+ /** Si el pedido lleva el campo, en el flag o dentro de `--data`. */
153
+ function hasField(args, field) {
154
+ if (optionValue(args, field.flag) !== undefined)
155
+ return true;
156
+ const data = inlineData(args);
157
+ return data !== undefined && data !== "opaque" && valueAt(data, field.path) !== undefined;
158
+ }
159
+ /** Copia de `obj` sin lo que hay en `path`; si el objeto padre queda vacío, también se va. */
160
+ function withoutPath(obj, path) {
161
+ const [head, ...rest] = path;
162
+ if (rest.length === 0) {
163
+ const { [head]: _removed, ...others } = obj;
164
+ return others;
165
+ }
166
+ const child = obj[head];
167
+ if (typeof child !== "object" || child === null)
168
+ return obj;
169
+ const inner = withoutPath(child, rest);
170
+ const { [head]: _old, ...others } = obj;
171
+ return Object.keys(inner).length === 0 ? others : { ...others, [head]: inner };
172
+ }
173
+ /**
174
+ * El comando sin esos campos, de donde estén (flag o `--data` en línea), y el aviso para el `when`: el `--data` va tapado (`<value>`) en el
175
+ * `next`, así que se dice qué hay que sacar de él. Con `--data` de un archivo o de stdin no se puede mirar: el aviso lo pide por las dudas.
176
+ */
177
+ function withoutFields(args, fields) {
178
+ const dropped = withoutFieldsArgs(args, fields);
179
+ return { command: commandText(dropped.args), note: dropped.note };
180
+ }
181
+ /** Lo mismo que `withoutFields`, pero devuelve los argumentos (para seguir armando el comando) en vez del texto. */
182
+ function withoutFieldsArgs(args, fields) {
183
+ let out = args;
184
+ const inData = [];
185
+ let opaque = false;
186
+ for (const field of fields) {
187
+ out = withoutOption(out, field.flag);
188
+ const data = inlineData(out);
189
+ if (data === "opaque")
190
+ opaque = true;
191
+ else if (data !== undefined && valueAt(data, field.path) !== undefined) {
192
+ inData.push(field.path.join("."));
193
+ const next = JSON.stringify(withoutPath(data, field.path));
194
+ // Solo el `--data` de antes de un `--`: lo que viene después es el mensaje, no un flag.
195
+ const end = flagsEnd(out);
196
+ out = out.map((arg, i) => {
197
+ if (i >= end)
198
+ return arg;
199
+ if (arg.startsWith("--data="))
200
+ return `--data=${next}`;
201
+ return out[i - 1] === "--data" ? next : arg;
202
+ });
203
+ }
204
+ }
205
+ const names = fields.map((f) => `\`${f.path.join(".")}\``).join(" and ");
206
+ const note = inData.length > 0
207
+ ? `; the --data of your command has ${inData.map((n) => `\`${n}\``).join(" and ")}: send the --data again without ${inData.length > 1 ? "them" : "it"} (the next hides it as <value>)`
208
+ : opaque
209
+ ? `; if your --data (a file or stdin) has ${names}, take it out of it too`
210
+ : "";
211
+ return { args: out, note };
212
+ }
213
+ /** Si el comando lleva algún campo de `agents run` que pide el permiso `write` (flag o `--data`). */
214
+ function hasWriteFlag(args) {
215
+ return WRITE_FIELDS.some((field) => hasField(args, field));
216
+ }
217
+ /** El campo de `agents run` que corresponde a un `details.field` de modelo. */
218
+ const RUN_FIELD_OF_DETAILS = {
219
+ model: MODEL_FIELD,
220
+ "model_settings.reasoning": REASONING_FIELD,
221
+ };
222
+ /**
223
+ * En `agents run`: el mismo comando sin el campo que choca (`--model` o `--reasoning`, según `details.field`), si el comando lo lleva
224
+ * (en el flag o en `--data`). Sin él el turno corre con lo que tiene la versión.
225
+ */
226
+ function runWithoutFlagStep(hints, field) {
227
+ const target = typeof field === "string" ? RUN_FIELD_OF_DETAILS[field] : undefined;
228
+ if (!target || hints.command?.join(" ") !== "agents run" || !hints.args?.length)
229
+ return [];
230
+ // Con `--data` de un archivo o stdin no se puede mirar adentro: como en los errores de environment, el comando sigue igual y el aviso pide sacar el campo.
231
+ if (!hasField(hints.args, target) && inlineData(hints.args) !== "opaque")
232
+ return [];
233
+ const { command, note } = withoutFields(hints.args, [target]);
234
+ // En evals, con lo que tiene la versión solo anda si ese modelo tiene evals (si no, da evals_not_supported).
235
+ const data = inlineData(hints.args);
236
+ const inEvals = optionValue(hints.args, ENVIRONMENT_FIELD.flag) === "evals" ||
237
+ (data !== undefined && data !== "opaque" && valueAt(data, ENVIRONMENT_FIELD.path) === "evals");
238
+ const evals = inEvals ? "; in evals this only works if the model of the version has evals" : "";
239
+ // Solo en un `--data` de archivo o stdin (el comando no lleva el flag): no hay un flag que sacar, hay que editar el archivo y correr el mismo comando.
240
+ if (!hasField(hints.args, target)) {
241
+ return [
242
+ {
243
+ command,
244
+ when: `take \`${target.path.join(".")}\` out of your --data file (or stdin), then run the same command, with what the version has${evals}`,
245
+ },
246
+ ];
247
+ }
248
+ return [
249
+ { command, when: `to run it without ${target.flag}, with what the version has${evals}${note}` },
250
+ ];
251
+ }
84
252
  /** `args` con el flag en `value`: si ya estaba se reemplaza, y se suma antes de un `--` para que siga siendo un flag. */
85
253
  function withOptionValue(args, flag, value) {
86
254
  const rest = withoutOption(args, flag);
87
- const end = rest.indexOf("--");
88
- return end === -1
89
- ? [...rest, flag, value]
90
- : [...rest.slice(0, end), flag, value, ...rest.slice(end)];
255
+ const end = flagsEnd(rest);
256
+ return [...rest.slice(0, end), flag, value, ...rest.slice(end)];
91
257
  }
92
258
  /**
93
259
  * El comando que muestra si un pedido que sigue corriendo ya hizo efecto: el `list` (o `get`) del recurso que
@@ -123,27 +289,191 @@ function idempotencyCheckCommand(hints) {
123
289
  }
124
290
  /** El mensaje de `idempotency_key_in_progress`: dice que el primer intento puede seguir en el servidor, no que hubo un choque. */
125
291
  const IN_PROGRESS_MESSAGE = "The first attempt failed or took too long, so the CLI retried it, and the server is still processing that first request: it may still finish and apply. Check that it did not apply before running the command again.";
126
- /** `next` de los errores comunes de la API (Q9): a qué comando ir según el `code`. */
292
+ /** `details.field` del choque con `thinking` cuando el modelo que razona es el de `follow_up.model` (camelCase o snake_case). */
293
+ function isFollowUpModelField(field) {
294
+ return typeof field === "string" && /^config\.(followUp|follow_up)\.model(\.|$)/.test(field);
295
+ }
296
+ /** El modelo para `follow_up.model` cuando el choque con `thinking` es del follow-up (la tool `thinking` se queda). */
297
+ const THINKING_FOLLOW_UP_MODEL = "a model with THINKING TOOL yes in `models list` (`capabilities.thinking_tool` true with --json)";
298
+ /**
299
+ * El `when` del primer `next` de un choque con `thinking` al guardar. En un `update` la tool puede no estar en el `--config`: si solo
300
+ * se cambió el modelo, ya estaba guardada en la versión de la que parte el update, y se saca mandando `"tools"` sin ella.
301
+ * Si el choque es del modelo del follow-up (`details.field` en `follow_up.model`), no hay una tool que nombrar: se cambia ese modelo
302
+ * (a uno que no razone) o se saca la tool, y `follow_up` se manda entero porque reemplaza al guardado.
303
+ */
304
+ function thinkingSaveWhen(path, args, field) {
305
+ if (isFollowUpModelField(field)) {
306
+ return `details.field is follow_up.model (the model of the follow-up), not a tool: set follow_up.model in this --config to ${THINKING_FOLLOW_UP_MODEL}, or drop the thinking tool from the config; send follow_up whole, because it replaces the saved one, then run it again`;
307
+ }
308
+ const modelChoice = `or set ${THINKING_TOOL_MODEL}, then run it again`;
309
+ if (path !== "agents update") {
310
+ return `drop the thinking tool from --config (details.field says which tool) ${modelChoice}`;
311
+ }
312
+ if (optionValue(args, "--config") !== undefined) {
313
+ return `the thinking tool is in this --config or already saved in the version it starts from (details.field says which tool): send "tools" in the --config without it, ${modelChoice}`;
314
+ }
315
+ return `the thinking tool is in the request or already saved in the version it starts from (details.field says which tool): send "tools" without it, ${modelChoice}`;
316
+ }
317
+ /** Ruta de `agents follow-ups run`: sus errores de conversación y environment tienen su propio `next` (el thread no está en `memory`). */
318
+ const FOLLOW_UP_RUN = "agents follow-ups run";
319
+ /** El archivo con la conversación que sugiere el `next` cuando el thread no existe o no se puede usar. */
320
+ const FOLLOW_UP_MESSAGES_FILE = "@messages.json";
321
+ /**
322
+ * `next` de `agents follow-ups run`. La API pide exactamente uno de `thread` y `messages`: ningún `next` saca el thread sin
323
+ * poner otra conversación (`--messages` u otro `--thread`). Con otro código devuelve `undefined` y sigue el `next` de siempre.
324
+ */
325
+ function followUpNext(code, hints, details) {
326
+ const args = hints.args ?? [];
327
+ // `<thread_id>`/`messages.json` son marcadores: la persona pone su id o su archivo.
328
+ const withMessages = (fields) => {
329
+ const dropped = withoutFieldsArgs(args, fields);
330
+ return {
331
+ command: commandText(withOptionValue(dropped.args, "--messages", FOLLOW_UP_MESSAGES_FILE)),
332
+ note: dropped.note,
333
+ };
334
+ };
335
+ if (code === "conversation_not_found") {
336
+ if (!args.length)
337
+ return undefined;
338
+ const other = withOptionValue(args, "--thread", "<thread_id>");
339
+ const messages = withMessages([FOLLOW_UP_THREAD_FIELD]);
340
+ return [
341
+ {
342
+ command: messages.command,
343
+ when: `the thread does not exist in this organization; to simulate on a conversation you write instead: save it as messages.json, a list of { "role": "user" | "assistant", "parts": [{ "type": "text", "text": "..." }] }${messages.note}`,
344
+ },
345
+ {
346
+ command: commandText(other),
347
+ when: "to simulate on another thread of this agent (put its id instead of <thread_id>)",
348
+ },
349
+ ];
350
+ }
351
+ if (code === "invalid_request" && details.reason === "environment_mismatch") {
352
+ if (!args.length)
353
+ return undefined;
354
+ const threadEnvironment = details.thread_environment === "evals" ? "evals" : null;
355
+ const same = threadEnvironment === "evals"
356
+ ? { command: commandText(withOptionValue(args, "--environment", "evals")), note: "" }
357
+ : withoutFields(args, [ENVIRONMENT_FIELD]);
358
+ return [
359
+ {
360
+ command: same.command,
361
+ when: `${threadEnvironment === "evals"
362
+ ? "to run it in the environment the thread was created with (evals)"
363
+ : "to run it in the environment the thread was created with (production, without --environment)"}${same.note}`,
364
+ },
365
+ ];
366
+ }
367
+ if (code === "evals_not_supported") {
368
+ if (!args.length)
369
+ return undefined;
370
+ const models = {
371
+ command: "laburen models list",
372
+ when: `to pick ${EVALS_MODEL}; the models that run need evals: the one of the agent (follow_up.model or, without it, the model of the version; checked with --mode agent or both) and follow_up.decider.model (checked with --mode decider or both); fix them with agents update, or pass --version-id of a version that has them; models list needs the \`read\` permission`,
373
+ };
374
+ // Con --thread (de evals) sacar solo --environment da environment_mismatch, que vuelve a evals_not_supported:
375
+ // se cambia el thread por --messages, que no tiene environment, y se corre en producción.
376
+ if (hasField(args, FOLLOW_UP_THREAD_FIELD) || inlineData(args) === "opaque") {
377
+ const fresh = withMessages([FOLLOW_UP_THREAD_FIELD, ENVIRONMENT_FIELD]);
378
+ return [
379
+ {
380
+ command: fresh.command,
381
+ when: `to run it on a conversation you write (save it as messages.json), without --thread and --environment, on production${fresh.note}`,
382
+ },
383
+ models,
384
+ ];
385
+ }
386
+ const prod = withoutFields(args, [ENVIRONMENT_FIELD]);
387
+ return [
388
+ { command: prod.command, when: `to run it without --environment, on production${prod.note}` },
389
+ models,
390
+ ];
391
+ }
392
+ return undefined;
393
+ }
127
394
  function apiNext(code, hints, details = {}, message = "") {
128
- // Una versión con la tool `thinking` y un modelo que razona: `models list` no lo arregla, hay que apagar el reasoning de la corrida o correr otra versión.
129
- if (code === "invalid_request" &&
130
- details.field === "model_settings.reasoning" &&
131
- /thinking tool/.test(message)) {
132
- const steps = [];
133
- // Solo si el modelo puede apagar el reasoning; uno que "always reasons" no acepta `off`.
134
- if (/already reasons/.test(message)) {
135
- steps.push({
136
- command: hints.args?.length
137
- ? commandText(withOptionValue(hints.args, "--reasoning", "off"))
138
- : "laburen agents run <agent_id> <message> --reasoning off",
139
- when: "to run it with reasoning off, which the thinking tool allows",
140
- });
395
+ if (hints.command?.join(" ") === FOLLOW_UP_RUN) {
396
+ const next = followUpNext(code, hints, details);
397
+ if (next)
398
+ return next;
399
+ }
400
+ // Una versión con la tool `thinking` y un modelo que razona: `off` no lo arregla (el modelo razona en todos los niveles).
401
+ // Se reconoce por `details.reason` (el `field` y el texto cambian). Salida: una versión sin la tool o un modelo con `thinking_tool`.
402
+ if (details.reason === THINKING_TOOL_CONFLICT) {
403
+ // Al guardar no hay run: el `next` depende solo del comando que falló (la CLI no sabe de dónde vino la tool).
404
+ const path = hints.command?.join(" ");
405
+ if (path !== "agents run") {
406
+ const modelsList = {
407
+ command: "laburen models list",
408
+ when: `to pick ${THINKING_TOOL_MODEL}`,
409
+ };
410
+ if (path === "agents tools add" && isFollowUpModelField(details.field)) {
411
+ // El choque es del `follow_up.model` guardado: cambiar el `model` del agente no lo arregla. `follow_up` se reemplaza entero.
412
+ return [
413
+ {
414
+ command: "laburen models list",
415
+ when: `to pick ${THINKING_FOLLOW_UP_MODEL} for follow_up.model (or remove the thinking tool you are adding)`,
416
+ },
417
+ {
418
+ command: fillIds(["agents", "get", "<agent_id>"], hints.ids),
419
+ when: "to read the saved follow_up; agents update replaces it whole, so send it complete with the new follow_up.model",
420
+ },
421
+ ];
422
+ }
423
+ if (path === "agents tools add") {
424
+ return [
425
+ modelsList,
426
+ {
427
+ command: fillIds(["agents", "update", "<agent_id>", "--config", '{"model":{"id":"<model_id>"}}'], hints.ids),
428
+ when: "then set the model you picked (put its id instead of <model_id>)",
429
+ },
430
+ ];
431
+ }
432
+ if (path === "agents versions restore") {
433
+ return [
434
+ {
435
+ command: fillIds(["agents", "versions", "list", "<agent_id>"], hints.ids),
436
+ when: "this version has the thinking tool and a model that reasons; to find another version to restore",
437
+ },
438
+ modelsList,
439
+ ];
440
+ }
441
+ if (path === "agents create" ||
442
+ path === "agents update" ||
443
+ path === "agents versions create") {
444
+ return [
445
+ ...(hints.args?.length
446
+ ? [
447
+ {
448
+ command: commandText(hints.args),
449
+ when: thinkingSaveWhen(path, hints.args, details.field),
450
+ },
451
+ ]
452
+ : []),
453
+ modelsList,
454
+ ...(path === "agents update"
455
+ ? [
456
+ {
457
+ command: fillIds(["agents", "tools", "remove", "<agent_id>", "<tool_id>"], hints.ids),
458
+ when: "only if the thinking tool is already in the latest version and you changed just the model (put its id instead of <tool_id>); then run the update again",
459
+ },
460
+ ]
461
+ : []),
462
+ ];
463
+ }
464
+ return [modelsList];
141
465
  }
142
- steps.push({
143
- command: fillIds(["agents", "versions", "list", "<agent_id>"], hints.ids),
144
- when: "to find a version without the thinking tool; run it with --version-id",
145
- });
146
- return steps;
466
+ return [
467
+ ...runWithoutFlagStep(hints, details.field),
468
+ {
469
+ command: fillIds(["agents", "versions", "list", "<agent_id>"], hints.ids),
470
+ when: "to find a version without the thinking tool; run it with --version-id",
471
+ },
472
+ {
473
+ command: "laburen models list",
474
+ when: `to pick ${THINKING_TOOL_MODEL}; run it with --model, which needs the \`write\` permission (models list needs \`read\`)`,
475
+ },
476
+ ];
147
477
  }
148
478
  // El nombre o el nivel de reasoning no es de los que ofrece la API: `models list` dice cuáles hay.
149
479
  // Hay errores de forma ("must be a non-empty string") que `models list` no arregla: solo cuando el mensaje dice que no se ofrece.
@@ -152,6 +482,7 @@ function apiNext(code, hints, details = {}, message = "") {
152
482
  MODEL_FIELDS.has(details.field) &&
153
483
  /not offered|is invalid|not allowed/.test(message)) {
154
484
  return [
485
+ ...runWithoutFlagStep(hints, details.field),
155
486
  {
156
487
  command: "laburen models list",
157
488
  when: "the model or reasoning level is not available; to see the offered models and their reasoning levels",
@@ -161,6 +492,19 @@ function apiNext(code, hints, details = {}, message = "") {
161
492
  // Repetir el comando manda un pedido nuevo (otra key) y puede duplicar: primero se mira si el primero ya hizo efecto.
162
493
  if (code === "idempotency_key_in_progress") {
163
494
  const check = idempotencyCheckCommand(hints);
495
+ // `threads create` no tiene `list`. Con `channel` encuentra el thread de esa conversación: repetirlo es seguro. Sin canal repetir
496
+ // manda otra key y puede crear un segundo thread (o duplicar --messages): sin next, como `agents run`.
497
+ if (!check &&
498
+ hints.command?.join(" ") === "threads create" &&
499
+ hints.args?.length &&
500
+ hasField(hints.args, CHANNEL_FIELD)) {
501
+ return [
502
+ {
503
+ command: commandText(hints.args),
504
+ when: "the first request is still running and may finish; wait a few seconds, then run it again: with --channel it finds the same thread",
505
+ },
506
+ ];
507
+ }
164
508
  return check
165
509
  ? [
166
510
  {
@@ -265,6 +609,107 @@ function apiNext(code, hints, details = {}, message = "") {
265
609
  },
266
610
  ];
267
611
  }
612
+ // Evals: el modelo no tiene cuenta de evals (nunca corre en producción por su cuenta). Lo que alcanza con `query` es correrlo sin
613
+ // --environment; elegir otro modelo pide `read` (models list) y `write` (--model).
614
+ if (code === "evals_not_supported") {
615
+ const args = hints.args ?? [];
616
+ const needsWrite = hasWriteFlag(args)
617
+ ? "it keeps flags that need the `write` permission (--model, --instructions, --reasoning, --max-steps)"
618
+ : "needs only the `query` permission";
619
+ // Con --thread, el thread es de evals (el run mandó --environment evals): sacar solo --environment da environment_mismatch, que
620
+ // vuelve a evals_not_supported. Lo que sí funciona: el mismo thread con un --model con evals, o una conversación nueva sin --thread.
621
+ // Con un `--data` de archivo o stdin no se ve el thread: se asume que puede haberlo (sacar solo --environment daría el mismo loop).
622
+ if (hasField(args, THREAD_FIELD) || inlineData(args) === "opaque") {
623
+ const fresh = withoutFields(args, [THREAD_FIELD, ENVIRONMENT_FIELD]);
624
+ return [
625
+ {
626
+ command: commandText(withOptionValue(args, "--model", "<model_id>")),
627
+ when: `to keep this thread in evals with ${EVALS_MODEL} (put its id instead of <model_id>; if the version has the thinking tool, also THINKING TOOL yes); --model needs the \`write\` permission`,
628
+ },
629
+ {
630
+ command: fresh.command,
631
+ when: `to run it without --thread and --environment: it starts a new conversation on production; ${needsWrite}${fresh.note}`,
632
+ },
633
+ {
634
+ command: "laburen models list",
635
+ when: `to pick ${EVALS_MODEL}; models list needs the \`read\` permission`,
636
+ },
637
+ ];
638
+ }
639
+ const prod = args.length ? withoutFields(args, [ENVIRONMENT_FIELD]) : undefined;
640
+ return [
641
+ ...(prod
642
+ ? [
643
+ {
644
+ command: prod.command,
645
+ when: `to run it without --environment, on production; ${needsWrite}${prod.note}`,
646
+ },
647
+ ]
648
+ : []),
649
+ {
650
+ command: "laburen models list",
651
+ when: `to pick ${EVALS_MODEL} and run it with --model; models list needs the \`read\` permission and --model the \`write\` permission`,
652
+ },
653
+ ];
654
+ }
655
+ // Evals: el thread se creó con otro environment y no cambia nunca. Primero el mismo comando con el environment del thread
656
+ // (el que arregla el pedido); después una conversación nueva, que queda en el environment del pedido (el opuesto al del thread).
657
+ if (code === "invalid_request" && details.reason === "environment_mismatch") {
658
+ const threadEnvironment = details.thread_environment === "evals" ? "evals" : null;
659
+ if (!hints.args?.length) {
660
+ return [
661
+ {
662
+ command: helpCommand(hints.command),
663
+ when: "the thread was created with another environment, which never changes; send the same one or start a new conversation",
664
+ },
665
+ ];
666
+ }
667
+ const sameEnvironment = threadEnvironment === "evals"
668
+ ? { command: commandText(withOptionValue(hints.args, "--environment", "evals")), note: "" }
669
+ : withoutFields(hints.args, [ENVIRONMENT_FIELD]);
670
+ const newThread = withoutFields(hints.args, [THREAD_FIELD]);
671
+ return [
672
+ {
673
+ command: sameEnvironment.command,
674
+ when: `${threadEnvironment === "evals"
675
+ ? "to run it in the environment the thread was created with (evals)"
676
+ : "to run it in the environment the thread was created with (production, without --environment)"}${sameEnvironment.note}`,
677
+ },
678
+ {
679
+ command: newThread.command,
680
+ when: `${threadEnvironment === "evals"
681
+ ? "to run it without --thread: it starts a new conversation on production"
682
+ : "to run it without --thread: it starts a new conversation in evals"}${newThread.note}`,
683
+ },
684
+ ];
685
+ }
686
+ // Evals: `threads create` con --environment y --channel. Una conversación de canal es la de un cliente real.
687
+ if (code === "invalid_request" && details.reason === "channel_conversation_is_real") {
688
+ const steps = [];
689
+ const args = hints.args ?? [];
690
+ if (hasField(args, ENVIRONMENT_FIELD)) {
691
+ const { command, note } = withoutFields(args, [ENVIRONMENT_FIELD]);
692
+ steps.push({
693
+ command,
694
+ when: `a channel conversation is a real one and cannot be an evals thread; to create it without --environment${note}`,
695
+ });
696
+ }
697
+ if (hasField(args, CHANNEL_FIELD)) {
698
+ const { command, note } = withoutFields(args, [CHANNEL_FIELD]);
699
+ steps.push({
700
+ command,
701
+ when: `to create an evals thread, which cannot be linked to a channel${note}`,
702
+ });
703
+ }
704
+ return steps.length > 0
705
+ ? steps
706
+ : [
707
+ {
708
+ command: helpCommand(hints.command),
709
+ when: "an evals thread cannot have a channel; drop `environment` or `channel` from --data",
710
+ },
711
+ ];
712
+ }
268
713
  // Repetir el comando no lo arregla: el canal se conecta desde el dashboard, o el número es de otro agente.
269
714
  if (code === "invalid_request" &&
270
715
  (details.reason === "channel_not_connected" || details.reason === "agent_not_linked_to_channel")) {
@@ -290,26 +735,30 @@ function apiNext(code, hints, details = {}, message = "") {
290
735
  }
291
736
  // El mismo comando sin el flag que no encaja con la conversación existente.
292
737
  if (code === "thread_resource_mismatch" || code === "conversation_not_found") {
293
- const flag = code === "thread_resource_mismatch" ? "--resource" : "--thread";
738
+ const field = code === "thread_resource_mismatch" ? RESOURCE_FIELD : THREAD_FIELD;
739
+ const dropped = hints.args?.length ? withoutFields(hints.args, [field]) : undefined;
294
740
  return [
295
741
  {
296
- command: hints.args?.length
297
- ? commandText(withoutOption(hints.args, flag))
298
- : `laburen agents run <agent_id> <message>`,
299
- when: code === "thread_resource_mismatch"
742
+ command: dropped?.command ?? `laburen agents run <agent_id> <message>`,
743
+ when: `${code === "thread_resource_mismatch"
300
744
  ? "to run it without --resource (the thread already belongs to another end user)"
301
- : "to run it without --thread and start a new conversation",
745
+ : "to run it without --thread and start a new conversation"}${dropped?.note ?? ""}`,
302
746
  },
303
747
  ];
304
748
  }
305
- // La IA está apagada en ese hilo (la tomó una persona): el mismo comando sin `--thread` abre una conversación nueva.
749
+ // La IA está apagada en ese hilo (la tomó una persona): el mismo comando sin `--thread` abre una conversación nueva, o
750
+ // `threads update --ai-enabled` la vuelve a prender en ese hilo; el id sale de `details.conversation_id` de la API.
306
751
  if (code === "ai_disabled_for_conversation") {
752
+ const dropped = hints.args?.length ? withoutFields(hints.args, [THREAD_FIELD]) : undefined;
753
+ const threadId = typeof details.conversation_id === "string" ? details.conversation_id : "<thread_id>";
307
754
  return [
308
755
  {
309
- command: hints.args?.length
310
- ? commandText(withoutOption(hints.args, "--thread"))
311
- : "laburen agents run <agent_id> <message>",
312
- when: "the AI is off in that thread (a human took over); to run it without --thread and start a new conversation",
756
+ command: dropped?.command ?? "laburen agents run <agent_id> <message>",
757
+ when: `the AI is off in that thread (a human took over); to run it without --thread and start a new conversation${dropped?.note ?? ""}`,
758
+ },
759
+ {
760
+ command: `laburen threads update ${threadId} --ai-enabled`,
761
+ when: "to turn the AI back on in that thread (not in chatwoot or crm threads: there the AI state is managed in Chatwoot)",
313
762
  },
314
763
  ];
315
764
  }
@@ -349,7 +798,7 @@ function apiNext(code, hints, details = {}, message = "") {
349
798
  // Un agente sin versión activa no se puede correr: se ven sus versiones y se activa una.
350
799
  // Otros invalid_agent_config (una versión con la config rota) no se arreglan activando: caen en el `--help` genérico.
351
800
  if (code === "invalid_agent_config" &&
352
- hints.command?.join(" ") === "agents run" &&
801
+ (hints.command?.join(" ") === "agents run" || hints.command?.join(" ") === FOLLOW_UP_RUN) &&
353
802
  /no active version/i.test(message)) {
354
803
  return [
355
804
  {
@@ -390,7 +839,7 @@ function apiNext(code, hints, details = {}, message = "") {
390
839
  return [];
391
840
  }
392
841
  /** Comandos a mano (no generados) que tienen `--schema`. */
393
- const CUSTOM_SCHEMA_COMMANDS = new Set(["agents run", "agents tools add"]);
842
+ const CUSTOM_SCHEMA_COMMANDS = new Set(["agents run", "agents tools add", "agents follow-ups run"]);
394
843
  /** Si el comando tiene body y por eso `--schema` (los generados con body y los de `CUSTOM_SCHEMA_COMMANDS`). */
395
844
  function hasSchemaFlag(command) {
396
845
  const path = command.join(" ");
@@ -457,11 +906,35 @@ export function toCliError(err, hints = {}) {
457
906
  // La CLI nunca manda su key: la inventa el SDK por llamada, así que este código solo llega en su propio reintento (C44).
458
907
  return new CliError(reason, IN_PROGRESS_MESSAGE, 1, next, requestId, extra);
459
908
  }
460
- if (hints.continueCommand) {
909
+ // Una decisión que falló queda guardada con su error_code: leerla es lo que sigue.
910
+ const decisionId = err.details.decision_id;
911
+ if (hints.command?.join(" ") === "decisions create" &&
912
+ typeof decisionId === "string" &&
913
+ decisionId !== "") {
914
+ next.push({
915
+ command: `laburen decisions get ${decisionId}`,
916
+ when: "the failed decision was saved; read it",
917
+ });
918
+ }
919
+ if (reason === "model_context_exceeded") {
920
+ // Repetir vuelve a fallar. En un turno sirve un modelo con más contexto; en decisions, un state más chico (sus modelos no están en models list).
921
+ if (hints.command?.[0] === "agents") {
922
+ // Si no entró en el filtro del follow-up, el modelo a cambiar es el del filtro; sin --thread no hay thread que dejar.
923
+ const which = err.details.stage === "decider" ? "follow_up.decider.model" : "the model of the agent";
924
+ const thread = hints.args?.some((arg) => arg === "--thread" || arg.startsWith("--thread="))
925
+ ? ", or start a new conversation without --thread"
926
+ : ", or send a shorter conversation";
927
+ next.push({
928
+ command: "laburen models list",
929
+ when: `the conversation does not fit: pick for ${which} one with a larger context_window${thread}`,
930
+ });
931
+ }
932
+ }
933
+ else if (hints.continueCommand) {
461
934
  // Un error a mitad del stream (de cualquier familia) no es un pedido mal armado: `--help` no sirve, seguir el thread sí.
462
935
  next.push({
463
936
  command: hints.continueCommand,
464
- when: "to keep going with the same conversation",
937
+ when: `to keep going with the same conversation${hints.continueNote ? `; ${hints.continueNote}` : ""}`,
465
938
  });
466
939
  }
467
940
  else if (hints.retryCommand) {