@alook/daemon 0.1.71 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli/index.js +1243 -466
  2. package/dist/index.js +977 -463
  3. package/package.json +4 -4
package/dist/cli/index.js CHANGED
@@ -13522,13 +13522,13 @@ var require_sourcemap_codec_umd = __commonJS((exports, module) => {
13522
13522
  });
13523
13523
  });
13524
13524
 
13525
- // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13525
+ // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.3/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13526
13526
  var require_resolve_uri_umd = __commonJS((exports, module) => {
13527
13527
  (function(global, factory) {
13528
13528
  typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.resolveURI = factory());
13529
13529
  })(exports, function() {
13530
13530
  const schemeRegex = /^[\w+.-]+:\/\//;
13531
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13531
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?(\[[^\]]+\]|[^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13532
13532
  const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
13533
13533
  function isAbsoluteUrl(input2) {
13534
13534
  return schemeRegex.test(input2);
@@ -43112,7 +43112,7 @@ var AgentModelReportSchema = exports_external.object({
43112
43112
  provider: identity2.optional(),
43113
43113
  source: exports_external.enum(["response", "session"]),
43114
43114
  responseId: identity2.optional(),
43115
- observedAt: exports_external.string().datetime({ offset: true })
43115
+ observedAt: exports_external.iso.datetime({ offset: true })
43116
43116
  });
43117
43117
 
43118
43118
  // ../shared/src/community-decision-card.ts
@@ -43232,7 +43232,8 @@ var DecisionCardEmbedSchema = exports_external.strictObject({
43232
43232
  summary: exports_external.string().trim().min(1).max(DECISION_CARD_SUMMARY_MAX_LENGTH).optional(),
43233
43233
  assignees: exports_external.array(DecisionCardAssigneeSchema).max(DECISION_CARD_MAX_MENTIONS),
43234
43234
  questions: exports_external.array(DecisionCardNormalizedQuestionSchema).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS),
43235
- respondedUserIds: exports_external.array(exports_external.string().min(1)).optional()
43235
+ respondedUserIds: exports_external.array(exports_external.string().min(1)).optional(),
43236
+ viewerDismissed: exports_external.boolean().optional()
43236
43237
  });
43237
43238
  var DecisionCardAnswerItemSchema = exports_external.strictObject({
43238
43239
  questionId: idFieldSchema,
@@ -43319,8 +43320,8 @@ var QuotaLimitSchema = exports_external.object({
43319
43320
  model: QuotaModelIdentitySchema,
43320
43321
  window: QuotaWindowIdentitySchema
43321
43322
  }).strict(),
43322
- usedPercent: exports_external.number().finite().min(0).max(100),
43323
- resetsAt: exports_external.string().datetime({ offset: true }).optional()
43323
+ usedPercent: exports_external.number().min(0).max(100),
43324
+ resetsAt: exports_external.iso.datetime({ offset: true }).optional()
43324
43325
  }).strict();
43325
43326
  function quotaIdentity(limit) {
43326
43327
  const { product, model, window: window2, limitId } = limit.bucket;
@@ -43843,7 +43844,7 @@ var BotAuditEventKindSchema = exports_external.enum([
43843
43844
  var HostBotAuditEventFrameSchema = exports_external.object({
43844
43845
  type: exports_external.literal("bot_audit_event"),
43845
43846
  eventId: exports_external.string().min(1).max(128).optional(),
43846
- occurredAt: exports_external.string().datetime({ offset: true }).optional(),
43847
+ occurredAt: exports_external.iso.datetime({ offset: true }).optional(),
43847
43848
  agentId: exports_external.string().min(1),
43848
43849
  sessionId: exports_external.string().nullable().optional(),
43849
43850
  launchId: exports_external.string().nullable().optional(),
@@ -44099,11 +44100,53 @@ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
44099
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)))
44100
44101
  ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
44101
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
+ });
44102
44144
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
44103
44145
  var CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({
44104
44146
  ...envelope,
44105
44147
  page: CommunityPageSchema,
44106
44148
  relatedMessages: exports_external.array(CommunityMessageResourceSchema).optional(),
44149
+ refs: CommunityMessageRefsSchema.optional(),
44107
44150
  surfaceReceipt: exports_external.strictObject({ channelId: id, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
44108
44151
  }).superRefine(validateRelatedMessageGraph);
44109
44152
  var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
@@ -44183,7 +44226,13 @@ var CommunityMessageReadSchema = exports_external.strictObject({
44183
44226
  validateRelatedMessageGraph({ messages: [read.message], relatedMessages: read.relatedMessages, profiles: read.profiles }, ctx);
44184
44227
  });
44185
44228
  var CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: exports_external.boolean(), threadId: id.optional() });
44186
- 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
+ });
44187
44236
  var CommunityThreadsReadSchema = exports_external.strictObject({
44188
44237
  ...envelope,
44189
44238
  channel: CommunityChannelResourceSchema,
@@ -44415,7 +44464,7 @@ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
44415
44464
  var EntitlementValueSchema = exports_external.lazy(() => exports_external.union([
44416
44465
  exports_external.null(),
44417
44466
  exports_external.boolean(),
44418
- exports_external.number().finite(),
44467
+ exports_external.number(),
44419
44468
  exports_external.string(),
44420
44469
  exports_external.array(EntitlementValueSchema),
44421
44470
  exports_external.record(exports_external.string(), EntitlementValueSchema)
@@ -44442,11 +44491,11 @@ var BillingOfferSchema = exports_external.object({
44442
44491
  var BillingSubscriptionSchema = exports_external.object({
44443
44492
  plan: BillingPlanSchema,
44444
44493
  status: exports_external.string().min(1),
44445
- currentPeriodEnd: exports_external.string().datetime().nullable(),
44446
- cancelAt: exports_external.string().datetime().nullable(),
44494
+ currentPeriodEnd: exports_external.iso.datetime().nullable(),
44495
+ cancelAt: exports_external.iso.datetime().nullable(),
44447
44496
  scheduledChange: exports_external.object({
44448
44497
  plan: BillingPlanSchema,
44449
- effectiveAt: exports_external.string().datetime()
44498
+ effectiveAt: exports_external.iso.datetime()
44450
44499
  }).nullable()
44451
44500
  });
44452
44501
  var PublicPricingSchema = exports_external.object({
@@ -44471,7 +44520,7 @@ var BillingPortalRequestSchema = exports_external.strictObject({
44471
44520
  priceId: exports_external.string().min(1).max(255).optional()
44472
44521
  });
44473
44522
  var BillingRedirectResponseSchema = exports_external.object({
44474
- url: exports_external.string().url()
44523
+ url: exports_external.url()
44475
44524
  });
44476
44525
  // ../shared/src/utils/day-key.ts
44477
44526
  function utcDayKey(now) {
@@ -44509,7 +44558,7 @@ function dayKeyInTimeZone(now, timeZone) {
44509
44558
  return `${year}-${month}-${day}`;
44510
44559
  }
44511
44560
 
44512
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/entity.js
44561
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/entity.js
44513
44562
  var entityKind = Symbol.for("drizzle:entityKind");
44514
44563
  var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
44515
44564
  function is(value, type) {
@@ -44534,7 +44583,7 @@ function is(value, type) {
44534
44583
  return false;
44535
44584
  }
44536
44585
 
44537
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/column.js
44586
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column.js
44538
44587
  class Column {
44539
44588
  constructor(table, config2) {
44540
44589
  this.table = table;
@@ -44584,7 +44633,7 @@ class Column {
44584
44633
  }
44585
44634
  }
44586
44635
 
44587
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/column-builder.js
44636
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column-builder.js
44588
44637
  class ColumnBuilder {
44589
44638
  static [entityKind] = "ColumnBuilder";
44590
44639
  config;
@@ -44640,20 +44689,20 @@ class ColumnBuilder {
44640
44689
  }
44641
44690
  }
44642
44691
 
44643
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/table.utils.js
44692
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.utils.js
44644
44693
  var TableName = Symbol.for("drizzle:Name");
44645
44694
 
44646
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/tracing-utils.js
44695
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing-utils.js
44647
44696
  function iife(fn, ...args) {
44648
44697
  return fn(...args);
44649
44698
  }
44650
44699
 
44651
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/unique-constraint.js
44700
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/unique-constraint.js
44652
44701
  function uniqueKeyName(table, columns) {
44653
44702
  return `${table[TableName]}_${columns.join("_")}_unique`;
44654
44703
  }
44655
44704
 
44656
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/columns/common.js
44705
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/common.js
44657
44706
  class PgColumn extends Column {
44658
44707
  constructor(table, config2) {
44659
44708
  if (!config2.uniqueName) {
@@ -44702,7 +44751,7 @@ class ExtraConfigColumn extends PgColumn {
44702
44751
  }
44703
44752
  }
44704
44753
 
44705
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/columns/enum.js
44754
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/enum.js
44706
44755
  class PgEnumObjectColumn extends PgColumn {
44707
44756
  static [entityKind] = "PgEnumObjectColumn";
44708
44757
  enum;
@@ -44732,7 +44781,7 @@ class PgEnumColumn extends PgColumn {
44732
44781
  }
44733
44782
  }
44734
44783
 
44735
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/subquery.js
44784
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/subquery.js
44736
44785
  class Subquery {
44737
44786
  static [entityKind] = "Subquery";
44738
44787
  constructor(sql, fields, alias, isWith = false, usedTables = []) {
@@ -44747,10 +44796,10 @@ class Subquery {
44747
44796
  }
44748
44797
  }
44749
44798
 
44750
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/version.js
44799
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/version.js
44751
44800
  var version2 = "0.45.4";
44752
44801
 
44753
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/tracing.js
44802
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing.js
44754
44803
  var otel;
44755
44804
  var rawTracer;
44756
44805
  var tracer = {
@@ -44777,10 +44826,10 @@ var tracer = {
44777
44826
  }
44778
44827
  };
44779
44828
 
44780
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/view-common.js
44829
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/view-common.js
44781
44830
  var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
44782
44831
 
44783
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/table.js
44832
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.js
44784
44833
  var Schema = Symbol.for("drizzle:Schema");
44785
44834
  var Columns = Symbol.for("drizzle:Columns");
44786
44835
  var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
@@ -44818,7 +44867,7 @@ class Table {
44818
44867
  }
44819
44868
  }
44820
44869
 
44821
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/sql.js
44870
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/sql.js
44822
44871
  function isSQLWrapper(value) {
44823
44872
  return value !== null && value !== undefined && typeof value.getSQL === "function";
44824
44873
  }
@@ -45181,7 +45230,7 @@ Subquery.prototype.getSQL = function() {
45181
45230
  return new SQL([this]);
45182
45231
  };
45183
45232
 
45184
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/alias.js
45233
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/alias.js
45185
45234
  class ColumnAliasProxyHandler {
45186
45235
  constructor(table) {
45187
45236
  this.table = table;
@@ -45237,7 +45286,7 @@ class TableAliasProxyHandler {
45237
45286
  }
45238
45287
  }
45239
45288
 
45240
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/utils.js
45289
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/utils.js
45241
45290
  function getColumnNameAndConfig(a, b) {
45242
45291
  return {
45243
45292
  name: typeof a === "string" && a.length > 0 ? a : "",
@@ -45246,7 +45295,7 @@ function getColumnNameAndConfig(a, b) {
45246
45295
  }
45247
45296
  var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
45248
45297
 
45249
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/expressions/conditions.js
45298
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/conditions.js
45250
45299
  function bindIfParam(value, column) {
45251
45300
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
45252
45301
  return new Param(value, column);
@@ -45277,7 +45326,7 @@ function isNotNull(value) {
45277
45326
  return sql`${value} is not null`;
45278
45327
  }
45279
45328
 
45280
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/expressions/select.js
45329
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/select.js
45281
45330
  function desc(column) {
45282
45331
  return sql`${column} desc`;
45283
45332
  }
@@ -45316,12 +45365,12 @@ __export(exports_community_schema, {
45316
45365
  communityAttachment: () => communityAttachment
45317
45366
  });
45318
45367
 
45319
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/alias.js
45368
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/alias.js
45320
45369
  function alias(table, alias2) {
45321
45370
  return new Proxy(table, new TableAliasProxyHandler(alias2, false));
45322
45371
  }
45323
45372
 
45324
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/checks.js
45373
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/checks.js
45325
45374
  class CheckBuilder {
45326
45375
  constructor(name, value) {
45327
45376
  this.name = name;
@@ -45348,7 +45397,7 @@ function check2(name, value) {
45348
45397
  return new CheckBuilder(name, value);
45349
45398
  }
45350
45399
 
45351
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
45400
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
45352
45401
  class ForeignKeyBuilder {
45353
45402
  static [entityKind] = "SQLiteForeignKeyBuilder";
45354
45403
  reference;
@@ -45402,7 +45451,7 @@ class ForeignKey {
45402
45451
  }
45403
45452
  }
45404
45453
 
45405
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
45454
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
45406
45455
  function uniqueKeyName2(table, columns) {
45407
45456
  return `${table[TableName]}_${columns.join("_")}_unique`;
45408
45457
  }
@@ -45447,7 +45496,7 @@ class UniqueConstraint {
45447
45496
  }
45448
45497
  }
45449
45498
 
45450
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/common.js
45499
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/common.js
45451
45500
  class SQLiteColumnBuilder extends ColumnBuilder {
45452
45501
  static [entityKind] = "SQLiteColumnBuilder";
45453
45502
  foreignKeyConfigs = [];
@@ -45498,7 +45547,7 @@ class SQLiteColumn extends Column {
45498
45547
  static [entityKind] = "SQLiteColumn";
45499
45548
  }
45500
45549
 
45501
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/blob.js
45550
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/blob.js
45502
45551
  class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
45503
45552
  static [entityKind] = "SQLiteBigIntBuilder";
45504
45553
  constructor(name) {
@@ -45586,7 +45635,7 @@ function blob(a, b) {
45586
45635
  return new SQLiteBlobBufferBuilder(name);
45587
45636
  }
45588
45637
 
45589
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/custom.js
45638
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/custom.js
45590
45639
  class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
45591
45640
  static [entityKind] = "SQLiteCustomColumnBuilder";
45592
45641
  constructor(name, fieldConfig, customTypeParams) {
@@ -45627,7 +45676,7 @@ function customType(customTypeParams) {
45627
45676
  };
45628
45677
  }
45629
45678
 
45630
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/integer.js
45679
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/integer.js
45631
45680
  class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
45632
45681
  static [entityKind] = "SQLiteBaseIntegerBuilder";
45633
45682
  constructor(name, dataType, columnType) {
@@ -45729,7 +45778,7 @@ function integer2(a, b) {
45729
45778
  return new SQLiteIntegerBuilder(name);
45730
45779
  }
45731
45780
 
45732
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
45781
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
45733
45782
  class SQLiteNumericBuilder extends SQLiteColumnBuilder {
45734
45783
  static [entityKind] = "SQLiteNumericBuilder";
45735
45784
  constructor(name) {
@@ -45799,7 +45848,7 @@ function numeric(a, b) {
45799
45848
  return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
45800
45849
  }
45801
45850
 
45802
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/real.js
45851
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/real.js
45803
45852
  class SQLiteRealBuilder extends SQLiteColumnBuilder {
45804
45853
  static [entityKind] = "SQLiteRealBuilder";
45805
45854
  constructor(name) {
@@ -45820,7 +45869,7 @@ function real(name) {
45820
45869
  return new SQLiteRealBuilder(name ?? "");
45821
45870
  }
45822
45871
 
45823
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/text.js
45872
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/text.js
45824
45873
  class SQLiteTextBuilder extends SQLiteColumnBuilder {
45825
45874
  static [entityKind] = "SQLiteTextBuilder";
45826
45875
  constructor(name, config2) {
@@ -45875,7 +45924,7 @@ function text(a, b = {}) {
45875
45924
  return new SQLiteTextBuilder(name, config2);
45876
45925
  }
45877
45926
 
45878
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/all.js
45927
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/all.js
45879
45928
  function getSQLiteColumnBuilders() {
45880
45929
  return {
45881
45930
  blob,
@@ -45887,7 +45936,7 @@ function getSQLiteColumnBuilders() {
45887
45936
  };
45888
45937
  }
45889
45938
 
45890
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/table.js
45939
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/table.js
45891
45940
  var InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
45892
45941
 
45893
45942
  class SQLiteTable extends Table {
@@ -45921,7 +45970,7 @@ var sqliteTable = (name, columns, extraConfig) => {
45921
45970
  return sqliteTableBase(name, columns, extraConfig);
45922
45971
  };
45923
45972
 
45924
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/indexes.js
45973
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/indexes.js
45925
45974
  class IndexBuilderOn {
45926
45975
  constructor(name, unique2) {
45927
45976
  this.name = name;
@@ -45967,7 +46016,7 @@ function uniqueIndex(name) {
45967
46016
  return new IndexBuilderOn(name, true);
45968
46017
  }
45969
46018
 
45970
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/primary-keys.js
46019
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/primary-keys.js
45971
46020
  function primaryKey(...config2) {
45972
46021
  if (config2[0].columns) {
45973
46022
  return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
@@ -46149,7 +46198,7 @@ var nativeOauthAttempt = sqliteTable("native_oauth_attempt", {
46149
46198
  AND ${t.openedAt} IS NOT NULL AND ${t.readyAt} IS NOT NULL AND ${t.consumedAt} IS NULL
46150
46199
  AND ${t.failedAt} IS NULL AND ${t.cancelledAt} IS NULL AND ${t.replacedAt} IS NULL
46151
46200
  AND ${t.handoffCodeHash} IS NOT NULL AND ${t.handoffExpiresAt} IS NOT NULL
46152
- AND ${t.handoffExpiresAt} = ${t.readyAt} + 120000
46201
+ AND ${t.handoffExpiresAt} = min(${t.readyAt} + 120000, ${t.attemptExpiresAt})
46153
46202
  AND ${t.authKind} IS NOT NULL AND ${t.failureCode} IS NULL
46154
46203
  ) OR (
46155
46204
  ${t.status} = 'consumed'
@@ -46243,6 +46292,7 @@ var communityChannelMember = sqliteTable("community_channel_member", {
46243
46292
  }, (t) => [
46244
46293
  index("idx_community_channel_member_added_by_lookup").on(t.addedBy),
46245
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),
46246
46296
  index("idx_channel_member_user").on(t.userId)
46247
46297
  ]);
46248
46298
  var communityMessage = sqliteTable("community_message", {
@@ -46262,6 +46312,7 @@ var communityMessage = sqliteTable("community_message", {
46262
46312
  clientNonce: text("client_nonce")
46263
46313
  }, (t) => [
46264
46314
  index("idx_community_message_author_id_lookup").on(t.authorId),
46315
+ index("idx_message_channel_seq").on(t.channelId, t.seq),
46265
46316
  index("idx_message_channel_created").on(t.channelId, t.createdAt),
46266
46317
  index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt),
46267
46318
  index("idx_community_message_channel_reply_author").on(t.channelId, t.replyToId, t.authorId).where(sql`${t.replyToId} IS NOT NULL`)
@@ -46366,7 +46417,8 @@ var communityReaction = sqliteTable("community_reaction", {
46366
46417
  }, (t) => [
46367
46418
  index("idx_community_reaction_user_id_lookup").on(t.userId),
46368
46419
  unique("uq_reaction_message_user_emoji").on(t.messageId, t.userId, t.emoji),
46369
- 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)
46370
46422
  ]);
46371
46423
  var communityAttachment = sqliteTable("community_attachment", {
46372
46424
  id: text("id").primaryKey().$defaultFn(() => nanoid3()),
@@ -46528,18 +46580,6 @@ var communityMessageTag = sqliteTable("community_message_tag", {
46528
46580
  index("idx_message_tag_tag").on(t.tag, t.messageId)
46529
46581
  ]);
46530
46582
 
46531
- // ../shared/src/db/queries/_chunk.ts
46532
- var D1_MAX_BIND_PARAMS = 100;
46533
- function maxInParams(fixedParams) {
46534
- if (!Number.isInteger(fixedParams) || fixedParams < 0) {
46535
- throw new Error("fixed params must be a non-negative integer");
46536
- }
46537
- if (fixedParams >= D1_MAX_BIND_PARAMS) {
46538
- throw new Error("fixed params must leave room for at least one IN parameter");
46539
- }
46540
- return D1_MAX_BIND_PARAMS - fixedParams;
46541
- }
46542
-
46543
46583
  // ../shared/src/community-server-rail.ts
46544
46584
  var MAX_SERVER_RAIL_COMMANDS = 3;
46545
46585
  var idSchema = exports_external.string().trim().min(1);
@@ -46655,19 +46695,18 @@ class Logger {
46655
46695
  entry[k] = { message: v.message, stack: v.stack };
46656
46696
  }
46657
46697
  }
46658
- let line;
46659
- if (this.pretty) {
46698
+ const output2 = this.pretty ? (() => {
46660
46699
  const ts = entry.ts.replace("T", " ").replace("Z", "");
46661
46700
  const lvl = entry.level.toUpperCase().padEnd(5);
46662
46701
  const pairs = Object.entries(entry).filter(([k]) => k !== "level" && k !== "msg" && k !== "service" && k !== "ts").map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`).join(" ");
46663
- line = `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
46664
- } else {
46665
- line = JSON.stringify(entry);
46666
- }
46702
+ return `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
46703
+ })() : entry;
46667
46704
  if (level === "error") {
46668
- console.error(line);
46705
+ console.error(output2);
46706
+ } else if (level === "warn") {
46707
+ console.warn(output2);
46669
46708
  } else {
46670
- console.log(line);
46709
+ console.log(output2);
46671
46710
  }
46672
46711
  }
46673
46712
  }
@@ -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,58 @@ 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
+
47581
47683
  // ../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 };
47684
+ 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 };
47583
47685
  // ../shared/src/db/queries/native-oauth.ts
47584
47686
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
47585
47687
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
@@ -47608,6 +47710,126 @@ var metadataProjection = {
47608
47710
  };
47609
47711
  // ../shared/src/db/queries/community/diagnostic-report.ts
47610
47712
  var diagnosticOwner = alias(user, "diagnostic_owner");
47713
+ // ../shared/src/schedule.ts
47714
+ var SCHEDULE_TITLE_MAX_LENGTH = 160;
47715
+ var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
47716
+ var SCHEDULE_MIN_DURATION_MINUTES = 5;
47717
+ var SCHEDULE_MAX_DURATION_MINUTES = 1440;
47718
+ var SCHEDULE_MAX_RANGE_MS = 62 * 24 * 60 * 60 * 1000;
47719
+ var ScheduleRecurrenceFreqSchema = exports_external.enum(["hourly", "daily", "weekly", "monthly"]);
47720
+ var ScheduleRecurrenceSchema = exports_external.strictObject({
47721
+ freq: ScheduleRecurrenceFreqSchema,
47722
+ interval: exports_external.number().int().min(1).max(365),
47723
+ byWeekday: exports_external.array(exports_external.number().int().min(0).max(6)).min(1).max(7).optional(),
47724
+ untilAt: exports_external.iso.datetime({ offset: true }).nullable().optional(),
47725
+ count: exports_external.number().int().min(1).max(1000).nullable().optional()
47726
+ }).superRefine((value, ctx) => {
47727
+ if (value.byWeekday !== undefined && value.freq !== "weekly") {
47728
+ ctx.addIssue({
47729
+ code: "custom",
47730
+ path: ["byWeekday"],
47731
+ message: "byWeekday is only supported for weekly recurrence"
47732
+ });
47733
+ }
47734
+ });
47735
+ var ScheduleRunStatusSchema = exports_external.enum([
47736
+ "pending",
47737
+ "dispatched",
47738
+ "completed",
47739
+ "blocked_access"
47740
+ ]);
47741
+ var ScheduleOccurrenceStatusSchema = exports_external.enum([
47742
+ "scheduled",
47743
+ "pending",
47744
+ "dispatched",
47745
+ "completed",
47746
+ "blocked_access"
47747
+ ]);
47748
+ var ScheduleSourceMessageStatusSchema = exports_external.enum([
47749
+ "accessible",
47750
+ "inaccessible",
47751
+ "deleted"
47752
+ ]);
47753
+ var ScheduleActorSummarySchema = exports_external.strictObject({
47754
+ id: exports_external.string().min(1),
47755
+ handle: exports_external.string().min(1),
47756
+ name: exports_external.string().min(1),
47757
+ avatarVersion: exports_external.number().int().nonnegative(),
47758
+ isBot: exports_external.boolean()
47759
+ });
47760
+ var ScheduleLastExecutionSchema = exports_external.strictObject({
47761
+ scheduledAt: exports_external.iso.datetime(),
47762
+ status: ScheduleRunStatusSchema,
47763
+ lastError: exports_external.string().nullable(),
47764
+ ackedAt: exports_external.iso.datetime().nullable(),
47765
+ updatedAt: exports_external.iso.datetime()
47766
+ });
47767
+ var ScheduleSourceMessageSchema = exports_external.strictObject({
47768
+ id: exports_external.string().min(1),
47769
+ accessible: exports_external.boolean(),
47770
+ status: ScheduleSourceMessageStatusSchema,
47771
+ ref: exports_external.string().nullable(),
47772
+ channelRef: exports_external.string().nullable(),
47773
+ seq: exports_external.number().int().positive().nullable(),
47774
+ preview: exports_external.string().nullable()
47775
+ });
47776
+ var ScheduleEventSchema = exports_external.strictObject({
47777
+ id: exports_external.string().min(1),
47778
+ title: exports_external.string().min(1),
47779
+ description: exports_external.string(),
47780
+ createdBy: ScheduleActorSummarySchema,
47781
+ startAt: exports_external.iso.datetime(),
47782
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES),
47783
+ timeZone: exports_external.string().min(1),
47784
+ recurrence: ScheduleRecurrenceSchema.nullable(),
47785
+ nextRunAt: exports_external.iso.datetime().nullable(),
47786
+ sourceMessage: ScheduleSourceMessageSchema,
47787
+ lastExecution: ScheduleLastExecutionSchema.nullable(),
47788
+ createdAt: exports_external.iso.datetime(),
47789
+ updatedAt: exports_external.iso.datetime()
47790
+ });
47791
+ var ScheduleOccurrenceSchema = exports_external.strictObject({
47792
+ eventId: exports_external.string().min(1),
47793
+ occurrenceKey: exports_external.string().min(1),
47794
+ startAt: exports_external.iso.datetime(),
47795
+ endAt: exports_external.iso.datetime(),
47796
+ runStatus: ScheduleOccurrenceStatusSchema
47797
+ });
47798
+ var ScheduleListResponseSchema = exports_external.strictObject({
47799
+ events: exports_external.array(ScheduleEventSchema),
47800
+ occurrences: exports_external.array(ScheduleOccurrenceSchema),
47801
+ creators: exports_external.array(ScheduleActorSummarySchema)
47802
+ });
47803
+ var ScheduleCreateRequestSchema = exports_external.strictObject({
47804
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH),
47805
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
47806
+ startAt: exports_external.iso.datetime({ offset: true }),
47807
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
47808
+ timeZone: exports_external.string().trim().min(1).max(128),
47809
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
47810
+ sourceMessageRef: exports_external.string().trim().min(1).max(512)
47811
+ });
47812
+ var ScheduleUpdateRequestSchema = exports_external.strictObject({
47813
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH).optional(),
47814
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
47815
+ startAt: exports_external.iso.datetime({ offset: true }).optional(),
47816
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
47817
+ timeZone: exports_external.string().trim().min(1).max(128).optional(),
47818
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
47819
+ sourceMessageRef: exports_external.string().trim().min(1).max(512).optional(),
47820
+ ack: exports_external.literal(true).optional()
47821
+ });
47822
+ function isValidIanaTimeZone(timeZone) {
47823
+ if (!timeZone || typeof timeZone !== "string")
47824
+ return false;
47825
+ try {
47826
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(0);
47827
+ return true;
47828
+ } catch {
47829
+ return false;
47830
+ }
47831
+ }
47832
+ var formatterCache = new Map;
47611
47833
  // ../shared/src/lib/invite-link.ts
47612
47834
  var INVITE_URL_RE = /(?:https?:\/\/[^\s/]+)?\/c\/invite\/([A-Za-z0-9_-]{6,64})/;
47613
47835
  var BARE_TOKEN_RE = /^[A-Za-z0-9_-]{6,64}$/;
@@ -47620,6 +47842,12 @@ function parseInviteToken(input2) {
47620
47842
  return urlMatch[1];
47621
47843
  return BARE_TOKEN_RE.test(trimmed) ? trimmed : null;
47622
47844
  }
47845
+ // ../shared/src/lib/channel-ref-syntax.ts
47846
+ 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`;
47847
+ var REF_SEG = `[^\\s/#${REF_TERM}]+`;
47848
+ var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
47849
+ var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
47850
+ var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
47623
47851
  // ../shared/src/utils/email.ts
47624
47852
  var DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`;
47625
47853
  // ../shared/src/lib/safe-redirect.ts
@@ -55790,7 +56018,7 @@ function toResult(value) {
55790
56018
  }
55791
56019
  return value === null || value === undefined ? empty : [value];
55792
56020
  }
55793
- // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.4/node_modules/mdast-util-find-and-replace/lib/index.js
56021
+ // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.5/node_modules/mdast-util-find-and-replace/lib/index.js
55794
56022
  function findAndReplace(tree, list2, options) {
55795
56023
  const settings = options || {};
55796
56024
  const ignored = convert(settings.ignore || []);
@@ -55826,9 +56054,7 @@ function findAndReplace(tree, list2, options) {
55826
56054
  if (typeof value === "string") {
55827
56055
  value = value.length > 0 ? { type: "text", value } : undefined;
55828
56056
  }
55829
- if (value === false) {
55830
- find.lastIndex = position2 + 1;
55831
- } else {
56057
+ if (value !== false) {
55832
56058
  if (start !== position2) {
55833
56059
  add({ type: "text", value: node3.value.slice(start, position2) });
55834
56060
  }
@@ -55841,6 +56067,10 @@ function findAndReplace(tree, list2, options) {
55841
56067
  start = position2 + match[0].length;
55842
56068
  change = true;
55843
56069
  }
56070
+ if (value === false || match[0].length === 0) {
56071
+ const code = node3.value.codePointAt(position2) || 0;
56072
+ find.lastIndex = position2 + (/[uv]/.test(find.flags) && code > 65535 ? 2 : 1);
56073
+ }
55844
56074
  if (!find.global) {
55845
56075
  break;
55846
56076
  }
@@ -55886,7 +56116,7 @@ function toFunction(replace) {
55886
56116
  return replace;
55887
56117
  };
55888
56118
  }
55889
- // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.0.1/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
56119
+ // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.1.0/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
55890
56120
  var inConstruct = "phrasing";
55891
56121
  var notInConstruct = ["autolink", "link", "image", "label"];
55892
56122
  function gfmAutolinkLiteralFromMarkdown() {
@@ -55934,7 +56164,7 @@ function gfmAutolinkLiteralToMarkdown() {
55934
56164
  };
55935
56165
  }
55936
56166
  function enterLiteralAutolink(token) {
55937
- this.enter({ type: "link", title: null, url: "", children: [] }, token);
56167
+ this.enter({ type: "link", title: null, url: "", children: [], position: undefined }, token);
55938
56168
  }
55939
56169
  function enterLiteralAutolinkValue(token) {
55940
56170
  this.config.enter.autolinkProtocol.call(this, token);
@@ -55956,62 +56186,107 @@ function exitLiteralAutolink(token) {
55956
56186
  }
55957
56187
  function transformGfmAutolinkLiterals(tree) {
55958
56188
  findAndReplace(tree, [
55959
- [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
55960
- [/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail]
56189
+ [
56190
+ /(?<![\da-z])(https?:\/\/|www(?=\.))([\w-]*\.[\w\-.]*)([^\t\n\r ]*)/gi,
56191
+ findUrl
56192
+ ],
56193
+ [
56194
+ /(?<![\w+\-.@])xmpp:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)(\/(?:[\w\-/]|\.(?=[\dA-Za-z]))*)?/g,
56195
+ findXmpp
56196
+ ],
56197
+ [/(?<![\w+\-.@])mailto:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g, findMailto],
56198
+ [
56199
+ /(?<![\w+\-.]|(?:^|[^\d@A-Za-z])(?:mailto|xmpp):)([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g,
56200
+ findEmail
56201
+ ]
55961
56202
  ], { ignore: ["link", "linkReference"] });
55962
56203
  }
55963
56204
  function findUrl(_, protocol, domain2, path2, match) {
55964
- let prefix = "";
55965
56205
  if (!previous2(match)) {
55966
56206
  return false;
55967
56207
  }
56208
+ let prefix = "";
55968
56209
  if (/^w/i.test(protocol)) {
55969
56210
  domain2 = protocol + domain2;
55970
56211
  protocol = "";
55971
56212
  prefix = "http://";
55972
56213
  }
55973
- if (!isCorrectDomain(domain2)) {
56214
+ if (unicodePunctuation(domain2.charCodeAt(0)) || !isCorrectDomain(domain2)) {
55974
56215
  return false;
55975
56216
  }
55976
56217
  const parts = splitUrl(domain2 + path2);
55977
- if (!parts[0])
55978
- return false;
55979
56218
  const result = {
55980
56219
  type: "link",
55981
56220
  title: null,
55982
56221
  url: prefix + protocol + parts[0],
55983
- children: [{ type: "text", value: protocol + parts[0] }]
56222
+ children: [{ type: "text", value: protocol + parts[0], position: undefined }],
56223
+ position: undefined
55984
56224
  };
55985
56225
  if (parts[1]) {
55986
- return [result, { type: "text", value: parts[1] }];
56226
+ return [result, { type: "text", value: parts[1], position: undefined }];
55987
56227
  }
55988
56228
  return result;
55989
56229
  }
55990
- function findEmail(_, atext, label, match) {
55991
- if (!previous2(match, true) || /[-\d_]$/.test(label)) {
56230
+ function findEmail(_, atext, label) {
56231
+ if (/[\d\-_]$/.test(label)) {
55992
56232
  return false;
55993
56233
  }
55994
56234
  return {
55995
56235
  type: "link",
55996
56236
  title: null,
55997
56237
  url: "mailto:" + atext + "@" + label,
55998
- children: [{ type: "text", value: atext + "@" + label }]
56238
+ children: [{ type: "text", value: atext + "@" + label, position: undefined }],
56239
+ position: undefined
56240
+ };
56241
+ }
56242
+ function findMailto(_, atext, label) {
56243
+ if (/[\d\-_]$/.test(label)) {
56244
+ return false;
56245
+ }
56246
+ const value = "mailto:" + atext + "@" + label;
56247
+ return {
56248
+ type: "link",
56249
+ title: null,
56250
+ url: value,
56251
+ children: [{ type: "text", value, position: undefined }],
56252
+ position: undefined
56253
+ };
56254
+ }
56255
+ function findXmpp(matchValue, atext, label, resource, match) {
56256
+ if (/[\d\-_]$/.test(label) || resource && (!/[A-Za-z]$/.test(resource) || match.input.charAt(match.index + matchValue.length) === "@")) {
56257
+ return false;
56258
+ }
56259
+ const value = "xmpp:" + atext + "@" + label + (resource || "");
56260
+ return {
56261
+ type: "link",
56262
+ title: null,
56263
+ url: value,
56264
+ children: [{ type: "text", value, position: undefined }],
56265
+ position: undefined
55999
56266
  };
56000
56267
  }
56001
56268
  function isCorrectDomain(domain2) {
56002
56269
  const parts = domain2.split(".");
56003
- if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\d]/.test(parts[parts.length - 2]))) {
56270
+ if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[\dA-Za-z]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[\dA-Za-z]/.test(parts[parts.length - 2]))) {
56004
56271
  return false;
56005
56272
  }
56006
56273
  return true;
56007
56274
  }
56008
56275
  function splitUrl(url2) {
56009
- const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url2);
56010
- if (!trailExec) {
56276
+ let index3 = url2.length;
56277
+ while (index3 > 0) {
56278
+ const code = url2.charCodeAt(index3 - 1);
56279
+ if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 62 || code === 63 || code === 93 || code === 125) {
56280
+ index3--;
56281
+ } else {
56282
+ break;
56283
+ }
56284
+ }
56285
+ if (index3 === url2.length) {
56011
56286
  return [url2, undefined];
56012
56287
  }
56013
- url2 = url2.slice(0, trailExec.index);
56014
- let trail = trailExec[0];
56288
+ let trail = url2.slice(index3);
56289
+ url2 = url2.slice(0, index3);
56015
56290
  let closingParenIndex = trail.indexOf(")");
56016
56291
  const openingParens = ccount(url2, "(");
56017
56292
  let closingParens = ccount(url2, ")");
@@ -56023,9 +56298,9 @@ function splitUrl(url2) {
56023
56298
  }
56024
56299
  return [url2, trail];
56025
56300
  }
56026
- function previous2(match, email3) {
56301
+ function previous2(match) {
56027
56302
  const code = match.input.charCodeAt(match.index - 1);
56028
- return (match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code)) && (!email3 || code !== 47);
56303
+ return match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code);
56029
56304
  }
56030
56305
  // ../../node_modules/.pnpm/mdast-util-gfm-footnote@2.1.0/node_modules/mdast-util-gfm-footnote/lib/index.js
56031
56306
  footnoteReference.peek = footnoteReferencePeek;
@@ -56558,25 +56833,37 @@ function emphasisPeek(_, _1, state) {
56558
56833
  return state.options.emphasis || "*";
56559
56834
  }
56560
56835
 
56561
- // ../../node_modules/.pnpm/unist-util-visit@5.1.0/node_modules/unist-util-visit/lib/index.js
56562
- function visit2(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
56836
+ // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
56837
+ function visit2(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
56838
+ let check3;
56839
+ let visitors;
56563
56840
  let reverse;
56564
- let test;
56565
- let visitor;
56566
- if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
56567
- test = undefined;
56568
- visitor = testOrVisitor;
56569
- reverse = visitorOrReverse;
56570
- } else {
56571
- test = testOrVisitor;
56572
- visitor = visitorOrReverse;
56841
+ if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
56842
+ check3 = testOrEnterOrVisitors;
56843
+ visitors = enterOrVisitorsOrReverse;
56573
56844
  reverse = maybeReverse;
56845
+ } else {
56846
+ visitors = testOrEnterOrVisitors;
56847
+ reverse = enterOrVisitorsOrReverse;
56574
56848
  }
56575
- visitParents(tree, test, overload, reverse);
56576
- function overload(node3, parents) {
56577
- const parent = parents[parents.length - 1];
56578
- const index3 = parent ? parent.children.indexOf(node3) : undefined;
56579
- return visitor(node3, index3, parent);
56849
+ if (typeof visitors === "function") {
56850
+ visitParents(tree, check3, wrap2(visitors), reverse);
56851
+ } else {
56852
+ visitParents(tree, check3, wrapVisitors(visitors), reverse);
56853
+ }
56854
+ }
56855
+ function wrapVisitors(visitors) {
56856
+ if (!visitors || typeof visitors !== "object")
56857
+ return visitors;
56858
+ return {
56859
+ enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
56860
+ exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
56861
+ };
56862
+ }
56863
+ function wrap2(visitor) {
56864
+ return overload;
56865
+ function overload(node3, parents, index3) {
56866
+ return visitor(node3, index3, parents[parents.length - 1]);
56580
56867
  }
56581
56868
  }
56582
56869
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
@@ -59653,43 +59940,10 @@ function peek(_, _1, state) {
59653
59940
  return state.options.emphasis || "*";
59654
59941
  }
59655
59942
 
59656
- // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
59657
- function visit3(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
59658
- let check4;
59659
- let visitors;
59660
- let reverse;
59661
- if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
59662
- check4 = testOrEnterOrVisitors;
59663
- visitors = enterOrVisitorsOrReverse;
59664
- reverse = maybeReverse;
59665
- } else {
59666
- visitors = testOrEnterOrVisitors;
59667
- reverse = enterOrVisitorsOrReverse;
59668
- }
59669
- if (typeof visitors === "function") {
59670
- visitParents(tree, check4, wrap2(visitors), reverse);
59671
- } else {
59672
- visitParents(tree, check4, wrapVisitors(visitors), reverse);
59673
- }
59674
- }
59675
- function wrapVisitors(visitors) {
59676
- if (!visitors || typeof visitors !== "object")
59677
- return visitors;
59678
- return {
59679
- enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
59680
- exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
59681
- };
59682
- }
59683
- function wrap2(visitor) {
59684
- return overload;
59685
- function overload(node3, parents, index3) {
59686
- return visitor(node3, index3, parents[parents.length - 1]);
59687
- }
59688
- }
59689
59943
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.2.3/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
59690
59944
  function formatHeadingAsSetext2(node3, state) {
59691
59945
  let literalWithBreak = false;
59692
- visit3(node3, function(node4) {
59946
+ visit2(node3, function(node4) {
59693
59947
  if ("value" in node4 && /\r?\n|\r/.test(node4.value) || node4.type === "break") {
59694
59948
  literalWithBreak = true;
59695
59949
  return EXIT;
@@ -61487,11 +61741,6 @@ var exitSpoiler = function(token) {
61487
61741
  };
61488
61742
 
61489
61743
  // ../shared/src/lib/chat-syntax-plugin.ts
61490
- 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`;
61491
- var REF_SEG = `[^\\s/#${REF_TERM}]+`;
61492
- var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
61493
- var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
61494
- var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
61495
61744
  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");
61496
61745
  function memberMentionSyntax() {
61497
61746
  const construct = {
@@ -61847,7 +62096,7 @@ function checkProfiles(rows, resources, ctx) {
61847
62096
  }
61848
62097
  }
61849
62098
  var CommunityAcceptedFriendsReadSchema = exports_external.union([
61850
- exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
62099
+ 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)),
61851
62100
  exports_external.strictObject({ ...stale, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema).length(0) })
61852
62101
  ]);
61853
62102
  var CommunityBlockedFriendsReadSchema = exports_external.union([
@@ -61952,7 +62201,10 @@ var CommunityReactionDetailsReadSchema = exports_external.strictObject({
61952
62201
  exports_external.strictObject({ kind: exports_external.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
61953
62202
  exports_external.strictObject({ kind: exports_external.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id })
61954
62203
  ]),
61955
- actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() }))
62204
+ actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() })),
62205
+ emoji: exports_external.string().optional(),
62206
+ hasMore: exports_external.boolean().optional(),
62207
+ cursor: exports_external.string().nullable().optional()
61956
62208
  }).superRefine((value, ctx) => {
61957
62209
  if (new Set(value.actors.map((row) => row.userId)).size !== value.actors.length || value.actors.some((row) => row.profile && row.profile.id !== row.userId))
61958
62210
  ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" });
@@ -63594,9 +63846,11 @@ function parseNativeExecution(data) {
63594
63846
 
63595
63847
  class NativeExecutionReader {
63596
63848
  readRows;
63849
+ continuations;
63597
63850
  path;
63598
- constructor(home, sessionId, readRows = queryExecutionRows) {
63851
+ constructor(home, sessionId, readRows = queryExecutionRows, continuations = false) {
63599
63852
  this.readRows = readRows;
63853
+ this.continuations = continuations;
63600
63854
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
63601
63855
  throw new Error("Invalid native execution session identity");
63602
63856
  this.path = join7(home, "antigravity-cli", "conversations", `${sessionId}.db`);
@@ -63612,20 +63866,28 @@ class NativeExecutionReader {
63612
63866
  return { index: row.idx, executionId: execution.executionId, lastStepIndex: execution.lastStepIndex };
63613
63867
  }
63614
63868
  async terminal(checkpoint) {
63615
- const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex);
63616
- if (rows.length !== 1)
63869
+ const max = this.continuations ? 32 : 1;
63870
+ const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex, undefined, max + 1);
63871
+ if (!rows.length || rows.length > max)
63617
63872
  throw new Error("Native execution terminal unavailable or ambiguous");
63618
- const row = this.validate(rows[0]);
63619
- const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
63620
- if (row.has_children !== 0)
63621
- throw new Error("Native executor subtrajectory ownership cannot be verified");
63622
- if (row.idx !== checkpoint.index + 1 || execution.executionId === checkpoint.executionId)
63623
- throw new Error("Native execution terminal does not belong to the new root");
63624
- if (execution.hasError || execution.reason === 1)
63625
- return "failed";
63626
- if (execution.reason === 2)
63627
- return "interrupted";
63628
- return execution.reason === 4 ? "success" : "failed";
63873
+ let lastStep = checkpoint.lastStepIndex;
63874
+ const identities = new Set([checkpoint.executionId]);
63875
+ let outcome = "success";
63876
+ for (let index3 = 0;index3 < rows.length; index3++) {
63877
+ const row = this.validate(rows[index3]);
63878
+ const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
63879
+ if (row.has_children !== 0)
63880
+ throw new Error("Native executor subtrajectory ownership cannot be verified");
63881
+ if (row.idx !== checkpoint.index + index3 + 1 || identities.has(execution.executionId) || this.continuations && execution.lastStepIndex <= lastStep)
63882
+ throw new Error("Native execution terminal does not belong to the new root");
63883
+ identities.add(execution.executionId);
63884
+ lastStep = execution.lastStepIndex;
63885
+ if (execution.hasError || execution.reason !== 2 && execution.reason !== 4)
63886
+ outcome = "failed";
63887
+ else if (execution.reason === 2 && outcome !== "failed")
63888
+ outcome = "interrupted";
63889
+ }
63890
+ return outcome;
63629
63891
  }
63630
63892
  validate(row) {
63631
63893
  if (!Number.isSafeInteger(row.idx) || row.idx < 0 || !/^(?:[a-f0-9]{2})+$/i.test(row.data) || row.data.length > 2 * 1024 * 1024)
@@ -63647,10 +63909,12 @@ async function openNativeExecutionDatabase(path8, loadBuiltin = async () => {
63647
63909
  }
63648
63910
  return new sqlite.DatabaseSync(path8, { readOnly: true });
63649
63911
  }
63650
- async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = openNativeExecutionDatabase) {
63912
+ async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = openNativeExecutionDatabase, maxRows = 2) {
63651
63913
  if (after !== undefined && (!Number.isSafeInteger(after) || after < -1) || !Number.isSafeInteger(afterStep) || afterStep < -1)
63652
63914
  throw new Error("Invalid native execution cursor");
63653
- const query = `SELECT idx,hex(substr(data,1,1048577)) AS data,${after === undefined ? "(SELECT EXISTS(SELECT 1 FROM steps WHERE idx<0 AND has_subtrajectory=1))" : `(SELECT EXISTS(SELECT 1 FROM steps WHERE idx>${afterStep} AND has_subtrajectory=1))`} AS has_children FROM executor_metadata ${after === undefined ? "ORDER BY idx DESC LIMIT 1" : `WHERE idx>${after} ORDER BY idx LIMIT 2`}`;
63915
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows > 33)
63916
+ throw new Error("Invalid native execution read limit");
63917
+ const query = `SELECT idx,hex(substr(data,1,1048577)) AS data,${after === undefined ? "(SELECT EXISTS(SELECT 1 FROM steps WHERE idx<0 AND has_subtrajectory=1))" : `(SELECT EXISTS(SELECT 1 FROM steps WHERE idx>${afterStep} AND has_subtrajectory=1))`} AS has_children FROM executor_metadata ${after === undefined ? "ORDER BY idx DESC LIMIT 1" : `WHERE idx>${after} ORDER BY idx LIMIT ${maxRows}`}`;
63654
63918
  const db = await openDatabase(path8);
63655
63919
  try {
63656
63920
  return db.prepare(query).all();
@@ -63659,6 +63923,37 @@ async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = o
63659
63923
  }
63660
63924
  }
63661
63925
 
63926
+ class NativeSessionActivityReader {
63927
+ sessionId;
63928
+ version;
63929
+ openDatabase;
63930
+ path;
63931
+ constructor(home, sessionId, version3, openDatabase = openNativeExecutionDatabase) {
63932
+ this.sessionId = sessionId;
63933
+ this.version = version3;
63934
+ this.openDatabase = openDatabase;
63935
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
63936
+ throw new Error("Invalid native activity session identity");
63937
+ this.path = join7(home, "antigravity-cli", "conversation_summaries.db");
63938
+ }
63939
+ async activity() {
63940
+ if (this.version !== "1.5.16")
63941
+ return "unknown";
63942
+ const db = await this.openDatabase(this.path);
63943
+ try {
63944
+ const rows = db.prepare("SELECT status,not_fully_idle FROM conversation_summaries WHERE conversation_id = ? LIMIT 1").all(this.sessionId);
63945
+ const row = rows[0];
63946
+ if (!row || row.not_fully_idle !== 0 && row.not_fully_idle !== 1)
63947
+ return "unknown";
63948
+ if (row.status === "CASCADE_RUN_STATUS_RUNNING")
63949
+ return "running";
63950
+ return row.status === "CASCADE_RUN_STATUS_IDLE" ? row.not_fully_idle ? "running" : "idle" : "unknown";
63951
+ } finally {
63952
+ db.close();
63953
+ }
63954
+ }
63955
+ }
63956
+
63662
63957
  // agent-driver/dist/internal/model-observation.js
63663
63958
  function id3(value) {
63664
63959
  if (typeof value !== "string")
@@ -63876,6 +64171,18 @@ class AgyAcpLane {
63876
64171
  events = new EventEmitter;
63877
64172
  pending = new Map;
63878
64173
  toolCalls = new Map;
64174
+ completedTools = new Set;
64175
+ unownedContent = false;
64176
+ activityReader;
64177
+ activityRead;
64178
+ activityTimer;
64179
+ nativeActivity = "unknown";
64180
+ publishedActivity;
64181
+ activityRevision = 0;
64182
+ nativeVersion = "";
64183
+ contentOwner;
64184
+ executionIsolated = true;
64185
+ nativeClose = false;
63879
64186
  process = null;
63880
64187
  requestSequence = 0;
63881
64188
  started = false;
@@ -63951,10 +64258,13 @@ class AgyAcpLane {
63951
64258
  const sessionId = this.sessionId;
63952
64259
  if (!sessionId)
63953
64260
  throw new Error("Agy ACP handshake completed without a session id");
63954
- this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId);
64261
+ this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, this.nativeVersion === "1.5.16");
63955
64262
  this.processActivated = true;
63956
64263
  this.ready = true;
63957
64264
  this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input2.sessionId ? "resumed" : "created", evidence: "native_api" } });
64265
+ this.activityReader = this.options.activityReader ?? new NativeSessionActivityReader(this.stateHome, sessionId, this.nativeVersion);
64266
+ await this.refreshActivity();
64267
+ this.scheduleActivity();
63958
64268
  const admission = await this.admitRoot(input2.text, input2.inputs);
63959
64269
  if (!admission.ok)
63960
64270
  throw new AgyAcpIncompatibleError(admission.error ?? "Native execution state unavailable");
@@ -63999,6 +64309,7 @@ class AgyAcpLane {
63999
64309
  stop(input2 = {}) {
64000
64310
  this.requestedStopReason ??= input2.reason ?? "requested_stop";
64001
64311
  this.ready = false;
64312
+ this.clearActivityTimer();
64002
64313
  this.currentPromptRequestId = null;
64003
64314
  this.terminalOwner = null;
64004
64315
  this.toolCalls.clear();
@@ -64006,30 +64317,34 @@ class AgyAcpLane {
64006
64317
  this.promptOutcomes.clear();
64007
64318
  this.observedPrompts.clear();
64008
64319
  this.usage.reset();
64009
- const waiter = this.configWaiter;
64010
- if (waiter) {
64011
- clearTimeout(waiter.timer);
64012
- this.configWaiter = undefined;
64013
- waiter.reject(new Error("Antigravity CLI lane stopped"));
64014
- }
64320
+ this.rejectConfigWaiter(new Error("Antigravity CLI lane stopped"));
64015
64321
  this.stopPromise ??= this.stopPhysicalOnce(input2);
64016
64322
  return this.stopPromise;
64017
64323
  }
64018
64324
  async stopPhysicalOnce(input2) {
64325
+ const deadline = Date.now() + (input2.forceAfterMs ?? SESSION_STOP_GRACE_MS);
64019
64326
  await this.spawnPromise?.catch(() => {
64020
64327
  return;
64021
64328
  });
64022
64329
  const proc = this.process;
64023
64330
  if (!proc)
64024
64331
  return;
64332
+ let closeAcknowledged = false;
64333
+ if (this.nativeClose && this.sessionId && !this.isClosed() && deadline > Date.now()) {
64334
+ try {
64335
+ await this.request("session/close", { sessionId: this.sessionId }, Math.max(1, deadline - Date.now())).promise;
64336
+ closeAcknowledged = true;
64337
+ } catch {}
64338
+ }
64025
64339
  if (proc.pid) {
64026
- await killProcessTree(proc.pid, { graceMs: input2.forceAfterMs ?? SESSION_STOP_GRACE_MS });
64340
+ await killProcessTree(proc.pid, { graceMs: closeAcknowledged ? 0 : Math.max(0, deadline - Date.now()) });
64027
64341
  } else if (!this.isClosed()) {
64028
64342
  proc.kill(input2.signal ?? "SIGTERM");
64029
64343
  }
64030
64344
  await this.executionRead?.catch(() => {
64031
64345
  return;
64032
64346
  });
64347
+ await this.activityRead;
64033
64348
  }
64034
64349
  async handshake(ctx) {
64035
64350
  const initialize = record3(await this.call("initialize", {
@@ -64044,6 +64359,7 @@ class AgyAcpLane {
64044
64359
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support protocol version 1");
64045
64360
  }
64046
64361
  const capabilities = record3(initialize.agentCapabilities);
64362
+ this.nativeClose = record3(record3(capabilities?.sessionCapabilities)?.close) !== null;
64047
64363
  if (capabilities?.loadSession !== true) {
64048
64364
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support persistent session loading");
64049
64365
  }
@@ -64051,6 +64367,7 @@ class AgyAcpLane {
64051
64367
  throw new AgyAcpIncompatibleError("Expected the native Antigravity CLI ACP server");
64052
64368
  }
64053
64369
  const version3 = record3(initialize.agentInfo)?.version;
64370
+ this.nativeVersion = typeof version3 === "string" ? version3 : "";
64054
64371
  this.usageProfile = version3 === "1.4.12" ? { inputIncludesCache: true, outputIncludesReasoning: false } : version3 === "1.5.9" ? { inputIncludesCache: false, outputIncludesReasoning: true } : undefined;
64055
64372
  if (!record3(record3(initialize.agentCapabilities)?.sessionCapabilities)?.resume) {
64056
64373
  throw new AgyAcpIncompatibleError("Antigravity CLI ACP does not support native session resume");
@@ -64257,6 +64574,7 @@ class AgyAcpLane {
64257
64574
  if (!this.ready || this.requestedStopReason || this.isClosed())
64258
64575
  return { ok: false, reason: "closed" };
64259
64576
  this.executionCheckpoint = checkpoint;
64577
+ this.executionIsolated = !this.unownedContent && !this.hasPendingTools();
64260
64578
  return this.admitPrompt(text7, "prompt", inputs);
64261
64579
  } catch {
64262
64580
  return { ok: false, reason: "runtime_error", error: "Antigravity CLI native execution state cannot be verified. A readable native conversation database and the packaged SQLite runtime are required." };
@@ -64283,7 +64601,7 @@ class AgyAcpLane {
64283
64601
  this.terminalOwner = prompt.receipt;
64284
64602
  this.currentPromptRequestId = requestId;
64285
64603
  if (delivery === "prompt") {
64286
- this.toolCalls.clear();
64604
+ this.contentOwner = !this.unownedContent && !this.hasPendingTools() ? prompt.receipt : undefined;
64287
64605
  this.promptOutcomes.clear();
64288
64606
  this.observedPrompts.clear();
64289
64607
  this.loopStartedAt = new Date().toISOString();
@@ -64350,13 +64668,22 @@ class AgyAcpLane {
64350
64668
  const read = this.executionReader.terminal(this.executionCheckpoint);
64351
64669
  this.executionRead = read;
64352
64670
  nativeOutcome = await read;
64671
+ if (!this.executionIsolated)
64672
+ nativeOutcome = "unknown";
64353
64673
  } catch {
64354
- verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
64674
+ if (this.executionIsolated)
64675
+ verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
64676
+ else
64677
+ nativeOutcome = "unknown";
64355
64678
  } finally {
64356
64679
  this.executionRead = undefined;
64357
64680
  }
64358
64681
  if (this.terminalOwner !== owner || this.requestedStopReason || this.processTerminal)
64359
64682
  return;
64683
+ if (this.hasPendingTools())
64684
+ this.unownedContent = true;
64685
+ this.observeOutsideWork();
64686
+ this.refreshActivity();
64360
64687
  this.finishing = false;
64361
64688
  const outcomes = [...this.promptOutcomes].sort(([a], [b]) => b - a);
64362
64689
  let latest = outcomes.find(([, outcome]) => outcome.error)?.[1] ?? outcomes[0]?.[1];
@@ -64389,7 +64716,7 @@ class AgyAcpLane {
64389
64716
  this.usage.reset();
64390
64717
  this.currentPromptRequestId = null;
64391
64718
  this.terminalOwner = null;
64392
- this.toolCalls.clear();
64719
+ this.contentOwner = undefined;
64393
64720
  this.promptOutcomes.clear();
64394
64721
  this.observedPrompts.clear();
64395
64722
  if (!latest) {
@@ -64401,7 +64728,7 @@ class AgyAcpLane {
64401
64728
  kind: "turn_end",
64402
64729
  sessionId: this.sessionId ?? undefined,
64403
64730
  turnOwner: terminalOwner,
64404
- outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? "success" : "failed",
64731
+ outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? nativeOutcome === "unknown" ? "unknown" : "success" : "failed",
64405
64732
  stopReason: latest?.stopReason,
64406
64733
  ...latest?.stopReason === "cancelled" ? { pendingContent: "discard" } : {}
64407
64734
  });
@@ -64493,6 +64820,8 @@ class AgyAcpLane {
64493
64820
  }
64494
64821
  this.processTerminal = true;
64495
64822
  this.ready = false;
64823
+ this.clearActivityTimer();
64824
+ this.rejectConfigWaiter(normalized);
64496
64825
  this.currentPromptRequestId = null;
64497
64826
  this.terminalOwner = null;
64498
64827
  this.toolCalls.clear();
@@ -64512,10 +64841,13 @@ class AgyAcpLane {
64512
64841
  return;
64513
64842
  this.processTerminal = true;
64514
64843
  this.ready = false;
64844
+ this.clearActivityTimer();
64845
+ const exitError = new Error("Agy ACP process exited");
64846
+ this.rejectConfigWaiter(exitError);
64515
64847
  this.currentPromptRequestId = null;
64516
64848
  this.terminalOwner = null;
64517
64849
  this.toolCalls.clear();
64518
- this.rejectAllPending(new Error("Agy ACP process exited"));
64850
+ this.rejectAllPending(exitError);
64519
64851
  if (this.suppressExit || !this.processActivated)
64520
64852
  return;
64521
64853
  this.events.emit("exit", {
@@ -64633,24 +64965,38 @@ class AgyAcpLane {
64633
64965
  this.rememberConfig(configuration, true);
64634
64966
  return;
64635
64967
  }
64636
- if (!this.ready || this.currentPromptRequestId === null) {
64637
- this.diagnostic("warning", "Agy ACP emitted a session update without an active prompt");
64968
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
64638
64969
  return;
64639
- }
64640
64970
  const update = record3(payload.update) ?? {};
64641
64971
  const updateType = update?.sessionUpdate;
64642
64972
  switch (updateType) {
64643
64973
  case "agent_message_chunk": {
64644
64974
  const content3 = record3(update.content);
64645
64975
  if (content3?.type === "text" && typeof content3.text === "string") {
64646
- this.events.emit("runtime_event", { kind: "assistant_message_delta", text: content3.text });
64976
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
64977
+ this.unownedContent = true;
64978
+ this.observeOutsideWork();
64979
+ }
64980
+ this.events.emit("runtime_event", {
64981
+ kind: "assistant_message_delta",
64982
+ text: content3.text,
64983
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64984
+ });
64647
64985
  }
64648
64986
  return;
64649
64987
  }
64650
64988
  case "agent_thought_chunk": {
64651
64989
  const content3 = record3(update.content);
64652
64990
  if (content3?.type === "text" && typeof content3.text === "string") {
64653
- this.events.emit("runtime_event", { kind: "assistant_reasoning_delta", text: content3.text });
64991
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
64992
+ this.unownedContent = true;
64993
+ this.observeOutsideWork();
64994
+ }
64995
+ this.events.emit("runtime_event", {
64996
+ kind: "assistant_reasoning_delta",
64997
+ text: content3.text,
64998
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64999
+ });
64654
65000
  }
64655
65001
  return;
64656
65002
  }
@@ -64674,56 +65020,67 @@ class AgyAcpLane {
64674
65020
  this.diagnostic("warning", "Agy ACP emitted a malformed tool_call update");
64675
65021
  return;
64676
65022
  }
64677
- if (!this.toolCalls.has(update.toolCallId)) {
64678
- const name = typeof update.name === "string" ? update.name : update.title;
64679
- this.toolCalls.set(update.toolCallId, name);
65023
+ if (this.completedTools.has(update.toolCallId))
65024
+ return;
65025
+ let tool = this.toolCalls.get(update.toolCallId);
65026
+ if (!tool) {
65027
+ tool = {
65028
+ name: typeof update.name === "string" ? update.name : update.title,
65029
+ owner: this.contentOwner
65030
+ };
65031
+ this.toolCalls.set(update.toolCallId, tool);
64680
65032
  this.events.emit("runtime_event", {
64681
65033
  kind: "tool_call",
64682
65034
  callId: update.toolCallId,
64683
- name,
64684
- input: update.rawInput
64685
- });
64686
- }
64687
- if ((update.status === "completed" || update.status === "failed") && this.toolCalls.get(update.toolCallId) !== null) {
64688
- const name = this.toolCalls.get(update.toolCallId) ?? update.title;
64689
- this.toolCalls.set(update.toolCallId, null);
64690
- this.events.emit("runtime_event", {
64691
- kind: "tool_output",
64692
- callId: update.toolCallId,
64693
- name,
64694
- outcome: update.status === "failed" ? "failed" : "success",
64695
- output: update.rawOutput
65035
+ name: tool.name,
65036
+ input: update.rawInput,
65037
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
64696
65038
  });
64697
65039
  }
65040
+ this.observeOutsideWork();
65041
+ if (update.status === "completed" || update.status === "failed")
65042
+ this.finishTool(update, tool);
64698
65043
  return;
64699
65044
  }
64700
65045
  case "tool_call_update": {
64701
- if (typeof update.toolCallId === "string" && (update.status === "completed" || update.status === "failed")) {
64702
- const name = this.toolCalls.get(update.toolCallId);
64703
- if (name === undefined || name === null)
64704
- return;
64705
- this.toolCalls.set(update.toolCallId, null);
64706
- this.events.emit("runtime_event", {
64707
- kind: "tool_output",
64708
- callId: update.toolCallId,
64709
- outcome: update.status === "failed" ? "failed" : "success",
64710
- output: update.rawOutput,
64711
- name
64712
- });
64713
- }
65046
+ if (typeof update.toolCallId !== "string")
65047
+ return;
65048
+ const tool = this.toolCalls.get(update.toolCallId);
65049
+ if (!tool)
65050
+ return;
65051
+ if (update.status === "completed" || update.status === "failed")
65052
+ this.finishTool(update, tool);
64714
65053
  return;
64715
65054
  }
64716
65055
  case "plan":
64717
65056
  this.events.emit("runtime_event", {
64718
65057
  kind: "internal_progress",
64719
65058
  source: "agy.acp",
64720
- itemType: "plan"
65059
+ itemType: "plan",
65060
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64721
65061
  });
64722
65062
  return;
64723
65063
  default:
64724
65064
  this.diagnostic("warning", `Unsupported Agy ACP session update: ${safeLabel(updateType)}`);
64725
65065
  }
64726
65066
  }
65067
+ finishTool(update, tool) {
65068
+ this.toolCalls.delete(update.toolCallId);
65069
+ this.completedTools.add(update.toolCallId);
65070
+ if (this.completedTools.size > 4096)
65071
+ this.completedTools.delete(this.completedTools.values().next().value);
65072
+ if (!tool.owner || tool.owner !== this.terminalOwner)
65073
+ this.unownedContent = true;
65074
+ this.observeOutsideWork();
65075
+ this.events.emit("runtime_event", {
65076
+ kind: "tool_output",
65077
+ callId: update.toolCallId,
65078
+ name: tool.name,
65079
+ outcome: update.status === "failed" ? "failed" : "success",
65080
+ output: update.rawOutput ?? update.content,
65081
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
65082
+ });
65083
+ }
64727
65084
  diagnostic(severity, message) {
64728
65085
  this.events.emit("runtime_event", {
64729
65086
  kind: "runtime_diagnostic",
@@ -64732,6 +65089,72 @@ class AgyAcpLane {
64732
65089
  message
64733
65090
  });
64734
65091
  }
65092
+ hasPendingTools() {
65093
+ return this.toolCalls.size > 0;
65094
+ }
65095
+ publishActivity() {
65096
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
65097
+ return;
65098
+ const status = this.hasPendingTools() ? "running" : this.nativeActivity;
65099
+ if (status === this.publishedActivity)
65100
+ return;
65101
+ this.publishedActivity = status;
65102
+ this.events.emit("runtime_event", { kind: "session_activity", observation: { status, source: "agy.native" } });
65103
+ }
65104
+ observeOutsideWork() {
65105
+ this.activityRevision += 1;
65106
+ this.nativeActivity = "unknown";
65107
+ this.publishActivity();
65108
+ }
65109
+ refreshActivity() {
65110
+ if (this.activityRead)
65111
+ return this.activityRead;
65112
+ if (!this.ready || !this.activityReader || this.requestedStopReason || this.processTerminal)
65113
+ return Promise.resolve();
65114
+ const revision = this.activityRevision;
65115
+ const reading = (async () => {
65116
+ let status = "unknown";
65117
+ try {
65118
+ status = await this.activityReader.activity();
65119
+ } catch {}
65120
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
65121
+ return;
65122
+ if (revision === this.activityRevision)
65123
+ this.nativeActivity = status;
65124
+ if (status === "running" && this.currentPromptRequestId === null)
65125
+ this.unownedContent = true;
65126
+ this.publishActivity();
65127
+ })();
65128
+ this.activityRead = reading;
65129
+ reading.finally(() => {
65130
+ if (this.activityRead === reading)
65131
+ this.activityRead = undefined;
65132
+ });
65133
+ return reading;
65134
+ }
65135
+ clearActivityTimer() {
65136
+ if (!this.activityTimer)
65137
+ return;
65138
+ clearTimeout(this.activityTimer);
65139
+ this.activityTimer = undefined;
65140
+ }
65141
+ rejectConfigWaiter(error62) {
65142
+ const waiter = this.configWaiter;
65143
+ if (!waiter)
65144
+ return;
65145
+ clearTimeout(waiter.timer);
65146
+ this.configWaiter = undefined;
65147
+ waiter.reject(error62);
65148
+ }
65149
+ scheduleActivity() {
65150
+ if (!this.ready || this.requestedStopReason || this.processTerminal || this.activityTimer)
65151
+ return;
65152
+ this.activityTimer = setTimeout(() => {
65153
+ this.activityTimer = undefined;
65154
+ this.refreshActivity().then(() => this.scheduleActivity());
65155
+ }, this.options.activityPollMs ?? 1000);
65156
+ this.activityTimer.unref?.();
65157
+ }
64735
65158
  protocolFailure(message) {
64736
65159
  const error62 = new Error(message);
64737
65160
  this.rejectAllPending(error62);
@@ -67023,7 +67446,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
67023
67446
  const candidates3 = [];
67024
67447
  const readDirectory = options.readDirectory ?? ((directory) => readdir(directory, { withFileTypes: true }));
67025
67448
  const statPath = options.statPath ?? stat;
67026
- const visit4 = async (directory, remainingDepth, includeFiles) => {
67449
+ const visit3 = async (directory, remainingDepth, includeFiles) => {
67027
67450
  let entries;
67028
67451
  try {
67029
67452
  entries = await readDirectory(directory);
@@ -67035,7 +67458,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
67035
67458
  await Promise.all(entries.map(async (entry) => {
67036
67459
  const entryPath = path9.join(directory, entry.name);
67037
67460
  if (entry.isDirectory() && remainingDepth > 0) {
67038
- await visit4(entryPath, remainingDepth - 1, true);
67461
+ await visit3(entryPath, remainingDepth - 1, true);
67039
67462
  } else if (includeFiles && entry.isFile() && entry.name.endsWith(".jsonl")) {
67040
67463
  try {
67041
67464
  const metadata = await statPath(entryPath);
@@ -67048,7 +67471,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
67048
67471
  }
67049
67472
  }));
67050
67473
  };
67051
- await visit4(root3, options.maxDepth ?? Number.POSITIVE_INFINITY, options.includeRootFiles ?? true);
67474
+ await visit3(root3, options.maxDepth ?? Number.POSITIVE_INFINITY, options.includeRootFiles ?? true);
67052
67475
  return candidates3;
67053
67476
  }
67054
67477
  function retainNewest(values2, key, value, topK) {
@@ -74734,6 +75157,10 @@ class LogicalAgentSession {
74734
75157
  events;
74735
75158
  closed;
74736
75159
  state = "new";
75160
+ activity;
75161
+ sessionMessage = emptySemanticAssembler();
75162
+ sessionReasoning = emptySemanticAssembler();
75163
+ sessionContentTimer;
74737
75164
  backendSessionId;
74738
75165
  acquisition;
74739
75166
  configuration;
@@ -74934,11 +75361,12 @@ class LogicalAgentSession {
74934
75361
  }
74935
75362
  snapshot() {
74936
75363
  return {
75364
+ ...this.activity ? { activity: this.activity } : {},
74937
75365
  ...this.acquisition ? { acquisition: this.acquisition } : {},
74938
75366
  ...this.configuration ? { configuration: this.configuration } : {},
74939
75367
  ...this.observedModel ? { observedModel: { ...this.observedModel } } : {},
74940
75368
  sessionInstanceId: this.sessionInstanceId,
74941
- state: this.state,
75369
+ state: this.state === "idle" && this.activity && this.activity.status === "running" ? "working" : this.state,
74942
75370
  backendSessionId: this.backendSessionId,
74943
75371
  activeTurn: this.activeTurn ? { turnId: this.activeTurn.turnId, commandIds: this.activeTurn.commandIds } : undefined,
74944
75372
  queuedCommands: this.queued.map(({ message }) => ({
@@ -75264,6 +75692,13 @@ class LogicalAgentSession {
75264
75692
  return;
75265
75693
  if (this.isClosedPerTurnLaneTail(physicalOwner, generation))
75266
75694
  return;
75695
+ if (event.kind === "session_activity") {
75696
+ if (event.observation.status === "idle")
75697
+ this.flushSessionContent();
75698
+ this.activity = event.observation;
75699
+ this.emit({ type: "session_activity", observation: event.observation });
75700
+ return;
75701
+ }
75267
75702
  const observation = event.kind === "model_observed" ? modelObservation(event.observation.model, event.observation.source, event.observation.provider, event.observation.responseId) : event.kind === "configuration_observed" && event.observation.evidence === "observed" && event.observation.effective === "current" ? modelObservation(event.observation.model, "session") : undefined;
75268
75703
  if (observation)
75269
75704
  this.emit({
@@ -75274,7 +75709,19 @@ class LogicalAgentSession {
75274
75709
  });
75275
75710
  if (event.kind === "model_observed")
75276
75711
  return;
75277
- if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown") {
75712
+ if (event.attribution?.scope === "session" && (event.kind === "assistant_message_delta" || event.kind === "assistant_reasoning_delta")) {
75713
+ appendSemanticFragment(event.kind === "assistant_message_delta" ? this.sessionMessage : this.sessionReasoning, event.text);
75714
+ if (event.text && !this.sessionContentTimer) {
75715
+ this.sessionContentTimer = setTimeout(() => {
75716
+ this.sessionContentTimer = undefined;
75717
+ if (this.state !== "closed" && this.state !== "stopping")
75718
+ this.flushSessionContent();
75719
+ }, 500);
75720
+ this.sessionContentTimer.unref?.();
75721
+ }
75722
+ return;
75723
+ }
75724
+ if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown" || event.attribution?.scope === "session") {
75278
75725
  this.emit({
75279
75726
  type: "activity",
75280
75727
  attribution: event.attribution,
@@ -75282,6 +75729,7 @@ class LogicalAgentSession {
75282
75729
  ..."text" in event ? { text: boundedSemanticCompletion(event.text).text } : {},
75283
75730
  ..."callId" in event ? { callId: event.callId } : {},
75284
75731
  ..."name" in event ? { name: event.name } : {},
75732
+ ..."input" in event ? { input: jsonValue(event.input) } : {},
75285
75733
  ..."outcome" in event ? { outcome: event.outcome } : {},
75286
75734
  ..."output" in event ? { output: jsonValue(event.output) } : {}
75287
75735
  });
@@ -75492,10 +75940,23 @@ class LogicalAgentSession {
75492
75940
  this.emit({ type: "assistant_message_completed", turnId, ...message });
75493
75941
  }
75494
75942
  }
75943
+ this.flushSessionContent();
75495
75944
  this.completeTurn(event.sessionId, physicalOwner, generation, event.turnOwner);
75496
75945
  return;
75497
75946
  }
75498
75947
  }
75948
+ flushSessionContent() {
75949
+ if (this.sessionContentTimer)
75950
+ clearTimeout(this.sessionContentTimer);
75951
+ this.sessionContentTimer = undefined;
75952
+ for (const [kind, buffer] of [["assistant_reasoning_completed", this.sessionReasoning], ["assistant_message_completed", this.sessionMessage]]) {
75953
+ const completion = finishSemanticAssembler(buffer);
75954
+ if (completion.text)
75955
+ this.emit({ type: "activity", attribution: { scope: "session" }, kind, ...completion });
75956
+ }
75957
+ this.sessionMessage = emptySemanticAssembler();
75958
+ this.sessionReasoning = emptySemanticAssembler();
75959
+ }
75499
75960
  isClosedPerTurnLaneTail(physicalOwner, generation) {
75500
75961
  if (this.adapter.execution.lifetime !== "turn" || this.activeTurn)
75501
75962
  return false;
@@ -76023,6 +76484,7 @@ class LogicalAgentSession {
76023
76484
  const cleanup = hostCleanup.status === "failed" || hostCleanup.status === "timed_out" ? hostCleanup : this.laneCleanupFailure ?? hostCleanup;
76024
76485
  const result2 = buildResult(cleanup);
76025
76486
  this.terminalResult = result2;
76487
+ this.flushSessionContent();
76026
76488
  this.state = "closed";
76027
76489
  this.emit({ type: "session_closed", result: result2 });
76028
76490
  this.eventQueue.close();
@@ -76690,6 +77152,9 @@ function resolveProxyCapability(method, pathname) {
76690
77152
  return "read";
76691
77153
  if (pathname === "/api/community/bots/creation-requests" && method === "POST")
76692
77154
  return "send";
77155
+ if (/^\/api\/community\/schedule\/events(\/[^/]+)?$/.test(pathname)) {
77156
+ return method === "GET" ? "read" : "send";
77157
+ }
76693
77158
  if ((method === "GET" || method === "PATCH") && pathname === communityProxyRoutes.profile || method === "POST" && pathname === communityProxyRoutes.avatar)
76694
77159
  return "profile";
76695
77160
  if (pathname.includes("/attachment"))
@@ -76764,6 +77229,22 @@ function resolveProxyAuditOperation(pathname, method) {
76764
77229
  return "profileAvatarUpdate";
76765
77230
  if (/^\/api\/community\/bots\/me\/nap(\/|$|\?)/.test(canonical))
76766
77231
  return "nap";
77232
+ if (/^\/api\/community\/schedule\/events$/.test(canonical)) {
77233
+ if (method === "GET")
77234
+ return "scheduleList";
77235
+ if (method === "POST")
77236
+ return "scheduleCreate";
77237
+ return null;
77238
+ }
77239
+ if (/^\/api\/community\/schedule\/events\/[^/]+$/.test(canonical)) {
77240
+ if (method === "GET")
77241
+ return "scheduleGet";
77242
+ if (method === "PATCH")
77243
+ return "scheduleUpdate";
77244
+ if (method === "DELETE")
77245
+ return "scheduleDelete";
77246
+ return null;
77247
+ }
76767
77248
  return null;
76768
77249
  }
76769
77250
  function propertyAuditMetadata(method, pathname, requestUrl) {
@@ -80773,212 +81254,233 @@ async function startCredentialProxy(broker, options = {}) {
80773
81254
  return;
80774
81255
  }
80775
81256
  };
80776
- const server = http.createServer(async (req, res) => {
80777
- const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
80778
- const pathname = requestUrl.pathname;
80779
- if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
80780
- if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
80781
- writeJson(res, 405, { error: "method not allowed" });
80782
- req.resume();
81257
+ const server = http.createServer((req, res) => {
81258
+ (async () => {
81259
+ const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
81260
+ const pathname = requestUrl.pathname;
81261
+ if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
81262
+ if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
81263
+ writeJson(res, 405, { error: "method not allowed" });
81264
+ req.resume();
81265
+ return;
81266
+ }
81267
+ const verdict2 = broker.check(req.headers["authorization"], "send");
81268
+ if (!verdict2.ok) {
81269
+ writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
81270
+ req.resume();
81271
+ return;
81272
+ }
81273
+ await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
80783
81274
  return;
80784
81275
  }
80785
- const verdict2 = broker.check(req.headers["authorization"], "send");
80786
- if (!verdict2.ok) {
80787
- writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
80788
- req.resume();
81276
+ if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
81277
+ const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
81278
+ if (!localVerdict.ok) {
81279
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81280
+ req.resume();
81281
+ return;
81282
+ }
81283
+ await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
80789
81284
  return;
80790
81285
  }
80791
- await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
80792
- return;
80793
- }
80794
- if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
80795
- const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
80796
- if (!localVerdict.ok) {
80797
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
80798
- req.resume();
81286
+ if (pathname.startsWith("/__alook/local/")) {
81287
+ if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
81288
+ writeJson(res, 404, { error: "unknown local route", code: "not_found" });
81289
+ req.resume();
81290
+ return;
81291
+ }
81292
+ if (req.method !== "PUT") {
81293
+ writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
81294
+ req.resume();
81295
+ return;
81296
+ }
81297
+ const localVerdict = broker.check(req.headers["authorization"], "send");
81298
+ if (!localVerdict.ok) {
81299
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81300
+ req.resume();
81301
+ return;
81302
+ }
81303
+ handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
80799
81304
  return;
80800
81305
  }
80801
- await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
80802
- return;
80803
- }
80804
- if (pathname.startsWith("/__alook/local/")) {
80805
- if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
80806
- writeJson(res, 404, { error: "unknown local route", code: "not_found" });
81306
+ const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
81307
+ const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
81308
+ const verdict = broker.check(req.headers["authorization"], requiredCap);
81309
+ if (!verdict.ok) {
81310
+ res.writeHead(verdict.status, { "content-type": "application/json" });
81311
+ res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
80807
81312
  req.resume();
80808
81313
  return;
80809
81314
  }
80810
- if (req.method !== "PUT") {
80811
- writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
80812
- req.resume();
81315
+ if (pathname.startsWith("/api/community/machines") && !(req.method === "GET" && /^\/api\/community\/machines(?:\/[^/]+(?:\/models)?)?$/.test(pathname) || req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname))) {
81316
+ writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
80813
81317
  return;
80814
81318
  }
80815
- const localVerdict = broker.check(req.headers["authorization"], "send");
80816
- if (!localVerdict.ok) {
80817
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81319
+ const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81320
+ if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
81321
+ res.writeHead(404, { "content-type": "application/json" });
81322
+ res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
80818
81323
  req.resume();
80819
81324
  return;
80820
81325
  }
80821
- handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
80822
- return;
80823
- }
80824
- const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
80825
- const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
80826
- const verdict = broker.check(req.headers["authorization"], requiredCap);
80827
- if (!verdict.ok) {
80828
- res.writeHead(verdict.status, { "content-type": "application/json" });
80829
- res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
80830
- req.resume();
80831
- return;
80832
- }
80833
- if (pathname.startsWith("/api/community/machines") && !(req.method === "GET" && /^\/api\/community\/machines(?:\/[^/]+(?:\/models)?)?$/.test(pathname) || req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname))) {
80834
- writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
80835
- return;
80836
- }
80837
- const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
80838
- if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
80839
- res.writeHead(404, { "content-type": "application/json" });
80840
- res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
80841
- req.resume();
80842
- return;
80843
- }
80844
- if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
80845
- writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
80846
- req.resume();
80847
- return;
80848
- }
80849
- const reg = verdict.reg;
80850
- if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
80851
- writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
80852
- req.resume();
80853
- return;
80854
- }
80855
- let filteredBody;
80856
- let piiTriggeredFilters = [];
80857
- if (options.pii && route.filterPiiSend) {
80858
- try {
80859
- const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
80860
- filteredBody = filtered.body;
80861
- piiTriggeredFilters = filtered.triggeredFilters;
80862
- } catch (error62) {
80863
- writePiiError(res, error62);
81326
+ if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
81327
+ writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
81328
+ req.resume();
80864
81329
  return;
80865
81330
  }
80866
- if (res.destroyed)
81331
+ const reg = verdict.reg;
81332
+ if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
81333
+ writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
81334
+ req.resume();
80867
81335
  return;
80868
- }
80869
- const isInboxPull = route.inboxObservation === "pull";
80870
- const isInboxAck = route.inboxObservation === "ack";
80871
- const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
80872
- const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
80873
- let inboxPullObservationToken;
80874
- let inboxAckObservationToken;
80875
- if (shouldObserveInboxPull) {
80876
- try {
80877
- inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
80878
- } catch {
80879
- reportInboxPullObservationError({
80880
- agentId: reg.agentId,
80881
- reason: "observer_failed",
80882
- contentEncoding: "identity"
80883
- });
80884
81336
  }
80885
- }
80886
- if (shouldObserveInboxAck) {
80887
- try {
80888
- inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
80889
- } catch {
80890
- reportInboxAckObservationError({
80891
- agentId: reg.agentId,
80892
- reason: "observer_failed",
80893
- contentEncoding: "identity"
80894
- });
81337
+ let filteredBody;
81338
+ let piiTriggeredFilters = [];
81339
+ if (options.pii && route.filterPiiSend) {
81340
+ try {
81341
+ const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
81342
+ filteredBody = filtered.body;
81343
+ piiTriggeredFilters = filtered.triggeredFilters;
81344
+ } catch (error62) {
81345
+ writePiiError(res, error62);
81346
+ return;
81347
+ }
81348
+ if (res.destroyed)
81349
+ return;
80895
81350
  }
80896
- }
80897
- if (onProxyRequest) {
80898
- try {
80899
- const method = req.method ?? "GET";
80900
- onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
80901
- } catch {}
80902
- }
80903
- const outHeaders = { ...req.headers };
80904
- delete outHeaders["authorization"];
80905
- delete outHeaders["host"];
80906
- outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
80907
- outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
80908
- outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
80909
- outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
80910
- if (isInboxPull || isInboxAck)
80911
- outHeaders["accept-encoding"] = "identity";
80912
- if (filteredBody) {
80913
- delete outHeaders["transfer-encoding"];
80914
- outHeaders["content-length"] = filteredBody.byteLength;
80915
- }
80916
- let responded = false;
80917
- if (piiTriggeredFilters.length)
80918
- outHeaders["accept-encoding"] = "identity";
80919
- let upstreamRes;
80920
- const upstreamReq = upstreamClient.request({
80921
- protocol: upstream.protocol,
80922
- hostname: upstream.hostname,
80923
- port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
80924
- method: req.method,
80925
- path: joinPath(upstream.pathname, req.url ?? "/"),
80926
- headers: outHeaders
80927
- }, (res_) => {
80928
- responded = true;
80929
- upstreamRes = res_;
80930
- const destroyResIfIncomplete = () => {
80931
- if (!res_.complete)
80932
- res.destroy();
80933
- };
80934
- res_.on("error", destroyResIfIncomplete);
80935
- res_.on("close", destroyResIfIncomplete);
80936
- if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
80937
- const chunks = [];
80938
- res_.on("data", (chunk2) => chunks.push(chunk2));
80939
- res_.on("end", () => {
80940
- const body = Buffer.concat(chunks);
80941
- const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
80942
- if (contentEncoding !== "identity") {
80943
- if (shouldObserveInboxPull) {
80944
- reportInboxPullObservationError({
80945
- agentId: reg.agentId,
80946
- reason: "unexpected_content_encoding",
80947
- contentEncoding
80948
- });
80949
- } else {
80950
- reportInboxAckObservationError({
80951
- agentId: reg.agentId,
80952
- reason: "unexpected_content_encoding",
80953
- contentEncoding
80954
- });
80955
- }
80956
- } else {
80957
- let parsed;
80958
- try {
80959
- parsed = JSON.parse(body.toString("utf8"));
80960
- } catch {
81351
+ const isInboxPull = route.inboxObservation === "pull";
81352
+ const isInboxAck = route.inboxObservation === "ack";
81353
+ const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
81354
+ const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
81355
+ let inboxPullObservationToken;
81356
+ let inboxAckObservationToken;
81357
+ if (shouldObserveInboxPull) {
81358
+ try {
81359
+ inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
81360
+ } catch {
81361
+ reportInboxPullObservationError({
81362
+ agentId: reg.agentId,
81363
+ reason: "observer_failed",
81364
+ contentEncoding: "identity"
81365
+ });
81366
+ }
81367
+ }
81368
+ if (shouldObserveInboxAck) {
81369
+ try {
81370
+ inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
81371
+ } catch {
81372
+ reportInboxAckObservationError({
81373
+ agentId: reg.agentId,
81374
+ reason: "observer_failed",
81375
+ contentEncoding: "identity"
81376
+ });
81377
+ }
81378
+ }
81379
+ if (onProxyRequest) {
81380
+ try {
81381
+ const method = req.method ?? "GET";
81382
+ onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
81383
+ } catch {}
81384
+ }
81385
+ const outHeaders = { ...req.headers };
81386
+ delete outHeaders["authorization"];
81387
+ delete outHeaders["host"];
81388
+ outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
81389
+ outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
81390
+ outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
81391
+ outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
81392
+ if (isInboxPull || isInboxAck)
81393
+ outHeaders["accept-encoding"] = "identity";
81394
+ if (filteredBody) {
81395
+ delete outHeaders["transfer-encoding"];
81396
+ outHeaders["content-length"] = filteredBody.byteLength;
81397
+ }
81398
+ let responded = false;
81399
+ if (piiTriggeredFilters.length)
81400
+ outHeaders["accept-encoding"] = "identity";
81401
+ let upstreamRes;
81402
+ const upstreamReq = upstreamClient.request({
81403
+ protocol: upstream.protocol,
81404
+ hostname: upstream.hostname,
81405
+ port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
81406
+ method: req.method,
81407
+ path: joinPath(upstream.pathname, req.url ?? "/"),
81408
+ headers: outHeaders
81409
+ }, (res_) => {
81410
+ responded = true;
81411
+ upstreamRes = res_;
81412
+ const destroyResIfIncomplete = () => {
81413
+ if (!res_.complete)
81414
+ res.destroy();
81415
+ };
81416
+ res_.on("error", destroyResIfIncomplete);
81417
+ res_.on("close", destroyResIfIncomplete);
81418
+ if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
81419
+ const chunks = [];
81420
+ res_.on("data", (chunk2) => chunks.push(chunk2));
81421
+ res_.on("end", () => {
81422
+ const body = Buffer.concat(chunks);
81423
+ const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
81424
+ if (contentEncoding !== "identity") {
80961
81425
  if (shouldObserveInboxPull) {
80962
- reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81426
+ reportInboxPullObservationError({
81427
+ agentId: reg.agentId,
81428
+ reason: "unexpected_content_encoding",
81429
+ contentEncoding
81430
+ });
80963
81431
  } else {
80964
- reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81432
+ reportInboxAckObservationError({
81433
+ agentId: reg.agentId,
81434
+ reason: "unexpected_content_encoding",
81435
+ contentEncoding
81436
+ });
80965
81437
  }
80966
- }
80967
- if (parsed !== undefined) {
80968
- if (shouldObserveInboxPull) {
80969
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
80970
- reportInboxPullObservationError({
81438
+ } else {
81439
+ let parsed;
81440
+ try {
81441
+ parsed = JSON.parse(body.toString("utf8"));
81442
+ } catch {
81443
+ if (shouldObserveInboxPull) {
81444
+ reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81445
+ } else {
81446
+ reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81447
+ }
81448
+ }
81449
+ if (parsed !== undefined) {
81450
+ if (shouldObserveInboxPull) {
81451
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
81452
+ reportInboxPullObservationError({
81453
+ agentId: reg.agentId,
81454
+ reason: "invalid_inbox_shape",
81455
+ contentEncoding
81456
+ });
81457
+ } else {
81458
+ const messages = parsed.messages;
81459
+ if (messages.length > 0) {
81460
+ try {
81461
+ onPull(reg.agentId, messages, inboxPullObservationToken);
81462
+ } catch {
81463
+ reportInboxPullObservationError({
81464
+ agentId: reg.agentId,
81465
+ reason: "observer_failed",
81466
+ contentEncoding
81467
+ });
81468
+ }
81469
+ }
81470
+ }
81471
+ } else if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.applied) || !parsed.applied.every((cursor) => Boolean(cursor) && typeof cursor === "object" && !Array.isArray(cursor) && typeof cursor.channel === "string" && cursor.channel.length > 0 && typeof cursor.seq === "number" && Number.isSafeInteger(cursor.seq) && cursor.seq > 0)) {
81472
+ reportInboxAckObservationError({
80971
81473
  agentId: reg.agentId,
80972
- reason: "invalid_inbox_shape",
81474
+ reason: "invalid_ack_shape",
80973
81475
  contentEncoding
80974
81476
  });
80975
81477
  } else {
80976
- const messages = parsed.messages;
80977
- if (messages.length > 0) {
81478
+ const applied = parsed.applied;
81479
+ if (applied.length > 0) {
80978
81480
  try {
80979
- onPull(reg.agentId, messages, inboxPullObservationToken);
81481
+ onAck(reg.agentId, applied, inboxAckObservationToken);
80980
81482
  } catch {
80981
- reportInboxPullObservationError({
81483
+ reportInboxAckObservationError({
80982
81484
  agentId: reg.agentId,
80983
81485
  reason: "observer_failed",
80984
81486
  contentEncoding
@@ -80986,66 +81488,47 @@ async function startCredentialProxy(broker, options = {}) {
80986
81488
  }
80987
81489
  }
80988
81490
  }
80989
- } else if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.applied) || !parsed.applied.every((cursor) => Boolean(cursor) && typeof cursor === "object" && !Array.isArray(cursor) && typeof cursor.channel === "string" && cursor.channel.length > 0 && typeof cursor.seq === "number" && Number.isSafeInteger(cursor.seq) && cursor.seq > 0)) {
80990
- reportInboxAckObservationError({
80991
- agentId: reg.agentId,
80992
- reason: "invalid_ack_shape",
80993
- contentEncoding
80994
- });
80995
- } else {
80996
- const applied = parsed.applied;
80997
- if (applied.length > 0) {
80998
- try {
80999
- onAck(reg.agentId, applied, inboxAckObservationToken);
81000
- } catch {
81001
- reportInboxAckObservationError({
81002
- agentId: reg.agentId,
81003
- reason: "observer_failed",
81004
- contentEncoding
81005
- });
81006
- }
81007
- }
81008
81491
  }
81009
81492
  }
81010
- }
81011
- res.writeHead(res_.statusCode, res_.headers);
81012
- res.end(body);
81013
- });
81014
- } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
81015
- forwardPiiSendResponse(res_, res, piiTriggeredFilters);
81016
- } else {
81017
- res.writeHead(res_.statusCode ?? 502, res_.headers);
81018
- res_.pipe(res);
81019
- }
81020
- });
81021
- upstreamReq.on("error", (err) => {
81022
- if (responded)
81023
- return;
81024
- responded = true;
81025
- res.writeHead(502, { "content-type": "application/json" });
81026
- res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
81027
- });
81028
- const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
81029
- const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
81030
- upstreamReq.setTimeout(upstreamTimeoutMs, () => {
81031
- upstreamReq.destroy();
81032
- upstreamRes?.destroy();
81033
- if (responded) {
81034
- res.destroy();
81035
- return;
81036
- }
81037
- responded = true;
81038
- res.writeHead(504, { "content-type": "application/json" });
81039
- res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
81040
- });
81041
- res.on("close", () => {
81042
- upstreamReq.destroy();
81043
- upstreamRes?.destroy();
81044
- });
81045
- if (filteredBody)
81046
- upstreamReq.end(filteredBody);
81047
- else
81048
- req.pipe(upstreamReq);
81493
+ res.writeHead(res_.statusCode, res_.headers);
81494
+ res.end(body);
81495
+ });
81496
+ } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
81497
+ forwardPiiSendResponse(res_, res, piiTriggeredFilters);
81498
+ } else {
81499
+ res.writeHead(res_.statusCode ?? 502, res_.headers);
81500
+ res_.pipe(res);
81501
+ }
81502
+ });
81503
+ upstreamReq.on("error", (err) => {
81504
+ if (responded)
81505
+ return;
81506
+ responded = true;
81507
+ res.writeHead(502, { "content-type": "application/json" });
81508
+ res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
81509
+ });
81510
+ const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
81511
+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
81512
+ upstreamReq.setTimeout(upstreamTimeoutMs, () => {
81513
+ upstreamReq.destroy();
81514
+ upstreamRes?.destroy();
81515
+ if (responded) {
81516
+ res.destroy();
81517
+ return;
81518
+ }
81519
+ responded = true;
81520
+ res.writeHead(504, { "content-type": "application/json" });
81521
+ res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
81522
+ });
81523
+ res.on("close", () => {
81524
+ upstreamReq.destroy();
81525
+ upstreamRes?.destroy();
81526
+ });
81527
+ if (filteredBody)
81528
+ upstreamReq.end(filteredBody);
81529
+ else
81530
+ req.pipe(upstreamReq);
81531
+ })();
81049
81532
  });
81050
81533
  await new Promise((resolve7, reject) => {
81051
81534
  server.once("error", reject);
@@ -81072,7 +81555,10 @@ function joinPath(basePath, reqUrl) {
81072
81555
  }
81073
81556
  // src/manager/managerPolicy.ts
81074
81557
  function isActivelyWorking(agent) {
81075
- return agent.status === "running" && (leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
81558
+ return agent.status === "running" && (agent.sessionActivity?.status === "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
81559
+ }
81560
+ function sessionBlocksIdleCleanup(agent) {
81561
+ return agent.sessionActivity !== undefined && agent.sessionActivity.status !== "idle";
81076
81562
  }
81077
81563
  var DEFAULT_STALE_THRESHOLD_MS = 120000;
81078
81564
  var DEFAULT_TURN_SILENCE_POLICY = {
@@ -81098,6 +81584,19 @@ function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS
81098
81584
  }
81099
81585
  function reduceManager(state, event) {
81100
81586
  switch (event.type) {
81587
+ case "session_activity": {
81588
+ const current = state.agents[event.agentId];
81589
+ if (!current || !matchesSession(current, event.sessionInstanceId) || current.status === "stopping")
81590
+ return { state, effects: [] };
81591
+ const agent = clone2(current);
81592
+ const changed = agent.sessionActivity?.status !== event.observation.status;
81593
+ agent.sessionActivity = event.observation;
81594
+ if (sessionBlocksIdleCleanup(agent))
81595
+ agent.idleSince = null;
81596
+ else if (changed && !leaseIsWorking(agent.execution.lease) && agent.pendingAdmissions.length === 0 && agent.inbox.length === 0)
81597
+ agent.idleSince = event.nowMs;
81598
+ return commit(state, agent, []);
81599
+ }
81101
81600
  case "register":
81102
81601
  return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
81103
81602
  case "wake":
@@ -81147,6 +81646,7 @@ function reduceManager(state, event) {
81147
81646
  {
81148
81647
  const a = agent;
81149
81648
  a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
81649
+ a.sessionActivity = undefined;
81150
81650
  a.turnSilence = event.turnSilence ?? {
81151
81651
  ...DEFAULT_TURN_SILENCE_POLICY,
81152
81652
  nativeIdleTimeoutMs: state.staleThresholdMs,
@@ -81348,6 +81848,7 @@ function reduceManager(state, event) {
81348
81848
  const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
81349
81849
  agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
81350
81850
  agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
81851
+ agent.sessionActivity = undefined;
81351
81852
  syncExecutionProjection(agent);
81352
81853
  return commit(state, agent, recoveryEffects(agent, closing));
81353
81854
  }
@@ -81476,7 +81977,7 @@ function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endRe
81476
81977
  ...messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" }))
81477
81978
  ]);
81478
81979
  }
81479
- agent.idleSince = agent.status === "running" && !agent.resetting ? nowMs : null;
81980
+ agent.idleSince = agent.status === "running" && !agent.resetting && !sessionBlocksIdleCleanup(agent) ? nowMs : null;
81480
81981
  return commit(state, agent, clearEffects);
81481
81982
  }
81482
81983
  function onTurnToolLifecycle(state, event, lifecycle) {
@@ -81626,13 +82127,13 @@ function onTick(state, nowMs) {
81626
82127
  effects.push({ type: "force_exit", agentId: id4, reason: "stopping_stuck" });
81627
82128
  continue;
81628
82129
  }
81629
- const idleResetEligible = a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
82130
+ const idleResetEligible = !sessionBlocksIdleCleanup(a) && a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
81630
82131
  if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
81631
82132
  agents[id4] = { ...a, idleSince: nowMs };
81632
82133
  effects.push({ type: "maintain_idle_memory", agentId: id4, sessionId: a.sessionId });
81633
82134
  continue;
81634
82135
  }
81635
- const idleEligible = a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
82136
+ const idleEligible = !sessionBlocksIdleCleanup(a) && a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
81636
82137
  if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
81637
82138
  agents[id4] = { ...a, status: "stopping", stoppingSince: nowMs };
81638
82139
  effects.push({ type: "stop", agentId: id4, reason: "idle_timeout" });
@@ -81666,6 +82167,8 @@ function freshAgent(agentId) {
81666
82167
  }
81667
82168
  function enterStable(agent, status) {
81668
82169
  agent.status = status;
82170
+ if (status === "idle")
82171
+ agent.sessionActivity = undefined;
81669
82172
  agent.resetting = false;
81670
82173
  agent.resettingSince = null;
81671
82174
  agent.stoppingSince = null;
@@ -81829,6 +82332,11 @@ function messagingSection() {
81829
82332
  "- 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.",
81830
82333
  "- Use `0` only when no later action depends on a reply. It disables the timer.",
81831
82334
  "",
82335
+ "#### Schedule future or recurring work",
82336
+ "",
82337
+ "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message or daemon restart cancels it.",
82338
+ `- 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.`,
82339
+ "",
81832
82340
  "#### Sending mechanics",
81833
82341
  "",
81834
82342
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
@@ -81879,7 +82387,11 @@ function messagingSection() {
81879
82387
  "",
81880
82388
  "#### Ask for a decision",
81881
82389
  "",
81882
- `Alook users cannot see native question prompts. When you need someone to choose from options, use \`${CLI} message send --ask\` with JSON on stdin (max 8 KiB).`,
82390
+ `Whenever you would use your native Ask Question tool, use Alook’s \`${CLI} message send --ask --remind-after 5m\` in the current conversation instead. People on Alook can only see the question you send there.`,
82391
+ "",
82392
+ "When you ask a question and can offer options, use a decision card. " + "Use a normal Alook message for updates and questions without options.",
82393
+ "",
82394
+ "Pass JSON on stdin (max 8 KiB).",
81883
82395
  "Include a required non-empty `summary` (1–240 chars). Recommend at least one option per question to help the user decide. Use `recommended: true`. Use `mentions` to name respondents, and short `header` values for multi-question tabs. Answers arrive in your inbox as replies to the original question.",
81884
82396
  "",
81885
82397
  "```json",
@@ -82004,6 +82516,15 @@ function cliCommandsSection() {
82004
82516
  "Adding stores a source copy. Later edits to the input file do not update the installed filter. " + "Do not edit daemon-managed copies.",
82005
82517
  "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.",
82006
82518
  "",
82519
+ "### Schedule",
82520
+ "",
82521
+ "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.",
82522
+ "",
82523
+ `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given, expanded occurrences.`,
82524
+ `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.`,
82525
+ `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack]\` — update a task, or pass \`--ack\` after finishing the triggered run to mark it completed.`,
82526
+ `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
82527
+ "",
82007
82528
  "### Settings",
82008
82529
  "",
82009
82530
  `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.`,
@@ -83771,6 +84292,9 @@ ${this.opts.wakePromptFooter}` : text8;
83771
84292
  return;
83772
84293
  }
83773
84294
  const sessionSuperseded = owner.superseded;
84295
+ if (event.type === "session_activity" && !sessionSuperseded) {
84296
+ this.dispatch({ type: "session_activity", agentId, sessionInstanceId: event.sessionInstanceId, observation: event.observation, nowMs: this.now() }, owner);
84297
+ }
83774
84298
  const runtimeError = event.type === "session_failed" ? event.error : event.type === "turn_completed" && event.result.outcome === "failed" ? event.result.error : undefined;
83775
84299
  if (runtimeError !== undefined && !sessionSuperseded) {
83776
84300
  this.emitErrorAudit(agentId, "runtime", runtimeError.code, runtimeError.message);
@@ -83787,12 +84311,12 @@ ${this.opts.wakePromptFooter}` : text8;
83787
84311
  }
83788
84312
  }
83789
84313
  if (this.opts.onBotAuditEvent) {
83790
- if (event.type === "assistant_message_completed" && event.text.length > 0) {
84314
+ if ((event.type === "assistant_message_completed" || event.type === "activity" && event.kind === "assistant_message_completed") && event.text && event.text.length > 0) {
83791
84315
  const { text: text8, truncated, chars } = truncateAuditText(event.text);
83792
84316
  try {
83793
84317
  this.opts.onBotAuditEvent(agentId, {
83794
84318
  kind: "text",
83795
- payload: { text: text8, truncated: truncated || event.truncated, chars }
84319
+ payload: { text: text8, truncated: truncated || event.truncated === true, chars }
83796
84320
  }, {
83797
84321
  sessionId: this.liveSessions.get(agentId) ?? null,
83798
84322
  launchId: this.launchIds.get(agentId) ?? null
@@ -87668,6 +88192,7 @@ function projectDaemonLogRow(value, targetAgentId) {
87668
88192
  };
87669
88193
  }
87670
88194
  var CURRENT_MANAGER_EVENTS = {
88195
+ session_activity: "include",
87671
88196
  register: "include",
87672
88197
  wake: "include",
87673
88198
  spawned: "include",
@@ -89888,6 +90413,208 @@ function registerPlatformCommands(program, getApi, output2, readFeedbackInput) {
89888
90413
  });
89889
90414
  }
89890
90415
 
90416
+ // src/cli/schedule.ts
90417
+ var WEEKDAY_TOKENS = {
90418
+ "0": 0,
90419
+ sun: 0,
90420
+ sunday: 0,
90421
+ "1": 1,
90422
+ mon: 1,
90423
+ monday: 1,
90424
+ "2": 2,
90425
+ tue: 2,
90426
+ tues: 2,
90427
+ tuesday: 2,
90428
+ "3": 3,
90429
+ wed: 3,
90430
+ wednesday: 3,
90431
+ "4": 4,
90432
+ thu: 4,
90433
+ thur: 4,
90434
+ thurs: 4,
90435
+ thursday: 4,
90436
+ "5": 5,
90437
+ fri: 5,
90438
+ friday: 5,
90439
+ "6": 6,
90440
+ sat: 6,
90441
+ saturday: 6
90442
+ };
90443
+ function parseIsoOption(raw, flag) {
90444
+ const ms = Date.parse(raw);
90445
+ if (!Number.isFinite(ms)) {
90446
+ throw new Error(`${flag} must be a valid ISO-8601 timestamp (e.g. 2026-11-26T09:00:00+08:00)`);
90447
+ }
90448
+ return new Date(ms).toISOString();
90449
+ }
90450
+ function parsePositiveIntOption(raw, flag) {
90451
+ if (!/^\d+$/.test(raw.trim()))
90452
+ throw new Error(`${flag} must be a positive integer`);
90453
+ const value = Number(raw.trim());
90454
+ if (!Number.isSafeInteger(value) || value <= 0)
90455
+ throw new Error(`${flag} must be a positive integer`);
90456
+ return value;
90457
+ }
90458
+ function parseWeekdaysOption(raw) {
90459
+ const tokens = raw.split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
90460
+ if (tokens.length === 0)
90461
+ throw new Error("--weekdays requires at least one weekday (0-6 or sun..sat)");
90462
+ const days = [];
90463
+ for (const token of tokens) {
90464
+ const mapped = WEEKDAY_TOKENS[token];
90465
+ if (mapped === undefined)
90466
+ throw new Error(`invalid weekday "${token}" (use 0-6 or sun..sat)`);
90467
+ days.push(mapped);
90468
+ }
90469
+ return [...new Set(days)].sort((a, b) => a - b);
90470
+ }
90471
+ function parseRecurrenceOptions(opts) {
90472
+ const hasRecurrenceFlags = opts.repeat !== undefined || opts.interval !== undefined || opts.weekdays !== undefined || opts.until !== undefined || opts.count !== undefined;
90473
+ if (!hasRecurrenceFlags)
90474
+ return;
90475
+ if (opts.repeat?.trim().toLowerCase() === "none")
90476
+ return null;
90477
+ if (!opts.repeat) {
90478
+ throw new Error("--repeat <hourly|daily|weekly|monthly> is required when using --interval, --weekdays, --until, or --count");
90479
+ }
90480
+ const freq = ScheduleRecurrenceFreqSchema.safeParse(opts.repeat.trim().toLowerCase());
90481
+ if (!freq.success) {
90482
+ throw new Error("--repeat must be one of hourly, daily, weekly, monthly, or none");
90483
+ }
90484
+ const interval = opts.interval ? parsePositiveIntOption(opts.interval, "--interval") : 1;
90485
+ const byWeekday = opts.weekdays ? parseWeekdaysOption(opts.weekdays) : undefined;
90486
+ const untilAt = opts.until && opts.until.trim().toLowerCase() !== "none" ? parseIsoOption(opts.until, "--until") : undefined;
90487
+ const count2 = opts.count && opts.count.trim().toLowerCase() !== "none" ? parsePositiveIntOption(opts.count, "--count") : undefined;
90488
+ return {
90489
+ freq: freq.data,
90490
+ interval,
90491
+ ...byWeekday ? { byWeekday } : {},
90492
+ ...untilAt ? { untilAt } : {},
90493
+ ...count2 ? { count: count2 } : {}
90494
+ };
90495
+ }
90496
+ function defaultLocalTimeZone() {
90497
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
90498
+ return tz && isValidIanaTimeZone(tz) ? tz : "UTC";
90499
+ }
90500
+ function presentScheduleEventForAgent(event) {
90501
+ return {
90502
+ id: event.id,
90503
+ title: event.title,
90504
+ description: event.description,
90505
+ createdBy: event.createdBy.handle,
90506
+ startAt: toLocalISO(event.startAt),
90507
+ durationMinutes: event.durationMinutes,
90508
+ timeZone: event.timeZone,
90509
+ recurrence: event.recurrence ? {
90510
+ ...event.recurrence,
90511
+ ...event.recurrence.untilAt ? { untilAt: toLocalISO(event.recurrence.untilAt) } : {}
90512
+ } : null,
90513
+ nextRunAt: event.nextRunAt ? toLocalISO(event.nextRunAt) : null,
90514
+ sourceMessage: {
90515
+ accessible: event.sourceMessage.accessible,
90516
+ status: event.sourceMessage.status,
90517
+ ...event.sourceMessage.ref ? { ref: event.sourceMessage.ref } : {},
90518
+ ...event.sourceMessage.preview ? { preview: event.sourceMessage.preview } : {}
90519
+ },
90520
+ ...event.lastExecution ? {
90521
+ lastExecution: {
90522
+ scheduledAt: toLocalISO(event.lastExecution.scheduledAt),
90523
+ status: event.lastExecution.status,
90524
+ ...event.lastExecution.ackedAt ? { ackedAt: toLocalISO(event.lastExecution.ackedAt) } : {},
90525
+ ...event.lastExecution.lastError ? { lastError: event.lastExecution.lastError } : {},
90526
+ updatedAt: toLocalISO(event.lastExecution.updatedAt)
90527
+ }
90528
+ } : {},
90529
+ createdAt: toLocalISO(event.createdAt),
90530
+ updatedAt: toLocalISO(event.updatedAt)
90531
+ };
90532
+ }
90533
+ function presentOccurrenceForAgent(occ) {
90534
+ return {
90535
+ eventId: occ.eventId,
90536
+ startAt: toLocalISO(occ.startAt),
90537
+ endAt: toLocalISO(occ.endAt),
90538
+ runStatus: occ.runStatus
90539
+ };
90540
+ }
90541
+ function registerScheduleCommands(program, getApi, output2) {
90542
+ const schedule2 = program.command("schedule").description("manage the household shared schedule (owner and bots)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
90543
+ 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() {
90544
+ const opts = this.opts();
90545
+ const api2 = getApi();
90546
+ if (!api2.scheduleList)
90547
+ throw new Error("Schedule commands are unavailable");
90548
+ const from = opts.from ? parseIsoOption(opts.from, "--from") : undefined;
90549
+ const to = opts.to ? parseIsoOption(opts.to, "--to") : undefined;
90550
+ const res = await api2.scheduleList({
90551
+ ...from ? { from } : {},
90552
+ ...to ? { to } : {},
90553
+ ...opts.creator ? { creatorHandle: opts.creator } : {}
90554
+ });
90555
+ output2({
90556
+ success: {
90557
+ events: res.events.map(presentScheduleEventForAgent),
90558
+ ...res.occurrences.length > 0 ? { occurrences: res.occurrences.map(presentOccurrenceForAgent) } : {},
90559
+ creators: res.creators.map((c) => c.handle)
90560
+ }
90561
+ });
90562
+ });
90563
+ 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() {
90564
+ const opts = this.opts();
90565
+ const api2 = getApi();
90566
+ if (!api2.scheduleCreate)
90567
+ throw new Error("Schedule commands are unavailable");
90568
+ const timeZone = opts.tz?.trim() || defaultLocalTimeZone();
90569
+ if (!isValidIanaTimeZone(timeZone))
90570
+ throw new Error(`invalid IANA timezone: ${timeZone}`);
90571
+ const recurrence = parseRecurrenceOptions(opts);
90572
+ const payload = ScheduleCreateRequestSchema.parse({
90573
+ title: opts.title,
90574
+ ...opts.description !== undefined ? { description: opts.description } : {},
90575
+ startAt: parseIsoOption(opts.at, "--at"),
90576
+ ...opts.duration !== undefined ? { durationMinutes: parsePositiveIntOption(opts.duration, "--duration") } : {},
90577
+ timeZone,
90578
+ ...recurrence !== undefined ? { recurrence } : {},
90579
+ sourceMessageRef: opts.message
90580
+ });
90581
+ const res = await api2.scheduleCreate(payload);
90582
+ output2({ success: { event: presentScheduleEventForAgent(res.event) } });
90583
+ });
90584
+ 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) {
90585
+ const opts = this.opts();
90586
+ const api2 = getApi();
90587
+ if (!api2.scheduleUpdate)
90588
+ throw new Error("Schedule commands are unavailable");
90589
+ if (opts.tz !== undefined && !isValidIanaTimeZone(opts.tz.trim())) {
90590
+ throw new Error(`invalid IANA timezone: ${opts.tz}`);
90591
+ }
90592
+ const recurrence = parseRecurrenceOptions(opts);
90593
+ const patch = ScheduleUpdateRequestSchema.parse({
90594
+ ...opts.title !== undefined ? { title: opts.title } : {},
90595
+ ...opts.description !== undefined ? { description: opts.description } : {},
90596
+ ...opts.at !== undefined ? { startAt: parseIsoOption(opts.at, "--at") } : {},
90597
+ ...opts.tz !== undefined ? { timeZone: opts.tz.trim() } : {},
90598
+ ...opts.duration !== undefined ? { durationMinutes: parsePositiveIntOption(opts.duration, "--duration") } : {},
90599
+ ...recurrence !== undefined ? { recurrence } : {},
90600
+ ...opts.message !== undefined ? { sourceMessageRef: opts.message } : {},
90601
+ ...opts.ack ? { ack: true } : {}
90602
+ });
90603
+ if (Object.keys(patch).length === 0) {
90604
+ throw new Error("provide at least one field to update");
90605
+ }
90606
+ const res = await api2.scheduleUpdate({ id: id4, patch });
90607
+ output2({ success: { event: presentScheduleEventForAgent(res.event) } });
90608
+ });
90609
+ schedule2.command("delete").argument("<id>", "schedule event id (sch_...)").description("delete a shared schedule event").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async (id4) => {
90610
+ const api2 = getApi();
90611
+ if (!api2.scheduleDelete)
90612
+ throw new Error("Schedule commands are unavailable");
90613
+ await api2.scheduleDelete({ id: id4 });
90614
+ output2({ success: { deleted: true, id: id4 } });
90615
+ });
90616
+ }
90617
+
89891
90618
  // src/cli/use-onboard-setup.ts
89892
90619
  import { readFile as readFile5, stat as stat2 } from "node:fs/promises";
89893
90620
  function registerOnboardSetup(use, request, output2) {
@@ -90585,10 +91312,59 @@ function createProxyServerApi(config2) {
90585
91312
  return platformCall("/bots");
90586
91313
  return platformCall("/bots/creation-requests", "POST", { requestId: req.requestId, bots: req.bots });
90587
91314
  }
91315
+ async function callScheduleList(req) {
91316
+ const params = new URLSearchParams;
91317
+ if (req.from)
91318
+ params.set("from", req.from);
91319
+ if (req.to)
91320
+ params.set("to", req.to);
91321
+ if (req.creatorHandle)
91322
+ params.set("creatorHandle", req.creatorHandle);
91323
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
91324
+ const res = await fetchImpl(`${base}/api/community/schedule/events${suffix}`, {
91325
+ method: "GET",
91326
+ headers: { authorization: `Bearer ${config2.voucher}` }
91327
+ });
91328
+ return parseJsonResponse(res, "scheduleList");
91329
+ }
91330
+ async function callScheduleCreate(req) {
91331
+ const res = await fetchImpl(`${base}/api/community/schedule/events`, {
91332
+ method: "POST",
91333
+ headers: {
91334
+ "content-type": "application/json",
91335
+ authorization: `Bearer ${config2.voucher}`
91336
+ },
91337
+ body: JSON.stringify(req)
91338
+ });
91339
+ return parseJsonResponse(res, "scheduleCreate");
91340
+ }
91341
+ async function callScheduleUpdate(req) {
91342
+ const res = await fetchImpl(`${base}/api/community/schedule/events/${encodeURIComponent(req.id)}`, {
91343
+ method: "PATCH",
91344
+ headers: {
91345
+ "content-type": "application/json",
91346
+ authorization: `Bearer ${config2.voucher}`
91347
+ },
91348
+ body: JSON.stringify(req.patch)
91349
+ });
91350
+ return parseJsonResponse(res, "scheduleUpdate");
91351
+ }
91352
+ async function callScheduleDelete(req) {
91353
+ const res = await fetchImpl(`${base}/api/community/schedule/events/${encodeURIComponent(req.id)}`, {
91354
+ method: "DELETE",
91355
+ headers: { authorization: `Bearer ${config2.voucher}` }
91356
+ });
91357
+ await parseJsonResponse(res, "scheduleDelete");
91358
+ return { deleted: true };
91359
+ }
90588
91360
  return {
90589
91361
  platformFeedback: (req) => platformCall("/platform/feedback", "POST", req),
90590
91362
  platformMachine: callPlatformMachine,
90591
91363
  platformBot: callPlatformBot,
91364
+ scheduleList: callScheduleList,
91365
+ scheduleCreate: callScheduleCreate,
91366
+ scheduleUpdate: callScheduleUpdate,
91367
+ scheduleDelete: callScheduleDelete,
90592
91368
  listServers: (_r) => callListServers(),
90593
91369
  joinServer: callJoinServer,
90594
91370
  leaveServer: callLeaveServer,
@@ -91482,6 +92258,7 @@ function buildProgram(stdin) {
91482
92258
  writeErr: () => {}
91483
92259
  }).option("--agent <id>", "agent identity (or ALOOK_AGENT_ID env)");
91484
92260
  registerPlatformCommands(program, getApi, printEnvelope, () => readLiteralInput({ command: "platform feedback", stdinSelected: true, stdin, maxBytes: BOT_FEEDBACK_MAX_BYTES }));
92261
+ registerScheduleCommands(program, getApi, printEnvelope);
91485
92262
  registerUseCommands(program, printEnvelope);
91486
92263
  registerPiiCommands(program, printEnvelope);
91487
92264
  const message = program.command("message").description("message operations").exitOverride();