hobots 2.4.0 → 3.2.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 +116 -367
- package/dist/index.cjs +1385 -909
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +252 -225
- package/dist/index.d.ts +252 -225
- package/dist/index.js +1385 -909
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +27 -2
- package/dist/protocol.d.ts +27 -2
- package/docs/README.md +16 -33
- package/docs/api-reference.md +75 -213
- package/docs/concepts.md +60 -393
- package/docs/getting-started.md +38 -84
- package/docs/protocol.md +31 -19
- package/docs/tasks.md +102 -247
- package/package.json +2 -2
- package/docs/telemetry.md +0 -162
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,170 @@
|
|
|
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, ItemColumn, MachineProcess, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunCreateRequest, RunCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame, TaskItemsDeclaration } 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
|
+
interface Logger {
|
|
41
|
+
debug: (...args: unknown[]) => void;
|
|
42
|
+
warn: (...args: unknown[]) => void;
|
|
43
|
+
error: (...args: unknown[]) => void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Coluna de itens como o dev declara: só a chave, ou chave + rótulo. */
|
|
47
|
+
type ItemColumnInput = string | {
|
|
48
|
+
key: string;
|
|
49
|
+
label?: string;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Opções do processo (telemetria, identidade, handlers globais). Valem as da PRIMEIRA
|
|
54
|
+
* chamada a register()/start(); chamadas seguintes com valores diferentes avisam e são ignoradas.
|
|
55
|
+
*/
|
|
56
|
+
interface HobotsOptions {
|
|
57
|
+
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie em Configurações → Agentes. */
|
|
58
|
+
clientSecret?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Identificador único e estável desta instância — a identidade do agente no painel
|
|
61
|
+
* (heartbeat e tasks convergem nele). Default: env HOBOTS_INSTANCE_ID; sem ela, o hostname.
|
|
62
|
+
*/
|
|
63
|
+
instanceId?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Ambiente lógico onde este robô roda: 'development', 'testing', 'staging' ou
|
|
66
|
+
* 'production'. Vai em todo evento, transaction e na identidade da instância — é por
|
|
67
|
+
* ele que as regras de alerta decidem se notificam. Default: env HOBOTS_ENVIRONMENT;
|
|
68
|
+
* sem ela, 'production'.
|
|
69
|
+
*/
|
|
70
|
+
environment?: EnvironmentInput;
|
|
71
|
+
/** Versão do programa, ex.: 'robo-nfe@1.4.2' */
|
|
72
|
+
release?: string;
|
|
73
|
+
/** Tags aplicadas a todos os eventos */
|
|
74
|
+
tags?: Record<string, string>;
|
|
75
|
+
/** Loga atividade do SDK no console */
|
|
76
|
+
debug?: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Coleta CPU, memória, disco e recursos do processo: vai em cada heartbeat/poll (série da
|
|
79
|
+
* instância no app) e como `contexts.machine` em cada evento. Só em Node. Default: true
|
|
80
|
+
*/
|
|
81
|
+
machineMetrics?: boolean;
|
|
82
|
+
/** Registra handlers globais de erro (uncaughtException etc.) que abrem issues. Default: true */
|
|
83
|
+
captureUnhandled?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Avançado. Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
86
|
+
* ativas como falha (AgentTerminated) antes do processo morrer. Nunca interfere quando
|
|
87
|
+
* o programa tem handler próprio para o sinal. Default: true
|
|
88
|
+
*/
|
|
89
|
+
installExitHandlers?: boolean;
|
|
90
|
+
}
|
|
91
|
+
/** Colunas de itens declaradas no código (até 12; chave: letras, números, `.`, `-`, `_`). */
|
|
92
|
+
interface TaskItemsOptions {
|
|
93
|
+
columns: ItemColumnInput[];
|
|
94
|
+
}
|
|
95
|
+
/** Opções de uma task (register ou start). */
|
|
96
|
+
interface TaskOptions extends HobotsOptions {
|
|
97
|
+
/**
|
|
98
|
+
* Colunas da aba "itens" da execução na plataforma: chaves do `payload` que cada
|
|
99
|
+
* item reportado (`ctx.items.*`) carrega, com rótulo opcional. Independe de
|
|
100
|
+
* formulário — vale para register e start. Personalizar na plataforma
|
|
101
|
+
* (Configurações → agente) sobrepõe o que for declarado aqui.
|
|
102
|
+
* Ex.: `{ columns: ['numero_nota', { key: 'valor', label: 'valor (R$)' }] }`
|
|
103
|
+
*/
|
|
104
|
+
items?: TaskItemsOptions;
|
|
105
|
+
/**
|
|
106
|
+
* Tentativas extras do handler quando ele lança, na mesma run (itens e progresso já
|
|
107
|
+
* enviados permanecem — escreva handlers idempotentes). Cancelamento e timeout nunca
|
|
108
|
+
* são re-tentados. Default: 1 (tenta 2 vezes no total); 0 desliga.
|
|
109
|
+
*/
|
|
110
|
+
retries?: number;
|
|
111
|
+
/** Espera entre tentativas: ms fixo ou função da tentativa que falhou (1-based). Default: 5_000 */
|
|
112
|
+
retryDelayMs?: RetryDelay;
|
|
113
|
+
/**
|
|
114
|
+
* Timeout client-side por tentativa. O handler não é morto — a run é reportada como
|
|
115
|
+
* falha (TaskTimeout, terminal) e o slot é liberado. Default: sem timeout.
|
|
116
|
+
*/
|
|
117
|
+
timeoutMs?: number;
|
|
118
|
+
/** Avançado. Intervalo do flush incremental de logs. Default: 2_000 */
|
|
119
|
+
logFlushIntervalMs?: number;
|
|
120
|
+
/**
|
|
121
|
+
* Avançado. Intervalo do heartbeat de cancelamento por run: um PATCH vazio que detecta
|
|
122
|
+
* runs canceladas no app e dispara o signal mesmo sem logs. Esse mesmo PATCH é o sinal
|
|
123
|
+
* de vida da run no servidor. Default: 5_000 (mínimo 1_000, máximo 15_000)
|
|
124
|
+
*/
|
|
125
|
+
cancelCheckIntervalMs?: number;
|
|
126
|
+
/**
|
|
127
|
+
* Avançado. Tempo de graça após o signal disparar (run cancelada no app) antes do
|
|
128
|
+
* SDK desistir de esperar o handler e liberar o slot. Default: 10_000
|
|
129
|
+
*/
|
|
130
|
+
cancelGraceMs?: number;
|
|
131
|
+
}
|
|
132
|
+
/** Opções de `register()` — task executada sob demanda, a partir das solicitações do app. */
|
|
133
|
+
interface RegisterOptions extends TaskOptions {
|
|
134
|
+
/** Runs simultâneas desta task (1..5). Default: 1 (sequencial) */
|
|
135
|
+
concurrency?: number;
|
|
136
|
+
/** Intervalo entre polls sem trabalho (mínimo 1_000). Vale o do primeiro register(). Default: 2_000 */
|
|
137
|
+
pollIntervalMs?: number;
|
|
138
|
+
}
|
|
139
|
+
/** Opções de `start()` — task que roda sempre, aberta pelo próprio bot. */
|
|
140
|
+
type StartOptions = TaskOptions;
|
|
141
|
+
/** Imagem enviada junto de um captureException — com legenda e content-type opcionais. */
|
|
142
|
+
interface CaptureAttachment {
|
|
143
|
+
/** Bytes (`Uint8Array`/`ArrayBuffer`/`Buffer`) ou um caminho de arquivo (só em Node) */
|
|
144
|
+
image: AttachInput;
|
|
145
|
+
/** Legenda curta, exibida sob a miniatura no app. Passa pelo scrub de segredos. */
|
|
146
|
+
caption?: string;
|
|
147
|
+
/** Informe quando os magic bytes não bastarem (o SDK sempre prefere o que detectar). */
|
|
148
|
+
contentType?: RunAttachmentContentType;
|
|
149
|
+
}
|
|
150
|
+
interface CaptureHint {
|
|
151
|
+
type?: EventType;
|
|
152
|
+
tags?: Record<string, string>;
|
|
153
|
+
extra?: Record<string, unknown>;
|
|
154
|
+
fingerprint?: string[];
|
|
155
|
+
/**
|
|
156
|
+
* Print da tela enviado junto da captura. Dentro de uma execução, a imagem vira anexo
|
|
157
|
+
* da linha de log que espelha o evento — miniatura na aba "logs do agente". Fora de uma
|
|
158
|
+
* execução não há onde pendurar a imagem: o SDK descarta com um aviso. O upload roda
|
|
159
|
+
* em segundo plano e **nunca bloqueia nem lança**. PNG, JPEG ou WEBP, até 5 MB, 20 por execução.
|
|
160
|
+
*
|
|
161
|
+
* ```ts
|
|
162
|
+
* hobots.captureException(error, { attachment: { image: await page.screenshot(), caption: 'tela no momento do erro' } });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
attachment?: AttachInput | CaptureAttachment;
|
|
166
|
+
}
|
|
167
|
+
|
|
9
168
|
interface ResolvedConfig {
|
|
10
169
|
/** Client Secret do agente (enviado como Authorization: Bearer, nunca na URL) */
|
|
11
170
|
key: string;
|
|
@@ -16,37 +175,6 @@ interface ResolvedConfig {
|
|
|
16
175
|
tasksBaseUrl: string;
|
|
17
176
|
}
|
|
18
177
|
|
|
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
|
-
interface Logger {
|
|
45
|
-
debug: (...args: unknown[]) => void;
|
|
46
|
-
warn: (...args: unknown[]) => void;
|
|
47
|
-
error: (...args: unknown[]) => void;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
178
|
/**
|
|
51
179
|
* Coleta CPU/memória/disco da máquina e do processo — só em Node (no browser é no-op).
|
|
52
180
|
*
|
|
@@ -75,6 +203,17 @@ declare class MachineSampler {
|
|
|
75
203
|
private diskUsage;
|
|
76
204
|
}
|
|
77
205
|
|
|
206
|
+
/** Opções de telemetria resolvidas pelo runtime a partir do primeiro register()/start(). */
|
|
207
|
+
interface ClientOptions {
|
|
208
|
+
environment?: EnvironmentInput;
|
|
209
|
+
release?: string;
|
|
210
|
+
/** Tags aplicadas a todos os eventos e transactions */
|
|
211
|
+
tags?: Record<string, string>;
|
|
212
|
+
debug?: boolean;
|
|
213
|
+
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
214
|
+
flushIntervalMs?: number;
|
|
215
|
+
maxBatchSize?: number;
|
|
216
|
+
}
|
|
78
217
|
declare class Client {
|
|
79
218
|
#private;
|
|
80
219
|
readonly logger: Logger;
|
|
@@ -82,21 +221,20 @@ declare class Client {
|
|
|
82
221
|
readonly debug: boolean;
|
|
83
222
|
private readonly transport;
|
|
84
223
|
private machine;
|
|
85
|
-
constructor(options:
|
|
86
|
-
get options():
|
|
224
|
+
constructor(options: ClientOptions, config: ResolvedConfig);
|
|
225
|
+
get options(): ClientOptions;
|
|
87
226
|
get config(): ResolvedConfig;
|
|
88
227
|
/** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
|
|
89
228
|
attachMachineSampler(sampler: MachineSampler | undefined): void;
|
|
90
229
|
/** Serialização explícita nunca inclui o secret. */
|
|
91
230
|
toJSON(): Record<string, unknown>;
|
|
92
|
-
captureException(error: unknown, hint
|
|
93
|
-
|
|
94
|
-
captureEvent(event: EventPayload, hint: CaptureHint | undefined, scope: Scope): string;
|
|
231
|
+
captureException(error: unknown, hint?: CaptureHint): string;
|
|
232
|
+
captureEvent(event: EventPayload, hint?: CaptureHint): string;
|
|
95
233
|
private prepareEvent;
|
|
96
234
|
sendTransaction(payload: TransactionPayload): void;
|
|
97
235
|
sendHeartbeat(payload: HeartbeatPayload): void;
|
|
98
236
|
/**
|
|
99
|
-
* Ambiente do item: o dele, senão o
|
|
237
|
+
* Ambiente do item: o dele, senão o das opções, senão produção. Centralizado
|
|
100
238
|
* porque evento, transaction e heartbeat precisam responder igual — o servidor
|
|
101
239
|
* normaliza apelidos legados, então aqui basta repassar.
|
|
102
240
|
*/
|
|
@@ -133,8 +271,7 @@ declare class Transaction {
|
|
|
133
271
|
private readonly client;
|
|
134
272
|
name: string;
|
|
135
273
|
readonly op?: string | undefined;
|
|
136
|
-
|
|
137
|
-
/** Correlaciona a uma execução de task — preenchido automaticamente em ctx.tx */
|
|
274
|
+
/** Correlaciona a uma execução de task — preenchido automaticamente em hobots.transaction */
|
|
138
275
|
private readonly runId?;
|
|
139
276
|
readonly eventId: string;
|
|
140
277
|
readonly stepId: string;
|
|
@@ -144,9 +281,10 @@ declare class Transaction {
|
|
|
144
281
|
private readonly tags;
|
|
145
282
|
private finished;
|
|
146
283
|
private lifecycleSink?;
|
|
284
|
+
private stepGuard?;
|
|
147
285
|
private lifecycleBacklog;
|
|
148
|
-
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
149
|
-
/** Correlaciona a uma execução de task — preenchido automaticamente em
|
|
286
|
+
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
287
|
+
/** Correlaciona a uma execução de task — preenchido automaticamente em hobots.transaction */
|
|
150
288
|
runId?: string | undefined);
|
|
151
289
|
/**
|
|
152
290
|
* Registra o início/fim de uma step ou transaction: espelha a linha no sink de
|
|
@@ -157,6 +295,11 @@ declare class Transaction {
|
|
|
157
295
|
emit(kind: 'transaction' | 'step', phase: 'start' | 'finish', label: string, startTs?: string, endTs?: string, status?: StepStatus | string): void;
|
|
158
296
|
/** Conecta o espelho de lifecycle (RunReporter) e faz replay do backlog em ordem. */
|
|
159
297
|
setLifecycleSink(sink: LifecycleSink): void;
|
|
298
|
+
/**
|
|
299
|
+
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
300
|
+
* `hobots.transaction.startChild()` (e `step.startChild()`) param uma run cancelada.
|
|
301
|
+
*/
|
|
302
|
+
setStepGuard(guard: () => void): void;
|
|
160
303
|
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
161
304
|
/** Step direta da transaction. */
|
|
162
305
|
startChild(op?: string, description?: string): Step;
|
|
@@ -166,46 +309,16 @@ declare class Transaction {
|
|
|
166
309
|
finish(): void;
|
|
167
310
|
}
|
|
168
311
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
}
|
|
312
|
+
/**
|
|
313
|
+
* `hobots.log`: cada método aceita vários argumentos, como `console.log` — cada um vira
|
|
314
|
+
* texto (`safeString`) e são unidos por espaço. Nunca lança, nem com a run cancelada.
|
|
315
|
+
*/
|
|
203
316
|
interface RunLogger {
|
|
204
|
-
debug(message:
|
|
205
|
-
info(message:
|
|
206
|
-
warn(message:
|
|
207
|
-
error(message:
|
|
208
|
-
success(message:
|
|
317
|
+
debug(message: unknown, ...rest: unknown[]): void;
|
|
318
|
+
info(message: unknown, ...rest: unknown[]): void;
|
|
319
|
+
warn(message: unknown, ...rest: unknown[]): void;
|
|
320
|
+
error(message: unknown, ...rest: unknown[]): void;
|
|
321
|
+
success(message: unknown, ...rest: unknown[]): void;
|
|
209
322
|
}
|
|
210
323
|
interface RunItemOptions {
|
|
211
324
|
/**
|
|
@@ -219,6 +332,7 @@ interface RunItemOptions {
|
|
|
219
332
|
* Registro dos itens que a execução processou/gerou (a entrega do bot: notas
|
|
220
333
|
* fiscais baixadas, boletos emitidos...). Chamadas são síncronas — os itens são
|
|
221
334
|
* bufferizados e enviados em lotes; o agente drena o buffer antes do reporte final.
|
|
335
|
+
* Cada chamada é um ponto de parada cooperativo: lança `RunCanceled` se a run foi cancelada.
|
|
222
336
|
*/
|
|
223
337
|
interface RunItems {
|
|
224
338
|
/** Forma genérica — os atalhos succeeded/failed/occurrence cobrem o dia a dia. */
|
|
@@ -237,9 +351,10 @@ interface RunItems {
|
|
|
237
351
|
}
|
|
238
352
|
/**
|
|
239
353
|
* Progresso da execução (itens processados / total) — opcional e independente de
|
|
240
|
-
* `
|
|
241
|
-
*
|
|
242
|
-
*
|
|
354
|
+
* `hobots.items`. Declare o total antes do loop e avance a cada item: a plataforma
|
|
355
|
+
* mostra barra, percentual e tempo restante estimado. Sem `total()` nada é enviado.
|
|
356
|
+
* Chamadas são síncronas e baratas (≤ 1 PATCH/s, pegando carona nos logs), e cada
|
|
357
|
+
* uma é um ponto de parada cooperativo (lança `RunCanceled` se a run foi cancelada).
|
|
243
358
|
*/
|
|
244
359
|
interface RunProgressReporter {
|
|
245
360
|
/** Declara (ou ajusta) o total de itens previsto — inteiro >= 1. Idempotente. */
|
|
@@ -253,158 +368,70 @@ interface RunProgressReporter {
|
|
|
253
368
|
/** `{ current, total }` quando há total declarado; null caso contrário. */
|
|
254
369
|
readonly snapshot: RunProgress | null;
|
|
255
370
|
}
|
|
371
|
+
/**
|
|
372
|
+
* Tudo que uma execução expõe ao código do bot. Acessível de qualquer lugar pelo
|
|
373
|
+
* objeto global `hobots` (resolve a run atual sozinho) ou pelo 2º argumento do handler.
|
|
374
|
+
*/
|
|
256
375
|
interface RunContext {
|
|
257
|
-
runId: string;
|
|
258
|
-
task: string;
|
|
259
|
-
/**
|
|
260
|
-
|
|
376
|
+
readonly runId: string;
|
|
377
|
+
readonly task: string;
|
|
378
|
+
/** Params da solicitação (formulário do app); `{}` no modo start */
|
|
379
|
+
readonly params: Record<string, unknown>;
|
|
380
|
+
/** Log bufferizado — enviado ao servidor em PATCHes incrementais com throttle. Nunca lança. */
|
|
381
|
+
readonly log: RunLogger;
|
|
261
382
|
/** 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;
|
|
383
|
+
readonly items: RunItems;
|
|
384
|
+
/** Progresso declarado (barra + ETA no app) — opcional, independente de `items` */
|
|
385
|
+
readonly progress: RunProgressReporter;
|
|
265
386
|
/**
|
|
266
387
|
* Transaction de performance desta execução — já correlacionada à run e finalizada
|
|
267
|
-
* automaticamente ao fim do handler. Use `
|
|
268
|
-
* as etapas (steps)
|
|
388
|
+
* automaticamente ao fim do handler. Use `transaction.startChild(op, description)` para
|
|
389
|
+
* medir as etapas (steps); elas aparecem como waterfall na aba de performance da execução.
|
|
269
390
|
*/
|
|
270
|
-
|
|
391
|
+
readonly transaction: Transaction;
|
|
271
392
|
/** Dispara em cancelamento (run cancelada no app), timeout ou shutdown — cancelamento cooperativo */
|
|
272
|
-
signal: AbortSignal;
|
|
393
|
+
readonly signal: AbortSignal;
|
|
273
394
|
/**
|
|
274
|
-
* Lança um erro `RunCanceled` se a run foi cancelada/abortada
|
|
275
|
-
*
|
|
395
|
+
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
396
|
+
* items/progress/transaction.startChild/sleep/retry; use para um controle mais fino.
|
|
276
397
|
*/
|
|
277
398
|
throwIfCanceled(): void;
|
|
278
|
-
/** Sleep cancelável: rejeita com `RunCanceled` se
|
|
399
|
+
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
279
400
|
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
|
-
/**
|
|
327
|
-
* Habilita a execução remota de tarefas sob demanda — o módulo Solicitações do app
|
|
328
|
-
* (true usa defaults). Usa o mesmo clientSecret e o instanceId como identidade.
|
|
329
|
-
* Depois de init(), chame register() e start().
|
|
330
|
-
*/
|
|
331
|
-
tasks?: boolean | TasksOptions;
|
|
332
|
-
/** Última chance de editar/descartar um evento (retorne null para descartar) */
|
|
333
|
-
beforeSend?: (event: EventPayload) => EventPayload | null;
|
|
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
401
|
/**
|
|
356
|
-
*
|
|
357
|
-
*
|
|
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
|
-
* ```
|
|
402
|
+
* Anexa uma imagem (print) a uma linha de log da run — miniatura no app. Nunca lança nem
|
|
403
|
+
* bloqueia: o upload roda em segundo plano. PNG/JPEG/WEBP, até 5 MB, 20 por execução.
|
|
366
404
|
*/
|
|
367
|
-
|
|
405
|
+
attach(image: AttachInput, options?: AttachOptions): Promise<AttachResult>;
|
|
406
|
+
/** async-retry ciente do cancelamento desta run (ver `RetryOptions`). */
|
|
407
|
+
retry<T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions): Promise<T>;
|
|
368
408
|
}
|
|
409
|
+
/** O retorno do handler é ignorado — nada além de status/logs/erro é enviado ao servidor. */
|
|
410
|
+
type TaskHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
|
|
369
411
|
|
|
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
412
|
/**
|
|
403
|
-
*
|
|
404
|
-
* e
|
|
413
|
+
* O objeto global do SDK: as funções do processo (register/start/close/captureException/
|
|
414
|
+
* retry) e o contexto da execução ATUAL (log, items, progress, transaction, signal…),
|
|
415
|
+
* resolvido a cada acesso — funciona de qualquer módulo, sem passar `ctx` de mão em mão.
|
|
405
416
|
*/
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
417
|
+
interface Hobots extends RunContext {
|
|
418
|
+
/** Task sob demanda: executada a cada solicitação do app (formulário/agendamento) via polling. */
|
|
419
|
+
register<P = Record<string, unknown>>(task: string, handler: TaskHandler<P>, options?: RegisterOptions): void;
|
|
420
|
+
/** Task sempre-ligada: o bot abre a própria run e roda o handler; a plataforma recebe logs, itens e progresso. */
|
|
421
|
+
start(task: string, handler: TaskHandler, options?: StartOptions): void;
|
|
422
|
+
/** Encerra tudo (polling, runs em voo, heartbeat, flush final). Chame antes do processo terminar. */
|
|
423
|
+
close(timeoutMs?: number): Promise<boolean>;
|
|
424
|
+
/** Captura uma exceção como issue (módulo Issues). Retorna o event_id. */
|
|
425
|
+
captureException(error: unknown, hint?: CaptureHint): string | undefined;
|
|
426
|
+
}
|
|
427
|
+
declare global {
|
|
428
|
+
var hobots: Hobots;
|
|
429
|
+
}
|
|
430
|
+
declare const hobots: Hobots;
|
|
431
|
+
declare const register: <P = Record<string, unknown>>(task: string, handler: TaskHandler<P>, options?: RegisterOptions) => void;
|
|
432
|
+
declare const start: (task: string, handler: TaskHandler, options?: StartOptions) => void;
|
|
433
|
+
declare const close: (timeoutMs?: number) => Promise<boolean>;
|
|
434
|
+
declare const captureException: (error: unknown, hint?: CaptureHint) => string | undefined;
|
|
435
|
+
declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions) => Promise<T>;
|
|
409
436
|
|
|
410
|
-
export { type AttachInput,
|
|
437
|
+
export { type AttachFailureReason, type AttachInput, type AttachOptions, type AttachResult, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, HeartbeatPayload, type Hobots, type HobotsOptions, type ItemColumnInput, 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 TaskItemsOptions, type TaskOptions, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, register, retry, start };
|