@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/cli.js CHANGED
@@ -9069,6 +9069,379 @@ var MarketsResource = class {
9069
9069
  }
9070
9070
  };
9071
9071
 
9072
+ // src/resources/schedules.ts
9073
+ var SCHEDULE_FIELDS = `
9074
+ id
9075
+ channel { id }
9076
+ name
9077
+ rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
9078
+ bounds { startsAtMs untilMs maxOccurrences }
9079
+ message { text }
9080
+ status
9081
+ failureCode
9082
+ failureAtMs
9083
+ occurrencesUsed
9084
+ nextFireAtMs
9085
+ createdAtMs
9086
+ updatedAtMs
9087
+ `;
9088
+ var LIST_SCHEDULES = `
9089
+ query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
9090
+ viewer { channel(id: $channelId) {
9091
+ schedules(input: { first: 64, after: $after }) {
9092
+ edges { node { ${SCHEDULE_FIELDS} } }
9093
+ pageInfo { hasNextPage endCursor }
9094
+ }
9095
+ } }
9096
+ }`.trim();
9097
+ var UPDATE_SCHEDULE = `
9098
+ mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
9099
+ updateChannelSchedule(input: $input) {
9100
+ schedule { ${SCHEDULE_FIELDS} }
9101
+ deleted
9102
+ }
9103
+ }`.trim();
9104
+ var AGENT_CHANNEL = `
9105
+ query ToolkitAgentChannel {
9106
+ viewer { channels { id kind } }
9107
+ }`.trim();
9108
+ var SCHEDULE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
9109
+ var RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i;
9110
+ var ISO_DURATION = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
9111
+ var GRAPHQL_STATUS_BY_CODE = {
9112
+ INVALID_ARGUMENT: 400,
9113
+ UNAUTHENTICATED: 401,
9114
+ PERMISSION_DENIED: 403,
9115
+ NOT_FOUND: 404,
9116
+ ALREADY_EXISTS: 409,
9117
+ ABORTED: 409,
9118
+ FAILED_PRECONDITION: 412,
9119
+ RESOURCE_EXHAUSTED: 429,
9120
+ INTERNAL: 500,
9121
+ UNKNOWN: 500,
9122
+ DATA_LOSS: 500,
9123
+ UNAVAILABLE: 503,
9124
+ DEADLINE_EXCEEDED: 504
9125
+ };
9126
+ var SchedulesResource = class {
9127
+ constructor(client) {
9128
+ this.client = client;
9129
+ }
9130
+ client;
9131
+ async list(params) {
9132
+ this.client._requireAuth();
9133
+ const id = channelID(params.channelId);
9134
+ const schedules = [];
9135
+ let after = null;
9136
+ const seenCursors = /* @__PURE__ */ new Set();
9137
+ for (; ; ) {
9138
+ const data = await this.graphql(
9139
+ LIST_SCHEDULES,
9140
+ { channelId: id, after }
9141
+ );
9142
+ const connection = data.viewer?.channel?.schedules;
9143
+ if (!connection?.edges) throw scheduleNotFound();
9144
+ for (const edge of connection.edges) {
9145
+ if (!edge?.node) throw scheduleEmptyResponse();
9146
+ schedules.push(fromWireSchedule(edge.node));
9147
+ }
9148
+ if (connection.pageInfo?.hasNextPage !== true) return schedules;
9149
+ const next = connection.pageInfo.endCursor;
9150
+ if (!next || seenCursors.has(next)) throw scheduleEmptyResponse();
9151
+ seenCursors.add(next);
9152
+ after = next;
9153
+ }
9154
+ }
9155
+ async put(params) {
9156
+ this.client._requireAuth();
9157
+ const input = {
9158
+ channelId: channelID(params.channelId),
9159
+ name: requireName(params.name),
9160
+ definition: {
9161
+ ...ruleInput(params.rule, params.bounds),
9162
+ message: { text: requireText(params.text) }
9163
+ }
9164
+ };
9165
+ const data = await this.graphql(UPDATE_SCHEDULE, { input });
9166
+ const schedule = data.updateChannelSchedule?.schedule;
9167
+ if (!schedule) throw scheduleEmptyResponse();
9168
+ return fromWireSchedule(schedule);
9169
+ }
9170
+ pause(params) {
9171
+ return this.manage("PAUSED", params);
9172
+ }
9173
+ resume(params) {
9174
+ return this.manage("ACTIVE", params);
9175
+ }
9176
+ async delete(params) {
9177
+ this.client._requireAuth();
9178
+ const data = await this.graphql(UPDATE_SCHEDULE, {
9179
+ input: { ...managementInput(params), lifecycle: "REMOVED" }
9180
+ });
9181
+ if (data.updateChannelSchedule?.deleted !== true)
9182
+ throw scheduleEmptyResponse();
9183
+ }
9184
+ /** Resolve the authenticated viewer's unique Agent Channel for CLI defaults. */
9185
+ async agentChannelId() {
9186
+ this.client._requireAuth();
9187
+ const data = await this.graphql(AGENT_CHANNEL);
9188
+ const id = data.viewer?.channels?.find(
9189
+ (channel) => channel.kind === "AGENT"
9190
+ )?.id;
9191
+ if (!id) throw scheduleNotFound();
9192
+ return id;
9193
+ }
9194
+ async manage(lifecycle, params) {
9195
+ this.client._requireAuth();
9196
+ const data = await this.graphql(UPDATE_SCHEDULE, {
9197
+ input: { ...managementInput(params), lifecycle }
9198
+ });
9199
+ const schedule = data.updateChannelSchedule?.schedule;
9200
+ if (!schedule) throw scheduleEmptyResponse();
9201
+ return fromWireSchedule(schedule);
9202
+ }
9203
+ async graphql(query, variables) {
9204
+ const response = await this.client._request("POST", "/query", {
9205
+ body: variables === void 0 ? { query } : { query, variables }
9206
+ });
9207
+ if (response.errors?.length) {
9208
+ const codes = response.errors.map((error) => error.extensions?.code);
9209
+ const distinctCodes = new Set(codes);
9210
+ const canonicalCode = distinctCodes.size === 1 && typeof codes[0] === "string" ? codes[0] : void 0;
9211
+ const canonicalStatus = canonicalCode ? GRAPHQL_STATUS_BY_CODE[canonicalCode] : void 0;
9212
+ const errorCode = canonicalCode !== void 0 && canonicalStatus !== void 0 ? canonicalCode : "GRAPHQL_ERROR";
9213
+ throw new AlvaError(
9214
+ errorCode,
9215
+ response.errors.map((error) => error.message).filter((message) => typeof message === "string").join("; ") || "GraphQL request failed",
9216
+ canonicalStatus ?? 502,
9217
+ { errors: response.errors }
9218
+ );
9219
+ }
9220
+ if (!response.data) throw scheduleEmptyResponse();
9221
+ return response.data;
9222
+ }
9223
+ };
9224
+ function ruleInput(rule, bounds) {
9225
+ const convertedBounds = boundsInput(bounds);
9226
+ switch (rule.kind) {
9227
+ case "after":
9228
+ if (convertedBounds)
9229
+ throw invalid("after does not accept recurring bounds");
9230
+ const requestedAt = Date.now() + durationMilliseconds(rule.duration, 1);
9231
+ const atMs = Math.ceil(requestedAt / 1e3) * 1e3;
9232
+ if (!Number.isSafeInteger(atMs) || Number.isNaN(new Date(atMs).getTime()))
9233
+ throw invalid("after is out of range");
9234
+ return {
9235
+ rule: {
9236
+ kind: "AT",
9237
+ atMs
9238
+ }
9239
+ };
9240
+ case "at":
9241
+ if (convertedBounds) throw invalid("at does not accept recurring bounds");
9242
+ return {
9243
+ rule: { kind: "AT", atMs: timestampMilliseconds(rule.timestamp) }
9244
+ };
9245
+ case "every":
9246
+ return {
9247
+ rule: {
9248
+ kind: "EVERY",
9249
+ everyIntervalSeconds: durationSeconds(rule.interval)
9250
+ },
9251
+ ...convertedBounds ? { bounds: convertedBounds } : {}
9252
+ };
9253
+ case "cron":
9254
+ if (!rule.expression.trim() || !rule.timezone.trim()) {
9255
+ throw invalid("cron expression and timezone are required");
9256
+ }
9257
+ return {
9258
+ rule: {
9259
+ kind: "CRON",
9260
+ cronExpression: rule.expression,
9261
+ cronTimezone: rule.timezone
9262
+ },
9263
+ ...convertedBounds ? { bounds: convertedBounds } : {}
9264
+ };
9265
+ }
9266
+ }
9267
+ function boundsInput(bounds) {
9268
+ if (!bounds) return void 0;
9269
+ const result = {};
9270
+ if (bounds.startsAt !== void 0)
9271
+ result.startsAtMs = timestampMilliseconds(bounds.startsAt);
9272
+ if (bounds.until !== void 0)
9273
+ result.untilMs = timestampMilliseconds(bounds.until);
9274
+ if (bounds.maxOccurrences !== void 0) {
9275
+ if (!Number.isSafeInteger(bounds.maxOccurrences) || bounds.maxOccurrences <= 0) {
9276
+ throw invalid("maxOccurrences must be a positive safe integer");
9277
+ }
9278
+ result.maxOccurrences = bounds.maxOccurrences;
9279
+ }
9280
+ return Object.keys(result).length > 0 ? result : void 0;
9281
+ }
9282
+ function fromWireSchedule(schedule) {
9283
+ const statuses = {
9284
+ ACTIVE: "active",
9285
+ PAUSED: "paused",
9286
+ COMPLETED: "completed",
9287
+ FAILED: "failed"
9288
+ };
9289
+ const status = statuses[schedule.status];
9290
+ if (!status) throw scheduleEmptyResponse();
9291
+ const bounds = schedule.bounds ?? {};
9292
+ const message = schedule.message ?? {};
9293
+ const result = {
9294
+ name: schedule.name,
9295
+ rule: fromWireRule(schedule.rule),
9296
+ bounds: {
9297
+ ...bounds.startsAtMs != null ? { startsAt: timestampString(bounds.startsAtMs, true) } : {},
9298
+ ...bounds.untilMs != null ? { until: timestampString(bounds.untilMs, true) } : {},
9299
+ ...bounds.maxOccurrences != null ? {
9300
+ maxOccurrences: safeInteger(
9301
+ bounds.maxOccurrences,
9302
+ "maxOccurrences"
9303
+ )
9304
+ } : {}
9305
+ },
9306
+ text: message.text ?? "",
9307
+ status,
9308
+ occurrencesUsed: safeInteger(schedule.occurrencesUsed, "occurrencesUsed"),
9309
+ ...schedule.nextFireAtMs != null ? { nextFireAt: timestampString(schedule.nextFireAtMs, true) } : {},
9310
+ createdAt: timestampString(schedule.createdAtMs),
9311
+ updatedAt: timestampString(schedule.updatedAtMs)
9312
+ };
9313
+ if (status === "failed") {
9314
+ if (!schedule.failureCode) throw scheduleEmptyResponse();
9315
+ const failureCodes = {
9316
+ TARGET_INVALID: "target_invalid",
9317
+ DELIVERY_EXHAUSTED: "delivery_exhausted",
9318
+ PAYLOAD_CONFLICT: "payload_conflict"
9319
+ };
9320
+ const code = failureCodes[schedule.failureCode];
9321
+ if (!code) throw scheduleEmptyResponse();
9322
+ result.failure = {
9323
+ code,
9324
+ ...schedule.failureAtMs != null ? { at: timestampString(schedule.failureAtMs) } : {}
9325
+ };
9326
+ }
9327
+ return result;
9328
+ }
9329
+ function fromWireRule(rule) {
9330
+ switch (rule.kind) {
9331
+ case "AT":
9332
+ if (rule.atMs == null) throw scheduleEmptyResponse();
9333
+ return { kind: "at", timestamp: timestampString(rule.atMs, true) };
9334
+ case "EVERY":
9335
+ if (rule.everyIntervalSeconds == null) throw scheduleEmptyResponse();
9336
+ return {
9337
+ kind: "every",
9338
+ interval: `PT${safeInteger(rule.everyIntervalSeconds, "interval")}S`
9339
+ };
9340
+ case "CRON":
9341
+ if (!rule.cronExpression || !rule.cronTimezone)
9342
+ throw scheduleEmptyResponse();
9343
+ return {
9344
+ kind: "cron",
9345
+ expression: rule.cronExpression,
9346
+ timezone: rule.cronTimezone
9347
+ };
9348
+ }
9349
+ throw scheduleEmptyResponse();
9350
+ }
9351
+ function managementInput(params) {
9352
+ return {
9353
+ channelId: channelID(params.channelId),
9354
+ name: requireName(params.name)
9355
+ };
9356
+ }
9357
+ function channelID(value) {
9358
+ if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) {
9359
+ throw invalid(
9360
+ "numeric channelId must be a positive safe integer; use a decimal string for larger IDs"
9361
+ );
9362
+ }
9363
+ const rendered = String(value);
9364
+ if (!/^[1-9]\d*$/.test(rendered))
9365
+ throw invalid("channelId must be a positive integer");
9366
+ return rendered;
9367
+ }
9368
+ function requireName(value) {
9369
+ if (!SCHEDULE_NAME.test(value))
9370
+ throw invalid(
9371
+ "name must be 1-63 lowercase alphanumeric characters or hyphens"
9372
+ );
9373
+ return value;
9374
+ }
9375
+ function requireText(value) {
9376
+ const size = utf8Size(value);
9377
+ if (size === void 0 || !value.trim() || size > 16 * 1024)
9378
+ throw invalid("text must be 1..16384 UTF-8 bytes");
9379
+ return value;
9380
+ }
9381
+ function durationSeconds(value) {
9382
+ const milliseconds = durationMilliseconds(value, 60);
9383
+ if (milliseconds % 1e3 !== 0)
9384
+ throw invalid("duration must resolve to whole seconds");
9385
+ return milliseconds / 1e3;
9386
+ }
9387
+ function durationMilliseconds(value, minimumSeconds) {
9388
+ const match = ISO_DURATION.exec(value);
9389
+ if (!match || match.slice(1, 5).every((part) => part === void 0) || value.includes("T") && match.slice(2, 5).every((part) => part === void 0)) {
9390
+ throw invalid("duration must be a positive ISO 8601 day/time duration");
9391
+ }
9392
+ const [days, hours, minutes, seconds] = match.slice(1, 5).map((part) => BigInt(part ?? "0"));
9393
+ const totalSeconds = ((days * 24n + hours) * 60n + minutes) * 60n + seconds;
9394
+ if (totalSeconds < BigInt(minimumSeconds)) {
9395
+ throw invalid(`duration must be at least ${minimumSeconds} whole seconds`);
9396
+ }
9397
+ const result = Number(totalSeconds * 1000n);
9398
+ if (!Number.isSafeInteger(result)) throw invalid("duration is out of range");
9399
+ return result;
9400
+ }
9401
+ function timestampMilliseconds(value) {
9402
+ const match = RFC3339.exec(value);
9403
+ if (!match) throw invalid("timestamp must be RFC3339 with a timezone");
9404
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
9405
+ const offsetHour = Number(match[8] ?? 0);
9406
+ const offsetMinute = Number(match[9] ?? 0);
9407
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
9408
+ const result = Date.parse(value);
9409
+ 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) {
9410
+ throw invalid("timestamp must be RFC3339 with a timezone");
9411
+ }
9412
+ return result;
9413
+ }
9414
+ function timestampString(value, semantic = false) {
9415
+ if (!Number.isSafeInteger(value)) throw scheduleEmptyResponse();
9416
+ if (semantic && value % 1e3 !== 0) throw scheduleEmptyResponse();
9417
+ const timestamp = new Date(value);
9418
+ if (Number.isNaN(timestamp.getTime())) throw scheduleEmptyResponse();
9419
+ return timestamp.toISOString();
9420
+ }
9421
+ function safeInteger(value, field) {
9422
+ const result = Number(value);
9423
+ if (!Number.isSafeInteger(result) || result < 0)
9424
+ throw invalid(`${field} exceeds JavaScript safe integer range`);
9425
+ return result;
9426
+ }
9427
+ function invalid(message) {
9428
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
9429
+ }
9430
+ function utf8Size(value) {
9431
+ const bytes = new TextEncoder().encode(value);
9432
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes) === value ? bytes.byteLength : void 0;
9433
+ }
9434
+ function scheduleNotFound() {
9435
+ return new AlvaError("NOT_FOUND", "channel schedule target not found", 404);
9436
+ }
9437
+ function scheduleEmptyResponse() {
9438
+ return new AlvaError(
9439
+ "GRAPHQL_EMPTY_RESPONSE",
9440
+ "GraphQL response did not include a valid schedule",
9441
+ 502
9442
+ );
9443
+ }
9444
+
9072
9445
  // src/client.ts
9073
9446
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
9074
9447
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
@@ -9177,6 +9550,7 @@ var AlvaClient = class {
9177
9550
  _functions;
9178
9551
  _credits;
9179
9552
  _markets;
9553
+ _schedules;
9180
9554
  constructor(config) {
9181
9555
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
9182
9556
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -9274,6 +9648,9 @@ var AlvaClient = class {
9274
9648
  get markets() {
9275
9649
  return this._markets ??= new MarketsResource(this);
9276
9650
  }
9651
+ get schedules() {
9652
+ return this._schedules ??= new SchedulesResource(this);
9653
+ }
9277
9654
  _requireAuth() {
9278
9655
  if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
9279
9656
  throw new AlvaError(
@@ -9690,19 +10067,25 @@ var COMMAND_DEFINITIONS = [
9690
10067
  values: ["id", "workflow-run-id"]
9691
10068
  }),
9692
10069
  command("deploy run-logs", { values: ["id", "run-id"] }),
9693
- command("loop create", {
10070
+ command("schedule list", { values: ["channel-id"] }),
10071
+ command("schedule put", {
9694
10072
  values: [
9695
- "goal",
9696
- "cron",
9697
10073
  "channel-id",
9698
- "start",
9699
- "until",
9700
- "runs",
9701
10074
  "name",
9702
- // Retained so the handler can emit the existing migration guidance.
9703
- "expires-in"
10075
+ "message",
10076
+ "at",
10077
+ "after",
10078
+ "every",
10079
+ "cron",
10080
+ "timezone",
10081
+ "starts-at",
10082
+ "until",
10083
+ "max-occurrences"
9704
10084
  ]
9705
10085
  }),
10086
+ command("schedule pause", { values: ["channel-id", "name"] }),
10087
+ command("schedule resume", { values: ["channel-id", "name"] }),
10088
+ command("schedule delete", { values: ["channel-id", "name"] }),
9706
10089
  command("service-account create", { values: ["name"] }),
9707
10090
  command("service-account list"),
9708
10091
  command("service-account delete", { values: ["id"] }),
@@ -14288,7 +14671,7 @@ ${formatReport(report, "human")}
14288
14671
  }
14289
14672
 
14290
14673
  // src/cli/dispatch.ts
14291
- var CLI_VERSION = true ? "0.25.0" : "dev";
14674
+ var CLI_VERSION = true ? "0.25.2-beta.0" : "dev";
14292
14675
  var DEFAULT_RUN_TIMEOUT_MS = 6e5;
14293
14676
  var RUN_TIMEOUT_ENV = "ALVA_RUN_TIMEOUT_MS";
14294
14677
  var GLOBAL_VALUE_FLAGS = Object.entries(GLOBAL_FLAG_DEFINITIONS).filter(([, kind]) => kind === "value").map(([name]) => `--${name}`);
@@ -14330,7 +14713,7 @@ Commands:
14330
14713
  fs Filesystem operations (read, write, stat, readdir, mkdir, remove, rename, copy, symlink, readlink, chmod, grant, revoke)
14331
14714
  run Execute code in the Alva runtime
14332
14715
  deploy Cronjob management (create, list, get, update, delete, pause, resume, runs, run-logs)
14333
- loop Self-scheduled in-channel goal loops (create)
14716
+ schedule Agent-owned named schedules (list, put, pause, resume, delete)
14334
14717
  service-account Restricted run-as identities (create, list, delete, grant, revoke)
14335
14718
  release Feed and playbook releases (feed, playbook-draft, playbook)
14336
14719
  lint Design-system lint (playbook)
@@ -14700,36 +15083,35 @@ Build-time verify (fire once, then poll up to 5 minutes):
14700
15083
  esac
14701
15084
  [ "$STATE" = COMPLETED ] || alva deploy run-logs --id 42 \\
14702
15085
  --run-id "$(echo "$STATUS_JSON" | jq -r .run.id)"`,
14703
- loop: `Usage: alva loop <subcommand> [options]
15086
+ schedule: `Usage: alva schedule <subcommand> [options]
14704
15087
 
14705
- Create a bounded, self-scheduled goal loop in an Alva channel. Each tick runs
14706
- one fire-and-forget agent turn on the Alva channel's stable main
14707
- session (via the @alva/loop SDK), continuing that conversation toward a goal. Creation
14708
- seeds a shared runner, creates its cronjob, and registers the cronjob as an
14709
- Automation without starting an extra publish-time run.
15088
+ Manage named future and recurring work for an Alva Channel Agent.
14710
15089
 
14711
15090
  Subcommands:
14712
- create Create a loop and its visible Automation
15091
+ list List schedules
15092
+ put Create or replace a schedule by name
15093
+ pause Pause a schedule
15094
+ resume Resume a schedule
15095
+ delete Delete a schedule
14713
15096
 
14714
- Create flags:
14715
- --goal <text> Instruction run each tick (required)
14716
- --cron <expression> Cron schedule (required, e.g. "0 * * * *")
14717
- --channel-id <id> Target Alva channel ID. Omit \u21D2 your default
14718
- Alva agent channel
14719
- --start <time> First eligible time: 'now' (default) or RFC3339
14720
- --until <time> Exclusive RFC3339 cutoff
14721
- --runs <count> Maximum admitted runs after --start
14722
- --name <name> Cronjob name (default: derived from --goal;
14723
- 1-63 lowercase alphanumeric/hyphens)
14724
-
14725
- At least one of --until or --runs is required. RFC3339 timestamps must include
14726
- a timezone (Z or \xB1HH:MM). The result includes automation_id and cronjob_id.
14727
- Use 'alva automation inspect/stop/resume/delete --id <automation_id>' for
14728
- lifecycle management; deletion also removes the Automation's producer cronjob.
15097
+ Common flags:
15098
+ --channel-id <id> Target Channel; omit for your Agent Channel
15099
+ --name <name> Stable schedule name
15100
+
15101
+ Put flags:
15102
+ --message <text> Agent instruction delivered at each occurrence
15103
+ Choose exactly one: --after <ISO duration>, --at <RFC3339>,
15104
+ --every <ISO duration>, or --cron <five fields>
15105
+ --timezone <IANA> Required with --cron
15106
+ --starts-at <RFC3339> Inclusive recurrence lower bound
15107
+ --until <RFC3339> Exclusive recurrence upper bound
15108
+ --max-occurrences <n> Positive recurrence count bound
14729
15109
 
14730
15110
  Examples:
14731
- alva loop create --channel-id 7284... --goal "watch NVDA pre-market, alert on setup" --cron "*/5 * * * *" --until "2026-07-15T09:30:00-04:00"
14732
- alva loop create --goal "check the next 12 intervals" --cron "0 * * * *" --start now --runs 12`,
15111
+ alva schedule put --name review --message "Review status" --after PT30M
15112
+ alva schedule put --name market-open --message "Review the open" --cron "30 9 * * 1-5" --timezone America/New_York
15113
+ alva schedule list
15114
+ alva schedule pause --name market-open`,
14733
15115
  "service-account": `Usage: alva service-account <subcommand> [options]
14734
15116
 
14735
15117
  Manage restricted run-as identities. A service account executes a UDF or
@@ -15985,84 +16367,69 @@ function parseCreditsDurationMs(value) {
15985
16367
  }
15986
16368
  return durationMs;
15987
16369
  }
15988
- var LOOP_RUNNER_PATH = "~/loops/_runner/index.js";
15989
- var LOOP_RUNNER_SRC = [
15990
- "const { loop } = require('@alva/loop');",
15991
- "const { goal, channelId } = require('env').args;",
15992
- "loop(goal, channelId ? { channelId } : {});",
15993
- ""
15994
- ].join("\n");
15995
- function parseLoopTimestamp(value, flag) {
15996
- const raw = value.trim();
15997
- const match = /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[zZ]|([+-])(\d{2}):(\d{2}))$/.exec(
15998
- raw
16370
+ async function scheduleChannelId(client, flags) {
16371
+ return flags["channel-id"] ?? client.schedules.agentChannelId();
16372
+ }
16373
+ function scheduleRuleFromFlags(flags) {
16374
+ const selected = ["after", "at", "every", "cron"].filter(
16375
+ (flag) => flags[flag] !== void 0
15999
16376
  );
16000
- if (!match) {
16377
+ if (selected.length !== 1) {
16001
16378
  throw new CliUsageError(
16002
- `--${flag} must be an RFC3339 timestamp with a timezone (Z or \xB1HH:MM), got '${value}'`,
16003
- "loop"
16379
+ "schedule put requires exactly one of --after, --at, --every, or --cron",
16380
+ "schedule"
16004
16381
  );
16005
16382
  }
16006
- const year = Number(match[1]);
16007
- const month = Number(match[2]);
16008
- const day = Number(match[3]);
16009
- const hour = Number(match[4]);
16010
- const minute = Number(match[5]);
16011
- const second = Number(match[6]);
16012
- const offsetHour = Number(match[8] ?? 0);
16013
- const offsetMinute = Number(match[9] ?? 0);
16014
- const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
16015
- const monthDays = [
16016
- 31,
16017
- leapYear ? 29 : 28,
16018
- 31,
16019
- 30,
16020
- 31,
16021
- 30,
16022
- 31,
16023
- 31,
16024
- 30,
16025
- 31,
16026
- 30,
16027
- 31
16028
- ];
16029
- if (month < 1 || month > 12 || day < 1 || day > monthDays[month - 1] || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
16383
+ if (selected[0] !== "cron" && flags["timezone"] !== void 0) {
16384
+ throw new CliUsageError("--timezone is only valid with --cron", "schedule");
16385
+ }
16386
+ switch (selected[0]) {
16387
+ case "after":
16388
+ return { kind: "after", duration: flags["after"] };
16389
+ case "at":
16390
+ return {
16391
+ kind: "at",
16392
+ timestamp: parseScheduleTimestamp(flags["at"], "at")
16393
+ };
16394
+ case "every":
16395
+ return { kind: "every", interval: flags["every"] };
16396
+ default:
16397
+ return {
16398
+ kind: "cron",
16399
+ expression: flags["cron"],
16400
+ timezone: requireFlag(flags, "timezone", "schedule put")
16401
+ };
16402
+ }
16403
+ }
16404
+ function parseScheduleTimestamp(value, flag) {
16405
+ const raw = value.trim();
16406
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:Z|[+-](\d{2}):(\d{2}))$/i.exec(
16407
+ raw
16408
+ );
16409
+ if (!match) {
16030
16410
  throw new CliUsageError(
16031
- `--${flag} must be a valid RFC3339 timestamp, got '${value}'`,
16032
- "loop"
16411
+ `--${flag} must be an RFC3339 timestamp with a timezone`,
16412
+ "schedule"
16033
16413
  );
16034
16414
  }
16035
- const timestamp = Date.parse(raw);
16036
- if (!Number.isFinite(timestamp)) {
16415
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
16416
+ const offsetHour = Number(match[7] ?? 0);
16417
+ const offsetMinute = Number(match[8] ?? 0);
16418
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
16419
+ const parsed = Date.parse(raw);
16420
+ if (!Number.isFinite(parsed) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
16037
16421
  throw new CliUsageError(
16038
- `--${flag} must be a valid RFC3339 timestamp, got '${value}'`,
16039
- "loop"
16422
+ `--${flag} must be a valid RFC3339 timestamp with a timezone`,
16423
+ "schedule"
16040
16424
  );
16041
16425
  }
16042
- return new Date(timestamp).toISOString();
16043
- }
16044
- function parseLoopRuns(value) {
16045
- if (value === void 0) return void 0;
16046
- if (!/^[1-9]\d*$/.test(value)) {
16047
- throw new CliUsageError("--runs must be a positive integer", "loop");
16048
- }
16049
- const runs = Number(value);
16050
- if (!Number.isSafeInteger(runs) || runs > 2147483647) {
16051
- throw new CliUsageError("--runs is too large", "loop");
16052
- }
16053
- return runs;
16426
+ return new Date(parsed).toISOString().replace(".000Z", "Z");
16054
16427
  }
16055
- function loopCronjobName(flags, goal) {
16056
- if (flags["name"] !== void 0) return flags["name"];
16057
- const base = goal.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
16058
- const slug = (base ? `loop-${base}` : "loop").slice(0, 63).replace(/-+$/g, "");
16059
- return slug || "loop";
16060
- }
16061
- function loopAutomationDescription(goal) {
16062
- const prefix = "Channel loop: ";
16063
- const maxDescriptionRunes = 4096;
16064
- const availableGoalRunes = maxDescriptionRunes - Array.from(prefix).length;
16065
- return prefix + Array.from(goal).slice(0, availableGoalRunes).join("");
16428
+ function scheduleBoundsFromFlags(flags) {
16429
+ const startsAt = flags["starts-at"] !== void 0 ? parseScheduleTimestamp(flags["starts-at"], "starts-at") : void 0;
16430
+ const until = flags["until"] !== void 0 ? parseScheduleTimestamp(flags["until"], "until") : void 0;
16431
+ const maxOccurrences = flags["max-occurrences"] !== void 0 ? requirePositiveIntegerFlag(flags, "max-occurrences", "schedule put") : void 0;
16432
+ return startsAt !== void 0 || until !== void 0 || maxOccurrences !== void 0 ? { startsAt, until, maxOccurrences } : void 0;
16066
16433
  }
16067
16434
  function parseCreditsItemsParams(flags) {
16068
16435
  const command2 = "credits items";
@@ -16611,83 +16978,64 @@ async function executeParsedCommand(client, parsedCommand, meta, deps) {
16611
16978
  );
16612
16979
  }
16613
16980
  }
16614
- case "loop": {
16615
- if (!subcommand)
16616
- throw new CliUsageError("Missing subcommand for loop", "loop");
16981
+ case "schedule": {
16982
+ if (!subcommand) {
16983
+ throw new CliUsageError("Missing subcommand for schedule", "schedule");
16984
+ }
16617
16985
  switch (subcommand) {
16618
- case "create": {
16619
- if (flags["expires-in"] !== void 0) {
16620
- throw new CliUsageError(
16621
- "Unknown flag --expires-in; use --until and/or --runs",
16622
- "loop"
16623
- );
16624
- }
16625
- const goal = requireFlag(flags, "goal", "loop create");
16626
- const cron = requireFlag(flags, "cron", "loop create");
16627
- const channelId = flags["channel-id"];
16628
- const startRaw = (flags["start"] ?? "now").trim();
16629
- const startAt = startRaw.toLowerCase() === "now" ? void 0 : parseLoopTimestamp(startRaw, "start");
16630
- const endAt = flags["until"] ? parseLoopTimestamp(flags["until"], "until") : void 0;
16631
- const maxRuns = parseLoopRuns(flags["runs"]);
16632
- if (endAt === void 0 && maxRuns === void 0) {
16633
- throw new CliUsageError(
16634
- "loop create requires at least one of --until or --runs",
16635
- "loop"
16636
- );
16637
- }
16638
- if (startAt !== void 0 && endAt !== void 0 && endAt <= startAt) {
16986
+ case "list": {
16987
+ const channelId = await scheduleChannelId(client, flags);
16988
+ return client.schedules.list({ channelId });
16989
+ }
16990
+ case "put": {
16991
+ const rule = scheduleRuleFromFlags(flags);
16992
+ const bounds = scheduleBoundsFromFlags(flags);
16993
+ if ((rule.kind === "at" || rule.kind === "after") && bounds !== void 0) {
16639
16994
  throw new CliUsageError(
16640
- "--until must be later than --start",
16641
- "loop"
16995
+ `${rule.kind} does not accept recurring bounds`,
16996
+ "schedule"
16642
16997
  );
16643
16998
  }
16644
- const name = loopCronjobName(flags, goal);
16645
- await client.fs.write({
16646
- path: LOOP_RUNNER_PATH,
16647
- data: LOOP_RUNNER_SRC,
16648
- mkdir_parents: true
16649
- });
16650
- const cronjob = await client.deploy.create({
16999
+ const name = requireFlag(flags, "name", "schedule put");
17000
+ const text = requireFlag(flags, "message", "schedule put");
17001
+ const channelId = await scheduleChannelId(client, flags);
17002
+ return client.schedules.put({
17003
+ channelId,
16651
17004
  name,
16652
- path: LOOP_RUNNER_PATH,
16653
- cron_expression: cron,
16654
- args: channelId ? { goal, channelId } : { goal },
16655
- start_at: startAt,
16656
- end_at: endAt,
16657
- max_runs: maxRuns
17005
+ text,
17006
+ rule,
17007
+ bounds
16658
17008
  });
16659
- try {
16660
- const automation = await client.automation.publish({
16661
- name,
16662
- version: "1.0.0",
16663
- cronjob_id: cronjob.id,
16664
- description: loopAutomationDescription(goal),
16665
- skip_auto_trigger: true
16666
- });
16667
- return {
16668
- name,
16669
- automation_id: String(automation.feed_id),
16670
- cronjob_id: cronjob.id
16671
- };
16672
- } catch (publishError) {
16673
- const publishMessage = publishError instanceof Error ? publishError.message : String(publishError);
16674
- try {
16675
- await client.deploy.delete({ id: cronjob.id });
16676
- } catch (rollbackError) {
16677
- const rollbackMessage = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
16678
- throw new Error(
16679
- `failed to publish loop "${name}" as an automation after creating cronjob ${cronjob.id}: ${publishMessage}; automatic rollback failed: ${rollbackMessage}; cronjob ${cronjob.id} may still exist; run \`alva deploy delete --id ${cronjob.id}\``
16680
- );
16681
- }
16682
- throw new Error(
16683
- `failed to publish loop "${name}" as an automation; rolled back cronjob ${cronjob.id}: ${publishMessage}`
16684
- );
16685
- }
17009
+ }
17010
+ case "pause": {
17011
+ const name = requireFlag(flags, "name", "schedule pause");
17012
+ const channelId = await scheduleChannelId(client, flags);
17013
+ return client.schedules.pause({
17014
+ channelId,
17015
+ name
17016
+ });
17017
+ }
17018
+ case "resume": {
17019
+ const name = requireFlag(flags, "name", "schedule resume");
17020
+ const channelId = await scheduleChannelId(client, flags);
17021
+ return client.schedules.resume({
17022
+ channelId,
17023
+ name
17024
+ });
17025
+ }
17026
+ case "delete": {
17027
+ const name = requireFlag(flags, "name", "schedule delete");
17028
+ const channelId = await scheduleChannelId(client, flags);
17029
+ await client.schedules.delete({
17030
+ channelId,
17031
+ name
17032
+ });
17033
+ return { deleted: true };
16686
17034
  }
16687
17035
  default:
16688
17036
  throw new CliUsageError(
16689
- `Unknown subcommand: loop ${subcommand}`,
16690
- "loop"
17037
+ `Unknown subcommand: schedule ${subcommand}`,
17038
+ "schedule"
16691
17039
  );
16692
17040
  }
16693
17041
  }