@halcyonlabs/app 0.47.0-halcyon.409 → 0.47.0-halcyon.411

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -83,8 +83,8 @@ declare const appSettingsSchema: z$1.ZodObject<{
83
83
  providerOrder: z$1.ZodArray<z$1.ZodString>;
84
84
  defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
85
85
  providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
86
- flat: "flat";
87
86
  collapse: "collapse";
87
+ flat: "flat";
88
88
  }>>;
89
89
  streamerMode: z$1.ZodBoolean;
90
90
  allowFastServiceTier: z$1.ZodBoolean;
@@ -105,8 +105,8 @@ declare const appSettingsUpdateSchema: z$1.ZodUnion<readonly [z$1.ZodObject<{
105
105
  providerOrder: z$1.ZodArray<z$1.ZodString>;
106
106
  defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
107
107
  providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
108
- flat: "flat";
109
108
  collapse: "collapse";
109
+ flat: "flat";
110
110
  }>>;
111
111
  streamerMode: z$1.ZodBoolean;
112
112
  managedBranchPrefix: z$1.ZodString;
@@ -143,8 +143,8 @@ declare const appSettingsUpdateSchema: z$1.ZodUnion<readonly [z$1.ZodObject<{
143
143
  providerOrder: z$1.ZodArray<z$1.ZodString>;
144
144
  defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
145
145
  providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
146
- flat: "flat";
147
146
  collapse: "collapse";
147
+ flat: "flat";
148
148
  }>>;
149
149
  streamerMode: z$1.ZodBoolean;
150
150
  machineServerUrl: z$1.ZodNullable<z$1.ZodString>;
@@ -524,8 +524,8 @@ declare const environmentSchema: z$1.ZodObject<{
524
524
  retireAt: z$1.ZodNullable<z$1.ZodNumber>;
525
525
  teardown: z$1.ZodNullable<z$1.ZodObject<{
526
526
  status: z$1.ZodEnum<{
527
- running: "running";
528
527
  failed: "failed";
528
+ running: "running";
529
529
  removed: "removed";
530
530
  }>;
531
531
  attempt: z$1.ZodNumber;
@@ -620,8 +620,8 @@ declare const hostSchema: z$1.ZodObject<{
620
620
  pendingLog: z$1.ZodString;
621
621
  teardown: z$1.ZodNullable<z$1.ZodObject<{
622
622
  status: z$1.ZodEnum<{
623
- running: "running";
624
623
  failed: "failed";
624
+ running: "running";
625
625
  removed: "removed";
626
626
  }>;
627
627
  attempt: z$1.ZodNumber;
@@ -732,8 +732,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
732
732
  providerThreadId: z$1.ZodString;
733
733
  objective: z$1.ZodString;
734
734
  status: z$1.ZodEnum<{
735
- paused: "paused";
736
735
  active: "active";
736
+ paused: "paused";
737
737
  budgetLimited: "budgetLimited";
738
738
  complete: "complete";
739
739
  }>;
@@ -1304,9 +1304,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1304
1304
  step: z$1.ZodString;
1305
1305
  status: z$1.ZodOptional<z$1.ZodEnum<{
1306
1306
  pending: "pending";
1307
+ active: "active";
1307
1308
  completed: "completed";
1308
1309
  failed: "failed";
1309
- active: "active";
1310
1310
  }>>;
1311
1311
  }, z$1.core.$strip>>;
1312
1312
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -1385,10 +1385,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1385
1385
  }>;
1386
1386
  taskStatus: z$1.ZodEnum<{
1387
1387
  pending: "pending";
1388
- running: "running";
1389
- paused: "paused";
1390
1388
  completed: "completed";
1391
1389
  failed: "failed";
1390
+ paused: "paused";
1391
+ running: "running";
1392
1392
  killed: "killed";
1393
1393
  stopped: "stopped";
1394
1394
  }>;
@@ -1405,8 +1405,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1405
1405
  index: z$1.ZodNumber;
1406
1406
  label: z$1.ZodString;
1407
1407
  state: z$1.ZodEnum<{
1408
- running: "running";
1409
1408
  failed: "failed";
1409
+ running: "running";
1410
1410
  queued: "queued";
1411
1411
  done: "done";
1412
1412
  skipped: "skipped";
@@ -2076,9 +2076,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2076
2076
  step: z$1.ZodString;
2077
2077
  status: z$1.ZodOptional<z$1.ZodEnum<{
2078
2078
  pending: "pending";
2079
+ active: "active";
2079
2080
  completed: "completed";
2080
2081
  failed: "failed";
2081
- active: "active";
2082
2082
  }>>;
2083
2083
  }, z$1.core.$strip>>;
2084
2084
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -2157,10 +2157,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2157
2157
  }>;
2158
2158
  taskStatus: z$1.ZodEnum<{
2159
2159
  pending: "pending";
2160
- running: "running";
2161
- paused: "paused";
2162
2160
  completed: "completed";
2163
2161
  failed: "failed";
2162
+ paused: "paused";
2163
+ running: "running";
2164
2164
  killed: "killed";
2165
2165
  stopped: "stopped";
2166
2166
  }>;
@@ -2177,8 +2177,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2177
2177
  index: z$1.ZodNumber;
2178
2178
  label: z$1.ZodString;
2179
2179
  state: z$1.ZodEnum<{
2180
- running: "running";
2181
2180
  failed: "failed";
2181
+ running: "running";
2182
2182
  queued: "queued";
2183
2183
  done: "done";
2184
2184
  skipped: "skipped";
@@ -2389,10 +2389,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2389
2389
  }>;
2390
2390
  taskStatus: z$1.ZodEnum<{
2391
2391
  pending: "pending";
2392
- running: "running";
2393
- paused: "paused";
2394
2392
  completed: "completed";
2395
2393
  failed: "failed";
2394
+ paused: "paused";
2395
+ running: "running";
2396
2396
  killed: "killed";
2397
2397
  stopped: "stopped";
2398
2398
  }>;
@@ -2409,8 +2409,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2409
2409
  index: z$1.ZodNumber;
2410
2410
  label: z$1.ZodString;
2411
2411
  state: z$1.ZodEnum<{
2412
- running: "running";
2413
2412
  failed: "failed";
2413
+ running: "running";
2414
2414
  queued: "queued";
2415
2415
  done: "done";
2416
2416
  skipped: "skipped";
@@ -2488,10 +2488,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2488
2488
  }>;
2489
2489
  taskStatus: z$1.ZodEnum<{
2490
2490
  pending: "pending";
2491
- running: "running";
2492
- paused: "paused";
2493
2491
  completed: "completed";
2494
2492
  failed: "failed";
2493
+ paused: "paused";
2494
+ running: "running";
2495
2495
  killed: "killed";
2496
2496
  stopped: "stopped";
2497
2497
  }>;
@@ -2508,8 +2508,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2508
2508
  index: z$1.ZodNumber;
2509
2509
  label: z$1.ZodString;
2510
2510
  state: z$1.ZodEnum<{
2511
- running: "running";
2512
2511
  failed: "failed";
2512
+ running: "running";
2513
2513
  queued: "queued";
2514
2514
  done: "done";
2515
2515
  skipped: "skipped";
@@ -2704,9 +2704,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2704
2704
  step: z$1.ZodString;
2705
2705
  status: z$1.ZodOptional<z$1.ZodEnum<{
2706
2706
  pending: "pending";
2707
+ active: "active";
2707
2708
  completed: "completed";
2708
2709
  failed: "failed";
2709
- active: "active";
2710
2710
  }>>;
2711
2711
  }, z$1.core.$strip>>;
2712
2712
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -2715,8 +2715,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2715
2715
  threadId: z$1.ZodString;
2716
2716
  providerThreadId: z$1.ZodString;
2717
2717
  state: z$1.ZodEnum<{
2718
- running: "running";
2719
2718
  idle: "idle";
2719
+ running: "running";
2720
2720
  }>;
2721
2721
  }, z$1.core.$strip>, z$1.ZodObject<{
2722
2722
  type: z$1.ZodLiteral<"turn/diff/updated">;
@@ -3578,9 +3578,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
3578
3578
  threadId: z$1.ZodString;
3579
3579
  provisioningId: z$1.ZodString;
3580
3580
  status: z$1.ZodEnum<{
3581
+ active: "active";
3581
3582
  completed: "completed";
3582
3583
  failed: "failed";
3583
- active: "active";
3584
3584
  cancelled: "cancelled";
3585
3585
  }>;
3586
3586
  environmentId: z$1.ZodNullable<z$1.ZodString>;
@@ -4240,8 +4240,8 @@ declare const providerInfoSchema: z$1.ZodObject<{
4240
4240
  }, z$1.core.$strip>;
4241
4241
  }, z$1.core.$strip>], "kind">>;
4242
4242
  completedTurnDisplay: z$1.ZodEnum<{
4243
- flat: "flat";
4244
4243
  collapse: "collapse";
4244
+ flat: "flat";
4245
4245
  }>;
4246
4246
  available: z$1.ZodBoolean;
4247
4247
  strings: z$1.ZodOptional<z$1.ZodObject<{
@@ -4329,8 +4329,8 @@ declare const threadTimelinePendingTodosSchema: z$1.ZodObject<{
4329
4329
  type ThreadTimelinePendingTodos = z$1.infer<typeof threadTimelinePendingTodosSchema>;
4330
4330
 
4331
4331
  declare const threadParentNotificationsSchema: z$1.ZodEnum<{
4332
- off: "off";
4333
4332
  auto: "auto";
4333
+ off: "off";
4334
4334
  stuck: "stuck";
4335
4335
  }>;
4336
4336
  type ThreadParentNotifications = z$1.infer<typeof threadParentNotificationsSchema>;
@@ -5766,9 +5766,9 @@ declare const hostDaemonCommandRegistry: {
5766
5766
  }, z$1.core.$strict>, z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
5767
5767
  kind: z$1.ZodLiteral<"wording">;
5768
5768
  status: z$1.ZodEnum<{
5769
- unavailable: "unavailable";
5770
5769
  pass: "pass";
5771
5770
  revise: "revise";
5771
+ unavailable: "unavailable";
5772
5772
  }>;
5773
5773
  }, z$1.core.$strict>, z$1.ZodObject<{
5774
5774
  kind: z$1.ZodLiteral<"review">;
@@ -6009,8 +6009,8 @@ declare const hostDaemonCommandRegistry: {
6009
6009
  providerInstallation: z$1.ZodBoolean;
6010
6010
  supportsServiceTier: z$1.ZodBoolean;
6011
6011
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6012
- auto: "auto";
6013
6012
  "accept-edits": "accept-edits";
6013
+ auto: "auto";
6014
6014
  full: "full";
6015
6015
  }>>;
6016
6016
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6036,16 +6036,16 @@ declare const hostDaemonCommandRegistry: {
6036
6036
  permissionScope: z$1.ZodLiteral<"workspace">;
6037
6037
  approvalReviewer: z$1.ZodLiteral<"user">;
6038
6038
  permissionEscalation: z$1.ZodEnum<{
6039
- deny: "deny";
6040
6039
  ask: "ask";
6040
+ deny: "deny";
6041
6041
  }>;
6042
6042
  }, z$1.core.$strip>, z$1.ZodObject<{
6043
6043
  permissionMode: z$1.ZodLiteral<"auto">;
6044
6044
  permissionScope: z$1.ZodLiteral<"workspace">;
6045
6045
  approvalReviewer: z$1.ZodLiteral<"automatic">;
6046
6046
  permissionEscalation: z$1.ZodEnum<{
6047
- deny: "deny";
6048
6047
  ask: "ask";
6048
+ deny: "deny";
6049
6049
  }>;
6050
6050
  }, z$1.core.$strip>, z$1.ZodObject<{
6051
6051
  permissionMode: z$1.ZodLiteral<"full">;
@@ -6129,8 +6129,8 @@ declare const hostDaemonCommandRegistry: {
6129
6129
  skillFilePath: z$1.ZodString;
6130
6130
  }, z$1.core.$strict>], "kind">>;
6131
6131
  instructionMode: z$1.ZodEnum<{
6132
- append: "append";
6133
6132
  replace: "replace";
6133
+ append: "append";
6134
6134
  }>;
6135
6135
  type: z$1.ZodLiteral<"thread.rewind.prepare">;
6136
6136
  leaseId: z$1.ZodString;
@@ -6158,8 +6158,8 @@ declare const hostDaemonCommandRegistry: {
6158
6158
  providerInstallation: z$1.ZodBoolean;
6159
6159
  supportsServiceTier: z$1.ZodBoolean;
6160
6160
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6161
- auto: "auto";
6162
6161
  "accept-edits": "accept-edits";
6162
+ auto: "auto";
6163
6163
  full: "full";
6164
6164
  }>>;
6165
6165
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6185,16 +6185,16 @@ declare const hostDaemonCommandRegistry: {
6185
6185
  permissionScope: z$1.ZodLiteral<"workspace">;
6186
6186
  approvalReviewer: z$1.ZodLiteral<"user">;
6187
6187
  permissionEscalation: z$1.ZodEnum<{
6188
- deny: "deny";
6189
6188
  ask: "ask";
6189
+ deny: "deny";
6190
6190
  }>;
6191
6191
  }, z$1.core.$strip>, z$1.ZodObject<{
6192
6192
  permissionMode: z$1.ZodLiteral<"auto">;
6193
6193
  permissionScope: z$1.ZodLiteral<"workspace">;
6194
6194
  approvalReviewer: z$1.ZodLiteral<"automatic">;
6195
6195
  permissionEscalation: z$1.ZodEnum<{
6196
- deny: "deny";
6197
6196
  ask: "ask";
6197
+ deny: "deny";
6198
6198
  }>;
6199
6199
  }, z$1.core.$strip>, z$1.ZodObject<{
6200
6200
  permissionMode: z$1.ZodLiteral<"full">;
@@ -6278,8 +6278,8 @@ declare const hostDaemonCommandRegistry: {
6278
6278
  skillFilePath: z$1.ZodString;
6279
6279
  }, z$1.core.$strict>], "kind">>;
6280
6280
  instructionMode: z$1.ZodEnum<{
6281
- append: "append";
6282
6281
  replace: "replace";
6282
+ append: "append";
6283
6283
  }>;
6284
6284
  type: z$1.ZodLiteral<"thread.start">;
6285
6285
  requestId: z$1.ZodString;
@@ -6329,9 +6329,9 @@ declare const hostDaemonCommandRegistry: {
6329
6329
  skill: "skill";
6330
6330
  }>;
6331
6331
  origin: z$1.ZodEnum<{
6332
- user: "user";
6333
- project: "project";
6334
6332
  builtin: "builtin";
6333
+ project: "project";
6334
+ user: "user";
6335
6335
  }>;
6336
6336
  label: z$1.ZodString;
6337
6337
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
@@ -6419,9 +6419,9 @@ declare const hostDaemonCommandRegistry: {
6419
6419
  skill: "skill";
6420
6420
  }>;
6421
6421
  origin: z$1.ZodEnum<{
6422
- user: "user";
6423
- project: "project";
6424
6422
  builtin: "builtin";
6423
+ project: "project";
6424
+ user: "user";
6425
6425
  }>;
6426
6426
  label: z$1.ZodString;
6427
6427
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
@@ -6522,9 +6522,9 @@ declare const hostDaemonCommandRegistry: {
6522
6522
  skill: "skill";
6523
6523
  }>;
6524
6524
  origin: z$1.ZodEnum<{
6525
- user: "user";
6526
- project: "project";
6527
6525
  builtin: "builtin";
6526
+ project: "project";
6527
+ user: "user";
6528
6528
  }>;
6529
6529
  label: z$1.ZodString;
6530
6530
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
@@ -6612,9 +6612,9 @@ declare const hostDaemonCommandRegistry: {
6612
6612
  skill: "skill";
6613
6613
  }>;
6614
6614
  origin: z$1.ZodEnum<{
6615
- user: "user";
6616
- project: "project";
6617
6615
  builtin: "builtin";
6616
+ project: "project";
6617
+ user: "user";
6618
6618
  }>;
6619
6619
  label: z$1.ZodString;
6620
6620
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
@@ -6668,16 +6668,16 @@ declare const hostDaemonCommandRegistry: {
6668
6668
  permissionScope: z$1.ZodLiteral<"workspace">;
6669
6669
  approvalReviewer: z$1.ZodLiteral<"user">;
6670
6670
  permissionEscalation: z$1.ZodEnum<{
6671
- deny: "deny";
6672
6671
  ask: "ask";
6672
+ deny: "deny";
6673
6673
  }>;
6674
6674
  }, z$1.core.$strip>, z$1.ZodObject<{
6675
6675
  permissionMode: z$1.ZodLiteral<"auto">;
6676
6676
  permissionScope: z$1.ZodLiteral<"workspace">;
6677
6677
  approvalReviewer: z$1.ZodLiteral<"automatic">;
6678
6678
  permissionEscalation: z$1.ZodEnum<{
6679
- deny: "deny";
6680
6679
  ask: "ask";
6680
+ deny: "deny";
6681
6681
  }>;
6682
6682
  }, z$1.core.$strip>, z$1.ZodObject<{
6683
6683
  permissionMode: z$1.ZodLiteral<"full">;
@@ -6696,8 +6696,8 @@ declare const hostDaemonCommandRegistry: {
6696
6696
  providerInstallation: z$1.ZodBoolean;
6697
6697
  supportsServiceTier: z$1.ZodBoolean;
6698
6698
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6699
- auto: "auto";
6700
6699
  "accept-edits": "accept-edits";
6700
+ auto: "auto";
6701
6701
  full: "full";
6702
6702
  }>>;
6703
6703
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6715,9 +6715,6 @@ declare const hostDaemonCommandRegistry: {
6715
6715
  workspaceContext: z$1.ZodObject<{
6716
6716
  workspacePath: z$1.ZodString;
6717
6717
  }, z$1.core.$strip>;
6718
- projectId: z$1.ZodString;
6719
- providerThreadId: z$1.ZodString;
6720
- providerId: z$1.ZodString;
6721
6718
  bridgeLaunch: z$1.ZodObject<{
6722
6719
  pluginId: z$1.ZodString;
6723
6720
  source: z$1.ZodObject<{
@@ -6729,8 +6726,8 @@ declare const hostDaemonCommandRegistry: {
6729
6726
  providerInstallation: z$1.ZodBoolean;
6730
6727
  supportsServiceTier: z$1.ZodBoolean;
6731
6728
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6732
- auto: "auto";
6733
6729
  "accept-edits": "accept-edits";
6730
+ auto: "auto";
6734
6731
  full: "full";
6735
6732
  }>>;
6736
6733
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6745,9 +6742,11 @@ declare const hostDaemonCommandRegistry: {
6745
6742
  envPassthrough: z$1.ZodArray<z$1.ZodString>;
6746
6743
  }, z$1.core.$strict>;
6747
6744
  instructionMode: z$1.ZodEnum<{
6748
- append: "append";
6749
6745
  replace: "replace";
6746
+ append: "append";
6750
6747
  }>;
6748
+ projectId: z$1.ZodString;
6749
+ providerId: z$1.ZodString;
6751
6750
  instructions: z$1.ZodString;
6752
6751
  dynamicTools: z$1.ZodArray<z$1.ZodObject<{
6753
6752
  name: z$1.ZodString;
@@ -6823,6 +6822,7 @@ declare const hostDaemonCommandRegistry: {
6823
6822
  sourceRootPath: z$1.ZodString;
6824
6823
  skillFilePath: z$1.ZodString;
6825
6824
  }, z$1.core.$strict>], "kind">>;
6825
+ providerThreadId: z$1.ZodString;
6826
6826
  }, z$1.core.$strict>;
6827
6827
  target: z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
6828
6828
  mode: z$1.ZodLiteral<"start">;
@@ -6884,16 +6884,16 @@ declare const hostDaemonCommandRegistry: {
6884
6884
  permissionScope: z$1.ZodLiteral<"workspace">;
6885
6885
  approvalReviewer: z$1.ZodLiteral<"user">;
6886
6886
  permissionEscalation: z$1.ZodEnum<{
6887
- deny: "deny";
6888
6887
  ask: "ask";
6888
+ deny: "deny";
6889
6889
  }>;
6890
6890
  }, z$1.core.$strip>, z$1.ZodObject<{
6891
6891
  permissionMode: z$1.ZodLiteral<"auto">;
6892
6892
  permissionScope: z$1.ZodLiteral<"workspace">;
6893
6893
  approvalReviewer: z$1.ZodLiteral<"automatic">;
6894
6894
  permissionEscalation: z$1.ZodEnum<{
6895
- deny: "deny";
6896
6895
  ask: "ask";
6896
+ deny: "deny";
6897
6897
  }>;
6898
6898
  }, z$1.core.$strip>, z$1.ZodObject<{
6899
6899
  permissionMode: z$1.ZodLiteral<"full">;
@@ -6912,8 +6912,8 @@ declare const hostDaemonCommandRegistry: {
6912
6912
  providerInstallation: z$1.ZodBoolean;
6913
6913
  supportsServiceTier: z$1.ZodBoolean;
6914
6914
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6915
- auto: "auto";
6916
6915
  "accept-edits": "accept-edits";
6916
+ auto: "auto";
6917
6917
  full: "full";
6918
6918
  }>>;
6919
6919
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6931,9 +6931,6 @@ declare const hostDaemonCommandRegistry: {
6931
6931
  workspaceContext: z$1.ZodObject<{
6932
6932
  workspacePath: z$1.ZodString;
6933
6933
  }, z$1.core.$strip>;
6934
- projectId: z$1.ZodString;
6935
- providerThreadId: z$1.ZodString;
6936
- providerId: z$1.ZodString;
6937
6934
  bridgeLaunch: z$1.ZodObject<{
6938
6935
  pluginId: z$1.ZodString;
6939
6936
  source: z$1.ZodObject<{
@@ -6945,8 +6942,8 @@ declare const hostDaemonCommandRegistry: {
6945
6942
  providerInstallation: z$1.ZodBoolean;
6946
6943
  supportsServiceTier: z$1.ZodBoolean;
6947
6944
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
6948
- auto: "auto";
6949
6945
  "accept-edits": "accept-edits";
6946
+ auto: "auto";
6950
6947
  full: "full";
6951
6948
  }>>;
6952
6949
  supportsThreadArchive: z$1.ZodBoolean;
@@ -6961,9 +6958,11 @@ declare const hostDaemonCommandRegistry: {
6961
6958
  envPassthrough: z$1.ZodArray<z$1.ZodString>;
6962
6959
  }, z$1.core.$strict>;
6963
6960
  instructionMode: z$1.ZodEnum<{
6964
- append: "append";
6965
6961
  replace: "replace";
6962
+ append: "append";
6966
6963
  }>;
6964
+ projectId: z$1.ZodString;
6965
+ providerId: z$1.ZodString;
6967
6966
  instructions: z$1.ZodString;
6968
6967
  dynamicTools: z$1.ZodArray<z$1.ZodObject<{
6969
6968
  name: z$1.ZodString;
@@ -7039,6 +7038,7 @@ declare const hostDaemonCommandRegistry: {
7039
7038
  sourceRootPath: z$1.ZodString;
7040
7039
  skillFilePath: z$1.ZodString;
7041
7040
  }, z$1.core.$strict>], "kind">>;
7041
+ providerThreadId: z$1.ZodString;
7042
7042
  }, z$1.core.$strict>;
7043
7043
  }, z$1.core.$strict>, z$1.ZodObject<{
7044
7044
  cleared: z$1.ZodBoolean;
@@ -7077,8 +7077,8 @@ declare const hostDaemonCommandRegistry: {
7077
7077
  providerInstallation: z$1.ZodBoolean;
7078
7078
  supportsServiceTier: z$1.ZodBoolean;
7079
7079
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
7080
- auto: "auto";
7081
7080
  "accept-edits": "accept-edits";
7081
+ auto: "auto";
7082
7082
  full: "full";
7083
7083
  }>>;
7084
7084
  supportsThreadArchive: z$1.ZodBoolean;
@@ -7110,8 +7110,8 @@ declare const hostDaemonCommandRegistry: {
7110
7110
  providerInstallation: z$1.ZodBoolean;
7111
7111
  supportsServiceTier: z$1.ZodBoolean;
7112
7112
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
7113
- auto: "auto";
7114
7113
  "accept-edits": "accept-edits";
7114
+ auto: "auto";
7115
7115
  full: "full";
7116
7116
  }>>;
7117
7117
  supportsThreadArchive: z$1.ZodBoolean;
@@ -7493,8 +7493,8 @@ declare const hostDaemonCommandRegistry: {
7493
7493
  skills: z$1.ZodArray<z$1.ZodObject<{
7494
7494
  path: z$1.ZodString;
7495
7495
  origin: z$1.ZodEnum<{
7496
- user: "user";
7497
7496
  project: "project";
7497
+ user: "user";
7498
7498
  }>;
7499
7499
  recursive: z$1.ZodBoolean;
7500
7500
  ancestors: z$1.ZodBoolean;
@@ -7512,8 +7512,8 @@ declare const hostDaemonCommandRegistry: {
7512
7512
  commands: z$1.ZodArray<z$1.ZodObject<{
7513
7513
  path: z$1.ZodString;
7514
7514
  origin: z$1.ZodEnum<{
7515
- user: "user";
7516
7515
  project: "project";
7516
+ user: "user";
7517
7517
  }>;
7518
7518
  recursive: z$1.ZodBoolean;
7519
7519
  ancestors: z$1.ZodBoolean;
@@ -7538,8 +7538,8 @@ declare const hostDaemonCommandRegistry: {
7538
7538
  skill: "skill";
7539
7539
  }>;
7540
7540
  origin: z$1.ZodEnum<{
7541
- user: "user";
7542
7541
  project: "project";
7542
+ user: "user";
7543
7543
  }>;
7544
7544
  description: z$1.ZodNullable<z$1.ZodString>;
7545
7545
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
@@ -7586,8 +7586,8 @@ declare const hostDaemonCommandRegistry: {
7586
7586
  skills: z$1.ZodArray<z$1.ZodObject<{
7587
7587
  path: z$1.ZodString;
7588
7588
  origin: z$1.ZodEnum<{
7589
- user: "user";
7590
7589
  project: "project";
7590
+ user: "user";
7591
7591
  }>;
7592
7592
  recursive: z$1.ZodBoolean;
7593
7593
  ancestors: z$1.ZodBoolean;
@@ -7605,8 +7605,8 @@ declare const hostDaemonCommandRegistry: {
7605
7605
  commands: z$1.ZodArray<z$1.ZodObject<{
7606
7606
  path: z$1.ZodString;
7607
7607
  origin: z$1.ZodEnum<{
7608
- user: "user";
7609
7608
  project: "project";
7609
+ user: "user";
7610
7610
  }>;
7611
7611
  recursive: z$1.ZodBoolean;
7612
7612
  ancestors: z$1.ZodBoolean;
@@ -7632,14 +7632,14 @@ declare const hostDaemonCommandRegistry: {
7632
7632
  realPath: z$1.ZodString;
7633
7633
  contentSha256: z$1.ZodString;
7634
7634
  rootKind: z$1.ZodEnum<{
7635
- plugin: "plugin";
7636
7635
  "shared-user": "shared-user";
7637
7636
  "shared-project": "shared-project";
7637
+ plugin: "plugin";
7638
7638
  "bb-project": "bb-project";
7639
+ "provider-user": "provider-user";
7640
+ "provider-project": "provider-project";
7639
7641
  "bb-data-dir": "bb-data-dir";
7640
7642
  "bb-builtin": "bb-builtin";
7641
- "provider-project": "provider-project";
7642
- "provider-user": "provider-user";
7643
7643
  }>;
7644
7644
  linked: z$1.ZodBoolean;
7645
7645
  }, z$1.core.$strip>>;
@@ -7693,14 +7693,14 @@ declare const hostDaemonCommandRegistry: {
7693
7693
  realPath: z$1.ZodString;
7694
7694
  contentSha256: z$1.ZodString;
7695
7695
  rootKind: z$1.ZodEnum<{
7696
- plugin: "plugin";
7697
7696
  "shared-user": "shared-user";
7698
7697
  "shared-project": "shared-project";
7698
+ plugin: "plugin";
7699
7699
  "bb-project": "bb-project";
7700
+ "provider-user": "provider-user";
7701
+ "provider-project": "provider-project";
7700
7702
  "bb-data-dir": "bb-data-dir";
7701
7703
  "bb-builtin": "bb-builtin";
7702
- "provider-project": "provider-project";
7703
- "provider-user": "provider-user";
7704
7704
  }>;
7705
7705
  linked: z$1.ZodBoolean;
7706
7706
  }, z$1.core.$strip>>;
@@ -7708,10 +7708,10 @@ declare const hostDaemonCommandRegistry: {
7708
7708
  "host.delete_skill": HostDaemonCommandDescriptor<"host.delete_skill", z$1.ZodObject<{
7709
7709
  type: z$1.ZodLiteral<"host.delete_skill">;
7710
7710
  scope: z$1.ZodEnum<{
7711
+ "bb-user": "bb-user";
7711
7712
  "bb-project": "bb-project";
7712
- "provider-project": "provider-project";
7713
7713
  "provider-user": "provider-user";
7714
- "bb-user": "bb-user";
7714
+ "provider-project": "provider-project";
7715
7715
  }>;
7716
7716
  name: z$1.ZodString;
7717
7717
  cwd: z$1.ZodNullable<z$1.ZodString>;
@@ -7722,8 +7722,8 @@ declare const hostDaemonCommandRegistry: {
7722
7722
  "host.write_skill": HostDaemonCommandDescriptor<"host.write_skill", z$1.ZodObject<{
7723
7723
  type: z$1.ZodLiteral<"host.write_skill">;
7724
7724
  scope: z$1.ZodEnum<{
7725
- "bb-project": "bb-project";
7726
7725
  "bb-user": "bb-user";
7726
+ "bb-project": "bb-project";
7727
7727
  }>;
7728
7728
  name: z$1.ZodString;
7729
7729
  cwd: z$1.ZodNullable<z$1.ZodString>;
@@ -7820,8 +7820,8 @@ declare const hostDaemonCommandRegistry: {
7820
7820
  selectedBranch: z$1.ZodOptional<z$1.ZodString>;
7821
7821
  limit: z$1.ZodNumber;
7822
7822
  remoteRefresh: z$1.ZodEnum<{
7823
- background: "background";
7824
7823
  none: "none";
7824
+ background: "background";
7825
7825
  }>;
7826
7826
  }, z$1.core.$strict>, z$1.ZodObject<{
7827
7827
  branches: z$1.ZodArray<z$1.ZodString>;
@@ -7860,14 +7860,14 @@ declare const hostDaemonCommandRegistry: {
7860
7860
  modifiedAtMs: z$1.ZodOptional<z$1.ZodNumber>;
7861
7861
  sha256: z$1.ZodString;
7862
7862
  }, z$1.core.$strip>, z$1.ZodObject<{
7863
+ path: z$1.ZodString;
7863
7864
  contentEncoding: z$1.ZodEnum<{
7864
7865
  base64: "base64";
7865
7866
  utf8: "utf8";
7866
7867
  }>;
7867
- sha256: z$1.ZodString;
7868
- sizeBytes: z$1.ZodNumber;
7869
- path: z$1.ZodString;
7870
7868
  mimeType: z$1.ZodOptional<z$1.ZodString>;
7869
+ sizeBytes: z$1.ZodNumber;
7870
+ sha256: z$1.ZodString;
7871
7871
  modifiedAtMs: z$1.ZodOptional<z$1.ZodNumber>;
7872
7872
  notModified: z$1.ZodLiteral<true>;
7873
7873
  }, z$1.core.$strip>]>, "onlineRpc", true>;
@@ -7942,8 +7942,8 @@ declare const hostDaemonCommandRegistry: {
7942
7942
  providerInstallation: z$1.ZodBoolean;
7943
7943
  supportsServiceTier: z$1.ZodBoolean;
7944
7944
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
7945
- auto: "auto";
7946
7945
  "accept-edits": "accept-edits";
7946
+ auto: "auto";
7947
7947
  full: "full";
7948
7948
  }>>;
7949
7949
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8072,8 +8072,8 @@ declare const hostDaemonCommandRegistry: {
8072
8072
  providerInstallation: z$1.ZodBoolean;
8073
8073
  supportsServiceTier: z$1.ZodBoolean;
8074
8074
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
8075
- auto: "auto";
8076
8075
  "accept-edits": "accept-edits";
8076
+ auto: "auto";
8077
8077
  full: "full";
8078
8078
  }>>;
8079
8079
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8109,8 +8109,8 @@ declare const hostDaemonCommandRegistry: {
8109
8109
  providerInstallation: z$1.ZodBoolean;
8110
8110
  supportsServiceTier: z$1.ZodBoolean;
8111
8111
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
8112
- auto: "auto";
8113
8112
  "accept-edits": "accept-edits";
8113
+ auto: "auto";
8114
8114
  full: "full";
8115
8115
  }>>;
8116
8116
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8132,10 +8132,10 @@ declare const hostDaemonCommandRegistry: {
8132
8132
  health: z$1.ZodObject<{
8133
8133
  status: z$1.ZodEnum<{
8134
8134
  unknown: "unknown";
8135
- ready: "ready";
8136
8135
  not_installed: "not_installed";
8137
8136
  unauthenticated: "unauthenticated";
8138
8137
  expired: "expired";
8138
+ ready: "ready";
8139
8139
  unsupported_version: "unsupported_version";
8140
8140
  }>;
8141
8141
  statusMessage: z$1.ZodNullable<z$1.ZodString>;
@@ -8163,8 +8163,8 @@ declare const hostDaemonCommandRegistry: {
8163
8163
  providerInstallation: z$1.ZodBoolean;
8164
8164
  supportsServiceTier: z$1.ZodBoolean;
8165
8165
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
8166
- auto: "auto";
8167
8166
  "accept-edits": "accept-edits";
8167
+ auto: "auto";
8168
8168
  full: "full";
8169
8169
  }>>;
8170
8170
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8183,9 +8183,9 @@ declare const hostDaemonCommandRegistry: {
8183
8183
  executablePath: z$1.ZodNullable<z$1.ZodString>;
8184
8184
  installed: z$1.ZodBoolean;
8185
8185
  installSource: z$1.ZodEnum<{
8186
- external: "external";
8187
8186
  notInstalled: "notInstalled";
8188
8187
  npmGlobal: "npmGlobal";
8188
+ external: "external";
8189
8189
  }>;
8190
8190
  currentVersion: z$1.ZodNullable<z$1.ZodString>;
8191
8191
  latestVersion: z$1.ZodNullable<z$1.ZodString>;
@@ -8194,8 +8194,8 @@ declare const hostDaemonCommandRegistry: {
8194
8194
  npmGlobalPackageVersion: z$1.ZodNullable<z$1.ZodString>;
8195
8195
  installAction: z$1.ZodNullable<z$1.ZodObject<{
8196
8196
  kind: z$1.ZodEnum<{
8197
- update: "update";
8198
8197
  install: "install";
8198
+ update: "update";
8199
8199
  }>;
8200
8200
  label: z$1.ZodEnum<{
8201
8201
  Install: "Install";
@@ -8210,8 +8210,8 @@ declare const hostDaemonCommandRegistry: {
8210
8210
  type: z$1.ZodLiteral<"provider.installation.run">;
8211
8211
  providerId: z$1.ZodString;
8212
8212
  action: z$1.ZodEnum<{
8213
- update: "update";
8214
8213
  install: "install";
8214
+ update: "update";
8215
8215
  }>;
8216
8216
  bridgeLaunch: z$1.ZodObject<{
8217
8217
  pluginId: z$1.ZodString;
@@ -8224,8 +8224,8 @@ declare const hostDaemonCommandRegistry: {
8224
8224
  providerInstallation: z$1.ZodBoolean;
8225
8225
  supportsServiceTier: z$1.ZodBoolean;
8226
8226
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
8227
- auto: "auto";
8228
8227
  "accept-edits": "accept-edits";
8228
+ auto: "auto";
8229
8229
  full: "full";
8230
8230
  }>>;
8231
8231
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8278,8 +8278,8 @@ declare const hostDaemonCommandRegistry: {
8278
8278
  providerInstallation: z$1.ZodBoolean;
8279
8279
  supportsServiceTier: z$1.ZodBoolean;
8280
8280
  permissionModes: z$1.ZodArray<z$1.ZodEnum<{
8281
- auto: "auto";
8282
8281
  "accept-edits": "accept-edits";
8282
+ auto: "auto";
8283
8283
  full: "full";
8284
8284
  }>>;
8285
8285
  supportsThreadArchive: z$1.ZodBoolean;
@@ -8631,8 +8631,8 @@ declare const hostDaemonCommandRegistry: {
8631
8631
  message: z$1.ZodNullable<z$1.ZodString>;
8632
8632
  state: z$1.ZodNullable<z$1.ZodEnum<{
8633
8633
  pending: "pending";
8634
- activating: "activating";
8635
8634
  ready: "ready";
8635
+ activating: "activating";
8636
8636
  }>>;
8637
8637
  }, z$1.core.$strict>, "onlineRpc", true>;
8638
8638
  "server_move.prepare": HostDaemonCommandDescriptor<"server_move.prepare", z$1.ZodObject<{
@@ -8734,9 +8734,9 @@ declare const providerCliStatusResponseSchema: z$1.ZodRecord<z$1.ZodString, z$1.
8734
8734
  executablePath: z$1.ZodNullable<z$1.ZodString>;
8735
8735
  installed: z$1.ZodBoolean;
8736
8736
  installSource: z$1.ZodEnum<{
8737
- external: "external";
8738
8737
  notInstalled: "notInstalled";
8739
8738
  npmGlobal: "npmGlobal";
8739
+ external: "external";
8740
8740
  }>;
8741
8741
  currentVersion: z$1.ZodNullable<z$1.ZodString>;
8742
8742
  latestVersion: z$1.ZodNullable<z$1.ZodString>;
@@ -8745,8 +8745,8 @@ declare const providerCliStatusResponseSchema: z$1.ZodRecord<z$1.ZodString, z$1.
8745
8745
  npmGlobalPackageVersion: z$1.ZodNullable<z$1.ZodString>;
8746
8746
  installAction: z$1.ZodNullable<z$1.ZodObject<{
8747
8747
  kind: z$1.ZodEnum<{
8748
- update: "update";
8749
8748
  install: "install";
8749
+ update: "update";
8750
8750
  }>;
8751
8751
  label: z$1.ZodEnum<{
8752
8752
  Install: "Install";
@@ -8761,8 +8761,8 @@ type ProviderCliStatusResponse = z$1.infer<typeof providerCliStatusResponseSchem
8761
8761
  declare const providerCliInstallRequestSchema: z$1.ZodObject<{
8762
8762
  provider: z$1.ZodString;
8763
8763
  actionKind: z$1.ZodEnum<{
8764
- update: "update";
8765
8764
  install: "install";
8765
+ update: "update";
8766
8766
  }>;
8767
8767
  }, z$1.core.$strip>;
8768
8768
  type ProviderCliInstallRequest = z$1.infer<typeof providerCliInstallRequestSchema>;
@@ -16461,17 +16461,17 @@ declare const threadTimelineResponseSchema: z$1.ZodObject<{
16461
16461
  timeUsedSeconds: z$1.ZodNumber;
16462
16462
  }, z$1.core.$strip>>;
16463
16463
  providerCommands: z$1.ZodNullable<z$1.ZodArray<z$1.ZodObject<{
16464
+ source: z$1.ZodEnum<{
16465
+ command: "command";
16466
+ skill: "skill";
16467
+ }>;
16468
+ name: z$1.ZodString;
16464
16469
  origin: z$1.ZodEnum<{
16465
16470
  project: "project";
16466
16471
  builtin: "builtin";
16467
16472
  user: "user";
16468
16473
  }>;
16469
16474
  description: z$1.ZodNullable<z$1.ZodString>;
16470
- source: z$1.ZodEnum<{
16471
- command: "command";
16472
- skill: "skill";
16473
- }>;
16474
- name: z$1.ZodString;
16475
16475
  argumentHint: z$1.ZodNullable<z$1.ZodString>;
16476
16476
  }, z$1.core.$strip>>>;
16477
16477
  sessionOptions: z$1.ZodNullable<z$1.ZodArray<z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
@@ -23941,10 +23941,10 @@ declare function createApiClient(baseUrl: string, options?: PublicApiClientOptio
23941
23941
  timeUsedSeconds: number;
23942
23942
  } | null;
23943
23943
  providerCommands: {
23944
- origin: "project" | "builtin" | "user";
23945
- description: string | null;
23946
23944
  source: "command" | "skill";
23947
23945
  name: string;
23946
+ origin: "project" | "builtin" | "user";
23947
+ description: string | null;
23948
23948
  argumentHint: string | null;
23949
23949
  }[] | null;
23950
23950
  sessionOptions: ({
@@ -209,7 +209,7 @@ on error number -128
209
209
  return ""
210
210
  end try`],{env:vt({env:process.env})})).stdout}catch(n){throw new ge("folder_picker_failed",`Folder picker failed: ${n instanceof Error?n.message:String(n)}`)}let t=e.trim();return{path:t===""?null:t.replace(/\/$/,"")}}var g6e,Zoe=g(()=>{"use strict";Ee();Ye();g6e=h6e(f6e)});function lo(e){return e instanceof Error?e:new Error(String(e))}function fL(e){return e instanceof Error?{errorMessage:e.message,errorName:e.name}:{errorMessage:String(e),errorName:"NonError"}}function Xe(e){return process.env.NODE_ENV==="production"?fL(e):{err:e}}var Fi=g(()=>{"use strict"});import $i from"node:path";function y6e(e){return(e.includes("\\")?$i.win32.basename(e):$i.posix.basename(e)).toLowerCase().replace(/\.exe$/u,"")}function b6e(e){let t=y6e(e);return t==="pwsh"||t==="powershell"?"powershell":t==="cmd"?"cmd":"posix"}function x6e(e){return e.length===0?"''":/^[A-Za-z0-9_@%+=:,./-]+$/u.test(e)?e:`'${e.replaceAll("'",`'"'"'`)}'`}function w6e(e){return`'${e.replace(/['\u2018\u2019\u201a\u201b]/gu,"$&$&")}'`}function E6e(e){return/^[A-Za-z0-9_@+=:,.\\/-]+$/u.test(e)?e:`"${e.replaceAll('"','""')}"`}function P6e(e,t){if(t.mode==="command")return t.command;switch(e){case"powershell":return`& ${t.argv.map(w6e).join(" ")}`;case"cmd":return t.argv.map(E6e).join(" ");case"posix":return t.argv.map(x6e).join(" ")}}function Joe(e){let t=b6e(e.shell);if(e.start.mode==="shell")return t==="powershell"?["-NoLogo"]:[];let n=P6e(t,e.start);switch(t){case"powershell":return["-NoLogo","-Command",`${n}${S6e}`];case"cmd":return["/d","/s","/c",n];case"posix":return["-lc",n]}}function Yoe(e){return(e.includes("\\")?$i.win32.basename(e):$i.posix.basename(e)).replace(/\.exe$/iu,"")||"Terminal"}async function Xoe(e){let t=e.env.PATH??e.env.Path??"";for(let o of t.split($i.win32.delimiter)){if(o.length===0)continue;let s=$i.win32.join(o,"pwsh.exe");if(await e.fileExists(s))return s}let n=e.env.SystemRoot??e.env.SYSTEMROOT;if(n!==void 0&&n.length>0){let o=$i.win32.join(n,v6e);if(await e.fileExists(o))return o}let r=e.env.ComSpec??e.env.COMSPEC;return r!==void 0&&r.length>0?r:"cmd.exe"}var v6e,S6e,Qoe=g(()=>{"use strict";v6e=$i.win32.join("System32","WindowsPowerShell","v1.0","powershell.exe");S6e=`
211
211
  if (-not $?) { if ($LASTEXITCODE -is [int] -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }; exit 1 }`});import{accessSync as T6e,chmodSync as R6e,constants as iie,existsSync as I6e}from"node:fs";import{access as _6e,stat as k6e}from"node:fs/promises";import{createRequire as A6e}from"node:module";import C6e from"node:os";import ha from"node:path";import{spawn as D6e}from"node-pty";function K6e(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function Z6e(e){let t="destroy"in e?e.destroy:void 0;if(typeof t!="function")throw new Error("node-pty terminal does not expose resource disposal");Reflect.apply(t,e,[])}function sie(e){let t=[];for(let n of W6e)for(let r of q6e){let o=ha.resolve(e.packageDirectory,"lib",r,n);t.push(ha.join(o,"spawn-helper"))}return t}function Y6e(e){return sie(e).filter(t=>I6e(t))}function nie(e){try{return T6e(e,iie.X_OK),!0}catch{return!1}}function X6e(e){let t=Y6e({packageDirectory:e.packageDirectory});if(t.length===0){e.logger.warn({component:"terminal-manager",msg:G6e,searched:sie({packageDirectory:e.packageDirectory})});return}for(let n of t)if(nie(n)||R6e(n,493),!nie(n))throw new Error(`node-pty spawn-helper is not executable: ${n}`)}function gL(e){if(tie||process.platform!=="darwin")return;tie=!0;let t=V6e.resolve("node-pty/package.json");X6e({logger:e,packageDirectory:ha.dirname(t)})}async function rie(e){try{return await _6e(e,iie.X_OK),!0}catch{return!1}}function Q6e(e){return e!==void 0&&e.length>0}async function e3e(){if(process.platform==="win32")return Xoe({env:process.env,fileExists:rie});let e=[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(Q6e);for(let t of e)if(await rie(t))return t;return"/bin/sh"}function t3e(e){return{...vt({env:process.env}),...e.shellEnv,BB_TERMINAL_SESSION_ID:e.terminalId,COLORTERM:"truecolor",DISABLE_AUTO_TITLE:"true",FORCE_HYPERLINK:"1",PROMPT_EOL_MARK:"",TERM:"xterm-256color"}}function oie(e){let t=e.trim().replace(/\s+/g," ");return aY(t)<=80?t:`${cY(t,77)}...`}function n3e(e,t){switch(e.start.mode){case"shell":return Yoe(t);case"command":return oie(e.start.command);case"argv":return oie(e.start.argv.join(" "))}}async function r3e(e){let t=e??C6e.homedir();if(!ha.isAbsolute(t))throw new Error("Terminal cwd must be an absolute path");if(!(await k6e(t)).isDirectory())throw new Error(`Terminal cwd is not a directory: ${t}`);return t}function o3e(){let e=()=>{throw new Error("Terminal operation completion resolver was not set")};return{promise:new Promise(n=>{e=n}),resolve:e}}function i3e(e,t){let n=e+t,r=n.endsWith("\x1B[0")?"\x1B[0":n.endsWith("\x1B[")?"\x1B[":n.endsWith("\x1B")?"\x1B":"",o=n.slice(0,n.length-r.length),s=0;return{output:o.replace(H6e,()=>(s+=1,"")),pendingQuery:r,queryCount:s}}var O6e,M6e,hL,eie,N6e,L6e,B6e,F6e,$6e,j6e,H6e,U6e,z6e,W6e,q6e,G6e,V6e,tie,J6e,zx,vL=g(()=>{"use strict";Tl();Vp();Ee();RS();Fi();lm();Ye();Qoe();O6e=4*1024*1024,M6e=1e4,hL=64*1024,eie=4,N6e=1024*1024,L6e=512*1024,B6e=50,F6e=2e3,$6e=32,j6e=16*1024*1024,H6e=/\u001b\[(?:0)?c/g,U6e="\x1B[?1;2c",z6e=8,W6e=[ha.join("build","Release"),ha.join("build","Debug"),ha.join("prebuilds",`${process.platform}-${process.arch}`)],q6e=["..","."],G6e="no node-pty spawn-helper found at known paths",V6e=A6e(import.meta.url),tie=!1;J6e={spawn(e){gL(e.logger);let t=D6e(e.file,e.args,{cols:e.cols,cwd:e.cwd,env:e.env,name:"xterm-256color",rows:e.rows});return{dispose:()=>Z6e(t),kill:n=>{if(process.platform==="win32"){t.kill();return}Gc({child:{pid:t.pid,kill:r=>t.kill(r)},signal:n??"SIGHUP"})},hasExited:()=>!K6e(t.pid),onData:n=>t.onData(n),onExit:n=>t.onExit(r=>n({exitCode:r.exitCode})),pause:()=>t.pause(),resize:(n,r)=>t.resize(n,r),resume:()=>t.resume(),write:n=>t.write(n)}}};zx=class{constructor(t){this.options=t;this.closeGracePeriodMs=t.closeGracePeriodMs??F6e,this.exitedRetentionMs=t.exitedRetentionMs??u8,this.maxExitedScrollbackBytes=t.maxExitedScrollbackBytes??j6e,this.maxExitedTerminals=t.maxExitedTerminals??$6e,this.ptyAdapter=t.ptyAdapter??J6e,this.resolveShell=t.resolveShell??e3e}options;closeGracePeriodMs;exitedRetentionMs;maxExitedScrollbackBytes;maxExitedTerminals;ptyAdapter;resolveShell;terminalOperations=new Map;openingTerminalIds=new Set;sessions=new Map;exitedSessions=new Map;exitedScrollbackBytes=0;dispose(){this.releaseOutputFlowControl();for(let t of[...this.exitedSessions.keys()])this.forgetExitedSession(t)}releaseOutputFlowControl(){for(let t of this.sessions.values())this.disableOutputFlow(t)}async handleMessage(t){await this.runTerminalOperation({operation:()=>this.handleSerializedMessage(t),terminalId:t.terminalId})}async handleSerializedMessage(t){switch(t.type){case"terminal.open":await this.openTerminal(t);return;case"terminal.attach":this.attachTerminal(t);return;case"terminal.input":this.writeTerminalInput(t.terminalId,t.dataBase64);return;case"terminal.resize":this.resizeTerminal({cols:t.cols,rows:t.rows,terminalId:t.terminalId});return;case"terminal.close":this.closeTerminal({reason:t.reason,terminalId:t.terminalId});return;case"terminal.flow-control":this.setOutputFlowControl(t.terminalId,t.enabled);return;case"terminal.ack":this.acknowledgeOutput(t.terminalId,t.nextSeq);return}}async shutdownAll(t="daemon-disconnect"){let n=new Set([...this.sessions.keys(),...this.openingTerminalIds]);await Promise.all([...n].map(r=>this.runTerminalOperation({operation:()=>this.shutdownTerminal({reason:t,terminalId:r}),terminalId:r})))}async openTerminal(t){if(this.sessions.has(t.terminalId)){this.sendTerminalError({code:"terminal_exists",message:"Terminal session is already open",requestId:t.requestId,terminalId:t.terminalId});return}this.openingTerminalIds.add(t.terminalId);try{let n=await this.resolveTerminalOpenTarget(t),r=await this.resolveShell(),o=this.ptyAdapter.spawn({args:Joe({shell:r,start:t.start}),cols:t.cols,cwd:n.cwd,env:to(t.contributedEnv,t3e({shellEnv:this.options.runtimeManager.getShellEnv(),terminalId:t.terminalId})),file:r,logger:this.options.logger,rows:t.rows}),s={closeReason:null,closeTimeout:null,cols:t.cols,disposables:[],environmentId:n.environmentId,lastOutputFlushAt:0,nextSeq:0,outputBuffers:[],outputBytes:0,outputFlow:null,outputFlushCancel:null,pendingPrimaryDeviceAttributesQuery:"",pty:o,rows:t.rows,scrollback:[],scrollbackBytes:0,terminalId:t.terminalId};this.sessions.set(t.terminalId,s),n.environmentId!==null&&this.options.runtimeManager.markTerminalActive(n.environmentId,t.terminalId),s.disposables.push(o.onData(a=>this.handleTerminalOutput(s,a)),o.onExit(a=>{this.runTerminalOperation({operation:()=>this.finishTerminalSession({closeReason:s.closeReason??"process-exit",exitCode:a.exitCode,session:s}),terminalId:s.terminalId}).catch(c=>{this.options.logger.warn({terminalId:s.terminalId,...Xe(c)},"Terminal exit handler failed")})})),this.options.sendMessage({type:"terminal.opened",requestId:t.requestId,terminalId:t.terminalId,shell:r,title:n3e(t,r),initialCwd:n.cwd,cols:t.cols,rows:t.rows})}catch(n){let r=n instanceof ge&&n.code==="workspace_type_mismatch"?n.code:"terminal_open_failed";this.sendTerminalError({code:r,message:n instanceof Error?n.message:String(n),requestId:t.requestId,terminalId:t.terminalId})}finally{this.openingTerminalIds.delete(t.terminalId)}}async resolveTerminalOpenTarget(t){switch(t.target.kind){case"workspace":return{cwd:(await ro({environmentId:t.target.environmentId,runtimeManager:this.options.runtimeManager,workspaceContext:t.target.workspaceContext})).path,environmentId:t.target.environmentId};case"host_path":return{cwd:await r3e(t.target.cwd),environmentId:null}}}attachTerminal(t){let n=this.sessions.get(t.terminalId);if(n){this.flushTerminalOutput(n),this.sendTerminalReplay({message:t,nextSeq:n.nextSeq,scrollback:n.scrollback});return}let r=this.exitedSessions.get(t.terminalId);if(r){this.sendTerminalReplay({message:t,nextSeq:r.nextSeq,scrollback:r.scrollback});return}this.sendTerminalError({code:"terminal_not_found",message:"Terminal session is not open",requestId:t.requestId,terminalId:t.terminalId})}sendTerminalReplay(t){let n=t.scrollback.filter(s=>s.chunk.seq>=t.message.sinceSeq),r=n.reduce((s,a)=>s+a.byteLength,0);for(;n.length>1&&r>t.message.tailBytes;){let s=n.shift();s&&(r-=s.byteLength)}let o=n.map(s=>s.chunk);this.options.sendMessage({type:"terminal.replay",requestId:t.message.requestId,terminalId:t.message.terminalId,chunks:o,replayStartSeq:o[0]?.seq??t.nextSeq,nextSeq:t.nextSeq})}writeTerminalInput(t,n){let r=this.sessions.get(t);r&&r.pty.write(Buffer.from(n,"base64"))}resizeTerminal(t){let n=this.sessions.get(t.terminalId);n&&(n.cols===t.cols&&n.rows===t.rows||(n.cols=t.cols,n.rows=t.rows,n.pty.resize(t.cols,t.rows)))}closeTerminal(t){let n=this.sessions.get(t.terminalId);if(!n){this.options.sendMessage({type:"terminal.exited",terminalId:t.terminalId,exitCode:null,closeReason:t.reason});return}if(n.closeReason===null){n.closeReason=t.reason,this.disableOutputFlow(n),n.closeTimeout=setTimeout(()=>{n.closeTimeout=null,this.runTerminalOperation({operation:()=>this.forceCloseTerminal(n),terminalId:n.terminalId})},this.closeGracePeriodMs);try{n.pty.kill()}catch(r){this.options.logger.warn({terminalId:t.terminalId,...Xe(r)},"Failed to kill terminal"),this.finishTerminalSession({closeReason:t.reason,exitCode:null,session:n})}}}forceCloseTerminal(t){if(this.sessions.get(t.terminalId)===t){this.options.logger.warn({terminalId:t.terminalId},"Terminal did not exit after close; forcing cleanup");try{t.pty.kill("SIGKILL")}catch(n){this.options.logger.warn({terminalId:t.terminalId,...Xe(n)},"Failed to force kill terminal")}this.finishTerminalSession({closeReason:t.closeReason??"user",exitCode:null,session:t})}}shutdownTerminal(t){let n=this.sessions.get(t.terminalId);if(n){this.disableOutputFlow(n);try{n.pty.kill()}catch(r){this.options.logger.warn({terminalId:n.terminalId,...Xe(r)},"Failed to kill terminal during shutdown")}this.finishTerminalSession({closeReason:t.reason,exitCode:null,session:n})}}handleTerminalOutput(t,n){if(this.sessions.get(t.terminalId)!==t)return;let r=i3e(t.pendingPrimaryDeviceAttributesQuery,n);if(t.pendingPrimaryDeviceAttributesQuery=r.pendingQuery,r.queryCount>0){let o=Math.min(r.queryCount,z6e);t.pty.write(U6e.repeat(o))}this.bufferTerminalOutput(t,r.output)}bufferTerminalOutput(t,n){let r=Buffer.from(n,"utf8");if(r.byteLength===0)return;if(t.outputBuffers.push(r),t.outputBytes+=r.byteLength,t.outputBytes>=hL){this.flushTerminalOutput(t);return}if(t.outputFlushCancel!==null)return;let o=()=>{t.outputFlushCancel=null,this.flushTerminalOutput(t)};if(performance.now()-t.lastOutputFlushAt>=eie){let a=setImmediate(o);t.outputFlushCancel=()=>clearImmediate(a);return}let s=setTimeout(o,eie);t.outputFlushCancel=()=>clearTimeout(s)}flushTerminalOutput(t){if(t.outputFlushCancel!==null&&(t.outputFlushCancel(),t.outputFlushCancel=null),this.sessions.get(t.terminalId)!==t||t.outputBytes===0){t.outputBuffers=[],t.outputBytes=0;return}let n=Buffer.concat(t.outputBuffers,t.outputBytes);t.outputBuffers=[],t.outputBytes=0,t.lastOutputFlushAt=performance.now();for(let r=0;r<n.byteLength;r+=hL){let o=n.subarray(r,Math.min(r+hL,n.byteLength)),s={seq:t.nextSeq,dataBase64:o.toString("base64")};t.nextSeq+=1;let a={byteLength:o.byteLength,chunk:s};t.scrollback.push(a),t.scrollbackBytes+=a.byteLength,this.pruneScrollback(t),this.recordUnacknowledgedOutput(t,a),this.options.sendMessage({type:"terminal.output",terminalId:t.terminalId,chunk:s})}}setOutputFlowControl(t,n){let r=this.sessions.get(t);if(r){if(!n){this.disableOutputFlow(r);return}r.outputFlow!==null||r.closeReason!==null||(r.outputFlow={acknowledgedNextSeq:r.nextSeq,pausedExitPoll:null,unacknowledgedBytes:0,unacknowledgedChunks:[]})}}acknowledgeOutput(t,n){let r=this.sessions.get(t),o=r?.outputFlow;if(!r||!o||n<=o.acknowledgedNextSeq)return;o.acknowledgedNextSeq=n;let s=0;for(let a of o.unacknowledgedChunks){if(a.seq>=n)break;o.unacknowledgedBytes-=a.byteLength,s+=1}o.unacknowledgedChunks.splice(0,s),o.pausedExitPoll!==null&&o.unacknowledgedBytes<=L6e&&this.resumeOutput(r,o)}recordUnacknowledgedOutput(t,n){let r=t.outputFlow;r!==null&&(r.unacknowledgedChunks.push({byteLength:n.byteLength,seq:n.chunk.seq}),r.unacknowledgedBytes+=n.byteLength,!(r.pausedExitPoll!==null||r.unacknowledgedBytes<=N6e)&&(t.pty.pause(),r.pausedExitPoll=setInterval(()=>{t.pty.hasExited()&&this.disableOutputFlow(t)},B6e)))}resumeOutput(t,n){n.pausedExitPoll!==null&&(clearInterval(n.pausedExitPoll),n.pausedExitPoll=null,t.pty.resume())}disableOutputFlow(t){let n=t.outputFlow;n!==null&&(t.outputFlow=null,this.resumeOutput(t,n))}pruneScrollback(t){for(;t.scrollbackBytes>O6e||t.scrollback.length>M6e;){let n=t.scrollback.shift();if(!n)return;t.scrollbackBytes-=n.byteLength}}finishTerminalSession(t){if(this.sessions.get(t.session.terminalId)===t.session){t.session.pendingPrimaryDeviceAttributesQuery.length>0&&(this.bufferTerminalOutput(t.session,t.session.pendingPrimaryDeviceAttributesQuery),t.session.pendingPrimaryDeviceAttributesQuery=""),this.flushTerminalOutput(t.session),this.disableOutputFlow(t.session),t.session.closeTimeout!==null&&(clearTimeout(t.session.closeTimeout),t.session.closeTimeout=null),this.sessions.delete(t.session.terminalId),this.retainExitedSession(t.session),t.session.environmentId!==null&&this.options.runtimeManager.markTerminalInactive(t.session.environmentId,t.session.terminalId);for(let n of t.session.disposables)n.dispose();try{t.session.pty.dispose()}catch(n){this.options.logger.warn({terminalId:t.session.terminalId,...Xe(n)},"Failed to dispose terminal PTY")}this.options.sendMessage({type:"terminal.exited",terminalId:t.session.terminalId,exitCode:t.exitCode,closeReason:t.closeReason})}}retainExitedSession(t){if(this.maxExitedTerminals<1||this.exitedRetentionMs<=0)return;this.forgetExitedSession(t.terminalId);let n={expiryTimeout:null,nextSeq:t.nextSeq,scrollback:t.scrollback,scrollbackBytes:t.scrollbackBytes,terminalId:t.terminalId},r=setTimeout(()=>{n.expiryTimeout=null,this.forgetExitedSession(n.terminalId)},this.exitedRetentionMs);r.unref(),n.expiryTimeout=r,this.exitedSessions.set(n.terminalId,n),this.exitedScrollbackBytes+=n.scrollbackBytes,this.evictExitedSessions()}evictExitedSessions(){for(;this.exitedSessions.size>this.maxExitedTerminals||this.exitedSessions.size>1&&this.exitedScrollbackBytes>this.maxExitedScrollbackBytes;){let t=this.exitedSessions.keys().next();if(t.done)return;this.forgetExitedSession(t.value)}}forgetExitedSession(t){let n=this.exitedSessions.get(t);n&&(n.expiryTimeout!==null&&(clearTimeout(n.expiryTimeout),n.expiryTimeout=null),this.exitedSessions.delete(t),this.exitedScrollbackBytes-=n.scrollbackBytes)}sendTerminalError(t){this.options.sendMessage({type:"terminal.error",requestId:t.requestId,terminalId:t.terminalId,code:t.code,message:t.message})}runTerminalOperation(t){let n=this.terminalOperations.get(t.terminalId),r=o3e();this.terminalOperations.set(t.terminalId,r.promise);let o=this.runTerminalOperationAfterPrevious({operation:t.operation,previousOperation:n});return o.then(()=>{r.resolve()},()=>{r.resolve()}),r.promise.then(()=>{this.terminalOperations.get(t.terminalId)===r.promise&&this.terminalOperations.delete(t.terminalId)}),o}async runTerminalOperationAfterPrevious(t){t.previousOperation&&await t.previousOperation,await t.operation()}}});import{PassThrough as aie}from"node:stream";import{spawn as s3e}from"node-pty";function c3e(){return{spawn(e){let t=new aie,n=new aie,r=process.cwd(),o=e.env??process.env,s=rO(e.command,{cwd:r,env:o});if(s===void 0)throw new Error(`Command not found: ${e.command}`);gL(a3e);let a=s3e(s,e.args,{cols:120,cwd:r,env:o,name:"xterm-256color",rows:30});return a.onData(c=>t.write(c)),a.onExit(()=>{t.end(),n.end()}),{stdout:t,stderr:n,kill(c){return a.kill(c),!0},onError(c){},onClose(c){a.onExit(l=>c(l.exitCode,null))}}}}}function cie(e){if(Hm!==null)throw new Um(Hm);Hm=e.providerId;let t=!1,n=null,r=()=>{Hm===e.providerId&&(Hm=null)};return new ReadableStream({start(o){let s=new TextEncoder,a=l=>{if(t)return;let u=bl.parse(l);o.enqueue(s.encode(`${JSON.stringify(u)}
212
- `))},c=()=>{t||(t=!0,r(),o.close())};a({type:"started",provider:e.providerId,command:e.plan.displayCommand});try{n=(e.processSpawner??c3e()).spawn({command:e.plan.command,args:[...e.plan.args],...e.env===void 0?{}:{env:e.env}})}catch(l){a({type:"error",provider:e.providerId,message:l instanceof Error?l.message:String(l)}),c();return}n.stdout.setEncoding("utf8"),n.stdout.on("data",l=>a({type:"output",provider:e.providerId,stream:"stdout",text:l})),n.stderr.setEncoding("utf8"),n.stderr.on("data",l=>a({type:"output",provider:e.providerId,stream:"stderr",text:l})),n.onError(l=>{a({type:"error",provider:e.providerId,message:l.message}),c()}),n.onClose((l,u)=>{a({type:"completed",provider:e.providerId,exitCode:l,signal:u,success:l===0}),c()})},cancel(){t=!0,r(),n?.kill("SIGTERM")}})}var a3e,Hm,Um,lie=g(()=>{"use strict";Ee();wt();vL();a3e={debug(){},info(){},warn(){},error(){}},Hm=null,Um=class extends Error{providerId;constructor(t){super(`Provider installation already running for ${t}`),this.name="ProviderInstallationInProgressError",this.providerId=t}}});import{mkdir as l3e,readFile as u3e,rm as d3e,rmdir as p3e,stat as m3e,writeFile as f3e}from"node:fs/promises";import ga from"node:path";function g3e(e){return ga.isAbsolute(e)||ga.win32.isAbsolute(e)||/^[a-zA-Z][a-zA-Z0-9+.-]*:/u.test(e)}function die(e){return e.type!=="localFile"&&e.type!=="localImage"?!1:!g3e(e.path)}function v3e(e){let n=(e.type==="localFile"&&e.name?e.name:e.path).replaceAll("\\","/"),o=ga.posix.basename(n).replace(/[^a-zA-Z0-9._-]+/gu,"-");return o.length>0?o:"attachment"}function y3e(e){return e instanceof Error?e.message:String(e)}function yL(e){return e.type==="localFile"?e.sizeBytes:void 0}function b3e(e){let t=yL(e.attachment);if(t!==void 0&&t>36700160)throw new W("attachment_unavailable",`Attachment ${e.attachment.path} exceeds ${36700160} byte limit`)}function S3e(e,t){let n=yL(e);if(n!==void 0&&t.byteLength!==n)throw new W("attachment_unavailable",`Attachment ${e.path} size mismatch: expected ${n} bytes, received ${t.byteLength}`);if(t.byteLength>36700160)throw new W("attachment_unavailable",`Attachment ${e.path} exceeds ${36700160} byte limit`)}function zm(e,t,n){let r=s3({rootPath:e,candidatePath:t});if(!r)throw new W("invalid_path",n);return r}function x3e(e){let t=zm(e.threadStorageRootPath,ga.join(e.threadStorageRootPath,e.threadId),"Attachment staging path escapes the thread storage root");return zm(e.threadStorageRootPath,ga.join(t,"Attachments"),"Attachment staging path escapes the thread storage root")}function w3e(e,t){let n=ga.extname(e);return n?`${e.slice(0,-n.length)}${t}${n}`:`${e}${t}`}async function E3e(e,t){return(await m3e(e)).size!==t.byteLength?!1:Buffer.from(t).equals(await u3e(e))}async function P3e(e,t){let n=v3e(e.attachment);for(let r=1;;r+=1){let o=ga.join(e.stagingDir,r===1?n:w3e(n,`-${r}`));if(!e.stagedPaths.includes(o)){try{return await f3e(o,t,{flag:"wx",mode:h3e}),e.createdPaths.push(o),o}catch(s){if(!Ne(s,"EEXIST"))throw s}if(await E3e(o,t))return o}}}async function uie(e,t){await Promise.all(t.map(n=>d3e(n,{force:!0,recursive:!1}))),await p3e(e).catch(()=>{})}async function T3e(e){b3e(e);let t;try{t=(await e.fetchProjectAttachment({expectedSizeBytes:yL(e.attachment),maxBytes:36700160,projectId:e.projectId,threadId:e.threadId,path:e.attachment.path})).bytes}catch(n){throw new W("attachment_unavailable",`Failed to fetch attachment ${e.attachment.path}: ${y3e(n)}`)}return S3e(e.attachment,t),P3e(e,t)}async function R3e(e){let t=[];for(let n of e.input){if(!die(n)){t.push(n);continue}let r=await T3e({...e,attachment:n});t.push({...n,path:r}),e.stagedPaths.push(r)}return t}async function pie(e){let t=await bL({...e,inputGroups:[e.input]});return{cleanup:t.cleanup,input:t.inputGroups[0]??e.input}}async function bL(e){if(!e.inputGroups.some(o=>o.some(die)))return{cleanup:async()=>{},inputGroups:e.inputGroups};let t=x3e({...e,input:[]});await l3e(t,{recursive:!0});let n=[],r=[];try{let o=[];for(let s of e.inputGroups)o.push(await R3e({...e,createdPaths:n,input:s,stagedPaths:r,stagingDir:t}));return{cleanup:()=>uie(t,n),inputGroups:o}}catch(o){throw await uie(t,n),o}}var h3e,mie=g(()=>{"use strict";Ee();Ye();Uo();h3e=384});function hie(e){return`${e.providerId}#bridge:${Ci(e.bridgeLaunch)}#${e.requirement??"thread_start"}`}function gie({ttlMs:e,now:t=Date.now}){let n=new Map,r=new Map,o=0;function s(c,l){let u=r.get(c);if(u!==void 0)return u;let d=o,p=l().then(m=>d!==o?s(c,l):((m.installed||m.minimumSupportedVersion===null)&&!m.versionUnsupported?n.set(c,{status:m,expiresAt:t()+e}):n.delete(c),m),m=>{if(d!==o)return s(c,l);throw n.delete(c),m}).finally(()=>{r.get(c)===p&&r.delete(c)});return r.set(c,p),p}return{clear(){o+=1,n.clear(),r.clear()},run:(c,l)=>{let u=n.get(c);return u===void 0?s(c,l):(u.expiresAt<=t()&&s(c,l).catch(()=>{}),Promise.resolve(u.status))}}}var fie,SL=g(()=>{"use strict";HS();fie=5*6e4});import{AsyncLocalStorage as I3e}from"node:async_hooks";import{performance as vie}from"node:perf_hooks";function yie(e,t){return e.type!=="turn.submit"?t():xL.run({receivedAt:vie.now(),trace:{spans:[]}},t)}function ji(e){let t=xL.getStore();t!==void 0&&t.trace.spans.push({name:e,atMs:Ls(vie.now()-t.receivedAt)})}function bie(){return xL.getStore()?.trace??{spans:[]}}var xL,wL=g(()=>{"use strict";Ee();xL=new I3e});import xie from"node:fs/promises";import _3e from"node:path";async function wie(e,t){let n=zm(t.threadStorageRootPath,_3e.join(t.threadStorageRootPath,e.threadId),"Thread storage path escapes the storage root");await Ap({directories:[n]}),await xie.rm(n,{recursive:!0,force:!0})}async function Eie(e){try{await e()}catch{}}async function Pie({command:e,options:t}){if(!e.bridgeLaunch.capabilities.providerInstallation)return;let n=e.type==="thread.rewind.prepare"?"thread_rewind":void 0;await t.refreshShellEnv({allowStale:!0});let r=await t.runtimeManager.providerInstallationGate.run(hie({providerId:e.providerId,bridgeLaunch:e.bridgeLaunch,requirement:n}),async()=>{let a=await lr(e.bridgeLaunch,t);return t.providerInstallationStatus({providerId:e.providerId,bridgeLaunch:a,checkUpdates:!1,...n!==void 0?{requirement:n}:{}})});if(!r.versionUnsupported)return;let o=r.currentVersion?` ${r.currentVersion}`:"",s=r.minimumSupportedVersion??"a newer version";throw new ge("provider_cli_unsupported_version",`Provider "${e.providerId}"${o} is too old for this operation. Update it to ${s} or newer.`)}async function Tie(e){if(e.command.inputGroups!==void 0){let t=await bL({fetchProjectAttachment:e.fetchProjectAttachment,inputGroups:e.command.inputGroups,projectId:e.projectId,requestId:e.command.requestId,threadStorageRootPath:e.threadStorageRootPath,threadId:e.command.threadId});return{cleanup:t.cleanup,input:Vg(t.inputGroups)}}return pie({fetchProjectAttachment:e.fetchProjectAttachment,input:e.command.input,projectId:e.projectId,requestId:e.command.requestId,threadStorageRootPath:e.threadStorageRootPath,threadId:e.command.threadId})}async function Rie(e,t){let n=await lr(e.bridgeLaunch,t),r=await ro({environmentId:e.environmentId,injectedSkillSources:e.injectedSkillSources,runtimeManager:t.runtimeManager,targetThreadId:e.threadId,workspaceContext:e.workspaceContext});return{bridgeLaunch:n,entry:r}}async function Iie(e){let{command:t,entry:n,options:r}=e,{resumeContext:o}=t;if(n.runtime.hasThread(t.threadId))return;if(!o.providerThreadId)throw new W("unknown_thread_runtime",`No provider thread id available for thread ${t.threadId}`);let s=await lr(t.resumeContext.bridgeLaunch??t.bridgeLaunch,r);await n.runtime.resumeThread({bridgeLaunch:s,skillRoots:n.skillRoots,environmentId:t.environmentId,threadId:t.threadId,projectId:o.projectId,providerThreadId:o.providerThreadId,providerId:o.providerId,contributedEnv:o.contributedEnv,options:t.options,instructions:o.instructions,dynamicTools:o.dynamicTools,instructionMode:o.instructionMode})}async function _ie(e,t){if(await Pie({command:e,options:t}),e.threadStoragePath){let r=zm(t.threadStorageRootPath,e.threadStoragePath,"Thread storage path escapes the storage root");await xie.mkdir(r,{recursive:!0})}let n=await Tie({command:e,fetchProjectAttachment:t.fetchProjectAttachment,projectId:e.projectId,threadStorageRootPath:t.threadStorageRootPath});try{let{bridgeLaunch:r,entry:o}=await Rie(e,t);return await o.runtime.startThread({bridgeLaunch:r,skillRoots:o.skillRoots,environmentId:e.environmentId,threadId:e.threadId,projectId:e.projectId,providerId:e.providerId,contributedEnv:e.contributedEnv,clientRequestId:e.requestId,input:n.input,options:e.options,instructions:e.instructions,dynamicTools:e.dynamicTools,instructionMode:e.instructionMode,...e.fork?{fork:e.fork}:{}})}catch(r){throw await Eie(n.cleanup),r}}async function kie(e,t){await Pie({command:e,options:t});let{bridgeLaunch:n,entry:r}=await Rie(e,t);return r.runtime.prepareThreadRewind({bridgeLaunch:n,skillRoots:r.skillRoots,environmentId:e.environmentId,threadId:e.threadId,leaseId:e.leaseId,projectId:e.projectId,providerId:e.providerId,contributedEnv:e.contributedEnv,sourceProviderThreadId:e.sourceProviderThreadId,retainThroughProviderCheckpoint:e.retainThroughProviderCheckpoint,options:e.options,instructions:e.instructions,dynamicTools:e.dynamicTools,instructionMode:e.instructionMode})}async function Aie(e,t){let n=await t.runtimeManager.getOrAwait(e.environmentId);return n?(await n.runtime.discardThreadRewind({leaseId:e.leaseId}),{}):{}}async function EL(e,t){let{resumeContext:n}=e,r=await ro({environmentId:e.environmentId,injectedSkillSources:n.injectedSkillSources,runtimeManager:t.runtimeManager,targetThreadId:e.threadId,workspaceContext:n.workspaceContext});ji("skills.staged");let o=await t.runtimeManager.releaseThreadFromOtherEnvironments({activeTurn:e.type==="turn.submit"?"interrupt":"keep",environmentId:e.environmentId,threadId:e.threadId}),[s]=o.activeTurnEnvironmentIds;if(s!==void 0)throw new ge("thread_busy_in_other_environment",`Thread ${e.threadId} still runs a turn in environment ${s}`);return await Iie({command:e,entry:r,options:t}),ji("runtime.ready"),r}async function Cie(e,t){await t.runtime.runTurn({threadId:e.threadId,input:e.input,clientRequestId:e.requestId,options:e.options,contributedEnv:e.resumeContext.contributedEnv,instructions:e.resumeContext.instructions})}async function A3e(e,t,n){let r=n,o=null;for(let s=0;s<Sie;s+=1){let a=await t.runtime.steerTurn({threadId:e.threadId,expectedTurnId:r,input:e.input,clientRequestId:e.requestId,options:e.options,contributedEnv:e.resumeContext.contributedEnv,instructions:e.resumeContext.instructions});if(a.status==="steered")return;if(o=a.activeTurnId,s===Sie-1)break;let c=await Die(e,t);if(c===null)return Cie(e,t);if(c===r)break;r=c}throw new W("stale_turn",`Expected active turn ${r} for thread ${e.threadId}, but active turn is ${o??"none"}`)}async function Die(e,t){let n=t.runtime.getActiveTurnId(e.threadId);if(n!==null)return n;if(!t.runtime.getLiveThreadIds().includes(e.threadId))return null;let r=await t.runtime.waitForActiveTurn(e.threadId,{timeoutMs:k3e});if(r!==null)return r;let o=t.runtime.getActiveTurnId(e.threadId);if(o!==null)return o;if(t.runtime.getLiveThreadIds().includes(e.threadId))throw new W(sS,`Refusing to start a competing turn while ${e.threadId} is still starting`);return null}async function C3e(e,t){return e.target.mode==="start"?null:e.target.mode==="steer"&&e.target.expectedTurnId!==null?e.target.expectedTurnId:await Die(e,t)??e.target.expectedTurnId}async function D3e(e,t){let n=await C3e(e,t);return e.target.mode==="start"||n===null?Cie(e,t):A3e(e,t,n)}async function Oie(e,t,n){let r=await Tie({command:e,fetchProjectAttachment:n.fetchProjectAttachment,projectId:e.resumeContext.projectId,threadStorageRootPath:n.threadStorageRootPath});ji("input.staged");let o={...e,input:r.input};try{await Iie({command:o,entry:t,options:n}),await D3e(o,t)}catch(s){throw await Eie(r.cleanup),s}return ji("bridge.turnStarted"),{trace:bie()}}var k3e,Sie,Mie=g(()=>{"use strict";Me();Ee();wt();Ye();mie();SL();lm();wL();k3e=5e3,Sie=2});import PL from"node:fs/promises";import Wm from"node:path";function M3e(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,80).replace(/-+$/u,"")||"project"}function TL(e,t){return Wm.resolve(e,"checkouts",M3e(t))}async function N3e(e){try{if(!(await PL.stat(e)).isDirectory()||(await PL.readdir(e)).length>0)throw new ge("target_not_empty",`Clone target is not empty: ${e}`)}catch(t){if(t instanceof ge)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}}async function RL(e,t={}){let n=Wm.resolve(e),r=await Fe(["remote","get-url","origin"],{cwd:n,...t,allowFailure:!0}),o=r.exitCode===0?r.stdout.trim():"";return{path:n,gitRemoteUrl:o||null}}async function Nie(e){let t=Wm.resolve(e.targetPath??TL(e.dataDir,e.projectSlug));await N3e(t),await PL.mkdir(Wm.dirname(t),{recursive:!0});let n="",r=e.onProgress===void 0?void 0:o=>{for(n+=o;;){let s=/\r\n|\r|\n/u.exec(n);if(s===null)return;e.onProgress?.(n.slice(0,s.index)),n=n.slice(s.index+s[0].length)}};try{await Fe(["clone","--progress",e.remoteUrl,t],{cwd:Wm.dirname(t),env:e.env,...e.shellPath!==void 0?{shellPath:e.shellPath}:{},timeoutMs:O3e,...r===void 0?{}:{onStderr:r}})}catch(o){throw o instanceof Te?new ge(o.code,o.message):new Error(o instanceof Error?o.message:String(o))}finally{n.length>0&&e.onProgress?.(n)}return RL(t,e.shellPath===void 0?{}:{shellPath:e.shellPath})}var O3e,Lie=g(()=>{"use strict";$o();Ye();O3e=1200*1e3});import{constants as Bie}from"node:fs";import qx from"node:fs/promises";import qm from"node:path";function Fie(e){return Ne(e,"ENOENT")||e instanceof W&&e.code==="ENOENT"}async function F3e(e){try{let t=await Dx({resolvedPath:e.filePath,resultPath:e.filePath,rootPath:e.rootPath});return"content"in t?t.contentEncoding==="utf8"?t.content:Buffer.from(t.content,"base64").toString("utf8"):null}catch(t){if(Fie(t))return null;throw t}}async function $3e(e){let t=qm.join(e.skillsRootPath,e.directoryName);try{let n=qm.join(t,Vn),r=await Dr(n,e.rootPath);if(r===null)return null;let o=await qx.stat(r);if(!o.isFile())return null;if(!dt(await qx.realpath(e.rootPath),r))throw new W("invalid_path","Skill file escapes read root");let s={kind:"oversized",directoryName:e.directoryName,sizeBytes:o.size},a={kind:"budget-exceeded",directoryName:e.directoryName};if(o.size>e.maxFileBytes)return s;if(o.size+2>e.remainingBytes)return a;let c=Math.min(e.maxFileBytes,e.remainingBytes),l=await qx.open(r,Bie.O_RDONLY|Bie.O_NOFOLLOW),u;try{let d=Buffer.allocUnsafe(Math.min(o.size+1,c+1)),p=0;for(;p<=c;){if(p===d.length){let f=Buffer.allocUnsafe(Math.min(d.length*2,c+1));d.copy(f),d=f}let m=await l.read(d,p,d.length-p,null);if(m.bytesRead===0)break;p+=m.bytesRead}if(p>e.maxFileBytes)return{...s,sizeBytes:p};if(p>c)return a;u=d.subarray(0,p).toString("utf8")}finally{await l.close()}return Buffer.byteLength(JSON.stringify(u))>e.remainingBytes?a:{kind:"file",directoryName:e.directoryName,content:u}}catch(n){if(Fie(n))return null;throw n}}async function j3e(e,t){let n=qm.join(e,...L3e);if(await qx.realpath(n).catch(()=>null)!==null&&await Dr(n,e)===null)throw new W("invalid_path","Skills path escapes read root");let r=(await lN({path:n,shape:"skill",boundaryPath:e})).map(a=>a.name).filter(a=>!a.startsWith(".")&&!t.excludeNames.includes(a)),o=[],s=t.maxContentBytes;for(let a of r.slice(0,t.limit)){let c=await $3e({directoryName:a,rootPath:e,skillsRootPath:n,maxFileBytes:t.maxFileBytes,remainingBytes:s});c!==null&&(c.kind==="file"&&(s-=Buffer.byteLength(JSON.stringify(c.content))),o.push(c))}return{skills:o,truncated:r.length>t.limit}}async function H3e(e){let n=(await F3e({filePath:qm.join(e,...B3e),rootPath:e}))?.trim()??"";return n.length>0?n:null}async function $ie(e){if(!qm.isAbsolute(e.rootPath))throw new W("invalid_path","rootPath must be absolute");let[t,n,r]=await Promise.all([j3e(e.rootPath,e.projectSkillRead),e.includeAgentInstructions?H3e(e.rootPath):Promise.resolve(null),Vre({cwd:e.rootPath,roots:e.sharedSkillRoots})]);return{agentInstructions:n,projectSkills:t.skills,projectSkillsTruncated:t.truncated,sharedSkills:r}}var L3e,B3e,jie=g(()=>{"use strict";Ee();Ye();Im();Uo();Ox();GN();ym();L3e=[".bb","skills"],B3e=[".bb","AGENTS.md"]});import{mkdir as U3e}from"node:fs/promises";import z3e from"node:path";async function Hie(e,t){let n=await t.runtimeManager.releaseThreadFromOtherEnvironments({activeTurn:"interrupt",environmentId:e.environmentId,threadId:e.threadId}),r=await t.runtimeManager.getOrAwait(e.environmentId);if(!r)return await t.eventSink.flush(),{providerCheckpointId:n.providerCheckpointId};let o=n.providerCheckpointId;if(r.runtime.hasThread(e.threadId)){if(e.type==="thread.stop"&&e.intent==="release"&&r.runtime.getActiveTurnId(e.threadId)!==null)return await t.eventSink.flush(),{providerCheckpointId:o,activeTurnRetained:!0};(e.type!=="thread.stop"||e.intent!=="release")&&await r.runtime.waitForActiveTurn(e.threadId,{timeoutMs:W3e}),o=(await r.runtime.stopThread({threadId:e.threadId})).providerCheckpointId??o}return await t.eventSink.flush(),{providerCheckpointId:o}}function Wie(e){throw e instanceof Te&&e.code==="path_not_found"?new ge(e.code,e.message):e}function q3e(e){return e.PATH?{...process.env,PATH:e.PATH}:process.env}function qie(e,t){let n=e.trim();n.length!==0&&t.push(bl.parse(JSON.parse(n)))}function G3e(e,t){let n=e.split(/\r?\n/u),r=n.pop();for(let o of n)qie(o,t);return r??""}async function V3e(e){let t=e.getReader(),n=new TextDecoder,r=[],o="";for(;;){let s=await t.read();if(s.done)break;o+=n.decode(s.value,{stream:!0}),o=G3e(o,r)}return o+=n.decode(),qie(o,r),r}function Uie(e){let t=[...e.events],n=t.findIndex(o=>o.type==="completed"&&o.success),r=t[n];return r?.type!=="completed"?e.events:(t[n]={...r,success:!1},t.splice(n,0,{type:"error",provider:e.providerId,message:e.message}),t)}function K3e(e,t){switch(e.kind){case"installed":return t.installed;case"version_at_least":{let n=t.currentVersion===null?null:va.default.valid(t.currentVersion),r=va.default.valid(e.version);return n!==null&&r!==null&&va.default.gte(n,r)}case"version_changed":{let n=t.currentVersion;if(n===null)return!1;let r=va.default.valid(n),o=va.default.valid(e.previousVersion);return r!==null&&o!==null?va.default.gt(r,o):n!==e.previousVersion}}return!1}async function Z3e(e,t){try{let n=q3e(t.runtimeManager.getShellEnv()),r=await lr(e.bridgeLaunch,t),o={providerId:e.providerId,bridgeLaunch:r},s=await t.providerInstallationRun({...o,action:e.action});if(!s.available)return{events:[{type:"error",provider:e.providerId,message:s.message}]};let a=t.streamProviderInstallation??cie,c=await V3e(a({providerId:e.providerId,plan:s.command,env:n}));if(c.some(l=>l.type==="completed"&&l.success))try{let l=await t.providerInstallationStatus(o);K3e(s.verification,l)||(c=Uie({providerId:e.providerId,events:c,message:`${e.providerId} ${e.action} exited successfully, but the provider could not verify the installed result.`}))}catch{c=Uie({providerId:e.providerId,events:c,message:`${e.providerId} ${e.action} exited successfully, but its installation status could not be verified.`})}return c.some(l=>l.type==="completed"&&l.success)&&await t.runtimeManager.invalidateProviderMaintenanceRuntime(),{events:c}}catch(n){if(n instanceof Um)return{events:[{type:"error",provider:e.providerId,message:n.message}]};throw n}}async function Gx(e,t,n){let r=await t.runtimeManager.retainEnvironmentForThreadCommand(e.environmentId,e.threadId);try{return await n()}finally{r()}}function ru(e){if(!e.serverMove)throw new Error("Server move is unavailable on this daemon");return e.serverMove}async function Nr(e,t){if(!t.desktopBrowserBroker)throw new Error("Desktop browser broker unavailable");return t.desktopBrowserBroker.request(e)}async function zie(e,t,n){let r=await lr(e.bridgeLaunch,t);return n({providerId:e.providerId,...e.cwd!==void 0?{cwd:e.cwd}:{},bridgeLaunch:r})}async function Vx(e,t,n){let r=await NM({environmentId:e.environmentId,requireGit:!0,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext});if(!r.ok)return{outcome:"unavailable",failure:r.failure};try{return{outcome:"available",...await n(r.entry.workspace)}}catch(o){return{outcome:"unavailable",failure:MM({error:o,workspacePath:e.workspaceContext.workspacePath})}}}async function Gie(e,t){try{return await eO("interactive",()=>J3e[e.type](e,t))}catch(n){Wie(n)}}async function IL(e,t,n){try{return await eO(e.type==="workspace.status"?"status":"interactive",()=>Y3e[e.type](e,t,n))}catch(r){Wie(r)}}var va,W3e,J3e,Y3e,Vie=g(()=>{"use strict";OX();Ee();Tl();p7();wt();va=Gt(tee(),1);Ye();oee();pee();hre();$N();GN();Boe();Nx();joe();qoe();Voe();Zoe();lie();Mie();$o();Lie();lm();ta();jie();Ye();W3e=5e3;J3e={"thread.rewind.discard":(e,t)=>Gx(e,t,()=>Aie(e,t)),"thread.rewind.prepare":(e,t)=>Gx(e,t,()=>kie(e,t)),"thread.start":(e,t)=>Gx(e,t,()=>_ie(e,t)),"turn.submit":(e,t)=>Gx(e,t,async()=>{let n=await EL(e,t);return Oie(e,n,t)}),"thread.stop":Hie,"thread.storage.delete":async(e,t)=>{let n=await Hie(e,t);return await wie(e,t),n},"thread.goal.clear":async(e,t)=>{let r=await(await EL(e,t)).runtime.clearThreadGoal({threadId:e.threadId});return await t.eventSink.flush(),r},"thread.plan.cancel":async(e,t)=>{let n=t.runtimeManager.listThreadOwnerEntries(e.threadId);if(n.length===0)throw new ge("unknown_thread_runtime",`No provider runtime available for thread ${e.threadId}`);let r=n.find(o=>o.runtime.getActiveTurnId(e.threadId)===e.expectedTurnId);return r?(await r.runtime.stopThread({threadId:e.threadId}),await t.eventSink.flush(),{cancelled:!0}):{cancelled:!1}},"thread.rename":async(e,t)=>{let n=await t.runtimeManager.getOrAwait(e.environmentId);return n?(await n.runtime.renameThread({threadId:e.threadId,title:e.title}),{}):{}},"thread.archive":async(e,t)=>{let n=await ro({environmentId:e.environmentId,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext}),r=await lr(e.bridgeLaunch,t);return await n.runtime.archiveThread({threadId:e.threadId,providerId:e.providerId,providerThreadId:e.providerThreadId,bridgeLaunch:r}),{}},"thread.unarchive":async(e,t)=>{let n=await lr(e.bridgeLaunch,t);return await t.runtimeManager.withProviderMaintenanceRuntime({dataDir:t.dataDir},r=>r.unarchiveThread({threadId:e.threadId,providerId:e.providerId,providerThreadId:e.providerThreadId,bridgeLaunch:n})),{}},"interactive.resolve":Goe,"environment.attach":nee,"project.clone":(e,t)=>Nie({dataDir:t.dataDir,projectSlug:e.projectSlug,env:to(e.contributedEnv,{...process.env,...t.runtimeManager.getShellEnv()},!0),remoteUrl:e.remoteUrl,onProgress:n=>t.emitEnvironmentHookProgress?.({type:"environment.hook.progress",operationId:e.operationId,entry:{type:"output",text:n,status:null}}),...On(t.runtimeManager.getShellEnv()),...e.targetPath!==void 0?{targetPath:e.targetPath}:{}}),"environment.attach.cancel":ree,"workspace.commit":async(e,t)=>(await ro({environmentId:e.environmentId,requireGit:!0,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext})).workspace.commit({message:e.message,noVerify:!0})},Y3e={"reply.private":DX,"desktop.broker.prove":async(e,t)=>{if(!t.desktopBrowserBroker)throw new Error("Desktop browser broker unavailable");return t.desktopBrowserBroker.prove(e.challenge)},"environment.hook.run":l7,"environment.hook.cancel":u7,"environment.inspect_cleanup":d7,"desktop.browser.list_instances":Nr,"desktop.browser.list_tabs":Nr,"desktop.browser.create_tab":Nr,"desktop.browser.reveal_tab":Nr,"desktop.browser.close_tab":Nr,"desktop.browser.capture_tab":Nr,"desktop.browser.acquire_control":Nr,"desktop.browser.open_connection":Nr,"desktop.browser.release_control":Nr,"desktop.browser.list_import_sources":Nr,"desktop.browser.import_cookies":Nr,"connect-tunnel.ensure-identity":async(e,t)=>{if(!t.ensureConnectTunnelIdentity)throw new Error("bb connect tunnel identity is unavailable");return t.ensureConnectTunnelIdentity()},"host.list_files":(e,t,n)=>Aoe(e,n),"host.list_paths":(e,t,n)=>Coe(e,n),"host.mkdir":Uoe,"host.move_path":zoe,"host.remove_path":Woe,"host.browse_directory":Doe,"host.paths_exist":Ooe,"project.inspect":async(e,t)=>RL(e.path,On(t.runtimeManager.getShellEnv())),"project.clone_default_path":async(e,t)=>({path:TL(t.dataDir,e.projectSlug)}),"host.pick_folder":Koe,"plugin.host.call":async()=>{throw new Error("plugin.host.call must be routed by CommandRouter")},"plugin.host.cancel":async()=>{throw new Error("plugin.host.cancel must be routed by CommandRouter")},"plugin.host.dispose":async()=>{throw new Error("plugin.host.dispose must be routed by CommandRouter")},"host.list_commands":wre,"host.list_skills":Kre,"host.read_workspace_agent_context":$ie,"host.delete_skill":Yre,"host.write_skill":Xre,"host.install_global_skills":fre,"host.global_skills_status":async e=>mre(e,{}),"host.inspect_git_source":dee,"host.list_branch_options":uee,"host.read_file":Moe,"host.read_file_chunk":Noe,"host.read_file_relative":Loe,"host.write_file":Mx,"provider.list_models":(e,t)=>zie(e,t,n=>t.listModels({...n,contributedEnv:e.contributedEnv})),"provider.list_commands":async(e,t)=>{let n=e.cwd??z3e.join(t.dataDir,"provider-command-catalog");return e.cwd===null&&await U3e(n,{recursive:!0}),t.listCommands({providerId:e.providerId,bridgeLaunch:await lr(e.bridgeLaunch,t),cwd:n})},"provider.health":(e,t)=>zie(e,t,n=>t.providerHealth(n)),"provider.usage":async(e,t)=>t.providerUsage({providerId:e.providerId,bridgeLaunch:await lr(e.bridgeLaunch,t)}),"host.discover_repos":e=>$oe({maxDepth:e.maxDepth,sinceDays:e.sinceDays,limit:e.limit}),"provider.installation.status":async(e,t)=>{let n=await lr(e.bridgeLaunch,t);return t.providerInstallationStatus({providerId:e.providerId,bridgeLaunch:n})},"provider.installation.run":Z3e,"workspace.status":(e,t)=>Vx(e,t,async n=>({workspaceStatus:await n.getStatus({mergeBaseBranch:e.mergeBaseBranch,maxFiles:e.maxFiles,maxUntrackedLineStatFiles:e.maxUntrackedLineStatFiles,maxUntrackedLineStatBytes:e.maxUntrackedLineStatBytes})})),"workspace.diff":(e,t)=>Vx(e,t,async n=>({diff:await n.getDiff({target:e.target,maxDiffBytes:e.maxDiffBytes,maxFileListBytes:e.maxFileListBytes,maxUntrackedFiles:e.maxUntrackedFiles})})),"workspace.diffFiles":(e,t)=>Vx(e,t,n=>n.diffFiles({target:e.target,maxFiles:e.maxFiles,ignoreWhitespace:e.ignoreWhitespace})),"workspace.diffPatch":(e,t)=>Vx(e,t,async n=>({patches:await n.diffPatch({target:e.target,paths:e.paths,maxBytesPerFile:e.maxBytesPerFile,ignoreWhitespace:e.ignoreWhitespace})})),"server_move.inspect":(e,t)=>ru(t).inspect(e),"server_move.probe":(e,t)=>ru(t).probe(e),"server_move.prepare":(e,t)=>ru(t).prepare(e),"server_move.activate":(e,t)=>ru(t).activate(e),"server_move.abort":(e,t)=>ru(t).abort(e),"server_move.delete_old_copy":(e,t)=>ru(t).deleteOldCopy()}});import{performance as Zie}from"node:perf_hooks";function Kie(e){return Zie.now()-e}var X3e,Kx,Jie=g(()=>{"use strict";wt();Vie();Ye();Ee();la();wL();X3e=1e3;Kx=class{constructor(t){this.options=t;this.logger=t.logger}options;logger;environmentLanes=new Map;threadUnarchiveBarriers=new Map;threadLaneTails=new Map;threadTurnLaneTails=new Map;onlineRpcAbortControllers=new Map;async handleOnlineRpcRequest(t){let n=Zie.now(),r=new AbortController;this.onlineRpcAbortControllers.set(t.requestId,r);try{let o=await yie(t.command,()=>this.executeHostRpcCommand(t.command,r.signal));return this.logOnlineRpc({commandType:t.command.type,handlerMs:Kie(n),ok:!0}),D0.parse({type:"host-rpc.response",requestId:t.requestId,commandType:t.command.type,ok:!0,result:o})}catch(o){let s=WS(o);return kX(o)||this.logger.warn({type:t.command.type,err:o},"online host RPC failed"),this.logOnlineRpc({commandType:t.command.type,errorCode:s,handlerMs:Kie(n),ok:!1}),{type:"host-rpc.response",requestId:t.requestId,commandType:t.command.type,ok:!1,errorCode:s,errorMessage:o instanceof Error?o.message:String(o)}}finally{this.onlineRpcAbortControllers.get(t.requestId)===r&&this.onlineRpcAbortControllers.delete(t.requestId)}}cancelOnlineRpcRequest(t){this.onlineRpcAbortControllers.get(t.requestId)?.abort()}executeHostRpcCommand(t,n){return aJ(t)?this.executeLiveDaemonCommand(t):this.executeOnlineRpcCommand(t,n)}executeOnlineRpcCommand(t,n){if(t.type==="plugin.host.call")return this.options.pluginHostManager?this.options.pluginHostManager.call(t):Promise.reject(new Error("host plugin runtime is unavailable"));if(t.type==="plugin.host.cancel"){if(!this.options.pluginHostManager)return Promise.reject(new Error("host plugin runtime is unavailable"));let s=this.options.pluginHostManager.cancel(t);return Promise.resolve(s)}if(t.type==="plugin.host.dispose")return this.options.pluginHostManager?this.options.pluginHostManager.dispose(t):Promise.reject(new Error("host plugin runtime is unavailable"));let r=k0(t);return(r&&"environmentId"in t?this.runInEnvironmentLane(t.environmentId,r,()=>IL(t,this.createDispatchOptions(),n)):IL(t,this.createDispatchOptions(),n)).then(s=>uJ(t,s))}executeLiveDaemonCommand(t){let n=k0(t),r=this.resolveThreadLaneKey(t),o=this.runAfterThreadUnarchiveBarrier(t,()=>this.runInThreadTurnLane(t,()=>this.runInExecutionLanes(t,n,r,()=>this.executeLiveDaemonCommandBody(t))));return this.registerThreadUnarchiveBarrier(t,o),o}async executeLiveDaemonCommandBody(t){ji("lanes.entered");let n=await Gie(t,this.createDispatchOptions());return cJ(t)&&(await this.options.eventSink.flush(),ji("events.flushed")),lJ(t,n)}runInEnvironmentLane(t,n,r){return this.runInReadWriteLane({key:t,lanes:this.environmentLanes,mode:n,work:r})}runInExecutionLanes(t,n,r,o){let s=r===null?o:()=>Nn(this.threadLaneTails,r,o);if(!n)return s();if(!("environmentId"in t)||!t.environmentId)throw new Error(`Command ${t.type} is missing environmentId`);return this.runInEnvironmentLane(t.environmentId,n,s)}runInThreadTurnLane(t,n){return t.type!=="thread.start"&&t.type!=="turn.submit"?n():Nn(this.threadTurnLaneTails,t.threadId,n)}createDispatchOptions(){return{fetchProjectAttachment:this.options.fetchProjectAttachment,fetchSkillTree:this.options.fetchSkillTree,fetchPluginHostArtifact:this.options.fetchPluginHostArtifact,runtimeManager:this.options.runtimeManager,desktopBrowserBroker:this.options.desktopBrowserBroker,dataDir:this.options.dataDir,eventSink:this.options.eventSink,listModels:this.options.listModels,listCommands:this.options.listCommands,providerHealth:this.options.providerHealth,providerUsage:this.options.providerUsage,providerInstallationStatus:this.options.providerInstallationStatus,providerInstallationRun:this.options.providerInstallationRun,refreshShellEnv:this.options.refreshShellEnv,emitEnvironmentHookProgress:this.options.emitEnvironmentHookProgress,resolveInteractiveRequest:this.options.resolveInteractiveRequest,ensureConnectTunnelIdentity:this.options.ensureConnectTunnelIdentity,serverMove:this.options.serverMove,threadStorageRootPath:this.options.threadStorageRootPath,logger:this.options.logger}}logOnlineRpc(t){(t.handlerMs>=X3e||!t.ok)&&this.logger.debug?.({commandType:t.commandType,...t.errorCode?{errorCode:t.errorCode}:{},handlerMs:Ls(t.handlerMs),ok:t.ok},"Online host RPC")}getOrCreateReadWriteLane(t,n){let r=n.get(t);if(r)return r;let o=Promise.resolve(),s={tail:o,writeTail:o};return n.set(t,s),s}async runAfterThreadUnarchiveBarrier(t,n){if(t.type==="turn.submit"||t.type==="thread.start"){let r=this.threadUnarchiveBarriers.get(t.threadId);r&&await r}return n()}registerThreadUnarchiveBarrier(t,n){if(t.type!=="thread.unarchive")return;let{threadId:r}=t,o=n.then(()=>{},()=>{});this.threadUnarchiveBarriers.set(r,o),o.then(()=>{this.threadUnarchiveBarriers.get(r)===o&&this.threadUnarchiveBarriers.delete(r)})}runInReadWriteLane({key:t,lanes:n,mode:r,work:o}){let s=this.getOrCreateReadWriteLane(t,n);if(r==="read"){let u=s.writeTail.catch(()=>{}).then(o),d=u.then(()=>{},()=>{}),p=s.tail,m=Promise.all([p.catch(()=>{}),d]).then(()=>{});return s.tail=m,this.deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:s,tail:m}),u}let a=s.tail.catch(()=>{}).then(o),c=a.then(()=>{},()=>{});return s.tail=c,s.writeTail=c,this.deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:s,tail:c}),a}deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:r,tail:o}){o.then(()=>{n.get(t)===r&&r.tail===o&&n.delete(t)})}resolveThreadLaneKey(t){switch(t.type){case"thread.start":case"turn.submit":case"thread.archive":case"interactive.resolve":case"thread.stop":case"thread.storage.delete":case"thread.plan.cancel":case"thread.goal.clear":return`${t.environmentId}\0thread:${t.threadId}`;default:return null}}}});function Yie(e){let t=!1,n=!1,r=null,o=null,s=null,a=null,c=0,l,u=new Promise(w=>{l=w}),d=e.signalSource??process,p=new Map;function m(){for(let[w,T]of p)d.off(w,T);p.clear()}function f(w,T){(a===null||T>c)&&(a=w,c=T)}function v(){let w=e.exitProcess;if(!w)return;let T=e.shutdownExitGraceMs??eZe;s=setTimeout(()=>{s=null,e.logger.error({reason:a,graceMs:T,activeResources:process.getActiveResourcesInfo()},"Host daemon shutdown did not end the process; forcing exit so the service manager can restart it."),w(c)},T),s.unref?.()}function b(){let w=e.exitProcess;n||!w||(s!==null&&(clearTimeout(s),s=null),w(c))}async function S(w,T){return f(w,T),r||(v(),r=(async()=>{m(),e.logger.info({mode:"shutdown",reason:w},"Shutting down host daemon");let A=null,F=[{name:"flushEvents",run:e.flushEvents},{name:"shutdownRuntimes",run:e.shutdownRuntimes},{name:"releaseLock",run:e.releaseLock}];for(let $ of F)if($.run)try{await $.run()}catch(B){let H=lo(B);A??=H,e.logger.error({err:H,step:$.name},"Shutdown step failed")}if(A)throw o=A,l?.(),A;l?.(),b()})(),r)}async function E(w,T){return S(w,T)}return{identity:e.identity,async start(){if(!(t||r)){for(let w of Q3e){let T=()=>{S(w,0).catch(A=>{e.logger.error({err:A,signal:w},"Signal-triggered host daemon shutdown failed")})};p.set(w,T),d.on(w,T)}try{if(await e.onStart?.(),r)return;t=!0,e.logger.info({identity:e.identity},"Host daemon started")}catch(w){if(r){await S("startup-interrupted",0).catch(()=>{});return}throw n=!0,await S("startup-failed",1).catch(()=>{}),w}}},shutdown:E,async waitUntilStopped(){if(await u,o)throw o}}}var Q3e,eZe,Xie=g(()=>{"use strict";Fi();Q3e=["SIGINT","SIGTERM"],eZe=15e3});var ese=M((Njt,Qie)=>{function mr(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Qie.exports=mr;mr.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};mr.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};mr.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0};mr.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};mr.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};mr.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};mr.prototype.start=mr.prototype.try;mr.prototype.errors=function(){return this._errors};mr.prototype.attempts=function(){return this._attempts};mr.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var o=this._errors[r],s=o.message,a=(e[s]||0)+1;e[s]=a,a>=n&&(t=o,n=a)}return t}});var tse=M(ya=>{var tZe=ese();ya.operation=function(e){var t=ya.timeouts(e);return new tZe(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};ya.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<t.retries;o++)r.push(this.createTimeout(o,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,t)),r.sort(function(s,a){return s-a}),r};ya.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout),r};ya.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n){n=[];for(var r in e)typeof e[r]=="function"&&n.push(r)}for(var o=0;o<n.length;o++){var s=n[o],a=e[s];e[s]=function(l){var u=ya.operation(t),d=Array.prototype.slice.call(arguments,1),p=d.pop();d.push(function(m){u.retry(m)||(m&&(arguments[0]=u.mainError()),p.apply(this,arguments))}),u.attempt(function(){l.apply(e,d)})}.bind(e,a),e[s].options=t}}});var rse=M((Bjt,nse)=>{nse.exports=tse()});function _L(e){if(!(e&&rZe(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:n,stack:r}=e;return n==="Load failed"?r===void 0||"__sentry_captured__"in e:n.startsWith("error sending request for url")||n==="Failed to fetch"||n.startsWith("Failed to fetch (")&&n.endsWith(")")?!0:oZe.has(n)}var nZe,rZe,oZe,ose=g(()=>{nZe=Object.prototype.toString,rZe=e=>nZe.call(e)==="[object Error]",oZe=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});async function kL(e,t){return new Promise((n,r)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=sse.default.operation(t),s=()=>{o.stop(),r(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let a=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async c=>{try{let l=await e(c);a(),n(l)}catch(l){try{if(!(l instanceof Error))throw new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`);if(l instanceof ou)throw l.originalError;if(l instanceof TypeError&&!_L(l))throw l;if(ise(l,c,t),await t.shouldRetry(l)||(o.stop(),r(l)),await t.onFailedAttempt(l),!o.retry(l))throw o.mainError()}catch(u){ise(u,c,t),a(),r(u)}}})})}var sse,ou,ise,ase=g(()=>{sse=Gt(rse(),1);ose();ou=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},ise=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e}});function iu(e=process.platform,t=process.env){return e==="darwin"?"darwin":e==="linux"?t.WSL_DISTRO_NAME!=null||t.WSL_INTEROP!=null?"wsl":"linux":e==="win32"?"win32":"unknown"}var Zx=g(()=>{"use strict"});function sZe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cse(e){return sZe(e)?e:null}function aZe(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}let n=cse(t);if(!n||typeof n.code!="string"||typeof n.message!="string")return null;let r=cse(n.details),o=r?.retryUpdate===!0,s=n.code===c8?iZe.safeParse(r).data??null:null;return typeof n.retryable=="boolean"?{code:n.code,message:n.message,protocolUpdateRetryRequested:o,retryable:n.retryable,serverMoved:s}:{code:n.code,message:n.message,protocolUpdateRetryRequested:o,serverMoved:s}}async function cZe(e){try{let t=await e.text(),n=aZe(t);return n!==null?n:e.status===403&&/body too large/i.test(t)?{code:null,message:"body too large",protocolUpdateRetryRequested:!1,serverMoved:null}:null}catch{return null}}function lZe(e){return e<400||e>=500}function uZe(e){return e.retryable?e:new ou(e)}function CL(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1"}function lse(e){if(!e)return null;let t=Number(e);return!Number.isSafeInteger(t)||t<0?null:t}function use(e,t){if(e.expectedSizeBytes!==void 0&&t>e.expectedSizeBytes)throw new Error(`Project attachment size mismatch: expected ${e.expectedSizeBytes} bytes, received more than ${e.expectedSizeBytes}`);if(t>e.maxBytes)throw new Error(`Project attachment exceeds ${e.maxBytes} byte limit: received ${t}`)}function AL(e,t){if(e.expectedSizeBytes!==void 0&&t!==e.expectedSizeBytes)throw new Error(`Project attachment size mismatch: expected ${e.expectedSizeBytes} bytes, received ${t}`);use(e,t)}async function mZe(e,t){if(!e.body)return AL(t,0),new Uint8Array;let n=e.body.getReader(),r=[],o=0;for(;;){let c=await n.read();if(c.done)break;o+=c.value.byteLength,use(t,o),r.push(c.value)}AL(t,o);let s=new Uint8Array(o),a=0;for(let c of r)s.set(c,a),a+=c.byteLength;return s}function fZe(e,t,n){if(t>n)throw new Error(`Host artifact exceeds the ${n} byte limit`);if(t>e)throw new Error(`Host artifact length mismatch: expected ${e}, received more than ${e}`)}function hZe(e,t){let n=lse(e.headers.get("content-length"));if(n!==null){if(n>qn)throw new Error(`Host artifact exceeds the ${qn} byte limit`);if(n!==t)throw new Error(`Host artifact length mismatch: expected ${t}, received ${n}`)}}async function gZe(e,t,n=qn){if(!e.body)throw new Error(`Host artifact length mismatch: expected ${t}, received 0`);let r=e.body.getReader(),o=[],s=0;try{for(;;){let l=await r.read();if(l.done)break;s+=l.value.byteLength,fZe(t,s,n),o.push(l.value)}}catch(l){throw await r.cancel(l).catch(()=>{}),l}if(s!==t)throw new Error(`Host artifact length mismatch: expected ${t}, received ${s}`);let a=new Uint8Array(s),c=0;for(let l of o)a.set(l,c),c+=l.byteLength;return a}function dse(e){let t=e.fetchFn??fetch;function n(){let a=e.getSessionId();if(!a)throw new Error("Server session is not open");return a}function r(){return{authorization:`Bearer ${e.hostKey}`,"content-type":"application/json",...e.serverHeaders}}function o(a,c){let l=new URL(`/internal${a}`,e.serverUrl);if(c)for(let[u,d]of Object.entries(c))d!==void 0&&l.searchParams.set(u,d);return l.toString()}async function s(a,c){let l=await cZe(c);return new fr({action:a,bodyMessage:l?.message??null,code:l?.code??null,protocolUpdateRetryRequested:l?.protocolUpdateRetryRequested??!1,retryable:l?.retryable??lZe(c.status),serverMoved:l?.serverMoved??null,status:c.status,statusText:c.statusText})}return{async openSession(a){let c={hostId:a.hostId,instanceId:a.instanceId,hostName:a.hostName,hasMachineCredential:!!e.serverHeaders?.["x-bb-connect-machine"]?.trim(),platform:iu(),dataDir:a.dataDir,localApiPort:a.localApiPort,protocolVersion:258,activeThreads:await a.activeThreads,undeliveredEventThreadIds:a.undeliveredEventThreadIds,loadedEnvironments:await a.loadedEnvironments},l=await t(o("/session/open"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(l.status!==201)throw await s("open session",l);return xJ.parse(await l.json())},async fetchProjectAttachment(a){if(!CL(e.serverUrl))throw new ou(`Refusing to fetch project attachment over insecure server URL: ${e.serverUrl}`);let c={sessionId:n(),threadId:a.threadId,projectId:a.projectId,path:a.path},l=await t(o("/session/project-attachment-content",c),{method:"GET",headers:r()});if(!l.ok)throw await s("fetch project attachment",l);let u=lse(l.headers.get("content-length"));return u!==null&&AL(a,u),{bytes:await mZe(l,a)}},async fetchSkillTree(a){let c=await t(o(`/skills/tree/${encodeURIComponent(a)}`),{method:"GET",headers:r()});if(!c.ok)throw await s("fetch skill tree",c);return DJ.parse(await c.json())},async fetchPluginHostArtifact(a){if(a.expectedByteLength>qn)throw new Error(`Host artifact exceeds the ${qn} byte limit`);let c=await t(o(`/plugins/${encodeURIComponent(a.pluginId)}/host/${encodeURIComponent(a.digest)}`),{method:"GET",headers:r()});if(!c.ok)throw await s("fetch plugin host artifact",c);return hZe(c,a.expectedByteLength),gZe(c,a.expectedByteLength)},async postEvents(a){let c={sessionId:n(),eventGroups:wJ(a)},l=new AbortController,u=setTimeout(()=>{l.abort(new Error("Sending station updates timed out."))},dZe);u.unref();try{let d=await t(o("/session/events"),{method:"POST",headers:r(),body:JSON.stringify(c),signal:l.signal});if(!d.ok)throw await s("post events",d);let p=await d.json(),m=EJ.parse(p);return{acceptedEvents:m.acceptedEvents,rejectedEvents:m.rejectedEvents}}catch(d){throw l.signal.throwIfAborted(),d}finally{clearTimeout(u)}},async callTool(a,c){let l={threadId:a.threadId,providerThreadId:a.providerThreadId,turnId:a.turnId,callId:a.callId,tool:a.tool,...a.arguments!==void 0?{arguments:a.arguments}:{},sessionId:n()},u=await t(o("/session/tool-call"),{signal:c,method:"POST",headers:r(),body:JSON.stringify(l)});if(!u.ok)throw await s("call tool",u);return kJ.parse(await u.json())},async registerInteractiveRequest(a){return kL(async()=>{await e.beforeInteractiveRequestRegistrationAttempt?.();let c={sessionId:n(),interaction:a},l=await t(o("/session/interactive-request"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(!l.ok)throw uZe(await s("register interactive request",l));return AJ.parse(await l.json())},{retries:pZe,minTimeout:100,maxTimeout:2e3,randomize:!0,onFailedAttempt(c){e.logger.warn({attempt:c.attemptNumber,retriesLeft:c.retriesLeft,...Xe(c)},"interactive request registration failed, retrying")}})},async interruptInteractiveRequests(a){let c={sessionId:n(),providerId:a.providerId,threadIds:[...a.threadIds],reason:a.reason},l=await t(o("/session/interactive-request/interrupt"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(!l.ok)throw await s("interrupt interactive requests",l);return CJ.parse(await l.json())}}}var iZe,fr,dZe,pZe,Gm=g(()=>{"use strict";ase();j();wt();Vp();Fi();Zx();iZe=i.object({serverUrl:Vb.shape.serverUrl,toHostName:Vb.shape.toHostName,movedAt:Vb.shape.movedAt,headers:i.record(i.string(),i.string()).optional()}),fr=class extends Error{action;bodyMessage;code;protocolUpdateRetryRequested;retryable;serverMoved;status;statusText;constructor(t){let n=t.bodyMessage?` - ${t.bodyMessage}`:"";super(`Failed to ${t.action}: ${t.status} ${t.statusText}${n}`),this.name="ServerResponseError",this.action=t.action,this.bodyMessage=t.bodyMessage,this.code=t.code,this.protocolUpdateRetryRequested=t.protocolUpdateRetryRequested??!1,this.retryable=t.retryable,this.serverMoved=t.serverMoved??null,this.status=t.status,this.statusText=t.statusText}};dZe=3e4,pZe=5});function wZe(e){return e.type!=="item/started"&&e.type!=="item/completed"||e.item.type!=="commandExecution"&&e.item.type!=="fileChange"?!1:e.item.approvalStatus==="waiting_for_approval"}function EZe(e){return e.type==="turn/started"||e.type==="item/completed"||e.type==="turn/completed"||e.type==="system/error"||e.type==="system/thread/interrupted"?!0:e.type==="provider/error"?e.willRetry!==!0:wZe(e)}function DL(e){return e instanceof fr&&(e.status===413||e.status===403&&/body too large/i.test(e.bodyMessage??"")||e.code==="invalid_request")}function PZe(e){return e.map(t=>({eventIndex:t.eventIndex,reason:t.reason,threadId:t.threadId}))}function mse(e){let t=e.now??(()=>Date.now()),n=[],r=new Map,o=new Set,s=new Set,a=new Map,c=null,l=0,u=null,d=new Set,p=Number.NEGATIVE_INFINITY,m=null,f=Number.POSITIVE_INFINITY,v=null,b=0,S=new Set,E=Number.NEGATIVE_INFINITY,w=null,T=null,A=!1,F=null,$=!1,B=pse;function H(){if($||F===null)return;let C=n.length,O=t()-F;O<Jx&&(C<SZe||O<xZe)||($=!0,e.logger.warn({queueDepth:C,queueAgeMs:O},"Daemon event queue is backing up; delivery may be stalled"))}function D(){m!==null&&(clearTimeout(m),m=null,f=Number.POSITIVE_INFINITY)}function U(){v!==null&&(clearTimeout(v),v=null)}function N(C){e.logger.error(Xe(lo(C)),"Daemon event delivery failed")}function X(C){if(A||v!==null||n.length===0)return;let O=C?0:Math.max(0,p+yZe-t()),L=t()+O;if(m!==null){if(f<=L)return;D()}f=L,m=setTimeout(()=>{m=null,f=Number.POSITIVE_INFINITY,he()},O)}function ie(){if(A||v!==null||!e.isSessionOpen())return;D();let C=Math.floor(B*(.5+Math.random()*.5));B=Math.min(B*2,bZe),v=setTimeout(()=>{v=null,Qe().catch(N)},C)}function pe(C,O){let L=0,Z=O;for(let{envelope:ae,queuedAt:Be}of C)Z=Math.min(Z,Be),(ae.event.type==="item/agentMessage/delta"||ae.event.type==="item/reasoning/summaryTextDelta"||ae.event.type==="item/reasoning/textDelta"||ae.event.type==="item/plan/delta")&&(L+=ae.event.delta.length);e.logger.debug({eventBatch:{events:C.length,textChars:L,oldestQueuedMs:O-Z,sincePreviousPostMs:c===null?null:O-c,postMs:t()-O,postedAt:O}},"Posted daemon event batch"),c=O}function oe(C){S.add(C);for(let L of d)L.envelope.threadId===C&&(d.delete(L),s.delete(L));let O=0;for(let L of n)L.envelope.threadId!==C&&(n[O++]=L);n.length=O}async function V(C){let O=C.findIndex(ae=>S.has(ae.envelope.threadId));if(O>=0){if(O>0){let Be=await V(C.slice(0,O));if(Be<O)return Be}let ae=O;for(;ae<C.length;){let Be=C[ae];if(!Be||!S.has(Be.envelope.threadId))break;ae+=1}return ae+await V(C.slice(ae))}if(C.length===0)return 0;let L,Z=t();try{L=await e.postEvents(C.map(ae=>ae.envelope))}catch(ae){l+=1;let Be=lo(ae);for(let P of C)s.add(P);w=t(),T=DL(Be)?"refused":"failed";let Lt=u??F??t();if(!DL(Be)&&t()-Lt>=Jx&&t()-E>=Jx&&(E=t(),e.onDeliveryStalled?.()),!DL(Be))return e.logger.error(Xe(Be),"Failed to post daemon events; keeping events queued for retry"),0;let[Ve]=C;if(C.length===1&&Ve!==void 0)return e.onRefusedEvent?(e.onRefusedEvent(Ve.envelope),oe(Ve.envelope.threadId),1):(e.logger.error({...Xe(Be),eventType:Ve.envelope.event.type,threadId:Ve.envelope.threadId},"Server refused a daemon event; keeping it queued for retry"),0);let x=Math.floor(C.length/2),h=await V(C.slice(0,x));return h<x?h:x+await V(C.slice(x))}for(let ae of C)s.delete(ae);s.size===0&&(T=null),l=L.rejectedEvents.length>0?l+1:0,(L.acceptedEvents.length>0||L.rejectedEvents.length===0)&&(u=t());for(let ae of C)d.delete(ae);return pe(C,Z),L.rejectedEvents.length>0&&e.logger.warn({rejectedEvents:PZe(L.rejectedEvents)},"Server rejected daemon events"),C.length}function se(){let C=[],O=256,L=0,Z=!1;for(let ae of n){if(r.has(ae.envelope.threadId)||Z){n[L++]=ae;continue}if(C.length>0&&O+ae.bytes>ML){Z=!0,n[L++]=ae;continue}C.push(ae),O+=ae.bytes,Z=C.length>=OL}return n.length=L,C}function we(C,O){for(let L of C){let Z=(r.get(L.envelope.threadId)??1)-1;Z===0?r.delete(L.envelope.threadId):r.set(L.envelope.threadId,Z)}if(O<C.length){b+=1,A||n.unshift(...C.slice(O).filter(L=>!S.has(L.envelope.threadId)));return}n.length===0&&r.size===0&&(F=null,w=null,T=null,$=!1,B=pse)}function he(){if(A||!e.isSessionOpen()||o.size>=vZe)return;let C=se();if(C.length===0)return;p=t(),a.set(C,t());for(let Z of C)r.set(Z.envelope.threadId,(r.get(Z.envelope.threadId)??0)+1);let O=b,L=V(C).catch(Z=>(N(Z),0)).then(Z=>{we(C,Z)}).finally(()=>{o.delete(L),a.delete(C);for(let Z of C)r.has(Z.envelope.threadId)||S.delete(Z.envelope.threadId);b!==O?ie():X(n.some(Z=>Z.immediate&&!r.has(Z.envelope.threadId)))});o.add(L)}async function Qe(){for(D(),U();;){let C=b;if(he(),o.size===0||(await Promise.all(o),b!==C))return}}return{emit(C){if(A)throw new Vm;F===null&&(F=t()),S.delete(C.threadId);let O=EZe(C.event),L={threadId:C.threadId,event:C.event,...C.deliveryId===void 0?{}:{deliveryId:C.deliveryId}},Z={envelope:L,bytes:Buffer.byteLength(JSON.stringify(L))+32,immediate:O,queuedAt:t()};n.push(Z),d.add(Z),H(),X(O)},flush:Qe,deliveryHealth(){let C=t(),O=e.isSessionOpen()?C:F??C;for(let L of a.values())O=Math.min(O,L);return{pendingEvents:d.size,backlogSince:F,lastFailureAt:w,failure:T,stalled:d.size>0&&(T!==null||C-O>=Jx)}},deliveryReport(){let C=null;for(let O of d)C=C===null?O.queuedAt:Math.min(C,O.queuedAt);return{oldestPendingAt:C,consecutiveRefusals:l,lastAcceptedAt:u}},listUndeliveredThreadIds(){let C=new Set(r.keys());for(let O of n)C.add(O.envelope.threadId);return[...C]},async dispose(){A=!0,D(),U(),await Promise.all(o),n.length=0,s.clear(),d.clear(),S.clear(),F=null,T=null,w=null}}}var OL,ML,vZe,yZe,pse,bZe,SZe,xZe,Jx,Vm,NL=g(()=>{"use strict";wM();Fi();Gm();OL=256,ML=1024*1024,vZe=2,yZe=NS,pse=1e3,bZe=3e4,SZe=512,xZe=5e3,Jx=3e4,Vm=class extends Error{constructor(){super("Cannot emit to disposed event sink"),this.name="EventSinkDisposedError"}}});import{Buffer as TZe}from"node:buffer";function gse(e){let t=e.now??Date.now,n=new Map,r=0,o=!1,s=Number.NEGATIVE_INFINITY,a=null;function c(){let p=t();p-s<LL||(s=p,e.onDeliveryStalled?.())}let l=mse({...e,onDeliveryStalled:c,onRefusedEvent:p=>{e.spool.defer(p,t(),t()+LL);let m=e.spool.summary().oldest;m!==null&&t()-m>=LL&&c();for(let[f,v]of n)v.threadId===p.threadId&&(r-=v.bytes,n.delete(f));d()},postEvents:async p=>{let m=await e.postEvents(p);e.spool.acknowledge(p);for(let f of p){if(f.deliveryId===void 0)throw new Error("Saved event has no delivery ID");r-=n.get(f.deliveryId)?.bytes??0,n.delete(f.deliveryId)}return d(),m}});function u(){if(a!==null&&clearTimeout(a),a=null,o)return;let p=e.spool.deferrals().next;p===null||p<=t()||(a=setTimeout(()=>{a=null,d(),l.flush().catch(m=>{e.logger.error({error:String(m)},"Retrying saved station updates failed.")})},p-t()))}function d(){if(o||n.size>=fse||r>=hse)return;let p=e.spool.take(new Set(n.keys()),fse-n.size,hse-r,t());for(let{deliveryId:m,envelope:f}of p){let v=TZe.byteLength(JSON.stringify(f));n.set(m,{bytes:v,threadId:f.threadId}),r+=v,l.emit(f)}u()}return d(),{emit(p){if(o){l.emit(p);return}e.spool.append(p,t()),d()},async flush(){d(),await l.flush()},deliveryHealth(){let p=l.deliveryHealth(),m=e.spool.summary(),f=e.spool.deferrals();return{...p,pendingEvents:m.count,backlogSince:m.oldest,failure:f.count>0?"refused":p.failure,lastFailureAt:f.oldest??p.lastFailureAt,stalled:m.count>0&&(p.stalled||f.count>0)}},deliveryReport(){return{...l.deliveryReport(),oldestPendingAt:e.spool.summary().oldest}},listUndeliveredThreadIds:()=>e.spool.threadIds(),async dispose(){if(!o){o=!0,a!==null&&clearTimeout(a),a=null;try{await l.dispose()}finally{e.spool.close()}}}}}var fse,hse,LL,vse=g(()=>{"use strict";NL();fse=2*OL,hse=2*ML,LL=3e4});import{randomUUID as RZe,createHash as IZe}from"node:crypto";import{chmodSync as yse,mkdirSync as _Ze}from"node:fs";import{join as bse}from"node:path";import{DatabaseSync as kZe}from"node:sqlite";function Sse(e,t){let n=bse(e,"event-delivery");_Ze(n,{recursive:!0,mode:448}),yse(n,448);let r=IZe("sha256").update(t).digest("hex"),o=bse(n,`${r}.sqlite`),s=new kZe(o);yse(o,384),s.exec(`
212
+ `))},c=()=>{t||(t=!0,r(),o.close())};a({type:"started",provider:e.providerId,command:e.plan.displayCommand});try{n=(e.processSpawner??c3e()).spawn({command:e.plan.command,args:[...e.plan.args],...e.env===void 0?{}:{env:e.env}})}catch(l){a({type:"error",provider:e.providerId,message:l instanceof Error?l.message:String(l)}),c();return}n.stdout.setEncoding("utf8"),n.stdout.on("data",l=>a({type:"output",provider:e.providerId,stream:"stdout",text:l})),n.stderr.setEncoding("utf8"),n.stderr.on("data",l=>a({type:"output",provider:e.providerId,stream:"stderr",text:l})),n.onError(l=>{a({type:"error",provider:e.providerId,message:l.message}),c()}),n.onClose((l,u)=>{a({type:"completed",provider:e.providerId,exitCode:l,signal:u,success:l===0}),c()})},cancel(){t=!0,r(),n?.kill("SIGTERM")}})}var a3e,Hm,Um,lie=g(()=>{"use strict";Ee();wt();vL();a3e={debug(){},info(){},warn(){},error(){}},Hm=null,Um=class extends Error{providerId;constructor(t){super(`Provider installation already running for ${t}`),this.name="ProviderInstallationInProgressError",this.providerId=t}}});import{mkdir as l3e,readFile as u3e,rm as d3e,rmdir as p3e,stat as m3e,writeFile as f3e}from"node:fs/promises";import ga from"node:path";function g3e(e){return ga.isAbsolute(e)||ga.win32.isAbsolute(e)||/^[a-zA-Z][a-zA-Z0-9+.-]*:/u.test(e)}function die(e){return e.type!=="localFile"&&e.type!=="localImage"?!1:!g3e(e.path)}function v3e(e){let n=(e.type==="localFile"&&e.name?e.name:e.path).replaceAll("\\","/"),o=ga.posix.basename(n).replace(/[^a-zA-Z0-9._-]+/gu,"-");return o.length>0?o:"attachment"}function y3e(e){return e instanceof Error?e.message:String(e)}function yL(e){return e.type==="localFile"?e.sizeBytes:void 0}function b3e(e){let t=yL(e.attachment);if(t!==void 0&&t>36700160)throw new W("attachment_unavailable",`Attachment ${e.attachment.path} exceeds ${36700160} byte limit`)}function S3e(e,t){let n=yL(e);if(n!==void 0&&t.byteLength!==n)throw new W("attachment_unavailable",`Attachment ${e.path} size mismatch: expected ${n} bytes, received ${t.byteLength}`);if(t.byteLength>36700160)throw new W("attachment_unavailable",`Attachment ${e.path} exceeds ${36700160} byte limit`)}function zm(e,t,n){let r=s3({rootPath:e,candidatePath:t});if(!r)throw new W("invalid_path",n);return r}function x3e(e){let t=zm(e.threadStorageRootPath,ga.join(e.threadStorageRootPath,e.threadId),"Attachment staging path escapes the thread storage root");return zm(e.threadStorageRootPath,ga.join(t,"Attachments"),"Attachment staging path escapes the thread storage root")}function w3e(e,t){let n=ga.extname(e);return n?`${e.slice(0,-n.length)}${t}${n}`:`${e}${t}`}async function E3e(e,t){return(await m3e(e)).size!==t.byteLength?!1:Buffer.from(t).equals(await u3e(e))}async function P3e(e,t){let n=v3e(e.attachment);for(let r=1;;r+=1){let o=ga.join(e.stagingDir,r===1?n:w3e(n,`-${r}`));if(!e.stagedPaths.includes(o)){try{return await f3e(o,t,{flag:"wx",mode:h3e}),e.createdPaths.push(o),o}catch(s){if(!Ne(s,"EEXIST"))throw s}if(await E3e(o,t))return o}}}async function uie(e,t){await Promise.all(t.map(n=>d3e(n,{force:!0,recursive:!1}))),await p3e(e).catch(()=>{})}async function T3e(e){b3e(e);let t;try{t=(await e.fetchProjectAttachment({expectedSizeBytes:yL(e.attachment),maxBytes:36700160,projectId:e.projectId,threadId:e.threadId,path:e.attachment.path})).bytes}catch(n){throw new W("attachment_unavailable",`Failed to fetch attachment ${e.attachment.path}: ${y3e(n)}`)}return S3e(e.attachment,t),P3e(e,t)}async function R3e(e){let t=[];for(let n of e.input){if(!die(n)){t.push(n);continue}let r=await T3e({...e,attachment:n});t.push({...n,path:r}),e.stagedPaths.push(r)}return t}async function pie(e){let t=await bL({...e,inputGroups:[e.input]});return{cleanup:t.cleanup,input:t.inputGroups[0]??e.input}}async function bL(e){if(!e.inputGroups.some(o=>o.some(die)))return{cleanup:async()=>{},inputGroups:e.inputGroups};let t=x3e({...e,input:[]});await l3e(t,{recursive:!0});let n=[],r=[];try{let o=[];for(let s of e.inputGroups)o.push(await R3e({...e,createdPaths:n,input:s,stagedPaths:r,stagingDir:t}));return{cleanup:()=>uie(t,n),inputGroups:o}}catch(o){throw await uie(t,n),o}}var h3e,mie=g(()=>{"use strict";Ee();Ye();Uo();h3e=384});function hie(e){return`${e.providerId}#bridge:${Ci(e.bridgeLaunch)}#${e.requirement??"thread_start"}`}function gie({ttlMs:e,now:t=Date.now}){let n=new Map,r=new Map,o=0;function s(c,l){let u=r.get(c);if(u!==void 0)return u;let d=o,p=l().then(m=>d!==o?s(c,l):((m.installed||m.minimumSupportedVersion===null)&&!m.versionUnsupported?n.set(c,{status:m,expiresAt:t()+e}):n.delete(c),m),m=>{if(d!==o)return s(c,l);throw n.delete(c),m}).finally(()=>{r.get(c)===p&&r.delete(c)});return r.set(c,p),p}return{clear(){o+=1,n.clear(),r.clear()},run:(c,l)=>{let u=n.get(c);return u===void 0?s(c,l):(u.expiresAt<=t()&&s(c,l).catch(()=>{}),Promise.resolve(u.status))}}}var fie,SL=g(()=>{"use strict";HS();fie=5*6e4});import{AsyncLocalStorage as I3e}from"node:async_hooks";import{performance as vie}from"node:perf_hooks";function yie(e,t){return e.type!=="turn.submit"?t():xL.run({receivedAt:vie.now(),trace:{spans:[]}},t)}function ji(e){let t=xL.getStore();t!==void 0&&t.trace.spans.push({name:e,atMs:Ls(vie.now()-t.receivedAt)})}function bie(){return xL.getStore()?.trace??{spans:[]}}var xL,wL=g(()=>{"use strict";Ee();xL=new I3e});import xie from"node:fs/promises";import _3e from"node:path";async function wie(e,t){let n=zm(t.threadStorageRootPath,_3e.join(t.threadStorageRootPath,e.threadId),"Thread storage path escapes the storage root");await Ap({directories:[n]}),await xie.rm(n,{recursive:!0,force:!0})}async function Eie(e){try{await e()}catch{}}async function Pie({command:e,options:t}){if(!e.bridgeLaunch.capabilities.providerInstallation)return;let n=e.type==="thread.rewind.prepare"?"thread_rewind":void 0;await t.refreshShellEnv({allowStale:!0});let r=await t.runtimeManager.providerInstallationGate.run(hie({providerId:e.providerId,bridgeLaunch:e.bridgeLaunch,requirement:n}),async()=>{let a=await lr(e.bridgeLaunch,t);return t.providerInstallationStatus({providerId:e.providerId,bridgeLaunch:a,checkUpdates:!1,...n!==void 0?{requirement:n}:{}})});if(!r.versionUnsupported)return;let o=r.currentVersion?` ${r.currentVersion}`:"",s=r.minimumSupportedVersion??"a newer version";throw new ge("provider_cli_unsupported_version",`Provider "${e.providerId}"${o} is too old for this operation. Update it to ${s} or newer.`)}async function Tie(e){if(e.command.inputGroups!==void 0){let t=await bL({fetchProjectAttachment:e.fetchProjectAttachment,inputGroups:e.command.inputGroups,projectId:e.projectId,requestId:e.command.requestId,threadStorageRootPath:e.threadStorageRootPath,threadId:e.command.threadId});return{cleanup:t.cleanup,input:Vg(t.inputGroups)}}return pie({fetchProjectAttachment:e.fetchProjectAttachment,input:e.command.input,projectId:e.projectId,requestId:e.command.requestId,threadStorageRootPath:e.threadStorageRootPath,threadId:e.command.threadId})}async function Rie(e,t){let n=await lr(e.bridgeLaunch,t),r=await ro({environmentId:e.environmentId,injectedSkillSources:e.injectedSkillSources,runtimeManager:t.runtimeManager,targetThreadId:e.threadId,workspaceContext:e.workspaceContext});return{bridgeLaunch:n,entry:r}}async function Iie(e){let{command:t,entry:n,options:r}=e,{resumeContext:o}=t;if(n.runtime.hasThread(t.threadId))return;if(!o.providerThreadId)throw new W("unknown_thread_runtime",`No provider thread id available for thread ${t.threadId}`);let s=await lr(t.resumeContext.bridgeLaunch??t.bridgeLaunch,r);await n.runtime.resumeThread({bridgeLaunch:s,skillRoots:n.skillRoots,environmentId:t.environmentId,threadId:t.threadId,projectId:o.projectId,providerThreadId:o.providerThreadId,providerId:o.providerId,contributedEnv:o.contributedEnv,options:t.options,instructions:o.instructions,dynamicTools:o.dynamicTools,instructionMode:o.instructionMode})}async function _ie(e,t){if(await Pie({command:e,options:t}),e.threadStoragePath){let r=zm(t.threadStorageRootPath,e.threadStoragePath,"Thread storage path escapes the storage root");await xie.mkdir(r,{recursive:!0})}let n=await Tie({command:e,fetchProjectAttachment:t.fetchProjectAttachment,projectId:e.projectId,threadStorageRootPath:t.threadStorageRootPath});try{let{bridgeLaunch:r,entry:o}=await Rie(e,t);return await o.runtime.startThread({bridgeLaunch:r,skillRoots:o.skillRoots,environmentId:e.environmentId,threadId:e.threadId,projectId:e.projectId,providerId:e.providerId,contributedEnv:e.contributedEnv,clientRequestId:e.requestId,input:n.input,options:e.options,instructions:e.instructions,dynamicTools:e.dynamicTools,instructionMode:e.instructionMode,...e.fork?{fork:e.fork}:{}})}catch(r){throw await Eie(n.cleanup),r}}async function kie(e,t){await Pie({command:e,options:t});let{bridgeLaunch:n,entry:r}=await Rie(e,t);return r.runtime.prepareThreadRewind({bridgeLaunch:n,skillRoots:r.skillRoots,environmentId:e.environmentId,threadId:e.threadId,leaseId:e.leaseId,projectId:e.projectId,providerId:e.providerId,contributedEnv:e.contributedEnv,sourceProviderThreadId:e.sourceProviderThreadId,retainThroughProviderCheckpoint:e.retainThroughProviderCheckpoint,options:e.options,instructions:e.instructions,dynamicTools:e.dynamicTools,instructionMode:e.instructionMode})}async function Aie(e,t){let n=await t.runtimeManager.getOrAwait(e.environmentId);return n?(await n.runtime.discardThreadRewind({leaseId:e.leaseId}),{}):{}}async function EL(e,t){let{resumeContext:n}=e,r=await ro({environmentId:e.environmentId,injectedSkillSources:n.injectedSkillSources,runtimeManager:t.runtimeManager,targetThreadId:e.threadId,workspaceContext:n.workspaceContext});ji("skills.staged");let o=await t.runtimeManager.releaseThreadFromOtherEnvironments({activeTurn:e.type==="turn.submit"?"interrupt":"keep",environmentId:e.environmentId,threadId:e.threadId}),[s]=o.activeTurnEnvironmentIds;if(s!==void 0)throw new ge("thread_busy_in_other_environment",`Thread ${e.threadId} still runs a turn in environment ${s}`);return await Iie({command:e,entry:r,options:t}),ji("runtime.ready"),r}async function Cie(e,t){await t.runtime.runTurn({threadId:e.threadId,input:e.input,clientRequestId:e.requestId,options:e.options,contributedEnv:e.resumeContext.contributedEnv,instructions:e.resumeContext.instructions})}async function A3e(e,t,n){let r=n,o=null;for(let s=0;s<Sie;s+=1){let a=await t.runtime.steerTurn({threadId:e.threadId,expectedTurnId:r,input:e.input,clientRequestId:e.requestId,options:e.options,contributedEnv:e.resumeContext.contributedEnv,instructions:e.resumeContext.instructions});if(a.status==="steered")return;if(o=a.activeTurnId,s===Sie-1)break;let c=await Die(e,t);if(c===null)return Cie(e,t);if(c===r)break;r=c}throw new W("stale_turn",`Expected active turn ${r} for thread ${e.threadId}, but active turn is ${o??"none"}`)}async function Die(e,t){let n=t.runtime.getActiveTurnId(e.threadId);if(n!==null)return n;if(!t.runtime.getLiveThreadIds().includes(e.threadId))return null;let r=await t.runtime.waitForActiveTurn(e.threadId,{timeoutMs:k3e});if(r!==null)return r;let o=t.runtime.getActiveTurnId(e.threadId);if(o!==null)return o;if(t.runtime.getLiveThreadIds().includes(e.threadId))throw new W(sS,`Refusing to start a competing turn while ${e.threadId} is still starting`);return null}async function C3e(e,t){return e.target.mode==="start"?null:e.target.mode==="steer"&&e.target.expectedTurnId!==null?e.target.expectedTurnId:await Die(e,t)??e.target.expectedTurnId}async function D3e(e,t){let n=await C3e(e,t);return e.target.mode==="start"||n===null?Cie(e,t):A3e(e,t,n)}async function Oie(e,t,n){let r=await Tie({command:e,fetchProjectAttachment:n.fetchProjectAttachment,projectId:e.resumeContext.projectId,threadStorageRootPath:n.threadStorageRootPath});ji("input.staged");let o={...e,input:r.input};try{await Iie({command:o,entry:t,options:n}),await D3e(o,t)}catch(s){throw await Eie(r.cleanup),s}return ji("bridge.turnStarted"),{trace:bie()}}var k3e,Sie,Mie=g(()=>{"use strict";Me();Ee();wt();Ye();mie();SL();lm();wL();k3e=5e3,Sie=2});import PL from"node:fs/promises";import Wm from"node:path";function M3e(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,80).replace(/-+$/u,"")||"project"}function TL(e,t){return Wm.resolve(e,"checkouts",M3e(t))}async function N3e(e){try{if(!(await PL.stat(e)).isDirectory()||(await PL.readdir(e)).length>0)throw new ge("target_not_empty",`Clone target is not empty: ${e}`)}catch(t){if(t instanceof ge)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}}async function RL(e,t={}){let n=Wm.resolve(e),r=await Fe(["remote","get-url","origin"],{cwd:n,...t,allowFailure:!0}),o=r.exitCode===0?r.stdout.trim():"";return{path:n,gitRemoteUrl:o||null}}async function Nie(e){let t=Wm.resolve(e.targetPath??TL(e.dataDir,e.projectSlug));await N3e(t),await PL.mkdir(Wm.dirname(t),{recursive:!0});let n="",r=e.onProgress===void 0?void 0:o=>{for(n+=o;;){let s=/\r\n|\r|\n/u.exec(n);if(s===null)return;e.onProgress?.(n.slice(0,s.index)),n=n.slice(s.index+s[0].length)}};try{await Fe(["clone","--progress",e.remoteUrl,t],{cwd:Wm.dirname(t),env:e.env,...e.shellPath!==void 0?{shellPath:e.shellPath}:{},timeoutMs:O3e,...r===void 0?{}:{onStderr:r}})}catch(o){throw o instanceof Te?new ge(o.code,o.message):new Error(o instanceof Error?o.message:String(o))}finally{n.length>0&&e.onProgress?.(n)}return RL(t,e.shellPath===void 0?{}:{shellPath:e.shellPath})}var O3e,Lie=g(()=>{"use strict";$o();Ye();O3e=1200*1e3});import{constants as Bie}from"node:fs";import qx from"node:fs/promises";import qm from"node:path";function Fie(e){return Ne(e,"ENOENT")||e instanceof W&&e.code==="ENOENT"}async function F3e(e){try{let t=await Dx({resolvedPath:e.filePath,resultPath:e.filePath,rootPath:e.rootPath});return"content"in t?t.contentEncoding==="utf8"?t.content:Buffer.from(t.content,"base64").toString("utf8"):null}catch(t){if(Fie(t))return null;throw t}}async function $3e(e){let t=qm.join(e.skillsRootPath,e.directoryName);try{let n=qm.join(t,Vn),r=await Dr(n,e.rootPath);if(r===null)return null;let o=await qx.stat(r);if(!o.isFile())return null;if(!dt(await qx.realpath(e.rootPath),r))throw new W("invalid_path","Skill file escapes read root");let s={kind:"oversized",directoryName:e.directoryName,sizeBytes:o.size},a={kind:"budget-exceeded",directoryName:e.directoryName};if(o.size>e.maxFileBytes)return s;if(o.size+2>e.remainingBytes)return a;let c=Math.min(e.maxFileBytes,e.remainingBytes),l=await qx.open(r,Bie.O_RDONLY|Bie.O_NOFOLLOW),u;try{let d=Buffer.allocUnsafe(Math.min(o.size+1,c+1)),p=0;for(;p<=c;){if(p===d.length){let f=Buffer.allocUnsafe(Math.min(d.length*2,c+1));d.copy(f),d=f}let m=await l.read(d,p,d.length-p,null);if(m.bytesRead===0)break;p+=m.bytesRead}if(p>e.maxFileBytes)return{...s,sizeBytes:p};if(p>c)return a;u=d.subarray(0,p).toString("utf8")}finally{await l.close()}return Buffer.byteLength(JSON.stringify(u))>e.remainingBytes?a:{kind:"file",directoryName:e.directoryName,content:u}}catch(n){if(Fie(n))return null;throw n}}async function j3e(e,t){let n=qm.join(e,...L3e);if(await qx.realpath(n).catch(()=>null)!==null&&await Dr(n,e)===null)throw new W("invalid_path","Skills path escapes read root");let r=(await lN({path:n,shape:"skill",boundaryPath:e})).map(a=>a.name).filter(a=>!a.startsWith(".")&&!t.excludeNames.includes(a)),o=[],s=t.maxContentBytes;for(let a of r.slice(0,t.limit)){let c=await $3e({directoryName:a,rootPath:e,skillsRootPath:n,maxFileBytes:t.maxFileBytes,remainingBytes:s});c!==null&&(c.kind==="file"&&(s-=Buffer.byteLength(JSON.stringify(c.content))),o.push(c))}return{skills:o,truncated:r.length>t.limit}}async function H3e(e){let n=(await F3e({filePath:qm.join(e,...B3e),rootPath:e}))?.trim()??"";return n.length>0?n:null}async function $ie(e){if(!qm.isAbsolute(e.rootPath))throw new W("invalid_path","rootPath must be absolute");let[t,n,r]=await Promise.all([j3e(e.rootPath,e.projectSkillRead),e.includeAgentInstructions?H3e(e.rootPath):Promise.resolve(null),Vre({cwd:e.rootPath,roots:e.sharedSkillRoots})]);return{agentInstructions:n,projectSkills:t.skills,projectSkillsTruncated:t.truncated,sharedSkills:r}}var L3e,B3e,jie=g(()=>{"use strict";Ee();Ye();Im();Uo();Ox();GN();ym();L3e=[".bb","skills"],B3e=[".bb","AGENTS.md"]});import{mkdir as U3e}from"node:fs/promises";import z3e from"node:path";async function Hie(e,t){let n=await t.runtimeManager.releaseThreadFromOtherEnvironments({activeTurn:"interrupt",environmentId:e.environmentId,threadId:e.threadId}),r=await t.runtimeManager.getOrAwait(e.environmentId);if(!r)return await t.eventSink.flush(),{providerCheckpointId:n.providerCheckpointId};let o=n.providerCheckpointId;if(r.runtime.hasThread(e.threadId)){if(e.type==="thread.stop"&&e.intent==="release"&&r.runtime.getActiveTurnId(e.threadId)!==null)return await t.eventSink.flush(),{providerCheckpointId:o,activeTurnRetained:!0};(e.type!=="thread.stop"||e.intent!=="release")&&await r.runtime.waitForActiveTurn(e.threadId,{timeoutMs:W3e}),o=(await r.runtime.stopThread({threadId:e.threadId})).providerCheckpointId??o}return await t.eventSink.flush(),{providerCheckpointId:o}}function Wie(e){throw e instanceof Te&&e.code==="path_not_found"?new ge(e.code,e.message):e}function q3e(e){return e.PATH?{...process.env,PATH:e.PATH}:process.env}function qie(e,t){let n=e.trim();n.length!==0&&t.push(bl.parse(JSON.parse(n)))}function G3e(e,t){let n=e.split(/\r?\n/u),r=n.pop();for(let o of n)qie(o,t);return r??""}async function V3e(e){let t=e.getReader(),n=new TextDecoder,r=[],o="";for(;;){let s=await t.read();if(s.done)break;o+=n.decode(s.value,{stream:!0}),o=G3e(o,r)}return o+=n.decode(),qie(o,r),r}function Uie(e){let t=[...e.events],n=t.findIndex(o=>o.type==="completed"&&o.success),r=t[n];return r?.type!=="completed"?e.events:(t[n]={...r,success:!1},t.splice(n,0,{type:"error",provider:e.providerId,message:e.message}),t)}function K3e(e,t){switch(e.kind){case"installed":return t.installed;case"version_at_least":{let n=t.currentVersion===null?null:va.default.valid(t.currentVersion),r=va.default.valid(e.version);return n!==null&&r!==null&&va.default.gte(n,r)}case"version_changed":{let n=t.currentVersion;if(n===null)return!1;let r=va.default.valid(n),o=va.default.valid(e.previousVersion);return r!==null&&o!==null?va.default.gt(r,o):n!==e.previousVersion}}return!1}async function Z3e(e,t){try{let n=q3e(t.runtimeManager.getShellEnv()),r=await lr(e.bridgeLaunch,t),o={providerId:e.providerId,bridgeLaunch:r},s=await t.providerInstallationRun({...o,action:e.action});if(!s.available)return{events:[{type:"error",provider:e.providerId,message:s.message}]};let a=t.streamProviderInstallation??cie,c=await V3e(a({providerId:e.providerId,plan:s.command,env:n}));if(c.some(l=>l.type==="completed"&&l.success))try{let l=await t.providerInstallationStatus(o);K3e(s.verification,l)||(c=Uie({providerId:e.providerId,events:c,message:`${e.providerId} ${e.action} exited successfully, but the provider could not verify the installed result.`}))}catch{c=Uie({providerId:e.providerId,events:c,message:`${e.providerId} ${e.action} exited successfully, but its installation status could not be verified.`})}return c.some(l=>l.type==="completed"&&l.success)&&await t.runtimeManager.invalidateProviderMaintenanceRuntime(),{events:c}}catch(n){if(n instanceof Um)return{events:[{type:"error",provider:e.providerId,message:n.message}]};throw n}}async function Gx(e,t,n){let r=await t.runtimeManager.retainEnvironmentForThreadCommand(e.environmentId,e.threadId);try{return await n()}finally{r()}}function ru(e){if(!e.serverMove)throw new Error("Server move is unavailable on this daemon");return e.serverMove}async function Nr(e,t){if(!t.desktopBrowserBroker)throw new Error("Desktop browser broker unavailable");return t.desktopBrowserBroker.request(e)}async function zie(e,t,n){let r=await lr(e.bridgeLaunch,t);return n({providerId:e.providerId,...e.cwd!==void 0?{cwd:e.cwd}:{},bridgeLaunch:r})}async function Vx(e,t,n){let r=await NM({environmentId:e.environmentId,requireGit:!0,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext});if(!r.ok)return{outcome:"unavailable",failure:r.failure};try{return{outcome:"available",...await n(r.entry.workspace)}}catch(o){return{outcome:"unavailable",failure:MM({error:o,workspacePath:e.workspaceContext.workspacePath})}}}async function Gie(e,t){try{return await eO("interactive",()=>J3e[e.type](e,t))}catch(n){Wie(n)}}async function IL(e,t,n){try{return await eO(e.type==="workspace.status"?"status":"interactive",()=>Y3e[e.type](e,t,n))}catch(r){Wie(r)}}var va,W3e,J3e,Y3e,Vie=g(()=>{"use strict";OX();Ee();Tl();p7();wt();va=Gt(tee(),1);Ye();oee();pee();hre();$N();GN();Boe();Nx();joe();qoe();Voe();Zoe();lie();Mie();$o();Lie();lm();ta();jie();Ye();W3e=5e3;J3e={"thread.rewind.discard":(e,t)=>Gx(e,t,()=>Aie(e,t)),"thread.rewind.prepare":(e,t)=>Gx(e,t,()=>kie(e,t)),"thread.start":(e,t)=>Gx(e,t,()=>_ie(e,t)),"turn.submit":(e,t)=>Gx(e,t,async()=>{let n=await EL(e,t);return Oie(e,n,t)}),"thread.stop":Hie,"thread.storage.delete":async(e,t)=>{let n=await Hie(e,t);return await wie(e,t),n},"thread.goal.clear":async(e,t)=>{let r=await(await EL(e,t)).runtime.clearThreadGoal({threadId:e.threadId});return await t.eventSink.flush(),r},"thread.plan.cancel":async(e,t)=>{let n=t.runtimeManager.listThreadOwnerEntries(e.threadId);if(n.length===0)throw new ge("unknown_thread_runtime",`No provider runtime available for thread ${e.threadId}`);let r=n.find(o=>o.runtime.getActiveTurnId(e.threadId)===e.expectedTurnId);return r?(await r.runtime.stopThread({threadId:e.threadId}),await t.eventSink.flush(),{cancelled:!0}):{cancelled:!1}},"thread.rename":async(e,t)=>{let n=await t.runtimeManager.getOrAwait(e.environmentId);return n?(await n.runtime.renameThread({threadId:e.threadId,title:e.title}),{}):{}},"thread.archive":async(e,t)=>{let n=await ro({environmentId:e.environmentId,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext}),r=await lr(e.bridgeLaunch,t);return await n.runtime.archiveThread({threadId:e.threadId,providerId:e.providerId,providerThreadId:e.providerThreadId,bridgeLaunch:r}),{}},"thread.unarchive":async(e,t)=>{let n=await lr(e.bridgeLaunch,t);return await t.runtimeManager.withProviderMaintenanceRuntime({dataDir:t.dataDir},r=>r.unarchiveThread({threadId:e.threadId,providerId:e.providerId,providerThreadId:e.providerThreadId,bridgeLaunch:n})),{}},"interactive.resolve":Goe,"environment.attach":nee,"project.clone":(e,t)=>Nie({dataDir:t.dataDir,projectSlug:e.projectSlug,env:to(e.contributedEnv,{...process.env,...t.runtimeManager.getShellEnv()},!0),remoteUrl:e.remoteUrl,onProgress:n=>t.emitEnvironmentHookProgress?.({type:"environment.hook.progress",operationId:e.operationId,entry:{type:"output",text:n,status:null}}),...On(t.runtimeManager.getShellEnv()),...e.targetPath!==void 0?{targetPath:e.targetPath}:{}}),"environment.attach.cancel":ree,"workspace.commit":async(e,t)=>(await ro({environmentId:e.environmentId,requireGit:!0,runtimeManager:t.runtimeManager,workspaceContext:e.workspaceContext})).workspace.commit({message:e.message,noVerify:!0})},Y3e={"reply.private":DX,"desktop.broker.prove":async(e,t)=>{if(!t.desktopBrowserBroker)throw new Error("Desktop browser broker unavailable");return t.desktopBrowserBroker.prove(e.challenge)},"environment.hook.run":l7,"environment.hook.cancel":u7,"environment.inspect_cleanup":d7,"desktop.browser.list_instances":Nr,"desktop.browser.list_tabs":Nr,"desktop.browser.create_tab":Nr,"desktop.browser.reveal_tab":Nr,"desktop.browser.close_tab":Nr,"desktop.browser.capture_tab":Nr,"desktop.browser.acquire_control":Nr,"desktop.browser.open_connection":Nr,"desktop.browser.release_control":Nr,"desktop.browser.list_import_sources":Nr,"desktop.browser.import_cookies":Nr,"connect-tunnel.ensure-identity":async(e,t)=>{if(!t.ensureConnectTunnelIdentity)throw new Error("bb connect tunnel identity is unavailable");return t.ensureConnectTunnelIdentity()},"host.list_files":(e,t,n)=>Aoe(e,n),"host.list_paths":(e,t,n)=>Coe(e,n),"host.mkdir":Uoe,"host.move_path":zoe,"host.remove_path":Woe,"host.browse_directory":Doe,"host.paths_exist":Ooe,"project.inspect":async(e,t)=>RL(e.path,On(t.runtimeManager.getShellEnv())),"project.clone_default_path":async(e,t)=>({path:TL(t.dataDir,e.projectSlug)}),"host.pick_folder":Koe,"plugin.host.call":async()=>{throw new Error("plugin.host.call must be routed by CommandRouter")},"plugin.host.cancel":async()=>{throw new Error("plugin.host.cancel must be routed by CommandRouter")},"plugin.host.dispose":async()=>{throw new Error("plugin.host.dispose must be routed by CommandRouter")},"host.list_commands":wre,"host.list_skills":Kre,"host.read_workspace_agent_context":$ie,"host.delete_skill":Yre,"host.write_skill":Xre,"host.install_global_skills":fre,"host.global_skills_status":async e=>mre(e,{}),"host.inspect_git_source":dee,"host.list_branch_options":uee,"host.read_file":Moe,"host.read_file_chunk":Noe,"host.read_file_relative":Loe,"host.write_file":Mx,"provider.list_models":(e,t)=>zie(e,t,n=>t.listModels({...n,contributedEnv:e.contributedEnv})),"provider.list_commands":async(e,t)=>{let n=e.cwd??z3e.join(t.dataDir,"provider-command-catalog");return e.cwd===null&&await U3e(n,{recursive:!0}),t.listCommands({providerId:e.providerId,bridgeLaunch:await lr(e.bridgeLaunch,t),cwd:n})},"provider.health":(e,t)=>zie(e,t,n=>t.providerHealth(n)),"provider.usage":async(e,t)=>t.providerUsage({providerId:e.providerId,bridgeLaunch:await lr(e.bridgeLaunch,t)}),"host.discover_repos":e=>$oe({maxDepth:e.maxDepth,sinceDays:e.sinceDays,limit:e.limit}),"provider.installation.status":async(e,t)=>{let n=await lr(e.bridgeLaunch,t);return t.providerInstallationStatus({providerId:e.providerId,bridgeLaunch:n})},"provider.installation.run":Z3e,"workspace.status":(e,t)=>Vx(e,t,async n=>({workspaceStatus:await n.getStatus({mergeBaseBranch:e.mergeBaseBranch,maxFiles:e.maxFiles,maxUntrackedLineStatFiles:e.maxUntrackedLineStatFiles,maxUntrackedLineStatBytes:e.maxUntrackedLineStatBytes})})),"workspace.diff":(e,t)=>Vx(e,t,async n=>({diff:await n.getDiff({target:e.target,maxDiffBytes:e.maxDiffBytes,maxFileListBytes:e.maxFileListBytes,maxUntrackedFiles:e.maxUntrackedFiles})})),"workspace.diffFiles":(e,t)=>Vx(e,t,n=>n.diffFiles({target:e.target,maxFiles:e.maxFiles,ignoreWhitespace:e.ignoreWhitespace})),"workspace.diffPatch":(e,t)=>Vx(e,t,async n=>({patches:await n.diffPatch({target:e.target,paths:e.paths,maxBytesPerFile:e.maxBytesPerFile,ignoreWhitespace:e.ignoreWhitespace})})),"server_move.inspect":(e,t)=>ru(t).inspect(e),"server_move.probe":(e,t)=>ru(t).probe(e),"server_move.prepare":(e,t)=>ru(t).prepare(e),"server_move.activate":(e,t)=>ru(t).activate(e),"server_move.abort":(e,t)=>ru(t).abort(e),"server_move.delete_old_copy":(e,t)=>ru(t).deleteOldCopy()}});import{performance as Zie}from"node:perf_hooks";function Kie(e){return Zie.now()-e}var X3e,Kx,Jie=g(()=>{"use strict";wt();Vie();Ye();Ee();la();wL();X3e=1e3;Kx=class{constructor(t){this.options=t;this.logger=t.logger}options;logger;environmentLanes=new Map;threadUnarchiveBarriers=new Map;threadLaneTails=new Map;threadTurnLaneTails=new Map;onlineRpcAbortControllers=new Map;async handleOnlineRpcRequest(t){let n=Zie.now(),r=new AbortController;this.onlineRpcAbortControllers.set(t.requestId,r);try{let o=await yie(t.command,()=>this.executeHostRpcCommand(t.command,r.signal));return this.logOnlineRpc({commandType:t.command.type,handlerMs:Kie(n),ok:!0}),D0.parse({type:"host-rpc.response",requestId:t.requestId,commandType:t.command.type,ok:!0,result:o})}catch(o){let s=WS(o);return kX(o)||this.logger.warn({type:t.command.type,err:o},"online host RPC failed"),this.logOnlineRpc({commandType:t.command.type,errorCode:s,handlerMs:Kie(n),ok:!1}),{type:"host-rpc.response",requestId:t.requestId,commandType:t.command.type,ok:!1,errorCode:s,errorMessage:o instanceof Error?o.message:String(o)}}finally{this.onlineRpcAbortControllers.get(t.requestId)===r&&this.onlineRpcAbortControllers.delete(t.requestId)}}cancelOnlineRpcRequest(t){this.onlineRpcAbortControllers.get(t.requestId)?.abort()}executeHostRpcCommand(t,n){return aJ(t)?this.executeLiveDaemonCommand(t):this.executeOnlineRpcCommand(t,n)}executeOnlineRpcCommand(t,n){if(t.type==="plugin.host.call")return this.options.pluginHostManager?this.options.pluginHostManager.call(t):Promise.reject(new Error("host plugin runtime is unavailable"));if(t.type==="plugin.host.cancel"){if(!this.options.pluginHostManager)return Promise.reject(new Error("host plugin runtime is unavailable"));let s=this.options.pluginHostManager.cancel(t);return Promise.resolve(s)}if(t.type==="plugin.host.dispose")return this.options.pluginHostManager?this.options.pluginHostManager.dispose(t):Promise.reject(new Error("host plugin runtime is unavailable"));let r=k0(t);return(r&&"environmentId"in t?this.runInEnvironmentLane(t.environmentId,r,()=>IL(t,this.createDispatchOptions(),n)):IL(t,this.createDispatchOptions(),n)).then(s=>uJ(t,s))}executeLiveDaemonCommand(t){let n=k0(t),r=this.resolveThreadLaneKey(t),o=this.runAfterThreadUnarchiveBarrier(t,()=>this.runInThreadTurnLane(t,()=>this.runInExecutionLanes(t,n,r,()=>this.executeLiveDaemonCommandBody(t))));return this.registerThreadUnarchiveBarrier(t,o),o}async executeLiveDaemonCommandBody(t){ji("lanes.entered");let n=await Gie(t,this.createDispatchOptions());return cJ(t)&&(await this.options.eventSink.flush(),ji("events.flushed")),lJ(t,n)}runInEnvironmentLane(t,n,r){return this.runInReadWriteLane({key:t,lanes:this.environmentLanes,mode:n,work:r})}runInExecutionLanes(t,n,r,o){let s=r===null?o:()=>Nn(this.threadLaneTails,r,o);if(!n)return s();if(!("environmentId"in t)||!t.environmentId)throw new Error(`Command ${t.type} is missing environmentId`);return this.runInEnvironmentLane(t.environmentId,n,s)}runInThreadTurnLane(t,n){return t.type!=="thread.start"&&t.type!=="turn.submit"?n():Nn(this.threadTurnLaneTails,t.threadId,n)}createDispatchOptions(){return{fetchProjectAttachment:this.options.fetchProjectAttachment,fetchSkillTree:this.options.fetchSkillTree,fetchPluginHostArtifact:this.options.fetchPluginHostArtifact,runtimeManager:this.options.runtimeManager,desktopBrowserBroker:this.options.desktopBrowserBroker,dataDir:this.options.dataDir,eventSink:this.options.eventSink,listModels:this.options.listModels,listCommands:this.options.listCommands,providerHealth:this.options.providerHealth,providerUsage:this.options.providerUsage,providerInstallationStatus:this.options.providerInstallationStatus,providerInstallationRun:this.options.providerInstallationRun,refreshShellEnv:this.options.refreshShellEnv,emitEnvironmentHookProgress:this.options.emitEnvironmentHookProgress,resolveInteractiveRequest:this.options.resolveInteractiveRequest,ensureConnectTunnelIdentity:this.options.ensureConnectTunnelIdentity,serverMove:this.options.serverMove,threadStorageRootPath:this.options.threadStorageRootPath,logger:this.options.logger}}logOnlineRpc(t){(t.handlerMs>=X3e||!t.ok)&&this.logger.debug?.({commandType:t.commandType,...t.errorCode?{errorCode:t.errorCode}:{},handlerMs:Ls(t.handlerMs),ok:t.ok},"Online host RPC")}getOrCreateReadWriteLane(t,n){let r=n.get(t);if(r)return r;let o=Promise.resolve(),s={tail:o,writeTail:o};return n.set(t,s),s}async runAfterThreadUnarchiveBarrier(t,n){if(t.type==="turn.submit"||t.type==="thread.start"){let r=this.threadUnarchiveBarriers.get(t.threadId);r&&await r}return n()}registerThreadUnarchiveBarrier(t,n){if(t.type!=="thread.unarchive")return;let{threadId:r}=t,o=n.then(()=>{},()=>{});this.threadUnarchiveBarriers.set(r,o),o.then(()=>{this.threadUnarchiveBarriers.get(r)===o&&this.threadUnarchiveBarriers.delete(r)})}runInReadWriteLane({key:t,lanes:n,mode:r,work:o}){let s=this.getOrCreateReadWriteLane(t,n);if(r==="read"){let u=s.writeTail.catch(()=>{}).then(o),d=u.then(()=>{},()=>{}),p=s.tail,m=Promise.all([p.catch(()=>{}),d]).then(()=>{});return s.tail=m,this.deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:s,tail:m}),u}let a=s.tail.catch(()=>{}).then(o),c=a.then(()=>{},()=>{});return s.tail=c,s.writeTail=c,this.deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:s,tail:c}),a}deleteReadWriteLaneWhenIdle({key:t,lanes:n,state:r,tail:o}){o.then(()=>{n.get(t)===r&&r.tail===o&&n.delete(t)})}resolveThreadLaneKey(t){switch(t.type){case"thread.start":case"turn.submit":case"thread.archive":case"interactive.resolve":case"thread.stop":case"thread.storage.delete":case"thread.plan.cancel":case"thread.goal.clear":return`${t.environmentId}\0thread:${t.threadId}`;default:return null}}}});function Yie(e){let t=!1,n=!1,r=null,o=null,s=null,a=null,c=0,l,u=new Promise(w=>{l=w}),d=e.signalSource??process,p=new Map;function m(){for(let[w,T]of p)d.off(w,T);p.clear()}function f(w,T){(a===null||T>c)&&(a=w,c=T)}function v(){let w=e.exitProcess;if(!w)return;let T=e.shutdownExitGraceMs??eZe;s=setTimeout(()=>{s=null,e.logger.error({reason:a,graceMs:T,activeResources:process.getActiveResourcesInfo()},"Host daemon shutdown did not end the process; forcing exit so the service manager can restart it."),w(c)},T),s.unref?.()}function b(){let w=e.exitProcess;n||!w||(s!==null&&(clearTimeout(s),s=null),w(c))}async function S(w,T){return f(w,T),r||(v(),r=(async()=>{m(),e.logger.info({mode:"shutdown",reason:w},"Shutting down host daemon");let A=null,F=[{name:"flushEvents",run:e.flushEvents},{name:"shutdownRuntimes",run:e.shutdownRuntimes},{name:"releaseLock",run:e.releaseLock}];for(let $ of F)if($.run)try{await $.run()}catch(B){let H=lo(B);A??=H,e.logger.error({err:H,step:$.name},"Shutdown step failed")}if(A)throw o=A,l?.(),A;l?.(),b()})(),r)}async function E(w,T){return S(w,T)}return{identity:e.identity,async start(){if(!(t||r)){for(let w of Q3e){let T=()=>{S(w,0).catch(A=>{e.logger.error({err:A,signal:w},"Signal-triggered host daemon shutdown failed")})};p.set(w,T),d.on(w,T)}try{if(await e.onStart?.(),r)return;t=!0,e.logger.info({identity:e.identity},"Host daemon started")}catch(w){if(r){await S("startup-interrupted",0).catch(()=>{});return}throw n=!0,await S("startup-failed",1).catch(()=>{}),w}}},shutdown:E,async waitUntilStopped(){if(await u,o)throw o}}}var Q3e,eZe,Xie=g(()=>{"use strict";Fi();Q3e=["SIGINT","SIGTERM"],eZe=15e3});var ese=M((Njt,Qie)=>{function mr(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Qie.exports=mr;mr.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};mr.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};mr.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0};mr.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};mr.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};mr.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};mr.prototype.start=mr.prototype.try;mr.prototype.errors=function(){return this._errors};mr.prototype.attempts=function(){return this._attempts};mr.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var o=this._errors[r],s=o.message,a=(e[s]||0)+1;e[s]=a,a>=n&&(t=o,n=a)}return t}});var tse=M(ya=>{var tZe=ese();ya.operation=function(e){var t=ya.timeouts(e);return new tZe(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};ya.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<t.retries;o++)r.push(this.createTimeout(o,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,t)),r.sort(function(s,a){return s-a}),r};ya.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout),r};ya.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n){n=[];for(var r in e)typeof e[r]=="function"&&n.push(r)}for(var o=0;o<n.length;o++){var s=n[o],a=e[s];e[s]=function(l){var u=ya.operation(t),d=Array.prototype.slice.call(arguments,1),p=d.pop();d.push(function(m){u.retry(m)||(m&&(arguments[0]=u.mainError()),p.apply(this,arguments))}),u.attempt(function(){l.apply(e,d)})}.bind(e,a),e[s].options=t}}});var rse=M((Bjt,nse)=>{nse.exports=tse()});function _L(e){if(!(e&&rZe(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:n,stack:r}=e;return n==="Load failed"?r===void 0||"__sentry_captured__"in e:n.startsWith("error sending request for url")||n==="Failed to fetch"||n.startsWith("Failed to fetch (")&&n.endsWith(")")?!0:oZe.has(n)}var nZe,rZe,oZe,ose=g(()=>{nZe=Object.prototype.toString,rZe=e=>nZe.call(e)==="[object Error]",oZe=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});async function kL(e,t){return new Promise((n,r)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=sse.default.operation(t),s=()=>{o.stop(),r(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let a=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async c=>{try{let l=await e(c);a(),n(l)}catch(l){try{if(!(l instanceof Error))throw new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`);if(l instanceof ou)throw l.originalError;if(l instanceof TypeError&&!_L(l))throw l;if(ise(l,c,t),await t.shouldRetry(l)||(o.stop(),r(l)),await t.onFailedAttempt(l),!o.retry(l))throw o.mainError()}catch(u){ise(u,c,t),a(),r(u)}}})})}var sse,ou,ise,ase=g(()=>{sse=Gt(rse(),1);ose();ou=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},ise=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e}});function iu(e=process.platform,t=process.env){return e==="darwin"?"darwin":e==="linux"?t.WSL_DISTRO_NAME!=null||t.WSL_INTEROP!=null?"wsl":"linux":e==="win32"?"win32":"unknown"}var Zx=g(()=>{"use strict"});function sZe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cse(e){return sZe(e)?e:null}function aZe(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}let n=cse(t);if(!n||typeof n.code!="string"||typeof n.message!="string")return null;let r=cse(n.details),o=r?.retryUpdate===!0,s=n.code===c8?iZe.safeParse(r).data??null:null;return typeof n.retryable=="boolean"?{code:n.code,message:n.message,protocolUpdateRetryRequested:o,retryable:n.retryable,serverMoved:s}:{code:n.code,message:n.message,protocolUpdateRetryRequested:o,serverMoved:s}}async function cZe(e){try{let t=await e.text(),n=aZe(t);return n!==null?n:e.status===403&&/body too large/i.test(t)?{code:null,message:"body too large",protocolUpdateRetryRequested:!1,serverMoved:null}:null}catch{return null}}function lZe(e){return e<400||e>=500}function uZe(e){return e.retryable?e:new ou(e)}function CL(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1"}function lse(e){if(!e)return null;let t=Number(e);return!Number.isSafeInteger(t)||t<0?null:t}function use(e,t){if(e.expectedSizeBytes!==void 0&&t>e.expectedSizeBytes)throw new Error(`Project attachment size mismatch: expected ${e.expectedSizeBytes} bytes, received more than ${e.expectedSizeBytes}`);if(t>e.maxBytes)throw new Error(`Project attachment exceeds ${e.maxBytes} byte limit: received ${t}`)}function AL(e,t){if(e.expectedSizeBytes!==void 0&&t!==e.expectedSizeBytes)throw new Error(`Project attachment size mismatch: expected ${e.expectedSizeBytes} bytes, received ${t}`);use(e,t)}async function mZe(e,t){if(!e.body)return AL(t,0),new Uint8Array;let n=e.body.getReader(),r=[],o=0;for(;;){let c=await n.read();if(c.done)break;o+=c.value.byteLength,use(t,o),r.push(c.value)}AL(t,o);let s=new Uint8Array(o),a=0;for(let c of r)s.set(c,a),a+=c.byteLength;return s}function fZe(e,t,n){if(t>n)throw new Error(`Host artifact exceeds the ${n} byte limit`);if(t>e)throw new Error(`Host artifact length mismatch: expected ${e}, received more than ${e}`)}function hZe(e,t){let n=lse(e.headers.get("content-length"));if(n!==null){if(n>qn)throw new Error(`Host artifact exceeds the ${qn} byte limit`);if(n!==t)throw new Error(`Host artifact length mismatch: expected ${t}, received ${n}`)}}async function gZe(e,t,n=qn){if(!e.body)throw new Error(`Host artifact length mismatch: expected ${t}, received 0`);let r=e.body.getReader(),o=[],s=0;try{for(;;){let l=await r.read();if(l.done)break;s+=l.value.byteLength,fZe(t,s,n),o.push(l.value)}}catch(l){throw await r.cancel(l).catch(()=>{}),l}if(s!==t)throw new Error(`Host artifact length mismatch: expected ${t}, received ${s}`);let a=new Uint8Array(s),c=0;for(let l of o)a.set(l,c),c+=l.byteLength;return a}function dse(e){let t=e.fetchFn??fetch;function n(){let a=e.getSessionId();if(!a)throw new Error("Server session is not open");return a}function r(){return{authorization:`Bearer ${e.hostKey}`,"content-type":"application/json",...e.serverHeaders}}function o(a,c){let l=new URL(`/internal${a}`,e.serverUrl);if(c)for(let[u,d]of Object.entries(c))d!==void 0&&l.searchParams.set(u,d);return l.toString()}async function s(a,c){let l=await cZe(c);return new fr({action:a,bodyMessage:l?.message??null,code:l?.code??null,protocolUpdateRetryRequested:l?.protocolUpdateRetryRequested??!1,retryable:l?.retryable??lZe(c.status),serverMoved:l?.serverMoved??null,status:c.status,statusText:c.statusText})}return{async openSession(a){let c={hostId:a.hostId,instanceId:a.instanceId,hostName:a.hostName,hasMachineCredential:!!e.serverHeaders?.["x-bb-connect-machine"]?.trim(),platform:iu(),dataDir:a.dataDir,localApiPort:a.localApiPort,protocolVersion:258,activeThreads:await a.activeThreads,undeliveredEventThreadIds:a.undeliveredEventThreadIds,loadedEnvironments:await a.loadedEnvironments},l=await t(o("/session/open"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(l.status!==201)throw await s("open session",l);return xJ.parse(await l.json())},async fetchProjectAttachment(a){if(!CL(e.serverUrl))throw new ou(`Refusing to fetch project attachment over insecure server URL: ${e.serverUrl}`);let c={sessionId:n(),threadId:a.threadId,projectId:a.projectId,path:a.path},l=await t(o("/session/project-attachment-content",c),{method:"GET",headers:r()});if(!l.ok)throw await s("fetch project attachment",l);let u=lse(l.headers.get("content-length"));return u!==null&&AL(a,u),{bytes:await mZe(l,a)}},async fetchSkillTree(a){let c=await t(o(`/skills/tree/${encodeURIComponent(a)}`),{method:"GET",headers:r()});if(!c.ok)throw await s("fetch skill tree",c);return DJ.parse(await c.json())},async fetchPluginHostArtifact(a){if(a.expectedByteLength>qn)throw new Error(`Host artifact exceeds the ${qn} byte limit`);let c=await t(o(`/plugins/${encodeURIComponent(a.pluginId)}/host/${encodeURIComponent(a.digest)}`),{method:"GET",headers:r()});if(!c.ok)throw await s("fetch plugin host artifact",c);return hZe(c,a.expectedByteLength),gZe(c,a.expectedByteLength)},async postEvents(a){let c={sessionId:n(),eventGroups:wJ(a)},l=new AbortController,u=setTimeout(()=>{l.abort(new Error("Sending station updates timed out."))},dZe);u.unref();try{let d=await t(o("/session/events"),{method:"POST",headers:r(),body:JSON.stringify(c),signal:l.signal});if(!d.ok)throw await s("post events",d);let p=await d.json(),m=EJ.parse(p);return{acceptedEvents:m.acceptedEvents,rejectedEvents:m.rejectedEvents}}catch(d){throw l.signal.throwIfAborted(),d}finally{clearTimeout(u)}},async callTool(a,c){let l={threadId:a.threadId,providerThreadId:a.providerThreadId,turnId:a.turnId,callId:a.callId,tool:a.tool,...a.arguments!==void 0?{arguments:a.arguments}:{},sessionId:n()},u=await t(o("/session/tool-call"),{signal:c,method:"POST",headers:r(),body:JSON.stringify(l)});if(!u.ok)throw await s("call tool",u);return kJ.parse(await u.json())},async registerInteractiveRequest(a){return kL(async()=>{await e.beforeInteractiveRequestRegistrationAttempt?.();let c={sessionId:n(),interaction:a},l=await t(o("/session/interactive-request"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(!l.ok)throw uZe(await s("register interactive request",l));return AJ.parse(await l.json())},{retries:pZe,minTimeout:100,maxTimeout:2e3,randomize:!0,onFailedAttempt(c){e.logger.warn({attempt:c.attemptNumber,retriesLeft:c.retriesLeft,...Xe(c)},"interactive request registration failed, retrying")}})},async interruptInteractiveRequests(a){let c={sessionId:n(),providerId:a.providerId,threadIds:[...a.threadIds],reason:a.reason},l=await t(o("/session/interactive-request/interrupt"),{method:"POST",headers:r(),body:JSON.stringify(c)});if(!l.ok)throw await s("interrupt interactive requests",l);return CJ.parse(await l.json())}}}var iZe,fr,dZe,pZe,Gm=g(()=>{"use strict";ase();j();wt();Vp();Fi();Zx();iZe=i.object({serverUrl:Vb.shape.serverUrl,toHostName:Vb.shape.toHostName,movedAt:Vb.shape.movedAt,headers:i.record(i.string(),i.string()).optional()}),fr=class extends Error{action;bodyMessage;code;protocolUpdateRetryRequested;retryable;serverMoved;status;statusText;constructor(t){let n=t.bodyMessage?` - ${t.bodyMessage}`:"";super(`Failed to ${t.action}: ${t.status} ${t.statusText}${n}`),this.name="ServerResponseError",this.action=t.action,this.bodyMessage=t.bodyMessage,this.code=t.code,this.protocolUpdateRetryRequested=t.protocolUpdateRetryRequested??!1,this.retryable=t.retryable,this.serverMoved=t.serverMoved??null,this.status=t.status,this.statusText=t.statusText}};dZe=3e4,pZe=5});function wZe(e){return e.type!=="item/started"&&e.type!=="item/completed"||e.item.type!=="commandExecution"&&e.item.type!=="fileChange"?!1:e.item.approvalStatus==="waiting_for_approval"}function EZe(e){return e.type==="turn/started"||e.type==="item/completed"||e.type==="turn/completed"||e.type==="system/error"||e.type==="system/thread/interrupted"?!0:e.type==="provider/error"?e.willRetry!==!0:wZe(e)}function DL(e){return e instanceof fr&&(e.status===413||e.status===403&&/body too large/i.test(e.bodyMessage??"")||e.code==="invalid_request")}function PZe(e){return e.map(t=>({eventIndex:t.eventIndex,reason:t.reason,threadId:t.threadId}))}function mse(e){let t=e.now??(()=>Date.now()),n=[],r=new Map,o=new Set,s=new Set,a=new Map,c=null,l=0,u=null,d=new Set,p=Number.NEGATIVE_INFINITY,m=null,f=Number.POSITIVE_INFINITY,v=null,b=0,S=new Set,E=Number.NEGATIVE_INFINITY,w=null,T=null,A=!1,F=null,$=!1,B=pse;function H(){if($||F===null)return;let C=n.length,O=t()-F;O<Jx&&(C<SZe||O<xZe)||($=!0,e.logger.warn({queueDepth:C,queueAgeMs:O},"Daemon event queue is backing up; delivery may be stalled"))}function D(){m!==null&&(clearTimeout(m),m=null,f=Number.POSITIVE_INFINITY)}function U(){v!==null&&(clearTimeout(v),v=null)}function N(C){e.logger.error(Xe(lo(C)),"Daemon event delivery failed")}function X(C){if(A||v!==null||n.length===0)return;let O=C?0:Math.max(0,p+yZe-t()),L=t()+O;if(m!==null){if(f<=L)return;D()}f=L,m=setTimeout(()=>{m=null,f=Number.POSITIVE_INFINITY,he()},O)}function ie(){if(A||v!==null||!e.isSessionOpen())return;D();let C=Math.floor(B*(.5+Math.random()*.5));B=Math.min(B*2,bZe),v=setTimeout(()=>{v=null,Qe().catch(N)},C)}function pe(C,O){let L=0,Z=O;for(let{envelope:ae,queuedAt:Be}of C)Z=Math.min(Z,Be),(ae.event.type==="item/agentMessage/delta"||ae.event.type==="item/reasoning/summaryTextDelta"||ae.event.type==="item/reasoning/textDelta"||ae.event.type==="item/plan/delta")&&(L+=ae.event.delta.length);e.logger.debug({eventBatch:{events:C.length,textChars:L,oldestQueuedMs:O-Z,sincePreviousPostMs:c===null?null:O-c,postMs:t()-O,postedAt:O}},"Posted daemon event batch"),c=O}function oe(C){S.add(C);for(let L of d)L.envelope.threadId===C&&(d.delete(L),s.delete(L));let O=0;for(let L of n)L.envelope.threadId!==C&&(n[O++]=L);n.length=O}async function V(C){let O=C.findIndex(ae=>S.has(ae.envelope.threadId));if(O>=0){if(O>0){let Be=await V(C.slice(0,O));if(Be<O)return Be}let ae=O;for(;ae<C.length;){let Be=C[ae];if(!Be||!S.has(Be.envelope.threadId))break;ae+=1}return ae+await V(C.slice(ae))}if(C.length===0)return 0;let L,Z=t();try{L=await e.postEvents(C.map(ae=>ae.envelope))}catch(ae){l+=1;let Be=lo(ae);for(let P of C)s.add(P);w=t(),T=DL(Be)?"refused":"failed";let Lt=u??F??t();if(!DL(Be)&&t()-Lt>=Jx&&t()-E>=Jx&&(E=t(),e.onDeliveryStalled?.()),!DL(Be))return e.logger.error(Xe(Be),"Failed to post daemon events; keeping events queued for retry"),0;let[Ve]=C;if(C.length===1&&Ve!==void 0)return e.onRefusedEvent?(e.onRefusedEvent(Ve.envelope),oe(Ve.envelope.threadId),1):(e.logger.error({...Xe(Be),eventType:Ve.envelope.event.type,threadId:Ve.envelope.threadId},"Server refused a daemon event; keeping it queued for retry"),0);let x=Math.floor(C.length/2),h=await V(C.slice(0,x));return h<x?h:x+await V(C.slice(x))}for(let ae of C)s.delete(ae);s.size===0&&(T=null),l=L.rejectedEvents.length>0?l+1:0,(L.acceptedEvents.length>0||L.rejectedEvents.length===0)&&(u=t());for(let ae of C)d.delete(ae);return pe(C,Z),L.rejectedEvents.length>0&&e.logger.warn({rejectedEvents:PZe(L.rejectedEvents)},"Server rejected daemon events"),C.length}function se(){let C=[],O=256,L=0,Z=!1;for(let ae of n){if(r.has(ae.envelope.threadId)||Z){n[L++]=ae;continue}if(C.length>0&&O+ae.bytes>ML){Z=!0,n[L++]=ae;continue}C.push(ae),O+=ae.bytes,Z=C.length>=OL}return n.length=L,C}function we(C,O){for(let L of C){let Z=(r.get(L.envelope.threadId)??1)-1;Z===0?r.delete(L.envelope.threadId):r.set(L.envelope.threadId,Z)}if(O<C.length){b+=1,A||n.unshift(...C.slice(O).filter(L=>!S.has(L.envelope.threadId)));return}n.length===0&&r.size===0&&(F=null,w=null,T=null,$=!1,B=pse)}function he(){if(A||!e.isSessionOpen()||o.size>=vZe)return;let C=se();if(C.length===0)return;p=t(),a.set(C,t());for(let Z of C)r.set(Z.envelope.threadId,(r.get(Z.envelope.threadId)??0)+1);let O=b,L=V(C).catch(Z=>(N(Z),0)).then(Z=>{we(C,Z)}).finally(()=>{o.delete(L),a.delete(C);for(let Z of C)r.has(Z.envelope.threadId)||S.delete(Z.envelope.threadId);b!==O?ie():X(n.some(Z=>Z.immediate&&!r.has(Z.envelope.threadId)))});o.add(L)}async function Qe(){for(D(),U();;){let C=b;if(he(),o.size===0||(await Promise.all(o),b!==C))return}}return{emit(C){if(A)throw new Vm;F===null&&(F=t()),S.delete(C.threadId);let O=EZe(C.event),L={threadId:C.threadId,event:C.event,...C.deliveryId===void 0?{}:{deliveryId:C.deliveryId}},Z={envelope:L,bytes:Buffer.byteLength(JSON.stringify(L))+32,immediate:O,queuedAt:t()};n.push(Z),d.add(Z),H(),X(O)},flush:Qe,deliveryHealth(){let C=t(),O=e.isSessionOpen()?C:F??C;for(let L of a.values())O=Math.min(O,L);return{pendingEvents:d.size,backlogSince:F,lastFailureAt:w,failure:T,stalled:d.size>0&&(T!==null||C-O>=Jx)}},deliveryReport(){let C=null;for(let O of d)C=C===null?O.queuedAt:Math.min(C,O.queuedAt);return{oldestPendingAt:C,consecutiveRefusals:l,lastAcceptedAt:u}},listUndeliveredThreadIds(){let C=new Set(r.keys());for(let O of n)C.add(O.envelope.threadId);return[...C]},async dispose(){A=!0,D(),U(),await Promise.all(o),n.length=0,s.clear(),d.clear(),S.clear(),F=null,T=null,w=null}}}var OL,ML,vZe,yZe,pse,bZe,SZe,xZe,Jx,Vm,NL=g(()=>{"use strict";wM();Fi();Gm();OL=256,ML=1024*1024,vZe=2,yZe=NS,pse=1e3,bZe=3e4,SZe=512,xZe=5e3,Jx=3e4,Vm=class extends Error{constructor(){super("Cannot emit to disposed event sink"),this.name="EventSinkDisposedError"}}});import{Buffer as TZe}from"node:buffer";function gse(e){let t=e.now??Date.now,n=new Map,r=0,o=!1,s=Number.NEGATIVE_INFINITY,a=null;function c(){let p=t();p-s<LL||(s=p,e.onDeliveryStalled?.())}let l=mse({...e,onDeliveryStalled:c,onRefusedEvent:p=>{e.spool.defer(p,t(),t()+LL);let m=e.spool.summary().oldest;m!==null&&t()-m>=LL&&c();for(let[f,v]of n)v.threadId===p.threadId&&(r-=v.bytes,n.delete(f));d()},postEvents:async p=>{let m=await e.postEvents(p);e.spool.acknowledge(p);for(let f of p){if(f.deliveryId===void 0)throw new Error("Saved event has no delivery ID");r-=n.get(f.deliveryId)?.bytes??0,n.delete(f.deliveryId)}return d(),m}});function u(p){if(a!==null&&clearTimeout(a),a=null,o)return;let m=e.spool.deferrals().next;if(m===null||m<=p)return;let f=Math.max(0,m-t());a=setTimeout(()=>{a=null,d(),l.flush().catch(v=>{e.logger.error({error:String(v)},"Retrying saved station updates failed.")})},f)}function d(){if(o||n.size>=fse||r>=hse)return;let p=t(),m=e.spool.take(new Set(n.keys()),fse-n.size,hse-r,p);for(let{deliveryId:f,envelope:v}of m){let b=TZe.byteLength(JSON.stringify(v));n.set(f,{bytes:b,threadId:v.threadId}),r+=b,l.emit(v)}u(p)}return d(),{emit(p){if(o){l.emit(p);return}e.spool.append(p,t()),d()},async flush(){d(),await l.flush()},deliveryHealth(){let p=l.deliveryHealth(),m=e.spool.summary(),f=e.spool.deferrals();return{...p,pendingEvents:m.count,backlogSince:m.oldest,failure:f.count>0?"refused":p.failure,lastFailureAt:f.oldest??p.lastFailureAt,stalled:m.count>0&&(p.stalled||f.count>0)}},deliveryReport(){return{...l.deliveryReport(),oldestPendingAt:e.spool.summary().oldest}},listUndeliveredThreadIds:()=>e.spool.threadIds(),async dispose(){if(!o){o=!0,a!==null&&clearTimeout(a),a=null;try{await l.dispose()}finally{e.spool.close()}}}}}var fse,hse,LL,vse=g(()=>{"use strict";NL();fse=2*OL,hse=2*ML,LL=3e4});import{randomUUID as RZe,createHash as IZe}from"node:crypto";import{chmodSync as yse,mkdirSync as _Ze}from"node:fs";import{join as bse}from"node:path";import{DatabaseSync as kZe}from"node:sqlite";function Sse(e,t){let n=bse(e,"event-delivery");_Ze(n,{recursive:!0,mode:448}),yse(n,448);let r=IZe("sha256").update(t).digest("hex"),o=bse(n,`${r}.sqlite`),s=new kZe(o);yse(o,384),s.exec(`
213
213
  PRAGMA foreign_keys = ON;
214
214
  PRAGMA journal_mode = WAL;
215
215
  PRAGMA synchronous = FULL;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halcyonlabs/app",
3
- "version": "0.47.0-halcyon.409",
3
+ "version": "0.47.0-halcyon.411",
4
4
  "description": "bb app launcher for npx",
5
5
  "keywords": [
6
6
  "bb",
@@ -105,7 +105,7 @@
105
105
  "node": "^22.19.0 || ^24.0.0 || ^26.0.0"
106
106
  },
107
107
  "moonletRelease": {
108
- "summary": "fix(ci): bound test workers and wait for gate readiness (#430)"
108
+ "summary": "fix(orbit): preserve resumable build output at admission (#431)"
109
109
  },
110
110
  "license": "SEE LICENSE IN LICENSE"
111
111
  }
@@ -365,8 +365,6 @@ class Workspaces:
365
365
  settings = self.require_admission(records)
366
366
  need = self.start_space(records, settings)
367
367
  if free is None:
368
- if work_free(self) < need:
369
- self.reclaim_parked(need + settings['disk_start_headroom_bytes'], records)
370
368
  free = work_free(self)
371
369
  inodes = work_inodes(self)
372
370
  if workspace:
@@ -765,13 +763,9 @@ class Workspaces:
765
763
  need = self.start_space(records, settings, keep=job_id)
766
764
  free, inodes, low = work_reading(self)
767
765
  low = low or free < need
768
- if low:
769
- self.reclaim_parked(need, records, keep=job_id)
770
- free, inodes, low = work_reading(self)
771
- low = low or free < need
772
766
  if low:
773
767
  raise CapacityFull(f'Station disk has {gigabytes(free)} GB free space and {inodes} free file entries; '
774
- 'a waiting task needs the disk pressure to clear.')
768
+ 'a waiting task needs the disk pressure to clear. Resumable work was kept; archive handled work to free space.')
775
769
  if has_workspace(manifest):
776
770
  self.require_result_space(sum(self.result_reservation(r) for r in self.records()))
777
771
  return self.save_transition(manifest, 'running')
@@ -974,35 +968,6 @@ class Workspaces:
974
968
  os.close(directory)
975
969
 
976
970
 
977
- def reclaim_parked(self, target, records, keep=None):
978
- """Clear rebuildable caches from parked jobs, oldest parked first, until target bytes are free.
979
-
980
- The supervisor knows only the caches it creates for every job; anything else
981
- is reclaimed only when the job listed it in .orbit-rebuildable. This runs
982
- inside admission so a full disk never waits on a cleanup job that needs a slot.
983
- """
984
- parked = [r for r in records if r['state'] == 'parked' and has_workspace(r) and r['id'] != keep]
985
- parked.sort(key=lambda r: os.stat(r['id'] + '.json', dir_fd=self.state, follow_symlinks=False).st_mtime)
986
- reclaimed = []
987
- for record in parked:
988
- before = work_free(self)
989
- if before >= target:
990
- break
991
- try:
992
- root = self.open_workspace(record['id'])
993
- except (OSError, ValueError):
994
- continue
995
- try:
996
- reclaim_workspace(root, record['outputs'])
997
- except (OSError, ValueError) as error:
998
- print(f"Reclaiming parked job {record['id']} stopped early: {error}", file=sys.stderr)
999
- finally:
1000
- os.close(root)
1001
- freed = max(0, work_free(self) - before)
1002
- reclaimed.append((record['id'], freed))
1003
- print(f"Reclaimed {gigabytes(freed)} GB of rebuildable caches from parked job {record['id']}.", file=sys.stderr)
1004
- return reclaimed
1005
-
1006
971
  def destroy(self, job_id):
1007
972
  manifest = self.read(job_id)
1008
973
  if manifest['state'] != 'destroying':
@@ -1,12 +1,12 @@
1
1
  {
2
- "commit": "9d47d51e14c6341bc585d0fe906241bc710d3dde",
2
+ "commit": "fbe1b23b9fd40232e49f7a51ce5adb817cb77e20",
3
3
  "file": "orbit-deploy",
4
4
  "platform": "linux-x64",
5
5
  "provenance": {
6
- "artifactId": 14310379858,
7
- "artifactName": "linux-bundle-9d47d51e14c6341bc585d0fe906241bc710d3dde",
6
+ "artifactId": 14356405884,
7
+ "artifactName": "linux-bundle-fbe1b23b9fd40232e49f7a51ce5adb817cb77e20",
8
8
  "repository": "matt0x6F/personalassistant",
9
- "runId": 44042369149,
9
+ "runId": 44139881435,
10
10
  "workflow": ".github/workflows/moonlet-linux-bundle.yml"
11
11
  },
12
12
  "schema": 1,
@@ -1 +1 @@
1
- 9d47d51e14c6341bc585d0fe906241bc710d3dde
1
+ fbe1b23b9fd40232e49f7a51ce5adb817cb77e20