@alook/daemon 0.1.72 → 0.1.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24158,6 +24158,55 @@ async function killProcessTree(pid, opts) {
24158
24158
  import { createRequire as createRequire2 } from "node:module";
24159
24159
  import { homedir as homedir2 } from "node:os";
24160
24160
  import { join as join4, resolve } from "node:path";
24161
+ var MAX_CHILD_PROGRESS_ROWS = 64;
24162
+ function parseAgyVersion(version) {
24163
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.-]+)?$/.exec(version.trim());
24164
+ if (!match)
24165
+ return null;
24166
+ const major = Number(match[1]);
24167
+ const minor = Number(match[2]);
24168
+ const patch = Number(match[3]);
24169
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
24170
+ return null;
24171
+ }
24172
+ return [major, minor, patch];
24173
+ }
24174
+ function compareSemver(a, b) {
24175
+ for (let index = 0;index < 3; index += 1) {
24176
+ if (a[index] !== b[index])
24177
+ return a[index] - b[index];
24178
+ }
24179
+ return 0;
24180
+ }
24181
+ function isAgyVersionAtLeast(version, min, maxMajorExclusive) {
24182
+ const parsed = parseAgyVersion(version);
24183
+ if (!parsed)
24184
+ return false;
24185
+ if (maxMajorExclusive !== undefined && parsed[0] >= maxMajorExclusive)
24186
+ return false;
24187
+ return compareSemver(parsed, min) >= 0;
24188
+ }
24189
+ function resolveAgyUsageProfile(version) {
24190
+ const parsed = parseAgyVersion(version);
24191
+ if (!parsed || parsed[0] >= 2)
24192
+ return;
24193
+ if (compareSemver(parsed, [1, 5, 9]) >= 0) {
24194
+ return { inputIncludesCache: false, outputIncludesReasoning: true };
24195
+ }
24196
+ if (compareSemver(parsed, [1, 4, 12]) >= 0) {
24197
+ return { inputIncludesCache: true, outputIncludesReasoning: false };
24198
+ }
24199
+ return;
24200
+ }
24201
+ function readConversationSummaryColumns(db) {
24202
+ const rows = db.prepare("PRAGMA table_info(conversation_summaries)").all();
24203
+ const columns = new Set;
24204
+ for (const row of rows) {
24205
+ if (typeof row?.name === "string")
24206
+ columns.add(row.name);
24207
+ }
24208
+ return columns;
24209
+ }
24161
24210
  function agyStateHome(env, cwd) {
24162
24211
  const home = env.HOME || env.USERPROFILE || homedir2();
24163
24212
  return resolve(cwd, env.GEMINI_HOME?.trim().replace(/^~(?=[/\\]|$)/, home) || join4(home, ".gemini"));
@@ -24307,10 +24356,14 @@ class NativeSessionActivityReader {
24307
24356
  this.path = join4(home, "antigravity-cli", "conversation_summaries.db");
24308
24357
  }
24309
24358
  async activity() {
24310
- if (this.version !== "1.5.16")
24359
+ if (!isAgyVersionAtLeast(this.version, [1, 5, 16], 2))
24311
24360
  return "unknown";
24312
24361
  const db = await this.openDatabase(this.path);
24313
24362
  try {
24363
+ const columns = readConversationSummaryColumns(db);
24364
+ if (!columns.has("conversation_id") || !columns.has("status") || !columns.has("not_fully_idle")) {
24365
+ return "unknown";
24366
+ }
24314
24367
  const rows = db.prepare("SELECT status,not_fully_idle FROM conversation_summaries WHERE conversation_id = ? LIMIT 1").all(this.sessionId);
24315
24368
  const row = rows[0];
24316
24369
  if (!row || row.not_fully_idle !== 0 && row.not_fully_idle !== 1)
@@ -24322,6 +24375,40 @@ class NativeSessionActivityReader {
24322
24375
  db.close();
24323
24376
  }
24324
24377
  }
24378
+ async childProgress() {
24379
+ if (!isAgyVersionAtLeast(this.version, [1, 5, 16], 2))
24380
+ return null;
24381
+ let db;
24382
+ try {
24383
+ db = await this.openDatabase(this.path);
24384
+ } catch {
24385
+ return null;
24386
+ }
24387
+ try {
24388
+ const columns = readConversationSummaryColumns(db);
24389
+ if (!columns.has("conversation_id") || !columns.has("parent_conversation_id") || !columns.has("step_count") || !columns.has("last_modified_time")) {
24390
+ return null;
24391
+ }
24392
+ const rows = db.prepare(`SELECT conversation_id,step_count,last_modified_time FROM conversation_summaries WHERE parent_conversation_id = ? ORDER BY last_modified_time DESC LIMIT ${MAX_CHILD_PROGRESS_ROWS}`).all(this.sessionId);
24393
+ const children = [];
24394
+ for (const row of rows) {
24395
+ if (typeof row?.conversation_id !== "string" || !row.conversation_id)
24396
+ continue;
24397
+ const stepCount = typeof row.step_count === "number" && Number.isSafeInteger(row.step_count) && row.step_count >= 0 ? row.step_count : 0;
24398
+ const lastModifiedTime = typeof row.last_modified_time === "string" ? row.last_modified_time : typeof row.last_modified_time === "number" && Number.isFinite(row.last_modified_time) ? String(row.last_modified_time) : "";
24399
+ children.push({
24400
+ conversationId: row.conversation_id,
24401
+ stepCount,
24402
+ lastModifiedTime
24403
+ });
24404
+ }
24405
+ return children;
24406
+ } catch {
24407
+ return null;
24408
+ } finally {
24409
+ db.close();
24410
+ }
24411
+ }
24325
24412
  }
24326
24413
 
24327
24414
  // agent-driver/dist/internal/model-observation.js
@@ -24533,6 +24620,28 @@ function isMissingSessionError(error) {
24533
24620
  const message = error instanceof Error ? error.message : String(error);
24534
24621
  return /\bsession\b.*\b(not found|missing|unknown|invalid)\b/i.test(message) || /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);
24535
24622
  }
24623
+ function timestampAdvanced(previous, next) {
24624
+ if (!next || next === previous)
24625
+ return false;
24626
+ if (!previous)
24627
+ return true;
24628
+ const previousMs = Date.parse(previous);
24629
+ const nextMs = Date.parse(next);
24630
+ if (Number.isFinite(previousMs) && Number.isFinite(nextMs)) {
24631
+ return nextMs > previousMs || nextMs === previousMs && next > previous;
24632
+ }
24633
+ return next > previous;
24634
+ }
24635
+ function toChildProgressMap(children) {
24636
+ const map = new Map;
24637
+ for (const child of children) {
24638
+ map.set(child.conversationId, {
24639
+ stepCount: child.stepCount,
24640
+ lastModifiedTime: child.lastModifiedTime
24641
+ });
24642
+ }
24643
+ return map;
24644
+ }
24536
24645
 
24537
24646
  class AgyAcpLane {
24538
24647
  factory;
@@ -24549,6 +24658,8 @@ class AgyAcpLane {
24549
24658
  nativeActivity = "unknown";
24550
24659
  publishedActivity;
24551
24660
  activityRevision = 0;
24661
+ childProgressBaseline = null;
24662
+ resumedSession = false;
24552
24663
  nativeVersion = "";
24553
24664
  contentOwner;
24554
24665
  executionIsolated = true;
@@ -24598,6 +24709,7 @@ class AgyAcpLane {
24598
24709
  return { ok: false, reason: "runtime_error", error: "Agy ACP session already started" };
24599
24710
  }
24600
24711
  this.started = true;
24712
+ this.resumedSession = Boolean(input.sessionId ?? this.ctx.config.sessionId);
24601
24713
  const launchCtx = {
24602
24714
  ...this.ctx,
24603
24715
  prompt: input.text,
@@ -24628,7 +24740,7 @@ class AgyAcpLane {
24628
24740
  const sessionId = this.sessionId;
24629
24741
  if (!sessionId)
24630
24742
  throw new Error("Agy ACP handshake completed without a session id");
24631
- this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, this.nativeVersion === "1.5.16");
24743
+ this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, isAgyVersionAtLeast(this.nativeVersion, [1, 5, 16], 2));
24632
24744
  this.processActivated = true;
24633
24745
  this.ready = true;
24634
24746
  this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input.sessionId ? "resumed" : "created", evidence: "native_api" } });
@@ -24679,8 +24791,8 @@ class AgyAcpLane {
24679
24791
  stop(input = {}) {
24680
24792
  this.requestedStopReason ??= input.reason ?? "requested_stop";
24681
24793
  this.ready = false;
24682
- if (this.activityTimer)
24683
- clearTimeout(this.activityTimer);
24794
+ this.clearActivityTimer();
24795
+ this.childProgressBaseline = null;
24684
24796
  this.currentPromptRequestId = null;
24685
24797
  this.terminalOwner = null;
24686
24798
  this.toolCalls.clear();
@@ -24688,12 +24800,7 @@ class AgyAcpLane {
24688
24800
  this.promptOutcomes.clear();
24689
24801
  this.observedPrompts.clear();
24690
24802
  this.usage.reset();
24691
- const waiter = this.configWaiter;
24692
- if (waiter) {
24693
- clearTimeout(waiter.timer);
24694
- this.configWaiter = undefined;
24695
- waiter.reject(new Error("Antigravity CLI lane stopped"));
24696
- }
24803
+ this.rejectConfigWaiter(new Error("Antigravity CLI lane stopped"));
24697
24804
  this.stopPromise ??= this.stopPhysicalOnce(input);
24698
24805
  return this.stopPromise;
24699
24806
  }
@@ -24744,7 +24851,7 @@ class AgyAcpLane {
24744
24851
  }
24745
24852
  const version = record2(initialize.agentInfo)?.version;
24746
24853
  this.nativeVersion = typeof version === "string" ? version : "";
24747
- this.usageProfile = version === "1.4.12" ? { inputIncludesCache: true, outputIncludesReasoning: false } : version === "1.5.9" ? { inputIncludesCache: false, outputIncludesReasoning: true } : undefined;
24854
+ this.usageProfile = typeof version === "string" ? resolveAgyUsageProfile(version) : undefined;
24748
24855
  if (!record2(record2(initialize.agentCapabilities)?.sessionCapabilities)?.resume) {
24749
24856
  throw new AgyAcpIncompatibleError("Antigravity CLI ACP does not support native session resume");
24750
24857
  }
@@ -24949,6 +25056,11 @@ class AgyAcpLane {
24949
25056
  const checkpoint = await read;
24950
25057
  if (!this.ready || this.requestedStopReason || this.isClosed())
24951
25058
  return { ok: false, reason: "closed" };
25059
+ const childBaseline = await this.readChildProgress();
25060
+ if (!this.ready || this.requestedStopReason || this.isClosed())
25061
+ return { ok: false, reason: "closed" };
25062
+ if (childBaseline)
25063
+ this.childProgressBaseline = toChildProgressMap(childBaseline);
24952
25064
  this.executionCheckpoint = checkpoint;
24953
25065
  this.executionIsolated = !this.unownedContent && !this.hasPendingTools();
24954
25066
  return this.admitPrompt(text, "prompt", inputs);
@@ -25196,6 +25308,8 @@ class AgyAcpLane {
25196
25308
  }
25197
25309
  this.processTerminal = true;
25198
25310
  this.ready = false;
25311
+ this.clearActivityTimer();
25312
+ this.rejectConfigWaiter(normalized);
25199
25313
  this.currentPromptRequestId = null;
25200
25314
  this.terminalOwner = null;
25201
25315
  this.toolCalls.clear();
@@ -25215,10 +25329,13 @@ class AgyAcpLane {
25215
25329
  return;
25216
25330
  this.processTerminal = true;
25217
25331
  this.ready = false;
25332
+ this.clearActivityTimer();
25333
+ const exitError = new Error("Agy ACP process exited");
25334
+ this.rejectConfigWaiter(exitError);
25218
25335
  this.currentPromptRequestId = null;
25219
25336
  this.terminalOwner = null;
25220
25337
  this.toolCalls.clear();
25221
- this.rejectAllPending(new Error("Agy ACP process exited"));
25338
+ this.rejectAllPending(exitError);
25222
25339
  if (this.suppressExit || !this.processActivated)
25223
25340
  return;
25224
25341
  this.events.emit("exit", {
@@ -25477,6 +25594,51 @@ class AgyAcpLane {
25477
25594
  this.nativeActivity = "unknown";
25478
25595
  this.publishActivity();
25479
25596
  }
25597
+ async readChildProgress() {
25598
+ if (!this.activityReader?.childProgress)
25599
+ return null;
25600
+ try {
25601
+ return await this.activityReader.childProgress();
25602
+ } catch {
25603
+ return null;
25604
+ }
25605
+ }
25606
+ observeChildProgress(children) {
25607
+ if (!children || this.currentPromptRequestId === null || this.terminalOwner === null)
25608
+ return;
25609
+ if (this.childProgressBaseline === null) {
25610
+ this.childProgressBaseline = toChildProgressMap(children);
25611
+ if (!this.resumedSession && children.length > 0) {
25612
+ this.events.emit("runtime_event", {
25613
+ kind: "internal_progress",
25614
+ source: "agy.native",
25615
+ itemType: "subagent_progress"
25616
+ });
25617
+ }
25618
+ return;
25619
+ }
25620
+ let advanced = false;
25621
+ for (const child of children) {
25622
+ const previous = this.childProgressBaseline.get(child.conversationId);
25623
+ if (!previous || child.stepCount > previous.stepCount || timestampAdvanced(previous.lastModifiedTime, child.lastModifiedTime)) {
25624
+ advanced = true;
25625
+ }
25626
+ this.childProgressBaseline.set(child.conversationId, {
25627
+ stepCount: Math.max(previous?.stepCount ?? 0, child.stepCount),
25628
+ lastModifiedTime: previous && !timestampAdvanced(previous.lastModifiedTime, child.lastModifiedTime) ? previous.lastModifiedTime : child.lastModifiedTime
25629
+ });
25630
+ }
25631
+ while (this.childProgressBaseline.size > 256) {
25632
+ this.childProgressBaseline.delete(this.childProgressBaseline.keys().next().value);
25633
+ }
25634
+ if (advanced) {
25635
+ this.events.emit("runtime_event", {
25636
+ kind: "internal_progress",
25637
+ source: "agy.native",
25638
+ itemType: "subagent_progress"
25639
+ });
25640
+ }
25641
+ }
25480
25642
  refreshActivity() {
25481
25643
  if (this.activityRead)
25482
25644
  return this.activityRead;
@@ -25495,6 +25657,12 @@ class AgyAcpLane {
25495
25657
  if (status === "running" && this.currentPromptRequestId === null)
25496
25658
  this.unownedContent = true;
25497
25659
  this.publishActivity();
25660
+ if (this.currentPromptRequestId !== null && this.terminalOwner !== null) {
25661
+ const children = await this.readChildProgress();
25662
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
25663
+ return;
25664
+ this.observeChildProgress(children);
25665
+ }
25498
25666
  })();
25499
25667
  this.activityRead = reading;
25500
25668
  reading.finally(() => {
@@ -25503,8 +25671,22 @@ class AgyAcpLane {
25503
25671
  });
25504
25672
  return reading;
25505
25673
  }
25674
+ clearActivityTimer() {
25675
+ if (!this.activityTimer)
25676
+ return;
25677
+ clearTimeout(this.activityTimer);
25678
+ this.activityTimer = undefined;
25679
+ }
25680
+ rejectConfigWaiter(error) {
25681
+ const waiter = this.configWaiter;
25682
+ if (!waiter)
25683
+ return;
25684
+ clearTimeout(waiter.timer);
25685
+ this.configWaiter = undefined;
25686
+ waiter.reject(error);
25687
+ }
25506
25688
  scheduleActivity() {
25507
- if (!this.ready || this.requestedStopReason || this.processTerminal)
25689
+ if (!this.ready || this.requestedStopReason || this.processTerminal || this.activityTimer)
25508
25690
  return;
25509
25691
  this.activityTimer = setTimeout(() => {
25510
25692
  this.activityTimer = undefined;
@@ -37706,8 +37888,36 @@ async function readCursorQuota(options = {}, backend = "cursor") {
37706
37888
  // agent-driver/dist/adapters/agy/quota.js
37707
37889
  import { homedir as homedir14 } from "node:os";
37708
37890
  import { randomUUID as randomUUID9 } from "node:crypto";
37891
+ function classifyAgyQuotaError(message, sourceEpoch, structured) {
37892
+ const text2 = message.trim();
37893
+ if (!text2)
37894
+ return null;
37895
+ if (/(?:not authenticated|authentication (?:required|failed)|sign[ -]?in required|unauthenticated|unauthorized|invalid credentials|token expired|permission denied|\b401\b|\b403\b)/i.test(text2)) {
37896
+ return { status: "error", sourceEpoch, code: "unauthorized", retryable: false };
37897
+ }
37898
+ if (/(?:eligibility check failed|not eligible|not (?:currently )?available in your (?:location|region|country)|unsupported (?:location|region|country))/i.test(text2)) {
37899
+ return { status: "error", sourceEpoch, code: "provider_error", retryable: false };
37900
+ }
37901
+ if (/(?:econnrefused|econnreset|etimedout|enotfound|ehostunreach|network error|fetch failed|dial tcp|socket hang up|connection refused|connection reset|proxyconnect|timed out|\bdns\b|\btls\b|\bssl\b)/i.test(text2)) {
37902
+ return { status: "error", sourceEpoch, code: "network", retryable: true };
37903
+ }
37904
+ if (/(?:rate[ -]?limit|too many requests|quota exceeded|\b429\b|\b50[0234]\b|internal server error|service unavailable|bad gateway|temporarily unavailable|resource exhausted|upstream)/i.test(text2)) {
37905
+ return { status: "error", sourceEpoch, code: "provider_error", retryable: true };
37906
+ }
37907
+ return structured ? { status: "error", sourceEpoch, code: "provider_error", retryable: true } : null;
37908
+ }
37909
+ function tryParseJson(text2) {
37910
+ try {
37911
+ return { ok: true, value: JSON.parse(text2) };
37912
+ } catch {
37913
+ return { ok: false };
37914
+ }
37915
+ }
37709
37916
  function parseAgyQuota(value, sourceEpoch) {
37710
37917
  const result = asRecord(value);
37918
+ if (result?.status === "ERROR" && typeof result.error === "string" && result.error.trim()) {
37919
+ return classifyAgyQuotaError(result.error, sourceEpoch, true) ?? { status: "error", sourceEpoch, code: "provider_error", retryable: true };
37920
+ }
37711
37921
  const command = asRecord(result?.command);
37712
37922
  const data = asRecord(command?.data);
37713
37923
  const groups = data?.groups;
@@ -37744,21 +37954,58 @@ async function readAgyQuota(options = {}) {
37744
37954
  const source = quotaSource("agy", randomUUID9());
37745
37955
  const read = async (args) => {
37746
37956
  const child = (options.spawn ?? spawnAgentProcess)(spec.command, args, { cwd: options.cwd ?? process.cwd(), env: { ...env, CI: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "true" }, shell: spec.shell, stdin: "ignore" });
37747
- let output = "";
37748
- return runBoundedDiscoveryProcess({ process: child, label: "AGY quota", timeoutMs: options.timeoutMs ?? 30000, outputMaxBytes: options.outputMaxBytes ?? 1024 * 1024, stderr: "count", cleanupGraceMs: 100, cleanup: options.cleanup, exitEvent: "close", onStdout: (text2) => {
37749
- output += text2;
37750
- }, onExit: (code, _signal, control) => {
37751
- if (code !== 0)
37752
- return control.fail("AGY quota failed");
37753
- control.flushStdout();
37754
- control.finish(output);
37755
- } });
37957
+ let stdout = "";
37958
+ let stderr = "";
37959
+ return runBoundedDiscoveryProcess({
37960
+ process: child,
37961
+ label: "AGY quota",
37962
+ timeoutMs: options.timeoutMs ?? 30000,
37963
+ outputMaxBytes: options.outputMaxBytes ?? 1024 * 1024,
37964
+ stderr: "count",
37965
+ cleanupGraceMs: 100,
37966
+ cleanup: options.cleanup,
37967
+ exitEvent: "close",
37968
+ onStdout: (text2) => {
37969
+ stdout += text2;
37970
+ },
37971
+ onStderr: (text2) => {
37972
+ stderr += text2;
37973
+ },
37974
+ onExit: (code, _signal, control) => {
37975
+ control.flushStdout();
37976
+ control.flushStderr();
37977
+ control.finish({ exitCode: code, stdout, stderr });
37978
+ }
37979
+ });
37756
37980
  };
37757
37981
  try {
37758
- if (!parseAgyModelCatalog(await read(["models"])))
37982
+ const models = await read(["models"]);
37983
+ if (models.exitCode !== 0) {
37984
+ const classified2 = classifyAgyQuotaError(models.stderr || models.stdout, source.epoch, false);
37985
+ return source.finish(classified2 ?? source.error("unavailable", true));
37986
+ }
37987
+ if (!parseAgyModelCatalog(models.stdout))
37759
37988
  return source.finish(source.error("unauthorized"));
37760
- return source.finish(parseAgyQuota(JSON.parse(await read(["-p", "/usage", "--output-format", "json"])), source.epoch));
37761
- } catch {
37989
+ const usage = await read(["-p", "/usage", "--output-format", "json"]);
37990
+ const parsed = tryParseJson(usage.stdout);
37991
+ if (parsed.ok) {
37992
+ const record8 = asRecord(parsed.value);
37993
+ if (usage.exitCode === 0) {
37994
+ return source.finish(parseAgyQuota(parsed.value, source.epoch));
37995
+ }
37996
+ if (record8?.status === "ERROR" && typeof record8.error === "string" && record8.error.trim()) {
37997
+ return source.finish(parseAgyQuota(parsed.value, source.epoch));
37998
+ }
37999
+ }
38000
+ if (usage.exitCode === 0) {
38001
+ return source.finish(source.error("invalid_response", true));
38002
+ }
38003
+ const classified = classifyAgyQuotaError(usage.stderr || usage.stdout, source.epoch, false);
38004
+ return source.finish(classified ?? source.error("unavailable", true));
38005
+ } catch (error) {
38006
+ if (error instanceof DiscoveryProcessError && error.code === "output_limit") {
38007
+ return source.finish(source.error("invalid_response", true));
38008
+ }
37762
38009
  return source.finish(source.error("unavailable", true));
37763
38010
  }
37764
38011
  }
@@ -60292,11 +60539,53 @@ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
60292
60539
  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)))
60293
60540
  ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
60294
60541
  });
60542
+ var CommunityResolvedChannelRefSchema = exports_external.discriminatedUnion("status", [
60543
+ exports_external.strictObject({
60544
+ ref: exports_external.string().min(1),
60545
+ status: exports_external.literal("ready"),
60546
+ serverId: id2,
60547
+ channelId: id2
60548
+ }),
60549
+ exports_external.strictObject({
60550
+ ref: exports_external.string().min(1),
60551
+ status: exports_external.enum(["forbidden", "missing"])
60552
+ })
60553
+ ]);
60554
+ var CommunityMessageRefsSchema = exports_external.strictObject({
60555
+ servers: exports_external.array(CommunityServerResourceSchema),
60556
+ channels: exports_external.array(CommunityChannelResourceSchema),
60557
+ resolvedRefs: exports_external.array(CommunityResolvedChannelRefSchema)
60558
+ }).superRefine((refs, ctx) => {
60559
+ const serverIds = new Set(refs.servers.map((row) => row.id));
60560
+ const channelById = new Map(refs.channels.map((row) => [row.id, row]));
60561
+ const refKeys = new Set(refs.resolvedRefs.map((row) => row.ref));
60562
+ if (serverIds.size !== refs.servers.length || channelById.size !== refs.channels.length || refKeys.size !== refs.resolvedRefs.length) {
60563
+ ctx.addIssue({ code: "custom", message: "Duplicated ref resource" });
60564
+ return;
60565
+ }
60566
+ for (const channel of refs.channels) {
60567
+ if (channel.serverId === null || !serverIds.has(channel.serverId)) {
60568
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel server missing" });
60569
+ }
60570
+ if (channel.parentChannelId !== null && !channelById.has(channel.parentChannelId)) {
60571
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel parent missing" });
60572
+ }
60573
+ }
60574
+ for (const resolved of refs.resolvedRefs) {
60575
+ if (resolved.status !== "ready")
60576
+ continue;
60577
+ const channel = channelById.get(resolved.channelId);
60578
+ if (!serverIds.has(resolved.serverId) || !channel || channel.serverId !== resolved.serverId) {
60579
+ ctx.addIssue({ code: "custom", path: ["resolvedRefs"], message: "Resolved ref target missing from resources" });
60580
+ }
60581
+ }
60582
+ });
60295
60583
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
60296
60584
  var CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({
60297
60585
  ...envelope,
60298
60586
  page: CommunityPageSchema,
60299
60587
  relatedMessages: exports_external.array(CommunityMessageResourceSchema).optional(),
60588
+ refs: CommunityMessageRefsSchema.optional(),
60300
60589
  surfaceReceipt: exports_external.strictObject({ channelId: id2, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
60301
60590
  }).superRefine(validateRelatedMessageGraph);
60302
60591
  var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
@@ -60376,7 +60665,13 @@ var CommunityMessageReadSchema = exports_external.strictObject({
60376
60665
  validateRelatedMessageGraph({ messages: [read.message], relatedMessages: read.relatedMessages, profiles: read.profiles }, ctx);
60377
60666
  });
60378
60667
  var CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: exports_external.boolean(), threadId: id2.optional() });
60379
- var CommunityMembersReadSchema = exports_external.strictObject({ ...envelope, relation: exports_external.enum(["access", "notify"]), members: exports_external.array(CommunityMemberRelationSchema), profiles: exports_external.array(CommunityResourceProfileSchema) });
60668
+ var CommunityMembersReadSchema = exports_external.strictObject({
60669
+ ...envelope,
60670
+ relation: exports_external.enum(["access", "notify"]),
60671
+ members: exports_external.array(CommunityMemberRelationSchema),
60672
+ profiles: exports_external.array(CommunityResourceProfileSchema),
60673
+ page: exports_external.strictObject({ nextCursor: exports_external.string().nullable(), hasMore: exports_external.boolean() }).optional()
60674
+ });
60380
60675
  var CommunityThreadsReadSchema = exports_external.strictObject({
60381
60676
  ...envelope,
60382
60677
  channel: CommunityChannelResourceSchema,
@@ -62342,7 +62637,7 @@ var nativeOauthAttempt = sqliteTable("native_oauth_attempt", {
62342
62637
  AND ${t.openedAt} IS NOT NULL AND ${t.readyAt} IS NOT NULL AND ${t.consumedAt} IS NULL
62343
62638
  AND ${t.failedAt} IS NULL AND ${t.cancelledAt} IS NULL AND ${t.replacedAt} IS NULL
62344
62639
  AND ${t.handoffCodeHash} IS NOT NULL AND ${t.handoffExpiresAt} IS NOT NULL
62345
- AND ${t.handoffExpiresAt} = ${t.readyAt} + 120000
62640
+ AND ${t.handoffExpiresAt} = min(${t.readyAt} + 120000, ${t.attemptExpiresAt})
62346
62641
  AND ${t.authKind} IS NOT NULL AND ${t.failureCode} IS NULL
62347
62642
  ) OR (
62348
62643
  ${t.status} = 'consumed'
@@ -62436,6 +62731,7 @@ var communityChannelMember = sqliteTable("community_channel_member", {
62436
62731
  }, (t) => [
62437
62732
  index("idx_community_channel_member_added_by_lookup").on(t.addedBy),
62438
62733
  unique("uq_channel_member").on(t.channelId, t.userId, t.relation),
62734
+ index("idx_channel_member_channel_relation_user").on(t.channelId, t.relation, t.userId),
62439
62735
  index("idx_channel_member_user").on(t.userId)
62440
62736
  ]);
62441
62737
  var communityMessage = sqliteTable("community_message", {
@@ -62455,6 +62751,7 @@ var communityMessage = sqliteTable("community_message", {
62455
62751
  clientNonce: text2("client_nonce")
62456
62752
  }, (t) => [
62457
62753
  index("idx_community_message_author_id_lookup").on(t.authorId),
62754
+ index("idx_message_channel_seq").on(t.channelId, t.seq),
62458
62755
  index("idx_message_channel_created").on(t.channelId, t.createdAt),
62459
62756
  index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt),
62460
62757
  index("idx_community_message_channel_reply_author").on(t.channelId, t.replyToId, t.authorId).where(sql`${t.replyToId} IS NOT NULL`)
@@ -62559,7 +62856,8 @@ var communityReaction = sqliteTable("community_reaction", {
62559
62856
  }, (t) => [
62560
62857
  index("idx_community_reaction_user_id_lookup").on(t.userId),
62561
62858
  unique("uq_reaction_message_user_emoji").on(t.messageId, t.userId, t.emoji),
62562
- index("idx_reaction_message").on(t.messageId)
62859
+ index("idx_reaction_message").on(t.messageId),
62860
+ index("idx_reaction_message_emoji_created").on(t.messageId, t.emoji, t.createdAt, t.userId)
62563
62861
  ]);
62564
62862
  var communityAttachment = sqliteTable("community_attachment", {
62565
62863
  id: text2("id").primaryKey().$defaultFn(() => nanoid3()),
@@ -62721,18 +63019,6 @@ var communityMessageTag = sqliteTable("community_message_tag", {
62721
63019
  index("idx_message_tag_tag").on(t.tag, t.messageId)
62722
63020
  ]);
62723
63021
 
62724
- // ../shared/src/db/queries/_chunk.ts
62725
- var D1_MAX_BIND_PARAMS = 100;
62726
- function maxInParams(fixedParams) {
62727
- if (!Number.isInteger(fixedParams) || fixedParams < 0) {
62728
- throw new Error("fixed params must be a non-negative integer");
62729
- }
62730
- if (fixedParams >= D1_MAX_BIND_PARAMS) {
62731
- throw new Error("fixed params must leave room for at least one IN parameter");
62732
- }
62733
- return D1_MAX_BIND_PARAMS - fixedParams;
62734
- }
62735
-
62736
63022
  // ../shared/src/community-server-rail.ts
62737
63023
  var MAX_SERVER_RAIL_COMMANDS = 3;
62738
63024
  var idSchema = exports_external.string().trim().min(1);
@@ -63140,7 +63426,6 @@ var AGENT_MESSAGE_COLUMNS = {
63140
63426
  embeds: communityMessage.embeds
63141
63427
  };
63142
63428
  var channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${communityChannelMember.addedAt}, ${communityServerMember.joinedAt}, '')`;
63143
- var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
63144
63429
  // ../shared/src/community-ws-events.ts
63145
63430
  var string4 = exports_external.string();
63146
63431
  var nullableString = string4.nullable();
@@ -63298,7 +63583,8 @@ var communityMemberJoinSchema = exports_external.strictObject({
63298
63583
  userId: string4,
63299
63584
  role: string4,
63300
63585
  joinedAt: string4
63301
- })
63586
+ }),
63587
+ online: exports_external.boolean().optional()
63302
63588
  });
63303
63589
  var communityMemberLeaveSchema = exports_external.strictObject({
63304
63590
  type: exports_external.literal("community:member.leave"),
@@ -63394,6 +63680,10 @@ var communityPresenceUpdateSchema = exports_external.strictObject({
63394
63680
  userId: string4,
63395
63681
  online: exports_external.boolean()
63396
63682
  });
63683
+ var communityPresenceSnapshotSchema = exports_external.strictObject({
63684
+ type: exports_external.literal("community:presence.snapshot"),
63685
+ onlineUserIds: exports_external.array(string4)
63686
+ });
63397
63687
  var communityStatusUpdateSchema = exports_external.strictObject({
63398
63688
  type: exports_external.literal("community:status.update"),
63399
63689
  userId: string4,
@@ -63452,6 +63742,11 @@ var communityBotPiiSchema = exports_external.strictObject({
63452
63742
  requestId: exports_external.string().min(1).max(128),
63453
63743
  result: PiiResultSchema
63454
63744
  });
63745
+ var communityScheduleChangedSchema = exports_external.strictObject({
63746
+ type: exports_external.literal("community:schedule.changed"),
63747
+ eventId: string4,
63748
+ reason: exports_external.enum(["created", "updated", "deleted", "run_updated"])
63749
+ });
63455
63750
  var commonCommunityEventSchemas = [
63456
63751
  communityBotPiiSchema,
63457
63752
  communityMessageUpdatedSchema,
@@ -63485,13 +63780,15 @@ var commonCommunityEventSchemas = [
63485
63780
  communityReadStateAdvancedSchema,
63486
63781
  communityInboxChangedSchema,
63487
63782
  communityPresenceUpdateSchema,
63783
+ communityPresenceSnapshotSchema,
63488
63784
  communityStatusUpdateSchema,
63489
63785
  communityMachineCreatedSchema,
63490
63786
  communityMachineStatusSchema,
63491
63787
  communityMachineUpdatedSchema,
63492
63788
  communityRuntimeModelsSchema,
63493
63789
  communityMachineRemovedSchema,
63494
- communityBotAuditEventSchema
63790
+ communityBotAuditEventSchema,
63791
+ communityScheduleChangedSchema
63495
63792
  ];
63496
63793
  var CommunityWsEventSchema = exports_external.discriminatedUnion("type", [
63497
63794
  ...commonCommunityEventSchemas,
@@ -63540,6 +63837,7 @@ var WS_EVENTS = {
63540
63837
  READ_STATE_ADVANCED: "community:read_state.advanced",
63541
63838
  INBOX_CHANGED: "community:inbox.changed",
63542
63839
  PRESENCE_UPDATE: "community:presence.update",
63840
+ PRESENCE_SNAPSHOT: "community:presence.snapshot",
63543
63841
  STATUS_UPDATE: "community:status.update",
63544
63842
  IDENTITY_UPDATE: "community:identity.update",
63545
63843
  PROFILE_UPDATE: "community:profile.update",
@@ -63549,7 +63847,8 @@ var WS_EVENTS = {
63549
63847
  RUNTIME_MODELS: "community:runtime.models",
63550
63848
  BOT_PII: "community:bot.pii",
63551
63849
  MACHINE_REMOVED: "community:machine.removed",
63552
- BOT_AUDIT_EVENT: "community:bot.audit_event"
63850
+ BOT_AUDIT_EVENT: "community:bot.audit_event",
63851
+ SCHEDULE_CHANGED: "community:schedule.changed"
63553
63852
  };
63554
63853
  var COMMUNITY_EVENT_TYPES = new Set(Object.values(WS_EVENTS));
63555
63854
  var COMMUNITY_BROWSER_EVENT_MAX_BYTES = 65536;
@@ -63770,8 +64069,109 @@ var communityBotFeedback = sqliteTable("community_bot_feedback", {
63770
64069
  check2("bot_feedback_text_bytes", sql`length(cast(${t.text} as blob)) between 1 and ${sql.raw(String(BOT_FEEDBACK_MAX_BYTES))}`)
63771
64070
  ]);
63772
64071
 
64072
+ // ../shared/src/db/community-schedule-schema.ts
64073
+ var exports_community_schedule_schema = {};
64074
+ __export(exports_community_schedule_schema, {
64075
+ communityScheduleRun: () => communityScheduleRun,
64076
+ communityScheduleEvent: () => communityScheduleEvent
64077
+ });
64078
+ var communityScheduleEvent = sqliteTable("community_schedule_event", {
64079
+ id: text2("id").primaryKey(),
64080
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64081
+ createdByUserId: text2("created_by_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64082
+ title: text2("title").notNull(),
64083
+ description: text2("description").notNull().default(""),
64084
+ startAtMs: integer2("start_at_ms").notNull(),
64085
+ durationMinutes: integer2("duration_minutes").notNull().default(30),
64086
+ timeZone: text2("time_zone").notNull(),
64087
+ recurrenceJson: text2("recurrence_json"),
64088
+ occurrenceCount: integer2("occurrence_count").notNull().default(0),
64089
+ nextRunAtMs: integer2("next_run_at_ms"),
64090
+ sourceMessageId: text2("source_message_id").notNull(),
64091
+ sourceChannelId: text2("source_channel_id").notNull(),
64092
+ version: integer2("version").notNull().default(1),
64093
+ createdAtMs: integer2("created_at_ms").notNull(),
64094
+ updatedAtMs: integer2("updated_at_ms").notNull()
64095
+ }, (t) => [
64096
+ index("idx_community_schedule_event_owner_created").on(t.ownerUserId, t.createdAtMs),
64097
+ index("idx_community_schedule_event_owner_next_run").on(t.ownerUserId, t.nextRunAtMs).where(sql`${t.nextRunAtMs} IS NOT NULL`),
64098
+ index("idx_community_schedule_event_creator_id_lookup").on(t.createdByUserId)
64099
+ ]);
64100
+ var communityScheduleRun = sqliteTable("community_schedule_run", {
64101
+ id: text2("id").primaryKey(),
64102
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64103
+ eventId: text2("event_id").notNull().references(() => communityScheduleEvent.id, { onDelete: "cascade" }),
64104
+ eventVersion: integer2("event_version").notNull(),
64105
+ botUserId: text2("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64106
+ scheduledAtMs: integer2("scheduled_at_ms").notNull(),
64107
+ sourceMessageId: text2("source_message_id").notNull(),
64108
+ sourceChannelId: text2("source_channel_id").notNull(),
64109
+ titleSnapshot: text2("title_snapshot").notNull(),
64110
+ descriptionSnapshot: text2("description_snapshot").notNull(),
64111
+ status: text2("status").$type().notNull(),
64112
+ lastError: text2("last_error"),
64113
+ ackedAtMs: integer2("acked_at_ms"),
64114
+ createdAtMs: integer2("created_at_ms").notNull(),
64115
+ updatedAtMs: integer2("updated_at_ms").notNull()
64116
+ }, (t) => [
64117
+ uniqueIndex("uq_community_schedule_run_event_scheduled").on(t.eventId, t.scheduledAtMs),
64118
+ index("idx_community_schedule_run_owner_status_scheduled").on(t.ownerUserId, t.status, t.scheduledAtMs),
64119
+ index("idx_community_schedule_run_bot_id_lookup").on(t.botUserId)
64120
+ ]);
64121
+
64122
+ // ../shared/src/db/community-bot-private-inbox-schema.ts
64123
+ var exports_community_bot_private_inbox_schema = {};
64124
+ __export(exports_community_bot_private_inbox_schema, {
64125
+ communityBotPrivateInbox: () => communityBotPrivateInbox
64126
+ });
64127
+ var communityBotPrivateInbox = sqliteTable("community_bot_private_inbox", {
64128
+ id: text2("id").primaryKey(),
64129
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64130
+ botUserId: text2("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64131
+ sourceKind: text2("source_kind").$type().notNull(),
64132
+ sourceId: text2("source_id").notNull(),
64133
+ sourceRefId: text2("source_ref_id"),
64134
+ dedupeKey: text2("dedupe_key"),
64135
+ eventType: text2("event_type").notNull(),
64136
+ summary: text2("summary").notNull(),
64137
+ promptText: text2("prompt_text").notNull(),
64138
+ status: text2("status").$type().notNull(),
64139
+ lastError: text2("last_error"),
64140
+ createdAtMs: integer2("created_at_ms").notNull(),
64141
+ dispatchedAtMs: integer2("dispatched_at_ms")
64142
+ }, (t) => [
64143
+ uniqueIndex("uq_community_bot_private_inbox_dedupe").on(t.sourceKind, t.sourceId, t.dedupeKey).where(sql`${t.dedupeKey} IS NOT NULL`),
64144
+ index("idx_community_bot_private_inbox_bot_pending").on(t.botUserId, t.status, t.createdAtMs),
64145
+ index("idx_community_bot_private_inbox_source_created").on(t.sourceKind, t.sourceId, t.createdAtMs),
64146
+ index("idx_community_bot_private_inbox_owner").on(t.ownerUserId)
64147
+ ]);
64148
+
64149
+ // ../shared/src/db/community-bot-webhook-schema.ts
64150
+ var exports_community_bot_webhook_schema = {};
64151
+ __export(exports_community_bot_webhook_schema, {
64152
+ communityBotWebhook: () => communityBotWebhook
64153
+ });
64154
+ var communityBotWebhook = sqliteTable("community_bot_webhook", {
64155
+ id: text2("id").primaryKey(),
64156
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64157
+ botUserId: text2("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
64158
+ name: text2("name").notNull(),
64159
+ provider: text2("provider").$type().notNull(),
64160
+ tokenHash: text2("token_hash").notNull().unique(),
64161
+ signingSecretEnc: text2("signing_secret_enc"),
64162
+ eventFilterJson: text2("event_filter_json"),
64163
+ instruction: text2("instruction").notNull().default(""),
64164
+ enabled: integer2("enabled", { mode: "boolean" }).notNull().default(true),
64165
+ lastTriggeredAtMs: integer2("last_triggered_at_ms"),
64166
+ createdAtMs: integer2("created_at_ms").notNull(),
64167
+ updatedAtMs: integer2("updated_at_ms").notNull()
64168
+ }, (t) => [
64169
+ index("idx_community_bot_webhook_owner_bot").on(t.ownerUserId, t.botUserId, t.createdAtMs),
64170
+ index("idx_community_bot_webhook_bot").on(t.botUserId)
64171
+ ]);
64172
+
63773
64173
  // ../shared/src/db/index.ts
63774
- 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 };
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 };
63775
64175
  // ../shared/src/db/queries/native-oauth.ts
63776
64176
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
63777
64177
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
@@ -63800,6 +64200,223 @@ var metadataProjection = {
63800
64200
  };
63801
64201
  // ../shared/src/db/queries/community/diagnostic-report.ts
63802
64202
  var diagnosticOwner = alias(user, "diagnostic_owner");
64203
+ // ../shared/src/schedule.ts
64204
+ var SCHEDULE_TITLE_MAX_LENGTH = 160;
64205
+ var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
64206
+ var SCHEDULE_MIN_DURATION_MINUTES = 5;
64207
+ var SCHEDULE_MAX_DURATION_MINUTES = 1440;
64208
+ var SCHEDULE_MAX_RANGE_MS = 62 * 24 * 60 * 60 * 1000;
64209
+ var ScheduleRecurrenceFreqSchema = exports_external.enum(["hourly", "daily", "weekly", "monthly"]);
64210
+ var ScheduleRecurrenceSchema = exports_external.strictObject({
64211
+ freq: ScheduleRecurrenceFreqSchema,
64212
+ interval: exports_external.number().int().min(1).max(365),
64213
+ byWeekday: exports_external.array(exports_external.number().int().min(0).max(6)).min(1).max(7).optional(),
64214
+ untilAt: exports_external.iso.datetime({ offset: true }).nullable().optional(),
64215
+ count: exports_external.number().int().min(1).max(1000).nullable().optional()
64216
+ }).superRefine((value, ctx) => {
64217
+ if (value.byWeekday !== undefined && value.freq !== "weekly") {
64218
+ ctx.addIssue({
64219
+ code: "custom",
64220
+ path: ["byWeekday"],
64221
+ message: "byWeekday is only supported for weekly recurrence"
64222
+ });
64223
+ }
64224
+ });
64225
+ var ScheduleRunStatusSchema = exports_external.enum([
64226
+ "pending",
64227
+ "dispatched",
64228
+ "completed",
64229
+ "blocked_access"
64230
+ ]);
64231
+ var ScheduleOccurrenceStatusSchema = exports_external.enum([
64232
+ "scheduled",
64233
+ "pending",
64234
+ "dispatched",
64235
+ "completed",
64236
+ "blocked_access"
64237
+ ]);
64238
+ var ScheduleSourceMessageStatusSchema = exports_external.enum([
64239
+ "accessible",
64240
+ "inaccessible",
64241
+ "deleted"
64242
+ ]);
64243
+ var ScheduleActorSummarySchema = exports_external.strictObject({
64244
+ id: exports_external.string().min(1),
64245
+ handle: exports_external.string().min(1),
64246
+ name: exports_external.string().min(1),
64247
+ avatarVersion: exports_external.number().int().nonnegative(),
64248
+ isBot: exports_external.boolean()
64249
+ });
64250
+ var ScheduleLastExecutionSchema = exports_external.strictObject({
64251
+ scheduledAt: exports_external.iso.datetime(),
64252
+ status: ScheduleRunStatusSchema,
64253
+ lastError: exports_external.string().nullable(),
64254
+ ackedAt: exports_external.iso.datetime().nullable(),
64255
+ updatedAt: exports_external.iso.datetime()
64256
+ });
64257
+ var ScheduleSourceMessageSchema = exports_external.strictObject({
64258
+ id: exports_external.string().min(1),
64259
+ accessible: exports_external.boolean(),
64260
+ status: ScheduleSourceMessageStatusSchema,
64261
+ ref: exports_external.string().nullable(),
64262
+ channelRef: exports_external.string().nullable(),
64263
+ seq: exports_external.number().int().positive().nullable(),
64264
+ preview: exports_external.string().nullable()
64265
+ });
64266
+ var ScheduleEventSchema = exports_external.strictObject({
64267
+ id: exports_external.string().min(1),
64268
+ title: exports_external.string().min(1),
64269
+ description: exports_external.string(),
64270
+ createdBy: ScheduleActorSummarySchema,
64271
+ startAt: exports_external.iso.datetime(),
64272
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES),
64273
+ timeZone: exports_external.string().min(1),
64274
+ recurrence: ScheduleRecurrenceSchema.nullable(),
64275
+ nextRunAt: exports_external.iso.datetime().nullable(),
64276
+ sourceMessage: ScheduleSourceMessageSchema,
64277
+ lastExecution: ScheduleLastExecutionSchema.nullable(),
64278
+ createdAt: exports_external.iso.datetime(),
64279
+ updatedAt: exports_external.iso.datetime()
64280
+ });
64281
+ var ScheduleOccurrenceSchema = exports_external.strictObject({
64282
+ eventId: exports_external.string().min(1),
64283
+ occurrenceKey: exports_external.string().min(1),
64284
+ startAt: exports_external.iso.datetime(),
64285
+ endAt: exports_external.iso.datetime(),
64286
+ runStatus: ScheduleOccurrenceStatusSchema
64287
+ });
64288
+ var ScheduleListResponseSchema = exports_external.strictObject({
64289
+ events: exports_external.array(ScheduleEventSchema),
64290
+ occurrences: exports_external.array(ScheduleOccurrenceSchema),
64291
+ creators: exports_external.array(ScheduleActorSummarySchema)
64292
+ });
64293
+ var ScheduleCreateRequestSchema = exports_external.strictObject({
64294
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH),
64295
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
64296
+ startAt: exports_external.iso.datetime({ offset: true }),
64297
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
64298
+ timeZone: exports_external.string().trim().min(1).max(128),
64299
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
64300
+ sourceMessageRef: exports_external.string().trim().min(1).max(512)
64301
+ });
64302
+ var ScheduleUpdateRequestSchema = exports_external.strictObject({
64303
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH).optional(),
64304
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
64305
+ startAt: exports_external.iso.datetime({ offset: true }).optional(),
64306
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
64307
+ timeZone: exports_external.string().trim().min(1).max(128).optional(),
64308
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
64309
+ sourceMessageRef: exports_external.string().trim().min(1).max(512).optional(),
64310
+ ack: exports_external.literal(true).optional()
64311
+ });
64312
+ var formatterCache = new Map;
64313
+ // ../shared/src/bot-webhook.ts
64314
+ var BOT_WEBHOOK_PROVIDERS = [
64315
+ "github",
64316
+ "linear",
64317
+ "sentry",
64318
+ "stripe",
64319
+ "vercel",
64320
+ "gitlab",
64321
+ "slack",
64322
+ "openai",
64323
+ "resend",
64324
+ "clerk",
64325
+ "polar",
64326
+ "cloudflare",
64327
+ "grafana",
64328
+ "datadog",
64329
+ "n8n",
64330
+ "generic"
64331
+ ];
64332
+ var BOT_WEBHOOK_DELIVERY_STATUSES = ["pending", "dispatched", "ignored", "failed"];
64333
+ var BOT_WEBHOOK_NAME_MAX_LENGTH = 80;
64334
+ var BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH = 500;
64335
+ var BOT_WEBHOOK_SECRET_MIN_LENGTH = 8;
64336
+ var BOT_WEBHOOK_SECRET_MAX_LENGTH = 256;
64337
+ var BOT_WEBHOOK_MAX_EVENT_FILTERS = 32;
64338
+ var BOT_WEBHOOK_EVENT_NAME_MAX_LENGTH = 64;
64339
+ var BOT_WEBHOOK_RESYNC_WINDOW_MS = 24 * 60 * 60 * 1000;
64340
+ var BotWebhookProviderSchema = exports_external.enum(BOT_WEBHOOK_PROVIDERS);
64341
+ var BotWebhookDeliveryStatusSchema = exports_external.enum(BOT_WEBHOOK_DELIVERY_STATUSES);
64342
+ var EventFilterEntrySchema = exports_external.string().trim().min(1).max(BOT_WEBHOOK_EVENT_NAME_MAX_LENGTH).regex(/^[a-z0-9_.-]+$/i, "Event name may only contain letters, digits, _, ., and -");
64343
+ var BotWebhookEventFilterSchema = exports_external.array(EventFilterEntrySchema).max(BOT_WEBHOOK_MAX_EVENT_FILTERS).transform((items) => [...new Set(items.map((item) => item.toLowerCase()))]);
64344
+ var SigningSecretInputSchema = exports_external.string().trim().min(BOT_WEBHOOK_SECRET_MIN_LENGTH, `Verification key must be at least ${BOT_WEBHOOK_SECRET_MIN_LENGTH} characters`).max(BOT_WEBHOOK_SECRET_MAX_LENGTH, `Verification key must be at most ${BOT_WEBHOOK_SECRET_MAX_LENGTH} characters`);
64345
+ var BotWebhookLastDeliverySchema = exports_external.strictObject({
64346
+ id: exports_external.string().min(1),
64347
+ status: BotWebhookDeliveryStatusSchema,
64348
+ eventType: exports_external.string().min(1),
64349
+ summary: exports_external.string(),
64350
+ lastError: exports_external.string().nullable(),
64351
+ createdAt: exports_external.iso.datetime()
64352
+ });
64353
+ var BotWebhookDeliverySchema = exports_external.strictObject({
64354
+ id: exports_external.string().min(1),
64355
+ webhookId: exports_external.string().min(1),
64356
+ eventType: exports_external.string().min(1),
64357
+ summary: exports_external.string(),
64358
+ status: BotWebhookDeliveryStatusSchema,
64359
+ lastError: exports_external.string().nullable(),
64360
+ externalDeliveryId: exports_external.string().nullable(),
64361
+ createdAt: exports_external.iso.datetime(),
64362
+ dispatchedAt: exports_external.iso.datetime().nullable()
64363
+ });
64364
+ var BotWebhookSummarySchema = exports_external.strictObject({
64365
+ id: exports_external.string().min(1),
64366
+ botId: exports_external.string().min(1),
64367
+ name: exports_external.string().min(1),
64368
+ provider: BotWebhookProviderSchema,
64369
+ hasSigningSecret: exports_external.boolean(),
64370
+ eventFilter: exports_external.array(exports_external.string()).nullable(),
64371
+ instruction: exports_external.string(),
64372
+ enabled: exports_external.boolean(),
64373
+ lastTriggeredAt: exports_external.iso.datetime().nullable(),
64374
+ createdAt: exports_external.iso.datetime(),
64375
+ updatedAt: exports_external.iso.datetime(),
64376
+ lastDelivery: BotWebhookLastDeliverySchema.nullable()
64377
+ });
64378
+ var BotWebhookCreateSchema = exports_external.strictObject({
64379
+ name: exports_external.string().trim().min(1, "Name is required").max(BOT_WEBHOOK_NAME_MAX_LENGTH),
64380
+ provider: BotWebhookProviderSchema,
64381
+ eventFilter: BotWebhookEventFilterSchema.nullable().optional(),
64382
+ instruction: exports_external.string().trim().max(BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH).optional().default(""),
64383
+ requireSecret: exports_external.boolean().optional(),
64384
+ signingSecret: SigningSecretInputSchema.optional()
64385
+ });
64386
+ var BotWebhookUpdateSchema = exports_external.strictObject({
64387
+ name: exports_external.string().trim().min(1).max(BOT_WEBHOOK_NAME_MAX_LENGTH).optional(),
64388
+ enabled: exports_external.boolean().optional(),
64389
+ eventFilter: BotWebhookEventFilterSchema.nullable().optional(),
64390
+ instruction: exports_external.string().trim().max(BOT_WEBHOOK_INSTRUCTION_MAX_LENGTH).optional(),
64391
+ requireSecret: exports_external.boolean().optional(),
64392
+ signingSecret: SigningSecretInputSchema.optional(),
64393
+ rotateCredentials: exports_external.boolean().optional()
64394
+ }).refine((v) => v.name !== undefined || v.enabled !== undefined || v.eventFilter !== undefined || v.instruction !== undefined || v.requireSecret !== undefined || v.signingSecret !== undefined || v.rotateCredentials === true, { message: "At least one field must be provided" });
64395
+ var BotWebhookCreateResponseSchema = exports_external.strictObject({
64396
+ webhook: BotWebhookSummarySchema,
64397
+ webhookUrl: exports_external.url(),
64398
+ signingSecret: exports_external.string().nullable()
64399
+ });
64400
+ var BotWebhookUpdateResponseSchema = exports_external.strictObject({
64401
+ webhook: BotWebhookSummarySchema,
64402
+ webhookUrl: exports_external.url().optional(),
64403
+ signingSecret: exports_external.string().nullable().optional()
64404
+ });
64405
+ var BotWebhookListResponseSchema = exports_external.strictObject({
64406
+ webhooks: exports_external.array(BotWebhookSummarySchema)
64407
+ });
64408
+ var BotWebhookDeliveriesResponseSchema = exports_external.strictObject({
64409
+ deliveries: exports_external.array(BotWebhookDeliverySchema)
64410
+ });
64411
+ var BotWebhookTestResponseSchema = exports_external.strictObject({
64412
+ delivery: BotWebhookDeliverySchema
64413
+ });
64414
+ // ../shared/src/lib/channel-ref-syntax.ts
64415
+ 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`;
64416
+ var REF_SEG = `[^\\s/#${REF_TERM}]+`;
64417
+ var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
64418
+ var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
64419
+ var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
63803
64420
  // ../shared/src/utils/email.ts
63804
64421
  var DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`;
63805
64422
  // ../shared/src/lib/safe-redirect.ts
@@ -77693,11 +78310,6 @@ var exitSpoiler = function(token) {
77693
78310
  };
77694
78311
 
77695
78312
  // ../shared/src/lib/chat-syntax-plugin.ts
77696
- 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`;
77697
- var REF_SEG = `[^\\s/#${REF_TERM}]+`;
77698
- var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
77699
- var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
77700
- var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
77701
78313
  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");
77702
78314
  function memberMentionSyntax() {
77703
78315
  const construct = {
@@ -78027,7 +78639,7 @@ function checkProfiles(rows, resources, ctx) {
78027
78639
  }
78028
78640
  }
78029
78641
  var CommunityAcceptedFriendsReadSchema = exports_external.union([
78030
- exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
78642
+ 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)),
78031
78643
  exports_external.strictObject({ ...stale, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema).length(0) })
78032
78644
  ]);
78033
78645
  var CommunityBlockedFriendsReadSchema = exports_external.union([
@@ -78132,7 +78744,10 @@ var CommunityReactionDetailsReadSchema = exports_external.strictObject({
78132
78744
  exports_external.strictObject({ kind: exports_external.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
78133
78745
  exports_external.strictObject({ kind: exports_external.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id })
78134
78746
  ]),
78135
- actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() }))
78747
+ actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() })),
78748
+ emoji: exports_external.string().optional(),
78749
+ hasMore: exports_external.boolean().optional(),
78750
+ cursor: exports_external.string().nullable().optional()
78136
78751
  }).superRefine((value, ctx) => {
78137
78752
  if (new Set(value.actors.map((row) => row.userId)).size !== value.actors.length || value.actors.some((row) => row.profile && row.profile.id !== row.userId))
78138
78753
  ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" });
@@ -78236,6 +78851,11 @@ function messagingSection() {
78236
78851
  "- 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.",
78237
78852
  "- Use `0` only when no later action depends on a reply. It disables the timer.",
78238
78853
  "",
78854
+ "#### Schedule future or recurring work",
78855
+ "",
78856
+ "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message or daemon restart cancels it.",
78857
+ `- 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.`,
78858
+ "",
78239
78859
  "#### Sending mechanics",
78240
78860
  "",
78241
78861
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
@@ -78415,6 +79035,15 @@ function cliCommandsSection() {
78415
79035
  "Adding stores a source copy. Later edits to the input file do not update the installed filter. " + "Do not edit daemon-managed copies.",
78416
79036
  "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.",
78417
79037
  "",
79038
+ "### Schedule",
79039
+ "",
79040
+ "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.",
79041
+ "",
79042
+ `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given, expanded occurrences.`,
79043
+ `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.`,
79044
+ `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
+ `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
79046
+ "",
78418
79047
  "### Settings",
78419
79048
  "",
78420
79049
  `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.`,
@@ -81117,6 +81746,10 @@ var communityProxyRoutes = {
81117
81746
  avatar: "/api/community/users/me/avatar",
81118
81747
  marks: "/api/community/users/me/marks"
81119
81748
  };
81749
+ var SCHEDULE_EVENTS_PROXY_PATH_RE = /^\/api\/community\/schedule\/events(?:\/[^/]+)?$/;
81750
+ 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);
81752
+ }
81120
81753
  function resolveProxyCapability(method, pathname) {
81121
81754
  if (pathname === "/api/community/platform/feedback" && method === "POST")
81122
81755
  return "send";
@@ -81126,6 +81759,9 @@ function resolveProxyCapability(method, pathname) {
81126
81759
  return "read";
81127
81760
  if (pathname === "/api/community/bots/creation-requests" && method === "POST")
81128
81761
  return "send";
81762
+ if (SCHEDULE_EVENTS_PROXY_PATH_RE.test(pathname)) {
81763
+ return method === "GET" ? "read" : "send";
81764
+ }
81129
81765
  if ((method === "GET" || method === "PATCH") && pathname === communityProxyRoutes.profile || method === "POST" && pathname === communityProxyRoutes.avatar)
81130
81766
  return "profile";
81131
81767
  if (pathname.includes("/attachment"))
@@ -81200,6 +81836,22 @@ function resolveProxyAuditOperation(pathname, method) {
81200
81836
  return "profileAvatarUpdate";
81201
81837
  if (/^\/api\/community\/bots\/me\/nap(\/|$|\?)/.test(canonical))
81202
81838
  return "nap";
81839
+ if (/^\/api\/community\/schedule\/events$/.test(canonical)) {
81840
+ if (method === "GET")
81841
+ return "scheduleList";
81842
+ if (method === "POST")
81843
+ return "scheduleCreate";
81844
+ return null;
81845
+ }
81846
+ if (/^\/api\/community\/schedule\/events\/[^/]+$/.test(canonical)) {
81847
+ if (method === "GET")
81848
+ return "scheduleGet";
81849
+ if (method === "PATCH")
81850
+ return "scheduleUpdate";
81851
+ if (method === "DELETE")
81852
+ return "scheduleDelete";
81853
+ return null;
81854
+ }
81203
81855
  return null;
81204
81856
  }
81205
81857
  function propertyAuditMetadata(method, pathname, requestUrl) {
@@ -81210,6 +81862,7 @@ function propertyAuditMetadata(method, pathname, requestUrl) {
81210
81862
  }
81211
81863
  function resolveProxyRoute(pathname, method, requestUrl = pathname) {
81212
81864
  return {
81865
+ canonicalCommunityDoor: isCanonicalCommunityProxyPath(pathname),
81213
81866
  capability: resolveProxyCapability(method ?? "", pathname),
81214
81867
  auditOperation: resolveProxyAuditOperation(pathname, method),
81215
81868
  propertyMetadata: propertyAuditMetadata(method ?? "", pathname, requestUrl),
@@ -81910,8 +82563,7 @@ async function startCredentialProxy(broker, options = {}) {
81910
82563
  writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
81911
82564
  return;
81912
82565
  }
81913
- const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81914
- if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
82566
+ if (pathname === "/api" || pathname.startsWith("/api/") && !route.canonicalCommunityDoor) {
81915
82567
  res.writeHead(404, { "content-type": "application/json" });
81916
82568
  res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
81917
82569
  req.resume();