@alva-ai/toolkit 0.25.0 → 0.25.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ __export(src_exports, {
31
31
  SUBSCRIBE_MANAGE_MESSAGE: () => SUBSCRIBE_MANAGE_MESSAGE,
32
32
  SUBSCRIBE_PROPOSE_MESSAGE: () => SUBSCRIBE_PROPOSE_MESSAGE,
33
33
  SUBSCRIBE_RESULT_MESSAGE: () => SUBSCRIBE_RESULT_MESSAGE,
34
+ SchedulesResource: () => SchedulesResource,
34
35
  UDF_AUTH_REQUIRED_MESSAGE: () => UDF_AUTH_REQUIRED_MESSAGE,
35
36
  UDF_CONSENT_REQUEST_MESSAGE: () => UDF_CONSENT_REQUEST_MESSAGE,
36
37
  UDF_CONSENT_RESPONSE_MESSAGE: () => UDF_CONSENT_RESPONSE_MESSAGE,
@@ -3175,6 +3176,379 @@ var MarketsResource = class {
3175
3176
  }
3176
3177
  };
3177
3178
 
3179
+ // src/resources/schedules.ts
3180
+ var SCHEDULE_FIELDS = `
3181
+ id
3182
+ channel { id }
3183
+ name
3184
+ rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
3185
+ bounds { startsAtMs untilMs maxOccurrences }
3186
+ message { text }
3187
+ status
3188
+ failureCode
3189
+ failureAtMs
3190
+ occurrencesUsed
3191
+ nextFireAtMs
3192
+ createdAtMs
3193
+ updatedAtMs
3194
+ `;
3195
+ var LIST_SCHEDULES = `
3196
+ query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
3197
+ viewer { channel(id: $channelId) {
3198
+ schedules(input: { first: 64, after: $after }) {
3199
+ edges { node { ${SCHEDULE_FIELDS} } }
3200
+ pageInfo { hasNextPage endCursor }
3201
+ }
3202
+ } }
3203
+ }`.trim();
3204
+ var UPDATE_SCHEDULE = `
3205
+ mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
3206
+ updateChannelSchedule(input: $input) {
3207
+ schedule { ${SCHEDULE_FIELDS} }
3208
+ deleted
3209
+ }
3210
+ }`.trim();
3211
+ var AGENT_CHANNEL = `
3212
+ query ToolkitAgentChannel {
3213
+ viewer { channels { id kind } }
3214
+ }`.trim();
3215
+ var SCHEDULE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
3216
+ var RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i;
3217
+ var ISO_DURATION = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
3218
+ var GRAPHQL_STATUS_BY_CODE = {
3219
+ INVALID_ARGUMENT: 400,
3220
+ UNAUTHENTICATED: 401,
3221
+ PERMISSION_DENIED: 403,
3222
+ NOT_FOUND: 404,
3223
+ ALREADY_EXISTS: 409,
3224
+ ABORTED: 409,
3225
+ FAILED_PRECONDITION: 412,
3226
+ RESOURCE_EXHAUSTED: 429,
3227
+ INTERNAL: 500,
3228
+ UNKNOWN: 500,
3229
+ DATA_LOSS: 500,
3230
+ UNAVAILABLE: 503,
3231
+ DEADLINE_EXCEEDED: 504
3232
+ };
3233
+ var SchedulesResource = class {
3234
+ constructor(client) {
3235
+ this.client = client;
3236
+ }
3237
+ client;
3238
+ async list(params) {
3239
+ this.client._requireAuth();
3240
+ const id = channelID(params.channelId);
3241
+ const schedules = [];
3242
+ let after = null;
3243
+ const seenCursors = /* @__PURE__ */ new Set();
3244
+ for (; ; ) {
3245
+ const data = await this.graphql(
3246
+ LIST_SCHEDULES,
3247
+ { channelId: id, after }
3248
+ );
3249
+ const connection = data.viewer?.channel?.schedules;
3250
+ if (!connection?.edges) throw scheduleNotFound();
3251
+ for (const edge of connection.edges) {
3252
+ if (!edge?.node) throw scheduleEmptyResponse();
3253
+ schedules.push(fromWireSchedule(edge.node));
3254
+ }
3255
+ if (connection.pageInfo?.hasNextPage !== true) return schedules;
3256
+ const next = connection.pageInfo.endCursor;
3257
+ if (!next || seenCursors.has(next)) throw scheduleEmptyResponse();
3258
+ seenCursors.add(next);
3259
+ after = next;
3260
+ }
3261
+ }
3262
+ async put(params) {
3263
+ this.client._requireAuth();
3264
+ const input = {
3265
+ channelId: channelID(params.channelId),
3266
+ name: requireName(params.name),
3267
+ definition: {
3268
+ ...ruleInput(params.rule, params.bounds),
3269
+ message: { text: requireText(params.text) }
3270
+ }
3271
+ };
3272
+ const data = await this.graphql(UPDATE_SCHEDULE, { input });
3273
+ const schedule = data.updateChannelSchedule?.schedule;
3274
+ if (!schedule) throw scheduleEmptyResponse();
3275
+ return fromWireSchedule(schedule);
3276
+ }
3277
+ pause(params) {
3278
+ return this.manage("PAUSED", params);
3279
+ }
3280
+ resume(params) {
3281
+ return this.manage("ACTIVE", params);
3282
+ }
3283
+ async delete(params) {
3284
+ this.client._requireAuth();
3285
+ const data = await this.graphql(UPDATE_SCHEDULE, {
3286
+ input: { ...managementInput(params), lifecycle: "REMOVED" }
3287
+ });
3288
+ if (data.updateChannelSchedule?.deleted !== true)
3289
+ throw scheduleEmptyResponse();
3290
+ }
3291
+ /** Resolve the authenticated viewer's unique Agent Channel for CLI defaults. */
3292
+ async agentChannelId() {
3293
+ this.client._requireAuth();
3294
+ const data = await this.graphql(AGENT_CHANNEL);
3295
+ const id = data.viewer?.channels?.find(
3296
+ (channel) => channel.kind === "AGENT"
3297
+ )?.id;
3298
+ if (!id) throw scheduleNotFound();
3299
+ return id;
3300
+ }
3301
+ async manage(lifecycle, params) {
3302
+ this.client._requireAuth();
3303
+ const data = await this.graphql(UPDATE_SCHEDULE, {
3304
+ input: { ...managementInput(params), lifecycle }
3305
+ });
3306
+ const schedule = data.updateChannelSchedule?.schedule;
3307
+ if (!schedule) throw scheduleEmptyResponse();
3308
+ return fromWireSchedule(schedule);
3309
+ }
3310
+ async graphql(query, variables) {
3311
+ const response = await this.client._request("POST", "/query", {
3312
+ body: variables === void 0 ? { query } : { query, variables }
3313
+ });
3314
+ if (response.errors?.length) {
3315
+ const codes = response.errors.map((error) => error.extensions?.code);
3316
+ const distinctCodes = new Set(codes);
3317
+ const canonicalCode = distinctCodes.size === 1 && typeof codes[0] === "string" ? codes[0] : void 0;
3318
+ const canonicalStatus = canonicalCode ? GRAPHQL_STATUS_BY_CODE[canonicalCode] : void 0;
3319
+ const errorCode = canonicalCode !== void 0 && canonicalStatus !== void 0 ? canonicalCode : "GRAPHQL_ERROR";
3320
+ throw new AlvaError(
3321
+ errorCode,
3322
+ response.errors.map((error) => error.message).filter((message) => typeof message === "string").join("; ") || "GraphQL request failed",
3323
+ canonicalStatus ?? 502,
3324
+ { errors: response.errors }
3325
+ );
3326
+ }
3327
+ if (!response.data) throw scheduleEmptyResponse();
3328
+ return response.data;
3329
+ }
3330
+ };
3331
+ function ruleInput(rule, bounds) {
3332
+ const convertedBounds = boundsInput(bounds);
3333
+ switch (rule.kind) {
3334
+ case "after":
3335
+ if (convertedBounds)
3336
+ throw invalid("after does not accept recurring bounds");
3337
+ const requestedAt = Date.now() + durationMilliseconds(rule.duration, 1);
3338
+ const atMs = Math.ceil(requestedAt / 1e3) * 1e3;
3339
+ if (!Number.isSafeInteger(atMs) || Number.isNaN(new Date(atMs).getTime()))
3340
+ throw invalid("after is out of range");
3341
+ return {
3342
+ rule: {
3343
+ kind: "AT",
3344
+ atMs
3345
+ }
3346
+ };
3347
+ case "at":
3348
+ if (convertedBounds) throw invalid("at does not accept recurring bounds");
3349
+ return {
3350
+ rule: { kind: "AT", atMs: timestampMilliseconds(rule.timestamp) }
3351
+ };
3352
+ case "every":
3353
+ return {
3354
+ rule: {
3355
+ kind: "EVERY",
3356
+ everyIntervalSeconds: durationSeconds(rule.interval)
3357
+ },
3358
+ ...convertedBounds ? { bounds: convertedBounds } : {}
3359
+ };
3360
+ case "cron":
3361
+ if (!rule.expression.trim() || !rule.timezone.trim()) {
3362
+ throw invalid("cron expression and timezone are required");
3363
+ }
3364
+ return {
3365
+ rule: {
3366
+ kind: "CRON",
3367
+ cronExpression: rule.expression,
3368
+ cronTimezone: rule.timezone
3369
+ },
3370
+ ...convertedBounds ? { bounds: convertedBounds } : {}
3371
+ };
3372
+ }
3373
+ }
3374
+ function boundsInput(bounds) {
3375
+ if (!bounds) return void 0;
3376
+ const result = {};
3377
+ if (bounds.startsAt !== void 0)
3378
+ result.startsAtMs = timestampMilliseconds(bounds.startsAt);
3379
+ if (bounds.until !== void 0)
3380
+ result.untilMs = timestampMilliseconds(bounds.until);
3381
+ if (bounds.maxOccurrences !== void 0) {
3382
+ if (!Number.isSafeInteger(bounds.maxOccurrences) || bounds.maxOccurrences <= 0) {
3383
+ throw invalid("maxOccurrences must be a positive safe integer");
3384
+ }
3385
+ result.maxOccurrences = bounds.maxOccurrences;
3386
+ }
3387
+ return Object.keys(result).length > 0 ? result : void 0;
3388
+ }
3389
+ function fromWireSchedule(schedule) {
3390
+ const statuses = {
3391
+ ACTIVE: "active",
3392
+ PAUSED: "paused",
3393
+ COMPLETED: "completed",
3394
+ FAILED: "failed"
3395
+ };
3396
+ const status = statuses[schedule.status];
3397
+ if (!status) throw scheduleEmptyResponse();
3398
+ const bounds = schedule.bounds ?? {};
3399
+ const message = schedule.message ?? {};
3400
+ const result = {
3401
+ name: schedule.name,
3402
+ rule: fromWireRule(schedule.rule),
3403
+ bounds: {
3404
+ ...bounds.startsAtMs != null ? { startsAt: timestampString(bounds.startsAtMs, true) } : {},
3405
+ ...bounds.untilMs != null ? { until: timestampString(bounds.untilMs, true) } : {},
3406
+ ...bounds.maxOccurrences != null ? {
3407
+ maxOccurrences: safeInteger(
3408
+ bounds.maxOccurrences,
3409
+ "maxOccurrences"
3410
+ )
3411
+ } : {}
3412
+ },
3413
+ text: message.text ?? "",
3414
+ status,
3415
+ occurrencesUsed: safeInteger(schedule.occurrencesUsed, "occurrencesUsed"),
3416
+ ...schedule.nextFireAtMs != null ? { nextFireAt: timestampString(schedule.nextFireAtMs, true) } : {},
3417
+ createdAt: timestampString(schedule.createdAtMs),
3418
+ updatedAt: timestampString(schedule.updatedAtMs)
3419
+ };
3420
+ if (status === "failed") {
3421
+ if (!schedule.failureCode) throw scheduleEmptyResponse();
3422
+ const failureCodes = {
3423
+ TARGET_INVALID: "target_invalid",
3424
+ DELIVERY_EXHAUSTED: "delivery_exhausted",
3425
+ PAYLOAD_CONFLICT: "payload_conflict"
3426
+ };
3427
+ const code = failureCodes[schedule.failureCode];
3428
+ if (!code) throw scheduleEmptyResponse();
3429
+ result.failure = {
3430
+ code,
3431
+ ...schedule.failureAtMs != null ? { at: timestampString(schedule.failureAtMs) } : {}
3432
+ };
3433
+ }
3434
+ return result;
3435
+ }
3436
+ function fromWireRule(rule) {
3437
+ switch (rule.kind) {
3438
+ case "AT":
3439
+ if (rule.atMs == null) throw scheduleEmptyResponse();
3440
+ return { kind: "at", timestamp: timestampString(rule.atMs, true) };
3441
+ case "EVERY":
3442
+ if (rule.everyIntervalSeconds == null) throw scheduleEmptyResponse();
3443
+ return {
3444
+ kind: "every",
3445
+ interval: `PT${safeInteger(rule.everyIntervalSeconds, "interval")}S`
3446
+ };
3447
+ case "CRON":
3448
+ if (!rule.cronExpression || !rule.cronTimezone)
3449
+ throw scheduleEmptyResponse();
3450
+ return {
3451
+ kind: "cron",
3452
+ expression: rule.cronExpression,
3453
+ timezone: rule.cronTimezone
3454
+ };
3455
+ }
3456
+ throw scheduleEmptyResponse();
3457
+ }
3458
+ function managementInput(params) {
3459
+ return {
3460
+ channelId: channelID(params.channelId),
3461
+ name: requireName(params.name)
3462
+ };
3463
+ }
3464
+ function channelID(value) {
3465
+ if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) {
3466
+ throw invalid(
3467
+ "numeric channelId must be a positive safe integer; use a decimal string for larger IDs"
3468
+ );
3469
+ }
3470
+ const rendered = String(value);
3471
+ if (!/^[1-9]\d*$/.test(rendered))
3472
+ throw invalid("channelId must be a positive integer");
3473
+ return rendered;
3474
+ }
3475
+ function requireName(value) {
3476
+ if (!SCHEDULE_NAME.test(value))
3477
+ throw invalid(
3478
+ "name must be 1-63 lowercase alphanumeric characters or hyphens"
3479
+ );
3480
+ return value;
3481
+ }
3482
+ function requireText(value) {
3483
+ const size = utf8Size(value);
3484
+ if (size === void 0 || !value.trim() || size > 16 * 1024)
3485
+ throw invalid("text must be 1..16384 UTF-8 bytes");
3486
+ return value;
3487
+ }
3488
+ function durationSeconds(value) {
3489
+ const milliseconds = durationMilliseconds(value, 60);
3490
+ if (milliseconds % 1e3 !== 0)
3491
+ throw invalid("duration must resolve to whole seconds");
3492
+ return milliseconds / 1e3;
3493
+ }
3494
+ function durationMilliseconds(value, minimumSeconds) {
3495
+ const match = ISO_DURATION.exec(value);
3496
+ if (!match || match.slice(1, 5).every((part) => part === void 0) || value.includes("T") && match.slice(2, 5).every((part) => part === void 0)) {
3497
+ throw invalid("duration must be a positive ISO 8601 day/time duration");
3498
+ }
3499
+ const [days, hours, minutes, seconds] = match.slice(1, 5).map((part) => BigInt(part ?? "0"));
3500
+ const totalSeconds = ((days * 24n + hours) * 60n + minutes) * 60n + seconds;
3501
+ if (totalSeconds < BigInt(minimumSeconds)) {
3502
+ throw invalid(`duration must be at least ${minimumSeconds} whole seconds`);
3503
+ }
3504
+ const result = Number(totalSeconds * 1000n);
3505
+ if (!Number.isSafeInteger(result)) throw invalid("duration is out of range");
3506
+ return result;
3507
+ }
3508
+ function timestampMilliseconds(value) {
3509
+ const match = RFC3339.exec(value);
3510
+ if (!match) throw invalid("timestamp must be RFC3339 with a timezone");
3511
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
3512
+ const offsetHour = Number(match[8] ?? 0);
3513
+ const offsetMinute = Number(match[9] ?? 0);
3514
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
3515
+ const result = Date.parse(value);
3516
+ if (!Number.isFinite(result) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
3517
+ throw invalid("timestamp must be RFC3339 with a timezone");
3518
+ }
3519
+ return result;
3520
+ }
3521
+ function timestampString(value, semantic = false) {
3522
+ if (!Number.isSafeInteger(value)) throw scheduleEmptyResponse();
3523
+ if (semantic && value % 1e3 !== 0) throw scheduleEmptyResponse();
3524
+ const timestamp = new Date(value);
3525
+ if (Number.isNaN(timestamp.getTime())) throw scheduleEmptyResponse();
3526
+ return timestamp.toISOString();
3527
+ }
3528
+ function safeInteger(value, field) {
3529
+ const result = Number(value);
3530
+ if (!Number.isSafeInteger(result) || result < 0)
3531
+ throw invalid(`${field} exceeds JavaScript safe integer range`);
3532
+ return result;
3533
+ }
3534
+ function invalid(message) {
3535
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
3536
+ }
3537
+ function utf8Size(value) {
3538
+ const bytes = new TextEncoder().encode(value);
3539
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes) === value ? bytes.byteLength : void 0;
3540
+ }
3541
+ function scheduleNotFound() {
3542
+ return new AlvaError("NOT_FOUND", "channel schedule target not found", 404);
3543
+ }
3544
+ function scheduleEmptyResponse() {
3545
+ return new AlvaError(
3546
+ "GRAPHQL_EMPTY_RESPONSE",
3547
+ "GraphQL response did not include a valid schedule",
3548
+ 502
3549
+ );
3550
+ }
3551
+
3178
3552
  // src/client.ts
3179
3553
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
3180
3554
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
@@ -3283,6 +3657,7 @@ var AlvaClient = class {
3283
3657
  _functions;
3284
3658
  _credits;
3285
3659
  _markets;
3660
+ _schedules;
3286
3661
  constructor(config) {
3287
3662
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
3288
3663
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -3380,6 +3755,9 @@ var AlvaClient = class {
3380
3755
  get markets() {
3381
3756
  return this._markets ??= new MarketsResource(this);
3382
3757
  }
3758
+ get schedules() {
3759
+ return this._schedules ??= new SchedulesResource(this);
3760
+ }
3383
3761
  _requireAuth() {
3384
3762
  if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
3385
3763
  throw new AlvaError(
@@ -3993,7 +4371,7 @@ var installPlaybookRuntime = (targetWindow) => {
3993
4371
  };
3994
4372
 
3995
4373
  // src/index.ts
3996
- var VERSION = true ? "0.25.0" : "dev";
4374
+ var VERSION = true ? "0.25.2-beta.0" : "dev";
3997
4375
  // Annotate the CommonJS export names for ESM import in node:
3998
4376
  0 && (module.exports = {
3999
4377
  AlertsResource,
@@ -4007,6 +4385,7 @@ var VERSION = true ? "0.25.0" : "dev";
4007
4385
  SUBSCRIBE_MANAGE_MESSAGE,
4008
4386
  SUBSCRIBE_PROPOSE_MESSAGE,
4009
4387
  SUBSCRIBE_RESULT_MESSAGE,
4388
+ SchedulesResource,
4010
4389
  UDF_AUTH_REQUIRED_MESSAGE,
4011
4390
  UDF_CONSENT_REQUEST_MESSAGE,
4012
4391
  UDF_CONSENT_RESPONSE_MESSAGE,