@laburen/delta-sdk 1.3.0 → 1.5.0-canary.10

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 (150) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +3 -0
  3. package/dist/core/config.d.ts +12 -12
  4. package/dist/core/config.d.ts.map +1 -1
  5. package/dist/core/config.js +88 -88
  6. package/dist/core/config.js.map +1 -1
  7. package/dist/core/{constantes.d.ts → constants.d.ts} +3 -3
  8. package/dist/core/constants.d.ts.map +1 -0
  9. package/dist/core/{constantes.js → constants.js} +3 -3
  10. package/dist/core/constants.js.map +1 -0
  11. package/dist/core/{contadores.d.ts → counters.d.ts} +12 -11
  12. package/dist/core/counters.d.ts.map +1 -0
  13. package/dist/core/counters.js +53 -0
  14. package/dist/core/counters.js.map +1 -0
  15. package/dist/core/{sobre.d.ts → envelope.d.ts} +17 -17
  16. package/dist/core/envelope.d.ts.map +1 -0
  17. package/dist/core/envelope.js +198 -0
  18. package/dist/core/envelope.js.map +1 -0
  19. package/dist/core/scrubbing.d.ts +4 -4
  20. package/dist/core/scrubbing.d.ts.map +1 -1
  21. package/dist/core/scrubbing.js +38 -38
  22. package/dist/core/scrubbing.js.map +1 -1
  23. package/dist/core/{sesion.d.ts → session.d.ts} +2 -2
  24. package/dist/core/session.d.ts.map +1 -0
  25. package/dist/core/{sesion.js → session.js} +2 -2
  26. package/dist/core/session.js.map +1 -0
  27. package/dist/core/{transporte.d.ts → transport.d.ts} +9 -9
  28. package/dist/core/transport.d.ts.map +1 -0
  29. package/dist/core/{transporte.js → transport.js} +15 -15
  30. package/dist/core/transport.js.map +1 -0
  31. package/dist/core/{tipos.d.ts → types.d.ts} +4 -4
  32. package/dist/core/{tipos.d.ts.map → types.d.ts.map} +1 -1
  33. package/dist/core/{tipos.js → types.js} +1 -1
  34. package/dist/core/{tipos.js.map → types.js.map} +1 -1
  35. package/dist/index.d.ts +1 -1
  36. package/dist/platform/client.d.ts +8 -0
  37. package/dist/platform/client.d.ts.map +1 -0
  38. package/dist/platform/client.js +30 -0
  39. package/dist/platform/client.js.map +1 -0
  40. package/dist/platform/core/errors.d.ts +150 -0
  41. package/dist/platform/core/errors.d.ts.map +1 -0
  42. package/dist/platform/core/errors.js +265 -0
  43. package/dist/platform/core/errors.js.map +1 -0
  44. package/dist/platform/core/oauth.d.ts +37 -0
  45. package/dist/platform/core/oauth.d.ts.map +1 -0
  46. package/dist/platform/core/oauth.js +144 -0
  47. package/dist/platform/core/oauth.js.map +1 -0
  48. package/dist/platform/core/pagination.d.ts +30 -0
  49. package/dist/platform/core/pagination.d.ts.map +1 -0
  50. package/dist/platform/core/pagination.js +44 -0
  51. package/dist/platform/core/pagination.js.map +1 -0
  52. package/dist/platform/core/request.d.ts +6 -0
  53. package/dist/platform/core/request.d.ts.map +1 -0
  54. package/dist/platform/core/request.js +24 -0
  55. package/dist/platform/core/request.js.map +1 -0
  56. package/dist/platform/core/send.d.ts +36 -0
  57. package/dist/platform/core/send.d.ts.map +1 -0
  58. package/dist/platform/core/send.js +171 -0
  59. package/dist/platform/core/send.js.map +1 -0
  60. package/dist/platform/core/sse.d.ts +8 -0
  61. package/dist/platform/core/sse.d.ts.map +1 -0
  62. package/dist/platform/core/sse.js +72 -0
  63. package/dist/platform/core/sse.js.map +1 -0
  64. package/dist/platform/core/stream.d.ts +21 -0
  65. package/dist/platform/core/stream.d.ts.map +1 -0
  66. package/dist/platform/core/stream.js +268 -0
  67. package/dist/platform/core/stream.js.map +1 -0
  68. package/dist/platform/generated/resources.d.ts +120 -0
  69. package/dist/platform/generated/resources.d.ts.map +1 -0
  70. package/dist/platform/generated/resources.js +65 -0
  71. package/dist/platform/generated/resources.js.map +1 -0
  72. package/dist/platform/generated/schemas.d.ts +78 -0
  73. package/dist/platform/generated/schemas.d.ts.map +1 -0
  74. package/dist/platform/generated/schemas.js +2 -0
  75. package/dist/platform/generated/schemas.js.map +1 -0
  76. package/dist/platform/generated/types.d.ts +5167 -0
  77. package/dist/platform/generated/types.d.ts.map +1 -0
  78. package/dist/platform/generated/types.js +6 -0
  79. package/dist/platform/generated/types.js.map +1 -0
  80. package/dist/platform/index.d.ts +9 -0
  81. package/dist/platform/index.d.ts.map +1 -0
  82. package/dist/platform/index.js +7 -0
  83. package/dist/platform/index.js.map +1 -0
  84. package/dist/telemetry/{captura.d.ts → capture.d.ts} +3 -3
  85. package/dist/telemetry/capture.d.ts.map +1 -0
  86. package/dist/telemetry/{captura.js → capture.js} +54 -54
  87. package/dist/telemetry/capture.js.map +1 -0
  88. package/dist/telemetry/index.d.ts +2 -2
  89. package/dist/telemetry/index.js +1 -1
  90. package/dist/telemetry/{tipos.d.ts → types.d.ts} +2 -2
  91. package/dist/telemetry/types.d.ts.map +1 -0
  92. package/dist/telemetry/types.js +2 -0
  93. package/dist/telemetry/types.js.map +1 -0
  94. package/dist/telemetry/with-telemetry.d.ts +9 -9
  95. package/dist/telemetry/with-telemetry.d.ts.map +1 -1
  96. package/dist/telemetry/with-telemetry.js +31 -31
  97. package/dist/telemetry/with-telemetry.js.map +1 -1
  98. package/dist/telemetry/with-tool.d.ts +2 -2
  99. package/dist/telemetry/with-tool.d.ts.map +1 -1
  100. package/dist/telemetry/with-tool.js +3 -3
  101. package/dist/telemetry/with-tool.js.map +1 -1
  102. package/docs/platform/guide.md +554 -0
  103. package/docs/telemetry/que-se-manda.md +2 -2
  104. package/docs/telemetry/troubleshooting.md +1 -1
  105. package/package.json +15 -5
  106. package/src/core/config.ts +81 -83
  107. package/src/core/{constantes.ts → constants.ts} +2 -2
  108. package/src/core/counters.ts +72 -0
  109. package/src/core/envelope.ts +234 -0
  110. package/src/core/scrubbing.ts +41 -41
  111. package/src/core/{sesion.ts → session.ts} +1 -1
  112. package/src/core/{transporte.ts → transport.ts} +20 -20
  113. package/src/core/{tipos.ts → types.ts} +3 -3
  114. package/src/index.ts +1 -1
  115. package/src/platform/client.ts +32 -0
  116. package/src/platform/core/errors.ts +348 -0
  117. package/src/platform/core/oauth.ts +201 -0
  118. package/src/platform/core/pagination.ts +67 -0
  119. package/src/platform/core/request.ts +27 -0
  120. package/src/platform/core/send.ts +212 -0
  121. package/src/platform/core/sse.ts +68 -0
  122. package/src/platform/core/stream.ts +314 -0
  123. package/src/platform/generated/resources.ts +192 -0
  124. package/src/platform/generated/schemas.ts +79 -0
  125. package/src/platform/generated/types.ts +5167 -0
  126. package/src/platform/index.ts +45 -0
  127. package/src/telemetry/{captura.ts → capture.ts} +57 -57
  128. package/src/telemetry/index.ts +2 -2
  129. package/src/telemetry/{tipos.ts → types.ts} +1 -1
  130. package/src/telemetry/with-telemetry.ts +51 -54
  131. package/src/telemetry/with-tool.ts +5 -5
  132. package/dist/core/constantes.d.ts.map +0 -1
  133. package/dist/core/constantes.js.map +0 -1
  134. package/dist/core/contadores.d.ts.map +0 -1
  135. package/dist/core/contadores.js +0 -53
  136. package/dist/core/contadores.js.map +0 -1
  137. package/dist/core/sesion.d.ts.map +0 -1
  138. package/dist/core/sesion.js.map +0 -1
  139. package/dist/core/sobre.d.ts.map +0 -1
  140. package/dist/core/sobre.js +0 -200
  141. package/dist/core/sobre.js.map +0 -1
  142. package/dist/core/transporte.d.ts.map +0 -1
  143. package/dist/core/transporte.js.map +0 -1
  144. package/dist/telemetry/captura.d.ts.map +0 -1
  145. package/dist/telemetry/captura.js.map +0 -1
  146. package/dist/telemetry/tipos.d.ts.map +0 -1
  147. package/dist/telemetry/tipos.js +0 -2
  148. package/dist/telemetry/tipos.js.map +0 -1
  149. package/src/core/contadores.ts +0 -71
  150. package/src/core/sobre.ts +0 -236
@@ -1,6 +1,6 @@
1
- import type { TelemetryEvent } from "./tipos.js";
1
+ import type { TelemetryEvent } from "./types.js";
2
2
 
3
- export const REDACTADO = "[redactado]";
3
+ export const REDACTED = "[redactado]";
4
4
 
5
5
  /** Los términos habituales en credenciales: claves, tokens y headers de autorización. */
6
6
  export const DENYLIST = [
@@ -16,13 +16,13 @@ export const DENYLIST = [
16
16
  "private_key",
17
17
  ] as const;
18
18
 
19
- function escaparRegex(termino: string): string {
20
- return termino.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ function escapeRegex(term: string): string {
20
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
21
  }
22
22
 
23
- function claveSospechosa(clave: string, terminos: string[]): boolean {
24
- const bajo = clave.toLowerCase();
25
- return terminos.some((termino) => bajo.includes(termino.toLowerCase()));
23
+ function suspiciousKey(key: string, terms: string[]): boolean {
24
+ const lower = key.toLowerCase();
25
+ return terms.some((term) => lower.includes(term.toLowerCase()));
26
26
  }
27
27
 
28
28
  /** Es una red para descuidos, no una garantía: un secreto en un campo llamado `config` no lo
@@ -36,69 +36,69 @@ function claveSospechosa(clave: string, terminos: string[]): boolean {
36
36
  * tenían ningún secreto. Con `bearer` la apuesta vale la pena porque el 100% de sus apariciones
37
37
  * reales son un header sin dos puntos (`Bearer eyJ…`); con los términos que el propio cliente
38
38
  * pasa por `scrub` también, porque ahí la agresividad es la que pidió explícitamente. */
39
- function redactarTexto(texto: string, completa: readonly string[], agresivos: string[]): string {
40
- let salida = texto;
41
- for (const termino of completa) {
42
- const t = escaparRegex(termino);
39
+ function redactText(text: string, full: readonly string[], aggressive: string[]): string {
40
+ let output = text;
41
+ for (const term of full) {
42
+ const t = escapeRegex(term);
43
43
  // `clave: valor` y `clave=valor`: se borra el resto de la línea, porque el valor puede
44
44
  // tener espacios (`Authorization: Bearer eyJ…`).
45
- salida = salida.replace(new RegExp(`(${t})\\s*[:=]\\s*[^\\n]*`, "gi"), `$1: ${REDACTADO}`);
45
+ output = output.replace(new RegExp(`(${t})\\s*[:=]\\s*[^\\n]*`, "gi"), `$1: ${REDACTED}`);
46
46
  }
47
- for (const termino of agresivos) {
48
- const t = escaparRegex(termino);
47
+ for (const term of aggressive) {
48
+ const t = escapeRegex(term);
49
49
  // `clave valor`: solo el token que sigue, y solo para `bearer` y los términos del cliente
50
50
  // (ver el comentario de arriba). No matchea una mención suelta al final de la frase, que
51
51
  // no tiene nada detrás.
52
- salida = salida.replace(new RegExp(`(${t})\\s+(\\S+)`, "gi"), `$1 ${REDACTADO}`);
52
+ output = output.replace(new RegExp(`(${t})\\s+(\\S+)`, "gi"), `$1 ${REDACTED}`);
53
53
  }
54
- return salida;
54
+ return output;
55
55
  }
56
56
 
57
57
  /** Devuelve una copia con la denylist y los términos del cliente aplicados. No muta la entrada:
58
58
  * el evento original es el que ve el implementador si algo falla después. */
59
- export function scrubEvento(evento: TelemetryEvent, extra: string[] = []): TelemetryEvent {
60
- const terminos = [...DENYLIST, ...extra];
59
+ export function scrubEvent(event: TelemetryEvent, extra: string[] = []): TelemetryEvent {
60
+ const terms = [...DENYLIST, ...extra];
61
61
  // La regla sin separador solo corre para `bearer` (headers reales sin dos puntos) y lo que el
62
62
  // cliente mismo eligió redactar así: el resto de la denylist es prosa común, no un valor.
63
- const agresivos = ["bearer", ...extra];
64
- const salida: TelemetryEvent = { ...evento };
63
+ const aggressive = ["bearer", ...extra];
64
+ const output: TelemetryEvent = { ...event };
65
65
 
66
- if (salida.message !== undefined) {
67
- salida.message = redactarTexto(salida.message, terminos, agresivos);
66
+ if (output.message !== undefined) {
67
+ output.message = redactText(output.message, terms, aggressive);
68
68
  }
69
69
 
70
- if (salida.exception !== undefined) {
71
- const excepcion = { ...salida.exception };
72
- if (excepcion.message !== undefined) {
73
- excepcion.message = redactarTexto(excepcion.message, terminos, agresivos);
70
+ if (output.exception !== undefined) {
71
+ const exception = { ...output.exception };
72
+ if (exception.message !== undefined) {
73
+ exception.message = redactText(exception.message, terms, aggressive);
74
74
  }
75
- if (excepcion.stacktrace !== undefined) {
76
- excepcion.stacktrace = redactarTexto(excepcion.stacktrace, terminos, agresivos);
75
+ if (exception.stacktrace !== undefined) {
76
+ exception.stacktrace = redactText(exception.stacktrace, terms, aggressive);
77
77
  }
78
- salida.exception = excepcion;
78
+ output.exception = exception;
79
79
  }
80
80
 
81
- if (salida.attributes !== undefined) {
82
- const atributos: Record<string, string | number | boolean> = {};
83
- for (const [clave, valor] of Object.entries(salida.attributes)) {
84
- atributos[clave] = claveSospechosa(clave, terminos) ? REDACTADO : valor;
81
+ if (output.attributes !== undefined) {
82
+ const scrubbedAttrs: Record<string, string | number | boolean> = {};
83
+ for (const [key, value] of Object.entries(output.attributes)) {
84
+ scrubbedAttrs[key] = suspiciousKey(key, terms) ? REDACTED : value;
85
85
  }
86
- salida.attributes = atributos;
86
+ output.attributes = scrubbedAttrs;
87
87
  }
88
88
 
89
- return salida;
89
+ return output;
90
90
  }
91
91
 
92
92
  /** El escape hatch. Un `null` descarta el evento; una excepción no puede hacerlo perder. */
93
- export function aplicarBeforeSend(
94
- evento: TelemetryEvent,
95
- beforeSend: ((evento: TelemetryEvent) => TelemetryEvent | null) | undefined,
93
+ export function applyBeforeSend(
94
+ event: TelemetryEvent,
95
+ beforeSend: ((event: TelemetryEvent) => TelemetryEvent | null) | undefined,
96
96
  ): TelemetryEvent | null {
97
- if (beforeSend === undefined) return evento;
97
+ if (beforeSend === undefined) return event;
98
98
  try {
99
- return beforeSend(evento);
99
+ return beforeSend(event);
100
100
  } catch (error) {
101
101
  console.error("[delta-sdk] beforeSend lanzó; el evento se manda sin aplicarlo", error);
102
- return evento;
102
+ return event;
103
103
  }
104
104
  }
@@ -16,7 +16,7 @@ export function nextSeq(): number {
16
16
  }
17
17
 
18
18
  /** Solo para los tests. No sale por ninguna puerta del `exports` map. */
19
- export function reiniciarSesion(): void {
19
+ export function resetSession(): void {
20
20
  _session = null;
21
21
  _seq = 0;
22
22
  }
@@ -1,10 +1,10 @@
1
- import { contarCompletado, contarDisparado, contarFallado } from "./contadores.js";
2
- import type { CtxLike } from "./tipos.js";
1
+ import { countCompleted, countFailed, countFired } from "./counters.js";
2
+ import type { CtxLike } from "./types.js";
3
3
 
4
4
  /** El texto completo del aviso: dice qué pasó, qué consecuencia tiene y cómo arreglarlo. Sin este
5
5
  * aviso el evento se pierde en silencio en `worker` y `queue`, que es exactamente el modo de
6
6
  * falla que este paquete existe para eliminar. */
7
- export const AVISO_CTX_ROTO = [
7
+ export const BROKEN_CTX_WARNING = [
8
8
  "[delta-sdk] El `ctx` recibido tiene `waitUntil` pero no es invocable: parece una copia",
9
9
  "hecha con spread u Object.create (patrón habitual para inyectar `props` en un McpAgent).",
10
10
  "Los eventos se van a PERDER en surface 'worker' y 'queue'. Pasale a createTelemetry el",
@@ -12,27 +12,27 @@ export const AVISO_CTX_ROTO = [
12
12
  "el McpAgent, son dos consumidores distintos.",
13
13
  ].join(" ");
14
14
 
15
- export interface CtxUsable {
15
+ export interface UsableCtx {
16
16
  waitUntil: (p: Promise<unknown>) => void;
17
17
  }
18
18
 
19
19
  /** Lo prueba UNA vez, con una promesa ya resuelta. No alcanza con preguntar si `waitUntil`
20
20
  * existe: la copia del ctx hereda el método pero no la identidad del objeto nativo, así que
21
21
  * existe y tira `Illegal invocation` al invocarlo. */
22
- export function probarCtx(ctx: CtxLike | undefined, avisar: () => void): CtxUsable | null {
22
+ export function probeCtx(ctx: CtxLike | undefined, warn: () => void): UsableCtx | null {
23
23
  if (typeof ctx?.waitUntil !== "function") return null;
24
24
  try {
25
25
  ctx.waitUntil(Promise.resolve());
26
- return ctx as CtxUsable;
26
+ return ctx as UsableCtx;
27
27
  } catch {
28
- avisar();
28
+ warn();
29
29
  return null;
30
30
  }
31
31
  }
32
32
 
33
33
  /** El 401 no queda detrás de `debug`: es config rota y hay que verla. Los demás status solo
34
34
  * hablan en debug, porque el SDK no reintenta en ninguno. */
35
- function reportar(status: number, debug: boolean): void {
35
+ function report(status: number, debug: boolean): void {
36
36
  if (status === 401) {
37
37
  console.error(
38
38
  "[delta-sdk] la ingesta rechazó el bearer (401): revisá el apiKey del env, no se va a reportar nada",
@@ -46,21 +46,21 @@ function reportar(status: number, debug: boolean): void {
46
46
  }
47
47
  }
48
48
 
49
- export interface ArgsEnvio {
49
+ export interface SendArgs {
50
50
  body: string;
51
51
  apiKey: string;
52
52
  url: string;
53
- ctx: CtxUsable | null;
53
+ ctx: UsableCtx | null;
54
54
  debug: boolean;
55
- avisarCtxRoto: () => void;
55
+ warnBrokenCtx: () => void;
56
56
  }
57
57
 
58
58
  /** Dispara el POST y no espera nada. No reintenta, no lanza, y la promesa que le pasa a
59
59
  * `waitUntil` nunca rechaza. */
60
- export function enviar(args: ArgsEnvio): void {
61
- contarDisparado();
60
+ export function send(args: SendArgs): void {
61
+ countFired();
62
62
 
63
- const promesa = fetch(args.url, {
63
+ const promise = fetch(args.url, {
64
64
  method: "POST",
65
65
  headers: {
66
66
  Authorization: `Bearer ${args.apiKey}`,
@@ -69,14 +69,14 @@ export function enviar(args: ArgsEnvio): void {
69
69
  body: args.body,
70
70
  })
71
71
  .then(
72
- (respuesta) => {
72
+ (response) => {
73
73
  // Cualquier status es "salió y contestaron": el 429 y el 503 no son pérdida.
74
- contarCompletado();
75
- reportar(respuesta.status, args.debug);
74
+ countCompleted();
75
+ report(response.status, args.debug);
76
76
  },
77
77
  () => {
78
78
  // Solo la red y el DNS llegan acá. Nunca se re-lanza.
79
- contarFallado();
79
+ countFailed();
80
80
  },
81
81
  )
82
82
  .catch(() => {
@@ -85,9 +85,9 @@ export function enviar(args: ArgsEnvio): void {
85
85
  });
86
86
 
87
87
  try {
88
- args.ctx?.waitUntil(promesa);
88
+ args.ctx?.waitUntil(promise);
89
89
  } catch {
90
90
  // Segundo chequeo, por las dudas: el SDK nunca lanza. La promesa queda flotando.
91
- args.avisarCtxRoto();
91
+ args.warnBrokenCtx();
92
92
  }
93
93
  }
@@ -58,7 +58,7 @@ export interface Envelope {
58
58
  events: [TelemetryEvent];
59
59
  }
60
60
 
61
- /** Los números del reintento, en camelCase porque es API pública; `sobre.ts` los mapea a
61
+ /** Los números del reintento, en camelCase porque es API pública; `envelope.ts` los mapea a
62
62
  * snake_case. Si no viene `isFinalAttempt` se calcula como `attempt >= limit`. */
63
63
  export interface RetryInfo {
64
64
  attempt?: number;
@@ -103,7 +103,7 @@ export interface TelemetryConfig {
103
103
  /** SOLO desarrollo local. En producción la URL es constante del paquete. */
104
104
  ingestUrl?: string;
105
105
  scrub?: string[];
106
- beforeSend?: (evento: TelemetryEvent) => TelemetryEvent | null;
106
+ beforeSend?: (event: TelemetryEvent) => TelemetryEvent | null;
107
107
  debug?: boolean;
108
108
  /** El MISMO número, con el mismo nombre, que el `max_retries` del wrangler.jsonc del
109
109
  * consumer. El SDK le suma 1 porque son los reintentos DESPUÉS de la primera entrega, y
@@ -125,7 +125,7 @@ export interface TelemetryClient {
125
125
  captureEvent(message: string, options?: CaptureOptions): void;
126
126
  /** Envuelve una tool de MCP: captura y re-lanza el mismo error. */
127
127
  withTool<Args extends unknown[], R>(
128
- nombre: string,
128
+ name: string,
129
129
  fn: (...args: Args) => R | Promise<R>,
130
130
  ): (...args: Args) => Promise<R>;
131
131
  }
package/src/index.ts CHANGED
@@ -4,4 +4,4 @@ export type {
4
4
  Severity,
5
5
  Surface,
6
6
  TelemetryEvent,
7
- } from "./core/tipos.js";
7
+ } from "./core/types.js";
@@ -0,0 +1,32 @@
1
+ import { LaburenArgumentError } from "./core/errors.js";
2
+ import { type Page, type PageCursor, PagePromise } from "./core/pagination.js";
3
+ import { createCall } from "./core/request.js";
4
+ import type { PlatformConfig } from "./core/send.js";
5
+ import { buildResources, type Call, type Resources } from "./generated/resources.js";
6
+
7
+ /** Los cursores que pasó quien llama; el que no se usó se descarta en cada pedido. */
8
+ function initialCursor(params: Record<string, unknown> | undefined): PageCursor {
9
+ if (typeof params?.before_id === "string") return { before_id: params.before_id };
10
+ if (typeof params?.after_id === "string") return { after_id: params.after_id };
11
+ return {};
12
+ }
13
+
14
+ /**
15
+ * Crea el cliente de la puerta `/platform`. No hace ningún pedido al crearse: crealo adentro
16
+ * del handler, nunca en el scope global.
17
+ */
18
+ export function createPlatform(config: PlatformConfig): Resources {
19
+ if (config.token === "") throw new LaburenArgumentError("The token must not be empty.");
20
+ const request = createCall(config);
21
+ const call: Call = (spec, pathValues, params, options) => {
22
+ if (!spec.paginated) return request(spec, pathValues, params, options);
23
+ // `limit` y el resto de `params` se repiten en cada página; el cursor lo pone la paginación.
24
+ const { after_id: _after, before_id: _before, ...rest } = params ?? {};
25
+ return new PagePromise(
26
+ (cursor) =>
27
+ request(spec, pathValues, { ...rest, ...cursor }, options) as Promise<Page<unknown>>,
28
+ initialCursor(params),
29
+ );
30
+ };
31
+ return buildResources(call);
32
+ }
@@ -0,0 +1,348 @@
1
+ import type { components } from "../generated/types.js";
2
+
3
+ /** Código del catálogo de la API; acepta cualquier string para que un código nuevo no rompa un SDK viejo. */
4
+ export type ErrorCode = components["schemas"]["Error"]["error"]["code"] | (string & {});
5
+ /** Familia del error; mismo criterio que `ErrorCode`. */
6
+ export type ErrorType = components["schemas"]["Error"]["error"]["type"] | (string & {});
7
+
8
+ const API_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/api-error");
9
+ const CONNECTION_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/connection-error");
10
+ const TIMEOUT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/timeout-error");
11
+ const ABORT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/abort-error");
12
+ const OAUTH_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/oauth-error");
13
+ const ARGUMENT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/argument-error");
14
+
15
+ /**
16
+ * Los valores de `details`, como los declara el contrato: una lista de ids (`agent_ids` de `resource_in_use`) llega como
17
+ * `string[]` y una lista de objetos (`agent_versions`) como `Array<Record<...>>`.
18
+ */
19
+ export type ErrorDetails = Record<
20
+ string,
21
+ | string
22
+ | number
23
+ | boolean
24
+ | null
25
+ | string[]
26
+ | Array<Record<string, string | number | boolean | null>>
27
+ >;
28
+ type ErrorIssues = Array<{ field: string; message: string }>;
29
+
30
+ /** Lo que hace falta para armar un error de la API a partir de una respuesta. */
31
+ export interface LaburenApiErrorInit {
32
+ status: number;
33
+ message: string;
34
+ type?: ErrorType | null;
35
+ code?: ErrorCode | null;
36
+ details?: ErrorDetails;
37
+ issues?: ErrorIssues;
38
+ requestId?: string | null;
39
+ shouldRetry?: boolean | null;
40
+ }
41
+
42
+ /** Error que devolvió la API (cualquier status no exitoso con cuerpo del catálogo o sin él). */
43
+ export class LaburenApiError extends Error {
44
+ readonly status: number;
45
+ readonly type: ErrorType | null;
46
+ readonly code: ErrorCode | null;
47
+ readonly details: ErrorDetails;
48
+ readonly issues: ErrorIssues;
49
+ readonly requestId: string | null;
50
+ readonly shouldRetry: boolean | null;
51
+ declare readonly [API_ERROR_BRAND]: true;
52
+
53
+ constructor(init: LaburenApiErrorInit) {
54
+ super(init.message);
55
+ this.name = "LaburenApiError";
56
+ this.status = init.status;
57
+ this.type = init.type ?? null;
58
+ this.code = init.code ?? null;
59
+ this.details = init.details ?? {};
60
+ this.issues = init.issues ?? [];
61
+ this.requestId = init.requestId ?? null;
62
+ this.shouldRetry = init.shouldRetry ?? null;
63
+ Object.defineProperty(this, API_ERROR_BRAND, { value: true });
64
+ }
65
+ }
66
+
67
+ /** 400: el pedido es inválido. */
68
+ export class InvalidRequestError extends LaburenApiError {
69
+ constructor(init: LaburenApiErrorInit) {
70
+ super(init);
71
+ this.name = "InvalidRequestError";
72
+ }
73
+ }
74
+ /** 401: token faltante o inválido. */
75
+ export class AuthenticationError extends LaburenApiError {
76
+ constructor(init: LaburenApiErrorInit) {
77
+ super(init);
78
+ this.name = "AuthenticationError";
79
+ }
80
+ }
81
+ /** Sin créditos o problema de facturación. */
82
+ export class BillingError extends LaburenApiError {
83
+ constructor(init: LaburenApiErrorInit) {
84
+ super(init);
85
+ this.name = "BillingError";
86
+ }
87
+ }
88
+ /** 403: el token no puede hacer esto. */
89
+ export class PermissionError extends LaburenApiError {
90
+ constructor(init: LaburenApiErrorInit) {
91
+ super(init);
92
+ this.name = "PermissionError";
93
+ }
94
+ }
95
+ /** 404: el recurso no existe. */
96
+ export class NotFoundError extends LaburenApiError {
97
+ constructor(init: LaburenApiErrorInit) {
98
+ super(init);
99
+ this.name = "NotFoundError";
100
+ }
101
+ }
102
+ /** 409: choca con el estado actual del recurso. */
103
+ export class ConflictError extends LaburenApiError {
104
+ constructor(init: LaburenApiErrorInit) {
105
+ super(init);
106
+ this.name = "ConflictError";
107
+ }
108
+ }
109
+ /** 429: demasiados pedidos. */
110
+ export class RateLimitError extends LaburenApiError {
111
+ constructor(init: LaburenApiErrorInit) {
112
+ super(init);
113
+ this.name = "RateLimitError";
114
+ }
115
+ }
116
+ /** 5xx: falló el servidor. */
117
+ export class ApiError extends LaburenApiError {
118
+ constructor(init: LaburenApiErrorInit) {
119
+ super(init);
120
+ this.name = "ApiError";
121
+ }
122
+ }
123
+ /** Servicio sobrecargado o dependencia caída. */
124
+ export class OverloadedError extends LaburenApiError {
125
+ constructor(init: LaburenApiErrorInit) {
126
+ super(init);
127
+ this.name = "OverloadedError";
128
+ }
129
+ }
130
+
131
+ /** No se pudo hablar con el servidor (red, DNS, corte). */
132
+ export class LaburenConnectionError extends Error {
133
+ declare readonly [CONNECTION_ERROR_BRAND]: true;
134
+
135
+ constructor(message: string, options?: { cause?: unknown }) {
136
+ super(message, options);
137
+ this.name = "LaburenConnectionError";
138
+ Object.defineProperty(this, CONNECTION_ERROR_BRAND, { value: true });
139
+ }
140
+ }
141
+
142
+ /** El servidor no contestó a tiempo. */
143
+ export class LaburenTimeoutError extends LaburenConnectionError {
144
+ declare readonly [TIMEOUT_ERROR_BRAND]: true;
145
+
146
+ constructor(message: string, options?: { cause?: unknown }) {
147
+ super(message, options);
148
+ this.name = "LaburenTimeoutError";
149
+ Object.defineProperty(this, TIMEOUT_ERROR_BRAND, { value: true });
150
+ }
151
+ }
152
+
153
+ /** El llamador cortó la operación con su `signal`; el motivo de la señal queda en `cause`. No es un problema de red. */
154
+ export class LaburenAbortError extends Error {
155
+ declare readonly [ABORT_ERROR_BRAND]: true;
156
+
157
+ constructor(options?: { cause?: unknown }) {
158
+ super("Request was aborted.", options);
159
+ this.name = "LaburenAbortError";
160
+ Object.defineProperty(this, ABORT_ERROR_BRAND, { value: true });
161
+ }
162
+ }
163
+
164
+ /** El llamador pasó un argumento que no sirve (un id vacío, un token vacío); se lanza antes de mandar nada. */
165
+ export class LaburenArgumentError extends Error {
166
+ declare readonly [ARGUMENT_ERROR_BRAND]: true;
167
+
168
+ constructor(message: string) {
169
+ super(message);
170
+ this.name = "LaburenArgumentError";
171
+ Object.defineProperty(this, ARGUMENT_ERROR_BRAND, { value: true });
172
+ }
173
+ }
174
+
175
+ /** Error del flujo OAuth (formato RFC 6749: `error` y `error_description`). */
176
+ export class LaburenOAuthError extends Error {
177
+ readonly error: string;
178
+ readonly description: string | null;
179
+ readonly status: number;
180
+ declare readonly [OAUTH_ERROR_BRAND]: true;
181
+
182
+ constructor(init: { error: string; description?: string | null; status: number }) {
183
+ super(init.description ? `${init.error}: ${init.description}` : init.error);
184
+ this.name = "LaburenOAuthError";
185
+ this.error = init.error;
186
+ this.description = init.description ?? null;
187
+ this.status = init.status;
188
+ Object.defineProperty(this, OAUTH_ERROR_BRAND, { value: true });
189
+ }
190
+ }
191
+
192
+ function hasBrand(value: unknown, brand: symbol): boolean {
193
+ return (
194
+ typeof value === "object" &&
195
+ value !== null &&
196
+ (value as Record<symbol, unknown>)[brand] === true
197
+ );
198
+ }
199
+
200
+ /** Dice si es un error de la API, también el de otra copia del paquete (por marca, no por `instanceof`). */
201
+ export function isLaburenApiError(value: unknown): value is LaburenApiError {
202
+ return hasBrand(value, API_ERROR_BRAND);
203
+ }
204
+ /** Dice si es un error de conexión (un timeout también lo es). */
205
+ export function isLaburenConnectionError(value: unknown): value is LaburenConnectionError {
206
+ return hasBrand(value, CONNECTION_ERROR_BRAND);
207
+ }
208
+ /** Dice si es un error de timeout. */
209
+ export function isLaburenTimeoutError(value: unknown): value is LaburenTimeoutError {
210
+ return hasBrand(value, TIMEOUT_ERROR_BRAND);
211
+ }
212
+ /** Dice si es un error por haber abortado con `signal`. */
213
+ export function isLaburenAbortError(value: unknown): value is LaburenAbortError {
214
+ return hasBrand(value, ABORT_ERROR_BRAND);
215
+ }
216
+ /** Dice si es un error por un argumento inválido. */
217
+ export function isLaburenArgumentError(value: unknown): value is LaburenArgumentError {
218
+ return hasBrand(value, ARGUMENT_ERROR_BRAND);
219
+ }
220
+ /** Dice si es un error de OAuth. */
221
+ export function isLaburenOAuthError(value: unknown): value is LaburenOAuthError {
222
+ return hasBrand(value, OAUTH_ERROR_BRAND);
223
+ }
224
+
225
+ /** Una versión de agente que bloquea el borrado de una skill o una conexión MCP (`details.agent_versions` de `resource_in_use`). */
226
+ export interface ResourceInUseVersion {
227
+ agent_id: string;
228
+ version_id: string;
229
+ is_active: boolean;
230
+ }
231
+
232
+ function isResourceInUseVersion(value: unknown): value is ResourceInUseVersion {
233
+ if (!isRecord(value)) return false;
234
+ return (
235
+ typeof value.agent_id === "string" &&
236
+ typeof value.version_id === "string" &&
237
+ typeof value.is_active === "boolean"
238
+ );
239
+ }
240
+
241
+ /**
242
+ * Las versiones de agente que bloquean el borrado, si `error` es un `resource_in_use`; en cualquier otro caso, una lista
243
+ * vacía. Descarta las entradas que no tienen la forma `{ agent_id, version_id, is_active }`, así el resultado se usa sin casts.
244
+ */
245
+ export function resourceInUseVersions(error: unknown): ResourceInUseVersion[] {
246
+ if (!isLaburenApiError(error) || error.code !== "resource_in_use") return [];
247
+ const list: unknown = error.details.agent_versions;
248
+ return Array.isArray(list) ? list.filter(isResourceInUseVersion) : [];
249
+ }
250
+
251
+ type FamilyClass = new (init: LaburenApiErrorInit) => LaburenApiError;
252
+
253
+ const FAMILIES: Record<components["schemas"]["Error"]["error"]["type"], FamilyClass> = {
254
+ invalid_request_error: InvalidRequestError,
255
+ authentication_error: AuthenticationError,
256
+ billing_error: BillingError,
257
+ permission_error: PermissionError,
258
+ not_found_error: NotFoundError,
259
+ conflict_error: ConflictError,
260
+ rate_limit_error: RateLimitError,
261
+ api_error: ApiError,
262
+ overloaded_error: OverloadedError,
263
+ };
264
+
265
+ function isRecord(value: unknown): value is Record<string, unknown> {
266
+ return typeof value === "object" && value !== null && !Array.isArray(value);
267
+ }
268
+
269
+ function parseShouldRetry(headers: Headers): boolean | null {
270
+ const raw = headers.get("x-should-retry");
271
+ if (raw === "true") return true;
272
+ if (raw === "false") return false;
273
+ return null;
274
+ }
275
+
276
+ /** Arma el error de la familia que dice `init.type`; un tipo que el SDK no conoce da el `LaburenApiError` base. */
277
+ export function apiErrorFromFamily(init: LaburenApiErrorInit): LaburenApiError {
278
+ const Family =
279
+ typeof init.type === "string" && Object.hasOwn(FAMILIES, init.type)
280
+ ? FAMILIES[init.type as keyof typeof FAMILIES]
281
+ : LaburenApiError;
282
+ return new Family(init);
283
+ }
284
+
285
+ /** Status HTTP de cada familia (mismo mapa que usa la API); un type que el SDK no conoce da 500. */
286
+ const STATUS_BY_TYPE: Record<keyof typeof FAMILIES, number> = {
287
+ invalid_request_error: 400,
288
+ authentication_error: 401,
289
+ billing_error: 402,
290
+ permission_error: 403,
291
+ not_found_error: 404,
292
+ conflict_error: 409,
293
+ rate_limit_error: 429,
294
+ api_error: 500,
295
+ overloaded_error: 529,
296
+ };
297
+
298
+ /** Dice si `type` es una familia que el SDK conoce. */
299
+ export function isKnownErrorType(type: string | undefined): boolean {
300
+ return typeof type === "string" && Object.hasOwn(STATUS_BY_TYPE, type);
301
+ }
302
+
303
+ /** Status que corresponde a la familia `type`; sin familia conocida, 500. */
304
+ export function statusForErrorType(type: string | undefined): number {
305
+ return isKnownErrorType(type) ? STATUS_BY_TYPE[type as keyof typeof STATUS_BY_TYPE] : 500;
306
+ }
307
+
308
+ /** Arma el error tipado de una respuesta no exitosa; sin cuerpo del catálogo devuelve el base con `type` y `code` en null. */
309
+ export function apiErrorFromResponse(
310
+ status: number,
311
+ body: unknown,
312
+ headers: Headers,
313
+ ): LaburenApiError {
314
+ const shouldRetry = parseShouldRetry(headers);
315
+ const headerRequestId = headers.get("request-id");
316
+ const inner = isRecord(body) ? body.error : undefined;
317
+
318
+ if (
319
+ !isRecord(inner) ||
320
+ typeof inner.type !== "string" ||
321
+ typeof inner.code !== "string" ||
322
+ typeof inner.message !== "string"
323
+ ) {
324
+ return new LaburenApiError({
325
+ status,
326
+ message: `Error response without the expected format (status ${status}).`,
327
+ requestId: headerRequestId,
328
+ shouldRetry,
329
+ });
330
+ }
331
+
332
+ const requestId =
333
+ isRecord(body) && typeof body.request_id === "string" ? body.request_id : headerRequestId;
334
+ const init: LaburenApiErrorInit = {
335
+ status,
336
+ message: inner.message,
337
+ type: inner.type,
338
+ code: inner.code,
339
+ details: isRecord(inner.details) ? (inner.details as ErrorDetails) : {},
340
+ issues: Array.isArray(inner.issues) ? (inner.issues as ErrorIssues) : [],
341
+ requestId,
342
+ shouldRetry,
343
+ };
344
+ const Family = Object.hasOwn(FAMILIES, inner.type)
345
+ ? FAMILIES[inner.type as keyof typeof FAMILIES]
346
+ : LaburenApiError;
347
+ return new Family(init);
348
+ }