@alook/daemon 0.1.72 → 0.1.74

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/index.js CHANGED
@@ -44100,11 +44100,53 @@ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
44100
44100
  if (channels.size !== bundle.channels.length || servers.size !== bundle.servers.length || new Set(categories.map((row) => row.id)).size !== categories.length || categories.some((row) => readableCategories.get(row.id) !== row.serverId) || new Set(dmPeers.map((row) => row.channelId)).size !== dmPeers.length || dmPeers.some((row) => !dmChannels.has(row.channelId) || row.userId === bundle.viewerId || !profiles.has(row.userId)) || new Set(bundle.messages.map((row) => row.id)).size !== bundle.messages.length || profiles.size !== bundle.profiles.length || new Set(bundle.memberships.map((row) => `${row.channelId}:${row.userId}:${row.relation}`)).size !== bundle.memberships.length || new Set(bundle.serverMemberships.map((row) => `${row.serverId}:${row.userId}`)).size !== bundle.serverMemberships.length || bundle.messages.some((row) => !channels.has(row.channelId)) || bundle.servers.some((row) => !bundle.serverMemberships.some((member) => member.serverId === row.id && member.userId === bundle.viewerId)) || bundle.channels.some((row) => !bundle.memberships.some((member) => member.channelId === row.id && member.userId === bundle.viewerId && member.relation === "access")) || bundle.channels.some((row) => row.serverId !== null && !servers.has(row.serverId) || row.parentChannelId !== null && !channels.has(row.parentChannelId)) || bundle.memberships.some((row) => row.userId !== bundle.viewerId || !channels.has(row.channelId)) || bundle.serverMemberships.some((row) => row.userId !== bundle.viewerId || !servers.has(row.serverId)))
44101
44101
  ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
44102
44102
  });
44103
+ var CommunityResolvedChannelRefSchema = exports_external.discriminatedUnion("status", [
44104
+ exports_external.strictObject({
44105
+ ref: exports_external.string().min(1),
44106
+ status: exports_external.literal("ready"),
44107
+ serverId: id,
44108
+ channelId: id
44109
+ }),
44110
+ exports_external.strictObject({
44111
+ ref: exports_external.string().min(1),
44112
+ status: exports_external.enum(["forbidden", "missing"])
44113
+ })
44114
+ ]);
44115
+ var CommunityMessageRefsSchema = exports_external.strictObject({
44116
+ servers: exports_external.array(CommunityServerResourceSchema),
44117
+ channels: exports_external.array(CommunityChannelResourceSchema),
44118
+ resolvedRefs: exports_external.array(CommunityResolvedChannelRefSchema)
44119
+ }).superRefine((refs, ctx) => {
44120
+ const serverIds = new Set(refs.servers.map((row) => row.id));
44121
+ const channelById = new Map(refs.channels.map((row) => [row.id, row]));
44122
+ const refKeys = new Set(refs.resolvedRefs.map((row) => row.ref));
44123
+ if (serverIds.size !== refs.servers.length || channelById.size !== refs.channels.length || refKeys.size !== refs.resolvedRefs.length) {
44124
+ ctx.addIssue({ code: "custom", message: "Duplicated ref resource" });
44125
+ return;
44126
+ }
44127
+ for (const channel of refs.channels) {
44128
+ if (channel.serverId === null || !serverIds.has(channel.serverId)) {
44129
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel server missing" });
44130
+ }
44131
+ if (channel.parentChannelId !== null && !channelById.has(channel.parentChannelId)) {
44132
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel parent missing" });
44133
+ }
44134
+ }
44135
+ for (const resolved of refs.resolvedRefs) {
44136
+ if (resolved.status !== "ready")
44137
+ continue;
44138
+ const channel = channelById.get(resolved.channelId);
44139
+ if (!serverIds.has(resolved.serverId) || !channel || channel.serverId !== resolved.serverId) {
44140
+ ctx.addIssue({ code: "custom", path: ["resolvedRefs"], message: "Resolved ref target missing from resources" });
44141
+ }
44142
+ }
44143
+ });
44103
44144
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
44104
44145
  var CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({
44105
44146
  ...envelope,
44106
44147
  page: CommunityPageSchema,
44107
44148
  relatedMessages: exports_external.array(CommunityMessageResourceSchema).optional(),
44149
+ refs: CommunityMessageRefsSchema.optional(),
44108
44150
  surfaceReceipt: exports_external.strictObject({ channelId: id, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
44109
44151
  }).superRefine(validateRelatedMessageGraph);
44110
44152
  var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
@@ -44184,7 +44226,13 @@ var CommunityMessageReadSchema = exports_external.strictObject({
44184
44226
  validateRelatedMessageGraph({ messages: [read.message], relatedMessages: read.relatedMessages, profiles: read.profiles }, ctx);
44185
44227
  });
44186
44228
  var CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: exports_external.boolean(), threadId: id.optional() });
44187
- var CommunityMembersReadSchema = exports_external.strictObject({ ...envelope, relation: exports_external.enum(["access", "notify"]), members: exports_external.array(CommunityMemberRelationSchema), profiles: exports_external.array(CommunityResourceProfileSchema) });
44229
+ var CommunityMembersReadSchema = exports_external.strictObject({
44230
+ ...envelope,
44231
+ relation: exports_external.enum(["access", "notify"]),
44232
+ members: exports_external.array(CommunityMemberRelationSchema),
44233
+ profiles: exports_external.array(CommunityResourceProfileSchema),
44234
+ page: exports_external.strictObject({ nextCursor: exports_external.string().nullable(), hasMore: exports_external.boolean() }).optional()
44235
+ });
44188
44236
  var CommunityThreadsReadSchema = exports_external.strictObject({
44189
44237
  ...envelope,
44190
44238
  channel: CommunityChannelResourceSchema,
@@ -46150,7 +46198,7 @@ var nativeOauthAttempt = sqliteTable("native_oauth_attempt", {
46150
46198
  AND ${t.openedAt} IS NOT NULL AND ${t.readyAt} IS NOT NULL AND ${t.consumedAt} IS NULL
46151
46199
  AND ${t.failedAt} IS NULL AND ${t.cancelledAt} IS NULL AND ${t.replacedAt} IS NULL
46152
46200
  AND ${t.handoffCodeHash} IS NOT NULL AND ${t.handoffExpiresAt} IS NOT NULL
46153
- AND ${t.handoffExpiresAt} = ${t.readyAt} + 120000
46201
+ AND ${t.handoffExpiresAt} = min(${t.readyAt} + 120000, ${t.attemptExpiresAt})
46154
46202
  AND ${t.authKind} IS NOT NULL AND ${t.failureCode} IS NULL
46155
46203
  ) OR (
46156
46204
  ${t.status} = 'consumed'
@@ -46244,6 +46292,7 @@ var communityChannelMember = sqliteTable("community_channel_member", {
46244
46292
  }, (t) => [
46245
46293
  index("idx_community_channel_member_added_by_lookup").on(t.addedBy),
46246
46294
  unique("uq_channel_member").on(t.channelId, t.userId, t.relation),
46295
+ index("idx_channel_member_channel_relation_user").on(t.channelId, t.relation, t.userId),
46247
46296
  index("idx_channel_member_user").on(t.userId)
46248
46297
  ]);
46249
46298
  var communityMessage = sqliteTable("community_message", {
@@ -46263,6 +46312,7 @@ var communityMessage = sqliteTable("community_message", {
46263
46312
  clientNonce: text("client_nonce")
46264
46313
  }, (t) => [
46265
46314
  index("idx_community_message_author_id_lookup").on(t.authorId),
46315
+ index("idx_message_channel_seq").on(t.channelId, t.seq),
46266
46316
  index("idx_message_channel_created").on(t.channelId, t.createdAt),
46267
46317
  index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt),
46268
46318
  index("idx_community_message_channel_reply_author").on(t.channelId, t.replyToId, t.authorId).where(sql`${t.replyToId} IS NOT NULL`)
@@ -46367,7 +46417,8 @@ var communityReaction = sqliteTable("community_reaction", {
46367
46417
  }, (t) => [
46368
46418
  index("idx_community_reaction_user_id_lookup").on(t.userId),
46369
46419
  unique("uq_reaction_message_user_emoji").on(t.messageId, t.userId, t.emoji),
46370
- index("idx_reaction_message").on(t.messageId)
46420
+ index("idx_reaction_message").on(t.messageId),
46421
+ index("idx_reaction_message_emoji_created").on(t.messageId, t.emoji, t.createdAt, t.userId)
46371
46422
  ]);
46372
46423
  var communityAttachment = sqliteTable("community_attachment", {
46373
46424
  id: text("id").primaryKey().$defaultFn(() => nanoid3()),
@@ -46529,18 +46580,6 @@ var communityMessageTag = sqliteTable("community_message_tag", {
46529
46580
  index("idx_message_tag_tag").on(t.tag, t.messageId)
46530
46581
  ]);
46531
46582
 
46532
- // ../shared/src/db/queries/_chunk.ts
46533
- var D1_MAX_BIND_PARAMS = 100;
46534
- function maxInParams(fixedParams) {
46535
- if (!Number.isInteger(fixedParams) || fixedParams < 0) {
46536
- throw new Error("fixed params must be a non-negative integer");
46537
- }
46538
- if (fixedParams >= D1_MAX_BIND_PARAMS) {
46539
- throw new Error("fixed params must leave room for at least one IN parameter");
46540
- }
46541
- return D1_MAX_BIND_PARAMS - fixedParams;
46542
- }
46543
-
46544
46583
  // ../shared/src/community-server-rail.ts
46545
46584
  var MAX_SERVER_RAIL_COMMANDS = 3;
46546
46585
  var idSchema = exports_external.string().trim().min(1);
@@ -46948,7 +46987,6 @@ var AGENT_MESSAGE_COLUMNS = {
46948
46987
  embeds: communityMessage.embeds
46949
46988
  };
46950
46989
  var channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${communityChannelMember.addedAt}, ${communityServerMember.joinedAt}, '')`;
46951
- var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
46952
46990
  // ../shared/src/community-ws-events.ts
46953
46991
  var string4 = exports_external.string();
46954
46992
  var nullableString = string4.nullable();
@@ -47106,7 +47144,8 @@ var communityMemberJoinSchema = exports_external.strictObject({
47106
47144
  userId: string4,
47107
47145
  role: string4,
47108
47146
  joinedAt: string4
47109
- })
47147
+ }),
47148
+ online: exports_external.boolean().optional()
47110
47149
  });
47111
47150
  var communityMemberLeaveSchema = exports_external.strictObject({
47112
47151
  type: exports_external.literal("community:member.leave"),
@@ -47202,6 +47241,10 @@ var communityPresenceUpdateSchema = exports_external.strictObject({
47202
47241
  userId: string4,
47203
47242
  online: exports_external.boolean()
47204
47243
  });
47244
+ var communityPresenceSnapshotSchema = exports_external.strictObject({
47245
+ type: exports_external.literal("community:presence.snapshot"),
47246
+ onlineUserIds: exports_external.array(string4)
47247
+ });
47205
47248
  var communityStatusUpdateSchema = exports_external.strictObject({
47206
47249
  type: exports_external.literal("community:status.update"),
47207
47250
  userId: string4,
@@ -47260,6 +47303,11 @@ var communityBotPiiSchema = exports_external.strictObject({
47260
47303
  requestId: exports_external.string().min(1).max(128),
47261
47304
  result: PiiResultSchema
47262
47305
  });
47306
+ var communityScheduleChangedSchema = exports_external.strictObject({
47307
+ type: exports_external.literal("community:schedule.changed"),
47308
+ eventId: string4,
47309
+ reason: exports_external.enum(["created", "updated", "deleted", "run_updated"])
47310
+ });
47263
47311
  var commonCommunityEventSchemas = [
47264
47312
  communityBotPiiSchema,
47265
47313
  communityMessageUpdatedSchema,
@@ -47293,13 +47341,15 @@ var commonCommunityEventSchemas = [
47293
47341
  communityReadStateAdvancedSchema,
47294
47342
  communityInboxChangedSchema,
47295
47343
  communityPresenceUpdateSchema,
47344
+ communityPresenceSnapshotSchema,
47296
47345
  communityStatusUpdateSchema,
47297
47346
  communityMachineCreatedSchema,
47298
47347
  communityMachineStatusSchema,
47299
47348
  communityMachineUpdatedSchema,
47300
47349
  communityRuntimeModelsSchema,
47301
47350
  communityMachineRemovedSchema,
47302
- communityBotAuditEventSchema
47351
+ communityBotAuditEventSchema,
47352
+ communityScheduleChangedSchema
47303
47353
  ];
47304
47354
  var CommunityWsEventSchema = exports_external.discriminatedUnion("type", [
47305
47355
  ...commonCommunityEventSchemas,
@@ -47348,6 +47398,7 @@ var WS_EVENTS = {
47348
47398
  READ_STATE_ADVANCED: "community:read_state.advanced",
47349
47399
  INBOX_CHANGED: "community:inbox.changed",
47350
47400
  PRESENCE_UPDATE: "community:presence.update",
47401
+ PRESENCE_SNAPSHOT: "community:presence.snapshot",
47351
47402
  STATUS_UPDATE: "community:status.update",
47352
47403
  IDENTITY_UPDATE: "community:identity.update",
47353
47404
  PROFILE_UPDATE: "community:profile.update",
@@ -47357,7 +47408,8 @@ var WS_EVENTS = {
47357
47408
  RUNTIME_MODELS: "community:runtime.models",
47358
47409
  BOT_PII: "community:bot.pii",
47359
47410
  MACHINE_REMOVED: "community:machine.removed",
47360
- BOT_AUDIT_EVENT: "community:bot.audit_event"
47411
+ BOT_AUDIT_EVENT: "community:bot.audit_event",
47412
+ SCHEDULE_CHANGED: "community:schedule.changed"
47361
47413
  };
47362
47414
  var COMMUNITY_EVENT_TYPES = new Set(Object.values(WS_EVENTS));
47363
47415
  var COMMUNITY_BROWSER_EVENT_MAX_BYTES = 65536;
@@ -47578,8 +47630,109 @@ var communityBotFeedback = sqliteTable("community_bot_feedback", {
47578
47630
  check2("bot_feedback_text_bytes", sql`length(cast(${t.text} as blob)) between 1 and ${sql.raw(String(BOT_FEEDBACK_MAX_BYTES))}`)
47579
47631
  ]);
47580
47632
 
47633
+ // ../shared/src/db/community-schedule-schema.ts
47634
+ var exports_community_schedule_schema = {};
47635
+ __export(exports_community_schedule_schema, {
47636
+ communityScheduleRun: () => communityScheduleRun,
47637
+ communityScheduleEvent: () => communityScheduleEvent
47638
+ });
47639
+ var communityScheduleEvent = sqliteTable("community_schedule_event", {
47640
+ id: text("id").primaryKey(),
47641
+ ownerUserId: text("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47642
+ createdByUserId: text("created_by_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47643
+ title: text("title").notNull(),
47644
+ description: text("description").notNull().default(""),
47645
+ startAtMs: integer2("start_at_ms").notNull(),
47646
+ durationMinutes: integer2("duration_minutes").notNull().default(30),
47647
+ timeZone: text("time_zone").notNull(),
47648
+ recurrenceJson: text("recurrence_json"),
47649
+ occurrenceCount: integer2("occurrence_count").notNull().default(0),
47650
+ nextRunAtMs: integer2("next_run_at_ms"),
47651
+ sourceMessageId: text("source_message_id").notNull(),
47652
+ sourceChannelId: text("source_channel_id").notNull(),
47653
+ version: integer2("version").notNull().default(1),
47654
+ createdAtMs: integer2("created_at_ms").notNull(),
47655
+ updatedAtMs: integer2("updated_at_ms").notNull()
47656
+ }, (t) => [
47657
+ index("idx_community_schedule_event_owner_created").on(t.ownerUserId, t.createdAtMs),
47658
+ index("idx_community_schedule_event_owner_next_run").on(t.ownerUserId, t.nextRunAtMs).where(sql`${t.nextRunAtMs} IS NOT NULL`),
47659
+ index("idx_community_schedule_event_creator_id_lookup").on(t.createdByUserId)
47660
+ ]);
47661
+ var communityScheduleRun = sqliteTable("community_schedule_run", {
47662
+ id: text("id").primaryKey(),
47663
+ ownerUserId: text("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47664
+ eventId: text("event_id").notNull().references(() => communityScheduleEvent.id, { onDelete: "cascade" }),
47665
+ eventVersion: integer2("event_version").notNull(),
47666
+ botUserId: text("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47667
+ scheduledAtMs: integer2("scheduled_at_ms").notNull(),
47668
+ sourceMessageId: text("source_message_id").notNull(),
47669
+ sourceChannelId: text("source_channel_id").notNull(),
47670
+ titleSnapshot: text("title_snapshot").notNull(),
47671
+ descriptionSnapshot: text("description_snapshot").notNull(),
47672
+ status: text("status").$type().notNull(),
47673
+ lastError: text("last_error"),
47674
+ ackedAtMs: integer2("acked_at_ms"),
47675
+ createdAtMs: integer2("created_at_ms").notNull(),
47676
+ updatedAtMs: integer2("updated_at_ms").notNull()
47677
+ }, (t) => [
47678
+ uniqueIndex("uq_community_schedule_run_event_scheduled").on(t.eventId, t.scheduledAtMs),
47679
+ index("idx_community_schedule_run_owner_status_scheduled").on(t.ownerUserId, t.status, t.scheduledAtMs),
47680
+ index("idx_community_schedule_run_bot_id_lookup").on(t.botUserId)
47681
+ ]);
47682
+
47683
+ // ../shared/src/db/community-bot-private-inbox-schema.ts
47684
+ var exports_community_bot_private_inbox_schema = {};
47685
+ __export(exports_community_bot_private_inbox_schema, {
47686
+ communityBotPrivateInbox: () => communityBotPrivateInbox
47687
+ });
47688
+ var communityBotPrivateInbox = sqliteTable("community_bot_private_inbox", {
47689
+ id: text("id").primaryKey(),
47690
+ ownerUserId: text("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47691
+ botUserId: text("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47692
+ sourceKind: text("source_kind").$type().notNull(),
47693
+ sourceId: text("source_id").notNull(),
47694
+ sourceRefId: text("source_ref_id"),
47695
+ dedupeKey: text("dedupe_key"),
47696
+ eventType: text("event_type").notNull(),
47697
+ summary: text("summary").notNull(),
47698
+ promptText: text("prompt_text").notNull(),
47699
+ status: text("status").$type().notNull(),
47700
+ lastError: text("last_error"),
47701
+ createdAtMs: integer2("created_at_ms").notNull(),
47702
+ dispatchedAtMs: integer2("dispatched_at_ms")
47703
+ }, (t) => [
47704
+ uniqueIndex("uq_community_bot_private_inbox_dedupe").on(t.sourceKind, t.sourceId, t.dedupeKey).where(sql`${t.dedupeKey} IS NOT NULL`),
47705
+ index("idx_community_bot_private_inbox_bot_pending").on(t.botUserId, t.status, t.createdAtMs),
47706
+ index("idx_community_bot_private_inbox_source_created").on(t.sourceKind, t.sourceId, t.createdAtMs),
47707
+ index("idx_community_bot_private_inbox_owner").on(t.ownerUserId)
47708
+ ]);
47709
+
47710
+ // ../shared/src/db/community-bot-webhook-schema.ts
47711
+ var exports_community_bot_webhook_schema = {};
47712
+ __export(exports_community_bot_webhook_schema, {
47713
+ communityBotWebhook: () => communityBotWebhook
47714
+ });
47715
+ var communityBotWebhook = sqliteTable("community_bot_webhook", {
47716
+ id: text("id").primaryKey(),
47717
+ ownerUserId: text("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47718
+ botUserId: text("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47719
+ name: text("name").notNull(),
47720
+ provider: text("provider").$type().notNull(),
47721
+ tokenHash: text("token_hash").notNull().unique(),
47722
+ signingSecretEnc: text("signing_secret_enc"),
47723
+ eventFilterJson: text("event_filter_json"),
47724
+ instruction: text("instruction").notNull().default(""),
47725
+ enabled: integer2("enabled", { mode: "boolean" }).notNull().default(true),
47726
+ lastTriggeredAtMs: integer2("last_triggered_at_ms"),
47727
+ createdAtMs: integer2("created_at_ms").notNull(),
47728
+ updatedAtMs: integer2("updated_at_ms").notNull()
47729
+ }, (t) => [
47730
+ index("idx_community_bot_webhook_owner_bot").on(t.ownerUserId, t.botUserId, t.createdAtMs),
47731
+ index("idx_community_bot_webhook_bot").on(t.botUserId)
47732
+ ]);
47733
+
47581
47734
  // ../shared/src/db/index.ts
47582
- var allSchema = { ...exports_schema, ...exports_community_schema, ...exports_community_machine_schema, ...exports_product_plan_schema, ...exports_billing_schema, ...exports_community_funnel_analytics_schema, ...exports_bot_creation_schema, ...exports_automation_schema, ...exports_feedback_schema };
47735
+ var allSchema = { ...exports_schema, ...exports_community_schema, ...exports_community_machine_schema, ...exports_product_plan_schema, ...exports_billing_schema, ...exports_community_funnel_analytics_schema, ...exports_bot_creation_schema, ...exports_automation_schema, ...exports_feedback_schema, ...exports_community_schedule_schema, ...exports_community_bot_private_inbox_schema, ...exports_community_bot_webhook_schema };
47583
47736
  // ../shared/src/db/queries/native-oauth.ts
47584
47737
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
47585
47738
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
@@ -47608,6 +47761,227 @@ var metadataProjection = {
47608
47761
  };
47609
47762
  // ../shared/src/db/queries/community/diagnostic-report.ts
47610
47763
  var diagnosticOwner = alias(user, "diagnostic_owner");
47764
+ // ../shared/src/schedule.ts
47765
+ var SCHEDULE_TITLE_MAX_LENGTH = 160;
47766
+ var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
47767
+ var SCHEDULE_MIN_DURATION_MINUTES = 5;
47768
+ var SCHEDULE_MAX_DURATION_MINUTES = 1440;
47769
+ var SCHEDULE_MAX_RANGE_MS = 62 * 24 * 60 * 60 * 1000;
47770
+ var ScheduleRecurrenceFreqSchema = exports_external.enum(["hourly", "daily", "weekly", "monthly"]);
47771
+ var ScheduleRecurrenceSchema = exports_external.strictObject({
47772
+ freq: ScheduleRecurrenceFreqSchema,
47773
+ interval: exports_external.number().int().min(1).max(365),
47774
+ byWeekday: exports_external.array(exports_external.number().int().min(0).max(6)).min(1).max(7).optional(),
47775
+ untilAt: exports_external.iso.datetime({ offset: true }).nullable().optional(),
47776
+ count: exports_external.number().int().min(1).max(1000).nullable().optional()
47777
+ }).superRefine((value, ctx) => {
47778
+ if (value.byWeekday !== undefined && value.freq !== "weekly") {
47779
+ ctx.addIssue({
47780
+ code: "custom",
47781
+ path: ["byWeekday"],
47782
+ message: "byWeekday is only supported for weekly recurrence"
47783
+ });
47784
+ }
47785
+ });
47786
+ var ScheduleRunStatusSchema = exports_external.enum([
47787
+ "pending",
47788
+ "dispatched",
47789
+ "completed",
47790
+ "blocked_access"
47791
+ ]);
47792
+ var ScheduleOccurrenceStatusSchema = exports_external.enum([
47793
+ "scheduled",
47794
+ "pending",
47795
+ "dispatched",
47796
+ "completed",
47797
+ "blocked_access"
47798
+ ]);
47799
+ var ScheduleSourceMessageStatusSchema = exports_external.enum([
47800
+ "accessible",
47801
+ "inaccessible",
47802
+ "deleted"
47803
+ ]);
47804
+ var ScheduleActorSummarySchema = exports_external.strictObject({
47805
+ id: exports_external.string().min(1),
47806
+ handle: exports_external.string().min(1),
47807
+ name: exports_external.string().min(1),
47808
+ avatarVersion: exports_external.number().int().nonnegative(),
47809
+ isBot: exports_external.boolean()
47810
+ });
47811
+ var ScheduleLastExecutionSchema = exports_external.strictObject({
47812
+ scheduledAt: exports_external.iso.datetime(),
47813
+ status: ScheduleRunStatusSchema,
47814
+ lastError: exports_external.string().nullable(),
47815
+ ackedAt: exports_external.iso.datetime().nullable(),
47816
+ updatedAt: exports_external.iso.datetime()
47817
+ });
47818
+ var ScheduleSourceMessageSchema = exports_external.strictObject({
47819
+ id: exports_external.string().min(1),
47820
+ accessible: exports_external.boolean(),
47821
+ status: ScheduleSourceMessageStatusSchema,
47822
+ ref: exports_external.string().nullable(),
47823
+ channelRef: exports_external.string().nullable(),
47824
+ seq: exports_external.number().int().positive().nullable(),
47825
+ preview: exports_external.string().nullable()
47826
+ });
47827
+ var ScheduleEventSchema = exports_external.strictObject({
47828
+ id: exports_external.string().min(1),
47829
+ title: exports_external.string().min(1),
47830
+ description: exports_external.string(),
47831
+ createdBy: ScheduleActorSummarySchema,
47832
+ startAt: exports_external.iso.datetime(),
47833
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES),
47834
+ timeZone: exports_external.string().min(1),
47835
+ recurrence: ScheduleRecurrenceSchema.nullable(),
47836
+ nextRunAt: exports_external.iso.datetime().nullable(),
47837
+ sourceMessage: ScheduleSourceMessageSchema,
47838
+ lastExecution: ScheduleLastExecutionSchema.nullable(),
47839
+ createdAt: exports_external.iso.datetime(),
47840
+ updatedAt: exports_external.iso.datetime()
47841
+ });
47842
+ var ScheduleOccurrenceSchema = exports_external.strictObject({
47843
+ eventId: exports_external.string().min(1),
47844
+ occurrenceKey: exports_external.string().min(1),
47845
+ startAt: exports_external.iso.datetime(),
47846
+ endAt: exports_external.iso.datetime(),
47847
+ runStatus: ScheduleOccurrenceStatusSchema
47848
+ });
47849
+ var ScheduleListResponseSchema = exports_external.strictObject({
47850
+ events: exports_external.array(ScheduleEventSchema),
47851
+ occurrences: exports_external.array(ScheduleOccurrenceSchema),
47852
+ creators: exports_external.array(ScheduleActorSummarySchema)
47853
+ });
47854
+ var ScheduleCreateRequestSchema = exports_external.strictObject({
47855
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH),
47856
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
47857
+ startAt: exports_external.iso.datetime({ offset: true }),
47858
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
47859
+ timeZone: exports_external.string().trim().min(1).max(128),
47860
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
47861
+ sourceMessageRef: exports_external.string().trim().min(1).max(512)
47862
+ });
47863
+ var ScheduleUpdateRequestSchema = exports_external.strictObject({
47864
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH).optional(),
47865
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
47866
+ startAt: exports_external.iso.datetime({ offset: true }).optional(),
47867
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
47868
+ timeZone: exports_external.string().trim().min(1).max(128).optional(),
47869
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
47870
+ sourceMessageRef: exports_external.string().trim().min(1).max(512).optional(),
47871
+ ack: exports_external.literal(true).optional()
47872
+ });
47873
+ function isValidIanaTimeZone(timeZone) {
47874
+ if (!timeZone || typeof timeZone !== "string")
47875
+ return false;
47876
+ try {
47877
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(0);
47878
+ return true;
47879
+ } catch {
47880
+ return false;
47881
+ }
47882
+ }
47883
+ var formatterCache = new Map;
47884
+ // ../shared/src/bot-webhook.ts
47885
+ var BOT_WEBHOOK_PROVIDERS = [
47886
+ "github",
47887
+ "linear",
47888
+ "sentry",
47889
+ "stripe",
47890
+ "vercel",
47891
+ "gitlab",
47892
+ "slack",
47893
+ "openai",
47894
+ "resend",
47895
+ "clerk",
47896
+ "polar",
47897
+ "cloudflare",
47898
+ "grafana",
47899
+ "datadog",
47900
+ "n8n",
47901
+ "generic"
47902
+ ];
47903
+ var BOT_WEBHOOK_DELIVERY_STATUSES = ["pending", "dispatched", "ignored", "failed"];
47904
+ var BOT_WEBHOOK_NAME_MAX_LENGTH = 80;
47905
+ var BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH = 500;
47906
+ var BOT_WEBHOOK_SECRET_MIN_LENGTH = 8;
47907
+ var BOT_WEBHOOK_SECRET_MAX_LENGTH = 256;
47908
+ var BOT_WEBHOOK_MAX_EVENT_FILTERS = 32;
47909
+ var BOT_WEBHOOK_EVENT_NAME_MAX_LENGTH = 64;
47910
+ var BOT_WEBHOOK_RESYNC_WINDOW_MS = 24 * 60 * 60 * 1000;
47911
+ var BotWebhookProviderSchema = exports_external.enum(BOT_WEBHOOK_PROVIDERS);
47912
+ var BotWebhookDeliveryStatusSchema = exports_external.enum(BOT_WEBHOOK_DELIVERY_STATUSES);
47913
+ var EventFilterEntrySchema = exports_external.string().trim().min(1).max(BOT_WEBHOOK_EVENT_NAME_MAX_LENGTH).regex(/^[a-z0-9_.-]+$/i, "Event name may only contain letters, digits, _, ., and -");
47914
+ var BotWebhookEventFilterSchema = exports_external.array(EventFilterEntrySchema).max(BOT_WEBHOOK_MAX_EVENT_FILTERS).transform((items) => [...new Set(items.map((item) => item.toLowerCase()))]);
47915
+ var SigningSecretInputSchema = exports_external.string().trim().min(BOT_WEBHOOK_SECRET_MIN_LENGTH, `Verification key must be at least ${BOT_WEBHOOK_SECRET_MIN_LENGTH} characters`).max(BOT_WEBHOOK_SECRET_MAX_LENGTH, `Verification key must be at most ${BOT_WEBHOOK_SECRET_MAX_LENGTH} characters`);
47916
+ var BotWebhookLastDeliverySchema = exports_external.strictObject({
47917
+ id: exports_external.string().min(1),
47918
+ status: BotWebhookDeliveryStatusSchema,
47919
+ eventType: exports_external.string().min(1),
47920
+ summary: exports_external.string(),
47921
+ lastError: exports_external.string().nullable(),
47922
+ createdAt: exports_external.iso.datetime()
47923
+ });
47924
+ var BotWebhookDeliverySchema = exports_external.strictObject({
47925
+ id: exports_external.string().min(1),
47926
+ webhookId: exports_external.string().min(1),
47927
+ eventType: exports_external.string().min(1),
47928
+ summary: exports_external.string(),
47929
+ status: BotWebhookDeliveryStatusSchema,
47930
+ lastError: exports_external.string().nullable(),
47931
+ externalDeliveryId: exports_external.string().nullable(),
47932
+ createdAt: exports_external.iso.datetime(),
47933
+ dispatchedAt: exports_external.iso.datetime().nullable()
47934
+ });
47935
+ var BotWebhookSummarySchema = exports_external.strictObject({
47936
+ id: exports_external.string().min(1),
47937
+ botId: exports_external.string().min(1),
47938
+ name: exports_external.string().min(1),
47939
+ provider: BotWebhookProviderSchema,
47940
+ hasSigningSecret: exports_external.boolean(),
47941
+ eventFilter: exports_external.array(exports_external.string()).nullable(),
47942
+ instruction: exports_external.string(),
47943
+ enabled: exports_external.boolean(),
47944
+ lastTriggeredAt: exports_external.iso.datetime().nullable(),
47945
+ createdAt: exports_external.iso.datetime(),
47946
+ updatedAt: exports_external.iso.datetime(),
47947
+ lastDelivery: BotWebhookLastDeliverySchema.nullable()
47948
+ });
47949
+ var BotWebhookCreateSchema = exports_external.strictObject({
47950
+ name: exports_external.string().trim().min(1, "Name is required").max(BOT_WEBHOOK_NAME_MAX_LENGTH),
47951
+ provider: BotWebhookProviderSchema,
47952
+ eventFilter: BotWebhookEventFilterSchema.nullable().optional(),
47953
+ instruction: exports_external.string().trim().max(BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH).optional().default(""),
47954
+ requireSecret: exports_external.boolean().optional(),
47955
+ signingSecret: SigningSecretInputSchema.optional()
47956
+ });
47957
+ var BotWebhookUpdateSchema = exports_external.strictObject({
47958
+ name: exports_external.string().trim().min(1).max(BOT_WEBHOOK_NAME_MAX_LENGTH).optional(),
47959
+ enabled: exports_external.boolean().optional(),
47960
+ eventFilter: BotWebhookEventFilterSchema.nullable().optional(),
47961
+ instruction: exports_external.string().trim().max(BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH).optional(),
47962
+ requireSecret: exports_external.boolean().optional(),
47963
+ signingSecret: SigningSecretInputSchema.optional(),
47964
+ rotateCredentials: exports_external.boolean().optional()
47965
+ }).refine((v) => v.name !== undefined || v.enabled !== undefined || v.eventFilter !== undefined || v.instruction !== undefined || v.requireSecret !== undefined || v.signingSecret !== undefined || v.rotateCredentials === true, { message: "At least one field must be provided" });
47966
+ var BotWebhookCreateResponseSchema = exports_external.strictObject({
47967
+ webhook: BotWebhookSummarySchema,
47968
+ webhookUrl: exports_external.url(),
47969
+ signingSecret: exports_external.string().nullable()
47970
+ });
47971
+ var BotWebhookUpdateResponseSchema = exports_external.strictObject({
47972
+ webhook: BotWebhookSummarySchema,
47973
+ webhookUrl: exports_external.url().optional(),
47974
+ signingSecret: exports_external.string().nullable().optional()
47975
+ });
47976
+ var BotWebhookListResponseSchema = exports_external.strictObject({
47977
+ webhooks: exports_external.array(BotWebhookSummarySchema)
47978
+ });
47979
+ var BotWebhookDeliveriesResponseSchema = exports_external.strictObject({
47980
+ deliveries: exports_external.array(BotWebhookDeliverySchema)
47981
+ });
47982
+ var BotWebhookTestResponseSchema = exports_external.strictObject({
47983
+ delivery: BotWebhookDeliverySchema
47984
+ });
47611
47985
  // ../shared/src/lib/invite-link.ts
47612
47986
  var INVITE_URL_RE = /(?:https?:\/\/[^\s/]+)?\/c\/invite\/([A-Za-z0-9_-]{6,64})/;
47613
47987
  var BARE_TOKEN_RE = /^[A-Za-z0-9_-]{6,64}$/;
@@ -47620,6 +47994,12 @@ function parseInviteToken(input2) {
47620
47994
  return urlMatch[1];
47621
47995
  return BARE_TOKEN_RE.test(trimmed) ? trimmed : null;
47622
47996
  }
47997
+ // ../shared/src/lib/channel-ref-syntax.ts
47998
+ var REF_TERM = `.,;:!?)\\]}"'\\u2014\\u2019\\u201D\\u2026\\u3001\\u3002\\u3009\\u300B\\u300D\\u300F\\u3011\\u3015\\u3017\\u3019\\u301B\\uFF01\\uFF02\\uFF07\\uFF09\\uFF0C\\uFF0E\\uFF1A\\uFF1B\\uFF1F\\uFF3D\\uFF5D`;
47999
+ var REF_SEG = `[^\\s/#${REF_TERM}]+`;
48000
+ var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
48001
+ var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
48002
+ var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
47623
48003
  // ../shared/src/utils/email.ts
47624
48004
  var DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`;
47625
48005
  // ../shared/src/lib/safe-redirect.ts
@@ -61513,11 +61893,6 @@ var exitSpoiler = function(token) {
61513
61893
  };
61514
61894
 
61515
61895
  // ../shared/src/lib/chat-syntax-plugin.ts
61516
- var REF_TERM = `.,;:!?)\\]}"'\\u2014\\u2019\\u201D\\u2026\\u3001\\u3002\\u3009\\u300B\\u300D\\u300F\\u3011\\u3015\\u3017\\u3019\\u301B\\uFF01\\uFF02\\uFF07\\uFF09\\uFF0C\\uFF0E\\uFF1A\\uFF1B\\uFF1F\\uFF3D\\uFF5D`;
61517
- var REF_SEG = `[^\\s/#${REF_TERM}]+`;
61518
- var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
61519
- var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
61520
- var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
61521
61896
  var MENTION_RE = new RegExp(String.raw`(?<!/|${MENTION_IDENTIFIER_CHARACTERS})(?:@everyone(?!${MENTION_IDENTIFIER_CHARACTERS})|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}(?!${MENTION_IDENTIFIER_CHARACTERS}))`, "gu");
61522
61897
  function memberMentionSyntax() {
61523
61898
  const construct = {
@@ -61873,7 +62248,7 @@ function checkProfiles(rows, resources, ctx) {
61873
62248
  }
61874
62249
  }
61875
62250
  var CommunityAcceptedFriendsReadSchema = exports_external.union([
61876
- exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
62251
+ exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema), totalFriends: exports_external.number().int().nonnegative().optional() }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
61877
62252
  exports_external.strictObject({ ...stale, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema).length(0) })
61878
62253
  ]);
61879
62254
  var CommunityBlockedFriendsReadSchema = exports_external.union([
@@ -61978,7 +62353,10 @@ var CommunityReactionDetailsReadSchema = exports_external.strictObject({
61978
62353
  exports_external.strictObject({ kind: exports_external.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
61979
62354
  exports_external.strictObject({ kind: exports_external.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id })
61980
62355
  ]),
61981
- actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() }))
62356
+ actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() })),
62357
+ emoji: exports_external.string().optional(),
62358
+ hasMore: exports_external.boolean().optional(),
62359
+ cursor: exports_external.string().nullable().optional()
61982
62360
  }).superRefine((value, ctx) => {
61983
62361
  if (new Set(value.actors.map((row) => row.userId)).size !== value.actors.length || value.actors.some((row) => row.profile && row.profile.id !== row.userId))
61984
62362
  ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" });
@@ -63562,6 +63940,55 @@ async function killProcessTree(pid, opts) {
63562
63940
  import { createRequire as createRequire3 } from "node:module";
63563
63941
  import { homedir as homedir3 } from "node:os";
63564
63942
  import { join as join7, resolve } from "node:path";
63943
+ var MAX_CHILD_PROGRESS_ROWS = 64;
63944
+ function parseAgyVersion(version3) {
63945
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.-]+)?$/.exec(version3.trim());
63946
+ if (!match)
63947
+ return null;
63948
+ const major = Number(match[1]);
63949
+ const minor = Number(match[2]);
63950
+ const patch = Number(match[3]);
63951
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
63952
+ return null;
63953
+ }
63954
+ return [major, minor, patch];
63955
+ }
63956
+ function compareSemver(a, b) {
63957
+ for (let index3 = 0;index3 < 3; index3 += 1) {
63958
+ if (a[index3] !== b[index3])
63959
+ return a[index3] - b[index3];
63960
+ }
63961
+ return 0;
63962
+ }
63963
+ function isAgyVersionAtLeast(version3, min, maxMajorExclusive) {
63964
+ const parsed = parseAgyVersion(version3);
63965
+ if (!parsed)
63966
+ return false;
63967
+ if (maxMajorExclusive !== undefined && parsed[0] >= maxMajorExclusive)
63968
+ return false;
63969
+ return compareSemver(parsed, min) >= 0;
63970
+ }
63971
+ function resolveAgyUsageProfile(version3) {
63972
+ const parsed = parseAgyVersion(version3);
63973
+ if (!parsed || parsed[0] >= 2)
63974
+ return;
63975
+ if (compareSemver(parsed, [1, 5, 9]) >= 0) {
63976
+ return { inputIncludesCache: false, outputIncludesReasoning: true };
63977
+ }
63978
+ if (compareSemver(parsed, [1, 4, 12]) >= 0) {
63979
+ return { inputIncludesCache: true, outputIncludesReasoning: false };
63980
+ }
63981
+ return;
63982
+ }
63983
+ function readConversationSummaryColumns(db) {
63984
+ const rows = db.prepare("PRAGMA table_info(conversation_summaries)").all();
63985
+ const columns = new Set;
63986
+ for (const row of rows) {
63987
+ if (typeof row?.name === "string")
63988
+ columns.add(row.name);
63989
+ }
63990
+ return columns;
63991
+ }
63565
63992
  function agyStateHome(env, cwd) {
63566
63993
  const home = env.HOME || env.USERPROFILE || homedir3();
63567
63994
  return resolve(cwd, env.GEMINI_HOME?.trim().replace(/^~(?=[/\\]|$)/, home) || join7(home, ".gemini"));
@@ -63711,10 +64138,14 @@ class NativeSessionActivityReader {
63711
64138
  this.path = join7(home, "antigravity-cli", "conversation_summaries.db");
63712
64139
  }
63713
64140
  async activity() {
63714
- if (this.version !== "1.5.16")
64141
+ if (!isAgyVersionAtLeast(this.version, [1, 5, 16], 2))
63715
64142
  return "unknown";
63716
64143
  const db = await this.openDatabase(this.path);
63717
64144
  try {
64145
+ const columns = readConversationSummaryColumns(db);
64146
+ if (!columns.has("conversation_id") || !columns.has("status") || !columns.has("not_fully_idle")) {
64147
+ return "unknown";
64148
+ }
63718
64149
  const rows = db.prepare("SELECT status,not_fully_idle FROM conversation_summaries WHERE conversation_id = ? LIMIT 1").all(this.sessionId);
63719
64150
  const row = rows[0];
63720
64151
  if (!row || row.not_fully_idle !== 0 && row.not_fully_idle !== 1)
@@ -63726,6 +64157,40 @@ class NativeSessionActivityReader {
63726
64157
  db.close();
63727
64158
  }
63728
64159
  }
64160
+ async childProgress() {
64161
+ if (!isAgyVersionAtLeast(this.version, [1, 5, 16], 2))
64162
+ return null;
64163
+ let db;
64164
+ try {
64165
+ db = await this.openDatabase(this.path);
64166
+ } catch {
64167
+ return null;
64168
+ }
64169
+ try {
64170
+ const columns = readConversationSummaryColumns(db);
64171
+ if (!columns.has("conversation_id") || !columns.has("parent_conversation_id") || !columns.has("step_count") || !columns.has("last_modified_time")) {
64172
+ return null;
64173
+ }
64174
+ const rows = db.prepare(`SELECT conversation_id,step_count,last_modified_time FROM conversation_summaries WHERE parent_conversation_id = ? ORDER BY last_modified_time DESC LIMIT ${MAX_CHILD_PROGRESS_ROWS}`).all(this.sessionId);
64175
+ const children = [];
64176
+ for (const row of rows) {
64177
+ if (typeof row?.conversation_id !== "string" || !row.conversation_id)
64178
+ continue;
64179
+ const stepCount = typeof row.step_count === "number" && Number.isSafeInteger(row.step_count) && row.step_count >= 0 ? row.step_count : 0;
64180
+ const lastModifiedTime = typeof row.last_modified_time === "string" ? row.last_modified_time : typeof row.last_modified_time === "number" && Number.isFinite(row.last_modified_time) ? String(row.last_modified_time) : "";
64181
+ children.push({
64182
+ conversationId: row.conversation_id,
64183
+ stepCount,
64184
+ lastModifiedTime
64185
+ });
64186
+ }
64187
+ return children;
64188
+ } catch {
64189
+ return null;
64190
+ } finally {
64191
+ db.close();
64192
+ }
64193
+ }
63729
64194
  }
63730
64195
 
63731
64196
  // agent-driver/dist/internal/model-observation.js
@@ -63937,6 +64402,28 @@ function isMissingSessionError(error62) {
63937
64402
  const message = error62 instanceof Error ? error62.message : String(error62);
63938
64403
  return /\bsession\b.*\b(not found|missing|unknown|invalid)\b/i.test(message) || /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);
63939
64404
  }
64405
+ function timestampAdvanced(previous4, next) {
64406
+ if (!next || next === previous4)
64407
+ return false;
64408
+ if (!previous4)
64409
+ return true;
64410
+ const previousMs = Date.parse(previous4);
64411
+ const nextMs = Date.parse(next);
64412
+ if (Number.isFinite(previousMs) && Number.isFinite(nextMs)) {
64413
+ return nextMs > previousMs || nextMs === previousMs && next > previous4;
64414
+ }
64415
+ return next > previous4;
64416
+ }
64417
+ function toChildProgressMap(children) {
64418
+ const map6 = new Map;
64419
+ for (const child of children) {
64420
+ map6.set(child.conversationId, {
64421
+ stepCount: child.stepCount,
64422
+ lastModifiedTime: child.lastModifiedTime
64423
+ });
64424
+ }
64425
+ return map6;
64426
+ }
63940
64427
 
63941
64428
  class AgyAcpLane {
63942
64429
  factory;
@@ -63953,6 +64440,8 @@ class AgyAcpLane {
63953
64440
  nativeActivity = "unknown";
63954
64441
  publishedActivity;
63955
64442
  activityRevision = 0;
64443
+ childProgressBaseline = null;
64444
+ resumedSession = false;
63956
64445
  nativeVersion = "";
63957
64446
  contentOwner;
63958
64447
  executionIsolated = true;
@@ -64002,6 +64491,7 @@ class AgyAcpLane {
64002
64491
  return { ok: false, reason: "runtime_error", error: "Agy ACP session already started" };
64003
64492
  }
64004
64493
  this.started = true;
64494
+ this.resumedSession = Boolean(input2.sessionId ?? this.ctx.config.sessionId);
64005
64495
  const launchCtx = {
64006
64496
  ...this.ctx,
64007
64497
  prompt: input2.text,
@@ -64032,7 +64522,7 @@ class AgyAcpLane {
64032
64522
  const sessionId = this.sessionId;
64033
64523
  if (!sessionId)
64034
64524
  throw new Error("Agy ACP handshake completed without a session id");
64035
- this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, this.nativeVersion === "1.5.16");
64525
+ this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, isAgyVersionAtLeast(this.nativeVersion, [1, 5, 16], 2));
64036
64526
  this.processActivated = true;
64037
64527
  this.ready = true;
64038
64528
  this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input2.sessionId ? "resumed" : "created", evidence: "native_api" } });
@@ -64083,8 +64573,8 @@ class AgyAcpLane {
64083
64573
  stop(input2 = {}) {
64084
64574
  this.requestedStopReason ??= input2.reason ?? "requested_stop";
64085
64575
  this.ready = false;
64086
- if (this.activityTimer)
64087
- clearTimeout(this.activityTimer);
64576
+ this.clearActivityTimer();
64577
+ this.childProgressBaseline = null;
64088
64578
  this.currentPromptRequestId = null;
64089
64579
  this.terminalOwner = null;
64090
64580
  this.toolCalls.clear();
@@ -64092,12 +64582,7 @@ class AgyAcpLane {
64092
64582
  this.promptOutcomes.clear();
64093
64583
  this.observedPrompts.clear();
64094
64584
  this.usage.reset();
64095
- const waiter = this.configWaiter;
64096
- if (waiter) {
64097
- clearTimeout(waiter.timer);
64098
- this.configWaiter = undefined;
64099
- waiter.reject(new Error("Antigravity CLI lane stopped"));
64100
- }
64585
+ this.rejectConfigWaiter(new Error("Antigravity CLI lane stopped"));
64101
64586
  this.stopPromise ??= this.stopPhysicalOnce(input2);
64102
64587
  return this.stopPromise;
64103
64588
  }
@@ -64148,7 +64633,7 @@ class AgyAcpLane {
64148
64633
  }
64149
64634
  const version3 = record3(initialize.agentInfo)?.version;
64150
64635
  this.nativeVersion = typeof version3 === "string" ? version3 : "";
64151
- this.usageProfile = version3 === "1.4.12" ? { inputIncludesCache: true, outputIncludesReasoning: false } : version3 === "1.5.9" ? { inputIncludesCache: false, outputIncludesReasoning: true } : undefined;
64636
+ this.usageProfile = typeof version3 === "string" ? resolveAgyUsageProfile(version3) : undefined;
64152
64637
  if (!record3(record3(initialize.agentCapabilities)?.sessionCapabilities)?.resume) {
64153
64638
  throw new AgyAcpIncompatibleError("Antigravity CLI ACP does not support native session resume");
64154
64639
  }
@@ -64353,6 +64838,11 @@ class AgyAcpLane {
64353
64838
  const checkpoint = await read;
64354
64839
  if (!this.ready || this.requestedStopReason || this.isClosed())
64355
64840
  return { ok: false, reason: "closed" };
64841
+ const childBaseline = await this.readChildProgress();
64842
+ if (!this.ready || this.requestedStopReason || this.isClosed())
64843
+ return { ok: false, reason: "closed" };
64844
+ if (childBaseline)
64845
+ this.childProgressBaseline = toChildProgressMap(childBaseline);
64356
64846
  this.executionCheckpoint = checkpoint;
64357
64847
  this.executionIsolated = !this.unownedContent && !this.hasPendingTools();
64358
64848
  return this.admitPrompt(text7, "prompt", inputs);
@@ -64600,6 +65090,8 @@ class AgyAcpLane {
64600
65090
  }
64601
65091
  this.processTerminal = true;
64602
65092
  this.ready = false;
65093
+ this.clearActivityTimer();
65094
+ this.rejectConfigWaiter(normalized);
64603
65095
  this.currentPromptRequestId = null;
64604
65096
  this.terminalOwner = null;
64605
65097
  this.toolCalls.clear();
@@ -64619,10 +65111,13 @@ class AgyAcpLane {
64619
65111
  return;
64620
65112
  this.processTerminal = true;
64621
65113
  this.ready = false;
65114
+ this.clearActivityTimer();
65115
+ const exitError = new Error("Agy ACP process exited");
65116
+ this.rejectConfigWaiter(exitError);
64622
65117
  this.currentPromptRequestId = null;
64623
65118
  this.terminalOwner = null;
64624
65119
  this.toolCalls.clear();
64625
- this.rejectAllPending(new Error("Agy ACP process exited"));
65120
+ this.rejectAllPending(exitError);
64626
65121
  if (this.suppressExit || !this.processActivated)
64627
65122
  return;
64628
65123
  this.events.emit("exit", {
@@ -64881,6 +65376,51 @@ class AgyAcpLane {
64881
65376
  this.nativeActivity = "unknown";
64882
65377
  this.publishActivity();
64883
65378
  }
65379
+ async readChildProgress() {
65380
+ if (!this.activityReader?.childProgress)
65381
+ return null;
65382
+ try {
65383
+ return await this.activityReader.childProgress();
65384
+ } catch {
65385
+ return null;
65386
+ }
65387
+ }
65388
+ observeChildProgress(children) {
65389
+ if (!children || this.currentPromptRequestId === null || this.terminalOwner === null)
65390
+ return;
65391
+ if (this.childProgressBaseline === null) {
65392
+ this.childProgressBaseline = toChildProgressMap(children);
65393
+ if (!this.resumedSession && children.length > 0) {
65394
+ this.events.emit("runtime_event", {
65395
+ kind: "internal_progress",
65396
+ source: "agy.native",
65397
+ itemType: "subagent_progress"
65398
+ });
65399
+ }
65400
+ return;
65401
+ }
65402
+ let advanced = false;
65403
+ for (const child of children) {
65404
+ const previous4 = this.childProgressBaseline.get(child.conversationId);
65405
+ if (!previous4 || child.stepCount > previous4.stepCount || timestampAdvanced(previous4.lastModifiedTime, child.lastModifiedTime)) {
65406
+ advanced = true;
65407
+ }
65408
+ this.childProgressBaseline.set(child.conversationId, {
65409
+ stepCount: Math.max(previous4?.stepCount ?? 0, child.stepCount),
65410
+ lastModifiedTime: previous4 && !timestampAdvanced(previous4.lastModifiedTime, child.lastModifiedTime) ? previous4.lastModifiedTime : child.lastModifiedTime
65411
+ });
65412
+ }
65413
+ while (this.childProgressBaseline.size > 256) {
65414
+ this.childProgressBaseline.delete(this.childProgressBaseline.keys().next().value);
65415
+ }
65416
+ if (advanced) {
65417
+ this.events.emit("runtime_event", {
65418
+ kind: "internal_progress",
65419
+ source: "agy.native",
65420
+ itemType: "subagent_progress"
65421
+ });
65422
+ }
65423
+ }
64884
65424
  refreshActivity() {
64885
65425
  if (this.activityRead)
64886
65426
  return this.activityRead;
@@ -64899,6 +65439,12 @@ class AgyAcpLane {
64899
65439
  if (status === "running" && this.currentPromptRequestId === null)
64900
65440
  this.unownedContent = true;
64901
65441
  this.publishActivity();
65442
+ if (this.currentPromptRequestId !== null && this.terminalOwner !== null) {
65443
+ const children = await this.readChildProgress();
65444
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
65445
+ return;
65446
+ this.observeChildProgress(children);
65447
+ }
64902
65448
  })();
64903
65449
  this.activityRead = reading;
64904
65450
  reading.finally(() => {
@@ -64907,8 +65453,22 @@ class AgyAcpLane {
64907
65453
  });
64908
65454
  return reading;
64909
65455
  }
65456
+ clearActivityTimer() {
65457
+ if (!this.activityTimer)
65458
+ return;
65459
+ clearTimeout(this.activityTimer);
65460
+ this.activityTimer = undefined;
65461
+ }
65462
+ rejectConfigWaiter(error62) {
65463
+ const waiter = this.configWaiter;
65464
+ if (!waiter)
65465
+ return;
65466
+ clearTimeout(waiter.timer);
65467
+ this.configWaiter = undefined;
65468
+ waiter.reject(error62);
65469
+ }
64910
65470
  scheduleActivity() {
64911
- if (!this.ready || this.requestedStopReason || this.processTerminal)
65471
+ if (!this.ready || this.requestedStopReason || this.processTerminal || this.activityTimer)
64912
65472
  return;
64913
65473
  this.activityTimer = setTimeout(() => {
64914
65474
  this.activityTimer = undefined;
@@ -76904,6 +77464,10 @@ var communityProxyRoutes = {
76904
77464
  avatar: "/api/community/users/me/avatar",
76905
77465
  marks: "/api/community/users/me/marks"
76906
77466
  };
77467
+ var SCHEDULE_EVENTS_PROXY_PATH_RE = /^\/api\/community\/schedule\/events(?:\/[^/]+)?$/;
77468
+ function isCanonicalCommunityProxyPath(pathname) {
77469
+ return pathname === "/api/community/platform/feedback" || SCHEDULE_EVENTS_PROXY_PATH_RE.test(pathname) || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
77470
+ }
76907
77471
  function resolveProxyCapability(method, pathname) {
76908
77472
  if (pathname === "/api/community/platform/feedback" && method === "POST")
76909
77473
  return "send";
@@ -76913,6 +77477,9 @@ function resolveProxyCapability(method, pathname) {
76913
77477
  return "read";
76914
77478
  if (pathname === "/api/community/bots/creation-requests" && method === "POST")
76915
77479
  return "send";
77480
+ if (SCHEDULE_EVENTS_PROXY_PATH_RE.test(pathname)) {
77481
+ return method === "GET" ? "read" : "send";
77482
+ }
76916
77483
  if ((method === "GET" || method === "PATCH") && pathname === communityProxyRoutes.profile || method === "POST" && pathname === communityProxyRoutes.avatar)
76917
77484
  return "profile";
76918
77485
  if (pathname.includes("/attachment"))
@@ -76987,6 +77554,22 @@ function resolveProxyAuditOperation(pathname, method) {
76987
77554
  return "profileAvatarUpdate";
76988
77555
  if (/^\/api\/community\/bots\/me\/nap(\/|$|\?)/.test(canonical))
76989
77556
  return "nap";
77557
+ if (/^\/api\/community\/schedule\/events$/.test(canonical)) {
77558
+ if (method === "GET")
77559
+ return "scheduleList";
77560
+ if (method === "POST")
77561
+ return "scheduleCreate";
77562
+ return null;
77563
+ }
77564
+ if (/^\/api\/community\/schedule\/events\/[^/]+$/.test(canonical)) {
77565
+ if (method === "GET")
77566
+ return "scheduleGet";
77567
+ if (method === "PATCH")
77568
+ return "scheduleUpdate";
77569
+ if (method === "DELETE")
77570
+ return "scheduleDelete";
77571
+ return null;
77572
+ }
76990
77573
  return null;
76991
77574
  }
76992
77575
  function propertyAuditMetadata(method, pathname, requestUrl) {
@@ -76997,6 +77580,7 @@ function propertyAuditMetadata(method, pathname, requestUrl) {
76997
77580
  }
76998
77581
  function resolveProxyRoute(pathname, method, requestUrl = pathname) {
76999
77582
  return {
77583
+ canonicalCommunityDoor: isCanonicalCommunityProxyPath(pathname),
77000
77584
  capability: resolveProxyCapability(method ?? "", pathname),
77001
77585
  auditOperation: resolveProxyAuditOperation(pathname, method),
77002
77586
  propertyMetadata: propertyAuditMetadata(method ?? "", pathname, requestUrl),
@@ -77416,8 +78000,36 @@ async function readCursorQuota(options = {}, backend = "cursor") {
77416
78000
  // agent-driver/dist/adapters/agy/quota.js
77417
78001
  import { homedir as homedir15 } from "node:os";
77418
78002
  import { randomUUID as randomUUID11 } from "node:crypto";
78003
+ function classifyAgyQuotaError(message, sourceEpoch, structured) {
78004
+ const text8 = message.trim();
78005
+ if (!text8)
78006
+ return null;
78007
+ if (/(?:not authenticated|authentication (?:required|failed)|sign[ -]?in required|unauthenticated|unauthorized|invalid credentials|token expired|permission denied|\b401\b|\b403\b)/i.test(text8)) {
78008
+ return { status: "error", sourceEpoch, code: "unauthorized", retryable: false };
78009
+ }
78010
+ if (/(?:eligibility check failed|not eligible|not (?:currently )?available in your (?:location|region|country)|unsupported (?:location|region|country))/i.test(text8)) {
78011
+ return { status: "error", sourceEpoch, code: "provider_error", retryable: false };
78012
+ }
78013
+ if (/(?:econnrefused|econnreset|etimedout|enotfound|ehostunreach|network error|fetch failed|dial tcp|socket hang up|connection refused|connection reset|proxyconnect|timed out|\bdns\b|\btls\b|\bssl\b)/i.test(text8)) {
78014
+ return { status: "error", sourceEpoch, code: "network", retryable: true };
78015
+ }
78016
+ if (/(?:rate[ -]?limit|too many requests|quota exceeded|\b429\b|\b50[0234]\b|internal server error|service unavailable|bad gateway|temporarily unavailable|resource exhausted|upstream)/i.test(text8)) {
78017
+ return { status: "error", sourceEpoch, code: "provider_error", retryable: true };
78018
+ }
78019
+ return structured ? { status: "error", sourceEpoch, code: "provider_error", retryable: true } : null;
78020
+ }
78021
+ function tryParseJson(text8) {
78022
+ try {
78023
+ return { ok: true, value: JSON.parse(text8) };
78024
+ } catch {
78025
+ return { ok: false };
78026
+ }
78027
+ }
77419
78028
  function parseAgyQuota(value, sourceEpoch) {
77420
78029
  const result2 = asRecord(value);
78030
+ if (result2?.status === "ERROR" && typeof result2.error === "string" && result2.error.trim()) {
78031
+ return classifyAgyQuotaError(result2.error, sourceEpoch, true) ?? { status: "error", sourceEpoch, code: "provider_error", retryable: true };
78032
+ }
77421
78033
  const command = asRecord(result2?.command);
77422
78034
  const data = asRecord(command?.data);
77423
78035
  const groups = data?.groups;
@@ -77454,21 +78066,58 @@ async function readAgyQuota(options = {}) {
77454
78066
  const source = quotaSource("agy", randomUUID11());
77455
78067
  const read = async (args) => {
77456
78068
  const child = (options.spawn ?? spawnAgentProcess)(spec.command, args, { cwd: options.cwd ?? process.cwd(), env: { ...env, CI: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "true" }, shell: spec.shell, stdin: "ignore" });
77457
- let output2 = "";
77458
- return runBoundedDiscoveryProcess({ process: child, label: "AGY quota", timeoutMs: options.timeoutMs ?? 30000, outputMaxBytes: options.outputMaxBytes ?? 1024 * 1024, stderr: "count", cleanupGraceMs: 100, cleanup: options.cleanup, exitEvent: "close", onStdout: (text8) => {
77459
- output2 += text8;
77460
- }, onExit: (code4, _signal, control) => {
77461
- if (code4 !== 0)
77462
- return control.fail("AGY quota failed");
77463
- control.flushStdout();
77464
- control.finish(output2);
77465
- } });
78069
+ let stdout = "";
78070
+ let stderr = "";
78071
+ return runBoundedDiscoveryProcess({
78072
+ process: child,
78073
+ label: "AGY quota",
78074
+ timeoutMs: options.timeoutMs ?? 30000,
78075
+ outputMaxBytes: options.outputMaxBytes ?? 1024 * 1024,
78076
+ stderr: "count",
78077
+ cleanupGraceMs: 100,
78078
+ cleanup: options.cleanup,
78079
+ exitEvent: "close",
78080
+ onStdout: (text8) => {
78081
+ stdout += text8;
78082
+ },
78083
+ onStderr: (text8) => {
78084
+ stderr += text8;
78085
+ },
78086
+ onExit: (code4, _signal, control) => {
78087
+ control.flushStdout();
78088
+ control.flushStderr();
78089
+ control.finish({ exitCode: code4, stdout, stderr });
78090
+ }
78091
+ });
77466
78092
  };
77467
78093
  try {
77468
- if (!parseAgyModelCatalog(await read(["models"])))
78094
+ const models = await read(["models"]);
78095
+ if (models.exitCode !== 0) {
78096
+ const classified2 = classifyAgyQuotaError(models.stderr || models.stdout, source.epoch, false);
78097
+ return source.finish(classified2 ?? source.error("unavailable", true));
78098
+ }
78099
+ if (!parseAgyModelCatalog(models.stdout))
77469
78100
  return source.finish(source.error("unauthorized"));
77470
- return source.finish(parseAgyQuota(JSON.parse(await read(["-p", "/usage", "--output-format", "json"])), source.epoch));
77471
- } catch {
78101
+ const usage = await read(["-p", "/usage", "--output-format", "json"]);
78102
+ const parsed = tryParseJson(usage.stdout);
78103
+ if (parsed.ok) {
78104
+ const record9 = asRecord(parsed.value);
78105
+ if (usage.exitCode === 0) {
78106
+ return source.finish(parseAgyQuota(parsed.value, source.epoch));
78107
+ }
78108
+ if (record9?.status === "ERROR" && typeof record9.error === "string" && record9.error.trim()) {
78109
+ return source.finish(parseAgyQuota(parsed.value, source.epoch));
78110
+ }
78111
+ }
78112
+ if (usage.exitCode === 0) {
78113
+ return source.finish(source.error("invalid_response", true));
78114
+ }
78115
+ const classified = classifyAgyQuotaError(usage.stderr || usage.stdout, source.epoch, false);
78116
+ return source.finish(classified ?? source.error("unavailable", true));
78117
+ } catch (error62) {
78118
+ if (error62 instanceof DiscoveryProcessError && error62.code === "output_limit") {
78119
+ return source.finish(source.error("invalid_response", true));
78120
+ }
77472
78121
  return source.finish(source.error("unavailable", true));
77473
78122
  }
77474
78123
  }
@@ -81058,8 +81707,7 @@ async function startCredentialProxy(broker, options = {}) {
81058
81707
  writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
81059
81708
  return;
81060
81709
  }
81061
- const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81062
- if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
81710
+ if (pathname === "/api" || pathname.startsWith("/api/") && !route.canonicalCommunityDoor) {
81063
81711
  res.writeHead(404, { "content-type": "application/json" });
81064
81712
  res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
81065
81713
  req.resume();
@@ -82074,6 +82722,11 @@ function messagingSection() {
82074
82722
  "- Use `1m` to `24h` when silence would leave work unfinished — for example, after a question, " + "approval request, handoff, or blocker. If no newer message arrives by T, you will be reminded " + "to return; a newer message or daemon restart cancels the timer.",
82075
82723
  "- Use `0` only when no later action depends on a reply. It disables the timer.",
82076
82724
  "",
82725
+ "#### Schedule future or recurring work",
82726
+ "",
82727
+ "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message or daemon restart cancels it.",
82728
+ `- Use \`${CLI} schedule\` for tasks that must run at a specific future time (>24h or across restarts/offline machines) or on a recurring cadence (\`hourly\`/\`daily\`/\`weekly\`/\`monthly\`), visible in Home -> Schedule. Always bind the request's message ref, and run \`--ack\` after finishing a triggered run.`,
82729
+ "",
82077
82730
  "#### Sending mechanics",
82078
82731
  "",
82079
82732
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
@@ -82253,6 +82906,15 @@ function cliCommandsSection() {
82253
82906
  "Adding stores a source copy. Later edits to the input file do not update the installed filter. " + "Do not edit daemon-managed copies.",
82254
82907
  "The CLI only lists or appends filters; it cannot replace, reorder, enable, disable, or delete them. " + "Your human owner manages enabled state and deletion in Privacy. Filter errors block sending.",
82255
82908
  "",
82909
+ "### Schedule",
82910
+ "",
82911
+ "Your household shares one bot schedule visible to your owner in Home -> Schedule and to sibling bots. Every scheduled task binds to a concrete message ref.",
82912
+ "",
82913
+ `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given, expanded occurrences.`,
82914
+ `2. \`${CLI} schedule create --title <text> --at <iso> --message <ref> [--description <text>] [--tz <iana>] [--duration <minutes>] [--repeat <hourly|daily|weekly|monthly>] [--interval <n>] [--weekdays <days>] [--until <iso>] [--count <n>]\` — create a one-time or recurring task bound to a message you can read.`,
82915
+ `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack]\` — update a task, or pass \`--ack\` after finishing the triggered run to mark it completed.`,
82916
+ `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
82917
+ "",
82256
82918
  "### Settings",
82257
82919
  "",
82258
82920
  `1. \`${CLI} setting profile --set-bio <text> --set-avatar <path>\` — update your public bio ` + `and/or avatar. At least one flag is required; pass \`--set-bio ""\` to clear the bio.`,
@@ -90141,6 +90803,208 @@ function registerPlatformCommands(program, getApi, output2, readFeedbackInput) {
90141
90803
  });
90142
90804
  }
90143
90805
 
90806
+ // src/cli/schedule.ts
90807
+ var WEEKDAY_TOKENS = {
90808
+ "0": 0,
90809
+ sun: 0,
90810
+ sunday: 0,
90811
+ "1": 1,
90812
+ mon: 1,
90813
+ monday: 1,
90814
+ "2": 2,
90815
+ tue: 2,
90816
+ tues: 2,
90817
+ tuesday: 2,
90818
+ "3": 3,
90819
+ wed: 3,
90820
+ wednesday: 3,
90821
+ "4": 4,
90822
+ thu: 4,
90823
+ thur: 4,
90824
+ thurs: 4,
90825
+ thursday: 4,
90826
+ "5": 5,
90827
+ fri: 5,
90828
+ friday: 5,
90829
+ "6": 6,
90830
+ sat: 6,
90831
+ saturday: 6
90832
+ };
90833
+ function parseIsoOption(raw, flag) {
90834
+ const ms = Date.parse(raw);
90835
+ if (!Number.isFinite(ms)) {
90836
+ throw new Error(`${flag} must be a valid ISO-8601 timestamp (e.g. 2026-11-26T09:00:00+08:00)`);
90837
+ }
90838
+ return new Date(ms).toISOString();
90839
+ }
90840
+ function parsePositiveIntOption(raw, flag) {
90841
+ if (!/^\d+$/.test(raw.trim()))
90842
+ throw new Error(`${flag} must be a positive integer`);
90843
+ const value = Number(raw.trim());
90844
+ if (!Number.isSafeInteger(value) || value <= 0)
90845
+ throw new Error(`${flag} must be a positive integer`);
90846
+ return value;
90847
+ }
90848
+ function parseWeekdaysOption(raw) {
90849
+ const tokens = raw.split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
90850
+ if (tokens.length === 0)
90851
+ throw new Error("--weekdays requires at least one weekday (0-6 or sun..sat)");
90852
+ const days = [];
90853
+ for (const token of tokens) {
90854
+ const mapped = WEEKDAY_TOKENS[token];
90855
+ if (mapped === undefined)
90856
+ throw new Error(`invalid weekday "${token}" (use 0-6 or sun..sat)`);
90857
+ days.push(mapped);
90858
+ }
90859
+ return [...new Set(days)].sort((a, b) => a - b);
90860
+ }
90861
+ function parseRecurrenceOptions(opts) {
90862
+ const hasRecurrenceFlags = opts.repeat !== undefined || opts.interval !== undefined || opts.weekdays !== undefined || opts.until !== undefined || opts.count !== undefined;
90863
+ if (!hasRecurrenceFlags)
90864
+ return;
90865
+ if (opts.repeat?.trim().toLowerCase() === "none")
90866
+ return null;
90867
+ if (!opts.repeat) {
90868
+ throw new Error("--repeat <hourly|daily|weekly|monthly> is required when using --interval, --weekdays, --until, or --count");
90869
+ }
90870
+ const freq = ScheduleRecurrenceFreqSchema.safeParse(opts.repeat.trim().toLowerCase());
90871
+ if (!freq.success) {
90872
+ throw new Error("--repeat must be one of hourly, daily, weekly, monthly, or none");
90873
+ }
90874
+ const interval = opts.interval ? parsePositiveIntOption(opts.interval, "--interval") : 1;
90875
+ const byWeekday = opts.weekdays ? parseWeekdaysOption(opts.weekdays) : undefined;
90876
+ const untilAt = opts.until && opts.until.trim().toLowerCase() !== "none" ? parseIsoOption(opts.until, "--until") : undefined;
90877
+ const count2 = opts.count && opts.count.trim().toLowerCase() !== "none" ? parsePositiveIntOption(opts.count, "--count") : undefined;
90878
+ return {
90879
+ freq: freq.data,
90880
+ interval,
90881
+ ...byWeekday ? { byWeekday } : {},
90882
+ ...untilAt ? { untilAt } : {},
90883
+ ...count2 ? { count: count2 } : {}
90884
+ };
90885
+ }
90886
+ function defaultLocalTimeZone() {
90887
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
90888
+ return tz && isValidIanaTimeZone(tz) ? tz : "UTC";
90889
+ }
90890
+ function presentScheduleEventForAgent(event) {
90891
+ return {
90892
+ id: event.id,
90893
+ title: event.title,
90894
+ description: event.description,
90895
+ createdBy: event.createdBy.handle,
90896
+ startAt: toLocalISO(event.startAt),
90897
+ durationMinutes: event.durationMinutes,
90898
+ timeZone: event.timeZone,
90899
+ recurrence: event.recurrence ? {
90900
+ ...event.recurrence,
90901
+ ...event.recurrence.untilAt ? { untilAt: toLocalISO(event.recurrence.untilAt) } : {}
90902
+ } : null,
90903
+ nextRunAt: event.nextRunAt ? toLocalISO(event.nextRunAt) : null,
90904
+ sourceMessage: {
90905
+ accessible: event.sourceMessage.accessible,
90906
+ status: event.sourceMessage.status,
90907
+ ...event.sourceMessage.ref ? { ref: event.sourceMessage.ref } : {},
90908
+ ...event.sourceMessage.preview ? { preview: event.sourceMessage.preview } : {}
90909
+ },
90910
+ ...event.lastExecution ? {
90911
+ lastExecution: {
90912
+ scheduledAt: toLocalISO(event.lastExecution.scheduledAt),
90913
+ status: event.lastExecution.status,
90914
+ ...event.lastExecution.ackedAt ? { ackedAt: toLocalISO(event.lastExecution.ackedAt) } : {},
90915
+ ...event.lastExecution.lastError ? { lastError: event.lastExecution.lastError } : {},
90916
+ updatedAt: toLocalISO(event.lastExecution.updatedAt)
90917
+ }
90918
+ } : {},
90919
+ createdAt: toLocalISO(event.createdAt),
90920
+ updatedAt: toLocalISO(event.updatedAt)
90921
+ };
90922
+ }
90923
+ function presentOccurrenceForAgent(occ) {
90924
+ return {
90925
+ eventId: occ.eventId,
90926
+ startAt: toLocalISO(occ.startAt),
90927
+ endAt: toLocalISO(occ.endAt),
90928
+ runStatus: occ.runStatus
90929
+ };
90930
+ }
90931
+ function registerScheduleCommands(program, getApi, output2) {
90932
+ const schedule2 = program.command("schedule").description("manage the household shared schedule (owner and bots)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
90933
+ schedule2.command("list").description("list shared schedule events and optional expanded occurrences").option("--from <iso>", "window start (ISO-8601, pair with --to)").option("--to <iso>", "window end (ISO-8601, pair with --from)").option("--creator <handle>", "filter by creator handle (e.g. @Elwira#8700)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function() {
90934
+ const opts = this.opts();
90935
+ const api2 = getApi();
90936
+ if (!api2.scheduleList)
90937
+ throw new Error("Schedule commands are unavailable");
90938
+ const from = opts.from ? parseIsoOption(opts.from, "--from") : undefined;
90939
+ const to = opts.to ? parseIsoOption(opts.to, "--to") : undefined;
90940
+ const res = await api2.scheduleList({
90941
+ ...from ? { from } : {},
90942
+ ...to ? { to } : {},
90943
+ ...opts.creator ? { creatorHandle: opts.creator } : {}
90944
+ });
90945
+ output2({
90946
+ success: {
90947
+ events: res.events.map(presentScheduleEventForAgent),
90948
+ ...res.occurrences.length > 0 ? { occurrences: res.occurrences.map(presentOccurrenceForAgent) } : {},
90949
+ creators: res.creators.map((c) => c.handle)
90950
+ }
90951
+ });
90952
+ });
90953
+ schedule2.command("create").description("create a shared schedule event bound to a concrete message").requiredOption("--title <text>", "event title (1-160 chars)").requiredOption("--at <iso>", "first scheduled trigger time (ISO-8601)").requiredOption("--message <ref>", "full message ref bound for reply context (e.g. /Server#1234/chan#42)").option("--description <text>", "instructions/context for the scheduled execution").option("--tz <iana>", "IANA timezone (defaults to local machine timezone)").option("--duration <minutes>", "event duration in minutes (5-1440, default 30)").option("--repeat <freq>", "recurrence frequency: hourly, daily, weekly, monthly").option("--interval <n>", "recurrence interval (default 1)").option("--weekdays <days>", "comma-separated weekdays for weekly repeat (0-6 or sun..sat)").option("--until <iso>", "recurrence end timestamp (ISO-8601)").option("--count <n>", "maximum total occurrences (1-1000)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function() {
90954
+ const opts = this.opts();
90955
+ const api2 = getApi();
90956
+ if (!api2.scheduleCreate)
90957
+ throw new Error("Schedule commands are unavailable");
90958
+ const timeZone = opts.tz?.trim() || defaultLocalTimeZone();
90959
+ if (!isValidIanaTimeZone(timeZone))
90960
+ throw new Error(`invalid IANA timezone: ${timeZone}`);
90961
+ const recurrence = parseRecurrenceOptions(opts);
90962
+ const payload = ScheduleCreateRequestSchema.parse({
90963
+ title: opts.title,
90964
+ ...opts.description !== undefined ? { description: opts.description } : {},
90965
+ startAt: parseIsoOption(opts.at, "--at"),
90966
+ ...opts.duration !== undefined ? { durationMinutes: parsePositiveIntOption(opts.duration, "--duration") } : {},
90967
+ timeZone,
90968
+ ...recurrence !== undefined ? { recurrence } : {},
90969
+ sourceMessageRef: opts.message
90970
+ });
90971
+ const res = await api2.scheduleCreate(payload);
90972
+ output2({ success: { event: presentScheduleEventForAgent(res.event) } });
90973
+ });
90974
+ schedule2.command("update").argument("<id>", "schedule event id (sch_...)").description("update a shared schedule event").option("--title <text>", "new title").option("--description <text>", "new instructions/context").option("--at <iso>", "new start time (ISO-8601)").option("--tz <iana>", "new IANA timezone").option("--duration <minutes>", "new duration in minutes (5-1440)").option("--repeat <freq>", "hourly, daily, weekly, monthly, or none to clear recurrence").option("--interval <n>", "recurrence interval").option("--weekdays <days>", "comma-separated weekdays for weekly repeat (0-6 or sun..sat)").option("--until <iso>", "recurrence end timestamp (ISO-8601)").option("--count <n>", "maximum total occurrences").option("--message <ref>", "rebind to another accessible message ref").option("--ack", "mark the current scheduled execution as completed").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function(id4) {
90975
+ const opts = this.opts();
90976
+ const api2 = getApi();
90977
+ if (!api2.scheduleUpdate)
90978
+ throw new Error("Schedule commands are unavailable");
90979
+ if (opts.tz !== undefined && !isValidIanaTimeZone(opts.tz.trim())) {
90980
+ throw new Error(`invalid IANA timezone: ${opts.tz}`);
90981
+ }
90982
+ const recurrence = parseRecurrenceOptions(opts);
90983
+ const patch = ScheduleUpdateRequestSchema.parse({
90984
+ ...opts.title !== undefined ? { title: opts.title } : {},
90985
+ ...opts.description !== undefined ? { description: opts.description } : {},
90986
+ ...opts.at !== undefined ? { startAt: parseIsoOption(opts.at, "--at") } : {},
90987
+ ...opts.tz !== undefined ? { timeZone: opts.tz.trim() } : {},
90988
+ ...opts.duration !== undefined ? { durationMinutes: parsePositiveIntOption(opts.duration, "--duration") } : {},
90989
+ ...recurrence !== undefined ? { recurrence } : {},
90990
+ ...opts.message !== undefined ? { sourceMessageRef: opts.message } : {},
90991
+ ...opts.ack ? { ack: true } : {}
90992
+ });
90993
+ if (Object.keys(patch).length === 0) {
90994
+ throw new Error("provide at least one field to update");
90995
+ }
90996
+ const res = await api2.scheduleUpdate({ id: id4, patch });
90997
+ output2({ success: { event: presentScheduleEventForAgent(res.event) } });
90998
+ });
90999
+ schedule2.command("delete").argument("<id>", "schedule event id (sch_...)").description("delete a shared schedule event").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async (id4) => {
91000
+ const api2 = getApi();
91001
+ if (!api2.scheduleDelete)
91002
+ throw new Error("Schedule commands are unavailable");
91003
+ await api2.scheduleDelete({ id: id4 });
91004
+ output2({ success: { deleted: true, id: id4 } });
91005
+ });
91006
+ }
91007
+
90144
91008
  // src/cli/use-onboard-setup.ts
90145
91009
  import { readFile as readFile5, stat as stat2 } from "node:fs/promises";
90146
91010
  function registerOnboardSetup(use, request, output2) {
@@ -90838,10 +91702,59 @@ function createProxyServerApi(config2) {
90838
91702
  return platformCall("/bots");
90839
91703
  return platformCall("/bots/creation-requests", "POST", { requestId: req.requestId, bots: req.bots });
90840
91704
  }
91705
+ async function callScheduleList(req) {
91706
+ const params = new URLSearchParams;
91707
+ if (req.from)
91708
+ params.set("from", req.from);
91709
+ if (req.to)
91710
+ params.set("to", req.to);
91711
+ if (req.creatorHandle)
91712
+ params.set("creatorHandle", req.creatorHandle);
91713
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
91714
+ const res = await fetchImpl(`${base}/api/community/schedule/events${suffix}`, {
91715
+ method: "GET",
91716
+ headers: { authorization: `Bearer ${config2.voucher}` }
91717
+ });
91718
+ return parseJsonResponse(res, "scheduleList");
91719
+ }
91720
+ async function callScheduleCreate(req) {
91721
+ const res = await fetchImpl(`${base}/api/community/schedule/events`, {
91722
+ method: "POST",
91723
+ headers: {
91724
+ "content-type": "application/json",
91725
+ authorization: `Bearer ${config2.voucher}`
91726
+ },
91727
+ body: JSON.stringify(req)
91728
+ });
91729
+ return parseJsonResponse(res, "scheduleCreate");
91730
+ }
91731
+ async function callScheduleUpdate(req) {
91732
+ const res = await fetchImpl(`${base}/api/community/schedule/events/${encodeURIComponent(req.id)}`, {
91733
+ method: "PATCH",
91734
+ headers: {
91735
+ "content-type": "application/json",
91736
+ authorization: `Bearer ${config2.voucher}`
91737
+ },
91738
+ body: JSON.stringify(req.patch)
91739
+ });
91740
+ return parseJsonResponse(res, "scheduleUpdate");
91741
+ }
91742
+ async function callScheduleDelete(req) {
91743
+ const res = await fetchImpl(`${base}/api/community/schedule/events/${encodeURIComponent(req.id)}`, {
91744
+ method: "DELETE",
91745
+ headers: { authorization: `Bearer ${config2.voucher}` }
91746
+ });
91747
+ await parseJsonResponse(res, "scheduleDelete");
91748
+ return { deleted: true };
91749
+ }
90841
91750
  return {
90842
91751
  platformFeedback: (req) => platformCall("/platform/feedback", "POST", req),
90843
91752
  platformMachine: callPlatformMachine,
90844
91753
  platformBot: callPlatformBot,
91754
+ scheduleList: callScheduleList,
91755
+ scheduleCreate: callScheduleCreate,
91756
+ scheduleUpdate: callScheduleUpdate,
91757
+ scheduleDelete: callScheduleDelete,
90845
91758
  listServers: (_r) => callListServers(),
90846
91759
  joinServer: callJoinServer,
90847
91760
  leaveServer: callLeaveServer,
@@ -91735,6 +92648,7 @@ function buildProgram(stdin) {
91735
92648
  writeErr: () => {}
91736
92649
  }).option("--agent <id>", "agent identity (or ALOOK_AGENT_ID env)");
91737
92650
  registerPlatformCommands(program, getApi, printEnvelope, () => readLiteralInput({ command: "platform feedback", stdinSelected: true, stdin, maxBytes: BOT_FEEDBACK_MAX_BYTES }));
92651
+ registerScheduleCommands(program, getApi, printEnvelope);
91738
92652
  registerUseCommands(program, printEnvelope);
91739
92653
  registerPiiCommands(program, printEnvelope);
91740
92654
  const message = program.command("message").description("message operations").exitOverride();