@alook/daemon 0.1.74 → 0.1.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -35608,6 +35608,11 @@ function assertInstructionFileName(name) {
35608
35608
  import { mkdirSync as mkdirSync4 } from "node:fs";
35609
35609
  var SEMANTIC_ASSEMBLER_MAX_BYTES = 1048576;
35610
35610
  var WORK_HEARTBEAT_MIN_INTERVAL_MS = 1000;
35611
+ var QUEUED_BATCH_MAX_BYTES = 64 * 1024;
35612
+ var QUEUED_BATCH_SEPARATOR = `
35613
+
35614
+ `;
35615
+ var QUEUED_BATCH_SEPARATOR_BYTES = Buffer.byteLength(QUEUED_BATCH_SEPARATOR, "utf8");
35611
35616
  function emptySemanticAssembler() {
35612
35617
  return { chunks: [], bytes: 0, truncated: false };
35613
35618
  }
@@ -35729,6 +35734,8 @@ class LogicalAgentSession {
35729
35734
  compacting = false;
35730
35735
  reviewing = false;
35731
35736
  steeringDeliveries = new Set;
35737
+ pendingSteers = [];
35738
+ pendingSteerFlushTurn;
35732
35739
  laneAdmissionTail = Promise.resolve();
35733
35740
  laneAdmissionPending = 0;
35734
35741
  toolBoundaryOpen = true;
@@ -36585,30 +36592,57 @@ class LogicalAgentSession {
36585
36592
  canFlushSafeBoundaryQueue() {
36586
36593
  return this.state === "working" && this.behavior.midTurnDelivery === "safe_boundary_queue" && this.toolBoundaryOpen && !this.toolBoundaryFlushDisabled && !this.compacting && !this.reviewing && this.activeTurn !== undefined && this.lane !== null && this.queued.length > 0 && this.queued[0].message.delivery !== "next_turn";
36587
36594
  }
36595
+ takeBatch(queue, getMessage, opts = {}) {
36596
+ const batch = [];
36597
+ let totalBytes = 0;
36598
+ while (queue.length > 0) {
36599
+ const next = queue[0];
36600
+ if (opts.predicate && !opts.predicate(next))
36601
+ break;
36602
+ const message = getMessage(next);
36603
+ if (opts.stopAtNextTurn && message.delivery === "next_turn")
36604
+ break;
36605
+ const nextBytes = Buffer.byteLength(message.text, "utf8");
36606
+ const projected = batch.length === 0 ? nextBytes : totalBytes + QUEUED_BATCH_SEPARATOR_BYTES + nextBytes;
36607
+ if (batch.length > 0 && projected > QUEUED_BATCH_MAX_BYTES)
36608
+ break;
36609
+ queue.shift();
36610
+ batch.push(next);
36611
+ totalBytes = projected;
36612
+ }
36613
+ return batch;
36614
+ }
36588
36615
  async drainSafeBoundaryQueue() {
36589
36616
  while (this.canFlushSafeBoundaryQueue()) {
36590
- const item = this.queued.shift();
36617
+ const items = this.takeBatch(this.queued, (entry) => entry.message, { stopAtNextTurn: true });
36618
+ if (items.length === 0)
36619
+ return;
36591
36620
  const activeTurn = this.activeTurn;
36592
- const delivery = { item, activeTurn, finalized: false };
36621
+ const delivery = { items, activeTurn, finalized: false };
36593
36622
  this.safeBoundaryDelivery = delivery;
36623
+ const messages = items.map((item) => item.message);
36624
+ const text = messages.map((message) => message.text).join(QUEUED_BATCH_SEPARATOR);
36594
36625
  try {
36595
- await this.sendLane(item.message.text, "busy", [item.message]);
36626
+ await this.sendLane(text, "busy", messages);
36596
36627
  } catch (error) {
36597
36628
  if (error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {
36598
- this.queued.unshift(item);
36629
+ this.queued.unshift(...items);
36599
36630
  this.toolBoundaryFlushDisabled = true;
36600
36631
  return;
36601
36632
  }
36602
36633
  if (!delivery.finalized) {
36603
- this.recordQueueDwell(item);
36604
36634
  delivery.finalized = true;
36605
- this.emit({
36606
- type: "command_failed",
36607
- scope: "input",
36608
- commandId: item.message.id,
36609
- turnId: activeTurn.turnId,
36610
- error: driverError("process", "delivery_failed", String(error), true)
36611
- });
36635
+ const failure = driverError("process", "delivery_failed", String(error), true);
36636
+ for (const item of items) {
36637
+ this.recordQueueDwell(item);
36638
+ this.emit({
36639
+ type: "command_failed",
36640
+ scope: "input",
36641
+ commandId: item.message.id,
36642
+ turnId: activeTurn.turnId,
36643
+ error: failure
36644
+ });
36645
+ }
36612
36646
  }
36613
36647
  continue;
36614
36648
  } finally {
@@ -36617,15 +36651,17 @@ class LogicalAgentSession {
36617
36651
  }
36618
36652
  if (delivery.finalized)
36619
36653
  continue;
36620
- this.recordQueueDwell(item);
36621
36654
  delivery.finalized = true;
36622
- activeTurn.commandIds.push(item.message.id);
36623
- this.emit({
36624
- type: "command_accepted",
36625
- commandId: item.message.id,
36626
- turnId: activeTurn.turnId,
36627
- delivery: "steer"
36628
- });
36655
+ for (const item of items) {
36656
+ this.recordQueueDwell(item);
36657
+ activeTurn.commandIds.push(item.message.id);
36658
+ this.emit({
36659
+ type: "command_accepted",
36660
+ commandId: item.message.id,
36661
+ turnId: activeTurn.turnId,
36662
+ delivery: "steer"
36663
+ });
36664
+ }
36629
36665
  }
36630
36666
  }
36631
36667
  failSafeBoundaryDelivery(category, code, message) {
@@ -36633,13 +36669,16 @@ class LogicalAgentSession {
36633
36669
  if (!delivery || delivery.finalized)
36634
36670
  return;
36635
36671
  delivery.finalized = true;
36636
- this.emit({
36637
- type: "command_failed",
36638
- scope: "input",
36639
- commandId: delivery.item.message.id,
36640
- turnId: delivery.activeTurn.turnId,
36641
- error: driverError(category, code, message)
36642
- });
36672
+ const error = driverError(category, code, message);
36673
+ for (const item of delivery.items) {
36674
+ this.emit({
36675
+ type: "command_failed",
36676
+ scope: "input",
36677
+ commandId: item.message.id,
36678
+ turnId: delivery.activeTurn.turnId,
36679
+ error
36680
+ });
36681
+ }
36643
36682
  }
36644
36683
  failTurnAdmission(category, code, message) {
36645
36684
  this.failTurnAdmissionWithError(driverError(category, code, message));
@@ -36696,9 +36735,12 @@ class LogicalAgentSession {
36696
36735
  async startNextQueued() {
36697
36736
  if (this.state !== "idle" || this.queued.length === 0 || this.processTurnEnded || this.retiringLane)
36698
36737
  return;
36699
- const item = this.queued.shift();
36700
- this.recordQueueDwell(item);
36701
- await this.startTurn([item.message], "prompt");
36738
+ const items = this.takeBatch(this.queued, (entry) => entry.message);
36739
+ if (items.length === 0)
36740
+ return;
36741
+ for (const item of items)
36742
+ this.recordQueueDwell(item);
36743
+ await this.startTurn(items.map((item) => item.message), "prompt");
36702
36744
  }
36703
36745
  onLaneError(error, physicalOwner, generation) {
36704
36746
  const message = error instanceof Error ? error.message : String(error);
@@ -36887,6 +36929,10 @@ class LogicalAgentSession {
36887
36929
  return reserved;
36888
36930
  }
36889
36931
  async deliverSteer(message, activeTurn) {
36932
+ let resolveReceipt;
36933
+ const settled = new Promise((resolve6) => {
36934
+ resolveReceipt = resolve6;
36935
+ });
36890
36936
  let rejectCancellation;
36891
36937
  const cancellation = new Promise((_resolve, reject) => {
36892
36938
  rejectCancellation = reject;
@@ -36895,40 +36941,17 @@ class LogicalAgentSession {
36895
36941
  message,
36896
36942
  activeTurn,
36897
36943
  finalized: false,
36944
+ resolve: resolveReceipt,
36898
36945
  cancellation,
36899
36946
  cancel(error) {
36900
36947
  rejectCancellation(error);
36901
36948
  }
36902
36949
  };
36903
36950
  this.steeringDeliveries.add(delivery);
36904
- const physical = this.enqueueLaneAdmission(async () => {
36905
- try {
36906
- if (delivery.finalized || this.activeTurn !== activeTurn) {
36907
- throw delivery.failure ?? driverError("cancelled", "turn_closed_before_command_acceptance", "Turn closed before command acceptance");
36908
- }
36909
- await this.sendLane(message.text, "busy", [message]);
36910
- if (delivery.finalized || this.activeTurn !== activeTurn) {
36911
- throw delivery.failure ?? driverError("cancelled", "turn_closed_before_command_acceptance", "Turn closed before command acceptance");
36912
- }
36913
- delivery.finalized = true;
36914
- activeTurn.commandIds.push(message.id);
36915
- this.emit({ type: "command_accepted", commandId: message.id, turnId: activeTurn.turnId, delivery: "steer" });
36916
- return { status: "accepted", delivery: "steer", commandId: message.id, turnId: activeTurn.turnId };
36917
- } catch (error) {
36918
- if (!delivery.finalized && this.activeTurn === activeTurn && error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {
36919
- delivery.finalized = true;
36920
- return this.queue(message, "runtime_busy");
36921
- }
36922
- const failure = delivery.failure ?? (typeof error === "object" && error !== null && "category" in error ? error : driverError("process", "delivery_failed", String(error), true));
36923
- if (!delivery.finalized) {
36924
- delivery.finalized = true;
36925
- this.emit({ type: "command_failed", scope: "input", commandId: message.id, turnId: activeTurn.turnId, error: failure });
36926
- }
36927
- return { status: "rejected", reason: "runtime_unavailable", error: failure };
36928
- }
36929
- });
36951
+ this.pendingSteers.push(delivery);
36952
+ this.scheduleSteerFlush(activeTurn);
36930
36953
  try {
36931
- return await Promise.race([physical, cancellation]);
36954
+ return await Promise.race([settled, cancellation]);
36932
36955
  } catch (error) {
36933
36956
  const failure = delivery.failure ?? (typeof error === "object" && error !== null && "category" in error ? error : driverError("process", "delivery_failed", String(error), true));
36934
36957
  if (!delivery.finalized) {
@@ -36940,6 +36963,71 @@ class LogicalAgentSession {
36940
36963
  this.steeringDeliveries.delete(delivery);
36941
36964
  }
36942
36965
  }
36966
+ scheduleSteerFlush(activeTurn) {
36967
+ if (this.pendingSteerFlushTurn === activeTurn)
36968
+ return;
36969
+ this.pendingSteerFlushTurn = activeTurn;
36970
+ this.enqueueLaneAdmission(async () => {
36971
+ if (this.pendingSteerFlushTurn === activeTurn)
36972
+ this.pendingSteerFlushTurn = undefined;
36973
+ while (this.pendingSteers.length > 0 && this.pendingSteers[0].finalized) {
36974
+ this.pendingSteers.shift();
36975
+ }
36976
+ const batch = this.takeBatch(this.pendingSteers, (entry) => entry.message, { predicate: (entry) => !entry.finalized && entry.activeTurn === activeTurn });
36977
+ if (batch.length === 0)
36978
+ return;
36979
+ let deferredToQueue = false;
36980
+ try {
36981
+ if (this.activeTurn !== activeTurn || batch.every((entry) => entry.finalized)) {
36982
+ throw driverError("cancelled", "turn_closed_before_command_acceptance", "Turn closed before command acceptance");
36983
+ }
36984
+ const messages = batch.map((entry) => entry.message);
36985
+ const text = messages.map((msg) => msg.text).join(QUEUED_BATCH_SEPARATOR);
36986
+ await this.sendLane(text, "busy", messages);
36987
+ if (this.activeTurn !== activeTurn) {
36988
+ throw driverError("cancelled", "turn_closed_before_command_acceptance", "Turn closed before command acceptance");
36989
+ }
36990
+ for (const entry of batch) {
36991
+ if (entry.finalized)
36992
+ continue;
36993
+ entry.finalized = true;
36994
+ activeTurn.commandIds.push(entry.message.id);
36995
+ this.emit({ type: "command_accepted", commandId: entry.message.id, turnId: activeTurn.turnId, delivery: "steer" });
36996
+ entry.resolve({ status: "accepted", delivery: "steer", commandId: entry.message.id, turnId: activeTurn.turnId });
36997
+ }
36998
+ } catch (error) {
36999
+ if (this.activeTurn === activeTurn && error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {
37000
+ deferredToQueue = true;
37001
+ for (const entry of batch) {
37002
+ if (entry.finalized)
37003
+ continue;
37004
+ entry.finalized = true;
37005
+ entry.resolve(this.queue(entry.message, "runtime_busy"));
37006
+ }
37007
+ while (this.pendingSteers.length > 0 && this.pendingSteers[0].activeTurn === activeTurn) {
37008
+ const remaining = this.pendingSteers.shift();
37009
+ if (remaining.finalized)
37010
+ continue;
37011
+ remaining.finalized = true;
37012
+ remaining.resolve(this.queue(remaining.message, "runtime_busy"));
37013
+ }
37014
+ return;
37015
+ }
37016
+ for (const entry of batch) {
37017
+ const failure = entry.failure ?? (typeof error === "object" && error !== null && "category" in error ? error : driverError("process", "delivery_failed", String(error), true));
37018
+ if (!entry.finalized) {
37019
+ entry.finalized = true;
37020
+ this.emit({ type: "command_failed", scope: "input", commandId: entry.message.id, turnId: activeTurn.turnId, error: failure });
37021
+ }
37022
+ entry.resolve({ status: "rejected", reason: "runtime_unavailable", error: failure });
37023
+ }
37024
+ } finally {
37025
+ if (!deferredToQueue && this.activeTurn === activeTurn && this.pendingSteers.some((entry) => !entry.finalized && entry.activeTurn === activeTurn)) {
37026
+ this.scheduleSteerFlush(activeTurn);
37027
+ }
37028
+ }
37029
+ });
37030
+ }
36943
37031
  failSteeringDeliveries(category, code, message, activeTurn) {
36944
37032
  const error = driverError(category, code, message);
36945
37033
  for (const delivery of this.steeringDeliveries) {
@@ -60109,12 +60197,16 @@ var CommunityAgentSendRequestSchema = exports_external.object({
60109
60197
  channel: exports_external.string().min(1),
60110
60198
  content: CommunityAgentMessageContentSchema,
60111
60199
  question: DecisionCardInputSchema.optional(),
60200
+ page: exports_external.strictObject({ id: exports_external.string().regex(/^page_[A-Za-z0-9_-]+$/).max(128) }).optional(),
60112
60201
  attachments: exports_external.array(exports_external.string().min(1)).max(MAX_ATTACHMENTS_PER_MESSAGE).default([]),
60113
60202
  seenUpToSeq: CommunityAgentSeqSchema.optional(),
60114
60203
  replyToSeq: CommunityAgentPositiveSeqSchema.optional(),
60115
60204
  force: exports_external.boolean().optional(),
60116
60205
  nonce: exports_external.string().min(1).max(128).optional()
60117
60206
  }).superRefine((d, ctx) => {
60207
+ if (d.page && (!d.nonce || d.question)) {
60208
+ ctx.addIssue({ code: "custom", path: ["page"], message: "Page publication requires a nonce and cannot include a decision card" });
60209
+ }
60118
60210
  if (d.question !== undefined) {
60119
60211
  if (d.attachments.length > 0) {
60120
60212
  ctx.addIssue({
@@ -60227,7 +60319,7 @@ var AuditLogTextPayloadSchema = exports_external.object({
60227
60319
  var AuditLogTurnInterruptPayloadSchema = exports_external.object({
60228
60320
  status: exports_external.literal("accepted")
60229
60321
  });
60230
- var AuditLogWakeTriggerPayloadSchema = exports_external.object({
60322
+ var AuditLogChatWakeTriggerPayloadSchema = exports_external.object({
60231
60323
  messageId: exports_external.string().min(1),
60232
60324
  channel: exports_external.string().min(1),
60233
60325
  seq: CommunityAgentPositiveSeqSchema,
@@ -60235,6 +60327,27 @@ var AuditLogWakeTriggerPayloadSchema = exports_external.object({
60235
60327
  senderHandle: exports_external.string().min(1),
60236
60328
  reason: exports_external.enum(["unread", "mention"])
60237
60329
  });
60330
+ var AuditLogWebhookWakeTriggerPayloadSchema = exports_external.object({
60331
+ reason: exports_external.literal("webhook"),
60332
+ triggerId: exports_external.string().min(1),
60333
+ triggerName: exports_external.string().min(1).max(120),
60334
+ provider: exports_external.string().min(1).max(64),
60335
+ eventType: exports_external.string().min(1).max(120),
60336
+ summary: exports_external.string().min(1).max(240)
60337
+ });
60338
+ var AuditLogScheduleWakeTriggerPayloadSchema = exports_external.object({
60339
+ reason: exports_external.literal("schedule"),
60340
+ scheduleId: exports_external.string().min(1),
60341
+ runId: exports_external.string().min(1),
60342
+ title: exports_external.string().min(1).max(200),
60343
+ channel: exports_external.string().min(1).optional(),
60344
+ seq: CommunityAgentPositiveSeqSchema.optional()
60345
+ });
60346
+ var AuditLogWakeTriggerPayloadSchema = exports_external.union([
60347
+ AuditLogChatWakeTriggerPayloadSchema,
60348
+ AuditLogWebhookWakeTriggerPayloadSchema,
60349
+ AuditLogScheduleWakeTriggerPayloadSchema
60350
+ ]);
60238
60351
  var AuditLogSessionResetPayloadSchema = exports_external.object({
60239
60352
  trigger: exports_external.enum(["single", "reset_all", "idle_timeout"])
60240
60353
  });
@@ -60961,42 +61074,6 @@ var BillingPortalRequestSchema = exports_external.strictObject({
60961
61074
  var BillingRedirectResponseSchema = exports_external.object({
60962
61075
  url: exports_external.url()
60963
61076
  });
60964
- // ../shared/src/utils/day-key.ts
60965
- function utcDayKey(now) {
60966
- const d = now instanceof Date ? now : new Date(now);
60967
- return d.toISOString().slice(0, 10);
60968
- }
60969
- function calendarDayKeyDaysAgo(day, days) {
60970
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
60971
- if (!match)
60972
- throw new RangeError("invalid calendar day key");
60973
- const year = Number(match[1]);
60974
- const month = Number(match[2]);
60975
- const date5 = Number(match[3]);
60976
- const parsed = new Date(Date.UTC(year, month - 1, date5));
60977
- if (parsed.getUTCFullYear() !== year || parsed.getUTCMonth() !== month - 1 || parsed.getUTCDate() !== date5) {
60978
- throw new RangeError("invalid calendar day key");
60979
- }
60980
- parsed.setUTCDate(parsed.getUTCDate() - days);
60981
- return utcDayKey(parsed);
60982
- }
60983
- function dayKeyInTimeZone(now, timeZone) {
60984
- const date5 = now instanceof Date ? now : new Date(now);
60985
- const parts = new Intl.DateTimeFormat("en-US", {
60986
- timeZone,
60987
- year: "numeric",
60988
- month: "2-digit",
60989
- day: "2-digit"
60990
- }).formatToParts(date5);
60991
- const values = new Map(parts.map((part) => [part.type, part.value]));
60992
- const year = values.get("year");
60993
- const month = values.get("month");
60994
- const day = values.get("day");
60995
- if (!year || !month || !day)
60996
- throw new RangeError("unable to format calendar day key");
60997
- return `${year}-${month}-${day}`;
60998
- }
60999
-
61000
61077
  // ../../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
61001
61078
  var entityKind = Symbol.for("drizzle:entityKind");
61002
61079
  var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
@@ -61798,8 +61875,6 @@ __export(exports_community_schema, {
61798
61875
  communityChannel: () => communityChannel,
61799
61876
  communityCategory: () => communityCategory,
61800
61877
  communityBotDailyTokenUsage: () => communityBotDailyTokenUsage,
61801
- communityBotDailyActivity: () => communityBotDailyActivity,
61802
- communityBotApprovalRequest: () => communityBotApprovalRequest,
61803
61878
  communityBotActivityEvent: () => communityBotActivityEvent,
61804
61879
  communityAttachment: () => communityAttachment
61805
61880
  });
@@ -62950,24 +63025,6 @@ var communityPushDevice = sqliteTable("community_push_device", {
62950
63025
  check2("ck_push_device_android_environment", sql`${t.platform} = 'ios' or ${t.providerEnvironment} = 'production'`),
62951
63026
  check2("ck_push_device_token_hash", sql`length(${t.providerTokenHash}) = 64 and ${t.providerTokenHash} not glob '*[^0-9a-f]*'`)
62952
63027
  ]);
62953
- var communityBotApprovalRequest = sqliteTable("community_bot_approval_request", {
62954
- id: text2("id").primaryKey().$defaultFn(() => "bar_" + nanoid3()),
62955
- botId: text2("bot_id").notNull().references(() => user.id, { onDelete: "cascade" }),
62956
- kind: text2("kind").notNull(),
62957
- serverId: text2("server_id").references(() => communityServer.id, {
62958
- onDelete: "cascade"
62959
- }),
62960
- requestedByUserId: text2("requested_by_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
62961
- dmMessageId: text2("dm_message_id").notNull().references(() => communityMessage.id, { onDelete: "cascade" }),
62962
- status: text2("status").notNull().default("pending"),
62963
- createdAt: text2("created_at").notNull().$defaultFn(() => new Date().toISOString()),
62964
- resolvedAt: text2("resolved_at")
62965
- }, (t) => [
62966
- index("idx_community_bot_approval_bot").on(t.botId, t.status),
62967
- index("idx_community_bot_approval_server_lookup").on(t.serverId),
62968
- index("idx_community_bot_approval_requester_lookup").on(t.requestedByUserId),
62969
- index("idx_community_bot_approval_message_lookup").on(t.dmMessageId)
62970
- ]);
62971
63028
  var communityBotActivityEvent = sqliteTable("community_bot_activity_event", {
62972
63029
  id: text2("id").primaryKey().$defaultFn(() => "bae_" + nanoid3()),
62973
63030
  botId: text2("bot_id").notNull().references(() => user.id, { onDelete: "cascade" }),
@@ -62979,12 +63036,6 @@ var communityBotActivityEvent = sqliteTable("community_bot_activity_event", {
62979
63036
  }, (t) => [
62980
63037
  index("idx_bot_activity_event_bot_created").on(t.botId, t.createdAt, t.id)
62981
63038
  ]);
62982
- var communityBotDailyActivity = sqliteTable("community_bot_daily_activity", {
62983
- botId: text2("bot_id").notNull().references(() => user.id, { onDelete: "cascade" }),
62984
- day: text2("day").notNull(),
62985
- handledCount: integer2("handled_count").notNull().default(0),
62986
- sentCount: integer2("sent_count").notNull().default(0)
62987
- }, (t) => [primaryKey({ columns: [t.botId, t.day] })]);
62988
63039
  var communityBotDailyTokenUsage = sqliteTable("community_bot_daily_token_usage", {
62989
63040
  botId: text2("bot_id").notNull().references(() => user.id, { onDelete: "cascade" }),
62990
63041
  day: text2("day").notNull(),
@@ -63410,6 +63461,35 @@ var NOTIFY_CONFLICT_TARGET = [
63410
63461
  communityChannelMember.relation
63411
63462
  ];
63412
63463
 
63464
+ // ../shared/src/community-page.ts
63465
+ var pageId = exports_external.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/);
63466
+ var ALOOK_PAGE_EMBED_KIND = "alook_page";
63467
+ var AlookPageEmbedSchema = exports_external.strictObject({
63468
+ kind: exports_external.literal(ALOOK_PAGE_EMBED_KIND),
63469
+ id: pageId,
63470
+ type: exports_external.string().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/),
63471
+ title: exports_external.string().trim().min(1).max(256)
63472
+ });
63473
+ var AlookPageSourceSchema = exports_external.strictObject({ sourceMessageId: exports_external.string().min(1).max(128).optional() });
63474
+ var AlookPageCommentSchema = AlookPageSourceSchema.extend({
63475
+ text: exports_external.string().trim().min(1).max(8000),
63476
+ location: exports_external.string().trim().min(1).max(1024).optional()
63477
+ });
63478
+ var AlookPageViewerSchema = exports_external.strictObject({
63479
+ embedUrl: exports_external.url(),
63480
+ allowedOrigins: exports_external.array(exports_external.url()).min(1).max(2),
63481
+ expiresAt: exports_external.iso.datetime()
63482
+ });
63483
+ var artifactPath = exports_external.string().min(1).max(512).refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").some((part) => part === ".." || part === "." || part === ""), "A relative artifact path is required");
63484
+ var AlookPageOperationSchema = exports_external.discriminatedUnion("kind", [
63485
+ exports_external.strictObject({ kind: exports_external.literal("actions") }),
63486
+ exports_external.strictObject({ kind: exports_external.literal("manifest") }),
63487
+ exports_external.strictObject({ kind: exports_external.literal("read"), path: artifactPath }),
63488
+ exports_external.strictObject({ kind: exports_external.literal("write"), writes: exports_external.array(exports_external.strictObject({ path: artifactPath, content: exports_external.string().max(1398104).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((value) => value.length * 3 / 4 - (value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0) <= 1024 * 1024).nullable(), if_match: exports_external.string().max(256).nullable() })).min(1).max(16) }),
63489
+ exports_external.strictObject({ kind: exports_external.literal("action"), name: exports_external.string().min(1).max(128), args: exports_external.record(exports_external.string(), exports_external.unknown()) })
63490
+ ]);
63491
+ var PAGE_COVER_MAX_BYTES = 2 * 1024 * 1024;
63492
+
63413
63493
  // ../shared/src/db/resilience.ts
63414
63494
  var defaultLogger = createLogger({ service: "d1-resilience" });
63415
63495
 
@@ -64069,6 +64149,30 @@ var communityBotFeedback = sqliteTable("community_bot_feedback", {
64069
64149
  check2("bot_feedback_text_bytes", sql`length(cast(${t.text} as blob)) between 1 and ${sql.raw(String(BOT_FEEDBACK_MAX_BYTES))}`)
64070
64150
  ]);
64071
64151
 
64152
+ // ../shared/src/db/page-schema.ts
64153
+ var exports_page_schema = {};
64154
+ __export(exports_page_schema, {
64155
+ communityPage: () => communityPage,
64156
+ communityMessagePage: () => communityMessagePage
64157
+ });
64158
+ var communityPage = sqliteTable("community_page", {
64159
+ id: text2("id").primaryKey(),
64160
+ artifactId: text2("artifact_id").notNull(),
64161
+ archiveAttachmentId: text2("archive_attachment_id").notNull().references(() => communityAttachment.id, { onDelete: "restrict" }),
64162
+ botId: text2("bot_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64163
+ type: text2("type").notNull(),
64164
+ title: text2("title").notNull(),
64165
+ createdAt: text2("created_at").notNull()
64166
+ }, (t) => [
64167
+ uniqueIndex("uq_community_page_artifact").on(t.artifactId),
64168
+ uniqueIndex("uq_community_page_archive").on(t.archiveAttachmentId),
64169
+ index("idx_community_page_bot_id").on(t.botId, t.createdAt, t.id)
64170
+ ]);
64171
+ var communityMessagePage = sqliteTable("community_message_page", {
64172
+ messageId: text2("message_id").notNull().references(() => communityMessage.id, { onDelete: "cascade" }),
64173
+ pageId: text2("page_id").notNull().references(() => communityPage.id, { onDelete: "cascade" })
64174
+ }, (t) => [primaryKey({ columns: [t.messageId, t.pageId] }), index("idx_community_message_page_page").on(t.pageId, t.messageId)]);
64175
+
64072
64176
  // ../shared/src/db/community-schedule-schema.ts
64073
64177
  var exports_community_schedule_schema = {};
64074
64178
  __export(exports_community_schedule_schema, {
@@ -64171,7 +64275,7 @@ var communityBotWebhook = sqliteTable("community_bot_webhook", {
64171
64275
  ]);
64172
64276
 
64173
64277
  // ../shared/src/db/index.ts
64174
- var allSchema = { ...exports_schema, ...exports_community_schema, ...exports_community_machine_schema, ...exports_product_plan_schema, ...exports_billing_schema, ...exports_community_funnel_analytics_schema, ...exports_bot_creation_schema, ...exports_automation_schema, ...exports_feedback_schema, ...exports_community_schedule_schema, ...exports_community_bot_private_inbox_schema, ...exports_community_bot_webhook_schema };
64278
+ 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_page_schema, ...exports_community_schedule_schema, ...exports_community_bot_private_inbox_schema, ...exports_community_bot_webhook_schema };
64175
64279
  // ../shared/src/db/queries/native-oauth.ts
64176
64280
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
64177
64281
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
@@ -64200,6 +64304,9 @@ var metadataProjection = {
64200
64304
  };
64201
64305
  // ../shared/src/db/queries/community/diagnostic-report.ts
64202
64306
  var diagnosticOwner = alias(user, "diagnostic_owner");
64307
+ // ../shared/src/db/queries/community/page.ts
64308
+ var channelColumns = { id: communityChannel.id, type: communityChannel.type, serverId: communityChannel.serverId, parentChannelId: communityChannel.parentChannelId };
64309
+ var viewerTicket = exports_external.strictObject({ userId: exports_external.string().min(1), pageId: exports_external.string().min(1), origin: exports_external.url(), sourceMessageId: exports_external.string().min(1) });
64203
64310
  // ../shared/src/schedule.ts
64204
64311
  var SCHEDULE_TITLE_MAX_LENGTH = 160;
64205
64312
  var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
@@ -64419,6 +64526,41 @@ var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF
64419
64526
  var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
64420
64527
  // ../shared/src/utils/email.ts
64421
64528
  var DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`;
64529
+ // ../shared/src/utils/day-key.ts
64530
+ function utcDayKey(now) {
64531
+ const d = now instanceof Date ? now : new Date(now);
64532
+ return d.toISOString().slice(0, 10);
64533
+ }
64534
+ function calendarDayKeyDaysAgo(day, days) {
64535
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
64536
+ if (!match)
64537
+ throw new RangeError("invalid calendar day key");
64538
+ const year = Number(match[1]);
64539
+ const month = Number(match[2]);
64540
+ const date5 = Number(match[3]);
64541
+ const parsed = new Date(Date.UTC(year, month - 1, date5));
64542
+ if (parsed.getUTCFullYear() !== year || parsed.getUTCMonth() !== month - 1 || parsed.getUTCDate() !== date5) {
64543
+ throw new RangeError("invalid calendar day key");
64544
+ }
64545
+ parsed.setUTCDate(parsed.getUTCDate() - days);
64546
+ return utcDayKey(parsed);
64547
+ }
64548
+ function dayKeyInTimeZone(now, timeZone) {
64549
+ const date5 = now instanceof Date ? now : new Date(now);
64550
+ const parts = new Intl.DateTimeFormat("en-US", {
64551
+ timeZone,
64552
+ year: "numeric",
64553
+ month: "2-digit",
64554
+ day: "2-digit"
64555
+ }).formatToParts(date5);
64556
+ const values = new Map(parts.map((part) => [part.type, part.value]));
64557
+ const year = values.get("year");
64558
+ const month = values.get("month");
64559
+ const day = values.get("day");
64560
+ if (!year || !month || !day)
64561
+ throw new RangeError("unable to format calendar day key");
64562
+ return `${year}-${month}-${day}`;
64563
+ }
64422
64564
  // ../shared/src/lib/safe-redirect.ts
64423
64565
  var MAX_REDIRECT_BYTES = 2048;
64424
64566
  var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
@@ -78861,6 +79003,7 @@ function messagingSection() {
78861
79003
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
78862
79004
  `- Inline HTML: upload a self-contained UTF-8 \`<path>.html\` file with \`${CLI} message attachment upload --file <path>.html\`. ` + "Inline CSS and JavaScript in the file; do not depend on local paths on the sender's computer. " + "Include the returned ID with `--attachment <id>` when sending; see Message formatting for its inline reference syntax. " + "Use the Alook theme CSS variables injected by the host on `:root`: " + "`--background`, `--foreground`, `--card`, `--card-foreground`, `--popover`, `--popover-foreground`, " + "`--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`, `--muted`, `--muted-foreground`, " + "`--accent`, `--accent-foreground`, `--border`, `--input`, `--ring`, `--destructive`, `--warning`, " + "`--radius`, `--font-sans`, and `--font-mono`. Use their values directly with `var(...)`; " + "do not hardcode page theme colors to one light or dark scheme. " + "Do not add background colors to `html`, `body`, or the outermost element. Do not add an outer card, " + "border, banner title, or side padding. This rule takes priority over other page-background authoring rules. " + "An internal box that needs a background uses a theme variable, 16px padding, and `var(--radius)` corners. " + "Adapt to the available width and different screen sizes; do not hardcode a desktop page width. " + "Give charts fixed pixel heights. Let content set the page height. Do not use `vh`, `dvh`, `svh`, or `lvh`, " + "and do not set `height:100%` on `html` or `body`. The current preview validator rejects those viewport units; " + "percentage heights on the document roots can cause a measurement loop. " + "Alook measures the frame height automatically in CSS pixels, currently 80–2000px inline. " + "Sending a message requires no height parameter. Keep the original HTML within the current 2 MiB preview limit.",
78863
79005
  "- Reuse files: to forward an attachment or send the same file again, pass its existing ID with `--attachment <id>`. " + "Do not download and upload it again. Reuse works across channels, DMs, and threads while you can still read the file. " + "Upload only a new or changed file.",
79006
+ "- Alook Page: for living collaborative artifacts or apps that need persisted cloud state (not one-off inline HTML visuals without saved state), read `@alook-page.md`.",
78864
79007
  `- Cite a specific message: add \`--reply "#37"\` — \`--reply\` takes the \`#N\` seq ` + "(within `--target`) of the message you're answering.",
78865
79008
  "",
78866
79009
  "Write every message body in the stdin/heredoc block; never place it directly on the command line.",
@@ -78986,7 +79129,7 @@ function cliCommandsSection() {
78986
79129
  "### Messaging",
78987
79130
  "",
78988
79131
  `1. \`${CLI} inbox pull\` — fetch unread messages and advance their read waterlines.`,
78989
- `2. \`${CLI} message send --target <ref> --remind-after <0|Nm|Nh> [--ask] --stdin\` — Send to a ` + `channel, DM, or thread. ` + `For plain messages, pass up to 1 KiB of UTF-8 text through stdin and use \`--attachment <id>\` for files (repeatable, order matters). ` + `\`--remind-after\` accepts \`0\` or a whole-number duration from \`1m\` to \`24h\`.`,
79132
+ `2. \`${CLI} message send --target <ref> --remind-after <0|Nm|Nh> [--ask] [--page <page_id>] --stdin\` — Send to a ` + `channel, DM, or thread. ` + `For plain messages, pass up to 1 KiB of UTF-8 text through stdin and use \`--attachment <id>\` for files (repeatable, order matters). ` + `\`--remind-after\` accepts \`0\` or a whole-number duration from \`1m\` to \`24h\`.`,
78990
79133
  `3. \`${CLI} message attachment upload --file <path>\` — upload a local file and get a reusable attachment ID. Supports Markdown and inline HTML; see Communication for formatting.`,
78991
79134
  `4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download an attachment you can read, including your own unsent uploads.`,
78992
79135
  `5. \`${CLI} message property set --target <full-message-ref> --json <json>\` — add a supported property value to a message.`,
@@ -79044,6 +79187,12 @@ function cliCommandsSection() {
79044
79187
  `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack]\` — update a task, or pass \`--ack\` after finishing the triggered run to mark it completed.`,
79045
79188
  `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
79046
79189
  "",
79190
+ "### Pages",
79191
+ "",
79192
+ "Use an Alook Page only when people need a **persistent, living collaborative artifact or app** (documents, decks, spreadsheets, whiteboards, design boards, dashboards, motion compositions, design systems, or stateful custom apps) that stays editable and reusable across channels after chat moves on. For one-off visuals or ephemeral client-only snippets without saved state, use inline HTML; for read-only prose or logs, use plain text or a Markdown attachment.",
79193
+ "",
79194
+ "Before creating, previewing, uploading, sharing, editing, or deleting any Page, read `@alook-page.md` for all artifact types, authoring workflow, and `$ALOOK_CLI page` commands.",
79195
+ "",
79047
79196
  "### Settings",
79048
79197
  "",
79049
79198
  `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.`,
@@ -80206,8 +80355,8 @@ class AgentProcessManager {
80206
80355
  return { deliveryPhase };
80207
80356
  return { deliveryPhase, ...snapshotDiagnostics.metrics };
80208
80357
  }
80209
- withFooter(text8) {
80210
- return this.opts.wakePromptFooter ? `${text8}
80358
+ withFooter(text8, includeWakeFooter = false) {
80359
+ return includeWakeFooter && this.opts.wakePromptFooter ? `${text8}
80211
80360
 
80212
80361
  ${this.opts.wakePromptFooter}` : text8;
80213
80362
  }
@@ -80220,7 +80369,7 @@ ${this.opts.wakePromptFooter}` : text8;
80220
80369
  preparedInput: message.preparedInput ?? {
80221
80370
  id: message.id,
80222
80371
  kind: "user",
80223
- text: this.stampNow(this.withFooter(message.text)),
80372
+ text: this.stampNow(this.withFooter(message.text, message.includeWakeFooter)),
80224
80373
  sequence: message.seq
80225
80374
  }
80226
80375
  };
@@ -80517,7 +80666,7 @@ ${this.opts.wakePromptFooter}` : text8;
80517
80666
  throw new Error(`AgentProcessManager: spawn for ${agentId} has no command`);
80518
80667
  this.dispatch({ type: "queue_delivery", agentId, messages: pending });
80519
80668
  const first = this.prepareDelivery(initial);
80520
- const prompt = this.withFooter(first.text);
80669
+ const prompt = this.withFooter(first.text, first.includeWakeFooter);
80521
80670
  const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));
80522
80671
  this.liveBackendIds.set(agentId, driver.id);
80523
80672
  const base = this.opts.baseContextFor(agentId);
@@ -81430,7 +81579,8 @@ class AgentRouter {
81430
81579
  const producedEffect = this.opts.manager.deliver(cmd.agentId, {
81431
81580
  id: `${cmd.agentId}:wake:${cmd.unreadNotice.channel}:${cmd.unreadNotice.latestSeq}:admission:${this.nextWakeAdmissionOrdinal++}`,
81432
81581
  seq: cmd.unreadNotice.latestSeq,
81433
- text: text8
81582
+ text: text8,
81583
+ includeWakeFooter: true
81434
81584
  });
81435
81585
  if (producedEffect === false && beforeStatus === "running") {
81436
81586
  this.log.info("agent:wake produced no effect (coalesced onto running agent)", {
@@ -81748,9 +81898,19 @@ var communityProxyRoutes = {
81748
81898
  };
81749
81899
  var SCHEDULE_EVENTS_PROXY_PATH_RE = /^\/api\/community\/schedule\/events(?:\/[^/]+)?$/;
81750
81900
  function isCanonicalCommunityProxyPath(pathname) {
81751
- return pathname === "/api/community/platform/feedback" || SCHEDULE_EVENTS_PROXY_PATH_RE.test(pathname) || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81901
+ return pathname === "/api/community/platform/feedback" || SCHEDULE_EVENTS_PROXY_PATH_RE.test(pathname) || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines|pages)(\/|$)/.test(pathname);
81752
81902
  }
81753
81903
  function resolveProxyCapability(method, pathname) {
81904
+ if (/^\/api\/community\/pages\/[^/]+\/cover$/.test(pathname) && method === "PUT")
81905
+ return "attach";
81906
+ if (pathname === "/api/community/pages" && method === "GET")
81907
+ return "read";
81908
+ if (/^\/api\/community\/pages\/[^/]+$/.test(pathname) && method === "DELETE")
81909
+ return "send";
81910
+ if (pathname === "/api/community/pages" && method === "POST")
81911
+ return "attach";
81912
+ if (/^\/api\/community\/pages\/[^/]+\/operations$/.test(pathname) && method === "POST")
81913
+ return "send";
81754
81914
  if (pathname === "/api/community/platform/feedback" && method === "POST")
81755
81915
  return "send";
81756
81916
  if (pathname.startsWith("/api/community/machines"))
@@ -84386,7 +84546,7 @@ class PiiStore {
84386
84546
  }
84387
84547
 
84388
84548
  // src/daemon/createDaemon.ts
84389
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync9 } from "node:fs";
84549
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync10 } from "node:fs";
84390
84550
 
84391
84551
  // src/util/rotatingFileSink.ts
84392
84552
  import {
@@ -87027,6 +87187,81 @@ function createDaemonAgentDriverHost(ctx, onRawLine, onRawStderr) {
87027
87187
  };
87028
87188
  }
87029
87189
 
87190
+ // src/drivers/alookPageGuide.ts
87191
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync11 } from "node:fs";
87192
+ import { join as join25 } from "node:path";
87193
+ var ALOOK_PAGE_GUIDE_FILENAME = "alook-page.md";
87194
+ var ALOOK_PAGE_GUIDE_CONTENT = [
87195
+ "# Alook Page Guide",
87196
+ "",
87197
+ "Use this guide whenever you create, preview, upload, share, edit, or delete an Alook Page.",
87198
+ "",
87199
+ "## Choosing the right surface",
87200
+ "",
87201
+ "| Surface | Use when | State & collaboration |",
87202
+ "|---|---|---|",
87203
+ "| Plain text / `.md` attachment | Plans, reviews, logs, summaries, code diffs | Read-only prose in chat |",
87204
+ "| Inline HTML (`[alook-html-preview](id)`) | One-off charts, diagrams, sequence flows, UI mockups, or client-only interactive snippets | **Ephemeral** — no persisted cloud state |",
87205
+ "| **Alook Page** | Living documents, decks, spreadsheets, whiteboards, design boards, dashboards, or custom apps that stay editable over time | **Persistent cloud state** — collaborative editing, reusable across channels |",
87206
+ "",
87207
+ "## Artifact types",
87208
+ "",
87209
+ "Pick a built-in collaborative editor whenever it fits; use `page` only when you need a custom HTML/CSS/JS app.",
87210
+ "",
87211
+ "| `type` | Purpose |",
87212
+ "|---|---|",
87213
+ "| `docs` | Multi-tab collaborative rich-text documents (specs, PRDs, briefs, meeting notes) |",
87214
+ "| `slides` | Collaborative slide decks and presentations |",
87215
+ "| `sheets` | Spreadsheets with formulas and tabular modeling |",
87216
+ "| `whiteboard` | Infinite-canvas whiteboards, architecture diagrams, brainstorming |",
87217
+ "| `design` | Vector and UI layout design boards |",
87218
+ "| `data` | Live data dashboards and interactive metric reports backed by datasets |",
87219
+ "| `motion` | Timeline motion graphics and short video compositions |",
87220
+ "| `design-system` | Brand and UI design systems (colors, typography, component tokens) |",
87221
+ "| `page` | Custom stateful multi-file HTML/CSS/JS interactive web app (requires root `.artifact.json` + `index.html`) |",
87222
+ "",
87223
+ "## CLI commands",
87224
+ "",
87225
+ "### Local authoring, visual check, and upload",
87226
+ "",
87227
+ "1. `$ALOOK_CLI page guide [--type <type>] [--ref <file>]` — ensure the shared local Open Artifact runtime (`~/.alook/page-runtime/`) and read the official `SKILL.md` / `reference/*.md` authoring spec for any of the 9 types. Always read the target type's guide before authoring a built-in artifact.",
87228
+ "2. `$ALOOK_CLI page local <command> [args...]` — run native local Open Artifact authoring and validation commands (`create`, `update`, `read`, `batch`, `write-db`, `read-db`, `check`, `generate`, `upload`, `info`) on your local artifact directory; forwards piped stdin (e.g. `- <<'EOF'`) and all upstream flags verbatim.",
87229
+ "3. `$ALOOK_CLI page preview --dir <dir> --out <img.png>` — render your local artifact directory (all 9 types) at 16:10, save a screenshot to `--out` for visual inspection before upload, and automatically stop the temporary browser and local server on exit.",
87230
+ "4. `$ALOOK_CLI page upload --dir <dir> [--cover <img-path>]` — validate and auto-zip the local directory (auto-detects built-in markers like `doc/doc.json`, `sheet/sheet.json`, `project/deck.json`, `db/board/meta.json` or root `.artifact.json`; generic `page` requires `.artifact.json` + `index.html`; auto-excludes `.git`, `node_modules`, `.DS_Store`, `_agent`; rejects symlinks; limits: 16 MiB compressed, 32 MiB unpacked, 2,000 files), capture its 16:10 homepage cover locally before any network call (or upload `--cover <img-path>`, PNG/JPEG/WebP, ≤ 2 MiB), and return its reusable `page_id`.",
87231
+ "",
87232
+ "### Sharing, listing, live editing, and deleting cloud Pages",
87233
+ "",
87234
+ "5. `$ALOOK_CLI message send --target <ref> --page <page_id> --remind-after <0|Nm|Nh> --stdin` — attach or forward an uploaded `page_id` across channels without re-uploading (all linked cards share one live cloud Page; reader comments return to the opening conversation).",
87235
+ "6. `$ALOOK_CLI page list [--limit <1..100>] [--cursor <cursor>]` — list Pages created by this bot (including unused uploads) with `total` and each Page's `messageCount`.",
87236
+ '7. `$ALOOK_CLI page --id <id> --stdin [--out <path>]` — read or live-edit an accessible cloud Page via JSON on stdin: `{"kind":"manifest"}`, `{"kind":"read","path":"..."}` (use `--out` to write locally), `{"kind":"write","writes":[{"path":"...","content":"<base64>","if_match":"<etag>"}]}` (use JSON `null` for `if_match` when creating a new file), `{"kind":"actions"}` (inspect native editor action schemas), or `{"kind":"action","name":"...","args":{...}}`.',
87237
+ "8. `$ALOOK_CLI page delete --id <id>` — permanently delete a Page created by this bot, destroy its cloud data and cover, and unlink all messages (deleting a message removes only that link).",
87238
+ "",
87239
+ "## Authoring rules & safe collaboration",
87240
+ "",
87241
+ "- **Read the type guide first**: never guess schemas for built-in types; fetch `SKILL.md` and `reference/*.md` via `page guide`.",
87242
+ "- **Use native tools for structured types**: `docs` and `sheets` must be authored through `page local` commands (never hand-edit `doc/doc.json` or `sheet/edits.jsonl`), and `whiteboard`, `data`, and `motion` use `page local write-db` + `page local check`.",
87243
+ "- **Visually verify before upload**: run `page preview --dir <dir> --out preview.png` and inspect the rendered image to confirm layout, legibility, and calculated values before running `page upload`.",
87244
+ '- **Edit safely alongside humans**: for built-in editors, query `{"kind":"actions"}` and prefer native editor actions over raw file overwrites. For `{"kind":"write"}`, always `read` first and pass `if_match` with the returned etag so concurrent human edits are never clobbered.',
87245
+ "- **Comments**: reader comments posted from a Page return as normal messages in the exact conversation where the reader opened the card, mentioning that entry message's author bot.",
87246
+ ""
87247
+ ].join(`
87248
+ `);
87249
+ function syncAlookPageGuide(workingDirectory) {
87250
+ if (!workingDirectory)
87251
+ return false;
87252
+ mkdirSync9(workingDirectory, { recursive: true });
87253
+ const target2 = join25(workingDirectory, ALOOK_PAGE_GUIDE_FILENAME);
87254
+ try {
87255
+ if (readFileSync8(target2, "utf8") === ALOOK_PAGE_GUIDE_CONTENT)
87256
+ return false;
87257
+ } catch (error62) {
87258
+ if (error62?.code !== "ENOENT")
87259
+ throw error62;
87260
+ }
87261
+ writeFileSync11(target2, ALOOK_PAGE_GUIDE_CONTENT, "utf8");
87262
+ return true;
87263
+ }
87264
+
87030
87265
  // src/daemon/daemonSelfSleep.ts
87031
87266
  var DAEMON_SELF_SLEEP_TIMEOUT_MS = 7 * 24 * 60 * 60 * 1000;
87032
87267
  var systemClock = {
@@ -87101,7 +87336,7 @@ class DaemonSelfSleepScheduler {
87101
87336
 
87102
87337
  // src/telemetry/dailyTokenUsage.ts
87103
87338
  import { chmod, mkdir, open as open3, readFile as readFile4, rename, rm } from "node:fs/promises";
87104
- import { dirname as dirname6, join as join25 } from "node:path";
87339
+ import { dirname as dirname6, join as join26 } from "node:path";
87105
87340
  import { randomUUID as randomUUID14 } from "node:crypto";
87106
87341
  var TOKEN_USAGE_WINDOW_DAYS = 30;
87107
87342
  var TOKEN_USAGE_RECOVERY_DAYS = 2;
@@ -87162,7 +87397,7 @@ class DailyTokenUsageStore {
87162
87397
  this.now = now;
87163
87398
  this.resolveTimeZone = typeof timeZone === "string" ? () => timeZone : timeZone;
87164
87399
  this.timeZone;
87165
- this.filePath = join25(workingDirectoryBase, ".telemetry", "daily-token-usage.json");
87400
+ this.filePath = join26(workingDirectoryBase, ".telemetry", "daily-token-usage.json");
87166
87401
  }
87167
87402
  get timeZone() {
87168
87403
  const timeZone = this.resolveTimeZone();
@@ -87481,7 +87716,7 @@ function createRuntimeRawLineTap(args) {
87481
87716
  let sink = sinks.get(agentId);
87482
87717
  if (!sink) {
87483
87718
  try {
87484
- mkdirSync9(traceDir, { recursive: true });
87719
+ mkdirSync10(traceDir, { recursive: true });
87485
87720
  } catch (error62) {
87486
87721
  warnOnce(agentId, path17, "mkdir", error62);
87487
87722
  }
@@ -87510,6 +87745,7 @@ function emitImplicitTypingStopOnSend(args) {
87510
87745
  }
87511
87746
  function createBuiltinDaemonSessionFactory(onRuntimeRawLine, onRuntimeStderr) {
87512
87747
  return async ({ ctx, runtimeConfig }) => {
87748
+ syncAlookPageGuide(ctx.workingDirectory);
87513
87749
  const selected = toAgentBackendSelection(runtimeConfig);
87514
87750
  const sdk = createAgentDriverSdk({
87515
87751
  host: createDaemonAgentDriverHost(ctx, onRuntimeRawLine?.bind(null, ctx.agentId), onRuntimeStderr?.bind(null, ctx.agentId))
@@ -87961,7 +88197,7 @@ async function createDaemon(opts) {
87961
88197
  if (!opts.fsmTraceDir)
87962
88198
  return { source: null };
87963
88199
  try {
87964
- mkdirSync9(opts.fsmTraceDir, { recursive: true });
88200
+ mkdirSync10(opts.fsmTraceDir, { recursive: true });
87965
88201
  } catch {}
87966
88202
  const source = createRotatingFileSink(`${opts.fsmTraceDir}/fsm-trace.jsonl`, DEFAULT_TRACE_FILE_MAX_BYTES);
87967
88203
  const sampler = createTraceSampler((rec) => source.write(JSON.stringify(rec)));