@alook/daemon 0.1.71 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli/index.js +1243 -466
  2. package/dist/index.js +977 -463
  3. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -13521,13 +13521,13 @@ var require_sourcemap_codec_umd = __commonJS((exports, module) => {
13521
13521
  });
13522
13522
  });
13523
13523
 
13524
- // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13524
+ // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.3/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13525
13525
  var require_resolve_uri_umd = __commonJS((exports, module) => {
13526
13526
  (function(global, factory) {
13527
13527
  typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.resolveURI = factory());
13528
13528
  })(exports, function() {
13529
13529
  const schemeRegex = /^[\w+.-]+:\/\//;
13530
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13530
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?(\[[^\]]+\]|[^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13531
13531
  const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
13532
13532
  function isAbsoluteUrl(input2) {
13533
13533
  return schemeRegex.test(input2);
@@ -24216,9 +24216,11 @@ function parseNativeExecution(data) {
24216
24216
 
24217
24217
  class NativeExecutionReader {
24218
24218
  readRows;
24219
+ continuations;
24219
24220
  path;
24220
- constructor(home, sessionId, readRows = queryExecutionRows) {
24221
+ constructor(home, sessionId, readRows = queryExecutionRows, continuations = false) {
24221
24222
  this.readRows = readRows;
24223
+ this.continuations = continuations;
24222
24224
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
24223
24225
  throw new Error("Invalid native execution session identity");
24224
24226
  this.path = join4(home, "antigravity-cli", "conversations", `${sessionId}.db`);
@@ -24234,20 +24236,28 @@ class NativeExecutionReader {
24234
24236
  return { index: row.idx, executionId: execution.executionId, lastStepIndex: execution.lastStepIndex };
24235
24237
  }
24236
24238
  async terminal(checkpoint) {
24237
- const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex);
24238
- if (rows.length !== 1)
24239
+ const max = this.continuations ? 32 : 1;
24240
+ const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex, undefined, max + 1);
24241
+ if (!rows.length || rows.length > max)
24239
24242
  throw new Error("Native execution terminal unavailable or ambiguous");
24240
- const row = this.validate(rows[0]);
24241
- const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
24242
- if (row.has_children !== 0)
24243
- throw new Error("Native executor subtrajectory ownership cannot be verified");
24244
- if (row.idx !== checkpoint.index + 1 || execution.executionId === checkpoint.executionId)
24245
- throw new Error("Native execution terminal does not belong to the new root");
24246
- if (execution.hasError || execution.reason === 1)
24247
- return "failed";
24248
- if (execution.reason === 2)
24249
- return "interrupted";
24250
- return execution.reason === 4 ? "success" : "failed";
24243
+ let lastStep = checkpoint.lastStepIndex;
24244
+ const identities = new Set([checkpoint.executionId]);
24245
+ let outcome = "success";
24246
+ for (let index = 0;index < rows.length; index++) {
24247
+ const row = this.validate(rows[index]);
24248
+ const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
24249
+ if (row.has_children !== 0)
24250
+ throw new Error("Native executor subtrajectory ownership cannot be verified");
24251
+ if (row.idx !== checkpoint.index + index + 1 || identities.has(execution.executionId) || this.continuations && execution.lastStepIndex <= lastStep)
24252
+ throw new Error("Native execution terminal does not belong to the new root");
24253
+ identities.add(execution.executionId);
24254
+ lastStep = execution.lastStepIndex;
24255
+ if (execution.hasError || execution.reason !== 2 && execution.reason !== 4)
24256
+ outcome = "failed";
24257
+ else if (execution.reason === 2 && outcome !== "failed")
24258
+ outcome = "interrupted";
24259
+ }
24260
+ return outcome;
24251
24261
  }
24252
24262
  validate(row) {
24253
24263
  if (!Number.isSafeInteger(row.idx) || row.idx < 0 || !/^(?:[a-f0-9]{2})+$/i.test(row.data) || row.data.length > 2 * 1024 * 1024)
@@ -24269,10 +24279,12 @@ async function openNativeExecutionDatabase(path4, loadBuiltin = async () => {
24269
24279
  }
24270
24280
  return new sqlite.DatabaseSync(path4, { readOnly: true });
24271
24281
  }
24272
- async function queryExecutionRows(path4, after, afterStep = -1, openDatabase = openNativeExecutionDatabase) {
24282
+ async function queryExecutionRows(path4, after, afterStep = -1, openDatabase = openNativeExecutionDatabase, maxRows = 2) {
24273
24283
  if (after !== undefined && (!Number.isSafeInteger(after) || after < -1) || !Number.isSafeInteger(afterStep) || afterStep < -1)
24274
24284
  throw new Error("Invalid native execution cursor");
24275
- const query = `SELECT idx,hex(substr(data,1,1048577)) AS data,${after === undefined ? "(SELECT EXISTS(SELECT 1 FROM steps WHERE idx<0 AND has_subtrajectory=1))" : `(SELECT EXISTS(SELECT 1 FROM steps WHERE idx>${afterStep} AND has_subtrajectory=1))`} AS has_children FROM executor_metadata ${after === undefined ? "ORDER BY idx DESC LIMIT 1" : `WHERE idx>${after} ORDER BY idx LIMIT 2`}`;
24285
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows > 33)
24286
+ throw new Error("Invalid native execution read limit");
24287
+ const query = `SELECT idx,hex(substr(data,1,1048577)) AS data,${after === undefined ? "(SELECT EXISTS(SELECT 1 FROM steps WHERE idx<0 AND has_subtrajectory=1))" : `(SELECT EXISTS(SELECT 1 FROM steps WHERE idx>${afterStep} AND has_subtrajectory=1))`} AS has_children FROM executor_metadata ${after === undefined ? "ORDER BY idx DESC LIMIT 1" : `WHERE idx>${after} ORDER BY idx LIMIT ${maxRows}`}`;
24276
24288
  const db = await openDatabase(path4);
24277
24289
  try {
24278
24290
  return db.prepare(query).all();
@@ -24281,6 +24293,37 @@ async function queryExecutionRows(path4, after, afterStep = -1, openDatabase = o
24281
24293
  }
24282
24294
  }
24283
24295
 
24296
+ class NativeSessionActivityReader {
24297
+ sessionId;
24298
+ version;
24299
+ openDatabase;
24300
+ path;
24301
+ constructor(home, sessionId, version, openDatabase = openNativeExecutionDatabase) {
24302
+ this.sessionId = sessionId;
24303
+ this.version = version;
24304
+ this.openDatabase = openDatabase;
24305
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
24306
+ throw new Error("Invalid native activity session identity");
24307
+ this.path = join4(home, "antigravity-cli", "conversation_summaries.db");
24308
+ }
24309
+ async activity() {
24310
+ if (this.version !== "1.5.16")
24311
+ return "unknown";
24312
+ const db = await this.openDatabase(this.path);
24313
+ try {
24314
+ const rows = db.prepare("SELECT status,not_fully_idle FROM conversation_summaries WHERE conversation_id = ? LIMIT 1").all(this.sessionId);
24315
+ const row = rows[0];
24316
+ if (!row || row.not_fully_idle !== 0 && row.not_fully_idle !== 1)
24317
+ return "unknown";
24318
+ if (row.status === "CASCADE_RUN_STATUS_RUNNING")
24319
+ return "running";
24320
+ return row.status === "CASCADE_RUN_STATUS_IDLE" ? row.not_fully_idle ? "running" : "idle" : "unknown";
24321
+ } finally {
24322
+ db.close();
24323
+ }
24324
+ }
24325
+ }
24326
+
24284
24327
  // agent-driver/dist/internal/model-observation.js
24285
24328
  function id(value) {
24286
24329
  if (typeof value !== "string")
@@ -24498,6 +24541,18 @@ class AgyAcpLane {
24498
24541
  events = new EventEmitter;
24499
24542
  pending = new Map;
24500
24543
  toolCalls = new Map;
24544
+ completedTools = new Set;
24545
+ unownedContent = false;
24546
+ activityReader;
24547
+ activityRead;
24548
+ activityTimer;
24549
+ nativeActivity = "unknown";
24550
+ publishedActivity;
24551
+ activityRevision = 0;
24552
+ nativeVersion = "";
24553
+ contentOwner;
24554
+ executionIsolated = true;
24555
+ nativeClose = false;
24501
24556
  process = null;
24502
24557
  requestSequence = 0;
24503
24558
  started = false;
@@ -24573,10 +24628,13 @@ class AgyAcpLane {
24573
24628
  const sessionId = this.sessionId;
24574
24629
  if (!sessionId)
24575
24630
  throw new Error("Agy ACP handshake completed without a session id");
24576
- this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId);
24631
+ this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, this.nativeVersion === "1.5.16");
24577
24632
  this.processActivated = true;
24578
24633
  this.ready = true;
24579
24634
  this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input.sessionId ? "resumed" : "created", evidence: "native_api" } });
24635
+ this.activityReader = this.options.activityReader ?? new NativeSessionActivityReader(this.stateHome, sessionId, this.nativeVersion);
24636
+ await this.refreshActivity();
24637
+ this.scheduleActivity();
24580
24638
  const admission = await this.admitRoot(input.text, input.inputs);
24581
24639
  if (!admission.ok)
24582
24640
  throw new AgyAcpIncompatibleError(admission.error ?? "Native execution state unavailable");
@@ -24621,6 +24679,7 @@ class AgyAcpLane {
24621
24679
  stop(input = {}) {
24622
24680
  this.requestedStopReason ??= input.reason ?? "requested_stop";
24623
24681
  this.ready = false;
24682
+ this.clearActivityTimer();
24624
24683
  this.currentPromptRequestId = null;
24625
24684
  this.terminalOwner = null;
24626
24685
  this.toolCalls.clear();
@@ -24628,30 +24687,34 @@ class AgyAcpLane {
24628
24687
  this.promptOutcomes.clear();
24629
24688
  this.observedPrompts.clear();
24630
24689
  this.usage.reset();
24631
- const waiter = this.configWaiter;
24632
- if (waiter) {
24633
- clearTimeout(waiter.timer);
24634
- this.configWaiter = undefined;
24635
- waiter.reject(new Error("Antigravity CLI lane stopped"));
24636
- }
24690
+ this.rejectConfigWaiter(new Error("Antigravity CLI lane stopped"));
24637
24691
  this.stopPromise ??= this.stopPhysicalOnce(input);
24638
24692
  return this.stopPromise;
24639
24693
  }
24640
24694
  async stopPhysicalOnce(input) {
24695
+ const deadline = Date.now() + (input.forceAfterMs ?? SESSION_STOP_GRACE_MS);
24641
24696
  await this.spawnPromise?.catch(() => {
24642
24697
  return;
24643
24698
  });
24644
24699
  const proc = this.process;
24645
24700
  if (!proc)
24646
24701
  return;
24702
+ let closeAcknowledged = false;
24703
+ if (this.nativeClose && this.sessionId && !this.isClosed() && deadline > Date.now()) {
24704
+ try {
24705
+ await this.request("session/close", { sessionId: this.sessionId }, Math.max(1, deadline - Date.now())).promise;
24706
+ closeAcknowledged = true;
24707
+ } catch {}
24708
+ }
24647
24709
  if (proc.pid) {
24648
- await killProcessTree(proc.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });
24710
+ await killProcessTree(proc.pid, { graceMs: closeAcknowledged ? 0 : Math.max(0, deadline - Date.now()) });
24649
24711
  } else if (!this.isClosed()) {
24650
24712
  proc.kill(input.signal ?? "SIGTERM");
24651
24713
  }
24652
24714
  await this.executionRead?.catch(() => {
24653
24715
  return;
24654
24716
  });
24717
+ await this.activityRead;
24655
24718
  }
24656
24719
  async handshake(ctx) {
24657
24720
  const initialize = record2(await this.call("initialize", {
@@ -24666,6 +24729,7 @@ class AgyAcpLane {
24666
24729
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support protocol version 1");
24667
24730
  }
24668
24731
  const capabilities = record2(initialize.agentCapabilities);
24732
+ this.nativeClose = record2(record2(capabilities?.sessionCapabilities)?.close) !== null;
24669
24733
  if (capabilities?.loadSession !== true) {
24670
24734
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support persistent session loading");
24671
24735
  }
@@ -24673,6 +24737,7 @@ class AgyAcpLane {
24673
24737
  throw new AgyAcpIncompatibleError("Expected the native Antigravity CLI ACP server");
24674
24738
  }
24675
24739
  const version = record2(initialize.agentInfo)?.version;
24740
+ this.nativeVersion = typeof version === "string" ? version : "";
24676
24741
  this.usageProfile = version === "1.4.12" ? { inputIncludesCache: true, outputIncludesReasoning: false } : version === "1.5.9" ? { inputIncludesCache: false, outputIncludesReasoning: true } : undefined;
24677
24742
  if (!record2(record2(initialize.agentCapabilities)?.sessionCapabilities)?.resume) {
24678
24743
  throw new AgyAcpIncompatibleError("Antigravity CLI ACP does not support native session resume");
@@ -24879,6 +24944,7 @@ class AgyAcpLane {
24879
24944
  if (!this.ready || this.requestedStopReason || this.isClosed())
24880
24945
  return { ok: false, reason: "closed" };
24881
24946
  this.executionCheckpoint = checkpoint;
24947
+ this.executionIsolated = !this.unownedContent && !this.hasPendingTools();
24882
24948
  return this.admitPrompt(text, "prompt", inputs);
24883
24949
  } catch {
24884
24950
  return { ok: false, reason: "runtime_error", error: "Antigravity CLI native execution state cannot be verified. A readable native conversation database and the packaged SQLite runtime are required." };
@@ -24905,7 +24971,7 @@ class AgyAcpLane {
24905
24971
  this.terminalOwner = prompt.receipt;
24906
24972
  this.currentPromptRequestId = requestId;
24907
24973
  if (delivery === "prompt") {
24908
- this.toolCalls.clear();
24974
+ this.contentOwner = !this.unownedContent && !this.hasPendingTools() ? prompt.receipt : undefined;
24909
24975
  this.promptOutcomes.clear();
24910
24976
  this.observedPrompts.clear();
24911
24977
  this.loopStartedAt = new Date().toISOString();
@@ -24972,13 +25038,22 @@ class AgyAcpLane {
24972
25038
  const read = this.executionReader.terminal(this.executionCheckpoint);
24973
25039
  this.executionRead = read;
24974
25040
  nativeOutcome = await read;
25041
+ if (!this.executionIsolated)
25042
+ nativeOutcome = "unknown";
24975
25043
  } catch {
24976
- verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
25044
+ if (this.executionIsolated)
25045
+ verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
25046
+ else
25047
+ nativeOutcome = "unknown";
24977
25048
  } finally {
24978
25049
  this.executionRead = undefined;
24979
25050
  }
24980
25051
  if (this.terminalOwner !== owner || this.requestedStopReason || this.processTerminal)
24981
25052
  return;
25053
+ if (this.hasPendingTools())
25054
+ this.unownedContent = true;
25055
+ this.observeOutsideWork();
25056
+ this.refreshActivity();
24982
25057
  this.finishing = false;
24983
25058
  const outcomes = [...this.promptOutcomes].sort(([a], [b]) => b - a);
24984
25059
  let latest = outcomes.find(([, outcome]) => outcome.error)?.[1] ?? outcomes[0]?.[1];
@@ -25011,7 +25086,7 @@ class AgyAcpLane {
25011
25086
  this.usage.reset();
25012
25087
  this.currentPromptRequestId = null;
25013
25088
  this.terminalOwner = null;
25014
- this.toolCalls.clear();
25089
+ this.contentOwner = undefined;
25015
25090
  this.promptOutcomes.clear();
25016
25091
  this.observedPrompts.clear();
25017
25092
  if (!latest) {
@@ -25023,7 +25098,7 @@ class AgyAcpLane {
25023
25098
  kind: "turn_end",
25024
25099
  sessionId: this.sessionId ?? undefined,
25025
25100
  turnOwner: terminalOwner,
25026
- outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? "success" : "failed",
25101
+ outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? nativeOutcome === "unknown" ? "unknown" : "success" : "failed",
25027
25102
  stopReason: latest?.stopReason,
25028
25103
  ...latest?.stopReason === "cancelled" ? { pendingContent: "discard" } : {}
25029
25104
  });
@@ -25115,6 +25190,8 @@ class AgyAcpLane {
25115
25190
  }
25116
25191
  this.processTerminal = true;
25117
25192
  this.ready = false;
25193
+ this.clearActivityTimer();
25194
+ this.rejectConfigWaiter(normalized);
25118
25195
  this.currentPromptRequestId = null;
25119
25196
  this.terminalOwner = null;
25120
25197
  this.toolCalls.clear();
@@ -25134,10 +25211,13 @@ class AgyAcpLane {
25134
25211
  return;
25135
25212
  this.processTerminal = true;
25136
25213
  this.ready = false;
25214
+ this.clearActivityTimer();
25215
+ const exitError = new Error("Agy ACP process exited");
25216
+ this.rejectConfigWaiter(exitError);
25137
25217
  this.currentPromptRequestId = null;
25138
25218
  this.terminalOwner = null;
25139
25219
  this.toolCalls.clear();
25140
- this.rejectAllPending(new Error("Agy ACP process exited"));
25220
+ this.rejectAllPending(exitError);
25141
25221
  if (this.suppressExit || !this.processActivated)
25142
25222
  return;
25143
25223
  this.events.emit("exit", {
@@ -25255,24 +25335,38 @@ class AgyAcpLane {
25255
25335
  this.rememberConfig(configuration, true);
25256
25336
  return;
25257
25337
  }
25258
- if (!this.ready || this.currentPromptRequestId === null) {
25259
- this.diagnostic("warning", "Agy ACP emitted a session update without an active prompt");
25338
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
25260
25339
  return;
25261
- }
25262
25340
  const update = record2(payload.update) ?? {};
25263
25341
  const updateType = update?.sessionUpdate;
25264
25342
  switch (updateType) {
25265
25343
  case "agent_message_chunk": {
25266
25344
  const content = record2(update.content);
25267
25345
  if (content?.type === "text" && typeof content.text === "string") {
25268
- this.events.emit("runtime_event", { kind: "assistant_message_delta", text: content.text });
25346
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
25347
+ this.unownedContent = true;
25348
+ this.observeOutsideWork();
25349
+ }
25350
+ this.events.emit("runtime_event", {
25351
+ kind: "assistant_message_delta",
25352
+ text: content.text,
25353
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
25354
+ });
25269
25355
  }
25270
25356
  return;
25271
25357
  }
25272
25358
  case "agent_thought_chunk": {
25273
25359
  const content = record2(update.content);
25274
25360
  if (content?.type === "text" && typeof content.text === "string") {
25275
- this.events.emit("runtime_event", { kind: "assistant_reasoning_delta", text: content.text });
25361
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
25362
+ this.unownedContent = true;
25363
+ this.observeOutsideWork();
25364
+ }
25365
+ this.events.emit("runtime_event", {
25366
+ kind: "assistant_reasoning_delta",
25367
+ text: content.text,
25368
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
25369
+ });
25276
25370
  }
25277
25371
  return;
25278
25372
  }
@@ -25296,56 +25390,67 @@ class AgyAcpLane {
25296
25390
  this.diagnostic("warning", "Agy ACP emitted a malformed tool_call update");
25297
25391
  return;
25298
25392
  }
25299
- if (!this.toolCalls.has(update.toolCallId)) {
25300
- const name = typeof update.name === "string" ? update.name : update.title;
25301
- this.toolCalls.set(update.toolCallId, name);
25393
+ if (this.completedTools.has(update.toolCallId))
25394
+ return;
25395
+ let tool = this.toolCalls.get(update.toolCallId);
25396
+ if (!tool) {
25397
+ tool = {
25398
+ name: typeof update.name === "string" ? update.name : update.title,
25399
+ owner: this.contentOwner
25400
+ };
25401
+ this.toolCalls.set(update.toolCallId, tool);
25302
25402
  this.events.emit("runtime_event", {
25303
25403
  kind: "tool_call",
25304
25404
  callId: update.toolCallId,
25305
- name,
25306
- input: update.rawInput
25307
- });
25308
- }
25309
- if ((update.status === "completed" || update.status === "failed") && this.toolCalls.get(update.toolCallId) !== null) {
25310
- const name = this.toolCalls.get(update.toolCallId) ?? update.title;
25311
- this.toolCalls.set(update.toolCallId, null);
25312
- this.events.emit("runtime_event", {
25313
- kind: "tool_output",
25314
- callId: update.toolCallId,
25315
- name,
25316
- outcome: update.status === "failed" ? "failed" : "success",
25317
- output: update.rawOutput
25405
+ name: tool.name,
25406
+ input: update.rawInput,
25407
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
25318
25408
  });
25319
25409
  }
25410
+ this.observeOutsideWork();
25411
+ if (update.status === "completed" || update.status === "failed")
25412
+ this.finishTool(update, tool);
25320
25413
  return;
25321
25414
  }
25322
25415
  case "tool_call_update": {
25323
- if (typeof update.toolCallId === "string" && (update.status === "completed" || update.status === "failed")) {
25324
- const name = this.toolCalls.get(update.toolCallId);
25325
- if (name === undefined || name === null)
25326
- return;
25327
- this.toolCalls.set(update.toolCallId, null);
25328
- this.events.emit("runtime_event", {
25329
- kind: "tool_output",
25330
- callId: update.toolCallId,
25331
- outcome: update.status === "failed" ? "failed" : "success",
25332
- output: update.rawOutput,
25333
- name
25334
- });
25335
- }
25416
+ if (typeof update.toolCallId !== "string")
25417
+ return;
25418
+ const tool = this.toolCalls.get(update.toolCallId);
25419
+ if (!tool)
25420
+ return;
25421
+ if (update.status === "completed" || update.status === "failed")
25422
+ this.finishTool(update, tool);
25336
25423
  return;
25337
25424
  }
25338
25425
  case "plan":
25339
25426
  this.events.emit("runtime_event", {
25340
25427
  kind: "internal_progress",
25341
25428
  source: "agy.acp",
25342
- itemType: "plan"
25429
+ itemType: "plan",
25430
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
25343
25431
  });
25344
25432
  return;
25345
25433
  default:
25346
25434
  this.diagnostic("warning", `Unsupported Agy ACP session update: ${safeLabel(updateType)}`);
25347
25435
  }
25348
25436
  }
25437
+ finishTool(update, tool) {
25438
+ this.toolCalls.delete(update.toolCallId);
25439
+ this.completedTools.add(update.toolCallId);
25440
+ if (this.completedTools.size > 4096)
25441
+ this.completedTools.delete(this.completedTools.values().next().value);
25442
+ if (!tool.owner || tool.owner !== this.terminalOwner)
25443
+ this.unownedContent = true;
25444
+ this.observeOutsideWork();
25445
+ this.events.emit("runtime_event", {
25446
+ kind: "tool_output",
25447
+ callId: update.toolCallId,
25448
+ name: tool.name,
25449
+ outcome: update.status === "failed" ? "failed" : "success",
25450
+ output: update.rawOutput ?? update.content,
25451
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
25452
+ });
25453
+ }
25349
25454
  diagnostic(severity, message) {
25350
25455
  this.events.emit("runtime_event", {
25351
25456
  kind: "runtime_diagnostic",
@@ -25354,6 +25459,72 @@ class AgyAcpLane {
25354
25459
  message
25355
25460
  });
25356
25461
  }
25462
+ hasPendingTools() {
25463
+ return this.toolCalls.size > 0;
25464
+ }
25465
+ publishActivity() {
25466
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
25467
+ return;
25468
+ const status = this.hasPendingTools() ? "running" : this.nativeActivity;
25469
+ if (status === this.publishedActivity)
25470
+ return;
25471
+ this.publishedActivity = status;
25472
+ this.events.emit("runtime_event", { kind: "session_activity", observation: { status, source: "agy.native" } });
25473
+ }
25474
+ observeOutsideWork() {
25475
+ this.activityRevision += 1;
25476
+ this.nativeActivity = "unknown";
25477
+ this.publishActivity();
25478
+ }
25479
+ refreshActivity() {
25480
+ if (this.activityRead)
25481
+ return this.activityRead;
25482
+ if (!this.ready || !this.activityReader || this.requestedStopReason || this.processTerminal)
25483
+ return Promise.resolve();
25484
+ const revision = this.activityRevision;
25485
+ const reading = (async () => {
25486
+ let status = "unknown";
25487
+ try {
25488
+ status = await this.activityReader.activity();
25489
+ } catch {}
25490
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
25491
+ return;
25492
+ if (revision === this.activityRevision)
25493
+ this.nativeActivity = status;
25494
+ if (status === "running" && this.currentPromptRequestId === null)
25495
+ this.unownedContent = true;
25496
+ this.publishActivity();
25497
+ })();
25498
+ this.activityRead = reading;
25499
+ reading.finally(() => {
25500
+ if (this.activityRead === reading)
25501
+ this.activityRead = undefined;
25502
+ });
25503
+ return reading;
25504
+ }
25505
+ clearActivityTimer() {
25506
+ if (!this.activityTimer)
25507
+ return;
25508
+ clearTimeout(this.activityTimer);
25509
+ this.activityTimer = undefined;
25510
+ }
25511
+ rejectConfigWaiter(error) {
25512
+ const waiter = this.configWaiter;
25513
+ if (!waiter)
25514
+ return;
25515
+ clearTimeout(waiter.timer);
25516
+ this.configWaiter = undefined;
25517
+ waiter.reject(error);
25518
+ }
25519
+ scheduleActivity() {
25520
+ if (!this.ready || this.requestedStopReason || this.processTerminal || this.activityTimer)
25521
+ return;
25522
+ this.activityTimer = setTimeout(() => {
25523
+ this.activityTimer = undefined;
25524
+ this.refreshActivity().then(() => this.scheduleActivity());
25525
+ }, this.options.activityPollMs ?? 1000);
25526
+ this.activityTimer.unref?.();
25527
+ }
25357
25528
  protocolFailure(message) {
25358
25529
  const error = new Error(message);
25359
25530
  this.rejectAllPending(error);
@@ -35356,6 +35527,10 @@ class LogicalAgentSession {
35356
35527
  events;
35357
35528
  closed;
35358
35529
  state = "new";
35530
+ activity;
35531
+ sessionMessage = emptySemanticAssembler();
35532
+ sessionReasoning = emptySemanticAssembler();
35533
+ sessionContentTimer;
35359
35534
  backendSessionId;
35360
35535
  acquisition;
35361
35536
  configuration;
@@ -35556,11 +35731,12 @@ class LogicalAgentSession {
35556
35731
  }
35557
35732
  snapshot() {
35558
35733
  return {
35734
+ ...this.activity ? { activity: this.activity } : {},
35559
35735
  ...this.acquisition ? { acquisition: this.acquisition } : {},
35560
35736
  ...this.configuration ? { configuration: this.configuration } : {},
35561
35737
  ...this.observedModel ? { observedModel: { ...this.observedModel } } : {},
35562
35738
  sessionInstanceId: this.sessionInstanceId,
35563
- state: this.state,
35739
+ state: this.state === "idle" && this.activity && this.activity.status === "running" ? "working" : this.state,
35564
35740
  backendSessionId: this.backendSessionId,
35565
35741
  activeTurn: this.activeTurn ? { turnId: this.activeTurn.turnId, commandIds: this.activeTurn.commandIds } : undefined,
35566
35742
  queuedCommands: this.queued.map(({ message }) => ({
@@ -35886,6 +36062,13 @@ class LogicalAgentSession {
35886
36062
  return;
35887
36063
  if (this.isClosedPerTurnLaneTail(physicalOwner, generation))
35888
36064
  return;
36065
+ if (event.kind === "session_activity") {
36066
+ if (event.observation.status === "idle")
36067
+ this.flushSessionContent();
36068
+ this.activity = event.observation;
36069
+ this.emit({ type: "session_activity", observation: event.observation });
36070
+ return;
36071
+ }
35889
36072
  const observation = event.kind === "model_observed" ? modelObservation(event.observation.model, event.observation.source, event.observation.provider, event.observation.responseId) : event.kind === "configuration_observed" && event.observation.evidence === "observed" && event.observation.effective === "current" ? modelObservation(event.observation.model, "session") : undefined;
35890
36073
  if (observation)
35891
36074
  this.emit({
@@ -35896,7 +36079,19 @@ class LogicalAgentSession {
35896
36079
  });
35897
36080
  if (event.kind === "model_observed")
35898
36081
  return;
35899
- if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown") {
36082
+ if (event.attribution?.scope === "session" && (event.kind === "assistant_message_delta" || event.kind === "assistant_reasoning_delta")) {
36083
+ appendSemanticFragment(event.kind === "assistant_message_delta" ? this.sessionMessage : this.sessionReasoning, event.text);
36084
+ if (event.text && !this.sessionContentTimer) {
36085
+ this.sessionContentTimer = setTimeout(() => {
36086
+ this.sessionContentTimer = undefined;
36087
+ if (this.state !== "closed" && this.state !== "stopping")
36088
+ this.flushSessionContent();
36089
+ }, 500);
36090
+ this.sessionContentTimer.unref?.();
36091
+ }
36092
+ return;
36093
+ }
36094
+ if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown" || event.attribution?.scope === "session") {
35900
36095
  this.emit({
35901
36096
  type: "activity",
35902
36097
  attribution: event.attribution,
@@ -35904,6 +36099,7 @@ class LogicalAgentSession {
35904
36099
  ..."text" in event ? { text: boundedSemanticCompletion(event.text).text } : {},
35905
36100
  ..."callId" in event ? { callId: event.callId } : {},
35906
36101
  ..."name" in event ? { name: event.name } : {},
36102
+ ..."input" in event ? { input: jsonValue(event.input) } : {},
35907
36103
  ..."outcome" in event ? { outcome: event.outcome } : {},
35908
36104
  ..."output" in event ? { output: jsonValue(event.output) } : {}
35909
36105
  });
@@ -36114,10 +36310,23 @@ class LogicalAgentSession {
36114
36310
  this.emit({ type: "assistant_message_completed", turnId, ...message });
36115
36311
  }
36116
36312
  }
36313
+ this.flushSessionContent();
36117
36314
  this.completeTurn(event.sessionId, physicalOwner, generation, event.turnOwner);
36118
36315
  return;
36119
36316
  }
36120
36317
  }
36318
+ flushSessionContent() {
36319
+ if (this.sessionContentTimer)
36320
+ clearTimeout(this.sessionContentTimer);
36321
+ this.sessionContentTimer = undefined;
36322
+ for (const [kind, buffer] of [["assistant_reasoning_completed", this.sessionReasoning], ["assistant_message_completed", this.sessionMessage]]) {
36323
+ const completion = finishSemanticAssembler(buffer);
36324
+ if (completion.text)
36325
+ this.emit({ type: "activity", attribution: { scope: "session" }, kind, ...completion });
36326
+ }
36327
+ this.sessionMessage = emptySemanticAssembler();
36328
+ this.sessionReasoning = emptySemanticAssembler();
36329
+ }
36121
36330
  isClosedPerTurnLaneTail(physicalOwner, generation) {
36122
36331
  if (this.adapter.execution.lifetime !== "turn" || this.activeTurn)
36123
36332
  return false;
@@ -36645,6 +36854,7 @@ class LogicalAgentSession {
36645
36854
  const cleanup = hostCleanup.status === "failed" || hostCleanup.status === "timed_out" ? hostCleanup : this.laneCleanupFailure ?? hostCleanup;
36646
36855
  const result = buildResult(cleanup);
36647
36856
  this.terminalResult = result;
36857
+ this.flushSessionContent();
36648
36858
  this.state = "closed";
36649
36859
  this.emit({ type: "session_closed", result });
36650
36860
  this.eventQueue.close();
@@ -38508,7 +38718,10 @@ function compactTraceData(data) {
38508
38718
  }
38509
38719
  // src/manager/managerPolicy.ts
38510
38720
  function isActivelyWorking(agent) {
38511
- return agent.status === "running" && (leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
38721
+ return agent.status === "running" && (agent.sessionActivity?.status === "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
38722
+ }
38723
+ function sessionBlocksIdleCleanup(agent) {
38724
+ return agent.sessionActivity !== undefined && agent.sessionActivity.status !== "idle";
38512
38725
  }
38513
38726
  var DEFAULT_STALE_THRESHOLD_MS = 120000;
38514
38727
  var DEFAULT_TURN_SILENCE_POLICY = {
@@ -38534,6 +38747,19 @@ function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS
38534
38747
  }
38535
38748
  function reduceManager(state, event) {
38536
38749
  switch (event.type) {
38750
+ case "session_activity": {
38751
+ const current = state.agents[event.agentId];
38752
+ if (!current || !matchesSession(current, event.sessionInstanceId) || current.status === "stopping")
38753
+ return { state, effects: [] };
38754
+ const agent = clone(current);
38755
+ const changed = agent.sessionActivity?.status !== event.observation.status;
38756
+ agent.sessionActivity = event.observation;
38757
+ if (sessionBlocksIdleCleanup(agent))
38758
+ agent.idleSince = null;
38759
+ else if (changed && !leaseIsWorking(agent.execution.lease) && agent.pendingAdmissions.length === 0 && agent.inbox.length === 0)
38760
+ agent.idleSince = event.nowMs;
38761
+ return commit(state, agent, []);
38762
+ }
38537
38763
  case "register":
38538
38764
  return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
38539
38765
  case "wake":
@@ -38583,6 +38809,7 @@ function reduceManager(state, event) {
38583
38809
  {
38584
38810
  const a = agent;
38585
38811
  a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
38812
+ a.sessionActivity = undefined;
38586
38813
  a.turnSilence = event.turnSilence ?? {
38587
38814
  ...DEFAULT_TURN_SILENCE_POLICY,
38588
38815
  nativeIdleTimeoutMs: state.staleThresholdMs,
@@ -38784,6 +39011,7 @@ function reduceManager(state, event) {
38784
39011
  const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
38785
39012
  agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
38786
39013
  agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
39014
+ agent.sessionActivity = undefined;
38787
39015
  syncExecutionProjection(agent);
38788
39016
  return commit(state, agent, recoveryEffects(agent, closing));
38789
39017
  }
@@ -38912,7 +39140,7 @@ function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endRe
38912
39140
  ...messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" }))
38913
39141
  ]);
38914
39142
  }
38915
- agent.idleSince = agent.status === "running" && !agent.resetting ? nowMs : null;
39143
+ agent.idleSince = agent.status === "running" && !agent.resetting && !sessionBlocksIdleCleanup(agent) ? nowMs : null;
38916
39144
  return commit(state, agent, clearEffects);
38917
39145
  }
38918
39146
  function onTurnToolLifecycle(state, event, lifecycle) {
@@ -39062,13 +39290,13 @@ function onTick(state, nowMs) {
39062
39290
  effects.push({ type: "force_exit", agentId: id2, reason: "stopping_stuck" });
39063
39291
  continue;
39064
39292
  }
39065
- const idleResetEligible = a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
39293
+ const idleResetEligible = !sessionBlocksIdleCleanup(a) && a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
39066
39294
  if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
39067
39295
  agents[id2] = { ...a, idleSince: nowMs };
39068
39296
  effects.push({ type: "maintain_idle_memory", agentId: id2, sessionId: a.sessionId });
39069
39297
  continue;
39070
39298
  }
39071
- const idleEligible = a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
39299
+ const idleEligible = !sessionBlocksIdleCleanup(a) && a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
39072
39300
  if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
39073
39301
  agents[id2] = { ...a, status: "stopping", stoppingSince: nowMs };
39074
39302
  effects.push({ type: "stop", agentId: id2, reason: "idle_timeout" });
@@ -39102,6 +39330,8 @@ function freshAgent(agentId) {
39102
39330
  }
39103
39331
  function enterStable(agent, status) {
39104
39332
  agent.status = status;
39333
+ if (status === "idle")
39334
+ agent.sessionActivity = undefined;
39105
39335
  agent.resetting = false;
39106
39336
  agent.resettingSince = null;
39107
39337
  agent.stoppingSince = null;
@@ -59094,7 +59324,7 @@ var AgentModelReportSchema = exports_external.object({
59094
59324
  provider: identity2.optional(),
59095
59325
  source: exports_external.enum(["response", "session"]),
59096
59326
  responseId: identity2.optional(),
59097
- observedAt: exports_external.string().datetime({ offset: true })
59327
+ observedAt: exports_external.iso.datetime({ offset: true })
59098
59328
  });
59099
59329
 
59100
59330
  // ../shared/src/community-decision-card.ts
@@ -59208,7 +59438,8 @@ var DecisionCardEmbedSchema = exports_external.strictObject({
59208
59438
  summary: exports_external.string().trim().min(1).max(DECISION_CARD_SUMMARY_MAX_LENGTH).optional(),
59209
59439
  assignees: exports_external.array(DecisionCardAssigneeSchema).max(DECISION_CARD_MAX_MENTIONS),
59210
59440
  questions: exports_external.array(DecisionCardNormalizedQuestionSchema).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS),
59211
- respondedUserIds: exports_external.array(exports_external.string().min(1)).optional()
59441
+ respondedUserIds: exports_external.array(exports_external.string().min(1)).optional(),
59442
+ viewerDismissed: exports_external.boolean().optional()
59212
59443
  });
59213
59444
  var DecisionCardAnswerItemSchema = exports_external.strictObject({
59214
59445
  questionId: idFieldSchema,
@@ -59295,8 +59526,8 @@ var QuotaLimitSchema = exports_external.object({
59295
59526
  model: QuotaModelIdentitySchema,
59296
59527
  window: QuotaWindowIdentitySchema
59297
59528
  }).strict(),
59298
- usedPercent: exports_external.number().finite().min(0).max(100),
59299
- resetsAt: exports_external.string().datetime({ offset: true }).optional()
59529
+ usedPercent: exports_external.number().min(0).max(100),
59530
+ resetsAt: exports_external.iso.datetime({ offset: true }).optional()
59300
59531
  }).strict();
59301
59532
  function quotaIdentity(limit) {
59302
59533
  const { product, model, window: window2, limitId } = limit.bucket;
@@ -59819,7 +60050,7 @@ var BotAuditEventKindSchema = exports_external.enum([
59819
60050
  var HostBotAuditEventFrameSchema = exports_external.object({
59820
60051
  type: exports_external.literal("bot_audit_event"),
59821
60052
  eventId: exports_external.string().min(1).max(128).optional(),
59822
- occurredAt: exports_external.string().datetime({ offset: true }).optional(),
60053
+ occurredAt: exports_external.iso.datetime({ offset: true }).optional(),
59823
60054
  agentId: exports_external.string().min(1),
59824
60055
  sessionId: exports_external.string().nullable().optional(),
59825
60056
  launchId: exports_external.string().nullable().optional(),
@@ -60074,11 +60305,53 @@ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
60074
60305
  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)))
60075
60306
  ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
60076
60307
  });
60308
+ var CommunityResolvedChannelRefSchema = exports_external.discriminatedUnion("status", [
60309
+ exports_external.strictObject({
60310
+ ref: exports_external.string().min(1),
60311
+ status: exports_external.literal("ready"),
60312
+ serverId: id2,
60313
+ channelId: id2
60314
+ }),
60315
+ exports_external.strictObject({
60316
+ ref: exports_external.string().min(1),
60317
+ status: exports_external.enum(["forbidden", "missing"])
60318
+ })
60319
+ ]);
60320
+ var CommunityMessageRefsSchema = exports_external.strictObject({
60321
+ servers: exports_external.array(CommunityServerResourceSchema),
60322
+ channels: exports_external.array(CommunityChannelResourceSchema),
60323
+ resolvedRefs: exports_external.array(CommunityResolvedChannelRefSchema)
60324
+ }).superRefine((refs, ctx) => {
60325
+ const serverIds = new Set(refs.servers.map((row) => row.id));
60326
+ const channelById = new Map(refs.channels.map((row) => [row.id, row]));
60327
+ const refKeys = new Set(refs.resolvedRefs.map((row) => row.ref));
60328
+ if (serverIds.size !== refs.servers.length || channelById.size !== refs.channels.length || refKeys.size !== refs.resolvedRefs.length) {
60329
+ ctx.addIssue({ code: "custom", message: "Duplicated ref resource" });
60330
+ return;
60331
+ }
60332
+ for (const channel of refs.channels) {
60333
+ if (channel.serverId === null || !serverIds.has(channel.serverId)) {
60334
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel server missing" });
60335
+ }
60336
+ if (channel.parentChannelId !== null && !channelById.has(channel.parentChannelId)) {
60337
+ ctx.addIssue({ code: "custom", path: ["channels"], message: "Ref channel parent missing" });
60338
+ }
60339
+ }
60340
+ for (const resolved of refs.resolvedRefs) {
60341
+ if (resolved.status !== "ready")
60342
+ continue;
60343
+ const channel = channelById.get(resolved.channelId);
60344
+ if (!serverIds.has(resolved.serverId) || !channel || channel.serverId !== resolved.serverId) {
60345
+ ctx.addIssue({ code: "custom", path: ["resolvedRefs"], message: "Resolved ref target missing from resources" });
60346
+ }
60347
+ }
60348
+ });
60077
60349
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
60078
60350
  var CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({
60079
60351
  ...envelope,
60080
60352
  page: CommunityPageSchema,
60081
60353
  relatedMessages: exports_external.array(CommunityMessageResourceSchema).optional(),
60354
+ refs: CommunityMessageRefsSchema.optional(),
60082
60355
  surfaceReceipt: exports_external.strictObject({ channelId: id2, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
60083
60356
  }).superRefine(validateRelatedMessageGraph);
60084
60357
  var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
@@ -60158,7 +60431,13 @@ var CommunityMessageReadSchema = exports_external.strictObject({
60158
60431
  validateRelatedMessageGraph({ messages: [read.message], relatedMessages: read.relatedMessages, profiles: read.profiles }, ctx);
60159
60432
  });
60160
60433
  var CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: exports_external.boolean(), threadId: id2.optional() });
60161
- var CommunityMembersReadSchema = exports_external.strictObject({ ...envelope, relation: exports_external.enum(["access", "notify"]), members: exports_external.array(CommunityMemberRelationSchema), profiles: exports_external.array(CommunityResourceProfileSchema) });
60434
+ var CommunityMembersReadSchema = exports_external.strictObject({
60435
+ ...envelope,
60436
+ relation: exports_external.enum(["access", "notify"]),
60437
+ members: exports_external.array(CommunityMemberRelationSchema),
60438
+ profiles: exports_external.array(CommunityResourceProfileSchema),
60439
+ page: exports_external.strictObject({ nextCursor: exports_external.string().nullable(), hasMore: exports_external.boolean() }).optional()
60440
+ });
60162
60441
  var CommunityThreadsReadSchema = exports_external.strictObject({
60163
60442
  ...envelope,
60164
60443
  channel: CommunityChannelResourceSchema,
@@ -60390,7 +60669,7 @@ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
60390
60669
  var EntitlementValueSchema = exports_external.lazy(() => exports_external.union([
60391
60670
  exports_external.null(),
60392
60671
  exports_external.boolean(),
60393
- exports_external.number().finite(),
60672
+ exports_external.number(),
60394
60673
  exports_external.string(),
60395
60674
  exports_external.array(EntitlementValueSchema),
60396
60675
  exports_external.record(exports_external.string(), EntitlementValueSchema)
@@ -60417,11 +60696,11 @@ var BillingOfferSchema = exports_external.object({
60417
60696
  var BillingSubscriptionSchema = exports_external.object({
60418
60697
  plan: BillingPlanSchema,
60419
60698
  status: exports_external.string().min(1),
60420
- currentPeriodEnd: exports_external.string().datetime().nullable(),
60421
- cancelAt: exports_external.string().datetime().nullable(),
60699
+ currentPeriodEnd: exports_external.iso.datetime().nullable(),
60700
+ cancelAt: exports_external.iso.datetime().nullable(),
60422
60701
  scheduledChange: exports_external.object({
60423
60702
  plan: BillingPlanSchema,
60424
- effectiveAt: exports_external.string().datetime()
60703
+ effectiveAt: exports_external.iso.datetime()
60425
60704
  }).nullable()
60426
60705
  });
60427
60706
  var PublicPricingSchema = exports_external.object({
@@ -60446,7 +60725,7 @@ var BillingPortalRequestSchema = exports_external.strictObject({
60446
60725
  priceId: exports_external.string().min(1).max(255).optional()
60447
60726
  });
60448
60727
  var BillingRedirectResponseSchema = exports_external.object({
60449
- url: exports_external.string().url()
60728
+ url: exports_external.url()
60450
60729
  });
60451
60730
  // ../shared/src/utils/day-key.ts
60452
60731
  function utcDayKey(now) {
@@ -60484,7 +60763,7 @@ function dayKeyInTimeZone(now, timeZone) {
60484
60763
  return `${year}-${month}-${day}`;
60485
60764
  }
60486
60765
 
60487
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/entity.js
60766
+ // ../../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
60488
60767
  var entityKind = Symbol.for("drizzle:entityKind");
60489
60768
  var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
60490
60769
  function is(value, type) {
@@ -60509,7 +60788,7 @@ function is(value, type) {
60509
60788
  return false;
60510
60789
  }
60511
60790
 
60512
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/column.js
60791
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column.js
60513
60792
  class Column {
60514
60793
  constructor(table, config2) {
60515
60794
  this.table = table;
@@ -60559,7 +60838,7 @@ class Column {
60559
60838
  }
60560
60839
  }
60561
60840
 
60562
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/column-builder.js
60841
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column-builder.js
60563
60842
  class ColumnBuilder {
60564
60843
  static [entityKind] = "ColumnBuilder";
60565
60844
  config;
@@ -60615,20 +60894,20 @@ class ColumnBuilder {
60615
60894
  }
60616
60895
  }
60617
60896
 
60618
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/table.utils.js
60897
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.utils.js
60619
60898
  var TableName = Symbol.for("drizzle:Name");
60620
60899
 
60621
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/tracing-utils.js
60900
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing-utils.js
60622
60901
  function iife(fn, ...args) {
60623
60902
  return fn(...args);
60624
60903
  }
60625
60904
 
60626
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/unique-constraint.js
60905
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/unique-constraint.js
60627
60906
  function uniqueKeyName(table, columns) {
60628
60907
  return `${table[TableName]}_${columns.join("_")}_unique`;
60629
60908
  }
60630
60909
 
60631
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/columns/common.js
60910
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/common.js
60632
60911
  class PgColumn extends Column {
60633
60912
  constructor(table, config2) {
60634
60913
  if (!config2.uniqueName) {
@@ -60677,7 +60956,7 @@ class ExtraConfigColumn extends PgColumn {
60677
60956
  }
60678
60957
  }
60679
60958
 
60680
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/pg-core/columns/enum.js
60959
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/enum.js
60681
60960
  class PgEnumObjectColumn extends PgColumn {
60682
60961
  static [entityKind] = "PgEnumObjectColumn";
60683
60962
  enum;
@@ -60707,7 +60986,7 @@ class PgEnumColumn extends PgColumn {
60707
60986
  }
60708
60987
  }
60709
60988
 
60710
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/subquery.js
60989
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/subquery.js
60711
60990
  class Subquery {
60712
60991
  static [entityKind] = "Subquery";
60713
60992
  constructor(sql, fields2, alias, isWith = false, usedTables = []) {
@@ -60722,10 +61001,10 @@ class Subquery {
60722
61001
  }
60723
61002
  }
60724
61003
 
60725
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/version.js
61004
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/version.js
60726
61005
  var version2 = "0.45.4";
60727
61006
 
60728
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/tracing.js
61007
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing.js
60729
61008
  var otel;
60730
61009
  var rawTracer;
60731
61010
  var tracer = {
@@ -60752,10 +61031,10 @@ var tracer = {
60752
61031
  }
60753
61032
  };
60754
61033
 
60755
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/view-common.js
61034
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/view-common.js
60756
61035
  var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
60757
61036
 
60758
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/table.js
61037
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.js
60759
61038
  var Schema = Symbol.for("drizzle:Schema");
60760
61039
  var Columns = Symbol.for("drizzle:Columns");
60761
61040
  var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
@@ -60793,7 +61072,7 @@ class Table {
60793
61072
  }
60794
61073
  }
60795
61074
 
60796
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/sql.js
61075
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/sql.js
60797
61076
  function isSQLWrapper(value) {
60798
61077
  return value !== null && value !== undefined && typeof value.getSQL === "function";
60799
61078
  }
@@ -61156,7 +61435,7 @@ Subquery.prototype.getSQL = function() {
61156
61435
  return new SQL([this]);
61157
61436
  };
61158
61437
 
61159
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/alias.js
61438
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/alias.js
61160
61439
  class ColumnAliasProxyHandler {
61161
61440
  constructor(table) {
61162
61441
  this.table = table;
@@ -61212,7 +61491,7 @@ class TableAliasProxyHandler {
61212
61491
  }
61213
61492
  }
61214
61493
 
61215
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/utils.js
61494
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/utils.js
61216
61495
  function getColumnNameAndConfig(a, b) {
61217
61496
  return {
61218
61497
  name: typeof a === "string" && a.length > 0 ? a : "",
@@ -61221,7 +61500,7 @@ function getColumnNameAndConfig(a, b) {
61221
61500
  }
61222
61501
  var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
61223
61502
 
61224
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/expressions/conditions.js
61503
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/conditions.js
61225
61504
  function bindIfParam(value, column) {
61226
61505
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
61227
61506
  return new Param(value, column);
@@ -61252,7 +61531,7 @@ function isNotNull(value) {
61252
61531
  return sql`${value} is not null`;
61253
61532
  }
61254
61533
 
61255
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sql/expressions/select.js
61534
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/select.js
61256
61535
  function desc(column) {
61257
61536
  return sql`${column} desc`;
61258
61537
  }
@@ -61291,12 +61570,12 @@ __export(exports_community_schema, {
61291
61570
  communityAttachment: () => communityAttachment
61292
61571
  });
61293
61572
 
61294
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/alias.js
61573
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/alias.js
61295
61574
  function alias(table, alias2) {
61296
61575
  return new Proxy(table, new TableAliasProxyHandler(alias2, false));
61297
61576
  }
61298
61577
 
61299
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/checks.js
61578
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/checks.js
61300
61579
  class CheckBuilder {
61301
61580
  constructor(name, value) {
61302
61581
  this.name = name;
@@ -61323,7 +61602,7 @@ function check2(name, value) {
61323
61602
  return new CheckBuilder(name, value);
61324
61603
  }
61325
61604
 
61326
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
61605
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
61327
61606
  class ForeignKeyBuilder {
61328
61607
  static [entityKind] = "SQLiteForeignKeyBuilder";
61329
61608
  reference;
@@ -61377,7 +61656,7 @@ class ForeignKey {
61377
61656
  }
61378
61657
  }
61379
61658
 
61380
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
61659
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
61381
61660
  function uniqueKeyName2(table, columns) {
61382
61661
  return `${table[TableName]}_${columns.join("_")}_unique`;
61383
61662
  }
@@ -61422,7 +61701,7 @@ class UniqueConstraint {
61422
61701
  }
61423
61702
  }
61424
61703
 
61425
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/common.js
61704
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/common.js
61426
61705
  class SQLiteColumnBuilder extends ColumnBuilder {
61427
61706
  static [entityKind] = "SQLiteColumnBuilder";
61428
61707
  foreignKeyConfigs = [];
@@ -61473,7 +61752,7 @@ class SQLiteColumn extends Column {
61473
61752
  static [entityKind] = "SQLiteColumn";
61474
61753
  }
61475
61754
 
61476
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/blob.js
61755
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/blob.js
61477
61756
  class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
61478
61757
  static [entityKind] = "SQLiteBigIntBuilder";
61479
61758
  constructor(name) {
@@ -61561,7 +61840,7 @@ function blob(a, b) {
61561
61840
  return new SQLiteBlobBufferBuilder(name);
61562
61841
  }
61563
61842
 
61564
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/custom.js
61843
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/custom.js
61565
61844
  class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
61566
61845
  static [entityKind] = "SQLiteCustomColumnBuilder";
61567
61846
  constructor(name, fieldConfig, customTypeParams) {
@@ -61602,7 +61881,7 @@ function customType(customTypeParams) {
61602
61881
  };
61603
61882
  }
61604
61883
 
61605
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/integer.js
61884
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/integer.js
61606
61885
  class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
61607
61886
  static [entityKind] = "SQLiteBaseIntegerBuilder";
61608
61887
  constructor(name, dataType, columnType) {
@@ -61704,7 +61983,7 @@ function integer2(a, b) {
61704
61983
  return new SQLiteIntegerBuilder(name);
61705
61984
  }
61706
61985
 
61707
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
61986
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
61708
61987
  class SQLiteNumericBuilder extends SQLiteColumnBuilder {
61709
61988
  static [entityKind] = "SQLiteNumericBuilder";
61710
61989
  constructor(name) {
@@ -61774,7 +62053,7 @@ function numeric(a, b) {
61774
62053
  return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
61775
62054
  }
61776
62055
 
61777
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/real.js
62056
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/real.js
61778
62057
  class SQLiteRealBuilder extends SQLiteColumnBuilder {
61779
62058
  static [entityKind] = "SQLiteRealBuilder";
61780
62059
  constructor(name) {
@@ -61795,7 +62074,7 @@ function real(name) {
61795
62074
  return new SQLiteRealBuilder(name ?? "");
61796
62075
  }
61797
62076
 
61798
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/text.js
62077
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/text.js
61799
62078
  class SQLiteTextBuilder extends SQLiteColumnBuilder {
61800
62079
  static [entityKind] = "SQLiteTextBuilder";
61801
62080
  constructor(name, config2) {
@@ -61850,7 +62129,7 @@ function text2(a, b = {}) {
61850
62129
  return new SQLiteTextBuilder(name, config2);
61851
62130
  }
61852
62131
 
61853
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/columns/all.js
62132
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/all.js
61854
62133
  function getSQLiteColumnBuilders() {
61855
62134
  return {
61856
62135
  blob,
@@ -61862,7 +62141,7 @@ function getSQLiteColumnBuilders() {
61862
62141
  };
61863
62142
  }
61864
62143
 
61865
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/table.js
62144
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/table.js
61866
62145
  var InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
61867
62146
 
61868
62147
  class SQLiteTable extends Table {
@@ -61896,7 +62175,7 @@ var sqliteTable = (name, columns, extraConfig) => {
61896
62175
  return sqliteTableBase(name, columns, extraConfig);
61897
62176
  };
61898
62177
 
61899
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/indexes.js
62178
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/indexes.js
61900
62179
  class IndexBuilderOn {
61901
62180
  constructor(name, unique2) {
61902
62181
  this.name = name;
@@ -61942,7 +62221,7 @@ function uniqueIndex(name) {
61942
62221
  return new IndexBuilderOn(name, true);
61943
62222
  }
61944
62223
 
61945
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261114.1_@opentelemetry+api@1.10.0_@ty_3390f7c80ab771c33a3e98a1c71b9106/node_modules/drizzle-orm/sqlite-core/primary-keys.js
62224
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/primary-keys.js
61946
62225
  function primaryKey(...config2) {
61947
62226
  if (config2[0].columns) {
61948
62227
  return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
@@ -62124,7 +62403,7 @@ var nativeOauthAttempt = sqliteTable("native_oauth_attempt", {
62124
62403
  AND ${t.openedAt} IS NOT NULL AND ${t.readyAt} IS NOT NULL AND ${t.consumedAt} IS NULL
62125
62404
  AND ${t.failedAt} IS NULL AND ${t.cancelledAt} IS NULL AND ${t.replacedAt} IS NULL
62126
62405
  AND ${t.handoffCodeHash} IS NOT NULL AND ${t.handoffExpiresAt} IS NOT NULL
62127
- AND ${t.handoffExpiresAt} = ${t.readyAt} + 120000
62406
+ AND ${t.handoffExpiresAt} = min(${t.readyAt} + 120000, ${t.attemptExpiresAt})
62128
62407
  AND ${t.authKind} IS NOT NULL AND ${t.failureCode} IS NULL
62129
62408
  ) OR (
62130
62409
  ${t.status} = 'consumed'
@@ -62218,6 +62497,7 @@ var communityChannelMember = sqliteTable("community_channel_member", {
62218
62497
  }, (t) => [
62219
62498
  index("idx_community_channel_member_added_by_lookup").on(t.addedBy),
62220
62499
  unique("uq_channel_member").on(t.channelId, t.userId, t.relation),
62500
+ index("idx_channel_member_channel_relation_user").on(t.channelId, t.relation, t.userId),
62221
62501
  index("idx_channel_member_user").on(t.userId)
62222
62502
  ]);
62223
62503
  var communityMessage = sqliteTable("community_message", {
@@ -62237,6 +62517,7 @@ var communityMessage = sqliteTable("community_message", {
62237
62517
  clientNonce: text2("client_nonce")
62238
62518
  }, (t) => [
62239
62519
  index("idx_community_message_author_id_lookup").on(t.authorId),
62520
+ index("idx_message_channel_seq").on(t.channelId, t.seq),
62240
62521
  index("idx_message_channel_created").on(t.channelId, t.createdAt),
62241
62522
  index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt),
62242
62523
  index("idx_community_message_channel_reply_author").on(t.channelId, t.replyToId, t.authorId).where(sql`${t.replyToId} IS NOT NULL`)
@@ -62341,7 +62622,8 @@ var communityReaction = sqliteTable("community_reaction", {
62341
62622
  }, (t) => [
62342
62623
  index("idx_community_reaction_user_id_lookup").on(t.userId),
62343
62624
  unique("uq_reaction_message_user_emoji").on(t.messageId, t.userId, t.emoji),
62344
- index("idx_reaction_message").on(t.messageId)
62625
+ index("idx_reaction_message").on(t.messageId),
62626
+ index("idx_reaction_message_emoji_created").on(t.messageId, t.emoji, t.createdAt, t.userId)
62345
62627
  ]);
62346
62628
  var communityAttachment = sqliteTable("community_attachment", {
62347
62629
  id: text2("id").primaryKey().$defaultFn(() => nanoid3()),
@@ -62503,18 +62785,6 @@ var communityMessageTag = sqliteTable("community_message_tag", {
62503
62785
  index("idx_message_tag_tag").on(t.tag, t.messageId)
62504
62786
  ]);
62505
62787
 
62506
- // ../shared/src/db/queries/_chunk.ts
62507
- var D1_MAX_BIND_PARAMS = 100;
62508
- function maxInParams(fixedParams) {
62509
- if (!Number.isInteger(fixedParams) || fixedParams < 0) {
62510
- throw new Error("fixed params must be a non-negative integer");
62511
- }
62512
- if (fixedParams >= D1_MAX_BIND_PARAMS) {
62513
- throw new Error("fixed params must leave room for at least one IN parameter");
62514
- }
62515
- return D1_MAX_BIND_PARAMS - fixedParams;
62516
- }
62517
-
62518
62788
  // ../shared/src/community-server-rail.ts
62519
62789
  var MAX_SERVER_RAIL_COMMANDS = 3;
62520
62790
  var idSchema = exports_external.string().trim().min(1);
@@ -62630,19 +62900,18 @@ class Logger {
62630
62900
  entry[k] = { message: v.message, stack: v.stack };
62631
62901
  }
62632
62902
  }
62633
- let line;
62634
- if (this.pretty) {
62903
+ const output2 = this.pretty ? (() => {
62635
62904
  const ts = entry.ts.replace("T", " ").replace("Z", "");
62636
62905
  const lvl = entry.level.toUpperCase().padEnd(5);
62637
62906
  const pairs = Object.entries(entry).filter(([k]) => k !== "level" && k !== "msg" && k !== "service" && k !== "ts").map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`).join(" ");
62638
- line = `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
62639
- } else {
62640
- line = JSON.stringify(entry);
62641
- }
62907
+ return `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
62908
+ })() : entry;
62642
62909
  if (level === "error") {
62643
- console.error(line);
62910
+ console.error(output2);
62911
+ } else if (level === "warn") {
62912
+ console.warn(output2);
62644
62913
  } else {
62645
- console.log(line);
62914
+ console.log(output2);
62646
62915
  }
62647
62916
  }
62648
62917
  }
@@ -62923,7 +63192,6 @@ var AGENT_MESSAGE_COLUMNS = {
62923
63192
  embeds: communityMessage.embeds
62924
63193
  };
62925
63194
  var channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${communityChannelMember.addedAt}, ${communityServerMember.joinedAt}, '')`;
62926
- var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
62927
63195
  // ../shared/src/community-ws-events.ts
62928
63196
  var string4 = exports_external.string();
62929
63197
  var nullableString = string4.nullable();
@@ -63081,7 +63349,8 @@ var communityMemberJoinSchema = exports_external.strictObject({
63081
63349
  userId: string4,
63082
63350
  role: string4,
63083
63351
  joinedAt: string4
63084
- })
63352
+ }),
63353
+ online: exports_external.boolean().optional()
63085
63354
  });
63086
63355
  var communityMemberLeaveSchema = exports_external.strictObject({
63087
63356
  type: exports_external.literal("community:member.leave"),
@@ -63177,6 +63446,10 @@ var communityPresenceUpdateSchema = exports_external.strictObject({
63177
63446
  userId: string4,
63178
63447
  online: exports_external.boolean()
63179
63448
  });
63449
+ var communityPresenceSnapshotSchema = exports_external.strictObject({
63450
+ type: exports_external.literal("community:presence.snapshot"),
63451
+ onlineUserIds: exports_external.array(string4)
63452
+ });
63180
63453
  var communityStatusUpdateSchema = exports_external.strictObject({
63181
63454
  type: exports_external.literal("community:status.update"),
63182
63455
  userId: string4,
@@ -63235,6 +63508,11 @@ var communityBotPiiSchema = exports_external.strictObject({
63235
63508
  requestId: exports_external.string().min(1).max(128),
63236
63509
  result: PiiResultSchema
63237
63510
  });
63511
+ var communityScheduleChangedSchema = exports_external.strictObject({
63512
+ type: exports_external.literal("community:schedule.changed"),
63513
+ eventId: string4,
63514
+ reason: exports_external.enum(["created", "updated", "deleted", "run_updated"])
63515
+ });
63238
63516
  var commonCommunityEventSchemas = [
63239
63517
  communityBotPiiSchema,
63240
63518
  communityMessageUpdatedSchema,
@@ -63268,13 +63546,15 @@ var commonCommunityEventSchemas = [
63268
63546
  communityReadStateAdvancedSchema,
63269
63547
  communityInboxChangedSchema,
63270
63548
  communityPresenceUpdateSchema,
63549
+ communityPresenceSnapshotSchema,
63271
63550
  communityStatusUpdateSchema,
63272
63551
  communityMachineCreatedSchema,
63273
63552
  communityMachineStatusSchema,
63274
63553
  communityMachineUpdatedSchema,
63275
63554
  communityRuntimeModelsSchema,
63276
63555
  communityMachineRemovedSchema,
63277
- communityBotAuditEventSchema
63556
+ communityBotAuditEventSchema,
63557
+ communityScheduleChangedSchema
63278
63558
  ];
63279
63559
  var CommunityWsEventSchema = exports_external.discriminatedUnion("type", [
63280
63560
  ...commonCommunityEventSchemas,
@@ -63323,6 +63603,7 @@ var WS_EVENTS = {
63323
63603
  READ_STATE_ADVANCED: "community:read_state.advanced",
63324
63604
  INBOX_CHANGED: "community:inbox.changed",
63325
63605
  PRESENCE_UPDATE: "community:presence.update",
63606
+ PRESENCE_SNAPSHOT: "community:presence.snapshot",
63326
63607
  STATUS_UPDATE: "community:status.update",
63327
63608
  IDENTITY_UPDATE: "community:identity.update",
63328
63609
  PROFILE_UPDATE: "community:profile.update",
@@ -63332,7 +63613,8 @@ var WS_EVENTS = {
63332
63613
  RUNTIME_MODELS: "community:runtime.models",
63333
63614
  BOT_PII: "community:bot.pii",
63334
63615
  MACHINE_REMOVED: "community:machine.removed",
63335
- BOT_AUDIT_EVENT: "community:bot.audit_event"
63616
+ BOT_AUDIT_EVENT: "community:bot.audit_event",
63617
+ SCHEDULE_CHANGED: "community:schedule.changed"
63336
63618
  };
63337
63619
  var COMMUNITY_EVENT_TYPES = new Set(Object.values(WS_EVENTS));
63338
63620
  var COMMUNITY_BROWSER_EVENT_MAX_BYTES = 65536;
@@ -63553,8 +63835,58 @@ var communityBotFeedback = sqliteTable("community_bot_feedback", {
63553
63835
  check2("bot_feedback_text_bytes", sql`length(cast(${t.text} as blob)) between 1 and ${sql.raw(String(BOT_FEEDBACK_MAX_BYTES))}`)
63554
63836
  ]);
63555
63837
 
63838
+ // ../shared/src/db/community-schedule-schema.ts
63839
+ var exports_community_schedule_schema = {};
63840
+ __export(exports_community_schedule_schema, {
63841
+ communityScheduleRun: () => communityScheduleRun,
63842
+ communityScheduleEvent: () => communityScheduleEvent
63843
+ });
63844
+ var communityScheduleEvent = sqliteTable("community_schedule_event", {
63845
+ id: text2("id").primaryKey(),
63846
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
63847
+ createdByUserId: text2("created_by_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
63848
+ title: text2("title").notNull(),
63849
+ description: text2("description").notNull().default(""),
63850
+ startAtMs: integer2("start_at_ms").notNull(),
63851
+ durationMinutes: integer2("duration_minutes").notNull().default(30),
63852
+ timeZone: text2("time_zone").notNull(),
63853
+ recurrenceJson: text2("recurrence_json"),
63854
+ occurrenceCount: integer2("occurrence_count").notNull().default(0),
63855
+ nextRunAtMs: integer2("next_run_at_ms"),
63856
+ sourceMessageId: text2("source_message_id").notNull(),
63857
+ sourceChannelId: text2("source_channel_id").notNull(),
63858
+ version: integer2("version").notNull().default(1),
63859
+ createdAtMs: integer2("created_at_ms").notNull(),
63860
+ updatedAtMs: integer2("updated_at_ms").notNull()
63861
+ }, (t) => [
63862
+ index("idx_community_schedule_event_owner_created").on(t.ownerUserId, t.createdAtMs),
63863
+ index("idx_community_schedule_event_owner_next_run").on(t.ownerUserId, t.nextRunAtMs).where(sql`${t.nextRunAtMs} IS NOT NULL`),
63864
+ index("idx_community_schedule_event_creator_id_lookup").on(t.createdByUserId)
63865
+ ]);
63866
+ var communityScheduleRun = sqliteTable("community_schedule_run", {
63867
+ id: text2("id").primaryKey(),
63868
+ ownerUserId: text2("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
63869
+ eventId: text2("event_id").notNull().references(() => communityScheduleEvent.id, { onDelete: "cascade" }),
63870
+ eventVersion: integer2("event_version").notNull(),
63871
+ botUserId: text2("bot_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
63872
+ scheduledAtMs: integer2("scheduled_at_ms").notNull(),
63873
+ sourceMessageId: text2("source_message_id").notNull(),
63874
+ sourceChannelId: text2("source_channel_id").notNull(),
63875
+ titleSnapshot: text2("title_snapshot").notNull(),
63876
+ descriptionSnapshot: text2("description_snapshot").notNull(),
63877
+ status: text2("status").$type().notNull(),
63878
+ lastError: text2("last_error"),
63879
+ ackedAtMs: integer2("acked_at_ms"),
63880
+ createdAtMs: integer2("created_at_ms").notNull(),
63881
+ updatedAtMs: integer2("updated_at_ms").notNull()
63882
+ }, (t) => [
63883
+ uniqueIndex("uq_community_schedule_run_event_scheduled").on(t.eventId, t.scheduledAtMs),
63884
+ index("idx_community_schedule_run_owner_status_scheduled").on(t.ownerUserId, t.status, t.scheduledAtMs),
63885
+ index("idx_community_schedule_run_bot_id_lookup").on(t.botUserId)
63886
+ ]);
63887
+
63556
63888
  // ../shared/src/db/index.ts
63557
- 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 };
63889
+ 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 };
63558
63890
  // ../shared/src/db/queries/native-oauth.ts
63559
63891
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
63560
63892
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
@@ -63583,6 +63915,122 @@ var metadataProjection = {
63583
63915
  };
63584
63916
  // ../shared/src/db/queries/community/diagnostic-report.ts
63585
63917
  var diagnosticOwner = alias(user, "diagnostic_owner");
63918
+ // ../shared/src/schedule.ts
63919
+ var SCHEDULE_TITLE_MAX_LENGTH = 160;
63920
+ var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
63921
+ var SCHEDULE_MIN_DURATION_MINUTES = 5;
63922
+ var SCHEDULE_MAX_DURATION_MINUTES = 1440;
63923
+ var SCHEDULE_MAX_RANGE_MS = 62 * 24 * 60 * 60 * 1000;
63924
+ var ScheduleRecurrenceFreqSchema = exports_external.enum(["hourly", "daily", "weekly", "monthly"]);
63925
+ var ScheduleRecurrenceSchema = exports_external.strictObject({
63926
+ freq: ScheduleRecurrenceFreqSchema,
63927
+ interval: exports_external.number().int().min(1).max(365),
63928
+ byWeekday: exports_external.array(exports_external.number().int().min(0).max(6)).min(1).max(7).optional(),
63929
+ untilAt: exports_external.iso.datetime({ offset: true }).nullable().optional(),
63930
+ count: exports_external.number().int().min(1).max(1000).nullable().optional()
63931
+ }).superRefine((value, ctx) => {
63932
+ if (value.byWeekday !== undefined && value.freq !== "weekly") {
63933
+ ctx.addIssue({
63934
+ code: "custom",
63935
+ path: ["byWeekday"],
63936
+ message: "byWeekday is only supported for weekly recurrence"
63937
+ });
63938
+ }
63939
+ });
63940
+ var ScheduleRunStatusSchema = exports_external.enum([
63941
+ "pending",
63942
+ "dispatched",
63943
+ "completed",
63944
+ "blocked_access"
63945
+ ]);
63946
+ var ScheduleOccurrenceStatusSchema = exports_external.enum([
63947
+ "scheduled",
63948
+ "pending",
63949
+ "dispatched",
63950
+ "completed",
63951
+ "blocked_access"
63952
+ ]);
63953
+ var ScheduleSourceMessageStatusSchema = exports_external.enum([
63954
+ "accessible",
63955
+ "inaccessible",
63956
+ "deleted"
63957
+ ]);
63958
+ var ScheduleActorSummarySchema = exports_external.strictObject({
63959
+ id: exports_external.string().min(1),
63960
+ handle: exports_external.string().min(1),
63961
+ name: exports_external.string().min(1),
63962
+ avatarVersion: exports_external.number().int().nonnegative(),
63963
+ isBot: exports_external.boolean()
63964
+ });
63965
+ var ScheduleLastExecutionSchema = exports_external.strictObject({
63966
+ scheduledAt: exports_external.iso.datetime(),
63967
+ status: ScheduleRunStatusSchema,
63968
+ lastError: exports_external.string().nullable(),
63969
+ ackedAt: exports_external.iso.datetime().nullable(),
63970
+ updatedAt: exports_external.iso.datetime()
63971
+ });
63972
+ var ScheduleSourceMessageSchema = exports_external.strictObject({
63973
+ id: exports_external.string().min(1),
63974
+ accessible: exports_external.boolean(),
63975
+ status: ScheduleSourceMessageStatusSchema,
63976
+ ref: exports_external.string().nullable(),
63977
+ channelRef: exports_external.string().nullable(),
63978
+ seq: exports_external.number().int().positive().nullable(),
63979
+ preview: exports_external.string().nullable()
63980
+ });
63981
+ var ScheduleEventSchema = exports_external.strictObject({
63982
+ id: exports_external.string().min(1),
63983
+ title: exports_external.string().min(1),
63984
+ description: exports_external.string(),
63985
+ createdBy: ScheduleActorSummarySchema,
63986
+ startAt: exports_external.iso.datetime(),
63987
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES),
63988
+ timeZone: exports_external.string().min(1),
63989
+ recurrence: ScheduleRecurrenceSchema.nullable(),
63990
+ nextRunAt: exports_external.iso.datetime().nullable(),
63991
+ sourceMessage: ScheduleSourceMessageSchema,
63992
+ lastExecution: ScheduleLastExecutionSchema.nullable(),
63993
+ createdAt: exports_external.iso.datetime(),
63994
+ updatedAt: exports_external.iso.datetime()
63995
+ });
63996
+ var ScheduleOccurrenceSchema = exports_external.strictObject({
63997
+ eventId: exports_external.string().min(1),
63998
+ occurrenceKey: exports_external.string().min(1),
63999
+ startAt: exports_external.iso.datetime(),
64000
+ endAt: exports_external.iso.datetime(),
64001
+ runStatus: ScheduleOccurrenceStatusSchema
64002
+ });
64003
+ var ScheduleListResponseSchema = exports_external.strictObject({
64004
+ events: exports_external.array(ScheduleEventSchema),
64005
+ occurrences: exports_external.array(ScheduleOccurrenceSchema),
64006
+ creators: exports_external.array(ScheduleActorSummarySchema)
64007
+ });
64008
+ var ScheduleCreateRequestSchema = exports_external.strictObject({
64009
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH),
64010
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
64011
+ startAt: exports_external.iso.datetime({ offset: true }),
64012
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
64013
+ timeZone: exports_external.string().trim().min(1).max(128),
64014
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
64015
+ sourceMessageRef: exports_external.string().trim().min(1).max(512)
64016
+ });
64017
+ var ScheduleUpdateRequestSchema = exports_external.strictObject({
64018
+ title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH).optional(),
64019
+ description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
64020
+ startAt: exports_external.iso.datetime({ offset: true }).optional(),
64021
+ durationMinutes: exports_external.number().int().min(SCHEDULE_MIN_DURATION_MINUTES).max(SCHEDULE_MAX_DURATION_MINUTES).optional(),
64022
+ timeZone: exports_external.string().trim().min(1).max(128).optional(),
64023
+ recurrence: ScheduleRecurrenceSchema.nullable().optional(),
64024
+ sourceMessageRef: exports_external.string().trim().min(1).max(512).optional(),
64025
+ ack: exports_external.literal(true).optional()
64026
+ });
64027
+ var formatterCache = new Map;
64028
+ // ../shared/src/lib/channel-ref-syntax.ts
64029
+ 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`;
64030
+ var REF_SEG = `[^\\s/#${REF_TERM}]+`;
64031
+ var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
64032
+ var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
64033
+ var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
63586
64034
  // ../shared/src/utils/email.ts
63587
64035
  var DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`;
63588
64036
  // ../shared/src/lib/safe-redirect.ts
@@ -71753,7 +72201,7 @@ function toResult(value) {
71753
72201
  }
71754
72202
  return value === null || value === undefined ? empty : [value];
71755
72203
  }
71756
- // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.4/node_modules/mdast-util-find-and-replace/lib/index.js
72204
+ // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.5/node_modules/mdast-util-find-and-replace/lib/index.js
71757
72205
  function findAndReplace(tree, list2, options) {
71758
72206
  const settings = options || {};
71759
72207
  const ignored = convert(settings.ignore || []);
@@ -71789,9 +72237,7 @@ function findAndReplace(tree, list2, options) {
71789
72237
  if (typeof value === "string") {
71790
72238
  value = value.length > 0 ? { type: "text", value } : undefined;
71791
72239
  }
71792
- if (value === false) {
71793
- find.lastIndex = position2 + 1;
71794
- } else {
72240
+ if (value !== false) {
71795
72241
  if (start !== position2) {
71796
72242
  add({ type: "text", value: node3.value.slice(start, position2) });
71797
72243
  }
@@ -71804,6 +72250,10 @@ function findAndReplace(tree, list2, options) {
71804
72250
  start = position2 + match[0].length;
71805
72251
  change = true;
71806
72252
  }
72253
+ if (value === false || match[0].length === 0) {
72254
+ const code = node3.value.codePointAt(position2) || 0;
72255
+ find.lastIndex = position2 + (/[uv]/.test(find.flags) && code > 65535 ? 2 : 1);
72256
+ }
71807
72257
  if (!find.global) {
71808
72258
  break;
71809
72259
  }
@@ -71849,7 +72299,7 @@ function toFunction(replace) {
71849
72299
  return replace;
71850
72300
  };
71851
72301
  }
71852
- // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.0.1/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
72302
+ // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.1.0/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
71853
72303
  var inConstruct = "phrasing";
71854
72304
  var notInConstruct = ["autolink", "link", "image", "label"];
71855
72305
  function gfmAutolinkLiteralFromMarkdown() {
@@ -71897,7 +72347,7 @@ function gfmAutolinkLiteralToMarkdown() {
71897
72347
  };
71898
72348
  }
71899
72349
  function enterLiteralAutolink(token) {
71900
- this.enter({ type: "link", title: null, url: "", children: [] }, token);
72350
+ this.enter({ type: "link", title: null, url: "", children: [], position: undefined }, token);
71901
72351
  }
71902
72352
  function enterLiteralAutolinkValue(token) {
71903
72353
  this.config.enter.autolinkProtocol.call(this, token);
@@ -71919,62 +72369,107 @@ function exitLiteralAutolink(token) {
71919
72369
  }
71920
72370
  function transformGfmAutolinkLiterals(tree) {
71921
72371
  findAndReplace(tree, [
71922
- [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
71923
- [/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail]
72372
+ [
72373
+ /(?<![\da-z])(https?:\/\/|www(?=\.))([\w-]*\.[\w\-.]*)([^\t\n\r ]*)/gi,
72374
+ findUrl
72375
+ ],
72376
+ [
72377
+ /(?<![\w+\-.@])xmpp:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)(\/(?:[\w\-/]|\.(?=[\dA-Za-z]))*)?/g,
72378
+ findXmpp
72379
+ ],
72380
+ [/(?<![\w+\-.@])mailto:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g, findMailto],
72381
+ [
72382
+ /(?<![\w+\-.]|(?:^|[^\d@A-Za-z])(?:mailto|xmpp):)([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g,
72383
+ findEmail
72384
+ ]
71924
72385
  ], { ignore: ["link", "linkReference"] });
71925
72386
  }
71926
72387
  function findUrl(_, protocol, domain2, path13, match) {
71927
- let prefix = "";
71928
72388
  if (!previous2(match)) {
71929
72389
  return false;
71930
72390
  }
72391
+ let prefix = "";
71931
72392
  if (/^w/i.test(protocol)) {
71932
72393
  domain2 = protocol + domain2;
71933
72394
  protocol = "";
71934
72395
  prefix = "http://";
71935
72396
  }
71936
- if (!isCorrectDomain(domain2)) {
72397
+ if (unicodePunctuation(domain2.charCodeAt(0)) || !isCorrectDomain(domain2)) {
71937
72398
  return false;
71938
72399
  }
71939
72400
  const parts = splitUrl(domain2 + path13);
71940
- if (!parts[0])
71941
- return false;
71942
72401
  const result = {
71943
72402
  type: "link",
71944
72403
  title: null,
71945
72404
  url: prefix + protocol + parts[0],
71946
- children: [{ type: "text", value: protocol + parts[0] }]
72405
+ children: [{ type: "text", value: protocol + parts[0], position: undefined }],
72406
+ position: undefined
71947
72407
  };
71948
72408
  if (parts[1]) {
71949
- return [result, { type: "text", value: parts[1] }];
72409
+ return [result, { type: "text", value: parts[1], position: undefined }];
71950
72410
  }
71951
72411
  return result;
71952
72412
  }
71953
- function findEmail(_, atext, label2, match) {
71954
- if (!previous2(match, true) || /[-\d_]$/.test(label2)) {
72413
+ function findEmail(_, atext, label2) {
72414
+ if (/[\d\-_]$/.test(label2)) {
71955
72415
  return false;
71956
72416
  }
71957
72417
  return {
71958
72418
  type: "link",
71959
72419
  title: null,
71960
72420
  url: "mailto:" + atext + "@" + label2,
71961
- children: [{ type: "text", value: atext + "@" + label2 }]
72421
+ children: [{ type: "text", value: atext + "@" + label2, position: undefined }],
72422
+ position: undefined
72423
+ };
72424
+ }
72425
+ function findMailto(_, atext, label2) {
72426
+ if (/[\d\-_]$/.test(label2)) {
72427
+ return false;
72428
+ }
72429
+ const value = "mailto:" + atext + "@" + label2;
72430
+ return {
72431
+ type: "link",
72432
+ title: null,
72433
+ url: value,
72434
+ children: [{ type: "text", value, position: undefined }],
72435
+ position: undefined
72436
+ };
72437
+ }
72438
+ function findXmpp(matchValue, atext, label2, resource, match) {
72439
+ if (/[\d\-_]$/.test(label2) || resource && (!/[A-Za-z]$/.test(resource) || match.input.charAt(match.index + matchValue.length) === "@")) {
72440
+ return false;
72441
+ }
72442
+ const value = "xmpp:" + atext + "@" + label2 + (resource || "");
72443
+ return {
72444
+ type: "link",
72445
+ title: null,
72446
+ url: value,
72447
+ children: [{ type: "text", value, position: undefined }],
72448
+ position: undefined
71962
72449
  };
71963
72450
  }
71964
72451
  function isCorrectDomain(domain2) {
71965
72452
  const parts = domain2.split(".");
71966
- if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\d]/.test(parts[parts.length - 2]))) {
72453
+ if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[\dA-Za-z]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[\dA-Za-z]/.test(parts[parts.length - 2]))) {
71967
72454
  return false;
71968
72455
  }
71969
72456
  return true;
71970
72457
  }
71971
72458
  function splitUrl(url2) {
71972
- const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url2);
71973
- if (!trailExec) {
72459
+ let index3 = url2.length;
72460
+ while (index3 > 0) {
72461
+ const code = url2.charCodeAt(index3 - 1);
72462
+ if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 62 || code === 63 || code === 93 || code === 125) {
72463
+ index3--;
72464
+ } else {
72465
+ break;
72466
+ }
72467
+ }
72468
+ if (index3 === url2.length) {
71974
72469
  return [url2, undefined];
71975
72470
  }
71976
- url2 = url2.slice(0, trailExec.index);
71977
- let trail = trailExec[0];
72471
+ let trail = url2.slice(index3);
72472
+ url2 = url2.slice(0, index3);
71978
72473
  let closingParenIndex = trail.indexOf(")");
71979
72474
  const openingParens = ccount(url2, "(");
71980
72475
  let closingParens = ccount(url2, ")");
@@ -71986,9 +72481,9 @@ function splitUrl(url2) {
71986
72481
  }
71987
72482
  return [url2, trail];
71988
72483
  }
71989
- function previous2(match, email3) {
72484
+ function previous2(match) {
71990
72485
  const code = match.input.charCodeAt(match.index - 1);
71991
- return (match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code)) && (!email3 || code !== 47);
72486
+ return match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code);
71992
72487
  }
71993
72488
  // ../../node_modules/.pnpm/mdast-util-gfm-footnote@2.1.0/node_modules/mdast-util-gfm-footnote/lib/index.js
71994
72489
  footnoteReference.peek = footnoteReferencePeek;
@@ -72521,25 +73016,37 @@ function emphasisPeek(_, _1, state) {
72521
73016
  return state.options.emphasis || "*";
72522
73017
  }
72523
73018
 
72524
- // ../../node_modules/.pnpm/unist-util-visit@5.1.0/node_modules/unist-util-visit/lib/index.js
72525
- function visit2(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
73019
+ // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
73020
+ function visit2(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
73021
+ let check3;
73022
+ let visitors;
72526
73023
  let reverse;
72527
- let test;
72528
- let visitor;
72529
- if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
72530
- test = undefined;
72531
- visitor = testOrVisitor;
72532
- reverse = visitorOrReverse;
72533
- } else {
72534
- test = testOrVisitor;
72535
- visitor = visitorOrReverse;
73024
+ if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
73025
+ check3 = testOrEnterOrVisitors;
73026
+ visitors = enterOrVisitorsOrReverse;
72536
73027
  reverse = maybeReverse;
73028
+ } else {
73029
+ visitors = testOrEnterOrVisitors;
73030
+ reverse = enterOrVisitorsOrReverse;
72537
73031
  }
72538
- visitParents(tree, test, overload, reverse);
72539
- function overload(node3, parents) {
72540
- const parent = parents[parents.length - 1];
72541
- const index3 = parent ? parent.children.indexOf(node3) : undefined;
72542
- return visitor(node3, index3, parent);
73032
+ if (typeof visitors === "function") {
73033
+ visitParents(tree, check3, wrap2(visitors), reverse);
73034
+ } else {
73035
+ visitParents(tree, check3, wrapVisitors(visitors), reverse);
73036
+ }
73037
+ }
73038
+ function wrapVisitors(visitors) {
73039
+ if (!visitors || typeof visitors !== "object")
73040
+ return visitors;
73041
+ return {
73042
+ enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
73043
+ exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
73044
+ };
73045
+ }
73046
+ function wrap2(visitor) {
73047
+ return overload;
73048
+ function overload(node3, parents, index3) {
73049
+ return visitor(node3, index3, parents[parents.length - 1]);
72543
73050
  }
72544
73051
  }
72545
73052
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
@@ -75616,43 +76123,10 @@ function peek(_, _1, state) {
75616
76123
  return state.options.emphasis || "*";
75617
76124
  }
75618
76125
 
75619
- // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
75620
- function visit3(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
75621
- let check4;
75622
- let visitors;
75623
- let reverse;
75624
- if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
75625
- check4 = testOrEnterOrVisitors;
75626
- visitors = enterOrVisitorsOrReverse;
75627
- reverse = maybeReverse;
75628
- } else {
75629
- visitors = testOrEnterOrVisitors;
75630
- reverse = enterOrVisitorsOrReverse;
75631
- }
75632
- if (typeof visitors === "function") {
75633
- visitParents(tree, check4, wrap2(visitors), reverse);
75634
- } else {
75635
- visitParents(tree, check4, wrapVisitors(visitors), reverse);
75636
- }
75637
- }
75638
- function wrapVisitors(visitors) {
75639
- if (!visitors || typeof visitors !== "object")
75640
- return visitors;
75641
- return {
75642
- enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
75643
- exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
75644
- };
75645
- }
75646
- function wrap2(visitor) {
75647
- return overload;
75648
- function overload(node3, parents, index3) {
75649
- return visitor(node3, index3, parents[parents.length - 1]);
75650
- }
75651
- }
75652
76126
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.2.3/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
75653
76127
  function formatHeadingAsSetext2(node3, state) {
75654
76128
  let literalWithBreak = false;
75655
- visit3(node3, function(node4) {
76129
+ visit2(node3, function(node4) {
75656
76130
  if ("value" in node4 && /\r?\n|\r/.test(node4.value) || node4.type === "break") {
75657
76131
  literalWithBreak = true;
75658
76132
  return EXIT;
@@ -77450,11 +77924,6 @@ var exitSpoiler = function(token) {
77450
77924
  };
77451
77925
 
77452
77926
  // ../shared/src/lib/chat-syntax-plugin.ts
77453
- 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`;
77454
- var REF_SEG = `[^\\s/#${REF_TERM}]+`;
77455
- var HANDLE_SEG = `${REF_SEG}#\\d{4,}`;
77456
- var CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu");
77457
- var SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu");
77458
77927
  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");
77459
77928
  function memberMentionSyntax() {
77460
77929
  const construct = {
@@ -77784,7 +78253,7 @@ function checkProfiles(rows, resources, ctx) {
77784
78253
  }
77785
78254
  }
77786
78255
  var CommunityAcceptedFriendsReadSchema = exports_external.union([
77787
- exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
78256
+ 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)),
77788
78257
  exports_external.strictObject({ ...stale, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema).length(0) })
77789
78258
  ]);
77790
78259
  var CommunityBlockedFriendsReadSchema = exports_external.union([
@@ -77889,7 +78358,10 @@ var CommunityReactionDetailsReadSchema = exports_external.strictObject({
77889
78358
  exports_external.strictObject({ kind: exports_external.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
77890
78359
  exports_external.strictObject({ kind: exports_external.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id })
77891
78360
  ]),
77892
- actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() }))
78361
+ actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() })),
78362
+ emoji: exports_external.string().optional(),
78363
+ hasMore: exports_external.boolean().optional(),
78364
+ cursor: exports_external.string().nullable().optional()
77893
78365
  }).superRefine((value, ctx) => {
77894
78366
  if (new Set(value.actors.map((row) => row.userId)).size !== value.actors.length || value.actors.some((row) => row.profile && row.profile.id !== row.userId))
77895
78367
  ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" });
@@ -77993,6 +78465,11 @@ function messagingSection() {
77993
78465
  "- 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.",
77994
78466
  "- Use `0` only when no later action depends on a reply. It disables the timer.",
77995
78467
  "",
78468
+ "#### Schedule future or recurring work",
78469
+ "",
78470
+ "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message or daemon restart cancels it.",
78471
+ `- 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.`,
78472
+ "",
77996
78473
  "#### Sending mechanics",
77997
78474
  "",
77998
78475
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
@@ -78043,7 +78520,11 @@ function messagingSection() {
78043
78520
  "",
78044
78521
  "#### Ask for a decision",
78045
78522
  "",
78046
- `Alook users cannot see native question prompts. When you need someone to choose from options, use \`${CLI} message send --ask\` with JSON on stdin (max 8 KiB).`,
78523
+ `Whenever you would use your native Ask Question tool, use Alook’s \`${CLI} message send --ask --remind-after 5m\` in the current conversation instead. People on Alook can only see the question you send there.`,
78524
+ "",
78525
+ "When you ask a question and can offer options, use a decision card. " + "Use a normal Alook message for updates and questions without options.",
78526
+ "",
78527
+ "Pass JSON on stdin (max 8 KiB).",
78047
78528
  "Include a required non-empty `summary` (1–240 chars). Recommend at least one option per question to help the user decide. Use `recommended: true`. Use `mentions` to name respondents, and short `header` values for multi-question tabs. Answers arrive in your inbox as replies to the original question.",
78048
78529
  "",
78049
78530
  "```json",
@@ -78168,6 +78649,15 @@ function cliCommandsSection() {
78168
78649
  "Adding stores a source copy. Later edits to the input file do not update the installed filter. " + "Do not edit daemon-managed copies.",
78169
78650
  "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.",
78170
78651
  "",
78652
+ "### Schedule",
78653
+ "",
78654
+ "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.",
78655
+ "",
78656
+ `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given, expanded occurrences.`,
78657
+ `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.`,
78658
+ `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack]\` — update a task, or pass \`--ack\` after finishing the triggered run to mark it completed.`,
78659
+ `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
78660
+ "",
78171
78661
  "### Settings",
78172
78662
  "",
78173
78663
  `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.`,
@@ -79999,6 +80489,9 @@ ${this.opts.wakePromptFooter}` : text8;
79999
80489
  return;
80000
80490
  }
80001
80491
  const sessionSuperseded = owner.superseded;
80492
+ if (event.type === "session_activity" && !sessionSuperseded) {
80493
+ this.dispatch({ type: "session_activity", agentId, sessionInstanceId: event.sessionInstanceId, observation: event.observation, nowMs: this.now() }, owner);
80494
+ }
80002
80495
  const runtimeError = event.type === "session_failed" ? event.error : event.type === "turn_completed" && event.result.outcome === "failed" ? event.result.error : undefined;
80003
80496
  if (runtimeError !== undefined && !sessionSuperseded) {
80004
80497
  this.emitErrorAudit(agentId, "runtime", runtimeError.code, runtimeError.message);
@@ -80015,12 +80508,12 @@ ${this.opts.wakePromptFooter}` : text8;
80015
80508
  }
80016
80509
  }
80017
80510
  if (this.opts.onBotAuditEvent) {
80018
- if (event.type === "assistant_message_completed" && event.text.length > 0) {
80511
+ if ((event.type === "assistant_message_completed" || event.type === "activity" && event.kind === "assistant_message_completed") && event.text && event.text.length > 0) {
80019
80512
  const { text: text8, truncated, chars } = truncateAuditText(event.text);
80020
80513
  try {
80021
80514
  this.opts.onBotAuditEvent(agentId, {
80022
80515
  kind: "text",
80023
- payload: { text: text8, truncated: truncated || event.truncated, chars }
80516
+ payload: { text: text8, truncated: truncated || event.truncated === true, chars }
80024
80517
  }, {
80025
80518
  sessionId: this.liveSessions.get(agentId) ?? null,
80026
80519
  launchId: this.launchIds.get(agentId) ?? null
@@ -80876,6 +81369,9 @@ function resolveProxyCapability(method, pathname) {
80876
81369
  return "read";
80877
81370
  if (pathname === "/api/community/bots/creation-requests" && method === "POST")
80878
81371
  return "send";
81372
+ if (/^\/api\/community\/schedule\/events(\/[^/]+)?$/.test(pathname)) {
81373
+ return method === "GET" ? "read" : "send";
81374
+ }
80879
81375
  if ((method === "GET" || method === "PATCH") && pathname === communityProxyRoutes.profile || method === "POST" && pathname === communityProxyRoutes.avatar)
80880
81376
  return "profile";
80881
81377
  if (pathname.includes("/attachment"))
@@ -80950,6 +81446,22 @@ function resolveProxyAuditOperation(pathname, method) {
80950
81446
  return "profileAvatarUpdate";
80951
81447
  if (/^\/api\/community\/bots\/me\/nap(\/|$|\?)/.test(canonical))
80952
81448
  return "nap";
81449
+ if (/^\/api\/community\/schedule\/events$/.test(canonical)) {
81450
+ if (method === "GET")
81451
+ return "scheduleList";
81452
+ if (method === "POST")
81453
+ return "scheduleCreate";
81454
+ return null;
81455
+ }
81456
+ if (/^\/api\/community\/schedule\/events\/[^/]+$/.test(canonical)) {
81457
+ if (method === "GET")
81458
+ return "scheduleGet";
81459
+ if (method === "PATCH")
81460
+ return "scheduleUpdate";
81461
+ if (method === "DELETE")
81462
+ return "scheduleDelete";
81463
+ return null;
81464
+ }
80953
81465
  return null;
80954
81466
  }
80955
81467
  function propertyAuditMetadata(method, pathname, requestUrl) {
@@ -81598,212 +82110,233 @@ async function startCredentialProxy(broker, options = {}) {
81598
82110
  return;
81599
82111
  }
81600
82112
  };
81601
- const server = http.createServer(async (req, res) => {
81602
- const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
81603
- const pathname = requestUrl.pathname;
81604
- if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
81605
- if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
81606
- writeJson(res, 405, { error: "method not allowed" });
81607
- req.resume();
82113
+ const server = http.createServer((req, res) => {
82114
+ (async () => {
82115
+ const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
82116
+ const pathname = requestUrl.pathname;
82117
+ if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
82118
+ if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
82119
+ writeJson(res, 405, { error: "method not allowed" });
82120
+ req.resume();
82121
+ return;
82122
+ }
82123
+ const verdict2 = broker.check(req.headers["authorization"], "send");
82124
+ if (!verdict2.ok) {
82125
+ writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
82126
+ req.resume();
82127
+ return;
82128
+ }
82129
+ await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
81608
82130
  return;
81609
82131
  }
81610
- const verdict2 = broker.check(req.headers["authorization"], "send");
81611
- if (!verdict2.ok) {
81612
- writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
81613
- req.resume();
82132
+ if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
82133
+ const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
82134
+ if (!localVerdict.ok) {
82135
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
82136
+ req.resume();
82137
+ return;
82138
+ }
82139
+ await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
81614
82140
  return;
81615
82141
  }
81616
- await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
81617
- return;
81618
- }
81619
- if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
81620
- const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
81621
- if (!localVerdict.ok) {
81622
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81623
- req.resume();
82142
+ if (pathname.startsWith("/__alook/local/")) {
82143
+ if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
82144
+ writeJson(res, 404, { error: "unknown local route", code: "not_found" });
82145
+ req.resume();
82146
+ return;
82147
+ }
82148
+ if (req.method !== "PUT") {
82149
+ writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
82150
+ req.resume();
82151
+ return;
82152
+ }
82153
+ const localVerdict = broker.check(req.headers["authorization"], "send");
82154
+ if (!localVerdict.ok) {
82155
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
82156
+ req.resume();
82157
+ return;
82158
+ }
82159
+ handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
81624
82160
  return;
81625
82161
  }
81626
- await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
81627
- return;
81628
- }
81629
- if (pathname.startsWith("/__alook/local/")) {
81630
- if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
81631
- writeJson(res, 404, { error: "unknown local route", code: "not_found" });
82162
+ const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
82163
+ const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
82164
+ const verdict = broker.check(req.headers["authorization"], requiredCap);
82165
+ if (!verdict.ok) {
82166
+ res.writeHead(verdict.status, { "content-type": "application/json" });
82167
+ res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
81632
82168
  req.resume();
81633
82169
  return;
81634
82170
  }
81635
- if (req.method !== "PUT") {
81636
- writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
81637
- req.resume();
82171
+ if (pathname.startsWith("/api/community/machines") && !(req.method === "GET" && /^\/api\/community\/machines(?:\/[^/]+(?:\/models)?)?$/.test(pathname) || req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname))) {
82172
+ writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
81638
82173
  return;
81639
82174
  }
81640
- const localVerdict = broker.check(req.headers["authorization"], "send");
81641
- if (!localVerdict.ok) {
81642
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
82175
+ const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
82176
+ if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
82177
+ res.writeHead(404, { "content-type": "application/json" });
82178
+ res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
81643
82179
  req.resume();
81644
82180
  return;
81645
82181
  }
81646
- handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
81647
- return;
81648
- }
81649
- const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
81650
- const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
81651
- const verdict = broker.check(req.headers["authorization"], requiredCap);
81652
- if (!verdict.ok) {
81653
- res.writeHead(verdict.status, { "content-type": "application/json" });
81654
- res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
81655
- req.resume();
81656
- return;
81657
- }
81658
- if (pathname.startsWith("/api/community/machines") && !(req.method === "GET" && /^\/api\/community\/machines(?:\/[^/]+(?:\/models)?)?$/.test(pathname) || req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname))) {
81659
- writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
81660
- return;
81661
- }
81662
- const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81663
- if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
81664
- res.writeHead(404, { "content-type": "application/json" });
81665
- res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
81666
- req.resume();
81667
- return;
81668
- }
81669
- if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
81670
- writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
81671
- req.resume();
81672
- return;
81673
- }
81674
- const reg = verdict.reg;
81675
- if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
81676
- writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
81677
- req.resume();
81678
- return;
81679
- }
81680
- let filteredBody;
81681
- let piiTriggeredFilters = [];
81682
- if (options.pii && route.filterPiiSend) {
81683
- try {
81684
- const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
81685
- filteredBody = filtered.body;
81686
- piiTriggeredFilters = filtered.triggeredFilters;
81687
- } catch (error62) {
81688
- writePiiError(res, error62);
82182
+ if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
82183
+ writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
82184
+ req.resume();
81689
82185
  return;
81690
82186
  }
81691
- if (res.destroyed)
82187
+ const reg = verdict.reg;
82188
+ if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
82189
+ writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
82190
+ req.resume();
81692
82191
  return;
81693
- }
81694
- const isInboxPull = route.inboxObservation === "pull";
81695
- const isInboxAck = route.inboxObservation === "ack";
81696
- const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
81697
- const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
81698
- let inboxPullObservationToken;
81699
- let inboxAckObservationToken;
81700
- if (shouldObserveInboxPull) {
81701
- try {
81702
- inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
81703
- } catch {
81704
- reportInboxPullObservationError({
81705
- agentId: reg.agentId,
81706
- reason: "observer_failed",
81707
- contentEncoding: "identity"
81708
- });
81709
82192
  }
81710
- }
81711
- if (shouldObserveInboxAck) {
81712
- try {
81713
- inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
81714
- } catch {
81715
- reportInboxAckObservationError({
81716
- agentId: reg.agentId,
81717
- reason: "observer_failed",
81718
- contentEncoding: "identity"
81719
- });
82193
+ let filteredBody;
82194
+ let piiTriggeredFilters = [];
82195
+ if (options.pii && route.filterPiiSend) {
82196
+ try {
82197
+ const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
82198
+ filteredBody = filtered.body;
82199
+ piiTriggeredFilters = filtered.triggeredFilters;
82200
+ } catch (error62) {
82201
+ writePiiError(res, error62);
82202
+ return;
82203
+ }
82204
+ if (res.destroyed)
82205
+ return;
81720
82206
  }
81721
- }
81722
- if (onProxyRequest) {
81723
- try {
81724
- const method = req.method ?? "GET";
81725
- onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
81726
- } catch {}
81727
- }
81728
- const outHeaders = { ...req.headers };
81729
- delete outHeaders["authorization"];
81730
- delete outHeaders["host"];
81731
- outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
81732
- outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
81733
- outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
81734
- outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
81735
- if (isInboxPull || isInboxAck)
81736
- outHeaders["accept-encoding"] = "identity";
81737
- if (filteredBody) {
81738
- delete outHeaders["transfer-encoding"];
81739
- outHeaders["content-length"] = filteredBody.byteLength;
81740
- }
81741
- let responded = false;
81742
- if (piiTriggeredFilters.length)
81743
- outHeaders["accept-encoding"] = "identity";
81744
- let upstreamRes;
81745
- const upstreamReq = upstreamClient.request({
81746
- protocol: upstream.protocol,
81747
- hostname: upstream.hostname,
81748
- port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
81749
- method: req.method,
81750
- path: joinPath(upstream.pathname, req.url ?? "/"),
81751
- headers: outHeaders
81752
- }, (res_) => {
81753
- responded = true;
81754
- upstreamRes = res_;
81755
- const destroyResIfIncomplete = () => {
81756
- if (!res_.complete)
81757
- res.destroy();
81758
- };
81759
- res_.on("error", destroyResIfIncomplete);
81760
- res_.on("close", destroyResIfIncomplete);
81761
- if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
81762
- const chunks = [];
81763
- res_.on("data", (chunk2) => chunks.push(chunk2));
81764
- res_.on("end", () => {
81765
- const body = Buffer.concat(chunks);
81766
- const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
81767
- if (contentEncoding !== "identity") {
81768
- if (shouldObserveInboxPull) {
81769
- reportInboxPullObservationError({
81770
- agentId: reg.agentId,
81771
- reason: "unexpected_content_encoding",
81772
- contentEncoding
81773
- });
81774
- } else {
81775
- reportInboxAckObservationError({
81776
- agentId: reg.agentId,
81777
- reason: "unexpected_content_encoding",
81778
- contentEncoding
81779
- });
81780
- }
81781
- } else {
81782
- let parsed;
81783
- try {
81784
- parsed = JSON.parse(body.toString("utf8"));
81785
- } catch {
82207
+ const isInboxPull = route.inboxObservation === "pull";
82208
+ const isInboxAck = route.inboxObservation === "ack";
82209
+ const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
82210
+ const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
82211
+ let inboxPullObservationToken;
82212
+ let inboxAckObservationToken;
82213
+ if (shouldObserveInboxPull) {
82214
+ try {
82215
+ inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
82216
+ } catch {
82217
+ reportInboxPullObservationError({
82218
+ agentId: reg.agentId,
82219
+ reason: "observer_failed",
82220
+ contentEncoding: "identity"
82221
+ });
82222
+ }
82223
+ }
82224
+ if (shouldObserveInboxAck) {
82225
+ try {
82226
+ inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
82227
+ } catch {
82228
+ reportInboxAckObservationError({
82229
+ agentId: reg.agentId,
82230
+ reason: "observer_failed",
82231
+ contentEncoding: "identity"
82232
+ });
82233
+ }
82234
+ }
82235
+ if (onProxyRequest) {
82236
+ try {
82237
+ const method = req.method ?? "GET";
82238
+ onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
82239
+ } catch {}
82240
+ }
82241
+ const outHeaders = { ...req.headers };
82242
+ delete outHeaders["authorization"];
82243
+ delete outHeaders["host"];
82244
+ outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
82245
+ outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
82246
+ outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
82247
+ outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
82248
+ if (isInboxPull || isInboxAck)
82249
+ outHeaders["accept-encoding"] = "identity";
82250
+ if (filteredBody) {
82251
+ delete outHeaders["transfer-encoding"];
82252
+ outHeaders["content-length"] = filteredBody.byteLength;
82253
+ }
82254
+ let responded = false;
82255
+ if (piiTriggeredFilters.length)
82256
+ outHeaders["accept-encoding"] = "identity";
82257
+ let upstreamRes;
82258
+ const upstreamReq = upstreamClient.request({
82259
+ protocol: upstream.protocol,
82260
+ hostname: upstream.hostname,
82261
+ port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
82262
+ method: req.method,
82263
+ path: joinPath(upstream.pathname, req.url ?? "/"),
82264
+ headers: outHeaders
82265
+ }, (res_) => {
82266
+ responded = true;
82267
+ upstreamRes = res_;
82268
+ const destroyResIfIncomplete = () => {
82269
+ if (!res_.complete)
82270
+ res.destroy();
82271
+ };
82272
+ res_.on("error", destroyResIfIncomplete);
82273
+ res_.on("close", destroyResIfIncomplete);
82274
+ if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
82275
+ const chunks = [];
82276
+ res_.on("data", (chunk2) => chunks.push(chunk2));
82277
+ res_.on("end", () => {
82278
+ const body = Buffer.concat(chunks);
82279
+ const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
82280
+ if (contentEncoding !== "identity") {
81786
82281
  if (shouldObserveInboxPull) {
81787
- reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
82282
+ reportInboxPullObservationError({
82283
+ agentId: reg.agentId,
82284
+ reason: "unexpected_content_encoding",
82285
+ contentEncoding
82286
+ });
81788
82287
  } else {
81789
- reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
82288
+ reportInboxAckObservationError({
82289
+ agentId: reg.agentId,
82290
+ reason: "unexpected_content_encoding",
82291
+ contentEncoding
82292
+ });
81790
82293
  }
81791
- }
81792
- if (parsed !== undefined) {
81793
- if (shouldObserveInboxPull) {
81794
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
81795
- reportInboxPullObservationError({
82294
+ } else {
82295
+ let parsed;
82296
+ try {
82297
+ parsed = JSON.parse(body.toString("utf8"));
82298
+ } catch {
82299
+ if (shouldObserveInboxPull) {
82300
+ reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
82301
+ } else {
82302
+ reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
82303
+ }
82304
+ }
82305
+ if (parsed !== undefined) {
82306
+ if (shouldObserveInboxPull) {
82307
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
82308
+ reportInboxPullObservationError({
82309
+ agentId: reg.agentId,
82310
+ reason: "invalid_inbox_shape",
82311
+ contentEncoding
82312
+ });
82313
+ } else {
82314
+ const messages = parsed.messages;
82315
+ if (messages.length > 0) {
82316
+ try {
82317
+ onPull(reg.agentId, messages, inboxPullObservationToken);
82318
+ } catch {
82319
+ reportInboxPullObservationError({
82320
+ agentId: reg.agentId,
82321
+ reason: "observer_failed",
82322
+ contentEncoding
82323
+ });
82324
+ }
82325
+ }
82326
+ }
82327
+ } else if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.applied) || !parsed.applied.every((cursor) => Boolean(cursor) && typeof cursor === "object" && !Array.isArray(cursor) && typeof cursor.channel === "string" && cursor.channel.length > 0 && typeof cursor.seq === "number" && Number.isSafeInteger(cursor.seq) && cursor.seq > 0)) {
82328
+ reportInboxAckObservationError({
81796
82329
  agentId: reg.agentId,
81797
- reason: "invalid_inbox_shape",
82330
+ reason: "invalid_ack_shape",
81798
82331
  contentEncoding
81799
82332
  });
81800
82333
  } else {
81801
- const messages = parsed.messages;
81802
- if (messages.length > 0) {
82334
+ const applied = parsed.applied;
82335
+ if (applied.length > 0) {
81803
82336
  try {
81804
- onPull(reg.agentId, messages, inboxPullObservationToken);
82337
+ onAck(reg.agentId, applied, inboxAckObservationToken);
81805
82338
  } catch {
81806
- reportInboxPullObservationError({
82339
+ reportInboxAckObservationError({
81807
82340
  agentId: reg.agentId,
81808
82341
  reason: "observer_failed",
81809
82342
  contentEncoding
@@ -81811,66 +82344,47 @@ async function startCredentialProxy(broker, options = {}) {
81811
82344
  }
81812
82345
  }
81813
82346
  }
81814
- } else if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.applied) || !parsed.applied.every((cursor) => Boolean(cursor) && typeof cursor === "object" && !Array.isArray(cursor) && typeof cursor.channel === "string" && cursor.channel.length > 0 && typeof cursor.seq === "number" && Number.isSafeInteger(cursor.seq) && cursor.seq > 0)) {
81815
- reportInboxAckObservationError({
81816
- agentId: reg.agentId,
81817
- reason: "invalid_ack_shape",
81818
- contentEncoding
81819
- });
81820
- } else {
81821
- const applied = parsed.applied;
81822
- if (applied.length > 0) {
81823
- try {
81824
- onAck(reg.agentId, applied, inboxAckObservationToken);
81825
- } catch {
81826
- reportInboxAckObservationError({
81827
- agentId: reg.agentId,
81828
- reason: "observer_failed",
81829
- contentEncoding
81830
- });
81831
- }
81832
- }
81833
82347
  }
81834
82348
  }
81835
- }
81836
- res.writeHead(res_.statusCode, res_.headers);
81837
- res.end(body);
81838
- });
81839
- } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
81840
- forwardPiiSendResponse(res_, res, piiTriggeredFilters);
81841
- } else {
81842
- res.writeHead(res_.statusCode ?? 502, res_.headers);
81843
- res_.pipe(res);
81844
- }
81845
- });
81846
- upstreamReq.on("error", (err) => {
81847
- if (responded)
81848
- return;
81849
- responded = true;
81850
- res.writeHead(502, { "content-type": "application/json" });
81851
- res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
81852
- });
81853
- const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
81854
- const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
81855
- upstreamReq.setTimeout(upstreamTimeoutMs, () => {
81856
- upstreamReq.destroy();
81857
- upstreamRes?.destroy();
81858
- if (responded) {
81859
- res.destroy();
81860
- return;
81861
- }
81862
- responded = true;
81863
- res.writeHead(504, { "content-type": "application/json" });
81864
- res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
81865
- });
81866
- res.on("close", () => {
81867
- upstreamReq.destroy();
81868
- upstreamRes?.destroy();
81869
- });
81870
- if (filteredBody)
81871
- upstreamReq.end(filteredBody);
81872
- else
81873
- req.pipe(upstreamReq);
82349
+ res.writeHead(res_.statusCode, res_.headers);
82350
+ res.end(body);
82351
+ });
82352
+ } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
82353
+ forwardPiiSendResponse(res_, res, piiTriggeredFilters);
82354
+ } else {
82355
+ res.writeHead(res_.statusCode ?? 502, res_.headers);
82356
+ res_.pipe(res);
82357
+ }
82358
+ });
82359
+ upstreamReq.on("error", (err) => {
82360
+ if (responded)
82361
+ return;
82362
+ responded = true;
82363
+ res.writeHead(502, { "content-type": "application/json" });
82364
+ res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
82365
+ });
82366
+ const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
82367
+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
82368
+ upstreamReq.setTimeout(upstreamTimeoutMs, () => {
82369
+ upstreamReq.destroy();
82370
+ upstreamRes?.destroy();
82371
+ if (responded) {
82372
+ res.destroy();
82373
+ return;
82374
+ }
82375
+ responded = true;
82376
+ res.writeHead(504, { "content-type": "application/json" });
82377
+ res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
82378
+ });
82379
+ res.on("close", () => {
82380
+ upstreamReq.destroy();
82381
+ upstreamRes?.destroy();
82382
+ });
82383
+ if (filteredBody)
82384
+ upstreamReq.end(filteredBody);
82385
+ else
82386
+ req.pipe(upstreamReq);
82387
+ })();
81874
82388
  });
81875
82389
  await new Promise((resolve6, reject) => {
81876
82390
  server.once("error", reject);