hobots 4.2.0 → 5.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 +27 -11
- package/dist/cli.cjs +250 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/index.cjs +796 -246
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +91 -229
- package/dist/index.d.ts +91 -229
- package/dist/index.js +796 -246
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +17 -3
- package/dist/protocol.d.ts +17 -3
- package/docs/README.md +2 -2
- package/docs/api-reference.md +25 -9
- package/docs/concepts.md +12 -12
- package/docs/getting-started.md +5 -3
- package/docs/protocol.md +16 -8
- package/docs/runs.md +97 -23
- package/package.json +4 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RunAttachmentContentType,
|
|
2
|
-
export { Breadcrumb, BreadcrumbLevel, Envelope, EnvelopeItem, Environment, EventUser, ExceptionData, FileDownloadResponse, FileStorage, InstanceInfo, InstanceMode, ItemColumn, ItemsDeclaration, MachineProcess, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunCreateRequest, RunCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame } from './protocol.js';
|
|
1
|
+
import { RunAttachmentContentType, EnvironmentInput, EventType, FileRef, RunItemStatus, RunProgress } from './protocol.js';
|
|
2
|
+
export { Breadcrumb, BreadcrumbLevel, Envelope, EnvelopeItem, Environment, EventPayload, EventUser, ExceptionData, FileDownloadResponse, FileStorage, HeartbeatPayload, InstanceInfo, InstanceMode, ItemColumn, ItemsDeclaration, MachineProcess, MachineSnapshot, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunCreateRequest, RunCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunLogLevel, RunStartRequest, RunStartResponse, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame, StepData, StepStatus, TransactionPayload } from './protocol.js';
|
|
3
3
|
|
|
4
4
|
/** Espera entre tentativas: ms fixo ou função do número da tentativa que acabou de falhar (1-based). */
|
|
5
5
|
type RetryDelay = number | ((attempt: number) => number);
|
|
@@ -24,7 +24,7 @@ declare const IMAGE_BRAND: unique symbol;
|
|
|
24
24
|
/**
|
|
25
25
|
* Uma imagem pronta para ser pendurada num evento da run — o retorno de `hobots.image()`.
|
|
26
26
|
* É só um envelope (bytes/caminho + legenda); nenhum I/O acontece até o evento ser
|
|
27
|
-
* registrado por `hobots.log.*`, `hobots.items.*` ou `step.setStatus/
|
|
27
|
+
* registrado por `hobots.log.*`, `hobots.items.*` ou `step.setStatus/failed`.
|
|
28
28
|
*/
|
|
29
29
|
declare class ImageAttachment {
|
|
30
30
|
readonly input: AttachInput;
|
|
@@ -36,24 +36,55 @@ declare class ImageAttachment {
|
|
|
36
36
|
/** O que os métodos com imagem aceitam: bytes/caminho crus ou o envelope de `hobots.image()`. */
|
|
37
37
|
type ImageInput = AttachInput | ImageAttachment;
|
|
38
38
|
|
|
39
|
-
interface Logger {
|
|
40
|
-
debug: (...args: unknown[]) => void;
|
|
41
|
-
warn: (...args: unknown[]) => void;
|
|
42
|
-
error: (...args: unknown[]) => void;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
39
|
/** Coluna de itens como o dev declara: só a chave, ou chave + rótulo. */
|
|
46
40
|
type ItemColumnInput = string | {
|
|
47
41
|
key: string;
|
|
48
42
|
label?: string;
|
|
49
43
|
};
|
|
50
44
|
|
|
45
|
+
/** Opções de `hobots.step(nome, fn, opções)`. */
|
|
46
|
+
interface StepOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Tentativas extras da etapa quando `fn` lança (uma etapa só na Central, com `data.attempts`).
|
|
49
|
+
* Cancelamento e timeout nunca são re-tentados. Default: 1 (tenta 2 vezes no total); 0 desliga —
|
|
50
|
+
* use 0 em etapas com efeito colateral não idempotente (enviar, pagar, emitir).
|
|
51
|
+
*/
|
|
52
|
+
retries?: number;
|
|
53
|
+
/** Espera entre tentativas: ms fixo ou função da tentativa que falhou (1-based). Default: 5_000 */
|
|
54
|
+
retryDelayMs?: RetryDelay;
|
|
55
|
+
/**
|
|
56
|
+
* Ao terminar (deu certo ou esgotou), a etapa raiz faz `hobots.flush()` — ela, os itens e os
|
|
57
|
+
* logs aparecem na Central na hora. Sub-etapas saem no flush da etapa-mãe (ou do ciclo do
|
|
58
|
+
* `items.each`). `false` desliga. Default: true.
|
|
59
|
+
*/
|
|
60
|
+
flush?: boolean;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* A etapa em andamento — o handle que a função de `hobots.step(nome, fn)` recebe. O bot só
|
|
64
|
+
* registra o que o SDK não vê sozinho: um aviso de negócio, um print da tela e dados livres.
|
|
65
|
+
* Abrir, repetir e fechar a etapa é do SDK.
|
|
66
|
+
*/
|
|
67
|
+
interface StepHandle {
|
|
68
|
+
/**
|
|
69
|
+
* Marca a etapa como `warning` com o motivo (aparece no waterfall da Central e no log de
|
|
70
|
+
* FINISH). Uma etapa que já falhou não volta para aviso. `options.image` pendura um print.
|
|
71
|
+
*/
|
|
72
|
+
warning(message: string, options?: {
|
|
73
|
+
image?: ImageInput;
|
|
74
|
+
}): StepHandle;
|
|
75
|
+
/** Pendura um print do estado da tela na etapa (até 4 por etapa) — botão de imagem no app. */
|
|
76
|
+
image(image: ImageInput): StepHandle;
|
|
77
|
+
/** Dado livre da etapa (`data.<key>` no waterfall). A chave `attachments` é reservada. */
|
|
78
|
+
data(key: string, value: unknown): StepHandle;
|
|
79
|
+
}
|
|
80
|
+
/** A função de uma etapa: recebe o handle (pode ignorá-lo) e devolve o resultado da etapa. */
|
|
81
|
+
type StepFn<T> = (etapa: StepHandle) => T | Promise<T>;
|
|
51
82
|
/**
|
|
52
|
-
* Opções do processo (telemetria, identidade, handlers globais).
|
|
53
|
-
*
|
|
83
|
+
* Opções do processo (telemetria, identidade, handlers globais). Só há uma chamada a
|
|
84
|
+
* register()/start() por processo — a segunda lança (`o agente já foi iniciado`).
|
|
54
85
|
*/
|
|
55
86
|
interface HobotsOptions {
|
|
56
|
-
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie
|
|
87
|
+
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie na Central: agente → Configurações → agente → aba credenciais. */
|
|
57
88
|
clientSecret?: string;
|
|
58
89
|
/**
|
|
59
90
|
* Identificador único e estável desta instância — a identidade do agente no painel
|
|
@@ -78,7 +109,10 @@ interface HobotsOptions {
|
|
|
78
109
|
* instância no app) e como `contexts.machine` em cada evento. Só em Node. Default: true
|
|
79
110
|
*/
|
|
80
111
|
machineMetrics?: boolean;
|
|
81
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* Erro não tratado vira issue: o que escapa do handler de uma execução (além de falhar a
|
|
114
|
+
* run; cancelamento fica de fora) e o que escapa fora dele (uncaughtException etc.). Default: true
|
|
115
|
+
*/
|
|
82
116
|
captureUnhandled?: boolean;
|
|
83
117
|
/**
|
|
84
118
|
* Avançado. Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
@@ -134,6 +168,14 @@ interface RegisterOptions extends RunOptions {
|
|
|
134
168
|
concurrency?: number;
|
|
135
169
|
/** Intervalo entre polls sem trabalho (mínimo 1_000). Default: 2_000 */
|
|
136
170
|
pollIntervalMs?: number;
|
|
171
|
+
/**
|
|
172
|
+
* Avançado. Executa só esta run (já reivindicada para a instância, ex.: pelo Studio) em
|
|
173
|
+
* vez de fazer poll: anexa-se a ela (`POST /v1/runs/:id/start`), roda o handler uma vez e
|
|
174
|
+
* encerra o SDK (`close()`), liberando o processo. 404/409 (run inexistente, cancelada, já
|
|
175
|
+
* iniciada ou de outra instância) encerram sem rodar o handler. Default: env HOBOTS_RUN_ID;
|
|
176
|
+
* sem ela, poll normal.
|
|
177
|
+
*/
|
|
178
|
+
runId?: string;
|
|
137
179
|
}
|
|
138
180
|
/** Opções de `start()` — agente sempre ligado, que abre a própria run. */
|
|
139
181
|
type StartOptions = RunOptions;
|
|
@@ -153,7 +195,7 @@ interface CaptureHint {
|
|
|
153
195
|
fingerprint?: string[];
|
|
154
196
|
/**
|
|
155
197
|
* Print da tela enviado junto da captura. Dentro de uma execução, a imagem vira anexo
|
|
156
|
-
* da linha de log que espelha o evento
|
|
198
|
+
* da linha de log que espelha o evento (aba "logs do agente") e aparece na issue. Fora de uma
|
|
157
199
|
* execução não há onde pendurar a imagem: o SDK descarta com um aviso. O upload roda
|
|
158
200
|
* em segundo plano e **nunca bloqueia nem lança**. PNG, JPEG ou WEBP, até 5 MB, 20 por execução.
|
|
159
201
|
*
|
|
@@ -164,197 +206,6 @@ interface CaptureHint {
|
|
|
164
206
|
attachment?: ImageInput | CaptureAttachment;
|
|
165
207
|
}
|
|
166
208
|
|
|
167
|
-
interface ResolvedConfig {
|
|
168
|
-
/** Client Secret do agente (enviado como Authorization: Bearer, nunca na URL) */
|
|
169
|
-
key: string;
|
|
170
|
-
baseUrl: string;
|
|
171
|
-
/** Ingestão de telemetria: <baseUrl>/v1/ingest */
|
|
172
|
-
ingestEndpoint: string;
|
|
173
|
-
/** API de execuções (poll, runs, itens, anexos): <baseUrl>/v1/runs */
|
|
174
|
-
runsBaseUrl: string;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Coleta CPU/memória/disco da máquina e do processo — só em Node (no browser é no-op).
|
|
179
|
-
*
|
|
180
|
-
* Os módulos `node:*` entram por import dinâmico (o bundle é `platform: neutral`), e
|
|
181
|
-
* `sample()` é síncrono e barato: `os.cpus()` + `statfsSync` + `process.memoryUsage()`.
|
|
182
|
-
* Nunca lança — telemetria de recurso não pode derrubar o bot nem o capture de um erro.
|
|
183
|
-
*/
|
|
184
|
-
declare class MachineSampler {
|
|
185
|
-
private readonly instanceId;
|
|
186
|
-
private readonly logger;
|
|
187
|
-
private os;
|
|
188
|
-
private fs;
|
|
189
|
-
private ready;
|
|
190
|
-
private prevCpu;
|
|
191
|
-
private prevProcessCpu;
|
|
192
|
-
private prevAt;
|
|
193
|
-
private lastCpuPercent;
|
|
194
|
-
private lastProcessCpuPercent;
|
|
195
|
-
constructor(instanceId: string, logger: Logger);
|
|
196
|
-
/** Carrega os módulos e tira a leitura-base de CPU (a primeira amostra ainda sai com cpu_percent null). */
|
|
197
|
-
start(): Promise<void>;
|
|
198
|
-
sample(): MachineSnapshot | undefined;
|
|
199
|
-
private cpuTotals;
|
|
200
|
-
/** Média desde a leitura anterior; leituras com menos de 1s de janela reutilizam a última média. */
|
|
201
|
-
private updateCpu;
|
|
202
|
-
private diskUsage;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** Opções de telemetria resolvidas pelo runtime a partir do primeiro register()/start(). */
|
|
206
|
-
interface ClientOptions {
|
|
207
|
-
environment?: EnvironmentInput;
|
|
208
|
-
release?: string;
|
|
209
|
-
/** Tags aplicadas a todos os eventos e transactions */
|
|
210
|
-
tags?: Record<string, string>;
|
|
211
|
-
debug?: boolean;
|
|
212
|
-
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
213
|
-
flushIntervalMs?: number;
|
|
214
|
-
maxBatchSize?: number;
|
|
215
|
-
}
|
|
216
|
-
declare class Client {
|
|
217
|
-
#private;
|
|
218
|
-
readonly logger: Logger;
|
|
219
|
-
/** Eco de lifecycle (Transaction.emit) e afins só imprimem no terminal com debug ligado. */
|
|
220
|
-
readonly debug: boolean;
|
|
221
|
-
private readonly transport;
|
|
222
|
-
private machine;
|
|
223
|
-
constructor(options: ClientOptions, config: ResolvedConfig);
|
|
224
|
-
get options(): ClientOptions;
|
|
225
|
-
get config(): ResolvedConfig;
|
|
226
|
-
/** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
|
|
227
|
-
attachMachineSampler(sampler: MachineSampler | undefined): void;
|
|
228
|
-
/** Serialização explícita nunca inclui o secret. */
|
|
229
|
-
toJSON(): Record<string, unknown>;
|
|
230
|
-
captureException(error: unknown, hint?: CaptureHint): string;
|
|
231
|
-
captureEvent(event: EventPayload, hint?: CaptureHint): string;
|
|
232
|
-
private prepareEvent;
|
|
233
|
-
sendTransaction(payload: TransactionPayload): void;
|
|
234
|
-
sendHeartbeat(payload: HeartbeatPayload): void;
|
|
235
|
-
/**
|
|
236
|
-
* Ambiente do item: o dele, senão o das opções, senão produção. Centralizado
|
|
237
|
-
* porque evento, transaction e heartbeat precisam responder igual — o servidor
|
|
238
|
-
* normaliza apelidos legados, então aqui basta repassar.
|
|
239
|
-
*/
|
|
240
|
-
private resolveEnvironment;
|
|
241
|
-
flush(timeoutMs?: number): Promise<boolean>;
|
|
242
|
-
close(timeoutMs?: number): Promise<boolean>;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** Recebe os eventos de lifecycle da transaction para espelhá-los nos logs da run. */
|
|
246
|
-
type LifecycleSink = (level: RunLogLevel, message: string) => void;
|
|
247
|
-
/**
|
|
248
|
-
* Recebe a imagem de uma step e dispara o upload pela run; devolve o id do anexo
|
|
249
|
-
* (já referenciável em `data.attachments`) ou undefined quando descartada.
|
|
250
|
-
*/
|
|
251
|
-
type AttachmentSink = (image: ImageInput, ts: string) => string | undefined;
|
|
252
|
-
/** Opções dos desfechos de step que aceitam um print do estado da tela. */
|
|
253
|
-
interface StepOutcomeOptions {
|
|
254
|
-
/** Print da step (bytes/caminho ou `hobots.image(bytes, { caption })`) — botão de imagem no app. */
|
|
255
|
-
image?: ImageInput;
|
|
256
|
-
}
|
|
257
|
-
declare class Step {
|
|
258
|
-
private readonly transaction;
|
|
259
|
-
readonly parentStepId: string;
|
|
260
|
-
readonly op?: string | undefined;
|
|
261
|
-
readonly description?: string | undefined;
|
|
262
|
-
readonly stepId: string;
|
|
263
|
-
readonly startTimestamp: string;
|
|
264
|
-
status: StepStatus;
|
|
265
|
-
endTimestamp?: string;
|
|
266
|
-
data?: Record<string, unknown>;
|
|
267
|
-
constructor(transaction: Transaction, parentStepId: string, op?: string | undefined, description?: string | undefined);
|
|
268
|
-
/**
|
|
269
|
-
* Desfecho da step. `message` (opcional) é o motivo legível — vai em `data.message`
|
|
270
|
-
* e aparece na Central (performance e banner da execução) e no log de FINISH.
|
|
271
|
-
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
272
|
-
*/
|
|
273
|
-
setStatus(status: StepStatus, message?: string, options?: StepOutcomeOptions): this;
|
|
274
|
-
/**
|
|
275
|
-
* Marca a step como `error` guardando o motivo em `data.error` ({ type, message }).
|
|
276
|
-
* Aceita qualquer valor lançado; `message` sobrescreve a mensagem do erro.
|
|
277
|
-
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
278
|
-
*/
|
|
279
|
-
setError(error: unknown, message?: string, options?: StepOutcomeOptions): this;
|
|
280
|
-
/**
|
|
281
|
-
* Dispara o upload pela run (sink do RunReporter) e referencia o anexo em
|
|
282
|
-
* `data.attachments` (chave reservada; teto igual ao das linhas de log). Fora de uma
|
|
283
|
-
* run não há onde pendurar a imagem — descarta com aviso único.
|
|
284
|
-
*/
|
|
285
|
-
private attachImage;
|
|
286
|
-
/** Motivo registrado via setStatus(…, message) ou setError — usado no log de FINISH. */
|
|
287
|
-
private reason;
|
|
288
|
-
setData(key: string, value: unknown): this;
|
|
289
|
-
/** Step aninhada (filha desta step). */
|
|
290
|
-
startChild(op?: string, description?: string): Step;
|
|
291
|
-
finish(): void;
|
|
292
|
-
toJSON(): StepData;
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Uma unidade de trabalho nomeada (ex.: uma execução de rotina, uma sincronização).
|
|
296
|
-
* Steps filhas medem as etapas internas (chamadas HTTP, queries, etc.).
|
|
297
|
-
*/
|
|
298
|
-
declare class Transaction {
|
|
299
|
-
private readonly client;
|
|
300
|
-
name: string;
|
|
301
|
-
readonly op?: string | undefined;
|
|
302
|
-
/** Correlaciona a uma execução do agente — preenchido automaticamente em hobots.transaction */
|
|
303
|
-
private readonly runId?;
|
|
304
|
-
readonly eventId: string;
|
|
305
|
-
readonly stepId: string;
|
|
306
|
-
readonly startTimestamp: string;
|
|
307
|
-
status: string;
|
|
308
|
-
private readonly steps;
|
|
309
|
-
private readonly tags;
|
|
310
|
-
private finished;
|
|
311
|
-
private lifecycleSink?;
|
|
312
|
-
private attachmentSink?;
|
|
313
|
-
private warnedNoAttachmentSink;
|
|
314
|
-
private stepGuard?;
|
|
315
|
-
private lifecycleBacklog;
|
|
316
|
-
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
317
|
-
/** Correlaciona a uma execução do agente — preenchido automaticamente em hobots.transaction */
|
|
318
|
-
runId?: string | undefined);
|
|
319
|
-
/**
|
|
320
|
-
* Registra o início/fim de uma step ou transaction: espelha a linha no sink de
|
|
321
|
-
* lifecycle, se conectado (é assim que os eventos de performance aparecem nos
|
|
322
|
-
* logs da run no app), e ecoa no terminal apenas com `debug: true` — o SDK não
|
|
323
|
-
* escreve no stdout do processo do usuário sem permissão.
|
|
324
|
-
*/
|
|
325
|
-
emit(kind: 'transaction' | 'step', phase: 'start' | 'finish', label: string, startTs?: string, endTs?: string, status?: StepStatus | string, reason?: string): void;
|
|
326
|
-
/** Conecta o espelho de lifecycle (RunReporter) e faz replay do backlog em ordem. */
|
|
327
|
-
setLifecycleSink(sink: LifecycleSink): void;
|
|
328
|
-
/** Conecta o pipeline de anexos da run — é o que dá imagem às steps. */
|
|
329
|
-
setAttachmentSink(sink: AttachmentSink): void;
|
|
330
|
-
/** Imagem de uma step → id do anexo pela run; sem run, descarta com aviso único. */
|
|
331
|
-
attachImage(image: ImageInput): string | undefined;
|
|
332
|
-
/**
|
|
333
|
-
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
334
|
-
* `hobots.transaction.startChild()` (e `step.startChild()`) param uma run cancelada.
|
|
335
|
-
*/
|
|
336
|
-
setStepGuard(guard: () => void): void;
|
|
337
|
-
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
338
|
-
/** Step direta da transaction. */
|
|
339
|
-
startChild(op?: string, description?: string): Step;
|
|
340
|
-
setTag(key: string, value: string): this;
|
|
341
|
-
setStatus(status: string): this;
|
|
342
|
-
setName(name: string): this;
|
|
343
|
-
/**
|
|
344
|
-
* Envia já as steps raiz finalizadas (e todas as descendentes, fechando as que
|
|
345
|
-
* ficaram abertas) como transactions parciais da mesma run (`op` hobots.run.flush,
|
|
346
|
-
* `event_id` novo, até 200 steps cada) e as tira da memória. Steps raiz ainda abertas
|
|
347
|
-
* ficam para o próximo flush ou para o `finish()`. É assim que um agente sempre
|
|
348
|
-
* ligado (`start()`), cuja run não termina, entrega as etapas enquanto processa.
|
|
349
|
-
* Devolve quantas steps foram enviadas.
|
|
350
|
-
*/
|
|
351
|
-
flush(): number;
|
|
352
|
-
/** Entrega já (com teto) o que está na fila do transport — as transactions parciais inclusive. */
|
|
353
|
-
drain(timeoutMs: number): Promise<void>;
|
|
354
|
-
private payload;
|
|
355
|
-
finish(): void;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
209
|
interface FileDownloadOptions {
|
|
359
210
|
/**
|
|
360
211
|
* Destino da cópia: uma pasta existente (ou terminada em `/`) recebe o arquivo com o nome
|
|
@@ -420,24 +271,25 @@ interface RunItemOptions extends RunItemImageOptions {
|
|
|
420
271
|
}
|
|
421
272
|
/**
|
|
422
273
|
* O item em processamento dentro de `items.each`: o desfecho (`succeeded`/`failed`/
|
|
423
|
-
* `occurrence`) com o `id` e o payload base já resolvidos, e
|
|
424
|
-
*
|
|
425
|
-
*
|
|
274
|
+
* `occurrence`) com o `id` e o payload base já resolvidos, e o handle `step` da etapa do
|
|
275
|
+
* item (`warning`/`image`/`data`). Sub-etapas: `hobots.step(...)` dentro do handler já
|
|
276
|
+
* aninha na etapa do item. Sem chamada explícita, o SDK decide: retornou → `succeeded`;
|
|
277
|
+
* lançou → `failed` com a mensagem do erro.
|
|
426
278
|
*/
|
|
427
279
|
interface RunItemHandle {
|
|
428
280
|
/** Posição do elemento na lista (0-based). */
|
|
429
281
|
readonly index: number;
|
|
430
282
|
/** Identidade de negócio resolvida por `options.id` (undefined = o SDK gera uma). */
|
|
431
283
|
readonly id: string | undefined;
|
|
432
|
-
/**
|
|
433
|
-
readonly step:
|
|
284
|
+
/** Handle da etapa deste item no waterfall de performance; undefined fora de uma execução. */
|
|
285
|
+
readonly step: StepHandle | undefined;
|
|
434
286
|
/** true depois do primeiro desfecho registrado (o SDK não sobrescreve o que o handler decidiu). */
|
|
435
287
|
readonly reported: boolean;
|
|
436
288
|
/** Item processado com sucesso. `payload` é mesclado sobre o payload base de `options.payload`. */
|
|
437
289
|
succeeded(payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
438
|
-
/** Falha sem lançar — o loop segue igual; a
|
|
290
|
+
/** Falha sem lançar — o loop segue igual; a etapa vira `error` com o motivo. A imagem vai no item. */
|
|
439
291
|
failed(message: string, payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
440
|
-
/** Ocorrência de negócio — a
|
|
292
|
+
/** Ocorrência de negócio — a etapa vira `warning` com o motivo. A imagem vai no item. */
|
|
441
293
|
occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
442
294
|
}
|
|
443
295
|
interface RunItemsEachOptions<T> {
|
|
@@ -445,15 +297,20 @@ interface RunItemsEachOptions<T> {
|
|
|
445
297
|
id?: (element: T, index: number) => string | number | null | undefined;
|
|
446
298
|
/** Atributos base do item (viram colunas no app) — presentes em qualquer desfecho, inclusive falha. */
|
|
447
299
|
payload?: (element: T, index: number) => Record<string, unknown> | undefined;
|
|
448
|
-
/** `op` da
|
|
300
|
+
/** `op` da etapa de cada item no waterfall. Default: 'item'. */
|
|
449
301
|
op?: string;
|
|
450
|
-
/** Descrição da
|
|
302
|
+
/** Descrição da etapa de cada item. Default: o `id`, senão `#<posição>`. */
|
|
451
303
|
description?: (element: T, index: number) => string;
|
|
452
304
|
/**
|
|
453
305
|
* Progresso automático: declara o total (tamanho da lista, se o bot ainda não declarou um)
|
|
454
306
|
* e avança a cada elemento. `false` deixa o progresso por conta do bot. Default: true.
|
|
455
307
|
*/
|
|
456
308
|
progress?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* Ao fim de cada ciclo, `hobots.flush()`: a etapa, o item e os logs do elemento aparecem na
|
|
311
|
+
* Central na hora. `false` desliga (tudo sai no envio periódico ou no fim da run). Default: true.
|
|
312
|
+
*/
|
|
313
|
+
flush?: boolean;
|
|
457
314
|
}
|
|
458
315
|
/** Totalizadores do `items.each`, pelo desfecho final de cada elemento. */
|
|
459
316
|
interface RunItemsEachResult {
|
|
@@ -486,8 +343,8 @@ interface RunItems {
|
|
|
486
343
|
occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemOptions): void;
|
|
487
344
|
/**
|
|
488
345
|
* Processa uma lista item a item com o contrato da plataforma garantido pelo SDK: cada
|
|
489
|
-
* elemento vira uma
|
|
490
|
-
* (com a mensagem do erro), marca a
|
|
346
|
+
* elemento vira uma etapa e um item; uma exceção no handler registra o item como `failed`
|
|
347
|
+
* (com a mensagem do erro), marca a etapa como `error` e **segue para o próximo** — a
|
|
491
348
|
* lista inteira é processada, e o progresso avança a cada elemento. Só cancelamento,
|
|
492
349
|
* timeout e shutdown interrompem o loop (o erro sobe como em qualquer ponto de parada).
|
|
493
350
|
* Resolve com os totalizadores por desfecho.
|
|
@@ -534,24 +391,29 @@ interface RunContext {
|
|
|
534
391
|
*/
|
|
535
392
|
readonly files: RunFiles;
|
|
536
393
|
/**
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
394
|
+
* Registra a etapa `name` da execução executando `fn(etapa)` — o handle tem `warning`,
|
|
395
|
+
* `image` e `data`. Resolve com o retorno de `fn`. Falhou? Tenta de novo até `retries`
|
|
396
|
+
* vezes (default 1; `retries: 0` desliga), esperando `retryDelayMs` (default 5_000) entre
|
|
397
|
+
* as tentativas. Uma etapa só na Central: `warning` com o motivo quando a nova tentativa
|
|
398
|
+
* deu certo, `error` quando esgotou (a exceção sobe), `cancelled` em cancelamento/timeout
|
|
399
|
+
* (nunca repetem). `hobots.step` dentro de outra etapa vira sub-etapa. Abrir a etapa é um
|
|
400
|
+
* ponto de parada cooperativo (lança `RunCanceled` se a run foi cancelada). Ao terminar, a
|
|
401
|
+
* etapa raiz faz `flush()` (aparece na Central na hora); `flush: false` desliga.
|
|
540
402
|
*/
|
|
541
|
-
|
|
403
|
+
step<T>(name: string, fn: StepFn<T>, options?: StepOptions): Promise<T>;
|
|
542
404
|
/**
|
|
543
|
-
* Entrega já o que a execução fez: as
|
|
405
|
+
* Entrega já o que a execução fez: as etapas raiz finalizadas viram transactions parciais
|
|
544
406
|
* (waterfall da Central sem esperar a run terminar) e itens, logs e progresso pendentes
|
|
545
|
-
* saem sem esperar o throttle.
|
|
546
|
-
*
|
|
547
|
-
* teto (`timeoutMs`, default 15s) e nunca lança.
|
|
407
|
+
* saem sem esperar o throttle. `step` (raiz) e cada ciclo de `items.each` já fazem isto
|
|
408
|
+
* sozinhos; chame à mão só para o que roda fora deles (ex.: no `start()`, uma rodada que
|
|
409
|
+
* só loga). Aguarda a entrega com teto (`timeoutMs`, default 15s) e nunca lança.
|
|
548
410
|
*/
|
|
549
411
|
flush(timeoutMs?: number): Promise<void>;
|
|
550
412
|
/** Dispara em cancelamento (run cancelada no app), timeout ou shutdown — cancelamento cooperativo */
|
|
551
413
|
readonly signal: AbortSignal;
|
|
552
414
|
/**
|
|
553
415
|
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
554
|
-
* items/progress/
|
|
416
|
+
* items/progress/step/sleep/retry; use para um controle mais fino.
|
|
555
417
|
*/
|
|
556
418
|
throwIfCanceled(): void;
|
|
557
419
|
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
@@ -564,7 +426,7 @@ type RunHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => v
|
|
|
564
426
|
|
|
565
427
|
/**
|
|
566
428
|
* O objeto global do SDK: as funções do processo (register/start/close/captureException/
|
|
567
|
-
* retry) e o contexto da execução ATUAL (log, items, progress,
|
|
429
|
+
* retry) e o contexto da execução ATUAL (log, items, progress, step, signal…),
|
|
568
430
|
* resolvido a cada acesso — funciona de qualquer módulo, sem passar `ctx` de mão em mão.
|
|
569
431
|
*/
|
|
570
432
|
interface Hobots extends RunContext {
|
|
@@ -580,9 +442,9 @@ interface Hobots extends RunContext {
|
|
|
580
442
|
/** Captura uma exceção como issue (módulo Issues). Retorna o event_id. */
|
|
581
443
|
captureException(error: unknown, hint?: CaptureHint): string | undefined;
|
|
582
444
|
/**
|
|
583
|
-
* Embrulha um print para ir junto de um log, item ou
|
|
445
|
+
* Embrulha um print para ir junto de um log, item ou etapa — `hobots.log.error('x', hobots.image(png))`,
|
|
584
446
|
* `hobots.items.failed('x', payload, { image: hobots.image(png, { caption }) })`,
|
|
585
|
-
* `
|
|
447
|
+
* `etapa.warning('x', { image: png })`. Puro: nenhum I/O até o evento ser registrado.
|
|
586
448
|
*/
|
|
587
449
|
image(input: AttachInput, options?: ImageOptions): ImageAttachment;
|
|
588
450
|
/** O valor tem a forma de um arquivo de campo de upload (`FileRef`) — puro, sem I/O. */
|
|
@@ -600,4 +462,4 @@ declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: Retr
|
|
|
600
462
|
declare const image: (input: AttachInput, options?: ImageOptions) => ImageAttachment;
|
|
601
463
|
declare const isFileRef: (value: unknown) => value is FileRef;
|
|
602
464
|
|
|
603
|
-
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput,
|
|
465
|
+
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventType, type FileDownloadOptions, FileRef, type Hobots, type HobotsOptions, ImageAttachment, type ImageInput, type ImageOptions, type ItemColumnInput, type ItemsOptions, type RegisterOptions, type RetryDelay, type RetryOptions, RunAttachmentContentType, type RunContext, type RunFiles, type RunHandler, type RunItemHandle, type RunItemImageOptions, type RunItemOptions, RunItemStatus, type RunItems, type RunItemsEachHandler, type RunItemsEachOptions, type RunItemsEachResult, type RunLogger, type RunOptions, RunProgress, type RunProgressReporter, type StartOptions, type StepFn, type StepHandle, type StepOptions, captureException, close, hobots as default, hobots, image, isFileRef, register, retry, start };
|