robotrock 1.0.0 → 1.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.
Files changed (50) hide show
  1. package/dist/ai/index.d.ts +5 -5
  2. package/dist/ai/index.js +285 -47
  3. package/dist/ai/index.js.map +1 -1
  4. package/dist/ai/trigger.d.ts +3 -3
  5. package/dist/ai/trigger.js +285 -47
  6. package/dist/ai/trigger.js.map +1 -1
  7. package/dist/ai/workflow.d.ts +3 -3
  8. package/dist/ai/workflow.js +285 -47
  9. package/dist/ai/workflow.js.map +1 -1
  10. package/dist/{client-CzVmjXpz.d.ts → client-XTnFHGFE.d.ts} +34 -5
  11. package/dist/eve/agent/index.d.ts +188 -0
  12. package/dist/eve/agent/index.js +2322 -0
  13. package/dist/eve/agent/index.js.map +1 -0
  14. package/dist/eve/index.d.ts +5 -0
  15. package/dist/eve/index.js +446 -0
  16. package/dist/eve/index.js.map +1 -0
  17. package/dist/eve/tools/identity/index.d.ts +6 -0
  18. package/dist/eve/tools/identity/index.js +144 -0
  19. package/dist/eve/tools/identity/index.js.map +1 -0
  20. package/dist/eve/tools/identity/my-access.d.ts +58 -0
  21. package/dist/eve/tools/identity/my-access.js +106 -0
  22. package/dist/eve/tools/identity/my-access.js.map +1 -0
  23. package/dist/eve/tools/identity/whoami.d.ts +45 -0
  24. package/dist/eve/tools/identity/whoami.js +101 -0
  25. package/dist/eve/tools/identity/whoami.js.map +1 -0
  26. package/dist/eve/tools/inbox/create-task.d.ts +113 -0
  27. package/dist/eve/tools/inbox/create-task.js +1557 -0
  28. package/dist/eve/tools/inbox/create-task.js.map +1 -0
  29. package/dist/eve/tools/inbox/index.d.ts +5 -0
  30. package/dist/eve/tools/inbox/index.js +1557 -0
  31. package/dist/eve/tools/inbox/index.js.map +1 -0
  32. package/dist/eve/tools/index.d.ts +17 -0
  33. package/dist/eve/tools/index.js +1654 -0
  34. package/dist/eve/tools/index.js.map +1 -0
  35. package/dist/index-BL9qKHA8.d.ts +141 -0
  36. package/dist/index.d.ts +5 -44
  37. package/dist/index.js +541 -42
  38. package/dist/index.js.map +1 -1
  39. package/dist/schemas/index.js +75 -12
  40. package/dist/schemas/index.js.map +1 -1
  41. package/dist/tenant-5YKDrdC-.d.ts +23 -0
  42. package/dist/{tool-approval-bridge-DbwUEBHv.d.ts → tool-approval-bridge-C4bTm8vu.d.ts} +1 -1
  43. package/dist/trigger/index.d.ts +1 -1
  44. package/dist/trigger/index.js +256 -42
  45. package/dist/trigger/index.js.map +1 -1
  46. package/dist/{trigger-BCKBbAV7.d.ts → trigger-Dn0DFiyU.d.ts} +2 -2
  47. package/dist/workflow/index.d.ts +1 -1
  48. package/dist/workflow/index.js +256 -42
  49. package/dist/workflow/index.js.map +1 -1
  50. package/package.json +44 -7
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/eve/tools/inbox/create-task.ts","../../../src/schemas/index.ts","../../../../core/src/utils/safe-url.ts","../../../../core/src/schemas/task.ts","../../../../core/src/schemas/context-urls.ts","../../../src/approval-result.ts","../../../src/http.ts","../../../../core/src/handler-retry.ts","../../../../core/src/attribution/index.ts","../../../../core/src/app-url.ts","../../../src/auth-headers.ts","../../../src/chats.ts","../../../src/client.ts","../../../src/env.ts","../../../src/eve/agent/attributes.ts","../../../src/eve/agent/tenant.ts","../../../src/eve/agent/client-from-session.ts","../../../src/eve/agent/task-delegation.ts","../../../src/eve/agent/chat-audit-api.ts","../../../src/eve/tools/identity/my-access.ts","../../../src/eve/tools/identity/whoami.ts","../../../src/eve/tools/index.ts"],"sourcesContent":["import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport type { TenantCaller } from \"../../agent/tenant.js\";\nimport {\n buildRobotRockTaskPayload,\n createRobotRockTask,\n type RobotRockTaskToolInput,\n} from \"../../agent/task-delegation.js\";\nimport { postRobotRockLinkChatTask } from \"../../agent/chat-audit-api.js\";\nimport { requireTenantCaller } from \"../../agent/tenant.js\";\n\n/** Eve tool slug — must match the agent tool filename `create_robotrock_task.ts`. */\nexport const CREATE_INBOX_TASK_TOOL_NAME = \"create_robotrock_task\";\n\nconst actionSchema = z.object({\n id: z.string().min(1).describe(\"Stable action id, e.g. approve or reject.\"),\n title: z.string().min(1).describe(\"Button label shown in the inbox.\"),\n description: z.string().min(1).optional(),\n});\n\nconst assignToSchema = z\n .object({\n users: z\n .array(z.string().email())\n .optional()\n .describe(\"Assignee emails — only these users (plus group members) see the task.\"),\n groups: z\n .array(z.string().min(1))\n .optional()\n .describe('Group slugs, e.g. \"finance\". Only members of these groups see the task.'),\n })\n .optional()\n .refine(\n (value) =>\n value === undefined ||\n (value.users?.length ?? 0) > 0 ||\n (value.groups?.length ?? 0) > 0,\n { message: \"assignTo needs at least one user email or group slug.\" }\n );\n\nconst contextSchema = z\n .object({\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Structured fields shown in the inbox task detail.\"),\n ui: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Optional ui:* hints keyed by context.data field name.'),\n })\n .optional();\n\nexport const createInboxTaskInputSchema = z.object({\n type: z\n .string()\n .min(1)\n .describe(\"Task category slug, e.g. refund-approval or budget-approval.\"),\n name: z.string().min(1).describe(\"Short title shown in the inbox list.\"),\n description: z.string().min(1).optional(),\n actions: z\n .array(actionSchema)\n .min(1)\n .describe(\"At least one reviewer action (approve, reject, etc.).\"),\n assignTo: assignToSchema.describe(\n \"Limit visibility to specific users and/or groups. Omit to show the task to everyone in the tenant.\"\n ),\n context: contextSchema,\n validUntilHours: z\n .number()\n .positive()\n .optional()\n .describe(\"Optional deadline in hours from now. Defaults to the tenant task TTL.\"),\n priority: z.enum([\"low\", \"normal\", \"high\", \"urgent\"]).optional(),\n updateMessage: z\n .string()\n .min(1)\n .optional()\n .describe(\"Optional thread status update logged when the task is created.\"),\n delegationReason: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"User-facing explanation of why the requester cannot self-approve and the task was routed elsewhere. Required when assignTo excludes the caller.\"\n ),\n});\n\nexport type CreateInboxTaskToolInput = z.infer<typeof createInboxTaskInputSchema>;\n\nexport type DefineCreateInboxTaskToolOptions = {\n defaultApp?: string;\n resolveDelegationReason?: (\n input: CreateInboxTaskToolInput,\n caller: TenantCaller\n ) => string | undefined;\n};\n\nfunction defaultResolveDelegationReason(\n input: CreateInboxTaskToolInput\n): string | undefined {\n const assigneeGroups = input.assignTo?.groups?.filter(Boolean) ?? [];\n if (assigneeGroups.length > 0) {\n return `This was routed to ${assigneeGroups.join(\", \")} for review because you are not in the assignee group.`;\n }\n return undefined;\n}\n\nexport function defineCreateInboxTaskTool(\n options?: DefineCreateInboxTaskToolOptions\n) {\n return defineTool({\n description:\n \"Create a RobotRock inbox task and assign it to users or groups. Does not wait for a response. \" +\n \"Only call this after the user explicitly asked to create/send/delegate an inbox task, or after they confirmed via ask_question. \" +\n \"Never create a task silently when the user only asked for a preview, dummy example, or explanation. \" +\n \"Always set delegationReason when assignTo excludes the caller. \" +\n \"For refund approvals include chargeId, amount, currency, and reason in context.data.\",\n inputSchema: createInboxTaskInputSchema,\n async execute(input, ctx) {\n const caller = requireTenantCaller(ctx);\n const payload = buildRobotRockTaskPayload(input as RobotRockTaskToolInput, {\n requestedByEmail: caller.email,\n });\n\n if (options?.defaultApp && !payload.app) {\n payload.app = options.defaultApp;\n }\n\n const task = await createRobotRockTask(payload, ctx);\n const delegationReason =\n options?.resolveDelegationReason?.(input, caller) ??\n input.delegationReason?.trim() ??\n defaultResolveDelegationReason(input);\n\n await postRobotRockLinkChatTask(ctx, {\n eveSessionId: ctx.session.id,\n publicTaskId: task.taskId,\n toolCallId: ctx.callId,\n });\n\n return {\n ...task,\n name: input.name,\n assignedTo: input.assignTo ?? null,\n requestedBy: caller.email,\n delegationReason: delegationReason ?? null,\n message: delegationReason\n ? `${delegationReason} This chat updates when the assignee decides.`\n : \"Task created in RobotRock. Assignees can handle it from their inbox; this chat will update when they decide.\",\n };\n },\n });\n}\n\nexport const createInboxTaskTool = defineCreateInboxTaskTool();\n","import { z } from \"zod\";\nimport {\n isAllowedHandlerUrl,\n HANDLER_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 handlerUrlSchema = z.string().refine((url) => isAllowedHandlerUrl(url), {\n message: HANDLER_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: handlerUrlSchema,\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\n/** Action config without handlers — used for chat widgets and agent tool input. */\nexport const taskActionInputSchema = 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});\n\nconst taskActionSchema = taskActionInputSchema.extend({\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\n/** Task context wire format version (always `2` today). */\nexport const TASK_CONTEXT_FORMAT_VERSION = 2 as const;\nexport type TaskContextFormatVersion = typeof TASK_CONTEXT_FORMAT_VERSION;\n\nconst taskContextObjectBaseSchema = 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 contextVersion: z.literal(2).optional(),\n /** @deprecated Use `contextVersion`. Accepted on ingest only. */\n version: z.literal(2).optional(),\n actions: z.array(taskActionSchema).min(1, \"At least one action is required\"),\n});\n\nfunction normalizeTaskContextVersion<T extends { contextVersion?: 2; version?: 2 }>(\n data: T\n): Omit<T, \"version\" | \"contextVersion\"> & { contextVersion: 2 } {\n const { version: legacyVersion, contextVersion, ...rest } = data;\n return {\n ...rest,\n contextVersion: contextVersion ?? legacyVersion ?? TASK_CONTEXT_FORMAT_VERSION,\n };\n}\n\nconst taskContextObjectSchema = taskContextObjectBaseSchema.transform(\n normalizeTaskContextVersion\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\nexport const agentTelemetrySchema = z.object({\n version: z.string().min(1),\n});\n\nexport const createTaskBodySchema = taskContextObjectBaseSchema\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 .transform(normalizeTaskContextVersion)\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 TaskActionInput = z.infer<typeof taskActionInputSchema>;\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 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","const BLOCKED_HOSTNAMES = new Set([\n \"localhost\",\n \"metadata.google.internal\",\n \"metadata.goog\",\n]);\n\nfunction normalizeHostname(hostname: string): string {\n return hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n}\n\nfunction isBlockedIpv4(host: string): boolean {\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(host);\n if (!match) {\n return false;\n }\n\n const octets = match.slice(1, 5).map((part) => Number(part));\n if (octets.some((octet) => Number.isNaN(octet) || octet < 0 || octet > 255)) {\n return true;\n }\n\n const [a, b, _c, _d] = octets;\n if (a === undefined || b === undefined) {\n return true;\n }\n if (a === 127 || a === 0) return true;\n if (a === 10) return true;\n if (a === 169 && b === 254) return true;\n if (a === 192 && b === 168) return true;\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 100 && b >= 64 && b <= 127) return true;\n\n return false;\n}\n\nfunction ipv4FromNumericHost(host: string): string | null {\n if (/^\\d+$/.test(host)) {\n const num = Number(host);\n if (!Number.isFinite(num) || num < 0 || num > 0xffffffff) {\n return null;\n }\n const a = (num >>> 24) & 0xff;\n const b = (num >>> 16) & 0xff;\n const c = (num >>> 8) & 0xff;\n const d = num & 0xff;\n return `${a}.${b}.${c}.${d}`;\n }\n\n const hexMatch = /^0x([0-9a-f]{1,8})$/i.exec(host);\n if (hexMatch) {\n const num = Number.parseInt(hexMatch[1]!, 16);\n if (!Number.isFinite(num) || num < 0 || num > 0xffffffff) {\n return null;\n }\n const a = (num >>> 24) & 0xff;\n const b = (num >>> 16) & 0xff;\n const c = (num >>> 8) & 0xff;\n const d = num & 0xff;\n return `${a}.${b}.${c}.${d}`;\n }\n\n return null;\n}\n\nfunction isBlockedIpv4Mapped(host: string): boolean {\n const mappedDotted = /^::ffff:(\\d{1,3}(?:\\.\\d{1,3}){3})$/i.exec(host);\n if (mappedDotted) {\n return isBlockedIpv4(mappedDotted[1]!);\n }\n\n const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(host);\n if (mappedHex) {\n const high = Number.parseInt(mappedHex[1]!, 16);\n const low = Number.parseInt(mappedHex[2]!, 16);\n if (Number.isFinite(high) && Number.isFinite(low)) {\n const a = (high >> 8) & 0xff;\n const b = high & 0xff;\n const c = (low >> 8) & 0xff;\n const d = low & 0xff;\n return isBlockedIpv4(`${a}.${b}.${c}.${d}`);\n }\n }\n\n return false;\n}\n\nfunction isBlockedIpv6(host: string): boolean {\n if (host === \"::1\" || host === \"0:0:0:0:0:0:0:1\") {\n return true;\n }\n if (host.startsWith(\"fc\") || host.startsWith(\"fd\")) {\n return true;\n }\n if (host.startsWith(\"fe80:\")) {\n return true;\n }\n if (isBlockedIpv4Mapped(host)) {\n return true;\n }\n return false;\n}\n\nfunction isBlockedHostname(hostname: string): boolean {\n const host = normalizeHostname(hostname);\n if (!host) {\n return true;\n }\n if (BLOCKED_HOSTNAMES.has(host)) {\n return true;\n }\n if (host.endsWith(\".localhost\") || host.endsWith(\".local\")) {\n return true;\n }\n\n const numericIpv4 = ipv4FromNumericHost(host);\n if (numericIpv4 && isBlockedIpv4(numericIpv4)) {\n return true;\n }\n\n return isBlockedIpv4(host) || isBlockedIpv6(host);\n}\n\n/**\n * True when a handler URL targets the local machine. Convex cloud cannot POST\n * these directly; loopback deliveries are queued in Redis and drained by a local\n * worker (see apps/api handler-outbound).\n */\nexport function isLoopbackHandlerUrl(urlString: string): boolean {\n let url: URL;\n try {\n url = new URL(urlString);\n } catch {\n return false;\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return false;\n }\n if (url.username || url.password) {\n return false;\n }\n\n const host = url.hostname.toLowerCase();\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n );\n}\n\n/**\n * Webhook/trigger handler URLs may target a public host or loopback (local dev).\n */\nexport function isAllowedHandlerUrl(urlString: string): boolean {\n return isPublicHttpUrl(urlString) || isLoopbackHandlerUrl(urlString);\n}\n\n/**\n * Returns true when the URL uses http(s) and targets a public, non-reserved host.\n */\nexport function isPublicHttpUrl(urlString: string): boolean {\n let url: URL;\n try {\n url = new URL(urlString);\n } catch {\n return false;\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return false;\n }\n if (url.username || url.password) {\n return false;\n }\n\n return !isBlockedHostname(url.hostname);\n}\n\nexport const PUBLIC_HTTP_URL_ERROR =\n \"URL must be a public http:// or https:// address\";\n\nexport const HANDLER_URL_ERROR =\n \"Handler URL must be a public or loopback http:// or https:// address\";\n\nconst FORBIDDEN_HANDLER_HEADERS = new Set([\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"keep-alive\",\n \"x-robotrock-signature\",\n \"x-robotrock-delivery-id\",\n \"x-robotrock-delivery-attempt\",\n]);\n\n/**\n * Allow only safe custom webhook headers; blocks overrides of delivery metadata.\n */\nexport function filterHandlerHeaders(\n headers: Record<string, string> | undefined\n): Record<string, string> {\n if (!headers) {\n return {};\n }\n\n const filtered: Record<string, string> = {};\n for (const [rawKey, value] of Object.entries(headers)) {\n const key = rawKey.toLowerCase().trim();\n if (!key || FORBIDDEN_HANDLER_HEADERS.has(key)) {\n continue;\n }\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(key)) {\n continue;\n }\n filtered[key] = value;\n }\n return filtered;\n}\n","import { z } from \"zod\";\nimport {\n isAllowedHandlerUrl,\n isPublicHttpUrl,\n HANDLER_URL_ERROR,\n PUBLIC_HTTP_URL_ERROR,\n} from \"../utils/safe-url\";\nimport { validateContextPublicUrls } from \"./context-urls\";\nimport type { JSONSchema7 } from \"./json-schema\";\n\n/**\n * Extended JSONSchema7 type that includes RJSF extensions like enumNames\n */\nexport type ExtendedJSONSchema7 = JSONSchema7 & {\n enumNames?: string[];\n [key: string]: unknown;\n};\n\n/**\n * UI Schema for RJSF form customization\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\n// Helper schemas\nexport const safeUrlSchema = z.string().refine((url) => isPublicHttpUrl(url), {\n message: PUBLIC_HTTP_URL_ERROR,\n});\n\nconst handlerUrlSchema = z.string().refine((url) => isAllowedHandlerUrl(url), {\n message: HANDLER_URL_ERROR,\n});\n\n// JSONSchema7 validation\nconst jsonSchema7Schema = z.custom<ExtendedJSONSchema7>(\n (val) => typeof val === \"object\" && val !== null,\n { message: \"Must be a valid JSON Schema object\" }\n);\n\n// UiSchema validation\nconst uiSchemaSchema = z.custom<UiSchema>((val) => typeof val === \"object\" && val !== null, {\n message: \"Must be a valid UiSchema object\",\n});\n\n// Handler schemas (per-action handlers for webhooks, triggers, etc.)\nconst webhookHandlerSchema = z.object({\n type: z.literal(\"webhook\"),\n url: handlerUrlSchema,\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\n/** Action config without handlers — used for chat widgets and agent tool input. */\nexport const taskActionInputSchema = 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});\n\n// Action schema with JSONSchema-based feedback and optional handlers\nconst taskActionSchema = taskActionInputSchema.extend({\n // Optional handlers for this action - if present, must have at least 1\n handlers: z.array(handlerSchema).min(1).optional(),\n});\n\n// UI Field Schema\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\n// Context UI Schema\nconst contextUiSchema = z.record(z.string(), uiFieldSchemaSchema).optional();\n\n// Context data schema\nconst contextDataSchema = z\n .object({\n data: z.record(z.string(), z.unknown()),\n ui: contextUiSchema,\n })\n .optional();\n\nexport const TASK_CONTEXT_FORMAT_VERSION = 2 as const;\nexport type TaskContextFormatVersion = typeof TASK_CONTEXT_FORMAT_VERSION;\n\n// Main TaskContext schema\nconst taskContextObjectBaseSchema = z.object({\n /** Source application id; omitted tasks are grouped in the default inbox. */\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 /** Task context wire format version. @default 2 */\n contextVersion: z.literal(2).optional(),\n /** @deprecated Use `contextVersion`. Accepted on ingest only. */\n version: z.literal(2).optional(),\n actions: z.array(taskActionSchema).min(1, \"At least one action is required\"),\n});\n\nfunction normalizeTaskContextVersion<T extends { contextVersion?: 2; version?: 2 }>(\n data: T\n): Omit<T, \"version\" | \"contextVersion\"> & { contextVersion: 2 } {\n const { version: legacyVersion, contextVersion, ...rest } = data;\n return {\n ...rest,\n contextVersion: contextVersion ?? legacyVersion ?? TASK_CONTEXT_FORMAT_VERSION,\n };\n}\n\nconst taskContextObjectSchema = taskContextObjectBaseSchema.transform(\n normalizeTaskContextVersion\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\n/**\n * Agent release at task create (not shown in inbox reviewer UI).\n * Used for feedback analysis over deploys.\n */\nexport const agentTelemetrySchema = z.object({\n /** Agent or app version (semver, git SHA, deploy tag — caller-defined). */\n version: z.string().min(1),\n});\n\n/** POST /v1 body: task context plus optional assignment. */\nexport const createTaskBodySchema = taskContextObjectBaseSchema\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 release version — not shown in inbox UI. */\n agent: agentTelemetrySchema.optional(),\n })\n .transform(normalizeTaskContextVersion)\n .superRefine(refineContextPublicUrls);\n\n/** POST /v1/threads/:threadId/updates body: a standalone thread update. */\nexport const threadUpdateBodySchema = threadUpdateInputSchema;\n\n/** Action widget config for a seeded assistant message (mirrors the `requestActionInput` tool input). */\nexport const agentChatSeedActionSchema = z.object({\n /** Stable action id echoed back on submit; auto-derived from title when omitted. */\n id: z.string().min(1).optional(),\n title: z.string().min(1),\n description: z.string().optional(),\n /** JSON Schema object for the form fields. */\n schema: z.record(z.string(), z.unknown()).optional(),\n /** RJSF ui schema overrides (ui:widget, ui:enumNames, etc.). */\n ui: z.record(z.string(), z.unknown()).optional(),\n /** Optional default field values. */\n data: z.record(z.string(), z.unknown()).optional(),\n});\n\n/** A single pre-seeded chat message injected into a programmatic agent chat. */\nexport const agentChatSeedMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n text: z.string().min(1),\n /** Optional display-name override for the message sender. */\n senderName: z.string().min(1).optional(),\n /**\n * Optional structured input request rendered as a styled RobotRock action\n * widget below the message text. Use this instead of asking the user to reply\n * in plain text so the request is always a proper action form.\n */\n requestActionInput: z\n .object({\n prompt: z.string().optional(),\n action: agentChatSeedActionSchema,\n })\n .optional(),\n});\n\n/**\n * POST /v1/agent-chats body: create + assign one or more agent chat sessions.\n * Either `agentIdentifier` (new chat) or `parentChatId` (spawned from a chat) is required.\n */\nconst eveAgentChatTransportSchema = z.object({\n kind: z.literal(\"eve\"),\n chatId: z.string().min(1),\n baseUrl: z.string().url(),\n sessionId: z.string().optional(),\n continuationToken: z.string().optional(),\n streamIndex: z.number().int().nonnegative().optional(),\n isStreaming: z.boolean().optional(),\n});\n\nexport const createAgentChatBodySchema = z\n .object({\n /** Agent id (eve agent name). Required unless `parentChatId` is set. */\n agentIdentifier: z.string().min(1).optional(),\n /** Inherit tenant/connection/agent from an existing chat (agent-spawned chats). */\n parentChatId: z.string().min(1).optional(),\n /** Convex tenantEveConnections id; resolved from the tenant when omitted. */\n eveConnectionId: z.string().min(1).optional(),\n /** Source application id; groups the chat under an inbox section. */\n app: z.string().min(1).optional(),\n assignTo: assignToSchema.optional(),\n title: z.string().min(1),\n messages: z.array(agentChatSeedMessageSchema).default([]),\n /** Provenance label stored on the session (\"cron\" | \"agent\" | ...). */\n source: z.string().min(1).optional(),\n })\n .refine((data) => Boolean(data.agentIdentifier || data.parentChatId), {\n message: \"Provide either agentIdentifier or parentChatId\",\n });\n\n/** POST /v1/agent-chats/transport body: persist live-chat cursor for the browser. */\nexport const agentChatTransportBodySchema = eveAgentChatTransportSchema;\n\n/** POST /v1/agent-chats/audit-input body: log Eve HITL choices from agent hooks. */\nexport const agentChatAuditInputBodySchema = z.object({\n eveSessionId: z.string().min(1),\n userId: z.string().min(1),\n actionId: z.string().min(1),\n actionTitle: z.string().optional(),\n prompt: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n idempotencyKey: z.string().optional(),\n /** Eve input request id — used to merge staged HITL metadata. */\n requestId: z.string().optional(),\n /** Eve tool call id — fallback lookup for staged HITL metadata. */\n toolCallId: z.string().optional(),\n});\n\nconst eveHitlStagedOptionSchema = z.object({\n id: z.string(),\n label: z.string(),\n});\n\n/** POST /v1/agent-chats/stage-hitl body: persist pending Eve HITL requests on the chat. */\nexport const agentChatStageHitlBodySchema = z.object({\n eveSessionId: z.string().min(1),\n requests: z.array(\n z.object({\n requestId: z.string().min(1),\n toolCallId: z.string().min(1),\n toolName: z.string().min(1),\n prompt: z.string().min(1),\n display: z.enum([\"confirmation\", \"select\", \"text\"]).optional(),\n allowFreeform: z.boolean().optional(),\n options: z.array(eveHitlStagedOptionSchema).optional(),\n toolInput: z.record(z.string(), z.unknown()).optional(),\n })\n ),\n});\n\n/** POST /v1/agent-chats/link-task body: associate an inbox task with an Eve chat session. */\nexport const agentChatLinkTaskBodySchema = z.object({\n eveSessionId: z.string().min(1),\n publicTaskId: z.string().min(1),\n toolCallId: z.string().min(1),\n});\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\n// Type exports\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 AgentChatSeedAction = z.output<typeof agentChatSeedActionSchema>;\nexport type AgentChatSeedMessage = z.output<typeof agentChatSeedMessageSchema>;\nexport type CreateAgentChatBodyInput = z.input<typeof createAgentChatBodySchema>;\nexport type CreateAgentChatBody = z.output<typeof createAgentChatBodySchema>;\nexport type AgentChatTransportBody = z.output<typeof agentChatTransportBodySchema>;\nexport type AgentChatAuditInputBody = z.output<typeof agentChatAuditInputBodySchema>;\nexport type AgentChatStageHitlBody = z.output<typeof agentChatStageHitlBodySchema>;\nexport type AgentChatLinkTaskBody = z.output<typeof agentChatLinkTaskBodySchema>;\nexport type TaskContextInput = z.input<typeof taskContextSchema>;\nexport type TaskContextOutput = z.output<typeof taskContextSchema>;\nexport type TaskContext = TaskContextOutput;\nexport type SafeUrl = z.infer<typeof safeUrlSchema>;\nexport type TaskActionInput = z.infer<typeof taskActionInputSchema>;\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 ContextData = z.infer<typeof contextDataSchema>;\nexport type ContextUiSchema = z.infer<typeof contextUiSchema>;\nexport type UiFieldSchema = z.infer<typeof uiFieldSchemaSchema>;\nexport type AgentTelemetry = z.infer<typeof agentTelemetrySchema>;\nexport type AgentTelemetryInput = z.input<typeof agentTelemetrySchema>;\n","import { isPublicHttpUrl, PUBLIC_HTTP_URL_ERROR } from \"../utils/safe-url\";\n\ntype ContextInput = {\n data?: Record<string, unknown>;\n ui?: Record<string, unknown>;\n};\n\nfunction resolveLinkUrl(value: string): string {\n return value.startsWith(\"http://\") || value.startsWith(\"https://\")\n ? value\n : `https://${value}`;\n}\n\nfunction widgetType(\n ui: Record<string, unknown> | undefined,\n field: string\n): string | undefined {\n const fieldUi = ui?.[field];\n if (typeof fieldUi !== \"object\" || fieldUi === null) {\n return undefined;\n }\n const widget = (fieldUi as Record<string, unknown>)[\"ui:widget\"];\n return typeof widget === \"string\" ? widget : undefined;\n}\n\nfunction validateUrlValue(value: unknown, widget: string): string | null {\n if (widget === \"image\" || widget === \"link\") {\n if (typeof value !== \"string\") {\n return PUBLIC_HTTP_URL_ERROR;\n }\n const url = widget === \"link\" ? resolveLinkUrl(value) : value;\n if (!isPublicHttpUrl(url)) {\n return PUBLIC_HTTP_URL_ERROR;\n }\n return null;\n }\n\n if (widget === \"attachments\" && Array.isArray(value)) {\n for (const item of value) {\n if (typeof item !== \"object\" || item === null) {\n continue;\n }\n const url = (item as { url?: unknown }).url;\n if (typeof url === \"string\" && !isPublicHttpUrl(resolveLinkUrl(url))) {\n return PUBLIC_HTTP_URL_ERROR;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Validates URL-bearing context widget values (image, link, attachments).\n * Returns an error message or null when valid.\n */\nexport function validateContextPublicUrls(\n context: ContextInput | undefined\n): string | null {\n if (!context?.data) {\n return null;\n }\n\n for (const [field, value] of Object.entries(context.data)) {\n const widget = widgetType(context.ui, field);\n if (!widget) {\n continue;\n }\n const error = validateUrlValue(value, widget);\n if (error) {\n return `context.data.${field}: ${error}`;\n }\n }\n\n return null;\n}\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","export 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\ntype ParsedResponseBody = Record<string, unknown> | unknown[] | string | null;\n\nexport async function parseResponseBody(\n response: Response\n): 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\nexport function getErrorMessage(\n data: ParsedResponseBody,\n fallback: string\n): string {\n if (data && typeof data === \"object\" && !Array.isArray(data)) {\n const record = data as Record<string, unknown>;\n const maybeMessage = record.message;\n const maybeHint = record.hint;\n if (typeof maybeMessage === \"string\" && maybeMessage.trim()) {\n if (typeof maybeHint === \"string\" && maybeHint.trim()) {\n return `${maybeMessage.trim()} ${maybeHint.trim()}`;\n }\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","/** Delays between handler delivery attempts (after attempts 1–7). */\nexport const HANDLER_RETRY_DELAYS_MS = [\n 60_000, // 1m\n 300_000, // 5m\n 1_800_000, // 30m\n 3_600_000, // 1h\n 21_600_000, // 6h\n 86_400_000, // 24h\n 172_800_000, // 48h\n] as const;\n\nexport const HANDLER_MAX_ATTEMPTS = HANDLER_RETRY_DELAYS_MS.length + 1;\n\nexport const HANDLER_FETCH_TIMEOUT_MS = 30_000;\n\nexport function handlerRetryDelayMs(failedAttempt: number): number | null {\n if (failedAttempt < 1 || failedAttempt >= HANDLER_MAX_ATTEMPTS) {\n return null;\n }\n return HANDLER_RETRY_DELAYS_MS[failedAttempt - 1] ?? null;\n}\n\nexport function isRetriableHandlerFailure(\n statusCode: number | undefined,\n _error?: string\n): boolean {\n if (statusCode === undefined) {\n return true;\n }\n if (statusCode >= 200 && statusCode < 300) {\n return false;\n }\n if (statusCode === 408 || statusCode === 429) {\n return true;\n }\n if (statusCode >= 500) {\n return true;\n }\n return false;\n}\n","import { z } from \"zod\";\nimport { getAppBaseUrl } from \"../app-url\";\n\nexport { APP_SIGNUP_URL } from \"../app-url\";\n\nexport const ATTRIBUTION_COOKIE_NAME = \"rr_attribution\";\nexport const ATTRIBUTION_COOKIE_MAX_AGE = 60 * 60 * 24 * 90; // 90 days\nexport const ATTRIBUTION_COOKIE_DOMAIN = \".robotrock.io\";\n\nconst UTM_PARAM_MAP = {\n utm_source: \"utmSource\",\n utm_medium: \"utmMedium\",\n utm_campaign: \"utmCampaign\",\n utm_content: \"utmContent\",\n utm_term: \"utmTerm\",\n gclid: \"gclid\",\n} as const;\n\nexport const attributionSchema = z.object({\n utmSource: z.string().optional(),\n utmMedium: z.string().optional(),\n utmCampaign: z.string().optional(),\n utmContent: z.string().optional(),\n utmTerm: z.string().optional(),\n gclid: z.string().optional(),\n landingUrl: z.string().optional(),\n referrer: z.string().optional(),\n capturedAt: z.number(),\n});\n\nexport type Attribution = z.infer<typeof attributionSchema>;\n\nexport function hasAttributionSignal(attribution: Partial<Attribution>): boolean {\n return Boolean(\n attribution.utmSource ||\n attribution.utmMedium ||\n attribution.utmCampaign ||\n attribution.utmContent ||\n attribution.utmTerm ||\n attribution.gclid\n );\n}\n\nexport function parseAttributionFromSearchParams(\n params: URLSearchParams | Record<string, string | string[] | undefined>\n): Partial<Attribution> {\n const getParam = (key: string): string | undefined => {\n if (params instanceof URLSearchParams) {\n return params.get(key)?.trim() || undefined;\n }\n const value = params[key];\n if (Array.isArray(value)) {\n return value[0]?.trim() || undefined;\n }\n return value?.trim() || undefined;\n };\n\n const result: Partial<Attribution> = {};\n\n for (const [param, field] of Object.entries(UTM_PARAM_MAP)) {\n const value = getParam(param);\n if (value) {\n result[field as keyof typeof UTM_PARAM_MAP & keyof Partial<Attribution>] =\n value;\n }\n }\n\n return result;\n}\n\nexport function buildAttributionFromRequest(input: {\n searchParams: URLSearchParams;\n landingUrl?: string;\n referrer?: string;\n capturedAt?: number;\n}): Attribution | null {\n const parsed = parseAttributionFromSearchParams(input.searchParams);\n if (!hasAttributionSignal(parsed)) {\n return null;\n }\n\n return attributionSchema.parse({\n ...parsed,\n landingUrl: input.landingUrl,\n referrer: input.referrer || undefined,\n capturedAt: input.capturedAt ?? Date.now(),\n });\n}\n\nexport function serializeAttributionCookie(attribution: Attribution): string {\n return encodeURIComponent(JSON.stringify(attribution));\n}\n\nexport function parseAttributionCookie(raw: string | undefined | null): Attribution | null {\n if (!raw) return null;\n\n const candidates = [raw];\n try {\n const decoded = decodeURIComponent(raw);\n if (decoded !== raw) {\n candidates.push(decoded);\n }\n } catch {\n // Keep only the raw value.\n }\n\n for (const candidate of candidates) {\n try {\n const parsed = attributionSchema.parse(JSON.parse(candidate));\n if (hasAttributionSignal(parsed)) {\n return parsed;\n }\n } catch {\n continue;\n }\n }\n\n return null;\n}\n\nexport function formatAttributionCampaign(\n attribution: Partial<Attribution> | null | undefined\n): string | null {\n if (!attribution) return null;\n return attribution.utmCampaign ?? attribution.utmSource ?? null;\n}\n\nexport function appendAttributionToUrl(\n baseUrl: string,\n attribution: Partial<Attribution> | null | undefined,\n origin = getAppBaseUrl()\n): string {\n if (!attribution || !hasAttributionSignal(attribution)) {\n return baseUrl;\n }\n\n const url = baseUrl.startsWith(\"http\")\n ? new URL(baseUrl)\n : new URL(baseUrl, origin);\n const paramEntries: Array<[string, string | undefined]> = [\n [\"utm_source\", attribution.utmSource],\n [\"utm_medium\", attribution.utmMedium],\n [\"utm_campaign\", attribution.utmCampaign],\n [\"utm_content\", attribution.utmContent],\n [\"utm_term\", attribution.utmTerm],\n [\"gclid\", attribution.gclid],\n ];\n\n for (const [param, value] of paramEntries) {\n if (value) {\n url.searchParams.set(param, value);\n }\n }\n\n return baseUrl.startsWith(\"http\")\n ? url.toString()\n : `${url.pathname}${url.search}${url.hash}`;\n}\n\nexport function getAttributionCookieDomain(hostname: string): string | undefined {\n if (hostname === \"localhost\" || hostname.endsWith(\".localhost\")) {\n return undefined;\n }\n if (hostname === \"robotrock.io\" || hostname.endsWith(\".robotrock.io\")) {\n return ATTRIBUTION_COOKIE_DOMAIN;\n }\n return undefined;\n}\n","export const PRODUCTION_APP_URL = \"https://app.robotrock.io\";\nexport const DEV_APP_URL = \"http://localhost:4004\";\nexport const PRODUCTION_API_URL = \"https://api.robotrock.io/v1\";\nexport const DEV_API_URL = \"http://localhost:4001/v1\";\nexport const DEV_DOCS_URL = \"http://localhost:4002\";\n\n/** Local dev server ports for all RobotRock apps (4000–4008). */\nexport const DEV_PORTS = {\n marketing: 4000,\n api: 4001,\n docs: 4002,\n status: 4003,\n app: 4004,\n admin: 4005,\n triggerTest: 4006,\n workflowTest: 4007,\n mcp: 4008,\n} as const;\n\n/** Production signup URL (stable constant for tests and production defaults). */\nexport const APP_SIGNUP_URL = `${PRODUCTION_APP_URL}/sign-up`;\n\nfunction readExplicitAppUrl(): string | undefined {\n const url =\n process.env.NEXT_PUBLIC_APP_URL?.trim() ||\n process.env.NEXT_PUBLIC_APP_PREVIEW_URL?.trim();\n return url ? url.replace(/\\/$/, \"\") : undefined;\n}\n\n/** Dashboard origin — localhost:4004 in dev unless overridden via env. */\nexport function getAppBaseUrl(): string {\n const explicit = readExplicitAppUrl();\n if (explicit) return explicit;\n if (process.env.NODE_ENV === \"development\") {\n return DEV_APP_URL;\n }\n return PRODUCTION_APP_URL;\n}\n\nexport function getAppSignupBaseUrl(): string {\n return `${getAppBaseUrl()}/sign-up`;\n}\n\n/** Ensure the RobotRock API base URL ends with `/v1` (no trailing slash). */\nexport function normalizeRobotRockApiBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.trim().replace(/\\/+$/, \"\");\n if (trimmed.endsWith(\"/v1\")) {\n return trimmed;\n }\n return `${trimmed}/v1`;\n}\n\n/**\n * RobotRock API origin for SDK / agent hooks.\n * Local dev defaults to `http://localhost:4001/v1` unless overridden.\n */\nexport function getRobotRockApiBaseUrl(): string {\n const explicit =\n process.env.ROBOTROCK_BASE_URL?.trim() ||\n process.env.ROBOTROCK_API_URL?.trim();\n if (explicit) {\n return normalizeRobotRockApiBaseUrl(explicit);\n }\n if (process.env.NODE_ENV === \"production\") {\n return PRODUCTION_API_URL;\n }\n return DEV_API_URL;\n}\n","export type RobotRockAuthConfig =\n | { kind: \"apiKey\"; apiKey: string }\n | {\n kind: \"agentService\";\n token: string;\n tenantSlug: string;\n connectionId: string;\n };\n\nexport function buildRobotRockAuthHeaders(\n auth: RobotRockAuthConfig\n): Record<string, string> {\n if (auth.kind === \"apiKey\") {\n return {\n \"X-Api-Key\": auth.apiKey,\n };\n }\n\n return {\n Authorization: `Bearer ${auth.token}`,\n \"X-RobotRock-Tenant-Slug\": auth.tenantSlug,\n \"X-RobotRock-Connection-Id\": auth.connectionId,\n };\n}\n\nexport function resolveRobotRockAuthConfig(overrides?: {\n apiKey?: string;\n agentService?: {\n token: string;\n tenantSlug: string;\n connectionId: string;\n };\n}): RobotRockAuthConfig {\n if (overrides?.agentService) {\n return {\n kind: \"agentService\",\n ...overrides.agentService,\n };\n }\n\n const apiKey = overrides?.apiKey ?? process.env.ROBOTROCK_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"RobotRock auth is required. Set ROBOTROCK_API_KEY, ROBOTROCK_AGENT_SERVICE_TOKEN with tenant context, or pass auth when creating the client.\"\n );\n }\n\n return { kind: \"apiKey\", apiKey };\n}\n","import {\n agentChatAuditInputBodySchema,\n agentChatLinkTaskBodySchema,\n agentChatStageHitlBodySchema,\n createAgentChatBodySchema,\n type AgentChatAuditInputBody,\n type AgentChatLinkTaskBody,\n type AgentChatSeedMessage,\n type AgentChatStageHitlBody,\n type AssignToInput,\n} from \"@robotrock/core\";\nimport { RobotRockError, getErrorMessage, parseResponseBody } from \"./http.js\";\nimport {\n buildRobotRockAuthHeaders,\n type RobotRockAuthConfig,\n} from \"./auth-headers.js\";\n\n/** A chat created via {@link ChatsApi.create}. */\nexport type CreatedChat = {\n chatId: string;\n sessionId: string;\n userId?: string;\n agentIdentifier: string;\n deepLink: string;\n};\n\nexport type CreateChatResult = {\n tenantSlug: string;\n chats: CreatedChat[];\n};\n\nexport type CreateChatInput = {\n /** Agent to run the chat. Required unless `parentChatId` is provided. */\n agentIdentifier?: string;\n /** Spawn a chat from an existing chat; inherits its agent/app/owner and links audit. */\n parentChatId?: string;\n /** Trigger connection id to run the chat under (defaults to the tenant's). */\n connectionId?: string;\n /** Inbox app bucket. Overrides the client `app` when set. */\n app?: string;\n /** Assign to tenant users (email) and/or groups (slug). Narrows inbox visibility. */\n assignTo?: AssignToInput;\n /** Chat title shown in the inbox. */\n title: string;\n /** Seed messages to preload the conversation. Defaults to a welcome message. */\n messages?: AgentChatSeedMessage[];\n /** How the chat was created (statistics/audit). @default \"api\" */\n source?: string;\n};\n\nexport type CloseChatOptions = {\n /** Optional human-readable reason recorded on the audit trail. */\n reason?: string;\n};\n\nexport type LogChatInputSubmissionInput = AgentChatAuditInputBody;\n\nexport type StageChatHitlRequestsInput = AgentChatStageHitlBody;\n\nexport type LinkChatTaskInput = AgentChatLinkTaskBody;\n\nexport type StagedChatHitlRequest = StageChatHitlRequestsInput[\"requests\"][number];\n\nexport interface ChatsApi {\n /** Create one or more agent chats and assign them (task-style). */\n create(input: CreateChatInput): Promise<CreateChatResult>;\n /** Close (archive) a chat by its public chatId — e.g. when an agent is done. */\n close(chatId: string, options?: CloseChatOptions): Promise<void>;\n /** Persist pending Eve HITL requests on the chat for durable audit logging. */\n stageHitlRequests(input: StageChatHitlRequestsInput): Promise<void>;\n /** Read pending Eve HITL requests staged on the chat. */\n getStagedHitlRequests(eveSessionId: string): Promise<StagedChatHitlRequest[]>;\n /** Log an Eve HITL choice to the RobotRock chat audit trail. */\n logInputSubmission(input: LogChatInputSubmissionInput): Promise<void>;\n /** Link an inbox task to the originating Eve chat session. */\n linkTask(input: LinkChatTaskInput): Promise<void>;\n}\n\n/**\n * Build the `client.chats` namespace. Mirrors the `client.tasks` surface for the\n * long-lived chat resource, so a single client creates both tasks and chats.\n */\nexport function createChatsApi(config: {\n baseUrl: string;\n auth: RobotRockAuthConfig;\n app?: string;\n}): ChatsApi {\n const headers = (): Record<string, string> => ({\n \"Content-Type\": \"application/json\",\n ...buildRobotRockAuthHeaders(config.auth),\n });\n\n return {\n async create(input: CreateChatInput): Promise<CreateChatResult> {\n const bodyPayload = {\n ...input,\n app: input.app ?? config.app,\n messages: input.messages ?? [],\n };\n const validation = createAgentChatBodySchema.safeParse(bodyPayload);\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid chat: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const response = await fetch(`${config.baseUrl}/agent-chats`, {\n method: \"POST\",\n headers: headers(),\n body: JSON.stringify(validation.data),\n });\n\n const data = await parseResponseBody(response);\n if (!response.ok) {\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to create chat\"),\n response.status,\n data\n );\n }\n\n const result = data as unknown as CreateChatResult;\n return { tenantSlug: result.tenantSlug, chats: result.chats };\n },\n\n async close(chatId: string, options?: CloseChatOptions): Promise<void> {\n if (!chatId) {\n throw new RobotRockError(\"chatId is required to close a chat\", 400);\n }\n\n const response = await fetch(\n `${config.baseUrl}/agent-chats/${encodeURIComponent(chatId)}/close`,\n {\n method: \"POST\",\n headers: headers(),\n body: JSON.stringify({ reason: options?.reason }),\n }\n );\n\n if (!response.ok) {\n const data = await parseResponseBody(response);\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to close chat\"),\n response.status,\n data\n );\n }\n },\n\n async stageHitlRequests(input: StageChatHitlRequestsInput): Promise<void> {\n const validation = agentChatStageHitlBodySchema.safeParse(input);\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid stage HITL input: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const response = await fetch(`${config.baseUrl}/agent-chats/stage-hitl`, {\n method: \"POST\",\n headers: headers(),\n body: JSON.stringify(validation.data),\n });\n\n if (!response.ok) {\n const data = await parseResponseBody(response);\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to stage chat HITL requests\"),\n response.status,\n data\n );\n }\n },\n\n async getStagedHitlRequests(eveSessionId: string): Promise<StagedChatHitlRequest[]> {\n const trimmed = eveSessionId.trim();\n if (!trimmed) {\n throw new RobotRockError(\"eveSessionId is required\", 400);\n }\n\n const url = new URL(`${config.baseUrl}/agent-chats/staged-hitl`);\n url.searchParams.set(\"eveSessionId\", trimmed);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: headers(),\n });\n\n const data = await parseResponseBody(response);\n if (!response.ok) {\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to fetch staged chat HITL requests\"),\n response.status,\n data\n );\n }\n\n const requests = (data as { requests?: StagedChatHitlRequest[] }).requests;\n return Array.isArray(requests) ? requests : [];\n },\n\n async logInputSubmission(input: LogChatInputSubmissionInput): Promise<void> {\n const validation = agentChatAuditInputBodySchema.safeParse(input);\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid audit input: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const response = await fetch(`${config.baseUrl}/agent-chats/audit-input`, {\n method: \"POST\",\n headers: headers(),\n body: JSON.stringify(validation.data),\n });\n\n if (!response.ok) {\n const data = await parseResponseBody(response);\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to log chat input submission\"),\n response.status,\n data\n );\n }\n },\n\n async linkTask(input: LinkChatTaskInput): Promise<void> {\n const validation = agentChatLinkTaskBodySchema.safeParse(input);\n if (!validation.success) {\n throw new RobotRockError(\n `Invalid link task input: ${validation.error.issues[0]?.message}`,\n 400,\n validation.error.issues\n );\n }\n\n const response = await fetch(`${config.baseUrl}/agent-chats/link-task`, {\n method: \"POST\",\n headers: headers(),\n body: JSON.stringify(validation.data),\n });\n\n if (!response.ok) {\n const data = await parseResponseBody(response);\n throw new RobotRockError(\n getErrorMessage(data, \"Failed to link inbox task to chat\"),\n response.status,\n data\n );\n }\n },\n };\n}\n","import {\n type AssignToInput,\n type TaskContextInput,\n createTaskBodySchema,\n threadUpdateBodySchema,\n TASK_CONTEXT_FORMAT_VERSION,\n} from \"./schemas/index.js\";\nimport {\n TaskExpiredError,\n TaskTimeoutError,\n toDiscriminatedApprovalResult,\n} from \"./approval-result.js\";\nimport { RobotRockError, getErrorMessage, parseResponseBody } from \"./http.js\";\nimport { getRobotRockApiBaseUrl } from \"@robotrock/core\";\nimport { createChatsApi, type ChatsApi } from \"./chats.js\";\nimport {\n buildRobotRockAuthHeaders,\n resolveRobotRockAuthConfig,\n type RobotRockAuthConfig,\n} from \"./auth-headers.js\";\nimport type {\n DiscriminatedApprovalResult,\n Task,\n TaskPriority,\n TaskResponse,\n ThreadUpdate,\n ThreadUpdateResponse,\n ThreadUpdateStatus,\n TaskContextFormatVersion,\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\n/** Advanced client settings rarely changed by integrators. */\nexport type RobotRockAdvancedConfig = {\n /** Task context wire format version sent on every request. @default 2 */\n contextVersion?: TaskContextFormatVersion;\n};\n\ntype RobotRockClientBaseConfig = {\n /** Optional override for API key. Falls back to ROBOTROCK_API_KEY when agentService is unset. */\n apiKey?: string;\n /** Hosted-agent service auth (mutually exclusive with apiKey). */\n agentService?: {\n token: string;\n tenantSlug: string;\n connectionId: string;\n };\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 * Agent release version (semver, git SHA, deploy tag).\n * Defaults to `AGENT_VERSION` or `ROBOTROCK_AGENT_VERSION` from env when omitted.\n */\n version?: string;\n /** Advanced settings (context wire format, etc.). */\n advanced?: RobotRockAdvancedConfig;\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\" | \"contextVersion\" | \"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 release version override. When omitted, uses the client `version`.\n * Used for statistics and feedback analysis.\n */\n version?: string;\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 resolveAgentVersionFromEnv(): string | undefined {\n const fromEnv =\n process.env.AGENT_VERSION?.trim() || process.env.ROBOTROCK_AGENT_VERSION?.trim();\n return fromEnv || undefined;\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 { RobotRockError } from \"./http.js\";\n\n/** Task CRUD surface, exposed as `client.tasks`. */\nexport interface TasksApi {\n /** Create a task via POST /v1 without waiting for a human response. */\n create<const A extends readonly SendToHumanActionInput[]>(\n task: SendToHumanWithAppInput<A>\n ): Promise<TaskResponse[\"task\"]>;\n /** Get a task by public task id. */\n get(taskId: string): Promise<Task | null>;\n /** Cancel a task by public task id. */\n cancel(taskId: string): Promise<void>;\n /** Log a status update against a thread. */\n sendUpdate(input: SendUpdateInput): Promise<ThreadUpdate>;\n}\n\n/**\n * RobotRock API client for creating and querying human-in-the-loop tasks and\n * chats. CRUD lives under `client.tasks` and `client.chats`; the headline\n * `sendToHuman` verb stays top-level.\n */\nexport class RobotRock {\n private readonly auth: RobotRockAuthConfig;\n private readonly baseUrl: string;\n private readonly app?: string;\n private readonly agentVersion?: string;\n private readonly contextVersion: TaskContextFormatVersion;\n private readonly webhook?: RobotRockWebhookConfig;\n private readonly polling: RobotRockPollingOptions;\n\n /** Task CRUD: `create`, `get`, `cancel`, `sendUpdate`. */\n readonly tasks: TasksApi;\n /** Chat CRUD: `create`, `close`. */\n readonly chats: ChatsApi;\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 const agentService = config.agentService;\n if (apiKey && agentService) {\n throw new Error(\n \"RobotRock client cannot configure both apiKey and agentService.\"\n );\n }\n\n this.auth = resolveRobotRockAuthConfig({\n ...(apiKey ? { apiKey } : {}),\n ...(agentService ? { agentService } : {}),\n });\n this.baseUrl = config.baseUrl ?? getRobotRockApiBaseUrl();\n this.app = config.app;\n this.agentVersion = config.version ?? resolveAgentVersionFromEnv();\n this.contextVersion =\n config.advanced?.contextVersion ?? TASK_CONTEXT_FORMAT_VERSION;\n this.webhook = config.webhook;\n this.polling = config.polling ?? {};\n\n this.tasks = {\n create: (task) => this.createTaskRequest(task),\n get: (taskId) => this.getTaskById(taskId),\n cancel: (taskId) => this.cancelTaskRequest(taskId),\n sendUpdate: (input) => this.sendThreadUpdate(input),\n };\n this.chats = createChatsApi({\n baseUrl: this.baseUrl,\n auth: this.auth,\n app: this.app,\n });\n }\n\n private authHeaders(extra?: Record<string, string>): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n ...buildRobotRockAuthHeaders(this.auth),\n ...extra,\n };\n }\n\n private async createTaskRequest<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 contextVersion: this.contextVersion,\n agentVersion: this.agentVersion,\n });\n const agentVersion = task.version ?? this.agentVersion;\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 ...(agentVersion !== undefined ? { agent: { version: agentVersion } } : {}),\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 = this.authHeaders(\n task.idempotencyKey\n ? { \"Idempotency-Key\": task.idempotencyKey }\n : undefined\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 contextVersion: this.contextVersion,\n agentVersion: this.agentVersion,\n });\n const createdTaskTask = await this.createTaskRequest(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.getTaskById(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 * Create a task via POST /v1 without waiting for a human response.\n * @deprecated Use `client.tasks.create()` instead.\n */\n async createTask<const A extends readonly SendToHumanActionInput[]>(\n task: SendToHumanWithAppInput<A>\n ): Promise<TaskResponse[\"task\"]> {\n return this.tasks.create(task);\n }\n\n /**\n * Get a task by public task id (returned as `task.taskId` from {@link sendToHuman}).\n * @deprecated Use `client.tasks.get()` instead.\n */\n async getTask(taskId: string): Promise<Task | null> {\n return this.tasks.get(taskId);\n }\n\n /**\n * Log a status update against a thread.\n * @deprecated Use `client.tasks.sendUpdate()` instead.\n */\n async sendUpdate(input: SendUpdateInput): Promise<ThreadUpdate> {\n return this.tasks.sendUpdate(input);\n }\n\n /**\n * Cancel a task by public task id.\n * @deprecated Use `client.tasks.cancel()` instead.\n */\n async cancelTask(taskId: string): Promise<void> {\n return this.tasks.cancel(taskId);\n }\n\n private async getTaskById(taskId: string): Promise<Task | null> {\n const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {\n method: \"GET\",\n headers: this.authHeaders(),\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 private async sendThreadUpdate({\n threadId,\n message,\n status,\n }: 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: this.authHeaders(),\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 private async cancelTaskRequest(taskId: string): Promise<void> {\n const response = await fetch(`${this.baseUrl}/tasks/${taskId}/cancel`, {\n method: \"POST\",\n headers: this.authHeaders(),\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: {\n webhook?: RobotRockWebhookConfig;\n app?: string;\n contextVersion: TaskContextFormatVersion;\n agentVersion?: string;\n }\n): TaskContextInput {\n const {\n actions,\n idempotencyKey: _idempotencyKey,\n assignTo: _assignTo,\n threadId: _threadId,\n priority: _priority,\n update: _update,\n version: _version,\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 contextVersion: clientDefaults.contextVersion,\n ...(app ? { app } : {}),\n ...(validUntil !== undefined ? { validUntil: serializeValidUntil(validUntil) } : {}),\n actions: normalizedActions,\n };\n}\n\n","import { createClient, type RobotRock, type RobotRockConfig } from \"./client.js\";\nimport { getRobotRockApiBaseUrl } from \"@robotrock/core\";\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 agentService = overrides?.agentService;\n const apiKey = overrides?.apiKey ?? process.env.ROBOTROCK_API_KEY;\n\n if (agentService && apiKey) {\n throw new Error(\n \"RobotRock client cannot configure both apiKey and agentService.\"\n );\n }\n\n const baseUrl = overrides?.baseUrl ?? getRobotRockApiBaseUrl();\n const app = overrides?.app ?? process.env.ROBOTROCK_APP;\n\n if (agentService) {\n return app\n ? { agentService, baseUrl, app }\n : { agentService, baseUrl };\n }\n\n if (!apiKey) {\n throw new Error(\n \"RobotRock API key is required. Set ROBOTROCK_API_KEY or pass agentService when creating the client.\"\n );\n }\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","export function readStringAttribute(\n attributes: Readonly<Record<string, string | readonly string[]>> | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n if (Array.isArray(value) && typeof value[0] === \"string\" && value[0].length > 0) {\n return value[0];\n }\n return undefined;\n}\n\nexport function readStringArrayAttribute(\n attributes: Readonly<Record<string, string | readonly string[]>> | undefined,\n key: string\n): string[] {\n const value = attributes?.[key];\n if (typeof value === \"string\" && value.length > 0) {\n return [value];\n }\n if (Array.isArray(value)) {\n return value.filter(\n (entry): entry is string => typeof entry === \"string\" && entry.length > 0\n );\n }\n return [];\n}\n\nexport function parseTenantRole(\n value: string | undefined\n): \"admin\" | \"member\" | null {\n if (value === \"admin\" || value === \"member\") {\n return value;\n }\n return null;\n}\n","import type { SessionContext } from \"eve/context\";\nimport {\n parseTenantRole,\n readStringArrayAttribute,\n readStringAttribute,\n} from \"./attributes.js\";\n\nexport type TenantRole = \"admin\" | \"member\";\n\nexport type TenantCaller = {\n userId: string;\n email: string;\n name: string;\n tenantSlug: string;\n connectionId?: string;\n role: TenantRole;\n isAdmin: boolean;\n groups: string[];\n workosUserId?: string;\n};\n\n/** Resolve the authenticated RobotRock dashboard user for the current session. */\nexport function tryResolveTenantCaller(ctx: SessionContext): TenantCaller | null {\n const caller = ctx.session.auth.initiator ?? ctx.session.auth.current;\n if (caller?.principalType !== \"user\") {\n return null;\n }\n\n const email = readStringAttribute(caller.attributes, \"email\");\n const name = readStringAttribute(caller.attributes, \"name\");\n const tenantSlug =\n readStringAttribute(caller.attributes, \"tenantSlug\") ??\n readStringAttribute(caller.attributes, \"tenantId\");\n const role = parseTenantRole(readStringAttribute(caller.attributes, \"role\"));\n if (!email || !tenantSlug || !caller.principalId || !role) {\n return null;\n }\n\n const workosUserId = readStringAttribute(caller.attributes, \"workosUserId\");\n const connectionId = readStringAttribute(caller.attributes, \"connectionId\");\n const groups = readStringArrayAttribute(caller.attributes, \"groups\");\n\n return {\n userId: caller.principalId,\n email,\n name: name ?? email.split(\"@\")[0] ?? email,\n tenantSlug,\n ...(connectionId ? { connectionId } : {}),\n role,\n isAdmin: role === \"admin\",\n groups,\n ...(workosUserId ? { workosUserId } : {}),\n };\n}\n\n/** Like {@link tryResolveTenantCaller} but throws when the session has no user. */\nexport function requireTenantCaller(ctx: SessionContext): TenantCaller {\n const caller = tryResolveTenantCaller(ctx);\n if (!caller) {\n throw new Error(\"An authenticated RobotRock tenant user is required.\");\n }\n return caller;\n}\n\nexport function isAdminCaller(ctx: SessionContext): boolean {\n return tryResolveTenantCaller(ctx)?.isAdmin === true;\n}\n\n/** Require an authenticated tenant admin for the current session. */\nexport function requireAdminCaller(ctx: SessionContext): TenantCaller {\n const caller = requireTenantCaller(ctx);\n if (!caller.isAdmin) {\n throw new Error(\"Tenant admin access is required.\");\n }\n return caller;\n}\n","import {\n createClient,\n type RobotRock,\n} from \"../../client.js\";\nimport { resolveRobotRockConfig } from \"../../env.js\";\nimport type { SessionContext } from \"eve/context\";\nimport { tryResolveTenantCaller } from \"./tenant.js\";\n\nlet warnedMissingAuth = false;\n\n/** Create a RobotRock client bound to the current Eve session tenant context. */\nexport function tryCreateBoundRobotRockClient(\n ctx: SessionContext\n): RobotRock | null {\n const caller = tryResolveTenantCaller(ctx);\n const serviceToken = process.env.ROBOTROCK_AGENT_SERVICE_TOKEN?.trim();\n\n if (caller?.connectionId && serviceToken) {\n return createClient({\n baseUrl: process.env.ROBOTROCK_BASE_URL?.trim(),\n agentService: {\n token: serviceToken,\n tenantSlug: caller.tenantSlug,\n connectionId: caller.connectionId,\n },\n });\n }\n\n const apiKey = process.env.ROBOTROCK_API_KEY?.trim();\n if (apiKey) {\n return createClient(\n resolveRobotRockConfig({\n apiKey,\n baseUrl: process.env.ROBOTROCK_BASE_URL?.trim(),\n })\n );\n }\n\n if (!warnedMissingAuth) {\n warnedMissingAuth = true;\n console.warn(\n \"robotrock: set ROBOTROCK_AGENT_SERVICE_TOKEN for hosted multi-tenant auth, \" +\n \"or ROBOTROCK_API_KEY for single-tenant deployments.\"\n );\n }\n\n return null;\n}\n\n/** Reset missing-auth warning (tests only). */\nexport function resetBoundClientAuthWarning(): void {\n warnedMissingAuth = false;\n}\n","import {\n attachWebhookToActions,\n RobotRockError,\n type RobotRock,\n type SendToHumanActionInput,\n type SendToHumanInput,\n} from \"../../client.js\";\nimport type { TaskPriority } from \"../../schemas/index.js\";\nimport type { SessionContext } from \"eve/context\";\nimport { tryCreateBoundRobotRockClient } from \"./client-from-session.js\";\nimport { tryResolveTenantCaller } from \"./tenant.js\";\n\nexport type CreateRobotRockTaskInput = SendToHumanInput<\n readonly SendToHumanActionInput[]\n> & {\n app?: string;\n};\n\nfunction resolveTaskApp(app?: string): string {\n return app?.trim() || process.env.ROBOTROCK_APP?.trim() || \"robotrock-agent\";\n}\n\nfunction resolveWebhookBaseUrl(baseUrl?: string): string {\n return (\n baseUrl?.trim() ||\n process.env.ROBOTROCK_BASE_URL?.trim() ||\n \"http://localhost:4001/v1\"\n );\n}\n\n/** Resolve the webhook URL RobotRock calls when a delegated inbox task is handled. */\nexport function resolveTaskHandledWebhookUrl(baseUrl: string): string {\n const trimmed = baseUrl.trim().replace(/\\/+$/, \"\");\n const withV1 = trimmed.endsWith(\"/v1\") ? trimmed : `${trimmed}/v1`;\n return `${withV1}/agent-chats/task-handled`;\n}\n\nfunction requireBoundClient(ctx: SessionContext): RobotRock {\n const client = tryCreateBoundRobotRockClient(ctx);\n if (!client) {\n throw new Error(\n \"RobotRock auth is unset. Configure ROBOTROCK_AGENT_SERVICE_TOKEN for hosted agents or ROBOTROCK_API_KEY for self-hosted deployments.\"\n );\n }\n return client;\n}\n\n/** Create an inbox task via POST /v1 without waiting for a human response. */\nexport async function createRobotRockTask(\n input: CreateRobotRockTaskInput,\n ctx: SessionContext\n) {\n const client = requireBoundClient(ctx);\n const { app, ...taskInput } = input;\n const resolvedApp = resolveTaskApp(app);\n\n const webhookUrl = resolveTaskHandledWebhookUrl(\n resolveWebhookBaseUrl(process.env.ROBOTROCK_BASE_URL)\n );\n\n try {\n const task = await client.tasks.create({\n ...taskInput,\n app: resolvedApp,\n actions: attachWebhookToActions(taskInput.actions, {\n url: webhookUrl,\n headers: {},\n }),\n });\n return {\n taskId: task.taskId,\n threadId: task.threadId,\n status: task.status,\n validUntil: task.validUntil,\n submittedAt: task.submittedAt,\n };\n } catch (error) {\n const caller = tryResolveTenantCaller(ctx);\n if (error instanceof RobotRockError) {\n const response =\n error.response && typeof error.response === \"object\"\n ? (error.response as Record<string, unknown>)\n : undefined;\n console.error(\"[create_robotrock_task] API request failed\", {\n status: error.statusCode,\n message: error.message,\n code: response?.code,\n hint: response?.hint,\n tenantSlug: caller?.tenantSlug,\n connectionId: caller?.connectionId,\n baseUrl: process.env.ROBOTROCK_BASE_URL?.trim() || null,\n });\n } else {\n console.error(\"[create_robotrock_task] unexpected error\", error);\n }\n throw error;\n }\n}\n\nexport type RobotRockTaskActionInput = {\n id: string;\n title: string;\n description?: string;\n};\n\nexport type RobotRockTaskAssignToInput = {\n users?: string[];\n groups?: string[];\n};\n\nexport type RobotRockTaskContextInput = {\n data?: Record<string, unknown>;\n ui?: Record<string, unknown>;\n};\n\nexport type RobotRockTaskToolInput = {\n type: string;\n name: string;\n description?: string;\n actions: RobotRockTaskActionInput[];\n assignTo?: RobotRockTaskAssignToInput;\n context?: RobotRockTaskContextInput;\n validUntilHours?: number;\n priority?: TaskPriority;\n updateMessage?: string;\n app?: string;\n};\n\nexport function buildRobotRockTaskPayload(\n input: RobotRockTaskToolInput,\n options?: { requestedByEmail?: string }\n): CreateRobotRockTaskInput {\n const contextData: Record<string, unknown> = {\n ...(input.context?.data ?? {}),\n };\n\n if (options?.requestedByEmail) {\n contextData.requestedBy = options.requestedByEmail;\n }\n\n const hasContext =\n Object.keys(contextData).length > 0 ||\n (input.context?.ui && Object.keys(input.context.ui).length > 0);\n\n const payload: CreateRobotRockTaskInput = {\n type: input.type,\n name: input.name,\n ...(input.description ? { description: input.description } : {}),\n actions: input.actions.map((action) => ({\n id: action.id,\n title: action.title,\n ...(action.description ? { description: action.description } : {}),\n })),\n ...(input.assignTo ? { assignTo: input.assignTo } : {}),\n ...(input.priority ? { priority: input.priority } : {}),\n ...(input.app ? { app: input.app } : {}),\n ...(input.validUntilHours\n ? {\n validUntil: new Date(Date.now() + input.validUntilHours * 60 * 60 * 1000),\n }\n : {}),\n ...(input.updateMessage\n ? {\n update: {\n message: input.updateMessage,\n status: \"waiting\" as const,\n },\n }\n : {}),\n };\n\n if (hasContext) {\n payload.context = {\n data: contextData,\n ...(input.context?.ui ? { ui: input.context.ui } : {}),\n };\n }\n\n return payload;\n}\n","import type { StagedChatHitlRequest } from \"../../chats.js\";\nimport { RobotRockError } from \"../../http.js\";\nimport type { SessionContext } from \"eve/context\";\nimport { tryCreateBoundRobotRockClient } from \"./client-from-session.js\";\n\nlet warnedMissingAuth = false;\nlet warnedConnectionRefused = false;\n\nfunction isConnectionRefused(error: unknown): boolean {\n const inspect = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n if (\"code\" in value && value.code === \"ECONNREFUSED\") {\n return true;\n }\n if (\"cause\" in value) {\n return inspect(value.cause);\n }\n if (\"errors\" in value && Array.isArray(value.errors)) {\n return value.errors.some((entry) => inspect(entry));\n }\n return false;\n };\n\n return inspect(error);\n}\n\nfunction logAuditFailure(label: string, error: unknown): void {\n if (isConnectionRefused(error)) {\n if (!warnedConnectionRefused) {\n warnedConnectionRefused = true;\n console.warn(\n \"robotrock-chat-audit: RobotRock API is not reachable (connection refused). \" +\n \"Audit and task-link calls are skipped until the API is up.\"\n );\n }\n return;\n }\n\n const hint =\n error instanceof RobotRockError && error.statusCode === 405\n ? \" — set ROBOTROCK_BASE_URL=http://localhost:4001/v1 and run the local API\"\n : \"\";\n console.warn(`robotrock-chat-audit: failed to ${label}${hint}`, error);\n}\n\nexport type RobotRockChatAuditPayload = {\n eveSessionId: string;\n userId: string;\n actionId: string;\n actionTitle?: string;\n prompt?: string;\n data?: Record<string, unknown>;\n idempotencyKey?: string;\n requestId?: string;\n toolCallId?: string;\n};\n\n/** Observe-only audit POST — never throws. */\nexport async function postRobotRockChatInputAudit(\n ctx: SessionContext,\n payload: RobotRockChatAuditPayload\n): Promise<void> {\n const client = tryCreateBoundRobotRockClient(ctx);\n if (!client) {\n if (!warnedMissingAuth) {\n warnedMissingAuth = true;\n console.warn(\n \"robotrock-chat-audit: RobotRock auth is unset; skipping HITL audit logging.\"\n );\n }\n return;\n }\n\n try {\n await client.chats.logInputSubmission(payload);\n } catch (error) {\n logAuditFailure(\"log input submission\", error);\n }\n}\n\n/** Persist pending HITL requests across Eve durable waits — never throws. */\nexport async function postRobotRockStageHitl(\n ctx: SessionContext,\n input: {\n eveSessionId: string;\n requests: StagedChatHitlRequest[];\n }\n): Promise<void> {\n const client = tryCreateBoundRobotRockClient(ctx);\n if (!client) {\n return;\n }\n\n if (input.requests.length === 0) {\n return;\n }\n\n try {\n await client.chats.stageHitlRequests(input);\n } catch (error) {\n logAuditFailure(\"stage HITL requests\", error);\n }\n}\n\n/** Load staged HITL requests from Convex — returns [] on failure. */\nexport async function fetchRobotRockStagedHitl(\n ctx: SessionContext,\n eveSessionId: string\n): Promise<StagedChatHitlRequest[]> {\n const client = tryCreateBoundRobotRockClient(ctx);\n if (!client) {\n return [];\n }\n\n try {\n return await client.chats.getStagedHitlRequests(eveSessionId);\n } catch (error) {\n logAuditFailure(\"fetch staged HITL requests\", error);\n return [];\n }\n}\n\n/** Register an inbox task with its originating Eve chat session — never throws. */\nexport async function postRobotRockLinkChatTask(\n ctx: SessionContext,\n input: {\n eveSessionId: string;\n publicTaskId: string;\n toolCallId: string;\n }\n): Promise<void> {\n const client = tryCreateBoundRobotRockClient(ctx);\n if (!client) {\n if (!warnedMissingAuth) {\n warnedMissingAuth = true;\n console.warn(\n \"robotrock-task-link: RobotRock auth is unset; skipping chat task link.\"\n );\n }\n return;\n }\n\n try {\n await client.chats.linkTask(input);\n } catch (error) {\n logAuditFailure(\"link task to chat\", error);\n }\n}\n\n/** Reset audit warning flags (tests only). */\nexport function resetChatAuditWarnings(): void {\n warnedMissingAuth = false;\n warnedConnectionRefused = false;\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { tryResolveTenantCaller } from \"../../agent/tenant.js\";\n\n/** Eve tool slug — must match the agent tool filename `get_my_access.ts`. */\nexport const MY_ACCESS_TOOL_NAME = \"get_my_access\";\n\nexport const myAccessInputSchema = z.object({});\n\nfunction tenantCapabilities(isAdmin: boolean) {\n return {\n manageSettings: isAdmin,\n manageBilling: isAdmin,\n manageTeam: isAdmin,\n manageIntegrations: isAdmin,\n };\n}\n\nexport function defineMyAccessTool() {\n return defineTool({\n description:\n \"Check the authenticated user's tenant role, group memberships, and admin capabilities in RobotRock.\",\n inputSchema: myAccessInputSchema,\n async execute(_input, ctx) {\n const caller = tryResolveTenantCaller(ctx);\n if (!caller) {\n return {\n authenticated: false as const,\n message:\n \"No RobotRock user is attached to this session. Dashboard chat supplies user context via the Eve proxy.\",\n };\n }\n\n return {\n authenticated: true as const,\n tenantRole: caller.role,\n isTenantAdmin: caller.isAdmin,\n groupSlugs: caller.groups,\n capabilities: tenantCapabilities(caller.isAdmin),\n email: caller.email,\n tenantSlug: caller.tenantSlug,\n };\n },\n });\n}\n\nexport const myAccessTool = defineMyAccessTool();\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { tryResolveTenantCaller } from \"../../agent/tenant.js\";\n\nexport const WHOAMI_TOOL_NAME = \"whoami\";\n\nexport const whoamiInputSchema = z.object({});\n\nexport function defineWhoamiTool() {\n return defineTool({\n description:\n \"Return the authenticated RobotRock user, tenant, role, and group memberships for the current chat session.\",\n inputSchema: whoamiInputSchema,\n async execute(_input, ctx) {\n const caller = tryResolveTenantCaller(ctx);\n if (!caller) {\n return {\n authenticated: false as const,\n message:\n \"No RobotRock user is attached to this session. Dashboard chat supplies user context via the Eve proxy.\",\n };\n }\n\n return {\n authenticated: true as const,\n userId: caller.userId,\n name: caller.name,\n email: caller.email,\n tenantSlug: caller.tenantSlug,\n role: caller.role,\n isAdmin: caller.isAdmin,\n groups: caller.groups.map((slug) => ({ slug })),\n ...(caller.workosUserId ? { workosUserId: caller.workosUserId } : {}),\n sessionId: ctx.session.id,\n };\n },\n });\n}\n\nexport const whoamiTool = defineWhoamiTool();\n","import type { DefineCreateInboxTaskToolOptions } from \"./inbox/create-task.js\";\nimport {\n CREATE_INBOX_TASK_TOOL_NAME,\n createInboxTaskTool,\n defineCreateInboxTaskTool,\n} from \"./inbox/create-task.js\";\nimport {\n MY_ACCESS_TOOL_NAME,\n defineMyAccessTool,\n myAccessTool,\n} from \"./identity/my-access.js\";\nimport {\n WHOAMI_TOOL_NAME,\n defineWhoamiTool,\n whoamiTool,\n} from \"./identity/whoami.js\";\n\nexport type CreateRobotrockToolsOptions = {\n inbox?: false | DefineCreateInboxTaskToolOptions;\n identity?: boolean;\n};\n\n/** Register standard RobotRock Eve tools keyed by Eve tool slug. */\nexport function createRobotrockTools(\n options?: CreateRobotrockToolsOptions\n): Record<string, unknown> {\n const tools: Record<string, unknown> = {};\n\n if (options?.inbox !== false) {\n tools[CREATE_INBOX_TASK_TOOL_NAME] = defineCreateInboxTaskTool(\n options?.inbox === undefined ? undefined : options.inbox\n );\n }\n\n if (options?.identity !== false) {\n tools[WHOAMI_TOOL_NAME] = whoamiTool;\n tools[MY_ACCESS_TOOL_NAME] = myAccessTool;\n }\n\n return tools;\n}\n\nexport {\n CREATE_INBOX_TASK_TOOL_NAME,\n createInboxTaskInputSchema,\n defineCreateInboxTaskTool,\n createInboxTaskTool,\n} from \"./inbox/create-task.js\";\nexport type {\n CreateInboxTaskToolInput,\n DefineCreateInboxTaskToolOptions,\n} from \"./inbox/create-task.js\";\n\nexport {\n WHOAMI_TOOL_NAME,\n whoamiInputSchema,\n defineWhoamiTool,\n whoamiTool,\n} from \"./identity/whoami.js\";\n\nexport {\n MY_ACCESS_TOOL_NAME,\n myAccessInputSchema,\n defineMyAccessTool,\n myAccessTool,\n} from \"./identity/my-access.js\";\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,KAAAA,UAAS;;;ACDlB,SAAS,KAAAC,UAAS;;;ACAlB,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,kBAAkB,UAA0B;AACnD,SAAO,SAAS,YAAY,EAAE,QAAQ,YAAY,EAAE;AACtD;AAEA,SAAS,cAAc,MAAuB;AAC5C,QAAM,QAAQ,+CAA+C,KAAK,IAAI;AACtE,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,MAAM,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,SAAS,OAAO,IAAI,CAAC;AAC3D,MAAI,OAAO,KAAK,CAAC,UAAU,OAAO,MAAM,KAAK,KAAK,QAAQ,KAAK,QAAQ,GAAG,GAAG;AAC3E,WAAO;AAAA,EACT;AAEA,QAAM,CAAC,GAAG,GAAG,IAAI,EAAE,IAAI;AACvB,MAAI,MAAM,UAAa,MAAM,QAAW;AACtC,WAAO;AAAA,EACT;AACA,MAAI,MAAM,OAAO,MAAM,EAAG,QAAO;AACjC,MAAI,MAAM,GAAI,QAAO;AACrB,MAAI,MAAM,OAAO,MAAM,IAAK,QAAO;AACnC,MAAI,MAAM,OAAO,MAAM,IAAK,QAAO;AACnC,MAAI,MAAM,OAAO,KAAK,MAAM,KAAK,GAAI,QAAO;AAC5C,MAAI,MAAM,OAAO,KAAK,MAAM,KAAK,IAAK,QAA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AS;AAGX,IAAM,mBAAmB;AAEzB,IAAM,oBAAoBC,GAAE,OAAO,CAAC,CAAC;AAErC,SAAS,mBAAmB;AACjC,SAAOC,YAAW;AAAA,IAChB,aACE;AAAA,IACF,aAAa;AAAA,IACb,MAAM,QAAQ,QAAQ,KAAK;AACzB,YAAM,SAAS,uBAAuB,GAAG;AACzC,UAAI,CAAC,QAAQ;AACX,eAAO;AAAA,UACL,eAAe;AAAA,UACf,SACE;AAAA,QACJ;AAAA,MACF;AAEA,aAAO;AAAA,QACL,eAAe;AAAA,QACf,QAAQ,OAAO;AAAA,QACf,MAAM,OAAO;AAAA,QACb,OAAO,OAAO;AAAA,QACd,YAAY,OAAO;AAAA,QACnB,MAAM,OAAO;AAAA,QACb,SAAS,OAAO;AAAA,QAChB,QAAQ,OAAO,OAAO,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE;AAAA,QAC9C,GAAI,OAAO,eAAe,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;AAAA,QACnE,WAAW,IAAI,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEO,IAAM,aAAa,iBAAiB;;;AChBpC,SAAS,qBACd,SACyB;AACzB,QAAM,QAAiC,CAAC;AAExC,MAAI,SAAS,UAAU,OAAO;AAC5B,UAAM,2BAA2B,IAAI;AAAA,MACnC,SAAS,UAAU,SAAY,SAAY,QAAQ;AAAA,IACrD;AAAA,EACF;AAEA,MAAI,SAAS,aAAa,OAAO;AAC/B,UAAM,gBAAgB,IAAI;AAC1B,UAAM,mBAAmB,IAAI;AAAA,EAC/B;AAEA,SAAO;AACT;","names":["z","z","handlerUrlSchema","z","jsonSchema7Schema","uiSchemaSchema","webhookHandlerSchema","triggerHandlerSchema","handlerSchema","taskActionInputSchema","taskActionSchema","uiFieldSchemaSchema","contextUiSchema","contextDataSchema","TASK_CONTEXT_FORMAT_VERSION","taskContextObjectBaseSchema","normalizeTaskContextVersion","taskContextObjectSchema","refineContextPublicUrls","taskContextSchema","assignToSchema","threadUpdateMessageSchema","threadUpdateStatuses","threadUpdateStatusSchema","threadUpdateInputSchema","z","threadUpdateMessageSchema","threadUpdateStatusSchema","taskPriorities","taskPrioritySchema","agentTelemetrySchema","z","createTaskBodySchema","taskContextObjectBaseSchema","assignToSchema","taskPrioritySchema","threadUpdateInputSchema","normalizeTaskContextVersion","refineContextPublicUrls","z","z","TASK_CONTEXT_FORMAT_VERSION","createTaskBodySchema","warnedMissingAuth","warnedMissingAuth","z","assignToSchema","defineTool","z","z","defineTool","defineTool","z","z","defineTool"]}
@@ -0,0 +1,141 @@
1
+ import { S as SendToHumanActionInput } from './client-XTnFHGFE.js';
2
+ import { z } from 'zod';
3
+
4
+ /** One selectable option in an Eve HITL input request. */
5
+ type EveInputOption = {
6
+ readonly id: string;
7
+ readonly label: string;
8
+ readonly description?: string;
9
+ readonly style?: "danger" | "default" | "primary";
10
+ };
11
+ /** Eve HITL display mode — mirrors `InputRequest.display` from the eve runtime. */
12
+ type EveInputRequestDisplay = "confirmation" | "select" | "text";
13
+ /**
14
+ * Minimal Eve `InputRequest` shape for RobotRock bridging. Intentionally
15
+ * self-contained so the SDK does not depend on the `eve` package.
16
+ */
17
+ type EveInputRequest = {
18
+ readonly requestId: string;
19
+ readonly prompt: string;
20
+ readonly display?: EveInputRequestDisplay;
21
+ readonly allowFreeform?: boolean;
22
+ readonly options?: readonly EveInputOption[];
23
+ };
24
+ /** Eve `InputResponse` shape returned when resuming a parked session. */
25
+ type EveInputResponse = {
26
+ readonly requestId: string;
27
+ readonly optionId?: string;
28
+ readonly text?: string;
29
+ };
30
+ declare const EVE_INPUT_SUBMIT_ACTION_ID: "submit";
31
+ declare const EVE_INPUT_OTHER_CHOICE_ID: "__other__";
32
+ declare const EVE_INPUT_OTHER_CHOICE_LABEL: "Type your own answer";
33
+ /** Resolve the effective display mode when Eve omits `display`. */
34
+ declare function resolveEveInputDisplay(request: EveInputRequest, toolName?: string): EveInputRequestDisplay;
35
+ /** Keep select-form submissions mutually exclusive between preset choice and freeform other. */
36
+ declare function normalizeEveSelectFormData(data: Record<string, unknown>): Record<string, unknown>;
37
+ /**
38
+ * Map an Eve `InputRequest` to RobotRock inbox actions.
39
+ */
40
+ declare function eveInputRequestToActions(request: EveInputRequest, options?: {
41
+ toolName?: string;
42
+ }): readonly SendToHumanActionInput[];
43
+ /** Task type slug for an Eve input request. */
44
+ declare function eveInputRequestTaskType(request: EveInputRequest, options?: {
45
+ toolName?: string;
46
+ }): string;
47
+ /**
48
+ * Map a handled RobotRock task action back to an Eve `InputResponse`.
49
+ */
50
+ declare function taskHandledToEveInputResponse(request: EveInputRequest, actionId: string, actionData: unknown, options?: {
51
+ toolName?: string;
52
+ }): EveInputResponse;
53
+
54
+ type EveInputAuditContext = {
55
+ toolCallId: string;
56
+ toolName?: string;
57
+ requestId?: string;
58
+ display?: EveInputRequestDisplay;
59
+ toolInput?: unknown;
60
+ };
61
+ /**
62
+ * Map freeform composer text to an Eve `InputResponse`, mirroring Eve's
63
+ * `resolveTextToResponse` rules (option id/label, numeric index, freeform text).
64
+ */
65
+ declare function resolveEveFreeformTextToInputResponse(request: EveInputRequest, text: string): EveInputResponse | undefined;
66
+ /** Returns true for Eve's default approval gate (approve / deny options). */
67
+ declare function isEveApprovalInputRequest(request: EveInputRequest): boolean;
68
+ type EveInputActionSubmission = {
69
+ actionId: string;
70
+ actionTitle: string;
71
+ formData: Record<string, unknown>;
72
+ };
73
+ /**
74
+ * Map a resolved Eve `InputResponse` to RobotRock audit fields (action id/title).
75
+ */
76
+ declare function eveInputResponseToActionSubmission(request: EveInputRequest, response: EveInputResponse, options?: {
77
+ toolName?: string;
78
+ }): EveInputActionSubmission;
79
+ /** Audit payload for `chat_action_input_submitted`. */
80
+ declare function buildEveInputAuditSubmissionData(context: EveInputAuditContext, formData: Record<string, unknown>): Record<string, unknown>;
81
+ /**
82
+ * Parse an `ask_question` tool result output into an Eve input response shape.
83
+ */
84
+ declare function parseEveAskQuestionToolOutput(output: unknown): Pick<EveInputResponse, "optionId" | "text"> | null;
85
+
86
+ /** Default per-tool labels for common Eve demo/integration tools. */
87
+ declare const DEFAULT_TOOL_DISPLAY_LABELS: Readonly<Record<string, string>>;
88
+ /** Register additional or overriding tool display labels at runtime. */
89
+ declare function setToolDisplayLabelOverrides(overrides: Readonly<Record<string, string>>): void;
90
+ /** Resolve a user-facing label for a tool slug. */
91
+ declare function getToolDisplayLabel(toolName: string): string;
92
+ /** Format an Eve input request prompt for human-facing approval UIs. */
93
+ declare function formatEveApprovalTitle(request: EveInputRequest, toolName?: string): string;
94
+
95
+ declare const robotRockWebhookPayloadBodySchema: z.ZodObject<{
96
+ taskId: z.ZodString;
97
+ action: z.ZodObject<{
98
+ id: z.ZodString;
99
+ title: z.ZodString;
100
+ data: z.ZodUnknown;
101
+ }, z.core.$strip>;
102
+ handledBy: z.ZodOptional<z.ZodString>;
103
+ handledAt: z.ZodString;
104
+ handlerType: z.ZodString;
105
+ }, z.core.$strip>;
106
+ type RobotRockWebhookPayload = z.infer<typeof robotRockWebhookPayloadBodySchema> & {
107
+ headers: Record<string, string>;
108
+ };
109
+ type RobotRockWebhookErrorCode = "MISSING_WEBHOOK_SECRET" | "MISSING_SIGNATURE" | "INVALID_SIGNATURE" | "INVALID_JSON" | "INVALID_PAYLOAD";
110
+ declare class RobotRockWebhookError extends Error {
111
+ readonly code: RobotRockWebhookErrorCode;
112
+ readonly details?: unknown | undefined;
113
+ constructor(message: string, code: RobotRockWebhookErrorCode, details?: unknown | undefined);
114
+ }
115
+ interface VerifyRobotRockWebhookOptions {
116
+ /**
117
+ * Override shared secret (defaults to ROBOTROCK_WEBHOOK_SECRET).
118
+ * Keep undefined in production to enforce the canonical env var.
119
+ */
120
+ secret?: string;
121
+ /**
122
+ * Resolve the tenant signing secret by public task id (hosted MCP uses Convex).
123
+ * Used when secret is not passed explicitly.
124
+ */
125
+ resolveSecret?: (taskId: string) => Promise<string | undefined>;
126
+ /** Signature header to read. @default "x-robotrock-signature" */
127
+ signatureHeader?: string;
128
+ }
129
+ /**
130
+ * Verify a RobotRock webhook request and return a validated payload.
131
+ * Throws RobotRockWebhookError with machine-readable `code` for audit logging.
132
+ */
133
+ declare function verifyRobotRockWebhook(request: Request, options?: VerifyRobotRockWebhookOptions): Promise<RobotRockWebhookPayload>;
134
+
135
+ /** Build the assistant resume prompt when an inbox task linked to a chat is handled. */
136
+ declare function buildTaskHandledResumeMessage(payload: RobotRockWebhookPayload): string;
137
+
138
+ /** Hook slug advertised in GET /eve/v1/info for RobotRock-ready auto-detection. */
139
+ declare const ROBOTROCK_READY_HOOK_SLUG = "robotrock-ready";
140
+
141
+ export { DEFAULT_TOOL_DISPLAY_LABELS as D, EVE_INPUT_OTHER_CHOICE_ID as E, ROBOTROCK_READY_HOOK_SLUG as R, type VerifyRobotRockWebhookOptions as V, EVE_INPUT_OTHER_CHOICE_LABEL as a, EVE_INPUT_SUBMIT_ACTION_ID as b, type EveInputOption as c, type EveInputRequest as d, type EveInputRequestDisplay as e, type EveInputResponse as f, RobotRockWebhookError as g, type RobotRockWebhookErrorCode as h, type RobotRockWebhookPayload as i, buildTaskHandledResumeMessage as j, eveInputRequestTaskType as k, eveInputRequestToActions as l, formatEveApprovalTitle as m, getToolDisplayLabel as n, normalizeEveSelectFormData as o, type EveInputActionSubmission as p, type EveInputAuditContext as q, resolveEveInputDisplay as r, setToolDisplayLabelOverrides as s, taskHandledToEveInputResponse as t, buildEveInputAuditSubmissionData as u, verifyRobotRockWebhook as v, eveInputResponseToActionSubmission as w, isEveApprovalInputRequest as x, parseEveAskQuestionToolOutput as y, resolveEveFreeformTextToInputResponse as z };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { R as RobotRock, b as RobotRockConfig } from './client-CzVmjXpz.js';
2
- export { C as ChatsApi, c as CloseChatOptions, d as CreateChatInput, e as CreateChatResult, f as CreatedChat, g as RobotRockAdvancedConfig, h as RobotRockPollingClientConfig, i as RobotRockPollingOptions, j as RobotRockWebhookClientConfig, k as RobotRockWebhookConfig, S as SendToHumanActionInput, a as SendToHumanInput, l as SendToHumanResult, m as SendToHumanValidUntil, n as SendUpdateInput, T as TasksApi, o as attachWebhookToActions, p as createChatsApi, q as createClient } from './client-CzVmjXpz.js';
1
+ import { R as RobotRock, b as RobotRockConfig } from './client-XTnFHGFE.js';
2
+ export { C as ChatsApi, c as CloseChatOptions, d as CreateChatInput, e as CreateChatResult, f as CreatedChat, g as RobotRockAdvancedConfig, h as RobotRockPollingClientConfig, i as RobotRockPollingOptions, j as RobotRockWebhookClientConfig, k as RobotRockWebhookConfig, S as SendToHumanActionInput, a as SendToHumanInput, l as SendToHumanResult, m as SendToHumanValidUntil, n as SendUpdateInput, o as StageChatHitlRequestsInput, p as StagedChatHitlRequest, T as TasksApi, q as attachWebhookToActions, r as createChatsApi, s as createClient } from './client-XTnFHGFE.js';
3
3
  export { AgentChatSeedMessage, CreateAgentChatBody, CreateAgentChatBodyInput, agentChatSeedMessageSchema, createAgentChatBodySchema } from '@robotrock/core';
4
4
  import { Task, DiscriminatedApprovalResult } from './schemas/index.js';
5
5
  export { AgentTelemetry, AgentTelemetryInput, ApprovalResult, AssignToInput, CreateTaskBody, CreateTaskBodyInput, DEFAULT_TASK_PRIORITY, DEFAULT_THREAD_UPDATE_STATUS, Handler, InferActionData, LOWEST_TASK_PRIORITY, TASK_CONTEXT_FORMAT_VERSION, TASK_PRIORITY_RANK, TaskAction, TaskContext, TaskContextFormatVersion, TaskContextInput, TaskPriority, TaskResponse, TaskResult, TaskStatus, ThreadUpdate, ThreadUpdateBody, ThreadUpdateBodyInput, ThreadUpdateInput, ThreadUpdateResponse, ThreadUpdateSource, ThreadUpdateStatus, TriggerHandler, TupleElementIndices, WebhookHandler, agentTelemetrySchema, assignToSchema, createTaskBodySchema, taskContextSchema, taskPriorities, taskPrioritySchema, threadUpdateBodySchema, threadUpdateInputSchema, threadUpdateStatusSchema, threadUpdateStatuses } from './schemas/index.js';
6
- import { z } from 'zod';
6
+ export { D as DEFAULT_TOOL_DISPLAY_LABELS, E as EVE_INPUT_OTHER_CHOICE_ID, a as EVE_INPUT_OTHER_CHOICE_LABEL, b as EVE_INPUT_SUBMIT_ACTION_ID, c as EveInputOption, d as EveInputRequest, e as EveInputRequestDisplay, f as EveInputResponse, R as ROBOTROCK_READY_HOOK_SLUG, g as RobotRockWebhookError, h as RobotRockWebhookErrorCode, i as RobotRockWebhookPayload, V as VerifyRobotRockWebhookOptions, j as buildTaskHandledResumeMessage, k as eveInputRequestTaskType, l as eveInputRequestToActions, m as formatEveApprovalTitle, n as getToolDisplayLabel, o as normalizeEveSelectFormData, r as resolveEveInputDisplay, s as setToolDisplayLabelOverrides, t as taskHandledToEveInputResponse, v as verifyRobotRockWebhook } from './index-BL9qKHA8.js';
7
7
  export { E as EndRobotRockHumanWaitSpanOptions, b as RobotRockCreatedTask, c as RobotRockHandledOtelInput, a as RobotRockHandlerWebhookPayload, d as RobotRockHumanWaitOtelSession, e as RobotRockOtelHandle, f as RobotRockOtelRecordOptions, R as RobotRockPlatformOtelFields, g as beginRobotRockHumanWaitOtel, h as captureRobotRockOtelHandle, i as endRobotRockHumanWaitSpan, j as finishRobotRockHumanWaitOtel, r as recordRobotRockHandledToOtel, s as shouldRecordRobotRockOtel, k as startRobotRockHumanWaitSpan, l as stripPlatformOtelFields, t as toRobotRockHandledOtelInput } from './otel-platform-DzHyHkGk.js';
8
+ import 'zod';
8
9
  import '@opentelemetry/api';
9
10
 
10
11
  declare class RobotRockError extends Error {
@@ -105,44 +106,4 @@ declare function assertNotPlatformRejectRequest(actionId: string, data?: unknown
105
106
  */
106
107
  declare function shouldStopAgentForHandledAction(actionId: string | undefined): boolean;
107
108
 
108
- declare const robotRockWebhookPayloadBodySchema: z.ZodObject<{
109
- taskId: z.ZodString;
110
- action: z.ZodObject<{
111
- id: z.ZodString;
112
- title: z.ZodString;
113
- data: z.ZodUnknown;
114
- }, z.core.$strip>;
115
- handledBy: z.ZodOptional<z.ZodString>;
116
- handledAt: z.ZodString;
117
- handlerType: z.ZodString;
118
- }, z.core.$strip>;
119
- type RobotRockWebhookPayload = z.infer<typeof robotRockWebhookPayloadBodySchema> & {
120
- headers: Record<string, string>;
121
- };
122
- type RobotRockWebhookErrorCode = "MISSING_WEBHOOK_SECRET" | "MISSING_SIGNATURE" | "INVALID_SIGNATURE" | "INVALID_JSON" | "INVALID_PAYLOAD";
123
- declare class RobotRockWebhookError extends Error {
124
- readonly code: RobotRockWebhookErrorCode;
125
- readonly details?: unknown | undefined;
126
- constructor(message: string, code: RobotRockWebhookErrorCode, details?: unknown | undefined);
127
- }
128
- interface VerifyRobotRockWebhookOptions {
129
- /**
130
- * Override shared secret (defaults to ROBOTROCK_WEBHOOK_SECRET).
131
- * Keep undefined in production to enforce the canonical env var.
132
- */
133
- secret?: string;
134
- /**
135
- * Resolve the tenant signing secret by public task id (hosted MCP uses Convex).
136
- * Used when secret is not passed explicitly.
137
- */
138
- resolveSecret?: (taskId: string) => Promise<string | undefined>;
139
- /** Signature header to read. @default "x-robotrock-signature" */
140
- signatureHeader?: string;
141
- }
142
- /**
143
- * Verify a RobotRock webhook request and return a validated payload.
144
- * Throws RobotRockWebhookError with machine-readable `code` for audit logging.
145
- */
146
- declare function verifyRobotRockWebhook(request: Request, options?: VerifyRobotRockWebhookOptions): Promise<RobotRockWebhookPayload>;
147
-
148
- export { DiscriminatedApprovalResult, type HandledActionInput, type HandledOutcome, PLATFORM_MARK_DONE_ACTION_ID, PLATFORM_MARK_DONE_ACTION_TITLE, PLATFORM_REJECT_REQUEST_ACTION_ID, PLATFORM_REJECT_REQUEST_ACTION_TITLE, PLATFORM_TERMINAL_ACTION_IDS, type PlatformMarkDoneOutcome, type PlatformRejectRequestData, PlatformRejectRequestError, type PlatformRejectRequestOutcome, type PlatformTerminalActionId, RobotRock, RobotRockConfig, RobotRockError, RobotRockWebhookError, type RobotRockWebhookErrorCode, type RobotRockWebhookPayload, Task, type TaskActionOutcome, TaskExpiredError, TaskTimeoutError, type VerifyRobotRockWebhookOptions, assertNotPlatformRejectRequest, isPlatformMarkDoneAction, isPlatformRejectRequestAction, isPlatformTerminalAction, parseHandledOutcome, parsePlatformRejectRequestData, resolveRobotRockClient, resolveRobotRockConfig, shouldStopAgentForHandledAction, toDiscriminatedApprovalResult, verifyRobotRockWebhook };
109
+ export { DiscriminatedApprovalResult, type HandledActionInput, type HandledOutcome, PLATFORM_MARK_DONE_ACTION_ID, PLATFORM_MARK_DONE_ACTION_TITLE, PLATFORM_REJECT_REQUEST_ACTION_ID, PLATFORM_REJECT_REQUEST_ACTION_TITLE, PLATFORM_TERMINAL_ACTION_IDS, type PlatformMarkDoneOutcome, type PlatformRejectRequestData, PlatformRejectRequestError, type PlatformRejectRequestOutcome, type PlatformTerminalActionId, RobotRock, RobotRockConfig, RobotRockError, Task, type TaskActionOutcome, TaskExpiredError, TaskTimeoutError, assertNotPlatformRejectRequest, isPlatformMarkDoneAction, isPlatformRejectRequestAction, isPlatformTerminalAction, parseHandledOutcome, parsePlatformRejectRequestData, resolveRobotRockClient, resolveRobotRockConfig, shouldStopAgentForHandledAction, toDiscriminatedApprovalResult };