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,1557 @@
1
+ // src/eve/tools/inbox/create-task.ts
2
+ import { defineTool } from "eve/tools";
3
+ import { z as z4 } from "zod";
4
+
5
+ // src/schemas/index.ts
6
+ import { z as z2 } from "zod";
7
+
8
+ // ../core/src/utils/safe-url.ts
9
+ var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
10
+ "localhost",
11
+ "metadata.google.internal",
12
+ "metadata.goog"
13
+ ]);
14
+ function normalizeHostname(hostname) {
15
+ return hostname.toLowerCase().replace(/^\[|\]$/g, "");
16
+ }
17
+ function isBlockedIpv4(host) {
18
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
19
+ if (!match) {
20
+ return false;
21
+ }
22
+ const octets = match.slice(1, 5).map((part) => Number(part));
23
+ if (octets.some((octet) => Number.isNaN(octet) || octet < 0 || octet > 255)) {
24
+ return true;
25
+ }
26
+ const [a, b, _c, _d] = octets;
27
+ if (a === void 0 || b === void 0) {
28
+ return true;
29
+ }
30
+ if (a === 127 || a === 0) return true;
31
+ if (a === 10) return true;
32
+ if (a === 169 && b === 254) return true;
33
+ if (a === 192 && b === 168) return true;
34
+ if (a === 172 && b >= 16 && b <= 31) return true;
35
+ if (a === 100 && b >= 64 && b <= 127) return true;
36
+ return false;
37
+ }
38
+ function ipv4FromNumericHost(host) {
39
+ if (/^\d+$/.test(host)) {
40
+ const num = Number(host);
41
+ if (!Number.isFinite(num) || num < 0 || num > 4294967295) {
42
+ return null;
43
+ }
44
+ const a = num >>> 24 & 255;
45
+ const b = num >>> 16 & 255;
46
+ const c = num >>> 8 & 255;
47
+ const d = num & 255;
48
+ return `${a}.${b}.${c}.${d}`;
49
+ }
50
+ const hexMatch = /^0x([0-9a-f]{1,8})$/i.exec(host);
51
+ if (hexMatch) {
52
+ const num = Number.parseInt(hexMatch[1], 16);
53
+ if (!Number.isFinite(num) || num < 0 || num > 4294967295) {
54
+ return null;
55
+ }
56
+ const a = num >>> 24 & 255;
57
+ const b = num >>> 16 & 255;
58
+ const c = num >>> 8 & 255;
59
+ const d = num & 255;
60
+ return `${a}.${b}.${c}.${d}`;
61
+ }
62
+ return null;
63
+ }
64
+ function isBlockedIpv4Mapped(host) {
65
+ const mappedDotted = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(host);
66
+ if (mappedDotted) {
67
+ return isBlockedIpv4(mappedDotted[1]);
68
+ }
69
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(host);
70
+ if (mappedHex) {
71
+ const high = Number.parseInt(mappedHex[1], 16);
72
+ const low = Number.parseInt(mappedHex[2], 16);
73
+ if (Number.isFinite(high) && Number.isFinite(low)) {
74
+ const a = high >> 8 & 255;
75
+ const b = high & 255;
76
+ const c = low >> 8 & 255;
77
+ const d = low & 255;
78
+ return isBlockedIpv4(`${a}.${b}.${c}.${d}`);
79
+ }
80
+ }
81
+ return false;
82
+ }
83
+ function isBlockedIpv6(host) {
84
+ if (host === "::1" || host === "0:0:0:0:0:0:0:1") {
85
+ return true;
86
+ }
87
+ if (host.startsWith("fc") || host.startsWith("fd")) {
88
+ return true;
89
+ }
90
+ if (host.startsWith("fe80:")) {
91
+ return true;
92
+ }
93
+ if (isBlockedIpv4Mapped(host)) {
94
+ return true;
95
+ }
96
+ return false;
97
+ }
98
+ function isBlockedHostname(hostname) {
99
+ const host = normalizeHostname(hostname);
100
+ if (!host) {
101
+ return true;
102
+ }
103
+ if (BLOCKED_HOSTNAMES.has(host)) {
104
+ return true;
105
+ }
106
+ if (host.endsWith(".localhost") || host.endsWith(".local")) {
107
+ return true;
108
+ }
109
+ const numericIpv4 = ipv4FromNumericHost(host);
110
+ if (numericIpv4 && isBlockedIpv4(numericIpv4)) {
111
+ return true;
112
+ }
113
+ return isBlockedIpv4(host) || isBlockedIpv6(host);
114
+ }
115
+ function isLoopbackHandlerUrl(urlString) {
116
+ let url;
117
+ try {
118
+ url = new URL(urlString);
119
+ } catch {
120
+ return false;
121
+ }
122
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
123
+ return false;
124
+ }
125
+ if (url.username || url.password) {
126
+ return false;
127
+ }
128
+ const host = url.hostname.toLowerCase();
129
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]" || host.endsWith(".localhost");
130
+ }
131
+ function isAllowedHandlerUrl(urlString) {
132
+ return isPublicHttpUrl(urlString) || isLoopbackHandlerUrl(urlString);
133
+ }
134
+ function isPublicHttpUrl(urlString) {
135
+ let url;
136
+ try {
137
+ url = new URL(urlString);
138
+ } catch {
139
+ return false;
140
+ }
141
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
142
+ return false;
143
+ }
144
+ if (url.username || url.password) {
145
+ return false;
146
+ }
147
+ return !isBlockedHostname(url.hostname);
148
+ }
149
+ var PUBLIC_HTTP_URL_ERROR = "URL must be a public http:// or https:// address";
150
+ var HANDLER_URL_ERROR = "Handler URL must be a public or loopback http:// or https:// address";
151
+
152
+ // ../core/src/schemas/task.ts
153
+ import { z } from "zod";
154
+
155
+ // ../core/src/schemas/context-urls.ts
156
+ function resolveLinkUrl(value) {
157
+ return value.startsWith("http://") || value.startsWith("https://") ? value : `https://${value}`;
158
+ }
159
+ function widgetType(ui, field) {
160
+ const fieldUi = ui?.[field];
161
+ if (typeof fieldUi !== "object" || fieldUi === null) {
162
+ return void 0;
163
+ }
164
+ const widget = fieldUi["ui:widget"];
165
+ return typeof widget === "string" ? widget : void 0;
166
+ }
167
+ function validateUrlValue(value, widget) {
168
+ if (widget === "image" || widget === "link") {
169
+ if (typeof value !== "string") {
170
+ return PUBLIC_HTTP_URL_ERROR;
171
+ }
172
+ const url = widget === "link" ? resolveLinkUrl(value) : value;
173
+ if (!isPublicHttpUrl(url)) {
174
+ return PUBLIC_HTTP_URL_ERROR;
175
+ }
176
+ return null;
177
+ }
178
+ if (widget === "attachments" && Array.isArray(value)) {
179
+ for (const item of value) {
180
+ if (typeof item !== "object" || item === null) {
181
+ continue;
182
+ }
183
+ const url = item.url;
184
+ if (typeof url === "string" && !isPublicHttpUrl(resolveLinkUrl(url))) {
185
+ return PUBLIC_HTTP_URL_ERROR;
186
+ }
187
+ }
188
+ }
189
+ return null;
190
+ }
191
+ function validateContextPublicUrls(context) {
192
+ if (!context?.data) {
193
+ return null;
194
+ }
195
+ for (const [field, value] of Object.entries(context.data)) {
196
+ const widget = widgetType(context.ui, field);
197
+ if (!widget) {
198
+ continue;
199
+ }
200
+ const error = validateUrlValue(value, widget);
201
+ if (error) {
202
+ return `context.data.${field}: ${error}`;
203
+ }
204
+ }
205
+ return null;
206
+ }
207
+
208
+ // ../core/src/schemas/task.ts
209
+ var safeUrlSchema = z.string().refine((url) => isPublicHttpUrl(url), {
210
+ message: PUBLIC_HTTP_URL_ERROR
211
+ });
212
+ var handlerUrlSchema = z.string().refine((url) => isAllowedHandlerUrl(url), {
213
+ message: HANDLER_URL_ERROR
214
+ });
215
+ var jsonSchema7Schema = z.custom(
216
+ (val) => typeof val === "object" && val !== null,
217
+ { message: "Must be a valid JSON Schema object" }
218
+ );
219
+ var uiSchemaSchema = z.custom((val) => typeof val === "object" && val !== null, {
220
+ message: "Must be a valid UiSchema object"
221
+ });
222
+ var webhookHandlerSchema = z.object({
223
+ type: z.literal("webhook"),
224
+ url: handlerUrlSchema,
225
+ headers: z.record(z.string(), z.string())
226
+ });
227
+ var triggerHandlerSchema = webhookHandlerSchema.extend({
228
+ type: z.literal("trigger"),
229
+ tokenId: z.string().min(1)
230
+ });
231
+ var handlerSchema = z.discriminatedUnion("type", [webhookHandlerSchema, triggerHandlerSchema]);
232
+ var taskActionInputSchema = z.object({
233
+ id: z.string().min(1),
234
+ title: z.string().min(1),
235
+ description: z.string().optional(),
236
+ schema: jsonSchema7Schema.optional(),
237
+ ui: uiSchemaSchema.optional(),
238
+ data: z.record(z.string(), z.unknown()).optional()
239
+ });
240
+ var taskActionSchema = taskActionInputSchema.extend({
241
+ // Optional handlers for this action - if present, must have at least 1
242
+ handlers: z.array(handlerSchema).min(1).optional()
243
+ });
244
+ var uiFieldSchemaSchema = z.object({
245
+ "ui:widget": z.string().optional(),
246
+ "ui:title": z.string().optional(),
247
+ "ui:description": z.string().optional(),
248
+ "ui:options": z.record(z.string(), z.unknown()).optional(),
249
+ items: z.lazy(() => z.record(z.string(), uiFieldSchemaSchema)).optional()
250
+ }).passthrough();
251
+ var contextUiSchema = z.record(z.string(), uiFieldSchemaSchema).optional();
252
+ var contextDataSchema = z.object({
253
+ data: z.record(z.string(), z.unknown()),
254
+ ui: contextUiSchema
255
+ }).optional();
256
+ var TASK_CONTEXT_FORMAT_VERSION = 2;
257
+ var taskContextObjectBaseSchema = z.object({
258
+ /** Source application id; omitted tasks are grouped in the default inbox. */
259
+ app: z.string().min(1).optional(),
260
+ type: z.string().min(1),
261
+ name: z.string().min(1),
262
+ description: z.string().optional(),
263
+ validUntil: z.string().optional(),
264
+ context: contextDataSchema,
265
+ /** Task context wire format version. @default 2 */
266
+ contextVersion: z.literal(2).optional(),
267
+ /** @deprecated Use `contextVersion`. Accepted on ingest only. */
268
+ version: z.literal(2).optional(),
269
+ actions: z.array(taskActionSchema).min(1, "At least one action is required")
270
+ });
271
+ function normalizeTaskContextVersion(data) {
272
+ const { version: legacyVersion, contextVersion, ...rest } = data;
273
+ return {
274
+ ...rest,
275
+ contextVersion: contextVersion ?? legacyVersion ?? TASK_CONTEXT_FORMAT_VERSION
276
+ };
277
+ }
278
+ var taskContextObjectSchema = taskContextObjectBaseSchema.transform(
279
+ normalizeTaskContextVersion
280
+ );
281
+ function refineContextPublicUrls(data, ctx) {
282
+ const error = validateContextPublicUrls(data.context);
283
+ if (error) {
284
+ ctx.addIssue({
285
+ code: z.ZodIssueCode.custom,
286
+ message: error,
287
+ path: ["context"]
288
+ });
289
+ }
290
+ }
291
+ var taskContextSchema = taskContextObjectSchema.superRefine(
292
+ refineContextPublicUrls
293
+ );
294
+ var assignToSchema = z.object({
295
+ users: z.array(z.string().email()).optional(),
296
+ groups: z.array(z.string().min(1)).optional()
297
+ }).refine(
298
+ (data) => {
299
+ const groups = data.groups ?? [];
300
+ if (groups.includes("all") && groups.length > 1) {
301
+ return false;
302
+ }
303
+ return true;
304
+ },
305
+ { message: 'Cannot combine "all" with other group slugs' }
306
+ );
307
+ var threadUpdateMessageSchema = z.string().min(1).max(500);
308
+ var threadUpdateStatuses = [
309
+ "info",
310
+ "queued",
311
+ "running",
312
+ "waiting",
313
+ "succeeded",
314
+ "failed",
315
+ "cancelled"
316
+ ];
317
+ var threadUpdateStatusSchema = z.enum(threadUpdateStatuses);
318
+ var threadUpdateInputSchema = z.object({
319
+ message: threadUpdateMessageSchema,
320
+ status: threadUpdateStatusSchema.optional()
321
+ });
322
+ var taskPriorities = ["low", "normal", "high", "urgent"];
323
+ var taskPrioritySchema = z.enum(taskPriorities);
324
+ var agentTelemetrySchema = z.object({
325
+ /** Agent or app version (semver, git SHA, deploy tag — caller-defined). */
326
+ version: z.string().min(1)
327
+ });
328
+ var createTaskBodySchema = taskContextObjectBaseSchema.extend({
329
+ assignTo: assignToSchema.optional(),
330
+ /**
331
+ * Groups related tasks together. When omitted, the server generates one and
332
+ * returns it so the caller can reuse it on later tasks in the same thread.
333
+ */
334
+ threadId: z.string().min(1).optional(),
335
+ /**
336
+ * Optional thread priority. When set, applies to the whole thread and
337
+ * overwrites any previous priority. Omit on later tasks to leave unchanged.
338
+ */
339
+ priority: taskPrioritySchema.optional(),
340
+ /**
341
+ * Optional initial status update logged against the task's thread. Shows in
342
+ * the inbox status bar and the thread update log.
343
+ */
344
+ update: threadUpdateInputSchema.optional(),
345
+ /** Agent release version — not shown in inbox UI. */
346
+ agent: agentTelemetrySchema.optional()
347
+ }).transform(normalizeTaskContextVersion).superRefine(refineContextPublicUrls);
348
+ var agentChatSeedActionSchema = z.object({
349
+ /** Stable action id echoed back on submit; auto-derived from title when omitted. */
350
+ id: z.string().min(1).optional(),
351
+ title: z.string().min(1),
352
+ description: z.string().optional(),
353
+ /** JSON Schema object for the form fields. */
354
+ schema: z.record(z.string(), z.unknown()).optional(),
355
+ /** RJSF ui schema overrides (ui:widget, ui:enumNames, etc.). */
356
+ ui: z.record(z.string(), z.unknown()).optional(),
357
+ /** Optional default field values. */
358
+ data: z.record(z.string(), z.unknown()).optional()
359
+ });
360
+ var agentChatSeedMessageSchema = z.object({
361
+ role: z.enum(["user", "assistant"]),
362
+ text: z.string().min(1),
363
+ /** Optional display-name override for the message sender. */
364
+ senderName: z.string().min(1).optional(),
365
+ /**
366
+ * Optional structured input request rendered as a styled RobotRock action
367
+ * widget below the message text. Use this instead of asking the user to reply
368
+ * in plain text so the request is always a proper action form.
369
+ */
370
+ requestActionInput: z.object({
371
+ prompt: z.string().optional(),
372
+ action: agentChatSeedActionSchema
373
+ }).optional()
374
+ });
375
+ var eveAgentChatTransportSchema = z.object({
376
+ kind: z.literal("eve"),
377
+ chatId: z.string().min(1),
378
+ baseUrl: z.string().url(),
379
+ sessionId: z.string().optional(),
380
+ continuationToken: z.string().optional(),
381
+ streamIndex: z.number().int().nonnegative().optional(),
382
+ isStreaming: z.boolean().optional()
383
+ });
384
+ var createAgentChatBodySchema = z.object({
385
+ /** Agent id (eve agent name). Required unless `parentChatId` is set. */
386
+ agentIdentifier: z.string().min(1).optional(),
387
+ /** Inherit tenant/connection/agent from an existing chat (agent-spawned chats). */
388
+ parentChatId: z.string().min(1).optional(),
389
+ /** Convex tenantEveConnections id; resolved from the tenant when omitted. */
390
+ eveConnectionId: z.string().min(1).optional(),
391
+ /** Source application id; groups the chat under an inbox section. */
392
+ app: z.string().min(1).optional(),
393
+ assignTo: assignToSchema.optional(),
394
+ title: z.string().min(1),
395
+ messages: z.array(agentChatSeedMessageSchema).default([]),
396
+ /** Provenance label stored on the session ("cron" | "agent" | ...). */
397
+ source: z.string().min(1).optional()
398
+ }).refine((data) => Boolean(data.agentIdentifier || data.parentChatId), {
399
+ message: "Provide either agentIdentifier or parentChatId"
400
+ });
401
+ var agentChatAuditInputBodySchema = z.object({
402
+ eveSessionId: z.string().min(1),
403
+ userId: z.string().min(1),
404
+ actionId: z.string().min(1),
405
+ actionTitle: z.string().optional(),
406
+ prompt: z.string().optional(),
407
+ data: z.record(z.string(), z.unknown()).optional(),
408
+ idempotencyKey: z.string().optional(),
409
+ /** Eve input request id — used to merge staged HITL metadata. */
410
+ requestId: z.string().optional(),
411
+ /** Eve tool call id — fallback lookup for staged HITL metadata. */
412
+ toolCallId: z.string().optional()
413
+ });
414
+ var eveHitlStagedOptionSchema = z.object({
415
+ id: z.string(),
416
+ label: z.string()
417
+ });
418
+ var agentChatStageHitlBodySchema = z.object({
419
+ eveSessionId: z.string().min(1),
420
+ requests: z.array(
421
+ z.object({
422
+ requestId: z.string().min(1),
423
+ toolCallId: z.string().min(1),
424
+ toolName: z.string().min(1),
425
+ prompt: z.string().min(1),
426
+ display: z.enum(["confirmation", "select", "text"]).optional(),
427
+ allowFreeform: z.boolean().optional(),
428
+ options: z.array(eveHitlStagedOptionSchema).optional(),
429
+ toolInput: z.record(z.string(), z.unknown()).optional()
430
+ })
431
+ )
432
+ });
433
+ var agentChatLinkTaskBodySchema = z.object({
434
+ eveSessionId: z.string().min(1),
435
+ publicTaskId: z.string().min(1),
436
+ toolCallId: z.string().min(1)
437
+ });
438
+
439
+ // src/schemas/index.ts
440
+ var handlerUrlSchema2 = z2.string().refine((url) => isAllowedHandlerUrl(url), {
441
+ message: HANDLER_URL_ERROR
442
+ });
443
+ var jsonSchema7Schema2 = z2.custom(
444
+ (val) => typeof val === "object" && val !== null,
445
+ { message: "Must be a valid JSON Schema object" }
446
+ );
447
+ var uiSchemaSchema2 = z2.custom((val) => typeof val === "object" && val !== null, {
448
+ message: "Must be a valid UiSchema object"
449
+ });
450
+ var webhookHandlerSchema2 = z2.object({
451
+ type: z2.literal("webhook"),
452
+ url: handlerUrlSchema2,
453
+ headers: z2.record(z2.string(), z2.string())
454
+ });
455
+ var triggerHandlerSchema2 = webhookHandlerSchema2.extend({
456
+ type: z2.literal("trigger"),
457
+ tokenId: z2.string().min(1)
458
+ });
459
+ var handlerSchema2 = z2.discriminatedUnion("type", [webhookHandlerSchema2, triggerHandlerSchema2]);
460
+ var taskActionInputSchema2 = z2.object({
461
+ id: z2.string().min(1),
462
+ title: z2.string().min(1),
463
+ description: z2.string().optional(),
464
+ schema: jsonSchema7Schema2.optional(),
465
+ ui: uiSchemaSchema2.optional(),
466
+ data: z2.record(z2.string(), z2.unknown()).optional()
467
+ });
468
+ var taskActionSchema2 = taskActionInputSchema2.extend({
469
+ handlers: z2.array(handlerSchema2).min(1).optional()
470
+ });
471
+ var uiFieldSchemaSchema2 = z2.object({
472
+ "ui:widget": z2.string().optional(),
473
+ "ui:title": z2.string().optional(),
474
+ "ui:description": z2.string().optional(),
475
+ "ui:options": z2.record(z2.string(), z2.unknown()).optional(),
476
+ items: z2.lazy(() => z2.record(z2.string(), uiFieldSchemaSchema2)).optional()
477
+ }).passthrough();
478
+ var contextUiSchema2 = z2.record(z2.string(), uiFieldSchemaSchema2).optional();
479
+ var contextDataSchema2 = z2.object({
480
+ data: z2.record(z2.string(), z2.unknown()),
481
+ ui: contextUiSchema2
482
+ }).optional();
483
+ var TASK_CONTEXT_FORMAT_VERSION2 = 2;
484
+ var taskContextObjectBaseSchema2 = z2.object({
485
+ app: z2.string().min(1).optional(),
486
+ type: z2.string().min(1),
487
+ name: z2.string().min(1),
488
+ description: z2.string().optional(),
489
+ validUntil: z2.string().optional(),
490
+ context: contextDataSchema2,
491
+ contextVersion: z2.literal(2).optional(),
492
+ /** @deprecated Use `contextVersion`. Accepted on ingest only. */
493
+ version: z2.literal(2).optional(),
494
+ actions: z2.array(taskActionSchema2).min(1, "At least one action is required")
495
+ });
496
+ function normalizeTaskContextVersion2(data) {
497
+ const { version: legacyVersion, contextVersion, ...rest } = data;
498
+ return {
499
+ ...rest,
500
+ contextVersion: contextVersion ?? legacyVersion ?? TASK_CONTEXT_FORMAT_VERSION2
501
+ };
502
+ }
503
+ var taskContextObjectSchema2 = taskContextObjectBaseSchema2.transform(
504
+ normalizeTaskContextVersion2
505
+ );
506
+ function refineContextPublicUrls2(data, ctx) {
507
+ const error = validateContextPublicUrls(data.context);
508
+ if (error) {
509
+ ctx.addIssue({
510
+ code: z2.ZodIssueCode.custom,
511
+ message: error,
512
+ path: ["context"]
513
+ });
514
+ }
515
+ }
516
+ var taskContextSchema2 = taskContextObjectSchema2.superRefine(
517
+ refineContextPublicUrls2
518
+ );
519
+ var assignToSchema2 = z2.object({
520
+ users: z2.array(z2.string().email()).optional(),
521
+ groups: z2.array(z2.string().min(1)).optional()
522
+ }).refine(
523
+ (data) => {
524
+ const groups = data.groups ?? [];
525
+ if (groups.includes("all") && groups.length > 1) {
526
+ return false;
527
+ }
528
+ return true;
529
+ },
530
+ { message: 'Cannot combine "all" with other group slugs' }
531
+ );
532
+ var threadUpdateMessageSchema2 = z2.string().min(1).max(500);
533
+ var threadUpdateStatuses2 = [
534
+ "info",
535
+ "queued",
536
+ "running",
537
+ "waiting",
538
+ "succeeded",
539
+ "failed",
540
+ "cancelled"
541
+ ];
542
+ var threadUpdateStatusSchema2 = z2.enum(threadUpdateStatuses2);
543
+ var threadUpdateInputSchema2 = z2.object({
544
+ message: threadUpdateMessageSchema2,
545
+ status: threadUpdateStatusSchema2.optional()
546
+ });
547
+ var taskPriorities2 = ["low", "normal", "high", "urgent"];
548
+ var taskPrioritySchema2 = z2.enum(taskPriorities2);
549
+ var agentTelemetrySchema2 = z2.object({
550
+ version: z2.string().min(1)
551
+ });
552
+ var createTaskBodySchema2 = taskContextObjectBaseSchema2.extend({
553
+ assignTo: assignToSchema2.optional(),
554
+ /**
555
+ * Groups related tasks together. When omitted, the server generates one and
556
+ * returns it so the caller can reuse it on later tasks in the same thread.
557
+ */
558
+ threadId: z2.string().min(1).optional(),
559
+ /**
560
+ * Optional thread priority. When set, applies to the whole thread and
561
+ * overwrites any previous priority. Omit on later tasks to leave unchanged.
562
+ */
563
+ priority: taskPrioritySchema2.optional(),
564
+ /**
565
+ * Optional initial status update logged against the task's thread. Shows in
566
+ * the inbox status bar and the thread update log.
567
+ */
568
+ update: threadUpdateInputSchema2.optional(),
569
+ agent: agentTelemetrySchema2.optional()
570
+ }).transform(normalizeTaskContextVersion2).superRefine(refineContextPublicUrls2);
571
+ var threadUpdateBodySchema = threadUpdateInputSchema2;
572
+
573
+ // src/approval-result.ts
574
+ var TaskTimeoutError = class extends Error {
575
+ constructor(message) {
576
+ super(message);
577
+ this.name = "TaskTimeoutError";
578
+ }
579
+ };
580
+ var TaskExpiredError = class extends Error {
581
+ constructor(message) {
582
+ super(message);
583
+ this.name = "TaskExpiredError";
584
+ }
585
+ };
586
+ function toDiscriminatedApprovalResult(actions, task) {
587
+ void actions;
588
+ if (!task.handled) {
589
+ throw new Error("Task has no handled result");
590
+ }
591
+ return {
592
+ actionId: task.handled.action.id,
593
+ data: task.handled.action.data,
594
+ handledBy: task.handled.handledBy,
595
+ handledAt: new Date(task.handledAt ?? Date.now()),
596
+ taskId: task.id
597
+ };
598
+ }
599
+
600
+ // src/http.ts
601
+ var RobotRockError = class extends Error {
602
+ constructor(message, statusCode, response) {
603
+ super(message);
604
+ this.statusCode = statusCode;
605
+ this.response = response;
606
+ this.name = "RobotRockError";
607
+ }
608
+ };
609
+ async function parseResponseBody(response) {
610
+ const contentType = response.headers.get("content-type") ?? "";
611
+ const bodyText = await response.text();
612
+ if (!bodyText) {
613
+ return null;
614
+ }
615
+ if (contentType.toLowerCase().includes("application/json")) {
616
+ try {
617
+ return JSON.parse(bodyText);
618
+ } catch {
619
+ }
620
+ }
621
+ try {
622
+ return JSON.parse(bodyText);
623
+ } catch {
624
+ return bodyText;
625
+ }
626
+ }
627
+ function getErrorMessage(data, fallback) {
628
+ if (data && typeof data === "object" && !Array.isArray(data)) {
629
+ const record = data;
630
+ const maybeMessage = record.message;
631
+ const maybeHint = record.hint;
632
+ if (typeof maybeMessage === "string" && maybeMessage.trim()) {
633
+ if (typeof maybeHint === "string" && maybeHint.trim()) {
634
+ return `${maybeMessage.trim()} ${maybeHint.trim()}`;
635
+ }
636
+ return maybeMessage;
637
+ }
638
+ }
639
+ if (typeof data === "string" && data.trim()) {
640
+ const compact = data.replace(/\s+/g, " ").trim();
641
+ const snippet = compact.length > 180 ? `${compact.slice(0, 180)}...` : compact;
642
+ return `${fallback}. Server returned non-JSON response: ${snippet}`;
643
+ }
644
+ return fallback;
645
+ }
646
+
647
+ // ../core/src/handler-retry.ts
648
+ var HANDLER_RETRY_DELAYS_MS = [
649
+ 6e4,
650
+ // 1m
651
+ 3e5,
652
+ // 5m
653
+ 18e5,
654
+ // 30m
655
+ 36e5,
656
+ // 1h
657
+ 216e5,
658
+ // 6h
659
+ 864e5,
660
+ // 24h
661
+ 1728e5
662
+ // 48h
663
+ ];
664
+ var HANDLER_MAX_ATTEMPTS = HANDLER_RETRY_DELAYS_MS.length + 1;
665
+
666
+ // ../core/src/attribution/index.ts
667
+ import { z as z3 } from "zod";
668
+
669
+ // ../core/src/app-url.ts
670
+ var PRODUCTION_APP_URL = "https://app.robotrock.io";
671
+ var PRODUCTION_API_URL = "https://api.robotrock.io/v1";
672
+ var DEV_API_URL = "http://localhost:4001/v1";
673
+ var APP_SIGNUP_URL = `${PRODUCTION_APP_URL}/sign-up`;
674
+ function normalizeRobotRockApiBaseUrl(baseUrl) {
675
+ const trimmed = baseUrl.trim().replace(/\/+$/, "");
676
+ if (trimmed.endsWith("/v1")) {
677
+ return trimmed;
678
+ }
679
+ return `${trimmed}/v1`;
680
+ }
681
+ function getRobotRockApiBaseUrl() {
682
+ const explicit = process.env.ROBOTROCK_BASE_URL?.trim() || process.env.ROBOTROCK_API_URL?.trim();
683
+ if (explicit) {
684
+ return normalizeRobotRockApiBaseUrl(explicit);
685
+ }
686
+ if (process.env.NODE_ENV === "production") {
687
+ return PRODUCTION_API_URL;
688
+ }
689
+ return DEV_API_URL;
690
+ }
691
+
692
+ // ../core/src/attribution/index.ts
693
+ var ATTRIBUTION_COOKIE_MAX_AGE = 60 * 60 * 24 * 90;
694
+ var attributionSchema = z3.object({
695
+ utmSource: z3.string().optional(),
696
+ utmMedium: z3.string().optional(),
697
+ utmCampaign: z3.string().optional(),
698
+ utmContent: z3.string().optional(),
699
+ utmTerm: z3.string().optional(),
700
+ gclid: z3.string().optional(),
701
+ landingUrl: z3.string().optional(),
702
+ referrer: z3.string().optional(),
703
+ capturedAt: z3.number()
704
+ });
705
+
706
+ // src/auth-headers.ts
707
+ function buildRobotRockAuthHeaders(auth) {
708
+ if (auth.kind === "apiKey") {
709
+ return {
710
+ "X-Api-Key": auth.apiKey
711
+ };
712
+ }
713
+ return {
714
+ Authorization: `Bearer ${auth.token}`,
715
+ "X-RobotRock-Tenant-Slug": auth.tenantSlug,
716
+ "X-RobotRock-Connection-Id": auth.connectionId
717
+ };
718
+ }
719
+ function resolveRobotRockAuthConfig(overrides) {
720
+ if (overrides?.agentService) {
721
+ return {
722
+ kind: "agentService",
723
+ ...overrides.agentService
724
+ };
725
+ }
726
+ const apiKey = overrides?.apiKey ?? process.env.ROBOTROCK_API_KEY;
727
+ if (!apiKey) {
728
+ throw new Error(
729
+ "RobotRock auth is required. Set ROBOTROCK_API_KEY, ROBOTROCK_AGENT_SERVICE_TOKEN with tenant context, or pass auth when creating the client."
730
+ );
731
+ }
732
+ return { kind: "apiKey", apiKey };
733
+ }
734
+
735
+ // src/chats.ts
736
+ function createChatsApi(config) {
737
+ const headers = () => ({
738
+ "Content-Type": "application/json",
739
+ ...buildRobotRockAuthHeaders(config.auth)
740
+ });
741
+ return {
742
+ async create(input) {
743
+ const bodyPayload = {
744
+ ...input,
745
+ app: input.app ?? config.app,
746
+ messages: input.messages ?? []
747
+ };
748
+ const validation = createAgentChatBodySchema.safeParse(bodyPayload);
749
+ if (!validation.success) {
750
+ throw new RobotRockError(
751
+ `Invalid chat: ${validation.error.issues[0]?.message}`,
752
+ 400,
753
+ validation.error.issues
754
+ );
755
+ }
756
+ const response = await fetch(`${config.baseUrl}/agent-chats`, {
757
+ method: "POST",
758
+ headers: headers(),
759
+ body: JSON.stringify(validation.data)
760
+ });
761
+ const data = await parseResponseBody(response);
762
+ if (!response.ok) {
763
+ throw new RobotRockError(
764
+ getErrorMessage(data, "Failed to create chat"),
765
+ response.status,
766
+ data
767
+ );
768
+ }
769
+ const result = data;
770
+ return { tenantSlug: result.tenantSlug, chats: result.chats };
771
+ },
772
+ async close(chatId, options) {
773
+ if (!chatId) {
774
+ throw new RobotRockError("chatId is required to close a chat", 400);
775
+ }
776
+ const response = await fetch(
777
+ `${config.baseUrl}/agent-chats/${encodeURIComponent(chatId)}/close`,
778
+ {
779
+ method: "POST",
780
+ headers: headers(),
781
+ body: JSON.stringify({ reason: options?.reason })
782
+ }
783
+ );
784
+ if (!response.ok) {
785
+ const data = await parseResponseBody(response);
786
+ throw new RobotRockError(
787
+ getErrorMessage(data, "Failed to close chat"),
788
+ response.status,
789
+ data
790
+ );
791
+ }
792
+ },
793
+ async stageHitlRequests(input) {
794
+ const validation = agentChatStageHitlBodySchema.safeParse(input);
795
+ if (!validation.success) {
796
+ throw new RobotRockError(
797
+ `Invalid stage HITL input: ${validation.error.issues[0]?.message}`,
798
+ 400,
799
+ validation.error.issues
800
+ );
801
+ }
802
+ const response = await fetch(`${config.baseUrl}/agent-chats/stage-hitl`, {
803
+ method: "POST",
804
+ headers: headers(),
805
+ body: JSON.stringify(validation.data)
806
+ });
807
+ if (!response.ok) {
808
+ const data = await parseResponseBody(response);
809
+ throw new RobotRockError(
810
+ getErrorMessage(data, "Failed to stage chat HITL requests"),
811
+ response.status,
812
+ data
813
+ );
814
+ }
815
+ },
816
+ async getStagedHitlRequests(eveSessionId) {
817
+ const trimmed = eveSessionId.trim();
818
+ if (!trimmed) {
819
+ throw new RobotRockError("eveSessionId is required", 400);
820
+ }
821
+ const url = new URL(`${config.baseUrl}/agent-chats/staged-hitl`);
822
+ url.searchParams.set("eveSessionId", trimmed);
823
+ const response = await fetch(url.toString(), {
824
+ method: "GET",
825
+ headers: headers()
826
+ });
827
+ const data = await parseResponseBody(response);
828
+ if (!response.ok) {
829
+ throw new RobotRockError(
830
+ getErrorMessage(data, "Failed to fetch staged chat HITL requests"),
831
+ response.status,
832
+ data
833
+ );
834
+ }
835
+ const requests = data.requests;
836
+ return Array.isArray(requests) ? requests : [];
837
+ },
838
+ async logInputSubmission(input) {
839
+ const validation = agentChatAuditInputBodySchema.safeParse(input);
840
+ if (!validation.success) {
841
+ throw new RobotRockError(
842
+ `Invalid audit input: ${validation.error.issues[0]?.message}`,
843
+ 400,
844
+ validation.error.issues
845
+ );
846
+ }
847
+ const response = await fetch(`${config.baseUrl}/agent-chats/audit-input`, {
848
+ method: "POST",
849
+ headers: headers(),
850
+ body: JSON.stringify(validation.data)
851
+ });
852
+ if (!response.ok) {
853
+ const data = await parseResponseBody(response);
854
+ throw new RobotRockError(
855
+ getErrorMessage(data, "Failed to log chat input submission"),
856
+ response.status,
857
+ data
858
+ );
859
+ }
860
+ },
861
+ async linkTask(input) {
862
+ const validation = agentChatLinkTaskBodySchema.safeParse(input);
863
+ if (!validation.success) {
864
+ throw new RobotRockError(
865
+ `Invalid link task input: ${validation.error.issues[0]?.message}`,
866
+ 400,
867
+ validation.error.issues
868
+ );
869
+ }
870
+ const response = await fetch(`${config.baseUrl}/agent-chats/link-task`, {
871
+ method: "POST",
872
+ headers: headers(),
873
+ body: JSON.stringify(validation.data)
874
+ });
875
+ if (!response.ok) {
876
+ const data = await parseResponseBody(response);
877
+ throw new RobotRockError(
878
+ getErrorMessage(data, "Failed to link inbox task to chat"),
879
+ response.status,
880
+ data
881
+ );
882
+ }
883
+ }
884
+ };
885
+ }
886
+
887
+ // src/client.ts
888
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
889
+ var DEFAULT_TIMEOUT_MS = 24 * 60 * 60 * 1e3;
890
+ function sleep(ms) {
891
+ return new Promise((resolve) => setTimeout(resolve, ms));
892
+ }
893
+ function resolveAgentVersionFromEnv() {
894
+ const fromEnv = process.env.AGENT_VERSION?.trim() || process.env.ROBOTROCK_AGENT_VERSION?.trim();
895
+ return fromEnv || void 0;
896
+ }
897
+ function parseValidUntilMs(value) {
898
+ if (value === void 0) {
899
+ return void 0;
900
+ }
901
+ if (value instanceof Date) {
902
+ const ms = value.getTime();
903
+ return Number.isNaN(ms) ? void 0 : ms;
904
+ }
905
+ if (typeof value === "number") {
906
+ return Number.isFinite(value) ? value : void 0;
907
+ }
908
+ const parsed = Date.parse(value);
909
+ return Number.isNaN(parsed) ? void 0 : parsed;
910
+ }
911
+ function serializeValidUntil(value) {
912
+ if (value instanceof Date) {
913
+ const ms = value.getTime();
914
+ if (Number.isNaN(ms)) {
915
+ throw new RobotRockError("Invalid validUntil: Date is invalid", 400);
916
+ }
917
+ return value.toISOString();
918
+ }
919
+ if (typeof value === "string" && !Number.isNaN(Date.parse(value))) {
920
+ return new Date(value).toISOString();
921
+ }
922
+ throw new RobotRockError("Invalid validUntil: expected a Date or parseable date string", 400);
923
+ }
924
+ var RobotRock = class {
925
+ auth;
926
+ baseUrl;
927
+ app;
928
+ agentVersion;
929
+ contextVersion;
930
+ webhook;
931
+ polling;
932
+ /** Task CRUD: `create`, `get`, `cancel`, `sendUpdate`. */
933
+ tasks;
934
+ /** Chat CRUD: `create`, `close`. */
935
+ chats;
936
+ constructor(config) {
937
+ if (config.webhook && config.polling) {
938
+ throw new Error(
939
+ "RobotRock client cannot configure both webhook and polling. Use webhook for callbacks or polling to block until handled."
940
+ );
941
+ }
942
+ const apiKey = config.apiKey ?? process.env.ROBOTROCK_API_KEY;
943
+ const agentService = config.agentService;
944
+ if (apiKey && agentService) {
945
+ throw new Error(
946
+ "RobotRock client cannot configure both apiKey and agentService."
947
+ );
948
+ }
949
+ this.auth = resolveRobotRockAuthConfig({
950
+ ...apiKey ? { apiKey } : {},
951
+ ...agentService ? { agentService } : {}
952
+ });
953
+ this.baseUrl = config.baseUrl ?? getRobotRockApiBaseUrl();
954
+ this.app = config.app;
955
+ this.agentVersion = config.version ?? resolveAgentVersionFromEnv();
956
+ this.contextVersion = config.advanced?.contextVersion ?? TASK_CONTEXT_FORMAT_VERSION2;
957
+ this.webhook = config.webhook;
958
+ this.polling = config.polling ?? {};
959
+ this.tasks = {
960
+ create: (task) => this.createTaskRequest(task),
961
+ get: (taskId) => this.getTaskById(taskId),
962
+ cancel: (taskId) => this.cancelTaskRequest(taskId),
963
+ sendUpdate: (input) => this.sendThreadUpdate(input)
964
+ };
965
+ this.chats = createChatsApi({
966
+ baseUrl: this.baseUrl,
967
+ auth: this.auth,
968
+ app: this.app
969
+ });
970
+ }
971
+ authHeaders(extra) {
972
+ return {
973
+ "Content-Type": "application/json",
974
+ ...buildRobotRockAuthHeaders(this.auth),
975
+ ...extra
976
+ };
977
+ }
978
+ async createTaskRequest(task) {
979
+ const normalizedTask = normalizeSendToHumanInput(task, {
980
+ webhook: this.webhook,
981
+ app: this.app,
982
+ contextVersion: this.contextVersion,
983
+ agentVersion: this.agentVersion
984
+ });
985
+ const agentVersion = task.version ?? this.agentVersion;
986
+ const bodyPayload = {
987
+ ...normalizedTask,
988
+ ...task.assignTo !== void 0 ? { assignTo: task.assignTo } : {},
989
+ ...task.threadId !== void 0 ? { threadId: task.threadId } : {},
990
+ ...task.priority !== void 0 ? { priority: task.priority } : {},
991
+ ...task.update !== void 0 ? { update: task.update } : {},
992
+ ...agentVersion !== void 0 ? { agent: { version: agentVersion } } : {}
993
+ };
994
+ const validation = createTaskBodySchema2.safeParse(bodyPayload);
995
+ if (!validation.success) {
996
+ throw new RobotRockError(
997
+ `Invalid task: ${validation.error.issues[0]?.message}`,
998
+ 400,
999
+ validation.error.issues
1000
+ );
1001
+ }
1002
+ const headers = this.authHeaders(
1003
+ task.idempotencyKey ? { "Idempotency-Key": task.idempotencyKey } : void 0
1004
+ );
1005
+ const response = await fetch(`${this.baseUrl}/`, {
1006
+ method: "POST",
1007
+ headers,
1008
+ body: JSON.stringify(validation.data)
1009
+ });
1010
+ const data = await parseResponseBody(response);
1011
+ if (!response.ok) {
1012
+ throw new RobotRockError(
1013
+ getErrorMessage(data, "Failed to create task"),
1014
+ response.status,
1015
+ data
1016
+ );
1017
+ }
1018
+ return data.task;
1019
+ }
1020
+ async sendToHuman(task) {
1021
+ const normalizedTask = normalizeSendToHumanInput(task, {
1022
+ webhook: this.webhook,
1023
+ app: this.app,
1024
+ contextVersion: this.contextVersion,
1025
+ agentVersion: this.agentVersion
1026
+ });
1027
+ const createdTaskTask = await this.createTaskRequest(task);
1028
+ const hasHandlers = normalizedTask.actions.some(
1029
+ (action) => Array.isArray(action.handlers) && action.handlers.length > 0
1030
+ );
1031
+ if (hasHandlers) {
1032
+ return {
1033
+ mode: "created",
1034
+ task: createdTaskTask
1035
+ };
1036
+ }
1037
+ const timeoutMs = this.polling.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1038
+ const pollIntervalMs = this.polling.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1039
+ const pollingDeadline = Date.now() + timeoutMs;
1040
+ const validUntilMs = parseValidUntilMs(createdTaskTask.validUntil);
1041
+ const deadline = validUntilMs !== void 0 ? Math.min(pollingDeadline, validUntilMs) : pollingDeadline;
1042
+ const taskId = createdTaskTask.taskId;
1043
+ while (Date.now() < deadline) {
1044
+ const existing = await this.getTaskById(taskId);
1045
+ if (existing?.status === "handled" && existing.handled) {
1046
+ return {
1047
+ mode: "handled",
1048
+ task: createdTaskTask,
1049
+ ...toDiscriminatedApprovalResult(
1050
+ normalizedTask.actions,
1051
+ existing
1052
+ )
1053
+ };
1054
+ }
1055
+ if (existing?.status === "expired" || existing && Date.now() >= existing.validUntil) {
1056
+ throw new TaskExpiredError("Task reached validUntil before a human completed it");
1057
+ }
1058
+ const remainingMs = deadline - Date.now();
1059
+ await sleep(Math.min(pollIntervalMs, Math.max(0, remainingMs)));
1060
+ }
1061
+ if (validUntilMs !== void 0 && Date.now() >= validUntilMs) {
1062
+ throw new TaskExpiredError("Task reached validUntil before a human completed it");
1063
+ }
1064
+ throw new TaskTimeoutError(`No human response within ${timeoutMs}ms`);
1065
+ }
1066
+ /**
1067
+ * Create a task via POST /v1 without waiting for a human response.
1068
+ * @deprecated Use `client.tasks.create()` instead.
1069
+ */
1070
+ async createTask(task) {
1071
+ return this.tasks.create(task);
1072
+ }
1073
+ /**
1074
+ * Get a task by public task id (returned as `task.taskId` from {@link sendToHuman}).
1075
+ * @deprecated Use `client.tasks.get()` instead.
1076
+ */
1077
+ async getTask(taskId) {
1078
+ return this.tasks.get(taskId);
1079
+ }
1080
+ /**
1081
+ * Log a status update against a thread.
1082
+ * @deprecated Use `client.tasks.sendUpdate()` instead.
1083
+ */
1084
+ async sendUpdate(input) {
1085
+ return this.tasks.sendUpdate(input);
1086
+ }
1087
+ /**
1088
+ * Cancel a task by public task id.
1089
+ * @deprecated Use `client.tasks.cancel()` instead.
1090
+ */
1091
+ async cancelTask(taskId) {
1092
+ return this.tasks.cancel(taskId);
1093
+ }
1094
+ async getTaskById(taskId) {
1095
+ const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {
1096
+ method: "GET",
1097
+ headers: this.authHeaders()
1098
+ });
1099
+ if (response.status === 404) {
1100
+ return null;
1101
+ }
1102
+ const data = await parseResponseBody(response);
1103
+ if (!response.ok) {
1104
+ throw new RobotRockError(
1105
+ getErrorMessage(data, "Failed to get task"),
1106
+ response.status,
1107
+ data
1108
+ );
1109
+ }
1110
+ return data;
1111
+ }
1112
+ async sendThreadUpdate({
1113
+ threadId,
1114
+ message,
1115
+ status
1116
+ }) {
1117
+ if (!threadId) {
1118
+ throw new RobotRockError("threadId is required to send an update", 400);
1119
+ }
1120
+ const validation = threadUpdateBodySchema.safeParse({ message, status });
1121
+ if (!validation.success) {
1122
+ throw new RobotRockError(
1123
+ `Invalid update: ${validation.error.issues[0]?.message}`,
1124
+ 400,
1125
+ validation.error.issues
1126
+ );
1127
+ }
1128
+ const response = await fetch(
1129
+ `${this.baseUrl}/threads/${encodeURIComponent(threadId)}/updates`,
1130
+ {
1131
+ method: "POST",
1132
+ headers: this.authHeaders(),
1133
+ body: JSON.stringify(validation.data)
1134
+ }
1135
+ );
1136
+ const data = await parseResponseBody(response);
1137
+ if (!response.ok) {
1138
+ throw new RobotRockError(
1139
+ getErrorMessage(data, "Failed to send update"),
1140
+ response.status,
1141
+ data
1142
+ );
1143
+ }
1144
+ return data.update;
1145
+ }
1146
+ async cancelTaskRequest(taskId) {
1147
+ const response = await fetch(`${this.baseUrl}/tasks/${taskId}/cancel`, {
1148
+ method: "POST",
1149
+ headers: this.authHeaders()
1150
+ });
1151
+ if (!response.ok) {
1152
+ const data = await parseResponseBody(response);
1153
+ throw new RobotRockError(
1154
+ getErrorMessage(data, "Failed to cancel task"),
1155
+ response.status,
1156
+ data
1157
+ );
1158
+ }
1159
+ }
1160
+ };
1161
+ function createClient(config) {
1162
+ return new RobotRock(config);
1163
+ }
1164
+ function attachWebhookToActions(actions, webhook) {
1165
+ return actions.map((action) => ({
1166
+ ...action,
1167
+ handlers: webhookToHandlers(webhook)
1168
+ }));
1169
+ }
1170
+ function webhookToHandlers(webhook) {
1171
+ return [
1172
+ {
1173
+ type: "webhook",
1174
+ url: webhook.url,
1175
+ headers: webhook.headers ?? {}
1176
+ }
1177
+ ];
1178
+ }
1179
+ function normalizeSendToHumanInput(task, clientDefaults) {
1180
+ const {
1181
+ actions,
1182
+ idempotencyKey: _idempotencyKey,
1183
+ assignTo: _assignTo,
1184
+ threadId: _threadId,
1185
+ priority: _priority,
1186
+ update: _update,
1187
+ version: _version,
1188
+ validUntil,
1189
+ app: taskApp,
1190
+ ...rest
1191
+ } = task;
1192
+ const webhook = clientDefaults.webhook;
1193
+ const normalizedActions = webhook ? attachWebhookToActions(actions, webhook) : actions;
1194
+ const app = taskApp ?? clientDefaults.app;
1195
+ return {
1196
+ ...rest,
1197
+ contextVersion: clientDefaults.contextVersion,
1198
+ ...app ? { app } : {},
1199
+ ...validUntil !== void 0 ? { validUntil: serializeValidUntil(validUntil) } : {},
1200
+ actions: normalizedActions
1201
+ };
1202
+ }
1203
+
1204
+ // src/env.ts
1205
+ function resolveRobotRockConfig(overrides) {
1206
+ const agentService = overrides?.agentService;
1207
+ const apiKey = overrides?.apiKey ?? process.env.ROBOTROCK_API_KEY;
1208
+ if (agentService && apiKey) {
1209
+ throw new Error(
1210
+ "RobotRock client cannot configure both apiKey and agentService."
1211
+ );
1212
+ }
1213
+ const baseUrl = overrides?.baseUrl ?? getRobotRockApiBaseUrl();
1214
+ const app = overrides?.app ?? process.env.ROBOTROCK_APP;
1215
+ if (agentService) {
1216
+ return app ? { agentService, baseUrl, app } : { agentService, baseUrl };
1217
+ }
1218
+ if (!apiKey) {
1219
+ throw new Error(
1220
+ "RobotRock API key is required. Set ROBOTROCK_API_KEY or pass agentService when creating the client."
1221
+ );
1222
+ }
1223
+ return app ? { apiKey, baseUrl, app } : { apiKey, baseUrl };
1224
+ }
1225
+
1226
+ // src/eve/agent/attributes.ts
1227
+ function readStringAttribute(attributes, key) {
1228
+ const value = attributes?.[key];
1229
+ if (typeof value === "string" && value.length > 0) {
1230
+ return value;
1231
+ }
1232
+ if (Array.isArray(value) && typeof value[0] === "string" && value[0].length > 0) {
1233
+ return value[0];
1234
+ }
1235
+ return void 0;
1236
+ }
1237
+ function readStringArrayAttribute(attributes, key) {
1238
+ const value = attributes?.[key];
1239
+ if (typeof value === "string" && value.length > 0) {
1240
+ return [value];
1241
+ }
1242
+ if (Array.isArray(value)) {
1243
+ return value.filter(
1244
+ (entry) => typeof entry === "string" && entry.length > 0
1245
+ );
1246
+ }
1247
+ return [];
1248
+ }
1249
+ function parseTenantRole(value) {
1250
+ if (value === "admin" || value === "member") {
1251
+ return value;
1252
+ }
1253
+ return null;
1254
+ }
1255
+
1256
+ // src/eve/agent/tenant.ts
1257
+ function tryResolveTenantCaller(ctx) {
1258
+ const caller = ctx.session.auth.initiator ?? ctx.session.auth.current;
1259
+ if (caller?.principalType !== "user") {
1260
+ return null;
1261
+ }
1262
+ const email = readStringAttribute(caller.attributes, "email");
1263
+ const name = readStringAttribute(caller.attributes, "name");
1264
+ const tenantSlug = readStringAttribute(caller.attributes, "tenantSlug") ?? readStringAttribute(caller.attributes, "tenantId");
1265
+ const role = parseTenantRole(readStringAttribute(caller.attributes, "role"));
1266
+ if (!email || !tenantSlug || !caller.principalId || !role) {
1267
+ return null;
1268
+ }
1269
+ const workosUserId = readStringAttribute(caller.attributes, "workosUserId");
1270
+ const connectionId = readStringAttribute(caller.attributes, "connectionId");
1271
+ const groups = readStringArrayAttribute(caller.attributes, "groups");
1272
+ return {
1273
+ userId: caller.principalId,
1274
+ email,
1275
+ name: name ?? email.split("@")[0] ?? email,
1276
+ tenantSlug,
1277
+ ...connectionId ? { connectionId } : {},
1278
+ role,
1279
+ isAdmin: role === "admin",
1280
+ groups,
1281
+ ...workosUserId ? { workosUserId } : {}
1282
+ };
1283
+ }
1284
+ function requireTenantCaller(ctx) {
1285
+ const caller = tryResolveTenantCaller(ctx);
1286
+ if (!caller) {
1287
+ throw new Error("An authenticated RobotRock tenant user is required.");
1288
+ }
1289
+ return caller;
1290
+ }
1291
+
1292
+ // src/eve/agent/client-from-session.ts
1293
+ var warnedMissingAuth = false;
1294
+ function tryCreateBoundRobotRockClient(ctx) {
1295
+ const caller = tryResolveTenantCaller(ctx);
1296
+ const serviceToken = process.env.ROBOTROCK_AGENT_SERVICE_TOKEN?.trim();
1297
+ if (caller?.connectionId && serviceToken) {
1298
+ return createClient({
1299
+ baseUrl: process.env.ROBOTROCK_BASE_URL?.trim(),
1300
+ agentService: {
1301
+ token: serviceToken,
1302
+ tenantSlug: caller.tenantSlug,
1303
+ connectionId: caller.connectionId
1304
+ }
1305
+ });
1306
+ }
1307
+ const apiKey = process.env.ROBOTROCK_API_KEY?.trim();
1308
+ if (apiKey) {
1309
+ return createClient(
1310
+ resolveRobotRockConfig({
1311
+ apiKey,
1312
+ baseUrl: process.env.ROBOTROCK_BASE_URL?.trim()
1313
+ })
1314
+ );
1315
+ }
1316
+ if (!warnedMissingAuth) {
1317
+ warnedMissingAuth = true;
1318
+ console.warn(
1319
+ "robotrock: set ROBOTROCK_AGENT_SERVICE_TOKEN for hosted multi-tenant auth, or ROBOTROCK_API_KEY for single-tenant deployments."
1320
+ );
1321
+ }
1322
+ return null;
1323
+ }
1324
+
1325
+ // src/eve/agent/task-delegation.ts
1326
+ function resolveTaskApp(app) {
1327
+ return app?.trim() || process.env.ROBOTROCK_APP?.trim() || "robotrock-agent";
1328
+ }
1329
+ function resolveWebhookBaseUrl(baseUrl) {
1330
+ return baseUrl?.trim() || process.env.ROBOTROCK_BASE_URL?.trim() || "http://localhost:4001/v1";
1331
+ }
1332
+ function resolveTaskHandledWebhookUrl(baseUrl) {
1333
+ const trimmed = baseUrl.trim().replace(/\/+$/, "");
1334
+ const withV1 = trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
1335
+ return `${withV1}/agent-chats/task-handled`;
1336
+ }
1337
+ function requireBoundClient(ctx) {
1338
+ const client = tryCreateBoundRobotRockClient(ctx);
1339
+ if (!client) {
1340
+ throw new Error(
1341
+ "RobotRock auth is unset. Configure ROBOTROCK_AGENT_SERVICE_TOKEN for hosted agents or ROBOTROCK_API_KEY for self-hosted deployments."
1342
+ );
1343
+ }
1344
+ return client;
1345
+ }
1346
+ async function createRobotRockTask(input, ctx) {
1347
+ const client = requireBoundClient(ctx);
1348
+ const { app, ...taskInput } = input;
1349
+ const resolvedApp = resolveTaskApp(app);
1350
+ const webhookUrl = resolveTaskHandledWebhookUrl(
1351
+ resolveWebhookBaseUrl(process.env.ROBOTROCK_BASE_URL)
1352
+ );
1353
+ try {
1354
+ const task = await client.tasks.create({
1355
+ ...taskInput,
1356
+ app: resolvedApp,
1357
+ actions: attachWebhookToActions(taskInput.actions, {
1358
+ url: webhookUrl,
1359
+ headers: {}
1360
+ })
1361
+ });
1362
+ return {
1363
+ taskId: task.taskId,
1364
+ threadId: task.threadId,
1365
+ status: task.status,
1366
+ validUntil: task.validUntil,
1367
+ submittedAt: task.submittedAt
1368
+ };
1369
+ } catch (error) {
1370
+ const caller = tryResolveTenantCaller(ctx);
1371
+ if (error instanceof RobotRockError) {
1372
+ const response = error.response && typeof error.response === "object" ? error.response : void 0;
1373
+ console.error("[create_robotrock_task] API request failed", {
1374
+ status: error.statusCode,
1375
+ message: error.message,
1376
+ code: response?.code,
1377
+ hint: response?.hint,
1378
+ tenantSlug: caller?.tenantSlug,
1379
+ connectionId: caller?.connectionId,
1380
+ baseUrl: process.env.ROBOTROCK_BASE_URL?.trim() || null
1381
+ });
1382
+ } else {
1383
+ console.error("[create_robotrock_task] unexpected error", error);
1384
+ }
1385
+ throw error;
1386
+ }
1387
+ }
1388
+ function buildRobotRockTaskPayload(input, options) {
1389
+ const contextData = {
1390
+ ...input.context?.data ?? {}
1391
+ };
1392
+ if (options?.requestedByEmail) {
1393
+ contextData.requestedBy = options.requestedByEmail;
1394
+ }
1395
+ const hasContext = Object.keys(contextData).length > 0 || input.context?.ui && Object.keys(input.context.ui).length > 0;
1396
+ const payload = {
1397
+ type: input.type,
1398
+ name: input.name,
1399
+ ...input.description ? { description: input.description } : {},
1400
+ actions: input.actions.map((action) => ({
1401
+ id: action.id,
1402
+ title: action.title,
1403
+ ...action.description ? { description: action.description } : {}
1404
+ })),
1405
+ ...input.assignTo ? { assignTo: input.assignTo } : {},
1406
+ ...input.priority ? { priority: input.priority } : {},
1407
+ ...input.app ? { app: input.app } : {},
1408
+ ...input.validUntilHours ? {
1409
+ validUntil: new Date(Date.now() + input.validUntilHours * 60 * 60 * 1e3)
1410
+ } : {},
1411
+ ...input.updateMessage ? {
1412
+ update: {
1413
+ message: input.updateMessage,
1414
+ status: "waiting"
1415
+ }
1416
+ } : {}
1417
+ };
1418
+ if (hasContext) {
1419
+ payload.context = {
1420
+ data: contextData,
1421
+ ...input.context?.ui ? { ui: input.context.ui } : {}
1422
+ };
1423
+ }
1424
+ return payload;
1425
+ }
1426
+
1427
+ // src/eve/agent/chat-audit-api.ts
1428
+ var warnedMissingAuth2 = false;
1429
+ var warnedConnectionRefused = false;
1430
+ function isConnectionRefused(error) {
1431
+ const inspect = (value) => {
1432
+ if (!value || typeof value !== "object") {
1433
+ return false;
1434
+ }
1435
+ if ("code" in value && value.code === "ECONNREFUSED") {
1436
+ return true;
1437
+ }
1438
+ if ("cause" in value) {
1439
+ return inspect(value.cause);
1440
+ }
1441
+ if ("errors" in value && Array.isArray(value.errors)) {
1442
+ return value.errors.some((entry) => inspect(entry));
1443
+ }
1444
+ return false;
1445
+ };
1446
+ return inspect(error);
1447
+ }
1448
+ function logAuditFailure(label, error) {
1449
+ if (isConnectionRefused(error)) {
1450
+ if (!warnedConnectionRefused) {
1451
+ warnedConnectionRefused = true;
1452
+ console.warn(
1453
+ "robotrock-chat-audit: RobotRock API is not reachable (connection refused). Audit and task-link calls are skipped until the API is up."
1454
+ );
1455
+ }
1456
+ return;
1457
+ }
1458
+ const hint = error instanceof RobotRockError && error.statusCode === 405 ? " \u2014 set ROBOTROCK_BASE_URL=http://localhost:4001/v1 and run the local API" : "";
1459
+ console.warn(`robotrock-chat-audit: failed to ${label}${hint}`, error);
1460
+ }
1461
+ async function postRobotRockLinkChatTask(ctx, input) {
1462
+ const client = tryCreateBoundRobotRockClient(ctx);
1463
+ if (!client) {
1464
+ if (!warnedMissingAuth2) {
1465
+ warnedMissingAuth2 = true;
1466
+ console.warn(
1467
+ "robotrock-task-link: RobotRock auth is unset; skipping chat task link."
1468
+ );
1469
+ }
1470
+ return;
1471
+ }
1472
+ try {
1473
+ await client.chats.linkTask(input);
1474
+ } catch (error) {
1475
+ logAuditFailure("link task to chat", error);
1476
+ }
1477
+ }
1478
+
1479
+ // src/eve/tools/inbox/create-task.ts
1480
+ var CREATE_INBOX_TASK_TOOL_NAME = "create_robotrock_task";
1481
+ var actionSchema = z4.object({
1482
+ id: z4.string().min(1).describe("Stable action id, e.g. approve or reject."),
1483
+ title: z4.string().min(1).describe("Button label shown in the inbox."),
1484
+ description: z4.string().min(1).optional()
1485
+ });
1486
+ var assignToSchema3 = z4.object({
1487
+ users: z4.array(z4.string().email()).optional().describe("Assignee emails \u2014 only these users (plus group members) see the task."),
1488
+ groups: z4.array(z4.string().min(1)).optional().describe('Group slugs, e.g. "finance". Only members of these groups see the task.')
1489
+ }).optional().refine(
1490
+ (value) => value === void 0 || (value.users?.length ?? 0) > 0 || (value.groups?.length ?? 0) > 0,
1491
+ { message: "assignTo needs at least one user email or group slug." }
1492
+ );
1493
+ var contextSchema = z4.object({
1494
+ data: z4.record(z4.string(), z4.unknown()).optional().describe("Structured fields shown in the inbox task detail."),
1495
+ ui: z4.record(z4.string(), z4.unknown()).optional().describe("Optional ui:* hints keyed by context.data field name.")
1496
+ }).optional();
1497
+ var createInboxTaskInputSchema = z4.object({
1498
+ type: z4.string().min(1).describe("Task category slug, e.g. refund-approval or budget-approval."),
1499
+ name: z4.string().min(1).describe("Short title shown in the inbox list."),
1500
+ description: z4.string().min(1).optional(),
1501
+ actions: z4.array(actionSchema).min(1).describe("At least one reviewer action (approve, reject, etc.)."),
1502
+ assignTo: assignToSchema3.describe(
1503
+ "Limit visibility to specific users and/or groups. Omit to show the task to everyone in the tenant."
1504
+ ),
1505
+ context: contextSchema,
1506
+ validUntilHours: z4.number().positive().optional().describe("Optional deadline in hours from now. Defaults to the tenant task TTL."),
1507
+ priority: z4.enum(["low", "normal", "high", "urgent"]).optional(),
1508
+ updateMessage: z4.string().min(1).optional().describe("Optional thread status update logged when the task is created."),
1509
+ delegationReason: z4.string().min(1).optional().describe(
1510
+ "User-facing explanation of why the requester cannot self-approve and the task was routed elsewhere. Required when assignTo excludes the caller."
1511
+ )
1512
+ });
1513
+ function defaultResolveDelegationReason(input) {
1514
+ const assigneeGroups = input.assignTo?.groups?.filter(Boolean) ?? [];
1515
+ if (assigneeGroups.length > 0) {
1516
+ return `This was routed to ${assigneeGroups.join(", ")} for review because you are not in the assignee group.`;
1517
+ }
1518
+ return void 0;
1519
+ }
1520
+ function defineCreateInboxTaskTool(options) {
1521
+ return defineTool({
1522
+ description: "Create a RobotRock inbox task and assign it to users or groups. Does not wait for a response. Only call this after the user explicitly asked to create/send/delegate an inbox task, or after they confirmed via ask_question. Never create a task silently when the user only asked for a preview, dummy example, or explanation. Always set delegationReason when assignTo excludes the caller. For refund approvals include chargeId, amount, currency, and reason in context.data.",
1523
+ inputSchema: createInboxTaskInputSchema,
1524
+ async execute(input, ctx) {
1525
+ const caller = requireTenantCaller(ctx);
1526
+ const payload = buildRobotRockTaskPayload(input, {
1527
+ requestedByEmail: caller.email
1528
+ });
1529
+ if (options?.defaultApp && !payload.app) {
1530
+ payload.app = options.defaultApp;
1531
+ }
1532
+ const task = await createRobotRockTask(payload, ctx);
1533
+ const delegationReason = options?.resolveDelegationReason?.(input, caller) ?? input.delegationReason?.trim() ?? defaultResolveDelegationReason(input);
1534
+ await postRobotRockLinkChatTask(ctx, {
1535
+ eveSessionId: ctx.session.id,
1536
+ publicTaskId: task.taskId,
1537
+ toolCallId: ctx.callId
1538
+ });
1539
+ return {
1540
+ ...task,
1541
+ name: input.name,
1542
+ assignedTo: input.assignTo ?? null,
1543
+ requestedBy: caller.email,
1544
+ delegationReason: delegationReason ?? null,
1545
+ message: delegationReason ? `${delegationReason} This chat updates when the assignee decides.` : "Task created in RobotRock. Assignees can handle it from their inbox; this chat will update when they decide."
1546
+ };
1547
+ }
1548
+ });
1549
+ }
1550
+ var createInboxTaskTool = defineCreateInboxTaskTool();
1551
+ export {
1552
+ CREATE_INBOX_TASK_TOOL_NAME,
1553
+ createInboxTaskInputSchema,
1554
+ createInboxTaskTool,
1555
+ defineCreateInboxTaskTool
1556
+ };
1557
+ //# sourceMappingURL=index.js.map