hobots 2.0.1 → 2.3.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/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { Breadcrumb, EventUser, EventType, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunAttachmentContentType } from './protocol.cjs';
2
- export { BreadcrumbLevel, Envelope, EnvelopeItem, ExceptionData, InstanceInfo, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame } from './protocol.cjs';
1
+ import { Breadcrumb, EventUser, EventType, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunProgress, RunAttachmentContentType } from './protocol.cjs';
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.cjs';
3
3
 
4
4
  /** Aceita tudo que o handler pode ter em mãos: bytes ou um caminho de arquivo (só Node). */
5
5
  type AttachInput = Uint8Array | ArrayBuffer | string;
@@ -47,15 +47,46 @@ interface Logger {
47
47
  error: (...args: unknown[]) => void;
48
48
  }
49
49
 
50
+ /**
51
+ * Coleta CPU/memória/disco da máquina e do processo — só em Node (no browser é no-op).
52
+ *
53
+ * Os módulos `node:*` entram por import dinâmico (o bundle é `platform: neutral`), e
54
+ * `sample()` é síncrono e barato: `os.cpus()` + `statfsSync` + `process.memoryUsage()`.
55
+ * Nunca lança — telemetria de recurso não pode derrubar o bot nem o capture de um erro.
56
+ */
57
+ declare class MachineSampler {
58
+ private readonly instanceId;
59
+ private readonly logger;
60
+ private os;
61
+ private fs;
62
+ private ready;
63
+ private prevCpu;
64
+ private prevProcessCpu;
65
+ private prevAt;
66
+ private lastCpuPercent;
67
+ private lastProcessCpuPercent;
68
+ constructor(instanceId: string, logger: Logger);
69
+ /** Carrega os módulos e tira a leitura-base de CPU (a primeira amostra ainda sai com cpu_percent null). */
70
+ start(): Promise<void>;
71
+ sample(): MachineSnapshot | undefined;
72
+ private cpuTotals;
73
+ /** Média desde a leitura anterior; leituras com menos de 1s de janela reutilizam a última média. */
74
+ private updateCpu;
75
+ private diskUsage;
76
+ }
77
+
50
78
  declare class Client {
51
79
  #private;
52
80
  readonly logger: Logger;
53
81
  /** Eco de lifecycle (Transaction.emit) e afins só imprimem no terminal com debug ligado. */
54
82
  readonly debug: boolean;
55
83
  private readonly transport;
84
+ private machine;
56
85
  constructor(options: InitOptions, config?: ResolvedConfig);
57
86
  get options(): InitOptions;
58
87
  get config(): ResolvedConfig;
88
+ /** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
89
+ attachMachineSampler(sampler: MachineSampler | undefined): void;
59
90
  /** Serialização explícita nunca inclui o secret. */
60
91
  toJSON(): Record<string, unknown>;
61
92
  captureException(error: unknown, hint: CaptureHint | undefined, scope: Scope): string;
@@ -198,6 +229,24 @@ interface RunItems {
198
229
  /** Ocorrência de negócio (ex.: "nota nº 10 não encontrada") — não é falha do bot. */
199
230
  occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemOptions): void;
200
231
  }
232
+ /**
233
+ * Progresso da execução (itens processados / total) — opcional e independente de
234
+ * `ctx.items`. Declare o total antes do loop e avance a cada item: a plataforma e o
235
+ * Studio mostram barra, percentual e tempo restante estimado. Sem `total()` nada é
236
+ * enviado. Chamadas são síncronas e baratas (≤ 1 PATCH/s, pegando carona nos logs).
237
+ */
238
+ interface RunProgressReporter {
239
+ /** Declara (ou ajusta) o total de itens previsto — inteiro >= 1. Idempotente. */
240
+ total(total: number): void;
241
+ /** Incrementa os processados (padrão 1). Clampa em `total`. */
242
+ advance(count?: number): void;
243
+ /** Define o valor absoluto de processados e, opcionalmente, o total. */
244
+ set(current: number, total?: number): void;
245
+ /** Processados até agora (0 antes de qualquer chamada). */
246
+ readonly current: number;
247
+ /** `{ current, total }` quando há total declarado; null caso contrário. */
248
+ readonly snapshot: RunProgress | null;
249
+ }
201
250
  interface RunContext {
202
251
  runId: string;
203
252
  task: string;
@@ -205,6 +254,8 @@ interface RunContext {
205
254
  log: RunLogger;
206
255
  /** Itens processados/gerados pela execução — a entrega do bot, com status e atributos */
207
256
  items: RunItems;
257
+ /** Progresso declarado (barra + ETA no app) — opcional, independente de `ctx.items` */
258
+ progress: RunProgressReporter;
208
259
  /**
209
260
  * Transaction de performance desta execução — já correlacionada à run e finalizada
210
261
  * automaticamente ao fim do handler. Use `ctx.tx.startChild(op, description)` pra medir
@@ -250,6 +301,12 @@ interface InitOptions {
250
301
  maxBreadcrumbs?: number;
251
302
  /** Registra handlers globais de erro (uncaughtException etc.). Default: true */
252
303
  captureUnhandled?: boolean;
304
+ /**
305
+ * Coleta CPU, memória, disco e recursos do processo: vai em cada heartbeat/poll (série da
306
+ * instância no app) e como `contexts.machine` em cada evento (como estava a máquina na hora
307
+ * do erro). Só em Node; sem custo de timer — pega carona no heartbeat. Default: true
308
+ */
309
+ machineMetrics?: boolean;
253
310
  /** Habilita heartbeat periódico (true usa defaults) */
254
311
  heartbeat?: boolean | HeartbeatOptions;
255
312
  /**
@@ -336,4 +393,4 @@ declare function close(timeoutMs?: number): Promise<boolean>;
336
393
 
337
394
  declare function scrubSecrets(text: string): string;
338
395
 
339
- export { type AttachInput, Breadcrumb, type BreadcrumbInput, type CaptureAttachment, type CaptureHint, Client, DEFAULT_BASE_URL, EventPayload, EventType, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, RunAttachmentContentType, type RunContext, type RunItemOptions, RunItemStatus, type RunItems, RunLogLevel, Scope, Step, StepData, type TaskHandler, type TasksOptions, Transaction, TransactionPayload, addBreadcrumb, captureException, captureMessage, close, flush, getClient, init, register, scrubSecrets, setContext, setExtra, setTag, setTags, setUser, start, startTransaction, stop, withScope };
396
+ export { type AttachInput, Breadcrumb, type BreadcrumbInput, type CaptureAttachment, type CaptureHint, Client, DEFAULT_BASE_URL, EventPayload, EventType, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, MachineSnapshot, RunAttachmentContentType, type RunContext, type RunItemOptions, RunItemStatus, type RunItems, RunLogLevel, RunProgress, type RunProgressReporter, Scope, Step, StepData, type TaskHandler, type TasksOptions, Transaction, TransactionPayload, addBreadcrumb, captureException, captureMessage, close, flush, getClient, init, register, scrubSecrets, setContext, setExtra, setTag, setTags, setUser, start, startTransaction, stop, withScope };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Breadcrumb, EventUser, EventType, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunAttachmentContentType } from './protocol.js';
2
- export { BreadcrumbLevel, Envelope, EnvelopeItem, ExceptionData, InstanceInfo, PollRequest, PollResponse, RunAttachmentConfirmRequest, RunAttachmentConfirmResponse, RunAttachmentCreateRequest, RunAttachmentCreateResponse, RunDescriptor, RunError, RunItemInput, RunItemsCreateRequest, RunItemsCreateResponse, RunLogEntry, RunStatus, RunUpdateRequest, RunUpdateResponse, RunUpdateStatus, StackFrame } from './protocol.js';
1
+ import { Breadcrumb, EventUser, EventType, MachineSnapshot, EventPayload, TransactionPayload, HeartbeatPayload, StepStatus, RunLogLevel, StepData, RunItemStatus, RunProgress, RunAttachmentContentType } from './protocol.js';
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';
3
3
 
4
4
  /** Aceita tudo que o handler pode ter em mãos: bytes ou um caminho de arquivo (só Node). */
5
5
  type AttachInput = Uint8Array | ArrayBuffer | string;
@@ -47,15 +47,46 @@ interface Logger {
47
47
  error: (...args: unknown[]) => void;
48
48
  }
49
49
 
50
+ /**
51
+ * Coleta CPU/memória/disco da máquina e do processo — só em Node (no browser é no-op).
52
+ *
53
+ * Os módulos `node:*` entram por import dinâmico (o bundle é `platform: neutral`), e
54
+ * `sample()` é síncrono e barato: `os.cpus()` + `statfsSync` + `process.memoryUsage()`.
55
+ * Nunca lança — telemetria de recurso não pode derrubar o bot nem o capture de um erro.
56
+ */
57
+ declare class MachineSampler {
58
+ private readonly instanceId;
59
+ private readonly logger;
60
+ private os;
61
+ private fs;
62
+ private ready;
63
+ private prevCpu;
64
+ private prevProcessCpu;
65
+ private prevAt;
66
+ private lastCpuPercent;
67
+ private lastProcessCpuPercent;
68
+ constructor(instanceId: string, logger: Logger);
69
+ /** Carrega os módulos e tira a leitura-base de CPU (a primeira amostra ainda sai com cpu_percent null). */
70
+ start(): Promise<void>;
71
+ sample(): MachineSnapshot | undefined;
72
+ private cpuTotals;
73
+ /** Média desde a leitura anterior; leituras com menos de 1s de janela reutilizam a última média. */
74
+ private updateCpu;
75
+ private diskUsage;
76
+ }
77
+
50
78
  declare class Client {
51
79
  #private;
52
80
  readonly logger: Logger;
53
81
  /** Eco de lifecycle (Transaction.emit) e afins só imprimem no terminal com debug ligado. */
54
82
  readonly debug: boolean;
55
83
  private readonly transport;
84
+ private machine;
56
85
  constructor(options: InitOptions, config?: ResolvedConfig);
57
86
  get options(): InitOptions;
58
87
  get config(): ResolvedConfig;
88
+ /** Sampler de recursos da máquina — cada evento passa a levar `contexts.machine`. */
89
+ attachMachineSampler(sampler: MachineSampler | undefined): void;
59
90
  /** Serialização explícita nunca inclui o secret. */
60
91
  toJSON(): Record<string, unknown>;
61
92
  captureException(error: unknown, hint: CaptureHint | undefined, scope: Scope): string;
@@ -198,6 +229,24 @@ interface RunItems {
198
229
  /** Ocorrência de negócio (ex.: "nota nº 10 não encontrada") — não é falha do bot. */
199
230
  occurrence(message: string, payload?: Record<string, unknown>, options?: RunItemOptions): void;
200
231
  }
232
+ /**
233
+ * Progresso da execução (itens processados / total) — opcional e independente de
234
+ * `ctx.items`. Declare o total antes do loop e avance a cada item: a plataforma e o
235
+ * Studio mostram barra, percentual e tempo restante estimado. Sem `total()` nada é
236
+ * enviado. Chamadas são síncronas e baratas (≤ 1 PATCH/s, pegando carona nos logs).
237
+ */
238
+ interface RunProgressReporter {
239
+ /** Declara (ou ajusta) o total de itens previsto — inteiro >= 1. Idempotente. */
240
+ total(total: number): void;
241
+ /** Incrementa os processados (padrão 1). Clampa em `total`. */
242
+ advance(count?: number): void;
243
+ /** Define o valor absoluto de processados e, opcionalmente, o total. */
244
+ set(current: number, total?: number): void;
245
+ /** Processados até agora (0 antes de qualquer chamada). */
246
+ readonly current: number;
247
+ /** `{ current, total }` quando há total declarado; null caso contrário. */
248
+ readonly snapshot: RunProgress | null;
249
+ }
201
250
  interface RunContext {
202
251
  runId: string;
203
252
  task: string;
@@ -205,6 +254,8 @@ interface RunContext {
205
254
  log: RunLogger;
206
255
  /** Itens processados/gerados pela execução — a entrega do bot, com status e atributos */
207
256
  items: RunItems;
257
+ /** Progresso declarado (barra + ETA no app) — opcional, independente de `ctx.items` */
258
+ progress: RunProgressReporter;
208
259
  /**
209
260
  * Transaction de performance desta execução — já correlacionada à run e finalizada
210
261
  * automaticamente ao fim do handler. Use `ctx.tx.startChild(op, description)` pra medir
@@ -250,6 +301,12 @@ interface InitOptions {
250
301
  maxBreadcrumbs?: number;
251
302
  /** Registra handlers globais de erro (uncaughtException etc.). Default: true */
252
303
  captureUnhandled?: boolean;
304
+ /**
305
+ * Coleta CPU, memória, disco e recursos do processo: vai em cada heartbeat/poll (série da
306
+ * instância no app) e como `contexts.machine` em cada evento (como estava a máquina na hora
307
+ * do erro). Só em Node; sem custo de timer — pega carona no heartbeat. Default: true
308
+ */
309
+ machineMetrics?: boolean;
253
310
  /** Habilita heartbeat periódico (true usa defaults) */
254
311
  heartbeat?: boolean | HeartbeatOptions;
255
312
  /**
@@ -336,4 +393,4 @@ declare function close(timeoutMs?: number): Promise<boolean>;
336
393
 
337
394
  declare function scrubSecrets(text: string): string;
338
395
 
339
- export { type AttachInput, Breadcrumb, type BreadcrumbInput, type CaptureAttachment, type CaptureHint, Client, DEFAULT_BASE_URL, EventPayload, EventType, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, RunAttachmentContentType, type RunContext, type RunItemOptions, RunItemStatus, type RunItems, RunLogLevel, Scope, Step, StepData, type TaskHandler, type TasksOptions, Transaction, TransactionPayload, addBreadcrumb, captureException, captureMessage, close, flush, getClient, init, register, scrubSecrets, setContext, setExtra, setTag, setTags, setUser, start, startTransaction, stop, withScope };
396
+ export { type AttachInput, Breadcrumb, type BreadcrumbInput, type CaptureAttachment, type CaptureHint, Client, DEFAULT_BASE_URL, EventPayload, EventType, EventUser, type HeartbeatOptions, HeartbeatPayload, type InitOptions, MachineSnapshot, RunAttachmentContentType, type RunContext, type RunItemOptions, RunItemStatus, type RunItems, RunLogLevel, RunProgress, type RunProgressReporter, Scope, Step, StepData, type TaskHandler, type TasksOptions, Transaction, TransactionPayload, addBreadcrumb, captureException, captureMessage, close, flush, getClient, init, register, scrubSecrets, setContext, setExtra, setTag, setTags, setUser, start, startTransaction, stop, withScope };