hobots 4.5.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 +14 -11
- package/dist/cli.cjs +250 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/index.cjs +544 -222
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +75 -250
- package/dist/index.d.ts +75 -250
- package/dist/index.js +544 -222
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +5 -2
- package/dist/protocol.d.ts +5 -2
- package/docs/README.md +2 -2
- package/docs/api-reference.md +21 -7
- package/docs/concepts.md +11 -11
- package/docs/getting-started.md +1 -1
- package/docs/protocol.md +5 -5
- 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, RunStartRequest, RunStartResponse, 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);
|
|
@@ -36,18 +36,49 @@ 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
83
|
* Opções do processo (telemetria, identidade, handlers globais). Só há uma chamada a
|
|
53
84
|
* register()/start() por processo — a segunda lança (`o agente já foi iniciado`).
|
|
@@ -164,7 +195,7 @@ interface CaptureHint {
|
|
|
164
195
|
fingerprint?: string[];
|
|
165
196
|
/**
|
|
166
197
|
* Print da tela enviado junto da captura. Dentro de uma execução, a imagem vira anexo
|
|
167
|
-
* 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
|
|
168
199
|
* execução não há onde pendurar a imagem: o SDK descarta com um aviso. O upload roda
|
|
169
200
|
* em segundo plano e **nunca bloqueia nem lança**. PNG, JPEG ou WEBP, até 5 MB, 20 por execução.
|
|
170
201
|
*
|
|
@@ -175,222 +206,6 @@ interface CaptureHint {
|
|
|
175
206
|
attachment?: ImageInput | CaptureAttachment;
|
|
176
207
|
}
|
|
177
208
|
|
|
178
|
-
interface ResolvedConfig {
|
|
179
|
-
/** Client Secret do agente (enviado como Authorization: Bearer, nunca na URL) */
|
|
180
|
-
key: string;
|
|
181
|
-
baseUrl: string;
|
|
182
|
-
/** Ingestão de telemetria: <baseUrl>/v1/ingest */
|
|
183
|
-
ingestEndpoint: string;
|
|
184
|
-
/** API de execuções (poll, runs, itens, anexos): <baseUrl>/v1/runs */
|
|
185
|
-
runsBaseUrl: string;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Coleta CPU/memória/disco da máquina e do processo — só em Node (no browser é no-op).
|
|
190
|
-
*
|
|
191
|
-
* Os módulos `node:*` entram por import dinâmico (o bundle é `platform: neutral`), e
|
|
192
|
-
* `sample()` é síncrono e barato: `os.cpus()` + `statfsSync` + `process.memoryUsage()`.
|
|
193
|
-
* Nunca lança — telemetria de recurso não pode derrubar o bot nem o capture de um erro.
|
|
194
|
-
*/
|
|
195
|
-
declare class MachineSampler {
|
|
196
|
-
private readonly instanceId;
|
|
197
|
-
private readonly logger;
|
|
198
|
-
private os;
|
|
199
|
-
private fs;
|
|
200
|
-
private ready;
|
|
201
|
-
private prevCpu;
|
|
202
|
-
private prevProcessCpu;
|
|
203
|
-
private prevAt;
|
|
204
|
-
private lastCpuPercent;
|
|
205
|
-
private lastProcessCpuPercent;
|
|
206
|
-
constructor(instanceId: string, logger: Logger);
|
|
207
|
-
/** Carrega os módulos e tira a leitura-base de CPU (a primeira amostra ainda sai com cpu_percent null). */
|
|
208
|
-
start(): Promise<void>;
|
|
209
|
-
sample(): MachineSnapshot | undefined;
|
|
210
|
-
private cpuTotals;
|
|
211
|
-
/** Média desde a leitura anterior; leituras com menos de 1s de janela reutilizam a última média. */
|
|
212
|
-
private updateCpu;
|
|
213
|
-
private diskUsage;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** Opções de telemetria resolvidas pelo runtime a partir do primeiro register()/start(). */
|
|
217
|
-
interface ClientOptions {
|
|
218
|
-
environment?: EnvironmentInput;
|
|
219
|
-
release?: string;
|
|
220
|
-
/** Tags aplicadas a todos os eventos e transactions */
|
|
221
|
-
tags?: Record<string, string>;
|
|
222
|
-
debug?: boolean;
|
|
223
|
-
/**
|
|
224
|
-
* O erro final que escapou do handler de uma run também vira issue (além de falhar a run).
|
|
225
|
-
* Ligado pelo runtime junto com `captureUnhandled`; desligado no client cru (testes).
|
|
226
|
-
*/
|
|
227
|
-
captureRunErrors?: boolean;
|
|
228
|
-
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
229
|
-
flushIntervalMs?: number;
|
|
230
|
-
maxBatchSize?: number;
|
|
231
|
-
}
|
|
232
|
-
declare class Client {
|
|
233
|
-
#private;
|
|
234
|
-
readonly logger: Logger;
|
|
235
|
-
/** Eco de lifecycle (Transaction.emit) e afins só imprimem no terminal com debug ligado. */
|
|
236
|
-
readonly debug: boolean;
|
|
237
|
-
private readonly transport;
|
|
238
|
-
private machine;
|
|
239
|
-
constructor(options: ClientOptions, config: ResolvedConfig);
|
|
240
|
-
get options(): ClientOptions;
|
|
241
|
-
get config(): ResolvedConfig;
|
|
242
|
-
/** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
|
|
243
|
-
attachMachineSampler(sampler: MachineSampler | undefined): void;
|
|
244
|
-
/** Serialização explícita nunca inclui o secret. */
|
|
245
|
-
toJSON(): Record<string, unknown>;
|
|
246
|
-
captureException(error: unknown, hint?: CaptureHint): string;
|
|
247
|
-
captureEvent(event: EventPayload, hint?: CaptureHint): string;
|
|
248
|
-
private prepareEvent;
|
|
249
|
-
sendTransaction(payload: TransactionPayload): void;
|
|
250
|
-
sendHeartbeat(payload: HeartbeatPayload): void;
|
|
251
|
-
/**
|
|
252
|
-
* Ambiente do item: o dele, senão o das opções, senão produção. Centralizado
|
|
253
|
-
* porque evento, transaction e heartbeat precisam responder igual — o servidor
|
|
254
|
-
* normaliza apelidos legados, então aqui basta repassar.
|
|
255
|
-
*/
|
|
256
|
-
private resolveEnvironment;
|
|
257
|
-
flush(timeoutMs?: number): Promise<boolean>;
|
|
258
|
-
close(timeoutMs?: number): Promise<boolean>;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/** Recebe os eventos de lifecycle da transaction para espelhá-los nos logs da run. */
|
|
262
|
-
type LifecycleSink = (level: RunLogLevel, message: string) => void;
|
|
263
|
-
/**
|
|
264
|
-
* Recebe a imagem de uma step e dispara o upload pela run; devolve o id do anexo
|
|
265
|
-
* (já referenciável em `data.attachments`) ou undefined quando descartada.
|
|
266
|
-
*/
|
|
267
|
-
type AttachmentSink = (image: ImageInput, ts: string) => string | undefined;
|
|
268
|
-
/** Opções dos desfechos de step que aceitam um print do estado da tela. */
|
|
269
|
-
interface StepOutcomeOptions {
|
|
270
|
-
/** Print da step (bytes/caminho ou `hobots.image(bytes, { caption })`) — botão de imagem no app. */
|
|
271
|
-
image?: ImageInput;
|
|
272
|
-
}
|
|
273
|
-
declare class Step {
|
|
274
|
-
private readonly transaction;
|
|
275
|
-
readonly parentStepId: string;
|
|
276
|
-
readonly op?: string | undefined;
|
|
277
|
-
readonly description?: string | undefined;
|
|
278
|
-
readonly stepId: string;
|
|
279
|
-
readonly startTimestamp: string;
|
|
280
|
-
status: StepStatus;
|
|
281
|
-
endTimestamp?: string;
|
|
282
|
-
data?: Record<string, unknown>;
|
|
283
|
-
constructor(transaction: Transaction, parentStepId: string, op?: string | undefined, description?: string | undefined);
|
|
284
|
-
/**
|
|
285
|
-
* Desfecho da step. `message` (opcional) é o motivo legível — vai em `data.message`
|
|
286
|
-
* e aparece na Central (performance e banner da execução) e no log de FINISH.
|
|
287
|
-
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
288
|
-
*/
|
|
289
|
-
setStatus(status: StepStatus, message?: string, options?: StepOutcomeOptions): this;
|
|
290
|
-
/**
|
|
291
|
-
* Marca a step como `error` guardando o motivo em `data.error` ({ type, message }) e a
|
|
292
|
-
* fecha. Aceita qualquer valor lançado; `message` sobrescreve a mensagem do erro.
|
|
293
|
-
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
294
|
-
* Numa step já fechada não faz nada.
|
|
295
|
-
*/
|
|
296
|
-
failed(error: unknown, message?: string, options?: StepOutcomeOptions): this;
|
|
297
|
-
/**
|
|
298
|
-
* Dispara o upload pela run (sink do RunReporter) e referencia o anexo em
|
|
299
|
-
* `data.attachments` (chave reservada; teto igual ao das linhas de log). Fora de uma
|
|
300
|
-
* run não há onde pendurar a imagem — descarta com aviso único.
|
|
301
|
-
*/
|
|
302
|
-
private attachImage;
|
|
303
|
-
/** Motivo registrado via setStatus(…, message) ou failed — usado no log de FINISH. */
|
|
304
|
-
private reason;
|
|
305
|
-
setData(key: string, value: unknown): this;
|
|
306
|
-
/** Step aninhada (filha desta step). */
|
|
307
|
-
start(op?: string, description?: string): Step;
|
|
308
|
-
/**
|
|
309
|
-
* Fecha a step. O status fica o que estiver (`ok` por padrão, ou o de `setStatus`).
|
|
310
|
-
* Idempotente; a transaction fecha no fim da run o que ficou aberto.
|
|
311
|
-
*/
|
|
312
|
-
succeeded(): this;
|
|
313
|
-
private close;
|
|
314
|
-
toJSON(): StepData;
|
|
315
|
-
}
|
|
316
|
-
/**
|
|
317
|
-
* Uma unidade de trabalho nomeada (ex.: uma execução de rotina, uma sincronização).
|
|
318
|
-
* Steps filhas medem as etapas internas (chamadas HTTP, queries, etc.).
|
|
319
|
-
*/
|
|
320
|
-
declare class Transaction {
|
|
321
|
-
private readonly client;
|
|
322
|
-
name: string;
|
|
323
|
-
readonly op?: string | undefined;
|
|
324
|
-
/** Correlaciona a uma execução do agente — preenchido automaticamente em hobots.transaction */
|
|
325
|
-
private readonly runId?;
|
|
326
|
-
readonly eventId: string;
|
|
327
|
-
readonly stepId: string;
|
|
328
|
-
readonly startTimestamp: string;
|
|
329
|
-
status: string;
|
|
330
|
-
private readonly steps;
|
|
331
|
-
private readonly tags;
|
|
332
|
-
private finished;
|
|
333
|
-
private lifecycleSink?;
|
|
334
|
-
private attachmentSink?;
|
|
335
|
-
private warnedNoAttachmentSink;
|
|
336
|
-
private stepGuard?;
|
|
337
|
-
private lifecycleBacklog;
|
|
338
|
-
constructor(client: Client | undefined, name: string, op?: string | undefined,
|
|
339
|
-
/** Correlaciona a uma execução do agente — preenchido automaticamente em hobots.transaction */
|
|
340
|
-
runId?: string | undefined);
|
|
341
|
-
/**
|
|
342
|
-
* Registra o início/fim de uma step ou transaction: espelha a linha no sink de
|
|
343
|
-
* lifecycle, se conectado (é assim que os eventos de performance aparecem nos
|
|
344
|
-
* logs da run no app), e ecoa no terminal apenas com `debug: true` — o SDK não
|
|
345
|
-
* escreve no stdout do processo do usuário sem permissão.
|
|
346
|
-
*/
|
|
347
|
-
emit(kind: 'transaction' | 'step', phase: 'start' | 'finish', label: string, startTs?: string, endTs?: string, status?: StepStatus | string, reason?: string): void;
|
|
348
|
-
/** Conecta o espelho de lifecycle (RunReporter) e faz replay do backlog em ordem. */
|
|
349
|
-
setLifecycleSink(sink: LifecycleSink): void;
|
|
350
|
-
/** Conecta o pipeline de anexos da run — é o que dá imagem às steps. */
|
|
351
|
-
setAttachmentSink(sink: AttachmentSink): void;
|
|
352
|
-
/** Imagem de uma step → id do anexo pela run; sem run, descarta com aviso único. */
|
|
353
|
-
attachImage(image: ImageInput): string | undefined;
|
|
354
|
-
/**
|
|
355
|
-
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
356
|
-
* `hobots.transaction.start()` (e `step.start()`) param uma run cancelada.
|
|
357
|
-
*/
|
|
358
|
-
setStepGuard(guard: () => void): void;
|
|
359
|
-
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
360
|
-
/** Step direta da transaction. `op` é o nome usado por `succeeded(name)`/`failed(error, name)`. */
|
|
361
|
-
start(op?: string, description?: string): Step;
|
|
362
|
-
/**
|
|
363
|
-
* Fecha a step aberta mais recente — com `name`, a mais recente aberta com esse `op`.
|
|
364
|
-
* Sem step aberta (ou sem nenhuma com esse nome), não faz nada e devolve undefined.
|
|
365
|
-
*/
|
|
366
|
-
succeeded(name?: string): Step | undefined;
|
|
367
|
-
/**
|
|
368
|
-
* Marca como `error` e fecha a step aberta mais recente — com `name`, a mais recente
|
|
369
|
-
* aberta com esse `op`. `options.message` sobrescreve a mensagem do erro e
|
|
370
|
-
* `options.image` pendura um print. Sem step aberta, não faz nada e devolve undefined.
|
|
371
|
-
*/
|
|
372
|
-
failed(error: unknown, name?: string, options?: StepOutcomeOptions & {
|
|
373
|
-
message?: string;
|
|
374
|
-
}): Step | undefined;
|
|
375
|
-
private findOpenStep;
|
|
376
|
-
setTag(key: string, value: string): this;
|
|
377
|
-
setStatus(status: string): this;
|
|
378
|
-
setName(name: string): this;
|
|
379
|
-
/**
|
|
380
|
-
* Envia já as steps raiz finalizadas (e todas as descendentes, fechando as que
|
|
381
|
-
* ficaram abertas) como transactions parciais da mesma run (`op` hobots.run.flush,
|
|
382
|
-
* `event_id` novo, até 200 steps cada) e as tira da memória. Steps raiz ainda abertas
|
|
383
|
-
* ficam para o próximo flush ou para o `finish()`. É assim que um agente sempre
|
|
384
|
-
* ligado (`start()`), cuja run não termina, entrega as etapas enquanto processa.
|
|
385
|
-
* Devolve quantas steps foram enviadas.
|
|
386
|
-
*/
|
|
387
|
-
flush(): number;
|
|
388
|
-
/** Entrega já (com teto) o que está na fila do transport — as transactions parciais inclusive. */
|
|
389
|
-
drain(timeoutMs: number): Promise<void>;
|
|
390
|
-
private payload;
|
|
391
|
-
finish(): void;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
209
|
interface FileDownloadOptions {
|
|
395
210
|
/**
|
|
396
211
|
* Destino da cópia: uma pasta existente (ou terminada em `/`) recebe o arquivo com o nome
|
|
@@ -456,24 +271,25 @@ interface RunItemOptions extends RunItemImageOptions {
|
|
|
456
271
|
}
|
|
457
272
|
/**
|
|
458
273
|
* O item em processamento dentro de `items.each`: o desfecho (`succeeded`/`failed`/
|
|
459
|
-
* `occurrence`) com o `id` e o payload base já resolvidos, e
|
|
460
|
-
*
|
|
461
|
-
*
|
|
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.
|
|
462
278
|
*/
|
|
463
279
|
interface RunItemHandle {
|
|
464
280
|
/** Posição do elemento na lista (0-based). */
|
|
465
281
|
readonly index: number;
|
|
466
282
|
/** Identidade de negócio resolvida por `options.id` (undefined = o SDK gera uma). */
|
|
467
283
|
readonly id: string | undefined;
|
|
468
|
-
/**
|
|
469
|
-
readonly step:
|
|
284
|
+
/** Handle da etapa deste item no waterfall de performance; undefined fora de uma execução. */
|
|
285
|
+
readonly step: StepHandle | undefined;
|
|
470
286
|
/** true depois do primeiro desfecho registrado (o SDK não sobrescreve o que o handler decidiu). */
|
|
471
287
|
readonly reported: boolean;
|
|
472
288
|
/** Item processado com sucesso. `payload` é mesclado sobre o payload base de `options.payload`. */
|
|
473
289
|
succeeded(payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
474
|
-
/** 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. */
|
|
475
291
|
failed(message: string, payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
476
|
-
/** Ocorrência de negócio — a
|
|
292
|
+
/** Ocorrência de negócio — a etapa vira `warning` com o motivo. A imagem vai no item. */
|
|
477
293
|
occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemImageOptions): void;
|
|
478
294
|
}
|
|
479
295
|
interface RunItemsEachOptions<T> {
|
|
@@ -481,15 +297,20 @@ interface RunItemsEachOptions<T> {
|
|
|
481
297
|
id?: (element: T, index: number) => string | number | null | undefined;
|
|
482
298
|
/** Atributos base do item (viram colunas no app) — presentes em qualquer desfecho, inclusive falha. */
|
|
483
299
|
payload?: (element: T, index: number) => Record<string, unknown> | undefined;
|
|
484
|
-
/** `op` da
|
|
300
|
+
/** `op` da etapa de cada item no waterfall. Default: 'item'. */
|
|
485
301
|
op?: string;
|
|
486
|
-
/** Descrição da
|
|
302
|
+
/** Descrição da etapa de cada item. Default: o `id`, senão `#<posição>`. */
|
|
487
303
|
description?: (element: T, index: number) => string;
|
|
488
304
|
/**
|
|
489
305
|
* Progresso automático: declara o total (tamanho da lista, se o bot ainda não declarou um)
|
|
490
306
|
* e avança a cada elemento. `false` deixa o progresso por conta do bot. Default: true.
|
|
491
307
|
*/
|
|
492
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;
|
|
493
314
|
}
|
|
494
315
|
/** Totalizadores do `items.each`, pelo desfecho final de cada elemento. */
|
|
495
316
|
interface RunItemsEachResult {
|
|
@@ -522,8 +343,8 @@ interface RunItems {
|
|
|
522
343
|
occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemOptions): void;
|
|
523
344
|
/**
|
|
524
345
|
* Processa uma lista item a item com o contrato da plataforma garantido pelo SDK: cada
|
|
525
|
-
* elemento vira uma
|
|
526
|
-
* (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
|
|
527
348
|
* lista inteira é processada, e o progresso avança a cada elemento. Só cancelamento,
|
|
528
349
|
* timeout e shutdown interrompem o loop (o erro sobe como em qualquer ponto de parada).
|
|
529
350
|
* Resolve com os totalizadores por desfecho.
|
|
@@ -570,25 +391,29 @@ interface RunContext {
|
|
|
570
391
|
*/
|
|
571
392
|
readonly files: RunFiles;
|
|
572
393
|
/**
|
|
573
|
-
*
|
|
574
|
-
*
|
|
575
|
-
*
|
|
576
|
-
*
|
|
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.
|
|
577
402
|
*/
|
|
578
|
-
|
|
403
|
+
step<T>(name: string, fn: StepFn<T>, options?: StepOptions): Promise<T>;
|
|
579
404
|
/**
|
|
580
|
-
* 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
|
|
581
406
|
* (waterfall da Central sem esperar a run terminar) e itens, logs e progresso pendentes
|
|
582
|
-
* saem sem esperar o throttle.
|
|
583
|
-
*
|
|
584
|
-
* 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.
|
|
585
410
|
*/
|
|
586
411
|
flush(timeoutMs?: number): Promise<void>;
|
|
587
412
|
/** Dispara em cancelamento (run cancelada no app), timeout ou shutdown — cancelamento cooperativo */
|
|
588
413
|
readonly signal: AbortSignal;
|
|
589
414
|
/**
|
|
590
415
|
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
591
|
-
* items/progress/
|
|
416
|
+
* items/progress/step/sleep/retry; use para um controle mais fino.
|
|
592
417
|
*/
|
|
593
418
|
throwIfCanceled(): void;
|
|
594
419
|
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
@@ -601,7 +426,7 @@ type RunHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => v
|
|
|
601
426
|
|
|
602
427
|
/**
|
|
603
428
|
* O objeto global do SDK: as funções do processo (register/start/close/captureException/
|
|
604
|
-
* 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…),
|
|
605
430
|
* resolvido a cada acesso — funciona de qualquer módulo, sem passar `ctx` de mão em mão.
|
|
606
431
|
*/
|
|
607
432
|
interface Hobots extends RunContext {
|
|
@@ -617,9 +442,9 @@ interface Hobots extends RunContext {
|
|
|
617
442
|
/** Captura uma exceção como issue (módulo Issues). Retorna o event_id. */
|
|
618
443
|
captureException(error: unknown, hint?: CaptureHint): string | undefined;
|
|
619
444
|
/**
|
|
620
|
-
* 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))`,
|
|
621
446
|
* `hobots.items.failed('x', payload, { image: hobots.image(png, { caption }) })`,
|
|
622
|
-
* `
|
|
447
|
+
* `etapa.warning('x', { image: png })`. Puro: nenhum I/O até o evento ser registrado.
|
|
623
448
|
*/
|
|
624
449
|
image(input: AttachInput, options?: ImageOptions): ImageAttachment;
|
|
625
450
|
/** O valor tem a forma de um arquivo de campo de upload (`FileRef`) — puro, sem I/O. */
|
|
@@ -637,4 +462,4 @@ declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: Retr
|
|
|
637
462
|
declare const image: (input: AttachInput, options?: ImageOptions) => ImageAttachment;
|
|
638
463
|
declare const isFileRef: (value: unknown) => value is FileRef;
|
|
639
464
|
|
|
640
|
-
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 };
|