hobots 2.4.0 → 3.0.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/README.md +112 -369
- package/dist/index.cjs +1217 -852
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +218 -214
- package/dist/index.d.ts +218 -214
- package/dist/index.js +1217 -852
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +15 -2
- package/dist/protocol.d.ts +15 -2
- package/docs/README.md +16 -33
- package/docs/api-reference.md +74 -213
- package/docs/concepts.md +60 -393
- package/docs/getting-started.md +38 -84
- package/docs/protocol.md +28 -19
- package/docs/tasks.md +92 -251
- package/package.json +2 -2
- package/docs/telemetry.md +0 -162
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,145 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { BreadcrumbLevel, Envelope, EnvelopeItem, ExceptionData, InstanceInfo, MachineProcess, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame } from './protocol.js';
|
|
1
|
+
import { RunLogLevel, RunAttachmentContentType, EventType, EnvironmentInput, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, StepData, RunItemStatus, RunProgress } from './protocol.js';
|
|
2
|
+
export { Breadcrumb, BreadcrumbLevel, Envelope, EnvelopeItem, Environment, EventUser, ExceptionData, InstanceInfo, MachineProcess, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunCreateRequest, RunCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame } from './protocol.js';
|
|
3
3
|
|
|
4
|
+
/** Espera entre tentativas: ms fixo ou função do número da tentativa que acabou de falhar (1-based). */
|
|
5
|
+
type RetryDelay = number | ((attempt: number) => number);
|
|
6
|
+
interface RetryOptions {
|
|
7
|
+
/** Tentativas extras depois da primeira falha. Default: 3 */
|
|
8
|
+
retries?: number;
|
|
9
|
+
/** Espera entre tentativas. Default: 1_000 */
|
|
10
|
+
delayMs?: RetryDelay;
|
|
11
|
+
/** Filtro adicional: retorne false para desistir na hora. Cancelamento e timeout nunca são re-tentados. */
|
|
12
|
+
shouldRetry?: (error: unknown) => boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface AttachOptions {
|
|
16
|
+
/** Legenda curta, exibida sob a miniatura no app. Passa pelo scrub de segredos. */
|
|
17
|
+
caption?: string;
|
|
18
|
+
/** Nível da linha de log que carrega o anexo. Default: 'info' */
|
|
19
|
+
level?: RunLogLevel;
|
|
20
|
+
/** Texto da linha de log. Default: a legenda, ou 'captura de tela' */
|
|
21
|
+
message?: string;
|
|
22
|
+
/** Informe quando os magic bytes não bastarem (o SDK sempre prefere o que detectar). */
|
|
23
|
+
contentType?: RunAttachmentContentType;
|
|
24
|
+
}
|
|
25
|
+
type AttachFailureReason =
|
|
26
|
+
/** A instalação do Hobots não tem anexos habilitados (ou a API é anterior ao recurso) */
|
|
27
|
+
'unsupported' | 'too-large' | 'quota' | 'read-failed'
|
|
28
|
+
/** Formato não reconhecido ou fora de PNG/JPEG/WEBP */
|
|
29
|
+
| 'unsupported-format' | 'upload-failed' | 'canceled';
|
|
30
|
+
interface AttachResult {
|
|
31
|
+
/** Id do anexo, o mesmo referenciado na linha de log */
|
|
32
|
+
id: string;
|
|
33
|
+
ok: boolean;
|
|
34
|
+
/** Motivo do insucesso — para diagnóstico; `attach` nunca lança */
|
|
35
|
+
reason?: AttachFailureReason;
|
|
36
|
+
}
|
|
4
37
|
/** Aceita tudo que o handler pode ter em mãos: bytes ou um caminho de arquivo (só Node). */
|
|
5
38
|
type AttachInput = Uint8Array | ArrayBuffer | string;
|
|
6
39
|
|
|
7
|
-
/**
|
|
8
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Opções do processo (telemetria, identidade, handlers globais). Valem as da PRIMEIRA
|
|
42
|
+
* chamada a register()/start(); chamadas seguintes com valores diferentes avisam e são ignoradas.
|
|
43
|
+
*/
|
|
44
|
+
interface HobotsOptions {
|
|
45
|
+
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie em Configurações → Agentes. */
|
|
46
|
+
clientSecret?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Identificador único e estável desta instância — a identidade do agente no painel
|
|
49
|
+
* (heartbeat e tasks convergem nele). Default: env HOBOTS_INSTANCE_ID; sem ela, o hostname.
|
|
50
|
+
*/
|
|
51
|
+
instanceId?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Ambiente lógico onde este robô roda: 'development', 'testing', 'staging' ou
|
|
54
|
+
* 'production'. Vai em todo evento, transaction e na identidade da instância — é por
|
|
55
|
+
* ele que as regras de alerta decidem se notificam. Default: 'production'.
|
|
56
|
+
*/
|
|
57
|
+
environment?: EnvironmentInput;
|
|
58
|
+
/** Versão do programa, ex.: 'robo-nfe@1.4.2' */
|
|
59
|
+
release?: string;
|
|
60
|
+
/** Tags aplicadas a todos os eventos */
|
|
61
|
+
tags?: Record<string, string>;
|
|
62
|
+
/** Loga atividade do SDK no console */
|
|
63
|
+
debug?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Coleta CPU, memória, disco e recursos do processo: vai em cada heartbeat/poll (série da
|
|
66
|
+
* instância no app) e como `contexts.machine` em cada evento. Só em Node. Default: true
|
|
67
|
+
*/
|
|
68
|
+
machineMetrics?: boolean;
|
|
69
|
+
/** Registra handlers globais de erro (uncaughtException etc.) que abrem issues. Default: true */
|
|
70
|
+
captureUnhandled?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Avançado. Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
73
|
+
* ativas como falha (AgentTerminated) antes do processo morrer. Nunca interfere quando
|
|
74
|
+
* o programa tem handler próprio para o sinal. Default: true
|
|
75
|
+
*/
|
|
76
|
+
installExitHandlers?: boolean;
|
|
77
|
+
}
|
|
78
|
+
/** Opções de uma task (register ou start). */
|
|
79
|
+
interface TaskOptions extends HobotsOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Tentativas extras do handler quando ele lança, na mesma run (itens e progresso já
|
|
82
|
+
* enviados permanecem — escreva handlers idempotentes). Cancelamento e timeout nunca
|
|
83
|
+
* são re-tentados. Default: 1 (tenta 2 vezes no total); 0 desliga.
|
|
84
|
+
*/
|
|
85
|
+
retries?: number;
|
|
86
|
+
/** Espera entre tentativas: ms fixo ou função da tentativa que falhou (1-based). Default: 5_000 */
|
|
87
|
+
retryDelayMs?: RetryDelay;
|
|
88
|
+
/**
|
|
89
|
+
* Timeout client-side por tentativa. O handler não é morto — a run é reportada como
|
|
90
|
+
* falha (TaskTimeout, terminal) e o slot é liberado. Default: sem timeout.
|
|
91
|
+
*/
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
/** Avançado. Intervalo do flush incremental de logs. Default: 2_000 */
|
|
94
|
+
logFlushIntervalMs?: number;
|
|
95
|
+
/**
|
|
96
|
+
* Avançado. Intervalo do heartbeat de cancelamento por run: um PATCH vazio que detecta
|
|
97
|
+
* runs canceladas no app e dispara o signal mesmo sem logs. Esse mesmo PATCH é o sinal
|
|
98
|
+
* de vida da run no servidor. Default: 5_000 (mínimo 1_000, máximo 15_000)
|
|
99
|
+
*/
|
|
100
|
+
cancelCheckIntervalMs?: number;
|
|
101
|
+
/**
|
|
102
|
+
* Avançado. Tempo de graça após o signal disparar (run cancelada no app) antes do
|
|
103
|
+
* SDK desistir de esperar o handler e liberar o slot. Default: 10_000
|
|
104
|
+
*/
|
|
105
|
+
cancelGraceMs?: number;
|
|
106
|
+
}
|
|
107
|
+
/** Opções de `register()` — task executada sob demanda, a partir das solicitações do app. */
|
|
108
|
+
interface RegisterOptions extends TaskOptions {
|
|
109
|
+
/** Runs simultâneas desta task (1..5). Default: 1 (sequencial) */
|
|
110
|
+
concurrency?: number;
|
|
111
|
+
/** Intervalo entre polls sem trabalho (mínimo 1_000). Vale o do primeiro register(). Default: 2_000 */
|
|
112
|
+
pollIntervalMs?: number;
|
|
113
|
+
}
|
|
114
|
+
/** Opções de `start()` — task que roda sempre, aberta pelo próprio bot. */
|
|
115
|
+
type StartOptions = TaskOptions;
|
|
116
|
+
/** Imagem enviada junto de um captureException — com legenda e content-type opcionais. */
|
|
117
|
+
interface CaptureAttachment {
|
|
118
|
+
/** Bytes (`Uint8Array`/`ArrayBuffer`/`Buffer`) ou um caminho de arquivo (só em Node) */
|
|
119
|
+
image: AttachInput;
|
|
120
|
+
/** Legenda curta, exibida sob a miniatura no app. Passa pelo scrub de segredos. */
|
|
121
|
+
caption?: string;
|
|
122
|
+
/** Informe quando os magic bytes não bastarem (o SDK sempre prefere o que detectar). */
|
|
123
|
+
contentType?: RunAttachmentContentType;
|
|
124
|
+
}
|
|
125
|
+
interface CaptureHint {
|
|
126
|
+
type?: EventType;
|
|
127
|
+
tags?: Record<string, string>;
|
|
128
|
+
extra?: Record<string, unknown>;
|
|
129
|
+
fingerprint?: string[];
|
|
130
|
+
/**
|
|
131
|
+
* Print da tela enviado junto da captura. Dentro de uma execução, a imagem vira anexo
|
|
132
|
+
* da linha de log que espelha o evento — miniatura na aba "logs do agente". Fora de uma
|
|
133
|
+
* execução não há onde pendurar a imagem: o SDK descarta com um aviso. O upload roda
|
|
134
|
+
* em segundo plano e **nunca bloqueia nem lança**. PNG, JPEG ou WEBP, até 5 MB, 20 por execução.
|
|
135
|
+
*
|
|
136
|
+
* ```ts
|
|
137
|
+
* hobots.captureException(error, { attachment: { image: await page.screenshot(), caption: 'tela no momento do erro' } });
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
attachment?: AttachInput | CaptureAttachment;
|
|
141
|
+
}
|
|
142
|
+
|
|
9
143
|
interface ResolvedConfig {
|
|
10
144
|
/** Client Secret do agente (enviado como Authorization: Bearer, nunca na URL) */
|
|
11
145
|
key: string;
|
|
@@ -16,31 +150,6 @@ interface ResolvedConfig {
|
|
|
16
150
|
tasksBaseUrl: string;
|
|
17
151
|
}
|
|
18
152
|
|
|
19
|
-
type BreadcrumbInput = Omit<Breadcrumb, 'timestamp'> & {
|
|
20
|
-
timestamp?: string;
|
|
21
|
-
};
|
|
22
|
-
/** Estado contextual anexado aos eventos: tags, usuário, contexts, extras e breadcrumbs. */
|
|
23
|
-
declare class Scope {
|
|
24
|
-
tags: Record<string, string>;
|
|
25
|
-
user?: EventUser;
|
|
26
|
-
contexts: Record<string, Record<string, unknown>>;
|
|
27
|
-
extra: Record<string, unknown>;
|
|
28
|
-
type?: EventType;
|
|
29
|
-
fingerprint?: string[];
|
|
30
|
-
breadcrumbs: Breadcrumb[];
|
|
31
|
-
setTag(key: string, value: string): this;
|
|
32
|
-
setTags(tags: Record<string, string>): this;
|
|
33
|
-
setUser(user: EventUser | null): this;
|
|
34
|
-
setContext(name: string, context: Record<string, unknown> | null): this;
|
|
35
|
-
setExtra(key: string, value: unknown): this;
|
|
36
|
-
setExtras(extras: Record<string, unknown>): this;
|
|
37
|
-
setType(type: EventType): this;
|
|
38
|
-
setFingerprint(fingerprint: string[]): this;
|
|
39
|
-
addBreadcrumb(crumb: BreadcrumbInput, maxBreadcrumbs: number): this;
|
|
40
|
-
clearBreadcrumbs(): this;
|
|
41
|
-
clone(): Scope;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
153
|
interface Logger {
|
|
45
154
|
debug: (...args: unknown[]) => void;
|
|
46
155
|
warn: (...args: unknown[]) => void;
|
|
@@ -75,6 +184,17 @@ declare class MachineSampler {
|
|
|
75
184
|
private diskUsage;
|
|
76
185
|
}
|
|
77
186
|
|
|
187
|
+
/** Opções de telemetria resolvidas pelo runtime a partir do primeiro register()/start(). */
|
|
188
|
+
interface ClientOptions {
|
|
189
|
+
environment?: EnvironmentInput;
|
|
190
|
+
release?: string;
|
|
191
|
+
/** Tags aplicadas a todos os eventos e transactions */
|
|
192
|
+
tags?: Record<string, string>;
|
|
193
|
+
debug?: boolean;
|
|
194
|
+
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
195
|
+
flushIntervalMs?: number;
|
|
196
|
+
maxBatchSize?: number;
|
|
197
|
+
}
|
|
78
198
|
declare class Client {
|
|
79
199
|
#private;
|
|
80
200
|
readonly logger: Logger;
|
|
@@ -82,21 +202,20 @@ declare class Client {
|
|
|
82
202
|
readonly debug: boolean;
|
|
83
203
|
private readonly transport;
|
|
84
204
|
private machine;
|
|
85
|
-
constructor(options:
|
|
86
|
-
get options():
|
|
205
|
+
constructor(options: ClientOptions, config: ResolvedConfig);
|
|
206
|
+
get options(): ClientOptions;
|
|
87
207
|
get config(): ResolvedConfig;
|
|
88
208
|
/** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
|
|
89
209
|
attachMachineSampler(sampler: MachineSampler | undefined): void;
|
|
90
210
|
/** Serialização explícita nunca inclui o secret. */
|
|
91
211
|
toJSON(): Record<string, unknown>;
|
|
92
|
-
captureException(error: unknown, hint
|
|
93
|
-
|
|
94
|
-
captureEvent(event: EventPayload, hint: CaptureHint | undefined, scope: Scope): string;
|
|
212
|
+
captureException(error: unknown, hint?: CaptureHint): string;
|
|
213
|
+
captureEvent(event: EventPayload, hint?: CaptureHint): string;
|
|
95
214
|
private prepareEvent;
|
|
96
215
|
sendTransaction(payload: TransactionPayload): void;
|
|
97
216
|
sendHeartbeat(payload: HeartbeatPayload): void;
|
|
98
217
|
/**
|
|
99
|
-
* Ambiente do item: o dele, senão o
|
|
218
|
+
* Ambiente do item: o dele, senão o das opções, senão produção. Centralizado
|
|
100
219
|
* porque evento, transaction e heartbeat precisam responder igual — o servidor
|
|
101
220
|
* normaliza apelidos legados, então aqui basta repassar.
|
|
102
221
|
*/
|
|
@@ -133,8 +252,7 @@ declare class Transaction {
|
|
|
133
252
|
private readonly client;
|
|
134
253
|
name: string;
|
|
135
254
|
readonly op?: string | undefined;
|
|
136
|
-
|
|
137
|
-
/** Correlaciona a uma execução de task — preenchido automaticamente em ctx.tx */
|
|
255
|
+
/** Correlaciona a uma execução de task — preenchido automaticamente em hobots.transaction */
|
|
138
256
|
private readonly runId?;
|
|
139
257
|
readonly eventId: string;
|
|
140
258
|
readonly stepId: string;
|
|
@@ -144,9 +262,10 @@ declare class Transaction {
|
|
|
144
262
|
private readonly tags;
|
|
145
263
|
private finished;
|
|
146
264
|
private lifecycleSink?;
|
|
265
|
+
private stepGuard?;
|
|
147
266
|
private lifecycleBacklog;
|
|
148
|
-
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
149
|
-
/** Correlaciona a uma execução de task — preenchido automaticamente em
|
|
267
|
+
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
268
|
+
/** Correlaciona a uma execução de task — preenchido automaticamente em hobots.transaction */
|
|
150
269
|
runId?: string | undefined);
|
|
151
270
|
/**
|
|
152
271
|
* Registra o início/fim de uma step ou transaction: espelha a linha no sink de
|
|
@@ -157,6 +276,11 @@ declare class Transaction {
|
|
|
157
276
|
emit(kind: 'transaction' | 'step', phase: 'start' | 'finish', label: string, startTs?: string, endTs?: string, status?: StepStatus | string): void;
|
|
158
277
|
/** Conecta o espelho de lifecycle (RunReporter) e faz replay do backlog em ordem. */
|
|
159
278
|
setLifecycleSink(sink: LifecycleSink): void;
|
|
279
|
+
/**
|
|
280
|
+
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
281
|
+
* `hobots.transaction.startChild()` (e `step.startChild()`) param uma run cancelada.
|
|
282
|
+
*/
|
|
283
|
+
setStepGuard(guard: () => void): void;
|
|
160
284
|
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
161
285
|
/** Step direta da transaction. */
|
|
162
286
|
startChild(op?: string, description?: string): Step;
|
|
@@ -166,40 +290,6 @@ declare class Transaction {
|
|
|
166
290
|
finish(): void;
|
|
167
291
|
}
|
|
168
292
|
|
|
169
|
-
/** Opções de tasks dentro de `init({ tasks: ... })`. Credencial (clientSecret), identidade (instanceId) e debug vêm do init. */
|
|
170
|
-
interface TasksOptions {
|
|
171
|
-
/** Intervalo entre polls sem trabalho. Default: 2_000 (mínimo 1_000) */
|
|
172
|
-
pollIntervalMs?: number;
|
|
173
|
-
/** Runs simultâneas (1..5). Default: 1 (sequencial) */
|
|
174
|
-
concurrency?: number;
|
|
175
|
-
/**
|
|
176
|
-
* Timeout client-side por run. O handler não é morto — a run é reportada como
|
|
177
|
-
* falha e o slot é liberado. Default: sem timeout (o servidor é o backstop).
|
|
178
|
-
*/
|
|
179
|
-
taskTimeoutMs?: number;
|
|
180
|
-
/** Intervalo do flush incremental de logs. Default: 2_000 */
|
|
181
|
-
logFlushIntervalMs?: number;
|
|
182
|
-
/**
|
|
183
|
-
* Intervalo do heartbeat de cancelamento por run: um PATCH vazio que detecta
|
|
184
|
-
* runs canceladas no app e dispara ctx.signal mesmo sem logs. Esse mesmo PATCH
|
|
185
|
-
* é o sinal de vida da run — o servidor marca como "encerrada inesperadamente"
|
|
186
|
-
* uma run sem reporte por ~60s. Default: 5_000 (mínimo 1_000, máximo 15_000)
|
|
187
|
-
*/
|
|
188
|
-
cancelCheckIntervalMs?: number;
|
|
189
|
-
/**
|
|
190
|
-
* Tempo de graça após ctx.signal disparar (run cancelada no app) antes do
|
|
191
|
-
* agente desistir de esperar o handler e liberar o slot de concorrência. O
|
|
192
|
-
* handler não é morto — se ele nunca checar ctx.signal, pode continuar
|
|
193
|
-
* rodando em segundo plano; só o agente para de esperar por ele. Default: 10_000
|
|
194
|
-
*/
|
|
195
|
-
cancelGraceMs?: number;
|
|
196
|
-
/**
|
|
197
|
-
* Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
198
|
-
* ativas como falha (AgentTerminated) antes do processo morrer. Nunca interfere
|
|
199
|
-
* quando o programa tem handler próprio para o sinal. Default: true
|
|
200
|
-
*/
|
|
201
|
-
installExitHandlers?: boolean;
|
|
202
|
-
}
|
|
203
293
|
interface RunLogger {
|
|
204
294
|
debug(message: string): void;
|
|
205
295
|
info(message: string): void;
|
|
@@ -219,6 +309,7 @@ interface RunItemOptions {
|
|
|
219
309
|
* Registro dos itens que a execução processou/gerou (a entrega do bot: notas
|
|
220
310
|
* fiscais baixadas, boletos emitidos...). Chamadas são síncronas — os itens são
|
|
221
311
|
* bufferizados e enviados em lotes; o agente drena o buffer antes do reporte final.
|
|
312
|
+
* Cada chamada é um ponto de parada cooperativo: lança `RunCanceled` se a run foi cancelada.
|
|
222
313
|
*/
|
|
223
314
|
interface RunItems {
|
|
224
315
|
/** Forma genérica — os atalhos succeeded/failed/occurrence cobrem o dia a dia. */
|
|
@@ -237,9 +328,10 @@ interface RunItems {
|
|
|
237
328
|
}
|
|
238
329
|
/**
|
|
239
330
|
* Progresso da execução (itens processados / total) — opcional e independente de
|
|
240
|
-
* `
|
|
241
|
-
*
|
|
242
|
-
*
|
|
331
|
+
* `hobots.items`. Declare o total antes do loop e avance a cada item: a plataforma
|
|
332
|
+
* mostra barra, percentual e tempo restante estimado. Sem `total()` nada é enviado.
|
|
333
|
+
* Chamadas são síncronas e baratas (≤ 1 PATCH/s, pegando carona nos logs), e cada
|
|
334
|
+
* uma é um ponto de parada cooperativo (lança `RunCanceled` se a run foi cancelada).
|
|
243
335
|
*/
|
|
244
336
|
interface RunProgressReporter {
|
|
245
337
|
/** Declara (ou ajusta) o total de itens previsto — inteiro >= 1. Idempotente. */
|
|
@@ -253,158 +345,70 @@ interface RunProgressReporter {
|
|
|
253
345
|
/** `{ current, total }` quando há total declarado; null caso contrário. */
|
|
254
346
|
readonly snapshot: RunProgress | null;
|
|
255
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* Tudo que uma execução expõe ao código do bot. Acessível de qualquer lugar pelo
|
|
350
|
+
* objeto global `hobots` (resolve a run atual sozinho) ou pelo 2º argumento do handler.
|
|
351
|
+
*/
|
|
256
352
|
interface RunContext {
|
|
257
|
-
runId: string;
|
|
258
|
-
task: string;
|
|
259
|
-
/**
|
|
260
|
-
|
|
353
|
+
readonly runId: string;
|
|
354
|
+
readonly task: string;
|
|
355
|
+
/** Params da solicitação (formulário do app); `{}` no modo start */
|
|
356
|
+
readonly params: Record<string, unknown>;
|
|
357
|
+
/** Log bufferizado — enviado ao servidor em PATCHes incrementais com throttle. Nunca lança. */
|
|
358
|
+
readonly log: RunLogger;
|
|
261
359
|
/** Itens processados/gerados pela execução — a entrega do bot, com status e atributos */
|
|
262
|
-
items: RunItems;
|
|
263
|
-
/** Progresso declarado (barra + ETA no app) — opcional, independente de `
|
|
264
|
-
progress: RunProgressReporter;
|
|
360
|
+
readonly items: RunItems;
|
|
361
|
+
/** Progresso declarado (barra + ETA no app) — opcional, independente de `items` */
|
|
362
|
+
readonly progress: RunProgressReporter;
|
|
265
363
|
/**
|
|
266
364
|
* Transaction de performance desta execução — já correlacionada à run e finalizada
|
|
267
|
-
* automaticamente ao fim do handler. Use `
|
|
268
|
-
* as etapas (steps)
|
|
365
|
+
* automaticamente ao fim do handler. Use `transaction.startChild(op, description)` para
|
|
366
|
+
* medir as etapas (steps); elas aparecem como waterfall na aba de performance da execução.
|
|
269
367
|
*/
|
|
270
|
-
|
|
368
|
+
readonly transaction: Transaction;
|
|
271
369
|
/** Dispara em cancelamento (run cancelada no app), timeout ou shutdown — cancelamento cooperativo */
|
|
272
|
-
signal: AbortSignal;
|
|
370
|
+
readonly signal: AbortSignal;
|
|
273
371
|
/**
|
|
274
|
-
* Lança um erro `RunCanceled` se a run foi cancelada/abortada
|
|
275
|
-
*
|
|
372
|
+
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
373
|
+
* items/progress/transaction.startChild/sleep/retry; use para um controle mais fino.
|
|
276
374
|
*/
|
|
277
375
|
throwIfCanceled(): void;
|
|
278
|
-
/** Sleep cancelável: rejeita com `RunCanceled` se
|
|
376
|
+
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
279
377
|
sleep(ms: number): Promise<void>;
|
|
280
|
-
}
|
|
281
|
-
/** O retorno do handler é ignorado — nada além de status/logs/erro é enviado ao servidor. */
|
|
282
|
-
type TaskHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
|
|
283
|
-
|
|
284
|
-
interface HeartbeatOptions {
|
|
285
|
-
/** Intervalo entre batimentos. Default: 30_000 */
|
|
286
|
-
intervalMs?: number;
|
|
287
|
-
/** Nome amigável exibido no dashboard. Default: o instanceId do init */
|
|
288
|
-
name?: string;
|
|
289
|
-
metadata?: Record<string, unknown>;
|
|
290
|
-
}
|
|
291
|
-
interface InitOptions {
|
|
292
|
-
/** O Client Secret do agente (hb_…) — a mesma credencial para telemetria e tasks. Copie em Configurações → Agentes. */
|
|
293
|
-
clientSecret: string;
|
|
294
|
-
/**
|
|
295
|
-
* Ambiente lógico onde este robô roda: 'development', 'testing', 'staging'
|
|
296
|
-
* (homologação) ou 'production'. Vai em todo evento e transaction E na
|
|
297
|
-
* identidade da instância — é por ele que as regras de alerta decidem se
|
|
298
|
-
* notificam. Default: 'production'.
|
|
299
|
-
*
|
|
300
|
-
* Um valor livre herdado continua valendo — o servidor normaliza apelidos
|
|
301
|
-
* como 'prod' e 'qa'.
|
|
302
|
-
*/
|
|
303
|
-
environment?: EnvironmentInput;
|
|
304
|
-
/** Versão do programa, ex.: 'robo-nfe@1.4.2' */
|
|
305
|
-
release?: string;
|
|
306
|
-
/** Identificador único e estável desta instância — a identidade do agente no painel (heartbeat e poll de tasks convergem nele) */
|
|
307
|
-
instanceId: string;
|
|
308
|
-
/** Tags aplicadas a todos os eventos */
|
|
309
|
-
tags?: Record<string, string>;
|
|
310
|
-
/** Amostragem de eventos de erro (0..1). Default: 1 */
|
|
311
|
-
sampleRate?: number;
|
|
312
|
-
/** Amostragem de transactions (0..1). Default: 1 */
|
|
313
|
-
tracesSampleRate?: number;
|
|
314
|
-
/** Default: 100 */
|
|
315
|
-
maxBreadcrumbs?: number;
|
|
316
|
-
/** Registra handlers globais de erro (uncaughtException etc.). Default: true */
|
|
317
|
-
captureUnhandled?: boolean;
|
|
318
|
-
/**
|
|
319
|
-
* Coleta CPU, memória, disco e recursos do processo: vai em cada heartbeat/poll (série da
|
|
320
|
-
* instância no app) e como `contexts.machine` em cada evento (como estava a máquina na hora
|
|
321
|
-
* do erro). Só em Node; sem custo de timer — pega carona no heartbeat. Default: true
|
|
322
|
-
*/
|
|
323
|
-
machineMetrics?: boolean;
|
|
324
|
-
/** Habilita heartbeat periódico (true usa defaults) */
|
|
325
|
-
heartbeat?: boolean | HeartbeatOptions;
|
|
326
378
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
* Depois de init(), chame register() e start().
|
|
379
|
+
* Anexa uma imagem (print) a uma linha de log da run — miniatura no app. Nunca lança nem
|
|
380
|
+
* bloqueia: o upload roda em segundo plano. PNG/JPEG/WEBP, até 5 MB, 20 por execução.
|
|
330
381
|
*/
|
|
331
|
-
|
|
332
|
-
/**
|
|
333
|
-
|
|
334
|
-
/** Loga atividade do SDK no console */
|
|
335
|
-
debug?: boolean;
|
|
336
|
-
/** Intervalo do flush automático do transport. Default: 2_000 */
|
|
337
|
-
flushIntervalMs?: number;
|
|
338
|
-
/** Itens por envelope antes de flush imediato. Default: 10 */
|
|
339
|
-
maxBatchSize?: number;
|
|
340
|
-
}
|
|
341
|
-
/** Imagem enviada junto de um capture* — com legenda e content-type opcionais. */
|
|
342
|
-
interface CaptureAttachment {
|
|
343
|
-
/** Bytes (`Uint8Array`/`ArrayBuffer`/`Buffer`) ou um caminho de arquivo (só em Node) */
|
|
344
|
-
image: AttachInput;
|
|
345
|
-
/** Legenda curta, exibida sob a miniatura no app. Passa pelo scrub de segredos. */
|
|
346
|
-
caption?: string;
|
|
347
|
-
/** Informe quando os magic bytes não bastarem (o SDK sempre prefere o que detectar). */
|
|
348
|
-
contentType?: RunAttachmentContentType;
|
|
349
|
-
}
|
|
350
|
-
interface CaptureHint {
|
|
351
|
-
type?: EventType;
|
|
352
|
-
tags?: Record<string, string>;
|
|
353
|
-
extra?: Record<string, unknown>;
|
|
354
|
-
fingerprint?: string[];
|
|
355
|
-
/**
|
|
356
|
-
* Print da tela enviado junto da captura. Dentro de uma execução de task, a imagem
|
|
357
|
-
* vira anexo da linha de log da execução que espelha o evento — miniatura na aba
|
|
358
|
-
* "logs do agente". Fora de uma execução não há onde pendurar a imagem: o SDK
|
|
359
|
-
* descarta com um aviso. O upload roda em segundo plano e **nunca bloqueia nem lança**.
|
|
360
|
-
*
|
|
361
|
-
* PNG, JPEG ou WEBP, até 5 MB, no máximo 20 anexos por execução.
|
|
362
|
-
*
|
|
363
|
-
* ```ts
|
|
364
|
-
* Hobots.captureException(error, { attachment: { image: await page.screenshot(), caption: 'tela no momento do erro' } });
|
|
365
|
-
* ```
|
|
366
|
-
*/
|
|
367
|
-
attachment?: AttachInput | CaptureAttachment;
|
|
382
|
+
attach(image: AttachInput, options?: AttachOptions): Promise<AttachResult>;
|
|
383
|
+
/** async-retry ciente do cancelamento desta run (ver `RetryOptions`). */
|
|
384
|
+
retry<T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions): Promise<T>;
|
|
368
385
|
}
|
|
386
|
+
/** O retorno do handler é ignorado — nada além de status/logs/erro é enviado ao servidor. */
|
|
387
|
+
type TaskHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
|
|
369
388
|
|
|
370
|
-
/** Inicializa o SDK. Chame uma vez, o mais cedo possível no programa. */
|
|
371
|
-
declare function init(options: InitOptions): void;
|
|
372
|
-
declare function getClient(): Client | undefined;
|
|
373
|
-
/**
|
|
374
|
-
* Captura uma exceção e retorna o event_id (undefined se o SDK não foi inicializado).
|
|
375
|
-
* `hint.attachment` envia um print junto — dentro de uma execução de task, ele aparece
|
|
376
|
-
* como miniatura na linha de log da run correspondente ao erro.
|
|
377
|
-
*/
|
|
378
|
-
declare function captureException(error: unknown, hint?: CaptureHint): string | undefined;
|
|
379
|
-
declare function captureMessage(message: string, type?: EventType, hint?: CaptureHint): string | undefined;
|
|
380
|
-
/** Registra um breadcrumb — anexado aos próximos eventos como trilha do que aconteceu antes. */
|
|
381
|
-
declare function addBreadcrumb(crumb: BreadcrumbInput): void;
|
|
382
|
-
declare function setTag(key: string, value: string): void;
|
|
383
|
-
declare function setTags(tags: Record<string, string>): void;
|
|
384
|
-
declare function setUser(user: EventUser | null): void;
|
|
385
|
-
declare function setContext(name: string, context: Record<string, unknown> | null): void;
|
|
386
|
-
declare function setExtra(key: string, value: unknown): void;
|
|
387
|
-
/** Executa o callback com uma cópia isolada do scope (alterações não vazam para fora). */
|
|
388
|
-
declare function withScope<T>(callback: (scope: Scope) => T): T;
|
|
389
|
-
/** Inicia uma transaction de performance. Chame .finish() para enviá-la. */
|
|
390
|
-
declare function startTransaction(name: string, op?: string): Transaction;
|
|
391
|
-
/** Aguarda o envio de tudo que está na fila (até timeoutMs). */
|
|
392
|
-
declare function flush(timeoutMs?: number): Promise<boolean>;
|
|
393
|
-
/** Registra o handler de uma task (o task_slug configurado no formulário do app, em Configurações → Formulários). */
|
|
394
|
-
declare function register<P = Record<string, unknown>>(task: string, handler: TaskHandler<P>): void;
|
|
395
|
-
/**
|
|
396
|
-
* Inicia o polling de tasks. O timer NÃO é unref'd: o processo fica vivo
|
|
397
|
-
* aguardando trabalho até stop()/close() — o inverso deliberado da telemetria.
|
|
398
|
-
*/
|
|
399
|
-
declare function start(): void;
|
|
400
|
-
/** Para só o polling de tasks e aguarda as runs ativas (até timeoutMs). A telemetria continua. */
|
|
401
|
-
declare function stop(timeoutMs?: number): Promise<boolean>;
|
|
402
389
|
/**
|
|
403
|
-
*
|
|
404
|
-
* e
|
|
390
|
+
* O objeto global do SDK: as funções do processo (register/start/close/captureException/
|
|
391
|
+
* retry) e o contexto da execução ATUAL (log, items, progress, transaction, signal…),
|
|
392
|
+
* resolvido a cada acesso — funciona de qualquer módulo, sem passar `ctx` de mão em mão.
|
|
405
393
|
*/
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
394
|
+
interface Hobots extends RunContext {
|
|
395
|
+
/** Task sob demanda: executada a cada solicitação do app (formulário/agendamento) via polling. */
|
|
396
|
+
register<P = Record<string, unknown>>(task: string, handler: TaskHandler<P>, options?: RegisterOptions): void;
|
|
397
|
+
/** Task sempre-ligada: o bot abre a própria run e roda o handler; a plataforma recebe logs, itens e progresso. */
|
|
398
|
+
start(task: string, handler: TaskHandler, options?: StartOptions): void;
|
|
399
|
+
/** Encerra tudo (polling, runs em voo, heartbeat, flush final). Chame antes do processo terminar. */
|
|
400
|
+
close(timeoutMs?: number): Promise<boolean>;
|
|
401
|
+
/** Captura uma exceção como issue (módulo Issues). Retorna o event_id. */
|
|
402
|
+
captureException(error: unknown, hint?: CaptureHint): string | undefined;
|
|
403
|
+
}
|
|
404
|
+
declare global {
|
|
405
|
+
var hobots: Hobots;
|
|
406
|
+
}
|
|
407
|
+
declare const hobots: Hobots;
|
|
408
|
+
declare const register: <P = Record<string, unknown>>(task: string, handler: TaskHandler<P>, options?: RegisterOptions) => void;
|
|
409
|
+
declare const start: (task: string, handler: TaskHandler, options?: StartOptions) => void;
|
|
410
|
+
declare const close: (timeoutMs?: number) => Promise<boolean>;
|
|
411
|
+
declare const captureException: (error: unknown, hint?: CaptureHint) => string | undefined;
|
|
412
|
+
declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions) => Promise<T>;
|
|
409
413
|
|
|
410
|
-
export { type AttachInput,
|
|
414
|
+
export { type AttachFailureReason, type AttachInput, type AttachOptions, type AttachResult, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, HeartbeatPayload, type Hobots, type HobotsOptions, MachineSnapshot, type RegisterOptions, type RetryDelay, type RetryOptions, RunAttachmentContentType, type RunContext, type RunItemOptions, RunItemStatus, type RunItems, RunLogLevel, type RunLogger, RunProgress, type RunProgressReporter, type StartOptions, Step, StepData, StepStatus, type TaskHandler, type TaskOptions, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, register, retry, start };
|