hinacode 0.1.0-alpha.12 → 0.1.0-alpha.13

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.
@@ -2495,7 +2495,7 @@ const CurrentLogLevel$1 = /* @__PURE__ */ Reference("effect/References/CurrentLo
2495
2495
  fiberCached: true,
2496
2496
  defaultValue: () => "Info"
2497
2497
  });
2498
- const MinimumLogLevel = /* @__PURE__ */ Reference("effect/References/MinimumLogLevel", {
2498
+ const MinimumLogLevel$1 = /* @__PURE__ */ Reference("effect/References/MinimumLogLevel", {
2499
2499
  fiberCached: true,
2500
2500
  defaultValue: () => "Info"
2501
2501
  });
@@ -3001,7 +3001,7 @@ const makeFiberContextCache = (context2) => {
3001
3001
  tracerEnabled: get$6(context2, TracerEnabled),
3002
3002
  span: getOrUndefinedUnsafe(context2, ParentSpanKey),
3003
3003
  logLevel: get$6(context2, CurrentLogLevel$1),
3004
- minimumLogLevel: get$6(context2, MinimumLogLevel),
3004
+ minimumLogLevel: get$6(context2, MinimumLogLevel$1),
3005
3005
  stackFrame: get$6(context2, CurrentStackFrame),
3006
3006
  runtimeMetrics: getOrUndefinedUnsafe(context2, FiberRuntimeMetricsKey),
3007
3007
  maxOpsBeforeYield: get$6(context2, MaxOpsBeforeYield),
@@ -3418,8 +3418,48 @@ const tapEffectCont = function(value2) {
3418
3418
  };
3419
3419
  const asSome$1 = (self) => map$5(self, some);
3420
3420
  const andThen$1 = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, isEffect$1(f) ? returnPayload : andThenCont, f));
3421
- const tap$2 = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, isEffect$1(f) ? tapEffectCont : tapCont, f));
3421
+ const tap$3 = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, isEffect$1(f) ? tapEffectCont : tapCont, f));
3422
3422
  const asVoid$1 = (self) => new ContImpl(self, returnPayload, exitVoid);
3423
+ const raceAll = (all2, options) => withFiber$1((parent) => {
3424
+ const fibers = /* @__PURE__ */ new Set();
3425
+ onExitUnsafe(parent, () => fibers.size === 0 ? void 0 : fiberInterruptAll(fibers));
3426
+ return callback$2((resume) => {
3427
+ const effects = fromIterable$3(all2);
3428
+ const len = effects.length;
3429
+ let doneCount = 0;
3430
+ let done2 = false;
3431
+ const failures = [];
3432
+ const onExit2 = (exit2, fiber, i) => {
3433
+ doneCount++;
3434
+ if (exit2._tag === "Failure") {
3435
+ failures.push(...exit2.cause.reasons);
3436
+ if (doneCount >= len) {
3437
+ resume(failCause$6(causeFromReasons(failures)));
3438
+ }
3439
+ return;
3440
+ }
3441
+ const isWinner = !done2;
3442
+ done2 = true;
3443
+ resume(exit2);
3444
+ if (isWinner && options?.onWinner) {
3445
+ options.onWinner({
3446
+ fiber,
3447
+ index: i,
3448
+ parentFiber: parent
3449
+ });
3450
+ }
3451
+ };
3452
+ for (let i = 0; i < len; i++) {
3453
+ const fiber = forkUnsafe$1(parent, effects[i], true, true, false);
3454
+ fibers.add(fiber);
3455
+ fiber.addObserver((exit2) => {
3456
+ fibers.delete(fiber);
3457
+ onExit2(exit2, fiber, i);
3458
+ });
3459
+ if (done2) break;
3460
+ }
3461
+ });
3462
+ });
3423
3463
  const raceAllFirst = (all2, options) => withFiber$1((parent) => {
3424
3464
  const fibers = /* @__PURE__ */ new Set();
3425
3465
  onExitUnsafe(parent, () => fibers.size === 0 ? void 0 : fiberInterruptAll(fibers));
@@ -3447,6 +3487,7 @@ const raceAllFirst = (all2, options) => withFiber$1((parent) => {
3447
3487
  }
3448
3488
  });
3449
3489
  });
3490
+ const race$1 = /* @__PURE__ */ dual((args2) => isEffect$1(args2[1]), (self, that, options) => raceAll([self, that], options));
3450
3491
  const raceFirst$1 = /* @__PURE__ */ dual((args2) => isEffect$1(args2[1]), (self, that, options) => raceAllFirst([self, that], options));
3451
3492
  const flatMap$3 = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, andThenCont, f));
3452
3493
  const matchCauseEffectEager$1 = /* @__PURE__ */ dual(2, (self, options) => {
@@ -3847,7 +3888,7 @@ const scopedWith$1 = (f) => suspend$3(() => {
3847
3888
  const scope2 = scopeMakeUnsafe();
3848
3889
  return onExit$2(f(scope2), (exit2) => suspend$3(() => scopeCloseUnsafe(scope2, exit2) ?? void_$3));
3849
3890
  });
3850
- const acquireRelease$1 = (acquire, release2, options) => contextWith$1((context2) => uninterruptibleMask$1((restore) => flatMap$3(scope$1, (scope2) => tap$2(options?.interruptible ? restore(acquire) : acquire, (a) => scopeAddFinalizerExit(scope2, (exit2) => provideContext$3(release2(a, exit2), context2))))));
3891
+ const acquireRelease$1 = (acquire, release2, options) => contextWith$1((context2) => uninterruptibleMask$1((restore) => flatMap$3(scope$1, (scope2) => tap$3(options?.interruptible ? restore(acquire) : acquire, (a) => scopeAddFinalizerExit(scope2, (exit2) => provideContext$3(release2(a, exit2), context2))))));
3851
3892
  const addFinalizer$2 = (finalizer) => flatMap$3(scope$1, (scope2) => contextWith$1((context2) => scopeAddFinalizerExit(scope2, (exit2) => provideContext$3(finalizer(exit2), context2))));
3852
3893
  const OnExitImpl = /* @__PURE__ */ (function() {
3853
3894
  const Proto3 = /* @__PURE__ */ makePrimitiveProto({
@@ -4914,6 +4955,7 @@ const into = /* @__PURE__ */ dual(2, (self, deferred) => uninterruptibleMask$1((
4914
4955
  const CurrentLogAnnotations = CurrentLogAnnotations$1;
4915
4956
  const CurrentLogLevel = CurrentLogLevel$1;
4916
4957
  const CurrentLogSpans = CurrentLogSpans$1;
4958
+ const MinimumLogLevel = MinimumLogLevel$1;
4917
4959
  const TracerTimingEnabled = TracerTimingEnabled$1;
4918
4960
  const Scope = scopeTag;
4919
4961
  const make$1t = scopeMake;
@@ -5299,7 +5341,7 @@ const provide$2 = /* @__PURE__ */ dual((args2) => isEffect$1(args2[0]), (self, s
5299
5341
  const findErrorOnly = (cause) => cause.reasons.every(isFailReason$1) ? findError$1(cause) : fail$7(cause);
5300
5342
  const repeatOrElse = /* @__PURE__ */ dual(3, (self, schedule2, orElse) => flatMap$3(toStepWithMetadata(schedule2), (step) => {
5301
5343
  let meta = CurrentMetadata.defaultValue();
5302
- return catchCauseFilter$1(catchDone(forever$2(tap$2(flatMap$3(suspend$3(() => provideService$3(self, CurrentMetadata, meta)), step), (meta_) => sync$1(() => {
5344
+ return catchCauseFilter$1(catchDone(forever$2(tap$3(flatMap$3(suspend$3(() => provideService$3(self, CurrentMetadata, meta)), step), (meta_) => sync$1(() => {
5303
5345
  meta = meta_;
5304
5346
  })), {
5305
5347
  disableYield: true
@@ -5394,7 +5436,7 @@ const fromOption = fromOption$1;
5394
5436
  const flatMap$1 = flatMap$3;
5395
5437
  const flatten$1 = flatten$2;
5396
5438
  const andThen = andThen$1;
5397
- const tap$1 = tap$2;
5439
+ const tap$2 = tap$3;
5398
5440
  const result$1 = result$2;
5399
5441
  const option = option$1;
5400
5442
  const exit = exit$1;
@@ -5422,6 +5464,7 @@ const timeoutOption = timeoutOption$1;
5422
5464
  const timeoutOrElse = timeoutOrElse$1;
5423
5465
  const delay = delay$1;
5424
5466
  const sleep = sleep$1;
5467
+ const race = race$1;
5425
5468
  const raceFirst = raceFirst$1;
5426
5469
  const filterOrFail = filterOrFail$1;
5427
5470
  const when$2 = when$3;
@@ -11947,7 +11990,7 @@ const unsubscribe = (self) => uninterruptible(withFiber((state) => {
11947
11990
  return forEach$1(takeAll$2(self.pollers), (d) => interruptWith(d, state.id), {
11948
11991
  discard: true,
11949
11992
  concurrency: "unbounded"
11950
- }).pipe(tap$1(() => sync(() => {
11993
+ }).pipe(tap$2(() => sync(() => {
11951
11994
  self.subscribers.delete(self.subscription);
11952
11995
  self.subscription.unsubscribe();
11953
11996
  self.replayWindow.close();
@@ -12805,7 +12848,7 @@ const DefaultChunkSize = 4096;
12805
12848
  const asyncQueue = (scope2, f, options) => make$1d({
12806
12849
  capacity: options?.bufferSize,
12807
12850
  strategy: options?.strategy
12808
- }).pipe(tap$1((queue) => addFinalizer$1(scope2, shutdown(queue))), tap$1((queue) => provide$4(f(queue), scope2).pipe(catchCause$1((cause) => failCause$2(queue, cause)), forkIn(scope2))));
12851
+ }).pipe(tap$2((queue) => addFinalizer$1(scope2, shutdown(queue))), tap$2((queue) => provide$4(f(queue), scope2).pipe(catchCause$1((cause) => failCause$2(queue, cause)), forkIn(scope2))));
12809
12852
  const callbackArray = (f, options) => fromTransform$1((_, scope2) => map$3(asyncQueue(scope2, f, options), takeAll));
12810
12853
  const suspend$1 = (evaluate2) => fromTransform$1((upstream, scope2) => suspend$2(() => toTransform(evaluate2())(upstream, scope2)));
12811
12854
  const fromIterator = (iterator) => fromPull$1(sync(() => {
@@ -13030,7 +13073,7 @@ const mergeAll = /* @__PURE__ */ dual(2, (channels, {
13030
13073
  if (fibers.size === 0) yield* doneLatch.open;
13031
13074
  yield* interrupt(fiber2);
13032
13075
  }
13033
- const fiber = yield* childPull.pipe(tap$1(() => yieldNow), flatMap$1((value2) => offer(queue, value2)), forever({
13076
+ const fiber = yield* childPull.pipe(tap$2(() => yieldNow), flatMap$1((value2) => offer(queue, value2)), forever({
13034
13077
  disableYield: true
13035
13078
  }), onError(fnUntraced(function* (cause) {
13036
13079
  const exit$12 = doneExitFromCause(cause);
@@ -13349,7 +13392,7 @@ const make$1b = (options) => withFiber((fiber) => {
13349
13392
  self.state = {
13350
13393
  _tag: "Closed"
13351
13394
  };
13352
- return forEach$1(map2, ([, entry]) => exit(closeEntry(entry))).pipe(tap$1(() => sync(() => {
13395
+ return forEach$1(map2, ([, entry]) => exit(closeEntry(entry))).pipe(tap$2(() => sync(() => {
13353
13396
  clear$3(map2);
13354
13397
  })));
13355
13398
  }), self);
@@ -13604,6 +13647,7 @@ const map = /* @__PURE__ */ dual(2, (self, f) => suspend(() => {
13604
13647
  return fromChannel(map$1(self.channel, map$6((o) => f(o, i++))));
13605
13648
  }));
13606
13649
  const mapEffect = /* @__PURE__ */ dual((args2) => isStream(args2[0]), (self, f, options) => self.channel.pipe(flattenArray, mapEffect$1(f, options), map$1(of), fromChannel));
13650
+ const tap$1 = /* @__PURE__ */ dual((args2) => isStream(args2[0]), (self, f, options) => mapEffect(self, (a) => as(f(a), a), options));
13607
13651
  const concat = /* @__PURE__ */ dual(2, (self, that) => {
13608
13652
  const stream2 = fromChannel(flatten(fromIterator(() => concatChannels(self, that))));
13609
13653
  concatParts.set(stream2, [self, that]);
@@ -14151,7 +14195,7 @@ const make$14 = (layer2, options) => {
14151
14195
  let buildFiber;
14152
14196
  const contextEffect = withFiber((fiber) => {
14153
14197
  if (!buildFiber) {
14154
- buildFiber = runFork(tap$1(buildWithMemoMap(layer2, memoMap, layerScope), (context2) => sync(() => {
14198
+ buildFiber = runFork(tap$2(buildWithMemoMap(layer2, memoMap, layerScope), (context2) => sync(() => {
14155
14199
  self.cachedContext = context2;
14156
14200
  })), {
14157
14201
  ...defaultRunOptions,
@@ -14378,7 +14422,7 @@ const make$13 = /* @__PURE__ */ sync(() => {
14378
14422
  }
14379
14423
  return void_$1;
14380
14424
  });
14381
- const mutation = (keys2, effect2) => tap$1(effect2, invalidate(keys2));
14425
+ const mutation = (keys2, effect2) => tap$2(effect2, invalidate(keys2));
14382
14426
  const registerUnsafe = (keys2, handler) => {
14383
14427
  const resolvedKeys = [];
14384
14428
  keysToHashes(keys2, (hash2) => {
@@ -15800,7 +15844,8 @@ const Compaction = Union2([
15800
15844
  Struct({
15801
15845
  status: Literal2("done"),
15802
15846
  trigger: Literals(["manual", "auto"]),
15803
- preTokens: Number$1,
15847
+ /** Null when the agent does not report the sizes, as Codex does not. */
15848
+ preTokens: NullOr(Number$1),
15804
15849
  postTokens: NullOr(Number$1)
15805
15850
  }),
15806
15851
  /** `message` is null when the turn ended before the compaction reported back. */
@@ -15916,6 +15961,8 @@ const Worktree = Struct({
15916
15961
  setupLog: String$1,
15917
15962
  createdAt: Timestamp
15918
15963
  });
15964
+ const CheckoutState = Literals(["clean", "dirty", "missing"]);
15965
+ const WorktreeCheckout = Struct({ id: String$1, state: CheckoutState });
15919
15966
  const ChangedFileStatus = Literals(["added", "modified", "deleted", "untracked", "conflict"]);
15920
15967
  const Changes = Struct({
15921
15968
  files: ArraySchema(Struct({ path: String$1, status: ChangedFileStatus })),
@@ -16022,6 +16069,12 @@ const OpenPullRequest = Struct({
16022
16069
  author: String$1,
16023
16070
  isDraft: Boolean$1
16024
16071
  });
16072
+ const PullRequestMatch = Struct({
16073
+ number: Int,
16074
+ title: String$1,
16075
+ status: PullRequestStatus,
16076
+ author: String$1
16077
+ });
16025
16078
  const ThreadStatus = Literals(["idle", "running", "awaiting_approval", "limited", "archived"]);
16026
16079
  const isThreadBusy = (status) => status === "running" || status === "awaiting_approval";
16027
16080
  const AccessMode = Literals(["supervised", "auto", "full"]);
@@ -16211,6 +16264,8 @@ const defaultClientSettings = {
16211
16264
  appearance: { theme: "system", fontSize: 16, uiFont: null, monoFont: null, contrast: 0 },
16212
16265
  notifications: { completed: true, needsInput: true, failed: true, sound: true }
16213
16266
  };
16267
+ const AUTO_COMPACT_RANGE = { minimum: 1e5, maximum: 1e6 };
16268
+ const AutoCompactTokens = Int.check(isBetween(AUTO_COMPACT_RANGE));
16214
16269
  const Settings$1 = Struct({
16215
16270
  defaultModel: Struct({
16216
16271
  claude: NullOr(String$1),
@@ -16235,6 +16290,15 @@ const Settings$1 = Struct({
16235
16290
  codex: NullOr(AgentProfileName),
16236
16291
  muse: NullOr(AgentProfileName)
16237
16292
  }).pipe(withDecodingDefaultKey(succeed$3({ claude: null, codex: null, muse: null }))),
16293
+ /**
16294
+ * How full each agent's context window gets, in tokens, before it compacts the conversation. Null keeps the
16295
+ * agent's own threshold. The range is Claude Code's, which ignores anything outside it.
16296
+ */
16297
+ autoCompactTokens: Struct({
16298
+ claude: NullOr(AutoCompactTokens),
16299
+ codex: NullOr(AutoCompactTokens),
16300
+ muse: NullOr(AutoCompactTokens)
16301
+ }).pipe(withDecodingDefaultKey(succeed$3({ claude: null, codex: null, muse: null }))),
16238
16302
  /** Where the automation webhook listener binds. 0.0.0.0 exposes it on the LAN and Tailscale. */
16239
16303
  automations: Struct({
16240
16304
  bindHost: String$1,
@@ -16260,6 +16324,7 @@ const defaultSettings = {
16260
16324
  modelPresets: { claude: [], codex: [], muse: [] },
16261
16325
  defaultAccount: { claude: null, codex: null, muse: null },
16262
16326
  defaultAccountName: { claude: null, codex: null, muse: null },
16327
+ autoCompactTokens: { claude: null, codex: null, muse: null },
16263
16328
  automations: { bindHost: "127.0.0.1", port: 48080 },
16264
16329
  remote: { enabled: false, bindHost: "0.0.0.0", port: 48081 },
16265
16330
  textGenerationModel: "claude-sonnet-5-5",
@@ -16278,7 +16343,12 @@ const Environment = Struct({
16278
16343
  const EnvironmentStatus = Literals(["connecting", "connected", "offline", "unauthorized", "incompatible"]);
16279
16344
  const Environments$1 = Struct({
16280
16345
  clouds: ArraySchema(
16281
- Struct({ ...Environment.fields, status: EnvironmentStatus, lastSeenAt: NullOr(Timestamp) })
16346
+ Struct({
16347
+ ...Environment.fields,
16348
+ status: EnvironmentStatus,
16349
+ lastSeenAt: NullOr(Timestamp),
16350
+ protocol: optional$6(Int)
16351
+ })
16282
16352
  )
16283
16353
  });
16284
16354
  const VmControl = Literals(["agent", "user"]);
@@ -16573,6 +16643,8 @@ const RpcMethods = {
16573
16643
  Struct({ id: String$1, deleteBranch: Literals(["keep", "ifMerged", "force"]) }),
16574
16644
  Worktree
16575
16645
  ),
16646
+ /** The checkout state of every live worktree. A checkout git cannot read is left out. */
16647
+ "worktrees.checkouts": rpc(Void2, ArraySchema(WorktreeCheckout)),
16576
16648
  "worktrees.setupLog": rpc(Struct({ id: String$1 }), String$1),
16577
16649
  /** Kills a setup script still running; the worktree ends `failed`. */
16578
16650
  "worktrees.stopSetup": rpc(Struct({ id: String$1 }), Void2),
@@ -16591,6 +16663,14 @@ const RpcMethods = {
16591
16663
  "projects.branches": rpc(Struct({ id: String$1 }), ArraySchema(String$1)),
16592
16664
  /** Open pull requests of the project's repository, newest first. Empty when `gh` is missing or signed out. */
16593
16665
  "projects.pullRequests": rpc(Struct({ id: String$1 }), ArraySchema(OpenPullRequest)),
16666
+ /**
16667
+ * Pull requests of the project's GitHub repository in any state, best match first, or the newest for an empty query.
16668
+ * Empty when the project is not on GitHub or `gh` is missing or signed out.
16669
+ */
16670
+ "projects.searchPullRequests": rpc(
16671
+ Struct({ id: String$1, query: String$1 }),
16672
+ ArraySchema(PullRequestMatch)
16673
+ ),
16594
16674
  /** Fetches `origin`, so the branch picker and a new worktree's default base are current. */
16595
16675
  "projects.fetch": rpc(Struct({ id: String$1 }), Void2),
16596
16676
  /** The project's own favicon as a data URL, or null when it has none. */
@@ -16634,6 +16714,8 @@ const RpcMethods = {
16634
16714
  "environments.add": rpc(Struct({ name: String$1, pairingUrl: String$1 }), Environment),
16635
16715
  /** Forgets the cloud and its token. Its projects and threads stay on the cloud. */
16636
16716
  "environments.remove": rpc(Struct({ id: String$1 }), Void2),
16717
+ /** Dials an offline or incompatible cloud now instead of after its backoff. Calls waiting for it keep waiting. */
16718
+ "environments.reconnect": rpc(Struct({ id: String$1 }), Void2),
16637
16719
  "models.list": rpc(Struct({ provider: ProviderId }), ArraySchema(ModelInfo)),
16638
16720
  /** Who the account is signed in as. `accountId` null is the CLI's own login. */
16639
16721
  "agents.account": rpc(Struct({ provider: ProviderId, accountId: NullOr(String$1) }), AgentAccount),
@@ -16930,6 +17012,7 @@ const methodKind = {
16930
17012
  "worktrees.list": "read",
16931
17013
  "worktrees.create": "mutation",
16932
17014
  "worktrees.remove": "mutation",
17015
+ "worktrees.checkouts": "read",
16933
17016
  "worktrees.setupLog": "read",
16934
17017
  "worktrees.stopSetup": "mutation",
16935
17018
  "worktrees.pullRequest": "read",
@@ -16940,6 +17023,7 @@ const methodKind = {
16940
17023
  "projects.defaultBranch": "read",
16941
17024
  "projects.branches": "read",
16942
17025
  "projects.pullRequests": "read",
17026
+ "projects.searchPullRequests": "read",
16943
17027
  "projects.fetch": "mutation",
16944
17028
  "projects.icon": "read",
16945
17029
  "git.log": "read",
@@ -16956,6 +17040,7 @@ const methodKind = {
16956
17040
  "environments.list": "read",
16957
17041
  "environments.add": "mutation",
16958
17042
  "environments.remove": "mutation",
17043
+ "environments.reconnect": "mutation",
16959
17044
  "models.list": "read",
16960
17045
  "agents.account": "read",
16961
17046
  "agents.updates": "read",
@@ -17067,6 +17152,7 @@ const desktopOnlyMethods = /* @__PURE__ */ new Set([
17067
17152
  "environments.list",
17068
17153
  "environments.add",
17069
17154
  "environments.remove",
17155
+ "environments.reconnect",
17070
17156
  "agents.update"
17071
17157
  ]);
17072
17158
  const desktopOnlyPushes = /* @__PURE__ */ new Set([
@@ -17175,7 +17261,8 @@ const pairingUrl = ({ hosts, port, token }) => {
17175
17261
  const remoteWebSocketUrl = ({ host, port }) => `ws://${host.includes(":") ? `[${host}]` : host}:${port}${REMOTE_PATH}`;
17176
17262
  const isAuthorityOnlyHost = (host) => host !== "" && !/[\s/?#@[\]\\]/.test(host) && URL.parse(remoteWebSocketUrl({ host, port: 1 })) !== null;
17177
17263
  const parsePairingUrl = (text2) => {
17178
- const url = URL.parse(text2.trim());
17264
+ const word = text2.split(/\s+/).find((part) => /^hinacode:\/\/connect\?/i.test(part));
17265
+ const url = word === void 0 ? null : URL.parse(word);
17179
17266
  if (!url || url.protocol !== "hinacode:" || url.host !== "connect") return null;
17180
17267
  const hosts = url.searchParams.getAll("host");
17181
17268
  const port = Number(url.searchParams.get("port"));
@@ -17184,6 +17271,7 @@ const parsePairingUrl = (text2) => {
17184
17271
  if (!token || !Number.isInteger(port) || port < 1 || port > 65535) return null;
17185
17272
  return { hosts, port, token };
17186
17273
  };
17274
+ const isPortInUse = (listenError) => listenError.includes("EADDRINUSE");
17187
17275
  const ExitCode = /* @__PURE__ */ nominal();
17188
17276
  const ProcessId = /* @__PURE__ */ nominal();
17189
17277
  const HandleTypeId = "~effect/process/ChildProcessSpawner/ChildProcessHandle";
@@ -20170,6 +20258,7 @@ const layer$B = effect(
20170
20258
  ...effort === null ? {} : { effort },
20171
20259
  settings: {
20172
20260
  fastMode: input.fastMode,
20261
+ ...input.autoCompactTokens !== null && { autoCompactWindow: input.autoCompactTokens },
20173
20262
  ...input.effort === ULTRACODE && { ultracode: true },
20174
20263
  ...hidden !== null && { skillOverrides: hidden }
20175
20264
  },
@@ -20208,6 +20297,7 @@ const layer$B = effect(
20208
20297
  effort: input.effort,
20209
20298
  fastMode: input.fastMode,
20210
20299
  userSkills: input.userSkills,
20300
+ autoCompactTokens: input.autoCompactTokens,
20211
20301
  permissionMode: mode,
20212
20302
  prompts,
20213
20303
  abort,
@@ -20240,7 +20330,8 @@ const layer$B = effect(
20240
20330
  const acquireSession = (input, mode) => gen(function* () {
20241
20331
  const existing = sessions.get(input.threadId);
20242
20332
  if (existing !== void 0) {
20243
- if (sameContext(existing, input) && existing.userSkills === input.userSkills) return claim(existing);
20333
+ if (sameContext(existing, input) && existing.userSkills === input.userSkills && existing.autoCompactTokens === input.autoCompactTokens)
20334
+ return claim(existing);
20244
20335
  yield* closeSession(existing);
20245
20336
  }
20246
20337
  return yield* startSession(input, mode);
@@ -20485,6 +20576,7 @@ const usageLimitAssistant = {
20485
20576
  }
20486
20577
  };
20487
20578
  const markdownFixture = '# Heading 1 with `code`\n\nA paragraph right under a heading. It runs long enough to wrap, so the line height and the measure of the transcript column are visible. **Bold**, _italic_, **_bold italic_**, ~~strikethrough~~, `inline code`, and a [link to the docs](https://github.com/hinadev-ai/hinacode). A bare URL autolinks: https://github.com/hinadev-ai/hinacode. A pull request reference: #1.\n\nA second paragraph, to show the gap between paragraphs.\nThis line follows a soft break, so it joins the paragraph above.\\\nThis line follows a hard break, so it starts on its own line.\n\n## Heading 2\n\n### Heading 3\n\n#### Heading 4\n\n##### Heading 5\n\n###### Heading 6\n\n---\n\n## Links\n\nEach web link should start with an icon. Pull requests get the GitHub mark and a hover card, other sites their favicon, and a site without one the globe.\n\n- A bare pull request URL, shortened to `owner/repo#n`: https://github.com/react/react/pull/31139\n- A pull request with its own text: [the React Compiler ref fix](https://github.com/react/react/pull/34000)\n- A pull request in another repository: https://github.com/vercel/next.js/pull/71000\n- A GitHub issue, which is not a pull request: https://github.com/react/react/issues/11347\n- A repository: https://github.com/react/react\n- Documentation sites: [React docs](https://react.dev/reference/react/useMemo), [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap) and https://tailwindcss.com/docs/overflow-wrap\n- A site with no favicon: https://example.com\n- A link inside **bold text: [react.dev](https://react.dev)** and one inside a sentence that wraps across lines so the icon stays with its text: [the Effect documentation on services and layers](https://effect.website/docs/requirements-management/services/)\n- Not web links, so no icon: [an email](mailto:dev@example.com) and [a relative path](./README.md)\n\n## Lists\n\n- An unordered item\n- An item with **bold** and `code`\n - A nested item\n - A third level\n- An item long enough to wrap onto a second line, to check that the wrapped line lines up with the text and not with the bullet.\n\n1. First\n2. Second\n 1. Nested ordered\n 2. Another\n3. Third\n\nAn ordered list that starts at five:\n\n5. Five\n6. Six\n\nA task list:\n\n- [x] A finished task\n- [ ] An open task\n - [ ] A nested task\n\nA loose list:\n\n- A loose list item, with a blank line after it.\n\n- The next loose item, with a paragraph inside.\n\n A second paragraph in the same item.\n\n## Quotes\n\n> A quote with a single paragraph, long enough to wrap, so the bar runs the height of both lines and stays inside the quote.\n\n> A quote with a list:\n>\n> - one\n> - two\n>\n> > A nested quote.\n\n## Code\n\nInline `const answer = 42` sits on the baseline of the text around it.\n\n```ts\nimport { Effect } from "effect"\n\n/** A long line to check horizontal scrolling inside the block, instead of the whole transcript widening past the column. */\nexport const greet = (name: string) => Effect.succeed(`Hello, ${name}`)\n```\n\n```\nA fence without a language.\n```\n\n```sh\npnpm typecheck && pnpm lint && pnpm test\n```\n\n## Table\n\n| Left | Center | Right | Notes |\n| :----------------------------------- | :----: | -----: | ------------------------------------------------------------------------- |\n| `fonts/otf/` | 8 | 1.2 MB | Static weights from Thin to ExtraBold |\n| `fonts/ttf/` | 8 | 1.4 MB | The same weights as TTF |\n| `fonts/variable/PaperMono[wght].ttf` | 1 | 310 KB | One file covering the whole weight range, long enough to wrap in its cell |\n| `fonts/webfonts/` | 9 | 640 KB | WOFF2 versions of all of the above |\n\n## Diagram\n\n```mermaid\nflowchart LR\n Prompt --> Agent --> Worktree --> PR\n```\n\n## Text in other scripts\n\n這是一段繁體中文,用來檢查中英混排時的行高與字距,例如 `pnpm dev` 與 HinaCode 之間的間隔。\n\nこれは日本語の段落です。行の高さと、英数字の HinaCode や `git fetch` との混在を確認します。\n\n## Edge cases\n\nA footnote reference[^1] and an escaped \\*asterisk\\*. Keys render as keys: press <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>. Other raw HTML stays text: <div>, and a tag written in prose like <Suspense> stays visible.\n\nA very long unbroken token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\n[^1]: The footnote text.\n';
20579
+ const mockScenarios = ["usage-limit", "org-spend-limit", "todos", "markdown", "stream"];
20488
20580
  const commands = [
20489
20581
  {
20490
20582
  trigger: "/",
@@ -20505,8 +20597,18 @@ const toolCall = (callId, name, input, output) => [
20505
20597
  { type: "tool_call_started", callId, name, input },
20506
20598
  { type: "tool_call_finished", callId, output, isError: false }
20507
20599
  ];
20600
+ const chunks = (text2, size2) => text2.match(new RegExp(`[\\s\\S]{1,${size2}}`, "g")) ?? [];
20508
20601
  const markdownTurn = () => [
20509
- ...(markdownFixture.match(/[\s\S]{1,400}/g) ?? []).map((text2) => ({ type: "text_delta", text: text2 })),
20602
+ ...chunks(markdownFixture, 400).map((text2) => ({ type: "text_delta", text: text2 })),
20603
+ { type: "turn_completed" }
20604
+ ];
20605
+ const streamTurn = () => [
20606
+ ...chunks(markdownFixture.slice(0, 900), 30).map((text2) => ({ type: "reasoning_delta", text: text2 })),
20607
+ ...Array.from(
20608
+ { length: 6 },
20609
+ (_, index) => toolCall(`stream-read-${index}`, "Read", { file_path: `src/file-${index}.ts` }, markdownFixture)
20610
+ ).flat(),
20611
+ ...chunks(markdownFixture, 30).map((text2) => ({ type: "text_delta", text: text2 })),
20510
20612
  { type: "turn_completed" }
20511
20613
  ];
20512
20614
  const todoTurn = (first) => first ? [
@@ -20578,6 +20680,8 @@ const usageLimitLayer = (scenario = "usage-limit", resetAfterMs = 6e4) => effect
20578
20680
  listCommands: () => succeed$3(commands),
20579
20681
  runTurn: (input) => suspend(() => {
20580
20682
  if (scenario === "markdown") return fromIterable(markdownTurn());
20683
+ if (scenario === "stream")
20684
+ return fromIterable(streamTurn()).pipe(tap$1(() => sleep("20 millis")));
20581
20685
  if (scenario === "todos") {
20582
20686
  const first = !attempted.has(input.threadId);
20583
20687
  attempted.add(input.threadId);
@@ -21126,6 +21230,7 @@ const make$T = gen(function* () {
21126
21230
  const runs = /* @__PURE__ */ new Map();
21127
21231
  const subagentsByThread = /* @__PURE__ */ new Map();
21128
21232
  const subagentTurns = /* @__PURE__ */ new Map();
21233
+ const loadedCompactLimits = /* @__PURE__ */ new Map();
21129
21234
  const listModels = gen(function* () {
21130
21235
  const client = yield* getClient(null);
21131
21236
  const models = [];
@@ -21216,6 +21321,7 @@ const make$T = gen(function* () {
21216
21321
  config: {
21217
21322
  // Off by default in current Codex; the composer's task list is built from its plan.
21218
21323
  tools: { update_plan: { enabled: true } },
21324
+ ...input.autoCompactTokens !== null && { model_auto_compact_token_limit: input.autoCompactTokens },
21219
21325
  ...hiddenSkills !== null && {
21220
21326
  skills: { config: hiddenSkills.map((skill) => ({ path: skill.path, enabled: false })) }
21221
21327
  },
@@ -21226,11 +21332,17 @@ const make$T = gen(function* () {
21226
21332
  },
21227
21333
  developerInstructions: input.instructions
21228
21334
  };
21335
+ const resumed = input.resumeSessionId;
21336
+ const loadedLimit = resumed === null ? void 0 : loadedCompactLimits.get(resumed);
21337
+ if (resumed !== null && loadedLimit !== void 0 && loadedLimit !== input.autoCompactTokens) {
21338
+ yield* client.request("thread/unsubscribe", { threadId: resumed });
21339
+ }
21229
21340
  const { thread, sandbox } = input.resumeSessionId ? yield* client.request("thread/resume", {
21230
21341
  ...overrides,
21231
21342
  threadId: input.resumeSessionId,
21232
21343
  excludeTurns: true
21233
21344
  }) : yield* client.request("thread/start", overrides);
21345
+ loadedCompactLimits.set(thread.id, input.autoCompactTokens);
21234
21346
  yield* emit({ type: "session_bound", providerSessionId: thread.id });
21235
21347
  const skills = input.prompt.includes("$") ? (yield* listSkills2(input.cwd, input.home)).filter((skill) => input.userSkills || skill.scope !== "user") : [];
21236
21348
  const turnStart = {
@@ -21450,12 +21562,22 @@ const make$T = gen(function* () {
21450
21562
  }
21451
21563
  case "item/started": {
21452
21564
  const params2 = message.params;
21565
+ if (params2.item.type === "contextCompaction") {
21566
+ yield* emit({ type: "compaction_updated", compaction: { status: "running" } });
21567
+ }
21453
21568
  yield* startTool(params2.item);
21454
21569
  yield* emitSubagents(applyParentItem(subagents, params2.item, yield* nowIso));
21455
21570
  return false;
21456
21571
  }
21457
21572
  case "item/completed": {
21458
21573
  const params2 = message.params;
21574
+ if (params2.item.type === "contextCompaction") {
21575
+ yield* emit({
21576
+ type: "compaction_updated",
21577
+ // Codex starts compaction only by itself, and its item carries no token counts.
21578
+ compaction: { status: "done", trigger: "auto", preTokens: null, postTokens: null }
21579
+ });
21580
+ }
21459
21581
  yield* finishTool(params2.item);
21460
21582
  if (params2.item.type === "agentMessage" && params2.item.questions) {
21461
21583
  yield* emit({
@@ -22066,6 +22188,31 @@ const promptParts = (host, sessionId, text2, attachments, instructions) => gen(f
22066
22188
  };
22067
22189
  return [skill, ...images];
22068
22190
  });
22191
+ const trackContext = (sessions, method, params2) => {
22192
+ const session = sessions.get(params2?.sessionId ?? "");
22193
+ if (session === void 0) return;
22194
+ if (method === "session/contextUsage") session.usedTokens = params2.usedTokens;
22195
+ if (params2.item?.kind !== "compaction") return;
22196
+ if (method === "item/started") session.compacting = true;
22197
+ if (method === "item/completed") session.compacting = false;
22198
+ };
22199
+ const decodeContextUsage = decodeUnknownOption(Struct({ usedTokens: Number$1 }));
22200
+ const latestUsedTokens = (host, sessionId) => gen(function* () {
22201
+ let cursor = null;
22202
+ do {
22203
+ const raw2 = yield* host.request("view/page", {
22204
+ sessionId,
22205
+ direction: "backward",
22206
+ limit: 100,
22207
+ ...cursor === null ? {} : { cursor }
22208
+ });
22209
+ const page = yield* decodeUnknownEffect(ViewPage)(raw2);
22210
+ const usage = page.events.findLast((event) => event.method === "session/contextUsage");
22211
+ if (usage !== void 0) return getOrNull(decodeContextUsage(usage.params))?.usedTokens ?? null;
22212
+ cursor = page.nextCursor;
22213
+ } while (cursor !== null);
22214
+ return null;
22215
+ }).pipe(catch_$2(() => succeed$3(null)));
22069
22216
  const interruptTurn = (host, sessionId, turnId) => suspend$2(
22070
22217
  () => host.isAlive() ? host.command("turn/interrupt", { sessionId, turnId }).pipe(mapError(toAgentError)) : void_$1
22071
22218
  );
@@ -22092,11 +22239,16 @@ const make$S = gen(function* () {
22092
22239
  provide$4(scope2),
22093
22240
  onError(() => close(scope2, void_$2))
22094
22241
  );
22242
+ const sessions = /* @__PURE__ */ new Map();
22095
22243
  yield* host.subscribe((message) => {
22096
- if (message.kind !== "notification" || message.method !== "usage/changed") return;
22097
- planUsage = getOrElse(decodePlanUsage(message.params), () => planUsage);
22244
+ if (message.kind !== "notification") return;
22245
+ if (message.method === "usage/changed") {
22246
+ planUsage = getOrElse(decodePlanUsage(message.params), () => planUsage);
22247
+ } else {
22248
+ trackContext(sessions, message.method, message.params);
22249
+ }
22098
22250
  }).pipe(provide$4(scope2));
22099
- current = { host, scope: scope2, sessions: /* @__PURE__ */ new Map() };
22251
+ current = { host, scope: scope2, sessions };
22100
22252
  return current;
22101
22253
  })
22102
22254
  );
@@ -22150,12 +22302,24 @@ const make$S = gen(function* () {
22150
22302
  catch_$2(() => succeed$3(void 0))
22151
22303
  );
22152
22304
  if (resumed !== void 0) {
22153
- sessions.set(known, { model: resumed.modelId, approvalMode: resumed.approvalMode?.mode ?? null, cwd });
22305
+ sessions.set(known, {
22306
+ model: resumed.modelId,
22307
+ approvalMode: resumed.approvalMode?.mode ?? null,
22308
+ cwd,
22309
+ usedTokens: null,
22310
+ compacting: false
22311
+ });
22154
22312
  return known;
22155
22313
  }
22156
22314
  }
22157
22315
  const { session } = yield* host.command("session/start", { workspaceRoot: cwd }).pipe(mapError(toAgentError));
22158
- sessions.set(session.sessionId, { model: session.modelId ?? null, approvalMode: null, cwd });
22316
+ sessions.set(session.sessionId, {
22317
+ model: session.modelId ?? null,
22318
+ approvalMode: null,
22319
+ cwd,
22320
+ usedTokens: null,
22321
+ compacting: false
22322
+ });
22159
22323
  probeSessions.set(cwd, session.sessionId);
22160
22324
  return session.sessionId;
22161
22325
  })
@@ -22187,7 +22351,13 @@ const make$S = gen(function* () {
22187
22351
  approvalMode,
22188
22352
  config
22189
22353
  });
22190
- sessions.set(session.sessionId, { model: input.model, approvalMode, cwd: input.cwd });
22354
+ sessions.set(session.sessionId, {
22355
+ model: input.model,
22356
+ approvalMode,
22357
+ cwd: input.cwd,
22358
+ usedTokens: null,
22359
+ compacting: false
22360
+ });
22191
22361
  threadSessions.set(input.threadId, session.sessionId);
22192
22362
  return session.sessionId;
22193
22363
  }
@@ -22199,7 +22369,14 @@ const make$S = gen(function* () {
22199
22369
  excludeItems: true,
22200
22370
  config
22201
22371
  });
22202
- loaded = { model: session.modelId, approvalMode: session.approvalMode?.mode ?? null, cwd: input.cwd };
22372
+ loaded = {
22373
+ model: session.modelId,
22374
+ approvalMode: session.approvalMode?.mode ?? null,
22375
+ cwd: input.cwd,
22376
+ // An `excludeItems` resume carries no context usage.
22377
+ usedTokens: input.autoCompactTokens === null ? null : yield* latestUsedTokens(host, sessionId),
22378
+ compacting: false
22379
+ };
22203
22380
  sessions.set(sessionId, loaded);
22204
22381
  }
22205
22382
  threadSessions.set(input.threadId, sessionId);
@@ -22230,20 +22407,6 @@ const make$S = gen(function* () {
22230
22407
  const sessionId = yield* openSession(entry, input);
22231
22408
  run2.sessionId = sessionId;
22232
22409
  yield* emit({ type: "session_bound", providerSessionId: sessionId });
22233
- const prompt = yield* promptParts(host, sessionId, input.prompt, input.attachments, input.instructions);
22234
- run2.turnStart = yield* host.command("turn/start", {
22235
- sessionId,
22236
- // Muse shows `displayText`, never the instructions in front of the prompt.
22237
- input: prompt,
22238
- displayText: input.prompt,
22239
- ...input.effort === null ? {} : { reasoningEffort: input.effort }
22240
- }).pipe(
22241
- map$3((ack) => ack.turnId),
22242
- mapError(toAgentError),
22243
- forkIn(providerScope)
22244
- );
22245
- const turnId = yield* join$1(run2.turnStart);
22246
- run2.turnId = turnId;
22247
22410
  const threadGrants = grants.get(input.threadId) ?? /* @__PURE__ */ new Set();
22248
22411
  grants.set(input.threadId, threadGrants);
22249
22412
  const pendingApprovals = /* @__PURE__ */ new Map();
@@ -22253,6 +22416,7 @@ const make$S = gen(function* () {
22253
22416
  const toolOutput = /* @__PURE__ */ new Map();
22254
22417
  const openTools = /* @__PURE__ */ new Set();
22255
22418
  let context2;
22419
+ let compacting = false;
22256
22420
  const decide = (approval, decision) => gen(function* () {
22257
22421
  const stage2 = approval.params.currentRequirementId.sourceIndex;
22258
22422
  if (approval.answered === stage2) return;
@@ -22417,10 +22581,23 @@ const make$S = gen(function* () {
22417
22581
  return finishText(item, "reasoning_delta", (item.summary ?? []).join(SUMMARY_BREAK));
22418
22582
  case "toolCall":
22419
22583
  return finishTool(item);
22584
+ case "compaction":
22585
+ return finishCompaction(item);
22420
22586
  default:
22421
22587
  return void_$1;
22422
22588
  }
22423
22589
  };
22590
+ const finishCompaction = (item) => {
22591
+ const trigger = compacting || item.trigger !== "manual" ? "auto" : "manual";
22592
+ compacting = false;
22593
+ const compaction = item.outcome === "compacted" || item.outcome === "noop" ? {
22594
+ status: "done",
22595
+ trigger,
22596
+ preTokens: item.tokensBefore ?? null,
22597
+ postTokens: item.tokensAfter ?? null
22598
+ } : { status: "failed", message: item.reason ?? null };
22599
+ return emit({ type: "compaction_updated", compaction });
22600
+ };
22424
22601
  const finishTurn = (params2) => gen(function* () {
22425
22602
  for (const callId of openTools) {
22426
22603
  const output = toolOutput.get(callId) ?? `Turn ${params2.terminal}`;
@@ -22469,6 +22646,9 @@ const make$S = gen(function* () {
22469
22646
  case "item/started": {
22470
22647
  const { item } = message.params;
22471
22648
  if (item.kind === "toolCall") yield* startTool(item);
22649
+ if (item.kind === "compaction") {
22650
+ yield* emit({ type: "compaction_updated", compaction: { status: "running" } });
22651
+ }
22472
22652
  return false;
22473
22653
  }
22474
22654
  case "item/delta":
@@ -22487,13 +22667,13 @@ const make$S = gen(function* () {
22487
22667
  yield* resolveQuestion(message.params);
22488
22668
  return false;
22489
22669
  case "session/contextUsage": {
22490
- const { usedTokens, windowTokens } = message.params;
22491
- if (windowTokens !== void 0) context2 = { usedTokens, maxTokens: windowTokens };
22670
+ const { usedTokens: usedTokens2, windowTokens } = message.params;
22671
+ if (windowTokens !== void 0) context2 = { usedTokens: usedTokens2, maxTokens: windowTokens };
22492
22672
  return false;
22493
22673
  }
22494
22674
  case "turn/completed": {
22495
22675
  const params2 = message.params;
22496
- if (params2.turnId !== turnId) return false;
22676
+ if (params2.turnId !== run2.turnId) return false;
22497
22677
  yield* finishTurn(params2);
22498
22678
  return true;
22499
22679
  }
@@ -22501,6 +22681,34 @@ const make$S = gen(function* () {
22501
22681
  return false;
22502
22682
  }
22503
22683
  });
22684
+ const loaded = entry.sessions.get(sessionId);
22685
+ const usedTokens = loaded?.usedTokens ?? null;
22686
+ if (loaded?.compacting) {
22687
+ compacting = true;
22688
+ yield* emit({ type: "compaction_updated", compaction: { status: "running" } });
22689
+ } else if (input.autoCompactTokens !== null && usedTokens !== null && usedTokens >= input.autoCompactTokens) {
22690
+ const ack = yield* host.command("session/compact", { sessionId }).pipe(
22691
+ map$3((result2) => result2.status),
22692
+ catch_$2((error) => logWarning("session/compact failed", error.message).pipe(as(null)))
22693
+ );
22694
+ compacting = ack === "accepted";
22695
+ }
22696
+ if (compacting) {
22697
+ yield* take(inbox).pipe(flatMap$1(handle), repeat({ while: () => compacting }));
22698
+ }
22699
+ const prompt = yield* promptParts(host, sessionId, input.prompt, input.attachments, input.instructions);
22700
+ run2.turnStart = yield* host.command("turn/start", {
22701
+ sessionId,
22702
+ // Muse shows `displayText`, never the instructions in front of the prompt.
22703
+ input: prompt,
22704
+ displayText: input.prompt,
22705
+ ...input.effort === null ? {} : { reasoningEffort: input.effort }
22706
+ }).pipe(
22707
+ map$3((ack) => ack.turnId),
22708
+ mapError(toAgentError),
22709
+ forkIn(providerScope)
22710
+ );
22711
+ run2.turnId = yield* join$1(run2.turnStart);
22504
22712
  while (!(yield* take(inbox).pipe(flatMap$1(handle)))) {
22505
22713
  }
22506
22714
  });
@@ -23048,7 +23256,11 @@ const runMigrations = run({
23048
23256
  "18_thread_user_skills": threadUserSkills,
23049
23257
  "19_project_linear_review": projectLinearReview
23050
23258
  })
23051
- }).pipe(tap$1((ran) => logInfo("migrations ran", ran)));
23259
+ }).pipe(
23260
+ tap$2(
23261
+ (ran) => ran.length === 0 ? void_$1 : logInfo(`migrations ran up to ${ran.at(-1)?.join("_")}`)
23262
+ )
23263
+ );
23052
23264
  const setup = effectDiscard(
23053
23265
  gen(function* () {
23054
23266
  const sql = yield* SqlClient;
@@ -23316,8 +23528,9 @@ const reviewStatus = {
23316
23528
  CHANGES_REQUESTED: "changesRequested",
23317
23529
  REVIEW_REQUIRED: "reviewRequired"
23318
23530
  };
23531
+ const pullRequestStatus = (state, isDraft) => state === "OPEN" ? isDraft ? "draft" : "open" : state === "MERGED" ? "merged" : "closed";
23319
23532
  const toPullRequest = (json2) => {
23320
- const status = json2.state === "OPEN" ? json2.isDraft ? "draft" : "open" : json2.state === "MERGED" ? "merged" : "closed";
23533
+ const status = pullRequestStatus(json2.state, json2.isDraft);
23321
23534
  return {
23322
23535
  url: json2.url,
23323
23536
  number: json2.number,
@@ -23375,6 +23588,19 @@ const decodeOpenPullRequests = decodeUnknownEffect(
23375
23588
  )
23376
23589
  )
23377
23590
  );
23591
+ const decodePullRequestMatches = decodeUnknownEffect(
23592
+ fromJsonString(
23593
+ ArraySchema(
23594
+ Struct({
23595
+ number: Int,
23596
+ title: String$1,
23597
+ state: PullRequestFields.fields.state,
23598
+ isDraft: Boolean$1,
23599
+ author: Struct({ login: String$1 })
23600
+ })
23601
+ )
23602
+ )
23603
+ );
23378
23604
  class GitHub extends Service$1()("hinacode/GitHub") {
23379
23605
  }
23380
23606
  const SIGNED_OUT_EXIT_CODE = 4;
@@ -23449,6 +23675,29 @@ const make$P = gen(function* () {
23449
23675
  flatMap$1(decodeOpenPullRequests),
23450
23676
  map$3((list) => list.map(({ author, ...pullRequest }) => ({ ...pullRequest, author: author.login })))
23451
23677
  ),
23678
+ searchPullRequests: ({ owner, name }, query2) => gh(homedir(), [
23679
+ "pr",
23680
+ "list",
23681
+ "--repo",
23682
+ `${owner}/${name}`,
23683
+ "--state",
23684
+ "all",
23685
+ "--limit",
23686
+ "20",
23687
+ ...query2 === "" ? [] : [`--search=${query2}`],
23688
+ "--json",
23689
+ "number,title,state,isDraft,author"
23690
+ ]).pipe(
23691
+ flatMap$1(decodePullRequestMatches),
23692
+ map$3(
23693
+ (list) => list.map(({ number: number2, title, state, isDraft, author }) => ({
23694
+ number: number2,
23695
+ title,
23696
+ status: pullRequestStatus(state, isDraft),
23697
+ author: author.login
23698
+ }))
23699
+ )
23700
+ ),
23452
23701
  createPullRequest,
23453
23702
  clone: clone2,
23454
23703
  repository
@@ -23992,7 +24241,7 @@ const make$L = gen(function* () {
23992
24241
  })
23993
24242
  )
23994
24243
  );
23995
- const publishCurrent = (id) => get2(id).pipe(tap$1((worktree) => events.publish({ type: "worktree.updated", worktree })));
24244
+ const publishCurrent = (id) => get2(id).pipe(tap$2((worktree) => events.publish({ type: "worktree.updated", worktree })));
23996
24245
  const setStatus = (id, status) => sql`UPDATE worktree SET status = ${status} WHERE id = ${id}`.pipe(
23997
24246
  mapError(persistence("worktrees.setStatus")),
23998
24247
  andThen(publishCurrent(id))
@@ -24070,9 +24319,9 @@ Setup script exited with code ${exitCode}
24070
24319
  return running === void 0 ? void_$1 : interrupt(running);
24071
24320
  };
24072
24321
  const removals = /* @__PURE__ */ new Map();
24073
- const findOrphan = (rootPath, checkouts, branch) => gen(function* () {
24322
+ const findOrphan = (rootPath, checkouts2, branch) => gen(function* () {
24074
24323
  const checkout2 = (yield* registeredCheckouts(rootPath)).find(
24075
- ({ path, ref }) => ref === `refs/heads/${branch}` && dirname(path) === checkouts
24324
+ ({ path, ref }) => ref === `refs/heads/${branch}` && dirname(path) === checkouts2
24076
24325
  );
24077
24326
  if (!checkout2) return none();
24078
24327
  const recorded = yield* findByPath(checkout2.path).pipe(mapError(persistence("worktrees.create")));
@@ -24090,10 +24339,10 @@ Setup script exited with code ${exitCode}
24090
24339
  }
24091
24340
  const rootPath = yield* resolve2(project.rootPath);
24092
24341
  const { worktreeRoot } = yield* settings.get;
24093
- const checkouts = checkoutsDir(rootPath, worktreeRoot === null ? null : yield* resolve2(worktreeRoot));
24342
+ const checkouts2 = checkoutsDir(rootPath, worktreeRoot === null ? null : yield* resolve2(worktreeRoot));
24094
24343
  const id = randomUUID();
24095
- const orphan = yield* findOrphan(rootPath, checkouts, input.branch);
24096
- const path = getOrElse(orphan, () => checkoutPath(checkouts, input.branch, id));
24344
+ const orphan = yield* findOrphan(rootPath, checkouts2, input.branch);
24345
+ const path = getOrElse(orphan, () => checkoutPath(checkouts2, input.branch, id));
24097
24346
  if (isNone(orphan)) {
24098
24347
  const args2 = (yield* branchExists(rootPath, input.branch)) ? ["worktree", "add", path, input.branch] : input.startPoint === void 0 ? (
24099
24348
  // Forking from `origin/main` would otherwise make it the upstream, and a plain `git push` would fail.
@@ -24165,7 +24414,7 @@ Setup script exited with code ${exitCode}
24165
24414
  });
24166
24415
  const deleteFiles = (rootPath, worktree, deleteBranch) => gen(function* () {
24167
24416
  if ((yield* registeredCheckouts(rootPath)).some((registered) => registered.path === worktree.path)) {
24168
- yield* git2.run(rootPath, ["worktree", "remove", "--force", worktree.path]);
24417
+ yield* git2.run(rootPath, ["worktree", "remove", "--force", "--force", worktree.path]);
24169
24418
  }
24170
24419
  yield* git2.run(rootPath, ["worktree", "prune"]);
24171
24420
  if (deleteBranch !== "keep" && (yield* branchExists(rootPath, worktree.branch))) {
@@ -24197,6 +24446,23 @@ Setup script exited with code ${exitCode}
24197
24446
  return removed;
24198
24447
  });
24199
24448
  const remove2 = (id, deleteBranch, owner) => exclusive(removeWhileExclusive(id, deleteBranch, owner));
24449
+ const checkoutOf = (worktree) => gen(function* () {
24450
+ if (!(yield* fs.exists(worktree.path)))
24451
+ return some({ id: worktree.id, state: "missing" });
24452
+ const status = yield* git2.run(worktree.path, ["status", "--porcelain"]);
24453
+ return some({ id: worktree.id, state: status.trim() === "" ? "clean" : "dirty" });
24454
+ }).pipe(orElseSucceed(none));
24455
+ const checkouts = findAll$1(void 0).pipe(
24456
+ mapError(persistence("worktrees.checkouts")),
24457
+ flatMap$1(
24458
+ (all2) => forEach$1(
24459
+ all2.filter((worktree) => worktree.status !== "removed"),
24460
+ checkoutOf,
24461
+ { concurrency: 8 }
24462
+ )
24463
+ ),
24464
+ map$3((states) => states.flatMap(toArray))
24465
+ );
24200
24466
  const changes = (id) => gen(function* () {
24201
24467
  const worktree = yield* get2(id);
24202
24468
  if (worktree.status === "removed") return null;
@@ -24246,6 +24512,7 @@ Setup script exited with code ${exitCode}
24246
24512
  );
24247
24513
  return Worktrees.of({
24248
24514
  list: findAll$1(void 0).pipe(mapError(persistence("worktrees.list"))),
24515
+ checkouts,
24249
24516
  get: get2,
24250
24517
  create,
24251
24518
  createFromPullRequest,
@@ -26108,12 +26375,12 @@ const fromWebSocket = (acquire, options) => withFiber((fiber) => {
26108
26375
  }));
26109
26376
  }
26110
26377
  });
26111
- const writeAll = (chunks) => suspend$2(() => {
26378
+ const writeAll = (chunks2) => suspend$2(() => {
26112
26379
  const ws = currentWS;
26113
- if (ws === void 0) return latch.whenOpen(writeAll(chunks));
26380
+ if (ws === void 0) return latch.whenOpen(writeAll(chunks2));
26114
26381
  try {
26115
- for (let i = 0; i < chunks.length; i++) {
26116
- ws.send(chunks[i]);
26382
+ for (let i = 0; i < chunks2.length; i++) {
26383
+ ws.send(chunks2[i]);
26117
26384
  }
26118
26385
  return void_$1;
26119
26386
  } catch (cause) {
@@ -38789,7 +39056,7 @@ const make$b = gen(function* () {
38789
39056
  if (request2 === void 0) return void_$1;
38790
39057
  return providers[request2.provider]?.respondApproval(requestId, decision) ?? void_$1;
38791
39058
  });
38792
- const updateThread = (input) => threads.update(input).pipe(tap$1((thread) => push.publish({ type: "thread.updated", thread })));
39059
+ const updateThread = (input) => threads.update(input).pipe(tap$2((thread) => push.publish({ type: "thread.updated", thread })));
38793
39060
  const exclusive = (threadId) => (effect2) => {
38794
39061
  let lock = threadLocks.get(threadId);
38795
39062
  if (lock === void 0) threadLocks.set(threadId, lock = makeUnsafe$4(1));
@@ -38914,7 +39181,10 @@ const make$b = gen(function* () {
38914
39181
  const run2 = (prompt, attachments) => follow(
38915
39182
  unwrap(
38916
39183
  gen(function* () {
38917
- const [mcpServer, { experimental }] = yield* all([mcp.connectionFor(thread.id), settings.get]);
39184
+ const [mcpServer, { experimental, autoCompactTokens }] = yield* all([
39185
+ mcp.connectionFor(thread.id),
39186
+ settings.get
39187
+ ]);
38918
39188
  if (yield* isDone(stop)) {
38919
39189
  return succeed({ type: "turn_failed", message: "Turn interrupted" });
38920
39190
  }
@@ -38926,6 +39196,7 @@ const make$b = gen(function* () {
38926
39196
  model: thread.model,
38927
39197
  effort: thread.effort,
38928
39198
  fastMode: thread.fastMode,
39199
+ autoCompactTokens: autoCompactTokens[provider.id],
38929
39200
  userSkills: thread.userSkills,
38930
39201
  accessMode: thread.accessMode,
38931
39202
  resumeSessionId: thread.providerSessionId,
@@ -39876,10 +40147,11 @@ const CLOSE_AUTH_TIMEOUT = 4004;
39876
40147
  const CLOSE_MALFORMED_FRAME = 4005;
39877
40148
  const CLOSE_SLOW_CONSUMER = 4006;
39878
40149
  const isTailscale = (address) => address.startsWith("100.");
39879
- const reachableHosts = (bindHost) => {
40150
+ const isVirtualBridge = (name) => /^(docker|br-|veth|virbr|cni|flannel|podman|vboxnet|vmnet)/.test(name);
40151
+ const reachableHosts = (bindHost, interfaces = networkInterfaces(), host = hostname()) => {
39880
40152
  if (bindHost !== "0.0.0.0" && bindHost !== "::") return [bindHost];
39881
- const addresses = Object.values(networkInterfaces()).flatMap((nets) => nets ?? []).filter((net) => net.family === "IPv4" && !net.internal).map((net) => net.address);
39882
- return append$1([...addresses.filter(isTailscale), ...addresses.filter((a) => !isTailscale(a))], hostname());
40153
+ const addresses = Object.entries(interfaces).filter(([name]) => !isVirtualBridge(name)).flatMap(([, nets]) => nets ?? []).filter((net) => net.family === "IPv4" && !net.internal).map((net) => net.address);
40154
+ return append$1([...addresses.filter(isTailscale), ...addresses.filter((a) => !isTailscale(a))], host);
39883
40155
  };
39884
40156
  class RemoteAccess extends Service$1()("hinacode/RemoteAccess") {
39885
40157
  }
@@ -40113,6 +40385,21 @@ const learnFromPush = (owners, environmentId, event) => {
40113
40385
  }
40114
40386
  }
40115
40387
  };
40388
+ const unreachableMessage = ({ host, port }, code, reason) => {
40389
+ switch (code) {
40390
+ case "ECONNREFUSED":
40391
+ return `Nothing is listening on ${host}:${port}. Check that hinacode serve is running there and uses port ${port}.`;
40392
+ case "ETIMEDOUT":
40393
+ case "EHOSTUNREACH":
40394
+ case "ENETUNREACH":
40395
+ return `${host} did not answer. Check that this computer is on the same network or tailnet as it.`;
40396
+ case "ENOTFOUND":
40397
+ case "EAI_AGAIN":
40398
+ return `Could not find ${host}. Use its Tailscale or LAN address instead.`;
40399
+ default:
40400
+ return `Could not reach ${host}:${port}: ${reason}`;
40401
+ }
40402
+ };
40116
40403
  class InvalidPairingUrl extends TaggedError()("InvalidPairingUrl", {
40117
40404
  message: String$1
40118
40405
  }) {
@@ -40134,6 +40421,7 @@ const PING_INTERVAL = "10 seconds";
40134
40421
  const SILENCE_LIMIT_MS = 25e3;
40135
40422
  const OFFLINE_LIMIT_MS = 6e4;
40136
40423
  const STABLE_MS = 6e4;
40424
+ const PREFER_EARLIER_HOST_MS = 1e3;
40137
40425
  const reconnectDelay = (attempt) => Math.min(500 * 2 ** attempt, 6e4) * (0.7 + Math.random() * 0.6);
40138
40426
  const offline = (name) => ({
40139
40427
  error: { tag: "EnvironmentOffline", message: `${name} is offline` }
@@ -40180,6 +40468,7 @@ const probe = (target) => {
40180
40468
  const where = `${target.host}:${target.port}`;
40181
40469
  return callback$1((resume) => {
40182
40470
  let reason = "the connection closed";
40471
+ let errorCode;
40183
40472
  const socket = dial(target, target.token, {
40184
40473
  onFrame: (frame) => {
40185
40474
  if (frame.type !== "ready") return;
@@ -40187,7 +40476,8 @@ const probe = (target) => {
40187
40476
  socket.close();
40188
40477
  },
40189
40478
  onError: (error) => {
40190
- reason = error.message;
40479
+ reason = error.message || reason;
40480
+ errorCode = "code" in error && typeof error.code === "string" ? error.code : void 0;
40191
40481
  },
40192
40482
  onClose: (code) => {
40193
40483
  if (code === CLOSE_UNAUTHORIZED || code === CLOSE_TOKEN_ROTATED) {
@@ -40199,7 +40489,7 @@ const probe = (target) => {
40199
40489
  )
40200
40490
  );
40201
40491
  }
40202
- resume(fail$2(new EnvironmentUnreachable({ message: `Could not reach ${where}: ${reason}` })));
40492
+ resume(fail$2(new EnvironmentUnreachable({ message: unreachableMessage(target, errorCode, reason) })));
40203
40493
  }
40204
40494
  });
40205
40495
  return sync(() => socket.terminate());
@@ -40208,12 +40498,45 @@ const probe = (target) => {
40208
40498
  duration: READY_TIMEOUT_MS,
40209
40499
  orElse: () => fail$2(
40210
40500
  new EnvironmentUnreachable({
40211
- message: `Could not reach ${where}: no answer within ${READY_TIMEOUT_MS / 1e3} seconds`
40501
+ message: unreachableMessage(target, "ETIMEDOUT", `no answer within ${READY_TIMEOUT_MS / 1e3} seconds`)
40212
40502
  })
40213
40503
  )
40214
40504
  })
40215
40505
  );
40216
40506
  };
40507
+ const probeHosts = (pairing) => gen(function* () {
40508
+ const answers = [];
40509
+ const graceOver = yield* make$1u();
40510
+ let graceStarted = false;
40511
+ const startGrace = suspend$2(() => {
40512
+ if (graceStarted) return void_$1;
40513
+ graceStarted = true;
40514
+ return forkScoped(
40515
+ sleep(PREFER_EARLIER_HOST_MS).pipe(andThen(succeed$5(graceOver, void 0)))
40516
+ );
40517
+ });
40518
+ const probes = yield* forEach$1(
40519
+ pairing.hosts,
40520
+ (host, index) => forkScoped(
40521
+ probe({ host, port: pairing.port, token: pairing.token }).pipe(
40522
+ tap$2((ready) => {
40523
+ answers[index] = ready;
40524
+ return startGrace;
40525
+ }),
40526
+ result$1
40527
+ )
40528
+ )
40529
+ );
40530
+ const failures = [];
40531
+ for (const fiber of probes) {
40532
+ const outcome = yield* raceFirst(join$1(fiber), _await(graceOver).pipe(as(null)));
40533
+ if (outcome === null || outcome._tag === "Success") break;
40534
+ failures.push(outcome.failure);
40535
+ }
40536
+ const won = answers.findIndex((ready) => ready !== void 0);
40537
+ if (won !== -1) return { host: pairing.hosts[won], ready: answers[won] };
40538
+ return yield* fail$2(failures.find((error) => error._tag === "EnvironmentUnauthorized") ?? failures[0]);
40539
+ }).pipe(scoped);
40217
40540
  const send$1 = (live, call2) => {
40218
40541
  const key2 = live.dedupesCalls ? call2.key : void 0;
40219
40542
  call2.sent = true;
@@ -40297,7 +40620,7 @@ const make$8 = gen(function* () {
40297
40620
  const { id, name } = cloud.environment;
40298
40621
  const closed = yield* make$1u();
40299
40622
  let connectedAt = null;
40300
- let otherVersion = false;
40623
+ let otherProtocol = null;
40301
40624
  let heardAt = now2();
40302
40625
  const heard = () => {
40303
40626
  heardAt = now2();
@@ -40311,10 +40634,11 @@ const make$8 = gen(function* () {
40311
40634
  switch (frame.type) {
40312
40635
  case "ready": {
40313
40636
  if (frame.version !== REMOTE_PROTOCOL_VERSION) {
40314
- otherVersion = true;
40637
+ otherProtocol = frame.version;
40315
40638
  return socket.close();
40316
40639
  }
40317
40640
  connectedAt = now2();
40641
+ cloud.protocol = null;
40318
40642
  const live = { socket, dedupesCalls: frame.features?.includes("call-keys") ?? false };
40319
40643
  cloud.live = live;
40320
40644
  for (const call2 of cloud.outbox.values()) {
@@ -40376,7 +40700,7 @@ const make$8 = gen(function* () {
40376
40700
  const code = yield* _await(closed);
40377
40701
  return {
40378
40702
  code,
40379
- incompatible: otherVersion,
40703
+ otherProtocol,
40380
40704
  connectedMs: connectedAt === null ? 0 : now2() - connectedAt
40381
40705
  };
40382
40706
  }).pipe(scoped);
@@ -40391,18 +40715,26 @@ const make$8 = gen(function* () {
40391
40715
  let attempt = 0;
40392
40716
  for (; ; ) {
40393
40717
  const end2 = yield* session(cloud, token);
40394
- if (end2.incompatible) {
40395
- failAll(cloud, incompatible(name));
40396
- return yield* setStatus(cloud, "incompatible");
40397
- }
40398
40718
  if (end2.code === CLOSE_UNAUTHORIZED || end2.code === CLOSE_TOKEN_ROTATED) {
40399
40719
  failAll(cloud, unauthorized(name));
40400
40720
  return yield* setStatus(cloud, "unauthorized");
40401
40721
  }
40402
- yield* setStatus(cloud, "offline");
40722
+ if (end2.otherProtocol === null) {
40723
+ yield* setStatus(cloud, "offline");
40724
+ } else {
40725
+ cloud.protocol = end2.otherProtocol;
40726
+ failAll(cloud, incompatible(name));
40727
+ yield* setStatus(cloud, "incompatible");
40728
+ }
40403
40729
  if (end2.connectedMs >= STABLE_MS) attempt = 0;
40404
- yield* sleep(reconnectDelay(attempt));
40405
- attempt++;
40730
+ const wake = yield* make$1u();
40731
+ cloud.wake = wake;
40732
+ const woken = yield* race(
40733
+ sleep(reconnectDelay(attempt)).pipe(as(false)),
40734
+ _await(wake).pipe(as(true))
40735
+ );
40736
+ cloud.wake = null;
40737
+ attempt = woken ? 0 : attempt + 1;
40406
40738
  }
40407
40739
  }).pipe(catchCause$1((cause) => logWarning("environment connection stopped", cause)));
40408
40740
  const connections = yield* make$15();
@@ -40421,7 +40753,9 @@ const make$8 = gen(function* () {
40421
40753
  environment,
40422
40754
  status: "connecting",
40423
40755
  lastSeenAt: null,
40756
+ protocol: null,
40424
40757
  live: null,
40758
+ wake: null,
40425
40759
  outbox: /* @__PURE__ */ new Map(),
40426
40760
  remembered: /* @__PURE__ */ new Map()
40427
40761
  };
@@ -40434,7 +40768,8 @@ const make$8 = gen(function* () {
40434
40768
  return {
40435
40769
  clouds: rows.map((row) => {
40436
40770
  const cloud = clouds.get(row.id);
40437
- return { ...row, status: cloud?.status ?? "offline", lastSeenAt: cloud?.lastSeenAt ?? null };
40771
+ const entry = { ...row, status: cloud?.status ?? "offline", lastSeenAt: cloud?.lastSeenAt ?? null };
40772
+ return cloud?.status === "incompatible" && cloud.protocol !== null ? { ...entry, protocol: cloud.protocol } : entry;
40438
40773
  })
40439
40774
  };
40440
40775
  });
@@ -40445,8 +40780,8 @@ const make$8 = gen(function* () {
40445
40780
  message: "Paste the hinacode://connect URL that hinacode serve printed."
40446
40781
  });
40447
40782
  }
40448
- const target = { host: pairing.hosts[0], port: pairing.port, token: pairing.token };
40449
- const ready = yield* probe(target);
40783
+ const { host, ready } = yield* probeHosts(pairing);
40784
+ const target = { host, port: pairing.port, token: pairing.token };
40450
40785
  if (ready.environment?.id === self.id) {
40451
40786
  return yield* new InvalidPairingUrl({ message: "That pairing URL is for this desktop." });
40452
40787
  }
@@ -40478,6 +40813,14 @@ const make$8 = gen(function* () {
40478
40813
  clouds.delete(id);
40479
40814
  owners.forget(id);
40480
40815
  });
40816
+ const reconnect = (id) => suspend$2(() => {
40817
+ const cloud = clouds.get(id);
40818
+ const wake = cloud?.wake;
40819
+ if (cloud === void 0 || wake == null) return void_$1;
40820
+ cloud.wake = null;
40821
+ return setStatus(cloud, "connecting").pipe(andThen(succeed$5(wake, void 0)));
40822
+ });
40823
+ const reconnectAll = suspend$2(() => forEach$1([...clouds.keys()], reconnect, { discard: true }));
40481
40824
  const forward = (environmentId, { method, payload }) => suspend$2(() => {
40482
40825
  const cloud = clouds.get(environmentId);
40483
40826
  if (cloud === void 0) return succeed$3(unknownEnvironment(environmentId));
@@ -40528,7 +40871,7 @@ const make$8 = gen(function* () {
40528
40871
  { concurrency: "unbounded" }
40529
40872
  ).pipe(map$3((answers) => answers.flat()));
40530
40873
  yield* forEach$1(yield* findAll$1(void 0).pipe(mapError(persistence("environments.load"))), start);
40531
- return Environments.of({ list, add: add2, remove: remove2, forward, gather, owner: owners.owner });
40874
+ return Environments.of({ list, add: add2, remove: remove2, reconnect, reconnectAll, forward, gather, owner: owners.owner });
40532
40875
  });
40533
40876
  const layer$8 = effect(Environments, make$8);
40534
40877
  const previewMimes = {
@@ -40856,18 +41199,18 @@ const get = async (url, deadline) => {
40856
41199
  return null;
40857
41200
  };
40858
41201
  const readUpTo = async (response, limit) => {
40859
- const chunks = [];
41202
+ const chunks2 = [];
40860
41203
  let size2 = 0;
40861
41204
  const reader = response.body?.getReader();
40862
41205
  if (!reader) return { bytes: Buffer.alloc(0), truncated: false };
40863
41206
  while (size2 <= limit) {
40864
41207
  const { done: done2, value: value2 } = await reader.read();
40865
41208
  if (done2) break;
40866
- chunks.push(value2);
41209
+ chunks2.push(value2);
40867
41210
  size2 += value2.byteLength;
40868
41211
  }
40869
41212
  await reader.cancel();
40870
- return { bytes: Buffer.concat(chunks).subarray(0, limit), truncated: size2 > limit };
41213
+ return { bytes: Buffer.concat(chunks2).subarray(0, limit), truncated: size2 > limit };
40871
41214
  };
40872
41215
  const attribute = (tag2, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag2)?.slice(1).find((value2) => value2 !== void 0);
40873
41216
  const ICON_RELS = /* @__PURE__ */ new Set(["icon", "apple-touch-icon"]);
@@ -41407,7 +41750,7 @@ const make$5 = gen(function* () {
41407
41750
  launch(server).pipe(
41408
41751
  catchCause$1((cause) => {
41409
41752
  listenError = describeCause$1(cause);
41410
- return logWarning("automation webhook listener failed", cause);
41753
+ return logWarning("automation webhook listener failed", listenError);
41411
41754
  })
41412
41755
  )
41413
41756
  );
@@ -42043,7 +42386,7 @@ const startForward = (openTunnel) => callback$1((resume) => {
42043
42386
  track(local);
42044
42387
  runFork(
42045
42388
  openTunnel().pipe(
42046
- tap$1(
42389
+ tap$2(
42047
42390
  ({ socket, head }) => sync(() => {
42048
42391
  track(socket);
42049
42392
  if (local.destroyed) {
@@ -42430,7 +42773,7 @@ const makeRelayCore = (deps) => gen(function* () {
42430
42773
  duration: "180 seconds",
42431
42774
  orElse: () => as(deps.cancelCeremony, notAllowed("No answer came from this Mac in time"))
42432
42775
  }),
42433
- tap$1((outcome) => logInfo("tiny vm passkey: ceremony finished", validated.rpId, outcome.type)),
42776
+ tap$2((outcome) => logInfo("tiny vm passkey: ceremony finished", validated.rpId, outcome.type)),
42434
42777
  flatMap$1((outcome) => finishCeremony(session, request2, outcome))
42435
42778
  );
42436
42779
  pending.fiber = yield* forkIn(ceremony, scope$12);
@@ -42661,6 +43004,7 @@ const handlers = {
42661
43004
  "worktrees.list": () => Worktrees.use((worktrees) => worktrees.list),
42662
43005
  "worktrees.create": (input) => Worktrees.use((worktrees) => worktrees.create(input)),
42663
43006
  "worktrees.remove": ({ id, deleteBranch }) => Worktrees.use((worktrees) => worktrees.remove(id, deleteBranch)),
43007
+ "worktrees.checkouts": () => Worktrees.use((worktrees) => worktrees.checkouts),
42664
43008
  "worktrees.setupLog": ({ id }) => Worktrees.use((worktrees) => map$3(worktrees.get(id), (w) => w.setupLog)),
42665
43009
  "worktrees.stopSetup": ({ id }) => Worktrees.use((worktrees) => worktrees.stopSetup(id)),
42666
43010
  "worktrees.pullRequest": ({ id }) => Worktrees.use((worktrees) => worktrees.pullRequest(id)),
@@ -42680,6 +43024,17 @@ const handlers = {
42680
43024
  GitHubSignedOutError: () => succeed$3([])
42681
43025
  })
42682
43026
  ),
43027
+ "projects.searchPullRequests": ({ id, query: query2 }) => gen(function* () {
43028
+ const { rootPath } = yield* Projects.use((projects) => projects.get(id));
43029
+ const repository = yield* GitHub.use((github) => github.repository(rootPath));
43030
+ if (repository === null) return [];
43031
+ return yield* GitHub.use((github) => github.searchPullRequests(repository, query2));
43032
+ }).pipe(
43033
+ catchTags({
43034
+ GitHubCliMissingError: () => succeed$3([]),
43035
+ GitHubSignedOutError: () => succeed$3([])
43036
+ })
43037
+ ),
42683
43038
  "projects.icon": ({ id }) => Projects.use((projects) => projects.icon(id)),
42684
43039
  "git.log": ({ root, limit = 200 }) => knownRoot(root).pipe(andThen(Git.use((git2) => git2.log(root, limit)))),
42685
43040
  "git.show": ({ root, hash: hash2 }) => knownRoot(root).pipe(andThen(Git.use((git2) => git2.show(root, hash2)))),
@@ -42693,6 +43048,7 @@ const handlers = {
42693
43048
  "environments.list": () => Environments.use((environments2) => environments2.list),
42694
43049
  "environments.add": (input) => Environments.use((environments2) => environments2.add(input)),
42695
43050
  "environments.remove": ({ id }) => Environments.use((environments2) => environments2.remove(id)),
43051
+ "environments.reconnect": ({ id }) => Environments.use((environments2) => environments2.reconnect(id)),
42696
43052
  "notifications.permission": (_, desktop) => desktop?.notificationPermission ?? succeed$3("unknown"),
42697
43053
  "notifications.askPermission": ({ title, body: body2 }, desktop) => desktop?.askNotificationPermission(title, body2) ?? succeed$3("noAnswer"),
42698
43054
  "models.list": ({ provider }) => AgentRunner.use((runner) => runner.listModels(provider)),
@@ -42989,9 +43345,10 @@ const make$2 = gen(function* () {
42989
43345
  yield* run$2(
42990
43346
  listener,
42991
43347
  listen(remote).pipe(
42992
- catchCause$1(
42993
- (cause) => access2.report({ listenError: describeCause(cause) }).pipe(andThen(logWarning("remote listener failed", cause)))
42994
- )
43348
+ catchCause$1((cause) => {
43349
+ const listenError = describeCause(cause);
43350
+ return access2.report({ listenError }).pipe(andThen(logWarning("remote listener failed", listenError)));
43351
+ })
42995
43352
  )
42996
43353
  );
42997
43354
  });
@@ -43013,6 +43370,49 @@ const make$2 = gen(function* () {
43013
43370
  );
43014
43371
  });
43015
43372
  const layer$2 = effectDiscard(make$2);
43373
+ const USAGE = `Usage: hinacode <command> [options]
43374
+
43375
+ Commands:
43376
+ serve Run a HinaCode cloud: agents, worktrees and threads on this machine, driven from the desktop or phone app.
43377
+ pair Print the pairing URLs and QR code of the cloud again, without restarting it.
43378
+
43379
+ serve options:
43380
+ --port <n> Port to listen on, or HINACODE_SERVE_PORT.
43381
+ --host <host> Address to bind, or HINACODE_SERVE_HOST. 0.0.0.0 for every interface.
43382
+ --rotate-token Replace the token, which unpairs every client, or HINACODE_SERVE_ROTATE_TOKEN=1.
43383
+
43384
+ -h, --help Print this help.
43385
+ --version Print the version.
43386
+
43387
+ A cloud installed with npm install -g installs new releases on its own once nothing is running.
43388
+ Set HINACODE_SERVE_AUTO_UPDATE=0 to update it by hand instead.
43389
+
43390
+ Data lives in HINACODE_USER_DATA, default ~/.hinacode-cloud.`;
43391
+ class UsageError extends Error {
43392
+ }
43393
+ const OPTIONS = {
43394
+ serve: { values: ["--port", "--host"], switches: ["--rotate-token"] },
43395
+ pair: { values: [], switches: [] }
43396
+ };
43397
+ const parseCommand = (argv) => {
43398
+ if (argv.includes("--help") || argv.includes("-h")) return "help";
43399
+ const [command, ...rest] = argv;
43400
+ if (command === "--version") return "version";
43401
+ if (command !== "serve" && command !== "pair") {
43402
+ throw new UsageError(command === void 0 ? "missing command" : `unknown command ${command}`);
43403
+ }
43404
+ const { values: values2, switches } = OPTIONS[command];
43405
+ for (let index = 0; index < rest.length; index++) {
43406
+ const arg = rest[index];
43407
+ const name = arg.split("=")[0];
43408
+ if (values2.includes(name)) {
43409
+ if (name === arg) index++;
43410
+ } else if (!switches.includes(arg)) {
43411
+ throw new UsageError(arg.startsWith("-") ? `unknown option ${name}` : `unexpected argument ${arg}`);
43412
+ }
43413
+ }
43414
+ return command;
43415
+ };
43016
43416
  const envFlag = (env, name) => {
43017
43417
  const value2 = env[name];
43018
43418
  if (value2 === void 0 || value2 === "0" || value2 === "false") return false;
@@ -43026,6 +43426,15 @@ const portOf = (raw2, source) => {
43026
43426
  }
43027
43427
  return port;
43028
43428
  };
43429
+ const restartCommand = (process2) => {
43430
+ const { HINACODE_SERVE_ROTATE_TOKEN: _rotated, ...env } = process2.env;
43431
+ return {
43432
+ file: process2.execPath,
43433
+ args: [process2.execPath, ...process2.execArgv, ...process2.argv.slice(1).filter((arg) => arg !== "--rotate-token")],
43434
+ env
43435
+ };
43436
+ };
43437
+ const autoUpdate = (env) => env["HINACODE_SERVE_AUTO_UPDATE"] === void 0 || envFlag(env, "HINACODE_SERVE_AUTO_UPDATE");
43029
43438
  const flagValue = (argv, name) => {
43030
43439
  const inline = argv.find((arg) => arg.startsWith(`--${name}=`));
43031
43440
  if (inline !== void 0) return inline.slice(name.length + 3);
@@ -43276,13 +43685,13 @@ const layer = effect(PullRequestWatcher, make2);
43276
43685
  const simulatedClaude = (env) => {
43277
43686
  const mode = env["HINACODE_MOCK_CLAUDE"];
43278
43687
  if (mode === void 0) return void 0;
43279
- if (mode !== "usage-limit" && mode !== "org-spend-limit" && mode !== "todos" && mode !== "markdown")
43280
- throw new Error("HINACODE_MOCK_CLAUDE must be usage-limit, org-spend-limit, todos or markdown");
43688
+ const scenario = mockScenarios.find((candidate) => candidate === mode);
43689
+ if (scenario === void 0) throw new Error(`HINACODE_MOCK_CLAUDE must be one of ${mockScenarios.join(", ")}`);
43281
43690
  if (!env["HINACODE_USER_DATA"]) throw new Error("Claude simulation requires HINACODE_USER_DATA");
43282
43691
  const resetMs = Number(env["HINACODE_MOCK_RESET_MS"] ?? 6e4);
43283
43692
  if (!Number.isFinite(resetMs) || Math.abs(resetMs) > 36e5)
43284
43693
  throw new Error("HINACODE_MOCK_RESET_MS must be between -3600000 and 3600000");
43285
- return usageLimitLayer(mode, resetMs);
43694
+ return usageLimitLayer(scenario, resetMs);
43286
43695
  };
43287
43696
  const makeAppLayer = ({ userData, sbxConfigPath, keyring, updates, toWindows, serve: serve2 }) => {
43288
43697
  const mockClaude = simulatedClaude(process.env);
@@ -43354,65 +43763,91 @@ const hydratePath = async (env) => {
43354
43763
  env.PATH = [...new Set(entries)].join(":");
43355
43764
  };
43356
43765
  export {
43357
- githubAssetId as $,
43358
- Environments as A,
43359
- flatMap$1 as B,
43360
- catch_$2 as C,
43361
- all as D,
43362
- EVENT_CHANNEL as E,
43363
- map$3 as F,
43364
- decodeUnknownEffect as G,
43365
- RpcMethods as H,
43366
- inlineSource as I,
43367
- Events as J,
43368
- runFork as K,
43369
- logWarning as L,
43370
- repeat as M,
43371
- spaced as N,
43372
- forkScoped as O,
43373
- suspend$2 as P,
43374
- effect as Q,
43766
+ seconds as $,
43767
+ make$14 as A,
43768
+ makeAppLayer as B,
43769
+ autoUpdate as C,
43770
+ layer$b as D,
43771
+ Events as E,
43772
+ provideMerge as F,
43773
+ mergeAll$1 as G,
43774
+ layer$p as H,
43775
+ layer$w as I,
43776
+ provide$3 as J,
43777
+ noKeyring as K,
43778
+ layer$z as L,
43779
+ succeed$4 as M,
43780
+ MinimumLogLevel as N,
43781
+ Settings as O,
43782
+ pairingUrl as P,
43783
+ isPortInUse as Q,
43375
43784
  RemoteAccess as R,
43376
- String$1 as S,
43377
- TaggedError as T,
43785
+ Struct as S,
43786
+ Threads as T,
43378
43787
  Updates as U,
43379
- ignore$1 as V,
43380
- ATTACHMENT_PROTOCOL as W,
43381
- GITHUB_ASSET_PROTOCOL as X,
43382
- PROJECT_FILE_PROTOCOL as Y,
43383
- Keyring as Z,
43384
- isInside as _,
43385
- makeAppLayer as a,
43386
- GitHub as a0,
43387
- externalUrl as a1,
43388
- projectFileRequest as a2,
43389
- Files as a3,
43390
- BROWSER_PARTITION as a4,
43391
- lockDownWebview as a5,
43392
- isAllowedNavigation as a6,
43393
- succeed$4 as b,
43394
- sync as c,
43395
- catchDefect as d,
43396
- succeed$3 as e,
43397
- callback$1 as f,
43398
- seconds as g,
43399
- hydratePath as h,
43400
- promise as i,
43401
- tryPromise as j,
43402
- Struct as k,
43403
- RpcCall as l,
43404
- make$14 as m,
43405
- noKeyring as n,
43406
- optional$6 as o,
43407
- pairingUrl as p,
43408
- decodeUnknownOption as q,
43409
- RPC_CHANNEL as r,
43410
- serveConfig as s,
43411
- timeoutOrElse as t,
43788
+ restartCommand as V,
43789
+ Worktrees as W,
43790
+ catchDefect as X,
43791
+ succeed$3 as Y,
43792
+ callback$1 as Z,
43793
+ timeoutOrElse as _,
43794
+ spaced as a,
43795
+ TaggedError as a0,
43796
+ promise as a1,
43797
+ optional$6 as a2,
43798
+ RpcCall as a3,
43799
+ decodeUnknownOption as a4,
43800
+ EVENT_CHANNEL as a5,
43801
+ RPC_CHANNEL as a6,
43802
+ isTrustedSender as a7,
43803
+ getOrUndefined$1 as a8,
43804
+ dispatch as a9,
43805
+ Environments as aa,
43806
+ catch_$2 as ab,
43807
+ all as ac,
43808
+ map$3 as ad,
43809
+ decodeUnknownEffect as ae,
43810
+ RpcMethods as af,
43811
+ inlineSource as ag,
43812
+ runFork as ah,
43813
+ logWarning as ai,
43814
+ ignore$1 as aj,
43815
+ ATTACHMENT_PROTOCOL as ak,
43816
+ GITHUB_ASSET_PROTOCOL as al,
43817
+ PROJECT_FILE_PROTOCOL as am,
43818
+ Keyring as an,
43819
+ isInside as ao,
43820
+ githubAssetId as ap,
43821
+ GitHub as aq,
43822
+ externalUrl as ar,
43823
+ projectFileRequest as as,
43824
+ Files as at,
43825
+ BROWSER_PARTITION as au,
43826
+ lockDownWebview as av,
43827
+ isAllowedNavigation as aw,
43828
+ Terminals as b,
43829
+ forEach$1 as c,
43830
+ decodeUnknownSync as d,
43831
+ effect as e,
43832
+ forkScoped as f,
43833
+ gen as g,
43834
+ sync as h,
43835
+ isThreadBusy as i,
43836
+ String$1 as j,
43837
+ andThen as k,
43838
+ matchEffect as l,
43839
+ make$1c as m,
43840
+ forkDetach as n,
43841
+ orElseSucceed as o,
43842
+ flatMap$1 as p,
43843
+ UsageError as q,
43844
+ repeat as r,
43845
+ suspend$2 as s,
43846
+ tryPromise as t,
43412
43847
  unsupported as u,
43413
43848
  void_$1 as v,
43414
- isTrustedSender as w,
43415
- gen as x,
43416
- getOrUndefined$1 as y,
43417
- dispatch as z
43849
+ USAGE as w,
43850
+ parseCommand as x,
43851
+ serveConfig as y,
43852
+ hydratePath as z
43418
43853
  };