hobots 1.0.0 → 1.1.0

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.
package/dist/index.d.ts CHANGED
@@ -1,25 +1,58 @@
1
1
  import { Severity, EventPayload, Breadcrumb, EventUser, TransactionPayload, CheckInPayload, HeartbeatPayload, SpanData, CheckInStatus } from './protocol.js';
2
2
  export { Envelope, EnvelopeItem, ExceptionData, StackFrame } from './protocol.js';
3
- import { L as Logger } from './utils-LReLqjzN.js';
3
+ import { RunLogLevel, ManagerPollRequest, ManagerPollResponse, ManagerRunUpdateRequest } from './manager/protocol.js';
4
+ export { ManagerAgentInfo, ManagerRunDescriptor, ManagerRunError, ManagerRunStatus, ManagerRunUpdateResponse, ManagerRunUpdateStatus, RunLogEntry } from './manager/protocol.js';
5
+
6
+ /** Opções do Manager dentro de `init({ manager: ... })`. DSN, identidade (instanceId) e debug vêm do init. */
7
+ interface ManagerOptions {
8
+ /** Intervalo entre polls sem trabalho. Default: 5_000 (mínimo 1_000) */
9
+ pollIntervalMs?: number;
10
+ /** Runs simultâneas (1..5). Default: 1 (sequencial) */
11
+ concurrency?: number;
12
+ /**
13
+ * Timeout client-side por run. O handler não é morto — a run é reportada como
14
+ * falha e o slot é liberado. Default: sem timeout (o servidor é o backstop).
15
+ */
16
+ taskTimeoutMs?: number;
17
+ /** Intervalo do flush incremental de logs. Default: 2_000 */
18
+ logFlushIntervalMs?: number;
19
+ }
20
+ /** Opções resolvidas pelo init unificado e entregues ao ManagerAgent. */
21
+ interface ManagerAgentOptions extends ManagerOptions {
22
+ /** A DSN única do projeto — a mesma do Monitor */
23
+ dsn: string;
24
+ /** Identidade do agente no dashboard — o instanceId do init */
25
+ instanceId: string;
26
+ /** Loga atividade do SDK no console */
27
+ debug?: boolean;
28
+ }
29
+ interface RunContext {
30
+ runId: string;
31
+ task: string;
32
+ /** Log bufferizado — enviado ao servidor em PATCHes incrementais com throttle */
33
+ log(level: RunLogLevel, message: string): void;
34
+ /** Dispara em cancelamento (run cancelada no app), timeout ou shutdown — cancelamento cooperativo */
35
+ signal: AbortSignal;
36
+ }
37
+ /** O retorno do handler é ignorado — nada além de status/logs/erro é enviado ao servidor. */
38
+ type ManagerTaskHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
4
39
 
5
40
  interface HeartbeatOptions {
6
41
  /** Intervalo entre batimentos. Default: 30_000 */
7
42
  intervalMs?: number;
8
- /** Identificador estável da instância (default: serverName, HOSTNAME ou id aleatório por processo) */
9
- instanceId?: string;
10
- /** Nome amigável exibido no dashboard */
43
+ /** Nome amigável exibido no dashboard. Default: o instanceId do init */
11
44
  name?: string;
12
45
  metadata?: Record<string, unknown>;
13
46
  }
14
47
  interface InitOptions {
15
- /** Ex.: https://<publicKey>@monitor.hobots.app/<projectId> */
48
+ /** A DSN única do projeto — a mesma para Monitor e Manager. Ex.: https://<secretKey>@app.hobots.app/<projeto> */
16
49
  dsn: string;
17
50
  /** Default: 'production' */
18
51
  environment?: string;
19
52
  /** Versão do programa, ex.: 'robo-nfe@1.4.2' */
20
53
  release?: string;
21
- /** Nome da máquina/instância; também usado como instanceId do heartbeat */
22
- serverName?: string;
54
+ /** Identificador único e estável desta instância — a identidade do agente no painel (heartbeat do Monitor e agente do Manager convergem nele) */
55
+ instanceId: string;
23
56
  /** Tags aplicadas a todos os eventos */
24
57
  tags?: Record<string, string>;
25
58
  /** Amostragem de eventos de erro (0..1). Default: 1 */
@@ -32,6 +65,11 @@ interface InitOptions {
32
65
  captureUnhandled?: boolean;
33
66
  /** Habilita heartbeat periódico (true usa defaults) */
34
67
  heartbeat?: boolean | HeartbeatOptions;
68
+ /**
69
+ * Habilita o agente Manager — execução remota de tarefas sob demanda (true usa defaults).
70
+ * Usa a mesma DSN e o instanceId como identidade. Depois de init(), chame register() e start().
71
+ */
72
+ manager?: boolean | ManagerOptions;
35
73
  /** Última chance de editar/descartar um evento (retorne null para descartar) */
36
74
  beforeSend?: (event: EventPayload) => EventPayload | null;
37
75
  /** Loga atividade do SDK no console */
@@ -49,12 +87,20 @@ interface CaptureHint {
49
87
  }
50
88
 
51
89
  interface ParsedDsn {
52
- publicKey: string;
53
- projectId: string;
54
- /** URL de ingestão derivada: <origin>/api/ingest/<publicKey> */
55
- endpoint: string;
90
+ /** Chave secreta do projeto (enviada como Authorization: Bearer, nunca na URL) */
91
+ key: string;
92
+ /** Slug do projeto (informativo — a identidade real vem da chave) */
93
+ projectSlug: string;
94
+ origin: string;
95
+ /** Ingestão do Monitor: <origin>/api/ingest */
96
+ ingestEndpoint: string;
97
+ /** API do Manager: <origin>/api/manager */
98
+ managerBaseUrl: string;
56
99
  }
57
- /** Formato: https://<publicKey>@host[:porta]/<projectId> */
100
+ /**
101
+ * A DSN única do projeto Hobots — a mesma para Monitor e Manager.
102
+ * Formato: https://<secretKey>@host[:porta]/<projectSlug>
103
+ */
58
104
  declare function parseDsn(dsn: string): ParsedDsn;
59
105
 
60
106
  type BreadcrumbInput = Omit<Breadcrumb, 'timestamp'> & {
@@ -82,6 +128,12 @@ declare class Scope {
82
128
  clone(): Scope;
83
129
  }
84
130
 
131
+ interface Logger {
132
+ debug: (...args: unknown[]) => void;
133
+ warn: (...args: unknown[]) => void;
134
+ error: (...args: unknown[]) => void;
135
+ }
136
+
85
137
  declare class Client {
86
138
  readonly options: InitOptions;
87
139
  readonly dsn: ParsedDsn;
@@ -181,7 +233,80 @@ declare function checkIn(options: CheckInOptions): string | undefined;
181
233
  declare function withMonitor<T>(monitorSlug: string, fn: () => T | Promise<T>, options?: WithMonitorOptions): Promise<T>;
182
234
  /** Aguarda o envio de tudo que está na fila (até timeoutMs). */
183
235
  declare function flush(timeoutMs?: number): Promise<boolean>;
184
- /** Flush final + encerra heartbeat e transport. Chame antes do processo terminar. */
236
+ /** Registra o handler de uma task do Manager (o task_slug configurado no formulário do app). */
237
+ declare function register<P = Record<string, unknown>>(task: string, handler: ManagerTaskHandler<P>): void;
238
+ /**
239
+ * Inicia o polling do Manager. O timer NÃO é unref'd: o processo fica vivo
240
+ * aguardando trabalho até stop()/close() — o inverso deliberado do Monitor.
241
+ */
242
+ declare function start(): void;
243
+ /** Para só o Manager: encerra o polling e aguarda as runs ativas (até timeoutMs). A telemetria continua. */
244
+ declare function stop(timeoutMs?: number): Promise<boolean>;
245
+ /**
246
+ * Encerra tudo: para o Manager (aguardando runs em voo), o heartbeat e faz o
247
+ * flush final do transport. Chame antes do processo terminar.
248
+ */
185
249
  declare function close(timeoutMs?: number): Promise<boolean>;
186
250
 
187
- export { Breadcrumb, type BreadcrumbInput, type CaptureHint, type CheckInOptions, CheckInPayload, CheckInStatus, Client, EventPayload, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, type ParsedDsn, Scope, Severity, Span, SpanData, Transaction, TransactionPayload, type WithMonitorOptions, addBreadcrumb, captureException, captureMessage, checkIn, close, flush, getClient, init, parseDsn, setContext, setExtra, setTag, setTags, setUser, startTransaction, withMonitor, withScope };
251
+ /**
252
+ * Loop de polling do Manager: busca runs pendentes, executa os handlers registrados
253
+ * e reporta status/logs/result. Ao contrário do Monitor, o timer de polling NÃO é
254
+ * unref'd — um agente iniciado mantém o processo vivo até stop().
255
+ */
256
+ declare class ManagerAgent {
257
+ private readonly options;
258
+ private readonly registry;
259
+ readonly logger: Logger;
260
+ private readonly api;
261
+ private readonly pollIntervalMs;
262
+ private readonly concurrency;
263
+ private readonly instanceId;
264
+ private readonly taskTimeoutMs?;
265
+ private readonly logFlushIntervalMs?;
266
+ private state;
267
+ private timer;
268
+ private pollAbort;
269
+ private consecutiveFailures;
270
+ private consecutiveAuthFailures;
271
+ private readonly activeRuns;
272
+ private readonly reporters;
273
+ constructor(options: ManagerAgentOptions, registry: Map<string, ManagerTaskHandler>);
274
+ get activeCount(): number;
275
+ start(): void;
276
+ /** Para o polling e aguarda as runs ativas (até timeoutMs). Retorna true se tudo terminou a tempo. */
277
+ stop(timeoutMs?: number): Promise<boolean>;
278
+ /** Timer intencionalmente NÃO unref'd: o agente é a razão do processo existir. */
279
+ private schedule;
280
+ private tick;
281
+ private delayAfterPollError;
282
+ private dispatch;
283
+ private executeRun;
284
+ private invokeWithTimeout;
285
+ }
286
+
287
+ declare class ManagerApiError extends Error {
288
+ readonly status: number;
289
+ constructor(message: string, status: number);
290
+ }
291
+ interface ManagerApiOptions {
292
+ baseUrl: string;
293
+ key: string;
294
+ logger: Logger;
295
+ }
296
+ /** Cliente HTTP do agente — bearer auth, retry com backoff nos updates. */
297
+ declare class ManagerApi {
298
+ private readonly baseUrl;
299
+ private readonly key;
300
+ private readonly logger;
301
+ constructor(options: ManagerApiOptions);
302
+ private headers;
303
+ /** Um request só — o loop de polling é quem decide o backoff entre tentativas. */
304
+ poll(request: ManagerPollRequest, signal?: AbortSignal): Promise<ManagerPollResponse>;
305
+ /**
306
+ * PATCH de status/logs com retry em falha de rede/5xx/429.
307
+ * 4xx é definitivo e vira ManagerApiError imediato (409 = run cancelada/transição inválida).
308
+ */
309
+ updateRun(runId: string, update: ManagerRunUpdateRequest): Promise<void>;
310
+ }
311
+
312
+ export { Breadcrumb, type BreadcrumbInput, type CaptureHint, type CheckInOptions, CheckInPayload, CheckInStatus, Client, EventPayload, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, ManagerAgent, ManagerApi, ManagerApiError, type ManagerOptions, ManagerPollRequest, ManagerPollResponse, ManagerRunUpdateRequest, type ManagerTaskHandler, type ParsedDsn, type RunContext, RunLogLevel, Scope, Severity, Span, SpanData, Transaction, TransactionPayload, type WithMonitorOptions, addBreadcrumb, captureException, captureMessage, checkIn, close, flush, getClient, init, parseDsn, register, setContext, setExtra, setTag, setTags, setUser, start, startTransaction, stop, withMonitor, withScope };