hobots 4.1.0 → 4.5.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 +49 -5
- package/dist/index.cjs +685 -110
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +101 -23
- package/dist/index.d.ts +101 -23
- package/dist/index.js +685 -110
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +50 -1
- package/dist/protocol.d.ts +50 -1
- package/docs/api-reference.md +9 -5
- package/docs/concepts.md +3 -3
- package/docs/getting-started.md +4 -2
- package/docs/protocol.md +21 -3
- package/docs/runs.md +41 -11
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RunAttachmentContentType, EventType, EnvironmentInput, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunProgress } from './protocol.cjs';
|
|
2
|
-
export { Breadcrumb, BreadcrumbLevel, Envelope, EnvelopeItem, Environment, EventUser, ExceptionData, 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.cjs';
|
|
1
|
+
import { RunAttachmentContentType, EventType, EnvironmentInput, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, FileRef, RunItemStatus, RunProgress } from './protocol.cjs';
|
|
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.cjs';
|
|
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;
|
|
@@ -49,11 +49,11 @@ type ItemColumnInput = string | {
|
|
|
49
49
|
};
|
|
50
50
|
|
|
51
51
|
/**
|
|
52
|
-
* Opções do processo (telemetria, identidade, handlers globais).
|
|
53
|
-
*
|
|
52
|
+
* Opções do processo (telemetria, identidade, handlers globais). Só há uma chamada a
|
|
53
|
+
* register()/start() por processo — a segunda lança (`o agente já foi iniciado`).
|
|
54
54
|
*/
|
|
55
55
|
interface HobotsOptions {
|
|
56
|
-
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie
|
|
56
|
+
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie na Central: agente → Configurações → agente → aba credenciais. */
|
|
57
57
|
clientSecret?: string;
|
|
58
58
|
/**
|
|
59
59
|
* Identificador único e estável desta instância — a identidade do agente no painel
|
|
@@ -78,7 +78,10 @@ interface HobotsOptions {
|
|
|
78
78
|
* instância no app) e como `contexts.machine` em cada evento. Só em Node. Default: true
|
|
79
79
|
*/
|
|
80
80
|
machineMetrics?: boolean;
|
|
81
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Erro não tratado vira issue: o que escapa do handler de uma execução (além de falhar a
|
|
83
|
+
* run; cancelamento fica de fora) e o que escapa fora dele (uncaughtException etc.). Default: true
|
|
84
|
+
*/
|
|
82
85
|
captureUnhandled?: boolean;
|
|
83
86
|
/**
|
|
84
87
|
* Avançado. Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
@@ -134,6 +137,14 @@ interface RegisterOptions extends RunOptions {
|
|
|
134
137
|
concurrency?: number;
|
|
135
138
|
/** Intervalo entre polls sem trabalho (mínimo 1_000). Default: 2_000 */
|
|
136
139
|
pollIntervalMs?: number;
|
|
140
|
+
/**
|
|
141
|
+
* Avançado. Executa só esta run (já reivindicada para a instância, ex.: pelo Studio) em
|
|
142
|
+
* vez de fazer poll: anexa-se a ela (`POST /v1/runs/:id/start`), roda o handler uma vez e
|
|
143
|
+
* encerra o SDK (`close()`), liberando o processo. 404/409 (run inexistente, cancelada, já
|
|
144
|
+
* iniciada ou de outra instância) encerram sem rodar o handler. Default: env HOBOTS_RUN_ID;
|
|
145
|
+
* sem ela, poll normal.
|
|
146
|
+
*/
|
|
147
|
+
runId?: string;
|
|
137
148
|
}
|
|
138
149
|
/** Opções de `start()` — agente sempre ligado, que abre a própria run. */
|
|
139
150
|
type StartOptions = RunOptions;
|
|
@@ -209,6 +220,11 @@ interface ClientOptions {
|
|
|
209
220
|
/** Tags aplicadas a todos os eventos e transactions */
|
|
210
221
|
tags?: Record<string, string>;
|
|
211
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;
|
|
212
228
|
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
213
229
|
flushIntervalMs?: number;
|
|
214
230
|
maxBatchSize?: number;
|
|
@@ -272,23 +288,29 @@ declare class Step {
|
|
|
272
288
|
*/
|
|
273
289
|
setStatus(status: StepStatus, message?: string, options?: StepOutcomeOptions): this;
|
|
274
290
|
/**
|
|
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.
|
|
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.
|
|
277
293
|
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
294
|
+
* Numa step já fechada não faz nada.
|
|
278
295
|
*/
|
|
279
|
-
|
|
296
|
+
failed(error: unknown, message?: string, options?: StepOutcomeOptions): this;
|
|
280
297
|
/**
|
|
281
298
|
* Dispara o upload pela run (sink do RunReporter) e referencia o anexo em
|
|
282
299
|
* `data.attachments` (chave reservada; teto igual ao das linhas de log). Fora de uma
|
|
283
300
|
* run não há onde pendurar a imagem — descarta com aviso único.
|
|
284
301
|
*/
|
|
285
302
|
private attachImage;
|
|
286
|
-
/** Motivo registrado via setStatus(…, message) ou
|
|
303
|
+
/** Motivo registrado via setStatus(…, message) ou failed — usado no log de FINISH. */
|
|
287
304
|
private reason;
|
|
288
305
|
setData(key: string, value: unknown): this;
|
|
289
306
|
/** Step aninhada (filha desta step). */
|
|
290
|
-
|
|
291
|
-
|
|
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;
|
|
292
314
|
toJSON(): StepData;
|
|
293
315
|
}
|
|
294
316
|
/**
|
|
@@ -331,12 +353,26 @@ declare class Transaction {
|
|
|
331
353
|
attachImage(image: ImageInput): string | undefined;
|
|
332
354
|
/**
|
|
333
355
|
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
334
|
-
* `hobots.transaction.
|
|
356
|
+
* `hobots.transaction.start()` (e `step.start()`) param uma run cancelada.
|
|
335
357
|
*/
|
|
336
358
|
setStepGuard(guard: () => void): void;
|
|
337
359
|
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
338
|
-
/** Step direta da transaction. */
|
|
339
|
-
|
|
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;
|
|
340
376
|
setTag(key: string, value: string): this;
|
|
341
377
|
setStatus(status: string): this;
|
|
342
378
|
setName(name: string): this;
|
|
@@ -355,6 +391,38 @@ declare class Transaction {
|
|
|
355
391
|
finish(): void;
|
|
356
392
|
}
|
|
357
393
|
|
|
394
|
+
interface FileDownloadOptions {
|
|
395
|
+
/**
|
|
396
|
+
* Destino da cópia: uma pasta existente (ou terminada em `/`) recebe o arquivo com o nome
|
|
397
|
+
* original; qualquer outro caminho é o arquivo final. Omitido: pasta temporária da
|
|
398
|
+
* execução, apagada quando ela termina.
|
|
399
|
+
*/
|
|
400
|
+
dest?: string;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Arquivos dos campos de upload do formulário (`hobots.files`). O valor do campo nos
|
|
404
|
+
* params é um `FileRef` (ou uma lista deles); `download` traz o arquivo para o disco
|
|
405
|
+
* desta máquina — do S3 (enviado pela Central) ou da pasta do Studio (mesmo computador)
|
|
406
|
+
* — e o consome na origem: cada arquivo é baixado uma vez.
|
|
407
|
+
*/
|
|
408
|
+
interface RunFiles {
|
|
409
|
+
/** Todos os arquivos dos params (campos de topo, valor único ou lista), na ordem dos campos. */
|
|
410
|
+
list(): FileRef[];
|
|
411
|
+
/** O arquivo do campo (campo único), a lista (campo "vários arquivos") ou undefined. */
|
|
412
|
+
get(field: string): FileRef | FileRef[] | undefined;
|
|
413
|
+
/**
|
|
414
|
+
* Baixa um arquivo e resolve com o caminho local. Aceita o `FileRef` ou o nome de um
|
|
415
|
+
* campo de arquivo único (para campo com vários arquivos, use `downloadAll`). Só depois
|
|
416
|
+
* da cópia completa e conferida o arquivo é consumido na origem — uma falha não perde
|
|
417
|
+
* nada e pode ser tentada de novo. Respeita o cancelamento da execução.
|
|
418
|
+
*/
|
|
419
|
+
download(refOrField: FileRef | string, options?: FileDownloadOptions): Promise<string>;
|
|
420
|
+
/** Baixa todos os arquivos do campo (único ou lista), em ordem. `dest` aqui é uma pasta. */
|
|
421
|
+
downloadAll(field: string, options?: FileDownloadOptions): Promise<string[]>;
|
|
422
|
+
/** Conteúdo do arquivo em memória — baixa, lê e apaga a cópia temporária. */
|
|
423
|
+
read(refOrField: FileRef | string): Promise<Buffer>;
|
|
424
|
+
}
|
|
425
|
+
|
|
358
426
|
/**
|
|
359
427
|
* `hobots.log`: cada método aceita vários argumentos, como `console.log` — cada um vira
|
|
360
428
|
* texto (`safeString`) e são unidos por espaço. Nunca lança, nem com a run cancelada.
|
|
@@ -389,7 +457,7 @@ interface RunItemOptions extends RunItemImageOptions {
|
|
|
389
457
|
/**
|
|
390
458
|
* O item em processamento dentro de `items.each`: o desfecho (`succeeded`/`failed`/
|
|
391
459
|
* `occurrence`) com o `id` e o payload base já resolvidos, e a step da etapa para quem
|
|
392
|
-
* quiser medir sub-etapas (`item.step.
|
|
460
|
+
* quiser medir sub-etapas (`item.step.start(...)`). Sem chamada explícita, o SDK
|
|
393
461
|
* decide: retornou → `succeeded`; lançou → `failed` com a mensagem do erro.
|
|
394
462
|
*/
|
|
395
463
|
interface RunItemHandle {
|
|
@@ -455,7 +523,7 @@ interface RunItems {
|
|
|
455
523
|
/**
|
|
456
524
|
* Processa uma lista item a item com o contrato da plataforma garantido pelo SDK: cada
|
|
457
525
|
* elemento vira uma step e um item; uma exceção no handler registra o item como `failed`
|
|
458
|
-
* (com a mensagem do erro), marca a step com `
|
|
526
|
+
* (com a mensagem do erro), marca a step com `failed` e **segue para o próximo** — a
|
|
459
527
|
* lista inteira é processada, e o progresso avança a cada elemento. Só cancelamento,
|
|
460
528
|
* timeout e shutdown interrompem o loop (o erro sobe como em qualquer ponto de parada).
|
|
461
529
|
* Resolve com os totalizadores por desfecho.
|
|
@@ -495,10 +563,17 @@ interface RunContext {
|
|
|
495
563
|
readonly items: RunItems;
|
|
496
564
|
/** Progresso declarado (barra + ETA no app) — opcional, independente de `items` */
|
|
497
565
|
readonly progress: RunProgressReporter;
|
|
566
|
+
/**
|
|
567
|
+
* Arquivos dos campos de upload do formulário: `list()`, `get(campo)`, `download(refOuCampo)`
|
|
568
|
+
* (caminho local), `downloadAll(campo)` e `read(refOuCampo)` (conteúdo em memória).
|
|
569
|
+
* Cada arquivo é consumido na origem ao ser baixado — baixe uma vez e reaproveite a cópia.
|
|
570
|
+
*/
|
|
571
|
+
readonly files: RunFiles;
|
|
498
572
|
/**
|
|
499
573
|
* Transaction de performance desta execução — já correlacionada à run e finalizada
|
|
500
|
-
* automaticamente ao fim do handler. Use `transaction.
|
|
501
|
-
*
|
|
574
|
+
* automaticamente ao fim do handler. Use `transaction.start(op, description)` para
|
|
575
|
+
* abrir as etapas (steps) e `succeeded(op?)`/`failed(error, op?)` para fechá-las; elas
|
|
576
|
+
* aparecem como waterfall na aba de performance da execução.
|
|
502
577
|
*/
|
|
503
578
|
readonly transaction: Transaction;
|
|
504
579
|
/**
|
|
@@ -513,7 +588,7 @@ interface RunContext {
|
|
|
513
588
|
readonly signal: AbortSignal;
|
|
514
589
|
/**
|
|
515
590
|
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
516
|
-
* items/progress/transaction.
|
|
591
|
+
* items/progress/transaction.start/sleep/retry; use para um controle mais fino.
|
|
517
592
|
*/
|
|
518
593
|
throwIfCanceled(): void;
|
|
519
594
|
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
@@ -544,9 +619,11 @@ interface Hobots extends RunContext {
|
|
|
544
619
|
/**
|
|
545
620
|
* Embrulha um print para ir junto de um log, item ou step — `hobots.log.error('x', hobots.image(png))`,
|
|
546
621
|
* `hobots.items.failed('x', payload, { image: hobots.image(png, { caption }) })`,
|
|
547
|
-
* `step.
|
|
622
|
+
* `step.failed(err, undefined, { image: png })`. Puro: nenhum I/O até o evento ser registrado.
|
|
548
623
|
*/
|
|
549
624
|
image(input: AttachInput, options?: ImageOptions): ImageAttachment;
|
|
625
|
+
/** O valor tem a forma de um arquivo de campo de upload (`FileRef`) — puro, sem I/O. */
|
|
626
|
+
isFileRef(value: unknown): value is FileRef;
|
|
550
627
|
}
|
|
551
628
|
declare global {
|
|
552
629
|
var hobots: Hobots;
|
|
@@ -558,5 +635,6 @@ declare const close: (timeoutMs?: number) => Promise<boolean>;
|
|
|
558
635
|
declare const captureException: (error: unknown, hint?: CaptureHint) => string | undefined;
|
|
559
636
|
declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions) => Promise<T>;
|
|
560
637
|
declare const image: (input: AttachInput, options?: ImageOptions) => ImageAttachment;
|
|
638
|
+
declare const isFileRef: (value: unknown) => value is FileRef;
|
|
561
639
|
|
|
562
|
-
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, HeartbeatPayload, type Hobots, type HobotsOptions, ImageAttachment, type ImageInput, type ImageOptions, type ItemColumnInput, type ItemsOptions, MachineSnapshot, type RegisterOptions, type RetryDelay, type RetryOptions, RunAttachmentContentType, type RunContext, type RunHandler, type RunItemHandle, type RunItemImageOptions, type RunItemOptions, RunItemStatus, type RunItems, type RunItemsEachHandler, type RunItemsEachOptions, type RunItemsEachResult, RunLogLevel, type RunLogger, type RunOptions, RunProgress, type RunProgressReporter, type StartOptions, Step, StepData, type StepOutcomeOptions, StepStatus, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, image, register, retry, start };
|
|
640
|
+
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, type FileDownloadOptions, FileRef, HeartbeatPayload, type Hobots, type HobotsOptions, ImageAttachment, type ImageInput, type ImageOptions, type ItemColumnInput, type ItemsOptions, MachineSnapshot, 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, RunLogLevel, type RunLogger, type RunOptions, RunProgress, type RunProgressReporter, type StartOptions, Step, StepData, type StepOutcomeOptions, StepStatus, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, image, isFileRef, register, retry, start };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RunAttachmentContentType, EventType, EnvironmentInput, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunProgress } from './protocol.js';
|
|
2
|
-
export { Breadcrumb, BreadcrumbLevel, Envelope, EnvelopeItem, Environment, EventUser, ExceptionData, 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, EventType, EnvironmentInput, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, FileRef, RunItemStatus, RunProgress } from './protocol.js';
|
|
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';
|
|
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;
|
|
@@ -49,11 +49,11 @@ type ItemColumnInput = string | {
|
|
|
49
49
|
};
|
|
50
50
|
|
|
51
51
|
/**
|
|
52
|
-
* Opções do processo (telemetria, identidade, handlers globais).
|
|
53
|
-
*
|
|
52
|
+
* Opções do processo (telemetria, identidade, handlers globais). Só há uma chamada a
|
|
53
|
+
* register()/start() por processo — a segunda lança (`o agente já foi iniciado`).
|
|
54
54
|
*/
|
|
55
55
|
interface HobotsOptions {
|
|
56
|
-
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie
|
|
56
|
+
/** Client Secret do agente (hb_…). Default: env HOBOTS_CLIENT_SECRET. Copie na Central: agente → Configurações → agente → aba credenciais. */
|
|
57
57
|
clientSecret?: string;
|
|
58
58
|
/**
|
|
59
59
|
* Identificador único e estável desta instância — a identidade do agente no painel
|
|
@@ -78,7 +78,10 @@ interface HobotsOptions {
|
|
|
78
78
|
* instância no app) e como `contexts.machine` em cada evento. Só em Node. Default: true
|
|
79
79
|
*/
|
|
80
80
|
machineMetrics?: boolean;
|
|
81
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Erro não tratado vira issue: o que escapa do handler de uma execução (além de falhar a
|
|
83
|
+
* run; cancelamento fica de fora) e o que escapa fora dele (uncaughtException etc.). Default: true
|
|
84
|
+
*/
|
|
82
85
|
captureUnhandled?: boolean;
|
|
83
86
|
/**
|
|
84
87
|
* Avançado. Instala handlers de SIGINT/SIGTERM/uncaughtException que reportam as runs
|
|
@@ -134,6 +137,14 @@ interface RegisterOptions extends RunOptions {
|
|
|
134
137
|
concurrency?: number;
|
|
135
138
|
/** Intervalo entre polls sem trabalho (mínimo 1_000). Default: 2_000 */
|
|
136
139
|
pollIntervalMs?: number;
|
|
140
|
+
/**
|
|
141
|
+
* Avançado. Executa só esta run (já reivindicada para a instância, ex.: pelo Studio) em
|
|
142
|
+
* vez de fazer poll: anexa-se a ela (`POST /v1/runs/:id/start`), roda o handler uma vez e
|
|
143
|
+
* encerra o SDK (`close()`), liberando o processo. 404/409 (run inexistente, cancelada, já
|
|
144
|
+
* iniciada ou de outra instância) encerram sem rodar o handler. Default: env HOBOTS_RUN_ID;
|
|
145
|
+
* sem ela, poll normal.
|
|
146
|
+
*/
|
|
147
|
+
runId?: string;
|
|
137
148
|
}
|
|
138
149
|
/** Opções de `start()` — agente sempre ligado, que abre a própria run. */
|
|
139
150
|
type StartOptions = RunOptions;
|
|
@@ -209,6 +220,11 @@ interface ClientOptions {
|
|
|
209
220
|
/** Tags aplicadas a todos os eventos e transactions */
|
|
210
221
|
tags?: Record<string, string>;
|
|
211
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;
|
|
212
228
|
/** Knobs internos do transport (testes) — não fazem parte da API pública */
|
|
213
229
|
flushIntervalMs?: number;
|
|
214
230
|
maxBatchSize?: number;
|
|
@@ -272,23 +288,29 @@ declare class Step {
|
|
|
272
288
|
*/
|
|
273
289
|
setStatus(status: StepStatus, message?: string, options?: StepOutcomeOptions): this;
|
|
274
290
|
/**
|
|
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.
|
|
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.
|
|
277
293
|
* `options.image` pendura um print do estado da tela em `data.attachments`.
|
|
294
|
+
* Numa step já fechada não faz nada.
|
|
278
295
|
*/
|
|
279
|
-
|
|
296
|
+
failed(error: unknown, message?: string, options?: StepOutcomeOptions): this;
|
|
280
297
|
/**
|
|
281
298
|
* Dispara o upload pela run (sink do RunReporter) e referencia o anexo em
|
|
282
299
|
* `data.attachments` (chave reservada; teto igual ao das linhas de log). Fora de uma
|
|
283
300
|
* run não há onde pendurar a imagem — descarta com aviso único.
|
|
284
301
|
*/
|
|
285
302
|
private attachImage;
|
|
286
|
-
/** Motivo registrado via setStatus(…, message) ou
|
|
303
|
+
/** Motivo registrado via setStatus(…, message) ou failed — usado no log de FINISH. */
|
|
287
304
|
private reason;
|
|
288
305
|
setData(key: string, value: unknown): this;
|
|
289
306
|
/** Step aninhada (filha desta step). */
|
|
290
|
-
|
|
291
|
-
|
|
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;
|
|
292
314
|
toJSON(): StepData;
|
|
293
315
|
}
|
|
294
316
|
/**
|
|
@@ -331,12 +353,26 @@ declare class Transaction {
|
|
|
331
353
|
attachImage(image: ImageInput): string | undefined;
|
|
332
354
|
/**
|
|
333
355
|
* Conecta a checagem de cancelamento chamada antes de cada step nova — é assim que
|
|
334
|
-
* `hobots.transaction.
|
|
356
|
+
* `hobots.transaction.start()` (e `step.start()`) param uma run cancelada.
|
|
335
357
|
*/
|
|
336
358
|
setStepGuard(guard: () => void): void;
|
|
337
359
|
createStep(parentStepId: string, op?: string, description?: string): Step;
|
|
338
|
-
/** Step direta da transaction. */
|
|
339
|
-
|
|
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;
|
|
340
376
|
setTag(key: string, value: string): this;
|
|
341
377
|
setStatus(status: string): this;
|
|
342
378
|
setName(name: string): this;
|
|
@@ -355,6 +391,38 @@ declare class Transaction {
|
|
|
355
391
|
finish(): void;
|
|
356
392
|
}
|
|
357
393
|
|
|
394
|
+
interface FileDownloadOptions {
|
|
395
|
+
/**
|
|
396
|
+
* Destino da cópia: uma pasta existente (ou terminada em `/`) recebe o arquivo com o nome
|
|
397
|
+
* original; qualquer outro caminho é o arquivo final. Omitido: pasta temporária da
|
|
398
|
+
* execução, apagada quando ela termina.
|
|
399
|
+
*/
|
|
400
|
+
dest?: string;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Arquivos dos campos de upload do formulário (`hobots.files`). O valor do campo nos
|
|
404
|
+
* params é um `FileRef` (ou uma lista deles); `download` traz o arquivo para o disco
|
|
405
|
+
* desta máquina — do S3 (enviado pela Central) ou da pasta do Studio (mesmo computador)
|
|
406
|
+
* — e o consome na origem: cada arquivo é baixado uma vez.
|
|
407
|
+
*/
|
|
408
|
+
interface RunFiles {
|
|
409
|
+
/** Todos os arquivos dos params (campos de topo, valor único ou lista), na ordem dos campos. */
|
|
410
|
+
list(): FileRef[];
|
|
411
|
+
/** O arquivo do campo (campo único), a lista (campo "vários arquivos") ou undefined. */
|
|
412
|
+
get(field: string): FileRef | FileRef[] | undefined;
|
|
413
|
+
/**
|
|
414
|
+
* Baixa um arquivo e resolve com o caminho local. Aceita o `FileRef` ou o nome de um
|
|
415
|
+
* campo de arquivo único (para campo com vários arquivos, use `downloadAll`). Só depois
|
|
416
|
+
* da cópia completa e conferida o arquivo é consumido na origem — uma falha não perde
|
|
417
|
+
* nada e pode ser tentada de novo. Respeita o cancelamento da execução.
|
|
418
|
+
*/
|
|
419
|
+
download(refOrField: FileRef | string, options?: FileDownloadOptions): Promise<string>;
|
|
420
|
+
/** Baixa todos os arquivos do campo (único ou lista), em ordem. `dest` aqui é uma pasta. */
|
|
421
|
+
downloadAll(field: string, options?: FileDownloadOptions): Promise<string[]>;
|
|
422
|
+
/** Conteúdo do arquivo em memória — baixa, lê e apaga a cópia temporária. */
|
|
423
|
+
read(refOrField: FileRef | string): Promise<Buffer>;
|
|
424
|
+
}
|
|
425
|
+
|
|
358
426
|
/**
|
|
359
427
|
* `hobots.log`: cada método aceita vários argumentos, como `console.log` — cada um vira
|
|
360
428
|
* texto (`safeString`) e são unidos por espaço. Nunca lança, nem com a run cancelada.
|
|
@@ -389,7 +457,7 @@ interface RunItemOptions extends RunItemImageOptions {
|
|
|
389
457
|
/**
|
|
390
458
|
* O item em processamento dentro de `items.each`: o desfecho (`succeeded`/`failed`/
|
|
391
459
|
* `occurrence`) com o `id` e o payload base já resolvidos, e a step da etapa para quem
|
|
392
|
-
* quiser medir sub-etapas (`item.step.
|
|
460
|
+
* quiser medir sub-etapas (`item.step.start(...)`). Sem chamada explícita, o SDK
|
|
393
461
|
* decide: retornou → `succeeded`; lançou → `failed` com a mensagem do erro.
|
|
394
462
|
*/
|
|
395
463
|
interface RunItemHandle {
|
|
@@ -455,7 +523,7 @@ interface RunItems {
|
|
|
455
523
|
/**
|
|
456
524
|
* Processa uma lista item a item com o contrato da plataforma garantido pelo SDK: cada
|
|
457
525
|
* elemento vira uma step e um item; uma exceção no handler registra o item como `failed`
|
|
458
|
-
* (com a mensagem do erro), marca a step com `
|
|
526
|
+
* (com a mensagem do erro), marca a step com `failed` e **segue para o próximo** — a
|
|
459
527
|
* lista inteira é processada, e o progresso avança a cada elemento. Só cancelamento,
|
|
460
528
|
* timeout e shutdown interrompem o loop (o erro sobe como em qualquer ponto de parada).
|
|
461
529
|
* Resolve com os totalizadores por desfecho.
|
|
@@ -495,10 +563,17 @@ interface RunContext {
|
|
|
495
563
|
readonly items: RunItems;
|
|
496
564
|
/** Progresso declarado (barra + ETA no app) — opcional, independente de `items` */
|
|
497
565
|
readonly progress: RunProgressReporter;
|
|
566
|
+
/**
|
|
567
|
+
* Arquivos dos campos de upload do formulário: `list()`, `get(campo)`, `download(refOuCampo)`
|
|
568
|
+
* (caminho local), `downloadAll(campo)` e `read(refOuCampo)` (conteúdo em memória).
|
|
569
|
+
* Cada arquivo é consumido na origem ao ser baixado — baixe uma vez e reaproveite a cópia.
|
|
570
|
+
*/
|
|
571
|
+
readonly files: RunFiles;
|
|
498
572
|
/**
|
|
499
573
|
* Transaction de performance desta execução — já correlacionada à run e finalizada
|
|
500
|
-
* automaticamente ao fim do handler. Use `transaction.
|
|
501
|
-
*
|
|
574
|
+
* automaticamente ao fim do handler. Use `transaction.start(op, description)` para
|
|
575
|
+
* abrir as etapas (steps) e `succeeded(op?)`/`failed(error, op?)` para fechá-las; elas
|
|
576
|
+
* aparecem como waterfall na aba de performance da execução.
|
|
502
577
|
*/
|
|
503
578
|
readonly transaction: Transaction;
|
|
504
579
|
/**
|
|
@@ -513,7 +588,7 @@ interface RunContext {
|
|
|
513
588
|
readonly signal: AbortSignal;
|
|
514
589
|
/**
|
|
515
590
|
* Lança um erro `RunCanceled` se a run foi cancelada/abortada. O SDK já chama isto em
|
|
516
|
-
* items/progress/transaction.
|
|
591
|
+
* items/progress/transaction.start/sleep/retry; use para um controle mais fino.
|
|
517
592
|
*/
|
|
518
593
|
throwIfCanceled(): void;
|
|
519
594
|
/** Sleep cancelável: rejeita com `RunCanceled` se o signal disparar antes de ms. */
|
|
@@ -544,9 +619,11 @@ interface Hobots extends RunContext {
|
|
|
544
619
|
/**
|
|
545
620
|
* Embrulha um print para ir junto de um log, item ou step — `hobots.log.error('x', hobots.image(png))`,
|
|
546
621
|
* `hobots.items.failed('x', payload, { image: hobots.image(png, { caption }) })`,
|
|
547
|
-
* `step.
|
|
622
|
+
* `step.failed(err, undefined, { image: png })`. Puro: nenhum I/O até o evento ser registrado.
|
|
548
623
|
*/
|
|
549
624
|
image(input: AttachInput, options?: ImageOptions): ImageAttachment;
|
|
625
|
+
/** O valor tem a forma de um arquivo de campo de upload (`FileRef`) — puro, sem I/O. */
|
|
626
|
+
isFileRef(value: unknown): value is FileRef;
|
|
550
627
|
}
|
|
551
628
|
declare global {
|
|
552
629
|
var hobots: Hobots;
|
|
@@ -558,5 +635,6 @@ declare const close: (timeoutMs?: number) => Promise<boolean>;
|
|
|
558
635
|
declare const captureException: (error: unknown, hint?: CaptureHint) => string | undefined;
|
|
559
636
|
declare const retry: <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions) => Promise<T>;
|
|
560
637
|
declare const image: (input: AttachInput, options?: ImageOptions) => ImageAttachment;
|
|
638
|
+
declare const isFileRef: (value: unknown) => value is FileRef;
|
|
561
639
|
|
|
562
|
-
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, HeartbeatPayload, type Hobots, type HobotsOptions, ImageAttachment, type ImageInput, type ImageOptions, type ItemColumnInput, type ItemsOptions, MachineSnapshot, type RegisterOptions, type RetryDelay, type RetryOptions, RunAttachmentContentType, type RunContext, type RunHandler, type RunItemHandle, type RunItemImageOptions, type RunItemOptions, RunItemStatus, type RunItems, type RunItemsEachHandler, type RunItemsEachOptions, type RunItemsEachResult, RunLogLevel, type RunLogger, type RunOptions, RunProgress, type RunProgressReporter, type StartOptions, Step, StepData, type StepOutcomeOptions, StepStatus, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, image, register, retry, start };
|
|
640
|
+
export { type AttachInput, type CaptureAttachment, type CaptureHint, EnvironmentInput, EventPayload, EventType, type FileDownloadOptions, FileRef, HeartbeatPayload, type Hobots, type HobotsOptions, ImageAttachment, type ImageInput, type ImageOptions, type ItemColumnInput, type ItemsOptions, MachineSnapshot, 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, RunLogLevel, type RunLogger, type RunOptions, RunProgress, type RunProgressReporter, type StartOptions, Step, StepData, type StepOutcomeOptions, StepStatus, Transaction, TransactionPayload, captureException, close, hobots as default, hobots, image, isFileRef, register, retry, start };
|