hobots 3.4.0 → 4.1.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/protocol.cjs CHANGED
@@ -35,7 +35,6 @@ var protocol_limits_default = {
35
35
  MAX_LOGS_PER_PATCH: 100,
36
36
  MAX_ERROR_MESSAGE_CHARS: 1e4,
37
37
  MAX_ERROR_STACK_CHARS: 2e4,
38
- MAX_ITEMS_PER_RUN: 1e4,
39
38
  MAX_ITEMS_PER_REQUEST: 500,
40
39
  MAX_ITEM_MESSAGE_CHARS: 2e3,
41
40
  MAX_ITEM_PAYLOAD_BYTES: 16384,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocol.ts","../protocol-limits.json","../src/wire-limits.ts"],"sourcesContent":["/**\n * Tipos do protocolo do Hobots (SDK → servidor).\n *\n * Este arquivo é a fonte de verdade do wire format: reexporta tipos (o app valida\n * os payloads com zod e trava o drift via `satisfies z.ZodType<...>` contra eles)\n * e os LIMITES numéricos do wire (WIRE_LIMITS, de protocol-limits.json) — o único\n * valor de runtime daqui, para a api aplicar exatamente os caps que o SDK aplica.\n */\n\nexport { WIRE_LIMITS, type WireLimits } from './wire-limits';\n\nimport type { EnvironmentInput } from './environment-protocol';\nimport type { MachineSnapshot } from './machine-protocol';\n\n// Wire format de tasks (agente ↔ servidor) — reexportado aqui para o app\n// consumir tudo de `hobots/protocol`.\nexport type {\n RunStatus,\n RunUpdateStatus,\n RunLogLevel,\n RunLogEntry,\n InstanceInfo,\n PollRequest,\n RunDescriptor,\n PollResponse,\n RunCreateRequest,\n RunCreateResponse,\n RunError,\n RunProgress,\n RunUpdateRequest,\n RunUpdateResponse,\n RunItemStatus,\n RunItemInput,\n RunItemsCreateRequest,\n RunItemsCreateResponse,\n ItemColumn,\n TaskItemsDeclaration,\n RunAttachmentContentType,\n RunAttachmentCreateRequest,\n RunAttachmentCreateResponse,\n RunAttachmentConfirmRequest,\n RunAttachmentConfirmResponse,\n} from './tasks/protocol';\n\n// Snapshot de recursos da máquina — usado no heartbeat, no poll e em contexts.machine.\nexport type { MachineProcess, MachineSnapshot } from './machine-protocol';\nexport type { Environment, EnvironmentInput } from './environment-protocol';\n\n/**\n * Tipo de um evento — o que ele é, não o quanto ele fala. Só 'fatal', 'error' e\n * 'warning' viram issue; 'success' é ingerido e nunca abre issue.\n * Ruído de log não é evento: para isso existem os logs da execução (RunLogLevel)\n * e as breadcrumbs, que têm níveis próprios com 'debug'/'info'.\n */\nexport type EventType = 'fatal' | 'error' | 'warning' | 'success';\n\n/** Nível de uma breadcrumb — trilha do que aconteceu antes, aqui log é bem-vindo. */\nexport type BreadcrumbLevel = 'debug' | 'info' | 'warning' | 'error' | 'fatal';\n\n/** Frames em ordem innermost-first (mesma ordem impressa pelo V8). */\nexport interface StackFrame {\n function?: string;\n filename?: string;\n lineno?: number;\n colno?: number;\n in_app: boolean;\n}\n\nexport interface Breadcrumb {\n /** ISO 8601 */\n timestamp: string;\n type?: string;\n category?: string;\n message?: string;\n level?: BreadcrumbLevel;\n data?: Record<string, unknown>;\n}\n\nexport interface ExceptionData {\n type: string;\n value: string;\n stacktrace?: { frames: StackFrame[] };\n}\n\nexport interface EventUser {\n id?: string;\n username?: string;\n email?: string;\n}\n\nexport interface EventPayload {\n /** uuid v4 sem hífens (32 hex), gerado pelo SDK */\n event_id: string;\n /** ISO 8601 */\n timestamp: string;\n type: EventType;\n message?: string;\n exception?: ExceptionData;\n /** Override de agrupamento; quando ausente o servidor calcula pelo stack trace */\n fingerprint?: string[];\n breadcrumbs?: Breadcrumb[];\n tags?: Record<string, string>;\n user?: EventUser;\n contexts?: Record<string, Record<string, unknown>>;\n extra?: Record<string, unknown>;\n release?: string;\n environment?: EnvironmentInput;\n}\n\n/** Status de uma step (etapa). `warning` = terminou, mas merece atenção (não é falha). */\nexport type StepStatus = 'ok' | 'warning' | 'error' | 'cancelled';\n\nexport interface StepData {\n /** 16 hex */\n step_id: string;\n parent_step_id?: string;\n op?: string;\n description?: string;\n status?: StepStatus;\n /** ISO 8601 */\n start_timestamp: string;\n /** ISO 8601 (fim da step) */\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\nexport interface TransactionPayload {\n event_id: string;\n name: string;\n op?: string;\n status: string;\n start_timestamp: string;\n timestamp: string;\n steps: StepData[];\n tags?: Record<string, string>;\n release?: string;\n environment?: EnvironmentInput;\n /** Correlaciona esta transaction a uma execução de task (ctx.tx dentro de um task handler) */\n run_id?: string;\n}\n\nexport interface HeartbeatPayload {\n instance_id: string;\n name?: string;\n interval_ms: number;\n /** ISO 8601 */\n timestamp: string;\n metadata?: Record<string, unknown>;\n release?: string;\n /** Ambiente da instância — é ele que o app exibe e que as regras de alerta filtram */\n environment?: EnvironmentInput;\n /** Recursos da máquina no momento do beat (CPU, memória, disco, processo) */\n machine?: MachineSnapshot;\n}\n\nexport type EnvelopeItem =\n | { type: 'event'; payload: EventPayload }\n | { type: 'transaction'; payload: TransactionPayload }\n | { type: 'heartbeat'; payload: HeartbeatPayload };\n\nexport interface Envelope {\n sdk: { name: string; version: string };\n /** ISO 8601 */\n sent_at: string;\n items: EnvelopeItem[];\n}\n","{\n \"MAX_ITEMS_PER_ENVELOPE\": 50,\n \"HEARTBEAT_DEFAULT_INTERVAL_MS\": 30000,\n \"HEARTBEAT_MIN_INTERVAL_MS\": 1000,\n \"HEARTBEAT_MAX_INTERVAL_MS\": 900000,\n \"MAX_CLAIM_PER_POLL\": 5,\n \"MAX_LOG_MESSAGE_CHARS\": 10000,\n \"MAX_LOGS_PER_PATCH\": 100,\n \"MAX_ERROR_MESSAGE_CHARS\": 10000,\n \"MAX_ERROR_STACK_CHARS\": 20000,\n \"MAX_ITEMS_PER_RUN\": 10000,\n \"MAX_ITEMS_PER_REQUEST\": 500,\n \"MAX_ITEM_MESSAGE_CHARS\": 2000,\n \"MAX_ITEM_PAYLOAD_BYTES\": 16384,\n \"MAX_ITEM_COLUMNS\": 12,\n \"MAX_ITEM_COLUMN_LABEL_CHARS\": 60,\n \"MAX_ATTACHMENT_BYTES\": 5242880,\n \"MAX_ATTACHMENTS_PER_RUN\": 20,\n \"MAX_ATTACHMENTS_PER_LOG_ENTRY\": 4,\n \"MAX_CAPTION_CHARS\": 200,\n \"MAX_IMAGE_DIMENSION_PX\": 20000\n}\n","import limits from '../protocol-limits.json';\n\n/**\n * Limites do wire SDK ↔ servidor — fonte ÚNICA (protocol-limits.json): o SDK\n * Node lê daqui, a @hobots/api importa de `hobots/protocol` e o SDK Python\n * confere a paridade num teste que lê o mesmo JSON. Mudar um limite = mudar o\n * JSON (e, no Python, a constante espelhada — o teste acusa).\n */\nexport const WIRE_LIMITS = limits as Readonly<typeof limits>;\nexport type WireLimits = typeof WIRE_LIMITS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,wBAA0B;AAAA,EAC1B,+BAAiC;AAAA,EACjC,2BAA6B;AAAA,EAC7B,2BAA6B;AAAA,EAC7B,oBAAsB;AAAA,EACtB,uBAAyB;AAAA,EACzB,oBAAsB;AAAA,EACtB,yBAA2B;AAAA,EAC3B,uBAAyB;AAAA,EACzB,mBAAqB;AAAA,EACrB,uBAAyB;AAAA,EACzB,wBAA0B;AAAA,EAC1B,wBAA0B;AAAA,EAC1B,kBAAoB;AAAA,EACpB,6BAA+B;AAAA,EAC/B,sBAAwB;AAAA,EACxB,yBAA2B;AAAA,EAC3B,+BAAiC;AAAA,EACjC,mBAAqB;AAAA,EACrB,wBAA0B;AAC5B;;;ACbO,IAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/protocol.ts","../protocol-limits.json","../src/wire-limits.ts"],"sourcesContent":["/**\n * Tipos do protocolo do Hobots (SDK → servidor).\n *\n * Este arquivo é a fonte de verdade do wire format: reexporta tipos (o app valida\n * os payloads com zod e trava o drift via `satisfies z.ZodType<...>` contra eles)\n * e os LIMITES numéricos do wire (WIRE_LIMITS, de protocol-limits.json) — o único\n * valor de runtime daqui, para a api aplicar exatamente os caps que o SDK aplica.\n */\n\nexport { WIRE_LIMITS, type WireLimits } from './wire-limits';\n\nimport type { EnvironmentInput } from './environment-protocol';\nimport type { MachineSnapshot } from './machine-protocol';\n\n// Wire format de execuções (agente ↔ servidor) — reexportado aqui para o app\n// consumir tudo de `hobots/protocol`.\nexport type {\n RunStatus,\n RunUpdateStatus,\n RunLogLevel,\n RunLogEntry,\n InstanceInfo,\n PollRequest,\n RunDescriptor,\n PollResponse,\n RunCreateRequest,\n RunCreateResponse,\n RunError,\n RunProgress,\n RunUpdateRequest,\n RunUpdateResponse,\n RunItemStatus,\n RunItemInput,\n RunItemsCreateRequest,\n RunItemsCreateResponse,\n ItemColumn,\n ItemsDeclaration,\n InstanceMode,\n RunAttachmentContentType,\n RunAttachmentCreateRequest,\n RunAttachmentCreateResponse,\n RunAttachmentConfirmRequest,\n RunAttachmentConfirmResponse,\n} from './tasks/protocol';\n\n// Snapshot de recursos da máquina — usado no heartbeat, no poll e em contexts.machine.\nexport type { MachineProcess, MachineSnapshot } from './machine-protocol';\nexport type { Environment, EnvironmentInput } from './environment-protocol';\n\n/**\n * Tipo de um evento — o que ele é, não o quanto ele fala. Só 'fatal', 'error' e\n * 'warning' viram issue; 'success' é ingerido e nunca abre issue.\n * Ruído de log não é evento: para isso existem os logs da execução (RunLogLevel)\n * e as breadcrumbs, que têm níveis próprios com 'debug'/'info'.\n */\nexport type EventType = 'fatal' | 'error' | 'warning' | 'success';\n\n/** Nível de uma breadcrumb — trilha do que aconteceu antes, aqui log é bem-vindo. */\nexport type BreadcrumbLevel = 'debug' | 'info' | 'warning' | 'error' | 'fatal';\n\n/** Frames em ordem innermost-first (mesma ordem impressa pelo V8). */\nexport interface StackFrame {\n function?: string;\n filename?: string;\n lineno?: number;\n colno?: number;\n in_app: boolean;\n}\n\nexport interface Breadcrumb {\n /** ISO 8601 */\n timestamp: string;\n type?: string;\n category?: string;\n message?: string;\n level?: BreadcrumbLevel;\n data?: Record<string, unknown>;\n}\n\nexport interface ExceptionData {\n type: string;\n value: string;\n stacktrace?: { frames: StackFrame[] };\n}\n\nexport interface EventUser {\n id?: string;\n username?: string;\n email?: string;\n}\n\nexport interface EventPayload {\n /** uuid v4 sem hífens (32 hex), gerado pelo SDK */\n event_id: string;\n /** ISO 8601 */\n timestamp: string;\n type: EventType;\n message?: string;\n exception?: ExceptionData;\n /** Override de agrupamento; quando ausente o servidor calcula pelo stack trace */\n fingerprint?: string[];\n breadcrumbs?: Breadcrumb[];\n tags?: Record<string, string>;\n user?: EventUser;\n contexts?: Record<string, Record<string, unknown>>;\n extra?: Record<string, unknown>;\n release?: string;\n environment?: EnvironmentInput;\n}\n\n/** Status de uma step (etapa). `warning` = terminou, mas merece atenção (não é falha). */\nexport type StepStatus = 'ok' | 'warning' | 'error' | 'cancelled';\n\nexport interface StepData {\n /** 16 hex */\n step_id: string;\n parent_step_id?: string;\n op?: string;\n description?: string;\n status?: StepStatus;\n /** ISO 8601 */\n start_timestamp: string;\n /** ISO 8601 (fim da step) */\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\nexport interface TransactionPayload {\n event_id: string;\n name: string;\n op?: string;\n status: string;\n start_timestamp: string;\n timestamp: string;\n steps: StepData[];\n tags?: Record<string, string>;\n release?: string;\n environment?: EnvironmentInput;\n /** Correlaciona esta transaction a uma execução do agente (hobots.transaction dentro do handler) */\n run_id?: string;\n}\n\nexport interface HeartbeatPayload {\n instance_id: string;\n name?: string;\n interval_ms: number;\n /** ISO 8601 */\n timestamp: string;\n metadata?: Record<string, unknown>;\n release?: string;\n /** Ambiente da instância — é ele que o app exibe e que as regras de alerta filtram */\n environment?: EnvironmentInput;\n /** Recursos da máquina no momento do beat (CPU, memória, disco, processo) */\n machine?: MachineSnapshot;\n}\n\nexport type EnvelopeItem =\n | { type: 'event'; payload: EventPayload }\n | { type: 'transaction'; payload: TransactionPayload }\n | { type: 'heartbeat'; payload: HeartbeatPayload };\n\nexport interface Envelope {\n sdk: { name: string; version: string };\n /** ISO 8601 */\n sent_at: string;\n items: EnvelopeItem[];\n}\n","{\n \"MAX_ITEMS_PER_ENVELOPE\": 50,\n \"HEARTBEAT_DEFAULT_INTERVAL_MS\": 30000,\n \"HEARTBEAT_MIN_INTERVAL_MS\": 1000,\n \"HEARTBEAT_MAX_INTERVAL_MS\": 900000,\n \"MAX_CLAIM_PER_POLL\": 5,\n \"MAX_LOG_MESSAGE_CHARS\": 10000,\n \"MAX_LOGS_PER_PATCH\": 100,\n \"MAX_ERROR_MESSAGE_CHARS\": 10000,\n \"MAX_ERROR_STACK_CHARS\": 20000,\n \"MAX_ITEMS_PER_REQUEST\": 500,\n \"MAX_ITEM_MESSAGE_CHARS\": 2000,\n \"MAX_ITEM_PAYLOAD_BYTES\": 16384,\n \"MAX_ITEM_COLUMNS\": 12,\n \"MAX_ITEM_COLUMN_LABEL_CHARS\": 60,\n \"MAX_ATTACHMENT_BYTES\": 5242880,\n \"MAX_ATTACHMENTS_PER_RUN\": 20,\n \"MAX_ATTACHMENTS_PER_LOG_ENTRY\": 4,\n \"MAX_CAPTION_CHARS\": 200,\n \"MAX_IMAGE_DIMENSION_PX\": 20000\n}\n","import limits from '../protocol-limits.json';\n\n/**\n * Limites do wire SDK ↔ servidor — fonte ÚNICA (protocol-limits.json): o SDK\n * Node lê daqui, a @hobots/api importa de `hobots/protocol` e o SDK Python\n * confere a paridade num teste que lê o mesmo JSON. Mudar um limite = mudar o\n * JSON (e, no Python, a constante espelhada — o teste acusa).\n */\nexport const WIRE_LIMITS = limits as Readonly<typeof limits>;\nexport type WireLimits = typeof WIRE_LIMITS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,wBAA0B;AAAA,EAC1B,+BAAiC;AAAA,EACjC,2BAA6B;AAAA,EAC7B,2BAA6B;AAAA,EAC7B,oBAAsB;AAAA,EACtB,uBAAyB;AAAA,EACzB,oBAAsB;AAAA,EACtB,yBAA2B;AAAA,EAC3B,uBAAyB;AAAA,EACzB,uBAAyB;AAAA,EACzB,wBAA0B;AAAA,EAC1B,wBAA0B;AAAA,EAC1B,kBAAoB;AAAA,EACpB,6BAA+B;AAAA,EAC/B,sBAAwB;AAAA,EACxB,yBAA2B;AAAA,EAC3B,+BAAiC;AAAA,EACjC,mBAAqB;AAAA,EACrB,wBAA0B;AAC5B;;;ACZO,IAAM,cAAc;","names":[]}
@@ -72,7 +72,10 @@ interface MachineSnapshot {
72
72
  }
73
73
 
74
74
  /**
75
- * Tipos do protocolo de tasks do Hobots (agente SDK ↔ servidor).
75
+ * Tipos do protocolo de execuções do Hobots (agente SDK ↔ servidor).
76
+ *
77
+ * O agente é a própria tarefa: não há slug de task no wire. O que o agente faz é
78
+ * identificado pelo client secret; a instância só declara COMO trabalha (`mode`).
76
79
  *
77
80
  * Este arquivo é a fonte de verdade do wire format e não pode importar nada:
78
81
  * o app valida os payloads com zod e trava o drift via `satisfies z.ZodType<...>`
@@ -91,7 +94,7 @@ interface RunLogEntry {
91
94
  message: string;
92
95
  /**
93
96
  * Ids dos anexos (imagens) desta linha — gerados pelo agente (32 hex) e criados via
94
- * `POST /v1/tasks/runs/{id}/attachments`. O upload roda em segundo plano: a linha pode
97
+ * `POST /v1/runs/{id}/attachments`. O upload roda em segundo plano: a linha pode
95
98
  * chegar ao servidor antes do binário estar no S3.
96
99
  */
97
100
  attachments?: string[];
@@ -102,8 +105,10 @@ interface ItemColumn {
102
105
  /** ausente = a plataforma exibe a própria key */
103
106
  label?: string;
104
107
  }
105
- /** Colunas de itens declaradas no código para uma task (`items.columns` do register/start). */
106
- interface TaskItemsDeclaration {
108
+ /** Como a instância trabalha: 'on_demand' = register (poll de solicitações); 'always_on' = start (abre a própria run). */
109
+ type InstanceMode = 'on_demand' | 'always_on';
110
+ /** Colunas de itens declaradas no código (`items.columns` do register/start). */
111
+ interface ItemsDeclaration {
107
112
  attributes: ItemColumn[];
108
113
  }
109
114
  interface InstanceInfo {
@@ -116,10 +121,10 @@ interface InstanceInfo {
116
121
  host?: string;
117
122
  /** Ambiente da instância — mesmo valor do heartbeat; agentes poll-only só o informam aqui */
118
123
  environment?: EnvironmentInput;
119
- /** Tasks registradas no agente */
120
- tasks?: string[];
121
- /** Colunas de itens declaradas no código, por task — só as tasks que declararam `items` */
122
- task_items?: Record<string, TaskItemsDeclaration>;
124
+ /** Modo de trabalho desta instância (register = on_demand, start = always_on) */
125
+ mode?: InstanceMode;
126
+ /** Colunas de itens declaradas no código — só quando o register/start declarou `items` */
127
+ items?: ItemsDeclaration;
123
128
  /**
124
129
  * Intervalo de poll em ms — alimenta a tolerância de offline do servidor (3×) em
125
130
  * agentes poll-only, que sem isso herdariam a tolerância do heartbeat (30s × 3).
@@ -128,17 +133,14 @@ interface InstanceInfo {
128
133
  /** Recursos da máquina no momento do poll — alimenta a série da instância em agentes sem heartbeat */
129
134
  machine?: MachineSnapshot;
130
135
  }
131
- /** POST /v1/tasks/poll */
136
+ /** POST /v1/runs/poll */
132
137
  interface PollRequest {
133
138
  instance?: InstanceInfo;
134
139
  /** Quantas runs reivindicar de uma vez (1..5). Default: 1 */
135
140
  max?: number;
136
- /** Só entrega runs destas tasks (nomes registrados no agente) */
137
- tasks?: string[];
138
141
  }
139
142
  interface RunDescriptor {
140
143
  id: string;
141
- task: string;
142
144
  params: Record<string, unknown>;
143
145
  form: {
144
146
  id: string;
@@ -153,13 +155,11 @@ interface PollResponse {
153
155
  runs: RunDescriptor[];
154
156
  }
155
157
  /**
156
- * POST /v1/tasks/runs — modo start do SDK: a própria instância abre a run, que já
158
+ * POST /v1/runs — modo start do SDK: a própria instância abre a run, que já
157
159
  * nasce 'running' (started_at = now), sem formulário nem solicitante. Dali em diante
158
160
  * ela é reportada pelas mesmas rotas de uma run reivindicada no poll.
159
161
  */
160
162
  interface RunCreateRequest {
161
- /** slug da task (1..255) — vira task_runs.task_slug */
162
- task: string;
163
163
  /** presença da instância — obrigatória: a run nasce vinculada à instância */
164
164
  instance: InstanceInfo;
165
165
  }
@@ -181,7 +181,7 @@ interface RunProgress {
181
181
  /** total de itens previsto (>= 1) */
182
182
  total: number;
183
183
  }
184
- /** PATCH /v1/tasks/runs/{id} — 'running' pode repetir com logs incrementais */
184
+ /** PATCH /v1/runs/{id} — 'running' pode repetir com logs incrementais */
185
185
  interface RunUpdateRequest {
186
186
  status: RunUpdateStatus;
187
187
  /** Apenas com status 'failed' */
@@ -219,7 +219,7 @@ interface RunItemInput {
219
219
  /** Ids de anexo (print do item) — opcional; mesmo teto por entrada das linhas de log */
220
220
  attachments?: string[];
221
221
  }
222
- /** POST /v1/tasks/runs/{id}/items — aceito mesmo com a run cancelada/terminal */
222
+ /** POST /v1/runs/{id}/items — aceito mesmo com a run cancelada/terminal */
223
223
  interface RunItemsCreateRequest {
224
224
  items: RunItemInput[];
225
225
  }
@@ -231,7 +231,7 @@ interface RunItemsCreateResponse {
231
231
  }
232
232
  /** Formatos aceitos para anexo. O S3 valida o content-type contra a assinatura. */
233
233
  type RunAttachmentContentType = 'image/png' | 'image/jpeg' | 'image/webp';
234
- /** POST /v1/tasks/runs/{id}/attachments */
234
+ /** POST /v1/runs/{id}/attachments */
235
235
  interface RunAttachmentCreateRequest {
236
236
  /** Id do anexo gerado pelo agente (32 hex) — já referenciado no log/item/step que o carrega */
237
237
  id: string;
@@ -253,7 +253,7 @@ interface RunAttachmentCreateResponse {
253
253
  /** Validade da URL, em segundos */
254
254
  expires_in: number;
255
255
  }
256
- /** PATCH /v1/tasks/runs/{id}/attachments/{attachmentId} */
256
+ /** PATCH /v1/runs/{id}/attachments/{attachmentId} */
257
257
  interface RunAttachmentConfirmRequest {
258
258
  status: 'uploaded' | 'failed';
259
259
  size_bytes?: number;
@@ -273,7 +273,6 @@ var MAX_LOG_MESSAGE_CHARS = 10000;
273
273
  var MAX_LOGS_PER_PATCH = 100;
274
274
  var MAX_ERROR_MESSAGE_CHARS = 10000;
275
275
  var MAX_ERROR_STACK_CHARS = 20000;
276
- var MAX_ITEMS_PER_RUN = 10000;
277
276
  var MAX_ITEMS_PER_REQUEST = 500;
278
277
  var MAX_ITEM_MESSAGE_CHARS = 2000;
279
278
  var MAX_ITEM_PAYLOAD_BYTES = 16384;
@@ -294,7 +293,6 @@ var limits = {
294
293
  MAX_LOGS_PER_PATCH: MAX_LOGS_PER_PATCH,
295
294
  MAX_ERROR_MESSAGE_CHARS: MAX_ERROR_MESSAGE_CHARS,
296
295
  MAX_ERROR_STACK_CHARS: MAX_ERROR_STACK_CHARS,
297
- MAX_ITEMS_PER_RUN: MAX_ITEMS_PER_RUN,
298
296
  MAX_ITEMS_PER_REQUEST: MAX_ITEMS_PER_REQUEST,
299
297
  MAX_ITEM_MESSAGE_CHARS: MAX_ITEM_MESSAGE_CHARS,
300
298
  MAX_ITEM_PAYLOAD_BYTES: MAX_ITEM_PAYLOAD_BYTES,
@@ -407,7 +405,7 @@ interface TransactionPayload {
407
405
  tags?: Record<string, string>;
408
406
  release?: string;
409
407
  environment?: EnvironmentInput;
410
- /** Correlaciona esta transaction a uma execução de task (ctx.tx dentro de um task handler) */
408
+ /** Correlaciona esta transaction a uma execução do agente (hobots.transaction dentro do handler) */
411
409
  run_id?: string;
412
410
  }
413
411
  interface HeartbeatPayload {
@@ -443,4 +441,4 @@ interface Envelope {
443
441
  items: EnvelopeItem[];
444
442
  }
445
443
 
446
- export { type Breadcrumb, type BreadcrumbLevel, type Envelope, type EnvelopeItem, type Environment, type EnvironmentInput, type EventPayload, type EventType, type EventUser, type ExceptionData, type HeartbeatPayload, type InstanceInfo, type ItemColumn, type MachineProcess, type MachineSnapshot, type PollRequest, type PollResponse, type RunAttachmentConfirmRequest, type RunAttachmentConfirmResponse, type RunAttachmentContentType, type RunAttachmentCreateRequest, type RunAttachmentCreateResponse, type RunCreateRequest, type RunCreateResponse, type RunDescriptor, type RunError, type RunItemInput, type RunItemStatus, type RunItemsCreateRequest, type RunItemsCreateResponse, type RunLogEntry, type RunLogLevel, type RunProgress, type RunStatus, type RunUpdateRequest, type RunUpdateResponse, type RunUpdateStatus, type StackFrame, type StepData, type StepStatus, type TaskItemsDeclaration, type TransactionPayload, WIRE_LIMITS, type WireLimits };
444
+ export { type Breadcrumb, type BreadcrumbLevel, type Envelope, type EnvelopeItem, type Environment, type EnvironmentInput, type EventPayload, type EventType, type EventUser, type ExceptionData, type HeartbeatPayload, type InstanceInfo, type InstanceMode, type ItemColumn, type ItemsDeclaration, type MachineProcess, type MachineSnapshot, type PollRequest, type PollResponse, type RunAttachmentConfirmRequest, type RunAttachmentConfirmResponse, type RunAttachmentContentType, type RunAttachmentCreateRequest, type RunAttachmentCreateResponse, type RunCreateRequest, type RunCreateResponse, type RunDescriptor, type RunError, type RunItemInput, type RunItemStatus, type RunItemsCreateRequest, type RunItemsCreateResponse, type RunLogEntry, type RunLogLevel, type RunProgress, type RunStatus, type RunUpdateRequest, type RunUpdateResponse, type RunUpdateStatus, type StackFrame, type StepData, type StepStatus, type TransactionPayload, WIRE_LIMITS, type WireLimits };
@@ -72,7 +72,10 @@ interface MachineSnapshot {
72
72
  }
73
73
 
74
74
  /**
75
- * Tipos do protocolo de tasks do Hobots (agente SDK ↔ servidor).
75
+ * Tipos do protocolo de execuções do Hobots (agente SDK ↔ servidor).
76
+ *
77
+ * O agente é a própria tarefa: não há slug de task no wire. O que o agente faz é
78
+ * identificado pelo client secret; a instância só declara COMO trabalha (`mode`).
76
79
  *
77
80
  * Este arquivo é a fonte de verdade do wire format e não pode importar nada:
78
81
  * o app valida os payloads com zod e trava o drift via `satisfies z.ZodType<...>`
@@ -91,7 +94,7 @@ interface RunLogEntry {
91
94
  message: string;
92
95
  /**
93
96
  * Ids dos anexos (imagens) desta linha — gerados pelo agente (32 hex) e criados via
94
- * `POST /v1/tasks/runs/{id}/attachments`. O upload roda em segundo plano: a linha pode
97
+ * `POST /v1/runs/{id}/attachments`. O upload roda em segundo plano: a linha pode
95
98
  * chegar ao servidor antes do binário estar no S3.
96
99
  */
97
100
  attachments?: string[];
@@ -102,8 +105,10 @@ interface ItemColumn {
102
105
  /** ausente = a plataforma exibe a própria key */
103
106
  label?: string;
104
107
  }
105
- /** Colunas de itens declaradas no código para uma task (`items.columns` do register/start). */
106
- interface TaskItemsDeclaration {
108
+ /** Como a instância trabalha: 'on_demand' = register (poll de solicitações); 'always_on' = start (abre a própria run). */
109
+ type InstanceMode = 'on_demand' | 'always_on';
110
+ /** Colunas de itens declaradas no código (`items.columns` do register/start). */
111
+ interface ItemsDeclaration {
107
112
  attributes: ItemColumn[];
108
113
  }
109
114
  interface InstanceInfo {
@@ -116,10 +121,10 @@ interface InstanceInfo {
116
121
  host?: string;
117
122
  /** Ambiente da instância — mesmo valor do heartbeat; agentes poll-only só o informam aqui */
118
123
  environment?: EnvironmentInput;
119
- /** Tasks registradas no agente */
120
- tasks?: string[];
121
- /** Colunas de itens declaradas no código, por task — só as tasks que declararam `items` */
122
- task_items?: Record<string, TaskItemsDeclaration>;
124
+ /** Modo de trabalho desta instância (register = on_demand, start = always_on) */
125
+ mode?: InstanceMode;
126
+ /** Colunas de itens declaradas no código — só quando o register/start declarou `items` */
127
+ items?: ItemsDeclaration;
123
128
  /**
124
129
  * Intervalo de poll em ms — alimenta a tolerância de offline do servidor (3×) em
125
130
  * agentes poll-only, que sem isso herdariam a tolerância do heartbeat (30s × 3).
@@ -128,17 +133,14 @@ interface InstanceInfo {
128
133
  /** Recursos da máquina no momento do poll — alimenta a série da instância em agentes sem heartbeat */
129
134
  machine?: MachineSnapshot;
130
135
  }
131
- /** POST /v1/tasks/poll */
136
+ /** POST /v1/runs/poll */
132
137
  interface PollRequest {
133
138
  instance?: InstanceInfo;
134
139
  /** Quantas runs reivindicar de uma vez (1..5). Default: 1 */
135
140
  max?: number;
136
- /** Só entrega runs destas tasks (nomes registrados no agente) */
137
- tasks?: string[];
138
141
  }
139
142
  interface RunDescriptor {
140
143
  id: string;
141
- task: string;
142
144
  params: Record<string, unknown>;
143
145
  form: {
144
146
  id: string;
@@ -153,13 +155,11 @@ interface PollResponse {
153
155
  runs: RunDescriptor[];
154
156
  }
155
157
  /**
156
- * POST /v1/tasks/runs — modo start do SDK: a própria instância abre a run, que já
158
+ * POST /v1/runs — modo start do SDK: a própria instância abre a run, que já
157
159
  * nasce 'running' (started_at = now), sem formulário nem solicitante. Dali em diante
158
160
  * ela é reportada pelas mesmas rotas de uma run reivindicada no poll.
159
161
  */
160
162
  interface RunCreateRequest {
161
- /** slug da task (1..255) — vira task_runs.task_slug */
162
- task: string;
163
163
  /** presença da instância — obrigatória: a run nasce vinculada à instância */
164
164
  instance: InstanceInfo;
165
165
  }
@@ -181,7 +181,7 @@ interface RunProgress {
181
181
  /** total de itens previsto (>= 1) */
182
182
  total: number;
183
183
  }
184
- /** PATCH /v1/tasks/runs/{id} — 'running' pode repetir com logs incrementais */
184
+ /** PATCH /v1/runs/{id} — 'running' pode repetir com logs incrementais */
185
185
  interface RunUpdateRequest {
186
186
  status: RunUpdateStatus;
187
187
  /** Apenas com status 'failed' */
@@ -219,7 +219,7 @@ interface RunItemInput {
219
219
  /** Ids de anexo (print do item) — opcional; mesmo teto por entrada das linhas de log */
220
220
  attachments?: string[];
221
221
  }
222
- /** POST /v1/tasks/runs/{id}/items — aceito mesmo com a run cancelada/terminal */
222
+ /** POST /v1/runs/{id}/items — aceito mesmo com a run cancelada/terminal */
223
223
  interface RunItemsCreateRequest {
224
224
  items: RunItemInput[];
225
225
  }
@@ -231,7 +231,7 @@ interface RunItemsCreateResponse {
231
231
  }
232
232
  /** Formatos aceitos para anexo. O S3 valida o content-type contra a assinatura. */
233
233
  type RunAttachmentContentType = 'image/png' | 'image/jpeg' | 'image/webp';
234
- /** POST /v1/tasks/runs/{id}/attachments */
234
+ /** POST /v1/runs/{id}/attachments */
235
235
  interface RunAttachmentCreateRequest {
236
236
  /** Id do anexo gerado pelo agente (32 hex) — já referenciado no log/item/step que o carrega */
237
237
  id: string;
@@ -253,7 +253,7 @@ interface RunAttachmentCreateResponse {
253
253
  /** Validade da URL, em segundos */
254
254
  expires_in: number;
255
255
  }
256
- /** PATCH /v1/tasks/runs/{id}/attachments/{attachmentId} */
256
+ /** PATCH /v1/runs/{id}/attachments/{attachmentId} */
257
257
  interface RunAttachmentConfirmRequest {
258
258
  status: 'uploaded' | 'failed';
259
259
  size_bytes?: number;
@@ -273,7 +273,6 @@ var MAX_LOG_MESSAGE_CHARS = 10000;
273
273
  var MAX_LOGS_PER_PATCH = 100;
274
274
  var MAX_ERROR_MESSAGE_CHARS = 10000;
275
275
  var MAX_ERROR_STACK_CHARS = 20000;
276
- var MAX_ITEMS_PER_RUN = 10000;
277
276
  var MAX_ITEMS_PER_REQUEST = 500;
278
277
  var MAX_ITEM_MESSAGE_CHARS = 2000;
279
278
  var MAX_ITEM_PAYLOAD_BYTES = 16384;
@@ -294,7 +293,6 @@ var limits = {
294
293
  MAX_LOGS_PER_PATCH: MAX_LOGS_PER_PATCH,
295
294
  MAX_ERROR_MESSAGE_CHARS: MAX_ERROR_MESSAGE_CHARS,
296
295
  MAX_ERROR_STACK_CHARS: MAX_ERROR_STACK_CHARS,
297
- MAX_ITEMS_PER_RUN: MAX_ITEMS_PER_RUN,
298
296
  MAX_ITEMS_PER_REQUEST: MAX_ITEMS_PER_REQUEST,
299
297
  MAX_ITEM_MESSAGE_CHARS: MAX_ITEM_MESSAGE_CHARS,
300
298
  MAX_ITEM_PAYLOAD_BYTES: MAX_ITEM_PAYLOAD_BYTES,
@@ -407,7 +405,7 @@ interface TransactionPayload {
407
405
  tags?: Record<string, string>;
408
406
  release?: string;
409
407
  environment?: EnvironmentInput;
410
- /** Correlaciona esta transaction a uma execução de task (ctx.tx dentro de um task handler) */
408
+ /** Correlaciona esta transaction a uma execução do agente (hobots.transaction dentro do handler) */
411
409
  run_id?: string;
412
410
  }
413
411
  interface HeartbeatPayload {
@@ -443,4 +441,4 @@ interface Envelope {
443
441
  items: EnvelopeItem[];
444
442
  }
445
443
 
446
- export { type Breadcrumb, type BreadcrumbLevel, type Envelope, type EnvelopeItem, type Environment, type EnvironmentInput, type EventPayload, type EventType, type EventUser, type ExceptionData, type HeartbeatPayload, type InstanceInfo, type ItemColumn, type MachineProcess, type MachineSnapshot, type PollRequest, type PollResponse, type RunAttachmentConfirmRequest, type RunAttachmentConfirmResponse, type RunAttachmentContentType, type RunAttachmentCreateRequest, type RunAttachmentCreateResponse, type RunCreateRequest, type RunCreateResponse, type RunDescriptor, type RunError, type RunItemInput, type RunItemStatus, type RunItemsCreateRequest, type RunItemsCreateResponse, type RunLogEntry, type RunLogLevel, type RunProgress, type RunStatus, type RunUpdateRequest, type RunUpdateResponse, type RunUpdateStatus, type StackFrame, type StepData, type StepStatus, type TaskItemsDeclaration, type TransactionPayload, WIRE_LIMITS, type WireLimits };
444
+ export { type Breadcrumb, type BreadcrumbLevel, type Envelope, type EnvelopeItem, type Environment, type EnvironmentInput, type EventPayload, type EventType, type EventUser, type ExceptionData, type HeartbeatPayload, type InstanceInfo, type InstanceMode, type ItemColumn, type ItemsDeclaration, type MachineProcess, type MachineSnapshot, type PollRequest, type PollResponse, type RunAttachmentConfirmRequest, type RunAttachmentConfirmResponse, type RunAttachmentContentType, type RunAttachmentCreateRequest, type RunAttachmentCreateResponse, type RunCreateRequest, type RunCreateResponse, type RunDescriptor, type RunError, type RunItemInput, type RunItemStatus, type RunItemsCreateRequest, type RunItemsCreateResponse, type RunLogEntry, type RunLogLevel, type RunProgress, type RunStatus, type RunUpdateRequest, type RunUpdateResponse, type RunUpdateStatus, type StackFrame, type StepData, type StepStatus, type TransactionPayload, WIRE_LIMITS, type WireLimits };
package/dist/protocol.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  WIRE_LIMITS
3
- } from "./chunk-5WIIACWC.js";
3
+ } from "./chunk-HKCDMUA3.js";
4
4
  export {
5
5
  WIRE_LIMITS
6
6
  };
package/docs/README.md CHANGED
@@ -2,27 +2,29 @@
2
2
 
3
3
  SDK JavaScript da **Hobots** para robôs (RPAs) e integrações. Cliente HTTP puro, sem dependências de runtime, Node 18+.
4
4
 
5
- **Tudo é uma task.** Não existe `init()`: a primeira chamada a `register()`/`start()` configura o processo (credenciais do ambiente, heartbeat sempre ligado, captura de erros não tratados). O objeto global `hobots` expõe a execução atual — `hobots.log`, `hobots.items`, `hobots.progress`, `hobots.transaction`… — de qualquer lugar do programa.
5
+ **O agente é a própria tarefa.** Não existe `init()` nem slug: a única chamada a `register()`/`start()` configura o processo (credenciais do ambiente, heartbeat sempre ligado, captura de erros não tratados) e diz o que o robô faz. O objeto global `hobots` expõe a execução atual — `hobots.log`, `hobots.items`, `hobots.progress`, `hobots.transaction`… — de qualquer lugar do programa.
6
6
 
7
7
  | Modo | Chamada | Para quê |
8
8
  | --- | --- | --- |
9
- | **Sob demanda** | `hobots.register(task, handler, options?)` | O robô faz polling e executa uma solicitação do app (formulário/agendamento) por vez — módulo **Solicitações**. |
10
- | **Sempre ligado** | `hobots.start(task, handler, options?)` | O robô abre a própria execução e roda o handler (o seu loop) dentro dela; a plataforma recebe logs, itens e progresso. |
9
+ | **Sob demanda** | `hobots.register(handler, options?)` | O robô faz polling e executa uma solicitação do app (formulário do agente/agendamento) por vez — módulo **Trabalhos**. |
10
+ | **Sempre ligado** | `hobots.start(handler, options?)` | O robô abre a própria execução e roda o handler (o seu loop) dentro dela; a plataforma recebe logs, itens e progresso. |
11
+
12
+ Uma chamada por processo: um processo é um agente, e um agente faz uma coisa.
11
13
 
12
14
  ## Páginas
13
15
 
14
- - [Getting started](./getting-started.md) — instalação, envs, primeira task nos dois modos, encerramento.
15
- - [Tasks](./tasks.md) — handler, o objeto `hobots`, itens, progresso, anexos, cancelamento automático, retry, concorrência, idempotência.
16
- - [Conceitos](./concepts.md) — o vocabulário: task, execução, evento, issue, transaction, step, heartbeat, instância, claim.
16
+ - [Getting started](./getting-started.md) — instalação, envs, o primeiro agente nos dois modos, encerramento.
17
+ - [Execuções](./runs.md) — handler, o objeto `hobots`, itens, progresso, anexos, cancelamento automático, retry, concorrência, idempotência.
18
+ - [Conceitos](./concepts.md) — o vocabulário: agente, execução, evento, issue, transaction, step, heartbeat, instância, claim.
17
19
  - [Referência de API](./api-reference.md) — assinaturas, tabelas de opções e tempos.
18
- - [Protocolo & transporte](./protocol.md) — Client Secret, endpoints (`/v1/ingest`, `/v1/tasks/*`), envelope, retries, claim atômico.
20
+ - [Protocolo & transporte](./protocol.md) — Client Secret, endpoints (`/v1/ingest`, `/v1/runs/*`), envelope, retries, claim atômico.
19
21
 
20
22
  ## Exemplo mínimo
21
23
 
22
24
  ```js
23
25
  import hobots from 'hobots'; // HOBOTS_CLIENT_SECRET e HOBOTS_INSTANCE_ID no ambiente
24
26
 
25
- hobots.register('processar-nfe', async params => {
27
+ hobots.register(async params => {
26
28
  hobots.log.info(`processando lote ${params.lote}…`);
27
29
  hobots.items.succeeded({ numero_nota: '123' }, { id: '123' });
28
30
  hobots.log.success('concluído'); // o retorno do handler é ignorado — reporte por log/itens
@@ -4,43 +4,47 @@
4
4
 
5
5
  | Import | Conteúdo |
6
6
  | --- | --- |
7
- | `hobots` | `hobots` (default e named), `register`, `start`, `close`, `captureException`, `retry` e os tipos. |
8
- | `hobots/protocol` | Tipos do wire format (telemetria e tasks). |
7
+ | `hobots` | `hobots` (default e named), `register`, `start`, `close`, `captureException`, `retry`, `image` e os tipos. |
8
+ | `hobots/protocol` | Tipos do wire format (telemetria e execuções). |
9
9
 
10
- ESM e CommonJS (`const { hobots } = require('hobots')`), com `.d.ts`. Depois da primeira task, `globalThis.hobots` também existe (tipado via `declare global`).
10
+ ESM e CommonJS (`const { hobots } = require('hobots')`), com `.d.ts`. Depois do `register()`/`start()`, `globalThis.hobots` também existe (tipado via `declare global`).
11
11
 
12
12
  ## Funções do processo
13
13
 
14
14
  | Função | Assinatura | Notas |
15
15
  | --- | --- | --- |
16
- | `hobots.register` | `<P>(task: string, handler: TaskHandler<P>, options?: RegisterOptions) => void` | Task sob demanda. Síncrona: valida slug/handler/secret e lança na hora. O boot roda num microtask — chamadas seguidas entram no primeiro poll. Slug repetido lança. |
17
- | `hobots.start` | `(task: string, handler: TaskHandler, options?: StartOptions) => void` | Task sempre ligada: abre a própria execução e roda o handler uma vez. |
16
+ | `hobots.register` | `<P>(handler: RunHandler<P>, options?: RegisterOptions) => void` | Agente sob demanda. Síncrona: valida handler/secret e lança na hora. O boot roda num microtask. **Uma chamada por processo** (register ou start) — a segunda lança `o agente já foi iniciado`. |
17
+ | `hobots.start` | `(handler: RunHandler, options?: StartOptions) => void` | Agente sempre ligado: abre a própria execução e roda o handler uma vez. Mesma regra de uma chamada por processo. |
18
18
  | `hobots.close` | `(timeoutMs = 30_000) => Promise<boolean>` | Para o polling, espera as execuções em voo (até `timeoutMs`; as restantes viram `AgentTerminated`), para o heartbeat e faz o flush final. `false` se estourou. Um `register`/`start` depois inicia um runtime novo. |
19
- | `hobots.captureException` | `(error: unknown, hint?: CaptureHint) => string \| undefined` | Issue no módulo Issues; devolve o `event_id`. Antes de qualquer task: descarta com aviso. |
19
+ | `hobots.captureException` | `(error: unknown, hint?: CaptureHint) => string \| undefined` | Issue no módulo Issues; devolve o `event_id`. Antes de iniciar o agente: descarta com aviso. |
20
20
  | `hobots.retry` | `<T>(fn: (attempt: number) => T \| Promise<T>, options?: RetryOptions) => Promise<T>` | async-retry; dentro de uma execução usa o signal dela. |
21
+ | `hobots.image` | `(input: AttachInput, options?: ImageOptions) => ImageAttachment` | Embrulha um print para ir junto de um log, item ou step. Puro, nunca lança. |
21
22
 
22
23
  ## Contexto da execução (`RunContext` — os membros de `hobots` e o `ctx` do handler)
23
24
 
24
25
  | Membro | Tipo | Notas |
25
26
  | --- | --- | --- |
26
- | `runId`, `task` | `string` | Identidade da execução (`''` fora de uma execução) |
27
- | `params` | `Record<string, unknown>` | Params da solicitação; `{}` no modo start |
28
- | `log` | `RunLogger` — `debug/info/warn/error/success(message, ...rest)` | Nunca lança. Vários argumentos viram texto unidos por espaço (como `console.log`); um `hobots.image(...)` no **último** argumento vira o print da linha |
27
+ | `runId` | `string` | Identidade da execução (`''` fora de uma execução) |
28
+ | `params` | `Record<string, unknown>` | Params da solicitação (formulário do agente); `{}` no modo start |
29
+ | `log` | `RunLogger` — `debug/info/warn/error/success(message, ...rest)` | Nunca lança. Vários argumentos viram texto unidos por espaço (como `console.log`); um `hobots.image(...)` no **último** argumento vira o print da linha. Eco no terminal: `[hobots] INFO …` |
29
30
  | `items` | `RunItems` — `add(item)`, `succeeded(payload?, opts?)`, `failed(message, payload?, opts?)`, `occurrence(message, payload?, opts?)`; `opts.id` = identidade de negócio, `opts.image` = print do item. `each(list, (element, item, index) => …, { id?, payload?, op?, description?, progress? }) => Promise<{ total, succeeded, failed, occurrence }>` processa a lista inteira: exceção no handler vira item `failed` + step em erro e o loop segue; `item: RunItemHandle` = `succeeded(payload?, { image }?)/failed(msg, payload?, { image }?)/occurrence(…)`, `id`, `index`, `step`, `reported` | Ponto de parada cooperativo (o `each` para só em cancelamento/timeout) |
30
31
  | `progress` | `RunProgressReporter` — `total(n)`, `advance(count = 1)`, `set(current, total?)`, `current`, `snapshot` | `total/advance/set` são pontos de parada |
31
- | `transaction` | `Transaction` — `startChild(op?, description?)`, `setTag`, `setStatus`, `setName`; `Step` — `startChild`, `setStatus('ok' \| 'warning' \| 'error', message?, { image }?)`, `setError(err, message?, { image }?)` (motivo em `data.error`, print em `data.attachments`, exibidos na Central), `setData(k, v)`, `finish()` | Finalizada pelo SDK; `startChild` é ponto de parada |
32
+ | `flush` | `(timeoutMs = 15_000) => Promise<void>` — envia já as steps raiz finalizadas (transactions parciais, op `hobots.run.flush`) e os itens/logs/progresso pendentes | Nunca lança |
33
+ | `transaction` | `Transaction` (`run`, op `hobots.run`) — `startChild(op?, description?)`, `flush()`, `setTag`, `setStatus`, `setName`; `Step` — `startChild`, `setStatus('ok' \| 'warning' \| 'error', message?, { image }?)`, `setError(err, message?, { image }?)` (motivo em `data.error`, print em `data.attachments`, exibidos na Central), `setData(k, v)`, `finish()` | Finalizada pelo SDK; `startChild` é ponto de parada |
32
34
  | `signal` | `AbortSignal` | Cancelamento (app, timeout, shutdown) |
33
35
  | `throwIfCanceled()` | `() => void` | Lança `RunCanceled` se o signal disparou |
34
36
  | `sleep(ms)` | `(ms: number) => Promise<void>` | Rejeita com `RunCanceled` no cancelamento |
35
37
  | `retry(fn, options?)` | como `hobots.retry` | |
36
38
 
37
- `hobots.image(input, options?)` — `(input: AttachInput, options?: ImageOptions) => ImageAttachment`; `AttachInput = Uint8Array \| ArrayBuffer \| string` (caminho); `ImageOptions = { caption?, contentType? }`; `ImageInput = AttachInput \| ImageAttachment` é o que `log.*` (só o embrulho), `items.*` e `step.setStatus/setError` aceitam. Puro, nunca lança; o upload (segundo plano, nunca bloqueia) acontece quando o evento é registrado.
39
+ `AttachInput = Uint8Array \| ArrayBuffer \| string` (caminho); `ImageOptions = { caption?, contentType? }`; `ImageInput = AttachInput \| ImageAttachment` é o que `log.*` (só o embrulho), `items.*` e `step.setStatus/setError` aceitam. O upload (segundo plano, nunca bloqueia) acontece quando o evento é registrado.
38
40
 
39
41
  Fora de uma execução, `hobots.*` cai em fallbacks seguros com aviso único por membro (log ecoa no terminal, imagem descartada; items/progress no-op; `signal` nunca aborta).
40
42
 
41
43
  ## Tabelas de opções
42
44
 
43
- ### `HobotsOptions` (processo — a primeira chamada define; divergências avisam e são ignoradas)
45
+ Só há uma chamada por processo, então todas as opções são **do agente**. Os tipos se empilham: `HobotsOptions` (telemetria e identidade) → `RunOptions` (a execução) → `RegisterOptions` (só sob demanda); `StartOptions = RunOptions`.
46
+
47
+ ### `HobotsOptions` (telemetria, identidade, handlers globais)
44
48
 
45
49
  | Opção | Tipo | Default | Descrição |
46
50
  | --- | --- | --- | --- |
@@ -54,26 +58,26 @@ Fora de uma execução, `hobots.*` cai em fallbacks seguros com aviso único por
54
58
  | `captureUnhandled` | `boolean` | `true` | handlers globais de erro (issues) |
55
59
  | `installExitHandlers` | `boolean` | `true` | avançado — SIGINT/SIGTERM/uncaughtException reportam `AgentTerminated` |
56
60
 
57
- ### `TaskOptions extends HobotsOptions` (por task)
61
+ ### `RunOptions extends HobotsOptions` (a execução — `register` e `start`)
58
62
 
59
63
  | Opção | Tipo | Default | Descrição |
60
64
  | --- | --- | --- | --- |
65
+ | `items` | `ItemsOptions` = `{ columns: Array<string \| { key, label? }> }` | — | colunas da aba de itens no app (chaves do `payload` dos itens); até 12, chave `[a-zA-Z0-9_.-]`. Uma declaração só, do agente; independe de formulário; personalizar no app sobrepõe |
61
66
  | `retries` | `number` | `1` | tentativas extras do handler; `0` desliga |
62
67
  | `retryDelayMs` | `number \| (attempt) => number` | `5_000` | `attempt` 1-based (a que falhou) |
63
68
  | `timeoutMs` | `number` | — | por tentativa; terminal (`TaskTimeout`) |
64
69
  | `logFlushIntervalMs` | `number` | `2_000` | avançado |
65
70
  | `cancelCheckIntervalMs` | `number` | `5_000` (1_000..15_000) | avançado — PATCH vazio que detecta cancelamento e é o sinal de vida da execução |
66
71
  | `cancelGraceMs` | `number` | `10_000` | avançado — graça após o signal antes de liberar o slot |
67
- | `items` | `{ columns: Array<string \| { key, label? }> }` | — | colunas da aba de itens no app (chaves do `payload` dos itens); até 12, chave `[a-zA-Z0-9_.-]`. Independe de formulário; personalizar no app sobrepõe |
68
72
 
69
- ### `RegisterOptions extends TaskOptions`
73
+ ### `RegisterOptions extends RunOptions` (só sob demanda)
70
74
 
71
75
  | Opção | Tipo | Default | Descrição |
72
76
  | --- | --- | --- | --- |
73
- | `concurrency` | `number` | `1` | execuções simultâneas desta task (1..5) |
74
- | `pollIntervalMs` | `number` | `2_000` (mín. 1_000) | intervalo entre polls sem trabalho; vale o do primeiro `register()` |
77
+ | `concurrency` | `number` | `1` | execuções simultâneas do agente (1..5) |
78
+ | `pollIntervalMs` | `number` | `2_000` (mín. 1_000) | intervalo entre polls sem trabalho |
75
79
 
76
- `StartOptions = TaskOptions`.
80
+ `StartOptions = RunOptions`.
77
81
 
78
82
  ### `RetryOptions`
79
83
 
@@ -91,12 +95,22 @@ Fora de uma execução, `hobots.*` cai em fallbacks seguros com aviso único por
91
95
  | `tags`, `extra`, `fingerprint` | | metadados do evento (`fingerprint` sobrescreve o agrupamento) |
92
96
  | `attachment` | `ImageInput \| { image, caption?, contentType? }` | print anexado à linha de log da execução atual |
93
97
 
94
- ### `TaskHandler`
98
+ ### `RunHandler`
95
99
 
96
100
  ```ts
97
- type TaskHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
101
+ type RunHandler<P = Record<string, unknown>> = (params: P, ctx: RunContext) => void | Promise<void>;
98
102
  ```
99
103
 
104
+ ### Tipos do wire que mudaram na 4.0
105
+
106
+ | Tipo | O que é |
107
+ | --- | --- |
108
+ | `InstanceMode` | `'on_demand' \| 'always_on'` — como a instância trabalha (`register` / `start`) |
109
+ | `ItemsDeclaration` | `{ attributes: ItemColumn[] }` — as colunas de itens declaradas pela opção `items` |
110
+ | `InstanceInfo` | ganhou `mode?: InstanceMode` e `items?: ItemsDeclaration`; perdeu a lista de tasks e as colunas por task da 3.x |
111
+ | `PollRequest` | `{ instance?, max? }` — sem lista de tasks |
112
+ | `RunDescriptor` / `RunCreateRequest` | sem `task` |
113
+
100
114
  ## Tempos e intervalos
101
115
 
102
116
  | O quê | Valor |