robotrock 0.7.0 → 0.8.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.
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../src/schemas/index.ts","../../src/approval-result.ts","../../src/client.ts","../../src/env.ts","../../src/handler-webhook.ts","../../src/wait-timing.ts","../../src/trigger/index.ts","../../src/workflow/index.ts","../../src/ai/approve-by-human-tool-core.ts","../../src/ai/context.ts","../../src/ai/human-tool-result.ts","../../src/ai/create-send-to-human-tool-core.ts","../../src/ai/create-send-update-tool-core.ts","../../src/ai/workflow-tools.ts","../../src/ai/format-tool-approval-task.ts","../../src/ai/tool-approval-bridge.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n isPublicHttpUrl,\n PUBLIC_HTTP_URL_ERROR,\n} from \"@robotrock/core/utils\";\nimport { validateContextPublicUrls } from \"@robotrock/core/schemas\";\n\nexport interface JSONSchema7 {\n $id?: string;\n $ref?: string;\n $schema?: string;\n $comment?: string;\n type?: JSONSchema7TypeName | JSONSchema7TypeName[];\n enum?: unknown[];\n const?: unknown;\n multipleOf?: number;\n maximum?: number;\n exclusiveMaximum?: number;\n minimum?: number;\n exclusiveMinimum?: number;\n maxLength?: number;\n minLength?: number;\n pattern?: string;\n format?: string;\n items?: JSONSchema7 | JSONSchema7[];\n additionalItems?: JSONSchema7 | boolean;\n maxItems?: number;\n minItems?: number;\n uniqueItems?: boolean;\n contains?: JSONSchema7;\n maxProperties?: number;\n minProperties?: number;\n required?: string[];\n properties?: Record<string, JSONSchema7>;\n patternProperties?: Record<string, JSONSchema7>;\n additionalProperties?: JSONSchema7 | boolean;\n dependencies?: Record<string, JSONSchema7 | string[]>;\n propertyNames?: JSONSchema7;\n if?: JSONSchema7;\n then?: JSONSchema7;\n else?: JSONSchema7;\n allOf?: JSONSchema7[];\n anyOf?: JSONSchema7[];\n oneOf?: JSONSchema7[];\n not?: JSONSchema7;\n title?: string;\n description?: string;\n default?: unknown;\n readOnly?: boolean;\n writeOnly?: boolean;\n examples?: unknown[];\n}\n\nexport type JSONSchema7TypeName =\n | \"string\"\n | \"number\"\n | \"integer\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"null\";\n\nexport type ExtendedJSONSchema7 = JSONSchema7 & {\n enumNames?: string[];\n [key: string]: unknown;\n};\n\nexport type UiSchema = {\n \"ui:widget\"?: string;\n \"ui:title\"?: string;\n \"ui:description\"?: string;\n \"ui:placeholder\"?: string;\n \"ui:options\"?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nconst safeUrlSchema = z.string().refine((url) => isPublicHttpUrl(url), {\n message: PUBLIC_HTTP_URL_ERROR,\n});\n\nconst jsonSchema7Schema = z.custom<ExtendedJSONSchema7>(\n (val) => typeof val === \"object\" && val !== null,\n { message: \"Must be a valid JSON Schema object\" }\n);\n\nconst uiSchemaSchema = z.custom<UiSchema>((val) => typeof val === \"object\" && val !== null, {\n message: \"Must be a valid UiSchema object\",\n});\n\nconst webhookHandlerSchema = z.object({\n type: z.literal(\"webhook\"),\n url: safeUrlSchema,\n headers: z.record(z.string(), z.string()),\n});\n\nconst triggerHandlerSchema = webhookHandlerSchema.extend({\n type: z.literal(\"trigger\"),\n tokenId: z.string().min(1),\n});\n\nconst handlerSchema = z.discriminatedUnion(\"type\", [webhookHandlerSchema, triggerHandlerSchema]);\n\nconst taskActionSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n description: z.string().optional(),\n schema: jsonSchema7Schema.optional(),\n ui: uiSchemaSchema.optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n handlers: z.array(handlerSchema).min(1).optional(),\n});\n\nconst uiFieldSchemaSchema: z.ZodType<Record<string, unknown>> = z\n .object({\n \"ui:widget\": z.string().optional(),\n \"ui:title\": z.string().optional(),\n \"ui:description\": z.string().optional(),\n \"ui:options\": z.record(z.string(), z.unknown()).optional(),\n items: z.lazy(() => z.record(z.string(), uiFieldSchemaSchema)).optional(),\n })\n .passthrough();\n\nconst contextUiSchema = z.record(z.string(), uiFieldSchemaSchema).optional();\n\nconst contextDataSchema = z\n .object({\n data: z.record(z.string(), z.unknown()),\n ui: contextUiSchema,\n })\n .optional();\n\nconst taskContextObjectSchema = z.object({\n app: z.string().min(1).optional(),\n type: z.string().min(1),\n name: z.string().min(1),\n description: z.string().optional(),\n validUntil: z.string().optional(),\n context: contextDataSchema,\n version: z.literal(2).optional(),\n actions: z.array(taskActionSchema).min(1, \"At least one action is required\"),\n});\n\nfunction refineContextPublicUrls<T extends { context?: z.infer<typeof contextDataSchema> }>(\n data: T,\n ctx: z.RefinementCtx\n) {\n const error = validateContextPublicUrls(data.context);\n if (error) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: error,\n path: [\"context\"],\n });\n }\n}\n\nexport const taskContextSchema = taskContextObjectSchema.superRefine(\n refineContextPublicUrls\n);\n\n/**\n * Assignment targets at task create (not stored in task context JSON).\n * Unknown user emails are auto-provisioned as assignee memberships (count toward seat limits).\n */\nexport const assignToSchema = z\n .object({\n users: z.array(z.string().email()).optional(),\n groups: z.array(z.string().min(1)).optional(),\n })\n .refine(\n (data) => {\n const groups = data.groups ?? [];\n if (groups.includes(\"all\") && groups.length > 1) {\n return false;\n }\n return true;\n },\n { message: 'Cannot combine \"all\" with other group slugs' }\n );\n\n/** A short thread-scoped status update message (1-2 sentences). */\nexport const threadUpdateMessageSchema = z.string().min(1).max(500);\n\n/**\n * Lifecycle status carried by a thread update. Drives the icon and color shown\n * in the inbox status bar. Defaults to `info` when omitted.\n */\nexport const threadUpdateStatuses = [\n \"info\",\n \"queued\",\n \"running\",\n \"waiting\",\n \"succeeded\",\n \"failed\",\n \"cancelled\",\n] as const;\n\nexport const threadUpdateStatusSchema = z.enum(threadUpdateStatuses);\n\n/** The default status applied when an update omits one. */\nexport const DEFAULT_THREAD_UPDATE_STATUS: ThreadUpdateStatus = \"info\";\n\n/** Shared shape for a thread update (standalone and at task creation). */\nexport const threadUpdateInputSchema = z.object({\n message: threadUpdateMessageSchema,\n status: threadUpdateStatusSchema.optional(),\n});\n\n/** Thread priority levels for inbox ordering and display. */\nexport const taskPriorities = [\"low\", \"normal\", \"high\", \"urgent\"] as const;\n\nexport const taskPrioritySchema = z.enum(taskPriorities);\n\nexport type TaskPriority = (typeof taskPriorities)[number];\n\nexport const DEFAULT_TASK_PRIORITY: TaskPriority = \"normal\";\n\nexport const LOWEST_TASK_PRIORITY: TaskPriority = \"low\";\n\nexport const TASK_PRIORITY_RANK: Record<TaskPriority, number> = {\n low: 1,\n normal: 2,\n high: 3,\n urgent: 4,\n};\n\nconst nonNegativeInt = z.number().int().nonnegative();\n\nexport const agentCostTokensSchema = z.object({\n input: nonNegativeInt.optional(),\n output: nonNegativeInt.optional(),\n total: nonNegativeInt.optional(),\n});\n\nexport const agentCostSchema = z.object({\n tokens: agentCostTokensSchema.optional(),\n eur: z.number().nonnegative().optional(),\n usd: z.number().nonnegative().optional(),\n});\n\nconst AGENT_INFO_MAX_KEYS = 32;\n\nexport const agentTelemetrySchema = z\n .object({\n version: z.string().min(1).optional(),\n toolCallCount: nonNegativeInt.optional(),\n cost: agentCostSchema.optional(),\n info: z.record(z.string(), z.unknown()).optional(),\n })\n .refine(\n (data) => {\n const keys = data.info ? Object.keys(data.info) : [];\n return keys.length <= AGENT_INFO_MAX_KEYS;\n },\n { message: `agent.info may contain at most ${AGENT_INFO_MAX_KEYS} keys` }\n );\n\nexport const createTaskBodySchema = taskContextObjectSchema\n .extend({\n assignTo: assignToSchema.optional(),\n /**\n * Groups related tasks together. When omitted, the server generates one and\n * returns it so the caller can reuse it on later tasks in the same thread.\n */\n threadId: z.string().min(1).optional(),\n /**\n * Optional thread priority. When set, applies to the whole thread and\n * overwrites any previous priority. Omit on later tasks to leave unchanged.\n */\n priority: taskPrioritySchema.optional(),\n /**\n * Optional initial status update logged against the task's thread. Shows in\n * the inbox status bar and the thread update log.\n */\n update: threadUpdateInputSchema.optional(),\n agent: agentTelemetrySchema.optional(),\n })\n .superRefine(refineContextPublicUrls);\n\n/** POST /v1/threads/:threadId/updates body: a standalone thread update. */\nexport const threadUpdateBodySchema = threadUpdateInputSchema;\n\n/** Where a thread update originated. */\nexport type ThreadUpdateSource = \"api\" | \"task_create\" | \"dashboard\";\n\n/** Lifecycle status carried by a thread update. */\nexport type ThreadUpdateStatus = (typeof threadUpdateStatuses)[number];\n\n/** A logged thread update as returned by the API. */\nexport interface ThreadUpdate {\n id: string;\n threadId: string;\n message: string;\n status: ThreadUpdateStatus;\n source: ThreadUpdateSource;\n createdAt: number;\n}\n\nexport type AssignToInput = z.infer<typeof assignToSchema>;\nexport type CreateTaskBodyInput = z.input<typeof createTaskBodySchema>;\nexport type CreateTaskBody = z.output<typeof createTaskBodySchema>;\nexport type ThreadUpdateBodyInput = z.input<typeof threadUpdateBodySchema>;\nexport type ThreadUpdateBody = z.output<typeof threadUpdateBodySchema>;\nexport type ThreadUpdateInput = z.input<typeof threadUpdateInputSchema>;\nexport type TaskContextInput = z.input<typeof taskContextSchema>;\nexport type TaskContextOutput = z.output<typeof taskContextSchema>;\nexport type TaskContext = TaskContextOutput;\nexport type TaskAction = z.infer<typeof taskActionSchema>;\nexport type WebhookHandler = z.infer<typeof webhookHandlerSchema>;\nexport type TriggerHandler = z.infer<typeof triggerHandlerSchema>;\nexport type Handler = z.infer<typeof handlerSchema>;\nexport type AgentCostTokens = z.infer<typeof agentCostTokensSchema>;\nexport type AgentCost = z.infer<typeof agentCostSchema>;\nexport type AgentTelemetry = z.infer<typeof agentTelemetrySchema>;\nexport type AgentTelemetryInput = z.input<typeof agentTelemetrySchema>;\n\ntype InferObjectProperties<\n Props,\n Req extends PropertyKey,\n> = Props extends Record<string, unknown>\n ? ({\n [K in keyof Props as K extends Req ? K : never]-?: InferJsonSchema7<Props[K]>;\n } & {\n [K in keyof Props as K extends Req ? never : K]?: InferJsonSchema7<Props[K]>;\n } extends infer O\n ? { [K in keyof O]: O[K] }\n : never)\n : Record<string, unknown>;\n\ntype RequiredKeys<S> =\n S extends { readonly required: readonly string[] } ? S[\"required\"][number] : never;\n\nexport type InferJsonSchema7<S> = [S] extends [undefined]\n ? Record<string, never>\n : S extends { readonly const: infer C }\n ? C\n : S extends {\n readonly enum: readonly (infer E)[];\n }\n ? E\n : S extends {\n readonly type: \"object\";\n readonly properties?: infer Props;\n }\n ? InferObjectProperties<Props, RequiredKeys<S>>\n : S extends {\n readonly type: \"object\";\n readonly properties?: undefined;\n }\n ? Record<string, unknown>\n : S extends {\n readonly type: \"array\";\n readonly items?: infer Items;\n }\n ? Items extends readonly unknown[]\n ? InferJsonSchema7<Items[number]>[]\n : Items extends object\n ? InferJsonSchema7<Items>[]\n : unknown[]\n : S extends { readonly type: \"string\" }\n ? string\n : S extends { readonly type: \"number\" } | { readonly type: \"integer\" }\n ? number\n : S extends { readonly type: \"boolean\" }\n ? boolean\n : unknown;\n\nexport type TaskStatus = \"pending\" | \"open\" | \"handled\" | \"expired\";\n\nexport interface TaskResponse {\n success: boolean;\n task: {\n taskId: string;\n threadId: string;\n status: \"pending\" | \"open\";\n context: TaskContext;\n validUntil: string;\n submittedAt: string;\n };\n message: string;\n}\n\nexport interface ThreadUpdateResponse {\n success: boolean;\n update: ThreadUpdate;\n message: string;\n}\n\nexport interface Task {\n id: string;\n threadId?: string;\n createdAt: Date;\n status: TaskStatus;\n context: TaskContext;\n validUntil: number;\n handledAt?: number;\n handled?: {\n action: {\n id: string;\n data: unknown;\n };\n handledBy?: string;\n userId?: string;\n token?: string;\n };\n}\n\nexport type InferActionData<T extends { schema?: unknown }> = [\n Exclude<T[\"schema\"], undefined>,\n] extends [\n never,\n]\n ? Record<string, never>\n : Exclude<T[\"schema\"], undefined> extends infer S\n ? InferJsonSchema7<S>\n : Record<string, never>;\n\nexport type TupleElementIndices<T extends readonly unknown[]> = T extends readonly [\n unknown,\n ...unknown[],\n]\n ? Exclude<keyof T, keyof unknown[]>\n : number;\n\nexport interface TaskResult<T = Record<string, unknown>> {\n actionId: string;\n data: T;\n handledBy?: string;\n handledAt: Date;\n}\n\nexport interface ApprovalResult<T = Record<string, unknown>> extends TaskResult<T> {\n taskId: string;\n}\n\nexport type DiscriminatedApprovalResult<\n TActions extends readonly { id: string; schema?: unknown }[],\n> = {\n [I in TupleElementIndices<TActions>]: TActions[I] extends { id: string; schema?: unknown }\n ? Omit<ApprovalResult<InferActionData<TActions[I]>>, \"actionId\" | \"data\"> & {\n actionId: TActions[I][\"id\"];\n data: InferActionData<TActions[I]>;\n }\n : never\n}[TupleElementIndices<TActions>];\n","import type { DiscriminatedApprovalResult, Task } from \"./schemas/index.js\";\n\nexport class TaskTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TaskTimeoutError\";\n }\n}\n\nexport class TaskExpiredError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TaskExpiredError\";\n }\n}\n\n/**\n * Map a handled API task to a discriminated approval result.\n * Runtime validation is minimal; TypeScript narrows via `task.actions` at the call site.\n */\nexport function toDiscriminatedApprovalResult<A extends readonly { id: string; schema?: unknown }[]>(\n actions: A,\n task: Task\n): DiscriminatedApprovalResult<A> {\n void actions;\n\n if (!task.handled) {\n throw new Error(\"Task has no handled result\");\n }\n\n return {\n actionId: task.handled.action.id,\n data: task.handled.action.data,\n handledBy: task.handled.handledBy,\n handledAt: new Date(task.handledAt ?? Date.now()),\n taskId: task.id,\n } as DiscriminatedApprovalResult<A>;\n}\n","import {\n type AssignToInput,\n type TaskContextInput,\n createTaskBodySchema,\n threadUpdateBodySchema,\n} from \"./schemas/index.js\";\nimport {\n TaskExpiredError,\n TaskTimeoutError,\n toDiscriminatedApprovalResult,\n} from \"./approval-result.js\";\nimport type {\n DiscriminatedApprovalResult,\n Task,\n TaskPriority,\n TaskResponse,\n ThreadUpdate,\n ThreadUpdateResponse,\n ThreadUpdateStatus,\n AgentTelemetryInput,\n} from \"./schemas/index.js\";\n\nexport type RobotRockWebhookConfig = {\n url: string;\n headers?: Record<string, string>;\n};\n\nexport interface RobotRockPollingOptions {\n /** Poll interval when no webhook is configured (ms). @default 2000 */\n intervalMs?: number;\n /**\n * Max time to poll when no webhook is configured (ms).\n * Polling also stops when the task's `validUntil` passes, whichever is sooner.\n * @default 86400000 (24h)\n */\n timeoutMs?: number;\n}\n\ntype RobotRockClientBaseConfig = {\n /** Optional override for API key. Falls back to ROBOTROCK_API_KEY. */\n apiKey?: string;\n /**\n * Base URL for the RobotRock API\n * @default \"https://api.robotrock.io/v1\"\n */\n baseUrl?: string;\n /**\n * Default inbox app bucket for every task from this client.\n * When omitted, the API uses your API key name.\n */\n app?: string;\n /**\n * Task context format version sent on every `sendToHuman` request.\n * @default 2\n */\n version?: 2;\n};\n\n/** Client config with a webhook (mutually exclusive with `polling`). */\nexport type RobotRockWebhookClientConfig = RobotRockClientBaseConfig & {\n webhook: RobotRockWebhookConfig;\n polling?: never;\n};\n\n/** Client config without a webhook; optional `polling` controls the wait loop. */\nexport type RobotRockPollingClientConfig = RobotRockClientBaseConfig & {\n webhook?: never;\n polling?: RobotRockPollingOptions;\n};\n\nexport type RobotRockConfig = RobotRockWebhookClientConfig | RobotRockPollingClientConfig;\n\nexport type SendToHumanActionInput = Omit<TaskContextInput[\"actions\"][number], \"handlers\">;\n\nexport type SendToHumanValidUntil = Date | string;\n\nexport type SendToHumanInput<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = Omit<TaskContextInput, \"app\" | \"actions\" | \"version\" | \"validUntil\"> & {\n actions: A;\n /** Task deadline; serialized to an ISO 8601 string on the wire. */\n validUntil?: SendToHumanValidUntil;\n /** Optional idempotency key to prevent duplicate tasks */\n idempotencyKey?: string;\n /** Assign to tenant users (email) and/or groups (slug). Narrows inbox visibility. */\n assignTo?: AssignToInput;\n /**\n * Groups related tasks together in the inbox. Omit to let the server generate\n * one (returned as `task.threadId`) and reuse it on later tasks in the thread.\n */\n threadId?: string;\n /**\n * Optional thread priority. When set, applies to the whole thread and\n * overwrites any previous priority. Omit on later tasks to leave unchanged.\n */\n priority?: TaskPriority;\n /**\n * Optional initial status update logged against the task's thread. Shows in\n * the inbox status bar and the thread update log.\n */\n update?: {\n /** A short status update (1-2 sentences). */\n message: string;\n /** Lifecycle status for the icon/color in the status bar. @default \"info\" */\n status?: ThreadUpdateStatus;\n };\n /**\n * Agent telemetry (version, cost, tool calls) — not shown in inbox UI.\n * Used for statistics and feedback analysis.\n */\n agent?: AgentTelemetryInput;\n};\n\ntype SendToHumanWithAppInput<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = (SendToHumanInput<A> | Readonly<SendToHumanInput<A>>) & {\n /** Inbox app bucket. Overrides the client `app` when set. */\n app?: string;\n};\n\nexport type SendUpdateInput = {\n /** The thread to log the update against (from `task.threadId`). */\n threadId: string;\n /** A short status update (1-2 sentences). */\n message: string;\n /** Lifecycle status for the icon/color in the status bar. @default \"info\" */\n status?: ThreadUpdateStatus;\n};\n\nexport type SendToHumanResult<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> =\n | {\n mode: \"created\";\n task: TaskResponse[\"task\"];\n }\n | ({\n mode: \"handled\";\n task: TaskResponse[\"task\"];\n } & DiscriminatedApprovalResult<A>);\n\nconst DEFAULT_POLL_INTERVAL_MS = 2_000;\nconst DEFAULT_TIMEOUT_MS = 24 * 60 * 60 * 1_000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseValidUntilMs(value: string | number | Date | undefined): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (value instanceof Date) {\n const ms = value.getTime();\n return Number.isNaN(ms) ? undefined : ms;\n }\n\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\nfunction serializeValidUntil(value: SendToHumanValidUntil): string {\n if (value instanceof Date) {\n const ms = value.getTime();\n if (Number.isNaN(ms)) {\n throw new RobotRockError(\"Invalid validUntil: Date is invalid\", 400);\n }\n return value.toISOString();\n }\n\n if (typeof value === \"string\" && !Number.isNaN(Date.parse(value))) {\n return new Date(value).toISOString();\n }\n\n throw new RobotRockError(\"Invalid validUntil: expected a Date or parseable date string\", 400);\n}\n\nexport class RobotRockError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly response?: unknown\n ) {\n super(message);\n this.name = \"RobotRockError\";\n }\n}\n\n/**\n * RobotRock API client for creating and querying human-in-the-loop tasks.\n */\nexport class RobotRock {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly app?: string;\n private readonly version: 2;\n private readonly webhook?: RobotRockWebhookConfig;\n private readonly polling: RobotRockPollingOptions;\n\n constructor(config: RobotRockConfig) {\n if (config.webhook && config.polling) {\n throw new Error(\n \"RobotRock client cannot configure both webhook and polling. Use webhook for callbacks or polling to block until handled.\"\n );\n }\n\n const apiKey = config.apiKey ?? process.env.ROBOTROCK_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"RobotRock API key is required. Set ROBOTROCK_API_KEY or pass apiKey when creating the client.\"\n );\n }\n this.apiKey = apiKey;\n const rawBase = config.baseUrl ?? \"https://api.robotrock.io/v1\";\n this.baseUrl = rawBase.replace(/\\/+$/, \"\");\n this.app = config.app;\n this.version = config.version ?? 2;\n this.webhook = config.webhook;\n this.polling = config.polling ?? {};\n }\n\n /**\n * Create a task via POST /v1 without waiting for a human response.\n */\n async createTask<const A extends readonly SendToHumanActionInput[]>(\n task: SendToHumanWithAppInput<A>\n ): Promise<TaskResponse[\"task\"]> {\n const normalizedTask = normalizeSendToHumanInput(task, {\n webhook: this.webhook,\n app: this.app,\n version: this.version,\n });\n const bodyPayload = {\n ...normalizedTask,\n ...(task.assignTo !== undefined ? { assignTo: task.assignTo } : {}),\n ...(task.threadId !== undefined ? { threadId: task.threadId } : {}),\n ...(task.priority !== undefined ? { priority: task.priority } : {}),\n ...(task.update !== undefined ? { update: task.update } : {}),\n ...(task.agent !== undefined ? { agent: task.agent } : {}),\n };\n const validation = createTaskBodySchema.safeParse(bodyPayload);\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid task: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": this.apiKey,\n };\n\n if (task.idempotencyKey) {\n headers[\"Idempotency-Key\"] = task.idempotencyKey;\n }\n\n const response = await fetch(`${this.baseUrl}/`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(validation.data),\n });\n\n const data = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to create task\"),\n response.status,\n data\n );\n }\n\n return (data as unknown as TaskResponse).task;\n }\n\n async sendToHuman<const A extends readonly SendToHumanActionInput[]>(\n task: SendToHumanWithAppInput<A>\n ): Promise<SendToHumanResult<A>> {\n const normalizedTask = normalizeSendToHumanInput(task, {\n webhook: this.webhook,\n app: this.app,\n version: this.version,\n });\n const createdTaskTask = await this.createTask(task);\n const hasHandlers = normalizedTask.actions.some(\n (action) => Array.isArray(action.handlers) && action.handlers.length > 0\n );\n\n if (hasHandlers) {\n return {\n mode: \"created\",\n task: createdTaskTask,\n };\n }\n\n const timeoutMs = this.polling.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = this.polling.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const pollingDeadline = Date.now() + timeoutMs;\n const validUntilMs = parseValidUntilMs(createdTaskTask.validUntil);\n const deadline =\n validUntilMs !== undefined ? Math.min(pollingDeadline, validUntilMs) : pollingDeadline;\n const taskId = createdTaskTask.taskId;\n\n while (Date.now() < deadline) {\n const existing = await this.getTask(taskId);\n\n if (existing?.status === \"handled\" && existing.handled) {\n return {\n mode: \"handled\",\n task: createdTaskTask,\n ...(toDiscriminatedApprovalResult(\n normalizedTask.actions as unknown as A,\n existing\n ) as DiscriminatedApprovalResult<A>),\n };\n }\n\n if (existing?.status === \"expired\" || (existing && Date.now() >= existing.validUntil)) {\n throw new TaskExpiredError(\"Task reached validUntil before a human completed it\");\n }\n\n const remainingMs = deadline - Date.now();\n await sleep(Math.min(pollIntervalMs, Math.max(0, remainingMs)));\n }\n\n if (validUntilMs !== undefined && Date.now() >= validUntilMs) {\n throw new TaskExpiredError(\"Task reached validUntil before a human completed it\");\n }\n\n throw new TaskTimeoutError(`No human response within ${timeoutMs}ms`);\n }\n\n /**\n * Get a task by public task id (returned as `task.taskId` from {@link sendToHuman}).\n */\n async getTask(taskId: string): Promise<Task | null> {\n const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {\n method: \"GET\",\n headers: {\n \"X-Api-Key\": this.apiKey,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n const data = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to get task\"),\n response.status,\n data\n );\n }\n\n return data as unknown as Task;\n }\n\n /**\n * Log a status update against a thread. The update shows in the inbox status\n * bar and thread update log for every task in the thread.\n */\n async sendUpdate({ threadId, message, status }: SendUpdateInput): Promise<ThreadUpdate> {\n if (!threadId) {\n throw new RobotRockError(\"threadId is required to send an update\", 400);\n }\n\n const validation = threadUpdateBodySchema.safeParse({ message, status });\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid update: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const response = await fetch(\n `${this.baseUrl}/threads/${encodeURIComponent(threadId)}/updates`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": this.apiKey,\n },\n body: JSON.stringify(validation.data),\n }\n );\n\n const data = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to send update\"),\n response.status,\n data\n );\n }\n\n return (data as unknown as ThreadUpdateResponse).update;\n }\n\n async cancelTask(taskId: string): Promise<void> {\n const response = await fetch(`${this.baseUrl}/tasks/${taskId}/cancel`, {\n method: \"POST\",\n headers: {\n \"X-Api-Key\": this.apiKey,\n },\n });\n\n if (!response.ok) {\n const data = await parseResponseBody(response);\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to cancel task\"),\n response.status,\n data\n );\n }\n }\n}\n\nexport function createClient(config: RobotRockConfig): RobotRock {\n return new RobotRock(config);\n}\n\nexport function attachWebhookToActions(\n actions: readonly SendToHumanActionInput[],\n webhook: RobotRockWebhookConfig\n): TaskContextInput[\"actions\"] {\n return actions.map((action) => ({\n ...action,\n handlers: webhookToHandlers(webhook),\n }));\n}\n\nfunction webhookToHandlers(\n webhook: RobotRockWebhookConfig\n): TaskContextInput[\"actions\"][number][\"handlers\"] {\n return [\n {\n type: \"webhook\" as const,\n url: webhook.url,\n headers: webhook.headers ?? {},\n },\n ];\n}\n\nfunction normalizeSendToHumanInput<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n>(\n task: SendToHumanWithAppInput<A>,\n clientDefaults: { webhook?: RobotRockWebhookConfig; app?: string; version: 2 }\n): TaskContextInput {\n const {\n actions,\n idempotencyKey: _idempotencyKey,\n assignTo: _assignTo,\n threadId: _threadId,\n priority: _priority,\n update: _update,\n validUntil,\n app: taskApp,\n ...rest\n } = task;\n\n const webhook = clientDefaults.webhook;\n const normalizedActions: TaskContextInput[\"actions\"] = webhook\n ? attachWebhookToActions(actions, webhook)\n : (actions as unknown as TaskContextInput[\"actions\"]);\n\n const app = taskApp ?? clientDefaults.app;\n\n return {\n ...rest,\n version: clientDefaults.version,\n ...(app ? { app } : {}),\n ...(validUntil !== undefined ? { validUntil: serializeValidUntil(validUntil) } : {}),\n actions: normalizedActions,\n };\n}\n\ntype ParsedResponseBody = Record<string, unknown> | unknown[] | string | null;\n\nasync function parseResponseBody(response: Response): Promise<ParsedResponseBody> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const bodyText = await response.text();\n\n if (!bodyText) {\n return null;\n }\n\n if (contentType.toLowerCase().includes(\"application/json\")) {\n try {\n return JSON.parse(bodyText) as ParsedResponseBody;\n } catch {\n // Fall through and return text body below so error messages stay useful.\n }\n }\n\n try {\n return JSON.parse(bodyText) as ParsedResponseBody;\n } catch {\n return bodyText;\n }\n}\n\nfunction getErrorMessage(data: ParsedResponseBody, fallback: string): string {\n if (data && typeof data === \"object\" && !Array.isArray(data)) {\n const maybeMessage = (data as Record<string, unknown>).message;\n if (typeof maybeMessage === \"string\" && maybeMessage.trim()) {\n return maybeMessage;\n }\n }\n\n if (typeof data === \"string\" && data.trim()) {\n const compact = data.replace(/\\s+/g, \" \").trim();\n const snippet = compact.length > 180 ? `${compact.slice(0, 180)}...` : compact;\n return `${fallback}. Server returned non-JSON response: ${snippet}`;\n }\n\n return fallback;\n}\n","import { createClient, type RobotRock, type RobotRockConfig } from \"./client.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.robotrock.io/v1\";\n\n/**\n * Read RobotRock client config from environment variables.\n *\n * - `ROBOTROCK_API_KEY` (required when not passed explicitly)\n * - `ROBOTROCK_BASE_URL` or `ROBOTROCK_API_URL` (optional)\n * - `ROBOTROCK_APP` (optional inbox app bucket)\n */\nexport function resolveRobotRockConfig(\n overrides?: Partial<RobotRockConfig>\n): RobotRockConfig {\n const apiKey = overrides?.apiKey ?? process.env.ROBOTROCK_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"RobotRock API key is required. Set ROBOTROCK_API_KEY or pass apiKey when creating the client.\"\n );\n }\n\n const baseUrl =\n overrides?.baseUrl ??\n process.env.ROBOTROCK_BASE_URL ??\n process.env.ROBOTROCK_API_URL ??\n DEFAULT_BASE_URL;\n\n const app = overrides?.app ?? process.env.ROBOTROCK_APP;\n\n return app ? { apiKey, baseUrl, app } : { apiKey, baseUrl };\n}\n\n/** Use an explicit client or create one from env / optional config overrides. */\nexport function resolveRobotRockClient(\n client?: RobotRock,\n configOverrides?: Partial<RobotRockConfig>\n): RobotRock {\n if (client) {\n return client;\n }\n return createClient(resolveRobotRockConfig(configOverrides));\n}\n","/**\n * JSON body posted when a RobotRock action handler runs (webhook or Trigger wait token).\n */\nexport interface RobotRockHandlerWebhookPayload {\n taskId: string;\n action: {\n id: string;\n title: string;\n data: unknown;\n };\n handledBy?: string;\n handledAt: string;\n handlerType: string;\n}\n\nexport function isRobotRockHandlerWebhookPayload(\n value: unknown\n): value is RobotRockHandlerWebhookPayload {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const v = value as Record<string, unknown>;\n if (typeof v.taskId !== \"string\" || typeof v.handledAt !== \"string\") {\n return false;\n }\n const action = v.action;\n if (typeof action !== \"object\" || action === null) {\n return false;\n }\n const a = action as Record<string, unknown>;\n return typeof a.id === \"string\" && \"data\" in a;\n}\n","/** Default wait when `validUntil` is omitted. */\nexport const DEFAULT_WAIT_DURATION_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function resolveWaitTiming(validUntilInput?: Date | string): {\n validUntil: Date | string;\n timeout: string;\n} {\n const validUntilMs =\n validUntilInput !== undefined\n ? parseValidUntilMs(validUntilInput)\n : Date.now() + DEFAULT_WAIT_DURATION_MS;\n\n const durationMs = validUntilMs - Date.now();\n if (durationMs <= 0) {\n throw new Error(\"validUntil must be in the future\");\n }\n\n return {\n validUntil: validUntilInput ?? new Date(validUntilMs),\n timeout: durationMsToTimeout(durationMs),\n };\n}\n\nexport function parseValidUntilMs(value: Date | string): number {\n if (value instanceof Date) {\n const ms = value.getTime();\n if (Number.isNaN(ms)) {\n throw new Error(\"Invalid validUntil: Date is invalid\");\n }\n return ms;\n }\n\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n throw new Error(\"Invalid validUntil: expected a parseable date string\");\n }\n\n return parsed;\n}\n\n/** Duration string for Trigger.dev `wait.createToken` and Workflow `sleep`. */\nexport function durationMsToTimeout(durationMs: number): string {\n const seconds = Math.ceil(durationMs / 1000);\n if (seconds <= 0) {\n throw new Error(\"validUntil must be in the future\");\n }\n\n if (seconds >= 86_400) {\n return `${Math.ceil(seconds / 86_400)}d`;\n }\n if (seconds >= 3_600) {\n return `${Math.ceil(seconds / 3_600)}h`;\n }\n if (seconds >= 60) {\n return `${Math.ceil(seconds / 60)}m`;\n }\n\n return `${seconds}s`;\n}\n","import type { DiscriminatedApprovalResult } from \"../schemas/index.js\";\nimport { task, wait } from \"@trigger.dev/sdk\";\nimport {\n createClient,\n type SendToHumanActionInput,\n type SendToHumanInput,\n} from \"../client.js\";\nimport { resolveRobotRockConfig } from \"../env.js\";\nimport { toDiscriminatedApprovalResult } from \"../approval-result.js\";\nimport {\n isRobotRockHandlerWebhookPayload,\n type RobotRockHandlerWebhookPayload,\n} from \"../handler-webhook.js\";\nimport { resolveWaitTiming } from \"../wait-timing.js\";\n\nexport type { RobotRockHandlerWebhookPayload } from \"../handler-webhook.js\";\n\nexport type SendToHumanPayload<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = SendToHumanInput<A> & {\n /** Inbox app bucket. Overrides `ROBOTROCK_APP` when set. */\n app?: string;\n};\n\nexport type ApproveByHumanPayload = Omit<SendToHumanPayload, \"actions\">;\n\ntype Expand<T> = T extends unknown ? { [K in keyof T]: T[K] } : never;\n\nconst APPROVE_BY_HUMAN_ACTIONS = [\n { id: \"approve\", title: \"Approve\" },\n { id: \"decline\", title: \"Decline\" },\n] as const;\n\nasync function runSendToHuman<const A extends readonly SendToHumanActionInput[]>(\n payload: SendToHumanPayload<A>\n): Promise<Expand<DiscriminatedApprovalResult<A>>> {\n const { validUntil: validUntilInput, ...taskInput } = payload;\n const { validUntil, timeout } = resolveWaitTiming(validUntilInput);\n\n const token = await wait.createToken({ timeout });\n\n const baseConfig = resolveRobotRockConfig();\n const client = createClient({\n apiKey: baseConfig.apiKey,\n baseUrl: baseConfig.baseUrl,\n ...(baseConfig.app ? { app: baseConfig.app } : {}),\n ...(baseConfig.version ? { version: baseConfig.version } : {}),\n webhook: { url: token.url },\n });\n\n const sendResult = await client.sendToHuman({\n ...taskInput,\n validUntil,\n });\n\n const outcome = await wait.forToken<RobotRockHandlerWebhookPayload>(token.id);\n\n if (!outcome.ok) {\n throw new Error(`Human response timed out before validUntil (${timeout})`);\n }\n\n const output = outcome.output;\n if (!isRobotRockHandlerWebhookPayload(output)) {\n throw new Error(\n \"Wait token completed with unexpected payload; expected RobotRock handler body (taskId, action.id, action.data).\"\n );\n }\n\n return toDiscriminatedApprovalResult(\n payload.actions,\n {\n id: output.taskId,\n createdAt: new Date(),\n status: \"handled\",\n context: sendResult.task.context,\n validUntil: Date.now(),\n handledAt: new Date(output.handledAt).getTime(),\n handled: {\n action: {\n id: output.action.id,\n data: output.action.data,\n },\n handledBy: output.handledBy,\n },\n }\n ) as unknown as Expand<DiscriminatedApprovalResult<A>>;\n}\n\n/**\n * Durable human-in-the-loop task for Trigger.dev.\n * Re-export from your `trigger/` directory so Trigger.dev discovers it on deploy.\n */\nexport const sendToHumanTask = task({\n id: \"robotrock/send-to-human\",\n run: async (payload: SendToHumanPayload) => runSendToHuman(payload),\n});\n\n/**\n * Simple approve/decline human gate for Trigger.dev.\n * Re-export from your `trigger/` directory so Trigger.dev discovers it on deploy.\n */\nexport const approveByHumanTask = task({\n id: \"robotrock/approve-by-human\",\n run: async (payload: ApproveByHumanPayload) =>\n runSendToHuman({\n ...payload,\n actions: APPROVE_BY_HUMAN_ACTIONS,\n }),\n});\n\nexport type {\n ApprovalResult,\n DiscriminatedApprovalResult,\n TaskContextInput,\n TaskResult,\n} from \"../schemas/index.js\";\n","import { createWebhook, sleep } from \"workflow\";\nimport type {\n DiscriminatedApprovalResult,\n ThreadUpdate,\n ThreadUpdateStatus,\n} from \"../schemas/index.js\";\nimport {\n createClient,\n type SendToHumanActionInput,\n type SendToHumanInput,\n} from \"../client.js\";\nimport { resolveRobotRockConfig } from \"../env.js\";\nimport { toDiscriminatedApprovalResult } from \"../approval-result.js\";\nimport {\n isRobotRockHandlerWebhookPayload,\n type RobotRockHandlerWebhookPayload,\n} from \"../handler-webhook.js\";\nimport { parseValidUntilMs, resolveWaitTiming } from \"../wait-timing.js\";\n\nexport type SendToHumanWorkflowPayload<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = SendToHumanInput<A> & {\n /** Inbox app bucket. Overrides `ROBOTROCK_APP` when set. */\n app?: string;\n};\n\nexport type ApproveByHumanWorkflowPayload = Omit<SendToHumanWorkflowPayload, \"actions\">;\n\ntype Expand<T> = T extends unknown ? { [K in keyof T]: T[K] } : never;\n\nconst APPROVE_BY_HUMAN_ACTIONS = [\n { id: \"approve\", title: \"Approve\" },\n { id: \"decline\", title: \"Decline\" },\n] as const;\n\ntype CreateTaskStepInput = {\n webhookUrl: string;\n app?: string;\n validUntil: Date | string;\n taskInput: Omit<SendToHumanWorkflowPayload, \"validUntil\" | \"app\">;\n};\n\n/**\n * Creates the RobotRock inbox task with the workflow webhook URL as the handler.\n * Marked as a step so API calls run in full Node.js with retries.\n */\nasync function createRobotRockTaskForWebhook(input: CreateTaskStepInput) {\n \"use step\";\n\n const baseConfig = resolveRobotRockConfig();\n const client = createClient({\n apiKey: baseConfig.apiKey,\n baseUrl: baseConfig.baseUrl,\n ...((input.app ?? baseConfig.app) ? { app: input.app ?? baseConfig.app } : {}),\n ...(baseConfig.version ? { version: baseConfig.version } : {}),\n webhook: { url: input.webhookUrl },\n });\n\n return client.sendToHuman({\n ...input.taskInput,\n validUntil: input.validUntil,\n });\n}\n\nasync function parseRobotRockWebhookRequest(request: Request) {\n \"use step\";\n\n const body: unknown = await request.json();\n if (!isRobotRockHandlerWebhookPayload(body)) {\n throw new Error(\n \"Workflow webhook completed with unexpected payload; expected RobotRock handler body (taskId, action.id, action.data).\"\n );\n }\n\n return body;\n}\n\n/**\n * Durable human-in-the-loop wait for Vercel Workflow.\n *\n * Call from a function with `\"use workflow\"` as its first statement. Creates a\n * {@link createWebhook} URL, registers it as the RobotRock task webhook, and\n * suspends until a human handles an action or `validUntil` passes.\n */\nexport async function sendToHumanInWorkflow<\n const A extends readonly SendToHumanActionInput[],\n>(\n payload: SendToHumanWorkflowPayload<A>\n): Promise<Expand<DiscriminatedApprovalResult<A>>> {\n const { validUntil: validUntilInput, app, ...taskInput } = payload;\n const { validUntil, timeout } = resolveWaitTiming(validUntilInput);\n const timeoutMs = parseValidUntilMs(validUntil) - Date.now();\n\n using webhook = createWebhook();\n\n const sendResult = await createRobotRockTaskForWebhook({\n webhookUrl: webhook.url,\n app,\n validUntil,\n taskInput,\n });\n\n const outcome = await Promise.race([\n webhook.then((request) => parseRobotRockWebhookRequest(request)),\n sleep(timeoutMs).then(() => ({ timedOut: true }) as const),\n ]);\n\n if (\"timedOut\" in outcome) {\n throw new Error(`Human response timed out before validUntil (${timeout})`);\n }\n\n const output: RobotRockHandlerWebhookPayload = outcome;\n\n return toDiscriminatedApprovalResult(payload.actions, {\n id: output.taskId,\n createdAt: new Date(),\n status: \"handled\",\n context: sendResult.task.context,\n validUntil: Date.now(),\n handledAt: new Date(output.handledAt).getTime(),\n handled: {\n action: {\n id: output.action.id,\n data: output.action.data,\n },\n handledBy: output.handledBy,\n },\n }) as unknown as Expand<DiscriminatedApprovalResult<A>>;\n}\n\n/**\n * Approve / decline gate for Vercel Workflow (`sendToHumanInWorkflow` with fixed actions).\n */\nexport async function approveByHumanInWorkflow(\n payload: ApproveByHumanWorkflowPayload\n): Promise<Expand<DiscriminatedApprovalResult<typeof APPROVE_BY_HUMAN_ACTIONS>>> {\n return sendToHumanInWorkflow({\n ...payload,\n actions: APPROVE_BY_HUMAN_ACTIONS,\n });\n}\n\nexport type SendUpdateWorkflowPayload = {\n /** Thread to log the update against (from a prior task's `threadId`). */\n threadId: string;\n /** Short status update (1-2 sentences) shown in the inbox status bar. */\n message: string;\n /** Lifecycle status driving the status-bar icon/color. @default \"info\" */\n status?: ThreadUpdateStatus;\n /** Inbox app bucket. Overrides `ROBOTROCK_APP` when set. */\n app?: string;\n};\n\n/**\n * Posts a thread update via `client.sendUpdate()`. Marked as a step so the API\n * call runs in full Node.js with retries and is recorded in the workflow run.\n */\nasync function sendRobotRockUpdate(payload: SendUpdateWorkflowPayload): Promise<ThreadUpdate> {\n \"use step\";\n\n const { app, ...update } = payload;\n const baseConfig = resolveRobotRockConfig();\n const client = createClient({\n apiKey: baseConfig.apiKey,\n baseUrl: baseConfig.baseUrl,\n ...((app ?? baseConfig.app) ? { app: app ?? baseConfig.app } : {}),\n ...(baseConfig.version ? { version: baseConfig.version } : {}),\n });\n\n return client.sendUpdate(update);\n}\n\n/**\n * Durable thread update for Vercel Workflow.\n *\n * Wraps {@link createClient}'s `sendUpdate` in a `\"use step\"` so progress\n * reports are retried and recorded in the run. Fire-and-forget: returns the\n * created update without suspending the workflow (no human wait involved).\n *\n * Call from a function with `\"use workflow\"` as its first statement.\n */\nexport async function sendUpdateInWorkflow(\n payload: SendUpdateWorkflowPayload\n): Promise<ThreadUpdate> {\n return sendRobotRockUpdate(payload);\n}\n\nexport type { RobotRockHandlerWebhookPayload } from \"../handler-webhook.js\";\nexport type {\n ApprovalResult,\n DiscriminatedApprovalResult,\n TaskContextInput,\n TaskResult,\n ThreadUpdate,\n ThreadUpdateStatus,\n} from \"../schemas/index.js\";\n","import { z } from \"zod\";\nimport type { RobotRock } from \"../client.js\";\nimport {\n approveByHumanForAi,\n normalizeRobotRockAiContext,\n type RobotRockAiContext,\n} from \"./context.js\";\nimport { toHumanToolResult } from \"./human-tool-result.js\";\nimport type { HumanToolResult } from \"./types.js\";\n\nexport const APPROVE_BY_HUMAN_ACTIONS = [\n { id: \"approve\", title: \"Approve\" },\n { id: \"decline\", title: \"Decline\" },\n] as const;\n\nexport const approveByHumanInputSchema = z.object({\n type: z\n .string()\n .optional()\n .describe(\"Task type slug; defaults to ai-approval\"),\n name: z.string().describe(\"Short title for the approval request\"),\n description: z\n .string()\n .describe(\"What needs approval and the consequences of approving or declining\"),\n contextSummary: z\n .string()\n .optional()\n .describe(\"Optional markdown summary shown to the reviewer\"),\n});\n\nexport type ApproveByHumanToolInput = z.infer<typeof approveByHumanInputSchema>;\n\nexport type ApproveByHumanToolOptions = {\n defaultType?: string;\n description?: string;\n toolName?: string;\n};\n\nexport type ApproveByHumanToolDurableOptions = ApproveByHumanToolOptions &\n RobotRockAiContext & { mode: \"trigger\" | \"workflow\" };\n\nexport type ApproveByHumanToolDefinition = {\n description: string;\n inputSchema: typeof approveByHumanInputSchema;\n execute: (input: ApproveByHumanToolInput) => Promise<HumanToolResult>;\n};\n\nfunction resolveApproveByHumanToolConfig(\n clientOrContext: RobotRock | ApproveByHumanToolDurableOptions,\n maybeOptions: ApproveByHumanToolOptions = {}\n): {\n aiContext: RobotRockAiContext;\n options: ApproveByHumanToolOptions;\n} {\n const isDurable =\n typeof clientOrContext === \"object\" &&\n clientOrContext !== null &&\n \"mode\" in clientOrContext &&\n (clientOrContext.mode === \"trigger\" || clientOrContext.mode === \"workflow\");\n\n const aiContext = normalizeRobotRockAiContext(\n isDurable\n ? {\n mode: (clientOrContext as ApproveByHumanToolDurableOptions).mode,\n app: (clientOrContext as ApproveByHumanToolDurableOptions).app,\n }\n : (clientOrContext as RobotRock)\n );\n const options = isDurable\n ? (clientOrContext as ApproveByHumanToolDurableOptions)\n : maybeOptions;\n\n return { aiContext, options };\n}\n\n/**\n * Plain tool definition for Vercel Workflow and DurableAgent (no `tool()` from the AI SDK).\n */\nexport function buildApproveByHumanToolDefinition(\n clientOrContext: RobotRock | ApproveByHumanToolDurableOptions,\n maybeOptions: ApproveByHumanToolOptions = {}\n): ApproveByHumanToolDefinition {\n const { aiContext, options } = resolveApproveByHumanToolConfig(\n clientOrContext,\n maybeOptions\n );\n const description =\n options.description ??\n \"Request explicit human approval before a sensitive or irreversible step. Returns whether the human approved or declined.\";\n\n return {\n description,\n inputSchema: approveByHumanInputSchema,\n execute: async (input: ApproveByHumanToolInput): Promise<HumanToolResult> => {\n const taskContext =\n input.contextSummary !== undefined\n ? {\n data: { summary: input.contextSummary },\n ui: {\n summary: { \"ui:widget\": \"textarea\", \"ui:options\": { rows: 6 } },\n },\n }\n : undefined;\n\n const result = await approveByHumanForAi(aiContext, {\n type: input.type ?? options.defaultType ?? \"ai-approval\",\n name: input.name,\n description: input.description,\n context: taskContext,\n });\n\n return toHumanToolResult(result);\n },\n };\n}\n","import {\n createClient,\n type RobotRock,\n type SendToHumanActionInput,\n type SendToHumanInput,\n type SendUpdateInput,\n} from \"../client.js\";\nimport { resolveRobotRockConfig } from \"../env.js\";\nimport type { DiscriminatedApprovalResult, ThreadUpdate } from \"../schemas/index.js\";\nconst APPROVE_BY_HUMAN_ACTIONS = [\n { id: \"approve\", title: \"Approve\" },\n { id: \"decline\", title: \"Decline\" },\n] as const;\n\n/** How RobotRock waits for a human inside AI SDK tool `execute`. */\nexport type RobotRockAiMode = \"polling\" | \"trigger\" | \"workflow\";\n\n/**\n * Polling: `client.sendToHuman()` blocks until handled (scripts, API routes with long timeout).\n * Trigger: `sendToHumanTask.triggerAndWait()` uses wait tokens (Trigger.dev workers).\n * Workflow: `sendToHumanInWorkflow()` uses workflow webhooks (Vercel Workflow).\n */\nexport type RobotRockAiPollingContext = {\n mode?: \"polling\";\n client: RobotRock;\n};\n\nexport type RobotRockAiTriggerContext = {\n mode: \"trigger\";\n /** Inbox app bucket; falls back to `ROBOTROCK_APP` in the Trigger worker. */\n app?: string;\n};\n\nexport type RobotRockAiWorkflowContext = {\n mode: \"workflow\";\n /** Inbox app bucket; falls back to `ROBOTROCK_APP` in the workflow run. */\n app?: string;\n};\n\nexport type RobotRockAiContext =\n | RobotRockAiPollingContext\n | RobotRockAiTriggerContext\n | RobotRockAiWorkflowContext;\n\n/** Shorthand for `{ mode: \"trigger\", app }`. */\nexport function createRobotRockAiTriggerContext(\n options: Omit<RobotRockAiTriggerContext, \"mode\"> = {}\n): RobotRockAiContext {\n return { mode: \"trigger\", ...options };\n}\n\n/** Shorthand for `{ mode: \"workflow\", app }`. */\nexport function createRobotRockAiWorkflowContext(\n options: Omit<RobotRockAiWorkflowContext, \"mode\"> = {}\n): RobotRockAiContext {\n return { mode: \"workflow\", ...options };\n}\n\nexport function isRobotRockClient(value: unknown): value is RobotRock {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"sendToHuman\" in value &&\n typeof (value as RobotRock).sendToHuman === \"function\"\n );\n}\n\nexport function normalizeRobotRockAiContext(\n clientOrContext: RobotRock | RobotRockAiContext\n): RobotRockAiContext {\n if (isRobotRockClient(clientOrContext)) {\n return { mode: \"polling\", client: clientOrContext };\n }\n\n if (clientOrContext.mode === \"trigger\" || clientOrContext.mode === \"workflow\") {\n return clientOrContext;\n }\n\n if (clientOrContext.mode === \"polling\" || clientOrContext.mode === undefined) {\n if (!(\"client\" in clientOrContext) || !clientOrContext.client) {\n throw new Error('RobotRock AI polling mode requires `client` on the context object.');\n }\n return { mode: \"polling\", client: clientOrContext.client };\n }\n\n throw new Error(`Unknown RobotRock AI mode: ${String((clientOrContext as { mode?: string }).mode)}`);\n}\n\nexport async function sendToHumanForAi<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n>(\n context: RobotRockAiContext,\n payload: SendToHumanInput<A>\n): Promise<DiscriminatedApprovalResult<A>> {\n if (context.mode === \"trigger\") {\n const { sendToHumanTask } = await import(\"../trigger/index.js\");\n const waitResult = await sendToHumanTask.triggerAndWait({\n ...payload,\n ...(context.app ? { app: context.app } : {}),\n });\n\n if (!waitResult.ok) {\n throw waitResult.error;\n }\n\n return waitResult.output as DiscriminatedApprovalResult<A>;\n }\n\n if (context.mode === \"workflow\") {\n const { sendToHumanInWorkflow } = await import(\"../workflow/index.js\");\n const result = await sendToHumanInWorkflow({\n ...payload,\n ...(context.app ? { app: context.app } : {}),\n });\n return result as unknown as DiscriminatedApprovalResult<A>;\n }\n\n const result = await context.client.sendToHuman(payload);\n\n if (result.mode !== \"handled\") {\n throw new Error(\n \"RobotRock task was created but not handled. Configure client polling or webhook, or use mode: 'trigger' / 'workflow' for durable waits.\"\n );\n }\n\n return {\n actionId: result.actionId,\n data: result.data,\n handledBy: result.handledBy,\n handledAt: result.handledAt,\n taskId: result.taskId,\n } as DiscriminatedApprovalResult<A>;\n}\n\n/**\n * Posts a thread update for an AI tool, routing by execution mode.\n *\n * `sendUpdate` is fire-and-forget (no human wait), so only the workflow path\n * needs durability — it runs inside a `\"use step\"`. Trigger and polling modes\n * issue the request directly.\n */\nexport async function sendUpdateForAi(\n context: RobotRockAiContext,\n payload: SendUpdateInput\n): Promise<ThreadUpdate> {\n if (context.mode === \"workflow\") {\n const { sendUpdateInWorkflow } = await import(\"../workflow/index.js\");\n return sendUpdateInWorkflow({\n ...payload,\n ...(context.app ? { app: context.app } : {}),\n });\n }\n\n if (context.mode === \"trigger\") {\n const client = createClient(\n resolveRobotRockConfig(context.app ? { app: context.app } : undefined)\n );\n return client.sendUpdate(payload);\n }\n\n return context.client.sendUpdate(payload);\n}\n\nexport async function approveByHumanForAi(\n context: RobotRockAiContext,\n payload: Omit<SendToHumanInput, \"actions\"> & { app?: string }\n): Promise<DiscriminatedApprovalResult<typeof APPROVE_BY_HUMAN_ACTIONS>> {\n if (context.mode === \"trigger\") {\n const { approveByHumanTask } = await import(\"../trigger/index.js\");\n const waitResult = await approveByHumanTask.triggerAndWait({\n ...payload,\n ...(context.app ? { app: context.app } : {}),\n });\n\n if (!waitResult.ok) {\n throw waitResult.error;\n }\n\n return waitResult.output;\n }\n\n if (context.mode === \"workflow\") {\n const { approveByHumanInWorkflow } = await import(\"../workflow/index.js\");\n return await approveByHumanInWorkflow({\n ...payload,\n ...(context.app ? { app: context.app } : {}),\n });\n }\n\n const result = await context.client.sendToHuman({\n ...payload,\n actions: APPROVE_BY_HUMAN_ACTIONS,\n });\n\n if (result.mode !== \"handled\") {\n throw new Error(\n \"RobotRock approval was not handled. Configure client polling or use mode: 'trigger' / 'workflow' for durable waits.\"\n );\n }\n\n return {\n actionId: result.actionId,\n data: result.data,\n handledBy: result.handledBy,\n handledAt: result.handledAt,\n taskId: result.taskId,\n } as DiscriminatedApprovalResult<typeof APPROVE_BY_HUMAN_ACTIONS>;\n}\n","import type { DiscriminatedApprovalResult } from \"../schemas/index.js\";\nimport type { HumanToolResult } from \"./types.js\";\n\nconst APPROVE_IDS = new Set([\"approve\", \"approved\"]);\nconst DECLINE_IDS = new Set([\"decline\", \"reject\", \"deny\", \"denied\"]);\n\nexport function toHumanToolResult(\n result: DiscriminatedApprovalResult<readonly { id: string }[]>\n): HumanToolResult {\n const payload: HumanToolResult = {\n taskId: result.taskId,\n actionId: result.actionId,\n data: result.data,\n handledBy: result.handledBy,\n handledAt: result.handledAt.toISOString(),\n };\n\n if (APPROVE_IDS.has(result.actionId)) {\n payload.approved = true;\n } else if (DECLINE_IDS.has(result.actionId)) {\n payload.approved = false;\n }\n\n return payload;\n}\n","import { z } from \"zod\";\nimport { assignToSchema } from \"../schemas/index.js\";\nimport type { RobotRock, SendToHumanActionInput, SendToHumanInput } from \"../client.js\";\nimport type { TaskContextInput } from \"../schemas/index.js\";\nimport {\n normalizeRobotRockAiContext,\n sendToHumanForAi,\n type RobotRockAiContext,\n} from \"./context.js\";\nimport { toHumanToolResult } from \"./human-tool-result.js\";\nimport type { HumanToolResult } from \"./types.js\";\n\nexport const sendToHumanToolInputSchema = z.object({\n type: z.string().describe(\"Task type slug shown in the RobotRock inbox\"),\n name: z.string().describe(\"Short title for the human reviewer\"),\n description: z\n .string()\n .optional()\n .describe(\"What you need from the human and why you cannot proceed alone\"),\n context: z\n .object({\n data: z.record(z.string(), z.unknown()).optional(),\n ui: z.record(z.string(), z.unknown()).optional(),\n })\n .optional()\n .describe(\"Optional structured context for the inbox UI\"),\n validUntil: z\n .string()\n .datetime()\n .optional()\n .describe(\"Optional ISO deadline for the task\"),\n assignTo: assignToSchema\n .optional()\n .describe(\n \"Assign to tenant member emails and/or group slugs; narrows who sees the task in the inbox\"\n ),\n});\n\nexport type SendToHumanToolInput = z.infer<typeof sendToHumanToolInputSchema>;\n\nexport type CreateSendToHumanToolOptions<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = {\n actions: A;\n defaultType?: string;\n description?: string;\n toolName?: string;\n /**\n * Group every task this tool creates onto a shared thread. Pass the same\n * value to {@link createSendUpdateTool} so updates land on the same thread.\n */\n threadId?: string;\n};\n\nexport type CreateSendToHumanToolDurableOptions<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n> = CreateSendToHumanToolOptions<A> & RobotRockAiContext & { mode: \"trigger\" | \"workflow\" };\n\nexport type SendToHumanToolDefinition = {\n description: string;\n inputSchema: typeof sendToHumanToolInputSchema;\n execute: (input: SendToHumanToolInput) => Promise<HumanToolResult>;\n};\n\nfunction resolveSendToHumanToolConfig<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n>(\n clientOrOptions: RobotRock | CreateSendToHumanToolDurableOptions<A>,\n maybeOptions?: CreateSendToHumanToolOptions<A>\n): {\n aiContext: RobotRockAiContext;\n options: CreateSendToHumanToolOptions<A>;\n} {\n const isDurable =\n typeof clientOrOptions === \"object\" &&\n clientOrOptions !== null &&\n \"mode\" in clientOrOptions &&\n (clientOrOptions.mode === \"trigger\" || clientOrOptions.mode === \"workflow\");\n\n const aiContext = normalizeRobotRockAiContext(\n isDurable\n ? {\n mode: (clientOrOptions as CreateSendToHumanToolDurableOptions<A>).mode,\n app: (clientOrOptions as CreateSendToHumanToolDurableOptions<A>).app,\n }\n : (clientOrOptions as RobotRock)\n );\n const options = (isDurable ? clientOrOptions : maybeOptions!) as CreateSendToHumanToolOptions<A>;\n\n return { aiContext, options };\n}\n\n/**\n * Plain tool definition for Vercel Workflow and DurableAgent (no `tool()` from the AI SDK).\n */\nexport function buildSendToHumanToolDefinition<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n>(\n clientOrOptions: RobotRock | CreateSendToHumanToolDurableOptions<A>,\n maybeOptions?: CreateSendToHumanToolOptions<A>\n): SendToHumanToolDefinition {\n const { aiContext, options } = resolveSendToHumanToolConfig(clientOrOptions, maybeOptions);\n const description =\n options.description ??\n \"Request structured input or a decision from a human in the RobotRock inbox. Use when you lack required information, need policy approval, or must confirm an irreversible step.\";\n\n return {\n description,\n inputSchema: sendToHumanToolInputSchema,\n execute: async (input: SendToHumanToolInput): Promise<HumanToolResult> => {\n const taskContext: TaskContextInput[\"context\"] | undefined = input.context\n ? ({\n data: input.context.data ?? {},\n ui: input.context.ui,\n } as TaskContextInput[\"context\"])\n : undefined;\n\n const payload: SendToHumanInput<A> = {\n type: input.type ?? options.defaultType ?? \"ai-human-input\",\n name: input.name,\n description: input.description,\n context: taskContext,\n validUntil: input.validUntil,\n assignTo: input.assignTo,\n actions: options.actions,\n ...(options.threadId ? { threadId: options.threadId } : {}),\n };\n\n const result = await sendToHumanForAi(aiContext, payload);\n\n return toHumanToolResult(result);\n },\n };\n}\n","import { z } from \"zod\";\nimport { threadUpdateStatusSchema } from \"../schemas/index.js\";\nimport { RobotRockError, type RobotRock } from \"../client.js\";\nimport type { ThreadUpdate } from \"../schemas/index.js\";\nimport {\n normalizeRobotRockAiContext,\n sendUpdateForAi,\n type RobotRockAiContext,\n} from \"./context.js\";\n\n/**\n * Result returned to the model by {@link createSendUpdateTool}.\n *\n * Updates are fire-and-forget, so a missing thread (no task created yet) is\n * reported as `{ posted: false }` instead of throwing — that way an agent loop\n * is never aborted by a non-critical progress update. Genuine failures (auth,\n * validation, server errors) still throw.\n */\nexport type SendUpdateToolResult =\n | { posted: true; threadId: string; update: ThreadUpdate }\n | {\n posted: false;\n threadId: string;\n reason: \"thread_not_found\";\n message: string;\n };\n\nexport const sendUpdateToolInputSchema = z.object({\n threadId: z\n .string()\n .optional()\n .describe(\n \"Thread to post the update to. Use the `threadId` returned by a prior send-to-human task. Omit only when a session threadId is configured on the tool.\"\n ),\n message: z\n .string()\n .describe(\"Short progress update (1-2 sentences) shown in the inbox status bar\"),\n status: threadUpdateStatusSchema\n .optional()\n .describe(\n \"Lifecycle status driving the status-bar icon/color: info, queued, running, waiting, succeeded, failed, cancelled\"\n ),\n});\n\nexport type SendUpdateToolInput = z.infer<typeof sendUpdateToolInputSchema>;\n\nexport type CreateSendUpdateToolOptions = {\n /**\n * Session thread to post updates to when the model does not supply `threadId`.\n * Pass the same value to {@link createSendToHumanTool} to auto-thread tasks\n * and updates together.\n */\n threadId?: string;\n description?: string;\n};\n\nexport type CreateSendUpdateToolDurableOptions = CreateSendUpdateToolOptions &\n RobotRockAiContext & { mode: \"trigger\" | \"workflow\" };\n\nexport type SendUpdateToolDefinition = {\n description: string;\n inputSchema: typeof sendUpdateToolInputSchema;\n execute: (input: SendUpdateToolInput) => Promise<SendUpdateToolResult>;\n};\n\nfunction resolveSendUpdateToolConfig(\n clientOrOptions: RobotRock | CreateSendUpdateToolDurableOptions,\n maybeOptions: CreateSendUpdateToolOptions = {}\n): {\n aiContext: RobotRockAiContext;\n options: CreateSendUpdateToolOptions;\n} {\n const isDurable =\n typeof clientOrOptions === \"object\" &&\n clientOrOptions !== null &&\n \"mode\" in clientOrOptions &&\n (clientOrOptions.mode === \"trigger\" || clientOrOptions.mode === \"workflow\");\n\n const aiContext = normalizeRobotRockAiContext(\n isDurable\n ? {\n mode: (clientOrOptions as CreateSendUpdateToolDurableOptions).mode,\n app: (clientOrOptions as CreateSendUpdateToolDurableOptions).app,\n }\n : (clientOrOptions as RobotRock)\n );\n const options = isDurable\n ? (clientOrOptions as CreateSendUpdateToolDurableOptions)\n : maybeOptions;\n\n return { aiContext, options };\n}\n\n/**\n * Plain tool definition for Vercel Workflow and DurableAgent (no `tool()` from the AI SDK).\n */\nexport function buildSendUpdateToolDefinition(\n clientOrOptions: RobotRock | CreateSendUpdateToolDurableOptions,\n maybeOptions: CreateSendUpdateToolOptions = {}\n): SendUpdateToolDefinition {\n const { aiContext, options } = resolveSendUpdateToolConfig(clientOrOptions, maybeOptions);\n const description =\n options.description ??\n \"Post a short progress update to the RobotRock thread you are working on. Use to report status changes (running, succeeded, failed) so humans can follow along in the inbox.\";\n\n return {\n description,\n inputSchema: sendUpdateToolInputSchema,\n execute: async (input: SendUpdateToolInput): Promise<SendUpdateToolResult> => {\n const threadId = input.threadId ?? options.threadId;\n if (!threadId) {\n throw new Error(\n \"createSendUpdateTool: no threadId. Pass `threadId` from a prior send-to-human result, or configure a session `threadId` in the tool options.\"\n );\n }\n\n try {\n const update = await sendUpdateForAi(aiContext, {\n threadId,\n message: input.message,\n status: input.status,\n });\n return { posted: true, threadId, update };\n } catch (error) {\n if (error instanceof RobotRockError && error.statusCode === 404) {\n return {\n posted: false,\n threadId,\n reason: \"thread_not_found\",\n message: `No task exists for thread \"${threadId}\" yet, so the update was not posted. Create a task on this thread with send-to-human before reporting progress.`,\n };\n }\n throw error;\n }\n },\n };\n}\n","import type { RobotRock, SendToHumanActionInput } from \"../client.js\";\nimport {\n buildApproveByHumanToolDefinition,\n type ApproveByHumanToolDurableOptions,\n type ApproveByHumanToolOptions,\n} from \"./approve-by-human-tool-core.js\";\nimport {\n buildSendToHumanToolDefinition,\n type CreateSendToHumanToolDurableOptions,\n type CreateSendToHumanToolOptions,\n} from \"./create-send-to-human-tool-core.js\";\nimport {\n buildSendUpdateToolDefinition,\n type CreateSendUpdateToolDurableOptions,\n type CreateSendUpdateToolOptions,\n} from \"./create-send-update-tool-core.js\";\nimport type { RobotRockAiWorkflowContext } from \"./context.js\";\n\n/**\n * Workflow-safe approve/decline tool for `generateText`, `DurableAgent`, and similar.\n * Returns a plain `{ description, inputSchema, execute }` object — no AI SDK `tool()` helper.\n */\nexport function approveByHumanTool(\n clientOrContext: RobotRock | ApproveByHumanToolDurableOptions,\n maybeOptions: ApproveByHumanToolOptions = {}\n) {\n return buildApproveByHumanToolDefinition(clientOrContext, maybeOptions);\n}\n\n/**\n * Workflow-safe send-to-human tool. See {@link approveByHumanTool} for usage notes.\n */\nexport function createSendToHumanTool<\n A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[],\n>(\n clientOrOptions: RobotRock | CreateSendToHumanToolDurableOptions<A>,\n maybeOptions?: CreateSendToHumanToolOptions<A>\n) {\n return buildSendToHumanToolDefinition(clientOrOptions, maybeOptions);\n}\n\n/**\n * Workflow-safe send-update tool. See {@link approveByHumanTool} for usage notes.\n */\nexport function createSendUpdateTool(\n clientOrOptions: RobotRock | CreateSendUpdateToolDurableOptions,\n maybeOptions: CreateSendUpdateToolOptions = {}\n) {\n return buildSendUpdateToolDefinition(clientOrOptions, maybeOptions);\n}\n\nexport type CreateRobotRockAiWorkflowToolsOptions = {\n app?: string;\n threadId?: string;\n};\n\nexport function createRobotRockAiTools(options: CreateRobotRockAiWorkflowToolsOptions = {}) {\n const context: RobotRockAiWorkflowContext = { mode: \"workflow\", app: options.app };\n\n return {\n context,\n approveByHuman: (toolOptions?: ApproveByHumanToolOptions) =>\n buildApproveByHumanToolDefinition({ ...context, ...toolOptions }),\n sendToHuman: <A extends readonly SendToHumanActionInput[]>(\n toolOptions: CreateSendToHumanToolOptions<A>\n ) =>\n buildSendToHumanToolDefinition({\n ...context,\n ...(options.threadId ? { threadId: options.threadId } : {}),\n ...toolOptions,\n }),\n sendUpdate: (toolOptions: CreateSendUpdateToolOptions = {}) =>\n buildSendUpdateToolDefinition({\n ...context,\n ...(options.threadId ? { threadId: options.threadId } : {}),\n ...toolOptions,\n }),\n };\n}\n","import type { SendToHumanInput } from \"../client.js\";\nimport type { FormatToolApprovalTaskOptions, RobotRockToolCallInfo } from \"./types.js\";\n\nconst DEFAULT_APPROVE_ACTIONS = [\n { id: \"approve\", title: \"Approve execution\" },\n { id: \"deny\", title: \"Deny\" },\n] as const;\n\n/**\n * Build a RobotRock task payload for an AI SDK tool approval request.\n */\nexport function defaultFormatToolApprovalTask(\n toolCall: RobotRockToolCallInfo,\n options: FormatToolApprovalTaskOptions = {}\n): SendToHumanInput {\n const approveId = options.approveActionId ?? \"approve\";\n const denyId = options.denyActionId ?? \"deny\";\n\n let inputPreview: string;\n try {\n inputPreview = JSON.stringify(toolCall.input, null, 2);\n } catch {\n inputPreview = String(toolCall.input);\n }\n\n return {\n type: options.type ?? \"ai-tool-approval\",\n name: `Approve: ${toolCall.toolName}`,\n description: `Review the proposed \\`${toolCall.toolName}\\` tool call before it runs.`,\n context: {\n data: {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n input: toolCall.input,\n },\n ui: {\n toolName: { \"ui:widget\": \"text\" },\n toolCallId: { \"ui:widget\": \"text\" },\n input: { \"ui:widget\": \"textarea\" },\n },\n },\n actions: [\n { id: approveId, title: \"Approve execution\" },\n { id: denyId, title: \"Deny\" },\n ],\n };\n}\n\nexport { DEFAULT_APPROVE_ACTIONS };\n","import type { ToolApprovalResponse } from \"ai\";\nimport type { RobotRock } from \"../client.js\";\nimport {\n normalizeRobotRockAiContext,\n sendToHumanForAi,\n type RobotRockAiContext,\n} from \"./context.js\";\nimport { defaultFormatToolApprovalTask } from \"./format-tool-approval-task.js\";\nimport type {\n ResolveToolApprovalsOptions,\n RobotRockToolApprovalConfig,\n RobotRockToolCallInfo,\n RunWithRobotRockApprovalsOptions,\n ToolApprovalRequestPart,\n} from \"./types.js\";\n\nexport type RobotRockToolApprovalDecision = \"user-approval\" | undefined;\n\nfunction buildToolMatcher(config: RobotRockToolApprovalConfig) {\n const names = config.tools ? new Set(config.tools) : null;\n\n return (toolCall: RobotRockToolCallInfo): boolean => {\n if (config.when?.(toolCall)) {\n return true;\n }\n if (names && names.has(toolCall.toolName)) {\n return true;\n }\n return false;\n };\n}\n\n/**\n * AI SDK 7+: pass the return value to `toolApproval` on `generateText`, `streamText`, or `ToolLoopAgent`.\n * Returns `'user-approval'` for configured tools so execution pauses until a human responds via RobotRock.\n */\nexport function createRobotRockToolApproval(config: RobotRockToolApprovalConfig) {\n const matches = buildToolMatcher(config);\n\n const toolApproval = async (options: {\n toolCall: RobotRockToolCallInfo;\n }): Promise<RobotRockToolApprovalDecision> => {\n return matches(options.toolCall) ? \"user-approval\" : undefined;\n };\n\n return toolApproval;\n}\n\n/**\n * AI SDK 5–6: use as `needsApproval` on tool definitions (or via {@link applyRobotRockToolApprovalToTools}).\n */\nexport function createRobotRockNeedsApproval(config: RobotRockToolApprovalConfig) {\n const matches = buildToolMatcher(config);\n\n return async (\n _input: unknown,\n options: { toolCallId: string; messages?: unknown[] }\n ): Promise<boolean> => {\n const toolCall = findToolCallInMessages(options.messages, options.toolCallId);\n if (!toolCall) {\n return false;\n }\n return matches(toolCall);\n };\n}\n\n/**\n * AI SDK 5–6: merge `needsApproval` into each matching tool in a tools object.\n */\nexport function applyRobotRockToolApprovalToTools<T extends Record<string, object>>(\n tools: T,\n config: RobotRockToolApprovalConfig\n): T {\n const names = config.tools ? new Set(config.tools) : null;\n const needsApproval = createRobotRockNeedsApproval(config);\n\n const next = { ...tools } as T;\n\n for (const key of Object.keys(tools) as Array<keyof T>) {\n const name = String(key);\n const shouldApply =\n (names && names.has(name)) || (names === null && config.when !== undefined);\n\n if (!shouldApply) {\n continue;\n }\n\n const existing = tools[key];\n next[key] = {\n ...existing,\n needsApproval,\n } as T[keyof T];\n }\n\n return next;\n}\n\nfunction findToolCallInMessages(\n messages: unknown[] | undefined,\n toolCallId: string\n): RobotRockToolCallInfo | undefined {\n if (!messages) {\n return undefined;\n }\n\n for (const message of messages) {\n if (typeof message !== \"object\" || message === null) {\n continue;\n }\n const role = (message as { role?: string }).role;\n if (role !== \"assistant\") {\n continue;\n }\n const content = (message as { content?: unknown }).content;\n if (!Array.isArray(content)) {\n continue;\n }\n\n for (const part of content) {\n if (typeof part !== \"object\" || part === null) {\n continue;\n }\n const p = part as Record<string, unknown>;\n if (p.type === \"tool-call\" && p.toolCallId === toolCallId) {\n return {\n toolName: String(p.toolName ?? \"\"),\n toolCallId,\n input: p.input,\n };\n }\n }\n }\n\n return undefined;\n}\n\nfunction collectApprovalRequests(source: unknown): ToolApprovalRequestPart[] {\n const requests: ToolApprovalRequestPart[] = [];\n\n const visit = (value: unknown) => {\n if (!value) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n visit(item);\n }\n return;\n }\n\n if (typeof value !== \"object\") {\n return;\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj.type === \"tool-approval-request\" && typeof obj.approvalId === \"string\") {\n if (obj.isAutomatic === true) {\n return;\n }\n\n const embedded = obj.toolCall as Record<string, unknown> | undefined;\n const toolCallId =\n typeof obj.toolCallId === \"string\"\n ? obj.toolCallId\n : typeof embedded?.toolCallId === \"string\"\n ? embedded.toolCallId\n : undefined;\n\n let toolCall: RobotRockToolCallInfo | undefined;\n if (embedded && typeof embedded.toolName === \"string\") {\n toolCall = {\n toolName: embedded.toolName,\n toolCallId: String(embedded.toolCallId ?? toolCallId ?? \"\"),\n input: embedded.input,\n };\n } else if (toolCallId) {\n toolCall = findToolCallInMessages(\n (source as { messages?: unknown[] }).messages,\n toolCallId\n );\n }\n\n requests.push({\n type: \"tool-approval-request\",\n approvalId: obj.approvalId,\n toolCallId,\n toolCall,\n isAutomatic: obj.isAutomatic === true,\n });\n return;\n }\n\n if (Array.isArray(obj.content)) {\n visit(obj.content);\n }\n if (Array.isArray(obj.steps)) {\n visit(obj.steps);\n }\n if (obj.response && typeof obj.response === \"object\") {\n visit((obj.response as { messages?: unknown[] }).messages);\n }\n };\n\n visit(source);\n\n if (typeof source === \"object\" && source !== null && Array.isArray((source as { content?: unknown[] }).content)) {\n visit((source as { content: unknown[] }).content);\n }\n\n const seen = new Set<string>();\n return requests.filter((r) => {\n if (seen.has(r.approvalId)) {\n return false;\n }\n seen.add(r.approvalId);\n return true;\n });\n}\n\nfunction resolveToolCallForRequest(\n request: ToolApprovalRequestPart,\n source: unknown,\n messages: unknown[]\n): RobotRockToolCallInfo {\n if (request.toolCall) {\n return request.toolCall;\n }\n\n const toolCallId = request.toolCallId;\n if (toolCallId) {\n const fromMessages = findToolCallInMessages(messages, toolCallId);\n if (fromMessages) {\n return fromMessages;\n }\n }\n\n if (typeof source === \"object\" && source !== null && Array.isArray((source as { toolCalls?: unknown[] }).toolCalls)) {\n for (const call of (source as { toolCalls: Array<Record<string, unknown>> }).toolCalls) {\n if (call.toolCallId === toolCallId) {\n return {\n toolName: String(call.toolName ?? \"\"),\n toolCallId: String(call.toolCallId ?? \"\"),\n input: call.input,\n };\n }\n }\n }\n\n throw new Error(\n `Could not resolve tool call for approval ${request.approvalId}. Pass messages that include the assistant tool-call.`\n );\n}\n\n/**\n * Create RobotRock tasks for pending AI SDK tool approvals and return `tool-approval-response` parts.\n */\nexport async function resolveToolApprovalsViaRobotRock(\n clientOrContext: RobotRock | RobotRockAiContext,\n source: unknown,\n options: ResolveToolApprovalsOptions = {}\n): Promise<{\n responses: ToolApprovalResponse[];\n messages: unknown[];\n}> {\n const context = normalizeRobotRockAiContext(clientOrContext);\n const approveId = options.approveActionId ?? \"approve\";\n const denyId = options.denyActionId ?? \"deny\";\n const formatTask = options.formatTask ?? defaultFormatToolApprovalTask;\n\n const baseMessages =\n typeof source === \"object\" && source !== null && Array.isArray((source as { messages?: unknown[] }).messages)\n ? [...(source as { messages: unknown[] }).messages]\n : [];\n\n const requests = collectApprovalRequests(source);\n const responses: ToolApprovalResponse[] = [];\n\n for (const request of requests) {\n const toolCall = resolveToolCallForRequest(request, source, baseMessages);\n const taskInput = formatTask(toolCall, {\n approveActionId: approveId,\n denyActionId: denyId,\n });\n\n const result = await sendToHumanForAi(context, taskInput);\n\n const approved = result.actionId === approveId;\n const reason =\n typeof result.data === \"object\" &&\n result.data !== null &&\n \"reason\" in result.data &&\n typeof (result.data as { reason?: unknown }).reason === \"string\"\n ? (result.data as { reason: string }).reason\n : approved\n ? \"Approved in RobotRock inbox\"\n : \"Denied in RobotRock inbox\";\n\n responses.push({\n type: \"tool-approval-response\",\n approvalId: request.approvalId,\n approved,\n reason,\n });\n }\n\n const messages = [...baseMessages];\n if (responses.length > 0) {\n messages.push({ role: \"tool\", content: responses });\n }\n\n return { responses, messages };\n}\n\n/**\n * Run `generate` in a loop until manual tool approvals are resolved via RobotRock or `maxRounds` is reached.\n */\nexport async function runWithRobotRockApprovals<T>(\n options: RunWithRobotRockApprovalsOptions<T>\n): Promise<T> {\n const clientOrContext =\n options.context ??\n (options.client\n ? options.client\n : (() => {\n throw new Error(\"runWithRobotRockApprovals requires `client` or `context`.\");\n })());\n\n const maxRounds = options.maxRounds ?? 20;\n let messages = options.messages ? [...options.messages] : [];\n let lastResult: T | undefined;\n\n for (let round = 0; round < maxRounds; round++) {\n lastResult = await options.generate(messages);\n const { responses, messages: nextMessages } = await resolveToolApprovalsViaRobotRock(\n clientOrContext,\n { ...(lastResult as object), messages },\n options.resolveOptions\n );\n\n if (responses.length === 0) {\n return lastResult;\n }\n\n messages = nextMessages;\n }\n\n throw new Error(`RobotRock approval loop exceeded maxRounds (${maxRounds})`);\n}\n\nexport { collectApprovalRequests };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAyI1C,SAAS,wBACP,MACA,KACA;AACA,QAAM,QAAQ,0BAA0B,KAAK,OAAO;AACpD,MAAI,OAAO;AACT,QAAI,SAAS;AAAA,MACX,MAAM,EAAE,aAAa;AAAA,MACrB,SAAS;AAAA,MACT,MAAM,CAAC,SAAS;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AA1JA,IA4EM,eAIA,mBAKA,gBAIA,sBAMA,sBAKA,eAEA,kBAUA,qBAUA,iBAEA,mBAOA,yBAyBO,mBAQA,gBAiBA,2BAMA,sBAUA,0BAMA,yBAMA,gBAEA,oBAeP,gBAEO,uBAMA,iBAMP,qBAEO,sBAeA,sBAuBA;AAxRb;AAAA;AAAA;AA4EA,IAAM,gBAAgB,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,gBAAgB,GAAG,GAAG;AAAA,MACrE,SAAS;AAAA,IACX,CAAC;AAED,IAAM,oBAAoB,EAAE;AAAA,MAC1B,CAAC,QAAQ,OAAO,QAAQ,YAAY,QAAQ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C,SAAS,GAAG;AAC7E;","names":["task","task","parseValidUntilMs","sleep","parseValidUntilMs","APPROVE_BY_HUMAN_ACTIONS","z","APPROVE_BY_HUMAN_ACTIONS","sendToHumanTask","sendToHumanInWorkflow","result","sendUpdateInWorkflow","approveByHumanTask","approveByHumanInWorkflow","APPROVE_BY_HUMAN_ACTIONS","z","z","z","z","z"]}
@@ -1,4 +1,4 @@
1
- import { TaskContextInput, AssignToInput, TaskPriority, ThreadUpdateStatus, TaskResponse, DiscriminatedApprovalResult, Task, ThreadUpdate } from './schemas/index.js';
1
+ import { TaskContextInput, AssignToInput, TaskPriority, ThreadUpdateStatus, AgentTelemetryInput, TaskResponse, DiscriminatedApprovalResult, Task, ThreadUpdate } from './schemas/index.js';
2
2
 
3
3
  type RobotRockWebhookConfig = {
4
4
  url: string;
@@ -74,6 +74,11 @@ type SendToHumanInput<A extends readonly SendToHumanActionInput[] = readonly Sen
74
74
  /** Lifecycle status for the icon/color in the status bar. @default "info" */
75
75
  status?: ThreadUpdateStatus;
76
76
  };
77
+ /**
78
+ * Agent telemetry (version, cost, tool calls) — not shown in inbox UI.
79
+ * Used for statistics and feedback analysis.
80
+ */
81
+ agent?: AgentTelemetryInput;
77
82
  };
78
83
  type SendToHumanWithAppInput<A extends readonly SendToHumanActionInput[] = readonly SendToHumanActionInput[]> = (SendToHumanInput<A> | Readonly<SendToHumanInput<A>>) & {
79
84
  /** Inbox app bucket. Overrides the client `app` when set. */
@@ -129,4 +134,4 @@ declare class RobotRock {
129
134
  declare function createClient(config: RobotRockConfig): RobotRock;
130
135
  declare function attachWebhookToActions(actions: readonly SendToHumanActionInput[], webhook: RobotRockWebhookConfig): TaskContextInput["actions"];
131
136
 
132
- export { type RobotRockConfig as R, type SendToHumanActionInput as S, type SendToHumanInput as a, RobotRock as b, RobotRockError as c, attachWebhookToActions as d, createClient as e, type RobotRockWebhookClientConfig as f, type RobotRockPollingClientConfig as g, type RobotRockWebhookConfig as h, type RobotRockPollingOptions as i, type SendToHumanValidUntil as j, type SendToHumanResult as k, type SendUpdateInput as l };
137
+ export { RobotRock as R, type SendToHumanActionInput as S, type SendToHumanInput as a, type RobotRockConfig as b, RobotRockError as c, type RobotRockPollingClientConfig as d, type RobotRockPollingOptions as e, type RobotRockWebhookClientConfig as f, type RobotRockWebhookConfig as g, type SendToHumanResult as h, type SendToHumanValidUntil as i, type SendUpdateInput as j, attachWebhookToActions as k, createClient as l };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { R as RobotRockConfig, b as RobotRock } from './client-CLcHdjOz.js';
2
- export { c as RobotRockError, g as RobotRockPollingClientConfig, i as RobotRockPollingOptions, f as RobotRockWebhookClientConfig, h as RobotRockWebhookConfig, S as SendToHumanActionInput, a as SendToHumanInput, k as SendToHumanResult, j as SendToHumanValidUntil, l as SendUpdateInput, d as attachWebhookToActions, e as createClient } from './client-CLcHdjOz.js';
1
+ import { R as RobotRock, b as RobotRockConfig } from './client-D-XEBOWd.js';
2
+ export { c as RobotRockError, d as RobotRockPollingClientConfig, e as RobotRockPollingOptions, f as RobotRockWebhookClientConfig, g as RobotRockWebhookConfig, S as SendToHumanActionInput, a as SendToHumanInput, h as SendToHumanResult, i as SendToHumanValidUntil, j as SendUpdateInput, k as attachWebhookToActions, l as createClient } from './client-D-XEBOWd.js';
3
3
  import { Task, DiscriminatedApprovalResult } from './schemas/index.js';
4
- export { ApprovalResult, AssignToInput, CreateTaskBody, CreateTaskBodyInput, DEFAULT_TASK_PRIORITY, DEFAULT_THREAD_UPDATE_STATUS, Handler, InferActionData, LOWEST_TASK_PRIORITY, TASK_PRIORITY_RANK, TaskAction, TaskContext, TaskContextInput, TaskPriority, TaskResponse, TaskResult, TaskStatus, ThreadUpdate, ThreadUpdateBody, ThreadUpdateBodyInput, ThreadUpdateInput, ThreadUpdateResponse, ThreadUpdateSource, ThreadUpdateStatus, TriggerHandler, TupleElementIndices, WebhookHandler, assignToSchema, createTaskBodySchema, taskContextSchema, taskPriorities, taskPrioritySchema, threadUpdateBodySchema, threadUpdateInputSchema, threadUpdateStatusSchema, threadUpdateStatuses } from './schemas/index.js';
4
+ export { AgentCost, AgentCostTokens, AgentTelemetry, AgentTelemetryInput, ApprovalResult, AssignToInput, CreateTaskBody, CreateTaskBodyInput, DEFAULT_TASK_PRIORITY, DEFAULT_THREAD_UPDATE_STATUS, Handler, InferActionData, LOWEST_TASK_PRIORITY, TASK_PRIORITY_RANK, TaskAction, TaskContext, TaskContextInput, TaskPriority, TaskResponse, TaskResult, TaskStatus, ThreadUpdate, ThreadUpdateBody, ThreadUpdateBodyInput, ThreadUpdateInput, ThreadUpdateResponse, ThreadUpdateSource, ThreadUpdateStatus, TriggerHandler, TupleElementIndices, WebhookHandler, agentCostSchema, agentCostTokensSchema, agentTelemetrySchema, assignToSchema, createTaskBodySchema, taskContextSchema, taskPriorities, taskPrioritySchema, threadUpdateBodySchema, threadUpdateInputSchema, threadUpdateStatusSchema, threadUpdateStatuses } from './schemas/index.js';
5
5
  import { z } from 'zod';
6
6
  export { R as RobotRockHandlerWebhookPayload } from './handler-webhook-BqEi6Bk-.js';
7
7
 
@@ -37,43 +37,12 @@ declare const robotRockWebhookPayloadSchema: z.ZodObject<{
37
37
  id: z.ZodString;
38
38
  title: z.ZodString;
39
39
  data: z.ZodUnknown;
40
- }, "strip", z.ZodTypeAny, {
41
- id: string;
42
- title: string;
43
- data?: unknown;
44
- }, {
45
- id: string;
46
- title: string;
47
- data?: unknown;
48
- }>;
40
+ }, z.core.$strip>;
49
41
  handledBy: z.ZodOptional<z.ZodString>;
50
42
  handledAt: z.ZodString;
51
43
  handlerType: z.ZodString;
52
- } & {
53
44
  headers: z.ZodRecord<z.ZodString, z.ZodString>;
54
- }, "strip", z.ZodTypeAny, {
55
- headers: Record<string, string>;
56
- taskId: string;
57
- handledAt: string;
58
- action: {
59
- id: string;
60
- title: string;
61
- data?: unknown;
62
- };
63
- handlerType: string;
64
- handledBy?: string | undefined;
65
- }, {
66
- headers: Record<string, string>;
67
- taskId: string;
68
- handledAt: string;
69
- action: {
70
- id: string;
71
- title: string;
72
- data?: unknown;
73
- };
74
- handlerType: string;
75
- handledBy?: string | undefined;
76
- }>;
45
+ }, z.core.$strip>;
77
46
  type RobotRockWebhookErrorCode = "MISSING_WEBHOOK_SECRET" | "MISSING_SIGNATURE" | "INVALID_SIGNATURE" | "INVALID_JSON" | "INVALID_PAYLOAD";
78
47
  declare class RobotRockWebhookError extends Error {
79
48
  readonly code: RobotRockWebhookErrorCode;