@alook/daemon 0.1.70 → 0.1.72

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 +1058 -489
  2. package/dist/index.js +948 -438
  3. package/package.json +4 -4
package/dist/cli/index.js CHANGED
@@ -13522,13 +13522,13 @@ var require_sourcemap_codec_umd = __commonJS((exports, module) => {
13522
13522
  });
13523
13523
  });
13524
13524
 
13525
- // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13525
+ // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.3/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
13526
13526
  var require_resolve_uri_umd = __commonJS((exports, module) => {
13527
13527
  (function(global, factory) {
13528
13528
  typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.resolveURI = factory());
13529
13529
  })(exports, function() {
13530
13530
  const schemeRegex = /^[\w+.-]+:\/\//;
13531
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13531
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?(\[[^\]]+\]|[^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
13532
13532
  const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
13533
13533
  function isAbsoluteUrl(input2) {
13534
13534
  return schemeRegex.test(input2);
@@ -43079,7 +43079,7 @@ var CommunityResourceProfileSchema = exports_external.strictObject({
43079
43079
  statusText: exports_external.string().nullable().optional()
43080
43080
  });
43081
43081
  // ../shared/src/business-schema-version.ts
43082
- var BUSINESS_SCHEMA_VERSION = 10;
43082
+ var BUSINESS_SCHEMA_VERSION = 11;
43083
43083
 
43084
43084
  // ../shared/src/community-contract.ts
43085
43085
  var COMMUNITY_RESOURCE_CONTRACT_VERSION = BUSINESS_SCHEMA_VERSION;
@@ -43112,7 +43112,136 @@ var AgentModelReportSchema = exports_external.object({
43112
43112
  provider: identity2.optional(),
43113
43113
  source: exports_external.enum(["response", "session"]),
43114
43114
  responseId: identity2.optional(),
43115
- observedAt: exports_external.string().datetime({ offset: true })
43115
+ observedAt: exports_external.iso.datetime({ offset: true })
43116
+ });
43117
+
43118
+ // ../shared/src/community-decision-card.ts
43119
+ var DECISION_CARD_EMBED_KIND = "decision_card";
43120
+ var DECISION_CARD_EMBED_VERSION = 1;
43121
+ var DECISION_CARD_MAX_BYTES = 8 * 1024;
43122
+ var DECISION_CARD_MAX_MENTIONS = 20;
43123
+ var DECISION_CARD_MIN_QUESTIONS = 1;
43124
+ var DECISION_CARD_MAX_QUESTIONS = 4;
43125
+ var DECISION_CARD_MIN_OPTIONS = 2;
43126
+ var DECISION_CARD_MAX_OPTIONS = 6;
43127
+ var DECISION_CARD_ID_MAX_LENGTH = 40;
43128
+ var DECISION_CARD_SUMMARY_MAX_LENGTH = 240;
43129
+ var DECISION_CARD_HEADER_MAX_LENGTH = 24;
43130
+ var DECISION_CARD_QUESTION_MAX_LENGTH = 300;
43131
+ var DECISION_CARD_OPTION_LABEL_MAX_LENGTH = 120;
43132
+ var DECISION_CARD_OPTION_DESC_MAX_LENGTH = 240;
43133
+ var DECISION_CARD_OTHER_TEXT_MAX_LENGTH = 500;
43134
+ function decisionCardUtf8Bytes(value) {
43135
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
43136
+ }
43137
+ var idFieldSchema = exports_external.string().trim().min(1).max(DECISION_CARD_ID_MAX_LENGTH).regex(/^[a-zA-Z0-9_-]+$/, "id must contain only letters, digits, hyphens, or underscores");
43138
+ var optionalTrimmedText = (max) => exports_external.string().trim().max(max).transform((value) => value.length > 0 ? value : undefined).optional();
43139
+ var requiredSummarySchema = exports_external.string().trim().min(1, "summary is required").max(DECISION_CARD_SUMMARY_MAX_LENGTH);
43140
+ var DecisionCardOptionInputSchema = exports_external.strictObject({
43141
+ id: idFieldSchema.optional(),
43142
+ label: exports_external.string().trim().min(1).max(DECISION_CARD_OPTION_LABEL_MAX_LENGTH),
43143
+ description: optionalTrimmedText(DECISION_CARD_OPTION_DESC_MAX_LENGTH),
43144
+ recommended: exports_external.boolean().optional()
43145
+ });
43146
+ var DecisionCardQuestionInputSchema = exports_external.strictObject({
43147
+ id: idFieldSchema.optional(),
43148
+ header: optionalTrimmedText(DECISION_CARD_HEADER_MAX_LENGTH),
43149
+ question: exports_external.string().trim().min(1).max(DECISION_CARD_QUESTION_MAX_LENGTH),
43150
+ multiSelect: exports_external.boolean().optional(),
43151
+ allowOther: exports_external.boolean().optional(),
43152
+ options: exports_external.array(DecisionCardOptionInputSchema).min(DECISION_CARD_MIN_OPTIONS).max(DECISION_CARD_MAX_OPTIONS)
43153
+ });
43154
+ function hasDuplicateIds(ids) {
43155
+ return new Set(ids).size !== ids.length;
43156
+ }
43157
+ var mentionHandleSchema = exports_external.string().trim().min(1).max(128).refine((value) => parseNameAndTag(value.startsWith("@") ? value.slice(1) : value) !== null, { message: 'mention must be a handle like "@alice#0001"' });
43158
+ var DecisionCardInputSchema = exports_external.strictObject({
43159
+ mentions: exports_external.array(mentionHandleSchema).max(DECISION_CARD_MAX_MENTIONS).optional(),
43160
+ summary: requiredSummarySchema,
43161
+ questions: exports_external.array(DecisionCardQuestionInputSchema).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS)
43162
+ }).superRefine((value, ctx) => {
43163
+ const qIds = value.questions.map((q, index) => q.id ?? `q${index + 1}`);
43164
+ if (hasDuplicateIds(qIds)) {
43165
+ ctx.addIssue({
43166
+ code: "custom",
43167
+ path: ["questions"],
43168
+ message: "question ids must be unique"
43169
+ });
43170
+ }
43171
+ value.questions.forEach((q, qIndex) => {
43172
+ const optIds = q.options.map((opt, oIndex) => opt.id ?? `o${oIndex + 1}`);
43173
+ if (hasDuplicateIds(optIds)) {
43174
+ ctx.addIssue({
43175
+ code: "custom",
43176
+ path: ["questions", qIndex, "options"],
43177
+ message: "option ids must be unique within a question"
43178
+ });
43179
+ }
43180
+ });
43181
+ if (decisionCardUtf8Bytes(value) > DECISION_CARD_MAX_BYTES) {
43182
+ ctx.addIssue({
43183
+ code: "custom",
43184
+ path: [],
43185
+ message: `decision card exceeds ${DECISION_CARD_MAX_BYTES} bytes`
43186
+ });
43187
+ }
43188
+ });
43189
+ var DecisionCardCliOptionSchema = exports_external.union([
43190
+ exports_external.string().trim().min(1).max(DECISION_CARD_OPTION_LABEL_MAX_LENGTH).transform((label) => ({ label })),
43191
+ DecisionCardOptionInputSchema
43192
+ ]);
43193
+ var DecisionCardCliInputSchema = exports_external.strictObject({
43194
+ mentions: exports_external.array(mentionHandleSchema).max(DECISION_CARD_MAX_MENTIONS).optional(),
43195
+ summary: requiredSummarySchema,
43196
+ questions: exports_external.array(exports_external.strictObject({
43197
+ id: idFieldSchema.optional(),
43198
+ header: optionalTrimmedText(DECISION_CARD_HEADER_MAX_LENGTH),
43199
+ question: exports_external.string().trim().min(1).max(DECISION_CARD_QUESTION_MAX_LENGTH),
43200
+ multiSelect: exports_external.boolean().optional(),
43201
+ allowOther: exports_external.boolean().optional(),
43202
+ options: exports_external.array(DecisionCardCliOptionSchema).min(DECISION_CARD_MIN_OPTIONS).max(DECISION_CARD_MAX_OPTIONS)
43203
+ })).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS)
43204
+ });
43205
+ function parseDecisionCardCliInput(raw) {
43206
+ const pre = DecisionCardCliInputSchema.safeParse(raw);
43207
+ if (!pre.success)
43208
+ return pre;
43209
+ return DecisionCardInputSchema.safeParse(pre.data);
43210
+ }
43211
+ var DecisionCardAssigneeSchema = exports_external.strictObject({
43212
+ userId: exports_external.string().min(1),
43213
+ handle: exports_external.string().min(1)
43214
+ });
43215
+ var DecisionCardNormalizedOptionSchema = exports_external.strictObject({
43216
+ id: idFieldSchema,
43217
+ label: exports_external.string().trim().min(1).max(DECISION_CARD_OPTION_LABEL_MAX_LENGTH),
43218
+ description: exports_external.string().trim().min(1).max(DECISION_CARD_OPTION_DESC_MAX_LENGTH).optional(),
43219
+ recommended: exports_external.boolean().optional()
43220
+ });
43221
+ var DecisionCardNormalizedQuestionSchema = exports_external.strictObject({
43222
+ id: idFieldSchema,
43223
+ header: exports_external.string().trim().min(1).max(DECISION_CARD_HEADER_MAX_LENGTH).optional(),
43224
+ question: exports_external.string().trim().min(1).max(DECISION_CARD_QUESTION_MAX_LENGTH),
43225
+ multiSelect: exports_external.boolean(),
43226
+ allowOther: exports_external.boolean(),
43227
+ options: exports_external.array(DecisionCardNormalizedOptionSchema).min(DECISION_CARD_MIN_OPTIONS).max(DECISION_CARD_MAX_OPTIONS)
43228
+ });
43229
+ var DecisionCardEmbedSchema = exports_external.strictObject({
43230
+ kind: exports_external.literal(DECISION_CARD_EMBED_KIND),
43231
+ version: exports_external.literal(DECISION_CARD_EMBED_VERSION),
43232
+ summary: exports_external.string().trim().min(1).max(DECISION_CARD_SUMMARY_MAX_LENGTH).optional(),
43233
+ assignees: exports_external.array(DecisionCardAssigneeSchema).max(DECISION_CARD_MAX_MENTIONS),
43234
+ questions: exports_external.array(DecisionCardNormalizedQuestionSchema).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS),
43235
+ respondedUserIds: exports_external.array(exports_external.string().min(1)).optional(),
43236
+ viewerDismissed: exports_external.boolean().optional()
43237
+ });
43238
+ var DecisionCardAnswerItemSchema = exports_external.strictObject({
43239
+ questionId: idFieldSchema,
43240
+ selectedOptionIds: exports_external.array(idFieldSchema).max(DECISION_CARD_MAX_OPTIONS).optional(),
43241
+ otherText: exports_external.string().trim().max(DECISION_CARD_OTHER_TEXT_MAX_LENGTH).optional()
43242
+ });
43243
+ var DecisionCardAnswerInputSchema = exports_external.strictObject({
43244
+ answers: exports_external.array(DecisionCardAnswerItemSchema).min(DECISION_CARD_MIN_QUESTIONS).max(DECISION_CARD_MAX_QUESTIONS)
43116
43245
  });
43117
43246
 
43118
43247
  // ../shared/src/provider-telemetry.ts
@@ -43191,8 +43320,8 @@ var QuotaLimitSchema = exports_external.object({
43191
43320
  model: QuotaModelIdentitySchema,
43192
43321
  window: QuotaWindowIdentitySchema
43193
43322
  }).strict(),
43194
- usedPercent: exports_external.number().finite().min(0).max(100),
43195
- resetsAt: exports_external.string().datetime({ offset: true }).optional()
43323
+ usedPercent: exports_external.number().min(0).max(100),
43324
+ resetsAt: exports_external.iso.datetime({ offset: true }).optional()
43196
43325
  }).strict();
43197
43326
  function quotaIdentity(limit) {
43198
43327
  const { product, model, window: window2, limitId } = limit.bucket;
@@ -43539,12 +43668,38 @@ var CommunityAgentCursorSchema = exports_external.object({
43539
43668
  var CommunityAgentSendRequestSchema = exports_external.object({
43540
43669
  channel: exports_external.string().min(1),
43541
43670
  content: CommunityAgentMessageContentSchema,
43671
+ question: DecisionCardInputSchema.optional(),
43542
43672
  attachments: exports_external.array(exports_external.string().min(1)).max(MAX_ATTACHMENTS_PER_MESSAGE).default([]),
43543
43673
  seenUpToSeq: CommunityAgentSeqSchema.optional(),
43544
43674
  replyToSeq: CommunityAgentPositiveSeqSchema.optional(),
43545
43675
  force: exports_external.boolean().optional(),
43546
43676
  nonce: exports_external.string().min(1).max(128).optional()
43547
- }).refine((d) => d.content.text.trim().length > 0 || d.attachments.length > 0, { message: "message must have text or attachments" });
43677
+ }).superRefine((d, ctx) => {
43678
+ if (d.question !== undefined) {
43679
+ if (d.attachments.length > 0) {
43680
+ ctx.addIssue({
43681
+ code: "custom",
43682
+ path: ["attachments"],
43683
+ message: "decision card messages cannot include attachments"
43684
+ });
43685
+ }
43686
+ if (d.content.text.trim().length > 0) {
43687
+ ctx.addIssue({
43688
+ code: "custom",
43689
+ path: ["content", "text"],
43690
+ message: "decision card messages must omit content.text"
43691
+ });
43692
+ }
43693
+ return;
43694
+ }
43695
+ if (d.content.text.trim().length === 0 && d.attachments.length === 0) {
43696
+ ctx.addIssue({
43697
+ code: "custom",
43698
+ path: [],
43699
+ message: "message must have text or attachments"
43700
+ });
43701
+ }
43702
+ });
43548
43703
  var CommunityAgentAttachmentUploadResponseSchema = exports_external.object({
43549
43704
  id: exports_external.string(),
43550
43705
  filename: exports_external.string(),
@@ -43689,7 +43844,7 @@ var BotAuditEventKindSchema = exports_external.enum([
43689
43844
  var HostBotAuditEventFrameSchema = exports_external.object({
43690
43845
  type: exports_external.literal("bot_audit_event"),
43691
43846
  eventId: exports_external.string().min(1).max(128).optional(),
43692
- occurredAt: exports_external.string().datetime({ offset: true }).optional(),
43847
+ occurredAt: exports_external.iso.datetime({ offset: true }).optional(),
43693
43848
  agentId: exports_external.string().min(1),
43694
43849
  sessionId: exports_external.string().nullable().optional(),
43695
43850
  launchId: exports_external.string().nullable().optional(),
@@ -43838,7 +43993,7 @@ var CommunityMessageResourceSchema = exports_external.strictObject({
43838
43993
  seq: exports_external.number().int().nonnegative(),
43839
43994
  authorId: id,
43840
43995
  createdAt: exports_external.string(),
43841
- type: exports_external.enum(["chat", "system"]),
43996
+ type: exports_external.enum(["chat", "system", "question"]),
43842
43997
  content: exports_external.string(),
43843
43998
  replyToId: nullableId,
43844
43999
  clientNonce: exports_external.string().nullable(),
@@ -43931,11 +44086,18 @@ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
43931
44086
  servers: exports_external.array(CommunityServerResourceSchema),
43932
44087
  serverMemberships: exports_external.array(CommunityServerMembershipResourceSchema),
43933
44088
  channels: exports_external.array(CommunityChannelResourceSchema),
43934
- memberships: exports_external.array(CommunityChannelMembershipResourceSchema)
44089
+ memberships: exports_external.array(CommunityChannelMembershipResourceSchema),
44090
+ categories: exports_external.array(CommunityCategoryResourceSchema).optional(),
44091
+ dmPeers: exports_external.array(exports_external.strictObject({ channelId: id, userId: id })).optional()
43935
44092
  }).superRefine((bundle, ctx) => {
43936
44093
  const channels = new Set(bundle.channels.map((row) => row.id));
43937
44094
  const servers = new Set(bundle.servers.map((row) => row.id));
43938
- if (channels.size !== bundle.channels.length || servers.size !== bundle.servers.length || new Set(bundle.messages.map((row) => row.id)).size !== bundle.messages.length || new Set(bundle.profiles.map((row) => row.id)).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)))
44095
+ const categories = bundle.categories ?? [];
44096
+ const dmPeers = bundle.dmPeers ?? [];
44097
+ const dmChannels = new Set(bundle.channels.filter((row) => row.type === "dm").map((row) => row.id));
44098
+ const profiles = new Set(bundle.profiles.map((row) => row.id));
44099
+ const readableCategories = new Map(bundle.channels.flatMap((row) => row.categoryId ? [[row.categoryId, row.serverId]] : []));
44100
+ if (channels.size !== bundle.channels.length || servers.size !== bundle.servers.length || new Set(categories.map((row) => row.id)).size !== categories.length || categories.some((row) => readableCategories.get(row.id) !== row.serverId) || new Set(dmPeers.map((row) => row.channelId)).size !== dmPeers.length || dmPeers.some((row) => !dmChannels.has(row.channelId) || row.userId === bundle.viewerId || !profiles.has(row.userId)) || new Set(bundle.messages.map((row) => row.id)).size !== bundle.messages.length || profiles.size !== bundle.profiles.length || new Set(bundle.memberships.map((row) => `${row.channelId}:${row.userId}:${row.relation}`)).size !== bundle.memberships.length || new Set(bundle.serverMemberships.map((row) => `${row.serverId}:${row.userId}`)).size !== bundle.serverMemberships.length || bundle.messages.some((row) => !channels.has(row.channelId)) || bundle.servers.some((row) => !bundle.serverMemberships.some((member) => member.serverId === row.id && member.userId === bundle.viewerId)) || bundle.channels.some((row) => !bundle.memberships.some((member) => member.channelId === row.id && member.userId === bundle.viewerId && member.relation === "access")) || bundle.channels.some((row) => row.serverId !== null && !servers.has(row.serverId) || row.parentChannelId !== null && !channels.has(row.parentChannelId)) || bundle.memberships.some((row) => row.userId !== bundle.viewerId || !channels.has(row.channelId)) || bundle.serverMemberships.some((row) => row.userId !== bundle.viewerId || !servers.has(row.serverId)))
43939
44101
  ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
43940
44102
  });
43941
44103
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
@@ -44058,7 +44220,7 @@ var AttentionScopeSchema = exports_external.strictObject({
44058
44220
  });
44059
44221
  var AttentionItemSchema = exports_external.strictObject({
44060
44222
  id: id2,
44061
- kind: exports_external.enum(["mention", "reply", "friend_request", "forum_post"]),
44223
+ kind: exports_external.enum(["mention", "reply", "friend_request", "forum_post", "question"]),
44062
44224
  sourceId: id2,
44063
44225
  scopeId: id2.nullable().optional(),
44064
44226
  messageId: id2.nullable().optional(),
@@ -44093,7 +44255,7 @@ var AttentionItemSchema = exports_external.strictObject({
44093
44255
  ctx.addIssue({ code: "custom", message: "message attention requires an actor" });
44094
44256
  }
44095
44257
  if (item.childChannelId || item.openerSeq !== undefined || item.readTarget) {
44096
- ctx.addIssue({ code: "custom", message: "mention or reply cannot carry forum presentation refs" });
44258
+ ctx.addIssue({ code: "custom", message: "message attention cannot carry forum presentation refs" });
44097
44259
  }
44098
44260
  });
44099
44261
  var AttentionIncludedServerSchema = CommunityServerResourceSchema.pick({ id: true, name: true, discriminator: true });
@@ -44149,6 +44311,7 @@ var AccountAttentionProjectionSchema = exports_external.strictObject({
44149
44311
  items: exports_external.array(AttentionItemSchema),
44150
44312
  limit: exports_external.number().int().positive(),
44151
44313
  truncated: exports_external.boolean(),
44314
+ todosTruncated: exports_external.boolean().optional(),
44152
44315
  included: AttentionIncludedSchema
44153
44316
  });
44154
44317
  var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
@@ -44211,7 +44374,7 @@ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
44211
44374
  ctx.addIssue({ code: "custom", message: `duplicate attention item: ${item.id}` });
44212
44375
  }
44213
44376
  itemIds.add(item.id);
44214
- if (item.scopeId && !scopeIds.has(item.scopeId)) {
44377
+ if (item.kind !== "question" && item.scopeId && !scopeIds.has(item.scopeId)) {
44215
44378
  ctx.addIssue({ code: "custom", message: `attention item references missing scope: ${item.scopeId}` });
44216
44379
  }
44217
44380
  if (item.kind === "friend_request") {
@@ -44220,6 +44383,16 @@ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
44220
44383
  }
44221
44384
  continue;
44222
44385
  }
44386
+ if (item.kind === "question") {
44387
+ const message2 = item.messageId ? messageById.get(item.messageId) : undefined;
44388
+ const channel = item.scopeId ? channelById.get(item.scopeId) : undefined;
44389
+ const dm = item.scopeId ? dmById.get(item.scopeId) : undefined;
44390
+ const ownerValid = Boolean(channel && serverById.has(channel.serverId) || dm && profileById.has(dm.userId));
44391
+ if (!item.scopeId || !message2 || message2.channelId !== item.scopeId || !item.actorUserId || !profileById.has(item.actorUserId) || !ownerValid) {
44392
+ ctx.addIssue({ code: "custom", message: `question attention references incomplete owners: ${item.id}` });
44393
+ }
44394
+ continue;
44395
+ }
44223
44396
  const scope = item.scopeId ? snapshot.scopes.find((candidate) => candidate.scopeId === item.scopeId) : undefined;
44224
44397
  const message = item.messageId ? messageById.get(item.messageId) : undefined;
44225
44398
  if (!scope || !message) {
@@ -44243,7 +44416,7 @@ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
44243
44416
  var EntitlementValueSchema = exports_external.lazy(() => exports_external.union([
44244
44417
  exports_external.null(),
44245
44418
  exports_external.boolean(),
44246
- exports_external.number().finite(),
44419
+ exports_external.number(),
44247
44420
  exports_external.string(),
44248
44421
  exports_external.array(EntitlementValueSchema),
44249
44422
  exports_external.record(exports_external.string(), EntitlementValueSchema)
@@ -44270,11 +44443,11 @@ var BillingOfferSchema = exports_external.object({
44270
44443
  var BillingSubscriptionSchema = exports_external.object({
44271
44444
  plan: BillingPlanSchema,
44272
44445
  status: exports_external.string().min(1),
44273
- currentPeriodEnd: exports_external.string().datetime().nullable(),
44274
- cancelAt: exports_external.string().datetime().nullable(),
44446
+ currentPeriodEnd: exports_external.iso.datetime().nullable(),
44447
+ cancelAt: exports_external.iso.datetime().nullable(),
44275
44448
  scheduledChange: exports_external.object({
44276
44449
  plan: BillingPlanSchema,
44277
- effectiveAt: exports_external.string().datetime()
44450
+ effectiveAt: exports_external.iso.datetime()
44278
44451
  }).nullable()
44279
44452
  });
44280
44453
  var PublicPricingSchema = exports_external.object({
@@ -44299,7 +44472,7 @@ var BillingPortalRequestSchema = exports_external.strictObject({
44299
44472
  priceId: exports_external.string().min(1).max(255).optional()
44300
44473
  });
44301
44474
  var BillingRedirectResponseSchema = exports_external.object({
44302
- url: exports_external.string().url()
44475
+ url: exports_external.url()
44303
44476
  });
44304
44477
  // ../shared/src/utils/day-key.ts
44305
44478
  function utcDayKey(now) {
@@ -44337,7 +44510,7 @@ function dayKeyInTimeZone(now, timeZone) {
44337
44510
  return `${year}-${month}-${day}`;
44338
44511
  }
44339
44512
 
44340
- // ../../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
44513
+ // ../../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
44341
44514
  var entityKind = Symbol.for("drizzle:entityKind");
44342
44515
  var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
44343
44516
  function is(value, type) {
@@ -44362,7 +44535,7 @@ function is(value, type) {
44362
44535
  return false;
44363
44536
  }
44364
44537
 
44365
- // ../../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
44538
+ // ../../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
44366
44539
  class Column {
44367
44540
  constructor(table, config2) {
44368
44541
  this.table = table;
@@ -44412,7 +44585,7 @@ class Column {
44412
44585
  }
44413
44586
  }
44414
44587
 
44415
- // ../../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
44588
+ // ../../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
44416
44589
  class ColumnBuilder {
44417
44590
  static [entityKind] = "ColumnBuilder";
44418
44591
  config;
@@ -44468,20 +44641,20 @@ class ColumnBuilder {
44468
44641
  }
44469
44642
  }
44470
44643
 
44471
- // ../../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
44644
+ // ../../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
44472
44645
  var TableName = Symbol.for("drizzle:Name");
44473
44646
 
44474
- // ../../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
44647
+ // ../../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
44475
44648
  function iife(fn, ...args) {
44476
44649
  return fn(...args);
44477
44650
  }
44478
44651
 
44479
- // ../../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
44652
+ // ../../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
44480
44653
  function uniqueKeyName(table, columns) {
44481
44654
  return `${table[TableName]}_${columns.join("_")}_unique`;
44482
44655
  }
44483
44656
 
44484
- // ../../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
44657
+ // ../../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
44485
44658
  class PgColumn extends Column {
44486
44659
  constructor(table, config2) {
44487
44660
  if (!config2.uniqueName) {
@@ -44530,7 +44703,7 @@ class ExtraConfigColumn extends PgColumn {
44530
44703
  }
44531
44704
  }
44532
44705
 
44533
- // ../../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
44706
+ // ../../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
44534
44707
  class PgEnumObjectColumn extends PgColumn {
44535
44708
  static [entityKind] = "PgEnumObjectColumn";
44536
44709
  enum;
@@ -44560,7 +44733,7 @@ class PgEnumColumn extends PgColumn {
44560
44733
  }
44561
44734
  }
44562
44735
 
44563
- // ../../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
44736
+ // ../../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
44564
44737
  class Subquery {
44565
44738
  static [entityKind] = "Subquery";
44566
44739
  constructor(sql, fields, alias, isWith = false, usedTables = []) {
@@ -44575,10 +44748,10 @@ class Subquery {
44575
44748
  }
44576
44749
  }
44577
44750
 
44578
- // ../../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
44751
+ // ../../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
44579
44752
  var version2 = "0.45.4";
44580
44753
 
44581
- // ../../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
44754
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing.js
44582
44755
  var otel;
44583
44756
  var rawTracer;
44584
44757
  var tracer = {
@@ -44605,10 +44778,10 @@ var tracer = {
44605
44778
  }
44606
44779
  };
44607
44780
 
44608
- // ../../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
44781
+ // ../../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
44609
44782
  var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
44610
44783
 
44611
- // ../../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
44784
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.js
44612
44785
  var Schema = Symbol.for("drizzle:Schema");
44613
44786
  var Columns = Symbol.for("drizzle:Columns");
44614
44787
  var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
@@ -44646,7 +44819,7 @@ class Table {
44646
44819
  }
44647
44820
  }
44648
44821
 
44649
- // ../../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
44822
+ // ../../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
44650
44823
  function isSQLWrapper(value) {
44651
44824
  return value !== null && value !== undefined && typeof value.getSQL === "function";
44652
44825
  }
@@ -45009,7 +45182,7 @@ Subquery.prototype.getSQL = function() {
45009
45182
  return new SQL([this]);
45010
45183
  };
45011
45184
 
45012
- // ../../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
45185
+ // ../../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
45013
45186
  class ColumnAliasProxyHandler {
45014
45187
  constructor(table) {
45015
45188
  this.table = table;
@@ -45065,7 +45238,7 @@ class TableAliasProxyHandler {
45065
45238
  }
45066
45239
  }
45067
45240
 
45068
- // ../../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
45241
+ // ../../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
45069
45242
  function getColumnNameAndConfig(a, b) {
45070
45243
  return {
45071
45244
  name: typeof a === "string" && a.length > 0 ? a : "",
@@ -45074,7 +45247,7 @@ function getColumnNameAndConfig(a, b) {
45074
45247
  }
45075
45248
  var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
45076
45249
 
45077
- // ../../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
45250
+ // ../../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
45078
45251
  function bindIfParam(value, column) {
45079
45252
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
45080
45253
  return new Param(value, column);
@@ -45098,11 +45271,14 @@ function and(...unfilteredConditions) {
45098
45271
  new StringChunk(")")
45099
45272
  ]);
45100
45273
  }
45274
+ function isNull(value) {
45275
+ return sql`${value} is null`;
45276
+ }
45101
45277
  function isNotNull(value) {
45102
45278
  return sql`${value} is not null`;
45103
45279
  }
45104
45280
 
45105
- // ../../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
45281
+ // ../../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
45106
45282
  function desc(column) {
45107
45283
  return sql`${column} desc`;
45108
45284
  }
@@ -45120,6 +45296,7 @@ __export(exports_community_schema, {
45120
45296
  communityReadStateRevision: () => communityReadStateRevision,
45121
45297
  communityReadState: () => communityReadState,
45122
45298
  communityReaction: () => communityReaction,
45299
+ communityQuestionTodo: () => communityQuestionTodo,
45123
45300
  communityPushDevice: () => communityPushDevice,
45124
45301
  communityPin: () => communityPin,
45125
45302
  communityNotificationSetting: () => communityNotificationSetting,
@@ -45140,12 +45317,12 @@ __export(exports_community_schema, {
45140
45317
  communityAttachment: () => communityAttachment
45141
45318
  });
45142
45319
 
45143
- // ../../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
45320
+ // ../../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
45144
45321
  function alias(table, alias2) {
45145
45322
  return new Proxy(table, new TableAliasProxyHandler(alias2, false));
45146
45323
  }
45147
45324
 
45148
- // ../../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
45325
+ // ../../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
45149
45326
  class CheckBuilder {
45150
45327
  constructor(name, value) {
45151
45328
  this.name = name;
@@ -45172,7 +45349,7 @@ function check2(name, value) {
45172
45349
  return new CheckBuilder(name, value);
45173
45350
  }
45174
45351
 
45175
- // ../../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
45352
+ // ../../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
45176
45353
  class ForeignKeyBuilder {
45177
45354
  static [entityKind] = "SQLiteForeignKeyBuilder";
45178
45355
  reference;
@@ -45226,7 +45403,7 @@ class ForeignKey {
45226
45403
  }
45227
45404
  }
45228
45405
 
45229
- // ../../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
45406
+ // ../../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
45230
45407
  function uniqueKeyName2(table, columns) {
45231
45408
  return `${table[TableName]}_${columns.join("_")}_unique`;
45232
45409
  }
@@ -45271,7 +45448,7 @@ class UniqueConstraint {
45271
45448
  }
45272
45449
  }
45273
45450
 
45274
- // ../../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
45451
+ // ../../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
45275
45452
  class SQLiteColumnBuilder extends ColumnBuilder {
45276
45453
  static [entityKind] = "SQLiteColumnBuilder";
45277
45454
  foreignKeyConfigs = [];
@@ -45322,7 +45499,7 @@ class SQLiteColumn extends Column {
45322
45499
  static [entityKind] = "SQLiteColumn";
45323
45500
  }
45324
45501
 
45325
- // ../../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
45502
+ // ../../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
45326
45503
  class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
45327
45504
  static [entityKind] = "SQLiteBigIntBuilder";
45328
45505
  constructor(name) {
@@ -45410,7 +45587,7 @@ function blob(a, b) {
45410
45587
  return new SQLiteBlobBufferBuilder(name);
45411
45588
  }
45412
45589
 
45413
- // ../../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
45590
+ // ../../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
45414
45591
  class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
45415
45592
  static [entityKind] = "SQLiteCustomColumnBuilder";
45416
45593
  constructor(name, fieldConfig, customTypeParams) {
@@ -45451,7 +45628,7 @@ function customType(customTypeParams) {
45451
45628
  };
45452
45629
  }
45453
45630
 
45454
- // ../../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
45631
+ // ../../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
45455
45632
  class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
45456
45633
  static [entityKind] = "SQLiteBaseIntegerBuilder";
45457
45634
  constructor(name, dataType, columnType) {
@@ -45553,7 +45730,7 @@ function integer2(a, b) {
45553
45730
  return new SQLiteIntegerBuilder(name);
45554
45731
  }
45555
45732
 
45556
- // ../../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
45733
+ // ../../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
45557
45734
  class SQLiteNumericBuilder extends SQLiteColumnBuilder {
45558
45735
  static [entityKind] = "SQLiteNumericBuilder";
45559
45736
  constructor(name) {
@@ -45623,7 +45800,7 @@ function numeric(a, b) {
45623
45800
  return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
45624
45801
  }
45625
45802
 
45626
- // ../../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
45803
+ // ../../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
45627
45804
  class SQLiteRealBuilder extends SQLiteColumnBuilder {
45628
45805
  static [entityKind] = "SQLiteRealBuilder";
45629
45806
  constructor(name) {
@@ -45644,7 +45821,7 @@ function real(name) {
45644
45821
  return new SQLiteRealBuilder(name ?? "");
45645
45822
  }
45646
45823
 
45647
- // ../../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
45824
+ // ../../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
45648
45825
  class SQLiteTextBuilder extends SQLiteColumnBuilder {
45649
45826
  static [entityKind] = "SQLiteTextBuilder";
45650
45827
  constructor(name, config2) {
@@ -45699,7 +45876,7 @@ function text(a, b = {}) {
45699
45876
  return new SQLiteTextBuilder(name, config2);
45700
45877
  }
45701
45878
 
45702
- // ../../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
45879
+ // ../../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
45703
45880
  function getSQLiteColumnBuilders() {
45704
45881
  return {
45705
45882
  blob,
@@ -45711,7 +45888,7 @@ function getSQLiteColumnBuilders() {
45711
45888
  };
45712
45889
  }
45713
45890
 
45714
- // ../../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
45891
+ // ../../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
45715
45892
  var InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
45716
45893
 
45717
45894
  class SQLiteTable extends Table {
@@ -45745,7 +45922,7 @@ var sqliteTable = (name, columns, extraConfig) => {
45745
45922
  return sqliteTableBase(name, columns, extraConfig);
45746
45923
  };
45747
45924
 
45748
- // ../../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
45925
+ // ../../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
45749
45926
  class IndexBuilderOn {
45750
45927
  constructor(name, unique2) {
45751
45928
  this.name = name;
@@ -45791,7 +45968,7 @@ function uniqueIndex(name) {
45791
45968
  return new IndexBuilderOn(name, true);
45792
45969
  }
45793
45970
 
45794
- // ../../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
45971
+ // ../../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
45795
45972
  function primaryKey(...config2) {
45796
45973
  if (config2[0].columns) {
45797
45974
  return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
@@ -46087,7 +46264,20 @@ var communityMessage = sqliteTable("community_message", {
46087
46264
  }, (t) => [
46088
46265
  index("idx_community_message_author_id_lookup").on(t.authorId),
46089
46266
  index("idx_message_channel_created").on(t.channelId, t.createdAt),
46090
- index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt)
46267
+ index("idx_message_channel_mention_created").on(t.channelId, t.mentionType, t.createdAt),
46268
+ index("idx_community_message_channel_reply_author").on(t.channelId, t.replyToId, t.authorId).where(sql`${t.replyToId} IS NOT NULL`)
46269
+ ]);
46270
+ var communityQuestionTodo = sqliteTable("community_question_todo", {
46271
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
46272
+ messageId: text("message_id").notNull().references(() => communityMessage.id, { onDelete: "cascade" }),
46273
+ channelId: text("channel_id").notNull().references(() => communityChannel.id, { onDelete: "cascade" }),
46274
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
46275
+ dismissedAt: text("dismissed_at")
46276
+ }, (t) => [
46277
+ primaryKey({ columns: [t.userId, t.messageId] }),
46278
+ index("idx_community_question_todo_user_active").on(t.userId, desc(t.createdAt), desc(t.messageId)).where(isNull(t.dismissedAt)),
46279
+ index("idx_community_question_todo_message_id_lookup").on(t.messageId),
46280
+ index("idx_community_question_todo_channel_id_lookup").on(t.channelId)
46091
46281
  ]);
46092
46282
  var communityMessageSeq = sqliteTable("community_message_seq", {
46093
46283
  channelId: text("channel_id").primaryKey().references(() => communityChannel.id, { onDelete: "cascade" }),
@@ -46466,19 +46656,18 @@ class Logger {
46466
46656
  entry[k] = { message: v.message, stack: v.stack };
46467
46657
  }
46468
46658
  }
46469
- let line;
46470
- if (this.pretty) {
46659
+ const output2 = this.pretty ? (() => {
46471
46660
  const ts = entry.ts.replace("T", " ").replace("Z", "");
46472
46661
  const lvl = entry.level.toUpperCase().padEnd(5);
46473
46662
  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(" ");
46474
- line = `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
46475
- } else {
46476
- line = JSON.stringify(entry);
46477
- }
46663
+ return `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`;
46664
+ })() : entry;
46478
46665
  if (level === "error") {
46479
- console.error(line);
46666
+ console.error(output2);
46667
+ } else if (level === "warn") {
46668
+ console.warn(output2);
46480
46669
  } else {
46481
- console.log(line);
46670
+ console.log(output2);
46482
46671
  }
46483
46672
  }
46484
46673
  }
@@ -46754,7 +46943,9 @@ var AGENT_MESSAGE_COLUMNS = {
46754
46943
  createdAt: communityMessage.createdAt,
46755
46944
  channelId: communityMessage.channelId,
46756
46945
  seq: communityMessage.seq,
46757
- replyToId: communityMessage.replyToId
46946
+ replyToId: communityMessage.replyToId,
46947
+ type: communityMessage.type,
46948
+ embeds: communityMessage.embeds
46758
46949
  };
46759
46950
  var channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${communityChannelMember.addedAt}, ${communityServerMember.joinedAt}, '')`;
46760
46951
  var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
@@ -47002,6 +47193,7 @@ var communityInboxChangedSchema = exports_external.strictObject({
47002
47193
  "read_all",
47003
47194
  "mention_read_all",
47004
47195
  "mention_dismiss",
47196
+ "todo_dismiss",
47005
47197
  "notification_policy"
47006
47198
  ])
47007
47199
  });
@@ -55598,7 +55790,7 @@ function toResult(value) {
55598
55790
  }
55599
55791
  return value === null || value === undefined ? empty : [value];
55600
55792
  }
55601
- // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.4/node_modules/mdast-util-find-and-replace/lib/index.js
55793
+ // ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.5/node_modules/mdast-util-find-and-replace/lib/index.js
55602
55794
  function findAndReplace(tree, list2, options) {
55603
55795
  const settings = options || {};
55604
55796
  const ignored = convert(settings.ignore || []);
@@ -55634,9 +55826,7 @@ function findAndReplace(tree, list2, options) {
55634
55826
  if (typeof value === "string") {
55635
55827
  value = value.length > 0 ? { type: "text", value } : undefined;
55636
55828
  }
55637
- if (value === false) {
55638
- find.lastIndex = position2 + 1;
55639
- } else {
55829
+ if (value !== false) {
55640
55830
  if (start !== position2) {
55641
55831
  add({ type: "text", value: node3.value.slice(start, position2) });
55642
55832
  }
@@ -55649,6 +55839,10 @@ function findAndReplace(tree, list2, options) {
55649
55839
  start = position2 + match[0].length;
55650
55840
  change = true;
55651
55841
  }
55842
+ if (value === false || match[0].length === 0) {
55843
+ const code = node3.value.codePointAt(position2) || 0;
55844
+ find.lastIndex = position2 + (/[uv]/.test(find.flags) && code > 65535 ? 2 : 1);
55845
+ }
55652
55846
  if (!find.global) {
55653
55847
  break;
55654
55848
  }
@@ -55694,7 +55888,7 @@ function toFunction(replace) {
55694
55888
  return replace;
55695
55889
  };
55696
55890
  }
55697
- // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.0.1/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
55891
+ // ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.1.0/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
55698
55892
  var inConstruct = "phrasing";
55699
55893
  var notInConstruct = ["autolink", "link", "image", "label"];
55700
55894
  function gfmAutolinkLiteralFromMarkdown() {
@@ -55742,7 +55936,7 @@ function gfmAutolinkLiteralToMarkdown() {
55742
55936
  };
55743
55937
  }
55744
55938
  function enterLiteralAutolink(token) {
55745
- this.enter({ type: "link", title: null, url: "", children: [] }, token);
55939
+ this.enter({ type: "link", title: null, url: "", children: [], position: undefined }, token);
55746
55940
  }
55747
55941
  function enterLiteralAutolinkValue(token) {
55748
55942
  this.config.enter.autolinkProtocol.call(this, token);
@@ -55764,62 +55958,107 @@ function exitLiteralAutolink(token) {
55764
55958
  }
55765
55959
  function transformGfmAutolinkLiterals(tree) {
55766
55960
  findAndReplace(tree, [
55767
- [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
55768
- [/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail]
55961
+ [
55962
+ /(?<![\da-z])(https?:\/\/|www(?=\.))([\w-]*\.[\w\-.]*)([^\t\n\r ]*)/gi,
55963
+ findUrl
55964
+ ],
55965
+ [
55966
+ /(?<![\w+\-.@])xmpp:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)(\/(?:[\w\-/]|\.(?=[\dA-Za-z]))*)?/g,
55967
+ findXmpp
55968
+ ],
55969
+ [/(?<![\w+\-.@])mailto:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g, findMailto],
55970
+ [
55971
+ /(?<![\w+\-.]|(?:^|[^\d@A-Za-z])(?:mailto|xmpp):)([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g,
55972
+ findEmail
55973
+ ]
55769
55974
  ], { ignore: ["link", "linkReference"] });
55770
55975
  }
55771
55976
  function findUrl(_, protocol, domain2, path2, match) {
55772
- let prefix = "";
55773
55977
  if (!previous2(match)) {
55774
55978
  return false;
55775
55979
  }
55980
+ let prefix = "";
55776
55981
  if (/^w/i.test(protocol)) {
55777
55982
  domain2 = protocol + domain2;
55778
55983
  protocol = "";
55779
55984
  prefix = "http://";
55780
55985
  }
55781
- if (!isCorrectDomain(domain2)) {
55986
+ if (unicodePunctuation(domain2.charCodeAt(0)) || !isCorrectDomain(domain2)) {
55782
55987
  return false;
55783
55988
  }
55784
55989
  const parts = splitUrl(domain2 + path2);
55785
- if (!parts[0])
55786
- return false;
55787
55990
  const result = {
55788
55991
  type: "link",
55789
55992
  title: null,
55790
55993
  url: prefix + protocol + parts[0],
55791
- children: [{ type: "text", value: protocol + parts[0] }]
55994
+ children: [{ type: "text", value: protocol + parts[0], position: undefined }],
55995
+ position: undefined
55792
55996
  };
55793
55997
  if (parts[1]) {
55794
- return [result, { type: "text", value: parts[1] }];
55998
+ return [result, { type: "text", value: parts[1], position: undefined }];
55795
55999
  }
55796
56000
  return result;
55797
56001
  }
55798
- function findEmail(_, atext, label, match) {
55799
- if (!previous2(match, true) || /[-\d_]$/.test(label)) {
56002
+ function findEmail(_, atext, label) {
56003
+ if (/[\d\-_]$/.test(label)) {
55800
56004
  return false;
55801
56005
  }
55802
56006
  return {
55803
56007
  type: "link",
55804
56008
  title: null,
55805
56009
  url: "mailto:" + atext + "@" + label,
55806
- children: [{ type: "text", value: atext + "@" + label }]
56010
+ children: [{ type: "text", value: atext + "@" + label, position: undefined }],
56011
+ position: undefined
56012
+ };
56013
+ }
56014
+ function findMailto(_, atext, label) {
56015
+ if (/[\d\-_]$/.test(label)) {
56016
+ return false;
56017
+ }
56018
+ const value = "mailto:" + atext + "@" + label;
56019
+ return {
56020
+ type: "link",
56021
+ title: null,
56022
+ url: value,
56023
+ children: [{ type: "text", value, position: undefined }],
56024
+ position: undefined
56025
+ };
56026
+ }
56027
+ function findXmpp(matchValue, atext, label, resource, match) {
56028
+ if (/[\d\-_]$/.test(label) || resource && (!/[A-Za-z]$/.test(resource) || match.input.charAt(match.index + matchValue.length) === "@")) {
56029
+ return false;
56030
+ }
56031
+ const value = "xmpp:" + atext + "@" + label + (resource || "");
56032
+ return {
56033
+ type: "link",
56034
+ title: null,
56035
+ url: value,
56036
+ children: [{ type: "text", value, position: undefined }],
56037
+ position: undefined
55807
56038
  };
55808
56039
  }
55809
56040
  function isCorrectDomain(domain2) {
55810
56041
  const parts = domain2.split(".");
55811
- 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]))) {
56042
+ 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]))) {
55812
56043
  return false;
55813
56044
  }
55814
56045
  return true;
55815
56046
  }
55816
56047
  function splitUrl(url2) {
55817
- const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url2);
55818
- if (!trailExec) {
56048
+ let index3 = url2.length;
56049
+ while (index3 > 0) {
56050
+ const code = url2.charCodeAt(index3 - 1);
56051
+ 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) {
56052
+ index3--;
56053
+ } else {
56054
+ break;
56055
+ }
56056
+ }
56057
+ if (index3 === url2.length) {
55819
56058
  return [url2, undefined];
55820
56059
  }
55821
- url2 = url2.slice(0, trailExec.index);
55822
- let trail = trailExec[0];
56060
+ let trail = url2.slice(index3);
56061
+ url2 = url2.slice(0, index3);
55823
56062
  let closingParenIndex = trail.indexOf(")");
55824
56063
  const openingParens = ccount(url2, "(");
55825
56064
  let closingParens = ccount(url2, ")");
@@ -55831,9 +56070,9 @@ function splitUrl(url2) {
55831
56070
  }
55832
56071
  return [url2, trail];
55833
56072
  }
55834
- function previous2(match, email3) {
56073
+ function previous2(match) {
55835
56074
  const code = match.input.charCodeAt(match.index - 1);
55836
- return (match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code)) && (!email3 || code !== 47);
56075
+ return match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code);
55837
56076
  }
55838
56077
  // ../../node_modules/.pnpm/mdast-util-gfm-footnote@2.1.0/node_modules/mdast-util-gfm-footnote/lib/index.js
55839
56078
  footnoteReference.peek = footnoteReferencePeek;
@@ -56366,25 +56605,37 @@ function emphasisPeek(_, _1, state) {
56366
56605
  return state.options.emphasis || "*";
56367
56606
  }
56368
56607
 
56369
- // ../../node_modules/.pnpm/unist-util-visit@5.1.0/node_modules/unist-util-visit/lib/index.js
56370
- function visit2(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
56608
+ // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
56609
+ function visit2(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
56610
+ let check3;
56611
+ let visitors;
56371
56612
  let reverse;
56372
- let test;
56373
- let visitor;
56374
- if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
56375
- test = undefined;
56376
- visitor = testOrVisitor;
56377
- reverse = visitorOrReverse;
56378
- } else {
56379
- test = testOrVisitor;
56380
- visitor = visitorOrReverse;
56613
+ if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
56614
+ check3 = testOrEnterOrVisitors;
56615
+ visitors = enterOrVisitorsOrReverse;
56381
56616
  reverse = maybeReverse;
56617
+ } else {
56618
+ visitors = testOrEnterOrVisitors;
56619
+ reverse = enterOrVisitorsOrReverse;
56382
56620
  }
56383
- visitParents(tree, test, overload, reverse);
56384
- function overload(node3, parents) {
56385
- const parent = parents[parents.length - 1];
56386
- const index3 = parent ? parent.children.indexOf(node3) : undefined;
56387
- return visitor(node3, index3, parent);
56621
+ if (typeof visitors === "function") {
56622
+ visitParents(tree, check3, wrap2(visitors), reverse);
56623
+ } else {
56624
+ visitParents(tree, check3, wrapVisitors(visitors), reverse);
56625
+ }
56626
+ }
56627
+ function wrapVisitors(visitors) {
56628
+ if (!visitors || typeof visitors !== "object")
56629
+ return visitors;
56630
+ return {
56631
+ enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
56632
+ exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
56633
+ };
56634
+ }
56635
+ function wrap2(visitor) {
56636
+ return overload;
56637
+ function overload(node3, parents, index3) {
56638
+ return visitor(node3, index3, parents[parents.length - 1]);
56388
56639
  }
56389
56640
  }
56390
56641
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
@@ -59461,43 +59712,10 @@ function peek(_, _1, state) {
59461
59712
  return state.options.emphasis || "*";
59462
59713
  }
59463
59714
 
59464
- // ../../node_modules/.pnpm/unist-util-visit@5.2.0/node_modules/unist-util-visit/lib/index.js
59465
- function visit3(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, maybeReverse) {
59466
- let check4;
59467
- let visitors;
59468
- let reverse;
59469
- if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") {
59470
- check4 = testOrEnterOrVisitors;
59471
- visitors = enterOrVisitorsOrReverse;
59472
- reverse = maybeReverse;
59473
- } else {
59474
- visitors = testOrEnterOrVisitors;
59475
- reverse = enterOrVisitorsOrReverse;
59476
- }
59477
- if (typeof visitors === "function") {
59478
- visitParents(tree, check4, wrap2(visitors), reverse);
59479
- } else {
59480
- visitParents(tree, check4, wrapVisitors(visitors), reverse);
59481
- }
59482
- }
59483
- function wrapVisitors(visitors) {
59484
- if (!visitors || typeof visitors !== "object")
59485
- return visitors;
59486
- return {
59487
- enter: typeof visitors.enter === "function" ? wrap2(visitors.enter) : visitors.enter,
59488
- exit: typeof visitors.exit === "function" ? wrap2(visitors.exit) : visitors.exit
59489
- };
59490
- }
59491
- function wrap2(visitor) {
59492
- return overload;
59493
- function overload(node3, parents, index3) {
59494
- return visitor(node3, index3, parents[parents.length - 1]);
59495
- }
59496
- }
59497
59715
  // ../../node_modules/.pnpm/mdast-util-to-markdown@2.2.3/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
59498
59716
  function formatHeadingAsSetext2(node3, state) {
59499
59717
  let literalWithBreak = false;
59500
- visit3(node3, function(node4) {
59718
+ visit2(node3, function(node4) {
59501
59719
  if ("value" in node4 && /\r?\n|\r/.test(node4.value) || node4.type === "break") {
59502
59720
  literalWithBreak = true;
59503
59721
  return EXIT;
@@ -63402,9 +63620,11 @@ function parseNativeExecution(data) {
63402
63620
 
63403
63621
  class NativeExecutionReader {
63404
63622
  readRows;
63623
+ continuations;
63405
63624
  path;
63406
- constructor(home, sessionId, readRows = queryExecutionRows) {
63625
+ constructor(home, sessionId, readRows = queryExecutionRows, continuations = false) {
63407
63626
  this.readRows = readRows;
63627
+ this.continuations = continuations;
63408
63628
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
63409
63629
  throw new Error("Invalid native execution session identity");
63410
63630
  this.path = join7(home, "antigravity-cli", "conversations", `${sessionId}.db`);
@@ -63420,20 +63640,28 @@ class NativeExecutionReader {
63420
63640
  return { index: row.idx, executionId: execution.executionId, lastStepIndex: execution.lastStepIndex };
63421
63641
  }
63422
63642
  async terminal(checkpoint) {
63423
- const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex);
63424
- if (rows.length !== 1)
63643
+ const max = this.continuations ? 32 : 1;
63644
+ const rows = await this.readRows(this.path, checkpoint.index, checkpoint.lastStepIndex, undefined, max + 1);
63645
+ if (!rows.length || rows.length > max)
63425
63646
  throw new Error("Native execution terminal unavailable or ambiguous");
63426
- const row = this.validate(rows[0]);
63427
- const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
63428
- if (row.has_children !== 0)
63429
- throw new Error("Native executor subtrajectory ownership cannot be verified");
63430
- if (row.idx !== checkpoint.index + 1 || execution.executionId === checkpoint.executionId)
63431
- throw new Error("Native execution terminal does not belong to the new root");
63432
- if (execution.hasError || execution.reason === 1)
63433
- return "failed";
63434
- if (execution.reason === 2)
63435
- return "interrupted";
63436
- return execution.reason === 4 ? "success" : "failed";
63647
+ let lastStep = checkpoint.lastStepIndex;
63648
+ const identities = new Set([checkpoint.executionId]);
63649
+ let outcome = "success";
63650
+ for (let index3 = 0;index3 < rows.length; index3++) {
63651
+ const row = this.validate(rows[index3]);
63652
+ const execution = parseNativeExecution(Buffer.from(row.data, "hex"));
63653
+ if (row.has_children !== 0)
63654
+ throw new Error("Native executor subtrajectory ownership cannot be verified");
63655
+ if (row.idx !== checkpoint.index + index3 + 1 || identities.has(execution.executionId) || this.continuations && execution.lastStepIndex <= lastStep)
63656
+ throw new Error("Native execution terminal does not belong to the new root");
63657
+ identities.add(execution.executionId);
63658
+ lastStep = execution.lastStepIndex;
63659
+ if (execution.hasError || execution.reason !== 2 && execution.reason !== 4)
63660
+ outcome = "failed";
63661
+ else if (execution.reason === 2 && outcome !== "failed")
63662
+ outcome = "interrupted";
63663
+ }
63664
+ return outcome;
63437
63665
  }
63438
63666
  validate(row) {
63439
63667
  if (!Number.isSafeInteger(row.idx) || row.idx < 0 || !/^(?:[a-f0-9]{2})+$/i.test(row.data) || row.data.length > 2 * 1024 * 1024)
@@ -63455,10 +63683,12 @@ async function openNativeExecutionDatabase(path8, loadBuiltin = async () => {
63455
63683
  }
63456
63684
  return new sqlite.DatabaseSync(path8, { readOnly: true });
63457
63685
  }
63458
- async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = openNativeExecutionDatabase) {
63686
+ async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = openNativeExecutionDatabase, maxRows = 2) {
63459
63687
  if (after !== undefined && (!Number.isSafeInteger(after) || after < -1) || !Number.isSafeInteger(afterStep) || afterStep < -1)
63460
63688
  throw new Error("Invalid native execution cursor");
63461
- 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`}`;
63689
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows > 33)
63690
+ throw new Error("Invalid native execution read limit");
63691
+ 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}`}`;
63462
63692
  const db = await openDatabase(path8);
63463
63693
  try {
63464
63694
  return db.prepare(query).all();
@@ -63467,6 +63697,37 @@ async function queryExecutionRows(path8, after, afterStep = -1, openDatabase = o
63467
63697
  }
63468
63698
  }
63469
63699
 
63700
+ class NativeSessionActivityReader {
63701
+ sessionId;
63702
+ version;
63703
+ openDatabase;
63704
+ path;
63705
+ constructor(home, sessionId, version3, openDatabase = openNativeExecutionDatabase) {
63706
+ this.sessionId = sessionId;
63707
+ this.version = version3;
63708
+ this.openDatabase = openDatabase;
63709
+ if (!/^[a-zA-Z0-9_-]{1,100}$/.test(sessionId))
63710
+ throw new Error("Invalid native activity session identity");
63711
+ this.path = join7(home, "antigravity-cli", "conversation_summaries.db");
63712
+ }
63713
+ async activity() {
63714
+ if (this.version !== "1.5.16")
63715
+ return "unknown";
63716
+ const db = await this.openDatabase(this.path);
63717
+ try {
63718
+ const rows = db.prepare("SELECT status,not_fully_idle FROM conversation_summaries WHERE conversation_id = ? LIMIT 1").all(this.sessionId);
63719
+ const row = rows[0];
63720
+ if (!row || row.not_fully_idle !== 0 && row.not_fully_idle !== 1)
63721
+ return "unknown";
63722
+ if (row.status === "CASCADE_RUN_STATUS_RUNNING")
63723
+ return "running";
63724
+ return row.status === "CASCADE_RUN_STATUS_IDLE" ? row.not_fully_idle ? "running" : "idle" : "unknown";
63725
+ } finally {
63726
+ db.close();
63727
+ }
63728
+ }
63729
+ }
63730
+
63470
63731
  // agent-driver/dist/internal/model-observation.js
63471
63732
  function id3(value) {
63472
63733
  if (typeof value !== "string")
@@ -63684,6 +63945,18 @@ class AgyAcpLane {
63684
63945
  events = new EventEmitter;
63685
63946
  pending = new Map;
63686
63947
  toolCalls = new Map;
63948
+ completedTools = new Set;
63949
+ unownedContent = false;
63950
+ activityReader;
63951
+ activityRead;
63952
+ activityTimer;
63953
+ nativeActivity = "unknown";
63954
+ publishedActivity;
63955
+ activityRevision = 0;
63956
+ nativeVersion = "";
63957
+ contentOwner;
63958
+ executionIsolated = true;
63959
+ nativeClose = false;
63687
63960
  process = null;
63688
63961
  requestSequence = 0;
63689
63962
  started = false;
@@ -63759,10 +64032,13 @@ class AgyAcpLane {
63759
64032
  const sessionId = this.sessionId;
63760
64033
  if (!sessionId)
63761
64034
  throw new Error("Agy ACP handshake completed without a session id");
63762
- this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId);
64035
+ this.executionReader = this.options.executionReader ?? new NativeExecutionReader(this.stateHome, sessionId, undefined, this.nativeVersion === "1.5.16");
63763
64036
  this.processActivated = true;
63764
64037
  this.ready = true;
63765
64038
  this.events.emit("runtime_event", { kind: "session_init", sessionId, acquisition: { status: input2.sessionId ? "resumed" : "created", evidence: "native_api" } });
64039
+ this.activityReader = this.options.activityReader ?? new NativeSessionActivityReader(this.stateHome, sessionId, this.nativeVersion);
64040
+ await this.refreshActivity();
64041
+ this.scheduleActivity();
63766
64042
  const admission = await this.admitRoot(input2.text, input2.inputs);
63767
64043
  if (!admission.ok)
63768
64044
  throw new AgyAcpIncompatibleError(admission.error ?? "Native execution state unavailable");
@@ -63807,6 +64083,8 @@ class AgyAcpLane {
63807
64083
  stop(input2 = {}) {
63808
64084
  this.requestedStopReason ??= input2.reason ?? "requested_stop";
63809
64085
  this.ready = false;
64086
+ if (this.activityTimer)
64087
+ clearTimeout(this.activityTimer);
63810
64088
  this.currentPromptRequestId = null;
63811
64089
  this.terminalOwner = null;
63812
64090
  this.toolCalls.clear();
@@ -63824,20 +64102,29 @@ class AgyAcpLane {
63824
64102
  return this.stopPromise;
63825
64103
  }
63826
64104
  async stopPhysicalOnce(input2) {
64105
+ const deadline = Date.now() + (input2.forceAfterMs ?? SESSION_STOP_GRACE_MS);
63827
64106
  await this.spawnPromise?.catch(() => {
63828
64107
  return;
63829
64108
  });
63830
64109
  const proc = this.process;
63831
64110
  if (!proc)
63832
64111
  return;
64112
+ let closeAcknowledged = false;
64113
+ if (this.nativeClose && this.sessionId && !this.isClosed() && deadline > Date.now()) {
64114
+ try {
64115
+ await this.request("session/close", { sessionId: this.sessionId }, Math.max(1, deadline - Date.now())).promise;
64116
+ closeAcknowledged = true;
64117
+ } catch {}
64118
+ }
63833
64119
  if (proc.pid) {
63834
- await killProcessTree(proc.pid, { graceMs: input2.forceAfterMs ?? SESSION_STOP_GRACE_MS });
64120
+ await killProcessTree(proc.pid, { graceMs: closeAcknowledged ? 0 : Math.max(0, deadline - Date.now()) });
63835
64121
  } else if (!this.isClosed()) {
63836
64122
  proc.kill(input2.signal ?? "SIGTERM");
63837
64123
  }
63838
64124
  await this.executionRead?.catch(() => {
63839
64125
  return;
63840
64126
  });
64127
+ await this.activityRead;
63841
64128
  }
63842
64129
  async handshake(ctx) {
63843
64130
  const initialize = record3(await this.call("initialize", {
@@ -63852,6 +64139,7 @@ class AgyAcpLane {
63852
64139
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support protocol version 1");
63853
64140
  }
63854
64141
  const capabilities = record3(initialize.agentCapabilities);
64142
+ this.nativeClose = record3(record3(capabilities?.sessionCapabilities)?.close) !== null;
63855
64143
  if (capabilities?.loadSession !== true) {
63856
64144
  throw new AgyAcpIncompatibleError("Installed Agy ACP does not support persistent session loading");
63857
64145
  }
@@ -63859,6 +64147,7 @@ class AgyAcpLane {
63859
64147
  throw new AgyAcpIncompatibleError("Expected the native Antigravity CLI ACP server");
63860
64148
  }
63861
64149
  const version3 = record3(initialize.agentInfo)?.version;
64150
+ this.nativeVersion = typeof version3 === "string" ? version3 : "";
63862
64151
  this.usageProfile = version3 === "1.4.12" ? { inputIncludesCache: true, outputIncludesReasoning: false } : version3 === "1.5.9" ? { inputIncludesCache: false, outputIncludesReasoning: true } : undefined;
63863
64152
  if (!record3(record3(initialize.agentCapabilities)?.sessionCapabilities)?.resume) {
63864
64153
  throw new AgyAcpIncompatibleError("Antigravity CLI ACP does not support native session resume");
@@ -64065,6 +64354,7 @@ class AgyAcpLane {
64065
64354
  if (!this.ready || this.requestedStopReason || this.isClosed())
64066
64355
  return { ok: false, reason: "closed" };
64067
64356
  this.executionCheckpoint = checkpoint;
64357
+ this.executionIsolated = !this.unownedContent && !this.hasPendingTools();
64068
64358
  return this.admitPrompt(text7, "prompt", inputs);
64069
64359
  } catch {
64070
64360
  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." };
@@ -64091,7 +64381,7 @@ class AgyAcpLane {
64091
64381
  this.terminalOwner = prompt.receipt;
64092
64382
  this.currentPromptRequestId = requestId;
64093
64383
  if (delivery === "prompt") {
64094
- this.toolCalls.clear();
64384
+ this.contentOwner = !this.unownedContent && !this.hasPendingTools() ? prompt.receipt : undefined;
64095
64385
  this.promptOutcomes.clear();
64096
64386
  this.observedPrompts.clear();
64097
64387
  this.loopStartedAt = new Date().toISOString();
@@ -64158,13 +64448,22 @@ class AgyAcpLane {
64158
64448
  const read = this.executionReader.terminal(this.executionCheckpoint);
64159
64449
  this.executionRead = read;
64160
64450
  nativeOutcome = await read;
64451
+ if (!this.executionIsolated)
64452
+ nativeOutcome = "unknown";
64161
64453
  } catch {
64162
- verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
64454
+ if (this.executionIsolated)
64455
+ verificationError = new Error("Antigravity CLI native execution terminal could not be verified");
64456
+ else
64457
+ nativeOutcome = "unknown";
64163
64458
  } finally {
64164
64459
  this.executionRead = undefined;
64165
64460
  }
64166
64461
  if (this.terminalOwner !== owner || this.requestedStopReason || this.processTerminal)
64167
64462
  return;
64463
+ if (this.hasPendingTools())
64464
+ this.unownedContent = true;
64465
+ this.observeOutsideWork();
64466
+ this.refreshActivity();
64168
64467
  this.finishing = false;
64169
64468
  const outcomes = [...this.promptOutcomes].sort(([a], [b]) => b - a);
64170
64469
  let latest = outcomes.find(([, outcome]) => outcome.error)?.[1] ?? outcomes[0]?.[1];
@@ -64197,7 +64496,7 @@ class AgyAcpLane {
64197
64496
  this.usage.reset();
64198
64497
  this.currentPromptRequestId = null;
64199
64498
  this.terminalOwner = null;
64200
- this.toolCalls.clear();
64499
+ this.contentOwner = undefined;
64201
64500
  this.promptOutcomes.clear();
64202
64501
  this.observedPrompts.clear();
64203
64502
  if (!latest) {
@@ -64209,7 +64508,7 @@ class AgyAcpLane {
64209
64508
  kind: "turn_end",
64210
64509
  sessionId: this.sessionId ?? undefined,
64211
64510
  turnOwner: terminalOwner,
64212
- outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? "success" : "failed",
64511
+ outcome: latest?.stopReason === "cancelled" ? "interrupted" : latest?.stopReason === "end_turn" ? nativeOutcome === "unknown" ? "unknown" : "success" : "failed",
64213
64512
  stopReason: latest?.stopReason,
64214
64513
  ...latest?.stopReason === "cancelled" ? { pendingContent: "discard" } : {}
64215
64514
  });
@@ -64441,24 +64740,38 @@ class AgyAcpLane {
64441
64740
  this.rememberConfig(configuration, true);
64442
64741
  return;
64443
64742
  }
64444
- if (!this.ready || this.currentPromptRequestId === null) {
64445
- this.diagnostic("warning", "Agy ACP emitted a session update without an active prompt");
64743
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
64446
64744
  return;
64447
- }
64448
64745
  const update = record3(payload.update) ?? {};
64449
64746
  const updateType = update?.sessionUpdate;
64450
64747
  switch (updateType) {
64451
64748
  case "agent_message_chunk": {
64452
64749
  const content3 = record3(update.content);
64453
64750
  if (content3?.type === "text" && typeof content3.text === "string") {
64454
- this.events.emit("runtime_event", { kind: "assistant_message_delta", text: content3.text });
64751
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
64752
+ this.unownedContent = true;
64753
+ this.observeOutsideWork();
64754
+ }
64755
+ this.events.emit("runtime_event", {
64756
+ kind: "assistant_message_delta",
64757
+ text: content3.text,
64758
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64759
+ });
64455
64760
  }
64456
64761
  return;
64457
64762
  }
64458
64763
  case "agent_thought_chunk": {
64459
64764
  const content3 = record3(update.content);
64460
64765
  if (content3?.type === "text" && typeof content3.text === "string") {
64461
- this.events.emit("runtime_event", { kind: "assistant_reasoning_delta", text: content3.text });
64766
+ if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
64767
+ this.unownedContent = true;
64768
+ this.observeOutsideWork();
64769
+ }
64770
+ this.events.emit("runtime_event", {
64771
+ kind: "assistant_reasoning_delta",
64772
+ text: content3.text,
64773
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64774
+ });
64462
64775
  }
64463
64776
  return;
64464
64777
  }
@@ -64482,56 +64795,67 @@ class AgyAcpLane {
64482
64795
  this.diagnostic("warning", "Agy ACP emitted a malformed tool_call update");
64483
64796
  return;
64484
64797
  }
64485
- if (!this.toolCalls.has(update.toolCallId)) {
64486
- const name = typeof update.name === "string" ? update.name : update.title;
64487
- this.toolCalls.set(update.toolCallId, name);
64798
+ if (this.completedTools.has(update.toolCallId))
64799
+ return;
64800
+ let tool = this.toolCalls.get(update.toolCallId);
64801
+ if (!tool) {
64802
+ tool = {
64803
+ name: typeof update.name === "string" ? update.name : update.title,
64804
+ owner: this.contentOwner
64805
+ };
64806
+ this.toolCalls.set(update.toolCallId, tool);
64488
64807
  this.events.emit("runtime_event", {
64489
64808
  kind: "tool_call",
64490
64809
  callId: update.toolCallId,
64491
- name,
64492
- input: update.rawInput
64493
- });
64494
- }
64495
- if ((update.status === "completed" || update.status === "failed") && this.toolCalls.get(update.toolCallId) !== null) {
64496
- const name = this.toolCalls.get(update.toolCallId) ?? update.title;
64497
- this.toolCalls.set(update.toolCallId, null);
64498
- this.events.emit("runtime_event", {
64499
- kind: "tool_output",
64500
- callId: update.toolCallId,
64501
- name,
64502
- outcome: update.status === "failed" ? "failed" : "success",
64503
- output: update.rawOutput
64810
+ name: tool.name,
64811
+ input: update.rawInput,
64812
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
64504
64813
  });
64505
64814
  }
64815
+ this.observeOutsideWork();
64816
+ if (update.status === "completed" || update.status === "failed")
64817
+ this.finishTool(update, tool);
64506
64818
  return;
64507
64819
  }
64508
64820
  case "tool_call_update": {
64509
- if (typeof update.toolCallId === "string" && (update.status === "completed" || update.status === "failed")) {
64510
- const name = this.toolCalls.get(update.toolCallId);
64511
- if (name === undefined || name === null)
64512
- return;
64513
- this.toolCalls.set(update.toolCallId, null);
64514
- this.events.emit("runtime_event", {
64515
- kind: "tool_output",
64516
- callId: update.toolCallId,
64517
- outcome: update.status === "failed" ? "failed" : "success",
64518
- output: update.rawOutput,
64519
- name
64520
- });
64521
- }
64821
+ if (typeof update.toolCallId !== "string")
64822
+ return;
64823
+ const tool = this.toolCalls.get(update.toolCallId);
64824
+ if (!tool)
64825
+ return;
64826
+ if (update.status === "completed" || update.status === "failed")
64827
+ this.finishTool(update, tool);
64522
64828
  return;
64523
64829
  }
64524
64830
  case "plan":
64525
64831
  this.events.emit("runtime_event", {
64526
64832
  kind: "internal_progress",
64527
64833
  source: "agy.acp",
64528
- itemType: "plan"
64834
+ itemType: "plan",
64835
+ ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
64529
64836
  });
64530
64837
  return;
64531
64838
  default:
64532
64839
  this.diagnostic("warning", `Unsupported Agy ACP session update: ${safeLabel(updateType)}`);
64533
64840
  }
64534
64841
  }
64842
+ finishTool(update, tool) {
64843
+ this.toolCalls.delete(update.toolCallId);
64844
+ this.completedTools.add(update.toolCallId);
64845
+ if (this.completedTools.size > 4096)
64846
+ this.completedTools.delete(this.completedTools.values().next().value);
64847
+ if (!tool.owner || tool.owner !== this.terminalOwner)
64848
+ this.unownedContent = true;
64849
+ this.observeOutsideWork();
64850
+ this.events.emit("runtime_event", {
64851
+ kind: "tool_output",
64852
+ callId: update.toolCallId,
64853
+ name: tool.name,
64854
+ outcome: update.status === "failed" ? "failed" : "success",
64855
+ output: update.rawOutput ?? update.content,
64856
+ ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
64857
+ });
64858
+ }
64535
64859
  diagnostic(severity, message) {
64536
64860
  this.events.emit("runtime_event", {
64537
64861
  kind: "runtime_diagnostic",
@@ -64540,6 +64864,58 @@ class AgyAcpLane {
64540
64864
  message
64541
64865
  });
64542
64866
  }
64867
+ hasPendingTools() {
64868
+ return this.toolCalls.size > 0;
64869
+ }
64870
+ publishActivity() {
64871
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
64872
+ return;
64873
+ const status = this.hasPendingTools() ? "running" : this.nativeActivity;
64874
+ if (status === this.publishedActivity)
64875
+ return;
64876
+ this.publishedActivity = status;
64877
+ this.events.emit("runtime_event", { kind: "session_activity", observation: { status, source: "agy.native" } });
64878
+ }
64879
+ observeOutsideWork() {
64880
+ this.activityRevision += 1;
64881
+ this.nativeActivity = "unknown";
64882
+ this.publishActivity();
64883
+ }
64884
+ refreshActivity() {
64885
+ if (this.activityRead)
64886
+ return this.activityRead;
64887
+ if (!this.ready || !this.activityReader || this.requestedStopReason || this.processTerminal)
64888
+ return Promise.resolve();
64889
+ const revision = this.activityRevision;
64890
+ const reading = (async () => {
64891
+ let status = "unknown";
64892
+ try {
64893
+ status = await this.activityReader.activity();
64894
+ } catch {}
64895
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
64896
+ return;
64897
+ if (revision === this.activityRevision)
64898
+ this.nativeActivity = status;
64899
+ if (status === "running" && this.currentPromptRequestId === null)
64900
+ this.unownedContent = true;
64901
+ this.publishActivity();
64902
+ })();
64903
+ this.activityRead = reading;
64904
+ reading.finally(() => {
64905
+ if (this.activityRead === reading)
64906
+ this.activityRead = undefined;
64907
+ });
64908
+ return reading;
64909
+ }
64910
+ scheduleActivity() {
64911
+ if (!this.ready || this.requestedStopReason || this.processTerminal)
64912
+ return;
64913
+ this.activityTimer = setTimeout(() => {
64914
+ this.activityTimer = undefined;
64915
+ this.refreshActivity().then(() => this.scheduleActivity());
64916
+ }, this.options.activityPollMs ?? 1000);
64917
+ this.activityTimer.unref?.();
64918
+ }
64543
64919
  protocolFailure(message) {
64544
64920
  const error62 = new Error(message);
64545
64921
  this.rejectAllPending(error62);
@@ -66831,7 +67207,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
66831
67207
  const candidates3 = [];
66832
67208
  const readDirectory = options.readDirectory ?? ((directory) => readdir(directory, { withFileTypes: true }));
66833
67209
  const statPath = options.statPath ?? stat;
66834
- const visit4 = async (directory, remainingDepth, includeFiles) => {
67210
+ const visit3 = async (directory, remainingDepth, includeFiles) => {
66835
67211
  let entries;
66836
67212
  try {
66837
67213
  entries = await readDirectory(directory);
@@ -66843,7 +67219,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
66843
67219
  await Promise.all(entries.map(async (entry) => {
66844
67220
  const entryPath = path9.join(directory, entry.name);
66845
67221
  if (entry.isDirectory() && remainingDepth > 0) {
66846
- await visit4(entryPath, remainingDepth - 1, true);
67222
+ await visit3(entryPath, remainingDepth - 1, true);
66847
67223
  } else if (includeFiles && entry.isFile() && entry.name.endsWith(".jsonl")) {
66848
67224
  try {
66849
67225
  const metadata = await statPath(entryPath);
@@ -66856,7 +67232,7 @@ async function collectJsonlFileCandidates(root3, options = {}) {
66856
67232
  }
66857
67233
  }));
66858
67234
  };
66859
- await visit4(root3, options.maxDepth ?? Number.POSITIVE_INFINITY, options.includeRootFiles ?? true);
67235
+ await visit3(root3, options.maxDepth ?? Number.POSITIVE_INFINITY, options.includeRootFiles ?? true);
66860
67236
  return candidates3;
66861
67237
  }
66862
67238
  function retainNewest(values2, key, value, topK) {
@@ -74542,6 +74918,10 @@ class LogicalAgentSession {
74542
74918
  events;
74543
74919
  closed;
74544
74920
  state = "new";
74921
+ activity;
74922
+ sessionMessage = emptySemanticAssembler();
74923
+ sessionReasoning = emptySemanticAssembler();
74924
+ sessionContentTimer;
74545
74925
  backendSessionId;
74546
74926
  acquisition;
74547
74927
  configuration;
@@ -74742,11 +75122,12 @@ class LogicalAgentSession {
74742
75122
  }
74743
75123
  snapshot() {
74744
75124
  return {
75125
+ ...this.activity ? { activity: this.activity } : {},
74745
75126
  ...this.acquisition ? { acquisition: this.acquisition } : {},
74746
75127
  ...this.configuration ? { configuration: this.configuration } : {},
74747
75128
  ...this.observedModel ? { observedModel: { ...this.observedModel } } : {},
74748
75129
  sessionInstanceId: this.sessionInstanceId,
74749
- state: this.state,
75130
+ state: this.state === "idle" && this.activity && this.activity.status === "running" ? "working" : this.state,
74750
75131
  backendSessionId: this.backendSessionId,
74751
75132
  activeTurn: this.activeTurn ? { turnId: this.activeTurn.turnId, commandIds: this.activeTurn.commandIds } : undefined,
74752
75133
  queuedCommands: this.queued.map(({ message }) => ({
@@ -75072,6 +75453,13 @@ class LogicalAgentSession {
75072
75453
  return;
75073
75454
  if (this.isClosedPerTurnLaneTail(physicalOwner, generation))
75074
75455
  return;
75456
+ if (event.kind === "session_activity") {
75457
+ if (event.observation.status === "idle")
75458
+ this.flushSessionContent();
75459
+ this.activity = event.observation;
75460
+ this.emit({ type: "session_activity", observation: event.observation });
75461
+ return;
75462
+ }
75075
75463
  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;
75076
75464
  if (observation)
75077
75465
  this.emit({
@@ -75082,7 +75470,19 @@ class LogicalAgentSession {
75082
75470
  });
75083
75471
  if (event.kind === "model_observed")
75084
75472
  return;
75085
- if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown") {
75473
+ if (event.attribution?.scope === "session" && (event.kind === "assistant_message_delta" || event.kind === "assistant_reasoning_delta")) {
75474
+ appendSemanticFragment(event.kind === "assistant_message_delta" ? this.sessionMessage : this.sessionReasoning, event.text);
75475
+ if (event.text && !this.sessionContentTimer) {
75476
+ this.sessionContentTimer = setTimeout(() => {
75477
+ this.sessionContentTimer = undefined;
75478
+ if (this.state !== "closed" && this.state !== "stopping")
75479
+ this.flushSessionContent();
75480
+ }, 500);
75481
+ this.sessionContentTimer.unref?.();
75482
+ }
75483
+ return;
75484
+ }
75485
+ if (event.attribution?.scope === "child" || event.attribution?.scope === "unknown" || event.attribution?.scope === "session") {
75086
75486
  this.emit({
75087
75487
  type: "activity",
75088
75488
  attribution: event.attribution,
@@ -75090,6 +75490,7 @@ class LogicalAgentSession {
75090
75490
  ..."text" in event ? { text: boundedSemanticCompletion(event.text).text } : {},
75091
75491
  ..."callId" in event ? { callId: event.callId } : {},
75092
75492
  ..."name" in event ? { name: event.name } : {},
75493
+ ..."input" in event ? { input: jsonValue(event.input) } : {},
75093
75494
  ..."outcome" in event ? { outcome: event.outcome } : {},
75094
75495
  ..."output" in event ? { output: jsonValue(event.output) } : {}
75095
75496
  });
@@ -75300,10 +75701,23 @@ class LogicalAgentSession {
75300
75701
  this.emit({ type: "assistant_message_completed", turnId, ...message });
75301
75702
  }
75302
75703
  }
75704
+ this.flushSessionContent();
75303
75705
  this.completeTurn(event.sessionId, physicalOwner, generation, event.turnOwner);
75304
75706
  return;
75305
75707
  }
75306
75708
  }
75709
+ flushSessionContent() {
75710
+ if (this.sessionContentTimer)
75711
+ clearTimeout(this.sessionContentTimer);
75712
+ this.sessionContentTimer = undefined;
75713
+ for (const [kind, buffer] of [["assistant_reasoning_completed", this.sessionReasoning], ["assistant_message_completed", this.sessionMessage]]) {
75714
+ const completion = finishSemanticAssembler(buffer);
75715
+ if (completion.text)
75716
+ this.emit({ type: "activity", attribution: { scope: "session" }, kind, ...completion });
75717
+ }
75718
+ this.sessionMessage = emptySemanticAssembler();
75719
+ this.sessionReasoning = emptySemanticAssembler();
75720
+ }
75307
75721
  isClosedPerTurnLaneTail(physicalOwner, generation) {
75308
75722
  if (this.adapter.execution.lifetime !== "turn" || this.activeTurn)
75309
75723
  return false;
@@ -75831,6 +76245,7 @@ class LogicalAgentSession {
75831
76245
  const cleanup = hostCleanup.status === "failed" || hostCleanup.status === "timed_out" ? hostCleanup : this.laneCleanupFailure ?? hostCleanup;
75832
76246
  const result2 = buildResult(cleanup);
75833
76247
  this.terminalResult = result2;
76248
+ this.flushSessionContent();
75834
76249
  this.state = "closed";
75835
76250
  this.emit({ type: "session_closed", result: result2 });
75836
76251
  this.eventQueue.close();
@@ -80238,12 +80653,75 @@ async function handleLocalPii(request, response, botId, pii) {
80238
80653
  writePiiError(response, error62);
80239
80654
  }
80240
80655
  }
80656
+ async function filterQuestionPii(rawQuestion, botId, pii) {
80657
+ const parsed = DecisionCardInputSchema.safeParse(rawQuestion);
80658
+ if (!parsed.success)
80659
+ throw new PiiError("PII_INVALID_REQUEST");
80660
+ const triggeredById = new Map;
80661
+ const runField = async (value) => {
80662
+ const result2 = await pii.filterWithResult(botId, value);
80663
+ for (const filter of result2.triggeredFilters) {
80664
+ if (!triggeredById.has(filter.id))
80665
+ triggeredById.set(filter.id, filter);
80666
+ }
80667
+ return result2.text;
80668
+ };
80669
+ const source = parsed.data;
80670
+ const summary = await runField(source.summary);
80671
+ const questions = [];
80672
+ for (const question of source.questions) {
80673
+ const header = question.header !== undefined ? await runField(question.header) : undefined;
80674
+ const prompt = await runField(question.question);
80675
+ const options = [];
80676
+ for (const option of question.options) {
80677
+ const label2 = await runField(option.label);
80678
+ const description = option.description !== undefined ? await runField(option.description) : undefined;
80679
+ options.push({
80680
+ ...option.id !== undefined ? { id: option.id } : {},
80681
+ label: label2,
80682
+ ...description !== undefined ? { description } : {},
80683
+ ...option.recommended !== undefined ? { recommended: option.recommended } : {}
80684
+ });
80685
+ }
80686
+ questions.push({
80687
+ ...question.id !== undefined ? { id: question.id } : {},
80688
+ ...header !== undefined ? { header } : {},
80689
+ question: prompt,
80690
+ ...question.multiSelect !== undefined ? { multiSelect: question.multiSelect } : {},
80691
+ ...question.allowOther !== undefined ? { allowOther: question.allowOther } : {},
80692
+ options
80693
+ });
80694
+ }
80695
+ const filtered = {
80696
+ ...source.mentions !== undefined ? { mentions: source.mentions } : {},
80697
+ summary,
80698
+ questions
80699
+ };
80700
+ if (decisionCardUtf8Bytes(filtered) > DECISION_CARD_MAX_BYTES) {
80701
+ throw new PiiError("PII_OUTPUT_TOO_LARGE");
80702
+ }
80703
+ const validated = DecisionCardInputSchema.safeParse(filtered);
80704
+ if (!validated.success)
80705
+ throw new PiiError("PII_INVALID_RESULT");
80706
+ return { question: validated.data, triggeredFilters: [...triggeredById.values()] };
80707
+ }
80241
80708
  async function filterPiiRequest(request, botId, pii) {
80242
80709
  const body = await readJson2(request);
80243
80710
  const content3 = body.content;
80244
80711
  if (!content3 || typeof content3 !== "object" || Array.isArray(content3) || content3.text !== undefined && typeof content3.text !== "string") {
80245
80712
  throw new PiiError("PII_INVALID_REQUEST");
80246
80713
  }
80714
+ if (body.question !== undefined) {
80715
+ if ((content3.text ?? "").trim().length > 0) {
80716
+ throw new PiiError("PII_INVALID_REQUEST");
80717
+ }
80718
+ const filteredQuestion = await filterQuestionPii(body.question, botId, pii);
80719
+ body.content = { ...content3, text: "" };
80720
+ body.question = filteredQuestion.question;
80721
+ if (!CommunityAgentSendRequestSchema.safeParse(body).success)
80722
+ throw new PiiError("PII_INVALID_RESULT");
80723
+ return { body: Buffer.from(JSON.stringify(body)), triggeredFilters: filteredQuestion.triggeredFilters };
80724
+ }
80247
80725
  const { text: text8, triggeredFilters } = await pii.filterWithResult(botId, content3.text ?? "");
80248
80726
  if (Buffer.byteLength(text8, "utf8") > PII_TEXT_MAX_BYTES)
80249
80727
  throw new PiiError("PII_OUTPUT_TOO_LARGE");
@@ -80518,212 +80996,233 @@ async function startCredentialProxy(broker, options = {}) {
80518
80996
  return;
80519
80997
  }
80520
80998
  };
80521
- const server = http.createServer(async (req, res) => {
80522
- const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
80523
- const pathname = requestUrl.pathname;
80524
- if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
80525
- if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
80526
- writeJson(res, 405, { error: "method not allowed" });
80527
- req.resume();
80999
+ const server = http.createServer((req, res) => {
81000
+ (async () => {
81001
+ const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
81002
+ const pathname = requestUrl.pathname;
81003
+ if (pathname === LOCAL_MEMORY_COMMIT_PATH) {
81004
+ if (req.method !== "POST" || req.url !== LOCAL_MEMORY_COMMIT_PATH) {
81005
+ writeJson(res, 405, { error: "method not allowed" });
81006
+ req.resume();
81007
+ return;
81008
+ }
81009
+ const verdict2 = broker.check(req.headers["authorization"], "send");
81010
+ if (!verdict2.ok) {
81011
+ writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
81012
+ req.resume();
81013
+ return;
81014
+ }
81015
+ await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
80528
81016
  return;
80529
81017
  }
80530
- const verdict2 = broker.check(req.headers["authorization"], "send");
80531
- if (!verdict2.ok) {
80532
- writeJson(res, verdict2.status, { error: verdict2.error, code: verdict2.code });
80533
- req.resume();
81018
+ if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
81019
+ const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
81020
+ if (!localVerdict.ok) {
81021
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81022
+ req.resume();
81023
+ return;
81024
+ }
81025
+ await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
80534
81026
  return;
80535
81027
  }
80536
- await handleLocalMemoryCommit(req, res, verdict2.reg, options.onMemoryCommit, options.onMemoryCommitResetError);
80537
- return;
80538
- }
80539
- if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
80540
- const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
80541
- if (!localVerdict.ok) {
80542
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
80543
- req.resume();
81028
+ if (pathname.startsWith("/__alook/local/")) {
81029
+ if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
81030
+ writeJson(res, 404, { error: "unknown local route", code: "not_found" });
81031
+ req.resume();
81032
+ return;
81033
+ }
81034
+ if (req.method !== "PUT") {
81035
+ writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
81036
+ req.resume();
81037
+ return;
81038
+ }
81039
+ const localVerdict = broker.check(req.headers["authorization"], "send");
81040
+ if (!localVerdict.ok) {
81041
+ writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81042
+ req.resume();
81043
+ return;
81044
+ }
81045
+ handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
80544
81046
  return;
80545
81047
  }
80546
- await handleLocalPii(req, res, localVerdict.reg.agentId, options.pii);
80547
- return;
80548
- }
80549
- if (pathname.startsWith("/__alook/local/")) {
80550
- if (req.url !== LOCAL_MESSAGE_REMINDER_PATH) {
80551
- writeJson(res, 404, { error: "unknown local route", code: "not_found" });
81048
+ const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
81049
+ const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
81050
+ const verdict = broker.check(req.headers["authorization"], requiredCap);
81051
+ if (!verdict.ok) {
81052
+ res.writeHead(verdict.status, { "content-type": "application/json" });
81053
+ res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
80552
81054
  req.resume();
80553
81055
  return;
80554
81056
  }
80555
- if (req.method !== "PUT") {
80556
- writeJson(res, 405, { error: "method not allowed", code: "method_not_allowed" });
80557
- req.resume();
81057
+ 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))) {
81058
+ writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
80558
81059
  return;
80559
81060
  }
80560
- const localVerdict = broker.check(req.headers["authorization"], "send");
80561
- if (!localVerdict.ok) {
80562
- writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code });
81061
+ const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
81062
+ if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
81063
+ res.writeHead(404, { "content-type": "application/json" });
81064
+ res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
80563
81065
  req.resume();
80564
81066
  return;
80565
81067
  }
80566
- handleLocalMessageReminder(req, res, localVerdict.reg.agentId, options.onMessageReminderArm);
80567
- return;
80568
- }
80569
- const route = resolveProxyRoute(pathname, req.method ?? "GET", req.url ?? pathname);
80570
- const requiredCap = resolveCap ? resolveCap(req.method ?? "GET", pathname) : route.capability;
80571
- const verdict = broker.check(req.headers["authorization"], requiredCap);
80572
- if (!verdict.ok) {
80573
- res.writeHead(verdict.status, { "content-type": "application/json" });
80574
- res.end(JSON.stringify({ error: verdict.error, code: verdict.code }));
80575
- req.resume();
80576
- return;
80577
- }
80578
- 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))) {
80579
- writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
80580
- return;
80581
- }
80582
- const canonicalCommunityDoor = pathname === "/api/community/platform/feedback" || /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
80583
- if (pathname === "/api" || pathname.startsWith("/api/") && !canonicalCommunityDoor) {
80584
- res.writeHead(404, { "content-type": "application/json" });
80585
- res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
80586
- req.resume();
80587
- return;
80588
- }
80589
- if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
80590
- writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
80591
- req.resume();
80592
- return;
80593
- }
80594
- const reg = verdict.reg;
80595
- if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
80596
- writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
80597
- req.resume();
80598
- return;
80599
- }
80600
- let filteredBody;
80601
- let piiTriggeredFilters = [];
80602
- if (options.pii && route.filterPiiSend) {
80603
- try {
80604
- const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
80605
- filteredBody = filtered.body;
80606
- piiTriggeredFilters = filtered.triggeredFilters;
80607
- } catch (error62) {
80608
- writePiiError(res, error62);
81068
+ if (/^\/api\/community\/bots\/me\/nap(?:\/|$)/.test(pathname)) {
81069
+ writeJson(res, 410, { error: "nap was removed; use local commit to record a memory review", code: "command_removed" });
81070
+ req.resume();
80609
81071
  return;
80610
81072
  }
80611
- if (res.destroyed)
81073
+ const reg = verdict.reg;
81074
+ if (/^\/api\/community\/bots\/[^/]+\/pii\/?$/.test(pathname)) {
81075
+ writeJson(res, 403, { error: "PII management requires a human owner session", code: "forbidden" });
81076
+ req.resume();
80612
81077
  return;
80613
- }
80614
- const isInboxPull = route.inboxObservation === "pull";
80615
- const isInboxAck = route.inboxObservation === "ack";
80616
- const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
80617
- const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
80618
- let inboxPullObservationToken;
80619
- let inboxAckObservationToken;
80620
- if (shouldObserveInboxPull) {
80621
- try {
80622
- inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
80623
- } catch {
80624
- reportInboxPullObservationError({
80625
- agentId: reg.agentId,
80626
- reason: "observer_failed",
80627
- contentEncoding: "identity"
80628
- });
80629
81078
  }
80630
- }
80631
- if (shouldObserveInboxAck) {
80632
- try {
80633
- inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
80634
- } catch {
80635
- reportInboxAckObservationError({
80636
- agentId: reg.agentId,
80637
- reason: "observer_failed",
80638
- contentEncoding: "identity"
80639
- });
81079
+ let filteredBody;
81080
+ let piiTriggeredFilters = [];
81081
+ if (options.pii && route.filterPiiSend) {
81082
+ try {
81083
+ const filtered = await filterPiiRequest(req, reg.agentId, options.pii);
81084
+ filteredBody = filtered.body;
81085
+ piiTriggeredFilters = filtered.triggeredFilters;
81086
+ } catch (error62) {
81087
+ writePiiError(res, error62);
81088
+ return;
81089
+ }
81090
+ if (res.destroyed)
81091
+ return;
80640
81092
  }
80641
- }
80642
- if (onProxyRequest) {
80643
- try {
80644
- const method = req.method ?? "GET";
80645
- onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
80646
- } catch {}
80647
- }
80648
- const outHeaders = { ...req.headers };
80649
- delete outHeaders["authorization"];
80650
- delete outHeaders["host"];
80651
- outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
80652
- outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
80653
- outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
80654
- outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
80655
- if (isInboxPull || isInboxAck)
80656
- outHeaders["accept-encoding"] = "identity";
80657
- if (filteredBody) {
80658
- delete outHeaders["transfer-encoding"];
80659
- outHeaders["content-length"] = filteredBody.byteLength;
80660
- }
80661
- let responded = false;
80662
- if (piiTriggeredFilters.length)
80663
- outHeaders["accept-encoding"] = "identity";
80664
- let upstreamRes;
80665
- const upstreamReq = upstreamClient.request({
80666
- protocol: upstream.protocol,
80667
- hostname: upstream.hostname,
80668
- port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
80669
- method: req.method,
80670
- path: joinPath(upstream.pathname, req.url ?? "/"),
80671
- headers: outHeaders
80672
- }, (res_) => {
80673
- responded = true;
80674
- upstreamRes = res_;
80675
- const destroyResIfIncomplete = () => {
80676
- if (!res_.complete)
80677
- res.destroy();
80678
- };
80679
- res_.on("error", destroyResIfIncomplete);
80680
- res_.on("close", destroyResIfIncomplete);
80681
- if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
80682
- const chunks = [];
80683
- res_.on("data", (chunk2) => chunks.push(chunk2));
80684
- res_.on("end", () => {
80685
- const body = Buffer.concat(chunks);
80686
- const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
80687
- if (contentEncoding !== "identity") {
80688
- if (shouldObserveInboxPull) {
80689
- reportInboxPullObservationError({
80690
- agentId: reg.agentId,
80691
- reason: "unexpected_content_encoding",
80692
- contentEncoding
80693
- });
80694
- } else {
80695
- reportInboxAckObservationError({
80696
- agentId: reg.agentId,
80697
- reason: "unexpected_content_encoding",
80698
- contentEncoding
80699
- });
80700
- }
80701
- } else {
80702
- let parsed;
80703
- try {
80704
- parsed = JSON.parse(body.toString("utf8"));
80705
- } catch {
81093
+ const isInboxPull = route.inboxObservation === "pull";
81094
+ const isInboxAck = route.inboxObservation === "ack";
81095
+ const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
81096
+ const shouldObserveInboxAck = Boolean(isInboxAck && onAck);
81097
+ let inboxPullObservationToken;
81098
+ let inboxAckObservationToken;
81099
+ if (shouldObserveInboxPull) {
81100
+ try {
81101
+ inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
81102
+ } catch {
81103
+ reportInboxPullObservationError({
81104
+ agentId: reg.agentId,
81105
+ reason: "observer_failed",
81106
+ contentEncoding: "identity"
81107
+ });
81108
+ }
81109
+ }
81110
+ if (shouldObserveInboxAck) {
81111
+ try {
81112
+ inboxAckObservationToken = options.onInboxAckStart?.(reg.agentId);
81113
+ } catch {
81114
+ reportInboxAckObservationError({
81115
+ agentId: reg.agentId,
81116
+ reason: "observer_failed",
81117
+ contentEncoding: "identity"
81118
+ });
81119
+ }
81120
+ }
81121
+ if (onProxyRequest) {
81122
+ try {
81123
+ const method = req.method ?? "GET";
81124
+ onProxyRequest(reg.agentId, method, pathname, route.propertyMetadata, route.auditOperation);
81125
+ } catch {}
81126
+ }
81127
+ const outHeaders = { ...req.headers };
81128
+ delete outHeaders["authorization"];
81129
+ delete outHeaders["host"];
81130
+ outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
81131
+ outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
81132
+ outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
81133
+ outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
81134
+ if (isInboxPull || isInboxAck)
81135
+ outHeaders["accept-encoding"] = "identity";
81136
+ if (filteredBody) {
81137
+ delete outHeaders["transfer-encoding"];
81138
+ outHeaders["content-length"] = filteredBody.byteLength;
81139
+ }
81140
+ let responded = false;
81141
+ if (piiTriggeredFilters.length)
81142
+ outHeaders["accept-encoding"] = "identity";
81143
+ let upstreamRes;
81144
+ const upstreamReq = upstreamClient.request({
81145
+ protocol: upstream.protocol,
81146
+ hostname: upstream.hostname,
81147
+ port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),
81148
+ method: req.method,
81149
+ path: joinPath(upstream.pathname, req.url ?? "/"),
81150
+ headers: outHeaders
81151
+ }, (res_) => {
81152
+ responded = true;
81153
+ upstreamRes = res_;
81154
+ const destroyResIfIncomplete = () => {
81155
+ if (!res_.complete)
81156
+ res.destroy();
81157
+ };
81158
+ res_.on("error", destroyResIfIncomplete);
81159
+ res_.on("close", destroyResIfIncomplete);
81160
+ if ((shouldObserveInboxPull || shouldObserveInboxAck) && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300) {
81161
+ const chunks = [];
81162
+ res_.on("data", (chunk2) => chunks.push(chunk2));
81163
+ res_.on("end", () => {
81164
+ const body = Buffer.concat(chunks);
81165
+ const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
81166
+ if (contentEncoding !== "identity") {
80706
81167
  if (shouldObserveInboxPull) {
80707
- reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81168
+ reportInboxPullObservationError({
81169
+ agentId: reg.agentId,
81170
+ reason: "unexpected_content_encoding",
81171
+ contentEncoding
81172
+ });
80708
81173
  } else {
80709
- reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81174
+ reportInboxAckObservationError({
81175
+ agentId: reg.agentId,
81176
+ reason: "unexpected_content_encoding",
81177
+ contentEncoding
81178
+ });
80710
81179
  }
80711
- }
80712
- if (parsed !== undefined) {
80713
- if (shouldObserveInboxPull) {
80714
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
80715
- reportInboxPullObservationError({
81180
+ } else {
81181
+ let parsed;
81182
+ try {
81183
+ parsed = JSON.parse(body.toString("utf8"));
81184
+ } catch {
81185
+ if (shouldObserveInboxPull) {
81186
+ reportInboxPullObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81187
+ } else {
81188
+ reportInboxAckObservationError({ agentId: reg.agentId, reason: "invalid_json", contentEncoding });
81189
+ }
81190
+ }
81191
+ if (parsed !== undefined) {
81192
+ if (shouldObserveInboxPull) {
81193
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.messages)) {
81194
+ reportInboxPullObservationError({
81195
+ agentId: reg.agentId,
81196
+ reason: "invalid_inbox_shape",
81197
+ contentEncoding
81198
+ });
81199
+ } else {
81200
+ const messages = parsed.messages;
81201
+ if (messages.length > 0) {
81202
+ try {
81203
+ onPull(reg.agentId, messages, inboxPullObservationToken);
81204
+ } catch {
81205
+ reportInboxPullObservationError({
81206
+ agentId: reg.agentId,
81207
+ reason: "observer_failed",
81208
+ contentEncoding
81209
+ });
81210
+ }
81211
+ }
81212
+ }
81213
+ } 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)) {
81214
+ reportInboxAckObservationError({
80716
81215
  agentId: reg.agentId,
80717
- reason: "invalid_inbox_shape",
81216
+ reason: "invalid_ack_shape",
80718
81217
  contentEncoding
80719
81218
  });
80720
81219
  } else {
80721
- const messages = parsed.messages;
80722
- if (messages.length > 0) {
81220
+ const applied = parsed.applied;
81221
+ if (applied.length > 0) {
80723
81222
  try {
80724
- onPull(reg.agentId, messages, inboxPullObservationToken);
81223
+ onAck(reg.agentId, applied, inboxAckObservationToken);
80725
81224
  } catch {
80726
- reportInboxPullObservationError({
81225
+ reportInboxAckObservationError({
80727
81226
  agentId: reg.agentId,
80728
81227
  reason: "observer_failed",
80729
81228
  contentEncoding
@@ -80731,66 +81230,47 @@ async function startCredentialProxy(broker, options = {}) {
80731
81230
  }
80732
81231
  }
80733
81232
  }
80734
- } 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)) {
80735
- reportInboxAckObservationError({
80736
- agentId: reg.agentId,
80737
- reason: "invalid_ack_shape",
80738
- contentEncoding
80739
- });
80740
- } else {
80741
- const applied = parsed.applied;
80742
- if (applied.length > 0) {
80743
- try {
80744
- onAck(reg.agentId, applied, inboxAckObservationToken);
80745
- } catch {
80746
- reportInboxAckObservationError({
80747
- agentId: reg.agentId,
80748
- reason: "observer_failed",
80749
- contentEncoding
80750
- });
80751
- }
80752
- }
80753
81233
  }
80754
81234
  }
80755
- }
80756
- res.writeHead(res_.statusCode, res_.headers);
80757
- res.end(body);
80758
- });
80759
- } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
80760
- forwardPiiSendResponse(res_, res, piiTriggeredFilters);
80761
- } else {
80762
- res.writeHead(res_.statusCode ?? 502, res_.headers);
80763
- res_.pipe(res);
80764
- }
80765
- });
80766
- upstreamReq.on("error", (err) => {
80767
- if (responded)
80768
- return;
80769
- responded = true;
80770
- res.writeHead(502, { "content-type": "application/json" });
80771
- res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
80772
- });
80773
- const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
80774
- const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
80775
- upstreamReq.setTimeout(upstreamTimeoutMs, () => {
80776
- upstreamReq.destroy();
80777
- upstreamRes?.destroy();
80778
- if (responded) {
80779
- res.destroy();
80780
- return;
80781
- }
80782
- responded = true;
80783
- res.writeHead(504, { "content-type": "application/json" });
80784
- res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
80785
- });
80786
- res.on("close", () => {
80787
- upstreamReq.destroy();
80788
- upstreamRes?.destroy();
80789
- });
80790
- if (filteredBody)
80791
- upstreamReq.end(filteredBody);
80792
- else
80793
- req.pipe(upstreamReq);
81235
+ res.writeHead(res_.statusCode, res_.headers);
81236
+ res.end(body);
81237
+ });
81238
+ } else if (piiTriggeredFilters.length && res_.statusCode !== undefined && res_.statusCode >= 200 && res_.statusCode < 300 && normalizeContentEncoding(res_.headers["content-encoding"]) === "identity") {
81239
+ forwardPiiSendResponse(res_, res, piiTriggeredFilters);
81240
+ } else {
81241
+ res.writeHead(res_.statusCode ?? 502, res_.headers);
81242
+ res_.pipe(res);
81243
+ }
81244
+ });
81245
+ upstreamReq.on("error", (err) => {
81246
+ if (responded)
81247
+ return;
81248
+ responded = true;
81249
+ res.writeHead(502, { "content-type": "application/json" });
81250
+ res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
81251
+ });
81252
+ const waitingForModels = route.modelDiscovery && requestUrl.searchParams.get("wait") === "1";
81253
+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
81254
+ upstreamReq.setTimeout(upstreamTimeoutMs, () => {
81255
+ upstreamReq.destroy();
81256
+ upstreamRes?.destroy();
81257
+ if (responded) {
81258
+ res.destroy();
81259
+ return;
81260
+ }
81261
+ responded = true;
81262
+ res.writeHead(504, { "content-type": "application/json" });
81263
+ res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));
81264
+ });
81265
+ res.on("close", () => {
81266
+ upstreamReq.destroy();
81267
+ upstreamRes?.destroy();
81268
+ });
81269
+ if (filteredBody)
81270
+ upstreamReq.end(filteredBody);
81271
+ else
81272
+ req.pipe(upstreamReq);
81273
+ })();
80794
81274
  });
80795
81275
  await new Promise((resolve7, reject) => {
80796
81276
  server.once("error", reject);
@@ -80817,7 +81297,10 @@ function joinPath(basePath, reqUrl) {
80817
81297
  }
80818
81298
  // src/manager/managerPolicy.ts
80819
81299
  function isActivelyWorking(agent) {
80820
- return agent.status === "running" && (leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
81300
+ return agent.status === "running" && (agent.sessionActivity?.status === "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
81301
+ }
81302
+ function sessionBlocksIdleCleanup(agent) {
81303
+ return agent.sessionActivity !== undefined && agent.sessionActivity.status !== "idle";
80821
81304
  }
80822
81305
  var DEFAULT_STALE_THRESHOLD_MS = 120000;
80823
81306
  var DEFAULT_TURN_SILENCE_POLICY = {
@@ -80843,6 +81326,19 @@ function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS
80843
81326
  }
80844
81327
  function reduceManager(state, event) {
80845
81328
  switch (event.type) {
81329
+ case "session_activity": {
81330
+ const current = state.agents[event.agentId];
81331
+ if (!current || !matchesSession(current, event.sessionInstanceId) || current.status === "stopping")
81332
+ return { state, effects: [] };
81333
+ const agent = clone2(current);
81334
+ const changed = agent.sessionActivity?.status !== event.observation.status;
81335
+ agent.sessionActivity = event.observation;
81336
+ if (sessionBlocksIdleCleanup(agent))
81337
+ agent.idleSince = null;
81338
+ else if (changed && !leaseIsWorking(agent.execution.lease) && agent.pendingAdmissions.length === 0 && agent.inbox.length === 0)
81339
+ agent.idleSince = event.nowMs;
81340
+ return commit(state, agent, []);
81341
+ }
80846
81342
  case "register":
80847
81343
  return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
80848
81344
  case "wake":
@@ -80892,6 +81388,7 @@ function reduceManager(state, event) {
80892
81388
  {
80893
81389
  const a = agent;
80894
81390
  a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
81391
+ a.sessionActivity = undefined;
80895
81392
  a.turnSilence = event.turnSilence ?? {
80896
81393
  ...DEFAULT_TURN_SILENCE_POLICY,
80897
81394
  nativeIdleTimeoutMs: state.staleThresholdMs,
@@ -81093,6 +81590,7 @@ function reduceManager(state, event) {
81093
81590
  const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
81094
81591
  agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
81095
81592
  agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
81593
+ agent.sessionActivity = undefined;
81096
81594
  syncExecutionProjection(agent);
81097
81595
  return commit(state, agent, recoveryEffects(agent, closing));
81098
81596
  }
@@ -81221,7 +81719,7 @@ function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endRe
81221
81719
  ...messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" }))
81222
81720
  ]);
81223
81721
  }
81224
- agent.idleSince = agent.status === "running" && !agent.resetting ? nowMs : null;
81722
+ agent.idleSince = agent.status === "running" && !agent.resetting && !sessionBlocksIdleCleanup(agent) ? nowMs : null;
81225
81723
  return commit(state, agent, clearEffects);
81226
81724
  }
81227
81725
  function onTurnToolLifecycle(state, event, lifecycle) {
@@ -81371,13 +81869,13 @@ function onTick(state, nowMs) {
81371
81869
  effects.push({ type: "force_exit", agentId: id4, reason: "stopping_stuck" });
81372
81870
  continue;
81373
81871
  }
81374
- 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);
81872
+ 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);
81375
81873
  if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
81376
81874
  agents[id4] = { ...a, idleSince: nowMs };
81377
81875
  effects.push({ type: "maintain_idle_memory", agentId: id4, sessionId: a.sessionId });
81378
81876
  continue;
81379
81877
  }
81380
- 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);
81878
+ 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);
81381
81879
  if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
81382
81880
  agents[id4] = { ...a, status: "stopping", stoppingSince: nowMs };
81383
81881
  effects.push({ type: "stop", agentId: id4, reason: "idle_timeout" });
@@ -81411,6 +81909,8 @@ function freshAgent(agentId) {
81411
81909
  }
81412
81910
  function enterStable(agent, status) {
81413
81911
  agent.status = status;
81912
+ if (status === "idle")
81913
+ agent.sessionActivity = undefined;
81414
81914
  agent.resetting = false;
81415
81915
  agent.resettingSince = null;
81416
81916
  agent.stoppingSince = null;
@@ -81622,6 +82122,19 @@ function messagingSection() {
81622
82122
  "ALOOK_MESSAGE_7F3C",
81623
82123
  "```",
81624
82124
  "",
82125
+ "#### Ask for a decision",
82126
+ "",
82127
+ `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.`,
82128
+ "",
82129
+ "When you ask a question and can offer options, use a decision card. " + "Use a normal Alook message for updates and questions without options.",
82130
+ "",
82131
+ "Pass JSON on stdin (max 8 KiB).",
82132
+ "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.",
82133
+ "",
82134
+ "```json",
82135
+ `{"mentions":["@alice#0001"],"summary":"Confirm today's release","questions":[{"question":"Ship today?","options":[{"label":"Ship","recommended":true},"Wait"]}]}`,
82136
+ "```",
82137
+ "",
81625
82138
  "#### Pulled messages",
81626
82139
  "",
81627
82140
  "```json",
@@ -81691,7 +82204,7 @@ function cliCommandsSection() {
81691
82204
  "### Messaging",
81692
82205
  "",
81693
82206
  `1. \`${CLI} inbox pull\` — fetch unread messages and advance their read waterlines.`,
81694
- `2. \`${CLI} message send --target <ref> --remind-after <0|Nm|Nh> --stdin\` — send to a ` + `channel, DM, or thread. ` + `The body is required through \`--stdin\` and limited to 1 KiB of UTF-8. ` + `Attach files with \`--attachment <id>\` (repeatable, order matters). ` + `\`--remind-after\` accepts \`0\`, or a whole-number duration from \`1m\` to \`24h\`.`,
82207
+ `2. \`${CLI} message send --target <ref> --remind-after <0|Nm|Nh> [--ask] --stdin\` — Send to a ` + `channel, DM, or thread. ` + `For plain messages, pass up to 1 KiB of UTF-8 text through stdin and use \`--attachment <id>\` for files (repeatable, order matters). ` + `\`--remind-after\` accepts \`0\` or a whole-number duration from \`1m\` to \`24h\`.`,
81695
82208
  `3. \`${CLI} message attachment upload --file <path>\` — upload a local file and get a reusable attachment ID. Supports Markdown and inline HTML; see Communication for formatting.`,
81696
82209
  `4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download an attachment you can read, including your own unsent uploads.`,
81697
82210
  `5. \`${CLI} message property set --target <full-message-ref> --json <json>\` — add a supported property value to a message.`,
@@ -83507,6 +84020,9 @@ ${this.opts.wakePromptFooter}` : text8;
83507
84020
  return;
83508
84021
  }
83509
84022
  const sessionSuperseded = owner.superseded;
84023
+ if (event.type === "session_activity" && !sessionSuperseded) {
84024
+ this.dispatch({ type: "session_activity", agentId, sessionInstanceId: event.sessionInstanceId, observation: event.observation, nowMs: this.now() }, owner);
84025
+ }
83510
84026
  const runtimeError = event.type === "session_failed" ? event.error : event.type === "turn_completed" && event.result.outcome === "failed" ? event.result.error : undefined;
83511
84027
  if (runtimeError !== undefined && !sessionSuperseded) {
83512
84028
  this.emitErrorAudit(agentId, "runtime", runtimeError.code, runtimeError.message);
@@ -83523,12 +84039,12 @@ ${this.opts.wakePromptFooter}` : text8;
83523
84039
  }
83524
84040
  }
83525
84041
  if (this.opts.onBotAuditEvent) {
83526
- if (event.type === "assistant_message_completed" && event.text.length > 0) {
84042
+ if ((event.type === "assistant_message_completed" || event.type === "activity" && event.kind === "assistant_message_completed") && event.text && event.text.length > 0) {
83527
84043
  const { text: text8, truncated, chars } = truncateAuditText(event.text);
83528
84044
  try {
83529
84045
  this.opts.onBotAuditEvent(agentId, {
83530
84046
  kind: "text",
83531
- payload: { text: text8, truncated: truncated || event.truncated, chars }
84047
+ payload: { text: text8, truncated: truncated || event.truncated === true, chars }
83532
84048
  }, {
83533
84049
  sessionId: this.liveSessions.get(agentId) ?? null,
83534
84050
  launchId: this.launchIds.get(agentId) ?? null
@@ -87404,6 +87920,7 @@ function projectDaemonLogRow(value, targetAgentId) {
87404
87920
  };
87405
87921
  }
87406
87922
  var CURRENT_MANAGER_EVENTS = {
87923
+ session_activity: "include",
87407
87924
  register: "include",
87408
87925
  wake: "include",
87409
87926
  spawned: "include",
@@ -90678,8 +91195,18 @@ async function readLiteralInput(args) {
90678
91195
  throw new CliError(`${command}: input exceeds ${args.maxBytes} UTF-8 bytes`);
90679
91196
  chunks.push(bytes);
90680
91197
  }
90681
- return Buffer.concat(chunks).toString("utf8");
91198
+ const raw = Buffer.concat(chunks);
91199
+ if (args.strictUtf8) {
91200
+ try {
91201
+ return new TextDecoder("utf-8", { fatal: true }).decode(raw);
91202
+ } catch {
91203
+ throw new CliError(`${command}: --stdin must be valid UTF-8 JSON`);
91204
+ }
91205
+ }
91206
+ return raw.toString("utf8");
90682
91207
  } catch (err) {
91208
+ if (err instanceof CliError)
91209
+ throw err;
90683
91210
  throw new CliError(`${command}: cannot read stdin: ${err.message}`);
90684
91211
  }
90685
91212
  }
@@ -90736,55 +91263,21 @@ function contentTypeFromFilename(filename) {
90736
91263
  async function sendWithRetry(api2, req) {
90737
91264
  return withTransientMutationRetry(() => api2.send(req));
90738
91265
  }
90739
- async function cmdMessageSend(opts, stdin) {
90740
- const remindAfterFlag = opts.remindAfter;
90741
- const remindAfterMs = parseRemindAfter(remindAfterFlag);
90742
- const api2 = getApi();
90743
- const agent = agentId(opts);
90744
- const channel = opts.target;
90745
- if (!channel)
90746
- throw new CliError("message send: --target <ref> is required (e.g. /demo-workspace#1234/general)");
90747
- parseRef(channel);
90748
- const literalText = await readLiteralInput({
90749
- command: "message send",
90750
- stdinSelected: opts.stdin === true,
90751
- stdin
90752
- });
90753
- const text8 = stripMalformedAlookHeredocTail(literalText ?? "");
90754
- const textBytes = Buffer.byteLength(text8, "utf8");
90755
- if (textBytes > CLIENT_MAX_MESSAGE_BODY_BYTES) {
90756
- throw new CliError(`message send: --stdin body is ${textBytes} bytes; max ${CLIENT_MAX_MESSAGE_BODY_BYTES}. Rewrite it before retrying.
90757
-
90758
- ${MESSAGE_SEND_STDIN_POLICY}`);
90759
- }
90760
- const attachmentIds = Array.isArray(opts.attachment) ? opts.attachment : [];
90761
- const hasText = text8.trim().length > 0;
90762
- if (!hasText && attachmentIds.length === 0) {
90763
- throw new CliError("message send: --stdin must contain text unless --attachment <id> is present");
90764
- }
90765
- let replyToSeq;
90766
- const replyFlag = opts.reply;
90767
- if (replyFlag !== undefined && replyFlag !== "") {
90768
- const raw = String(replyFlag).trim();
90769
- const stripped = raw.startsWith("#") ? raw.slice(1) : raw;
90770
- const n = Number(stripped);
90771
- if (!/^\d+$/.test(stripped) || !Number.isInteger(n) || n < 1) {
90772
- throw new CliError('message send: --reply must be a message seq like "#37"');
90773
- }
90774
- replyToSeq = n;
91266
+ function parseReplySeqOption(command, replyFlag) {
91267
+ if (replyFlag === undefined || replyFlag === "")
91268
+ return;
91269
+ const raw = String(replyFlag).trim();
91270
+ const stripped = raw.startsWith("#") ? raw.slice(1) : raw;
91271
+ const n = Number(stripped);
91272
+ if (!/^\d+$/.test(stripped) || !Number.isInteger(n) || n < 1) {
91273
+ throw new CliError(`${command}: --reply must be a message seq like "#37"`);
90775
91274
  }
90776
- const nonce = randomUUID20();
91275
+ return n;
91276
+ }
91277
+ async function dispatchSendAndArmReminder(api2, channel, remindAfterMs, req) {
90777
91278
  let res;
90778
91279
  try {
90779
- res = await sendWithRetry(api2, {
90780
- agentId: agent,
90781
- channel,
90782
- content: { text: text8 ?? "" },
90783
- attachments: attachmentIds.length > 0 ? attachmentIds : undefined,
90784
- replyToSeq,
90785
- nonce,
90786
- ...opts.force === true ? { force: true } : {}
90787
- });
91280
+ res = await sendWithRetry(api2, req);
90788
91281
  } catch (err) {
90789
91282
  if (err instanceof Error && "code" in err && err.code === "duplicate_message") {
90790
91283
  err.hint = "If this message really needs to be sent, retry with --force. This only bypasses duplicate detection; channel alignment is still required.";
@@ -90812,6 +91305,82 @@ ${MESSAGE_SEND_STDIN_POLICY}`);
90812
91305
  return { sent, ...pii, reminder: { armed: false, reason: "local reminder request failed" } };
90813
91306
  }
90814
91307
  }
91308
+ async function cmdMessageSend(opts, stdin) {
91309
+ const remindAfterFlag = opts.remindAfter;
91310
+ const remindAfterMs = parseRemindAfter(remindAfterFlag);
91311
+ const api2 = getApi();
91312
+ const agent = agentId(opts);
91313
+ const channel = opts.target;
91314
+ if (!channel)
91315
+ throw new CliError("message send: --target <ref> is required (e.g. /demo-workspace#1234/general)");
91316
+ parseRef(channel);
91317
+ const attachmentIds = Array.isArray(opts.attachment) ? opts.attachment : [];
91318
+ const replyToSeq = parseReplySeqOption("message send", opts.reply);
91319
+ if (opts.ask === true) {
91320
+ if (attachmentIds.length > 0) {
91321
+ throw new CliError("message send --ask: cannot combine --ask with --attachment");
91322
+ }
91323
+ const rawBody = await readLiteralInput({
91324
+ command: "message send --ask",
91325
+ stdinSelected: opts.stdin === true,
91326
+ stdin,
91327
+ maxBytes: DECISION_CARD_MAX_BYTES,
91328
+ strictUtf8: true
91329
+ });
91330
+ const cleaned = stripMalformedAlookHeredocTail(rawBody ?? "").trim();
91331
+ if (!cleaned) {
91332
+ throw new CliError("message send --ask: --stdin must contain a JSON decision card payload");
91333
+ }
91334
+ let parsedJson;
91335
+ try {
91336
+ parsedJson = JSON.parse(cleaned);
91337
+ } catch {
91338
+ throw new CliError("message send --ask: --stdin must be valid UTF-8 JSON");
91339
+ }
91340
+ const validated = parseDecisionCardCliInput(parsedJson);
91341
+ if (!validated.success) {
91342
+ const issue2 = validated.error.issues[0];
91343
+ const path24 = issue2?.path?.length ? `${issue2.path.join(".")}: ` : "";
91344
+ throw new CliError(`message send --ask: invalid decision card payload (${path24}${issue2?.message ?? "invalid schema"})`);
91345
+ }
91346
+ const nonce2 = randomUUID20();
91347
+ return dispatchSendAndArmReminder(api2, channel, remindAfterMs, {
91348
+ agentId: agent,
91349
+ channel,
91350
+ content: { text: "" },
91351
+ question: validated.data,
91352
+ replyToSeq,
91353
+ nonce: nonce2,
91354
+ ...opts.force === true ? { force: true } : {}
91355
+ });
91356
+ }
91357
+ const literalText = await readLiteralInput({
91358
+ command: "message send",
91359
+ stdinSelected: opts.stdin === true,
91360
+ stdin
91361
+ });
91362
+ const text8 = stripMalformedAlookHeredocTail(literalText ?? "");
91363
+ const textBytes = Buffer.byteLength(text8, "utf8");
91364
+ if (textBytes > CLIENT_MAX_MESSAGE_BODY_BYTES) {
91365
+ throw new CliError(`message send: --stdin body is ${textBytes} bytes; max ${CLIENT_MAX_MESSAGE_BODY_BYTES}. Rewrite it before retrying.
91366
+
91367
+ ${MESSAGE_SEND_STDIN_POLICY}`);
91368
+ }
91369
+ const hasText = text8.trim().length > 0;
91370
+ if (!hasText && attachmentIds.length === 0) {
91371
+ throw new CliError("message send: --stdin must contain text unless --attachment <id> is present");
91372
+ }
91373
+ const nonce = randomUUID20();
91374
+ return dispatchSendAndArmReminder(api2, channel, remindAfterMs, {
91375
+ agentId: agent,
91376
+ channel,
91377
+ content: { text: text8 ?? "" },
91378
+ attachments: attachmentIds.length > 0 ? attachmentIds : undefined,
91379
+ replyToSeq,
91380
+ nonce,
91381
+ ...opts.force === true ? { force: true } : {}
91382
+ });
91383
+ }
90815
91384
  function parseMessagePropertyJson(command, raw) {
90816
91385
  if (typeof raw !== "string")
90817
91386
  throw new CliError(`${command}: --json <json> is required`);
@@ -91170,7 +91739,7 @@ function buildProgram(stdin) {
91170
91739
  registerPiiCommands(program, printEnvelope);
91171
91740
  const message = program.command("message").description("message operations").exitOverride();
91172
91741
  message.configureOutput({ writeOut: () => {}, writeErr: () => {} });
91173
- message.command("send").description("send a message to a channel, DM, or thread").option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace#1234/general)").requiredOption("--stdin", "read the required UTF-8 message body from non-TTY stdin (max 1 KiB)").option("-a, --attachment <id>", "attach an uploaded file by id (repeatable — order = message order)", (v, prev = []) => [...prev, v], []).option("--force", "bypass duplicate detection only; channel alignment and other send checks still apply").option("--reply <seq>", 'reply to a message by its seq in --target (e.g. "#37" or 37)').requiredOption("--remind-after <0|Nm|Nh>", "required idle follow-up: 0 disables; 1m..24h arms/resets one same-scope timer; a newer message or daemon restart cancels it").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function() {
91742
+ message.command("send").description("send a message to a channel, DM, or thread").option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace#1234/general)").requiredOption("--stdin", "read the required UTF-8 message body from non-TTY stdin (max 1 KiB, or 8 KiB JSON with --ask)").option("--ask", "send a structured decision card from UTF-8 JSON on --stdin with required summary and questions (text channel, thread, or DM)").option("-a, --attachment <id>", "attach an uploaded file by id (repeatable — order = message order)", (v, prev = []) => [...prev, v], []).option("--force", "bypass duplicate detection only; channel alignment and other send checks still apply").option("--reply <seq>", 'reply to a message by its seq in --target (e.g. "#37" or 37)').requiredOption("--remind-after <0|Nm|Nh>", "required idle follow-up: 0 disables; 1m..24h arms/resets one same-scope timer; a newer message or daemon restart cancels it").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function() {
91174
91743
  const localOpts = this.opts();
91175
91744
  const globalOpts = program.opts();
91176
91745
  const result2 = await cmdMessageSend({ ...globalOpts, ...localOpts }, stdin);