@alook/daemon 0.1.60 → 0.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -41754,6 +41754,125 @@ function bigint3(params) {
41754
41754
  function date4(params) {
41755
41755
  return _coercedDate(ZodDate, params);
41756
41756
  }
41757
+ // ../shared/src/constants/community.ts
41758
+ var MAX_SERVER_NAME_LENGTH = 100;
41759
+ var MAX_SERVER_DESCRIPTION_LENGTH = 2000;
41760
+ var MAX_FOLDER_NAME_LENGTH = 100;
41761
+ var MAX_PROFILE_NAME_LENGTH = 100;
41762
+ var MAX_PROFILE_ABOUT_LENGTH = 1000;
41763
+ var MAX_MESSAGE_CONTENT_LENGTH = 4000;
41764
+ var MAX_ATTACHMENTS_PER_MESSAGE = 10;
41765
+ var MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024;
41766
+ var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 720;
41767
+ var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 256 * 1024;
41768
+ var MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024;
41769
+ var ALLOWED_ICON_MIME_TYPES = [
41770
+ "image/png",
41771
+ "image/jpeg",
41772
+ "image/webp",
41773
+ "image/gif"
41774
+ ];
41775
+ var MAX_ICON_SOURCE_FILE_SIZE_BYTES = 15 * 1024 * 1024;
41776
+ var PARTICIPANT_SOURCE = {
41777
+ MENTION: "mention",
41778
+ SPOKE: "spoke",
41779
+ ADDED: "added"
41780
+ };
41781
+
41782
+ // ../shared/src/lib/discriminator.ts
41783
+ function parseNameAndTag(q) {
41784
+ const m = /^(.+)#(\d{4,})$/.exec(q);
41785
+ if (!m)
41786
+ return null;
41787
+ const name = m[1].trim();
41788
+ const discriminator = m[2];
41789
+ if (!name)
41790
+ return null;
41791
+ return { name, discriminator };
41792
+ }
41793
+ function formatHandle(name, discriminator) {
41794
+ return `${name}#${discriminator}`;
41795
+ }
41796
+
41797
+ // ../shared/src/pii-contract.ts
41798
+ var PII_CAPABILITY = "pii-v1";
41799
+ var PII_MAX_PLUGINS = 32;
41800
+ var PII_SOURCE_MAX_BYTES = 16 * 1024;
41801
+ var PII_TEXT_MAX_BYTES = 1024;
41802
+ var PII_REQUEST_MAX_BYTES = 8 * 1024;
41803
+ var PiiPreviewTextSchema = exports_external.string().max(PII_TEXT_MAX_BYTES).refine((text) => new TextEncoder().encode(text).byteLength <= PII_TEXT_MAX_BYTES).refine((text) => text.trim().length > 0);
41804
+ var PiiPluginSchema = exports_external.strictObject({
41805
+ id: exports_external.string().min(1).max(128),
41806
+ name: exports_external.string().trim().min(1).max(80),
41807
+ description: exports_external.string().trim().min(1).max(256),
41808
+ enabled: exports_external.boolean()
41809
+ });
41810
+ var PiiSnapshotSchema = exports_external.strictObject({
41811
+ revision: exports_external.number().int().nonnegative(),
41812
+ plugins: exports_external.array(PiiPluginSchema).max(PII_MAX_PLUGINS)
41813
+ });
41814
+ var pluginId = exports_external.string().min(1).max(128);
41815
+ var expectedRevision = exports_external.number().int().nonnegative();
41816
+ var PiiOperationSchema = exports_external.discriminatedUnion("action", [
41817
+ exports_external.strictObject({ action: exports_external.literal("list") }),
41818
+ exports_external.strictObject({ action: exports_external.literal("setEnabled"), pluginId, enabled: exports_external.boolean(), expectedRevision }),
41819
+ exports_external.strictObject({ action: exports_external.literal("remove"), pluginId, expectedRevision }),
41820
+ exports_external.strictObject({ action: exports_external.literal("preview"), text: PiiPreviewTextSchema, expectedRevision })
41821
+ ]);
41822
+ var PiiRequestSchema = exports_external.strictObject({
41823
+ requestId: exports_external.string().min(1).max(128),
41824
+ operation: PiiOperationSchema
41825
+ });
41826
+ var PiiCommandSchema = PiiRequestSchema.extend({
41827
+ type: exports_external.literal("pii:manage"),
41828
+ botId: exports_external.string().min(1).max(128)
41829
+ });
41830
+ var PiiErrorCodeSchema = exports_external.enum([
41831
+ "PII_CONFLICT",
41832
+ "PII_UNAVAILABLE",
41833
+ "PII_PLUGIN_NOT_FOUND",
41834
+ "PII_BOT_NOT_FOUND",
41835
+ "PII_PLUGIN_FAILED",
41836
+ "PII_PLUGIN_TIMEOUT",
41837
+ "PII_INVALID_RESULT",
41838
+ "PII_OUTPUT_TOO_LARGE",
41839
+ "PII_INVALID_SOURCE",
41840
+ "PII_CONFIG_UNAVAILABLE",
41841
+ "PII_SOURCE_TOO_LARGE",
41842
+ "PII_INVALID_REQUEST"
41843
+ ]);
41844
+ var PiiResultSchema = exports_external.discriminatedUnion("status", [
41845
+ exports_external.strictObject({ status: exports_external.literal("complete"), snapshot: PiiSnapshotSchema, output: PiiPreviewTextSchema.optional(), triggeredFilters: exports_external.array(PiiPluginSchema.pick({ id: true, name: true })).max(PII_MAX_PLUGINS).optional() }),
41846
+ exports_external.strictObject({
41847
+ status: exports_external.literal("error"),
41848
+ code: PiiErrorCodeSchema,
41849
+ pluginId: pluginId.optional(),
41850
+ snapshot: PiiSnapshotSchema.optional()
41851
+ })
41852
+ ]);
41853
+ var PiiResultFrameSchema = exports_external.strictObject({
41854
+ type: exports_external.literal("pii_result"),
41855
+ botId: exports_external.string().min(1).max(128),
41856
+ requestId: exports_external.string().min(1).max(128),
41857
+ result: PiiResultSchema
41858
+ });
41859
+ var PiiLocalRequestSchema = exports_external.discriminatedUnion("action", [
41860
+ exports_external.strictObject({ action: exports_external.literal("list") }),
41861
+ exports_external.strictObject({
41862
+ action: exports_external.literal("add"),
41863
+ name: PiiPluginSchema.shape.name,
41864
+ description: PiiPluginSchema.shape.description,
41865
+ source: exports_external.string().min(1).max(PII_SOURCE_MAX_BYTES)
41866
+ })
41867
+ ]);
41868
+
41869
+ // ../shared/src/utils/community-roles.ts
41870
+ var ROLES = {
41871
+ OWNER: "owner",
41872
+ ADMIN: "admin",
41873
+ MEMBER: "member"
41874
+ };
41875
+
41757
41876
  // ../shared/src/db/community-machine-schema.ts
41758
41877
  var exports_community_machine_schema = {};
41759
41878
  __export(exports_community_machine_schema, {
@@ -44240,25 +44359,6 @@ var OwnerDiagnosticReportSchema = exports_external.discriminatedUnion("status",
44240
44359
  objectExpired: exports_external.literal(false)
44241
44360
  }).strict()
44242
44361
  ]);
44243
- // ../shared/src/community-contract.ts
44244
- var COMMUNITY_RESOURCE_CONTRACT_VERSION = 3;
44245
-
44246
- // ../shared/src/community-friend-approval.ts
44247
- var profile = exports_external.strictObject({
44248
- id: exports_external.string(),
44249
- name: exports_external.string(),
44250
- discriminator: exports_external.string(),
44251
- image: exports_external.string().nullable(),
44252
- avatarVersion: exports_external.number().int().nonnegative()
44253
- });
44254
- var FriendApprovalPayloadSchema = exports_external.strictObject({
44255
- friendshipId: exports_external.string(),
44256
- status: exports_external.enum(["pending", "approved", "denied", "superseded", "cancelled"]),
44257
- waitingOn: exports_external.enum(["you", "other-owner", "addressee"]).nullable(),
44258
- otherProfile: profile,
44259
- botProfile: profile,
44260
- waitingOnProfile: profile.nullable().optional()
44261
- });
44262
44362
 
44263
44363
  // ../shared/src/runtime-models-contract.ts
44264
44364
  var RUNTIME_MODEL_DISCOVERY_CAPABILITY = "runtime-model-discovery-v1";
@@ -44275,100 +44375,6 @@ var RuntimeModelDiscoveryErrorSchema = exports_external.strictObject({
44275
44375
  message: exports_external.string().min(1).max(256)
44276
44376
  });
44277
44377
 
44278
- // ../shared/src/utils/slug.ts
44279
- init_nanoid();
44280
- var slugId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz");
44281
- function sanitizeSlug(input2) {
44282
- return input2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/g, "");
44283
- }
44284
-
44285
- // ../shared/src/pii-contract.ts
44286
- var PII_CAPABILITY = "pii-v1";
44287
- var PII_MAX_PLUGINS = 32;
44288
- var PII_SOURCE_MAX_BYTES = 16 * 1024;
44289
- var PII_TEXT_MAX_BYTES = 1024;
44290
- var PII_REQUEST_MAX_BYTES = 8 * 1024;
44291
- var PiiPreviewTextSchema = exports_external.string().max(PII_TEXT_MAX_BYTES).refine((text2) => new TextEncoder().encode(text2).byteLength <= PII_TEXT_MAX_BYTES).refine((text2) => text2.trim().length > 0);
44292
- var PiiPluginSchema = exports_external.strictObject({
44293
- id: exports_external.string().min(1).max(128),
44294
- name: exports_external.string().trim().min(1).max(80),
44295
- description: exports_external.string().trim().min(1).max(256),
44296
- enabled: exports_external.boolean()
44297
- });
44298
- var PiiSnapshotSchema = exports_external.strictObject({
44299
- revision: exports_external.number().int().nonnegative(),
44300
- plugins: exports_external.array(PiiPluginSchema).max(PII_MAX_PLUGINS)
44301
- });
44302
- var pluginId = exports_external.string().min(1).max(128);
44303
- var expectedRevision = exports_external.number().int().nonnegative();
44304
- var PiiOperationSchema = exports_external.discriminatedUnion("action", [
44305
- exports_external.strictObject({ action: exports_external.literal("list") }),
44306
- exports_external.strictObject({ action: exports_external.literal("setEnabled"), pluginId, enabled: exports_external.boolean(), expectedRevision }),
44307
- exports_external.strictObject({ action: exports_external.literal("remove"), pluginId, expectedRevision }),
44308
- exports_external.strictObject({ action: exports_external.literal("preview"), text: PiiPreviewTextSchema, expectedRevision })
44309
- ]);
44310
- var PiiRequestSchema = exports_external.strictObject({
44311
- requestId: exports_external.string().min(1).max(128),
44312
- operation: PiiOperationSchema
44313
- });
44314
- var PiiCommandSchema = PiiRequestSchema.extend({
44315
- type: exports_external.literal("pii:manage"),
44316
- botId: exports_external.string().min(1).max(128)
44317
- });
44318
- var PiiErrorCodeSchema = exports_external.enum([
44319
- "PII_CONFLICT",
44320
- "PII_UNAVAILABLE",
44321
- "PII_PLUGIN_NOT_FOUND",
44322
- "PII_BOT_NOT_FOUND",
44323
- "PII_PLUGIN_FAILED",
44324
- "PII_PLUGIN_TIMEOUT",
44325
- "PII_INVALID_RESULT",
44326
- "PII_OUTPUT_TOO_LARGE",
44327
- "PII_INVALID_SOURCE",
44328
- "PII_CONFIG_UNAVAILABLE",
44329
- "PII_SOURCE_TOO_LARGE",
44330
- "PII_INVALID_REQUEST"
44331
- ]);
44332
- var PiiResultSchema = exports_external.discriminatedUnion("status", [
44333
- exports_external.strictObject({ status: exports_external.literal("complete"), snapshot: PiiSnapshotSchema, output: PiiPreviewTextSchema.optional(), triggeredFilters: exports_external.array(PiiPluginSchema.pick({ id: true, name: true })).max(PII_MAX_PLUGINS).optional() }),
44334
- exports_external.strictObject({
44335
- status: exports_external.literal("error"),
44336
- code: PiiErrorCodeSchema,
44337
- pluginId: pluginId.optional(),
44338
- snapshot: PiiSnapshotSchema.optional()
44339
- })
44340
- ]);
44341
- var PiiResultFrameSchema = exports_external.strictObject({
44342
- type: exports_external.literal("pii_result"),
44343
- botId: exports_external.string().min(1).max(128),
44344
- requestId: exports_external.string().min(1).max(128),
44345
- result: PiiResultSchema
44346
- });
44347
- var PiiLocalRequestSchema = exports_external.discriminatedUnion("action", [
44348
- exports_external.strictObject({ action: exports_external.literal("list") }),
44349
- exports_external.strictObject({
44350
- action: exports_external.literal("add"),
44351
- name: PiiPluginSchema.shape.name,
44352
- description: PiiPluginSchema.shape.description,
44353
- source: exports_external.string().min(1).max(PII_SOURCE_MAX_BYTES)
44354
- })
44355
- ]);
44356
-
44357
- // ../shared/src/lib/discriminator.ts
44358
- function parseNameAndTag(q) {
44359
- const m = /^(.+)#(\d{4,})$/.exec(q);
44360
- if (!m)
44361
- return null;
44362
- const name = m[1].trim();
44363
- const discriminator = m[2];
44364
- if (!name)
44365
- return null;
44366
- return { name, discriminator };
44367
- }
44368
- function formatHandle(name, discriminator) {
44369
- return `${name}#${discriminator}`;
44370
- }
44371
-
44372
44378
  // ../shared/src/community-cli-contract.ts
44373
44379
  var AGENT_EVENT_PROMPT_MAX_LENGTH = 32768;
44374
44380
  var DM_SERVER = ".dm";
@@ -44544,6 +44550,91 @@ var HostCommandSchema = exports_external.discriminatedUnion("type", [
44544
44550
  DiagnosticCollectCommandSchema
44545
44551
  ]);
44546
44552
 
44553
+ // ../shared/src/automation.ts
44554
+ var AUTOMATION_WRITE_PERMISSIONS = ["bot.create", "server.create", "server.invite", "message.send"];
44555
+ var AUTOMATION_READ_PERMISSIONS = ["machine.read", "friend.read", "server.read"];
44556
+ var AutomationPermissionSchema = exports_external.enum([...AUTOMATION_WRITE_PERMISSIONS, ...AUTOMATION_READ_PERMISSIONS]);
44557
+ var AutomationExpirySchema = exports_external.enum(["1h", "24h", "7d", "30d", "forever"]);
44558
+ var AutomationPermissionPolicySchema = exports_external.strictObject({
44559
+ permission: AutomationPermissionSchema,
44560
+ limit: exports_external.number().int().positive(),
44561
+ period: exports_external.enum(["hour", "day"])
44562
+ }).refine((value) => value.limit <= (value.period === "hour" ? 64 : 1536), {
44563
+ message: "Limit cannot exceed 64/hour or 1536/day",
44564
+ path: ["limit"]
44565
+ });
44566
+ var permissions = exports_external.array(AutomationPermissionPolicySchema).min(1).max(AutomationPermissionSchema.options.length).refine((values) => new Set(values.map((value) => value.permission)).size === values.length, "Duplicate permission");
44567
+ var AutomationAccessCodeCreateSchema = exports_external.strictObject({
44568
+ name: exports_external.string().trim().min(1).max(100),
44569
+ expiresIn: AutomationExpirySchema.default("24h"),
44570
+ permissions
44571
+ });
44572
+ var AutomationAccessCodeUpdateSchema = exports_external.strictObject({
44573
+ name: exports_external.string().trim().min(1).max(100).optional(),
44574
+ expiresIn: AutomationExpirySchema.optional(),
44575
+ permissions: permissions.optional()
44576
+ }).refine((value) => Object.keys(value).length > 0, "Provide at least one change");
44577
+ var AutomationMessageSendSchema = exports_external.strictObject({
44578
+ target: exports_external.string().min(1).max(1024).refine((value) => {
44579
+ try {
44580
+ parseRef(value);
44581
+ return true;
44582
+ } catch {
44583
+ return false;
44584
+ }
44585
+ }, "Use a channel or DM ref"),
44586
+ as: exports_external.string().max(128).refine((value) => value === "me" || value.startsWith("@") && Boolean(parseNameAndTag(value.slice(1))), "Use me or @name#NNNN"),
44587
+ content: exports_external.string().max(MAX_MESSAGE_CONTENT_LENGTH).refine((value) => value.trim().length > 0, "Message content is required"),
44588
+ nonce: exports_external.string().min(1).max(128)
44589
+ });
44590
+ var AutomationMessageSentSchema = exports_external.object({
44591
+ state: exports_external.literal("sent"),
44592
+ seq: exports_external.string().regex(/^#[1-9]\d*$/),
44593
+ deduped: exports_external.boolean(),
44594
+ threadId: exports_external.string().optional()
44595
+ });
44596
+ // ../shared/src/community-profile-resource.ts
44597
+ var CommunityResourceProfileSchema = exports_external.strictObject({
44598
+ id: exports_external.string().min(1),
44599
+ name: exports_external.string(),
44600
+ discriminator: exports_external.string().min(1),
44601
+ avatar: exports_external.string().nullable(),
44602
+ avatarVersion: exports_external.number().int().nonnegative(),
44603
+ aboutMe: exports_external.string().optional(),
44604
+ bannerColor: exports_external.string().nullable().optional(),
44605
+ kind: exports_external.enum(["human", "bot"]).optional(),
44606
+ ownerUserId: exports_external.string().min(1).nullable().optional(),
44607
+ ownerHandle: exports_external.string().nullable().optional(),
44608
+ mutualServers: exports_external.number().int().nonnegative().optional(),
44609
+ ownedByViewer: exports_external.boolean().optional(),
44610
+ statusEmoji: exports_external.string().nullable().optional(),
44611
+ statusText: exports_external.string().nullable().optional()
44612
+ });
44613
+ // ../shared/src/business-schema-version.ts
44614
+ var BUSINESS_SCHEMA_VERSION = 7;
44615
+
44616
+ // ../shared/src/community-contract.ts
44617
+ var COMMUNITY_RESOURCE_CONTRACT_VERSION = BUSINESS_SCHEMA_VERSION;
44618
+
44619
+ // ../shared/src/community-friend-approval.ts
44620
+ var identity = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatarVersion: true });
44621
+ var profile = identity.extend({ image: CommunityResourceProfileSchema.shape.avatar });
44622
+ var FriendApprovalPayloadSchema = exports_external.strictObject({
44623
+ friendshipId: exports_external.string(),
44624
+ status: exports_external.enum(["pending", "approved", "denied", "superseded", "cancelled"]),
44625
+ waitingOn: exports_external.enum(["you", "other-owner", "addressee"]).nullable(),
44626
+ otherProfile: profile,
44627
+ botProfile: profile,
44628
+ waitingOnProfile: profile.nullable().optional()
44629
+ });
44630
+
44631
+ // ../shared/src/utils/slug.ts
44632
+ init_nanoid();
44633
+ var slugId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz");
44634
+ function sanitizeSlug(input2) {
44635
+ return input2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/g, "");
44636
+ }
44637
+
44547
44638
  // ../shared/src/provider-telemetry.ts
44548
44639
  var DAILY_TOKEN_USAGE_WINDOW_DAYS = 30;
44549
44640
  var safeToken = exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
@@ -44611,11 +44702,11 @@ var AvailableQuotaObservationSchema = exports_external.object({
44611
44702
  }).strict().superRefine((value, ctx) => {
44612
44703
  const identities = new Set;
44613
44704
  for (const [index2, limit] of value.limits.entries()) {
44614
- const identity = quotaIdentity(limit);
44615
- if (identities.has(identity)) {
44705
+ const identity2 = quotaIdentity(limit);
44706
+ if (identities.has(identity2)) {
44616
44707
  ctx.addIssue({ code: "custom", message: "duplicate quota bucket identity", path: ["limits", index2] });
44617
44708
  }
44618
- identities.add(identity);
44709
+ identities.add(identity2);
44619
44710
  }
44620
44711
  });
44621
44712
  var ProviderQuotaObservationSchema = exports_external.union([
@@ -44632,24 +44723,6 @@ var ProviderQuotaSnapshotSchema = exports_external.object({
44632
44723
  observation: ProviderQuotaObservationSchema
44633
44724
  }).strict();
44634
44725
 
44635
- // ../shared/src/constants/community.ts
44636
- var MAX_FOLDER_NAME_LENGTH = 100;
44637
- var MAX_PROFILE_NAME_LENGTH = 100;
44638
- var MAX_PROFILE_ABOUT_LENGTH = 1000;
44639
- var MAX_MESSAGE_CONTENT_LENGTH = 4000;
44640
- var MAX_ATTACHMENTS_PER_MESSAGE = 10;
44641
- var MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024;
44642
- var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 720;
44643
- var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 256 * 1024;
44644
- var MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024;
44645
- var ALLOWED_ICON_MIME_TYPES = [
44646
- "image/png",
44647
- "image/jpeg",
44648
- "image/webp",
44649
- "image/gif"
44650
- ];
44651
- var MAX_ICON_SOURCE_FILE_SIZE_BYTES = 15 * 1024 * 1024;
44652
-
44653
44726
  // ../shared/src/lib/community-name.ts
44654
44727
  var FORBIDDEN_NAME_CHARS = /[#@\x00-\x1f\x7f-\x9f]/;
44655
44728
  function validateCommunityName(name) {
@@ -44775,15 +44848,6 @@ var PollResponseSchema = exports_external.object({
44775
44848
  file_requests: exports_external.array(FileRequestItemSchema).optional(),
44776
44849
  meetings: exports_external.array(PollMeetingItemSchema).optional()
44777
44850
  });
44778
- var DaemonPushMessageSchema = exports_external.discriminatedUnion("type", [
44779
- exports_external.object({ type: exports_external.literal("daemon.tasks"), tasks: exports_external.array(TaskApiSchema) }),
44780
- exports_external.object({ type: exports_external.literal("daemon.file_requests"), workspaceId: exports_external.string(), requests: exports_external.array(FileRequestItemSchema) }),
44781
- exports_external.object({ type: exports_external.literal("daemon.meetings"), meetings: exports_external.array(PollMeetingItemSchema) }),
44782
- exports_external.object({ type: exports_external.literal("daemon.evict"), workspaceId: exports_external.string() }),
44783
- exports_external.object({ type: exports_external.literal("daemon.update"), version: exports_external.string() }),
44784
- exports_external.object({ type: exports_external.literal("daemon.rescan") }),
44785
- exports_external.object({ type: exports_external.literal("daemon.kill"), workspaceId: exports_external.string(), agentId: exports_external.string().min(1), taskId: exports_external.string(), targetTaskId: exports_external.string() })
44786
- ]);
44787
44851
  var RegisterResponseSchema = exports_external.object({
44788
44852
  runtimes: exports_external.array(exports_external.object({ id: exports_external.string() }))
44789
44853
  });
@@ -44977,11 +45041,7 @@ var CreateConversationRequestSchema = exports_external.object({
44977
45041
  });
44978
45042
  var CreateMessageRequestSchema = exports_external.object({
44979
45043
  content: exports_external.string().min(1, "content is required"),
44980
- metadata: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
44981
- });
44982
- var AgentDmRequestSchema = exports_external.object({
44983
- content: exports_external.string().min(1, "content is required"),
44984
- task_id: exports_external.string().min(1).optional()
45044
+ metadata: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
44985
45045
  });
44986
45046
  var EmailAttachmentSchema = exports_external.object({
44987
45047
  key: exports_external.string().min(1),
@@ -45611,13 +45671,12 @@ var BotCreationSubmitSchema = exports_external.strictObject({
45611
45671
  requestId: exports_external.string().min(1).max(128),
45612
45672
  bots: exports_external.array(BotCreationProposalSchema).min(1).max(BOT_CREATION_MAX_ITEMS)
45613
45673
  });
45614
- var BotCreationIdentitySchema = exports_external.strictObject({
45615
- id: exports_external.string(),
45616
- name: exports_external.string(),
45617
- discriminator: exports_external.string(),
45618
- image: exports_external.string().nullable(),
45619
- avatarVersion: exports_external.number().int().nonnegative()
45620
- });
45674
+ var BotCreationIdentitySchema = CommunityResourceProfileSchema.pick({
45675
+ id: true,
45676
+ name: true,
45677
+ discriminator: true,
45678
+ avatarVersion: true
45679
+ }).extend({ image: CommunityResourceProfileSchema.shape.avatar });
45621
45680
  var BotCreationItemSchema = BotCreationProposalSchema.extend({
45622
45681
  itemId: exports_external.string(),
45623
45682
  description: exports_external.string(),
@@ -45640,7 +45699,26 @@ var BotCreationDecisionSchema = exports_external.strictObject({ decision: export
45640
45699
  // ../shared/src/community-resources.ts
45641
45700
  var id = exports_external.string().min(1);
45642
45701
  var nullableId = id.nullable();
45643
- var legacyArchivedSchema = exports_external.union([exports_external.boolean(), exports_external.literal(0), exports_external.literal(1)]).transform((value) => value === true || value === 1);
45702
+ var storedArchivedSchema = exports_external.union([exports_external.boolean(), exports_external.literal(0), exports_external.literal(1)]).transform((value) => value === true || value === 1);
45703
+ var CommunityServerResourceSchema = exports_external.strictObject({
45704
+ id: exports_external.string().min(1),
45705
+ position: exports_external.number().int().nonnegative(),
45706
+ name: exports_external.string(),
45707
+ discriminator: exports_external.string(),
45708
+ description: exports_external.string(),
45709
+ ownerId: exports_external.string(),
45710
+ icon: exports_external.string().nullable(),
45711
+ official: exports_external.boolean(),
45712
+ isOwner: exports_external.boolean()
45713
+ });
45714
+ var CommunityCategoryResourceSchema = exports_external.strictObject({
45715
+ id: exports_external.string().min(1),
45716
+ serverId: exports_external.string().min(1),
45717
+ name: exports_external.string(),
45718
+ position: exports_external.number(),
45719
+ private: exports_external.boolean(),
45720
+ creatorId: exports_external.string().nullable()
45721
+ });
45644
45722
  var CommunityChannelResourceSchema = exports_external.strictObject({
45645
45723
  id,
45646
45724
  type: exports_external.enum(["text", "forum", "thread", "dm"]),
@@ -45668,31 +45746,13 @@ var CommunityChannelIdentitySchema = CommunityChannelResourceSchema.pick({
45668
45746
  archived: true,
45669
45747
  lastMessageAt: true,
45670
45748
  createdAt: true
45671
- }).partial({ createdAt: true }).strip();
45672
- var legacyChannelIdentitySchema = CommunityChannelIdentitySchema.extend({
45673
- archived: legacyArchivedSchema,
45674
- parentChannelId: nullableId.default(null),
45675
- parentMessageId: nullableId.default(null),
45676
- creatorId: nullableId.default(null),
45677
- lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null)
45678
- });
45749
+ }).strip();
45679
45750
  var CommunityAccessDecisionSchema = exports_external.strictObject({
45680
45751
  channelId: id,
45681
45752
  canRead: exports_external.boolean(),
45682
45753
  canSend: exports_external.boolean(),
45683
45754
  canCreateDiscussion: exports_external.boolean()
45684
45755
  });
45685
- var CommunityLegacyMessageAttachmentSchema = exports_external.strictObject({
45686
- kind: exports_external.enum(["image", "file"]),
45687
- name: exports_external.string(),
45688
- url: exports_external.string(),
45689
- thumbnailUrl: exports_external.string().optional(),
45690
- contentType: exports_external.string().optional(),
45691
- size: exports_external.string().optional(),
45692
- sizeBytes: exports_external.number().nonnegative().optional(),
45693
- width: exports_external.number().nonnegative().optional(),
45694
- height: exports_external.number().nonnegative().optional()
45695
- });
45696
45756
  var CommunityMessageAttachmentSchema = exports_external.strictObject({
45697
45757
  id,
45698
45758
  name: exports_external.string(),
@@ -45703,23 +45763,6 @@ var CommunityMessageAttachmentSchema = exports_external.strictObject({
45703
45763
  width: exports_external.number().int().nonnegative().nullable(),
45704
45764
  height: exports_external.number().int().nonnegative().nullable()
45705
45765
  });
45706
- var CommunityMessagePreviewAttachmentSchema = CommunityMessageAttachmentSchema.partial().required({ name: true, url: true });
45707
- var CommunityResourceProfileSchema = exports_external.strictObject({
45708
- id,
45709
- name: exports_external.string(),
45710
- discriminator: exports_external.string().min(1).nullable(),
45711
- avatar: exports_external.string().nullable(),
45712
- avatarVersion: exports_external.number().int().nonnegative(),
45713
- aboutMe: exports_external.string().optional(),
45714
- bannerColor: exports_external.string().nullable().optional(),
45715
- kind: exports_external.enum(["human", "bot"]).optional(),
45716
- ownerUserId: nullableId.optional(),
45717
- ownerHandle: exports_external.string().nullable().optional(),
45718
- mutualServers: exports_external.number().int().nonnegative().optional(),
45719
- ownedByViewer: exports_external.boolean().optional(),
45720
- statusEmoji: exports_external.string().nullable().optional(),
45721
- statusText: exports_external.string().nullable().optional()
45722
- });
45723
45766
  var CommunityMessageThreadParticipantSchema = CommunityResourceProfileSchema.pick({ id: true, name: true, avatar: true, avatarVersion: true });
45724
45767
  var messageThreadSchema = exports_external.strictObject({
45725
45768
  id,
@@ -45731,14 +45774,6 @@ var messageThreadSchema = exports_external.strictObject({
45731
45774
  participants: exports_external.array(CommunityMessageThreadParticipantSchema).optional(),
45732
45775
  participantCount: exports_external.number().int().nonnegative().optional()
45733
45776
  });
45734
- var legacyMessageThreadSchema = messageThreadSchema.extend({
45735
- name: exports_external.string(),
45736
- lastReplyAt: exports_external.string().optional(),
45737
- participants: exports_external.array(CommunityMessageThreadParticipantSchema.extend({ avatar: exports_external.string() })).optional()
45738
- });
45739
- var messageThreadPreviewSchema = messageThreadSchema.partial().required({ id: true }).extend({
45740
- participants: exports_external.array(CommunityMessageThreadParticipantSchema.partial().required({ id: true })).optional()
45741
- });
45742
45777
  var CommunityMessageResourceSchema = exports_external.strictObject({
45743
45778
  id,
45744
45779
  channelId: id,
@@ -45761,7 +45796,7 @@ var CommunityMessageResourceSchema = exports_external.strictObject({
45761
45796
  authorName: exports_external.string(),
45762
45797
  text: exports_external.string(),
45763
45798
  deleted: exports_external.boolean().optional()
45764
- }).optional(),
45799
+ }).refine((reply) => reply.deleted === true || reply.authorId !== undefined, { message: "Live reply author identity missing" }).optional(),
45765
45800
  embeds: exports_external.array(exports_external.unknown()).optional(),
45766
45801
  reactions: exports_external.array(exports_external.strictObject({
45767
45802
  emoji: exports_external.string(),
@@ -45773,21 +45808,37 @@ var CommunityMessageResourceSchema = exports_external.strictObject({
45773
45808
  approval: FriendApprovalPayloadSchema.optional(),
45774
45809
  botCreation: BotCreationPayloadSchema.optional()
45775
45810
  });
45776
- var CommunityMessagePreviewSchema = CommunityMessageResourceSchema.partial().required({
45777
- id: true,
45778
- type: true
45779
- }).extend({ attachments: exports_external.array(CommunityMessagePreviewAttachmentSchema).optional(), thread: messageThreadPreviewSchema.optional() });
45811
+ function communityMessageProfileIds(messages) {
45812
+ return [...new Set(messages.flatMap((message2) => [message2.authorId, ...message2.replyTo?.authorId && message2.replyTo.deleted !== true ? [message2.replyTo.authorId] : []]))];
45813
+ }
45814
+ var CommunityMessageResourcesSchema = exports_external.strictObject({
45815
+ messages: exports_external.array(CommunityMessageResourceSchema),
45816
+ profiles: exports_external.array(CommunityResourceProfileSchema)
45817
+ }).superRefine((resources, ctx) => {
45818
+ const ids = new Set(resources.profiles.map((profile2) => profile2.id));
45819
+ if (ids.size !== resources.profiles.length || communityMessageProfileIds(resources.messages).some((id2) => !ids.has(id2))) {
45820
+ ctx.addIssue({ code: "custom", path: ["profiles"], message: "Message profile missing or duplicated in resource graph" });
45821
+ }
45822
+ });
45780
45823
  var CommunityReadStateResourceSchema = exports_external.strictObject({
45781
45824
  channelId: id,
45782
45825
  lastReadMessageId: nullableId,
45783
45826
  lastReadAt: exports_external.string().nullable(),
45784
45827
  lastReadSeq: exports_external.number().int().nonnegative()
45785
45828
  });
45786
- var CommunityMemberRelationSchema = exports_external.strictObject({
45829
+ var CommunityServerMembershipResourceSchema = exports_external.strictObject({
45830
+ serverId: id,
45831
+ userId: id,
45832
+ memberId: id,
45833
+ role: exports_external.string()
45834
+ });
45835
+ var CommunityChannelMembershipResourceSchema = exports_external.strictObject({
45787
45836
  channelId: id,
45788
45837
  userId: id,
45789
45838
  relation: exports_external.enum(["access", "notify"]),
45790
- source: exports_external.string(),
45839
+ source: exports_external.enum([...Object.values(PARTICIPANT_SOURCE), "explicit", "inherited", "admin", "access-decision"])
45840
+ });
45841
+ var CommunityMemberRelationSchema = CommunityChannelMembershipResourceSchema.extend({
45791
45842
  isCreator: exports_external.boolean(),
45792
45843
  role: exports_external.string().nullable(),
45793
45844
  memberId: nullableId
@@ -45800,14 +45851,25 @@ var CommunityPageSchema = exports_external.strictObject({
45800
45851
  latestSeq: exports_external.number().int().nonnegative()
45801
45852
  });
45802
45853
  var envelope = { contractVersion: exports_external.literal(COMMUNITY_RESOURCE_CONTRACT_VERSION), channelId: id };
45854
+ var CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
45855
+ viewerId: id,
45856
+ servers: exports_external.array(CommunityServerResourceSchema),
45857
+ serverMemberships: exports_external.array(CommunityServerMembershipResourceSchema),
45858
+ channels: exports_external.array(CommunityChannelResourceSchema),
45859
+ memberships: exports_external.array(CommunityChannelMembershipResourceSchema)
45860
+ }).superRefine((bundle, ctx) => {
45861
+ const channels = new Set(bundle.channels.map((row) => row.id));
45862
+ const servers = new Set(bundle.servers.map((row) => row.id));
45863
+ 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((member2) => member2.serverId === row.id && member2.userId === bundle.viewerId)) || bundle.channels.some((row) => !bundle.memberships.some((member2) => member2.channelId === row.id && member2.userId === bundle.viewerId && member2.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)))
45864
+ ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" });
45865
+ });
45803
45866
  var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
45804
- var CommunityMessagesReadSchema = exports_external.strictObject({
45867
+ var CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({
45805
45868
  ...envelope,
45806
- messages: exports_external.array(CommunityMessageResourceSchema),
45807
45869
  page: CommunityPageSchema,
45808
45870
  surfaceReceipt: exports_external.strictObject({ channelId: id, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
45809
45871
  });
45810
- var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.extend({
45872
+ var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
45811
45873
  viewerId: id,
45812
45874
  peer: CommunityResourceProfileSchema.nullable(),
45813
45875
  channel: CommunityChannelResourceSchema,
@@ -45822,6 +45884,12 @@ var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.extend({
45822
45884
  anchorMessageId: nullableId
45823
45885
  })
45824
45886
  }).superRefine((entry, ctx) => {
45887
+ if (entry.opener) {
45888
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [...entry.messages, entry.opener], profiles: entry.profiles });
45889
+ if (!graph.success)
45890
+ for (const issue3 of graph.error.issues)
45891
+ ctx.addIssue({ code: "custom", path: issue3.path, message: issue3.message });
45892
+ }
45825
45893
  for (const [path, channelId] of [
45826
45894
  [["channel", "id"], entry.channel.id],
45827
45895
  [["access", "channelId"], entry.access.channelId],
@@ -45859,72 +45927,37 @@ var CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.extend({
45859
45927
  if (entry.selection.reason === "read_pointer_missing" && entry.readState.lastReadMessageId === null)
45860
45928
  ctx.addIssue({ code: "custom", path: ["selection", "reason"], message: "Conversation entry missing read pointer" });
45861
45929
  });
45862
- var CommunityMessagePostedSchema = CommunityMessagesReadSchema.pick({ contractVersion: true, channelId: true }).extend({
45930
+ var CommunityMessageReadSchema = exports_external.strictObject({
45931
+ ...envelope,
45863
45932
  message: CommunityMessageResourceSchema,
45864
- deduped: exports_external.boolean(),
45865
- threadId: id.optional()
45933
+ profiles: CommunityMessageResourcesSchema.shape.profiles
45934
+ }).superRefine((read, ctx) => {
45935
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [read.message], profiles: read.profiles });
45936
+ if (!graph.success)
45937
+ for (const issue3 of graph.error.issues)
45938
+ ctx.addIssue({ code: "custom", path: issue3.path, message: issue3.message });
45866
45939
  });
45867
- var CommunityMessageReadSchema = CommunityMessagePostedSchema.omit({ deduped: true, threadId: true });
45940
+ var CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: exports_external.boolean(), threadId: id.optional() });
45868
45941
  var CommunityMembersReadSchema = exports_external.strictObject({ ...envelope, relation: exports_external.enum(["access", "notify"]), members: exports_external.array(CommunityMemberRelationSchema), profiles: exports_external.array(CommunityResourceProfileSchema) });
45869
45942
  var CommunityThreadsReadSchema = exports_external.strictObject({
45870
45943
  ...envelope,
45871
45944
  channel: CommunityChannelResourceSchema,
45872
45945
  threads: exports_external.array(CommunityChannelResourceSchema),
45873
- included: exports_external.strictObject({
45874
- messages: exports_external.array(CommunityMessageResourceSchema),
45946
+ included: CommunityMessageResourcesSchema.safeExtend({
45875
45947
  members: exports_external.array(CommunityMemberRelationSchema),
45876
- profiles: exports_external.array(CommunityResourceProfileSchema),
45877
45948
  tags: exports_external.array(exports_external.strictObject({ messageId: id, tag: exports_external.string() })),
45878
45949
  participantCounts: exports_external.array(exports_external.strictObject({ channelId: id, count: exports_external.number().int().nonnegative() }))
45879
45950
  }),
45880
45951
  page: exports_external.strictObject({ nextCursor: exports_external.string().nullable(), hasMore: exports_external.boolean() })
45881
45952
  });
45882
45953
  var CommunityReadAdvanceSchema = exports_external.strictObject({ ...envelope, changed: exports_external.boolean(), targetSeq: exports_external.number().int().nonnegative(), revision: exports_external.number().int().nonnegative() });
45954
+ var CommunityInviteJoinTargetSchema = exports_external.object({ serverId: CommunityServerResourceSchema.shape.id }).strip();
45883
45955
  var CommunityReadErrorSchema = exports_external.strictObject({ contractVersion: exports_external.literal(COMMUNITY_RESOURCE_CONTRACT_VERSION), error: exports_external.strictObject({
45884
45956
  code: exports_external.enum(["invalid_input", "invalid_reply_target", "unauthenticated", "not_found", "not_allowed", "blocked", "idempotency_conflict", "rate_limited", "temporarily_unavailable"]),
45885
45957
  message: exports_external.string(),
45886
- retryable: exports_external.boolean()
45958
+ retryable: exports_external.boolean(),
45959
+ details: exports_external.array(exports_external.string()).optional()
45887
45960
  }) });
45888
- var legacyProfileSchema = CommunityResourceProfileSchema.pick({
45889
- id: true,
45890
- name: true,
45891
- avatar: true,
45892
- avatarVersion: true
45893
- }).extend({ discriminator: exports_external.string().nullable(), statusEmoji: exports_external.string().nullable(), statusText: exports_external.string() });
45894
- var CommunityLegacyMessageResourceSchema = CommunityMessageResourceSchema.extend({ authorAvatar: exports_external.string().optional(), attachments: exports_external.array(CommunityLegacyMessageAttachmentSchema), thread: legacyMessageThreadSchema.optional() });
45895
- var legacyEnvelope = { contractVersion: exports_external.literal(2), channelId: id };
45896
- var legacyReadSchemas = {
45897
- channel: CommunityChannelReadSchema.extend(legacyEnvelope),
45898
- messages: CommunityMessagesReadSchema.extend({ ...legacyEnvelope, messages: exports_external.array(CommunityLegacyMessageResourceSchema) }),
45899
- members: CommunityMembersReadSchema.extend({ ...legacyEnvelope, profiles: exports_external.array(legacyProfileSchema) }),
45900
- threads: CommunityThreadsReadSchema.extend({ ...legacyEnvelope, included: CommunityThreadsReadSchema.shape.included.extend({
45901
- messages: exports_external.array(CommunityLegacyMessageResourceSchema),
45902
- profiles: exports_external.array(legacyProfileSchema)
45903
- }) }),
45904
- readAdvance: CommunityReadAdvanceSchema.extend(legacyEnvelope),
45905
- error: CommunityReadErrorSchema.extend({ contractVersion: exports_external.literal(2) })
45906
- };
45907
- var legacyChannelResourcePreviewSchema = CommunityChannelResourceSchema.partial().strip().extend({
45908
- archived: legacyArchivedSchema.optional()
45909
- });
45910
- var legacyChannelResourceSchema = CommunityChannelResourceSchema.strip().extend({
45911
- topic: CommunityChannelResourceSchema.shape.topic.nullish().transform((value) => value ?? ""),
45912
- position: CommunityChannelResourceSchema.shape.position.nullish().transform((value) => value ?? 0),
45913
- messageCount: CommunityChannelResourceSchema.shape.messageCount.nullish().transform((value) => value ?? 0),
45914
- categoryId: nullableId.default(null),
45915
- parentChannelId: nullableId.default(null),
45916
- parentMessageId: nullableId.default(null),
45917
- creatorId: nullableId.default(null),
45918
- lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),
45919
- archived: legacyArchivedSchema
45920
- });
45921
- var legacyMessageResourceSchema = CommunityLegacyMessageResourceSchema.strip().extend({
45922
- channelId: id.optional(),
45923
- replyToId: nullableId.optional(),
45924
- clientNonce: CommunityMessageResourceSchema.shape.clientNonce.default(null),
45925
- attachments: CommunityLegacyMessageResourceSchema.shape.attachments.default([]),
45926
- embeds: CommunityMessageResourceSchema.shape.embeds.nullable().transform((value) => value ?? undefined)
45927
- });
45928
45961
 
45929
45962
  // ../shared/src/community-attention.ts
45930
45963
  var id2 = exports_external.string().min(1);
@@ -45979,11 +46012,7 @@ var AttentionItemSchema = exports_external.strictObject({
45979
46012
  ctx.addIssue({ code: "custom", message: "mention or reply cannot carry forum presentation refs" });
45980
46013
  }
45981
46014
  });
45982
- var AttentionIncludedServerSchema = exports_external.strictObject({
45983
- id: id2,
45984
- name: exports_external.string(),
45985
- discriminator: exports_external.string()
45986
- });
46015
+ var AttentionIncludedServerSchema = CommunityServerResourceSchema.pick({ id: true, name: true, discriminator: true });
45987
46016
  var AttentionIncludedChannelSchema = CommunityChannelResourceSchema.pick({
45988
46017
  id: true,
45989
46018
  serverId: true,
@@ -46004,20 +46033,17 @@ var AttentionIncludedChannelSchema = CommunityChannelResourceSchema.pick({
46004
46033
  var AttentionIncludedDmSchema = exports_external.strictObject({
46005
46034
  id: id2,
46006
46035
  userId: id2,
46007
- name: exports_external.string(),
46008
- discriminator: exports_external.string(),
46009
- avatar: exports_external.string(),
46010
- avatarVersion: exports_external.number().int().nonnegative(),
46036
+ ...CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).shape,
46011
46037
  lastMessageAt: exports_external.string(),
46012
46038
  lastUnreadSeq: exports_external.number().int().nonnegative()
46013
46039
  });
46014
46040
  var AttentionIncludedProfileSchema = exports_external.strictObject({
46015
46041
  userId: CommunityResourceProfileSchema.shape.id,
46016
46042
  ...CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).shape,
46017
- discriminator: exports_external.string(),
46018
- avatar: exports_external.string()
46043
+ discriminator: CommunityResourceProfileSchema.shape.discriminator,
46044
+ avatar: CommunityResourceProfileSchema.shape.avatar
46019
46045
  });
46020
- var AttentionIncludedMessageSchema = CommunityMessagePreviewSchema.pick({
46046
+ var AttentionIncludedMessageSchema = CommunityMessageResourceSchema.pick({
46021
46047
  id: true,
46022
46048
  channelId: true,
46023
46049
  type: true,
@@ -46026,7 +46052,7 @@ var AttentionIncludedMessageSchema = CommunityMessagePreviewSchema.pick({
46026
46052
  seq: true,
46027
46053
  createdAt: true,
46028
46054
  content: true
46029
- }).required({ channelId: true, seq: true, createdAt: true, content: true });
46055
+ }).partial({ authorId: true });
46030
46056
  var AttentionIncludedSchema = exports_external.strictObject({
46031
46057
  servers: exports_external.array(AttentionIncludedServerSchema),
46032
46058
  channels: exports_external.array(AttentionIncludedChannelSchema),
@@ -46034,13 +46060,19 @@ var AttentionIncludedSchema = exports_external.strictObject({
46034
46060
  profiles: exports_external.array(AttentionIncludedProfileSchema),
46035
46061
  messages: exports_external.array(AttentionIncludedMessageSchema)
46036
46062
  });
46037
- var AccountAttentionSnapshotSchema = exports_external.strictObject({
46063
+ var AccountAttentionProjectionSchema = exports_external.strictObject({
46038
46064
  scopes: exports_external.array(AttentionScopeSchema),
46039
46065
  items: exports_external.array(AttentionItemSchema),
46040
46066
  limit: exports_external.number().int().positive(),
46041
46067
  truncated: exports_external.boolean(),
46042
46068
  included: AttentionIncludedSchema
46069
+ });
46070
+ var AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
46071
+ resources: CommunityResourceBundleSchema
46043
46072
  }).superRefine((snapshot, ctx) => {
46073
+ const resources = snapshot.resources;
46074
+ if (snapshot.included.servers.some((summary) => !resources.servers.some((row) => row.id === summary.id)) || [...snapshot.included.channels, ...snapshot.included.dms].some((summary) => !resources.channels.some((row) => row.id === summary.id)) || snapshot.included.profiles.some((summary) => !resources.profiles.some((row) => row.id === summary.userId)) || snapshot.included.messages.some((summary) => !resources.messages.some((row) => row.id === summary.id && row.channelId === summary.channelId)) || resources.memberships.some((row) => row.userId !== resources.viewerId || row.relation !== "access" || !resources.channels.some((channel2) => channel2.id === row.channelId)) || resources.serverMemberships.some((row) => row.userId !== resources.viewerId || !resources.servers.some((server) => server.id === row.serverId)))
46075
+ ctx.addIssue({ code: "custom", message: "Attention resource closure mismatch" });
46044
46076
  const scopeIds = new Set;
46045
46077
  for (const scope of snapshot.scopes) {
46046
46078
  if (scopeIds.has(scope.scopeId)) {
@@ -46835,52 +46867,85 @@ var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
46835
46867
 
46836
46868
  // ../shared/src/db/queries/community/mention.ts
46837
46869
  var MENTION_INSERT_MAX_ROWS = maxRowsPerInsert(5);
46870
+ // ../shared/src/community-cache.ts
46871
+ var nullableString = exports_external.string().nullable();
46872
+ var optionalNullableString = nullableString.optional();
46873
+ var serverSchema = CommunityServerResourceSchema;
46874
+ var categorySchema = CommunityCategoryResourceSchema.extend({ pending: exports_external.boolean() });
46875
+ var channelLocalSchema = exports_external.strictObject({
46876
+ muted: exports_external.boolean(),
46877
+ tags: exports_external.array(exports_external.string()),
46878
+ pending: exports_external.boolean(),
46879
+ openerSeq: exports_external.number().int().nonnegative().optional(),
46880
+ openerUnread: exports_external.boolean().optional(),
46881
+ preview: exports_external.string().optional(),
46882
+ firstMessageId: exports_external.string().min(1).nullable().optional(),
46883
+ participantCount: exports_external.number().int().nonnegative().optional()
46884
+ });
46885
+ var channelSchema = CommunityChannelResourceSchema.extend(channelLocalSchema.shape);
46886
+ var serverMembershipSchema = CommunityServerMembershipResourceSchema.extend({
46887
+ id: exports_external.string().min(1),
46888
+ nickname: optionalNullableString,
46889
+ joinedAt: exports_external.string().optional(),
46890
+ viewer: exports_external.boolean()
46891
+ });
46892
+ var channelMembershipSchema = CommunityChannelMembershipResourceSchema.extend({ id: exports_external.string().min(1) });
46893
+ var readStateSchema = CommunityReadStateResourceSchema.extend({ observedRevision: exports_external.number().int().nonnegative().optional() });
46894
+ var friendshipSchema = exports_external.strictObject({
46895
+ id: exports_external.string().min(1),
46896
+ userId: exports_external.string().min(1),
46897
+ kind: exports_external.enum(["accepted", "incoming", "outgoing", "blocked"]),
46898
+ sub: exports_external.string().optional(),
46899
+ needsOwnerApproval: optionalNullableString
46900
+ });
46901
+ var readStateClockSchema = exports_external.strictObject({
46902
+ id: exports_external.literal("account"),
46903
+ revision: exports_external.number().int().nonnegative()
46904
+ });
46905
+ var folderSchema = exports_external.strictObject({
46906
+ id: exports_external.string().min(1),
46907
+ name: exports_external.string()
46908
+ });
46909
+ var serverRailSchema = exports_external.strictObject({
46910
+ id: exports_external.literal("account"),
46911
+ entries: exports_external.array(serverRailEntrySchema)
46912
+ });
46913
+ var folderItemSchema = exports_external.strictObject({
46914
+ id: exports_external.string().min(1),
46915
+ folderId: exports_external.string().min(1),
46916
+ serverId: exports_external.string().min(1),
46917
+ position: exports_external.number()
46918
+ });
46919
+ var notificationSettingSchema = exports_external.strictObject({
46920
+ id: exports_external.string().min(1),
46921
+ serverId: optionalNullableString,
46922
+ channelId: optionalNullableString,
46923
+ level: exports_external.string()
46924
+ }).superRefine((row, ctx) => {
46925
+ if (Boolean(row.serverId) === Boolean(row.channelId)) {
46926
+ ctx.addIssue({
46927
+ code: "custom",
46928
+ message: "notification setting requires exactly one target"
46929
+ });
46930
+ }
46931
+ });
46932
+
46838
46933
  // ../shared/src/community-ws-events.ts
46839
46934
  var string4 = exports_external.string();
46840
- var nullableString = string4.nullable();
46935
+ var nullableString2 = string4.nullable();
46841
46936
  var channelTypeSchema = CommunityChannelResourceSchema.shape.type.extract(["text", "forum"]);
46842
- var messageAttachmentSchema = exports_external.strictObject({
46843
- id: string4,
46844
- filename: string4,
46845
- url: string4,
46846
- thumbnailUrl: string4.optional(),
46847
- contentType: string4.optional(),
46848
- size: exports_external.number().optional(),
46849
- width: exports_external.number().nullable().optional(),
46850
- height: exports_external.number().nullable().optional()
46851
- });
46852
- var messageSchema = CommunityMessageResourceSchema.pick({
46853
- content: true,
46854
- type: true,
46855
- systemKind: true,
46856
- authorAvatar: true,
46857
- authorAvatarVersion: true,
46858
- mentionType: true,
46859
- embeds: true,
46860
- createdAt: true,
46861
- approval: true,
46862
- botCreation: true
46863
- }).extend({
46864
- id: string4,
46865
- seq: exports_external.number(),
46866
- authorId: string4,
46867
- authorName: string4,
46868
- authorAvatar: string4.optional(),
46869
- authorAvatarVersion: CommunityMessageResourceSchema.shape.authorAvatarVersion.unwrap(),
46870
- replyToId: nullableString.optional(),
46871
- replyTo: CommunityMessageResourceSchema.shape.replyTo.unwrap().extend({
46872
- id: string4,
46873
- authorId: string4.optional()
46874
- }).optional(),
46875
- attachments: exports_external.array(messageAttachmentSchema).optional(),
46876
- clientNonce: string4.optional()
46877
- });
46878
- var CommunityLegacyMessageCreateSchema = exports_external.strictObject({
46937
+ var communityMessageCreateSchema = exports_external.strictObject({
46879
46938
  type: exports_external.literal("community:message.create"),
46880
46939
  channelId: string4,
46881
46940
  serverId: string4.optional(),
46882
46941
  parentChannelId: string4.optional(),
46883
- message: messageSchema
46942
+ message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }),
46943
+ profiles: CommunityMessageResourcesSchema.shape.profiles
46944
+ }).refine((event) => event.message.channelId === event.channelId).superRefine((event, ctx) => {
46945
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [event.message], profiles: event.profiles });
46946
+ if (!graph.success)
46947
+ for (const issue3 of graph.error.issues)
46948
+ ctx.addIssue({ code: "custom", path: issue3.path, message: issue3.message });
46884
46949
  });
46885
46950
  var communityMessageUpdatedSchema = exports_external.strictObject({
46886
46951
  type: exports_external.literal("community:message.updated"),
@@ -46889,14 +46954,6 @@ var communityMessageUpdatedSchema = exports_external.strictObject({
46889
46954
  approval: FriendApprovalPayloadSchema.optional(),
46890
46955
  botCreation: BotCreationPayloadSchema.optional()
46891
46956
  }).refine((event) => event.approval !== undefined || event.botCreation !== undefined);
46892
- var communityMessageEditedSchema = exports_external.strictObject({
46893
- type: exports_external.literal("community:message.edited"),
46894
- channelId: string4,
46895
- messageId: string4,
46896
- content: string4,
46897
- parentChannelId: string4.optional(),
46898
- serverId: string4.optional()
46899
- }).refine((event) => event.parentChannelId === undefined || event.serverId !== undefined);
46900
46957
  var communityReactionAddSchema = exports_external.strictObject({
46901
46958
  type: exports_external.literal("community:reaction.add"),
46902
46959
  channelId: string4,
@@ -46938,35 +46995,19 @@ var communityTypingStopSchema = exports_external.strictObject({
46938
46995
  var communityChildChannelCreateSchema = exports_external.strictObject({
46939
46996
  type: exports_external.literal("community:channel.child_create"),
46940
46997
  parentChannelId: string4,
46941
- channel: exports_external.strictObject({
46942
- id: string4,
46943
- name: string4,
46944
- type: exports_external.literal("thread"),
46945
- creatorId: string4.optional(),
46946
- createdAt: string4
46947
- }),
46998
+ channel: CommunityChannelResourceSchema.extend({ type: exports_external.literal("thread") }),
46948
46999
  parentMessageId: string4.optional()
46949
- });
47000
+ }).refine((event) => event.channel.parentChannelId === event.parentChannelId && (event.parentMessageId === undefined || event.parentMessageId === event.channel.parentMessageId));
46950
47001
  var communityChildChannelUpdateSchema = exports_external.strictObject({
46951
47002
  type: exports_external.literal("community:channel.child_update"),
46952
47003
  parentChannelId: string4,
46953
47004
  channelId: string4,
46954
- changes: exports_external.strictObject({
46955
- name: string4.optional(),
46956
- archived: exports_external.boolean().optional(),
46957
- tags: exports_external.array(string4).nullable().optional(),
46958
- lastMessageAt: string4.optional(),
46959
- messageCount: exports_external.number().optional()
46960
- })
47005
+ changes: CommunityChannelResourceSchema.pick({ name: true, archived: true, lastMessageAt: true, messageCount: true }).partial().extend({ tags: exports_external.array(string4).nullable().optional() })
46961
47006
  });
46962
47007
  var communityServerUpdateSchema = exports_external.strictObject({
46963
47008
  type: exports_external.literal("community:server.update"),
46964
47009
  serverId: string4,
46965
- changes: exports_external.strictObject({
46966
- name: string4.optional(),
46967
- description: string4.optional(),
46968
- icon: nullableString.optional()
46969
- })
47010
+ changes: serverSchema.pick({ name: true, description: true, icon: true }).partial()
46970
47011
  });
46971
47012
  var communityServerRailChangedSchema = exports_external.strictObject({
46972
47013
  type: exports_external.literal("community:server_rail.changed")
@@ -46978,32 +47019,19 @@ var communityServerDeleteSchema = exports_external.strictObject({
46978
47019
  var communityChannelCreateSchema = exports_external.strictObject({
46979
47020
  type: exports_external.literal("community:channel.create"),
46980
47021
  serverId: string4,
46981
- channel: exports_external.strictObject({
46982
- id: string4,
46983
- name: string4,
46984
- type: channelTypeSchema,
46985
- categoryId: nullableString.optional(),
46986
- topic: string4.optional(),
46987
- position: exports_external.number(),
46988
- createdAt: string4
46989
- })
46990
- });
47022
+ channel: CommunityChannelResourceSchema.extend({ type: channelTypeSchema })
47023
+ }).refine((event) => event.channel.serverId === event.serverId);
46991
47024
  var communityChannelUpdateSchema = exports_external.strictObject({
46992
47025
  type: exports_external.literal("community:channel.update"),
46993
47026
  serverId: string4,
46994
47027
  channelId: string4,
46995
- changes: exports_external.strictObject({
46996
- name: string4.optional(),
46997
- topic: string4.optional(),
46998
- categoryId: nullableString.optional(),
46999
- type: channelTypeSchema.optional()
47000
- })
47028
+ changes: CommunityChannelResourceSchema.pick({ name: true, topic: true, categoryId: true, type: true }).partial().extend({ type: channelTypeSchema.optional() })
47001
47029
  });
47002
47030
  var communityChannelDeleteSchema = exports_external.strictObject({
47003
47031
  type: exports_external.literal("community:channel.delete"),
47004
47032
  serverId: string4,
47005
47033
  channelId: string4,
47006
- parentChannelId: nullableString.optional(),
47034
+ parentChannelId: nullableString2.optional(),
47007
47035
  parentMessageId: string4.optional()
47008
47036
  }).refine((event) => event.parentMessageId === undefined || typeof event.parentChannelId === "string" && event.parentChannelId.length > 0, { message: "parentMessageId requires parentChannelId" });
47009
47037
  var positionedIdSchema = exports_external.strictObject({ id: string4, position: exports_external.number() });
@@ -47012,18 +47040,6 @@ var communityChannelReorderSchema = exports_external.strictObject({
47012
47040
  serverId: string4,
47013
47041
  channels: exports_external.array(positionedIdSchema)
47014
47042
  });
47015
- var communityChannelMemberAddSchema = exports_external.strictObject({
47016
- type: exports_external.literal("community:channel.member_add"),
47017
- serverId: string4,
47018
- channelId: string4,
47019
- userId: string4
47020
- });
47021
- var communityChannelMemberRemoveSchema = exports_external.strictObject({
47022
- type: exports_external.literal("community:channel.member_remove"),
47023
- serverId: string4,
47024
- channelId: string4,
47025
- userId: string4
47026
- });
47027
47043
  var communityChannelMembershipChangeSchema = exports_external.strictObject({
47028
47044
  type: exports_external.literal("community:channel.membership.change"),
47029
47045
  channelId: string4,
@@ -47035,12 +47051,7 @@ var communityChannelMembershipChangeSchema = exports_external.strictObject({
47035
47051
  var communityCategoryCreateSchema = exports_external.strictObject({
47036
47052
  type: exports_external.literal("community:category.create"),
47037
47053
  serverId: string4,
47038
- category: exports_external.strictObject({
47039
- id: string4,
47040
- name: string4,
47041
- position: exports_external.number(),
47042
- private: exports_external.boolean()
47043
- })
47054
+ category: CommunityCategoryResourceSchema
47044
47055
  });
47045
47056
  var communityCategoryUpdateSchema = exports_external.strictObject({
47046
47057
  type: exports_external.literal("community:category.update"),
@@ -47065,13 +47076,9 @@ var communityCategoryReorderSchema = exports_external.strictObject({
47065
47076
  var communityMemberJoinSchema = exports_external.strictObject({
47066
47077
  type: exports_external.literal("community:member.join"),
47067
47078
  serverId: string4,
47068
- member: exports_external.strictObject({
47079
+ member: CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).extend({
47069
47080
  id: string4,
47070
47081
  userId: string4,
47071
- name: string4,
47072
- discriminator: string4,
47073
- avatar: string4.optional(),
47074
- avatarVersion: exports_external.number().int().nonnegative(),
47075
47082
  role: string4,
47076
47083
  joinedAt: string4
47077
47084
  })
@@ -47088,7 +47095,7 @@ var communityMemberUpdateSchema = exports_external.strictObject({
47088
47095
  userId: string4.optional(),
47089
47096
  changes: exports_external.strictObject({
47090
47097
  role: string4.optional(),
47091
- nickname: nullableString.optional()
47098
+ nickname: nullableString2.optional()
47092
47099
  })
47093
47100
  });
47094
47101
  var communityFriendRequestSchema = exports_external.strictObject({
@@ -47119,7 +47126,7 @@ var communityFriendBlockSchema = exports_external.strictObject({
47119
47126
  userId: string4,
47120
47127
  blockedByViewer: exports_external.boolean().optional()
47121
47128
  });
47122
- var communityInviteCreateSchema = exports_external.strictObject({
47129
+ var CommunityInviteCreateSchema = exports_external.strictObject({
47123
47130
  type: exports_external.literal("community:invite.create"),
47124
47131
  serverId: string4,
47125
47132
  invite: exports_external.strictObject({
@@ -47127,7 +47134,7 @@ var communityInviteCreateSchema = exports_external.strictObject({
47127
47134
  token: string4,
47128
47135
  maxUses: exports_external.number().nullable().optional(),
47129
47136
  uses: exports_external.number().nullable().optional(),
47130
- expiresAt: nullableString.optional(),
47137
+ expiresAt: nullableString2.optional(),
47131
47138
  createdAt: string4
47132
47139
  })
47133
47140
  });
@@ -47172,24 +47179,17 @@ var communityPresenceUpdateSchema = exports_external.strictObject({
47172
47179
  var communityStatusUpdateSchema = exports_external.strictObject({
47173
47180
  type: exports_external.literal("community:status.update"),
47174
47181
  userId: string4,
47175
- statusEmoji: nullableString,
47176
- statusText: nullableString
47182
+ statusEmoji: nullableString2,
47183
+ statusText: nullableString2
47177
47184
  });
47178
- var communityIdentityUpdateSchema = exports_external.strictObject({
47185
+ var communityIdentityUpdateSchema = CommunityResourceProfileSchema.pick({ avatar: true, avatarVersion: true }).extend({
47179
47186
  type: exports_external.literal("community:identity.update"),
47180
47187
  userId: string4,
47181
- avatar: string4,
47182
- avatarVersion: exports_external.number().int().positive()
47188
+ avatarVersion: CommunityResourceProfileSchema.shape.avatarVersion.refine((version3) => version3 > 0)
47183
47189
  });
47184
- var communityProfileUpdateSchema = exports_external.strictObject({
47190
+ var communityProfileUpdateSchema = CommunityResourceProfileSchema.pick({ name: true, discriminator: true, aboutMe: true, bannerColor: true, kind: true, ownerUserId: true }).required().extend({
47185
47191
  type: exports_external.literal("community:profile.update"),
47186
- userId: string4,
47187
- name: string4,
47188
- discriminator: string4,
47189
- aboutMe: string4,
47190
- bannerColor: nullableString,
47191
- kind: exports_external.enum(["human", "bot"]),
47192
- ownerUserId: nullableString
47192
+ userId: string4
47193
47193
  });
47194
47194
  var communityMachineCreatedSchema = exports_external.strictObject({
47195
47195
  type: exports_external.literal("community:machine.created"),
@@ -47216,8 +47216,8 @@ var communityBotAuditEventSchema = exports_external.strictObject({
47216
47216
  id: string4,
47217
47217
  kind: exports_external.enum(["cli_invocation", "tool_call", "thinking", "text", "turn_interrupt", "wake_trigger", "session_reset", "nap", "model_changed", "provider_changed", "error"]),
47218
47218
  payload: exports_external.unknown(),
47219
- sessionId: nullableString.optional(),
47220
- launchId: nullableString.optional(),
47219
+ sessionId: nullableString2.optional(),
47220
+ launchId: nullableString2.optional(),
47221
47221
  createdAt: string4
47222
47222
  }).refine((event) => Object.prototype.hasOwnProperty.call(event, "payload"));
47223
47223
  var communityRuntimeModelsSchema = exports_external.strictObject({
@@ -47237,7 +47237,6 @@ var communityBotPiiSchema = exports_external.strictObject({
47237
47237
  var commonCommunityEventSchemas = [
47238
47238
  communityBotPiiSchema,
47239
47239
  communityMessageUpdatedSchema,
47240
- communityMessageEditedSchema,
47241
47240
  communityReactionAddSchema,
47242
47241
  communityReactionRemoveSchema,
47243
47242
  communityPinAddSchema,
@@ -47249,8 +47248,6 @@ var commonCommunityEventSchemas = [
47249
47248
  communityServerDeleteSchema,
47250
47249
  communityChannelDeleteSchema,
47251
47250
  communityChannelReorderSchema,
47252
- communityChannelMemberAddSchema,
47253
- communityChannelMemberRemoveSchema,
47254
47251
  communityChannelMembershipChangeSchema,
47255
47252
  communityCategoryCreateSchema,
47256
47253
  communityCategoryUpdateSchema,
@@ -47264,7 +47261,7 @@ var commonCommunityEventSchemas = [
47264
47261
  communityFriendRejectSchema,
47265
47262
  communityFriendRemoveSchema,
47266
47263
  communityFriendBlockSchema,
47267
- communityInviteCreateSchema,
47264
+ CommunityInviteCreateSchema,
47268
47265
  communityMentionCreateSchema,
47269
47266
  communityUnreadBumpSchema,
47270
47267
  communityReadStateAdvancedSchema,
@@ -47278,9 +47275,9 @@ var commonCommunityEventSchemas = [
47278
47275
  communityMachineRemovedSchema,
47279
47276
  communityBotAuditEventSchema
47280
47277
  ];
47281
- var CommunityWsEventDiscriminatedSchema = exports_external.discriminatedUnion("type", [
47278
+ var CommunityWsEventSchema = exports_external.discriminatedUnion("type", [
47282
47279
  ...commonCommunityEventSchemas,
47283
- CommunityLegacyMessageCreateSchema,
47280
+ communityMessageCreateSchema,
47284
47281
  communityChildChannelCreateSchema,
47285
47282
  communityChannelCreateSchema,
47286
47283
  communityChildChannelUpdateSchema,
@@ -47288,22 +47285,9 @@ var CommunityWsEventDiscriminatedSchema = exports_external.discriminatedUnion("t
47288
47285
  communityIdentityUpdateSchema,
47289
47286
  communityProfileUpdateSchema
47290
47287
  ]);
47291
- var CommunityResourceWsEventDiscriminatedSchema = exports_external.discriminatedUnion("type", [
47292
- ...commonCommunityEventSchemas,
47293
- CommunityLegacyMessageCreateSchema.extend({ message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }) }).refine((event) => event.message.channelId === event.channelId),
47294
- communityChildChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: exports_external.literal("thread") }) }).refine((event) => event.channel.parentChannelId === event.parentChannelId && (event.parentMessageId === undefined || event.parentMessageId === event.channel.parentMessageId)),
47295
- communityChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: channelTypeSchema }) }).refine((event) => event.channel.serverId === event.serverId),
47296
- communityChildChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, archived: true, lastMessageAt: true, messageCount: true }).partial().extend({ tags: exports_external.array(string4).nullable().optional() }) }),
47297
- communityChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, topic: true, categoryId: true, type: true }).partial().extend({ type: channelTypeSchema.optional() }) }),
47298
- communityIdentityUpdateSchema.extend({ avatar: CommunityResourceProfileSchema.shape.avatar, avatarVersion: CommunityResourceProfileSchema.shape.avatarVersion.refine((version3) => version3 > 0) }),
47299
- CommunityResourceProfileSchema.pick({ name: true, discriminator: true, aboutMe: true, bannerColor: true, kind: true, ownerUserId: true }).required().extend({ type: exports_external.literal("community:profile.update"), userId: string4 })
47300
- ]);
47301
- var CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema.transform((event) => event);
47302
- var CommunityResourceWsEventSchema = CommunityResourceWsEventDiscriminatedSchema.transform((event) => event);
47303
47288
  var WS_EVENTS = {
47304
47289
  MESSAGE_CREATE: "community:message.create",
47305
47290
  MESSAGE_UPDATED: "community:message.updated",
47306
- MESSAGE_EDITED: "community:message.edited",
47307
47291
  REACTION_ADD: "community:reaction.add",
47308
47292
  REACTION_REMOVE: "community:reaction.remove",
47309
47293
  PIN_ADD: "community:pin.add",
@@ -47319,8 +47303,6 @@ var WS_EVENTS = {
47319
47303
  CHANNEL_UPDATE: "community:channel.update",
47320
47304
  CHANNEL_DELETE: "community:channel.delete",
47321
47305
  CHANNEL_REORDER: "community:channel.reorder",
47322
- CHANNEL_MEMBER_ADD: "community:channel.member_add",
47323
- CHANNEL_MEMBER_REMOVE: "community:channel.member_remove",
47324
47306
  CHANNEL_MEMBERSHIP_CHANGE: "community:channel.membership.change",
47325
47307
  CATEGORY_CREATE: "community:category.create",
47326
47308
  CATEGORY_UPDATE: "community:category.update",
@@ -47380,20 +47362,14 @@ var MESSAGE_DELIVERY_MAX_USERS = 1000;
47380
47362
  var MESSAGE_DELIVERY_MAX_EVENTS_PER_USER = 5;
47381
47363
  var target = exports_external.string().refine(isValidCommunityUserTarget);
47382
47364
  var targetList = exports_external.array(target).max(MESSAGE_DELIVERY_MAX_USERS);
47383
- var memberAddedSchema = exports_external.strictObject({
47384
- userId: target,
47385
- serverId: exports_external.string().min(1),
47386
- channelId: exports_external.string().min(1)
47387
- });
47388
47365
  var batchShape = exports_external.strictObject({
47389
- communityContract: exports_external.literal(3).optional(),
47366
+ communityContract: exports_external.literal(BUSINESS_SCHEMA_VERSION),
47390
47367
  messageId: exports_external.string().min(1),
47391
47368
  messageEvent: exports_external.unknown(),
47392
47369
  contentUserIds: targetList,
47393
47370
  unreadPlainUserIds: targetList,
47394
47371
  unreadMentionUserIds: targetList,
47395
47372
  mentionUserIds: targetList,
47396
- memberAdded: memberAddedSchema.optional(),
47397
47373
  joinedParticipantUserIds: targetList.optional(),
47398
47374
  rosterRefreshUserId: target.optional(),
47399
47375
  parentProjection: exports_external.unknown().optional(),
@@ -47521,12 +47497,36 @@ var communityBotCreationRequest = sqliteTable("community_bot_creation_request",
47521
47497
  resolvedAt: text("resolved_at")
47522
47498
  }, (t) => [index("idx_bot_creation_requester").on(t.requesterId, t.createdAt), index("idx_bot_creation_owner").on(t.ownerId, t.createdAt)]);
47523
47499
 
47500
+ // ../shared/src/db/automation-schema.ts
47501
+ var exports_automation_schema = {};
47502
+ __export(exports_automation_schema, {
47503
+ automationAccessPermission: () => automationAccessPermission,
47504
+ automationAccessCode: () => automationAccessCode
47505
+ });
47506
+ var automationAccessCode = sqliteTable("automation_access_code", {
47507
+ id: text("id").primaryKey(),
47508
+ ownerId: text("owner_id").notNull().references(() => user.id, { onDelete: "cascade" }),
47509
+ name: text("name").notNull(),
47510
+ secretHash: text("secret_hash").notNull().unique(),
47511
+ expiresAt: text("expires_at"),
47512
+ createdAt: text("created_at").notNull()
47513
+ }, (table) => [index("idx_automation_code_owner").on(table.ownerId)]);
47514
+ var automationAccessPermission = sqliteTable("automation_access_permission", {
47515
+ codeId: text("code_id").notNull().references(() => automationAccessCode.id, { onDelete: "cascade" }),
47516
+ permission: text("permission").$type().notNull(),
47517
+ limit: integer2("request_limit").notNull(),
47518
+ period: text("period", { enum: ["hour", "day"] }).notNull()
47519
+ }, (table) => [primaryKey({ columns: [table.codeId, table.permission] })]);
47520
+
47524
47521
  // ../shared/src/db/index.ts
47525
- var allSchema = { ...exports_schema, ...exports_community_schema, ...exports_community_machine_schema, ...exports_product_plan_schema, ...exports_billing_schema, ...exports_community_funnel_analytics_schema, ...exports_bot_creation_schema };
47522
+ var allSchema = { ...exports_schema, ...exports_community_schema, ...exports_community_machine_schema, ...exports_product_plan_schema, ...exports_billing_schema, ...exports_community_funnel_analytics_schema, ...exports_bot_creation_schema, ...exports_automation_schema };
47526
47523
  // ../shared/src/db/queries/native-oauth.ts
47527
47524
  var ATTEMPT_TTL_MS = 10 * 60 * 1000;
47528
47525
  var HANDOFF_TTL_MS = 2 * 60 * 1000;
47529
47526
  var RETENTION_MS = 24 * 60 * 60 * 1000;
47527
+
47528
+ // ../shared/src/db/queries/automation.ts
47529
+ var publicFields = { id: automationAccessCode.id, name: automationAccessCode.name, createdAt: automationAccessCode.createdAt, expiresAt: automationAccessCode.expiresAt };
47530
47530
  // ../shared/src/db/queries/task.ts
47531
47531
  var DEFAULT_STALE_SECONDS = Number(process.env.ALOOK_STALE_DISPATCH_TIMEOUT_S) || 20;
47532
47532
  var DEFAULT_STALE_RUNNING_SECONDS = Number(process.env.ALOOK_STALE_RUNNING_TIMEOUT_S) || 3600;
@@ -47690,11 +47690,204 @@ var channelReorderRequestSchema = exports_external.strictObject({
47690
47690
  channelIds: exports_external.array(exports_external.string().min(1)).min(1).refine((ids) => new Set(ids).size === ids.length, "channelIds must be unique"),
47691
47691
  move: exports_external.strictObject({ channelId: exports_external.string().min(1), categoryId: exports_external.string().min(1).nullable() }).optional()
47692
47692
  }).refine((request) => !request.move || request.channelIds.includes(request.move.channelId), "moved channel must be included in channelIds");
47693
+ // ../shared/src/task-payload-cache.ts
47694
+ var TaskEmailAddressCacheSchema = exports_external.array(exports_external.strictObject({
47695
+ workspaceId: exports_external.string().min(1),
47696
+ agentId: exports_external.string().min(1),
47697
+ emailAddress: exports_external.string()
47698
+ }));
47699
+ var TaskMemberInstructionCacheSchema = exports_external.strictObject({
47700
+ workspaceId: exports_external.string().min(1),
47701
+ userId: exports_external.string().min(1),
47702
+ globalInstruction: exports_external.string()
47703
+ }).nullable();
47704
+ var TaskUserIdentityCacheSchema = CommunityResourceProfileSchema.pick({ id: true, name: true }).extend({ email: exports_external.string() }).nullable();
47705
+ // ../shared/src/community-forum-sidebar.ts
47706
+ var timestamp = exports_external.string().refine((value) => Number.isFinite(Date.parse(value)));
47707
+ var CommunityForumSidebarChannelSummarySchema = CommunityChannelResourceSchema.pick({
47708
+ id: true,
47709
+ name: true,
47710
+ serverId: true,
47711
+ parentChannelId: true,
47712
+ parentMessageId: true
47713
+ }).extend({
47714
+ serverId: CommunityChannelResourceSchema.shape.serverId.unwrap(),
47715
+ parentChannelId: CommunityChannelResourceSchema.shape.parentChannelId.unwrap(),
47716
+ parentMessageId: CommunityChannelResourceSchema.shape.parentMessageId.unwrap(),
47717
+ activityAt: timestamp,
47718
+ expiresAt: timestamp,
47719
+ unread: exports_external.boolean()
47720
+ });
47721
+ var CommunityForumSidebarEnvelopeSchema = exports_external.strictObject({
47722
+ schemaVersion: exports_external.literal(BUSINESS_SCHEMA_VERSION),
47723
+ serverId: exports_external.string().min(1),
47724
+ channels: exports_external.array(CommunityForumSidebarChannelSummarySchema),
47725
+ canonicalChannels: exports_external.array(CommunityForumSidebarChannelSummarySchema),
47726
+ retainedChannel: CommunityForumSidebarChannelSummarySchema.nullable(),
47727
+ retainedDisposition: exports_external.enum(["eligible", "opener-archived", "genuine-negative"]).nullable(),
47728
+ resources: CommunityResourceBundleSchema,
47729
+ serverNow: timestamp
47730
+ }).superRefine((data, ctx) => {
47731
+ const selected = [...data.canonicalChannels, ...data.retainedChannel ? [data.retainedChannel] : []];
47732
+ if (data.resources.servers.some((row) => row.id !== data.serverId) || data.resources.channels.some((row) => row.serverId !== data.serverId) || new Set(data.channels.map((row) => row.id)).size !== data.channels.length || new Set(data.canonicalChannels.map((row) => row.id)).size !== data.canonicalChannels.length || data.canonicalChannels.some((row) => data.canonicalChannels.filter((other) => other.parentChannelId === row.parentChannelId).length > 5) || data.channels.some((row) => !selected.some((other) => other.id === row.id)) || data.retainedDisposition === "eligible" !== (data.retainedChannel !== null) || selected.some((row) => !data.resources.channels.some((channel2) => channel2.id === row.id && channel2.type === "thread" && channel2.serverId === row.serverId && channel2.parentChannelId === row.parentChannelId && channel2.parentMessageId === row.parentMessageId) || !data.resources.messages.some((message2) => message2.id === row.parentMessageId && message2.channelId === row.parentChannelId) || !data.resources.memberships.some((member2) => member2.channelId === row.id && member2.userId === data.resources.viewerId && member2.relation === "notify"))) {
47733
+ ctx.addIssue({ code: "custom", message: "Forum sidebar resource closure mismatch" });
47734
+ }
47735
+ });
47736
+ // ../shared/src/community-machine-resources.ts
47737
+ var CommunityMachineIdentityCacheSchema = CommunityMachineSummarySchema.pick({
47738
+ id: true,
47739
+ hostname: true,
47740
+ displayName: true,
47741
+ platform: true,
47742
+ arch: true,
47743
+ osRelease: true,
47744
+ daemonVersion: true,
47745
+ createdAt: true,
47746
+ updatedAt: true
47747
+ });
47748
+ var CommunityMachineListReadSchema = exports_external.strictObject({ machines: exports_external.array(CommunityMachineSummarySchema), complete: exports_external.literal(true) });
47749
+ // ../shared/src/community-friends.ts
47750
+ var CommunityAcceptedFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true, sub: true });
47751
+ var CommunityBlockedFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true });
47752
+ var CommunityPendingFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true, needsOwnerApproval: true }).extend({
47753
+ kind: friendshipSchema.shape.kind.extract(["incoming", "outgoing"])
47754
+ });
47755
+ var envelope2 = { contractVersion: exports_external.literal(BUSINESS_SCHEMA_VERSION) };
47756
+ var fresh = { ...envelope2, resources: CommunityResourceBundleSchema, stale: exports_external.literal(false).optional() };
47757
+ var stale = { ...envelope2, stale: exports_external.literal(true) };
47758
+ function checkProfiles(rows, resources, ctx) {
47759
+ if (rows.some((row) => !resources.profiles.some((profile2) => profile2.id === row.userId))) {
47760
+ ctx.addIssue({ code: "custom", message: "Friend profile resource missing" });
47761
+ }
47762
+ }
47763
+ var CommunityAcceptedFriendsReadSchema = exports_external.union([
47764
+ exports_external.strictObject({ ...fresh, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
47765
+ exports_external.strictObject({ ...stale, friends: exports_external.array(CommunityAcceptedFriendDescriptorSchema).length(0) })
47766
+ ]);
47767
+ var CommunityBlockedFriendsReadSchema = exports_external.union([
47768
+ exports_external.strictObject({ ...fresh, blocked: exports_external.array(CommunityBlockedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.blocked, value.resources, ctx)),
47769
+ exports_external.strictObject({ ...stale, blocked: exports_external.array(CommunityBlockedFriendDescriptorSchema).length(0) })
47770
+ ]);
47771
+ var CommunityPendingFriendsReadSchema = exports_external.union([
47772
+ exports_external.strictObject({ ...fresh, pending: exports_external.array(CommunityPendingFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.pending, value.resources, ctx)),
47773
+ exports_external.strictObject({ ...stale, pending: exports_external.array(CommunityPendingFriendDescriptorSchema).length(0) })
47774
+ ]);
47775
+ // ../shared/src/community-invites.ts
47776
+ var CommunityInviteListItemSchema = CommunityInviteCreateSchema.shape.invite.required({ maxUses: true, uses: true, expiresAt: true }).extend({
47777
+ uses: CommunityInviteCreateSchema.shape.invite.shape.uses.unwrap().unwrap().int().nonnegative(),
47778
+ creatorId: CommunityResourceProfileSchema.shape.id.nullable()
47779
+ });
47780
+ var CommunityInvitesReadSchema = exports_external.strictObject({
47781
+ contractVersion: exports_external.literal(BUSINESS_SCHEMA_VERSION),
47782
+ serverId: CommunityServerResourceSchema.shape.id,
47783
+ invites: exports_external.array(CommunityInviteListItemSchema),
47784
+ resources: CommunityResourceBundleSchema
47785
+ }).superRefine((value, ctx) => {
47786
+ if (new Set(value.invites.map((row) => row.id)).size !== value.invites.length)
47787
+ ctx.addIssue({ code: "custom", message: "Duplicate invite descriptor" });
47788
+ if (!value.resources.servers.some((row) => row.id === value.serverId) || value.resources.servers.some((row) => row.id !== value.serverId))
47789
+ ctx.addIssue({ code: "custom", message: "Invite server resource mismatch" });
47790
+ if (value.invites.some((row) => row.creatorId !== null && !value.resources.profiles.some((profile2) => profile2.id === row.creatorId)))
47791
+ ctx.addIssue({ code: "custom", message: "Invite creator profile resource missing" });
47792
+ });
47793
+ // ../shared/src/community-dms.ts
47794
+ var CommunityDmReadItemSchema = exports_external.strictObject({
47795
+ id: CommunityChannelResourceSchema.shape.id,
47796
+ userId: CommunityResourceProfileSchema.shape.id,
47797
+ channel: CommunityChannelResourceSchema,
47798
+ profile: CommunityResourceProfileSchema,
47799
+ memberships: exports_external.array(CommunityMemberRelationSchema).length(2),
47800
+ preview: exports_external.string(),
47801
+ activityAt: CommunityChannelResourceSchema.shape.createdAt,
47802
+ unread: exports_external.boolean(),
47803
+ lastUnreadSeq: CommunityMessageResourceSchema.shape.seq.optional()
47804
+ }).superRefine((dm, ctx) => {
47805
+ const users = new Set(dm.memberships.map((row) => row.userId));
47806
+ if (dm.channel.id !== dm.id || dm.channel.type !== "dm" || dm.channel.serverId !== null || dm.channel.categoryId !== null || dm.channel.parentChannelId !== null || dm.channel.parentMessageId !== null || dm.profile.id !== dm.userId || users.size !== 2 || !users.has(dm.userId) || dm.memberships.some((row) => row.channelId !== dm.id || row.relation !== "access") || dm.unread !== (dm.lastUnreadSeq !== undefined)) {
47807
+ ctx.addIssue({ code: "custom", message: "DM resource scope mismatch" });
47808
+ }
47809
+ });
47810
+ var CommunityDmsReadSchema = exports_external.strictObject({ conversations: exports_external.array(CommunityDmReadItemSchema) }).superRefine((value, ctx) => {
47811
+ if (new Set(value.conversations.map((row) => row.id)).size !== value.conversations.length) {
47812
+ ctx.addIssue({ code: "custom", message: "Duplicate DM resource identity" });
47813
+ }
47814
+ });
47815
+ // ../shared/src/community-profile-reads.ts
47816
+ var CommunitySelfProfileReadSchema = CommunityResourceProfileSchema.pick({
47817
+ id: true,
47818
+ name: true,
47819
+ discriminator: true,
47820
+ avatar: true,
47821
+ avatarVersion: true,
47822
+ aboutMe: true,
47823
+ bannerColor: true,
47824
+ statusEmoji: true,
47825
+ statusText: true
47826
+ }).required();
47827
+ var card = CommunitySelfProfileReadSchema.omit({ avatar: true }).extend({
47828
+ image: CommunityResourceProfileSchema.shape.avatar,
47829
+ mutualServers: CommunityResourceProfileSchema.shape.mutualServers.unwrap()
47830
+ });
47831
+ var CommunityUserCardReadSchema = exports_external.discriminatedUnion("kind", [
47832
+ card.extend({ kind: exports_external.literal("human") }),
47833
+ card.extend({ kind: exports_external.literal("bot"), ownerProfile: exports_external.strictObject({ id: CommunityResourceProfileSchema.shape.id, handle: CommunityResourceProfileSchema.shape.ownerHandle.unwrap().unwrap() }), ownedByViewer: CommunityResourceProfileSchema.shape.ownedByViewer.unwrap() })
47834
+ ]);
47835
+ var CommunityServerMemberReadSchema = CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true, statusEmoji: true, statusText: true }).required().extend({
47836
+ id: CommunityServerMembershipResourceSchema.shape.memberId,
47837
+ userId: CommunityResourceProfileSchema.shape.id,
47838
+ role: exports_external.enum(ROLES),
47839
+ status: exports_external.enum(["online", "offline"]),
47840
+ sub: exports_external.string(),
47841
+ isBot: exports_external.literal(true).optional(),
47842
+ ownerUserId: CommunityResourceProfileSchema.shape.id.optional()
47843
+ }).superRefine((row, ctx) => {
47844
+ if (row.isBot === true !== (row.ownerUserId !== undefined))
47845
+ ctx.addIssue({ code: "custom", message: "Member owner metadata mismatch" });
47846
+ });
47847
+ var page = exports_external.strictObject({
47848
+ viewerId: CommunityResourceProfileSchema.shape.id,
47849
+ serverId: CommunityServerMembershipResourceSchema.shape.serverId,
47850
+ members: exports_external.array(CommunityServerMemberReadSchema),
47851
+ hasMore: exports_external.boolean(),
47852
+ cursor: exports_external.string().min(1).optional(),
47853
+ limit: exports_external.number().int().positive()
47854
+ });
47855
+ var validatePage = (value, ctx) => {
47856
+ if (value.hasMore && !value.cursor || new Set(value.members.map((row) => row.id)).size !== value.members.length || new Set(value.members.map((row) => row.userId)).size !== value.members.length || value.members.length > value.limit || value.members.some((row) => row.ownerUserId !== undefined && row.ownerUserId !== value.viewerId))
47857
+ ctx.addIssue({ code: "custom", message: "Member page scope mismatch" });
47858
+ };
47859
+ var CommunityServerMembersReadSchema = page.extend({ total: exports_external.number().int().nonnegative() }).superRefine(validatePage);
47860
+ var CommunityServerMemberSearchReadSchema = page.superRefine(validatePage);
47861
+ var CommunityUserSearchReadSchema = exports_external.strictObject({ users: exports_external.array(CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatarVersion: true }).extend({ image: CommunityResourceProfileSchema.shape.avatar })) });
47862
+ var CommunityReactionActorProfileSchema = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatar: true, avatarVersion: true });
47863
+ var CommunityReactionDetailsReadSchema = exports_external.strictObject({
47864
+ messageId: CommunityResourceProfileSchema.shape.id,
47865
+ scope: exports_external.discriminatedUnion("kind", [
47866
+ exports_external.strictObject({ kind: exports_external.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
47867
+ exports_external.strictObject({ kind: exports_external.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id })
47868
+ ]),
47869
+ actors: exports_external.array(exports_external.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() }))
47870
+ }).superRefine((value, ctx) => {
47871
+ if (new Set(value.actors.map((row) => row.userId)).size !== value.actors.length || value.actors.some((row) => row.profile && row.profile.id !== row.userId))
47872
+ ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" });
47873
+ });
47874
+ var CommunityBotProfileSummarySchema = CommunityResourceProfileSchema.pick({ id: true, name: true, avatarVersion: true }).extend({
47875
+ image: CommunityResourceProfileSchema.shape.avatar,
47876
+ discriminator: CommunityResourceProfileSchema.shape.discriminator.optional(),
47877
+ description: CommunityResourceProfileSchema.shape.aboutMe,
47878
+ presence: exports_external.enum(["online", "offline"]).optional()
47879
+ }).strip();
47880
+ var CommunityBotsProfileReadSchema = exports_external.object({
47881
+ bots: exports_external.array(CommunityBotProfileSummarySchema.required({ discriminator: true, description: true, presence: true }).extend({ ownerUserId: CommunityResourceProfileSchema.shape.id }))
47882
+ }).strip().superRefine((value, ctx) => {
47883
+ if (new Set(value.bots.map((row) => row.id)).size !== value.bots.length)
47884
+ ctx.addIssue({ code: "custom", message: "Duplicate bot catalogue identity" });
47885
+ });
47693
47886
  // src/cli/platform.ts
47694
47887
  var failure2 = (message2, code, details) => Object.assign(new Error(message2), { code, platformDetails: details });
47695
47888
  function registerPlatformCommands(program, getApi, output2) {
47696
47889
  const platform = program.command("platform").description("owner-scoped platform capabilities").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
47697
- const machine2 = platform.command("machine").description("read machines, backends, models and model-specific effort").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).option("--list", "list your owner's machines").option("--backends", "show backends on --id").option("--models", "show models and effort for --id and --backend").option("--id <id>", "owner machine ID").option("--backend <id>", "backend ID from the selected machine").option("--model <id>", "show effort for this full model ID").option("--refresh", "ask the target to refresh its reported models");
47890
+ const machine2 = platform.command("machine").description("read machines, backends, models and model-specific effort").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).option("--list", "list your owner's machines").option("--backends", "show backends on --id").option("--models", "show models and effort for --id and --backend").option("--id <id>", "owner machine ID").option("--backend <id>", "backend ID from the selected machine").option("--model <id>", "show effort for this full model ID").option("--refresh", "bypass the five-minute model cache and wait for fresh models");
47698
47891
  machine2.action(async () => {
47699
47892
  const opts = machine2.opts();
47700
47893
  const actions = [opts.list, opts.backends, opts.models].filter(Boolean).length;
@@ -47715,7 +47908,7 @@ function registerPlatformCommands(program, getApi, output2) {
47715
47908
  const api2 = getApi();
47716
47909
  if (!api2.platformMachine)
47717
47910
  throw failure2("Platform machine commands are unavailable", "UPGRADE_REQUIRED");
47718
- const result = await api2.platformMachine(opts.list ? { action: "list" } : opts.backends ? { action: "backends", machineId: opts.id } : { action: "models", machineId: opts.id, backendId: opts.backend, ...opts.model ? { model: opts.model } : {}, refresh: opts.refresh === true, ...opts.refresh ? { requestId: randomUUID() } : {} });
47911
+ const result = await api2.platformMachine(opts.list ? { action: "list" } : opts.backends ? { action: "backends", machineId: opts.id } : { action: "models", machineId: opts.id, backendId: opts.backend, ...opts.model ? { model: opts.model } : {}, refresh: opts.refresh === true, requestId: randomUUID() });
47719
47912
  output2({ success: result });
47720
47913
  });
47721
47914
  const bot = platform.command("bot").description("read bots or request owner-approved creation").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).option("--list", "list your owner's bot summaries").option("--create <bot-json>", "request one bot; repeat for one gallery request", (value, previous) => [...previous, value], []);
@@ -47758,6 +47951,239 @@ function registerPlatformCommands(program, getApi, output2) {
47758
47951
  });
47759
47952
  }
47760
47953
 
47954
+ // src/cli/use.ts
47955
+ import { randomUUID as randomUUID2 } from "node:crypto";
47956
+ import { readFile, stat } from "node:fs/promises";
47957
+ var BotInput = exports_external.strictObject({
47958
+ ...CommunityBotCreateRequestSchema.omit({ runtime: true, image: true }).shape,
47959
+ backendId: exports_external.string().min(1).max(64)
47960
+ });
47961
+ var ServerInput = exports_external.strictObject({ name: exports_external.string().trim().min(1).max(MAX_SERVER_NAME_LENGTH), description: exports_external.string().max(MAX_SERVER_DESCRIPTION_LENGTH).optional() });
47962
+ var BackendList = exports_external.array(exports_external.object({
47963
+ id: exports_external.string().min(1),
47964
+ version: exports_external.string().optional(),
47965
+ health: exports_external.enum(["healthy", "unhealthy"]),
47966
+ modelRequired: exports_external.boolean()
47967
+ }));
47968
+ var ServerChannels = exports_external.array(exports_external.object({ name: exports_external.string().min(1), type: exports_external.enum(["text", "forum"]), ref: exports_external.string().min(1) }));
47969
+ var MemberList = exports_external.object({
47970
+ server: exports_external.string().min(1),
47971
+ url: exports_external.url(),
47972
+ members: exports_external.array(exports_external.object({ handle: exports_external.string().min(1), role: exports_external.string().min(1) })),
47973
+ hasMore: exports_external.boolean(),
47974
+ cursor: exports_external.string().min(1).optional()
47975
+ }).refine((value) => !value.hasMore || Boolean(value.cursor));
47976
+ var ModelList = exports_external.object({
47977
+ machineId: exports_external.string().min(1),
47978
+ backendId: exports_external.string().min(1),
47979
+ source: exports_external.enum(["fresh_discovery", "cached_report"]),
47980
+ requestId: exports_external.string().min(1),
47981
+ readAt: exports_external.string(),
47982
+ observedAt: exports_external.iso.datetime(),
47983
+ modelRequired: exports_external.boolean(),
47984
+ defaultModelId: exports_external.string().nullable(),
47985
+ models: exports_external.array(exports_external.object({
47986
+ id: exports_external.string().min(1),
47987
+ displayName: exports_external.string().optional(),
47988
+ reasoningEfforts: exports_external.array(exports_external.object({ value: exports_external.string().min(1), description: exports_external.string().optional() })),
47989
+ defaultReasoningEffort: exports_external.string().nullable()
47990
+ })).nullable()
47991
+ });
47992
+ async function readAccessCode(file2) {
47993
+ let secret = process.env.ALOOK_ACCESS_CODE?.trim();
47994
+ if (file2) {
47995
+ if ((await stat(file2)).size > 1024)
47996
+ throw new Error("Access code file is too large");
47997
+ secret = (await readFile(file2, "utf8")).trim();
47998
+ }
47999
+ if (!secret || !/^aac_[a-f0-9]{64}$/.test(secret))
48000
+ throw new Error("Set ALOOK_ACCESS_CODE or use --access-code-file with an Automation access code");
48001
+ return secret;
48002
+ }
48003
+ function serverOrigin(value) {
48004
+ const url2 = new URL(value);
48005
+ if (url2.username || url2.password || url2.search || url2.hash || url2.pathname !== "/")
48006
+ throw new Error("--server-url must be a server origin");
48007
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname);
48008
+ if (url2.protocol !== "https:" && !(url2.protocol === "http:" && local))
48009
+ throw new Error("--server-url requires HTTPS, except for local development");
48010
+ return url2.origin;
48011
+ }
48012
+ function parseInput(value, schema) {
48013
+ if (Buffer.byteLength(value, "utf8") > 131072)
48014
+ throw new Error("Automation request is too large");
48015
+ let input2;
48016
+ try {
48017
+ input2 = JSON.parse(value);
48018
+ } catch {
48019
+ throw new Error("Invalid request JSON");
48020
+ }
48021
+ const parsed = schema.safeParse(input2);
48022
+ if (!parsed.success)
48023
+ throw new Error(parsed.error.issues.map((issue3) => `${issue3.path.join(".")}: ${issue3.message}`).join("; "));
48024
+ return parsed.data;
48025
+ }
48026
+ var InviteInput = exports_external.strictObject({
48027
+ server: exports_external.string().max(128).refine((value) => Boolean(parseNameAndTag(value)), "Use a full server handle"),
48028
+ friend: exports_external.string().max(128).refine((value) => Boolean(parseNameAndTag(value)), "Use a full friend handle")
48029
+ });
48030
+ function registerUseCommands(program, output2) {
48031
+ const use = program.command("use").description("user Automation access: read lists, create resources, invite friends and send messages; no daemon connection required").option("--access-code-file <path>", "read the code from a file instead of ALOOK_ACCESS_CODE").option("--server-url <url>", "server origin (or ALOOK_SERVER_URL; defaults to production)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
48032
+ const request = async (path, body, timeoutMs = 30000) => {
48033
+ const options = use.opts();
48034
+ const origin = serverOrigin(options.serverUrl || process.env.ALOOK_SERVER_URL || "https://alook.ai");
48035
+ const secret = await readAccessCode(options.accessCodeFile);
48036
+ let response;
48037
+ try {
48038
+ response = await fetch(`${origin}${path}`, {
48039
+ method: body === undefined ? "GET" : "POST",
48040
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${secret}` },
48041
+ ...body === undefined ? {} : { body: JSON.stringify(body) },
48042
+ redirect: "error",
48043
+ signal: AbortSignal.timeout(timeoutMs)
48044
+ });
48045
+ } catch {
48046
+ throw new Error(body === undefined ? "Automation request failed" : "Automation request failed; the result may be unknown. Do not retry automatically.");
48047
+ }
48048
+ let raw;
48049
+ try {
48050
+ raw = await response.json();
48051
+ } catch {
48052
+ throw new Error(`Automation returned HTTP ${response.status} without a valid result; do not retry automatically`);
48053
+ }
48054
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
48055
+ throw new Error("Automation returned an invalid result");
48056
+ const result = raw;
48057
+ if (!response.ok) {
48058
+ const message2 = typeof result.error === "string" ? result.error.replaceAll(secret, "[redacted]") : `Automation failed: HTTP ${response.status}`;
48059
+ throw Object.assign(new Error(message2), {
48060
+ ...typeof result.code === "string" ? { code: result.code.replaceAll(secret, "[redacted]") } : {},
48061
+ ...response.status === 429 ? { hint: `Retry after ${response.headers.get("Retry-After") ?? "the indicated"} seconds` } : {}
48062
+ });
48063
+ }
48064
+ return { result, origin };
48065
+ };
48066
+ use.command("expire").description("expire the supplied access code immediately").action(async () => {
48067
+ const { result } = await request("/api/community/automation/expire", {});
48068
+ if (result.expired !== true)
48069
+ throw new Error("Automation returned an invalid expiration result");
48070
+ output2({ success: { expired: true } });
48071
+ });
48072
+ use.command("message").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).description("send a UTF-8 file as yourself or an owned bot").option("--send", "send one message").requiredOption("--target <ref>", "channel or DM ref").requiredOption("--as <identity>", "me or @name#NNNN of your bot").requiredOption("--file <path>", "UTF-8 message body file").action(async (options) => {
48073
+ if (!options.send)
48074
+ throw new Error("Use message --send");
48075
+ const info = await stat(options.file);
48076
+ if (!info.isFile() || info.size > MAX_MESSAGE_CONTENT_LENGTH * 4)
48077
+ throw new Error("Message file is invalid or too large");
48078
+ const bytes = await readFile(options.file);
48079
+ if (bytes.length > MAX_MESSAGE_CONTENT_LENGTH * 4)
48080
+ throw new Error("Message file is too large");
48081
+ const content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
48082
+ const body = parseInput(JSON.stringify({ target: options.target, as: options.as, content, nonce: randomUUID2() }), AutomationMessageSendSchema);
48083
+ const { result } = await request("/api/community/automation/messages", body);
48084
+ if (result.state === "blocked")
48085
+ throw Object.assign(new Error("Bot has unread messages; use its normal inbox pull before sending"), { code: "unaligned" });
48086
+ const sent = AutomationMessageSentSchema.safeParse(result);
48087
+ if (!sent.success)
48088
+ throw new Error("Automation returned an invalid message result");
48089
+ output2({ success: sent.data });
48090
+ });
48091
+ for (const kind of ["bot", "server", "machine", "friend"]) {
48092
+ const command = use.command(kind).description(`Automation ${kind} operations`).exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
48093
+ if (kind === "bot" || kind === "server")
48094
+ command.option("--create <json>", kind === "bot" ? "bot JSON: name, machineId, backendId, optional description/model/reasoningEffort" : "server JSON: name, optional description");
48095
+ if (kind !== "bot")
48096
+ command.option("--list", `list minimal ${kind} identities`);
48097
+ if (kind === "machine")
48098
+ command.option("--list-models", "fetch fresh backend models and reasoning efforts").option("--refresh", "bypass the five-minute model cache").option("--id <machine-id>", "target machine ID for --list-models").option("--backend <backend-id>", "target backend ID for --list-models");
48099
+ if (kind === "server")
48100
+ command.option("--invite <json>", "invite JSON: server and friend full handles").option("--members <server>", "list joined members by full server handle").option("--cursor <cursor>", "next page cursor for --members");
48101
+ command.action(async () => {
48102
+ const options = command.opts();
48103
+ if ([options.create !== undefined, options.list === true, options.invite !== undefined, options.listModels === true, options.members !== undefined].filter(Boolean).length !== 1)
48104
+ throw new Error("Choose exactly one action: --create, --list, --invite, --list-models, or --members");
48105
+ if (options.cursor !== undefined && options.members === undefined)
48106
+ throw new Error("--cursor requires --members");
48107
+ if (options.members !== undefined) {
48108
+ if (!parseNameAndTag(options.members))
48109
+ throw new Error("Use a full server handle");
48110
+ const query = options.cursor ? `?${new URLSearchParams({ cursor: options.cursor })}` : "";
48111
+ const { result: result2 } = await request(`/api/community/automation/servers/${encodeURIComponent(options.members)}/members${query}`);
48112
+ const parsed = MemberList.safeParse(result2);
48113
+ if (!parsed.success || parsed.data.server !== options.members)
48114
+ throw new Error("Automation returned an invalid member list");
48115
+ output2({ success: parsed.data });
48116
+ return;
48117
+ }
48118
+ if (options.listModels) {
48119
+ if (!options.id?.trim() || !options.backend?.trim())
48120
+ throw new Error("--list-models requires --id and --backend");
48121
+ const requestId = randomUUID2();
48122
+ const { result: result2 } = await request(`/api/community/automation/machines/${encodeURIComponent(options.id)}/discover-models`, { requestId, runtimeId: options.backend, ...options.refresh ? { refresh: true } : {} }, 55000);
48123
+ const parsed = ModelList.safeParse(result2);
48124
+ if (!parsed.success || parsed.data.machineId !== options.id || parsed.data.backendId !== options.backend || parsed.data.requestId !== requestId)
48125
+ throw new Error("Automation returned an invalid model list");
48126
+ output2({ success: parsed.data });
48127
+ return;
48128
+ }
48129
+ if (options.id !== undefined || options.backend !== undefined || options.refresh)
48130
+ throw new Error("--id, --backend and --refresh require --list-models");
48131
+ if (options.list) {
48132
+ const key = `${kind}s`;
48133
+ const { result: result2 } = await request(kind === "friend" ? "/api/community/automation/friends" : `/api/community/automation/${key}`);
48134
+ const rows = result2[key];
48135
+ if (!Array.isArray(rows))
48136
+ throw new Error("Automation returned an invalid list");
48137
+ const list = rows.map((row) => {
48138
+ if (!row || typeof row !== "object" || !("name" in row) || typeof row.name !== "string")
48139
+ throw new Error("Automation returned an invalid identity");
48140
+ if (kind === "machine" && "id" in row && typeof row.id === "string" && "status" in row && (row.status === "online" || row.status === "offline")) {
48141
+ const backends = BackendList.safeParse("backends" in row ? row.backends : undefined);
48142
+ if (!backends.success)
48143
+ throw new Error("Automation returned an invalid backend list");
48144
+ return { id: row.id, name: row.name, status: row.status, backends: backends.data };
48145
+ }
48146
+ if (kind === "friend" && "handle" in row && typeof row.handle === "string" && "is_my_bot" in row && typeof row.is_my_bot === "boolean")
48147
+ return { name: row.name, handle: row.handle, is_my_bot: row.is_my_bot };
48148
+ if (kind === "server" && "handle" in row && typeof row.handle === "string") {
48149
+ const channels = ServerChannels.safeParse("channels" in row ? row.channels : undefined);
48150
+ if (!channels.success)
48151
+ throw new Error("Automation returned an invalid server channel list");
48152
+ return { name: row.name, handle: row.handle, channels: channels.data };
48153
+ }
48154
+ throw new Error("Automation returned an invalid identity");
48155
+ });
48156
+ output2({ success: { [key]: list } });
48157
+ return;
48158
+ }
48159
+ if (options.invite !== undefined) {
48160
+ const input2 = parseInput(options.invite, InviteInput);
48161
+ const { result: result2 } = await request(`/api/community/automation/servers/${encodeURIComponent(input2.server)}/invites`, { friend: input2.friend });
48162
+ const value = result2.invitation;
48163
+ if (!value || typeof value !== "object" || !("sent" in value) || value.sent !== true || !("server" in value) || typeof value.server !== "string" || !("friend" in value) || typeof value.friend !== "string")
48164
+ throw new Error("Automation returned an invalid invitation result; do not retry automatically");
48165
+ output2({ success: { invitation: { server: value.server, friend: value.friend, sent: true } } });
48166
+ return;
48167
+ }
48168
+ let body;
48169
+ if (kind === "bot") {
48170
+ const { backendId, ...bot } = parseInput(options.create, BotInput);
48171
+ body = { ...bot, runtime: backendId };
48172
+ } else
48173
+ body = parseInput(options.create, ServerInput);
48174
+ const { result, origin } = await request(`/api/community/automation/${kind}s`, body);
48175
+ const resource = result[kind];
48176
+ if (!resource || typeof resource !== "object" || !("id" in resource) || !("name" in resource) || !("discriminator" in resource) || typeof resource.id !== "string" || typeof resource.name !== "string" || typeof resource.discriminator !== "string")
48177
+ throw new Error("Automation returned an invalid result; do not retry automatically");
48178
+ output2({ success: { [kind]: {
48179
+ id: resource.id,
48180
+ handle: `${resource.name}#${resource.discriminator}`,
48181
+ ...kind === "server" ? { url: `${origin}/c/channels/${encodeURIComponent(resource.id)}` } : {}
48182
+ } } });
48183
+ });
48184
+ }
48185
+ }
48186
+
47761
48187
  // src/cli/index.ts
47762
48188
  import { Command, CommanderError } from "commander";
47763
48189
 
@@ -48135,7 +48561,7 @@ function registerPiiCommands(program, output2) {
48135
48561
 
48136
48562
  // src/cli/index.ts
48137
48563
  import { realpathSync as realpathSync2 } from "node:fs";
48138
- import { randomUUID as randomUUID14 } from "node:crypto";
48564
+ import { randomUUID as randomUUID15 } from "node:crypto";
48139
48565
  import { pathToFileURL as pathToFileURL2 } from "node:url";
48140
48566
  // src/cli/proxyServerApi.ts
48141
48567
  import * as fs from "fs";
@@ -48550,9 +48976,7 @@ function createProxyServerApi(config2) {
48550
48976
  const machine2 = `/machines/${encodeURIComponent(req.machineId)}`;
48551
48977
  if (req.action === "backends")
48552
48978
  return platformCall(machine2);
48553
- if (req.refresh)
48554
- return platformCall(`${machine2}/discover-models`, "POST", { requestId: req.requestId ?? crypto.randomUUID(), runtimeId: req.backendId });
48555
- return platformCall(`${machine2}/models?backend=${encodeURIComponent(req.backendId)}${req.model ? `&model=${encodeURIComponent(req.model)}` : ""}`);
48979
+ return platformCall(`${machine2}/discover-models?wait=1${req.model ? `&model=${encodeURIComponent(req.model)}` : ""}`, "POST", { requestId: req.requestId ?? crypto.randomUUID(), runtimeId: req.backendId, ...req.refresh ? { refresh: true } : {} });
48556
48980
  }
48557
48981
  async function callPlatformBot(req) {
48558
48982
  if (req.action === "list")
@@ -48600,7 +49024,7 @@ import * as path14 from "path";
48600
49024
  import * as fs6 from "fs";
48601
49025
  import { fileURLToPath } from "url";
48602
49026
  // agent-driver/dist/host/default-host.js
48603
- import { randomUUID as randomUUID2 } from "node:crypto";
49027
+ import { randomUUID as randomUUID3 } from "node:crypto";
48604
49028
  function createDefaultAgentDriverHost(options = {}) {
48605
49029
  const environment = { ...options.environment ?? process.env };
48606
49030
  return {
@@ -48623,7 +49047,7 @@ function createDefaultAgentDriverHost(options = {}) {
48623
49047
  options.onRawOutput?.(event);
48624
49048
  },
48625
49049
  now: () => Date.now(),
48626
- createId: () => randomUUID2()
49050
+ createId: () => randomUUID3()
48627
49051
  };
48628
49052
  }
48629
49053
 
@@ -48636,7 +49060,7 @@ import { EventEmitter } from "events";
48636
49060
 
48637
49061
  // agent-driver/dist/internal/killTree.js
48638
49062
  import { execFileSync as execFileSync2, spawn } from "child_process";
48639
- import { randomUUID as randomUUID3 } from "node:crypto";
49063
+ import { randomUUID as randomUUID4 } from "node:crypto";
48640
49064
  import { createServer } from "node:net";
48641
49065
  import { PassThrough } from "node:stream";
48642
49066
 
@@ -49091,7 +49515,7 @@ function spawnAgentProcess(command, args, opts) {
49091
49515
  if (!isPosix) {
49092
49516
  const stdin = opts.stdin ?? "pipe";
49093
49517
  const stdinProxy = stdin === "pipe" ? new PassThrough : undefined;
49094
- const stdinPipe = stdinProxy ? `\\\\.\\pipe\\alook-agent-${process.pid}-${randomUUID3()}` : undefined;
49518
+ const stdinPipe = stdinProxy ? `\\\\.\\pipe\\alook-agent-${process.pid}-${randomUUID4()}` : undefined;
49095
49519
  let stdinSocket;
49096
49520
  const stdinServer = stdinProxy ? createServer((socket) => {
49097
49521
  stdinSocket = socket;
@@ -49771,9 +50195,9 @@ async function prepareCliTransport(ctx, extraEnv = {}, cli = DEFAULT_CLI_CONFIG,
49771
50195
  }
49772
50196
 
49773
50197
  // agent-driver/dist/internal/utils.js
49774
- import { randomUUID as randomUUID4 } from "crypto";
50198
+ import { randomUUID as randomUUID5 } from "crypto";
49775
50199
  function jsonRpcRequest(method, params, id3) {
49776
- return JSON.stringify({ jsonrpc: "2.0", id: id3 ?? randomUUID4(), method, params });
50200
+ return JSON.stringify({ jsonrpc: "2.0", id: id3 ?? randomUUID5(), method, params });
49777
50201
  }
49778
50202
  function tryParseJsonLine(line) {
49779
50203
  try {
@@ -49927,10 +50351,10 @@ async function probeAgy(command, includeModels = false) {
49927
50351
  function validIdentityPart(value) {
49928
50352
  return value.trim().length > 0 && Buffer.byteLength(value, "utf8") <= 512;
49929
50353
  }
49930
- function identityKey(identity) {
49931
- if (!validIdentityPart(identity.runtime) || !validIdentityPart(identity.backendSessionId) || !validIdentityPart(identity.providerRecordId))
50354
+ function identityKey(identity2) {
50355
+ if (!validIdentityPart(identity2.runtime) || !validIdentityPart(identity2.backendSessionId) || !validIdentityPart(identity2.providerRecordId))
49932
50356
  return null;
49933
- return JSON.stringify([identity.runtime, identity.backendSessionId, identity.providerRecordId]);
50357
+ return JSON.stringify([identity2.runtime, identity2.backendSessionId, identity2.providerRecordId]);
49934
50358
  }
49935
50359
  function metric(value) {
49936
50360
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
@@ -49970,8 +50394,8 @@ class SettledUsageProjector {
49970
50394
  usage: { input: input2, output: output2, cache }
49971
50395
  };
49972
50396
  }
49973
- release(identity) {
49974
- const key = identityKey(identity);
50397
+ release(identity2) {
50398
+ const key = identityKey(identity2);
49975
50399
  if (key)
49976
50400
  this.active.delete(key);
49977
50401
  }
@@ -50277,9 +50701,9 @@ function count(data, number4) {
50277
50701
  function parseNativeGeneration(data) {
50278
50702
  const chat = nested(fields(data), 1);
50279
50703
  const usage = nested(chat, 4);
50280
- const timestamp = nested(nested(chat, 9), 4);
50281
- const seconds = count(timestamp, 1);
50282
- const nanos = count(timestamp, 2) ?? 0;
50704
+ const timestamp2 = nested(nested(chat, 9), 4);
50705
+ const seconds = count(timestamp2, 1);
50706
+ const nanos = count(timestamp2, 2) ?? 0;
50283
50707
  const milliseconds = seconds === null ? NaN : seconds * 1000 + Math.floor(nanos / 1e6);
50284
50708
  const occurredAt = nanos < 1e9 && Number.isFinite(milliseconds) && milliseconds <= 8640000000000000 ? new Date(milliseconds).toISOString() : null;
50285
50709
  return { usage: { input: count(usage, 2), output: count(usage, 3), cache: count(usage, 5) }, occurredAt };
@@ -51160,7 +51584,7 @@ class AntigravityAcpLane {
51160
51584
  }
51161
51585
 
51162
51586
  // agent-driver/dist/adapters/antigravity/probe.js
51163
- import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
51587
+ import { createHash as createHash3, randomUUID as randomUUID6 } from "node:crypto";
51164
51588
  import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
51165
51589
  import { homedir as homedir5 } from "node:os";
51166
51590
  import { join as join6 } from "node:path";
@@ -51170,8 +51594,8 @@ function antigravitySpawnSpec(command, platform = process.platform) {
51170
51594
  async function probeAntigravity(command, options = {}) {
51171
51595
  const spec = antigravitySpawnSpec(command);
51172
51596
  const includeModels = options.includeModels !== false;
51173
- const identity = createHash3("sha256").update(JSON.stringify([spec.command, process.env.GEMINI_HOME ?? ""])).digest("hex").slice(0, 16);
51174
- const directory = options.cacheDirectory ?? (includeModels ? join6(homedir5(), ".cache", "alook", "antigravity-probe", identity) : homedir5());
51597
+ const identity2 = createHash3("sha256").update(JSON.stringify([spec.command, process.env.GEMINI_HOME ?? ""])).digest("hex").slice(0, 16);
51598
+ const directory = options.cacheDirectory ?? (includeModels ? join6(homedir5(), ".cache", "alook", "antigravity-probe", identity2) : homedir5());
51175
51599
  const cacheFile = join6(directory, "session");
51176
51600
  let cachedSessionId;
51177
51601
  if (includeModels)
@@ -51290,7 +51714,7 @@ async function probeAntigravity(command, options = {}) {
51290
51714
  return fail("antigravity_acp_invalid_session");
51291
51715
  if (!loading) {
51292
51716
  try {
51293
- const temporary = `${cacheFile}.${randomUUID5()}.tmp`;
51717
+ const temporary = `${cacheFile}.${randomUUID6()}.tmp`;
51294
51718
  writeFileSync3(temporary, sessionId, { mode: 384 });
51295
51719
  renameSync2(temporary, cacheFile);
51296
51720
  } catch {
@@ -51356,7 +51780,7 @@ class AntigravityDriver {
51356
51780
  }
51357
51781
 
51358
51782
  // agent-driver/dist/adapters/claude/index.js
51359
- import { randomUUID as randomUUID7 } from "node:crypto";
51783
+ import { randomUUID as randomUUID8 } from "node:crypto";
51360
51784
 
51361
51785
  // agent-driver/dist/adapters/claude/providerIsolation.js
51362
51786
  import * as fs5 from "fs";
@@ -51716,7 +52140,7 @@ class ClaudeEventNormalizer {
51716
52140
  }
51717
52141
 
51718
52142
  // agent-driver/dist/adapters/claude/turnProtocol.js
51719
- import { randomUUID as randomUUID6 } from "node:crypto";
52143
+ import { randomUUID as randomUUID7 } from "node:crypto";
51720
52144
 
51721
52145
  class ClaudeTurnProtocol {
51722
52146
  rootUuid = null;
@@ -51726,7 +52150,7 @@ class ClaudeTurnProtocol {
51726
52150
  interruptRequested = false;
51727
52151
  finalized = false;
51728
52152
  beginTurn() {
51729
- const uuid3 = randomUUID6();
52153
+ const uuid3 = randomUUID7();
51730
52154
  this.rootUuid = uuid3;
51731
52155
  this.segmentOwnerUuid = uuid3;
51732
52156
  this.delivered.clear();
@@ -51742,7 +52166,7 @@ class ClaudeTurnProtocol {
51742
52166
  return this.rootUuid;
51743
52167
  }
51744
52168
  steeringInputUuid() {
51745
- const uuid3 = randomUUID6();
52169
+ const uuid3 = randomUUID7();
51746
52170
  this.delivered.set(uuid3, { acknowledged: false, followOn: this.awaitingFollowOn });
51747
52171
  return uuid3;
51748
52172
  }
@@ -51809,7 +52233,7 @@ import { createInterface } from "node:readline";
51809
52233
  // agent-driver/dist/internal/recent-context.js
51810
52234
  import path6 from "node:path";
51811
52235
  import { createReadStream } from "node:fs";
51812
- import { readdir, stat } from "node:fs/promises";
52236
+ import { readdir, stat as stat2 } from "node:fs/promises";
51813
52237
  function normalizeAbsolutePath(value) {
51814
52238
  if (typeof value !== "string" || !path6.isAbsolute(value))
51815
52239
  return null;
@@ -51853,7 +52277,7 @@ async function readFirstLine(filePath, maxBytes = 65536) {
51853
52277
  async function collectJsonlFileCandidates(root, options = {}) {
51854
52278
  const candidates = [];
51855
52279
  const readDirectory = options.readDirectory ?? ((directory) => readdir(directory, { withFileTypes: true }));
51856
- const statPath = options.statPath ?? stat;
52280
+ const statPath = options.statPath ?? stat2;
51857
52281
  const visit2 = async (directory, remainingDepth, includeFiles) => {
51858
52282
  let entries;
51859
52283
  try {
@@ -52122,7 +52546,7 @@ class ClaudeDriver {
52122
52546
  writeInterrupt(input2, process2) {
52123
52547
  process2.stdin.write(JSON.stringify({
52124
52548
  type: "control_request",
52125
- request_id: input2.requestId ?? randomUUID7(),
52549
+ request_id: input2.requestId ?? randomUUID8(),
52126
52550
  request: { subtype: "interrupt" }
52127
52551
  }) + `
52128
52552
  `);
@@ -52651,22 +53075,22 @@ class CodexEventNormalizer {
52651
53075
  handleItemStarted(params) {
52652
53076
  const t = params?.item?.type ?? params?.type;
52653
53077
  const callId = this.itemCallId(params);
52654
- const identity = callId ? { callId } : {};
53078
+ const identity2 = callId ? { callId } : {};
52655
53079
  switch (t) {
52656
53080
  case "commandExecution":
52657
- return [{ kind: "tool_call", ...identity, name: "shell", input: params?.item }];
53081
+ return [{ kind: "tool_call", ...identity2, name: "shell", input: params?.item }];
52658
53082
  case "contextCompaction":
52659
53083
  return [{ kind: "compaction_started" }];
52660
53084
  case "enteredReviewMode":
52661
53085
  return [{ kind: "review_started" }];
52662
53086
  case "fileChange":
52663
- return [{ kind: "tool_call", ...identity, name: "file_change", input: normalizeFileChangeInput(params?.item) }];
53087
+ return [{ kind: "tool_call", ...identity2, name: "file_change", input: normalizeFileChangeInput(params?.item) }];
52664
53088
  case "mcpToolCall":
52665
- return [{ kind: "tool_call", ...identity, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}`, input: params?.item }];
53089
+ return [{ kind: "tool_call", ...identity2, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}`, input: params?.item }];
52666
53090
  case "webSearch":
52667
- return [{ kind: "tool_call", ...identity, name: "web_search", input: params?.item }];
53091
+ return [{ kind: "tool_call", ...identity2, name: "web_search", input: params?.item }];
52668
53092
  case "collabAgentToolCall":
52669
- return [{ kind: "tool_call", ...identity, name: "collab_tool_call", input: params?.item }];
53093
+ return [{ kind: "tool_call", ...identity2, name: "collab_tool_call", input: params?.item }];
52670
53094
  default:
52671
53095
  return [];
52672
53096
  }
@@ -52674,22 +53098,22 @@ class CodexEventNormalizer {
52674
53098
  handleItemCompleted(params) {
52675
53099
  const t = params?.item?.type ?? params?.type;
52676
53100
  const callId = this.itemCallId(params);
52677
- const identity = callId ? { callId } : {};
53101
+ const identity2 = callId ? { callId } : {};
52678
53102
  switch (t) {
52679
53103
  case "commandExecution":
52680
- return [{ kind: "tool_output", ...identity, name: "shell" }];
53104
+ return [{ kind: "tool_output", ...identity2, name: "shell" }];
52681
53105
  case "contextCompaction":
52682
53106
  return [{ kind: "compaction_finished" }];
52683
53107
  case "exitedReviewMode":
52684
53108
  return [{ kind: "review_finished" }];
52685
53109
  case "fileChange":
52686
- return [{ kind: "tool_output", ...identity, name: "file_change" }];
53110
+ return [{ kind: "tool_output", ...identity2, name: "file_change" }];
52687
53111
  case "mcpToolCall":
52688
- return [{ kind: "tool_output", ...identity, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}` }];
53112
+ return [{ kind: "tool_output", ...identity2, name: `mcp_${params?.item?.tool ?? params?.item?.name ?? "tool"}` }];
52689
53113
  case "webSearch":
52690
- return [{ kind: "tool_output", ...identity, name: "web_search" }];
53114
+ return [{ kind: "tool_output", ...identity2, name: "web_search" }];
52691
53115
  case "collabAgentToolCall":
52692
- return [{ kind: "tool_output", ...identity, name: "collab_tool_call" }];
53116
+ return [{ kind: "tool_output", ...identity2, name: "collab_tool_call" }];
52693
53117
  case "agentMessage":
52694
53118
  return [{ kind: "assistant_message_completed", text: params?.item?.text ?? "" }];
52695
53119
  case "reasoning": {
@@ -55892,9 +56316,9 @@ class OpenCodeServiceLane {
55892
56316
  if (this.stopping)
55893
56317
  throw new OpenCodeStoppedError("OpenCode service lane stopped during startup");
55894
56318
  }
55895
- assertStartupIdentity(identity) {
56319
+ assertStartupIdentity(identity2) {
55896
56320
  this.assertRunning();
55897
- if (!this.isIdentity(identity)) {
56321
+ if (!this.isIdentity(identity2)) {
55898
56322
  throw new Error("OpenCode service identity changed during startup");
55899
56323
  }
55900
56324
  }
@@ -56009,14 +56433,14 @@ class OpenCodeServiceLane {
56009
56433
  await this.catchUpHistory(false);
56010
56434
  }
56011
56435
  startStreams() {
56012
- const identity = this.identity;
56013
- if (!identity || !this.sessionId)
56436
+ const identity2 = this.identity;
56437
+ if (!identity2 || !this.sessionId)
56014
56438
  throw new Error("OpenCode service streams started before session initialization");
56015
- this.durableTask = this.runDurableStream(identity).catch((error62) => this.streamFailure("durable", error62));
56016
- this.liveTask = this.runLiveStream(identity).catch((error62) => this.streamFailure("live", error62));
56439
+ this.durableTask = this.runDurableStream(identity2).catch((error62) => this.streamFailure("durable", error62));
56440
+ this.liveTask = this.runLiveStream(identity2).catch((error62) => this.streamFailure("live", error62));
56017
56441
  }
56018
- async runDurableStream(identity) {
56019
- while (!this.stopping && this.isIdentity(identity)) {
56442
+ async runDurableStream(identity2) {
56443
+ while (!this.stopping && this.isIdentity(identity2)) {
56020
56444
  this.durableGap = true;
56021
56445
  const gate = this.durableGate;
56022
56446
  const controller = new AbortController;
@@ -56025,7 +56449,7 @@ class OpenCodeServiceLane {
56025
56449
  const path10 = `/api/session/${encodeURIComponent(this.sessionId)}/event?after=${this.lastDurableSeq}`;
56026
56450
  const response = await this.openStream(path10, controller, "durable event stream");
56027
56451
  await this.catchUpHistory(true);
56028
- if (!this.isIdentity(identity))
56452
+ if (!this.isIdentity(identity2))
56029
56453
  return;
56030
56454
  this.durableGap = false;
56031
56455
  gate.resolve();
@@ -56036,7 +56460,7 @@ class OpenCodeServiceLane {
56036
56460
  if (!this.stopping)
56037
56461
  this.diagnostic("warning", "OpenCode durable event stream disconnected; replaying from its cursor");
56038
56462
  } catch (error62) {
56039
- if (this.stopping || !this.isIdentity(identity) || controller.signal.aborted)
56463
+ if (this.stopping || !this.isIdentity(identity2) || controller.signal.aborted)
56040
56464
  return;
56041
56465
  if (error62 instanceof OpenCodeProtocolError || error62 instanceof OpenCodeHttpError && error62.status < 500) {
56042
56466
  this.protocolFailure("OpenCode durable event stream violated the v2 protocol", error62);
@@ -56057,22 +56481,22 @@ class OpenCodeServiceLane {
56057
56481
  await delay(this.options.reconnectDelayMs ?? RECONNECT_DELAY_MS);
56058
56482
  }
56059
56483
  }
56060
- async runLiveStream(identity) {
56061
- while (!this.stopping && this.isIdentity(identity)) {
56484
+ async runLiveStream(identity2) {
56485
+ while (!this.stopping && this.isIdentity(identity2)) {
56062
56486
  const gate = this.liveGate;
56063
56487
  const controller = new AbortController;
56064
56488
  this.liveAbort = controller;
56065
56489
  try {
56066
56490
  const response = await this.openStream("/api/event", controller, "live event stream");
56067
56491
  await this.recoverPendingPermissions();
56068
- if (!this.isIdentity(identity))
56492
+ if (!this.isIdentity(identity2))
56069
56493
  return;
56070
56494
  gate.resolve();
56071
56495
  await this.consumeSse(response, (value) => this.handleLiveEvent(value));
56072
56496
  if (!this.stopping)
56073
56497
  this.diagnostic("warning", "OpenCode live event stream disconnected; reconnecting");
56074
56498
  } catch (error62) {
56075
- if (this.stopping || !this.isIdentity(identity) || controller.signal.aborted)
56499
+ if (this.stopping || !this.isIdentity(identity2) || controller.signal.aborted)
56076
56500
  return;
56077
56501
  if (error62 instanceof OpenCodeProtocolError || error62 instanceof OpenCodeHttpError && error62.status < 500) {
56078
56502
  this.protocolFailure("OpenCode live event stream violated the v2 protocol", error62);
@@ -56273,13 +56697,13 @@ class OpenCodeServiceLane {
56273
56697
  const tokens = record5(data.tokens);
56274
56698
  if (tokens) {
56275
56699
  const cache = record5(tokens.cache);
56276
- const identity = {
56700
+ const identity2 = {
56277
56701
  runtime: "opencode",
56278
56702
  backendSessionId,
56279
56703
  providerRecordId: event.id
56280
56704
  };
56281
56705
  const usage = this.usageProjector.project({
56282
- ...identity,
56706
+ ...identity2,
56283
56707
  source: "opencode.v2",
56284
56708
  input: tokens.input,
56285
56709
  output: tokens.output,
@@ -56291,7 +56715,7 @@ class OpenCodeServiceLane {
56291
56715
  });
56292
56716
  if (usage)
56293
56717
  this.events.emit("runtime_event", usage);
56294
- this.usageProjector.release(identity);
56718
+ this.usageProjector.release(identity2);
56295
56719
  }
56296
56720
  break;
56297
56721
  }
@@ -56456,8 +56880,8 @@ class OpenCodeServiceLane {
56456
56880
  }
56457
56881
  async evaluateTerminal() {
56458
56882
  const root = this.activeRoot;
56459
- const identity = this.identity;
56460
- if (!root || !identity || this.stopping || this.evaluating)
56883
+ const identity2 = this.identity;
56884
+ if (!root || !identity2 || this.stopping || this.evaluating)
56461
56885
  return;
56462
56886
  if (root.pendingAdmissions > 0 || root.interruptPending || this.durableGap || root.frontier.size === 0 || root.observedAdmissions.size !== root.frontier.size)
56463
56887
  return;
@@ -56474,14 +56898,14 @@ class OpenCodeServiceLane {
56474
56898
  const active = record5(body?.data);
56475
56899
  if (!active)
56476
56900
  throw new OpenCodeProtocolError("OpenCode active session query returned invalid data");
56477
- if (!this.barrierStillCurrent(root, identity, generation))
56901
+ if (!this.barrierStillCurrent(root, identity2, generation))
56478
56902
  return;
56479
56903
  if (active[this.sessionId] !== undefined) {
56480
56904
  this.scheduleEvaluation(this.options.activePollMs ?? ACTIVE_POLL_MS);
56481
56905
  return;
56482
56906
  }
56483
56907
  await this.catchUpHistory(true);
56484
- if (!this.barrierStillCurrent(root, identity, generation) || this.durableGap)
56908
+ if (!this.barrierStillCurrent(root, identity2, generation) || this.durableGap)
56485
56909
  return;
56486
56910
  if (root.observedAdmissions.size !== root.frontier.size || this.lastDurableSeq < maxAdmission)
56487
56911
  return;
@@ -56500,7 +56924,7 @@ class OpenCodeServiceLane {
56500
56924
  this.protocolFailure("OpenCode active barrier violated the v2 protocol", error62);
56501
56925
  return;
56502
56926
  }
56503
- if (!this.stopping && this.activeRoot === root && this.isIdentity(identity)) {
56927
+ if (!this.stopping && this.activeRoot === root && this.isIdentity(identity2)) {
56504
56928
  this.diagnostic("warning", "OpenCode active barrier query failed; retrying without settling the turn");
56505
56929
  this.scheduleEvaluation(this.options.activePollMs ?? ACTIVE_POLL_MS);
56506
56930
  }
@@ -56514,8 +56938,8 @@ class OpenCodeServiceLane {
56514
56938
  }
56515
56939
  }
56516
56940
  }
56517
- barrierStillCurrent(root, identity, generation) {
56518
- return this.activeRoot === root && root.generation === generation && root.pendingAdmissions === 0 && !root.interruptPending && this.isIdentity(identity) && this.identityMatches();
56941
+ barrierStillCurrent(root, identity2, generation) {
56942
+ return this.activeRoot === root && root.generation === generation && root.pendingAdmissions === 0 && !root.interruptPending && this.isIdentity(identity2) && this.identityMatches();
56519
56943
  }
56520
56944
  settleRoot(root, success2, message2, code = "opencode.turn_failed") {
56521
56945
  if (this.activeRoot !== root)
@@ -56625,15 +57049,15 @@ class OpenCodeServiceLane {
56625
57049
  this.events.emit("error", new Error(message2));
56626
57050
  }
56627
57051
  identityMatches() {
56628
- const identity = this.identity;
56629
- const matches = !!identity && identity.process === this.process && identity.process.pid === identity.pid && !this.isProcessClosed(identity.process);
56630
- if (!matches && identity && identity.process === this.process && identity.process.pid !== identity.pid && this.ready && !this.stopping) {
57052
+ const identity2 = this.identity;
57053
+ const matches = !!identity2 && identity2.process === this.process && identity2.process.pid === identity2.pid && !this.isProcessClosed(identity2.process);
57054
+ if (!matches && identity2 && identity2.process === this.process && identity2.process.pid !== identity2.pid && this.ready && !this.stopping) {
56631
57055
  this.failPidIdentity();
56632
57056
  }
56633
57057
  return matches;
56634
57058
  }
56635
- isIdentity(identity) {
56636
- return this.identity === identity && this.identityMatches();
57059
+ isIdentity(identity2) {
57060
+ return this.identity === identity2 && this.identityMatches();
56637
57061
  }
56638
57062
  isProcessClosed(proc) {
56639
57063
  return proc.exitCode !== null || proc.signalCode !== null;
@@ -56878,8 +57302,8 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
56878
57302
  }
56879
57303
  async primeHistory() {}
56880
57304
  startStreams() {
56881
- const identity = this.identity;
56882
- this.liveTask = this.runLiveStream(identity).catch((error62) => {
57305
+ const identity2 = this.identity;
57306
+ this.liveTask = this.runLiveStream(identity2).catch((error62) => {
56883
57307
  if (!this.stopping)
56884
57308
  this.protocolFailure("OpenCode CLI v2 live stream failed", error62);
56885
57309
  });
@@ -56947,13 +57371,13 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
56947
57371
  return this.admit(input2.text, "steer", this.newMessageId(), root);
56948
57372
  }
56949
57373
  async beginRoot(input2) {
56950
- const page = await this.messagePage(undefined, 1);
57374
+ const page2 = await this.messagePage(undefined, 1);
56951
57375
  if (this.stopping || !this.identityMatches())
56952
57376
  return { ok: false, reason: "closed" };
56953
57377
  const receipt = input2.terminalOwner?.startsWith("msg_") ? input2.terminalOwner : this.newMessageId();
56954
57378
  const root = {
56955
57379
  receipt,
56956
- baseline: typeof page.data[0]?.id === "string" ? page.data[0].id : null,
57380
+ baseline: typeof page2.data[0]?.id === "string" ? page2.data[0].id : null,
56957
57381
  inputs: new Set,
56958
57382
  generation: 0,
56959
57383
  pending: 0
@@ -56995,37 +57419,37 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
56995
57419
  const { response, body } = await this.fetchJsonWithTimeout(`/api/session/${encodeURIComponent(this.sessionId)}/message?${query}`, { method: "GET" }, "message recovery");
56996
57420
  if (!response.ok)
56997
57421
  throw new OpenCodeHttpError(response.status, "message recovery");
56998
- const page = record5(body);
56999
- const cursors = record5(page?.cursor);
57000
- if (!Array.isArray(page?.data) || !cursors || page.data.some((item) => typeof record5(item)?.id !== "string")) {
57422
+ const page2 = record5(body);
57423
+ const cursors = record5(page2?.cursor);
57424
+ if (!Array.isArray(page2?.data) || !cursors || page2.data.some((item) => typeof record5(item)?.id !== "string")) {
57001
57425
  throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid message page");
57002
57426
  }
57003
57427
  if (cursors.next !== undefined && cursors.next !== null && typeof cursors.next !== "string")
57004
57428
  throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid message cursor");
57005
- return { data: page.data, next: typeof cursors.next === "string" ? cursors.next : undefined };
57429
+ return { data: page2.data, next: typeof cursors.next === "string" ? cursors.next : undefined };
57006
57430
  }
57007
57431
  async messagesAfter(root) {
57008
57432
  const messages = [];
57009
57433
  const cursors = new Set;
57010
57434
  let cursor;
57011
57435
  for (;; ) {
57012
- const page = await this.messagePage(cursor);
57436
+ const page2 = await this.messagePage(cursor);
57013
57437
  if (this.root !== root || this.stopping)
57014
57438
  return [];
57015
- for (const message2 of page.data) {
57439
+ for (const message2 of page2.data) {
57016
57440
  if (message2.id === root.baseline)
57017
57441
  return messages.reverse();
57018
57442
  messages.push(message2);
57019
57443
  }
57020
- if (!page.next) {
57444
+ if (!page2.next) {
57021
57445
  if (root.baseline !== null)
57022
57446
  throw new OpenCodeProtocolError("OpenCode CLI v2 message recovery lost its root boundary");
57023
57447
  return messages.reverse();
57024
57448
  }
57025
- if (cursors.has(page.next))
57449
+ if (cursors.has(page2.next))
57026
57450
  throw new OpenCodeProtocolError("OpenCode CLI v2 message cursor did not advance");
57027
- cursors.add(page.next);
57028
- cursor = page.next;
57451
+ cursors.add(page2.next);
57452
+ cursor = page2.next;
57029
57453
  }
57030
57454
  }
57031
57455
  schedule() {
@@ -57048,12 +57472,12 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
57048
57472
  }
57049
57473
  async evaluate() {
57050
57474
  const root = this.root;
57051
- const identity = this.identity;
57052
- if (!root || !identity || this.stopping || root.pending > 0 || root.inputs.size === 0 || this.v2Evaluating)
57475
+ const identity2 = this.identity;
57476
+ if (!root || !identity2 || this.stopping || root.pending > 0 || root.inputs.size === 0 || this.v2Evaluating)
57053
57477
  return;
57054
57478
  this.v2Evaluating = true;
57055
57479
  const generation = root.generation;
57056
- const current = () => this.root === root && root.generation === generation && root.pending === 0 && this.isIdentity(identity);
57480
+ const current = () => this.root === root && root.generation === generation && root.pending === 0 && this.isIdentity(identity2);
57057
57481
  try {
57058
57482
  if (await this.isActive())
57059
57483
  return;
@@ -57191,9 +57615,9 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
57191
57615
  if (!tokens || !this.sessionId)
57192
57616
  return;
57193
57617
  const cache = record5(tokens.cache);
57194
- const identity = { runtime: "opencode", backendSessionId: this.sessionId, providerRecordId: message2.id };
57618
+ const identity2 = { runtime: "opencode", backendSessionId: this.sessionId, providerRecordId: message2.id };
57195
57619
  const usage = this.usage.project({
57196
- ...identity,
57620
+ ...identity2,
57197
57621
  source: "opencode.v2",
57198
57622
  input: tokens.input,
57199
57623
  output: tokens.output,
@@ -57205,7 +57629,7 @@ class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
57205
57629
  });
57206
57630
  if (usage)
57207
57631
  this.events.emit("runtime_event", usage);
57208
- this.usage.release(identity);
57632
+ this.usage.release(identity2);
57209
57633
  }
57210
57634
  async interrupt(_input) {
57211
57635
  const root = this.root;
@@ -57693,9 +58117,9 @@ function mapPiSdkEvent(event, sessionId, state) {
57693
58117
  state.usageRecordSequence = (state.usageRecordSequence ?? 0) + 1;
57694
58118
  const providerRecordId = typeof message2.responseId === "string" && message2.responseId ? message2.responseId : `live:${message2.timestamp ?? "unknown"}:${state.usageRecordSequence}`;
57695
58119
  const { projector, pending } = piUsageState(state);
57696
- const identity = { runtime: "pi", backendSessionId: sessionId, providerRecordId };
58120
+ const identity2 = { runtime: "pi", backendSessionId: sessionId, providerRecordId };
57697
58121
  const usage = projector.project({
57698
- ...identity,
58122
+ ...identity2,
57699
58123
  source: "pi_message_end",
57700
58124
  input: message2.usage.input,
57701
58125
  output: message2.usage.output,
@@ -58159,8 +58583,8 @@ function ensureSymlinks(workDir, canonical = CANONICAL_FILE, aliases = SYMLINK_A
58159
58583
  continue;
58160
58584
  const aliasPath = join11(workDir, alias2);
58161
58585
  try {
58162
- const stat2 = lstatSync(aliasPath);
58163
- if (stat2.isSymbolicLink()) {
58586
+ const stat3 = lstatSync(aliasPath);
58587
+ if (stat3.isSymbolicLink()) {
58164
58588
  const target2 = readlinkSync(aliasPath);
58165
58589
  if (target2 === canonical)
58166
58590
  continue;
@@ -59920,6 +60344,11 @@ function readDaemonVersion() {
59920
60344
  return "";
59921
60345
  }
59922
60346
 
60347
+ // src/npmEnvironment.ts
60348
+ function withoutNpmExecPackage(env) {
60349
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key.toLowerCase() !== "npm_config_package"));
60350
+ }
60351
+
59923
60352
  // src/cli/daemonRunner.ts
59924
60353
  import * as fs11 from "node:fs";
59925
60354
  import * as path17 from "node:path";
@@ -59931,7 +60360,7 @@ import { homedir as homedir14 } from "os";
59931
60360
  // src/pii/store.ts
59932
60361
  import { chmodSync, existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync5 } from "node:fs";
59933
60362
  import { join as join13 } from "node:path";
59934
- import { randomUUID as randomUUID8 } from "node:crypto";
60363
+ import { randomUUID as randomUUID9 } from "node:crypto";
59935
60364
 
59936
60365
  // src/pii/id-numbers.ts
59937
60366
  var ID_NUMBERS_SOURCE = String.raw`export default (text: string) => {
@@ -61402,7 +61831,7 @@ class PiiStore {
61402
61831
  }
61403
61832
  save(botId, pipeline) {
61404
61833
  const directory = this.directoryFor(botId);
61405
- const temporary = join13(directory, `.${randomUUID8()}.tmp`);
61834
+ const temporary = join13(directory, `.${randomUUID9()}.tmp`);
61406
61835
  try {
61407
61836
  mkdirSync6(directory, { recursive: true, mode: 448 });
61408
61837
  chmodSync(directory, 448);
@@ -61433,7 +61862,7 @@ class PiiStore {
61433
61862
  const pipeline = { ...current, plugins: [...current.plugins] };
61434
61863
  if (pipeline.plugins.length >= PII_MAX_PLUGINS)
61435
61864
  throw new PiiError("PII_PLUGIN_LIMIT");
61436
- pipeline.plugins.push({ id: randomUUID8(), name: input2.name, description: input2.description, enabled: true, source: input2.source });
61865
+ pipeline.plugins.push({ id: randomUUID9(), name: input2.name, description: input2.description, enabled: true, source: input2.source });
61437
61866
  pipeline.revision++;
61438
61867
  this.save(botId, pipeline);
61439
61868
  return this.snapshot(pipeline);
@@ -61538,8 +61967,8 @@ function createRotatingFileSink(path15, maxBytes, opts = {}) {
61538
61967
  if (!existsSync8(filePath))
61539
61968
  return true;
61540
61969
  try {
61541
- const stat2 = lstatSync2(filePath);
61542
- if (!stat2.isFile()) {
61970
+ const stat3 = lstatSync2(filePath);
61971
+ if (!stat3.isFile()) {
61543
61972
  if (opts.mode === undefined && !opts.hardMaxBytes)
61544
61973
  return true;
61545
61974
  report("unsafe_generation", new Error("log generation is not a regular file"));
@@ -61547,7 +61976,7 @@ function createRotatingFileSink(path15, maxBytes, opts = {}) {
61547
61976
  }
61548
61977
  if (opts.mode !== undefined)
61549
61978
  chmodSync2(filePath, opts.mode);
61550
- if (opts.hardMaxBytes && maxBytes > 0 && stat2.size > maxBytes) {
61979
+ if (opts.hardMaxBytes && maxBytes > 0 && stat3.size > maxBytes) {
61551
61980
  try {
61552
61981
  unlinkSync3(filePath);
61553
61982
  } catch (error62) {
@@ -61619,10 +62048,10 @@ function createRotatingFileSink(path15, maxBytes, opts = {}) {
61619
62048
  const noFollow = "O_NOFOLLOW" in constants ? constants.O_NOFOLLOW : 0;
61620
62049
  const fd = openSync(candidate, constants.O_RDONLY | noFollow);
61621
62050
  try {
61622
- const stat2 = fstatSync(fd);
61623
- if (!stat2.isFile())
62051
+ const stat3 = fstatSync(fd);
62052
+ if (!stat3.isFile())
61624
62053
  throw new Error("snapshot source is not a regular file");
61625
- files.push({ path: candidate, fd, size: stat2.size });
62054
+ files.push({ path: candidate, fd, size: stat3.size });
61626
62055
  } catch (error62) {
61627
62056
  closeSync(fd);
61628
62057
  throw error62;
@@ -62722,7 +63151,8 @@ async function startCredentialProxy(broker, options = {}) {
62722
63151
  }
62723
63152
  };
62724
63153
  const server = http.createServer(async (req, res) => {
62725
- const pathname = new URL2(req.url ?? "/", "http://placeholder").pathname;
63154
+ const requestUrl = new URL2(req.url ?? "/", "http://placeholder");
63155
+ const pathname = requestUrl.pathname;
62726
63156
  if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {
62727
63157
  const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");
62728
63158
  if (!localVerdict.ok) {
@@ -62955,7 +63385,8 @@ async function startCredentialProxy(broker, options = {}) {
62955
63385
  res.writeHead(502, { "content-type": "application/json" });
62956
63386
  res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));
62957
63387
  });
62958
- const upstreamTimeoutMs = options.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS;
63388
+ const waitingForModels = req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname) && requestUrl.searchParams.get("wait") === "1";
63389
+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55000 : DEFAULT_UPSTREAM_TIMEOUT_MS);
62959
63390
  upstreamReq.setTimeout(upstreamTimeoutMs, () => {
62960
63391
  upstreamReq.destroy();
62961
63392
  upstreamRes?.destroy();
@@ -63201,14 +63632,14 @@ function reduceManager(state, event) {
63201
63632
  if (!matchesSession(a, event.sessionInstanceId))
63202
63633
  return;
63203
63634
  const lease = a.execution.lease;
63204
- const identity = identityOf(event);
63205
- if ((lease.state === "active" || lease.state === "suspect_active") && !sameIdentity(lease.identity, identity))
63635
+ const identity2 = identityOf(event);
63636
+ if ((lease.state === "active" || lease.state === "suspect_active") && !sameIdentity(lease.identity, identity2))
63206
63637
  return;
63207
63638
  const startedCommands = new Set(event.commandIds);
63208
63639
  a.pendingAdmissions = a.pendingAdmissions.filter((entry) => !startedCommands.has(entry.commandId));
63209
63640
  a.execution.lease = {
63210
63641
  state: "active",
63211
- identity,
63642
+ identity: identity2,
63212
63643
  lastWorkAt: event.nowMs,
63213
63644
  nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
63214
63645
  recoveryExtensionsUsed: 0
@@ -63236,8 +63667,8 @@ function reduceManager(state, event) {
63236
63667
  if (!matchesSession(a, event.sessionInstanceId))
63237
63668
  return;
63238
63669
  const lease = a.execution.lease;
63239
- const identity = identityOf(event);
63240
- if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity)) {
63670
+ const identity2 = identityOf(event);
63671
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity2)) {
63241
63672
  a.execution.lease = {
63242
63673
  ...lease,
63243
63674
  lastWorkAt: event.nowMs,
@@ -63246,11 +63677,11 @@ function reduceManager(state, event) {
63246
63677
  };
63247
63678
  } else {
63248
63679
  const terminal = lease.state === "none" ? lease.lastTerminal : null;
63249
- if (!terminal || !sameIdentity(terminal.identity, identity))
63680
+ if (!terminal || !sameIdentity(terminal.identity, identity2))
63250
63681
  return;
63251
63682
  a.execution.lease = {
63252
63683
  state: "suspect_active",
63253
- identity,
63684
+ identity: identity2,
63254
63685
  lastWorkAt: event.nowMs,
63255
63686
  nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
63256
63687
  recoveryExtensionsUsed: 0,
@@ -63289,13 +63720,13 @@ function reduceManager(state, event) {
63289
63720
  if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
63290
63721
  return { state, effects: [] };
63291
63722
  const lease = existing.execution.lease;
63292
- const identity = { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
63293
- if (lease.state !== "active" && lease.state !== "suspect_active" || !sameIdentity(lease.identity, identity)) {
63723
+ const identity2 = { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
63724
+ if (lease.state !== "active" && lease.state !== "suspect_active" || !sameIdentity(lease.identity, identity2)) {
63294
63725
  return { state, effects: [] };
63295
63726
  }
63296
63727
  return mutate(state, event.agentId, (a) => {
63297
63728
  const active = a.execution.lease;
63298
- if (active.state !== "active" && active.state !== "suspect_active" || !sameIdentity(active.identity, identity))
63729
+ if (active.state !== "active" && active.state !== "suspect_active" || !sameIdentity(active.identity, identity2))
63299
63730
  return;
63300
63731
  if (event.kind === "recovery" && event.recoveryStage !== "recovered") {
63301
63732
  if (active.recoveryExtensionsUsed < a.turnSilence.maxRecoveryExtensions) {
@@ -63382,10 +63813,10 @@ function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endRe
63382
63813
  const lease = agent2.execution.lease;
63383
63814
  if (lease.state !== "active" && lease.state !== "suspect_active")
63384
63815
  return { state, effects: [] };
63385
- const identity = { sessionInstanceId, turnId };
63386
- if (!sameIdentity(lease.identity, identity))
63816
+ const identity2 = { sessionInstanceId, turnId };
63817
+ if (!sameIdentity(lease.identity, identity2))
63387
63818
  return { state, effects: [] };
63388
- const lastTerminal = { identity, at: nowMs };
63819
+ const lastTerminal = { identity: identity2, at: nowMs };
63389
63820
  agent2.execution.lease = { state: "none", lastTerminal };
63390
63821
  agent2.lastProgressAt = nowMs;
63391
63822
  agent2.lastNativeActivityAt = nowMs;
@@ -63411,9 +63842,9 @@ function onTurnToolLifecycle(state, event, lifecycle) {
63411
63842
  if (!existing || existing.resetting || existing.execution.sessionInstanceId !== event.sessionInstanceId)
63412
63843
  return { state, effects: [] };
63413
63844
  const current = existing.execution.lease;
63414
- const identity = identityOf(event);
63415
- const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, identity);
63416
- const matchesTerminal = lifecycle === "started" && current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, identity);
63845
+ const identity2 = identityOf(event);
63846
+ const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, identity2);
63847
+ const matchesTerminal = lifecycle === "started" && current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, identity2);
63417
63848
  if (!matchesActive && !matchesTerminal)
63418
63849
  return { state, effects: [] };
63419
63850
  return mutate(state, event.agentId, (agent2) => {
@@ -63421,7 +63852,7 @@ function onTurnToolLifecycle(state, event, lifecycle) {
63421
63852
  return;
63422
63853
  const lease = agent2.execution.lease;
63423
63854
  const callId = normalizedToolCallId(event.callId);
63424
- if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity)) {
63855
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity2)) {
63425
63856
  const identified = new Set(lease.outstandingToolCallIds ?? []);
63426
63857
  const currentCount = lease.outstandingToolUses ?? 0;
63427
63858
  const anonymousCount = Math.max(0, currentCount - identified.size);
@@ -63459,11 +63890,11 @@ function onTurnToolLifecycle(state, event, lifecycle) {
63459
63890
  }
63460
63891
  } else {
63461
63892
  const terminal = lease.state === "none" ? lease.lastTerminal : null;
63462
- if (lifecycle !== "started" || !terminal || !sameIdentity(terminal.identity, identity))
63893
+ if (lifecycle !== "started" || !terminal || !sameIdentity(terminal.identity, identity2))
63463
63894
  return;
63464
63895
  agent2.execution.lease = {
63465
63896
  state: "suspect_active",
63466
- identity,
63897
+ identity: identity2,
63467
63898
  lastWorkAt: event.nowMs,
63468
63899
  nativeDeadlineAt: event.nowMs + agent2.turnSilence.normalBudgetMs,
63469
63900
  recoveryExtensionsUsed: 0,
@@ -63676,10 +64107,11 @@ var MEMORY_MAINTENANCE_PROMPT = `The daemon is preparing to reset this idle sess
63676
64107
  2. Facts: Verify claims, especially work progress, against the latest original records. Search the context timeline and task discussions through their latest outcomes. Correct outdated or unsupported claims; keep uncertainty explicit.
63677
64108
  3. Learn: Use .context_timeline to find channels and threads you recently participated in. Read the full history of each recent discussion, from the initial request through the work, intermediate corrections, and any final decisions. Understand the sequence of events and why the user corrected the approach before learning first principles. Proactively record the user's guidance on communication, collaboration, and how to do work. Distill it into first principles: the underlying goals, reasons, and constraints that make the guidance reusable. Preserve its scope and source links; distinguish explicit user instructions from your own inferences. Update or remove superseded notes.
63678
64109
  4. Durability: Keep only lasting facts, preferences, and reusable lessons or procedures. Remove task status, milestones, temporary plans, and diaries; extract a reusable lesson only when useful. Keep memory.md brief with links; put procedures, scope, and reasons in experiences. Reason from first principles: distill specific events into underlying causes, constraints, and reusable principles. Omit incidental dates and details; retain context only when it changes the principle’s validity or scope.
64110
+ 5. Follow up: After completing the memory review and any needed edits, run \`$ALOOK_CLI message mark list\` and check each unfinished item's latest discussion. In the item's original channel, thread, or DM, send the relevant person a brief reminder of the remaining work and the next action needed. Skip items that are already complete or cancelled. Do not wait for replies.
63679
64111
 
63680
- Edit only your own memory files. This review is internal maintenance; perform it silently. Do not proactively send the owner, users, or channels progress updates, completion notices, or details about your memory state. Communicate task-relevant results, questions, and blockers normally. If nothing needs a user-facing response, send no message.
64112
+ Edit only your own memory files. This review is internal maintenance; perform it silently. Do not proactively send the owner, users, or channels progress updates, completion notices, or details about your memory state. The task reminders in step 5 are separate from memory-maintenance updates. Communicate task-relevant results, questions, and blockers normally. If nothing needs a user-facing response, send no message.
63681
64113
 
63682
- If new work arrives, handle it first and defer nap. Otherwise, after completing the review and any needed edits, your final action is to run the following command without --handoff. Do not finish with only a written reply. This instruction authorizes that nap:
64114
+ If new work arrives, handle it first and defer nap. Otherwise, after completing the review, any needed edits, and the task reminders, your final action is to run the following command without --handoff. Do not finish with only a written reply. This instruction authorizes that nap:
63683
64115
 
63684
64116
  $ALOOK_CLI nap`;
63685
64117
  // src/runtimeConfig.ts
@@ -63691,7 +64123,7 @@ function runtimeModelName(config2) {
63691
64123
  }
63692
64124
  // agent-driver/dist/adapters/antigravity/quota.js
63693
64125
  import { createHash as createHash5, randomBytes as randomBytes6 } from "node:crypto";
63694
- import { readFile } from "node:fs/promises";
64126
+ import { readFile as readFile2 } from "node:fs/promises";
63695
64127
  import { homedir as homedir11 } from "node:os";
63696
64128
  import { isAbsolute, join as join15 } from "node:path";
63697
64129
  var PROD = "https://cloudcode-pa.googleapis.com";
@@ -63767,7 +64199,7 @@ async function readAntigravityQuota(options = {}) {
63767
64199
  const home = options.home ?? homedir11();
63768
64200
  const configuredHome = env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, home);
63769
64201
  const root = configuredHome ? isAbsolute(configuredHome) ? configuredHome : join15(process.cwd(), configuredHome) : join15(home, ".gemini");
63770
- const read = options.readCredentialsFile ?? ((path16) => readFile(path16, "utf8"));
64202
+ const read = options.readCredentialsFile ?? ((path16) => readFile2(path16, "utf8"));
63771
64203
  let credentials = null;
63772
64204
  let authType;
63773
64205
  let storageUnavailable = false;
@@ -63800,9 +64232,9 @@ async function readAntigravityQuota(options = {}) {
63800
64232
  if (!(failure3 instanceof SyntaxError) && asRecord(failure3)?.code !== "ENOENT")
63801
64233
  storageUnavailable = true;
63802
64234
  }
63803
- const identity = createHash5("sha256").update(JSON.stringify([root, authType, credentials?.client_id, credentials?.refresh_token, credentials?.project_id])).digest("hex");
63804
- if (activeSource.identity !== identity)
63805
- activeSource = { identity, epoch: randomBytes6(16).toString("base64url") };
64235
+ const identity2 = createHash5("sha256").update(JSON.stringify([root, authType, credentials?.client_id, credentials?.refresh_token, credentials?.project_id])).digest("hex");
64236
+ if (activeSource.identity !== identity2)
64237
+ activeSource = { identity: identity2, epoch: randomBytes6(16).toString("base64url") };
63806
64238
  const source = activeSource;
63807
64239
  const error62 = (code, retryable = false) => ({ status: "error", sourceEpoch: activeSource.epoch, code: source === activeSource ? code : "unavailable", retryable: source === activeSource ? retryable : true });
63808
64240
  const clientId = text2(credentials?.client_id);
@@ -63885,7 +64317,7 @@ async function readAntigravityQuota(options = {}) {
63885
64317
 
63886
64318
  // agent-driver/dist/provider-quota.js
63887
64319
  import { execFile } from "node:child_process";
63888
- import { readFile as readFile2 } from "node:fs/promises";
64320
+ import { readFile as readFile3 } from "node:fs/promises";
63889
64321
  import { homedir as homedir12 } from "node:os";
63890
64322
  import { join as join16 } from "node:path";
63891
64323
  import { promisify } from "node:util";
@@ -63917,7 +64349,7 @@ async function claudeCredentials(options) {
63917
64349
  const env = options.env ?? process.env;
63918
64350
  const root = env.CLAUDE_CONFIG_DIR || join16(options.home ?? homedir12(), ".claude");
63919
64351
  try {
63920
- const value = options.readCredentialsFile ? await options.readCredentialsFile(join16(root, ".credentials.json")) : await readFile2(join16(root, ".credentials.json"), "utf8");
64352
+ const value = options.readCredentialsFile ? await options.readCredentialsFile(join16(root, ".credentials.json")) : await readFile3(join16(root, ".credentials.json"), "utf8");
63921
64353
  return parseCredentials(value);
63922
64354
  } catch {
63923
64355
  return null;
@@ -64040,7 +64472,7 @@ var MESSAGE_SEND_STDIN_POLICY = [
64040
64472
  " - a short list or table for several exact items, mappings, or comparisons;",
64041
64473
  " - pseudocode for logic, a shallow tree for hierarchy or ownership, Mermaid for sequence or " + "flow, and `diff` for what changed.",
64042
64474
  "- Keep each visual next to the short text it supports. Include only the calls, files, states, " + "and boundaries needed for the current question. Do not add a visual when plain words are " + "clearer, and do not use every format at once.",
64043
- "- The message body is limited to 1 KiB. Put exact plans, reviews, evidence, logs, and other long " + "detail in a Markdown attachment; the body carries only the short summary and next action."
64475
+ "- The message body is limited to 1 KiB. Put exact plans, reviews, evidence, logs, and other long " + "detail in a Markdown attachment; put HTML pages for inline display (charts, diagrams, or interface " + "mockups) in an HTML attachment and reference them in the body using the required inline HTML format; " + "the body carries only the short summary and next action."
64044
64476
  ].join(`
64045
64477
  `);
64046
64478
  function identitySection(config2) {
@@ -64115,7 +64547,7 @@ function cliCommandsSection() {
64115
64547
  "",
64116
64548
  `1. \`${CLI} platform machine --list\` — list your owner's machines.`,
64117
64549
  `2. \`${CLI} platform machine --backends --id <machine-id>\` — read the selected online machine's backends.`,
64118
- `3. \`${CLI} platform machine --models --id <machine-id> --backend <backend-id> [--model <full-model-id>] [--refresh]\` — read reported models and model-specific effort options. \`--refresh\` only dispatches an asynchronous refresh; read once later without \`--refresh\` for the stored report. Do not poll.`,
64550
+ `3. \`${CLI} platform machine --models --id <machine-id> --backend <backend-id> [--model <full-model-id>] [--refresh]\` — read models and model-specific effort options using a five-minute server cache. A cache miss or expiry fetches fresh models and waits for the result; \`--refresh\` bypasses the cache. Failures do not return an old list. Do not poll.`,
64119
64551
  `4. \`${CLI} platform bot --list\` — list your owner's bots.`,
64120
64552
  `5. \`${CLI} platform bot --create '<bot-json>'\` — request new bots for your owner. Each JSON requires \`name\`, \`machineId\`, \`backendId\` and \`reason\`; optional fields are \`description\`, \`model\` and \`reasoningEffort\`. ` + `Use an online machine and its backend. The \`reason\` explains to your owner why the bot is needed and what work it will do; this text appears on the approval card. Repeat \`--create\` for up to 20 bots in one request. ` + `The command submits one approval card to the DM between you and your owner. It creates no bots until your human owner approves the request.`,
64121
64553
  "",
@@ -64167,6 +64599,7 @@ function messagingSection() {
64167
64599
  "",
64168
64600
  `- Send body: use \`${CLI} message send --target <ref> --remind-after T --stdin\` with the ` + "quoted-heredoc form under *Message formatting*.",
64169
64601
  `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` + "add the returned id as `--attachment <id>` on the short stdin send.",
64602
+ `- Inline HTML: upload a self-contained UTF-8 \`<path>.html\` file with \`${CLI} message attachment upload --file <path>.html\`. ` + "Inline CSS and JavaScript in the file; do not depend on local paths on the sender's computer. " + "Include the returned ID with `--attachment <id>` when sending. Put `[alook-html-preview](attachment-id)` " + "in its own paragraph at the intended position in the message, with a blank line before and after; " + "do not put the marker in a code block. " + "Use the Alook theme CSS variables injected by the host on `:root`: " + "`--background`, `--foreground`, `--card`, `--card-foreground`, `--popover`, `--popover-foreground`, " + "`--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`, `--muted`, `--muted-foreground`, " + "`--accent`, `--accent-foreground`, `--border`, `--input`, `--ring`, `--destructive`, `--warning`, " + "`--radius`, `--font-sans`, and `--font-mono`. Use their values directly with `var(...)`; " + "do not hardcode page theme colors to one light or dark scheme. " + "Do not add background colors to `html`, `body`, or the outermost element. Do not add an outer card, " + "border, banner title, or side padding. This rule takes priority over other page-background authoring rules. " + "An internal box that needs a background uses a theme variable, 16px padding, and `var(--radius)` corners. " + "Adapt to the available width and different screen sizes; do not hardcode a desktop page width. " + "Give charts fixed pixel heights. Let content set the page height. Do not use `vh`, `dvh`, `svh`, or `lvh`, " + "and do not set `height:100%` on `html` or `body`. The current preview validator rejects those viewport units; " + "percentage heights on the document roots can cause a measurement loop. " + "Alook measures the frame height automatically in CSS pixels, currently 80–2000px inline. " + "Sending a message requires no height parameter. Keep the original HTML within the current 2 MiB preview limit.",
64170
64603
  "- Reuse files: to forward an attachment or send the same file again, pass its existing ID with `--attachment <id>`. " + "Do not download and upload it again. Reuse works across channels, DMs, and threads while you can still read the file. " + "Upload only a new or changed file.",
64171
64604
  `- Cite a specific message: add \`--reply "#37"\` — \`--reply\` takes the \`#N\` seq ` + "(within `--target`) of the message you're answering.",
64172
64605
  "",
@@ -64448,7 +64881,7 @@ function toLocalISO(iso) {
64448
64881
  }
64449
64882
 
64450
64883
  // src/manager/managerRuntime.ts
64451
- import { randomUUID as randomUUID9 } from "node:crypto";
64884
+ import { randomUUID as randomUUID10 } from "node:crypto";
64452
64885
  var SESSION_STOP_GRACE_MS2 = 2000;
64453
64886
  function normalizeTerminationCause(value) {
64454
64887
  return value === "runtime_error" || value === "killed_stalled" ? value : "other";
@@ -64688,7 +65121,7 @@ class AgentProcessManager {
64688
65121
  shuttingDown = false;
64689
65122
  shutdownPromise;
64690
65123
  publishedAgentActivity = new Map;
64691
- traceProcessNonce = randomUUID9();
65124
+ traceProcessNonce = randomUUID10();
64692
65125
  nextSpawnOrdinal = 1;
64693
65126
  nextDaemonTurnOrdinal = 1;
64694
65127
  nextDeliveryOrdinal = 1;
@@ -64997,7 +65430,7 @@ class AgentProcessManager {
64997
65430
  const session2 = this.sessions.get(agentId);
64998
65431
  if (!session2)
64999
65432
  return;
65000
- const result = await session2.interrupt({ requestId: randomUUID9(), reason: "owner_request" });
65433
+ const result = await session2.interrupt({ requestId: randomUUID10(), reason: "owner_request" });
65001
65434
  if (result.status !== "accepted")
65002
65435
  return;
65003
65436
  this.log.info("agent turn interrupt accepted", {
@@ -65583,7 +66016,7 @@ ${this.opts.wakePromptFooter}` : text3;
65583
66016
  if (!agent2 || agent2.sessionId !== effect.sessionId || agent2.resetting || agent2.idleSince === null)
65584
66017
  break;
65585
66018
  this.deliver(effect.agentId, {
65586
- id: `${effect.agentId}:memory-maintenance:${randomUUID9()}`,
66019
+ id: `${effect.agentId}:memory-maintenance:${randomUUID10()}`,
65587
66020
  text: MEMORY_MAINTENANCE_PROMPT
65588
66021
  });
65589
66022
  break;
@@ -66483,23 +66916,23 @@ class AgentRouter {
66483
66916
  const reply = this.opts.channel.reportRuntimeModels;
66484
66917
  if (!reply)
66485
66918
  return;
66486
- const identity = { type: "runtime_models", requestId: cmd.requestId, runtimeId: cmd.runtimeId };
66919
+ const identity2 = { type: "runtime_models", requestId: cmd.requestId, runtimeId: cmd.runtimeId };
66487
66920
  try {
66488
66921
  const current = this.runtimes.get(cmd.runtimeId);
66489
66922
  if (!current)
66490
66923
  throw new UnknownRuntimeError(cmd.runtimeId, [...this.runtimes.keys()]);
66491
66924
  const probe = await this.discoverRuntimeModels(cmd.runtimeId);
66492
66925
  if (!probe) {
66493
- reply.call(this.opts.channel, { ...identity, result: { status: "error", code: "model_discovery_timeout", message: "Model discovery timed out; retry the request" } });
66926
+ reply.call(this.opts.channel, { ...identity2, result: { status: "error", code: "model_discovery_timeout", message: "Model discovery timed out; retry the request" } });
66494
66927
  return;
66495
66928
  }
66496
66929
  if (probe.status !== "healthy") {
66497
- reply.call(this.opts.channel, { ...identity, result: { status: "error", code: probe.error.code, message: probe.error.message } });
66930
+ reply.call(this.opts.channel, { ...identity2, result: { status: "error", code: probe.error.code, message: probe.error.message } });
66498
66931
  return;
66499
66932
  }
66500
- reply.call(this.opts.channel, { ...identity, result: { status: "complete", runtimeReport: [...this.runtimes.values()] } });
66933
+ reply.call(this.opts.channel, { ...identity2, result: { status: "complete", runtimeReport: [...this.runtimes.values()] } });
66501
66934
  } catch {
66502
- reply.call(this.opts.channel, { ...identity, result: { status: "error", code: "model_discovery_failed", message: "Could not discover models for this runtime" } });
66935
+ reply.call(this.opts.channel, { ...identity2, result: { status: "error", code: "model_discovery_failed", message: "Could not discover models for this runtime" } });
66503
66936
  }
66504
66937
  return;
66505
66938
  }
@@ -66829,11 +67262,11 @@ function timelineRowHash(line) {
66829
67262
  }
66830
67263
  function timelineFileGeneration(filePath, lines) {
66831
67264
  try {
66832
- const stat2 = fs9.lstatSync(filePath, { bigint: true });
66833
- if (!stat2.isFile())
67265
+ const stat3 = fs9.lstatSync(filePath, { bigint: true });
67266
+ if (!stat3.isFile())
66834
67267
  return null;
66835
67268
  const digest = createHash6("sha256");
66836
- digest.update(`${stat2.dev}:${stat2.ino}:${stat2.size}:${stat2.mtimeNs}:${stat2.ctimeNs}
67269
+ digest.update(`${stat3.dev}:${stat3.ino}:${stat3.size}:${stat3.mtimeNs}:${stat3.ctimeNs}
66837
67270
  `);
66838
67271
  for (const line of lines)
66839
67272
  digest.update(line.text, "utf8").update(`
@@ -66933,8 +67366,8 @@ function scanTimelineFile(filePath) {
66933
67366
  let fd = null;
66934
67367
  try {
66935
67368
  fd = fs9.openSync(filePath, fs9.constants.O_RDONLY | (fs9.constants.O_NOFOLLOW ?? 0));
66936
- const stat2 = fs9.fstatSync(fd);
66937
- if (!stat2.isFile())
67369
+ const stat3 = fs9.fstatSync(fd);
67370
+ if (!stat3.isFile())
66938
67371
  return null;
66939
67372
  const chunk2 = Buffer.allocUnsafe(TIMELINE_READ_CHUNK_BYTES);
66940
67373
  const newest = [];
@@ -66947,9 +67380,9 @@ function scanTimelineFile(filePath) {
66947
67380
  let oversized = false;
66948
67381
  let stop = false;
66949
67382
  let discardIncompleteTail = false;
66950
- if (stat2.size > 0) {
67383
+ if (stat3.size > 0) {
66951
67384
  const last = Buffer.allocUnsafe(1);
66952
- fs9.readSync(fd, last, 0, 1, stat2.size - 1);
67385
+ fs9.readSync(fd, last, 0, 1, stat3.size - 1);
66953
67386
  discardIncompleteTail = last[0] !== 10;
66954
67387
  }
66955
67388
  const resetPhysicalLine = () => {
@@ -67008,7 +67441,7 @@ function scanTimelineFile(filePath) {
67008
67441
  }
67009
67442
  resetPhysicalLine();
67010
67443
  };
67011
- let position = stat2.size;
67444
+ let position = stat3.size;
67012
67445
  while (position > 0 && !stop) {
67013
67446
  const start = Math.max(0, position - chunk2.length);
67014
67447
  const requested = position - start;
@@ -67160,11 +67593,11 @@ function readResumeControlState(timelineDir) {
67160
67593
  let fd = null;
67161
67594
  try {
67162
67595
  fd = fs9.openSync(filePath, fs9.constants.O_RDONLY | (fs9.constants.O_NOFOLLOW ?? 0));
67163
- const stat2 = fs9.fstatSync(fd);
67164
- if (!stat2.isFile() || stat2.size <= 0 || stat2.size > RESUME_CONTROL_MAX_BYTES) {
67596
+ const stat3 = fs9.fstatSync(fd);
67597
+ if (!stat3.isFile() || stat3.size <= 0 || stat3.size > RESUME_CONTROL_MAX_BYTES) {
67165
67598
  return { kind: "invalid" };
67166
67599
  }
67167
- const bounded = Buffer.allocUnsafe(stat2.size + 1);
67600
+ const bounded = Buffer.allocUnsafe(stat3.size + 1);
67168
67601
  let bytesRead = 0;
67169
67602
  while (bytesRead < bounded.length) {
67170
67603
  const count2 = fs9.readSync(fd, bounded, bytesRead, bounded.length - bytesRead, bytesRead);
@@ -67172,7 +67605,7 @@ function readResumeControlState(timelineDir) {
67172
67605
  break;
67173
67606
  bytesRead += count2;
67174
67607
  }
67175
- if (bytesRead !== stat2.size)
67608
+ if (bytesRead !== stat3.size)
67176
67609
  return { kind: "invalid" };
67177
67610
  const raw = bounded.subarray(0, bytesRead).toString("utf8");
67178
67611
  const value = JSON.parse(raw);
@@ -68107,7 +68540,7 @@ class MessageReminderScheduler {
68107
68540
  }
68108
68541
 
68109
68542
  // src/manager/agentDriverHost.ts
68110
- import { randomUUID as randomUUID10 } from "node:crypto";
68543
+ import { randomUUID as randomUUID11 } from "node:crypto";
68111
68544
  import { homedir as homedir13 } from "node:os";
68112
68545
  import { join as join18 } from "node:path";
68113
68546
 
@@ -68226,7 +68659,7 @@ function createDaemonAgentDriverHost(ctx, onRawLine) {
68226
68659
  const resource = {
68227
68660
  executablePath: ctx.agentCliPath,
68228
68661
  environmentLayers: {
68229
- base: { ...process.env },
68662
+ base: withoutNpmExecPackage(process.env),
68230
68663
  hostStatic: {},
68231
68664
  identityProtected: buildGitIdentityEnv({
68232
68665
  agentName: ctx.config.agentName,
@@ -68263,12 +68696,12 @@ function createDaemonAgentDriverHost(ctx, onRawLine) {
68263
68696
  onRawLine?.(event.text);
68264
68697
  },
68265
68698
  now: () => Date.now(),
68266
- createId: () => randomUUID10()
68699
+ createId: () => randomUUID11()
68267
68700
  };
68268
68701
  }
68269
68702
 
68270
68703
  // src/daemon/daemonSelfSleep.ts
68271
- var DAEMON_SELF_SLEEP_TIMEOUT_MS = 15 * 24 * 60 * 60 * 1000;
68704
+ var DAEMON_SELF_SLEEP_TIMEOUT_MS = 7 * 24 * 60 * 60 * 1000;
68272
68705
  var systemClock = {
68273
68706
  setTimer: (callback, delayMs) => setTimeout(callback, delayMs),
68274
68707
  clearTimer: (timer) => clearTimeout(timer)
@@ -68340,9 +68773,9 @@ class DaemonSelfSleepScheduler {
68340
68773
  }
68341
68774
 
68342
68775
  // src/telemetry/dailyTokenUsage.ts
68343
- import { chmod, mkdir, open as open3, readFile as readFile3, rename, rm } from "node:fs/promises";
68776
+ import { chmod, mkdir, open as open3, readFile as readFile4, rename, rm } from "node:fs/promises";
68344
68777
  import { dirname as dirname6, join as join19 } from "node:path";
68345
- import { randomUUID as randomUUID11 } from "node:crypto";
68778
+ import { randomUUID as randomUUID12 } from "node:crypto";
68346
68779
  var TOKEN_USAGE_WINDOW_DAYS = 30;
68347
68780
  var TOKEN_USAGE_RECOVERY_DAYS = 2;
68348
68781
  var TOKEN_USAGE_RETENTION_DAYS = TOKEN_USAGE_WINDOW_DAYS + TOKEN_USAGE_RECOVERY_DAYS;
@@ -68409,13 +68842,13 @@ class DailyTokenUsageStore {
68409
68842
  dayKeyInTimeZone(0, timeZone);
68410
68843
  return timeZone;
68411
68844
  }
68412
- record(botId, delta, identity) {
68845
+ record(botId, delta, identity2) {
68413
68846
  return this.enqueue(async () => {
68414
- if (identity) {
68415
- if (!identity.source || identity.source.length > 256 || !Number.isSafeInteger(identity.index) || identity.index < 0 || !Number.isFinite(Date.parse(identity.occurredAt)))
68847
+ if (identity2) {
68848
+ if (!identity2.source || identity2.source.length > 256 || !Number.isSafeInteger(identity2.index) || identity2.index < 0 || !Number.isFinite(Date.parse(identity2.occurredAt)))
68416
68849
  throw new Error("Invalid token usage identity");
68417
- if (!this.pending.some((sample) => sample.botId === botId && sample.identity.source === identity.source && sample.identity.index === identity.index))
68418
- this.pending.push({ botId, delta, identity });
68850
+ if (!this.pending.some((sample) => sample.botId === botId && sample.identity.source === identity2.source && sample.identity.index === identity2.index))
68851
+ this.pending.push({ botId, delta, identity: identity2 });
68419
68852
  await this.load();
68420
68853
  await this.flushPending();
68421
68854
  } else {
@@ -68448,13 +68881,13 @@ class DailyTokenUsageStore {
68448
68881
  throw error62;
68449
68882
  }
68450
68883
  }
68451
- apply(botId, delta, identity) {
68884
+ apply(botId, delta, identity2) {
68452
68885
  const at = this.now();
68453
68886
  const timeZone = this.timeZone;
68454
- const day = dayKeyInTimeZone(identity ? new Date(identity.occurredAt) : at, timeZone);
68455
- if (identity && day < oldestRetainedDay(at, timeZone))
68887
+ const day = dayKeyInTimeZone(identity2 ? new Date(identity2.occurredAt) : at, timeZone);
68888
+ if (identity2 && day < oldestRetainedDay(at, timeZone))
68456
68889
  return;
68457
- if (identity && this.data.sources?.[botId]?.[identity.source]?.ranges.some(([start, end]) => identity.index >= start && identity.index <= end))
68890
+ if (identity2 && this.data.sources?.[botId]?.[identity2.source]?.ranges.some(([start, end]) => identity2.index >= start && identity2.index <= end))
68458
68891
  return;
68459
68892
  this.prune(at, timeZone);
68460
68893
  const snapshots = this.data.bots[botId] ?? [];
@@ -68469,11 +68902,11 @@ class DailyTokenUsageStore {
68469
68902
  snapshots.push(next);
68470
68903
  snapshots.sort((a, b) => a.day.localeCompare(b.day));
68471
68904
  this.data.bots[botId] = snapshots;
68472
- if (identity) {
68905
+ if (identity2) {
68473
68906
  this.data.sources ??= {};
68474
68907
  this.data.sources[botId] ??= {};
68475
- const saved = this.data.sources[botId][identity.source];
68476
- const ranges = [...saved?.ranges ?? [], [identity.index, identity.index]].sort((a, b) => a[0] - b[0]);
68908
+ const saved = this.data.sources[botId][identity2.source];
68909
+ const ranges = [...saved?.ranges ?? [], [identity2.index, identity2.index]].sort((a, b) => a[0] - b[0]);
68477
68910
  const merged = [];
68478
68911
  for (const range of ranges) {
68479
68912
  const last = merged.at(-1);
@@ -68482,7 +68915,7 @@ class DailyTokenUsageStore {
68482
68915
  else
68483
68916
  merged.push([range[0], range[1]]);
68484
68917
  }
68485
- this.data.sources[botId][identity.source] = { ranges: merged, day: saved && saved.day > day ? saved.day : day };
68918
+ this.data.sources[botId][identity2.source] = { ranges: merged, day: saved && saved.day > day ? saved.day : day };
68486
68919
  }
68487
68920
  }
68488
68921
  snapshots(botId) {
@@ -68523,7 +68956,7 @@ class DailyTokenUsageStore {
68523
68956
  return;
68524
68957
  let source;
68525
68958
  try {
68526
- source = await readFile3(this.filePath, "utf8");
68959
+ source = await readFile4(this.filePath, "utf8");
68527
68960
  } catch (error62) {
68528
68961
  if (!error62 || typeof error62 !== "object" || !("code" in error62) || error62.code !== "ENOENT") {
68529
68962
  throw error62;
@@ -68591,7 +69024,7 @@ class DailyTokenUsageStore {
68591
69024
  async persist() {
68592
69025
  const directory = dirname6(this.filePath);
68593
69026
  await mkdir(directory, { recursive: true, mode: 448 });
68594
- const temporary = `${this.filePath}.${randomUUID11()}.tmp`;
69027
+ const temporary = `${this.filePath}.${randomUUID12()}.tmp`;
68595
69028
  try {
68596
69029
  const file2 = await open3(temporary, "wx", 384);
68597
69030
  try {
@@ -69277,10 +69710,10 @@ async function createDaemon(opts) {
69277
69710
  tokenUsageAvailability.set(agentId, { backendId, status });
69278
69711
  reportTelemetryForIdleAgent(agentId);
69279
69712
  },
69280
- onTokenUsage: ({ agentId, usage, identity }) => {
69713
+ onTokenUsage: ({ agentId, usage, identity: identity2 }) => {
69281
69714
  if (usageSealed)
69282
69715
  return;
69283
- trackTelemetry(dailyTokenUsage2.record(agentId, usage, identity).then(() => reportTelemetryForIdleAgent(agentId)).catch(() => {
69716
+ trackTelemetry(dailyTokenUsage2.record(agentId, usage, identity2).then(() => reportTelemetryForIdleAgent(agentId)).catch(() => {
69284
69717
  log2.warn("daily token usage persistence failed", { agentId });
69285
69718
  }));
69286
69719
  },
@@ -69648,12 +70081,12 @@ async function readPinnedJsonFile(args) {
69648
70081
  }
69649
70082
  }
69650
70083
  fd = openSync3(args.path, constants3.O_RDONLY | noFollow);
69651
- const stat2 = fstatSync3(fd);
69652
- if (!stat2.isFile())
70084
+ const stat3 = fstatSync3(fd);
70085
+ if (!stat3.isFile())
69653
70086
  return { value: null, warnings: ["source_unavailable"] };
69654
- if (stat2.size > args.maxBytes)
70087
+ if (stat3.size > args.maxBytes)
69655
70088
  return { value: null, warnings: ["line_too_long"] };
69656
- const bytes = readPinnedBytes(fd, stat2.size);
70089
+ const bytes = readPinnedBytes(fd, stat3.size);
69657
70090
  try {
69658
70091
  return { value: JSON.parse(bytes.toString("utf8")), warnings: [] };
69659
70092
  } catch {
@@ -70193,7 +70626,7 @@ async function buildDiagnosticBundle(args) {
70193
70626
  let truncated = false;
70194
70627
  const counts = { status: args.status ? 1 : 0, daemon_log: 0, fsm: 0 };
70195
70628
  const statusTime = typeof args.status?.timeMs === "number" ? args.status.timeMs : null;
70196
- const envelope2 = () => {
70629
+ const envelope3 = () => {
70197
70630
  const firstEvent = retained[head]?.row.timeMs ?? null;
70198
70631
  const lastEvent = retained.at(-1)?.row.timeMs ?? null;
70199
70632
  const earliestAt = statusTime === null ? firstEvent : firstEvent === null ? statusTime : Math.min(statusTime, firstEvent);
@@ -70224,7 +70657,7 @@ async function buildDiagnosticBundle(args) {
70224
70657
  retained.push({ row, bytes: serialized });
70225
70658
  retainedBytes += serialized.byteLength;
70226
70659
  counts[row.recordType] += 1;
70227
- while (envelope2().total > maxUncompressed && head < retained.length) {
70660
+ while (envelope3().total > maxUncompressed && head < retained.length) {
70228
70661
  const removed = retained[head];
70229
70662
  delete retained[head];
70230
70663
  head += 1;
@@ -70238,7 +70671,7 @@ async function buildDiagnosticBundle(args) {
70238
70671
  head = 0;
70239
70672
  }
70240
70673
  }
70241
- const { footer, total } = envelope2();
70674
+ const { footer, total } = envelope3();
70242
70675
  if (total > maxUncompressed)
70243
70676
  throw new BundleTooLargeError;
70244
70677
  const hash2 = createHash7("sha256");
@@ -70376,8 +70809,8 @@ function createDiagnosticReportCoordinator(args) {
70376
70809
  const sidecarPath = (reportId) => join20(dir, `report-${reportId}.json`);
70377
70810
  const ensureDir = () => {
70378
70811
  if (existsSync9(dir)) {
70379
- const stat2 = lstatSync5(dir);
70380
- if (!stat2.isDirectory() || stat2.isSymbolicLink())
70812
+ const stat3 = lstatSync5(dir);
70813
+ if (!stat3.isDirectory() || stat3.isSymbolicLink())
70381
70814
  throw new CoordinatorError("local_artifact_invalid");
70382
70815
  if (process.platform !== "win32")
70383
70816
  chmodSync3(dir, 448);
@@ -70392,8 +70825,8 @@ function createDiagnosticReportCoordinator(args) {
70392
70825
  };
70393
70826
  const removeExact = (path16) => {
70394
70827
  try {
70395
- const stat2 = lstatSync5(path16);
70396
- if (stat2.isFile() && !stat2.isSymbolicLink())
70828
+ const stat3 = lstatSync5(path16);
70829
+ if (stat3.isFile() && !stat3.isSymbolicLink())
70397
70830
  unlinkSync6(path16);
70398
70831
  } catch {}
70399
70832
  };
@@ -70434,8 +70867,8 @@ function createDiagnosticReportCoordinator(args) {
70434
70867
  const committedArchive = (reportId) => {
70435
70868
  const path16 = archivePath(reportId);
70436
70869
  try {
70437
- const stat2 = lstatSync5(path16);
70438
- if (!stat2.isFile() || stat2.isSymbolicLink())
70870
+ const stat3 = lstatSync5(path16);
70871
+ if (!stat3.isFile() || stat3.isSymbolicLink())
70439
70872
  return null;
70440
70873
  const bytes = readFileSync9(path16);
70441
70874
  return { sizeBytes: bytes.byteLength, sha256: createHash8("sha256").update(bytes).digest("hex") };
@@ -70564,8 +70997,8 @@ function createDiagnosticReportCoordinator(args) {
70564
70997
  const readSidecar = (reportId) => {
70565
70998
  const path16 = sidecarPath(reportId);
70566
70999
  try {
70567
- const stat2 = lstatSync5(path16);
70568
- if (!stat2.isFile() || stat2.isSymbolicLink())
71000
+ const stat3 = lstatSync5(path16);
71001
+ if (!stat3.isFile() || stat3.isSymbolicLink())
70569
71002
  return null;
70570
71003
  return parseSidecar(JSON.parse(readFileSync9(path16, "utf8")));
70571
71004
  } catch {
@@ -70795,8 +71228,8 @@ function tuplesEqual(value, expected) {
70795
71228
  }
70796
71229
  function readIntent(baseDir, machineId) {
70797
71230
  const filePath = intentPath(baseDir, machineId);
70798
- const stat2 = fs10.lstatSync(filePath);
70799
- if (!stat2.isFile())
71231
+ const stat3 = fs10.lstatSync(filePath);
71232
+ if (!stat3.isFile())
70800
71233
  throw new Error("unsafe daemon update intent type");
70801
71234
  fs10.chmodSync(filePath, 384);
70802
71235
  const value = JSON.parse(fs10.readFileSync(filePath, "utf8"));
@@ -70893,10 +71326,10 @@ function readTestPackageMap(baseDir, machineId) {
70893
71326
  const filePath = updatePackageMapPath(baseDir, machineId);
70894
71327
  if (!fs10.existsSync(filePath))
70895
71328
  return null;
70896
- const stat2 = fs10.lstatSync(filePath);
70897
- if (!stat2.isFile())
71329
+ const stat3 = fs10.lstatSync(filePath);
71330
+ if (!stat3.isFile())
70898
71331
  throw new Error("unsafe daemon update package map type");
70899
- if (process.platform !== "win32" && (stat2.mode & 63) !== 0) {
71332
+ if (process.platform !== "win32" && (stat3.mode & 63) !== 0) {
70900
71333
  throw new Error("daemon update package map must be mode 0600");
70901
71334
  }
70902
71335
  const parsed = JSON.parse(fs10.readFileSync(filePath, "utf8"));
@@ -71592,8 +72025,8 @@ function writePrivateJsonAtomic2(filePath, value) {
71592
72025
  function secureExistingFile(filePath) {
71593
72026
  if (!fs12.existsSync(filePath))
71594
72027
  return;
71595
- const stat2 = fs12.lstatSync(filePath);
71596
- if (!stat2.isFile())
72028
+ const stat3 = fs12.lstatSync(filePath);
72029
+ if (!stat3.isFile())
71597
72030
  throw new Error("unsafe daemon ownership file type");
71598
72031
  fs12.chmodSync(filePath, 384);
71599
72032
  }
@@ -71661,8 +72094,8 @@ function readReplacementLock(filePath) {
71661
72094
  if (!fs12.existsSync(filePath))
71662
72095
  return null;
71663
72096
  try {
71664
- const stat2 = fs12.lstatSync(filePath);
71665
- if (!stat2.isFile())
72097
+ const stat3 = fs12.lstatSync(filePath);
72098
+ if (!stat3.isFile())
71666
72099
  throw new Error("unsafe daemon replacement lock type");
71667
72100
  fs12.chmodSync(filePath, 384);
71668
72101
  const content = JSON.parse(fs12.readFileSync(filePath, "utf8"));
@@ -71966,8 +72399,8 @@ function credentialFilePathByMachineId(baseDir, machineId) {
71966
72399
  function readCredentialFile(filePath) {
71967
72400
  if (!fs12.existsSync(filePath))
71968
72401
  return null;
71969
- const stat2 = fs12.lstatSync(filePath);
71970
- if (!stat2.isFile())
72402
+ const stat3 = fs12.lstatSync(filePath);
72403
+ if (!stat3.isFile())
71971
72404
  throw new Error("unsafe daemon credential file type");
71972
72405
  fs12.chmodSync(filePath, 384);
71973
72406
  try {
@@ -72268,6 +72701,7 @@ function runnerArguments() {
72268
72701
  }
72269
72702
  function spawnBlockedRunner() {
72270
72703
  return spawn3(process.execPath, runnerArguments(), {
72704
+ env: withoutNpmExecPackage(process.env),
72271
72705
  detached: true,
72272
72706
  stdio: ["ignore", "ignore", "ignore", "ipc"]
72273
72707
  });
@@ -72788,7 +73222,7 @@ ${MESSAGE_SEND_STDIN_POLICY}`);
72788
73222
  }
72789
73223
  replyToSeq = n;
72790
73224
  }
72791
- const nonce = randomUUID14();
73225
+ const nonce = randomUUID15();
72792
73226
  let res;
72793
73227
  try {
72794
73228
  res = await sendWithRetry(api2, {
@@ -73181,6 +73615,7 @@ function buildProgram(stdin) {
73181
73615
  writeErr: () => {}
73182
73616
  }).option("--agent <id>", "agent identity (or ALOOK_AGENT_ID env)");
73183
73617
  registerPlatformCommands(program, getApi, printEnvelope);
73618
+ registerUseCommands(program, printEnvelope);
73184
73619
  registerPiiCommands(program, printEnvelope);
73185
73620
  const message2 = program.command("message").description("message operations").exitOverride();
73186
73621
  message2.configureOutput({ writeOut: () => {}, writeErr: () => {} });