@alook/daemon 0.1.45 → 0.1.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli/index.js +873 -565
  2. package/dist/index.js +639 -348
  3. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -22343,8 +22343,8 @@ var MAX_PROFILE_ABOUT_LENGTH = 1000;
22343
22343
  var MAX_MESSAGE_CONTENT_LENGTH = 4000;
22344
22344
  var MAX_ATTACHMENTS_PER_MESSAGE = 10;
22345
22345
  var MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024;
22346
- var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 1024;
22347
- var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 512 * 1024;
22346
+ var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 720;
22347
+ var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 256 * 1024;
22348
22348
  var MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024;
22349
22349
  var ALLOWED_ICON_MIME_TYPES = [
22350
22350
  "image/png",
@@ -23020,7 +23020,7 @@ var REASONING_EFFORT_RE = /^[A-Za-z0-9._-]+$/;
23020
23020
  var COMMUNITY_REASONING_EFFORT_MAX = 32;
23021
23021
  var COMMUNITY_REASONING_DESCRIPTION_MAX = 256;
23022
23022
  var COMMUNITY_REASONING_OPTIONS_MAX = 16;
23023
- var COMMUNITY_REASONING_MODELS_MAX = 512;
23023
+ var COMMUNITY_REASONING_MODELS_MAX = 1024;
23024
23024
  var ReasoningEffortSchema = exports_external.string().min(1).max(COMMUNITY_REASONING_EFFORT_MAX).regex(REASONING_EFFORT_RE, "invalid reasoning effort charset");
23025
23025
  var RuntimeReasoningOptionSchema = exports_external.object({
23026
23026
  value: ReasoningEffortSchema,
@@ -23050,18 +23050,22 @@ var RuntimeReasoningModelSchema = exports_external.object({
23050
23050
  var RuntimeReasoningCatalogSchema = exports_external.object({
23051
23051
  updateMode: exports_external.enum(["live_next_turn", "context_preserving_restart", "unsupported"]),
23052
23052
  defaultModelId: exports_external.string().min(1).max(100).optional().catch(undefined),
23053
- models: exports_external.array(exports_external.unknown()).max(COMMUNITY_REASONING_MODELS_MAX).transform((models) => {
23053
+ models: exports_external.array(exports_external.unknown()).transform((models) => {
23054
23054
  const seen = new Set;
23055
- return models.flatMap((candidate) => {
23055
+ const retained = [];
23056
+ for (const candidate of models) {
23056
23057
  const parsed = RuntimeReasoningModelSchema.safeParse(candidate);
23057
23058
  if (!parsed.success)
23058
- return [];
23059
+ continue;
23059
23060
  const model = parsed.data;
23060
23061
  if (seen.has(model.id))
23061
- return [];
23062
+ continue;
23062
23063
  seen.add(model.id);
23063
- return [model];
23064
- });
23064
+ retained.push(model);
23065
+ if (retained.length >= COMMUNITY_REASONING_MODELS_MAX)
23066
+ break;
23067
+ }
23068
+ return retained;
23065
23069
  })
23066
23070
  });
23067
23071
  var CommunityMachineRuntimeSchema = exports_external.object({
@@ -23899,7 +23903,7 @@ function maxRowsPerInsert(paramsPerRow) {
23899
23903
 
23900
23904
  // ../shared/src/db/queries/community/message.ts
23901
23905
  var log = createLogger({ service: "community-queries" });
23902
- var listedMessageProjection = {
23906
+ var messageProjection = {
23903
23907
  id: communityMessage.id,
23904
23908
  authorId: communityMessage.authorId,
23905
23909
  content: communityMessage.content,
@@ -23907,16 +23911,19 @@ var listedMessageProjection = {
23907
23911
  mentionType: communityMessage.mentionType,
23908
23912
  replyToId: communityMessage.replyToId,
23909
23913
  embeds: communityMessage.embeds,
23910
- seq: communityMessage.seq,
23911
23914
  createdAt: communityMessage.createdAt,
23912
23915
  channelId: communityMessage.channelId,
23913
- friendshipId: communityMessage.friendshipId,
23914
- clientNonce: communityMessage.clientNonce,
23915
23916
  authorName: user.name,
23916
- authorEmail: user.email,
23917
23917
  authorImage: user.image,
23918
23918
  authorAvatarVersion: user.avatarVersion
23919
23919
  };
23920
+ var listedMessageProjection = {
23921
+ ...messageProjection,
23922
+ seq: communityMessage.seq,
23923
+ friendshipId: communityMessage.friendshipId,
23924
+ clientNonce: communityMessage.clientNonce,
23925
+ authorEmail: user.email
23926
+ };
23920
23927
  var wakeContextMessageProjection = {
23921
23928
  id: communityMessage.id,
23922
23929
  authorId: communityMessage.authorId,
@@ -24035,26 +24042,207 @@ var AGENT_UNREAD_CHANNEL_CHUNK_SIZE = maxInParams(13);
24035
24042
 
24036
24043
  // ../shared/src/db/queries/community/mention.ts
24037
24044
  var MENTION_INSERT_MAX_ROWS = maxRowsPerInsert(5);
24038
- // ../shared/src/community-ws-events.ts
24039
- var string4 = exports_external.string();
24040
- var nullableString = string4.nullable();
24041
- var channelTypeSchema = exports_external.enum(["text", "forum"]);
24042
- var mentionTypeSchema = exports_external.literal("everyone");
24043
- var friendApprovalProfileSchema = exports_external.strictObject({
24044
- id: string4,
24045
- name: string4,
24046
- discriminator: string4,
24047
- image: nullableString,
24045
+ // ../shared/src/community-friend-approval.ts
24046
+ var profile = exports_external.strictObject({
24047
+ id: exports_external.string(),
24048
+ name: exports_external.string(),
24049
+ discriminator: exports_external.string(),
24050
+ image: exports_external.string().nullable(),
24048
24051
  avatarVersion: exports_external.number().int().nonnegative()
24049
24052
  });
24050
24053
  var FriendApprovalPayloadSchema = exports_external.strictObject({
24051
- friendshipId: string4,
24054
+ friendshipId: exports_external.string(),
24052
24055
  status: exports_external.enum(["pending", "approved", "denied", "superseded", "cancelled"]),
24053
24056
  waitingOn: exports_external.enum(["you", "other-owner", "addressee"]).nullable(),
24054
- otherProfile: friendApprovalProfileSchema,
24055
- botProfile: friendApprovalProfileSchema,
24056
- waitingOnProfile: friendApprovalProfileSchema.nullable().optional()
24057
+ otherProfile: profile,
24058
+ botProfile: profile,
24059
+ waitingOnProfile: profile.nullable().optional()
24060
+ });
24061
+
24062
+ // ../shared/src/community-contract.ts
24063
+ var COMMUNITY_CONTRACT_VERSION = 2;
24064
+
24065
+ // ../shared/src/community-resources.ts
24066
+ var id2 = exports_external.string().min(1);
24067
+ var nullableId = id2.nullable();
24068
+ var legacyArchivedSchema = exports_external.union([exports_external.boolean(), exports_external.literal(0), exports_external.literal(1)]).transform((value) => value === true || value === 1);
24069
+ var CommunityChannelResourceSchema = exports_external.strictObject({
24070
+ id: id2,
24071
+ type: exports_external.enum(["text", "forum", "thread", "dm"]),
24072
+ serverId: nullableId,
24073
+ categoryId: nullableId,
24074
+ name: exports_external.string().nullable(),
24075
+ topic: exports_external.string(),
24076
+ parentChannelId: nullableId,
24077
+ parentMessageId: nullableId,
24078
+ creatorId: nullableId,
24079
+ position: exports_external.number(),
24080
+ archived: exports_external.boolean(),
24081
+ createdAt: exports_external.string(),
24082
+ lastMessageAt: exports_external.string().nullable(),
24083
+ messageCount: exports_external.number().int().nonnegative()
24084
+ });
24085
+ var CommunityChannelIdentitySchema = CommunityChannelResourceSchema.pick({
24086
+ id: true,
24087
+ type: true,
24088
+ serverId: true,
24089
+ name: true,
24090
+ parentChannelId: true,
24091
+ parentMessageId: true,
24092
+ creatorId: true,
24093
+ archived: true,
24094
+ lastMessageAt: true,
24095
+ createdAt: true
24096
+ }).partial({ createdAt: true }).strip();
24097
+ var legacyChannelIdentitySchema = CommunityChannelIdentitySchema.extend({
24098
+ archived: legacyArchivedSchema,
24099
+ parentChannelId: nullableId.default(null),
24100
+ parentMessageId: nullableId.default(null),
24101
+ creatorId: nullableId.default(null),
24102
+ lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null)
24103
+ });
24104
+ var CommunityAccessDecisionSchema = exports_external.strictObject({
24105
+ channelId: id2,
24106
+ canRead: exports_external.boolean(),
24107
+ canSend: exports_external.boolean(),
24108
+ canCreateDiscussion: exports_external.boolean()
24109
+ });
24110
+ var CommunityMessageAttachmentSchema = exports_external.strictObject({
24111
+ kind: exports_external.enum(["image", "file"]),
24112
+ name: exports_external.string(),
24113
+ url: exports_external.string(),
24114
+ thumbnailUrl: exports_external.string().optional(),
24115
+ contentType: exports_external.string().optional(),
24116
+ size: exports_external.string().optional(),
24117
+ sizeBytes: exports_external.number().nonnegative().optional(),
24118
+ width: exports_external.number().nonnegative().optional(),
24119
+ height: exports_external.number().nonnegative().optional()
24120
+ });
24121
+ var CommunityMessageResourceSchema = exports_external.strictObject({
24122
+ id: id2,
24123
+ channelId: id2,
24124
+ seq: exports_external.number().int().nonnegative(),
24125
+ authorId: id2,
24126
+ createdAt: exports_external.string(),
24127
+ type: exports_external.enum(["chat", "system"]),
24128
+ content: exports_external.string(),
24129
+ replyToId: nullableId,
24130
+ clientNonce: exports_external.string().nullable(),
24131
+ attachments: exports_external.array(CommunityMessageAttachmentSchema),
24132
+ systemKind: exports_external.literal("thread").optional(),
24133
+ authorName: exports_external.string().optional(),
24134
+ authorAvatar: exports_external.string().optional(),
24135
+ authorAvatarVersion: exports_external.number().int().nonnegative().optional(),
24136
+ mentionType: exports_external.literal("everyone").nullable().optional(),
24137
+ replyTo: exports_external.strictObject({
24138
+ id: id2,
24139
+ authorId: id2.optional(),
24140
+ authorName: exports_external.string(),
24141
+ text: exports_external.string(),
24142
+ deleted: exports_external.boolean().optional()
24143
+ }).optional(),
24144
+ embeds: exports_external.array(exports_external.unknown()).optional(),
24145
+ reactions: exports_external.array(exports_external.strictObject({
24146
+ emoji: exports_external.string(),
24147
+ count: exports_external.number().int().nonnegative(),
24148
+ me: exports_external.boolean(),
24149
+ userIds: exports_external.array(id2)
24150
+ })).optional(),
24151
+ thread: exports_external.strictObject({
24152
+ id: id2,
24153
+ name: exports_external.string(),
24154
+ messageCount: exports_external.number().int().nonnegative(),
24155
+ lastReplyAt: exports_external.string().optional(),
24156
+ tags: exports_external.array(exports_external.string()).optional(),
24157
+ preview: exports_external.string().optional(),
24158
+ participants: exports_external.array(exports_external.strictObject({ id: id2, name: exports_external.string(), avatar: exports_external.string(), avatarVersion: exports_external.number().int().nonnegative() })).optional(),
24159
+ participantCount: exports_external.number().int().nonnegative().optional()
24160
+ }).optional(),
24161
+ approval: FriendApprovalPayloadSchema.optional()
24162
+ });
24163
+ var CommunityReadStateResourceSchema = exports_external.strictObject({
24164
+ channelId: id2,
24165
+ lastReadMessageId: nullableId,
24166
+ lastReadAt: exports_external.string().nullable(),
24167
+ lastReadSeq: exports_external.number().int().nonnegative()
24168
+ });
24169
+ var CommunityMemberRelationSchema = exports_external.strictObject({
24170
+ channelId: id2,
24171
+ userId: id2,
24172
+ relation: exports_external.enum(["access", "notify"]),
24173
+ source: exports_external.string(),
24174
+ isCreator: exports_external.boolean(),
24175
+ role: exports_external.string().nullable(),
24176
+ memberId: nullableId
24177
+ });
24178
+ var CommunityResourceProfileSchema = exports_external.strictObject({
24179
+ id: id2,
24180
+ name: exports_external.string(),
24181
+ discriminator: exports_external.string().nullable(),
24182
+ avatar: exports_external.string().nullable(),
24183
+ avatarVersion: exports_external.number().int().nonnegative(),
24184
+ statusEmoji: exports_external.string().nullable(),
24185
+ statusText: exports_external.string()
24186
+ });
24187
+ var CommunityPageSchema = exports_external.strictObject({
24188
+ olderCursor: exports_external.string().nullable(),
24189
+ newerCursor: exports_external.string().nullable(),
24190
+ hasMoreOlder: exports_external.boolean(),
24191
+ hasMoreNewer: exports_external.boolean(),
24192
+ latestSeq: exports_external.number().int().nonnegative()
24193
+ });
24194
+ var envelope = { contractVersion: exports_external.literal(COMMUNITY_CONTRACT_VERSION), channelId: id2 };
24195
+ var CommunityChannelReadSchema = exports_external.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema });
24196
+ var CommunityMessagesReadSchema = exports_external.strictObject({
24197
+ ...envelope,
24198
+ messages: exports_external.array(CommunityMessageResourceSchema),
24199
+ page: CommunityPageSchema,
24200
+ surfaceReceipt: exports_external.strictObject({ channelId: id2, surfaceKind: exports_external.enum(["channel", "forum", "thread", "dm"]) })
24201
+ });
24202
+ var CommunityReadStateReadSchema = exports_external.strictObject({ ...envelope, readState: CommunityReadStateResourceSchema });
24203
+ var CommunityMembersReadSchema = exports_external.strictObject({ ...envelope, relation: exports_external.enum(["access", "notify"]), members: exports_external.array(CommunityMemberRelationSchema), profiles: exports_external.array(CommunityResourceProfileSchema) });
24204
+ var CommunityThreadsReadSchema = exports_external.strictObject({
24205
+ ...envelope,
24206
+ channel: CommunityChannelResourceSchema,
24207
+ threads: exports_external.array(CommunityChannelResourceSchema),
24208
+ included: exports_external.strictObject({
24209
+ messages: exports_external.array(CommunityMessageResourceSchema),
24210
+ members: exports_external.array(CommunityMemberRelationSchema),
24211
+ profiles: exports_external.array(CommunityResourceProfileSchema),
24212
+ tags: exports_external.array(exports_external.strictObject({ messageId: id2, tag: exports_external.string() })),
24213
+ participantCounts: exports_external.array(exports_external.strictObject({ channelId: id2, count: exports_external.number().int().nonnegative() }))
24214
+ }),
24215
+ page: exports_external.strictObject({ nextCursor: exports_external.string().nullable(), hasMore: exports_external.boolean() })
24216
+ });
24217
+ var CommunityReadAdvanceSchema = exports_external.strictObject({ ...envelope, changed: exports_external.boolean(), targetSeq: exports_external.number().int().nonnegative(), revision: exports_external.number().int().nonnegative() });
24218
+ var CommunityReadErrorSchema = exports_external.strictObject({ contractVersion: exports_external.literal(COMMUNITY_CONTRACT_VERSION), error: exports_external.strictObject({
24219
+ code: exports_external.enum(["invalid_input", "invalid_reply_target", "unauthenticated", "not_found", "not_allowed", "blocked", "idempotency_conflict", "rate_limited", "temporarily_unavailable"]),
24220
+ message: exports_external.string(),
24221
+ retryable: exports_external.boolean()
24222
+ }) });
24223
+ var legacyChannelResourceSchema = CommunityChannelResourceSchema.strip().extend({
24224
+ topic: CommunityChannelResourceSchema.shape.topic.nullish().transform((value) => value ?? ""),
24225
+ position: CommunityChannelResourceSchema.shape.position.nullish().transform((value) => value ?? 0),
24226
+ messageCount: CommunityChannelResourceSchema.shape.messageCount.nullish().transform((value) => value ?? 0),
24227
+ categoryId: nullableId.default(null),
24228
+ parentChannelId: nullableId.default(null),
24229
+ parentMessageId: nullableId.default(null),
24230
+ creatorId: nullableId.default(null),
24231
+ lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),
24232
+ archived: legacyArchivedSchema
24233
+ });
24234
+ var legacyMessageResourceSchema = CommunityMessageResourceSchema.strip().extend({
24235
+ channelId: id2.optional(),
24236
+ replyToId: nullableId.optional(),
24237
+ clientNonce: CommunityMessageResourceSchema.shape.clientNonce.default(null),
24238
+ attachments: CommunityMessageResourceSchema.shape.attachments.default([]),
24239
+ embeds: CommunityMessageResourceSchema.shape.embeds.nullable().transform((value) => value ?? undefined)
24057
24240
  });
24241
+
24242
+ // ../shared/src/community-ws-events.ts
24243
+ var string4 = exports_external.string();
24244
+ var nullableString = string4.nullable();
24245
+ var channelTypeSchema = CommunityChannelResourceSchema.shape.type.extract(["text", "forum"]);
24058
24246
  var messageAttachmentSchema = exports_external.strictObject({
24059
24247
  id: string4,
24060
24248
  filename: string4,
@@ -24065,30 +24253,29 @@ var messageAttachmentSchema = exports_external.strictObject({
24065
24253
  width: exports_external.number().nullable().optional(),
24066
24254
  height: exports_external.number().nullable().optional()
24067
24255
  });
24068
- var messageSchema = exports_external.strictObject({
24256
+ var messageSchema = CommunityMessageResourceSchema.pick({
24257
+ content: true,
24258
+ type: true,
24259
+ systemKind: true,
24260
+ authorAvatar: true,
24261
+ authorAvatarVersion: true,
24262
+ mentionType: true,
24263
+ embeds: true,
24264
+ createdAt: true,
24265
+ approval: true
24266
+ }).extend({
24069
24267
  id: string4,
24070
24268
  seq: exports_external.number(),
24071
24269
  authorId: string4,
24072
24270
  authorName: string4,
24073
- authorAvatar: string4.optional(),
24074
- authorAvatarVersion: exports_external.number().int().nonnegative(),
24075
- content: string4,
24076
- type: exports_external.enum(["chat", "system"]),
24077
- systemKind: exports_external.literal("thread").optional(),
24078
- mentionType: mentionTypeSchema.nullable().optional(),
24271
+ authorAvatarVersion: CommunityMessageResourceSchema.shape.authorAvatarVersion.unwrap(),
24079
24272
  replyToId: nullableString.optional(),
24080
- replyTo: exports_external.strictObject({
24273
+ replyTo: CommunityMessageResourceSchema.shape.replyTo.unwrap().extend({
24081
24274
  id: string4,
24082
- authorId: string4.optional(),
24083
- authorName: string4,
24084
- text: string4,
24085
- deleted: exports_external.boolean().optional()
24275
+ authorId: string4.optional()
24086
24276
  }).optional(),
24087
- embeds: exports_external.array(exports_external.unknown()).optional(),
24088
24277
  attachments: exports_external.array(messageAttachmentSchema).optional(),
24089
- createdAt: string4,
24090
- clientNonce: string4.optional(),
24091
- approval: FriendApprovalPayloadSchema.optional()
24278
+ clientNonce: string4.optional()
24092
24279
  });
24093
24280
  var communityMessageCreateSchema = exports_external.strictObject({
24094
24281
  type: exports_external.literal("community:message.create"),
@@ -24235,6 +24422,14 @@ var communityChannelMemberRemoveSchema = exports_external.strictObject({
24235
24422
  channelId: string4,
24236
24423
  userId: string4
24237
24424
  });
24425
+ var communityChannelMembershipChangeSchema = exports_external.strictObject({
24426
+ type: exports_external.literal("community:channel.membership.change"),
24427
+ channelId: string4,
24428
+ serverId: string4.nullable(),
24429
+ userId: string4,
24430
+ relation: CommunityMemberRelationSchema.shape.relation,
24431
+ present: exports_external.boolean()
24432
+ });
24238
24433
  var communityCategoryCreateSchema = exports_external.strictObject({
24239
24434
  type: exports_external.literal("community:category.create"),
24240
24435
  serverId: string4,
@@ -24319,7 +24514,8 @@ var communityFriendRemoveSchema = exports_external.strictObject({
24319
24514
  });
24320
24515
  var communityFriendBlockSchema = exports_external.strictObject({
24321
24516
  type: exports_external.literal("community:friend.block"),
24322
- userId: string4
24517
+ userId: string4,
24518
+ blockedByViewer: exports_external.boolean().optional()
24323
24519
  });
24324
24520
  var communityInviteCreateSchema = exports_external.strictObject({
24325
24521
  type: exports_external.literal("community:invite.create"),
@@ -24462,6 +24658,7 @@ var CommunityWsEventDiscriminatedSchema = exports_external.discriminatedUnion("t
24462
24658
  communityChannelReorderSchema,
24463
24659
  communityChannelMemberAddSchema,
24464
24660
  communityChannelMemberRemoveSchema,
24661
+ communityChannelMembershipChangeSchema,
24465
24662
  communityCategoryCreateSchema,
24466
24663
  communityCategoryUpdateSchema,
24467
24664
  communityCategoryDeleteSchema,
@@ -24510,6 +24707,7 @@ var WS_EVENTS = {
24510
24707
  CHANNEL_REORDER: "community:channel.reorder",
24511
24708
  CHANNEL_MEMBER_ADD: "community:channel.member_add",
24512
24709
  CHANNEL_MEMBER_REMOVE: "community:channel.member_remove",
24710
+ CHANNEL_MEMBERSHIP_CHANGE: "community:channel.membership.change",
24513
24711
  CATEGORY_CREATE: "community:category.create",
24514
24712
  CATEGORY_UPDATE: "community:category.update",
24515
24713
  CATEGORY_DELETE: "community:category.delete",
@@ -24579,6 +24777,8 @@ var batchShape = exports_external.strictObject({
24579
24777
  unreadMentionUserIds: targetList,
24580
24778
  mentionUserIds: targetList,
24581
24779
  memberAdded: memberAddedSchema.optional(),
24780
+ joinedParticipantUserIds: targetList.optional(),
24781
+ rosterRefreshUserId: target.optional(),
24582
24782
  parentProjection: exports_external.unknown().optional(),
24583
24783
  parentProjectionUserIds: targetList.optional()
24584
24784
  });
@@ -25311,13 +25511,13 @@ function createProxyServerApi(config2) {
25311
25511
 
25312
25512
  // src/cli/daemonStart.ts
25313
25513
  import * as fs12 from "fs";
25314
- import * as path17 from "path";
25514
+ import * as path18 from "path";
25315
25515
  import * as crypto5 from "crypto";
25316
25516
  import * as os3 from "os";
25317
- import { homedir as homedir11 } from "os";
25517
+ import { homedir as homedir13 } from "os";
25318
25518
 
25319
25519
  // src/discovery.ts
25320
- import * as path13 from "path";
25520
+ import * as path14 from "path";
25321
25521
  import * as fs6 from "fs";
25322
25522
  import { fileURLToPath } from "url";
25323
25523
  // agent-driver/dist/host/default-host.js
@@ -25397,6 +25597,18 @@ function resolveLaunchFieldsOrDefault(input2) {
25397
25597
  // agent-driver/dist/internal/cliLink.js
25398
25598
  import * as fs2 from "fs";
25399
25599
  import * as path2 from "path";
25600
+ function shellQuote(value) {
25601
+ return `'${value.replaceAll("'", "'\\''")}'`;
25602
+ }
25603
+ function writeWindowsBashEnv(binDir, cliName, envPrefix, previous) {
25604
+ const startup = path2.join(binDir, `${cliName}.bash-env`).replaceAll("\\", "/");
25605
+ const envValue = startup.replace(/[$`]/g, "\\$&");
25606
+ const source = previous && previous !== envValue && previous.replaceAll("\\", "/") !== startup ? `. ${shellQuote(previous.replaceAll("\\", "/"))}
25607
+ ` : "";
25608
+ fs2.writeFileSync(startup, source + `export ${shellQuote(`${envPrefix}_CLI=${path2.join(binDir, cliName).replaceAll("\\", "/")}`)}
25609
+ `);
25610
+ return envValue;
25611
+ }
25400
25612
  function writeCliLink(stateDir, cliName, hostCliPath, platform = process.platform) {
25401
25613
  const binDir = path2.join(stateDir, "bin");
25402
25614
  fs2.mkdirSync(binDir, { recursive: true });
@@ -25404,10 +25616,15 @@ function writeCliLink(stateDir, cliName, hostCliPath, platform = process.platfor
25404
25616
  return binDir;
25405
25617
  if (platform === "win32") {
25406
25618
  const cmdFile = path2.join(binDir, `${cliName}.cmd`);
25619
+ const executable = /\.(?:c|m)?js$/i.test(hostCliPath) ? `"${process.execPath}" "${hostCliPath}"` : `"${hostCliPath}"`;
25407
25620
  const body = `@echo off\r
25408
- "${hostCliPath}" %*\r
25621
+ ${executable} %*\r
25409
25622
  `;
25410
25623
  fs2.writeFileSync(cmdFile, body);
25624
+ const bashExecutable = /\.(?:c|m)?js$/i.test(hostCliPath) ? `${shellQuote(process.execPath.replaceAll("\\", "/"))} ${shellQuote(hostCliPath.replaceAll("\\", "/"))}` : shellQuote(hostCliPath.replaceAll("\\", "/"));
25625
+ fs2.writeFileSync(path2.join(binDir, cliName), `#!/bin/sh
25626
+ MSYS2_ARG_CONV_EXCL='*' exec ${bashExecutable} "$@"
25627
+ `, { mode: 493 });
25411
25628
  return binDir;
25412
25629
  }
25413
25630
  const linkPath = path2.join(binDir, cliName);
@@ -25475,7 +25692,12 @@ async function prepareCliTransport(ctx, extraEnv = {}, cli = DEFAULT_CLI_CONFIG,
25475
25692
  {
25476
25693
  name: "platformProtected",
25477
25694
  precedence: 40,
25478
- vars: { ...resource.platformProtected, FORCE_COLOR: "0", NO_COLOR: "1" }
25695
+ vars: {
25696
+ ...resource.platformProtected,
25697
+ ...platform === "win32" && hostCliPath ? { [`${cli.envPrefix}_CLI`]: path3.join(binDir, `${cli.cliName}.cmd`).replaceAll("\\", "/") } : {},
25698
+ FORCE_COLOR: "0",
25699
+ NO_COLOR: "1"
25700
+ }
25479
25701
  },
25480
25702
  { name: "runtimeProtected", precedence: 50, vars: resource.runtimeProtected },
25481
25703
  {
@@ -25492,15 +25714,143 @@ async function prepareCliTransport(ctx, extraEnv = {}, cli = DEFAULT_CLI_CONFIG,
25492
25714
  }
25493
25715
  ];
25494
25716
  const { env: spawnEnv } = mergeEnvLayers(resource.base, layers);
25717
+ if (platform === "win32" && hostCliPath) {
25718
+ spawnEnv.BASH_ENV = writeWindowsBashEnv(binDir, cli.cliName, cli.envPrefix, spawnEnv.BASH_ENV);
25719
+ }
25495
25720
  const tokenFile = String(resource.credentialSensitive.ALOOK_PROXY_TOKEN_FILE ?? "");
25496
25721
  return { stateDir, tokenFile, spawnEnv };
25497
25722
  }
25498
25723
 
25499
25724
  // agent-driver/dist/internal/killTree.js
25500
- import { execFileSync, spawn } from "child_process";
25725
+ import { execFileSync as execFileSync2, spawn } from "child_process";
25501
25726
  import { randomUUID as randomUUID2 } from "node:crypto";
25502
25727
  import { createServer } from "node:net";
25503
25728
  import { PassThrough } from "node:stream";
25729
+
25730
+ // agent-driver/dist/internal/probe.js
25731
+ import { execFileSync } from "child_process";
25732
+ import * as fs4 from "fs";
25733
+ import * as path4 from "path";
25734
+ import { homedir } from "os";
25735
+ var PROBE_TIMEOUT_MS = 5000;
25736
+ var PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
25737
+ function resolveCommandOnPath(command, deps = {}) {
25738
+ if (deps.which)
25739
+ return deps.which(command);
25740
+ try {
25741
+ if (process.platform === "win32") {
25742
+ const out2 = execFileSync("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
25743
+ const first = out2.split(/\r?\n/).map((line) => line.trim()).find((line) => /\.(exe|com|cmd|bat)$/i.test(line));
25744
+ return first || null;
25745
+ }
25746
+ const out = execFileSync("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
25747
+ return out.trim() || null;
25748
+ } catch {
25749
+ return null;
25750
+ }
25751
+ }
25752
+ function firstExistingPath(candidates) {
25753
+ for (const c of candidates) {
25754
+ if (c && fs4.existsSync(c))
25755
+ return c;
25756
+ }
25757
+ return null;
25758
+ }
25759
+ function looksLikeVersion(line) {
25760
+ return /\d+\.\d+/.test(line);
25761
+ }
25762
+ function needsWindowsShimShell(command, platform) {
25763
+ return platform === "win32" && /\.(cmd|bat)$/i.test(command);
25764
+ }
25765
+ function quoteWindowsShimCommand(command, platform = process.platform) {
25766
+ return needsWindowsShimShell(command, platform) && /\s/.test(command) ? `"${command}"` : command;
25767
+ }
25768
+ function probeCommandVersion(command, args = [], deps = {}, platform = process.platform) {
25769
+ try {
25770
+ const shell = needsWindowsShimShell(command, platform);
25771
+ const out = execFileSync(quoteWindowsShimCommand(command, platform), [...args, "--version"], {
25772
+ encoding: "utf8",
25773
+ timeout: PROBE_TIMEOUT_MS,
25774
+ shell,
25775
+ input: "",
25776
+ env: { ...process.env, CI: "1" }
25777
+ });
25778
+ const line = out.split(`
25779
+ `)[0]?.trim();
25780
+ if (!line)
25781
+ return { ok: false, error: "empty_version_output" };
25782
+ if (!looksLikeVersion(line))
25783
+ return { ok: false, error: "invalid_version_output" };
25784
+ return { ok: true, version: line };
25785
+ } catch (err) {
25786
+ const code = err?.code ?? err?.code ?? "version_probe_failed";
25787
+ return { ok: false, error: String(code) };
25788
+ }
25789
+ }
25790
+ function probeCommandOutput(command, args, platform = process.platform) {
25791
+ try {
25792
+ const output2 = execFileSync(quoteWindowsShimCommand(command, platform), args, {
25793
+ encoding: "utf8",
25794
+ timeout: PROBE_TIMEOUT_MS,
25795
+ maxBuffer: PROBE_OUTPUT_MAX_BYTES,
25796
+ shell: needsWindowsShimShell(command, platform),
25797
+ stdio: ["pipe", "pipe", "ignore"],
25798
+ input: "",
25799
+ env: { ...process.env, CI: "1" }
25800
+ });
25801
+ return { ok: true, output: output2 };
25802
+ } catch (err) {
25803
+ const code = err?.code ?? "command_probe_failed";
25804
+ return { ok: false, error: String(code) };
25805
+ }
25806
+ }
25807
+ function resolveHomePath(relativePath, deps = {}) {
25808
+ return path4.join(deps.homeDir || process.env.HOME || ".", relativePath);
25809
+ }
25810
+ function resolveSpawnSpec(command, args, override, deps = {}, platform = process.platform) {
25811
+ const trimmed = override?.trim();
25812
+ const target2 = trimmed && trimmed.length > 0 ? trimmed : command;
25813
+ const looksLikePath = trimmed !== undefined && trimmed.length > 0 && /[\\/]/.test(trimmed);
25814
+ const resolved = looksLikePath ? target2 : resolveCommandOnPath(target2, deps) ?? target2;
25815
+ return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
25816
+ }
25817
+ function resolveClaudeCommand(deps = {}) {
25818
+ const onPath = resolveCommandOnPath("claude", deps);
25819
+ if (onPath)
25820
+ return onPath;
25821
+ if (process.platform === "win32") {
25822
+ const home = deps.homeDir || process.env.USERPROFILE || process.env.HOME || homedir();
25823
+ return firstExistingPath([path4.join(home, ".local", "bin", "claude.exe")]);
25824
+ }
25825
+ if (process.platform === "darwin") {
25826
+ return firstExistingPath([
25827
+ resolveHomePath("Applications/Claude Code URL Handler.app/Contents/MacOS/claude", deps),
25828
+ "/Applications/Claude Code URL Handler.app/Contents/MacOS/claude"
25829
+ ]);
25830
+ }
25831
+ return null;
25832
+ }
25833
+ function probeClaude(deps = {}) {
25834
+ const command = resolveClaudeCommand(deps);
25835
+ if (!command)
25836
+ return { status: "unhealthy", lastError: "not_on_path" };
25837
+ const r = probeCommandVersion(command, [], deps);
25838
+ if (!r.ok)
25839
+ return { status: "unhealthy", lastError: r.error };
25840
+ return { status: "healthy", version: r.version };
25841
+ }
25842
+ function probeCliRuntime(binary, deps = {}, override) {
25843
+ const explicit = override?.trim();
25844
+ const command = explicit || resolveCommandOnPath(binary, deps);
25845
+ if (!command)
25846
+ return { status: "unhealthy", lastError: "not_on_path" };
25847
+ const r = probeCommandVersion(command, [], deps);
25848
+ if (!r.ok)
25849
+ return { status: "unhealthy", lastError: r.error };
25850
+ return { status: "healthy", version: r.version };
25851
+ }
25852
+
25853
+ // agent-driver/dist/internal/killTree.js
25504
25854
  var POLL_MS = 100;
25505
25855
  var FORCE_EXIT_WAIT_MS = 2000;
25506
25856
  var TASKKILL_WAIT_MS = 2000;
@@ -25850,7 +26200,7 @@ function spawnAgentProcess(command, args, opts) {
25850
26200
  const env = {
25851
26201
  ...opts.env,
25852
26202
  [WINDOWS_JOB_NODE_ENV]: process.execPath,
25853
- [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
26203
+ [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command: opts.shell ? quoteWindowsShimCommand(command) : command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
25854
26204
  [WINDOWS_JOB_RUNNER_ENV]: WINDOWS_JOB_RUNNER,
25855
26205
  ...stdinPipe ? { [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe } : {}
25856
26206
  };
@@ -25912,7 +26262,7 @@ function capturePosixTreeTargets(rootPid, rootOwnsProcessGroup) {
25912
26262
  });
25913
26263
  let output2;
25914
26264
  try {
25915
- output2 = execFileSync("ps", ["-axo", "pid=,ppid=,pgid="], {
26265
+ output2 = execFileSync2("ps", ["-axo", "pid=,ppid=,pgid="], {
25916
26266
  encoding: "utf8",
25917
26267
  timeout: POSIX_TREE_CAPTURE_TIMEOUT_MS,
25918
26268
  maxBuffer: POSIX_TREE_CAPTURE_MAX_BUFFER
@@ -25976,6 +26326,9 @@ function signalPosixTargets(targets, signal) {
25976
26326
  } catch {}
25977
26327
  }
25978
26328
  }
26329
+
26330
+ class WindowsTreeExitError extends Error {
26331
+ }
25979
26332
  function taskkillTree(pid) {
25980
26333
  return new Promise((resolve, reject) => {
25981
26334
  const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
@@ -26006,17 +26359,24 @@ function taskkillTree(pid) {
26006
26359
  settle2("resolve");
26007
26360
  return;
26008
26361
  }
26009
- settle2("reject", new Error(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`));
26362
+ settle2("reject", new WindowsTreeExitError(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`));
26010
26363
  });
26011
26364
  });
26012
26365
  }
26013
26366
  async function killWindowsProcessTree(pid) {
26014
26367
  if (!isAlive(pid))
26015
26368
  return;
26016
- await taskkillTree(pid);
26369
+ let terminationError;
26370
+ try {
26371
+ await taskkillTree(pid);
26372
+ } catch (error62) {
26373
+ if (!(error62 instanceof WindowsTreeExitError))
26374
+ throw error62;
26375
+ terminationError = error62;
26376
+ }
26017
26377
  await waitForProcessExit(pid, FORCE_EXIT_WAIT_MS);
26018
26378
  if (isAlive(pid))
26019
- throw new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
26379
+ throw terminationError ?? new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
26020
26380
  }
26021
26381
  async function waitForProcessExit(pid, timeoutMs) {
26022
26382
  const deadline = Date.now() + timeoutMs;
@@ -26059,8 +26419,8 @@ async function killProcessTree(pid, opts) {
26059
26419
 
26060
26420
  // agent-driver/dist/adapters/antigravity/usage.js
26061
26421
  import { createHash } from "node:crypto";
26062
- import { homedir } from "node:os";
26063
- import { resolve, join as join3 } from "node:path";
26422
+ import { homedir as homedir2 } from "node:os";
26423
+ import { resolve, join as join4 } from "node:path";
26064
26424
 
26065
26425
  // agent-driver/dist/adapters/antigravity/local-data.js
26066
26426
  async function readLocalCommand(command, args, limit = 256 * 1024) {
@@ -26158,7 +26518,7 @@ function parseNativeGeneration(data) {
26158
26518
  return { usage: { input: count(usage, 2), output: count(usage, 3), cache: count(usage, 5) }, occurredAt };
26159
26519
  }
26160
26520
  function nativeUsageHome(env, cwd) {
26161
- return resolve(cwd, env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, homedir()) || join3(homedir(), ".gemini"));
26521
+ return resolve(cwd, env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, homedir2()) || join4(homedir2(), ".gemini"));
26162
26522
  }
26163
26523
  var QUERY = "WITH pending AS (SELECT idx,data FROM gen_metadata WHERE idx>? ORDER BY idx LIMIT 128), batch AS (SELECT idx,data,sum(length(data)) OVER (ORDER BY idx) AS bytes FROM pending) SELECT idx,hex(substr(data,1,4194305)) AS data,(SELECT COUNT(*) FROM steps WHERE has_subtrajectory=1) AS has_children FROM batch WHERE bytes<=4194304 OR idx=(SELECT min(idx) FROM batch) ORDER BY idx";
26164
26524
 
@@ -26176,12 +26536,12 @@ class NativeUsageReader {
26176
26536
  throw new Error("Invalid native usage session identity");
26177
26537
  }
26178
26538
  async read() {
26179
- const path4 = join3(this.home, "antigravity-acp", "conversations", `${this.sessionId}.db`);
26539
+ const path5 = join4(this.home, "antigravity-acp", "conversations", `${this.sessionId}.db`);
26180
26540
  let cursor = this.cursor;
26181
26541
  let complete = false;
26182
26542
  const result = [];
26183
26543
  for (let batch = 0;batch < 16; batch++) {
26184
- const rows = await this.readRows(path4, cursor);
26544
+ const rows = await this.readRows(path5, cursor);
26185
26545
  for (const row of rows) {
26186
26546
  if (!Number.isSafeInteger(row.idx) || row.idx <= cursor || !/^(?:[a-f0-9]{2})*$/i.test(row.data) || row.data.length > 8 * 1024 * 1024)
26187
26547
  throw new Error("Invalid native usage row");
@@ -26202,11 +26562,11 @@ class NativeUsageReader {
26202
26562
  return { samples: result, complete, ...this.childTrajectories ? { incompleteScope: true } : {} };
26203
26563
  }
26204
26564
  }
26205
- async function queryNativeRowsWithCli(path4, cursor) {
26206
- const output2 = await readLocalCommand("sqlite3", ["-readonly", "-json", path4, QUERY.replace("idx>?", `idx>${cursor}`)], 16 * 1024 * 1024);
26565
+ async function queryNativeRowsWithCli(path5, cursor) {
26566
+ const output2 = await readLocalCommand("sqlite3", ["-readonly", "-json", path5, QUERY.replace("idx>?", `idx>${cursor}`)], 16 * 1024 * 1024);
26207
26567
  return output2.trim() ? JSON.parse(output2) : [];
26208
26568
  }
26209
- async function queryNativeRows(path4, cursor, loadSqlite = async () => {
26569
+ async function queryNativeRows(path5, cursor, loadSqlite = async () => {
26210
26570
  const module = "node:sqlite";
26211
26571
  return await import(module);
26212
26572
  }) {
@@ -26214,9 +26574,9 @@ async function queryNativeRows(path4, cursor, loadSqlite = async () => {
26214
26574
  try {
26215
26575
  sqlite = await loadSqlite();
26216
26576
  } catch {
26217
- return queryNativeRowsWithCli(path4, cursor);
26577
+ return queryNativeRowsWithCli(path5, cursor);
26218
26578
  }
26219
- const db = new sqlite.DatabaseSync(path4, { readOnly: true });
26579
+ const db = new sqlite.DatabaseSync(path5, { readOnly: true });
26220
26580
  try {
26221
26581
  return db.prepare(QUERY).all(cursor);
26222
26582
  } finally {
@@ -26225,27 +26585,27 @@ async function queryNativeRows(path4, cursor, loadSqlite = async () => {
26225
26585
  }
26226
26586
 
26227
26587
  // agent-driver/dist/internal/modelCatalog.js
26228
- var RUNTIME_MODEL_CATALOG_MAX = 512;
26588
+ var RUNTIME_MODEL_CATALOG_MAX = 1024;
26229
26589
  var RUNTIME_MODEL_ID_MAX = 100;
26230
26590
  function normalizeRuntimeModelId(value) {
26231
26591
  if (typeof value !== "string")
26232
26592
  return;
26233
- const id2 = value.trim();
26234
- if (!id2 || id2.length > RUNTIME_MODEL_ID_MAX || /\s/.test(id2))
26593
+ const id3 = value.trim();
26594
+ if (!id3 || id3.length > RUNTIME_MODEL_ID_MAX || /\s/.test(id3))
26235
26595
  return;
26236
- return id2;
26596
+ return id3;
26237
26597
  }
26238
26598
  function catalogFromIds(ids) {
26239
26599
  const seen = new Set;
26240
26600
  const models = [];
26241
26601
  for (const rawId of ids) {
26242
- const id2 = normalizeRuntimeModelId(rawId);
26243
- if (!id2 || seen.has(id2))
26602
+ const id3 = normalizeRuntimeModelId(rawId);
26603
+ if (!id3 || seen.has(id3))
26244
26604
  continue;
26245
26605
  if (models.length >= RUNTIME_MODEL_CATALOG_MAX)
26246
- return;
26247
- seen.add(id2);
26248
- models.push({ id: id2, supportedReasoningEfforts: [] });
26606
+ break;
26607
+ seen.add(id3);
26608
+ models.push({ id: id3, supportedReasoningEfforts: [] });
26249
26609
  }
26250
26610
  if (models.length === 0)
26251
26611
  return;
@@ -26253,8 +26613,8 @@ function catalogFromIds(ids) {
26253
26613
  }
26254
26614
  function parseOpenCodeModelCatalog(output2) {
26255
26615
  const ids = output2.split(/\r?\n/).flatMap((line) => {
26256
- const id2 = normalizeRuntimeModelId(line);
26257
- return id2 && /^[^/]+\/.+$/.test(id2) ? [id2] : [];
26616
+ const id3 = normalizeRuntimeModelId(line);
26617
+ return id3 && /^[^/]+\/.+$/.test(id3) ? [id3] : [];
26258
26618
  });
26259
26619
  return catalogFromIds(ids);
26260
26620
  }
@@ -26266,16 +26626,16 @@ function parsePiModelCatalog(values) {
26266
26626
  return [];
26267
26627
  const model = value;
26268
26628
  const provider = normalizeRuntimeModelId(model.provider);
26269
- const id2 = normalizeRuntimeModelId(model.id);
26270
- return provider && id2 && !provider.includes("/") ? [`${provider}/${id2}`] : [];
26629
+ const id3 = normalizeRuntimeModelId(model.id);
26630
+ return provider && id3 && !provider.includes("/") ? [`${provider}/${id3}`] : [];
26271
26631
  });
26272
26632
  return catalogFromIds(ids);
26273
26633
  }
26274
26634
 
26275
26635
  // agent-driver/dist/internal/utils.js
26276
26636
  import { randomUUID as randomUUID3 } from "crypto";
26277
- function jsonRpcRequest(method, params, id2) {
26278
- return JSON.stringify({ jsonrpc: "2.0", id: id2 ?? randomUUID3(), method, params });
26637
+ function jsonRpcRequest(method, params, id3) {
26638
+ return JSON.stringify({ jsonrpc: "2.0", id: id3 ?? randomUUID3(), method, params });
26279
26639
  }
26280
26640
  function tryParseJsonLine(line) {
26281
26641
  try {
@@ -26293,26 +26653,28 @@ function tryParseJsonRecord(line) {
26293
26653
 
26294
26654
  // agent-driver/dist/adapters/antigravity/catalog.js
26295
26655
  function choices(value) {
26296
- if (!Array.isArray(value) || value.length > RUNTIME_MODEL_CATALOG_MAX)
26656
+ if (!Array.isArray(value))
26297
26657
  return [];
26298
26658
  const rows = [];
26659
+ const seen = new Set;
26299
26660
  for (const item of value) {
26300
26661
  const row = asRecord(item);
26301
26662
  if (!row)
26302
26663
  continue;
26303
26664
  const nested2 = Array.isArray(row.options) ? row.options : [row];
26304
- if (nested2.length + rows.length > RUNTIME_MODEL_CATALOG_MAX)
26305
- return [];
26306
26665
  for (const child of nested2) {
26307
26666
  const option = asRecord(child);
26308
- const id2 = normalizeRuntimeModelId(option?.value ?? option?.modelId);
26309
- if (!id2)
26667
+ const id3 = normalizeRuntimeModelId(option?.value ?? option?.modelId);
26668
+ if (!id3 || seen.has(id3))
26310
26669
  continue;
26670
+ seen.add(id3);
26311
26671
  const name = option?.name;
26312
- rows.push({ id: id2, ...typeof name === "string" && name.length <= 256 ? { displayName: name } : {} });
26672
+ rows.push({ id: id3, ...typeof name === "string" && name.length <= 256 ? { displayName: name } : {} });
26673
+ if (rows.length >= RUNTIME_MODEL_CATALOG_MAX)
26674
+ return rows;
26313
26675
  }
26314
26676
  }
26315
- return rows.filter((row, index2) => rows.findIndex((other) => other.id === row.id) === index2);
26677
+ return rows;
26316
26678
  }
26317
26679
  function parseAntigravityCatalog(value) {
26318
26680
  const session2 = asRecord(value);
@@ -26329,8 +26691,8 @@ function parseAntigravityCatalog(value) {
26329
26691
  ...configId ? { configId } : {}
26330
26692
  };
26331
26693
  }
26332
- function variant(id2) {
26333
- const match = /^(gemini-[a-z0-9.-]+)-(high|medium|low)$/.exec(id2);
26694
+ function variant(id3) {
26695
+ const match = /^(gemini-[a-z0-9.-]+)-(high|medium|low)$/.exec(id3);
26334
26696
  return match ? { family: match[1], effort: match[2] } : undefined;
26335
26697
  }
26336
26698
  function antigravityReasoningCatalog(catalog) {
@@ -26746,7 +27108,7 @@ class AntigravityAcpLane {
26746
27108
  return this.request(method, params, this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS).promise;
26747
27109
  }
26748
27110
  request(method, params, timeoutMs) {
26749
- const id2 = ++this.requestSequence;
27111
+ const id3 = ++this.requestSequence;
26750
27112
  let resolve2;
26751
27113
  let reject;
26752
27114
  const promise2 = new Promise((accept, decline) => {
@@ -26754,24 +27116,24 @@ class AntigravityAcpLane {
26754
27116
  reject = decline;
26755
27117
  });
26756
27118
  const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
26757
- const pending = this.pending.get(id2);
27119
+ const pending = this.pending.get(id3);
26758
27120
  if (!pending || pending.kind !== "call")
26759
27121
  return;
26760
- this.pending.delete(id2);
27122
+ this.pending.delete(id3);
26761
27123
  pending.reject(new Error(`Antigravity ACP ${method} timed out`));
26762
27124
  }, timeoutMs);
26763
27125
  timer?.unref?.();
26764
- this.pending.set(id2, { kind: "call", method, resolve: resolve2, reject, ...timer ? { timer } : {} });
27126
+ this.pending.set(id3, { kind: "call", method, resolve: resolve2, reject, ...timer ? { timer } : {} });
26765
27127
  try {
26766
- this.write({ jsonrpc: "2.0", id: id2, method, params });
27128
+ this.write({ jsonrpc: "2.0", id: id3, method, params });
26767
27129
  } catch (error62) {
26768
- const pending = this.pending.get(id2);
26769
- this.pending.delete(id2);
27130
+ const pending = this.pending.get(id3);
27131
+ this.pending.delete(id3);
26770
27132
  if (pending?.kind === "call" && pending.timer)
26771
27133
  clearTimeout(pending.timer);
26772
27134
  throw error62 instanceof Error ? error62 : new Error(String(error62));
26773
27135
  }
26774
- return { id: id2, promise: promise2 };
27136
+ return { id: id3, promise: promise2 };
26775
27137
  }
26776
27138
  write(message2) {
26777
27139
  const stdin = this.process?.stdin;
@@ -26882,14 +27244,14 @@ class AntigravityAcpLane {
26882
27244
  }
26883
27245
  this.protocolFailure("Antigravity ACP emitted an unrecognized JSON-RPC message");
26884
27246
  }
26885
- handleResponse(id2, message2) {
26886
- const pending = typeof id2 === "number" ? this.pending.get(id2) : undefined;
26887
- if (typeof id2 !== "number" || !pending) {
27247
+ handleResponse(id3, message2) {
27248
+ const pending = typeof id3 === "number" ? this.pending.get(id3) : undefined;
27249
+ if (typeof id3 !== "number" || !pending) {
26888
27250
  this.diagnostic("warning", "Antigravity ACP emitted a duplicate or unknown response id");
26889
27251
  return;
26890
27252
  }
26891
27253
  if (pending.kind === "prompt") {
26892
- this.pending.delete(id2);
27254
+ this.pending.delete(id3);
26893
27255
  const finish = () => {
26894
27256
  if (message2.error !== undefined) {
26895
27257
  const payload = record2(message2.error);
@@ -26933,23 +27295,23 @@ class AntigravityAcpLane {
26933
27295
  if (message2.error !== undefined) {
26934
27296
  const payload = record2(message2.error);
26935
27297
  if (/authentication required|not authenticated|login required/i.test(rpcErrorMessage(message2.error))) {
26936
- this.settleRequest(id2, false, new AntigravityAcpAuthenticationError("Antigravity ACP requires local authentication; complete its Google sign-in before starting this agent"));
27298
+ this.settleRequest(id3, false, new AntigravityAcpAuthenticationError("Antigravity ACP requires local authentication; complete its Google sign-in before starting this agent"));
26937
27299
  return;
26938
27300
  }
26939
- this.settleRequest(id2, false, new AntigravityAcpRpcError(pending.method, typeof payload?.code === "number" ? payload.code : undefined, rpcErrorMessage(message2.error)));
27301
+ this.settleRequest(id3, false, new AntigravityAcpRpcError(pending.method, typeof payload?.code === "number" ? payload.code : undefined, rpcErrorMessage(message2.error)));
26940
27302
  return;
26941
27303
  }
26942
27304
  if (!("result" in message2)) {
26943
- this.settleRequest(id2, false, new Error("Antigravity ACP response omitted result"));
27305
+ this.settleRequest(id3, false, new Error("Antigravity ACP response omitted result"));
26944
27306
  return;
26945
27307
  }
26946
- this.settleRequest(id2, true, message2.result);
27308
+ this.settleRequest(id3, true, message2.result);
26947
27309
  }
26948
- settleRequest(id2, ok, value) {
26949
- const pending = this.pending.get(id2);
27310
+ settleRequest(id3, ok, value) {
27311
+ const pending = this.pending.get(id3);
26950
27312
  if (!pending || pending.kind !== "call")
26951
27313
  return;
26952
- this.pending.delete(id2);
27314
+ this.pending.delete(id3);
26953
27315
  if (pending.timer)
26954
27316
  clearTimeout(pending.timer);
26955
27317
  if (ok)
@@ -26957,11 +27319,11 @@ class AntigravityAcpLane {
26957
27319
  else
26958
27320
  pending.reject(value instanceof Error ? value : new Error(String(value)));
26959
27321
  }
26960
- handleRequest(id2, method, params) {
27322
+ handleRequest(id3, method, params) {
26961
27323
  if (method !== "session/request_permission") {
26962
27324
  this.write({
26963
27325
  jsonrpc: "2.0",
26964
- id: id2,
27326
+ id: id3,
26965
27327
  error: { code: -32601, message: "Unsupported Antigravity ACP client request" }
26966
27328
  });
26967
27329
  this.diagnostic("warning", `Unsupported Antigravity ACP client request: ${safeLabel(method)}`);
@@ -26972,13 +27334,13 @@ class AntigravityAcpLane {
26972
27334
  const options = Array.isArray(payload?.options) ? payload.options.map(record2).filter(Boolean) : [];
26973
27335
  const allowOnce = options.find((option) => option.kind === "allow_once" && typeof option.optionId === "string" && option.optionId.trim().length > 0);
26974
27336
  if (!this.ready || this.cancelling || this.currentPromptRequestId === null || !sameSession || !allowOnce) {
26975
- this.write({ jsonrpc: "2.0", id: id2, result: { outcome: { outcome: "cancelled" } } });
27337
+ this.write({ jsonrpc: "2.0", id: id3, result: { outcome: { outcome: "cancelled" } } });
26976
27338
  this.diagnostic("error", "Antigravity ACP permission request was not allowed for the active prompt");
26977
27339
  return;
26978
27340
  }
26979
27341
  this.write({
26980
27342
  jsonrpc: "2.0",
26981
- id: id2,
27343
+ id: id3,
26982
27344
  result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } }
26983
27345
  });
26984
27346
  }
@@ -27085,8 +27447,8 @@ class AntigravityAcpLane {
27085
27447
  this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});
27086
27448
  }
27087
27449
  rejectAllPending(error62) {
27088
- for (const [id2, pending] of [...this.pending]) {
27089
- this.pending.delete(id2);
27450
+ for (const [id3, pending] of [...this.pending]) {
27451
+ this.pending.delete(id3);
27090
27452
  if (pending.kind === "call") {
27091
27453
  if (pending.timer)
27092
27454
  clearTimeout(pending.timer);
@@ -27102,132 +27464,15 @@ class AntigravityAcpLane {
27102
27464
  // agent-driver/dist/adapters/antigravity/probe.js
27103
27465
  import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
27104
27466
  import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
27105
- import { homedir as homedir2 } from "node:os";
27467
+ import { homedir as homedir3 } from "node:os";
27106
27468
  import { join as join5 } from "node:path";
27107
-
27108
- // agent-driver/dist/internal/probe.js
27109
- import { execFileSync as execFileSync2 } from "child_process";
27110
- import * as fs4 from "fs";
27111
- import * as path4 from "path";
27112
- var PROBE_TIMEOUT_MS = 5000;
27113
- var PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
27114
- function resolveCommandOnPath(command, deps = {}) {
27115
- if (deps.which)
27116
- return deps.which(command);
27117
- try {
27118
- if (process.platform === "win32") {
27119
- const out2 = execFileSync2("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
27120
- const first = out2.split(/\r?\n/).find((line) => line.trim().length > 0);
27121
- return first?.trim() || null;
27122
- }
27123
- const out = execFileSync2("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
27124
- return out.trim() || null;
27125
- } catch {
27126
- return null;
27127
- }
27128
- }
27129
- function firstExistingPath(candidates) {
27130
- for (const c of candidates) {
27131
- if (c && fs4.existsSync(c))
27132
- return c;
27133
- }
27134
- return null;
27135
- }
27136
- function looksLikeVersion(line) {
27137
- return /\d+\.\d+/.test(line);
27138
- }
27139
- function needsWindowsShimShell(command, platform) {
27140
- return platform === "win32" && /\.(cmd|bat)$/i.test(command);
27141
- }
27142
- function probeCommandVersion(command, args = [], deps = {}, platform = process.platform) {
27143
- try {
27144
- const shell = needsWindowsShimShell(command, platform);
27145
- const out = execFileSync2(command, [...args, "--version"], {
27146
- encoding: "utf8",
27147
- timeout: PROBE_TIMEOUT_MS,
27148
- shell,
27149
- input: "",
27150
- env: { ...process.env, CI: "1" }
27151
- });
27152
- const line = out.split(`
27153
- `)[0]?.trim();
27154
- if (!line)
27155
- return { ok: false, error: "empty_version_output" };
27156
- if (!looksLikeVersion(line))
27157
- return { ok: false, error: "invalid_version_output" };
27158
- return { ok: true, version: line };
27159
- } catch (err) {
27160
- const code = err?.code ?? err?.code ?? "version_probe_failed";
27161
- return { ok: false, error: String(code) };
27162
- }
27163
- }
27164
- function probeCommandOutput(command, args, platform = process.platform) {
27165
- try {
27166
- const output2 = execFileSync2(command, args, {
27167
- encoding: "utf8",
27168
- timeout: PROBE_TIMEOUT_MS,
27169
- maxBuffer: PROBE_OUTPUT_MAX_BYTES,
27170
- shell: needsWindowsShimShell(command, platform),
27171
- stdio: ["pipe", "pipe", "ignore"],
27172
- input: "",
27173
- env: { ...process.env, CI: "1" }
27174
- });
27175
- return { ok: true, output: output2 };
27176
- } catch (err) {
27177
- const code = err?.code ?? "command_probe_failed";
27178
- return { ok: false, error: String(code) };
27179
- }
27180
- }
27181
- function resolveHomePath(relativePath, deps = {}) {
27182
- return path4.join(deps.homeDir || process.env.HOME || ".", relativePath);
27183
- }
27184
- function resolveSpawnSpec(command, args, override, deps = {}, platform = process.platform) {
27185
- const trimmed = override?.trim();
27186
- const target2 = trimmed && trimmed.length > 0 ? trimmed : command;
27187
- const looksLikePath = trimmed !== undefined && trimmed.length > 0 && /[\\/]/.test(trimmed);
27188
- const resolved = looksLikePath ? target2 : resolveCommandOnPath(target2, deps) ?? target2;
27189
- return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
27190
- }
27191
- function resolveClaudeCommand(deps = {}) {
27192
- const onPath = resolveCommandOnPath("claude", deps);
27193
- if (onPath)
27194
- return onPath;
27195
- if (process.platform === "darwin") {
27196
- return firstExistingPath([
27197
- resolveHomePath("Applications/Claude Code URL Handler.app/Contents/MacOS/claude", deps),
27198
- "/Applications/Claude Code URL Handler.app/Contents/MacOS/claude"
27199
- ]);
27200
- }
27201
- return null;
27202
- }
27203
- function probeClaude(deps = {}) {
27204
- const command = resolveClaudeCommand(deps);
27205
- if (!command)
27206
- return { status: "unhealthy", lastError: "not_on_path" };
27207
- const r = probeCommandVersion(command, [], deps);
27208
- if (!r.ok)
27209
- return { status: "unhealthy", lastError: r.error };
27210
- return { status: "healthy", version: r.version };
27211
- }
27212
- function probeCliRuntime(binary, deps = {}, override) {
27213
- const explicit = override?.trim();
27214
- const command = explicit || resolveCommandOnPath(binary, deps);
27215
- if (!command)
27216
- return { status: "unhealthy", lastError: "not_on_path" };
27217
- const r = probeCommandVersion(command, [], deps);
27218
- if (!r.ok)
27219
- return { status: "unhealthy", lastError: r.error };
27220
- return { status: "healthy", version: r.version };
27221
- }
27222
-
27223
- // agent-driver/dist/adapters/antigravity/probe.js
27224
27469
  function antigravitySpawnSpec(command, platform = process.platform) {
27225
27470
  return resolveSpawnSpec(platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par", platform === "linux" ? ["--uid="] : [], command);
27226
27471
  }
27227
27472
  async function probeAntigravity(command, options = {}) {
27228
27473
  const spec = antigravitySpawnSpec(command);
27229
27474
  const identity = createHash2("sha256").update(JSON.stringify([spec.command, process.env.GEMINI_HOME ?? ""])).digest("hex").slice(0, 16);
27230
- const directory = options.cacheDirectory ?? join5(homedir2(), ".cache", "alook", "antigravity-probe", identity);
27475
+ const directory = options.cacheDirectory ?? join5(homedir3(), ".cache", "alook", "antigravity-probe", identity);
27231
27476
  const cacheFile = join5(directory, "session");
27232
27477
  let cachedSessionId;
27233
27478
  try {
@@ -27274,7 +27519,7 @@ async function probeAntigravity(command, options = {}) {
27274
27519
  cleanup(proc).then(() => resolve2(result), () => resolve2({ status: "unhealthy", lastError: "antigravity_acp_cleanup_failed" }));
27275
27520
  };
27276
27521
  const fail = (lastError) => finish({ status: "unhealthy", lastError });
27277
- const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? 1e4);
27522
+ const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? (process.platform === "win32" ? 30000 : 1e4));
27278
27523
  const write = (value) => {
27279
27524
  try {
27280
27525
  if (!proc.stdin || proc.stdin.destroyed || proc.stdin.writableEnded || proc.stdin.writable === false) {
@@ -28179,7 +28424,7 @@ class ClaudeTurnProtocol {
28179
28424
 
28180
28425
  // agent-driver/dist/adapters/claude/recent-context.js
28181
28426
  import { createReadStream as createReadStream2 } from "node:fs";
28182
- import { homedir as homedir3 } from "node:os";
28427
+ import { homedir as homedir4 } from "node:os";
28183
28428
  import path7 from "node:path";
28184
28429
  import { createInterface } from "node:readline";
28185
28430
 
@@ -28388,7 +28633,7 @@ async function discoverClaudeRecentContext(request, dependencies = {}) {
28388
28633
  const collector = new RecentContextCollector(request, "supported");
28389
28634
  if (collector.satisfied)
28390
28635
  return collector.result();
28391
- const projectsRoot = path7.resolve(dependencies.projectsRoot ?? path7.join(process.env.CLAUDE_CONFIG_DIR || path7.join(homedir3(), ".claude"), "projects"));
28636
+ const projectsRoot = path7.resolve(dependencies.projectsRoot ?? path7.join(process.env.CLAUDE_CONFIG_DIR || path7.join(homedir4(), ".claude"), "projects"));
28392
28637
  const readProjectPath = dependencies.readProjectPath ?? readClaudeProjectPath;
28393
28638
  const candidates = await collectJsonlFileCandidates(projectsRoot, {
28394
28639
  includeRootFiles: false,
@@ -28415,8 +28660,8 @@ async function discoverClaudeRecentContext(request, dependencies = {}) {
28415
28660
  // agent-driver/dist/adapters/claude/index.js
28416
28661
  var CLAUDE_MODEL_CATALOG = {
28417
28662
  updateMode: "unsupported",
28418
- models: ["opus", "sonnet", "haiku"].map((id2) => ({
28419
- id: id2,
28663
+ models: ["opus", "sonnet", "haiku"].map((id3) => ({
28664
+ id: id3,
28420
28665
  supportedReasoningEfforts: []
28421
28666
  }))
28422
28667
  };
@@ -29263,7 +29508,6 @@ class CodexDriver {
29263
29508
  let listId = 0;
29264
29509
  const models = [];
29265
29510
  const seenModels = new Set;
29266
- let overflow = false;
29267
29511
  let defaultModelId;
29268
29512
  const finish = (catalog) => {
29269
29513
  if (settled)
@@ -29284,13 +29528,9 @@ class CodexDriver {
29284
29528
  if (!value || typeof value !== "object")
29285
29529
  return;
29286
29530
  const model = value;
29287
- const id2 = normalizeRuntimeModelId(model.id);
29288
- if (!id2 || seenModels.has(id2))
29289
- return;
29290
- if (models.length >= MODEL_LIST_MAX) {
29291
- overflow = true;
29531
+ const id3 = normalizeRuntimeModelId(model.id);
29532
+ if (!id3 || seenModels.has(id3))
29292
29533
  return;
29293
- }
29294
29534
  const rawOptions = Array.isArray(model.supportedReasoningEfforts) ? model.supportedReasoningEfforts : [];
29295
29535
  const seenEfforts = new Set;
29296
29536
  const supportedReasoningEfforts = rawOptions.flatMap((raw) => {
@@ -29305,11 +29545,11 @@ class CodexDriver {
29305
29545
  return [{ value: value2, ...description ? { description } : {} }];
29306
29546
  }).slice(0, MODEL_EFFORT_MAX);
29307
29547
  const candidateDefault = typeof model.defaultReasoningEffort === "string" ? model.defaultReasoningEffort : undefined;
29308
- seenModels.add(id2);
29548
+ seenModels.add(id3);
29309
29549
  if (model.isDefault === true)
29310
- defaultModelId = id2;
29550
+ defaultModelId = id3;
29311
29551
  models.push({
29312
- id: id2,
29552
+ id: id3,
29313
29553
  supportedReasoningEfforts,
29314
29554
  ...candidateDefault && supportedReasoningEfforts.some((item) => item.value === candidateDefault) ? { defaultReasoningEffort: candidateDefault } : {}
29315
29555
  });
@@ -29332,14 +29572,13 @@ class CodexDriver {
29332
29572
  if (message2.error || !message2.result || typeof message2.result !== "object")
29333
29573
  return finish();
29334
29574
  const result = message2.result;
29335
- for (const model of Array.isArray(result.data) ? result.data : [])
29575
+ for (const model of Array.isArray(result.data) ? result.data : []) {
29336
29576
  consumeModel(model);
29337
- if (overflow)
29338
- return finish();
29577
+ if (models.length >= MODEL_LIST_MAX)
29578
+ break;
29579
+ }
29339
29580
  const cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
29340
- if (cursor && models.length >= MODEL_LIST_MAX)
29341
- return finish();
29342
- if (cursor)
29581
+ if (cursor && models.length < MODEL_LIST_MAX)
29343
29582
  return requestModelPage(cursor);
29344
29583
  if (models.length === 0)
29345
29584
  return finish();
@@ -29463,10 +29702,10 @@ class CodexDriver {
29463
29702
  error: this.settingsError("process", "settings_thread_unavailable", "Codex thread is not available for a settings update", true)
29464
29703
  });
29465
29704
  }
29466
- const id2 = this.nextRequestId();
29705
+ const id3 = this.nextRequestId();
29467
29706
  return new Promise((resolve3) => {
29468
29707
  const timer = setTimeout(() => {
29469
- if (!this.pendingSettingsUpdates.delete(id2))
29708
+ if (!this.pendingSettingsUpdates.delete(id3))
29470
29709
  return;
29471
29710
  resolve3({
29472
29711
  status: "failed",
@@ -29474,13 +29713,13 @@ class CodexDriver {
29474
29713
  });
29475
29714
  }, SETTINGS_UPDATE_TIMEOUT_MS);
29476
29715
  timer.unref?.();
29477
- this.pendingSettingsUpdates.set(id2, { resolve: resolve3, timer });
29716
+ this.pendingSettingsUpdates.set(id3, { resolve: resolve3, timer });
29478
29717
  try {
29479
- stdin.write(jsonRpcRequest("thread/settings/update", { threadId, effort: input2.reasoningEffort }, id2) + `
29718
+ stdin.write(jsonRpcRequest("thread/settings/update", { threadId, effort: input2.reasoningEffort }, id3) + `
29480
29719
  `);
29481
29720
  } catch (error62) {
29482
29721
  clearTimeout(timer);
29483
- this.pendingSettingsUpdates.delete(id2);
29722
+ this.pendingSettingsUpdates.delete(id3);
29484
29723
  resolve3({
29485
29724
  status: "failed",
29486
29725
  error: this.settingsError("process", "settings_update_write_failed", String(error62), true)
@@ -29529,9 +29768,9 @@ class CodexDriver {
29529
29768
  return { category, code, message: scrubDriverErrorMessage(message2), retryable };
29530
29769
  }
29531
29770
  failPendingSettingsUpdates(code, message2) {
29532
- for (const [id2, pending] of this.pendingSettingsUpdates) {
29771
+ for (const [id3, pending] of this.pendingSettingsUpdates) {
29533
29772
  clearTimeout(pending.timer);
29534
- this.pendingSettingsUpdates.delete(id2);
29773
+ this.pendingSettingsUpdates.delete(id3);
29535
29774
  pending.resolve({
29536
29775
  status: "failed",
29537
29776
  error: this.settingsError("process", code, message2, true)
@@ -29621,7 +29860,7 @@ function parseCursorAcpModelCatalog(session2) {
29621
29860
  if (option.value === "default[]" || seen.has(option.value))
29622
29861
  continue;
29623
29862
  if (models.length >= RUNTIME_MODEL_CATALOG_MAX)
29624
- return;
29863
+ break;
29625
29864
  seen.add(option.value);
29626
29865
  models.push({
29627
29866
  id: option.value,
@@ -30085,7 +30324,7 @@ class CursorAcpLane {
30085
30324
  return this.request(method, params, this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS2).promise;
30086
30325
  }
30087
30326
  request(method, params, timeoutMs) {
30088
- const id2 = ++this.requestSequence;
30327
+ const id3 = ++this.requestSequence;
30089
30328
  let resolve3;
30090
30329
  let reject;
30091
30330
  const promise2 = new Promise((accept, decline) => {
@@ -30093,24 +30332,24 @@ class CursorAcpLane {
30093
30332
  reject = decline;
30094
30333
  });
30095
30334
  const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
30096
- const pending = this.pending.get(id2);
30335
+ const pending = this.pending.get(id3);
30097
30336
  if (!pending || pending.kind !== "call")
30098
30337
  return;
30099
- this.pending.delete(id2);
30338
+ this.pending.delete(id3);
30100
30339
  pending.reject(new Error(`Cursor ACP ${method} timed out`));
30101
30340
  }, timeoutMs);
30102
30341
  timer?.unref?.();
30103
- this.pending.set(id2, { kind: "call", method, resolve: resolve3, reject, ...timer ? { timer } : {} });
30342
+ this.pending.set(id3, { kind: "call", method, resolve: resolve3, reject, ...timer ? { timer } : {} });
30104
30343
  try {
30105
- this.write({ jsonrpc: "2.0", id: id2, method, params });
30344
+ this.write({ jsonrpc: "2.0", id: id3, method, params });
30106
30345
  } catch (error62) {
30107
- const pending = this.pending.get(id2);
30108
- this.pending.delete(id2);
30346
+ const pending = this.pending.get(id3);
30347
+ this.pending.delete(id3);
30109
30348
  if (pending?.kind === "call" && pending.timer)
30110
30349
  clearTimeout(pending.timer);
30111
30350
  throw error62 instanceof Error ? error62 : new Error(String(error62));
30112
30351
  }
30113
- return { id: id2, promise: promise2 };
30352
+ return { id: id3, promise: promise2 };
30114
30353
  }
30115
30354
  write(message2) {
30116
30355
  const stdin = this.process?.stdin;
@@ -30216,14 +30455,14 @@ class CursorAcpLane {
30216
30455
  }
30217
30456
  this.protocolFailure("Cursor ACP emitted an unrecognized JSON-RPC message");
30218
30457
  }
30219
- handleResponse(id2, message2) {
30220
- const pending = typeof id2 === "number" ? this.pending.get(id2) : undefined;
30221
- if (typeof id2 !== "number" || !pending) {
30458
+ handleResponse(id3, message2) {
30459
+ const pending = typeof id3 === "number" ? this.pending.get(id3) : undefined;
30460
+ if (typeof id3 !== "number" || !pending) {
30222
30461
  this.diagnostic("warning", "Cursor ACP emitted a duplicate or unknown response id");
30223
30462
  return;
30224
30463
  }
30225
30464
  if (pending.kind === "prompt") {
30226
- this.pending.delete(id2);
30465
+ this.pending.delete(id3);
30227
30466
  if (message2.error !== undefined) {
30228
30467
  const payload = record4(message2.error);
30229
30468
  const rpcCode = typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined;
@@ -30237,20 +30476,20 @@ class CursorAcpLane {
30237
30476
  }
30238
30477
  if (message2.error !== undefined) {
30239
30478
  const payload = record4(message2.error);
30240
- this.settleRequest(id2, false, new CursorAcpRpcError(pending.method, typeof payload?.code === "number" ? payload.code : undefined, rpcErrorMessage2(message2.error)));
30479
+ this.settleRequest(id3, false, new CursorAcpRpcError(pending.method, typeof payload?.code === "number" ? payload.code : undefined, rpcErrorMessage2(message2.error)));
30241
30480
  return;
30242
30481
  }
30243
30482
  if (!("result" in message2)) {
30244
- this.settleRequest(id2, false, new Error("Cursor ACP response omitted result"));
30483
+ this.settleRequest(id3, false, new Error("Cursor ACP response omitted result"));
30245
30484
  return;
30246
30485
  }
30247
- this.settleRequest(id2, true, message2.result);
30486
+ this.settleRequest(id3, true, message2.result);
30248
30487
  }
30249
- settleRequest(id2, ok, value) {
30250
- const pending = this.pending.get(id2);
30488
+ settleRequest(id3, ok, value) {
30489
+ const pending = this.pending.get(id3);
30251
30490
  if (!pending || pending.kind !== "call")
30252
30491
  return;
30253
- this.pending.delete(id2);
30492
+ this.pending.delete(id3);
30254
30493
  if (pending.timer)
30255
30494
  clearTimeout(pending.timer);
30256
30495
  if (ok)
@@ -30258,11 +30497,11 @@ class CursorAcpLane {
30258
30497
  else
30259
30498
  pending.reject(value instanceof Error ? value : new Error(String(value)));
30260
30499
  }
30261
- handleRequest(id2, method, params) {
30500
+ handleRequest(id3, method, params) {
30262
30501
  if (method !== "session/request_permission") {
30263
30502
  this.write({
30264
30503
  jsonrpc: "2.0",
30265
- id: id2,
30504
+ id: id3,
30266
30505
  error: { code: -32601, message: "Unsupported Cursor ACP client request" }
30267
30506
  });
30268
30507
  this.diagnostic("warning", `Unsupported Cursor ACP client request: ${safeLabel2(method)}`);
@@ -30273,13 +30512,13 @@ class CursorAcpLane {
30273
30512
  const options = Array.isArray(payload?.options) ? payload.options.map(record4).filter(Boolean) : [];
30274
30513
  const allowOnce = options.find((option) => option.kind === "allow_once" && typeof option.optionId === "string" && option.optionId.trim().length > 0);
30275
30514
  if (!this.ready || this.currentPromptRequestId === null || !sameSession || !allowOnce) {
30276
- this.write({ jsonrpc: "2.0", id: id2, result: { outcome: { outcome: "cancelled" } } });
30515
+ this.write({ jsonrpc: "2.0", id: id3, result: { outcome: { outcome: "cancelled" } } });
30277
30516
  this.diagnostic("error", "Cursor ACP permission request was not allowed for the active prompt");
30278
30517
  return;
30279
30518
  }
30280
30519
  this.write({
30281
30520
  jsonrpc: "2.0",
30282
- id: id2,
30521
+ id: id3,
30283
30522
  result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } }
30284
30523
  });
30285
30524
  }
@@ -30367,8 +30606,8 @@ class CursorAcpLane {
30367
30606
  this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});
30368
30607
  }
30369
30608
  rejectAllPending(error62) {
30370
- for (const [id2, pending] of [...this.pending]) {
30371
- this.pending.delete(id2);
30609
+ for (const [id3, pending] of [...this.pending]) {
30610
+ this.pending.delete(id3);
30372
30611
  if (pending.kind === "call") {
30373
30612
  if (pending.timer)
30374
30613
  clearTimeout(pending.timer);
@@ -30676,14 +30915,14 @@ function parseGrokModelCatalog(value) {
30676
30915
  const models = [];
30677
30916
  for (const item of available) {
30678
30917
  const model = asRecord(item);
30679
- const id2 = normalizeRuntimeModelId(model?.modelId);
30680
- if (!model || !id2 || seen.has(id2))
30918
+ const id3 = normalizeRuntimeModelId(model?.modelId);
30919
+ if (!model || !id3 || seen.has(id3))
30681
30920
  continue;
30682
30921
  if (models.length >= RUNTIME_MODEL_CATALOG_MAX)
30683
- return;
30684
- seen.add(id2);
30922
+ break;
30923
+ seen.add(id3);
30685
30924
  const displayName = boundedText2(model.name, MODEL_DISPLAY_NAME_MAX2);
30686
- models.push({ id: id2, ...displayName ? { displayName } : {}, ...reasoningCatalog(model) });
30925
+ models.push({ id: id3, ...displayName ? { displayName } : {}, ...reasoningCatalog(model) });
30687
30926
  }
30688
30927
  if (models.length === 0)
30689
30928
  return;
@@ -30737,13 +30976,13 @@ async function probeGrokAcpCatalog(command, options = {}) {
30737
30976
  const cleanup = options.cleanup ?? cleanupProbeProcess2;
30738
30977
  Promise.resolve().then(() => cleanup(processHandle)).catch(() => {}).finally(() => resolve3(value));
30739
30978
  };
30740
- const write = (method, params, id2) => {
30979
+ const write = (method, params, id3) => {
30741
30980
  const stdin = processHandle.stdin;
30742
30981
  if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {
30743
30982
  return finish({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });
30744
30983
  }
30745
30984
  try {
30746
- stdin.write(`${jsonRpcRequest(method, params, id2)}
30985
+ stdin.write(`${jsonRpcRequest(method, params, id3)}
30747
30986
  `);
30748
30987
  } catch {
30749
30988
  finish({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });
@@ -30777,8 +31016,8 @@ async function probeGrokAcpCatalog(command, options = {}) {
30777
31016
  const capabilities = asRecord(result.agentCapabilities);
30778
31017
  const methods = Array.isArray(result.authMethods) ? result.authMethods : [];
30779
31018
  const methodIds = methods.flatMap((method) => {
30780
- const id2 = asRecord(method)?.id;
30781
- return typeof id2 === "string" ? [id2] : [];
31019
+ const id3 = asRecord(method)?.id;
31020
+ return typeof id3 === "string" ? [id3] : [];
30782
31021
  });
30783
31022
  if (result.protocolVersion !== ACP_PROTOCOL_VERSION5) {
30784
31023
  return finish({ status: "unhealthy", lastError: "grok_acp_protocol_incompatible" });
@@ -30787,7 +31026,7 @@ async function probeGrokAcpCatalog(command, options = {}) {
30787
31026
  return finish({ status: "unhealthy", lastError: "grok_acp_load_session_unsupported" });
30788
31027
  }
30789
31028
  if (!methodIds.includes(AUTH_METHOD_ID4)) {
30790
- if (methodIds.some((id2) => INTERACTIVE_AUTH_METHOD_IDS.has(id2))) {
31029
+ if (methodIds.some((id3) => INTERACTIVE_AUTH_METHOD_IDS.has(id3))) {
30791
31030
  return finish({ status: "unhealthy", lastError: "grok_acp_authentication_failed" });
30792
31031
  }
30793
31032
  return finish({ status: "unhealthy", lastError: "grok_acp_cached_auth_unsupported" });
@@ -31144,11 +31383,11 @@ class GrokAcpLane {
31144
31383
  }
31145
31384
  const authMethods = Array.isArray(initialize.authMethods) ? initialize.authMethods : [];
31146
31385
  const authMethodIds = authMethods.flatMap((method) => {
31147
- const id2 = asRecord(method)?.id;
31148
- return typeof id2 === "string" ? [id2] : [];
31386
+ const id3 = asRecord(method)?.id;
31387
+ return typeof id3 === "string" ? [id3] : [];
31149
31388
  });
31150
31389
  if (!authMethodIds.includes(AUTH_METHOD_ID5)) {
31151
- if (authMethodIds.some((id2) => INTERACTIVE_AUTH_METHOD_IDS2.has(id2))) {
31390
+ if (authMethodIds.some((id3) => INTERACTIVE_AUTH_METHOD_IDS2.has(id3))) {
31152
31391
  throw new GrokAcpAuthenticationError("Grok authentication failed; run `grok login` and retry");
31153
31392
  }
31154
31393
  throw new GrokAcpIncompatibleError("Installed Grok ACP does not expose cached-token authentication");
@@ -31314,7 +31553,7 @@ class GrokAcpLane {
31314
31553
  return this.request(method, params, timeoutMs ?? this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS3).promise;
31315
31554
  }
31316
31555
  request(method, params, timeoutMs) {
31317
- const id2 = ++this.requestSequence;
31556
+ const id3 = ++this.requestSequence;
31318
31557
  let resolve3;
31319
31558
  let reject;
31320
31559
  const promise2 = new Promise((accept, decline) => {
@@ -31322,24 +31561,24 @@ class GrokAcpLane {
31322
31561
  reject = decline;
31323
31562
  });
31324
31563
  const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
31325
- const pending = this.pending.get(id2);
31564
+ const pending = this.pending.get(id3);
31326
31565
  if (!pending || pending.kind !== "call")
31327
31566
  return;
31328
- this.pending.delete(id2);
31567
+ this.pending.delete(id3);
31329
31568
  pending.reject(new Error(`Grok ACP ${method} timed out`));
31330
31569
  }, timeoutMs);
31331
31570
  timer?.unref?.();
31332
- this.pending.set(id2, { kind: "call", method, resolve: resolve3, reject, ...timer ? { timer } : {} });
31571
+ this.pending.set(id3, { kind: "call", method, resolve: resolve3, reject, ...timer ? { timer } : {} });
31333
31572
  try {
31334
- this.write({ jsonrpc: "2.0", id: id2, method, params });
31573
+ this.write({ jsonrpc: "2.0", id: id3, method, params });
31335
31574
  } catch (error62) {
31336
- const pending = this.pending.get(id2);
31337
- this.pending.delete(id2);
31575
+ const pending = this.pending.get(id3);
31576
+ this.pending.delete(id3);
31338
31577
  if (pending?.kind === "call" && pending.timer)
31339
31578
  clearTimeout(pending.timer);
31340
31579
  throw error62 instanceof Error ? error62 : new Error(String(error62));
31341
31580
  }
31342
- return { id: id2, promise: promise2 };
31581
+ return { id: id3, promise: promise2 };
31343
31582
  }
31344
31583
  write(message2) {
31345
31584
  const stdin = this.process?.stdin;
@@ -31439,14 +31678,14 @@ class GrokAcpLane {
31439
31678
  }
31440
31679
  this.protocolFailure("Grok ACP emitted an unrecognized JSON-RPC message");
31441
31680
  }
31442
- handleResponse(id2, message2) {
31443
- const pending = typeof id2 === "number" ? this.pending.get(id2) : undefined;
31444
- if (typeof id2 !== "number" || !pending) {
31681
+ handleResponse(id3, message2) {
31682
+ const pending = typeof id3 === "number" ? this.pending.get(id3) : undefined;
31683
+ if (typeof id3 !== "number" || !pending) {
31445
31684
  this.diagnostic("warning", "Grok ACP emitted a duplicate or unknown response id");
31446
31685
  return;
31447
31686
  }
31448
31687
  if (pending.kind === "prompt") {
31449
- this.pending.delete(id2);
31688
+ this.pending.delete(id3);
31450
31689
  if (message2.error !== undefined) {
31451
31690
  const payload = asRecord(message2.error);
31452
31691
  const code = typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined;
@@ -31460,20 +31699,20 @@ class GrokAcpLane {
31460
31699
  }
31461
31700
  if (message2.error !== undefined) {
31462
31701
  const payload = asRecord(message2.error);
31463
- this.settleRequest(id2, false, new GrokAcpRpcError(pending.method, typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined, rpcErrorMessage3(message2.error)));
31702
+ this.settleRequest(id3, false, new GrokAcpRpcError(pending.method, typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined, rpcErrorMessage3(message2.error)));
31464
31703
  return;
31465
31704
  }
31466
31705
  if (!("result" in message2)) {
31467
- this.settleRequest(id2, false, new Error("Grok ACP response omitted result"));
31706
+ this.settleRequest(id3, false, new Error("Grok ACP response omitted result"));
31468
31707
  return;
31469
31708
  }
31470
- this.settleRequest(id2, true, message2.result);
31709
+ this.settleRequest(id3, true, message2.result);
31471
31710
  }
31472
- settleRequest(id2, ok, value) {
31473
- const pending = this.pending.get(id2);
31711
+ settleRequest(id3, ok, value) {
31712
+ const pending = this.pending.get(id3);
31474
31713
  if (!pending || pending.kind !== "call")
31475
31714
  return;
31476
- this.pending.delete(id2);
31715
+ this.pending.delete(id3);
31477
31716
  if (pending.timer)
31478
31717
  clearTimeout(pending.timer);
31479
31718
  if (ok)
@@ -31481,9 +31720,9 @@ class GrokAcpLane {
31481
31720
  else
31482
31721
  pending.reject(value instanceof Error ? value : new Error(String(value)));
31483
31722
  }
31484
- handleRequest(id2, method, params) {
31723
+ handleRequest(id3, method, params) {
31485
31724
  if (method !== "session/request_permission") {
31486
- this.write({ jsonrpc: "2.0", id: id2, error: { code: -32601, message: "Unsupported Grok ACP client request" } });
31725
+ this.write({ jsonrpc: "2.0", id: id3, error: { code: -32601, message: "Unsupported Grok ACP client request" } });
31487
31726
  this.diagnostic("warning", `Unsupported Grok ACP client request: ${safeLabel3(method)}`);
31488
31727
  return;
31489
31728
  }
@@ -31491,13 +31730,13 @@ class GrokAcpLane {
31491
31730
  const options = Array.isArray(payload?.options) ? payload.options.map(asRecord).filter(Boolean) : [];
31492
31731
  const allowOnce = options.find((option) => option.kind === "allow_once" && typeof option.optionId === "string" && option.optionId.trim());
31493
31732
  if (!this.ready || this.currentPromptRequestId === null || payload?.sessionId !== this.sessionId || !allowOnce) {
31494
- this.write({ jsonrpc: "2.0", id: id2, result: { outcome: { outcome: "cancelled" } } });
31733
+ this.write({ jsonrpc: "2.0", id: id3, result: { outcome: { outcome: "cancelled" } } });
31495
31734
  this.diagnostic("error", "Grok ACP permission request was not allowed for the active prompt");
31496
31735
  return;
31497
31736
  }
31498
31737
  this.write({
31499
31738
  jsonrpc: "2.0",
31500
- id: id2,
31739
+ id: id3,
31501
31740
  result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } }
31502
31741
  });
31503
31742
  }
@@ -31659,8 +31898,8 @@ class GrokAcpLane {
31659
31898
  this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});
31660
31899
  }
31661
31900
  rejectAllPending(error62) {
31662
- for (const [id2, pending] of [...this.pending]) {
31663
- this.pending.delete(id2);
31901
+ for (const [id3, pending] of [...this.pending]) {
31902
+ this.pending.delete(id3);
31664
31903
  if (pending.kind === "call") {
31665
31904
  if (pending.timer)
31666
31905
  clearTimeout(pending.timer);
@@ -31839,7 +32078,6 @@ import { randomBytes as randomBytes4 } from "node:crypto";
31839
32078
  import { randomBytes as randomBytes3 } from "node:crypto";
31840
32079
  import { EventEmitter as EventEmitter5 } from "node:events";
31841
32080
  import { createServer as createServer2 } from "node:net";
31842
- var SUPPORTED_VERSION = "1.17.20";
31843
32081
  var HOST = "127.0.0.1";
31844
32082
  var START_TIMEOUT_MS = 15000;
31845
32083
  var REQUEST_TIMEOUT_MS = 15000;
@@ -32257,8 +32495,8 @@ class OpenCodeServiceLane {
32257
32495
  const { response, body } = await this.fetchJsonWithTimeout("/global/health", { method: "GET" }, "health", healthTimeoutMs);
32258
32496
  if (response.ok) {
32259
32497
  const health = record5(body);
32260
- if (health?.healthy !== true || health.version !== SUPPORTED_VERSION) {
32261
- throw new OpenCodeIncompatibleError(`Installed OpenCode service must be version ${SUPPORTED_VERSION}`);
32498
+ if (health?.healthy !== true) {
32499
+ throw new OpenCodeIncompatibleError("Installed OpenCode service did not report healthy status");
32262
32500
  }
32263
32501
  await this.verifyOpenApi();
32264
32502
  return;
@@ -32992,6 +33230,59 @@ class OpenCodeServiceLane {
32992
33230
  }
32993
33231
  }
32994
33232
 
33233
+ // agent-driver/dist/adapters/opencode/legacy-auth.js
33234
+ import { open as open2 } from "node:fs/promises";
33235
+ import { homedir as homedir6 } from "node:os";
33236
+ import path10 from "node:path";
33237
+ function record6(value) {
33238
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
33239
+ }
33240
+ function parse5(value) {
33241
+ try {
33242
+ return record6(JSON.parse(value));
33243
+ } catch {
33244
+ return;
33245
+ }
33246
+ }
33247
+ async function readJson(filename, maxBytes) {
33248
+ try {
33249
+ const file2 = await open2(filename, "r");
33250
+ try {
33251
+ if ((await file2.stat()).size > maxBytes)
33252
+ return;
33253
+ return parse5(await file2.readFile("utf8"));
33254
+ } finally {
33255
+ await file2.close();
33256
+ }
33257
+ } catch {
33258
+ return;
33259
+ }
33260
+ }
33261
+ function xdgRoot(value, fallback) {
33262
+ return value && path10.isAbsolute(value) ? value : fallback;
33263
+ }
33264
+ async function legacyOpenCodeApiEnvironment(environment, model) {
33265
+ if (!model || model.indexOf("/") < 1)
33266
+ return {};
33267
+ if (environment.OPENCODE_MODELS_URL && environment.OPENCODE_MODELS_URL !== "https://models.opencode.ai" && !environment.OPENCODE_MODELS_PATH)
33268
+ return {};
33269
+ const provider = model.slice(0, model.indexOf("/"));
33270
+ const home = (process.platform === "win32" ? environment.USERPROFILE : undefined) || environment.HOME || homedir6();
33271
+ const cache = xdgRoot(environment.XDG_CACHE_HOME, path10.join(home, ".cache"));
33272
+ const catalog = await readJson(environment.OPENCODE_MODELS_PATH || path10.join(cache, "opencode", "models.json"), 16 * 1024 * 1024);
33273
+ const providerInfo = record6(catalog?.[provider]);
33274
+ const names = Array.isArray(providerInfo?.env) ? providerInfo.env.filter((name2) => typeof name2 === "string") : [];
33275
+ if (names.some((name2) => environment[name2] !== undefined))
33276
+ return {};
33277
+ const name = names.find((name2) => /^[A-Z][A-Z0-9_]*(?:_API_KEY|_TOKEN)$/.test(name2));
33278
+ if (!name)
33279
+ return {};
33280
+ const data = xdgRoot(environment.XDG_DATA_HOME, path10.join(home, ".local", "share"));
33281
+ const auth = (environment.OPENCODE_AUTH_CONTENT ? parse5(environment.OPENCODE_AUTH_CONTENT) : undefined) ?? await readJson(path10.join(data, "opencode", "auth.json"), 1024 * 1024);
33282
+ const credential = record6(auth?.[provider]);
33283
+ return credential?.type === "api" && typeof credential.key === "string" && credential.key.trim() ? { [name]: credential.key } : {};
33284
+ }
33285
+
32995
33286
  // agent-driver/dist/adapters/opencode/recent-context.js
32996
33287
  var OPENCODE_DISCOVERY_TIMEOUT_MS = 15000;
32997
33288
  var OPENCODE_DISCOVERY_OUTPUT_MAX_BYTES = 4 * 1024 * 1024;
@@ -33072,7 +33363,7 @@ class OpenCodeDriver {
33072
33363
  instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] };
33073
33364
  execution = {
33074
33365
  lifetime: "session",
33075
- transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },
33366
+ transport: { kind: "http_sse", protocol: "opencode.v2.service" },
33076
33367
  wakeStart: "immediate",
33077
33368
  terminalOwnership: "transport_request"
33078
33369
  };
@@ -33105,7 +33396,9 @@ class OpenCodeDriver {
33105
33396
  const { spawnEnv } = await prepareCliTransport(ctx, {
33106
33397
  OPENCODE_SERVER_PASSWORD: password
33107
33398
  });
33108
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
33399
+ const fields2 = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
33400
+ Object.assign(spawnEnv, await legacyOpenCodeApiEnvironment(spawnEnv, fields2.model));
33401
+ const override = fields2.command;
33109
33402
  const args = [
33110
33403
  "serve",
33111
33404
  "--pure",
@@ -33128,8 +33421,8 @@ class OpenCodeDriver {
33128
33421
  // agent-driver/dist/adapters/pi/index.js
33129
33422
  import { createRequire as createRequire2 } from "module";
33130
33423
  import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync4, realpathSync } from "fs";
33131
- import { homedir as homedir6 } from "os";
33132
- import * as path12 from "path";
33424
+ import { homedir as homedir8 } from "os";
33425
+ import * as path13 from "path";
33133
33426
 
33134
33427
  // agent-driver/dist/controller/sdk-host.js
33135
33428
  import { EventEmitter as EventEmitter6 } from "events";
@@ -33244,7 +33537,7 @@ class SdkLane {
33244
33537
 
33245
33538
  // agent-driver/dist/adapters/pi/sessionDeps.js
33246
33539
  import { readFileSync as readFileSync3 } from "fs";
33247
- import * as path10 from "path";
33540
+ import * as path11 from "path";
33248
33541
  import { pathToFileURL } from "url";
33249
33542
  var PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
33250
33543
  var cachedSdkPromise = null;
@@ -33253,9 +33546,9 @@ async function importPiSdkFromGlobalInstall() {
33253
33546
  if (!dir) {
33254
33547
  throw new Error(`${PI_SDK_PACKAGE_NAME} not found — install it (e.g. \`npm install -g ${PI_SDK_PACKAGE_NAME}\`) before launching a pi agent`);
33255
33548
  }
33256
- const pkg = JSON.parse(readFileSync3(path10.join(dir, "package.json"), "utf-8"));
33549
+ const pkg = JSON.parse(readFileSync3(path11.join(dir, "package.json"), "utf-8"));
33257
33550
  const entry = pkg.exports?.["."]?.import ?? pkg.main ?? "./dist/index.js";
33258
- const entryPath = path10.join(dir, entry);
33551
+ const entryPath = path11.join(dir, entry);
33259
33552
  const barrel = await import(pathToFileURL(entryPath).href);
33260
33553
  return withSessionDirHelper(barrel, entryPath);
33261
33554
  }
@@ -33263,7 +33556,7 @@ async function withSessionDirHelper(barrel, entryPath) {
33263
33556
  if (typeof barrel.getDefaultSessionDir === "function")
33264
33557
  return barrel;
33265
33558
  try {
33266
- const deepPath = path10.join(path10.dirname(entryPath), "core", "session-manager.js");
33559
+ const deepPath = path11.join(path11.dirname(entryPath), "core", "session-manager.js");
33267
33560
  const deep = await import(pathToFileURL(deepPath).href);
33268
33561
  if (typeof deep.getDefaultSessionDir !== "function")
33269
33562
  return barrel;
@@ -33344,13 +33637,13 @@ function createPiSessionDependencies(ctx, loadSdk = loadPiSdkModule) {
33344
33637
  }
33345
33638
 
33346
33639
  // agent-driver/dist/adapters/pi/recent-context.js
33347
- import { homedir as homedir5 } from "node:os";
33348
- import path11 from "node:path";
33640
+ import { homedir as homedir7 } from "node:os";
33641
+ import path12 from "node:path";
33349
33642
  function expandTildePath(value) {
33350
33643
  if (value === "~")
33351
- return homedir5();
33644
+ return homedir7();
33352
33645
  if (value.startsWith("~/"))
33353
- return path11.join(homedir5(), value.slice(2));
33646
+ return path12.join(homedir7(), value.slice(2));
33354
33647
  return value;
33355
33648
  }
33356
33649
  async function discoverPiRecentContext(request, dependencies = {}) {
@@ -33358,7 +33651,7 @@ async function discoverPiRecentContext(request, dependencies = {}) {
33358
33651
  if (collector.satisfied)
33359
33652
  return collector.result();
33360
33653
  const customSessionDirectory = process.env.PI_CODING_AGENT_SESSION_DIR;
33361
- const sessionsRoot = path11.resolve(expandTildePath(dependencies.sessionsRoot ?? customSessionDirectory ?? path11.join(process.env.PI_CODING_AGENT_DIR || path11.join(homedir5(), ".pi", "agent"), "sessions")));
33654
+ const sessionsRoot = path12.resolve(expandTildePath(dependencies.sessionsRoot ?? customSessionDirectory ?? path12.join(process.env.PI_CODING_AGENT_DIR || path12.join(homedir7(), ".pi", "agent"), "sessions")));
33362
33655
  const scanDirectSessions = dependencies.sessionsRoot == null && customSessionDirectory != null;
33363
33656
  const readHeader = dependencies.readHeader ?? readFirstLine;
33364
33657
  const candidates = await collectJsonlFileCandidates(sessionsRoot, {
@@ -33406,15 +33699,15 @@ function resolvePiSdkPackageDir(deps = {}) {
33406
33699
  if (!binPath)
33407
33700
  return;
33408
33701
  try {
33409
- let dir = path12.dirname(realpathSync(binPath));
33702
+ let dir = path13.dirname(realpathSync(binPath));
33410
33703
  const MAX_DEPTH = 8;
33411
33704
  for (let i = 0;i < MAX_DEPTH; i++) {
33412
- if (isPiSdkPackageJson(path12.join(dir, "package.json")))
33705
+ if (isPiSdkPackageJson(path13.join(dir, "package.json")))
33413
33706
  return dir;
33414
- const siblingDir = path12.join(dir, "node_modules", PI_SDK_PACKAGE_NAME2);
33415
- if (isPiSdkPackageJson(path12.join(siblingDir, "package.json")))
33707
+ const siblingDir = path13.join(dir, "node_modules", PI_SDK_PACKAGE_NAME2);
33708
+ if (isPiSdkPackageJson(path13.join(siblingDir, "package.json")))
33416
33709
  return siblingDir;
33417
- const parent = path12.dirname(dir);
33710
+ const parent = path13.dirname(dir);
33418
33711
  if (parent === dir)
33419
33712
  break;
33420
33713
  dir = parent;
@@ -33431,21 +33724,21 @@ function findPiSessionFile(sessionDir, sessionId) {
33431
33724
  }
33432
33725
  const suffix = `_${sessionId}.jsonl`;
33433
33726
  const match = entries.find((entry) => entry.endsWith(suffix));
33434
- return match ? path12.join(sessionDir, match) : null;
33727
+ return match ? path13.join(sessionDir, match) : null;
33435
33728
  }
33436
33729
  function resolvePiSessionDir(sdk, cwd) {
33437
33730
  if (typeof sdk.getDefaultSessionDir === "function")
33438
33731
  return sdk.getDefaultSessionDir(cwd);
33439
- const agentDir = typeof sdk.getAgentDir === "function" ? sdk.getAgentDir() : path12.join(homedir6(), ".pi", "agent");
33440
- const encoded = `--${path12.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
33441
- return path12.join(agentDir, "sessions", encoded);
33732
+ const agentDir = typeof sdk.getAgentDir === "function" ? sdk.getAgentDir() : path13.join(homedir8(), ".pi", "agent");
33733
+ const encoded = `--${path13.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
33734
+ return path13.join(agentDir, "sessions", encoded);
33442
33735
  }
33443
33736
  function resolvePiSdkVersionFromPath(deps = {}) {
33444
33737
  const dir = resolvePiSdkPackageDir(deps);
33445
33738
  if (!dir)
33446
33739
  return;
33447
33740
  try {
33448
- const pkg = JSON.parse(readFileSync4(path12.join(dir, "package.json"), "utf-8"));
33741
+ const pkg = JSON.parse(readFileSync4(path13.join(dir, "package.json"), "utf-8"));
33449
33742
  return pkg.version;
33450
33743
  } catch {
33451
33744
  return;
@@ -33637,10 +33930,10 @@ function createAgentDriverRegistry(registrations) {
33637
33930
  const backendIds = Object.freeze([...entries.keys()]);
33638
33931
  return Object.freeze({
33639
33932
  backendIds,
33640
- get(id2) {
33641
- const registration = entries.get(id2);
33933
+ get(id3) {
33934
+ const registration = entries.get(id3);
33642
33935
  if (!registration)
33643
- throw new Error(`Unknown agent backend: ${id2}`);
33936
+ throw new Error(`Unknown agent backend: ${id3}`);
33644
33937
  return registration;
33645
33938
  }
33646
33939
  });
@@ -35535,11 +35828,11 @@ function getDriver(runtimeId) {
35535
35828
  if (!BUILTIN_BACKEND_IDS.includes(runtimeId)) {
35536
35829
  throw new Error(`Unknown runtime: ${runtimeId}. Available: ${BUILTIN_BACKEND_IDS.join(", ")}`);
35537
35830
  }
35538
- const id2 = runtimeId;
35831
+ const id3 = runtimeId;
35539
35832
  return {
35540
- id: id2,
35541
- capabilities: capabilitiesFor(id2),
35542
- probe: () => createAgentDriverSdk2().probe({ backend: id2 })
35833
+ id: id3,
35834
+ capabilities: capabilitiesFor(id3),
35835
+ probe: () => createAgentDriverSdk2().probe({ backend: id3 })
35543
35836
  };
35544
35837
  }
35545
35838
  function listRuntimeIds() {
@@ -35548,22 +35841,22 @@ function listRuntimeIds() {
35548
35841
 
35549
35842
  // src/discovery.ts
35550
35843
  function resolveAlookCliPath(moduleDir) {
35551
- const thisDir = moduleDir ?? path13.dirname(fileURLToPath(import.meta.url));
35552
- const target2 = path13.basename(thisDir) === "dist" ? path13.resolve(thisDir, "cli", "index.js") : path13.resolve(thisDir, "..", "scripts", "alook-shim.mjs");
35844
+ const thisDir = moduleDir ?? path14.dirname(fileURLToPath(import.meta.url));
35845
+ const target2 = path14.basename(thisDir) === "dist" ? path14.resolve(thisDir, "cli", "index.js") : path14.resolve(thisDir, "..", "scripts", "alook-shim.mjs");
35553
35846
  return fs6.existsSync(target2) ? target2 : null;
35554
35847
  }
35555
35848
  function deriveCliFallbackCandidates(cliPath) {
35556
35849
  if (!cliPath)
35557
35850
  return [];
35558
- const normalized = cliPath.split(path13.sep).join("/");
35851
+ const normalized = cliPath.split(path14.sep).join("/");
35559
35852
  const marker = "/node_modules/";
35560
35853
  const idx = normalized.indexOf(marker);
35561
35854
  if (idx === -1)
35562
35855
  return [];
35563
35856
  const globalRoot = cliPath.slice(0, idx + marker.length - 1);
35564
- const tail = path13.join("dist", "cli", "index.js");
35857
+ const tail = path14.join("dist", "cli", "index.js");
35565
35858
  return [
35566
- path13.join(globalRoot, "@alook", "daemon", tail)
35859
+ path14.join(globalRoot, "@alook", "daemon", tail)
35567
35860
  ].filter((candidate) => candidate !== cliPath);
35568
35861
  }
35569
35862
  function resolveAlookCliPathWithFallback(primary) {
@@ -35583,20 +35876,20 @@ async function detectRuntimes() {
35583
35876
  const ids = listRuntimeIds();
35584
35877
  const results = [];
35585
35878
  const nowIso = new Date().toISOString();
35586
- for (const id2 of ids) {
35879
+ for (const id3 of ids) {
35587
35880
  try {
35588
- const driver = getDriver(id2);
35881
+ const driver = getDriver(id3);
35589
35882
  const probe = await driver.probe();
35590
35883
  if (probe.status === "healthy") {
35591
35884
  results.push({
35592
- id: id2,
35885
+ id: id3,
35593
35886
  status: "healthy",
35594
35887
  version: probe.version,
35595
35888
  reasoning: probe.reasoning
35596
35889
  });
35597
35890
  } else {
35598
35891
  results.push({
35599
- id: id2,
35892
+ id: id3,
35600
35893
  status: "unhealthy",
35601
35894
  lastError: probe.error.code ?? "probe_failed",
35602
35895
  lastErrorAt: nowIso
@@ -35604,7 +35897,7 @@ async function detectRuntimes() {
35604
35897
  }
35605
35898
  } catch (err) {
35606
35899
  results.push({
35607
- id: id2,
35900
+ id: id3,
35608
35901
  status: "unhealthy",
35609
35902
  lastError: err?.code ?? "probe_threw",
35610
35903
  lastErrorAt: nowIso
@@ -35666,14 +35959,14 @@ function createLogger2(options = {}) {
35666
35959
  `));
35667
35960
  const err = options.err ?? ((line) => process.stderr.write(line + `
35668
35961
  `));
35669
- const record6 = options.record;
35962
+ const record7 = options.record;
35670
35963
  const emit = (level, message2, data) => {
35671
35964
  if (LEVEL_RANK[level] < minRank)
35672
35965
  return;
35673
35966
  const time3 = now();
35674
35967
  const line = `${time3} ${header} ${level.toUpperCase().padEnd(5)} ${message2}${formatData(data)}`;
35675
35968
  try {
35676
- record6?.({ time: time3, header, level, message: message2, fields: recordFields(data) });
35969
+ record7?.({ time: time3, header, level, message: message2, fields: recordFields(data) });
35677
35970
  } catch {}
35678
35971
  (level === "warn" || level === "error" ? err : out)(line);
35679
35972
  };
@@ -35705,11 +35998,11 @@ function readDaemonVersion() {
35705
35998
 
35706
35999
  // src/cli/daemonRunner.ts
35707
36000
  import * as fs11 from "node:fs";
35708
- import * as path16 from "node:path";
36001
+ import * as path17 from "node:path";
35709
36002
  import { WebSocket } from "ws";
35710
36003
 
35711
36004
  // src/daemon/createDaemon.ts
35712
- import { homedir as homedir10 } from "os";
36005
+ import { homedir as homedir12 } from "os";
35713
36006
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync9 } from "node:fs";
35714
36007
 
35715
36008
  // src/util/rotatingFileSink.ts
@@ -35726,7 +36019,7 @@ import {
35726
36019
  statSync,
35727
36020
  unlinkSync as unlinkSync3
35728
36021
  } from "node:fs";
35729
- function createRotatingFileSink(path14, maxBytes, opts = {}) {
36022
+ function createRotatingFileSink(path15, maxBytes, opts = {}) {
35730
36023
  const report = (operation, error62) => {
35731
36024
  try {
35732
36025
  opts.onError?.({ operation, error: error62 });
@@ -35762,9 +36055,9 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35762
36055
  };
35763
36056
  const rotate = () => {
35764
36057
  try {
35765
- renameSync3(path14, `${path14}.1`);
36058
+ renameSync3(path15, `${path15}.1`);
35766
36059
  if (opts.mode !== undefined)
35767
- chmodSync(`${path14}.1`, opts.mode);
36060
+ chmodSync(`${path15}.1`, opts.mode);
35768
36061
  return true;
35769
36062
  } catch (error62) {
35770
36063
  report("rotate", error62);
@@ -35773,7 +36066,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35773
36066
  };
35774
36067
  const currentSize = () => {
35775
36068
  try {
35776
- return existsSync6(path14) ? statSync(path14).size : 0;
36069
+ return existsSync6(path15) ? statSync(path15).size : 0;
35777
36070
  } catch (error62) {
35778
36071
  report("stat", error62);
35779
36072
  return null;
@@ -35781,7 +36074,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35781
36074
  };
35782
36075
  const sink = {
35783
36076
  secure() {
35784
- return secureGeneration(`${path14}.1`) && secureGeneration(path14);
36077
+ return secureGeneration(`${path15}.1`) && secureGeneration(path15);
35785
36078
  },
35786
36079
  write(line) {
35787
36080
  try {
@@ -35801,7 +36094,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35801
36094
  const shouldRotate = maxBytes > 0 && (opts.hardMaxBytes ? currentBytes > 0 && currentBytes + serializedBytes > maxBytes : currentBytes >= maxBytes);
35802
36095
  if (shouldRotate && !rotate() && opts.hardMaxBytes)
35803
36096
  return;
35804
- appendFileSync(path14, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
36097
+ appendFileSync(path15, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
35805
36098
  } catch (error62) {
35806
36099
  report("append", error62);
35807
36100
  }
@@ -35809,7 +36102,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35809
36102
  openSnapshot() {
35810
36103
  const files = [];
35811
36104
  try {
35812
- for (const candidate of [`${path14}.1`, path14]) {
36105
+ for (const candidate of [`${path15}.1`, path15]) {
35813
36106
  if (!existsSync6(candidate))
35814
36107
  continue;
35815
36108
  if (!secureGeneration(candidate))
@@ -35970,11 +36263,11 @@ function createTraceSampler(emit, throttleMs = DEFAULT_TRACE_SAMPLE_MS) {
35970
36263
 
35971
36264
  // src/util/statusFile.ts
35972
36265
  import { writeFileSync as writeFileSync5, renameSync as renameSync4 } from "node:fs";
35973
- function writeStatusFile(path14, snapshot) {
36266
+ function writeStatusFile(path15, snapshot) {
35974
36267
  try {
35975
- const tmp = `${path14}.tmp`;
36268
+ const tmp = `${path15}.tmp`;
35976
36269
  writeFileSync5(tmp, JSON.stringify(snapshot));
35977
- renameSync4(tmp, path14);
36270
+ renameSync4(tmp, path15);
35978
36271
  } catch {}
35979
36272
  }
35980
36273
 
@@ -36656,7 +36949,7 @@ import * as fs7 from "fs";
36656
36949
  import * as http from "http";
36657
36950
  import * as https from "https";
36658
36951
  import * as os2 from "os";
36659
- import * as path14 from "path";
36952
+ import * as path15 from "path";
36660
36953
  import { URL as URL2 } from "url";
36661
36954
  var LOCAL_MESSAGE_REMINDER_PATH = "/__alook/local/message-reminder";
36662
36955
  var LOCAL_MESSAGE_REMINDER_BODY_MAX_BYTES = 4 * 1024;
@@ -36670,8 +36963,8 @@ var DEFAULT_HEADER_NAMES = {
36670
36963
  function randomVoucher(prefix) {
36671
36964
  return prefix + crypto3.randomBytes(32).toString("base64url");
36672
36965
  }
36673
- function sanitizeIdSegment(id2) {
36674
- return id2.replace(/[^A-Za-z0-9._-]/g, "_") || "_";
36966
+ function sanitizeIdSegment(id3) {
36967
+ return id3.replace(/[^A-Za-z0-9._-]/g, "_") || "_";
36675
36968
  }
36676
36969
 
36677
36970
  class CredentialBroker {
@@ -36688,15 +36981,15 @@ class CredentialBroker {
36688
36981
  this.voucherPrefix = config2.voucherPrefix ?? "vch_";
36689
36982
  this.clientLabel = config2.clientLabel ?? "cli";
36690
36983
  this.headerNames = config2.headerNames ?? DEFAULT_HEADER_NAMES;
36691
- this.voucherDir = config2.voucherDir ?? path14.join(os2.tmpdir(), "agent-vouchers");
36984
+ this.voucherDir = config2.voucherDir ?? path15.join(os2.tmpdir(), "agent-vouchers");
36692
36985
  }
36693
36986
  mint(agentId, launchId, capabilities2, runnerKey) {
36694
36987
  if (!runnerKey)
36695
36988
  throw new Error("CredentialBroker.mint: runnerKey is required (per-agent tier-2 credential)");
36696
36989
  const voucher = randomVoucher(this.voucherPrefix);
36697
- const dir = path14.join(this.voucherDir, sanitizeIdSegment(agentId));
36990
+ const dir = path15.join(this.voucherDir, sanitizeIdSegment(agentId));
36698
36991
  fs7.mkdirSync(dir, { recursive: true });
36699
- const voucherFile = path14.join(dir, `${sanitizeIdSegment(launchId)}.token`);
36992
+ const voucherFile = path15.join(dir, `${sanitizeIdSegment(launchId)}.token`);
36700
36993
  fs7.writeFileSync(voucherFile, voucher, { mode: 384 });
36701
36994
  this.registrations.set(voucher, {
36702
36995
  agentId,
@@ -36824,20 +37117,20 @@ function parseLocalMessageReminderBody(body, agentId) {
36824
37117
  }
36825
37118
  if (!value || typeof value !== "object" || Array.isArray(value))
36826
37119
  return null;
36827
- const record6 = value;
36828
- if (Object.keys(record6).sort().join(",") !== "channel,remindAfterMs,sentSeq")
37120
+ const record7 = value;
37121
+ if (Object.keys(record7).sort().join(",") !== "channel,remindAfterMs,sentSeq")
36829
37122
  return null;
36830
- if (typeof record6.channel !== "string" || !isCanonicalChannelScope(record6.channel))
37123
+ if (typeof record7.channel !== "string" || !isCanonicalChannelScope(record7.channel))
36831
37124
  return null;
36832
- if (!Number.isSafeInteger(record6.sentSeq) || record6.sentSeq < 1)
37125
+ if (!Number.isSafeInteger(record7.sentSeq) || record7.sentSeq < 1)
36833
37126
  return null;
36834
- if (!Number.isSafeInteger(record6.remindAfterMs) || record6.remindAfterMs !== 0 && record6.remindAfterMs < LOCAL_MESSAGE_REMINDER_MIN_MS || record6.remindAfterMs > LOCAL_MESSAGE_REMINDER_MAX_MS)
37127
+ if (!Number.isSafeInteger(record7.remindAfterMs) || record7.remindAfterMs !== 0 && record7.remindAfterMs < LOCAL_MESSAGE_REMINDER_MIN_MS || record7.remindAfterMs > LOCAL_MESSAGE_REMINDER_MAX_MS)
36835
37128
  return null;
36836
37129
  return {
36837
37130
  agentId,
36838
- channel: record6.channel,
36839
- sentSeq: record6.sentSeq,
36840
- remindAfterMs: record6.remindAfterMs
37131
+ channel: record7.channel,
37132
+ sentSeq: record7.sentSeq,
37133
+ remindAfterMs: record7.remindAfterMs
36841
37134
  };
36842
37135
  }
36843
37136
  async function handleLocalMessageReminder(req, res, agentId, onArm) {
@@ -37239,13 +37532,13 @@ function reduceManager(state, event) {
37239
37532
  const existing = state.agents[event.agentId];
37240
37533
  if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
37241
37534
  return { state, effects: [] };
37242
- const record6 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
37243
- if (!record6)
37535
+ const record7 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
37536
+ if (!record7)
37244
37537
  return { state, effects: [] };
37245
37538
  const agent2 = clone2(existing);
37246
37539
  agent2.pendingAdmissions = agent2.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId || entry.commandId !== event.commandId);
37247
37540
  syncExecutionProjection(agent2);
37248
- return commit(state, agent2, event.outcome === "failed" ? recoveryEffects(agent2, [record6]) : []);
37541
+ return commit(state, agent2, event.outcome === "failed" ? recoveryEffects(agent2, [record7]) : []);
37249
37542
  }
37250
37543
  case "admission_acknowledged": {
37251
37544
  const existing = state.agents[event.agentId];
@@ -37627,14 +37920,14 @@ function onExit(state, agentId) {
37627
37920
  function onTick(state, nowMs) {
37628
37921
  const effects = [];
37629
37922
  const agents = { ...state.agents };
37630
- for (const id2 of Object.keys(agents)) {
37631
- const a = agents[id2];
37923
+ for (const id3 of Object.keys(agents)) {
37924
+ const a = agents[id3];
37632
37925
  const lease = a.execution.lease;
37633
37926
  const stalled = a.status === "running" && (lease.state === "active" || lease.state === "suspect_active") && (lease.outstandingToolUses ?? 0) === 0 && nowMs - lease.lastWorkAt >= a.turnSilence.normalBudgetMs && nowMs >= lease.nativeDeadlineAt;
37634
37927
  if (stalled) {
37635
37928
  const repeatedSessionStall = a.sessionId !== null && a.stalledSessionId === a.sessionId;
37636
37929
  const forgetSessionId = repeatedSessionStall ? a.sessionId : undefined;
37637
- agents[id2] = {
37930
+ agents[id3] = {
37638
37931
  ...a,
37639
37932
  status: "stopping",
37640
37933
  sessionId: repeatedSessionStall ? null : a.sessionId,
@@ -37642,12 +37935,12 @@ function onTick(state, nowMs) {
37642
37935
  idleSince: null,
37643
37936
  stoppingSince: nowMs
37644
37937
  };
37645
- effects.push(forgetSessionId ? { type: "terminate_stalled", agentId: id2, forgetSessionId } : a.sessionId !== null ? { type: "terminate_stalled", agentId: id2, recordSessionId: a.sessionId } : { type: "terminate_stalled", agentId: id2 });
37938
+ effects.push(forgetSessionId ? { type: "terminate_stalled", agentId: id3, forgetSessionId } : a.sessionId !== null ? { type: "terminate_stalled", agentId: id3, recordSessionId: a.sessionId } : { type: "terminate_stalled", agentId: id3 });
37646
37939
  continue;
37647
37940
  }
37648
37941
  const expiredAdmission = a.status === "running" && a.pendingAdmissions.filter((entry) => !entry.driverAcknowledged && nowMs - entry.admittedAt >= state.staleThresholdMs);
37649
37942
  if (expiredAdmission && expiredAdmission.length > 0 && a.execution.sessionInstanceId !== null) {
37650
- agents[id2] = {
37943
+ agents[id3] = {
37651
37944
  ...a,
37652
37945
  pendingAdmissions: a.pendingAdmissions.filter((entry) => !expiredAdmission.includes(entry)),
37653
37946
  status: "stopping",
@@ -37657,7 +37950,7 @@ function onTick(state, nowMs) {
37657
37950
  effects.push(...recoveryEffects(a, expiredAdmission));
37658
37951
  effects.push({
37659
37952
  type: "expire_admission",
37660
- agentId: id2,
37953
+ agentId: id3,
37661
37954
  sessionInstanceId: a.execution.sessionInstanceId,
37662
37955
  commandIds: expiredAdmission.map((entry) => entry.commandId)
37663
37956
  });
@@ -37665,25 +37958,25 @@ function onTick(state, nowMs) {
37665
37958
  }
37666
37959
  const resetStuck = a.resetting && a.status !== "stopping" && a.resettingSince !== null && nowMs - a.resettingSince >= state.resetStuckThresholdMs;
37667
37960
  if (resetStuck) {
37668
- agents[id2] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };
37669
- effects.push({ type: "terminate_stalled", agentId: id2 });
37961
+ agents[id3] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };
37962
+ effects.push({ type: "terminate_stalled", agentId: id3 });
37670
37963
  continue;
37671
37964
  }
37672
37965
  const stoppingStuck = a.status === "stopping" && a.stoppingSince !== null && nowMs - a.stoppingSince >= state.stoppingStuckThresholdMs;
37673
37966
  if (stoppingStuck) {
37674
- effects.push({ type: "force_exit", agentId: id2, reason: "stopping_stuck" });
37967
+ effects.push({ type: "force_exit", agentId: id3, reason: "stopping_stuck" });
37675
37968
  continue;
37676
37969
  }
37677
37970
  const idleResetEligible = a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
37678
37971
  if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
37679
- agents[id2] = { ...a, idleSince: nowMs };
37680
- effects.push({ type: "maintain_idle_memory", agentId: id2, sessionId: a.sessionId });
37972
+ agents[id3] = { ...a, idleSince: nowMs };
37973
+ effects.push({ type: "maintain_idle_memory", agentId: id3, sessionId: a.sessionId });
37681
37974
  continue;
37682
37975
  }
37683
37976
  const idleEligible = a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
37684
37977
  if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
37685
- agents[id2] = { ...a, status: "stopping", stoppingSince: nowMs };
37686
- effects.push({ type: "stop", agentId: id2, reason: "idle_timeout" });
37978
+ agents[id3] = { ...a, status: "stopping", stoppingSince: nowMs };
37979
+ effects.push({ type: "stop", agentId: id3, reason: "idle_timeout" });
37687
37980
  }
37688
37981
  }
37689
37982
  return { state: { ...state, agents }, effects };
@@ -37768,11 +38061,11 @@ function syncExecutionProjection(agent2) {
37768
38061
  agent2.lastDeliverAt = agent2.pendingAdmissions.length > 0 ? Math.max(...agent2.pendingAdmissions.map((entry) => entry.admittedAt)) : null;
37769
38062
  }
37770
38063
  function recoveryEffects(agent2, records) {
37771
- return records.filter((record6) => record6.requeueOnFailure).map((record6) => ({
38064
+ return records.filter((record7) => record7.requeueOnFailure).map((record7) => ({
37772
38065
  type: "requeue_delivery",
37773
38066
  agentId: agent2.agentId,
37774
- message: record6.exactAgentMsg,
37775
- mode: record6.mode
38067
+ message: record7.exactAgentMsg,
38068
+ mode: record7.mode
37776
38069
  }));
37777
38070
  }
37778
38071
  function commit(state, agent2, effects) {
@@ -37813,7 +38106,7 @@ function runtimeModelName(config2) {
37813
38106
  // agent-driver/dist/adapters/antigravity/quota.js
37814
38107
  import { createHash as createHash4, randomBytes as randomBytes6 } from "node:crypto";
37815
38108
  import { readFile } from "node:fs/promises";
37816
- import { homedir as homedir7 } from "node:os";
38109
+ import { homedir as homedir9 } from "node:os";
37817
38110
  import { isAbsolute, join as join13 } from "node:path";
37818
38111
  var PROD = "https://cloudcode-pa.googleapis.com";
37819
38112
  var DAILY = "https://daily-cloudcode-pa.googleapis.com";
@@ -37856,18 +38149,18 @@ function parseAntigravityQuota(value) {
37856
38149
  return;
37857
38150
  if (row.disabled === true)
37858
38151
  continue;
37859
- const id2 = label(row.bucketId);
38152
+ const id3 = label(row.bucketId);
37860
38153
  const fraction = row.remainingFraction;
37861
38154
  const windowId = row.window === undefined || row.window === "" ? "unspecified" : label(row.window);
37862
- if (!id2 || !windowId || typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
38155
+ if (!id3 || !windowId || typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
37863
38156
  return;
37864
- const windowName = label(row.displayName) ?? item.group ?? id2;
38157
+ const windowName = label(row.displayName) ?? item.group ?? id3;
37865
38158
  const resetsAt = text2(row.resetTime);
37866
38159
  if (resetsAt && !Number.isFinite(Date.parse(resetsAt)))
37867
38160
  return;
37868
38161
  const limit = {
37869
38162
  bucket: {
37870
- limitId: id2,
38163
+ limitId: id3,
37871
38164
  product: { kind: "reported", id: "antigravity", displayName: "Antigravity" },
37872
38165
  model: { kind: "unknown" },
37873
38166
  window: { kind: "provider_defined", id: windowId, displayName: windowName }
@@ -37875,7 +38168,7 @@ function parseAntigravityQuota(value) {
37875
38168
  usedPercent: (1 - fraction) * 100,
37876
38169
  ...resetsAt ? { resetsAt: new Date(resetsAt).toISOString() } : {}
37877
38170
  };
37878
- const key = `${id2}\x00${windowId}`;
38171
+ const key = `${id3}\x00${windowId}`;
37879
38172
  const previous = limits.get(key);
37880
38173
  if (previous && (previous.usedPercent !== limit.usedPercent || previous.resetsAt !== limit.resetsAt))
37881
38174
  return;
@@ -37885,10 +38178,10 @@ function parseAntigravityQuota(value) {
37885
38178
  }
37886
38179
  async function readAntigravityQuota(options = {}) {
37887
38180
  const env = options.env ?? process.env;
37888
- const home = options.home ?? homedir7();
38181
+ const home = options.home ?? homedir9();
37889
38182
  const configuredHome = env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, home);
37890
38183
  const root = configuredHome ? isAbsolute(configuredHome) ? configuredHome : join13(process.cwd(), configuredHome) : join13(home, ".gemini");
37891
- const read = options.readCredentialsFile ?? ((path15) => readFile(path15, "utf8"));
38184
+ const read = options.readCredentialsFile ?? ((path16) => readFile(path16, "utf8"));
37892
38185
  let credentials = null;
37893
38186
  let authType;
37894
38187
  let storageUnavailable = false;
@@ -38007,7 +38300,7 @@ async function readAntigravityQuota(options = {}) {
38007
38300
  // agent-driver/dist/provider-quota.js
38008
38301
  import { execFile } from "node:child_process";
38009
38302
  import { readFile as readFile2 } from "node:fs/promises";
38010
- import { homedir as homedir8 } from "node:os";
38303
+ import { homedir as homedir10 } from "node:os";
38011
38304
  import { join as join14 } from "node:path";
38012
38305
  import { promisify } from "node:util";
38013
38306
  import { randomBytes as randomBytes7 } from "node:crypto";
@@ -38036,7 +38329,7 @@ async function claudeCredentials(options) {
38036
38329
  } catch {}
38037
38330
  }
38038
38331
  const env = options.env ?? process.env;
38039
- const root = env.CLAUDE_CONFIG_DIR || join14(options.home ?? homedir8(), ".claude");
38332
+ const root = env.CLAUDE_CONFIG_DIR || join14(options.home ?? homedir10(), ".claude");
38040
38333
  try {
38041
38334
  const value = options.readCredentialsFile ? await options.readCredentialsFile(join14(root, ".credentials.json")) : await readFile2(join14(root, ".credentials.json"), "utf8");
38042
38335
  return parseCredentials(value);
@@ -38125,8 +38418,8 @@ async function readClaudeQuota(options) {
38125
38418
  if (!body || typeof body !== "object") {
38126
38419
  return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
38127
38420
  }
38128
- const record6 = body;
38129
- const limits = ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_opus"].map((key) => claudeLimit(key, record6[key])).filter((limit) => limit !== null);
38421
+ const record7 = body;
38422
+ const limits = ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_opus"].map((key) => claudeLimit(key, record7[key])).filter((limit) => limit !== null);
38130
38423
  if (limits.length === 0) {
38131
38424
  return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
38132
38425
  }
@@ -39280,8 +39573,8 @@ class AgentProcessManager {
39280
39573
  if (eventAgentId) {
39281
39574
  emit(eventAgentId);
39282
39575
  } else if (event.type === "tick") {
39283
- for (const id2 of Object.keys(this.state.agents))
39284
- emit(id2);
39576
+ for (const id3 of Object.keys(this.state.agents))
39577
+ emit(id3);
39285
39578
  }
39286
39579
  }
39287
39580
  if (closingOwner && closingSpan) {
@@ -40312,32 +40605,32 @@ class AgentRouter {
40312
40605
  }
40313
40606
  return out;
40314
40607
  }
40315
- isRuntimeHealthy(id2) {
40316
- return this.runtimes.get(id2)?.status === "healthy";
40608
+ isRuntimeHealthy(id3) {
40609
+ return this.runtimes.get(id3)?.status === "healthy";
40317
40610
  }
40318
- recordRuntimeSpawnFailure(id2, reason) {
40611
+ recordRuntimeSpawnFailure(id3, reason) {
40319
40612
  if (!DEFINITIVE_EXECUTABLE_FAILURES.has(reason))
40320
40613
  return;
40321
- this.markRuntimeUnhealthy(id2, reason);
40614
+ this.markRuntimeUnhealthy(id3, reason);
40322
40615
  }
40323
- markRuntimeUnhealthy(id2, reason) {
40324
- const existing = this.runtimes.get(id2);
40616
+ markRuntimeUnhealthy(id3, reason) {
40617
+ const existing = this.runtimes.get(id3);
40325
40618
  if (!existing)
40326
40619
  return;
40327
40620
  const nowIso = new Date().toISOString();
40328
40621
  if (existing.status === "unhealthy" && existing.lastError === reason)
40329
40622
  return;
40330
- this.runtimes.set(id2, {
40623
+ this.runtimes.set(id3, {
40331
40624
  ...existing,
40332
40625
  status: "unhealthy",
40333
40626
  lastError: reason,
40334
40627
  lastErrorAt: nowIso
40335
40628
  });
40336
- this.log.warn("runtime marked unhealthy", { runtimeId: id2, reason });
40629
+ this.log.warn("runtime marked unhealthy", { runtimeId: id3, reason });
40337
40630
  this.scheduleReadyFrameResend();
40338
40631
  }
40339
- markRuntimeHealthy(id2) {
40340
- const existing = this.runtimes.get(id2);
40632
+ markRuntimeHealthy(id3) {
40633
+ const existing = this.runtimes.get(id3);
40341
40634
  if (!existing)
40342
40635
  return;
40343
40636
  if (existing.status === "healthy" && !existing.lastError && !existing.lastErrorAt)
@@ -40345,8 +40638,8 @@ class AgentRouter {
40345
40638
  const healthy = { ...existing, status: "healthy" };
40346
40639
  delete healthy.lastError;
40347
40640
  delete healthy.lastErrorAt;
40348
- this.runtimes.set(id2, healthy);
40349
- this.log.info("runtime marked healthy again", { runtimeId: id2 });
40641
+ this.runtimes.set(id3, healthy);
40642
+ this.log.info("runtime marked healthy again", { runtimeId: id3 });
40350
40643
  this.scheduleReadyFrameResend();
40351
40644
  }
40352
40645
  markLocallyStopped(agentId) {
@@ -40826,9 +41119,9 @@ function compactLines(input2) {
40826
41119
  }
40827
41120
  return suffix;
40828
41121
  }
40829
- function isRealDirectory(path15) {
41122
+ function isRealDirectory(path16) {
40830
41123
  try {
40831
- return fs9.lstatSync(path15).isDirectory();
41124
+ return fs9.lstatSync(path16).isDirectory();
40832
41125
  } catch {
40833
41126
  return false;
40834
41127
  }
@@ -41973,15 +42266,15 @@ class MessageReminderScheduler {
41973
42266
  const startedAt = this.now();
41974
42267
  const dueAt = startedAt + input2.remindAfterMs;
41975
42268
  const sentRef = `${input2.channel}#${input2.sentSeq}`;
41976
- const record6 = {
42269
+ const record7 = {
41977
42270
  ...input2,
41978
42271
  sentRef,
41979
42272
  startedAt,
41980
42273
  dueAt,
41981
42274
  timer: undefined
41982
42275
  };
41983
- record6.timer = this.setTimer(() => {
41984
- if (this.reminders.get(key) !== record6)
42276
+ record7.timer = this.setTimer(() => {
42277
+ if (this.reminders.get(key) !== record7)
41985
42278
  return;
41986
42279
  this.reminders.delete(key);
41987
42280
  try {
@@ -41992,8 +42285,8 @@ class MessageReminderScheduler {
41992
42285
  Promise.resolve(delivery).catch(() => {});
41993
42286
  } catch {}
41994
42287
  }, input2.remindAfterMs);
41995
- record6.timer.unref?.();
41996
- this.reminders.set(key, record6);
42288
+ record7.timer.unref?.();
42289
+ this.reminders.set(key, record7);
41997
42290
  return { armed: true, dueAt };
41998
42291
  }
41999
42292
  observe(agentId, channel2, latestSeq) {
@@ -42033,7 +42326,7 @@ class MessageReminderScheduler {
42033
42326
 
42034
42327
  // src/manager/agentDriverHost.ts
42035
42328
  import { randomUUID as randomUUID8 } from "node:crypto";
42036
- import { homedir as homedir9 } from "node:os";
42329
+ import { homedir as homedir11 } from "node:os";
42037
42330
  import { join as join16 } from "node:path";
42038
42331
 
42039
42332
  // src/drivers/gitIdentityEnv.ts
@@ -42159,7 +42452,7 @@ function createDaemonAgentDriverHost(ctx, onRawLine) {
42159
42452
  hostUser: readHostGitIdentity() ?? undefined
42160
42453
  }),
42161
42454
  platformProtected: {
42162
- ALOOK_HOME: process.env.ALOOK_HOME ?? join16(homedir9(), ".alook"),
42455
+ ALOOK_HOME: process.env.ALOOK_HOME ?? join16(homedir11(), ".alook"),
42163
42456
  ALOOK_ID: ctx.agentId,
42164
42457
  ALOOK_CLI: ctx.agentCliPath,
42165
42458
  ALOOK_SERVER_URL: ctx.config.serverUrl,
@@ -42265,7 +42558,7 @@ class DaemonSelfSleepScheduler {
42265
42558
  }
42266
42559
 
42267
42560
  // src/telemetry/dailyTokenUsage.ts
42268
- import { chmod, mkdir, open as open2, readFile as readFile3, rename, rm } from "node:fs/promises";
42561
+ import { chmod, mkdir, open as open3, readFile as readFile3, rename, rm } from "node:fs/promises";
42269
42562
  import { dirname as dirname6, join as join17 } from "node:path";
42270
42563
  import { randomUUID as randomUUID9 } from "node:crypto";
42271
42564
  var TOKEN_USAGE_WINDOW_DAYS = 30;
@@ -42518,7 +42811,7 @@ class DailyTokenUsageStore {
42518
42811
  await mkdir(directory, { recursive: true, mode: 448 });
42519
42812
  const temporary = `${this.filePath}.${randomUUID9()}.tmp`;
42520
42813
  try {
42521
- const file2 = await open2(temporary, "wx", 384);
42814
+ const file2 = await open3(temporary, "wx", 384);
42522
42815
  try {
42523
42816
  await file2.writeFile(JSON.stringify(this.data), { encoding: "utf8" });
42524
42817
  await file2.sync();
@@ -42528,7 +42821,7 @@ class DailyTokenUsageStore {
42528
42821
  await rename(temporary, this.filePath);
42529
42822
  await chmod(this.filePath, 384);
42530
42823
  try {
42531
- const directoryHandle = await open2(directory, "r");
42824
+ const directoryHandle = await open3(directory, "r");
42532
42825
  try {
42533
42826
  await directoryHandle.sync();
42534
42827
  } finally {
@@ -42579,7 +42872,7 @@ function appendRecentContextToPrompt(prompt, result) {
42579
42872
  return lines.join(`
42580
42873
  `);
42581
42874
  }
42582
- function createRecentContextPromptAppender(discover, recentSessionFilesTopK = 10, recentProjectsTopK = 5) {
42875
+ function createRecentContextPromptAppender(discover, recentSessionFilesTopK = 20, recentProjectsTopK = 5) {
42583
42876
  return async (prompt, runtimeConfig) => {
42584
42877
  const selected = toAgentBackendSelection(runtimeConfig);
42585
42878
  const command = selected.config.command;
@@ -42613,8 +42906,6 @@ var RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;
42613
42906
  var RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";
42614
42907
  var STATUS_WRITE_INTERVAL_MS = 5000;
42615
42908
  var TOKEN_USAGE_BACKENDS = new Set(["claude", "codex", "grok", "opencode", "pi", "antigravity"]);
42616
- var ONBOARDING_RECENT_SESSION_FILES_TOP_K = 10;
42617
- var ONBOARDING_RECENT_PROJECTS_TOP_K = 5;
42618
42909
  function parseRuntimeRawTraceAgentIds(value) {
42619
42910
  return new Set((value ?? "").split(",").map((agentId) => agentId.trim()).filter((agentId) => agentId.length > 0 && agentId !== "*"));
42620
42911
  }
@@ -42625,13 +42916,13 @@ function createRuntimeRawLineTap(args) {
42625
42916
  const maxBytes = args.maxBytes ?? RUNTIME_RAW_TRACE_MAX_BYTES;
42626
42917
  const sinks = new Map;
42627
42918
  const warned = new Set;
42628
- const warnOnce = (agentId, path15, operation, error62) => {
42919
+ const warnOnce = (agentId, path16, operation, error62) => {
42629
42920
  if (warned.has(agentId))
42630
42921
  return;
42631
42922
  warned.add(agentId);
42632
42923
  args.logger.warn("runtime raw trace sink failed", {
42633
42924
  agentId,
42634
- path: path15,
42925
+ path: path16,
42635
42926
  operation,
42636
42927
  error: error62 instanceof Error ? error62.message : String(error62)
42637
42928
  });
@@ -42640,10 +42931,10 @@ function createRuntimeRawLineTap(args) {
42640
42931
  if (!args.enabledAgentIds.has(agentId))
42641
42932
  return;
42642
42933
  const encodedAgentId = encodeURIComponent(agentId).replace(/\./g, "%2E");
42643
- const path15 = `${traceDir}/runtime-raw-events-${encodedAgentId}.jsonl`;
42934
+ const path16 = `${traceDir}/runtime-raw-events-${encodedAgentId}.jsonl`;
42644
42935
  const serializedBytes = Buffer.byteLength(line, "utf8") + 1;
42645
42936
  if (serializedBytes > maxBytes) {
42646
- warnOnce(agentId, path15, "oversize", new Error(`raw line is ${serializedBytes} bytes; max is ${maxBytes}`));
42937
+ warnOnce(agentId, path16, "oversize", new Error(`raw line is ${serializedBytes} bytes; max is ${maxBytes}`));
42647
42938
  return;
42648
42939
  }
42649
42940
  let sink = sinks.get(agentId);
@@ -42651,12 +42942,12 @@ function createRuntimeRawLineTap(args) {
42651
42942
  try {
42652
42943
  mkdirSync9(traceDir, { recursive: true });
42653
42944
  } catch (error62) {
42654
- warnOnce(agentId, path15, "mkdir", error62);
42945
+ warnOnce(agentId, path16, "mkdir", error62);
42655
42946
  }
42656
- sink = createRotatingFileSink(path15, maxBytes, {
42947
+ sink = createRotatingFileSink(path16, maxBytes, {
42657
42948
  mode: 384,
42658
42949
  hardMaxBytes: true,
42659
- onError: ({ operation, error: error62 }) => warnOnce(agentId, path15, operation, error62)
42950
+ onError: ({ operation, error: error62 }) => warnOnce(agentId, path16, operation, error62)
42660
42951
  });
42661
42952
  sinks.set(agentId, sink);
42662
42953
  }
@@ -42749,8 +43040,8 @@ function createBuiltinDaemonSessionFactory(onRuntimeRawLine) {
42749
43040
  async function createDaemon(opts) {
42750
43041
  const log2 = opts.logger ?? createLogger2({ header: "@alook/daemon" });
42751
43042
  const recentContextSdk = createAgentDriverSdk();
42752
- const appendRecentContext = createRecentContextPromptAppender((input2) => recentContextSdk.discoverRecentContext(input2), ONBOARDING_RECENT_SESSION_FILES_TOP_K, ONBOARDING_RECENT_PROJECTS_TOP_K);
42753
- const fallbackBase = (process.env.ALOOK_PROJECT_ROOT || `${homedir10()}/.alook`) + "/daemon";
43043
+ const appendRecentContext = createRecentContextPromptAppender((input2) => recentContextSdk.discoverRecentContext(input2));
43044
+ const fallbackBase = (process.env.ALOOK_PROJECT_ROOT || `${homedir12()}/.alook`) + "/daemon";
42754
43045
  const workingDirectoryBase = opts.workingDirectoryBase ?? fallbackBase;
42755
43046
  const workdirFor = (agentId) => `${workingDirectoryBase}/${agentId}`;
42756
43047
  const dailyTokenUsage2 = new DailyTokenUsageStore(workingDirectoryBase);
@@ -44025,7 +44316,7 @@ async function buildDiagnosticBundle(args) {
44025
44316
  let truncated = false;
44026
44317
  const counts = { status: args.status ? 1 : 0, daemon_log: 0, fsm: 0 };
44027
44318
  const statusTime = typeof args.status?.timeMs === "number" ? args.status.timeMs : null;
44028
- const envelope = () => {
44319
+ const envelope2 = () => {
44029
44320
  const firstEvent = retained[head]?.row.timeMs ?? null;
44030
44321
  const lastEvent = retained.at(-1)?.row.timeMs ?? null;
44031
44322
  const earliestAt = statusTime === null ? firstEvent : firstEvent === null ? statusTime : Math.min(statusTime, firstEvent);
@@ -44056,7 +44347,7 @@ async function buildDiagnosticBundle(args) {
44056
44347
  retained.push({ row, bytes: serialized });
44057
44348
  retainedBytes += serialized.byteLength;
44058
44349
  counts[row.recordType] += 1;
44059
- while (envelope().total > maxUncompressed && head < retained.length) {
44350
+ while (envelope2().total > maxUncompressed && head < retained.length) {
44060
44351
  const removed = retained[head];
44061
44352
  delete retained[head];
44062
44353
  head += 1;
@@ -44070,7 +44361,7 @@ async function buildDiagnosticBundle(args) {
44070
44361
  head = 0;
44071
44362
  }
44072
44363
  }
44073
- const { footer, total } = envelope();
44364
+ const { footer, total } = envelope2();
44074
44365
  if (total > maxUncompressed)
44075
44366
  throw new BundleTooLargeError;
44076
44367
  const hash2 = createHash6("sha256");
@@ -44141,7 +44432,7 @@ class CoordinatorError extends Error {
44141
44432
  function defaultFsOps() {
44142
44433
  return {
44143
44434
  randomSuffix: () => randomBytes9(12).toString("hex"),
44144
- open: (path15, flags, mode) => openSync4(path15, flags, mode),
44435
+ open: (path16, flags, mode) => openSync4(path16, flags, mode),
44145
44436
  write: (fd, bytes) => {
44146
44437
  writeSync(fd, bytes);
44147
44438
  },
@@ -44154,10 +44445,10 @@ function defaultFsOps() {
44154
44445
  rename: (from, to) => {
44155
44446
  renameSync6(from, to);
44156
44447
  },
44157
- fsyncDirectory: (path15) => {
44448
+ fsyncDirectory: (path16) => {
44158
44449
  if (process.platform === "win32")
44159
44450
  return;
44160
- const fd = openSync4(path15, "r");
44451
+ const fd = openSync4(path16, "r");
44161
44452
  try {
44162
44453
  fsyncSync2(fd);
44163
44454
  } finally {
@@ -44222,11 +44513,11 @@ function createDiagnosticReportCoordinator(args) {
44222
44513
  args.logger?.warn("diagnostic local artifact invalid", { reportId, code: "local_artifact_invalid" });
44223
44514
  } catch {}
44224
44515
  };
44225
- const removeExact = (path15) => {
44516
+ const removeExact = (path16) => {
44226
44517
  try {
44227
- const stat2 = lstatSync5(path15);
44518
+ const stat2 = lstatSync5(path16);
44228
44519
  if (stat2.isFile() && !stat2.isSymbolicLink())
44229
- unlinkSync6(path15);
44520
+ unlinkSync6(path16);
44230
44521
  } catch {}
44231
44522
  };
44232
44523
  const cleanup = (reportId) => {
@@ -44264,12 +44555,12 @@ function createDiagnosticReportCoordinator(args) {
44264
44555
  checkpoint(sidecar.phase === "collecting" ? "collecting_dir_fsynced" : "ready_dir_fsynced");
44265
44556
  };
44266
44557
  const committedArchive = (reportId) => {
44267
- const path15 = archivePath(reportId);
44558
+ const path16 = archivePath(reportId);
44268
44559
  try {
44269
- const stat2 = lstatSync5(path15);
44560
+ const stat2 = lstatSync5(path16);
44270
44561
  if (!stat2.isFile() || stat2.isSymbolicLink())
44271
44562
  return null;
44272
- const bytes = readFileSync7(path15);
44563
+ const bytes = readFileSync7(path16);
44273
44564
  return { sizeBytes: bytes.byteLength, sha256: createHash7("sha256").update(bytes).digest("hex") };
44274
44565
  } catch {
44275
44566
  return null;
@@ -44394,12 +44685,12 @@ function createDiagnosticReportCoordinator(args) {
44394
44685
  return uploadReady(ready);
44395
44686
  };
44396
44687
  const readSidecar = (reportId) => {
44397
- const path15 = sidecarPath(reportId);
44688
+ const path16 = sidecarPath(reportId);
44398
44689
  try {
44399
- const stat2 = lstatSync5(path15);
44690
+ const stat2 = lstatSync5(path16);
44400
44691
  if (!stat2.isFile() || stat2.isSymbolicLink())
44401
44692
  return null;
44402
- return parseSidecar(JSON.parse(readFileSync7(path15, "utf8")));
44693
+ return parseSidecar(JSON.parse(readFileSync7(path16, "utf8")));
44403
44694
  } catch {
44404
44695
  return null;
44405
44696
  }
@@ -44487,9 +44778,9 @@ function createDiagnosticReportCoordinator(args) {
44487
44778
  }
44488
44779
  // src/diagnostics/httpTransport.ts
44489
44780
  import { Readable as Readable2 } from "node:stream";
44490
- function endpoint(serverUrl, path15) {
44781
+ function endpoint(serverUrl, path16) {
44491
44782
  const base = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
44492
- return new URL(path15.replace(/^\//, ""), base).toString();
44783
+ return new URL(path16.replace(/^\//, ""), base).toString();
44493
44784
  }
44494
44785
  async function strictOutcome(response, allowed) {
44495
44786
  try {
@@ -44497,11 +44788,11 @@ async function strictOutcome(response, allowed) {
44497
44788
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
44498
44789
  return { kind: "retryable" };
44499
44790
  }
44500
- const record6 = value;
44501
- if (Object.keys(record6).length !== 2 || record6.kind !== "terminal") {
44791
+ const record7 = value;
44792
+ if (Object.keys(record7).length !== 2 || record7.kind !== "terminal") {
44502
44793
  return { kind: "retryable" };
44503
44794
  }
44504
- const status = record6.status;
44795
+ const status = record7.status;
44505
44796
  if (status !== "uploaded" && status !== "failed" || allowed[status] !== response.status) {
44506
44797
  return { kind: "retryable" };
44507
44798
  }
@@ -44553,29 +44844,29 @@ function createDiagnosticHttpTransport(args) {
44553
44844
  // src/cli/daemonUpdate.ts
44554
44845
  import * as crypto4 from "node:crypto";
44555
44846
  import * as fs10 from "node:fs";
44556
- import * as path15 from "node:path";
44847
+ import * as path16 from "node:path";
44557
44848
  import { spawn as spawn2 } from "node:child_process";
44558
44849
  var UPDATE_INTENT_SCHEMA_VERSION = 1;
44559
44850
  var UPDATE_LOG_MAX_BYTES = 512 * 1024;
44560
44851
  var UPDATE_LOG_KEEP_BYTES = 256 * 1024;
44561
44852
  var REQUEST_ID_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
44562
44853
  function intentPath(baseDir, machineId) {
44563
- return path15.join(daemonDirById(baseDir, machineId), "update-intent.json");
44854
+ return path16.join(daemonDirById(baseDir, machineId), "update-intent.json");
44564
44855
  }
44565
44856
  function updateLogPath(baseDir, machineId) {
44566
- return path15.join(daemonDirById(baseDir, machineId), "update.log");
44857
+ return path16.join(daemonDirById(baseDir, machineId), "update.log");
44567
44858
  }
44568
44859
  function updatePackageMapPath(baseDir, machineId) {
44569
- return path15.join(daemonDirById(baseDir, machineId), "update-package-map.json");
44860
+ return path16.join(daemonDirById(baseDir, machineId), "update-package-map.json");
44570
44861
  }
44571
44862
  function ensurePrivateDir(dir) {
44572
44863
  fs10.mkdirSync(dir, { recursive: true, mode: 448 });
44573
44864
  fs10.chmodSync(dir, 448);
44574
44865
  }
44575
44866
  function writePrivateJsonAtomic(filePath, value) {
44576
- const dir = path15.dirname(filePath);
44867
+ const dir = path16.dirname(filePath);
44577
44868
  ensurePrivateDir(dir);
44578
- const tempPath = path15.join(dir, `.${path15.basename(filePath)}.${process.pid}.${crypto4.randomBytes(8).toString("hex")}.tmp`);
44869
+ const tempPath = path16.join(dir, `.${path16.basename(filePath)}.${process.pid}.${crypto4.randomBytes(8).toString("hex")}.tmp`);
44579
44870
  let fd = fs10.openSync(tempPath, "wx", 384);
44580
44871
  try {
44581
44872
  fs10.writeFileSync(fd, JSON.stringify(value));
@@ -44600,7 +44891,7 @@ function scrub(value) {
44600
44891
  }
44601
44892
  function appendUpdateLog(baseDir, machineId, event, fields2 = {}) {
44602
44893
  const filePath = updateLogPath(baseDir, machineId);
44603
- ensurePrivateDir(path15.dirname(filePath));
44894
+ ensurePrivateDir(path16.dirname(filePath));
44604
44895
  try {
44605
44896
  if (fs10.existsSync(filePath) && fs10.statSync(filePath).size > UPDATE_LOG_MAX_BYTES) {
44606
44897
  const data = fs10.readFileSync(filePath);
@@ -44667,7 +44958,7 @@ function pathEnvironment(env, platform) {
44667
44958
  return entry?.[1];
44668
44959
  }
44669
44960
  function launchFromNpmPath(args) {
44670
- const pathApi = args.platform === "win32" ? path15.win32 : path15.posix;
44961
+ const pathApi = args.platform === "win32" ? path16.win32 : path16.posix;
44671
44962
  if (!pathApi.isAbsolute(args.npmPath) || !args.probe.isFile(args.npmPath))
44672
44963
  return null;
44673
44964
  const extension = pathApi.extname(args.npmPath).toLowerCase();
@@ -44699,7 +44990,7 @@ function resolveNpmLaunchCommand(options = {}) {
44699
44990
  if (launch)
44700
44991
  return launch;
44701
44992
  }
44702
- const pathApi = platform === "win32" ? path15.win32 : path15.posix;
44993
+ const pathApi = platform === "win32" ? path16.win32 : path16.posix;
44703
44994
  const names = platform === "win32" ? ["npm.exe", "npm.cmd", "npm.bat", "npm"] : ["npm"];
44704
44995
  const pathValue = pathEnvironment(env, platform);
44705
44996
  for (const directory of pathValue?.split(pathApi.delimiter) ?? []) {
@@ -44738,7 +45029,7 @@ function readTestPackageMap(baseDir, machineId) {
44738
45029
  for (const [key, value] of Object.entries(parsed)) {
44739
45030
  if (key !== "latest" && !parseReleaseVersion(key))
44740
45031
  throw new Error("invalid daemon update package map key");
44741
- if (typeof value !== "string" || !path15.isAbsolute(value))
45032
+ if (typeof value !== "string" || !path16.isAbsolute(value))
44742
45033
  throw new Error("invalid daemon update package map value");
44743
45034
  result[key] = value;
44744
45035
  }
@@ -45047,7 +45338,7 @@ async function buildRunnerDiagnosticBundle(args) {
45047
45338
  function createDaemonProcessLogger(daemonDir, foreground) {
45048
45339
  fs11.mkdirSync(daemonDir, { recursive: true, mode: 448 });
45049
45340
  fs11.chmodSync(daemonDir, 448);
45050
- const logPath = path16.join(daemonDir, "daemon.log");
45341
+ const logPath = path17.join(daemonDir, "daemon.log");
45051
45342
  let warnedOversize = false;
45052
45343
  const sink = createRotatingFileSink(logPath, DAEMON_LOG_MAX_BYTES, {
45053
45344
  mode: 384,
@@ -45074,7 +45365,7 @@ function createDaemonProcessLogger(daemonDir, foreground) {
45074
45365
  `) : quiet,
45075
45366
  err: foreground ? (line2) => process.stderr.write(line2 + `
45076
45367
  `) : quiet,
45077
- record: (record6) => sink.write(JSON.stringify(record6))
45368
+ record: (record7) => sink.write(JSON.stringify(record7))
45078
45369
  });
45079
45370
  return { logger, logPath, sink };
45080
45371
  }
@@ -45283,35 +45574,35 @@ var LEGACY_DAEMON_ID_PATTERN = /^[a-f0-9]{12}$/;
45283
45574
  var DEFAULT_SERVER_URL = "https://alook.ai";
45284
45575
  var DEFAULT_WS_URL = "wss://alook.ai/api/ws/community-daemon";
45285
45576
  function resolveDefaultBaseDir() {
45286
- const root = process.env.ALOOK_PROJECT_ROOT || path17.join(homedir11(), ".alook");
45287
- return path17.join(root, "daemon");
45577
+ const root = process.env.ALOOK_PROJECT_ROOT || path18.join(homedir13(), ".alook");
45578
+ return path18.join(root, "daemon");
45288
45579
  }
45289
45580
  var DEFAULT_BASE_DIR = resolveDefaultBaseDir();
45290
45581
  var log2 = createLogger2({ header: "@alook/daemon" });
45291
45582
  function daemonsDir(baseDir) {
45292
- return path17.join(baseDir, "daemons");
45583
+ return path18.join(baseDir, "daemons");
45293
45584
  }
45294
- function daemonDirById(baseDir, id2) {
45295
- return path17.join(daemonsDir(baseDir), validateDaemonId(id2));
45585
+ function daemonDirById(baseDir, id3) {
45586
+ return path18.join(daemonsDir(baseDir), validateDaemonId(id3));
45296
45587
  }
45297
45588
  function validateMachineId(machineId) {
45298
45589
  if (!MACHINE_ID_PATTERN.test(machineId))
45299
45590
  throw new Error("invalid machine identity returned by server");
45300
45591
  return machineId;
45301
45592
  }
45302
- function isDaemonId(id2) {
45303
- return MACHINE_ID_PATTERN.test(id2) || LEGACY_DAEMON_ID_PATTERN.test(id2);
45593
+ function isDaemonId(id3) {
45594
+ return MACHINE_ID_PATTERN.test(id3) || LEGACY_DAEMON_ID_PATTERN.test(id3);
45304
45595
  }
45305
- function validateDaemonId(id2) {
45306
- if (!isDaemonId(id2))
45596
+ function validateDaemonId(id3) {
45597
+ if (!isDaemonId(id3))
45307
45598
  throw new Error("invalid daemon id");
45308
- return id2;
45599
+ return id3;
45309
45600
  }
45310
- function pidfilePathById(baseDir, id2) {
45311
- return path17.join(daemonDirById(baseDir, id2), "daemon.pid");
45601
+ function pidfilePathById(baseDir, id3) {
45602
+ return path18.join(daemonDirById(baseDir, id3), "daemon.pid");
45312
45603
  }
45313
- function statusFilePathById(baseDir, id2) {
45314
- return path17.join(daemonDirById(baseDir, id2), "status.json");
45604
+ function statusFilePathById(baseDir, id3) {
45605
+ return path18.join(daemonDirById(baseDir, id3), "status.json");
45315
45606
  }
45316
45607
  function isProcessAlive(pid) {
45317
45608
  try {
@@ -45371,9 +45662,9 @@ function syncDirectory(dir) {
45371
45662
  }
45372
45663
  }
45373
45664
  function writeExclusive(filePath, value) {
45374
- const dir = path17.dirname(filePath);
45665
+ const dir = path18.dirname(filePath);
45375
45666
  ensurePrivateDir2(dir);
45376
- const tempPath = path17.join(dir, `.${path17.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45667
+ const tempPath = path18.join(dir, `.${path18.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45377
45668
  let fd = fs12.openSync(tempPath, "wx", 384);
45378
45669
  try {
45379
45670
  fs12.writeFileSync(fd, JSON.stringify(value));
@@ -45395,9 +45686,9 @@ function writeExclusive(filePath, value) {
45395
45686
  }
45396
45687
  }
45397
45688
  function writePrivateJsonAtomic2(filePath, value) {
45398
- const dir = path17.dirname(filePath);
45689
+ const dir = path18.dirname(filePath);
45399
45690
  ensurePrivateDir2(dir);
45400
- const tempPath = path17.join(dir, `.${path17.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45691
+ const tempPath = path18.join(dir, `.${path18.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45401
45692
  let fd = fs12.openSync(tempPath, "wx", 384);
45402
45693
  try {
45403
45694
  fs12.writeFileSync(fd, JSON.stringify(value));
@@ -45484,7 +45775,7 @@ function clearStaleOwnership(filePath, liveError) {
45484
45775
  } catch {}
45485
45776
  }
45486
45777
  function replacementLockPathById(baseDir, machineId) {
45487
- return path17.join(daemonDirById(baseDir, machineId), "daemon.replace.lock");
45778
+ return path18.join(daemonDirById(baseDir, machineId), "daemon.replace.lock");
45488
45779
  }
45489
45780
  function readReplacementLock(filePath) {
45490
45781
  if (!fs12.existsSync(filePath))
@@ -45554,7 +45845,7 @@ function checkReplacementLock(baseDir, machineId, resumeRequestId) {
45554
45845
  }
45555
45846
  function acquireDaemonReplacementLock(args) {
45556
45847
  const lockPath = replacementLockPathById(args.baseDir, args.machineId);
45557
- ensurePrivateDir2(path17.dirname(lockPath));
45848
+ ensurePrivateDir2(path18.dirname(lockPath));
45558
45849
  checkReplacementLock(args.baseDir, args.machineId);
45559
45850
  const lock = {
45560
45851
  pid: process.pid,
@@ -45567,11 +45858,11 @@ function acquireDaemonReplacementLock(args) {
45567
45858
  return { path: lockPath, lock };
45568
45859
  }
45569
45860
  function coarseStartLockPath(baseDir) {
45570
- return path17.join(daemonsDir(baseDir), ".start.lock");
45861
+ return path18.join(daemonsDir(baseDir), ".start.lock");
45571
45862
  }
45572
45863
  function acquireCoarseLock(baseDir, ownerToken) {
45573
45864
  const lf = coarseStartLockPath(baseDir);
45574
- ensurePrivateDir2(path17.dirname(lf));
45865
+ ensurePrivateDir2(path18.dirname(lf));
45575
45866
  secureExistingFile(lf);
45576
45867
  clearStaleOwnership(lf, (pid) => new Error(`another daemon start is in progress on this machine (pid ${pid})`));
45577
45868
  writeExclusive(lf, { pid: process.pid, machineId: "coarse", startedAt: new Date().toISOString(), ownerToken });
@@ -45580,7 +45871,7 @@ function acquireCoarseLock(baseDir, ownerToken) {
45580
45871
  function acquireLaunchLock(baseDir, machineId, ownerToken, resumeRequestId) {
45581
45872
  const daemonDir = daemonDirById(baseDir, machineId);
45582
45873
  ensurePrivateDir2(daemonDir);
45583
- const lockPath = path17.join(daemonDir, "daemon.launch.lock");
45874
+ const lockPath = path18.join(daemonDir, "daemon.launch.lock");
45584
45875
  const finalPath = pidfilePathById(baseDir, machineId);
45585
45876
  checkReplacementLock(baseDir, machineId, resumeRequestId);
45586
45877
  secureExistingFile(lockPath);
@@ -45602,9 +45893,9 @@ function legacyPidfileCandidates(baseDir) {
45602
45893
  const candidates = [];
45603
45894
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45604
45895
  if (entry.isDirectory()) {
45605
- candidates.push(path17.join(dir, entry.name, "daemon.pid"));
45896
+ candidates.push(path18.join(dir, entry.name, "daemon.pid"));
45606
45897
  } else if (entry.isFile() && entry.name.endsWith(".pid")) {
45607
- candidates.push(path17.join(dir, entry.name));
45898
+ candidates.push(path18.join(dir, entry.name));
45608
45899
  }
45609
45900
  }
45610
45901
  return candidates;
@@ -45647,7 +45938,7 @@ function daemonList(opts) {
45647
45938
  return [];
45648
45939
  const results = [];
45649
45940
  const now = Date.now();
45650
- const pushRow = (id2, pidfile, statusPath) => {
45941
+ const pushRow = (id3, pidfile, statusPath) => {
45651
45942
  const data = readPidFile(pidfile);
45652
45943
  if (!data)
45653
45944
  return;
@@ -45671,12 +45962,12 @@ function daemonList(opts) {
45671
45962
  lastActiveMs = daemonLastActiveMs(s, now);
45672
45963
  }
45673
45964
  }
45674
- results.push({ id: id2, pid: data.pid, alive, agents, running, lastActiveMs });
45965
+ results.push({ id: id3, pid: data.pid, alive, agents, running, lastActiveMs });
45675
45966
  };
45676
45967
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45677
45968
  if (entry.isDirectory() && isDaemonId(entry.name)) {
45678
- const id2 = entry.name;
45679
- pushRow(id2, path17.join(dir, id2, "daemon.pid"), path17.join(dir, id2, "status.json"));
45969
+ const id3 = entry.name;
45970
+ pushRow(id3, path18.join(dir, id3, "daemon.pid"), path18.join(dir, id3, "status.json"));
45680
45971
  }
45681
45972
  }
45682
45973
  return results;
@@ -45724,7 +46015,7 @@ function daemonIdsWithStatus(baseDir) {
45724
46015
  return [];
45725
46016
  const ids = [];
45726
46017
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45727
- if (entry.isDirectory() && isDaemonId(entry.name) && fs12.existsSync(path17.join(dir, entry.name, "status.json"))) {
46018
+ if (entry.isDirectory() && isDaemonId(entry.name) && fs12.existsSync(path18.join(dir, entry.name, "status.json"))) {
45728
46019
  ids.push(entry.name);
45729
46020
  }
45730
46021
  }
@@ -45787,10 +46078,10 @@ async function stopByPidfile(pf, notFoundHint) {
45787
46078
  }
45788
46079
  async function daemonStop(opts) {
45789
46080
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
45790
- await stopByPidfile(path17.join(daemonDirById(baseDir, opts.id), "daemon.pid"), `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);
46081
+ await stopByPidfile(path18.join(daemonDirById(baseDir, opts.id), "daemon.pid"), `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);
45791
46082
  }
45792
46083
  function credentialFilePathByMachineId(baseDir, machineId) {
45793
- return path17.join(daemonsDir(baseDir), `${validateMachineId(machineId)}.credential.json`);
46084
+ return path18.join(daemonsDir(baseDir), `${validateMachineId(machineId)}.credential.json`);
45794
46085
  }
45795
46086
  function readCredentialFile(filePath) {
45796
46087
  if (!fs12.existsSync(filePath))
@@ -45817,18 +46108,18 @@ function readCredentialFile(filePath) {
45817
46108
  } catch {}
45818
46109
  return null;
45819
46110
  }
45820
- function writeCredentialFile(filePath, record6) {
45821
- writePrivateJsonAtomic2(filePath, record6);
46111
+ function writeCredentialFile(filePath, record7) {
46112
+ writePrivateJsonAtomic2(filePath, record7);
45822
46113
  }
45823
46114
  function readDaemonLaunchRecord(baseDir, machineId) {
45824
- const record6 = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
45825
- if (!record6 || !("schemaVersion" in record6) || record6.schemaVersion !== 1 || !parseReleaseVersion(record6.daemonVersion)) {
46115
+ const record7 = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
46116
+ if (!record7 || !("schemaVersion" in record7) || record7.schemaVersion !== 1 || !parseReleaseVersion(record7.daemonVersion)) {
45826
46117
  throw new Error("daemon launch record is missing or requires a manual start upgrade");
45827
46118
  }
45828
- validateMachineId(record6.machineId);
45829
- if (record6.machineId !== machineId)
46119
+ validateMachineId(record7.machineId);
46120
+ if (record7.machineId !== machineId)
45830
46121
  throw new Error("daemon launch record machine mismatch");
45831
- return record6;
46122
+ return record7;
45832
46123
  }
45833
46124
  function findExistingCredentialForBearer(baseDir, bearer) {
45834
46125
  const dir = daemonsDir(baseDir);
@@ -45837,7 +46128,7 @@ function findExistingCredentialForBearer(baseDir, bearer) {
45837
46128
  for (const file2 of fs12.readdirSync(dir)) {
45838
46129
  if (!file2.endsWith(".credential.json"))
45839
46130
  continue;
45840
- const parsed = readCredentialFile(path17.join(dir, file2));
46131
+ const parsed = readCredentialFile(path18.join(dir, file2));
45841
46132
  if (parsed && parsed.credential === bearer)
45842
46133
  return parsed;
45843
46134
  }
@@ -45993,23 +46284,23 @@ async function daemonResume(opts) {
45993
46284
  if (!/^[A-Za-z0-9_-]{16,128}$/.test(opts.requestId))
45994
46285
  throw new Error("invalid replacement request id");
45995
46286
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
45996
- const record6 = readDaemonLaunchRecord(baseDir, opts.id);
46287
+ const record7 = readDaemonLaunchRecord(baseDir, opts.id);
45997
46288
  if (false) {}
45998
46289
  await daemonStart({
45999
- machineKey: record6.credential,
46000
- serverUrl: record6.serverUrl,
46001
- wsUrl: record6.wsUrl,
46290
+ machineKey: record7.credential,
46291
+ serverUrl: record7.serverUrl,
46292
+ wsUrl: record7.wsUrl,
46002
46293
  baseDir,
46003
46294
  resumeRequestId: opts.requestId
46004
46295
  });
46005
46296
  }
46006
46297
  async function daemonStartById(opts) {
46007
46298
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
46008
- const record6 = readDaemonLaunchRecord(baseDir, opts.id);
46299
+ const record7 = readDaemonLaunchRecord(baseDir, opts.id);
46009
46300
  await daemonStart({
46010
- machineKey: record6.credential,
46011
- serverUrl: record6.serverUrl,
46012
- wsUrl: record6.wsUrl,
46301
+ machineKey: record7.credential,
46302
+ serverUrl: record7.serverUrl,
46303
+ wsUrl: record7.wsUrl,
46013
46304
  baseDir,
46014
46305
  foreground: opts.foreground
46015
46306
  });
@@ -46025,7 +46316,11 @@ async function daemonReconnect(opts, deps = {}) {
46025
46316
  }
46026
46317
  const machineId = validateMachineId(opts.id);
46027
46318
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
46028
- const launch = readDaemonLaunchRecord(baseDir, machineId);
46319
+ const launch = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
46320
+ if (launch && launch.machineId !== machineId)
46321
+ throw new Error("daemon launch record machine mismatch");
46322
+ const serverUrl = opts.serverUrl ?? (launch && "serverUrl" in launch ? launch.serverUrl : undefined);
46323
+ const wsUrl = opts.wsUrl ?? (launch && "wsUrl" in launch ? launch.wsUrl : undefined);
46029
46324
  const pidPath = pidfilePathById(baseDir, machineId);
46030
46325
  const before = readPidFile(pidPath);
46031
46326
  if (before && (before.machineId !== machineId || !before.startedAt || !before.ownerToken)) {
@@ -46041,6 +46336,9 @@ async function daemonReconnect(opts, deps = {}) {
46041
46336
  throw new Error("daemon ownership changed after reconnect lock acquisition");
46042
46337
  }
46043
46338
  if (owned && (deps.isProcessAlive ?? isProcessAlive)(owned.pid)) {
46339
+ if (!launch) {
46340
+ throw new Error(`cannot safely reconnect a running daemon without its saved credential; run daemon stop ${machineId}, then retry the reconnect command`);
46341
+ }
46044
46342
  await (deps.stopExactDaemonPid ?? stopExactDaemonPid)(owned.pid);
46045
46343
  oldStopped = true;
46046
46344
  removePidFileIfMatches(pidPath, owned);
@@ -46050,8 +46348,8 @@ async function daemonReconnect(opts, deps = {}) {
46050
46348
  try {
46051
46349
  await (deps.start ?? daemonStart)({
46052
46350
  machineKey: opts.machineKey,
46053
- serverUrl: opts.serverUrl ?? launch.serverUrl,
46054
- wsUrl: opts.wsUrl ?? launch.wsUrl,
46351
+ serverUrl,
46352
+ wsUrl,
46055
46353
  baseDir,
46056
46354
  resumeRequestId: requestId,
46057
46355
  expectedMachineId: machineId,
@@ -46063,7 +46361,17 @@ async function daemonReconnect(opts, deps = {}) {
46063
46361
  const canRestoreOldEpoch = !activationAttempted || error62 instanceof PairingActivationError && error62.sessionOutcome === "not_committed";
46064
46362
  if (oldStopped && canRestoreOldEpoch) {
46065
46363
  try {
46066
- await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
46364
+ if (deps.resume || launch && "daemonVersion" in launch && parseReleaseVersion(launch.daemonVersion)) {
46365
+ await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
46366
+ } else {
46367
+ await (deps.start ?? daemonStart)({
46368
+ machineKey: launch.credential,
46369
+ serverUrl,
46370
+ wsUrl,
46371
+ baseDir,
46372
+ resumeRequestId: requestId
46373
+ });
46374
+ }
46067
46375
  } catch (rollbackError) {
46068
46376
  throw new AggregateError([error62, rollbackError], "reconnect failed before rotation and the prior daemon could not be resumed");
46069
46377
  }
@@ -46118,7 +46426,7 @@ function waitForReceipt(child, prepared) {
46118
46426
  };
46119
46427
  const configuredTestTimeout = NaN;
46120
46428
  const receiptTimeoutMs = Number.isFinite(configuredTestTimeout) && configuredTestTimeout > 0 ? configuredTestTimeout : START_RECEIPT_TIMEOUT_MS;
46121
- const timeout = setTimeout(() => settle2(new Error(`daemon start timed out; inspect ${path17.join(prepared.daemonDir, "daemon.log")}`)), receiptTimeoutMs);
46429
+ const timeout = setTimeout(() => settle2(new Error(`daemon start timed out; inspect ${path18.join(prepared.daemonDir, "daemon.log")}`)), receiptTimeoutMs);
46122
46430
  child.on("message", (message2) => {
46123
46431
  const accepted = message2;
46124
46432
  if (accepted.type === "daemon:accepted") {
@@ -46137,7 +46445,7 @@ function waitForReceipt(child, prepared) {
46137
46445
  settle2(undefined, receipt);
46138
46446
  });
46139
46447
  child.once("exit", (code2, signal) => {
46140
- settle2(new Error(`daemon child exited before ready (${signal ?? code2}); inspect ${path17.join(prepared.daemonDir, "daemon.log")}`));
46448
+ settle2(new Error(`daemon child exited before ready (${signal ?? code2}); inspect ${path18.join(prepared.daemonDir, "daemon.log")}`));
46141
46449
  });
46142
46450
  child.once("error", (error62) => settle2(error62));
46143
46451
  });
@@ -46456,10 +46764,10 @@ function getApi() {
46456
46764
  throw new CliError("no ServerApi available — ALOOK_PROXY_URL + ALOOK_PROXY_TOKEN_FILE must be set");
46457
46765
  }
46458
46766
  function agentId(opts) {
46459
- const id2 = opts.agent || process.env.ALOOK_AGENT_ID || process.env.ALOOK_ID;
46460
- if (!id2)
46767
+ const id3 = opts.agent || process.env.ALOOK_AGENT_ID || process.env.ALOOK_ID;
46768
+ if (!id3)
46461
46769
  throw new CliError("agent identity required — pass --agent <id> or set ALOOK_AGENT_ID");
46462
- return id2;
46770
+ return id3;
46463
46771
  }
46464
46772
  var TEXT_ESCAPE_MAP = { n: `
46465
46773
  `, t: "\t", r: "\r", "\\": "\\" };
@@ -46748,14 +47056,14 @@ async function cmdAttachmentUpload(opts) {
46748
47056
  async function cmdAttachmentDownload(opts) {
46749
47057
  const api2 = getApi();
46750
47058
  const agent2 = agentId(opts);
46751
- const id2 = opts.id;
46752
- if (!id2)
47059
+ const id3 = opts.id;
47060
+ if (!id3)
46753
47061
  throw new CliError("message attachment download: --id <id> is required");
46754
47062
  const outFlag = opts.out;
46755
47063
  const os4 = await import("os");
46756
47064
  const pathMod = await import("path");
46757
- const destPath = outFlag ?? pathMod.join(os4.tmpdir(), "alook-attachments", agent2, id2, "file");
46758
- const result = await api2.attachmentDownload({ agentId: agent2, id: id2, destPath });
47065
+ const destPath = outFlag ?? pathMod.join(os4.tmpdir(), "alook-attachments", agent2, id3, "file");
47066
+ const result = await api2.attachmentDownload({ agentId: agent2, id: id3, destPath });
46759
47067
  if (!outFlag) {
46760
47068
  const fs13 = await import("fs/promises");
46761
47069
  const destDir = pathMod.dirname(destPath);
@@ -47124,13 +47432,13 @@ function buildProgram(stdin) {
47124
47432
  daemon.command("start").description("start the daemon (connects to server, manages agent lifecycles)").option("--machine-key <key>", "machine key for first-time pairing").option("--id <machineId>", "restart a previously paired machine by id").option("--server-url <url>", "server HTTP URL (or ALOOK_SERVER_URL; defaults to production)").option("--ws-url <url>", "server WebSocket URL (or ALOOK_SERVER_WS_URL; defaults to production)").option("--base-dir <path>", "data directory for agent workspaces and pidfile (or ALOOK_DATA_DIR env)").option("--foreground", "run in the current process and tee daemon logs to the terminal").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function() {
47125
47433
  const localOpts = this.opts();
47126
47434
  const machineKey = localOpts.machineKey;
47127
- const id2 = localOpts.id;
47128
- if (!machineKey && !id2 || machineKey && id2) {
47435
+ const id3 = localOpts.id;
47436
+ if (!machineKey && !id3 || machineKey && id3) {
47129
47437
  throw new CliError("daemon start requires exactly one of --machine-key <key> or --id <machineId>");
47130
47438
  }
47131
- if (id2) {
47439
+ if (id3) {
47132
47440
  await daemonStartById({
47133
- id: id2,
47441
+ id: id3,
47134
47442
  baseDir: localOpts.baseDir,
47135
47443
  foreground: localOpts.foreground === true
47136
47444
  });
@@ -47173,10 +47481,10 @@ function buildProgram(stdin) {
47173
47481
  requestId: localOpts.requestId
47174
47482
  });
47175
47483
  });
47176
- daemon.command("stop").argument("<id>", "daemon id from `alook daemon list` (the ID column)").description("stop a daemon by its id (from `alook daemon list`)").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function(id2) {
47484
+ daemon.command("stop").argument("<id>", "daemon id from `alook daemon list` (the ID column)").description("stop a daemon by its id (from `alook daemon list`)").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function(id3) {
47177
47485
  const localOpts = this.opts();
47178
47486
  await daemonStop({
47179
- id: id2,
47487
+ id: id3,
47180
47488
  baseDir: localOpts.baseDir
47181
47489
  });
47182
47490
  });
@@ -47190,9 +47498,9 @@ function buildProgram(stdin) {
47190
47498
  process.stdout.write(renderDaemonList(daemons) + `
47191
47499
  `);
47192
47500
  });
47193
- daemon.command("status").argument("[id]", "daemon id from `alook daemon list` (omit if only one daemon)").description("dump each agent's current FSM state from a daemon's status snapshot").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(function(id2) {
47501
+ daemon.command("status").argument("[id]", "daemon id from `alook daemon list` (omit if only one daemon)").description("dump each agent's current FSM state from a daemon's status snapshot").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(function(id3) {
47194
47502
  const localOpts = this.opts();
47195
- const status = daemonStatus({ id: id2, baseDir: localOpts.baseDir });
47503
+ const status = daemonStatus({ id: id3, baseDir: localOpts.baseDir });
47196
47504
  if (status.ambiguous) {
47197
47505
  printEnvelope({
47198
47506
  error: "multiple daemons on this machine — pass an id: `alook daemon status <id>`",