@laburen/delta-cli 0.0.0-stage → 0.2.0-canary.9

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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +16 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/commands/agent-checks.d.ts +3 -0
  7. package/dist/commands/agent-checks.js +36 -0
  8. package/dist/commands/agent-checks.js.map +1 -0
  9. package/dist/commands/agent-run/body.d.ts +22 -0
  10. package/dist/commands/agent-run/body.js +88 -0
  11. package/dist/commands/agent-run/body.js.map +1 -0
  12. package/dist/commands/agent-run/render.d.ts +40 -0
  13. package/dist/commands/agent-run/render.js +271 -0
  14. package/dist/commands/agent-run/render.js.map +1 -0
  15. package/dist/commands/agent-run.d.ts +10 -0
  16. package/dist/commands/agent-run.js +205 -0
  17. package/dist/commands/agent-run.js.map +1 -0
  18. package/dist/commands/agent-tools/add.d.ts +5 -0
  19. package/dist/commands/agent-tools/add.js +80 -0
  20. package/dist/commands/agent-tools/add.js.map +1 -0
  21. package/dist/commands/agent-tools/remove.d.ts +5 -0
  22. package/dist/commands/agent-tools/remove.js +126 -0
  23. package/dist/commands/agent-tools/remove.js.map +1 -0
  24. package/dist/commands/agent-tools/shared.d.ts +276 -0
  25. package/dist/commands/agent-tools/shared.js +94 -0
  26. package/dist/commands/agent-tools/shared.js.map +1 -0
  27. package/dist/commands/agent-tools.d.ts +5 -0
  28. package/dist/commands/agent-tools.js +11 -0
  29. package/dist/commands/agent-tools.js.map +1 -0
  30. package/dist/commands/auth.d.ts +14 -0
  31. package/dist/commands/auth.js +161 -0
  32. package/dist/commands/auth.js.map +1 -0
  33. package/dist/commands/completion.d.ts +4 -0
  34. package/dist/commands/completion.js +50 -0
  35. package/dist/commands/completion.js.map +1 -0
  36. package/dist/commands/config-sources.d.ts +22 -0
  37. package/dist/commands/config-sources.js +46 -0
  38. package/dist/commands/config-sources.js.map +1 -0
  39. package/dist/commands/config-wizard.d.ts +9 -0
  40. package/dist/commands/config-wizard.js +332 -0
  41. package/dist/commands/config-wizard.js.map +1 -0
  42. package/dist/commands/orgs.d.ts +11 -0
  43. package/dist/commands/orgs.js +179 -0
  44. package/dist/commands/orgs.js.map +1 -0
  45. package/dist/commands/skill-dir.d.ts +18 -0
  46. package/dist/commands/skill-dir.js +97 -0
  47. package/dist/commands/skill-dir.js.map +1 -0
  48. package/dist/commands/token-notice.d.ts +4 -0
  49. package/dist/commands/token-notice.js +13 -0
  50. package/dist/commands/token-notice.js.map +1 -0
  51. package/dist/commands/whoami.d.ts +8 -0
  52. package/dist/commands/whoami.js +38 -0
  53. package/dist/commands/whoami.js.map +1 -0
  54. package/dist/commands/wizards.d.ts +4 -0
  55. package/dist/commands/wizards.js +210 -0
  56. package/dist/commands/wizards.js.map +1 -0
  57. package/dist/completion/bash.d.ts +3 -0
  58. package/dist/completion/bash.js +60 -0
  59. package/dist/completion/bash.js.map +1 -0
  60. package/dist/completion/files.d.ts +33 -0
  61. package/dist/completion/files.js +171 -0
  62. package/dist/completion/files.js.map +1 -0
  63. package/dist/completion/powershell.d.ts +9 -0
  64. package/dist/completion/powershell.js +83 -0
  65. package/dist/completion/powershell.js.map +1 -0
  66. package/dist/completion/tree.d.ts +25 -0
  67. package/dist/completion/tree.js +53 -0
  68. package/dist/completion/tree.js.map +1 -0
  69. package/dist/completion/zsh.d.ts +3 -0
  70. package/dist/completion/zsh.js +76 -0
  71. package/dist/completion/zsh.js.map +1 -0
  72. package/dist/config/auth.d.ts +26 -0
  73. package/dist/config/auth.js +223 -0
  74. package/dist/config/auth.js.map +1 -0
  75. package/dist/config/link.d.ts +16 -0
  76. package/dist/config/link.js +74 -0
  77. package/dist/config/link.js.map +1 -0
  78. package/dist/config/paths.d.ts +3 -0
  79. package/dist/config/paths.js +20 -0
  80. package/dist/config/paths.js.map +1 -0
  81. package/dist/config/settings.d.ts +8 -0
  82. package/dist/config/settings.js +24 -0
  83. package/dist/config/settings.js.map +1 -0
  84. package/dist/confirm.d.ts +35 -0
  85. package/dist/confirm.js +51 -0
  86. package/dist/confirm.js.map +1 -0
  87. package/dist/context.d.ts +27 -0
  88. package/dist/context.js +15 -0
  89. package/dist/context.js.map +1 -0
  90. package/dist/errors.d.ts +54 -0
  91. package/dist/errors.js +184 -0
  92. package/dist/errors.js.map +1 -0
  93. package/dist/generated/commands.d.ts +47 -0
  94. package/dist/generated/commands.js +52 -0
  95. package/dist/generated/commands.js.map +1 -0
  96. package/dist/generated/schemas.d.ts +5 -0
  97. package/dist/generated/schemas.js +18 -0
  98. package/dist/generated/schemas.js.map +1 -0
  99. package/dist/invocation.d.ts +64 -0
  100. package/dist/invocation.js +325 -0
  101. package/dist/invocation.js.map +1 -0
  102. package/dist/mode.d.ts +17 -0
  103. package/dist/mode.js +22 -0
  104. package/dist/mode.js.map +1 -0
  105. package/dist/operations/call.d.ts +6 -0
  106. package/dist/operations/call.js +14 -0
  107. package/dist/operations/call.js.map +1 -0
  108. package/dist/operations/extensions.d.ts +46 -0
  109. package/dist/operations/extensions.js +29 -0
  110. package/dist/operations/extensions.js.map +1 -0
  111. package/dist/operations/json-input.d.ts +7 -0
  112. package/dist/operations/json-input.js +50 -0
  113. package/dist/operations/json-input.js.map +1 -0
  114. package/dist/operations/params.d.ts +17 -0
  115. package/dist/operations/params.js +95 -0
  116. package/dist/operations/params.js.map +1 -0
  117. package/dist/operations/register.d.ts +10 -0
  118. package/dist/operations/register.js +102 -0
  119. package/dist/operations/register.js.map +1 -0
  120. package/dist/operations/run-operation.d.ts +8 -0
  121. package/dist/operations/run-operation.js +146 -0
  122. package/dist/operations/run-operation.js.map +1 -0
  123. package/dist/operations/schema-flag.d.ts +8 -0
  124. package/dist/operations/schema-flag.js +12 -0
  125. package/dist/operations/schema-flag.js.map +1 -0
  126. package/dist/operations/skeleton.d.ts +16 -0
  127. package/dist/operations/skeleton.js +116 -0
  128. package/dist/operations/skeleton.js.map +1 -0
  129. package/dist/operations/tables.d.ts +3 -0
  130. package/dist/operations/tables.js +52 -0
  131. package/dist/operations/tables.js.map +1 -0
  132. package/dist/operations.d.ts +5 -0
  133. package/dist/operations.js +7 -0
  134. package/dist/operations.js.map +1 -0
  135. package/dist/output.d.ts +22 -0
  136. package/dist/output.js +169 -0
  137. package/dist/output.js.map +1 -0
  138. package/dist/pickers.d.ts +51 -0
  139. package/dist/pickers.js +277 -0
  140. package/dist/pickers.js.map +1 -0
  141. package/dist/program.d.ts +31 -0
  142. package/dist/program.js +251 -0
  143. package/dist/program.js.map +1 -0
  144. package/dist/prompter.d.ts +54 -0
  145. package/dist/prompter.js +129 -0
  146. package/dist/prompter.js.map +1 -0
  147. package/dist/session.d.ts +45 -0
  148. package/dist/session.js +170 -0
  149. package/dist/session.js.map +1 -0
  150. package/dist/update-check.d.ts +4 -0
  151. package/dist/update-check.js +60 -0
  152. package/dist/update-check.js.map +1 -0
  153. package/docs/SKILL.md +108 -0
  154. package/docs/references/auth-and-organizations.md +72 -0
  155. package/docs/references/commands.md +186 -0
  156. package/docs/references/output-and-errors.md +87 -0
  157. package/package.json +39 -5
@@ -0,0 +1,54 @@
1
+ import type { CliContext } from "./context.js";
2
+ import { CliError } from "./errors.js";
3
+ import type { Mode } from "./mode.js";
4
+ /** Una opción de una lista: `value` es lo que se devuelve (un id o un valor del contrato). */
5
+ export interface PromptOption {
6
+ value: string;
7
+ label: string;
8
+ hint?: string;
9
+ }
10
+ /** Las preguntas que puede hacer la CLI; cancelar (Ctrl-C, Esc, Ctrl-D) lanza `CliError("cancelled")`. */
11
+ export interface Prompter {
12
+ select(params: {
13
+ message: string;
14
+ options: PromptOption[];
15
+ initialValue?: string;
16
+ }): Promise<string>;
17
+ multiselect(params: {
18
+ message: string;
19
+ options: PromptOption[];
20
+ initialValues?: string[];
21
+ required?: boolean;
22
+ }): Promise<string[]>;
23
+ confirm(params: {
24
+ message: string;
25
+ initialValue?: boolean;
26
+ }): Promise<boolean>;
27
+ text(params: {
28
+ message: string;
29
+ placeholder?: string;
30
+ initialValue?: string;
31
+ validate?: (value: string) => string | undefined;
32
+ }): Promise<string>;
33
+ }
34
+ /** Con más opciones que esto el `select` pasa a tener buscador, mostrando esta cantidad por pantalla (C31). */
35
+ export declare const SEARCH_THRESHOLD = 15;
36
+ /** Devuelve si la CLI puede preguntar (C26): ni `--non-interactive`, ni `--json`, ni CI, y stdin y stderr son terminales. */
37
+ export declare function canPrompt(ctx: CliContext, mode: Mode): boolean;
38
+ /** El error de cancelar una pregunta: código 1 y sin `next` (C32). */
39
+ export declare function cancelled(): CliError;
40
+ /** Adapter de clack: dibuja las preguntas en stderr (C25) y lee de `ctx.stdin`; todo texto que dibuja pasa escapado. */
41
+ export declare function clackPrompter(ctx: CliContext): Prompter;
42
+ /** Un ítem de una lista para elegir; `current` lo preselecciona y le suma `(current)` a la etiqueta (C28). */
43
+ export interface Choice extends PromptOption {
44
+ current?: boolean;
45
+ }
46
+ /** Elige un ítem: con uno solo lo toma sin preguntar y avisa cuál por stderr (salvo `alwaysAsk`); con varios pregunta con `select` (C28, C31). */
47
+ export declare function chooseOne(ctx: CliContext, mode: Mode, prompter: Prompter, params: {
48
+ message: string;
49
+ noun: string;
50
+ choices: Choice[];
51
+ alwaysAsk?: boolean;
52
+ /** Preselecciona el primero que no es el actual (al borrar, el actual no se puede). */
53
+ avoidCurrent?: boolean;
54
+ }): Promise<string>;
@@ -0,0 +1,129 @@
1
+ import { autocomplete, confirm, isCancel, multiselect, select, settings, text, } from "@clack/prompts";
2
+ import { CliError } from "./errors.js";
3
+ import { escapeControl, notice } from "./output.js";
4
+ /** Con más opciones que esto el `select` pasa a tener buscador, mostrando esta cantidad por pantalla (C31). */
5
+ export const SEARCH_THRESHOLD = 15;
6
+ /** Devuelve si la CLI puede preguntar (C26): ni `--non-interactive`, ni `--json`, ni CI, y stdin y stderr son terminales. */
7
+ export function canPrompt(ctx, mode) {
8
+ const stderrIsTTY = ctx.stderrIsTTY ?? ctx.stdoutIsTTY;
9
+ return !mode.nonInteractive && !mode.json && !ctx.env.CI && ctx.stdinIsTTY && stderrIsTTY;
10
+ }
11
+ /** El error de cancelar una pregunta: código 1 y sin `next` (C32). */
12
+ export function cancelled() {
13
+ return new CliError("cancelled", "Cancelled.", 1);
14
+ }
15
+ /** Corre una pregunta de clack sobre stdin y stderr; Ctrl-D o el fin de stdin la abortan y cancelar lanza `cancelled`. */
16
+ async function ask(ctx, prompt) {
17
+ const input = (ctx.stdin ?? process.stdin);
18
+ const controller = new AbortController();
19
+ // clack 1.8.1 no trata Ctrl-D: readline cierra y la promesa queda colgada (node sale 13). Ctrl-D cancela en
20
+ // toda pregunta, también en un `text` con algo escrito (no borra hacia adelante como en una shell).
21
+ const onKey = (_s, key) => {
22
+ if (key?.ctrl && key.name === "d")
23
+ controller.abort();
24
+ };
25
+ const onEnd = () => controller.abort();
26
+ input.on("keypress", onKey);
27
+ input.once("end", onEnd);
28
+ if (input.readableEnded)
29
+ controller.abort();
30
+ try {
31
+ const value = await prompt({
32
+ input,
33
+ output: ctx.stderr,
34
+ signal: controller.signal,
35
+ });
36
+ if (isCancel(value))
37
+ throw cancelled();
38
+ return value;
39
+ }
40
+ catch (err) {
41
+ if (controller.signal.aborted && !(err instanceof CliError))
42
+ throw cancelled();
43
+ throw err;
44
+ }
45
+ finally {
46
+ input.off("keypress", onKey);
47
+ input.off("end", onEnd);
48
+ }
49
+ }
50
+ /**
51
+ * clack 1.8.1: en `confirm`, Esc primero mueve el cursor (cambia No por Yes) y después cancela, así que dibuja "Yes"
52
+ * tachado (Q5). Mientras dura `fn`, Esc cancela por su secuencia (`\x1b`) y no por el nombre que mueve el cursor.
53
+ */
54
+ async function escapeWithoutToggle(fn) {
55
+ const byName = settings.aliases.get("escape");
56
+ const bySequence = settings.aliases.has("\x1b");
57
+ settings.aliases.delete("escape");
58
+ if (!bySequence)
59
+ settings.aliases.set("\x1b", "cancel");
60
+ try {
61
+ return await fn();
62
+ }
63
+ finally {
64
+ if (byName)
65
+ settings.aliases.set("escape", byName);
66
+ if (!bySequence)
67
+ settings.aliases.delete("\x1b");
68
+ }
69
+ }
70
+ /** Escapa etiqueta y `hint` de cada opción: suelen venir del servidor (nombres) y clack los dibuja tal cual (R1). */
71
+ function safeOptions(options) {
72
+ return options.map((o) => ({
73
+ value: o.value,
74
+ label: escapeControl(o.label),
75
+ ...(o.hint !== undefined && { hint: escapeControl(o.hint) }),
76
+ }));
77
+ }
78
+ /** Adapter de clack: dibuja las preguntas en stderr (C25) y lee de `ctx.stdin`; todo texto que dibuja pasa escapado. */
79
+ export function clackPrompter(ctx) {
80
+ return {
81
+ select: (params) => ask(ctx, (streams) => {
82
+ const safe = {
83
+ ...params,
84
+ message: escapeControl(params.message),
85
+ options: safeOptions(params.options),
86
+ };
87
+ return params.options.length > SEARCH_THRESHOLD
88
+ ? autocomplete({ ...safe, ...streams, maxItems: SEARCH_THRESHOLD })
89
+ : select({ ...safe, ...streams });
90
+ }),
91
+ multiselect: (params) => ask(ctx, (streams) => multiselect({
92
+ required: false,
93
+ ...params,
94
+ message: escapeControl(params.message),
95
+ options: safeOptions(params.options),
96
+ ...streams,
97
+ })),
98
+ confirm: (params) => escapeWithoutToggle(() => ask(ctx, (streams) => confirm({ ...params, message: escapeControl(params.message), ...streams }))),
99
+ text: (params) => ask(ctx, (streams) => text({
100
+ ...params,
101
+ message: escapeControl(params.message),
102
+ ...streams,
103
+ validate: params.validate ? (value) => params.validate?.(value ?? "") : undefined,
104
+ })),
105
+ };
106
+ }
107
+ /** Elige un ítem: con uno solo lo toma sin preguntar y avisa cuál por stderr (salvo `alwaysAsk`); con varios pregunta con `select` (C28, C31). */
108
+ export async function chooseOne(ctx, mode, prompter, params) {
109
+ const [first, ...rest] = params.choices;
110
+ if (!first)
111
+ throw new Error("chooseOne needs at least one choice");
112
+ if (rest.length === 0 && !params.alwaysAsk) {
113
+ const hint = first.hint ? ` (${escapeControl(first.hint)})` : "";
114
+ notice(ctx, mode, `Only one ${params.noun} available: ${escapeControl(first.label)}${hint}.`);
115
+ return first.value;
116
+ }
117
+ return prompter.select({
118
+ message: params.message,
119
+ initialValue: params.avoidCurrent
120
+ ? params.choices.find((c) => !c.current)?.value
121
+ : params.choices.find((c) => c.current)?.value,
122
+ options: params.choices.map((c) => ({
123
+ value: c.value,
124
+ label: c.current ? `${c.label} (current)` : c.label,
125
+ hint: c.hint,
126
+ })),
127
+ });
128
+ }
129
+ //# sourceMappingURL=prompter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompter.js","sourceRoot":"","sources":["../src/prompter.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,OAAO,EACP,QAAQ,EACR,WAAW,EACX,MAAM,EACN,QAAQ,EACR,IAAI,GACJ,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA+BpD,+GAA+G;AAC/G,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAEnC,6HAA6H;AAC7H,MAAM,UAAU,SAAS,CAAC,GAAe,EAAE,IAAU;IACpD,MAAM,WAAW,GAAG,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,WAAW,CAAC;IACvD,OAAO,CAAC,IAAI,CAAC,cAAc,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,UAAU,IAAI,WAAW,CAAC;AAC3F,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,SAAS;IACxB,OAAO,IAAI,QAAQ,CAAC,WAAW,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC;AACnD,CAAC;AAQD,0HAA0H;AAC1H,KAAK,UAAU,GAAG,CACjB,GAAe,EACf,MAAiD;IAEjD,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,KA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,CAAC,GAAG,CAAC,CAAC,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK;YACnD,IAAI,EAAE,CAAC,CAAC,IAAI;SACZ,CAAC,CAAC;KACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { refreshToken as defaultRefreshToken, type Resources } from "@laburen/delta-sdk/platform";
2
+ import type { CliContext } from "./context.js";
3
+ import { CliError } from "./errors.js";
4
+ import type { Mode } from "./mode.js";
5
+ /** Flags globales que acepta todo comando. */
6
+ export interface GlobalFlags {
7
+ org?: string;
8
+ apiUrl?: string;
9
+ globalConfig?: string;
10
+ json?: boolean;
11
+ color?: boolean;
12
+ nonInteractive?: boolean;
13
+ }
14
+ /** Lo que un comando necesita para llamar a la API: la puerta ya armada y de dónde salió cada dato. */
15
+ export interface Session {
16
+ apiUrl: string;
17
+ configDir: string;
18
+ organization?: string;
19
+ tokenSource: "env" | "file";
20
+ platform: Resources;
21
+ /** El último token que la puerta mandó en un pedido; sirve para saber si otro proceso lo renovó (Q8). */
22
+ lastToken(): string | undefined;
23
+ }
24
+ /** Piezas reemplazables en tests: el `fetch` de la puerta y la función que renueva el token. */
25
+ export interface SessionDeps {
26
+ fetch?: typeof fetch;
27
+ refreshToken?: typeof defaultRefreshToken;
28
+ /** No manda el header de organización (la puerta no tiene otra forma de omitirlo en un pedido); `session.organization` igual se resuelve. */
29
+ omitOrganizationHeader?: boolean;
30
+ /** No busca `link.json` al resolver la organización (lo usa `link`, que lo va a reescribir aunque esté roto). */
31
+ ignoreLink?: boolean;
32
+ /** Si la organización no se puede resolver (link.json roto, mismatch) sigue sin organización en vez de fallar: para comandos que no la mandan. */
33
+ softOrganization?: boolean;
34
+ }
35
+ /** URL de la API (C16): `--api-url` > `LABUREN_API_URL` > la de la puerta, sin barras al final. */
36
+ export declare function resolveApiUrl(ctx: CliContext, flags: GlobalFlags): string;
37
+ /** `login_required` con un `next` de login que conserva la URL y la carpeta de credenciales que se usaron (Q3c). */
38
+ export declare function loginRequired(ctx: CliContext, flags: GlobalFlags, apiUrl: string, message: string): CliError;
39
+ /** Arma la sesión de un comando (C16-C20): URL, token, organización y la puerta lista para llamar. */
40
+ export declare function openSession(ctx: CliContext, flags: GlobalFlags, mode: Mode, deps?: SessionDeps): Promise<Session>;
41
+ /**
42
+ * Devuelve si vale reintentar una vez un pedido que falló con `err` (Q8): la API rechazó un token guardado
43
+ * (`invalid_token`) y auth.json ya tiene otro, porque otro proceso lo renovó. Con `LABUREN_TOKEN` nunca.
44
+ */
45
+ export declare function tokenRenewedElsewhere(session: Session, err: unknown): Promise<boolean>;
@@ -0,0 +1,170 @@
1
+ import { createPlatform, DEFAULT_BASE_URL, refreshToken as defaultRefreshToken, isLaburenApiError, isLaburenOAuthError, } from "@laburen/delta-sdk/platform";
2
+ import { lockWaitNotice, REFRESH_TIMEOUT_MS, readAuth, withAuthLock, writeAuth, } from "./config/auth.js";
3
+ import { findLink } from "./config/link.js";
4
+ import { resolveConfigDir } from "./config/paths.js";
5
+ import { readSettings } from "./config/settings.js";
6
+ import { CliError } from "./errors.js";
7
+ import { commandText, invocationOf, shellQuote, withoutOption } from "./invocation.js";
8
+ /** Margen para renovar antes de que el token venza de verdad. */
9
+ const REFRESH_MARGIN_SECONDS = 60;
10
+ /** URL de la API (C16): `--api-url` > `LABUREN_API_URL` > la de la puerta, sin barras al final. */
11
+ export function resolveApiUrl(ctx, flags) {
12
+ return normalizeApiUrl(flags.apiUrl || ctx.env.LABUREN_API_URL || DEFAULT_BASE_URL);
13
+ }
14
+ function normalizeApiUrl(url) {
15
+ return url.replace(/\/+$/, "");
16
+ }
17
+ /** Errores de OAuth que significan "esta sesión ya no sirve"; el resto (server_error, etc.) no toca las credenciales. */
18
+ const DEAD_SESSION_OAUTH_ERRORS = new Set(["invalid_grant", "invalid_token", "expired_token"]);
19
+ /** `login_required` con un `next` de login que conserva la URL y la carpeta de credenciales que se usaron (Q3c). */
20
+ export function loginRequired(ctx, flags, apiUrl, message) {
21
+ const args = ["laburen", "login"];
22
+ if (apiUrl !== normalizeApiUrl(DEFAULT_BASE_URL))
23
+ args.push("--api-url", shellQuote(apiUrl));
24
+ const configDir = flags.globalConfig || ctx.env.LABUREN_CONFIG_DIR;
25
+ if (configDir)
26
+ args.push("--global-config", shellQuote(configDir));
27
+ return new CliError("login_required", message, 1, [
28
+ { command: args.join(" "), when: "to sign in and save credentials" },
29
+ ]);
30
+ }
31
+ /** Los `next` de un `organization_mismatch` según de dónde vino la organización que no coincide (Q3b). */
32
+ function mismatchNext(ctx, source, value, linked) {
33
+ const relink = {
34
+ command: `laburen link --org ${shellQuote(value)}`,
35
+ when: `to link this folder to ${value} instead`,
36
+ };
37
+ const unlink = {
38
+ command: "laburen unlink",
39
+ when: "to stop using the organization of this folder",
40
+ // `unlink` no usa la organización.
41
+ omitGlobals: ["--org"],
42
+ };
43
+ if (source === "LABUREN_ORG") {
44
+ return [
45
+ { command: "unset LABUREN_ORG", when: `to use the organization of this folder (${linked})` },
46
+ relink,
47
+ unlink,
48
+ ];
49
+ }
50
+ const { args } = invocationOf(ctx);
51
+ const rerun = args.length > 0 ? commandText(withoutOption(args, "--org")) : "laburen <command>";
52
+ return [
53
+ {
54
+ command: rerun,
55
+ when: `to run it without --org, with the organization of this folder (${linked})`,
56
+ omitGlobals: ["--org"],
57
+ },
58
+ relink,
59
+ unlink,
60
+ ];
61
+ }
62
+ /** Resuelve la organización (C17): `--org` > `LABUREN_ORG` > link.json > la guardada (solo si se puede preguntar). */
63
+ async function resolveOrganization(ctx, flags, mode, configDir, ignoreLink) {
64
+ const link = ignoreLink ? null : await findLink(ctx.cwd);
65
+ const candidates = [
66
+ ["--org", flags.org || undefined],
67
+ ["LABUREN_ORG", ctx.env.LABUREN_ORG || undefined],
68
+ ];
69
+ for (const [source, value] of candidates) {
70
+ if (value && link && link.link.organization_id !== value) {
71
+ throw new CliError("organization_mismatch", `${source} is ${value}, but ${link.path} points to ${link.link.organization_id}.`, 2, mismatchNext(ctx, source, value, link.link.organization_id));
72
+ }
73
+ }
74
+ const explicit = candidates.find(([, value]) => value)?.[1];
75
+ if (explicit)
76
+ return explicit;
77
+ if (link)
78
+ return link.link.organization_id;
79
+ if (mode.nonInteractive)
80
+ return undefined;
81
+ return (await readSettings(configDir)).organization_id;
82
+ }
83
+ /** Devuelve un token vigente: el de auth.json, o uno renovado una sola vez bajo lock aunque haya varios procesos. */
84
+ async function validToken(ctx, flags, configDir, apiUrl, refresh) {
85
+ const isFresh = (a) => a.expires_at > ctx.now() / 1000 + REFRESH_MARGIN_SECONDS;
86
+ const current = await readAuth(configDir);
87
+ if (!current || normalizeApiUrl(current.api_url) !== apiUrl)
88
+ throw loginRequired(ctx, flags, apiUrl, `No saved credentials for ${apiUrl}.`);
89
+ if (isFresh(current))
90
+ return current.token;
91
+ return withAuthLock(configDir, async () => {
92
+ // Otro proceso pudo renovar mientras esperábamos el lock: releemos antes de gastar el refresh.
93
+ const latest = await readAuth(configDir);
94
+ if (!latest || normalizeApiUrl(latest.api_url) !== apiUrl)
95
+ throw loginRequired(ctx, flags, apiUrl, `No saved credentials for ${apiUrl}.`);
96
+ if (isFresh(latest))
97
+ return latest.token;
98
+ try {
99
+ const res = await refresh({
100
+ refreshToken: latest.refresh_token,
101
+ baseUrl: apiUrl,
102
+ timeout: REFRESH_TIMEOUT_MS,
103
+ });
104
+ await writeAuth(configDir, {
105
+ token: res.access_token,
106
+ refresh_token: res.refresh_token,
107
+ expires_at: ctx.now() / 1000 + res.expires_in,
108
+ api_url: apiUrl,
109
+ });
110
+ return res.access_token;
111
+ }
112
+ catch (err) {
113
+ if (isLaburenOAuthError(err) && DEAD_SESSION_OAUTH_ERRORS.has(err.error)) {
114
+ throw loginRequired(ctx, flags, apiUrl, `The saved session for ${apiUrl} expired (${err.message}).`);
115
+ }
116
+ throw err;
117
+ }
118
+ }, { onWait: lockWaitNotice(ctx.stderr) });
119
+ }
120
+ /** Arma la sesión de un comando (C16-C20): URL, token, organización y la puerta lista para llamar. */
121
+ export async function openSession(ctx, flags, mode, deps = {}) {
122
+ const apiUrl = resolveApiUrl(ctx, flags);
123
+ const configDir = resolveConfigDir(ctx, flags.globalConfig);
124
+ const envToken = ctx.env.LABUREN_TOKEN || undefined;
125
+ const refresh = deps.refreshToken ?? defaultRefreshToken;
126
+ if (!envToken) {
127
+ // Falla antes de armar la puerta, así un token de otra URL nunca viaja.
128
+ const auth = await readAuth(configDir);
129
+ if (!auth || normalizeApiUrl(auth.api_url) !== apiUrl)
130
+ throw loginRequired(ctx, flags, apiUrl, `No saved credentials for ${apiUrl}.`);
131
+ }
132
+ const organization = await resolveOrganization(ctx, flags, mode, configDir, deps.ignoreLink ?? false).catch((err) => {
133
+ // Un comando que no manda la organización solo la usa para marcar la actual: si no se puede, sigue sin ella.
134
+ if (deps.softOrganization && err instanceof CliError)
135
+ return undefined;
136
+ throw err;
137
+ });
138
+ let lastToken;
139
+ const token = async () => {
140
+ lastToken = envToken ?? (await validToken(ctx, flags, configDir, apiUrl, refresh));
141
+ return lastToken;
142
+ };
143
+ const platform = createPlatform({
144
+ token,
145
+ organization: deps.omitOrganizationHeader ? undefined : organization,
146
+ baseUrl: apiUrl,
147
+ fetch: deps.fetch,
148
+ });
149
+ return {
150
+ apiUrl,
151
+ configDir,
152
+ organization,
153
+ tokenSource: envToken ? "env" : "file",
154
+ platform,
155
+ lastToken: () => lastToken,
156
+ };
157
+ }
158
+ /**
159
+ * Devuelve si vale reintentar una vez un pedido que falló con `err` (Q8): la API rechazó un token guardado
160
+ * (`invalid_token`) y auth.json ya tiene otro, porque otro proceso lo renovó. Con `LABUREN_TOKEN` nunca.
161
+ */
162
+ export async function tokenRenewedElsewhere(session, err) {
163
+ if (session.tokenSource === "env")
164
+ return false;
165
+ if (!isLaburenApiError(err) || err.code !== "invalid_token")
166
+ return false;
167
+ const saved = await readAuth(session.configDir);
168
+ return saved !== null && saved.token !== session.lastToken();
169
+ }
170
+ //# sourceMappingURL=session.js.map
@@ -0,0 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AC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,eAAe;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChD,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,KAAK,KAAK,OAAO,CAAC,SAAS,EAAE,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { CliContext } from "./context.js";
2
+ import type { Mode } from "./mode.js";
3
+ /** Avisa por stderr si hay versión nueva; consulta npm una vez cada 24 horas y ignora cualquier falla. */
4
+ export declare function checkForUpdate(ctx: CliContext, mode: Mode, configDir: string, current: string, fetchFn?: typeof fetch): Promise<void>;
@@ -0,0 +1,60 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { notice } from "./output.js";
4
+ const REGISTRY_URL = "https://registry.npmjs.org/@laburen/delta-cli/latest";
5
+ const CACHE_FILE = "update-check.json";
6
+ const DAY_MS = 24 * 60 * 60 * 1000;
7
+ const TIMEOUT_MS = 1500;
8
+ /** Compara versiones `x.y.z` (ignora prerelease): true si `a` es mayor que `b`. */
9
+ function isNewer(a, b) {
10
+ const pa = a.split("-")[0]?.split(".").map(Number) ?? [];
11
+ const pb = b.split("-")[0]?.split(".").map(Number) ?? [];
12
+ for (let i = 0; i < 3; i++) {
13
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
14
+ if (d !== 0)
15
+ return d > 0;
16
+ }
17
+ return false;
18
+ }
19
+ async function readCache(file) {
20
+ try {
21
+ const c = JSON.parse(await readFile(file, "utf8"));
22
+ return typeof c.checked_at === "number" ? c : null;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** Avisa por stderr si hay versión nueva; consulta npm una vez cada 24 horas y ignora cualquier falla. */
29
+ export async function checkForUpdate(ctx, mode, configDir, current, fetchFn = fetch) {
30
+ if (mode.json || mode.nonInteractive || ctx.env.CI)
31
+ return;
32
+ try {
33
+ const file = join(configDir, CACHE_FILE);
34
+ let cache = await readCache(file);
35
+ if (!cache || ctx.now() - cache.checked_at >= DAY_MS) {
36
+ // Se anota el intento aunque falle, para no pagar el timeout en cada comando sin red.
37
+ cache = { checked_at: ctx.now(), latest: cache?.latest };
38
+ try {
39
+ const res = await fetchFn(REGISTRY_URL, { signal: AbortSignal.timeout(TIMEOUT_MS) });
40
+ if (res.ok) {
41
+ const body = (await res.json());
42
+ if (typeof body.version === "string")
43
+ cache.latest = body.version;
44
+ }
45
+ }
46
+ catch {
47
+ // Sin red: se sigue con el último `latest` conocido.
48
+ }
49
+ await mkdir(configDir, { recursive: true, mode: 0o700 });
50
+ await writeFile(file, JSON.stringify(cache));
51
+ }
52
+ if (cache.latest && isNewer(cache.latest, current)) {
53
+ notice(ctx, mode, `Update available: ${current} → ${cache.latest}. Run npm i -g @laburen/delta-cli`);
54
+ }
55
+ }
56
+ catch {
57
+ // Un chequeo de versión nunca debe romper un comando.
58
+ }
59
+ }
60
+ //# sourceMappingURL=update-check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-check.js","sourceRoot":"","sources":["../src/update-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,MAAM,YAAY,GAAG,sDAAsD,CAAC;AAC5E,MAAM,UAAU,GAAG,mBAAmB,CAAC;AACvC,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,UAAU,GAAG,IAAI,CAAC;AAOxB,mFAAmF;AACnF,SAAS,OAAO,CAAC,CAAS,EAAE,CAAS;IACpC,MAAM,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CA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
1
+ ---
2
+ name: laburen-cli
3
+ description: Use the `laburen` CLI to create, run and operate Laburen agents, skills, MCP connections and API tokens from the terminal, without the dashboard. Use when a task says "create an agent", "run or test an agent", "add a tool", "upload a skill", "connect an MCP", "version or activate an agent", or "create the worker token".
4
+ metadata:
5
+ package: "@laburen/delta-cli"
6
+ ---
7
+
8
+ ## When to use
9
+
10
+ Use this skill when you need to manage Laburen resources from a terminal or from an AI agent: agents and their versions, skills, MCP connections, API tokens, and which organization you are working in.
11
+
12
+ ## How to use
13
+
14
+ Install and run:
15
+
16
+ ```sh
17
+ npm i -g @laburen/delta-cli
18
+ laburen login
19
+ laburen agents list
20
+ ```
21
+
22
+ - Run `laburen login` once. It prints a URL and a code; the person approves it in the browser. In CI or a server, set `LABUREN_TOKEN` instead.
23
+ - Every command accepts `--json`, `--org`, `--api-url`, `--global-config`, `--non-interactive`, `--no-non-interactive` and `--no-color`.
24
+ - Without a terminal the saved organization (`orgs switch`) is ignored: pass `--org <id>` or set `LABUREN_ORG=<id>` (or use `laburen link --org <id>` in the folder). A token that belongs to one organization needs none.
25
+ - Run `laburen <command> --help` for the flags of any command.
26
+ - Tab completion for zsh, bash and PowerShell (on Windows, run it from PowerShell, or from Git Bash/WSL for bash): run `laburen completion --install` once and open a new terminal. It refreshes itself after the CLI is updated. `laburen completion zsh|bash|powershell` prints the script instead.
27
+ - If you are an AI agent with no terminal, the CLI is non-interactive: it never asks questions, and errors come as JSON on stdout with a `next` list of commands that fix them (and `issues` with the invalid fields, when the API sends them). Run the command in `next`: it is the command you ran with what was missing added.
28
+ - Exit codes: `0` ok, `1` API or network error, `2` wrong usage.
29
+
30
+ ## Discover, then build
31
+
32
+ - `laburen whoami` shows who you are, the organization and the credential.
33
+ - `--schema` on any command with a body prints the command, its positionals and the JSON Schemas of the body and the response. It needs no login and calls no API.
34
+ - `--skeleton` (on `agents create` and `agents versions create`) prints a config JSON with the required fields, the fields that have a published default, an empty `prompt` block (`[{"type":"text","content":""}]`), `"tools": []` and a `"$schema"` pointing to `<api-url>/schemas/agent-config.json` (nothing else is invented: no `reasoning_effort`). The available tool types go to stderr (`tool types: ... → see --schema`); stdout stays pure JSON. Edit it and send it with `--config @config.json`: the `$schema` is sent as is and the API ignores it.
35
+ - A selector (an agent, a skill, a connection by name) searches by name when the list has more than one page.
36
+ - Interactive `agents create` (after `Configure the first version now?`) and `agents versions create` ask the whole config, with models from `laburen models list` and projects from `laburen knowledge projects list`. Headers of http tools are never asked because they are secrets.
37
+
38
+ Tool rules the API enforces (the wizard and `--schema` already follow them): every tool type except `http` can appear only once in `config.tools` (the schema marks them with `x-single: true`); `reasoning_effort` must be one of the model's levels (`laburen models list` shows them in REASONING) and a model without reasoning takes none; a `thinking` tool is only for models that do not reason, or with `reasoning_effort: "off"`. `laburen agents tools add --schema` prints the schema of a tool, with no login.
39
+
40
+ - `laburen models list` shows each model's default effort in REASONING, for example `low,medium,high (default: medium)`; it is used when `reasoning_effort` is omitted. A model that reasons and has no `off` level can never use a `thinking` tool.
41
+ - Items of the http tool's `headers`, `body`, `query_parameters` and `path_variables` are `{ "key", "value", "description"? }`, for example `{"key":"Authorization","value":"Bearer xyz"}`.
42
+ - `agents tools remove <agent_id> <tool_id>` takes the tool's `id` from `config.tools[]`; read it with `laburen agents versions get <agent_id> <version_id>` (or the latest version). Without a TTY it is required; with a TTY a picker lists the tools.
43
+ - `laburen tokens create` returns the secret once, in `value`. Save it right away.
44
+
45
+ `base_version_id` guards against a concurrent change: if it is not the latest version the API answers `409 base_version_mismatch`; omit it to skip the check. Send `base_version_id: null` to say the resource has no versions yet. There is no flag for `null`: use `--data`, for example `--data '{"config":{...},"base_version_id":null}'`.
46
+
47
+ Order of steps: first create what the agent will use and look up ids, then build the agent.
48
+
49
+ ```sh
50
+ laburen skills create --name faq --dir ./faq --json
51
+ laburen mcp connections create --name crm --url https://example.com/mcp --json
52
+ laburen knowledge projects list --json
53
+ laburen models list --json
54
+ laburen agents create --name Support --harness-type mastra --config @config.json \
55
+ --skills '[{"skill_id":"<skill_id>"}]' --mcp-connections '[{"connection_id":"<connection_id>"}]' --json
56
+ ```
57
+
58
+ `config.json` only takes the model (`model.id`), `knowledge.project_ids`, the prompt, the tools and the other settings of the version. Skills and MCP connections do not go in it: pass them in the body with `--skills` and `--mcp-connections` (or in `--data`), on `agents create` or `agents versions create`.
59
+
60
+ Each item of `--mcp-connections` accepts `"tools": ["<tool name>"]` to limit the agent to those tools of the connection (absent = all of them); discover the names with `laburen mcp connections tools list <connection_id>` (the `name` field). The API validates them when it saves: an unknown name fails with `400 invalid_request` on `mcp_connections[i].tools[j]`. If the response carries a `mcp_tools_unverified` warning, the server could not be reached and the filter was not checked; the CLI prints it to stderr as `Warning: ...`. The interactive wizards ask it per connection, with every tool preselected.
61
+
62
+ `agents tools add` and `agents tools remove` send `base_version_id` and retry once by themselves. If you get `409 base_version_mismatch` from any other command, someone created a version meanwhile: read again and retry.
63
+
64
+ ## Questions: when the CLI asks and when it never does
65
+
66
+ The CLI asks a question only if all of this is true: no `--non-interactive` (an AI agent without a terminal gets it on its own), no `--json`, no `CI` variable with a non-empty value, and stdin and stderr are terminals. Questions are drawn on stderr. Otherwise it never asks: it fails with a JSON error that says what to pass.
67
+
68
+ Every question has a flag that replaces it, so an agent never needs one:
69
+
70
+ - A missing id (`laburen agents get`): pass the id. Without it the error is `missing_arguments` with `choices`. If the list cannot be fetched there are no `choices`; if you are not logged in the error is `login_required`.
71
+ - A delete, `tokens revoke` or `agents tools remove`: the confirmation is skipped with `--yes` (`-y`). `agents tools remove` reads the agent first (so it never asks about a tool that does not exist): it needs a session, and without one it fails with `login_required` before `confirmation_required`.
72
+ - `agents create`, `tokens create`, `skills create`, `mcp connections create`: each question is a flag (`--name`, `--kind`, `--permissions`, `--dir`, `--url`, `--skills`, `--mcp-connections`, `--activate`). The full table is in [Commands](references/commands.md#questions-in-create).
73
+ - `agents tools add` and `agents tools remove`: whether to activate the new version is `--activate` or `--no-activate` (without either, the version stays inactive and stderr prints the `agents versions activate` command).
74
+ - `versions compare`: `--from` and `--to`.
75
+ - `orgs switch`: the organization id. Without it the error is `missing_arguments` with `choices`, like a missing id.
76
+ - `--data -` reads the body from stdin, so the CLI cannot ask anything else in that run: a missing required field fails with `missing_required`.
77
+
78
+ What to do with each error when you are an AI agent:
79
+
80
+ - `confirmation_required` (exit 2, `userActionRequired: true`): something would be deleted or revoked. Ask the user. Only if they approve, run the `next` command: it is the same command with `--yes`. **Never add `--yes` on your own.**
81
+ - `missing_arguments` with `choices` (exit 2, `userActionRequired: true`): show the user the `choices` (`{ id, name }`, the current one with `current: true`) and ask which one. Then run the `next` that has that id. **Do not choose yourself**, even if one looks obvious.
82
+ - `cancelled` (exit 1): the person cancelled a question (Ctrl-C, Esc, Ctrl-D, or No at a confirmation). Nothing changed. Do not retry on your own.
83
+ - `config_required` (exit 2): `agents create` got `--skills`, `--mcp-connections` or `--activate` without `--config`. Add `--config` (the `next` shows where) or drop those flags.
84
+ - `<value>` in a `next` command: the value of a secret flag (`--data`, `--headers`, `--config`, `--tool`, `--token`...) is never copied into `next`, in any error. Put the real value back before running it. `<id>` and `<version_id>` are also placeholders: you get them from a `list` or from the user.
85
+
86
+ Commands an agent can run without any question:
87
+
88
+ ```sh
89
+ laburen agents create --name Support --harness-type mastra --config @config.json --json
90
+ laburen tokens create --name worker --kind organization --permissions '["read","write"]' --json
91
+ laburen skills create --name faq --dir ./faq --json
92
+ laburen mcp connections create --name crm --url https://example.com/mcp --headers @headers.json --json
93
+ laburen agents versions compare <agent_id> --from <version_id> --to <version_id> --json
94
+ laburen orgs switch <org_id> --json
95
+ laburen agents delete <agent_id> --json # fails with confirmation_required: ask the user before adding --yes
96
+ ```
97
+
98
+ Read the individual reference documents for details.
99
+
100
+ ## Run an agent
101
+
102
+ `laburen agents run <agent_id> "<message>"` runs one turn. stdout gets the answer text only; tool calls, sources and the footer go to stderr. Add `--json` to wait for the end and read one JSON object (`text`, `memory.thread`, `cost`, `tool_calls`...) on stdout: use it when you are an AI agent. To continue the conversation, pass `--thread <memory.thread>`. `--instructions`, `--model`, `--reasoning` and `--max-steps` replace the agent's settings for that run and need `write` permission. A run costs credits, and Ctrl+C does not stop the turn on the server.
103
+
104
+ ### References
105
+
106
+ - [Commands](references/commands.md) - every command with one example, `agents run`, the confirmation before deleting, picking a missing id and the questions of each `create`.
107
+ - [Auth and organizations](references/auth-and-organizations.md) - login, `LABUREN_TOKEN`, which organization is used, `link.json`, API URL, separate sessions, testing against a local dashboard.
108
+ - [Output and errors](references/output-and-errors.md) - stdout vs stderr, `--json`, `--paginate`, the error JSON with `next`, exit codes, colors.